Index: /tags/Mars-V0.9/.rootrc
===================================================================
--- /tags/Mars-V0.9/.rootrc	(revision 9772)
+++ /tags/Mars-V0.9/.rootrc	(revision 9772)
@@ -0,0 +1,45 @@
+#############################################################################
+#                                                                           #
+# This is the path where root seraches for macros                           #
+# to execute (eg. .x merpp.C)                                               #
+#                                                                           #
+#############################################################################
+
+Unix.*.Root.MacroPath:       .:./macros
+
+#############################################################################
+#                                                                           #
+# This is the path where the dynamic loader (eg. gSystem->Load("mars.so")   #
+# is searching for the shared objects                                       #
+#                                                                           #
+#############################################################################
+
+Unix.*.Root.DynamicPath:     .:./lib
+
+#############################################################################
+#                                                                           #
+# This is the name of the logon macro (executed at root startup) and the    #
+# logoff macro (executed when quiting root)                                 #
+#                                                                           #
+#############################################################################
+
+Rint.Logon:                  rootlogon.C
+Rint.Logoff:                 rootlogoff.C
+
+#############################################################################
+#                                                                           #
+# This is used if you want to use the root documentation facility to        #
+# create the documentation of the code out of the code                      #
+#                                                                           #
+#############################################################################
+
+Root.Html.DescriptionStyle:  Doc++
+
+Root.Html.Author:            !   Author(s):
+Root.Html.Copyright:         !   Copyright
+Root.Html.Modified:          !   Modified:
+Root.Html.Description        // ----
+
+Root.Html.Root:              http://root.cern.ch/root/htmldoc/
+Root.Html.HomePage:          http://magic.astro.uni-wuerzburg.de/mars/
+Root.Html.SearchEngine:      http://magic.astro.uni-wuerzburg.de/mars/search.html
Index: /tags/Mars-V0.9/Changelog
===================================================================
--- /tags/Mars-V0.9/Changelog	(revision 9772)
+++ /tags/Mars-V0.9/Changelog	(revision 9772)
@@ -0,0 +1,3072 @@
+
+ 
+Please  do  not write behind the end of line tag so that it is  possible
+to   send  a   Changelog   file  to  a  line  printer  directly.  Thanks.
+
+For your entries please follow EXACTLY this style:
+
+_yyyy/mm/dd_[Your Name]
+_
+___*_filename:
+_____-_description
+_
+___*_filename2, filename3:
+_____-_description
+_
+_
+_
+
+While an underscore is a placeholder for a white-space or an empty line.
+
+
+                                                 -*-*- END OF LINE -*-*-
+ 2005/03/23 Thomas Bretz
+
+   * Release 0.9
+
+
+
+ 2005/03/23 Thomas Bretz
+
+   * ganymed.cc:
+     - implemented wobble-mode option
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - fixed a problem in wobble mode (number of on- minus number
+       of off-entries where calculated as 0)
+     - added some additional resource options for scaling
+     - added some missing const-qualifiers
+
+   * mhflux/MHAlpha.cc:
+     - some cosmetic change to output
+
+   * mjobs/MDataSet.[h,cc]:
+     - added the possibility to add a source name for wobble mode
+       (preliminary)
+     - added reading from *.edb catalog
+
+   * mjobs/MJCalibTest.cc, mjobs/MJCalibrateSignal.cc,
+     mjobs/MJCalibration.cc, mjobs/MJPedestal.cc:
+     - replaced iter.Print("all") by iter.Print()
+
+   * mjobs/MJCut.[h,cc]:
+     - implemented wobble mode
+     - implemented getting source position
+
+   * mjobs/MJStar.cc:
+     - switched off calculation of MConcentration
+     - implemented the new debug option for files (was still missing
+       in MJStar)
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - always writa the anti-source position into the parameter list, too
+     - implemented wobble mode (exchange source and anti-source position)
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - added MJOptimize
+
+   * mfilter/MFSupercuts.[h,cc]:
+     - added
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - added MFSupercuts
+     - removed MFAlpha
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MEnergyEst
+     - removed MEnergyEstParam
+     - removed MEnergyEstParamDanielMkn421
+     - removed MSupercuts
+     - removed MSupercutsCalc
+     - removed MFindSupercuts
+     - removed MMinuitInterface
+     - removed MFiltercutsCalc
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MHEnergyTime
+     - removed MHEnergyTheta
+     - removed MHAlphaEnergyTime
+     - removed MHAlphaEnergyTheta
+     - removed MHThetabarTime
+     - removed MHThetabarTheta
+     - removed MHGamma
+     - removed MHSigmaPixel
+     - removed MHSigmabarTheta
+     - removed MHOnSubtraction
+     - removed MHFindSignificance
+     - removed MHCT1Supercuts
+
+   * mhflux/Makefile, mhflux/HistLinkDef.h:
+     - added MHEnergyEst
+
+
+
+ 2005/03/22 Thomas Bretz
+
+   * mjobs/MJCalibTest.cc, mjobs/MJCalibrateSignal.cc,
+     mjobs/MJCalibration.cc, mjobs/MJPedestal.cc:
+     - added a possibility to print the files which are 
+       searched/found if the files doesn't match the sequence
+
+   * mjobs/MJPedestal.cc:
+     - undocumented(!) change, changed fgExtractWinLeft
+       from 3.5 to 2.5
+
+   * mimage/MHillas.cc:
+     - fixed a bug which took unused pixels into account
+       introduced errornously with the last change to MSignalCam
+
+
+
+ 2005/03/21 Thomas Bretz
+
+   * mfbase/MFDataChain.cc:
+     - fixed a bug in GetDataMember if fData is not valid
+
+   * mhbase/MH3.cc:
+     - moved drawing histograms back to Draw. This fixes a
+       problem with root 4.02/00. Reading/Writing should be
+       no problem if the names of the profiles are well known.
+     - with this fix 'same' is currently NOT supported
+
+   * mimage/ImageLinkDef.h, mimage/Makefile:
+     - added MNewImagepar2
+     - added MHCewImagePar2
+   
+   * mimage/MNewImagePar2.[h,cc], mimage/MHNewImagePar2.[h,cc]:
+     - added new classes calculating and displaying the length
+     of the border line of a shower
+
+   * mimage/MHImagePar.cc:
+     - fixed a problem with root 4.02/00 when setting the margin
+       in Divide to 0 by setting it to 1e-10
+
+   * mimage/MHNewImagePar.[h,cc]:
+     - fixed to display Areas in deg^2
+
+   * mimage/MHillas.cc, mimage/MHillasExt.cc, mimage/MHillasSrc.cc,
+     mimage/MImagePar.cc, mimage/MNewImagePar.cc
+     - a small fix to Print()
+
+   * mimage/MHillasCalc.[h,cc]:
+     - added MNewImagePar2 to supported image parameters
+
+   * mjobs/MJStar.cc:
+     - replaced MCerPhotEvt by MSignalCam
+
+   * msignal/cosmics_weights46.dat, msignal/calibration_weightsUV46.dat,
+     mjobs/hilocalib_df46.root:
+     - added new intercalibration file for digital filter 4sl higain
+       and 6sl logian
+
+  * mbase/MLogHtml.cc:
+     - fixed a bug in Underline which cause a crash if fOut==NULL
+     - output a message if file cannot be opened
+
+   * mhcalib/MHCalibrationPulseTimeCam.cc:
+     - for some output there was a replacement of pix.GetPixId()
+       by hist.GetName() <undocumented>
+
+   * mimage/MHillas.[h,cc]:
+     - added new member function GetBorderLine returning the border
+       line correspondig to an ellipse with axis lnegth and width
+     - added new member function GetArea returning the area
+       correspondig to an ellipse with axis lnegth and width
+
+
+
+ 2005/03/19 Markus Gaug
+ 
+   * mjobs/hilocalib_df46.root
+     - added new intercalibration file for digital filter 4sl higain 
+       and 6 slices logain
+
+   * mjobs/MJCalibration.cc
+      - exchanged intercalibration file from hilocalib_df_4.root to  
+        hilocalib_df46.root
+      - do not apply hi-gain lo-gain intercalibration for MC files.
+
+   * mjobs/MJPedestal.cc
+     - exchanged two (Int_t)'s by TMath::Nint().
+     - undocumented(!) change to the calculation of the extraction
+       range (PulsePosCheck)
+
+   * callisto.rc
+     - exchanged default weights file for Digital filter from
+       cosmics_weights4.dat to cosmics_weights46.dat and from 
+       calibration_weights_UV4.dat to calibration_weights_UV46.dat!
+       This change is absolutely necessary, given the new results from 
+       Nuria about the signal resolution in the low gain which gets worse
+       than the intrinsic Poisson jitter above 350 phes. Also the time
+       resolution is too bad. This was not known before we had the  
+       correct low-gain MC pulse.
+
+
+
+ 2005/03/18 Thomas Bretz
+
+   * Makefile:
+     - removed mone from list of compiled programs
+
+   * mars.cc:
+     - replaced the MARS display by the Camera Display directly
+
+   * manalysis/MCameraData.[h,cc], mcalib/MCalibrateData.[h,cc],
+     mbadpixels/MBadPixelsTreat.[h,cc], mcalib/MCalibrateRelTimes.[h,cc],
+     mimage/MCameraSmooth.[h,cc], mimage/MConcentration.[h,cc],
+     mimage/MHillas.[h,cc], mimage/MHillasExt.[h,cc], 
+     mimage/MImgCleanStd.[h,cc], mimage/MNewImagePar.[h,cc],
+     mimage/MImagePar.[h,cc], MNewImagePar.[h,cc],
+     mjobs/MJCalibTest.cc, mhcalib/MHCalibrationTestCam.[h,cc],
+     mpedestal/MPedPhotCalc.[h,cc], mjobs/MJCalibrateSignal.cc:
+     - removed dependancy on MArrivalTime, information now
+       found in MSignalCam
+     - replaced MCerPhotEvt by MSignalCam
+     - it was renamed because it will be completely incompatible
+       anyhow
+
+   * mjobs/MJCalibrateSignal.cc:
+     - use new MSignalCam type to display pulse position of cosmics
+
+   * mcalib/MCalibrateData.cc:
+     - calculate number of saturated pixels
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - removed possibility for zero-supression. Now the index
+       is identical with the position in the array
+     - renamed and moved to msignal/MSignalCam.[h,cc]
+
+   * manalysis/MCerPhotPix.cc:
+     - removed obsolete values
+     - added arrival time
+     - renamed and moved to msignal/MSignalPix.[h,cc]
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - some cosmetic changes and small fixed from the Munich cvs
+       (undocumented)
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed bug in RecursiveRemove which caused crashed with real
+       data
+
+   * mhft/MGeomCamMagicEnhance.cc, mhft/MHexagonalFTCalc.cc:
+     - updated, but untested
+
+   * mhist/MHCamEvent.[h,cc]:
+     - some fixes in Draw to get a correct display in root 4.02/00
+       (at least on 64-bit systems)
+     - removed kSqrtVariance it is included in kProfile now
+
+   * mhist/MHCamera.[h,cc]:
+     - removed sqrtvariance option which is included in profile now
+     - the profile now uses the new array fBinEntries to display
+       a more accurate profile
+
+   * mhist/MHEvent.cc:
+     - set to type 6 for arrival times
+
+   * mimage/MHillasCalc.cc:
+     - updated text for error=1
+
+   * mimage/MImagePar.cc:
+     - copy number of saturated pixels from MSignalCam
+
+   * mjobs/MJStar.cc:
+     - enhanced title of some histogram
+
+   * mjobs/MSequence.cc:
+     - updated path to fit data center (D.Dorner)
+
+   * mmain/MEventDisplay.cc:
+     - display Arrival Time from MSignalCam now
+
+   * msignal/MArrivalTimeCam.cc:
+     - implemented a new case 6 which is identical with the 
+       default case AND arrival time from MSignalCam
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h,
+     manalysis/:
+     - removed MCerPhotEvt
+     - removed MCerPHotPix
+     - removed MCerPhotAnal
+     - removed MCerPhotAnal2
+     - removed MCerPhotCalc
+
+   * mimage/Makefile, manalysis/ImageLinkDef.h:
+     - removed MHillasSrcCalc
+
+   * manalysis/MSupercutsCalc.cc:
+     - removed an obsolete include
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MHSigmaTheta
+
+   * mmain/Makefile, mmain/HistLinkDef.h:
+     - removed MDataCheck
+     - removed Mars
+     - removed MAnalysis
+     - removed MMonteCarlo
+     - removed MGDisplayAdc
+     - removed MOnlineDisplay
+     - removed MOnlineDump
+
+   * msignal/Makefile, msignal/HistLinkDef.h, msignal/:
+     - added MSignalCam
+     - added MSignalPix
+     - added MSignalCalc
+
+   * msql/Makefile, msql/SqlLinkDef.h:
+     - removed MSqlInsertRun
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - removed MFSelBasic
+     - removed MFSelStandard
+     - removed MFSelFinal
+
+
+
+ 2005/03/17 Thomas Bretz
+
+   * callisto.cc:
+     - added new option moon
+     - use light condition from MSequence to determin light condition
+       automatically
+
+   * mjobs/MJPedestal.h:
+     - allow setting SetUseHists also to kFALSE
+
+   * mjobs/MSequence.[h,cc]:
+     - added fLightCondition
+
+   * mcalib/MCalibrateData.cc:
+     - undocumented change from Markus Gaug
+
+   * mfilter/MFCT1SelBasic.[h,cc], mfilter/MFCT1SelStandard.[h,cc],
+     mfilter/MFCT1SelFinal.[h,cc]:
+     - moved to manalysisct1
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - removed MFCT1SelBasic
+     - removed MFCT1SelStandard
+     - removed MFCT1SelFinal
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MPad
+     - removed MMakePadHistograms
+     - removed MSigmabar
+     - removed MSigmabarParam
+     - removed MSigmabarCalc
+
+   * mimage/Makefile, mimage/ImageLinkDef.h:
+     - removed MImgCleanTGB
+
+   * mmontecarlo/Makefile, mmontecarlo/MonteCarloLinkDef.h
+     - removed MMcEnergyEst
+     - removed MMcTimeGenerate
+
+   * msignal/Makefile, msignal/SignalLinkDef.h:
+     - removed MArrivalTime
+     - removed MArrivalTimeCalc
+     - removed MArrivalTimeCalc2
+
+   * mjobs/MJCalibration.cc:
+     - followed some undocumented changes from the other cvs
+
+
+
+ 2005/03/16 Thomas Bretz
+
+   * callisto.cc:
+     - set changed extractor in MJCalibrateSignal from MJPedestal
+     - don't process 'range finding' for MonteCarlo data
+
+   * callisto.rc:
+     - removed obsolete Modified* option
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - removed obsolete flag for ModifiedExtractWin
+     - allow also NULL for SetExtractor
+     - rearanged the too MWriteRootFile instantiations otherwise
+       callisto crashes in MWriteRootFile::ChangeFile
+     - removed some obsolete comments about an old MC workaround
+
+   * mdata/MDataChain.cc:
+     - fixe to allow sign after e (eg. 1e-3, 1e+5 instead of 1e3, 1e5)
+
+   * mcalib/MCalibColorSet.cc, mcalib/MCalibrationChargeCalc.cc,
+     mhcalib/MHCalibrationCam.cc:
+     - undocummented change
+
+
+
+ 2005/03/16 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - fixed a bug in the reading of the resource file (reading of the 
+       MExtractTimeAndCharge resources was skipped).
+
+   * mcalib/MCalibrateData.cc
+     - for the case that the high-gain saturates, but the low-gain signal
+       could not be extracted successfully, take the high-gain signal,
+       multiplied by 1.5 (before, 0 was taken erroneously).
+
+   * msignal/MExtractTimeAndCharge.cc
+     - catch one potential case for memory leaks in the low-gain 
+       calculation. Extract low-gain only if the remaining extraction 
+       window is not smaller than the number of slices needed by the 
+       signal extractor. 
+     - set the default fgLoGainStartShift to -3.5
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - adjust fLoGainStartShift by one slice, after findings from MC.
+
+
+
+ 2005/03/15 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSpline.h
+     - take fRandomIter out of the streamer. 
+     - take fRiseTimeLoGain and fFallTimeLoGain into the streamer.
+     - raise version number to 4
+
+   * mjobs/MJCalibration.cc
+     - set default to kFALSE for PIN Diode or Blind Pixel calibration 
+       (was kTRUE by error).
+
+
+
+ 2005/03/15 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - added the fExtractor data member
+     - added a destructor deleting it
+     - only read extractor from file if not set by user
+     - user fExtractor as extractor1
+     - do not delete extractor1 if set by user
+     - added member function to set extractor
+
+   * mjobs/MJPedestal.cc:
+     - removed MFEventSelector workaround again
+     - do not write pedy file anymore
+
+   * callisto.cc:
+     - MJCalibrateSignal now takes the signal extractor directly
+       instead of taking the long way round a new file
+
+   * mpedestal/MExtractPedestal.cc:
+     - ReInit extractor correctly. Now the workaround should be
+       really obsolete
+
+   * mbase/MGMenu.[h,cc]:
+     - make fix fix also compile root 3.10.02
+
+
+
+ 2005/03/14 Thomas Bretz
+
+   * mbase/MGMenu.h:
+     - added a fix for root 4.02.00
+
+
+
+ 2005/03/14 Markus Gaug
+
+   * mcalib/MCalibrateData.cc
+     - catch the case that now high-gain low-gian intercalibration const.
+       is available.
+
+   * mjobs/MJPedestal.cc
+     - modify option for pedy*.root: from UPDATE to RECREATE
+
+
+
+ 2005/03/11 Markus Gaug
+
+   * callisto.rc
+     - changed default weights for DF to cosmics_weights4.dat. (This has 
+       turned out to be the most stable set of weights). 
+
+   * mjobs/MJCalibration.cc
+     - some cosmetic changes in the output
+     - in case of WriteHists(), do not overwrite existing signal*.root 
+       file, but append histograms (bugfix!)
+
+
+
+ 2005/03/10 Toni Coarasa (With Nadia's and Alessandro's inside)
+
+   * mjobs/MJCut.cc
+     - inclusion of (TString) to avoid compiler error under 2.95.3
+
+   * sinope.cc
+     - inclusion of <errno.h> to avoid compiler error under 2.95.3
+
+
+
+ 2005/03/10 Markus Gaug
+
+   * msignal/MExtractTimeAndCharge.cc
+     - set fgLoGainStartShift to -4.0
+     - put a check to avoid a dynamic low-gain range < 0 (should not 
+       occur with current extractors, but one never knows...)
+
+   * msignal/MExtractor.[h,cc]
+     - introduced Clear()-function, used in SetRange()
+
+   * mjobs/MJCalibrateSignal.cc
+     - changed order of initialization of the 2 MWriteRootFiles whereupon
+       the crash goes away. Have to revise the /dev/null work-around 
+       in MWriteRootFile!
+
+
+
+ 2005/03/09 Markus Gaug
+  
+   * msignal/MExtractTimeAndCharge.cc
+     - catch a (very unprobable) case in which the low-gain range could 
+       be negative
+
+   * mjobs/MJCalibrateSignal.cc
+     - modify writing of MCalibrationPulseTimeCam to disk in order to 
+       avoid program crash in the destructor of MJCalibrateSignal
+
+   * mhcalib/MHGausEvents.h
+     - take fGraphEvents, fGraphPowerSpectrum, fHPowerProbability and 
+       fPowerSpectrum out of the streamer.
+     - intialize fFlags to 0
+
+
+
+ 2005/03/09 Thomas Hengstebeck
+
+   * mranforest/MRFEnergyEst.cc
+     - changed call of min, max functions to TMath::Min() and 
+       TMath::Max() to avoid compilation problems with some gcc
+       versions
+     - changed check of energy rule (last col of MHMatrix) so, that 
+       any rule containing "fEnergy" is accepted.
+
+
+
+ 2005/03/08 Markus Gaug
+
+   * mhcalib/MHPedestalCam.[h,cc]
+     - introduce new parameter "fFitStart" to decide from outside where
+       to start fitting the pedestals.
+
+
+
+ 2005/03/07 Markus Gaug
+
+   * mjobs/hilocalib_df6.root
+   * mjobs/hilocalib_sp2.root
+     - two files with the high-gain vs. logain intercalibration results.
+       for Digital filter and September data and Spline and December 
+       data.
+
+   * callisto.rc
+     - allow setting the variables ExtractWinLeft and ExtractWinRight.
+
+   * mhcalib/MHCalibrationHiLoCam.h
+   * mhcalib/MHCalibrationCam.h
+   * mhcalib/MHGausEvents.h
+     - put the Draw-functions into the *MENU*
+
+   * mjobs/MJCalibration.[h,cc]
+     - introduced reading of hi-vs.logain calibration file
+
+   * mjobs/MJPedestal.[h,cc]
+     - modified range setting according Thomas S. suggestions
+
+   * msignal/MArrivalTime.[h,cc]
+     - took out some commented code which will not be used any more
+     - improve Print() function
+
+
+
+ 2005/03/05 Markus Gaug
+  
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]
+     - removed the obsolete parts of "kMaximum" and "kHalfMaximum" in the
+       code which were still persistent
+     - set default extraction type to integral (instead of amplitude)
+     - set version number to 3
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - added new function GetAvergedConvFADC2PhePerArea for the datacheck
+
+   * mjobs/MJPedestal.[h,cc]
+     - added function WriteExtractor which writes the extractor with the
+       new ranges to disk if fPulsePosCheck has been selected.
+
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - added functionality to read the updated extractor from 
+       MJPedestalY2 (with the new extraction ranges).
+
+
+
+ 2005/03/04 Abelardo Moralejo
+
+   * mmc/MFadcDefine.h
+     - Changed constant SUBBINS from 5 to 500. This defines the 
+       resolution of the analog signal simulation in the camera MC. 
+       The time step is the duration of one FADC slice divided by 
+       SUBBINS. The change was necessary to implement correctly the PMT 
+       time jitter.
+
+
+
+ 2005/03/03 Markus Gaug
+
+   * mjobs/pedestalref.rc
+   * mjobs/calibrationref.rc
+   * mjobs/calibrationref_Nov04.rc
+     - added documentation
+
+   * mjobs/signalref.rc
+     - added
+
+   * mjobs/MJPedestal.cc
+     - re-added MFEventSelector which had been removed by TB on the
+       15.2.2005.
+     - added pulse position selector, as decided at the Berlin soft-
+       ware meeting.
+
+   * callisto.cc
+     - added SetPulsePosCheck() in MJPedestalY2
+   
+   * mjobs/MJCalibrateSignal.cc
+     - updated pulse pos. calculator, can be switched off now.
+
+   * mjobs/MJCalib.[h,cc]
+     - added flag fPulsePosCheck
+
+
+
+ 2005/03/02 Markus Gaug
+
+   * mjobs/MJCalib.[h,cc]
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - put the storage types in the base class
+
+   * mbadpixels/MBadPixelsCam.cc
+     - add some output in case that AsciiRead does not work
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - speed integration up a little bit.
+
+   * callisto.rc
+     - adapt the low-gain stretch for the different pulse form for 
+       calibration and cosmics pulses (only applied if spline is used).
+
+
+
+ 2005/02/25 Markus Gaug
+
+   * mhcalib/MHCalibrationHiLoCam.[h,cc]
+     - fixed bug in inter-calibration hi-logain for arrival times.
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]
+     - fixed the situation where the maximum bin is already found in the
+       low-gain samples.
+
+   * mjobs/MJCalibration.cc
+     - write the MPedestalCams also to disk (needed for data-check).
+
+
+
+ 2005/02/25 Abelardo Moralejo
+
+   * msignal/MC_calibration_weights_UV.dat
+     - Added. Weights file for using the digital filter on MC 
+       calibration files. For the moment the weights are the same as in
+       the file calibration_weights_UV.dat, only that high and low gain
+       have both the same weights because for the moment the MC pulse
+       shape is the same in both gain branches.
+
+
+
+ 2005/02/24 Markus Gaug
+
+   * mjobs/MJCalibrateSignal.cc
+     - include display of pulse times (calculated in the post-process)
+     - include the possibility for the pixel check (like in MJCalibration)
+
+   * mhcalib/MHCalibrationHiLoCam.cc
+     - set default range up to 30.
+
+   * mhcalib/MHCalibrationChargeBlindPix.h
+     - take the TVectors out of the streamer, to be exectuable with 
+       root.04.02
+
+
+
+ 2005/02/24 Thomas Hengstebeck
+
+   * macros/RFEnergyEst.C
+     - new macro to show the usage of RFEnergyEst class.
+
+
+
+ 2005/02/24 Abelardo Moralejo
+
+   * mtemp/mpadova/macros/resize.C
+     - moved MSrcPosCam output container from RunHeaders to Events tree.
+
+
+
+ 2005/02/18 Marcos Lopez 
+
+   * mflux/
+     - new directory to store the flux related classes.
+  
+   * mflux/MHadAlphaCut.{h,cc}
+     - container to store the optimal hadronness and alpha cut for each bin in
+       estimated energy and theta.
+
+   * mflux/MFHadAlpha.{h,cc}
+     - filter to apply the hadronness and alpha cuts stored in
+       MHadAlphaCut. It can be selected to apply only alpha, only hadronness 
+       cut or both.  
+
+
+
+ 2005/02/18 Markus Gaug 
+
+   * mhcalib/MHCalibrationPulseTimeCam.[h,cc]
+     - new class to histogram the arrival time of cosmics above a certain
+       threshold.
+   
+   * mcalib/MCalibrationPulseTimeCam.[h,cc]
+     - new class container with results of MHCalibrationPulseTimeCam
+
+   * mjobs/MJCalibrateSignal.cc
+     - include MCalibrationPulseTimeCam to display
+
+ 2005/02/18 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - switch off TH1::AddDirectory during DrawClonePad
+
+   * mjobs/MSequence.[h,cc]:
+     - added some code (still commented) for later use, 
+       allowing to setup a different filename for each runfile
+     - added SetNight member function
+     - added Add*Runs member function
+     - with this changes MSequence can replace MRunIter now
+     - allow requesting of standard path from outside 
+       (GetStandardPath)
+
+   * Makefile:
+     - added sinope
+
+   * sinope.cc:
+     - added (small tool to check contents of run for datacenter)
+
+   * callisto.cc:
+     - added background information about Callisto
+
+   * ganymed.cc:
+     - added background information about Ganymed
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed special MC code. The MC files now have a lo-gain
+       switch and we can extract the pedestal rms from lo-gain
+     - don't print statistics if nothing was executed
+     - fixed display. The displayed pedestal RMS was the one
+       caluclated with a extractor but not at random position
+       (This only effects the display, the algorithm was ok)
+
+
+
+ 2005/02/17 Markus Gaug
+
+   * mjobs/MJCalibTest.cc
+     - removed bug treating the MC calibration files uncorrectly
+     - added Pixel-Check treatment
+
+   * mjobs/MJCalibration.cc
+     - added Pixel-Check treatment
+
+   * callisto.rc
+     - added pixel-check option
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - calculate high-gain signal even if saturation occurs
+
+
+
+ 2005/02/17 Thomas Bretz
+
+   * mjobs/MJStar.cc:
+     - fixed some missing containers in case of MC files
+
+   * callisto.cc:
+     - removed obsolete second check for kModeC
+
+   * mars.rc:
+     - added a lot of option to be able to use a 
+       different signal extractor looking into uncalibrated
+       data
+
+   * manalysis/MCameraData.[h,cc]:
+     - added Print() member function
+
+   * manalysis/MCerPhotAnal2.[h,cc]:
+     - switched off writing into MCerPhotEvt
+
+   * mdata/MDataChain.[h,cc]:
+     - added code to handle priorities of operators correctly
+
+   * mhist/MHEvent.cc:
+     - fixed display for MPedestalRMS
+
+   * mjobs/MJCalib.cc:
+     - fixed treatment of PixelCheck resource
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added some comments about Monte Carlo
+     - added MMcFadcHeader to output
+
+   * mjobs/MJPedestal.cc: 
+     - do not allow 'UseData' for Monte Carlos. Reason is given as 
+       comment in the code
+
+   * mmain/MEventDisplay.[h,cc]:
+     - changed such, that mars.cc allows to set the used extractor
+     - removed the obsolete cam.root, ped.root option
+
+   * mmain/MCameraDisplay.cc:
+     - adapted to change in MEventDisplay
+
+
+
+
+ 2005/02/16 Javier Rico
+
+   * mhistmc/MHMcUnfoldCoeff.[cc,h], mhistmc/Makefile, 
+     mhistmc/HistMcLinkDef.h
+     - Added container class holding the histograms of the coefficients
+       for the (iterative) unfolding.
+
+   * mmontecarlo/MMcUnfoldCoeffCalc.[cc,h], mmontecarlo/Makefile, 
+     mmontecarlo/MonteCarloLinkDef.h
+     - Added task class to compute the coefficients for the (iterative) 
+       unfolding.	
+
+   * macros/unfoldCoeff.C
+     - added macro that computes the effective areas and coefficients
+       from a MC input file (with OriginalMC tree and MEnergyEst
+       branch containing the energy estimator). This may be used 
+       as layout for spectrum computation program.
+
+
+
+ 2005/02/16 Markus Gaug
+
+   * mdata/MDataChain.cc
+     - replaced ROOT version check for the compiler from 4.02.00 to 
+       4.01.00
+
+   * mranforest/MRFEnergyEst.cc
+     - include "TVector.h", otherwise this class does not compile
+       in newer root versions
+
+   * msignal/MExtractTimeAndCharge.cc
+     - initialize fLoGainStartShift correctly if read from conf. file 
+       and modified fOffsetLoGain exists.
+
+   * msignal/*weights*.dat
+     - new weights with the uniform pedestal RMS. (Please use these!)
+
+   * msignal/pulpo_weights*.dat
+     - new weights with the pulpo-pulse form and without NSB!!
+
+
+
+ 2005/02/16 Thomas Hengstebeck
+
+   * mranforest/MRFEnergyEst.[h,cc]
+     - added RF class for energy estimation
+
+   * mranforest/MRFEnergyEst.cc
+     - changed calculation of estimated energy, now interpolated values
+       are returned                                                                        	
+
+
+
+ 2005/02/16 Abelardo Moralejo
+
+   * macros/starmc2.C:
+     - Changed the way in which the "OriginalMC" tree is copied from
+       the input to the output file. Now we ise the new procedure
+       MWriteRootFile::AddCopySource
+
+   * mhistmc/MHMcCollectionArea.cc
+     - Changed default fName to "MHMcCollectionArea"
+
+   * mtemp/mpadova/macros/resize.C
+     - Changed weights
+
+
+
+ 2005/02/16 Thomas Bretz
+
+   * mbase/MEvtLoop.cc:
+     - fixed a typo
+
+   * mbase/MParList.cc, mfileio/MReadMarsFile.cc,
+     mfileio/MReadTree.cc, mfileio/MWriteRootFile.cc,
+     mjobs/MJStar.cc:
+     - optimized size of some output
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - fixed CopySource option for single-file case
+
+   * mhist/MHCamEvent.cc:
+     - replaced the warn in SetupFill by an inf
+
+   * mhcalib/MHCalibrationCam.cc, mhcalib/MHCalibrationHiLoCam.cc,
+     mhcalib/MHCalibrationChargePINDiode.cc:
+     - removed obsolete output after a failed FindCreateObj (the
+       function itself does the output in case of failure)
+
+   * mhcalib/MHCalibrationCam.cc:
+     - replaced 'err' by 'warn' for under-/overflow in lo-gain pixel,
+       it doesn't result in an fatal error (abort)
+
+   * mranforest/MRanForestCalc.cc:
+     - added a missing debug level to some output
+
+   * mranforest/MRFEnergyEst.[h,cc]: 
+     - cleaned up includes
+
+   * callisto.cc, ganymed.cc, star.cc:
+     - implemented enhanced handling of resource debugging
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MEnv
+
+   * mbase/MEnv.[h,cc]:
+     - added
+
+   * mjobs/MJob.[h,cc]:
+     - added new function to allow distribution of extranl MEnv
+     - replaced Bool_t by Int_t for fEnvDebug
+
+   * mjobs/MJPedestal.cc:
+     - adapted to changes of EnvDebug
+
+
+
+ 2005/02/15 Abelardo Moralejo
+
+   * macros/mccalibrate.C
+     - fixed small bug
+
+   * mmontecarlo/MMcCollectionAreaCalc.[h,cc] 
+   * mhistmc/MHMcCollectionArea.[h,cc]
+     - Changed the way of calculating final effective area for data 
+       analysis. The new approach requires the use of MC files produced
+       with the current CVS version of camera. We now make use of the
+       true total number of produced MC events, and allow for the 
+       setting of a "tentative" differential gamma spectrum to be used 
+       in the calculation of effective areas. 
+       Removed unused constructor argument "input" in 
+       MMcCollectionAreaCalc.
+
+   * macros/collarea.C
+     - Adapted to the new way of calculating effective areas.
+
+
+
+ 2005/02/15 Thomas Bretz
+
+   * callisto.rc:
+     - replaced mutal exclusive options (Integral, Amplitude) by
+       a one-line resource
+
+   * msignal/MExtractTimeAndChargeSpline.cc:
+     - replaced mutal exclusive options (Integral, Amplitude) by
+       a one-line resource "ExtractionType" (old code still works)
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added new variables to store information about islands
+       and removed pixels - PRELIMINARY
+     - increased class version number
+
+   * mfilter/MFSoftwareTrigger.cc:
+     - optimized output in PostProcess
+
+   * mimage/MHImagePar.[h,cc]:
+     - added new histograms for new variables in MCerPhotEvt
+
+   * mimage/MImagePar.[h,cc]:
+     - added new data members for the new image parameters
+     - increased class version
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - adapted image cleaning to calculate the new image
+       parameters
+     - added a flag to keep single core pixels
+
+   * manalysis/MMatrixLoop.[h,cc], mfileio/MReadReports.[h,cc],
+     mfileio/MReadRflFile.[h,cc], mfileio/MReadTree.[h,cc],
+     mraw/MRawFileRead.[h,cc], mraw/MRawSocketRead.h:
+     - renamed GetFileName to GetFullFileName
+
+   * mbase/MInputStreamID.h:
+     - added new member function HasStreamId
+
+   * mbase/MParContainer.[h,cc]:
+     - added a static list to keep track of all created
+       TMathodCall objects
+
+   * mbase/MTask.cc:
+     - enhanced PrintStatistics
+
+   * mfileio/MRead.[h,cc]:
+     - new abstract function GetFullFileName
+     - added implementatio of GetFileName based on GetFullFileName
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - moved open of a new file to new common member function
+       OpenFile
+     - allow to use an already existing file also when using rules
+     - added a new option which can be used to copy an existing
+       tree (without any change) from the old file into the new file.
+       (in principal you can also do this for some of its branches only)
+       This is done by AddCopySource
+
+   * mjobs/MJCalibrateSignal.cc:
+     - in case of MonteCarlo files write an independant tree
+       'MonteCarlo' for 'MMcEvtBasic'
+
+   * mjobs/MJStar.cc:
+     - copy tree 'MonteCarlo' from old into new files
+
+   * mjobs/MJPedestal.cc:
+     - removed wrong use of MFEventSelector
+
+   * mpedestal/MExtractPedestal.cc:
+     - made sure that fExtractor is correctly pre- and 
+       postprocessed.
+
+   * mbase/MTask.cc:
+     - don't preprocess a task if it has been preprocessed already
+
+   * mraw/MRawFileWrite.cc:
+     - if display is set write output to status line
+
+   * mfileio/MReadTree.cc, mfileio/MReadMarsFile.cc:
+     - moved code to display filename in status display from
+       MReadMarsFile::Notify to MReadTree::Notify
+
+
+
+ 2005/02/15 Markus Gaug
+
+   * mjobs/MJCalib.h
+     - added GetDataFlag(), otherwise code does not compile!
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - moved default saturation limit for number of high-gain events from 
+       0.02 to 0.05. 
+
+   * msignal/MExtractTimeAndCharge.cc
+     - lowered default low-gain switch from 150 to 120. (for calibration 
+       events which saturate more than 5% of the events).
+
+   * mjobs/MJCalib.[h,cc]
+     - include possibility to display pixels distributions for test
+       reasons
+
+
+
+ 2005/02/14 Thomas Bretz
+
+   * callisto.cc, ganymed.cc, star.cc:  
+     - added some more information to '--help' output
+     - replaced MSequences by MDataSet
+     - implemented new debugging options (maybe not perfect yet)
+       --print-files and --print-found
+
+   * mjobs/MJCut.[h,cc]: 
+     - replaced MSequences by MDataSet
+     - write MEnergyEst
+     - recalculate MHillasSrc
+     - made sure both MWriteRootFile have different names
+     - don't use "same" option if no off-data
+
+   * mjobs/MSequences.[h,cc]: 
+     - removed
+
+   * mjobs/MDataSet.[h,cc]: 
+     - added
+
+   * manalysis/MEventRateCalc.[h,cc]:
+     - added a fix which make sure, that the rate is not influenced
+       too much by the start of data taking
+     - fixed setting of mean time corresponding to rate-interval
+
+   * mraw/MRawFileRead.[h,cc]:
+     - calculate total number of events from all files in PreProcess
+
+   * mcalib/MCalibConstCam.cc:
+     - added case 2 to GetPixelContent
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed redirection of stream with interleaved calibration infos
+     - changed 'Arrival Time' to 'Calibrated Arrival Time'
+     - display interpolated signal in equivalent photoelectrons to
+       to get rid of scaling effects which makes it difficult to see 
+       details of the structure of the inner pixels in the histogram.
+       With this you can immediatly see whether the relative number
+       of phe in the outer pixels is equiv. to the inner pixels.
+     - the same for the calibration factor - with the same argument
+     - adapted to change in MWriteRootFile
+     - use MReadMarsFile for Monte Carlo flag set
+
+   * mhist/MHCamera.cc:
+     - changed drawing such, that NaN is not displayed anymore
+
+   * Makefile:   
+     - added new program ganymed
+
+   * mfileio/MWriteRootFile.[h,cc]:  
+     - added possibility to use UPDATE mode with rules (dangerous!)
+       as discussed with Abelardo, Daniel M. and Thomas S.
+
+   * mjobs/MJStar.cc:
+     - adapted to change in MWriteRootFile
+     - added software trigger (still untuned) as suggested by
+       Thomas S.
+     - added calculation of source position before calculation
+       of image parameters
+     - added MPointingPos to Events-Tree
+     - removed MPointingPos from Drive-Tree
+     - renamed sub-tasklists to something more intuitive
+
+   * mjobs/Makefile, mjobs/JobsLinkDef.h:
+     - added MJCut.cc
+
+   * mraw/MRawFileRead.cc:
+     - return kERROR if ReInit fails
+
+   * mfilter/MFSoftwareTrigger.[h,cc]:  
+     - updated to allow using time coincidence
+     - changed default values
+     - added a pattern independant trigger algorithm
+
+   * mbase/MDirIter.cc:
+     - implemented option 'dbg' in Print()
+
+   * mjobs/MJCalib.h:
+     - added a getter for data-flag (should be renamed
+       to 'datatype' soon)
+
+
+
+ 2005/02/12 Abelardo Moralejo
+
+   * mtemp/mpadova/macros/wobblemap.C
+     - Added. Macro to do some studies on wobble mode data.
+
+   * macros/mccalibrate.C
+     - Added option to divide the output in a train and a test sample.
+       Included in output new container MMcEvtBasic (if found in input 
+       files) for later use in effective areas calculations.
+
+   * macros/starmc2.C
+     - Added writing out of new container MMcEvtBasic. Removed 
+       possibility of splitting output in train and test samples, since
+       this has now to be done in mccalibrate.C to make possible that 
+       the tree OriginalMC containing MMcEvtBasic has all the original
+       MC events (and only those) from which the events present in the
+       Events tree derive.
+
+   * macros/starmc.C
+     - Changed a couple of wrong "." by "->" in function calls. Changed
+       default tail cuts.
+
+
+
+ 2005/02/12 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - change default rise time to 0.5 and default fall time to 1.5
+
+   * callisto.rc
+     - made intitializations of extractors more explicit
+
+   * mpedestal/MExtractPedestal.cc
+     - make check for even number of slices in the case of "fundamental"
+       pedestal calc.
+ 
+   * mcalib/MCalibrationChargeCalc.cc
+     - take out some commented code
+
+   * mjobs/MJCalib.h
+     - removed GetDataFlag()
+
+
+
+ 2005/02/12 Abelardo Moralejo
+
+   * mmc/MMcTrig.hxx 
+     - Added getter GetNumFirstLevel. This is necessary if that data
+       member is to be used for instance in MF filters. There was 
+       already a getter, but it is called GetFirstLevel and hence not
+       recognized.
+
+
+
+ 2005/02/11 Abelardo Moralejo
+
+   * mmc/MMcEvtBasic.[h,cc]:
+     - New class. Contains 5 very basic MC parameters which we intend
+       to save for all generated Corsika events. This is needed for
+       proper effective area calculations.
+
+   * mmc/Makefile, McLinkDef.h
+     - Added new class above.
+
+
+
+ 2005/02/11 Thomas Bretz
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - added the possibility to write to an already existing file.
+      This doesn't affect the old behaviour, but using this new feature
+      might still have problems.
+
+   * mfileio/MReadReports.cc: 
+     - fixed column-level in PrintStatistics
+
+   * mjobs/MJCalibrateSignal.cc:
+     - keep MMcRunHeader in the output
+
+
+
+ 2005/02/10 Abelardo Moralejo 
+
+   * macros/mccalibrate.C 
+     - Added possibility to calibrate in photons or photoelectrons
+
+   * macros/starmc2.C
+     - Added comment about value of cleaning levels
+
+
+
+ 2005/02/10 Markus Gaug 
+ 
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MCalibrate.[h,cc] 
+     - removed mcalib/MCalibrate.* because it has been replaced by 
+       MCalibrateData
+
+   * mmain/MEventDisplay.cc
+     - replaced MCalibrate by MCalibrateData
+
+   * mhcalib/MHCalibrationCam.cc
+     - replaced warning about empty histogram from red (err) by 
+       yellow (warn).
+
+   * mcalib/MCalibColorSet.cc
+     - return kTRUE in case of MC-file
+
+   * msignal/MExtractTimaAndChargeSpline.[h,cc]
+     - make sure that all variables are set correctly independent on 
+       the order of their initialization by the user
+
+
+
+ 2005/02/10 Thomas Bretz
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added new member functions (GetNeighbors) to get all pixels
+       around a given pixel with a given radius
+
+   * mars.rc:
+     - use same values for image cleaning as default in star
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - added the possibility to set the Source position from
+       a resource file
+
+   * mjobs/MJStar.cc:
+     - write MMcRunHeader to RunHeaders
+
+   * mfileio/MWriteRootFile.cc:
+     - removed an obsolete line
+     - removed a debug line which should not be there
+
+   * mimage/MHillas.h:
+     - added new Getter GetDist0 returning the distance to the 
+       camera center
+
+   * mhflux/MHFalseSource.cc:
+     - the scaling in Paint() was nonsense in case we are looking
+       at on/off-data. Fixed.
+
+
+
+ 2005/02/10 Abelardo Moralejo 
+
+   * manalysis/MMcCalibrationUpdate.h
+     - Added comment on new member fSignalType. Sorry for compilation
+       problems... I forgot to commit the header yesterday, but M. Gaug 
+       did it.
+
+   * macros/starmc.C
+     - Cleaned up a little bit, made the option to choose between 
+       calibration in photons or phe- easier to set.
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Added getter and setter for fSignalType. Set fSignalType=kPhot as
+       default for consistency with MCalibrateData.
+
+
+
+ 2005/02/09 Abelardo Moralejo 
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - Updated to make the MC calibration in phe- work
+
+   * macros/starmc.C
+     - same as above. Now default is calibration in phe-
+
+   * mraw/MRawEvtHeader.h
+     - Added setter for the trigger pattern, absolutely needed for 
+       creating proper MC root files.
+
+
+
+ 2005/02/09 Markus Gaug 
+
+   * manalysis/MMcCalibrationUpdate.h
+     - added missing declaration of fSignalType
+
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/badpixels_0_559.rc
+   * callisto.rc
+     - allow exclusion of bad pixels from the beginning (default is 
+       Pixel 0 and 559).
+     - removed some obsolete includes
+     - took out data member fPedestalHist from MJPedestal.h which removes 
+       the crash, however I don't understand why it caused the crash!!! 
+       There seem to be problems with memory usage either in callisto.cc 
+       or in this class!!
+       (valgrind shows several memory leaks in the TG... classes).
+  
+   * mjobs/MJCalibration.cc
+     - write display and containers also in case of failure of eventloop
+
+   * mhcalib/MHGausEvents.cc
+     - make default display window 600x600
+
+   * mcalib/MCalibrationQECamMagic.cc
+     - updated five pixels
+
+   * mpedestal/MExtractPedestal.[h,cc]
+   * mpedestal/MPedCalcPedRun.cc
+   * mpedestal/MPedCalcFromLoGain.cc
+     - included possibility for intermediate pedestal cam (not yet used)
+
+   * msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc
+     - initialize the bad events counters to 0 also in constructor 
+     - release the limit for bad events a bit
+
+   * mcalib/MCalibrationTestCam.h
+     - take out include of TArrayI (already in base class)
+
+   * mcalib/MCalibrateData.h
+     - make default argument for SetSignalType kPhe.
+
+   * mjobs/MJCalibrateSignalFromOuside.[h,cc]
+     - removed
+
+
+
+ 2005/02/08 Markus Gaug 
+ 
+   * mhcalib/MHCalibrationCam.cc
+   * mcalib/MCalibrationChargeCalc.cc
+     - replaced GetNumExecutions()==0 condition by GetNumExecution() < 1 
+
+
+
+ 2005/02/08 Thomas Bretz
+
+   * mpointing/MPointingPosInterpolate.cc:
+     - use debug option in addition to switch off output from internal
+       eventloop. It is confusing having this output inside another
+       eventloop.
+     - updated missing connections in class description
+
+   * msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc:
+     - made sure that output of PostProcess fits into 80col boundary
+
+   * mimage/MHillas.cc:
+     - removed an obsolete call to TLine::Paint() in Paint.
+
+
+
+ 2005/02/07 Thomas Bretz
+
+   * mbase/MFilter.cc:
+     - use paranthesis around ClassName in GetRule
+
+   * mdata/MDataFormula.h:
+     - fixed a wrong comment in variable description
+
+   * mhist/MHCamEvent.[h,cc], mhist/MHCamera.[h,cc],
+     mjobs/MJCalibrateSignal.cc, 
+     mjobs/MJCalibrateSignalFromOutside.cc:
+     - to make sure there are no missunderstandings we have to
+       replace all occurances of 'Variance' by 'SqrtVariance'
+       (it was not my decision)
+
+   * mastro/MAstro.[h,cc]:
+     - added new function Angle2Coordinate
+
+   * mbase/MTaskEnv.[h,cc]:
+     - fixed a bug which caused the resource task to be ignored
+       if the default task was '<dummy>'
+
+   * mhbase/MH3.cc:
+     - fixed a bug in Paint (use GetListOfPrimitives->FindObject
+       instead of FindObject) which caused the histogram to
+       be put a lot of times into the pad.
+
+   * mjobs/MJCalib.[h,cc]:
+     - derived MJCalib from MJob in order to be able to move
+       common code from derived classes into the base-class
+     - implemented CheckEnvLocal to handle the resource 'DataType'
+     - changed publicity of some variables and functions
+       to allow setting file type from outside
+     - added new function to set data-type for use in callisto.cc
+
+   * mjobs/MJCalibTest.[h,cc], mjobs/MJCalibrateSignal.[h,cc],
+     mjobs/MJCalibration.[h,cc], mjobs/MJPedestal.[h,cc]:
+     - removed double inheritance, replaced by single inheritance
+       from MJCalib
+     - replaced code to handle the resource 'DataType' by the 
+       common code in the base class
+     - put reading of reference file into a new member function
+       to make source code reading resource file simpler and to
+       be able to write a function description about it (simple
+       copy&past)
+
+   * callisto.cc:
+     - added option for file-type
+
+   * mjobs/MJOptimize.[h,cc], mjobs/MSequences.[h,cc],
+     mjobs/MJCut.[h,cc], ganymed.[cc,rc], mhflux/MHEnergyEst.[h,cc]:
+     - added to repository, but not yet to Makefile because
+       there is still some work to be done. But whoever is
+       interested in the new classes/program may already use it.
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added option to choose the minimization value
+
+   * mhflux/MHAlpha.cc:
+     - replaced significance by minimization value
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - use E-Option when fitting to improve error calculation
+       by using Minos technique
+
+
+
+ 2005/02/04 Markus Gaug
+
+   * mjobs/MJCalibration.cc
+     - found a "the `impossible' happened" when running callisto with 
+       a pure signal extractor --> MExtractTimeFastSpline has some 
+       problems with the management of the internal arrays. Replaced it 
+       by MExtractTimeHighestIntegral as default which is as good. 
+
+   * callisto.rc
+     - use MExtractTimeAndChargeDigitalFilterPeakSearch as default 
+       instead of MExtractTimeAndChargeDigitalFilter. This extractor is 
+       now tested and checks for the positions of the pulse within the
+       DAQ-window.
+
+
+
+ 2005/02/04 Thomas Bretz
+
+   * Makefile.rules:
+     - fixed creation of main MDep.d
+
+   * callisto.cc, merpp.cc, showlog.cc, showplot.cc, star.cc:
+     - added commandline option --version
+
+   * mbase/MFilter.cc:
+     - changed default for 'GetRule'
+
+   * mbase/MParContainer.cc:
+     - simplified GetNewObject
+
+   * mfbase/MF.cc:
+     - if no conditional sign is found try to create
+       MFilter-object
+
+   * mraw/MRawEvtData.cc:
+     - fixed the initialization of fABFlags in case maxid==0 which
+       is the default. This caused MRawEvtPixelIter::HasABFlag
+       to do unallowed access to memory for old root-files without
+       the AB flag, because it assumed (due to size==1) that the
+       data contains the ab flag
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - removed some obsolete debug comments
+     - simplified HasABFlag
+
+   * manalysis/MCerPhotPix.h:
+     - removed the `!` again. It gave problems with the Mars
+       display. We agreed that this is a minor problem because
+       the structure of MCerPhot* will chnage soon in any case.
+
+
+
+ 2005/02/04 Abelardo Moralejo
+
+   * macros/starmc2.C
+     - added to output missing container MConcentration.
+
+
+
+ 2005/02/03 Thomas Bretz
+
+   * mfbase/MFilterList.[h,cc]:
+     - added new function AddToList(TCollection&)
+
+   * mhbase/MFillH.cc:
+     - print a warning if 'same'-option given without 
+       a corresponding existing tab
+
+   * mhflux/MHAlpha.[h,cc]:
+     - made time bins settable by user
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed ReInit and a warning output when writing to memory
+
+
+
+ 2005/02/03 Markus Gaug
+
+   * mcalib/MCalibColorSet.[h,cc]
+     - implement possibility to set colour explicitely (e.g. for MC).
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - intialize fTimeShiftHiGain and fTimeShiftLoGain by default.
+ 
+   * mjobs/MJPedestal.cc
+     - in case, extractor is used, put the extractor into the tasklist, 
+       otherwise ranges do not get initialized correctly (wrong memory 
+       usage!). Use an event selector, however to not skip the Process.
+       This is as fast as before and now safe for any kind of extractor
+  
+   * mcalib/MCalibrationCam.h
+   * mcalib/MCalibrationTestCam.h
+   * mcalib/MCalibrationTestCam.cc
+     - initialize a missing array in InitAverageAreas
+ 
+   * mraw/MRawEvtHeader.h
+     - introduced Setter() of cal. pattern for Abelardo
+
+
+
+ 2005/02/02 Markus Gaug
+
+   * mcalib/MCalibrationChargeCam.cc
+     - fixed small bug in the display of mean charges when low-gain was
+       used.
+
+   * msignal/MExtractor.cc
+     - print the missing overlap between high-gain and low-gain
+       in the Print() function
+     - remove setting of fHiLoLast in PreProcess, otherwise cloned 
+       extractors do not work any more with windows exceeding the 
+       high-gain range.
+
+   * mhcalib/MHCalibrationTestCam.[h,cc]
+   * mhcalib/MHCalibrationTestTimeCam.[h,cc]
+     - set proper probability limits for the fits
+
+   * mcalib/MCalibrateData.cc
+     - catch the case in which no interlaced cal. events are being sent
+       by the pulser box.
+
+   * mjobs/MJCalib.[h,cc]
+     - put the data type enum in a new base class
+
+   * mjobs/MJCalibTest.[h,cc]
+     - re-name old class MJExtractCalibTest to MJCalibTest and make it 
+       compatible with the sequence-files.
+   
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - removed
+
+   * mjobs/MJCalibrateSignal.cc
+     - put a compiler warning about the default cal. to photo-electrons
+
+   * callisto.cc
+     - add new flag "--use-test" to enable the MJCalibTest facility
+       (default: not used)
+
+
+
+ 2005/02/01 Raquel de los Reyes
+
+   * mjobs/MSequence.h
+     - Added "Get" functions for the TArrays variables.
+
+
+
+ 2005/02/01 Markus Gaug
+  
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+   * mjobs/MJCalibrateSignal.[h,cc]
+   * callisto.rc
+     - put enum for data type. Can now set the data type (mc, raw, root)
+       without running the data check.
+
+   * mhcalib/MHCalibrationCam.cc
+     - return kTRUE in PostProcess if GetNumExecutions is 0
+   
+   * mcalib/MCalibrationChargeCalc.cc
+     - return kTRUE in PostProcess if GetNumExecutions is 0
+
+
+
+ 2005/02/01 Daniel Mazin
+
+   * MPointingPosInterpolate.cc:
+     - fixed bug to match the units of Ra and Decl in MPointingPos
+     - fixed bug in handling of events with times outside of times from 
+       MDrive tree
+
+
+
+ 2005/02/01 Thomas Bretz
+
+   * showplot.cc:
+     - another fix to make the batch mode working (you can use the batch
+       mode to convert a root-file into another format)
+
+
+
+ 2005/01/31 Thomas Bretz
+
+   * mbase/MStatusDisplay.cc:
+     - fixed handling of batch mode in GetCanvas(const TString &name)
+     - don't skip already existing tabs in Display()
+
+
+
+ 2005/01/31 Raquel de los Reyes
+
+   * mjobs/MSequence.h
+     - Added "Get" functions for some of the sequence.txt file 
+       parameters.
+
+
+
+ 2005/01/31 Markus Gaug 
+ 
+   * mjobs/MJob.[h,cc]
+   * mjobs/MJCalibrateSignal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+     - move file type enum to base class
+
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - allow also for direct setting of an MRunIter (not used in
+       callisto).
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - test also for pulser strength changes additionally to changes in 
+       colour.
+
+
+
+ 2005/01/31 Abelardo Moralejo
+
+   * mpointing/MSrcPosCalc.cc
+     - Create only one instance of MAstroSky2Local for the 
+       transformations, instead of two identical ones, as it was before.
+
+
+
+ 2005/01/30 Markus Gaug 
+ 
+   * mjobs/MJCalibration.cc
+   * mjobs/MJPedestal.cc
+   * mjobs/calibrationref_Nov04.rc
+   * mhcalib/MHCalibrationRelTimeCam.[h,cc]
+     - updated correct display of reference lines
+
+
+
+ 2005/01/29 Markus Gaug 
+    
+   * msignal/MExtractFixedWindowSpline.[h,cc]
+     - fixed a bug occurring with overlapping windows between high-gain
+       and low-gain
+
+   * msignal/MExtractFixedWindowPeakSearch.cc
+     - take out call to fSignals->Clear() which is already done in 
+       MTaskList.
+
+   * msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.[h,cc]
+     - new extractor reducing the bias and solving the problem with the 
+       jumping pulse readout.
+
+
+
+ 2005/01/28 Abelardo Moralejo
+
+   * mpointing/MSrcPosCalc.cc
+     - updated. Make it work as desired: obtain for each event the x,y 
+       position on the camera of a source whose celestial coordinates 
+       (J2000) have been set by the user in the container "MSourcePos" 
+       of type MPointingPos, added to the parameter list. If the 
+       container MSourcePos is not found, the center of the camera (or 
+       other fixed position x,y set in the parameter list by the user - 
+       in MSrcPosCam) is used as source position for all the events in 
+       the loop.
+
+
+
+ 2005/01/28 Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed that extract1,2,3 haven't been deleted if loop failed.
+     - print tasklist also if loop failed.
+     - added a undefined task (MTaskEnv "FinalFantasy") as last task to
+       the event processing tasklist
+
+   * callisto.rc:
+     - added comments about "FinalFantasy" into call
+     - added comment for obsolete resources as discussed yesterday
+       evening: TimeUpperLimit
+
+   * mbase/MMath.[h,cc], manalysis/MCerPhotPix.[h,cc], 
+     mpedestal/MPedPhotPix.h:
+     - replaced TruncatePrecision by ReducePrecision (its simply a better
+       name)
+
+   * mbase/MParList.cc:
+     - added a check to make 200%(!) sure that the container added
+       to the list is a MParContainer (everything else could crash
+       almost everything in Mars!)
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.[h,cc],
+     mjobs/MJPedestal.cc:
+     - simplified the code in the WriteResult functions by using
+       the new WriteContainer in MJob
+     - removed the TObjArray from the MParList! It is NOT a MParContainer
+       there are a lot of circumstance how this can crash Mars. I don't
+       know why the compiler allowed for this.
+     - unified WriteResult and WriteHists
+     - split GetOutputFile into two functions for simplification
+
+   * mjobs/MJCalibration.h:
+     - copy the extractorcam name when copying the contents
+
+   * mjobs/MJob.[h,cc]:
+     - new member function WriteContainer to simplify code in derived
+       classes
+
+   * mpointing/MSrcPosCalc.[h,cc]
+     - fixed the header according to Abelardo's changes
+     - added the initialization of the pointers to the constructor
+
+
+
+ 2005/01/28 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - introduce a security check for the time fine adjustment in case, 
+       it is too large.
+
+   * mcalib/MCalibConstCam.[h,cc]
+   * mcalib/MCalibConstPix.h
+     - new classes to allow display of changing cal. constants with the
+       interlaced cal. events
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - removed stopping of PostProcess in case that the evtloop is
+       finished with interlaced cal. events
+
+   * mcalib/MCalibrateData.[h,cc]
+     - fill MCalibConstCam with update results (once per calib. consts
+       update == every 10 sec.)
+     - introduce check for size of calibration constant. In case, it is 
+       completetly out of range, set the MBadPixelsPix::IsUnsuitableRun
+
+   * mjobs/MJCalibrateSignal.cc:
+     - display one MHCamera more with changing conv. factors (only for
+       interlaced cal. events)
+
+   * mpedestal/MPedCalcFromLoGain.cc
+     - set default for MExtractWinFirst from 15 to 17 because of the 
+       late cosmics signals in December
+
+
+ 2005/01/28 Abelardo Moralejo
+
+   * mtemp/mpadova/macros/trainsubsample.C
+     - added # of events to be written in the output (instead of 
+       fraction of total). Moved MSrcPosCam in output from RunHeaders
+       to Events tree.
+
+
+
+ 2005/01/27 Daniel Mazin and Markus Gaug
+
+   * mcalib/MCalibrateData.[h,cc]
+     - derive this class from MCamEvent in order to be able to display
+       evolution of conversion factors in case of interlaced cal. 
+       events
+
+   * mpointing/MInterpolatePointingPos.[h,cc]
+     - new class to interpolate pointing positions, adapted from a class 
+       by Marcos Lopez 
+
+   * mjobs/MJCalibrateSignal.[h,cc]
+     - enabled the calibration of data with interlaced calibration events     
+
+   * msignal/MArrivalTime.[h,cc]
+   * mcalib/MCalibrateRelTime.cc
+     - removed Error of calibrated arrival time, as agreed on the last 
+       software calibration meeting yesterday
+
+   * mjobs/MJCalibrateSignal.cc
+     - add display to show histogramming of conversion factors
+     - modify default calibration to equiv. photo-electrons
+     - allow for setting of MC, Raw or Root-file type in callisto.rc
+
+   * callisto.rc
+     - updated conf. file
+
+
+ 2005/01/27 Thomas Bretz
+
+   * callisto.cc:
+     - don't display starting pedestals when calibrating the signal
+
+   * callisto.rc:
+     - added some comments
+
+   * star.rc:
+     - according to Daniel M. we have agreed to change the default
+       cleaning level to adapt it roughly to the new pedestal
+
+   * manalysis/MCerPhotPix.[h,cc], mpedestal/MPedPhotPix.h:
+     - as agreed in the current calibration meeting we truncate the
+       precision of the stored floating point values to roughly 0.5%
+       to gain storage space in the calibrated data (the gzip
+       algorithm compresses this stuff nicely - we gain roughly 15%)
+
+   * mhflux/MHFalseSource.cc, mjobs/MJCalibration.cc, mjobs/MJStar.cc:
+     - added a comment
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed title of unsuitable plot
+     - removed plot for calibrated fundamental pedestal as agreed in the
+       current calibration meeting (we may change this to an option)
+
+   * mjobs/MJPedestal.[h,cc]:
+     - changed the name of the "PedDiff" plot to be consistent with the
+       other tab-name
+     - changed the options for the display
+     - removed the dependancy of fDisplayType and the SetDataCheck
+       option
+     - added option kDisplayNone
+     - renamed enums from k*Display to kDisplay*
+
+   * mhist/MHCamEvent.cc:
+     - trying to get rid of the Err_%p workaround.
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added some '!' signs in the comment line. This is quick hack
+       to gain I/O speed and storage space. We will soon have new
+       containers for the calibrated data and image cleaning
+       information.
+     - changed version number to 6
+
+   * mhist/MHCamera.cc:
+     - added member function SetAllUsed
+
+
+
+ 2005/01/26 Abelardo Moralejo
+
+   * macros/mccalibrate.C
+     - removed creation and writing out of MSrcPosCam. It is more 
+       flexible to add it in starmc2.C if needed (for wobble mode for
+       instance).
+
+   * mtemp/mpadova/macros/RanForestDISP.C
+     - added possibility to set the number of hadrons read in for the 
+       training. Added some missing containers to output.
+     - Fixed rule concerning the DISP, by adding parentheses. Remember
+       that MHMatrix::AddColumn  does not respect the usual precedence
+       of operations!
+
+   * mtemp/mpadova/macros/resize.C
+     - added to output missing container MRawEvtHeader
+
+   * macros/starmc2.C
+     - added missing container MImagePar. Added possibility to set the
+       source position on the camera (for the wobble mode).
+
+
+
+ 2005/01/25 Abelardo Moralejo
+
+   * macros/starmc2.C
+     - modified to allow double (train / test) output, for g/h 
+       separation studies. Added several missing containers to output.
+
+
+
+ 2005/01/25 Thomas Bretz
+
+   * mcalib/MCalibrationIntensityChargeCam.cc:
+     - fixed a lot of 'default argument'-warnings to make to code
+       compile
+
+   * mbase/MParContainer.[h,cc]:
+     - moved the empty Reset() function into the source file and
+       added a lot of comments
+     - implemented new helper-functions: GetNewObject
+
+   * mbase/MContinue.[h,cc]:
+     - allow to use MFilter-classes as filter in ReadEnv
+
+   * mbase/MTaskEnv.cc:
+     - replaced some code by GetNewObject
+
+   * mhbase/MFillH.cc:
+     - handle DrawOption "same" to be able to draw to the same pad
+
+   * mhbase/MH.[h,cc]:
+     - added same-argument to DrawSame
+
+   * mhbase/MH3.cc:
+     - removed some obsolete comments
+     - remove own drawing options before calling fHist->Draw
+
+   * mimage/MHHillas.cc, mimage/MHImagePar.cc:
+     - first try of implementing 'same' drawing option
+
+
+
+ 2005/01/25 Markus Gaug
+
+   * mcalib/MCalibrationPattern.[h,cc]
+   * mcalib/MCalibrationPatternDecode.[h,cc]
+     - New Decoder task for the calibration pattern from the 
+       digital modules
+ 
+   * mraw/MRawEvtHeader.[h,cc]
+     - remove decoding from this class   
+
+   * mcalib/MCalibrationIntensityHiLoCam.[h,cc]
+     - remove, because one needs anyhow much more than one data file
+       to get a reasonable conversion factor
+
+   * mcalib/MCalibCalcFromPast.[h,cc]
+     - remove MCalibrationIntensityHiLoCam
+
+   * mbadpixels/MBadPixelsPix.h
+   * mbadpixels/MBadPixelsCam.cc
+     - changed one function name to GetUnsuitableCalLevel()
+
+   * mjobs/MJCalibration.cc
+     - replace all Y-titles with units "FADC counts" by "FADC cnts" and 
+       "FADC slices" by "FADC sl.", otherwise they range out of the 
+       canvas.
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - ensure to set the color correctly in MCalibrationBlindCam
+
+   * callisto.rc
+     - put space for 
+       MJCalibrateSignal.ExtractSignal.HiGainFirst:     2
+       MJCalibrateSignal.ExtractSignal.HiGainLast:     16
+
+
+ 2005/01/24 Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - Adapted to changes in MCalibrateData from 2005/01/16: moved 
+       qepix.SetAvNormFFactor(1.)  from Process() to ReInit(). Due to 
+       this, for the last week you may have found trouble running 
+       starmc.C and mccalibrate.C.
+
+
+
+ 2005/01/24 Thomas Bretz
+
+   * callisto.cc:
+     - removed non-existing option from output
+
+   * manalysis/MEnergyEstimate.[h,cc]:
+     - added ReadEnv member function
+
+   * mbase/MContinue.[h,cc]:
+     - implementes AllowEmpty option to support doing nothing 
+       defined in resource file
+     - added a first draft to allow usage of class-filters instead of 
+       rules
+
+   * mbase/MMath.[h,cc]:
+     - implemented a function suggested by Florian Goebel which reduces
+       the precision of a float to ~0.5% which is usefull for data
+       compression by gzip
+
+   * mdata/MDataChain.[h,cc]:
+     - implemented ReadEnv member function
+
+   * mfbase/MF.cc:
+     - a small enhancement to the output in ReadEnv
+
+   * mhbase/MH3.cc:
+     - fixed call to FindObject in Paint which caused a profile to be
+       displayed incorrectly in case it was read from a file
+
+   * mhflux/MHFalseSource.[h,cc]:
+     - removed old obsolete unsused Significance functions
+     - implemented ReadEnv member function
+     - set false source binning only if BinningFalseSource is not default
+     - check parlist for BinningAlpha
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJCalibration.cc, 
+     mjobs/MJPedestal.cc:
+     - added an additional check and output if output-file could
+       not be opened
+
+   * mjobs/MJob.h:
+     - added some Getter
+
+   * mhbase/MBinning.[h,cc].
+     - added nen member functions
+       + SetEdgesRaw
+       + ReadEnv
+       + Print
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added new member function ReadEnv
+
+   * mhflux/MHAlpha.cc:
+     - fixed a problem when fitting without off-data
+
+   * mbase/MStatusDisplay.cc:
+     - implemented a further fix in DrawClonePad to make sure
+       that the X-stuff doesn't get confused while still
+       GetDrawOption returns the correct value
+
+
+
+ 2005/01/24 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - introduced security check for the times fine-tuning to catch 
+       outliers because of deviating pulse forms.
+
+   * msignal/MExtractTime.cc
+   * msignal/MExtractor.cc
+     - lowered default high-gain saturation limit to 250
+     - removed Clear() for two results containers at beginning of Process()
+
+   * msignal/MExtractor.h
+     - Take fHiLoLast into the Clone()
+
+   * msignal/MExtractedSignalPix.cc
+     - change sign of default initializer to negative.
+
+
+
+ 2005/01/23 Markus Gaug
+  
+   * mhcalib/MHCalibrationHiLoCam.[h,cc]
+     - updated to new logain switch setting in MExtractTimeAndCharge
+     - extract also high-gain vs. low-gain time difference
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+     - updated reading of conf. values in ReadEnv
+
+   * mhcalib/MCalibrationHiLoCam.[h,cc]
+   * mhcalib/MCalibrationHiLoPix.[h,cc]
+   * mhcalib/MCalibrationIntensityHiLoCam.[h,cc]
+     - updated accordingly
+
+   * mbadpixels/MBadPixelsCam.cc
+     - removed some bugs in the Print() function
+
+
+
+ 2005/01/22 Markus Gaug
+
+   * mhcalib/MHCalibrationRelTimeCam.cc
+     - display in the averaged times display the event-by-event averaged
+       absolute arrival times instead of the rel. ones which do not make 
+       much sense.
+
+   * mhcalib/MHCalibrationTestTimeCam.[h,cc]
+   * mhcalib/MHCalibrationTestCam.[h,cc]
+     - update to the latest changes in analysis chain.
+
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - update to the latest changes in analysis chain.
+    
+   * mjobs/MJCalibration.cc
+     - replace title of that times-averageing Tab from "RelTimes" by 
+       "Times".
+
+   * macros/calibration.C
+     - update to changes in MJExtractCalibTest
+
+
+
+ 2005/01/21 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - use the max. bin content for low-gain extraction
+   
+   * callisto.rc
+     - add place for LoGainSwitch
+
+
+
+ 2005/01/21 Florian Goebel
+
+   * mfbase/MF.cc:
+     - include a (TString) cast to make it compilable with gcc2.95.3
+
+
+
+ 2005/01/21 Thomas Bretz
+
+   * mpointing/MSrcPosFromModel.cc:
+     - fixed crash in Process if no pointing model available
+
+   * mpointing/MPointingPosCalc.h:
+     - added missing initialization of data members
+
+   * mastro/MObservatory.[h,cc]:
+     - added ReadEnv member function
+
+   * mbase/MTaskEnv.h:
+     - added (=0) default to SetDefault
+
+
+
+ 2005/01/20 Markus Gaug
+
+   * mcalib/MCalibrationIntensityChargeCam.[h,cc] 
+     - added function to display fluctuations of a variable
+
+   * mcalib/MCalibrationPix.cc
+     - fixed small bug in High-gain mean error.
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - introduced high-gain maximum limit before extracting the low-gain
+
+
+
+ 2005/01/20 Thomas Bretz
+
+   * mbase/MContinue.[h,cc]:
+     - added ReadEnv member function to support resource files
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added a second arguemtn to reading of the resource file by name
+     - added some checks when reding the resource file and the
+       parameter list hasn't been setup
+
+   * mbase/MParList.cc:
+     - removed an obsolete output from ReadEnv
+
+   * mfbase/MF.[h,cc]:
+     - added ReadEnv member function to support resource files
+     - added kAllowEpty flag to support skipping by resource files
+
+   * mfbase/MFilterList.cc:
+     - added a comment
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - fixed Write to be compatible with root 4.02/00
+     - worked around a problem with reading the DrawOption correctly
+       from a stored status display
+
+
+
+ 2005/01/19 Thomas Bretz
+ 
+   * mbase/MMath.cc:
+     - added a comment to SignificanceLiMa, made by Daniel Mazin
+     - also check for b==0
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - fixed significance calculation in case of on-off data
+     - added fScaleFactor
+
+   * mhflux/MHAlpha.[h,cc], mhflux/MHFalseSource.cc:
+     - handle scale factor in case of on-off observations
+
+   * mjobs/MJPedestal.cc:
+     - aligned screen output to 80col rule
+
+   * mtrigger/MFTriggerPattern.[h,cc]:
+     - assigned correct integers to enum
+     - made sure that the enum is correctly handled in all function by
+       applying a r-value to the condition
+
+
+
+ 2005/01/19 Abelardo Moralejo
+
+   * mtrigger/MFTriggerPattern.[cc,h]
+     - Changed Bool_t arguments of all setters to new type Prescale_t
+       defined by N. Galante (see below)
+
+
+
+ 2005/01/19 Nicola Galante
+
+   * mtrigger/MFTriggerPattern.[cc,h]
+     - added in header enum Prescale_t { kUnPrescaled = kFALSE, 
+       kPrescaled   = kTRUE }; 
+
+     - fixed a bug in Process, both fMaskRequiredUnprescaled and
+       fMaskRequiredPrescaled are checked simultaneously.
+
+
+
+ 2005/01/18 Markus Gaug
+
+   * mcalib/MCalibColorSet.cc
+     - fixed the remaining day of data without colour in project name
+       neither in digital modules bits.
+
+   * mpedestal/MPedCalcPedRun.[h,cc] 
+     - catch the continuous light runs with MRawRunHeader::fRunType 
+       == kRTCalibration to be recognized as effective pedestal runs.
+
+
+ 2005/01/18 Thomas Bretz
+
+   * mbase/MMath.cc:
+     - added a check for s==0 in SignificanceLiMa, because otherwise the 
+       result is NaN
+
+   * mfbase/MF.cc:
+     - removed an obsolete debugging output from the latest changes
+
+   * mhflux/MHAlpha.cc:
+     - reset fHTime, too
+
+
+
+ 2005/01/18 Nicola Galante
+
+   * mtrigger/MFTriggerPattern.cc:
+     - added parentesis to ensure bitwise operators priority
+       with respect to logical operators.
+
+
+ 2005/01/17 Thomas Bretz
+ 
+   * manalysis/MEnergyEstimate.[h,cc]:
+     - changed to be more general. Energy is now estimated from a rule
+       (MDataChain) The default behaviour is still the same as before
+       to copy the energy from MMcEvt
+
+   * mbase/MTask.cc:
+     - changed to write out the descriptor istead of the task-name only
+       in Pre/PostProcess
+
+   * mhbase/MH.cc:
+     - initialize fSerialNumber and fNumExecutions in constructor
+
+   * mhflux/MHFalseSource.cc:
+     - according to a suggestion by Markus Mayer I have changed
+       \\sigma_{max}=f to S_{max}=f\\sigma
+
+   * mjobs/MJCalibrateSignal.cc:
+     - as discussed with Markus and Abelardo fixed the MFTriggerPattern
+       call.
+
+   * mtrigger/MFTriggerPattern.cc, mtrigger/MTriggerPattern.cc,
+     mtrigger/MTriggerPatternDecode.cc:
+     - added some comment about file version
+
+   * mbase/MFilter.h:
+     - implemented new virtual function GetDataMember like in MData
+
+   * mbase/MTask.[h,cc]:
+     - when filter is added ass GetDataMember to branch list (should be
+       obsolete, because filter is in the tasklist, but it should not hurt)
+
+   * mfbase/MF.[h,cc], mfbase/MFDataChain.[h,cc], mfbase/MFDataMember.[h,cc],
+     mfbase/MFilterList.[h,cc]:
+     - implemented new function GetDataMember
+
+
+
+ 2005/01/17 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - remove a situation where the high-gain signal can be 0.
+
+   * mtrigger/MTriggerPattern.h
+     - fixed a bug in defining the trigger bit pattern (Have to start
+       from 0 instead of 1)
+
+   * mjobs/MJPedestal.cc
+   * mjobs/MJCalibrateSignal.cc
+     - fixed default extraction ranges.
+
+   * callisto.rc
+     - fixed default weights files for pedestal extraction for cosmcis
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - removed program exit on occurrance of multiple colours without 
+       intensity calibration
+
+
+
+ 2005/01/17 Nadia Tonello and Markus Gaug
+
+   * mcalib/MCalibrationChargeCam.cc
+     - some fit improvements in the function GetAveragedConvFADC2PhotPerArea
+
+
+
+ 2005/01/16 Markus Gaug
+
+   * mhcalib/MHCalibrationCam.[h,cc], mhcalib/MHCalibrationRelTimeCam.[h,cc],
+     mhcalib/MHCalibrationChargeCam.[h,cc]
+     - put overflow management and results camera initialization into 
+       base class
+ 
+   * mcalib/MCalibrateData.[h,cc]
+     - added possibility to re-normalize signal to equiv. photo-electrons
+       ( SetSignalType(MCalibrateData::kPhe) ). 
+       Default is old version in photons
+     - speed up Process by storing pre-calculated calibration constants
+       in arrays (needed 40% of CPU time of the eventloop before, now: 23%) 
+     - added new pointer to different MCalibrationChargeCam used for 
+       updates
+     - added possibility to update the conversion factors using the 
+       MCalibrationChargeCam stored in fCalibUpdate. 
+     - added Print() function
+
+   * mcalib/MCalibCalcFromPast.[h,cc]
+     - committed final version, now also in the Makefile
+
+   * mjobs/MJCalibrateSignalFromOutside.[h,cc], macros/calibration.C
+     - committed final version, now able to calibrate interlaced cal. 
+       events.
+
+
+
+ 2005/01/14 Hendrik Bartko
+
+   * msignal/calibration_weights_UV.dat
+     - fixed a small bug in the noise autocorrelation of the AB-noise
+
+   * msignal/calibration_weights_blue.dat	
+     - new weights file for blue calibration pulses
+
+   * cosmics_weights.dat
+     - fixed a small bug in the noise autocorrelation of the AB-noise
+
+
+
+ 2005/01/14 Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - added a small acceleration of the program, tested by Hendrik and
+       me.
+
+   * mpedestal/MPedCalcFromLoGain.cc
+     - fixed one warning output which was not a real warning.
+
+   * mcalib/MCalibrationChargeCam.cc
+     - improved the function to calculate a mean conversion factor over 
+       the whole camera including a fit to the values.
+
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - undo some changes introduced by TB on 2/12/04 which had made the 
+       use of interlaced pedestal events impossible again. 
+     - Use now the new class MTriggerPattern directly to recognize an 
+       interlaced pedestal event.     
+
+
+
+ 2005/01/14 Thomas Bretz
+ 
+   * callisto.cc:
+     - fixed a typo in output
+
+   * manalysis/MGeomApply.cc:
+     - removed some old code already in comments
+     - added possibility to switch off automatic processing (used
+       if two different geometries around)
+
+   * manalysis/MMultiDimDistCalc.cc, mhbase/MHMatrix.[h,cc],
+     mranforest/MRanForestCalc.cc, mtools/MHSimulatedAnnealing.[h,cc],
+     mtools/MSimulatedAnnealing.h:
+     - added include of TVector because in newer root version it is 
+       not included from TMatrix anymore
+
+   * mbase/BaseLinkDef.h, mbase/MMath.[h,cc]:
+     - to stick to the convention of TMath in newer root versions MMath
+       changed from a class to a namespace
+
+   * mbase/MEvtLoop.[h,cc]:
+     - to support newer root version added a second Write-function
+       with a const qualifier.
+
+   * mdata/MDataChain.cc:
+     - changed access to TMath for newer root versions
+
+   * mfileio/MChain.[h,cc]:
+     - implemented a workaround for teh changed LoadTree definition
+       in newer root-versions
+
+   * mfileio/MReadTree.cc:
+     - fixed a bug in CheckBranchSize caused some warning to be
+       displayed
+
+   * mhflux/MHAlpha.cc:
+     - removed check for fResult in PostProcess (it is always there)
+
+   * msignal/MExtractTimeFastSpline.cc:
+     - fixed delete --> delete[]
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - slight change to some output
+
+   * mbase/MTaskEnv.h:
+     - set name of default task when pointer is given
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed handling of extraction range for various cases
+     - fixed handling in case no arrival times are calculated
+
+   * mjobs/MJCalibration.cc:
+     - write at least a default arrival time calibration container
+       to make further processing easier
+
+   * mjobs/MJPedestal.[h,cc]:
+     - fixed handling of extraction range for various cases
+
+
+
+ 2005/01/14 Abelardo Moralejo
+
+   * mtemp/mpadova/macros/trainsubsample.C, RanForestDISP.C
+     - added. Two macros used in the analysis of real wobble mode data.
+
+
+
+ 2005/01/14 Daniela Dorner
+
+   * macros/sql/filldotrun.C
+     - added new arehucas-verions and changed code accordingly
+
+
+
+ 2005/01/13 Abelardo Moralejo
+
+   * macros/starmc.C
+     - Added (commented) lines for the case of gamma MC source off-axis 
+       (wobble mode). Changed default extractor to 
+       MExtractFixedWindowPeakSearch.
+
+
+
+ 2005/01/13 Raquel de los Reyes
+
+   * callisto.rc
+     - introduced several configuration lines 
+       (format: "class".DataCheck: No) to allow callisto 
+       to run with rawfiles. Necessary for the datacheck.
+
+
+
+ 2005/01/13 Markus Gaug
+
+   * mcalib/MCalibColorSet.cc
+     - fixed runs 45605-45609
+
+   * msignal/MExtractor.h
+     - take out the variable fHiLoLast from the streamer. Will be 
+       initialized in the ReInit(), if needed
+
+   * msignal/MExtractor.cc
+     - Initialized fHiLoLast to 0. Otherwise, a second eventloop with 
+       the same extractor may have that variable set to a certain 
+       value, even if not desired. The ReInit() fixes fHiLoLast, if 
+       different from 0.
+
+   * mpedestal/MExtractPedestal.cc
+   * mpedestal/MPedCalcPedRun.cc
+   * mpedestal/MPedCalcFromLoGain.cc
+     - fix the output of the print to the correct value for the case 
+       that the extractor is used.
+
+
+ 2005/01/13 Thomas Bretz
+
+   * callisto.rc:
+     - fixed some typos
+
+   * mbase/MLog.cc:
+     - unset DEBUG defined unintentionally
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - removed printing Weights in InitArrays, because otherwise
+       the output of a full data calibration is totally crowded
+       with numbers. Having the weights-file name on the display
+       is perfectly enough.
+
+
+
+ 2005/01/12 Markus Gaug
+
+   * mcalib/MCalibrationIntensityRelTimeCam.cc
+     - added fit to improve averageing of the obtained results
+
+
+
+ 2005/01/12 Thomas Bretz
+
+   * manalysis/MMatrixLoop.cc:
+     - changed name to MRead because it now derives from MRead
+
+   * mbase/MEvtLoop.[h,cc]:
+     - implemented an option not to cascade the status display to the
+       parameter list in PreProcess
+
+   * mhflux/MHAlpha.cc:
+     - changed name of "Significance" to "MinimizationValue"
+     - return -significance to have a value being minimized
+
+   * mhist/MHCamera.cc:
+     - fixed output of text in legend
+
+   * mhist/MHEvent.[h,cc]:
+     - implemented new options for calibrated pedestals
+
+   * mmain/MEventDisplay.cc:
+     - fixed to support latest changes in MJCalibrateSignal
+
+   * mpedestal/MPedPhotCam.cc:
+     - added new options in GetPixelContent (4 and 5) to support
+       a correct camera display
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed display of calibrated pedestal and pedestal rms
+     - changed order of plots. Now all interpolated values 
+       (means all calibrated values which are bad-pixel treated)
+       are displayed behind the unsuitable pixels.
+
+   * mjobs/MJ*.cc:
+     - corrected all wrong %06d to %08d to fit the number of
+       digits in run-numbers
+
+
+
+ 2005/01/11 Abelardo Moralejo
+
+   * mjobs/Makefile
+     - added missing include -I ../mtrigger
+
+
+
+ 2005/01/11 Thomas Bretz
+
+   * callisto.cc, callisto.rc:
+     - changed such, that all three kinds of pedestals are calcualted 
+       (usefull for studies)
+
+   * manalysis/MMatrixLoop.[h,cc]:
+     - derived from MRead
+     - implemented some basic functions from MRead
+
+   * mfilter/MFCosmics.[h,cc]:
+     - allow setting of name of MPedestalCam
+
+   * mhbase/MBinning.[h,cc]:
+     - added SetEdges taking MParList as input
+
+   * mhflux/MHAlpha.cc:
+     - use new function from MBinning
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - changed to calculate all three kinds of pedestals
+     - added filters for trigger pattern and illuminated events
+
+   * mjobs/MJPedestal.cc:
+     - give different names to tabs with different pedestals
+
+   * mjobs/MJStar.cc:
+     - on request changed used pedestal from "FromExtractor" to
+       "FromExtractorRndm"
+
+   * mtrigger/MTriggerPattern.h:
+     - added Reset function
+
+   * mtrigger/MTriggerPatternDecode.[h,cc]:
+     - added using file format version number
+
+
+
+ 2005/01/11 Markus Gaug
+
+   * mbadpixels/MBadPixelsPix.cc
+     - updated documentation
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - make pixels with deviating number of phes unreliable instead of 
+       unsuitable (this was already thought so, but missed to modify
+       at one place).
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+     - add possible flag 'kInterlaced': default: kFALSE (like before)
+     - added pointer to MRawEvtHeader to deny cosmics events in case
+       of 'interlaced' flag is set. No changes for 'normal' calibration
+
+
+
+ 2005/01/10 Benjamin Riegel
+ 
+   * mreport/MReportStarguider.cc, mreport/MReportStarguider.h
+     - added two classes for implementing starguider-data 
+ 
+   * mreport/ReportLinkDef.h
+     - added class MReportStarguider to be linked:
+       #pragma link C++ class MReportStarguider+;
+     
+   * mreport/Makefile
+     - added file MReportStarguider.cc
+   
+   * merpp.cc
+     - added two containers ( MReportStarguider, MTimeStarguider ) and
+       added MReportStarguider to the list:
+       w->AddContainer("MReportStarguider",  "Starguider");
+       w->AddContainer("MTimeStarguider",    "Starguider");
+       r->AddToList("MReportStarguider");
+       
+       
+       
+ 2005/01/10 Markus Gaug
+
+   * mcalib/MCalibColorSet.cc
+     - return kFALSE for CL-run instead of kTRUE
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - stop program in case that multiple colours are found in same file
+       without intensity calibration
+
+   * mbadpixels/MBadPixelsPix.h
+     - added two new possible UnCalibrated_t flags for the hi-lo 
+       calibration
+
+   * macros/calibration.C
+     - add the calls to:
+	  MArray::Class()->IgnoreTObjectStreamer();
+	  MParContainer::Class()->IgnoreTObjectStreamer();
+       in main.
+
+   * msignal/MExtractor.h
+     - added Getter for fOffsetLoGain (was still missing)
+
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+     - remove pixels with histogram overflow only if their percentage 
+       passes a certain limit (default: 0.5%). Before, every overflow 
+       lead to an unsuitable pixel.
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - implemented changes suggested by T.B. to speed up calculations
+     - take fNameWeightsFile into the streamer, otherwise the Clone() 
+       will always create an extractor with cosmic's weights. 
+     - set fOffsetLoGain to a slighly higher value. The DF seems to 
+       have a different offset since it uses different pulse shapes 
+       and thus sightly different time definitions.
+
+
+
+ 2005/01/10 Thomas Bretz
+
+   * mhvstime/MHVsTime.cc:
+     - fixed a compiler error for gcc 2.95.3, see Mantis bug # 157
+
+   * callisto.cc:
+     - changed such, that the calculated pedestal is not random
+       anymore
+     - added code to calculate the pedestal also with randomization,
+       but this code is for the moment commented out.
+
+   * callisto.rc:
+     - fixed naming of pedestal calculation
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - added a second check which compares the pedestal rms with
+       the variance of the pedestal rms in the same sector
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - changed to calculate the pedestal from extractor without 
+       randomization
+     - added code to calculate the pedestal also with randomization,
+       but this code is for the moment commented out.
+
+   * mjobs/MJCalibration.cc:
+     - made sure that pedcam always has the correct name
+       (FIXME? Print a warning if it has the wrong name)
+
+   * mjobs/MJPedestal.[h,cc]:
+     - changed such, that it allows the calculation of pedestals
+       in three different ways (fundamental, fromextractor, 
+       fromextractorrndm)
+     - therefor removed SetExtractorResolution and added
+       + void SetExtractionFundamental()
+       + void SetExtractionWithExtractorRndm()
+       + void SetExtractionWithExtractor()
+
+   * mjobs/MJStar.cc:
+     - changed/fixed the input name of the MPedPhotCam used in the
+       image cleaning
+
+   * mraw/MRawFileRead.[h,cc]:
+     - changed return type of OpenNextFile
+     - in some cases return kERROR in OpenNextFile to abort the Processing
+       with an error
+
+   * mraw/MRawRunHeader.cc:
+     - call a wrong file format version ERROR now
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - make sure that resetted values are returned if fit failed
+     - set default scaling too kOffRegion
+
+   * mhflux/MHAlpha.cc:
+     - some small fixes to handling of MHAlphaOff
+
+   * mhflux/MHFalseSource.[h,cc]:
+     - implemented possible usage of MHFalsSourceOff for On-Off-Analysis
+     - updated display accordingly
+     - updated fit accordingly
+     - removed catalog temporarily from plots until I found the
+       reason for the strange crashes
+
+   * mbadpixels/MBadPixelCalc.[h,cc]:
+     - implemented the possibility to check the pedestal rms against the
+       variance of the pedstal rms, too. The option is curretly switched
+       off.
+     - enahanced informal output in PreProcess
+
+   * mbase/MTaskList.cc:
+     - a little change to some output
+
+
+
+ 2005/01/10 Wolfgang Wittek
+
+   * mfbase/MFEventSelector2.cc
+     - check whether filter exists before calling 
+       filter->CallPreProcess(parlist)
+
+
+
+ 2005/01/08 Markus Gaug
+
+   * mhcalib/MHCalibrationHiLoCam.[h,cc]
+   * mcalib/MCalibrationHiLoCam.[h,cc]
+   * mcalib/MCalibrationHiLoPix.[h,cc]
+   * mcalib/MIntensityCalibrationHiLoCam.[h,cc]
+   * mhcalib/Makefile, mcalib/Makefile, mhcalib/HCalibLinkDef.h, 
+     mcalib/CalibLinkDef.h
+     - new classes for calibration of conversion high-gain vs. low-gain 
+
+   * msignal/MExtractedSignalPix.[h,cc]
+     - added data member fChisquare, set to -1. by Clear() and Reset()
+     - raised version number by 1
+
+   * msignal/MExtractedSignalCam.[h,cc]
+     - added data member fNdf, set to -1 by default
+     - new function: GetProb(const Int_t pixidx) to be called to 
+       calculate the joint probability of Chisquare of pixel "pixidx"
+       and fNdf
+     - added documentation of data members
+     - raised version number by 1
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - strengthened default histogram limits a bit, should accelerate
+       the calibration by 20%.
+
+   * mjobs/MJCalibrateSignalFromOutside.cc
+     - fixed two lines to compile MCalibrateData with the recent changes
+       by TB
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - fixed two bugs introduced yesterday by TB.
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - adopt part of TB's speed accelerations into these classes
+
+   * msignal/MExtractTimeAndCharge.cc
+     - fix the low-gain extraction window for the case that the high-gain
+       is saturated. Was skipped so far.
+
+
+
+ 2005/01/07 Markus Gaug
+
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - catch the case that more than 90% of the pixels have saturated 
+       signals and fix the extraction window from the occurrance of 
+       saturation, then. Important for high-intensity calibration events.
+
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractTime.cc
+   * msignal/MExtractTimeAndCharge.cc
+     - added some documentation
+
+   * msignal/MExtractTime.[h,cc]  
+     - moved the empty function FindTimeHiGain() and FindTimeLoGain() to
+       the header-file.
+      
+
+
+
+ 2005/01/07 Abelardo Moralejo
+
+   * mbase/MLog.h
+     - Added #include "TSystem.h", otherwise gSystem is not recognized
+       in Mac OSX.
+
+   * manalysis/MMakePadHistograms.cc
+     - Changed badcalc.SetNamePedPhotContainer to 
+       badcalc.SetNamePedPhotCam
+
+
+
+ 2005/01/07 Thomas Bretz
+
+   * mbadpixels/MBadPixelsCalc.[h,cc], macros/ONOFFAnalaysis.C:
+     - replaced PedPhotContainer by PedPhotCam for consistency
+   
+   * mbase/MLog.[h,cc]:
+     - return *this in Seperator()
+
+   * mbase/MPrint.[h,cc]:
+     - use new separator manipulator in PreProcess
+     - fixed a type: separator instead of seperator
+
+   * mfileio/MReadTree.[h,cc]:
+     - added a check for branch->IsAutoDelete() in Notify()
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - added new option 'fRandomCalculation' be used to switch on-/off-
+       randomization in extractors, the default should be like before
+     - added Process() calling Calc()
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc], mpedestal/MPedCalcPedRun.[h,cc]:
+     - renamed Process() to Calc()
+
+   * Makefile:
+     - removed macros/calibration.C, which seems to have been
+       unintantionally introduced.
+
+   * manalysis/Makefile:
+     - removed unintantionally introduced wrong include
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - a small acceleration discussed with Hendrik by replacing a
+       counter in a loop by pointer arithmetics
+
+   * mraw/MRawEvtPixelIter.cc:
+     - fixed a bug in GetMaxIdxHiLoGain which caused the loop to
+       read one byte behind the end of the array
+     - fixed HasLoGain() which really did weired things, means accessing
+       sometimes memory somewhere. This could theoretically result
+       in assigning the wrong lo-gains to the wrong pixels.
+
+   * mtrigger/MTriggerPattern.[h,cc], mtrigger/MTriggerPatternDecode.[h,cc],
+     mtrigger/MFTriggerPattern.[h,cc]:
+     - added
+
+   * mtrigger/Makefile, mtrigger/TriggerLinkDef.h:
+     - added MTriggerPattern, MTriggerPatternDecode and MFTriggerPattern
+
+   * manalysis/MEnergyEstParam.h:
+     - added a new function SetVariables calling SetCoeff
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - removed data members for container names
+     - added new lists for container names
+     - allow to calibrate more than one pedestal container at the same
+       time
+
+   * mjobs/MJCalibrateSignal.cc:
+     - changed accordingly
+
+
+
+ 2005/01/05 Thomas Bretz
+
+   * mcalib/MCalibrationBlindPix.cc, mcalib/MCalibrationChargeCalc.cc,
+     mhcalib/MHCalibrationRelTimeCam.cc:
+     - made some output lines fit into convinience window of 80 col
+
+   * mhist/MHCamEvent.cc:
+     - make sure that x-axis has correct title
+
+   * msignal/MArrivalTimePix.cc:
+     - init error to -1 which is a obviously non valid value
+     - fixed IsValid() which gave wrong results
+
+   * msignal/MExtractTimeAndCharge.cc, msignal/MExtractedSignalPix.cc:
+     - made sure that LoGain is flagged non-valid if no lo-gain exists
+     - push time back at the edge of the allowed limits if outside
+
+   * mbase/MGList.[h,cc]:
+     - introduced new functions Delete and DeletePictures
+     - SetBit(kMustCleanup) in constructor. Otherwise it is not
+       correctly removed from ListOfCleanups
+
+   * mbase/MLog.cc:
+     - SetBit(kMustCleanup) if adding a plugin to make sure it is cleaned
+       from the list
+
+   * mbase/MParContainer.[h,cc]:
+     - replaced return type of GetDescriptor by TString. The old version
+       was terribly wrong! The returned memory wasn't removed as soon
+       as the function returned.
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - for security (thread safty) replaced all Form() by MString::Form()
+     - implemented a more secure scheme of Closing (Clone()) this was
+       a hint given by valgrind
+     - set kMustCleanup for all new object in ClonePad not only kCanDelete
+     - fixed some lines in pulldown-menus
+     - add TPads to ListOfCleanups in ClonePad (workaround!)
+
+   * mbase/MString.[h,cc]:
+     - implemented a new static Form() function returning a copy of
+       the result
+
+   * mbase/MTask.[h,cc]:
+     - replaced return type of GetDescriptor by TString. The old version
+       was terribly wrong! The returned memory wasn't removed as soon
+       as the function returned. 
+     - Made GetDescriptor thread safe using MString::Form
+
+   * mfileio/MWriteRootFile.cc:
+     - Use GetDescriptor().Data() when using any kind of printf function
+
+   * mhbase/MFillH.cc:
+     - replaced string concatenation in all constructors by a Form 
+       (also suggested by valgrind)
+
+   * mhcalib/MHCalibrationRelTimeCam.cc:
+     - made some output fit into 80col boundary
+
+
+
+
+ 2005/01/03 Thomas Bretz (HAPPY NEW YEAR)
+
+   * mfht:
+     - added new directory for hexagonal fourier transformation
+
+   * mfht/HftIncl.h, mhft/HftLinkDef.h, mhft/MGeomCamMagicXT.[h,cc],
+     mhft/MGeomCamMagicEnhance.[h,cc], mhft/MHexgaonalFT.[h,cc], 
+     mhft/MHexagonalFreqSpace.[h,cc], mhft/MHexagonalFTCalc.[h,cc],
+     mhft/Makefile:
+     - added
+
+   * macros/extendcam.C: 
+     - added: tutorial for MGeomCamExtend
+
+   * macros/hft.C: 
+     - added: tutorial for MHexgonalFTCalc
+
+   * macros/dohtml.C: 
+     - updated
+
+   * macros/rootlogon.C: 
+     - updated
+
+   * Makefile:
+     - mhft added
+
+   * mbase/MParContainer.cc, mbase/MLog.cc:
+     - added a pre-compiler option for destructor debugging
+
+   * mbase/MTaskList.[h,cc]:
+     - added new function Replace
+
+   * mdata/MDataChain.cc, mfbase/MF.cc:
+     - shortened some output
+
+   * mdata/MDataArray.[h,cc]:
+     - added new function FindRule
+
+   * mfileio/MReadTree.[h,cc]:
+     - enhanced functionality to be able to read a TTree stored in memory
+       instead of a file. Therefor introduced fTree which is now the pointer
+       used and replaced fChain where TTree and TChain have common behaviour.
+       Where they behave uncommon new code for the new case has been added.
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - enhanced functionality to be able to write a TTree into memory
+       instead of a file. This were maily bugfixes for the case fOut==0, which
+       must be handled correctly. Becarefull a tree filles without a file
+       is not deleted automatically!
+    
+   * mhbase/MBinning.h:
+     - added copy constructor
+     - fixed buggy SetEdges(MBinning&) which didn't work
+
+   * mhbase/MHMatrix.cc:
+     - when adding a new rule check first if the same rule already exists
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added new functionality to support on-off analysis
+     - didn't touch existing code
+
+   * mhflux/MHAlpha.[h,cc]:
+     - added new functionality to support on-off analysis
+     - replaced Fit() calls by newer function calls
+     - added DrawAll - PRELIMINARY
+     - fixed a bug when projecting - may be the reson for some strange
+       crashes
+
+   * mcalib/MCalibColorSet.cc:
+     - fixed a stupid bug introduced last year, which caused MCalibColorSet
+       in some circumstances to stop the eventloop when it shouldn't
+
+   * mjobs/MSequence.cc:
+     - expand path names
+ 
Index: /tags/Mars-V0.9/Changelog.02
===================================================================
--- /tags/Mars-V0.9/Changelog.02	(revision 9772)
+++ /tags/Mars-V0.9/Changelog.02	(revision 9772)
@@ -0,0 +1,5677 @@
+                                                 -*-*- END OF LINE -*-*-
+
+ 2002/12/13: Abelardo Moralejo
+
+    * manalysis/MSigmabar.cc
+      - added cast in first arguments in calls to TMath::Min and
+        TMath::Max otherwise, we got a compilation error in Alpha
+        machines.
+
+
+
+ 2002/12/13: Oscar blanch
+
+    * mgeom/MGeomMirror.[h,cc]
+      - function SetMirrorDeviations added
+
+
+
+ 2002/12/09: Robert Wagner
+
+    * manalysis/MSigmabar.[cc,h]:
+      - added
+
+    * manalysis/MSigmabarCalc.[cc,h]:
+      - added
+
+    * manalysis/MSigmabarParam.[cc,h]:
+      - added
+      - preliminary version for CT1 test
+
+    * manalysis/MApplyPadding.[cc,h]:
+      - added
+
+    * mhist/MHSigmabarTheta.[cc,h]:
+      - added
+
+    * mhist/MHSigmabarPixel.[cc,h]:
+      - added
+      - preliminary version for CT1 test
+
+    * mtemp/MObservatoryLocation.[cc,h]:
+      - added
+
+    * mtemp/MVPObject.[cc,h]:
+      - added
+
+    * mtemp/MVPPlotter.[cc,h]:
+      - added
+
+    * mtemp/MVPTime.[cc,h]:
+      - added
+	
+    * mtemp/TempIncl.h, mtemp/TempLinkDef.h, mtemp/Makefile:
+      - added above mentioned classes
+
+    * mhist/HistLinkDef.h, mhist/Histfile:
+      - added above mentioned classes
+
+    * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+      - added above mentioned classes
+
+
+
+ 2002/11/25: Thomas Bretz
+
+   * mgui/MCamDisplay.cc:
+     - fixed a bug when sprintf the pointer to the char-array, only
+       took place on alphas.
+
+   * macros/multidimdist2.C:
+     - renamed eventloops (instances had same names)
+     - fixed a type in PrintStatistics (the gamma statistics
+       were printed two times)
+
+   * mbase/MEvtLoop.cc:
+     - take the lowest value (entries from MRead or user input)
+       for the progress bar
+     - reset the progress bar
+
+   * mbase/MFilter.h:
+     - added 'private'
+
+   * meventdisp/MGCamDisplay.[h,cc], meventdisp/MGEvtDisplay.[h,cc],
+     meventdisp/MGFadcDisp.[h,cc], mmain/MMonteCarlo.[h,cc],
+     mmain/MAnalysis.[h,cc], mmain/MBrowser.[h,cc], 
+     mmain/MCameraDisplay.[h,cc], mmain/MDataCheck.[h,cc],
+     mmain/MEvtDisp.[h,cc], mmain/MMars.cc:
+     - changed from TTransientFrame to TMainFrame (with this I
+       get decorations, eg. Close Button)
+
+   * meventdisp/MGEvtDisplay.cc:
+     - Update the layout each time the fEvtInfo has changed
+
+   * mfileio/MCT1ReadAscii.cc, mfileio/MCT1ReadPreProc.cc:
+     - delete return of gSystem->ExpandPathName
+
+   * mfileio/MCT1ReadPreProc.[h,cc]:
+     - added output of Time
+     - added usage of Selector
+     - changed MTask basics to be private
+
+   * mfileio/MRead.[h,cc]:
+     - added comment about selector
+     - added Selector-stuff
+
+   * mfileio/MReadMarsFile.[h,cc], mfileio/MReadTree.[h,cc]:
+     - added 'entries' argument to AddFile
+
+   * mfileio/MReadTree.[h,cc]:
+     - added workaround for a root bug when a file doesn't exist
+     - changed AddFiles to use Add(TChain*)
+     - changed to use Selector
+
+   * mfilter/MF.cc:
+     - Set debug level to suppress output when MFDataChain is created
+
+   * mfilter/MFEventSelector.h:
+     - changed Pre//PostProcess to private
+     
+   * mfilter/MF.cc, mfilter/MFilterList.cc:
+     - changed the use of Pre//PostProcess to CallPre//PostProcess
+   
+   * mhist/MBinning.[h,cc]:
+     - changed comments
+     - added SetEdgesCos
+
+   * mhist/MFillH.[h,cc]:
+     - added GetBinCenterLog
+
+   * mhist/MH3.h:
+     - added default argument to GetHistByName
+
+   * mhist/MHAlphaEnergyTheta.[h,cc], mhist/MHAlphaEnergyTime.h,
+     mhist/MHEffOnTime.[h,cc], mhist/MHEffOnTimeTheta.h,
+     mhist/MHEffOnTimeTime.h, mhist/MHFlux.[h,cc], mhist/MHGamma.[h,cc],
+     mhist/MHMcEnergyMigration.h, mhist/MHThetabarTheta.[h,cc],
+     mhist/MHThetabarTime.h:
+     - changed the output
+     - changed the algorithms to be more modular (more usage of member
+       function)
+     - changed ClassDef to 0
+     - fixed some small bugs (access of TArray[n])
+
+   * mhist/MHHadronness.[h,cc]:
+     - removed shortest distance to (0,1) stuff
+
+   * mhist/MHMcCollectionArea.h:
+     - changed Fill to Double_t
+
+   * mhist/MHTimeDiffTheta.[h,cc], mhist/MHTimeDiffTime.[h,cc]:
+     - in a first draft changed to use 200ns timing of CT1
+     - changed ClassDef to 0
+
+
+
+ 2002/11/22: Thomas Bretz
+
+   * macros/threshold.C:
+     - Simplified the new writing routine
+
+   * mbase/MLog.h:
+     - added a Getter-function for the debug level
+
+   * mbase/MTaskList.cc: 
+     - added another debugging output
+
+   * mfilter/MF.[h,cc]:
+     - made the automatically created chain names unique
+
+   * mfilter/MFDataChain.cc:
+     - corrected the GetRule stuff ({} were missing)
+
+   * mhist/MH3.cc:
+     - added MBinning as class type to FindObject
+     - added BinningHist (without the X) as binning name for a 1D histogram
+
+   * mfileio/MReadMarsFile.cc:
+     - corrected typo
+
+   * mfileio/MCT1ReadPreProc.cc:
+     - fixed a warning
+
+
+
+ 2002/11/22: Abelardo Moralejo
+
+   * macros/threshold.C:
+     - Added 2nd argument to write an output file containing the 
+       energy spectrum histogram.
+
+
+
+ 2002/11/21: Thomas Bretz
+
+   * mbase/MAGIC.h, mbase/MEvtLoop.[h,cc], MTask.cc, MTaskList.cc:
+     - introduced kERROR to stop an eventloop with an error
+
+   * mbase/MTask.h:
+     - made SetFilter virtual
+
+   * mbase/MTaskList.[h,cc]:
+     - added new member function AddToListBefore/After
+     - split the code of the AddToList function into CheckAddToList
+
+   * manalysis/MMultiDimDistCalc.cc:
+     - introduced usage of kERROR in case the matrix is not posdef.
+
+   * macros/collarea.C:
+     - some simplifications
+
+   * mhist/MHMcRate.h, mhist/MHMcIntRate.h, mhist/MHEnergyTime.h,
+     mhist/MHEnergyTheta.h, mfileio/MCTReadPreProc.cc, mfileio/MChain.h,
+     mfileio/MReadMarsFile.h, mfileio/MReadTree.cc, mfileio/MWriteAsciiFile.h,
+     mfileio/MWriteRoootFile.[h,cc], manalysis/MMatrixLoop.h, 
+     manalysis/MEnergyEstimate.h, mbase/MGGroupFrame.h, mbase/MGTask.h,
+     mfilter/MFParticleId.h:
+     - updated documentation
+
+   * mfileio/MCT1ReadPreProc.cc:
+     - Changed MSrcPosCam name from Source to MSrcPosCam
+     - changed the way the MC data is filled into the MC container
+     - updated algorithm to read preproc files
+
+   * mfileio/MReadMarsFile.cc:
+     - printed a warning to the screen in case Camera=V0.5
+
+   * mfileio/structures.h:
+     - changed to version 0.6
+
+   * mmc/MMcEvt.hxx:
+     - added GetTelescopePhi
+     - added GetTelescopeTheta
+
+   * mdata/MDataChain.[h,cc]:
+     - added 'sqr'
+
+   * mfilter/MF.[h,cc]:
+     - added support for MFDataChain
+
+   * mfilter/MFDataChain.[h,cc]:
+     - added
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - added MFDataChain
+
+
+
+ 2002/11/20: Thomas Bretz
+
+   * macros/dohtml.C:
+     - fixed a typo
+
+   * mmain/MAnalysis.cc:
+     - removed the Anti-Source from the hillas calculation
+
+   * mhist/MHFadcPix.[h,cc], mhist/MHFadcCam.[h,cc],
+     mmain/MDataCheck.[h,cc]:
+     - added enhancement for displaying sum of FADC slices
+
+
+
+ 2002/11/20: Abelardo Moralejo
+
+   * macros/collarea.C:
+     - Introduced check before opening output file to avoid annoying 
+       error message.
+
+
+
+ 2002/11/19: Abelardo Moralejo
+
+   * macros/collarea.C:
+     - Removed some strange pieces of text which somehow got into the
+       file (anyone knows how?)
+
+
+
+ 2002/11/19: Thomas Bretz
+
+   * mmain/MMonteCarlo.cc:
+     - exchanged MReadTree with MReadMarsFile for collection area calculation
+ 
+   * mmontecarlo/MMcCollectionAreaCalc.cc:
+     - fixed the uninitialized fTheta
+
+   * macros/MagicHillas.C:
+     - removed the unnecessary second MHillasSrcCalc
+     - removed also the corresponding AddToList for the tasklist
+
+   * mhist/MH.cc:
+     - make FindGoodLimits work
+
+
+
+ 2002/11/19: Abelardo Moralejo
+
+   * macros/collarea.C:
+     - Added 2nd argument to write an output file containing the 
+       collection area histogram.
+
+
+
+ 2002/11/18: Abelardo Moralejo
+
+   * mmain/MMars.cc:
+     - Corrected typo on Mars starting screen.
+
+   * mhist/MHMcCollectionArea.cc:
+     - Added comment.
+
+   * manalysis/MImgCleanStd.cc:
+     - implemented "democratic cleaning" (cut value proportional to square
+       root of pixel area) according to Wolfgang's suggestion.
+
+   * macros/MagicHillas.C:
+     - added missing declaration MHillasSrcCalc csrc2;
+
+   * mgeom/MGeomPix.cc:
+     - fixed some typos in comments
+
+
+
+ 2002/11/18: Thomas Bretz
+
+   * macros/CT1Hillas.C:
+     - changed MWRiteRootFile to write the histograms only
+     - renamed HillasSource to MHillasSrc
+
+   * macros/MagicHillas.C:
+     - removed all anti source stuff (corresponding to star.C)
+     - changed MWRiteRootFile to write the histograms only
+     - renamed HillasSource to MHillasSrc
+
+   * macros/estfit.C:
+     - renamed HillasSource to MHillasSrc
+
+   * macros/estimate.C:
+     - renamed HillasSource to MHillasSrc
+     - changed to display more interesting histograms
+
+   * multidimdist.C:
+     - added Theta
+     - added Alpha
+
+   * macros/star.C
+     - removed wrong HillasSource
+     - added MSrcPosCam
+
+   * starplot.C:
+     - removed all anti source stuff (corresponding to star.C)
+     - renamed HillasSource to MHillasSrc
+
+   * macros/multidimdist2.C:
+     - fixed a typo
+     - added Alpha and Theta
+
+   * mbase/MTime.h:
+     - added minus-operator
+
+   * mdata/MDataChain.[h,cc]:
+     - added floor
+
+   * mhist/MFillH.[h,cc]:
+     - moved MMap and MMap support MHArray
+
+   * mhist/MHArray.[h,cc]:
+     - added MMap
+     - added MMap-support
+     - added legend
+     - added more draw options
+
+   * mhist/MHFadcCam.[h,cc]:
+     - added Fill(const MRawEvtData*)
+     - added const getter functions
+
+   * mhist/MHFadcPix.h:
+     - added const getter functions
+
+   * mmc/MMcCorsikaRunHeader.[h,cc]:
+     - removed underscores from names
+     - removed empty destructor
+
+   * manalysis/MPedestalCalc.[h,cc]:
+     - added (not yet to LinkDef.h and Makefile)
+
+   * mgeom/MGeomMirror.[h,cc], mgeom/MGeomPMT.[h,cc], 
+     mmc/MMcConfigRunHeader.[h,cc], mmc/MMcCorsikaRunHeader.[h,cc]:
+     - changed comments
+     - added missing manalysis-dir (strange!)
+
+   * macros/dohtml.C:
+     - added new macros
+
+
+
+ 2002/11/16: Abelardo Moralejo
+
+   * mmc/MMcCorsikaRunHeader.cc:
+     - added default destructor
+
+
+
+ 2002/11/15: Thomas Bretz
+
+   * mmc/MMcCorsikaRunHeader.[h,cc]:
+     - small changes
+
+   * mmc/McLinkDef.h:
+     - added missing MMcCorsikaRunHeader
+
+
+
+ 2002/11/15: Oscar Blanch
+
+   * mmc/MMcCorsikaRunHeader.[h,cc]:
+     - added
+
+
+
+ 2002/11/14: Thomas Bretz
+
+   * mmain/MAnalysis.cc, mmain/MMonteCarlo.cc, mmain/MDataCheck.cc:
+     - removed SetProgressBar of reader
+
+   * mhist/MHFlux.cc:
+     - localized some variables
+     - get rid of old c-style sprintf
+     - return errorflag in Parab as return value!
+
+   * mgeom/MGeomPMT.cc, mgeom/MGeomMirror.cc:
+     - removed redefinition of a default argument
+
+   * mhist/MHMcIntRate.cc, mhist/MHMcCollectionArea.[h,cc]: 
+     - changed the error calculation according to a suggestion from Raquel
+
+   * mmontecarlo/MMcCollectionAreaCalc.cc: 
+     - for collection area: MMcTrig isn't needed if all showers are
+       triggered showers
+
+   * mmc/MMcConfigRunHeader.cc:
+     - made function definition identical to function declaration
+
+   * macros/star.C:
+     - removed anti source for the moment
+
+   * macros/multidimdist2.C:
+     - added
+
+   * macros/comprob.C, macros/multidimdist.C:
+     - changed to use MHillasSrc instead of HillasSource
+
+   * mhist/MHHadronness.cc:
+     - changed the output of Print a bit
+
+
+
+ 2002/11/13: Thomas Bretz
+
+   * mfilter/MFEventSelector.[h,cc]:
+     - if total number of events read from file the selector worked only for
+       one eventloop - fixed.
+     - changed MReadMarsFile to MRead
+
+   * mbase/MContinue.cc:
+     - fixed a typo
+
+   * mbase/MEvtLoop.cc, meventdisp/MGEvtDisplay.cc:
+     - renamed MReadMarsFile/MReadTree to MRead
+
+   * mfileio/FileIOLinkDef.h, mfileio/Makefile:
+     - added MRead
+
+   * mfileio/MRead.[h,cc]:
+     - added
+
+   * mfileio/MReadMarsFile.[h,cc], mfileio/MReadTree.[h,cc]:
+     - renamed from MReadMarsFile to MRead
+     - derived from MRead
+     - removed progressbar support from MReadTree
+
+   * mfileio/MWriteRootFile.cc:
+     - added a info output
+
+   * mfileio/MCT1ReadPreProc.[h,cc]:
+     - changed to work much much better :)
+
+   * mgeom/GeomLinkDef.h, mmc/McLinkDef.h:
+     - added missing LinkDefs (helllo Oscar!)
+
+   * mgeom/MGeomCamCT1.cc:
+     - mirrored the CT1 camera in x (CT1 default)
+
+   * mgeom/MGeomMirror.[h,cc]:
+     - some small changes
+   
+   * mgeom/MGeomPMT.[h,cc]:
+     - changed usage of TArrayF from pointer to reference
+
+   * mgui/MCamDisplay.cc:
+     - fixed a crash at delete when the user closed a automatically
+       created canvas
+
+   * mhist/MHFadcCam.[h,cc]:
+     - implemented ResetHistograms
+
+   * mhist/MHMatrix.[h,cc]:
+     - implemented ReduceNumberOfRows (preliminary, untested)
+
+   * mmc/MMcConfigRunHeader.[h,cc]:
+     - some small changes
+     - changed usage of TArrayF from pointer to reference
+
+
+
+ 2002/11/11: Thomas Bretz
+
+   * manalysis/MHillas.cc:
+     - moved division by size before test of number of used pixels
+
+   * mfileio/MCT1ReadPreProc.cc:
+     - added a eof-conditional
+
+   * mhist/MH3.cc:
+     - added a 'nonew' option to DrawClone
+
+   * mhist/MHHadronness.cc:
+     - check for NaN in Fill
+
+
+
+ 2002/11/08: Oscar Blanch
+
+   * mgeom/MGeomPMT.[h,cc]:
+     - added
+     - Information about simulated QE
+
+   * mgeom/MGeomMirror.[h,cc]:
+     - added
+     - Mirrors properties
+
+   * mgeom/Makefile:
+     - modified to compile new classes
+
+   * mmc/MMcConfigRunHeader.[h,cc]:
+     - added
+
+   * mmc/Makefile:
+     - modified to compile new classes
+
+
+
+ 2002/11/08: Thomas Bretz
+
+   * mhist/MHMatrix.cc:
+     - implemented a zero suppression
+
+
+
+ 2002/11/07: Thomas Bretz
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - added MFEventSelector
+
+   * mfilter/MFEventSelector.[h,cc]:
+     - added
+
+   * mfilter/MF.[h,cc]:
+     - made gsDef[Name,Title] a static const member
+
+   * manalysis/MMultiDimDistCalc.cc:
+     - changed the default function to kernel
+
+
+
+ 2002/11/07: Oscar Blanch
+   * mmc/MMcEvt.[hxx,cxx]
+     - Some new variable from the reflector header event.
+     - Class version switched to 2
+
+   * mmc/MMcRunHeader.[hxx,cxx]
+     - Varible member fOpticLinksNoise has been introduced
+     - Class version switched to 3
+
+
+ 2002/11/07: Wolfgang Wittek
+
+   * mhist/MHFlux.[h,cc]
+     - changed to avoid warnings : "member initializers will be re-ordered
+                                    to match declaration order"
+
+
+
+ 2002/11/06: Thomas Bretz
+
+   * Makfile.conf.osf5.1:
+     - added
+
+   * mhist/MHMatrix.cc:
+     - changed all math.h functions or similar to TMath
+     - added 2*pow(rows, 1/(4+cols))^2 as the standard kernel window
+
+   * mfileio/MCT1ReadPreProc.cc:
+     - corrected the reading routines
+
+   * mfileio/*.cc:
+     - changed my eMail address
+
+   * mfileio/structures.h:
+     - small changes to make it architecture independant
+
+
+
+ 2002/11/04: Thomas Bretz
+
+   * macros/estimate.C, macros/estfit.C:
+     - added
+     
+   * mfileio/structures.h, mfileio/defines.h:
+     - added from CT1 PreProc 0.5
+
+   * mfileio/MCT1ReadPreProc.[h,cc]:
+     - added 
+
+   * mhist/MHArray.[h,cc]:
+     - added
+
+   * Makefile:
+     - changed the order of the libs to make the linker happy
+     
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - changed to be able to use also an existing MBlindPixels from the 
+       parlist
+     - changed to use the pixel Id instead of its index number from the evt
+
+   * manalysis/MCameraSmooth.cc:
+     - changed to use the pixel Id instead of its index number from the evt
+       
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added GetPixById member function
+
+   * manalysis/MCompProbCalc.[h,cc]:
+     - changed Hadroness to Hadronness
+   
+   * manalysis/MHillasExt.cc:
+     - fixed a typo in a comment
+
+   * mbase/MParContainer.[h,cc]:
+     - added New-virtual member function
+
+   * mbase/MTask.[h,cc]:
+     - changed AddToBranchList so that it also accepts comma seperated
+       lists (only when using TString)
+       
+   * mdata/MData.[h,cc], mdata/MDataArray.[h,cc], mdata/MDataChain.[h,cc],
+     mdata/MDataElement.[h,cc], mdata/MDataList.[h,cc]
+     - updated comments
+     - added new GetDataMember member function
+     
+   * mdata/MDataArray.[h,cc]:
+     - added new member function AddEntry(MData*)
+     
+   * mfileio/FileIOLinkDef.h, mfileio/Makefile:
+     - added MCT1ReadPreProc
+     
+   * mfileio/MCT1ReadAscii.cc:
+     - removed fNphot->Clear() (automatically called for each event by
+       Reset();
+       
+   * mhist/HistLinkDef.h, mhist/Makefile:
+     - added MHArray
+     
+   * mhist/MFillH.[h,cc]:
+     - made work with arrays of histograms (MHArray) the mapping is
+       done by a preliminary class MMap
+       
+   * mhist/MH.[h,cc]:
+     - implemented GetHistByName virtual function
+     - implemented GetDataMember virtual function
+     - small changes to debug output
+     
+   * mhist/MH3.[h,cc]:
+     - implemented usage of GetDataMember for AddBranchToList
+     - implemented GetHistByName
+     - implemented New to be used in MHArray
+
+   * mhist/MHAlphaEnergyTheta.h, mhist/MHAlphaEnergyTime.h,
+     mhist/MHEnergyTheta.h, mhist/MHEnergyTime.h,
+     mhist/MHHillas.[h,cc], mhist/MHHillasExt.[h,cc],
+     mhist/MHHillasSrc.[h,cc], mhist/MHMcDifRate.h,
+     mhist/MHMcEfficiency.h, mhist/MHMcEfficiencyEnergy.h,
+     mhist/MHMcEfficiencyImpact.h, mhist/MHMcEnergy.[h,cc],
+     mhist/MHMcEnergyImpact.h, mhist/MHMcEnergyMigration.h,
+     mhist/MHMcIntRate.h, mhist/MHStarMap.h, mhist/MHThetabarTheta.h,
+     mhist/MHThetabarTime.h, mhist/MHTimeDiffTheta.h, 
+     mhist/MHTimeDiffTime.h:
+     - implemented GetHistByName
+   
+   * mhist/MHHadronness.[h,cc]:
+     - some small changes and checks
+     - changed histogram io from standard pointer to '->'
+
+   * mhist/MHMatrix.cc:
+     - updated comments
+     - implemented GetDataMembers
+
+
+
+ 2002/10/31: Thomas Bretz
+
+   * mfileio/MReadTree.cc:
+     - enhanced the validity of the fNuMEntries workaround from
+       3.02.06 to 3.07.01
+
+   * manalysis/MBlindPixelCalc.h, mhist/MBinning.h:
+     - added an explicit cast to get rid of a compiler warning on Alpha
+
+   * mhist/MH.cc:
+     - removed an unused variable to get rid of a compiler warning on Alpha
+
+
+
+ 2002/10/31: Wolfgang Wittek
+
+   * mhist/MHFlux.[h,cc]:
+     - type of fVarname and fUnit changed from char* to TString
+
+
+
+ 2002/10/30: Thomas Bretz
+
+   * mhist/MHMatrix.cc:
+     - changed the return value for the kernel method from log to -log
+     - fixed a typo in an error message
+     - fixed a crash in case the matrix is singular
+
+   * mhist/MMultiDimDistCalc.cc:
+     - check whether calculation of the distance succeeded
+
+   * mfileio/MReadTree.[h,cc]:
+     - implementation which makes sure, that the number of events returned 
+       by GetEntries always is the correct value.
+     - removed const from the GetEntries definition
+     - mainly use GetEntries now instead of fNumEntries
+
+   * manalysis/MCameraSmooth.cc:
+     - removed include of MMcRunHeader
+
+
+
+ 2002/10/29: Thomas Bretz
+
+   * manalysis/MHadroness.[h,cc]:
+     - renamed to MHadronness
+
+   * mhist/MHHadroness.[h,cc]:
+     - renamed to MHHadronness
+     - small changes to the graphical and text output
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h, macros/multidimdist.C,
+     manalysis/MMultiDimDistCalc.[h,cc], macros/comprob.C,
+     mhist/Makefile, mhist/HistLinkDef.h:
+     - changed Hadroness to Hadronness
+
+   * manalysis/MCerPhotAnal.cc:
+     - small changes to the code layout
+
+
+
+ 2002/10/24: Thomas Bretz
+
+   * macros/multidimdist.C:
+     - some changes to make it work with the latest version of Mars
+
+   * mhist/MHMatrix.cc:
+     - changed the Print member function to be more flexible
+
+   * mhist/MHHadroness.[h,cc]:
+     - changed fQfac from TH to TGraph
+     - changed the Qfactor-plot x-axis from Hadronness to Gamma-Acceptance
+
+   * mgui/MCamDisplay.cc:
+     - changed ratio from ratio to sqrt(ratio) in GetColorError
+
+   * mhist/MH3.cc:
+     - changed plotted errors from spread/sqrt(n) to spread
+
+
+
+ 2002/10/19: Abelardo Moralejo
+
+   * manalysis/MCerPhotCalc.cc
+     - Added check of whether a pixel has all its FADC slices empty before
+       subtracting pedestal.
+
+
+
+ 2002/10/18: Thomas Bretz
+
+   * mfileio/MWriteRootFile.cc
+     - make sure that the tree is created in the corresponding file
+
+
+
+ 2002/10/17: Thomas Bretz
+
+   * mraw/MRawEvtPixelIter.[h,cc]
+     - added function to get the sum of squares of the samples
+
+
+
+ 2002/10/16: Abelardo Moralejo
+
+   * manalysis/MCerPhotCalc2.[h,cc], MCerPhotCalc.[h,cc]
+     - Class MCerPhotCalc2 renamed MCerPhotCalc (they were redundant).
+     - Now the default pixel treatment is the same as originally: add 
+       all FADC slices
+
+   * macros/MagicHillas.C
+     - changed accordingly to changes above.
+
+
+
+ 2002/10/16: Thomas Bretz
+
+   * macros/readMagic.C:
+     - added MPrint for MRawEvtHeader
+     - changed to MPrint to new Skip-Style
+
+   * manalysis/MHillasCalc.cc, manalysis/MHillasSrcCalc.cc:
+     - corrected output stream in case of hex or setfill was used
+
+   * mbase/MPrint.[h,cc]:
+     - introduced new behaviour of PreProcess (EnableSkip)
+
+   * mbase/MTaskList.cc:
+     - fixed a bug in Process which caused Histograms to be written
+       after each event
+
+   * meventdisp/MGEvtDisplay.cc:
+     - introduced printing of MRawEvtHeader
+
+   * mmc/MMcEvt.cxx:
+     - some small changes
+     - changed Print output from cout to fLog
+     - changes to the default values
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - removed the second empty line after Print
+     - added Getter-function for the DAQEvtNumber
+
+   * macros/star.C, macros/starplot.C, macros/threshold.C, macros/trigrate.C,
+     macros/plot.C, macros/plot2.C, macros/MagicHillas.C, macros/CT1Hillas.C,
+     macros/collarea.C:
+     - added ProgressBar
+
+   * macros/flux.C:
+     - fixed some coding bugs (redeclaration of Draw, Draw starting with a
+       capital)
+
+   * macros/MagicHillas.C:
+     - fixed some typos
+
+
+
+ 2002/10/15: Thomas Bretz
+
+   * mbase/MContinue.[h,cc]:
+     - added
+     
+   * Makefile:
+     - added some comments
+     
+   * macros/readMagic.C:
+     - replaced MHillas by MHillasExt
+     - print also MC Information
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - use MGeomCam::GetPixRatio
+     - added GetRatio[Min,Max]
+     - added GetErrorPhot[Min,Max]
+
+   * manalysis/MHillas.[h,cc], manalysis/MHillasExt.[h,cc],
+     manalysis/MHillasSrc.[h,cc]:
+     - return error codes
+     - don't display any error message or warning
+
+   * manalysis/MHillasCalc.[h,cc], manalysis/MHillasSrcCalc.[h,cc]:
+     - evaluate error codes returned by MHillas::Calc
+     - added Postprocess
+
+   * manalysis/MMcPedestalCopy.cc:
+     - removed obsolete comment
+
+   * manalysis/MMcPedestalNSBAdd.cc:
+     - added include MGeomPix
+
+   * manalysis/MPedestalCam.[h,cc]:
+     - moved some stuff from header file to source file
+       to get rid of some includes in the header file
+     - adde GetSize
+     - added GetMean[Min,Max]
+
+   * manalysis/MPedestalPix.[h,cc]:
+     - added Clear
+     - added IsValid
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MContinue
+     
+   * mbase/MClone.h:
+     - added GetObject
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added SetProgressBar II
+
+   * mbase/MTask.[h,cc], mbase/MTaskList.[h,cc]:
+     - enhanced some comments
+     - print the name of the filter in PrintStatistic
+     - made the def name and title a static member
+     
+   * meventdisp/MGCamDisplay.[h,cc]:
+     - added displays for: Errors, Phot/Err, Levels and Pedestals
+     
+   * meventdisp/MGEvtDisplay.cc:
+     - Some simplifications
+     - introduced AddTab
+   
+   * mfileio/MCT1ReadAscii.cc:
+     - added include MPedestalPix
+     
+   * mgeom/MGeomCam.[h,cc]:
+     - added GetPixRatio
+
+   * mgui/MCamDisplay.[h,cc]:
+     - added possibilities to display: errors, ratios, levels and pedestals
+
+   * mhist/MHHillasSrc.cc:
+     - some small changes if mmdeg=0
+     
+   * mhist/MHStarMap.cc:
+     - anhanced displayed radius from 2/3r to 5/6r
+
+   * mmain/MMars.[h,cc]:
+     - changed layout
+     - added comments to display
+
+   * mmain/MProgressBar.cc:
+     - added some comments
+
+   * manalysis/MImgCleanStd.cc:
+     - pixels with to many 'used' neighbors are left used
+
+
+ 2002/10/14: Abelardo Moralejo
+
+   * manalysis/McerPhotCalc.cc, manalysis/MCerPhotCalc2.cc
+     - Initialized fEnableFix (before, bad pedestal subtraction if
+       reading camera 0.4 root files)
+
+
+ 2002/10/09: Abelardo Moralejo
+
+   * mhist/MHMcRate.cc:
+     - fixed a bug in total rate calculation (results change very little, 
+       only a 0.2 percent at most)
+
+
+ 2002/09/16: Thomas Bretz
+
+   * mtools/MagicSnake.cc:
+     - removed some debugging output
+     - fixed a small bug in the initialization
+
+
+
+ 2002/09/16: Thomas Bretz
+
+   * manalysis/MCerPhotPix.cc:
+     - shortened output
+
+   * mbase/MEvtLoop.cc:
+     - added a better progressbar support, if MReadTree or MReadMarsFile
+       exists in the Tasklist 
+
+   * mbase/MTaskList.cc:
+     - fixed a bug which caused MParList::Reset not to be called anymore
+       as soon as kCONTINUE was called once.
+
+   * mfileio/MReadTree.[h,cc]:
+     - added AddFiles member function
+
+   * mmain/MProgressBar.[h,cc]:
+     - added as a simple Progress meter for eventloops
+
+   * mmain/Makefile, mmain/MainLinkDef.h:
+     - added MProgressBar
+
+   * manalysis/MHillas.cc:
+     - removed warning in case of no photons. problems with Thomas' files.
+
+   * mbase/Makefile:
+     - added mfileio
+
+
+
+ 2002/09/16: Thomas Bretz
+
+   * macros/rootlogon.C:
+     - added SetMakeSharedLib to make it work correctly on linux
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MEnergyEstParam
+     - added MMatrixLoop
+
+   * manalysis/MEnergyEstParam.[h,cc], manalysis/MMatrixLoop.[h,cc]:
+     - added
+
+   * manalysis/MEnergyEst.h:
+     - added fImpact provisionally
+     - changed to 'no-storage'
+
+   * manalysis/MHillas.[h,cc], manalysis/MHillasExt.[h,cc],
+     manalysis/MHillasSrc.[h,cc]:
+     - added set function to support Thomas Schweitzers Image files
+
+   * mbase/MFilter.cc:
+     - small changes to output
+
+   * mbase/MLog.[h,cc]:
+     - added IsNull to switch off output completely
+
+   * mbase/MParList.[h,cc]:
+     - added Remove function
+     - added IsOwner function
+     - changes to SavePrimitive
+     - kDoNotReset-support
+
+   * mbase/MTaskList.cc:
+     - make sure, that in sub-tasklist the parameterlist isn't reset
+
+   * mdata/MDataLinkDef.h, mdata/Makefile:
+     - added MDataElement
+     - added mhist-path
+
+   * mdata/MDataChain.[h,cc]:
+     - added support for MDataElement
+
+   * mhist/MH3.[h,cc]:
+     - added enums for log-scale
+     - set logscale automatic when drawing
+     - added 'only' option to draw functions
+     - set colors when 'col' option is given
+
+   * mhist/MHHillas.cc:
+     - better hist range for fCenter
+
+   * mhist/MHMatrix.[h,cc]:
+     - made default name and title a static class member
+     - changed AddColumn now returning the new comlumn index
+     - added Fill to fill Matrix from file
+     - added locking
+     - added IsValid
+     - added GetNumRows
+     - added SetNumRow
+     - added []-operator
+     - added GetNumRow
+
+   * mhist/MHStarMap.cc:
+     - fixed some comments
+
+   * mbase/MEvtLoop.[h,cc], MParContainer.[h,cc]:
+     - added support for writing two or more Evtloops into one macro
+
+
+
+ 2002/09/02: Thomas Bretz
+
+   * mhist/MHMatrix.[h,cc]:
+     - added GetIndexdOfSortedColumn
+     - added SortMatrixByColumn
+
+   * mhist/HistIncl.h:
+     - added TArrayI.h (for MHMatrix.h)
+
+
+
+ 2002/08/19: Thomas Bretz
+
+   * mhist/MHillasExt.cc:
+     - removed a wrong 2 in the calculation of fAsym
+
+
+
+ 2002/08/16: Thomas Bretz
+
+   * mhist/MFillH.cc:
+     - if not title is given create a default title from the names
+
+   * mhist/MHHillas.cc, mhist/MHHillasExt.cc:
+     - use the new MH::Draw[Copy] function
+     - added names to the histograms in MHHillasExt
+
+   * manalysis/MCerPhotPix.h:
+     - unimportant change
+
+   * manalysis/MImgCleanStd.cc:
+     - added comment
+
+   * mhist/MH.[h,cc]:
+     - added function to draw two histograms in one pad with
+       a layout of two stat boxes and a legend: Draw[Copy]
+     - added comments
+     - added another sanity check in SetBinning(TH1*,TH1*)
+
+
+
+ 2002/08/14: Thomas Bretz
+
+   * mbase/MTask.[h,cc], mbase/MTaskList.[h,cc]:
+     - added second argument to PrintStatistics
+
+
+
+
+
+ 2002/08/12: Thomas Bretz
+
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - fixed a typo in the SetUseCentralPixel
+     - only use pixels without starlight for interpolation
+
+
+
+ 2002/08/09: Thomas Bretz
+
+   * mbase/MIter.[h,cc]:
+     - added
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MIter
+
+   * mdata/MDataChain.cc:
+     - added sanity check in StreamPrimitive
+
+   * mfilter/MF.[h,cc]:
+     - fixed StreamPrimitive
+     - don'w stream standard name and title.
+     - added default constructor
+
+   * mfilter/MFDataMeber.cc:
+     - strip spces from value before returning GetRule
+
+   * mfilter/MFilterList.[h,cc]:
+     - fixed StreamPrimitive
+     - don't stream standard name and title.
+
+
+
+ 2002/08/08: Thomas Bretz
+
+   * manalysis/MHillasSrc.cc:
+     - use double dist instead of single fDist for calculation
+
+   * manalysis/MMultiDimDistCalc.[h,cc]:
+     - added support for the kernel method
+     - added stream primitive
+     - changed version number to 1
+     - adapted to new MHMatrix (using MDataArray)
+
+   * mdata/MDataArray.[h,cc]:
+     - added
+
+   * mdata/DataLinkDef.h, madata/Makefile:
+     - added MDataArray
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed some bugs in StreamPrimitive
+     - StreamPrimtive doesn't write the default name/title anymore
+
+   * mhist/MHMatrix.[h,cc]:
+     - replaced the Arrays for the rules by a MDataArray
+     - implemented StreamPrimitive
+     - implement the use of the kernel function for num<0
+     - multiply fM2 by nevts-1
+     - added sanity check in case of dists[i]<0
+
+   * mhist/MHHillas.[h,cc]:
+     - added fUsedPix, fCorePix
+     - added fUsedPix, fCorePix to plots
+     - changed layout of plots
+     - changed name and title of MakeDefCanvas
+
+   * mhist/MHHillasSrc.[h,cc]:
+     - changed plot of Alpha from fabs(fAlpha) to fAlpha
+     - changed name and title of MakeDefCanvas
+
+   * mhist/MHillasExt.[h,cc]:
+     - changed layout of plots
+     - changed name and title of MakeDefCanvas
+     - made independant of MHillas
+     - exchanged the usage of the Fill-argument (MHillasExt) and the
+       stored pointer (MHillasSrc)
+     - changed the default binning of asym to be symmetric
+
+   * mbase/MTask.cc:
+     - fixed wrong streaming of filter name
+
+   * macros/starplot.C:
+     - added
+
+   * macros/dohtml.C:
+     - added starplot.C
+
+   * macros/MagicHillas.C, macros/CT1Hillas.C:
+     - changed to use new stylish Hillas Histograms
+
+   * macros/star.C:
+     - changed to interpolate pixels around hot spots
+     - write Sourcs and AntoSource to RunHeaders
+
+
+
+ 2002/08/07: Thomas Bretz
+
+   * macros/dohtml.C:
+     - added missing paths
+
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - replaced booleans by fFlags
+     - added StreamPrimitive
+     - changed version number to 1
+
+   * manalysis/MHillasSrcCalc.[h,cc]:
+     - added correct initializations for the pointers
+     - made the pointers persistent
+
+   * manalysis/MImgCleanStd.cc, manalysis/MSrcPosCam.cc,
+     mfileio/MWriteRootFile.cc:
+     - don't stream name and title if not necessary
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added some output
+     - added print function
+     - added gListOfPrimitives to delete BIT(15) of streamed containers
+     - Added default argument for Read and Write
+
+   * mbase/MParContainer.cc:
+     - added usage of gListOfPrimitives
+
+   * mbase/MParList.cc, mbase/MTaskList.cc, mhist/MBinning.cc:
+     - fixed a bug when only the title is different from the default
+
+   * mhist/MHHillas.cc:
+     - fixed the wrong usage of ApplyBinning for the 2D-Hist fCenter
+
+
+
+ 2002/08/06: Thomas Bretz
+
+   * mhist/MHHillas.cc:
+     - fixed setting of binning for fCamera
+
+   * mhist/MH.cc, mhist/MBinning.cc:
+     - added sanity check in ApplyBinning and Apply
+
+   * mbase/MFilterList.[h,cc]:
+     - moved to mfilter
+
+   * mbase/Makefile, mbase/BaseLinkDef.h, 
+     mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - changed accordingly
+
+
+
+ 2002/08/05: Thomas Bretz
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added a warning in case of duplicate names in the lists
+     - added orresponding member functions (HasDuplicateNames)
+     - added some sanity checks, checking for an open file
+
+   * mbase/MFilter.[h,cc]:
+     - added GetRule virtual member function
+
+   * mbase/MFilterList.[h,cc]:
+     - added GetRule 
+     - added StreamPrimitive
+     - added name and title to the constructor
+     - set version number to 1
+
+   * mbase/MTask.h:
+     - removed const qualifiers from fFilter (seems, that the root io
+       doesn't like it)
+
+   * mdata/MDataChain.[h,cc], mdata/MDataList.[h,cc], mdata/MDataMember.[h,cc],
+     mdata/MDataValue.[h,cc]:
+     - set class version to 1
+     - added default constructor if missing
+     - added fDataMember to MDataMember (formaly fName isn't stored)
+
+   * mfilter/MF.[h,cc], mfilter/MFAlpha.[h,cc], mfilter/MFDataMember.[h,cc],
+     mfilter/MFParticleId.[h,cc], mfilter/MFTriggerLvl1.[h,cc]:
+     - added StreamPrimitive
+     - removed const qualifiers from data members
+     - added the "!" to the data member storing the result
+     - added GetRule
+
+   * mhist/MFillH.[h,cc]:
+     - fixed some small bugs in StreamPrimitive
+
+   * mhist/MH3.[h,cc]:
+     - added the missing const-qualifier of StreamPrimitive
+
+   * mbase/MParContainer.[h,cc]:
+     - implemented setting a unique id in SavePrimitive
+     - imnplemented GetUniqueID 
+     
+   * manalysis/MHillasSrcCalc.cc, manalysis/MImgCleanStd.cc,
+     manalysis/MSrcPosCam.cc, mbase/MEvtLoop.cc, mbase/MParList.cc,
+     mbase/MTaskList.cc, mfileio/MReadTree.cc, mfileio/MWriteRootFile.cc,
+     mhist/MF.cc, mfilter/MFAlpha.cc, mfilter/MFDataMember.cc,
+     mfilter/MFParticleId.cc, mfilter/MFTriggerLvl1.cc, mhist/MBinning.cc,
+     mhist/MFillH.cc, mhist/MH3.cc:
+     - changed the 'instance' name to the UniqueName
+     - in some files: implemented a static constant name and title, which
+       is used to descide whether the name and/or title should be stream
+       in the constructor-call in StreamPrimitive
+
+
+
+ 2002/08/06: Wolfgang Wittek
+
+   * mbase/MTask.cc:
+     - redefinition of default argument in MTask::SavePrimitive removed
+
+
+
+ 2002/08/02: Thomas Bretz
+
+   * manalysis/MHillasSrcCalc.[h,cc], manalysis/MImgCleanStd.cc,
+     manalysis/MSrcPosCam.cc, mbase/MParContainer.[h,cc],
+     mfileio/MReadTree.cc, mfileio/MWriteRootFile.cc, mhist/MBinning.cc:
+     - added comments
+
+   * manalysis/MSrcPosCam.cc, mfileio/MWriteRootFile.cc, mhist/MFillH.cc:
+     - fixed a missing " in SavePrimitive
+
+   * mbase/MTask.[h,cc], mhist/MBinning.[h,cc], mhist/MH3.[h,cc]:
+     - implemented SavePrimitive
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added MakeMacro
+     - added Read and Write
+
+   * mbase/MParContainer.[h,cc], mbase/MParList.[h,cc], 
+     mbase/MTaskList.[h,cc]:
+     - added GetNames, SetNames virtual functions
+
+   * mdata/MData.[h,cc], mdata/MDataChain.[h,cc], mdata/MDataList.[h,cc],
+     mdata/MDataValue.[h,cc], mdata/MDataMember.[h,cc]:
+     - implemented GetRule
+     - move Code from Print to GetRule
+     - removed Print
+
+   * mhist/MH3.[h,cc]:
+     - implemented default constructor
+
+   * manalysis/MHillasSrcCalc.[h,cc], manalysis/MImgCleanStd.[h,cc],
+     manalysis/MSrcPosCam.[h,cc], mbase/MParList.[h,cc], mbase/MTask.h,
+     mbase/MTaskList.[h,cc], mfileio/MReadTree.[h,cc], 
+     mfileio/MWriteRootFile.[h,cc], mhist/MBinning.[h,cc], 
+     mhist/MFillH.[h,cc], mhist/MH3.[h,cc]:
+     - renamed SavePrimitive to StreamPrimitive
+     - implemented more accurate streaming
+     - removed some "//!" from the data members
+
+   * mbase/MParContainer.[h,cc]:
+     - new virtual function StreamPrimitive
+     - implemented flag whether this container has been streamed already
+
+   * mbase/MTask.[h,cc]:
+     - corrected streaming of primitive to stream filters correctly
+     - increased version number to 1
+
+   * mhist/MBinning.[h,cc]:
+     - move SetEdges and SetEdgesLog to the source file
+     - implemented a flag telling something about the type of the binning
+
+
+
+ 2002/08/01: Thomas Bretz
+
+   * manalysis/MHillasSrcCalc.[h,cc], manalysis/MImgCleanStd.[h,cc],
+     manalysis/MSrcPosCam.[h,cc], mbase/MEvtLoop.[h,cc], 
+     mbase/MParContainer.[h,cc], mbase/MParList.[h,cc],
+     mbase/MTaskList.[h,cc], mfileio/MReadTree.[h,cc],
+     mfileio/MWriteRootFile.[h,cc], mhist/MFillH.[h,cc]:
+     - added SavePrimitive
+
+   * mbase/MEvtLoop.h, mbase/MParList.h, mbase/MTaskList.h,
+     mfileio/MReadMarsFile.h, mfileio/MReadTree.h, 
+     mfileio/MWriteRootFile.h, mhist/MFillH.h:
+     - changed from ClassVersion 0 to ClassVersion 1
+   
+   * mfileio/FileIOLinkDef.h:
+     - added MChain
+
+   * mfileio/MReadMarsFile.cc, mfileio/MReadTree.cc, 
+     mfileio/MWriteRootFile.cc, mhist/MFillH.cc:
+     - added default constructor
+
+   * mfileio/MReadTree.cc:
+     - moved MChain to its own file
+
+   * mfileio/MWriteRootFile.cc:
+     - added default constructor to MRootFileBranch
+     - changed Version number from 0 to 1
+
+   * mfileio/Makefile, mfileio/FileIOLinkDef.h:
+     - MChain added
+
+   * mfileio/MChain.[h,cc]:
+     - added (from MReadTree.cc)
+
+   * manalysis/MHillas.[h,cc]:
+     - don't draw ellipse if values are invalid
+     - add used and core pixels to Print-output
+
+   * manalysis/MHillasExt.cc:
+     - reordered some comments
+
+   * mdata/MDataChain.[h,cc]:
+     - fixed a bug causing usage of '-' sometime not to work
+     - added handling of '+' sign
+
+   * mfileio/MReadTree.h:
+     - changed some comments
+
+   * mhist/MBinning.[h,cc]:
+     - added Apply
+
+   * mhist/MHHillas.[h,cc], mhist/MHHillasSrc.[h,cc], 
+     mhist/MHHillasExt.[h,cc]:
+     - added default binning (usefull for the Magic Camera)
+     - some changes to the layout
+     - added support for the sign in MHHillasExt
+
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - added the possibility to use the interpolation of the
+       surrounding pixels
+     - clean the array with the blind pixel IDs at any ReInit
+
+   * manalysis/MBlindPixels.h:
+     - IsBlind now checks also for the validity of the array
+
+   * manalysis/MCerPhotPix.h:
+     - added Set-function
+
+   * manalysis/MHillas.cc:
+     - Don't ouput a warning if fSize==0 or fNumUsedPixels<0
+       (happens too often)
+
+   * manalysis/MCameraSmooth.[h,cc]:
+     - added
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - added MCameraSmooth
+
+
+
+ 2002/07/31: Thomas Bretz
+
+   * mgeom/MGeomPix.[h,cc]:
+     - added bits to flag pixel sin the two most outer rings
+     - added IsInOutermostRing and IsInOuterRing member function
+     - added CheckOuterRing mebmber function
+     - set the bit for the most outer ring in the member function to
+       initialize the next neighbors.
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added InitOuterRing to initialize the bits for the secendmost 
+       outer ring
+
+   * mgeom/MGeomCamMagic.cc:
+     - Call InitOuterRing
+
+   * manalysis/MHillasExt.[h,cc]:
+     - removed AsciiRead member function
+     - reset fConc/fConc1 to -1 instead of 0
+     - replaced float by Float_t
+     - replaced Float_t for m3x/y, dzx and dzy by Double_t
+     - replaced maxpixx and maxpixy by maxpixid
+     - added somew new calculations (still in comments)
+     - scaled nphot by the ratio of the area of the current pixel to
+       the pixel with id zero to make a fair comparison in the maxpix
+       findinng
+
+   * manalysis/MSrcPosCam.[h,cc]:
+     - removed AsciiRead/Write member function
+
+   * manalysis/MImgCleanStd.cc:
+     - changed ispixused array size from max to max+1
+
+   * macros/MagicHillas.C:
+     - use the default binning of the histograms
+
+   * mhist/MH.[h,cc]:
+     - changed argument of SetBinning from TArrayD* to TArrayD&
+     - added ScaleArray
+     - added ScaleAxis
+     - proved that ScaleAxis is really working
+     - Added ApplyBinning
+
+   * mhist/MHHillas.[h,cc], mhist/MHHillasSrc.[h,cc]:
+     - corrected the default binning
+     - take use of MH::ApplyBinning
+     - don't stop execution if no binning was found (take default)
+     - made sure, that rescaling of the axis is working properly
+
+
+
+ 2002/07/29: Thomas Bretz
+
+   * manalysis/MImgCleanStd.[h,cc]:
+     - changed ispixused from static size to dynamicly allocated size
+       (thanks to Markus Gaug)
+
+
+
+ 2002/07/29: Thomas Bretz
+
+   * mhist/MH.[h,cc]:
+     - added FindGoodLimits (taken from TTreePlayer)
+     - added GetMinimumGT
+
+   * mbase/MAGIC.h:
+     - removed kPI (redefinition in TVector2.h)
+
+   * mbase/BaseLinkDef.h:
+     - removed kPI (redefinition in TVector2.h)
+
+
+
+ 2002/07/26: Abelardo Moralejo
+
+   * mhist/MH.cc
+     - Fix: removed default arguments of ScaleAxis(...)  (did not 
+       compile on alphas).
+
+
+
+ 2002/07/25: Abelardo Moralejo
+
+   * manalysis/MCerPhotCalc2.[h,cc]:
+     - Changed fWeight into a TArrayF to make the class usable for
+       any number of FADC slices.
+     - added procedure SetDefaultWeights for initialization.
+
+   * macros/MagicHillas.C: 
+     - changed accordingly
+
+
+
+ 2002/07/25: Wolfgang Wittek, Thomas Bretz
+
+   * mhist/MHHillas.[h,cc], mhist/MHHillasSrc.[h,cc]:
+     - added some more histograms showing the new parameters.
+
+   * mhist/MH.[h,cc]:
+     - added ScaleAxis member functions
+
+
+
+ 2002/07/25: Thomas Bretz
+
+   * mtools, mtools/Makefile, mtools/ToolsLinkDef.h, mtools/ToolsIncl.h:
+     - added
+
+   * mgeom, mgeom/Makefile, mgeom/GeomLinkDef.h, mgeom/GeomIncl.h:
+     - added
+
+   * Makefile:
+     - mtools added
+     - mgeom added
+
+   * mtools/MagicCivilization.[h,cc], mtools/MagicDomino.[h,cc],
+     mtools/MagicShow.[h,cc], mtools/MagicSnake.[h,cc]:
+     - added
+
+   * mgui/MineSweeper.[h,cc]:
+     - moved to mtools
+
+   * mgui/MGeom*.[h,cc]:
+     - moved to mgeom
+
+   * mgeom/MGeomCamMagic.cc:
+     - corrected 48(!) wrong entries in the Next Neighbor table
+
+   * mmain/Makefile, eventdisp/Makefile:
+     - added mgeom
+
+   * mgui/Makefile, mgui/LinkDef.h, mhist/Makefile, manalysis/Makefile:
+     - removed MGeom* and MineSweeper
+
+   * macros/rootlogon.C:
+     - added new include paths
+
+   * manalysis/MCerPhotEvt.cc, mgeom/MGeomCam.cc:
+     - removed include of MHexagon
+
+
+
+ 2002/07/23: Thomas Bretz
+
+   * mgui/MineSweeper.cc, mgui/MCamDisplay.cc:
+     - fixed a bug which could caused the destructor of the created canvas
+       not to be called if the object was deleted.
+
+   * mgui/MCamDisplay.h:
+     - some reordering
+
+   * mgui/MHexagon.cc:
+     - return the correct distance to primitive
+     - do a sanity check in DistancetoPrimitive
+
+   * mhist/HistLinkDef.h:
+     - added missing classes
+
+
+
+ 2002/07/23: Wolfgang Wittek, Thomas Bretz
+
+   * manalysis/MHillas.cc, manalysis/MHillasSrc.cc:
+     - replaced algorithms by the ones from the corresponding TDAS note
+     - made results of calculations (hopefully) more accurate
+     - added some output warnings and sanity checks
+     - changed the default parameters in the Reset function
+
+   * manalysis/MHillasSrc.[h,cc]:
+     - added fCosDeltaAlpha
+     - made Calc returning a Bool_t
+
+   * manalysis/MHillasSrcCalc.cc:
+     - make use of the return value of MHillasSrc::Calc 
+
+
+
+ 2002/07/22: Abelardo Moralejo
+
+   * manalysis/MCerPhotCalc2.[h,cc]:
+     -added procedure SetWeights.
+
+   * macros/MagicHillas.C:
+     -added example on how to use MCerPhotCalc2
+
+
+
+ 2002/07/22: Thomas Bretz
+
+   * mgui/MCamDisplay.cc:
+     - removed some unecessary includes
+     - replaced *fPixels by *this
+
+   * mgui/MineSweeper.[h,cc]:
+     - added more comments
+     - removed some unnecessary includes
+     - replaced enum constants for colors by the root ones
+     - added gInterpreter->DeleteGlobal(this)
+     - removed the deletion of the self-allocated fDrawingPad
+     - added kUserBits, replacing kBitMask
+
+
+
+ 2002/07/16: Thomas Bretz
+
+   * macros/plot.C, macros/plot2.C, macros/star.C, macros/comprob.C:
+     - updated the comments in the macros
+     
+   * mgui/MHexagon.cc:
+     - added a sanity check in DistanceToPrimitive
+
+   * mgui/MCamDisplay.[h,cc]:
+     - added DistanceToPrimitive
+     - declared virtual functions as virtual (easier to read in the Dox)
+
+   * mfileio/MWriteAsciiFile.[h,cc]:
+     - renamed AddContainer and AddRule to AddColumn and AddColumns
+
+   * macros/MagicHillas.C:
+     - adopted to new names of MWriteAsciiFile member functions
+
+
+
+ 2002/07/16: Wolfgang Wittek
+
+   * new 
+     ---
+     mhist    : MHEffOnTime     (replaces MHEffOnTimeTime and
+                                          MHEffOnTimeTheta)
+                MHThetabarTheta (forgotten to comit last time)
+                MHThetabarTime  (forgotten to comit last time)
+                MHGamma         (makes the subtraction SRC-ASRC and
+                                 counts the events with alpha<alpha0)
+
+   * modified 
+     --------
+     Mars     : Makefile.conf.general 
+                Changelog
+
+
+     mhist    : Makefile
+                HistLinkDef.h 
+                MHFlux             (performs the flux calculation)
+
+                MHAlphaEnergyTheta (replace BinningAlpha by BinningAlphaFlux)
+                MHAlphaEnergyTime  (replace BinningAlpha by BinningAlphaFlux)
+
+     macros   : flux.C       (replace some code by MHGamma,
+                              replace MHEffOnTimeTime and MHEffOnTimeTheta
+                              by MHEffOnTime)
+
+   * removed
+     -------
+     mhist    : MHEffOnTimeTime
+                MHEffOnTimeTheta
+
+
+
+ 2002/07/15: Abelardo Moralejo
+
+   * manalysis/MCerPhotCalc2.[h,cc]
+     - converted fWeight into a static variable.
+
+
+
+ 2002/07/11: Thomas Bretz
+
+   * mgui/MGeomCamCT1.cc:
+     - fixed a bug in the NN-Table (127 doesn't exist, 126 missing)
+
+   * mgui/MCamDisplay.cc:
+     - changed some gPad to fDrawingPad
+     - added kNoContextMenu and kCannotPick flags for the Primitives
+     - scaled the size of the pixel numbers text with the pixel radius
+
+   * mgui/MineSweeper.[h,cc]:
+     - added
+
+   * mgui/Makefile, mgui/GuiLinkDef.h:
+     - added MineSweeper
+
+   * Makefile:
+     - added missing mfileio
+
+
+
+ 2002/07/11: Abelardo Moralejo
+
+   * manalysis/MCerPhotCalc2.[h,cc]
+     - new class to compute nphe weighting FADC slices.
+
+
+
+ 2002/07/10: Oscar Blanch
+
+   * manalysis/MCerPhotAnal.[h,cc]
+     - new class to compute nphe. First version.
+
+
+
+ 2002/07/10: Abelardo Moralejo
+
+   * macros/MagicHillas.C:
+     -added MMcEvt container to hillas.root output
+
+
+
+ 2002/07/10: Thomas Bretz
+
+   * mmain/Makefile:
+     - added -I../mfileio
+
+   * manalysis/MCerPhotPix.h:
+     - renamed IsCorePixel to IsPixelCore
+     - renamed SetCorePixel to SetPixelCore
+
+   * manalysis/MHillas.[h,cc]:
+     - added fNumCorePixel
+     - added fNumUsedPixel
+
+   * manalysis/MImgCleanStd.cc, manalysis/MCerPhotEvt.cc:
+     - renamed IsCorePixel and SetCorePixel
+
+
+
+ 2002/07/08: Thomas Bretz
+
+   * macros/rootlogon.C:
+     - added include pathes for ACLIC
+
+   * mfileio, mfileio/FileIOLinkDef.h, mfileio/FileIOIncl.h, 
+     mfileio/Makefile:
+     - new directory
+
+   * mbase/MWriteAsciiFile.[h,cc], mbase/MWriteRootFile.[h,cc],
+     mbase/MReadTree.[h,cc], mbase/MReadMarsFile.[h,cc],
+     manalysis/MCT1ReadAscii.[h,cc]:
+     - moved to mfileio
+
+   * mbase/Makefile, mbase/BaseLinkDef.h, mbase/BaseIncl.h,
+     manalysis/Makefile, manalysis/AnalysisLinkDef.h, 
+     manalysis/AnalysisIncl.h, meventdisp/Makefile:
+     - changed accordingly
+
+   * meventdisp/MGCamDisplay.cc:
+     - cd to right canvas before drawing camera display
+
+   * meventdisp/MGEvtDisplay.[h,cc]:
+     - added the "Geometry"-Tab
+     - added MC informations to gui
+
+   * mgui/MCamDisplay.[h,cc]:
+     - added DrawPixelNumbers
+     - added buttons to change the palette online
+
+   * mgui/MHexagon.h:
+     - added Getter functions
+
+   * macros/MagicHillas.C:
+     - added read.DisableAutoScheme()
+
+   * mhist/MH.[h,cc]:
+     - changed Fill to be non abstract anymore
+
+
+
+ 2002/07/04: Abelardo Moralejo
+
+   * macros/trigrate.C:
+     - Introduced some style improvements suggested by T. Bretz.
+
+
+
+ 2002/07/04: Abelardo Moralejo
+
+   * mmontecarlo/MMcTriggerRateCalc.h,cc:
+     - Now the dimension of fTrigger is set dynamically, to allow
+       the processing of files with an arbitrarily large number of 
+       trigger conditions inside.
+
+   * macros/trigrate.C:
+     - Adapted the macro to changes above, and added a third argument:
+       the name of a file containing pure NSB events from which the
+       accidental trigger rate is calculated. Previously, this had to 
+       be introduced in the macro by hand by the user.
+
+
+
+ 2002/06/14: Thomas Bretz
+
+   * mhist/MBinning.cc:
+     - Initialize the binning with 10 edges from 0 to 1
+
+
+
+ 2002/06/13: Thomas Bretz
+
+   * mdata/MData.cc:
+     - changed ostream.h to ofstream.h to make it compile on alpha
+
+
+
+ 2002/06/10: Thomas Bretz
+
+   * mbase/MReadMarsFile.cc:
+     - changed name of fRun to ReadRunHeaders
+
+   * mbase/MReadTree.cc:
+     - changed output to show name of class
+
+   * macros/plot.C:
+     - added
+
+   * macros/plot2.C:
+     - added
+
+   * manalysis/MHillas.cc:
+     - changed atan2 to atan for fDelta
+
+   * mbase/MAGIC.h, mbase/BaseLinkDef.h:
+     - changed definitions for Particle Id to enum
+
+   * mbase/MGList.cc:
+     - IsA()->InheritsFrom() replaced with InheritsFrom()
+
+   * mbase/MWriteAsciiFile.cc:
+     - IsA()->InheritsFrom() replaced with InheritsFrom()
+     - removed some debug outputs
+
+   * mbase/MDataChain.[h,cc]:
+     - implemented sign '-'
+
+   * mhist/MH.h:
+     - changed default canvas size to 580x435
+
+   * mhist/MHHadroness.cc:
+     - added some more output to Print
+
+   * mhist/MHMatrix.h:
+     - changed some i,j to x,y
+     - removed fabs from distance calculation
+     - added sqrt to distance calculation
+
+   * mmc/MMcEvt.cxx:
+     - changed output of Print
+
+
+
+ 2002/06/06: Thomas Bretz
+
+   * manalysis/MHillasSrc.cc:
+     - changed atan2 to atan for fAlpha
+
+
+
+ 2002/06/05: Thomas Bretz
+
+   * mbase/MWriteAsciiFile.[h,cc]:
+     - changed the code completely to support rules (data chains), too.
+       the interface stayed the same.
+
+   * mdata/MDataChain.cc, mhist/MHMatrix.cc:
+     - added math.h for alpha compilers
+
+   * mbase/MParContainer.h:
+     - changes IsReadyToSave to const
+
+   * mdata/MData.[h,cc]:
+     - added AsciiWrite
+
+   * mdata/MDataChain.[h,cc], mdata/MDataList.[h,cc], mdata/MDataValue.h:
+     - added IsReadyToSave
+
+   * mdata/MDataMember.[h,cc]:
+     - added a new constructor
+     - added IsReadyToSave
+
+
+
+ 2002/06/04: Thomas Bretz
+
+   * mhist/MHCompProb.[h,cc]:
+     - added
+
+   * mhist/MHMatrix.cc:
+     - corrected some bugs in the algorithm to calculate the distance
+
+   * mhist/Makefile:
+     - added -I../mmc
+
+   * mbase/Makefile:
+     - added -I../mdata
+
+   * mhist/MHHadroness.cc:
+     - some changes to the layout of the drawn histograms
+
+
+
+ 2002/06/03: Thomas Bretz
+
+   * mhist/MHCompProb.[h,cc]:
+     - added
+
+   * mhist/MHHadroness.[h,cc]:
+     - added
+
+   * mhist/HistLinkDef.h, mhist/Makefile:
+     - added MHCompProb
+     - added MHHadroness
+
+   * mhist/MFillH.cc:
+     - added a info-output
+
+   * mhist/MH3.cc:
+     - excluded temporary profiles from directory
+
+   * mhist/MHMatrix.[h,cc]:
+     - added code to calculate multi-dimensional distances
+     - added comments
+
+   * mbase/MAGIC.h:
+     - changed kGAMMA to 1
+
+   * mbase/MParList.[h,cc]:
+     - added Replace-function
+
+   * mbase/MReadMarsFile.[h,cc]:
+     - added correct seeking for the run headers
+
+   * mbase/MReadTree.[h,cc]:
+     - added GetFileIndex()
+
+   * mbase/MTaskList.cc:
+     - changed fTasksProcess.Delete() to fTasksProcess.Clear()
+
+   * mbase/MWriteAsciiFile.[h,cc]:
+     - added some code for future usage (in comments)
+
+   * mbase/MLogo.[h,cc]:
+     - added (not in use)
+
+   * mfilter/MFParticleId.[h,cc]:
+     - added
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - added MFParticleId
+
+   * manalysis/MHadroness.[h,cc]:
+     - added
+
+   * manalysis/MCompProbCalc.[h,cc]:
+     - added
+
+   * manalysis/MMultiDimDistCalc.[h,cc]:
+     - added
+                                                           
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MHadroness
+     - added MCompProbCalc
+     - added MMultiDimDistCalc
+
+   * manalysis/Makefile:
+     - added ../mdata
+     - added ../mhist
+
+   * macros/star.C:
+     - added
+
+   * macros/comprob.C:
+     - added
+
+   * macros/multidimdist.C:
+     - added
+  
+  * macros/dohtml.C:
+     - added star.C
+     - added comprob.C
+     - added multidimdist.C
+
+  * mdata/MData.h:
+     - added ()-operator
+
+  * mdata/MDataList.cc:
+     - removed 'all' modifier in Print-statement
+
+  * mdata/MDataChain.[h,cc]:
+     - added default constructor
+
+  * mdata/MReadTree.cc:
+     - fixed a root bug for root versions<3.03/00 (the open file in
+       the TChain was not deleted (closed))           
+
+   * mbase/MReadMarsFile.[h,cc]:
+     - store parlist instead of tasklist
+     - check for run types between files
+     - check for used reflector version (because of a bug in the program)
+
+   * mmc/MMcRunheader.hxx:
+     - added GetReflVersion()
+
+   * mmontecarlo/MMcTriggerRateCalc.cc:
+     - changed particle Id numbers to predefined constants
+
+
+
+ 2002/05/29: Thomas Bretz
+
+   * mhist/MHMatrix.[h,cc]:
+     - added
+
+   * mhist/HistLinkDef.h, mhist/Makefile
+     - added MHMatrix
+
+   * mhist/MH.h:
+     - added Finalize-function prototype to be called at the end of
+       the eventloop
+
+   * mhist/MFillH.cc:
+     - added call to Finalize-function to in PostProcess
+
+   * mhist/MH3.cc:
+     - removed old includes
+
+   * mhist/MDataChain.cc:
+     - fixed a harmfull bug in the constructor. fOperatorType wasn't
+       correctly initialized
+
+   * mhist/MDataMember.cc:
+     - added some output in case of failures
+
+   * mgui/MGeomCam.[h,cc]:
+     - renamed fMm2Deg to fConvMm2Deg to be consistent with the Getter
+       function name
+
+
+
+ 2002/05/13: Thomas Bretz
+
+   * mbase/MReadTree.cc:
+     - changed the Notify-workaround from GetEntry to LoadTree.
+
+   * mfilter/MFDataMember.[h,cc]:
+     - changed class to use MDataMember instead of a direct access to
+       TMethodCall
+
+   * mfilter/Makefile:
+     - added path to mdata
+
+
+
+ 2002/05/06: Thomas Bretz
+
+   * mbase/MReadMarsFile.cc, mbase/MReadTree.cc, mbase/MTaskList.cc:
+     - implemented usage of the return value of the Notofy function
+
+   * mdata/MDataChain.[h,cc]:
+     - implemented single-argument operators (like abs or exp)
+
+
+
+ 2002/05/03: Thomas Bretz
+
+   * mars.cc:
+     - changed version to 0.8
+     - added logo stuff
+
+   * merpp.cc:
+     - changed usage-output
+
+   * mgui/MCamDisplay.cc, mgui/MGeomCam.cc, mgui/MGeomCamCT1.cc, 
+     mgui/MGeomCamMagic.cc, mgui/MHexagon.cc, mhist/MBinning.cc,
+     mhist/MFillH.cc, mhist/MH.cc, mhist/MHAlphaEnergyTheta.cc,
+     mhist/MHAlphaEnergyTime.cc, mhist/MHEffOnTimeTheta.cc,
+     mhist/MHEffOnTimeTime.cc, mhist/MHEnergyTheta.cc, MHEnergyTime.cc,
+     mhist/MHMcCollectionArea.cc, mhist/MHStarMap.cc, mmain/MMars.cc,
+     mmontecarlo/MMcCollectionAreaCalc.cc
+     - changed mail address
+     - added missing copyright notices
+     - added missing class description
+
+   * mbase/MWriteRootFile.cc, mbase/MWriteAsciiFile.cc:
+     - added AddToBranch call to AddContainer(const char*, const char*)
+
+
+
+ 2002/04/30: Thomas Bretz
+
+   * macros/MagicHillas.C:
+     - made eventloop infinite
+
+   * macros/tar.C:
+     - implemented some sanity checks (existing files)
+
+   * mgui/MCamDisplay.[h,cc]:
+     - changed to use DeepSea palette in root versions newer than 3.01/05
+     - fixed a bug which caused the destructor to do strange thing
+       (the uncloned fGeomCam was deleted)
+     - implemented a more accurate deletion of the objects in the
+       TClonesArrays by using TClonesArray::Delete
+     - Implemented deletion of automatically created TCanvas
+     - Implemented a sanity check in Draw and DrawPhotNum
+
+   * macros/readCT1.C, macros/readMagic.C:
+     - changed to Handling of the gui and keyboard input
+     - implemented the filename as function argument
+
+   * manalysis/MCT1ReadAscii.cc:
+     - Expanded filename to support filnames containing '~'
+
+   * mhist/MH3.h:
+     - removed 'const' to make 0.7 root 3.01/06 compatible
+
+   * mdata/MDataMember.cc, mdata/MDataValue.cc, mdata/MDataChain.cc:
+     - removed a 'redefinition of default argument'
+
+   * mdata/MFDataMember.cc:
+     - fixed a bug in the process function (second switch was never reached)
+
+
+
+ 2002/04/29: Thomas Bretz
+
+   * macros/tar.C:
+     - added
+
+   * Makefile:
+     - changed "make tar" to use macros/tar.C and root
+
+
+
+ 2002/04/29: Wolfgang Wittek
+
+   * mhist/Makefile, mhist/HistLinkDef.h 
+     - MHThetabarTheta and MHThetabarTime were added
+
+   * mhist/MHThetabarTheta.[h,cc], mhist/MHThetabarTime.[h,cc]:
+     - added
+
+   * mhist/MHMcEnergyMigration.[h,cc]:
+     - added
+
+
+
+ 2002/04/27: Oscar Blanch
+
+   * mmc/MMcRunHedaer.cxx, mmc/MMcTrig.cxx, mmc/MMcTrigHeader:
+     - description of variables that have been introduced in the second
+       version of this Containers.
+
+
+
+ 2002/04/26: Thomas Bretz
+
+   * mhist/MHFadcCam.cc:
+     - start numbering of pixels with 1
+
+   * mhist/MHFadcPix.[h,cc]:
+     - overloaded clone to get rid of the histograms in any directory
+     - removed some unnecessary StrDup calls
+     - changed binning (Thanks to Abelardo)
+
+   * mdata/MData.[h,cc]:
+     - documentation added
+     - implemented a new abstract member function: IsValid
+
+   * mdata/MDataChain.cc, mdata/MDataList.cc:
+     - changed logging output
+     - documentation added
+
+   * mdata/MDataList.h, mdata/MDataMember.h, mdata/MDataValue.h:
+     - implemented IsValid
+
+   * mdata/MDataMember.cc:
+     - Don't preprocess if fCall is already available
+     - documentation added
+
+   * mdata/MDataValue.cc:
+     - documentation added
+
+   * mhist/MHMcDifRate.h, mhist/MHMcEfficiency.h, 
+     mhist/MHMcEfficiencyEnergy.h, mhist/MHMcEfficiencyImpact.h, 
+     mhist/MHMcEnergyImpact.h:
+     - corrected class description
+
+   * mbase/MParList.cc:
+     - fixed a bug in CreateObjList
+
+
+
+ 2002/04/25: Thomas Bretz
+
+   * mmontecarlo/MMcCollectionAreaCalc.[h,cc]:
+     - counts now the number of simulated showers
+     - implemented some sanity checks (corsika version, etc)
+
+   * mhist/MMcCollectionArea.[h,cc]:
+     - added a first implementation of a calculation using only triggered
+       events
+
+   * mhist/MH.[h,cc]:
+     - changed the first argument in SetBinning (according to the number
+       of axis) to TH2 or TH3
+
+   * mhist/MH2.cc:
+     - changed the first argument in SetBinning (according to the number
+       of axis) to TH2 or TH3
+
+   * macros/collarea.C:
+     - replaces MReadTree by MReadMarsFile
+
+   * mmc/MMcRunHeader.hxx:
+     - added GetAllEvtsTriggered
+
+
+
+ 2002/04/24: Thomas Bretz
+
+   * mbase/MReadTree.cc:
+     - made use of TBranch::GetClassName root version dependant 
+
+   * manalysis/MCerPhotCalc.[h,cc]:
+     - added a fix (ped.mean - 0.5) for files from camera with version <= 40
+
+   * mmc/MMcRunHeader.hxx:
+     - added some Getter functions
+
+   * mdata/MDataChain.cc:
+     - use rule as a title if no title ios given
+
+   * mhist/MH3.[h,cc]:
+     - added usage of Data-Chains
+     - added a profiling option to the draw functions
+     - use the title (rule) of the data-chain as axis title
+
+   * mhist/Makefile:
+     - added mdata-path
+
+   * mbase/MParContainer.h:
+     - changed some output in GetterFunction
+
+
+
+ 2002/04/24: Wolfgang Wittek
+
+   * Work was done on the calculation of photon fluxes as a function of
+     Theta and as a function of time. The work is still in progress.
+
+   * macros/wowflux.C
+     - the macr0 was added (extended and improved version of flux.C)
+     - the macro steers the calculation of photon fluxes as a function
+       of Theta and time
+     - the macro is not yet complete; testing and developing is going on
+
+   * mhist/MHAlphaEnergyTheta.[h,cc], mhist/MHAlphaEnergyTime.[h,cc],
+     mhist/MHEffOnTimeTheta.[h,cc], mhist/MHEffOnTimeTime.[h,cc],
+     mhist/MHTimeDiffTheta.[h,cc], mhist/MHTimeDiffTime.[h,cc]:
+     - documentation was added 
+     - histogram axes were labeled
+
+   * mhist/MHEffOnTimeTheta.cc:
+     - range in which the fit of the distribution of time differences
+       is to be performed has been calculated
+     - new histograms were added (chi2/NDF, lambda, N0del)
+
+
+
+ 2002/04/23: Thomas Bretz
+
+   * madata/Makefile, mdata/DataIncl.h, mdata/DataLinkDef.h,
+     mdata/MData.[h,cc], mdata/MDataValue.[h,cc], mdata/MDataList.[h,cc],
+     mdata/MDataChain.[h,cc], mdata/MDataMember.[h,cc]:
+     - added
+
+   * mmc/MMcEvt.[hxx,cxx]:
+     - added correct units for fImpact
+
+
+
+ 2002/04/22: Thomas Bretz
+
+   * Makefile:
+     - added a chapter how to compile mars using shared libraries
+
+   * NEWS:
+     - updated
+ 
+   * mfilter/MF.[h,cc]:
+     - added 
+
+   * mfilter/MFDataMember.[h,cc]:
+     - added 
+
+   * mhist/MH3.[h,cc]:
+     - added 
+
+   * mhist/MHHillasExt.[h,cc]:
+     - added 
+     
+   * macros/rootlogon.C:
+     - added make() function
+     - splitted rootlogon()
+     
+   * mbase/MFilterList.cc:
+     - fixed a bug in the constructor
+     - small changes to the print function
+     
+   * mbase/MParContainer.[h,cc]:
+     - Added GetterMethod-Function
+
+   * mbase/MParList.cc:
+     - Added a security check in case no def. constructor of the new class 
+       is available
+     - changed print function
+     
+   * mbase/MReadTree.cc:
+     - changed so that the class type of the branch is used for creation of 
+       a new object instead of its name
+
+   * mbase/MTaskList.[h,cc]:
+     - fixed the check for the Process function. Only base classes
+       of first order have been checked
+       
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MF, MFDataMember
+
+   * mhist/HistLinkDef.h, mhist/MFillH.cc:
+     - added MH3, MHHillasExt
+
+   * mhist/MFillH.cc:
+     - small changes
+
+   * mhist/MH.[h,cc]:
+     - changed name handling in MakeDefCanvas to TString
+
+   * mhist/MHHillas.cc:
+     - exchanged Get*axis()->SetTitle with Set*Title()
+     
+   * mhist/MHHillas.h:
+     - made SetMm2Deg virtual (for MHHillasExt)
+
+   * mhist/MHStarMap.[h,cc]:
+     - changed layout from mm to deg
+
+   * mhist/MHHillasSrc.cc:
+     - fixed a bug which made it unpossible to display fDist in degrees
+
+
+
+ 2002/04/19: Thomas Bretz
+
+   * mbase/MTaskList.cc:
+     - fixed a heavy bug which caused PreProcess to crash (GetListOfBases
+       return a List of TBaseClasses not a List of TClass objects)
+     - added a security check to Process whether we have something to process or not.
+
+   * macros/CT1Hillas.C:
+     - changed to the new Hillas classes
+
+   * macros/readCT1.C:
+     - fixed a bug causing readCT1.C to crash when reading the first event 
+       being a pedestal event
+
+
+
+ 2002/04/17: Thomas Bretz
+
+   * mbase/MParContainer.cc:
+     - case label TMethodCall::kOther changed to default to get rid of
+       some warnings in newer root's (missing case label kString)
+
+   * mbase/MAGIC.h:
+     - changed defintion of Glog so that it now works on Alpha machines, too.
+
+
+
+ 2002/04/16: Thomas Bretz
+
+   * mhist/MHHillas.cc:
+     - Fixed a 'redefinition of default argument' on alpha
+
+
+
+ 2002/04/15: Thomas Bretz
+
+   * mgui/MGeomCam.cc:
+     - Added SetReadyToSave to Constructor
+
+   * mhist/MH.cc:
+     - Added some #ifdef conditionals for a fix in root
+
+   * mfilter/MFAlpha.[h,cc]:
+     - made IsExpressionTrue inline
+
+
+
+ 2002/04/05: Thomas Bretz
+
+   * mmain/MDataCheck.cc:
+     - exchanged order in call to MFillH constructor
+     - made eventloop infinite (only 300 events have been processed)
+
+   * mbase/MEvtLoop.h:
+     - added GetTaskList
+
+   * mbase/MTaskList.[h,cc]:
+     - introduced fTasksProcess which contains only the tasks
+       which overloads the process function so that processing
+       tasks doesn't waste time if a tasks doesn't have the process
+       function
+
+   * mgui/MGeomPix.[h,cc]:
+     - corrected calculation of pixel area
+
+
+
+ 2002/04/04: Thomas Bretz
+
+   * mbase/MLog.cc:
+     - stripped last character (CR) from output redirected to GUI    
+
+
+
+ 2002/03/21: Thomas Bretz
+
+   * mhists/MH.cc:
+     - TAxis::Set resets the axis title so I implemented a workaround
+       in SetBinning so that the axis title survives.
+
+   * mhists/MHEffOnTimeTheta.cc, MHEffOnTimeTime.cc:
+     - replaced Get*axis()->SetTitle() by Set*Title()
+     - corrected the Name in MakeDefCanvas
+
+
+
+ 2002/03/20: Thomas Bretz
+
+   * macros/flux.C:
+     - fixed a small bug (thanks to Wolfgang)
+
+   * mhist/MHHillas.[h,cc]:
+     - added more scaling options
+     - added setting for scaling factor
+
+   * mhist/MHStarMap.cc:
+     - changed sign of t (due to a mail of Wolfgang)
+
+   * mhist/MHTimeDiff*.cc:
+     - removed an implicit down-cast (TH1D --> TH1)
+
+
+
+ 2002/03/15: Oscar Blanch
+
+   * mmc/McLinkDef.h
+     - Automatic scheme evolution for all MC format classes.
+       It has been checked that it keeps compatibility with old files.
+
+   * mmc/MTriggerDefine.h
+     - Enlarge number of trigger pixels.
+
+   * mmc/MTrigger.[cxx,hxx]
+     - Trigger zone has been enlarged. Now information about status
+       of the pixel is saved for all Camera pixels.
+     - Old files can still be read but becareful when one looks at the
+       data member fPixelsFirst which is an array of different size for
+       the new and old files.
+     - ClassDef version upgraded to 2.
+
+   * mmc/MTriggerHedaer.[cxx,hxx]
+     - Member data fElecNoiseTrig, which has information about the 
+       electronic noise in the trigger chain, has been introduced.
+     - Trigger zone has been enlarged. Now information about status
+       of the pixel is saved for all Camera pixels.
+     - Old files can still be read but becareful when one looks at the
+       data member fThreshold which is an array of diferent size for
+       the new and old files.
+     - ClassDef version upgraded to 2.	
+
+
+
+ 2002/03/13: Oscar Blanch
+
+   * mmc/MMcRunHeader.[cxx,hxx]
+     -  Several new variable members have been added
+     -  Version number updated to 2
+
+
+
+ 2002/03/12: Thomas Bretz
+
+   * mmontecarlo/MMcTimeGenerate.cc (thanks to Wolfgang):
+     - removed wrong comment for Process
+     - changed Int_t to UInt_t (more readable)
+     - replaced unit: ms -> 0.1ms
+
+
+
+ 2002/03/08: Thomas Bretz
+
+   * manalysis/MHillasSrc.[h,cc]:
+     - added fHeadTail
+     - changed version number to 2.
+
+
+
+ 2002/03/07: Thomas Bretz
+
+   * mbase/MParContainer.[h,cc], MWriteAsciiFile.[h,cc]:
+     - added a scale value which can be used in case you are writing
+       single data mambers
+
+
+
+ 2002/03/04: Thomas Bretz
+
+   * mbase/MParContainer.cc:
+     - changed AsciiWrite so that only base classes with a version
+       id > 0 are written (important for MParContainer)
+
+
+
+ 2002/03/01: Thomas Bretz
+
+   * mhist/MHMcEfficiencyEnergy.[h,cc], mhist/MHMcEfficiencyImpact.[h,cc],
+     mhist/MHMcDifRate.[h,cc], mhist/MHMcIntRate.[h,cc]:
+     - added
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - added MHMcEfficiencyEnergy and MHMcEfficiencyImpact
+     - added MHMcDifRate and MHMcIntRate
+
+   * mhist/MHMcCollectionArea.[h,cc]:
+     - changed instantiation of collection area histogram
+     - added settings for the binning
+     - replaced division by root function
+     - added Calc-functions
+     - added GetHist
+
+   * mhist/MHMcEfficiency.[h,cc]:
+     - changed pointers in Calc functions to references
+
+
+
+
+
+ 2002/02/28: Thomas Bretz
+
+   * mhist/MHMcEnergyImpact.[h,cc], mhist/MHMcEfficiency.[h,cc]:
+     - added
+     
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - added MHMcEnergyImpact and MHMcEfficiency
+
+   * mhist/*.cc:
+     - repaced some *&-> casts by &.
+
+   * mhist/MHMcCollectionArea.[h,cc]:
+     - changed to be able to use new MHMcEfficiency.
+
+
+
+ 2002/02/21: Abelardo Moralejo
+
+   * manalysis/MHillasExt.cc :
+     - added #include <math.h>  (else, fabs not recognized by OSF)
+
+
+
+ 2002/02/21: Thomas Bretz
+ 
+   * manalysis/MHillas.[h,cc]:
+     - changed fMeanx and fMeany to fMeanX and fMeanY to match the names
+       of the getter functions, needed by TDataMember::GetterMethod
+     - commented out WriteAscii (replaced by more general in MParContainer
+       and MWriteAsciiFile)
+
+    * manalysis/MHillasSrc.[h,cc], mmc/MMcEvt.[hxx, cxx]:
+      - commented out WriteAscii (replaced by more general in MParContainer
+        and MWriteAsciiFile)
+
+    * manalysis/MHillasExt.[h,cc]:
+      - added necessary Getter Methods
+     
+    * mbase/MFilterList.cc:
+      - removed a nonsens comment
+    
+    * mbase/MGList.cc:
+      - relay on the bugfix for DynamicCast
+    
+    * mbase/MParContainer.[h,cc]:
+      - implemented WriteDataMember to have a more general interface
+        for readable output.
+      - changed ofstream to a more general ostream
+  
+    * mbase/MWriteAsciiFile.[cc,h]:
+      - generalized ascii writer to be able to write single data members
+
+
+
+ 2002/02/13: Thomas Bretz
+
+   * Makefile:
+     - made 'make dox' dependant on existance of shared object
+
+
+     
+ 2002/02/13: Thomas Bretz
+
+   * macros/MagicHillas.C, mhist/MHHillas.[h,cc], mhist/MHHillasSrc.[h,cc]:
+     - implemented variable binning (MBinning)
+     - implemented conversion to degrees (thanks to rudy)
+     
+   * mgui/MGeomCam.[h,cc], mgui/MGeomCamCT1.cc, mgui/MGeomCamMagic.cc:
+     - implemented fMm2Deg and fCamDist
+
+
+
+ 2002/01/23: Thomas Bretz
+
+   * macros/flux.C:
+     - fixed some bugs
+     - uncommented all drawing
+     
+   * mhist/MBinning.h:
+     - changed SetEdges(TArrayD)
+     
+   * mhist/MH.cc:
+     - SetBinning(..., TAxis*,...) didn't work. Corrected.
+     
+   * mhist/MHAlphaEnergyTheta.cc, mhist/MHAlphaEnergyTime.cc,
+     mhist/MHEffOnTimeTheta.cc, mhist/MHEffOnTimeTime.cc,
+     mhist/MHTimeDiffTheta.cc, mhist/MHTimeDiffTime.cc:
+     - changed wrong titles, names, etc.
+     - changed way of drawing projections
+     - fixed usage of MH::SetBinning(TH1*)
+
+
+     
+ 2002/01/22: Thomas Bretz
+ 
+   * mhist/MHHillasSrc.[h,cc], mhist/MHFadcCam.[h,cc]:
+     - changed return type of Fill to Bool_t
+   
+   * mfilter/MFAlpha.[h,cc]:
+     - added
+
+   * mfilter/MFill.[h,cc]:
+     - implemented a new calling style which allows you to let MFillH
+       create the necessary histogram objects
+
+   * mmain/MAnalysis.cc, macros/MagicHillas.C:
+     - changed to new stylish MHillas parameter containers
+
+   * meventdisp/MGEvtDisplay.cc, mgui/MCamDisplay.cc,
+     mmain/MDataCheck.[h,cc]:
+     - fixed a warning in red hat linux
+  
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MFAlpha
+  
+   * mhist/MHHillas.[h,cc], mhist/MHHillasSrc.[h,cc]:
+     - added SetupFill and usage of MBinning objects
+
+   * manalysis/MEnergyEst.[h,cc], manalysis/MEnergyEstimate.[h,cc],
+     mhist/MHTimeDiffTime.[h,cc], mhist/MHEnergyTheta.[h,cc],
+     mhist/MHEnergyTime.[h,cc], mhist/MHAlphaEnergyTheta.[h,cc],
+     mhist/MHAlphaEnergyTime.[h,cc], mhist/MHTimeDiffTheta.[h,cc],
+     mmontecarlo/MMcTimeGenerate.[h,cc]:
+     - added
+
+   * manalysis/Makefile:
+     - added MEnergyEst.cc
+     - added MEnergyEstimate.cc
+   
+   * mbase/MFilter.[h,cc], mfilter/MF*.[h,cc]:
+     - added name and title to constructor
+
+   * macros/flux.C:
+     - added
+
+
+
+ 2002/01/21: Thomas Bretz
+ 
+   * mbase/MReadMarsFile.cc, mbase/MReadTree.[h,cc]:
+     - implemented GetFileName
+
+   * mmc/MMcEvt.[hxx,cxx]
+     - implemented WriteAscii
+   
+   * mgui/MGeomPix.h:
+     - implemented first version of GetA
+
+   * mhist/MBinning.h:
+     - small changes to formulas
+     
+   * mhist/MH.[h,cc]:
+     - implemented SetBinnign functions
+
+   * macros/readMagic.C:
+     - removed MPedestalCam
+
+
+
+ 2002/01/19: Thomas Bretz
+ 
+   * mbase/MParContainer.cc:
+     - generalized virtual function AsciiWrite
+   
+   * changed to fit new MHillas inhertance model:
+     - manalysis/MHillas.[h,cc]
+     - manalysis/MHillasCalc.[h,cc]
+     - mhist/MHHillas.[h,cc]
+     - mhist/MHStarMap.[h,cc]
+
+   * added to fit new MHillas inhertance model:
+     - manalysis/MSrcPosCam.[h,cc]
+     - manalysis/MHillasSrc.[h,cc]
+     - manalysis/MHillasSrcCalc.[h,cc]
+     - manalysis/MHillasExt.[h,cc]
+     - mhist/MHHillasSrc.[h,cc]
+
+   * manalysis/MCerPhotEvt.[cc,h]:
+     - introduced weighting with pixel size in GetNumPhotonsMin
+     - introduced weighting with pixel size in GetNumPhotonsMax
+
+   * mgui/MCamDisplay.cc:
+     - weight the displayed color with the pixel size
+
+
+
+ 2002/01/18: Thomas Bretz
+ 
+   * mhist/MBinning.[h,cc]:
+     - added (not yet in Makefile)
+   
+   * mbase/MWriteAsciiFile.cc:
+     - fixed a bug: replaced GetSize by GetEntries
+     
+   * mbase/MReadTree.cc:
+     - changed EnableBranch to accept "Master.Sub" also
+
+
+
+ 2002/01/16: Thomas Bretz
+ 
+   * mars.cc:
+     - changed version number to 0.7
+
+   * NEWS:
+     - changed current version to 0.7
+
+   * manalysis/MMcPedestalNSBAdd.cc:
+     - small changes to output
+ 
+   * mbase/MParList.[h,cc]:
+     - added FindObject with class type argument
+   
+   * mbase/MWriteAsciiFile.cc
+     - replaced call to InheritsFrom by new FindObject
+ 
+ 
+ 
+ 2002/01/15: Thomas Bretz
+
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - added more comments
+     - removed a debug statement
+    
+   * manalysis/MBlindPixels.[h,cc]:
+     - added more comments
+    
+   * manalysis/MCerPhotCalc.cc:
+     - changed the warning output
+    
+   * manalysis/MMcPedestalCopy.h:
+     - added comments
+    
+   * manalysis/MMcPedestalNSBAdd.[h,cc]:
+     - added comments
+     - changed call to AddedToBranchList
+    
+   * mbase/MWriteAsciiFile.cc:
+     - added comments
+    
+   * mmc/MMcRunHeader.[hxx,cxx]:
+     - made getter const
+
+   * meventdisp/MGCamDisplay.cc:
+     - updated to use MBlindPixelCalc
+
+   * mbase/MEvtLoop.cc:
+     - replaced wrong "MTasklist" by "MTaskList"
+
+
+
+ 2002/01/14: Thomas Bretz
+ 
+   * manalysis/MMcPedestalCopy.cc, manalysis/MMcPedestalNSBAdd.cc:
+     - added comments
+
+   * mbase/MReadMarsFile.cc:
+     - changed output when switching to new file
+     
+   * meventdisp/MGFadcDisp.cc:
+     - made char array in constructor const
+     - changed char-array to TString
+
+   * mmain/MBrowser.[h,cc]:
+     - changed char-arrays to TString
+
+   * mmain/MDataCheck.[h,cc]:
+     - made char array in constructor const
+     
+   * Makefile.conf.linux, Makefile.conf.linux-gnu:
+     - changed to O5
+     
+   * mbase/MEvtLoop.cc:
+     - check for inheritance from MTaskList
+
+   * manalysis/MPedestalCopy.cc, manalysis/MPedestalNSBAdd.cc:
+     - small changes
+   
+   * mbase/MWriteAsciiFile.[h,cc]:
+     - changed to be able to write more than one container in a line
+
+
+
+ 2002/01/11: Oscar Blanch Bigas
+
+   * mmain/MAnalysis.cc:
+     - added MBlindPixelCalc step.
+
+   * macros/trigrate.C:
+     - the list of MHMcRate is created using from and to instead of
+       only dimension. Otherwise the case of a single trigger option is
+       not well treated.
+
+   * mhist/MHMcRate.[h,cc]:
+     - added funtion members SetFlux and SetIncidentRate and small
+       modification in CalcRate member function
+
+   * mmontecarlo/MMcTriggerRateCalc.cc:
+     - now this task sets the parameters to know the incident particle
+       flux using MHMcRate::SetFlux. The value are decided by the task
+       itself depending on the fPartId.
+
+   * manalysis/MBlindPixelCalc.cc:
+     - rename MMcRunHeader:GetStarFieldDe to MMcRunHeader:GetStarFieldDec. 
+
+   * mmc/MMcRunHeader.[hxx, cxx]:
+     - rename MMcRunHeader:GetStarFieldDe to MMcRunHeader:GetStarFieldDec. 
+
+
+
+ 2002/01/10: Oscar Blanch Bigas
+
+   * mbase/Makefile:
+     - added -I../MRawFormat in the included directories for compile
+       and link. It was needed to use this Makefile to compile the
+       files inside the drectory while compiling Monte Carlo programs.
+
+   * mraw/Makefile:
+     - added -I../MBase in the included directories for compile
+       and link. It was needed to use this Makefile to compile the
+       files inside the drectory while compiling Monte Carlo programs.
+
+   * mbase/Makefile:
+     - added -I../MBase- in the included directories for compile
+       and link. It was needed to use this Makefile to compile the
+       files inside the drectory while compiling Monte Carlo programs.
+
+   * mbase/MReadTree.cc:
+     - changed #include "../mraw/MRawEvtData.h" by #include
+       "MRawEvtData.h" to remove dependencies on the directory tree naming.
+
+
+
+ 2002/01/09: Oscar Blanch Bigas
+   
+   * manalysis/MPedestalCam.[h,cc]:
+     - added CheckBounds function to check that program does not try to
+       access pedestal outside the camera size.
+
+   * manalysis/MCerPhotCalc.h:
+     - Member data const MPedestalCam *fPedestals -> MPedestalCam
+     *fPedestals.
+
+   * manalysis/MCerPhotCalc.cc:
+     - Sanity check to avoid searching to pedestals outside the camera
+       size has been added.
+
+   * mmc/MMcRunHeader.[h,cxx]:
+     - added functions GetStarField[De,Ra].
+
+   * manalysis/MBlindPixels.[h,cc]:
+     - new containet that has a list of pixels that should not be used
+       in the analysis for any reason (corrupted, star in them, ...).
+
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - It is a task used to set up the list of blind pixels. Currently
+       it recognises the CrabNebula starfield and then switch off the
+       Theta Taury pixels. Blind pixels can be also introduced through
+       the macro or analysis program.
+
+   * manalysis/Makefile:
+     - added MBlindPixels and MBlinPixelCalc.
+
+   * manalysis/AnalysisLinkDef.h:
+     - added MBlindPixels and MBlinPixelCalc.
+
+   * macros/MagicHillas.C:
+     - added MBlindPixelCalc to avoid bias results due to Star Field
+       NSB.
+
+   * macros/readMagic.C:
+     - added MBlindPixelCalc to avoid bias results due to Star Field NSB while
+       computing the Hillas parameters.
+
+
+
+ 2001/12/19: Thomas Bretz
+  
+   * mbase/MEvtLoop.cc:
+     - added #ifdef directive to make it work on older root also
+      
+   * mbase/MReadTree.cc:
+     - added #ifdef directive to get rid of the memory leak in prior
+       root 3.02/* versions
+	    
+   * macros/MagicHillas.C, macros/readMagic.C, meventdisp/MGCamDisplay.cc,
+     mmain/MAnalysis.cc:
+     - changes MMcPedestalNSB to MMcPedestalNSBAdd
+     
+   * manalysis/MMcPedestalCopy.[h,cc], manalysis/MMcPedestalNSBAdd.[h,cc]:
+     - reorganized ReInit, PreProcess.
+     - moved some code from ReInit to PreProcess to make the code
+       simpler. At the moment we don't intend to change the 
+       objects in the parlist while runtime.
+
+   * manalysis/MMcPedestalNSB.[h,cc]:
+     - removed
+
+   * mbase/MReadMarsFile.cc:
+     - read the first run header twice. To make it available in the
+       PreProcess of all tasks
+   
+   * mbase/MTaskList.cc:
+     - fixed a bug in the ReInit function. The ReInits where calles with 
+       a NULL-pointer
+
+
+
+ 2001/12/18: Oscar Blanch
+								 
+   * manalysis/Makefile:
+     - Removed MMcPedestalNSB from compilation and added
+       MMcPedestalNSBAdd.
+
+   * manalysis/AnalysisLinkDefine.h:
+     - Removed MMcPedestalNSB from class list and added
+       MMcPedestalNSBAdd.
+
+   * manalysis/MMcPedestalCopy.[h,cc]
+     - added ReInit function.
+     - move all actions needed to redo for each run from PreProcess
+       to ReInit
+     - fix bug of Pedestal and Pedestal fluctuaions correspondence.
+
+   * manalysis/MMcPedestalNSBAdd.[h,cc]
+     - new name for old MMcPedestalNSB.[h,cc]
+     - added ReInit function.
+     - move all actions needed to redo for each run from PreProcess
+       to ReInit
+     - information about pixel size is used from MGeomCam.
+
+   * manalysis/MCerPhotCalc.[h,cc]
+     - remove fNumLoGainFadcSlices and fNumHiGainFadcSlices members
+     - fix bug of Pedestal and Pedestal fluctuaions correspondence.
+
+
+ 2001/12/18: Thomas Bretz
+ 
+   * manalysis/MMcPedestalCopy.cc:
+     - changed output
+     
+   * manalysis/MMcPedestalNSB.cc:
+     - changed output
+     - simplified initialization in PreProcess
+     
+   * mbase/MAGIC.h:
+     - added kSKIP
+     
+   * mbase/MParList.cc:
+     - added a check for the correct inheritance in FindCreateObj
+   
+   * mbase/MTask.cc:
+     - added support for kSKIP in PreProcess
+
+   * mbase/MTaskList.[h,cc]
+     - added support for kSKIP in PreProcess
+     - added Remove function (private)
+
+
+
+ 2001/12/17: Thomas Bretz
+ 
+   * .rootrc:
+     - added Root.Html.DescriptionStyle
+     - added Root.Html.SearchEngine
+     
+   * macros/dohtml.C:
+     - changed to use THtml (root >= 3.02/06 only)
+     
+   * manalysis/Makefile:
+     - changed order to get rid of some wranings
+   
+   * mbase/BaseLinkDef.h:
+     - removed MHtml
+     
+   * mbase/MEvtLoop.cc:
+     - exchanged gSystem->ProcessEvents() by gClient->ProcessEventsFor()
+       to make gui update faster
+       
+   * mbase/MGList.cc:
+     - added a missing sanity check (workaround for a root bug)
+     
+   * mbase/MReadTree.cc:
+     - uncomment EnableBranchCoosing for AutoEnablingScheme
+       (don't know why there was a comment which made things realy slow)
+     - changed the auto enabling scheme, so that a branch isn't enabled
+       more than once. This doesn't hurt, but the output may confuse the
+       users.
+       
+    * mbase/MTask.cc:
+      - added a simple not really necessary check whether the branch is
+        already in the list
+        
+    * mbase/MWriteRootFile.cc:
+      - changed kFillTree to a local const
+      
+    * mbase/Makefile:
+      - removed MHtml.cc
+    
+    * mfilter/MFTriggerLvl1.cc:
+      - changed AddBranchToList to use the correct container name
+
+
+
+ 2001/12/14: Thomas Bretz
+ 
+   * mbase/MReadMarsFile.[h,cc], mbase/MReadFild.[h,cc]:
+     - corrected handling of ReInit/Notify (at the moment I assume 
+       one run per file)
+     - made sure, that we don't get memory leaks when using MReadTree 
+       more than once because the pointer to the pointer isn't deleted.
+     - added a small class MChain which enhances TChain by a function to
+       reset fTree. This is used to control when notification are
+       happening
+
+   * mbase/MTask.cc:
+     - reset the number of executions before the preprocessing
+
+
+
+ 2001/12/11: Thomas Bretz
+
+   * mbase/MGGroupFrame.cc:
+     - removed default arguments from source file
+
+   * mbase/MGList.cc:
+     - changed cast in IsExisting to ?:
+
+   * NEWS:
+     - changed
+
+   * manalysis/MCerPhotCalc.cc, mfilter/MTriggerLvl1.cc,
+     mmontecarlo/MMcCollectionAreaCalc.cc,
+     mmontacarlo/MMcThresholdCalc.cc,
+     MMcTriggerRateCalc.cc:
+     - added Masterbranch name to AddToBranchList
+
+   * manalysis/MMcPedestalCopy.cc:
+     - added Masterbranch name to AddToBranchList
+     - fixed a bug in the branch name
+
+   * mbase/MGList.[h,cc]:
+     - added a better output if a picture wasn't found
+
+   * mbase/MReadTree.[h,cc]:
+     - added support for branches with master branch names to auto scheme
+       (first the complete branch name is tried and if this isn't found
+        only the subbranch name is used to enable the branch)
+
+   * mbase/MWriteRootFile.cc:
+     - appended a '.' to all newly create branches
+
+   * mmain/MBrowser.cc, mmain/MMars.cc:
+     - add the gui elements only if the corresponding picture was found
+
+   * mmain/MMars.[h,cc]:
+     - removed fPic1
+     - removed fPic2
+     - changed TList to MGList
+
+   * mraw/MRawFileWrite.cc:
+     - added a '.' to all branch names
+
+   * mbase/MTask.[h,cc]:
+     - added Prototype for ReInit-function
+
+   * mbase/MTaskList.[h,cc]:
+     - implemented ReInit for a task list
+
+   * mhist/MHFadcCam.h:
+     - added '->' to fArray
+
+
+
+ 2001/12/10: Thomas Bretz
+
+   * mmc/*.hxx:
+     - Changed MPARCONTAINER_H to MARS_MParContainer
+
+   * meventdisp/MGCamDisplay.cc:
+     - added MMcPedestalCopy to task list
+     - added MMcPedestalNSB  to task list
+
+   * mmain/MAnalysis.cc:
+     - added MMcPedestalCopy to task list
+     - added MMcPedestalNSB  to task list
+     - changed reader from MReadTree to MReadMarsFile
+
+   * meventdisp/MGEvtDisplay.cc:
+     - changed reader from MReadTree to MReadMarsFile
+
+   * macros/MagicHillas.C, macros/readMagic.C:
+     - removed unnecessary MReadTree
+
+
+
+ 2001/11/28: Oscar Blanch Bigas
+
+   * mbase/MReadMarsFile.cc:
+     - Added process of fRun = new MReadTree("RunHeaders", fname),
+       needed to read RunHeaders tree information.
+
+   * manalysis/MCerPhotCalc.h:
+     - Added fNumLoGainFadcSlices and fNumHiGainFadcSlices member
+       variables because they are needed for Pedestal substraction.
+
+   * manalysis/MCerPhotCalc.h:
+     - Change in the methode to substract the pedestal. The new
+       methode is valid either for MC data and real data but only for
+       the current integration (GetSumHiGainSamples()).
+
+   * macros/readMagic.C:
+     - Added several tasks in the task list:
+	     MReadMarsFile to read  RunHeaders Tree
+	     MPedestalCopy and MPedestalNSB to treat correctly pedestals.
+
+   * macros/MagicHillas.C:
+     - Added several tasks in the task list:
+	     MReadMarsFile to read  RunHeaders Tree
+	     MPedestalCopy and MPedestalNSB to treat correctly pedestals.
+
+   * mmc/MMcRunHeader.hxx:
+     - Added GetNumPheFromDNSB().
+
+   * mmc/MMcFadcHeader.hxx:
+     - Added GetAmplitud().
+
+   * manalysis/MMcPedestalNSB.h / .cc:
+     - New class which adds to the pedestal rms the contribution from
+      the diffuse NSB.
+
+   * manalysis/Makefile:
+     - New class MMcPedestalNSB added.
+
+   * manalysis/AnalysisLinkDefine.
+     - New class MMcPedestalNSB added.
+
+
+
+ 2001/11/16: Thomas Bretz
+
+   * mhist/MHMcCollectionArea.cc:
+     - set the ReadyToSave bit in CalcEfficiency.
+
+   * mmontecarlo/MMcThresholdCalc.cc:
+     - set the ReadyToSave bit after the calculation has been finished.
+
+   * mhist/MHMcRate.cc:
+     - set the ReadyToSave bit in CalcRate
+
+
+
+ 2001/11/16: Thomas Bretz
+
+   * mbase/MEvtLoop.cc:
+     - removed clock.Print()
+
+   * mbase/MGList.[cc,h]:
+     - added support for TGPictures
+
+   * mbase/MReadTree.[h,cc]:
+     - set ReadyToSave-bit only if reading was successfull
+     - made SetReadyToSave private
+
+   * mbase/MTaskList.cc:
+     - corrected a small bug in the output
+
+   * mbase/MWriteRootFile.cc:
+     - added a workaround in Print (don't know why it fails for me)
+     - removed fTrees.SetOwner()
+
+   * mbase/MTask.cc:
+     - removed include of TOrdCollection, TMethod
+     - some changes to the output
+
+   * mbase/MParContainer.h:
+     - removed old comments
+
+   * mmain/MAnalysis.cc, mmain/MCameraDisplay.cc, mmain/MDataCheck.cc,
+     mmain/MEvtDisp.cc, mmain/MMonteCarlo.cc:
+     - changed Widget IDs to root style enums
+     - moved enumerations in the range below 0x100
+
+   * mmain/MBrowser.[h,cc]:
+     - removed some of the member variables, accessed via MGList now
+     - changed TList to MGList
+     - added a file-filter combo-box
+
+   * mars.cc:
+     - changed output
+
+
+
+ 2001/11/15: Thomas Bretz
+
+   * mbase/MArray.cc, mbase/MArrayB.cc,mbase/MArrayS.cc,
+     mbase/MClone.cc, mbase/MEvtLoop.cc, mbase/MFilter.cc,
+     mbase/MFilterList.cc, mbase/MGGroupFrame.cc, mbase/MGList.cc,
+     mbase/MGTask.cc, mbase/MInputStreamID.cc, mbase/MLog.cc,
+     mbase/MLogManip.cc, mbase/MParContainer.cc, mbase/MParList.cc,
+     mbase/MPrint.cc, mbase/MReadMarsFile.cc, mbase/MReadTree.cc,
+     mbase/MTime.cc, mbase/MWriteAsciiFile.cc, mbase/MWriteFile.cc,
+     mbase/MWriteRootFile.cc, manalysis/MCT1ReadAscii.cc,
+     manalysis/MCerPhotCalc.cc, manalysis/MHillas.cc,
+     manalysis/MHillasCalc.cc, manalysis/MMcPedestalCopy.cc,
+     manalysis/MPedCalcPedRun.cc, manalysis/MPedestalCam.cc,
+     manalysis/MPedestalPix.cc, manalysis/MCerPhotEvt.cc,
+     manalysis/MCerPhotPix.cc, manalysis/MImgCleanStd.cc,
+     manalysis/MImgCleanStd.cc, mdatacheck/MDumlEvtHeader.cc,
+     mdatacheck/MGDisplayAdc.cc, meventdisp/MGCamDisplay.cc,
+     meventdisp/MGEvtDisplay.cc, meventdisp/MGFadcDisp.cc,
+     mfilter/MFTriggerLvl1.cc, mgui/MGeomCam.cc, mgui/MGeomCamMagic.cc,
+     mgui/MGeomCamCT1.cc, mgui/MgeomPix.cc, mgui/Mhexagon.cc,
+     hist/MFillH.cc, mhist/MH.cc, mhist/MHFadcCam.cc, mhist/MHFadcPix.cc,
+     hist/MHHillas.cc, mhist/MHMcCollectionArea.cc, mhist/MHMcEnergy.cc,
+     mhist/MHMcRate.cc, mhist/MHStarMap.cc, mmain/MAnalysis.cc,
+     mmain/MBrowser.cc, mmain/MCameraDisplay.cc, mmain/MDataCheck.cc,
+     mmain/MEvtDisp.cc, mmain/MMars.cc, mmain/MMonteCarlo.cc,
+     mmontcarlo/MMcCollectionAreaCalc.cc, mmontecarlo/MMcThresholdCalc.cc,
+     mmontecarlo/MMcTriggerRateCalc.cc, mraw/MrawCrateArray.cc,
+     mraw/MRawCrateData.cc, mraw/MRawEvtData.cc, mraw/MRawEvtHeader.cc
+     mraw/MRawEvtPixelIter.cc, mraw/MRawEvtFileRead.cc, 
+     mraw/MRawEvtFileWrite.cc, mraw/MRawEvtRunHeader.cc
+     - changed mailing address of author according to THtml of root 3.02
+
+   * mbase/MClone.cc, mbase/MEvtLoop.cc, mbase/MFilterList.cc,
+     mbase/MGTask.cc, mbase/MParContainer.cc, mbase/MParList.cc,
+     mbase/MPrint.cc, mbase/MReadMarsFile.cc, mbase/MReadTree.cc,
+     mbase/MWriteAsciiFile.cc, mbase/MWriteFile.cc,
+     mbase/MWriteRootFile.cc, manalysis/MCerPhotEvt.cc, 
+     manalysis/MCerPhotPix.cc, manalysis/MImgCleanStd.cc,
+     mgui/MGeomCam.cc, mgui/MGeomCamMagic.cc, mgui/MGeomCamCT1.cc, 
+     mgui/MgeomPix.cc, mgui/Mhexagon.cc, hist/MFillH.cc, mhist/MHMcEnergy.cc,
+     mhist/MHMcRate.cc, mmontcarlo/MMcCollectionAreaCalc.cc,
+     mmontecarlo/MMcThresholdCalc.cc, mmontecarlo/MMcTriggerRateCalc.cc
+     mraw/MRawCrateData.cc, mraw/MRawEvtData.cc, mraw/MRawEvtHeader.cc
+     mraw/MRawEvtPixelIter.cc, mraw/MRawEvtFileRead.cc, 
+     mraw/MRawEvtFileWrite.cc, mraw/MRawEvtRunHeader.cc
+     - changed output to new style logging (verbosity level introduced)
+
+   * mbase/MGTask.h:
+     - added default to CreateGui
+
+   * mbase/MLog.cc
+     - chnaged comparision between output and debug level from >= to >
+
+   * mbase/MLogManip.h:
+     - added defintions for debug levels
+
+   * mbase/MReadTree.[h,cc]:
+      - added support for filters
+      - SetReadyToSave added
+      - Print added
+
+   * mbase/MTaskList.[h,cc], MTask.[h,cc]:
+     - changed TOrCollection to TList, because TList can be stored in a 
+       root file.
+
+   * mbase/MTask.[h,cc]:
+     - added GetFilter function (used in MReadTree)
+
+   * manalysis/MImgCleanStd.cc:
+     - same changed to the GUI layout
+     - added Print member function
+
+   * meventdisp/MGCamDisplay.cc:
+     - added group frame around some gui elements
+
+   * mfilter/MFTriggerLvl1.cc:
+     - fixed missing Init call
+     - added missing AddToBranchList call
+
+   * mars.cc:
+     - added command line option to set the verbosity level
+
+   * merpp.cc:
+     - added setup for highest verbosity level
+
+
+
+ 2001/11/14: Thomas Bretz
+
+   * macros/dohtml.C:
+     - added missing path to mfilter
+   
+   * manalysis/MHillas.cc:
+     - changed the degree symbol back to 'deg', it seems that the code
+       for it isn't common
+   
+   * mhist/MH.cc:
+     - added comment for MakeDefCanvas
+
+   * mhist/MHFadcCam.[h,cc]:
+     - removed old comments (SaveHist)
+
+   * mhist/MHHillas.cc:
+     - changed the Name of fAlpha back. Symbols are nonsens in the name.
+     
+   * mbase/MGList.[h,cc], mbase/MGTask.[h,cc], mbase/MGGroupFrame.[h,cc]:
+     - added
+
+   * Makefile.conf.linux, Makefile.conf.linux-gnu:
+     - changed to O3
+     - added -fnonnull-objects
+     - added -Woverloaded-virtual
+
+   * macros/readCT1.C, macros/readMagic.C:
+     - changed to use MClone
+
+   * manalysis/MImgCleanStd.[h,cc]:
+     - derived from TGTask
+     - added CreateGuiElements 
+     - added ProcessMessage
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MGTask
+     - added MGList
+     - added MGGroupFrame
+
+   * mbase/MInputStreamID.cc:
+     - rmoved old comment
+
+   * mbase/MParContainer.[h,cc]:
+     - changed output
+     - made Hash const
+     - added GetDiscriptor
+
+   * mbase/MParList.[h,cc]:
+     - made FindObject const correct (see TObject)
+
+   * mbase/MTask.[h,cc]:
+     - changed output to use GetDescriptor
+     - made Call* functions virtual (used in TGTask)
+
+   * mbase/MTaskList.[h,cc]:
+     - made FindObject const correct (see TObject)
+     - changed output to use GetDescriptor
+
+   * mbase/MTime.cc:
+     - code reformatting
+
+   * mbase/MWriteRootFile.cc:
+     - small changes in output
+
+   * mgui/MHexagon.cc:
+     - changed output according to TEllipse and similar
+     - made ls const
+
+   * mhist/MFillH.cc:
+     - changed output to use GetDescriptor
+
+   * mmain/MAnalysis.[h,cc]:
+     - changed to use new GUI of MImgCleanStd
+
+   * mraw/MRawEvtData.cc:
+     - small changes to output
+     - better sanity check for non existing fRunHeader
+
+
+
+ 2001/11/09: Thomas Bretz
+
+   * mars.cc, merp.cc, macros/rootlogon.C:
+     - added MArray::Class()->IgnoreTObjectStreamer();
+
+
+
+ 2001/11/08: Thomas Bretz
+
+   * meventdisp/MGCamDisplay.cc:
+     - changed enums to root style
+     - get rid of the problem of button deletion by adding the buttons 
+       as first entries to the list
+
+   * mmain/MMonteCarlo.cc:
+     - changed enums to root style
+     - get rid of the problem of button deletion by adding the buttons 
+       as first entries to the list
+
+   * manalysis/MCerPhotCalc.cc, manalysis/MPedCalcPedRun.cc,
+     mhist/MHFadcCam.cc:
+     - removed 'Fadc' from function names
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - made AddPixel inline
+   
+   * manalysis/MMcPedestalCopy.cc:
+     - added output
+
+   * manalysis/MPedestalCam.cc:
+     - removed FIXME
+
+   * Makefile's:
+     - some reordering
+     - changed to the output
+
+   * mbase/MReadTree.cc:
+     - removed setting of AutoDel-flag (this was not intended and doesn't
+       work for a TChain, yet)
+
+   * meventdisp/MGCamDisplay.cc, meventdisp/MGFadcDisp.cc:
+     - moved SetWMSizeHints to base class
+
+   * meventdisp/MGEvtDisplay.cc:
+     - added a random move and the SetWMSizeHints
+
+   * mhist/MHHillas.cc:
+     - replaced some text by Latex-formulas
+
+   * mmain/MBrowser.cc:
+     - added a menu entry for opening a TBrowser
+     - added a random move
+
+   * mmain/MMars.[h,cc]:
+     - changed enums to root style
+     - moved size specification from header to source
+     - changed SetWMSizeHints call
+
+   * mraw/MrawEvtPixelIter.[h,cc]:
+     - added fNum[Hi,Lo]GainSamples to make GetSum* faster
+     - removed 'Fadc' from function names
+
+
+
+ 2001/11/07: Thomas Bretz
+
+   * Makefile:
+     - changed order in 'mrproper'
+
+   * manalysis/MCT1ReadAscii.cc, manalysis/MCerPhotCalc.cc:
+     - added InitSize
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - introduces InitSize to speed up things
+     - changed []-operator to an unchecked access
+
+   * manalysis/MPedestalCam.h:
+     - changed ExpandCreateFast to ExpandCreate (due to lack of good dox)
+     - changed []-operator to an unchecked access
+
+   * mbase/MEvtLoop.cc:
+     - changed 'total' to 'real' time.
+
+   * mgui/MGeomCam.[h,cc]:
+     - moved []-operator code back to class definition, due to runtime speed
+     - changed []-operator to an unchecked access
+
+   * mhist/MHHillas.cc:
+     - changed 'degree' to Latex-style
+
+   * manalysis/MImgCleanStd.cc:
+     - we are now initialising an array holding the used pixel to prevent
+       looping through all pixel thousands of times
+       (MCerPhotEvt::IsPixelUsed)
+
+   * mbase/MWriteAsciiFile.cc:
+     - enhanced the documentation
+
+   * mmain/MBrowser.[h,cc]:
+     - enhanced the functionality to display the filename
+     - improved the layout
+
+   * mmain/MMars.cc:
+     - added calling of 'netscape' for the two picture buttons
+
+
+
+ 2001/11/06: Thomas Bretz
+
+   * mbase/MReadMarsFile.[h,cc]:
+     - added
+
+   * manalysis/MMcPedestalCopy.[h,cc]:
+     - moved copying to PreProcess
+     - removed Process
+
+   * mbase/Makefile, mbase/BaseLinkDef.h
+     - added MReadMarsFile
+
+   * mbase/MReadTree.[h,cc]:
+     - added a list of TObjects to be called when file in the chain 
+       is changed
+
+   * Makefile.conf.linux, Makefile.conf.linux-gnu:
+     - removed -g flag
+
+   * mraw/MRawRunHeader.h:
+     - fixed return type of GetNumEvents
+
+   * mraw/MRawCrateArray.[h,cc]:
+     - added SetSize which takes care of the size of the array
+     - changed the access to an unchecked one
+
+   * mraw/MRawCrateData.h
+     - derives from MParContainer now
+
+   * mraw/MRawEvtData.[h,cc]:
+     - made Print const
+     - changed so, that the arrays are dreed and allocated only
+       as less as possible
+
+   * mraw/MRawFileRead.[h,cc]:
+     - changed to support faster I/O of MRawEvtData and MRawCrateArray
+     - added sanity check (warning) to PostProcess
+
+   * mraw/MRawFileWrite.cc:
+     - removed deletion of trees (done by ~TFile)
+     - switched of AutoSave by use of a big size
+     - removed '.' from Branch names (each tree contains only one master
+       branch with equal subbranches)
+
+   * macros/readCT1.C:
+     - fixed a small bug
+
+   * manalysis/MCerPhotCalc.cc:
+     - removed Clear from Process (done by Reset now)
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added reset-function
+     - some small changes to the code layout
+
+   * mmc/MMcFadcHeader.[h,cc], mmc/MMcTrig.[h,cc]:
+     - chenged constructor to support fName and fTitle
+
+   * mbase/MReadTree.cc:
+     - removes '.' from a branch name now before searching/creating the object
+
+
+
+ 2001/11/01: Thomas Bretz
+ 
+   * mbase/MParContainer.cc:
+     - removed 'newname' from TObject::Clone call.
+
+   * mbase/MParContainer.h:
+     - layout changes
+
+   * mbase/MParList.h:
+     - changed destructor definition to virtual
+
+   * mbase/MReadTree.[h,cc]:
+     - added initialization for fProgress
+     - changed output
+     - move some code to new functions
+     - branch enabling now checks for the existance of the branch
+     - veto branch disables the corresponding sub branches now physically
+     - changed comments
+
+   * mdatacheck/MGDisplayAdc.cc:
+     - added some sanity checks
+
+   * meventdisp/MGCamDisplay.cc, meventdisp/MGEvtDisplay.[h,cc],
+     meventdisp/MGFadcDisp.cc:
+     - moved some code to MGEvtDisplay
+
+   * mhist/MFillH.cc:
+     - added warning to comment
+
+   * mhist/MHFadcCam.[h,cc]:
+     - added Clone-function. It seems, that this is necessary since 
+       root 3.01
+
+   * mhist/MHFadcPix.cc:
+     - changed axis titles
+
+   * mmain/MAnalysis.cc:
+     - added progress bar
+
+   * mmain/MBrowser.[h,cc]:
+     - added layout hints to fTop1,2,3
+     - adde Create/DestroyProgrssBar
+
+   * mmain/MDataCheck.cc:
+     - changes to the layout
+     - disable auto scheme
+     - added progress bar
+
+   * mmain/MMonteCarlo.[h,cc]:
+     - layout changes
+     - added progress bar
+     
+   * mraw/MRawEvtData.cc:
+     - new sanity check in Draw
+
+
+
+ 2001/11/01: Thomas Bretz
+
+   * macros/MagicHillas.C:
+     - changed Draw to DrawClone
+
+   * manalysis/MCerPhotPix.h:
+     - some layout changes
+
+   * mbase/MParList.cc: 
+     - fixed a bug in the dstructor which causes the d'tor to crash when
+       the owner bit was set
+     - changed some TCollection loop to macro ForEach
+
+   * mbase/MTaskList.cc:
+     - changed some TCollection loop to macro ForEach
+
+   * meventdisp/MGEvtDisplay.[h,cc]:
+     - added filemenu
+
+   * mgui/MCamDisplay.[h,cc], mgui/MHexagon.[h,cc]:
+     - added SavePrimitive function
+
+   * mhist/MHHillas.cc:
+     - changed 'deg' to '°'
+
+   * mmain/MDataCheck.cc:
+     - changed name of enums for buttons
+
+   * Makefile.conf.osf1:
+     - added some more exclusion flags to get rid of to much informations
+
+   * Makefile:
+     - changed flags of tar from '-cvf' to 'cvf' so that it runs on alpha, too
+
+   * mbase/MAGIC.h:
+     - put brackets around defines, to make it compile on alpha
+
+   * mbase/MEvtLoop.cc, mbase/MParList.cc, mbase/MTask.cc, 
+     mgui/MGeomCam.cc, mhist/MHFadcPix.cc, mmc/MMcTrig.cxx:
+     - removed inline statement, to make it link on alpha
+
+
+
+ 2001/10/31: Thomas Bretz
+
+   * Makefile:             
+     - changed MrProper output   
+
+   * Makefile.conf.general, Makefile.conf.linux,
+     Makefile.conf.linux-gnu, Makefile.conf.osf:
+     - added ARCHDEF environment
+
+   * manalysis/MHillas.[h,cc]:
+     - added units
+
+   * mbase/BaseLinkDef.h:
+     - added '+' for MTime
+
+   * mbase/MAGIC.h:
+     - let Linux find gLog when creating dictionary
+
+   * mbase/MHtml.h:
+     - removed include of TNamed
+
+   * */Makefile
+     - reordered *.cc filed to get rid of some 'rootcint' warnings
+
+   * mgui/MCamDisplay.cc:
+     - added SetBorderMode(0)
+   
+   * mgui/MHexagon.[h,cc]:
+     - changed Print-output to fit into two lines
+     - made Print appear in the context menu
+
+   * merpp.cc:
+     - Added MParContainer::Class()->IgnoreTObjectStreamer()
+
+   * mbase/MEvtLoop.[h,cc],  mbase/MReadTree.[h,cc],
+     mmain/MAnalysis.[h,cc]:
+     - added support for a progressbar
+
+   * mbase/MFilterList.h:
+     - added SetOwner-support
+
+   * mbase/MLogManip.h:
+     - added 'dec' manipulator to dbginf
+
+   * mbase/MTask.h:
+     - added GetNumExecutions
+
+   * mraw/RawLinkDef.h:
+     - added '+' for MRawEvtPixelIter, MRawCrateArray, MRawCrateData and
+       MRawFile[Read,Write]
+
+
+
+ 2001/10/30: Thomas Bretz
+
+   * macros/MagicHillas.C
+     - removed precreated objects
+
+   * macros/readCt1.C:
+     - fixed a bug (-> instead of .)
+
+   * *LinDef.h:
+     - added a '+' to all 'new' classes. 'new' means, that the object
+       is not yet used in Monte Carlo Files.
+
+   * *.h:
+     - changed defines from CLASS_H to MARS_Class type (like root)
+
+   * MMcPedestalCopy.[h,cc]:
+     - added AddToBranchList stamements
+
+   * manalysis/MPedestalPix.h, manalysis/MCerPhotPix.h, mgui/MGeomPix.h:
+     - changed derivement from TObject to MParContainer to be sure
+       fBits are not written, without specifying this for any TObject
+       derived class
+
+
+
+ 2001/10/29: Thomas Bretz
+
+   * Makefile.rules:
+     - changed the output
+
+   * macros/rootlogon.C:
+     - Added IgnorTObjectStreamer
+
+   * manalysis/MCT1ReadAscii.cc:
+     - changed fFileNames to a TList of TNamed objects
+
+   * mbase/MArray.h:
+     - removed include of MArray.h
+
+   * mbase/MParContainer.[h,cc]:
+     - changed fName, fTitle from pointer to static object
+     - Changed ClassVersion to 0
+
+   * mbase/MParList.[h,cc]:
+     - changed fName, fTitle from pointer to static object
+     - changed include of TObjArray to a forward declaration
+       (for faster compilation)
+     - simplified the code
+
+   * mbase/MInputStreamID.[h,cc]:
+     - changed fStreamId from char* to TString
+     - Changed ClassVersion to 0
+ 
+   * mbase/MReadTree.[h,cc]:
+     - changed veto-list to an array of TNamed objects
+     - implemented auto enabeling
+
+   * mbase/MTask.[h,cc]:
+     - implemented fListOfBranches for auto enabeling
+     
+   * mbase/MTaskList.[h,cc]:
+     - changed fName, fTitle from pointer to static object
+     - changed include of TObjArray to a forward declaration
+       (for faster compilation)
+
+   * mbase/MWriteRootFile.cc:
+     - changed fName, fTitle from pointer to static object
+     - set splitlevel in TTree::Branch to default
+     - changed kSaveNow to kFillTree
+
+   * mhist/MFillH.cc:
+     - changed fName, fTitle from pointer to static object
+     - check inharitance from MH
+
+   * mhist/MH.[h,cc]:
+     - changed fName, fTitle from pointer to static object
+     - implementation of simplified static MakeDefCanvas
+
+   * mhist/MHFadcCam.h:
+     - removed include of TH1
+
+   * mhist/MHFadcPix.[h,cc]:
+     - implemented persistent pixid
+     - get rid of 'fixed string sizes'
+     - Delete histograms from file structure (SetDirectory)
+     - changed Root's MakeDefCanvas to TH1::MakeDefCanvas
+     - removed include of TH1
+
+   * mhist/MHHillas.cc
+     - changed fName, fTitle from pointer to static object
+     - Delete histograms from file structure (SetDirectory)
+     - changed Root's MakeDefCanvas to TH1::MakeDefCanvas
+     - changed DrawClone to DrawCopy
+
+   * mhist/MHMcCollectionArea.[h,cc]:
+     - changed fName, fTitle from pointer to static object
+     - Delete histograms from file structure (SetDirectory)
+     - changed Root's MakeDefCanvas to TH1::MakeDefCanvas
+     - changed DrawClone to DrawCopy
+     - changed binning to log scale
+     - removed include of TH1
+
+   * mhist/MHMcEnergy.cc, mhist/MHStarMap.cc:
+     - changed fName, fTitle from pointer to static object
+     - Delete histograms from file structure (SetDirectory)
+     - changed Root's MakeDefCanvas to TH1::MakeDefCanvas
+
+   * manalysis/MCerPhotEvt.cc, manalysis/MHillas.cc, 
+     manalysis/MHillasCalc.cc, manalysis/MImgCleanStd.cc, 
+     manalysis/MMcPedestalCopy.cc, manalysis/MPedestalCam.cc,
+     mbase/MClone.cc, mbase/MPrint.cc, mbase/MTime.h,
+     mbase/MWriteAsciiFile.cc, mgui/MGeomCam.cc, mhist/MHFadcCam.cc, 
+     mhist/MHMcRate.cc, mmc/MMcTrig.cxx, mraw/MRawCrateArray.cc, 
+     mraw/MRawEvtData.cc, mraw/MRawEvtHeader.cc, mraw/MRawFileRead.cc:
+     - changed fName, fTitle from pointer to static object
+
+   * manalysis/MCerPhotCalc.cc, manalysis/MPedCalcPedRun.cc, 
+     mmontecarlo/MMcThresholdCalc.[h,cc], 
+     mmontecarlo/MMcTriggerRateCalc.[h,cc], 
+     mmontecarlo/MMcCollectionAreaCalc.[h,cc]:
+     - changed fName, fTitle from pointer to static object
+     - changed to use auto enabling scheme
+
+   * macros/threshold.C, macros/collarea.C, macros/trigrate.C:
+     - removed UseLeaf
+
+   * macros/CT1Hillas.C, macros/readMagic.C:
+     - made run again
+
+   * mraw/MRawFileWrite.cc:
+     - changed fName, fTitle from pointer to static object
+     - changed TTree::Branch to use default split level (99)
+     - added the missing important '.' to the Branch names!
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - changed fName, fTitle from pointer to static object
+     - implemented enum for Run Type
+
+
+
+ 2001/10/26: Thomas Bretz
+
+   * Makefile.rules:
+     - changed output
+
+   * readraw.cc:
+     - changed name and description in TROOT
+     - removed argument in MMcEvt::Print()
+
+   * manalysis/MCerPhotEvt.[h,cc], manalysis/MCerPhotPix.[h,cc],
+     manalysis/MHillas.[h,cc], mmc/MMcEvt.[hxx,cxx],
+     mmc/MMcFadcHeader.[hxx,cxx], mmc/MMcTrig.[hxx,cxx],
+     mmc/MMcTrigHeader.[hxx,cxx]:
+     - according to root 3.01 made Print const
+
+   * mbase/BaseLinkDef.h:
+     - added MPrint
+
+   * mbase/MPrint.[h,cc]:
+     - added
+
+   * mbase/MClone.[h,cc]:
+     - changed MParContainer to a more general TObject
+
+   * mbase/Makefile:
+     - MPrint.cc added
+
+   * meventdisp/MGCamDisplay.[h,cc], meventdisp/MGEvtDisplay.[h,cc],
+     meventdisp/MGFadcDisp.[h,cc]:
+     - introduced fInitOk for the case PreProcessing failed
+
+   * mmain/MMonteCarlo.cc:
+     - added correction for use of several trigger conditions
+     - speedup threshold calc by usage of UseLeaf
+
+   * magiclogo.xpm, marslogo.xpm:
+     - changed
+
+   * mmain/MMonteCarlo.cc:
+     - added a workaround for the <TClass::TClass> no dictionary for MMc*
+       problem
+
+   * mbase/MWriteRootFile.[h,cc]:
+     - simplified code by removing MRootFileTree class
+
+   * mbase/MLog.cc:
+     - changed char[len+1] to 'new' statement
+
+
+
+
+ 2001/10/23: Thomas Bretz
+
+   * mbase/MLog.[h,cc]:
+     - replaced usage of tmpnam by mkstemp
+
+   * mgui/MCamDisplay.[h,cc]:
+     - Paint function added which maintains the aspect ratio of the image
+     - DrawPhotErr removed
+     - removed gPad->Clear, so that we can draw into pads not only
+       canvases
+
+   * mhist/MFillHFadc.[h,cc], mhist/MFillHHillas.[h,cc],
+     mhist/MFillHStarMap.[h,cc]:
+     - removed
+
+   * mmontecarlo/MMcTriggerRateCalc.[h,cc]:
+     - removed unused spectral index and flux
+
+   * mmontecarlo/MMcThesholdCalc.[h,cc],:
+     mbase/MParList.[h,cc]:
+     - fixed the Dimension handling
+
+   * mmontecarlo/MMcTriggerRateCalc.[h,cc],
+     - fixed the Dimension handling
+     - added destructor
+
+   * macros/trigrate.C:
+     - fixed some small things
+     - accelerated by use of MReadTree::UseLeaf
+
+   * mhist/MHMcCollectionArea.h:
+     - changed default argument of DrawClone from NULL to "".
+       NULL caused the interpreter to crash.
+
+   * mbase/MFilterList.[h,cc], mbase/MParContainer.[h,cc],
+     mbase/MParList.[h.cc], mbase/MTime.[h,cc],
+     mgui/MGeomCam.[h,cc], mgui/MGeomPix.[h,cc],
+     mgui/MHexagon.[h,cc], mhist/MHMcEnergy.[h,cc],
+     mhist/MHMcRate.[h,cc], mraw/MRawCrateData.[h,cc],
+     mraw/MRawEvtHeader.[h,cc], mraw/MRawRunHeader.[h,cc]:
+     - according to root 3.01 I made Print() const
+
+   * mdatacheck/MViewAdcSoectra.[h,cc], mdatacheck/MShowSpect.[h,cc]:
+     - removed
+
+   * mbase/MReadTree.cc:
+     - removed default argument from GetEntry-call
+
+   * mbase/MTask.[h,cc]:
+     - introduced mapping function for (Pre/Post)&Process
+     - according to root 3.01 I made Print() const
+     - added PrintStatistics
+     - added call counter
+
+   * mbase/MTaskList.[h,cc]:
+     - adapted to new MTask mapping functions
+     - according to root 3.01 I made Print() const
+     - added PrintStatistics
+     - moved some functionality to MTask-Mapper functions
+
+   * mmain/MMonteCarlo.cc:
+     - adapted to some changes in other classes
+     - some small simplifications
+     - accelerated, by use of UseLeaf
+     - workaround for the ButtonGroup/Button delete bug
+
+   * mmain/MAnalysis.cc:
+     - workaround for the ButtonGroup/Button delete bug
+
+
+
+ 2001/10/23: Thomas Bretz
+
+   * macros/dohtml.C:
+     - changed macro names
+
+   * macros/getCollArea.C:
+     - renamed to collarea.C
+     - make use of new fast MReadTree
+
+   * macros/getRate.C:
+     - renamed to trigrate.C
+
+   * macros/getThreshold.C:
+     - renamed to threshold.C
+
+   * Makefile.depend:
+     - removed
+
+   * mgui/MCamDisplay.[h,cc]:
+     - fixed wrong usage of new operator in TClonesArray
+     - the aspect ratio of the Canvas is used now to display geometries
+       correctly (no 'small CT1 camera anymore)
+     - replaced include of MCerPhotPix by a forward declaration
+     - replaced include of MHexagon by a forward declaration
+
+   * mgui/MGeomCam.[h,cc]:
+     - added GetMaxRadius()-function
+     - added CalcMaxRadius()-function
+     - replaced include of MGeomPix by a forward declaration
+     - replaced include of TObjArray by a forward declaration
+
+   * mgui/MGeomCamMagic.cc, mgui/MGeomCamCT1.cc:
+     - call CalcMaxRadius in the constructor
+
+
+
+ 2001/10/22: Thomas Bretz
+
+   * mhist/MH*.[h,cc]:
+     - changed DrawClone according to root 3.01/06 to 'const'
+
+
+
+ 2001/10/16: Thomas Bretz
+
+   * mbase/MReadTree.[h,cc]:
+     - added some output statements
+     - added comments
+     - added UseLeaf
+     - changed AddFile to Int_t
+     - simplified GetEntry call
+
+   * mgui/MGeomCam.[h,cc], MGeomCamCT1.[h,cc], MGeomCamMagic.[h,cc]:
+     - added come comments
+     - removed Draw-function
+   
+   * mars.cc:
+     - Changed name of TROOT object to 'mars'
+
+   * merpp.cc:
+     - changed name of TROOT object to 'merpp'
+     - added some more ouput
+
+   * mbase/MBaseLinkDef.h:
+     - added MRootFileBranch
+     - added MRootFileTree
+
+   * mgui/MGeomPix.cc, mbase/MClone.cc, mraw/MRawRunHeader.cc:
+     - added comments
+
+   * mbase/MEvtLoop.cc:
+     - added missing include
+     - added another time output
+
+   * mbase/MWriteRootFile.cc:
+     - added ClassImp
+   
+   * mhist/MFillH.cc, mmontecarlo/MMcCollectionAreaCalc.cc:
+     - changed output
+   
+   * mhist/MHMcCollectionArea.cc:
+     - small fixes
+     - changed error calculation according to Ciro
+
+   * macros/CT1Hillas.C:
+     - fixes some bugs (typos)
+
+
+
+ 2001/10/05: Thomas Bretz
+
+   * manalysis/MHillas.cc, manalysis/MImgCleanStd.cc, mbase/MClone.[h,cc],
+     mbase/MFilterList.h, mbase/MWriteFile.h, mbase/MWriteRootFile.h,
+     mdatacheck/MGDisplayAdc.cc, meventdisp/MGCamDisplay.cc, 
+     meventdisp/MGCamDisplay.h, meventdisp/MGEvtDisplay.h,
+     mgui/MGeomPix.h, mhist/MFillH.h, mhist/MHHillas.h,
+     mmain/MAnalysis.h, mmain/MBrowser.h, mmain/MCameraDisplay.h,
+     mmain/MDataCheck.h, mmain/MEvtDisp.h, mmain/MMonteCarlo.h,
+     mraw/MRawFileRead.cc
+     - comments updated
+     
+   * mbase/MFilter.[h,cc]:
+     - made IsExpressionTrue abstract
+     
+   * meventdisp/MGEvtDisplay.cc:
+     - fixed a bug that only every second event was displayed
+
+   * meventdisp/MGFadcDisp.[h,cc]:
+     - reorganized code (changing pixel number drawed the histogram twice)
+     
+   * mgui/MCamDisplay.[h,cc]:
+     - added fDrawingPad to make sure that all output goes into the same pad
+     
+   * mhist/HistLinkDef.h, mhist/Makefile:
+     - removed old MFillH* classes
+
+
+
+ 2001/10/02: Thomas Bretz
+
+   * mbase/MClone.[h,cc],
+     meventdisp/MGCamDisplay.[h,cc],
+     meventdisp/MGEvtDisplay.[h,cc],
+     mmain/MCameraDisplay.[h,cc]:
+     - added
+     
+   * macros/readMagic.C:
+     - fixed a  "'->' and '.' mixed bug"
+     
+   * manalysis/MCT1ReadAscii.cc:
+     - added initialisation of fIn
+     
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - made IsPixelExisting const
+     - made IsPixelCore const
+     - made IsPixelUsed const
+     - made GetNumPhotons[Min,Max] const
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MClone
+     
+   * mbase/MEvtLoop.[h,cc], mbase/MParList.[h,cc], mbase/MTaskList.[h,cc]:
+     - added SetOwner-support
+     
+   * mdatacheck/DataCheckLinkDef.h, mdatacheck/Makefile:
+     - removed MShowSpect
+     - removed MViewAdcSpect
+     
+   * mdatacheck/MDumpEvtHeader.cc:
+     - added missing descriptions
+     
+   * mdatacheck/MGDisplayAdc.[h,cc]:
+     - small changes
+     
+   * meventdisp/EvtDispLinkDef.h:
+     - added MGEvtDisplay
+     - added MGCamDisplay
+     
+   * meventdisp/MGFadcDisp.[h,cc]:
+     - derived from MGEvtDisplay
+     - most of the code moved to MGEvtDisplay to support MGCamDisplay, too
+     
+   * meventdisp/Makefile:
+     - added MGCamDisplay
+     
+   * mgui/MCamDisplay.[h,cc]:
+     - cleaned
+     - reorganized
+     
+   * mgui/MHexagon.cc:
+     - added missing descriptions
+     
+   * mhist/MHFadcPix.cc:
+     - reorganized some code in the constructor which creates the 'names'
+     
+   * mhist/MHHillas.cc, mhist/MHMcCollectionArea.cc, 
+     mhist/MHMcEnergy.cc, mhist/MHStarMap.cc:
+     - Draw-function supports a default canvas now
+   
+   * mmain/MDataCheck.cc:
+     - added/rorganized comments
+     - removed usage of MViewAdcSpectra
+     
+   * mmain/MMars.[h,cc]:
+     - added new "Camera Display" Button
+     
+   * mmain/MainLinkDef.h, mmain/Makefile:
+     - added MCameraDisplay
+
+
+
+ 2001/09/28: Thomas Bretz
+
+   * macros/getRate.C:
+     - changed TObjArray to a non-pointer object
+     - added Printing of the result at the end of the macro
+     
+   * mhist/MHMcCollectionArea.[h,cc], mhist/MHMcEnergy.[h,cc]:
+     - added DrawClone
+     
+   * mhist/MHMcRate.[h,cc]:
+     - added a dummy for DrawClone
+     
+   * mmain/MMonteCarlo.[cc, h]:
+     - added Gui elements
+     - added CalculateCollectionArea (not yet tested)
+     - added CalculateTriggerRate (not yet tested)
+     - added Threshold (not yet tested)
+
+   * mmontecarlo/MMcTriggerRateCalc.cc:
+     - removed output stuff from PostProcessing
+
+   * meventdisp/MGFadcDisp.[h,cc], mdatacheck/MGDisplayAdc.[h,cc]:
+     - reorganized code (constructor)
+     - reorganized deletion of gui objects
+     - fixed many, many memory leaks
+
+
+
+ 2001/09/27: Thomas Bretz
+
+   * mmain/MBrowser.cc:
+     - added comments
+
+   * mmain/MAnalysis.[h,cc]:
+     - added entry field for cleaning levels
+     - restructured code a bit
+
+   * mhist/MFillH.cc:
+     - fixed missing initialization of member variables in Init
+
+   * mhist/MHHillas.[h,cc]:
+     - Added comments
+     - Added DrawClone
+     - Removed kCanDelete bits from Draw function
+
+   * mhist/MHStarMap.[h,cc]:
+     - Added comments
+     - Added DrawClone
+     - moved some code from the Draw-functions to PrepareDrawing
+
+
+
+ 2001/09/26: Thomas Bretz
+
+   * mmain/MMars.[cc,h], mmain/MBrowser.[cc,h], MDataCheck.[cc,h],
+     mmain/MEvtDisp.[cc,h], mmain/MMonteCarlo.[cc,h]:
+     - reorganized code (constructor)
+     - reorganized deletion of gui objects
+     - fixed many, many memory leaks
+     - small changes in layout
+
+   * mmain/MAnalysis.[h,cc]:
+     - added
+
+   * macros/*:
+     - added Copyright notice
+     - added some small sanity checks
+
+   * macros/MagicHillas.C:
+     - fixed '->' bug
+     - changed MFillHStarMap to MFillH
+     
+   * mbase/MReadTree.cc, mraw/MRawFileWrite.cc:
+     - removed an old debug statement
+     
+   * mmain/MMars.cc:
+     - added new Analysis functionality
+     
+   * mmain/MainLinkDef.h:
+     - addded MAnalysis
+     
+   * mmain/Makefile:
+     - added MAnalysis.cc
+     
+   * mmc/McLinkDef.h:
+     - removed nonsens define statement
+
+
+
+ 2001/09/25: Thomas Bretz
+
+   * Makefile:
+     - changed make tar so that 'CVS/Root' isn't added to the tar-file anymore
+       It contains the origin (CVSROOT) of the repository and my confuse
+       people triing to commit changed files from such an archive to
+       the repository
+       
+   * mmain/MBrowser.[cc,h]:
+     - reorganized code (constructor)
+     - reorganized deletion of gui objects
+     - fixed many, many memory leaks
+
+   * mmain/MMars.[cc,h]:
+     - reorganized code (constructor)
+     - reorganized deletion of gui objects
+     - fixed many, many memory leaks
+
+
+
+ 2001/09/20: Thomas Bretz
+
+   * mbase/MLog.[h,cc]:
+     - made working with Cosy
+     - fixed gui stuff to work like expected
+
+   * manalysis/MCerPhotPix.h:
+     - replaced TROOT.h by MAGIC.h
+
+   * mfilter/MFTriggerLvl1.h:
+     - added description
+
+
+
+ 2001/09/20: Thomas Bretz
+
+   * released Version 0.4
+
+   * mevtdisp/MGFadcDisp.cc, mmain/MMars.cc:
+     - switched to root version >= 3.00
+     
+   * Makefile.conf.linux:
+     - added to support the new Linux distributions
+
+   * .rootrc:
+     - removed references to MARSSYS
+
+
+
+ 2001/09/13: Thomas Bretz
+ 
+   * Makefile.conf.linux-gnu:
+     - removed "-Woverloaded-virtual". it doesn't really help
+
+
+
+ 2001/08/02: Thomas Bretz
+
+   * macros/getRate.C:
+     - make use of new stylish lists of containers
+
+
+   * macros/CT1Hillas.C, macros/getCollArea.C:
+     - make use of return value of Eventloop
+
+   * macros/merpp.C:
+     - changed return type to void
+
+
+
+ 2001/07/23: Thomas Bretz
+ 
+   * mbase/MParList.cc:
+     - redifinition of default argument: fixed
+
+
+
+ 2001/07/23: Thomas Bretz
+ 
+   * mmontecarlo/MMcThresholdCalc.[cc,h]:
+     - changed PreProcess action to new stylish lists of containers
+
+   * mhist/Makefile:
+     - removed MEnergies.cc
+
+   * mhist/HistLinkDef.h:
+     - removed MEnergies.cc
+   
+   * mbase/MReadTree.cc:
+     - removed a bug which causes MReadTree to show strange behaviour.
+       We cannot use GetBranch()->SetAddress() we have to use
+       SetBranchAddress.
+       
+   * macros/MagicHillas.C:
+     - changed to new stylish histogram fillers.
+
+   * mhist/MHMcRate.cc:
+     - some simplifications to the constructors
+     - some accelerations of the rate calculation
+     
+   * mhist/MHHillas.C:
+     - added axis descriptions (thanks to Rudy)
+
+
+
+ 2001/07/20: Thomas Bretz
+ 
+   * mhist/MH.cc:
+     - added comments
+
+   * mhist/MFillH.cc:
+     - added comments
+
+   * mbase/MParList.[h,cc]:
+     - Added AddToList from a TObjArray
+     - Added GetClassName
+     - Added GetObjName
+     - Added FindObjectList
+     - Added FindCreateObjList
+     - Added CreateObjList
+
+   * mhist/MHMcEnergies.[h,cc]:
+     - deleted
+
+   * mhist/MHMcEnergy.[h,cc]:
+     - rewrote constructor in a way that MHMcEnergies isn't needed anymore
+     - added a SetName function which replaces the old constructor somehow
+
+   * macros/getThreshold.C:
+     - make use of some new features
+
+
+
+ 2001/07/19: Thomas Bretz
+ 
+   * mbase/MEvtLoop.cc:
+     - added comments
+     
+   * mbase/MTaskList.cc:
+     - changed the wrong 'break' for kCONTINUE into 'return kTRUE'
+     
+   * mhist/MH.[cc,h]
+     - added
+
+   * mhist/MFillH.[cc,h]
+     - added
+     - in principal MFillHHillas, MFillHFadc and MFillHStarMap
+       can be deleted now
+     
+   * mhist/HistLinkDef.h:
+     - added MH
+     - added MFillH
+     
+   * mhist/MFillHFadc.cc:
+     - moved source for filling to corresponding histogram class
+     
+   * mhist/MFillHHillas.cc:
+     - included MHillas.h
+     
+   * mhist/MHFadcCam.[cc, h]:
+     - added Fill
+     - made FillHi, FillLo private
+     
+   * mhist/MHHillas.[cc, h], mhist/MHStarMap.[h,cc]:
+     - changed Fill function to new style
+     - derived class from MH
+
+   * mhist/Makefile:
+     - added MH.cc
+     - added MFillH.cc
+
+
+
+ 2001/07/18: Oscar Blanch
+ 
+   * macros/getRate.C:
+     - Macro to compute the trigger rate from a MonteCarlo file
+
+   * mhist/MHMcRate.[h,cc]:
+     - Container to store trigger rate information
+     - Draw() functin member to be implemented
+
+   * mmontecarlo/MMcTriggerRateCalc.[h,cc]:
+     - Task to compute trigger rate
+
+
+
+ 2001/07/13: Thomas Bretz
+
+   * mbase/MEvtLoop.[h,cc]:
+     - Added a result value to Eventloop to be able to detect if the
+       execution was successfull
+     - changes postProcess to return the return value from 
+       MTaskList::PostProcess
+     
+   * mbase/MParList.cc:
+     - FindCreateObj removes now a 'dot' from the end of an indexed
+       object name like "Events;7."
+     
+   * mbase/MReadTree.cc:
+     - small changes to the output
+
+   * mbase/MTask.[h,cc]:
+     - added Preprocessed flag. This enables the tasklist to only postprocess
+       already preprocessed tasks
+
+   * mbase/MTaskList.cc:
+     - don't postprocess non preprocessed tasks
+   
+   * mhist/MHMcCollectionArea.cc:
+     - added descriptions to histrograms
+     - changed names of histograms
+     - added drawing of canvas to Draw-functions
+
+   * mhist/MHMcEnergy.[h,cc]:
+     - added variables to store the calculated result
+     - changed names and titles of histogram
+     - added axis titles to histogram
+     - moved result calculation into fit-function
+
+   * mmontecarlo/MMcCollectionAreaCalc.cc:
+     - added name of input container to be able to process another
+       container than "MMcTrig"
+
+   * mmontecarlo/MMcThresholdCalc.cc:
+     - removed trailing dot from container name creation
+   
+   * mhist/MMcThresholdCalc.cc:
+     - removed a wrong '.' behind the number when processing more than
+       one trigger condition
+
+   * mraw/MRawRunHeader.cc:
+     - added "Monte Carlo Data" as runtype
+
+
+
+ 2001/07/10: Thomas Bretz
+
+   * mhist/MHMcEnergy.h:
+     - renamed SetBins to SetNumBins
+     
+   * mmontecarlo/MMcThresholdCalc.cc:
+     - changed style of comments
+     - moved sqrt(2) from Postprocess to header.
+     
+   * mmontecarlo/MMcEnerHisto.[cc,h], mmontecarlo/MMcEnerThre.[cc,h], 
+     mmontecarlo/MMcEnerThreCalc.[cc,h]:
+     - removed
+
+   * mmontecarlo/MCollArea.[cc,h], mmontecarlo/MCollAreaTrigger.[cc,h]:
+     - removed
+
+
+
+ 2001/07/09: Thomas Bretz
+ 
+   * mbase/MParList.cc:
+     - made handling of already existing containers in AddToList a bit 
+       more convinient
+     
+   * mbase/MTaskList.[h,cc]:
+     - added come comments
+     - made handling of already existing tasks in AddToList a bit 
+       more convinient
+     - Added name-argument to constructor
+     
+   * mraw/MRawFileRead.[cc, h]:
+     - move file-open check from constructor to PreProcess
+     - added variable for filename
+     
+   * mraw/MRawFileWrite.[cc,h]:
+     - moved fOut->Write from PostProcess to destructor
+     - removed PostProcess
+
+
+
+ 2001/07/06: Thomas Bretz
+ 
+   * mfilter/FilterIncl.h, mfilter/FilterLinkDef.h, 
+     mfilter/MFTriggerLvl1.[h,cc], mfilter/mfilter/Makefile:
+     - added
+     
+   * Makefile
+     - mfilter added
+     
+   * Makefile.conf.linux-gnu:
+     - added some warning options
+     
+   * Makefile.conf.osf1:
+     - enhanced warnings
+     
+   * manalysis/MCerPhotEvt.cc:
+     - removed a small buf from the constructor
+     
+   * BaseLinkDef.h:
+     - added MFilter
+     - added MFilterList
+     
+   * mbase/MLog.[h,cc]:
+     - added a non-empty copy constructor to make cxx happy
+     
+   * mbase/MParList.[h,cc]:
+     - added second overload-function FindObject
+   
+   * mbase/MTask.h:
+     - added all Filter stuff
+     
+   * mbase/MTaskList.cc:
+     - changed debug output
+     - added filter-stuff to Process
+     
+   * mbase/MTaskList.h:
+     - changed Print default option from NULL to ""
+     
+   * mbase/Makefile:
+     - added MFilter
+     - added MFilterList
+   
+   * mhist/MFillHFadc.cc:
+     removed a small bug in the PreProcessing
+   
+   * manalysis/MCerPhotEvt.h, manalysis/MHillas.cc, manalysis/MHillas.h, 
+     manalysis/MImgCleanStd.cc, manalysis/MPedestalCam.h, mgui/MGeomCam.h,
+     mhist/MFillHHillas.h, manalysis/MHillasCalc.h, manalysis/MCerPhotCalc.h,
+     manalysis/MImgCleanStd.h, mhist/MFillHStarMap.h, mhist/MHHillas.cc,
+     mhist/MHHillas.h, mhist/MHStarMap.cc, mhist/MHStarMap.h,
+     mmc/MMcFadcHeader.hxx, mmc/MMcFadcHeader.hxx, mmc/MMcTrig.hxx,
+     mmontecarlo/MMcThresholdCalc.h:
+     - made more const-correct
+
+   * manalysis/MCT1ReadAscii.cc, manalysis/MCerPhotCalc.cc, 
+     manalysis/MHillasCalc.cc, manalysis/MImgCleanStd.cc,
+     manalysis/MMcPedestalCopy.cc, manalysis/MPedCalcPedRun.cc,
+     mhist/MFillHFadc.cc, mhist/MFillHHillas.cc, mhist/MFillHStarMap.cc,
+     mmontecarlo/MMcThresholdCalc.cc, mraw/MRawFileRead.cc,
+     mraw/MRawFileWrite.cc:
+     - added comments
+
+   * manalysis/MCT1ReadAscii.cc, manalysis/MCerPhotCalc.cc, 
+     manalysis/MCerPhotPix.cc, manalysis/MHillas.cc,
+     manalysis/MHillasCalc.cc, manalysis/MImgCleanStd.cc, 
+     manalysis/MMcPedestalCopy.cc, manalysis/MMcPedestalCopy.h,
+     manalysis/MPedCalcPedRun.cc, manalysis/MPedestalCam.cc, 
+     manalysis/MPedestalPix.cc,
+     mbase/MArray.cc, mbase/MArrayB.cc, mbase/MArrayS.cc, mbase/MEvtLoop.cc, 
+     mbase/MLog.cc, mbase/MParList.cc, mbase/MReadTree.cc, mbase/MTask.cc, 
+     mbase/MTime.cc, mbase/MWriteAsciiFile.cc, mbase/MWriteFile.cc, 
+     mbase/MWriteRootFile.cc,
+     mhist/MFillHFadc.cc, mhist/MFillHFadc.cc, mhist/MFillHHillas.cc,
+     mhist/MFillHStarMap.cc, mhist/MHFadcCam.cc, mhist/MHFadcPix.cc,
+     mhist/MHHillas.cc, mhist/MHMcCollectionArea.cc, mhist/MHMcEnergies.cc,
+     mhist/MHMcEnergy.cc, mhist/MHStarMap.cc, mraw/MRawCrateArray.cc,
+     mraw/MRawCrateData.cc, mraw/MRawEvtData.cc, mraw/MRawEvtHeader.cc,
+     mraw/MRawEvtPixelIter.cc, mraw/MRawFileRead.cc,
+     mraw/MRawFileWrite.cc, mraw/MRawRunHeader.cc:
+     - added semicolon after ClassImp to make my editor happy
+
+   * mmain/MEvtDisp.cc:
+     - removed a wrong comma in the enumerations
+     
+   * mmontecarlo/MMcThresholdCalc.cc:
+     - made compile on osf by removing brackets in new steatement (constructor)
+     
+
+
+ 2001/07/05: Thomas Bretz
+
+   * macros/CT1Hillas.C:
+     - changed the wrong pointers to dots.
+     
+   * macros/getThreshold.C:
+     - added some comments
+     - removed the canvas creation
+     - drawing replaced by a loop
+     - changed trigger conditions to 1 (should work with any MC file)
+     
+   * macros/readMagic.C:
+     - changed the event counter to the number of the event in the file
+     - removed icound
+     
+   * manalysis/MPedCalcPedRun.cc, manalysis/MCerPhotCalc.cc,
+     mbase/MParContainer.cc, mbase/MParContainer.h, mbase/MParList.cc,
+     mbase/MParList.h, mbase/MTaskList.cc, mbase/MWriteAsciiFile.cc,
+     mbase/MWriteRootFile.cc, mhist/MFillHFadc.cc, mhist/MFillHHillas.cc,
+     mhist/MFillHStarMap.cc,
+     - changed HasChanged to ReadyToSave
+     
+   * mbase/MReadTree.cc:
+     - added some comments
+     
+   * mhist/MHMcEnergies.h:
+     - fixed bug in []-operator
+     
+   * mhist/MHMcEnergy.cc:
+     - added canvas creation to draw function
+   
+   * mmontecarlo/MMcThresholdCalc.cc:
+     - fixed a bug in the constructor
+ 
+ 
+ 
+ 2001/06/20: Thomas Bretz
+ 
+   * macros/merpp.C:
+     - fixed type in comment
+     
+   * manalysis/MHillas.cc:
+     - fixed 'FIXME' comment
+   
+   * mbase/MWriteFile.[h,cc]:
+     - added
+  
+   * mbase/MWriteRootFile.[h,cc]:
+     - added
+   
+   * mbase/BaseLinkDef.h:
+     - Added MWriteFile
+     - Added MWriteRootFile
+   
+   * mbase/MEvtLoop.cc:
+     - fixed the counting in the eventloop
+     
+   * mbase/MWriteAsciiFile.[h,cc]:
+     - changed class that it is based on MWriteFile now
+   
+   * mbase/Makefile:
+     - added MWriteFile
+     - added MWriteRootFile
+   
+   * mhist/MFillHFadc.[h,cc]:
+     - added set for HasChanged (new PostProcess)
+   
+   * mhist/MFillHHillas.cc:
+     - added set for HasChanged (new PostProcess)
+   
+   * mhist/MFillHStarMap.cc:
+     - added set for HasChanged (new PostProcess)
+
+   * mhist/MHHillas.cc:
+     - Set kCanDelete to make sure, that the histograms are deleted
+       together with the canvas
+     
+   * mraw/MRawFileWrite.[h,cc]:
+     - changed the handling of opening, closing and checking file
+
+
+
+ 2001/06/13: Thomas Bretz
+
+   * ./.../*.h:
+     - added some comments and corrected some descriptions.
+     
+   * mbase/MParContainer.[h,cc]:
+     - added a 'dummy' function for AsciiRead, AsciiWrite
+
+   * mbase/MWriteAsciiFile.[h,cc]:
+     - added new constructor (specify directly the pointer to the class)
+
+   * mgui/MHexagon.cc:
+     - made Copy-function more readable
+
+   * mgui/MParContainer.cc:
+     - made Copy-function more readable
+
+   * mhist/MHMcEnergies.[h,cc]:
+     - files added as a container to make handling of several MHMcEnergy easier
+   
+   * mbase/MAGIC.h:
+     - encapsulated include of TROOT
+
+   * mbase/MTaskList.cc:
+     - added SetHasChange and Reset to PostProcess
+
+   * mhist/HistLinkDef.h
+     - added MHMcEnergies
+     
+   * mhist/MHMcEnergy.[h,cc]:
+     - added name and title to constructor
+     - added number to name of container
+   
+   * mmontecarlo/MMcThresholdCalc.cc:
+     - corrected typo in creation of the container names
+   
+   * mraw/MRawEvtData.cc:
+     - Set kCanDelete in Draw function
+
+
+
+ 2001/06/12: Thomas Bretz
+
+   * mmontecarlo/MMcEnerThreCalc.[cc,h] 
+     - copied to mmontecarlo/MMcThresholdCalc.[cc,h]
+
+   * mmontecarlo/MMcEnerThreHistos.[h,cc]
+     - copied to mmhist/MHMcEnergy.[h,cc]
+
+   * mbase/Makefile:
+     - added MWriteAsciiFile.cc
+   
+   * mhist/HistIncl.h:
+     - added TF1.h
+
+   * mhist/HistLinkDef.h:
+     - added MHMcEnergy
+ 
+   * mhist/Makefile
+     - added MHMcEnergy
+   
+   * mmontecarlo/MCollArea.h:
+     - fixed typo in ifndef
+   
+   * mmontecarlo/Makefile:
+     - added MMcThresholdCalc.cc
+     - removed MMcEnerHisto.cc
+     - removed MMcEnerThre.cc
+     - removed MMcEnerThreCalc.cc
+
+   * mmontecarlo/MonteCarloLinkDef.h:
+     - added MMcThresholdCalc.cc
+     - removed MMcEnerHisto.cc
+     - removed MMcEnerThre.cc
+     - removed MMcEnerThreCalc.cc
+ 
+   * mbase/MWriteAsciiFile.[h,cc]: 
+     - added
+
+   * manalysis/MCT1ReadAscii.h: 
+     - removed fFileName from class definition
+ 
+   * manalysis/MCerPhotCalc.cc: 
+     - use of SetHasChanged added
+ 
+   * manalysis/MHillas.[h,cc]: 
+     - Reset added
+     - AsciiRead added
+     - AsciiWrite added
+     - use of SetHasChanged added
+
+   * manalysis/MPedCalcPedRun.[h,cc]:
+     - made fNumHiGainSamples a class member
+     - renamed some member functions
+     - made the 'internal' member functions private
+     - added SetHasChanged
+     - made these functions const
+     
+   * mbase/BaseLinkDef.h
+     - MWriteAsciiFile added
+   
+   * mbase/MEvtLoop.cc:
+     - some small changes to the logging output
+   
+   * mbase/MParContainer.cc:
+     - fHasChanged added 
+   
+   * mbase/MParContainer.h:
+     - Reset prototype added
+     - HasChanged added
+     - SetHasChanged added
+   
+   * mbase/MParList.[cc,h]:
+     - SetHasChanged added
+     - Reset added
+   
+   * mbase/MTaskList.cc:
+     - Process: call SetHasChanged before looping
+     - Process: call Reset before looping
+   
+   * mbase/MTaskList.h:
+     - fParList added to class definition
+
+
+
+ 2001/04/27: Thomas Bretz
+
+   * macros/merpp.C:
+     - made the merpp-macro Mars 0.3 compatible
+
+
+
+ 2001/04/19: Thomas Bretz
+
+   * mbase/MParList.cc:
+     - added stripping of the string after last semicolon (classname)
+
+   * mbase/MReadTree.cc:
+     - added Veto funtionality to PreProcess
+     - added HasVeto
+     - added fVetoList
+     - added VetoBranch
+
+
+
+ 2001/04/18: Thomas Bretz
+
+   * mbase/MHtml.[cc.h]:
+     - Added
+     
+   * mbase/*.cc:
+     - changed comments of member functions to new MHtml-Style
+
+
+
+ 2001/04/09: Thomas Bretz
+
+   * mbase/MParList.cc:
+     - Added the possibility to specify a different object name in
+       FindCreateObj
+
+   * .rootrc:
+     - changed the style for the html documentation
+    
+   * macros/dohtml.C:
+     - added SetXwho
+    
+   * (*.cc):
+     - added the copyright comment block
+  
+   * mgui/MGeomCamMagic.cc:
+     - added some comments to all these numbers
+  
+   * mraw/MRawEvtPixelIter.h:
+     - added Jump member function which jumps directly to the pixel with a
+       given id
+      
+
+
+ 2001/04/09: Thomas Bretz
+
+   * mgui/MGeomPix.cc:
+     - fixed a small error in SetNeighbors (thanks to Oscar)
+     
+   * mgui/MGFadcDisp.[h,cc]:
+     - Fixed many small errors which caused the display to display nonsens
+       in some situations
+
+
+
+ 2001/04/04: Thomas Bretz
+
+   * mraw/MRawEvtData.[cc,h]:
+     - changed wrong return type of GetNumPixels to UShort_t
+
+   * mmain/MBrowser.[cc,h]:
+     - made the dialog somehow work like it should
+
+
+
+ 2001/04/03: Thomas Bretz
+
+   * manalysis/MCT1ReadAscii.cc:
+     - the pedestal values read from the file are now stored in MeanRms 
+       instead of Sigma
+   
+   * manalysis/MCerPhotCalc.cc:
+     - The pedestal mean Rms is used as the pixel error
+   
+   * MImgCleanStd.cc:
+     - CleanStep1: the '<' was replaced by a '<=' to clean also pixels 
+       with value=noise=0
+     
+   * MMcPedestalCopy.cc:
+     - All the pedestal values are now filled in (are they calculated correctly?)
+   
+   * mgui/MGeomCamMagic.cc:
+     - Forgot to initialize the Nextneighbors of the Magic Camera
+       (thanks to Oscar)
+     
+   * mhist/MHStarMap.cc:
+     - I changed the model of the display (colors and bin width) to
+       get a 'better' result
+
+
+
+ 2001/04/02: Thomas Bretz
+ 
+   * mraw/MRawEvtHeader.h, mraw/MRawFileWrite.cc:
+     - added constants (kTT*) for trigger type
+   
+   * manalysis/MImgCleanStd.[h,cc]:
+     - added changeable cleaning levels
+ 
+   * manalysis/MHillas.cc:
+     - added some more sanity checks to the calculation
+     
+   * manalysis/MCT1ReadAscii.[h,cc]:
+     - added some kind of chain feature (AddFile) to process more than one file
+ 
+   * mgui/MGeomPix.[h,c]:
+     - added interface to pixel neighbors
+ 
+   * mgui/MGeomCamCT1.[cc,h], mgui/MGeomCamMagic.[cc,h]:
+     - creates the neighbor geomtry now, too
+ 
+   * manalysis/MImgCleanStd.[cc,h]:
+     - switched to new stylish neighbors from MGeomCam
+
+
+
+ 2001/03/30: Thomas Bretz
+ 
+   * mdatacheck/MH*, mdatacheck/MFillH*:
+     - moved to mhist
+   
+   * mraw/MrawEvtPixelIter:
+     - IsLoGain -> HasLoGain
+   
+   * mgui/MG*:
+     - renamed
+     - moved to mmain
+     - move Browser functionality to MBrowser
+ 
+   * mmain/, mhist:
+     - new
+
+
+
+ 2001/03/21: Thomas Bretz
+                            
+   * manalysis/MHillas.[h,cc]:
+     - fixed some minor errors, added sanity check (N<2) to Calc
+
+   * manalysis/MFillHHillas.cc:
+     - skip event if Hillas calculations fails
+     
+   * macros/getCollArea.C, macros/readMagic.C, 
+     mdatacheck/MViewAdcSpectra.cc, meventdisp/MGFadcDisp.cc:
+     - changed order in MReadTree constructor
+
+   * manalysis/MCT1ReadAscii.[h,cc]:
+     - changed to use MPedestalCam
+     
+   * manalysis/MCT1Pedestals.[h,cc]:
+     - removed
+     
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MCT1Pedestals
+     
+   * mbase/BaseLinkDef.h:
+     - added const values from Magic.h
+     
+   * mbase/MLogManip.h:
+     - changed style of dbginf
+   
+   * mbase/MParList.cc:
+     - make use of dbginf
+     
+   * mbase/MReadTree.[h,cc]:
+     - switched from a TTree to a TChain object
+     - chnaged order of variables of the constructor
+
+
+
+ 2001/03/21: Thomas Bretz
+                                                                  
+   * macros/CT1Hillas.C, manalysis/MImgCleanStd.cc, manalysis/MImgCleanStd.h,
+     manalysis/MMcPedestalCopy.cc, manalysis/MMcPedestalCopy.h,
+     manalysis/MCerPhotCalc.h, manalysis/MCerPhotCalc.cc, mdatacheck/MHHillas.h,
+     mdatacheck/MHHillas.cc, mdatacheck/MFillHFadc.cc, mdatacheck/MFillHFadc.h,
+     mdatacheck/MHFadcCam.cc, mdatacheck/MHFadcCam.h, mdatacheck/MHFadcPix.cc,
+     mdatacheck/MHFadcPix.h, mdatacheck/MFillHHillas.cc, 
+     mdatacheck/MFillHHillas.h
+     - added
+
+   * mdatacheck/MHistosAdc.[h,cc]:
+     - replaced by MHFadc[Cam,Pix]
+
+   * mdatacheck/MFillAdcSpect.[h,cc]:
+     - replaced by MFillHFadc
+
+   * macros/readCT1.C:
+     - uses the new classes now
+     - calculates and displays hillas
+
+   * manalysis/AnalysisLinkDef.h:
+     - added MCerPhotCalc, MImgCleanStd, MMcPedestalCopy
+
+   * manalysis/MCT1ReadAscii.cc:
+     - PreProcess uses FindCreateObj now
+
+   * manalysis/MCerPhotEvt.cc, manalysis/MPedestalCam.cc:
+     - changed the new back to 'new with placement'
+
+   * manalysis/MCerPhotEvt.[h, cc]:
+     - removed cleaning from this class
+
+   * manalysis/MHillas.cc:
+     - some small changes in the naming inside Calc()
+
+   * manalysis/MHillas.h:
+     - added Get-functions
+     
+   * manalysis/MPedestalCam.h:
+     - added InitSize-function
+     
+   * manalysis/MPedestalPix.h:
+     - made Get-functions const
+     
+   * manalysis/Makefile:
+     - added MMcPedestalCopy, MImgCleanStd, MCerPhotCalc
+     
+   * mbase/MLogManip.h:
+     - "l." before line number
+     
+   * mbase/MParList.cc:
+     - added the autodelete feature for automatically created classes
+     
+   * mdatacheck/DataCheckLinkDef.h:
+     - added MHFadc[Cam,Pix], MHHillas
+     - removed MHistosAdc
+     - added MFillHFadc, MFillHHillas
+     
+   * mdatacheck/MGDisplayAdc.[h,cc], MShowSpect.[h,cc],
+     mdatacheck/MViewAdcSpectra.[h,cc], :
+     - changed from MHistaosAdc to MHFadcCam
+     
+   * mdatacheck/Makefile:
+     - added MFillHFadc.cc, MFillHHillas.cc
+     - removed MFillAdcSpect.cc
+
+   * manalysis/MCT1ReadAscii.h, mbase/MEvtLoop.h, mbase/MLog.h,
+     mbase/MParList.h, mbase/MReadTree.h, mbase/MTask.h,
+     mbase/MTaskList.h, mdatacheck/MDumpEvtHeader.h,
+     meventdisp/MGFadcDisp.h, mgui/MCamDisplay.h,
+     mgui/MCamNeighbor.h, mgui/MGDataCheckMain.h,
+     mgui/MGEventDispMain.h, mgui/MGMarsMain.h,
+     mgui/MGMonteCarloMain.h, mgui/MGPrototyp.h, mgui/MHexagon.h,
+     mmontecarlo/MCollAreaTrigger.h, mraw/MRawEvtPixelIter.h,
+     mraw/MRawFileRead.h, mraw/MRawFileWrite.h:
+     - set version number to '0' (no i/o for this class)
+
+   * mgui/MGeomCamCT1.cc:
+     - new claculation algorith for the CT1 camera. It is more
+       exact in the camera plain
+       
+   * mgui/MHexagon.cc:
+     - removed Draw-function (it is inherited from TObject)
+     
+   * mmc/MMcFadcHeader.hxx:
+     - Added get-functions
+     
+
+
+
+ 2001/03/20: Thomas Bretz
+                                                                  
+   * manalysis/MPedestalPix.[h,cc], manalysis/MPedestalCam.[h,cc],
+     manalysis/MHillas.[h,cc], manalysis/MHillasCalc.[h,cc],
+     mgui/MGeomCamCT1.[h,cc], mgui/MGeomCamMagic.[h,cc]
+     - added
+
+   * macros/readCT1.C:
+     - added calculation of Hillas parameters
+     - changed from pointers to objects
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MPedestalPix/Cam, MHillas, MHillasCalc
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - removed fType
+     - commented out Draw function - should be fixed soon
+     - renamed *Nb* to *Num*
+     - renamed Get[Min,Max]NumPhotons to GetNumPhontons[Min,Max]
+
+   * meventdisp/MGFadcDisp.[h,cc]:
+     - changed parameter of ReadinEvent to unsigned
+
+   * mgui/GuiLinkDef.h, mgui/Makefile:
+     - added MGeomCamCT1, MGeomCamMagic
+
+   * mgui/MCamDisplay.[h,cc]:
+     - changed constructor argument from int to MGeomCam
+     - renamed *Nb* to *Num*
+
+   * mgui/MGeomCam.[h,cc]:
+     - removed all camara specific stuff
+     - MGeomCam is now used as a base class for the classes
+       MGeomCam[Magic,CT1] which are containing the camera specific stuff
+
+   * mgui/MGeomPix.h:
+     - added Set function
+
+
+
+ 2001/03/02: Thomas Bretz
+   
+   * manalysis/Makefile, mdatacheck/Makefile, meventdisp/Makefile,
+     mgui/Makefile: 
+     - new
+   
+   * mbase/MParList.[cc,h]: 
+     - Added FindCreateObj member function
+     - added a name to the constructor
+ 
+   * mbase/MReadTree.cc: 
+     - changed to use FindCreateObj
+
+   * mdatacheck/MDumpEvtHeader.cc: 
+     - removed fPixelIter from member list
+     - changed cout to *fLog
+   
+   * mdatacheck/MViewAdcSpectra.cc:
+     - removed a HUGE memory leak. All the objects in the list (and the
+       lists itself were NEVER deleted)
+   
+   * mdatacheck/MFillAdcSpect.cc
+     - removed fPixelIter from member list
+     - changed cout to *fLog
+     - changed to use FindCreateObj
+     - changed high and low to hi and lo
+   
+   * mdatacheck/MShowSpect.cc
+     - changed cout to *fLog
+     - added a name to the constructor
+   
+   * mraw/MRawFileRead.cc:
+     - changed to use FindCreateObj
+   
+   * mdatacheck/MGDisplayAdc.[h,cc]: 
+     - added some new member functions to make code more clear
+     - removed fHists from the destructor
+   
+   * mdatacheck/MHistosAdc.h:
+     - changed high and low to hi and lo
+
+   * macros/dohtml.C:
+     - added manalysis
+
+
+
+ 2001/03/01: Thomas Bretz
+
+   * Makefile: 
+     - added headers to dependencies
+ 
+   * Makefile.rules: 
+     - added headers to dependencies
+ 
+   * merpp.cc: 
+     - changed from pointers to objects
+     - added compression level support
+ 
+   * readraw.cc: 
+     - removed unnecessary includes
+ 
+   * mbase/MArray*.*: 
+     - changed all Int_t to UInt_t
+ 
+   * mbase/MLogManip.h: 
+     - changed name of __DINF__ to dbginf
+ 
+   * mraw/MRawCrateData.[h,cc], mraw/MRawEvtHeader.[h,cc],
+     mraw/MRawRunHeader.[h,cc]: 
+     - changed ifstream to istream
+     
+   * mraw/MRawEvtData.cc: 
+     - changed the reading, which speeds up merpp by a factor of 10
+   
+   * mraw/MRawEvtData.h: 
+     - added flag to InitArrays and DeletePixels 
+       (not yet used)
+
+   * mraw/MRawFileRead.h: 
+     - removed pParList from parameter list
+ 
+   * manalysis/AnalysisLinkDef.h
+     - removed MReadCT1Ascii, added MCT1ReadAscii
+     - added MCT1Pedestals
+   
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - changed the constructor a little bit
+     - rewrote Print() to make it a bit more readable
+     - moved MCerphotPix to new File
+     - added many lines of comments
+     - exchanged old stylish new call with new stylish(=) one
+     - replaced all accesses to fPixels with the [] operator to make this
+       lines more readable
+     - made all variable declarations const-correct,
+     - I changed the style of the cleaning method from if(a){if()b{if(c){}}}
+       to if(!a)continue; if(!b)continue if(!c) continue; to make it more
+       compact, readable and easier to understand
+     - renamed the Boolean-functions to Is* to get a stricter structure
+     - replaced mapping function to access the pixel list entries by the new 
+       operator to get rid of more than the necessary number of member 
+       functions without loosing speed or readability
+     - renamed GetMinimum/MaximumPhoton to GetMin/MaxNumPhotons to be 
+       more exact
+   
+   * mgui/MCamGeom.* splitted and changed to MGeomCam/Pix:
+     - added a new operator to access the TObjArray
+     - removed unnecessary code from CreateCT1
+ 
+   * mbase/MAGIC.h: 
+     - added kPI
+ 
+   * mbase/MReadTree.cc: 
+     - added some comments
+ 
+   * mgui/MCamDisplay.[h,cc]: 
+     - added some comments, reordered a bit the calls in the constructor 
+       to get a 'straight forward structure', MGeomCam is now only
+       locally used where it is needed, replaced access to the 
+       TClonesArrays by new member-function to get a more readable code,
+       replaced old stylish new call with new stylish one, made
+       variable decleration const-correct, introduced a new member function
+       to set the pixel color, renamed the overloaded Draw functions to
+       DrawPhotons, DrawPhotErr to prevent missunderstatements, changed
+       the 'layout' of GetColor to make it easier to understand the algorithm,
+   
+   * mgui/MCamNeighbor.[h, cc]:
+     - changed to new log-interface
+     - exchanged -9999 by -1
+     - skipped the exits
+     - you must check for -1 one in any case
+     - this means a warning should be enough
+   
+   * mgui/MHexagon.[h,cc]:
+     - added new constructor whcih uses a MGeomPix-object
+
+
+
+ 2001/02/28: Thomas Bretz
+
+   * mbase/MParList.[h,cc]: 
+      - changed return type of FindObject back to TObject
+      - it seems so, that some compilers don't like overriding the
+        return type of a virtual member function
+
+
+
+ 2001/02/23: Thomas Bretz
+
+   * mraw/MRawEvtPixelIter.h: 
+      - added GetSum* functions
+
+   * mbase/MParList.[h,cc]: 
+      - Removed unnecessary fNext-stuff
+
+
+
+ 2001/02/22: Thomas Bretz
+
+   * merpp.cc, readraw.cc, mbase/MParContainer.cc, mbase/MParList.cc,
+     mbase/MParList.h, mbase/MReadTree.cc, mbase/MTask.cc, mbase/MTask.h,
+     mbase/MTaskList.cc, mbase/MTime.cc, mdatacheck/MDumpEvtHeader.cc,
+     mdatacheck/MShowSpect.cc, meventdisp/MGFadcDisp.cc, mgui/MGPrototyp.h,
+     mmc/MHeaderTrig.cxx, mraw/MRawCrateArray.cc, mraw/MRawEvtData.cc,
+     mraw/MRawEvtHeader.cc, mraw/MRawFileRead.cc, mraw/MRawFileWrite.cc,
+     mraw/MRawRunHeader.cc:
+      - exchanged cout with the new logging style (gLog, *fLog)
+
+   * mraw/MRawEvtData.cc: 
+      - added 'dec' option to Print
+  
+   * mmc/MHeaderTrig.cxx, mmc/MMcEvt.cxx, mmc/MMcTrig.cxx:
+      - small changes to the Print funtions
+
+
+
+ 2001/02/21: Thomas Bretz
+
+   * MRawEvtData.cc: 
+      - Changed ReadEvt according to the new raw binary format 2001/02/20
+     
+   * Added MLog.[h,cc], MLogManip.[h,cc]
+   
+   * Adde SetStreamer and fLog to the MParContainer base class
+   
+   * Derived MEvtLoop from MParContainer
+
+   * Makefile: 
+      - added 'tar'
+
+   * mbase/BaseIncl.h: 
+      - added fstream.h, TGListBox.h
+ 
+   * mbase/BaseLinkDef.h: 
+      - added pragma for gLog and MLog
+ 
+   * mbase/MAGIC.h: 
+      - added forward definition for gLog
+ 
+   * mbase/MEvtLoop.cc: 
+      - exchanged cout with *fLog
+      - added statements to provide log-facility to all tasks als parameter 
+        containers
+    
+   * mbase/MEvtLoop.h: 
+      - Small changes
+  
+   * mbase/MParContainer.h: 
+      - Added definitions necessary for use of Log-Facility
+  
+   * mbase/MParList.[h,cc]: 
+      - Added SetLogStream
+  
+   * mbase/MTask.h: 
+      - added fLog
+  
+   * mbase/MTaskList.[h,cc]: 
+      - added SetLogStream
+  
+   * mbase/Makefile: 
+      - Added MLog.cc, MLogManip.cc
+
+
+
+ 2001/02/19: Harald Kornmayer	
+
+  *  implemented the Image Cleaning a la CT1 to the class MCerPhotEvt
+  
+  *  changed the readCT1.C file to show the effects of the image cleaning
+     a la CT1
+
+  *  changed 
+	mgui/MCamNeighbor.cc
+	mananlysis/MCerPhotEvt.cc  .h 
+	macros/readCT1.C
+
+
+
+ 2001/02/19: Thomas Bretz
+
+   * MParContainer.h added prototypes for AsciiRead/Write
+
+   * .rootrc added
+
+   * MEvtLoop.[h,cc]: 
+      - split eventloop in its three parts, this should be used for 
+        debugging only.
+
+
+
+ 2001/02/06: Harald Kornmayer
+
+   *  the first running version with a eventdisplay. Now we are able
+      to display an Event on the photo electron level. To do this, run
+      the macro "macros/readCT1.C" after changing the file name. 
+
+      changed: 
+	macros/readCT1.C
+	manalysis/MNphotEvent.cc, manalysis/MNphotEvent.h
+	analysis/MReadCT1Ascii.cc
+	mgui/MCamDisplay.cc, mgui/MCamDisplay.h
+
+
+
+ 2001/01/23: Harald Kornmayer
+
+   *  the integration of the class FadcDisp in the mars enviroment
+      and further developments in the display
+
+      changed: 
+	meventdisp/MGFadcDisp.h
+	meventdisp/MGFadcDisp.cc
+	mgui/GuiIncl.h
+	mgui/GuiLinkDef.h
+	mgui/MGMarsMain.cc
+	mgui/MGPrototyp.cc
+	mgui/MGPrototyp.h
+	mgui/Makefile
+
+      added: 
+	mgui/MGEventDispMain.h
+	mgui/MGEventDispMain.cc
+
+
+
+ 2001/01/22: Harald Kornmayer
+
+   *  started with the development of a EventDisplay Utitliy. 
+      Therefore I added the following files. 
+
+      meventdisp/EvtDispIncl.h
+      meventdisp/EvtDispLinkDef.h
+      meventdisp/MGFadcDisp.cc
+      meventdisp/MGFadcDisp.h
+      meventdisp/Makefile
+
+      Also a few of the older files where slightly changed. 
+      ./Makefile
+      ./Makefile.rules
+      mraw/MRawEvtData.
+      
+
+
+ 2001/01/19: Thomas Bretz
+
+    * mmc/*.hxx:
+       - changed include of MDefineTrigger.h back
+
+
+
+ 2001/01/19: Oscar Blanch
+
+    * mmc/MTriggerDefine.h:
+       - added
+
+
+
+ 2001/01/18: Thomas Bretz
+
+    * Makefile:
+       - mmc-library added
+
+    * Makefile.conf.general:
+       - Added definition of __MARS__
+
+    * Makefile.rules:
+       - Added definitions to rootcint
+
+    * Oscar added the McFormat subdir of the Monte Carlo as mmc
+
+    * mmc/MMcEvt.h:
+       - renamed to MMcEvt.hxx
+
+    * mmc/*.hxx:
+       - added necessary defintions from MDefineTrigger.h
+
+    * mmc/Makefile, mmc/McLinkDef.h, mmc/McIncl.h, mmc/readme.txt:
+       - added
+
+    * mmc/LinkDef.h:
+       - removed
+
+
+
+ 2001/01/17: Thomas Bretz
+
+    * Makefile:
+       - Exchanged explicit rules to make library by implicit ones
+       - The shared object works now. I exchanged the libraries with the object
+         files. But I don't know why the libraries don't work.
+
+    * Makefile.conf.linux-gnu:
+       - replaced CC with gcc (instead of g++)
+
+    * mdatacheck/DataCheckLinkDef.h:
+       - removed unused statements
+
+    * mraw/RawLinkDef.h:
+       - added globals
+
+    * mraw/MerppLinkDef.h:
+       - removed unused file
+
+
+
+ 2001/01/12: Thomas Bretz
+
+    * MLinkDef.h, MIncl.h, marslogo.xpm, magiclogo.xpm:
+       - added
+
+    * LinkDef.h:
+       - removed
+
+    * Makefile:
+       - Added CINT, mrproper
+
+    * mbase/Makefile, mraw/Makefile, mgui/Makefile, mdatacheck/Makefile:
+       - included makefile.general, Makefile.rules,
+       - removes corresponding lines
+
+    * mdatacheck/MDumpEvtHeader.[h,cc], mdatacheck/MFillAdcSpect.[cc,h],
+      mdatacheck/MFillAdcSpect.[h,cc], mdatacheck/MGDisplayAdc.[cc,h],
+      mdatacheck/MHistsosAdc.[h,cc], mdatacheck.MShowSpect.[cc,h]
+       - changed include statements
+
+    * mgui/MGDataCheckMain.[cc,h], mgui/MGMarsMain.[cc,h]
+       - changed include statements
+       - move enum from h to cc
+       - removed comma operator from delete statements (nonsense)
+
+
+
+ 2001/01/11: Harald Kornmayer
+
+    * ./
+      readraw.cc, Makefile, Makefile.rules, LinkDef.h, MParList.cc, MReadTree.cc,
+      MReadTree.h, mbase/Makefile, mraw/Makefile
+       - small changes in this files. Not really critical.
+
+    * mars.cc
+       - added the main file for the gui
+
+    * mgui/
+      GuiIncl.h, MGMarsMain.cc, GuiLinkDef.h, MGMarsMain.h, MGDataCheckMain.cc,
+      Makefile, MGDataCheckMain.h
+       - added the subdir mgui and this files
+
+    * mdatacheck/
+      DataCheckIncl.h, DataCheckLinkDef.h, MHistosAdc.cc, MHistosAdc.h,
+      MDumpEvtHeader.cc, MDumpEvtHeader.h, MShowSpect.cc, MShowSpect.h,
+      MFillAdcSpect.cc, MFillAdcSpect.h, MViewAdcSpectra.cc, MViewAdcSpectra.h,
+      MGDisplayAdc.cc, MGDisplayAdc.h, Makefile
+       - added the subdir mdatacheck and this files
+
+
+
+ 2000/12/28: Thomas Bretz
+
+    * merpp.cc, MArray.cc, MArray.h, MArrayB.cc, MArrayB.h, MArrayS.cc,
+      MArrayS.h, MEvtLoop.cc, MEvtLoop.h, MInputStreamID.cc, MInputStreamID.h,
+      MParContainer.cc, MParContainer.h, MParList.cc, MParList.h, MReadTree.cc,
+      MTask.cc, MTask.h, MTaskList.cc, MTaskList.h, MTime.cc, MTime.h:
+       - Added changes some comments.
+
+    * MLoopEvt.cc, MLoopEvt.h:
+       - Removed
+
+
+
+ 2000/12/22 - Thomas Bretz:
+
+    * readraw.cc:
+       - changed some comments and the Root-Name of the program
+       - added check for the existance of the file
+       - changed name of numbers of entries from iEnt to nent
+
+    * dohtml.C:
+       - changed title of converted macros
+
+    * MRawEvtData.cc:
+       - added a commet in Draw()
+
+    * MRawEvtPixelIter.[h,cc]:
+       - Added the comment header of the file
+       - removed inheritance from TIterator (not needed)
+       - some changes to get it work (the one in the repository was untested
+         and not working)
+       - changed calling style of iterator from do...while to while-loop
+       - changed some comments
+
+    * MRawRunHeader.cc:
+       - added some comments
+
+    * Changelog, News: added
+
+    * test.C: removed
Index: /tags/Mars-V0.9/Changelog.03
===================================================================
--- /tags/Mars-V0.9/Changelog.03	(revision 9772)
+++ /tags/Mars-V0.9/Changelog.03	(revision 9772)
@@ -0,0 +1,7211 @@
+
+ 2003/12/23: Abelardo Moralejo
+
+   * manalysis/MExtractedSignalPix.cc
+     - in Clear(), initialized fExtractedSignalHiGain to 0 instead 
+       of -1. In MC files run without noise, the ADC info of pixels 
+       with no C-photons is missing. Later noise will be added to all 
+       pixels in the padding, and "empty" ones must have a 0 before 
+       the addition of this noise.
+
+   * manalysis/MGeomApply.cc
+     - initialized size of MPedPhotCam.
+
+   * manalysis/MMcCalibrationCalc.[cc,h]
+     - Removed setter function SetConversionHiLo: the ratio from high 
+       to low gain is now read from MMcFadcHeader, and set in ReInit.
+     - Fixed bug: fADC2PhOuter was initialized before the MMcFadcHeader
+       was available. Now it is done in ReInit.
+     - fPedPhotCam is now initialized in PreProcess and not in ReInit.
+     - fGeom is now set in ReInit (there should be one MGeomCam per
+       run header in the camera file).
+
+   * mmc/MMcFadcHeader.hxx
+     - added getter function GetLow2HighGain()
+
+
+
+ 2003/12/23: Thomas Bretz
+
+   * manalysis/MPedCalcPedRun.[h,cc]:
+     - removed fCounter
+     - replaced by GetNumExecutions()
+
+   * mraw/MRaw*:
+     - some changes and debug output for the upcomming time-stamp
+     - a fix to broken reading
+
+
+
+ 2003/12/23: Wolfgang Wittek
+
+   * macros/ONAnalysis.C
+     - new macro for the MAGIC analysis, corresponding to CT1Analysis.C
+
+   * macros/AnalyseCT1.C
+     - deleted because outdated
+
+   * manalysis/MPadOn.[h,cc]
+     - new class for the MAGIC analysis, corresponding to MCT1PadSchweizer
+
+   * manalysis/MPadOnOFF.[h,cc]
+     - minor changes (printouts)
+
+   * manalysis/MPedestalWorkaround.[h,cc]
+     - put zenith angle into MMcEvt
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h
+     - added MPadON
+
+   * mmc/MMcEvt.hxx
+     - add member function SetTelescopeTheta(), SetTelescopePhi()
+
+
+
+ 2003/12/22: Thomas Bretz
+ 
+   * manalysis/MCT1FindSupercuts.cc, manalysis/MFindSupercuts.cc:
+     - replaced MFRandomSplit by MFEventSelector
+   
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - removed MFRandomSplit (functionality already implemented
+       in MFEventSelector)
+       
+   * mfilter/MFEventSelector.[h,cc]:
+     - did some cosmetics
+     - removed some obsolete data members
+     - added some comments
+     
+   * mfilter/MFEventSelector2.[h,cc]:
+     - added some comments
+
+   * macros/dohtml.C, macros/rootlogon.C:
+     - added mcalib
+     - added mhbase
+     
+   * macros/estfit.C:
+     - get chisq from MParameterD
+     
+   * manalysis/MEventRateCalc.cc:
+     - added comments
+     
+   * mbase/MParContainer.h:
+     - added a comment
+     
+   * mhist/MHCamera.h:
+     - added default argument for DrawClone
+     
+   * mmontecarlo/MMcEnergyEst.cc:
+     - use an MParameterD instead of accessing MChisqEval
+     
+   * mtools/MChisqEval.[h,cc]:
+     - write result to an MParameterD
+
+   * mtools/MTFillMatrix.[h,cc]:
+     - some more features
+
+
+
+ 2003/12/21: Thomas Bretz
+
+   * mcalib:
+     - new directory containing all MCalib* and MHCalib* classes
+
+   * manalysis/MCalib*:
+     - moved to mcalib
+
+   * mhist/MHCalib*:
+     - moved to mcalib
+
+   * Makefile:
+     - added mcalib
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MCalib*
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MHCalib*
+
+   * mhbase:
+     - new directory containing base classes for histogram stuff
+
+   * mhist/MFillH.[h,cc], mhist/MBinning.[h,cc], mhist/MWeight.[h,cc],
+     mhist/MH.[h,cc], mhist/MH3.[h,cc], mhist/MHArray.[h,cc],
+     mhist/MHMatrix.[h,cc]:
+     - moved to mhbase
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MFillH, MBinning, MWeight, MH, MH3, MHMatrix and MHArray
+
+   * */Makefile:
+     - updated include paths accordingly
+
+
+
+ 2003/12/20: Abelardo Moralejo
+
+   * manalysis/MMcCalibration.[h,cc]
+     - adapted to changes in calibration classes. Removed SetADC2PhOuter
+       (ratio of inner to outer can be found from MMcFadcHeader).
+
+   * mananalysis/MCalibrate.cc
+     - commented out check of sizes of MExtractedSignal and 
+       MCalibrationCam (they are different in MC when no noise is 
+       simulated).
+
+   * mmc/MMcFadcHeader.hxx
+     - added getter function for fAmplitudOuter.
+
+
+
+ 2003/12/20: Thomas Bretz
+
+   * Makefile:
+     - added an option to statically link the programs (for
+       debugging)
+       
+   * merpp.cc, readdaq.cc, readraw.cc:
+     - small changes to the command line options
+       (the aim is a generalization)
+
+   * manalysis/MCalibrate.[h,cc]:
+     - removed leading '//' from class description
+     - removed usage of MGeomCam (it is obsolete here)
+     - small changes to make the output fit the 'standard'
+     - take the number of pixels from the containers, added a
+       consistency check
+     - added many small comment about future development
+     - added some const-qualifiers
+     - removed the 'unused/empty' pixels. They are obsolete and not
+       wanted at all.
+     - changed pixid to pixidx
+
+   * manalysis/MCalibrationPix.h:
+     - sorted member functions
+     - added some const qualifiers
+     - added many small comment about future development
+
+   * manalysis/MExtractSignal.[h,cc]:
+     - removed arguments from constructor
+     - added corresponding member functions
+       + the convetion is to have only vital arguments in the
+         construtor and member functions to change the default
+     - removed obsolete PostProcess
+     ! PLEASE update you code accordingly.
+     
+   * manalysis/MExtractedSignalCam.h, manalysis/MExtractedSignalPix.h:
+     - added corresponding member functions
+   
+   * mbase/MArgs.[h,cc]:
+     - added some comments
+     - added options/arguments to Print
+     - added GetNumOptions
+     - added GetNumEntries
+     - added HasOnly
+     - added HasOnlyAndRemove
+     
+   * mbase/MEvtLoop.[h,cc]:
+     - removed leading '//' from class description
+     - replaced INT_MAX by kMaxUInt
+     - changed meaning of eventloop argument:
+       now 0 means all-events instead of -1
+     - forward tlist-name from Eventloop to PreProcess
+   
+   * mbase/MTime.[h,cc]:
+     - added UpdMagicTime
+
+   * mfilter/MFEventSelector2.cc:
+     - replaced INT_MAX by kMaxUInt
+     
+   * mmain/MEventDisplay.[h,cc]:
+     - make use of MEvtLoop::GetTaskList()
+     - removed GetReader
+     
+   * mmontecarlo/MMcEnergyEst.cc:
+     - removed leading '//' from class description
+     
+   * mranforest/MRanTree.cc:
+     - removed leading '//' from class description
+     - replaced 1e20 by FLT_MAX
+   
+   * mraw/MRawEvtHeader.[h,cc], mraw/MRawFileRead.cc,
+     mraw/MRawRead.[h,cc], mraw/MRawRunHeader.cc,
+     mraw/MRawSocketRead.cc:
+     - added decoding of time from event header - UNTESTED!
+     
+   * mreport/MReportRun.h:
+     - set class verseion to 0 -- not ment for writing at the
+       moment
+
+   * mtools/MTMinuit.[h,cc]:
+     - added (will replace MMinuitInterface soon)
+
+   * mtools/ToolsLinkDef.h, mtools/Makefile:
+     - added MTMinuit
+
+
+
+ 2003/12/19: Markus Gaug, Michele Doro
+
+   * manalysis/MExtractSignal.[h,cc], manalysis/MCalibrate.[h,cc],
+     manalysis/MCalibrationCalc.[h,cc], manalysis/MCalibrationPix.[h,cc]:
+     - Treatment of the conversion factors between HI Gain and Lo Gain
+       is now done in the MCalibrationPix. 
+
+       MExtractSignal does not convert anymore, but MCalibrate searches 
+       the conversion factor from MCalibrationPix.
+       This allows for different conversion factors for every pixel.
+
+
+
+ 2003/12/18: Abelardo Moralejo
+
+   * manalysis/Makefile, AnalysisLinkDef.h
+     - Added missing classes MPedPhotCam, MPedPhotPix
+
+   * manalysis/MMcCalibrationCalc.[h,cc]
+     - Changed names of conversion factors, because their meaning 
+       changed from "ADC->photoelectrons" to "ADC->photons before 
+       the PM". Added some comments. Added calls to MCalibrationPix::
+       SetBlindPixelMethodValid() and SetConversionBlindPixelMethod()
+
+   * manalysis/MCalibrate.cc
+     - Corrected variable names: Convertion -> Conversion, and also
+       removed the "f" at the beginning of local (non-member) variables.
+     - Added fGeomCam, fPedPhotCam (created in the PreProcess).
+
+
+
+ 2003/12/18: Markus Gaug, Michele Doro
+
+   * manalysis/MExtractSignal.[h,cc]
+     - introduced a third argument in the constructor: Byte_t logainshift
+
+   * manalysis/MCalibrationCam.cc
+   * manalysis/MCalibrationPix.cc
+     - introduced error calculation for the F-Factor method
+
+   * manalysis/MCalibrate.cc
+     - replace pix.IsValid by pix.IsBlindPixelMethodValid() which more 
+       what is checked exactly
+  
+   * macros/calibration.C
+     - display now the errors in the F-Factor method correctly	
+
+   * mhist/MHCalibrationPixel.[h,cc]
+     - before declaring a calibration factor as valid, check if the 
+       mean fitted arrival time is not in the first or last time bin
+
+
+
+ 2003/12/18: Abelardo Moralejo
+
+   * manalysis/MCalibrate.cc
+     - Changed  "if (!fCalibrations)" to "if (!fGeomCam)" in 
+       preprocess (this was a cut-and-paste error).
+     - In Process: added "fCerPhotEvt->AddPixel(pixid, 0., 0.)" before
+       setting pixel pixid to unused, in case !pix.IsValid()
+       May be removing both commands (adding the pixel and setting it 
+       to unused would have the same effect). 
+
+
+
+ 2003/12/18: Thomas Bretz
+
+   * mfilter/MFSoftwareTrigger.[h,cc]:
+     - added - code taken from M[CT1]SelBasic
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - added MFSoftwareTrigger
+
+   * manalysis/MExtractedSignalPix.h:
+     - added missing const-qualifier IsLoGainUsed
+
+   * mreport/MReportFileRead.[h,cc]:
+     - added support for line counter
+
+   * mreport/MReportRun.[h,cc]:
+     - added preliminary version to decode the Start/Stop run tags
+       in the report files.
+
+   * mreport/Makefile, mreport/ReportLinkDef.h:
+     - added MReportRun
+
+   * merpp.cc:
+     - added a first implementation to be able searching report
+       files for the run number
+
+   * mdata/MDataMember.[h,cc]:
+     - implemented a way to determin whether the data member is 
+       a floating point value or an integer
+
+   * mfilter/MFDataMember.[h,cc]:
+     - use the information to treat integer values more accuratly
+
+   * mbase/MAGIC.h:
+     - change minimum root version to 3.05/06
+
+   * mtools/MTFillMatrix.cc:
+     - added a check whether the file name is valid
+
+
+
+ 2003/12/18: Abelardo Moralejo
+
+   * mmc/MMcConfigRunHeader.[h,cc]
+     - Removed some obsolete parameters no longer used in reflector 
+       simulation since version 0.6.
+     - Updated version number to 2 !
+     - Added getter and setter functions for fPointSpread (allows 
+       camera simulation to change the value whenever the spot is made
+       bigger to fit the data).
+
+
+ 2003/12/17: Abelardo Moralejo
+
+   * manalysis/MExtractSignal.cc
+     - put SetNumPixelUsedFADCSlices into the ReInit, otherwise they 
+       are not accessible for MCalibrationCalc
+
+   * manalysis/MCalibration*
+   * mhist/MHCalibration*
+     - many small changes, mostly cosmetic
+
+
+
+ 2003/12/17: Abelardo Moralejo
+
+   * mbase/MAGIC.h:
+     - added kELECTRON, kPOSITRON to type ParticleId_t;
+
+   * mfilter/MFGeomag.cc:
+     - added kPOSITRON and kELECTRON as possible particle ids.
+     - added fResult = 0 for the case kGAMMA,  !fGamm_elec, to let
+       real gammas be accepted by the filter.
+
+
+
+ 2003/12/17: Thomas Bretz
+
+   * mreport/MReportCC.[h,cc]:
+     - added report storing weather data
+
+   * mreport/Makefile, mreport/ReportLinkDef.h:
+     - added MReportCC
+
+   * mtools/Makefile, mtools/ToolsLinkDef.h:
+     - added MTFillMatrix
+
+   * mtools/MTFillMatrix.[h,cc]:
+     - added
+
+   * mfilter/MFEventSelector2.[h,cc]:
+     - removed fUseOrigDistrib --> use a reference histogram with 
+       0 Entries instead.
+
+   * manalysis/MCT1FindSupercuts.[h,cc], manalysis/MFindSupercuts.[h,cc]:
+     - removed fUseOrigDistrib accoring to href.GetEntries()==0 used in
+       MFEventSelector2 and MFillMatrix
+
+   * macros/CT1Analysis.C, macros/ONOFFAnalysis.C, 
+     macros/ONOFFCT1Analysis.C:
+     - tried to make fUseOrigDistrib-stuff working again
+
+   * mhist/MHCamera.[h,cc]:
+     - implemented kVariance
+
+
+
+ 2003/12/16: Javi Lopez
+
+   * manalysis/MCalibrate.[h,cc]
+     - new classe that takes the integrated charge from MExtractedSignal
+       container and apply the calibration constants stored in
+       MCalibrationCam container storing the number of photons in
+       MCerPhotEvt.
+
+
+
+ 2003/12/16: Thomas Bretz
+
+   * mhist/MHSimulatedAnnealing.[h,cc], 
+     mhist/MSimulatedAnnealing.[h,cc]:
+     - fixed includes
+
+
+
+ 2003/12/12: Markus Gaug 
+
+   * manalysis/MSimulatedAnnealing.[h,cc]
+   * mhist/MHSimulatedAnnealing.[h,cc]
+     - new classes to do a minimization after the Simulated Annealing 
+       procedure. Please do make dox and look into the class documentation
+       to know how to use it
+
+   * manalysis/Makefile
+   * mhist/Makefile
+   * manalysis/AnalysisLinkDef.h
+   * mhist/HistLinkDef.h
+     - added the SimulatedAnnealing Classes
+
+
+
+ 2003/12/12: Markus Gaug / Michele Doro
+
+   * manalysis/MCalibrationCam.[h,cc]
+   * manalysis/MCalibrationPix.[h,cc]
+   * manalysis/MCalibrationBlindPix.[h,cc]
+   * manalysis/MCalibrationConfig.[h,cc]
+     - bug found transforming the number of photons from the blind pixel 
+       to the inner pixel. The previous results were wrong by a factor 2
+     - PIN Diode formally included
+     - Code better documented in MCalibrationCam
+
+
+
+ 2003/12/15: Thomas Bretz
+
+   * mraw/MRawRead.[h,cc]:
+     - added
+
+   * mraw/Makefile, mraw/RawLinkDef.h:
+     - added MRawRead
+
+   * mraw/MRawSocketRead.[h,cc], mraw/MRawFileRead.[h,cc]:
+     - changed such, that it derives from MRawRead now
+
+   * mfilter/MFAntiFilter.[h,cc]:
+     - removed. This function is implemented in MFilterList
+
+   * merpp.cc:
+     - enhanced to support start/stop time
+
+   * manalysis/MEventRateCalc.cc:
+     - removed some stuff which was commented out
+     
+   * mbase/MTime.cc:
+     - small change to GetString
+     
+   * mhist/MHCamera.cc:
+     - made the inverse deep blue dea palette the default
+       (FIXME: Make this a resource)
+     
+   * mreport/MReport.[h,cc]:
+     - added MTime arguments to Interprete
+     
+   * mreport/MReportFileRead.[h,cc]:
+     - added MTime arguments to Interprete
+     - added fStart/fStop data member
+
+
+
+ 2003/12/15: Abelardo Moralejo
+
+   * mgeom/MGeomCam.h
+     - made the CalcPixRatio function public.
+
+   * manalysis/MGeomApply.cc
+     - call the CalcPixRatio of the MGeomCam object. Workaround to 
+       allow the analysis of some files from a beta version of camera 
+       0.7 in which the array containing pixel ratios was not 
+       initialized.
+
+
+
+
+
+ 2003/12/12: Markus Gaug / Michele Doro
+
+   * manalysis/MCalibrationCam.cc
+     - did not compile because of a wrong command to MCalibrationPix, 
+       now corrected
+
+
+
+ 2003/12/12: Nadia Tonello
+
+   * mimage/MImgCleanStd.cc
+     - now the cleaning of rings>1 is done symmetrically around the core
+       pixels (bug solved)  
+
+
+
+ 2003/12/12: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationCalc.[h,cc]
+     - added fADC2PheInner, fADC2PheOuter and setter functions. Put 
+       these values into MCalibrationCam. Look for MExtractedSignalCam
+       to check which gain branch has been used (relevant for the
+       conversion factor) for each pixel.
+
+
+
+ 2003/12/12: Markus Gaug
+	
+   * manalysis/MExtractSignal.[h,cc]
+     - now with constructor allowing to set the first and last used
+       time slice
+     - (default like before)
+     - extract number of pixels from MGeomCam
+
+
+
+ 2003/12/12: Sabrina Stark
+  
+   * mfilter/MFSelBasic.[h,cc]
+     - new class for MAGIC analysis, corresponding to MFCT1SelBasic	
+
+   * mfilter/MFSelStandard.[h,cc]
+     - new class for MAGIC analysis, corresponding to MFCT1SelStandard	
+
+   * mfilter/MFSelFinal.[h,cc]
+     - new class for MAGIC analysis, corresponding to MFCT1SelFinal	
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h
+     - include MFSelBasic, MFSelStandard, MFSelFinal	
+
+   * manalysis/MPadONOFF.[h,cc]
+     - new class for MAGIC analysis, corresponding to MPadONOFF		
+
+   * manalysis/MSupercuts.[h,cc]
+     - new class for MAGIC analysis, corresponding to MCT1Supercuts		
+   
+   * manalysis/MSupercutsCalc.[h,cc]
+     - new class for MAGIC analysis, corresponding to MCT1SupercutsCalc		
+   
+   * manalysis/MFindSupercuts.[h,cc]
+     - new class for MAGIC analysis, corresponding to MCT1FindSupercuts		
+
+   * manalysis/MPedestalWorkaround.[h,cc]
+     - temporary task for MAGIC analysis to copy pedestal values and
+ 	RMS from MPedPhotCam to MPedestalCam	
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h
+     - include MPadONOFF, MSupercuts, MSupercutsCalc, MFindSupercuts,
+	MPedestalWorkaround	
+	
+   * mhist/MHSupercuts.[h,cc]
+     - new class for MAGIC analysis, corresponding to MHCT1Supercuts		
+
+   * mhist/Makefile, mhist/HistLinkDef.h
+     - include MHSupercuts
+
+   * macros/ONOFFAnalysis.C:
+     - adaption of ONOFFCT1Analysis to apply on Magic data
+	
+	
+ 
+ 2003/12/12: Markus Gaug
+
+   * manalysis/MExtractedSignalPix:
+     - Added fTailArrivalTime
+
+   * manalysis/MExtractSignals:
+     - SetArrivalTimes modified to 3 arguments (sorry!)
+
+
+
+ 2003/12/11: Sebastian Raducci & Villi Scalzotto
+
+   * manalysis/MArrivalTime.[h,cc]
+     - Added (new container)
+     - Preliminary version: do not use it
+
+   * manalysis/MArrivalTimeCalc.[h,cc]
+     - Added (new task)
+
+   * mraw/MRawEvtPixelIter.[h,cc]
+     - Added new method GetIdxMaxHiLoGainSample()
+   
+   * mraw/MRawEvtData.cc
+     - Added new case in GetPixelContent() method 
+
+   * mmain/MEventDisplay.cc
+     - Added new tab in the camera event display to show the arrival
+       time.
+
+   * mhist/MHEvent.[h,cc]
+     - Added new fType in the enumeration to handle the arrival time
+       histos
+
+
+ 2003/12/11: Abelardo Moralejo
+
+   * manalysis/MGeomApply.cc
+     - Initialize size of the MCalibrationCam object according to 
+       camera geometry.
+
+   * manalysis/MMcCalibrationCalc.[h,cc]
+     - Added. First draft of a class to get the calibration 
+       constants for the analysis of MC events.
+
+   * manalysis/Makefile, AnalysisLinkDef.h
+     - Added new class MMcCalibrationCalc
+
+
+ 2003/12/11: Markus Gaug
+
+   * manalysis/MExtractSignal, MExtractedSignalPix
+     - Store number of used FADC slices (HIGain, LoGAin)
+     - calculate signal with only 6 most significant slices (2 before, 
+       4 after the maximum)
+
+   * mhist/MHCalibrationBlindPixel:
+     - do the consistency check fitting the pedestal
+
+   * mhist/MHCalibrationPixel:
+     - store Hi Gain vs. Lo Gain values to extract the conversion
+       factor
+
+   * manalysis/MCalibrationPix:
+   * manalysis/MCalibrationCam:
+     - separate Hi Gain and Lo Gain
+     - include return of PIN Diode measurement
+
+
+
+ 2003/12/11: Thomas Bretz
+
+   * mbase/MTime.[h,cc]:
+     - small change to GetString
+     - added ReadBinary
+     
+   * mraw/MRawCrateData.[h,c], mraw/MRawFileRead.cc, 
+     mraw/MRawEvtData.[h,cc], mraw/MRawEvtPixelIter.[h,cc],
+     mraw/MRawRunHeader.[h,cc], mraw/MRawSocketRead.cc,
+     mraw/MRawCrateArray.[h,cc]:
+     - adapted to new DAQ file format Version 2
+     - changed ClassDef version accordingly
+
+   * mraw/RawIncl.h:
+     - added TArrayC
+
+   * mfileio/MCT1ReadPreProc.cc:
+     - tried to change reading CT1 data accordingly
+
+
+
+ 2003/12/10: Thomas Bretz
+
+   * manalysis/MPedPhotPix.[h,cc], manalysis/MPedPhotCam.[h,cc]:
+     - added
+
+   * merpp.cc:
+     - added support for dc report files
+     
+   * mcamera/CameraLinkDef.h, mcamera/Makefile:
+     - added MCameraDC
+     
+   * mhist/MHVsTime.cc:
+     - fixed a missing initialisation
+
+   * mraw/MRawFileRead.cc:
+     - fixed wrong MRawEvtTime name
+     
+   * mreport/MReport.cc:
+     - fixed reading of dc files
+     
+   * mreport/MReportCurrents.[h,cc]:
+     - do not store currents here. store it in MCameraDC
+     
+   * mreport/MReportFileRead.[h,cc]:
+     - added SetHasNoHeader and kHasNoHeader
+
+   * macros/readcurrents.C:
+     - fixed accordingly
+
+   * macros/sumcurrents.C:
+     - fixed accordingly
+
+
+
+ 2003/12/09: Markus Gaug
+
+   * mhist/MHCamera.[h,cc]:
+     - added SetCamError to set errors in the camera
+
+   * mhist/MHCalibration*:
+     - all hists doubles to separate High Gain and Low Gain
+
+   * manalysis/MCalibration*
+     - separate Hi Gain and Lo Gain
+     - use MExtractedSignalCam to extract charges
+
+   * manalysis/MExtractSignals.[h,cc]:
+     - new class to extract signals
+
+   * manalysis/MExtractedSignalCam.[h,cc]:
+     - new class to hold extracted signals
+
+   * manalysis/MExtractedSignalPix.[h,cc]:
+     - new class to hold extracted signals for pixel
+
+   * manalysis/Makefile
+   * manalysis/AnalysisLinkDef:
+     - contain MExtractedSignalCam, MExtractedSignalPix, MExtractedSignal
+
+   * macros/calibration.C
+     - EventDisplay which allows to get plot by clicking on pixel
+
+
+
+ 2003/12/08: Thomas Bretz
+
+   * mraw/MRawFileRead.cc:
+     - implemented an artificial time-stamp for the current data
+
+   * star.cc, macros/star.C:
+     - works now with MC files and real data.
+
+   * mimage/MHillas.[h.cc], mimage/MHillasExt.[h.cc], 
+     mimage/MHillasSrc.[h.cc]:
+     - implemented member functions Print(const MGeomCam&)
+
+   * macros/readMagic.C, macros/readCT1.C, mmain/MEventDisplay.cc:
+     - changed to display deg instead of millimeters
+
+   * manalysis/MEventRateCalc.[h,cc], manalysis/MEventRate.[h,cc]:
+     - updated algorithm
+
+   * macros/evtrate.C:
+     - tutorial how to calculate event rate added
+
+
+
+ 2003/12/07: Thomas Bretz
+
+   * mbase/MTime.[h,cc]:
+     - added some new member function
+     - fixed wrong calculations
+     - moved all stand-alone operators into class
+     
+   * mhist/MHPixVsTime.cc, mhist/MHVsTime.cc:
+     - fixed MTime handling
+
+   * Makefile.rules:
+     - removed obsolete $(HEADERS) from rule for $(LIB)
+     - added $(CINT)LinkDef.h for rule for $(CINT)Cint.cc
+     
+   * mbase/BaseLinkDef.h:
+     - added operator<<(ostream&, MTime&)
+     
+   * mmain/MOnlineDump.cc:
+     - fixed a small bug using MTime
+
+
+
+ 2003/12/05: Abelardo Moralejo
+ 
+   * mhistmc/MHMcCollectionArea.cc
+     - removed wrong comment in MHMcCollectionArea::CalcEfficiency2
+
+
+
+ 2003/12/05: Thomas Bretz
+
+   * mpointing/*:
+     - added
+
+   * Makefile:
+     - added mpointing
+
+   * NEWS:
+     - updated
+
+   * mbase/MTime.[h,cc]:
+     - complere rewrite of the data members
+     - ClassDef=3
+
+   * mfileio/MCT1ReadPreProc.cc, mfileio/MReadCurrents.cc,
+     mfileio/MReadReports.cc, mhist/MHPixVsTime.cc,
+     mhist/MHVsTime.cc, mmain/MOnlineDump.cc,
+     mmontecarlo/MMcTimeGenerate.cc, mreport/MReport.cc,
+     manalysis/MEventRateCalc.cc:
+     - adapted to new MTime
+
+   * mfileio/MReadReports.[h,cc]:
+     - added the possibility to enable Auto Scheme
+     - delete the TChains when removed
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - automaticalle create title for Trees
+     - added a 'Must-Have' flag for the added containers
+
+   * mreport/MReportCamera.h:
+     - added //! to all pointers
+
+   * mtools/MAstro.[h,cc]:
+     - added calculations from and to MJD
+     - moved to mbase
+
+   * mfileio/Makefile, mfileio/FileIOLinkDef.h:
+     - removed MReadCurrent
+
+   * readdaq.cc:
+     - changed to display board information on request 
+       (MRawCrateArray)
+
+   * mfileio/MReadMarsFile.cc:
+     - small changes to output
+     
+   * mfileio/MReadReports.[h,cc]:
+     - added 'Master' tree as a workaround for reading RunHeaders
+     
+   * mfileio/MReadTree.cc:
+     - call Notify() of all members of fNotify in Notify()
+     
+   * mraw/MRawCrateArray.[h,cc]:
+     - added Print() member function
+     
+
+
+
+ 2003/12/04: Markus Gaug
+
+   * manalysis/MCalibration*
+     - implemented some of Thomas Bretz suggestions to make the code
+       nicer
+     - implemented the possibility to have cosmics in the calibration
+       data and remove it
+     - implemented the conversion factors for the blind pixel method
+
+   * mhist/MHCalibration*
+     - implemented some of Thomas Bretz suggestions to make the code
+       nicer
+     - implemented the possibility to have cosmics in the calibration
+       data and still fit it
+
+   * macros/calibration.C
+     - MStatusDisplay of calibration histograms a little bit more readable
+
+
+
+ 2003/12/03: Abelardo Moralejo
+
+   * mimage/MStereoCalc.cc
+     - Fixed typo in the PreProcess (fmcevt1 was initialized a second
+       time, instead of fmcevt2).
+
+
+
+ 2003/12/02: Abelardo Moralejo
+
+   * mimage/MStereoCalc.[h,cc]
+     - changed names of variables (removed underscores). Use new
+       function MTask::AddSerialNumber  (see below).
+
+
+
+ 2003/12/02: Thomas Bretz
+ 
+   * mfilter/MFEventSelector2.[h,cc]:
+     - fixed and reorganized screen output
+     - added some small comments to the code
+     - moved some code from Process() to the new private function Select
+     - fixed uncounted events (underflow bins were not counted)
+     - renamed nonsens fErrors to fCounter
+     - fixed usage of fDisplay
+
+   * manalysis/MEventRate.[h,cc], manalysis/MEventRateCalc.[h,cc], 
+     mfileio/MReadReports.[h,cc], mreport/MReport*.[h,cc],
+     mcamera/MCamera*.[h,cc]:
+     - fixed and added comments.
+
+   * mbase/MTask.h:
+     - added static member functions AddSerialNumber to simplify 
+       using different Serial numbers.
+
+   * macros/readrep.C:
+     - updated to be an example for more functionality
+
+
+
+ 2003/12/01: Markus Gaug
+ 
+   * macros/calibration.C:
+     - adjusted some parameters
+
+   * manalysis/MCalibrationCalc.cc:
+     - cosmics are now skipped from the fit
+
+   * manalysis/MCalibrationPix:
+     - cosmics are now skipped from the fit
+
+   * mhist/MHCalibrationPixel:
+     - cosmics are now skipped from the fit
+
+   * manalysis/Makefile
+     - MPedCalcPedRun was not in Makefile
+
+   * manalysis/AnalysisLinkDef
+     - MPedCalcPedRun was not in AnalysisLinkDef
+
+
+
+ 2003/12/01: Thomas Bretz
+
+   * Makefile:
+     - added readdaq
+ 
+   * mona.cc:
+     - moved MOnlineDump behind hfilla/../d
+     
+   * macros/readrep.C:
+     - removed obsolete piece of code
+     - added 'writer'
+     - added code to read from file
+     
+   * mbase/MStatusDisplay.cc:
+     - removed obsolete workaround in HandleEvent. Found the bug
+       in MEventDisplay
+       
+   * mmain/MEventDisplay.cc:
+     - fixed a crash when switching to a tab without canvas
+     
+   * mmain/MOnlineDisplay.[h,cc]:
+     - removed obsolete code
+     
+   * mmain/MOnlineDump.cc:
+     - set maximum and minimum of 'sum' histogram to 0 and 15
+     
+   * mtemp/MObservatory.cc:
+     - changed telescope position (kMagic1) according to new data from GPS clock
+
+   * readraw.cc:
+     - changed includes
+     
+   * mbase/MPrint.[h,cc]:
+     - added kSeperator
+
+   * mbase/MTime.[h,cc]:
+     - added SetTime(const TTime&)
+
+   * mraw/MRawEvtHeader.cc:
+     - added 'nogains' option to Print
+     
+   * readdaq.cc:
+     - added
+
+   * mfilter/MFilterList.cc:
+     - added class description
+
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - removed obsolete MFAntiFilter (for a replacement see
+       class-description of MFilterList)
+       
+   * mfilter/MFRandomSplit.[h,cc]:
+     - fixed missing manipulators in fLog stream
+     - reset values in constructor which are out of range
+     - changed output in PostProcess according to the style in MHillasCalc etc.
+     - changed nonsense derivement from MF to MFilter
+
+   * mhist/MHCamera.[h,cc]:
+     - added DrawClone to get rid of the usage of gROOT->GetSelectedPad.
+       this resulted in some trouble in the past. If it will make more
+       trouble than before we can remove it again - please report problems.
+
+
+
+ 2003/12/1: Abelardo Moralejo
+
+   * mimage/MStereoPar.cc
+     - Added calculation of fCT1Impact2, fCT2Impact2, the estimates of
+       impact parameter using the a priori assumption that the events
+       come from a point source located at the center of the camera.
+
+
+
+ 2003/11/27: Wolfgang Wittek
+
+   * mfilter/MFEventSelector2.cc
+     - if number of requested events is too high reduce it to the maximum
+       number possible
+     - introduce the flag 'fUseOrigDistribution'; if it is set to kTRUE 
+       (by SetOrigDistribution()) the original distribution will be used
+       as the nominal distribution
+     - added member functions SetUseOrigDistribution()
+     - added member functions SetHistOrig()
+
+   * mfilter/MFRandomSplit.[h,cc]
+     - a filter which gives fResult = kTRUE with a certain probability
+
+   * mfilter/MFAntiFilter.[h,cc]
+     - a filter which checks the result of a given filter and returns 
+       the opposite result;
+       Thomas : could you please add a code which puts the filter whose 
+                result is checked into the task list ?
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h
+     - add MFRandomSplit and MFAntiFilter
+
+   * manalysis/MCT1FindSupercuts.[h,cc]
+     - in 'DefineTrainMatrix', 'DefineTestMatrix', and 
+       'DefineTrainTestMatrix()' :
+       replace call to 'MFEventSelector' by call to 'MFEventSelector2'
+     - add member function SetUseOrigDistribution(Bool_t b);
+       if b = kTRUE the events for the training and test samples are
+       selected randomnly from the input file
+
+
+
+ 2003/11/27: Abelardo Moralejo
+
+   * mdata/MDataChain.cc:
+     - added ';' as a possible alphanumeric character in the data 
+       string, to support the use of variables from MC stereo files
+       where the parameter containers for each telescope are tagged 
+       with a ';' followed by the telescope number. 
+
+
+
+ 2003/11/26: Thomas Bretz
+
+   * mhist/MHVsTime.[h,cc]:
+     - implemented usage of Event number
+
+   * mhist/MHPixVsTime.[h,cc]:
+     - implemented usage of time (untested - may not work)
+
+
+
+ 2003/11/25: Thomas Bretz
+ 
+   * mgeom/MGeomMirror.h:
+     - added Getter functions for Mirror Center and Mirror 
+       Normal vector
+
+
+
+ 2003/11/25: Abelardo Moralejo
+
+   * mimage/MStereoPar.[h,cc]
+   * mimage/MStereoCalc.[h,cc]
+     - Added. First version of some calculations for the data analysis
+       of two-telescope configurations (estimation of shower direction
+       and core position).
+   * mimage/Makefile, ImageLinkDef.h
+     - Updated accordingly.
+
+
+
+ 2003/11/23: Thomas Bretz
+
+   * star.cc:
+     - fixed a typo
+     
+   * manalysis/MCerPhotCalc.cc:
+     - fixed logging stream
+     
+   * mbase/MStatusDisplay.[h,cc]:
+     - made fLog available to derived classes
+     - added Reset()-function
+     - added some debug messages to CloseWindow()
+     - put 'return' back into HandleConfigureNotify (fixes the
+       problem with the random size of the Mona display)
+     - added a new workaround in HandleEvent which fixed a crash
+       when switching back to the 'main' tab in MEventDisplay
+       This is NOT understood!
+     - changed bit 14/15 to 15/16. BIT(14) is used in TGMainFrame
+       already
+     - fixed a typo. Must be kTabPrint instead of kFilePrint
+     
+   * mfilter/MFRealTimePeriod.h:
+     - added Setter for timeout
+     
+   * mhist/MHCamEvent.cc:
+     - fill the rms for each event. This may be switched off by
+       a status bit in the future for speed reasons.
+       
+   * mhist/MHCamera.[h,cc]:
+     - removed Profile() from GetMaximum/GetMinimum if no
+       autoscale is done
+     - added 'content' Draw option
+     - when kNoLegend is set draw the legend showing the size
+     
+   * mhist/MHEvent.cc:
+     - fixed a typo: GetNumEvents() --> GetRunNumber()
+     
+   * mhist/MHTriggerLvl0.cc:
+     - small changes to output
+     
+   * mraw/MRawSocketRead.[h,cc]:
+     - renamed fRawEvtTime to fTime
+     - changed 'MRawEvtTime' to 'MTime'
+     - added some debugging output in case of kContinue
+
+   * mmain/MOnlineDump.[h,cc], mmain/MOnlineDisplay.[h,cc]:
+     - added
+
+   * mmain/MainLinkDef.h, mmain/Makefile:
+     - added MOnlineDump
+     - added MOnlineDisplay
+
+   * mona.cc:
+     - updated
+
+   * manalysis/MEventRate.[h,cc], manalysis/MEventRateCalc.[h,cc]:
+     - added
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MEventRateCalc
+     - added MEventRate
+
+   * mgeom/MGeomMirror.h:
+     - fixed comments in the header - must be in one line!
+
+   * mreport/MReport.h:
+     - adde Getter-function for fState
+
+   * mreport/MReportDrive.[h,cc]:
+     - added GetAbsError() (preliminary!)
+
+
+
+ 2003/11/22: Thomas Bretz
+
+   * mreport/MReportCamera.cc:
+     - implemented real reading
+     - changed some loops to poinbter arithmetics
+
+   * mreport/Makefile:
+     - added mcamera
+
+   * merpp.cc:
+     - implemented preliminary support for report-files
+     
+   * star.cc:
+     - small changes to handling of update-mode
+     
+   * mbase/MParList.cc:
+     - fixed a wrong output
+     
+   * mbase/MTask.cc:
+     - fixed AddToBranchList(TString&)
+     
+   * mbase/MTime.[h,cc]:
+     - setfill only once
+     - fixed ()-operator
+     - removed nonsens GetTime()
+     
+   * mcamera/MCameraAUX.h, mcamera/MCameraCalibration.h,
+     mcamera/MCameraCooling.h, mcamera/MCameraHV.h,
+     mcamera/MCameraLV.h, mcamera/MCameraLid.h,
+     mcamera/MCameraLids.h, mcamera/MCameraPowerSupply.h:
+     - set version in ClassDef to 1
+
+   * mcamera/MCameraCooling.h:
+     - added Getter-functions
+
+   * mcamera/MCameraLV.h:
+     - changed fHumidity to Byte_t
+
+   * mcamera/MCameraLid.h:
+     - derived from MParContainer instead of TObject
+     
+   * mfileio/FileIOLinkDef.h, mfileio/Makefile:
+     - added MReadReports
+
+   * mfileio/MReadReports.[h.cc]:
+     - added
+
+   * mfileio/MReadTree.h:
+     - added MReadReports as friend class to allow access to fChain
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed output (didn't have the correct debug flags)
+     
+   * mhist/HistLinkDef.h, mhist/Makefile:
+     - added MHVsTime
+
+   * mhist/MHVsTime.[h,cc];
+     - added 
+     
+   * mhist/MFillH.cc:
+     - add eveything I know to BranchList
+     
+   * mraw/MRawFileWrite.[h,cc]:
+     - changed name of MTime from MRawEvtTime to MTime
+     - changed Tree names to:
+       + Events
+       + Pedestals
+       + Calibration
+     
+   * mreport/MReportTrigger.[h,cc]:
+     - fixed accoring to a discussion with Riccardo
+     - changed version number in ClassDef to 1
+
+   * mreport/Makefile:
+     - added mcamera
+
+   * macros/rootlogon.C:
+     - added colors
+     - changed the search path for libmars.so a bit
+     
+   * mdata/MDataList.[h,cc]:
+     - added support for '%'
+
+   * mhist/MHCamera.[h,cc]:
+     - removed DrawPixelIndices and DrawSectorIndices
+     - replaced by new Draw-options: 'sectorindex' and 'pixelindex'
+     - put together in PaintIndices
+     
+   * mmain/MEventDisplay.cc:
+     - added Sectors to tabs
+     - code for adding tab was in class twice (removed in
+       ReadinFirstEvent, uses AddGeometryTabs instead)
+       
+   * mreport/MReport.[h,cc]:  
+     - prpared to read new DC-REPORT files
+     
+   * mreport/MReportDrive.[h,cc]:
+     - removed debug 'D'
+     - added Getter-functions
+
+
+
+ 2003/11/21: Thomas Bretz
+
+   * mraw/MRawEvtData.cc:
+     - added type 3 and 4 to GetPixContent
+
+   * status.cc:
+     - added display of average index of slice witg maximum value
+     - implemented a scheme to exit the application and to 
+       leave it open when the loop is finished.
+       
+   * macros/status.C:
+     - added maximum index histogram
+     
+   * mbase/MStatusDisplay.[h,cc]:
+     - implemented kExitLoopOnExit and kExitLoopOnClose
+     
+   * mcamera/CameraLinkDef.h:
+     - added missing MCameraAUX and MCameraLid
+     
+   * mhist/MHCamEvent.[h,cc]:
+     - added fRms
+     
+   * mhist/MHCamera.cc:
+     - added error when printing pixel contents
+     
+   * mhist/MHTriggerLvl0.[h,cc]:
+     - use MHCamera::kProfile
+     - renamed PrintOutLayers to PrintOutliers
+     
+   * mmain/MEventDisplay.cc:
+     - made 'Mini-Canvas' working in all Tabs by catching kCM_TAB
+
+   * mhist/MFillH.[h,cc], mhist/MH.[h,cc]:
+     - implemented ReInit
+
+   * mbase/MParList.cc:
+     - implemented more sanity check whether a class can be created 
+
+   * Makefile:
+     - added mcamera
+     - added mreport
+     - added status
+     - added OBJS and MCint.o to the shared object
+     
+   * macros/readCT1.C:
+     - do not add non-existing geomcam to parlist
+     - add geomapl to tasklist
+     
+   * mcamera/MCameraCalibration.h, mcamera/MCameraCooling.h,
+     mcamera/MCameraHV.h, mcamera/MCameraLV.h, 
+     mcamera/MCameraLid.h, mcamera/MCameraLids.h,
+     mcamera/MCameraPowerSupply.h, mreport/MReportCamera.h:
+     - changed according to discussion with Pepe
+
+   * mtools/Makefile, mtools/ToolsLinkDef.h:
+     - added MAstro
+     
+   * mtools/MAstro.[h,cc]:
+     - added
+
+   * macros/readMagic.C, macros/readCT1.C:
+     - changed to display relative signal (which is compared to the
+       cleaning levels) and the cleaning levels
+
+
+
+ 2003/11/20: Markus Gaug
+
+   * macros/calibration.C
+     - all variables are now plotted in camera displays
+
+   * manalysis/MCalibrationPix:
+     - replaced fErrT by fSigmaT
+
+   * manalysis/MCalibrationCam.cc:
+     - replaced fErrT by fSigmaT
+
+   * mhist/MHCalibrationPix.cc:
+     - replaced GetErrT by GetSigmaT()
+
+
+
+ 2003/11/20: Wolfgang Wittek
+
+   * mimage/M2dimFunctionFit.[h,cc]
+     - removed; will be replaced by MFun2Fit.[h,cc]
+
+   * mimage/M2dimFunction.[h,cc]
+     - removed; will be replaced by MFunc2.[h,cc]
+
+   * mimage/MH2dimFunction.[h,cc]
+     - removed; will be replaced by MHFunc2.[h,cc]
+      
+
+
+
+ 2003/11/19: Markus Gaug
+
+   * manalysis/MCalibrationPix:
+     - new functions: GetPed(), GetPedRms(), GetQProb()
+     - new variable: fQProb
+
+   * manalysis/MCalibrationCam.cc:
+     - function GetPixelContent enlarged
+
+   * manalysis/MCalibrationCalc:
+     - function ReInit added like in MPedCalcPedRun
+
+
+
+ 2003/11/19: Thomas Bretz
+
+   * mreport/MReport.[h,cc]:
+     - replaced FindTime by SetupReading
+     - removed SetTime
+     
+   * mreport/MReportFileRead.cc:
+     - replaced SetTime by SetupReading
+
+   * mreport/MReportCamera.[h,cc]:
+     - use new stuff
+
+   * mcamera/*:
+     - added
+
+
+
+
+
+ 2003/11/19: Markus Gaug
+
+   * manalysis/MPedCalcPedRun:
+     - implemented function ReInit
+     - implemented pointer fRunheader
+     - fNumHiGainSamples now called from fRunHeader inside ReInit
+     - Now, fNumHiGainSamples gets right number, instead of inf
+
+   * mhist/MHCalibrationConig:
+     - gkStartQlast changed from 5000 to 10000.
+
+
+
+ 2003/11/18: Thomas Bretz
+
+   * mars.cc:
+     - changed Usage to standard Usage
+     
+   * merpp.cc, mona.cc, readraw.cc, star.cc, status.cc,
+     mbase/MArgs.[h,cc]:
+     - removed const-qualifier for argv
+     
+   * mbase/MTask.cc:
+     - fixed a bug in PrintStatistics (setfill was not set)
+     
+   * mbase/MTaskList.cc:
+     - simplified PrintStatistics
+   
+   * mbase/MTime.h:
+     - added Getter
+     
+   * mfileio/MReadTree.cc:
+     - remove a leading "*" when checking whether a branch which 
+       should be enabled exists
+       
+   * mfileio/MWriteRootFile.cc:
+     - fixed a crash when Print is called and GetTree() returns NULL
+     
+   * mhist/MHEvent.cc:
+     - implemented more levels (MeV, GeV, etc) for energy display
+     
+   * mraw/MRawSocketRead.cc:
+     - removed some obsolete comment
+     
+   * mreport/MReport.[h,cc]:
+     - added FindTime
+     - removed an invalid line (ReadAngle) in the header file
+     - Set class version to 1
+     - do not write fTime '//!'
+     
+   * mreport/MReportFileRead.cc:
+     - fixed handling of MTimes
+
+   * mhist/MH.cc:
+     - added some const qualifiers in CutEdges
+
+
+
+ 2003/11/18: Abelardo Moralejo
+
+   * mmc/MMcEvt.cxx:
+     - Fixed missing initialization of fLongitmax
+
+
+
+ 2003/11/18: Markus Gaug
+
+   * manalysis/MCalibrationCalc: 
+     - performs the eventloop and fills the calibration classes
+
+   * manalysis/MCalibrationCam: 
+     - holds the classes: MCalibrationPix and MCalibrationBlindPix
+       and MCalibrationPINDiode
+     - one MCalibrationPix per pixel
+
+   * manalysis/MCalibrationPix:
+     - holds the fit results and conversion factors, etc per pixel
+     - hold histograms MHCalibrationPixel
+
+   * manalysis/MCalibrationBlindPix:
+     - holds fit results and derived number of photons, etc
+     - hold histogram MHCalibrationBlindPixel
+
+   * manalysis/MCalibrationPINDiode:
+     - holds fit results and derived number of photons, etc
+     - hold histogram MHCalibrationPINDiode
+
+   * mhist/MHCalibrationPix:
+     - histograms with sum of charges, time slices and reduced
+       charges vs. event number
+     - fit functions
+
+   * mhist/MHCalibrationPixel:
+     - histograms with sum of charges, time slices and reduced
+       charges vs. event number
+     - fit functions
+
+   * mhist/MHCalibrationBlindPixel:
+     - histograms with sum of charges, time slices and reduced
+       charges vs. event number
+     - fit functions
+
+   * mhist/MHCalibrationPINDiode:
+     - histograms with sum of charges, time slices and reduced
+       charges vs. event number
+     - fit functions
+
+   * mhist/MH:
+     - new function: CutEdges
+
+   * macros/calibration.C
+     - simple macro showing the functionning
+
+
+
+ 2003/11/17: Thomas Bretz
+ 
+   * mbase/MLog.cc:
+     - replaced pthread_mutex by a TMutex
+     - renamed fgui to fGui
+     - renamed fout to fOut
+     
+   * mbase/MStatusDisplay.cc:
+     - removed ==13 using TryLock() (this was wrong)
+
+   * mreport/*
+     - added
+
+   * macros/readrep.C:
+     - added
+
+   * merpp.cc, readraw.cc:
+     - added option -?/-h
+     
+   * mona.cc:
+     - added MOnlineDump-class
+     - added port as a commandline option
+     - added commandline options
+     
+   * status.cc:
+     - added option -?/-h
+     - added filter to support MC and DAQ files
+     
+   * mdata/MDataChain.[h,cc]:
+     - added kERound
+
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MFRealTimePeriod
+     
+   * mgeom/MGeomCam.h:
+     - added InitGeometry
+     
+   * mgeom/MGeomCamCT1.cc, mgeom/MGeomCamCT1Daniel.cc,
+     mgeom/MGeomCamECO1000.cc, mgeom/MGeomCamECO1000HG.cc,
+     mgeom/MGeomCamMagic.cc, mgeom/MGeomCamMagic919.cc,
+     mgeom/MGeomCamMagicHG.cc:
+     - replaced Calc* by InitGeometry
+     
+   * mmain/MEventDisplay.cc:
+     - added a filter to support MC and real files
+     
+   * mmain/Makefile:
+     - added mdata and mfilter
+     
+   * mraw/MRawFileRead.cc:
+     - close file in PostProcess
+     
+   * mraw/MRawRunHeader.h:
+     - added a comment
+     
+   * mraw/RawIncl.h:
+     - removed some obsolete includes
+
+   * mhist/MH*:
+     - cleaned up many includes
+
+
+
+ 2003/11/15: Thomas Bretz, Abelardo Moralejo
+
+   * mhist/MH.h: 
+     - added fSerialNumber data member 
+
+   * mhist/MFillH.cc:
+     - distribute serial number to the MH object to be filled
+
+   * mranforest/MHRanForest.cc, mhist/MHHadronness.cc:
+     - added serial number to the MMcEvt container (does nothing unless
+       SetSerialNumber has been called for the corresponding MFillH)
+       This is intended to allow the use of Random Forest with MC
+       multi-telescope files.
+
+   * NEWS: 
+     - updated.
+
+
+
+ 2003/11/14: Abelardo Moralejo
+
+   * mfilter/MF.cc:
+     - added the possibility of using in the filter parameters from a
+       multi-telescope MC camera file, where master branches for each
+       telescope are tagged with ;i  being i  the number of telescope.
+       The change consists in the addittion in MF::IsAlNum of ';' as 
+       a possible alphanumeric character in the string.
+
+
+
+ 2003/11/13: Thomas Bretz
+
+   * macros/readCT1.C:
+     - fixed to work with the new MHCamera::Draw (see Mantis)
+     - changed to display event and cleaned event
+     
+   * macros/readMagic.C:
+     - fixed to work with the new MHCamera::Draw (see Mantis)
+
+   * mhist/MHEvent.cc:
+     - fixed display of the energy (see Mantis)
+     
+   * mmain/MEventDisplay.cc:
+     - fixed usage of small canvas with new MHCamera::Draw
+
+
+
+ 2003/11/11: Rudy Bock
+  
+   * mfilter/MFGeomag.[h,cc]:
+     - added a new class which reads two ASCII files (for +ve and -ve
+       particles) from the mfilter directory, and filters out 
+       low-energy charged Monte Carlo particles which do not reach the
+       earth's surface. Tables are from Adrian Biland. A method is
+       included which allows treating gammas as electrons (i.e. rejects
+       low energy particles).
+
+
+
+ 2003/11/11: Nicola Galante
+
+   * mhistmc/MHMcTriggerLvl2.[h,cc]:
+     - Removed 'const' qualifier for the returned object of the
+       method (TH1 *)MHMcTriggerLvl2::GetHistByName(const TString name)
+
+
+
+ 2003/11/10: Nicola Galante
+
+   * mhistmc/MHMcTriggerLvl2.[h,cc]:
+     - Changed return value of method MHMcTriggerLvl2::GetHistByName()
+       Now it returns a (TH1 *), no more a (TObject *), in order to keep
+       formal compatibility with the overloaded method of the mother
+       class TH1 *MH::GetHistByName(TString name)
+
+
+
+
+ 2003/11/10: Thomas Bretz
+  
+   * macros/dohtml.C:
+     - added mreflector
+     - removed mdatacheck
+     - removed mventdisp
+
+   * mbase/MEvtLoop.[h,cc]:
+     - removed instantiation of gListOfPrimitives
+     
+   * mbase/MGGroupFrame.h:
+     - minor change
+     
+   * mbase/MLog.cc:
+     - added a comment
+     
+   * mbase/MParContainer.[h,cc]:
+     - removed include MEvtLoop.h
+     - added instantiation of gListOfPrimitves
+     
+   * mbase/MReadSocket.[h,cc]:
+     - added more functionality
+     - added comments
+     - added Open() Close()
+     
+   * mbase/MTask.cc:
+     - removed obsolete include for MGGroupFrame
+
+   * mfilter/MFRealTimePeriod.h:
+     - initialize fTime with 0
+     
+   * mhist/MHCamEvent.cc, mhist/MHEvent.cc, mhist/MHTriggerLvl0.cc:
+     - removed creation of additional pad in Draw
+     
+   * mhist/MHCamera.cc:
+     - added creating of additional pad in Draw
+     - added some comments
+     
+   * mraw/MRawSocketRead.[h,cc]:
+     - added comments
+     - added fPort data member
+     - take MStatusDisplay status into account
+     - SetStausLine2 added
+     - removed obsolete include of iosfwd
+
+   * Makefile:
+     - changed makedepend line size
+     - renamed shared object from mars.so to libmars.so
+     - moved shared object from lib-directory to mars root directory
+     - make all executables load the shared object instead of statically 
+       linking
+     - removed mdatacheck
+
+   * Makefile.conf.darwin, Makefile.conf.linux, Makefile.conf.linux-gnu,
+     Makefile.conf.osf1, Makefile.conf.osf5.1:
+     - removed obsolete SUBDIRS in MARS_LIB
+     
+   * mars.cc:
+     - do not show logo if command line arguments are wrong
+
+   * macros/rootlogon.C:
+     - load libmars.so instead of lib/mars.so
+     - added mreflector to include path
+     - removed mdatacheck from include path
+     - removed mventdisp from include path
+     
+   * mmain/MStatusDisplay.[h,cc]:
+     - secure UpdateTab with a TMutex
+     - do not use MGTextView for root versions >= 3.02.05
+     - fixed a crash when all tabs where deleted, no tab was active
+       anymore
+     - show when updating postscript header
+
+   * mmain/MStatusDisplay.[h,cc], mmain/MSearch.[h,cc], mmain/MGMenu.[h,cc],
+     mmain/MSearch.[h,cc]:
+     - moved to mbase
+
+   * mmain/Makefile, mmain/MainLinkDef.h:
+     - removed MStatusDisplay
+     - removed MSearch
+     - removed MGMenu
+     - removed MProgressBar
+     - added MGDisplayAdc
+
+   * mbase/Makefile, mbase/MainLinkDef.h:
+     - added MStatusDisplay
+     - added MSearch
+     - added MGMenu
+     - added MProgressBar
+
+   * mdatacheck/Makefile, mdatacheck/DataCheckLinkDef.h:
+     - removed MGDisplayAdc
+
+   * meventdisp/Makefile, meventdisp/DataCheckLinkDef.h:
+     - removed MGCamDisplay
+     - removed MGEvtDisplay
+
+   * mdatacheck/MGDisplayAdc.[h,cc]:
+     - moved to mmain
+
+   * mona.cc:
+     - added ChangeContextMenus
+     - adapted to new MRawSocketRead interface
+     - assigned names to different tasks
+     - swiched off progress bar (temporarily)
+     - moved status display into thread
+     - exit thread by Exit() (seems to be necessary)
+     - added preliminary workaround for mssing RootPlugin
+
+   * mmain/MAnalysis.cc:
+     - removed external display
+     - added MStatusDisplay
+     
+   * mmain/MMonteCarlo.cc:
+     - old workaround (MMcEvt) obsolete
+
+   * mmain/MAnalysis.cc:
+     - do not call DisableAutoScheme
+     
+   * mmain/MCameraDisplay.cc:
+     - minor changes
+
+   * mgui/MCamDisplay.[h,cc], mmain/MEvtDisp.[h,cc],
+     meventdisp/MGCamDisplay.[h,cc], MGEvtDisplay.[h,cc],
+     meventdisp/MGFadcDisp.[h,cc], meventdisp/EvtDispIncl.h, 
+     meventdisp/EvtDispLinkDef.h, meventdisp/Makefile, meventdisp:
+     - removed (obsolete)
+
+   * mmain/MGDisplayAdc.[h,cc]:
+     - added ClassDef/ClassImp
+
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - corrected interpolation of all values (thanks to Nadia)
+     - fixed algorithm for pixels not existing yet
+
+   * manalysis/MCerPhotEvt.h:
+     - added return value to AddPixel
+
+
+
+ 2003/11/08: Nicola Galante
+
+   * mhistmc/MHMcTriggerLvl2.[cc,h]:
+     - Changed binning of histograms fHistLutPseudoSize, 
+       fHistLutPseudoSizeNorm, fHistSizeBiggerCell, 
+       fHistSizeBiggerCellNorm to fix an overflow bug
+     - In method GetHistByName(const TString name): changed the class 
+       of the returned object, now it returns a (TObject *), no more 
+       a (TH1F *), in order to return either (TH1 *) than (TH2 *); 
+       changed the order by which it checks the name of the
+       histogram in order to fix a bug in the lexing
+
+   * macros/triglvl2.C:
+     - Added some instruction to write all the MMcTriggerLvl2 histograms into
+       a TFile 
+
+
+
+ 2003/11/07: Thomas Bretz
+  
+   * mmain/MCameraDisplay.cc:
+     - changed MGCamDisplay to MEventDisplay
+     
+   * mmain/MMars.cc:
+     - removed 'Event Display' button
+     - removed MEvtDisp
+
+   * mmain/MEventDisplay.[h,cc], mhist/MHEvent.[h,cc]:
+     - added
+
+   * mmain/Makefile, mmain/MainLinkDef.h:
+     - removed MEvtDisp
+     - added MEventDisplay
+
+   * Makefile:
+     - removed mevtdisp
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - added MHEvent
+
+   * Makefile, Makefile.rules:
+     - automatically create dependancies
+
+   * NEWS:
+     - updated
+     
+   * mhist/MHCamera.[h,cc]:
+     - implemented kNoLegend=BIT(20)
+     - Clear pad before drawing Camera
+
+   * mmain/MStatusDisplay.cc:
+     - print when updating ps-header
+
+   * status.cc:
+     - added (not yet in Makefile)
+
+   * manalysis/MMcPedestalCopy.[h,cc]:
+     - made sure, that MPedestalCam is in the list 
+     
+   * mraw/MRawEvtData.cc:
+     - set the maximum/minimum of the fadc histograms
+     
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - added a fixes for the case that fData->fLoGainPixId->GetArray()=NULL
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - added MCameraData
+
+   * manalysis/MCameraData.[h,cc]:
+     - added
+     
+   * mhist/MHEvent.[h,cc]:
+     - fixed display of levels
+     - fixed unallowed characters
+     
+   * mimage/MImgCleanStd.[h,cc]:
+     - moved the calculation for signal/noise to MCameraData
+     
+   * mmain/MEventDisplay.cc:
+     - added display for cleaning data and levels
+
+
+
+ 2003/11/06: Antonio Stamerra
+
+   * manalysis/MMcTriggerLvl2.cc
+     - Removed annoying warning message and put it in the Print method.
+
+
+
+ 2003/11/05: Wolfgang Wittek
+
+   * macros/CT1Analysis.C, macros/ONOFFCT1Analysis.C:
+     - current versions of the macros for the analysis of CT1 data
+ 
+   * manalysis/MMarquardt.[h,cc]:
+     - very pleliminary version of a class performing a minimization 
+       using the Marquardt method
+
+   * mimage/M2dimFunctionFit.[h,cc]
+     - very pleliminary version of a class which fits a 2-dim function
+       to the shower image using the maximum likelihood method 
+
+   * mimage/M2dimFunction.[h,cc]:
+     - very pleliminary version of a container which contains the
+       parameters of the 2-dim function describing the shower image
+
+   * mimage/MH2dimFunction.[h,cc]
+     - very pleliminary version of a container holding the histograms
+       for the parameters of the 2-dim function describing the shower
+       image
+
+
+
+ 2003/11/05: Marcos Lopez
+  
+   * mmontecarlo/MMcWeightEnergySpecCalc.[h,cc]
+     - Now, if the new spectrum for the MC showers is a power law, we
+       don't convert it to a TF1 function.
+     - Changed the constructor for the case in which the new spectrum
+       is passed as a TF1 function. Now we pass the TF1 object by
+       reference.
+     - Thanks to the suggestions of T. Bretz, added three more
+       constructors to give the possibility of passing the shape of the
+       new spectrum in other different ways. Now, if the new spectrum
+       that you want for the MC showers is different from a power law,
+       you can specify its shape either with a TF1 function, with a
+       string (char*), or with a general C++ function defined by your
+       own. 
+     - In function Reinit(): added a sanity check to prevent from
+       dividing by zero.
+     - In PreProcess(): removed an unnecessary sentence.
+     - Fixed a compiling error which appeared under gcc 3.3
+	
+   * macros/weights.C
+     - addapted to show the new features introduced. 
+
+
+
+ 2003/11/05: Thomas Bretz
+  
+   * mbase/MTask.cc:
+     - initialize fSerialNumber=0
+
+   * mhist/MHCamera.cc:
+     - removed some obsolete IsUsed(idx) checks when filling the histogram
+     - ExecuteEvent now plots in the same canvas all the time
+
+   * mmain/MStatusDisplay.[h,cc]:
+     - added new data member fUserFrame
+     - added new member function AddUserFrame
+     - made call to ProcessEvent() and similar thread safe by
+       checking whether we run in the main thread or not.
+     - Set the progress bar range to (0,1)
+     - Added member function to set progress bar position
+     - updated comments
+     - added some workarounds for root bugs in TCanvas (sometimes
+       they call gPad->cd() indirectly when gPad==NULL)
+     - Fixed thread safety of UpdateTab()
+     - Fixed some crashes in case fTab==NULL
+     - Tried to make HandleConfigureNotify more flexible to allow
+       the new fUserFrame to work correctly - needs still some
+       investigations
+     - made fList a protected data member 
+     - added new member function Update()
+
+
+
+ 2003/11/04: Thomas Bretz
+  
+   * mmontecarlo/MMcTimeGenerate.cc:
+     - adapted to changes in MTime
+
+   * mgeom/MGeomCam.[h,cc]:
+     - precalculate pix ratio (and square root of it) for faster
+       calculations. This makes sense, because these values are
+       needed at least n times (while n is the number of pixels)
+       per event. Which results in billions of calculations already
+       for some events.
+     - implemented CalcPixRatio to do the precalculation
+     - changed class version of MGeomCam from 1 to 2
+
+   * mgeom/MGeomCamCT1.cc, mgeom/MGeomCamCT1Daniel.cc, 
+     mgeom/MGeomCamECO1000.cc, mgeom/MGeomCamMagic919.cc,
+     mgeom/MGeomCamECO1000HG.cc, mgeom/MGeomCamMagic.cc,
+     mgeom/MGeomCamMagicHG.cc:
+     - implemented CalcPixRatio to do the precalculation
+     - some simple code cleanup (removed obsolete comments, etc)
+   
+   * mgeom/MGeomPix.[h,cc]:
+     - replaces tan(60deg) by a build-in constant (fgTan60)
+     - pre calculate the area of the pixel in the constructor
+       (for speed reasons, see pixratio aboive)
+     - added fA
+     - changed version number from 1 to 2
+
+   * mimage/MImgCleanStd.cc, mimage/MImgCleanTGB.cc:
+     - directly use MGeomCam::GetPixRatioSqrt() now
+
+   * mraw/MRawSocketRead.cc:
+     - updated comment header
+     - updated class description
+     - removed obsolete fMutex, Lock() and UnLock()
+     - moved code from Do() to Process()
+     - added comments
+
+   * meventdisp/MGCamDisplay.cc:
+     - replaced MHillas:Clear() by Removing from ListOfPrimitives
+     
+   * mimage/MHillas.[h,cc]:
+     - removed fEllipse
+     - removed the Draw function
+     - added a correct Paint() function
+
+   * Makefile:
+     - added star
+     
+   * macros/star.C:
+     - removed obsolete MSrcPosCam (will be created automatically)
+     - made the macro work with a telescope serial number
+     
+   * mbase/MParContainer.[h,cc]:
+     - moved GetDescriptor to source file and added a function 
+       description
+     - changed GetDesciptor to be virtual
+       
+   * mbase/MTask.[h,cc]:
+     - added new data member fSerialNumber
+     - changed version number from 1 to 2
+     - added GetDescriptor aware of the serial number
+     - added Getter and Setter for serial number
+     - made StreamPrimitive serial number aware
+     
+   * mbase/MTaskList.[h,cc]:
+     - overwrote SetSerialNumber
+
+   * mfileio/MReadTree.cc:
+     - changed a C-cast to a C++-cast
+     
+   * mfileio/MWriteRootFile.h:
+     - changed BIT(16) to BIT(17). UPDATE mode was not working
+       with newer root versions, because BIT(16) was used already
+       
+   * manalysis/MBlindPixelCalc.cc, manalysis/MCerPhotCalc.cc,
+     manalysis/MGeomApply.cc, manalysis/MMcPedestalCopy.cc,
+     manalysis/MMcPedestalNSBAdd.cc, manalysis/MSigmabarCalc.cc,
+     mimage/MHillasCalc.cc, mimage/MHillasSrcCalc.cc, 
+     mimage/MImgCleanStd.cc:
+     - made serial number aware
+     
+   * mraw/MRawFileWrite.cc:
+     - automatically add .root extension
+
+   * star.cc:
+     - added
+
+
+
+ 2003/11/03: Thomas Bretz
+  
+   * manalysis/MMcPedestalCopy.[h,cc], manalysis/MMcPedestalNSBAdd.[h,cc]:
+     - fixed such, that it now works correctly with non-MC files
+     - moved container requests from PreProcess to ReInit
+     - removed some obsolete data members - made them locally
+     
+   * manalysis/MMcPedestalRead.[h,cc]:
+     - removed
+     
+   * mbase/MEvtLoop.cc:
+     - replaced the gApplication->InheritsFrom(TRint::Class())
+       workaround for thread safty by the more correct check
+       whether we are running in the main Thread (TThread::Self())
+     - added double-cast to TProgressBar::SetPosition
+       
+   * mbase/MTask.h:
+     - added the missing const-qualifier to GetNumExecutions
+     
+   * mbase/MTaskList.cc:
+     - fixed a typo in the output
+     
+   * mimage/MHillasCalc.[h,cc]:
+     - replaced TArrayC by TArrayL to support huge number of events
+     - added PrintSkipped
+     - added comments to the data members
+
+   * mars.cc:
+     - added code for a possible use of a TGApplication
+       (in comments)
+
+   * merpp.cc, readraw.cc:
+     - unified with the other executables (StartUpMessage, etc)
+     - removed TROOT-object
+     - readraw.cc: added more functionality
+
+   * mraw/MRawEvtData.cc:
+     - changed positions of 'fush' in Print() (this confused 'more'
+       because 'more' also counts the ANSI color codes to determin
+       the line-length)
+
+   * mhistmc/MHMcCollectionArea.cc:
+     - added UseCurrentStyle such that the axis labels are displayed
+
+   * mbase/MTime.[h,cc]:
+     - removed fTimeStamp
+     - increased version number
+     - changed Print() function
+     - removed obsolete functions and constructors
+     - fixed copy constructor
+     
+   * mfileio/MCT1ReadPreProc.cc:
+     - replaced SetTime by SetCT1Time
+     
+   * mhist/MHAlphaEnergyTime.cc, mhist/MHEnergyTime.cc,
+     mhist/MHThetabarTime.cc, mhist/MHTimeDiffTheta.cc,
+     mhist/MHTimeDiffTime.cc:
+     - adapted to changes in MTime
+     
+   * mraw/MRawEvtHeader.cc:
+     - adapted to changes in MTime
+     - minor change to output in Print()
+
+
+
+ 2003/10/31: Marcos Lopez
+
+   * mhist/MFillH.cc:
+     - Fixed a bug in function PreProcess(MParList *pList). Inside the 
+       conditional sentence "if (!fWeight && !fWeightName.IsNull())",  
+       fWeight never pointed to the object MWeight recoverd from the 
+       parameter list.
+
+   * mhistmc/MHMcEnergyImpact.cc:
+     - In the Fill function, pass the weight to the histogram fHist.
+
+   * mmontecarlo/MMcWeightEnergySpecCalc.[h,cc]:
+     - Added new class for changing the energy spectrum of the showers 
+       simulated with Corsika to a different one, be using weights   
+			
+   * mmontecarlo/Makefile, MonteCarloLinkDef.h
+      - Added the new class.
+ 
+   * macros/weights.C
+      - Added macro showing how to transform the spectrum of the MC showers.
+
+
+
+
+
+ 2003/10/31: Thomas Bretz
+
+   * mars.cc:
+     - change TGApllication back to TApplication (TGApplication doesn't
+       load the TVirtualPad plugin by default) DISPLAY must be set
+       manually if it is not set.
+
+
+
+ 2003/10/30: Antonio Stamerra
+
+   * manalysis/MMcTriggerLvl2.[h,cc]
+     - Added method CalcTriggerPattern to check which x-NN compact
+       pattern the event satisfies. The variable member fTriggerPattern 
+       contains the number x (x=3,4,5,6,7). 
+     - Inline function GetTriggerPattern added.
+
+   * manalysis/MMcTriggerLvl2Calc.cc
+     - Added call to the MMcTriggerLvl2::CalcTriggerPattern in Process().
+
+
+
+ 2003/10/30: Thomas Bretz
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - fixed a bug in the new Lut-stuff. Sometimes pixels where
+       considered existing, because there where no mark for 
+       empty entries in the Lut.
+     - all loops ignored pixel with index 0 and used it as reference
+       pixel - this is wrong, because pixel 0 must not exist at all.
+       Now all loops are starting with pixel 0.
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - renamed various local variables from 'id' to 'idx'
+     - in clean step 4 we assumed that a pixel with idx2 is existing
+       - this is a dangerous assumption. It is checked now.
+
+
+
+ 2003/10/29: Thomas Bretz
+  
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - removed MMcPedestalRead
+
+   * manalysis/MMcPedestalCopy.[h,cc]:
+     - merged functionality of MMcPedestalRead into it
+     - do not remove itself from the tasklist, but check 
+       the file type for each file again.
+     - added const-qualifiers in the class header
+       
+   * manalysis/MMcPedestalNSBAdd.[h,cc]:
+     - don't do something if camera file version is < 0.7
+     - do not remove itself from the tasklist, but check 
+       the file type for each file again.
+     - added const-qualifiers in the class header
+     
+   * mgui/MCamEvent.cc:
+     - added a comment
+     
+   * mimage/MHillasCalc.[h,cc]:
+     - replaced the fixed size array fErrors by a dynamic size array
+       (TArrayC) to make sure, that people get a warning on the
+       screen if the reprogram the error handling and write
+       into an unallowed index.
+
+
+
+ 2003/10/28: Thomas Bretz
+  
+   * macros/readCT1.C:
+     - fixed to work with the correct geometry
+     
+   * macros/readMagic.C:
+     - fixed - was crashing
+     
+   * macros/tar.C:
+     - exclude 'Tag' files from tar
+     
+   * manalysis/MGeomApply.[h,cc]:
+     - replaced constructor by SetGeometry (constructor was
+       not unique)
+
+   * mbase/MEvtLoop.[h,cc]:
+     - set fProgress already when setting fDisplay (gives the
+       possibility to overwrite fProgress)
+     - removed 'entries' from ProcessGuiEvents (moved to fNumEvents)
+     - Set ProgressBar position in percent instead of event number
+     - Set progress bar range from 0 to 1
+     
+   * mbase/MReadSocket.cc:
+     - fixed to treat timeout correctly
+     - replaces usleep() by gSystem->Sleep()
+
+   * mbase/MTime.h:
+     - added SetTime(ULong_t) (support for gSystem->Now())
+     - added SetTime(Double_t)
+     - added operator()
+     - fixed all comparison operators to use time instead of
+       time lo/hi - will be removed soon
+       
+   * mimage/MHHillasSrc.cc:
+     - delete 3rd Pad
+     
+   * mraw/MRawEvtData.cc:
+     - when drawing print gPad
+
+
+
+ 2003/10/28: Wolfgang Wittek
+
+   * manalysis/MCT1PadONOFF.cc
+     - replace GetMeanRms() by GetPedestalRms()
+     - replace SetMeanRms() by SetPedestalRms()
+     - reactivate code which was commented out by tgb
+       (no compilation errors on Alpha OSF)
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile
+     - put back MCT1PadONOFF
+
+   * macros/CT1Analysis.C, macros/ONOFFCT1Analysis.C
+     - current versions of macros for the analysis of CT1 data
+
+
+
+ 2003/10/26: Oscar Blanch Bigas
+
+   * mmc/MMcFadcHeader.[cc,h]
+     - Added variable member that has the sigma of the electronic noise
+       that goes with the same value to both FADC gains (fDigitalNoise)
+     - Class version has been changed from 2 to 3.
+
+
+
+ 2003/10/24: Abelardo Moralejo
+
+   * manalysis/MMcPedestalRead.[cc,h]
+     - Added. In coming camera version (0.7) the pedestal sigma per 
+       FADC slice is calculated by the camera simulation at run time, 
+       then written to the output file. This class reads in the pedestal
+       mean and sigma to be later used in the analysis (for tail cuts 
+       mainly). This task will replace MMcPedestalCopy and 
+       MMcPedestalNSBAdd for camera >= 0.7 files, for which the second
+       class would produce wrong results.
+
+
+
+ 2003/10/23: Abelardo Moralejo
+
+   * mhistmc/MHMcEnergyMigration.cc
+     - Changed the Draw procedure: with new root versions (3.04, 3.05)
+       the result of the used drawing options was different from what 
+       we had in 3.02, and the graphics output had become unreadable. 
+       Replacing some Draw() calls by DrawCopy() has solved the problem.
+
+
+
+ 2003/10/23: Thomas Bretz
+
+   * macros/star.C:
+     - replaced geometry by the task MGeomApply
+
+   * manalysis/MCerPhotCalc.cc:
+     - fixed typo
+
+
+
+ 2003/10/22: Thomas Bretz
+  
+   * mars.cc:
+     - replaced TApplication by TGApplication
+     - removed TROOT
+     - reset Batch mode in any case
+     
+   * meventdisp/MGCamDisplay.cc:
+     - use new MHCamera::SetLevels to display cleaning levels
+     
+   * mhist/MHCamera.[h,cc]:
+     - removed FillLevels - obsolete
+     - added SetLevels instead
+
+
+ 2003/10/21: Wolfgang Wittek
+
+  * manalysis/MMatrixLoop.[h,cc]
+    - member function PreProcess() put from .h to .cc
+
+  * mhist/MHMatrix.[h,cc]
+    - member function SetNumRow() put from .h to .cc
+
+
+
+ 2003/10/20: Thomas Bretz
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - changed name of member function from GetNumMax[Hi,Lo]GainSamples
+       to GetIdxMax[Hi,Lo]GainSamples
+  
+   * manalysis/MMcPedestalCopy.cc:
+     - changed GetPedestalRms to GetElecNoise to make Mars compile with
+       the changes done in MMcFadcHeader
+
+   * mmc/MMcTrig.cxx:
+     - changed <iostream.h> to <iostream> according to C++
+
+   * mhistmc/MHMcTriggerLvl2.[h,cc]:
+     - MHMcTriggerLvl2::GetHistByName removed const-qualifier and 
+       changed return type to TH1 according to definition in MH.
+
+   * macros/status.C:
+     - use MDirIter instead of a single file name
+     - adde MHTriggerLvl0
+     - Simplified macro by using PrintOutliers
+
+   * mhist/MHCamEvent.[h,cc]:
+     - renamed PrintOutlayers to PrintOutliers
+     - Divide pad only into two subpads
+
+   * mfilter/MF.cc:
+     - added comment about '=='
+
+   * mhist/MHMatrix.cc:
+     - removed some pieces of code which preserved the contents
+       of a matrix when resizing. This is done by root now.
+
+   * mfilter/MFRealTimePeriod.[h,cc]:
+     - added
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - added MFRealTimePeriod
+
+   * mars.cc:
+     - moved Start-up-message to StartUpMessage()
+
+   * manalysis/MBlindPixelCalc.h, manalysis/MCT1FindSupercuts.cc,
+     manalysis/MCerPhotAnal.h:
+     - minor changes
+
+   * mhist/MHCamera.[h,cc]:
+     - added Profile-option (display contents/entries)
+     - added Freeze-option  (ignore filling data into the histogram)
+     - added UseCurrentStyle to get the y-axis back
+     - overwrite DrawCopy
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added fLut to accelerate searching an index a lot, this should
+       be backward compatible to old class versions
+     - increased class version to 2
+     - removed all searches for indices - replaced by GetPixById
+     - GetPixById no uses the look-up-table, which is much much faster
+       and still searches the array if the fLut size is 0 which might
+       be because of a class version 1 object is read from a file -
+       according to Rene this should work.
+
+   * manalysis/MPedestalCam.[h,cc]:
+     - replaced a C-cast by a C++ static_cast
+
+   * mhist/MH.[h,cc]:
+     - renamed them from Draw/DrawCopy to DrawSame/DrawSameCopy
+
+   * mraw/MRawEvtData.[h,cc]:
+     - changed arrays to '//->'
+     - overwrote Copy() member function
+
+   * mhist/MFillH.[h,cc]:
+     - added GetCanvas()
+
+   * mhist/MHHadronness.cc, mimage/MHHillasExt.cc,
+     mimage/MHNewImagePar.cc:
+     - changed Draw to DrawSame
+
+   * mhist/MHCamEvent.cc:
+     - use new MHCamera profile mode
+
+   * mbase/MEvtLoop.cc, mmain/MStatusDisplay.cc:
+     - check whether application is TRint to make mone thread safe
+       This is necessary not to call ProcessEvents() twice at the
+       same time!
+
+
+
+ 2003/10/17: Oscar Blanch
+
+   * mmc/MMcFadcHeader.[cxx,hxx]:
+     - Added variable members to store the pedestal sigma from thte
+       camera simulation porgram: fPedesSigmaHigh fPedesSigmaLow
+
+   * mmc/MMcRunHeader.cxx:
+     - fill fNumEvts with number of stored events
+
+   * mmc/MTriggerDefine.h:
+     - Trigger zone for CT1 cameras up to 126 pixels
+
+   * mgeom/MGeomMirror.cc:
+     - fixed bug in filling axis desviation
+
+
+
+ 2003/10/15: Thomas Bretz
+
+   * Makefile.conf.general:
+     - added libThread to support mona
+     
+   * manalysis/MCerPhotAnal2.cc:
+     - changed comments
+     - accelerated the code a bit by using pointer arithmetic
+     
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MReadSocket
+
+   * mbase/MReadSocket.[h,cc]:
+     - added MReadSocket
+     
+   * mbase/MEvtLoop.cc:
+     - fixed some crashes in ProcessGuiEvents
+     
+   * mbase/MFilter.cc:
+     - changed header
+     
+   * mbase/MTime.h:
+     - added operator double() 
+
+   * mimage/MHillas.cc:
+     - changed the comments about corrxy
+     
+   * mmain/MStatusDisplay.[h,cc]:
+     - added many comments
+     - added kFileClose stuff
+     - added AddRawTab
+     - added thread handling in UpdateTab
+     - fixed deletion in case the pointer is on heap
+     - added date/time to ps-output
+     
+   * mraw/MRawEvtHeader.cc:
+     - added some comments about the total number of bytes read
+     
+   * mraw/MRawRunHeader.[h,cc]:
+     - added some comments about the total number of bytes read
+     - fixed treating files with 0xc0c1 as Magic-Number
+     - added GetNumTotalBytes
+
+   * mraw/Makefile, mraw/RawLinkDef.h:
+     - added MRawSocketRead
+
+   * mraw/MRawSocketRead.[h,cc]:
+     - added
+
+   * mona.cc:
+     - added
+
+
+
+ 2003/10/05: Abelardo Moralejo
+
+   * macros/star.C:
+     - returned to revision 1.9 (I had committed by mistake a private 
+       version of the macro, sorry!)
+
+
+
+ 2003/10/04: Thomas Bretz
+
+   * macros/MagicHillas.C, macros/pedestalvstime.C, macros/pixfirerate.C,
+     macros/pixsatrate.C, macros/readCT1.C, macros/readMagic.C,
+     macros/starplot.C, macros/status.C, macros/sumevents.C,
+     macros/sumeventserr.C, macros/sumeventsrms.C, macros/sumpedestalrms.C,
+     macros/sumpedestals.C, mmain/MDataCheck.cc:
+     - added MGeomApply
+     
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MGeomApply
+
+   * manalysis/MBlindPixelCalc.cc:
+     - for buid-in pixel numbers added a check whether the geometry
+       is mathcing
+       
+   * manalysis/MCerPhotCalc.cc, manalysis/MMcPedestalCopy.cc, 
+     manalysis/MMcPedestalNSBAdd.cc, meventdisp/MGCamDisplay.[h,cc],
+     meventdisp/MGEvtDisplay.[h,cc], mhist/MHFadcCam.cc:
+     - fixed that it can deal with variable size arrays
+
+   * manalysis/MGeomApply.[h,cc]:
+     - added. This task will take care of different geometries
+
+   * manalysis/MPedestalCam.cc:
+     - initialize array with size 1
+     - do not call new operator
+     
+   * mbase/MArgs.cc, mbase/MDirIter.cc:
+     - added comments
+     
+   * mdatacheck/MGDisplayAdc.cc:
+     - fixed a small bug in setting slider position for different geometries
+     
+   * mfileio/MWriteRootFile.cc:
+     - automatically append '.root' to file name
+     
+   * mhist/MHCamera.cc:
+     - added Init function
+     - moved parts of the construtor to Init function
+     - added default constructor
+     - added possibility to change geometry after creation by SetGeometry
+     - added many sanity checks (fNcells<=1)
+
+
+
+ 2003/10/02: Thomas Bretz
+
+   * mraw/MRawEvtData.cc:
+     - changed Draw so that also lo-gains are displayed.2
+
+
+
+ 2003/10/01: Nicola Galante
+
+   * mhistmc/MHMcTriggerLvl2.[h,cc]:
+     - in method MHMcTriggerLvl2::Fill added filling of 2D histograms
+       of fLutPseudoSize vs. energy and of fSizeBiggerCell vs. energy
+     - modified method MHMcTriggerLvl2::GetHistByName which now
+       can return any histogram (data member) of the class
+       MHMcTriggerLvl2 (now it returns a (TObject *) not a (TH1F *))
+     - Updated option list of the methid MHMcTriggerLvl2::DrawClone
+
+   * macros/triglvl2.C:
+     - Updated according with changes in class MHMcTriggerLvl2
+
+
+
+ 2003/09/30: Robert Wagner
+
+   * mfileio/MCT1ReadPreProc.cc
+     - undone change from 2003/09/26
+     - MJD is filled in fTime.Duration
+
+
+
+ 2003/09/29: Nicola Galante & Antonio Stamerra
+
+   * mmc/MMcTrig.cxx:
+     - Fixed a bug in function IsPixelFired():  the binary shift, introduced 
+       by T.B. to replace "pow" for power of two, was wrong. 
+       The correct operator to be used is "<<" and not ">>"! 
+
+   * manalysis/MMcTriggerLvl2.[h,cc]:
+     - Added method "CalcEnergy(MMcEvt *)" used to get correlation between
+       energy and size.
+     - Removed graphical functions "Drawcell" and "DrawLvl1"
+     - Fixed bug in the pixcell setting (pixel numbering in the cell starts 
+       from 0 but gsPixelInLut starts from 1).   
+     - Fixed bug in the "check" variable.	
+
+   * manalysis/MMcTriggerCalc.[h,cc]:
+     - Added call to MMcTriggerLvl2::CalcEnergy() in Process() 
+     - Removed 'const' from fMcEvt declaration	
+
+   * mhistmc/MHMcTriggerLvl2.[h,cc]:
+     - Added method "Draw2DHist" (draw correlation between
+       energy and size)
+     - Fixed bug in "DrawClone" function (histogram normalization)
+
+   * macros/triglvl2.C:
+     - Fixed a bug in the task list order to apply correctly the filters
+     - Now it writes on disk a root file with some histograms
+
+
+
+ 2003/09/26: Robert Wagner
+
+   * mfileio/MCT1ReadPreProc.cc
+     - provisionally pass complete event time to fTime container,
+       units are MJDs instead of seconds for the time being
+
+
+
+ 2003/09/25: Abelardo Moralejo
+
+   * macros/MagicHillas.C, star.C
+     - Added cast: TArrayF w(15,(Float_t*)x) to get rid of warning.
+
+
+
+ 2003/09/24: Abelardo Moralejo
+
+   * macros/MagicHillas.C, star.C
+     - Added const qualifier to TArrayF w(15,x); I got a crash due to
+       this missing qualifier when changing some code in MCerPhotCalc
+       (not yet submitted).
+
+   * macros/CT1Hillas.C
+     - removed code containing TArrayF w(15,x) (which was commented)
+       since it made no sense for CT1.
+
+
+
+ 2003/09/24: Wolfgang Wittek
+
+   * mfilter/MFEventSelector2.[h,cc]
+     - execution statistics added
+
+   * mhist/MHFindSignificance.cc
+     - add fHist->UseCurrentStyle()
+       to get the y-axis + labels drawn
+
+   * mhist/MHMatrix.h
+     - replace   Int_t fNumRow  //!   
+            by   Int_t fNumRow  //
+       because otherwise fNumRow is not defined when MHMatrix object is read in
+       after it had been written out
+
+   * mhist/MHCT1Supercuts.cc
+     - change title of object
+
+   * manalysis/MMinuitInterface.cc
+     - add arguments maxcalls and tolerance to SIMPLEX call
+
+   * manalysis/MCT1SupercutsCalc.[h,cc]
+     - add variables asymmetry, conc, leakage
+
+   * manalysis/MCT1Supercuts.[h,cc]
+     - add variables asymmetry, conc, leakage
+     - add TArrayD fStepsizes (initial step sizes for the parameters)
+
+   * manalysis/MCT1FindSupercuts.cc
+     - replace MGeomCamCT1Daniel by MGeomCamCT1
+     - arguments 'parSCinit', 'params' and 'steps' added in FindParams() ;
+         parSCinit is the name of the file containing the initial
+         values of the parameters
+         'params' and 'steps' are the initial values in case parSCinit == ""
+     - add member functions GetMatrixTrain() and GetMatrixTest()
+     - remove member function WriteMatrix()
+       because it didn't work; now the matrices are written out in
+       DefineTrainMatrix(), DefineTestMatri() and DefineTrainTestMatrix()
+
+   * macros/CT1EgyEst.C
+     - don't use Daniel's energy estimator
+
+   * mmontecarlo/MMcEnergyEst.cc
+     - extend printout of comments
+
+
+
+ 2003/09/17: Abelardo Moralejo
+
+   * manalysis MCerPhotCalc.cc:
+     - in warning about saturating low gains in pixels: changed the 
+       'if' by a 'switch' and slightly corrected text of warning (no 
+       change in performance or results).
+
+
+
+ 2003/09/16: Abelardo Moralejo
+
+   * manalysis MCerPhotCalc.[h,cc]:
+     - added the low gain treatment. It has first been implemented by
+       TB, and the version I submit is a slightly modified one. If any 
+       high gain FADC slice is saturated, we switch to low gain. If low 
+       gain is also saturated, the signal is nevertheless calculated 
+       ("truncated" of course), and a warning is displayed reporting 
+       the number of saturated pixels in the current event. 
+       Fixed also the calculation of the mean pixel pedestal (added 
+       variable fSumWeights), which previously would not work correctly 
+       in the case that one sets weights different from 0 or 1 in the 
+       array fWeight (which was anyway not done up to now, as far as I 
+       know). It would be necessary to add to the parameters of the 
+       analyzed events the number of saturated pixels in some way. 
+       In the MC files produced with camera versions 0.6 or earlier, no
+       low gain is simulated, and saturation of high gain is not 
+       correctly implemented, so this should not introduce any change
+       in the analysis of present or old MC files.
+
+
+
+ 2003/09/12: Thomas Bretz
+ 
+   * mimage/MHillasSrc.cc:
+     - fixed the NaN-problem in the calculation of Alpha. More 
+       information can be found in the comments there.
+
+   * mhist/MHFadcCam.[h,cc]:
+     - skip MC events which have no FADC information stored
+     - better output in case of changes in the number of slices
+     - added size argument to constructor to support ECO100, too.
+     - removed all fixed numbers and replaced them by the corresponding
+       function
+     - fixed pixel numbering to be consistent with the software pixel
+       numbering in the rest of Mars
+
+   * mhist/MHFadcPix.[h,cc]:
+     - fixed the missing y-axis (UseCurrentStyle()) 
+     - fixed pixel numbering by changing default arument of pixid in
+       constructor from 0 to -1
+
+   * mmain/MDataCheck.cc
+     - added 'Time Spectra of Cosmics' button
+     - added size argument to instatiation of MHFadcCam
+
+
+
+ 2003/09/10: Thomas Bretz
+ 
+   * mdata/MDataChain.[h,cc]:
+     - added log2, acosh, asinh, atanh, ceil, isnan and finite
+     - changed math.h callings to TMath:: namespace to be more
+       consistent
+       
+   * mhist/MHMatrix.[h,cc]:
+     - added RemoveInvalidRows member function to get rid of rows
+       containing invalid numbers (nan, inf)
+
+   * mraw/MRawEvtHeader.cc:
+     - fixed variable types calculating the time (ns, s, m and h)
+       to get rid of some compiler warnings, casting the values 
+       for-, back- and forward only wasts computing time.
+
+
+
+ 2003/09/08: Abelardo Moralejo
+
+   * mhist/MHOnSubtraction.cc: 
+     - added some casts in the arguments of function calls, to get rid 
+       of compilation warnings due to mismatch of variable type 
+       (variables: lowerBin, upperBin). Corrected order of arguments in 
+       TH1D constructor of fSignificanceHist (number of bins and bin 
+       limits).
+
+   * mraw/MRawEvtHeader.cc:
+     - Added casts to arguments of fTime->SetTime(h, m, s, ns) to get 
+       rid of compilation warnings.
+
+   * mhist/MHCamera.cc:
+     - Changed calls to abs and fabs by TMath::Abs. At least in RH7.2 
+       with gcc2.96, abs() was not recognized.
+
+
+
+ 2003/09/07: Abelardo Moralejo
+
+   * manalysis/MCerPhotCalc.cc:
+     - removed normalization of array fWeight introduced on 30/06. For
+       now, this array is intended only to select the FADC slices which
+       we want to integrate to get the signal. The use of this feature
+       of MCerPhotCalc is explained in the example macro MagicHillas.C
+       The array fWeight must contain 0's and 1's. If we normalize
+       these values, the signal units is no longer ADC counts (but 
+       "average ADC counts per slice"). As David realized, this was the 
+       reason for the discrepancies in the gamma/hadron separation 
+       results we were observing lately. The meaning of Size was 
+       different among the different people working on the subject, and 
+       hence, when we compared samples with a given Size cut we were
+       actually comparing different energy ranges.
+
+     - Turned fSumQuadWeights to its original meaning, the quadratic 
+       sum (square root of the sum of the squares) of the values in the 
+       fWeight array. Why was this changed?? (sqrt removed) Only because 
+       of the name of the variable??
+
+     - Changed the calculation of the mean pedestal to fit the meaning
+       of fSumQuadWeights.
+
+     - Moved the call to ScalePedestals() to the end of the ReInit 
+       function. Formerly it was called before the setting of the 
+       variable fEnableFix, and then the mean pedestal in each FADC 
+       slice was wrong by 0.5 units... once more: please Thomas B, 
+       be careful with these kind of changes.
+
+
+
+ 2003/08/27: Thomas Bretz
+
+   * mhist/MH3.cc:
+     - fixed missing UseCurrentStyle for newer root versions
+
+
+
+ 2003/08/26: Thomas Bretz
+
+   * mimage/MHHillas.cc, mimage/MHHillas.cc, mimage/MHHillasExt.cc,
+     mimage/MHNewImagePar.cc:
+     - fixed missing UseCurrentStyle for newer root versions
+
+
+
+ 2003/08/26: Wolfgang Wittek
+
+    * manalysis/MCT1FindSupercuts.cc
+      - set size of fStep, fLimlo, fLimup, fFix
+      - in 'fcnsupercuts' : get total number of parameters by calling 'mnstat'
+
+    * manalysis/MCT1Supercuts.[h,cc]
+      - extend error printout
+
+    * manalysis/MMinuitInterface.cc
+      - do not delete the Minuit object because it will still be used
+
+    * mhist/MHFindSignificance.cc
+      - formulaBackg was wrong
+
+
+
+ 2003/08/26: Robert Wagner
+
+    * mraw/MRawRunHeader.h
+      - Added Setter for MJD
+
+    * mfileio/MCT1ReadPreProc.cc
+      - Fill MJD from Preproc run header in fRawRunHeader 
+
+
+
+ 2003/08/22: Wolfgang Wittek
+
+    * mhistmc/MHMcCT1CollectionArea.cc
+      - change selection of theta bin in 'CalcEfficiency()'
+        (to be mored flexible in choosing the theta binnning)
+
+
+
+ 2003/08/21: Thomas Bretz
+
+   * manalysis/MCT1FindSupercuts.[h,cc], manalysis/MCT1Supercuts.[h,cc], 
+     manalysis/MCT1SupercutsCalc.[h,cc], manalysis/MMinuitInterface.[h,cc],
+     mhist/MHFindSignificance.[h,cc]: 
+     - changed some variables and member functions with respect to an upcoming
+       Minimization Class
+     - simplified some calls
+     - replaced fixed size arrays by variable size arrays
+     - added some sanity checks
+     - simplified some variable usage
+
+   * mhist/MHCT1Supercuts.[h,cc]:
+     - removed obsolete SetupFill
+
+
+
+ 2003/08/20: Thomas Bretz
+
+   * mhist/MHCamEvent.[h,cc]:
+     - added PrintOutlayers
+     
+   * mhist/MHHadronness.cc:
+     - changed PrintOutput
+     - set some Grids in plots
+     
+   * mhist/MHMatrix.cc:
+     - removed obsolete call to MEvtLoop::SetName
+     - Changed name to something more intuitive
+     
+   * mranforest/MRanForest.cc, mranforest/MRanTree.h:
+     - removed ^M
+     
+   * mranforest/MRanTree.cc:
+     - removed obsolete check for gRandom
+     - replaced mvar*numdata by a new variable mn
+
+
+
+ 2003/08/19: Thomas Hengstebeck
+
+   * mranforest/MRanForest.cc:
+     Removed error in calculation of fDataRang in CreateDataSort().
+     In the loop where fDataRang is set, the local variable v must 
+     be used with indices n1 and n2.   
+
+
+
+
+ 2003/08/19: Wolfgang Wittek
+
+    * manalysis/MCT1Supercuts.[h,cc]
+      - new class
+      - container for the supercut parameters
+
+    * manalysis/MCT1SupercutsCalc.[h,cc]
+      - get supercut parameters from container 'MCT1Supercuts'
+
+    * manalysis/MCT1FindSupercuts.[h,cc]
+      - new class
+      - optimizes the parameters for the supercuts
+
+    * manalysis/MMinuitInterface.[h,cc]
+      - new class
+      - interface for Minuit
+
+    * manalysis/Makefile
+                AnalysisLinkDef.h
+      - include MCT1FindSupercuts
+                MMinuitInterface
+
+    * mhist/MH3.cc
+      - reset fHist in SetupFill();
+        this is necessary if the same MH3 object is used in more than one 
+        eventloop 
+
+    * mhist/MHMatrix.cc
+      - give name to the event loop
+
+    * mhist/MHFindSignificance.[h,cc]
+      - new class
+      - calculates the significance of the gamma signal in the alpha plot      
+
+    * mhist/MHCT1Supercuts.[h,cc]
+      - new class
+      - plots various quantities during the optimization of the supercuts
+
+    * mhist/Makefile
+            HistLinkDef.h
+      - MHFindSignificance included
+      - MHCT1Supercuts included
+
+
+
+ 2003/08/01: Thomas Bretz
+
+   * mhist/MHCamera.[h,cc]:
+     - added Fill(x, y, w)
+     - renamed GetStats to GetStatisticBox
+     
+   * mhist/MHStarMap.[h,cc]:
+     - include TH2 moved to source file
+
+   * mranforest/MRanForest.[h,cc], mranforest/MRanTree.[h,cc]:
+     - do not use all the data numbers and dimensions in thousands
+       of arguments if the data is available eg from the size of an array
+     - removed obsolete variables from header
+     - many small simplifications
+     - removed some obsolete variables from functions
+     - added many const qualifiers
+     - localized many more variables
+     
+   * mranforest/MRanForestFill.[h,cc]:
+     - default fNumTrees set to -1 tree (all trees)
+
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - interpolate Pedestal, too
+     - Only count 'valid' pixels
+     
+   * mfileio/MRead.[h,cc]:
+     - enhanced AddFiles
+     
+   * mhist/MHCamEvent.[h,cc]:
+     - Added PrintOutlayers
+
+   * mhist/MHCamera.[h,cc]:
+     - added GetNumPixels
+     - added default to GetMean and GetRMS
+
+   * mhist/MHTriggerLvl0.[h,cc]:
+     - added PrintOutlayers
+
+   * merpp.cc:
+     - added more arguments
+     - replace .raw by .root if no root file given
+     - automatic extension adding
+     
+   * mbase/MEvtLoop.[h,cc]:
+     - added estimated run time
+     - in Process: Changes type of rc from Bool_t to Int_t 
+     
+   * mmain/MStatusDisplay.cc:
+     - changed order in Tab-menu
+     
+   * mraw/MRawFileRead.cc:
+     - consistency check for 0xc0c1 files
+     
+   * mraw/MRawRunHeader.cc:
+     - initialize variables
+     - added 0xc0c1 support
+
+
+     
+ 2003/07/29: Thomas Bretz
+ 
+   * manalysis/MBlindPixelCalc.cc:
+     - count only pixel which contents are adde
+     
+   * mbase/MArgs.cc:
+     - added namespace
+     
+   * mbase/MDirIter.h:
+     - added rec-argument to constructor
+     
+   * mfileio/MCT1ReadPreProc.[h,cc], mfileio/MReadRflFile.[h,cc]:
+     - adapted to virtual base function
+     
+   * mfileio/MRead.[h,cc]:
+     - added AddFiles(MDirIter&)
+     - changed AddFile to virtual
+     
+   * mfileio/MReadTree.cc:
+     - use AddFile in the constructor
+     
+   * mhist/MH.[h,cc]:
+     - remove 'nonew' from option
+     
+   * mhist/MHHadronness.[h,cc]:
+     - added GetHadronness
+     - changed output
+     
+   * mhist/MHMatrix.[h,cc]:
+     - use TMatrixRow in shuffle
+     - added ReduceRows
+     - use default for PrintStatistics
+     - removed graphics from Fill - will crash in batch mode
+     
+   * mimage/ImageLinkDef.h, mimage/Makefile:
+     - added MImgCleanTGB
+     
+   * mimage/MCameraSmooth.h:
+     - fixed a typo
+     
+   * mmain/MStatusDisplay.cc:
+     - added sanity check to HasCanvas
+     
+   * mranforest/MHRanForest.cc, mranforest/MHRanForestGini.cc:
+     - fixed a crashed caused by GetMaximum in newer root versions
+     - optimized some small pieces of code
+     - SetRangeUser removed, problems with newer root verion using
+       roots auto-scale instead
+       
+   * mranforest/MRanForest.cc:
+     - do not use variables in arguments which can be used locally
+     - replaced pow(,2) by faster and more accurate val*val
+     - test gRandom at the beginning of the function
+     - changed output
+     - removed TArray::Reset. Not necerry at many places. Instatiation
+       already initializes array with 0s
+     - Use a const reference to the matrices instead of a copy!
+     - Removed some unnecessary castings
+     - added some const qualifiers
+     - removed fErr from data members (obsolete)
+     
+   * mranforest/MRanForestCalc.cc:
+     - fixed a typo in the comments
+     
+   * mranforest/MRanTree.[h,cc]:
+     - do not use variables in arguments which can be used locally
+     - localized some variables
+     - test gRandom at the beginning of the function
+     - added some const qualifiers
+     - removed TArray::Reset. Not necerry at many places. Instatiation
+       already initializes array with 0s
+     - added some overwrites of TreeHad
+
+
+
+ 2003/07/17: Oscar Blanch
+
+   * mmc/MMcCorsikaRunHeader.[h,cc]
+     - add member data fNumTelesope
+     - add member data fTelescopes
+     - add member data fViewconeAngles[2]
+     - add member function Fill_CT
+     - version increased 2 -> 3
+
+   * mmc/MMcRunHeader.[hxx,cxx]
+     - add member data fImpactMax
+     - modify member function Fill
+     - version increased 3 -> 4
+
+   * mmc/MMcFadcHeadr.[hxx,cxx]
+     - add member data f[Ampl,Fwhm]Outer
+     - add member data fLow2HighGain
+     - modify member function Set[Ampl,Fwhm]
+     - add member function SetLow2High
+
+   * mmc/Mdefine.h, MFadcDefine.h, MTriggerDefine.h
+     - MFADC_CHANNELS, CAMERA_PIXELS, TRIGGER_PIXELS -> 3500
+
+   * mgeom/MGeomCorsikaCT.[h,cc]
+     - new class with information of CT location in Corsika simulation
+
+   * mgeom/Makefile, GeomLinkDef.h
+     - add new class
+
+
+
+
+
+ 2003/07/14: Wolfgang Wittek
+
+    * mhist/MHOnSubtraction.[h,cc]
+      - add member function GetSignificance()
+
+    * mhist/MHMatrix.cc
+      - add MProgressBar in Fill()
+
+    * mmontecarlo/MMcEnergyEst.h
+      - add member functions GetNumCoeffA()
+                             GetNumCoeffB()
+
+    * mfilter/MCT1SelBasic.[h,cc]
+      - remove runs 601, 613, 614 for MC gamma
+
+    * manalysis/MCT1SupercutsCalc.cc
+      - remove bug (dd2)
+      - set fMatrix = NULL in constructor
+
+    * mgeom.MGeomCamCT1Daniel.[h,cc]
+      - new; Daniel's CT1 geometry
+
+    * mgeom/Makefile
+            GeomLinkDef.h
+
+
+
+ 2003/07/14: Oscar Blanch
+
+    * mgeom/MGeomCamMagic919.[h,cc]
+      - Geometry for a Magic camera with 919 small pixels
+
+    * mgeom/[Makefile, GeomLinkDef.h]
+      - Compiling the above mentioned geometry
+
+
+
+ 2003/07/13: Thomas Bretz
+
+    * mbase/MArgs.[h,cc]:
+      - fixed compile problem with root 3.02/07
+
+    * meventdisp/MGCamDisplay.cc, mevtdisp/MGEvtDislay.cc:
+      - fixed missing MHCamera::SetOptStat
+
+
+
+ 2003/07/12: Thomas Bretz
+ 
+   * mhistmc/MHMcCT1CollectionArea.[h,cc]:
+     - made the enum as FillType_t a public member of the class
+
+   * macros/CT1collarea.C
+     - Updated accordingly. Can somebody please check whether it
+       still works.
+ 
+   * mbase/MArgs.h:
+     - added some comment
+     
+   * mraw/MRawRunHeader.cc:
+     - added an 'inf' to the log-stream
+  
+   * macros/status.C:
+     - added some more plots
+     - added some sanity chacks
+
+   * macros/sumevents.C, macros/sumeventserr.C, macros/sumeventsrms.C
+     macros/sumpedestalrms.C, macros/sumpedestals.C:
+     - fixed SetOptStat
+     
+   * manalysis/MBlindPixelCalc.[h,cc]:
+     - removed dangerous SetPixels(int, short*)
+     - changed Id to Idx
+     - fixed a bug in SetPixels which caused crashes
+     - renamed SetPixels to SetPixelIndices
+
+   * mhist/MHCamera.[h,cc]:
+     - removed SetOptStat and fOptStat - found a better solution
+     - fixed DistancetoPrimitive to show TPaveStat correctly
+     - Use GetPainter() instead of an own THistPainter
+
+   * mmain/MStatusDisplay.cc:
+     - some small changes to the layout
+
+
+
+ 2003/07/11: Wolfgang Wittek
+
+   * mhist/MHMatrix.cc
+     - add tlist.PrintStatistics() after event loop
+
+
+
+ 2003/07/08: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Uncommented the getter function for fCoreX and fCoreY (is there
+       any reason why they were commented out?). Added Getter functions
+       for the parameters of the longitudinal fit to the particle 
+       distribution of the shower.
+
+
+
+ 2003/07/08: Wolfgang Wittek
+
+   * macros/CT1EgyEst.C:
+     - de-comment filters 
+     - add PrintStatistics after event loop
+
+   * manalysis/MEnergyEstParamDanielMkn421.[h,cc]
+     - new; calculates estimated energy using Daniel's parametrization
+       and parameter values for Mkn421
+
+   * manalysis/AnalysisLinkDef.h
+               Makefile
+     - include MEnergyEstParamDanielMkn421
+
+   * manalysis/MCT1SupercutsCalc.[h,cc]
+     - add MHillasSrc.fAlpha to fMap
+     - add member functions SetParams(Double_t *par)
+                            GetParams(Double_t *par)
+
+
+
+ 2003/07/06: Abelardo Moralejo
+
+   * mhistmc/MHMcCT1CollectionArea.[h,cc]
+     - Added possibility of using a logarithmic or linear scale in
+       energy. The function MHMcCT1CollectionArea::SetEaxis sets
+       what should be filled in the energy axis (either the energy 
+       or its decimal logarithm).
+
+   * macros/CT1collarea.C
+     - Added example on how to use the new function 
+       MHMcCT1CollectionArea::SetEaxis
+
+
+
+ 2003/07/06: Thomas Bretz
+ 
+   * Makefile:
+     - replaced '-shared' by $(DYNLIB)
+     
+   * Makefile.conf.linux, Makefile.conf.linux-gnu,
+     Makefile.conf.osf1, Makefile.conf.osf5.1:
+     - added DYNLIB
+     
+   * Makefile.conf.darwin:
+     - added
+   
+   * mgui/MCamEvent.cc:
+     - removed obsolete include
+     
+   * mgui/Makefile:
+     - removed obsolete include dirs
+     
+   * mhist/MHCamera.cc:
+     - fixes for root 3.05/01
+     
+   * mraw/MRawEvtData.cc:
+     - added type 1 and 2 to GetPixContent
+     
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - added GetMax[Hi,Lo]GainSample
+
+   * macros/pixsatrate.C:
+     - added
+
+   * Makefile.conf.general:
+     - added -lHistPainter
+     
+   * NEWS:
+     - updated
+     
+   * macros/pixsatrate.C:
+     - added Saturation rate of lo gains
+     
+   * macros/sumevents.C, macros/sumeventserr.C,
+     macros/sumpedestalrms.C, macros/sumpedestals.C:
+     - fixed axis titles
+     - use new SetOptStat
+     
+   * manalysis/MCerPhotAnal2.[h,cc]:
+     - count and print number of skipped events
+     
+   * meventdisp/MGCamDisplay.cc:
+     - fixed a 'division by zero'
+     
+   * mhist/MHCamEvent.cc, mhist/MHTriggerLvl0.cc:
+     - take name from MHCamEvent if fNameEvt not available
+     
+   * mhist/MHCamera.[h,cc]:
+     - use THistPainter to Draw title and statistics box
+     - added fOptStat
+     - added GetMean
+     - added GetRMS
+     - some modification for a better layout
+     
+   * mraw/MRawEvtHeader.cc:
+     - calculate time from clock ticks
+
+   * mbase/MArgs.[h,cc]:
+     - added
+
+   * mbase/Makefile:
+     - MArgs.cc added
+
+   * mbase/BaseLinkDef.h:
+     - MArgs, MArgsEntry added
+
+   * merpp.cc:
+     - added '-v' option
+     - changes to use MArgs
+
+
+
+
+
+ 2003/07/04: Wolfgang Wittek
+
+   * macros/CT1EgyEst.C
+     - add TCanvas and cd() before calling Draw()
+
+   * mhistmc/MHMcEnergyMigration.cc
+     - swap first 2 arguments of fHist.Fill and fHist2.Fill
+
+
+
+ 2003/07/03: Abelardo Moralejo
+
+   * mhistmc/MHMcCT1CollectionArea.cc
+     - Added code to allow the calculation of CT1 collection areas 
+       at 55 and 65 degrees (from the events in DK's MC library)
+
+   * macros/CT1collarea.C
+     - Changed binning in theta to include high ZAs
+
+
+
+ 2003/07/01: Thomas Bretz
+
+  * manalysis/MCerPhotAnal2.cc:
+    - fixed some problems with the lo-gains
+  
+  * mraw/MRawEvtPixelIter.cc:
+    - Determin the maximum sample of the lo gains from the end.
+
+
+
+ 2003/07/01: Abelardo Moralejo
+
+   * macros/CT1collarea.C
+     - changed "const TArrayD xed(10,xedge);"  to:
+	       "const TArrayD xed; xed.Set(10,xedge);"
+       (and the same for yed). Otherwise, a funny Error message was 
+       printed about TArrayD, although everything worked.
+
+   * mhistmc/MHMcCT1CollectionArea.cc
+     - added some comments and made code more readable and more simple
+       to make it easier the addition of the necessary changes to allow 
+       the use of MC data (from D.Kranich) at zenith angles 55 and 65 
+       degrees.
+
+
+
+ 2003/07/01: Wolfgang Wittek
+
+   * manalysis/MSigmabar.cc, manalysis/MCT1PadSchweizer.cc,
+     manalysis/MCT1PadONOFF.cc, mhist/MHSigmaTheta.cc:
+     - change code because GetPixRatio returns area(pixel_zero)/area(pixel)
+                                       and not area(pixel)/area(pixel_zero)
+
+   * macros/CT1Analysis.C, macros/ONOFFCT1Analysis.C
+     - current versions of CT1 macros
+
+   * macros/unfold.C, macros/fluxunfold.C
+     - macros for testing the unfolding within root
+
+
+
+ 2003/06/30: Thomas Bretz
+ 
+   * macros/pixfirerate.C:
+     - changed to new style
+     
+   * manalysis/MCerPhotCalc.cc:
+     - scale weight so that sum=1
+     
+   * mhist/MHCamera.h:
+     - small change
+
+   * mmontecarlo/MMcCollectionAreaCalc.cc:
+     - small simplifications
+
+
+
+ 2003/06/27: Abelardo Moralejo
+
+   * mmontecarlo/MMcCollectionAreaCalc.[h,cc],
+     mhistmc/MHMcCollectionAreaCalc.[h,cc]:
+     - Adapted to allow their use with multiple files containing
+       MC data generated with diffferent energy spectra, even with
+       camera files which have only triggered events inside. Now the
+       histogram containing all showers (before trigger) is filled
+       in the ReInit function, and calculation of collection area
+       is done by CalcEfficiency2(). Some simplifications and cleaning 
+       are still possible.
+
+
+
+ 2003/06/27: Thomas Bretz
+ 
+   * macros/sumevents.C, macros/sumpedestals.C:
+     - some small changes
+     
+   * manalysis/MPedestalCam.cc:
+     - return pixel as used if the value is valid (>=0)
+     
+   * mhist/HistLinkDef.h, mhist/Makefile:
+     - MHPixVsTime added (Name is preliminary)
+
+   * mhist/MHCamEvent.cc:
+     - removed including MGeomPix
+     
+   * mhist/MHCamera.h:
+     - in SetCamContent copy also number of entries
+     
+   * mraw/MRawEvtData.cc:
+     - fixed to support correct pixel numbering
+     
+   * mhist/MHPixVsTime.[h,cc]:
+     - added
+
+   * mhist/MHCamera.cc:
+     - changed output of labels for color axis
+
+   * mfileio/MCT1ReadPreproc.cc:
+     - small simplification
+
+
+
+ 2003/06/27: Abelardo Moralejo
+
+   * mhistmc/MHMcCT1CollectionArea.cc:
+     - Added comments, changed theta angle corresponding to first bin to
+       adapt it to new standard theta-bin definition. This was the reason
+       for the missing area at low theta.
+
+   * macros/CT1collectionArea.C, macros/CT1EgyEst.C:
+     - Changed theta binnings to adapt them to the new standard.
+
+
+
+ 2003/06/26: Abelardo Moralejo
+
+   * macros/CT1EgyEst.C:
+     - Added to the argument list of CT1EEst the binnings in theta
+       and energy. Commented out the MLog.h and MLogManip.h, headers,
+       otherwise it does not run (don't know why). Commented out filters 
+       (my test file does not contain hadronness), please uncomment 
+       them to run on files with hadronness info.
+
+   * mhistmc/MHMcEnergyMigration.cc:
+     - exchanged axes of E_est and E_MC in the 3-d histograms.
+
+   * mfileio/MCT1ReadAscii.cc, mfileio/MCT1ReadPreProc.cc,
+     mhist/MHSigmaPixel.cc, mfileio/MHSigmaTheta.cc,
+     mimage/MImgCleanStd.cc:
+     - adapted to new function names in MPedestalPix (please Thomas
+       check these, I had to do it to make Mars compile)
+
+
+
+ 2003/06/26: Thomas Bretz
+
+  * macros/CT1EgyEst.C:
+    - converted from dos to unix type
+
+   * macros/rootlogon.C:
+     - removed "-fno-rtti" from options for Aclic
+     
+   * mbase/MLog.h:
+     - added a comment
+     
+   * mgeom/MGeomCam.[h,cc], mgeom/MGeomPix.[h,cc],
+     mgeom/MGeomCamCT1.cc, mgeom/MGeomCamECO1000.cc,
+     mgeom/MGeomCamECO1000HG.cc, mgeom/MGeomCamMagicHG.cc:
+     - added support for sectors
+   
+   * megom/MGeomCamMagic.[h,cc]:
+     - added sectors
+     
+   * mhist/MHCamera.[h,cc]:
+     - convert Option_t in Paint to lower case
+     - remove 'hist' if detected from Option_t 
+     - check for min==max
+     - added DrawSectorIndices()
+     - added TArrayC to AddCamContent
+     - added TArrayC to SetCamContent
+     - simplified DistancetoPrimitive
+     
+   * mraw/MRawEvtData.cc:
+     - simplified Draw by converting option string to lower case
+     
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - added GetNumMaxLoGainSample
+
+   * manalysis/MCT1PadSchweizer.cc, manalysis/MMcPedestalNSBAdd.cc,
+     manalysis/MSigmabar.cc:
+     - adapted to new function names in MPedestalPix
+     
+   * manalysis/MCerPhotAnal.cc:
+     - adapted to new function names in MPedestalPix
+     - fixed to work with real data and monte carlo data
+     - preliminarily removed error of pedestal and pedestalrms
+     
+   * manalysis/MCerPhotCalc.[h,cc]:
+     - adapted to new function names in MPedestalPix
+     - fixed to work with real data and monte carlo data
+   
+   * manalysis/MMcPedestalCopy.cc, manalysis/MPedCalcPedRun.[h,cc]:
+     - adapted to new function names in MPedestalPix
+     - preliminarily removed error of pedestal and pedestalrms
+ 
+   * manalysis/MPedestalCam.[h,cc]:
+     - adapted to new function names in MPedestalPix
+     - preliminarily removed error of pedestal and pedestalrms
+     - fixed GetPixelContent (do not return Pedestal*PixRatio)
+     
+   * manalysis/MPedestalPix.[h,cc]:
+     - removed old variables
+     - introduced Pedestal for pedestal
+     - introduced pedestalRMS for the rms of the pedestal
+     - error of both values still missing
+     
+   * meventdisp/MGCamDisplay.cc:
+     - fixed display, displays now:
+       + Number Of Photons
+       + Pedestal
+       + PedestalRMS
+       + Number of Photons/PedestalRMS
+       
+   * mimage/MImgCleanStd.[h,cc]:
+     - fixed image cleaning in the sense that erronously the error
+       of the number of photons was used instead of the error of
+       the PMT offset (pedestal)
+     - introduced some debugging option
+     
+   * mmontecarlo/MMcCollectionAreaCalc.cc:
+     - minor change
+
+   * macros/sumevents.C, macros/sumpedestals.C:
+     - added
+
+   * mhist/MHCamEvent.cc:
+     - do not scale with 100
+
+   * mhist/MHCamera.cc:
+     - fixed displaying number of entries when used 
+       SetCamContent(MHCamera&)
+
+
+
+ 2003/06/25: Thomas Bretz
+
+   * mgeom/MGeomCam.cc:
+     - fixed the description of GetPixRatio
+
+
+
+ 2003/06/25: Abelardo Moralejo
+
+   * mimage/MImgCleanStd.cc:
+     - Changed name of variable "ratio" to "factor", wherever it meant
+       the square root of the ratio between the area of an inner pixel
+       and the current pixel (it was confusing).
+
+
+
+ 2003/06/24: Thomas Bretz
+
+   * manalysis/MCT1SupercutsCalc.[h,cc]:
+     - implemented Mapping for Supercuts
+     - changed data member arrays to TArrayD
+     
+   * manalysis/MEnergyEstParam.h:
+     - added a comment
+
+   * mhist/MHHadronness.[h,cc]:
+     - implemented mapping
+     - implemented calculating Acc_g/sqrt(Acc_h) for filtercuts
+
+   * macros/status.C:
+     - removed MSrcPosCam
+
+   * mevtdisp/MGCamDisplay.cc:
+     - display ellipse in all canvas'
+
+   * macros/readrfl.C:
+     - adapted
+
+   * manalysis/MMcTriggerLvl2.cc, meventdisp/MGEvtDisplay.cc,
+     mraw/MRawEvtPixelIter.cc:
+     - adapted
+   
+   * mgui/MCamEvent.[h,cc], mhist/MHCamEvent.[h,cc]:
+     - more comments
+     
+   * mgui/MHexagon.[h,cc]:
+     - removed obsolete destructor
+
+   * mhist/MHCamera.[h,cc]:
+     - removed fPhotons
+     - removed ShowRflEvent
+     - added comments
+     
+   * mhist/MHTriggerLvl0.cc:
+     - fixed comments
+     
+   * mraw/MRawEvtData.cc:
+     - some small changes
+     
+   * mreflector/MRflEvtData.[h,cc]:
+     - implemented Paint function
+
+   * meventdisp/MGCamDisplay.cc:
+     - Set Name and title of MHCamera instances
+      
+   * mraw/MRawEvtData.cc:
+     - fixed a degug level problem
+
+   * mgui/MHexagon.[h,cc]:
+     - fixed CopyConstructor
+
+   * mbase/MLog.cc:
+     - fixed a bug in NoColor mode
+
+
+
+ 2003/06/23: Thomas Bretz
+ 
+   * manalysis/MBlindPixelCalc.[h,cc], manalysis/MCT1PadONOFF.[h,cc],
+     manalysis/MCT1PadSchweizer.[h,cc], manalysis/MCompProbCalc.[h,cc],
+     manalysis/MCT1PointingCorrCalc.[h,cc], manalysis/MEnergyEstimate.[h,cc],
+     manalysis/MCT1SupercutsCalc.[h,cc], manalysis/MEnergyEstParam.[h,cc],
+     manalysis/MFiltercutsCalc.[cc,h], manalysis/MMatrixLoop.[h,cc],
+     manalysis/MMcPedestalCopy.[h,cc], manalysis/MMcPedestalNSBAdd.[h,cc],
+     manalysis/MMcTriggerLvl2Calc.[h,cc], manalysis/MPadding.[h,cc],
+     manalysis/MMultiDimDistCalc.[h,cc], manalysis/MPedCalcPedRun.[h,cc],
+     manalysis/MPedestalCalc.[h,cc], manalysis/MPointingCorr.[h,cc],
+     mbase/MClone.[h,cc], mbase/MGTask.[h,cc], mbase/MPrint.[h,cc],
+     mbase/MTask.[h,cc], mbase/MTaskInteractive.[h,cc], 
+     mbase/MTaskList.[h,cc], mtools/MChisqEval.[h,cc],
+     mbase/MContinue.[h,cc], mdatacheck/MDumpEvtHeader.[h,cc]
+     mfileio/MCT1ReadAscii.[h,cc], mfileio/MCT1ReadPreProc.[h,cc],
+     mfileio/MReadCurrents.[h,cc], mfileio/MReadMarsFile.[h,cc],
+     mfileio/MReadRflFile.[h,cc], mfilter/MF.[h,cc], 
+     mfilter/MFAlpha.[h,cc], mfilter/MFCT1SelBasic.[h,cc],
+     mfilter/MFCT1SelFinal.[h,cc], mfilter/MFCT1SelStandard.[h,cc],
+     mfilter/MFDataChain.[h,cc], mfilter/MFDataMember.[h,cc],
+     mfilter/MFEnergySlope.[h,cc], mfilter/MFEventSelector.[h,cc],
+     mfilter/MFEventSelector2.[h,cc], mfilter/MFParticleId.[h,cc],
+     mfilter/MFTriggerLvl1.[h,cc], mfilter/MFTriggerLvl2.[h,cc],
+     mfilter/MFilterList.[h,cc], mhist/MFillH.[h,cc], 
+     mimage/MCameraSmooth.[h,cc], mimage/MHillasCalc.[h,cc],
+     mimage/MHillasSrcCalc.[h,cc], mimage/MImgCleanStd.[h,cc],
+     mimage/MNewImageParCalc.[h,cc], mmontecarlo/MMcThresholdCalc.[h,cc], 
+     mranforest/MRanForestCalc.[h,cc], mranforest/MRanForestFill.[h,cc]
+     mmontecarlo/MMcTimeGenerate.[h,cc], mranforest/MRanForestGrow.[h,cc],
+     mmontecarlo/MMcCollectionAreaCalc.[h,cc], mraw/MRawFileWrite.[h,cc],
+     mmontecarlo/MMcTriggerRateCalc.[h,cc], mraw/MRawFileRead.[h,cc],
+     manalysis/MSigmabarCalc.[h,cc], manalysis/MCerPhotAnal.[h,cc],
+     manalysis/MCerPhotCalc.[h,cc]:
+     - changed Bool_t in *Process to Int_t to support newer root
+       versions correctly - PRELIMINARY (will be replaced by
+       enums in the future)
+       
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added case 3 and 4 to GetPixelContent
+     - changed definition of GetPixelContent
+
+   * manalysis/MCurrents.[h,cc], manalysis/MPedestalCam.[h,cc]:  
+     - changed definition of GetPixelContent
+
+   * manalysis/MFiltercutsCalc.[h,cc]:
+     - Added list to ListOfCleanups, and set kMustCleanup for list
+     - Set kMustCleanup for external filters
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added to ListOfCleanups
+     - Set kMustCleanup for parlist, progressbar and display
+     - added some checks for root's Batch-Mode
+     - no need for checking ListOfSpecials for fDisplay (this is now
+       handled through the Cleanups)
+     - No need for kFileExit anymore (this can now be handles through 
+       the Cleanups)
+     - added recursiveRemove to support Cleanups
+     - added SetDisplay to set kMustCleanup for fDisplay
+
+   * mbase/MTaskList.cc, mdata/MDataArray.cc, mdata/MDataList.cc,
+     mfilter/MFilterList.cc:
+     - added lists to ListOfCleanups
+     - Set kMustCleanup for the lists
+
+   * mbase/MParList.[h,cc]:
+     - added lists to ListOfCleanups
+     - Set kMustCleanup for the lists
+     - added kCanDelete option to destructor
+     - set kMustCleanup for all containers added to thelist
+   
+   * mdatacheck/DataCheckLinkDef.h, mdatacheck/Makefile:
+     - removed unnecessary MDumpEvtHeader
+     
+   * mbase/MContinue.[h,cc]:
+     - added SetDisplay to support setting display for the filter
+     - added SetLogStream to support setting logstream for the filter
+     
+   * mfilter/MFCT1SelBasic.cc, mfilter/MFCT1SelFinal.cc, 
+     mfilter/MFCT1SelStandard.cc:
+     - added Set-function to simplify Process
+     
+   * mgui/MCamEvent.[h,cc]:
+     - changed GetPixelContent definition
+     
+   * mhist/MH.cc:
+     - fixed Draw(TH1&, TH1&) and DrawCopy layout for newer root versions
+
+   * mimage/MImgCleanStd.cc:
+     - fixed a bug in the access to ispixused-array (GetNeighbor 
+       could exceed maximum entries.
+       
+   * mmain/MStatusDisplay.[h,cc]:
+     - preliminary fixes to support root's batch mode
+     - removed adding MStatusDisplay to ListOfCleanups
+     - changed code updating the Canvas'
+     - exit now handled by Cleanups, so this can be deleted immediatly
+     
+   * mraw/MRawEvtData.[h,cc]:
+     - changed definition of GetPixelContent
+     - added code to GetPixelContent
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - returns GetNumMaxHiGainSample
+
+   * mreflector/MRflEvtData.[h,cc]:
+     - use static_cast in GetPhoton
+     - added GetPixelContent
+
+   * mhist/MHTriggerLvl0.[h,cc], MHmhist/Camera.[h,cc], 
+     mhist/MHCamEvent.[h,cc]:
+     - added
+
+   * manalysis/MSigmabar.cc:
+     - unimportant simplification
+     
+   * manalysis/MSigmabarCalc.cc:
+     - added a preliminary workaround to support files without MMcEvt
+     - make use of FLT_MAX
+     
+   * mgeom/MGeomCam.[h,cc]:
+     - Moved fPixels from pointer to an instance
+     - removed destructor
+     - use static_cast on operator[]
+     - Use ForEach macro in CheckOuterRing
+
+   * mhist/MHSigmaTheta.cc:
+     - added a preliminary workaround to support files without MMcEvt
+ 
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - removed MCT1PadONOFF
+     
+   * manalysis/MCerPhotEvt.h:
+     - added //-> to fPixels
+
+   * meventdisp/Makefile:
+     - added -I../mhist
+
+   * manalysis/MMcTriggerLvl2.[h,cc], meventdisp/MGCamDisplay.[h,cc]:
+     - replaced MCamDisplay by MHCamera
+
+   * mgui/GuiLinkDef.h, mgui/Makefile:
+     - removed MCamDisplay
+     
+   * mhist/HistLinkDef.h, mhist/Makefile:
+     - removed MHCerPhotEvt
+     - removed MHCurrents
+     - removed MHTrigLvl0
+     - removed MHOnSubtraction
+     - added MHCamera
+     - added MHCamEvent
+
+   * macros/sumcurrents.C:
+     - adapted to changes
+     - added filename to canvas
+  
+   * macros/readMagic.C, macros/readCT1.C, macros/status.C,
+     macros/readcurrents.C, macros/readrfl.C:
+     - adapted to changes
+     
+   * mbase/MAGIC.h:
+     - replaced extern by R__EXTERN
+
+   * mbase/MParContainer.[h,cc]:
+     - added a non empty destructor with some debug options
+
+   * mbase/MPrint.cc:
+     - fixed a bug (used kSKIP instead of kSkip)
+
+
+
+ 2003/06/19: Thomas Bretz
+ 
+   * mgui/MCamDisplay.[h,cc]:
+     - fixed color palette when loading MCamDisplay
+
+   * mevtdisp/MGEvtDisplay.cc:
+     - fixed a bug in ProcessMessage, 'Exit' still doesn't work.
+
+
+
+ 2003/06/18: Thomas Bretz
+
+   * macros/sumcurrents.C:
+     - added MDirIter support
+     - fixed the rel. error calculation
+     - some small corrections to the layout
+     
+   * mhist/MHCurrents.cc:
+     - changed histogram name
+     - added axis titles
+
+   * mbase/MLog.cc:
+     - include iomanip onstead of MLogManip
+
+   * mbase/MLogManip.h:
+     - replaced preprocessor defintions for all, warn, inf, err and dbg
+       by const variable declarations
+     - fixed dynamic_casts
+
+   * macros/merpp.C:
+     - made capable of more than one directory
+     
+   * mmain/MStatusDisplay.cc:
+     - removed an unsused variable
+
+   * Makefile.conf.osf1, Makefile.conf.osf5.1:
+     - added definitions for __USE_STD_IOSTREAM and R__ANSISTREAM
+       tp be able to compile on Alphas again
+       
+   * manalysis/MCT1PadONOFF.cc:
+     - included math.h
+     - commented out some code to be able to compile on Alpha - FIXME
+     
+   * mbase/MDirIter.h:
+     - fixed a bug in the definition of MatchFilter
+
+   * mraw/MRawFileWrite.h:
+     - default mode changed from UPDATE to RECREATE
+     - default compression level changed from 9 to 1
+
+   * mraw/MRawEvtData.[h,cc]:
+     - fixed to skip non connected pixels
+     
+   * mraw/MRawRunHeader.[h,cc]:
+     - added GetNumConnectedPixels
+
+
+
+
+ 2003/06/17: Oscar Blanch
+
+  * mgeom/MGeomCamECO1000HG.cc
+    - fixed a bug in NN table
+
+  * mgeom/MGeomCamMagicHG.[h,cc]
+    - New geometry for a high granularity hipothetic Magic camera
+
+  * mgeom/Makefile and mgeom/GeomLinkDef.h
+    - Introduction of MGeomMagicHG class.
+
+
+
+ 2003/06/17: Thomas Bretz
+
+   * meventdisp/MGEvtDisplay.cc:
+     - fixed a bug which caused a endlessloop
+
+   * mmain/MStatusDisplay.cc:
+     - fixed UpdatePSHeader for gcc 3.* and Suse 8.2
+
+   * manalysis/MCurrents.h:
+     - fixed a bug in the const operator[]
+
+   * mgui/MCamDisplay.[h,cc]:
+     - set ClassDef to 1 so that the camera display can be written into
+       a root file
+     - fixed destructor (didn't fit default constructor)
+     - implemented FillRandom for test cases
+
+   * mgui/MHexagon.h
+     - set ClassDef to 1 so that the camera display can be written into
+       a root file
+
+
+
+ 2003/06/16: Thomas Bretz
+
+   * mhist/MHOnSubtraction.cc:
+     - worked around the non compiling source file
+
+   * merpp.cc:
+     - set compression level default = 1
+
+   * macros/readCT1.C, macros/readMagic.C, macros/readcurrents.C,
+     meventdisp/MGCamDisplay.cc
+     - adapted to new MCamDisplay and MCamEvent
+
+   * macros/sumcurrents.C:
+     - enhanced
+
+   * manalysis/MCerPhotCalc.[h, cc]:
+     - simplified algorithm
+
+   * manalysis/MCerPhotEvt.[h,cc], manalysis/MCurrents.[h,cc],
+     manalysis/MPedestalCam.[h,cc]:
+     - derived from MCamEvent
+     
+   * manalysis/MMcPedestalNSBAdd.cc:
+     - minor change
+     
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MDirIter
+
+   * mbase/MDirIter.[h,cc]:
+     - added
+     
+   * mbase/MParList.cc:
+     - enhnced some output
+
+   * mbase/MTaskInteractive.cc:
+     - fixed a bug
+     
+   * mbase/MTaskList.cc:
+     - added handling of gui events for Pre- and PostProcess
+     
+   * mgeom/MGeomPix.cc:
+     - added a comment
+     
+   * mgui/MCamDisplay.[h,cc] -  PRELIMINARY:
+     - added a notification list
+     - fixed SetRange if pad is not the main pad
+     - new Fill functions using MCamEvent, removed old ones 
+     
+   * mhist/MFillH.cc:
+     - check for the existance of the canvas
+     
+   * mhist/MHCerPhotEvt.cc:
+     - take usage of MCamEvent
+
+   * mhist/MHCurrents.cc:
+     - take usage of MCamEvent
+     - added rms
+     
+   * mmain/MStatusDisplay.[h,cc]:
+     - added "Reset" and "Remove Tab" to menu bar
+
+   * mraw/MRawEvtData.[h,cc]:
+     - draw hi- and logains
+     - derived from MCamEvent
+     
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - added GetVarHiGainSamples
+
+   * mraw/Makefile:
+     - added -I../mgui - PRELIMINARY
+
+   * mhist/MH.cc:
+     - fixed Draw(TH1&,TH1&) for newer root versions
+
+   * mhist/MHHadronness.cc:
+     - fixed call to fGraph->SetMaximum(1) for newer root versions
+
+   * mmain/MStatusDisplay.cc:
+     - fixed for gcc 3.* and newer root versions
+     
+
+
+
+ 2003/06/13: Robert Wagner
+   * mhist/MHOnSubtraction.cc
+     - removed casts from double to Double_t found by gcc 3.3
+     - added MHOnSubtraction::CalcLightCurve, a methods towards a 
+       lightcurve 
+
+
+
+ 2003/06/13: Thomas Bretz (making Mars work with gcc 3.3 on Suse 8.2)
+
+   * Makefile.conf.linux:
+     - removed nonull-objects, Wtraditional and Wnested-externs
+       due to warnings in gcc 3.3
+     
+   * *:
+     - added 'using namespace std;'
+     - exchanged *.h C++ headers by correct headers (like <fstream>)
+     - replaced forward declarations of streams by <iosfwd>
+
+   * manalysis/MCerPhotAnal.cc:
+     - cast arguments of sqrt to correct type
+     - corrected argument type for SetPedestalRms
+     
+   * manalysis/MCurrents.h:
+     - const operator[] uses 'this' now
+     
+   * manalysis/MEnergyEstParam.[h,cc], manalysis/MSigmabarParam.[h,cc]:
+     - fixed definition of Print
+
+   * manalysis/MMcPedestalCopy.cc, manalysis/MPedCalcPedRun.cc,
+     mgui/MCamDisplay.cc, mmontecarlo/MMcThresholdCalc.cc:
+     - cast arguments of sqrt to correct type
+
+   * manalysis/MMultiDimDistCalc.cc:
+     - changed type of numg/numh to Int_t
+     
+   * mbase/BaseLinkDef.h:
+     - removed pragma for __omanip_debug
+
+   * mbase/MLog.[h,cc]:
+     - fixed copy constructor
+     - removed usage of mkstemp -- TO BE FIXED
+
+   * mbase/MLogManip.[h,cc]:
+     - completely replaced
+
+   * mdata/MDataArray.cc:
+     - fixed variable type ncols (Double_t -> Int_t)
+   
+   * mdata/MDataChain.cc:
+     - fixed argument type of gRandom->Integer()
+   
+   * meventdisp/MGEvtDisplay.[h,cc]:
+     - implemented skiping of  events which have 0 Pixels
+     
+   * mfileio/MCT1ReadPreProc.cc:
+     - fixed conversion for istream::read from Byte_t* to char*
+     - fixed argument type in Fill (fmcsize_phel)
+     
+   * mfileio/MChain.h:
+     - ResetTree must also set fTreeNumber to -1 due to changes in
+       TChain::LoadTree
+
+   * mfilter/MFAlpha.[h,cc]:
+      fixed type of Alpha in Init (Float_t instead of Int_t)
+      
+   * mfilter/MFEventSelector2.[h,cc]:
+     - renamed Read member function to ReadDistribution
+     
+   * mfilter/MFilterList.h:
+     - fixed overloading of GetRule
+     
+   * mhist/MBinning.cc, mhist/MH3.cc:
+     - removed default argument in source file
+
+   * mhist/MHArray.cc:
+      fixed type of sstyle (Stat_t -> Int_t)
+      
+   * mhist/MHCerPhotEvt.[h,cc], mhist/MHCurrents.[h,cc]:
+     - fixed definition of Clear()
+     
+   * mhist/MHFadcCam.[h,cc]:
+     - renamed Reset to ResetEntry
+     
+   * mhistmc/MHMcEnergy.cc:
+     - fixed argument type of log
+   
+   * mhistmc/MHMcRate.cc:
+     - cast argument of pow() to correct type
+   
+   * mimage/MHillas.cc:
+     - replaced default value for MeanX and MeanY by 0
+
+   * mmain/MMars.cc:
+     - fixed argument type in TGLayoutHints
+
+   * mmain/MStatusDisplay.cc:
+     - fixed some argument types
+     - for the moment removed the update of the ps-header
+
+   * mmc/MMcTrig.cxx:
+     - use binary shift instead of pow for power of two
+
+   * mmontecarlo/MMcEnergyEst.[h,cc]:
+     - declared fcn as static
+     - fixed definition of Print
+
+   * mmontecarlo/MMcTimeGenerate.cc:
+     - fixed argument type of SetTime
+   
+   * mmontecarlo/MMcTriggerRateCalc.[h,cc]:
+     - fixed definition of Draw
+
+   * mfileio/MReadRflFile.cc, mraw/MRawCrateData.cc, mraw/MRawEvtData.cc,
+     mraw/MRawEvtHeader.cc, mraw/MRawRunHeader.cc:
+     - fixed conversion for istream::read from Byte_t* to char*
+
+   * mreflector/MRflEvtData.cc, mreflector/MRflSinglePhoton.cc:
+     - fixed definition of Print
+
+
+
+ 2003/06/13: Robert Wagner
+   * mhist/MHOnSubtraction.cc
+     - Improvements in output
+
+
+
+ 2003/06/12: Thomas Bretz
+
+   * mgui/MCamDisplay.h:
+     - added //*MENU* to SetAutoScale, SetMinimum, SetMaximum
+
+
+
+ 2003/06/11: Robert Wagner
+
+   * mhist/MHOnSubtraction.[h,cc]
+     - Some bugfixes, e.g. concerning binning of result histograms
+     - Improvements in output
+
+
+
+
+
+ 2003/06/09: Wolfgang Wittek
+
+   * macros/CT1Analysis.C
+     - replace MPadSchweizer by MCT1PadSchweizer
+
+   * macros/ONOFFCT1Analysis.C
+     - current version of the macro for the analysis using ON, OFF and MC data
+
+   * manalysis/MPadSchweizer.[h,cc]
+               MPadONOFF.[h,cc]
+     - delete
+
+   * manalysis/MCT1PadSchweizer.[h,cc]
+               MCT1PadONOFF.[h,cc]
+     - add
+
+   * manalysis/Makefile
+               AnalysisLinkdef.h
+     - replace MPadSchweizer and MPadONOFF
+       by MCT1PadSchweizer and MCT1PadONOFF     
+
+
+
+ 2003/06/06: Robert Wagner
+
+   * mhist/MHOnSubtraction.[h,cc]
+     - Class for extracting a gamma signal from on data only. Works
+       on fully differential data in Alpha, Energy and Theta as well
+       as on single Alpha plots. Experimental version, expect
+       functionality but code still optimized for debugging purposes
+
+   * mhist/MHAlphaEnergyTheta.cc
+     - Fill signed alpha value instead of absolute value
+
+
+
+ 2003/06/06: Wolfgang Wittek
+
+   * macros/optPad.C
+     - macro for testing the optimal padding
+
+
+
+ 2003/06/05: Abelardo Moralejo
+
+   * mhist/MHTrigLvl0.[h,cc]:
+     - added. This is intended to find "hot" pixels firing too often
+       or pixels firing too rarely. Very preliminar!
+
+   * macros/pixfirerate.C:
+     - added. An example on how to use the class above.
+
+   * mhist/Makefile, HistLinkDef.h :
+     added new class.
+
+
+
+ 2003/06/05: Thomas Bretz
+
+   * mbase/MEvtLoop.cc:
+     - fixed some typos in the comments
+     
+   * meventdisp/MGCamDisplay.cc:
+     - added MHillasSrc to eventloop
+     
+   * meventdisp/MGEvtDisplay.cc:
+     - print MC informations to screen, too
+     
+   * mfileio/MReadCurrents.cc:
+     - added a comment
+     
+   * mhist/MHCerPhotEvt.h:
+     - removed typo
+     
+   * mimage/MHillasSrcCalc.cc:
+     - create a default source if now source is available
+
+
+
+ 2003/06/03: Thomas Bretz
+ 
+   * macros/readcurrents.C:
+     - display currents in Log-Scale
+
+   * mgui/MCamDisplay.[h,cc]:
+     - introduced fMinimum
+     - introduced fMaximum
+     - introduced fData
+     - removed Set-functions
+     - introduced Update()
+     - introduced Log-Scale
+
+   * macros/readCT1.C:
+     - fixed a typo
+
+   * mbase/MTaskInteractive.[h,cc]:
+     - added
+     
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MTaskInteractive
+
+   * mhist/MHCurrents.[h,cc]:
+     - added (PRELIMINARY)
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - added MHCurrents
+
+   * mgui/MCamDisplay.[h,cc]:
+     - changed number of ItemsLegend to display the maximum, too
+
+   * macros/sumcurrents.C:
+     - added
+
+
+
+ 2003/06/03: Wolfgang Wittek
+
+   * mfileio/MCT1ReadPreProc.[h,cc]
+     - reset blind pixels for each event
+       (because they may have been changed by the padding)
+
+   * macros/ONOFFCT1Analysis.C
+     - will be the macro for the CT1 analysis using ON and OFF data
+
+   * manalysis/MPadONOFF.[h,cc]
+     - new class
+     - class for the padding of ON/OFF data
+
+   * manalysis/MPadSchweizer.[h,cc]
+     - remove fBlinds->Clear() because the resetting of the
+       blind pixels is now done in MCT1ReadPreProc
+
+
+
+ 2003/06/02: Thomas Bretz
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MCurrents
+     
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added MGeomCam argument to GetRatioMin/Max
+     
+   * mfileio/FileIOLinkDef.h, mfileio/Makefile:
+     - added MReadCurrents
+
+   * mfileio/MReadCurrents.[h,cc]:
+     - added
+     
+   * manalysis/MCurrents.[h,cc]:
+     - added
+     
+   * mgui/MCamDisplay.[h,cc]:
+     - added current support
+
+   * mbase/MTime.h:
+     - preliminary changes to support currents
+     
+   * mhist/MH.[h,cc]:
+     - added usescreenfactor to MakeDefCanvas
+
+
+
+ 2003/05/30: Wolfgang Wittek
+
+   * macros/CT1Analysis.C
+     - current version of the CT1Analysis.C macro for the analysis of
+       CT1 data using ON and MC data
+
+
+
+ 2003/05/27: Thomas Bretz
+
+   * mreflector/Makefile:
+     - removed obsolete includes
+
+   * mbase/MLogManip.h:
+     - for the moment removed dbg<< from dbginf again
+
+   * mimage/MHNewImagePar.cc:
+     - security check in fill
+
+   * mmain/MAnalysis.cc:
+     - fixed filling of MHNewImagePar
+
+
+
+ 2003/05/26: Wolfgang Wittek
+
+   * mfileio/MCT1ReadPreProc.cc
+     - put back :  if (event.spixsig_10thphot[i]==0)
+                         continue;
+ 
+   * manalysis/MPadSchweizer.cc
+     - add pixels to MCerPhotEvt which are not yet in;
+       set their number of photons equal to zero
+
+
+
+ 2003/05/26: Thomas Bretz
+
+   * mhist/MHCerPhotEvt.cc, mfileio/MCT1ReadAscii.cc:
+     - InitSize --> FixSize
+
+   * manalysis/MMcPedestalNSBAdd.cc:
+     - fixed a typo (* instead of /)
+
+
+
+ 2003/05/23: Abelardo Moralejo
+
+   * mreflector/Makefile:
+     - added (was missing)
+
+
+
+ 2003/05/23: Thomas Bretz
+
+   * Makefile:
+     - added mreflector
+     
+   * manalysis/MCerPhotAnal.cc, manalysis/MCerPhotCalc.cc:
+     - use FixSize instead of InitSize
+     
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - replaced InitSize by FixSize (seems to be more logical)
+     
+   * manalysis/MMcPedestalNSBAdd.cc:
+     - replaced GetR by GetPixRatio
+
+   * manalysis/MPedestalCam.cc:
+     - replaced GetEntries by GetEntriesFast
+     
+   * mfileio/FileIOLinkDef.h, mfileio/Makefile:
+     - added MReadRflFile
+
+   * mgeom/MGeomCam.[h,cc], mgeom/MGeomPix.[h,cc], 
+     mgeom/MGeomCamMagic.[h,cc]:
+     - replaced R by D
+
+   * mgui/MCamDisplay.[h,cc]:
+     - added TClonesArray to display reflector events
+     - added FillRflEvent
+     - added ShowRflEvent
+     - adapted Paint function
+     
+   * mgui/MHexagon.[h,cc]:
+     - replaced GetR by GetD
+     - added DistanceToPrimitive (capital T)
+     
+   * mgui/Makefile:
+     - added mreflector
+
+   * mfileio/MReadRflFile.[h,cc]:
+     - added
+
+   * mreflector, mreflector/Makefile, mreflector/ReflectorLinkDef.h,
+     mreflector/MRflEvtData.[h,cc], mreflector/MRflSinglePhoton.[h,cc]:
+     mreflector/MRflEvtHeader.[h,cc], mreflector/MRflRunHeader.[h,cc]:
+     - added
+
+   * macros/readRfl.C:
+     - added
+
+
+
+ 2003/05/22: Abelardo Moralejo
+
+   * mhist/MHMatrix.[h,cc]
+     - add member function ShuffleRows() to randomize the order of the
+       matrix rows. This is useful for instance for the random forest, 
+       (See RanForest.C) when we feed a hadron training sample with 
+       both protons and helium nuclei: if they are ordered (first all
+       events of one type, then those of the other) the method does not
+       seem to work well. Any other kind of ordering might be harmful 
+       as well (in theta, phi or whatever).
+
+
+
+ 2003/05/22: Wolfgang Wittek
+
+   * mfileio/MCT1ReadPreProc.[h,cc]
+     - add member function DiscreteTheta
+     - discretize the Theta according to the binning in Theta
+       (for data and MC)
+       original Theta is stored in the container "ThetaOrig"
+       the discretized Theta is stored in MMcEvt.fTelescopeTheta
+
+
+
+ 2003/05/21: Thomas Bretz
+
+   * mfileio/MReadTree.cc:
+     - changed text of a warning
+     - removed obsolete comment
+     
+   * mfileio/MWriteRootFile.[h,cc]:
+     - changed Print function to support kIsNewTree flag
+     - changed BIT(15) to BIT(16) because it is already used by TBranch
+
+
+
+ 2003/05/21: Wolfgang Wittek
+
+   * mhist/MHBlindPixels.[h,cc]
+     - change 1D histogram into 2D histogram (pixel Id vs. Theta)
+     - add 2D histogram : no.of blind pixels vs. Theta
+
+   * mhist/MHSigmaTheta.cc
+     - correct "BinningPix"
+
+   * manalysis/MPadSchweizer.[h,cc]
+     - add simulation of blind pixels
+
+   * mhist/MHMatrix.cc
+     - in DefRefMatrix : allow variable bin size for 'hth' and 'hthd'
+
+
+
+ 2003/05/20: Oscar Blanch Bigas
+
+   * mgeom/MGeomCamECO1000HG.[h,cc]
+     - new files for ECO1000 camera geometry with pixels
+       of half angualr size.
+
+   * mgeom/Mkefile:
+     - added MGeomCamECO1000HG.[h,cc] files
+
+   * mgeom/GeomLinkDef.h
+      - added class MGeomCamECO1000HG
+
+
+
+ 2003/05/20: Thomas Bretz
+
+   * mbase/MLog.h:
+     - added Separator member function
+     
+   * mfileio/MReadMarsFile.cc:
+     - moved output in Notify to MReadTree::Notify
+     - call MReadTree:Notify in Notify
+     
+   * mfileio/MReadTree.[h,cc]:
+     - do not try to delete a Baddress if it is NULL ("*")
+     - added CheckBranchSize member function
+     - added the size consistency check to Notify
+     
+   * mfileio/MWriteRootFile.cc:
+     - mini changes to Print-output
+     
+   * mfilter/MF.[h,cc]:
+     - added Print-function
+     
+   * mraw/MRawEvtPixelIter.h:
+     - removed wrong EOL characters
+
+   * macros/multidimdist2.C:
+     - made variable names unique
+
+   * macros/star.C:
+     - added sigmabar
+
+   * macros/status.C:
+     - added sigmabar
+     - added MHSigmaTheta
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MFiltercutsCalc
+
+   * manalysis/MFiltercutsCalc.[h,cc]:
+     - added
+
+
+ 2003/05/19: Thomas Bretz
+
+   * mgui/MCamDisplay.cc:
+     - removed an unused variable.
+
+   * Makefile.rules:
+     - fixed Mr.Proper
+
+   * mbase/MEvtLoop.cc, mbase/MParList.cc, mbase/MTaskList.cc,
+     mfileio/MReadTree.cc, mfileio/MWriteRootFile.cc:
+     - use new manipulator 'underline'
+
+   * mbase/MLog.cc:
+     - added new underlining
+     - added blue color for debugging
+     
+   * mbase/MLogManip.[h,cc]:
+     - added underline
+     - added dbg and increased all other debug(n) levels by one
+     
+   * mbase/MParContainer.h:
+     - made fDisplay persistent (workaround for a obsolete warning in
+       root 3.02/07)
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - fixed a bug introduced when implementing UPDATE mode,
+       kIsNewTree set for TTree
+
+
+
+ 2003/05/16: Abelardo Moralejo
+
+   * mmontecarlo/MMcEnergyEst.[h,cc]
+     - Added SetCoeff
+
+
+
+ 2003/05/16: Thomas Bretz
+
+   * mfilter/MFEventSelector2.[h,cc]:
+     - added
+
+   * mfilter/Makefile, mfilter/FilterLinkDef.h:
+     - added MFEventSelector2
+
+   * mbase/MContinue.cc:
+     - SetDisplay for filter
+     - Set LogStream for filter
+     
+   * mbase/MEvtLoop.cc:
+     - don't use pointer to fTasklist in PostProcess if not initialized
+     - do not execute Process if fTasklist is not initialized
+     
+   * mbase/MTask.[h,cc]:
+     - overwrite SetDisplay (set also display of attached filter
+     
+   * mbase/MTaskList.cc:
+     - minor changes 
+     
+   * mdata/MDataChain.[h,cc]:
+     - implemented ParseDataMember to support constants
+
+   * mfileio/MCT1ReadPreProc.[h,cc]:
+     - added fNumFile to support Rewind
+     - added Rewind
+     
+   * mfileio/MRead.[h,cc]:
+     - new virtual function Rewind
+     
+   * mfileio/MReadMarsFile.[h,cc]:
+     - added Rewind
+     
+   * mfileio/MReadTree.[h,cc]:
+     - added Rewind
+     - fixed a missing 'else' in AddFile
+     
+   * mhist/MBinning.[h,cc]:
+     - added SetEdges(TAxis&)
+     - added SetEdges(TH1&, char)
+
+   * mhist/MFillH.[h,cc]:
+     - added bit kDoNotDisplay
+     
+   * mhist/MH.h:
+     - added a comment
+     
+   * mhist/MH3.[h,cc]:
+     - implemented GetRule
+     - implemented GetNbins
+     - implemented FindFixBin
+     
+   * mimage/MHHillasSrc.cc:
+     - replaced gPad->cd(4) by savepad
+
+   * mmain/MStatusDisplay.[h,cc]:
+     - fixed locked mode for loop-in-loop cases
+
+
+
+ 2003/05/15: Wolfgang Wittek
+
+   * macros/CT1EgyEst.C
+     - replace "energyest.root" by paramout
+
+
+
+ 2003/05/14: Wolfgang Wittek
+
+   * macros/CT1env.rc
+     - CT1env replaced by CT1env.rc
+
+   * mranforest/MRanForestCalc.cc
+     - exchange arguments in 
+       FindCreateObj("MHadronness", fHadronnessName)
+
+
+
+ 2003/05/13: Thomas Bretz
+
+   * mdata/MDataArray.[h,cc]:
+     - addeed GetData and >>-operator to fill a TVector from the array
+     
+   * manalysis/MMultiDimDistCalc.cc:
+     - use new >>-operator from MDataArray
+     
+   * mranforest/MRanForest.[h,cc]:
+     - TVector& in CalcHadronness declared const
+     - added a const qualifier to 'Float_t sum'
+     - removed Reset() from a TIter declaration (done by the TIter 
+       constructor)
+     
+   * mranforest/MRanForestCalc.cc:
+     - fill TVector with new >>-operator of MDataArray
+     
+   * mranforest/MRanTree.[h,cc]:
+     - removed obsolete returns at the end of some functions
+     - TVector& in TreeHad declared const
+     - changed if to ?:-operator in TreeHad
+     - TreeHad() calls TreeHad(const TVector &) now (code is not
+       implemented twice)
+
+
+
+ 2003/05/12: Abelardo Moralejo
+
+   * mhistmc/MHMcEnergyMigration.cc
+     - Draw(): fixed axis label in one plot.
+
+
+
+ 2003/05/12: Thomas Bretz
+
+   * mmain/MStatusDisplay.[h,cc]:
+     - implemented UpdatePSHeader
+
+
+
+ 2003/05/10: Thomas Bretz
+
+   * Makefile.rules:
+     - implemented diff
+     
+   * NEWS:
+     - changed
+     
+   * manalysis/MCT1SupercutsCalc.cc:
+     - fixed variable names
+     
+   * mbase/MParContainer.cc:
+     - replaces IsA()->GetName() by ClassName()
+     
+   * mbase/Makefile:
+     - removed obsolete include paths
+     
+   * mdata/MDataArray.[h,cc]:
+     - new member function GetRule(int)
+
+   * mgui/MCamDisplay.[h,cc]:
+     - implemented GetObjectInfo
+
+   * mhist/MH.[h,cc]:
+     - implemented ProjectionX
+     - implemented ProjectionY
+     - implemented FindObjectInPad
+     
+   * mhist/MHSigmaTheta.[h,cc]:
+     - implemented Paint
+     
+   * mmain/MStatusDisplay.[h,cc]:
+     - implemented kFileCanvas
+     - implemented kFileBrowser
+
+
+
+ 2003/05/09: Abelardo Moralejo
+
+   * mhistmc/MHMcEnergyMigration.[h,cc]
+     - Added histograms, changed Draw() to display them. Still 
+       provisional, many changes in the whole part of the energy 
+       estimator are needed.
+
+   * macros/CT1EEst.C, CT1EnergyEst.C
+     - Removed
+
+   * macros/CT1EgyEst.C
+     - Added example on how to use the energy estimation for CT1.
+       Very provisional!
+
+
+
+ 2003/05/09: Wolfgang Wittek
+
+   * manalysis/MCT1SupercutsCalc.cc
+     - add SetReadyToSave()
+
+
+
+ 2003/05/09: Thomas Bretz
+
+   * mbase/MLog.cc:
+     - do not underline if eNoColors is set
+     - fixed abug in Output() (last character missing when flushed)
+     - same when flushing to the GUI
+     
+   * mbase/MLogManip.cc:
+     - removed an obsolete comment
+     
+   * mfileio/MReadTree.cc:
+     - print warning in case no files could be added to chain
+     
+   * mfilter/MFDataChain.h:
+     - fixed code layout
+     
+   * mimage/MHHillasSrc.h:
+     - added Paint
+     
+   * mimage/MHillasCalc.[h,cc]:
+     - changed default title
+
+   * Makefile:
+     - added rule 'diff'
+
+   * mhist/MHMatrix.cc:
+     - compressed some debug outputs
+
+   * manalysis/MSigmabar.[h,cc]:
+     - deleted the fCalcPixNum variable (not used).
+
+   * macros/star.C, macros/starct1.C:
+     - updated
+
+   * mhist/MBinning.cc:
+     - fixed SetBinningCos
+     
+   * mhist/MHSigmaTheta.[h,cc]:
+     - in setting of binnings changes npix+1 to npix 
+       (SetEdges takes the number of _bins_ as argument)
+     - fixed titles (LaTeX style)
+     - added default binning (may have to be changed for Magic)
+     - removed obsolete destructor
+     - removed default canvas size of 900x900
+     - temporarily removed SetLogy() for first pad. I'm searching
+       for a solution to put it in again when using the status display
+
+
+
+ 2003/05/08: Thomas Bretz
+
+   * Makefile.rules:
+     - fixed the rmhtml bug
+
+   * macros/collarea.C:
+     - changed to use MStatusDisplay
+     
+   * manalysis/MCT1SupercutsCalc.cc: 
+     - fixed a typo
+     
+   * mbase/MEvtLoop.[h,cc], mbase/MTaskList.[h,cc]:
+     - added FindTask member functions
+     
+   * mbase/MLog.cc:
+     - do not crop logging to GUI to 1000 lines anymore
+
+   * mdata/MDataChain.cc:
+     - use GetRule() in the constructor instead of Print()
+     
+   * mdata/MDataElement.cc, mfilter/MFDataChain.cc:
+     - do not return str+"something"
+     
+   * mhist/MH.[h,cc]:
+     - fixed a bug in DrawCopy(TH1*,TH1*)
+     - overwrite Clone function and do not add TH1 to gDirectory 
+       when cloning MH classes
+     
+   * mimage/MHHillas.cc, mimage/MHHillasSrc.cc:
+     - adde a sanity check to Fill
+     
+   * mimage/MHHillasSrc.cc:
+     - do not set the log scale before we have entries in the histogram
+
+
+
+ 2003/05/08: Abelardo Moralejo
+
+   * mimage/MImgCleanStd.cc
+     - extended comment on standard cleaning. Removed an obsolete 
+       comment.
+
+   * mhistmc/MHMcCollectionAreaCalc.cc
+     - Changed binning of histograms, so that the collection area
+       can be calculated also between 5 and 10 GeV (for pulsar studies)
+
+
+
+ 2003/05/07: Nadia Tonello
+
+   * manalysis/MCT1PointingCorrCalc.[h,cc]
+     - deleted the fMcEvt variable (not used).
+
+
+ 2003/05/07: Thomas Bretz
+
+   * mmain/Makefile, mmain/MainLinkDef.h:
+     - added MSearch
+     
+   * mmain/MSearch.[h,cc]:
+     - added
+
+   * mmmain/MStatusDisplay.[h,cc]:
+     - implemented Search
+
+   * mhist/MHSigmaTheta.cc:
+     - removed borders around the pads (Draw)
+
+   * mfileio/MCT1ReadPreProc.cc:
+     - do not output the run number twice!
+
+   * mimage/MHillasExt.[h,cc]:
+     - changed ClassDef to 2
+     - updated comments
+
+   * mimage/MNewImagePar.cc:
+     - updated comments
+
+
+
+ 2003/05/07: Abelardo Moralejo
+
+   * mranforest/Makefile
+     - fixed typo.
+
+
+
+ 2003/05/06: Abelardo Moralejo
+ 
+   * mhistmc/MHMcCollectionArea.cc
+     - Added:  delete &pally
+
+   * mfilter/MFCT1SelFinal.cc
+     - changed FindObject("MGeomCam") to 
+       FindCreateObj("MGeomCamCT1","MGeomCam")
+
+   * mhistmc/MHMcCollectionArea.cc
+     - in procedure Calc(TH2D &hsel, TH2D &hall) : changed the 
+       calculation of maximum impact parameter. Now it looks for
+       the non-empty bin of histogram "hall" with highest impact 
+       parameter. The code could not work as it was before, but this 
+       had influence only when running over camera files containing all 
+       events, including non-triggers (while we usually run over files
+       containing only triggers).
+
+
+
+ 2003/05/06: Thomas Bretz
+ 
+   * manalysis/MRan*, mhist/MHRan*:
+     - moved to new directory mranforest
+     
+   * mranforest, mranforest/Makefile, mranforest/RanForestLinkDef.h,
+     mranforest/RanForestIncl.h:
+     - added
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MRan*
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MHRan*
+
+   * Makefile:
+     - mranforest added
+
+   * mbase/MLog.cc:
+     - sanity check in MLog::Output (len>0)
+
+   * mimage/MImgCleanStd.cc:
+     - adapted path to html images
+
+   * htmldoc/*:
+     - moved to new path htmldoc/images
+
+   * Makefile.rules:
+     - corrected rule rmhtmldoc
+     
+   * NEWS:
+     - updated
+
+   * macros/dohtml.C, macros/rootlogon.C:
+     - added mranforest
+
+   * mbase/MEvtLoop.cc:
+     - fixed a typo
+     
+   * mhist/HistLinkDef.h
+
+
+
+ 2003/05/05: Nadia Tonello
+
+   * mfilter/MFCT1SelStandard.cc
+     - correct the default name of fImgParName
+	("MNewImgPar") => ("MNewImagePar")
+
+
+
+ 2003/05/05: Thomas Bretz
+ 
+   * mbase/MEvtLoop.cc:
+     - underline Instatiation Message
+     - small change to a warning output
+     
+   * mbase/MLog.[h,cc]:
+     - added stuff for underlining
+     - changed from TGListBox to TGViewText
+     
+   * mmain/MStatusDisplay.[h,cc]:
+     - changed fLogBox from TGListBox to TGViewText
+     - added menu 'Log'
+     - changed division of status line to 'Goldener Schnitt'
+
+   * mhist/MHHadronness.cc, mhist/MHCerPhotEvt.cc, mhist/MHStarMap.cc,
+     mimage/MHHillas.cc:
+     - fixed 'redifinion of default argument'
+
+   * mbase/Makefile, mfileio/Makefile:
+     - moved first source file to second position to get rid of crashes
+       of rootcint on our Alpha
+
+   * mimage/MNewImagePar.cc:
+     - removed maxpixid (not used)
+
+   * manalysis/MRanTree.cc:
+     - replaced ostream.h by iostream.h
+
+   * manalysis/MPadding.h:
+     - added a missing const qualifier in the definition of 'Padding'
+
+   * mmontecarlo/MMcEnergyEst.cc:
+     - added math.h
+
+   * Makefile, mbase/Makefile, mmain/Makefile:
+     - changed order (linking on our Alpha failed)
+
+   * mbase/MLog.h:
+     - don't include iostream.h if __CINT__ (crashes rootcint on our
+       alpha)
+
+
+
+ 2003/05/05: Wolfgang Wittek
+
+   * manalysis/MPadSChweizer.cc
+     - delete histograms in destructor
+
+
+
+ 2003/05/02: Thomas Bretz
+
+   * Makefile.conf.general, Makefile.conf.linux, Makefile.conf.linux-gnu,
+     Makefile.conf.osf1, Makefile.conf.osf5.1:
+     - added MARSDEFINES, MARSFLAGS, MARSLIBS
+     
+   * mars.cc:
+     - replaces HAVE_LOGO by HAVE_XPM
+ 
+   * NEWS:
+     - updated
+     
+   * mbase/MLogo.cc:
+     - replaces marslogo_neu by marslogo
+     - encapsulated in HAVE_XPM
+     
+   * mbase/Makefile:
+     - added MLogo.cc
+     
+   * mmain/MGMenu.cc:
+     - fixed the 'KeyAutoRepeat' bug
+
+   * manalysis/MCerPhotEvt.[h,cc:
+     - added RemoveUnusedPixels
+     
+   * manalysis/MSigmabar.cc:
+     - small simplification for compiler optimization
+     
+   * mbase/MEvtLoop.cc:
+     - changed output to fDisplay
+     - changed behaviour in case of a failed PostProcess
+     
+   * mbase/MLog.[h,cc]:
+     - added flushing and tab conversion to GUI
+     - added color support
+     
+   * mbase/MParList.cc:
+     - replaced some *Iter by MIter
+
+   * mbase/MTask.cc, mbase/MTaskList.cc:
+     - added output to fDisplay
+     - replaced some *Iter by MIter
+     
+   * mhist/MH.cc:
+     - don't add clones to directory
+     
+   * mimage/MImgCleanStd.[h,cc]:
+     - replaced divisiond by multiplications
+     - fixed StreamePrimitive
+     - do not allow 0 rings
+     
+   * mmain/MStatusDisplay.[h,cc]:
+     - added writing gif
+     - added writing C
+     - changes SaveAs to non-const (added output to status lines)
+     - replaced TGLabels by TGStatusBar
+
+
+
+ 2003/04/30: Wolfgang Wittek
+
+   * manalysis/MPadSchweizer.[h,cc]
+     - reorder histograms
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - remove last 3 plots (otherwise get segmentation violation ???)
+
+   * mimage/MHNewImagePar.[h,cc]
+     - change range of leakage to be plotted
+       (want to see also leakage=0)
+
+
+
+ 2003/04/30: Nadia Tonello
+
+   * manalysis/MCerPhotPix.[h,cc]:
+     - deleted Bool_t fIsUsed and substituted with 
+	the condition: fRing>0 in the functions
+	Bool_t IsPixelUsed() const{return fRing>0;}
+	void   SetPixelUsed()  { fRing = 1;}
+	void   SetPixelUnused(){ fRing = 0;}
+
+
+
+ 2003/04/29: Wolfgang Wittek
+
+   * mhist/MHSigmaTheta.[h,cc]:
+     - ClassDef( ,0) -> ClassDef( , 1)
+     - minor corrections in Draw()
+
+
+
+ 2003/04/29: Thomas Bretz
+ 
+   * mfilter/MFCT1SelBasic.[h,cc], mfilter/MFCT1SelFinal.[h,cc],
+     mfilter/MFCT1SelStandard.[h,cc]:
+     - reordered includes
+     - removed MHillas from constructor (if present)
+     - added corresponding Setter-methods
+     - added many const qualifiers
+     - removed some obsolete data members
+     - made some member functions private
+     - only store fMm2Deg, not the pointer to MGeomCam
+     - don't use the CT1 camera build in... (to be discussed)
+     - fixed MHillas, MHillasExt and MNewImagePar stuff
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - added Nadia to the list of authors
+     - added pngs for the formulars
+     
+   * htmldoc, htmldoc/MImgCleanStd-f1.png, htmldoc/MImgCleanStd-f2.png:
+     - added
+
+   * manalysis/MCT1SupercutsCalc.[h,cc]:
+     - changed the default "MHillasExt" to "MHillas"
+
+   * mbase/MEvtLoop.cc:
+     - fixed a bug in ProcessGuiEvents
+
+   * mhist/MH*.[h,cc], mhistmc/MH*.[h,cc], mimage/MH*.[h,cc]:
+     - changed "Double_t w" in Fill to "const Stat_t w"
+     - added weight in some classes to TH::Fill
+
+   * mbase/MHtml.[h,cc]:
+     - removed
+
+   * mfileio/MCT1ReadPreProc.cc:
+     - removed the dependance on a MBinning in Theta.
+
+
+
+ 2003/04/29: Abelardo Moralejo
+
+   * mmontecarlo/MMcCollectionareaCalc.[h,cc]
+     - Now the energy limits and spectral slope used in Corsika are
+       read from the run header. Warning: impact parameter is still
+       fixed (I changed it from 400 m to 300 m, our present MC 
+       production default). Added warning message about this. 
+       Collection areas calculated up to now with the new MC library 
+       are overestimated by a ~77% ! This class will be removed in 
+       the future and replaced by MFillH.
+
+   * mhistmc/MHMcCollectionArea.[h,cc]
+     - Adapted to the change of MMcCollectionAreaCalc. Added arguments
+       to CalcEfficiency.
+
+
+
+ 2003/04/28: Nadia Tonello 
+
+   * mimage/MImgCleanStd.[h,cc]
+     - added the option kDemocratic using sigmabar of the inner pixels
+     - added the option to select the number of rings of pixels 
+       to analyze around the core pixels 
+     - added documentation
+
+   * manalysis/MCerPhotPix.[h,cc]
+     - added fRing and Get-Set functions 
+
+
+
+ 2003/04/28: Oscar Blanch
+
+   * mgeom/MGeomCamECO1000.[h,cc]
+     - New files for ECO 1000 camera geometry.
+
+   * mgeom/GeomLinkDef.h
+     - Added class MGeomCamECO1000
+
+   * mgeom/Makefile 
+     - Added class MGeomCamECO1000
+
+
+
+ 2003/04/28: Abelardo Moralejo
+
+   * mmontecarlo/MMcEnergyEst.[h,cc]
+     - Lots of fixes after Thomas suggestions. Now cuts are not part
+       of the class, but introduced via a new MFilter* member. Changed
+       all Char_t* for TString. Changed own TMiniut pointer by gMinuit.
+       Removed couts and used fLog instead. Function fcn is no longer
+       declared external.
+
+
+
+ 2003/04/28: Thomas Bretz
+
+   * NEWS:
+     - updated
+     
+   * manalysis/MBlindPixelCalc.cc:
+     - use Are of pixles while interpolating
+     
+   * mbase/MEvtLoop.cc:
+     - output speed in Evts/s to fDisplay
+     
+   * mbase/MGGroupFrame.h:
+     - fixed a typo
+     
+   * mbase/MTask.[h,cc]:
+     - Added OverwritesProcess
+     
+   * mbase/MTaskList.[h,cc]:
+     - removed CheckClassForProcess
+     - replaced by MTask::OverwritesProcess
+     
+   * mhist/MFillH.cc:
+     - only draw something if the class overwrites the Draw function
+   
+   * mhist/MH.[h,cc]:
+     - added OverwritesDraw
+     - added a higher maximum, lower minimum to Draw(TH1, TH1)
+     - changed default size 
+   
+   * mhist/MHMatrix.cc:
+     - mini change
+     
+   * mimage/MHHillas.[h,cc]:
+     - removed fUsedPix
+     - removed fCorePix
+     
+   * mimage/MHHillasExt.[h,cc]:
+     - removed fHConc
+     - removed fHConc1
+     - changed default name to MHillasExt
+     
+   * mimage/MHNewImagePar.[h,cc]:
+     - added fHistConc
+     - added fHistConc1
+     - added fHistUsedPix
+     - added fHistCorePix
+     
+   * mimage/MHillas.cc:
+     - removed fNumCorePixels
+     - removed fNumUsedPixels
+     - made fCosDelta writable
+     - made fSinDelta writable
+     - made GetSinDelta() public
+     - made GetCosDelta() public
+      
+   * mimage/MHillasExt.[h,cc]:
+     - removed fConc
+     - removed fConc1
+     - changed default name to MHillasExt
+     - derives from MParContainer now instead of MHillas
+     
+   * mimage/MNewImagePar.[h,cc]:
+     - added fNumCorePixels
+     - added fNumUsedPixels
+     - added fConc
+     - added fConc1
+   
+   * mimage/MNewImageParCalc.[h,cc]:
+     - removed
+
+   * mimage/MHillasCalc.[h,cc]:
+     - changed so, that it can calc MHillas, MHillasExt and MNewImagePar
+
+   * mimage/MHillasSrc.cc:
+     - sqrt(tand*tand+1) replaced by 1/CosDelta    
+
+   * mmain/MStatusDisplay.[h,cc]:
+     - added second argument to SetLogStream
+
+   * mhist/MHAlphaEnergyTheta.[h,cc], mhist/MHAlphaEnergyTime.[h,cc],
+     mhist/MHCerPhotEvt.[h,cc], mhist/MHEffOnTime.[h,cc],
+     mhist/MHEffOnTimeTheta.[h,cc], mhist/MHEffOnTimeTime.[h,cc],
+     mhist/MHEnergyTheta.[h,cc], mhist/MHEnergyTime.[h,cc],
+     mhist/MHFlux.[h,cc], mhist/MHMatrix.[h,cc],
+     mhist/MHSigmaTheta.[h,cc], mhistmc/MHMcCollectionArea.[h,cc],
+     mhistmc/MHMcDifRate.[h,cc], mhistmc/MHMcEfficiency.[h,cc],
+     mhistmc/MHMcEfficiencyEnergy.[h,cc], mhistmc/MHMcEfficiencyImpact.[h,cc],
+     mhistmc/MHMcEnergy.[h,cc], mhistmc/MHMcEnergyImpact.[h,cc],
+     mhistmc/MHMcEnergyMigration.[h,cc], mhistmc/MHMcRate.[h,cc]:
+     - removed DrawClone
+     - fixed Draw
+
+   * macros/MagicHillas.C, macros/star.C:
+     - removed MHillasExt (not necessary anymore)
+     - added MNewImagePar
+     
+   * macros/readCT1.C, macros/readMagic.C, meventdisp/MGCamDisplay.cc,
+     mmain/MAnalysis.cc:
+     - added MHillasExt to be displayed
+     - added MNewImagePar to be displayed
+
+   * manalysis/MCT1SupercutsCalc.[h,cc]:
+     - removed empty destructor
+     - fixed output in PreProcess
+     - changed MHillasExt to MHillas
+
+
+
+
+
+ 2003/04/28: Wolfgang Wittek
+
+   * manalysis/MPadSchweizer.[h,cc]
+     - extend documentation
+     - remove histograms which are also made by MHSigmaTheta
+     - minor modifications
+
+
+
+ 2003/04/25: Thomas Bretz
+
+   * mfilter/MFEnergySlope.cc:
+     - removed obsolete PostProcess
+
+   * mdatacheck/MGDisplayAdc.cc:
+     - fixed a bug which caused nothing to beeing displayed if only
+       the Hi gains where existing (Exists->HasHi)
+
+   * mhist/MH.cc:
+     - small change to GetNewPad
+
+   * mhistmc/MHMcEnergyMigration.h:
+     - fixed the includes
+
+   * mgui/MCamDisplay.cc:
+     - changed autoscaling (max<1:max=1 --> max==min:max=min+1)
+
+   * manalysis/MBlindPixelCalc.cc:
+     - interpolate: take pixel area into account
+
+   * mhist/MHSigmaTheta.h:
+     - removed nonsense GetSigmaThetaByName(const TString name)
+     - removed nonsense GetSigmaPixThetaByName(const TString name)
+     - removed nonsense GetDiffPixThetaByName(const TString name)
+     
+   * manalysis/MPadSchweizer.cc:
+     - fixed naming
+     - fixed usage of operators
+     - added some const qualifiers
+     - replaced 'int OK' by 'Bool_t ok'
+     - fixed wrong usage floating point value 0
+
+   * mimage/MImgCleanStd.cc:
+     - moved ratio to the other side of the condition (don't divide
+       if it is not necessary)
+
+
+
+ 2003/04/24: Abelardo Moralejo
+
+   * macros/rootlogon.C
+     - added gInterpreter->AddIncludePath(dir+"mhistmc");
+
+
+
+ 2003/04/24: Thomas Bretz
+
+   * macros/rootlogon.C:
+     - added mimage
+
+   * macros/dohtml.C:
+     - added mhistmc
+     - added mimage
+     - added status.C
+
+   * mfilter/MFCT1Supercuts.[h,cc]:
+     - removed
+
+   * manalysis/MPadSchweizer.[h,cc]:
+     - renamed arguments of SetHistograms to Mars style
+     - removed default argument for SetHistograms (usage would result
+       in a crash)
+     - removed empty destructor
+
+   * mhistmc/MHMcTriggerLvl2.h:
+     - removed the wrong f in GetHistf
+
+   * manalysis/MSigmabarParam.h:
+     - added const qualifiers to getters
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - fixed support for UPDATE
+
+   * mfilter/MFEnergySlope.cc:
+     - cleaned
+     - removed empty PostProcess
+     
+   * mhist/MHCerPhotEvt.cc:
+     - removed ratio from Fill
+
+   * mhist/MH.h:
+     - fixed a bug in the overloading of DrawClone
+
+   * mimage/MHillasSrc.[h,cc], mimage/MHHillasSrc.[h,cc]:
+     - like suggested by Wolfgang: removed Head-Tail
+
+   * mbase/MEvtLoop.cc:
+     - fixed a bug in the progress bar update at the end of the loop
+
+
+
+ 2003/04/24: Wolfgang Wittek
+
+    * mfilter/MFCT1SelFinal.cc
+      - small correction in output
+
+    * mhistmc/MHMcCT1CollectionArea.cc
+      - plot all 3 histograms in DrawClone()
+
+    * manalysis/MPadSchweizer.[h,cc]
+      - cleanup as proposed by Thomas
+      - new member function SetHistograms() to set the pointers to the
+        histograms to be used in the padding
+
+
+
+ 2003/04/24: Antonio Stamerra
+
+    * mhistmc/MHMcTriggerLvl2.[h,cc]
+      - renamed some variable (hf->fHist)
+      - added fHist*Norm and fFNorm in the destructor
+
+    * manalysis/MMcTriggerLvl2.[h,cc]
+      - added CalcCompactPixel() public method
+      - implemented CalcPseudoSize method (still under construction...)
+      - added inline method SetNewCamera(), used in the costructor
+      - renamed global variables pixels_in_cell->gsPixelsInCell 
+        and pixels_in_lut->gsPixelsInLut
+      - added destructor
+
+
+
+ 2003/04/23: Thomas Bretz
+
+   * mhist/MHCerPhotEvt.[h,cc]:
+     - updated dox
+
+   * manalysis/MCT1SupercutsCalc.h, manalysis/MPadSchweizer.h:
+     - ClassDef -> 0
+
+   * NEWS:
+     - updated
+     
+   * mfileio/MWriteRootFile.[hcc]:
+     - fixed the missing function of UPDATE files
+     
+   * mhist/MFillH.[h,cc]:
+     - implemented fWeight
+     - adapted StreamPrimitive
+     - changed fCanvas to //!
+     - changed class version umber from 1 to 2
+   
+   * mhist/MH.[h,cc], mhist/MHAlphaEnergyTheta.[h,cc],
+     mhist/MHAlphaEnergyTime.[h,cc], mhist/MHArray.[h,cc],
+     mhist/MHBlindPixels.[h,cc], mhist/MHCompProb.[h,cc],
+     mhist/MHEffOnTime.[h,cc], mhist/MHEffOnTimeTheta.[h,cc],
+     mhist/MHEffOnTimeTime.[h,cc], mhist/MHEnergyTheta.[h,cc],
+     mhist/MHFadcCam.[h,cc], mhist/MHFlux.[h,cc],
+     mhist/MHGamma.[h,cc], mhist/MHHadronness.[h,cc],
+     mhist/MHMatrix.[h,cc], mhist/MHRanForest.[h,cc],
+     mhist/MHRanForestGini.[h,cc], mhist/MHSigmaPixel.[h,cc],
+     mhist/MHSigmaTheta.[h,cc], mhist/MHSigmabarTheta.[h,cc],
+     mhist/MHStarMap.[h,cc], mhist/MHThetabarTheta.[h,cc],
+     mhist/MHThetabarTime.[h,cc], mhist/MHTimeDiffTheta.[h,cc],
+     mhist/MHTimeDiffTime.[h,cc], mhistmc/MHMcCT1CollectionArea.[h,cc],
+     mhistmc/MHMcEnergyImpact.[h,cc], mhistmc/MHMcEnergyMigration.[h,cc]
+     mhistmc/MHMcTriggerLvl2.[h,cc], mimage/MHHillas.[h,cc],
+     mimage/MHHillasExt.[h,cc], mimage/MHHillasSrc.[h,cc],
+     mimage/MHNewImagePar.[h,cc]:
+     - added second (weight) argument to Fill
+     - in some headers: removed obvious virtual
+     - removed some dummy Fill function (not necessary anymore)
+     
+
+
+ 2003/04/23: Abelardo Moralejo
+
+    * mhistmc/MHMcCT1CollectionArea.[h,cc]
+      - Now the class inherits from MH instead of directly from 
+       	MParContainer. Implemented SetupFill, so that the binning
+	definitions are read from the parlist.
+
+    * mmontecarlo/MMcCT1CollectionAreaCalc.[h,cc]
+      - Removed. This class was superfluous, since the same job 
+ 	can be done using MFillH.
+
+    * mmontecarlo/Makefile, MontecarloLinkDef.h
+      - removed class MMcCT1CollectionAreaCalc.
+
+    * macros/CT1collarea.C
+      - adapted to changes above.
+
+    * mmc/MMcRunHeader.[hxx,cxx], mmc/MMCEvt.[hxx,cxx]
+      - added comment in class description about the definition of
+	the azimuth angle phi in the MC classes.
+
+
+ 2003/04/23: Antonio Stamerra
+
+    * mfilter/MFEnergySlope.[h,cc]
+      - added new filter class to select events according to a given
+	energy slope 
+
+    * mfilter/Makefile, mfilter/FilterLinkDef.h
+      - modified accordingly (added MFEnergySlope)
+
+    * manalysis/MMcTriggerLvl2Calc.cc 
+      - removed call to the MHMcTriggerLvl2->Fill() in Process()
+
+    * macros/triglvl2.C 
+      - added example of the MFEnergySlope filter
+      - added filling of histos from MHMcTriggerLvl2
+
+
+ 2003/04/22: Abelardo Moralejo
+
+    * mmontecarlo/Makefile, MontecarloLinkDef.h
+      - added MMcEnergyEst
+      - added necessary include directories.
+
+    * mmontecarlo/MMcEnergyEst.cc
+      - added filterhadrons.SetHadronnessName(fHadronnessName) to
+        inform the filter about the name of the hadronness container
+        to be used in the cuts.
+
+    * mfilter/MFCT1SelFinal.[h,cc]
+      - added the possibility to cut also in Dist.
+
+
+
+ 2003/04/22: Thomas Bretz
+
+    * mhist/MHHadronness.[h,cc]:
+      - changed to support MStatusDisplay
+
+    * manalysis/MApplyPadding.[h,cc]:
+      - removed
+
+    * mhist/MHMcCT1CollectionArea.[h,cc], 
+      mhist/MHMcCollectionArea.[h,cc], mhist/MHMcDifRate.[h,cc], 
+      mhist/MHMcEfficiency.[h,cc], mhist/MHMcEfficiencyEnergy.[h,cc], 
+      mhist/MHMcEnergy.[h,cc], mhist/MHMcEnergyImpact.[h,cc], 
+      mhist/MHMcEnergyMigration.[h,cc], mhist/MHMcIntRate.[h,cc], 
+      mhist/MHMcRate.[h,cc], mhist/MHMcTriggerLvl2.[h,cc]:
+      - moved to new directory mhistmc
+    
+    * mhistmc, mhistmc/Makefile, mhistmc/HistMcLinkDef.h:
+      - new
+
+    * mhist/Makefile, mhist/HistLinkDef.h:
+      - removed MHMc*
+      
+    * mhistmc/MHMcCollectionArea.[h,cc]:
+      - changed to fit requirements of MStatusDisplay
+
+    * Makefile:
+      - added mhistmc
+
+    * mmain/MStatusDisplay.cc:
+      - SetNoContextMenu(Bool_t flag) removed default argument
+
+    * mmain/Makefile:
+      - added -I../mhistmc
+
+   * mhist/MWeight.[h,cc]:
+     - added
+     
+   * mhist/HistLinkDef.h:
+     - added MWeight
+     
+   * mhist/MH.h:
+     - removed some debugging stuff
+
+
+
+ 2003/04/22: Abelardo Moralejo
+
+   * mmontecarlo/MMcEnergyMigration.[h,cc]
+     - Removed. It was not necessary, since the same job can be done 
+       with the already existing task MFillH.
+
+   * mhist/MHMcEnergyMigration.h
+     - Changed ClassDef(MHMcEnergyMigration, 0) 
+       to ClassDef(MHMcEnergyMigration, 1) to allow writing the 
+       histograms to disk.
+
+
+
+ 2003/04/21: Thomas Bretz
+
+   * manalysis/MBlindPixels.h:
+     - IsBlind -> const
+     
+   * mhist/HistLinkDef.h, mhist/Makefile:
+     - added MHBlindPixels
+   
+   * mhist/MH.[h,cc]:
+     - changed the two DrawClone functions to one.
+     
+   * mhist/MHHadronness.[h,cc]:
+     - changed to fit the requirements of MStatusDisplay
+     
+   * mhist/MHMatrix.cc:
+     - SetDirectory(NULL) for all histograms created
+
+   * mhist/MHSigmaTheta.cc:
+     - removed fNpix    (is already in MHHillas)
+     - removed fBlindId (--> MHBlindPixels)
+
+   * mhist/MHBlindPixels.[h,cc]:
+     - new
+
+   * macros/plot.C:
+     - Added MStatusDisplay support
+     
+   * macros/status.C:
+     - added MHNewImagePar
+     - added MHHadronness
+
+   * manalysis/MBlindPixelCalc.cc:
+     - updated class reference
+     
+   * meventdisp/MGCamDisplay.[h,cc]:
+     - fixed
+     
+   * meventdisp/MGEvtDisplay.cc:
+     - changed function adding the tab
+     
+   * mgui/MCamDisplay.cc, mhist/MHCerPhotEvt.cc:
+     - as a preliminary solution removed inner pad
+
+   * mhist/MFillH.cc:
+     - make sure canvas is updated correctly in PostProcess
+
+   * mhist/MH.cc:
+     - changed DrawCopy(TH1, TH1) and Draw(TH1, TH1) to fit the new needs
+       display the range correctly and exchanged the two stat boxes
+   
+   * mhist/MH3.cc:
+     - fixed a bug in the default constructor
+     - removed DrawClone
+     - updated Draw function
+     
+   * mhist/MHMcIntRate.[h,cc], mhist/MHRanForest.[h,cc],
+     mhist/MHRanForestGini.[h,cc], mhist/MHSigmaPixel.[h,cc],
+     mhist/MHSigmaTheta.[h,cc], mhist/MHSigmabarTheta.[h,cc],
+     mhist/MHThetabarTheta.[h,cc], mhist/MHThetabarTime.[h,cc],
+     mhist/MHTimeDiffTheta.[h,cc], mhist/MHTimeDiffTime.[h,cc],
+     mimage/MHNewImagePar.[h,cc]:
+     - removed old DrawClone
+     - updated Draw function
+     - replaced some titles by latex titles in some classes
+
+   * mimage/MHNewImagePar.[h,cc], mimage/MNewImagePar.[h,cc]:
+     - removed scaling stuff
+
+   * mmain/MStatusDisplay.cc:
+     - fixed some minor bugs
+
+
+
+ 2003/04/20: Thomas Bretz
+
+   * Makefile:
+     - exchanged mbase and mmain
+   
+   * Makefile.conf.general:
+     - added MARSVER
+   
+   * mars.cc:
+     - use MARSVER
+   
+   * macros/readMagic.C:
+     - updated to work with the new MH-stuff
+     
+   * macros/status.C:
+     - added
+     
+   * manalysis/MBlindPixelCalc.cc, manalysis/MCerPhotCalc.cc,
+     manalysis/MMcPedestalCopy.ccm, manalysis/MMcPedestalNSBAdd.cc,
+     mfileio/MReadMarsFile.cc, mimage/MHillasCalc.cc,
+     mimage/MImgCleanStd.cc:
+     - changed def. title
+   
+   * manalysis/MCT1PointingCorrCalc.h:
+     - minor change
+     
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - don't use unused pixels for calculation of min/max
+     - added Scale member function
+   
+   * manalysis/MCerPhotPix.h:
+     - added Scale inline function
+     
+   * mbase/MEvtLoop.[h,cc], mbase/MParContainer.[h,cc],
+     mbase/MParList.[h,cc], mbase/MTaskList.[h,cc],
+     mfileio/MReadMarsFile.cc, mhist/MFillH.[h,cc]:
+     - implemented use of fDisplay 
+   
+   * mbase/MParContainer.h:
+     - Don't display name and class name if it is the same (GetDescriptor)
+
+   * meventdisp/MGCamDisplay.[h,cc]:
+     - made working with new MH-stuff
+   
+   * mfileio/Makefile:
+     - added -I../mmain
+   
+   * mgeom/MGeomCam.[h,cc]:
+     - added Clone function
+
+   * mgeom/MGeomCamCT1.cc, mgeom/MGeomCamMagic.cc:
+     - commented out informal output at constructor
+   
+   * mgui/MCamDisplay.[h,cc], mhist/MHStarMap.[h,cc], 
+     mimage/MHH*.[h,cc]:
+     - changed to be more root oriented
+   
+   * mgui/MHexagon.cc:
+     - small changes
+     
+   * mgui/Makefile:
+     - added mhist
+     
+   * mhist/MH.[h,cc]:
+     - changed to be more root oriented
+     - removed border
+     - added DrawClone
+     - GetNewPad
+
+   * mhist/MH3.cc:
+     - removed some strange debug output
+     
+   * mhist/MHCerPhotEvt.[h,cc]:
+     - fixed some bug
+     - made working with fDisplay
+   
+   * mhist/Makefile:
+     - added mmain
+     
+   * mmain/MProgressBar.cc:
+     - fixed a typo
+     
+   * mmain/MStatusDisplay.[h,cc]:
+     - new implementation
+     
+   * mmain/MainLinkDef.h, mmain/Makefile:
+     - added MStatusDisplay
+     - added MGMenu
+
+   * mmain/MGMenu.[h,cc]:
+     - added
+
+
+
+ 2003/04/19: Abelardo Moralejo
+
+   * mmontecarlo/MMcEnergyEst.[h,cc]
+     - Added. Contains routine for optimization of parameters of 
+       energy estimator.
+
+   * mmontecarlo/MMcEnergyMigration.[h,cc]
+     - Added. Task to fill the energy migration matrix histograms 
+       contained in class MHMcEnergyMigration.
+
+
+
+ 2003/04/17: Wolfgang Wittek
+
+   * mhist/MBinning.[h,cc]
+     - replace      for (int i=1; i<fEdges.GetSize()-1; i++)
+            by      for (int i=1; i<fEdges.GetSize(); i++)
+
+
+
+ 2003/04/17: Wolfgang Wittek
+
+   * mfileio/MCT1ReadPreProc.cc
+     - removed : if (theta > pi/2) continue;
+       otherwise get inconsistency between no.of read events 
+       and no.of events after filter
+     - write into MCerPhotEvt also pixels with zero no. of photons
+
+   * manalysis/MSigmabar.cc
+     - correct wrong argument in call to memset
+
+   * manalysis/MPadSchweizer.cc
+     - pad also pixels with zero no.of photons
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - add plot of no.of used pixels in MCerPhotEvt
+     - add plot of Id of blind pixel
+
+
+
+ 2003/04/14: Wolfgang Wittek
+ 
+  * manalysis/Makefile
+              AnalysisLinkDef.h
+    - MNewImagePar and MNewImageParCalc removed
+    
+
+
+
+ 2003/04/12: Thomas Bretz
+
+   * mmain/MStatusDisplay.[h,cc]:
+     - added
+
+   * manalysis/MPadding.[h,cc]:
+     - simplified includes
+     - changed some code (discussed with Robert)
+     - fixed comments in header
+     - changed ClassDef to 0
+     - changed output to Mars style
+     - fixed the memory leak of fHSigmabarMax
+     - replaced TRandom by gRandom
+     - removed usage of ->operator
+
+   * manalysis/MApplyPadding.[h,cc]:
+     - replaced fRnd by gRandom
+     - used MH::SetBinning
+     - use telescope theta instead of theta
+     - removed usage of ->operator
+     - removed PostProcess
+     
+   * manalysis/MPadSchweizer.cc:
+     - fixed outputs in PreProcess
+
+   * manalysis/MSigmabar.[h,cc]:
+     - added Reset member function
+     - usage of memset
+     - don't skip NumPhotons==0 
+     - changes discussed with Robert
+     - small simplifications in loops
+     - some fixes to the output
+
+   * manalysis/MSigmabarCalc.[h,cc]:
+     - fixed outputs
+     - some small simplifications
+     - moved test for theta<120deg to MCT1ReadPreProc
+
+   * mfileio/MCT1ReadPreProc.[h,cc]:
+     - skip events with theta>90deg
+
+   * mhist/MHSigmaPixel.[h,cc]:
+     - fixes to the screen output
+     - simplified usage of MBinning
+
+   * mhist/MHSigmaTheta.[h,cc]:
+     - fixes to the screen output
+     - simplified usage of MBinning
+     - lower cased upper case local variables   
+     - removed DrawClone from Finalize (call from macro or executable)
+
+   * mhist/MHSigmabarTheta.[h,cc]:
+     - fixes to the screen output
+     
+   * mhist/MHStarMap.cc:
+     - added some const qualifiers
+
+   * mhist/MHHadronnes.cc:
+     - removed output of function name in Finalize because this
+       information is already available on the screen.
+
+   * manalysis/MCT1PointingCorrCalc.h:
+     - changed ClassDef to 0
+     - removed empty PostProcess
+     - fixes to the screen output in PreProcess
+     - changed the order of the arguments in the constructor
+       (name, title to the end)
+
+   * manalysis/MMultiDimDistCalc.cc:
+     - added two const qualifiers
+     
+   * mtemp/MObservatory.cc:
+     - changed Magic1 coordinates to CT1 GPS.
+
+
+
+ 2003/04/12: Wolfgang Wittek
+
+   * manalysis/MCT1PointingCorrCalc.[h,cc]
+     - replaces MPointingCorr.[h,cc]
+
+   * manalysis/AnalysisLinkDef.h
+               Makefile
+
+   * mbase/MFilter.h
+     - set ClassDef(MFilter,1)
+
+   * mhist/MHHadronness.[h,cc]
+     - improve warning printout
+
+   * mhist/MHMatrix.[h,cc]
+     - type of 3rd argument of member function Fill
+       changed from 'MF' to 'MFilter'
+
+
+
+ 2003/04/11: Thomas Bretz
+
+   * macros/readMagic.C:
+     - replaced GetEventNum by GetNumEntry
+     
+   * manalysis/MCT1SupercutsCalc.cc:
+     - fixed constructor (no default for fHadronnessName)
+     - missing fHadronness->SetReadyToSave added
+     
+   * manalysis/MMultiDimDistCalc.cc:
+     - missing fHadronness->SetReadyToSave added
+    
+   * manalysis/MParameters.cc:
+     - changed title
+
+   * mfilter/MFCT1SelFinal.h:
+     - set ClassDef to 0
+   
+   * mimage/Makefile:
+     - fixed a typo
+     
+   * mraw/MRawEvtData.cc:
+     - fixed Pixel assignment (i->ipos, fPosInArray++)
+
+
+
+ 2003/04/10: Thomas Bretz                 
+ 
+   * mbase/MContinue.[h,cc]:
+     - changed, so that also a filter given as a pointer is added to
+       the tasklist automatically
+     - added SetInverted
+     - added IsInverted
+ 
+   * mbase/MTaskList.[h,cc]:
+     - added RemoveFromList-function
+
+   * merpp.cc:
+     - fixed typo
+     
+   * mbase/MFilter.[h,cc]:
+     - removed unnecessary base functions for Pre//PostProcess
+     - added SetInverted
+     - added IsInverted
+   
+   * mbase/MTask.cc, mfileio/MCT1ReadPreProc.cc, mfileio/MReadTree.cc,
+     mfilter/MF.cc, mfilter/MFilterList.cc
+     - implemented IsConditionalTrue to support inverted filters
+
+   * mhist/MHHadronness.cc:
+     - removed unnecessary check
+
+   * meventdisp/MGFadcDisp.cc:
+     - remove all IDs in listbox
+     - add entries sorted
+
+   * manalysis/MImgCleanStd.[h,cc], manalysis/MCameraSmooth.[h,cc], 
+     manalysis/MHillas.[h,cc], manalysis/MHillasSrc.[h,cc],
+     manalysis/MHillasSrc.[h,cc], manalysis/MHillasCalc.[h,cc],
+     manalysis/MNewImagePar.[h,cc], manalysis/MNewImageParCalc.[h,cc],
+     mhist/MHHillas.[h,cc], mhist/MHHillasSrc.[h,cc], 
+     mhist/MHHillasExt.[h,cc], mhist/MHNewImagePar.[h,cc]:
+     - moved to new directory mimage
+   
+   * mimage/Makefile, mimage/ImageLinkDef.h, mimage/ImageIncl.h:
+     - new
+   
+   * Makefile:
+     - added mimage
+   
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile
+     mhist/HistLinkDef.h, mhist/Makefile:
+     - removed moved files
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h,
+     mhist/Makefile, mhist/AnalysisLinkDef.h, mmain/Makefile,
+     mfilter/Makefile, meventdisp/Makefile, mgui/Makefile:
+     - adapted
+
+
+
+ 2003/04/09: Thomas Bretz
+ 
+   * manalysis/MCT1SupercutsCalc.[h,cc]:
+     - moved last changes from MFCT1Supercuts to MCT1SupercutsCalc
+
+   * mhist/MHMcTriggerLvl2.[h,cc]:
+     - fixed a warning
+     - removed global variables
+
+
+
+ 2003/04/09: Abelardo Moralejo
+
+   * manalysis/MHillasSrc.cc
+     - changed comment about meaning of fCosDeltaAlpha
+
+
+
+ 2003/04/08: Thomas Hengstebeck
+ 
+   * mhist/MHRanForest.cc, mhist/MHRanForestGini.cc
+     - removed gStyle->SetOptStat(10), gStyle settings should be 
+       done by the user himself  
+
+
+
+ 2003/04/08: Abelardo Moralejo
+
+   * manalysis/MImgCleanStd.cc
+     - Fixed "democratic" cleaning: now tail cut is proportional 
+       to pixel area instead of pixel radius as (erroneously) was 
+       before.
+
+   * NEWS
+     - Changed comment on image cleaning.
+
+
+
+ 2003/04/08: Thomas Bretz
+
+   * mhist/MHHadronness.cc:
+     - no check for sump==0 and sumg==0 in loop necessary anymore
+
+   * Changelog, Changelog.02:
+     - moved everything before 1/2003 to Changelog.02
+
+
+
+ 2003/04/08: Wolfgang Wittek
+
+   * mfilter/MFCT1SelFinal.[h,cc]
+     - add new member function SetHadronnessName()
+
+   * mhist/MHHadronness.[h,cc]
+     - reset to SetOptStat(111100)
+     - correct acceptance
+
+   * manalysis/MMultiDimDistCalc.[h,cc]
+     - swap arguments in FindCreateObj
+
+
+
+ 2003/04/08: Nicola Galante and Antonio Stamerra
+
+   * mhist/MHMcTriggerLvl2.[h,cc]
+      - New class added (histograms for the MMcTriggerLvl2 class)
+
+   * mhist/Makefile
+     - Added MHMcTrigggerLvl2 in SRCFILES
+
+   * manalysis/Makefile
+     - Reintroduced MMcTriggerLvl2 and MMcTriggerLvl2Calc 
+       (they were removed!!)
+
+   * manalysis/MMcTriggerLvl2.h
+     - 'const' added in inline functions Get****
+
+   * manalysis/MMcTriggerLvl2Calc.cc
+     - added call to Fill method of MHMcTriggerLvl2
+
+   * macros/triglvl2.C
+     - updated to have histograms with MHMcTriggerLvl2
+
+   * macros/dohtml.C
+     - added triglvl2.C
+
+   * NEWS
+     - new comment on L2T selection classes
+
+ 2003/04/08: Wolfgang Wittek
+
+   * mfilter/Makefile
+             FilterLinkDef.h
+     - MFCT1Supercuts removed
+
+   * manalysis/MMultiDimDistCalc.h
+     - set ClassDef(MMultiDimDistCalc,1)
+
+   * manalysis/MCT1SupercutsCalc.[h,cc]
+     - new; replaces MFCT1Supercuts in mfilter
+
+   * manalysis/Makefile
+               AnalysisLinkDef.h
+
+
+
+ 2003/04/07: Thomas Bretz
+
+   * Makefile:
+     - changed order
+     
+   * manalysis/MMultiDimDistCalc.[h,cc]:
+     - fixed default title
+     - simplified code
+     - added fHadronnessName
+
+   * manalysis/MRanForestCalc.[h,cc]:
+     - added fHadronnessName
+   
+   * mbase/MAGIC.h:
+     - fixed a bug with rootcint
+     
+   * meventdisp/MGFadcDisp.cc:
+     - fixed a variable name
+
+   * mhist/MHHadronness.cc:
+     - removed many old comments
+     - simplified some code
+     - uses argument in Fill now
+
+   * mmain/MMonteCarlo.cc:
+     - some code simplification
+     - fixed a warning 
+
+   * macros/dohtml.C:
+     - added testenv.C
+
+   * readraw.cc:
+     - simplified
+   
+   * mraw/MRawEvtData.cc:
+     - fixed a bug in the draw function (the drawn pixel has not been the
+       one with the given Id, but simply the i-th entry in the array)
+
+   * mfilter/MFCT1Supercuts.[h,cc]:
+     - changed naming style of variables
+     - changes array access
+
+   * mhist/MHFadcCam.[h,cc]:
+     - added HasHi
+     - added Exists
+
+   * mmain/MDataCheck.cc:
+     - removed unimplemented buttons
+
+   * mdatacheck/MGDisplayAdc.[h,cc]:
+     - tried to implement some unimplemented buttons
+     - don't display non existing (empty) histograms in list
+
+
+
+ 2003/04/04: Thomas Bretz
+
+   * mtools/MagicReversi.[h,cc]:
+     - added support for Number of Players
+     - added instructions
+     - added support for Esc key
+
+   * mbase/MAGIC.h:
+     - added version check to MAGIC.h
+
+
+
+ 2003/04/04: Wolfgang Wittek
+
+   * mfilter/Makefile
+            /FilterLinkDef.h
+     - added MFCT1SelBasic, MFCT1SelStandard, MFCT1SelFinal,
+             MFCT1Supercuts
+
+   * mfilter/MFCT1SelBasic.[h,cc]
+            /MFCT1SelStandard.[h,cc]
+            /MFCT1SelFinal.[h,cc]
+     - new; they replace manalysis/MSelBasic.[h,cc]
+                                  /MSelStandard.[h,cc]
+                                  /MSelFinal.[h,cc]
+ 
+   * mfilter/MFCT1Supercuts.[h,cc]
+     - new (supercuts from Daniel for CT1 Mkn421 2001 data)
+
+   * manalysis/MSelBasic.[h,cc]
+              /MSelStandard.[h,cc]
+              /MSelFinal.[h,cc]
+     - deleted
+
+   * manalysis/Makefile
+               AnalysisLinkDef.h
+     - MSelBasic, MSelStandard, MSelFinal removed
+
+   * mfileio/MCT1ReadPreProc.[h,cc]
+     - smeare theta only for MC events
+
+   // The following is not yet commited !!!!!!!!!!!!!
+   * Mars/Makefile
+     - in SUBDIRS put mfilter before manalysis
+       (otherwise get link error)
+
+
+
+ 2003/04/03: Abelardo Moralejo
+
+   * mmontecarlo/MMcTriggerRateCalc.cc:
+     - added #include <math.h> for compilation on alpha (otherwise 
+       floor() is unkown)
+
+
+
+ 2003/04/03: Thomas Bretz
+
+   * macros/testenv.C:
+     - added
+
+   * mbase/MEvtLopp.cc, mbase/MParContainer.[h,cc], 
+     mbase/MParList.cc, mbase/MTaskList.cc:
+     - changed the stuff for reading steering card - didn't really
+       work like expected
+
+   * mhist/MHMatrix.cc, mfileio/MRead.cc, manalysis/MImgCleanStd.cc:
+     - adapted ReadEnv
+
+   * mhist/MHMatrix.[h,cc]:
+     - added ReadEnv
+     
+   * mfileio/MCT1ReadPreProc.[h,cc]:
+     - base SmearTheta on new FindLoEndge
+     - simplified
+   
+   * mhist/MBinning.h:
+     - added FindBinLoEdge
+     - added FindBinHiEdge
+
+   * mdata/MDataArray.[h,cc]:
+     - added Clear
+     - added Delete
+
+   * mbase/MEvtLoop.cc:
+     - added output of the name
+   
+   * mbase/MLog.[h,cc]:
+     - don't use any pthread stuff if _REENTRANT is not defined
+   
+   * mfileio/MRead.cc, mhist/MHMatrix.cc:
+     - fixed waring for unreachable statement
+   
+   * mhist/MHArray.cc:
+     - fixed: redifinition of default argument
+     
+
+
+
+ 2003/04/02: Abelardo Moralejo
+
+   * mmc/MMcTrigHeader.hxx
+     - added threshold>0 check in the calculation of 
+       GetMeanThreshold
+
+   * mmontecarlo/MMcTriggerRateCalc.cc
+     - The check of the MC spectral index value is now done by 
+       comparing integers instead of real numbers.
+     - Found out with GREAT surprise that the graphical output
+       has been completely commented out by someone(?) because it 
+       produced a memory leak. Also the function comment did not 
+       match the rules (my fault; is it correct now?) This commenting 
+       out has not been logged to this file, as far as I can see. This
+       is rather unkind, I thought that when somebody finds some bug or
+       messy code, he should either correct and commit it (and log the 
+       change here) and/or inform the author of the mistake to correct 
+       it. Please try to do so in the future instead of simply 
+       commenting out useful code!
+
+   * mdata/MDataValue.h
+     - added default constructor (otherwise, no constant values 
+       can be used in the parameters used in the random forest 
+       separation)
+
+
+
+
+ 2003/04/02: Wolfgang Wittek
+
+   * mfileio/Makefile
+     - mhist added, because MBinning is used in MCT1ReadPreproc
+
+   * mfileio/MCT1ReadPreProc.[h,cc]
+     - new member function SmearTheta
+     - store smeared  Theta in MMcEvt::fTelescopeTheta
+       store original Theta in MParameterD container "ThetaOrig"
+       store fhourangle     in MParameterD container "HourAngle"
+
+   * manalysis/MPointingCorr.[h,cc]
+     - get hour angle from ParameterD container "HourAngle"
+
+   * manalysis/MSelBasic.[h,cc]
+               MSelStandard.[h,cc]
+               MSelFinal.[h,cc]
+     - new member functions SetCuts()
+
+
+
+ 2003/04/01: Abelardo Moralejo
+
+   * macros/CT1EnergyEst.C
+     - added argument (maximum dist parameter), changed (reduced) output 
+       histograms, added writing to (and reading from) a file the energy 
+       estimation parameters and the histograms. Added comments.
+
+   * manalysis/MEnergyEstParam.[h,cc]
+     - added member function GetCoeff. Changed comment.
+
+
+
+ 2003/03/31: Thomas Bretz
+
+   * manalysis/MParameters.[h,cc]:
+     - added
+
+   * manalysis/AnalysisLinkDef.h, manalysis/Makefile:
+     - added MParameters, MParameterD, MParameterI
+
+   * mhist/MHArray.[h,cc]:
+     - added default constructor
+     - added Set-function
+     - added Init function
+     - moved code from constructors to Set and Init
+ 
+   * Makefile.conf.linux:
+     - removed -fno-rtti to make it compatible with root 3.04.02
+   
+   * NEWS:
+     - changed
+   
+   * manalysis/MImgCleanStd.[h,cc]:
+     - added SetLvl1
+     - added SetLvl2
+     - added ReadEnv
+   
+   * manalysis/MNewImagePar.[h,cc]:
+     - removed unnecessary fHillas data member
+     - removed unnecessary fSrcPos data member
+     - removed unnecessary Set/GetSrcPos 
+   
+   * manalysis/MNewImageParCalc.[h,cc]:
+     - removed unnecessary SetSrcPos 
+     - removed const-qualifier from fGeomCam, fCerPhotEvt
+       (trouble with root 3.02/06)
+   
+   * manalysis/MRanForest.cc:
+     - changed cout-output
+     
+   * manalysis/MSigmabar.cc:
+     - changed Area to area (local variable)
+
+   * mbase/MEvtLoop.[h,cc]:
+     - added evtloop name to constructor (default=Evtloop)
+     - adapted StreamPrimitive
+     - added ReadEnv
+     - added WriteEnv
+     
+   * mbase/MParContainer.[h,cc]:
+     - removed TROOT.h
+     - fixed const-qualifier for Copy-function for root>3.04.01
+     - added ReadEnv
+     - added WriteEnv
+     - added IsEnvDefined
+     - added GetEnvValue
+     
+   * mbase/MParList.[h,cc], mbase/MTaskList.[h,cc]:
+     - added ReadEnv
+     - added WriteEnv
+   
+   * mfileio/MCT1ReadAscii.[h,cc], mfileio/MCT1ReadPreProc.[h,cc]:
+     - changed AddFile declaration to declaration in MRead
+     - added return value to AddFile
+     
+   * mfileio/MRead.[h,cc]:
+     - added template for AddFile
+     - added ReadEnv
+     
+   * mgui/MHexagon.[h,cc]:
+     - fixed const-qualifier for Copy-function for root>3.04.01
+   
+   * mhist/MH.cc:
+     - fixed the FindGoodLimit stuff for root> 3.04.01
+     
+   * mhist/MHRanForest.[h,cc], mhist/MHRanForestGini.[h,cc]:
+     - removed unnecessary casts
+     - fixed a copilation error with root 3.04.01 (kFullDotlarge 
+       doesn't exist)
+     - removed second Draw (one should not add something twice to 
+       the pad)
+       
+   * mmontecarlo/MMcTriggerRateCalc.cc:
+     - changes to the header
+     - changes to the fLog stuff
+     - added a cast to get rid of a warning
+     
+   * mtools/Makefile, mtools/ToolsLinkDef.h:
+     - added MagicReversi
+   
+   * mtools/MagicRevers.[h,cc]:
+     - added
+
+
+
+ 2003/03/28: Thomas Bretz
+
+   * mbase/MParContainer.h:
+     - added kEnableGraphicalOutput
+     - added EnableGraphicalOutput
+     - added IsGraphicalOutputEnabled
+   
+   * mbase/MParList.h:
+     - changed BIT(15) to BIT(17)
+   
+   * mhist/MH.[h,cc]:
+     - SetBinning(TH1*, TH1*) --> SetBinning(TH1*, const TH1*)
+   
+   * mhist/MH3.h:
+     - changed BIT(15) to BIT(17)
+     - changed BIT(16) to BIT(18)
+     - changed BIT(17) to BIT(19)
+
+   * mhist/MHMatrix.[h,cc]:
+     - added DrawDefRefInfo
+     - added CopyCrop
+     - added GetRandomArrayI
+     - changed DefRefMatrix to support the above
+     - fixed a bug in DefRefMatrix (evtcount2 in the last loop
+       instead of evtcount1)
+     - Don't do anything in the finalization if the matrix has the correct
+       dimensions
+     - fixed comment of DefRefMatrix
+     - changed number of first column from 1 to 0
+     - changed BIT(16) to BIT(17)
+
+
+
+ 2003/03/28: Wolfgang Wittek
+
+    * mhist/MHMatrix.cc
+      - DefRefMatrix: if nmaxevts>fM.GetNrows() set 
+        nmaxevts = fM.GetNrows()
+
+    * manalysis/MSelBasic.[h,cc]
+      - better output
+
+    * manalysis/MSelStandard.[h,cc]
+      - different cut in DIST
+
+    * mfileio/MCT1ReadPreProc.[h,cc]
+      - store hour angle in variable fOtherCphFraction
+
+    * manalysis/MHillasSrcCalc.h
+      - replace in 'SetInput'         fHillasName  = hilname;
+                    by                fHillasInput = hilname;        
+
+    * manalysis/MNewImagePar.[h,cc]
+               /MNewImageParCalc.[h,cc]
+      - new; calculates new image parameters
+
+    * mhist/MHNewImagePar.[h,cc]
+      - new; plots new image parameters              
+
+    * manalysis/AnalysisLinkDef.h
+      manalysis/Makefile
+
+    * mhist/HistLinkDef.h
+      mhist/Makefile
+
+
+
+ 2003/03/27: Thomas Hengstebeck
+
+    * manalysis/MRanForest.[h,cc]
+      - allocation of TObjArray fForest moved to constructor.
+      - use of gRandom 
+
+    * manalysis/MRanTree.[h,cc]
+      - use of gRandom
+    
+    * macros/RanForest.C
+      - gRandom initialized as TRandom3 object.
+ 
+
+
+ 2003/03/25: Abelardo Moralejo
+
+    * macros/mergecamera.C
+      - added warning to prevent dangerous misuse of this macro.
+
+
+
+ 2003/03/25: Wolfgang Wittek
+
+    * mhist/MHStarMap.[h,cc]
+      - use constant step size along the main axis of the ellipse
+
+    * manalysis/MPointingCorr.[h,cc]
+      - new class for calculating the pointing correction
+
+    * mmc/MMcEvt.hxx
+      - add GetOtherCphFraction()
+
+    * manalysis/Makefile
+
+    * manalysis/AnalysisLinkDef.h
+
+
+
+ 2003/03/24: Abelardo Moralejo
+
+    * manalysis/MEnergyEstParam.cc
+      - now energy estimation (for CT1) is done using the same model 
+	as in D.Krannich's thesis.
+
+
+
+ 2003/03/24: Thomas Bretz
+
+    * manalysis/MHillasSrcCalc.[h,cc]:
+      - removed last argument in constructor, replaced by SetInput
+
+    * mfilter/MFEventSelector.[h,cc]:
+      - removed unnecessary last argument
+
+
+
+ 2003/03/21: Thomas Hengstebeck
+ 
+    * manalysis/MRanTree.[h,cc]
+      - new; parameter container to store a single random tree
+
+    * manalysis/MRanForest.[h,cc]
+      - new; parameter container to store complete forest
+
+    * manalysis/MRanForestGrow.[h,cc]
+      - new; task to grow trees (training)
+
+    * manalysis/MRanForestCalc.[h,cc]
+      - new; task to calculate hadronness using random forest
+
+    * manalysis/MRanForestFill.[h,cc]
+      - new; task to read in the trees of the random forest
+
+    * manalysis/Makefile, manalysis/HistLinkDef.h:
+      - added MRanTree, MRanForest, MRanForestGrow, MRanForestCalc, 
+        MRanForestFill
+
+    * mhist/MHRanForest.[h,cc]
+      - new; histogram showing variance of estimated hadronness as 
+        function of no. of combined trees 
+
+    * mhist/MHRanForestGini.[h,cc]
+      - new; histogram showing mean decrease in Gini-index as function 
+        of RF-input-parameters
+
+    * mhist/Makefile, mhist/HistLinkDef.h:
+      - added MHRanForest, MHRanForestHillas
+
+    * macros/RanForest.C
+      - new; g/h-separation by Random Forest-method
+
+    * macros/RanForest2.C
+      - new; reading in saved random forest (using MRanForestFill)
+
+
+
+ 2003/03/21: Abelardo Moralejo
+
+    * mhist/MHMatrix.[h,cc]:
+      - Added third argument (a filter) to the second instantiation 
+	of the Fill procedure.
+
+    * macros/CT1EnergyEst.C:
+      - Example of the parameter calculation and use of the energy 
+	estimation method for CT1.
+
+
+
+ 2003/03/21: Thomas Bretz
+
+    * manalysis/MEnergyEstParam.[h,cc]
+      - Added StopMapping and Print functions.
+
+    * manalysis/MSel*.h:
+      -	set default for HilName to MHillas
+      -	set default for HilNameSrc to MHillasSrc
+
+    * mfileio/MCT1ReadPreProc.[h,cc]:
+      - do not flood the output with all events from the first run
+      - output meaningfull text instead of variable names
+      - removed a 'goto'!
+      - changed savePedRMS according to the coding conventions to
+        fPedRMS and the array of fixed size to a TArrayF
+    
+    * mbase/MEvtLoop.cc:
+      - added a events counter which counts the real number of 
+        processed events.
+
+    * mdata/MDataChain.[h,cc]:
+      - implemented random numbers
+      - implemented a conversion from degrees to radians and vice versa
+
+
+
+ 2003/03/20: Thomas Bretz
+
+    * mfilter/MF.[h,cc]:
+      -	changed fFilter (already used in base class MTask) to fF
+
+
+
+ 2003/03/19: Abelardo Moralejo
+
+    * macros/CT1collarea.C:
+      -	Added filter to cut in hadronness (now available in new version
+        of root CT1 Monte Carlo file from Wolfgang).
+
+
+
+ 2003/03/19: Robert Wagner
+
+    * mhist/MH3.cc:
+      - changed MH3::New() such that constructor according to Thomas'
+        previous changes is supported
+
+
+
+ 2003/03/19: Thomas Bretz
+
+    * mhist/MH3.[h,cc]:
+      - changed default constructor to support different dimensions
+
+    * mhist/MHArray.[h,cc]:
+      - added AddHistogram
+
+    * meventdisp/MGEvtDisplay.cc, mfileio/MReadTree.[h,cc],
+      meventdisp/MReadMarsFile.cc:
+      - changed MReadTree::GetEventNum to MReadTree::GetNumEntry
+
+    * macros/estfit.C:
+      - adopted to new MChisqEval
+
+    * mtools/MChisqEval.[h,cc]:
+      - added
+
+    * mtools/Makefile, mtools/ToolsLinkDef.h:
+      - added MChisqEval
+
+    * manalysis/MEnergyEstParam.[h,cc]:
+      - slight changes
+    
+    * mfileio/MCT1ReadPreProc.cc:
+      - changed name to MRead
+
+
+
+ 2003/03/18: Thomas Bretz
+
+    * mfileio/MReadTree.cc:
+      - fixed a bug in the AddFile function
+
+    * mhist/MHMatrix.[h,cc]:
+      - implemented a request of Th. Hengstebeck: Let DefRefMatrix
+        return the 'unused' events
+
+
+
+ 2003/03/18: Abelardo Moralejo
+
+    * mhist/MHMcCT1CollectionArea.[h,cc]
+      - Added arguments in constructor: number of bins and ranges of the 
+	x-axis (energy) of the 2-d histograms. Changed type of binning:
+	now the x-axis is log10(energy) and bins have equal width.
+
+    * macros/CT1collarea.C
+      - The MHMcCT1CollectionArea object is now created and added to the 
+       	parlist so that  we can choose the binning. Changed the way 
+       	histograms are written to the output file.
+
+
+
+ 2003/03/13: Abelardo moralejo
+
+    * mhist/MHMcCT1CollectionArea.[h,cc]
+      - Added for calculations of collection area for CT1.Contains three
+        2-d histograms with axis energy vs theta angle: one histogram for
+        all events, one for analyzed events, one for the collection area.
+
+    * mmontecarlo/MMcCT1CollectionAreaCalc.[h,cc]
+      - Added for the same reason. 
+
+    * macros/CT1collarea.C
+      - Uses the above classes
+
+
+
+ 2003/03/12: Abelardo Moralejo
+
+    * macros/mergecamera.C
+      - Added. Merges several MC camera output files into a single file.
+
+
+
+ 2003/03/08: Wolfgang Wittek
+
+    * macros/AnalyseCT1.C
+      - for the CT1 data analysis
+
+    * mhist/MHMatrix.[h,cc]
+      - let refcolumn start at 1 (not at 0)
+
+    * mhist/MHSigmaTheta.[h,cc]
+      - Draw replaced by DrawCopy
+      - add SetDirectory(NULL)
+
+    * manalysis/MSelBasic.[h,cc]
+                MSelStandard.[h,cc]
+                MSelFinal.[h,cc]
+      - more detailed output for errors
+      - bugs removed
+      
+    * manalysis/MPadSchweizer.[h,cc]
+      - add SetDirectory(NULL)
+      - add fErrors
+
+    * mfilter/MFEventSelector.[h,cc]
+      - add fErrors
+
+    * manalysis/MMultiDimDistCalc.[h,cc]
+      - check division by zero
+
+    * mhist/MHHadronness.[h,cc]
+      - check division by zero
+      - normalize distributions of hadronness
+
+    * mfileio/MCT1ReadPreProc.[h,cc]
+      - add event number (event.isecs_since_midday)
+      - change definition of "fIsMcFile", 
+        because outpars.bmontecarlo is set wrongly sometimes
+      - copy pedestalRMS for each event from the header information
+      - check for the presence of a footer record even after reading 
+        a run header
+
+    * mmc/MMcEvt.[hxx,cxx]:
+      - add GetEvtNumber()
+
+
+
+ 2003/02/27: Abelardo Moralejo
+
+    * mmontecarlo/MMcTriggerRateCalc.cc:
+      - Fixed: MMCTrigHeader could not be found in the case of camera
+	files containing single trigger condition.
+
+    * macros/trigrate.C
+      - no plot is made in the case of single trigger condition.
+
+    * mhist/MHMcRate.[h,cc]
+      - Added member fTriggerCondNum to keep track of what trigger
+        condition corresponds to each MHMcRate object, for the case of
+        files with more	than one condition (when running camera in 
+        trigger_loop mode). Added also Set and Get procedures for nre 
+        member.
+
+    * mmain/MMonteCarlo.cc
+      - Fixed bug: matrix BgR was created with dimension "dim", a number
+        which can be negative. Put "num" instead of "dim".
+
+
+
+ 2003/02/25: Thomas Bretz
+
+    * mbase/MParContainer.cc:
+      - small simplification for Cosy
+    
+    * mbase/MLog.cc:
+      - allow a maximum of 1000 lines in the gui
+
+
+
+ 2003/02/25: Abelardo Moralejo
+
+    * mmontecarlo/MMcTriggerRateCalc.[h,cc]
+      - Added axis labels in graphic output
+      - Added Get function for rate histograms
+
+    * macros/trigrate.C
+      - Added output file with rate histograms
+
+
+
+ 2003/02/24: Abelardo Moralejo
+
+    * mmontecarlo/MMcTriggerRateCalc.[h,cc]
+      - Fixed mistake when analysing camera files containing all
+        events (including non-triggers): fShowers was always zero.
+      - Added reading of MMcTrigHeaders in ReInit
+      - Added procedure Draw for graphics output: rate versus
+        discriminator threshold (useful for camera files with several
+        trigger conditions).
+
+    * macros/trigrate.C
+      - Added some explanations. Style improvements in function
+        GetNSBEvents. Added call to MMcTriggerRateCalc::Draw
+
+    * mhist/MHMcRate.[h,cc]
+      - Added GetTriggerRate() and GetTriggerRateError()
+      - Added members fMultiplicity and fMeanThreshold, with their
+        corresponding Set and Get functions
+      - Added info on discriminator threshold and L1 trigger
+        multiplicity on the printout.
+
+    * mmc/MMcTrigHeader.hxx
+      - Added GetMultiplicity() and GetMeanThreshold()
+
+
+ 2003/02/22: Wolfgang Wittek
+
+    * mhist/Makefile
+      - MHSigmaTheta added
+
+    * mhist/HistLinkDef.h
+      - MHSigmaTheta added
+
+    * mhist/MHSigmaTheta.[h,cc]
+      - type inconsistency removed
+
+
+
+ 2003/02/21: Abelardo Moralejo
+
+    * mmontecarlo/MMcTriggerRateCalc.[h,cc]
+      - adapted to new camera files, added warnings.
+      - added ReInit procedure to read relevant info from from the
+        run headers
+
+    * mhist/MHMcRate.[h,cc]
+      - adapted accordingly. Added Set functions for several members.
+
+    * mmc/MMcCorsikaRunHeader.h
+      - added Get functions for fELowLim, fEUppLim and fSlopeSpec.
+
+    * mmain/MMontecarlo.cc, macros/trigrate.C
+      - adapted to changes above, changed MReadTree to MReadMarsFile to
+	be able to read the run headers.
+
+
+
+ 2003/02/21: Antonio Stamerra 
+
+    * manalysis/MMcTriggerLvl2.[cc|h]
+      - new data member fCompactNN needed to define a compact pixels
+      - new inline functions SetCompactNN and GetCompactNN 
+      - Method Calc(int neighpix) -> Calc(). The value of neighpix
+	is read from fCompactNN
+
+    * manalysis/MMcTriggerLvl2Calc.[cc|h]
+      - Check on fCompactNN added in the PreProcess
+
+    * macros/triglvl2.C
+      - Set of fCompactNN added
+
+
+
+ 2003/02/21: Wolfgang Wittek
+
+    * manalysis/MSelFinal.[h,cc]
+      - 'const' removed from pointers
+
+    * macros/AnalyseCT1.C
+      - macro for the CT1 analysis (work in progress)
+
+
+
+ 2003/02/20: Wolfgang Wittek
+
+    * manalysis/Makefile
+      - add MSelFinal
+
+    * manalysis/AnalysisLinkDef.h
+      - add MSelFinal
+
+    * manalysis/MPadSchweizer.[h,cc]
+      - slight modification of padding procedure
+
+    * manalysis/MSigmabarCalc.[h,cc]
+      - 'const' removed from pointers
+
+    * mhist/MHMatrix.[h,cc]
+
+    * mhist/MHSigmaTheta.[h,cc]
+
+
+
+ 2003/02/20: Abelardo Moralejo
+
+    * mhist/MH.cc
+      - Removed call to TGaxis::Optimize for compilation under root 
+        versions > 3.03, since in them this procedure is no longer 
+        existing. I did this to allow compilation under root_3.04,
+        since earlier versions has a bug which prevents from
+        plotting in the simple way some variables in a tree
+        (example: fConc and others in the output  of star.C). This
+        is a temporal fix, I guess something will have to
+	substitute the call to Optimize...
+
+
+
+ 2003/02/20: Antonio Stamerra 
+
+    * manalysis/MMcTriggerLvl2.[cc|h]
+      - new; replaces MTrigLvl2.[cc|h]
+      - new data members: fLutPseudoSize, fPseudoSize.
+      - functions renamed:
+			GetLutPseudoSize -> CalcBiggerLutPseudoSize
+			GetBiggerFiredCell -> CalcBiggerFiredCell
+      - new inline functions: GetLutPseudoSize(), GetPseudoSize().	
+      - new member functions: 
+		Calc(); CalcPseudoSize (not yet implemented)
+      - Redefined Print() function as a TObject.
+      - pixels_in_cell and pixels_in_lut redefined as static data 
+        members
+
+    * manalysis/MMcTriggerLvl2Calc.[cc|h]
+      - new; replaces MTrigLvl2FillTask.[cc|h]
+      - creation and filling of histograms commented
+      - Process() calls the MMcTriggerLvl2::Calc()           
+ 
+    * mfilter/MFTriggerLvl2.[h|cc]
+      - new class to select events using MMcTriggerLvl2 data members.
+
+    * macros/triglvl2.C
+      - added example to use the MFTriggerLvl2 filter.
+
+
+
+ 2003/02/19: Wolfgang Wittek
+
+    * manalysis/MSelBasic.[h,cc]
+      - new; evaluates the Basic Cuts (after the calibration) 
+
+    * manalysis/MSelStandard.[h,cc]
+      - new; evaluates the Standard Cuts 
+        (after the calculation of the image parameters and before the 
+         calculation of the hadronness)
+
+    * manalysis/MHillasCalc.[h,cc]
+      - replace
+              fHillas = (MHillas*)pList->FindCreateObj(fHilName);
+        by          
+              fHillas = (MHillas*)pList->FindCreateObj("MHillas",
+                                                       fHilName);
+        in order to allow MHillas containers with a name 
+                                  different from "MHillas"
+
+    * mhist/MHHillasExt.[h,cc]
+      - replace
+               TObject *obj = plist->FindObject("MHillas");
+        by          
+               TObject *obj = plist->FindObject(fHilName, "MHillas");
+        in order to allow MHillas containers with a name 
+                                  different from "MHillas"
+      - add a 3rd argument in the constructor : fHilName
+
+    * manalysis/MHillasSrcCalc.[h,cc]
+      - add new argument for constructor:
+                the name of the MHillas input container
+        in order to allow MHillas input containers with a name
+                                  different from "MHillas"     
+
+    * mhist/MHMatrix.[h,cc]
+      - add member function DefRefMatrix();
+        it defines the reference sample for the g/h separation;
+        the selection of events for the reference sample can be made
+        such that the distribution of a certain variable (for example
+        Theta) agrees with a target distribution.
+
+    * mfilter/MFEventSelector.[h,cc]
+      - add new argument for constructor:
+                the name of the read object
+        in order to allow also read objects which have a name
+        different from
+           "MRead"        
+
+
+
+ 2003/02/18: Thomas Bretz
+ 
+    * mfileio/MReadTree.cc:
+      - added a fix for a bug in the workaround using wildcards
+
+
+
+ 2003/02/14: Thomas Bretz
+ 
+    * mtemp/MObservatory.[h,cc]:
+      - added
+
+
+
+ 2003/02/10: Abelardo Moralejo
+
+    * Makefile.conf.osf1
+      - Added -lpthread to compilation flags (otherwise linking fails
+        in alfa)
+
+    * manalysis/Makefile, AnalysisLinkDef.h
+      - Changed MApplyPadding for MPadding
+
+
+
+ 2003/02/07: Wolfgang Wittek
+
+    * mhist/MHSigmaTheta.[h,cc]
+      - new; 2D distribution : Theta, Sigmabar
+             3D distribution : Theta, pixel number, Sigma
+             3D distribution : Theta, pixel number, Sigma^2-Sigmabar^2
+        these histograms may be used for the padding
+
+    * manalysis/MPadding.[h,cc]
+      - new; replaces MApplyPadding.[h,cc] 
+             some errors removed               
+
+    * manalysis/MSigmabar.[h,cc]
+      - new definition of Sigmabar (only relevant for MAGIC) 
+      - add in member function 'Calc' a 3rd argument : 'const
+        MCerPhotEvt &evt'
+      - calculate sigmabar for 'MCerPhotEvt' pixels
+      - in member function 'Calc' return Float_t fSigmabar instead of
+        Bool_t
+      - copies of objects replaced by references
+
+    * manalysis/MSigmabarCalc.[h,cc]
+      - fSig->Calc(*fCam, *fPed)         replaced by
+        fSig->Calc(*fCam, *fPed, *fEvt)
+      - change type of result of fSig->Calc from Bool_t to Float_t
+
+    * mfileio/MCT1ReadPreProc.cc
+      - add in member function PreProcess() the initialization of the
+        total number of pixels :
+                               fPedest->InitSize(iMAXNUMPIX);
+      - remove statements that cannot be reached ('break' after 
+        'return')
+
+    * manalysis/MPadSchweizer.[h,cc]
+      - alternative to MPadding
+      - does the padding ala Thomas Schweizer 
+
+
+
+ 2003/02/06: Thomas Bretz
+
+    * mgeom/MGeomCam.[h,cc]:
+      - fixed a warning (GetPixRatio(int) --> GetPixRatio(Uint)
+
+
+
+ 2003/02/07: Antonio Stamerra 
+
+    * manalysis/MTrigLvl2.[cc|h]
+      - added new function 
+	MTrigLvl2::GetLutCompactPixel(int cell, int lut, int 
+        neighpix=2) which calculates the number of compact pixel
+        in one lut 
+      - added new function GetLutPseudoSize(int neighpix=2) which
+        calculates the lut-pseudosize 
+      - added static data member pixel_in_lut
+      - merging of the PrintCell and PrintStatus functions in a single 
+	Print(int cell) function	
+      - Added comments using the standard layout
+      - some small changes following Thomas comments (memset, *fLog) 	
+
+
+
+ 2003/02/06: Thomas Bretz
+
+    * mbase/MLog.[h,cc]:
+      - serialized the GUI output (problems with mutithreded prgs,
+        eg Cosy)
+
+    * mtemp/MObservatoryLocation.[h,cc], mtemp/MVPObject.[h,cc],
+      mtemp/MVPPlotter.[h,cc]:
+      - added changes discussed in Wuerzburg
+   
+    * mfileio/MCT1ReadPreProc.cc:
+      - some simplifications
+
+
+
+ 2003/01/31: Antonio Stamerra & Marcos Lopez
+
+    * mgui/MCamDisplay.[cc|h]
+      - Added a new function MCamDisplay::SetPix(const Int_t pixnum, 
+        const Int_t color, Float_t min, Float_t max) which just set the 
+        color of a given pixel 
+
+    * created two new classes for simulating the second level trigger 
+      in the directory manalysis:
+      - MTrigLvl2.[cc|h]         // Implement the Lvl2 topology and
+                                 // selection strategies
+      - MTrigLvl2FillTask.[cc|h] // For a given MMc event, fill the
+                                 // MTrigLvl2 with the Lvl1 trigger 
+                                 // information 
+
+    * manalysis/Makefile
+      - Added -I../mgui
+
+    * Added macro macros/triglvl2.C which uses the above classes.
+
+
+
+ 2003/01/27: Robert Wagner
+
+    * mfileio/MCT1ReadPreProc.[cc|h]
+      - Added call of MTaskList::ReInit after processing of new 
+        run header
+      - Filling of MC container complies to Oscar's changes of 
+        MMcEvt.[hxx,cxx] dated 2003/01/20
+      - Added filling of run number in MRawRunHeader object while
+        processing a new run header
+
+
+
+ 2003/01/23: Robert Wagner
+
+    * manalyis/MSigmabarCalc.cc
+      - MSigmabarCalc::Process()
+        Replaced fMcEvt->GetTheta() by fMcEvt->GetTelescopeTheta()
+
+
+
+ 2003/01/20: Oscar Blanch
+  
+    * mmc/MMcEvt.[hxx,cxx]
+      - Data members: fElecCphFraction, fMuonCphFraction, 
+        fOtherCphFraction have been introduced.
+      - Class version updated to 3.
+
+    * mmc/MMcCorsikaRunHeader.[h.cc]
+      - Data members: fWobbleMode and fAtmosphericModel introduced.
+      - Class version updated to 2.
+
+
+
+ 2003/01/19: Thomas Bretz
+
+    * manalysis/MCerPhotCalc.[h,cc]:
+      - slight changes, mainly to the layout
+
+    * manalysis/MCerPhotEvt.[h,cc]:
+      - some small changes to make the code a bit faster
+
+    * manalysis/MCerPhotPix.[h,cc]:
+      - added AddNumPhotons
+
+    * mbase/MContinue.[h,cc]:
+      - changed comments
+      - enhanced functionality and fixed some small bugs
+
+    * mbase/Makefile:
+      - added mfilter to paths (to be fixed)
+
+    * mfileio/MCT1ReadPreProc.cc:
+      - Init fNumEvents = 0
+
+    * mgeom/MGeomCam.cc:
+      - return 0 Ratio if the pixel number exceeds the number of pixels
+
+   * mgui/MCamDisplay.[h,cc]:
+     - added sanity check for the maximum number of pixels
+     - added functions to set the three different palettes
+     - removed the buttons
+     - fixed the context menu display
+   
+    * mhist/HistLinkDef.h, mhist/Makefile:
+      - added MHCerPhotEvt
+
+    * mhist/MHCerPhotEvt.[h,cc]:
+      - added
+     
+    * mhist/MFillH.cc:
+      - changed the initialization of fParContainer from pList to NULL
+   
+    * mhist/MHHillasExt.cc:
+      - fixed a smallo bug when filling the histograms (crached when scaling
+        under some circumstances)
+   
+    * mhist/MHStarMap.cc:
+      - added a warning output
+
+    * mmontecarlo/MMcCollectionAreaCalc.cc:
+      - added a check for impact=NaN (some MC Files have this)
+
+
+
+ 2003/01/17: Robert Wagner
+
+    * manalysis/MApplyPadding.cc
+      - bugfix: Effective number of used pixels taken from
+        MCerPhotEvt container, not from MPedestalCam
+
+
+
+ 2003/01/16: Wolfgang Wittek
+
+    * mhist/MHMatrix.[h,cc]
+      - member function MHMatrix::Read added
+        the function calls TObject::Read(name) and SetName(name)
+
+
+
+ 2003/01/15: Wolfgang Wittek
+
+    * mdata/MDataMember.cc
+      - in MDataMember::PreProcess()
+              "if (fCall)" replaced by "if (fCall && !fObject)"
+        The additional condition "&& !fObject" is to make sure that read 
+        MDataMembers works correctly.
+
+
+
+ 2003/01/08: Oscar Blanch Bigas
+
+   * mgeom/MGeomMirror.[h,cc]
+     - Varible members to store mirror reflectivities have been
+       introduced: fReflectivity and fWavelength.
+     - Member function to set reflectivity added: SetReflectivity
+     - Member function to set TArrayF size: SetArraySize
+     - Class version number changed to 2.
Index: /tags/Mars-V0.9/Changelog.04
===================================================================
--- /tags/Mars-V0.9/Changelog.04	(revision 9772)
+++ /tags/Mars-V0.9/Changelog.04	(revision 9772)
@@ -0,0 +1,10965 @@
+ 
+Please  do  not write behind the end of line tag so that it is  possible
+to   send  a   Changelog   file  to  a  line  printer  directly.  Thanks.
+
+For your entries please follow EXACTLY this style:
+
+_yyyy/mm/dd:_[Your Name]
+_
+___*_filename:
+_____-_description
+_
+___*_filename2, filename3:
+_____-_description
+_
+_
+_
+
+While an underscore is a placeholder for a white-space or an empty line.
+
+
+                                                 -*-*- END OF LINE -*-*-
+
+
+ 2004/12/27 Thomas Bretz
+
+   * macros/CCDataCheck.C:
+     - fixed some warnings: Wrong data access operator
+
+   * manalysis/MCerPhotPix.h:
+     - added to possibility to reset the core-flag
+
+   * mcalib/MCalibColorSet.[h,cc]:
+     - moved some common code to a new function CheckAndSet for
+       simplicity of the color decoding
+     - added an include for stdlib.h (needed for some compilers and atoi)
+
+   * mcalib/MCalibrationIntensityChargeCam.cc:
+     - fixed a warning about a invalid escape sequence -- seems that
+       not all compilers do display this warning...
+     - corrected order of includes
+
+   * mfbase/MFEventSelector2.[h,cc]:
+     - some cosmetic fixes
+     - some adpations to standard output (eg. Separator() instead of ***)
+     - added a check whether 'filter' inherits from MFilter
+     - fixed the return of ReadDistribution
+     - made comments for data members in cleass header 'one line'
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - added fNameGeomCam for parameter list access
+     - added fNameCerPhotEvt for parameter list access
+     - fixed a typo in an output
+     - NO change to ANY algorithm!
+     - changed class version from 1 to 2
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added a rule to replace .raw by .root in MWriteRootFile
+
+   * mranforest/MRanForestCalc.[h,cc]:
+     - fixed missing data member initialization in constructor
+     - added ReadEnv which is able to read a random forest from a file
+     - added an owner flag for the random forest tree
+
+
+
+ 2004/12/22 Markus Gaug
+
+    * mraw/MRawEvtHeader.[h,cc]:
+      - added some new Getter-functions for the calibration conf. 
+        pattern
+ 
+    * mcalib/MCalibrationChargeCalc.[h,cc],
+      mcalib/MCalibrationRelTimeCalc.[h,cc],
+      mcalib/MCalibrationColorSteer.cc:
+      - use the new functions
+
+    * mhcalib/MHCalibrationCam.[h,cc],
+      mhcalib/MHCalibrationRelTimeCam.[h,cc],
+      mhcalib/MHCalibrationChargeCam.[h,cc]:
+      - centralize the decision about the probability limit to be 
+        taken inside these classes.
+ 
+    * mhcalib/MHCalibrationPix.cc
+      - fix a bug in the calculation of outliers. Standard analyses  
+        not affected!
+
+
+
+ 2004/12/22 Eva Domingo
+
+    * mtemp/mifae/library/MImageParDisp.[cc,h]
+      - Container for the estimated distance to source position DISP.
+
+    * mtemp/mifae/library/MDisp.[cc,h]
+      - Container holding the parameters used for the DISP expression.
+        The current DISP parameterization is defined in MDisp::Calc.
+
+    * mtemp/mifae/library/MDispCalc.[cc,h]
+      - Task calculating DISP with the expression and parameter values
+        stored in MDisp. Training and test matrix of variables to be 
+        used in the DISP optimization are also defined within 
+        MDispCalc::InitMapping.
+
+    * mtemp/mifae/library/MHDisp.[cc,h]
+      - Container for the histograms to judge the quality of the DISP 
+        estimate. MHDisp::GetChi2 returns the value of the quantity 
+        requested to be minimized by Minuit, which is defined and 
+        computed in MHDisp::Fill and MHDisp::Finalize. 
+        MHDisp::GetSkymapXY returns the reconstructed map of source 
+        positions. MHDisp::SetSelectedPos function to choose the 
+        selection method of the DISP source position solution.
+
+    * mtemp/mifae/library/MFDisp.[cc,h]
+      - Filter to select a sample of events to do the DISP optimization.
+       Use MFDisp::SetCuts function.
+
+    * mtemp/mifae/library/MFindDisp.[cc,h]
+      - Main class for DISP optimization:
+         ::DefineTrainMatrix, ::DefineTestMatrix, ::DefineTrainTestMatrix
+        generate the training and test samples (in the form of matrices)
+        from the input file.
+	 ::FindParams is the function steering the optimization (over the
+        training sample), calling Minuit, passing the fcn function to be 
+        minimize and defining the event loop to be executed in each step.
+	 ::TestParams tests the quality of the DISP estimate using the 
+        test matrix sample
+
+    * mtemp/mifae/macros/OptimizeDisp.C
+      - macro for estimating the DISP parameter: create training and test
+        matrix; optimize DISP; test quality optimization; calculate DISP
+        and construct skymap for an input file.
+
+    * mtemp/mifae/library/Makefile, mtemp/mifae/library/IFAELinkDef.h
+      - include DISP classes.
+
+
+
+ 2004/12/22: Eva Domingo (for Wolfgang Wittek)
+
+   * mfbase/MFEventSelector2.[h,cc]:
+     - the 'original' distribution, a subsample of which wants
+       to be selected, now can be determined with some previous
+       selection cuts. When determing the 'original' distribution
+       in PreProcess() not only the 'read' object but also the 
+       'filter' object (with the name "FilterSelector2") of the 
+       current event loop is used.
+
+
+
+ 2004/12/22: Abelardo Moralejo
+
+   * mtemp/mpadova/macros/MRanForestPD.C:
+     - added parentheses in the expressions inside the calls to
+       AddColumn() regarding the scaled Width and Length, otherwise
+       they are not interpreted correctly. However, there is no
+       difference in the outcome: the "scaling" seems to be done
+       internally by RF in any case... 
+
+
+
+ 2004/12/17: Markus Gaug
+
+   * mcalib/MCalibColorSet.cc:
+     - added missing runs where run number does not appear any more in 
+       project-name and is not yet set in the digital modules.
+
+   * mcalib/MCalibrationIntensityCam.[h,cc],
+     mcalib/MCalibrationIntensityChargeCam.[h,cc],
+     mcalib/MCalibrationIntensityRelTimeCam.[h,cc]:
+     - added some new functions to display the results of the intensity
+       calibration
+
+
+
+ 2004/12/17: Thomas Bretz
+
+   * showplot.cc:
+     - added the error debug-level to some output
+
+   * mcalib/MCalibColorSet.cc:
+     - replaced arbitrary number for run type by correct enum
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - changed DrawClonePad such that
+       + before cloning we change into the pad (necessary for 
+         GetDrawOption)
+       + removed SetSelectedPad (seems not necessary at all)
+       + SetBit(kCanDelete) for all cloned object
+       + copy bits kMustCleanup, kCannotPick and kNoContextMenu
+       + oldc is not const anymore (cd()!)
+
+   * mhbase/MH3.[h,cc]:
+     - removed fNameProfX, fNameProfY - didn't work with a more accurate
+       scheme to get the handle to the profile histograms
+     - moved most code from Draw to Paint so that a more accurate handling
+       of read pads containing these histograms is possible
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - moved most code from Draw to Paint so that a more accurate handling
+       of read pads containing these histograms is possible
+
+   * mhflux/MHEffectiveOnTime.[h,cc]:
+     - removed fNameProj* - didn't work with a more accurate
+       scheme to get the handle to the profile histograms
+     - set no option for default AppendPad (istead of "fit" which 
+       didn't work for saved files - for unknown reasons)
+
+
+
+ 2004/12/16: Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.h
+     - set the class number up from 1 to 2
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - another bugfix for the low-gain extraction
+
+   * mhcalib/MHCalibrationRelTimeCam.[h,cc]
+     - fixed bug in display of the averaged cams.
+
+
+
+ 2004/12/15: Thomas Bretz (important bugfixes for callisto)
+
+   * callisto.rc:
+     - fixed wrong names in comments
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed naming of the two MPedCalcFromLoGain
+     - set correct pedestal container for extractor
+
+   * msignal/MArrivalTimeCam.h:
+     - added Reset() function
+
+   * msignal/MExtractTime.cc:
+     - replaced parts of the common PreProcess by new function PreProcessStd
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - removed Clear() in Process() -- this is automatically done by 
+       Reset()
+
+   * msignal/MExtractedSignalCam.h:
+     - added Reset() function
+
+   * msignal/MExtractor.[h,cc]:
+     - moved some common parts of PreProcess to new function PreProcessStd
+       this fixed the problem that searching for fPedestals was
+       overwritten in MExtractTime
+
+   * macros/readrep.C:
+     - added the missing '.' dot to MTime in a comment
+
+   * mhbase/MH3.cc:
+     - draw profile by default not in blue but in the same color as the
+       histogram. Use 'BLUE' option to get the old behaviour
+     - fixed handling of 'same' option
+     - propagate title of axis to profile histogram
+
+
+
+ 2004/12/15: Abelardo Moralejo
+
+   * mmc/MMcConfigRunHeader.h
+     - added data member fPmtTimeJitter, sigma of gaussian of the time
+       jitter introduced in the time of each photoelectron.
+
+
+
+ 2004/12/14: Markus Gaug
+
+   * msignal/MExtractor.[h,cc]
+     - add possibility to set pedestal pointer from outside
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - make modification of extraction window only for case of now 
+       high-gain saturation.
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - fixed some smaller bugs for special cases
+
+   * mcalib/MCalibrationIntensityChargeCam.[h,cc]
+     - implemented automatic plotting of Razmik plot and others
+
+
+
+ 2004/12/14: Markus Gaug and Abelardo Moralejo
+
+   * msignal/MExtractFixedWindowPeakSearch.cc
+     - adjusted the offset from peak search window to extraction window
+       such that they start at the same slice for the case: 
+       fOffsetFromWindow=0. This was the original intention of the 
+       extractor and had been lost at some place. Instead, the default 
+       (fOffsetFromWindow=1) did before correspond to an offset of 2 
+       slices which gave wrong results for the calibration and further
+       default settings. 
+     - Changed one comparison: (Byte_t - Byte_t) > 0 to (Byte_t > Byte_t)
+       since the first mode is always true (a negative "byte" simply gives 
+       256-difference. The version before could have lead to crashes from 
+       time to time.
+
+
+
+ 2004/12/12: Abelardo Moralejo
+
+  * mpoitning/MPointingPosCalc.cc
+    - Changed recently added sanity check in PreProcess so that it is 
+      done only for real data files and not for MC. Corrected typo in
+      warning.
+
+
+
+ 2004/12/09: Markus Gaug
+  
+   * mhcalib/MHCalibrationPix.[h,cc]
+     - fixed a bug in Reset(), fSaturation was not resetted before. 
+       Affects only intensity calibraion.
+   * mhcalib/MHGausEvents.cc
+     - fixed bug in Reset(), histogram ranges were not reset before.
+       Affects only intensity calibraion.
+
+
+
+ 2004/12/09: Thomas Bretz
+
+  * mbadpixels/MBadPixelsTreat.cc:
+    - set default in constructor to UseInterpolation, ProcessPedestalEvt
+      and ProcessTimes which is the callisto default
+    - enhanced comments in output
+
+
+
+ 2004/12/08: Thomas Bretz
+
+  * mraw/MRawRunHeader.cc:
+    - changed maximum allowed format version from 4 to 5
+
+  * mraw/MRawEvtHeader.[h,cc]:
+    - added correct decoding of the 200ns information as proposed by
+      Florian to DecodeTime
+
+   * callisto.cc:
+     - more fixes to make calibration of signal (Y) work again
+
+   * callisto.rc:
+     - adapted to changes in callisto
+     - changed such that the digital filter is used as a default
+
+   * mcalib/MCalibrateData.cc:
+     - allow calibration of Mean and Rms from different input
+       containers
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - removed SetNoiseCalculation -- now in its correct location
+     - added a second MPedCalcFromLoGain
+     - some more default setup
+     - added some new tabs with histograms
+     - ProcessFile now takes too input containers
+
+   * mjobs/MJCalibration.cc:
+     - set rel-time-calibration kTRUE by default
+     - removed SetNoiseCalculation -- now in its correct location
+     - enhanced writing extractors
+
+   * mjobs/MJPedestal.[h,cc]: 
+     - if cloning extractor - don't use name
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - some minor changes to output
+     - fixed order or arguments of FindObject
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - handle SetNoiseCalculation when calculating noise!
+
+   * msignal/MExtractTimeAndCharge.cc:
+     - some minor changes to output
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - some minor changes to output
+     - do not write fNameWeightsFile
+     - do not write fWeightsSet
+     - do not write fRandomIter
+
+   * mpointing/MPointingPosCalc.cc:
+     - added a sanity check in Process
+
+
+
+ 2004/12/06: Abelardo Moralejo
+
+  * macros/starmc.C
+    - Added container MConcentration to output. Added MPointingPosCalc
+      to tasklist, and MPointingPos to output.
+
+  * mtemp/mpadova/macros/resize.C
+    - Added containers MConcentration and MPointingPos to output.
+
+
+
+ 2004/12/06: Thomas Bretz
+
+  * mpedestal/MPedCalcPedRun.cc:
+    - fixed bug which I introdued on friday (PostProcess was
+      defined twice)
+
+   * macros/RanForest.C:
+     - replaced kGAMMA by MMcEvt::kGAMMA
+
+   * mhist/MHCamEvent.[h,cc]:
+     - allow to set name for MGeomCam
+
+   * mjobs/MJCalibration.cc:
+     - removed some obsolete comments
+     - reset SetNoiseCalculation for both extractors
+     - do not allow 'wrong' time&charge calibration (without
+       extractors cam)
+     - removed kTimeAndCharge flag because it is obsolete (nowhere used)
+       and not correctly handled at all
+
+   * callisto.cc, star.cc:
+     - added '--debug-mem' option
+
+   * callisto.rc:
+     - changed such to make it work with the new double-pedestal-loop
+       callisto
+     - default extractor now is Digital Filter
+
+
+
+
+ 2004/12/02: Thomas Bretz
+
+   * mbase/MLog.cc:
+     - fixed some warning about a missing return if __REENTRANT is not
+       defined (like in MAC OS X)
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]:
+     - added possibility to set fPedestals directly by pointer
+     - unfolded some Form statements
+
+   * callisto.cc:
+     - changed callisto to support second pedestal loop -- WORK IN PROGRESS
+
+   * mbase/MParContainer.[h,cc]:
+     - moved code from GetDescriptor to a static function GetDescriptor
+      
+   * mbase/MStatusDisplay.cc:
+     - removed a oboslete debug output
+
+   * mbase/MTaskEnv.h:
+     - made ReadEnv public
+
+   * mcalib/MCalibrationChargeCam.[h,cc]:
+     - changed some returned TArrayF* to TArrayF
+
+   * mimage/MImgCleanStd.cc:
+     - changed point of output of name of MPedPhotCam
+
+   * mjobs/MJCalibration.cc:
+     - don't use MParList to hand ExtractorCam over
+     - some changes to the structur for Writing (only consmetics)
+
+   * mjobs/MJPedestal.[h,cc]:
+     - ordered includes correctly
+     - for the moment removed fNameExtractorCam -- simplifies thing a lot
+     - make a clone of the extractor given by the user - for sanity
+     - correct handling of the allocated memory for fExtractor
+     - replaced counts/slice by cts/slice for space reasons
+     - changed name of new tabs for space reasons
+     - added possibility to CheckEnv to set extractor from resource-file
+     - outsourced some code to SetupExtractor
+     - given a name to MFillH
+     - changed handling of SetNoiseCalculation which is now set correctly all
+       the time
+     - Writing must still be checked!!!
+
+   * mjobs/MJob.[h,cc]:
+     - allow WriteContainer to use any TObject
+     - added Getter-functions for the TEnv stuff
+
+   * mpedestal/MExtractPedestal.[h,cc]:
+     - allow setting of fPedestalIn by pointer directly
+     - fixed handling of fPedestalIn accordingly
+     - changed some arguments from pointer to reference
+     - changed some accesses to TArrays from At to []-operator
+     - shortened and enhanced output
+     - fixed place and type of screen output
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - removed GetSlice -> replaced by a array with a copy of the data
+     - changed some loops to pointer arithmetic for speed reasons
+       in this case
+
+   * mpedestal/MPedCalcPedRun.[h,cc]:
+     - changed handling of first pedestal run for simplicity
+     - replaced some Form calls
+     - changed direct handling of single bits to correct enums
+     - fixed wrong 'all' in output
+     - simplified output
+     - fixed some stuff in the output
+
+   * mpedestal/MPedestalCam.[h,cc]:
+     - fixed the Copy function - WITHOUT this fix the calibration could
+       not have worked properly at all.
+     - changed some function names to Mars standrad names
+     - removed some obsolete loops - replaced by ForEach
+     - changed some TArrayF* returnes to TArrayF
+
+   * msignal/MExtractTime.cc, msignal/MExtractTimeAndCharge.cc,
+     msignal/MExtractTimeAndChargeDigitalFilter.cc, 
+     msignal/MExtractor.cc
+     - fixed some wrong debug levels in output
+     - some simplification and shortening to output
+
+
+
+
+ 2004/12/02: Markus Gaug
+ 
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - replaced CallPostProcess by public member function Finalize()
+
+
+
+ 2004/12/02: Thomas Bretz
+
+   * msignal/MExtractTime.cc, msignal/MExtractTimeAndCharge.cc,
+     msignal/MExtractor.cc:
+     - removed obsolete output after FindCreateObj
+
+   * msignal/MExtractor.h:
+     - don't write fNoiseCalculation to file
+
+
+
+ 2004/12/01: Markus Gaug and Thomas Schweizer
+ 
+   * mpedestal/MPedCalcFromLoGain.cc
+     - introduce a check which does not allow the last slice of the 
+       check window to be smaller than the last slice of the 
+       extraction window.
+
+
+
+ 2004/12/01: Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]:
+     - introduced a random iterator for the "pedestal" calculation of 
+       the amplitude spline.
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - fixed bug in the loop over the weights which can cause a call to 
+       an array index out of range. Since MArrays are used, this call 
+       could simply produce a segmentation violation (or not), at any 
+       place. This bug was there since the beginning, but should have 
+       happened only in very rare cases.
+
+
+
+ 2004/11/30: Thomas Bretz
+ 
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - InitArrays: added missing return statement
+
+
+
+ 2004/11/30: Markus Gaug
+
+   * macros/calibration.C
+     - new version incorporating the possibility to calculate the 
+       extractor resolution
+
+   * msignal/cosmics_weights_logaintest.dat
+   * msignal/cosmics_weights4_logaintest.dat
+   * msignal/calibration_weights_UV_logaintest.dat
+     - High-low-gain inverted weights files for the TDAS-Extractor 
+       nr. 29, 31, 33. Only to be used for the TDAS-test. The correct 
+       low-gain weights are already included in the "cosmics_weights.dat",
+       "cosmics_weights4.dat" and "calibration_weights_UV.dat".
+
+   * mjobs/MJCalibration.cc
+     - updated to new version of MPedCalcPedRun (only important for 
+       intensity calibration)
+     - installed the new possible handling of two MPedestalCam's - one 
+       for the signal extractor and another one (with the extractor 
+       resolution) for MCalibrationChargeCalc.
+      
+   * msignal/MExtractTimeAndCharge.cc
+     - fixed bug for very high saturating signals setting the low-gain 
+       range wrong. 
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - added variable containing the name of the requested MPedestalCam
+
+   * mpedestal/MPedestalCam.[h,cc]
+     - added in Copy-function call to MParContainer::Copy
+     - removed now obsolete ReCalc()-function
+
+   * mpedestal/MExtractPedestal.cc
+     - added reading of ExtractWindow in ReadEnv
+
+   * callisto.rc
+     - updated pedestal initializations
+
+
+
+ 2004/11/30: Wolfgang Wittek
+
+   * mtemp/PaddingExample.C
+     - example macro for the padding
+
+
+
+ 2004/11/29: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+     - implemented the possibility to extract the pedestal with a 
+       signal extractor. In order to do so, two new commands have to
+       be executed: 
+       1) MJPedestal::SetExtractorResolution()
+       2) MJPedestal::SetPedestals(MPedestalCam& )
+       In the second case, a fully filled PedestalCam has to be 
+       given, which will remained unchanged, however. This cam is 
+       used only to subtract the (AB-noise corrected) pedestals with
+       the signal extractor. 
+     
+       The newly created pedestal Cam can be retrieved via: 
+       MJPedestal::GetPedestals()
+       (like in the other cases as well). 
+    
+       The name of the extractor-filled pedestal cam can be set with:
+       MJPedestal::SetNameExtractorCam()
+
+
+
+ 2004/11/28: Markus Gaug
+
+   * mpedestal/MPedestalPix.cc
+     - removed (fPedestal>=0) in the IsValid() function since now, there 
+       can be valid pedestal Pix's with negative "pedestal".
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractTime.cc
+     - add a check for the pointers fSignal and fArrTime to be initialized
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - fixed documentation of data members
+     - Introduced setter and getter for name of weights file
+     - modified way to use the NoiseCalculation(). Now more compatible
+       with MPedCalcFromLoGain
+
+   * msignal/MExtractFixedWindowPeakSearch.cc
+     - fixed a bug which affects the extractor used with:
+       SetRange(hifirst,hilast,lofirst,lolast) where hilast is bigger
+       than the number of high-gain samples minus 1 (e.g. 14 in case of 
+       MAGIC). While other extractors treat this case by setting a 
+       steering variable ("fHiLoLast") in the ReInit(), this
+       extractor allocates this variable dynamically. However, the 
+       setting in ReInit() was also kept such that in the case that the 
+       peak-search-window did NOT exceed the number of high-gain samples, 
+       the part of the low-gain samples corresponding to fHILoLast was 
+       still extracted. This behaviour is corrected now, I hope it 
+       does not affect any current analysis!
+
+   * mbase/MStatusDisplay.[h,cc]
+     - added GetterFunction for one dedicated pad in the status display.
+       The pad gets resized to normal size, then. 
+
+
+
+ 2004/11/26: Markus Gaug
+
+   * mbase/MRunIter.[h,cc]
+     - fixed the missing initialization of kIsStandardFile to kFALSE. 
+ 
+   * msignal/MExtractTimeAndChargeSpline.h
+     - added Getter Functions for the variables fRiseTime and fFallTime     
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.h
+   * msignal/MExtractFixedWindowPeakSearch.h
+     - added Getter Functions for the variables fWindowSizeHiGain and 
+       fWindowSizeLoGain
+
+   * mpedestal/MHPedestalPix.[h,cc]
+     - removed 
+
+   * mcalib/MCalibrationPix.h
+     - added two new Getters
+
+   * mpedestal/MHPedestalCam.[h,cc]
+     - moved to directory mhcalib. 
+       I'm sorry for this moving around of classes. The important reason
+       is that this class derives from another class in mhcalib/, namely 
+       MHCalibrationCam. It ocurred that compiling this class in a 
+       job-class (e.g. MJPedestalCam), the Cint-Compiler got completely 
+       confused when a TArray or an MArray is part of MHPedestalCam. 
+       Then, the ClassName()'s of some OTHER classes got overwritten. 
+       This happens with a no other data-members and functions except 
+       for a TArray or and MArray. 
+       I have tried different versions of root, always compiling 
+       everything from the beginning, but only this moving solved the 
+       problem (see also a bugreport in mantis).
+     - added a direct calculation of mean's and RMS's stored in the 
+       "LoGain"-variables of MCalibrationPedCam
+
+   * mcalib/MCalibrationPedCam.cc
+     - added new flags in the GetPixelContent called the "low-gain" 
+       entries (s.a.)
+
+   * mcalib/MCalibColorSteer.[h,cc]
+     - removed pointer to MRawRunHeader
+  
+   * mpedestal/MExtractPedestal.[h,cc]
+     - new base class for pedestal extractor.
+     - incorporates possibility to have an incoming pedestal Container 
+       and an outgoing
+     - incorporates possibility to extract pedestals from an extractor
+
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - derives from MExtractPedestal now 
+     - Add two functions looking for the pedestal bit in the trigger
+       pattern
+     - Add the possibility to skip an event if: 
+       a) the run is not a pedestal run or
+       b) the trigger bit is set to pedestal
+     These modifications allow to use this class for interlaced pedestal
+     events.
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]
+     - derives from MExtractPedestal now 
+
+   * manalysis/Makefile
+     - removed inclusion of directory mhcalib/
+
+
+
+ 2004/11/23: Markus Gaug
+ 
+   * mbadpixels/MBadPixelsCam.[h,cc]
+     - improved the Print() function such that the individual pixels 
+       matching a certain badness-criterion are listed.
+
+   * mpedestal/MPedestalPix.[h,cc]
+   * mpedestal/MPedestalCam.[h,cc]
+     - introduced Copy-function
+
+
+
+ 2004/11/23: Raquel de los Reyes
+
+   * mbase/MRunIter.[h,cc]
+     - changed the format of the read file to allow the processing of
+       standard F0/F1 (pedestal/calibration) files.
+     - Included a Set function.
+
+
+
+ 2004/11/22: Markus Gaug
+
+   * mcalib/MCalibrationPix.h
+     - new data member fHiGainRms and fLoGainRms requested by Florian  
+       a long time ago to be used for the data check.
+     - set the version number from 1 to 2.
+
+   * mcalib/MCalibrationChargeCam.cc
+     - introduced new flag in GetPixelContent which returns the RMS  
+       divided by mean, to be called by MJCalibration in the datacheck.
+
+   * mhcalib/MHGausEvents.h
+     - new function GetHistRms() returning the RMS of the histogram
+
+   * mhcalib/MHCalibrationCam.cc
+     - stores the histogram RMS in MCalibrationPix in function 
+       FitHiGainHists and FitLoGainHists
+
+   * mjobs/MJCalibration.cc
+     - display in the datacheck the RMS per Mean instead of the reduced
+       sigma per mean which is anyhow reflected by the number of photo-
+       electrons.
+     - put a class MPedCalcPedRun in the tasklist for the intensity 
+       calibration (does not affect normal calibration).
+
+
+
+ 2004/11/22: Marcos Lopez
+
+   * mhist/MHFindSignificance.h:
+     - fixed the return type of some getter functions. Some was returning 
+       Float_t instead of Int_t and other Float_t instead of Double_t.
+     - added more getter functions.
+
+
+
+ 2004/11/22: Markus Gaug
+ 
+   * mcalib/MCalibColorSet.cc
+     - added runs 44768, 44976 and 45368 as blue runs
+     - added patch to work until the lecture of the .run files is 
+       synchronized with this class: All calibration runs are assumed 
+       to be 10Led_UV. This has to be removed immediately when the 
+       synchronization is done and serves especially the data-check.  
+
+
+
+ 2004/11/22: Thomas Bretz
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc:
+     - added check for \015 character in filename
+
+
+
+ 2004/11/22: Abelardo Moralejo
+
+   * mfbase/MFEventSelector2.cc
+     - Fixed error in Process: calls to Select and SelectProb were 
+       exchanged.
+     - Added example to documentation on how to use the "probability"
+       option.
+
+   * mfbase/MFEventSelector.h
+     - Fixed typo in comment
+
+   * mfilter/MFSize.[h,cc]
+     - removed class. The same kind of filtering can now be done, in  
+       a more versatile way, with MFEventSelector2
+
+   * mfilter/Makefile, FilterLinkDef.h
+     - removed class MFSize
+
+   * mtemp/mpadova/macros/resize.C
+     - Now the class MFEventSelector2 is used instead of the removed
+       MFSize. Behaviour is the same. Default probabilities have been 
+       slightly changed (but this is just an example).
+
+
+
+ 2004/11/18: Hendrik Bartko
+
+   * msignal/MC_weights_2GSamples.dat:
+     - new weights file for MC simulations of the 2 GSamples FADCs
+
+
+
+ 2004/11/18: Wolfgang Wittek
+
+   * mbadpixels/MHBadPixels.[h,cc]
+     - include 'fCam' to set the size of MPedPhotCam;
+       why is the size of MPedPhotCam equal to 0 ???
+     - use "UseCurrentStyle()" when drawing a histogram
+     - in SetupFill() the binnings of the histograms may be changed 
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]
+     - print name of MPedPhotCam container in PreProcess
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - use iterator for looping over MCerPhotPix
+     - use "UseCurrentStyle()" when drawing a histogram
+     - in SetupFill() the binnings of the histograms may be changed 
+     - plot also Theta versus phi
+
+   * macros/ONOFFAnalysis.C
+     - replaced part of the code by calls to 
+                - MMakePadHistograms
+                - and to new member functions of MPad
+
+   * manalysis/MMakePadHistograms.[h,cc]
+     - new class; it generates histograms which are needed for the 
+       padding 
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h
+     - add MMakePadHistograms
+
+   * manalysis/MPad.[h,cc]
+     - add member function ReadPadHistograms()  
+
+   * mfilter/MFSelBasic.[h,cc], mfilter/MFSelStandard.[h,cc],
+     mfilter/MFSelFinal.[h,cc]:
+     - move printout of cut values from SetCuts() to PreProcess()
+
+   * mimage/MImgCleanStd.[h,cc]
+     - print name of MPedPhotCam container in PreProcess()
+
+
+
+ 2004/11/18: Thomas Bretz
+
+   * mjobs/MJPedestal.cc:
+     - fixed a bug in the handling of kUsePed which caused the MTaskEnv
+       to be set incorrectly
+
+   * mfbase/MFEventSelector2.[h,cc]:
+     - added possibility to set a propability distribution
+
+   * mgeom/MGeomCam.[h,cc]:
+     - enhanced the Print function
+     - fixed the Clone function for the class being MGeomCam
+     - made InitGeometry public to support unsupported geometries
+
+   * mgeom/MGeomPix.h:
+     - added Copy function
+
+   * mhbase/MH3.[h,cc]:
+     - added a constructor taking a TH1 as argument
+
+
+
+ 2004/11/18: Markus Gaug
+
+   * msignal/MExtractor.[h,cc]
+     - introduce possibility to choose name of MExtractedSignalCam. Need
+       access to different MExtractedSignalCams for comparative extractor
+       studies. Analogues to MPedestalCam in MPedCalcFromLoGain. Default 
+       is "MExtractedSignalCam", like before. 
+     - set version number by one higher because of new data member 
+       "fNameSignalCam"
+
+   * msignal/MExtractTime.[h,cc]
+     - introduce possibility to choose name of MArrivalTimeCam. Need
+       access to different MArrivalTimeCams for comparative extractor
+       studies. Analogues to MPedestalCam in MPedCalcFromLoGain. Default 
+       is "MArrivalTimeCam", like before. 
+     - set version number by one higher because of new data member 
+       "fNameTimeCam"
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - initialize MExtractedSignalCam with the name chosen in the base 
+       class.
+
+
+ 2004/11/17: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Added getter method for fMuonCphFraction
+
+
+
+ 2004/11/17: Raquel de los Reyes
+
+   * mhist/MHFindSignificance.cc
+     - commented the creation of a canvas in the DrawFit function. Now it is 
+       allowed the option of display the result in a canvas, previously 
+       created, or in a new one if it doesn't exit.
+
+
+
+ 2004/11/16: Markus Gaug
+
+   * mcalib/MCalibrationRelTimeCalc.cc
+     - make pixels with deviating time resolution unreliable instead of 
+       unsuitable. This should take out 1 or 2 more unsuitable pixels. 
+
+   * mcalib/MCalibColorSet.cc
+     - introduce treatment of the case that one file in between the 
+       sequence of calibration runs is a pedestal file (run type == 1)
+       and return kCONTINUE in the process. As this task is at the 
+       beginning of the tasklist, the calibration tasks will be skipped
+       for these events. This treats now an interlaced pedestal run. 
+       Next will follow an interleaved pedestal event and finally an 
+       interleaved data event.
+
+   * mhcalib/MHCalibrationChargeCam.cc
+     - adapt the histogram ranges slightly because I have found high 
+       intensity calibration events creating non desired overflows.
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - fixed a bug in the setting of the window which set always the
+       default before.
+
+   * mcalib/MCalibrationChargePINDiode.[h,cc]
+     - updated numbers to the currently installed pin diode
+
+
+
+ 2004/11/16: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Added comment regarding change in version 4.
+
+   * mmc/MMcFadcHeader.hxx
+     - Added data member fNoiseGainFluctuations. Updated class version
+       to 6
+
+   * mmc/MMcTrigHeader.hxx
+     - Added data members fGainFluctuations and fNoiseGainFluctuations.
+       Will contain same values as the corresponding members in the
+       MMcFadcHeader of MC camera files. We just put them in both 
+       headers because the fluctuations affect both the trigger 
+       signal and the FADC signal.
+
+
+
+ 2004/11/16: Markus Gaug
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - give as argument to UpdateBlindPixelMethod() and 
+       UpdateFFactorMethod() the transmission of the plexiglass and the 
+       its rel. variance. 
+       This divides the normalization factor by those numbers and fixes a 
+       bug in the absolute normalization.
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - give the new arguments to MCalibrationQEPix
+
+
+
+ 2004/11/15: Thomas Bretz
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - reset logging stream to CORRECT one after redirection
+     - do not redirect the logging stream if no output file is
+       selected
+
+   * mhist/MHHadronness.cc:
+     - fixed a type in the class description
+
+   * mjobs/MJCalibration.cc:
+     - do not write miracle appearance files by MCalivrationChargeCalc
+
+
+
+ 2004/11/13: Hendrik Bartko
+
+   * msignal/cosmics_weights.dat:
+     - implemented low gain weights from pulpo data
+
+   * msignal/cosmics_weights4.dat:
+     - implemented low gain weights from pulpo data
+
+
+
+ 2004/11/12: Thomas Bretz
+
+   * mraw/MRawEvtData.[h,cc]:
+     - fixed a bug in the initialisation of the arrays (in both
+       cases - hi- and lo-gain - the number of hi gain samples were
+       used
+     - do not try to read lo gains if poslo==NULL
+     - changed return type of GetNum[Hi,Lo]GainSamples from
+       Byte_t to UShort_t to support up to 65535 samples
+
+   * mraw/MRawRunHeader.cc:
+     - updated Print()
+
+
+
+ 2004/11/11: Markus Gaug
+
+   * mcalib/MCalibrationBlindPix.[h,cc]
+     - introduced new data member: fAreaErr which is not zero for the
+       third blind pixel
+
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MCalibrationBlindCamThreeNewStyle.[h,cc]
+     - new class describing the blind pixel camera with three blind 
+       pixels.
+
+   * mjobs/MJCalibration.cc
+     - fixed a typo in the draw command of the blind pixel 
+       (MHCalibrationChargeChargeBlindCam -> MHCalibrationChargeBlindCam)
+     - introduced the new blind pixels initialization
+
+   * msignal/MExtractBlindPixel.cc
+     - added MRawEvtData2 to BranchList
+
+
+
+ 2004/11/11: Thomas Bretz
+
+   * callisto.cc:
+     - fixed a typo in the screen output
+     - added setting of input path to second call to MJPedestal
+       to get the extraction window from the calibration file
+
+   * mastro/MAstroCamera.cc:
+     - made a simple simplification
+
+   * mmuon/MMuonSearchParCalc.cc:
+     - changed some log-output to be standard
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - Updated fTitle
+     - Fixed AddToBranchList entries
+     - invented a new function (ResetArrays)
+     - added a return value to SetCheckRange
+     - added a return value to SetCheckRange
+     - changed arguments of SetExtractWindow to UShort_t which is more
+       intuitive
+     - changed arguments of SetExtractWindow to UShort_t which is more
+       intuitive
+     - changed some log-output to be more standard
+     - changed return type of GetSlice to UShort_t
+     - fixed names of resources to fit variable names
+     - implemented Print()
+     - changed types of default to UShort_t
+     - changed derivement from MExtractor to MTask
+
+   * mraw/MRawRead.cc:
+     - fixed a bug which caused the special pixel indices to be 2,3,4,...
+       instead of 0,1,2,3,...
+
+   * msignal/MExtractor.[h,cc]:
+     - changed non intuitive default argument of SetNoiseCalculation
+       from kFALSE to kTRUE
+
+   * mjobs/MJCalibrateSignal.cc:
+     - automatically get correct range for pedestal extraction 
+       (MPedCalcFromLoGain) from Signal Extractor
+
+   * mjobs/MJPedestal.cc:
+     - simplified a complicated if-else-construction towards a
+       correct setting of ranges also for the calibration of the signal.
+     - added reading of extraction window from calibration file
+       (ReadCalibration)
+     - made sure that in the case of an extractor from a calibration file
+       the extraction window for pedestals is correctly set
+     - set SetPedestalUpdate(kFALSE) as default for MPedCalcFromLoGain
+
+   * mbase/MEvtLoop.cc:
+     - updated a comment
+
+   * msignal/MExtractor.cc:
+     - added printing hi-gain samples
+
+
+
+ 2004/11/10: Abelardo Moralejo
+
+   * mhist/MHHadronness.cc
+     - Changed upper limit of hadronness histograms from 1. to 1.0001.
+       Before, events with hadronness=1 were put in the overflow bin,
+       and they were not counted in the calculation of hadron efficiency
+       or of the quality factors that were displayed in the plots and 
+       on the text messages. At high energies the underestimation of Q
+       could be as large as a 20%.
+
+
+
+ 2004/11/10: Markus Gaug
+
+   * mhcalib/MHCalibrationRelTimeCam.cc
+     - reduced nr of bins from 900 to 200 which is sufficient. 
+       Apparently, Nadia had got some problems with the high memory 
+       needed. 
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - updated the effective number of slices (CAN be used for a rude 
+       pedestal RMS estimation) from 2.5 to 4. (e.g. in case of 6 slices 
+       used by the weights file) after getting the equivalent result 
+       from Hendrik. This should approximate the real pedestal RMS to a 
+       relatively good precision although still the extensive test with 
+       the noise calculation from the extractor directly is missing.
+     - subtract the pedestal right at the beginning instead of twice 
+       during execution of the filter.
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - added treatment of IsNoiseCalculation() for the "integral" 
+       method.
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.cc
+     - added treatment of IsNoiseCalculation().
+
+
+
+ 2004/11/10: Abelardo Moralejo
+
+   * mfbase/MFEventSelector2.cc
+     - Added some comments in class description.
+
+
+
+ 2004/11/09: Abelardo Moralejo
+
+   * mfilter/MFSize.cc
+     - Eliminated allocation of histogram fProb in constructor. Now
+       it has to be supplied by the user.
+
+
+
+ 2004/11/09: Hendrik Bartko
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - implemented an unbiased application of the digital filter in the
+       case of MExtractor::IsNoiseCalibration() is true. Thereby the
+       weights are quasi randomly chosen and applied to the first slices
+       available in the set range
+
+   * msignal/MC_weights.dat
+    - new weights file using 6 slices for the digital filter, especially
+      made for MC pulses
+
+
+
+ 2004/11/09: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+     - implemented the possibility to use the extractor to calculate the 
+       pedestals. Now, there are three possibilities: 
+
+       1) SetUseData(): will use MPedCalcFromLoGain together with a data
+                        file (and possibly a signal extractor to 
+                        determine the ranges)
+       2) SetUsePedRun(): will use MPedCalcPedRun together with a 
+                          pedestal run (and possibly a signal extractor
+                          to determine the ranges)
+       3) SetUseExtractor(): Will use the extractor itself and checks 
+                          that the flag IsNoiseCalculation() is set.
+
+   * msignal/MExtractor.[h,cc] 
+     - introduced flag "fNoiseCalculation" to be used by the 
+       deriving classes to calculate the noise from a fixed window in 
+       time.
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]
+     - corrected the documentation of the indiv. functions
+     - some cosmetic changes
+
+   * mpedestal/MPedCalcPedRun.cc
+     - previously the variable fNumLoGainSize was automatically set to
+       2 in case that it was initialized to 0. This is a bugfix, since 
+       the default uses 0 slices (see e.g. MJPedestal) for the low-gain.
+       The effect is rather small since the ped. RMS PER SLICE does not 
+       change so much by going up 2 slices, maybe 1-2% depending on the 
+       extraction window. The smaller the window, the bigger the 
+       relative error.
+
+
+
+ 2004/11/08: Abelardo Moralejo
+
+   * mpedestal/MPedPhotCalc.cc
+     - In ReInit: removed check of whether file is MC file. Now fSumx
+       and fSumx2 are initialized also for MC files. This is needed to
+       run some parts of the calibration over pedestal and calibration 
+       MC files.
+
+
+
+ 2004/11/06: Abelardo Moralejo
+
+   * mbase/MTask.cc
+     - Fixed typo in PrintSkipped: "%5.1f" instead of wrong "5.1f", 
+       which resulted in the percentage of skipped events not being
+       displayed.
+
+   * mimage/MHillasCalc.cc
+     - Changed, in constructor, initialization of size of fErrors from
+       6 to 7, since there are 6 error codes (+ succesful operation)
+       for the Hillas calculations. 
+     - Changed in PostProcess calls to TestBit by calls to TestFlag. 
+       With TestBit, return value was always false and statistics of 
+       the Hillas calculations were never shown!
+
+
+
+ 2004/11/04: Markus Gaug
+
+   * macros/calibration.C
+     - updated comments
+
+
+
+ 2004/11/04: Abelardo Moralejo
+
+   * mmc/MMcConfigRunHeader.h
+     - Added member fMirrorFraction to keep the active fraction of the
+       mirror dish set in the camera simulation. Added Getter & Setter.
+       Added some comments. Update class version to 4.
+
+   * mmc/MMcRunHeader.[hxx,cxx]
+     - Removed member fTelesTheta, fTelesPhi. They make no sense since
+       telescope orientation can change from event to event in MC too.
+       Added getter and setter for fShowerThetaMin and fShowerThetaMax.
+
+   * mmontecarlo/MMcCollectionAreaCalc.[h,cc]
+     - Changed consistency check on MMcRunHeader.fTelesTheta to check
+       on fShowerThetaMin and fShowerThetaMax
+
+   * mfileio/MReadMarsFile.cc
+     - Removed obsolete check of old MC files, which needed the removed
+       data member MMcRunHeader.fTelesTheta.
+
+
+
+ 2004/11/04: Markus Gaug
+
+   * mjobs/MJPedestal.cc
+     - adapted to changes in MPedCalcFromLoGain
+
+
+
+ 2004/11/04: Nepomuk Otte
+
+   * mpedestal/MPedCalFromLoGain
+     - Class interface changed s. MPedCalcFromLoGain.cc
+     - It can now be searched for a signal in all slices 0..29 prior
+       pedestal extraction. This is recommended to do.
+
+
+
+ 2004/11/02: Abelardo Moralejo
+
+   * mfilter/MFSize.[h,cc]
+     - added. A filter to modify the Size spectrum of a sample through
+       cutting out events as a function of their Size.
+
+   * mfilter/Makefile, FilterLinkDef.h 
+     - added new class MFSize.
+
+   * mtemp/mpadova/macros/resize.C
+     - Added. Example of how to use the new filter.
+
+
+
+ 2004/11/01: Markus Gaug
+
+   * msignal/MExtractTimeAndChageDigitalFilter.cc
+     - delete the pointer to derivativelo and derivativehi at the end of 
+       the function
+     - reduce the effective number of high-gain samples (used for the 
+       calculation of the pedestal RMS in the calibration) from 6. to 
+       2.5
+
+
+
+ 2004/11/01: Markus Meyer and Keiichi Mase
+
+   * mmuon/MMuonCalibParCalc.[h,cc]
+     - changed according to Thomas Bretz's suggestion.
+       The main part of the calculation is moved from MMuonCalibPar to 
+       MMuonCalibParCalc.
+     - changed. The function of the UseCleanForWidth is removed since we found 
+       that we should get the Arc Width with uncleaned images.
+
+   * mmuon/MMuonCalibPar.[h,cc]
+     - changed according to Thomas Bretz's suggestion as written above.
+
+   * mmuon/MMuonSearchPar.[h,cc]
+     - changed according to Thomas Bretz's suggestion.
+       The pointer of the funciotn is changed to the reference.
+
+
+
+ 2004/11/01: Abelardo Moralejo
+
+   * mtemp/mpadova/macros/RanForestPD.C
+     - Just some cleaning up of old (commented) code.
+
+
+
+ 2004/11/01: David Paneque
+
+   * mtemp/mmpi/SupercutsONOFFClasses/MHFindSignificanceONOFF.cc
+     - Condition to assume a constant background in the fit 
+       of the ON and OFF data is softened: 
+	  1) Bins with zero content are allowed (if they are less than 10%
+	  of the total number of bins used). Yet their error is set to 
+	  a huge number 10E19; which means that they are not taken into account 
+	  in the fit.
+	  2) Maximum number of bins with low content (less than 9) is increased 
+	  from 5% to 20%. The error of these bins is set to 3.
+
+       The motivation of these changes is to allow the fitting procedures also 
+       in those cases where the background rejection is that large that very few 
+       events remain in the background region of the alpha plot. This situation 
+       is occuring quite often when using the Random Forest and SPECIALLY, when 
+       making large SIZE cuts.
+
+
+
+ 2004/10/30: Markus Gaug
+
+   * msignal/MExtractor.h
+   * msignal/MExtractTime.h
+     - set the version number by 1 higher due to the changes on 12.10.
+
+
+
+ 2004/10/29: Abelardo Moralejo
+
+   * mtemp/mpadova/macros/RanForestPD.C
+     - corrected an error which made a few hadrons get into the gamma
+       training sample.
+
+
+
+ 2004/10/28: Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed a bug which caused all files to be added and processed
+       twice
+
+   * mmuon/MMuonCalibParCalc.cc, mmuon/MMuonSearchParCalc.cc:
+     - changed output in PreProcess to fit standards
+
+   * mmuon/MMuonCalibPar.cc:
+     - changed title and axis-title of histograms to fit the Mars
+       titles better
+
+
+
+ 2004/10/26: Abelardo Moralejo
+
+   * mmc/MMcEvt.[hxx,cxx], MMcFadcHeader.hxx
+     - added new data members fFadcTimeJitter and fGainFluctuations for 
+       new camera simulation options. Updated class versions to 4 and 5 
+       respectively
+
+
+
+ 2004/10/22: Thomas Bretz
+
+   * callisto.cc, star.cc:
+     - commented out some checks which became obsolete with some new 
+       features. I'll think of a more convinient check in the future
+
+   * mbase/MDirIter.[h,cc]:
+     - added MakeRegexp which is used instead of TRegexp::MakeWildcard
+       to support better handling of regular expressions
+
+   * mbase/MRunIter.cc:
+     - a small simplification
+
+   * mbase/MStatusDisplay.cc:
+     - fixed a bug in CloseWindow (never use a data member after you 
+       delete 'this')
+
+   * mbase/MTaskEnv.cc:
+     - call ReadEnv also if task is the 'external' one
+
+   * mcalib/MCalibrateRelTimes.cc:
+     - check for unsuitability for run AND event
+
+   * mhist/MHCamera.cc:
+     - fixed the cases in which GetBinError returned NaN
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - implemented reading raw-data
+     - implemented new scheme to setup MDirIter by MSequence
+
+   * mjobs/MJCalibration.[h,cc]:
+     - fixed workaround
+     - implemented new scheme to setup MDirIter by MSequence
+
+   * mjobs/MJPedestal.cc:
+     - implemented new scheme to setup MDirIter by MSequence
+
+   * mjobs/MSequence.[h,cc]:
+     - changed SetupCalls to new scheme allowing to set the file type id
+
+   * mmain/MEventDisplay.cc:
+     - fixed a crash if file is invalid
+
+   * mraw/MRawFileRead.[h,cc]:
+     - replaced default name MRawFileRead by MRead to support MJ*
+     - added IsFileValid
+
+   * msignal/MExtractTime.cc:
+     - fixed call to base ReInit (return value was ignored)
+
+   * msignal/MExtractTimeAndCharge.[h,cc]:
+     - fixed some output
+     - added Print
+     - fixed call to base ReInit (return value was ignored)
+     - set Version Number to 1
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - added Print
+
+
+
+ 2004/10/21: Thomas Bretz
+
+   * star.cc:
+     - added a missing 'return -1'
+
+   * mbase/MLog.cc:
+     - expanded path before opening ofstream
+
+   * mfbase/MF.cc:
+     - added a comment
+
+   * mhbase/MH3.cc:
+     - fixed behaviour of projections in status-display
+
+   * mhflux/MHAlpha.cc:
+     - fixed TLatex output
+
+   * mhflux/MHFalseSource.[h,cc]:
+     - replaced cut in L/D by D/W (which is more physical)
+
+
+
+ 2004/10/21: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - fixed a bug occurring in the case that the colour changes in one 
+       same MRunIter. Returns now kFALSE instead of kCONTINUE
+
+
+
+ 2004/10/20: Thomas Bretz
+
+   * msignal/MExtractTimeFastSpline.cc:
+     - fixed a compiler warning: Unused variable
+
+   * mjob/MJPedestal.cc:
+     - added "DisableOutput" as a resource option
+
+   * mbase/MArrayF.h:
+     - added a new Reset(Float_t) member function
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]:
+     - enrolled some if-else blocks
+     - fixed includes
+     - enhanced error handling when a file is read
+     - moved output from PostProcess to PreProcess
+     - fixed and enhanced ReadEnv
+
+   * mjob/MJCalibrateSignal.cc:
+     - enabled variance display for tabs showing signal
+
+   * mhist/MHCamera.cc:
+     - fixed returning GetBinError for kProfile mode switched on
+
+   * mbase/MDirIter.cc:
+     - fixed a bug in the Sort function: AddDirectory was incorrectly used
+
+
+ 2004/10/20: Markus Gaug
+
+   * msignal/MExtractTimeAndChargeSpline.cc
+     - fixed a small bug concerning the way the second derivatives are 
+       calculated. The effect is less than 1% on the time resolution
+
+   * msignal/MExtractTimeFastSpline.cc
+     - comment the search for the half maximum and use the maximum again. 
+       The half maximum fails sometimes by 0.5 slices which seems to be 
+       some intrinsic behavior of the calibration pulses. 
+       The maximum seems to be OK, though. 
+
+
+
+ 2004/10/19: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - adapted to latest version of Camera simulation, which for stereo
+       configurations creates one MMcConfigRunHeader per telescope,
+       instead of a single one, as it used to be. So now we add the
+       serial number when looking for the container in ReInit.
+
+
+
+ 2004/10/12: Markus Gaug 
+
+   * msignal/MExtractor.h, msignal/MExtractTime.h
+     - put fOffSetLoGain from MExtractTime to MExtractor. Like this, it 
+       is accessible for all extractor classes.
+
+
+
+ 2004/10/12: Abelardo Moralejo
+
+   * mmc/Mdefine.h
+     - Removed #define FADC_SLICES (was duplicated)
+
+   * mmc/MTriggerDefine.h, MFadcDefine.h
+     - Changed names of a few #defines used by the camera simulation 
+       code, to make their meanings clearer.
+
+
+
+ 2004/10/12: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+     - fixed documentation of data members
+     - implemented option kNoStorage for neither reading nor writing 
+       the F0-files to disk.
+
+   * mjobs/MJCalibration.[h,cc]
+     - implemented option SetTimeAndCharge() in order to use the 
+       extractor deriving from MExtractTimeAndCharge, like e.g. the 
+       digital filter.
+
+   * mhcalib/MHCalibrationCam.cc
+     - fixed a bug in the binning of the low-gain events, affected 
+       the relative times in case of high-gain saturation.
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - fix the range for the low-gain extraction dynamically by 
+       using the calculated time of the high-gain extraction. This 
+       should solve the problem reported by Nuria for the extractors
+       deriving from this class.   
+
+
+
+ 2004/10/11: Markus Gaug
+
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - calculate addtionally to the usual pedestal the ABOffset, like 
+       in MPedCalcFromLoGain. 
+
+   * msignal/MExtractTimeAndChargeSpline.[h,cc]
+     - fixed class documentation and some last bugs.
+
+   * msignal/MExtractTimeAndChargeSlidingWindow.[h,cc]
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+     - the combined extractor class sliding window and highest integral
+       with pedestal-AB-flag corrected, to be used for the TDAS-extractor
+
+
+
+ 2004/10/08: Markus Meyer and Keiichi Mase
+ 
+   * mmuon/MMuonSearchPar.[h,cc], mmuon/MMuonCalibPar.[h,cc],
+     - changed according to Thomas's suggestion. The main changes are the
+       followings;
+        1. The parameter name is changed in order to make the name self
+           descriptive.
+        2. The version come back to 1.
+        3. The TH1 objects are changed to pointers.
+        4. The fixed value of the pre cuts now can be set by yourself.
+
+   * mmuon/MMuonSearchParCalc.[h,cc], mmuon/MMuonCalibParCalc.[h,cc],
+     - added. In principle, you can work out, but these classes has to be
+       checked by Thomas. Therefore, remind that this class may be changed.
+
+
+
+ 2004/10/08: R. DelosReyes
+
+  * mbase/MRunIter.h
+    - changed the name of the Sort() function name by SortRuns() 
+      to avoid conflicts with the Sort() function in the MDirIter class.
+
+
+
+ 2004/10/07: Markus Gaug
+
+  * mhcalib/MHCalibrationRelTimeCam.[h,cc]
+    - uncommented the Clone() function (which otherwise causes 150MB to 
+      be cloned). It is from now on working exactly equal like in 
+      MHCalibrationChargeCam which behaved fine until now. 
+
+  * mpedestal/MPedCalcFromLoGain.cc
+    - fixed the case that a window size of 1. is handed over which 
+      previously set the window size to the next smaller even number, 
+      which is 0. Now, it sets it to 2. This makes this class usable 
+      together with the amplitude spline.
+       
+  * msignal/MExtractTimeAndChargeSpline.[h,cc]
+    - combined extractor: MExtractTimeFastSpline 
+      and MExtractAmplitudeSpline, to be used like Hendrik's filter, 
+      i.e. in combination with: MJCalibration::SetTimeAndCharge()
+
+
+
+ 2004/10/06: Hendrik Bartko
+
+  * msignal/cosmics_weights4.dat
+    - new weights file using 4 slices for the digital filter
+
+
+
+ 2004/10/05: Markus Gaug
+   
+  * mcalib/MCalibrationChargePix.[h,cc]
+  * mcalib/MCalibrationChargeCalc.cc
+    - after talking with Florian, we reduced the electronic noise for the 
+      low-gain pedestal calculation from 1.5 to 1.0, independent from
+      inner or outer pixels. 
+    - additionally found a small bug in the calculation of the low-gain 
+      pedestal RMS which amounts to about the same size as the difference 
+      in the assumed electronic noise.
+
+  * mcalib/MCalibrationChargeCalc.cc
+    - fixed small bug for the case that multiple colours are found, but 
+      no intensity calibration is used.
+
+  * msignal/MExtractTimeAndCharge.cc
+    - fixed small bug in the calculation of the low-gain AB flag.
+
+  * mcalib/MCalibrateData.cc
+    - fixed bug nr. ID 144
+
+
+
+ 2004/10/05: Thomas Bretz
+
+   * mjobs/MJStar.cc:
+     - removed rate cut from eventloop because its highly untested and
+       unstable
+
+   * macros/tar.C:
+     - removed mtemp-directory from tarball
+
+   * macros/rootlogon.C, macros/dohtml.C:
+     - added mmuon
+     - added mtrigger
+     - added mhflux
+
+
+
+ 2004/10/05: Markus Meyer and Keiichi Mase
+ 
+   * mmuon/MMuonSearchPar.[h,cc], mmuon/MMuonCalibPar.[h,cc],
+     mmuon/Makfile, mmuon/MuonLinkDef.h, mmuon/MuonIncl.h:
+     - added: Finally our muon classes are merged and commited.
+       These are container classes and will not work only by themselves.
+       After Thomas's check, we will commit the task classes, then
+       you can use it.
+
+
+ 2004/10/04: Markus Gaug 
+ 
+   * mjobs/MJPedestal.h
+     - added function SetPedContainerName() 
+
+
+
+ 2004/10/04: Hendrik Bartko
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.cc
+     - fixed a bug in the weights calculation
+
+
+
+ 2004/10/01: Thomas Bretz
+
+   * mcalib/MCalibrationChargeCalc.cc, 
+     mcalib/MCalibrationRelTimeCalc.cc,
+     mhcalib/MHCalibrationChargeCam.cc.
+     mhcalib/MHCalibrationRelTimeCam.cc:
+     - changed some output to fit into a standard 80-col
+       console
+
+   * mhist/MHCamEvent.[h,cc]:
+     - added the option to count 'above threshold'
+       (former MHTrigger)
+
+   * mhist/MHCamEventRot.[h,cc]:
+     - added the option to count 'above threshold'
+
+   * mhist/MHCamera.[h,cc]:
+     - fixed filling of thresholded events (CntCamContent)
+       such that it takes the 'used'flag into account
+
+   * mjobs/MJStar.cc:
+     - added plots showing how often a pixel survived image 
+       cleaning and the corresponding derotated 2D plot
+
+   * mjobs/MJCalibrateSignal.cc:
+     - display in all plots in which we expect a stable value
+       the variance instead of the rms
+
+   * mjobs/MJPedestal.cc, mjobs/MJCalibration.cc:
+     - fixed usage of raw-data files and AddDatRuns
+
+   * mjobs/MJob.cc:
+     - fixed a typo in an output
+
+   * callisto.cc:
+     - removed "-mc" option (now autodetected)
+       --> to be done in the other jobs, too
+
+   * mfileio/MRead.[h,cc], mfileio/MReadMarsFile.[h,cc],
+     mfileio/MReadTree.[h,cc], mjobs/MJCalibrateSignal.[h,cc],
+     mraw/MRawFileRead.[h,cc]:
+     - implemented IsFileValid as a first step to file auto-detection
+
+
+
+ 2004/09/30: Hendrik Bartko, Markus Gaug
+
+   * msignal/MExtractFixedWindowSpline.cc
+     - corrected a small bug for the case that the high-gain extraction 
+       window ranges into the low-gain
+
+   * mjobs/MJPedestal.cc
+     - use MPedCalcFromLoGain if IsUseData() is set
+
+
+
+ 2004/09/29: Hendrik Bartko, Diego Tescaro, Markus Gaug
+
+   * msignal/MExtractTimeAndChargeDigitalFilter.[h,cc]
+     - Hendriks digital filter finally implemented
+
+   * msignal/cosmics_weights.root msignal/calibration_weights_UV.root
+     - needed weights for the digital filter
+
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+     - added MExtractTimeAndChargeDigitalFilter and 
+       MExtractTimeAndCharge
+
+   * msignal/MExtractTime.h
+     - made PreProcess, ReInit and Process protected
+
+   * msignal/MExtractTimeAndCharge.[h,cc]
+     - added variable abflag in function FindTimeAndChargeHiGain and 
+       FindTimeAndChargeLoGain
+
+
+
+ 2004/09/29: Thomas Bretz
+
+   * mhist/MHEvent.[h,cc]:
+     - enhanced display
+
+   * mmain/MEventDisplay.cc:
+     - adapted to changes in MEventDisplay
+
+
+
+ 2004/09/28: Thomas Bretz
+
+   * mbase/MGMap.h:
+     - added Clear() function
+
+   * mfileio/MReadReports.[h,cc]:
+     - added GetReader member function
+
+   * mhbase/MBinning.h:
+     - set a default for a constructor argument
+
+   * mhbase/MH.cc:
+     - do not treat errors when enhancing histograms
+       if errors are not set
+
+   * mhflux/MHEffectiveOnTime.cc:
+     - changed conditions for fit:
+       + 5% - 95%  --->  60% - 99%
+       + start value 200Hz
+       + ok if chi2<3*NDF
+     - resturn chi2 as result of fit
+     - changed some text output in pads
+
+   * mhflux/MHFalseSource.cc:
+     - made work without MPointingPos
+     - fixed crash if star-display is used
+     - fixed dissapearing alpha plot
+
+   * mhist/MHCamEvent.[h,cc]:
+     - removed rms histogram
+     - enhanced display
+     - fixed handling of title
+
+   * mhist/MHCamera.[h,cc]:
+     - simplified projection functions a bit
+     - simplified profile functions a bit
+     - added default for binning
+     - added binning to Profiles
+
+   * mimage/MConcentration.c:
+     - fixed author list
+
+   * mimage/MHHillas.cc:
+     - display size as logy
+
+   * mimage/MHHillasExt.cc, mimage/MHHillasSrc.cc:
+     - fixed binnings
+     - removed obsolete pad->Update in Draw
+
+   * mimage/MHImagePar.cc:
+     - fixed setting of log-scale
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed histogram titles and axis titles
+
+   * mjobs/MJStar.cc:
+     - added EventRate cut which cuts out events with extremely
+       changing rates
+
+   * mmain/MEventDisplay.cc:
+     - unlock event display
+
+   * msignal/MArrivalTime.cc:
+     - fixed GetPixelContent
+
+   * mastro/MAstroCamera.cc:
+     - replaced "unknown" by "n/a"
+
+   * mbase/MDirIter.[h,cc]:
+     - added Sort function (not yet fully tested)
+
+   * mgeom/MGeomCam.cc:
+     - removed automatic setting of ReadyToSave in constructor
+       PLEASE contact me if you have trouble with this
+
+   * mraw/MRawFileRead.cc:
+     - SetReadyToSave for run-header after reading
+
+   * msignal/MExtractSlidingWindow.cc:
+     - fixed ReInit-output
+
+
+
+ 2004/09/28: Raquel de los Reyes
+
+   * mbase/MRunIter.cc
+     - Changes in the AddRun function to read the old and the new DAQ 
+       numbering format. Changes took place between runs 35487 and 
+       00035488 (2004_08_30)
+
+
+
+ 2004/09/27: Abelardo Moralejo
+
+   * mtemp/mpadova/macros/plotnoise.C
+     - Added. Macro to compare the piled-up signals for many pixels and
+       events together, intended to check the noise fluctuations.
+
+
+
+ 2004/09/23: Markus Gaug
+ 
+   * mhcalib/MHCalibration*Cam.[h,cc]
+     - replaced the TObjArrays by TOrdCollections because the TObjArrays
+       do not enter the streamer. In case, the histograms want to be 
+       stored, need to use an TOrdCollection, instead, like in the 
+       MCalibration*Cam classes. 
+     - simplified the naming of the histograms somewhat
+
+   * msignal/MExtractBlindPixel.[h,cc]
+     - added enum DataType_t to set in which MRawEvtData container the 
+       blind pixel is found. The container of the blind pixel has changed 
+       from MRawEvtData to MRawEvtData2
+
+   * mcalib/MCalibrationBlindCam.[h,cc]
+     - added function SetPulserColor which was only available in 
+       MCalibrationBlindPix. 
+
+   * mcalib/MCalibrationChargeBlindCam.[h,cc]
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - removed the two classes since obsolete
+
+   * mcalib/MCalibrationCam.h
+     - make SetPulserColor virtual
+
+   * mcalib/MCalibrationQECam.[h,cc]
+     - added new functions to display cornings vs. quantum efficiencies
+
+   * mcalib/MCalibrationQEPix.cc
+     - changed transmission probability of plexiglass from 0.96 to 0.92
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - added a CallPostProcess() function in order to avoid setting 
+       back the fPreProcessed flag which otherwise impedes the linearity
+       calibration to be performed
+
+   * mhcalib/MHGausEvents.[h,cc]
+     - added function SimulateGausEvents()
+
+
+
+ 2004/09/23: Abelardo Moralejo
+   * mtemp/mpadova/macros/area.C, RanForestPD.C, gammarate.C
+     - Added
+
+   * macros/starmc.C
+     - Added some missing RunHeaders in the output
+
+
+
+ 2004/09/19: Thomas Bretz
+
+   * mbadpixels/MBadPixlesCam.[h,cc]:
+     - added Reset-function. This makes sure, that the event-wise
+       bad pixels determined by MBadPIxelsCalc are deleted after
+       one execution of the event-loop and don't remain for all
+       following data
+
+   * mpointing/MPointingPos.cc, mreport/MReportDrive.cc:
+     - initialize the variables in the constructor
+
+
+
+ 2004/09/17: Markus Gaug
+
+   * mjobs/MJCalibration.[h,cc]
+     - introduced two flags to avoid storage of containers or to 
+       store also the histogram containers. Default is like it always
+       was. 
+
+
+
+ 2004/09/17: Thomas Bretz
+
+   * mhcalib/MH*.[h,cc]:
+     - redone some changes from yesterday - for unknown reason they
+       were lost
+
+   * mbase/MTask.cc:
+     - make sure that the correct number of executions is returned
+       counter which cannot be reset properly)
+     - added GetNumExecutionsTotal
+
+   * mdata/MDataArray.cc:
+     - some changes to Print-output
+
+   * mfbase/MF.[h,cc]:
+     - added GetRule
+
+   * mfileio/MReadTree.cc:
+     - some improvements to output
+
+   * mhbase/MHMatrix.cc:
+     - some improvements in Print
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - calculate the significance also from the first bins
+     - added Copy
+     - added print
+
+   * mhflux/MHAlpha.[h,cc]:
+     - added some fFit.Print to keep track of what's going on
+     - give a name to the function, no name results in weired
+       behaviour of the whole system. root people were already informed
+
+   * mhflux/MHFalseSource.cc:
+     - made lines of 2D-Gauss smaller
+
+   * star.cc:
+     - fixed handling of commandline arguments in batch mode
+
+   * mhist/MHEvent.[h,cc], mmain/MEventDisplay.cc:
+     - remove non working signal/ped rms
+
+
+
+ 2004/09/16: Abelardo Moralejo
+
+     WARNING: Today 16/9, between 19.00 and 20.00 aprox, I accidentally 
+     removed and/or changed some classes in mbase/ while updating the 
+     camera simulation code in the CVS. I have put back everything to
+     its original status as soon as I realized this. I am sorry! You 
+     may have encountered compilation problems if you downloaded Mars 
+     during that period. Everything should be OK now, please report
+     otherwise.
+
+
+
+ 2004/09/16: Markus Gaug
+
+   * mhcalib/MHCalibrationChargeBlindPix.cc
+   * mhcalib/MHGausEvents.cc
+     - added call to gROOT->GetListOfFunctions->Remove(f) in destructor
+
+   * mhcalib/MHCalibrationBlindCam.[h,cc]
+     - re-installed the Clone-function. Without, DrawClone() does not 
+       Clone()
+
+
+
+ 2004/09/16: Thomas Bretz
+
+   * mimage/MHillasCalc.[h,cc]
+     - removed obsolete PrintSkipped
+
+   * mhbase/MH.cc, mfilter/MFDeltaT.cc:
+     - Form %5.1 when printing statistics
+
+   * mfilter/MFDeltaT.cc:
+     - enhaced filter criterias
+
+   * mbase/MTime.h:
+     - added IsMidnight
+
+   * mbase/MTask.cc:
+     - changed setw(3) to Form %5.1f
+
+   * mjobs/MJCalibration.[h,cc]:
+     - set default to 'nice' data-check display
+     - removed obsolete FindColor
+
+   * mjobs/MJPedestal.cc:
+     - enhanced output
+
+   * mjobs/MJob.cc:
+     - small changes to output
+
+   * mhflux, mhflux/Makefile, mhflux/FluxLinkDef.h mhflux/FluxIncl.h:
+     - added
+
+   * mhist/MHFalseSource.[h,cc], mhist/MHAlpha.[h,cc], 
+     mhist/MHEffectiveOnTime.[h,cc]:
+     - moved to mhflux
+
+   * mhflux/MAlphaFitter.[h,cc]:
+     - added
+
+   * Makefile:
+     - added mhflux
+
+   * mhist/MHEffOnTimeTime.[h,cc], mhist/MHEffOnTimeTheta.[h,cc],
+     mhist/MHEffOnTime.[h,cc], mhist/MHTimeDiffTime.[h,cc],
+     mhist/MHTimeDiffTheta.[h,cc], mhist/MHFalseSource.[h,cc], 
+     mhist/MHAlpha.[h,cc], mhist/MHEffectiveOnTime.[h,cc]:
+     - removed
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MHEffectiveOnTime
+     - removed MHAlpha
+     - removed MHFalseSource
+     - removed MHFlux (temporary until adapted to MHEffectiveOnTime)
+     - removed MHEffOnTimeTime  (use MHEffectiveOnTime instead)
+     - removed MHEffOnTimeTheta (use MHEffectiveOnTime instead)
+     - removed MHEffOnTime      (use MHEffectiveOnTime instead)
+     - removed MHTimeDiffTime   (use MHEffectiveOnTime instead)
+     - removed MHTimeDiffTheta  (use MHEffectiveOnTime instead)
+     * If you need help to get MHEffectiveOnTIme working please ask me!
+
+   * star.rc:
+     - use scaled image cleaning by default
+
+   * mmontecarlo/MMcCollectionAreaCalc.cc:
+     - fixed some possible crashes
+
+   * mhflux/MAlphaFitter.h:
+     - remove function from global list
+
+   * mhflux/MHFalseSource.cc:
+     - added a 2D Gauss-Fit
+
+   * mimage/MHillasSrc.[h,cc]:
+     - fixed a bug in the output of DCA (wrong units)
+
+   * mhcalib/MHCalibrationChargeBlindCam.[h,cc],
+     mhcalib/MHCalibrationChargeBlindPix.cc,
+     mhcalib/MHCalibrationChargeCam.[h,cc],
+     mhcalib/MHCalibrationChargePINDiode.[h,cc],
+     mhcalib/MHCalibrationRelTimeCam.[h,cc],
+     mhcalib/MHGausEvents.[h,cc]:
+     - took out the Clone-functions. Everything here seems to be
+       a lot more stable without. I guess it is due to the change
+       away from the TClonesArrays which makes the automatic
+       streamed cloning work fine.
+     - moved the removing of TF1 from the destructor to the 
+       allocation of the objects. It seems that already before the
+       destructor can remove the objects from these list 'shit happens'
+
+
+
+ 2004/09/15: Thomas Bretz
+
+   * callisto.rc:
+     - added new line for intensity calibration
+     - fixed MJPedestalY.ExtractPedestal.PedestalUpdate (should be 'no')
+     
+   * mbase/MEvtLoop.cc:
+     - changed such that returning kCONTINUE in MTaskList::Process
+     is allowed
+
+   * mbase/MTaskList.cc:
+     - changed to return kCONTINUE if Task returned kCONTINUE
+
+   * mcalib/MCalibrate.cc, mcalib/MCalibrationChargeCalc.cc:
+     - cosmetics to output
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - added an output/skip in case more than 90% of all pixels have
+       been skipped
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - fixed to read the MJCalibration output
+     - simplified reading container
+
+   * mjobs/MJCalibration.[h,cc]:
+     - simplified writing container
+
+   * mjobs/MJob.[h,cc]:
+     - added WriteContainer
+     - added ReadContainer
+
+   * mpedestal/MPedCalcFromLoGain.cc:
+     - initialize default number of dump events (500)
+     - log status of task in PreProcess
+
+   * mimage/MHillasSrcCalc.cc:
+     - fixed
+     - THE USE OF THIS TASK IS DEPRICATED. PLEASE USE MHillasCalc INSTEAD!!!
+
+   * mimage/MHillas.cc:
+     - enhanced Paint
+
+
+
+ 2004/09/15: Markus Gaug
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - replaced TArrays by MArrays
+     - added Copy function
+
+   * mcalib/MCalibration*Cam.[h,cc]
+     - replace TObjArray by TOrdCollection, otherwise the streamer does not work
+
+   * mimage/MHillasCalc.[h,cc]
+     - move PrintSkipped(int,const char*) to PrintSkipped(UInt_t, const char*)
+       otherwise always warnings about hidden function from MTask
+  
+   * mjobs/MJCalibration.cc
+     - data check plot for the rel. time calibration
+
+   * mhcalib/MHCalibrationCam.cc
+     - set MBadPixelsPix::kLoGainNotFitted only if High-Gain Saturation
+       had occurred. 
+
+   * mhcalib/MHCalibrationChargeCam.cc
+   * mcalib/MCalibrationChargeCalc.cc
+     - simply calls to IntensityCam somewhat
+
+   * mcalib/MCalibrationBlindCam.[h,cc]
+     - added function GetFluxInsidePlexiglass() and variances
+
+
+
+ 2004/09/15: Abelardo Moralejo
+
+   * macros/starmc.C, mccalibrate.C, starmc2.C
+     - adapted to changes in MHillasCalc from August 23. The macros
+       did no longer work, but only today did someone report it... 
+       Sorry!
+
+
+
+ 2004/09/14: Antonio Stamerra
+
+   * mtrigger/MTriggerIPR.h:
+     - added "=" to (idx >= gsNTrigPix) in GetPixelContent
+
+   * macros/readIPR.C:
+     - new macro to read and display the IPRs
+
+   * macro/dohtml.C:
+     - added readIPR
+		
+
+
+
+ 2004/09/14: Markus Gaug
+
+   * mcalib/MCalibChargeCalc.[h,cc]
+     - added IntensityBadPixelsCam and IntensityQECam
+
+   * mhcalib/MHCalibration*Cam.[h,cc]
+   * mcalib/MCalibColorSteer.[h,cc]
+     - added MBadpixelsIntenstiyCam
+
+   * mbadpixels/MBadPixelsIntensityCam.[h,cc]
+   * mcalib/MCalibrationIntensity*Cam.[h,cc]
+   * mcalib/MCalibration*Cam.[h,cc]
+     - replace TClonesArray by TObjArray
+
+   * mjobs/MJCalibration.cc
+     - took out FindColor() which is now taken care of by 
+       MCalibColorSet
+     - introduced MBadPixelsIntensityCam
+
+   * mhcalib/MHGausEvents.cc
+     - some changes in Draw for the case that there is no histogram
+
+   * manalysis/MHPedestalPix.[h,cc]
+   * manalysis/MHPedestalCam.[h,cc]
+     - moved to mpedestal/
+
+   * mpedestal/PedestalLinkDef.h
+   * msignal/SignalLinkDef.h
+     - replaced some '++' by '+'s.
+
+   * mhbase/MH.cc
+     - removed an infinite loop created some hours before.
+
+   * mhcalib/MHGausEvents.[h,cc]
+     - put fEventFrequency back from MHCalibraionPix.
+     - always delete fHPowerProbability, if existing. 
+ 
+   * mhcalib/MHCalibrationPix.[h,cc]
+     - take out fEventFrequency
+
+
+
+ 2004/09/14: Thomas Bretz
+
+   * mbase/MFilter.[h,cc]:
+     - added PrintSkipped
+
+   * mbase/MTask.[h,cc]:
+     - added PrintSkipped
+
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MFDeltaT
+
+   * mhbase/MFillH.[h,cc]:
+     - added forwarding of number of executions
+
+   * mhbase/MH.[h,cc]:
+     - simplified the new Projection functions
+     - added PrintSkipped
+     - increased ClassDef version number to 2
+
+   * mhcalib/HCalibLinkDef.h:
+     - removed second + from MHGausEvents
+
+   * mjobs/MJCalibration.cc:
+     - fixed a comment
+
+   * mjobs/MJStar.cc:
+     - added MFDeltaT
+
+   * mpedestal/MPedCalcFromLoGain.cc: 
+     - fixed a typo in a comment
+
+
+ 
+ 2004/09/13: Antonio Stamerra
+
+   * mtrigger/MTrigger*.h:
+     - removed inheritance from MCamEvent (except MTriggerIPR).
+     - Added Get... functions to retrieve the data members
+
+   * mreport/MReportTrigger.[h,cc]
+     - added fTriggerTable, fL1(L2)Triggertable to the data members
+
+
+
+ 2004/09/13: Markus Gaug 
+  
+   * mjobs/MJCalibration.[h,cc]
+     - added MCalibrationIntensityBlindCam
+     - replaced MCalibrationChargeBlindCam by MCalibrationBlindCam
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - added Copy function
+
+   * mcalib/MCalibrationIntensityBlindCam.[h,cc]
+     - new class for Intensity calibration
+
+   * mcalib/MCalibrationBlindCam.[h,cc]
+   * mcalib/MCalibrationBlindPix.[h,cc]
+     - new containers based on MCalibrationCam and MCalibrationPix. 
+     - similiar to MCalibrationChargePix and MCalibrationChargeCam, but 
+       slightly different data members. In order not to get confused with
+       already stored data, this is for the moment a second, equivalent 
+       class. 
+  
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - added Intenisty Calibration for blind pixel
+     - take new MCalibrationBlindCam instead of MCalibrationChargeBlindCam
+
+   * mcalib/MCalibrationCam.cc
+   * mcalib/MCalibrationChargeCam.cc
+   * mcalib/MCalibrationQECam.cc
+   * mcalib/MCalibrationRelTimeCam.cc
+     - initialize fAverageBadPixels in derived classes
+
+   * mhcalib/MHCalibrationChargeBlindCam.[h,cc]
+   * mhcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - derive class from MHCalibrationCam now and treat pointers 
+       like done in MHCalibrationChargeCam
+     - implement Intensity Calibration
+     - write results to MCalibrationBlindCam instead of 
+       MCalibrationChargeBlindCam 
+
+   * mhcalib/MHCalibrationCam.h
+     - took out the "->" for all pointers
+     - introduce new steering flags: 
+       kLoGain, kOscillations, kAverageing, kSizeCheck
+
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+     - wrote a ReadEnv function
+
+   * mbase/MFilter.[h,cc]:
+     - added PrintSkipped
+
+   * mbase/MTask.[h,cc]:
+     - added PrintSkipped
+
+   * mfilter/FilterLinkDef.h, mfilter/Makefile:
+     - added MFDeltaT
+
+   * mhbase/MFillH.[h,cc]:
+     - added forwarding of number of executions
+
+   * mhbase/MH.[h,cc]:
+     - simplified the new Projecttion functions
+     - added PrintSkipped
+     - increased ClassDef version number to 2
+
+   * mhcalib/HCalibLinkDef.h:
+     - removed second + from MHGausEvents
+
+   * mjobs/MJCalibration.cc:
+     - fixed a comment
+
+   * mjobs/MJStar.cc:
+     - added MFDeltaT
+
+   * mpedestal/MPedCalcFromLoGain.cc: 
+     - fixed a typo in a comment
+
+
+
+ 2004/09/13: Thomas Bretz
+
+   * merpp.cc:
+     - added MTrigger* containers to output
+
+   * mastro/MAstro.[h,cc]:
+     - added member function GetDistOnPlain
+
+   * mbase/MDirIter.[h,cc]:
+     - renamed Check to CheckEntry
+
+   * mbase/MMath.[h,c]:
+     - added functions for parabolic interpolation
+
+   * mbase/MStatusArray.[h,cc]:
+     - added functions to access contents
+
+   * mhbase/MBinning.[h,cc]:
+     - added RemoveFirstEdge
+     - added RemoveLastEdge
+     - removed some obsolete const-casts
+
+   * mhbase/MH.[h,cc]:
+     - added RemoveFirstBin
+
+   * mhist/MHEffectiveOnTime.[h,cc]:
+     - fixed number of bins
+     - remove first edge when finalizing
+     - added plots for lambda and NDF
+
+   * mjobs/MJStar.cc:
+     - removed a duplicate line
+
+   * mpointing/MPointing.[h,cc]:
+     - added support for TVector3
+     - added ClassDef and ClassImp for AltAz
+     - added ClassDef and ClassImp for ZdAz
+
+   * mpointing/MSrcPosFromModel.[h,cc]:
+     - changed to directly calculate the source position 
+       from a pointing model
+
+   * mpointing/PointingLinkDef.h:
+     - added AltAz
+     - added ZdAz
+     
+   * mreport/MReportTrigger.[h,cc]:
+     - removed '!' from data members
+     - increased ClassDef to 2
+
+   * mstarcam/MStarCamTrans.cc:
+     - added a single line of comment
+
+   * mtrigger/MTrigger*.[h,cc]:
+     - updated class description and title
+
+   * mcalib/MCalibrationCam.h:
+     - removed -> from fPixels, fAverageArea/Sectors
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - small changes to output
+     - simplification of an if-else block
+
+   * mcalib/MCalibrationIntensityCam.cc:
+     - removed double deletion of fCams - caused a crash
+
+   * mcalib/MCalibrationIntensityCam.h:
+     - removed -> from fCams
+
+   * mcalib/MCalibration*.h:
+     - removed some obsolete (empty) destructors
+
+   * mastro/MVector3.[h,cc]:
+     - added from MAstroCatalog
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - removed MVector3
+
+   * mastro/Makefile:
+     - added MVector3
+
+
+
+ 2004/09/11: Markus Gaug
+ 
+   * mbase/MArray.[h,cc]
+     - moved function StripZeros(TArrayD &arr) to MArrayD
+     - moved function StripZeros(TArrayF &arr) to MArrayF
+
+   * mbase/MArrayD.[h,cc]
+     - new function StripZeros() 
+
+   * mbase/MArrayF.[h,cc]
+   * mbase/Makefile
+   * mbase/BaseLinkDef.h
+     - new class analogously to MArrayD
+
+   * mhbase/MH.[h,cc]
+     - added functions ProjectArray(MArrayD,...) 
+       and ProjectArray(MArrayF,...)
+
+   * mtools/MFFT.[h,cc]
+     - added functions:
+	  MArrayF* PowerSpectrumDensity(const MArrayI *array);  
+	  MArrayF* PowerSpectrumDensity(const MArrayF *array);
+	  MArrayD* PowerSpectrumDensity(const MArrayD *array);
+
+   * mhcalib/MHGausEvents.[h,cc]
+     - made fEvents an MArrayF
+
+   * mhcalib/MHCalibrationPix.[h,cc]
+     - changed function name SetSaturated to AddSaturated
+
+   * mhcalib/MHCalibrationChargeCam.cc
+   * mhcalib/MHCalibrationRelTimeCam.cc
+     - take cloning of averaged sectors out of the Clone() function
+
+   * mbadpixels/MBadPixelsIntensityCam.[h,cc]
+   * mbadpixels/Makefile
+   * mbadpixels/BadPixelsLinkDef.h
+     - new class for the intensity calibration
+
+
+
+ 2004/09/10: Markus Gaug
+
+   * mhcalib/
+   * mcalib/
+     moved all MHCalibration* classes to new directory mhcalib/
+
+   * mhcalib/MHCalibrationCam.[h,cc]
+     - New base function InitHiGainArrays and InitLoGainArrays
+       Initializing the histograms in a standard way
+     - ReadEnv: added NBins, First and Last
+
+   * mhcalib/MHCalibrationRelTimeCam.[h,cc]
+   * mhcalib/MHCalibrationChargeCam.[h,cc]
+   * mhcalib/MHCalibrationTestCam.[h,cc]
+   * mhcalib/MHCalibrationTestTimeCam.[h,cc]
+     - use new functions InitHiGainArrays and InitLoGainArrays
+ 
+   * mhcalib/MHCalibrationRelTimePix.[h,cc]
+   * mhcalib/MHCalibrationTestPix.[h,cc]
+   * mhcalib/MHCalibrationTestTimePix.[h,cc]
+     - removed
+
+
+
+ 2004/09/10: Antonio Stamerra
+
+   * mreport/MReportTrigger.[h,cc]:
+     - updated to read IPRs and to fill MTrigger{xxx} containers
+
+   * mreport/Makefile:
+     - added include for mtrigger   
+
+   * Makefile:
+     - added mtrigger directory
+
+   * NEWS:
+     - updated
+
+
+
+ 2004/09/10: Thomas Bretz
+
+   * mhist/MHCamera.cc:
+     - removed some obsolete const_casts
+     - fixed an (un)signed comparison warning
+
+   * mbase/MArray*.h:
+     - added const &operator[](UInt_t i) const
+
+   * mhist/MHEffectiveOnTime.[h,cc]:
+     - changed to support variable bin-sizes in time to keep
+       the statistic per bin constant
+
+   * mhbase/MBinning.[h,cc]:
+     - added function to enhance the number of bins by one
+
+   * mbase/MTime.[h,cc]:
+     - added function to add one NanoSecond
+
+   * mjobs/MJStar.cc:
+     - removed Histogram of effective on-time vs time
+
+   * mhist/Makefile, mhist/HistLinkDef.h:
+     - added MHEffectiveOnTime
+
+   * mhbase/MH3.[h,cc]:
+     - fixed a bug in SetupFill which was introduced when I allowed
+       set the axis titles from the object title
+     - added support for unique-profile names
+
+   * Makefile:
+     - added new dir mhcalib
+
+   * mhcalib/HCalibIncl.h:
+     - added - was missing
+
+   * mcalib/CalibLinkDef.h:
+     - fixed some typos
+
+
+
+ 2004/09/09: Markus Gaug
+ 
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - initialize bins directly here. Remove MHCalibraitonChargeHiGainPix
+       and MHCalibrationChargeLoGainPix classes
+
+   * mcalib/MHCalibrationChargeHiGainPix.[h,cc]
+   * mcalib/MHCalibrationChargeLoGainPix.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - removed first two classes
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - make default for GetNumUnsuitable and GetNumUnreliable
+
+   * mcalib/MCalibrationIntensityCam.[h,cc]
+   * mcalib/MCalibrationIntensityChargeCam.[h,cc]
+   * mcalib/MCalibrationIntensityQECam.[h,cc]
+   * mcalib/MCalibrationIntensityRelTimeCam.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new classes for the intensity calibration. First is base class, 
+       other derive from it.
+
+   * mcalib/MHGausEvents.[h,cc]
+   * mcalib/MHCalibrationPix.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - put typical calibration members into new base class MHCalibrationPix
+       and leave only typical Gaussian behaviour members in MHGausEvents.
+     - all MHCalibration*Pix classes derive now from MHCalibrationPix
+
+   * mcalib/MHCalibrationCam.[h,cc]
+     - operators return MHCalibrationPix instead of MHGausEvents
+     - new function ResetHists() needed by MCalibColorSteer
+     - removed TArrayI *Overflow.
+       
+   * mcalib/MCalibColorSet.[h,cc]
+     - finished
+
+   * mcalib/MCalibColorSteer.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new task to be executed before the calibration tasks. Steers the 
+       occurrance of multiple intensities and the new *Intensity* 
+       containers
+
+   * mcalib/MHCalibrationChargePix.[h,cc]
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+   * mcalib/MHCalibrationChargePINDiode.[h,cc]
+   * mcalib/MHCalibrationRelTimePix.[h,cc]
+   * mcalib/MHCalibrationTestPix.[h,cc]
+   * mcalib/MHCalibrationTestTimePix.[h,cc]
+   * manalysis/MHPedestalPix.[h,cc]
+     - derive from MHCalibrationPix
+     - new functions Reset()
+
+   * mcalib/MHCalibrationChargeCam.cc
+   * mcalib/MHCalibrationRelTimeCam.cc
+   * mcalib/MHCalibrationTestCam.cc
+   * mcalib/MHCalibrationTestTimeCam.cc
+     - able to recognize an *Intensity*Cam if in MParList
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - able to recognize an *Intensity*Cam if in MParList
+     - set pulser pattern accordingly in Process from MRawEvtHeader     
+     - add switches to perform types of checks or not
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - able to recognize an *Intensity*Cam if in MParList
+
+   * mjobs/MJCalibration.[h,cc] 
+     - fixed flags
+     - included intensity calibration (MJCalibration::SetIntensity())
+       (default is standard calibration like before)
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractTimeHighestIntegral.cc
+   * msignal/MExtractSlidingWindow.cc
+   * msignal/MExtractPINDiode.cc
+   * msignal/MExtractFixedWindow.cc
+   * msignal/MExtractFixedWindowSpline.cc
+   * msignal/MExtractBlindPixel.cc
+   * msignal/MExtractAmplitudeSpline.cc
+     - removed some possible bugs in the case that no LoGain is 
+       available at all.
+
+
+
+ 2004/09/09: Thomas Bretz
+
+   * mhvstime/MHPixVsTime.[h,cc], mhvstime/MHVsTime.[h,cc],
+     mhvstime/MHSectorVsTime.[h,cc], mhbase/MH3.[h,cc]:
+     - changed such that the axis titles can be set via the 
+       title or (if available) a MBinning
+
+   * mhbase/MBinning.cc:
+     - added HasTitle
+
+   * mjobs/MJPedestal.cc:
+     - added lost UseData again to CheckEnvLocal
+
+   * mjobs/MJStar.cc:
+     - fixed handling of Axis titles of histograms
+
+   * mjobs/Makefile:
+     - added path to mhvstime
+
+   * manalysis/MParameters.[h,cc]:
+     - added Print() functions
+
+   * mfileio/MReadReports.[h,cc], mfileio/MReadTree.[h,cc]:
+     - moved setting of StreamId from MReadReports To MReadTree
+
+   * mhbase/MH.cc:
+     - workaround all the this which are reset in TAxis::Set
+  
+   * mfileio/MReadRflFile.[h,cc]:
+     - added missing abstract functions
+
+   * star.cc, callisto.cc, mjobs/MJStar.[h,cc], 
+     mjobs/MJCalibrateSignal.[h,cc]:
+     - added option to process monte carlo files
+
+   * mhist/MHEffectiveOnTime.[h,cc]:
+     - added a histogram taking the on-time vs time
+     - fixed handling of Draw/Project/Paint
+
+
+
+ 2004/09/08: Thomas Bretz
+ 
+   * mbadpixels/MBadPixelsCam.[h,cc], mbase/MParContainer.[h,cc],
+     mhvstime/MHPixVsTime.cc, mhvstime/MHSectorVsTime.cc:
+     - replaces ifstream by istream in AsciiRead
+
+   * mbase/MTime.[h,cc]:
+     - fixed comment about SetTimeFormat
+     - added AsciiRead
+     - added AsciiWrite
+     - added Minus1ns
+
+   * mfileio/MWriteAsciiFile.cc:
+     - write all containers if one has its SetReadyToSaveFlag set
+
+   * mhist/MHEffectiveOnTime.[h,cc]:
+     - for MEffectiveOnTime fit the whole projection instead
+       of using the sum of the theta-bins
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - replaces ifstream by istream in AsciiRead
+     - fixed to support MStatusDisplay
+     - do not fill the same time twice
+     - added support for error bars
+
+   * mjobs/MJStar.cc:
+     - replaced MReadMarsFile by MReadReports
+     - added MEventRateCalc and corresponding histogram
+     - added MHEffectiveOnTime
+
+
+
+ 2004/09/07: Thomas Bretz
+
+   * merpp.cc:
+     - added lost update-option
+
+   * mjobs/MJCalibrateSignal.cc:
+     - fixed a compiler error geom.ClassName() --> geom
+
+   * mraw/MRawRunHeader.cc:
+     - added 'header' option to Print-function
+
+   * msql/MSQLServer.[h,cc]:
+     - added new onstructors taking TEnv as argument
+
+   * macros/sql/*.C:
+     - updated to use sql.rc
+
+   * macros/sql/sql.rc:
+     - added
+
+   * mcalib/MCalib*.[h,cc]:
+     - simplified the includes a little bit to accelerate compiling
+       and maybe to secure everything from compiler bugs a bit more
+
+   * callisto.cc, star.cc:
+     - do not allow implicit batch-mode
+
+   * showlog.cc:
+     - removed an unused variable
+
+   * manalysis/MEventRateCalc.[h,cc]:
+     - started implementing a corrsponding time
+
+   * manalysis/MParameters.[h,cc], manalysis/AnalysisLinkDef.h:
+     - added MParameterDerr
+
+   * mbadpixels/MHBadPixels.[h,cc]:
+     - removed obsolete fPedPhotCam
+
+   * mbase/MTime.[h,cc]:
+     - added AddMilliSeconds
+     - added SetMean
+
+
+
+
+ 2004/09/07: Markus Gaug
+
+   * mcalib/MHGausEvents.[h,cc]
+     - added function IsOnlyUnderflow()
+
+   * mcalib/MHCalibrationCam.[h,cc]
+   * mcalib/MHCalibrationChargeCam.cc
+   * mcalib/MHCalibrationRelTimeCam.cc
+     - added bool kLoGain which is set if number of LoGain Slices in 
+       MRawRunHeader is not 0. This excludes the low gain calculations 
+       in case that there is no lowgain at all. 
+
+   * mcalib/MCalibrationQECamMagic.cc
+     - implemented Nicola's solution for the compiling problem of the 
+       TArrayD's 
+
+   * mcalib/MCalibColorSet.cc
+     - implemented intensity recognition
+
+   * mhist/MHCamera.[h,cc]
+     - included functions AddCamContent(MArrayD...) and 
+       SetCamContent(MArrayD... )
+
+
+
+ 2004/09/06: Thomas Bretz
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - read camera geometry from calib-file
+
+   * mjobs/MJCalibration.[h,cc]:
+     - write camera geometry to calib-file
+
+   * macros/sql/filldotraw.C, macros/sql/fillcalib.C:
+     - added
+
+   * macros/sql/filldot*.C
+     - fixed some comments
+
+   * mpointing/MPointingPosCalc.cc:
+     - removed some obsolete comments
+
+
+
+ 2004/09/05: Markus Gaug
+
+   * mcalib/MCalibColorSet.[h,cc]
+     - finished setting of the asumed pulse pattern
+
+
+
+ 2004/09/03: Markus Gaug
+
+   * mcalib/MCalibrationChargeBlindCamTwoNewStyle.cc
+     - small modification in QE of new blind pixel
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - new functions:
+       GetAveragedConvFADC2PhotPerArea,  
+       GetAveragedConvFADC2PhotPerSector, 
+       GetAveragedArrivalTimeMeanPerArea,  
+       GetAveragedArrivalTimeMeanPerSector, 
+       GetAveragedArrivalTimeRmsPerArea,  
+       GetAveragedArrivalTimeRmsPerSector, 
+       to be used by the data check.
+
+   * mcalib/MCalibrationChargePix.cc
+     - found small bug concerning the MBadPixelpix::kChargeSigmaNotValid
+       pixels which are recovered since last week. 
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - fixed UpdateCombinedMethod, removed AddAverageCombinedQEs
+
+   * mcalib/MCalibrationQECam.[h,cc]
+     - new array with cornings, not included in the I/O
+     - added copy function
+
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MCalibrationQECamMagic.[h,cc]
+   * htmldoc/images/Cornings.gif
+     - new class derived from MCalibrationQECam which intialized the 
+       cornings for the Magic camera
+
+
+
+ 2004/09/03: Wolfgang Wittek
+
+   * mbadpixels/MHBadPixels.[h,cc]
+     - new class; histograms for bad pixels
+
+   * mbadpixels/Makefile, mbaspixels/BadPixelsLinkdef.h
+     - MHBadPixels added
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - remove MSigmabar stuff
+
+   * mhist/Makefile, mhist/HistLinkdef.h
+     - MHSigmaTheta added
+   
+   * manalysis/Makefile, manalysis/AnalysisLinkdef.h
+     - remove MPedestalWorkaround and MSourcePosFromStarPos
+     - add MPad
+
+   * manalysis/MPad.[h,cc]
+     - remove *BlindPixel* stuff
+     - remove MSigmabar stuff
+
+
+
+ 2004/09/03: Thomas Bretz
+
+   * manalysis/MCameraData.[h,cc], mimage/MImgCleanStd.[h,cc]:
+     - implemeted cleaning in absolute number of photons
+     - moved output of setup of image cleaning to PreProcess
+ 
+   * mhbase/MBinning.[h,cc]:
+     - added const-qualifier to Apply
+
+   * mhist/MHAlpha.cc:
+     - let TLatex use NDC coordinates
+
+   * mimage/MHHillasSrc.cc:
+     - cosmetics
+
+   * mreport/MReportDrive.[h,cc]:
+     - added Print member function
+
+   * mpointing/MSrcPosFromModel.cc:
+     - removed an obsolete include
+
+   * mraw/MRawEvtHeader.h:
+     - added SetCalibrationPattern as a workaround for the runs
+       which don't have the correct pattern set
+
+   * mcalib/MCalibColorSet.[h,cc]:
+     - added as a workaround for the runs which don't have the
+       correct pattern set
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - added MCalibColorSet
+
+
+
+ 2004/09/02: Thomas Bretz
+
+   * star.cc:
+     - fixed treatment of batch-mode
+
+   * mbase/MParContainer.h:
+     - added a comment
+
+   * mbase/MParList.[h,cc]:
+     - added FindTaskListWithTask
+
+   * mbase/MTaskList.[h,cc]:
+     - added sanity checks in AddToList
+     - added FindTaskList
+
+   * mhbase/MH3.[h,cc]:
+     - moved some drawing code from Draw to Paint
+     - added possibility to set logarithmic axis manually
+     - fixed a bug which caused MH3s in MFillH::Finalize to disappear
+
+   * mhist/MHAlpha.cc:
+     - paint significance and othe rinformations
+     - unified fit in Finalize and Paint
+     - replaced significance calculation by Li/Ma
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - added option to average data
+
+   * mjobs/MJCalibrateSignal.cc:
+     - added MPointingPosCalc for "Drive"
+
+   * mmain/MEventDisplay.cc:
+     - fixed some problems with the display
+
+   * msignal/MArrivalTime.[h,cc]:
+     - added Print()
+
+   * manalysis/MEventRateCalc.[h,cc]:
+     - added the difference in time between two events into the output
+     - made setup more flexible
+
+   * mbase/MContinue.cc:
+     - fixed a bug which caused a problem if MContinue was not in the
+       main tasklist
+
+   * mimage/MHImagePar.[h,cc], mimage/MHNewImagePar.[h,cc]:
+     - added Paint function to support logarithmic y-axis scles
+
+
+
+ 2004/09/01: Thomas Bretz
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - do not add a container which is already in the list
+     - replaced fNameCont by fTitle in MRootFileBranch
+
+   * mgeom/MGeomPix.[h,cc]:
+     - declared tan(30)
+     - added GetL member function
+
+   * mhist/MHAlpha.cc:
+     - added a logging output
+
+   * mhist/MHFalseSource.[h,cc]:
+     - shift by MSrcPosCam introduced
+     - fixed on-off plot
+     - fixed changed return value MHillasSrc::Calc
+     - as a workaround for some crashes removed SetBit(kCanDelete)
+       of catalog
+
+   * mimage/MHHillasSrc.cc, mimage/MHillasSrc.cc:
+     - some small fixes to new plots
+     - some cosmetics to the code
+
+   * mimage/MHillas.cc, mimage/MHillasExt.cc, 
+     mimage/MImagePar.cc, mimage/MImgCleanStd.cc,
+     mimage/MNewImagePar.cc:
+     - removed obsolete include of fstream
+
+   * mpointing/Makefile, mpointing/PointingLinkDef.h:
+     - added new class MPointingPosFromModel
+     
+   * mpointing/MPointingPosFromModel.[h,cc]:
+     - added
+
+
+
+ 2004/08/31: Daniel Mazin
+
+   * manalysis/MSigmabarCalc.h:
+     - added function SetNamePedPhotCam to set the name of the 
+       MPedPhotCam container
+
+
+
+ 2004/08/31: Thomas Bretz
+
+   * star.cc:
+     - implemented batch- and quit-mode
+
+   * mastro/MAstroCatalog.h:
+     - implemented default argument for magnitude in MVector3
+       setters
+
+   * mbase/MDirIter.cc:
+     - fixed a typo
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed a typo
+
+   * mimage/MHHillasSrc.[h,cc], mimage/MHillasSrc.[h,cc]:
+     - added DCA and DCADelta as discussed with the ETH people
+     - incrementes version number of MHillasSrc
+     - changed return type of MHillasSrc::Calc from Bool_t to Int_t
+
+   * mimage/MHillasCalc.cc:
+     - changed to support error code 6
+
+   * mpointing/MPointingPos.h:
+     - added Getter for ZdA7Az in rad
+
+   * mpointing/MPointingPosCalc.cc:
+     - fixed a bug which converted Ra/Dec wrongly to rad
+
+   * mmain/MEventDisplay.cc:
+     - switched on usage of context menu in constructor
+
+
+
+ 2004/08/30: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.cc
+   * mcalib/MCalibrationTestCalc.cc
+   * mcalib/MCalibrationRelTimeCalc.cc
+   * mcalib/MHCalibrationTestCam.cc
+   * mcalib/MHCalibrationTestTimeCam.cc
+     - exchanged all arrays by TArray's
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+   * mcalib/MHCalibrationRelTimeCam.[h,cc]
+     - exchanged all arrays by MArray's
+
+
+
+ 2004/08/30: Thomas Bretz
+
+   * showlog.cc, showplot.cc:
+     - enhanced functionality
+
+   * callisto.cc, mjobs/MSequence.cc:
+     - enhanced comments
+
+
+
+ 2004/08/29: Markus Gaug
+ 
+   * mbadpixels/MBadPixelsPix.[h,cc] 
+   * mbadpixels/MBadPixelsCam.cc
+   * mjobs/MJCalibration.cc 
+     - introduced new calibration bits: kHiGainOverFlow 
+       and kLoGainOverFlow being filled when the calibration histograms 
+       overflow. Will cause an kUnsuitableRun afterwards. 
+     - added in datacheck-display of MJCalibration
+
+   * mcalib/MHCalibrationChargeHiGainPix.[h,cc]
+   * mcalib/MHCalibrationChargeLoGainPix.[h,cc]
+     - default lower histogram limit moved to -100.5
+
+   * mcalib/MHCalibrationCam.h
+   * mcalib/MHCalibrationChargeCam.cc
+     - make TArrayI out of fOverFlowHiGain and fOverFlowLoGain
+
+   * mjobs/MJCalibration.[h,cc]
+     - finished datacheck display with the arrival times.
+
+
+
+ 2004/08/27: Florian Goebel
+
+   * mpedestal/MPedestalPix.h
+     - correct calculation of error of RMS
+
+
+
+ 2004/08/27: Hendrik Bartko
+
+   * msignal/MExtractTime.cc
+     - check that the pixel has a low gain before calculating the time 
+       for the low gain in case of a saturated high gain.
+
+
+
+ 2004/08/27: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - adapted to possible use of MPedCalcFromLoGain
+
+   * mjobs/MJPedestal.h
+     - added function SetUseData() and IsUseData()
+
+   * mcalib/MCalibrationQEPix.cc
+     - changed initialization of fNorm... variables from 1. to -1. 
+       Like this, an accidental not-filling of MCalibrationQECam will
+       be recognized easier.
+
+   * mcalib/MCalibrationChargeCalc.cc
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - change treatment of pixels with kSigmaNotValid
+
+   * mpedestal/MPedestalCam.cc
+     - added functions GetAveragedPedPerArea  
+                       GetAveragedPedPerSector
+                       GetAveragedRmsPerArea  
+                       GetAveragedRmsPerSector
+       to be used for the datacheck.
+
+     - fixed a small bug in the calculation of the PedestalRms Error 
+       in GetPixelContent()
+
+   * macros/bootcampstandardanalysis.C 
+   * macros/mccalibrate.C 
+   * macros/pedphotcalc.C
+   * macros/starmc.C:
+     - replace MCalibrate by MCalibrateData
+
+   * mjobs/MJCalibration.h
+     - re-added function SetInput which had been removed recently 
+       (probably by accident)
+
+   * mjobs/MJCalibration.cc
+     - return kTRUE in function FindColor() if the colour has already 
+       been set (e.g. by the macro).
+
+   * mcalib/MHGausEvents.cc
+     - removed one call to fHPowerProbability->SetDirectory(0) which was
+       at a completely wrong place in CreateEventXaxis(). Probably a 
+       slip of the emacs-pen.
+ 
+   * mcalib/MJExtractSignal.cc
+     - replace MCalibrate by MCalibrateData
+
+
+
+ 2004/08/27: Thomas Bretz
+
+   * Makefile:
+     - added comments how to link statically
+     - added star again
+
+   * callisto.cc: 
+     - fixed some output
+     - fixed batch mode
+
+   * mbadpixels/Makefile:
+     - added a comment
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MArrayI
+
+   * mbase/MArrayI.[h,cc]:
+     - added
+
+   * mbase/MArrayD.cc:
+     - fixed some comments
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - unified CalibratePedestal and CalibrateData. Calling GetConvFactor twice
+       took a lot of time.
+
+   * mjobs/MJCalibrateSignal.cc, mjobs/MJPedestal.cc, MJCalibration.cc:
+     - added two empty lines to output if finished
+     - added a sanity check around the call to CheckEnv
+
+   * mpedestal/MPedPhotCam.cc:
+     - use faster MArrays in ReCalc
+     - accelerated GetPixelContent
+
+   * msignal/MExtractTimeFastSpline.cc:
+     - accelerated a bit by defining
+          Float_t higainklo = fHiGainSecondDeriv[klo];
+          Float_t higainkhi = fHiGainSecondDeriv[khi];
+       instead of accesing the arrays many times inside the loops.
+       Somebody should do the same for logain.
+
+   * mraw/MRawEvtData.cc:
+     - fixed a bug in InitArrays
+
+   * showlog.cc:
+     - added some more functionality
+
+   * star.cc:
+     - changed to use new MJStar
+
+   * mfileio/MChain.cc:
+     - added namespace
+
+   * mfileio/MReadTree.cc:
+     - added a call to ResetTree as first call in PreProcess. Using
+       MReadReports with a tree missing in the file mysteriously
+       crashed because TChain::fTreeNumber was set already by
+       a root-miracle.
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added MJStar
+
+   * mjobs/MJCalibrateSignal.cc:
+     - replaced MReadMarsFile by MReadReports
+
+   * mmain/MEventDisplay.cc:
+     - fixed reading of resource file
+
+   * mbase/MStatusDisplay.cc:
+     - made Reset() batch-mode safe
+
+   * mcalib/MCalibrateData.cc:
+     - simplified a calculation
+
+   * mfileio/MReadReports.[h,cc]:
+     - implemented GetEntries()
+     - implemented GetFileName()
+     - changed kHasMaster from BIT(15) to BIT(14)
+     - fixed a bug in AddTree which caused the Master-Bit to be
+       set for the wrong object
+
+   * mfileio/MReadTree.cc:
+     - return 0 entries if entrie==TChain::kBigNumber
+
+   * msignal/MExtractFixedWindow.cc:
+     - updated output to fitz into a std 80-col console
+
+   * mars.rc, star.rc:
+     - added
+
+
+
+ 2004/08/26: Wolfgang Wittek
+
+   * mstarcam/MStarCamTrans.[h,cc]
+     - include optical aberration when plotting the grid
+
+   * mtemp/MTelAxisFromStars.[h,cc]
+     - add member functions SetPointingPosition and SetSourcePosition
+
+
+
+ 2004/08/26: Markus Gaug
+
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - derived from MJob
+     - removed obsolete code (which has been moved to MJob)
+
+   * macros/calibration.C
+     - adapt code to changes done in MJob
+
+
+
+ 2004/08/26: Thomas Bretz
+
+   * mbase/MMath.cc:
+     - changed calculation of sign of SignificanceLiMaSigned due to
+       bug #131
+
+   * readdaq.cc, readraw.cc:
+     - updated to support MRawEvtData2
+     
+   * mraw/MRawEvtData.[h,cc], mraw/MRawFileRead.cc, 
+     mraw/MRawFileWrite.[h,cc], mraw/MRawRead.[h,cc], 
+     mraw/MRawSocketRead.cc:
+     - updated to support negative pixel ids
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - increased max format version to 4
+     - added GetNumNormalPixels
+     - added GetNumSpecialPixels
+     - added GetMinPixId
+     - added GetMaxPixId
+
+   * merpp.cc: 
+     - added a new option --auto-time to get the time range for 
+       cc and/or caco data from the run header of the raw data
+
+   * callisto.cc: 
+     - some additional checks
+     - more comments
+
+   * mfileio/MReadReports.h:
+     - overwrote GetFileName - otherwise CINT refuses to create an object
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - added an primitive interpolation of arrival times which
+       tries to keep the random arrival time for pixels without
+       signal
+     - fixed a bug which could cause a crash
+     - added more control over the pedestal treatment
+
+
+
+ 2004/08/25: Thomas Bretz
+
+   * callisto.cc:
+     - updated handling of command line parameters
+     - added MJPedestal in second loop
+     - changed MJ* to support new MJob base class
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added MJob
+
+   * mjobs/MJob.[h,cc]:
+     - added
+
+   * mjobs/MJCalibrateSignal.[h,cc], mjobs/MJCalibrateSignal.[h,cc],
+     mjobs/MJCalibration.[h,cc], mjobs/MJPedestal.[h,cc]:
+     - derived from MJob
+     - removed obsolete code (which has been moved to MJob)
+
+   * mjobs/MSequence.[h,cc]:
+     - use MDirIter::GetEntries in SetupRuns
+     - implemented raw-file mode
+     - added GetNum*Runs
+
+   * callisto.rc:
+     - fixed
+
+   * showlog.cc, mbase/MTime.cc, mreport/MReportFileReadCC.cc:
+     - some fixes for gcc 2.95.3
+
+   * mbase/MEvtLoop.cc:
+     - allow prefix argument in ReadEnv
+
+   * mbase/MLog.cc:
+     - added options for log-file and html-file
+
+   * mbase/MTaskEnv.[h,cc]:
+     - added comment
+     - implemented dummy/skip-mode
+
+   * mjobs/MJCalibrateSignal.cc:
+     - removed non existance check from reading extractors (MTaskEnv dummy mode!)
+     - small changed to output
+
+   * mjobs/MJCalibration.cc:
+     - added a cast for gcc 2.95.3
+     - allow dummy mode MTaskEnvs
+
+   * mjobs/MJPedestal.[h,cc]:
+     - implemented CheckEnv
+
+   * msignal/MExtractTime.cc:
+     - fixed Print()-output
+
+   * msignal/MExtractTimeFastSpline.[h,cc]:
+     - added ReadEnv
+     - added Print
+
+
+
+ 2004/08/25: Wolfgang Wittek
+
+   * mpointing/MPointingPos.h
+     - add member function GetHa()
+
+
+
+ 2004/08/24: Thomas Bretz
+
+   * Makefile:
+     - added callisto
+     - added showplot
+     - removed star
+     - removed status
+
+   * merpp.cc:
+     - updated Usage()
+     - use some new feature or MArgs
+
+   * callisto.cc:
+     - a new program to calculate the calibration
+
+   * callisto.rc:
+     - resource file for callisto
+
+   * showplot.cc:
+     - a new program to show data check plots from a file
+
+   * mbase/MArgs.[h,cc]:
+     - added Get*AndRemove with a default argument
+
+   * mbase/MDirIter.[h,cc]:
+     - added Add(MDirIter &)
+
+   * mbase/MEvtLoop.cc:
+     - check for the existance of the resource file
+
+   * mbase/MLog.[h,cc]:
+     - added Usage()
+
+   * mbase/MTaskEnv.cc:
+     - added output in ReInit
+
+   * mjobs/MJCalibration.cc, mjobs/MJPedestal.cc:
+     - added Overwrite option
+     - maintained CheckEnv
+     - added InputPath
+
+   * mjobs/MSequence.cc:
+     - added return value to Setup*
+     - added comments
+
+   * mmain/MEventDisplay.cc:
+     - added tab for cleaning data
+
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]:
+     - added ReadEnv
+     - for consistency renamed fWindowSize* to f*WindowSize
+
+   * msignal/MExtractTimeHighestIntegral.[h,cc]:
+     - added ReadEnv
+
+   * mcalib/MCalibrationRelTimeCalc.cc:
+     - do not write to a log file if logging is not enabled
+     - replaced some arrays by TArrays
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added MJCalibrateSignal
+
+   * mjobs/MJCalibrateSignal.[h,cc]:
+     - added
+
+   * msignal/MExtractFixedWindow.[h,cc], msignal/MExtractFixedWindowPeakSearch.[h,cc],
+     msignal/MExtractSlidingWindow.[h,cc], msignal/MExtractTime.[h,cc],
+     msignal/MExtractTimeAndCharge.[h,cc], msignal/MExtractTimeHighestIntegral.[h,cc]
+     msignal/MExtractor.[h,cc]:
+     - added Print
+     - added ReadEnv
+     - changed version number to 1
+
+
+
+ 2004/08/23: Wolfgang Wittek
+
+    * mtemp/MTelAxisFromStars.[h,cc]
+      - replace MStarLocalCam by MStarCam
+      - replace MStarLocalPos by MStarPos
+
+    * mtemp/MHTelAxisFromStars.[h,cc]
+      - replace MStarLocalCam by MStarCam
+      - replace MStarLocalPos by MStarPos
+
+    * mstarcam/MStarPos.[h,cc]
+      - remove data members containing 'CG' ('correlated Gauss');
+        put results from uncorrelated and correlated Gauss fit 
+        into the same area
+
+    * mtemp/MFindStars.h[cc]
+      - changes due to the changes in MStarPos
+      - remove fit with fixed correlation
+
+    * mtemp/MSourceDirections.[h,cc]
+      - changes due to the changes in MStarPos
+
+    * mtemp/findTelAxisFromStars.C
+      - changes due to changes in MTelAxisFromStars and MFindStars
+
+
+
+ 2004/08/23: Thomas Bretz
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - changed missleading ProcessRMS to ProcessPedestal
+
+   * mfileio/MReadTree.h:
+     - added AddFiles(MDirIter&) which is overloaded by another function
+       which resulted in some trouble
+
+   * mfileio/MWriteRootFile.[h,cc]:
+     - added cd() member function
+
+   * mimage/MHHillas.[h,cc]:
+     - added display of camera on top of MeanXY-plot
+
+   * mraw/MRawSocketRead.h:
+     - added GetFileName()
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added new data member fNumIslands
+     - added new functions (CalcIsland/CalcIslands to calculate islands)
+     - added new member function to sort pixels by index
+     - added island index in GetPixelContent
+     - increased version number
+
+   * manalysis/MCerPhotPix.[h,cc]:
+     - added fIdxIsland data member
+     - overloaded Compare function to be able to sort by pixel index
+     - increased version number
+
+   * mhist/MHEvent.[h,cc]:
+     - added new option for island index
+     - added kEvtCleaningData
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - added island calculation after image cleaning
+     - fixed some output to be consistent
+     - added ReadEnv
+     - updated StreamPrimitive
+     - added new cleaning method (probability cleaning)
+
+   * mimage/Makefile:
+     - added mhist
+
+   * mmain/MEventDisplay.cc:
+     - added display of island index
+     - changed to support files with calibrated data, too
+
+   * mhvstime/MHVsTime.[h,cc]:
+     - implemented the possibility to set a maximum number of points
+
+   * mbase/MParContainer.h:
+     - changed StreamPrimitive to public
+
+   * mcalib/MMcCalibrationCalc.[h,cc]:
+     - added fPar data member (MImagePar) to get number of 
+       saturating hi gain pixels
+
+   * mimage/Makefile, mimage/ImageLinkDef.h:
+     - added MImagePar
+     - added MHImagePar
+
+   * mimage/MConcentration.[h,cc]:
+     - removed obsolete destructor
+
+   * mimage/MHillas.[h,cc]:
+     - added a check for island index to calculation
+
+   * mimage/MHillasCalc.cc:
+     - added option kCalcImagePar
+     - added option kCalcHillasSrc
+     - added Print function
+     - added StreamPrimitive function
+     - added resource support (ReadEnv)
+
+   * mimage/MHillasExt.[h,cc]:
+     - added a check for island index to calculation
+     - replaced for-loop by iterator
+
+   * mimage/MHillasSrc.[h,cc]:
+     - changed argument to Calc from pointer to reference
+
+   * mimage/MHillasSrcCalc.[h,cc]:
+     - fixed StreamPrimitive
+     - added some const-qualifiers to data members
+     - adapted to change in MHillasSrc
+
+   * mimage/MNewImagePar.[h,cc]:
+     - moved saturating pixels to new class MImagePar
+     - added a check for island index to calculation
+     - increased version number
+
+   * mpointing/MSrcPosCam.h:
+     - made StreamPrimitive public
+
+   * msignal/MArrivalTime.h:
+     - removed operator()
+     - added operator[] const
+
+   * manalysis/MCameraData.[h,cc]:
+     - added algorithm for 'Probability cleaning'
+
+   * mbase/MMath.[h,cc]:
+     - added GaussProb
+
+   * mjobs/MSequence.h:
+     - added IsValid
+
+
+
+ 2004/08/20: Thomas Bretz
+
+   * mjobs/MSequence.[h,cc]:
+     - added path-option to SetupRuns
+
+   * mjobs/MJCalibration.cc, mjobs/MJExtractSignal.cc, MJPedestal.cc:
+     - changed file "UPDATE" to "RECREATE"
+ 
+   * macros/sql/filldotrbk.C:
+     - removed obsolete output
+
+   * macros/sql/filldotrun.C:
+     - removed obsolete output
+     - updated to support ExcludedFDA-table
+
+   * mbase/MParList.[h,cc]:
+     - added FindTask-member function
+
+   * mcalib/MHCalibrationChargeBlindCam.cc:
+     - fixed a 'comparison between signed and unsigned'
+
+   * mfileio/MRead.h:
+     - added GetFileName()
+     - removed const-qualifier from CheckAndWrite
+
+   * mfileio/MReadMarsFile.cc:
+     - changed some logiing output
+
+   * mfileio/MWriteAsciiFile.[h,cc], mfileio/MWriteFile.[h,cc]:
+     - removed const-qualifier from CheckAndWrite
+     
+   * mfileio/MWriteRootFile.[h,cc]:
+     - simplified the constructor by adding Init() function
+     - added ReInit function to support file splitting
+     - added file splitting support (GetNewFileName, ChangeFile)
+     - added new constructor for file splitting
+     - made gsDef* a static member
+     - slight changed to PreProcess to support file-splitting
+     - if file-spliiting is enabled return always kTRUE in IsFileOpen
+     - added many new outputs in case of possible problems
+
+   * mraw/MRawFileRead.[h,cc]:
+     - changed return type of GetFileName()
+
+   * mraw/MRawFileWrite.[h,cc]:
+     - removed obsolete pParList data member
+     - by default write all events to the 'Events' tree
+
+   * msql/MSQLServer.[h,cc]:
+     - enhanced Query function
+
+
+
+ 2004/08/19: Marcos Lopez
+
+   * mjobs/MJCalibration.cc:
+     - In the function FindColor(), when looking for the calibration color in 
+       the calibration file name, ignore the case, to deal with colors
+       written in capital letters.
+
+
+
+ 2004/08/19: Thomas Bretz
+
+   * mastro/MTransCelLocCam.[h,cc]:
+     - renamed to MStarCamTrans and moved to mstarcam
+
+   * mastro/Makefile, mastro/AstroLinkDef.h:
+     - removed MTransCelLocCam
+
+   * mstarcam/Makefile, mstarcam/AstroLinkDef.h:
+   - cleaned up includes in Makefile
+   - added MStarCamTrans
+
+
+
+ 2004/08/19: Robert Wagner
+
+   * mtemp/MFindStars.[cc,h], mastro/MAstroCamera.cc,
+     mtemp/MSourceDirections.[cc,h]
+     - Changes to reflect the change of name of MStarPos, MStarCam
+
+
+
+ 2004/08/18: Thomas Bretz
+
+   * mbadpixels/MBadPixelsCam.[h,cc]:
+     - implemented function to calculate max cluster sizes
+
+   * macros/sql/filldotrbk.C, macros/sql/filldotrun.C:
+     - added return value
+
+   * mjobs/MJCalibration.cc:
+     - simplified FindColor by 1000% for later move to a new location
+
+   * mpedestal/MPedCalcFromLoGain.cc:
+     - output the range only if it has changed
+
+
+
+ 2004/08/18: Wolfgang Wittek
+
+   * mastro/MTransCelLocCam.[h,cc]
+     - new class; allows to calculate for any point (X, Y) in the 
+       camera the local (celestial) coordinates if the local 
+       (celestial) coordinates are known for some fixed point (X0, Y0) 
+       in the camera
+     - for given local (celestial) coordinates of the camera center,
+       the meber function PlotGrid draws the lines of constant theta 
+       and phi (and of constant dec and hourangle) onto the camera 
+       plane 
+
+   * mastro/Makefile, mastro/AstroLinkDef.h
+     - MTransCelLocCam added
+
+   * macros/testMTrans.C
+     - macro to test the class MTransCelLocCam
+
+
+
+ 2004/08/17: Markus Gaug
+ 
+   * msignal/MExtractBlindPixel.[h,cc]
+     - remove fModified which is taken care of in MJCalibration by the 
+       correct initialization
+
+   * mcalib/MCalibrationChargeBlindCam.[h,cc]
+     - now a base class for different types of blind pixels cams. 
+     - moved fBlindPixels away from pointer, analogue to MGeomCam
+
+   * mcalib/MHCalibrationChargeBlindCam.[h,cc]
+     - updated to new call to GetNumBlindPixels()
+
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MCalibrationChargeBlindCamOneOldStyle.[h,cc]
+   * mcalib/MCalibrationChargeBlindCamTwoNewStye.[h,cc]
+     - new classes deriving from and intializing 
+       MCalibrationChargeBlindCam 
+
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+     - derive from MCalibrationPix instead of MCalibrationChargePix
+     - create possibility to intialize QE's, etc. from outside
+     - fix default to previous behaviour such that old code can still 
+       run on old files without changes
+     - create copy function
+
+   * macros/calibration.C
+     - updated macro to use of MCalibrationTestCam
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - comment the static variable gkNumPulserColors
+     - take the pulser color enum and gkNumPulserColors out of the streamer
+     - set the version nr from 3 to 4
+     - Simplify a piece of the code dealing with the ForEach macro
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - removed Init() function which is already fulfilled by the Init() 
+       function of MCalibrationCam
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - some changes to the output
+     - call to MCalibrationChargeBlindCam->IsValid() removed
+
+   * mbadpixels/MBadPixelsCam.cc
+     - included kDeviatingNumPhots in GetPixelContent()
+
+   * mjobs/MJCalibration.[h,cc]
+     - some small modifications in the data-check display, discussed 
+       with Florian
+     - found that the MFillH for the MHCalibrationChargeBlindCam had 
+       been replaced to MHCalibrationChargeBlindPix -> redone
+     - adapted InitBlindPixel() to new classes initializing the right 
+       MCalibrationChargeBlindCam's
+
+   * mcalib/MCalibrationTestPix.[h,cc]
+   * mcalib/MCalibrationTestCam.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new container class to store results of MCalibrationTestCalc
+       and MHCalibrationTestCam
+
+   * mcalib/MCalibrationTestCalc.[h,cc]
+     - adapted to use of MCalibrationTestCam
+
+   * mcalib/MHCalibrationTestCam.[h,cc]
+     - adapted to use of MCalibrationTestCam
+
+
+
+ 2004/08/17: Thomas Bretz
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - unrolled some if-else statements to accelerate the algorithm a
+       bit (it is just the bottelneck of calibrating the signal)
+     - made sure that code which in not needed is not executed in
+       this case
+
+   * mbadpixels/MBadPixelsCam.cc:
+     - unrolled if-else statements in GetPixelContent
+
+   * mcalib/MHCalibrationChargeBlindPix.cc:
+     - commented out unsused variable
+
+   * mjobs/MJCalibration.cc:
+     - some more output when writing the file
+
+   * mjobs/MJPedestal.[h,cc]:
+     - added more resources
+     - added fMaxEvents
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - fixed behaviour or fABFlags in case the array is empty
+     - changed Char_t data member to Byte_t according to change
+       in MRawEvtData
+
+   * mraw/MRawEvtData.[h,cc]:
+     - changed TArrayC data member to MArrayB to get rid of a memory
+       leak which resulted in huge memory usage when reading
+       MRawEvtData
+     - changed version number from 4 to 5
+     - changed size of fABFlag array to a more reasonable size
+       (maxid/8+1)
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - implemeted Getter for calibration pattern
+
+   * mhbase/MHMatrix.[h,cc], mranforest/MRanTree.cc,
+     mtools/MHSimmulatedAnnealing.h, mtools/MSimmulatedAnnealing.h:
+     - changed to compile with root-4.00/08
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - changed SetDumpEvents to SetNumEventsDump to fit roots naming
+       convention
+     - fixed crashes in case nothing has beendone
+     - do not process abflag if it is not existing
+     - for the moment do no call to ReCalc in Process
+     - added some const-qualifiers
+
+   * mhist/MHCamera.h:
+     - changed the definition of FetMinimum/GetMaximum such that
+       it compiles with root 4.00/08
+
+
+
+ 2004/08/17: Robert Wagner
+
+   * mstarcam, mstarcam/Makefile, mstarcam/StarcamLinkDef.h,   
+     mstarcam/StarcamIncl.h, macros/dohtml.C, macros/rootlogon.C
+     - Added directory mstarcam for holding all classes related to
+       studies of stars
+
+   * mstarcam/MStarPos.[cc,h], mstarcam/MStarCam.[cc,h],
+     mstarcam/StarcamLinkDef.h, mstarcam/Makefile, Makefile
+     - moved mtemp/MStarLocalPos.[cc,h], mtemp/MStarLocalCam.[cc,h]
+
+   * mastro/MAstroCamera.cc, mtemp/MFindStars.[cc,h],
+     mtemp/MSourceDirections.[cc,h]
+     - changed references to MStarLocalPos to MStarPos
+
+
+
+ 2004/08/16: Thomas Bretz
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - change to support also 'No calibration of data'
+     - removed obsolete dependancie on *'FromData' containers
+
+   * mcalib/MCalibrateData.[h,cc], mbadpixels/MBadPixelsCalc.[h,cc]:
+     - added member function ReadEnv
+
+   * mbase/MTime.[h,cc]:
+     - added new member function SetStringFmt
+
+   * mcalib/MHCalibrationChargeBlindPix.cc:
+     - removed unused variable
+
+   * mcalib/MHCalibrationChargeBlindPix.cc:
+     - removed unused variable
+
+
+
+ 2004/08/16: Markus Gaug
+ 
+   * mcalib/MHCalibrationCam.cc
+     - add a criterion to stop the Finalize() if both fHiGainArray 
+       and fLoGainArray have not been expanded. 
+     - replace two gLog by *fLog
+     - add the pulser color (needed for the datacheck histograms)
+     - some modifications in the data-check display, discussed with Florian
+
+   * mjobs/MJCalibration.[h,cc]
+     - some small modifications in the data-check display, discussed 
+       with Florian
+
+   * mcalib/MHGausEvents.[h,cc]
+     - make fSaturated Int_t and set to 0 in the Clean() function
+
+   * mcalib/MHCalibrationChargePix.[h,cc]
+     - remove the Clean() function
+
+   * mbadpixels/MBadPixelsPix.h
+   * mbadpixels/MBadPixelsCam.cc
+     - new functions GetUnsuitableCalibration() and 
+       GetUnreliableCalibration() to denote the reason for unsuitability
+       and unreliability. 
+     - in GetPixelContent flags 6 and 7.
+     - will be used for the datacheck display
+
+
+
+ 2004/08/14: Markus Gaug
+
+   * msignal/MExtractor.cc:
+     - documented data members
+     - included default for SetNamePedContainer()
+
+   * mjobs/MJPedestal.[h,cc]
+     - some small modifications in the data-check display, discussed 
+       with Florian
+
+
+
+ 2004/08/13: Thomas Bretz
+ 
+   * macros/readraw.C:
+     - updated to get it working with MC data
+
+   * mbase/MTaskEnv.cc:
+     - fixed a typo
+
+   * mcalib/MCalibrationChargeCalc.[h,cc], 
+     mcalib/MHCalibrationCam.[h,cc]:
+     - added ReadEnv
+     - changed some output slightly to match into a typical
+       80-column console
+
+   * mjobs/MJCalibration.[h,cc]:
+     - changed to support Sequences
+     - added SetEnv
+     - added possibility to change extractors from a resource file
+     - put MBadPixelsMerge into the tasklist - for strange reasons
+       it was missing
+
+   * mjobs/MJPedestal.[h,cc]:
+     - fixed the output name for sequences
+     - added possibility to set output from resource file
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - changed handling of sanity check for setup 
+     - removed obsolete variables
+     - changed output slightly to fit into a typical 80-column
+       console
+     - added some sanity checks to PostProcess
+     - added some info-output to PostProcess
+     - calculate a mean number of total events
+     - call ReCalc to calc mean values of sectors and areas
+
+   * mpedestal/MPedCalcPedRun.[h,cc]:
+     - changed to use ReCalc instead of doing the calculation itself
+       for convinience I left the old code as a comment inside -
+       will be removed later
+
+   * mpedestal/MPedPhotCam.[h,cc]:
+     - slight changes in ReCalc
+
+   * mpedestal/MPedestalCam.[h,cc]:
+     - added ReCalc function (maily taken from PedPhotCamReCalc)
+
+   * mpedestal/MPedestalPix.h:
+     - added Getter for fNumEvents
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - started adding support for calibration pattern. Please don't
+       take the current implementation to serious
+
+
+
+ 2004/08/12: Hendrik Bartko
+
+   * msignal/MExtractor.cc:
+     - corrected the setting of AddSerialNumber for Find(Create)Object
+
+   * msignal/MExtractTime.cc:
+     - corrected the setting of AddSerialNumber for FindObject
+
+   * mbadpixels/MBadPixelsCalc.cc
+     - corrected the setting of AddSerialNumber for FindObject
+
+   * mbadpixels/MBadPixelsTreat.cc
+     - corrected the setting of AddSerialNumber for FindObject
+
+   * mimage/MImgCleanStd.cc
+     - corrected the setting of AddSerialNumber for FindObject
+
+
+
+  2004/08/12: Markus Gaug
+
+   * msignal/MExtractBlindPixel.[h,cc]
+     - Set the method from outside
+     - unified the defaults to new blind pixels
+
+   * mjobs/MJCalibration.[h,cc]
+     - implementation of MHCalibrationChargeCam
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - adapt Draw() and DrawLegend() for the datacheck display
+
+   * mcalib/MHCalibrationChargeBlindCam.[h,cc]
+     - new member function fFitFunc, can be set from outside and is 
+       further passed onto the MHCalibrationChargeBlindPix's
+
+   * mcalib/MHCalibrationChargeCalc.[h,cc]
+     - improved readability of output
+     - set default fPheErrLimit to 4.5 sigma
+
+   * mcalib/MCalibrateData.[h,cc]
+     - give defaults to the Setter functions
+     - change default calibration mode from blindpixel to ffactor
+     - change exclusion of bad pixels from unsuitable run to unsuitable.
+     - some cosmetic changes
+     - remove fNumHiGainFADCSamples and fNumLoGainFADCSamples as 
+       data members    
+     - remove fConversionHiLo which is not used in the class
+     - write a StreamPrimitive()
+
+
+  2004/08/12: Thomas Bretz
+
+   * mreport/MReportFileReadCC.cc:
+     - fixed a bug in CheckFileHeader which caused a condition to
+       be wrongly evaluated
+
+   * mbase/MStatusDisplay.cc:
+     - small modification to postscript output
+
+   * showlog.cc:
+     - added
+
+   * Makefile:
+     - added showlog
+
+   * macros/sql/filldotrbk.C, macros/sql/filldotrun.C:
+     - update of comments
+
+   * mbase/MEvtLoop.cc:
+     - first interprete environment for fLog
+
+   * mbase/MEvtLoop.[h,cc], mbase/MParContainer.[h,cc],
+     mbase/MParList.[h,cc], mbase/MTaskList.[h,cc],
+     mfileio/MRead.[h,cc], mhbase/MHMatrix.[h,cc],
+     mpedestal/MPedCalcFromLoGain.[h,cc],
+     mpedestal/MPedCalcFromPedRun.[h,cc],
+     msignal/MExtractor.[h,cc]:
+     - changed type of ReadEnv from Bool_t to Int_t
+
+   * mbase/MLog.cc:
+     - fixed ReadEnv
+
+   * mbase/MParContainer.[h,cc]:
+     - added TestEnv
+
+   * mbase/MParList.cc, mbase/MTaskList.cc:
+     - moved some code to MParContainer::TestEnv
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MTaskEnv
+
+   * mhist/MHCamera.cc:
+     - removed some output (Draw function don't write something
+       to the console) - it is displayed anyhow
+     - added some SetBorderMode(0)
+
+   * mjobs/JobsLinkDef.h, mjobs/Makefile:
+     - added MSequence
+
+   * mjobs/MJPedestal.[h,cc]:
+     - changed to allow a sequence as input
+     - changed to allow setting up the extractor from a TEnv
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - moved a common block of code to a new Calc function
+     - fixed ReadEnv
+
+   * mpedestal/MPedCalcPedRun.cc, msignal/MExtractor.cc:
+     - fixed ReadEnv
+
+   * mraw/MRawCrateData.cc:
+     - updated Print()
+
+   * mraw/MRawFileRead.h:
+     - added default to first constructor argument
+
+
+
+
+  2004/08/12: Hendrik Bartko
+
+   * msignal/MExtractor.[h,cc]:
+     - add SetNamePedContainer to set the name of the pedestal
+       container
+
+   * msignal/MExtractTime.[h,cc]:
+     - add SetNamePedContainer to set the name of the pedestal
+       container
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]
+     - add SetNamePedPhotContainer to set the name of the pedphot
+       container
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]
+     - add SetNamePedPhotContainer to set the name of the pedphot
+       container
+
+   * mimage/MImgCleanStd.[h,cc]
+     - add SetNamePedPhotContainer to set the name of the pedphot
+       container
+
+
+
+  2004/08/12 : Wolfgang Wittek
+
+   * manalysis/MSourcPosFromStarPos.[h,cc]
+     - replace MMcEvt by MPointingPos
+
+   * manalysis/MSigmabarCalc.[h,cc]
+     - replace MMcEvt by MPointingPos
+
+   * manalysis/MSigmabar.[h,cc]
+     - in member function Calc() return fSigmabarInner,
+       not fSigmabar
+     - update comments
+     - sigmabar is the sqrt of the average (pedRMS^2/area)
+
+   * manalysis/MPad.[h,cc]
+     - replace MMcEvt by MPointingPos
+     - remove bugs
+
+   * mfilter/MFSelBasic.[h,cc]
+     - replace MMcEvt by MPointingPos
+
+   * mfilter/Makefile
+     - add -I../mpointing
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - replace MMcEvt by MPointingPos     
+     - replace 'MCerPhotPix cerpix' by 'MCerPhotPix &cerpix'
+     - add plot "Sigmabar(Outer) versus Theta"
+
+   * macros/ONOFFAnalysis.C
+     - Job A : got the padding working, work in progress
+
+
+
+ 2004/08/11: Hendrik Bartko
+
+   * mcalib/MCalibrateData.[h,cc]:
+     - add SetPedestalType to choose whether to calibrate the pedestal 
+       for each run or each event
+     - add EnablePedestalType to enable to calibrate the pedestal for 
+       each run or each event
+     - add DisablePedestalType to disable to calibrate the pedestal for 
+       each run or each event
+     - add TestFlag test whether to do the run and / or event pedestal
+       calculation
+     - add SetNamePedADCRunContainer to change name of pedestal input 
+       container for run pedestals
+     - add SetNamePedADCEventContainer to change name of pedestal input 
+       container for event pedestals
+     - add SetNamePedPhotRunContainer to change name of pedestal output 
+       container for run pedestals
+     - add SetNamePedPhotEventContainer to change name of pedestal output 
+       container for run pedestals
+     - add CalibratePedestal, function to calibrate the chosen pedestal 
+     - added the calibration types kFlatCharge, kDummy as in MCalibrate
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - in MBadPixelsCalc::Process() called the MPedPhotCam::ReCalc to
+       calculate the mean values of the pedestal and RMS for the areas
+       and sectors of the camera.
+
+
+
+ 2004/08/10: Thomas Bretz
+
+   * mreport/MReportFileReadCC.[h,cc]:
+     - added
+
+   * mreport/Makefile, mreport/ReportsLinkDef.h:
+     - added MReportFileReadCC
+
+   * mreport/MReport*.[h,cc]:
+     - prpagate file version number to all Interpreters
+
+   * merpp.cc:
+     - added new commandline options to support different CC files
+     - changed help-output
+     - temporarily removed SQL option
+
+   * readraw.cc:
+     - a small fix (a '.' was missing)
+
+   * mraw/MRawEvtData.cc:
+     - fixed bug in Print
+
+   * manalysis/MGeomApply.cc:
+     - changed to Init all MCamEvents in the parlist
+
+   * mbase/MParList.[h,cc]:
+     - added a cast operator to TIterator*
+     - check whether a automatic created class inherits from MParConatiner
+
+   * mgui/MCamEvent.[h,cc]:
+     - added Init
+     - added InitSize
+
+   * mmc/MMcTrig.cxx:
+     - added a new option to Print()
+
+   * mraw/MRawEvtData.[h,cc], mraw/MRawEvtHeader.[h,cc],
+     mraw/MRawFileRead.cc, mraw/MRawSocketRead.cc
+     - changed Init() to InitRead()
+
+   * msignal/MArrivalTime.[h,cc]:
+     - changed argument of InitSize according to MCamEvent
+
+   * msql/MSQLServer.[h,cc]:
+     - small changes to interface
+
+   * mimage/MHillasCalc.[h,cc]:
+     - changed names of TString data members
+
+
+
+ 2004/08/10: Robert Wagner
+
+   * mreport/MReportCamera.[h,cc]
+     - added function InterpreteHOT which interprete the HOT* part of 
+       the report. The variable HVs_modified_by_HOT_Pixels is 
+       extracted, but not yet written in the corresponding MARS
+       parameter container 
+
+
+
+ 2004/08/10: Markus Gaug
+
+   * mcalib/MCalibrationTestCalc.[h,cc]
+     - added calculation and output of maximum not-interpolatable 
+       cluster.
+
+   * macros/bootcampstandardanalysis.C 
+     - added MBadPixelsTreat
+
+
+   * mcalib/MCalibrate.cc
+     - implemented different way to calculate error of signal 
+       in method kFlatCharge (as discussed with Keiichi).
+
+
+
+ 2004/08/10: Florian Goebel
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]
+     - add SetPedContainerName() to change name
+       of output container
+     - fix bug affecting behaviour when running twice
+       over the same run
+     - change format of "Format"
+     - change default value for fgMaxHiGainVar to 40
+
+
+
+ 2004/08/10: Nadia Tonello
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]
+     - replaced flag SetSloppyTreatment() with SetHardTreatment() 
+       Now the default behaviour consists on treating only the 
+       unsuitable pixels, and not also the ureliable, as it was 
+       before. If you want to keep on treating both unsuitable and
+       unreliable pixels, please set the new flag on in your macro. 
+
+   * mjobs/MJExtractCalibTest.cc
+     - removed line containing SetSloppyTreatment()
+
+
+
+ 2004/08/10: Thomas Bretz
+
+   * mpedestal/MPedestalPix.[h,cc]:
+     - as discussed removed fValid
+
+   * mpedestal/MPedCalcFromPedRun.[h,cc], 
+     mpedestal/MPedCalcFromLoGain.[h,cc]:
+     - removed dependancy on MBadPixelsCam
+
+   * mastro/MAstro.[h,cc]:
+     - implemented GetMoonPeriod
+     - implemented GetMoonPhase
+
+   * mbase/MTime.cc:
+     - Fixed a floating point problem in Set(&tv)
+     - added GetDateOfSunrise
+
+
+
+ 2004/08/09: Markus Gaug
+
+   * mcalib/MHGausEvents.[h,cc]
+     - added function IsOnlyOverflow()
+
+   * mcalib/MHCalibrationChargeBlindCam.[h,cc]
+     - put default arguments in the Clone() and the Draw() function 
+       (needed by e.g. TObject::DrawClone())
+     - added name and title to the class (was forgotten)
+
+   * mjobs/MJPedestal.[h,cc]
+     - set the possibility to have the datacheck display with the 
+       function SetDataCheckDisplay()
+
+
+
+  2004/08/09: Wolfgang Wittek
+
+   * mtemp/MStarLocalCam.[h,cc], mtemp/MStarLocalPos.[h,cc]
+     - new variables added for the fit of a 2dim Gaussian with 
+       correlations
+     - the corresponding Set and Get functions were added
+     - the Paint function was extended correspondingly
+
+   * mtemp/MTelAxisFromStars.[h,cc]
+     - new class (task) which determines the source position from star 
+       positions in the camera
+   
+   * mtemp/MHTelAxisFromStars.[h,cc]
+     - new class (container); produce plots for MTelAxisFromStars
+
+   * mtemp/MSkyCamTrans.[h,cc]
+     - new class (task) ; container holding the parameters for the 
+       transformation from sky coordinates (projected onto the camera) 
+       to camera coordinates
+
+   * mtemp/Makefile, mtemp/TempLinkDef.h
+     - MTelAxisFRomStars  added
+     - MHTelAxisFromStars added
+     - MSkyCamTrans       added
+
+   * mtemp/findTelAxisFromStars.C
+     - new macro: extended version of findstars.C 
+       (in mtemp/mifae/macros/)
+     - call to MTelAxcisFromStars and MHTelAxisFromStars
+       was added
+
+   * mtemp/MFindStars.[h,cc]
+     - add correlated Gauss fit
+
+
+
+ 2004/08/06: Markus Gaug
+ 
+   * mcalib/MCalibrationTestCalc.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new class to retrieve the results of MHCalbirationTestCam 
+     - outputs the results of the bad pixels interpolation and the 
+       new relative flat-fielding of the camera.
+
+   * mjobs/MJExtractCalibTest.cc
+     - uncomment (and use) the interpolation of bad pixels
+     - use the class MCalibrationTestCalc
+
+   * mcalib/MHCalibrationChargeLoGainPix.cc
+     - increase the default upper histogram limits for the 
+       large extraction windows.
+
+   * msignal/MExtractor.cc
+     - fixed a bug in one possible output using Form() 
+       which produced a segm.violation in that case.
+
+   * mcalib/MHCalibrationTestCam.cc
+     - adapt class for the interpolation of pixels.
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - fixed a small bug in the calculation of average number of 
+       photo-electrons
+
+
+ 2004/08/06: Nadia Tonello
+
+   * mimage/MImgCleanStd.cc:
+     - in the Process, the Step3 (that checks the boundary pixels) 
+       is skipped when no action is espected, i.e. if lvl1 <= lvl2.
+       This will accelerate the cleaning process in such cases.
+
+   * mbadpixels/MBadPixelsCalc.[h,cc]:
+     - removed dependence on MSigmabar 
+
+
+
+ 2004/08/05: Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - changed return type of AddObject to Bool_t
+     - changed Reading member function to use AddObject
+
+   * msignal/MArrivalTime.h:
+     - Added missing ClassDef
+
+   * mhist/MHEvent.h:
+     - Removed strange MCameraSignal
+
+
+
+ 2004/08/05: Robert Wagner
+
+   * mastro/MAstroCatalog.[h,cc]
+     - Added MAstroCatalog::AddObject, functionality to insert single
+       objects manually; needed for mtemp/mmpi/MSourceDirections
+
+
+
+ 2004/08/05: Thomas Bretz
+
+   * manalysis/MGeomApply.cc, mimage/MCameraSmooth.[h,cc]:
+     - removed dependancy on MBlindPixel
+
+   * macros/sql/readrbk.C, msql/MSQLServer.cc:
+     - fixed some memory leaks - the result of TSQLServer::Query
+       must be deleted
+
+   * mbase/MTaskInteractive.cc:
+     - added some comments
+
+   * mmain/MBrowser.cc:
+     - fixed a bug which caused '/data/MAGIC' not to be shown in
+       the dir-list
+
+   * mmc/MMcEvt.hxx:
+     - added some more particle ids
+
+   * msql/MSQLServer.[h,cc]:
+     - some improvements to the user interface
+
+   * macros/sql/filldotrun.C:
+     - added
+
+
+
+ 2004/08/04: Markus Gaug
+
+   * msignal/MExtractFixedWindowSpline.cc
+     - replaced delete's of the array by a delete [].
+
+   * mjobs/MJCalibration.cc
+     - replaced default time extractor by MExtractTimeFastSpline
+
+   * mbadpixels/MBadPixelsPix.cc
+     - updated the class description
+
+
+
+ 2004/08/04: Thomas Bretz
+
+   * manalysis/MBlindPixels.[h,cc], manalysis/MBlindPixelCalc.[h,cc], 
+     manalysis/MBlindPixelCalc2.[h,cc]:
+     - as discussed some weeks ago the classes have been removed
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed the MBlind* entries
+
+   * star.cc, mmain/MEventDisplay.cc, mmain/MOnlineDisplay.cc, 
+     mmain/MAnalysis.cc, mfileio/MCT1ReadPreProc.[h,cc]:
+     - removed usage of MBlind*
+     - MBadPixel* TO BE ADDED
+
+   * merpp.cc:
+     - moved interpretation of command line options to MLog
+     - added a check for unknown options
+
+   * manalysis/MCameraData.[h,cc]:
+     - added some comments
+     - fixed some errors in the documentation
+     - changed ClassDef to 1
+     - changed the new algorithms such that any number of different
+       pixel-sizes are supported
+     - small modifications to the sanity checks
+
+   * mbadpixels/MBadPixelsTreat.h:
+     - fixed the argument type of SetNumMinNeighbors
+
+   * mbase/MArgs.cc:
+     - comment updated
+
+   * mbase/MEvtLoop.cc:
+     - added reading and writing of fLog environment
+
+   * mbase/MLog.[h,cc]:
+     - added Reading and writing Environment (ReadEnv, WriteEnv)
+     - added a function to setup MLog from command line arguments
+
+   * mbase/MTaskInteractive.[h,cc]:
+     - added an example
+
+   * mbase/MTime.cc:
+     - added a warning for the SetTimeFormat usage
+
+   * mimage/MImgCleanStd.[h,cc]:
+     - some updates to the old comments
+     - NEW COMMENTS FOR SCALED CLEANING STILL MISSING!
+     - implemented scaled image cleaning
+     - replaced usage of MSigmabar by MPedPhotCam for democratic cleaning
+
+   * manalysisct1, manalysisct1/Makefile, 
+     manalysisct1/AnalysisCT1LinkDef.h:
+     - new
+
+   * manalysis/MCT1*, mfileio/structures.h, mfileio/MCT1Read*.[h,cc]:
+     - moved to new directory manalysisct1
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - updated
+     - removed MPad because long time ago changed discuseed were not made
+       (it doesn't compile anymore, because MBlindPixels is missing now)
+
+   * mfileio/Makefile, mfileio/FileIOLinkDef.h:
+     - updated
+
+   * mbase/MLog.cc:
+     - added missing kMustCleanup bit of fPlugins
+
+   * mbadpixels/MBadPixelsPix.h:
+     - added easier access to the information whether a pixel is unsuitable
+       or unreliable
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - added SloppyTreatment
+
+
+
+ 2004/08/03: Hendrik Bartko
+
+   * manalysis/MCameraData.[h,cc]
+     - Added new function CalcCleaningLevel2 to take into account that
+       the pedestal RMS does not scale with the inverse square root of
+       the pixel area for the calculation of the cleaning levels.
+     - Added new function CalcCleaningLevelDemocratic. It calculates
+       the cleaning levels for the democratic image cleaning directly
+       from the average values of MPedPhotCam instead of using 
+       MSigmabar.
+
+
+
+ 2004/08/03: Thomas Bretz
+
+   * macros/sql:
+     - new directory
+
+   * macros/sql/readrbk.C:
+     - new macro
+
+   * mjobs/MJExtractSignal.cc:
+     - fixed missing initialisation of fExtractor, fExtractorTime
+
+
+
+ 2004/07/30: Robert Wagner
+
+   * mastro/MAstroCamera.[h,cc]
+     - Added method FillStarList() which fills a TList with objects
+       of type MStarLocalPos for all stars found from the catalog
+       matching specified criteria (FOV, magnitude limit, position)
+     - Lines involving MStarLocalPos have been commented out for
+       the time being since MStarLocalPos is not part of standard
+       MARS yet!
+
+   * mtemp/MStarLocalPos.[h,cc]
+     - Added handling of the minuit error matrix elements to
+       MStarLocalPos::MSetFitValues
+     - Added member variables to hold error matrix elements
+     - Added getters for error matrix elements
+     - Expected star position is painted by Paint, too.
+     - Error matrix elements are printed by Print, too.
+
+
+
+ 2004/07/28: Javi Lopez
+
+   * mhist/MHCamera.[h,cc]
+     - Added new argument to CntCamContent() funtion to select to count
+       the events above or bellow a certain discriminator level.
+
+
+
+ 2004/07/20: Florian Goebel
+
+   * mpedestal/MPedestalPix.[h,cc]
+     - added: 
+      + fPedestalABoffset: difference between pedestal mean of odd slices
+                           and the total pedestal mean (fPedestal)                
+      + fNumEvents:        number of times, the Process was executed          
+                           (to estimate the error of pedestal)
+
+   * mpedestal/MPedestalCam.cc
+     - calculate error using pixel vise fNumEvents
+
+   * mpedestal/MPedCalcFromLoGain.[h,cc]
+   * mpedestal/Makefile
+   * mpedestal/PedestalLinkDef.h
+     - added class which calculates pedestal values from the low gain
+       slices of a data run
+     - it also calculates the ABoffset values and fills MPedestalPix
+       accordingly
+
+   * macros/ScanPulseABPed.C
+     - macro plotting the pulse shape using MPedCalcFromLoGain
+       and correcting for the AB 150 MHz clock noise.
+
+   * msignal/MExtractSignalABcorr.[h,cc]
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+     - example for signal extractor class similar to MExtractSignal 
+       correcting for ABoffset which allows to use odd number of slices
+
+   * macros/ScanExtractSignalABCorr.C
+     - macro using MExtractSignalABcorr
+
+
+
+ 2004/07/16: Markus Gaug
+
+   * msignal/MExtractFixedWindowSpline.cc
+     - replace the delete's by delete [].
+
+   * mcalib/MHCalibrationChargeCam.cc
+     - remove some obsolete commented code
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - derive only from MHGausEvents and not additionally from 
+       MHCalibrationChargePix
+     - Additional setter for MCalibrationChargeBlindPix, used by 
+       MHCalibrationChargeBlindCam
+     - Getter for fSinglePheCut
+     - adapted Draw for the "datacheck" option
+     - use variable histogram range depending on whether amplitude
+       or integral has been extracted
+
+   * mcalib/MCalibrationChargeBlindCam.[h,cc]
+   * mcalib/MHCalibrationChargeBlindCam.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - two new classes for the treatment of various blind pixels in the 
+       camera
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - adapted to use of various blind pixels
+
+
+
+ 2004/07/15: Markus Gaug
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - hard coded the reference lines for the DataCheck Display. 
+       Should be faster and easier to read than the TArrayF's. 
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - removed obsolete pointer to MEvtTime
+     - fixed bug in calculation of RMS for FFactor of inner pixels
+       in case that the fit does not converge. 
+     - introduced blind pixel and PIN Diode result flags for later
+       output or storage in DB.
+
+
+
+ 2004/07/14: Hendrik Bartko
+
+   * mpedestal/MPedPhotCam.[h,cc]
+     - added average areas and sectors (in analogy MPedestalCam)
+     - added new function InitAreas(const UInt_t i)
+     - added new function InitSectors(const UInt_t i)
+     - added new function GetNumAreas()
+     - added new function GetNumSectors()
+     - added new function ReCalc, computes the average values for the
+       sectors from all pixels which are not marked 
+       MBadPixelsPix::kUnsuitableRun
+
+   * mpedestal/MPedPhotPix.[h,cc]
+     - added a variable for the number of events from which the 
+       pedestals are computed
+
+   * manalysis/MGeomApply.cc
+     - changed initialization of MPedPhotCam
+
+   * msignal/MExtractTimeHighestIntegral.cc
+     - implemented the time calculation respective to the zero FADC
+       time sample, not respective to the first sample of the chosen
+       range
+
+   * msignal/MArrivalTimeCalc2.cc
+     - implemented the time calculation respective to the zero FADC
+       time sample, not respective to the first sample of the chosen
+       range
+
+
+
+ 2004/07/14: Markus Gaug
+
+   * msignal/MExtractedSignalBlindPixel.[h,cc]
+     - added new function GetNumBlindPixels()
+     - added more comments
+
+   * msignal/MExtractBlindPixel.[h,cc]
+     - adapted to new configuration of now three blind pixels
+     - runs with run number smaller than 31693 are treated in the old way
+     - runs with run number higher than 31693 have no more NSB filter, 
+       but possibility to choose between integral or amplitude (with spline) 
+       extraction. Default is amplitude.
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - use the variable fPixId to design an ID to the class. 
+       Later, a new class MHCalibrationChargeBlindCam can host 
+       the different blind pixels as individual 
+       MHCalibrationChargeBlindPix. 
+     - Default ID is 0 which is also default in MExtractedSignalBlindPix
+     - for current code, nothing has thus changed so far...
+
+   * msignal/MExtractAmplitudeSpline.cc
+     - fixed a bug causing a segmentation violation in the destructor 
+       (array dimension was not respected correctly)
+
+   * mcalib/MHGausEvents.cc
+     - removed an inconsistency in the naming of fHPowerProbability which 
+       can cause a memory leak (I hope, this was the cause of some of the 
+       leaks we had, but I'm not sure).
+     - removed the setting of fPixId to -1 in the Clear()
+
+
+
+ 2004/06/30: Thomas Bretz
+
+   * mbase/MEvtLoop.[h,cc]:
+     - overwrite ReadEnv with a new function taking the
+       name of the setup file as argument
+
+   * mjobs/MJPedestal.[h,cc]:
+     - added setup file name as argument to 
+
+   * mjobs/MJPedestal.[h,cc]:
+     - implemented a new data member fEnv
+     - implemented new setter SetEnv
+     - some small changes towards setup files
+     - some simplifications to line drawing
+
+   * msignal/MExtractor.[h,cc]:
+     - added ReadEnv member function
+     - removed obsolete virtual qualifiers in header
+     - simplified usage of Form()
+
+   * mraw/MRawFileWrite.[h,cc]:
+     - moved writing of RunHeaders from PreProcess to new ReInit
+
+
+
+ 2004/06/29: Thomas Bretz
+
+   * mpedestal/MPedCalcFromData.[h,cc]
+     - changed data member names according to coding rules
+
+
+
+ 2004/06/25: Pepe Flix
+
+   * mpedestal/MPedCalcFromData.[h,cc]
+     - added class to evaluate pedestal mean/RMS from real data events.
+       Low Gain samples used when no switch to LG happened.
+
+   * macros/PedCalcFromData.C
+     - added macro that uses the class to evaluate pedestals from real
+       data.
+
+
+
+ 2004/06/23: Markus Gaug
+
+   * macros/calibration.C
+     - added flag to skip the testing
+     - added calibration of pedestal files and creation of F2-files.
+
+   * macros/bootcampstandardanalysis.C
+     - updated to use MJExtractSignal
+
+   * mcalib/MHGausEvents.cc
+     - give a unique name to fHPowerProbability, otherwise 
+       MH::ProjectArray will use an existing one. 
+ 
+
+
+ 2004/06/18: Markus Gaug
+
+   * manalysis/MHPedestalCam.[h,cc]
+     - use flag to choose if one wants to re-normalize the histogram 
+       results
+
+   * mhist/MHCamera.[h,cc]
+     - added one argument to CntCamContent to tell if event above or 
+       below threshold have to be counted. Default is above, like before
+     - added one argument to Projection and ProjectionS giving the number 
+       of bins as argument (default 50 like before)
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - replaced extraction of mean number of photo-electrons and mean 
+       F-Factor by a Gauss fit (instead of mean and RMS). Set the 
+       limit for deviating F-Factor from 3.5 to 4.5. This should reduce 
+       the number of uncalibrated pixels below 50 again (which was not 
+       the case in the last weeks). 
+
+   * mcalib/MHGausEvents.h
+     - make DrawEvents() public
+
+   * mcalib/MHCalibrationChargeLoGainPix.cc
+     - upper histogram limit lowered for the better visibility in the 
+       data check.
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - adapted Draw for the datacheck
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - adapted for various blind pixels
+     - adapted Draw for the datacheck
+
+   * msignal/MExtractor.[h,cc]
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidingWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+   * msignal/MExtractFixedWindowSpline.[h,cc]
+     - made sum in FindSignal() float which is now the variable used by 
+       the majority of the extractors.
+
+   * msignal/MExtractAmplitudeSpline.[h,cc]
+     - new extractor calculating the amplitude using a spline. 
+
+   * mcalib/MCalibrationPix.[h,cc]
+   * mcalib/MCalibrationChargePix.[h,cc]
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - added debug flags and output on debug
+
+   * mbadpixels/MBadPixelsCam.cc
+     - enlarged the Print-function
+
+
+
+ 2004/06/17: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+     - adapted display for the datacheck
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - new function Draw for the datacheck
+     - new clone function for the DrawClone
+  
+   * mcalib/MHCalibrationCam.h
+     - make clone function virtual
+
+   * mjobs/MJCalibration.cc
+     - adapted display for the datacheck    
+  
+   * mcalib/MHGausEvents.h
+     - two new getters for fFirst and fLast
+
+   * mhist/MHCamera.h
+     - make SetUsed() and Fill(x,w) public. It is now possible to use the 
+       Fill-function together with the SetUsed(idx), when no 
+       SetCamContent(...) is available. 
+       Previously, only a Fill(x,y,w) was public, with x and y positions 
+       in the camera. 
+
+  * mjobs/MJPedestal.[h,cc]
+    - updated the data-check display
+
+
+
+ 2004/06/12: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc
+   * mcalib/MMcCalibrationCalc.[h,cc]
+     - Fixed mistake in the calibration which occurred only when 
+       different light collection efficiency was simulated for outer 
+       pixels.
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Adapted to the possibility of having different light collection
+       efficiencies in inner and outer pixels. For now we assume that the
+       dependence with incidence angle on the camera plane is the same
+       for both types of pixels.
+
+
+
+ 2004/06/12: Markus Gaug
+
+   * msignal/MExtractFixedWindow.cc 
+     - output the number and exact range of extraction to *fLog in the 
+       ReInit(), like it is done by MPedCalcPedRun
+
+   * macros/bootcampstandardanalysis.C
+     - exchanged MArrivalTimeCalc2 in 4th loop by timeext (defined 
+       in the beginning)
+
+
+
+ 2004/06/11: Markus Gaug
+
+   * mpedestals/MPedCalcPedRun.cc
+     - set the default upper range to 29, because otherwise the extraction
+       window will be made too small in case that more than 14 "high-gain" 
+       slices shall be extracted. This is a bugfix! It calculated wrong 
+       pedestals in case that the user says: SetRange(a,b), where b is 
+       bigger than 14 in combination with SetWindowSize(x) where x is bigger 
+       than 14 as well (instead of : SetRange(a,b,c,d), where 
+       everything went fine). However, the intention of the last months 
+       changes was to allow exactly also the first possibility. 
+
+   * mjobs/MJCalibration.cc
+     - put run 27474 in list of unavailable runs (see runbook)
+
+
+
+ 2004/06/08: Markus Gaug
+
+   * mhist/MHCamera.cc
+     - reduce number of default bins in AzimuthProfile
+     - use MatchSector in AzimuthProfile, like in RadialProfile
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - fix lower limit for deviation F-Factor to 1.1. This discarts a 
+       smaller number of especially outer pixels in some runs taken with
+       the CT1 pulser box.
+
+
+
+ 2004/06/07: Markus Gaug
+
+   * mcalib/MHCalibrationCam.h
+     - add a function GetSize()
+
+   * msignal/MExtractTimeFastSpline.cc
+     - fixed a bug introduced on 1.6. and accelerate it a bit. 
+
+
+
+ 2004/06/04: Markus Gaug
+
+   * mcalib/MHGausEvents.cc
+     - some small modifications in the way the axes are drawn and their
+       titles are drawn.
+
+
+
+ 2004/06/03: Martin Merck
+
+   * msignal/MArrivalTimeCam.h
+   * msignal/MArrivalTime.h
+   * msignal/MArrivalTimePix.h
+   * msignal/MExtractedSignalCam.h
+   * msignal/MExtractedSignalPix.h
+   * msignal/MExtractedSignalPINDiode.h
+   * msignal/MExtractedSignalBlindPixel.h
+     - Set version in ClassDef to 1 for the streamer.
+
+   * msignal/SignalLinkDef.h
+     - Added a + at the pragma for MExtractedSignalCam and 
+       MExtractedSignalPix for consistency.
+
+   * msjobs/MExtractSignal.[h,cc]
+     - Added methods to set the Extractor and TimeExtractor to be
+       used when extracting the signal.
+
+
+ 
+ 2004/06/03: Markus Gaug
+
+   * mhist/MHCamera.[h,cc]
+   * mjobs/MJCalibration.cc
+     - added functions AzimuthProfile and DrawAzimuthProfile, same 
+       like the RadialProfile functions, only with azimuth instead of 
+       radius.
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - replace fNumHiGainFADCSlices and fNumLoGainFADCSlices by a 
+       TArrayF and increment ClassDef by 1 for the streamer.
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - found a small bug making a difference in the number of valid 
+       pixels with the blind PIxel method and the ffactor method. Now
+       fixed. (The difference was usually a couple of pixels)
+
+   * msignal/MExtractTime.h
+     - make members protected instead of private in order to allow 
+       classes to derive from it
+
+   * msignal/MExtractFixedWindow.cc
+     - added some documentation
+
+   * msignal/MExtractFixedWindowSpline.[h,cc]
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+     - new fast spline signal extractor
+
+
+ 
+ 2004/06/02: Antonio Stamerra
+
+   * mtrigger/*:
+     - added directory and new classes to correctly handle the 
+	trigger-report string from report file. 
+	Not yet into the Makefile.
+
+
+
+ 2004/06/01: Thomas Bretz
+
+   * mbase/MLog.[h,cc]:
+     - some changes to Lock/UnLock of mutices. Necessary for Cosy.
+
+
+
+ 2004/06/01: Abelardo Moralejo
+
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - Added variable fLowGainPeakShift and setter. It allows to shift
+       the integration window for low gain with respect to the one of
+       the high gain. By default its value is 0 (corresponding to a 
+       total delay of 15 slices) so that default behaviour of the
+       extractor is the same as before.
+
+
+
+ 2004/06/01: Markus Gaug
+ 
+   * mjobs/MJCalibration.cc
+     - small change in the way the "full display" is displayed
+
+   * mcalib/MHCalibrationChargeBlindPix.cc
+   * mcalib/MHCalibrationChargePix.cc
+     - replace Draw(opt) by Draw(). This make the histograms reappear 
+       again, although I have no idea why. A printout of the opt gives 
+       always empty. 
+
+   * mcalib/MCalibrationQEPix.cc
+     - put Eckarts transmission of the plexiglass into the class 
+       documentation
+
+   * msignal/MExtractTimeFastSpline.cc
+     - fixed some smaller bugs affecting a small part of the signals
+
+
+ 2004/05/31: Hendrik Bartko
+
+   * msignal/MArrivalTimeCalc2.cc
+     - fixed a bug in pointer arithmetics found by Florian.
+
+
+
+ 2004/05/31: Raquel de los Reyes
+
+   * macros/DAQDataCheck.C
+     - committed the macro to check the raw data and display the quality
+       plots.
+
+
+
+ 2004/05/30: Markus Gaug
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - added more documentation (plots)
+     - separated calls for light guides eff. , QE, and coll. eff.
+   
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - fixed a small bug in the calculation of the error on the number 
+       of photons with the F-Factor method, did not include the division
+       by number of pixels for the precision of the QE. This does not 
+       affect the general analysis. 
+
+   * mjobs/MJCalibration.cc
+     - added runnumber 26924 to list of runs without clear colour in 
+       the file name. 
+
+
+
+ 2004/05/28: Markus Gaug
+
+   * macros/calibration.C
+     - make the macro compilable with possibility to run it in batch 
+       mode. 
+
+   * msignal/MExtractor.cc
+     - put an additional check in case that the number of FADC slices 
+       in the run header is smaller or equal to 0.
+
+
+
+ 2004/05/27: Javier Rico
+
+   * mbase/MDirIter.h 
+     - remove unneeded ResetIter method (Reset does all the job)
+
+   * mjobs/MJCalibration.cc
+     - change call to the removed MDirIter::ResetIter for Reset
+	
+
+
+ 2004/05/27: Markus Gaug
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]
+     - put some protection against zero-division in fitFuncMichele
+
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+     - set flag to distinguish between coated and un-coated blind pixel
+     - increase ClassDef number by one.
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - set a global variable CollEfficiency and LightguidesEfficiency. 
+       The more precise result for the QE calculated with 
+       the F-Factor method differs now by about 5% (while the statistical
+       error remains around 20%). 
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - write the number of photons directy into MCalibrationChargeCam. 
+       These numbers would otherwise have to be assembled by different 
+       parts in separate code. 
+
+
+
+ 2004/05/27: Thomas Bretz
+ 
+   * mastro/MAstroCatalog.cc
+     - removed a statement after '#endif'
+
+   * mastro/MAstroCamera.h
+     - removed obsolete empty function which (believing the Changelog)
+       are not there at all!
+
+   * mbase/MDirIter.[h,cc]:
+     - moved code of Reset() funtion to source file
+     - added more comments to Reset function
+
+
+
+ 2004/05/26: Martin Merck
+
+   * mbase/MDirIter.cc
+     - changed MatchFilter to allow for filenames containing a '+'
+       character.
+
+
+
+ 2004/05/26: Markus Gaug
+
+   * mjobs/MJCalibration.[h,cc]
+     - set MCalibrationChargeBlindPix and MCalibrationChargePINDiode as 
+       data members and store them in the output of WriteResult()
+
+   * mcalib/MCalibrationQEPix.cc
+   * mcalib/MCalibrationChargeCalc.cc
+     - several small bugs fixed concerning calibration with the blind
+       pixel or the PIN Diode
+
+   * mjobs/MGCamDisplays.[h,cc]
+   * mhist/MHCamera.[h,cc]
+     - put the last function (CamDraw) of MGCamDisplays into MHCamera
+       and removed MGCamDisplays.
+
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - don't derive from MGCamDisplays any more.
+
+   * msignal/MExtractBlindPixel.cc
+     - adjusted some default numbers for the current blind pixel
+
+   * msignal/MExtractedSignalBlindPixel.[h,cc]
+     - set extracted signal from UInt_t to Int_t (sometimes, less
+       than 0)
+
+   * mcalib/MCalibrationCam.h
+   * mcalib/MHCalibrationCam.h
+     - make destructors virtual. 
+
+   * mcalib/MHCalibrationCam.[h,cc]
+     - create a copy contructor
+
+
+
+ 2004/05/26: Javier Rico
+
+   * mbase/MDirIter.h
+     - Add method to reset the internal TIter iterator 
+
+   * mjobs/MJCalibration.cc
+     - In FindColorReset method, reset the file iterator before looping
+
+   * mimage/MNewImagePar.cc
+     - Add output lines in Print(const MGeomCam &geom) method for 
+       fInnerLeakage1, fInnerLeakage2 and fInnerSize
+
+
+
+ 2004/05/25: Raquel de los Reyes and Thomas Bretz
+
+   * mjobs/MJCalibration.cc
+     - uncommented the line to read .raw files.
+
+   * mraw/MRawFileRead.cc
+     - changed the PreProcess and Process functions to allow the analysis
+       of .raw files.
+
+   * mfileio/MReadReports.cc
+     - changed the Process function to read the updated root files.
+
+
+
+ 2004/05/25: Markus Gaug
+
+   * mjobs/MJCalibration.[h,cc]
+     - add possibility to switch on and off the blind pixel or pin diode
+       calibration
+     - fixed a small bug in reading the MCalibrationRelTimeCam when the
+       times calibration has been switched off.
+
+   * mjobs/MExtractSignal.[h,cc]
+     - made changes in MProcessFileP such that it fits with the new 
+       calibration. THIS IS ONLY A TEMPORARY SOLUTION. PEDESTALS AND 
+       DATA FILES MUST BE TREATED EQUALLY! OTHERWISE THERE IS NOT 
+       MATCHING FOR THE HIT CLEANING!!!
+
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - implement switch to use or not the cosmics filter
+
+ 
+   * mcalib/MHCalibrationTestPix.cc
+     - enlarged the dynamic range of the histograms for the high-int. 
+       pulses
+
+
+
+ 2004/05/24: Javier Rico
+
+   * mpedestal/MPedPhotCalc.cc
+     - Correct a bug that made pedestals be assigned to the wrong pixel
+
+   * mimage/MNewImagePar.[h,cc]
+     - add getters and output lines in Print() method for 
+       fInnerLeakage1, fInnerLeakage2 and fInnerSize
+
+
+
+ 2004/05/24: Markus Gaug
+
+   * mcalib/MCalibrationChargePix.cc
+     - reduce limit in number of phe's from 5 to 1. since some pulses 
+       have less than 5 phe's now.
+
+   * mcalib/MHCalibrationTestCam.[h,cc]
+     - number of photons/area are now stored in TArray's in order to 
+       retrieve them easier in later processing from stored files.
+
+   * mcalib/MCalibrationCam.cc
+     - initialize AverageAreas and AverageSectors with the number of 
+       aidx and sector as SetPixId()
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - small modification in the Print()
+     - introduce data members to store the average number of photons by 
+       the three methods
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - calculate the limits for acceptance of number of photo-electrons
+       for the calculation of the mean by normal mean instead of weighted 
+       mean. There were too many outliers still present in the weighted
+       mean such to modify the result by a sizeable amount.
+     - do not discard unreliable pixels any more in calculation of 
+       mean number of phe.s In some runs, there is simply too many of 
+       them in order to get reliable results.
+
+   * mpedestals/MPedCalcPedRun.cc
+     - put a condition if number of pixels in area index or in sector 
+       is zero, don't calculate av. pedestal and av. pedRMS of this part.
+
+
+
+ 2004/05/22: Markus Gaug
+
+   * mjobs/MJPedestal.[h,cc]
+   * mjobs/MJCalibration.[h,cc]
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - replaced the TString GetOutputFile() functions by const char* 
+       GetOutputFile(). This apparenty caused a memory leak which is now 
+       removed.
+
+   * mcalib/MCalibrationChargePix.cc
+     - fixed bug calculating the reduced sigma for low-gain events: 
+       the electronics Ped.RMS was taken from Hi-gain pedestal events and 
+       too high. It is now divided by the factor 10. conversion between 
+       both samples, but this value is probably too optimistic. Needs 
+       more detailed studies, but does not exclude as many pixels as 
+       before. 
+
+   * mcalib/MHCalibrationChargePix.h
+   * mcalib/MHGausEvents.h
+     - put fSaturated from MHCalibrationChargePix into MHGausEvents
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+   * mcalib/MHCalibrationCam.h
+     - put fNumHiGainSaturated and fNumLoGainSaturated from 
+       MHCalibrationChargeCam into MHCalibrationCam
+
+   * mcalib/MHCalibrationRelTimeCam.[h,cc]
+     - set flags fSaturated in order to distinguish if the hi-gain or 
+       the low-gain time has been extracted. 
+
+   * mcalib/MHCalibrationCam.cc
+     - remove cloning of all pixels on the Clone() function. This caused 
+       the need for three times more memory during runtime than now. It 
+       should not affect the current macros.
+
+   * macros/calibration.C
+     - added a debug switch with which you can print out Object
+       Allocation (like suggested by TBretz).
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - replaced the relative limit for acceptance of the time resolution 
+       by an absolute limit
+     - set up output statistics logging (data written into DB)
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - moved limit for acceptance of number of phe;s from 5 to 8
+     - set up output statistics logging (data written into DB)
+
+   * mjobs/MJCalibration.cc
+     - set up output statistics logging (data written into DB)
+
+
+
+ 2004/05/22: Abelardo Moralejo
+
+   * macros/calibrate_data.C
+     - removed wrong call to MPedCalcPedRun::SetExtractor, which does
+       not exist (should use MJPedestal like calibration.C, instead of 
+       a normal loop)
+
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - changed name of variable fOffsetFromPeak to fOffsetFromWindow
+       to avoid confusion.
+     - introduced initialization to 0 of startslice and sat in FindPeak
+     - changed initialization of maxsumhi in Process from 0 to -1e6
+
+
+
+ 2004/05/20: Raquel de los Reyes
+ 
+   * mraw/MRawRead.h
+   * mraw/Makefile
+   * msql/Makefile
+     - changed the inheritance of MRawRead class from MTask to MRead to
+       implement the AddFiles(MDirIter &) function in MRawFileRead class.
+
+   * mraw/MRawFileRead.[h,cc]
+     - implemented a second argument to the AddFile function and skip 
+       adding NULL files in the constructor.
+
+   * mjobs/MJPedestal.cc
+     - uncommented the line to allow the analysis of .raw files.
+
+
+
+ 2004/05/20: Markus Gaug
+ 
+   * mjobs/MJPedestal.cc
+     - put MGeomCamMagic into the plist (MGeomApply complained not to 
+       find the GeomCam(
+
+   * msignal/MExtractFixedWindowPeakSearch.cc
+     - fixed a bug affecting signals with late arrival times which use 
+       the variable fHiLoLast. 
+     - set back fgOffsetFromPeak from peak to 1 (instead of 2). Abelardo 
+       explained that this variable is not strictly the offset from the 
+       peak but the offset from the peak search window. 
+
+
+
+ 2004/05/19: Markus Gaug
+ 
+   * mcalib/MCalibrationChargeCam.cc
+     - replaced a small bug in Print() which gave a segmentation 
+       violation	
+
+   * mjobs/MJCalibration.cc
+     - use cosmics filter only for CT1 pulser runs
+
+
+
+ 2004/05/19: Abelardo Moralejo
+
+   * mbase/MGMap.cc
+     - replaced rint by TMath::Nint() (my Mac did not recognize the 
+       former)
+
+
+
+ 2004/05/19: Abelardo Moralejo
+
+   * macros/starmc2.C
+     - added third argument in adding MPointingPos to the output:
+       write.AddContainer("MPointingPos",  "Events", kFALSE);
+       If not exisiting in the input file, it is simply ignored.
+
+
+
+ 2004/05/15: Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - changed Form to MString for thread safty
+     - fixed a bug which caused the construtor to crash in batch-mode
+     - added option argument to PaintImg
+
+   * mbase/MGMap.[h,cc]:
+     - added many new static member function to draw figures
+
+   * mbase/MParContainer.cc:
+     - changed Form to MString for thread safty
+
+   * mbase/MString.[h,cc]:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MString
+
+
+
+ 2004/05/15: Markus Gaug
+
+   * msignal/MArrivalTimePix.h
+   * msignal/MArrivalTimeCam.cc
+     - introduced functin GetHiGainSaturation() in MArrivalTimePix.h
+     - added type in GetPixelContent() which asks for Hi-Gain saturation
+       and return the hi-gain time or the low-gain time, correspondingly.
+
+   * mbase/MGMap.cc
+     - fixed two bugs which did not complile under gcc 3.3.x introduced
+       by TB.
+
+
+
+ 2004/05/12: Markus Gaug
+
+   * msignal/MExtractTime.[h,cc]
+     - introduced intrinsic delay of low-gain, as measured by Florian. 
+
+   * mjobs/MJCalibration.cc
+   * mjobs/MJExtractCalibTest.cc
+     - fixed some errors in the storage of the rel. times.
+
+   * mjobs/MJExtractCalibTest.cc
+     - put the cosmics filter which was forgotten
+
+   * mcalib/MCalibrate.h
+     - changed default from Blindpixel to Ffactor     
+
+
+
+ 2004/05/12: Thomas Bretz
+
+   * mona.cc:
+     - changed names
+
+   * macros/sumcurrents.C:
+     - changed units from nA to \\mu A
+
+   *: mastro/MAstroCamera.[h,cc]:
+     - added '=' Draw option
+     - use fMapG directly
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - added support to read and write a compressed catalog
+     - changed TExMap to new MGMap
+     - added support for HeasarcPPM catalog
+     - added PaintImg to paint catalog into a bitmap (used in
+       starguider software)
+     - don't clone MObservatory copy the contents
+     - changed type of dx and dy in DrawLine from Double to Int
+     - fixed drawig of the tooltip corresponding to the grid
+       (some were missing, some were existing twice)
+     - Now AddPrimitives takes fLimMag into account
+
+   * mhbase/MFillH.cc:
+     - added a const-qualifier
+
+   * mhist/MHCamera.cc:
+     - fixed a bug which caused SetPalette in the constructor to crash
+
+   * mbase/MGMap.[h,cc]:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MGMap
+
+
+
+ 2004/05/11: Thomas Bretz
+
+   * mraw/MRawEvtHeader.cc:
+     - added a check whether the file has finished or not after
+     reading the first bytes.
+
+
+
+ 2004/05/10: Marcos Lopez
+
+   * mmontecarlo/MMcEnergyEst.cc: 
+     - In static void fcn(...), fixed the following bugs which caused a
+       "segmentation violation":
+     - Replace: MTaskList *tlist  = evtloop->GetTaskList()
+       by:      MTaskList *tlist = (MTaskList*)plist->FindObject("MTaskList")
+     - And get the pointer *eval to MParamterD("MFitResult"), after 
+       the excution of the Eventloop and not before it (since that object is 
+       created when calling the PreProcess).
+
+
+
+ 2004/05/10: Thomas Bretz
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - changed return type of ReadEvt from int to Int_t
+     - Enhanced output in case of invalid time
+
+   * mraw/MRawRead.cc:
+     - fixed the return type of ReadEvt (was bool instead of int)
+       which confused merpp completely in case of invalid times
+
+
+
+ 2004/05/10: Markus Gaug
+
+   * macros/calibrate_data.C
+     - updated setting of arr. time extractor
+
+
+
+ 2004/05/09: Thomas Bretz
+
+   * Makefile:
+     - added workaround for Mac to create so- and dynlib-object
+
+   * Makefile.conf.darwin:
+     - added necessary option to create both kind of files
+
+   * Makefile.conf.linux:
+     - changed the options to create so-object only
+
+   * Makefile.rules:
+     - added DYLIB to rmbin
+
+   * mraw/MRawEvtData.cc:
+     - changed some output
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - skip the rest of the header if the time is invalid. Otherwise
+       merpps force-mode will corrupt the data when further processing
+     - implemented GetNumBytes returning the size of the header
+
+
+
+ 2004/05/08: Thomas Bretz
+
+   * mona.cc:
+     - some changes to make it work again
+
+   * mraw/MRawSocketRead.cc:
+     - fixed the sync with what DAQ sends
+
+
+
+ 2004/05/07: Markus Gaug
+
+   * mcalib/MHCalibrationChargeHiGainPix.cc
+   * mcalib/MHCalibrationChargeLoGainPix.cc
+     - take out half of the bins for the hists in order to save memory  
+
+   * mjobs/MExtractCalibTest.cc
+     - include write-out of the containers in the loop
+
+   * mjobs/MJCalibration.cc
+     - take runs 20660 and 20661 into the list of known runs with colour
+       green.
+
+   * mpedestal/MPedCalcPedRun.[h,cc]
+     - make the arrays fSum and fSum2 doubles. This is necessary since 
+       rounding errors of the floats introduced significant errors in the 
+       RMS! 
+     - introduced one condition about possible window sizes of 0.
+
+
+
+ 2004/05/06: Markus Gaug
+
+   * htmldoc/images/PedestalStudyInner.gif
+   * htmldoc/images/PedestalStudyOuter.gif
+     - two gifs used for the documentation of MPedCalcPedRun  
+
+   * mpedestal/MPedCalcPedRun.cc
+     - updated documentation
+
+   * macros/pedestalstudies.C
+     - updated to the latest version of MPedCalcPedRun
+
+   * macros/bootcampstandardanalysis.C
+     - updated to the latest changes in the ArrivalTime Extraction
+
+
+
+ 2004/05/05: Markus Gaug
+
+   * mcalib/MHGausEvents.cc
+     - removed some warning saying "Cannot create Fourier spectrum"
+
+   * mcalib/MCalibrationChargePix.cc
+     - loosened the limits somewhat for calibration with the low-gain
+     - introduced different electronic noise for inner and outer pixels
+       (like seen in the data)
+
+   * mpedestal/MPedCalcPedRun.cc
+     - fixed a small inconsistency in case that the range goes out of 
+       the high-gain samples and reaches into the low-gain samples. In 
+       that case, the last slice of the high-gain was not taken (but the 
+       window size correctly)
+ 
+   * mjobs/MJExtractCalibTest.[h,cc]
+     - included setters for the time extractor
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - set default of fgPheErrLimit from 4 sigma to 5.
+
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+   * mcalib/MHCalibrationTestTimeCam.[h,cc]
+   * mcalib/MHCalibrationTestTimeCam.[h,cc]
+     - analogue to MHCalibrationTestCam, two classes to test the 
+       output of the calibration.
+
+   * mcalib/MHCalibrationCam.cc
+     - in InitHists, exclude only pixels with kUnsuitableRun, instead of 
+       all (IsBad())
+
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+   * msignal/MExtractTimeFastSpline.[h,cc]
+     - new fast spline extractor for the equally spaced time slices. 
+       Searches for the position of the half maximum between maximum and 
+       pedestal. About 6 times faster than MArrivalTimeCalc
+
+   * mjobs/MJCalibration.cc
+     - changed names of the MHCameras to contain run name
+
+
+
+ 2004/05/04: Raquel de los Reyes
+ 
+   * mbase/MRunIter.[h,cc]
+     - Added a flag and a set function to read .raw files. 
+       The default option is set to read .root files.
+
+
+
+ 2004/05/04: Javier Rico
+ 
+   * mcalib/MCalibrate.cc
+     - when calibrating using kNONE, weight by the pixel area
+
+
+
+ 2004/05/04: Thomas Bretz
+ 
+   * macros/MagicHillas.C, macros/comprob.C, macros/derotatedc.C, 
+     macros/dohtml.C, macros/evtrate.C, macros/merpp.C, 
+     macros/pixfirerate.C, macros/pixsatrate.C, macros/plot.C, 
+     macros/plot2.C, macros/pointing.C, macros/readMagic.C, 
+     macros/rootlogon.C, macros/runbook.C, macros/sectorvstime.C, 
+     macros/star.C, macros/sumcurrents.C, macros/tar.C, 
+     macros/testenv.C, macros/weights.C:
+     - updated documentation
+
+   * mastro/MAstroCamera.[h,cc]:
+     - added member function to read MC .def files for mirror geometry
+     - added GetDiffZdAz
+
+   * mastro/MObservatory.[h,cc]:
+     - added Copy-member function
+
+   * mbase/MLog.[h,cc]:
+     - updated handling of mutices
+     - added a new mutex to lock the stream
+
+   * mhist/MHCamera.[h,cc]:
+     - added functionality to linear deform the camera display
+       (to correct for abberation)
+
+   * mtools/MFFT.cc:
+     - added more documentation
+
+   * mbase/MTime.[h,cc]:
+     - renamed overloaded Set-function to SetMjd. There were some
+       trouble with the interpreter and the new naming is more
+       intuitive.
+
+
+
+ 2004/05/04: Markus Gaug
+ 
+   * mcalib/MHCalibrationChargeBlindPix.cc
+     - intialized the 2 vectors differently, now they don't give 
+       warnings any more.
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractFixedWindow.cc
+     - put one initialization to 0 into the MExtractor
+
+   * mastro/MAstroCatalog.h
+     - make AlignCoordinates() protected, in order to compile
+
+   * mcalib/MHGausEvents.cc
+     - took out fEvents(0) and fHGausHist() from constructor
+
+   * msignal/MExtractor.cc
+   * msignal/MExtractPINDiode.cc
+     - fixed StreamPrimitive
+
+   * msignal/MExtractBlindPixel.[h,cc]
+     - deriving from MExtractor, possibility to filter NSB events
+
+ 
+
+ 2004/05/03: Thomas Bretz
+
+   * mbase/MRunIter.cc:
+     - AddRuns(char*) added some const-qualifiers
+     - replaced deprecated if-else-if by continue- and return-
+       constructions
+
+
+
+ 2004/05/03: Javier Lopez
+ 
+   * mbadpixels/MBadPixelsPix.[h,cc]
+     - put another enum for hardware malfunctionning. Started to be 
+       filled with kHVNotNominal
+
+
+
+ 2004/05/03: Markus Gaug
+
+   * mcalib/MHCalibrationBlindPix.[h,cc]
+     - removed a "->" behind the comment
+     - Create a TVector in Draw only if the array is not zero
+
+   * mraw/MRawEvtPixelIter.cc
+     - corrected bug in GetIdxMaxLoGainSamples() which looped over 
+       one slice too much 
+	end = fLoGainPos + fNumLoGainSamples + 1 replaced by:
+	end = fLoGainPos + fNumLoGainSamples
+
+   * msignal/MTimeExtractor.[h,cc]
+   * msignal/MExtractTime.[h,cc]
+     - changed name for alphabetical display in dox
+
+   * mjobs/MJCalibration.[h,cc]
+   * msignal/MExtractTimeSpline.h
+   * msignal/MExtractTimeHighestIntegral.h
+     - changed name of base class to MExtractTime
+
+   * mcalib/MCalibrationCam.[h,cc]
+   * mcalib/MCalibrationChargeCam.[h,cc]
+   * mcalib/MCalibrationRelTimeCam.[h,cc]
+     - put the number of unsuitable and unreliable pixels in the base
+       class
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - fixed a bug calculating the average time resolution
+ 
+   * mpedestals/MPedestalPix.[h,cc]
+     - add a dedicated fValid flag in order to be able to discard pixels 	 
+       from outside (e.g. from MBadPixelsCam)
+
+   * mpedestals/MPedCalcPedRun.[h,cc]
+     - catch badpixels cam from parameter list, if existing and set 
+       corresponding pixels to not valid in MPedestalPix
+
+   * mjobs/MGCamDisplays.[h,cc]
+   * mhist/MHCamera.[h,cc]
+     - put DrawProjection and DrawRadialProfile in MHCamera
+
+   * macros/dohtml.C
+     - include directory mfit and macros calibration.C and 
+       bootcampstandardanalysis.C
+     - take out pixvstime.C which does not exist
+
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidingWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+   * msignal/MExtractor.[h,cc]
+   * msignal/MExtractPINDiode.[h,cc]
+   * msignal/MExtractTime.[h,cc]
+     - set number of slices not in base class, but in derived one. 
+       Like this, extractors setting their signal in other containers 
+       don't have a conflict with the ReInit() in MExtractor.
+
+
+
+ 2004/05/01: Thomas Bretz
+
+   * macros/rootlogon.C:
+     - ignore MARSSYS if libmars.so is found in the current path
+
+   * mastro/MObservatory.cc:
+     - small change to coordinates
+
+   * mbase/MLog.[h,cc]:
+     - enhanced output in case of problem with mutices
+
+   * mtemp/TempIncl.h, mtemp/TemlLinkDef.h:
+     - removed everything
+
+   * Makefile*, */Makefile
+     - changed all to support mtemp/mifae and similar
+
+
+
+ 2004/05/01: Abelardo Moralejo
+
+   * mmain/MEventDisplay.cc
+     - changed back integration range for MC to 0-14 slices to avoid 
+       confusions.
+
+
+
+ 2004/05/01: Markus Gaug
+
+   * macros/dohtml.C
+     - include directory mpedestal
+
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidingWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+   * msignal/MExtractor.[h,cc]
+     - include the possibility to set the range for the hi-gain outside
+       the range of MRawEvtPixelIter::GetNumHiGainSamples() and to take 
+       the "low-gain" slices instead. This is necessary for the March 
+       data!
+
+   * mjobs/MJCalibration.[h,cc]
+     - accept arrival time extractors deriving from MTimeExtractor
+
+
+
+ 2004/04/30: Thomas Bretz
+
+   * mastro/MAstroCamera.[h,cc]:
+     - removed obsolete TList data member (use a argument in
+       GetStarList instead)
+
+   * mbase/MTime.h:
+     - added 'istream &operator<<(istream &in, MTime &t)'
+
+   * mbase/BaseLinkDef.h:
+     - added new operator
+
+
+
+ 2004/04/30: Daniela Dorner
+  
+   * macros/pointing.C
+     - implemented plot: Control Deviation vs Time
+     - rearranged plots
+
+
+
+ 2004/04/30: Markus Gaug
+
+   * mcalib/MCalibrationRelTimeCalc.[h,cc]
+     - new class to treat rel. times after fits
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - search for outliers in the total F-Factor and set a flag in 
+       MBadPixelsPix
+
+   * mcalib/MCalibrationRelTimeCam.h
+     - new TArrayIs to store number of unsuitable and unreliable pixels
+   
+
+   * mbadpixels/MBadPixelsPix.h
+     - two new flags added: kDeviatingFFactor and kDeviationTimeResolution
+  
+   * mcalib/MHCalibrationRelTimePix.[h,cc]
+     - take out commented part of code related to re-normalization
+
+   * mcalib/MHCalibrationCam.[h,cc]
+     - retrieve the used run numbers in order to store them in teh 
+       histogram titles to help transparency of the displays
+
+   * mcalib/MHCalibrationRelTimeCam.[h,cc]
+     - Getter and Setter for the reference pixel
+
+   * mcalib/MCalibrate.cc
+     - make error of nphot to be taken from square root of absolute 
+       number of photons instead of number of photons, otherwise 
+       NaN's are obtained
+
+   * msignal/MExtractPINDiode.[h,cc]
+     - now deriving from MExtractor
+
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+   * msignal/MExtractTimeSpline.[h,cc]
+   * msignal/MExtractTimeHighestIntegral.[h,cc]
+     - replacements for MArrivalTimeCalc and MArrivalTimeCalc2
+
+   * mjobs/MJCalibration.[h,cc]
+     - Set time extractor by pointer 
+
+
+
+ 2004/04/29: Thomas Bretz
+
+   * mbase/MTask.cc:
+     - fixed behaviour of GetNumExecutions. Because of a root bug
+       Count returns a number which is to high by 1.
+
+
+
+ 2004/04/29: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Added minor comment (explanation of fPassPhotCone).
+
+   * mmc/MMcRunHeader.[hxx,cxx]
+     - Removed obsolete parameters fSourceOffsetTheta, fSourceOffsetPhi
+     - Updated class version to 5.
+
+
+
+ 2004/04/29: Nadia Tonello
+
+   * mbadpixels/MBadPixelsTreat.h
+     - changed enums {.. BIT(1), ... BIT(2), ... BIT(3) } in {1,2,3}
+       to have the right behaviour of the flags (and of SetProcessRMS)
+
+   * manalysis/MCT1PointingCorrCalc.[h,cc]
+     - added pointing correction for 1ES1959
+
+
+
+ 2004/04/29: Markus Gaug
+
+   * msignal/MArrivalTimePix.[h,cc]
+     - removed flag fLoGainUsed which is not used at all
+
+   * msignal/MTimeExtractor.[h,cc]
+     - new base class for arrival time extractors
+   
+   * msignal/Makefile
+   * msignal/SignalLinkDef.h
+   * msignal/MExtractTimeSpline.[h,cc]
+     - replacement of MArrivalTimeCalc, derived from MTimeExtractor
+
+
+   * msignal/MExtractor.h
+     - make SetRange virtual
+     - check for range w.r.t. ranges given in the run header in ReInit
+
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidingWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - overload the SetRange() function in order to do the necessary 
+       checks of the range there. Slight differences in every extractor
+       because of the floating windows.
+
+
+   * mpedestals/MPedCalcPedRun.[h,cc]
+     - add the possibility to set ranges and extraction windows. Default
+       is what has always been
+
+
+   * mjobs/MJPedestals.[h,cc]
+     - add the possibility to set a signal extractor which gives the 
+       extraction ranges to MPedCalcPedRun
+     - derive from MHCamDisplays
+
+   * mcalib/MCalibrationChargeCam.cc
+     - updated the Print() a little
+
+
+ 2004/04/29: Javier Rico
+
+   * mbase/MRunIter.cc
+     - Remove AddRuns(const char*,const char*) dependence on length of 
+       first character chain
+
+	
+ 2004/04/28: Javier Rico
+
+   * mbase/MRunIter.[h,cc]
+     - include function to read runs specified in a character chain
+       with the format, e.g., run1,run2-run3,run4-run5,...
+
+
+
+ 2004/04/28: Abelardo Moralejo
+
+   * macros/starmc.C
+     - adapted to change in MC calibration: replaced 
+       MMcCalibrationCalc::GetHist by GetHistADC2PhotEl and 
+       GetHistPhot2PhotEl.
+
+
+
+ 2004/04/28: Markus Gaug
+ 
+   * mjobs/MGCamDisplays.cc
+   * mjobs/MJCalibration.cc
+     - introduced new "fit" flag in DrawProjection allowing to draw 
+       two separate pad with the (fitted) histograms for inner and 
+       outer pixels. This is displayed by MJCalibration if the 
+       kNormalDisplay option is chosen (default).
+
+   * mjobs/MJCalibration.h
+     - took out the const of GetBadPixels() in order to allow compilation
+       of macros/bootcampstandardanalysis.C. This will change again soon 
+       when mjobs/MJExtraction is updated and used there. 
+
+   * msignal/MArrivalTimeCalc.[h,cc]
+     - remove the ReInit() which calls to an MGeomCam which is later not 
+       used
+
+   * macros/calibrate_data.C
+     - fixed a bug in loop 3 taking the default QE Cam instead of the 
+       one filled by MJCalibration 
+
+   * msignal/MExtractor.[h,cc]
+     - new base class for signal extractors
+
+   * msignal/Makefile	
+   * msignal/SignalLinkDef.h	
+   * msignal/MExtractFixedWindow.[h,cc]
+   * msignal/MExtractSlidindWindow.[h,cc]
+   * msignal/MExtractFixedWindowPeakSearch.[h,cc]
+     - replacements for MExtractSignal, MExtractSignal2, MExtractSignal3
+
+   * macros/calibration.C
+   * macros/calibrate_data.C
+   * macros/pedphotcalc.C
+   * macros/bootcampstandardanalysis.C
+     - adapted to new extractors
+
+   * mbadpixels/MBadPixelsPix.h
+     - set back the old definition of IsOK(), namely no information 
+       available
+
+
+
+ 2004/04/27: Raquel de los Reyes
+
+   * mhvstime/MHVsTime.cc
+     - added a line in the Fill function to avoid empty time events.
+
+
+
+ 2004/04/27: Abelardo Moralejo
+
+   * mcalib/MMcCalibrationCalc.[h,cc]
+     - added histogram which stores the conversion of photons before 
+       the plexiglas to photoelectrons hitting first dynode.
+
+   * macros/mccalibrate.C
+     - added MPointingPosCalc to the tasklist to create and fill an 
+       MPointingPos object, and later write it to the Events tree of 
+       the calibrated MC files. Added some comments and simplified
+       some lines. One more histogram from MMcCalibrationCalc (see
+       above) is now written to the output.
+
+   * macros/starmc2.C
+     - added the writing of MPointingPos to output star file.
+
+
+
+ 2004/04/27: Markus Gaug
+
+   * mjobs/MJCalibration.[h,cc]
+     - put the three camera drawing facilities into a separate base 
+       class MGCamDisplays
+
+   * mjobs/MGCamDisplays.[h,cc]
+   * mjobs/Makefile
+   * mjobs/JobsLinkDef.h
+     - camera drawing facilities: CamDraw, DrawProjection and 
+       DrawRadialProfile, used by all jobs
+
+   * mjobs/MJExtractCalibTest.[h,cc]
+   * mjobs/Makefile
+   * mjobs/MJobsLinkDef.h
+     - new class to test the calibration results
+
+   * mcalib/MCalibrationChargeCalc.cc
+     - set unsuitable pixels to excluded in MCalibrationChargePix, which 
+       will not display them in the status display
+
+   * mjobs/MJCalibration.cc
+     - take out display of previously excluded pixels 
+
+   * mbadpixels/MBadPixelsCam.cc
+     - set val to 1 in case that GetPixelContent is true, before display 
+       was not correct
+
+   * macros/calibration.C
+     - added the test class MJExtractCalibTest
+
+
+
+ 2004/04/27: Abelardo Moralejo
+
+   * mhistmc/MHMcCollectionArea.[h,cc]
+     - Added fMCAreaRadius and setter to allow changing the radius of
+       the circular area in which MC events are produced. Useful for
+       instance for stereo configuration studies. By default it is 300 m
+       as was assumed before.
+
+
+
+ 2004/04/26: Markus Gaug
+
+   * mcalib/MHCalibrationTestPix.[h,cc]
+   * mcalib/MHCalibrationTestCam.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - two new histogram classes to perform claibraion checks, will be 
+       especially useful for the data-check.
+
+   * mcalib/MCalibrationQEPix.cc
+     - found a bug in the setting of validity flags of colours. This 
+       made the QE used for calibration uncorrect by about a factor 1.5 
+       for the outer pixels if only one colour is used for calibration.
+
+   * mjobs/MJCalibration.[h,cc]
+     - moved colour finder from the macros into this class with the 
+       function FindColor()
+     - had to add ~MJCalibration() {} because otherwise, I get a 
+       segmentation violation in the destructor, the debugger says in 
+       some TString. Maybe it's because of the GetDescriptor() in  
+       ~MParContainer() ?
+
+   * macros/calibration.C
+   * macros/calibrate_data.C
+   * macros/pedphotcalc.C
+   * macros/bootcampstandardanalysis.C
+     - removed function FindColor()
+
+   * mcalib/MCalibrationCam.h
+     - make Init() and InitSize() virtual
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - introduce two TArrayI's for the number of uncalibrated and 
+       unreliable pixels.
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - calculate and store the above numbers.
+
+   * mbadpixels/MBadPixelsPix.[h,cc]
+   * mbadpixels/MBadPixelsCam.cc
+     - removed bits: kHiGainNotCalibrated and kLoGainNotCalibrated
+     - added bits: kDeviatingFFactor, kConversionHiLoNotValid
+     - removed functions: IsCalibrationResultOK() 
+	and IsCalibrationSignalOK()
+     - changed function IsOK() such that it returns false only if 
+       the pixels is not suitable (run or evt)
+
+   * mcalib/MCalibrate.cc
+   * mcalib/MCalibrateRelTime.cc
+     - exchanged query for IsCalibrationResultOK() to 
+       IsUnsuitableRun(MBadPixelsPix::kUnsuitableRun). This includes 
+       now the oscillating pixels (which are sometimes many!!)
+
+   * mcalib/MHCalibrationRelTimePix.cc
+     - commented re-normalization to ns in Renorm()
+     - introduced Getter to fFADCSliceWidth
+
+   * mcalib/MHCalibrationRelTimeCam.cc
+     - renorm to ns in GetPixelsContent()
+     --> now, calibration in MCalibrateRelTimes is consistent
+
+
+
+ 2004/04/26: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - changed from 1 to 10 the "dummy" value of conversion high to low 
+       gain for old camera 0.6 files. Usually these files have no low 
+       gain at all, but there was a patched version of the program 
+       which did have low gain (with a gain 10 lower than hg).
+
+
+
+ 2004/04/25: Abelardo Moralejo
+
+   * mbadpixels/MBadPixelsTreat.cc
+     - Change in line 204:    if ((*fBadPixels)[i].IsBad()) by
+       if ((*fBadPixels)[j].IsBad())   The way it was done, it never
+       worked, because the check on whether the neighbour pixels
+       were OK was performed on the same pixel to be treated (i), which 
+       is obviously not OK. The same problem fixed in the interpolation 
+       of pedestals. Amazingly, this error would have shown up in any
+       test of the class.... I assume it must have been commited 
+       completely untested.
+
+     - In InterpolateSignal: moved division of summed charge over 
+       number of pixels : put it after the check of the number of 
+       valid neighbours to avoid division by 0.
+
+
+
+ 2004/04/23: Markus Gaug
+
+   * mcalib/MHCalibrationCam.cc
+     - fixed a bug in the ReInit() for the number of average events in 
+       each area index and sector
+
+
+ 2004/04/23: Thomas Bretz
+
+   * */Makefile:
+     - added some more mpedestal
+
+   * mreport/MReportRun.cc:
+     - changed to work with the latest version of report-files
+       --> This will make it incompatible with older report files
+           (for this use older Mars versions for merpping)
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added combo-box to surf through tabs in MARS-tab
+
+
+
+ 2004/04/22: Nadia Tonello
+
+   * mcalib/MCalibrateData.cc
+     - changed request for MBadPixelsPix::IsCalibrationResultOK() for 
+       MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableRun)
+
+
+
+ 2004/04/22: Thomas Bretz
+
+   * mhist/MHCamera.[h,cc]:
+     - implemented SetUsed
+
+   * merpp.cc:
+     - added "-ff" and interleave mode - both not execcively tested yet
+
+   * mhbase/MFillH.cc:
+     - added a missing 'endl'
+
+   * mraw/MRawCrateData.[h,cc], mraw/MRawEvtData.[h,cc],
+     mraw/MRawEvtHeader.[h,cc]
+     - added SkipEvt (the number of skipped bytes is untested)
+
+   * mraw/MRawEvtHeader.[h,cc]
+     - return kCONTINUE if time is invalid
+
+   * mraw/MRawFileRead.[h,cc]:
+     - implemented AddFile feature - first draft!
+     - added feature to skip events
+
+   * mraw/MRawFileWrite.h:
+     - changed default compression level corresponding to merpp to 2
+
+   * mraw/MRawRead.[h,cc]:
+     - added fForceMode flag to be able to suppress event errors
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - changes such that the pedestal interpolation is now done
+       only in ReInit. If you need the old behaviour call
+       SetProcessRMS()
+
+   Another step towards less mess:
+   
+   * MMcPedestalCopy.[h,cc], MMcPedestalNSBAdd.[h,cc],
+     MPedPhotCalc.[h,cc], MPedPhotCam.[h,cc], MPedPhotPix.[h,cc],
+     MPedCalcPedRun.[h,cc], MPedestalCam.[h,cc],
+     MPedestalPix.[h,cc]:
+     - moved from manalysis to mpedestal
+
+   * mpedestal/Makefile, mpedestal/PedestalLinkDef.h,
+     mpedestal/PedestalIncl.h:
+     - added
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h,
+     manalysis/AnalysisIncl.h:
+     - removed files above
+
+   * mbadpixels/Makefile:
+     - added mpedestals
+
+   * Makefile:
+     - added mpedestals
+
+
+ 2004/04/22: Antonio Stamerra
+
+   * mmain/MEventDisplay.cc
+     - Added new tab "Trigger" adding a new MHEvent (evt9), 
+	filled through the MMcTriggerLvl2 container.
+	A new MFillH task for evt9 and MMcTriggerLvl2Calc task 
+	have been added. 
+
+   * mhist/MHEvent.[h,cc]
+     - Added new event type kEvtTrigPix
+
+   * manalysis/MMcTriggerLvl2.[h,cc]
+     - The class now inherits from MCamEvent
+     - Added the methods GetPixelContent and DrawPixelContent (from MCamEvent)
+     - Added the method IsPixelInTrigger that returns kTRUE if a pixels 
+	is in the trigger region
+
+   * manalysis/MMcTriggerLvl2Calc.[h,cc]
+     - Added the methods CheckRunType and ReInit to check if the file is MC.
+
+   * mhistmc/Makefile
+     - Added the include for mgui
+
+
+ 2004/04/22: Markus Gaug
+
+   * mcalib/MCalibrate.[h,cc]
+     - introduced flat-fielding of charges for the muon calibration, 
+       accessible with SetCalibrationMode(kFlatCharge)
+
+   * manalysis/MPedCalcPedRun.cc
+     - added a SetReadyToSave() at the end of PostProcess
+   
+   * mjobs/Makefile
+     - added include of mraw
+
+   * mjobs/MJCalibration.cc
+     - added MRawFileRead for option SetDataCheck()
+
+   * mjobs/MJPedestal.cc
+     - added MRawFileRead for option SetDataCheck()
+
+
+ 2004/04/21: Thomas Bretz
+
+   * mbase/MTask.cc,  mbase/MTaskList.cc:
+     - let MTask in list fTaskProcess to be used as a counter
+
+   * mdata/MDataChain.[h,cc]:
+     - added some treatments for combinations of +/- signs
+
+   * mfbase/MFilterList.[h,cc]:
+     - added a new constructor to simplyfy filter-inversions
+
+   * mfileio/MReadReports.cc:
+     - added comment
+
+   * mhbase/MBinning.[h,cc]:
+     - added new constructor to simplify calls in macros
+
+   * mhbase/MFillH.[h,cc]:
+     - added fDrawOption to be used in MStatusDisplay
+
+   * mhist/MHFalseSource.cc:
+     - added comment
+
+
+
+ 2004/04/20: Thomas Bretz
+
+   * macros/derotatedc.C
+     - added tutorial macro plotting derotated dc currents
+
+   * mhist/MHCamEventRot.[h,cc]:
+     - added histogram to be filled with derotated MCamEvents
+
+
+
+ 2004/04/18: Abelardo Moralejo
+
+   * mgeom/MGeomCam.h
+     - Update class version to 4 (necessary after M. Gaug's change 
+       of the type of member fMaxRadius.
+
+
+
+ 2004/04/16: Abelardo Moralejo
+
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - Added fAverageQE. Same role as gkDefaultAverageQE, but can be 
+       changed via SetAverageQE. Made public GetAverageQE and 
+       GetAverageQERelVar (this changes needed for MC).
+
+   * mcalib/MMcCalibrationCalc.[h,cc]
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Adapted to M. Gaug's changes in calibration classes. Behaviour
+       has been tested to be the same as before those changes. Now the
+       conversion factor from ADC counts to photoelectrons, and the
+       average QE (photons->photoelectrons) are calculated independently 
+       (and later combined by MCalibrate to obtain the conversion 
+       ADC->photons).
+
+   * mmain/MEventDisplay.cc, macros/mccalibrate.C, starmc.C
+     - Added call to MExtractSignal::SetSaturationLimit(240)  Affects 
+       only MC display. This was necessary because if electronic noise
+       is simulated in the FADC, sometimes saturated slices look not
+       saturated due to negative fluctuations, so it is better to set 
+       the saturation limit at a safe value (240 ADC counts). Changed 
+       signal integration range (only for MC), now from slices 5 to 10.
+
+   * msignal/MExtractSignal3.[h,cc]
+     - Changed name of function SetRange for the more adecquate 
+       "SetWindows". No change in behaviour of the function.
+
+
+
+ 2004/04/16: Markus Gaug
+
+   * msignal/MExtractSignal.cc
+     - commited proposed larger default window from fgLast = 10 to 
+       fgLast = 14, because in March the pulses have moved to later 
+       arrival times.
+     - removed some inconsistency with slice numbering in FindSignal() 
+       from pixel.GetHiGainSamples()+fHiGainFirst-1 to 
+       pixel.GetHiGainSamples()+fHiGainFirst and also for the low gain
+
+   * msignal/MExtractSignal2.cc
+     - committed the proposed smaller window egdes from fgFirst=0 to 
+       fgFirst = 3, because in March some of the high-gain pulses reach 
+       into the "low-gain samples" and mislead thus sliding window to 
+       be maximized on the tail of the high-gain pulse.
+
+   * mcalib/MHPedestalPix.cc
+     - fixed a bug which made normalization to values per slice not happen
+
+   * macros/pedestalstudies.C
+     - fixed and documented
+
+
+
+ 2004/04/15: Markus Gaug
+
+   * macros/calibration.C
+     - added a function FindColor() to extract the colour by filename, 
+       works if there is indeed a colour or if the run nubmer is smaller 
+       than 20000 -> take ct1
+
+   * macros/bootcampstandardanalysis.C
+   * macros/pedphotcalc.C
+   * macros/calibrate_data.C
+     - updated the macro to the cvs-standard used at the Udine bootcamp
+
+   * mcalib/MCalibrateRelTimes.[h,cc]
+   * mcalib/Makefile
+   * mcalib/CalibLinkDef.h
+     - new class to calibrate the relative times
+
+   * manalysis/MGeomApply.cc
+     - added MArrivalTime::Init()
+
+   * msignal/MArrivalTime.[h,cc]
+     - added array fDataErr
+ 
+   * macros/rootlogon.C
+     - added directories mbadpixels and mjobs
+
+   * mcalib/MCalibrationQEPix.cc 
+     - set the fAvNorm variables to 1 in Clean()
+
+   * manalysis/MPedPhotCalc.[h,cc]
+     - included possibility to use an MBadPixelsCam
+
+
+
+ 2004/04/14: Thomas Bretz
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - fixed a bug which caused a missing last pixel (in most cases
+       Index 576)
+
+   * manalysis/MCerPhotPix.cc:
+     - fixed output in Print
+
+   * macros/mccalibrate.C, mmain/MEventDisplay.cc:
+     - added missing SetCalibrationMethod
+
+   * mbadpixels/MBadPixelsCam.[h,cc]:
+     - added copy constructor
+
+   * mbadpixels/MBadPixelsMerge.cc:
+     - added comments
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added new run-type (kRTPointRun=7)
+
+   * mmain/MEventDisplay.cc:
+     - fixed the broken cleaning levels
+
+
+
+ 2004/04/14: Markus Gaug
+  
+   * mcalib/MCalibrationQEPix.cc
+     - found a bug in the calculation of the error, fixed
+
+   * macros/mccalibrate.C, mmain/MEventDisplay.cc:
+     - replaced SetCalibrationMethod by SetCalibrationMode
+
+   * htmldoc/images/CalibClasses.gif
+   * htmldoc/images/RelTimeClasses.gif
+     - two schemes used in the class descriptions
+
+   * mcalib/MHCalibrationCam.[h,cc]
+     - included function GetAverageAreas() and GetAverageSectors() like 
+       in MCalibrationCam
+
+   * mjobs/MJCalibration.[h,cc]
+     - included calibration of rel.Times, to be chosen with a flag 
+       RelTimeCalibration()
+     - signal extractor and arrival time extractor can be chosen by 
+       flags as well (see Class description)
+
+
+   * mbadpixels/MBadPixelsCam.cc
+     - add two new types in GetPixelContent, add documentation of 
+       GetPixelContent
+
+   * msignal/MArrivalTimeCalc2.cc
+     - commented the warning for pixels with lowgain saturation
+
+
+
+ 2004/04/13: Markus Gaug
+
+   * macros/dohtml.C
+     - included directory mbadpixels
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - add functions GetHiLoMeansDivided(), GetHiLoSigmasDivided() and 
+       errors
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - removed hi-vs.Lo histograms (come into a separate MIntensityCam) 
+     - updated GetPixelContents
+     - updated class documentation
+
+   * mgeom/MGeomMirror.h
+     - include <TVector3.h>, otherwise it does not compile on my machine  
+
+   * mjobs/MJPedestals.cc
+   * mjobs/MJCalibration.cc
+     - replaced MBadPixelsMerge by MParList.AddToList(fBadPixels) until 
+       bug in MBadPixelsMerge is resolved (see bugtracker).
+
+   * mcalib/MHCalibrationChargePINDiode.cc
+     - return in Draw() if histogram is empty (otherwise segm. violation 
+       in eventloop
+
+   * msignal/MExtractedSignalCam.cc
+     - intialize variables by default to 0. 
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - pointer to fSig is not stored, somehow, when running MJCalibration
+       Don't know why. Removed and stored some variables instead
+
+   * mjobs/MJCalibration.[h,cc]
+     - updated documentation, updated QE Cam
+     - set the pulser colour (now obligatory)
+     - set the possibility to choose different displays
+ 
+   * mcalib/MCalibrationChargeCalc.cc
+     - set the pulser colour (now obligatory)
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - put GetRSigmaPerCharge into this class
+
+
+
+ 2004/04/13: Thomas Bretz
+
+   * mastro/MAstroCamera.cc, mastro/MAstroCatalog.[h,cc]:
+     - enhanced comments
+     - added some new features
+     
+   * mbase/MAGIC.h:
+     - removed some empty lines
+     
+   * mfileio/MWriteRootFile.cc:
+     - fixed a compiler warning
+     
+   * mgeom/MGeomCorsikaCT.h:
+     - removed obsolete include of TArrayF
+
+   * mgeom/MGeomMirror.[h,cc]:
+     - replaced fReflector by *fReflector
+
+   * mmain/MGDisplayAdc.cc:
+     - fixed a bug which caused the wrong histogram entry to be
+       displayed
+
+
+
+ 2004/04/10: Markus Gaug
+  
+   * macros/dohtml.C
+     - included directory mjobs
+
+   * mjobs/MJCalibration.[h,cc]
+     - added and updated documentation (not yet ready)
+
+   * htmldoc/images/CalibClasses.gif
+     - scheme of the calibration classes, used for documentation in 
+       MJCalibration.cc
+
+
+
+ 2004/04/10: Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc], mastro/MAstroCamera.[h,cc]:
+     - added comments
+
+   * macros/starfield.C:
+     - added
+
+   * mastro/Makefile, mastro/AstroLinkDef.h
+     - added MAstroCamera
+
+
+
+ 2004/04/09: Markus Gaug
+
+   * mcalib/MHCalibrationChargePINDiode.[h,cc]	
+   * mcalib/MHCalibrationChargeCam.[h,cc]	
+   * mcalib/MHCalibrationChargeCalc.[h,cc]	
+     - put abs. time consistency check from MCalibrationChargeCalc into 
+       MHCalibrationChargePINDiode and MHCalibrationChargeCam
+
+   * mcalib/MHCalibrationCam.[h,cc]	
+   * mcalib/MHCalibrationChargeCalc.[h,cc]	
+     - number of used FADC slices also stored in MHCalibrationCam, 
+       MHCalibrationChargeCalc needs no pointer to the signal extractors
+       any more -> removed
+
+   * mcalib/MCalibrationChargePINDiode.[h,cc]	
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]	
+   * mcalib/MCalibrationCam.[h,cc]	
+     - put a default pulser color kNONE
+
+   * manalysis/MPedestalCam.[h,cc]
+   * manalysis/MPedCalcPedRun.[h,cc]
+   * manalysis/MGeomApply.cc
+     - added average pixels in the way like it is done in MCalibrationCam
+
+
+
+ 2004/04/08: Thomas Bretz
+
+   * mfbase/MF.cc:
+     - optimized output
+
+   * mfbase/MFilterList.cc:
+     - added some comments
+
+   * mfileio/MReadMarsFile.[h,cc], mfileio/MReadTree.[h,cc]:
+     - added SortFiled-option -- RAQUEL, this is for you!
+
+   * mfileio/MWriteRootFile.cc:
+     - class AddSerialNumber in AddContainer
+
+   * mhist/MHFalseSource.[h,cc]:
+     - optimized setting of hist maximum
+     - added more source dependant cuts
+     - changed display layout
+     - scale number of entries to correct for different acceptance
+       (not perfect, but the best I can currently do)
+
+   * mimage/MHHillasExt.[h,cc]:
+     - added new histogram for fMaxDist
+
+   * mimage/MHNewImagePar.[h,cc]:
+     - added new histograms for Used/CoreArea
+
+   * mimage/MHillasCalc.cc:
+     - optimized output
+
+   * mimage/MHillasExt.cc:
+     - fMaxDist got a sign
+
+   * mimage/MNewImagePar.[h,cc]:
+     - enhanced comments
+     - added new Print() member function
+
+   * macros/readCT1.C, macros/readMagic.C, mmain/MEventDisplay.cc:
+     - forward geomcam to newimgepar.Print()
+
+
+
+ 2004/04/08: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+   * mcalib/MCalibrationChargeCam.[h,cc]
+   * mcalib/MCalibrationChargePix.[h,cc]
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+   * mcalib/MCalibrationChargePINDiode.[h,cc]
+     - put calculation of photon fluxes with the three methods into 
+       MCalibrationChargeCalc
+     - reorganized calculations in a better readable way (hopefully!)
+
+   * mbase/MAGIC.h
+   * mcalib/MCalibrationCam.[h,cc]
+   * mcalib/MCalibrationQECam.[h,cc]
+   * mcalib/MCalibrationQEPix.[h,cc]
+     - put PulserColor_t away from MAGIC.h into MCalibrationCam
+     - full implementation of the QE-calibration from MCalibrationQEPix
+
+   * msignal/MExtractBlindPixel.cc
+     - removed warning about low-gain saturation of Blind pixel
+
+   * mcalib/MCalibrate.[h,cc]
+   * mcalib/MCalibrateData.[h,cc]
+   * mcalib/MMcCalibrationCalc.[h,cc]
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - conversion factors now separated into FADC2phe and then into 
+       call to average Quantum efficiency. 
+
+
+ 2004/04/07: Markus Gaug
+
+   * mcalib/MHGausEvents.[h,cc]
+     - added fBlackout events
+
+
+
+ 2004/04/06: Thomas Bretz
+
+   * mcalib/MCalibrationCam.[h,cc]:
+     - simplified call to initialization by new function Init()
+
+   * mcalib/MH*.cc:
+     - fixed some warnings (comparision between signed and unsigned)
+
+   * manalysis/MGeomApply.cc:
+     - use new Init-funtion of MCalibrationCam
+
+   * mastro/MAstro.cc:
+     - some fixes to the conversion functions
+
+   * mastro/MAstroCamera.[h,cc]:
+     - added comments
+     - changed argument type of AddPrimitives
+     
+   * mastro/MAstroCatalog.[h,cc]:
+     - many changes to make it possible to overlay the
+       catalog on top of a 2D histogram
+     
+   * mbase/MEvtLoop.cc:
+     - fixed estimation of run-time
+
+   * mbase/MMath.[h,cc]:
+     - added member functions for signed significances
+
+   * mbase/MParContainer.cc:
+     - changed GetterMethod() to support double reference data mebers
+
+   * mbase/MStatusDisplay.cc:
+     - removed some obsolete debug outputs
+
+   * mbase/MTask.[h,cc]:
+     - removed fNumExecutions, fStopwatch already counts the calls
+     - slight chagnes to output of PrintStatistics
+
+   * mbase/MTaskList.[h,cc]:
+     - slight chagnes to output of PrintStatistics
+     
+   * mbase/MTime.cc:
+     - removed +TwoPi from GetGmst
+
+   * mcamera/MCameraAUX.h, mcamera/MCameraHV.h, mcamera/MCameraLV.h,
+     mcamera/MCameraLid.h, mcamera/MCameraLids.h,
+     mcamera/MCameraPowerSupply.h:
+     - added missing Getter functions
+
+   * mcamera/MCameraHV.h:
+     - removed obsolete data-meber fMean
+
+   * mdata/DataLinkDef.h:
+     - added MDataFormula
+
+   * mdata/MDataChain.cc, mdata/Makefile:
+     - enhanced dosumentation
+     - implemented use of multi argument functions
+     - added ^-operator
+
+   * mdata/MDataList.[h,cc]:
+     - added ^-operator
+     - enhanced IsValid
+
+   * mfbase/MFilterList.cc:
+     - changed a warn-output to inf
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added getter returning index corresponding to XY
+
+   * mgeom/MGeomPix.[h,cc]:
+     - added getter IsInside
+
+   * mhist/MHCamera.cc:
+     - Return 0 in GetMean if no entries
+
+   * mhist/MHFalseSource.[h,cc]:
+     - removed conversion stuff (mm/deg) 
+     - slight change to calculation of significance
+     - added dist-cuts
+     - added histogram showing number of entries
+     - added display of catalog
+
+   * mhist/MHStarMap.cc:
+     - added comment
+     
+   * mimage/MHillasExt.[h,cc]:
+     - changed class version to 3
+     - added new data-member fMaxDist
+     
+   * mimage/MNewImagePar.[h,cc]:
+     - added new data member fUsedArea and fCoreArea
+
+   * mmc/MMcConfigRunHeader.h:
+     - readded GetMirrors (WHY WAS IT GONE?)
+
+   * mpointing/MPointingPos.[h,cc]
+     - implemented Getter to get coordinates in rad
+     
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - fixed direction of rotation
+     - for the moment do use fTime
+
+
+
+ 2004/04/06: Markus Gaug
+ 
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - change names of the GetLoGain*() functions to 
+       GetConvertedLoGain*() for better clarity
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - updated and enlarged documentation
+
+   * mcalib/MHCalibrationChargeCam.cc
+   * mcalib/MHCalibrationRelTimeCam.cc
+     - set the arrays by use of memset
+     - initialize TObjArrays with the Init-Function
+
+
+ 2004/04/05: Markus Gaug
+
+   * msignal/MExtractedSignalPINDiode.h
+     - new function GetLastUsedSlice()
+
+   * mcalib/MCalibrationChargeCalc.[h,cc],
+   * mcalib/MCalibrationChargeCam.cc:
+     - holds also pointers to MExtractedSignalPINDiode and 
+       MExtractedSignalBlindPixel and does the checks inside the task 
+       (instead of inside the containers)
+
+   * mcalib/MCalibrationChargeBlindPix.[h,cc],
+   * mcalib/MCalibrationChargePINDiode.[h,cc]:
+     - updated and enlarged documentation
+
+   * mcalib/MHCalibrationChargePINDiode.cc
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - rename Setter for fMeanVar from SetMeanErr() to SetMeanVar()
+     - rename arrays of fAverageSigmaErr to AverageSigmaVar
+
+   * mcalib/MCalibrationPix.[h,cc]
+   * mcalib/MCalibrationChargePix.[h,cc]
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+   * mcalib/MCalibrationChargePINDiode.[h,cc]
+     - add Getters to the relative variance
+
+   * mcalib/MHGausEvents.[h,cc]
+   * mcalib/MCalibrationPix.[h,cc]
+   * mcalib/MHCalibrationCam.cc
+     - add to Pickup also Blackout events
+
+
+ 2004/04/05: Nadia Tonello
+
+   * mbadpixels/MBadPixelsTreat.cc
+     - In Unmap(): replaced SetPixelUnused with SetPixelUnmapped 
+
+
+
+ 2004/04/02: Markus Gaug
+
+   * mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationCam.[h,cc],
+     mcalib/MCalibrationQEPix.[h,cc], mcalib/MCalibrationQECam.[h,cc],
+     mcalib/MCalibrationRelTimeCam.[h,cc],
+     mcalib/MCalibrationRelTimePix.[h,cc]:
+     - updated and enlarged documentation
+
+   * mcalib/MHGausEvents.[h,cc], mcalib/MHPedestalPix.[h,cc],
+     mcalib/MHCalibrationChargePix.[h,cc],
+     mcalib/MHCalibrationChargeHiGainPix.[h,cc],
+     mcalib/MHCalibrationChargeLoGainPix.[h,cc],
+     mcalib/MHCalibrationChargeBlindPix.[h,cc],
+     mcalib/MHCalibrationChargePINDiode.[h,cc]:
+     - put fPixId, fPickup, fPickupLimt, CountPickup(), RepeatFit() and 
+       ChangeHistId() into MHGausEvents (before in the derived classes)
+     - put fChargeNbins, fChargeFirst, fChargeLast, 
+
+   * mcalib/MHCalibrationRelTimePix.[h,cc]:
+     - put fRelTimeNbins, fRelTimeFirst, fRelTimeLast together 
+       into MHGausEvents as fNbins, fFirst and fLast
+
+   * mcalib/MHCalibrationRelTimePix.[h,cc]:
+     - remove Renormalization to time slices. Need to think about 
+       more direct way to implement
+
+   * mcalib/MHPedestalCam.[h,cc], mcalib/MHCalibrationCam.[h,cc],
+     mcalib/MHCalibrationChargeCam.[h,cc],
+     mcalib/MHCalibrationRelTimeCam.[h,cc]:
+     - put most of the functionality into the base class MHCalibrationCam
+     - derived classes overload the functions SetupHists, ReInitHists, 
+       FillHists, FinalizeHists and FinalizeBadPixels. 
+     - functions FitHiGainArrays, FitLoGainArrays, FitHiGainHists, 
+       FitLoGainHists and InitHists can be used from base class. 
+
+   * mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationChargePix.[h,cc],
+     mcalib/MCalibrationRelTimePix.[h,cc]:
+     - put most of the functionality into the base class MCalibrationPix
+     - other two classes derive now from MCalibrationPix
+
+   * mcalib/MCalibrationCam.[h,cc], mcalib/MCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationRelTimeCam.[h,cc]:
+     - put most of the functionality into the base class MCalibrationCam
+     - other two classes derive now from MCalibrationCam
+     - calls to MCalibration*Cam[i] now have to cast!
+
+   * mcalib/MCalibrate.cc, mcalib/MCalibrateData.cc,
+   * mcalib/MMcCalibrateCalc.cc, manalysis/MMcCalibrationUpdate.cc,
+   * mcalib/MCalibrationChargeCalc.cc:
+     - cast calls to MCalibration*Cam[i]
+
+   * manalysis/MGeomApply.cc
+     - add initialization MCalibrationRelTimeCam
+     - add intialization of average pixels
+
+
+
+ 2004/04/02: Abelardo Moralejo
+
+   * msignal/MExtractSignal3.[h,cc]
+     - added. Alternative method for signal extraction. Uses sliding 
+       window from event to event, but a common window for all pixels 
+       in an event.
+
+   * msignal/Makefile, SignalLinkDef.h
+     - added MExtractSignal3.
+
+
+
+ 2004/04/02: Markus Gaug
+
+   * mbadpixels/MBadPixelsPix.h
+     - added kRelTimeNotFitted and kRelTimeOscillating to Calibration_t 
+       enum
+ 
+   * mcalib/MCalibrationCam.[h,cc], mcalib/MCalibrationPix.[h,cc],
+     mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - two new base classes for general calibration storage containers,
+       contain average pixel storage functionality
+
+   * mcalib/MCalibrationRelTimeCam.[h,cc],
+     mcalib/MCalibrationRelTimePix.[h,cc]:
+     - new storage container for the rel. time calibration results, derive
+       from MCalibrationPix, MCalibrationCam
+
+
+
+ 2004/04/01: Markus Gaug
+
+   * msignal/MArrivalTimeCalc.[h,cc]
+     - set fSaturationLimit as a variable with default (instead of 0xff)
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationChargeCalc.cc, manalysis/MGeomApply.cc:
+     - add average pixels per sector
+
+   * mcalib/MHGausEvents.[h,cc], mcalib/MHCalibrationChargePix.[h,cc],
+     mcalib/MHCalibrationRelTimePix.[h,cc]:
+     - moved BypassFit() function to MHGausEvents
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]:
+     - updated and enlarged documentation
+     - derives now from mcalib/MHCalibrationCam
+
+   * mcalib/MCalibrationChargePix.[h,cc]:
+     - removed flag kLoGainSaturation, because it is already in MBadPixelsPix
+
+   * mcalib/MCalibrationCam.[h,cc], mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - new base class for all MHCalibration*Cam object, contains the average
+       pixel functionality
+
+
+
+ 2004/03/31: Markus Gaug
+
+   * mcalib/MHCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCalc.cc, manalysis/MGeomApply.cc:
+     - make the average pixel independent on camera geometry, i.e.
+       one average pixel per MGeomPix::Aidx
+
+
+
+ 2004/03/31: Abelardo Moralejo
+
+   * mmc/MMcConfigRunHeader.[h,cc]
+     - updated to current version (3) in camera program. Added member
+       fLightCollectionFactorOuter so that we can store the data on 
+       the simulatedlight collection efficiency (light guides + 
+       plexiglas +...) as a function of incidence angle for outer and 
+       inner pixels independently. Added getters for this information
+       on light collection efficiency.
+
+
+
+ 2004/03/30: Markus Gaug
+ 
+   * mcalib/MHGausEvents.[h,cc],
+     mcalib/MHCalibrationChargePix.[h,cc],
+     mcalib/MHCalibrationChargeHiGainPix.[h,cc],
+     mcalib/MHCalibrationChargeLoGainPix.[h,cc],
+     mcalib/MHCalibrationChargeBlindPix.[h,cc],
+     mcalib/MHCalibrationChargePINDiode.[h,cc],
+     mcalib/MHCalibrationRelTimeCam.[h,cc],
+     mcalib/MHCalibrationRelTimePix.[h,cc],
+     mcalib/MHPedestalPix.[h,cc],
+     mcalib/MHPedestalCam.[h,cc]:
+     - updated and enlarged documentation
+
+
+
+ 2004/03/30: Abelardo Moralejo
+
+   * mmc/MMcFadcHeader.hxx
+     - updated to current version (4) in camera program.
+
+
+
+ 2004/03/29: Markus Gaug
+  
+   * manalysis/MSourcePosFromStarPos.cc
+     - replaced fabs(ival) by TMath::Abs(ival)
+
+   * mbadpixels/MBadPixelsPix.h
+     - adopt treatment of UnCalibrated_t like the one in Unsuitable_t 
+
+   * mbadpixels/MBadPixelsPix.cc
+     - put some documentation in the header
+
+   * mcalib/MHCalibrationChargeCam.cc
+     mcalib/MCalibrationChargeCam.cc
+     mbadpixels/MBadPixelsCam.cc
+     - adopt to new style in MBadPixelsPix.h
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     mcalib/MCalibrationChargePix.[h,cc]
+     - move consistency checks from Pix to Calc
+
+   * mcalib/MHGausEvents.[h,cc]
+     - fixed axes for event and fourier spectrum Draw
+
+   * mcalib/MHCalibrationChargePix.[h,cc] 
+     mcalib/MHCalibrationChargeCam.[h,cc] 
+     - moved definition of pulser frequency to MHCalibrationChargeCam
+
+
+
+ 2004/03/24: Thomas Bretz
+
+   * mbase/MMath.cc:
+     - now SignificanceLiMa returns 0 in case sum==0
+
+
+
+ 2004/03/23: Thomas Bretz
+
+   * mbase/MContinue.cc, mhbase/MH.cc:
+     - changed a warning message to an inf-message
+
+   * mfileio/MReadTree.cc:
+     - added an additional logging message when adding files to a
+       chain successfully.
+
+   * mbase/MProgressBar.cc:
+     - fixed initial size
+
+   * mastro/MAstro.[h,cc]:
+     - changed the code for the rotation angle back to its original
+       shape. The definition I tried to introduced was already
+       correctly implemented (assuming that sin is the x-component
+       of the vector I had it wrong in my mind twice, using
+       atan2(y,x) everywhere I did recognize it...)
+
+   * mreport/MReport.cc:
+     - fixed a bug which caused a crash when the time is not valid
+
+   * mhist/MHStarMap.cc, mpointing/MSrcPosCalc.cc:
+     - fixed: v.Roatete() must be v=v.Rotate()
+     - MHStarMap no waorks also without MSrcPosCam, MPointingPos
+       or MObservatory (leaving out the corresponding translations)
+
+
+
+ 2004/03/22: Markus Gaug
+
+   * mfileio/Makefile, mimage/Makefile
+     - mpointing included
+
+
+
+ 2004/03/22: Thomas Bretz
+ 
+   * mpointing/MSrcPosCalc.[h,cc], MSrcPosCam.[h,cc]: 
+     - added
+     
+   * mastro/MAstro.[h,cc]:
+     - added code to calculate rotationangle previously in MObservatory
+     - changed definition of rotation angle such, that it is now 
+       180deg if Ra and Az grid is parallel
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - fixes and enhancements to the display (such as misscalculated
+       number of grid lines, title display, etc)
+     - enhancements to the output
+     - generalized creation of grid - for further usage
+
+   * mastro/MAstroSky2Local.[h,cc]:
+     - replaced calculation of rotation angle by the function in
+       MAstro
+
+   * mastro/MObservatory.[h,cc]:
+     - small changes to Print output
+     - moved code for calculation of rotation angle to MAstro
+
+   * mbase/MEvtLoop.cc:
+     - do not output number of events per second if no events processed
+     
+   * mbase/MParList.cc:
+     - updated some comments
+     
+   * mfileio/MCT1ReadAscii.cc, mfileio/MCT1ReadPreProc.cc,
+     mfileio/MReadRflFile.cc, mraw/MRawFileRead.cc,
+     mreport/MReportFileRead.cc:
+     - output error string if file cannot be opened
+     
+   * mfileio/MReadTree.cc:
+     - output name of chain which is scanned
+
+   * mimage/MConcentration.cc:
+     - replaced loop by iterator
+     - removed obsolete (unused) variables
+     
+   * mimage/MHNewImagePar.[h,cc]:
+     - fixed display colors
+
+   * mpointing/MPointingPos.[h,cc]:
+     - added member function to calculate rotation angle
+     - added comments
+
+   * mpointing/Makefile:
+     - added include MAstro
+
+   * manalysis/MSrcPosCam.[h,cc]:
+     - moved to mpointing
+
+   * mpointing/MSrcPosCalc.[h,cc]:
+     - added: Derotates a star in the camera into MSrcPosCam
+
+   * mpointing/Makefile, mpointing/PointingLinkDef.h:
+     - added MSrcPosCam
+     - added MSrcPosCalc
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MSrcPosCam
+
+   * mmain/Makefile:
+     - added include for mpointing
+
+   * manalysis/AnalysisIncl.h:
+     - removed TVector2
+
+   * mbase/MParContainer.h:
+     - added new abstract virtual member function SetVariables
+       (to be used in fits)
+     - addeed some text to class description
+
+   * mdata/MData.cc:
+     - added comment
+     
+   * mdata/MDataArray.[h,cc], mdata/MDataElement.h,
+     mdata/MDataList.[h,cc], mdata/MDataMember.h,
+     mfbase/MFDataMember.[h,cc], mfbase/MFilterList.[h,cc]:
+     - added SetVariables
+
+   * mdata/MDataChain.[h,cc]:
+     - added support for indexed variables [i]
+     - added SetVariables
+
+   * mdata/MDataValue.[h,cc]: 
+     - added support for variable values (through SetVariables)
+     - added support for an index
+     - added SetVariables
+
+   * mfbase/MF.[h,cc]:
+     - removed support for {}. This case is now detected
+       automatically
+     - added SetVariables
+     - added support for expressiond like 
+       "MHillas.fLength<2*MHillas.fWidth"
+
+   * mfbase/MFDataChain.[h,cc]:
+     - added fCond data member
+     - addednew constructor to support fCond
+     - added support for new condition type
+     - adapted Print and GetRule
+
+   * mimage/MNewImagePar.[h,cc]:
+     - added some comments
+
+   * mhist/MHStarMap.[h,cc]: 
+     - fixed to use the correct MPointingPos instead of the
+       deprecated MMcEvt. Use MPointingPosCalc to copy the
+       pointing position from MMcEvt to MPointingPos
+
+   * mbase/MMath.[h,cc]:
+     - added, which currently only implements calculation of
+       significance and Li/Ma significance
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MMath
+
+
+
+ 2004/03/19: Markus Gaug
+
+   * mcalib/MHCalibrationChargePix.cc
+     - added some style to the default Draw in order to see the 
+       label and axis titles better
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - store and display more information on the average pxiels
+
+   * mcalib/MCalibrationCam.cc
+     - the GetPixelContent flag were not correct any more, fixed them 
+       
+   * macros/calibration.C
+     - fixed GetPixelContent flags
+     - draw radial profile of the variables
+
+   * mjobs/MJCalibration.cc
+     - fixed GetPixelContent flags
+     - introduced RadialProfile for some displays
+     - removed some not so important displays
+
+   * manalysis/MGeomApply.cc
+     - included MCalibrationQECam to be initialized
+
+   * mcalib/MCalibrationChargePix.[h,cc],
+     mcalib/MCalibrationQEPix.[h,cc]:
+     - replace DefinePixId by SetPixId
+   
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - added MCalibrationQECam
+     - cleaned the code up a little
+     - give more information at the end
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - took out fNumLoGainSampels whihc is not needed any more because 
+       conversion is only done in the getters
+     - Canceled function ApplyLoGainConversion (for same reason)
+
+   * msignal/MExtractSignal2.cc
+     - remove uncommented piece of code
+
+   * msignal/MExtractSignal.cc, msignal/MExtractSignal2.cc:
+     - remove warning about pixel with low gain saturation, 
+       now in MBadPixelsPix
+
+   * mbadpixels/MBadPixelsPix.[h,cc], mcalib/MCalibrationChargeCam.cc:
+     - added new flag: kDeviatingNumPhes
+
+   * mcalib/MCalibrationChargePix.cc
+     - check for mean arr. time in last bin replaced by check in last 
+       two bins
+
+   * mcalib/MCalibrationChargePix.[h,cc], 
+     mcalib/MCalibrationChargeCam.cc,
+     mcalib/MHCalibrationChargeCam.cc:
+     - removed flag kHiGainFitted, kLoGainFitted, since they are
+       available from MBadPixelsPix
+
+   * macros/calibration.C, macros/calibrate_data.C
+     - a few flags from MCalibrationChargeCam::GetPixelContent were wrong, 
+       corrected them
+
+
+
+ 2004/03/18: Raquel de los Reyes
+
+   * macros/DAQDataCheck.C
+     - macro to check the data from the DAQ system (.raw files).
+
+
+
+ 2004/03/18: Thomas Bretz
+ 
+   * manalysis/AnalysisIncl.h:
+     - added TVector2
+
+   * manalysis/MSrcPosCam.[h,cc]:
+     - added Getter/Setter using TVector2
+
+   * mhbase/MH.cc:
+     - fixed GetMinimumGT for TH2 and TH3
+
+   * mpointing/MPointingPos.h:
+     - added Getter/Setter for Ra/Dec
+
+   * mpointing/MPointingPosCalc.cc:
+     - fill Ra/Dec into MPointingPos
+
+
+
+ 2004/03/18: Markus Gaug
+
+   * mgeom/MGeomCam.[h,cc]
+     - replace fMaxRadius by a TArrayF of pixel area types
+     - new TArrayF fMinRadius of each pixel area type
+     - backward compatibility should be given, 
+       call to GetMaxRadius() returns the value for the whole camera
+       (which corresponds to the previous value for the Magic camera)
+
+   * mimage/MConcentration.cc
+     - fixed on flog to fLog in order to compile
+
+
+
+ 2004/03/17: Thomas Bretz
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - some simplifications and changes
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - some simplifications and changes
+
+   * mastro/MAstroSky2Local.[h,cc]:
+     - rotation matrix from sky to local coordinates
+     - added
+
+   * mastro/Makefile, mastro/AstroLinkDef.h:
+     - MAstroSky2Local added
+
+   * mraw/MRawEvtPixelIter.cc:
+     - GetIdxMaxLoGainSample(const Byte_t lofirst) const
+       accelerated and fixed (the first slice was compared to itself
+       and the last slice was not taken into account)
+
+   * manalysis/MCerPhotAnal2.cc:
+     - fixed a bug in the new treatment of lo-gains
+
+   * mhvstime/MHPixVsTime.cc:
+     - fixed missing initialization of fTypeErr in constructor
+
+   * mimage/MHillas.[h,cc]:
+     - implemented member function which returns MeanX/Y as TVector2
+
+   * mimage/ImageIncl.h:
+     - added TVector2
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - fixed a bug in AddPixels which - in some special circumstances -
+       cutted pixels with high pixel indices
+
+
+
+ 2004/03/17: Antonio Stamerra
+
+   * macros/datatrigcheck.C
+     - added macro for time and trigger data-checking
+
+
+
+ 2004/03/17: Abelardo Moralejo
+
+   * manalysis/MSourcePosfromStarPos.cc
+     - added cast fabs((Double_t)ival), line 703. Otherwise it does not
+       compile.
+
+   * macros/starmc.C
+     - added parameter accepted_fraction to select fraction of events 
+       to be processed (useful to make smaller outputs).
+
+
+
+ 2004/03/17: Wolfgang Wittek
+
+   * manalysis/MSigmabar.[h,cc]
+     - correct calculation of sector, which was wrong 
+
+
+
+ 2004/03/16: Markus Gaug
+ 
+   * mhist/MHCamera.[h,cc]
+     - added function RadialProfile which returns a TProfile of the 
+       value along the radius from the camera center
+
+
+
+ 2004/03/16: Oscar Blanch Bigas
+
+   * mimage/MConcentration.[h,cc]
+     - new class for Concentration stuff.
+     - It computes and stores Concentration 1-8
+
+   * mimage/MNewImagePar.[h,cc]
+     - New Concentration stuff is moved to MConcentration.
+
+   * mimage/MHillasCalc.[h,cc], Makefile, ImageLinkDef.h
+     - Modifications needed to support and compile new 
+       MConcentration class.
+
+
+
+ 2004/03/16: Thomas Bretz
+
+   * mjobs/MJ*.[h,cc]
+     - removed some obsolete comments
+     - removed projections from Directory (SetDirectory(0))
+
+
+
+ 2004/03/16: Wolfgang Wittek
+
+   * manalysis/MSigmabar.[h,cc]
+     - calculate sigmabar as mean of individual pedestalRMS
+       instead of            sqrt of mean pedestalRMS^2
+
+
+
+ 2004/03/16: Oscar Blanch
+
+   * mimage/MNewImagePar.[h,cc]
+     - New variables members added: fInnerSize, fInnerLeakage[1,2],
+       fConc[3-8].
+     - It is only ready for Magic Camera geometry. It has to be done
+       MGeomCam base.
+     - The version ahs not been updated since it was done on the 
+       2004/03/10 by Abelardo.
+
+
+
+ 2004/03/15: Markus Gaug 
+
+   * mcalib/MCalibrationChargePix.[h,cc],
+     mcalib/MCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCalc.cc:
+   - conversion from hi- to logain now not applied until the value is 
+     exported outside the class. This is necessary for the error 
+     propagation in the F-Factor method: In the calculation of the 
+     number of Phe, the conversion factors cancel out and do not 
+     enlarge the errors 
+   - pixels with number of phe's outside the range defined by 
+     fPheFFactorRelErrLimit are not any more declared as: 
+     MCalibrationChargePix::IsFFactorMethodValid() == kFALSE , 
+     but instead as:
+     MBadPixelsPix::IsSuitableRun(MBadPixelsPix::kUnreliableRun) == kTRUE,
+     Like this, everybody is allowed to calibrate pixels which give 
+     no reasonable results in the calibration without bothering that
+     too many pixels fall out. Enjoy!
+   - In that procedure, the classes passed _internally_ from calculation
+     of sigmas to calculation of variances which saves all the useless 
+     square rooting.
+   - took out pointers to MCalibrationChargeBlindPix and 
+     MCalibrationChargePINDiode in MCalibrationChargeCam.
+
+
+
+ 2004/03/15: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - added getter function for fZFirstInteraction
+
+
+
+ 2004/03/15: Wolfgang Wittek
+
+   * mastro/MObservatory.[h,cc]
+     - remove bugs in RotationAngle(theta, phi, sin, cos)
+       replaced
+         cos = sinl + cosl*cosp /denom;
+       by
+         cos = (sinl - cosl*cosp) /denom;
+
+
+
+ 2004/03/15: Thomas Bretz
+
+   * mastro/MObservatory.[h,cc]:
+     - implemented RotationAngle(ra, dec, time)
+
+   * mbase/MTask.[h,cc]:
+     - implemented usage of a TStopwatch to retriev time consumtion
+       informations
+     - changed PrintStatistics not to print classes having no
+       Process() function
+
+   * mbase/MTaskList.[h,cc], mfileio/MReadReports.[h,cc]:
+     - changed PrintStatistics according to changes in MTask
+
+   * mraw/MRawEvtHeader.cc:
+     - added a comment to Fill member function
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added fLut.Set to FixSize and resize fLut by a factor of 2
+       instead of +1 which acelerates creation of all pixels a lot
+
+   * mbadpixels/MBadPixelsPix.cc:
+     - fixed a typo
+
+   * mfilter/MFSoftwareTrigger.cc:
+     - made statistics output meaning independant of usage of filter!
+
+   * mhbase/MFill.[h,cc]:
+     - added possibility to give tab a different name
+
+   * mhist/MHCamera.cc:
+     - fixed a bug when determin scale for same-option
+
+   * mjobs/MJCalibration.cc:
+     - changed tab names for MFillH
+
+   * mjobs/MJExtactSignal.cc:
+     - added MRawEvtHeader to output
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - changed displayed year
+     - read and store MStatusArray to and from files
+
+   * mfileio/MReadTree.cc:
+     - enhanced output
+
+   * mmain/MCameraDisplay.cc, mmain/MEventDisplay.[h,cc]:
+     - added preliminary mode to display F1/F2/F3-files
+
+   * mbase/MStatusArray.[h,cc]:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MStatusArray
+
+   * mhits/MHCamera.[h,cc], mgui/MHexagon.[h,cc]:
+     - improved drawing MHCamera with 'same' option
+
+
+
+ 2004/03/13: Markus Gaug 
+
+   * mcalib/MCalibrationChargeCalc.cc, mcalib/MCalibrationChargeCam.cc,
+     mcalib/MCalibrationChargePix.[h,cc], 
+     mcalib/MHCalibrationChargeCam.cc,
+     mcalib/MHCalibrationChargeLoGainPix.cc:
+     - fixed Low Gain calibration
+
+   * mcalib/MHGausEvents.cc:
+     - changed default fit prob. limit from 0.005 to 0.001
+
+   * mbadpixels/MBadPixelsPix.h :
+     - IsCalibrationResultOK does not ask for FitOK any more
+
+   * mcalib/MHCalibrationChargeCam.cc:
+     - replaced Rel. Err. Limit for outliers in Phe's from 5 sigma to 7
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - function GetIdxMaxLoGainSamples can be called optionally with 
+       offset (because first "loGain" samples are often in reality 
+       hiGain with high values.
+
+
+
+ 2004/03/12: Sebastian Raducci
+
+   * manalysis/Makefile
+     - added mastro in the include directories
+
+
+
+ 2004/03/12: Thomas Bretz
+
+   * merpp.cc:
+     - added 'force' option
+
+   * manalysis/MCerPhotAnal2.cc:
+     - extract pedestal and pedestal rms from lo-gain if hi-gain not
+       above a certain athreshold 
+
+   * mastro/MAstroCatalog.[h,c]:
+     - added text argument to DrawStar
+
+   * mbase/MStatusDisplay.cc:
+     - some small changes to output of SaveAsPS
+
+   * mfilter/MFCosmics.cc:
+     - changed output of filter statistics
+
+   * mbadpixels/MBadPixelsTreat.[h,cc]:
+     - fixed some problems with the code - now it should work like
+       expected
+     - added a new member function to be able to change the number
+       of required neighbors
+
+
+
+ 2004/03/12: Wolfgang Wittek
+
+   * manalysis/Makefile
+     - include 'mastro'
+
+   * manalysis/MSourcePosfromStarPos.[h,cc]
+     - include MObservatory.h
+     - call member function Rotationangle() of MObservatory
+
+
+
+ 2004/03/12: Markus Gaug
+
+   * mjobs/MJCalibration.cc
+     - updated call in displays to the corr. Cams.
+
+   * macros/calibrate_data.C
+     - macro to study calibrate and study data used in Munich and IFAE
+
+
+
+ 2004/03/12: Antonio Stamerra
+
+   * mraw/MRawEvtHeader.[h,cc]
+     - Added the method GetTriggerID() to decode the trigger pattern.
+
+
+
+ 2004/03/11: Abelardo Moralejo
+
+   * mimage/MHillasCalc.cc
+     - Added some printout in PostProcess, to better express the reasons
+       for which the reconstruction of some events did not succeed.
+
+
+
+ 2004/03/11: Thomas Bretz
+
+   * status.cc:
+     - updated
+
+   * manalysis/MCerPhotAnal2.cc:
+     - removed an obsolete debug output
+
+   * mhist/MHCamera.[h,cc]:
+     - added same-option to camera display
+
+  * mbadpixels/MBadPixelsCalc.[h,cc], mbadpixels/MBadPixelsTreat.[h,cc]:
+     - implemented functionality of MBlindPixelsCalc2
+
+   * mbadpixels/MBadPixelsCam.[h,cc], mbadpixels/MBadPixelsPix.[h,cc],
+     mbadpixels/MMcBadPixelsSet.cc, mcalib/MCalibrationChargeCalc.cc,
+     mcalib/MCalibrationChargePix.cc, mcalib/MHCalibrationChargeCam.cc:
+     - replaced several Set/GetUnsuitable* by a single member function
+
+
+
+ 2004/03/11: Markus Gaug
+
+   * mbadpixels/MBadPixelsPix.h
+     - removed bits about validity of calibration methods
+     - IsCalibrationResultOK asks also from IsSuitableRun
+
+   * mbadpixels/MBadPixelsCam.cc
+     - updated GetPixelContent
+     - added Print function
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationChargePix.h, mcalib/MCalibrationChargeCalc.cc:
+     - removed pointers to MGeomCam and MBadPixelsCam in MCalibrationChargeCam
+     - use two loops over pixels in order to determine mean flux of phe;s to 
+       discard pixels far outside the normal distribution
+
+   * mcalib/MCalibrate.cc
+     - added case that no MBadPixelsCam is available.
+
+   * mcalib/MHCalibrationChargeCam.cc
+     - adapted to new MBadPixelsPix::SetUnsuitable function
+
+
+ 2004/03/10: Abelardo Moralejo
+
+   * manalysis/MCerPhotPix.[h,cc]
+     - Added member fIsHGSaturated, and setter/getter functions. 
+       Updated class version to 4.
+
+   * mcalib/MCalibrate.cc, MCalibrateData.cc
+     - Added setting of MCerPhotPix.fIsHGSaturated if one or more HG
+       slices saturate.
+
+   * mimage/MNewImagePar.[h,cc]
+     - Added member fNumHGSaturatedPixels to count the number of pixels 
+       in which high gain saturates. Added getter funciton for it. 
+       Updated class version to 3.
+
+
+
+ 2004/03/10: Markus Gaug
+
+   * mcalib/MCalibrationChargeCalc.cc,
+     mcalib/MCalibrationChargePix.[h,cc],
+     mcalib/MCalibrationChargeCam.[h,cc]:
+     - calculation of conversion factor with F-Factor method from 
+       same mean number of photons, derived from weighted mean number 
+       of photo-electrons from inner and outer pixels, respectively
+
+   * mjobs/MJPedestal.cc, mjobs/MJCalibration.cc, macros/calibration.C:
+     - fixed the projections (did only display inner pixels up to now)
+
+   * macros/calibration.C
+     - small bug fixed in display of rel. arrival times
+       ( used MArrivalTimeCam instead of MHCalibrationRelTimeCam)
+
+   * mbadpixels/MBadPixelsCam.cc
+     - replaced some InitSize(idx) by InitSize(idx+1) in order not to crash
+       to program when reading from an ascii-file.
+
+   * mbadpixels/MBadPixelsCalc.cc
+     - replaced one SetUnsuitableRun(....) by the new version without 
+       argument.
+
+
+
+ 2004/03/10: Thomas Bretz
+
+   * mfilter/MFSoftwareTrigger.[h,cc]:
+     - changed to support also a predifined number of NN
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - many enhancements
+     - many speed improvements
+
+   * mbadpixels/MBadPixelsPix.[h,cc]:
+     - fixed
+
+
+
+ 2004/03/10: Ester Aliu
+
+   * mtemp/MIslands.[h,cc]
+     - New MParContainer to hold information about islands
+       (number of islands, pixels in each Island, Signal/Noise of
+	each Island).
+
+   * mtemp/MIslandCalc.[h,cc]
+     - New MTask to count and characterize Islands.
+
+
+
+ 2004/03/09: Thomas Bretz
+
+   * Makefile.rules:
+     - replaced *.o by $(...) for building archives
+
+   * mjobs/MJCalibration.cc:
+     - exchanged  apply  and merge task
+
+   * mjobs/MJCalibration.h, mjobs/MJExtractSignal.h, mjobs/MJPedestal.h:
+     - fixed some const-qualifiers
+
+   * mcalib/MHCalibrationChargeBlindPix.cc, 
+     mcalib/MHCalibrationChargeCam.cc,
+     mcalib/MHCalibrationChargePINDiode.cc
+     - removed some obsolete output when calling FindCreateObj
+     - changed some 'not found' output messages to be 'Mars-compliant'
+     - replaced some gLog by *fLog
+
+
+
+ 2004/03/08: Markus Gaug
+   
+   * mbadpixels/MBadPixelsPix.h
+     - small modifications for better readability
+     - remove Getters for calibration methods
+     - added flag "UnReliableRun" in fInfo[0]
+
+   * mcalib/MHCalibrationChargeCam.cc, mcalib/MCalibrationChargePix.cc:
+     - fill MBadPixelsPix with UnReliableRun or UnSuitableRun when 
+       calibration does not succeed.
+
+   * mcalib/MCalibrationChargeCam.cc
+     - displaying saturation also for not-valid pixels in GetPixelContent
+
+   * msignal/MExtractedSignalCam.[h,cc], msignal/MExtractSignal.[h,cc],
+     msignal/MExtractSignal2.[h,cc], mananlysis/MHPedestalCam.cc,
+     mcalib/MCalibrationChargeCalc.[h,cc]:
+     - in SetUsedFADCSlices, also the window (hi-and logain) is set. 
+       This because MExtractSignal2 set the whole window which was much 
+       bigger than the actually used one. This bug is now removed.
+
+
+
+ 2004/03/08: Thomas Bretz
+
+   * merpp.cc:
+     - fixed a bug in the screen output
+
+   * mgeom/MGeomMirror.cc:
+     - added comment
+
+   * mmc/MMcConfigRunHeader.h:
+     - added member function GetMirrors
+
+
+
+ 2004/03/08: Abelardo Moralejo
+
+   * macros/starmc.C, starmcstereo.C, mccalibrate.C 
+      - adapted to m. Gaug's changes: now one MBadPixelsCam containers is 
+        added for each telescope to the parameter list.
+
+   * mmain/MEventDisplay.cc, Makefile
+     - added MBadPixelsCam to par list, and mbadpixels/ to includes.
+       Necessary due to changes in MCalibrate.
+
+
+
+ 2004/03/06: Markus Gaug
+
+   * macros/calibration.C
+     - adapted call to MHCamera::ProjectionS to the new version
+
+   * mcalib/Makefile
+     - include directory mbadpixels
+
+   * manalysis/Makefile
+     - include directory mbadpixels
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     - include MBadPixelsCam
+     - remove exclusion of pixels from ascii-file
+       (now accessible from MBadPixelsCam)
+
+   * mcalib/MCalibrationChargePix.[h,cc]
+     - include MBadPixelsCam
+
+   * mcalib/MCalibrationChargeCam.[h,cc]
+     - include MBadPixelsCam
+
+   * mcalib/MHCalibrationChargeCam.[h,cc]
+     - include MBadPixelsCam
+     - include one additional MBadPixelsPix for the average inner and 
+       outer pixel, respectively
+
+   * mcalib/MHCalibrationChargePix.[h,cc]
+     - make fSaturated and fPickup a Float_t (for average pixel)
+
+   * mbadpixels/MBadPixelsPix.h
+     - include the CalibrationType_t infos
+     - exchange "SetUnsuitable" by "SetUnsuitableRun"
+
+   * mbadpixels/MBadPixelsCam.cc, mbadpixels/MMcBadPixelsSet.cc:
+     - exchange "SetUnsuitable" by "SetUnsuitableRun"
+
+   * mbadpixels/MBadPixelsCalc.cc:
+     - exchange "SetUnsuitable" by "SetUnsuitableEvt"
+
+   * manalysis/MGeomApply.cc
+     - remove obsolete MArrivalTime
+     - add MBadPixelsCam
+
+   * mcalib/MCalibrate.[h,cc], mcalib/MCalibrateData.[h,cc]
+     - implemented calls to MBadPixelsCam
+
+   * macros/calibration.C, macros/bootcampstandardanalysis.C,
+     macros/pedphotcalc.C
+     - implemented calls to MBadPixelsCam
+
+   * mjobs/MJCalibration.cc
+     - call to MBadPixelsCam
+
+
+
+ 2004/03/05: Nadia Tonello
+
+   * manalysis/MBlindPixelsCalc2.[h,cc], manalysis/AnalysisLinkDef.h,
+     manalysis/Makefile
+     - Temporary class added (will be included in mbadpixels/ soon)
+     - All the functions of MBlindPixelCalc are kept(with small improvements)
+     - New function added: SetCheckPedestalRms
+
+   * manalysis/MCerPhotPix.h
+     - Status Unmapped added (not include the pixel in the cleaned image)
+
+   * mimage/MImgCleanStd.cc 
+     - Checks for Unmapped status added 
+
+   * mastro/MAstroCatalog.cc, msql/MSQLServer.cc:
+     - include <stdlib.h> to solve compilation error
+
+
+
+ 2004/03/05: Sebastian Raducci
+
+   * msignal/MArrivalTimeCalc.cc
+     - fixed a little bug (exchanged a - with a + in the Calc() method)
+
+
+
+ 2004/03/05: Markus Gaug
+
+   * mcalib/MCalibraitonChargeCalc.cc
+     - remove some runheader line: 
+	if (runheader->IsMonteCarloRun())
+            return kTRUE;
+       which gave always true since this week, don't know why.
+     - added some information in class description
+
+
+
+ 2004/03/04: Sebastian Raducci
+  
+   * msignal/MArrivalTimeCalc.cc
+     - fixed a memory leak (the spline was not deleted...)
+
+
+
+ 2004/03/04: Thomas Bretz
+
+   * mgeom/MGeomCam.[h,cc]:
+     - added new data member fNumAreas
+     - added new function CalcNumAreas
+     - increased class version to 3
+
+   * mgeom/MGeomCamMagic.cc:
+     - added setting of area index
+
+   * mgeom/MGeomPix.[h,cc]:
+     - added fAidx data member
+     - added getter function fAidx
+     - increased class version to 3
+
+   * macros/sectorvstime.C:
+     - added example of how to plot the evolution of a sector vs time
+
+   * mhist/MHVsTime.[h,cc], mhist/MHPixVsTime.[h,cc]:
+     - moved to mhvstime
+
+   * mhvstime/MHSectorVsTime.[h,cc]:
+     - added
+
+   * Makefile:
+     - added mhvstime
+
+   * mhvstime/Makefile, mhvstime/HVsTimeLinkDef.h, 
+     mhvstime/HVsTimeIncl.h:
+     - added
+
+   * mhist/Makefile, mhist/HistLinkDef.h, 
+     - removed MHVsTime
+     - removed MHPixVsTime
+
+   * macros/rootlogon.C, macros/dohtml.C:
+     - added new directory mhvstime
+
+   * msignal/MExtractSignal.cc, msignal/MExtractSignal2.cc:
+     - changes such, that it doesn't crash if signal has no lo-gain
+       (This might still give wrong results!)
+
+   * macros/dohtml.C:
+     - added pixvstime.C
+     - added sectorvstime.C
+
+   * manalysis/MMcCalibrationUpdate.cc:
+     - some changes on file consistency check done by Abelardo,
+       he may comment on it
+
+   * mhist/MHCamera.[h,cc]:
+     - changed to support also dividing the camera in pixels area indices
+
+   * mhist/MHEvent.cc:
+     - minor change
+
+   * mjobs/MJPedestal.cc:
+     - adapted to changes in MHCamera
+
+   * mastro/MAstroCatalog.[h,cc]:
+     - added preliminary catalog
+
+   * mastro/Makefile, mastro/AstroLinkDef.h:
+     - added MAstroCatalog
+
+
+
+ 2004/03/03: Thomas Bretz
+
+   * mgeom/MGeomCam.cc:
+     - give a name and title also if the default constructor is used
+
+   * mgeom/MGeomMirror.[h,cc]:
+     - added member function GetReflection
+     - added persistent data member fReflector
+
+   * mjobs/MJCalibration.cc, mjobs/MJExtractSignal.cc, mjobs/MJPedestal.cc:
+     - fixed a typo in the output
+
+   * mraw/MRawFileWrite.cc:
+     - added the missing '.' to MRawRunHeader. Because of the design of
+       MReadTree this is backward compatible
+
+   * mraw/MRawRunHeader.h:
+     - removed last change from Abelardo. '>255' is the correct 
+       check for MC files following the definition that all MC files
+       have run types >255 which was made in the past. 
+
+   * manalysis/MCerPhotAnal.[h,cc], manalysis/MCerPhotAnal2.[h,cc]:
+     - created ReInit member function to hold all code (moved from
+       PreProcess) accessing the run header. The run header is not
+       available in PreProcess. That it was working before was only
+       by chance, because the run type is initialized with 65535 which
+       is != 255 but not >255.
+
+
+
+ 2004/03/03: Sebastian Raducci
+
+   * msignal/MArrivalTimeCalc.cc
+     - The calculation of the arrival times is made only when needed
+       (when the HalfMax is over the pedestal)
+
+   * mtools/MCubicSpline.cc
+     - Commented out an annoying warn
+
+
+
+ 2004/03/03: Abelardo Moralejo
+
+   * mraw/MRawRunHeader.h
+     - Replaced
+         Bool_t IsMonteCarloRun() const { return fRunType>0x00ff; }  by
+         Bool_t IsMonteCarloRun() const { return (fRunType==0x0100); }
+     since the latter is the exact translation of what the function
+     intends to do. I do not know why, but the display of real data 
+     did not work with the upper line!
+
+   * mgeom/MGeomCam.cc
+     - Undid yesterday change! I do not know why, display completely 
+       fails after that change, both for old and new camera files. 
+       Put back fPixels[i] = new MGeomPix; in constructor.
+
+
+
+ 2004/03/02: Abelardo Moralejo
+
+   * mmc/MMcCorsikaRunHeader.[h,cc]
+     - Added operator [] to get references to the objects in 
+       TObjArray fTelescopes.
+     - Added Print() function.
+     - Added GetNumCT() function.
+     - Replaced
+          fTelescopes[i]= new MGeomCorsikaCT;   
+       by
+          MGeomCorsikaCT* dummy = new  MGeomCorsikaCT();
+          fTelescopes.Add(dummy);
+
+   * mgeom/MGeomCorsikaCT.[h,cc]
+     - Added getter functions for telescope coordinates.
+     - Added Print() function.
+
+   * mgeom/MGeomCam.cc  => NOTE: this change was undone later!
+     - Replaced
+          fPixels[i] = new MGeomPix;   
+       by
+          MGeomPix* dummy = new MGeomPix();
+          fPixels.Add(dummy);
+
+
+
+ 2004/03/02: Thomas Bretz
+
+   * mcalib/MCalibrateData.cc:
+     - removed usage of MGeomCam (you have MGeomApply for this!)
+
+
+
+ 2004/03/01: Nadia Tonello
+
+   * manalysis/MCerPhotEvt.cc
+     - TObject *MCerPhotEvtIter::Next() now returns Used pixels 
+	only if fUsedonly=kTRUE, otherwise it returns all the pixels 
+	in the array  
+ 
+
+
+ 2004/03/01: Sebastian Raducci
+
+   * msignal/MArrivalTimeCalc.[cc,h]
+     - now the arrival time is at the half max of the spline:
+       half max = (maximum - pedestal)/2
+   
+   * mmain/MEventDisplay.cc
+     - fixed an include (from MArrivalTime.h to MArrivalTimeCam.h)
+
+
+
+ 2004/03/01: Wolfgang Wittek
+  
+   * mhist/MHStarMap.[h,cc]
+     - remove bugs
+     - change GetRotationAngle() such that it can be called from outside
+
+
+
+ 2004/03/01: Thomas Bretz
+
+   * Makefile:
+     - enhanced all calls to subsequent makes by '-f Makefile' to
+       make sure the correct Makefile is called
+
+   * merpp.cc:
+     - enhanced interpretation of time
+     - fixed a bug in determin the file-type
+
+   * mbase/MTime.[h,cc]:
+     - added GetGmst() member function
+
+   * mastro/MAstro.[h,cc]:
+     - added Coordinate2Angle
+     - added AngularDistance
+     - implemented UT2GMST
+     - replaced defined by TMath::Pi()
+
+   * mastro/MObservatory.[h,cc]:
+     - added data members for sin-/cos-component of latitude
+     - added calculation of rotation angle
+
+   * mhist/MHStarMap.[h,cc]:
+     - changes to use MObservatory member function
+
+   * manalysis/MCerPhotAnal.cc, manalysis/MCerPhotAnal2.cc,
+     manalysis/MCerPhotCalc.cc, manalysis/MMcCalibrationUpdate.cc,
+     manalysis/MMcPedestalCopy.cc, manalysis/MMcPedestalNSBAdd.cc,
+     manalysis/MPedCalcPedRun.cc, manalysis/MPedPhotCalc.cc,
+     mcalib/MCalibrationChargeCalc.cc, mcalib/MMcCalibrationCalc.cc
+     - changed to use IsMonteCarloRun() now
+
+   * manalysis/MMcCalibrationUpdate.cc:
+     - unified output to log-stream
+     - replaced sqrt by TMath::Sqrt
+
+   * mcalib/MCalibrationChargeCalc.cc:
+     - unified output to log-stream
+     - removed .Data() from TString where obsolete
+     - fixed memory leak using gSystem->ExpandPathName
+
+   * mpointing/MPointingPosCalc.cc, mraw/MRawFileWrite.cc:
+     - adde class name to used kRT*/kTT* enums
+
+   * mraw/MRawEvtHeader.h:
+     - made enum data member of class
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - made kMagicNumber and kMaxFormatVersion a static data
+       member of the class
+     - added IsMonteCarloRun member function
+
+
+
+ 2004/02/27: Markus Gaug
+   
+   * mjobs/MJPedestal.cc, mjobs/MJCalibration.cc, macros/calibration.C:
+     - put in call to MHCamera::Projection the name of the calling 
+       class, otherwise the projected hsitogram will be overwritten by 
+       an empyt one.
+
+   * mcalib/MHCalibrationChargePix.[h,cc],
+     mcalib/MHCalibrationHiGainChargePix.[h,cc],
+     mcalib/MHCalibrationLoGainChargePix.[h,cc]:
+     - histogram name setting and title setting moved to constructor, 
+       Functions Init and ChangeHistId derive directly from 
+       MHcalibrationChargePix
+
+   * mcalib/MHCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCam.[h,cc],
+     mcalib/MCalibrationChargeCalc.[h,cc]:
+     - introduced "average inner" and "average outer" higain and logain 
+       pixels.
+
+
+
+ 2004/02/27: Raducci Sebastian 
+
+   * mhist/Makefile
+     - added mastro in the include list
+
+
+
+ 2004/02/27: Abelardo Moralejo
+
+   * mmain/MEventDisplay.cc
+     - replaced in fill8 obsolete MArrivalTime with MArrivalTimeCam.
+     - Updated display of MC data: removed MCerPhotCalc, and replaced 
+       it by MExtractSignal+MMcCalibrationUpdate+MCalibrate. Now
+       MPedPhotCam is filled and all the camera display tabs are shown 
+       correctly (most were not working for MC events since a while 
+       ago).
+
+   * mmain/Makefile
+     - Added mcalib to list of include directories.
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Added member variable Bool_t fOuterPixelsScaling, which is 
+       kTRUE by default. If set to kFALSE, MCalibrationCam is filled 
+       such that MCerPhotEvt will later be filled with the signal as it 
+       is, not corrected for the (possibly) different gain of the outer 
+       pixels electronic chain. This option was necessary to allow for
+       the change in the camera display (see above).
+
+   * macros/starmc.C
+     - added (optional) division of output into two, for use as train 
+       and test samples in g/h separation studies.
+
+
+
+ 2004/02/26: Hendrik Bartko
+
+   * macros/dohtml.C
+     - included the path msignals/
+
+
+
+ 2004/02/26: Abelardo Moralejo
+
+   * macros/starmcstereo.C
+     - changed filters to divide data between train and test sample for
+       gamma hadron separation studies. Now we use the modulus operator
+       applied to (Corsika) event number:
+         MF filter1("{MMcEvt;1.fEvtNumber%2}<0.5");
+         MF filter2("{MMcEvt;1.fEvtNumber%2}>0.5");
+     - cleaned up a bit the way the CT coordinates are fed to the task
+       MStereoCalc.
+     - Changed default FADC integration range (center range to adapt to 
+       new camera).
+
+
+
+ 2004/02/26: Thomas Bretz
+
+   * mhist/MHCamera.cc:
+     - fixed a function description
+
+   * mreport/MReport.cc, mreport/MReportFileRead.cc:
+     - introduced return case -1
+
+   * Makefile.rules:
+     - remove all dependancy files when calling 'rmdep'
+
+   * mbase/MAGIC.h, mmc/MMcEvt.hxx:
+     - moved ParticleId_t to MMcEvt
+     - implemented MMcEvt::GetParticleName
+     - implemented MMcEvt::GetEnergyStr
+
+   * mfilter/MFGeomag.cc, mfilter/MFParticleId.cc, mhist/MHCompProb.cc,
+     mhist/MHEvent.cc, mhist/MHHadronness.cc, 
+     mmontecarlo/MMcTriggerRateCalc.cc, mranforest/MHRanForest.cc:
+     - fixed usage of ParticleId_t
+
+   * msignal/Makefile:
+     - removed obsolete includes
+
+   * mastro/Makefile, mastro/AstroLinkDef.h, mastro/MAstro.[h,cc],
+     mastro/MObservatory.[h,cc]:
+     - added
+
+   * mbase/MAstro.[h,cc]:
+     - removed
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - removed MAstro
+
+   * Makefile:
+     - added mastro
+     - added msql
+     - added mfbase
+
+   * mtemp/MObservatory.[h,cc], mtemp/MObservatoryLocation.[h,cc]:
+     - removed
+
+   * merpp.cc:
+     - added Sql support
+     
+   * mraw/MRawFileRead.h:
+     - added GetFileName
+
+   * msql/Makefile, msql/SqlLinkDef.h, msql/SqlIncl.h, 
+     MSQLServer.[h,cc], MSqlInsertRun.[h,cc]:
+     - added
+
+   * mfilter/MF.[h,cc], mfilter/MFDataChain.[h,cc], 
+     mfilter/MFDataMember.[h,cc], mfilter/MFEventSelector.[h,cc],
+     mfilter/MFEventSelector2.[h,cc], mfilter/MFRealTimePeriod.[h,cc]:
+       - moved to mfbase
+
+   * mfbase/Makefile, mfbase/FBaseLinkDef.h, mfbase/FBaseIncl.h:
+     - added
+
+   * merpp.cc:
+     - implemented control of gDebug (root debugging)
+
+   * mfileio/MWriteAsciiFile.[h,cc], mfileio/MWriteFile.[h,cc],
+     mfileio/MWriteRootFile.[h,cc]:
+     - implemented CheckAndWrite return value
+
+   * mfileio/MWriteRootFile.cc:
+     - fixed updating already existing branches (eg concatenating report
+       files)
+
+   * macros/dohtml.C, macros/rootlogon.C:
+     - added mastro
+     - added mfbase
+     - added msql
+
+   * mraw/MRawEvtHeader.h:
+     - implemented GetNumTrigLvl1
+     - implemented GetNumTrigLvl2
+
+
+
+ 2004/02/25: Markus Gaug
+
+   * mcalib/MExtractBlindPixel.[h,cc],
+     mcalib/MExtractPINDiode.[h,cc],
+     mcalib/MExtractedSignalBlindPixel.[h,cc],
+     mcalib/MExtractedSignalPINDiode.[h,cc],
+     mcalib/Makefile, msignal/Makefile, mcalib/CalibLinkDef.h,
+     msignal/SignalLinkDef.h:
+     - moved blindpixel and PINdiode extractors to msignal
+
+
+   * mcalib/MCalibrationQECam.[h,cc], mcalib/MCalibrationQEPix.[h,cc]:
+     - two new classes to hold the quantum efficieny information of the 
+       calibration
+
+   * msignal/MArrivalTimeCalc.[h,cc]
+     - fill now MArrivalTimePix instead of MArrivalTime
+
+   * mcalib/MHCalibrationChargeCam.cc
+     - display only valid pixels for the corr. values in GetPixelContent
+
+   * mcalib/MHCalibrationRelTimeCam.cc
+     - is now filled from MArrivalTimeCam instead of MArrivalTime
+
+   * macros/calibration.C
+     - divided into two macros: calibration.C using the MJPedestal
+       standard procedure and   pedestalstudies.C using the old
+       procedures
+    
+   * macros/pedestalstudies.C
+     - new macro containing the first previous part of calibration.C
+
+   * mcalib/MCalibrationChargeBlindPix.h,
+     mcalib/MCalibrationChargePINDiode.h, mbase/MAGIC.h,
+     mjobs/MJCalibration.cc:
+     - definition of PulserColot_t in MAGIC.h. 
+
+
+
+ 2004/02/25: Hendrik Bartko
+  
+   * macros/rootlogon.C
+     - set the include path also to msignals/
+
+   * manalysis/MExtractSignal.[h,cc], manalysis/MExtractSignal2.[h,cc],
+     manalysis/MExtractedSignalCam.[h,cc],
+     manalysis/MExtractedSignalPix.[h,cc],
+     manalysis/MArrivalTime.[h,cc], manalysis/MArrivalTimeCalc.[h,cc],
+     manalysis/MArrivalTimeCalc2.[h,cc]:
+     - removed
+     
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:			
+     - removed classes mentioned above
+
+   * msignal/MExtractSignal.[h,cc], msignal/MExtractSignal2.[h,cc],
+     msignal/MExtractedSignalCam.[h,cc],
+     msignal/MExtractedSignalPix.[h,cc],
+     msignal/MArrivalTime.[h,cc], msignal/MArrivalTimeCalc.[h,cc],
+     msignal/MArrivalTimeCalc2.[h,cc]:
+     - added
+
+   * msignal/Makefile, msignal/AnalysisLinkDef.h:			
+     - added classes mentioned above
+     
+   * mfilter/Makefile, mcalib/Makefile, mjobs/Makefile, mmain/Makefile:
+     - added include msignal
+    
+
+
+
+ 2004/02/25: Wolfgang Wittek
+  
+   * mcalib/MCalibrateData.[h,cc]
+     - initialize size for MPedPhotCam
+
+
+
+ 2004/02/24: Wolfgang Wittek
+
+   * manalysis/MSourcPosfromStarPos.[h,cc]
+     - change member function SetSourceAndStarPosition() to expect sky
+       coordinates in the standard units
+     - generalize to more than 1 star
+     - the class is not yet fully tested
+
+   * mfilter/MFSelBasic.[h,cc]
+     - change default values of cuts
+
+
+
+ 2004/02/24: Markus Gaug
+
+   * mjobs/MJCalibration.cc, macros/calibration.C,
+     macros/bootcampstandardanalysis.C, macros/pedphotcalc.C:
+     - added MCalibrationChargeBlindPix to plist
+     - added new filling of histograms with MFillH
+     - changed SetPulserColor to MCalibrationChargeBlindPix and 
+       MCalibrationChargePINDiode
+
+   * mcalib/MHCalibrationChargeBlindPix.[h,cc]:
+     - receives a pointer to MCalibrationChargePINDiode which is filled 
+       with the results and told to calculate the fluxes in the 
+       Finalize function
+     - is filled via MFillH from MExtractBlindPixel
+     - SetPulserColor directly in this class
+
+   * mcalib/MCalibrationChargeBlindPix.[h,cc]
+     - new storage container of the blind pxiel resutls, replaces 
+       MCalibrationBlindPix
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]:
+     - does not fill the histograms any more, but does ony the 
+       calculations in the postprocess. No pointer to MExtractPINDidoe
+       or MExtractBlindPixel any more.
+
+   * mcalib/MCalibrationChargePix.cc
+     - discovered an error in the calculation of phe's in 
+       CalcFFactorMethod(). The average QE was applied twice. 
+       This error had been introduced on 13/02/04
+     - loosened criterium convFFactorRelErrLimit from 0.1 to 0.2
+     - CalcFFactor asks for IsChargeValid before calculating anything
+
+   * mcalib/MCalibrationChargePINDiode.[h,cc]
+     - added function SetFluxOutsidePlexiglassAvailable
+     - SetPulserColor directly in this class
+
+   * mcalib/MCalibrationChargeCam.cc
+     - removed function SetPulserColor from here 
+
+   * mcalib/MCalibrationPINDiode.[h,cc], mcalib/MHCalibrationConfig.h,
+     mcalib/MHCalibrationPINDiode.[h,cc],
+     mcalib/MCalibrationBlindPix.[h,cc],
+     mcalib/MHCalibrationBlindPixel.[h,cc]:
+     - removed since obsolote 
+
+   * mcalib/MHCalibrationChargePix.cc
+     - make fPickup an Int_t
+
+   * mcalib/MCalibrate.cc
+     - test validity of every calibration method before retrieving
+       conversion factors
+
+   * mcalib/MHGausEvents.[h,cc]
+     - add possibility to set fit ranges in call to FitGaus
+     - make function CreateXaxis protected 
+
+
+
+ 2004/02/23: Markus Gaug
+
+   * mraw/MRawEvtPixelIter.h
+     - include GetNumHiGainSamples and GetNumLoGainSamples
+
+   * mcalib/MExtractedSignalBlindPixel.h, 
+     mcalib/MExtractBlindPixel.[h,cc]:
+     - included storage of pedestal
+
+   * mcalib/MHGausEvents.[h,cc]
+     - make the fit functions protected
+
+
+
+ 2004/02/22: Markus Gaug
+
+   * mfilter/MFCosmics.[h,cc]
+     - fMaxNumEmpty changed from absolute number to relative number of 
+       pixels
+
+   * mcalib/MHGausEvents.h
+     - remove the "->" from the pointers which are initialized only 
+       in certain cases. The streamer did not work in case that 
+       MFGausFit was left at the NULL pointer.
+
+
+
+ 2004/02/21: Markus Gaug
+
+   * manalysis/MExtractedSignalPix.[h,cc]
+     - changed variable fIsLoGainUsed to fLoGainUsed
+     - added function GetNumHiGainSaturated()
+
+
+ 2004/02/20: Markus Gaug
+
+   * mcalib/MHCalibrationChargeHiGainPix.[h,cc], mcalib/Makefile,
+     mcalib/MHCalibrationChargeLoGainPix.[h,cc],
+     mcalib/CalibLinkDef.h
+     - new class to replace MHCalibrationPixel, 
+       based on MHCalibrationChargePix
+
+   * mcalib/MCalibrationChargeCalc.[h,cc]
+     mcalib/MCalibrationChargeCam.[h,cc]
+     mcalib/MCalibrationChargePix.[h,cc]
+     mcalib/MCalibrationChargePINDiode.[h,cc]
+     mcalib/MCalibrationCalc.[h,cc], mcalib/MCalibrationCam.[h,cc],
+     mcalib/MCalibrationPINDiode.[h,cc]:
+     - added the "charge" versions, remove the old ones. The histograms 
+       should be filled in the MH... versions independently of 
+       MCalibrationChargeCalc. This is fully realized for the PIN Didoe 
+       now and will later be so for the pixels and the blind pixel. 
+
+   * mcalib/MHCalibrationChargePINDiode.[h,cc]
+     - receives a pointer to MCalibrationChargePINDiode which is filled 
+       with the results and told to calculate the fluxes in the 
+       Finalize function
+
+   * mcalib/MCalibrate.[h,cc], mcalib/MCalibrateData.[h,cc],
+     mcalib/MMcCalibrationCalc.[h,cc], mjobs/MJCalibration.[h,cc],
+     manalysis/MMcCalibrationUpdate.[h,cc],
+     mjobs/MJExtractSignal.[h,cc], manalysis/MGeomApply.cc,
+     mcalib/Makefile, mcalib/CalibLinkDef.h, macros/calibration.C,
+     macros/bootcampstandardanalysis.C,
+     macros/pedphotcalc.C:
+    - replace MCalibrationCam by MCalibrationChargeCam
+    - replace MCalibrationCalc by MCalibrationChargeCalc
+
+
+
+ 2004/02/19: Markus Gaug
+
+   * mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationCam.cc,
+     mcalib/MCalibrate.cc, mcalib/MCalibrateDate.cc,
+     manalysis/MMcCalibrationUpdate.cc:
+     - standardized naming of variables containing "Error", this also affected 
+       the calling functions MCalibrate, MMcCalibrationUpdate and MCalibrateData
+
+   * mcalib/MCalibrationCam.cc, mcalib/MCalibrationPix.cc,
+     mcalib/MCalibrationCalc.cc, mcalib/MCalibrate.cc,
+     mcalib/MCalibrateData.cc, mcalib/MCalibrationConfig.h:
+     - took out some configuration numbers and put them directly into 
+       the class
+     - remove completely MCalibrationConfig.h
+
+
+
+ 2004/02/19: Abelardo Moralejo
+
+   * mhist/MHEvent.[h,cc]:
+     - Changed names of Event "types" to make them more descriptive.
+       Former kEvtSignal is now called kEvtSignalDensity, and indicates
+       pixel content scaled by area. Added kEvtSignalRaw, which 
+       corresponds to pixel content (with no scaling) in whatever units
+       (this depends on how the MHEvent object is filled!). The default
+       constructor initializes type=kEvtSignalRaw.
+
+   * mmain/MEventDisplay.cc
+     - Changed filling of evt1 and evt2. Now they are filled with raw 
+       content of MCerPhotEvt. Since in MEventDisplay, MCerPhotEvt is
+       still filled uncalibrated (hence in ADC counts), this means that 
+       what will be now shown in Mars' camera display is now the signal 
+       in each pixel without scaling with pixel area. Given that the 
+       default flat fielding is such that equal light density 
+       corresponds to equal absolute signal (in ADC counts), this is 
+       more reasonable, and allows to check for instance how the 
+       relative pixel gains are adjusted by looking at calibration 
+       events. To be FIXED: there is however an "inconsistency" in 
+       MEventDisplay, and it is that MCerPhotEvt is still used to keep
+       uncalibrated signals. To be replaced by MExtractedSignalCam?
+
+
+
+ 2004/02/19: Thomas Bretz
+
+   * manalysis/MCerPhotEvt.h:
+     - added operator= to MCerPhotEvtIter -- is this correct?
+
+   * mhist/MHCamera.[h,cc]:
+     - added member function to calculate minimum content and 
+       maximum content for a single sector
+     - Added possibility to get a projection for a single sector.
+     - GetMinimum/GetMaximum now only takes used pixels into account
+       (you can request all pixels using a different member function)
+     - fixed projection (projection only took pixels with contents!=0
+       instead of 'used' pixels
+     - Don't call Sumw2() anymore for projection
+
+   * mjobs/MJPedestal.cc:
+     - added MPedestalCam to output again - MPedestalCam was fixed
+       yesterday
+     - Added Histograms for the two camera halves
+
+
+
+ 2004/02/18: Markus Gaug
+
+    * macros/calibration.C
+      - fixed a buggy display of the F-Factor method
+
+    * mcalib/MCalibrationCalc.cc
+      - calculate the F-Factor method already in the post-Process
+
+    * mcalib/MCalibrationPix.h
+      - move CalcFFactorMethod to public
+
+
+
+ 2004/02/18: Abelardo Moralejo
+
+    * mtools/MCubicSpline.cc
+      - in Init, corrected initialization of arrays temp and ysd, which
+	was done with n-1 elements instead of n.
+
+    * mgui/MHexagon.cc
+      - added comment explaining the algorithm.
+      - changed explicit values of Sin and Cos 60 degrees by const
+	variables (more readable).
+
+
+
+ 2004/02/18: Hendrik Bartko
+
+   * msignal/:
+     - removed the backup files *~
+     - removed the object files *.o
+     - removed the files SignalCint.*
+
+    * mgui/MHexagon.cc
+      - added comment explaining the algorithm.
+
+
+
+ 2004/02/18: Thomas Bretz
+
+   * manalysis/MPedestalCam.[h,cc]:
+     - Changed order of derivements - seems to be VERY important!
+     - changed GetSize from UInt_t to Int_t which is the type
+       of TClonesArray::GetSize() !
+
+   * mfileio/MReadReports.cc:
+     - skip trees with no entries
+
+   * mgui/MCamEvent.cc:
+     - added a comment
+
+   * mhbase/MFillH.cc:
+     - in case SetupFill returns kFALSE and kCanSkip is set
+       Skip task
+
+   * mraw/MRawFileRead.cc:
+     - don't print warning in case of none executions
+
+   * manalysis/MArrivalTimeCalc2.cc:
+     - added some const-qualifiers
+
+
+
+ 2004/02/17: Raquel de los Reyes
+
+   * macros/CCDataCheck.C
+     - Added some improvements in the plots.
+
+
+
+ 2004/02/17: Abelardo Moralejo
+
+   * macros/readrfl.C
+     - Added missing gPad->cd(1), otherwise the display of events was
+       not updated.
+
+   * mgui/MHexagon.cc
+     - DistanceToPrimitive(Float_t px, Float_t py) Changed check of
+       whether px,py is inside the pixel or not. Previous algorithm 
+       was just an approximation.
+
+
+
+ 2004/02/17: Raquel de los Reyes
+
+   * mcamera/MCameraHV.h
+     - Now it derives from a MCamEvent class and implemented the
+       GetPixContent() and DrawPixelContent() functions. Added the 
+       GetMean function to get the mean HV settings of the camera.
+
+   * macros/CCDataCheck.C
+     - Added the HV settings plots.
+
+
+
+ 2004/02/17: Hendrik Bartko
+
+   * msignal:
+     - new: directory for all signal and time extraction classes
+
+   * msignal/MArrivalTimeCam.[h,cc], manalysis/Makefile, 
+     msignal/AnalysisLinkDef.h, MGeomApply.cc:
+     - new: Storage Container for the ArrivalTime in the camera
+   
+   * msignal/MArrivalTimePix.[h,cc], manalysis/Makefile, 
+     msignal/AnalysisLinkDef.h:
+     - new: Storage Container for ArrivalTime information of one pixel
+
+   * msignal/Makefile, SignalCint.[h,cc], SignalDep.d, SignalIncl.h, 
+     SignalLinkDef.h
+     - auxiliary files for msignal directory
+
+   * manalysis/MArrivalTimeCalc2.[h,cc]:
+     - added functionality to compute error of the extracted ArrivalTime
+     - calculated ArrivalTime is stored in MArrivalTimeCam
+
+   * manalysis/MGeomApply.cc
+     - geometry is applied to MArrivalTimeCam
+
+   * Makefile:
+     - directory msignal is included
+
+
+
+ 2004/02/17: Sebastian Raducci
+
+  * mtools/MCubicSpline.[h,cc]
+    - little corrections in minimums evalustion methods
+    - changed constructors (they require the fadc slices to be const)
+
+  * macros/spline.C
+    - changed according to the MCubicSpline new constructors 
+
+  * manalysis/MArrivalTimeCalc.[h,cc]
+    - changed to use the MCubicSpline class intead of the TSpline class
+    - warning: now the arrival time is again the maximum of the spline,
+      soon it will be changed to half maximum
+
+
+
+ 2004/02/17: Wolfgang Wittek
+
+  * manalysis/MSourcPosfromStarPos.[h,cc]
+    - new class; calculates the position of the source in the camera from
+                 the position of a star in the camera and puts it into
+                 MSrcPosCam
+
+
+
+ 2004/02/16: Abelardo Moralejo
+
+   * mcalib/MMcCalibrationCalc.cc
+     - Fixed two typos in screen output.
+
+
+
+ 2004/02/16: Markus Gaug
+
+   * mcalib/MCalibrationPix.cc
+     - documentation from David's email added
+     - EffectiveQE decreased from 0.2 to 0.18 (see documentation)
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - added MExtractBlindPixel and MExtractedSignalBlindPixel
+
+   * mcalib/MExtractBlindPixel.[h,cc]
+     - new signal extractor for the Blind Pixel
+
+   * mcalib/MExtractedSignalBlindPixel.[h,cc]
+     - new container for the extracted signal of the BlindPixel
+
+   * mcalib/MCalibrationCalc.[h,cc]
+     - does not extract signal from Blind Pixel any more, searches 
+       for MExtractedSignalBlindPixel and fills the hists from there
+  
+   * macros/calibration.C, macros/bootcampstandardanalysis.C,
+     macros/pedphotcalc.C, mjobs/MJCalibration.cc:
+     - introduce the blind pixel and PIN diode extraction in the macro
+
+   * manalysis/MPedestalCam.h 
+     - changed type of fTotalEntries from ULong_t to UInt_t 
+     - fixed documentation of fTotalEntries
+
+   * manalysis/MPedCalcPedRun.h 
+     - changed type of fNumSamplesTot from ULong_t to UInt_t 
+
+   * mcalib/MHGausEvents.h
+     - changed type of fCurrentSize from ULong_t to UInt_t 
+    
+   * mcalib/MCalibrationConfig.h
+     - removed gkConversionHiLo and gkConversionHiLoErr which is now
+       directly in the class MCalibrationPix 
+
+
+
+ 2004/02/16: Thomas Bretz
+
+   * manalysis/AnalysisLinkDef.h:
+     - added missing MCerPhotEvtIter
+
+   * merpp.cc:
+     - added possible usage of database
+
+   * star.cc:
+     - moved source code into new class MJStar - preliminary
+
+   * manalysis/MCerPhotPix.cc:
+     - updated class header
+     - fixed Print-output
+
+   * mbase/MAGIC.h:
+     - removed definition of MLog
+
+   * mbase/MArgs.h:
+     - removed include of MAGIC.h
+
+   * mbase/MLog.h:
+     - added extern definition of gLog
+
+   * mbase/MParContainer.[h,cc]:
+     - move body of constructors to source file
+
+   * mcalib/MCalibrate.cc, mcalib/MCalibrateData.cc,
+     mraw/MRawCrateArray.cc, mraw/MRawCrateData.cc,
+     mraw/MRawEvtData.cc, mraw/MRawEvtHeader.cc, mraw/MRawRead.cc,
+     mraw/MRawEvtPixelIter.cc, mraw/MRawFileWrite.cc:
+     - fixed documentation header
+
+   * mcalib/MMcCalibrationCalc.[h,cc]:
+     - fixed documentation header
+     - fixed usage of FindCreateObj and FindObject
+     - removed data member to count entries (use histogram instead)
+     - use TH1 function Integral instead of doing it manually
+
+   * mfilter/MFCosmics.cc:
+     - fixed documentation
+
+   * mimage/MHillas.cc, mimage/MImgCleanStd.cc,
+     mimage/MNewImagePar.[h,cc]:
+     - replaced for-loops by Iterators
+
+   * mraw/MRawFileRead.cc, mraw/MRawSocketRead.cc:
+     - fixed documentation header
+     - check return value of MRawRunHeader::ReadEvt
+
+   * mraw/mraw/MRawRunHeader.[h,cc]:
+     - fixed documentation header
+     - added return value to MRawRunHeader::ReadEvt
+     - added constant number for max format version - preliminary 
+       (should by a static data member)
+
+   * mcalib/MHCalibrationPINDiode.cc:
+     - do not delete pointers in the destructor which are already
+       deleted in the base class
+     - reset histograms in Clear()
+
+   * mcalib/MHCalibrationPixel.cc:
+     - after deletion of instances in Clear() initialize pointer to NULL
+
+   * mcalib/MCalibrationCalc.cc, mcalib/MHCalibrationBlindPixel.cc:
+     - fixed usage of logging stream output levels
+
+   * manalysis/MPedCalcPedRun.[h,cc]:
+     - removed obsolete fSignals
+
+     - removed obsolete fNumPixels
+
+   * manalysis/MPedestalCam.h:
+     - added '->' to fArray
+
+   * mfileio/MWriteRootFile.cc:
+     - changed some output to make debugging easier
+
+   * mjobs/MJCalibration.cc:
+     - fixed a bug in drawing
+
+   * mjobs/MJExtractSignal.cc:
+     - removed MPedestalCam from MWriteRootFile output.
+       When creating the branch it crashes - reason unknown I'll
+       investigate further
+
+
+
+ 2004/02/16: Markus Gaug
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h, macros/calibration.C:
+     - added MHCalibrationRelTimePix
+
+   * mcalib/MHCalibrationRelTimePix.[h,cc],
+     mcalib/MHCalibrationRelTimeCam.[h,cc]:
+     - new classes to fit and display the relative arrival times. 
+     - filled from MArrivalTime	
+     - need: MFillH("MHCalibrationRelTimeCam","MArrivalTime")
+
+   * manalysis/MCalibrationCalc.cc
+     - take out all uncommented code referring to the relative arrival time
+
+   * manalysis/MArrivalTime.h 
+     - changed function GetNumPixels to GetSize
+
+   * macros/bootcampstandardanalysis.C, macros/pedphotcalc.C
+     - included cosmics rejection which was in MCalibrationCalc before
+
+
+
+ 2004/02/14: Markus Gaug
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - added MHCalibrationChargePINDiode
+
+   * mcalib/MHCalibrationChargePINDiode.[h,cc]
+     - new class to fill the PIN Diode histograms. Derives from 
+       MHCalibrationChargePix and is filled with MFillH from the 
+       container MExtractedSignalPINDiode. 
+       Will replace MHCalibrationPINDiode entirely soon.
+
+   * mcalib/MHCalibrationChargePix.[h,cc]
+     - new base class for the calibration charges histogram pixel. 
+       Derives from MH and can be filled with the MH with the MH 
+       functions. 
+
+   * mcalib/MExtractPINDiode.[h,cc]
+     - new signal extractor for the PIN Diode
+
+   * mcalib/MExtractedSignalPINDiode.[h,cc]
+     - new container for the extracted signal of the PIN Diode
+
+   * mcalib/MCalibrationCalc.[h,cc]
+     - remove the PIN Diode signal extraction 
+
+   * manalysis/MHPedestalPix.[h,cc]
+     - new version of MHPedestalPixel, deriving from MHGausEvents.
+
+   * manalysis/MHPedestalPixel.[h,cc]
+     - old version removed, since obsolete (and erroneous)
+
+   * manalysis/MHPedestalCam.[h,cc]
+     - histogramming part of MPedestalCam now in own class 
+
+   * manalysis/MPedestalPix.h
+     - removed include of MHPedestalPixel
+
+   * macros/calibration.C 
+     - changed pedestal displays accordingly
+
+   * mjobs/MJPedestal.h
+     - class TCanvas included (did not compile otherwise)
+
+   * mhbase/MH.cc
+     - included call to FindGoodLimits(..) in CutEdges()
+     - axe from pointer to reference
+     - "CutEdges" renamed to "StripZeros"
+ 
+   * manalysis/MHPedestalPixel.cc, mcalib/MHCalibrationPixel.cc,
+     mcalib/MHCalibrationBlindPixel.cc:
+     - "CutEdges" renamed to "StripZeros"
+
+   * mcalib/MHGausEvent.[h,cc], mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - replaced by the improved version: MHGausEvents.[h,cc]
+
+
+
+ 2004/02/14: Thomas Bretz
+
+   * manalysis/MCerPhotEvt.[h,cc]:
+     - added 'Iterator' facility, this will replace some for-loops
+       in the near future
+     
+   * mbase/MTime.[h,cc]:
+     - added a more powerfull interface to get and interprete the
+       MTime contents as string
+     - added a new constructor
+
+   * mreport/MReportTrigger.h:
+     - fixed GetPixContent
+
+   * mtools/MCubicCoeff.cc, mtools/MCubicSpline.[h,cc]:
+     - many small changes to simple details (like order of includes)
+     - some speed improvements
+     - many small simplifications
+     - changed parts of the code to be more C++ like (eg Iterators
+       instead of for-loops)
+     - disentangles some if-cases
+     - replaced some math.h function by TMath::
+     - removed data-member fN (obsolete with iterators)
+
+
+
+ 2004/02/13: Wolfgang Wittek
+
+   * mcalib/MCalibrateData.[h,cc]
+     - new class; 
+       like MCalibrate, but in ReInit it fills the MPedPhot container
+       using informations from MPedestal, MExtracteSignalCam and 
+       MCalibrationCam
+
+   * mcalib/Makefile, mcalib/CalibLinkDef.h
+     - added MCalibrateData
+
+   * manalysis/MPedestalWorkaround.[h,cc]
+     - create MMcEvt container and fill with theta = 10.0
+     - set pedestalRMS = 0. if it is > 10.0
+
+   * manalysis/MSupercuts.[h,cc]
+     - change default values of parameters
+
+   * manalysis/MSupercutsCalc.[h,cc]
+     - change dNOMLOGSIZE from 4.1 to 5.0
+
+   * mhist/MHBlindPixels.[h,cc]
+     - change MPedestalCam to MPedPhotCam
+
+   * mhist/MHSigmaTheta.[h,cc]
+     - automatic binning for pixel number doesn't work
+       use default binning
+
+
+
+ 2004/02/13: Markus Gaug
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - added variables gkAverageQE, gkAverageQEErr, and fAverageQE, 
+       fAverageQEErr
+     - gkAverageQE initializes to 0.2 (according to David)
+     - gkAverageQEErr initializes to 0.02 (dito)
+     - added new member function: SetAverageQE
+     - call to GetMeanConversionFFactorMethod returns: 
+       fMeanConversionFFactorMethod/fAverageQE. 
+     - call to GetErrorConversionFFactorMethod returns: 
+       errors of fMeanConversionFFactorMethod and fAverageQEErr added 
+       quadratically
+
+   * mcalib/Makefile
+     - split into two parts one comment line 
+
+
+ 2004/02/13: Thomas Bretz
+
+   * mbadpixels/MBadPixelsTreat.[h.cc]:
+     - added for new bad pixel treatment
+
+   * mbadpixels/Makefile, mbadpixels/BadPixelsLinkDef.h:
+     - added MBadPixelsTreat
+
+   * merpp.cc:
+     - changed the name of the "DC" tree to "Currents" to make
+       MReportRead work correctly with this tree
+
+   * mbase/MTime.[h,cc]:
+     - Changed UpDMagicTime to support nanosec instead of millisec
+     - exchanged Reset() by Clear() not to clear the yy/mm/dd 
+       information away in an eventloop
+
+   * mraw/MRawEvtHeader.[h,cc]:
+     - implemented decoding of the time-stamp for raw-data files
+       with version>2. Thanks to Marcos.
+
+   * mraw/MRawRead.[h,c]:
+     - pipe file version number to MRawEvtHeader::ReadEvt
+     - create fake time for file-version<3
+
+   * macros/readMagic.C:
+     - changed to use MInteractiveTask
+
+   * mbase/MPrint.cc:
+     - fixed debugging level of some output
+     
+   * mhist/MHCamera.[h,cc]:
+     - fixed handling in AddNotify (necessayr due to change of
+       inheritance from MCamEvent)
+     - replaced cout by gLog
+     - added fNotify to list of cleanups
+
+   * mhist/MHEvent.cc, mjobs/MJCalibration.cc,
+     mjobs/MJPedestal.cc:
+     - fixed usage of AddNotify
+
+   * mfileio/MReadReports.cc:
+     - use a different way to determin whether the tree is a valid tree,
+       skip invalid trees
+       
+   * mfileio/MReadTree.cc:
+     - added another sanity check at the beginning of PreProcess
+     
+   * mhbase/MFillH.[h,cc]:
+     - added bit kCanSkip which skips MFillH in case the necessary container
+       wasn't found.
+     - cd into the corresponding canvas before filling the MH
+
+
+
+ 2004/02/12: Markus Gaug
+ 
+   * mbase/MArray.[h,cc]:
+     - changed name of StripZeros
+
+   * mcalib/MHGausEvent.cc:
+     - corrected call to StripZeros
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - implemented dummy for combined method
+
+   * mcalib/MCalibrate.[h,cc]
+     - implemented a dummy for calibration factor 1. (requested by
+       Javier Rico)
+     - implemented combined method
+     - check for valid methods moved to ReInit
+
+   * mcalib/MCalibrationCalc.cc
+     - removed initialization of non-used nsamples
+
+   * mcalib/MHCalibrationPixel.[h,cc], mcalib/MCalibrationPix.[h,cc],
+     mcalib/MCalibrationCalc.[h,cc]
+     macros/calibration.C
+     - implemented new histograms: 
+       HSinglePheFADCSlices and HPedestalFADCSlices
+       They are filled with the FADC slice values of either a s.phe. 
+       event or a pedestal event. The decision is taken with the 
+       variable: MCalibrationCalc::fBlindPixelSinglePheCut, to be set 
+       with a setter 
+
+   * mtools/MFFT.[h,cc]
+     - PowerSpectrumDensity of TArrayI implemented
+
+
+
+ 2004/02/12: Thomas Bretz
+ 
+   * mbase/MArray.[h,cc]:
+     - changed argument of CutEdges from pointer to reference
+
+   * mgeom/MGeomPix.h:
+     - fixed calculation of area of pixel. It was too big for a 
+       factor of 2
+
+   * mjobs/MJCalibration.cc:
+     - slight change of name of a MHCamera
+
+   * manalysis/MExtractSignal.cc:
+     - slight change to the creation of the satpixels list
+     
+   * mcalib/MHCalibrationBlindPixel.cc, mcalib/MHCalibrationPixel.cc,
+     mcalib/MHGausEvent.cc:
+     - corrected call to ProjectArray
+     - corrected call to CutEdges
+     
+   * mfilter/MFCosmics.[h,cc]:
+     - small fixes to logging output
+     - small simplification to return statement
+     - declared CosmicsRejection const
+
+   * mhbase/MH.[h,cc]:
+     - changed argument of ProjectArray from pointer to reference
+     - added missing calcualtion of minimum
+     - removed obsolete SetEntries
+     - changed SetDirectory from NULL to gROOT
+
+
+
+ 2004/02/12: Javier L�ez
+
+   * macros/pointspreadfunction.C
+     - added new macro that fits with a 2D gaussian the DC spot for an 
+       star. It gives you the RMS of the PSF and the center of the star,
+       very useful for misspointing studies.
+
+
+
+ 2004/02/11: Hendrik Bartko
+
+   * manalysis/MExtractSignal2.cc:
+     - introduced a validity check for the set-function of the window 
+       size (even number of slices, WindowSize < NumberSlices)
+
+   * manalysis/MArrivalTimeCalc2.[h,cc], manalysis/Makefile, 
+     manalysis/AnalysisLinkDef.h:
+     - new: introduced the calculation of the arrival time as the signal 
+       weighted mean of the time slices in the maximum window
+
+
+
+ 2004/02/11: Markus Gaug
+
+   * mcalib/MCalibrationCalc.cc:
+     - the blind pixel signal extractor introduced one week ago, counted 
+       one FADC slice too little, thus the normalization w.r.t. pedestals 
+       was wrong. Now corrected.
+
+   * manalysis/MExtractSignal.cc, manalysis/MExtractSignal2.cc:
+     - when "WARNING - Lo Gain saturated" occurs, display also the
+       corr. pixel numbers.
+
+   * mbase/MArray.[h,cc]:
+     - introduced function to cut array edges with zeros. 
+       (Thomas, should we keep it there or move it to another class? )
+
+   * mcalib/MCalibrationCalc.[h,cc]:
+     - new function SetBlindPixelRange to set start and end of FADC slices 
+       used for the blind pixel signal extraction. 
+     - remove fEvents which are not necessary any more after the shift 
+       to MFCosmics.
+
+   * mcalib/MHCalibration(Blind)Pixel.[h,cc]:
+     - show the fourier spectrum now with axes in frequency [Hz] instead 
+       of inverted events. 
+
+   * mcalib/MHGausEvent.[h,cc], mcalib/Makefile, mcalib/CalibLinkDef.h:
+     - new base class for all kind of events with variables having a 
+       Gaussian distribution. Will serve as base class for the 
+       existing and new calibration histogram classes. 
+
+
+
+ 2004/02/11: Abelardo Moralejo
+
+   * mmain/MEventDisplay.cc
+     - Switched order of MMcPedestalCopy and MCerPhotCalc in tasklist:
+       MMcPedestalCopy must be executed earlier!
+
+
+
+ 2004/02/10: Raquel de los Reyes
+
+   * mhist/MHPixVsTime.[h,cc]:
+     - Added a default draw function and replaced the TGraph object 
+       by a pointer to a TGraph object.
+
+   * mreport/MReportTrigger.h:
+     - Now it dereives from a MCamEvent class and implemented the
+       GetPixContent() and DrawPixelContent() functions.
+
+   * maccros/CCDataCheck.C:
+     - An update of the previous macro. New plots: subsystems status and
+       macrocells trigger.
+
+
+
+ 2004/02/10: Markus Gaug
+
+   * mcalib/MCalibrationCam.cc:
+     - fixed documentation
+
+   * mhbase/MH.[h,cc]:
+     - new function ProjectArray
+
+   * mcalib/MHCalibrationPixel.[h,cc],
+     mcalib/MHCalibrationBlindPixel.[h,cc]:
+     - use ProjectArray from MH to plot the projection of the fourier 
+       spectrum
+
+   * mfilter/MFCosmics.[h,cc], mfilter/Makefile,
+     mfilter/FilterLinkDef.h:
+     - new filter removing cosmics, the same as in MCalibrationCalc
+       where it was removed now. 
+       Call: MFCosmics cosmics; 
+             MContinue cont(&cosmics); 
+             tlist.AddToList(&cont);
+
+   * mcalib/MCalibrationCalc.[h,cc]:
+     - removed cosmics rejection from there
+ 
+   * macros/calibration.C, mjobs/MJCalibration.cc:
+     - changed cosmics rejection to the filter algorithm
+
+
+
+ 2004/02/09: Markus Gaug
+
+   * mcalib/MCalibrationBlindPix.[h,cc]:
+     - added histogram to display the average in FADC slices of all 
+       single and double phe events
+
+   * mcalib/MCalibrationCalc.cc:
+     - fill histograms of single-phe events with higain and logain
+       sampls
+
+   * mcalib/MCalibrationCam.[h,cc], mcalib/MCalibrationCalc.cc,
+     mcalib/MCalibrationConfig.h:
+     - take all pixel areas out of MGeomPix::GetA(), remove all previous
+       areas 
+     - calculate photon fluxes from blind pixel and PIN diode, use 
+       area only to fill the conversion factors in MCalibrationPix 
+
+
+   * mcalib/MJCalibration.cc:
+     - display of number of photons for Blindpixel and PIN Diode Method 
+       changed to display of photon flux which is the actually 
+       calculated quantity
+
+
+
+ 2004/02/09: Thomas Bretz
+
+   * mbadpixels/*:
+     - added
+
+   * Makefile:
+     - added MBadPixels
+
+   * manalysis/MGeomApply.cc:
+     - fixed class description
+
+   * mjobs/MJCalibration.[h,cc], mjobs/MJExtractSignal.[h,cc]:
+     - added bad pixel treatment
+
+   * mjobs/MJPedestal.[h,cc]:
+     - reorganized order of functions
+     - removed a nonsense scrren output (some BLABABLA or so)
+
+   * mjobs/Makefile:
+     - added include for mbadpixels
+
+   * mmain/MBrowser.cc:
+     - do not call construtor of TGTReeLBEntry if pic0=0
+
+
+
+ 2004/02/09: Raquel de los Reyes
+
+   * mcamera/MCameraLids.h, mreport/MReportCamera.h
+     - Added the "Get" functions to access the private data 
+       members of the class.
+
+
+
+ 2004/02/09: Markus Gaug
+
+   * MMcCalibrationUpdate.cc, MCalibrate.cc, MCalibrationPix.cc,
+     MCalibrationPix.h:
+     - replace MCalibrationPix->IsChargeFitValid() by IsChargeValid()
+       because we can calibrate with the histogram mean and RMS even 
+       if the fit is not OK. Thus, there is a question: IsFitted() and 
+       IsChargeValid(), i.e. does the charge make any sense? 
+
+   * MCalibrationCam.cc, MCalibrationConfig.h, MCalibrationCalc.cc:
+     - found serious bug in calculation of conversion factors for the 
+       outer pixels: 
+       GetMeanConversionBlindPixelMethod and 
+       GetMeanConversionPINDiodeMethod 
+       did not correct for the area of the outer pixel, this did only 
+       MCalibrationCam::GetPixelContent which is not used by MCalibrate
+
+
+
+ 2004/02/06: Markus Gaug
+
+   * mgeom/MGeomCam.h 
+     - replaced in Comment of fPixRatio: 
+       "ratio between size of pixel idx and pixel 0" by
+       "ratio between size of pixel 0 and pixel idx" 
+
+   * manalysis/MPedestalCam.cc
+     - catch calls to MHPedestalPixel in case that they are not filled 
+       This led previous calls to segmentation violations
+     - remove include of MHExtractedSignalPix
+ 
+   * manalysis/MHExtractedSignalPix.[h,cc]
+     - is everything in MHPedestalPixel, so removed it again
+
+   * mjobs/MJPedestal.cc
+     - put the projections into Display()
+     - correct the input of Display (0: pedestal, 1: pedestalerror, 
+                                     2: pedRMS, 3: pedRMSerror)
+
+   * manalysis/MHPedestalPixel.cc
+     - increased number of bins in for charges plot
+
+   * mtools/MFFT.[h,cc]
+     - possibility to have PSD directly from TArray
+
+   * mjobs/MJCalibration.[h,cc]
+     - fixed displays
+     - replaced MExtractSignal by MExtractSignal2
+
+   * mcalib/MHCalibrationPixel.[h,cc], mcalib/MHCalibrationBlindPixel.[h,cc],
+     mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationBlindPix.[h,cc],
+     mcalib/MCalibrationPINDiode.[h,cc], mcalib/MHCalibrationPINDiode.[h,cc]:
+     - remove histograms MHChargevsN..., now keep TArrays directly
+     - check for oscillations for all pixels (and you will not trust 
+       your eyes when you look at the results :-((((
+
+   * mcalib/MCalibrationCalc.[h,cc]
+     - remove ArrivalTime -> go to separate class
+     - remove BlindPixel and PIN Diode overflow, now handled directly 
+       inside the corr. classes. 
+     - remove SkipTimeFits -> go the arrival time class
+
+   * mcalib/MCalibrationCam.h
+     - new getters for number of photons
+     - removed timeslicewidth -> go the corr. time containers
+
+   * mcalib/MCalibrationCam.cc
+     - removed times of GetPixelContent
+     - added OscillationChecks in GetPixelContent
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - remove calpix.SkipTimeFits which is now obsolet
+
+   * macros/calibration.C
+     - all previous changes now in this macro.
+     - (NB: Thomas, du brauchst in MJCalibration nicht mehr aendern, 
+       das ging diesmal in einem Aufwasch)
+
+
+
+ 2004/02/06: Thomas Bretz
+
+   * mhist/MHPixVsTime.[h,cc]:
+     - changed such that you can set the name of the time container now 
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - added GetMaxPixId()
+
+   * mraw/MRawEvtData.cc:
+     - fixed wrong size calculation for fABflags
+
+
+
+ 2004/02/06: Oscar Blanch
+
+   * mmc/MFadcDefine.h && mmc/MMcFadcHeader.cxx
+     - We cahnged the name (and values) of the global variable
+        MFADC_RESPONSE_AMPLITUDE to  MFADC_RESPONSE_INTEGRAL
+
+
+
+ 2004/02/05: Markus Gaug
+
+   * mcalib/MHCalibrationPixel.[h,cc]
+     - put an NDF limit for the fit
+     - removed all TStrings and replace them by Form(..)
+     - Check for nan's of all returned fit values
+
+   * mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationCam.cc:
+     - reshuffled HiLoGainConversion, calculation of F-Factor method, 
+     - calculation of total F-Factor of the readout.
+
+   * mcalib/MCalibrationCam.cc
+     - include relative times to display with GetPixelContent
+
+   * mcalib/MCalibrationCalc.[h,cc]
+     - flag to skip Hi-Lo Calibration
+     - Hi-LO Graph not filled any more after overflow of ChargevsN
+     - fill the blind pixel differently from the rest of pixels
+
+   * mcalib/MCalibrate.cc:
+     - call to const MCalibrationPix &pix replaced by MCalibrationPix &pix
+
+   * manalysis/MArrivalTimeCalc.cc
+     - default step width 100 ps. 
+     - look for half maximum (at rising edge)
+
+   * manalysis/MExtractSignal.[h,cc]
+     - removed uncommented code (arrival time)
+     - set start byte back by one like it was before TB's changes 
+       (does not affect the calculation of number of FADC slices)
+
+   * manalysis/MExtractSignal2.[h,cc]
+     - removed uncommented code (arrival time)
+
+   * manalysis/MHPedestalPixel.[h,cc]
+     - is now filled with total pedestals (not per slice), but results are 
+       renormalized to values per slice (this is not to screw up with the 
+       pedestal RMS and the derived uncertainties)
+     - new function Renorm(nslices)
+
+   * manalysis/MPedestalCam.[h,cc]
+     - introduced function Clone() (like proposed by TB)
+     - call to MHPedestalPixel operator() not const any more
+     - take out lots of uncommented code 
+     - found bug in initialization of hists. SetupFill is called in 
+       PreProcess, therefore, TObjArray is not yet enlarged there. 
+       Now, InitUseHists is called in Fill
+     - MHPedestalPixel is now filled with total pedestals (not per slice), 
+	but results are 
+       renormalized to values per slice (this is not to screw up with the 
+       pedestal RMS and the derived uncertainties)
+
+   * manalysis/MPedCalcPedRun.cc
+     - added author
+     - split calculation of RMS into two steps to make it more clear to 
+       the user
+
+   * macros/calibration.C
+     - found bug introduced two days ago, namely calculating pedestlas with 
+       MExtractSignal2 which is now fixed
+     - Skip HiLoConversionCalibration
+
+
+
+ 2004/02/05: Abelardo Moralejo
+
+   * macros/starmc2.C
+     - added 3rd argument, "kFALSE", to call of MWriteRootFile::Add
+       for both MMcEvt and MMcRunHeader since these containers are
+       not present in real data. Name of macro is no longer adequate if
+       we will use it for calibrated real data (to be changed if so).
+
+
+
+ 2004/02/05: Sebastian Raducci
+
+   * mtools/MCubicSpline.[h,cc]
+     - added
+     - this class will take the place of the TSpline class to 
+       calculate arrival times
+
+   * mtools/MCubicCoeff.[h,cc]
+     - added
+     - this class is used by MCubicSpline to store coefficients
+
+   * macros/spline.C
+     - added
+     - test macro. Shows how to use the MCubicSpline class
+     - it could be used to test the methods of the Spline class
+
+
+
+ 2004/02/05: Thomas Bretz
+
+   * mmain/MBrowser.cc:
+     - fixed a double deletion of a TGLayoutHints
+
+
+
+ 2004/02/04: Markus Gaug
+
+   * mmain/MBrowser.cc:
+     - corrected TGTReeLBEntry for TGTreeLBEntry
+
+
+
+ 2004/02/04: Thomas Bretz
+ 
+   * manalysis/MExtractSignal2.cc:
+     - don't allow odd numbers for the window size
+
+   * mfilter/MFilterList.cc:
+     - corrected a wrong logging message
+
+   * mmain/MBrowser.cc:
+     - added '/data/MAGIC' as shortcut in the combo box
+     
+   * mraw/MRawEvtPixelIter.cc:
+     - optimized calculation of MaxIdx
+
+
+
+ 2004/02/04: Abelardo Moralejo
+
+  * macros/starmc2.C
+    - removed unnecessary variables BinsHigh, BinsLow
+
+
+
+ 2004/02/04: Markus Gaug
+
+  * manalysis/MPedestalCam.[h,cc], manalysis/MPedestalPix.[h,cc],
+    manalysis/MPedCalcPedRun.[h,cc], manalysis/MHPedestalPixel.[h,cc],
+    macros/calibration.C:
+    - histograms are now filled with MFillH as proposed and coded by 
+      Thomas Bretz. Some modifications had to be done, however. 
+    - Class to hold MHPedestalPixel is still MPedestalCam
+    - MPedCalcPedRun does nothing any more (except from what is was 
+      doing before)
+
+  * manalysis/MExtractSignal.cc
+    - remove uncommented code
+
+  * mcalib/MCalibrationCalc.[h,cc]
+    - modified way to handle histogram overflow: Now flags are set and 
+      ChargevsN histogram is not tried to be filled subsequently
+
+
+
+ 2004/02/03: Markus Gaug
+ 
+   * manalysis/MHExtractedSignalPix.[h,cc]
+     - added Thomas B. modified version of MHPedestalPixel. Later will 
+       remove MHPedestalPixel
+
+   * manalysis/MCalibrationPix.[h,cc], manalysis/MHCalibrationPixel.[h,cc],
+     manalysis/MCalibrationCam.cc, macros/calibration.C:
+     - now split completely absolute and relative times. Absolute 
+       times are not fitted, but their histogram mean and rms are 
+       returned.
+
+
+
+ 2004/02/03: Thomas Bretz
+
+   * mfileio/MReadTree.cc:
+     - fixed handling of -1 entries in AddFile: root 3.10/02 crashed
+
+   * manalysis/MExtractSignal.[h,cc]:
+     - moved code to extract the signal from Process to
+       new member function FindSignal, I left the arrival time 
+       extraction as commented-out code in the code just as a 
+       demonstration to do this very fast.
+
+
+
+ 2004/02/02: Markus Gaug
+
+  * manalysis/MPedCalcPedRun.cc
+    - corrected formulae in Class description
+
+  * mcalib/MCalibration.[h,cc], mcalib/MHCalibration.[h,cc],
+    manalysis/MMcCalibrationUpdate.cc:
+    - calculate relative times and absolute times. Fit only 
+      the relative ones. 
+
+
+
+ 2004/02/02: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.cc, MMcPedestalCopy.cc
+     - removed file type check (MC or data) from PreProcess since now
+       run headers are not yet known at that point.
+
+   * mcalib/MMcCalibrationCalc.cc
+     - same as above.
+
+   * NEWS
+     - updated.
+
+
+
+ 2004/02/02: Thomas Bretz
+
+   * manalysis/MExtractSignal2.[h,cc]:
+     - added new task which takes a given number of slices with the
+       highest integral content as signal.
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - added MExtractSignal2
+
+
+
+ 2004/01/30: Abelardo Moralejo
+
+   * macros/starmc.C
+     - changed default FADC integration range (more adequate for coming
+       camera version).
+
+   * macros/mccalibrate.C, starmc2.C
+     - added. First macro transforms input files from camera simulation
+       into files with pixel data already calibrated in photons. The 
+       second reads in an already calibrated data file and produces an 
+       output file with Hillas parameters. Both together do the same as
+       starmc.C, but it is convenient to have files containing 
+       calibrated pixel information.
+
+
+
+ 2004/01/30: Thomas Bretz
+ 
+   * mbase/MDirIter.h:
+     - added GetNumEntries
+
+   * mhist/MHEvent.cc:
+     - added a dynamic_cast from MParContainer to MCamEvent to get the
+       correct pointer to the correct base-class.
+
+   * mbase/MStatusDisplay.cc:
+     - In EventInfo check whether gPad==0
+     
+   * mfileio/MReadMarsFile.cc:
+     - removed reading RunHeaders from PreProcess, this resulted
+       in strange behaviour of writing RunHeaders
+     - fixed consistency check for RunType accordingly
+
+   * mfilter/MFilterList.cc:
+     - do not skip adding filter if only a filter with the same name 
+       exists
+       
+   * mraw/MRawFileRead.cc:
+     - added an output message if run header is not accessible
+     
+   * mraw/MRawRunHeader.[h,cc]:
+     - initialize fRunType to new enum kRTNone
+
+   * mfilter/MFGeomag.cc:
+     - set fResult to kFALSE at the beginning of Process
+     - according to this removed setting fResult=kFALSE before return
+     - replaced some float by Float_t
+     - added some const-qualifiers
+     - replaced (rig<0.5/pr*R*(r2-r1)+r1) by (rig-r1)*pr<rnd
+       with rnd = R * (r2-r1)/2 to make sure that we cannot
+       devide by 0
+
+   * manalysis/MPedCalcPedRun.cc:
+     - added some comments
+
+   * Makefile:
+     - added mjobs
+
+   * mjobs/*:
+     - added
+
+   * mbase/Makefile, mbase/BaseLinkDef.h:
+     - added MRunIter
+
+   * mbase/MRunIter.[h,cc]:
+     - added
+
+
+
+ 2004/01/30: Markus Gaug
+
+   * manalysis/MPedestalCam.h
+     - added function IsUsedHists()
+
+   * manalysis/MPedestalCam.cc
+     - modified GetPixelContent
+
+   * manalysis/MPedestalCam.cc, manalysis/MPedCalcPedRun.cc:
+     - include storage of number of used FADC slices to compare later 
+       the pedestal per slice ( and sigma per slice)
+     - return relative differences in GetPixelContent
+
+   * mcalib/MCalibrationCalc.[h,cc], mcalib/MHCalibrationBlindPixel.[h,cc]:
+     - fBlindPixelId and fPINDiodeId now like in PedestalCam
+     - fill Blind Pixel with information about its fitted pedestal if 
+       available
+     - initialize charges histogram with a bigger range
+     - use pedestal information to constrain the pedestal fit ranges
+
+   * manalysis/MHPedestalPixel.cc
+     - initialize charges histogram with a bigger range
+
+   * macros/calibration.C
+     - SetRange of MExtractSignal to 1,14 (see emails of yesterday)
+     - apply new GetPixelContents of MPedestalCam (more calculations 
+       and displays of errors, correction for different FADC slice 
+       number)
+
+   * manalysis/MExtractSignal.cc
+     - not access to MArrivalTime any more. The same information is 
+       stored in MRawEvt->GetPixelContent(...)
+
+   * manalysis/MCalibrationCalc.cc
+     - retrieve default arrival time from MRawEvt 
+
+   * manalysis/MCalibrationBlindPix.cc, manalysis/MCalibrationPix.cc
+     - check for NaN's in fit results
+
+
+
+ 2004/01/29: Abelardo Moralejo
+
+   * mfileio/MWriteFile.h
+     - added missing declaration of ReInit
+
+   * manalysis/MMcCalibrationUpdate.cc
+     - added call to MCalibrationCam::SetBlindPixelMethodValid(kTRUE) 
+       to adapt to recent changes in MCalibrate.
+
+
+
+ 2004/01/29: Thomas Bretz
+
+   * manalysis/MArrivalTime.h, manalysis/MCameraData.h,
+     manalysis/MCerPhotEvt.h, manalysis/MExtractSignalCam.h,
+     manalysis/MPedPhotCam.h, manalysis/MPedestalCam.h,
+     mcalib/MCalibrationCam.h, mcamera/MCameraDC.h,
+     mraw/MRawEvtData.h, mreflector/MRflEvtData.h:
+     - split derivement into MParContainer and MCamEvent
+
+   * manalysis/MExtractSignalCam.[h,cc]:
+     - removed obsolete MExtractSignal::ReInit
+     - added -> to fArray
+
+   * mbase/MParList.h:
+     - added a new bit kIsProcessing
+     
+   * mbase/MTaskList.cc:
+     - fixed the handling of kDoNotReset and the bahaviour of
+       SetReadyToSave, such that it is possible to write all
+       headers 
+
+   * mfileio/MWriteFile.cc:
+     - added ReInit which also calls CheckAndWrite
+     
+   * mgui/MCamEvent.h:
+     - does not derive from MParContainer anymore
+
+
+
+ 2004/01/29: Markus Gaug
+
+   * mcalib/MCalibrationCalc.[h,cc], mcalib/MCalibrationCam.[h,cc], 
+     mcalib/MCalibrationConfig.h
+     - put gkCalibrationBlindPixelId and gkCalibrationPINDiodeId 
+       directly into the corresponding classes.
+
+
+
+ 2004/01/29: Nicola Galante
+
+   * mhistmc/MHMcTriggerLvl2.[h,cc]:
+     - In method MHMcTriggerLvl2::GetHistByName(const TString name) 
+       added string checking to return also 
+       fHistCellPseudoSize, fHistCellPseudoSizeNorm
+       and fHistCellPseudoSizeEnergy.
+     - Added inline functions GetHistCellPseudoSize() and 
+       GetHistCellPseudoSizeNorm().
+
+
+
+ 2004/01/28: Javier Rico
+
+   * mcalib/MCalibrate.[h.cc]
+     - include possibility to select the calibration method to be used
+
+
+
+ 2004/01/28: Markus Gaug
+
+   * mcalib/MCalibrate.[h.cc]
+     - corrected Int_t ReInit() to Bool_t ReInit(MParList *pList)
+
+   * mcalib/MCalibrationCalc.[h,cc], mcalib/MCalibrationCam.[h,cc]:
+     - included flags to indicate if Blind Pixel Method or PIn Diode 
+       method was OK. Up to now, program stopped, if one of the two 
+       methods was chosen but not able to being executed.
+
+   * manalysis/MArrivalTimeCalc.cc, manalysis/MExtractSignals.cc,
+     manalysis/MGeomApply.cc:
+     - put all missing InitSize(npixels) into MGeomApply	 
+
+   * manalysis/MPedCalcPedRun.[h,cc], manalysis/MPedestalCam.[h,cc],
+     manalysis/MPedestalPix.[h,cc], manalysis/MHPedestalPixel.[h,cc],
+     manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - include possibility to fit the pedestals with Gaussian. 
+     - old methods are not affected. 
+     - add new method with MPedCalcPedRun::SetUseHists()
+
+
+
+ 2004/01/28: Abelardo Moralejo
+
+   * mcalib/MMcCalibration.cc
+     - fixed wrong variable type in call to TH1F constructor (number of
+       bins is now integer), which resulted in a compilation warning.
+
+
+
+ 2004/01/28: Thomas Bretz
+
+   * manalysis/MPedestalCam.cc:
+     - removed unwanted CheckBound from operators. CheckBounds is ONLY
+       ment for really old MC files and will be removed in the future
+       anyhow.
+
+   * mcalib/MHCalibrationPixel.h:
+     - removed obsolete include of MFFT 
+
+   * manalysis/MCerPhotAnal.cc, manalysis/MCerPhotCalc.cc,
+     manalysis/MPedestalCam.[h,cc]:
+     - removed use of obsolete MPedestalCam::CheckBounds. This was
+       a workaround for a 'bug' in very old camera files, which is not
+       necessary anymore.
+
+   * manalysis/MCerPhotAnal2.[h,cc]:
+     - replaced MPedestalCam by MPedPhotCam
+     
+   * manalysis/MExtractSignal.cc:
+     - some small simplification to the signal extraction
+     - removed some obsolete variables
+     - replaced for by while
+     - removed obsolete casts
+     
+   * mmain/MEventDisplay.cc:
+     - gave names to the filters
+     - removed adding MHCamera to fList because it was deleted twice
+
+   * mhist/MHCamera.cc:
+     - fixed usage of fPainter in Paint() - title was not updated 
+       correctly
+
+
+
+ 2004/01/28: Sebastian Raducci
+
+   * manalysis/MArrivalTime.[h,cc]:
+     - removed all the code relative to the cluster evaluation
+
+
+
+ 2004/01/27: Markus Gaug
+ 
+   * manalysis/MPedestalPix.cc:
+     - initialize default values to 0 instead of -1.
+
+   * manalysis/MPedestalCam.[h,cc]:
+     - include CheckBounds, also in operator[]
+
+   * mcalib/MCalibrationCam.[h,cc]:
+     - apparently, there was a reference to InitSize(UInt_t i) instead 
+       of InitSize(Int_t i), where compiler complained, now changed
+ 
+   * mcalib/MHCalibration*, mcalib/MCalibration*:
+     - fixed all Clear()'s, Reset()'s, direct intializers
+
+
+
+ 2004/01/27: Thomas Bretz
+
+   * mdata/MDataChain.cc:
+     - added '%' to supported operators
+
+
+
+ 2004/01/26: Nicola Galante
+
+   * manalysis/MMcTriggerLvl2.[cc,h]:
+
+     - Defined some static constants to avoid ugly "magic numbers"
+       in arrays: gsNCells, gsNTrigPixels,
+       gsNPixInCell, gsNLutInCell, gsNPixInLut, fNumPixCell.
+     - Added method 
+       MMcTriggerLvl2::GetCellCompactPixel(int cell, MGeomCam *fCam)
+       which computes compact pixels into a given L2T macrocell.
+     - Added method 
+       MMcTriggerLvl2::CalcBiggerCellPseudoSize() 
+       which computes fCellPseudoSize, the maximum Pseudo Size into L2T 
+       macrocells
+     - Added method 
+       MMcTriggerLvl2::GetCellPseudoSize() const 
+       which returns fCellPseudoSize
+     - Added method 
+       MMcTriggerLvl2::IsPixelInCell(Int_t pixel, Int_t cell),
+       which controls whether a pixel belongs to a given L2T cell.
+     - Added method 
+       MMcTriggerLvl2::GetMaxCell() const 
+       which returns fMaxCell, the cell with the maximum 
+       fCellPseudoSize.
+
+
+
+ 2004/01/26: Markus Gaug, Michele Doro
+
+   * manalysis/MArrivalTime.[h,cc], manalysis/MArrivalTimeCalc.[h,cc]:
+     - moved calculation of arrival time from MArrivalTime to 
+       MArrivalTimeCalc. MArrivalTime does not do any Process-job
+       anymore
+     - TSpline5 now on stack. 
+     - function to set the stepsize
+
+   * mcalib/MHCalibrationBlindPixel.[h,cc]:
+     - force mu_{0} in Blind Pixel Fit to be around 0 in fKPoisson4
+     - implement combined Polya fit and Michele's back-scattered electron
+       fit 
+
+   * mcalib/MHCalibrationPixel.[h,cc], mcalib/MCalibrationPix.cc,
+     mcalib/MCalibrationPINDiode.cc:
+     - combine FitChargeHiGain and FitChargeLoGain into one function
+
+   * macros/calibration.C
+     - improve double gauss fit a bit
+
+
+
+ 2004/01/26: Thomas Bretz
+
+   * mraw/MRawEvtPixelIter.[h,cc]:
+     - removed member function GetNumPixels. For more details see mantis.
+
+   * manalysis/MArrivalTime.[h,cc]:
+     - reorganized includes
+     - fixed InitSize and ClearArray (now Reset) to fit MParContainer
+       definition
+     - for the moment removed usage of fPixelChecked - THIS WILL CRASH YOUR
+       PROGRAM
+
+   * manalysis/MArrivalTimeCalc.[h,cc]:
+     - reorganized includes
+     - removed many obsolete code, exspecially copy&paste relicts!
+     - fixed usage of InitSize
+     - removed CleanArray. Reset() is called automatically before Process()
+
+   * manalysis/MExtractedSignalCam.[h,cc]:
+     - added SetLogStream
+     - removed obsolete include MGeomCam
+     - replaced PrintOut by Print
+     - added const-qualifiers to all Getters
+     - fixed documentation
+     
+   * manalysis/MExtractedSignalPix.[h,cc]:
+     - replaced PrintOut by Print
+     - fixed documentation
+
+   * manalysis/MEventRateCalc.cc, manalysis/MPedCalcPedRun.cc:
+     - replaced memset by Reset()
+
+
+
+ 2004/01/24: Abelardo Moralejo
+
+   * macros/starmcstereo.C
+     - Added. Example of how to run the analysis chain for MC files
+       containing simulation of stereo systems of 2 telescopes.
+
+   * mcalib/MCalibrate.cc
+     - Added check that value of signal from MExtractedSignalPix is not
+       the default (error) value. In such a case, the signal in 
+       MCerPhotEvt is now set to 0. Before, all pixels got very high
+       values in MCerPhotEvt in case the MRawEvtData object for the
+       event was missing in the file. This happened in MC files, in 
+       which in some circumstances an event is written without the
+       pixel information (for instance, when running stereo simulations
+       the pixel data is missing for non-triggered telescopes, but the
+       event headers are present).
+
+
+
+ 2004/01/23: Markus Gaug
+
+   * manalysis/MExtractSignal.[h,cc], manalysis/MExtractedSignalPix.[h,cc],
+     manalysis/MArrivalTime.[h,cc], mcalib/MCalibrationBlindPix.h,
+     mcalib/MHCalibrationBlindPixel.[h,cc], mcalib/MCalibrationPINDiode.h,
+     mcalib/MHCalibrationPINDiode.[h,cc], mcalib/MCalibrationPix.[h,cc],
+     mcalib/MHCalibrationPixel.[h,cc], mcalib/MCalibrationCalc.[h,cc]:
+     - use MArrivalTime for Storage (or calculation) of time
+       in MExtractSignal
+     - pass from TH1I histos to TH1F for times
+
+   * mcalib/MCalibrationBlindPix.h, mcalib/MHCalibrationBlindPixel.[h,cc],
+     mcalib/MCalibrationPix.[h,cc], mcalib/MHCalibrationPixel.[h,cc],
+     mcalib/MCalibrationCalc.[h,cc]:
+     - clean up  setters 
+     - pass to bit-fields for all flags
+
+   * mcalib/MCalibrationCam.cc
+     - exclude Blind Pixel from Camera display
+     - do not fill &val when return kFALSE
+
+   * macros/calibration.C
+     - include functions to exclude the blind pixel, 
+       calculation of times and quality checks
+
+
+
+ 2004/01/23: Abelardo Moralejo
+
+   * mcalib/MCalibrate.cc, manalysis/MExtractSignal.cc
+     - Added support (using AddSerialNumber) for stereo MC files.
+
+
+
+ 2004/01/23: Thomas Bretz
+
+   * mbase/MAstro.cc:
+     - Fixed calculation of MJD. In Ymd2Mjd a plus should be a minus.
+
+   * mreport/MReport*.[h,cc]:
+     - changed all classes to return Int_t instead of Bool_t in 
+       InterpreteBody
+     - changed MReportFileRead such, that a wrong line results in
+       skipping the line instead of abort reading.
+
+   * manalysis/MExtractSignal.cc:
+     - do not print information for each pixel - it's too much.
+     
+   * mbase/MStatusDisplay.cc:
+     - when reading a status display do not display tabs with
+       the same name than one which is already existing.
+       
+   * mcalib/MCalibrate.cc:
+     - directly store pointer to pixel when setting saturation flag
+     
+   * mcamera/MCameraDC.cc:
+     - fixed some comments
+     
+   * mhist/MHCamEvent.cc:
+     - fixed a crash when no geometry was available
+
+   * mhist/MHCamera.[h,cc]:
+     - removed obsolete member function SetPix
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added EventInfo member function
+     - implemented preliminary redirection of GetObjectInfo to
+       StatusLine2 -> An own status line for this is missing
+
+   * manalysis/MExtractSignal.[h,cc]:
+     - implemented StreamPrimitive
+     - changed deafults to be static const data members
+     
+   * manalysis/MGeomApply.[h,cc]:
+     - implemented StreamPrimitive
+
+
+
+ 2004/01/23: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.[h,cc] 
+     - Added check to guarantee that the FADC simulation parameters of
+       all read files (those used for calibration and those analyzed) 
+       are the same.
+     - Added missing support for analysis of stereo files.
+
+   * mcalib/MMcCalibrationCalc.cc
+     - Removed obsolete FIXME comment.
+     - Added missing support for analysis of stereo files.
+
+
+ 2004/01/23: Raquel de los Reyes
+
+   * macros/CCDataCheck.C
+     - Added the temperature distribution of the optical links
+       and the plots of the LV power supplies.
+   * mcamera/MCameraLV.h
+     - Added the "Get" functions to access the private data 
+       members of the class.
+
+
+ 2004/01/22: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Now ratio of high to low gain is taken from MCalibrationCam if
+       it existed previously in the parameter list, instead of being
+       read again from the MMcFadcHeader. Removed Setter function for
+       fADC2PhInner, no longer necessary. Fixed error regarding the 
+       pedestal conversion to photons (did not read conversion factor
+       from preexisting MCalibrationCam object).
+
+   * mcalib/MMcCalibrationCalc.cc
+     - Changed parameters of the histogram, and also the quantity being 
+       histogrammed. Check that input data come from a noiseless camera
+       file before proceeding to do the calibration. Introduced lower
+       size in cut for calibration. Now rhe calibration constant is not
+       calculated from the mean of photons/ADC counts, but from the peak
+       of the histogram.
+
+   * macros/starmc.C
+     - Introduced new scheme. Now there are two loops over two different
+       sets of files. First loop calculates the calibration constants,
+       second one does the analysis. Introduced comments. Now the 
+       histogram used in the light calibration is written to the output
+       file.
+
+
+
+ 2004/01/22: Thomas Bretz
+
+   * mcalib/MCalibrate.[h,cc], mcalib/MCalibrationCam.[h,cc],
+     mcalib/MCalibrationBlindPix.[h,cc], mcalib/MCalibrationCalc.[h,cc],
+     mcalib/MCalibrationPix.[h,cc], mcalib/MCalibrationPINDiode.[h,cc],
+     mcalib/MCalibrationBlindPixel.[h,cc], 
+     mcalib/MHCalibrationPixel.[h,cc], mcalib/MMcCalibrationCalc.[h,cc],
+     mcalib/MHCalibrationBlindPixel.[h,cc], 
+     mcalib/MHCalibrationPINDiode.[h,cc]:
+     - cleaned up includes
+
+
+
+ 2004/01/22: Raquel de los Reyes
+
+   * macros/CCDataCheck.C
+     - macro to check the data from the central control (.rep files).
+
+
+
+ 2004/01/22: Markus Gaug
+
+   * macros/calibration.C
+     - made MStatusDisplay 3 bit smaller
+
+   * manalysis/MExtractSignal.cc
+     - put fSignals->SetUsedFADCSlices into PreProcess
+
+   * manalysis/MPedCalcPedRun.cc
+     - calculate PedRMS as RMS of the sums, later renormalized to units 
+       of RMS/slice (eliminate the wrong effect of odd and even slices)
+
+   * mcalib/MCalibrationCalc.cc
+     - if bit SkipBlindPixelFit is set, now number of photons outside 
+       plexiglass is not intended to be calculated any more (previous
+       bug)
+     - exclude excluded pixels in eventloop
+	
+   * mcalib/MHCalibrationBlindPixel.[h,cc]
+     - move functions to pointer again (otherwise, Clone will give 
+       strange results)
+
+
+
+ 2004/01/21: Abelardo Moralejo
+
+   * mcalib/MMcCalibrationCalc.[h,cc]
+     - Added. First version of the task intended to calculate the
+       conversion factors from ADC counts to photons in the MC. It has
+       a different aim than the recently renamed class 
+       "MMcCalibrationUpdate" (which takes care that the correct 
+       pedestals and conversion factors are supplied to each event, but 
+       does not really calculate anything).
+
+   * mcalib/Makefile, CalibLinkDef.h
+     - Added new class MMcCalibrationCalc
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Now the container MCalibrationCam is not created or modified if
+       it is found that one such container already exists in the 
+       Parameter list (from a previous calibration).
+
+
+
+ 2004/01/21: Thomas Bretz
+
+   * mraw/MRawRead.cc:
+     - restore the fake time for all runs (current time stamp in
+       the data seems to be toally nonsense)
+ 
+   * mraw/MRawEvtHeader.cc:
+     - removed decoding of real time (current time stamp in the data
+       seems to be toally nonsense)
+
+
+
+ 2004/01/21: Abelardo Moralejo
+
+   * mmc/MMcEvt.hxx
+     - Uncommented 6 Getter functions (those regarding the number of 
+       photons surviving the different stages of simulation).
+
+   * manalysis/MMcCalibrationUpdate.[h,cc]
+     - Added (see below).
+
+   * manalysis/MMcCalibrationCalc.[h,cc]
+     - Removed: changed name of this class to MMcCalibrationUpdate, 
+       which is more representative of what it really does. Moved 
+       the filling of the MCalibrationCam container from Process to 
+       ReInit, since it does not change on an event by event basis.
+       Simplified PreProcess (MCalibrationCam was searched for twice).
+       Updated class description and comments.
+
+   * manalysis/Makefile, AnalysisLinkDef.h
+     - Adapted to change above
+
+   * macros/starmc.C
+     - Adapted to change above. Changed also task instance name from 
+       mccalibcalc to mccalibupdate.
+
+
+
+ 2004/01/21: Raquel de los Reyes
+
+   * mreport/MReportCC.h, mreport/MReportTrigger.h, mcamera/MCameraHV.h 
+     and mcamera/MCameraCalibration.h
+     - Added the "Get" functions (e.g GetStatus() for fStatus) to access 
+       the private data members of the class.
+
+
+
+ 2004/01/20: Thomas Hengstebeck
+
+   * mranforest/MRanForestCalc.[h,cc]
+     - Added member functions Grow (training of RF) and Fill (reading in
+       trained forest from file) which simplify macros. 
+       One just needs to call them instead of using MRanForestGrow and 
+       MRanForestFill (and the related training and fill loops) in a
+       macro.
+
+
+
+ 2004/01/20: Abelardo moralejo
+
+   * manalysis/MMcCalibrationCalc.cc
+     - removed call to MCalibrationPix::SetPedestal, which was not 
+       needed.
+
+
+
+ 2004/01/20: Thomas Bretz
+
+   * Makefile:
+     - replaced 'make' by '$(MAKE)'
+     
+   * Makefile.rules:
+     - added Makefile itself to dependencies
+     
+   * mbase/MTask.cc:
+     - added comment about ReInit
+
+   * mhbase/MH.cc:
+     - do not clear pad in DrawClone if 'same' option given
+
+   * mhist/MHVsTime.cc:
+     - evaluate 'same' option
+
+   * mfileio/MReadCurrents.[h,cc]:
+     - obsolete, removed
+
+   * manalysis/MCerPhotEvt.cc, manalysis/MCerPhotPix.cc:
+     - added some comments
+
+
+
+ 2004/01/20: Abelardo moralejo
+
+  * mcalib/MHCalibrationPINDiode.cc
+    - Added call to SetDirecory(0) for histograms fHErrCharge, 
+      fHPCharge, fHPTime.
+
+  * manalysis/MCerPhotPix.h: 
+    - Changed position of declaration of fIsSaturated to be the last 
+      private variable. Otherwise, since in the constructor it is 
+      initialized in the last place, a warning is displayed upon
+      compilation in some systems.
+
+
+
+ 2004/01/20: Markus Gaug
+  * mcalib/Makefile, manalysis/Makefile:
+    - include directory ../mtools
+ 
+  * mtools/MFFT.[h,cc]
+    - class inherits from TObject now
+
+
+
+ 2004/01/19: Markus Gaug
+
+  * mcalib/MHCalibrationBlindPixel.[h,cc]
+    - fixed a bug in fFitLegend due to which program crashed by calls 
+      to DrawClone
+    - Modified way to change the fit function
+
+  * mcalib/MHCalibrationPixel.[h,cc]
+    - reordered function calls
+    - removed SetupFill
+
+  * mcalib/MHCalibrationPINDiode.h
+    - reordered function calls
+
+  * mcalib/MCalibrationPix.[h,cc]
+    - limits to define fFitValid now as variables in class
+
+  * mcalib/MCalibrationCam.[h,cc]
+    - reordered function calls
+    - incorporate option to exclude pixels 
+
+  * mcalib/MCalibrationBlindPix.h
+    - Modified way to change the fit function
+
+  * mcalib/MCalibrationCalc.[h,cc]
+    - Modified way to change the fit function
+    - incorporate option to exclude pixels from configuration file
+
+  * macros/calibration.C
+    - Modified way to change the fit function
+    - incorporate option to exclude pixels from configuration file
+
+
+
+ 2004/01/19: Javier Rico
+
+   * manalysis/MPedCalcPedRun.cc, manalysis/MPedPhotCalc.cc
+     - Added documentation of member functions
+
+
+
+ 2004/01/19: Abelardo Moralejo
+
+   * manalysis/MCerPhotPix.[h,cc]
+     - Added fIsSaturated to flag whether low gain of the pixel is
+       saturated. Added corresponding getter and setter functions.
+       Updated ClassDef to version 2.
+
+   * mcalib/MCalibrate.cc
+     - Set the new saturation flag of MCerPhotPix to kTRUE if at least 
+       one low gain FADC slice is saturated.
+
+   * mimage/MNewImagePar.[h,cc]
+     - Added new member variable fNumSaturatedPixels to count how many
+       pixels were saturated. Updated ClassDef to version 2.
+
+
+
+ 2004/01/19: Thomas Bretz
+
+   * manalysis/MPedPhotCalc.[cc,h]:
+     - fixed order of includes
+     - removed obsolete forward declarations
+     - removed obsolete data member fNumPixels (stored already twice in
+       the two TArrayF)
+     - fixed some small bugs in the documentation
+
+   * manalysis/MPedCalcPedRun.cc:
+     - updated my eMail address
+
+
+
+ 2004/01/19: Javier Rico
+
+   * macros/dohtml.C, NEWS
+     - include some missing info
+
+
+
+ 2004/01/19: Abelardo Moralejo
+
+   * manalysis/MExtractedSignalPix.h
+     - added GetNumLoGainSaturated()
+
+
+
+ 2004/01/19: Markus Gaug
+
+   * macros/dohtml.C
+     - include calibration.C
+	
+   * manalysis/MExtractSignal.cc
+     - warning of logain saturation now only once per event (out of loop)
+
+   * mcalib/MCalibrationCalc.cc, mcalib/MCalibrationPix.[h,cc]
+     - new Flag fExcluded to indicate if pixel has been excluded from 
+       further analysis
+
+
+
+ 2004/01/16: Javier Rico & Pepe Flix
+
+   * manalysis/MPedPhotCalc.[cc,h]
+     - added
+     - new class for the evaluation of pedestals in units of photons
+       using the extracted signal from pedestal runs and calibration
+       constants defined in MCalibrate
+
+   * manalysis/AnalysisLinkDef.h,  manalysis/Makefile
+     - added entries for MPedPhotCalc
+
+   * macros/pedphotcalc.C
+     - added
+     - example on how to use MPedPhotCalc task
+
+
+
+ 2004/01/16: Markus Gaug
+
+   * mcalib/MCalibrationFits.h 
+     - removed and incorporated in MHCalibrationBlindPixel.h
+
+   * mcalib/MHCalibrationBlindPixel.[h,cc], mcalib/MHCalibrationConfig.h,
+     mcalib/MCalibrationBlindPix.h:
+     - incorporate Fit functions
+     - fixed a bug due to which DrawClone crashed when class was used 
+       in a compiled macro
+
+   * mcalib/MCalibrationCalc.cc, mcalib/MCalibrationPix.cc,
+     mcalib/MCalibrationBlindPix.cc, mcalib/MCalibrationPINDiode.cc,
+     mcalib/MCalibrationCam.cc, mcalib/MHCalibrationBlindPixel.cc,
+     mcalib/MHCalibrationPixel.cc:
+     - fixed the warns and errs in fLog's
+
+
+
+ 2004/01/16: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationCalc.cc
+     - TMath::Max() is no longer used because it did not compile in some 
+       systems for unkown reasons. I replaced it by a safer (and may be 
+       slower) code.
+     - Added calpix.SetFitValid();
+
+   * mhist/MHEvent.cc
+     - In MHEvent::Fill, fixed: second parameter of SetCamContent must 
+       be 1 in case of RMS:
+        case kEvtPedestalRMS:
+           fHist->SetCamContent(*(MCamEvent*)par, 1);
+
+
+
+ 2004/01/15: Abelardo Moralejo
+
+   * macros/starmc.C
+     - Added. Version of star showing new chain to get Hillas 
+       parameters (with Size calibrated in photons) from MC files.
+
+
+
+ 2004/01/15: Javier Rico
+	
+   * manalysis/MPedCalcPedRun.[h,cc]
+     - optimize the running time
+     - add (some) documentation
+     - correct treatment for the case of several input files 
+
+   * macros/pedvsevent.C
+     - added
+     - draw pedestal mean and rms vs event# for input pixel# and run 
+       file, and compares them to the global pedestal mean and rms 
+
+
+
+ 2004/01/15: Raquel de los Reyes
+
+   * mhist/MHCamEvent.cc, mhist/MHCamera.cc
+     - changed the MHCamEvent::SetupFill and MHCamera::GetBinError
+       functions to compute the estimation of the error of the
+       mean. It can be done calling to the function
+       MCamEvent::SetBit(MHCamera::kVariance) in the macro
+
+
+
+ 2004/01/15: Markus Gaug
+
+   * mhist/MHCamera.[h,cc]
+     - incorporate Thomas's changes
+     - replace void CreateProjection() by TH1D *Projection(const char*)
+
+   * macros/calibration.C
+     - replace MHCamera->Draw("proj") by MHCamera->Projection()
+     - produce better fits to the projection
+
+   * manalysis/MSimulatedAnnealing.[h,cc], 
+     mhist/MHSimulatedAnnealing.[h,cc]:
+     - moved to directory mtools
+     - MSimulatedAnnealing now inherits from TObject
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h,
+     mhist/Makefile, mhist/HistLinkDef.h:
+     - removed MSimulatedAnnealing
+     - removed MHSimulatedAnnealing
+
+   * mtools/Makefile, mtools/AnalysisLinkDef.h:
+     - added MSimulatedAnnealing
+     - added MHSimulatedAnnealing
+
+
+
+ 2004/01/15: Thomas Bretz
+
+   * manalysis/AnalysisLinkDef.h:
+     - removed MCurrents
+
+   * mhist/MHCamera.[h,cc]:
+     - added member function Projection
+     - removed fYproj
+
+   * mreport/MReport*.*:
+     - added more comments
+
+
+
+ 2004/01/14: Markus Gaug
+  
+   * mtools/MFFT.[h,cc]
+     - new class to perform Fast Fourier Transforms
+
+   * mtools/Makefile
+   * mtools/ToolsLinkDef.h
+     - include MFFT
+
+   * manalysis/MExtractedSignalCam.h
+     - removed variables fNumHiGainSamples and fNumLoGainSamples
+     - function SetNumUsedFADCSlices replaced by SetUsedFADCSlices
+
+   * manalysis/MExtractSignal.cc
+     - updated call to SetUsedFADCSlices
+
+
+
+ 2004/01/14: Abelardo Moralejo
+
+   * manalysis/MMcCalibrationCalc.cc:
+     - set pedestal rms per FADC slice to 0.01 counts in case it is 0.
+       This can happen (depending on camera simulation parameters), and
+       rms = 0 later resulted in the pixel being eliminated in the 
+       image cleaning.
+
+
+
+ 2004/01/14: Thomas Bretz
+
+   * Makefile:
+     - replaced old style Makefile.depend by directory specific
+       dependancy files
+       
+   * Makefile.rules:
+     - changed obsolete '.cc.o' style to newer style '%.o: %.c'
+     - added rule to make dependency files
+     - added rule to remove dependancy files.
+     - added rmdep as prerequisite to clean
+     - include dependency file
+
+   * mbase/Makefile, mcalib/Makefile, mcamera/Makefile,
+     mdata/Makefile, mfileio/Makefile, mfilter/Makefile,
+     mgeom/Makefile, mgui/Makefile, mhbase/Makefile, 
+     mhist/Makefile, mhistmc/Makefile, mimage/Makefile,
+     mmain/Makefile, mmc/Makefile, mmontecarlo/Makefile,
+     mpointing/Makefile, mranforest/Makefile, mraw/Makefile,
+     mreflector/Makefile, mreport/Makefile, mtemp/Makefile,
+     mtools/Makefile:
+     - removed clean-rule, use the one in Makefile.rules instead
+
+   * mreport/Makefile, mreport/ReportLinkDef.h:
+     - added MReportHelp
+
+   * mreport/MReportFileRead.cc:
+     - moved code from MReportHelp to new file
+     - removed usage of MReport class completely
+
+   * mfilter/MFGeomag.[h,cc]:
+     - fixed a bug which causes MFGeomag to fail if MARSSYS is not set
+     - changed the second loop from 0->1151 to 1152->2304
+     - removed dummy arrays used for reading
+     - output filename in case of 'file not found'
+     - removed obsolete data members
+     - removed obsolete Init function
+     - removed forbidden underscore from member variable
+     - changed wrong 0/1 in allocation of fResult into kFALSE/TRUE
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added new member function Open
+     - added new menu entry kFileOpen
+     - changed UpdatePSheader algorithm (the old one was much too slow)
+
+   * manalysis/MCurrents.[h,cc]:
+     - removed (old outdated)
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - removed MCurrents
+
+
+
+ 2004/01/14: Wolfgang Wittek
+
+   * macros/ONOFFAnalysis.C:
+     - current version
+
+   * mhist/MHSigmaTheta.[h,cc]:
+     - replace MPedestalCam by MPedPhotCam
+
+   * manalysis/MPad.[h,cc], manalysus/MSigmabar.[h,cc],
+     manalysus/MSigmabarCalc.[h,cc], manalysus/MCT1PadONOFF.[h,cc],
+     manalysus/MCT1PadSchweizer.[h,cc], manalysus/MPadding.[h,cc]:
+     - replace MPedestalCam by MPedPhotCam
+
+   * manalysis/MPedPhotPix.[h,cc]
+     - uncomment SetRms()
+
+
+
+ 2004/01/13: Markus Gaug
+ 
+   * manalysis/MExtractSignal.h
+     - seems that the reduced light intensity of the CT1 Pulser
+       results in broader pulses -> Set Default time slices to [3,10]
+
+   * mhist/MHCamera.cc
+     - make Stat Window in option 'proj' bigger
+     - add comment line at beginning of Draw()
+
+   * mcalib/MHCalibrationBlindPixel.[h.cc]
+     - add Function DrawClone()
+     - fix bug in calculation of integral (GetIntegral("width"))
+     - restrict parameters tighter
+     - declare fit as not valid, if less than 100 events 
+       in single photo-electron peak
+
+   * mcalib/MCalibrationFits.h, mcalib/MHCalibrationBlindPixel.[h.cc]
+     - fit now with fixed normalization
+
+   * mcalib/MHCalibrationPixel.[h.cc]
+     - new function IsEmpty()
+     - Time fit accepted if ChiSquare less than 30. (instead of 20.)
+
+   * mcalib/MCalibrationPix.[h.cc]
+     - F-Factor corrected and added error
+     - Histograms not fitted if they are empty
+     - rejection criteria of fitted charges now > 5 PedRMS (instead 3)
+
+   * mcalib/MCalibrationCam.cc
+     - Square Root of Reduced Sigmas not taken, if they are < 0.
+     - Reduced Sigma / Charge squared replaced by reduced sigma / charge
+
+   * mcalib/MCalibrationCalc.cc
+     - Blind Pixel is not additionally treated as normal pixel any more
+     - Blind Pixel Draw replaced by DrawClone
+
+   * macros/calibration.C
+     - took out some unused code
+     - some default axis labelling corrected
+
+
+
+ 2004/01/13: Abelardo Moralejo
+
+   * manalysis/MMcPedestalCopy.cc
+     - added check of whether input file is a MC file before executing 
+       the PreProcess.
+
+
+
+ 2004/01/13: Wolfgang Wittek
+
+   * macros/ONOFFAnalysis.C, macros/ONAnalysis.C:
+     - change macro to handle also MC events with finite sigmabar
+
+   * manalysis/MPadOn.[h,cc]:
+     - deleted, is replaced by MPad
+
+   * manalysis/MPadOnOFF.[h,cc]:
+     - deleted, is replaced by MPad
+
+   * manalysis/MPad.[h,cc]:
+     - new class, replacing MPadON and MPadONOFF
+     - handle also MC events with finite sigmabar
+
+   * manalysis/Makefile, manalysis/AnalysisLinkDef.h:
+     - replace MPadON and MPadONOFF by MPad
+
+
+
+ 2004/01/13: Thomas Bretz
+
+   * mraw/MRawRunHeader.[h,cc]:
+     - implemented new member function GetRunTypeStr
+
+   * Changelog.03: 
+     - added (contains entries of 2003)
+
+   * Changelog:
+     - removed entries of 2003
+
+   * mfilter/MFGeomag.cc:
+     - simplified open/close of input files
+
+   * manalysis/MEventRate.[h,cc], manalysis/MEventRateCalc.cc:
+     - added some comments
+     - added new member function GetError
+
+   * Makefile:
+     - updated 'make dox' output for convinience
+
+   * macros/dohtml.C:
+     - do not print Info's
+     - added mcamera
+     - added mpointing
+     - added mreport
+
+   * mreport/MReportCurrents.cc, mreport/MReportDAQ.cc:
+     - removed some obsolete comments (these comments confused THtml)
+
+   * manalysis/MCameraData.[h,cc], mfileio/MCT1ReadAscii.[h,cc],
+     mfileio/MCT1ReadPreProc.[h,cc], mfilter/MFCT1SelBasic.cc,
+     mfilter/MFSelBasic.cc, mhist/MHCamera.cc, mhist/MHEvent.[h,cc],
+     mimage/MImgCleanStd.[h,cc], mimage/MImgCleanTGB.[h,cc],
+     mmain/MAnalysis.cc, mmain/MEventDisplay.cc:
+     - replaced MPedestalCam by MPedPhotCam
+     - removed some obsolete includes
+
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MLogPlugin
+     - added MLogHtml
+
+   * mbase/MLog.[h,cc]:
+     - added use of plugins
+
+   * mbase/MLogPlugin.[h,cc], mbase/MLogHtml.[h,cc]:
+     - added
+
+   * mbase/MStatusDisplay.[h,cc]:
+     - added a Save-As dialog
+
+
+
+ 2004/01/12: Thomas Bretz
+
+   * macros/rootlogon.C:
+     - added mcamera to include path
+     - added mpointing to include path
+     - added mreport to include path
+     
+   * mbase/MLog.cc:
+     - updated my eMail address
+     
+   * mbase/MParContainer.h:
+     - added Read member function
+     
+   * mbase/MStatusDisplay.[h,cc]:
+     - changed size of ps-paper
+     - added a user defined bottom line to the ps-files
+     - added name (currently unused)
+     - added title (used as possible bottom line in ps-file)
+     
+   * mraw/MRawRunHeader.cc:
+     - added some comments
+
+   * status.cc:
+     - set name of input as bottom line of status display
+
+
+
+ 2004/01/12: Abelardo Moralejo
+
+   * mimage/MStereoPar.cc
+     - fixed mistake: now fSourceY = scale1*hillas1.GetMeanY() + ...
+       instead of         fSourceY = scale2*hillas1.GetMeanY() + ...
+       Bug had no effect unless scale1 != scale2 (-> telescopes of 
+       different size).
+
+
+
+ 2004/01/12: Markus Gaug
+
+   * manalysis/MExtractSignal.[h,cc]
+     - take out some uncommented code 
+     - replace logainshift by two independent variables: 
+       logainfirst, logainlast
+     - because in most data, maximum occurs in slice 4, shift default 
+       from slices 4-9 to slices 3-8.
+
+   * manalysis/MExtractedSignalPix.[h,cc]
+     - took out some uncommented code
+     - new initializers: instead of -1. now 99999.9
+
+
+
+ 2004/01/09: Markus Gaug
+
+   * mcalib/MCalibrationCam.[h,cc]
+     - take out 1-dim histos because we can use 
+       the projections in MHCamera (s.b.)
+
+   * mcalib/MHCalibrationBlindPixel.h
+     - make the fit by default quiet
+
+   * mcalib/MHCalibrationPixel.[h,cc]
+   * mcalib/MCalibrationPix.[h,cc]
+     - Ranges of time slices stored independently for HiGain and LoGain
+       in order to allow consecutive checks
+
+   * mhist/MHCamera.[h.cc]
+     - add the possibility to call a Draw("proj") which will 
+       draw a Y-Projection of the histogram
+
+   * macros/calibration.C
+     - apply the drawing of the projections and fit them
+
+   * mcalib/MCalibrationCalc.cc
+     - catch the possibility of a calibration file, 
+       unintendedly being a pedestal or cosmic file. 
+       Program now exits with an error before doing the fits
+
+   * mcalib/MCalibrationPix.[h,cc]
+     - fixed a bug in calculation of fFitValid. 
+       before, a call to IsFitValid() always returned false
+
+
+
+ 2004/01/09: Javier Lpez
+
+   * macros/bootcampstandardanalysis.C
+     - added new macro that holds the main scheleton discussed in the 
+       december bootcamp in Wuerzburg. It runs first over a pedestal
+       run, then over a calibration run, again over the pedestal run
+       to compute de pedestal in number of photons and finally over a
+       data run to calibrate the data.
+
+
+
+ 2004/01/06: Sebastian Raducci
+   
+   * manalysis/MArrivalTime.[h,cc]
+     - added new method to calculate photon arrival times. It uses the
+       TSpline5 Root Class to interpolate the Fadc Slices. The time is
+       the abscissa value of the absolute maximum of the interpolation
+     - added new method to find clusters with similar arrival times.
+       For now it's a preliminary version. It simply search for adiacent
+       pixels having the same arrival time (color).
+
+   * manalysis/MArrivalTimeCalc.[h,cc]
+     - modified the Process() method according to the changes in the
+       Arrival Time Cointainer
+
+   * mmain/MEventDisplay.cc
+     - added new tab in the camera event display to show the arrival
+       time. This arrival time is calculated with the spline method
+     - the old Arrival Time pad now it's called Max Slice Idx, because
+       it's only the index of the slice with the max content.
+   
+   * mhist/MHEvent.[h,cc]
+     - added new fType in te enumeration to handle the arrival time
+       histos
Index: /tags/Mars-V0.9/MIncl.h
===================================================================
--- /tags/Mars-V0.9/MIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/MIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/MLinkDef.h
===================================================================
--- /tags/Mars-V0.9/MLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/MLinkDef.h	(revision 9772)
@@ -0,0 +1,7 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#endif
Index: /tags/Mars-V0.9/Makefile
===================================================================
--- /tags/Mars-V0.9/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/Makefile	(revision 9772)
@@ -0,0 +1,154 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+# @maintitle
+
+# @code
+
+#
+#  please change all system depend values in the 
+#  config.mk.${OSTYPE} file 
+#
+#
+include Makefile.conf.$(OSTYPE)
+include Makefile.conf.general
+
+#
+#PROGRAMS = readraw merpp mars test mona status
+PROGRAMS = readdaq merpp readraw sinope callisto star ganymed showlog showplot mars
+SOLIB    = libmars.so
+CINT     = M
+
+#
+#  connect the include files defined in the config.mk file
+#
+#    WARNING: the result (whether the linkage works or not) depends on the
+#             order of the libraries. It seems, that the most base library
+#             must be the last one
+#
+
+#
+#  ----->>>   mars libraries
+#
+SUBDIRS = mbase \
+	  mastro \
+	  mmain \
+          mfbase \
+          mfilter \
+          mdata \
+          mhbase \
+          mhvstime \
+          mhist \
+          manalysis \
+          msignal \
+          mbadpixels \
+          mhcalib \
+          mhflux \
+	  mcalib \
+          mpedestal \
+          mfileio \
+          mreflector \
+          mgeom \
+          msql \
+          mimage \
+          mmontecarlo \
+          mhft \
+          mmc \
+          mraw \
+          mcamera \
+	  mtrigger \
+          mpointing \
+          mreport \
+          mgui \
+          mranforest \
+          mhistmc \
+          mjobs \
+          mtools \
+	  mstarcam
+
+#LIBRARIES = $(SUBDIRS:%=lib/lib%.a)
+LIBRARIES = $(SUBDIRS:=.a)
+MRPROPERS = $(SUBDIRS:=.mrproper)
+CLEANERS  = $(SUBDIRS:=.clean)
+LIBS      = $(SOLIB)
+
+#------------------------------------------------------------------------------
+.SUFFIXES: .c .cc .h .o 
+
+SRCFILES = 
+
+############################################################
+all: $(SOLIB) $(PROGRAMS)
+	@echo " Done. "
+	@echo " "
+
+static: LIBS=$(SUBDIRS:=/*.o) $(OBJS)
+#static: rmlib $(LIBRARIES) $(PROGRAMS)
+static: $(LIBRARIES) $(PROGRAMS)
+	@echo " Done. "
+	@echo " "
+
+include Makefile.rules
+
+#
+# Use $(CXX) -v ... for a more verbose output
+#
+# ROOTGLIBS must be there - why? How can I link the libraries?
+$(SOLIB): $(LIBRARIES) $(OBJS) $(HEADERS)
+	@echo " Linking shared object $(SOLIB) ..."
+	$(CXX) $(CXXFLAGS) $(SOFLAG) $(OBJS) $(SUBDIRS:=/*.o) $(ROOTGLIBS) -o $@
+
+# This is a special workaround to create the shared object (bundle, plugin)
+# for root and the dynlib (to be linked with the executable) on Mac OSX
+ifneq ($(OSTYPE),darwin)
+$(PROGRAMS): $(SOLIB) $(PROGRAMS:=.o)
+	@echo " Linking $@ ..." 
+	$(CXX) $(CXXFLAGS) $(ROOTGLIBS) $(SOLIB) $@.o $(MARS_LIB) -o $@
+
+# Use this to link the programs statically - for gprof
+#$(PROGRAMS): $(OBJS) $(HEADERS) $(PROGRAMS:=.o)
+#	@echo " Linking $@ ..." 
+#	$(CXX) $(CXXFLAGS) $(ROOTGLIBS) $(OBJS) $(SUBDIRS:=/*.o) $@.o $(MARS_LIB) -o $@
+else
+$(DYLIB): $(LIBRARIES) $(OBJS) $(HEADERS)
+	@echo " Linking dylib $(DYLIB) ..."
+	$(CXX) $(CXXFLAGS) $(DYFLAG) $(OBJS) $(SUBDIRS:=/*.o) $(ROOTGLIBS) -o $@
+
+$(PROGRAMS): $(DYLIB) $(PROGRAMS:=.o)
+	@echo " Linking mac executable $@ ..." 
+	$(CXX) $(CXXFLAGS) $(ROOTGLIBS) $(DYLIB) $@.o $(MARS_LIB) -o $@
+endif
+
+dox: $(SOLIB)
+	@echo
+	@echo " Creating html documentation and logfile dohtml.log..."
+	rm -f dohtml.log
+	root -b -q dohtml.C 2>&1 >> dohtml.log | tee -a dohtml.log
+	@echo " done."
+	@echo
+
+#clean:	rmcint rmobjs rmdep rmcore rmlib
+
+mrproper:	$(MRPROPERS) rmbin rmbak rmbakmac rmhtml clean
+	@echo " Done."
+	@echo " "
+
+tar:	mrproper
+	@echo "Making tar-file"
+	root -b -q -l -n tar.C
+#	@tar cvf ../mars.tar --exclude=Root .rootrc *
+#	@gzip -9 ../mars.tar
+
+#Makefile.depend:
+#	(! find ./ Makefile.depend -maxdepth 1 -empty 2> /dev/null && \
+#	echo " Generating dependancies into Makefile.depend" && \
+#	makedepend -- $(INCLUDES) -- $(PROGRAMS:=.cc) $(SRCS) $(SUBDIRS:=/*.cc) -w1024 -f- 2> /dev/null | grep -v Cint | grep -v "/usr/" > Makefile.depend && \
+#	echo " ") || find -maxdepth 0 -true > /dev/null
+#
+#depend:	Makefile.depend	
+
+# @endcode
Index: /tags/Mars-V0.9/Makefile.conf.darwin
===================================================================
--- /tags/Mars-V0.9/Makefile.conf.darwin	(revision 9772)
+++ /tags/Mars-V0.9/Makefile.conf.darwin	(revision 9772)
@@ -0,0 +1,48 @@
+##################################################################
+#
+# config.mk
+#
+# @file        config.mk
+# 
+##################################################################
+# @maintitle
+
+# @code
+
+# compilers
+
+CC       = gcc
+CXX      = g++
+F77      = f77
+AR       = ar -src
+
+#
+#  ----->>>   settings for compilation
+#
+OPTIM    = -O5 -Wall -fno-exceptions -fPIC -Wpointer-arith -Wcast-align -Wconversion -Wstrict-prototypes -Wmissing-prototypes -Woverloaded-virtual
+# ggc 3.2: removed -fnonnull-objects -Wtraditional -Wnested-externs
+DEBUG    = 
+ARCHDEF  = -D__LINUX__
+
+# For Mac OSX we need to kind of shared objects. One which can be plugged
+# into root (bundle) and one which can be linked to the executables (dynlib)
+SOFLAG   = -bundle -flat_namespace -Xlinker -bind_at_load
+DYFLAG   = -dynamiclib -single_module -flat_namespace
+
+DYLIB    = $(SOLIB:.so=.dylib)
+
+# For debugging information use '-g'
+# For producing gmon.out use    '-pg'
+
+#MARS_LIB = -Llib $(SUBDIRS:%=-l%) $(MARSLIBS)
+MARS_LIB = -Llib $(MARSLIBS)
+INCLUDES = -I. $(SUBDIRS:%=-I%)
+
+# uncomment this for quiet compilation
+
+.SILENT:
+
+# @endcode
+##EOF
+
+
Index: /tags/Mars-V0.9/Makefile.conf.general
===================================================================
--- /tags/Mars-V0.9/Makefile.conf.general	(revision 9772)
+++ /tags/Mars-V0.9/Makefile.conf.general	(revision 9772)
@@ -0,0 +1,27 @@
+#
+#  ----->>>   root libraries
+#
+
+ROOTVER    =  `root-config --version`
+ROOTLIBS   =  `root-config --libs` -lMinuit -lHistPainter -lThread
+ROOTGLIBS  =  `root-config --glibs` -lMinuit -lHistPainter -lThread
+ROOTCFLAGS =  `root-config --cflags`
+
+#
+#  compiler flags
+#
+
+#
+# You can use this flags to further costumize compilation:
+#   export MARSDEFINES="-DHAVE_DARKBACKGROUND -DHAVE_XPM"
+#   export MARSFLAGS=
+#   export MARSLIBS="-lX11 -lXpm -L/usr/X11R6/lib"
+#
+DEFINES	 = -DMARSVER=\"0.9\" -D__MARS__ -DROOTVER=\"$(ROOTVER)\" $(ARCHDEF) $(MARSDEFINES)
+
+CXXFLAGS = $(ROOTCFLAGS) $(INCLUDES) $(OPTIM) $(DEBUG) $(DEFINES)
+CFLAGS   = $(CXXFLAGS) $(MARSFLAGS)
+FFLAGS   = $(CXXFLAGS)
+
+HEADERS  = $($(subst .cxx,.cc,SRCFILES):.cc=.h)
+OBJS     = $($(subst .cxx,.cc,SRCFILES):.cc=.o) $(CINT)Cint.o
Index: /tags/Mars-V0.9/Makefile.conf.linux
===================================================================
--- /tags/Mars-V0.9/Makefile.conf.linux	(revision 9772)
+++ /tags/Mars-V0.9/Makefile.conf.linux	(revision 9772)
@@ -0,0 +1,34 @@
+##################################################################
+#
+# config.mk
+#
+# @file        config.mk
+# 
+##################################################################
+
+# compilers
+
+CC       = gcc
+CXX      = g++
+F77      = f77
+AR       = ar -rc
+
+#
+#  ----->>>   settings for compilation
+#
+OPTIM    = -O5 -Wall -fno-exceptions -fPIC -Wpointer-arith -Wcast-align -Wconversion -Wstrict-prototypes -Wmissing-prototypes -Woverloaded-virtual
+# ggc 3.2: removed -fnonnull-objects -Wtraditional -Wnested-externs
+DEBUG    = 
+ARCHDEF  = -D__LINUX__
+SOFLAG   = -shared
+
+# For debugging information use '-g'
+# For producing gmon.out use    '-pg' (needs static linking)
+
+#MARS_LIB = -Llib $(SUBDIRS:%=-l%) $(MARSLIBS)
+MARS_LIB = -Llib $(MARSLIBS)
+INCLUDES = -I. $(SUBDIRS:%=-I%)
+
+# uncomment this for quiet compilation
+
+.SILENT:
Index: /tags/Mars-V0.9/Makefile.conf.linux-gnu
===================================================================
--- /tags/Mars-V0.9/Makefile.conf.linux-gnu	(revision 9772)
+++ /tags/Mars-V0.9/Makefile.conf.linux-gnu	(revision 9772)
@@ -0,0 +1,45 @@
+##################################################################
+#
+# config.mk
+#
+# @file        config.mk
+# 
+##################################################################
+# @maintitle
+
+# @code
+
+# compilers
+
+CC       = gcc
+CXX      = g++
+F77      = f77
+AR       = ar -rc
+#
+#  ----->>>   settings for compilation
+#
+
+OPTIM    = -O5 -Wall -fno-rtti -fnonnull-objects -fno-exceptions -fPIC -Wtraditional -Wpointer-arith -Wcast-align -Wconversion -Wstrict-prototypes -Wmissing-prototypes -Wnested-externs -Woverloaded-virtual
+DEBUG    = 
+ARCHDEF  = -D__LINUX__
+DYNLIB   = -shared
+
+# To be tested:
+# OPTIM    = -pipe  
+# OPTIM2   = -fomit-frame-pointer -ffast-math -march=i686 -mcpu=i686
+
+# For debugging information use '-g'
+# For producing gmon.out use    '-pg'
+
+#MARS_LIB = -Llib $(SUBDIRS:%=-l%)  $(MARSLIBS)
+MARS_LIB = -Llib  $(MARSLIBS)
+INCLUDES = -I. $(SUBDIRS:%=-I%)
+
+# uncomment this for quiet compilation
+
+.SILENT:
+
+# @endcode
+##EOF
+
+
Index: /tags/Mars-V0.9/Makefile.conf.osf1
===================================================================
--- /tags/Mars-V0.9/Makefile.conf.osf1	(revision 9772)
+++ /tags/Mars-V0.9/Makefile.conf.osf1	(revision 9772)
@@ -0,0 +1,42 @@
+##################################################################
+#
+# config.mk
+#
+# @file        config.mk
+# 
+##################################################################
+# @maintitle
+
+# @code
+
+#
+# compilers
+#
+
+CC       = cc
+CXX      = cxx
+F77      = f77
+AR       = ar -c -r
+
+#
+#  ----->>>   settings for compilation
+#
+
+OPTIM    = -O2 -ieee -arch host -lpthread
+DEBUG    = -g  -w0 -msg_display_tag -msg_disable castqualtyp,undpreid,unrfunprm,extrasemi,intconlosbit,nonfundec,partovrd,stoclsnotfirst,boolexprconst
+ARCHDEF  = -D__OSF__ -D__USE_STD_IOSTREAM -DR__ANSISTREAM
+DYNLIB   = -shared
+
+#MARS_LIB = -Llib $(SUBDIRS/*/-l&)  $(MARSLIBS)
+MARS_LIB = -Llib $(MARSLIBS)
+INCLUDES = -I. $(SUBDIRS/*/-I&)
+
+# uncomment this for quiet compilation
+
+.SILENT:
+
+# @endcode
+##EOF
+
+
+
Index: /tags/Mars-V0.9/Makefile.conf.osf5.1
===================================================================
--- /tags/Mars-V0.9/Makefile.conf.osf5.1	(revision 9772)
+++ /tags/Mars-V0.9/Makefile.conf.osf5.1	(revision 9772)
@@ -0,0 +1,41 @@
+##################################################################
+#
+# config.mk
+#
+# @file        config.mk
+# 
+##################################################################
+# @maintitle
+
+# @code
+
+#
+# compilers
+#
+
+CC       = cc
+CXX      = cxx
+F77      = f77
+AR       = ar -c -r
+
+#
+#  ----->>>   settings for compilation
+#
+
+OPTIM    = -O2 -ieee -arch host
+DEBUG    = -g3  -w0 -msg_display_tag -msg_disable castqualtyp,undpreid,unrfunprm,extrasemi,intconlosbit,nonfundec,partovrd,stoclsnotfirst,boolexprconst
+ARCHDEF  = -D__OSF__ -D__USE_STD_IOSTREAM -DR__ANSISTREAM
+DYNLIB   = -shared
+
+#MARS_LIB = -Llib $(SUBDIRS/*/-l&)  $(MARSLIBS)
+MARS_LIB = -Llib $(MARSLIBS)
+INCLUDES = -I. $(SUBDIRS/*/-I&)
+
+# uncomment this for quiet compilation
+
+.SILENT:
+
+# @endcode
+##EOF
+
+
Index: /tags/Mars-V0.9/Makefile.rules
===================================================================
--- /tags/Mars-V0.9/Makefile.rules	(revision 9772)
+++ /tags/Mars-V0.9/Makefile.rules	(revision 9772)
@@ -0,0 +1,92 @@
+include $(CINT)Dep.d
+
+$(MRPROPERS):
+	@echo " Doing Mr.Proper in $(@:.mrproper=)"
+	(cd $(@:.mrproper=); ($(MAKE) -f Makefile mrproper > /dev/null); cd ..;) 
+
+$(CLEANERS):
+	@echo "Cleaning $(@:.clean=):"
+	(cd $(@:.clean=); $(MAKE) -f Makefile clean; cd ..;) 
+
+$(LIBRARIES):
+	@echo " Calling make in $(@:.a=)"
+	(cd $*; $(MAKE) -f Makefile all)
+
+$(LIB): $(OBJS) $(CINT)Cint.o
+	@echo " - Building Library $(LIB)"
+	$(CXX) $(CXXFLAGS) $(DYNLIB) $(OBJS) $(CINT)Cint.o -o $(LIB)
+	@echo " "
+
+$(CINT)Cint.cc: $(HEADERS) $(CINT)LinkDef.h
+	@echo " - Generating dictionary $(CINT)Cint.cc"
+	$(ROOTSYS)/bin/rootcint -f $(CINT)Cint.cc \
+	-c $(INCLUDES) $(DEFINES) $(HEADERS) $(CINT)Incl.h $(CINT)LinkDef.h 
+
+%.d:	
+	@echo " - Generating dependencies" $@
+	$(ROOTSYS)/bin/rmkdepend -f- -Y -w 3000 -- $(INCLUDES) -- $(SRCFILES) -- $(PROGRAMS:=.cc) 2> /dev/null | \
+         sed 's/^\(.*\).o:/$@ \1.o:/' > $@
+	echo "$@: Makefile" >> $@
+
+%.o:	%.cxx
+	@echo " - Compiling" $<
+	$(CXX) $(CXXFLAGS) -c $< -o $@
+
+%.o:	%.cc
+	@echo " - Compiling" $<
+	$(CXX) $(CXXFLAGS) -c $< -o $@
+
+%.o:	 %.c
+	@echo " - Compiling" $<
+	$(CC) $(CFLAGS) -c $< -o $@
+
+#
+# The cleaning facility
+#
+
+rmcint:	
+	@echo " Removing cint-stuff..."
+	@rm -f *Cint.*
+
+rmlib:	
+	@echo " Removing libraries..."
+	@echo " "
+	@rm -f lib/lib*.a lib*.a
+
+rmobjs:	
+	@echo " Removing object files..."
+	@rm -f *.o
+
+rmdep:	
+	@echo " Removing dependency files..."
+	@rm -f *Dep.d */*Dep.d
+
+rmcore:	
+	@echo " Removing core files..."
+	@rm -f core*
+
+rmbin:	
+	@echo " Removing binary files..."
+	@rm -f $(PROGRAMS) $(SOLIB) $(DYLIB) so_locations
+
+rmbak:
+	@echo " Removing backup files..."
+	@rm -f *~ kk.kk *.bak .#* .*~
+
+rmbakmac:
+	@echo " Removing backup files in macros"
+	@rm -f macros/*~
+
+rmhtml:
+	@echo " Removing htmldoc-tree"
+	rm -rf htmldoc/examples
+	rm -rf htmldoc/src
+	ls htmldoc/* | grep "htmldoc/" | grep -v images | grep -v CVS | xargs rm -f
+
+clean:	rmcint rmobjs rmdep rmcore rmlib
+
+cflags: 
+	@echo $(INCLUDES) $(CXXFLAGS)
+
+diff:
+	@cvs diff | grep -v "^? " > mars.diff
Index: /tags/Mars-V0.9/NEWS
===================================================================
--- /tags/Mars-V0.9/NEWS	(revision 9772)
+++ /tags/Mars-V0.9/NEWS	(revision 9772)
@@ -0,0 +1,794 @@
+                                                               -*-*- END -*-*-
+
+ *** Version 0.9 (2005/03/23)
+   
+   - Calibration is now done autmatically into photo-electrons like 
+     decided by the Collaboration Board
+ 
+   - Reference lines in the display can be read from resource file
+
+   - Interlaced calibration events can be handled by callisto 
+
+   - Hi-Gain vs. Lo-Gain calibration constants can be calculated
+     and applied in callisto.
+
+   - class MJCalibTest can be called by callisto
+
+   - callisto can now run with three data types: rawdata, rootdata, MC
+
+   - added two classes mreport/MReportStarguider.cc and 
+     mreport/MReportStarguider.h for implementing starguider-data
+     
+   - the output of merpp-update now contains starguider information:
+     MReportStarguider and MTimeStarguider
+   
+   - Fixed bug in MHHadronness.cc which made that the displayed Q-factor 
+     values were lower than they should. This was more visible for high
+     energy (Size) events.
+
+   - Made MExtractTimeAndChargeDigitalFilter the default for callisto
+
+   - added a new loop to callisto to support the correct extraction of 
+     the pedestal and pedestal rms through the signal extractor
+
+   - added class to perform fourier tranformation of a hexagonal structure
+     (MHexagonalFT)
+
+   - added class to perform fourier tranformation of a hexagonal structure
+     in a tasklist (MHexagonalFTCalc) example: hft.C
+
+   - added class to enhance the MCerPhotEvt from the Magic camera geometry
+     MGeomCamMagic to a enhanced geometry MGeomCamMagicXT having only
+     small pixels, example: extendcam.C
+
+   - added possibility to write data to memory (TTree) using MWriteRootFile
+
+   - added possibility to read a TTree stored only in memory by MReadTree
+
+   - new classes to deal with the interleaved calibration events:
+     MTriggerPattern, MTriggerPatternDecode and MFTriggerPattern
+
+   - implemented filters to callisto to skip calibration events
+
+   - changed callisto to calculate three kinds of pedestals and pedestal rms:
+     + fundamental pedestal (MPedPhotFundamental): extracted directly from
+       the slices by statistics                              
+     + pedestal from extractor (MPedPhotFromExtractor): extracted with the
+       signal extractor without randomization
+     + random pedestal from extractor (MPedPhotFromExtractorRndm): extracted
+       with the signal extractor with randomization (extraction window is 
+       randomly fixed)
+     The three kind of pedestal is not yet implemented (for speed reasons) as
+     long as nobody really needs it:
+     + pedestal from extractor with randomizatiuon (MPedPhotFromExtractorRndm): 
+       extracted with the signal extractor with randomization
+
+    - callisto now finds the pulse position in the data automatically
+
+    - implemented data reduction in calibrated data by reducing the precision
+      of the stored floating point values (pedestal, rms and signal) to
+      roughly 0.5%
+
+    - fixed showplot to make file format conversion (eg. converting a
+      status display stored in a root file into a postscript file) in
+      batch mode possible:
+      showplot -b --save-as-ps[=outfile.ps] infile.root
+
+    - Allow class names as part of filter rules, eg
+      (MFSupercuts) && (MHillas.fSize>100)
+
+    - fixed a lot of stuff to allow all programs to process MonteCarlo
+      camera files.
+
+    - enhanced possibility to debug reading of resource file
+
+    - MDataChain should handle priorities of operator more 
+      accurate now
+
+    - completely revised the container in which the signal is stored
+      MCerPhotEvt/Pix, MArrivalTime --> MSignalCam/Pix
+       * the new implementation is faster and
+       * needs less storage space
+
+    - FIRST version which can process Monte Carlos through the 
+      whole chain of programs (callisto, star, etc)
+
+    - implemented new image parameters for the border length of
+      the shower image (MNewImagePar2)
+
+    - implemented wobble-mode in ganymed
+
+    - new class (MJOptimize) taking care of all optimization processes
+
+
+
+ *** Version 0.8.6 (2004/10/05)
+
+   - New combined signal and time extractor 
+     MExtractTimeAndChargeDigitalFilter
+
+   - The Report for the trigger section in the CC run summary has been
+     updated, and now the IPRs (Individual Pixel Rates) are available.
+
+   - new macros for database interaction: filldotrun.C, filldotrbk.C
+
+   - added new program which can convert colored output which was redirected
+     into a file back into colored text (for example to display it with
+     more): showlog
+
+   - added new program to display an MStatusArray of plots (stored with
+     MStatusDisplay) from a file: showplot
+
+   - Added support for Sequences (MSequence). Sequences are blocks of run
+     files containing the same calibration and belonging to the same 
+     source
+
+   - Added a new task (MTaskEnv) which can be used in setup files to switch
+     between different tasks (for example to choose a signal extractor)
+
+   - Implemented automatic file splitting in MWriteRootFile
+
+   - After image cleaning an island index is assigned to all used pixels.
+     The index corresponds to the order of the islands in size.
+
+   - added a cleaning which takes signal height _and_ arrival time into
+     account: probability cleaning (for more details see MImgCleanStd)
+
+   - added a cleaning which takes takes the absolute number of photons
+     times the area ratio as cleaning level 
+     (for more details see MImgCleanStd)
+
+   - Changed calculation of image parameters such, that it can be done
+     for all used pixels or the pixels with a defined island index only
+
+   - implemented new image parameters displaying the number of islands,
+     saturated hi-gain and lo-gain pixels (MImagePar, MHImagePar)
+
+   - event display in executable changed to support also calibrated files
+     (done with MJCalibrateSignal)
+
+   - added program doing the calibration and the signal extraction
+     and signal calibration: callisto Most part of the setup is done
+     by a resource file: callisto.rc
+
+   - implemented support for pixels with negative IDs (Raw file format
+     version 4)
+
+   - implemented an new option in merpp (--auto-time) to get the time
+     range for cc and/or caco data from the run header of the raw data
+
+   - New star-program (star and MJStar). Taking calibrated data from
+     callisto/MJCalibrateSignal as input. The setup is done through
+     a resource file: star.rc
+
+   - Added possibility to setup the eventloop in the mars-executable
+     Camera Display by a resource file: mars.rc
+
+   - The the mars-executable Camera Display can now also read
+     calibrated data files written by callisto/MJCalibrateSignal
+
+   - Added a new class which can calculate the source position in
+     the camera from a pointing model known to be correct and
+     the pointing model used for observations (MSrcPosFromModel)
+
+   - added a new version of the class calculating the effective on-time
+     MHEffectiveOnTime. It unifies the old classes MHEffOnTime, 
+     MHEffOnTimeTime, MHEffOnTimeTheta, MHTimeDiff, MHTimeDiffTime and
+     MHTimeDiffTheta.
+
+   - added the possibility to count how often a signal is above (or 
+     below) a certain threshold in MHCamEvent and MHCamEventRot (this
+     can replace MHTriggerLvl0)
+
+   - added ore convinient ways to set the axis-titles of your histograms
+     in your macro to some MH-classes like: MH3, MHVsTime, MHSectorVsTime,
+     MHPixVsTime, MHVsTime, MHCamEvent and MHCamEventRot
+
+
+
+ *** Version 0.8.5 (2004/08/06)
+ 
+   - new Signal Extractors: MExtractFixedWindowSpline 
+     and MExtractAmplitudeSpline
+
+   - implementes interleave in merpp to be able to merpp parts of a file
+
+   - implemented force-functionality to merpp
+
+   - star display to display star catalogs (MAstroCatalog)
+
+   - star display to 'mirror' stars to the camera (MAstroCamera)
+
+   - implemented a new cleaning option which allows cleaning scaled with
+     the real ratio of the rms depending on the pixel size, not only the
+     square root of the pixelsize (MImgCleanStd, MCameraData)
+
+   - removed obsolete MBlind* classes
+
+   - Signal extractor taking the AB flag into account implemented (this makes
+     an odd number of slices for signal extraction possible
+     (MExtractSignalABcorr)
+
+   - implemented a class extracting the pedestal from the raw-data (events)
+     itself using empty lo-gain (MpedCalcFromLoGain)
+
+   - Added mean values to MPedPhotCam
+
+   - Added Makefile for Darwin (this OS is NOT officially supported!)
+
+
+
+ *** Version 0.8.4 (2004/04/19)
+
+   - new fast arrival time extractor using cubic splines: 
+     MExtractTimeFastSpline
+
+   - implementes multi-argument support in MDataChain
+     ("pow(a, b)")
+
+   - implemented double reference support in MDataChain
+     ("MCameraLV.fPowerSupplyA.fVoltagePos5V")
+
+   - added support in MF for expressiond like 
+     "MHillas.fWidth<2*<MHillas.fLength"
+
+   - MDataChain is now able to support variables like [0], [1], ...
+     which can be used in fit functions as parameters. The interface
+     is implemented through the new virtual function 
+     MParContainer::SetVariables
+
+   - added new class MArrivalTimeCam/MArrivalTimePix:
+     Storage containers to hold the ArrivalTime of the camera/pixel
+
+   - added new classes for the calibration of relative arrival times:
+     MCalibrationRelTimePix and MCalibrationRelTimeCam
+  
+   - added new classes to extract the signal of the blind pixel and the 
+     PIN Diode separately: MExtractBlindPixel and MExtractPINDiode
+
+   - added new classes for the bad-pixels treatment (MBadPixels*)
+     which are more powerfull than the old ones (MBlindPixel*)
+     and will replace them.
+
+   - added filter against cosmics: MFCosmics
+
+   - added new class MArrivalTimeCalc2:
+     Calculates the arrival time as the signal weighted mean of the time 
+     slices in the maximum window
+
+   - added a new macro call pointspreadfucntion.C that fits with a 2D 
+     gaussian the DC spot for an star. It gives you the RMS of
+     the PSF and the center of the star, very useful for misspointing 
+     studies.
+
+   - added support for multi-telescope camera files. Added classes 
+     MStereoCalc and MStereoPar, classes to calculate and store shower
+     parameters calculated from the data of two telescopes, for the MC
+     studies regarding the MAGIC clone.
+
+   - added MMcCalibrationCalc, MMcCalibrationUpdate, classes to obtain
+     MC data calibrated in photons instead of ADC counts.
+
+   - added three macros to show the calibration and analysis chain of 
+     MC data. The macro starmc.C does both calibration and analysis, producing
+     an output containing Hillas parameters for each event. The macro 
+     mccalibrate.C does just the calibration and writes out a file containing
+     pixel information in photons instead of FADC data. The macro starmc2.C
+     reads in such a file and produces an output with Hillas parameters.
+
+   - added MPedPhotCalc to compute pedestals in units of photons, see
+     macro pedphotcalc.C
+
+   - added all class to perform the calibration, see macro calibration.C
+
+   - added class MFFT to perform Fast Fourier Transforms
+
+   - added class MSimulatedAnnealing to perform simulated annealing 
+     minimizations
+
+   - added new macro bootcampstandardanalysis.C which holds the skeleton
+     of the analysis chain discussed in the december bootcamp. 
+
+   - added support for DAQ raw data file format V2
+
+   - implemented an arbitrary time stamp for the events from raw-data
+     files with file version<3. It is calculated from the run number, 
+     the date of start and the FADC clock tick from the first module
+
+   - implemented the correct decoding of the event time-stamp
+     coming from the DAQ for raw-data files with file-version>2
+
+   - added a new classes storing the pedestals in units of photons: 
+     MPedPhotPix, MPedPhotCam
+
+   - added support for DC current files from the camera control
+
+   - added support for start- and stop-time when merpping report files
+
+   - added MReportCC storing the weather data from the CC-REPORT
+
+   - added class to fill trainings and test matrices (MTFillMatrix)
+
+   - added a filter performing a software trigger (MFSoftwareTrigger)
+
+   - Added classes to perform parts of the standard analysis (Jobs):
+     + MJPedestals
+     + MJCalibration
+     + MJExtractSignal
+     Note: All of them are preliminary!
+
+   - Added Iterator to iterate over files giving only the run-number
+
+   - Added class (MHSectorVsTime) and example (sectorvstime.C) to plot
+     the evolution of a sector vs time
+
+
+
+ *** Version 0.8.3 (2003/12/05)
+
+   - adapted Random Forest classes to allow the use with MC
+     multi-telescope files which can be produced with the coming
+     camera version 0.7.
+
+   - added classes to read and interprete central control report files
+     (Directory: mreport, Base-Class: MReport, Reader: MReportFileRead, ...)
+
+   - enhanced merpp (the executable) to support .raw and .rep files.
+
+   - added classes for light calibration (MCalibration* and 
+     MHCalibration*) by Markus Gaug. Further work has to be and will
+     be done soon.
+
+   - Added a preliminary 'synchronizer' (MReadReports) which will 
+     replace MReadMarsFile as soon as it is finished.
+
+   - Added a tutorial macro demonstrating how report files are merpped
+     and how they can be read from the root file in the correct order
+     of time (readrep.C)
+
+   - Added a generalized histogram (similar to MH3) called MVsTime
+     which allows to plot variables (or rules - MDataChain - of
+     variables) vs time. For an example have a look at tempvstime.C.
+
+   - Changed the name of the event trees:
+       + Events    --> Events
+       + PedEvents --> Pedestals
+       + CalEvents --> Calibration
+
+  - changed name of MTime in the event trees from MRawEvtTime to MTime
+
+  - added displaying the sector indices to the mars event display
+
+  - Magic Online Analysis (MOnA) implemented in a first version
+    (see mona.cc, MOnlineDump and MOnlineDisplay)
+
+  - added classes to calculate event rate
+    (preliminary: MEventRateCalc, MEventRate)
+
+  - added new executable 'readdaq' to read *.raw files from the DAQ directly
+
+  - added classes dealing with the telescope pointing position (MPointing*)
+
+  - implemented the 'final' Mars time stamp based on some experiences with
+    the new 'Synchonizer'
+
+
+
+ *** Version 0.8.2 (2003/11/10)
+
+   - accelerated standard analysis by a factor of 6-8 ...
+     + doing precalculations in MGeomCam for the pixel area ratio
+     + creating a look up table for the single pixels in MCerPhotEvt
+
+   - added task to calculates weights in case you want to 'change'
+     the energy spectrum of a monte carlo file 
+     (MMcWeightEnergySpecCalc - Great work from Marcos Lopez Moya)
+
+   - added a new executable star which implements the
+     star.C macro as precompiled executable. Currently a flexible
+     setup is not possible, but a 'input card' setup will follow.
+
+   - Starting to implement Multi-Telescope-Support based on the 
+     upcomming camera version 0.7. The base for a general support
+     is implemented and the star-functionality is proven to work.
+
+   - Replaced Event-Display in and Camera-Display in the Mars GUI
+     executable by a more convinient display base on MStatusDisplay.
+
+   - fixed the algorithm for the blind pixel treatment (MBlindPixelCalc)
+
+
+
+ *** Version 0.8.1 (2003/10/20)
+   
+   - added signal subtraction for pure on data by means of fitting
+     the background in the off region or by performing a combined
+     signal/background fit. Provides necessary histograms for
+     obtaining energy spectra and a light curve.
+
+   - added classes to perform and study the selection of the 
+     2nd Level Trigger on MC data (example in triglvl2.C macro)
+
+   - added pedestal calculation
+
+   - implemented "democratic cleaning" (tail cut value proportional 
+     to pixel area) according to Wolfgang's suggestion.
+
+   - added Sigmabar treatment (calculation and basic histogramming)
+
+   - added basic routines to apply padding
+
+   - added first implementation of MARS-based source visibility plotter
+     (needs to be linked against slalib, preliminary version)
+
+   - enhanced functionality of data chains: random numbers, conversion
+     functions and access to MHMatrix objects
+   
+   - fixed some bugs in the CT1 Preproc file reader, which gave wrong
+     numbers under certain circumstances (runs with 0 events included)
+
+   - fixed a bug in the general filter MF (didn't work on some systems
+     at all)
+   
+   - fixed a bug in chaining files, which caused the analysis to crash or
+     ignore files
+
+   - implemented more geometry classes describing the parameters used
+     to simulate the PMT camera
+
+   - added new Monte Carlo classes containing the setup of the different
+     programs in the MC chain.
+
+   - added a (preliminary) general task to evaluate chi-square of a given
+     parameter in an eventloop.
+
+   - first implementation of a container describing the observatory
+     location (Long, Lat, etc)
+   
+   - added Random Forest - method for g/h-separation
+
+   - made compatible with the latest PRO version of root (3.04/02 and 3.05/07)
+     (this means, that it is compiling, but not yet fully tested)
+
+   - added a new status display which can show the present status
+     of histograms while an eventloop is running (MStatusDisplay,
+     an example can be found at status.C)
+
+   - reorganized directories:
+     classes describing the image              --> mimage
+     classes containing Monte Carlo Histograms --> mhistmc
+     classes for Random Forest method          --> mranforest
+
+   - added (event-)weights to fill histograms
+
+   - colors in logging output to screen
+
+   - changes to the Image Parameter declaration:
+       + moved fConc, fConc1 from MHillasSrc to MNewImagePar
+       + moved fNumUsedPix, fNumCorePix from MHillas to MNewImagePar
+       + MHillasExt now derives from MParContainer instead of MHillas
+     --> Files written with the old definition are more or less unreadable
+
+   - reading of reflector files
+
+   - display data from reflector files in the camera
+
+   - implemented currents (and display them in the camera)
+
+   - logarithmic scale in camera
+
+   - added class to iterate through directory contents (MDirIter)
+
+
+
+ *** Version 0.8 (2002/11/18)
+
+   - added all subdirectories as Include-Paths for ACLIC (s. rootlogon.C)
+
+   - corrected 48(!) wrong entries in the Next Neighbor table of the
+     Magic Camera (all in the inner part of the outer ring, mostly 
+     missing a single NN)
+
+   - Fixed a bug in the table describing the Next Neighbours of the
+     CT1 camera (a pixel 127 doesn't exist and the pixel 126 didn't
+     have any neighbour)
+
+   - changed trigrate.C: now it calculates the pure NSB triggers from
+     a camera file (generated with no showers), so there is no need
+     to introduce them by hand in the BgR array (for more details
+     please ask Abelardo)
+
+   - added MHHadronness (and MHadronness) as a general facility to evaluate
+     the quality of a gamma-hadron seperation method
+
+   - changed MWriteAsciiFile to accept rules (MDataChain)
+
+   - Calls to MWriteAsciiFile::AddContainer and MWriteAsciiFile::AddRule
+     must be replaced by calles to MWriteAsciiFile::AddColumn and
+     MWriteAsciiFile::AddColumns. Be carefull, the arguments have slightly
+     changed.
+
+   - Implemented generalized event-matrices (one row per event)
+     (MHMatrix)
+
+   - implemented the one dimensional composite probabilities
+     (MHCompProb, MCompProbCalc, comprob.C)
+
+   - implemented the Multidimensional Distances (Next Neighbours, Kernel)
+     (MMultiDimDistCalc, multidimdist.C, multidimdist2.C, MHMatrix)
+
+   - Added a camera display displaying the pixel numbers to the
+     event display gui.
+
+   - Added Monte Carlo Informations to event display gui
+
+   - Changed the camera display to display the pixel numbering
+   
+   - Added three buttons to the camera display to change the palette
+
+   - Added the number of used and core pixels after image cleaning
+     to MHillas
+
+   - Changed the algorithm used in MHillas according to TDAS 02-03
+
+   - Changed the Alpha range according to TDAS 02-03 to [-90°,90°]
+
+   - Changed the algorithm used in MHillasSrc according to TDAS 02-03
+
+   - Added fCosDeltaAlpha to MHillasSrc
+
+   - The numbers of photons used to calculate fConc and fConc1 in
+     MHillasExt are now scaled with the pixel size, so that one get
+     a four times smaller value for the bigger pixels in the outer ring.
+
+   - added new task to smooth the camera contents (MCameraSmooth)
+
+   - added possibility to use interpolated pixel values for blind pixels
+     instead of removing it completely from the analysis
+
+   - Implemented the possibility to save the whole eventloop with
+     its setup to a file. This information can be read and from
+     it you can (re)create a Macro. See MEvtLoop::Read, MEvtLoop::Write
+     and MEvtLoop::MakeMacro. If you find something not working, please
+     report - this stuff is still in a beta phase.
+
+   - MBlindPixelCalc set all Ceta-Tauri pixels to unused not only for the
+     file having crab starfield, but also for all following files - fixed
+
+   - MTaskList::PrintStatistics can now be instructud to print also the
+     title, too: use PrintStatistics(0, kTRUE)
+
+   - Changed the image cleaning so that pixels with to many 'used'
+     neighbors are left used (to get rid of 'holes' in events)
+
+   - Introduced more output to the camera displays
+
+   - Added an array of histograms (eg one hist per run), MHArray
+
+   - Added a _preliminary_ version of the reader for CT1 PreProc files
+     (MCT1ReadPreProc)
+
+   - Fixed the error calculation of MHMCollectionArea and MHMcIntRate
+     (thanks to Raquel)
+
+   - added the first energy estimator (MEnergyEstParam, estimate.C,
+     estfit.C) using a parametrization
+
+   - Added some new Monte Carlo paremeter containers used to store
+     setup information from the MC chain (MMcConfigRunHeader, 
+     MMcCorsikaRunHeader, MGeomPMT, MGeomMirror)
+
+
+
+ *** Version 0.7 (2002/04/30)
+ 
+   - added a bugfix to MCerPhotCalc. In older camera versions (<=40)
+     the pedestal mean value was saved incorrectly. For files from
+     this versions we substract 0.5 from the pedestal mean.
+     WARNING: This may effect your results, so don't wonder...
+
+   - First implementation of an algorithm using only triggered events
+     for the collection area calculation
+
+   - Ascii Output can now also be used for parameter containers which
+     doesn't overload MParCointainer::AsciiWrite
+
+   - The Ascii Output is now also capable of writing single data members
+     of one container
+
+   - You are now able to change the order of the values written to the
+     ascii file
+
+   - You can now specify a conversion factor for each data member written
+     to an ascii file. This may be usefull to change the units of the 
+     data member (eg. degrees instead of millimeters in case of the 
+     hillas parameters)
+
+   - Replaced old MHillas by a new structure which allows you to extend
+     the parameters stored in MHillas very easily:
+     see MHillas and MHillasExt
+
+   - Added classes to handle source dependancy of image parameters:
+     see MHillasSrc
+
+   - Added container (MBinning) to have a standard input for the binning
+     in different histograms (eg. the Energy bins should be the same in
+     all histograms)
+
+   - Changed Hillas histograms from mm to deg
+
+   - Added the flexible binning to the hillas histograms
+
+   - Added a filter for the alpha parameter (MFAlpha)
+
+   - It is now possible to write single data members of a class object to
+     an output stream instead of the whole container only
+
+   - Added a generalized filter for a data member:
+     MFDataMember filter("MHillas.fWidth", '<', 0.5);
+
+   - Added a generalized Filter parser for more difficult filter rules
+     MF filter("MHillas.fWidth<0.5 && MHillas.fLength>0.5");
+
+   - Added new Monte Carlo histograms:
+     MHMcEnergyImpact and MHMcEfficiency
+
+   - Added many new histograms needed for the flux calculation.
+
+   - Added a generalized histograms which can fill and show up to three
+     data members in either a one-, two- or three-dimensional histogram, eg:
+     MH3 mh3("MHillas.fWidth", "MHillas.fLength");
+
+   - Added:
+       * calculation of <Theta> as a function of Theta (MHThetabarTheta)
+       * calculation of <Theta> as a function of time (MHThetabarTime)
+     they are needed in the flux calculation in 
+     order to select for a given bin in Theta (or time) the appropriate 
+     effective collection area, which is assumed to be given as a function 
+     of Theta and the true energy
+
+   - Added calculation of the migration matrix in the energy 
+     (MHMcEnergyMigration):
+     the migration matrix describes the migration from the true (E_true)
+     to the estimated energy (E_est); it is needed to determine the
+     distribution of E_true from the measured distribution of E_est 
+     by unfolding
+
+   - changed the color palette in the camera display to DeapSea.
+
+
+
+ *** Version 0.6 (2002/01/15)
+
+   - Introduce the option of disable pixels (MBlindPixels and
+     MBlindPixelCalc) for the analysis (eg MHillasCalc) to be 
+     able to deal with Star Field NSB.
+
+   - Fixed a bug in the pedestals substraction
+
+   - Introduced verbosity levels
+
+   - Introduced a task (MReadMarsFile) which reads the RunHeader tree, too.
+
+   - Fixed several bugs in MFTriggerLvl1 which caused to filter not to
+     work correctly (thanks to Abelardo)
+
+   - Introduced correct treatment of the diffuse Night Sky Background 
+     and NSB (MMcPedestalNSB)
+
+   - Corrected treatment of the electronic noise (MMcPedestalCopy)
+
+   - Introduced MMcRunHeaders which contains monte carlo run informations
+
+   - Added a 'Print'-Task (MPrint) which calls the Print function
+     of a parameter container for each event
+
+   - Removed MHtml (was replaced by THtml of root 3.02) in dohtml.C
+
+   - changes to be more efficient with root 3.02/06
+
+   - root 3.02/06 fixes:
+     + the memory leak when reading MRawEvtData
+     + loosing more time than necessary to update the progress bar
+
+   - MWriteAsciiFile is now capable of writing more than one container
+     in a line. For example: To be able to write Monte Carlo and 
+     Hillas values (energy and alpha) in one line.
+
+
+
+ *** Version 0.5 (2001/11/06)
+
+   - Added new GUI functionality (Analysis)
+
+   - Added a camera display to be able to display events in the camera
+     together with the calculated hillas ellipse
+
+   - Added a 'Clone'-Task (MClone) which can clone a parameter container
+     object at any state of the analysis, so that the output are several
+     states
+
+   - Fixed a bug in the collection area error calculation 
+     (Thanks to Ciro and Abelardo)
+
+   - Fixed a bug which causes merpp to crash in some environments
+
+   - Implemented auto enabling scheme for Branches to speed up reading
+     a lot (see MReadTree and MTask)
+
+   - Fixed a bug in the Histogram classes which caused histograms to
+     be written to a file by MWriteRootFile without request
+
+   - changed the object I/O from the old stylish root I/O to the new
+     'auto evolution scheme' This was done only for classes which are not
+     yet used in Monte Carlo files, so that these files are still readable.
+
+   - Added support for a progress bar in MEvtLoop and MReadTree 
+     (see the Analysis Window in Mars for an example)
+
+   - Fixed a bug in the package creation which disturbed the conversion
+     between a mars version unpacked from a tar file and the repository.
+
+   - Changed the code to writer merpped (converted into root format)
+     raw files, to get faster (around 10%)
+
+
+
+ *** Version 0.4 (2001/09/20)
+
+    - This release is made to compile on a root version >= 3.00
+
+    - Fixed a bug which causes MReadTree to read the first file only
+
+    - Added a task to compute the trigger rate (MMcTriggerRateCalc)
+ 
+    - Added a task to write a container to an Ascii file (MWriteAsciiFile)
+
+    - Added a task to write several container to a root file (MWriteRootFile)
+    
+    - Added calculation of the Enegry Threshold (MMcThresholdCalc)
+    
+    - Added calculation of the collection area (MMcCollectionAreaCalc)
+    
+    - fixed some bugs in the Hillas calculation
+    
+    - added filters to be able to control the task execution dependent on
+      a parameter (for example: the number of level 1 triggers in a MC-file)
+
+
+
+ *** Version 0.3 (2001/04/23)
+	
+    - Many demo macros added    
+  
+    - MCT1ReadAscii is now able to handle more than one file (s. ::AddFile)
+    
+    - Hillas Calculation added
+    
+    - Standard image cleaning available
+    
+    - MReadTree is now able to handle more than one file
+      (Remark: of the same structure)
+    
+    - Now we are able to display events in a first version of the
+      Camera event display. To do this we must run the macro 
+      "macros/readCT1.C" to read data from CT1. 
+
+
+
+ *** Version 0.2 (2001/01/24)
+ 
+    - First Implementation of a Gui to read the raw data. Start the
+      gui with the command mars. 
+
+
+
+ *** Version 0.1 (2000/12/20)
+ 
+    - First official release 0.1
+    
+    - Changes:
+    
+       + changed calling style of MRawPixelIterator from do...while to 
+         while-loop
+
Index: /tags/Mars-V0.9/callisto.cc
===================================================================
--- /tags/Mars-V0.9/callisto.cc	(revision 9772)
+++ /tags/Mars-V0.9/callisto.cc	(revision 9772)
@@ -0,0 +1,627 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TGClient.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MDirIter.h"
+
+#include "MStatusDisplay.h"
+
+#include "MSequence.h"
+#include "MJPedestal.h"
+#include "MJCalibration.h"
+#include "MJCalibrateSignal.h"
+#include "MJCalibTest.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "========================================================" << endl;
+    gLog << "                 Callisto - MARS V" << MARSVER            << endl;
+    gLog << "    MARS -- CALibrate LIght Signals and Time Offsets"     << endl;
+    gLog << "               Compiled on <" << __DATE__ << ">"          << endl;
+    gLog << "                  Using ROOT v" << ROOTVER                << endl;
+    gLog << "========================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " callisto [-c] [-y] [options] sequence.txt" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   sequence.txt:             Ascii file defining a sequence of runs" << endl;
+    gLog << "                             For more details see MSequence" << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Operation Modes:" << endl;
+    gLog << "   -c                        Calculate the calibration constants" << endl;
+    gLog << "   -y                        Extract and calibrate signal" << endl << endl;
+    gLog << " Data Type (exclusive):" << endl;
+    gLog << "   -raw                      Read input from raw-data" << endl;
+    gLog << "   -mc                       Input root-files are monte carlo files" << endl;
+    gLog << "   -root                     Read input from root-files (merpped) <default>" << endl << endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    gLog << "   --debug-env=3             Debug setting resources from resource file" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   --ind=path                Path where to search for the data files" << endl;
+    gLog << "                             [default=standard path in datacenter]" << endl;
+    gLog << "   --iny=path                Path where to search for the calibration files" << endl;
+    gLog << "                             [default=local path or output path of Mode-C]" << endl;
+    gLog << "   --outc=path               Path to write Mode-C result to   [def=local path]" << endl;
+    gLog << "   --outy=path               Path to write Mode-Y result to   [def=local path]" << endl;
+    gLog << "   --out=path                Path to write the all results to [def=local path]" << endl;
+    gLog << "                             (overwrites --outc and --outy)" << endl;
+    gLog << "   --path=path               Path to write the all results to [def=local path]" << endl;
+    gLog << "                             (overwrites --iny, --outc and --outy)" << endl;
+    gLog << "   --print-seq               Print Sequence information" << endl;
+    gLog << "   --print-files             Print Files taken from Sequence" << endl;
+    gLog << "   --print-found             Print Files found from Sequence" << endl;
+    gLog << "   --use-test                Apply calibration constants to same calibration" << endl;
+    gLog << "                             file (for testing, calibration mode only)" << endl;
+    gLog << "   --moon                    Force using pedestal fits instead of calculated RMS" << endl;
+    gLog << "   --config=callisto.rc      Resource file [default=callisto.rc]" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << " Setup of the two jobs run by callisto (MJPedestal and MJCalibration)" << endl;
+    gLog << " can be done with the resource file. See MJPedestal and MJCalibration" << endl;
+    gLog << " especially CheckEnv() for more details.   Command line options might" << endl;
+    gLog << " be overwritten by the resource file." << endl << endl;
+    gLog << " If running in Mode-C and Mode-Y --iny= is obsolete,  instead --outc=" << endl;
+    gLog << " is used." << endl << endl;
+    gLog << " Using  --iny=,  --outc=,  --outy=,  --out=  or --path= automatically" << endl;
+    gLog << " enables the corresponmding modes.  In this case  -c/-y are obsolete." << endl << endl;
+    gLog << "Description:" << endl;
+    gLog << " callisto will calculate pedestals  from  pedestal-files defined in a" << endl;
+    gLog << " sequence-file.  This pedestals are used to calculate the calibration" << endl;
+    gLog << " contants. These constants are stored in a so called calibration-file" << endl;
+    gLog << " together with some datacheck plots  which can be viewed using either" << endl;
+    gLog << " showplot or MStatusDisplay in the interpreter.  A description  of  a" << endl;
+    gLog << " sequence-file can be found in the class reference of MSequence." << endl << endl;
+    gLog << "Background:" << endl;
+    gLog << " Callisto is a large,  icy,  dark-colored,  low-density outer moon of" << endl;
+    gLog << " Jupiter that is scarred with  impact craters  and  ejecta.  It has a" << endl;
+    gLog << " diameter of about 4800km, the second-largest moon of Jupiter;  it is" << endl;
+    gLog << " roughly the size of  Mercury.  Callisto has the largest-known impact" << endl;
+    gLog << " crater in the Solar System, Valhalla, which has a bright patch 600km" << endl;
+    gLog << " across  and  rings that go out  to almost  3000km.  Callisto  orbits" << endl;
+    gLog << " Jupiter at a mean distance of 1,883,000km. Its mass is 1.1e23 kg. It" << endl;
+    gLog << " takes Callisto  16.7 days to orbit  Jupiter  in a synchronous orbit." << endl;
+    gLog << " Jupiter's moon Callisto was discovered independantly by  Galileo and" << endl;
+    gLog << " S.Marius in 1610." << endl << endl;
+    gLog << "Example:" << endl;
+    gLog << " callisto -f --outc=mycal/ --outy=mysignal/ --log sequence02345.txt" << endl;
+    gLog << endl;
+}
+
+static void PrintFiles(const MSequence &seq, const TString &kInpathD, Bool_t raw, Bool_t all)
+{
+    const char *prep = all ? "Found" : "Scheduled";
+
+    MDirIter Next1, Next2, Next3;
+    seq.SetupPedRuns(Next1, kInpathD, "P", raw);
+    seq.SetupCalRuns(Next2, kInpathD, "C", raw);
+    seq.SetupDatRuns(Next3, kInpathD, "D", raw);
+
+    gLog << all;
+    gLog.Separator(Form("%s Pedestal Files", prep));
+    Next1.Print(all?"all":"");
+    gLog << endl;
+    gLog.Separator(Form("%s Calibration Files", prep));
+    Next2.Print(all?"all":"");
+    gLog << endl;
+    gLog.Separator(Form("%s Data Files", prep));
+    Next3.Print(all?"all":"");
+    gLog << endl;
+}
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv, kTRUE);
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    gLog.Setup(arg);
+
+    const TString kConfig     = arg.GetStringAndRemove("--config=", "callisto.rc");
+
+    const Bool_t  kPrintSeq   = arg.HasOnlyAndRemove("--print-seq");
+    const Bool_t  kPrintFiles = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kPrintFound = arg.HasOnlyAndRemove("--print-found");
+    const Bool_t  kUseTest    = arg.HasOnlyAndRemove("--use-test");
+    const Bool_t  kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+          Bool_t  kMoon       = arg.HasOnlyAndRemove("--moon");
+    Int_t kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit       = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch      = arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite  = arg.HasOnlyAndRemove("-f");
+    //const Bool_t  kForceExec  = arg.HasOnlyAndRemove("-ff");
+
+    const TString kInpathD    = arg.GetStringAndRemove("--ind=",  "");
+          TString kInpathY    = arg.GetStringAndRemove("--iny=",  "");
+          TString kOutpathY   = arg.GetStringAndRemove("--outy=", "");
+          TString kOutpathC   = arg.GetStringAndRemove("--outc=", "");
+    const TString kOutpath    = arg.GetStringAndRemove("--out=",  "");
+    const TString kPath       = arg.GetStringAndRemove("--path=", "");
+
+          Bool_t  kModeC      = arg.HasOnlyAndRemove("-c");
+          Bool_t  kModeY      = arg.HasOnlyAndRemove("-y");
+
+    MJCalib::DataType_t kDataType = MJCalib::kIsUseRootData; // root
+    if (arg.HasOnlyAndRemove("-raw"))
+        kDataType = MJCalib::kIsUseRawData;  // raw
+    if (arg.HasOnlyAndRemove("-mc"))
+        kDataType = MJCalib::kIsUseMC;       // monte carlo
+
+    if (!kInpathY.IsNull() || !kOutpathY.IsNull() || !kOutpath.IsNull() || !kPath.IsNull())
+        kModeY = kTRUE;
+    if (!kOutpathC.IsNull() || !kOutpath.IsNull() || !kPath.IsNull())
+        kModeC = kTRUE;
+
+    if (!kModeC && !kModeY /*&& !kUseTest*/)
+    {
+        gLog << err << "Neither calibration (-c) nor signal extraction (-y) or test-mode (--use-test) specified!" << endl;
+        Usage();
+        return 0;
+    }
+
+    if ((kModeC/* || kUseTest*/) && kOutpathC.IsNull())
+        kOutpathC = ".";
+    if (kModeY)
+    {
+        if (kInpathY.IsNull())
+            kInpathY = ".";
+        if (kOutpathY.IsNull())
+            kOutpathY = ".";
+    }
+    if (!kOutpath.IsNull())
+    {
+        kOutpathC = kOutpath;
+        kOutpathY = kOutpath;
+    }
+    if (!kPath.IsNull())
+    {
+        kOutpathC = kOutpath;
+        kOutpathY = kOutpath;
+        kInpathY  = kOutpath;
+    }
+
+    if (kModeC && kModeY)
+        kInpathY = kOutpathC;
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return -1;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Setup sequence file and check for its existance
+    //
+    const TString kSequence = arg.GetArgumentStr(0);
+
+    if (gSystem->AccessPathName(kSequence, kFileExists))
+    {
+        gLog << err << "Sorry, sequence file '" << kSequence << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    if (gSystem->AccessPathName(kConfig, kFileExists))
+    {
+        gLog << err << "Sorry, config file '" << kConfig << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Setup sequence and check its validity
+    //
+    MSequence seq(kSequence);
+    if (kPrintSeq)
+    {
+        gLog << all;
+        gLog.Separator(kSequence);
+        seq.Print();
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Sequence read but not valid!" << endl << endl;
+        return -1;
+    }
+
+    //
+    // Process print options
+    //
+    if (kPrintFiles)
+        PrintFiles(seq, kInpathD, kDataType==MJCalib::kIsUseRawData, kFALSE);
+    if (kPrintFound)
+        PrintFiles(seq, kInpathD, kDataType==MJCalib::kIsUseRawData, kTRUE);
+
+    if (seq.HasMoon())
+        kMoon = kTRUE;
+
+
+    /*
+    //
+    // Check for existance of all files
+    //
+    MDirIter iter;
+    const Int_t n0 = seq.SetupAllRuns(iter, kInpathD, "[DPC]");
+    const Int_t n1 = seq.GetNumAllRuns();
+    if (n0 != n1)
+    {
+        if (kForceExec)
+            gLog << warn << "WARNING";
+        else
+            gLog << err << "ERROR";
+        gLog << " - " << n1 << " files in sequence defined, but " << n0 << " found in ";
+        gLog << (kInpathD.IsNull() ? "<defaultpath>" : kInpathD.Data()) << endl;
+        if (!kForceExec)
+            return -1;
+    }
+
+    if (kPrintOnly)
+        return 0;
+  */
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("Callisto", &argc, argv);
+    if (!gROOT->IsBatch() && !gClient || gROOT->IsBatch() && !kBatch)
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(kSequence);
+
+    MEnv env(kConfig);
+    if (kModeC/* || kUseTest*/)
+    {
+        //
+        // Calculate pedestal for pedestal-calculation and calibration
+        //
+        MJPedestal job1(Form("MJPedestalC1 #%d", seq.GetSequence()));
+        job1.SetNoStorage();
+        job1.SetSequence(seq);
+        job1.SetEnv(&env);
+        job1.SetEnvDebug(kDebugEnv);
+        job1.SetDisplay(d);
+        job1.SetOverwrite(kOverwrite);
+        job1.SetPathData(kInpathD);
+        job1.SetDataType(kDataType);
+        job1.SetUseHists(kMoon);
+
+
+        job1.SetExtractionFundamental();
+        // job1.SetPathOut(kOutpathC); // not yet needed
+        // job1.SetPathIn(kInpathC);   // not yet needed
+
+        if (!job1.ProcessFile())
+        {
+            gLog << err << "Calculation of pedestal failed." << endl << endl;
+            return -1;
+        }
+
+        if (!job1.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Calculate pedestal and pedestal resolution
+        //
+        MJPedestal job2(Form("MJPedestalC2 #%d", seq.GetSequence()));
+        job2.SetNoStorage();
+        job2.SetSequence(seq);
+        job2.SetEnv(&env);
+        job2.SetEnvDebug(kDebugEnv);
+        job2.SetDisplay(d);;
+        job2.SetOverwrite(kOverwrite);
+        job2.SetPathData(kInpathD);
+        job2.SetDataType(kDataType);
+        job2.SetUseHists(kMoon);
+        // job1.SetPathOut(kOutpathC); // not yet needed
+        // job1.SetPathIn(kInpathC);   // not yet needed
+
+        //job2.SetExtractorResolution();
+        job2.SetExtractionWithExtractorRndm();
+        job2.SetExtractor(job1.GetExtractor());
+        job2.SetPedestals(job1.GetPedestalCam());
+        job2.SetBadPixels(job1.GetBadPixels());
+
+        if (!job2.ProcessFile())
+        {
+            gLog << err << "Calculation of pedestal resolution failed." << endl << endl;
+            return -1;
+        }
+
+        if (!job2.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Do calibration
+        //
+        MJCalibration job3(Form("MJCalibration #%d", seq.GetSequence()));
+        job3.SetSequence(seq);
+        job3.SetEnv(&env);
+        job3.SetEnvDebug(kDebugEnv);
+        job3.SetDisplay(d);
+        job3.SetOverwrite(kOverwrite);
+        job3.SetPathOut(kOutpathC);
+        job3.SetPathData(kInpathD);
+        job3.SetDataType(kDataType);
+        // job2.SetPathIn(kInpathC); // not yet needed
+
+        job3.SetBadPixels(job2.GetBadPixels());
+        job3.SetExtractor(job2.GetExtractor());
+        job3.SetExtractorCam(job2.GetPedestalCam());
+
+        if (!job3.ProcessFile(job1.GetPedestalCam()))
+        {
+            gLog << err << "Calculation of calibration failed." << endl << endl;
+            return -1;
+        }
+
+        if (kDebugEnv>0)
+            env.PrintUntouched();
+
+        if (!job3.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        if (kUseTest)
+        {
+            MJCalibTest job4(Form("MJCalibTest #%d", seq.GetSequence()));
+            job4.SetBadPixels(job2.GetBadPixels());
+            job4.SetSequence(seq);
+            job4.SetEnv(&env);
+            job4.SetEnvDebug(kDebugEnv);
+            job4.SetDisplay(d);;
+            job4.SetOverwrite(kOverwrite);
+            job4.SetPathOut(kOutpathC);
+            job4.SetPathData(kInpathD);
+            job4.SetDataType(kDataType);
+
+            if (!job4.ProcessFile(job1.GetPedestalCam()))
+            {
+                gLog << err << "Calibration of calibration failed." << endl << endl;
+                return -1;
+            }
+
+            if (kDebugEnv>0)
+                env.PrintUntouched();
+
+            if (!job4.GetDisplay())
+            {
+                gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+                return 1;
+            }
+        }
+    }
+
+    if (kModeY)
+    {
+        d->Reset();
+
+        //
+        // Calculate starting pedestal for data extraction
+        //
+        MJPedestal job1(Form("MJPedestalY1 #%d", seq.GetSequence()));
+        job1.SetNoStorage();
+        job1.SetSequence(seq);
+        job1.SetEnv(&env);
+        job1.SetEnvDebug(kDebugEnv);
+        job1.SetDisplay(d);
+        job1.SetNoDisplay();
+        job1.SetOverwrite(kOverwrite);
+        job1.SetPathData(kInpathD);
+        job1.SetPathIn(kInpathY);
+        job1.SetDataType(kDataType);
+        //job1.SetPathOut(kOutpathY);   // not yet needed
+        job1.SetUseData();
+        job1.SetExtractionFundamental();
+        job1.SetUseHists(kMoon);
+
+        if (!job1.ProcessFile())
+        {
+            gLog << err << "Calculation of fundamental pedestal failed." << endl << endl;
+            return -1;
+        }
+
+        if (!job1.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Calculate pedestal and pedestal resolution
+        //
+        MJPedestal job2(Form("MJPedestalY2 #%d", seq.GetSequence()));
+        job2.SetNoStorage();
+        job2.SetSequence(seq);
+        job2.SetEnv(&env);
+        job2.SetEnvDebug(kDebugEnv);
+        job2.SetDisplay(d);
+        job2.SetNoDisplay();
+        job2.SetOverwrite(kOverwrite);
+        job2.SetPathData(kInpathD);
+        job2.SetPathIn(kInpathY);
+        job2.SetDataType(kDataType);
+        job2.SetPulsePosCheck(kDataType!=MJCalib::kIsUseMC);
+        job2.SetPathOut(kOutpathY); // for updating the extractor
+
+        job2.SetUseData();
+        job2.SetExtractionWithExtractor();
+        job2.SetExtractor(job1.GetExtractor());
+        job2.SetPedestals(job1.GetPedestalCam());
+        job2.SetBadPixels(job1.GetBadPixels());
+        job2.SetUseHists(kMoon);
+
+        if (!job2.ProcessFile())
+        {
+            gLog << err << "Calculation of pedestal from extrtactor (random) failed." << endl << endl;
+            return -1;
+        }
+
+        if (!job2.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Calculate pedestal and pedestal resolution
+        //
+        MJPedestal job3(Form("MJPedestalY3 #%d", seq.GetSequence()));
+        job3.SetNoStorage();
+        job3.SetSequence(seq);
+        job3.SetEnv(&env);
+        job3.SetEnvDebug(kDebugEnv);
+        job3.SetDisplay(d);
+        job3.SetNoDisplay();
+        job3.SetOverwrite(kOverwrite);
+        job3.SetPathData(kInpathD);
+        job3.SetPathIn(kInpathY);
+        job3.SetDataType(kDataType);
+        // job1.SetPathOut(kOutpathC); // not yet needed
+        // job1.SetPathIn(kInpathC);   // not yet needed
+
+        job3.SetUseData();
+        job3.SetExtractionWithExtractorRndm();
+        job3.SetExtractor(job1.GetExtractor());
+        job3.SetPedestals(job1.GetPedestalCam());
+        job3.SetBadPixels(job1.GetBadPixels());
+        job3.SetUseHists(kMoon);
+
+        if (!job3.ProcessFile())
+        {
+            gLog << err << "Calculation of pedestal from extractor failed." << endl << endl;
+            return -1;
+        }
+
+        if (!job3.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+
+        //
+        // Extract signal and calibrate it
+        //
+        MJCalibrateSignal job4(Form("MJCalibrateSignal #%d", seq.GetSequence()));
+        job4.SetSequence(seq);
+        job4.SetDisplay(d);;
+        job4.SetEnv(&env);
+        job4.SetEnvDebug(kDebugEnv);
+        job4.SetOverwrite(kOverwrite);
+        job4.SetPathIn(kInpathY);
+        job4.SetPathOut(kOutpathY);
+        job4.SetPathData(kInpathD);
+        job4.SetDataType(kDataType);
+        if (kDataType!=MJCalib::kIsUseMC)
+            job4.SetExtractor(job2.GetExtractor());
+
+        // Where to search for calibration files
+        if (!job4.ProcessFile(job1.GetPedestalCam(), job2.GetPedestalCam(), job3.GetPedestalCam()))
+            return -1;
+
+        if (kDebugEnv>0)
+            env.PrintUntouched();
+
+        if (!job4.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
+
Index: /tags/Mars-V0.9/callisto.rc
===================================================================
--- /tags/Mars-V0.9/callisto.rc	(revision 9772)
+++ /tags/Mars-V0.9/callisto.rc	(revision 9772)
@@ -0,0 +1,425 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                             Calibration
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJPedestal output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathOut: .
+#MJPedestalC2.PathOut: .
+#MJPedestalC1.BadPixelsFile: mjobs/badpixels_0_559.rc
+#MJPedestalC1.ReferenceFile: mjobs/pedestalref.rc
+#MJPedestalC2.ReferenceFile: mjobs/pedestalref.rc
+MJCalibration.ReferenceFile: mjobs/calibrationref_Nov04.rc
+MJCalibration.MHCalibrationRelTimeCam.ReferenceFile: mjobs/calibrationref_Nov04.rc
+MJCalibration.MHCalibrationChargeCam.ReferenceFile: mjobs/calibrationref_Nov04.rc
+
+# -------------------------------------------------------------------------
+# Use this to define where the calibration output is stored. The filename
+# is created from the sequence number. If nothing is specified '.' is
+# assumed. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJCalibration.PathOut: calped
+
+# -------------------------------------------------------------------------
+# Use this to define where the program should search for the pedestal
+# and calibration files defined in the sequence. To use the local
+# directory use '.' If nothing is specified the default path in the
+# datacenter is used. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJPedestalC1.PathData:   /data/MAGIC/Period016/
+#MJPedestalC2.PathData:   /data/MAGIC/Period016/
+#MJCalibration.PathData:  /data/MAGIC/Period016/
+
+# -------------------------------------------------------------------------
+# Define here which signal extractor you are going to use for the
+# whole calibration chain
+# -------------------------------------------------------------------------
+MJPedestalC1.ExtractSignal: MExtractTimeAndChargeDigitalFilter
+# -------------------------------------------------------------------------
+# Define here an extractor which can be used for the December 04 data.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal: MExtractTimeAndChargeSpline, MExtractTimeAndChargeDigitalFilterPeakSearch, MExtractTimeAndChargeSlidingWindow
+# -------------------------------------------------------------------------
+# Define here parameters valid for all extractors above
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.HiGainFirst:         0
+#MJPedestalC1.ExtractSignal.HiGainLast:         15
+#MJPedestalC1.ExtractSignal.LoGainFirst:         3
+#MJPedestalC1.ExtractSignal.LoGainLast:         14
+#MJPedestalC1.ExtractSignal.SaturationLimit:   250
+#MJPedestalC1.ExtractSignal.OffsetLoGain:     1.51
+#MJPedestalC1.ExtractSignal.LoGainSwitch:      150
+#MJPedestalC1.ExtractSignal.LoGainStartShift: -2.8
+# -------------------------------------------------------------------------
+# Define here parameters valid for the spline:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.Resolution:        0.05
+#MJPedestalC1.ExtractSignal.RiseTimeHiGain:    0.5
+#MJPedestalC1.ExtractSignal.FallTimeHiGain:    1.5
+#MJPedestalC1.ExtractSignal.LoGainStretch:     1.5
+#MJPedestalC1.ExtractSignal.ExtractionType: Integral <default>
+#MJPedestalC1.ExtractSignal.ExtractionType: Amplitude
+# -------------------------------------------------------------------------
+# Define here parameters valid for the sliding window:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.HiGainWindowSize:     6
+#MJPedestalC1.ExtractSignal.LoGainWindowSize:     6
+# -------------------------------------------------------------------------
+# Define here parameters valid for the digital filter with peak search:
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractSignal.OffsetLeftFromPeak:   3
+#MJPedestalC1.ExtractSignal.OffsetRightFromPeak:  3
+#MJPedestalC1.ExtractSignal.PeakSearchWindowSize: 2
+#MJPedestalC1.ExtractSignal.HiGainFailureLimit:  10
+#MJPedestalC1.ExtractSignal.LoGainFailureLimit:  25
+
+# -------------------------------------------------------------------------
+# In the case of the Digital filter you have to overwrite the default
+# weights file depending on what you are extracting
+# -------------------------------------------------------------------------
+MJPedestalC2.ExtractSignal.WeightsFile:          msignal/calibration_weights_UV46.dat
+MJPedestalY2.ExtractSignal.WeightsFile:          msignal/cosmics_weights46.dat
+MJPedestalY3.ExtractSignal.WeightsFile:          msignal/cosmics_weights46.dat
+MJCalibration.ExtractSignal.WeightsFile:         msignal/calibration_weights_UV46.dat
+MJCalibrateSignal.ExtractSignal.WeightsFile:     msignal/cosmics_weights46.dat
+MJCalibrateSignal.ExtractInterlaced.WeightsFile: msignal/calibration_weights_UV46.dat
+#MJCalibrateSignal.ExtractSignal.LoGainStretch:     1.5
+#MJCalibrateSignal.ExtractInterlaced.LoGainStretch: 1.5
+
+# -------------------------------------------------------------------------
+# Configure MJCalibration
+# -------------------------------------------------------------------------
+# Switch on relative time calibration
+#MJCalibration.RelTimeCalibration: Yes
+# Switch on intensity calibration
+#MJCalibration.IntensityCalibration: Yes
+# Set color to be used
+#MJCalibration.Color:
+# Type of used data format: raw, root, mc
+#MJCalibration.DataType: Root
+# Type of displayed plots: Full,DataCheck,Normal
+#MJCalibration.Display: datacheck
+# Write additinal debug output
+#MJCalibration.Debug: No
+# Use blind pixel
+#MJCalibration.UseBlindPixel: No
+# Use pin diode
+#MJCalibration.UsePINDiode: No
+# Use pixel check option
+#MJCalibration.PixelCheck: Yes
+#MJCalibTest.PixelCheck: Yes
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcPedRun use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC1.ExtractPedestal.CheckWinSize:     29
+
+#MJPedestalC2.ExtractPedestal: MPedCalcPedRun
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC2.ExtractPedestal.CheckWinSize:     29
+
+# -------------------------------------------------------------------------
+# You can choose the pedestal extraction algorithm/task. To use
+# MPedCalcFromLoGain use the lines below. Be carefull, a pedestal file
+# could be (if no pedestal file available) a data-file, too.
+# -------------------------------------------------------------------------
+#MJPedestalC1.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC1.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC1.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC1.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC1.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC1.ExtractPedestal.CheckWinSize:     29
+#MJPedestalC1.ExtractPedestal.MaxHiGainVar:     40
+
+#MJPedestalC2.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalC2.ExtractPedestal.ExtractWinFirst:    0
+#MJPedestalC2.ExtractPedestal.ExtractWinSize:     6
+#MJPedestalC2.ExtractPedestal.PedestalUpdate:    no
+#MJPedestalC2.ExtractPedestal.CheckWinFirst:     0
+#MJPedestalC2.ExtractPedestal.CheckWinSize:     29
+#MJPedestalC2.ExtractPedestal.MaxHiGainVar:     40
+
+# -------------------------------------------------------------------------
+# Configure MJPedestalC1 and MJPedestalC2
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalC1.DataType: Root
+#MJPedestalC2.DataType: Root
+#MJPedestalC3.DataType: Root
+# Type of displayed plots: Full,DataCheck,None
+#MJPedestalC1.Display: datacheck
+#MJPedestalC2.Display: datacheck
+#MJPedestalC3.Display: datacheck
+# Maximum number of event processed in the loop
+#MJPedestalC1.MaxEvents: 1000
+#MJPedestalC2.MaxEvents: 1000
+# Allow to overwrite existing files with the output file
+#MJPedestalC1.AllowOverwrite: No
+#MJPedestalC2.AllowOverwrite: No
+# Use data runs from the sequence instead of calibration runs
+#MJPedestalC1.UseData: No
+#MJPedestalC2.UseData: No
+
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the software low-gain switch in the
+# calibration
+# -------------------------------------------------------------------------
+MJCalibration.ExtractSignal.LoGainSwitch:     170
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the higain-vs. logain intercalibration
+# -------------------------------------------------------------------------
+#MJCalibration.HiLoCalibFile:    mjobs/hilocalib_df46.root
+#MJCalibration.HiLoCalibration:  yes
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the time extractor for the calibration
+# and automatically the data extraction
+# -------------------------------------------------------------------------
+#MJCalibration.ExtractTime: <dummy>
+#MJCalibration.ExtractTime: MExtractTimeFastSpline
+#MJCalibration.ExtractTime.HiGainFirst:       0
+#MJCalibration.ExtractTime.HiGainLast:        7
+#MJCalibration.ExtractTime.LoGainFirst:       3
+#MJCalibration.ExtractTime.LoGainLast:        8
+#MJCalibration.ExtractTime.WindowSizeHiGain:  6
+#MJCalibration.ExtractTime.WindowSizeLoGain:  6
+#MJCalibration.ExtractTime.OffsetLoGain:    1.51
+
+# -------------------------------------------------------------------------
+# Use this to change the behaviour of the calibration
+# -------------------------------------------------------------------------
+# Type if you set a colour explicitely from outside (only for MC!!!)
+#MJCalibration.MCalibColorSet.ExplicitColor: green,blue,uv,ct1
+
+#MJCalibration.MCalibrationChargeCalc.ChargeLimit:        2.5
+#MJCalibration.MCalibrationChargeCalc.ChargeErrLimit:     0
+#MJCalibration.MCalibrationChargeCalc.ChargeRelErrLimit:  1
+#MJCalibration.MCalibrationChargeCalc.Debug:              no
+
+#MJCalibration.MCalibrationChargeCalc.FFactorErrLimit:    4.5
+#MJCalibration.MCalibrationChargeCalc.LambdaErrLimit:     0.2
+#MJCalibration.MCalibrationChargeCalc.LambdaCheckLimit:   0.5
+#MJCalibration.MCalibrationChargeCalc.PheErrLimit:        3.5
+
+#MJCalibration.MHCalibrationChargeCam.Debug:        no
+#MJCalibration.MHCalibrationChargeCam.LoGain:       yes
+#MJCalibration.MHCalibrationChargeCam.Oscillations: yes
+#MJCalibration.MHCalibrationChargeCam.SizeCheck:    yes
+#MJCalibration.MHCalibrationChargeCam.Averageing:   yes
+#MJCalibration.MHCalibrationChargeCam.HiGainNbins:  500
+#MJCalibration.MHCalibrationChargeCam.HiGainFirst:  -100.125
+#MJCalibration.MHCalibrationChargeCam.HiGainLast:   1899.875
+#MJCalibration.MHCalibrationChargeCam.LoGainNbins:   500
+#MJCalibration.MHCalibrationChargeCam.LoGainFirst:  -100.25
+#MJCalibration.MHCalibrationChargeCam.LoGainLast:   899.75
+#MJCalibration.MHCalibrationChargeCam.TimeLowerLimit: 1. 
+#MJCalibration.MHCalibrationChargeCam.TimeUpperLimit: 3. 
+#MJCalibration.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibration.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+#MJCalibration.MHCalibrationChargeCam.ProbLimit:     0.00000001
+#MJCalibration.MHCalibrationChargeCam.OverflowLimit: 0.005
+#MJCalibration.MHCalibrationChargeCam.PulserFrequency: 500
+
+#MJCalibration.MHCalibrationRelTimeCam.Debug:        no
+#MJCalibration.MHCalibrationRelTimeCam.LoGain:       no
+#MJCalibration.MHCalibrationRelTimeCam.Oscillations:  yes
+#MJCalibration.MHCalibrationRelTimeCam.SizeCheck:    yes
+#MJCalibration.MHCalibrationRelTimeCam.Averageing:   yes
+#MJCalibration.MHCalibrationRelTimeCam.HiGainNbins:  210
+#MJCalibration.MHCalibrationRelTimeCam.HiGainFirst:  -5.
+#MJCalibration.MHCalibrationRelTimeCam.HiGainLast:   10.
+#MJCalibration.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibration.MHCalibrationRelTimeCam.ProbLimit:    0.00001
+#MJCalibration.MHCalibrationRelTimeCam.OverflowLimit: 0.005
+#MJCalibration.MHCalibrationRelTimeCam.PulserFrequency: 500
+
+ 
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                            Signal extraction
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use a OutputPath if you want to write the results to a file
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.PathOut:  .
+#MJPedestalY1.PathOut:        .
+#MJPedestalY2.PathOut:        .
+#MJPedestalY3.PathOut:        .
+#MJPedestalY1.PathData:      /data/MAGIC/Period016/
+#MJPedestalY2.PathData:      /data/MAGIC/Period016/
+#MJPedestalY3.PathData:      /data/MAGIC/Period016/
+#MJCalibrateSignal.PathData: /data/MAGIC/Period016/
+#MJCalibrateSignal.PathIn:   .
+
+# -------------------------------------------------------------------------
+# If you want to change the behaviour of the pedestal extraction...
+# -------------------------------------------------------------------------
+# Possible data type: Raw,Root,MC
+#MJPedestalY1.DataType: Root
+#MJPedestalY2.DataType: Root
+#MJPedestalY3.DataType: Root
+#MJPedestalY1.UseData: Yes
+#MJPedestalY2.UseData: Yes
+#MJPedestalY3.UseData: Yes
+MJPedestalY1.MaxEvents: 500
+MJPedestalY2.MaxEvents: 2000
+MJPedestalY3.MaxEvents: 500
+
+# -------------------------------------------------------------------------
+# Use Pulse Position check to define the extraction ranges for the data?
+# -------------------------------------------------------------------------
+#MJPedestalY2.PulsePosCheck: yes
+#MJPedestalY2.ExtractWinLeft:  2.5
+#MJPedestalY2.ExtractWinRight: 4.5
+
+# -------------------------------------------------------------------------
+# Define the Pulse Position check parameters:
+# -------------------------------------------------------------------------
+#MJPedestalY2.MHCalibrationPulseTimeCam.SaturationLimit:  255
+#MJPedestalY2.MHCalibrationPulseTimeCam.LowerSignalLimit: 100
+#MJPedestalY2.MHCalibrationPulseTimeCam.NumPixelsRequired: 2
+#MJPedestalY2.PixelCheck: no
+
+#MJPedestalY.ExtractPedestal: MPedCalcFromLoGain
+#MJPedestalY.ExtractPedestal.PedestalUpdate:   no
+
+# -------------------------------------------------------------------------
+# Setup pedestal extractor for running through data
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MPedCalcFundamental.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFundamental.NumEventsDump:   1500
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinFirst:  17
+#MJCalibrateSignal.MPedCalcFundamental.ExtractWinSize:    6
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinFirst:     0
+#MJCalibrateSignal.MPedCalcFundamental.CheckWinSize:     29
+#MJCalibrateSignal.MPedCalcFundamental.MaxHiGainVar:     40
+
+#MJCalibrateSignal.MPedCalcFromExtractor.PedestalUpdate:   yes
+#MJCalibrateSignal.MPedCalcFromExtractor.NumEventsDump:   1500
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinFirst:  17
+#MJCalibrateSignal.MPedCalcFromExtractor.ExtractWinSize:    6
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinFirst:     0
+#MJCalibrateSignal.MPedCalcFromExtractor.CheckWinSize:     29
+#MJCalibrateSignal.MPedCalcFromExtractor.MaxHiGainVar:     40
+
+# -------------------------------------------------------------------------
+# Use this if you want to change to time from run headers instead of event time
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MPointingPosInterpolate.TimeMode: eventtime, runtime
+
+# -------------------------------------------------------------------------
+# Use this if you want to change the signal extractor
+# -------------------------------------------------------------------------
+MJCalibrateSignal.ExtractSignal.LoGainSwitch:    150
+
+# -------------------------------------------------------------------------
+# Setup calibration of data
+# -------------------------------------------------------------------------
+# Type of used data format: raw,root,MC
+#MJCalibrateSignal.DataType: Root
+# Type if you set a colour explicitely from outside (only for MC!!!)
+#MJCalibrateSignal.MCalibColorSet.ExpicitColor: green,blue,uv,ct1
+#MJCalibrateSignal.MCalibrateData.PedestalFlag: Event
+#MJCalibrateSignal.MCalibrateData.CalibrationMode: Default
+#MJCalibrateSignal.MCalibrateData.CalibConvMinLimit: 0.01
+#MJCalibrateSignal.MCalibrateData.CalibConvMaxLimit: 5.
+#MJCalibrateSignal.Interlaced: yes
+#MJCalibrateSignal.RelTimesUpdate: no
+#MJCalibrateSignal.HiLoCalibration: no
+#MJCalibrateSignal.PulsePosCheck: yes
+
+# -------------------------------------------------------------------------
+# Setup level for determining of bad pixels
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevel:         3.0
+#MJCalibrateSignal.MBadPixelsCalc.PedestalLevelVariance: 3.0
+#MJCalibrateSignal.MBadPixelsTreat.NumMinNeighbors:    3
+#MJCalibrateSignal.MBadPixelsTreat.UseInterpolation:   yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalEvt: yes
+#MJCalibrateSignal.MBadPixelsTreat.ProcessPedestalRun: no
+#MJCalibrateSignal.MBadPixelsTreat.ProcessTimes:       yes
+#MJCalibrateSignal.MBadPixelsTreat.UseCentralPixel:    no
+#MJCalibrateSignal.MBadPixelsTreat.HardTreatment:      no
+
+# -------------------------------------------------------------------------
+# Setup interlaced calibration events histogramming
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationChargeCam.Debug:        no
+#MJCalibrateSignal.MHCalibrationChargeCam.LoGain:       yes
+MJCalibrateSignal.MHCalibrationChargeCam.Oscillations:  no
+#MJCalibrateSignal.MHCalibrationChargeCam.SizeCheck:    yes
+#MJCalibrateSignal.MHCalibrationChargeCam.Averageing:   yes
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainNbins:  500
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainFirst:  -100.5
+#MJCalibrateSignal.MHCalibrationChargeCam.HiGainLast:   1899.5
+MJCalibrateSignal.MHCalibrationChargeCam.LoGainNbins:   250
+#MJCalibrateSignal.MHCalibrationChargeCam.LoGainFirst:  -100.5
+#MJCalibrateSignal.MHCalibrationChargeCam.LoGainLast:   899.5
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeLowerLimit: 1. 
+#MJCalibrateSignal.MHCalibrationChargeCam.TimeUpperLimit: 3. 
+#MJCalibrateSignal.MHCalibrationChargeCam.NumHiGainSaturationLimit: 0.02
+#MJCalibrateSignal.MHCalibrationChargeCam.NumLoGainSaturationLimit: 0.005 
+#MJCalibrateSignal.MHCalibrationChargeCam.ProbLimit:    0.0001
+#MJCalibrateSignal.MHCalibrationChargeCam.OverflowLimit: 0.005
+MJCalibrateSignal.MHCalibrationChargeCam.PulserFrequency: 50
+
+# -------------------------------------------------------------------------
+# Setup relative time interlaced calibration
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Debug:        no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.LoGain:       no
+MJCalibrateSignal.MHCalibrationRelTimeCam.Oscillations:  no
+#MJCalibrateSignal.MHCalibrationRelTimeCam.SizeCheck:    yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.Averageing:   yes
+#MJCalibrateSignal.MHCalibrationRelTimeCam.HiGainNbins:  210
+#MJCalibrateSignal.MHCalibrationRelTimeCam.HiGainFirst:  -5.
+#MJCalibrateSignal.MHCalibrationRelTimeCam.HiGainLast:   10.
+#MJCalibrateSignal.MHCalibrationRelTimeCam.NumHiGainSaturationLimit: 0.25
+#MJCalibrateSignal.MHCalibrationRelTimeCam.ProbLimit:    0.00001
+#MJCalibrateSignal.MHCalibrationRelTimeCam.OverflowLimit: 0.005
+MJCalibrateSignal.MHCalibrationRelTimeCam.PulserFrequency: 50
+
+# -------------------------------------------------------------------------
+# This is a special option for the datacheck. A task executed as last
+# task in the event processing task list - in the standard software it
+# is skipped
+# -------------------------------------------------------------------------
+#MJCalibrateSignal.FinalFantasy: MHCamFlorian
Index: /tags/Mars-V0.9/ganymed.cc
===================================================================
--- /tags/Mars-V0.9/ganymed.cc	(revision 9772)
+++ /tags/Mars-V0.9/ganymed.cc	(revision 9772)
@@ -0,0 +1,259 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TGClient.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MDirIter.h"
+
+#include "MStatusDisplay.h"
+
+#include "MDataSet.h"
+#include "MJCut.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "========================================================" << endl;
+    gLog << "                  Ganymed - MARS V" << MARSVER            << endl;
+    gLog << "   MARS -- Gammas Are Now Your Most Exciting Discovery"   << endl;
+    gLog << "               Compiled on <" << __DATE__ << ">"          << endl;
+    gLog << "                  Using ROOT v" << ROOTVER                << endl;
+    gLog << "========================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " ganymed [-c] [-y] [options] sequences.txt" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   dataset.txt:              Ascii file defining a collection of sequences" << endl;
+    gLog << "                             For more details see MDataSet." << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Operation Mode:" << endl;
+    gLog << "   --wobble                  Wobble Mode" << endl << endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    gLog << "   --debug-env=3             Debug setting resources from resource file" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   --n=[n]                   Analysis number" << endl;
+    gLog << "   --out=path                Path to write the all output to [def=local path]" << endl;
+    gLog << "   --outf=filename           Filename for output file (eg. status display)" << endl;
+    gLog << "   --sum[=filename]          Enable writing of summary file (events after cut0)" << endl;
+    gLog << "   --res[=filename]          Enable writing of result file (surviving events)" << endl;
+    gLog << "   --write-only              Only write output files. No histograms filled." << endl;
+    gLog << "   --print-ds                Print Dataset information" << endl;
+    gLog << "   --print-files             Print Files taken from Sequences ('+' found, '-' missing)" << endl;
+    gLog << "   --config=ganymed.rc       Resource file [default=ganymed.rc]" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << "Background:" << endl;
+    gLog << " Ganymed is the largest moon of Jupiter, a large, icy, outer moon that" << endl;
+    gLog << " is scarred  with impact craters  and  many parallel faults.  It has a" << endl;
+    gLog << " diameter of about  5268km  and orbits  Jupiter  at a mean distance of" << endl;
+    gLog << " 1,070,000km.  It has a magnetic field  and probably has a molten iron" << endl;
+    gLog << " core.  It takes  Ganymed  7.15 days to  orbit  Jupiter.  Its mass  is" << endl;
+    gLog << " 1.5e23kg. It was independently discovered by  Galileo and S.Marius in"<< endl;
+    gLog << " 1610.  Ganymed is  the largest moon  in the solar system;  it is also" << endl;
+    gLog << " larger than the planets Mercury and Pluto." << endl << endl;
+}
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv, kTRUE);
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    gLog.Setup(arg);
+
+    const TString kConfig       = arg.GetStringAndRemove("--config=", "ganymed.rc");
+
+    const Bool_t  kPrintSeq     = arg.HasOnlyAndRemove("--print-ds");
+    const Bool_t  kPrintFiles   = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kDebugMem     = arg.HasOnlyAndRemove("--debug-mem");
+    const Bool_t  kWriteOnly    = arg.HasOnlyAndRemove("--write-only");
+    Int_t  kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit         = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch        = arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite    = arg.HasOnlyAndRemove("-f");
+    //const Bool_t  kForceExec  = arg.HasOnlyAndRemove("-ff");
+
+    const Bool_t  kModeWobble   = arg.HasOnlyAndRemove("--wobble");
+
+    const Int_t   kNumAnalysis  = arg.GetIntAndRemove("--n=", -1);
+    const TString kOutpath      = arg.GetStringAndRemove("--out=",  ".");
+    const TString kOutfile      = arg.GetStringAndRemove("--outf=",  "");
+    const Bool_t  kWriteSummary = arg.HasOnlyAndRemove("--sum");
+    const TString kNameSummary  = arg.GetStringAndRemove("--sum=");
+    const Bool_t  kWriteResult  = arg.HasOnlyAndRemove("--res");
+    const TString kNameResult   = arg.GetStringAndRemove("--res=");
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Setup sequence file and check for its existance
+    //
+    const TString kSequences = arg.GetArgumentStr(0);
+
+    if (gSystem->AccessPathName(kSequences, kFileExists))
+    {
+        gLog << err << "Sorry, sequences file '" << kSequences << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    if (gSystem->AccessPathName(kConfig, kFileExists))
+    {
+        gLog << err << "Sorry, config file '" << kConfig << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Setup sequence and check its validity
+    //
+    MDataSet seq(kSequences);
+    if (kNumAnalysis>=0)
+        seq.SetNumAnalysis(kNumAnalysis);
+    if (kPrintSeq || kPrintFiles)
+    {
+        gLog << all;
+        gLog.Separator(kSequences);
+        seq.Print(kPrintFiles?"files":"");
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Sequences read but not valid!" << endl << endl;
+        return -1;
+    }
+
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("Ganymed", &argc, argv);
+    if (!gROOT->IsBatch() && !gClient || gROOT->IsBatch() && !kBatch)
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(kSequences);
+
+    //
+    // Calculate pedestal for pedestal-calculation and calibration
+    //
+    MEnv env(kConfig);
+
+    MJCut job(Form("MJCut #%d", seq.GetNumAnalysis()));
+    job.SetEnv(&env);
+    job.SetEnvDebug(kDebugEnv);
+    job.SetDisplay(d);;
+    job.SetOverwrite(kOverwrite);
+    job.SetPathOut(kOutpath);
+    job.SetNameOutFile(kOutfile);
+    job.SetNameSummaryFile(kNameSummary);
+    job.SetNameResultFile(kNameResult);
+    job.EnableWriteOnly(kWriteOnly);
+    job.EnableWobbleMode(kModeWobble);
+    if (kWriteSummary) // Don't change flag set in SetNameSummaryFile
+        job.EnableStorageOfSummary();
+    if (kWriteResult)  // Don't change flag set in SetNameSummaryFile
+        job.EnableStorageOfResult();
+
+    if (!job.ProcessFile(seq))
+    {
+        gLog << err << "Calculation of cuts failed." << endl << endl;
+        return -1;
+    }
+    if (kDebugEnv>0)
+        env.PrintUntouched();
+
+    if (!job.GetDisplay())
+    {
+        gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+        return 1;
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: /tags/Mars-V0.9/ganymed.rc
===================================================================
--- /tags/Mars-V0.9/ganymed.rc	(revision 9772)
+++ /tags/Mars-V0.9/ganymed.rc	(revision 9772)
@@ -0,0 +1,119 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                               Cuts
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write output to somewhere here you can give
+# the output path
+# -------------------------------------------------------------------------
+#MJCuts.PathOut: .
+
+# -------------------------------------------------------------------------
+# Use this to setup binnings. For more details see: MBinning::ReadEnv
+# -------------------------------------------------------------------------
+#BinningAlpha.Raw:        9   0    90
+#BinningFalseSource.Raw: 30  -1.2  1.2
+#BinningEnergyEst.Raw:   25   10   1000000 log
+#BinningTheta.Raw:       50   0    60      cos
+
+# -------------------------------------------------------------------------
+# Setup fit mode and ranges
+# -------------------------------------------------------------------------
+#MAlphaFitter.SignalIntegralMax:    15
+#MAlphaFitter.SignalFitMax:         25
+#MAlphaFitter.BackgroundFitMin:     35
+#MAlphaFitter.BackgroundFitMax:     75
+#MAlphaFitter.ScaleMin:             35
+#MAlphaFitter.ScaleMax:             80
+#MAlphaFitter.PolynomOrder:         2
+#/*MISSING*/ ScaleMode
+
+# -------------------------------------------------------------------------
+# There are three cuts:
+#   Cut0: After energy estimation, before writing summary file
+#   Cut1: After writing summary file before filling false source plots
+#   Cut2: After filling false source plots before filling alpha plots
+#   Cut3: After filling alpha plots (eg. Alpha cuts) for image parameter
+#         display
+# -------------------------------------------------------------------------
+Cut0.Inverted: Yes
+Cut1.Inverted: Yes
+Cut2.Inverted: Yes
+Cut3.Inverted: Yes
+
+#Cut0.Condition: MCameraCooling.fTempCenter < 55
+
+# Get rid of triangular events...
+Cut0.Condition: {0}
+Cut0.0:  0.33 * log10(MHillas.fSize) < 1.05 - log10(MNewImagePar.fConc)
+
+# If you could setup MFEventSelector by resource file you could use it here
+# To produce trainings and test sample use:  "{MMcEvt.fEvtNumber%2}>0.5"
+#Cut1.Condition: <MFSupercuts>
+#Cut1.Param0:  0.056
+#Cut1.Param8:  0.222
+#Cut1.Param16: 0.042
+#Cut1.Param24: 0.087
+#Cut1.Param32: 0.33
+
+Cut1.Condition: {0} && {1} && {2} && {3} && {4}
+
+Cut1.0: MHillas.fLength*MGeomCam.fConvMm2Deg > 0.0063*log10(MHillas.fSize)+0.0974
+Cut1.1: MHillas.fLength*MGeomCam.fConvMm2Deg < 0.0040*log10(MHillas.fSize)+0.1791
+Cut1.2: MHillas.fWidth *MGeomCam.fConvMm2Deg > 0.0067*log10(MHillas.fSize)+0.0511
+Cut1.3: MHillas.fWidth *MGeomCam.fConvMm2Deg < 0.0050*log10(MHillas.fSize)+0.1203
+Cut1.4: MHillas.fSize>95
+
+Cut2.Condition: MHillasSrc.fDist*MGeomCam.fConvMm2Deg>0.55
+
+Cut3.Condition: abs(MHillasSrc.fAlpha)<10
+
+# -------------------------------------------------------------------------
+# Setup cuts in false source plot
+# -------------------------------------------------------------------------
+MHFalseSource.DistMin: 0.55
+#MHFalseSource.DistMax: 0.55
+#MHFalseSource.DWMin: 0.55
+#MHFalseSource.DWMax: 0.55
+
+# -------------------------------------------------------------------------
+# Energy Estimation
+# -------------------------------------------------------------------------
+
+#EstimateEnergy: MEnergyEstimate
+EstimateEnergy.Rule: {0} + {1} + {2} + {3} + {4} + {5}
+EstimateEnergy.0:  6.3
+EstimateEnergy.1:  0.04*MHillasSrc.fDist*MGeomCam.fConvMm2Deg
+EstimateEnergy.2: -0.13*MHillas.fLength*MGeomCam.fConvMm2Deg
+EstimateEnergy.3:  0.15*MHillas.fSize
+EstimateEnergy.4:  0.0000519*MHillas.fSize*MHillasSrc.fDist*MGeomCam.fConvMm2Deg
+EstimateEnergy.5:  0.0000519*MHillas.fLength*MGeomCam.fConvMm2Deg*MHillasSrc.fDist*MGeomCam.fConvMm2Deg
+
+
+# -------------------------------------------------------------------------
+# Use this to executa a task (eg to calc hadronness) after energy
+# before Cut1
+# -------------------------------------------------------------------------
+# CalcHadronness: MRanForestCalc
+# CalcHadronness.File: /home/tbretz/Mars.cvs/RFspot3cmAll.root
+# CalcHadronness.Debug: No
Index: /tags/Mars-V0.9/lib/lib.txt
===================================================================
--- /tags/Mars-V0.9/lib/lib.txt	(revision 9772)
+++ /tags/Mars-V0.9/lib/lib.txt	(revision 9772)
@@ -0,0 +1,1 @@
+Directory for libraries while compiling
Index: /tags/Mars-V0.9/macros/CCDataCheck.C
===================================================================
--- /tags/Mars-V0.9/macros/CCDataCheck.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/CCDataCheck.C	(revision 9772)
@@ -0,0 +1,1456 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Raquel de los Reyes, 02/2004 <mailto:reyes@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== *//////////////////////////////////////////////////////////////////////////////
+//
+// This macro made the check of the central control files (.rep files).
+// It displays 9 tabs:
+//   - Drive system
+//   - Camera status
+//   - HV of power supplies and HV settings
+//   - DC of power supplies 
+//   - LV power supplies
+//   - Cooling system
+//   - Trigger system
+//   - Trigger macrocells
+//   - Weather station
+//
+////////////////////////////////////////////////////////////////////////////
+
+void CCDataCheck(const TString filename="CC_2004_04_28.root", const TString directory="/home/raquel/")
+{
+
+  //
+  // If you want to run the macro in batch mode, set batchmode to kTRUE
+  //
+  Bool_t batchmode = kFALSE;
+
+  if(!batchmode)
+    {
+      MStatusDisplay *d = new MStatusDisplay;
+      d->SetTitle(filename);
+      d->SetLogStream(&gLog, kTRUE);            // Disables output to stdout
+    }
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Set all the MHVsTime classes:
+  // Drive system
+  MHVsTime hZd("MReportDrive.fNominalZd");
+  hZd.SetName("Zd");
+  MHVsTime hAz("MReportDrive.fNominalAz");
+  hAz.SetName("Az");
+  MHVsTime hDState("MReportDrive.fState");
+  hDState.SetName("State");
+  // HV power supplies
+  MHVsTime hHVA("MCameraHV.fVoltageA");
+  hHVA.SetName("HVA");
+  MHVsTime hHVB("MCameraHV.fVoltageB");
+  hHVB.SetName("HVB");
+  MHVsTime hCA("MCameraHV.fCurrentA");
+  hCA.SetName("CA");
+  MHVsTime hCB("MCameraHV.fCurrentB");
+  hCB.SetName("CB");
+  // LV power supplies
+  MHVsTime hLVTemp("MCameraLV.fTemp");
+  hLVTemp.SetName("LVTemp");
+  MHVsTime hLVHum("MCameraLV.fHumidity");
+  hLVHum.SetName("LVHum");
+  MHVsTime hLVStatus("MCameraHV.fStatus");
+  hLVStatus.SetName("LVStatus");
+  MHVsTime hLVRPS("MCameraLV.fRequestPowerSupply");
+  hLVRPS.SetName("LVRPS");
+  // Cooling system
+  MHVsTime hTCenter("MCameraCooling.fTempCenter");
+  hTCenter.SetName("TCenter");
+  MHVsTime hTWall("MCameraCooling.fTempWall");
+  hTWall.SetName("TWall");
+  MHVsTime hTWater("MCameraCooling.fTempWater");
+  hTWater.SetName("TWater");
+  MHVsTime hTOptLink("MCameraCooling.fTempOptLink");
+  hTOptLink.SetName("TOptLink");
+  MHVsTime hHWall("MCameraCooling.fHumWall");
+  hHWall.SetName("HWall");
+  MHVsTime hHCenter("MCameraCooling.fHumCenter");
+  hHCenter.SetName("HCenter");
+  // Weather station
+  MHVsTime hCCHum("MReportCC.fHumidity");
+  hCCHum.SetName("CCHum");
+  MHVsTime hCCTemp("MReportCC.fTemperature");
+  hCCTemp.SetName("CCTemp");
+  MHVsTime hCCWS("MReportCC.fWindSpeed");
+  hCCWS.SetName("CCWS");
+  MHVsTime hCCSR("MReportCC.fSolarRadiation");
+  hCCSR.SetName("CCSR");
+  // Trigger system
+  MHVsTime hTrigBL2("MReportTrigger.fL2BeforePrescaler");
+  hTrigBL2.SetName("TrigBL2");
+  MHVsTime hTrigAL2("MReportTrigger.fL2AfterPrescaler");
+  hTrigAL2.SetName("TrigAL2");
+  MHVsTime hTrigStatus("MReportTrigger.fState");
+  hTrigStatus.SetName("TrigStatus");
+  // Camera status
+  MHVsTime hCamStatus("MReportCamera.fState");
+  hCamStatus.SetName("CamStatus");
+  MHVsTime hCamSentStatus("MReportCamera.fStatus");
+  hCamSentStatus.SetName("CamSentStatus");
+  MHVsTime hCamStatusDC("MReportCamera.fStatusDC");
+  hCamStatusDC.SetName("CamDCStatus");
+  MHVsTime hHVStatus("MCameraHV.fStatus");
+  hHVStatus.SetName("HVStatus");
+  MHVsTime hLidsStatus("MCameraLids.fStatus");
+  hLidsStatus.SetName("LidsStatus");
+  MHVsTime hCoolStatus("MCameraCooling.fStatus");
+  hCoolStatus.SetName("CoolingStatus");
+  MHVsTime hCamMean("MCameraHV.fMean");
+  hCamMean.SetName("CameraMean");
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Drive");
+  read.AddTree("Camera");
+  read.AddTree("CC");
+  read.AddTree("Trigger");
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportDrive.*");
+  read.AddToBranchList("MCameraHV.*");
+  read.AddToBranchList("MCameraLV.*");
+  read.AddToBranchList("MCameraCooling.*");
+  read.AddToBranchList("MReportCC.*");
+  read.AddToBranchList("MReportTrigger.*");
+  read.AddToBranchList("MReportCamera.*");
+  read.AddToBranchList("MCameraLids.*");
+
+  MGeomApply geomapl;
+  tlist.AddToList(&geomapl);
+
+  // Set of MHCamEvents classes
+  MHCamEvent HVdisplay("CamHV","Camera mean HV settings");
+  HVdisplay.SetBit(MHCamera::kVariance);
+  plist.AddToList(&HVdisplay);
+
+  // Set of MHPixVsTime classes (Trigger macroscells)
+  MHPixVsTime htrigmc1(0,"TrigMacrocell1");
+  htrigmc1.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc1);
+  MHPixVsTime htrigmc2(1,"TrigMacrocell2");
+  htrigmc2.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc2);
+  MHPixVsTime htrigmc3(2,"TrigMacrocell3");
+  htrigmc3.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc3);
+  MHPixVsTime htrigmc4(3,"TrigMacrocell4");
+  htrigmc4.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc4);
+  MHPixVsTime htrigmc5(4,"TrigMacrocell5");
+  htrigmc5.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc5);
+  MHPixVsTime htrigmc6(5,"TrigMacrocell6");
+  htrigmc6.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc6);
+  MHPixVsTime htrigmc7(6,"TrigMacrocell7");
+  htrigmc7.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc7);
+  MHPixVsTime htrigmc8(7,"TrigMacrocell8");
+  htrigmc8.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc8);
+  MHPixVsTime htrigmc9(8,"TrigMacrocell9");
+  htrigmc9.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc9);
+  MHPixVsTime htrigmc10(9,"TrigMacrocell10");
+  htrigmc10.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc10);
+  MHPixVsTime htrigmc11(10,"TrigMacrocell11");
+  htrigmc11.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc11);
+  MHPixVsTime htrigmc12(11,"TrigMacrocell12");
+  htrigmc12.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc12);
+  MHPixVsTime htrigmc13(12,"TrigMacrocell13");
+  htrigmc13.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc13);
+  MHPixVsTime htrigmc14(13,"TrigMacrocell14");
+  htrigmc14.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc14);
+  MHPixVsTime htrigmc15(14,"TrigMacrocell15");
+  htrigmc15.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc15);
+  MHPixVsTime htrigmc16(15,"TrigMacrocell16");
+  htrigmc16.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc16);
+  MHPixVsTime htrigmc17(16,"TrigMacrocell17");
+  htrigmc17.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc17);
+  MHPixVsTime htrigmc18(17,"TrigMacrocell18");
+  htrigmc18.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc18);
+  MHPixVsTime htrigmc19(18,"TrigMacrocell19");
+  htrigmc19.SetNameTime("MTimeTrigger");
+  plist.AddToList(&htrigmc19);
+
+  // Set of MH3 classes
+  MH3 hError("MReportDrive.GetAbsError*60");
+  hError.SetName("DeltaH");
+  MBinning bins("BinningDeltaH");
+  bins.SetEdges(18, 0, 3.6);
+  plist.AddToList(&bins);
+  MH3 hError2("MReportDrive.fNominalZd","MReportDrive.GetAbsError*60");
+  hError2.SetName("DeltaHvsZd");
+  MBinning bins2("BinningDeltaHvsZdX");
+  MBinning bins3("BinningDeltaHvsZdY");
+  bins2.SetEdges(90, 0, 90);
+  bins3.SetEdges(18, 0, 3.6);
+  plist.AddToList(&bins2);
+  plist.AddToList(&bins3);
+  MH3 hTempOptLink("MCameraCooling.fTempOptLink");
+  hTempOptLink.SetName("TOptLink");
+  MBinning bins4("BinningTOptLinkX");
+  bins4.SetEdges(50, 0, 50);
+  plist.AddToList(&bins4);
+  MH3 hTrigZd("MReportDrive.fNominalZd","MReportTrigger.fL2AfterPrescaler");
+  hTrigZd.SetName("TrigZd");
+  MBinning bins5("BinningTrigZdX");
+  bins5.SetEdges(90, 0, 90);
+  plist.AddToList(&bins5);
+  MBinning bins6("BinningTrigZdY");
+  bins6.SetEdges(10000, 0, 15000);
+  plist.AddToList(&bins6);
+
+
+  // Fill all the MH classes defined before
+  MFillH fillZd(&hZd,             "MTimeDrive");
+  MFillH fillAz(&hAz,             "MTimeDrive");
+  MFillH fillError(&hError);
+  MFillH fillDState(&hDState,     "MTimeDrive");
+  MFillH fillError2(&hError2);
+  MFillH fillHVA(&hHVA,           "MTimeCamera");
+  MFillH fillHVB(&hHVB,           "MTimeCamera");
+  MFillH fillCA(&hCA,             "MTimeCamera");
+  MFillH fillCB(&hCB,             "MTimeCamera");
+  MFillH fillLVTemp(&hLVTemp,     "MTimeCamera");
+  MFillH fillLVHum(&hLVHum,       "MTimeCamera");
+  MFillH fillLVStatus(&hLVStatus, "MTimeCamera");
+  MFillH fillLVRPS(&hLVRPS,       "MTimeCamera");
+  MFillH fillTCenter(&hTCenter,   "MTimeCamera");
+  MFillH fillTWall(&hTWall,       "MTimeCamera");
+  MFillH fillTWater(&hTWater,     "MTimeCamera");
+  MFillH fillTOptLink(&hTOptLink, "MTimeCamera");
+  MFillH fillTempOptLink(&hTempOptLink);
+  MFillH fillHWall(&hHWall,       "MTimeCamera");
+  MFillH fillHCenter(&hHCenter,   "MTimeCamera");
+  MFillH fillCCHum(&hCCHum,       "MTimeCC");
+  MFillH fillCCTemp(&hCCTemp,     "MTimeCC");
+  MFillH fillCCWS(&hCCWS,         "MTimeCC");
+  MFillH fillCCSR(&hCCSR,         "MTimeCC");
+  MFillH fillTrigBL2(&hTrigBL2,   "MTimeTrigger");
+  MFillH fillTrigAL2(&hTrigAL2,   "MTimeTrigger");
+  MFillH fillTrigStatus(&hTrigStatus,   "MTimeTrigger");
+  MFillH fillTrigZd(&hTrigZd);
+  MFillH fillCamStatus(&hCamStatus,"MTimeCamera");
+  MFillH fillCamSentStatus(&hCamSentStatus,"MTimeCamera");
+  MFillH fillCamStatusDC(&hCamStatusDC, "MTimeCamera");
+  MFillH fillHVStatus(&hHVStatus, "MTimeCamera");
+  MFillH fillLidsStatus(&hLidsStatus, "MTimeCamera");
+  MFillH fillCoolStatus(&hCoolStatus, "MTimeCamera");
+  MFillH filltrigmc1("TrigMacrocell1","MReportTrigger");
+  MFillH filltrigmc2("TrigMacrocell2","MReportTrigger");
+  MFillH filltrigmc3("TrigMacrocell3","MReportTrigger");
+  MFillH filltrigmc4("TrigMacrocell4","MReportTrigger");
+  MFillH filltrigmc5("TrigMacrocell5","MReportTrigger");
+  MFillH filltrigmc6("TrigMacrocell6","MReportTrigger");
+  MFillH filltrigmc7("TrigMacrocell7","MReportTrigger");
+  MFillH filltrigmc8("TrigMacrocell8","MReportTrigger");
+  MFillH filltrigmc9("TrigMacrocell9","MReportTrigger");
+  MFillH filltrigmc10("TrigMacrocell10","MReportTrigger");
+  MFillH filltrigmc11("TrigMacrocell11","MReportTrigger");
+  MFillH filltrigmc12("TrigMacrocell12","MReportTrigger");
+  MFillH filltrigmc13("TrigMacrocell13","MReportTrigger");
+  MFillH filltrigmc14("TrigMacrocell14","MReportTrigger");
+  MFillH filltrigmc15("TrigMacrocell15","MReportTrigger");
+  MFillH filltrigmc16("TrigMacrocell16","MReportTrigger");
+  MFillH filltrigmc17("TrigMacrocell17","MReportTrigger");
+  MFillH filltrigmc18("TrigMacrocell18","MReportTrigger");
+  MFillH filltrigmc19("TrigMacrocell19","MReportTrigger");
+  MFillH fillcammean(&hCamMean,"MTimeCamera");
+  MFillH fillHVD(&HVdisplay,"MCameraHV");
+
+  // Do not display the result given by the default draw function
+  fillZd.SetBit(MFillH::kDoNotDisplay);
+  fillAz.SetBit(MFillH::kDoNotDisplay);
+  fillError.SetBit(MFillH::kDoNotDisplay);
+  fillDState.SetBit(MFillH::kDoNotDisplay);
+  fillError2.SetBit(MFillH::kDoNotDisplay);
+  fillHVA.SetBit(MFillH::kDoNotDisplay);
+  fillHVB.SetBit(MFillH::kDoNotDisplay);
+  fillCA.SetBit(MFillH::kDoNotDisplay);
+  fillCB.SetBit(MFillH::kDoNotDisplay);
+  fillLVTemp.SetBit(MFillH::kDoNotDisplay);
+  fillLVHum.SetBit(MFillH::kDoNotDisplay);
+  fillLVStatus.SetBit(MFillH::kDoNotDisplay);
+  fillLVRPS.SetBit(MFillH::kDoNotDisplay);
+  fillTCenter.SetBit(MFillH::kDoNotDisplay);
+  fillTWall.SetBit(MFillH::kDoNotDisplay);
+  fillTWater.SetBit(MFillH::kDoNotDisplay);
+  fillTOptLink.SetBit(MFillH::kDoNotDisplay);
+  fillTempOptLink.SetBit(MFillH::kDoNotDisplay);
+  fillHWall.SetBit(MFillH::kDoNotDisplay);
+  fillHCenter.SetBit(MFillH::kDoNotDisplay);
+  fillCCHum.SetBit(MFillH::kDoNotDisplay);
+  fillCCTemp.SetBit(MFillH::kDoNotDisplay);
+  fillCCWS.SetBit(MFillH::kDoNotDisplay);
+  fillCCSR.SetBit(MFillH::kDoNotDisplay);
+  fillTrigBL2.SetBit(MFillH::kDoNotDisplay);
+  fillTrigAL2.SetBit(MFillH::kDoNotDisplay);
+  fillTrigStatus.SetBit(MFillH::kDoNotDisplay);
+  fillTrigZd.SetBit(MFillH::kDoNotDisplay);
+  fillCamStatus.SetBit(MFillH::kDoNotDisplay);
+  fillCamSentStatus.SetBit(MFillH::kDoNotDisplay);
+  fillCamStatusDC.SetBit(MFillH::kDoNotDisplay);
+  fillHVStatus.SetBit(MFillH::kDoNotDisplay);
+  fillLidsStatus.SetBit(MFillH::kDoNotDisplay);
+  fillCoolStatus.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc1.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc2.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc3.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc4.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc5.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc6.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc7.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc8.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc9.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc10.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc11.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc12.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc13.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc14.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc15.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc16.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc17.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc18.SetBit(MFillH::kDoNotDisplay);
+  filltrigmc19.SetBit(MFillH::kDoNotDisplay);
+  fillcammean.SetBit(MFillH::kDoNotDisplay);
+  fillHVD.SetBit(MFillH::kDoNotDisplay);
+
+  // Skip the fill function is there is no tree entries
+  fillZd.SetBit(MFillH::kCanSkip);
+  fillAz.SetBit(MFillH::kCanSkip);
+  fillError.SetBit(MFillH::kCanSkip);
+  fillDState.SetBit(MFillH::kCanSkip);
+  fillError2.SetBit(MFillH::kCanSkip);
+  fillHVA.SetBit(MFillH::kCanSkip);
+  fillHVB.SetBit(MFillH::kCanSkip);
+  fillCA.SetBit(MFillH::kCanSkip);
+  fillCB.SetBit(MFillH::kCanSkip);
+  fillLVTemp.SetBit(MFillH::kCanSkip);
+  fillLVHum.SetBit(MFillH::kCanSkip);
+  fillLVStatus.SetBit(MFillH::kCanSkip);
+  fillLVRPS.SetBit(MFillH::kCanSkip);
+  fillTCenter.SetBit(MFillH::kCanSkip);
+  fillTWall.SetBit(MFillH::kCanSkip);
+  fillTWater.SetBit(MFillH::kCanSkip);
+  fillTOptLink.SetBit(MFillH::kCanSkip);
+  fillTempOptLink.SetBit(MFillH::kCanSkip);
+  fillHWall.SetBit(MFillH::kCanSkip);
+  fillHCenter.SetBit(MFillH::kCanSkip);
+  fillCCHum.SetBit(MFillH::kCanSkip);
+  fillCCTemp.SetBit(MFillH::kCanSkip);
+  fillCCWS.SetBit(MFillH::kCanSkip);
+  fillCCSR.SetBit(MFillH::kCanSkip);
+  fillTrigBL2.SetBit(MFillH::kCanSkip);
+  fillTrigAL2.SetBit(MFillH::kCanSkip);
+  fillTrigStatus.SetBit(MFillH::kCanSkip);
+  fillTrigZd.SetBit(MFillH::kCanSkip);
+  fillCamStatus.SetBit(MFillH::kCanSkip);
+  fillCamSentStatus.SetBit(MFillH::kCanSkip);
+  fillCamStatusDC.SetBit(MFillH::kCanSkip);
+  fillHVStatus.SetBit(MFillH::kCanSkip);
+  fillLidsStatus.SetBit(MFillH::kCanSkip);
+  fillCoolStatus.SetBit(MFillH::kCanSkip);
+  filltrigmc1.SetBit(MFillH::kCanSkip);
+  filltrigmc2.SetBit(MFillH::kCanSkip);
+  filltrigmc3.SetBit(MFillH::kCanSkip);
+  filltrigmc4.SetBit(MFillH::kCanSkip);
+  filltrigmc5.SetBit(MFillH::kCanSkip);
+  filltrigmc6.SetBit(MFillH::kCanSkip);
+  filltrigmc7.SetBit(MFillH::kCanSkip);
+  filltrigmc8.SetBit(MFillH::kCanSkip);
+  filltrigmc9.SetBit(MFillH::kCanSkip);
+  filltrigmc10.SetBit(MFillH::kCanSkip);
+  filltrigmc11.SetBit(MFillH::kCanSkip);
+  filltrigmc12.SetBit(MFillH::kCanSkip);
+  filltrigmc13.SetBit(MFillH::kCanSkip);
+  filltrigmc14.SetBit(MFillH::kCanSkip);
+  filltrigmc15.SetBit(MFillH::kCanSkip);
+  filltrigmc16.SetBit(MFillH::kCanSkip);
+  filltrigmc17.SetBit(MFillH::kCanSkip);
+  filltrigmc18.SetBit(MFillH::kCanSkip);
+  filltrigmc19.SetBit(MFillH::kCanSkip);
+  fillcammean.SetBit(MFillH::kCanSkip);
+  fillHVD.SetBit(MFillH::kCanSkip);
+
+  // Add all the task to the task list
+  tlist.AddToList(&read);
+  tlist.AddToList(&fillZd,       "Drive");
+  tlist.AddToList(&fillAz,       "Drive");
+  tlist.AddToList(&fillError,    "Drive");
+  tlist.AddToList(&fillDState,   "Drive");
+  tlist.AddToList(&fillError2,   "Drive");
+  tlist.AddToList(&fillHVA,      "Camera");
+  tlist.AddToList(&fillHVB,      "Camera");
+  tlist.AddToList(&fillCA,       "Camera");
+  tlist.AddToList(&fillCB,       "Camera");
+  tlist.AddToList(&fillLVTemp,   "Camera");
+  tlist.AddToList(&fillLVHum,    "Camera");
+  tlist.AddToList(&fillLVStatus, "Camera");
+  tlist.AddToList(&fillLVRPS,    "Camera");
+  tlist.AddToList(&fillTCenter,  "Camera");
+  tlist.AddToList(&fillTWall,    "Camera");
+  tlist.AddToList(&fillTWater,   "Camera");
+  tlist.AddToList(&fillTOptLink, "Camera");
+  tlist.AddToList(&fillTempOptLink, "Camera");
+  tlist.AddToList(&fillHWall,    "Camera");
+  tlist.AddToList(&fillHCenter,  "Camera");
+  tlist.AddToList(&fillCCHum,    "CC");
+  tlist.AddToList(&fillCCTemp,   "CC");
+  tlist.AddToList(&fillCCWS,     "CC");
+  tlist.AddToList(&fillCCSR,     "CC");
+  tlist.AddToList(&fillTrigBL2,  "Trigger");
+  tlist.AddToList(&fillTrigAL2,  "Trigger");
+  tlist.AddToList(&fillTrigStatus,  "Trigger");
+  tlist.AddToList(&fillTrigZd);
+  tlist.AddToList(&fillCamStatus,  "Camera");
+  tlist.AddToList(&fillCamSentStatus,  "Camera");
+  tlist.AddToList(&fillCamStatusDC,"Camera");
+  tlist.AddToList(&fillHVStatus,"Camera");
+  tlist.AddToList(&fillLidsStatus,"Camera");
+  tlist.AddToList(&fillCoolStatus,"Camera");
+  tlist.AddToList(&filltrigmc1, "Trigger");
+  tlist.AddToList(&filltrigmc2, "Trigger");
+  tlist.AddToList(&filltrigmc3, "Trigger");
+  tlist.AddToList(&filltrigmc4, "Trigger");
+  tlist.AddToList(&filltrigmc5, "Trigger");
+  tlist.AddToList(&filltrigmc6, "Trigger");
+  tlist.AddToList(&filltrigmc7, "Trigger");
+  tlist.AddToList(&filltrigmc8, "Trigger");
+  tlist.AddToList(&filltrigmc9, "Trigger");
+  tlist.AddToList(&filltrigmc10, "Trigger");
+  tlist.AddToList(&filltrigmc11, "Trigger");
+  tlist.AddToList(&filltrigmc12, "Trigger");
+  tlist.AddToList(&filltrigmc13, "Trigger");
+  tlist.AddToList(&filltrigmc14, "Trigger");
+  tlist.AddToList(&filltrigmc15, "Trigger");
+  tlist.AddToList(&filltrigmc16, "Trigger");
+  tlist.AddToList(&filltrigmc17, "Trigger");
+  tlist.AddToList(&filltrigmc18, "Trigger");
+  tlist.AddToList(&filltrigmc19, "Trigger");
+  tlist.AddToList(&fillcammean, "Camera");
+  tlist.AddToList(&fillHVD);
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  if(!batchmode)
+    evtloop.SetDisplay(d);
+    
+  //
+  // Execute your analysis
+  //
+  if (!evtloop.Eventloop())
+    return;
+ 
+  tlist.PrintStatistics();
+
+  gStyle->SetPadGridX(kTRUE);
+  gStyle->SetPadGridY(kTRUE);
+  gStyle->SetCanvasColor(kWhite);
+  MHVsTime *clone1;
+  TGraph *g;
+  TH1 *hist;
+  TH1 *hist2;
+  TAxis *axey;
+  TAxis *axex;
+  MH3 *mh3;
+  MHPixVsTime *pixclone1;
+  MHCamera *Sum;
+  //
+  // Drive report (pointing.C from T. Bretz)
+  //
+  TCanvas *c1;
+  if ((d = evtloop.GetDisplay()))
+      c1 = &d->AddTab("DRIVE SYSTEM");
+  else
+      c1 = new TCanvas();
+
+  // ************* Plot the telescope tracking positions on the sky ***********
+  TGraph *g1 = hZd.GetGraph();
+  TGraph *g2 = hAz.GetGraph();
+  TPad *p = new TPad("", "",0,0.05,0.6,0.95);
+  p->Draw();
+  p->cd();
+  gPad->SetTheta(-90);
+  gPad->SetPhi(90);
+  gPad->SetBorderMode(0);
+  gStyle->SetOptStat(0);
+  TH2F h("pol", "Telescope Tracking Positions on the Sky", 16, 0, 1, 9, 0, 1);
+  h.DrawClone("surf1pol");
+  gPad->Modified();
+  gPad->Update();
+  TView *view = gPad->GetView();
+  if (!view)
+    {
+      cout << "No View!" << endl;
+      return;
+    }
+  Double_t *zd=g1->GetY();
+  Double_t *az=g2->GetY();
+  Double_t old[2] = {0,0};
+  for (int i=0; i<g1->GetN(); i++)
+    {
+      az[i] += 180;
+      az[i] *= TMath::Pi()/180;
+      Double_t x[3] = { zd[i]*cos(az[i])/90, zd[i]*sin(az[i])/90, 0};
+      Double_t y[3];
+      view->WCtoNDC(x, y);
+      if (old[0]!=0 && old[1]!=1)
+        {
+	  TLine *l = new TLine(y[0], y[1], old[0], old[1]);
+	  l->SetLineColor(kBlue);
+	  l->Draw();
+        }
+      TMarker *m = new TMarker(y[0], y[1], kFullDotMedium);
+      m->SetMarkerColor(i==g1->GetN()-1 ? kGreen : kRed);
+      m->Draw();
+      old[0] = y[0];
+      old[1] = y[1];
+    }
+  // ---------------------- Control deviation of the motors -------------------
+  c1->cd();
+  p = new TPad("", "", 0.6, 0, 1, 0.29);
+  p->Draw();
+  p->cd();
+  gStyle->SetOptStat(1110);
+  gStyle->SetStatFormat(".2g");
+  mh3 = (MH3*)hError.DrawClone("nonew");
+  mh3->GetHist().SetXTitle("\\Delta [arcmin]");
+  mh3->GetHist().SetYTitle("");
+  mh3->GetHist().SetTitle("Control deviation of the motors");
+  mh3->GetHist().SetStats(1);
+  mh3->GetHist().SetLabelSize(0.06,"X");
+  mh3->GetHist().SetLabelSize(0.06,"Y");
+  mh3->GetHist().SetTitleSize(0.06,"X");
+  TLine ln;
+  ln.SetLineColor(kGreen);
+  ln.DrawLine(0.5*360*60/16384., 0, 0.5*360*60/16384., hError.GetHist().GetMaximum());
+  ln.SetLineColor(kYellow);
+  ln.DrawLine(1.0*360*60/16384., 0, 1.0*360*60/16384., hError.GetHist().GetMaximum());
+  ln.SetLineColor(kRed);
+  ln.DrawLine(2.0*360*60/16384., 0, 2.0*360*60/16384., hError.GetHist().GetMaximum());
+  // ---------------------- Plot the drive status vs time ---------------------
+  c1->cd();
+  p = new TPad("", "", 0.6, 0.29, 1, 0.42);
+  p->Draw();
+  p->cd();
+  MHVsTime *hvt = (MHVsTime*)hDState.DrawClone("nonew");
+  hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+  if (hvt->GetGraph()->GetN())
+    {
+      hist = hvt->GetGraph()->GetHistogram();
+      TAxis *axey = hist->GetYaxis();
+      TAxis *axex = hist->GetXaxis();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+      hist->SetTitle("");
+      hist->SetLabelSize(0.1,"X");
+      hist->SetTitleSize(0.06,"X");
+      hist->SetStats(0);
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(4.5);
+      axey->Set(5, -0.5, 4.5);
+      axey->SetBinLabel(axey->FindFixBin(0), "Error");
+      axey->SetBinLabel(axey->FindFixBin(1), "Stopped");
+      axey->SetBinLabel(axey->FindFixBin(3), "Moving");
+      axey->SetBinLabel(axey->FindFixBin(4), "Tracking");
+      axey->SetLabelSize(0.15);
+      axex->SetLabelSize(0.08);
+      axex->SetTitleSize(0.09);
+      axex->SetTitleOffset(0.45);
+    }  
+  // --------------- Control deviation of the motors vs zenith angle ----------
+  c1->cd();
+  p = new TPad("", "", 0.6, 0.71, 1, 1);
+  p->Draw();
+  p->cd();
+  gStyle->SetOptStat(1110);
+  gStyle->SetStatFormat(".2g");
+  mh3 = (MH3*)hError2.DrawClone("nonew");
+  mh3->GetHist().SetXTitle("Zd [\\circ]");
+  mh3->GetHist().SetYTitle("\\Delta [arcmin]");
+  mh3->GetHist().SetTitle("Control deviation of the motors");
+  mh3->GetHist().SetLabelSize(0.06,"X");
+  mh3->GetHist().SetLabelSize(0.06,"Y");
+  mh3->GetHist().SetTitleSize(0.06,"X");
+  mh3->GetHist().SetTitleSize(0.06,"Y");
+  mh3->GetHist().SetStats(1);
+  mh3->GetHist().Draw("box");
+  // -------------------------- Zenith angle vs time --------------------------
+  c1->cd();
+  p = new TPad("", "", 0.6, 0.42, 1, 0.71);
+  p->Draw();
+  p->cd();
+  gPad->SetBorderMode(0);
+  hvt = (MHVsTime*)hZd.DrawClone("nonew");
+  hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+  if (hvt->GetGraph()->GetN())
+    {
+      hvt->GetGraph()->GetHistogram()->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hvt->GetGraph()->GetHistogram()->SetXTitle("Time");
+      hvt->GetGraph()->GetHistogram()->SetYTitle("Zd [\\circ]");
+      hvt->GetGraph()->GetHistogram()->SetTitle("Zd vs. Time");
+      hvt->GetGraph()->GetHistogram()->SetLabelSize(0.06,"X");
+      hvt->GetGraph()->GetHistogram()->SetTitleSize(0.06,"X");
+      hvt->GetGraph()->GetHistogram()->SetLabelSize(0.06,"Y");
+      hvt->GetGraph()->GetHistogram()->SetTitleSize(0.06,"Y");
+      hvt->GetGraph()->GetHistogram()->SetStats(0);
+    }
+  
+  
+  //
+  // Camera report 
+  // 
+  // **************************** CAMERA STATUS ********************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c2 = d.AddTab("CAMERA STATUS");
+  else
+    TCanvas *c2 = new TCanvas();
+  c2->Divide(1,2);
+  c2->cd(1);
+  g = hCamStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera status");
+  clone1 = (MHVsTime*)hCamStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"EROR");
+      axey->SetBinLabel(axey->FindFixBin(1),"ALARM");
+      axey->SetBinLabel(axey->FindFixBin(2),"BLOCKED!");
+      axey->SetBinLabel(axey->FindFixBin(3),"WARM!");
+      axey->SetBinLabel(axey->FindFixBin(4),"HOT");
+      axey->SetBinLabel(axey->FindFixBin(5),"HVRAMPING");
+      axey->SetBinLabel(axey->FindFixBin(6),"OK");
+      axey->SetBinLabel(axey->FindFixBin(7),"INIT");
+      axey->SetBinLabel(axey->FindFixBin(8),"SHUTD");
+      axey->SetBinLabel(axey->FindFixBin(9),"N/A");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  c2->cd(2);
+  g = hLidsStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera Lids status");
+  clone1 = (MHVsTime*)hLidsStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"SafetyLimit");
+      axey->SetBinLabel(axey->FindFixBin(4),"Closed");
+      axey->SetBinLabel(axey->FindFixBin(5),"Opened");
+      axey->SetBinLabel(axey->FindFixBin(6),"Moving");
+      axey->SetBinLabel(axey->FindFixBin(7),"Stopped");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.06,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  // ************************* HV of power supplies ***************************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c3 = d.AddTab("CAMERA HV");
+  else
+    TCanvas *c3 = new TCanvas();
+  c3->Divide(2,2);
+  c3->cd(1);
+  // --------------- Power supplies  and HV settings --------------------------
+  TLegend *legHV = new TLegend(0.75,0.85,0.99,0.99);
+  g = hHVA.GetGraph();
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("Voltages of power supplies and camera settings");
+  legHV->AddEntry(g,"PS A (hvps1)","l");
+  clone1 = (MHVsTime*)hHVA.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("High voltage [V]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetMinimum(0);
+    }
+  g = hHVB.GetGraph();
+  g->SetMarkerColor(3);
+  g->SetLineColor(3);
+  legHV->AddEntry(g,"PS B (hvps2)","l");
+  clone1 = (MHVsTime*)hHVB.DrawClone("nonewsame");
+  g = hCamMean.GetGraph();
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  legHV->AddEntry(g,"Camera mean HV","l");
+  clone1 = (MHVsTime*)hCamMean.DrawClone("nonewsame");
+  legHV->DrawClone();
+ // ---------------------------- HV status -----------------------------------
+  c3->cd(2);
+  g = hHVStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera HV status");
+  clone1 = (MHVsTime*)hHVStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"Mismatch");
+      axey->SetBinLabel(axey->FindFixBin(2),"Trip");
+      axey->SetBinLabel(axey->FindFixBin(3),"Ramping");
+      axey->SetBinLabel(axey->FindFixBin(4),"Off");
+      axey->SetBinLabel(axey->FindFixBin(5),"Nominal");
+      axey->SetBinLabel(axey->FindFixBin(6),"LimCurrentWarning");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  // ---------------------------- HV settings ---------------------------------
+  c3->cd(3);
+  Sum = (MHCamera*)HVdisplay.GetHistByName("sum");
+  TVirtualPad *c = gPad;
+  c->cd(1);
+  gPad->SetBorderMode(0);
+  Sum->SetYTitle("Mean");
+  Sum->DrawClone("pixelindex"); 
+  c3->cd(4);
+  gPad->SetBorderMode(0);
+  Sum->SetYTitle("Mean HV settings");
+  Sum->DrawClone("EPhist");
+
+  // ******************** Currents of power supplies *******************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c4 = d.AddTab("CAMERA DC");
+  else
+    TCanvas *c4 = new TCanvas();
+ // ----------------------------- Power supplies ------------------------------
+  c4->Divide(1,2);
+  c4->cd(1);
+  TLegend *legC = new TLegend(0.85,0.75,0.99,0.99);
+  g = hCA.GetGraph();
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("Currents of power supplies");
+  legC->AddEntry(g,"PS A (curr1)","l");
+  clone1 = (MHVsTime*)hCA.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Current [mA]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetMinimum(0);
+    }
+  g = hCB.GetGraph();
+  g->SetMarkerColor(3);
+  g->SetLineColor(3);
+  legC->AddEntry(g,"PS B (curr2)","l");
+  clone1 = (MHVsTime*)hCB.DrawClone("nonewsame");
+  legC->DrawClone();
+  c4->cd(2);
+  g = hCamStatusDC.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera DC status");
+  clone1 = (MHVsTime*)hCamStatusDC.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"Alarm");
+      axey->SetBinLabel(axey->FindFixBin(3),"Hot");
+      axey->SetBinLabel(axey->FindFixBin(5),"Ok");
+      axey->SetBinLabel(axey->FindFixBin(6),"Warm");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.09,"Y");
+      hist->SetLabelSize(0.04,"X");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+
+
+  // ***************************** LV power supplies **************************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c5 = d.AddTab("CAMERA LV");
+  else
+    TCanvas *c5 = new TCanvas();
+  c5->Divide(2,2);
+  c5->cd(1);
+  g = hLVTemp.GetGraph();
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("LV temperature");
+  clone1 = (MHVsTime*)hLVTemp.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Temperature [\\circ]");
+      hist->SetLabelSize(0.04,"X");
+    }
+  c5->cd(2);
+  g = hLVHum.GetGraph();
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  g->SetTitle("LV humidity");
+  clone1 = (MHVsTime*)hLVHum.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Humidity [%]");
+      hist->SetLabelSize(0.04,"X");
+    }
+  c5->cd(3);
+  g = hLVStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("LV status");
+  clone1 = (MHVsTime*)hLVStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"Alarm");
+      axey->SetBinLabel(axey->FindFixBin(2),"Trip");
+      axey->SetBinLabel(axey->FindFixBin(4),"Off");
+      axey->SetBinLabel(axey->FindFixBin(5),"On");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  c5->cd(4);
+  g = hLVRPS.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("LV request power supply");
+  clone1 = (MHVsTime*)hLVRPS.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+      hist->SetLabelSize(0.04,"X");
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(1.5);
+      axey->Set(2, -0.5, 1.5);
+      axey->SetBinLabel(axey->FindFixBin(0), "OFF");
+      axey->SetBinLabel(axey->FindFixBin(1), "ON");
+    }
+  // ****************************** Cooling ***********************************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c6 = d.AddTab("COOLING SYSTEM");
+  else
+    TCanvas *c6 = new TCanvas();
+  gStyle->SetPadGridX(kTRUE);
+  gStyle->SetPadGridY(kTRUE);
+  c6->Divide(2,2);
+  c6->cd(1);
+  // -------------------------- Camera temperatures ---------------------------
+  TLegend *legtemp = new TLegend(0.75,0.80,0.99,0.99);
+  g = hTCenter.GetGraph();
+  g->SetMarkerColor(8);
+  g->SetLineColor(8);
+  g->SetTitle("Camera temperature");
+  legtemp->AddEntry(g,"camera center","l");
+  clone1 = (MHVsTime*)hTCenter.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Temperature [\\circ C]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetMinimum(0);
+    }
+  g = hTWall.GetGraph();
+  g->SetMarkerColor(12);
+  g->SetLineColor(12);
+  legtemp->AddEntry(g,"camera wall","l");
+  clone1 = (MHVsTime*)hTWall.DrawClone("nonewsame");
+  g = hTWater.GetGraph();
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  legtemp->AddEntry(g,"water deposit","l");
+  clone1 = (MHVsTime*)hTWater.DrawClone("nonewsame");
+  g = hTOptLink.GetGraph();
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  legtemp->AddEntry(g,"optical links","l");
+  clone1 = (MHVsTime*)hTOptLink.DrawClone("nonewsame");
+  legtemp->DrawClone();
+  c6->cd(2);
+  g = hCoolStatus.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetTitle("Camera cooling status");
+  clone1 = (MHVsTime*)hCoolStatus.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      axey = hist->GetYaxis();
+      hist->SetMinimum(-0.5);
+      hist->SetMaximum(9.5);
+      axey->Set(10,-0.5,9.5);
+      axey->SetBinLabel(axey->FindFixBin(0),"Error");
+      axey->SetBinLabel(axey->FindFixBin(1),"Alarm");
+      axey->SetBinLabel(axey->FindFixBin(4),"Off");
+      axey->SetBinLabel(axey->FindFixBin(5),"Ok");
+      axey->SetBinLabel(axey->FindFixBin(6),"Temp.Warning");
+      axey->SetBinLabel(axey->FindFixBin(7),"Cond.Warning");
+      axey->SetBinLabel(axey->FindFixBin(9),"n/a");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("");
+    }
+  // ------------------------- Camera relative humidity -----------------------
+  c6->cd(3);
+  TLegend *leghum = new TLegend(0.75,0.85,0.99,0.99);
+  g = hHCenter.GetGraph();
+  g->SetMarkerColor(8);
+  g->SetLineColor(8);
+  g->SetTitle("Camera relative humidity");
+  leghum->AddEntry(g,"camera center","l");
+  clone1 = (MHVsTime*)hHCenter.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Relative humidity [%]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetMaximum(50);
+      hist->SetMinimum(0);
+    }
+  g = hHWall.GetGraph();
+  g->SetMarkerColor(12);
+  g->SetLineColor(12);
+  leghum->AddEntry(g,"camera wall","l");
+  clone1 = (MHVsTime*)hHWall.DrawClone("nonewsame");
+  leghum->DrawClone();
+  // ---------------------- Temperature distribution --------------------------
+  c6->cd(4);
+  hist = hTempOptLink.GetHistByName("TOptLink");
+  hist->SetXTitle("Temperature [\\circ C]");
+  hist->SetYTitle("");
+  hist->SetLineColor(2);
+  hist->SetTitle("Distribution of opt. links temperature");
+  hist->SetLabelSize(0.04,"X");
+  hist->SetStats(0);
+  mh3 = (MH3*)hTempOptLink.DrawClone("nonew");
+  //
+  // **************************** Trigger report ******************************
+  //
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c7 = d.AddTab("TRIGGER SYSTEM");
+  else
+    TCanvas *c7 = new TCanvas();
+  c7->Divide(1,3);
+  c7->cd(1);
+  gStyle->SetPadGridX(kTRUE);
+  gStyle->SetPadGridY(kTRUE);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.85,0.85,0.99,0.99);
+  g = hTrigBL2.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("L2 trigger rate");
+  legtrig->AddEntry(g,"Before prescaler","l");
+  clone1 = (MHVsTime*)hTrigBL2.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetLabelSize(0.06,"X");
+      hist->SetLabelSize(0.06,"Y");
+      hist->SetTitleSize(0.06,"X");
+      hist->SetTitleSize(0.06,"Y");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("L2 trigger rate [Hz]"); 
+    }
+  g = hTrigAL2.GetGraph();
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  legtrig->AddEntry(g,"After prescaler","l");
+  clone1 = (MHVsTime*)hTrigAL2.DrawClone("nonewsame");
+  legtrig->DrawClone();
+   c7->cd(2);
+   gPad->SetLogy();
+   hist = hTrigZd.GetHistByName("TrigZd");
+   hist->SetLabelSize(0.06,"X");
+   hist->SetLabelSize(0.06,"Y");
+   hist->SetTitleSize(0.06,"X");
+   hist->SetTitleSize(0.06,"Y");
+   hist->SetXTitle("Zenith angle[\\circ]");
+   hist->SetYTitle("Trigger rate [Hz]");
+   hist->SetMarkerColor(4);
+   hist->SetTitle("L2 trigger rate after prescaler");
+   hist->SetStats(0);
+   mh3 = (MH3*)hTrigZd.DrawClone("nonew");
+   hist->SetMinimum(1);
+   c7->cd(3);
+   g = hTrigStatus.GetGraph();
+   g->SetMarkerStyle(kFullDotSmall);
+   g->SetTitle("Trigger status");
+   clone1 = (MHVsTime*)hTrigStatus.DrawClone("nonew");
+   if(clone1->GetGraph()->GetN())
+     {
+       hist = clone1->GetGraph()->GetHistogram();
+       axey = hist->GetYaxis();
+       hist->SetMinimum(-0.5);
+       hist->SetMaximum(5.5);
+       axey->Set(6,-0.5,5.5);
+       axey->SetBinLabel(axey->FindFixBin(0),"Error");
+       axey->SetBinLabel(axey->FindFixBin(1),"Idle");
+       axey->SetBinLabel(axey->FindFixBin(2),"Loading");
+       axey->SetBinLabel(axey->FindFixBin(3),"Ready");
+       axey->SetBinLabel(axey->FindFixBin(4),"Active");
+       axey->SetBinLabel(axey->FindFixBin(5),"Stopped");
+       hist->SetLabelSize(0.07,"Y");
+       hist->SetLabelSize(0.06,"X");
+       hist->SetTitleSize(0.06,"X");
+       hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+       hist->SetXTitle("Time");
+       hist->SetYTitle("");
+     }
+  // ***************************** Trigger of macrocells **********************
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c8 = d.AddTab("TRIG. MACROCELLs");
+  else
+    TCanvas *c8 = new TCanvas();
+  c8->Divide(2,2);
+  c8->cd(1);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.80,0.80,0.99,0.99);
+  g = htrigmc1.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("Trigger rate of macrocell 1 : (maximum)");
+  pixclone1 = (MHPixVsTime*)htrigmc1.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = htrigmc1->GetGraph()->GetHistogram();
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Trigger [Hz]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+    }
+  legtrig->AddEntry(hist,Form("Mc 1: %3.0e",hist->GetMaximum()),"p");
+  legtrig->DrawClone();
+  c8->cd(2);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.80,0.70,0.99,0.99);
+  g = htrigmc2.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetTitle("Trigger rate of macrocells 2-7 : (maximum)");
+  pixclone1 = (MHPixVsTime*)htrigmc2.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = pixclone1->GetGraph()->GetHistogram();
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Trigger [Hz]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+    }
+  legtrig->AddEntry(hist,Form("Mc 2: %3.0e",hist->GetMaximum()),"p");
+  g=htrigmc3.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  if(htrigmc3.GetGraph()->GetN())
+  {
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      legtrig->AddEntry(g,Form("Mc 3: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc3.DrawClone("nonewsame");
+  g=htrigmc4.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  if(htrigmc4.GetGraph()->GetN())
+  {
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      legtrig->AddEntry(g,Form("Mc 4: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc4.DrawClone("nonewsame");
+  g=htrigmc5.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(5);
+  if(htrigmc5.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 5: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc5.DrawClone("nonewsame");
+  g=htrigmc6.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(6);
+  if(htrigmc6.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 6: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc6.DrawClone("nonewsame");
+  g=htrigmc7.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(7);
+  if(htrigmc7.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 7: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc7.DrawClone("nonewsame");
+  legtrig->DrawClone();
+  c8->cd(3);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.80,0.70,0.99,0.99);
+  g = htrigmc8.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetTitle("Trigger rate of macrocells 8-13 : (maximum)");
+  if(htrigmc8.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 8: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc8.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+	hist = pixclone1->GetGraph()->GetHistogram();
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Trigger [Hz]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+    }
+  g=htrigmc9.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  if(htrigmc9.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 9: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc9.DrawClone("nonewsame");
+  g=htrigmc10.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  if(htrigmc10.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 10: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc10.DrawClone("nonewsame");
+  g=htrigmc11.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(5);
+  if(htrigmc11.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 11: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc11.DrawClone("nonewsame");
+  g=htrigmc12.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(6);
+  if(htrigmc12.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 12: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc12.DrawClone("nonewsame");
+  g=htrigmc13.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(7);
+  if(htrigmc13.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 13: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc13.DrawClone("nonewsame");
+  legtrig->DrawClone();
+  c8->cd(4);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.80,0.70,0.99,0.99);
+  TGraph *g = htrigmc14.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  if(htrigmc14.GetGraph()->GetN())
+      legtrig->AddEntry(g,Form("Mc 14: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+  g->SetTitle("Trigger rate of macrocells 14-19 : (maximum)");
+  pixclone1 = (MHPixVsTime*)htrigmc14.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = pixclone1->GetGraph()->GetHistogram();
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	hist->SetMaximum(g->GetHistogram()->GetMaximum());
+      hist->SetMinimum(1);
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Trigger [Hz]");
+      hist->SetLabelSize(0.04,"X");
+      hist->SetLabelSize(0.05,"Y");
+    }
+  g=htrigmc15.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  if(htrigmc15.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 15: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc15.DrawClone("nonewsame");
+  g=htrigmc16.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  if(htrigmc16.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 16: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc16.DrawClone("nonewsame");
+  g=htrigmc17.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(5);
+  if(htrigmc17.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 17: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc17.DrawClone("nonewsame");
+  g=htrigmc18.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(6);
+  if(htrigmc18.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 18: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc18.DrawClone("nonewsame");
+  g=htrigmc19.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(7);
+  if(htrigmc19.GetGraph()->GetN())
+  {
+      legtrig->AddEntry(g,Form("Mc 19: %3.0e",g->GetHistogram()->GetMaximum()),"p");
+      if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+	  hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  }
+  pixclone1 = (MHPixVsTime*)htrigmc19.DrawClone("nonewsame");
+  legtrig->DrawClone();
+
+  //
+  // *************************** Weather station ******************************
+  //
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c9 = d.AddTab("WEATHER STATION");
+  else
+    TCanvas *c9 = new TCanvas();
+  c9->Divide(2,2);
+  // ----------------------- Relative humidity --------------------------------
+  c9->cd(1);
+  g = hCCHum.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  g->SetLineColor(4);
+  g->SetTitle("Relative humidity outside");
+  clone1 = (MHVsTime*)hCCHum.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Humidity [%]"); 
+    }
+  // -------------------------- Temperature -----------------------------------
+  c9->cd(2);
+  g = hCCTemp.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  g->SetLineColor(2);
+  g->SetTitle("Temperature outside");
+  clone1 = (MHVsTime*)hCCTemp.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Temperature [\\circ C]"); 
+    }
+  // --------------------------- Wind speed -----------------------------------
+  c9->cd(3);
+  g = hCCWS.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  g->SetLineColor(3);
+  g->SetTitle("Wind speed outside");
+  clone1 = (MHVsTime*)hCCWS.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Wind speed [km/h]"); 
+    }
+  // -------------------------- Solar radiation -------------------------------
+  c9->cd(4);
+  g = hCCSR.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(9);
+  g->SetLineColor(9);
+  g->SetTitle("Solar radiation outside");
+  clone1 = (MHVsTime*)hCCSR.DrawClone("nonew");
+  if(clone1->GetGraph()->GetN())
+    {
+      hist = clone1->GetGraph()->GetHistogram();
+      hist->GetXaxis()->SetTimeFormat("%H:%M %F1995-01-01 00:00:00");
+      hist->SetXTitle("Time");
+      hist->SetYTitle("Solar radiation [W/m^2]"); 
+    }
+
+  // Save data in a postscriptfile (filename.ps)
+  TString file;
+  if (filename.Last('.')>0)
+    file = filename(0, filename.Last('.')); 
+
+  // Make sure the display hasn't been deleted by the user while the
+  // eventloop was running.
+  if ((d = evtloop.GetDisplay()))
+      d->SaveAsPS(directory+file+".ps");
+  else
+    {
+      c1->Print(directory+file+".ps(");
+      c2->Print(directory+file+".ps");
+      c3->Print(directory+file+".ps");
+      c4->Print(directory+file+".ps");
+      c5->Print(directory+file+".ps");
+      c6->Print(directory+file+".ps");
+      c7->Print(directory+file+".ps");
+      c8->Print(directory+file+".ps");
+      c9->Print(directory+file+".ps)");
+    }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/CT1Analysis.C
===================================================================
--- /tags/Mars-V0.9/macros/CT1Analysis.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/CT1Analysis.C	(revision 9772)
@@ -0,0 +1,3381 @@
+
+#include "CT1EgyEst.C"
+
+#include "MBinning.h"
+#include "MBlindPixelCalc.h"
+#include "MContinue.h"
+#include "MCT1PointingCorrCalc.h"
+
+#include "MFCT1SelBasic.h"
+#include "MFCT1SelStandard.h"
+#include "MFCT1SelFinal.h"
+#include "MFillH.h"
+
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+#include "MImgCleanStd.h"
+
+#include "MParList.h"
+#include "MSigmabarCalc.h"
+#include "MSrcPosCam.h"
+#include "MTaskList.h"
+#include "MWriteRootFile.h"
+
+//#include "TH3D.h"
+
+
+void InitBinnings(MParList *plist)
+{
+        gLog << "InitBinnings" << endl;
+
+        //--------------------------------------------
+        MBinning *binse = new MBinning("BinningE");
+        //binse->SetEdgesLog(30, 1.0e2, 1.0e5);
+
+	//This is Daniel's binning in energy:
+        binse->SetEdgesLog(14, 296.296, 86497.6);
+        plist->AddToList(binse);
+
+        //--------------------------------------------
+
+        MBinning *binssize = new MBinning("BinningSize");
+        binssize->SetEdgesLog(50, 10, 1.0e5);
+        plist->AddToList(binssize);
+
+        MBinning *binsdistc = new MBinning("BinningDist");
+        binsdistc->SetEdges(50, 0, 1.4);
+        plist->AddToList(binsdistc);
+
+        MBinning *binswidth = new MBinning("BinningWidth");
+        binswidth->SetEdges(50, 0, 1.0);
+        plist->AddToList(binswidth);
+
+        MBinning *binslength = new MBinning("BinningLength");
+        binslength->SetEdges(50, 0, 1.0);
+        plist->AddToList(binslength);
+
+        MBinning *binsalpha = new MBinning("BinningAlpha");
+        binsalpha->SetEdges(100, -100, 100);
+        plist->AddToList(binsalpha);
+
+        MBinning *binsasym = new MBinning("BinningAsym");
+        binsasym->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsasym);
+
+        MBinning *binsm3l = new MBinning("BinningM3Long");
+        binsm3l->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3l);
+
+        MBinning *binsm3t = new MBinning("BinningM3Trans");
+        binsm3t->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3t);
+
+   
+        //.....
+        MBinning *binsb = new MBinning("BinningSigmabar");
+        binsb->SetEdges( 100,  0.0,  5.0);
+        plist->AddToList(binsb);
+
+        MBinning *binth = new MBinning("BinningTheta");
+        // this is Daniel's binning in theta
+        //Double_t yedge[8] = 
+        //  {9.41, 16.22, 22.68, 28.64, 34.03, 38.84, 43.08, 44.99};
+        // this is our binning
+        Double_t yedge[9] = 
+                       {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        TArrayD yed;
+        yed.Set(9,yedge);
+        binth->SetEdges(yed);
+        plist->AddToList(binth);
+
+        MBinning *bincosth = new MBinning("BinningCosTheta");
+        Double_t zedge[9]; 
+        for (Int_t i=0; i<9; i++)
+	{
+          zedge[8-i] = cos(yedge[i]/kRad2Deg);
+	}
+        TArrayD zed;
+        zed.Set(9,zedge);
+        bincosth->SetEdges(zed);
+        plist->AddToList(bincosth);
+
+        MBinning *binsdiff = new MBinning("BinningDiffsigma2");
+        binsdiff->SetEdges(100, -5.0, 20.0);
+        plist->AddToList(binsdiff);
+
+        // robert ----------------------------------------------
+        MBinning *binsalphaf = new MBinning("BinningAlphaFlux");
+        binsalphaf->SetEdges(100, -100, 100);
+        plist->AddToList(binsalphaf);
+
+	MBinning *binsdifftime = new MBinning("BinningTimeDiff");
+	binsdifftime->SetEdges(50, 0, 10);
+	plist->AddToList(binsdifftime);
+
+	MBinning *binstime = new MBinning("BinningTime");
+	binstime->SetEdges(50, 44500, 61000);
+	plist->AddToList(binstime);
+}
+
+
+void DeleteBinnings(MParList *plist)
+{
+        gLog << "DeleteBinnings" << endl;
+
+        TObject *bin;
+
+        //--------------------------------------------
+        bin = plist->FindObject("BinningE");
+        if (bin) delete bin;
+
+        //--------------------------------------------
+
+        bin = plist->FindObject("BinningSize");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDist");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningWidth");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningLength");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAlpha");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAsym");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Long");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Trans");
+        if (bin) delete bin;
+
+        //.....
+        bin = plist->FindObject("BinningSigmabar");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningCosTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDiffsigma2");
+        if (bin) delete bin;
+
+
+        // robert ----------------------------------------------
+        bin = plist->FindObject("BinningAlphaFlux");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTimeDiff");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTime");
+        if (bin) delete bin;
+}
+
+
+//************************************************************************
+void CT1Analysis()
+{
+
+  gLog << "Entry CT1Analysis()" << endl;
+
+      gLog.SetNoColors();
+
+      if (gRandom)
+        delete gRandom;
+      gRandom = new TRandom3(0);
+
+      //-----------------------------------------------
+      const char *offfile = "~magican/ct1test/wittek/offdata.preproc"; 
+
+      //const char *onfile  = "~magican/ct1test/wittek/mkn421_on.preproc"; 
+      const char *onfile  = "~magican/ct1test/wittek/mkn421_00-01"; 
+
+      const char *mcfile  = "~magican/ct1test/wittek/mkn421_mc_pedrms_0.001.preproc";
+      //-----------------------------------------------
+
+      // path for input for Mars
+      TString inPath = "~magican/ct1test/wittek/marsoutput/optionC/";
+
+      // path for output from Mars
+      TString outPath = "~magican/ct1test/wittek/marsoutput/optionC/";
+
+      //-----------------------------------------------
+
+      //TEnv env("macros/CT1env.rc");
+      //Bool_t printEnv = kFALSE;
+
+    //************************************************************************
+
+    // Job A_ON : read ON data
+    //  - generate sigmabar vs. Theta plot; 
+    //  - write root file for ON data (ON1.root);
+
+    Bool_t JobA_ON = kFALSE;  
+    Bool_t WHistON = kFALSE;   // write out histogram sigmabar vs. Theta ?
+    Bool_t WON1    = kFALSE;   // write out root file ON1.root ?
+
+
+    // Job A_MC : read MC gamma data, 
+    //  - read sigmabar vs. Theta plot from ON data  
+    //  - do padding; 
+    //  - write root file for MC gammas (MC1.root);
+
+    Bool_t JobA_MC  = kFALSE;  
+    Bool_t WMC1     = kFALSE;  // write out root file MC1.root ?
+
+
+    // Job B_RF_UP : read ON1.root (or MC1.root) file 
+    //  - if RTrainRF = TRUE : read in training matrices for hadrons and gammas
+    //  - if CTrainRF = TRUE : create  training matrices for hadrons and gammas
+    //  - if RTree    = TRUE : read in trees, otherwise create trees
+    //  - calculate hadroness for method of RANDOM FOREST
+    //  - update the input files with the hadroness (==>ON2.root or MC2.root)
+
+    Bool_t JobB_RF_UP  = kFALSE;  
+    Bool_t CTrainRF    = kFALSE;  // create matrices of training events
+    Bool_t RTrainRF    = kFALSE;  // read in matrices of training events
+    Bool_t RTree       = kFALSE;  // read in trees (otherwise grow them)
+    Bool_t WRF         = kFALSE;  // update input root file ?
+
+
+
+
+    // Job B_SC_UP : read ON2.root (or MC2.root) file 
+    //  - depending on WParSC : create (or read in) supercuts parameter values
+    //  - calculate hadroness for the SUPERCUTS
+    //  - update the input files with the hadroness (==>ON3.root or MC3.root)
+
+    Bool_t JobB_SC_UP  = kFALSE;
+    Bool_t CMatrix     = kFALSE;  // create training and test matrices 
+    Bool_t RMatrix     = kFALSE;  // read training and test matrices from file
+    Bool_t WOptimize   = kFALSE;  // do optimization using the training sample
+                                  // and write supercuts parameter values 
+                                  // onto the file parSCfile
+    Bool_t RTest       = kFALSE;  // test the supercuts using the test matrix
+    Bool_t WSC         = kFALSE;  // update input root file ?
+
+
+
+    // Job C: 
+    //  - read ON3.root and MC3.root files
+    //    which should have been updated to contain the hadronnesses  
+    //    for the method of 
+    //              RF
+    //              SUPERCUTS and
+    //  - produce Neyman-Pearson plots
+
+    Bool_t JobC  = kFALSE;  
+
+
+    // Job D :  
+    //  - select g/h separation method XX
+    //  - read ON3 (or MC3) root file
+    //  - apply cuts in hadronness
+    //  - make plots
+
+    Bool_t JobD  = kFALSE;  
+
+
+
+
+    // Job E_XX : extended version of E_XX (including flux plots)  
+    //  - select g/h separation method XX
+    //  - read MC root file 
+    //  - calculate eff. collection area
+    //  - optimize energy estimator
+    //  - read ON root file 
+    //  - apply final cuts
+    //  - calculate flux
+    //  - write root file for ON data after final cuts 
+
+
+    Bool_t JobE_XX  = kTRUE;  
+    Bool_t CCollArea= kFALSE;  // calculate eff. collection areas
+    Bool_t OEEst    = kFALSE;  // optimize energy estimator
+    Bool_t WEX      = kTRUE;  // update root file  ?
+    Bool_t WRobert  = kTRUE;  // write out Robert's file  ?
+
+
+
+    //************************************************************************
+
+    
+  //---------------------------------------------------------------------
+  // Job A_ON
+  //=========
+    // read ON data file 
+
+    //  - produce the 2D-histogram "sigmabar versus Theta" 
+    //    (SigmaTheta_ON.root) for ON data
+    //    (to be used for the padding of the MC gamma data)
+
+    //  - write a file of ON events (ON1.root) 
+    //    (after the standard cuts, before the g/h separation)
+    //    (to be used together with the corresponding MC gamma file (MC1.root)
+    //     for the optimization of the g/h separation)
+
+
+ if (JobA_ON)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job A_ON" << endl;
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobA_ON, WHistON, WON1 = " 
+         << (JobA_ON ? "kTRUE" : "kFALSE")  << ",  " 
+         << (WHistON ? "kTRUE" : "kFALSE")  << ",  " 
+         << (WON1    ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // name of input root file
+    TString filenamein(onfile);
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += "ON";
+    outNameImage += "1.root";
+
+    //--------------------------------------------------
+    // use for padding sigmabar vs. Theta from ON data
+    TString typeHist = "ON";
+    gLog << "typeHist = " << typeHist << endl;
+
+    // name of file to conatin the histograms for the padding
+    TString outNameSigTh = outPath;
+    outNameSigTh += "SigmaTheta_";
+    outNameSigTh += typeHist;
+    outNameSigTh += ".root";
+
+
+    //-----------------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    char *sourceName = "MSrcPosCam";
+    MSrcPosCam source(sourceName);
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MCT1ReadPreProc read(filenamein);
+
+    MCT1PointingCorrCalc pointcorr(sourceName, "MCT1PointingCorrCalc", 
+                                               "MCT1PointingCorrCalc");
+    MBlindPixelCalc blind;
+    blind.SetUseBlindPixels();
+
+    MFCT1SelBasic selbasic;
+    MContinue contbasic(&selbasic);
+    contbasic.SetName("SelBasic");
+
+    MFillH fillblind("BlindPixels[MHBlindPixels]", "MBlindPixels");
+    fillblind.SetName("HBlind");
+
+    MSigmabarCalc sigbarcalc;
+
+    MFillH fillsigtheta ("SigmaTheta[MHSigmaTheta]", "MMcEvt");
+    fillsigtheta.SetName("HSigmaTheta");
+
+    MImgCleanStd    clean; 
+
+
+    // calculation of  image parameters ---------------------
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImgPar(fImgParName);
+
+    MHillasSrcCalc hsrccalc(sourceName, fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+    // --------------------------------------------------
+
+    MFCT1SelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+    selstandard.SetCuts(92, 4, 60, 0.4, 1.05, 0.0, 0.0);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+      //MWriteRootFile &write = *(new MWriteRootFile(outNameImage));
+      MWriteRootFile write(outNameImage, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+
+    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+    //MF daniel( "(MRawRunHeader.fRunNumber<13167)||(MRawRunHeader.fRunNumber>13167)" );
+    //MContinue contdaniel(&daniel);
+    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+
+    //*****************************
+    // entries in MParList
+    
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(&source);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    //$$$$$$$$$$$$$$$$
+    //tliston.AddToList(&contdaniel);
+    //$$$$$$$$$$$$$$$$
+
+    tliston.AddToList(&pointcorr);
+    tliston.AddToList(&blind);
+
+    tliston.AddToList(&contbasic);
+    tliston.AddToList(&fillblind);
+    tliston.AddToList(&sigbarcalc);
+    tliston.AddToList(&fillsigtheta);
+    tliston.AddToList(&clean);
+
+    tliston.AddToList(&hcalc);
+    tliston.AddToList(&hsrccalc);
+
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contstandard);
+    if (WON1)
+      tliston.AddToList(&write);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //if (WON1)
+    //  evtloop.Write();
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+
+    pliston.FindObject("SigmaTheta", "MHSigmaTheta")->DrawClone();
+
+    pliston.FindObject("BlindPixels", "MHBlindPixels")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+
+    //-------------------------------------------
+    // Write histograms onto a file
+  if (WHistON)
+  {
+      MHSigmaTheta *sigtheta = 
+            (MHSigmaTheta*)pliston.FindObject("SigmaTheta");
+
+      MHBlindPixels *blindpixels = 
+            (MHBlindPixels*)pliston.FindObject("BlindPixels");
+      if (!sigtheta  ||  !blindpixels)
+	{
+          gLog << "Object 'SigmaTheta' or 'BlindPixels' not found" << endl;
+          return;
+	}
+      TH2D *fHSigTh    = sigtheta->GetSigmaTheta();
+      TH3D *fHSigPixTh = sigtheta->GetSigmaPixTheta();
+      TH3D *fHDifPixTh = sigtheta->GetDiffPixTheta();
+
+      TH2D *fHBlindId  = blindpixels->GetBlindId();
+      TH2D *fHBlindN   = blindpixels->GetBlindN();
+
+
+      TFile outfile(outNameSigTh, "RECREATE");
+      fHSigTh->Write();
+      fHSigPixTh->Write();
+      fHDifPixTh->Write();
+     
+      fHBlindId->Write();
+      fHBlindN->Write();
+
+      gLog << "" << endl;
+      gLog << "File " << outNameSigTh << " was written out" << endl;
+  }
+
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro CT1Analysis : End of Job A_ON" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+
+  //---------------------------------------------------------------------
+   // Job A_MC
+   //=========
+
+    // read MC gamma data  
+
+    //    - to pad them
+    //      (using the 2D-histogram "sigmabar versus Theta" 
+    //       (SigmaTheta_ON.root)  of the ON data)
+
+    //    - to write a file of padded MC gamma events (MC1.root)
+    //      (after the standard cuts, before the g/h separation)
+    //      (to be used together with the corresponding hadron file
+    //       for the optimization of the g/h separation)
+
+
+ if (JobA_MC)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job A_MC" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobA_MC, WMC1 = " 
+         << (JobA_MC ? "kTRUE" : "kFALSE")  << ",  " 
+         << (WMC1    ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // name of input root file
+    TString filenamein(mcfile);
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += "MC";
+    outNameImage += "1.root";
+
+    //------------------------------------------------
+    // use for padding sigmabar vs. Theta from ON data
+    TString typeHist = "ON";
+    gLog << "typeHist = " << typeHist << endl;
+
+    // name of file containing the histograms for the padding
+    TString outNameSigTh = outPath;
+    outNameSigTh += "SigmaTheta_";
+    outNameSigTh += typeHist;
+    outNameSigTh += ".root";
+
+
+    //------------------------------------
+    // Get the histograms "2D-ThetaSigmabar"
+    // and                "3D-ThetaPixSigma"
+    // and                "3D-ThetaPixDiff"
+    // and                "2D-IdBlindPixels"
+    // and                "2D-NBlindPixels"
+
+
+      gLog << "Reading in file " << outNameSigTh << endl;
+
+      TFile *infile = new TFile(outNameSigTh);
+      infile->ls();
+
+      TH2D *fHSigmaTheta = 
+      (TH2D*) gROOT->FindObject("2D-ThetaSigmabar");
+      if (!fHSigmaTheta)
+	{
+          gLog << "Object '2D-ThetaSigmabar' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '2D-ThetaSigmabar' was read in" << endl;
+
+      TH3D *fHSigmaPixTheta = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigma");
+      if (!fHSigmaPixTheta)
+	{
+          gLog << "Object '3D-ThetaPixSigma' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '3D-ThetaPixSigma' was read in" << endl;
+
+      TH3D *fHDiffPixTheta = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiff");
+      if (!fHDiffPixTheta)
+	{
+          gLog << "Object '3D-ThetaPixDiff' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '3D-ThetaPixDiff' was read in" << endl;
+
+
+      TH2D *fHIdBlindPixels = 
+      (TH2D*) gROOT->FindObject("2D-IdBlindPixels");
+      if (!fHIdBlindPixels)
+	{
+          gLog << "Object '2D-IdBlindPixels' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '2D-IdBlindPixels' was read in" << endl;
+
+      TH2D *fHNBlindPixels = 
+      (TH2D*) gROOT->FindObject("2D-NBlindPixels");
+      if (!fHNBlindPixels)
+	{
+          gLog << "Object '2D-NBlindPixels' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '2D-NBlindPixels' was read in" << endl;
+
+    //------------------------------------
+
+    MTaskList tlist;
+    MParList plist;
+
+    char *sourceName = "MSrcPosCam";
+    MSrcPosCam source(sourceName);
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)plist->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MCT1ReadPreProc read(filenamein);
+
+    MBlindPixelCalc blindbeforepad;
+    blindbeforepad.SetUseBlindPixels();
+    blindbeforepad.SetName("BlindBeforePadding");
+
+    MBlindPixelCalc blind;
+    blind.SetUseBlindPixels();
+    blind.SetName("BlindAfterPadding");
+
+    MFCT1SelBasic selbasic;
+    MContinue contbasic(&selbasic);
+    contbasic.SetName("SelBasic");
+
+
+    // There are 2 options for Thomas Schweizer's padding
+    //     fPadFlag = 1   get Sigmabar from fHSigmaTheta
+    //                    and Sigma    from fHDiffPixTheta
+    //     fPadFlag = 2   get Sigma    from fHSigmaPixTheta
+    
+    MCT1PadSchweizer padthomas("MCT1PadSchweizer","Task for the padding (Schweizer)");
+    padthomas.SetHistograms(fHSigmaTheta, fHSigmaPixTheta, fHDiffPixTheta,
+                            fHIdBlindPixels, fHNBlindPixels);
+    padthomas.SetPadFlag(1);
+
+    MFillH fillblind("MCBlindPixels[MHBlindPixels]", "MBlindPixels");
+    fillblind.SetName("HBlind");
+
+
+    //...........................................
+
+    MSigmabarCalc sigbarcalc;
+
+    MFillH fillsigtheta ("MCSigmaTheta[MHSigmaTheta]", "MMcEvt");
+    fillsigtheta.SetName("HSigmaTheta");
+
+    MImgCleanStd    clean; 
+
+    // calculation of  image parameters ---------------------
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImgPar(fImgParName);
+
+    MHillasSrcCalc hsrccalc(sourceName, fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+    // --------------------------------------------------
+
+    MFCT1SelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+    selstandard.SetCuts(92, 4, 60, 0.4, 1.05, 0.0, 0.0);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+
+      //MWriteRootFile &write = *(new MWriteRootFile(outNameImage));
+      MWriteRootFile write(outNameImage, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+
+
+    //*****************************
+    // entries in MParList
+
+    plist.AddToList(&tlist);
+    InitBinnings(&plist);
+
+    plist.AddToList(&source);
+
+
+    //*****************************
+    // entries in MTaskList
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&blindbeforepad);
+    tlist.AddToList(&padthomas);
+    tlist.AddToList(&blind);
+
+    tlist.AddToList(&contbasic);
+    tlist.AddToList(&fillblind);
+    tlist.AddToList(&sigbarcalc);
+    tlist.AddToList(&fillsigtheta);
+    tlist.AddToList(&clean);
+
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&hsrccalc);
+
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+
+    tlist.AddToList(&contstandard);
+    if (WMC1)
+      tlist.AddToList(&write);
+
+    //*****************************
+
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //if (WMC1)    
+    //  evtloop.Write();
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 1000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    plist.FindObject("MCSigmaTheta",  "MHSigmaTheta")->DrawClone();
+    plist.FindObject("MCBlindPixels", "MHBlindPixels")->DrawClone();
+
+    plist.FindObject("MHHillas")->DrawClone();
+    plist.FindObject("MHHillasExt")->DrawClone();
+    plist.FindObject("MHHillasSrc")->DrawClone();
+    plist.FindObject("MHNewImagePar")->DrawClone();
+    plist.FindObject("MHStarMap")->DrawClone();
+
+
+
+    DeleteBinnings(&plist);
+
+    gLog << "Macro CT1Analysis : End of Job A_MC" 
+         << endl;
+    gLog << "=========================================================" 
+         << endl;
+ }
+
+
+
+  //---------------------------------------------------------------------
+  // Job B_RF_UP
+  //============
+
+
+    //  - create (or read in) the matrices of training events for gammas 
+    //    and hadrons
+    //  - create (or read in) the trees
+    //  - then read ON1.root (or MC1.root) file 
+    //  - calculate the hadroness for the method of RANDOM FOREST
+    //  - update input root file with the hadroness
+
+
+ if (JobB_RF_UP)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job B_RF_UP" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobB_RF_UP, RTrainRF, CTrainRF, RTree, WRF = "
+         << (JobB_RF_UP ? "kTRUE" : "kFALSE")  << ",  " 
+         << (RTrainRF ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (CTrainRF ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (RTree ?      "kTRUE" : "kFALSE")  << ",  "
+         << (WRF ?        "kTRUE" : "kFALSE")  << endl;
+
+
+    //--------------------------------------------
+    // parameters for the random forest
+    Int_t NumTrees = 100;
+    Int_t NumTry   =   3;
+    Int_t NdSize   =   1;
+
+
+    TString hadRFName = "HadRF";
+    Float_t maxhadronness =  0.23;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+    TString extin  = "1.root";
+    TString extout = "2.root";
+
+    //--------------------------------------------
+    // for the analysis using ON data only set typeMatrixHadrons = "ON"
+    //                        ON and OFF data                    = "OFF"
+    TString typeMatrixHadrons = "ON";
+    gLog << "typeMatrixHadrons = " << typeMatrixHadrons << endl;
+
+
+    // file to be updated (ON, OFF or MC)
+
+    //TString typeInput = "ON";
+    TString typeInput = "OFF";
+    //TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+    // name of input root file
+    TString NameData = outPath;
+    NameData += typeInput;
+    TString inNameData(NameData);
+    inNameData += extin;
+    gLog << "inNameData = " << inNameData << endl; 
+
+    // name of output root file
+    TString outNameData(NameData);
+    outNameData += extout;
+    gLog << "outNameData = " << outNameData << endl; 
+
+    //--------------------------------------------
+    // files to be read for generating 
+    //    - the matrices of training events
+    //    - and the root files of training and test events
+
+
+    // "hadrons" :
+    TString filenameHad = outPath;
+    filenameHad += typeMatrixHadrons;
+    filenameHad += extin;
+    Int_t howManyHadronsTrain = 12000;
+    Int_t howManyHadronsTest  = 12000;
+    gLog << "filenameHad = "    << filenameHad << ",   howManyHadronsTrain = "
+         << howManyHadronsTrain << ",   howManyHadronsTest = "
+         << howManyHadronsTest  << endl; 
+    
+
+    // "gammas" :
+    TString filenameMC = outPath;
+    filenameMC += "MC";
+    filenameMC += extin;
+    Int_t howManyGammasTrain = 12000;
+    Int_t howManyGammasTest  = 12000;
+    gLog << "filenameMC = "    << filenameMC << ",   howManyGammasTrain = "
+         << howManyGammasTrain << ",   howManyGammasTest = "
+         << howManyGammasTest  << endl; 
+    
+    //--------------------------------------------
+    // files for the matrices of training events 
+
+    TString NameGammas = outPath;
+    NameGammas += "RFmatrix_gammas_Train_";
+    NameGammas += "MC";
+    NameGammas += extin;
+
+    TString NameHadrons = outPath;
+    NameHadrons += "RFmatrix_hadrons_Train_";
+    NameHadrons += typeMatrixHadrons;
+    NameHadrons += extin;
+
+
+    //--------------------------------------------
+    // root files for the training events 
+
+    TString NameGammasTrain = outPath;
+    NameGammasTrain += "RF_gammas_Train_";
+    NameGammasTrain += "MC";
+    TString inNameGammasTrain(NameGammasTrain);    
+    inNameGammasTrain += extin;
+    TString outNameGammasTrain(NameGammasTrain);    
+    outNameGammasTrain += extout;
+
+
+    TString NameHadronsTrain = outPath;
+    NameHadronsTrain += "RF_hadrons_Train_";
+    NameHadronsTrain += typeMatrixHadrons;
+    TString inNameHadronsTrain(NameHadronsTrain);    
+    inNameHadronsTrain += extin;
+    TString outNameHadronsTrain(NameHadronsTrain);    
+    outNameHadronsTrain += extout;
+
+
+    //--------------------------------------------
+    // root files for the test events 
+
+    TString NameGammasTest = outPath;
+    NameGammasTest += "RF_gammas_Test_";
+    NameGammasTest += "MC";
+    TString inNameGammasTest(NameGammasTest);    
+    inNameGammasTest += extin;
+    TString outNameGammasTest(NameGammasTest);    
+    outNameGammasTest += extout;
+
+    TString NameHadronsTest = outPath;
+    NameHadronsTest += "RF_hadrons_Test_";
+    NameHadronsTest += typeMatrixHadrons;
+    TString inNameHadronsTest(NameHadronsTest);    
+    inNameHadronsTest += extin;
+    TString outNameHadronsTest(NameHadronsTest);    
+    outNameHadronsTest += extout;
+
+    //--------------------------------------------------------------------
+
+
+    MHMatrix matrixg("MatrixGammas");
+    matrixg.EnableGraphicalOutput();
+
+    matrixg.AddColumn("cos(MMcEvt.fTelescopeTheta)");
+    matrixg.AddColumn("MSigmabar.fSigmabar");
+    matrixg.AddColumn("log10(MHillas.fSize)");
+    matrixg.AddColumn("MHillasSrc.fDist");
+    matrixg.AddColumn("MHillas.fWidth");
+    matrixg.AddColumn("MHillas.fLength");
+    matrixg.AddColumn("log10(MHillas.fSize/(MHillas.fWidth*MHillas.fLength))");
+    matrixg.AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    matrixg.AddColumn("MNewImagePar.fConc");
+    matrixg.AddColumn("MNewImagePar.fLeakage1");
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.EnableGraphicalOutput();
+
+    matrixh.AddColumns(matrixg.GetColumns());
+
+    //--------------------------------------------
+    // file of trees of the random forest 
+
+    TString outRF = outPath;
+    outRF += "RF.root";
+
+
+   //*************************************************************************
+   // read in matrices of training events
+if (RTrainRF)
+  {
+    const char* mtxName = "MatrixGammas";
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Get matrix for (gammas)" << endl;
+    gLog << "matrix name        = " << mtxName << endl;
+    gLog << "name of root file  = " << NameGammas << endl;
+    gLog << "" << endl;
+
+
+    // read in the object with the name 'mtxName' from file 'NameGammas'
+    //
+    TFile fileg(NameGammas); 
+
+    matrixg.Read(mtxName);
+    matrixg.Print("SizeCols");
+
+
+    //***************************************************************** 
+
+    const char* mtxName = "MatrixHadrons";
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << " Get matrix for (hadrons)" << endl;
+    gLog << "matrix name        = " << mtxName << endl;
+    gLog << "name of root file  = " << NameHadrons << endl;
+    gLog << "" << endl;
+
+
+    // read in the object with the name 'mtxName' from file 'NameHadrons'
+    //
+    TFile fileh(NameHadrons); 
+
+    matrixh.Read(mtxName);
+    matrixh.Print("SizeCols");
+  }
+
+
+   //*************************************************************************
+   // create matrices of training events
+   // and root files of training and test events
+ 
+if (CTrainRF)
+  {
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << " Create matrices of training events and root files of training and test events" 
+         << endl;
+    gLog << " Gammas :" << endl;
+    gLog << "---------" << endl;
+
+    MParList  plistg;
+    MTaskList tlistg;
+
+    MReadMarsFile  readg("Events", filenameMC);
+    readg.DisableAutoScheme();
+
+    TString mgname("costhg");
+    MBinning bing("Binning"+mgname);
+    bing.SetEdges(10, 0., 1.0);
+
+    MH3 gref("cos(MMcEvt.fTelescopeTheta)");
+    gref.SetName(mgname);
+    MH::SetBinning(&gref.GetHist(), &bing);
+    //for (Int_t i=1; i<=gref.GetNbins(); i++)
+    //  gref.GetHist().SetBinContent(i, 1.0);
+
+    MFEventSelector2 selectorg(gref);
+    selectorg.SetNumMax(howManyGammasTrain+howManyGammasTest);
+    selectorg.SetName("selectGammasTrainTest");
+    selectorg.SetInverted();
+    //selectorg.SetUseOrigDistribution(kTRUE);
+
+    MContinue contg(&selectorg);
+    contg.SetName("ContGammas");
+
+    Double_t probg = ( (Double_t) howManyGammasTrain )
+                   / ( (Double_t)(howManyGammasTrain+howManyGammasTest) );
+    MFRandomSplit splitg(probg);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&splitg);
+    fillmatg.SetName("fillGammas");
+
+    //-----------------------
+    // for writing the root files of training and test events
+    // for gammas
+    
+    MWriteRootFile writetraing(inNameGammasTrain, "RECREATE");
+    writetraing.SetName("WriteGammasTrain");
+    writetraing.SetFilter(&splitg);
+
+      writetraing.AddContainer("MRawRunHeader", "RunHeaders");
+      writetraing.AddContainer("MTime",         "Events");
+      writetraing.AddContainer("MMcEvt",        "Events");
+      writetraing.AddContainer("ThetaOrig",     "Events");
+      writetraing.AddContainer("MSrcPosCam",    "Events");
+      writetraing.AddContainer("MSigmabar",     "Events");
+      writetraing.AddContainer("MHillas",       "Events");
+      writetraing.AddContainer("MHillasExt",    "Events");
+      writetraing.AddContainer("MHillasSrc",    "Events");
+      writetraing.AddContainer("MNewImagePar",  "Events");
+
+    MContinue contgtrain(&splitg);
+    contgtrain.SetName("ContGammaTrain");
+
+    MWriteRootFile writetestg(inNameGammasTest, "RECREATE");
+    writetestg.SetName("WriteGammasTest");
+
+      writetestg.AddContainer("MRawRunHeader", "RunHeaders");
+      writetestg.AddContainer("MTime",         "Events");
+      writetestg.AddContainer("MMcEvt",        "Events");
+      writetestg.AddContainer("ThetaOrig",     "Events");
+      writetestg.AddContainer("MSrcPosCam",    "Events");
+      writetestg.AddContainer("MSigmabar",     "Events");
+      writetestg.AddContainer("MHillas",       "Events");
+      writetestg.AddContainer("MHillasExt",    "Events");
+      writetestg.AddContainer("MHillasSrc",    "Events");
+      writetestg.AddContainer("MNewImagePar",  "Events");
+
+    //-----------------------
+    
+    //*****************************   fill gammas   ***  
+    // entries in MParList
+    
+    plistg.AddToList(&tlistg);
+    InitBinnings(&plistg);
+
+    plistg.AddToList(&matrixg);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tlistg.AddToList(&readg);
+    tlistg.AddToList(&contg);
+
+    tlistg.AddToList(&splitg);
+    tlistg.AddToList(&fillmatg);
+    tlistg.AddToList(&writetraing);
+    tlistg.AddToList(&contgtrain);
+
+    tlistg.AddToList(&writetestg);
+
+    //*****************************
+
+    MProgressBar matrixbar;
+    MEvtLoop evtloopg;
+    evtloopg.SetName("FillGammaMatrix");
+    evtloopg.SetParList(&plistg);
+    //evtloopg.ReadEnv(env, "", printEnv);
+    evtloopg.SetProgressBar(&matrixbar);
+
+    Int_t maxevents = -1;
+    if (!evtloopg.Eventloop(maxevents))
+        return;
+
+    tlistg.PrintStatistics(0, kTRUE);
+
+    matrixg.Print("SizeCols");
+    Int_t generatedgTrain = matrixg.GetM().GetNrows();
+    if ( fabs(generatedgTrain-howManyGammasTrain) > 
+                                    3.0*sqrt(howManyGammasTrain) )
+    {
+      gLog << "ONOFFCT1Analysis.C : no.of generated gamma training events (" 
+           << generatedgTrain << ") is incompatible with the no.of requested events (" 
+           << howManyGammasTrain << ")" << endl;   
+    }
+
+
+    Int_t generatedgTest = writetestg.GetNumExecutions();
+    if ( fabs(generatedgTest-howManyGammasTest) > 
+                                    3.0*sqrt(howManyGammasTest) )
+    {
+      gLog << "ONOFFCT1Analysis.C : no.of generated gamma test events (" 
+           << generatedgTest << ") is incompatible with the no.of requested events (" 
+           << howManyGammasTest << ")" << endl;   
+    }
+
+    //*****************************   fill hadrons   ***  
+    gLog << "---------------------------------------------------------------"
+         << endl;
+    gLog << " Hadrons :" << endl;
+    gLog << "----------" << endl;
+
+    MParList  plisth;
+    MTaskList tlisth;
+
+    MReadMarsFile  readh("Events", filenameHad);
+    readh.DisableAutoScheme();
+
+    TString mhname("costhh");
+    MBinning binh("Binning"+mhname);
+    binh.SetEdges(10, 0., 1.0);
+
+    //MH3 href("cos(MMcEvt.fTelescopeTheta)");
+    //href.SetName(mhname);
+    //MH::SetBinning(&href.GetHist(), &binh);
+    //for (Int_t i=1; i<=href.GetNbins(); i++)
+    //  href.GetHist().SetBinContent(i, 1.0);
+
+    //use the original distribution from the gammas
+    MH3 &href = *(selectorg.GetHistOrig());
+
+    MFEventSelector2 selectorh(href);
+    selectorh.SetNumMax(howManyHadronsTrain+howManyHadronsTest);
+    selectorh.SetName("selectHadronsTrainTest");
+    selectorh.SetInverted();
+
+    MContinue conth(&selectorh);
+    conth.SetName("ContHadrons");
+
+    Double_t probh = ( (Double_t) howManyHadronsTrain )
+                   / ( (Double_t)(howManyHadronsTrain+howManyHadronsTest) );
+    MFRandomSplit splith(probh);
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&splith);
+    fillmath.SetName("fillHadrons");
+
+    //-----------------------
+    // for writing the root files of training and test events
+    // for hadrons
+    
+    MWriteRootFile writetrainh(inNameHadronsTrain, "RECREATE");
+    writetrainh.SetName("WriteHadronsTrain");
+    writetrainh.SetFilter(&splith);
+
+      writetrainh.AddContainer("MRawRunHeader", "RunHeaders");
+      writetrainh.AddContainer("MTime",         "Events");
+      writetrainh.AddContainer("MMcEvt",        "Events");
+      writetrainh.AddContainer("ThetaOrig",     "Events");
+      writetrainh.AddContainer("MSrcPosCam",    "Events");
+      writetrainh.AddContainer("MSigmabar",     "Events");
+      writetrainh.AddContainer("MHillas",       "Events");
+      writetrainh.AddContainer("MHillasExt",    "Events");
+      writetrainh.AddContainer("MHillasSrc",    "Events");
+      writetrainh.AddContainer("MNewImagePar",  "Events");
+
+    MContinue conthtrain(&splith);
+
+    MWriteRootFile writetesth(inNameHadronsTest, "RECREATE");
+    writetesth.SetName("WriteHadronsTest");
+
+      writetesth.AddContainer("MRawRunHeader", "RunHeaders");
+      writetesth.AddContainer("MTime",         "Events");
+      writetesth.AddContainer("MMcEvt",        "Events");
+      writetesth.AddContainer("ThetaOrig",     "Events");
+      writetesth.AddContainer("MSrcPosCam",    "Events");
+      writetesth.AddContainer("MSigmabar",     "Events");
+      writetesth.AddContainer("MHillas",       "Events");
+      writetesth.AddContainer("MHillasExt",    "Events");
+      writetesth.AddContainer("MHillasSrc",    "Events");
+      writetesth.AddContainer("MNewImagePar",  "Events");
+
+
+    //*****************************  
+    // entries in MParList
+    
+    plisth.AddToList(&tlisth);
+    InitBinnings(&plisth);
+
+    plisth.AddToList(&matrixh);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tlisth.AddToList(&readh);
+    tlisth.AddToList(&conth);
+
+    tlisth.AddToList(&splith);
+    tlisth.AddToList(&fillmath);
+    tlisth.AddToList(&writetrainh);
+    tlisth.AddToList(&conthtrain);
+
+    tlisth.AddToList(&writetesth);
+
+    //*****************************
+
+    MProgressBar matrixbar;
+    MEvtLoop evtlooph;
+    evtlooph.SetName("FillHadronMatrix");
+    evtlooph.SetParList(&plisth);
+    //evtlooph.ReadEnv(env, "", printEnv);
+    evtlooph.SetProgressBar(&matrixbar);
+
+    Int_t maxevents = -1;
+    if (!evtlooph.Eventloop(maxevents))
+        return;
+
+    tlisth.PrintStatistics(0, kTRUE);
+
+    matrixh.Print("SizeCols");
+    Int_t generatedhTrain = matrixh.GetM().GetNrows();
+    if ( fabs(generatedhTrain-howManyHadronsTrain) > 
+                                    3.0*sqrt(howManyHadronsTrain) )
+    {
+      gLog << "ONOFFCT1Analysis.C : no.of generated hadron training events (" 
+           << generatedhTrain << ") is incompatible with the no.of requested events (" 
+           << howManyHadronsTrain << ")" << endl;   
+    }
+
+
+    Int_t generatedhTest = writetesth.GetNumExecutions();
+    if ( fabs(generatedhTest-howManyHadronsTest) > 
+                                    3.0*sqrt(howManyHadronsTest) )
+    {
+      gLog << "ONOFFCT1Analysis.C : no.of generated gamma test events (" 
+           << generatedhTest << ") is incompatible with the no.of requested events (" 
+           << howManyHadronsTest << ")" << endl;   
+    }
+
+
+    //*****************************************************  
+
+
+    // write out matrices of training events 
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Write out matrices of training events" << endl;
+
+
+      //-------------------------------------------
+      // "gammas"
+      gLog << "Gammas :" << endl;    
+      matrixg.Print("SizeCols");
+
+      TFile writeg(NameGammas, "RECREATE", "");
+      matrixg.Write();
+
+      gLog << "" << endl;
+      gLog << "Macro CT1Analysis : matrix of training events for gammas written onto file "
+           << NameGammas << endl;
+
+      //-------------------------------------------
+      // "hadrons"
+      gLog << "Hadrons :" << endl;    
+      matrixh.Print("SizeCols");
+
+      TFile writeh(NameHadrons, "RECREATE", "");
+      matrixh.Write();
+
+      gLog << "" << endl;
+      gLog << "Macro CT1Analysis : matrix of training events for hadrons written onto file "
+           << NameHadrons << endl;
+
+  }
+   //**********   end of creating matrices of training events   ***********
+
+
+    MRanForest *fRanForest;
+    MRanTree *fRanTree;
+    //-----------------------------------------------------------------
+    // read in the trees of the random forest 
+    if (RTree)
+    {
+      MParList plisttr;
+      MTaskList tlisttr;
+      plisttr.AddToList(&tlisttr);
+
+      MReadTree readtr("TREE", outRF);
+      readtr.DisableAutoScheme();
+
+      MRanForestFill rffill;
+      rffill.SetNumTrees(NumTrees);
+
+      // list of tasks for the loop over the trees
+
+      tlisttr.AddToList(&readtr);
+      tlisttr.AddToList(&rffill);
+
+      //-------------------
+      // Execute tree loop
+      //
+      MEvtLoop evtlooptr;
+      evtlooptr.SetName("ReadRFTrees");
+      evtlooptr.SetParList(&plisttr);
+      if (!evtlooptr.Eventloop())
+        return;
+
+      tlisttr.PrintStatistics(0, kTRUE);
+
+      gLog << "ONOFFCT1Analysis : RF trees were read in from file "
+           << outRF << endl;
+
+    // get adresses of objects which are used in the next eventloop
+    fRanForest = (MRanForest*)plisttr->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        gLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plisttr->FindObject("MRanTree");
+    if (!fRanTree)                                  
+    {                                                                          
+        gLog << err << dbginf << "MRanTree not found... aborting." << endl;    
+        return kFALSE;
+    }
+
+    }
+
+    //-----------------------------------------------------------------
+    // grow the trees of the random forest (event loop = tree loop)
+
+    if (!RTree)
+    {
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Macro CT1Analysis : start growing trees" << endl;
+
+    MTaskList tlist2;
+    MParList plist2;
+    plist2.AddToList(&tlist2);
+
+    plist2.AddToList(&matrixg);
+    plist2.AddToList(&matrixh);
+
+    MRanForestGrow rfgrow2;
+    rfgrow2.SetNumTrees(NumTrees);
+    rfgrow2.SetNumTry(NumTry);
+    rfgrow2.SetNdSize(NdSize);
+
+    MWriteRootFile rfwrite2(outRF);
+    rfwrite2.AddContainer("MRanTree", "TREE");
+
+    MFillH fillh2("MHRanForestGini");
+
+    // list of tasks for the loop over the trees
+    
+    tlist2.AddToList(&rfgrow2);
+    tlist2.AddToList(&rfwrite2);
+    tlist2.AddToList(&fillh2);
+
+    //-------------------
+    // Execute tree loop
+    //
+    MEvtLoop treeloop;
+    treeloop.SetName("GrowRFTrees");
+    treeloop.SetParList(&plist2);
+
+    if ( !treeloop.Eventloop() )
+        return;
+
+    tlist2.PrintStatistics(0, kTRUE);
+
+    plist2.FindObject("MHRanForestGini")->DrawClone();
+
+
+    // get adresses of objects which are used in the next eventloop
+    fRanForest = (MRanForest*)plist2->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        gLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plist2->FindObject("MRanTree");
+    if (!fRanTree)                                  
+    {                                                                          
+        gLog << err << dbginf << "MRanTree not found... aborting." << endl;    
+        return kFALSE;
+    }
+
+    }
+    // end of growing the trees of the random forest
+    //-----------------------------------------------------------------
+
+
+    //-----------------------------------------------------------------
+    // Update the root files with the RF hadronness
+    //
+
+ if (WRF)
+  {
+    //TString fileName(inNameHadronsTrain);
+    //TString outName(outNameHadronsTrain);
+
+    //TString fileName(inNameHadronsTest);
+    //TString outName(outNameHadronsTest);
+
+    //TString fileName(inNameGammasTrain);
+    //TString outName(outNameGammasTrain);
+
+    //TString fileName(inNameGammasTest);
+    //TString outName(outNameGammasTest);
+
+    TString fileName(inNameData);
+    TString outName(outNameData);
+
+
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Update root file '" <<  fileName 
+         << "' with the RF hadronness; ==> " << outName << endl;
+
+   
+    MTaskList tliston;
+    MParList pliston;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", fileName);
+    read.DisableAutoScheme();
+
+
+    //.......................................................................
+    // calculate hadronnes for method of RANDOM FOREST
+
+
+    MRanForestCalc rfcalc;
+    rfcalc.SetHadronnessName(hadRFName);
+
+
+    //.......................................................................
+
+      //MWriteRootFile write(outName, "UPDATE");
+      MWriteRootFile write(outName, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      write.AddContainer(hadRFName,       "Events");
+
+    //-----------------------------------------------------------------
+
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadRFName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillranfor("MHRanForest");
+    fillranfor.SetName("HRanForest");
+
+    MFillH fillhadrf("hadRF[MHHadronness]", hadRFName);
+    fillhadrf.SetName("HhadRF");
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadRFName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(fRanForest);
+    pliston.AddToList(fRanTree);
+
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&rfcalc);
+    tliston.AddToList(&fillranfor);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&write);
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetName("UpdateRootFile");
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+    pliston.FindObject("MHRanForest")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->Print();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+     //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-macro");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << fileName << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+
+    DeleteBinnings(&pliston);
+  }
+
+    gLog << "Macro CT1Analysis : End of Job B_RF_UP" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+  //---------------------------------------------------------------------
+  // Job B_SC_UP
+  //============
+
+    //  - create (or read in) optimum supercuts parameter values
+    //
+    //  - calculate the hadroness for the supercuts
+    //
+    //  - update input root file, including the hadroness
+
+
+ if (JobB_SC_UP)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job B_SC_UP" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobB_SC_UP, CMatrix, RMatrix, WOptimize, RTest, WSC = "
+         << (JobB_SC_UP ? "kTRUE" : "kFALSE")  << ",  " 
+         << (CMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (RMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (WOptimize  ? "kTRUE" : "kFALSE")  << ",  "
+         << (RTest      ? "kTRUE" : "kFALSE")  << ",  "
+         << (WSC        ? "kTRUE" : "kFALSE")  << endl;
+
+
+    //--------------------------------------------
+    // file which contains the initial parameter values for the supercuts 
+    // if parSCinit ="" the initial values are taken from the constructor of
+    //                  MCT1Supercuts
+
+    TString parSCinit = outPath;
+    //parSCinit += "parSC_1709d";
+    parSCinit = "";
+
+    gLog << "parSCinit = " << parSCinit << endl;
+
+    //---------------
+    // file onto which the optimal parameter values for the supercuts 
+    // are written
+
+    TString parSCfile = outPath;
+    parSCfile += "parSC_2310a";
+
+    gLog << "parSCfile = " << parSCfile << endl;
+
+    //--------------------------------------------
+    // file to be updated (either ON or MC)
+
+    //TString typeInput = "ON";
+    //TString typeInput = "OFF";
+    TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+    // name of input root file
+    TString filenameData = outPath;
+    filenameData += typeInput;
+    filenameData += "2.root";
+    gLog << "filenameData = " << filenameData << endl; 
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += typeInput;
+    outNameImage += "3.root";
+    
+
+    //TString outNameImage = filenameData;
+
+    gLog << "outNameImage = " << outNameImage << endl; 
+
+    //--------------------------------------------
+    // files to be read for optimizing the supercuts
+    // 
+    // for the training
+    TString filenameTrain = outPath;
+    filenameTrain += "ON";
+    filenameTrain += "1.root";
+    Int_t howManyTrain = 800000;
+    gLog << "filenameTrain = " << filenameTrain << ",   howManyTrain = "
+         << howManyTrain  << endl; 
+
+    // for testing
+    TString filenameTest = outPath;
+    filenameTest += "ON";
+    filenameTest += "1.root";
+    Int_t howManyTest = 800000;
+
+    gLog << "filenameTest = " << filenameTest << ",   howManyTest = "
+         << howManyTest  << endl; 
+    
+
+    //--------------------------------------------
+    // files to contain the matrices (generated from filenameTrain and
+    //                                               filenameTest)
+    // 
+    // for the training
+    TString fileMatrixTrain = outPath;
+    fileMatrixTrain += "MatrixTrainSC";
+    fileMatrixTrain += ".root";
+    gLog << "fileMatrixTrain = " << fileMatrixTrain << endl; 
+
+    // for testing
+    TString fileMatrixTest = outPath;
+    fileMatrixTest += "MatrixTestSC";
+    fileMatrixTest += ".root";
+    gLog << "fileMatrixTest = " << fileMatrixTest << endl; 
+
+    
+
+    //---------------------------------------------------------------------
+    // Training and test matrices :
+    // - either create them and write them onto a file
+    // - or read them from a file
+
+
+    MCT1FindSupercuts findsuper;
+    findsuper.SetFilenameParam(parSCfile);
+    findsuper.SetHadronnessName("HadSC");
+    //findsuper.SetUseOrigDistribution(kTRUE);
+
+    //--------------------------
+    // create matrices and write them onto files 
+    if (CMatrix)
+    {
+      TString mname("costheta");
+      MBinning bin("Binning"+mname);
+      bin.SetEdges(10, 0., 1.0);
+
+      MH3 mh3("cos(MMcEvt.fTelescopeTheta)");
+      mh3.SetName(mname);
+      MH::SetBinning(&mh3.GetHist(), &bin);
+      //for (Int_t i=1; i<=mh3.GetNbins(); i++)
+      //  mh3.GetHist().SetBinContent(i, 1.0);
+
+
+      if (filenameTrain == filenameTest)
+      {
+        if ( !findsuper.DefineTrainTestMatrix(
+                              filenameTrain,   mh3, 
+                              howManyTrain,    howManyTest,  
+                              fileMatrixTrain, fileMatrixTest)     )
+        {
+          *fLog << "CT1Analysis.C : DefineTrainTestMatrix failed" << endl;
+          return;
+        }
+
+      }
+      else
+      {
+        if ( !findsuper.DefineTrainMatrix(filenameTrain, mh3,
+                                          howManyTrain,  fileMatrixTrain) )
+        {
+          *fLog << "CT1Analysis.C : DefineTrainMatrix failed" << endl;
+          return;
+        }
+
+	if ( !findsuper.DefineTestMatrix( filenameTest, mh3, 
+                                          howManyTest,  fileMatrixTest)  )
+        {
+          *fLog << "CT1Analysis.C : DefineTestMatrix failed" << endl;
+          return;
+        }
+      }
+     }
+
+    //--------------------------
+    // read matrices from files
+    //                              
+
+    if (RMatrix)
+      findsuper.ReadMatrix(fileMatrixTrain, fileMatrixTest);
+    //--------------------------
+
+
+
+    //---------------------------------------------------------------------
+    // optimize supercuts using the training sample
+    // 
+    // the initial values are taken 
+    //     - from the file parSCinit (if != "")
+    //     - or from the arrays params and steps (if their sizes are != 0)
+    //     - or from the MCT1Supercuts constructor
+
+
+if (WOptimize)
+  {
+    gLog << "CT1Analysis.C : optimize the supercuts using the training matrix" 
+         << endl;
+
+    TArrayD params(0);
+    TArrayD steps(0);
+  
+    if (parSCinit == "")
+    {
+      Double_t vparams[104] = {
+      // LengthUp
+	0.315585,  0.001455, 0.203198, 0.005532, -0.001670, -0.020362,
+	0.007388, -0.013463,
+      // LengthLo
+        0.151530,  0.028323, 0.510707, 0.053089,  0.013708,  2.357993,
+	0.000080, -0.007157,
+      // WidthUp
+        0.145412, -0.001771, 0.054462, 0.022280, -0.009893,  0.056353,
+        0.020711, -0.016703,
+      // WidthLo
+        0.089187, -0.006430, 0.074442, 0.003738, -0.004256, -0.014101,
+        0.006126, -0.002849,
+      // DistUp
+        1.787943,  0.0,      2.942310, 0.199815,  0.0,       0.249909,
+        0.189697,  0.0,
+      // DistLo
+        0.589406,  0.0,     -0.083964,-0.007975,  0.0,       0.045374,
+       -0.001750,  0.0,
+      // AsymUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp
+	13.12344,  0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+      Double_t vsteps[104] = {
+      // LengthUp
+        0.03,      0.0002,   0.02,     0.0006,    0.0002,    0.002,
+        0.0008,    0.002,
+      // LengthLo
+        0.02,      0.003,    0.05,     0.006,     0.002,     0.3,
+        0.0001,    0.0008,
+      // WidthUp
+        0.02,      0.0002,   0.006,    0.003,     0.002,     0.006,
+        0.002,     0.002,
+      // WidthLo
+        0.009,     0.0007,   0.008,    0.0004,    0.0005,    0.002,
+        0.0007,    0.003,
+      // DistUp
+        0.2,       0.0,      0.3,      0.02,      0.0,       0.03,
+        0.02,      0.0
+      // DistLo
+        0.06,      0.0,      0.009,    0.0008,    0.0,       0.005,
+        0.0002,    0.0
+      // AsymUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+      params.Set(104, vparams);
+      steps.Set (104, vsteps );
+    }
+
+    Bool_t rf;
+    rf = findsuper.FindParams(parSCinit, params, steps);
+
+    if (!rf) 
+    {
+       gLog << "CT1Analysis.C : optimization of supercuts failed" << endl;
+       return;
+    }
+  }
+
+    //--------------------------------------
+    // test the supercuts on the test sample
+    //    
+
+ if (RTest)
+ {
+    gLog << "CT1Analysis.C : test the supercuts on the test matrix" << endl;
+    Bool_t rt = findsuper.TestParams();
+    if (!rt) 
+    {
+       gLog << "CT1Analysis.C : test of supercuts on the test matrix failed" 
+            << endl;
+    }
+
+ }
+
+
+    //-----------------------------------------------------------------
+    // Update the input files with the SC hadronness
+    //
+
+ if (WSC)
+ {
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Update input file '" <<  filenameData 
+         << "' with the SC hadronness" << endl;
+
+
+    //----------------------------------------------------
+    // read in optimum parameter values for the supercuts
+
+    TFile inparam(parSCfile);
+    MCT1Supercuts scin;
+    scin.Read("MCT1Supercuts");
+    inparam.Close();
+
+    gLog << "Parameter values for supercuts were read in from file '"
+         << parSCfile << "'" << endl;
+
+    TArrayD supercutsPar;
+    supercutsPar =  scin.GetParameters();
+
+    TArrayD supercutsStep;
+    supercutsStep =  scin.GetStepsizes();
+
+    gLog << "Parameter values for supercuts : " << endl;
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+    {
+      gLog << supercutsPar[i] << ",  ";
+    }
+    gLog << endl;
+
+    gLog << "Step values for supercuts : " << endl;
+    for (Int_t i=0; i<supercutsStep.GetSize(); i++)
+    {
+      gLog << supercutsStep[i] << ",  ";
+    }
+    gLog << endl;
+
+
+    //----------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    // set the parameters of the supercuts
+    MCT1Supercuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+    gLog << "parameter values for the supercuts used for updating the input file ' " 
+         << filenameData << "'" << endl;
+    supercutsPar = supercuts.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+    {
+      gLog << supercutsPar[i] << ",  ";
+    }
+    gLog << endl;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+    //.......................................................................
+    // calculation of hadroness for the supercuts
+    // (=0.25 if fullfilled, =0.75 otherwise)
+
+    TString hadSCName = "HadSC";
+    MCT1SupercutsCalc sccalc(fHilName, fHilNameSrc);
+    sccalc.SetHadronnessName(hadSCName);
+
+
+    //.......................................................................
+
+
+      //MWriteRootFile write(outNameImage, "UPDATE");
+      //MWriteRootFile write = new MWriteRootFile(outNameImage, "RECREATE");
+
+    
+      MWriteRootFile write(outNameImage, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      write.AddContainer("HadRF",         "Events");
+      write.AddContainer(hadSCName,       "Events");
+    
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    Float_t maxhadronness =  0.40;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadSCName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillhadsc("hadSC[MHHadronness]", hadSCName);
+    fillhadsc.SetName("HhadSC");
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadSCName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+
+    TH1  &alphahist = alphaabs->GetHist();
+
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(&supercuts);
+
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&sccalc);
+    tliston.AddToList(&fillhadsc);
+
+    tliston.AddToList(&write);
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+     //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-macro");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << filenameData << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+    DeleteBinnings(&pliston);
+ }
+
+
+    gLog << "Macro CT1Analysis : End of Job B_SC_UP" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+
+  //---------------------------------------------------------------------
+  // Job C  
+  //======
+
+    //  - read ON1 and MC1 data files  
+    //    which should have been updated to contain the hadronnesses
+    //    for the method of Random Forest and for the SUPERCUTS
+    //  - produce Neyman-Pearson plots
+ 
+ if (JobC)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job C" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobC = " 
+         << (JobC       ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // name of input data file
+    TString filenameData = outPath;
+    filenameData += "ON";
+    filenameData += "3.root";
+    gLog << "filenameData = " << filenameData << endl;
+
+    // name of input MC file
+    TString filenameMC = outPath;
+    filenameMC += "MC";
+    filenameMC += "3.root";
+    gLog << "filenameMC   = " << filenameMC   << endl;
+
+
+    //-----------------------------------------------------------------
+
+    MTaskList tliston;
+    MParList pliston;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameMC);
+    read.AddFile(filenameData);
+    read.DisableAutoScheme();
+
+
+    //.......................................................................
+    // names of hadronness containers
+
+    //TString hadNNName = "HadNN";
+    TString hadSCName = "HadSC";
+    TString hadRFName = "HadRF";
+
+    //.......................................................................
+
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+    Float_t maxhadronness =  0.40;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadSCName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    //MFillH fillhadnn("hadNN[MHHadronness]", hadNNName);
+    //fillhadnn.SetName("HhadNN");
+    MFillH fillhadsc("hadSC[MHHadronness]", hadSCName);
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", hadRFName);
+    fillhadrf.SetName("HhadRF");
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadSCName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    //tliston.AddToList(&fillhadnn);
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+   
+    tliston.AddToList(&contfinalgh);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 35000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    //pliston.FindObject("hadNN", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro CT1Analysis : End of Job C" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+
+  //---------------------------------------------------------------------
+  // Job D
+  //======
+
+    //  - select g/h separation method XX
+    //  - read ON2 (or MC2) root file 
+    //  - apply cuts in hadronness
+    //  - make plots
+
+
+ if (JobD)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job D" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobD = " 
+         << (JobD        ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // type of data to be analysed
+    TString typeData = "ON";
+    //TString typeData = "OFF";
+    //TString typeData = "MC";
+    gLog << "typeData = " << typeData << endl;
+
+    TString ext      = "3.root";
+
+
+    //------------------------------
+    // selection of g/h separation method
+    // and definition of final selections
+
+    //TString XX("SC");
+    TString XX("RF");
+    TString fhadronnessName("Had");
+    fhadronnessName += XX;
+    gLog << "fhadronnessName = " << fhadronnessName << endl;
+
+    // maximum values of the hadronness, |ALPHA| and DIST
+    Float_t maxhadronness   = 0.233;
+    Float_t maxalpha        = 20.0;
+    Float_t maxdist         = 10.0;
+    gLog << "Maximum values of hadronness, |ALPHA| and DIST = "
+         << maxhadronness << ",  " << maxalpha << ",  " 
+         << maxdist << endl;
+
+
+    //------------------------------
+    // name of data file to be analysed
+    TString filenameData(outPath);
+    filenameData += typeData;
+    filenameData += ext;
+    gLog << "filenameData = " << filenameData << endl;
+
+
+
+    //*************************************************************************
+    //
+    // Analyse the data
+    //
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(fhadronnessName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillhadsc("hadSC[MHHadronness]", "HadSC");
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", "HadRF");
+    fillhadrf.SetName("HhadRF");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+
+    TH1  &alphahist = alphaabs->GetHist();
+
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");    
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");    
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(fhadronnessName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 10000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+    //-------------------------------------------
+
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-JobD");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << filenameData << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro CT1Analysis : End of Job D" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+
+
+  //---------------------------------------------------------------------
+  // Job E_XX
+  //=========
+
+    //  - select g/h separation method XX
+    //  - read MC_XX2.root file 
+    //  - calculate eff. collection area
+    //  - read ON_XX2.root file 
+    //  - apply final cuts
+    //  - calculate flux
+    //  - write root file for ON data after final cuts (ON_XX3.root))
+
+
+ if (JobE_XX)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job E_XX" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobE_XX, CCollArea, OEEst, WEX = " 
+         << (JobE_XX ? "kTRUE" : "kFALSE")  << ",  " 
+         << (CCollArea?"kTRUE" : "kFALSE")  << ",  " 
+         << (OEEst ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (WEX     ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // type of data to be analysed
+    //TString typeData = "ON";
+    //TString typeData = "OFF";
+    TString typeData = "MC";
+    gLog << "typeData = " << typeData << endl;
+
+    TString typeMC   = "MC";
+    TString ext      = "3.root";
+    TString extout   = "4.root";
+
+    //------------------------------
+    // selection of g/h separation method
+    // and definition of final selections
+
+    //TString XX("SC");
+    TString XX("RF");
+    TString fhadronnessName("Had");
+    fhadronnessName += XX;
+    gLog << "fhadronnessName = " << fhadronnessName << endl;
+
+    // maximum values of the hadronness, |ALPHA| and DIST
+    Float_t maxhadronness   = 0.23;
+    Float_t maxalpha        = 20.0;
+    Float_t maxdist         = 10.0;
+    gLog << "Maximum values of hadronness, |ALPHA| and DIST = "
+         << maxhadronness << ",  " << maxalpha << ",  " 
+         << maxdist << endl;
+
+    //------------------------------
+    // name of MC file to be used for optimizing the energy estimator
+    TString filenameOpt(outPath);
+    filenameOpt += typeMC;
+    filenameOpt += ext; 
+    gLog << "filenameOpt = " << filenameOpt << endl;
+
+    //------------------------------
+    // name of file containing the parameters of the energy estimator
+    TString energyParName(outPath);
+    energyParName += "energyest_";
+    energyParName += XX;
+    energyParName += ".root";
+    gLog << "energyParName = " << energyParName << endl;
+
+    //------------------------------
+    // name of MC file to be used for calculating the eff. collection areas
+    TString filenameArea(outPath);
+    filenameArea += typeMC;
+    filenameArea += ext; 
+    gLog << "filenameArea = " << filenameArea << endl;
+
+    //------------------------------
+    // name of file containing the eff. collection areas
+    TString collareaName(outPath);
+    collareaName += "area_";
+    collareaName += XX;
+    collareaName += ".root";
+    gLog << "collareaName = " << collareaName << endl;
+
+    //------------------------------
+    // name of data file to be analysed
+    TString filenameData(outPath);
+    filenameData += typeData;
+    filenameData += ext;
+    gLog << "filenameData = " << filenameData << endl;
+
+    //------------------------------
+    // name of output data file (after the final cuts)
+    TString filenameDataout(outPath);
+    filenameDataout += typeData;
+    filenameDataout += "_";
+    filenameDataout += XX;
+    filenameDataout += extout;
+    gLog << "filenameDataout = " << filenameDataout << endl;
+
+    //------------------------------
+    // name of file containing histograms for flux calculastion
+    TString filenameResults(outPath);
+    filenameResults += typeData;
+    filenameResults += "Results_";
+    filenameResults += XX;
+    filenameResults += extout;
+    gLog << "filenameResults = " << filenameResults << endl;
+
+
+    //====================================================================
+
+    MHMcCT1CollectionArea collarea;
+    collarea.SetEaxis(MHMcCT1CollectionArea::kLinear);
+
+    MParList  parlist;
+    InitBinnings(&parlist);
+
+  if (CCollArea)
+  {
+    gLog << "-----------------------------------------------" << endl;
+    gLog << "Start calculation of effective collection areas" << endl;
+
+
+    MTaskList tasklist;
+
+    //---------------------------------------
+    // Setup the tasks to be executed
+    //
+    MReadMarsFile reader("Events", filenameArea);
+    reader.DisableAutoScheme();
+
+    MFCT1SelFinal cuthadrons;
+    cuthadrons.SetHadronnessName(fhadronnessName);
+    cuthadrons.SetCuts(maxhadronness, maxalpha, maxdist);
+
+    MContinue conthadrons(&cuthadrons);
+
+
+    MFillH filler("MHMcCT1CollectionArea", "MMcEvt");
+    filler.SetName("CollectionArea");
+
+    //********************************
+    // entries in MParList
+
+    parlist.AddToList(&tasklist);
+
+    parlist.AddToList(&collarea);
+
+    //********************************
+    // entries in MTaskList
+
+    tasklist.AddToList(&reader);   
+    tasklist.AddToList(&conthadrons);
+    tasklist.AddToList(&filler);
+
+    //********************************
+
+    //-----------------------------------------
+    // Execute event loop
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    MProgressBar bar;
+    magic.SetProgressBar(&bar);
+    if (!magic.Eventloop())
+        return;
+
+    tasklist.PrintStatistics(0, kTRUE);
+
+    // Calculate effective collection areas 
+    // and display the histograms
+    //
+    //MHMcCT1CollectionArea *collarea = 
+    //     (MHMcCT1CollectionArea*)parlist.FindObject("MHMcCT1CollectionArea");
+    collarea.CalcEfficiency();
+    collarea.DrawClone();
+
+
+
+    //---------------------------------------------
+    // Write histograms to a file 
+    //
+
+    TFile f(collareaName, "RECREATE");
+    //collarea.GetHist()->Write();
+    //collarea.GetHAll()->Write();
+    //collarea.GetHSel()->Write();
+    collarea.Write();
+
+    f.Close();
+
+    gLog << "Collection area plots written onto file " << collareaName << endl;
+
+    gLog << "Calculation of effective collection areas done" << endl;
+    gLog << "-----------------------------------------------" << endl;    
+    //------------------------------------------------------------------
+  }
+
+  if (!CCollArea)
+  {
+    gLog << "-----------------------------------------------" << endl;
+    gLog << "Read in effective collection areas from file " 
+         << collareaName << endl;
+
+    TFile collfile(collareaName);
+    collfile.ls();
+    collarea.Read("MHMcCT1CollectionArea");
+    collarea.DrawClone();
+
+    gLog << "Effective collection areas were read in from file " 
+         << collareaName << endl;
+    gLog << "-----------------------------------------------" << endl;    
+  }
+
+
+    // save binnings for call to CT1EEst
+    MBinning *binsE     = (MBinning*)parlist.FindObject("BinningE");
+    if (!binsE)
+	{
+          gLog << "Object 'BinningE' not found in MParList" << endl;
+          return;
+	}
+    MBinning *binsTheta = (MBinning*)parlist.FindObject("BinningTheta");
+    if (!binsTheta)
+	{
+          gLog << "Object 'BinningTheta' not found in MParList" << endl;
+          return;
+	}
+
+    //-------------------------------------
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+ if (OEEst)
+ { 
+   //===========================================================
+    //
+    // Optimization of energy estimator
+    //
+    gLog << "Macro CT1Analysis.C : calling CT1EEst" << endl;
+
+    TString inpath("");
+    TString outpath("");
+    Int_t howMany = 2000;
+    CT1EEst(inpath,   filenameOpt,   outpath, energyParName, 
+            fHilName, fHilNameSrc,   fhadronnessName,
+            howMany,  maxhadronness, maxalpha, maxdist,
+            binsE, binsTheta);
+    gLog << "Macro CT1Analysis.C : returning from CT1EEst" << endl;
+ }
+
+ if (WEX)
+ {
+    //-----------------------------------------------------------
+    //
+    // Read in parameters of energy estimator ("MMcEnergyEst")
+    //                   and migration matrix ("MHMcEnergyMigration")
+    //
+    gLog << "================================================================"
+         << endl;
+    gLog << "Macro CT1Analysis.C : read parameters of energy estimator and migration matrix from file '"
+         << energyParName << "'" << endl;
+    TFile enparam(energyParName);
+    enparam.ls();
+    MMcEnergyEst mcest("MMcEnergyEst"); 
+    mcest.Read("MMcEnergyEst");
+
+    //MMcEnergyEst &mcest = *((MMcEnergyEst*)gROOT->FindObject("MMcEnergyEst"));
+    gLog << "Parameters of energy estimator were read in" << endl;
+
+
+    gLog << "Read in Migration matrix" << endl;   
+
+    MHMcEnergyMigration mighiston("MHMcEnergyMigration");
+    mighiston.Read("MHMcEnergyMigration");
+    //MHMcEnergyMigration &mighiston = 
+    //      *((MHMcEnergyMigration*)gROOT->FindObject("MHMcEnergyMigration"));
+
+    gLog << "Migration matrix was read in" << endl;
+
+
+    TArrayD parA(mcest.GetNumCoeffA());
+    TArrayD parB(mcest.GetNumCoeffB());
+    for (Int_t i=0; i<parA.GetSize(); i++)
+      parA[i] = mcest.GetCoeff(i);
+    for (Int_t i=0; i<parB.GetSize(); i++)
+      parB[i] = mcest.GetCoeff( i+parA.GetSize() );
+
+    //*************************************************************************
+    //
+    // Analyse the data
+    //
+    gLog << "============================================================"
+         << endl;
+    gLog << "Analyse the data" << endl;
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+    //.......................................................................
+
+      gLog << "CT1Analysis.C : write root file '" << filenameDataout 
+           << "'" << endl;
+   
+      //MWriteRootFile &write = *(new MWriteRootFile(filenameDataout));
+
+
+      MWriteRootFile write(filenameDataout, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      //write.AddContainer("HadNN",         "Events");
+      write.AddContainer("HadSC",         "Events");
+      write.AddContainer("HadRF",         "Events");
+
+      write.AddContainer("MEnergyEst",    "Events");
+
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(fhadronnessName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    //MFillH fillhadnn("hadNN[MHHadronness]", "HadNN");
+    //fillhadnn.SetName("HhadNN");
+    MFillH fillhadsc("hadSC[MHHadronness]", "HadSC");
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", "HadRF");
+    fillhadrf.SetName("HhadRF");
+
+    //---------------------------
+    // calculate estimated energy
+
+    MEnergyEstParam eeston(fHilName);
+    eeston.Add(fHilNameSrc);
+
+    eeston.SetCoeffA(parA);
+    eeston.SetCoeffB(parB);
+
+    //---------------------------
+    // calculate estimated energy using Daniel's parameters
+
+    //MEnergyEstParamDanielMkn421 eeston(fHilName);
+    //eeston.Add(fHilNameSrc);
+    //eeston.SetCoeffA(parA);
+    //eeston.SetCoeffB(parB);
+
+
+    //---------------------------
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");    
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");    
+
+    //---------------------------
+    // new from Robert
+
+    MFillH hfill6("MHTimeDiffTheta", "MMcEvt");
+    hfill6.SetName("HTimeDiffTheta");
+
+    MFillH hfill6a("MHTimeDiffTime", "MMcEvt");
+    hfill6a.SetName("HTimeDiffTime");
+
+    MFillH hfill7("MHAlphaEnergyTheta", fHilNameSrc);
+    hfill7.SetName("HAlphaEnergyTheta");
+
+    MFillH hfill7a("MHAlphaEnergyTime", fHilNameSrc);
+    hfill7a.SetName("HAlphaEnergyTime");
+
+    MFillH hfill7b("MHThetabarTime", fHilNameSrc);
+    hfill7b.SetName("HThetabarTime");
+
+    MFillH hfill7c("MHEnergyTime", "MMcEvt");
+    hfill7c.SetName("HEnergyTime");
+
+
+    //---------------------------
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(fhadronnessName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    // robert      
+    tliston.AddToList(&hfill6);   //timediff
+    tliston.AddToList(&hfill6a);   //timediff
+
+    tliston.AddToList(&contfinalgh);
+    tliston.AddToList(&eeston);
+
+    tliston.AddToList(&write);
+
+    //tliston.AddToList(&fillhadnn);
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    //robert
+    tliston.AddToList(&hfill7);
+    tliston.AddToList(&hfill7a);
+    tliston.AddToList(&hfill7b);
+    tliston.AddToList(&hfill7c);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    //pliston.FindObject("hadNN", "MHHadronness")->DrawClone();
+
+    gLog << "before hadRF" << endl;
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+
+    gLog << "before hadSC" << endl;
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    gLog << "before MHHillas" << endl;
+    pliston.FindObject("MHHillas")->DrawClone();
+
+    gLog << "before MHHillasExt" << endl;
+    pliston.FindObject("MHHillasExt")->DrawClone();
+
+    gLog << "before MHHillasSrc" << endl;
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+
+    gLog << "before MHNewImagePar" << endl;
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+
+    gLog << "before MHStarMap" << endl;
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    gLog << "before DeleteBinnings" << endl;
+
+    DeleteBinnings(&pliston);
+
+    gLog << "before Robert's code" << endl;
+
+
+//rwagner write all relevant histograms onto a file
+
+  if (WRobert)
+  {
+    gLog << "=======================================================" << endl;
+    gLog << "Write results onto file '" << filenameResults << "'" << endl;
+
+    TFile outfile(filenameResults,"recreate");
+
+    MHHillasSrc* hillasSrc = 
+      (MHHillasSrc*)(pliston->FindObject("MHHillasSrc"));
+        TH1F* alphaHist = (TH1F*)(hillasSrc->GetHistAlpha());
+    alphaHist->Write();
+    gLog << "Alpha plot has been written out" << endl;    
+
+
+    MHAlphaEnergyTheta* aetH = 
+      (MHAlphaEnergyTheta*)(pliston->FindObject("MHAlphaEnergyTheta"));
+    TH3D* aetHist = (TH3D*)(aetH->GetHist());
+    aetHist->SetName("aetHist");
+    aetHist->Write();
+    gLog << "AlphaEnergyTheta plot has been written out" << endl;    
+
+    MHAlphaEnergyTime* aetH2 = 
+      (MHAlphaEnergyTime*)(pliston->FindObject("MHAlphaEnergyTime"));
+    TH3D* aetHist2 = (TH3D*)(aetH2->GetHist());
+    aetHist2->SetName("aetimeHist");
+//     aetHist2->DrawClone();
+    aetHist2->Write();
+    gLog << "AlphaEnergyTime plot has been written out" << endl;    
+
+    MHThetabarTime* tbt = 
+      (MHThetabarTime*)(pliston->FindObject("MHThetabarTime"));
+    TProfile* tbtHist = (TProfile*)(tbt->GetHist());
+    tbtHist->SetName("tbtHist");
+    tbtHist->Write();
+    gLog << "ThetabarTime plot has been written out" << endl;    
+
+    MHEnergyTime* ent = 
+      (MHEnergyTime*)(pliston->FindObject("MHEnergyTime"));
+    TH2D* entHist = (TH2D*)(ent->GetHist());
+    entHist->SetName("entHist");
+    entHist->Write();
+    gLog << "EnergyTime plot has been written out" << endl;    
+    
+    MHTimeDiffTheta *time = (MHTimeDiffTheta*)pliston.FindObject("MHTimeDiffTheta");
+    TH2D* timeHist = (TH2D*)(time->GetHist());
+    timeHist->SetName("MHTimeDiffTheta");
+    timeHist->SetTitle("Time diffs");
+    timeHist->Write();
+    gLog << "TimeDiffTheta plot has been written out" << endl;    
+
+
+    MHTimeDiffTime *time2 = (MHTimeDiffTime*)pliston.FindObject("MHTimeDiffTime");
+    TH2D* timeHist2 = (TH2D*)(time2->GetHist());
+    timeHist2->SetName("MHTimeDiffTime");
+    timeHist2->SetTitle("Time diffs");
+    timeHist2->Write();
+    gLog << "TimeDiffTime plot has been written out" << endl;    
+
+//rwagner write also collareas to same file
+    collarea->GetHist()->Write();
+    collarea->GetHAll()->Write();
+    collarea->GetHSel()->Write();
+    gLog << "Effective collection areas have been written out" << endl;        
+
+//rwagner todo: write alpha_cut, type of g/h sep (RF, SC, NN), type of data
+//rwagner (ON/OFF/MC), MJDmin, MJDmax to this file
+
+    gLog << "before closing outfile" << endl;
+
+    //outfile.Close();
+    gLog << "Results were written onto file '" << filenameResults 
+         << "'" << endl;
+    gLog << "=======================================================" << endl;
+  }
+
+  }
+
+    gLog << "Macro CT1Analysis : End of Job E_XX" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/CT1EgyEst.C
===================================================================
--- /tags/Mars-V0.9/macros/CT1EgyEst.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/CT1EgyEst.C	(revision 9772)
@@ -0,0 +1,331 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz,  09/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Abelardo Moralejo, 03/2003 <mailto:moralejo@pd.infn.it>
+!              Wolfgang Wittek,   04/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MGeomCamCT1.h"
+#include "MFEventSelector.h"
+#include "MReadTree.h"
+#include "MFCT1SelFinal.h"
+#include "MHMatrix.h"
+#include "MEnergyEstParam.h"
+//#include "MEnergyEstParamDanielMkn421.h"
+#include "MMatrixLoop.h"
+#include "MChisqEval.h"
+
+/*
+#include "MLog.h"
+#include "MLogManip.h"
+*/
+
+void CT1EgyEst()
+{
+  //  TString inPath        = "~magican/ct1test/wittek/marsoutput/optionA/";
+  TString inPath        = "./";
+  TString fileNameIn    = "MC1.root";
+
+  //  TString outPath       = "~magican/ct1test/wittek/marsoutput/optionA/";
+  TString outPath       = "./";
+  TString energyParName = "energyest.root";
+ 
+  TString hilName    = "MHillas";
+  TString hilSrcName = "MHillasSrc";
+
+  //  TString hadronnessName = "MHadronness";
+  TString hadronnessName = "HadNN";
+
+  //  Int_t howMany = 10000;
+  Int_t howMany = 2000;
+
+  Float_t maxhadronness = 0.3;
+  Float_t maxalpha      = 20.0;
+  Float_t maxdist       = 1.;
+
+  MBinning BinningE("BinningE");
+  MBinning BinningTheta("BinningTheta");
+  BinningE.SetEdgesLog(50, 500, 50000.);
+
+  const Double_t yedge[7] = {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50.};
+  const TArrayD yed(7,yedge);
+  BinningTheta.SetEdges(yed);
+
+  CT1EEst(inPath,  fileNameIn, 
+	  outPath, energyParName, 
+	  hilName, hilSrcName,    hadronnessName, 
+	  howMany, maxhadronness, maxalpha, maxdist, 
+	  &BinningE, &BinningTheta);
+}
+
+//------------------------------------------------------------------------
+//
+// Arguments of CT1EEst :
+// ------------------------
+//
+// inPath,  fileNameIn       path and name of input file (MC gamma events)
+// outPath, energyParName    path and name of file containing the parameters
+//                           of the energy estimator
+// hilName, hilSrcName       names of "MHillas" and "MHillasSrc" containers
+// hadronnessName            name of container holding the hadronness
+// howMany                   no.of events to be read from input file
+// maxhadronness             maximum value of hadronness to be accepted
+// maxalpha                  maximum value of |ALPHA| to be accepted
+// maxdist                   maximum value of DIST (degrees) to be accepted
+//
+
+void CT1EEst(TString inPath,  TString fileNameIn, 
+	     TString outPath, TString energyParName,
+	     TString hilName, TString hilSrcName, TString hadronnessName,
+	     Int_t howMany, 
+	     Float_t maxhadronness, Float_t maxalpha, Float_t maxdist,
+	     MBinning* binsE, MBinning* binsTheta)
+{
+  cout << "================================================================"
+       << endl;
+  cout << "Start of energy estimation part" << endl;
+  cout << "" << endl;
+  cout << "CT1EEst input values : " << endl;
+  cout << "---------------------- " << endl;
+  cout << "inPath, fileNameIn = " 
+       <<  inPath << ",  " << fileNameIn << endl;
+  cout << "outPath, energyParName = " 
+       <<  outPath << ",  " << energyParName << endl;
+  cout << "hilName, hilSrcName, hadronnessName = " << hilName << ",  "
+       << hilSrcName << ",  " << hadronnessName << endl;
+  cout << "howMany, maxhadronness, maxalpha, maxdist = " << howMany << ",  "
+       << maxhadronness << ",  " << maxalpha << ",  " << maxdist << endl;
+  cout << "" << endl;
+
+
+  //==========================================================================
+  // Start of Part 1 (determination of the parameters of the energy estimator)
+  //
+
+  //-----------------------------------------------------------------------
+  // Fill events into a MHMatrix, 
+  // to be used later in the minimization by MINUIT
+  //
+
+  MMcEnergyEst Optimize;
+
+  TString inputfile(outPath);
+  inputfile += fileNameIn;
+  Optimize.SetInFile(inputfile);
+
+  TString paramout(outPath);
+  paramout += energyParName;
+  Optimize.SetOutFile(paramout);
+
+  
+  MFCT1SelFinal filterhadrons;
+  filterhadrons.SetHadronnessName(hadronnessName);
+  filterhadrons.SetCuts(maxhadronness, maxalpha, maxdist);
+  filterhadrons.SetInverted();
+  Optimize.SetEventFilter(&filterhadrons);
+  
+
+  Optimize.SetNevents(howMany);
+
+  //
+  // Find the optimal parameters for the energy estimator:
+  //
+  Optimize.FindParams();
+
+  cout << "--------------------------------------" << endl;
+  cout << "Write parameters of energy estimator onto file '" 
+       << paramout << endl;
+  cout << "--------------------------------------" << endl;
+
+  Optimize.Print();
+
+  TFile out(paramout, "recreate");
+  Optimize.SetReadyToSave();
+  Optimize.Write();
+  out.Close();
+
+  //
+  // END of Part 1
+  //==========================================================================
+
+
+
+  //==========================================================================
+  // Start of Part 2 (test quality of energy estimation)
+  //
+  //
+
+  //--------------------------------------------
+  // Read the parameters of the energy estimator 
+  //
+
+  TString paramin(outPath);
+  paramin += energyParName;
+
+  TFile enparam(paramin);
+  MMcEnergyEst mcest;
+  mcest.Read("MMcEnergyEst");
+  enparam.Close();
+
+  cout << "--------------------------------------" << endl;
+  cout << "Read parameters of energy estimator from file '" 
+       << paramin << endl;
+
+  TArrayD parA(5);
+  TArrayD parB(7);
+
+  for (Int_t i=0; i<parA.GetSize(); i++)
+    parA[i] = mcest.GetCoeff(i);
+  for (Int_t i=0; i<parB.GetSize(); i++)
+    parB[i] = mcest.GetCoeff(i+parA.GetSize());
+
+  //-----------------------------------------------
+  // Create energy estimator task, add necessary containers and 
+  // initialize parameters read from file:
+  //
+
+  MEnergyEstParam eest2(hilName);
+  eest2.Add(hilSrcName);
+
+  eest2.SetCoeffA(parA);
+  eest2.SetCoeffB(parB);
+
+  // estimate energy using Daniel's parameters
+  //MEnergyEstParamDanielMkn421 eest2(hilName);
+  //eest2.Add(hilSrcName);
+
+
+  //=======================================================================
+  // Setup the event loop
+  //
+  cout << "--------------------------------------" << endl;
+  cout << "Setup event loop for checking quality of energy estimation" << endl;
+
+
+  MTaskList tlist2;
+  MParList  parlist2;  
+
+  //-----------------------------------------------
+  // Read events
+  //
+
+  TString inputfile(inPath);
+  inputfile += fileNameIn;
+
+  cout << "Read events from file '" << inputfile << "'" << endl;    
+  MReadTree read2("Events");
+  read2.AddFile(inputfile);
+  read2.DisableAutoScheme();
+
+
+  //-----------------------------------------------
+  // Select events
+  //
+  
+  cout << "Select events with hadronness < " << maxhadronness 
+	<< " and |alpha| < " << maxalpha << endl; 
+  MFCT1SelFinal hcut2;
+  hcut2.SetHadronnessName(hadronnessName); hcut2;
+  hcut2.SetCuts(maxhadronness, maxalpha, maxdist);
+
+  MContinue cont(&hcut2);
+  
+  //-----------------------------------------------
+  // Create Object MHMcEnergyMigration containing useful histograms,
+  // and task MHMcEnergyMigration to fill them:
+  //
+
+  //MHMcEnergyMigration mighist;
+
+  MFillH migfill("MHMcEnergyMigration", "MMcEvt");
+
+  MBinning BinningDE("BinningDE");
+  MBinning BinningImpact("BinningImpact");
+ 
+  BinningDE.SetEdges(60, -1.2, 1.2);
+  BinningImpact.SetEdges(50, 0., 400.);
+
+  //********************************
+  // Entries in MParList
+
+  parlist2.AddToList(&tlist2);
+  //parlist2.AddToList(&mighist);
+  parlist2.AddToList(binsE);
+  parlist2.AddToList(binsTheta);
+  parlist2.AddToList(&BinningDE);
+  parlist2.AddToList(&BinningImpact);
+
+  //********************************
+  // Entries in MTaskList
+
+  tlist2.AddToList(&read2);
+  tlist2.AddToList(&cont);
+  tlist2.AddToList(&eest2);
+  tlist2.AddToList(&migfill);
+
+  //-----------------------------------------------
+  cout << "Event loop was setup" << endl; 
+  MProgressBar bar;
+
+  MEvtLoop evtloop2;
+  evtloop2.SetProgressBar(&bar);
+  evtloop2.SetParList(&parlist2);
+
+  if (!evtloop2.Eventloop())
+    return;
+
+  tlist2.PrintStatistics(0, kTRUE);
+
+  MHMcEnergyMigration &mighist = 
+    *(MHMcEnergyMigration*)parlist2->FindObject("MHMcEnergyMigration");
+  if (!&mighist)
+  {
+    cout << "CT1EgyEst.C : object 'MHMcEnergyMigration' not found ... aborting"
+         << endl;
+    return;
+  }
+
+  TString paramout(outPath);
+  paramout += energyParName;
+
+  TFile out2(paramout, "UPDATE");
+  mighist.Write();
+  out2.Close();
+
+  TCanvas *c = new TCanvas;
+  c->cd();
+  mighist.Draw();
+
+  cout << "Quality histograms and migration matrix were added onto the file '" << paramout << endl;
+  cout << endl;
+  cout << "End of energy estimation part" << endl;
+  cout << "================================================================" << endl;
+  //
+  // End of Part 2 (test quality of energy estimation)
+  //==========================================================================
+  //
+
+  return;
+
+}
Index: /tags/Mars-V0.9/macros/CT1Hillas.C
===================================================================
--- /tags/Mars-V0.9/macros/CT1Hillas.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/CT1Hillas.C	(revision 9772)
@@ -0,0 +1,169 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz et al,  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+
+void CT1Hillas(const char *filename)
+{
+    //
+    // This is a demonstration program which calculates the Hillas
+    // parameter out of a Magic root file (raw data file).
+    //
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList plist;
+
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // The geometry container must be created by yourself to make sure
+    // that you don't choos a wrong geometry by chance
+    //
+    MGeomCamCT1 geomcam;
+    plist.AddToList(&geomcam);
+
+    //
+    // Use this if you want to change the binning of one of
+    // the histograms. You can use:
+    // BinningConc, BinningConc1, BinningAsym, BinningM3Long,
+    // BinningM3Trans, BinningWidth, BinningLength, BinningDist,
+    // BinningHeadTail, BinningAlpha, BinningSize, BinningDelta,
+    // BinningPixels and BinningCamera
+    //
+    // For more information see MBinning and the corresponding
+    // histograms
+    //
+    // MBinning binsalpha("BinningAlpha");
+    // binsalpha.SetEdges(90, 0, 90);       // 90 bins from 0 to 90 deg
+    // plist.AddToList(&binsalpha);
+
+    // MBinning binssize("BinningSize");
+    // binssize.SetEdgesLog(50, 1, 1e7);
+    // plist.AddToList(&binssize);
+
+    //
+    // Craete the object which hlods the source positions in the camera
+    // plain in respect to which the image parameters will be calculated.
+    // For real data the containers will be filled by a task.
+    //
+    MSrcPosCam source("Source")
+    source.SetXY(0, 0);
+    plist.AddToList(&source);
+
+    //
+    // Now setup the tasks and tasklist:
+    //
+    //  1) read in the data from a ct1 ascii file   MCTReadAscii
+    //  2) clean the image                          MImgCleanStd
+    //  3) calculate hillas                         MHillasCalc
+    //  4) fill the hillas into the histograms      MFillHHillas
+    //
+    MCT1ReadAscii read("../data/CT1_97_on1.dat");
+    //read.AddFile("../data/CT1_97_off1.dat");
+
+    MMcPedestalCopy pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    MCerPhotCalc ncalc;
+
+    MCameraSmooth   smooth;
+    MImgCleanStd    clean;
+    MBlindPixelCalc blind;
+    //
+    // Instead of unmapping the pixels you can also
+    //
+    // blind.SetUseInterpolation();
+    // blind.SetUseCetralPixel();
+    //
+    MHillasCalc    hcalc;
+    MHillasSrcCalc csrc1("Source",  "HillasSource");
+
+    //
+    // Uncomment this two line if you want to use MHillasExt instead
+    // of MHillas
+    //
+    //MHillasExt hext;
+    //plist.AddToList(&hext);
+
+    MFillH hfill1("MHHillas", "MHillas");
+    MFillH hfill2("MHHillasExt");
+    MFillH hfill3("MHStarMap", "MHillas");
+    MFillH hfill4("HistExtSource [MHHillasExt]", "HillasSource");
+    MFillH hfill5("HistSource [MHHillasSrc]", "HillasSource");
+
+    MWriteRootFile write("hillas.root");
+    write.AddContainer("MHStarMap");
+    write.AddContainer("MHHillas");
+    write.AddContainer("MHHillasExt");
+    write.AddContainer("HistSource");
+    write.AddContainer("HistExtSource");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&blind);
+
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&csrc1);
+    tlist.AddToList(&csrc2);
+
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+    tlist.AddToList(&write);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // After the analysis is finished we can display the histograms
+    //
+    plist.FindObject("MHHillas")->DrawClone();
+    plist.FindObject("MHHillasExt")->DrawClone();
+    plist.FindObject("MHStarMap")->DrawClone();
+    plist.FindObject("HistSource")->DrawClone();
+    plist.FindObject("HistExtSource")->DrawClone();
+}
+
Index: /tags/Mars-V0.9/macros/CT1collarea.C
===================================================================
--- /tags/Mars-V0.9/macros/CT1collarea.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/CT1collarea.C	(revision 9772)
@@ -0,0 +1,123 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 (tbretz@uni-sw.gwdg.de)
+!   Author(s): Abelardo Moralejo 4/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+void CT1collarea(TString filename="MC_SC4.root", TString outname="")
+{ 
+
+    //
+    // first we have to create our empty lists
+    //
+    MParList  parlist;
+    MTaskList tasklist;
+
+    parlist.AddToList(&tasklist);
+
+    //
+    // Setup out tasks:
+    //  - First we have to read the events
+    //  - Then we can fill the efficiency histograms
+    //
+    MReadMarsFile reader("Events", filename);
+    reader.DisableAutoScheme();
+
+    MHMcCT1CollectionArea collarea;
+
+    MBinning binsx("BinningE");
+
+    /*
+    Double_t xedge[15] = {2.47712, 2.64345, 2.82607, 3., 3.17609, 3.35218, 3.52892, 3.70415, 3.88024, 4.05652, 4.23274, 4.40875, 4.58478, 4.76080, 4.90309};
+    const TArrayD xed;
+    xed.Set(15,xedge);
+    binsx.SetEdges(xed);
+    collarea.SetEaxis(MHMcCollectionArea::kLog10);
+    */
+
+    //
+    // SetEaxis tells MHMcCT1CollectionArea whether the variable to histogram
+    // is the Energy (argument is kEnergy) or its decimal logarithm 
+    // (kLog10Energy). Of course this depends on how the energy binning is 
+    // defined via the object binsx. 
+    //
+    binsx.SetEdgesLog(14,300,1.e5);
+    collarea.SetEaxis(MHMcCT1CollectionArea::kLinear);
+
+
+    MBinning binsy("BinningTheta");
+    const Double_t yedge[9] = {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+    const TArrayD yed;
+    yed.Set(9,yedge);
+    binsy.SetEdges(yed);
+
+    parlist.AddToList(&collarea);
+    parlist.AddToList(&binsx);
+    parlist.AddToList(&binsy);
+
+    tasklist.AddToList(&reader);   
+
+    MF filterhadrons("HadSC.fHadronness<0.3 && {abs(MHillasSrc.fAlpha)} < 13.1");
+    tasklist.AddToList(&filterhadrons);
+
+
+    MFillH filler("MHMcCT1CollectionArea","MMcEvt");
+    filler.SetFilter(&filterhadrons);
+    tasklist.AddToList(&filler);
+
+    //
+    // set up the loop for the processing
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    //
+    // Start to loop over all events
+    //
+    MProgressBar bar;
+    magic.SetProgressBar(&bar);
+    if (!magic.Eventloop())
+        return;
+
+    tasklist.PrintStatistics();
+
+    collarea.CalcEfficiency();
+
+    //
+    // Now the histogram we wanted to get out of the data is
+    // filled and can be displayed
+    //
+    collarea.DrawClone();
+
+    //
+    // Write histogram to a file in case an output
+    // filename has been supplied
+    //
+    if (outname.IsNull())
+        return;
+
+    TFile f(outname,"recreate");
+    collarea.GetHist()->Write();
+    collarea.GetHAll()->Write();
+    collarea.GetHSel()->Write();
+}
+
Index: /tags/Mars-V0.9/macros/CT1env.rc
===================================================================
--- /tags/Mars-V0.9/macros/CT1env.rc	(revision 9772)
+++ /tags/Mars-V0.9/macros/CT1env.rc	(revision 9772)
@@ -0,0 +1,38 @@
+# Environment file for CT1 analysis
+#----------------------------------
+
+#-----------------------------------------------------------
+# Setup Matrix columns for all jobs and all MHMatrix objects
+#
+
+MHMatrix.Column0: cos(MMcEvt.fTelescopeTheta)
+MHMatrix.Column1: MSigmabar.fSigmabar
+MHMatrix.Column2: log10(MHillas.fSize)
+MHMatrix.Column3: MHillasSrc.fDist
+MHMatrix.Column4: MHillas.fWidth
+MHMatrix.Column5: MHillas.fLength
+MHMatrix.Column6: log10(MHillas.fSize/(MHillas.fWidth*MHillas.fLength))
+MHMatrix.Column7: sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)
+MHMatrix.Column8: MNewImagePar.fConc
+MHMatrix.Column9: MNewImagePar.fLeakage1
+
+
+#-----------------------------------------------------------
+# Setup Files for Job1
+# 
+##Job1.MRead.File0: rootfile1.root
+##Job1.MRead.File1: rootfiles*.root
+##Job1.MRead.File2: rootfile3.root
+
+#-----------------------------------------------------------
+# Setup Files for Job2
+# 
+##Job2.MRead.File0: otherrootfile.root
+
+#
+# Setup columns for a matrix called MatrixGammas in Job2
+#
+##Job2.MatrixGammas.Column0: MHillasSrc.fDist
+##Job2.MatrixGammas.Column1: sin(MMcEvt.fTelescopePhi)
+
+#-----------------------------------------------------------
Index: /tags/Mars-V0.9/macros/DAQDataCheck.C
===================================================================
--- /tags/Mars-V0.9/macros/DAQDataCheck.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/DAQDataCheck.C	(revision 9772)
@@ -0,0 +1,313 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Raquel de los Reyes, 05/2004 <mailto:reyes@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+// This macro makes the check of the DAQ files (.raw files).
+//
+// The only argument to the macro is the directory with the night raw files
+// (ended with "/"). The macro sorts the entries in alphabetical order;
+// it then joins all the consecutive pedestal, calibration and data runs 
+// and analyses all of them together. Data runs are taken consecutively
+// until it finds a run of other type (pedestal or calibration) or a data run 
+// from another source. When a given source has no previous pedestal and/or
+// calibration runs, the macro takes the most recent ones. 
+//
+// The analysis is done through the jobs classes MJPedestal and MJCalibration.
+//
+///////////////////////////////////////////////////////////////////////////
+void DataAnalysis(const Int_t prun1,const Int_t prun2,
+		  const Int_t crun1,const Int_t crun2,
+		  const Int_t drun1,const Int_t drun2,
+		  const TString inpath,
+		  const TString outdir)
+{
+
+  // Check if no pedestal runs has been detected
+  if(prun1==0)
+  {
+      cout << "No pedestal run(s)!!!"<< endl;
+      break;
+  }
+
+  gStyle->SetOptStat(1);
+  gStyle->SetOptFit();
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+  //
+  // Set the filter of MRunIter to .raw files
+  pruns.SetRawFile(kTRUE);
+  cruns.SetRawFile(kTRUE);
+  druns.SetRawFile(kTRUE);
+
+  //
+  // Check if you are analyzing more than one file
+  if(prun1==prun2)
+    pruns.AddRun(prun1,inpath);
+  else
+    pruns.AddRuns(prun1,prun2,inpath);
+  if(crun1==crun2)
+    cruns.AddRun(crun1,inpath);
+  else
+    cruns.AddRuns(crun1,crun2,inpath);
+  if(drun1==drun2)
+    druns.AddRun(drun1,inpath);
+  else
+    druns.AddRuns(drun1,drun2,inpath);
+
+  // 
+  // Set up the source run-range
+  //
+  TRegexp type("_[A-Z]_");
+  TString source = "";
+  if(pruns.GetNumRuns()!=0)
+    source = pruns.Next();
+  source = source(source.Index(type)+3,source.Length());
+  source.Remove(source.Last('_'),source.Length());
+
+  TString title = outdir+source+"_"+prun2+"-"+crun2+"-"+drun2+".ps";
+
+  MStatusDisplay *d = new MStatusDisplay;
+  d->SetTitle(title);
+  d->SetLogStream(&gLog, kTRUE);
+
+  TObject::SetObjectStat(kTRUE);
+ 
+  //
+  // Choose the signal Extractor:
+  //
+  //  MExtractFixedWindowPeakSearch extractor;
+  //  MExtractSlidingWindow  extractor;
+   MExtractFixedWindow    extractor;
+ 
+  //
+  // Set Ranges or Windows
+  //
+   extractor.SetRange(3,14,3,14);
+  //  extractor.SetWindows(8,8);
+ 
+  //
+  // Choose the arrival time Extractor:
+  //
+  //  MExtractTimeHighestIntegral timeext;
+  MExtractTimeFastSpline timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(2,12,4,14);
+
+  // ************************ GENERAL CONTAINERS  *************************
+  MBadPixelsCam     badcam;
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  MCalibrationQECam qecam;  
+
+  // **********************************************************************
+  // ***************************** PEDESTALS ******************************
+  // **********************************************************************
+  if(pruns.GetNumRuns()==0)
+    {
+      cout << "Warning, no entries found in pedestal run(s)!!!"<< endl;
+      break;
+    }
+
+  MJPedestal pedloop;
+  pedloop.SetExtractor(&extractor);           
+  pedloop.SetInput(&pruns);
+  pedloop.SetDisplay(d);
+  pedloop.SetBadPixels(badcam);
+  //
+  // If you want to run the data-check on RAW DATA!!!, choose:
+  pedloop.SetDataCheck(kTRUE);
+
+  //
+  // Execute first analysis
+  //
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+  if (!pedloop.Process())
+    return;
+
+  //
+  // Save display into a postcript file
+  //
+  d->SaveAsPS(outdir+source+"_"+prun2+"-"+crun2+"-"+drun2+".ps");
+
+  // **********************************************************************
+  // ***************************** CALIBRATION ****************************
+  // **********************************************************************
+  if(cruns.GetNumRuns()==0)
+    {
+      cout << "Warning, no entries found in calibration run(s)!!!"<< endl;
+      break;
+    }
+
+  //
+  // Tell if you want to calibrate times:
+  //
+  static const  Bool_t useTimes = kTRUE;
+
+  MJCalibration calloop;
+  //
+  // If you want to run the data-check on RAW DATA!!!, choose:
+  calloop.SetDataCheck();
+  //
+  // If you want to see the data-check plots only, choose:
+  calloop.SetDataCheckDisplay();
+
+  calloop.SetRelTimeCalibration(useTimes);
+  calloop.SetExtractor(&extractor);
+  calloop.SetTimeExtractor(&timeext);
+  calloop.SetInput(&cruns);
+  calloop.SetDisplay(d);
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop.GetBadPixels());            
+
+  //
+  // Execute first analysis
+  //
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  if (!calloop.Process(pedloop.GetPedestalCam()))
+    return;
+
+  //
+  // Save display into a postcript file
+  //
+  d->SaveAsPS(outdir+source+"_"+prun2+"-"+crun2+"-"+drun2+".ps");
+
+
+}
+
+void DAQDataCheck(const TString directory="/remote/bigdown/data/Magic-DATA/Period014/rawdata/2004_02_17/",const TString outdir="./")
+{
+
+  MDirIter iter;
+  iter.AddDirectory(directory,"*.raw");
+
+  TString str=iter.Next();
+
+  TList list;
+  while(!str.IsNull())
+    {
+      list.Add(new TNamed(str,""));
+      str=iter.Next();
+    }
+  list.Sort();
+
+  TIter Next(&list);
+
+  TString fName="file.raw";
+
+  TRegexp run("_[0-9][0-9][0-9][0-9][0-9]_");
+  TRegexp type("_[A-Z]_");
+
+  Int_t pedrun1=0, pedrun2=0;
+  Int_t calrun1=0, calrun2=0;
+  Int_t datarun1=0, datarun2=0;
+
+  TString source="";
+
+  TObject o*;
+  o=Next();
+  fName = o->GetName();  // absolut path
+
+  while(!fName.IsNull())
+    {
+
+      source = fName(fName.Index(type)+3,fName.Length());
+      source.Remove(source.Last('_'),source.Length());
+
+      // Pedestal runs
+      if(fName.Contains("_P_"))
+	pedrun1=atoi(fName(fName.Index(run)+1,5).Data());
+      pedrun2=pedrun1;
+
+      while(fName.Contains("_P_")&&fName.Contains(source))
+	{
+	  pedrun2=atoi(fName(fName.Index(run)+1,5).Data());
+	  o=Next();
+	  if(!o)
+	    {
+	      fName="";
+	      break;
+	    }
+	  fName = o->GetName(); 
+	}
+
+      // Calibration runs
+      if(fName.Contains("_C_"))//||(!fName.Contains(source)))
+	calrun1=atoi(fName(fName.Index(run)+1,5).Data());
+//      else
+//	  calrun1=0; 
+      calrun2=calrun1;
+
+      while(fName.Contains("_C_")&&fName.Contains(source))
+	{
+	  calrun2=atoi(fName(fName.Index(run)+1,5).Data());
+	  o=Next();
+	  if(!o)
+	    {
+	      fName = "";
+	      break;
+	    }
+	  fName = o->GetName(); 
+	}
+
+      // Data runs
+      if(fName.Contains("_D_"))//||(!fName.Contains(source)))
+	datarun1=atoi(fName(fName.Index(run)+1,5).Data());
+      else
+	  datarun1=0; 
+      datarun2=datarun1;
+
+      while(fName.Contains("_D_")&&fName.Contains(source))
+	{
+	  datarun2=atoi(fName(fName.Index(run)+1,5).Data());
+	  o=Next();
+	  if(!o)
+	    {
+	      fName = "";
+	      break;
+	    }
+	  fName = o->GetName(); 
+	}
+
+//        cout << pedrun1 << "\t"<<pedrun2 << endl;
+//        cout << calrun1 << "\t"<<calrun2 << endl;
+//        cout << datarun1 << "\t"<<datarun2 << endl;
+
+      DataAnalysis(pedrun1,pedrun2,calrun1,calrun2,datarun1,datarun2,directory,outdir);
+
+      cout << "----------------------------------------------" << endl;
+
+    }
+
+}
+
+
+
Index: /tags/Mars-V0.9/macros/MagicHillas.C
===================================================================
--- /tags/Mars-V0.9/macros/MagicHillas.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/MagicHillas.C	(revision 9772)
@@ -0,0 +1,190 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// MagicHillas.C
+// =============
+//
+// This is a demonstration program which calculates image (Hillas +)
+// parameters using as input a Merpp output file (raw data).
+// All parameters are written to an output file called hillas.root. Also
+// filles histograms are displayed.
+// For the calculation an arbitrary signal extractor (MCerPhotAnal2/Calc)
+// is used.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void MagicHillas(const char *filename="~/data/Gamma_20_N*.root")
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Use this if you want to change the binning of one of
+    // the histograms. You can use:
+    // BinningConc, BinningConc1, BinningAsym, BinningM3Long,
+    // BinningM3Trans, BinningWidth, BinningLength, BinningDist,
+    // BinningHeadTail, BinningAlpha, BinningSize, BinningDelta,
+    // BinningPixels and BinningCamera
+    //
+    // For more information see MBinning and the corresponding
+    // histograms
+    //
+    // MBinning binsalpha("BinningAlpha");
+    // binsalpha.SetEdges(90, 0, 90);       // 90 bins from 0 to 90 deg
+    // plist.AddToList(&binsalpha);
+
+    // MBinning binssize("BinningSize");
+    // binssize.SetEdgesLog(50, 1, 1e7);
+    // plist.AddToList(&binssize);
+
+    //
+    // Craete the object which hlods the source positions in the camera
+    // plain in respect to which the image parameters will be calculated.
+    // For real data the containers will be filled by a task.
+    //
+    MSrcPosCam source;
+    source.SetReadyToSave();
+    plist.AddToList(&source);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    // The first argument is the tree you want to read.
+    //   Events:     Cosmic ray events
+    //   PedEvents:  Pedestal Events
+    //   CalEvents:  Calibration Events
+    //
+    MReadMarsFile read("Events", filename);
+    read.DisableAutoScheme();
+
+    // Setup a task which makes sure that all used arrays have
+    // the correct size
+    MGeomApply geomapl;
+
+    // tasks used if MC files are detected to calculate pedestals
+    MMcPedestalCopy pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    // calculate the signal in a very simple way
+    // for real adat files use MCerPhotAnal2 instead which also
+    // calculates the pedestal.
+    MCerPhotCalc ncalc;
+    //
+    //  Alternative photon calculation:
+    //  Example: use only 2nd to 6th FADC slices for photon calculation:
+    //
+    //    const Float_t x[15]={0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+    //    const TArrayF w(15,(Float_t*)x);
+    //    ncalc.SetWeights(w);
+    //
+
+    // setup image cleaning and blind pixel treatment
+    MImgCleanStd    clean;
+    MBlindPixelCalc blind;
+
+    //
+    // Instead of unmapping the pixels you can also (The use of this
+    // class is deprecated, it will be replaced by MBadPixels*)
+    //
+    // blind.SetUseInterpolation();
+    // blind.SetUseCetralPixel();
+    //
+
+    // setup tasks to calculate image parameters
+    MHillasCalc    hcalc;
+    MHillasSrcCalc csrc1;
+
+    // setup tasks to fill histograms
+    MFillH hfill1("MHHillas", "MHillas");
+    MFillH hfill2("MHHillasExt");
+    MFillH hfill3("MHStarMap", "MHillas");
+    MFillH hfill4("HistExtSource [MHHillasExt]", "MHillasSrc");
+    MFillH hfill5("HistSource [MHHillasSrc]", "MHillasSrc");
+    MFillH hfill6("MHNewImagePar");
+
+    // setup task to write containers to a file
+    MWriteRootFile write("hillas.root");
+    write.AddContainer("MHStarMap");
+    write.AddContainer("MHHillas");
+    write.AddContainer("MHHillasExt");
+    write.AddContainer("HistSource");
+    write.AddContainer("HistExtSource");
+    write.AddContainer("MHNewImagePar");
+
+    // Setup the contents of zour tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&blind);
+
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&csrc1);
+
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+    tlist.AddToList(&hfill6);
+    tlist.AddToList(&write);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // After the analysis is finished we can display the histograms
+    //
+    plist.FindObject("MHHillas")->DrawClone();
+    plist.FindObject("MHHillasExt")->DrawClone();
+    plist.FindObject("MHStarMap")->DrawClone();
+    plist.FindObject("HistSource")->DrawClone();
+    plist.FindObject("HistExtSource")->DrawClone();
+    plist.FindObject("MHNewImagePar")->DrawClone();
+}
+
Index: /tags/Mars-V0.9/macros/ONAnalysis.C
===================================================================
--- /tags/Mars-V0.9/macros/ONAnalysis.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/ONAnalysis.C	(revision 9772)
@@ -0,0 +1,3447 @@
+
+//#include "MagicEgyEst.C"
+
+void InitBinnings(MParList *plist)
+{
+        gLog << "InitBinnings" << endl;
+
+        //--------------------------------------------
+        MBinning *binse = new MBinning("BinningE");
+        //binse->SetEdgesLog(30, 1.0e2, 1.0e5);
+
+	//This is Daniel's binning in energy:
+        binse->SetEdgesLog(14, 296.296, 86497.6);
+        plist->AddToList(binse);
+
+        //--------------------------------------------
+
+        MBinning *binssize = new MBinning("BinningSize");
+        binssize->SetEdgesLog(50, 10, 1.0e5);
+        plist->AddToList(binssize);
+
+        MBinning *binsdistc = new MBinning("BinningDist");
+        binsdistc->SetEdges(50, 0, 1.4);
+        plist->AddToList(binsdistc);
+
+        MBinning *binswidth = new MBinning("BinningWidth");
+        binswidth->SetEdges(50, 0, 1.0);
+        plist->AddToList(binswidth);
+
+        MBinning *binslength = new MBinning("BinningLength");
+        binslength->SetEdges(50, 0, 1.0);
+        plist->AddToList(binslength);
+
+        MBinning *binsalpha = new MBinning("BinningAlpha");
+        binsalpha->SetEdges(100, -100, 100);
+        plist->AddToList(binsalpha);
+
+        MBinning *binsasym = new MBinning("BinningAsym");
+        binsasym->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsasym);
+
+        MBinning *binsm3l = new MBinning("BinningM3Long");
+        binsm3l->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3l);
+
+        MBinning *binsm3t = new MBinning("BinningM3Trans");
+        binsm3t->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3t);
+
+   
+        //.....
+        MBinning *binsb = new MBinning("BinningSigmabar");
+        binsb->SetEdges( 100,  0.0,  5.0);
+        plist->AddToList(binsb);
+
+        MBinning *binth = new MBinning("BinningTheta");
+        // this is Daniel's binning in theta
+        //Double_t yedge[8] = 
+        //  {9.41, 16.22, 22.68, 28.64, 34.03, 38.84, 43.08, 44.99};
+        // this is our binning
+        Double_t yedge[9] = 
+                       {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        TArrayD yed;
+        yed.Set(9,yedge);
+        binth->SetEdges(yed);
+        plist->AddToList(binth);
+
+        MBinning *bincosth = new MBinning("BinningCosTheta");
+        Double_t zedge[9]; 
+        for (Int_t i=0; i<9; i++)
+	{
+          zedge[8-i] = cos(yedge[i]/kRad2Deg);
+	}
+        TArrayD zed;
+        zed.Set(9,zedge);
+        bincosth->SetEdges(zed);
+        plist->AddToList(bincosth);
+
+        MBinning *binsdiff = new MBinning("BinningDiffsigma2");
+        binsdiff->SetEdges(100, -5.0, 20.0);
+        plist->AddToList(binsdiff);
+
+        // robert ----------------------------------------------
+        MBinning *binsalphaf = new MBinning("BinningAlphaFlux");
+        binsalphaf->SetEdges(100, -100, 100);
+        plist->AddToList(binsalphaf);
+
+	MBinning *binsdifftime = new MBinning("BinningTimeDiff");
+	binsdifftime->SetEdges(50, 0, 10);
+	plist->AddToList(binsdifftime);
+
+	MBinning *binstime = new MBinning("BinningTime");
+	binstime->SetEdges(50, 44500, 61000);
+	plist->AddToList(binstime);
+}
+
+
+void DeleteBinnings(MParList *plist)
+{
+        gLog << "DeleteBinnings" << endl;
+
+        TObject *bin;
+
+        //--------------------------------------------
+        bin = plist->FindObject("BinningE");
+        if (bin) delete bin;
+
+        //--------------------------------------------
+
+        bin = plist->FindObject("BinningSize");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDist");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningWidth");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningLength");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAlpha");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAsym");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Long");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Trans");
+        if (bin) delete bin;
+
+        //.....
+        bin = plist->FindObject("BinningSigmabar");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningCosTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDiffsigma2");
+        if (bin) delete bin;
+
+
+        // robert ----------------------------------------------
+        bin = plist->FindObject("BinningAlphaFlux");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTimeDiff");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTime");
+        if (bin) delete bin;
+}
+
+
+//************************************************************************
+void ONAnalysis()
+{
+
+  gLog << "Entry ONAnalysis()" << endl;
+
+      gLog.SetNoColors();
+
+      if (gRandom)
+        delete gRandom;
+      gRandom = new TRandom3(0);
+
+      //-----------------------------------------------
+      const char *offfile = 
+      "/.magic/data14a/crab_2003Nov/rootdata/2003_11_29/*OffCrab1*.root"; 
+
+      const char *onfile  = 
+      "/.magic/data14a/crab_2003Nov/rootdata/2003_11_29/*Crab-Nebula*.root"; 
+      const char *onfile1  = 
+      "/.magic/data14a/crab_2003Nov/rootdata/2003_11_30/*CrabNebula*.root"; 
+
+      const char *mcfile  = 
+            "/data/MAGIC/mc_eth/magLQE_3/gh/0/0/G_M0_00_0_550*.root";
+      //-----------------------------------------------
+
+      // path for input for Mars
+      TString inPath =  "/.magic/data14a/wittek/ONAnalysis/";
+
+      // path for output from Mars
+      TString outPath = "/.magic/data14a/wittek/ONAnalysis/";
+
+      //-----------------------------------------------
+
+      //TEnv env("macros/CT1env.rc");
+      //Bool_t printEnv = kFALSE;
+
+    //************************************************************************
+
+    // Job A_ON : read ON data
+    //  - generate sigmabar vs. Theta plot; 
+    //  - write root file for ON data (ON1.root);
+
+    Bool_t JobA_ON = kTRUE;  
+    Bool_t WHistON = kFALSE;   // write out histogram sigmabar vs. Theta ?
+    Bool_t WON1    = kFALSE;   // write out root file ON1.root ?
+
+
+    // Job A_MC : read MC gamma data, 
+    //  - read sigmabar vs. Theta plot from ON data  
+    //  - do padding; 
+    //  - write root file for MC gammas (MC1.root);
+
+    Bool_t JobA_MC  = kFALSE;  
+    Bool_t WMC1     = kFALSE;  // write out root file MC1.root ?
+
+
+    // Job B_RF_UP : read ON1.root (or MC1.root) file 
+    //  - if RTrainRF = TRUE : read in training matrices for hadrons and gammas
+    //  - if CTrainRF = TRUE : create  training matrices for hadrons and gammas
+    //  - if RTree    = TRUE : read in trees, otherwise create trees
+    //  - calculate hadroness for method of RANDOM FOREST
+    //  - update the input files with the hadroness (==>ON2.root or MC2.root)
+
+    Bool_t JobB_RF_UP  = kFALSE;  
+    Bool_t CTrainRF    = kFALSE;  // create matrices of training events
+    Bool_t RTrainRF    = kFALSE;  // read in matrices of training events
+    Bool_t RTree       = kFALSE;  // read in trees (otherwise grow them)
+    Bool_t WRF         = kFALSE;  // update input root file ?
+
+
+
+
+    // Job B_SC_UP : read ON2.root (or MC2.root) file 
+    //  - depending on WParSC : create (or read in) supercuts parameter values
+    //  - calculate hadroness for the SUPERCUTS
+    //  - update the input files with the hadroness (==>ON3.root or MC3.root)
+
+    Bool_t JobB_SC_UP  = kFALSE;
+    Bool_t CMatrix     = kFALSE;  // create training and test matrices 
+    Bool_t RMatrix     = kFALSE;  // read training and test matrices from file
+    Bool_t WOptimize   = kFALSE;  // do optimization using the training sample
+                                  // and write supercuts parameter values 
+                                  // onto the file parSCfile
+    Bool_t RTest       = kFALSE;  // test the supercuts using the test matrix
+    Bool_t WSC         = kFALSE;  // update input root file ?
+
+
+
+    // Job C: 
+    //  - read ON3.root and MC3.root files
+    //    which should have been updated to contain the hadronnesses  
+    //    for the method of 
+    //              RF
+    //              SUPERCUTS and
+    //  - produce Neyman-Pearson plots
+
+    Bool_t JobC  = kFALSE;  
+
+
+    // Job D :  
+    //  - select g/h separation method XX
+    //  - read ON3 (or MC3) root file
+    //  - apply cuts in hadronness
+    //  - make plots
+
+    Bool_t JobD  = kFALSE;  
+
+
+
+
+    // Job E_XX : extended version of E_XX (including flux plots)  
+    //  - select g/h separation method XX
+    //  - read MC root file 
+    //  - calculate eff. collection area
+    //  - optimize energy estimator
+    //  - read ON root file 
+    //  - apply final cuts
+    //  - calculate flux
+    //  - write root file for ON data after final cuts 
+
+
+    Bool_t JobE_XX  = kFALSE;  
+    Bool_t CCollArea= kFALSE;  // calculate eff. collection areas
+    Bool_t OEEst    = kFALSE;  // optimize energy estimator
+    Bool_t WEX      = kFALSE;  // update root file  ?
+    Bool_t WRobert  = kFALSE;  // write out Robert's file  ?
+
+
+
+    //************************************************************************
+
+    
+  //---------------------------------------------------------------------
+  // Job A_ON
+  //=========
+    // read ON data file 
+
+    //  - produce the 2D-histogram "sigmabar versus Theta" 
+    //    (SigmaTheta_ON.root) for ON data
+    //    (to be used for the padding of the MC gamma data)
+
+    //  - write a file of ON events (ON1.root) 
+    //    (after the standard cuts, before the g/h separation)
+    //    (to be used together with the corresponding MC gamma file (MC1.root)
+    //     for the optimization of the g/h separation)
+
+
+ if (JobA_ON)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONAnalysis : Start of Job A_ON" << endl;
+    gLog << "" << endl;
+    gLog << "Macro ONAnalysis : JobA_ON, WHistON, WON1 = " 
+         << (JobA_ON ? "kTRUE" : "kFALSE")  << ",  " 
+         << (WHistON ? "kTRUE" : "kFALSE")  << ",  " 
+         << (WON1    ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // name of input root file
+    TString filenamein(onfile);
+    TString filenamein1(onfile1);
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += "ON";
+    outNameImage += "1.root";
+
+    //--------------------------------------------------
+    // use for padding sigmabar vs. Theta from ON data
+    TString typeHist = "ON";
+    gLog << "typeHist = " << typeHist << endl;
+
+    // name of file to conatin the histograms for the padding
+    TString outNameSigTh = outPath;
+    outNameSigTh += "SigmaTheta_";
+    outNameSigTh += typeHist;
+    outNameSigTh += ".root";
+
+
+    //-----------------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    char *sourceName = "MSrcPosCam";
+    MSrcPosCam source(sourceName);
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    TFile test("/.magic/data14a/crab_2003Nov/rootdata/2003_11_29/20031128_03127_P_Crab-Nebula_E.root");
+    test.ls();
+
+    //MCT1ReadPreProc read(filenamein);
+    MReadMarsFile  read("Events", filenamein);
+    read.ls();
+    read.AddFile(filenamein1);    
+    read.DisableAutoScheme();
+
+    //---------------------
+    MF selectCrabNebula
+        ("(MRawRunHeader.fRunNumber>3126 && MRawRunHeader.fRunNumber<3216)||(MRawRunHeader.fRunNumber>3283 && MRawRunHeader.fRunNumber<3335)||(MRawRunHeader.fRunNumber>3339 && MRawRunHeader.fRunNumber<3417)");
+    selectCrabNebula.SetInverted();
+
+    MF selectOffCrab1
+        ("(MRawRunHeader.fRunNumber>3215 && MRawRunHeader.fRunNumber<3275)||(MRawRunHeader.fRunNumber>3416 && MRawRunHeader.fRunNumber<3444)");
+    selectOffCrab1.SetInverted();
+
+    MF selectMrk421
+        ("(MRawRunHeader.fRunNumber>3443 && MRawRunHeader.fRunNumber<3490)");
+    selectMrk421.SetInverted();
+                
+    MContinue contCrabNebula(&selectCrabNebula);
+    MContinue contOffCrab1(&selectOffCrab1);
+    MContinue contMrk421(&selectMrk421);
+
+
+    //..............................
+    MGeomApply        apply;
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    MPedestalWorkaround waround;
+
+    // a way to find out whether one is dealing with MC :
+    MFDataMember fMC("MRawRunHeader.fRunType", '>', 255.5);  // MC
+    fMC.SetName("Select MC");
+    MFDataMember fDa("MRawRunHeader.fRunType", '<', 255.5);  // data
+    fDa.SetName("Select Data");
+
+    MCerPhotCalc      ncalc;
+    ncalc.SetFilter(&fMC);
+    MCerPhotAnal2     nanal;
+    nanal.SetFilter(&fDa);
+    //..............................
+
+
+    //MPointingCorrCalc pointcorr(sourceName, "MPointingCorrCalc", 
+    //                                         "MPointingCorrCalc");
+    MBlindPixelCalc blind;
+    blind.SetUseBlindPixels();
+
+    MFSelBasic selbasic;
+    MContinue contbasic(&selbasic);
+    contbasic.SetName("SelBasic");
+
+    MFillH fillblind("BlindPixels[MHBlindPixels]", "MBlindPixels");
+    fillblind.SetName("HBlind");
+
+    MSigmabarCalc sigbarcalc;
+
+    MFillH fillsigtheta ("SigmaTheta[MHSigmaTheta]", "MMcEvt");
+    fillsigtheta.SetName("HSigmaTheta");
+
+    MImgCleanStd    clean; 
+
+
+    // calculation of  image parameters ---------------------
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImgPar(fImgParName);
+
+    MHillasSrcCalc hsrccalc(sourceName, fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+    // --------------------------------------------------
+
+    MFSelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+    selstandard.SetCuts(92, 4, 60, 0.4, 1.05, 0.0, 0.0);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+      //MWriteRootFile &write = *(new MWriteRootFile(outNameImage));
+      MWriteRootFile write(outNameImage, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+
+    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+    //MF daniel( "(MRawRunHeader.fRunNumber<13167)||(MRawRunHeader.fRunNumber>13167)" );
+    //MContinue contdaniel(&daniel);
+    //$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+
+    //*****************************
+    // entries in MParList
+    
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(&source);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+    tliston.AddToList(&contCrabNebula);
+
+    //......................
+    tliston.AddToList(&fMC);
+    tliston.AddToList(&fDa);
+    tliston.AddToList(&apply);
+    tliston.AddToList(&pcopy);
+    //tliston.AddToList(&waround);
+
+    tliston.AddToList(&pnsb);
+    tliston.AddToList(&ncalc);
+    tliston.AddToList(&nanal);
+    //......................
+
+    //tliston.AddToList(&pointcorr);
+    tliston.AddToList(&blind);
+    tliston.AddToList(&contbasic);
+
+    tliston.AddToList(&fillblind);
+    tliston.AddToList(&sigbarcalc);
+    tliston.AddToList(&fillsigtheta);
+    tliston.AddToList(&clean);
+
+    tliston.AddToList(&hcalc);
+    tliston.AddToList(&hsrccalc);
+
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contstandard);
+    if (WON1)
+      tliston.AddToList(&write);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //if (WON1)
+    //  evtloop.Write();
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+
+    pliston.FindObject("SigmaTheta", "MHSigmaTheta")->DrawClone();
+
+    pliston.FindObject("BlindPixels", "MHBlindPixels")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+
+    //-------------------------------------------
+    // Write histograms onto a file
+  if (WHistON)
+  {
+      MHSigmaTheta *sigtheta = 
+            (MHSigmaTheta*)pliston.FindObject("SigmaTheta");
+
+      MHBlindPixels *blindpixels = 
+            (MHBlindPixels*)pliston.FindObject("BlindPixels");
+      if (!sigtheta  ||  !blindpixels)
+	{
+          gLog << "Object 'SigmaTheta' or 'BlindPixels' not found" << endl;
+          return;
+	}
+      TH2D *fHSigTh    = sigtheta->GetSigmaTheta();
+      TH3D *fHSigPixTh = sigtheta->GetSigmaPixTheta();
+      TH3D *fHDifPixTh = sigtheta->GetDiffPixTheta();
+
+      TH2D *fHBlindId  = blindpixels->GetBlindId();
+      TH2D *fHBlindN   = blindpixels->GetBlindN();
+
+
+      TFile outfile(outNameSigTh, "RECREATE");
+      fHSigTh->Write();
+      fHSigPixTh->Write();
+      fHDifPixTh->Write();
+     
+      fHBlindId->Write();
+      fHBlindN->Write();
+
+      gLog << "" << endl;
+      gLog << "File " << outNameSigTh << " was written out" << endl;
+  }
+
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro ONAnalysis : End of Job A_ON" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+
+  //---------------------------------------------------------------------
+   // Job A_MC
+   //=========
+
+    // read MC gamma data  
+
+    //    - to pad them
+    //      (using the 2D-histogram "sigmabar versus Theta" 
+    //       (SigmaTheta_ON.root)  of the ON data)
+
+    //    - to write a file of padded MC gamma events (MC1.root)
+    //      (after the standard cuts, before the g/h separation)
+    //      (to be used together with the corresponding hadron file
+    //       for the optimization of the g/h separation)
+
+
+ if (JobA_MC)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONAnalysis : Start of Job A_MC" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONAnalysis : JobA_MC, WMC1 = " 
+         << (JobA_MC ? "kTRUE" : "kFALSE")  << ",  " 
+         << (WMC1    ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // name of input root file
+    TString filenamein(mcfile);
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += "MC";
+    outNameImage += "1.root";
+
+    //------------------------------------------------
+    // use for padding sigmabar vs. Theta from ON data
+    TString typeHist = "ON";
+    gLog << "typeHist = " << typeHist << endl;
+
+    // name of file containing the histograms for the padding
+    TString outNameSigTh = outPath;
+    outNameSigTh += "SigmaTheta_";
+    outNameSigTh += typeHist;
+    outNameSigTh += ".root";
+
+
+    //------------------------------------
+    // Get the histograms "2D-ThetaSigmabar"
+    // and                "3D-ThetaPixSigma"
+    // and                "3D-ThetaPixDiff"
+    // and                "2D-IdBlindPixels"
+    // and                "2D-NBlindPixels"
+
+
+      gLog << "Reading in file " << outNameSigTh << endl;
+
+      TFile *infile = new TFile(outNameSigTh);
+      infile->ls();
+
+      TH2D *fHSigmaTheta = 
+      (TH2D*) gROOT->FindObject("2D-ThetaSigmabar");
+      if (!fHSigmaTheta)
+	{
+          gLog << "Object '2D-ThetaSigmabar' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '2D-ThetaSigmabar' was read in" << endl;
+
+      TH3D *fHSigmaPixTheta = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigma");
+      if (!fHSigmaPixTheta)
+	{
+          gLog << "Object '3D-ThetaPixSigma' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '3D-ThetaPixSigma' was read in" << endl;
+
+      TH3D *fHDiffPixTheta = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiff");
+      if (!fHDiffPixTheta)
+	{
+          gLog << "Object '3D-ThetaPixDiff' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '3D-ThetaPixDiff' was read in" << endl;
+
+
+      TH2D *fHIdBlindPixels = 
+      (TH2D*) gROOT->FindObject("2D-IdBlindPixels");
+      if (!fHIdBlindPixels)
+	{
+          gLog << "Object '2D-IdBlindPixels' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '2D-IdBlindPixels' was read in" << endl;
+
+      TH2D *fHNBlindPixels = 
+      (TH2D*) gROOT->FindObject("2D-NBlindPixels");
+      if (!fHNBlindPixels)
+	{
+          gLog << "Object '2D-NBlindPixels' not found on root file" << endl;
+          return;
+	}
+      gLog << "Object '2D-NBlindPixels' was read in" << endl;
+
+    //------------------------------------
+
+    MTaskList tlist;
+    MParList plist;
+
+    char *sourceName = "MSrcPosCam";
+    MSrcPosCam source(sourceName);
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)plist->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    //MCT1ReadPreProc read(filenamein);
+    MReadMarsFile  read("Events", filenamein);
+    read.DisableAutoScheme();
+
+    //..............................
+    MGeomApply        apply;
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    MPedestalWorkaround waround;
+
+    // a way to find out whether one is dealing with MC :
+    MFDataMember fMC("MRawRunHeader.fRunType", '>', 255.5);  // MC
+    fMC.SetName("Select MC");
+    MFDataMember fDa("MRawRunHeader.fRunType", '<', 255.5);  // data
+    fDa.SetName("Select Data");
+
+    MCerPhotCalc      ncalc;
+    ncalc.SetFilter(&fMC);
+    MCerPhotAnal2     nanal;
+    nanal.SetFilter(&fDa);
+    //..............................
+
+    MBlindPixelCalc blindbeforepad;
+    blindbeforepad.SetUseBlindPixels();
+    blindbeforepad.SetName("BlindBeforePadding");
+
+    MBlindPixelCalc blind;
+    blind.SetUseBlindPixels();
+    blind.SetName("BlindAfterPadding");
+
+    MFSelBasic selbasic;
+    MContinue contbasic(&selbasic);
+    contbasic.SetName("SelBasic");
+
+    MPad padthomas("MPad","Task for the padding");
+    padthomas.MergeONMC(fHSigmaThetaMC, fHDiffPixThetaMC, fHSigmaPixThetaMC,
+                        fHIdBlindPixelsMC, fHNBlindPixelsMC,
+                        fHSigmaThetaON, fHDiffPixThetaON, fHSigmaPixThetaON,
+                        fHIdBlindPixelsON, fHNBlindPixelsON);
+
+    MFillH fillblind("MCBlindPixels[MHBlindPixels]", "MBlindPixels");
+    fillblind.SetName("HBlind");
+
+
+    //...........................................
+
+    MSigmabarCalc sigbarcalc;
+
+    MFillH fillsigtheta ("MCSigmaTheta[MHSigmaTheta]", "MMcEvt");
+    fillsigtheta.SetName("HSigmaTheta");
+
+    MImgCleanStd    clean; 
+
+    // calculation of  image parameters ---------------------
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImgPar(fImgParName);
+
+    MHillasSrcCalc hsrccalc(sourceName, fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+    // --------------------------------------------------
+
+    MFSelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+    selstandard.SetCuts(92, 4, 60, 0.4, 1.05, 0.0, 0.0);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+
+      //MWriteRootFile &write = *(new MWriteRootFile(outNameImage));
+      MWriteRootFile write(outNameImage, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+
+
+    //*****************************
+    // entries in MParList
+
+    plist.AddToList(&tlist);
+    InitBinnings(&plist);
+
+    plist.AddToList(&source);
+
+
+    //*****************************
+    // entries in MTaskList
+
+    tlist.AddToList(&read);
+
+    //......................
+    tlist.AddToList(&fMC);
+    tlist.AddToList(&fDa);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&pcopy);
+    //tlist.AddToList(&waround);
+
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&nanal);
+    //......................
+
+    tlist.AddToList(&blindbeforepad);
+    tlist.AddToList(&padthomas);
+    tlist.AddToList(&blind);
+
+    tlist.AddToList(&contbasic);
+    tlist.AddToList(&fillblind);
+    tlist.AddToList(&sigbarcalc);
+    tlist.AddToList(&fillsigtheta);
+    tlist.AddToList(&clean);
+
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&hsrccalc);
+
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+
+    tlist.AddToList(&contstandard);
+    if (WMC1)
+      tlist.AddToList(&write);
+
+    //*****************************
+
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //if (WMC1)    
+    //  evtloop.Write();
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 1000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    plist.FindObject("MCSigmaTheta",  "MHSigmaTheta")->DrawClone();
+    plist.FindObject("MCBlindPixels", "MHBlindPixels")->DrawClone();
+
+    plist.FindObject("MHHillas")->DrawClone();
+    plist.FindObject("MHHillasExt")->DrawClone();
+    plist.FindObject("MHHillasSrc")->DrawClone();
+    plist.FindObject("MHNewImagePar")->DrawClone();
+    plist.FindObject("MHStarMap")->DrawClone();
+
+
+
+    DeleteBinnings(&plist);
+
+    gLog << "Macro ONAnalysis : End of Job A_MC" 
+         << endl;
+    gLog << "=========================================================" 
+         << endl;
+ }
+
+
+
+  //---------------------------------------------------------------------
+  // Job B_RF_UP
+  //============
+
+
+    //  - create (or read in) the matrices of training events for gammas 
+    //    and hadrons
+    //  - create (or read in) the trees
+    //  - then read ON1.root (or MC1.root) file 
+    //  - calculate the hadroness for the method of RANDOM FOREST
+    //  - update input root file with the hadroness
+
+
+ if (JobB_RF_UP)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONAnalysis : Start of Job B_RF_UP" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONAnalysis : JobB_RF_UP, RTrainRF, CTrainRF, RTree, WRF = "
+         << (JobB_RF_UP ? "kTRUE" : "kFALSE")  << ",  " 
+         << (RTrainRF ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (CTrainRF ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (RTree ?      "kTRUE" : "kFALSE")  << ",  "
+         << (WRF ?        "kTRUE" : "kFALSE")  << endl;
+
+
+    //--------------------------------------------
+    // parameters for the random forest
+    Int_t NumTrees = 100;
+    Int_t NumTry   =   3;
+    Int_t NdSize   =   1;
+
+
+    TString hadRFName = "HadRF";
+    Float_t maxhadronness =  0.23;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+    TString extin  = "1.root";
+    TString extout = "2.root";
+
+    //--------------------------------------------
+    // for the analysis using ON data only set typeMatrixHadrons = "ON"
+    //                        ON and OFF data                    = "OFF"
+    TString typeMatrixHadrons = "ON";
+    gLog << "typeMatrixHadrons = " << typeMatrixHadrons << endl;
+
+
+    // file to be updated (ON, OFF or MC)
+
+    //TString typeInput = "ON";
+    TString typeInput = "OFF";
+    //TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+    // name of input root file
+    TString NameData = outPath;
+    NameData += typeInput;
+    TString inNameData(NameData);
+    inNameData += extin;
+    gLog << "inNameData = " << inNameData << endl; 
+
+    // name of output root file
+    TString outNameData(NameData);
+    outNameData += extout;
+    gLog << "outNameData = " << outNameData << endl; 
+
+    //--------------------------------------------
+    // files to be read for generating 
+    //    - the matrices of training events
+    //    - and the root files of training and test events
+
+
+    // "hadrons" :
+    TString filenameHad = outPath;
+    filenameHad += typeMatrixHadrons;
+    filenameHad += extin;
+    Int_t howManyHadronsTrain = 12000;
+    Int_t howManyHadronsTest  = 12000;
+    gLog << "filenameHad = "    << filenameHad << ",   howManyHadronsTrain = "
+         << howManyHadronsTrain << ",   howManyHadronsTest = "
+         << howManyHadronsTest  << endl; 
+    
+
+    // "gammas" :
+    TString filenameMC = outPath;
+    filenameMC += "MC";
+    filenameMC += extin;
+    Int_t howManyGammasTrain = 12000;
+    Int_t howManyGammasTest  = 12000;
+    gLog << "filenameMC = "    << filenameMC << ",   howManyGammasTrain = "
+         << howManyGammasTrain << ",   howManyGammasTest = "
+         << howManyGammasTest  << endl; 
+    
+    //--------------------------------------------
+    // files for the matrices of training events 
+
+    TString NameGammas = outPath;
+    NameGammas += "RFmatrix_gammas_Train_";
+    NameGammas += "MC";
+    NameGammas += extin;
+
+    TString NameHadrons = outPath;
+    NameHadrons += "RFmatrix_hadrons_Train_";
+    NameHadrons += typeMatrixHadrons;
+    NameHadrons += extin;
+
+
+    //--------------------------------------------
+    // root files for the training events 
+
+    TString NameGammasTrain = outPath;
+    NameGammasTrain += "RF_gammas_Train_";
+    NameGammasTrain += "MC";
+    TString inNameGammasTrain(NameGammasTrain);    
+    inNameGammasTrain += extin;
+    TString outNameGammasTrain(NameGammasTrain);    
+    outNameGammasTrain += extout;
+
+
+    TString NameHadronsTrain = outPath;
+    NameHadronsTrain += "RF_hadrons_Train_";
+    NameHadronsTrain += typeMatrixHadrons;
+    TString inNameHadronsTrain(NameHadronsTrain);    
+    inNameHadronsTrain += extin;
+    TString outNameHadronsTrain(NameHadronsTrain);    
+    outNameHadronsTrain += extout;
+
+
+    //--------------------------------------------
+    // root files for the test events 
+
+    TString NameGammasTest = outPath;
+    NameGammasTest += "RF_gammas_Test_";
+    NameGammasTest += "MC";
+    TString inNameGammasTest(NameGammasTest);    
+    inNameGammasTest += extin;
+    TString outNameGammasTest(NameGammasTest);    
+    outNameGammasTest += extout;
+
+    TString NameHadronsTest = outPath;
+    NameHadronsTest += "RF_hadrons_Test_";
+    NameHadronsTest += typeMatrixHadrons;
+    TString inNameHadronsTest(NameHadronsTest);    
+    inNameHadronsTest += extin;
+    TString outNameHadronsTest(NameHadronsTest);    
+    outNameHadronsTest += extout;
+
+    //--------------------------------------------------------------------
+
+
+    MHMatrix matrixg("MatrixGammas");
+    matrixg.EnableGraphicalOutput();
+
+    matrixg.AddColumn("cos(MMcEvt.fTelescopeTheta)");
+    matrixg.AddColumn("MSigmabar.fSigmabar");
+    matrixg.AddColumn("log10(MHillas.fSize)");
+    matrixg.AddColumn("MHillasSrc.fDist");
+    matrixg.AddColumn("MHillas.fWidth");
+    matrixg.AddColumn("MHillas.fLength");
+    matrixg.AddColumn("log10(MHillas.fSize/(MHillas.fWidth*MHillas.fLength))");
+    matrixg.AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    matrixg.AddColumn("MNewImagePar.fConc");
+    matrixg.AddColumn("MNewImagePar.fLeakage1");
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.EnableGraphicalOutput();
+
+    matrixh.AddColumns(matrixg.GetColumns());
+
+    //--------------------------------------------
+    // file of trees of the random forest 
+
+    TString outRF = outPath;
+    outRF += "RF.root";
+
+
+   //*************************************************************************
+   // read in matrices of training events
+if (RTrainRF)
+  {
+    const char* mtxName = "MatrixGammas";
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Get matrix for (gammas)" << endl;
+    gLog << "matrix name        = " << mtxName << endl;
+    gLog << "name of root file  = " << NameGammas << endl;
+    gLog << "" << endl;
+
+
+    // read in the object with the name 'mtxName' from file 'NameGammas'
+    //
+    TFile fileg(NameGammas); 
+
+    matrixg.Read(mtxName);
+    matrixg.Print("SizeCols");
+
+
+    //***************************************************************** 
+
+    const char* mtxName = "MatrixHadrons";
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << " Get matrix for (hadrons)" << endl;
+    gLog << "matrix name        = " << mtxName << endl;
+    gLog << "name of root file  = " << NameHadrons << endl;
+    gLog << "" << endl;
+
+
+    // read in the object with the name 'mtxName' from file 'NameHadrons'
+    //
+    TFile fileh(NameHadrons); 
+
+    matrixh.Read(mtxName);
+    matrixh.Print("SizeCols");
+  }
+
+
+   //*************************************************************************
+   // create matrices of training events
+   // and root files of training and test events
+ 
+if (CTrainRF)
+  {
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << " Create matrices of training events and root files of training and test events" 
+         << endl;
+    gLog << " Gammas :" << endl;
+    gLog << "---------" << endl;
+
+    MParList  plistg;
+    MTaskList tlistg;
+
+    MReadMarsFile  readg("Events", filenameMC);
+    readg.DisableAutoScheme();
+
+    TString mgname("costhg");
+    MBinning bing("Binning"+mgname);
+    bing.SetEdges(10, 0., 1.0);
+
+    MH3 gref("cos(MMcEvt.fTelescopeTheta)");
+    gref.SetName(mgname);
+    MH::SetBinning(&gref.GetHist(), &bing);
+    for (Int_t i=1; i<=gref.GetNbins(); i++)
+      gref.GetHist().SetBinContent(i, 1.0);
+
+    MFEventSelector2 selectorg(gref);
+    selectorg.SetNumMax(howManyGammasTrain+howManyGammasTest);
+    selectorg.SetName("selectGammasTrainTest");
+    selectorg.SetInverted();
+    selectorg.SetUseOrigDistribution(kTRUE);
+
+    MContinue contg(&selectorg);
+    contg.SetName("ContGammas");
+
+    Double_t probg = ( (Double_t) howManyGammasTrain )
+                   / ( (Double_t)(howManyGammasTrain+howManyGammasTest) );
+    MFRandomSplit splitg(probg);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&splitg);
+    fillmatg.SetName("fillGammas");
+
+    //-----------------------
+    // for writing the root files of training and test events
+    // for gammas
+    
+    MWriteRootFile writetraing(inNameGammasTrain, "RECREATE");
+    writetraing.SetName("WriteGammasTrain");
+    writetraing.SetFilter(&splitg);
+
+      writetraing.AddContainer("MRawRunHeader", "RunHeaders");
+      writetraing.AddContainer("MTime",         "Events");
+      writetraing.AddContainer("MMcEvt",        "Events");
+      writetraing.AddContainer("ThetaOrig",     "Events");
+      writetraing.AddContainer("MSrcPosCam",    "Events");
+      writetraing.AddContainer("MSigmabar",     "Events");
+      writetraing.AddContainer("MHillas",       "Events");
+      writetraing.AddContainer("MHillasExt",    "Events");
+      writetraing.AddContainer("MHillasSrc",    "Events");
+      writetraing.AddContainer("MNewImagePar",  "Events");
+
+    MContinue contgtrain(&splitg);
+    contgtrain.SetName("ContGammaTrain");
+
+    MWriteRootFile writetestg(inNameGammasTest, "RECREATE");
+    writetestg.SetName("WriteGammasTest");
+
+      writetestg.AddContainer("MRawRunHeader", "RunHeaders");
+      writetestg.AddContainer("MTime",         "Events");
+      writetestg.AddContainer("MMcEvt",        "Events");
+      writetestg.AddContainer("ThetaOrig",     "Events");
+      writetestg.AddContainer("MSrcPosCam",    "Events");
+      writetestg.AddContainer("MSigmabar",     "Events");
+      writetestg.AddContainer("MHillas",       "Events");
+      writetestg.AddContainer("MHillasExt",    "Events");
+      writetestg.AddContainer("MHillasSrc",    "Events");
+      writetestg.AddContainer("MNewImagePar",  "Events");
+
+    //-----------------------
+    
+    //*****************************   fill gammas   ***  
+    // entries in MParList
+    
+    plistg.AddToList(&tlistg);
+    InitBinnings(&plistg);
+
+    plistg.AddToList(&matrixg);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tlistg.AddToList(&readg);
+    tlistg.AddToList(&contg);
+
+    tlistg.AddToList(&splitg);
+    tlistg.AddToList(&fillmatg);
+    tlistg.AddToList(&writetraing);
+    tlistg.AddToList(&contgtrain);
+
+    tlistg.AddToList(&writetestg);
+
+    //*****************************
+
+    MProgressBar matrixbar;
+    MEvtLoop evtloopg;
+    evtloopg.SetName("FillGammaMatrix");
+    evtloopg.SetParList(&plistg);
+    //evtloopg.ReadEnv(env, "", printEnv);
+    evtloopg.SetProgressBar(&matrixbar);
+
+    Int_t maxevents = -1;
+    if (!evtloopg.Eventloop(maxevents))
+        return;
+
+    tlistg.PrintStatistics(0, kTRUE);
+
+    matrixg.Print("SizeCols");
+    Int_t generatedgTrain = matrixg.GetM().GetNrows();
+    if ( fabs(generatedgTrain-howManyGammasTrain) > 
+                                    3.0*sqrt(howManyGammasTrain) )
+    {
+      gLog << "Macro ONAnalysis.C : no.of generated gamma training events (" 
+           << generatedgTrain << ") is incompatible with the no.of requested events (" 
+           << howManyGammasTrain << ")" << endl;   
+    }
+
+
+    Int_t generatedgTest = writetestg.GetNumExecutions();
+    if ( fabs(generatedgTest-howManyGammasTest) > 
+                                    3.0*sqrt(howManyGammasTest) )
+    {
+      gLog << "Macro ONAnalysis.C : no.of generated gamma test events (" 
+           << generatedgTest << ") is incompatible with the no.of requested events (" 
+           << howManyGammasTest << ")" << endl;   
+    }
+
+    //*****************************   fill hadrons   ***  
+    gLog << "---------------------------------------------------------------"
+         << endl;
+    gLog << " Hadrons :" << endl;
+    gLog << "----------" << endl;
+
+    MParList  plisth;
+    MTaskList tlisth;
+
+    MReadMarsFile  readh("Events", filenameHad);
+    readh.DisableAutoScheme();
+
+    TString mhname("costhh");
+    MBinning binh("Binning"+mhname);
+    binh.SetEdges(10, 0., 1.0);
+
+    //MH3 href("cos(MMcEvt.fTelescopeTheta)");
+    //href.SetName(mhname);
+    //MH::SetBinning(&href.GetHist(), &binh);
+    //for (Int_t i=1; i<=href.GetNbins(); i++)
+    //  href.GetHist().SetBinContent(i, 1.0);
+
+    //use the original distribution from the gammas
+    MH3 &href = *(selectorg.GetHistOrig());
+
+    MFEventSelector2 selectorh(href);
+    selectorh.SetNumMax(howManyHadronsTrain+howManyHadronsTest);
+    selectorh.SetName("selectHadronsTrainTest");
+    selectorh.SetInverted();
+
+    MContinue conth(&selectorh);
+    conth.SetName("ContHadrons");
+
+    Double_t probh = ( (Double_t) howManyHadronsTrain )
+                   / ( (Double_t)(howManyHadronsTrain+howManyHadronsTest) );
+    MFRandomSplit splith(probh);
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&splith);
+    fillmath.SetName("fillHadrons");
+
+    //-----------------------
+    // for writing the root files of training and test events
+    // for hadrons
+    
+    MWriteRootFile writetrainh(inNameHadronsTrain, "RECREATE");
+    writetrainh.SetName("WriteHadronsTrain");
+    writetrainh.SetFilter(&splith);
+
+      writetrainh.AddContainer("MRawRunHeader", "RunHeaders");
+      writetrainh.AddContainer("MTime",         "Events");
+      writetrainh.AddContainer("MMcEvt",        "Events");
+      writetrainh.AddContainer("ThetaOrig",     "Events");
+      writetrainh.AddContainer("MSrcPosCam",    "Events");
+      writetrainh.AddContainer("MSigmabar",     "Events");
+      writetrainh.AddContainer("MHillas",       "Events");
+      writetrainh.AddContainer("MHillasExt",    "Events");
+      writetrainh.AddContainer("MHillasSrc",    "Events");
+      writetrainh.AddContainer("MNewImagePar",  "Events");
+
+    MContinue conthtrain(&splith);
+
+    MWriteRootFile writetesth(inNameHadronsTest, "RECREATE");
+    writetesth.SetName("WriteHadronsTest");
+
+      writetesth.AddContainer("MRawRunHeader", "RunHeaders");
+      writetesth.AddContainer("MTime",         "Events");
+      writetesth.AddContainer("MMcEvt",        "Events");
+      writetesth.AddContainer("ThetaOrig",     "Events");
+      writetesth.AddContainer("MSrcPosCam",    "Events");
+      writetesth.AddContainer("MSigmabar",     "Events");
+      writetesth.AddContainer("MHillas",       "Events");
+      writetesth.AddContainer("MHillasExt",    "Events");
+      writetesth.AddContainer("MHillasSrc",    "Events");
+      writetesth.AddContainer("MNewImagePar",  "Events");
+
+
+    //*****************************  
+    // entries in MParList
+    
+    plisth.AddToList(&tlisth);
+    InitBinnings(&plisth);
+
+    plisth.AddToList(&matrixh);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tlisth.AddToList(&readh);
+    tlisth.AddToList(&conth);
+
+    tlisth.AddToList(&splith);
+    tlisth.AddToList(&fillmath);
+    tlisth.AddToList(&writetrainh);
+    tlisth.AddToList(&conthtrain);
+
+    tlisth.AddToList(&writetesth);
+
+    //*****************************
+
+    MProgressBar matrixbar;
+    MEvtLoop evtlooph;
+    evtlooph.SetName("FillHadronMatrix");
+    evtlooph.SetParList(&plisth);
+    //evtlooph.ReadEnv(env, "", printEnv);
+    evtlooph.SetProgressBar(&matrixbar);
+
+    Int_t maxevents = -1;
+    if (!evtlooph.Eventloop(maxevents))
+        return;
+
+    tlisth.PrintStatistics(0, kTRUE);
+
+    matrixh.Print("SizeCols");
+    Int_t generatedhTrain = matrixh.GetM().GetNrows();
+    if ( fabs(generatedhTrain-howManyHadronsTrain) > 
+                                    3.0*sqrt(howManyHadronsTrain) )
+    {
+      gLog << "Macro ONAnalysis.C : no.of generated hadron training events (" 
+           << generatedhTrain << ") is incompatible with the no.of requested events (" 
+           << howManyHadronsTrain << ")" << endl;   
+    }
+
+
+    Int_t generatedhTest = writetesth.GetNumExecutions();
+    if ( fabs(generatedhTest-howManyHadronsTest) > 
+                                    3.0*sqrt(howManyHadronsTest) )
+    {
+      gLog << "Macro ONAnalysis.C : no.of generated gamma test events (" 
+           << generatedhTest << ") is incompatible with the no.of requested events (" 
+           << howManyHadronsTest << ")" << endl;   
+    }
+
+
+    //*****************************************************  
+
+
+    // write out matrices of training events 
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Write out matrices of training events" << endl;
+
+
+      //-------------------------------------------
+      // "gammas"
+      gLog << "Gammas :" << endl;    
+      matrixg.Print("SizeCols");
+
+      TFile writeg(NameGammas, "RECREATE", "");
+      matrixg.Write();
+
+      gLog << "" << endl;
+      gLog << "Macro ONAnalysis : matrix of training events for gammas written onto file "
+           << NameGammas << endl;
+
+      //-------------------------------------------
+      // "hadrons"
+      gLog << "Hadrons :" << endl;    
+      matrixh.Print("SizeCols");
+
+      TFile writeh(NameHadrons, "RECREATE", "");
+      matrixh.Write();
+
+      gLog << "" << endl;
+      gLog << "Macro ONAnalysis : matrix of training events for hadrons written onto file "
+           << NameHadrons << endl;
+
+  }
+   //**********   end of creating matrices of training events   ***********
+
+
+    MRanForest *fRanForest;
+    MRanTree *fRanTree;
+    //-----------------------------------------------------------------
+    // read in the trees of the random forest 
+    if (RTree)
+    {
+      MParList plisttr;
+      MTaskList tlisttr;
+      plisttr.AddToList(&tlisttr);
+
+      MReadTree readtr("TREE", outRF);
+      readtr.DisableAutoScheme();
+
+      MRanForestFill rffill;
+      rffill.SetNumTrees(NumTrees);
+
+      // list of tasks for the loop over the trees
+
+      tlisttr.AddToList(&readtr);
+      tlisttr.AddToList(&rffill);
+
+      //-------------------
+      // Execute tree loop
+      //
+      MEvtLoop evtlooptr;
+      evtlooptr.SetName("ReadRFTrees");
+      evtlooptr.SetParList(&plisttr);
+      if (!evtlooptr.Eventloop())
+        return;
+
+      tlisttr.PrintStatistics(0, kTRUE);
+
+      gLog << "ONAnalysis : RF trees were read in from file "
+           << outRF << endl;
+
+    // get adresses of objects which are used in the next eventloop
+    fRanForest = (MRanForest*)plisttr->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        gLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plisttr->FindObject("MRanTree");
+    if (!fRanTree)                                  
+    {                                                                          
+        gLog << err << dbginf << "MRanTree not found... aborting." << endl;    
+        return kFALSE;
+    }
+
+    }
+
+    //-----------------------------------------------------------------
+    // grow the trees of the random forest (event loop = tree loop)
+
+    if (!RTree)
+    {
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Macro ONAnalysis : start growing trees" << endl;
+
+    MTaskList tlist2;
+    MParList plist2;
+    plist2.AddToList(&tlist2);
+
+    plist2.AddToList(&matrixg);
+    plist2.AddToList(&matrixh);
+
+    MRanForestGrow rfgrow2;
+    rfgrow2.SetNumTrees(NumTrees);
+    rfgrow2.SetNumTry(NumTry);
+    rfgrow2.SetNdSize(NdSize);
+
+    MWriteRootFile rfwrite2(outRF);
+    rfwrite2.AddContainer("MRanTree", "TREE");
+
+    MFillH fillh2("MHRanForestGini");
+
+    // list of tasks for the loop over the trees
+    
+    tlist2.AddToList(&rfgrow2);
+    tlist2.AddToList(&rfwrite2);
+    tlist2.AddToList(&fillh2);
+
+    //-------------------
+    // Execute tree loop
+    //
+    MEvtLoop treeloop;
+    treeloop.SetName("GrowRFTrees");
+    treeloop.SetParList(&plist2);
+
+    if ( !treeloop.Eventloop() )
+        return;
+
+    tlist2.PrintStatistics(0, kTRUE);
+
+    plist2.FindObject("MHRanForestGini")->DrawClone();
+
+
+    // get adresses of objects which are used in the next eventloop
+    fRanForest = (MRanForest*)plist2->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        gLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plist2->FindObject("MRanTree");
+    if (!fRanTree)                                  
+    {                                                                          
+        gLog << err << dbginf << "MRanTree not found... aborting." << endl;    
+        return kFALSE;
+    }
+
+    }
+    // end of growing the trees of the random forest
+    //-----------------------------------------------------------------
+
+
+    //-----------------------------------------------------------------
+    // Update the root files with the RF hadronness
+    //
+
+ if (WRF)
+  {
+    //TString fileName(inNameHadronsTrain);
+    //TString outName(outNameHadronsTrain);
+
+    //TString fileName(inNameHadronsTest);
+    //TString outName(outNameHadronsTest);
+
+    //TString fileName(inNameGammasTrain);
+    //TString outName(outNameGammasTrain);
+
+    //TString fileName(inNameGammasTest);
+    //TString outName(outNameGammasTest);
+
+    TString fileName(inNameData);
+    TString outName(outNameData);
+
+
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Update root file '" <<  fileName 
+         << "' with the RF hadronness; ==> " << outName << endl;
+
+   
+    MTaskList tliston;
+    MParList pliston;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", fileName);
+    read.DisableAutoScheme();
+
+
+    //.......................................................................
+    // calculate hadronnes for method of RANDOM FOREST
+
+
+    MRanForestCalc rfcalc;
+    rfcalc.SetHadronnessName(hadRFName);
+
+
+    //.......................................................................
+
+      //MWriteRootFile write(outName, "UPDATE");
+      MWriteRootFile write(outName, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      write.AddContainer(hadRFName,       "Events");
+
+    //-----------------------------------------------------------------
+
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadRFName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillranfor("MHRanForest");
+    fillranfor.SetName("HRanForest");
+
+    MFillH fillhadrf("hadRF[MHHadronness]", hadRFName);
+    fillhadrf.SetName("HhadRF");
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadRFName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(fRanForest);
+    pliston.AddToList(fRanTree);
+
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&rfcalc);
+    tliston.AddToList(&fillranfor);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&write);
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetName("UpdateRootFile");
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+    pliston.FindObject("MHRanForest")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->Print();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+     //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-macro");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << fileName << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+
+    DeleteBinnings(&pliston);
+  }
+
+    gLog << "Macro ONAnalysis : End of Job B_RF_UP" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+  //---------------------------------------------------------------------
+  // Job B_SC_UP
+  //============
+
+    //  - create (or read in) optimum supercuts parameter values
+    //
+    //  - calculate the hadroness for the supercuts
+    //
+    //  - update input root file, including the hadroness
+
+
+ if (JobB_SC_UP)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONAnalysis : Start of Job B_SC_UP" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONAnalysis : JobB_SC_UP, CMatrix, RMatrix, WOptimize, RTest, WSC = "
+         << (JobB_SC_UP ? "kTRUE" : "kFALSE")  << ",  " 
+         << (CMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (RMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (WOptimize  ? "kTRUE" : "kFALSE")  << ",  "
+         << (RTest      ? "kTRUE" : "kFALSE")  << ",  "
+         << (WSC        ? "kTRUE" : "kFALSE")  << endl;
+
+
+    //--------------------------------------------
+    // file which contains the initial parameter values for the supercuts 
+    // if parSCinit ="" the initial values are taken from the constructor of
+    //                  MSupercuts
+
+    TString parSCinit = outPath;
+    //parSCinit += "parSC_1709d";
+    parSCinit = "";
+
+    gLog << "parSCinit = " << parSCinit << endl;
+
+    //---------------
+    // file onto which the optimal parameter values for the supercuts 
+    // are written
+
+    TString parSCfile = outPath;
+    parSCfile += "parSC_2310a";
+
+    gLog << "parSCfile = " << parSCfile << endl;
+
+    //--------------------------------------------
+    // file to be updated (either ON or MC)
+
+    //TString typeInput = "ON";
+    //TString typeInput = "OFF";
+    TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+    // name of input root file
+    TString filenameData = outPath;
+    filenameData += typeInput;
+    filenameData += "2.root";
+    gLog << "filenameData = " << filenameData << endl; 
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += typeInput;
+    outNameImage += "3.root";
+    
+
+    //TString outNameImage = filenameData;
+
+    gLog << "outNameImage = " << outNameImage << endl; 
+
+    //--------------------------------------------
+    // files to be read for optimizing the supercuts
+    // 
+    // for the training
+    TString filenameTrain = outPath;
+    filenameTrain += "ON";
+    filenameTrain += "1.root";
+    Int_t howManyTrain = 800000;
+    gLog << "filenameTrain = " << filenameTrain << ",   howManyTrain = "
+         << howManyTrain  << endl; 
+
+    // for testing
+    TString filenameTest = outPath;
+    filenameTest += "ON";
+    filenameTest += "1.root";
+    Int_t howManyTest = 800000;
+
+    gLog << "filenameTest = " << filenameTest << ",   howManyTest = "
+         << howManyTest  << endl; 
+    
+
+    //--------------------------------------------
+    // files to contain the matrices (generated from filenameTrain and
+    //                                               filenameTest)
+    // 
+    // for the training
+    TString fileMatrixTrain = outPath;
+    fileMatrixTrain += "MatrixTrainSC";
+    fileMatrixTrain += ".root";
+    gLog << "fileMatrixTrain = " << fileMatrixTrain << endl; 
+
+    // for testing
+    TString fileMatrixTest = outPath;
+    fileMatrixTest += "MatrixTestSC";
+    fileMatrixTest += ".root";
+    gLog << "fileMatrixTest = " << fileMatrixTest << endl; 
+
+    
+
+    //---------------------------------------------------------------------
+    // Training and test matrices :
+    // - either create them and write them onto a file
+    // - or read them from a file
+
+
+    MFindSupercuts findsuper;
+    findsuper.SetFilenameParam(parSCfile);
+    findsuper.SetHadronnessName("HadSC");
+    findsuper.SetUseOrigDistribution(kTRUE);
+
+    //--------------------------
+    // create matrices and write them onto files 
+    if (CMatrix)
+    {
+      TString mname("costheta");
+      MBinning bin("Binning"+mname);
+      bin.SetEdges(10, 0., 1.0);
+
+      MH3 mh3("cos(MMcEvt.fTelescopeTheta)");
+      mh3.SetName(mname);
+      MH::SetBinning(&mh3.GetHist(), &bin);
+      for (Int_t i=1; i<=mh3.GetNbins(); i++)
+        mh3.GetHist().SetBinContent(i, 1.0);
+
+
+      if (filenameTrain == filenameTest)
+      {
+        if ( !findsuper.DefineTrainTestMatrix(
+                              filenameTrain,   mh3, 
+                              howManyTrain,    howManyTest,  
+                              fileMatrixTrain, fileMatrixTest)     )
+        {
+          *fLog << "Macro ONAnalysis.C : DefineTrainTestMatrix failed" << endl;
+          return;
+        }
+
+      }
+      else
+      {
+        if ( !findsuper.DefineTrainMatrix(filenameTrain, mh3,
+                                          howManyTrain,  fileMatrixTrain) )
+        {
+          *fLog << "Macro ONAnalysis.C : DefineTrainMatrix failed" << endl;
+          return;
+        }
+
+	if ( !findsuper.DefineTestMatrix( filenameTest, mh3, 
+                                          howManyTest,  fileMatrixTest)  )
+        {
+          *fLog << "Macro ONAnalysis.C : DefineTestMatrix failed" << endl;
+          return;
+        }
+      }
+     }
+
+    //--------------------------
+    // read matrices from files
+    //                              
+
+    if (RMatrix)
+      findsuper.ReadMatrix(fileMatrixTrain, fileMatrixTest);
+    //--------------------------
+
+
+
+    //---------------------------------------------------------------------
+    // optimize supercuts using the training sample
+    // 
+    // the initial values are taken 
+    //     - from the file parSCinit (if != "")
+    //     - or from the arrays params and steps (if their sizes are != 0)
+    //     - or from the MSupercuts constructor
+
+
+if (WOptimize)
+  {
+    gLog << "Macro ONAnalysis.C : optimize the supercuts using the training matrix" 
+         << endl;
+
+    TArrayD params(0);
+    TArrayD steps(0);
+  
+    if (parSCinit == "")
+    {
+      Double_t vparams[104] = {
+      // LengthUp
+	0.315585,  0.001455, 0.203198, 0.005532, -0.001670, -0.020362,
+	0.007388, -0.013463,
+      // LengthLo
+        0.151530,  0.028323, 0.510707, 0.053089,  0.013708,  2.357993,
+	0.000080, -0.007157,
+      // WidthUp
+        0.145412, -0.001771, 0.054462, 0.022280, -0.009893,  0.056353,
+        0.020711, -0.016703,
+      // WidthLo
+        0.089187, -0.006430, 0.074442, 0.003738, -0.004256, -0.014101,
+        0.006126, -0.002849,
+      // DistUp
+        1.787943,  0.0,      2.942310, 0.199815,  0.0,       0.249909,
+        0.189697,  0.0,
+      // DistLo
+        0.589406,  0.0,     -0.083964,-0.007975,  0.0,       0.045374,
+       -0.001750,  0.0,
+      // AsymUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp
+	13.12344,  0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+      Double_t vsteps[104] = {
+      // LengthUp
+        0.03,      0.0002,   0.02,     0.0006,    0.0002,    0.002,
+        0.0008,    0.002,
+      // LengthLo
+        0.02,      0.003,    0.05,     0.006,     0.002,     0.3,
+        0.0001,    0.0008,
+      // WidthUp
+        0.02,      0.0002,   0.006,    0.003,     0.002,     0.006,
+        0.002,     0.002,
+      // WidthLo
+        0.009,     0.0007,   0.008,    0.0004,    0.0005,    0.002,
+        0.0007,    0.003,
+      // DistUp
+        0.2,       0.0,      0.3,      0.02,      0.0,       0.03,
+        0.02,      0.0
+      // DistLo
+        0.06,      0.0,      0.009,    0.0008,    0.0,       0.005,
+        0.0002,    0.0
+      // AsymUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+      params.Set(104, vparams);
+      steps.Set (104, vsteps );
+    }
+
+    Bool_t rf;
+    rf = findsuper.FindParams(parSCinit, params, steps);
+
+    if (!rf) 
+    {
+       gLog << "Macro ONAnalysis.C : optimization of supercuts failed" << endl;
+       return;
+    }
+  }
+
+    //--------------------------------------
+    // test the supercuts on the test sample
+    //    
+
+ if (RTest)
+ {
+    gLog << "Macro ONAnalysis.C : test the supercuts on the test matrix" << endl;
+    Bool_t rt = findsuper.TestParams();
+    if (!rt) 
+    {
+       gLog << "Macro ONAnalysis.C : test of supercuts on the test matrix failed" 
+            << endl;
+    }
+
+ }
+
+
+    //-----------------------------------------------------------------
+    // Update the input files with the SC hadronness
+    //
+
+ if (WSC)
+ {
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Update input file '" <<  filenameData 
+         << "' with the SC hadronness" << endl;
+
+
+    //----------------------------------------------------
+    // read in optimum parameter values for the supercuts
+
+    TFile inparam(parSCfile);
+    MSupercuts scin;
+    scin.Read("MSupercuts");
+    inparam.Close();
+
+    gLog << "Parameter values for supercuts were read in from file '"
+         << parSCfile << "'" << endl;
+
+    TArrayD supercutsPar;
+    supercutsPar =  scin.GetParameters();
+
+    TArrayD supercutsStep;
+    supercutsStep =  scin.GetStepsizes();
+
+    gLog << "Parameter values for supercuts : " << endl;
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+    {
+      gLog << supercutsPar[i] << ",  ";
+    }
+    gLog << endl;
+
+    gLog << "Step values for supercuts : " << endl;
+    for (Int_t i=0; i<supercutsStep.GetSize(); i++)
+    {
+      gLog << supercutsStep[i] << ",  ";
+    }
+    gLog << endl;
+
+
+    //----------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    // set the parameters of the supercuts
+    MSupercuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+    gLog << "parameter values for the supercuts used for updating the input file ' " 
+         << filenameData << "'" << endl;
+    supercutsPar = supercuts.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+    {
+      gLog << supercutsPar[i] << ",  ";
+    }
+    gLog << endl;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+    //.......................................................................
+    // calculation of hadroness for the supercuts
+    // (=0.25 if fullfilled, =0.75 otherwise)
+
+    TString hadSCName = "HadSC";
+    MSupercutsCalc sccalc(fHilName, fHilNameSrc);
+    sccalc.SetHadronnessName(hadSCName);
+
+
+    //.......................................................................
+
+
+      //MWriteRootFile write(outNameImage, "UPDATE");
+      //MWriteRootFile write = new MWriteRootFile(outNameImage, "RECREATE");
+
+    
+      MWriteRootFile write(outNameImage, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      write.AddContainer("HadRF",         "Events");
+      write.AddContainer(hadSCName,       "Events");
+    
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    Float_t maxhadronness =  0.40;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadSCName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillhadsc("hadSC[MHHadronness]", hadSCName);
+    fillhadsc.SetName("HhadSC");
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadSCName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+
+    TH1  &alphahist = alphaabs->GetHist();
+
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(&supercuts);
+
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&sccalc);
+    tliston.AddToList(&fillhadsc);
+
+    tliston.AddToList(&write);
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+     //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-macro");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << filenameData << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+    DeleteBinnings(&pliston);
+ }
+
+
+    gLog << "Macro ONAnalysis : End of Job B_SC_UP" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+
+  //---------------------------------------------------------------------
+  // Job C  
+  //======
+
+    //  - read ON1 and MC1 data files  
+    //    which should have been updated to contain the hadronnesses
+    //    for the method of Random Forest and for the SUPERCUTS
+    //  - produce Neyman-Pearson plots
+ 
+ if (JobC)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONAnalysis : Start of Job C" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONAnalysis : JobC = " 
+         << (JobC       ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // name of input data file
+    TString filenameData = outPath;
+    filenameData += "ON";
+    filenameData += "3.root";
+    gLog << "filenameData = " << filenameData << endl;
+
+    // name of input MC file
+    TString filenameMC = outPath;
+    filenameMC += "MC";
+    filenameMC += "3.root";
+    gLog << "filenameMC   = " << filenameMC   << endl;
+
+
+    //-----------------------------------------------------------------
+
+    MTaskList tliston;
+    MParList pliston;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameMC);
+    read.AddFile(filenameData);
+    read.DisableAutoScheme();
+
+
+    //.......................................................................
+    // names of hadronness containers
+
+    //TString hadNNName = "HadNN";
+    TString hadSCName = "HadSC";
+    TString hadRFName = "HadRF";
+
+    //.......................................................................
+
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+    Float_t maxhadronness =  0.40;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadSCName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    //MFillH fillhadnn("hadNN[MHHadronness]", hadNNName);
+    //fillhadnn.SetName("HhadNN");
+    MFillH fillhadsc("hadSC[MHHadronness]", hadSCName);
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", hadRFName);
+    fillhadrf.SetName("HhadRF");
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadSCName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    //tliston.AddToList(&fillhadnn);
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+   
+    tliston.AddToList(&contfinalgh);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 35000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    //pliston.FindObject("hadNN", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro ONAnalysis : End of Job C" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+
+  //---------------------------------------------------------------------
+  // Job D
+  //======
+
+    //  - select g/h separation method XX
+    //  - read ON2 (or MC2) root file 
+    //  - apply cuts in hadronness
+    //  - make plots
+
+
+ if (JobD)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONAnalysis : Start of Job D" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONAnalysis : JobD = " 
+         << (JobD        ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // type of data to be analysed
+    TString typeData = "ON";
+    //TString typeData = "OFF";
+    //TString typeData = "MC";
+    gLog << "typeData = " << typeData << endl;
+
+    TString ext      = "3.root";
+
+
+    //------------------------------
+    // selection of g/h separation method
+    // and definition of final selections
+
+    //TString XX("SC");
+    TString XX("RF");
+    TString fhadronnessName("Had");
+    fhadronnessName += XX;
+    gLog << "fhadronnessName = " << fhadronnessName << endl;
+
+    // maximum values of the hadronness, |ALPHA| and DIST
+    Float_t maxhadronness   = 0.233;
+    Float_t maxalpha        = 20.0;
+    Float_t maxdist         = 10.0;
+    gLog << "Maximum values of hadronness, |ALPHA| and DIST = "
+         << maxhadronness << ",  " << maxalpha << ",  " 
+         << maxdist << endl;
+
+
+    //------------------------------
+    // name of data file to be analysed
+    TString filenameData(outPath);
+    filenameData += typeData;
+    filenameData += ext;
+    gLog << "filenameData = " << filenameData << endl;
+
+
+
+    //*************************************************************************
+    //
+    // Analyse the data
+    //
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(fhadronnessName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillhadsc("hadSC[MHHadronness]", "HadSC");
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", "HadRF");
+    fillhadrf.SetName("HhadRF");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+
+    TH1  &alphahist = alphaabs->GetHist();
+
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");    
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");    
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(fhadronnessName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 10000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+    //-------------------------------------------
+
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-JobD");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << filenameData << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro ONAnalysis : End of Job D" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+
+
+  //---------------------------------------------------------------------
+  // Job E_XX
+  //=========
+
+    //  - select g/h separation method XX
+    //  - read MC_XX2.root file 
+    //  - calculate eff. collection area
+    //  - read ON_XX2.root file 
+    //  - apply final cuts
+    //  - calculate flux
+    //  - write root file for ON data after final cuts (ON_XX3.root))
+
+
+ if (JobE_XX)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONAnalysis : Start of Job E_XX" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro 
+Analysis : JobE_XX, CCollArea, OEEst, WEX = " 
+         << (JobE_XX ? "kTRUE" : "kFALSE")  << ",  " 
+         << (CCollArea?"kTRUE" : "kFALSE")  << ",  " 
+         << (OEEst ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (WEX     ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // type of data to be analysed
+    //TString typeData = "ON";
+    //TString typeData = "OFF";
+    TString typeData = "MC";
+    gLog << "typeData = " << typeData << endl;
+
+    TString typeMC   = "MC";
+    TString ext      = "3.root";
+    TString extout   = "4.root";
+
+    //------------------------------
+    // selection of g/h separation method
+    // and definition of final selections
+
+    //TString XX("SC");
+    TString XX("RF");
+    TString fhadronnessName("Had");
+    fhadronnessName += XX;
+    gLog << "fhadronnessName = " << fhadronnessName << endl;
+
+    // maximum values of the hadronness, |ALPHA| and DIST
+    Float_t maxhadronness   = 0.23;
+    Float_t maxalpha        = 20.0;
+    Float_t maxdist         = 10.0;
+    gLog << "Maximum values of hadronness, |ALPHA| and DIST = "
+         << maxhadronness << ",  " << maxalpha << ",  " 
+         << maxdist << endl;
+
+    //------------------------------
+    // name of MC file to be used for optimizing the energy estimator
+    TString filenameOpt(outPath);
+    filenameOpt += typeMC;
+    filenameOpt += ext; 
+    gLog << "filenameOpt = " << filenameOpt << endl;
+
+    //------------------------------
+    // name of file containing the parameters of the energy estimator
+    TString energyParName(outPath);
+    energyParName += "energyest_";
+    energyParName += XX;
+    energyParName += ".root";
+    gLog << "energyParName = " << energyParName << endl;
+
+    //------------------------------
+    // name of MC file to be used for calculating the eff. collection areas
+    TString filenameArea(outPath);
+    filenameArea += typeMC;
+    filenameArea += ext; 
+    gLog << "filenameArea = " << filenameArea << endl;
+
+    //------------------------------
+    // name of file containing the eff. collection areas
+    TString collareaName(outPath);
+    collareaName += "area_";
+    collareaName += XX;
+    collareaName += ".root";
+    gLog << "collareaName = " << collareaName << endl;
+
+    //------------------------------
+    // name of data file to be analysed
+    TString filenameData(outPath);
+    filenameData += typeData;
+    filenameData += ext;
+    gLog << "filenameData = " << filenameData << endl;
+
+    //------------------------------
+    // name of output data file (after the final cuts)
+    TString filenameDataout(outPath);
+    filenameDataout += typeData;
+    filenameDataout += "_";
+    filenameDataout += XX;
+    filenameDataout += extout;
+    gLog << "filenameDataout = " << filenameDataout << endl;
+
+    //------------------------------
+    // name of file containing histograms for flux calculastion
+    TString filenameResults(outPath);
+    filenameResults += typeData;
+    filenameResults += "Results_";
+    filenameResults += XX;
+    filenameResults += extout;
+    gLog << "filenameResults = " << filenameResults << endl;
+
+
+    //====================================================================
+
+    MHMcCT1CollectionArea collarea;
+    collarea.SetEaxis(MHMcCT1CollectionArea::kLinear);
+
+    MParList  parlist;
+    InitBinnings(&parlist);
+
+  if (CCollArea)
+  {
+    gLog << "-----------------------------------------------" << endl;
+    gLog << "Start calculation of effective collection areas" << endl;
+
+
+    MTaskList tasklist;
+
+    //---------------------------------------
+    // Setup the tasks to be executed
+    //
+    MReadMarsFile reader("Events", filenameArea);
+    reader.DisableAutoScheme();
+
+    MFSelFinal cuthadrons;
+    cuthadrons.SetHadronnessName(fhadronnessName);
+    cuthadrons.SetCuts(maxhadronness, maxalpha, maxdist);
+
+    MContinue conthadrons(&cuthadrons);
+
+
+    MFillH filler("MHMcCT1CollectionArea", "MMcEvt");
+    filler.SetName("CollectionArea");
+
+    //********************************
+    // entries in MParList
+
+    parlist.AddToList(&tasklist);
+
+    parlist.AddToList(&collarea);
+
+    //********************************
+    // entries in MTaskList
+
+    tasklist.AddToList(&reader);   
+    tasklist.AddToList(&conthadrons);
+    tasklist.AddToList(&filler);
+
+    //********************************
+
+    //-----------------------------------------
+    // Execute event loop
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    MProgressBar bar;
+    magic.SetProgressBar(&bar);
+    if (!magic.Eventloop())
+        return;
+
+    tasklist.PrintStatistics(0, kTRUE);
+
+    // Calculate effective collection areas 
+    // and display the histograms
+    //
+    //MHMcCT1CollectionArea *collarea = 
+    //     (MHMcCT1CollectionArea*)parlist.FindObject("MHMcCT1CollectionArea");
+    collarea.CalcEfficiency();
+    collarea.DrawClone();
+
+
+
+    //---------------------------------------------
+    // Write histograms to a file 
+    //
+
+    TFile f(collareaName, "RECREATE");
+    //collarea.GetHist()->Write();
+    //collarea.GetHAll()->Write();
+    //collarea.GetHSel()->Write();
+    collarea.Write();
+
+    f.Close();
+
+    gLog << "Collection area plots written onto file " << collareaName << endl;
+
+    gLog << "Calculation of effective collection areas done" << endl;
+    gLog << "-----------------------------------------------" << endl;    
+    //------------------------------------------------------------------
+  }
+
+  if (!CCollArea)
+  {
+    gLog << "-----------------------------------------------" << endl;
+    gLog << "Read in effective collection areas from file " 
+         << collareaName << endl;
+
+    TFile collfile(collareaName);
+    collfile.ls();
+    collarea.Read("MHMcCT1CollectionArea");
+    collarea.DrawClone();
+
+    gLog << "Effective collection areas were read in from file " 
+         << collareaName << endl;
+    gLog << "-----------------------------------------------" << endl;    
+  }
+
+
+    // save binnings for call to CT1EEst
+    MBinning *binsE     = (MBinning*)parlist.FindObject("BinningE");
+    if (!binsE)
+	{
+          gLog << "Object 'BinningE' not found in MParList" << endl;
+          return;
+	}
+    MBinning *binsTheta = (MBinning*)parlist.FindObject("BinningTheta");
+    if (!binsTheta)
+	{
+          gLog << "Object 'BinningTheta' not found in MParList" << endl;
+          return;
+	}
+
+    //-------------------------------------
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+ if (OEEst)
+ { 
+   //===========================================================
+    //
+    // Optimization of energy estimator
+    //
+    gLog << "Macro ONAnalysis.C : calling CT1EEst" << endl;
+
+    TString inpath("");
+    TString outpath("");
+    Int_t howMany = 2000;
+    CT1EEst(inpath,   filenameOpt,   outpath, energyParName, 
+            fHilName, fHilNameSrc,   fhadronnessName,
+            howMany,  maxhadronness, maxalpha, maxdist,
+            binsE, binsTheta);
+    gLog << "Macro ONAnalysis.C : returning from CT1EEst" << endl;
+ }
+
+ if (WEX)
+ {
+    //-----------------------------------------------------------
+    //
+    // Read in parameters of energy estimator ("MMcEnergyEst")
+    //                   and migration matrix ("MHMcEnergyMigration")
+    //
+    gLog << "================================================================"
+         << endl;
+    gLog << "Macro ONAnalysis.C : read parameters of energy estimator and migration matrix from file '"
+         << energyParName << "'" << endl;
+    TFile enparam(energyParName);
+    enparam.ls();
+    MMcEnergyEst mcest("MMcEnergyEst"); 
+    mcest.Read("MMcEnergyEst");
+
+    //MMcEnergyEst &mcest = *((MMcEnergyEst*)gROOT->FindObject("MMcEnergyEst"));
+    gLog << "Parameters of energy estimator were read in" << endl;
+
+
+    gLog << "Read in Migration matrix" << endl;   
+
+    MHMcEnergyMigration mighiston("MHMcEnergyMigration");
+    mighiston.Read("MHMcEnergyMigration");
+    //MHMcEnergyMigration &mighiston = 
+    //      *((MHMcEnergyMigration*)gROOT->FindObject("MHMcEnergyMigration"));
+
+    gLog << "Migration matrix was read in" << endl;
+
+
+    TArrayD parA(mcest.GetNumCoeffA());
+    TArrayD parB(mcest.GetNumCoeffB());
+    for (Int_t i=0; i<parA.GetSize(); i++)
+      parA[i] = mcest.GetCoeff(i);
+    for (Int_t i=0; i<parB.GetSize(); i++)
+      parB[i] = mcest.GetCoeff( i+parA.GetSize() );
+
+    //*************************************************************************
+    //
+    // Analyse the data
+    //
+    gLog << "============================================================"
+         << endl;
+    gLog << "Analyse the data" << endl;
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+    //.......................................................................
+
+      gLog << "Macro ONAnalysis.C : write root file '" << filenameDataout 
+           << "'" << endl;
+   
+      //MWriteRootFile &write = *(new MWriteRootFile(filenameDataout));
+
+
+      MWriteRootFile write(filenameDataout, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      //write.AddContainer("HadNN",         "Events");
+      write.AddContainer("HadSC",         "Events");
+      write.AddContainer("HadRF",         "Events");
+
+      write.AddContainer("MEnergyEst",    "Events");
+
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(fhadronnessName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    //MFillH fillhadnn("hadNN[MHHadronness]", "HadNN");
+    //fillhadnn.SetName("HhadNN");
+    MFillH fillhadsc("hadSC[MHHadronness]", "HadSC");
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", "HadRF");
+    fillhadrf.SetName("HhadRF");
+
+    //---------------------------
+    // calculate estimated energy
+
+    MEnergyEstParam eeston(fHilName);
+    eeston.Add(fHilNameSrc);
+
+    eeston.SetCoeffA(parA);
+    eeston.SetCoeffB(parB);
+
+    //---------------------------
+    // calculate estimated energy using Daniel's parameters
+
+    //MEnergyEstParamDanielMkn421 eeston(fHilName);
+    //eeston.Add(fHilNameSrc);
+    //eeston.SetCoeffA(parA);
+    //eeston.SetCoeffB(parB);
+
+
+    //---------------------------
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");    
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");    
+
+    //---------------------------
+    // new from Robert
+
+    MFillH hfill6("MHTimeDiffTheta", "MMcEvt");
+    hfill6.SetName("HTimeDiffTheta");
+
+    MFillH hfill6a("MHTimeDiffTime", "MMcEvt");
+    hfill6a.SetName("HTimeDiffTime");
+
+    MFillH hfill7("MHAlphaEnergyTheta", fHilNameSrc);
+    hfill7.SetName("HAlphaEnergyTheta");
+
+    MFillH hfill7a("MHAlphaEnergyTime", fHilNameSrc);
+    hfill7a.SetName("HAlphaEnergyTime");
+
+    MFillH hfill7b("MHThetabarTime", fHilNameSrc);
+    hfill7b.SetName("HThetabarTime");
+
+    MFillH hfill7c("MHEnergyTime", "MMcEvt");
+    hfill7c.SetName("HEnergyTime");
+
+
+    //---------------------------
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(fhadronnessName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    // robert      
+    tliston.AddToList(&hfill6);   //timediff
+    tliston.AddToList(&hfill6a);   //timediff
+
+    tliston.AddToList(&contfinalgh);
+    tliston.AddToList(&eeston);
+
+    tliston.AddToList(&write);
+
+    //tliston.AddToList(&fillhadnn);
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    //robert
+    tliston.AddToList(&hfill7);
+    tliston.AddToList(&hfill7a);
+    tliston.AddToList(&hfill7b);
+    tliston.AddToList(&hfill7c);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    //pliston.FindObject("hadNN", "MHHadronness")->DrawClone();
+
+    gLog << "before hadRF" << endl;
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+
+    gLog << "before hadSC" << endl;
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    gLog << "before MHHillas" << endl;
+    pliston.FindObject("MHHillas")->DrawClone();
+
+    gLog << "before MHHillasExt" << endl;
+    pliston.FindObject("MHHillasExt")->DrawClone();
+
+    gLog << "before MHHillasSrc" << endl;
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+
+    gLog << "before MHNewImagePar" << endl;
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+
+    gLog << "before MHStarMap" << endl;
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    gLog << "before DeleteBinnings" << endl;
+
+    DeleteBinnings(&pliston);
+
+    gLog << "before Robert's code" << endl;
+
+
+//rwagner write all relevant histograms onto a file
+
+  if (WRobert)
+  {
+    gLog << "=======================================================" << endl;
+    gLog << "Write results onto file '" << filenameResults << "'" << endl;
+
+    TFile outfile(filenameResults,"recreate");
+
+    MHHillasSrc* hillasSrc = 
+      (MHHillasSrc*)(pliston->FindObject("MHHillasSrc"));
+        TH1F* alphaHist = (TH1F*)(hillasSrc->GetHistAlpha());
+    alphaHist->Write();
+    gLog << "Alpha plot has been written out" << endl;    
+
+
+    MHAlphaEnergyTheta* aetH = 
+      (MHAlphaEnergyTheta*)(pliston->FindObject("MHAlphaEnergyTheta"));
+    TH3D* aetHist = (TH3D*)(aetH->GetHist());
+    aetHist->SetName("aetHist");
+    aetHist->Write();
+    gLog << "AlphaEnergyTheta plot has been written out" << endl;    
+
+    MHAlphaEnergyTime* aetH2 = 
+      (MHAlphaEnergyTime*)(pliston->FindObject("MHAlphaEnergyTime"));
+    TH3D* aetHist2 = (TH3D*)(aetH2->GetHist());
+    aetHist2->SetName("aetimeHist");
+//     aetHist2->DrawClone();
+    aetHist2->Write();
+    gLog << "AlphaEnergyTime plot has been written out" << endl;    
+
+    MHThetabarTime* tbt = 
+      (MHThetabarTime*)(pliston->FindObject("MHThetabarTime"));
+    TProfile* tbtHist = (TProfile*)(tbt->GetHist());
+    tbtHist->SetName("tbtHist");
+    tbtHist->Write();
+    gLog << "ThetabarTime plot has been written out" << endl;    
+
+    MHEnergyTime* ent = 
+      (MHEnergyTime*)(pliston->FindObject("MHEnergyTime"));
+    TH2D* entHist = (TH2D*)(ent->GetHist());
+    entHist->SetName("entHist");
+    entHist->Write();
+    gLog << "EnergyTime plot has been written out" << endl;    
+    
+    MHTimeDiffTheta *time = (MHTimeDiffTheta*)pliston.FindObject("MHTimeDiffTheta");
+    TH2D* timeHist = (TH2D*)(time->GetHist());
+    timeHist->SetName("MHTimeDiffTheta");
+    timeHist->SetTitle("Time diffs");
+    timeHist->Write();
+    gLog << "TimeDiffTheta plot has been written out" << endl;    
+
+
+    MHTimeDiffTime *time2 = (MHTimeDiffTime*)pliston.FindObject("MHTimeDiffTime");
+    TH2D* timeHist2 = (TH2D*)(time2->GetHist());
+    timeHist2->SetName("MHTimeDiffTime");
+    timeHist2->SetTitle("Time diffs");
+    timeHist2->Write();
+    gLog << "TimeDiffTime plot has been written out" << endl;    
+
+//rwagner write also collareas to same file
+    collarea->GetHist()->Write();
+    collarea->GetHAll()->Write();
+    collarea->GetHSel()->Write();
+    gLog << "Effective collection areas have been written out" << endl;        
+
+//rwagner todo: write alpha_cut, type of g/h sep (RF, SC, NN), type of data
+//rwagner (ON/OFF/MC), MJDmin, MJDmax to this file
+
+    gLog << "before closing outfile" << endl;
+
+    //outfile.Close();
+    gLog << "Results were written onto file '" << filenameResults 
+         << "'" << endl;
+    gLog << "=======================================================" << endl;
+  }
+
+  }
+
+    gLog << "Macro ONAnalysis : End of Job E_XX" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/ONOFFAnalysis.C
===================================================================
--- /tags/Mars-V0.9/macros/ONOFFAnalysis.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/ONOFFAnalysis.C	(revision 9772)
@@ -0,0 +1,3392 @@
+
+//#include "MagicEgyEst.C"
+
+
+void InitBinnings(MParList *plist)
+{
+        gLog << "InitBinnings" << endl;
+
+        //--------------------------------------------
+        MBinning *binse = new MBinning("BinningE");
+        //binse->SetEdgesLog(30, 1.0e2, 1.0e5);
+
+	//This is Daniel's binning in energy:
+        binse->SetEdgesLog(14, 296.296, 86497.6);
+        plist->AddToList(binse);
+
+        //--------------------------------------------
+
+        MBinning *binssize = new MBinning("BinningSize");
+        binssize->SetEdgesLog(50, 10, 1.0e5);
+        plist->AddToList(binssize);
+
+        MBinning *binsdistc = new MBinning("BinningDist");
+        binsdistc->SetEdges(50, 0, 1.4);
+        plist->AddToList(binsdistc);
+
+        MBinning *binswidth = new MBinning("BinningWidth");
+        binswidth->SetEdges(50, 0, 1.0);
+        plist->AddToList(binswidth);
+
+        MBinning *binslength = new MBinning("BinningLength");
+        binslength->SetEdges(50, 0, 1.0);
+        plist->AddToList(binslength);
+
+        MBinning *binsalpha = new MBinning("BinningAlpha");
+        binsalpha->SetEdges(100, -100, 100);
+        plist->AddToList(binsalpha);
+
+        MBinning *binsasym = new MBinning("BinningAsym");
+        binsasym->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsasym);
+
+        MBinning *binsm3l = new MBinning("BinningM3Long");
+        binsm3l->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3l);
+
+        MBinning *binsm3t = new MBinning("BinningM3Trans");
+        binsm3t->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3t);
+
+   
+        //.....
+        MBinning *binsb = new MBinning("BinningSigmabar");
+        binsb->SetEdges( 100,  0.0,  50.0);
+        plist->AddToList(binsb);
+
+        MBinning *binssig = new MBinning("BinningSigma");
+        binssig->SetEdges( 100,  0.0, 120.0);
+        plist->AddToList(binssig);
+
+        MBinning *binth = new MBinning("BinningTheta");
+        // this is Daniel's binning in theta
+        //Double_t yedge[8] = 
+        //  {9.41, 16.22, 22.68, 28.64, 34.03, 38.84, 43.08, 44.99};
+        // this is our binning
+        //Double_t yedge[9] = 
+        //               {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        //TArrayD yed;
+        //yed.Set(9,yedge);
+        //binth->SetEdges(yed);
+        
+        binth->SetEdges(     1, 0.0, 90.0);
+        //binth->SetEdgesCos( 10, 0.0, 90.0);
+        plist->AddToList(binth);
+
+        //MBinning *bincosth = new MBinning("BinningCosTheta");
+        //Double_t yedge[9] = 
+        //               {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        //Double_t zedge[9]; 
+        //for (Int_t i=0; i<9; i++)
+	//{
+	//zedge[8-i] = cos(yedge[i]/kRad2Deg);
+	//}
+        //TArrayD zed;
+        //zed.Set(9,zedge);
+        //bincosth->SetEdges(zed);
+        //plist->AddToList(bincosth);
+
+        MBinning *binsdiff = new MBinning("BinningDiffsigma2");
+        binsdiff->SetEdges(100, -500.0, 1500.0);
+        plist->AddToList(binsdiff);
+
+        // robert ----------------------------------------------
+        MBinning *binsalphaf = new MBinning("BinningAlphaFlux");
+        binsalphaf->SetEdges(100, -100, 100);
+        plist->AddToList(binsalphaf);
+
+	MBinning *binsdifftime = new MBinning("BinningTimeDiff");
+	binsdifftime->SetEdges(50, 0, 10);
+	plist->AddToList(binsdifftime);
+
+	MBinning *binstime = new MBinning("BinningTime");
+	binstime->SetEdges(50, 44500, 61000);
+	plist->AddToList(binstime);
+}
+
+
+void DeleteBinnings(MParList *plist)
+{
+        gLog << "DeleteBinnings" << endl;
+
+        TObject *bin;
+
+        //--------------------------------------------
+        bin = plist->FindObject("BinningE");
+        if (bin) delete bin;
+
+        //--------------------------------------------
+
+        bin = plist->FindObject("BinningSize");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDist");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningWidth");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningLength");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAlpha");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAsym");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Long");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Trans");
+        if (bin) delete bin;
+
+        //.....
+        bin = plist->FindObject("BinningSigmabar");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningSigma");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningCosTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDiffsigma2");
+        if (bin) delete bin;
+
+
+        // robert ----------------------------------------------
+        bin = plist->FindObject("BinningAlphaFlux");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTimeDiff");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTime");
+        if (bin) delete bin;
+}
+
+
+
+//************************************************************************
+void ONOFFAnalysis()
+{
+      gLog.SetNoColors();
+
+      if (gRandom)
+        delete gRandom;
+      gRandom = new TRandom3(0);
+
+      //-----------------------------------------------
+      TString tag = "080000";
+
+      const char *offfile  = "*";
+
+      const char *onfile  = "*";
+
+      // Pratik
+      //const char *mcfile = "MCGamma_calibrate";
+      // Keiichi
+      const char *mcfile = "calibrated_MCdata2";
+
+      //-----------------------------------------------
+
+      // path for input for Mars
+
+     if (tag == "080000")  
+     { 
+       TString inPathON  = "/home/pcmagic14/wittek/CalibData/CrabSept2004/2004_09_21/";
+       TString inPathOFF = "/home/pcmagic14/wittek/CalibData/OffSept2004/2004_09_18/";
+       // Pratik
+       //TString inPathMC  = "/home/pcmagic21/pratik/mcdata/gamma/MCcalibrate/";
+       // Keiichi
+       TString inPathMC  = "/.magic/data21a/mase/Mars/Mars041103/DataCalibUV/";
+
+     }
+
+      // path for output from Mars
+     TString outPath = "/.magic/data21a/wittek/";
+     outPath += tag;
+     outPath += "/";
+
+      //-----------------------------------------------
+
+      //TEnv env("macros/CT1env.rc");
+      //Bool_t printEnv = kFALSE;
+
+    //************************************************************************
+
+    // Job A : 
+    //  - produce MHSigmaTheta plots for ON, OFF and MC data
+    //  - write out (or read in) these MHSigmaTheta plots
+    //  - read ON (or OFF or MC) data
+    //  - pad the events; 
+    //  - write root file for ON (or OFF or MC) data (ON1.root, ...);
+
+    Bool_t JobA    = kTRUE;  
+    Bool_t GPadON  = kFALSE;    // \  generate Pad histograms 
+    Bool_t GPadOFF = kFALSE;    //  | and write them onto disk
+    Bool_t GPadMC  = kFALSE;    // /
+    Bool_t Merge   = kFALSE;   // read the Pad histograms, merge them
+                               // and write them onto disk
+    Bool_t Wout    = kTRUE;   // \  read in merged padding histograms and
+                               //  | write out root file of padded data
+                               // /  (ON1.root, OFF1.root or MC1.root) 
+    //TString typeInput("ON");
+    TString typeInput("OFF");
+    //TString typeInput("MC");
+
+
+    // Job B_RF_UP : read ON1.root (OFF1.root or MC1.root) file 
+    //  - if CTrainRF = TRUE : create matrices of training events
+    //                         and root files of training and test events
+    //  - if RTrainRF = TRUE : read in training matrices for hadrons and gammas
+    //  - if RTree    = TRUE : read in trees, otherwise create trees
+    //  - calculate hadroness for method of RANDOM FOREST
+    //  - update the input files with the hadronesses (ON2.root, OFF2.root
+    //     or MC2.root)
+
+    Bool_t JobB_RF_UP  = kFALSE;  
+    Bool_t CTrainRF    = kFALSE;  // create  matrices of training events
+                                  // and root files of training and test events
+    Bool_t RTrainRF    = kFALSE;  // read in matrices of training events
+    Bool_t RTree       = kFALSE;  // read in trees (otherwise grow them)
+    Bool_t WRF         = kFALSE;  // update input root file ?
+
+
+    // Job B_SC_UP : read ON2.root (or MC2.root) file 
+    //  - depending on WParSC : create (or read in) supercuts parameter values
+    //  - calculate hadroness for the SUPERCUTS
+    //  - update the input files with the hadroness (==>ON3.root or MC3.root)
+
+    Bool_t JobB_SC_UP  = kFALSE;
+    Bool_t CMatrix     = kFALSE;  // create training and test matrices 
+    Bool_t RMatrix     = kFALSE;  // read training and test matrices from file
+    Bool_t WOptimize   = kFALSE;  // do optimization using the training sample
+                                  // and write supercuts parameter values 
+                                  // onto the file parSCfile
+    Bool_t RTest       = kFALSE;  // test the supercuts using the test matrix
+    Bool_t WSC         = kFALSE;  // update input root file ?
+
+
+    // Job C: 
+    //  - read ON3.root and MC3.root files
+    //    which should have been updated to contain the hadronnesses  
+    //    for the method of 
+    //              RF
+    //              SUPERCUTS and
+    //  - produce Neyman-Pearson plots
+
+    Bool_t JobC  = kFALSE;  
+
+
+    // Job D :  
+    //  - select g/h separation method XX
+    //  - read ON3 (or MC3) root file
+    //  - apply cuts in hadronness
+    //  - make plots
+
+    Bool_t JobD  = kFALSE;  
+
+
+
+    // Job E_XX : extended version of E_XX (including flux plots)  
+    //  - select g/h separation method XX
+    //  - read MC root file
+    //  - calculate eff. collection area
+    //  - optimize energy estimator
+    //  - read ON root file 
+    //  - apply final cuts
+    //  - calculate flux
+    //  - write root file for ON data after final cuts 
+
+
+    Bool_t JobE_XX  = kFALSE;  
+    Bool_t CCollArea= kFALSE;  // calculate eff. collection areas
+    Bool_t OEEst    = kFALSE;  // optimize energy estimator
+    Bool_t WEX      = kFALSE;  // update root file  ?
+    Bool_t WRobert  = kFALSE;  // write out Robert's file  ?
+
+
+
+    //************************************************************************
+
+    
+  //---------------------------------------------------------------------
+  // Job A
+  //=========
+
+    //  - produce the histograms "sigmabar versus Theta", etc. 
+    //    for ON, OFF and MC data (to be used for the padding)
+    //
+    //  - write root file of padded ON (OFF, MC) events (ON1.root, ...) 
+    //    (after the standard cuts, before the g/h separation)
+
+
+ if (JobA)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : Start of Job A" << endl;
+    gLog << "" << endl;
+    gLog << "Macro ONOFFAnalysis : JobA, GPadON, GPadOFF, GPadMC, Merge, Wout = " 
+         << (JobA    ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadON  ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadOFF ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadMC  ? "kTRUE" : "kFALSE")  << ",  " 
+         << (Merge   ? "kTRUE" : "kFALSE")  << ",  " 
+         << (Wout    ? "kTRUE" : "kFALSE")  << endl;
+    
+    //--------------------------------------------------
+
+    TString fNamePedPhotCam("MPedPhotCamFromData");
+    // for Keiichi's file
+    //TString fNamePedPhotCam("MPedPhotCam");
+
+
+    //************************************************************
+    // generate histograms to be used in the padding
+    // 
+    // read ON, OFF and MC data files
+    // generate (or read in) the padding histograms for ON, OFF and MC data
+    //
+
+    MPad pad;
+    pad.SetName("MPad");
+
+    //--------------------------------------------------
+    // names of ON and OFF files to be read
+    // for generating the histograms to be used in the padding 
+    TString fileON  = inPathON;
+    fileON += onfile;
+    fileON += ".root";
+
+    TString fileOFF = inPathOFF;
+    fileOFF += offfile;
+    fileOFF += ".root";
+
+    TString fileMC = inPathMC;
+    fileMC += mcfile;
+    fileMC += ".root";
+
+    //--------------------------------------------------
+    // name of files to contain the paddding histograms of ON, OFF and MC data
+      TString NamePadON(outPath);
+      NamePadON += "PadON";
+      NamePadON += ".root";
+
+      TString NamePadOFF(outPath);
+      NamePadOFF += "PadOFF";
+      NamePadOFF += ".root";
+
+      TString NamePadMC(outPath);
+      NamePadMC += "PadMC";
+      NamePadMC += ".root";
+
+    // name of file to conatin the merged histograms for the padding
+    TString outNameSigTh = outPath;
+    outNameSigTh += "SigmaTheta";
+    outNameSigTh += ".root";
+
+    //--------------------------------------------------
+
+    if (GPadON || GPadOFF || GPadMC)
+    {
+      // generate the padding histograms
+      gLog << "=====================================================" << endl;
+      gLog << "Start generating the padding histograms" << endl;
+
+
+    gLog << "fileON, fileOFF, fileMC = " << fileON << ",  " 
+         << fileOFF << ",  " << fileMC   << endl;
+
+
+
+    //--------------------------------------------------
+      MMakePadHistograms makepad;
+      makepad.SetMaxEvents(10000);
+      makepad.SetNamePedPhotCam(fNamePedPhotCam);
+      makepad.SetPedestalLevel(2.0);
+      makepad.SetUseInterpolation(kTRUE);
+      makepad.SetProcessPedestal(kTRUE);
+      makepad.SetProcessTime(kFALSE);
+
+      //-----------------------------------------
+      // ON events
+
+      if (GPadON)
+      {
+        makepad.SetDataType("ON");
+        makepad.SetNameInputFile(fileON);
+        makepad.SetNameOutputFile(NamePadON);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+      // OFF events
+
+      if (GPadOFF)
+      {
+        makepad.SetDataType("OFF");
+        makepad.SetNameInputFile(fileOFF);
+        makepad.SetNameOutputFile(NamePadOFF);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+      // MC events
+
+      if (GPadMC)
+      {
+        makepad.SetDataType("MC");
+        makepad.SetNameInputFile(fileMC);
+        makepad.SetNameOutputFile(NamePadMC);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+
+
+      gLog << "" << endl;
+      gLog << "End of generating the padding histograms" << endl;
+      gLog << "=====================================================" << endl;
+    }
+
+    //************************************************************
+
+    if (Merge)
+    {
+      gLog << "=====================================================" << endl;
+      gLog << "Start of merging the padding histograms" << endl;
+      gLog << "" << endl;
+
+      pad.MergeONOFFMC(NamePadON, NamePadOFF, NamePadMC, outNameSigTh);
+      //pad.MergeONOFFMC(NamePadON, "", NamePadMC, outNameSigTh);
+      //pad.MergeONOFFMC(NamePadON, NamePadOFF, "", outNameSigTh);
+      //pad.MergeONOFFMC("", NamePadOFF, NamePadMC, outNameSigTh);
+
+      gLog << "" << endl;
+      gLog << "End of merging the padding histograms" << endl;
+      gLog << "=====================================================" << endl;
+    }
+    // end of Merge
+
+
+
+    //************************************************************
+
+  if (Wout)
+  {
+    // read the target padding histograms ---------------------------
+    pad.ReadPaddingDist(outNameSigTh);
+
+
+    gLog << "=====================================================" << endl;
+    gLog << "Start the padding" << endl;
+
+    //--------------------------------------------------
+    // type of data to be padded 
+    gLog << "typeInput = " << typeInput << endl;
+
+    //-------------------------------------------
+    // name of input root file
+    if (typeInput == "ON")
+      TString filenamein(fileON);
+    else if (typeInput == "OFF")
+      TString filenamein(fileOFF);
+    else if (typeInput == "MC")
+      TString filenamein(fileMC);
+    gLog << "data to be padded : " << filenamein << endl;
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += "Hillas";
+    outNameImage += typeInput;
+    outNameImage += "1.root";
+    gLog << "padded data to be written onto : " << outNameImage << endl;
+
+    //-----------------------------------------------------------
+    pad.SetDataType(typeInput);
+    pad.SetNamePedPhotCam(fNamePedPhotCam);
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenamein);
+    read.DisableAutoScheme();
+
+    MGeomApply        apply;
+
+    // a way to find out whether one is dealing with MC :
+    //MFDataMember f1("MRawRunHeader.fRunType", '>', 255.5);  // MC
+    //f1.SetName("Select MC");
+    //MFDataMember f2("MRawRunHeader.fRunType", '<', 255.5);  // data
+    //f2.SetName("Select Data");
+
+
+
+      MBadPixelsCalc badcalc;
+      badcalc.SetNamePedPhotContainer(fNamePedPhotCam);
+      badcalc.SetPedestalLevel(2.0);
+      badcalc.SetName("BadCalc");
+
+      MBadPixelsTreat badtreat;
+      badtreat.SetNamePedPhotCam(fNamePedPhotCam);
+      badtreat.SetUseInterpolation(kTRUE);
+      badtreat.SetProcessPedestal(kTRUE);
+      badtreat.SetProcessTimes(kFALSE);
+      badtreat.SetName("BadTreat");
+
+      MFSelBasic selbasic;
+      MContinue contbasic(&selbasic);
+      contbasic.SetName("SelBasic");
+
+      MHBadPixels bad("BadPixels");
+      bad.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillbad("BadPixels[MHBadPixels]", "MBadPixelsCam");
+      fillbad.SetName("FillBad");
+
+      MHSigmaTheta sigth("SigmaTheta");
+      sigth.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillsigtheta ("SigmaTheta[MHSigmaTheta]", "");
+      fillsigtheta.SetName("FillSigTheta");    
+
+
+    MImgCleanStd    clean(3.0, 2.5);
+    //clean.SetMethod(MImgCleanStd::kDemocratic);
+    clean.SetCleanRings(3); 
+    clean.SetName("Clean");
+    clean.SetNamePedPhotCam(fNamePedPhotCam);
+
+    // calculation of  image parameters ---------------------
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImagePar(fImgParName);
+
+    MHillasSrcCalc hsrccalc("MSrcPosCam", fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+    // --------------------------------------------------
+
+    MFSelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+    selstandard.SetCuts(200, 5, 200, 0.0, 5.0, 0.1, 0.07);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+    /*  
+      MWriteRootFile write(outNameImage);
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      //write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+      //write.AddContainer("MTime",         "Events");
+      write.AddContainer("MPointingPos", "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+    */      
+
+    //*****************************
+    // entries in MParList
+    
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+    pliston.AddToList(&bad);
+    pliston.AddToList(&sigth);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+    //tliston.AddToList(&f1);
+    //tliston.AddToList(&f2);
+    tliston.AddToList(&apply);
+
+    tliston.AddToList(&badcalc);
+    tliston.AddToList(&badtreat);
+
+    tliston.AddToList(&contbasic);
+    tliston.AddToList(&pad); 
+
+    
+    tliston.AddToList(&fillbad);
+    tliston.AddToList(&fillsigtheta);
+    tliston.AddToList(&clean);
+
+    tliston.AddToList(&hcalc);
+    tliston.AddToList(&hsrccalc);
+
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contstandard);
+    //tliston.AddToList(&write);
+    
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //  evtloop.Write();
+
+    //Int_t maxevents = -1;
+    Int_t maxevents = 2000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+
+    pliston.FindObject("SigmaTheta", "MHSigmaTheta")->DrawClone();
+    pliston.FindObject("BadPixels",  "MHBadPixels")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    //DeleteBinnings(&pliston);
+
+      gLog << "End of padding" << endl;
+      gLog << "=====================================================" << endl;
+  }  
+
+
+    gLog << "Macro ONOFFAnalysis : End of Job A" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+
+
+
+
+  //---------------------------------------------------------------------
+  // Job B_RF_UP
+  //============
+
+
+    //  - create (or read in) the matrices of training events for gammas 
+    //    and hadrons
+    //  - create (or read in) the trees
+    //  - then read ON1.root (or MC1.root) file 
+    //  - calculate the hadroness for the method of RANDOM FOREST
+    //  - update input root file with the hadroness
+
+
+ if (JobB_RF_UP)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : Start of Job B_RF_UP" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONOFFAnalysis : JobB_RF_UP, RTrainRF, CTrainRF, RTree, WRF = "
+         << (JobB_RF_UP ? "kTRUE" : "kFALSE")  << ",  " 
+         << (RTrainRF ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (CTrainRF ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (RTree ?      "kTRUE" : "kFALSE")  << ",  "
+         << (WRF ?        "kTRUE" : "kFALSE")  << endl;
+
+
+    //--------------------------------------------
+    // parameters for the random forest
+    Int_t NumTrees = 100;
+    Int_t NumTry   =   3;
+    Int_t NdSize   =   1;
+
+
+    TString hadRFName = "HadRF";
+    Float_t maxhadronness =  0.23;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+    TString extin  = "1.root";
+    TString extout = "2.root";
+
+    //--------------------------------------------
+    // for the analysis using ON data only set typeMatrixHadrons = "ON"
+    //                        ON and OFF data                    = "OFF"
+    TString typeMatrixHadrons = "OFF";
+    gLog << "typeMatrixHadrons = " << typeMatrixHadrons << endl;
+
+
+    // file to be updated (ON, OFF or MC)
+
+    //TString typeInput = "ON";
+    TString typeInput = "OFF";
+    //TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+    // name of input root file
+    TString NameData = outPath;
+    NameData += typeInput;
+    TString inNameData(NameData);
+    inNameData += extin;
+    gLog << "inNameData = " << inNameData << endl; 
+
+    // name of output root file
+    TString outNameData(NameData);
+    outNameData += extout;
+    gLog << "outNameData = " << outNameData << endl; 
+
+    //--------------------------------------------
+    // files to be read for generating 
+    //    - the matrices of training events
+    //    - and the root files of training and test events
+
+
+    // "hadrons" :
+    TString filenameHad = outPath;
+    filenameHad += typeMatrixHadrons;
+    filenameHad += extin;
+    Int_t howManyHadronsTrain = 12000;
+    Int_t howManyHadronsTest  = 12000;
+    gLog << "filenameHad = "    << filenameHad << ",   howManyHadronsTrain = "
+         << howManyHadronsTrain << ",   howManyHadronsTest = "
+         << howManyHadronsTest  << endl; 
+    
+
+    // "gammas" :
+    TString filenameMC = outPath;
+    filenameMC += "MC";
+    filenameMC += extin;
+    Int_t howManyGammasTrain = 12000;
+    Int_t howManyGammasTest  = 12000;
+    gLog << "filenameMC = "    << filenameMC << ",   howManyGammasTrain = "
+         << howManyGammasTrain << ",   howManyGammasTest = "
+         << howManyGammasTest  << endl; 
+    
+    //--------------------------------------------
+    // files for the matrices of training events 
+
+    TString NameGammas = outPath;
+    NameGammas += "RFmatrix_gammas_Train_";
+    NameGammas += "MC";
+    NameGammas += extin;
+
+    TString NameHadrons = outPath;
+    NameHadrons += "RFmatrix_hadrons_Train_";
+    NameHadrons += typeMatrixHadrons;
+    NameHadrons += extin;
+
+
+    //--------------------------------------------
+    // root files for the training events 
+
+    TString NameGammasTrain = outPath;
+    NameGammasTrain += "RF_gammas_Train_";
+    NameGammasTrain += "MC";
+    TString inNameGammasTrain(NameGammasTrain);    
+    inNameGammasTrain += extin;
+    TString outNameGammasTrain(NameGammasTrain);    
+    outNameGammasTrain += extout;
+
+
+    TString NameHadronsTrain = outPath;
+    NameHadronsTrain += "RF_hadrons_Train_";
+    NameHadronsTrain += typeMatrixHadrons;
+    TString inNameHadronsTrain(NameHadronsTrain);    
+    inNameHadronsTrain += extin;
+    TString outNameHadronsTrain(NameHadronsTrain);    
+    outNameHadronsTrain += extout;
+
+
+    //--------------------------------------------
+    // root files for the test events 
+
+    TString NameGammasTest = outPath;
+    NameGammasTest += "RF_gammas_Test_";
+    NameGammasTest += "MC";
+    TString inNameGammasTest(NameGammasTest);    
+    inNameGammasTest += extin;
+    TString outNameGammasTest(NameGammasTest);    
+    outNameGammasTest += extout;
+
+    TString NameHadronsTest = outPath;
+    NameHadronsTest += "RF_hadrons_Test_";
+    NameHadronsTest += typeMatrixHadrons;
+    TString inNameHadronsTest(NameHadronsTest);    
+    inNameHadronsTest += extin;
+    TString outNameHadronsTest(NameHadronsTest);    
+    outNameHadronsTest += extout;
+
+    //--------------------------------------------------------------------
+
+
+    MHMatrix matrixg("MatrixGammas");
+    matrixg.EnableGraphicalOutput();
+
+    matrixg.AddColumn("cos((MPointingPos.fZd)/kRad2Deg)");
+    matrixg.AddColumn("MSigmabar.fSigmabar");
+    matrixg.AddColumn("log10(MHillas.fSize)");
+    matrixg.AddColumn("MHillasSrc.fDist");
+    matrixg.AddColumn("MHillas.fWidth");
+    matrixg.AddColumn("MHillas.fLength");
+    matrixg.AddColumn("log10(MHillas.fSize/(MHillas.fWidth*MHillas.fLength))");
+    matrixg.AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    matrixg.AddColumn("MNewImagePar.fConc");
+    matrixg.AddColumn("MNewImagePar.fLeakage1");
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.EnableGraphicalOutput();
+
+    matrixh.AddColumns(matrixg.GetColumns());
+
+    //--------------------------------------------
+    // file of trees of the random forest 
+
+    TString outRF = outPath;
+    outRF += "RF.root";
+
+
+   //*************************************************************************
+   // read in matrices of training events
+if (RTrainRF)
+  {
+    const char* mtxName = "MatrixGammas";
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Get matrix for (gammas)" << endl;
+    gLog << "matrix name        = " << mtxName << endl;
+    gLog << "name of root file  = " << NameGammas << endl;
+    gLog << "" << endl;
+
+
+    // read in the object with the name 'mtxName' from file 'NameGammas'
+    //
+    TFile fileg(NameGammas); 
+
+    matrixg.Read(mtxName);
+    matrixg.Print("SizeCols");
+
+
+    //***************************************************************** 
+
+    const char* mtxName = "MatrixHadrons";
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << " Get matrix for (hadrons)" << endl;
+    gLog << "matrix name        = " << mtxName << endl;
+    gLog << "name of root file  = " << NameHadrons << endl;
+    gLog << "" << endl;
+
+
+    // read in the object with the name 'mtxName' from file 'NameHadrons'
+    //
+    TFile fileh(NameHadrons); 
+
+    matrixh.Read(mtxName);
+    matrixh.Print("SizeCols");
+  }
+
+
+   //*************************************************************************
+   // create matrices of training events
+   // and root files of training and test events
+ 
+if (CTrainRF)
+  {
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << " Create matrices of training events and root files of training and test events" 
+         << endl;
+    gLog << " Gammas :" << endl;
+    gLog << "---------" << endl;
+
+    MParList  plistg;
+    MTaskList tlistg;
+
+    MReadMarsFile  readg("Events", filenameMC);
+    readg.DisableAutoScheme();
+
+    TString mgname("costhg");
+    MBinning bing("Binning"+mgname);
+    bing.SetEdges(10, 0., 1.0);
+
+    MH3 gref("cos((MPointingPos.fZd)/kRad2Deg)");
+    gref.SetName(mgname);
+    MH::SetBinning(&gref.GetHist(), &bing);
+    //for (Int_t i=1; i<=gref.GetNbins(); i++)
+    //  gref.GetHist().SetBinContent(i, 1.0);
+
+    MFEventSelector2 selectorg(gref);
+    selectorg.SetNumMax(howManyGammasTrain+howManyGammasTest);
+    selectorg.SetName("selectGammasTrainTest");
+    selectorg.SetInverted();
+    //selectorg.SetUseOrigDistribution(kTRUE);
+
+    MContinue contg(&selectorg);
+    contg.SetName("ContGammas");
+
+    Double_t probg = ( (Double_t) howManyGammasTrain )
+                   / ( (Double_t)(howManyGammasTrain+howManyGammasTest) );
+    MFRandomSplit splitg(probg);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&splitg);
+    fillmatg.SetName("fillGammas");
+
+    //-----------------------
+    // for writing the root files of training and test events
+    // for gammas
+    
+    MWriteRootFile writetraing(inNameGammasTrain, "RECREATE");
+    writetraing.SetName("WriteGammasTrain");
+    writetraing.SetFilter(&splitg);
+
+      writetraing.AddContainer("MRawRunHeader", "RunHeaders");
+      writetraing.AddContainer("MTime",         "Events");
+      writetraing.AddContainer("MPointingPos",  "Events");
+      writetraing.AddContainer("ThetaOrig",     "Events");
+      writetraing.AddContainer("MSrcPosCam",    "Events");
+      writetraing.AddContainer("MSigmabar",     "Events");
+      writetraing.AddContainer("MHillas",       "Events");
+      writetraing.AddContainer("MHillasExt",    "Events");
+      writetraing.AddContainer("MHillasSrc",    "Events");
+      writetraing.AddContainer("MNewImagePar",  "Events");
+
+    MContinue contgtrain(&splitg);
+    contgtrain.SetName("ContGammaTrain");
+
+    MWriteRootFile writetestg(inNameGammasTest, "RECREATE");
+    writetestg.SetName("WriteGammasTest");
+
+      writetestg.AddContainer("MRawRunHeader", "RunHeaders");
+      writetestg.AddContainer("MTime",         "Events");
+      writetestg.AddContainer("MPointingPos",  "Events");
+      writetestg.AddContainer("ThetaOrig",     "Events");
+      writetestg.AddContainer("MSrcPosCam",    "Events");
+      writetestg.AddContainer("MSigmabar",     "Events");
+      writetestg.AddContainer("MHillas",       "Events");
+      writetestg.AddContainer("MHillasExt",    "Events");
+      writetestg.AddContainer("MHillasSrc",    "Events");
+      writetestg.AddContainer("MNewImagePar",  "Events");
+
+    //-----------------------
+    
+    //*****************************   fill gammas   ***  
+    // entries in MParList
+    
+    plistg.AddToList(&tlistg);
+    InitBinnings(&plistg);
+
+    plistg.AddToList(&matrixg);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tlistg.AddToList(&readg);
+    tlistg.AddToList(&contg);
+
+    tlistg.AddToList(&splitg);
+    tlistg.AddToList(&fillmatg);
+    tlistg.AddToList(&writetraing);
+    tlistg.AddToList(&contgtrain);
+
+    tlistg.AddToList(&writetestg);
+
+    //*****************************
+
+    MProgressBar matrixbar;
+    MEvtLoop evtloopg;
+    evtloopg.SetName("FillGammaMatrix");
+    evtloopg.SetParList(&plistg);
+    //evtloopg.ReadEnv(env, "", printEnv);
+    evtloopg.SetProgressBar(&matrixbar);
+
+    Int_t maxevents = -1;
+    if (!evtloopg.Eventloop(maxevents))
+        return;
+
+    tlistg.PrintStatistics(0, kTRUE);
+
+    matrixg.Print("SizeCols");
+    Int_t generatedgTrain = matrixg.GetM().GetNrows();
+    if ( fabs(generatedgTrain-howManyGammasTrain) > 
+                                    3.0*sqrt(howManyGammasTrain) )
+    {
+      gLog << "ONOFFAnalysis.C : no.of generated gamma training events (" 
+           << generatedgTrain << ") is incompatible with the no.of requested events (" 
+           << howManyGammasTrain << ")" << endl;   
+    }
+
+
+    Int_t generatedgTest = writetestg.GetNumExecutions();
+    if ( fabs(generatedgTest-howManyGammasTest) > 
+                                    3.0*sqrt(howManyGammasTest) )
+    {
+      gLog << "ONOFFAnalysis.C : no.of generated gamma test events (" 
+           << generatedgTest << ") is incompatible with the no.of requested events (" 
+           << howManyGammasTest << ")" << endl;   
+    }
+
+    //*****************************   fill hadrons   ***  
+    gLog << "---------------------------------------------------------------"
+         << endl;
+    gLog << " Hadrons :" << endl;
+    gLog << "----------" << endl;
+
+    MParList  plisth;
+    MTaskList tlisth;
+
+    MReadMarsFile  readh("Events", filenameHad);
+    readh.DisableAutoScheme();
+
+    TString mhname("costhh");
+    MBinning binh("Binning"+mhname);
+    binh.SetEdges(10, 0., 1.0);
+
+    //MH3 href("cos((MPointingPos.fZd)/kRad2Deg)");
+    //href.SetName(mhname);
+    //MH::SetBinning(&href.GetHist(), &binh);
+    //for (Int_t i=1; i<=href.GetNbins(); i++)
+    //  href.GetHist().SetBinContent(i, 1.0);
+
+    //use the original distribution from the gammas
+    MH3 &href = *(selectorg.GetHistOrig());
+
+    MFEventSelector2 selectorh(href);
+    selectorh.SetNumMax(howManyHadronsTrain+howManyHadronsTest);
+    selectorh.SetName("selectHadronsTrainTest");
+    selectorh.SetInverted();
+
+    MContinue conth(&selectorh);
+    conth.SetName("ContHadrons");
+
+    Double_t probh = ( (Double_t) howManyHadronsTrain )
+                   / ( (Double_t)(howManyHadronsTrain+howManyHadronsTest) );
+    MFRandomSplit splith(probh);
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&splith);
+    fillmath.SetName("fillHadrons");
+
+    //-----------------------
+    // for writing the root files of training and test events
+    // for hadrons
+    
+    MWriteRootFile writetrainh(inNameHadronsTrain, "RECREATE");
+    writetrainh.SetName("WriteHadronsTrain");
+    writetrainh.SetFilter(&splith);
+
+      writetrainh.AddContainer("MRawRunHeader", "RunHeaders");
+      writetrainh.AddContainer("MTime",         "Events");
+      writetrainh.AddContainer("MPointingPos",  "Events");
+      writetrainh.AddContainer("ThetaOrig",     "Events");
+      writetrainh.AddContainer("MSrcPosCam",    "Events");
+      writetrainh.AddContainer("MSigmabar",     "Events");
+      writetrainh.AddContainer("MHillas",       "Events");
+      writetrainh.AddContainer("MHillasExt",    "Events");
+      writetrainh.AddContainer("MHillasSrc",    "Events");
+      writetrainh.AddContainer("MNewImagePar",  "Events");
+
+    MContinue conthtrain(&splith);
+
+    MWriteRootFile writetesth(inNameHadronsTest, "RECREATE");
+    writetesth.SetName("WriteHadronsTest");
+
+      writetesth.AddContainer("MRawRunHeader", "RunHeaders");
+      writetesth.AddContainer("MTime",         "Events");
+      writetesth.AddContainer("MPointingPos",  "Events");
+      writetesth.AddContainer("ThetaOrig",     "Events");
+      writetesth.AddContainer("MSrcPosCam",    "Events");
+      writetesth.AddContainer("MSigmabar",     "Events");
+      writetesth.AddContainer("MHillas",       "Events");
+      writetesth.AddContainer("MHillasExt",    "Events");
+      writetesth.AddContainer("MHillasSrc",    "Events");
+      writetesth.AddContainer("MNewImagePar",  "Events");
+
+
+    //*****************************  
+    // entries in MParList
+    
+    plisth.AddToList(&tlisth);
+    InitBinnings(&plisth);
+
+    plisth.AddToList(&matrixh);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tlisth.AddToList(&readh);
+    tlisth.AddToList(&conth);
+
+    tlisth.AddToList(&splith);
+    tlisth.AddToList(&fillmath);
+    tlisth.AddToList(&writetrainh);
+    tlisth.AddToList(&conthtrain);
+
+    tlisth.AddToList(&writetesth);
+
+    //*****************************
+
+    MProgressBar matrixbar;
+    MEvtLoop evtlooph;
+    evtlooph.SetName("FillHadronMatrix");
+    evtlooph.SetParList(&plisth);
+    //evtlooph.ReadEnv(env, "", printEnv);
+    evtlooph.SetProgressBar(&matrixbar);
+
+    Int_t maxevents = -1;
+    if (!evtlooph.Eventloop(maxevents))
+        return;
+
+    tlisth.PrintStatistics(0, kTRUE);
+
+    matrixh.Print("SizeCols");
+    Int_t generatedhTrain = matrixh.GetM().GetNrows();
+    if ( fabs(generatedhTrain-howManyHadronsTrain) > 
+                                    3.0*sqrt(howManyHadronsTrain) )
+    {
+      gLog << "ONOFFAnalysis.C : no.of generated hadron training events (" 
+           << generatedhTrain << ") is incompatible with the no.of requested events (" 
+           << howManyHadronsTrain << ")" << endl;   
+    }
+
+
+    Int_t generatedhTest = writetesth.GetNumExecutions();
+    if ( fabs(generatedhTest-howManyHadronsTest) > 
+                                    3.0*sqrt(howManyHadronsTest) )
+    {
+      gLog << "ONOFFAnalysis.C : no.of generated gamma test events (" 
+           << generatedhTest << ") is incompatible with the no.of requested events (" 
+           << howManyHadronsTest << ")" << endl;   
+    }
+
+
+    //*****************************************************  
+
+
+    // write out matrices of training events 
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Write out matrices of training events" << endl;
+
+
+      //-------------------------------------------
+      // "gammas"
+      gLog << "Gammas :" << endl;    
+      matrixg.Print("SizeCols");
+
+      TFile writeg(NameGammas, "RECREATE", "");
+      matrixg.Write();
+
+      gLog << "" << endl;
+      gLog << "Macro ONOFFAnalysis : matrix of training events for gammas written onto file "
+           << NameGammas << endl;
+
+      //-------------------------------------------
+      // "hadrons"
+      gLog << "Hadrons :" << endl;    
+      matrixh.Print("SizeCols");
+
+      TFile writeh(NameHadrons, "RECREATE", "");
+      matrixh.Write();
+
+      gLog << "" << endl;
+      gLog << "Macro ONOFFAnalysis : matrix of training events for hadrons written onto file "
+           << NameHadrons << endl;
+
+  }
+   //**********   end of creating matrices of training events   ***********
+
+
+    MRanForest *fRanForest;
+    MRanTree *fRanTree;
+    //-----------------------------------------------------------------
+    // read in the trees of the random forest 
+    if (RTree)
+    {
+      MParList plisttr;
+      MTaskList tlisttr;
+      plisttr.AddToList(&tlisttr);
+
+      MReadTree readtr("TREE", outRF);
+      readtr.DisableAutoScheme();
+
+      MRanForestFill rffill;
+      rffill.SetNumTrees(NumTrees);
+
+      // list of tasks for the loop over the trees
+
+      tlisttr.AddToList(&readtr);
+      tlisttr.AddToList(&rffill);
+
+      //-------------------
+      // Execute tree loop
+      //
+      MEvtLoop evtlooptr;
+      evtlooptr.SetName("ReadRFTrees");
+      evtlooptr.SetParList(&plisttr);
+      if (!evtlooptr.Eventloop())
+        return;
+
+      tlisttr.PrintStatistics(0, kTRUE);
+
+      gLog << "ONOFFAnalysis : RF trees were read in from file "
+           << outRF << endl;
+
+    // get adresses of objects which are used in the next eventloop
+    fRanForest = (MRanForest*)plisttr->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        gLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plisttr->FindObject("MRanTree");
+    if (!fRanTree)                                  
+    {                                                                          
+        gLog << err << dbginf << "MRanTree not found... aborting." << endl;    
+        return kFALSE;
+    }
+
+    }
+
+    //-----------------------------------------------------------------
+    // grow the trees of the random forest (event loop = tree loop)
+
+    if (!RTree)
+    {
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : start growing trees" << endl;
+
+    MTaskList tlist2;
+    MParList plist2;
+    plist2.AddToList(&tlist2);
+
+    plist2.AddToList(&matrixg);
+    plist2.AddToList(&matrixh);
+
+    MRanForestGrow rfgrow2;
+    rfgrow2.SetNumTrees(NumTrees);
+    rfgrow2.SetNumTry(NumTry);
+    rfgrow2.SetNdSize(NdSize);
+
+    MWriteRootFile rfwrite2(outRF);
+    rfwrite2.AddContainer("MRanTree", "TREE");
+
+    MFillH fillh2("MHRanForestGini");
+
+    // list of tasks for the loop over the trees
+    
+    tlist2.AddToList(&rfgrow2);
+    tlist2.AddToList(&rfwrite2);
+    tlist2.AddToList(&fillh2);
+
+    //-------------------
+    // Execute tree loop
+    //
+    MEvtLoop treeloop;
+    treeloop.SetName("GrowRFTrees");
+    treeloop.SetParList(&plist2);
+
+    if ( !treeloop.Eventloop() )
+        return;
+
+    tlist2.PrintStatistics(0, kTRUE);
+
+    plist2.FindObject("MHRanForestGini")->DrawClone();
+
+
+    // get adresses of objects which are used in the next eventloop
+    fRanForest = (MRanForest*)plist2->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        gLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plist2->FindObject("MRanTree");
+    if (!fRanTree)                                  
+    {                                                                          
+        gLog << err << dbginf << "MRanTree not found... aborting." << endl;    
+        return kFALSE;
+    }
+
+    }
+    // end of growing the trees of the random forest
+    //-----------------------------------------------------------------
+
+
+    //-----------------------------------------------------------------
+    // Update the root files with the RF hadronness
+    //
+
+ if (WRF)
+  {
+    //TString fileName(inNameHadronsTrain);
+    //TString outName(outNameHadronsTrain);
+
+    //TString fileName(inNameHadronsTest);
+    //TString outName(outNameHadronsTest);
+
+    //TString fileName(inNameGammasTrain);
+    //TString outName(outNameGammasTrain);
+
+    //TString fileName(inNameGammasTest);
+    //TString outName(outNameGammasTest);
+
+    TString fileName(inNameData);
+    TString outName(outNameData);
+
+
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Update root file '" <<  fileName 
+         << "' with the RF hadronness; ==> " << outName << endl;
+
+   
+    MTaskList tliston;
+    MParList pliston;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", fileName);
+    read.DisableAutoScheme();
+
+
+    //.......................................................................
+    // calculate hadronnes for method of RANDOM FOREST
+
+
+    MRanForestCalc rfcalc;
+    rfcalc.SetHadronnessName(hadRFName);
+
+
+    //.......................................................................
+
+      //MWriteRootFile write(outName, "UPDATE");
+      MWriteRootFile write(outName, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MPointingPos",  "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      write.AddContainer(hadRFName,       "Events");
+
+    //-----------------------------------------------------------------
+
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadRFName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillranfor("MHRanForest");
+    fillranfor.SetName("HRanForest");
+
+    MFillH fillhadrf("hadRF[MHHadronness]", hadRFName);
+    fillhadrf.SetName("HhadRF");
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadRFName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(fRanForest);
+    pliston.AddToList(fRanTree);
+
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&rfcalc);
+    tliston.AddToList(&fillranfor);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&write);
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetName("UpdateRootFile");
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+    pliston.FindObject("MHRanForest")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->Print();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+     //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-macro");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << fileName << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+
+    DeleteBinnings(&pliston);
+  }
+
+    gLog << "Macro ONOFFAnalysis : End of Job B_RF_UP" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+  //---------------------------------------------------------------------
+  // Job B_SC_UP
+  //============
+
+    //  - create (or read in) optimum supercuts parameter values
+    //
+    //  - calculate the hadroness for the supercuts
+    //
+    //  - update input root file, including the hadroness
+
+
+ if (JobB_SC_UP)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : Start of Job B_SC_UP" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONOFFAnalysis : JobB_SC_UP, CMatrix, RMatrix, WOptimize, RTest, WSC = "
+         << (JobB_SC_UP ? "kTRUE" : "kFALSE")  << ",  " 
+         << (CMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (RMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (WOptimize  ? "kTRUE" : "kFALSE")  << ",  "
+         << (RTest      ? "kTRUE" : "kFALSE")  << ",  "
+         << (WSC        ? "kTRUE" : "kFALSE")  << endl;
+
+
+    //--------------------------------------------
+    // file which contains the initial parameter values for the supercuts 
+    // if parSCinit ="" the initial values are taken from the constructor of
+    //                  MSupercuts
+
+    TString parSCinit = outPath;
+    //parSCinit += "parSC_060204";
+    //parSCinit = "parSC_240204a";
+    parSCinit = "";
+
+    if (parSCinit != "")
+    {
+      gLog << "Initial values of parameters are taken from file '" 
+           << parSCinit << "'" << endl;
+    }
+    else
+    {
+      gLog << "Initial values of parameters are taken from the constructor of MSupercuts" 
+           << endl;
+    }
+
+
+    //---------------
+    // file onto which the optimal parameter values for the supercuts 
+    // are written
+
+    TString parSCfile = outPath;
+    parSCfile += "parSC_050304a";
+
+    gLog << "parSCfile = " << parSCfile << endl;
+
+    //--------------------------------------------
+    // file to be updated (either ON or MC)
+
+    TString typeInput = "ON";
+    //TString typeInput = "OFF";
+    //TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+    if (typeInput == "ON")
+      TString file(onfile);
+    else if (typeInput == "OFF")
+      TString file(offfile);
+    else if (typeInput == "MC")
+      TString file(mcfile);
+
+    // name of input root file
+    TString filenameData = outPath;
+    filenameData += file;
+    filenameData += "Hillas";
+    filenameData += typeInput;
+    filenameData += "1c.root";
+    gLog << "filenameData = " << filenameData << endl; 
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += file;
+    outNameImage += "Hillas";
+    outNameImage += typeInput;
+    outNameImage += "2c.root";
+    
+
+    //TString outNameImage = filenameData;
+
+    gLog << "outNameImage = " << outNameImage << endl; 
+
+    //--------------------------------------------
+    // files to be read for optimizing the supercuts
+    // 
+    // for the training
+    TString filenameTrain = outPath;
+    filenameTrain += onfile;
+    filenameTrain += "Hillas";
+    filenameTrain += typeInput;
+    filenameTrain += "1.root";
+    Int_t howManyTrain = 20000;
+    gLog << "filenameTrain = " << filenameTrain << ",   howManyTrain = "
+         << howManyTrain  << endl; 
+
+    // for testing
+    TString filenameTest = outPath;
+    filenameTest += onfile;
+    filenameTest += "Hillas";
+    filenameTest += typeInput;
+    filenameTest += "1.root";
+    Int_t howManyTest = 20000;
+
+    gLog << "filenameTest = " << filenameTest << ",   howManyTest = "
+         << howManyTest  << endl; 
+    
+
+    //--------------------------------------------
+    // files to contain the matrices (generated from filenameTrain and
+    //                                               filenameTest)
+    // 
+    // for the training
+    TString fileMatrixTrain = outPath;
+    fileMatrixTrain += "MatrixTrainSC";
+    fileMatrixTrain += ".root";
+    gLog << "fileMatrixTrain = " << fileMatrixTrain << endl; 
+
+    // for testing
+    TString fileMatrixTest = outPath;
+    fileMatrixTest += "MatrixTestSC";
+    fileMatrixTest += ".root";
+    gLog << "fileMatrixTest = " << fileMatrixTest << endl; 
+
+    
+
+    //---------------------------------------------------------------------
+    // Training and test matrices :
+    // - either create them and write them onto a file
+    // - or read them from a file
+
+
+    MFindSupercuts findsuper;
+    findsuper.SetFilenameParam(parSCfile);
+    findsuper.SetHadronnessName("HadSC");
+    //findsuper.SetUseOrigDistribution(kTRUE);
+
+    //--------------------------
+    // create matrices and write them onto files 
+    if (CMatrix)
+    {
+      TString mname("costheta");
+      MBinning bin("Binning"+mname);
+      bin.SetEdges(10, 0., 1.0);
+
+      MH3 mh3("cos((MPointingPos.fZd)/kRad2Deg)");
+      mh3.SetName(mname);
+      MH::SetBinning(&mh3.GetHist(), &bin);
+      //for (Int_t i=1; i<=mh3.GetNbins(); i++)
+      //  mh3.GetHist().SetBinContent(i, 1.0);
+
+
+      if (filenameTrain == filenameTest)
+      {
+        if ( !findsuper.DefineTrainTestMatrix(
+                              filenameTrain,   mh3, 
+                              howManyTrain,    howManyTest,  
+                              fileMatrixTrain, fileMatrixTest)     )
+        {
+          *fLog << "MagicAnalysis.C : DefineTrainTestMatrix failed" << endl;
+          return;
+        }
+
+      }
+      else
+      {
+        if ( !findsuper.DefineTrainMatrix(filenameTrain, mh3,
+                                          howManyTrain,  fileMatrixTrain) )
+        {
+          *fLog << "MagicAnalysis.C : DefineTrainMatrix failed" << endl;
+          return;
+        }
+
+	if ( !findsuper.DefineTestMatrix( filenameTest, mh3, 
+                                          howManyTest,  fileMatrixTest)  )
+        {
+          *fLog << "MagicAnalysis.C : DefineTestMatrix failed" << endl;
+          return;
+        }
+      }
+     }
+
+    //--------------------------
+    // read matrices from files
+    //                              
+
+    if (RMatrix)
+      findsuper.ReadMatrix(fileMatrixTrain, fileMatrixTest);
+    //--------------------------
+
+
+
+    //---------------------------------------------------------------------
+    // optimize supercuts using the training sample
+    // 
+    // the initial values are taken 
+    //     - from the file parSCinit (if != "")
+    //     - or from the arrays params and steps (if their sizes are != 0)
+    //     - or from the MSupercuts constructor
+
+
+if (WOptimize)
+  {
+    gLog << "MagicAnalysis.C : optimize the supercuts using the training matrix" 
+         << endl;
+
+    TArrayD params(0);
+    TArrayD steps(0);
+  
+
+    if (parSCinit == "")
+    {
+      /*
+      Double_t vparams[104] = {
+      // LengthUp
+	0.2,       0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // LengthLo
+        0.,        0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // WidthUp
+        0.1,       0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // WidthLo
+        0.,        0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // DistUp
+        0.,        0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // DistLo
+        0.,        0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // AsymUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp
+	13.12344,  0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+      Double_t vsteps[104] = {
+      // LengthUp
+	0.02,      0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // LengthLo
+        0.,        0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // WidthUp
+        0.01,      0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // WidthLo
+        0.,        0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // DistUp
+        0.,        0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // DistLo
+        0.,        0.,       0.,       0.,        0.,        0.0,
+	0.,        0.,
+      // AsymUp
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp
+	0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+      */
+
+
+      Double_t vparams[104] = {
+      // LengthUp
+	0.315585,  0.001455, 0.203198, 0.005532, -0.001670, -0.020362,
+	0.007388, -0.013463,
+      // LengthLo
+        0.151530,  0.028323, 0.510707, 0.053089,  0.013708,  2.357993,
+	0.000080, -0.007157,
+      // WidthUp
+        0.145412, -0.001771, 0.054462, 0.022280, -0.009893,  0.056353,
+        0.020711, -0.016703,
+      // WidthLo
+        0.089187, -0.006430, 0.074442, 0.003738, -0.004256, -0.014101,
+        0.006126, -0.002849,
+      // DistUp
+        1.787943,  0.0,      2.942310, 0.199815,  0.0,       0.249909,
+        0.189697,  0.0,
+      // DistLo
+        0.589406,  0.0,     -0.083964,-0.007975,  0.0,       0.045374,
+       -0.001750,  0.0,
+      // AsymUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp
+	13.12344,  0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+      Double_t vsteps[104] = {
+      // LengthUp
+        0.03,      0.0002,   0.02,     0.0006,    0.0002,    0.002,
+        0.0008,    0.002,
+      // LengthLo
+        0.02,      0.003,    0.05,     0.006,     0.002,     0.3,
+        0.0001,    0.0008,
+      // WidthUp
+        0.02,      0.0002,   0.006,    0.003,     0.002,     0.006,
+        0.002,     0.002,
+      // WidthLo
+        0.009,     0.0007,   0.008,    0.0004,    0.0005,    0.002,
+        0.0007,    0.003,
+      // DistUp
+        0.2,       0.0,      0.3,      0.02,      0.0,       0.03,
+        0.02,      0.0
+      // DistLo
+        0.06,      0.0,      0.009,    0.0008,    0.0,       0.005,
+        0.0002,    0.0
+      // AsymUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+ 
+      params.Set(104, vparams);
+      steps.Set (104, vsteps );
+    }
+
+    Bool_t rf;
+    rf = findsuper.FindParams(parSCinit, params, steps);
+
+    if (!rf) 
+    {
+       gLog << "MagicAnalysis.C : optimization of supercuts failed" << endl;
+       return;
+    }
+  }
+
+    //--------------------------------------
+    // test the supercuts on the test sample
+    //    
+
+ if (RTest)
+ {
+    gLog << "MagicAnalysis.C : test the supercuts on the test matrix" << endl;
+    Bool_t rt = findsuper.TestParams();
+    if (!rt) 
+    {
+       gLog << "MagicAnalysis.C : test of supercuts on the test matrix failed" 
+            << endl;
+    }
+
+ }
+
+
+    //-----------------------------------------------------------------
+    // Update the input files with the SC hadronness
+    //
+
+ if (WSC)
+ {
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Update input file '" <<  filenameData 
+         << "' with the SC hadronness" << endl;
+
+
+    //----------------------------------------------------
+    // read in optimum parameter values for the supercuts
+
+    TFile inparam(parSCfile);
+    MSupercuts scin;
+    scin.Read("MSupercuts");
+    inparam.Close();
+
+    gLog << "Parameter values for supercuts were read in from file '"
+         << parSCfile << "'" << endl;
+
+    TArrayD supercutsPar;
+    supercutsPar =  scin.GetParameters();
+
+    TArrayD supercutsStep;
+    supercutsStep =  scin.GetStepsizes();
+
+    gLog << "Parameter values for supercuts : " << endl;
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+    {
+      gLog << supercutsPar[i] << ",  ";
+    }
+    gLog << endl;
+
+    gLog << "Step values for supercuts : " << endl;
+    for (Int_t i=0; i<supercutsStep.GetSize(); i++)
+    {
+      gLog << supercutsStep[i] << ",  ";
+    }
+    gLog << endl;
+
+
+    //----------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    // set the parameters of the supercuts
+    MSupercuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+    gLog << "parameter values for the supercuts used for updating the input file ' " 
+         << filenameData << "'" << endl;
+    supercutsPar = supercuts.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+    {
+      gLog << supercutsPar[i] << ",  ";
+    }
+    gLog << endl;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+    //.......................................................................
+    // calculation of hadroness for the supercuts
+    // (=0.25 if fullfilled, =0.75 otherwise)
+
+    TString hadSCName = "HadSC";
+    MSupercutsCalc sccalc(fHilName, fHilNameSrc);
+    sccalc.SetHadronnessName(hadSCName);
+
+
+    //.......................................................................
+
+
+      //MWriteRootFile write(outNameImage, "UPDATE");
+      //MWriteRootFile write = new MWriteRootFile(outNameImage, "RECREATE");
+
+    
+      MWriteRootFile write(outNameImage, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MPointingPos",  "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      //write.AddContainer("HadRF",         "Events");
+      write.AddContainer(hadSCName,       "Events");
+    
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    Float_t maxhadronness =  0.40;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadSCName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillhadsc("hadSC[MHHadronness]", hadSCName);
+    fillhadsc.SetName("HhadSC");
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadSCName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+
+    TH1  &alphahist = alphaabs->GetHist();
+
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(&supercuts);
+
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&sccalc);
+    tliston.AddToList(&fillhadsc);
+
+    tliston.AddToList(&write);
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+     //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-macro");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << filenameData << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+    DeleteBinnings(&pliston);
+ }
+
+
+    gLog << "Macro ONOFFAnalysis : End of Job B_SC_UP" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+
+  //---------------------------------------------------------------------
+  // Job C  
+  //======
+
+    //  - read ON1 and MC1 data files  
+    //    which should have been updated to contain the hadronnesses
+    //    for the method of Random Forest and for the SUPERCUTS
+    //  - produce Neyman-Pearson plots
+ 
+ if (JobC)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : Start of Job C" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONOFFAnalysis : JobC = " 
+         << (JobC ? "kTRUE" : "kFALSE")  << endl;
+
+
+
+    TString ext("2.root");
+    TString extout("2.root");
+
+    TString typeHadrons("OFF");
+    TString typeGammas("MC");
+
+    //--------------------------------------------
+    // name of input data file
+    TString NameData = outPath;
+    NameData += typeHadrons;
+    TString inNameData(NameData);
+    inNameData += ext;
+    gLog << "inNameData   = " << inNameData   << endl;
+
+    // name of input MC file
+    TString NameMC = outPath;
+    NameMC += typeGammas;
+    TString inNameMC(NameMC);
+    inNameMC += ext;
+    gLog << "inNameMC   = " << inNameMC   << endl;
+
+
+    //--------------------------------------------
+    // root files for the training events 
+
+
+
+    TString NameGammasTrain = outPath;
+    NameGammasTrain += "RF_gammas_Train_";
+    NameGammasTrain += typeGammas;
+    TString outNameGammasTrain(NameGammasTrain);    
+    outNameGammasTrain += extout;
+
+
+    TString NameHadronsTrain = outPath;
+    NameHadronsTrain += "RF_hadrons_Train_";
+    NameHadronsTrain += typeHadrons;
+    TString outNameHadronsTrain(NameHadronsTrain);    
+    outNameHadronsTrain += extout;
+
+
+    //--------------------------------------------
+    // root files for the test events 
+
+    TString NameGammasTest = outPath;
+    NameGammasTest += "RF_gammas_Test_";
+    NameGammasTest += typeGammas;
+    TString outNameGammasTest(NameGammasTest);    
+    outNameGammasTest += extout;
+
+    TString NameHadronsTest = outPath;
+    NameHadronsTest += "RF_hadrons_Test_";
+    NameHadronsTest += typeHadrons;
+    TString outNameHadronsTest(NameHadronsTest);    
+    outNameHadronsTest += extout;
+
+    //--------------------------------------------------------------------
+
+    //TString filenameData(inNameData);
+    //TString filenameMC(inNameMC);
+
+    //TString filenameData(outNameHadronsTrain);
+    //TString filenameMC(outNameGammasTrain);
+
+    TString filenameData(outNameHadronsTest);
+    TString filenameMC(outNameGammasTest);
+
+    gLog << "filenameData = " << filenameData << endl;
+    gLog << "filenameMC   = " << filenameMC   << endl;
+
+    //-----------------------------------------------------------------
+
+    MTaskList tliston;
+    MParList pliston;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameMC);
+    read.AddFile(filenameData);
+    read.DisableAutoScheme();
+
+
+    //.......................................................................
+    // names of hadronness containers
+
+    TString hadSCName = "HadSC";
+    TString hadRFName = "HadRF";
+
+    //.......................................................................
+
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+    Float_t maxhadronness =  0.40;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadRFName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+
+    //MFillH fillhadsc("hadSC[MHHadronness]", hadSCName);
+    //fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", hadRFName);
+    fillhadrf.SetName("HhadRF");
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadRFName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    //tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+   
+    tliston.AddToList(&contfinalgh);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 35000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    //pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro ONOFFAnalysis : End of Job C" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+
+
+  //---------------------------------------------------------------------
+  // Job D
+  //======
+
+    //  - select g/h separation method XX
+    //  - read ON2 (or MC2) root file 
+    //  - apply cuts in hadronness
+    //  - make plots
+
+
+ if (JobD)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : Start of Job D" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONOFFAnalysis : JobD = " 
+         << (JobD        ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // type of data to be analysed
+    TString typeData = "ON";
+    //TString typeData = "OFF";
+    //TString typeData = "MC";
+    gLog << "typeData = " << typeData << endl;
+
+    TString ext      = "3.root";
+
+
+    //------------------------------
+    // selection of g/h separation method
+    // and definition of final selections
+
+    //TString XX("SC");
+    TString XX("RF");
+    TString fhadronnessName("Had");
+    fhadronnessName += XX;
+    gLog << "fhadronnessName = " << fhadronnessName << endl;
+
+    // maximum values of the hadronness, |ALPHA| and DIST
+    Float_t maxhadronness   = 0.233;
+    Float_t maxalpha        = 20.0;
+    Float_t maxdist         = 10.0;
+    gLog << "Maximum values of hadronness, |ALPHA| and DIST = "
+         << maxhadronness << ",  " << maxalpha << ",  " 
+         << maxdist << endl;
+
+
+    //------------------------------
+    // name of data file to be analysed
+    TString filenameData(outPath);
+    filenameData += typeData;
+    filenameData += ext;
+    gLog << "filenameData = " << filenameData << endl;
+
+
+
+    //*************************************************************************
+    //
+    // Analyse the data
+    //
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(fhadronnessName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillhadsc("hadSC[MHHadronness]", "HadSC");
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", "HadRF");
+    fillhadrf.SetName("HhadRF");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+
+    TH1  &alphahist = alphaabs->GetHist();
+
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");    
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");    
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(fhadronnessName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 10000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+    //-------------------------------------------
+
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-JobD");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << filenameData << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro ONOFFAnalysis : End of Job D" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+
+
+
+  //---------------------------------------------------------------------
+  // Job E_XX
+  //=========
+
+    //  - select g/h separation method XX
+    //  - read MC_XX2.root file 
+    //  - calculate eff. collection area
+    //  - read ON_XX2.root file 
+    //  - apply final cuts
+    //  - calculate flux
+    //  - write root file for ON data after final cuts (ON_XX3.root))
+
+
+ if (JobE_XX)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : Start of Job E_XX" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro ONOFFAnalysis : JobE_XX, CCollArea, OEEst, WEX = " 
+         << (JobE_XX ? "kTRUE" : "kFALSE")  << ",  " 
+         << (CCollArea?"kTRUE" : "kFALSE")  << ",  " 
+         << (OEEst ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (WEX     ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // type of data to be analysed
+    //TString typeData = "ON";
+    //TString typeData = "OFF";
+    TString typeData = "MC";
+    gLog << "typeData = " << typeData << endl;
+
+    TString typeMC   = "MC";
+    TString ext      = "3.root";
+    TString extout   = "4.root";
+
+    //------------------------------
+    // selection of g/h separation method
+    // and definition of final selections
+
+    //TString XX("SC");
+    TString XX("RF");
+    TString fhadronnessName("Had");
+    fhadronnessName += XX;
+    gLog << "fhadronnessName = " << fhadronnessName << endl;
+
+    // maximum values of the hadronness, |ALPHA| and DIST
+    Float_t maxhadronness   = 0.23;
+    Float_t maxalpha        = 20.0;
+    Float_t maxdist         = 10.0;
+    gLog << "Maximum values of hadronness, |ALPHA| and DIST = "
+         << maxhadronness << ",  " << maxalpha << ",  " 
+         << maxdist << endl;
+
+    //------------------------------
+    // name of MC file to be used for optimizing the energy estimator
+    TString filenameOpt(outPath);
+    filenameOpt += typeMC;
+    filenameOpt += ext; 
+    gLog << "filenameOpt = " << filenameOpt << endl;
+
+    //------------------------------
+    // name of file containing the parameters of the energy estimator
+    TString energyParName(outPath);
+    energyParName += "energyest_";
+    energyParName += XX;
+    energyParName += ".root";
+    gLog << "energyParName = " << energyParName << endl;
+
+    //------------------------------
+    // name of MC file to be used for calculating the eff. collection areas
+    TString filenameArea(outPath);
+    filenameArea += typeMC;
+    filenameArea += ext; 
+    gLog << "filenameArea = " << filenameArea << endl;
+
+    //------------------------------
+    // name of file containing the eff. collection areas
+    TString collareaName(outPath);
+    collareaName += "area_";
+    collareaName += XX;
+    collareaName += ".root";
+    gLog << "collareaName = " << collareaName << endl;
+
+    //------------------------------
+    // name of data file to be analysed
+    TString filenameData(outPath);
+    filenameData += typeData;
+    filenameData += ext;
+    gLog << "filenameData = " << filenameData << endl;
+
+    //------------------------------
+    // name of output data file (after the final cuts)
+    TString filenameDataout(outPath);
+    filenameDataout += typeData;
+    filenameDataout += "_";
+    filenameDataout += XX;
+    filenameDataout += extout;
+    gLog << "filenameDataout = " << filenameDataout << endl;
+
+    //------------------------------
+    // name of file containing histograms for flux calculastion
+    TString filenameResults(outPath);
+    filenameResults += typeData;
+    filenameResults += "Results_";
+    filenameResults += XX;
+    filenameResults += extout;
+    gLog << "filenameResults = " << filenameResults << endl;
+
+
+    //====================================================================
+
+    MHMcCollectionArea collarea;
+    collarea.SetEaxis(MHMcCollectionArea::kLinear);
+
+    MParList  parlist;
+    InitBinnings(&parlist);
+
+  if (CCollArea)
+  {
+    gLog << "-----------------------------------------------" << endl;
+    gLog << "Start calculation of effective collection areas" << endl;
+
+
+    MTaskList tasklist;
+
+    //---------------------------------------
+    // Setup the tasks to be executed
+    //
+    MReadMarsFile reader("Events", filenameArea);
+    reader.DisableAutoScheme();
+
+    MFSelFinal cuthadrons;
+    cuthadrons.SetHadronnessName(fhadronnessName);
+    cuthadrons.SetCuts(maxhadronness, maxalpha, maxdist);
+
+    MContinue conthadrons(&cuthadrons);
+
+
+    MFillH filler("MHMcCollectionArea", "MPointingPos");
+    filler.SetName("CollectionArea");
+
+    //********************************
+    // entries in MParList
+
+    parlist.AddToList(&tasklist);
+
+    parlist.AddToList(&collarea);
+
+    //********************************
+    // entries in MTaskList
+
+    tasklist.AddToList(&reader);   
+    tasklist.AddToList(&conthadrons);
+    tasklist.AddToList(&filler);
+
+    //********************************
+
+    //-----------------------------------------
+    // Execute event loop
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    MProgressBar bar;
+    magic.SetProgressBar(&bar);
+    if (!magic.Eventloop())
+        return;
+
+    tasklist.PrintStatistics(0, kTRUE);
+
+    // Calculate effective collection areas 
+    // and display the histograms
+    //
+    //MHMcCollectionArea *collarea = 
+    //     (MHMcCollectionArea*)parlist.FindObject("MHMcCollectionArea");
+    collarea.CalcEfficiency();
+    collarea.DrawClone();
+
+
+
+    //---------------------------------------------
+    // Write histograms to a file 
+    //
+
+    TFile f(collareaName, "RECREATE");
+    //collarea.GetHist()->Write();
+    //collarea.GetHAll()->Write();
+    //collarea.GetHSel()->Write();
+    collarea.Write();
+
+    f.Close();
+
+    gLog << "Collection area plots written onto file " << collareaName << endl;
+
+    gLog << "Calculation of effective collection areas done" << endl;
+    gLog << "-----------------------------------------------" << endl;    
+    //------------------------------------------------------------------
+  }
+
+  if (!CCollArea)
+  {
+    gLog << "-----------------------------------------------" << endl;
+    gLog << "Read in effective collection areas from file " 
+         << collareaName << endl;
+
+    TFile collfile(collareaName);
+    collfile.ls();
+    collarea.Read("MHMcCollectionArea");
+    collarea.DrawClone();
+
+    gLog << "Effective collection areas were read in from file " 
+         << collareaName << endl;
+    gLog << "-----------------------------------------------" << endl;    
+  }
+
+
+    // save binnings for call to MagicEEst
+    MBinning *binsE     = (MBinning*)parlist.FindObject("BinningE");
+    if (!binsE)
+	{
+          gLog << "Object 'BinningE' not found in MParList" << endl;
+          return;
+	}
+    MBinning *binsTheta = (MBinning*)parlist.FindObject("BinningTheta");
+    if (!binsTheta)
+	{
+          gLog << "Object 'BinningTheta' not found in MParList" << endl;
+          return;
+	}
+
+    //-------------------------------------
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+ if (OEEst)
+ { 
+   //===========================================================
+    //
+    // Optimization of energy estimator
+    //
+    gLog << "Macro ONOFFAnalysis.C : calling MagicEEst" << endl;
+
+    TString inpath("");
+    TString outpath("");
+    Int_t howMany = 2000;
+    MagicEEst(inpath,   filenameOpt,   outpath, energyParName, 
+            fHilName, fHilNameSrc,   fhadronnessName,
+            howMany,  maxhadronness, maxalpha, maxdist,
+            binsE, binsTheta);
+    gLog << "Macro ONOFFAnalysis.C : returning from MagicEEst" << endl;
+ }
+
+ if (WEX)
+ {
+    //-----------------------------------------------------------
+    //
+    // Read in parameters of energy estimator ("MMcEnergyEst")
+    //                   and migration matrix ("MHMcEnergyMigration")
+    //
+    gLog << "================================================================"
+         << endl;
+    gLog << "Macro ONOFFAnalysis.C : read parameters of energy estimator and migration matrix from file '"
+         << energyParName << "'" << endl;
+    TFile enparam(energyParName);
+    enparam.ls();
+    MMcEnergyEst mcest("MMcEnergyEst"); 
+    mcest.Read("MMcEnergyEst");
+
+    //MMcEnergyEst &mcest = *((MMcEnergyEst*)gROOT->FindObject("MMcEnergyEst"));
+    gLog << "Parameters of energy estimator were read in" << endl;
+
+
+    gLog << "Read in Migration matrix" << endl;   
+
+    MHMcEnergyMigration mighiston("MHMcEnergyMigration");
+    mighiston.Read("MHMcEnergyMigration");
+    //MHMcEnergyMigration &mighiston = 
+    //      *((MHMcEnergyMigration*)gROOT->FindObject("MHMcEnergyMigration"));
+
+    gLog << "Migration matrix was read in" << endl;
+
+
+    TArrayD parA(mcest.GetNumCoeffA());
+    TArrayD parB(mcest.GetNumCoeffB());
+    for (Int_t i=0; i<parA.GetSize(); i++)
+      parA[i] = mcest.GetCoeff(i);
+    for (Int_t i=0; i<parB.GetSize(); i++)
+      parB[i] = mcest.GetCoeff( i+parA.GetSize() );
+
+    //*************************************************************************
+    //
+    // Analyse the data
+    //
+    gLog << "============================================================"
+         << endl;
+    gLog << "Analyse the data" << endl;
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+    //.......................................................................
+
+      gLog << "MagicAnalysis.C : write root file '" << filenameDataout 
+           << "'" << endl;
+   
+      //MWriteRootFile &write = *(new MWriteRootFile(filenameDataout));
+
+
+      MWriteRootFile write(filenameDataout, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MPointingPos",  "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      //write.AddContainer("HadNN",         "Events");
+      write.AddContainer("HadSC",         "Events");
+      write.AddContainer("HadRF",         "Events");
+
+      write.AddContainer("MEnergyEst",    "Events");
+
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    MFSelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(fhadronnessName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    //MFillH fillhadnn("hadNN[MHHadronness]", "HadNN");
+    //fillhadnn.SetName("HhadNN");
+    MFillH fillhadsc("hadSC[MHHadronness]", "HadSC");
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", "HadRF");
+    fillhadrf.SetName("HhadRF");
+
+    //---------------------------
+    // calculate estimated energy
+
+    MEnergyEstParam eeston(fHilName);
+    eeston.Add(fHilNameSrc);
+
+    eeston.SetCoeffA(parA);
+    eeston.SetCoeffB(parB);
+
+    //---------------------------
+    // calculate estimated energy using Daniel's parameters
+
+    //MEnergyEstParamDanielMkn421 eeston(fHilName);
+    //eeston.Add(fHilNameSrc);
+    //eeston.SetCoeffA(parA);
+    //eeston.SetCoeffB(parB);
+
+
+    //---------------------------
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");    
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");    
+
+    //---------------------------
+    // new from Robert
+
+    MFillH hfill6("MHTimeDiffTheta", "MPointingPos");
+    hfill6.SetName("HTimeDiffTheta");
+
+    MFillH hfill6a("MHTimeDiffTime", "MPointingPos");
+    hfill6a.SetName("HTimeDiffTime");
+
+    MFillH hfill7("MHAlphaEnergyTheta", fHilNameSrc);
+    hfill7.SetName("HAlphaEnergyTheta");
+
+    MFillH hfill7a("MHAlphaEnergyTime", fHilNameSrc);
+    hfill7a.SetName("HAlphaEnergyTime");
+
+    MFillH hfill7b("MHThetabarTime", fHilNameSrc);
+    hfill7b.SetName("HThetabarTime");
+
+    MFillH hfill7c("MHEnergyTime", "MMcEvt");
+    hfill7c.SetName("HEnergyTime");
+
+
+    //---------------------------
+
+    MFSelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(fhadronnessName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    // robert      
+    tliston.AddToList(&hfill6);   //timediff
+    tliston.AddToList(&hfill6a);   //timediff
+
+    tliston.AddToList(&contfinalgh);
+    tliston.AddToList(&eeston);
+
+    tliston.AddToList(&write);
+
+    //tliston.AddToList(&fillhadnn);
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    //robert
+    tliston.AddToList(&hfill7);
+    tliston.AddToList(&hfill7a);
+    tliston.AddToList(&hfill7b);
+    tliston.AddToList(&hfill7c);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    //pliston.FindObject("hadNN", "MHHadronness")->DrawClone();
+
+    gLog << "before hadRF" << endl;
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+
+    gLog << "before hadSC" << endl;
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    gLog << "before MHHillas" << endl;
+    pliston.FindObject("MHHillas")->DrawClone();
+
+    gLog << "before MHHillasExt" << endl;
+    pliston.FindObject("MHHillasExt")->DrawClone();
+
+    gLog << "before MHHillasSrc" << endl;
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+
+    gLog << "before MHNewImagePar" << endl;
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+
+    gLog << "before MHStarMap" << endl;
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    gLog << "before DeleteBinnings" << endl;
+
+    DeleteBinnings(&pliston);
+
+    gLog << "before Robert's code" << endl;
+
+
+//rwagner write all relevant histograms onto a file
+
+  if (WRobert)
+  {
+    gLog << "=======================================================" << endl;
+    gLog << "Write results onto file '" << filenameResults << "'" << endl;
+
+    TFile outfile(filenameResults,"recreate");
+
+    MHHillasSrc* hillasSrc = 
+      (MHHillasSrc*)(pliston->FindObject("MHHillasSrc"));
+        TH1F* alphaHist = (TH1F*)(hillasSrc->GetHistAlpha());
+    alphaHist->Write();
+    gLog << "Alpha plot has been written out" << endl;    
+
+
+    MHAlphaEnergyTheta* aetH = 
+      (MHAlphaEnergyTheta*)(pliston->FindObject("MHAlphaEnergyTheta"));
+    TH3D* aetHist = (TH3D*)(aetH->GetHist());
+    aetHist->SetName("aetHist");
+    aetHist->Write();
+    gLog << "AlphaEnergyTheta plot has been written out" << endl;    
+
+    MHAlphaEnergyTime* aetH2 = 
+      (MHAlphaEnergyTime*)(pliston->FindObject("MHAlphaEnergyTime"));
+    TH3D* aetHist2 = (TH3D*)(aetH2->GetHist());
+    aetHist2->SetName("aetimeHist");
+//     aetHist2->DrawClone();
+    aetHist2->Write();
+    gLog << "AlphaEnergyTime plot has been written out" << endl;    
+
+    MHThetabarTime* tbt = 
+      (MHThetabarTime*)(pliston->FindObject("MHThetabarTime"));
+    TProfile* tbtHist = (TProfile*)(tbt->GetHist());
+    tbtHist->SetName("tbtHist");
+    tbtHist->Write();
+    gLog << "ThetabarTime plot has been written out" << endl;    
+
+    MHEnergyTime* ent = 
+      (MHEnergyTime*)(pliston->FindObject("MHEnergyTime"));
+    TH2D* entHist = (TH2D*)(ent->GetHist());
+    entHist->SetName("entHist");
+    entHist->Write();
+    gLog << "EnergyTime plot has been written out" << endl;    
+    
+    MHTimeDiffTheta *time = (MHTimeDiffTheta*)pliston.FindObject("MHTimeDiffTheta");
+    TH2D* timeHist = (TH2D*)(time->GetHist());
+    timeHist->SetName("MHTimeDiffTheta");
+    timeHist->SetTitle("Time diffs");
+    timeHist->Write();
+    gLog << "TimeDiffTheta plot has been written out" << endl;    
+
+
+    MHTimeDiffTime *time2 = (MHTimeDiffTime*)pliston.FindObject("MHTimeDiffTime");
+    TH2D* timeHist2 = (TH2D*)(time2->GetHist());
+    timeHist2->SetName("MHTimeDiffTime");
+    timeHist2->SetTitle("Time diffs");
+    timeHist2->Write();
+    gLog << "TimeDiffTime plot has been written out" << endl;    
+
+//rwagner write also collareas to same file
+    collarea->GetHist()->Write();
+    collarea->GetHAll()->Write();
+    collarea->GetHSel()->Write();
+    gLog << "Effective collection areas have been written out" << endl;        
+
+//rwagner todo: write alpha_cut, type of g/h sep (RF, SC, NN), type of data
+//rwagner (ON/OFF/MC), MJDmin, MJDmax to this file
+
+    gLog << "before closing outfile" << endl;
+
+    //outfile.Close();
+    gLog << "Results were written onto file '" << filenameResults 
+         << "'" << endl;
+    gLog << "=======================================================" << endl;
+  }
+
+  }
+
+    gLog << "Macro ONOFFAnalysis : End of Job E_XX" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+}
+
+
+
+
+
+
+
+   
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/ONOFFCT1Analysis.C
===================================================================
--- /tags/Mars-V0.9/macros/ONOFFCT1Analysis.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/ONOFFCT1Analysis.C	(revision 9772)
@@ -0,0 +1,3310 @@
+
+
+#include "CT1EgyEst.C"
+
+
+void InitBinnings(MParList *plist)
+{
+        gLog << "InitBinnings" << endl;
+
+        //--------------------------------------------
+        MBinning *binse = new MBinning("BinningE");
+        //binse->SetEdgesLog(30, 1.0e2, 1.0e5);
+
+	//This is Daniel's binning in energy:
+        binse->SetEdgesLog(14, 296.296, 86497.6);
+        plist->AddToList(binse);
+
+        //--------------------------------------------
+
+        MBinning *binssize = new MBinning("BinningSize");
+        binssize->SetEdgesLog(50, 10, 1.0e5);
+        plist->AddToList(binssize);
+
+        MBinning *binsdistc = new MBinning("BinningDist");
+        binsdistc->SetEdges(50, 0, 1.4);
+        plist->AddToList(binsdistc);
+
+        MBinning *binswidth = new MBinning("BinningWidth");
+        binswidth->SetEdges(50, 0, 1.0);
+        plist->AddToList(binswidth);
+
+        MBinning *binslength = new MBinning("BinningLength");
+        binslength->SetEdges(50, 0, 1.0);
+        plist->AddToList(binslength);
+
+        MBinning *binsalpha = new MBinning("BinningAlpha");
+        binsalpha->SetEdges(100, -100, 100);
+        plist->AddToList(binsalpha);
+
+        MBinning *binsasym = new MBinning("BinningAsym");
+        binsasym->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsasym);
+
+        MBinning *binsm3l = new MBinning("BinningM3Long");
+        binsm3l->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3l);
+
+        MBinning *binsm3t = new MBinning("BinningM3Trans");
+        binsm3t->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3t);
+
+   
+        //.....
+        MBinning *binsb = new MBinning("BinningSigmabar");
+        binsb->SetEdges( 100,  0.0,  5.0);
+        plist->AddToList(binsb);
+
+        MBinning *binth = new MBinning("BinningTheta");
+        // this is Daniel's binning in theta
+        //Double_t yedge[8] = 
+        //  {9.41, 16.22, 22.68, 28.64, 34.03, 38.84, 43.08, 44.99};
+        // this is our binning
+        Double_t yedge[9] = 
+                       {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        TArrayD yed;
+        yed.Set(9,yedge);
+        binth->SetEdges(yed);
+        plist->AddToList(binth);
+
+        MBinning *bincosth = new MBinning("BinningCosTheta");
+        Double_t zedge[9]; 
+        for (Int_t i=0; i<9; i++)
+	{
+          zedge[8-i] = cos(yedge[i]/kRad2Deg);
+	}
+        TArrayD zed;
+        zed.Set(9,zedge);
+        bincosth->SetEdges(zed);
+        plist->AddToList(bincosth);
+
+        MBinning *binsdiff = new MBinning("BinningDiffsigma2");
+        binsdiff->SetEdges(100, -5.0, 20.0);
+        plist->AddToList(binsdiff);
+
+        // robert ----------------------------------------------
+        MBinning *binsalphaf = new MBinning("BinningAlphaFlux");
+        binsalphaf->SetEdges(100, -100, 100);
+        plist->AddToList(binsalphaf);
+
+	MBinning *binsdifftime = new MBinning("BinningTimeDiff");
+	binsdifftime->SetEdges(50, 0, 10);
+	plist->AddToList(binsdifftime);
+
+	MBinning *binstime = new MBinning("BinningTime");
+	binstime->SetEdges(50, 44500, 61000);
+	plist->AddToList(binstime);
+}
+
+
+void DeleteBinnings(MParList *plist)
+{
+        gLog << "DeleteBinnings" << endl;
+
+        TObject *bin;
+
+        //--------------------------------------------
+        bin = plist->FindObject("BinningE");
+        if (bin) delete bin;
+
+        //--------------------------------------------
+
+        bin = plist->FindObject("BinningSize");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDist");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningWidth");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningLength");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAlpha");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAsym");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Long");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Trans");
+        if (bin) delete bin;
+
+        //.....
+        bin = plist->FindObject("BinningSigmabar");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningCosTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDiffsigma2");
+        if (bin) delete bin;
+
+
+        // robert ----------------------------------------------
+        bin = plist->FindObject("BinningAlphaFlux");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTimeDiff");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTime");
+        if (bin) delete bin;
+}
+
+
+
+//************************************************************************
+void ONOFFCT1Analysis()
+{
+      gLog.SetNoColors();
+
+      if (gRandom)
+        delete gRandom;
+      gRandom = new TRandom3(0);
+
+      //-----------------------------------------------
+      const char *offfile = "~magican/ct1test/wittek/offdata.preproc"; 
+
+      //const char *onfile  = "~magican/ct1test/wittek/mkn421_on.preproc"; 
+      const char *onfile  = "~magican/ct1test/wittek/mkn421_00-01"; 
+
+      const char *mcfile  = "~magican/ct1test/wittek/mkn421_mc_pedrms_0.001.preproc";
+      //-----------------------------------------------
+
+      // path for input for Mars
+      TString inPath = "~magican/ct1test/wittek/marsoutput/optionD/";
+
+      // path for output from Mars
+      TString outPath = "~magican/ct1test/wittek/marsoutput/optionD/";
+
+      //-----------------------------------------------
+
+      //TEnv env("macros/CT1env.rc");
+      //Bool_t printEnv = kFALSE;
+
+    //************************************************************************
+
+    // Job A : 
+    //  - produce MHSigmaTheta plots for ON and OFF data
+    //  - write out (or read in) these MHSigmaTheta plots
+    //  - read ON (or OFF or MC) data
+    //  - pad the events; 
+    //  - write root file for ON (or OFF or MC) data (ON1.root, ...);
+
+    Bool_t JobA    = kFALSE;  
+    Bool_t WPad    = kFALSE;   // write out padding histograms ?
+    Bool_t RPad    = kFALSE;   // read in padding histograms ?
+    Bool_t Wout    = kFALSE;   // write out root file ON1.root 
+                               // (or OFF1.root or MC1.root)?
+
+
+    // Job B_RF_UP : read ON1.root (OFF1.root or MC1.root) file 
+    //  - if CTrainRF = TRUE : create matrices of training events
+    //                         and root files of training and test events
+    //  - if RTrainRF = TRUE : read in training matrices for hadrons and gammas
+    //  - if RTree    = TRUE : read in trees, otherwise create trees
+    //  - calculate hadroness for method of RANDOM FOREST
+    //  - update the input files with the hadronesses (ON2.root, OFF2.root
+    //     or MC2.root)
+
+    Bool_t JobB_RF_UP  = kFALSE;  
+    Bool_t CTrainRF    = kFALSE;  // create  matrices of training events
+                                  // and root files of training and test events
+    Bool_t RTrainRF    = kFALSE;  // read in matrices of training events
+    Bool_t RTree       = kFALSE;  // read in trees (otherwise grow them)
+    Bool_t WRF         = kFALSE;  // update input root file ?
+
+
+    // Job B_SC_UP : read ON2.root (or MC2.root) file 
+    //  - depending on WParSC : create (or read in) supercuts parameter values
+    //  - calculate hadroness for the SUPERCUTS
+    //  - update the input files with the hadroness (==>ON3.root or MC3.root)
+
+    Bool_t JobB_SC_UP  = kTRUE;
+    Bool_t CMatrix     = kTRUE;  // create training and test matrices 
+    Bool_t RMatrix     = kFALSE;  // read training and test matrices from file
+    Bool_t WOptimize   = kFALSE;  // do optimization using the training sample
+                                  // and write supercuts parameter values 
+                                  // onto the file parSCfile
+    Bool_t RTest       = kFALSE;  // test the supercuts using the test matrix
+    Bool_t WSC         = kFALSE;  // update input root file ?
+
+
+    // Job C: 
+    //  - read ON3.root and MC3.root files
+    //    which should have been updated to contain the hadronnesses  
+    //    for the method of 
+    //              RF
+    //              SUPERCUTS and
+    //  - produce Neyman-Pearson plots
+
+    Bool_t JobC  = kFALSE;  
+
+
+    // Job D :  
+    //  - select g/h separation method XX
+    //  - read ON3 (or MC3) root file
+    //  - apply cuts in hadronness
+    //  - make plots
+
+    Bool_t JobD  = kFALSE;  
+
+
+
+    // Job E_XX : extended version of E_XX (including flux plots)  
+    //  - select g/h separation method XX
+    //  - read MC root file 
+    //  - calculate eff. collection area
+    //  - optimize energy estimator
+    //  - read ON root file 
+    //  - apply final cuts
+    //  - calculate flux
+    //  - write root file for ON data after final cuts 
+
+
+    Bool_t JobE_XX  = kFALSE;  
+    Bool_t CCollArea= kFALSE;  // calculate eff. collection areas
+    Bool_t OEEst    = kFALSE;  // optimize energy estimator
+    Bool_t WEX      = kFALSE;  // update root file  ?
+    Bool_t WRobert  = kFALSE;  // write out Robert's file  ?
+
+
+
+    //************************************************************************
+
+    
+  //---------------------------------------------------------------------
+  // Job A
+  //=========
+    // read ON data file 
+
+    //  - produce the 2D-histogram "sigmabar versus Theta" 
+    //    (SigmaTheta_ON.root) for ON data
+    //    (to be used for the padding of the MC gamma data)
+
+    //  - write a file of ON events (ON1.root) 
+    //    (after the standard cuts, before the g/h separation)
+    //    (to be used together with the corresponding MC gamma file (MC1.root)
+    //     for the optimization of the g/h separation)
+
+
+ if (JobA)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job A" << endl;
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobA, WPad, RPad, Wout = " 
+         << (JobA ? "kTRUE" : "kFALSE")  << ",  " 
+         << (WPad ? "kTRUE" : "kFALSE")  << ",  " 
+         << (RPad ? "kTRUE" : "kFALSE")  << ",  " 
+         << (Wout ? "kTRUE" : "kFALSE")  << endl;
+    
+
+    //--------------------------------------------------
+    // names of ON and OFF files to be read
+    // for generating the histograms to be used in the padding 
+    TString fileON  = onfile;
+    TString fileOFF = offfile;
+    gLog << "fileON, fileOFF = " << fileON << ",  " << fileOFF << endl;
+
+    // name of file to conatin the histograms for the padding
+    TString outNameSigTh = outPath;
+    outNameSigTh += "SigmaTheta";
+    outNameSigTh += ".root";
+
+    //--------------------------------------------------
+    // type of data to be padded 
+    //TString typeInput = "ON";
+    //TString typeInput = "OFF";
+    TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+
+    // name of input root file
+    if (typeInput == "ON")
+      TString filenamein(onfile);
+    else if (typeInput == "OFF")
+      TString filenamein(offfile);
+    else if (typeInput == "MC")
+      TString filenamein(mcfile);
+    gLog << "data to be padded : " << filenamein << endl;
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += typeInput;
+    outNameImage += "1.root";
+    gLog << "padded data to be written onto : " << outNameImage << endl;
+
+    //--------------------------------------------------
+
+    //************************************************************
+    // generate histograms to be used in the padding
+    // 
+    // read ON and OFF data files
+    // generate (or read in) the padding histograms for ON and OFF data
+    //                       and merge these histograms
+
+    MCT1PadONOFF pad;
+    pad.SetName("MCT1PadONOFF");
+    pad.SetPadFlag(1);
+    pad.SetDataType(typeInput);
+
+    // generate the padding histograms
+    if (!RPad)
+    {
+      gLog << "=====================================================" << endl;
+      gLog << "Start generating the padding histograms" << endl;
+      //-----------------------------------------
+      // ON events
+
+      gLog << "-----------" << endl;
+      gLog << "ON events :" << endl;
+      gLog << "-----------" << endl;
+
+      MTaskList tliston;
+      MParList pliston;
+
+      MCT1ReadPreProc readON(fileON);
+
+      //MFCT1SelBasic selthetaon;
+      //selthetaon.SetCuts(-100.0, 29.5, 35.5);
+      //MContinue contthetaon(&selthetaon);
+
+      MBlindPixelCalc blindon;
+      blindon.SetUseBlindPixels();
+
+      MFCT1SelBasic selbasicon;
+      MContinue contbasicon(&selbasicon);
+
+      MHBlindPixels blindON("BlindPixelsON");
+      MFillH fillblindON("BlindPixelsON[MHBlindPixels]", "MBlindPixels");
+      fillblindON.SetName("FillBlind");
+
+      MSigmabarCalc sigbarcalcon;
+
+      MHSigmaTheta sigthON("SigmaThetaON");
+      MFillH fillsigthetaON ("SigmaThetaON[MHSigmaTheta]", "MMcEvt");
+      fillsigthetaON.SetName("FillSigTheta");    
+ 
+      //*****************************
+      // entries in MParList
+    
+      pliston.AddToList(&tliston);
+      InitBinnings(&pliston);
+      pliston.AddToList(&blindON);
+      pliston.AddToList(&sigthON);
+
+
+      //*****************************
+      // entries in MTaskList
+    
+      tliston.AddToList(&readON);
+      //tliston.AddToList(&contthetaon);
+
+      tliston.AddToList(&blindon);
+
+      tliston.AddToList(&contbasicon);
+      tliston.AddToList(&fillblindON);
+      tliston.AddToList(&sigbarcalcon);
+      tliston.AddToList(&fillsigthetaON);
+
+      MProgressBar baron;
+      MEvtLoop evtloopon;
+      evtloopon.SetParList(&pliston);
+      evtloopon.SetProgressBar(&baron);
+
+      Int_t maxeventson = -1;
+      //Int_t maxeventson = 10000;
+      if ( !evtloopon.Eventloop(maxeventson) )
+          return;
+
+      tliston.PrintStatistics(0, kTRUE);
+
+      blindON.DrawClone();
+      sigthON.DrawClone();
+
+      // save the histograms for the padding
+      TH2D *sigthon     = sigthON.GetSigmaTheta();
+      TH3D *sigpixthon  = sigthON.GetSigmaPixTheta();
+      TH3D *diffpixthon = sigthON.GetDiffPixTheta();
+
+      TH2D *blindidthon = blindON.GetBlindId();
+      TH2D *blindnthon  = blindON.GetBlindN();
+
+      //-----------------------------------------
+      // OFF events
+
+      gLog << "------------" << endl;
+      gLog << "OFF events :" << endl;
+      gLog << "------------" << endl;
+
+      MTaskList tlistoff;
+      MParList plistoff;
+
+      MCT1ReadPreProc readOFF(fileOFF);
+
+      MFCT1SelBasic selthetaoff;
+      selthetaoff.SetCuts(-100.0, 29.5, 35.5);
+      MContinue contthetaoff(&selthetaoff);
+
+      MBlindPixelCalc blindoff;
+      blindoff.SetUseBlindPixels();
+
+      MFCT1SelBasic selbasicoff;
+      MContinue contbasicoff(&selbasicoff);
+
+      MHBlindPixels blindOFF("BlindPixelsOFF");
+      MFillH fillblindOFF("BlindPixelsOFF[MHBlindPixels]", "MBlindPixels");
+      fillblindOFF.SetName("FillBlindOFF");
+
+      MSigmabarCalc sigbarcalcoff;
+
+      MHSigmaTheta sigthOFF("SigmaThetaOFF");
+      MFillH fillsigthetaOFF ("SigmaThetaOFF[MHSigmaTheta]", "MMcEvt");
+      fillsigthetaOFF.SetName("FillSigThetaOFF");     
+
+      //*****************************
+      // entries in MParList
+    
+      plistoff.AddToList(&tlistoff);
+      InitBinnings(&plistoff);
+      plistoff.AddToList(&blindOFF);
+      plistoff.AddToList(&sigthOFF);
+
+
+      //*****************************
+      // entries in MTaskList
+    
+      tlistoff.AddToList(&readOFF);
+      //tlistoff.AddToList(&contthetaoff);
+
+      tlistoff.AddToList(&blindoff);
+
+      tlistoff.AddToList(&contbasicoff);
+      tlistoff.AddToList(&fillblindOFF);
+      tlistoff.AddToList(&sigbarcalcoff);
+      tlistoff.AddToList(&fillsigthetaOFF);
+
+      MProgressBar baroff;
+      MEvtLoop evtloopoff;
+      evtloopoff.SetParList(&plistoff);
+      evtloopoff.SetProgressBar(&baroff);
+
+      Int_t maxeventsoff = -1;
+      //Int_t maxeventsoff = 20000;
+      if ( !evtloopoff.Eventloop(maxeventsoff) )
+          return;
+
+      tlistoff.PrintStatistics(0, kTRUE);
+
+      blindOFF.DrawClone();
+      sigthOFF.DrawClone();
+
+      // save the histograms for the padding
+      TH2D *sigthoff     = sigthOFF.GetSigmaTheta();
+      TH3D *sigpixthoff  = sigthOFF.GetSigmaPixTheta();
+      TH3D *diffpixthoff = sigthOFF.GetDiffPixTheta();
+
+      TH2D *blindidthoff = blindOFF.GetBlindId();
+      TH2D *blindnthoff  = blindOFF.GetBlindN();
+
+
+      //-----------------------------------------
+
+      gLog << "End of generating the padding histograms" << endl;
+      gLog << "=====================================================" << endl;
+
+      pad.MergeHistograms(sigthon,     sigthoff,
+                          sigpixthon,  sigpixthoff,
+                          diffpixthon, diffpixthoff,
+                          blindidthon, blindidthoff,
+                          blindnthon,  blindnthoff);
+
+      if (WPad)
+      {
+        // write the padding histograms onto a file  ---------
+        pad.WriteTargetDist(outNameSigTh);     
+      }
+    }
+
+    // read the padding histograms ---------------------------
+    if (RPad)
+    {
+      pad.ReadTargetDist(outNameSigTh);
+    }
+
+
+    //************************************************************
+
+  if (Wout)
+  {
+    gLog << "=====================================================" << endl;
+    gLog << "Start the padding" << endl;
+
+    //-----------------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    char *sourceName = "MSrcPosCam";
+    MSrcPosCam source(sourceName);
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MCT1ReadPreProc read(filenamein);
+
+    MFCT1SelBasic seltheta;
+    seltheta.SetCuts(-100.0, 29.5, 35.5);
+    MContinue conttheta(&seltheta);
+
+    if (typeInput ==  "ON")
+    {
+      MCT1PointingCorrCalc pointcorr(sourceName, "MCT1PointingCorrCalc", 
+                                                 "MCT1PointingCorrCalc");
+    }
+
+    MBlindPixelCalc blindbeforepad;
+    blindbeforepad.SetUseBlindPixels();
+    blindbeforepad.SetName("BlindBeforePadding");
+
+    MBlindPixelCalc blind;
+    blind.SetUseBlindPixels();
+    blind.SetName("BlindAfterPadding");
+
+    MFCT1SelBasic selbasic;
+    MContinue contbasic(&selbasic);
+    contbasic.SetName("SelBasic");
+
+    MFillH fillblind("BlindPixels[MHBlindPixels]", "MBlindPixels");
+    fillblind.SetName("HBlind");
+
+    MSigmabarCalc sigbarcalc;
+
+    MFillH fillsigtheta ("SigmaTheta[MHSigmaTheta]", "MMcEvt");
+    fillsigtheta.SetName("HSigmaTheta");
+
+    MImgCleanStd    clean; 
+
+
+    // calculation of  image parameters ---------------------
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImgPar(fImgParName);
+
+    MHillasSrcCalc hsrccalc(sourceName, fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+    // --------------------------------------------------
+
+    MFCT1SelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+    selstandard.SetCuts(92, 4, 60, 0.4, 1.05, 0.0, 0.0);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+
+      MWriteRootFile write(outNameImage);
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+
+    //*****************************
+    // entries in MParList
+    
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(&source);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+    //tliston.AddToList(&conttheta);
+
+    tliston.AddToList(&blindbeforepad);
+    tliston.AddToList(&pad);
+    if (typeInput ==  "ON")
+      tliston.AddToList(&pointcorr);
+    tliston.AddToList(&blind);
+
+    tliston.AddToList(&contbasic);
+    tliston.AddToList(&fillblind);
+    tliston.AddToList(&sigbarcalc);
+    tliston.AddToList(&fillsigtheta);
+    tliston.AddToList(&clean);
+
+    tliston.AddToList(&hcalc);
+    tliston.AddToList(&hsrccalc);
+
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contstandard);
+    tliston.AddToList(&write);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //  evtloop.Write();
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 1000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+
+    pliston.FindObject("SigmaTheta", "MHSigmaTheta")->DrawClone();
+    pliston.FindObject("BlindPixels", "MHBlindPixels")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    DeleteBinnings(&pliston);
+
+      gLog << "End of padding" << endl;
+      gLog << "=====================================================" << endl;
+  }  
+
+
+    gLog << "Macro CT1Analysis : End of Job A" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+
+
+
+
+  //---------------------------------------------------------------------
+  // Job B_RF_UP
+  //============
+
+
+    //  - create (or read in) the matrices of training events for gammas 
+    //    and hadrons
+    //  - create (or read in) the trees
+    //  - then read ON1.root (or MC1.root) file 
+    //  - calculate the hadroness for the method of RANDOM FOREST
+    //  - update input root file with the hadroness
+
+
+ if (JobB_RF_UP)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job B_RF_UP" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobB_RF_UP, RTrainRF, CTrainRF, RTree, WRF = "
+         << (JobB_RF_UP ? "kTRUE" : "kFALSE")  << ",  " 
+         << (RTrainRF ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (CTrainRF ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (RTree ?      "kTRUE" : "kFALSE")  << ",  "
+         << (WRF ?        "kTRUE" : "kFALSE")  << endl;
+
+
+    //--------------------------------------------
+    // parameters for the random forest
+    Int_t NumTrees = 100;
+    Int_t NumTry   =   3;
+    Int_t NdSize   =   1;
+
+
+    TString hadRFName = "HadRF";
+    Float_t maxhadronness =  0.23;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+    TString extin  = "1.root";
+    TString extout = "2.root";
+
+    //--------------------------------------------
+    // for the analysis using ON data only set typeMatrixHadrons = "ON"
+    //                        ON and OFF data                    = "OFF"
+    TString typeMatrixHadrons = "OFF";
+    gLog << "typeMatrixHadrons = " << typeMatrixHadrons << endl;
+
+
+    // file to be updated (ON, OFF or MC)
+
+    //TString typeInput = "ON";
+    TString typeInput = "OFF";
+    //TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+    // name of input root file
+    TString NameData = outPath;
+    NameData += typeInput;
+    TString inNameData(NameData);
+    inNameData += extin;
+    gLog << "inNameData = " << inNameData << endl; 
+
+    // name of output root file
+    TString outNameData(NameData);
+    outNameData += extout;
+    gLog << "outNameData = " << outNameData << endl; 
+
+    //--------------------------------------------
+    // files to be read for generating 
+    //    - the matrices of training events
+    //    - and the root files of training and test events
+
+
+    // "hadrons" :
+    TString filenameHad = outPath;
+    filenameHad += typeMatrixHadrons;
+    filenameHad += extin;
+    Int_t howManyHadronsTrain = 12000;
+    Int_t howManyHadronsTest  = 12000;
+    gLog << "filenameHad = "    << filenameHad << ",   howManyHadronsTrain = "
+         << howManyHadronsTrain << ",   howManyHadronsTest = "
+         << howManyHadronsTest  << endl; 
+    
+
+    // "gammas" :
+    TString filenameMC = outPath;
+    filenameMC += "MC";
+    filenameMC += extin;
+    Int_t howManyGammasTrain = 12000;
+    Int_t howManyGammasTest  = 12000;
+    gLog << "filenameMC = "    << filenameMC << ",   howManyGammasTrain = "
+         << howManyGammasTrain << ",   howManyGammasTest = "
+         << howManyGammasTest  << endl; 
+    
+    //--------------------------------------------
+    // files for the matrices of training events 
+
+    TString NameGammas = outPath;
+    NameGammas += "RFmatrix_gammas_Train_";
+    NameGammas += "MC";
+    NameGammas += extin;
+
+    TString NameHadrons = outPath;
+    NameHadrons += "RFmatrix_hadrons_Train_";
+    NameHadrons += typeMatrixHadrons;
+    NameHadrons += extin;
+
+
+    //--------------------------------------------
+    // root files for the training events 
+
+    TString NameGammasTrain = outPath;
+    NameGammasTrain += "RF_gammas_Train_";
+    NameGammasTrain += "MC";
+    TString inNameGammasTrain(NameGammasTrain);    
+    inNameGammasTrain += extin;
+    TString outNameGammasTrain(NameGammasTrain);    
+    outNameGammasTrain += extout;
+
+
+    TString NameHadronsTrain = outPath;
+    NameHadronsTrain += "RF_hadrons_Train_";
+    NameHadronsTrain += typeMatrixHadrons;
+    TString inNameHadronsTrain(NameHadronsTrain);    
+    inNameHadronsTrain += extin;
+    TString outNameHadronsTrain(NameHadronsTrain);    
+    outNameHadronsTrain += extout;
+
+
+    //--------------------------------------------
+    // root files for the test events 
+
+    TString NameGammasTest = outPath;
+    NameGammasTest += "RF_gammas_Test_";
+    NameGammasTest += "MC";
+    TString inNameGammasTest(NameGammasTest);    
+    inNameGammasTest += extin;
+    TString outNameGammasTest(NameGammasTest);    
+    outNameGammasTest += extout;
+
+    TString NameHadronsTest = outPath;
+    NameHadronsTest += "RF_hadrons_Test_";
+    NameHadronsTest += typeMatrixHadrons;
+    TString inNameHadronsTest(NameHadronsTest);    
+    inNameHadronsTest += extin;
+    TString outNameHadronsTest(NameHadronsTest);    
+    outNameHadronsTest += extout;
+
+    //--------------------------------------------------------------------
+
+
+    MHMatrix matrixg("MatrixGammas");
+    matrixg.EnableGraphicalOutput();
+
+    matrixg.AddColumn("cos(MMcEvt.fTelescopeTheta)");
+    matrixg.AddColumn("MSigmabar.fSigmabar");
+    matrixg.AddColumn("log10(MHillas.fSize)");
+    matrixg.AddColumn("MHillasSrc.fDist");
+    matrixg.AddColumn("MHillas.fWidth");
+    matrixg.AddColumn("MHillas.fLength");
+    matrixg.AddColumn("log10(MHillas.fSize/(MHillas.fWidth*MHillas.fLength))");
+    matrixg.AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    matrixg.AddColumn("MNewImagePar.fConc");
+    matrixg.AddColumn("MNewImagePar.fLeakage1");
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.EnableGraphicalOutput();
+
+    matrixh.AddColumns(matrixg.GetColumns());
+
+    //--------------------------------------------
+    // file of trees of the random forest 
+
+    TString outRF = outPath;
+    outRF += "RF.root";
+
+
+   //*************************************************************************
+   // read in matrices of training events
+if (RTrainRF)
+  {
+    const char* mtxName = "MatrixGammas";
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Get matrix for (gammas)" << endl;
+    gLog << "matrix name        = " << mtxName << endl;
+    gLog << "name of root file  = " << NameGammas << endl;
+    gLog << "" << endl;
+
+
+    // read in the object with the name 'mtxName' from file 'NameGammas'
+    //
+    TFile fileg(NameGammas); 
+
+    matrixg.Read(mtxName);
+    matrixg.Print("SizeCols");
+
+
+    //***************************************************************** 
+
+    const char* mtxName = "MatrixHadrons";
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << " Get matrix for (hadrons)" << endl;
+    gLog << "matrix name        = " << mtxName << endl;
+    gLog << "name of root file  = " << NameHadrons << endl;
+    gLog << "" << endl;
+
+
+    // read in the object with the name 'mtxName' from file 'NameHadrons'
+    //
+    TFile fileh(NameHadrons); 
+
+    matrixh.Read(mtxName);
+    matrixh.Print("SizeCols");
+  }
+
+
+   //*************************************************************************
+   // create matrices of training events
+   // and root files of training and test events
+ 
+if (CTrainRF)
+  {
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << " Create matrices of training events and root files of training and test events" 
+         << endl;
+    gLog << " Gammas :" << endl;
+    gLog << "---------" << endl;
+
+    MParList  plistg;
+    MTaskList tlistg;
+
+    MReadMarsFile  readg("Events", filenameMC);
+    readg.DisableAutoScheme();
+
+    TString mgname("costhg");
+    MBinning bing("Binning"+mgname);
+    bing.SetEdges(10, 0., 1.0);
+
+    MH3 gref("cos(MMcEvt.fTelescopeTheta)");
+    gref.SetName(mgname);
+    MH::SetBinning(&gref.GetHist(), &bing);
+    //for (Int_t i=1; i<=gref.GetNbins(); i++)
+    //  gref.GetHist().SetBinContent(i, 1.0);
+
+    MFEventSelector2 selectorg(gref);
+    selectorg.SetNumMax(howManyGammasTrain+howManyGammasTest);
+    selectorg.SetName("selectGammasTrainTest");
+    selectorg.SetInverted();
+    //selectorg.SetUseOrigDistribution(kTRUE);
+
+    MContinue contg(&selectorg);
+    contg.SetName("ContGammas");
+
+    Double_t probg = ( (Double_t) howManyGammasTrain )
+                   / ( (Double_t)(howManyGammasTrain+howManyGammasTest) );
+    MFRandomSplit splitg(probg);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&splitg);
+    fillmatg.SetName("fillGammas");
+
+    //-----------------------
+    // for writing the root files of training and test events
+    // for gammas
+    
+    MWriteRootFile writetraing(inNameGammasTrain, "RECREATE");
+    writetraing.SetName("WriteGammasTrain");
+    writetraing.SetFilter(&splitg);
+
+      writetraing.AddContainer("MRawRunHeader", "RunHeaders");
+      writetraing.AddContainer("MTime",         "Events");
+      writetraing.AddContainer("MMcEvt",        "Events");
+      writetraing.AddContainer("ThetaOrig",     "Events");
+      writetraing.AddContainer("MSrcPosCam",    "Events");
+      writetraing.AddContainer("MSigmabar",     "Events");
+      writetraing.AddContainer("MHillas",       "Events");
+      writetraing.AddContainer("MHillasExt",    "Events");
+      writetraing.AddContainer("MHillasSrc",    "Events");
+      writetraing.AddContainer("MNewImagePar",  "Events");
+
+    MContinue contgtrain(&splitg);
+    contgtrain.SetName("ContGammaTrain");
+
+    MWriteRootFile writetestg(inNameGammasTest, "RECREATE");
+    writetestg.SetName("WriteGammasTest");
+
+      writetestg.AddContainer("MRawRunHeader", "RunHeaders");
+      writetestg.AddContainer("MTime",         "Events");
+      writetestg.AddContainer("MMcEvt",        "Events");
+      writetestg.AddContainer("ThetaOrig",     "Events");
+      writetestg.AddContainer("MSrcPosCam",    "Events");
+      writetestg.AddContainer("MSigmabar",     "Events");
+      writetestg.AddContainer("MHillas",       "Events");
+      writetestg.AddContainer("MHillasExt",    "Events");
+      writetestg.AddContainer("MHillasSrc",    "Events");
+      writetestg.AddContainer("MNewImagePar",  "Events");
+
+    //-----------------------
+    
+    //*****************************   fill gammas   ***  
+    // entries in MParList
+    
+    plistg.AddToList(&tlistg);
+    InitBinnings(&plistg);
+
+    plistg.AddToList(&matrixg);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tlistg.AddToList(&readg);
+    tlistg.AddToList(&contg);
+
+    tlistg.AddToList(&splitg);
+    tlistg.AddToList(&fillmatg);
+    tlistg.AddToList(&writetraing);
+    tlistg.AddToList(&contgtrain);
+
+    tlistg.AddToList(&writetestg);
+
+    //*****************************
+
+    MProgressBar matrixbar;
+    MEvtLoop evtloopg;
+    evtloopg.SetName("FillGammaMatrix");
+    evtloopg.SetParList(&plistg);
+    //evtloopg.ReadEnv(env, "", printEnv);
+    evtloopg.SetProgressBar(&matrixbar);
+
+    Int_t maxevents = -1;
+    if (!evtloopg.Eventloop(maxevents))
+        return;
+
+    tlistg.PrintStatistics(0, kTRUE);
+
+    matrixg.Print("SizeCols");
+    Int_t generatedgTrain = matrixg.GetM().GetNrows();
+    if ( fabs(generatedgTrain-howManyGammasTrain) > 
+                                    3.0*sqrt(howManyGammasTrain) )
+    {
+      gLog << "ONOFFCT1Analysis.C : no.of generated gamma training events (" 
+           << generatedgTrain << ") is incompatible with the no.of requested events (" 
+           << howManyGammasTrain << ")" << endl;   
+    }
+
+
+    Int_t generatedgTest = writetestg.GetNumExecutions();
+    if ( fabs(generatedgTest-howManyGammasTest) > 
+                                    3.0*sqrt(howManyGammasTest) )
+    {
+      gLog << "ONOFFCT1Analysis.C : no.of generated gamma test events (" 
+           << generatedgTest << ") is incompatible with the no.of requested events (" 
+           << howManyGammasTest << ")" << endl;   
+    }
+
+    //*****************************   fill hadrons   ***  
+    gLog << "---------------------------------------------------------------"
+         << endl;
+    gLog << " Hadrons :" << endl;
+    gLog << "----------" << endl;
+
+    MParList  plisth;
+    MTaskList tlisth;
+
+    MReadMarsFile  readh("Events", filenameHad);
+    readh.DisableAutoScheme();
+
+    TString mhname("costhh");
+    MBinning binh("Binning"+mhname);
+    binh.SetEdges(10, 0., 1.0);
+
+    //MH3 href("cos(MMcEvt.fTelescopeTheta)");
+    //href.SetName(mhname);
+    //MH::SetBinning(&href.GetHist(), &binh);
+    //for (Int_t i=1; i<=href.GetNbins(); i++)
+    //  href.GetHist().SetBinContent(i, 1.0);
+
+    //use the original distribution from the gammas
+    MH3 &href = *(selectorg.GetHistOrig());
+
+    MFEventSelector2 selectorh(href);
+    selectorh.SetNumMax(howManyHadronsTrain+howManyHadronsTest);
+    selectorh.SetName("selectHadronsTrainTest");
+    selectorh.SetInverted();
+
+    MContinue conth(&selectorh);
+    conth.SetName("ContHadrons");
+
+    Double_t probh = ( (Double_t) howManyHadronsTrain )
+                   / ( (Double_t)(howManyHadronsTrain+howManyHadronsTest) );
+    MFRandomSplit splith(probh);
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&splith);
+    fillmath.SetName("fillHadrons");
+
+    //-----------------------
+    // for writing the root files of training and test events
+    // for hadrons
+    
+    MWriteRootFile writetrainh(inNameHadronsTrain, "RECREATE");
+    writetrainh.SetName("WriteHadronsTrain");
+    writetrainh.SetFilter(&splith);
+
+      writetrainh.AddContainer("MRawRunHeader", "RunHeaders");
+      writetrainh.AddContainer("MTime",         "Events");
+      writetrainh.AddContainer("MMcEvt",        "Events");
+      writetrainh.AddContainer("ThetaOrig",     "Events");
+      writetrainh.AddContainer("MSrcPosCam",    "Events");
+      writetrainh.AddContainer("MSigmabar",     "Events");
+      writetrainh.AddContainer("MHillas",       "Events");
+      writetrainh.AddContainer("MHillasExt",    "Events");
+      writetrainh.AddContainer("MHillasSrc",    "Events");
+      writetrainh.AddContainer("MNewImagePar",  "Events");
+
+    MContinue conthtrain(&splith);
+
+    MWriteRootFile writetesth(inNameHadronsTest, "RECREATE");
+    writetesth.SetName("WriteHadronsTest");
+
+      writetesth.AddContainer("MRawRunHeader", "RunHeaders");
+      writetesth.AddContainer("MTime",         "Events");
+      writetesth.AddContainer("MMcEvt",        "Events");
+      writetesth.AddContainer("ThetaOrig",     "Events");
+      writetesth.AddContainer("MSrcPosCam",    "Events");
+      writetesth.AddContainer("MSigmabar",     "Events");
+      writetesth.AddContainer("MHillas",       "Events");
+      writetesth.AddContainer("MHillasExt",    "Events");
+      writetesth.AddContainer("MHillasSrc",    "Events");
+      writetesth.AddContainer("MNewImagePar",  "Events");
+
+
+    //*****************************  
+    // entries in MParList
+    
+    plisth.AddToList(&tlisth);
+    InitBinnings(&plisth);
+
+    plisth.AddToList(&matrixh);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tlisth.AddToList(&readh);
+    tlisth.AddToList(&conth);
+
+    tlisth.AddToList(&splith);
+    tlisth.AddToList(&fillmath);
+    tlisth.AddToList(&writetrainh);
+    tlisth.AddToList(&conthtrain);
+
+    tlisth.AddToList(&writetesth);
+
+    //*****************************
+
+    MProgressBar matrixbar;
+    MEvtLoop evtlooph;
+    evtlooph.SetName("FillHadronMatrix");
+    evtlooph.SetParList(&plisth);
+    //evtlooph.ReadEnv(env, "", printEnv);
+    evtlooph.SetProgressBar(&matrixbar);
+
+    Int_t maxevents = -1;
+    if (!evtlooph.Eventloop(maxevents))
+        return;
+
+    tlisth.PrintStatistics(0, kTRUE);
+
+    matrixh.Print("SizeCols");
+    Int_t generatedhTrain = matrixh.GetM().GetNrows();
+    if ( fabs(generatedhTrain-howManyHadronsTrain) > 
+                                    3.0*sqrt(howManyHadronsTrain) )
+    {
+      gLog << "ONOFFCT1Analysis.C : no.of generated hadron training events (" 
+           << generatedhTrain << ") is incompatible with the no.of requested events (" 
+           << howManyHadronsTrain << ")" << endl;   
+    }
+
+
+    Int_t generatedhTest = writetesth.GetNumExecutions();
+    if ( fabs(generatedhTest-howManyHadronsTest) > 
+                                    3.0*sqrt(howManyHadronsTest) )
+    {
+      gLog << "ONOFFCT1Analysis.C : no.of generated gamma test events (" 
+           << generatedhTest << ") is incompatible with the no.of requested events (" 
+           << howManyHadronsTest << ")" << endl;   
+    }
+
+
+    //*****************************************************  
+
+
+    // write out matrices of training events 
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Write out matrices of training events" << endl;
+
+
+      //-------------------------------------------
+      // "gammas"
+      gLog << "Gammas :" << endl;    
+      matrixg.Print("SizeCols");
+
+      TFile writeg(NameGammas, "RECREATE", "");
+      matrixg.Write();
+
+      gLog << "" << endl;
+      gLog << "Macro CT1Analysis : matrix of training events for gammas written onto file "
+           << NameGammas << endl;
+
+      //-------------------------------------------
+      // "hadrons"
+      gLog << "Hadrons :" << endl;    
+      matrixh.Print("SizeCols");
+
+      TFile writeh(NameHadrons, "RECREATE", "");
+      matrixh.Write();
+
+      gLog << "" << endl;
+      gLog << "Macro CT1Analysis : matrix of training events for hadrons written onto file "
+           << NameHadrons << endl;
+
+  }
+   //**********   end of creating matrices of training events   ***********
+
+
+    MRanForest *fRanForest;
+    MRanTree *fRanTree;
+    //-----------------------------------------------------------------
+    // read in the trees of the random forest 
+    if (RTree)
+    {
+      MParList plisttr;
+      MTaskList tlisttr;
+      plisttr.AddToList(&tlisttr);
+
+      MReadTree readtr("TREE", outRF);
+      readtr.DisableAutoScheme();
+
+      MRanForestFill rffill;
+      rffill.SetNumTrees(NumTrees);
+
+      // list of tasks for the loop over the trees
+
+      tlisttr.AddToList(&readtr);
+      tlisttr.AddToList(&rffill);
+
+      //-------------------
+      // Execute tree loop
+      //
+      MEvtLoop evtlooptr;
+      evtlooptr.SetName("ReadRFTrees");
+      evtlooptr.SetParList(&plisttr);
+      if (!evtlooptr.Eventloop())
+        return;
+
+      tlisttr.PrintStatistics(0, kTRUE);
+
+      gLog << "ONOFFCT1Analysis : RF trees were read in from file "
+           << outRF << endl;
+
+    // get adresses of objects which are used in the next eventloop
+    fRanForest = (MRanForest*)plisttr->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        gLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plisttr->FindObject("MRanTree");
+    if (!fRanTree)                                  
+    {                                                                          
+        gLog << err << dbginf << "MRanTree not found... aborting." << endl;    
+        return kFALSE;
+    }
+
+    }
+
+    //-----------------------------------------------------------------
+    // grow the trees of the random forest (event loop = tree loop)
+
+    if (!RTree)
+    {
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Macro CT1Analysis : start growing trees" << endl;
+
+    MTaskList tlist2;
+    MParList plist2;
+    plist2.AddToList(&tlist2);
+
+    plist2.AddToList(&matrixg);
+    plist2.AddToList(&matrixh);
+
+    MRanForestGrow rfgrow2;
+    rfgrow2.SetNumTrees(NumTrees);
+    rfgrow2.SetNumTry(NumTry);
+    rfgrow2.SetNdSize(NdSize);
+
+    MWriteRootFile rfwrite2(outRF);
+    rfwrite2.AddContainer("MRanTree", "TREE");
+
+    MFillH fillh2("MHRanForestGini");
+
+    // list of tasks for the loop over the trees
+    
+    tlist2.AddToList(&rfgrow2);
+    tlist2.AddToList(&rfwrite2);
+    tlist2.AddToList(&fillh2);
+
+    //-------------------
+    // Execute tree loop
+    //
+    MEvtLoop treeloop;
+    treeloop.SetName("GrowRFTrees");
+    treeloop.SetParList(&plist2);
+
+    if ( !treeloop.Eventloop() )
+        return;
+
+    tlist2.PrintStatistics(0, kTRUE);
+
+    plist2.FindObject("MHRanForestGini")->DrawClone();
+
+
+    // get adresses of objects which are used in the next eventloop
+    fRanForest = (MRanForest*)plist2->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        gLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plist2->FindObject("MRanTree");
+    if (!fRanTree)                                  
+    {                                                                          
+        gLog << err << dbginf << "MRanTree not found... aborting." << endl;    
+        return kFALSE;
+    }
+
+    }
+    // end of growing the trees of the random forest
+    //-----------------------------------------------------------------
+
+
+    //-----------------------------------------------------------------
+    // Update the root files with the RF hadronness
+    //
+
+ if (WRF)
+  {
+    //TString fileName(inNameHadronsTrain);
+    //TString outName(outNameHadronsTrain);
+
+    //TString fileName(inNameHadronsTest);
+    //TString outName(outNameHadronsTest);
+
+    //TString fileName(inNameGammasTrain);
+    //TString outName(outNameGammasTrain);
+
+    //TString fileName(inNameGammasTest);
+    //TString outName(outNameGammasTest);
+
+    TString fileName(inNameData);
+    TString outName(outNameData);
+
+
+
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Update root file '" <<  fileName 
+         << "' with the RF hadronness; ==> " << outName << endl;
+
+   
+    MTaskList tliston;
+    MParList pliston;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", fileName);
+    read.DisableAutoScheme();
+
+
+    //.......................................................................
+    // calculate hadronnes for method of RANDOM FOREST
+
+
+    MRanForestCalc rfcalc;
+    rfcalc.SetHadronnessName(hadRFName);
+
+
+    //.......................................................................
+
+      //MWriteRootFile write(outName, "UPDATE");
+      MWriteRootFile write(outName, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      write.AddContainer(hadRFName,       "Events");
+
+    //-----------------------------------------------------------------
+
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadRFName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillranfor("MHRanForest");
+    fillranfor.SetName("HRanForest");
+
+    MFillH fillhadrf("hadRF[MHHadronness]", hadRFName);
+    fillhadrf.SetName("HhadRF");
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadRFName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(fRanForest);
+    pliston.AddToList(fRanTree);
+
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&rfcalc);
+    tliston.AddToList(&fillranfor);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&write);
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetName("UpdateRootFile");
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+    pliston.FindObject("MHRanForest")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->Print();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+     //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-macro");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << fileName << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+
+    DeleteBinnings(&pliston);
+  }
+
+    gLog << "Macro CT1Analysis : End of Job B_RF_UP" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+  //---------------------------------------------------------------------
+  // Job B_SC_UP
+  //============
+
+    //  - create (or read in) optimum supercuts parameter values
+    //
+    //  - calculate the hadroness for the supercuts
+    //
+    //  - update input root file, including the hadroness
+
+
+ if (JobB_SC_UP)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job B_SC_UP" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobB_SC_UP, CMatrix, RMatrix, WOptimize, RTest, WSC = "
+         << (JobB_SC_UP ? "kTRUE" : "kFALSE")  << ",  " 
+         << (CMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (RMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (WOptimize  ? "kTRUE" : "kFALSE")  << ",  "
+         << (RTest      ? "kTRUE" : "kFALSE")  << ",  "
+         << (WSC        ? "kTRUE" : "kFALSE")  << endl;
+
+
+    //--------------------------------------------
+    // file which contains the initial parameter values for the supercuts 
+    // if parSCinit ="" the initial values are taken from the constructor of
+    //                  MCT1Supercuts
+
+    TString parSCinit = outPath;
+    //parSCinit += "parSC_1709d";
+    parSCinit = "";
+
+    gLog << "parSCinit = " << parSCinit << endl;
+
+    //---------------
+    // file onto which the optimal parameter values for the supercuts 
+    // are written
+
+    TString parSCfile = outPath;
+    parSCfile += "parSC_2310a";
+
+    gLog << "parSCfile = " << parSCfile << endl;
+
+    //--------------------------------------------
+    // file to be updated (either ON or MC)
+
+    //TString typeInput = "ON";
+    //TString typeInput = "OFF";
+    TString typeInput = "MC";
+    gLog << "typeInput = " << typeInput << endl;
+
+    // name of input root file
+    TString filenameData = outPath;
+    filenameData += typeInput;
+    filenameData += "2.root";
+    gLog << "filenameData = " << filenameData << endl; 
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += typeInput;
+    outNameImage += "3.root";
+    
+
+    //TString outNameImage = filenameData;
+
+    gLog << "outNameImage = " << outNameImage << endl; 
+
+    //--------------------------------------------
+    // files to be read for optimizing the supercuts
+    // 
+    // for the training
+    TString filenameTrain = outPath;
+    filenameTrain += "ON";
+    filenameTrain += "1.root";
+    Int_t howManyTrain = 800000;
+    gLog << "filenameTrain = " << filenameTrain << ",   howManyTrain = "
+         << howManyTrain  << endl; 
+
+    // for testing
+    TString filenameTest = outPath;
+    filenameTest += "ON";
+    filenameTest += "1.root";
+    Int_t howManyTest = 800000;
+
+    gLog << "filenameTest = " << filenameTest << ",   howManyTest = "
+         << howManyTest  << endl; 
+    
+
+    //--------------------------------------------
+    // files to contain the matrices (generated from filenameTrain and
+    //                                               filenameTest)
+    // 
+    // for the training
+    TString fileMatrixTrain = outPath;
+    fileMatrixTrain += "MatrixTrainSC";
+    fileMatrixTrain += ".root";
+    gLog << "fileMatrixTrain = " << fileMatrixTrain << endl; 
+
+    // for testing
+    TString fileMatrixTest = outPath;
+    fileMatrixTest += "MatrixTestSC";
+    fileMatrixTest += ".root";
+    gLog << "fileMatrixTest = " << fileMatrixTest << endl; 
+
+    
+
+    //---------------------------------------------------------------------
+    // Training and test matrices :
+    // - either create them and write them onto a file
+    // - or read them from a file
+
+
+    MCT1FindSupercuts findsuper;
+    findsuper.SetFilenameParam(parSCfile);
+    findsuper.SetHadronnessName("HadSC");
+    //findsuper.SetUseOrigDistribution(kTRUE);
+
+    //--------------------------
+    // create matrices and write them onto files 
+    if (CMatrix)
+    {
+      TString mname("costheta");
+      MBinning bin("Binning"+mname);
+      bin.SetEdges(10, 0., 1.0);
+
+      MH3 mh3("cos(MMcEvt.fTelescopeTheta)");
+      mh3.SetName(mname);
+      MH::SetBinning(&mh3.GetHist(), &bin);
+      //for (Int_t i=1; i<=mh3.GetNbins(); i++)
+      //  mh3.GetHist().SetBinContent(i, 1.0);
+
+
+      if (filenameTrain == filenameTest)
+      {
+        if ( !findsuper.DefineTrainTestMatrix(
+                              filenameTrain,   mh3, 
+                              howManyTrain,    howManyTest,  
+                              fileMatrixTrain, fileMatrixTest)     )
+        {
+          *fLog << "CT1Analysis.C : DefineTrainTestMatrix failed" << endl;
+          return;
+        }
+
+      }
+      else
+      {
+        if ( !findsuper.DefineTrainMatrix(filenameTrain, mh3,
+                                          howManyTrain,  fileMatrixTrain) )
+        {
+          *fLog << "CT1Analysis.C : DefineTrainMatrix failed" << endl;
+          return;
+        }
+
+	if ( !findsuper.DefineTestMatrix( filenameTest, mh3, 
+                                          howManyTest,  fileMatrixTest)  )
+        {
+          *fLog << "CT1Analysis.C : DefineTestMatrix failed" << endl;
+          return;
+        }
+      }
+     }
+
+    //--------------------------
+    // read matrices from files
+    //                              
+
+    if (RMatrix)
+      findsuper.ReadMatrix(fileMatrixTrain, fileMatrixTest);
+    //--------------------------
+
+
+
+    //---------------------------------------------------------------------
+    // optimize supercuts using the training sample
+    // 
+    // the initial values are taken 
+    //     - from the file parSCinit (if != "")
+    //     - or from the arrays params and steps (if their sizes are != 0)
+    //     - or from the MCT1Supercuts constructor
+
+
+if (WOptimize)
+  {
+    gLog << "CT1Analysis.C : optimize the supercuts using the training matrix" 
+         << endl;
+
+    TArrayD params(0);
+    TArrayD steps(0);
+  
+    if (parSCinit == "")
+    {
+      Double_t vparams[104] = {
+      // LengthUp
+	0.315585,  0.001455, 0.203198, 0.005532, -0.001670, -0.020362,
+	0.007388, -0.013463,
+      // LengthLo
+        0.151530,  0.028323, 0.510707, 0.053089,  0.013708,  2.357993,
+	0.000080, -0.007157,
+      // WidthUp
+        0.145412, -0.001771, 0.054462, 0.022280, -0.009893,  0.056353,
+        0.020711, -0.016703,
+      // WidthLo
+        0.089187, -0.006430, 0.074442, 0.003738, -0.004256, -0.014101,
+        0.006126, -0.002849,
+      // DistUp
+        1.787943,  0.0,      2.942310, 0.199815,  0.0,       0.249909,
+        0.189697,  0.0,
+      // DistLo
+        0.589406,  0.0,     -0.083964,-0.007975,  0.0,       0.045374,
+       -0.001750,  0.0,
+      // AsymUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up
+        1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo
+       -1.e10,     0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp
+	13.12344,  0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+      Double_t vsteps[104] = {
+      // LengthUp
+        0.03,      0.0002,   0.02,     0.0006,    0.0002,    0.002,
+        0.0008,    0.002,
+      // LengthLo
+        0.02,      0.003,    0.05,     0.006,     0.002,     0.3,
+        0.0001,    0.0008,
+      // WidthUp
+        0.02,      0.0002,   0.006,    0.003,     0.002,     0.006,
+        0.002,     0.002,
+      // WidthLo
+        0.009,     0.0007,   0.008,    0.0004,    0.0005,    0.002,
+        0.0007,    0.003,
+      // DistUp
+        0.2,       0.0,      0.3,      0.02,      0.0,       0.03,
+        0.02,      0.0
+      // DistLo
+        0.06,      0.0,      0.009,    0.0008,    0.0,       0.005,
+        0.0002,    0.0
+      // AsymUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AsymLo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // ConcLo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Up  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // Leakage1Lo  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0,
+      // AlphaUp  
+        0.0,       0.0,      0.0,      0.0,       0.0,       0.0,
+        0.0,       0.0                                                 };
+
+      params.Set(104, vparams);
+      steps.Set (104, vsteps );
+    }
+
+    Bool_t rf;
+    rf = findsuper.FindParams(parSCinit, params, steps);
+
+    if (!rf) 
+    {
+       gLog << "CT1Analysis.C : optimization of supercuts failed" << endl;
+       return;
+    }
+  }
+
+    //--------------------------------------
+    // test the supercuts on the test sample
+    //    
+
+ if (RTest)
+ {
+    gLog << "CT1Analysis.C : test the supercuts on the test matrix" << endl;
+    Bool_t rt = findsuper.TestParams();
+    if (!rt) 
+    {
+       gLog << "CT1Analysis.C : test of supercuts on the test matrix failed" 
+            << endl;
+    }
+
+ }
+
+
+    //-----------------------------------------------------------------
+    // Update the input files with the SC hadronness
+    //
+
+ if (WSC)
+ {
+    gLog << "" << endl;
+    gLog << "========================================================" << endl;
+    gLog << "Update input file '" <<  filenameData 
+         << "' with the SC hadronness" << endl;
+
+
+    //----------------------------------------------------
+    // read in optimum parameter values for the supercuts
+
+    TFile inparam(parSCfile);
+    MCT1Supercuts scin;
+    scin.Read("MCT1Supercuts");
+    inparam.Close();
+
+    gLog << "Parameter values for supercuts were read in from file '"
+         << parSCfile << "'" << endl;
+
+    TArrayD supercutsPar;
+    supercutsPar =  scin.GetParameters();
+
+    TArrayD supercutsStep;
+    supercutsStep =  scin.GetStepsizes();
+
+    gLog << "Parameter values for supercuts : " << endl;
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+    {
+      gLog << supercutsPar[i] << ",  ";
+    }
+    gLog << endl;
+
+    gLog << "Step values for supercuts : " << endl;
+    for (Int_t i=0; i<supercutsStep.GetSize(); i++)
+    {
+      gLog << supercutsStep[i] << ",  ";
+    }
+    gLog << endl;
+
+
+    //----------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    // set the parameters of the supercuts
+    MCT1Supercuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+    gLog << "parameter values for the supercuts used for updating the input file ' " 
+         << filenameData << "'" << endl;
+    supercutsPar = supercuts.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+    {
+      gLog << supercutsPar[i] << ",  ";
+    }
+    gLog << endl;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+    //.......................................................................
+    // calculation of hadroness for the supercuts
+    // (=0.25 if fullfilled, =0.75 otherwise)
+
+    TString hadSCName = "HadSC";
+    MCT1SupercutsCalc sccalc(fHilName, fHilNameSrc);
+    sccalc.SetHadronnessName(hadSCName);
+
+
+    //.......................................................................
+
+
+      //MWriteRootFile write(outNameImage, "UPDATE");
+      //MWriteRootFile write = new MWriteRootFile(outNameImage, "RECREATE");
+
+    
+      MWriteRootFile write(outNameImage, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      write.AddContainer("HadRF",         "Events");
+      write.AddContainer(hadSCName,       "Events");
+    
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    Float_t maxhadronness =  0.40;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadSCName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillhadsc("hadSC[MHHadronness]", hadSCName);
+    fillhadsc.SetName("HhadSC");
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadSCName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+
+    TH1  &alphahist = alphaabs->GetHist();
+
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(&supercuts);
+
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&sccalc);
+    tliston.AddToList(&fillhadsc);
+
+    tliston.AddToList(&write);
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+     //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-macro");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << filenameData << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+    DeleteBinnings(&pliston);
+ }
+
+
+    gLog << "Macro CT1Analysis : End of Job B_SC_UP" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+
+  //---------------------------------------------------------------------
+  // Job C  
+  //======
+
+    //  - read ON1 and MC1 data files  
+    //    which should have been updated to contain the hadronnesses
+    //    for the method of Random Forest and for the SUPERCUTS
+    //  - produce Neyman-Pearson plots
+ 
+ if (JobC)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job C" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobC = " 
+         << (JobC ? "kTRUE" : "kFALSE")  << endl;
+
+
+
+    TString ext("2.root");
+    TString extout("2.root");
+
+    TString typeHadrons("OFF");
+    TString typeGammas("MC");
+
+    //--------------------------------------------
+    // name of input data file
+    TString NameData = outPath;
+    NameData += typeHadrons;
+    TString inNameData(NameData);
+    inNameData += ext;
+    gLog << "inNameData   = " << inNameData   << endl;
+
+    // name of input MC file
+    TString NameMC = outPath;
+    NameMC += typeGammas;
+    TString inNameMC(NameMC);
+    inNameMC += ext;
+    gLog << "inNameMC   = " << inNameMC   << endl;
+
+
+    //--------------------------------------------
+    // root files for the training events 
+
+
+
+    TString NameGammasTrain = outPath;
+    NameGammasTrain += "RF_gammas_Train_";
+    NameGammasTrain += typeGammas;
+    TString outNameGammasTrain(NameGammasTrain);    
+    outNameGammasTrain += extout;
+
+
+    TString NameHadronsTrain = outPath;
+    NameHadronsTrain += "RF_hadrons_Train_";
+    NameHadronsTrain += typeHadrons;
+    TString outNameHadronsTrain(NameHadronsTrain);    
+    outNameHadronsTrain += extout;
+
+
+    //--------------------------------------------
+    // root files for the test events 
+
+    TString NameGammasTest = outPath;
+    NameGammasTest += "RF_gammas_Test_";
+    NameGammasTest += typeGammas;
+    TString outNameGammasTest(NameGammasTest);    
+    outNameGammasTest += extout;
+
+    TString NameHadronsTest = outPath;
+    NameHadronsTest += "RF_hadrons_Test_";
+    NameHadronsTest += typeHadrons;
+    TString outNameHadronsTest(NameHadronsTest);    
+    outNameHadronsTest += extout;
+
+    //--------------------------------------------------------------------
+
+    //TString filenameData(inNameData);
+    //TString filenameMC(inNameMC);
+
+    //TString filenameData(outNameHadronsTrain);
+    //TString filenameMC(outNameGammasTrain);
+
+    TString filenameData(outNameHadronsTest);
+    TString filenameMC(outNameGammasTest);
+
+    gLog << "filenameData = " << filenameData << endl;
+    gLog << "filenameMC   = " << filenameMC   << endl;
+
+    //-----------------------------------------------------------------
+
+    MTaskList tliston;
+    MParList pliston;
+
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameMC);
+    read.AddFile(filenameData);
+    read.DisableAutoScheme();
+
+
+    //.......................................................................
+    // names of hadronness containers
+
+    TString hadSCName = "HadSC";
+    TString hadRFName = "HadRF";
+
+    //.......................................................................
+
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+    Float_t maxhadronness =  0.40;
+    Float_t maxalpha      =  20.0;
+    Float_t maxdist       =  10.0;
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(hadRFName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+
+    //MFillH fillhadsc("hadSC[MHHadronness]", hadSCName);
+    //fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", hadRFName);
+    fillhadrf.SetName("HhadRF");
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(hadRFName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",    fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+    
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    //tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+   
+    tliston.AddToList(&contfinalgh);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 35000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    //pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro CT1Analysis : End of Job C" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+
+
+  //---------------------------------------------------------------------
+  // Job D
+  //======
+
+    //  - select g/h separation method XX
+    //  - read ON2 (or MC2) root file 
+    //  - apply cuts in hadronness
+    //  - make plots
+
+
+ if (JobD)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job D" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobD = " 
+         << (JobD        ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // type of data to be analysed
+    TString typeData = "ON";
+    //TString typeData = "OFF";
+    //TString typeData = "MC";
+    gLog << "typeData = " << typeData << endl;
+
+    TString ext      = "3.root";
+
+
+    //------------------------------
+    // selection of g/h separation method
+    // and definition of final selections
+
+    //TString XX("SC");
+    TString XX("RF");
+    TString fhadronnessName("Had");
+    fhadronnessName += XX;
+    gLog << "fhadronnessName = " << fhadronnessName << endl;
+
+    // maximum values of the hadronness, |ALPHA| and DIST
+    Float_t maxhadronness   = 0.233;
+    Float_t maxalpha        = 20.0;
+    Float_t maxdist         = 10.0;
+    gLog << "Maximum values of hadronness, |ALPHA| and DIST = "
+         << maxhadronness << ",  " << maxalpha << ",  " 
+         << maxdist << endl;
+
+
+    //------------------------------
+    // name of data file to be analysed
+    TString filenameData(outPath);
+    filenameData += typeData;
+    filenameData += ext;
+    gLog << "filenameData = " << filenameData << endl;
+
+
+
+    //*************************************************************************
+    //
+    // Analyse the data
+    //
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(fhadronnessName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    MFillH fillhadsc("hadSC[MHHadronness]", "HadSC");
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", "HadRF");
+    fillhadrf.SetName("HhadRF");
+
+    TString mh3name = "abs(Alpha)";
+    MBinning binsalphaabs("Binning"+mh3name);
+    binsalphaabs.SetEdges(50, -2.0, 98.0);
+
+    MH3 alphaabs("abs(MHillasSrc.fAlpha)");
+    alphaabs.SetName(mh3name);
+
+    TH1  &alphahist = alphaabs->GetHist();
+
+    MFillH alpha(&alphaabs);
+    alpha.SetName("FillAlphaAbs");
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");    
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");    
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(fhadronnessName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+    pliston.AddToList(&binsalphaabs);
+    pliston.AddToList(&alphaabs);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    tliston.AddToList(&contfinalgh);
+
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&alpha);
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 10000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+
+    //-------------------------------------------
+
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    MH3* absalpha = (MH3*)(pliston.FindObject(mh3name, "MH3"));
+    TH1  &alphaHist = absalpha->GetHist();
+    alphaHist.SetXTitle("|alpha|  [\\circ]");
+    alphaHist.SetName("alpha-JobD");
+
+    Double_t alphasig = 13.1;
+    Double_t alphamin = 30.0;
+    Double_t alphamax = 90.0;
+    Int_t    degree   =    2;
+    Double_t significance = -99.0;
+    Bool_t   drawpoly  = kTRUE;
+    Bool_t   fitgauss  = kTRUE;
+    Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist, alphamin, alphamax, degree, 
+                        alphasig, drawpoly, fitgauss, print);
+    significance = findsig.GetSignificance();
+    Float_t alphasi = findsig.GetAlphasi();
+
+    gLog << "For file '" << filenameData << "' : " << endl;
+    gLog << "Significance of gamma signal after supercuts : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+
+    findsig.SigmaVsAlpha(&alphaHist, alphamin, alphamax, degree, print);
+
+    //-------------------------------------------
+
+
+    DeleteBinnings(&pliston);
+
+    gLog << "Macro CT1Analysis : End of Job D" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+
+
+
+
+  //---------------------------------------------------------------------
+  // Job E_XX
+  //=========
+
+    //  - select g/h separation method XX
+    //  - read MC_XX2.root file 
+    //  - calculate eff. collection area
+    //  - read ON_XX2.root file 
+    //  - apply final cuts
+    //  - calculate flux
+    //  - write root file for ON data after final cuts (ON_XX3.root))
+
+
+ if (JobE_XX)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro CT1Analysis : Start of Job E_XX" << endl;
+
+    gLog << "" << endl;
+    gLog << "Macro CT1Analysis : JobE_XX, CCollArea, OEEst, WEX = " 
+         << (JobE_XX ? "kTRUE" : "kFALSE")  << ",  " 
+         << (CCollArea?"kTRUE" : "kFALSE")  << ",  " 
+         << (OEEst ?   "kTRUE" : "kFALSE")  << ",  " 
+         << (WEX     ? "kTRUE" : "kFALSE")  << endl;
+
+
+    // type of data to be analysed
+    //TString typeData = "ON";
+    //TString typeData = "OFF";
+    TString typeData = "MC";
+    gLog << "typeData = " << typeData << endl;
+
+    TString typeMC   = "MC";
+    TString ext      = "3.root";
+    TString extout   = "4.root";
+
+    //------------------------------
+    // selection of g/h separation method
+    // and definition of final selections
+
+    //TString XX("SC");
+    TString XX("RF");
+    TString fhadronnessName("Had");
+    fhadronnessName += XX;
+    gLog << "fhadronnessName = " << fhadronnessName << endl;
+
+    // maximum values of the hadronness, |ALPHA| and DIST
+    Float_t maxhadronness   = 0.23;
+    Float_t maxalpha        = 20.0;
+    Float_t maxdist         = 10.0;
+    gLog << "Maximum values of hadronness, |ALPHA| and DIST = "
+         << maxhadronness << ",  " << maxalpha << ",  " 
+         << maxdist << endl;
+
+    //------------------------------
+    // name of MC file to be used for optimizing the energy estimator
+    TString filenameOpt(outPath);
+    filenameOpt += typeMC;
+    filenameOpt += ext; 
+    gLog << "filenameOpt = " << filenameOpt << endl;
+
+    //------------------------------
+    // name of file containing the parameters of the energy estimator
+    TString energyParName(outPath);
+    energyParName += "energyest_";
+    energyParName += XX;
+    energyParName += ".root";
+    gLog << "energyParName = " << energyParName << endl;
+
+    //------------------------------
+    // name of MC file to be used for calculating the eff. collection areas
+    TString filenameArea(outPath);
+    filenameArea += typeMC;
+    filenameArea += ext; 
+    gLog << "filenameArea = " << filenameArea << endl;
+
+    //------------------------------
+    // name of file containing the eff. collection areas
+    TString collareaName(outPath);
+    collareaName += "area_";
+    collareaName += XX;
+    collareaName += ".root";
+    gLog << "collareaName = " << collareaName << endl;
+
+    //------------------------------
+    // name of data file to be analysed
+    TString filenameData(outPath);
+    filenameData += typeData;
+    filenameData += ext;
+    gLog << "filenameData = " << filenameData << endl;
+
+    //------------------------------
+    // name of output data file (after the final cuts)
+    TString filenameDataout(outPath);
+    filenameDataout += typeData;
+    filenameDataout += "_";
+    filenameDataout += XX;
+    filenameDataout += extout;
+    gLog << "filenameDataout = " << filenameDataout << endl;
+
+    //------------------------------
+    // name of file containing histograms for flux calculastion
+    TString filenameResults(outPath);
+    filenameResults += typeData;
+    filenameResults += "Results_";
+    filenameResults += XX;
+    filenameResults += extout;
+    gLog << "filenameResults = " << filenameResults << endl;
+
+
+    //====================================================================
+
+    MHMcCT1CollectionArea collarea;
+    collarea.SetEaxis(MHMcCT1CollectionArea::kLinear);
+
+    MParList  parlist;
+    InitBinnings(&parlist);
+
+  if (CCollArea)
+  {
+    gLog << "-----------------------------------------------" << endl;
+    gLog << "Start calculation of effective collection areas" << endl;
+
+
+    MTaskList tasklist;
+
+    //---------------------------------------
+    // Setup the tasks to be executed
+    //
+    MReadMarsFile reader("Events", filenameArea);
+    reader.DisableAutoScheme();
+
+    MFCT1SelFinal cuthadrons;
+    cuthadrons.SetHadronnessName(fhadronnessName);
+    cuthadrons.SetCuts(maxhadronness, maxalpha, maxdist);
+
+    MContinue conthadrons(&cuthadrons);
+
+
+    MFillH filler("MHMcCT1CollectionArea", "MMcEvt");
+    filler.SetName("CollectionArea");
+
+    //********************************
+    // entries in MParList
+
+    parlist.AddToList(&tasklist);
+
+    parlist.AddToList(&collarea);
+
+    //********************************
+    // entries in MTaskList
+
+    tasklist.AddToList(&reader);   
+    tasklist.AddToList(&conthadrons);
+    tasklist.AddToList(&filler);
+
+    //********************************
+
+    //-----------------------------------------
+    // Execute event loop
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    MProgressBar bar;
+    magic.SetProgressBar(&bar);
+    if (!magic.Eventloop())
+        return;
+
+    tasklist.PrintStatistics(0, kTRUE);
+
+    // Calculate effective collection areas 
+    // and display the histograms
+    //
+    //MHMcCT1CollectionArea *collarea = 
+    //     (MHMcCT1CollectionArea*)parlist.FindObject("MHMcCT1CollectionArea");
+    collarea.CalcEfficiency();
+    collarea.DrawClone();
+
+
+
+    //---------------------------------------------
+    // Write histograms to a file 
+    //
+
+    TFile f(collareaName, "RECREATE");
+    //collarea.GetHist()->Write();
+    //collarea.GetHAll()->Write();
+    //collarea.GetHSel()->Write();
+    collarea.Write();
+
+    f.Close();
+
+    gLog << "Collection area plots written onto file " << collareaName << endl;
+
+    gLog << "Calculation of effective collection areas done" << endl;
+    gLog << "-----------------------------------------------" << endl;    
+    //------------------------------------------------------------------
+  }
+
+  if (!CCollArea)
+  {
+    gLog << "-----------------------------------------------" << endl;
+    gLog << "Read in effective collection areas from file " 
+         << collareaName << endl;
+
+    TFile collfile(collareaName);
+    collfile.ls();
+    collarea.Read("MHMcCT1CollectionArea");
+    collarea.DrawClone();
+
+    gLog << "Effective collection areas were read in from file " 
+         << collareaName << endl;
+    gLog << "-----------------------------------------------" << endl;    
+  }
+
+
+    // save binnings for call to CT1EEst
+    MBinning *binsE     = (MBinning*)parlist.FindObject("BinningE");
+    if (!binsE)
+	{
+          gLog << "Object 'BinningE' not found in MParList" << endl;
+          return;
+	}
+    MBinning *binsTheta = (MBinning*)parlist.FindObject("BinningTheta");
+    if (!binsTheta)
+	{
+          gLog << "Object 'BinningTheta' not found in MParList" << endl;
+          return;
+	}
+
+    //-------------------------------------
+    TString fHilName    = "MHillas"; 
+    TString fHilNameExt = "MHillasExt"; 
+    TString fHilNameSrc = "MHillasSrc"; 
+    TString fImgParName = "MNewImagePar"; 
+
+
+ if (OEEst)
+ { 
+   //===========================================================
+    //
+    // Optimization of energy estimator
+    //
+    gLog << "Macro CT1Analysis.C : calling CT1EEst" << endl;
+
+    TString inpath("");
+    TString outpath("");
+    Int_t howMany = 2000;
+    CT1EEst(inpath,   filenameOpt,   outpath, energyParName, 
+            fHilName, fHilNameSrc,   fhadronnessName,
+            howMany,  maxhadronness, maxalpha, maxdist,
+            binsE, binsTheta);
+    gLog << "Macro CT1Analysis.C : returning from CT1EEst" << endl;
+ }
+
+ if (WEX)
+ {
+    //-----------------------------------------------------------
+    //
+    // Read in parameters of energy estimator ("MMcEnergyEst")
+    //                   and migration matrix ("MHMcEnergyMigration")
+    //
+    gLog << "================================================================"
+         << endl;
+    gLog << "Macro CT1Analysis.C : read parameters of energy estimator and migration matrix from file '"
+         << energyParName << "'" << endl;
+    TFile enparam(energyParName);
+    enparam.ls();
+    MMcEnergyEst mcest("MMcEnergyEst"); 
+    mcest.Read("MMcEnergyEst");
+
+    //MMcEnergyEst &mcest = *((MMcEnergyEst*)gROOT->FindObject("MMcEnergyEst"));
+    gLog << "Parameters of energy estimator were read in" << endl;
+
+
+    gLog << "Read in Migration matrix" << endl;   
+
+    MHMcEnergyMigration mighiston("MHMcEnergyMigration");
+    mighiston.Read("MHMcEnergyMigration");
+    //MHMcEnergyMigration &mighiston = 
+    //      *((MHMcEnergyMigration*)gROOT->FindObject("MHMcEnergyMigration"));
+
+    gLog << "Migration matrix was read in" << endl;
+
+
+    TArrayD parA(mcest.GetNumCoeffA());
+    TArrayD parB(mcest.GetNumCoeffB());
+    for (Int_t i=0; i<parA.GetSize(); i++)
+      parA[i] = mcest.GetCoeff(i);
+    for (Int_t i=0; i<parB.GetSize(); i++)
+      parB[i] = mcest.GetCoeff( i+parA.GetSize() );
+
+    //*************************************************************************
+    //
+    // Analyse the data
+    //
+    gLog << "============================================================"
+         << endl;
+    gLog << "Analyse the data" << endl;
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenameData);
+    read.DisableAutoScheme();
+
+    //.......................................................................
+
+      gLog << "CT1Analysis.C : write root file '" << filenameDataout 
+           << "'" << endl;
+   
+      //MWriteRootFile &write = *(new MWriteRootFile(filenameDataout));
+
+
+      MWriteRootFile write(filenameDataout, "RECREATE");
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MMcEvt",        "Events");
+      write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+
+      //write.AddContainer("HadNN",         "Events");
+      write.AddContainer("HadSC",         "Events");
+      write.AddContainer("HadRF",         "Events");
+
+      write.AddContainer("MEnergyEst",    "Events");
+
+
+    //-----------------------------------------------------------------
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamCT1", "MGeomCam");
+
+    MFCT1SelFinal selfinalgh(fHilNameSrc);
+    selfinalgh.SetCuts(maxhadronness, 100.0, maxdist);
+    selfinalgh.SetHadronnessName(fhadronnessName);
+    selfinalgh.SetName("SelFinalgh");
+    MContinue contfinalgh(&selfinalgh);
+    contfinalgh.SetName("ContSelFinalgh");
+
+    //MFillH fillhadnn("hadNN[MHHadronness]", "HadNN");
+    //fillhadnn.SetName("HhadNN");
+    MFillH fillhadsc("hadSC[MHHadronness]", "HadSC");
+    fillhadsc.SetName("HhadSC");
+    MFillH fillhadrf("hadRF[MHHadronness]", "HadRF");
+    fillhadrf.SetName("HhadRF");
+
+    //---------------------------
+    // calculate estimated energy
+
+    MEnergyEstParam eeston(fHilName);
+    eeston.Add(fHilNameSrc);
+
+    eeston.SetCoeffA(parA);
+    eeston.SetCoeffB(parB);
+
+    //---------------------------
+    // calculate estimated energy using Daniel's parameters
+
+    //MEnergyEstParamDanielMkn421 eeston(fHilName);
+    //eeston.Add(fHilNameSrc);
+    //eeston.SetCoeffA(parA);
+    //eeston.SetCoeffB(parB);
+
+
+    //---------------------------
+
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");    
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");    
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");    
+
+    //---------------------------
+    // new from Robert
+
+    MFillH hfill6("MHTimeDiffTheta", "MMcEvt");
+    hfill6.SetName("HTimeDiffTheta");
+
+    MFillH hfill6a("MHTimeDiffTime", "MMcEvt");
+    hfill6a.SetName("HTimeDiffTime");
+
+    MFillH hfill7("MHAlphaEnergyTheta", fHilNameSrc);
+    hfill7.SetName("HAlphaEnergyTheta");
+
+    MFillH hfill7a("MHAlphaEnergyTime", fHilNameSrc);
+    hfill7a.SetName("HAlphaEnergyTime");
+
+    MFillH hfill7b("MHThetabarTime", fHilNameSrc);
+    hfill7b.SetName("HThetabarTime");
+
+    MFillH hfill7c("MHEnergyTime", "MMcEvt");
+    hfill7c.SetName("HEnergyTime");
+
+
+    //---------------------------
+
+    MFCT1SelFinal selfinal(fHilNameSrc);
+    selfinal.SetCuts(maxhadronness, maxalpha, maxdist);
+    selfinal.SetHadronnessName(fhadronnessName);
+    selfinal.SetName("SelFinal");
+    MContinue contfinal(&selfinal);
+    contfinal.SetName("ContSelFinal");
+
+
+    //*****************************
+    // entries in MParList
+
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    // robert      
+    tliston.AddToList(&hfill6);   //timediff
+    tliston.AddToList(&hfill6a);   //timediff
+
+    tliston.AddToList(&contfinalgh);
+    tliston.AddToList(&eeston);
+
+    tliston.AddToList(&write);
+
+    //tliston.AddToList(&fillhadnn);
+    tliston.AddToList(&fillhadsc);
+    tliston.AddToList(&fillhadrf);
+
+    tliston.AddToList(&hfill1);
+    tliston.AddToList(&hfill2);
+    tliston.AddToList(&hfill3);
+    tliston.AddToList(&hfill4);
+    tliston.AddToList(&hfill5);
+
+    //robert
+    tliston.AddToList(&hfill7);
+    tliston.AddToList(&hfill7a);
+    tliston.AddToList(&hfill7b);
+    tliston.AddToList(&hfill7c);
+
+    tliston.AddToList(&contfinal);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxevents = -1;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+    //
+
+    //pliston.FindObject("hadNN", "MHHadronness")->DrawClone();
+
+    gLog << "before hadRF" << endl;
+    pliston.FindObject("hadRF", "MHHadronness")->DrawClone();
+
+    gLog << "before hadSC" << endl;
+    pliston.FindObject("hadSC", "MHHadronness")->DrawClone();
+
+    gLog << "before MHHillas" << endl;
+    pliston.FindObject("MHHillas")->DrawClone();
+
+    gLog << "before MHHillasExt" << endl;
+    pliston.FindObject("MHHillasExt")->DrawClone();
+
+    gLog << "before MHHillasSrc" << endl;
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+
+    gLog << "before MHNewImagePar" << endl;
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+
+    gLog << "before MHStarMap" << endl;
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    gLog << "before DeleteBinnings" << endl;
+
+    DeleteBinnings(&pliston);
+
+    gLog << "before Robert's code" << endl;
+
+
+//rwagner write all relevant histograms onto a file
+
+  if (WRobert)
+  {
+    gLog << "=======================================================" << endl;
+    gLog << "Write results onto file '" << filenameResults << "'" << endl;
+
+    TFile outfile(filenameResults,"recreate");
+
+    MHHillasSrc* hillasSrc = 
+      (MHHillasSrc*)(pliston->FindObject("MHHillasSrc"));
+        TH1F* alphaHist = (TH1F*)(hillasSrc->GetHistAlpha());
+    alphaHist->Write();
+    gLog << "Alpha plot has been written out" << endl;    
+
+
+    MHAlphaEnergyTheta* aetH = 
+      (MHAlphaEnergyTheta*)(pliston->FindObject("MHAlphaEnergyTheta"));
+    TH3D* aetHist = (TH3D*)(aetH->GetHist());
+    aetHist->SetName("aetHist");
+    aetHist->Write();
+    gLog << "AlphaEnergyTheta plot has been written out" << endl;    
+
+    MHAlphaEnergyTime* aetH2 = 
+      (MHAlphaEnergyTime*)(pliston->FindObject("MHAlphaEnergyTime"));
+    TH3D* aetHist2 = (TH3D*)(aetH2->GetHist());
+    aetHist2->SetName("aetimeHist");
+//     aetHist2->DrawClone();
+    aetHist2->Write();
+    gLog << "AlphaEnergyTime plot has been written out" << endl;    
+
+    MHThetabarTime* tbt = 
+      (MHThetabarTime*)(pliston->FindObject("MHThetabarTime"));
+    TProfile* tbtHist = (TProfile*)(tbt->GetHist());
+    tbtHist->SetName("tbtHist");
+    tbtHist->Write();
+    gLog << "ThetabarTime plot has been written out" << endl;    
+
+    MHEnergyTime* ent = 
+      (MHEnergyTime*)(pliston->FindObject("MHEnergyTime"));
+    TH2D* entHist = (TH2D*)(ent->GetHist());
+    entHist->SetName("entHist");
+    entHist->Write();
+    gLog << "EnergyTime plot has been written out" << endl;    
+    
+    MHTimeDiffTheta *time = (MHTimeDiffTheta*)pliston.FindObject("MHTimeDiffTheta");
+    TH2D* timeHist = (TH2D*)(time->GetHist());
+    timeHist->SetName("MHTimeDiffTheta");
+    timeHist->SetTitle("Time diffs");
+    timeHist->Write();
+    gLog << "TimeDiffTheta plot has been written out" << endl;    
+
+
+    MHTimeDiffTime *time2 = (MHTimeDiffTime*)pliston.FindObject("MHTimeDiffTime");
+    TH2D* timeHist2 = (TH2D*)(time2->GetHist());
+    timeHist2->SetName("MHTimeDiffTime");
+    timeHist2->SetTitle("Time diffs");
+    timeHist2->Write();
+    gLog << "TimeDiffTime plot has been written out" << endl;    
+
+//rwagner write also collareas to same file
+    collarea->GetHist()->Write();
+    collarea->GetHAll()->Write();
+    collarea->GetHSel()->Write();
+    gLog << "Effective collection areas have been written out" << endl;        
+
+//rwagner todo: write alpha_cut, type of g/h sep (RF, SC, NN), type of data
+//rwagner (ON/OFF/MC), MJDmin, MJDmax to this file
+
+    gLog << "before closing outfile" << endl;
+
+    //outfile.Close();
+    gLog << "Results were written onto file '" << filenameResults 
+         << "'" << endl;
+    gLog << "=======================================================" << endl;
+  }
+
+  }
+
+    gLog << "Macro CT1Analysis : End of Job E_XX" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/PedCalcFromData.C
===================================================================
--- /tags/Mars-V0.9/macros/PedCalcFromData.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/PedCalcFromData.C	(revision 9772)
@@ -0,0 +1,200 @@
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// Description: Macro that uses MPedCalcFromData to evaluate Pedestals from//
+//              Data Runs.                                                 //
+// Author:      Josep Flix (jflix@ifae.es)                                 //
+// Date:        25/06/2004                                                 //
+//                                                                         // 
+/////////////////////////////////////////////////////////////////////////////
+
+void PedCalcFromData()
+{
+
+    gROOT->Reset();
+    gStyle->SetCanvasColor(0);
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetPadBorderMode(0);
+    gStyle->SetFrameBorderMode(0);
+    gStyle->SetOptStat(0000000);
+    gStyle->SetPalette(1);
+
+    TString pedfile("20040422_23229_P_Mrk421_E.root");
+    TString datafile("20040422_23230_D_Mrk421_E.root");
+    
+    gStyle->SetOptFit(0);
+    gStyle->SetOptStat(0000);
+    
+    MParList       plist;
+    MTaskList      tlist;
+    
+    MPedestalCam   cam;  
+    plist.AddToList(&cam);
+    
+    plist.AddToList(&tlist);
+    
+    MReadMarsFile read("Events", "/home/pepe/DATA_REAL/Mkn421/"+pedfile);
+    read.DisableAutoScheme();    
+    MGeomApply      geomapl;
+    MExtractFixedWindow    extractor;   
+    extractor.SetRange(2,14,4,14);
+   
+    MPedCalcPedRun ped;
+    ped.SetWindowSize(12);
+    ped.SetRange(2,14);
+    
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&ped); 
+    
+    MEvtLoop evtloop;
+    
+    if (!tlist.PreProcess(&plist))
+	return;
+    
+    while (tlist.Process())
+    {
+    }
+    tlist.PostProcess();     
+    
+    
+    // ---------------------------------------------------------------
+    // 2nd evt loop
+    // ---------------------------------------------------------------
+
+    c1 = new TCanvas("c1","c1",0,0,600,300);
+    c1->Divide(2,1);
+    c1->SetBorderMode(0);
+    
+    TH2D *plot1 = new TH2D("","",1,0.1,175000,1,8,15);
+    TH2D *plot2 = new TH2D("","",1,0.1,175000,1,1,40);
+    c1->cd(1);
+    plot1->Draw();
+    c1->cd(2);
+    plot2->Draw();
+
+    Int_t COUNT=0;
+    
+    for (int j = 0; j < 6 ; j++){
+
+	if (j == 1)
+	    TString datafile("20040422_23231_D_Mrk421_E.root");
+	if (j == 2)
+	    TString datafile("20040422_23233_D_Mrk421_E.root");
+	if (j == 3)
+	    TString datafile("20040422_23234_D_Mrk421_E.root");
+	if (j == 4)
+	    TString datafile("20040422_23236_D_Mrk421_E.root");
+	if (j == 5)
+	    TString datafile("20040422_23237_D_Mrk421_E.root");
+
+	MParList  plist2;
+	MTaskList tlist2;
+	plist2.AddToList(&tlist2);
+	plist2.AddToList(&cam);
+	
+	MGeomCam *geomcam = (MGeomCam*)plist->FindObject("MGeomCam");
+	
+	MReadMarsFile read2("Events");
+	read2.DisableAutoScheme();
+    
+	read2.AddFile("/home/pepe/DATA_REAL/Mkn421/"+datafile);
+	MGeomApply        apply2;
+	
+	MPedCalcFromData  ped2;
+	ped2.SetDumpEvents(500);
+	ped2.SetLoRange(2,14);
+	ped2.SetHighGainThreshold(50);
+	
+	tlist2.AddToList(&read2);
+	tlist2.AddToList(&apply2);
+	tlist2.AddToList(&ped2);
+	
+	MEvtLoop evtloop2;
+	evtloop2.SetParList(&plist2);
+	
+	if (!tlist2.PreProcess(&plist2))
+	    return;
+	
+	TArrayD PedMean[577];
+	TArrayD PedRms[577];
+	for (int i = 0; i < 577 ; i++){
+	    PedMean[i].Set(20001);
+	    PedRms[i].Set(20001);
+	};
+	Double_t x[20001];
+	Double_t y[20001];
+	Int_t Cont = 0;
+	Int_t HOT = 0;
+	
+	while (tlist2.Process())
+	{
+	    
+	    COUNT++;
+	    
+	    if (read2.GetNumExecutions()==1 || read2.GetNumExecutions()%500==0){
+		
+		x[Cont] = COUNT;
+		for (int i = 1; i < 577; i++){
+		    
+		    PedMean[i](Cont) = cam[i]->GetPedestal();
+		    PedRms[i](Cont) = cam[i]->GetPedestalRms();
+		    
+		};
+		Cont++;
+	    };
+//         if (read2.GetNumExecutions() == 5000) break;
+	}
+	
+	tlist2.PostProcess();
+	cout << "EXEC = " << read2.GetNumExecutions() << '\t' << HOT << endl;
+	
+	for (int i = 1; i < 577; i++){
+	    
+	    if ( i == 8 || i ==146 || i ==200 || i ==269 || i==279 || i==400 || i==26 || i==439 || i==490 || i==39){
+		
+		for (int k = 0 ; k < 20000; k++)
+		    y[k] = PedMean[i](k);
+		
+		c1->cd(1);
+		
+		TGraph *graph1 = new TGraph(Cont,x,y);
+		graph1->SetLineColor((int)i/3);
+		graph1->SetMarkerColor((int)i/3);
+		graph1->SetMarkerSize(.4);
+		graph1->SetMarkerStyle(20);
+		graph1->Draw("PL");
+		
+		c1->cd(2);
+		for (int k = 0 ; k < 20000; k++)
+		    y[k] = PedRms[i](k);
+		
+		TGraph *graph2 = new TGraph(Cont,x,y);
+		graph2->SetMarkerSize(.4);
+		graph2->SetLineColor((int)i/3);
+		graph2->SetMarkerStyle(20);
+		graph2->SetMarkerColor((int)i/3);
+		graph2->Draw("PL");
+		
+		Char_t tit[100];
+		sprintf(tit,"Pixel %i",i);
+		TLatex *pix = new TLatex(20000.,38.-1.*HOT,tit);
+		pix->SetTextColor((int)i/3);
+		pix->SetTextSize(.03);
+		pix->Draw("");
+		HOT++;
+	    };
+	    
+	};
+	
+	TLine *line2 = new TLine(x[Cont-1],1.,x[Cont-1],40.);
+	line2->SetLineStyle(2);
+	TLine *line1 = new TLine(x[Cont-1],8.,x[Cont-1],15.);
+	line1->SetLineStyle(2);
+	c1->cd(1);
+	line1->Draw("");
+	c1->cd(2);
+	line2->Draw("");
+	
+    };    
+}
Index: /tags/Mars-V0.9/macros/Pedestals_Stability.C
===================================================================
--- /tags/Mars-V0.9/macros/Pedestals_Stability.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/Pedestals_Stability.C	(revision 9772)
@@ -0,0 +1,147 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): ???
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+ void Pedestals_Stability()
+{
+    char *files[11] = {"ped_stab/stab1.root",
+                      "ped_stab/stab2.root",
+                      "ped_stab/stab3.root",
+                      "ped_stab/stab4.root",
+                      "ped_stab/stab5.root",
+                      "ped_stab/stab6.root",
+                      "ped_stab/stab7.root",
+                      "ped_stab/stab8.root",
+                      "ped_stab/stab9.root",
+                      "ped_stab/stab10.root",
+                      "ped_stab/stab11.root"};
+
+    for (Int_t stab_f=0; stab_f<11; stab_f++){
+
+      MParList plist;
+
+      MPedestalCam  pedest;
+      MTaskList     tlist;
+
+      plist->AddToList(&pedest);
+      plist->AddToList(&tlist);
+
+      MReadTree read("Events", files[stab_f] );
+      MPedCalcPedRun pedcalc;
+
+      tlist.AddToList(&read);
+      tlist.AddToList(&pedcalc);
+
+      MEvtLoop evtloop;
+      evtloop.SetParList(&plist);
+
+      if (!evtloop.PreProcess())
+        return;
+
+      const UInt_t NumEnt = read.GetEntries();
+
+      Float_t pedmeantohist[8][NumEnt];
+      Float_t pedMean[8][11];
+      Float_t pedRMS[8][11];
+
+      Int_t Ecount = 0;
+
+      while (read.Process())
+      {
+
+        pedcalc.Process();
+
+        for (Int_t i=0; i<8; i++){
+          pedmeantohist[i][Ecount] = pedest[i].GetMean();
+        }
+
+	Ecount++;
+
+      } 
+
+      evtloop.PostProcess();
+
+
+    // Create Histogram to get Mean & RMS per 100 pixel events
+ 
+      gROOT->Reset();
+
+      PixelHist = new TH1F("Pixel Hist","Pixel x - Ped hist",100,0,1000);
+
+      cout << files[stab_f] << endl;
+
+      for (Int_t pix=0; pix<8 ; pix++){
+         for (Int_t ev=0; ev<NumEnt; ev++){
+           PixelHist->Fill(pedmeantohist[pix][ev]);
+        }
+     
+	 pedMean[pix][stab_f] = PixelHist->GetMean();
+	 pedRMS[pix][stab_f] = PixelHist->GetRMS();
+
+	 //        cout << "Px" << pix << " - Ped = " 
+	 //	     << PixelHist->GetMean() << " +/- " << PixelHist->GetRMS() << endl;
+
+        PixelHist->Reset();     
+
+      }
+    }
+
+
+    // Plot the results
+
+    // Create the Canvas
+
+    c1 = new TCanvas("c1","Pedestals for all pixels",605,0,600,650);
+    c1->Divide(3,3);
+
+    for (Int_t pix=0; pix<8 ; pix++){
+
+      Float_t Time[11] = {0,51,117,170,229,341,409,475,533,585,643};
+      Float_t Err_Time[11];
+
+      Float_t PedestMeantoGraph[11];
+      Float_t PedestRMStoGraph[11];
+
+      char Title[40];
+
+       for (Int_t ev=0; ev<11; ev++){
+	 PedestMeantoGraph[ev] = pedMean[pix][ev];
+	 PedestRMStoGraph[ev] = pedRMS[pix][ev];
+       }
+       c1->cd(pix+1);
+       gr = new TGraphErrors(11,Time,PedestMeantoGraph,Err_Time,PedestRMStoGraph);
+
+       sprintf(Title,"Pedestal Stability - Pixel %d",pix+1);
+       gr->SetMarkerStyle(20);
+       gr->SetMarkerSize(0.7);
+       gr->SetTitle(Title);
+       gr->Draw("ALP");
+       gr->GetXaxis()->SetTitle("Time (min)");
+       gr->GetYaxis()->SetTitle("ADC Counts");
+       gr->Draw("ALP");
+    
+    }
+    c1->Update();
+
+}
Index: /tags/Mars-V0.9/macros/RFEnergyEst.C
===================================================================
--- /tags/Mars-V0.9/macros/RFEnergyEst.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/RFEnergyEst.C	(revision 9772)
@@ -0,0 +1,265 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck, 02/2005 <mailto:hengsteb@physik.hu-berlin.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// This macro shows you how to use the new class MRFEnergyEst, which is
+// an implementation of energy estimation with RF. It contains following
+// functions:
+//
+//   - CreateMatrices()  : Create matrix for training (and matrix for test)
+//   - RFEnergyEstTrain(): Training of RFs
+//   - ReadForests()     : Read and print out energy bins which have been used
+//                         in training (depence on statistics)
+//
+//   - RFEnergyEstTest() : Fast testing using a matrix with test data
+//   - RFEnergyEstLoop() : Application of RF energy est in eventloop
+//
+////////////////////////////////////////////////////////////////////////////
+
+
+//****************************************************************************
+// main user settings
+//****************************************************************************
+
+//----------------------------------------------------------------------------
+// settings for RF training
+const Int_t ntrees    = 50; // 50-100 is usually sufficient
+const Int_t numtrials = 3;  // should be <= sqrt(no. of used var)
+const Int_t nodesize  = 1;  // best results with 1
+
+// settings for energy grid
+const Int_t ebins   = 30;
+const Float_t e_low = log10(10);    // lower limit of log10(energy[GeV])
+const Float_t e_up  = log10(30000); // upper limit
+
+//----------------------------------------------------------------------------
+// data settings
+TString path="/emc/commich/Mars/mcdata/oldout/";
+
+//TString nameTrain = "19990101_10001_I_MCGamTrainLZA_E_10_5";
+//TString nameTest  = "19990101_10002_I_MCGamTestLZA_E_10_5";
+TString nameTrain = "19990101_10003_I_MCGamTrainHZA_E_10_5";
+TString nameTest  = "19990101_10004_I_MCGamTestHZA_E_10_5" ;
+
+TString info=""; // put here additional info e.g. about cuts used in
+                 // CreateMatrices function
+
+//----------------------------------------------------------------------------
+// generate filenames
+TString fileNameTrain = path + nameTrain + ".root";
+TString fileNameTest  = path + nameTest  + ".root";
+
+TString fileMatrixTrain = nameTrain + "_Matrix" + info + ".root";
+TString fileMatrixTest  = nameTest  + "_Matrix" + info + ".root";
+
+TString fileForest = "EForests" + nameTrain + info + ".root";
+
+
+//****************************************************************************
+//   Create matrices for training (and test)
+//****************************************************************************
+void CreateMatrices()
+{
+    MGeomCamMagic gcam;
+    const Double_t mm2deg=gcam.GetConvMm2Deg();//180./17000./3.14159265358979312;
+
+    TString filename[2]   = {fileNameTrain,fileNameTest};
+    TString filematrix[2] = {fileMatrixTrain,fileMatrixTest};
+
+    for(int i=0;i<2;i++)
+    {
+        if(filename[i].IsNull() || filematrix[i].IsNull())
+            continue;
+
+        MParList  plist;
+        MTaskList tlist;
+        plist.AddToList(&tlist);
+
+        MReadTree  read("Events", filename[i]);
+        read.DisableAutoScheme();
+
+        MHMatrix matrix("MatrixGammas");
+        // setting rules (MC energy must be last column!!!)
+        matrix.AddColumn("log10(MHillas.fSize)");
+        matrix.AddColumn("MHillasSrc.fDist");
+        matrix.AddColumn("MHillas.fWidth");
+        matrix.AddColumn("MHillas.fLength");
+        matrix.AddColumn("log10(MHillas.fSize/(MHillas.fLength*MHillas.fWidth))");
+        matrix.AddColumn("MNewImagePar.fConc");
+        matrix.AddColumn("MNewImagePar.fLeakage1");
+        matrix.AddColumn("MPointingPos.fZd");
+        matrix.AddColumn("MMcEvt.fEnergy");
+
+        plist.AddToList(&matrix);
+        MFillH fillmat("MatrixGammas");
+
+        // pre-cuts on data,
+        // take care that this is inverted logic (MContinue task!!)
+        MContinue sizecut("MHillas.fSize<60.");
+        MContinue leakcut("MNewImagePar.fLeakage1>0.1");
+        MContinue distcutlo(Form("MHillasSrc.fDist*%f<0.3",mm2deg));
+        MContinue distcutup(Form("MHillasSrc.fDist*%f>1.1",mm2deg));
+        MContinue hcut("MHadronness.fHadronness>0.3");
+
+        tlist.AddToList(&read);
+
+        // put cuts into tlist
+        tlist.AddToList(&sizecut);
+        tlist.AddToList(&leakcut);
+        tlist.AddToList(&distcutlo);
+        tlist.AddToList(&distcutup);
+        //tlist.AddToList(&hcut);
+
+        tlist.AddToList(&fillmat);
+
+        MEvtLoop evtloop;
+        evtloop.SetParList(&plist);
+
+        if (!evtloop.Eventloop()) return;
+        tlist.PrintStatistics();
+
+        TFile file(filematrix[i],"recreate","");
+        matrix.Write();
+        file.Close();
+    }
+
+    return;
+}
+
+//****************************************************************************
+//   Training of RFs
+//****************************************************************************
+void RFEnergyEstTrain()
+{
+    // initializations
+    TArrayD egrid(ebins+1);
+
+    for(Int_t i=0;i<=ebins;i++)
+        egrid[i]=e_low+i*(e_up-e_low)/float(ebins);
+
+    MHMatrix matrix;
+    TFile *file=new TFile(fileMatrixTrain);
+    matrix.Read("MatrixGammas");
+
+    // output info about used rules
+    cout<<endl<<"Rules for energy estimation:"<<endl;
+    for(Int_t i=0;i<matrix.GetM().GetNcols();i++)
+    {
+        MDataArray *rules = matrix.GetColumns();
+        MData &data=(*rules)[i];
+
+        cout<<" "<<i+1<<") "<<data.GetRule()<<endl;
+    }
+
+    // setup RF for energy estimation
+    MRFEnergyEst rf;
+    rf.SetMatrixTrain(&matrix);
+    rf.SetFile(fileForest);
+    rf.SetLogEnergyGrid(egrid);
+
+    rf.SetNumTrees(ntrees);  // number of trees
+    rf.SetNumTry(numtrials); // number of trials in random split selection
+    rf.SetNdSize(nodesize);  // limit for nodesize
+
+    rf.Train();
+
+    return;
+}
+
+//****************************************************************************
+//   Check which energy bins have been used
+//****************************************************************************
+void ReadForests()
+{
+    TFile fileRF(fileForest,"read");
+    TList *list=(TList*)fileRF.GetListOfKeys();
+    const Int_t n=list->GetSize()-1;// subtract 1 since 1 key belongs to MDataArray
+
+    MRanForest forest;
+    for(Int_t i=0;i<n;i++)
+    {
+        forest.Read(Form("%d",i));
+        MRanForest *curforest=(MRanForest*)forest.Clone();
+        const char *energy=list->FindObject(Form("%d",i))->GetTitle();
+        const char *bin   =list->FindObject(Form("%d",i))->GetName();
+
+        if(i<10) cout<<"Bin  "<<bin<<":   log10(Energy[GeV]) = "<<energy<<endl;
+        else     cout<<"Bin "<< bin<<":   log10(Energy[GeV]) = "<<energy<<endl;
+    }
+    fileRF.Close();
+
+    return;
+}
+
+//****************************************************************************
+//   Fast Testing with matrix
+//****************************************************************************
+void RFEnergyEstTest()
+{
+    MHMatrix matrix;
+    TFile *file=new TFile(fileMatrixTest);
+    matrix.Read("MatrixGammas");
+
+    MRFEnergyEst rf;
+    rf.SetMatrixTest(&matrix);
+    rf.SetFile(fileForest);
+
+    rf.SetBit(MParContainer::kEnableGraphicalOutput,1);
+    rf.Test();
+
+    return;
+}
+
+//****************************************************************************
+//   Apply RF energy estimation in eventloop
+//****************************************************************************
+void RFEnergyEstLoop()
+{
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    MReadTree  read("Events",fileNameTest);
+    read.DisableAutoScheme();
+
+    MRFEnergyEst rf;
+    rf.SetFile(fileForest);
+
+    MWriteRootFile write("EnergyEstTest.root");
+    write.AddContainer("MMcEvt",     "Events");
+    write.AddContainer("MEnergyEst", "Events");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&rf);
+    tlist.AddToList(&write);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop()) return;
+    tlist.PrintStatistics();
+
+    return;
+}
Index: /tags/Mars-V0.9/macros/RanForest.C
===================================================================
--- /tags/Mars-V0.9/macros/RanForest.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/RanForest.C	(revision 9772)
@@ -0,0 +1,179 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>!
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void RanForest()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadMarsFile  read("Events", "~/MagicData/data1/CT1Data/ONTrain/*.root");
+    read.DisableAutoScheme();
+    tlist.AddToList(&read);
+
+    MFParticleId fgamma("MMcEvt", '=', MMcEvt::kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    MFParticleId fhadrons("MMcEvt", '!', MMcEvt::kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    MHMatrix matrixg("MatrixGammas");
+    matrixg.AddColumn("cos(MMcEvt.fTelescopeTheta)");
+    matrixg.AddColumn("MSigmabar.fSigmabar");
+    matrixg.AddColumn("log10(Hillas.fSize)");
+    matrixg.AddColumn("HillasSrc.fDist");
+    matrixg.AddColumn("Hillas.fWidth");
+    matrixg.AddColumn("Hillas.fLength");
+    matrixg.AddColumn("log10(Hillas.fSize)/Hillas.fWidth*Hillas.fLength");
+    matrixg.AddColumn("abs(Hillas.fM3Long)");
+    matrixg.AddColumn("Hillas.fConc");
+    matrixg.AddColumn("Hillas.fConc1");
+
+    //matrixg.AddColumn("abs(Hillas.fAsym)");
+    //matrixg.AddColumn("abs(Hillas.fM3Trans)");
+    //matrixg.AddColumn("abs(HillasSrc.fHeadTail)");
+    //matrixg.AddColumn("abs(HillasSrc.fAlpha)");
+
+    plist.AddToList(&read);
+
+    plist.AddToList(&matrixg);
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.AddColumns(matrixg.GetColumns());
+    plist.AddToList(&matrixh);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&fgamma);
+    tlist.AddToList(&fillmatg);
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&fhadrons);
+    tlist.AddToList(&fillmath);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // second event loop: the trees of the random forest are grown,
+    // the event loop is now actually a tree loop (loop of training
+    // process)
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist2;
+    plist.Replace(&tlist2);
+
+    MRanForestGrow rfgrow2;
+    rfgrow2.SetNumTrees(10);
+    rfgrow2.SetNumTry(3);
+    rfgrow2.SetNdSize(10);
+
+    MWriteRootFile rfwrite2("RF.root");
+    rfwrite2.AddContainer("MRanTree","Tree");       //save all trees
+    MFillH fillh2("MHRanForestGini");
+
+    tlist2.AddToList(&rfgrow2);
+    tlist2.AddToList(&rfwrite2);
+    tlist2.AddToList(&fillh2);
+
+    // gRandom is accessed from MRanForest (-> bootstrap aggregating)
+    // and MRanTree (-> random split selection) and should be initialized
+    // here if you want to set a certain random number generator
+    if(gRandom)
+        delete gRandom;
+    gRandom = new TRandom3(0);
+
+    //
+    // Execute tree growing (now the eventloop is actually a treeloop)
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist2.PrintStatistics();
+
+    plist.FindObject("MHRanForestGini")->DrawClone();
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // third event loop: the control sample (star2.root) is processed
+    // through the previously grown random forest,
+    //
+    // the histograms MHHadronness (quality of g/h-separation) and
+    // MHRanForest are created and displayed.
+    // MHRanForest shows the convergence of the classification error
+    // as function of the number of grown (and combined) trees
+    // and tells the user how many trees are actually needed in later
+    // classification tasks.
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist3;
+
+    plist.Replace(&tlist3);
+
+    MReadMarsFile  read3("Events", "~/MagicData/data1/CT1Data/ONTest/*.root");
+    read3.DisableAutoScheme();
+    tlist3.AddToList(&read3);
+
+    MRanForestCalc calc;
+    tlist3.AddToList(&calc);
+
+    MFillH fillh3a("MHHadronness");
+    MFillH fillh3b("MHRanForest");
+
+    tlist3.AddToList(&fillh3a);
+    tlist3.AddToList(&fillh3b);
+
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist3.PrintStatistics();
+
+    plist.FindObject("MHRanForest")->DrawClone();
+    plist.FindObject("MHHadronness")->DrawClone();
+    plist.FindObject("MHHadronness")->Print();//*/
+}
Index: /tags/Mars-V0.9/macros/RanForest2.C
===================================================================
--- /tags/Mars-V0.9/macros/RanForest2.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/RanForest2.C	(revision 9772)
@@ -0,0 +1,110 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck, 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void RanForest2()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    //
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // first event loop: the trees of the random forest are read in
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    //
+    MReadTree read("Tree","RF.root");
+    read.DisableAutoScheme();
+
+    MRanForestFill rffill;
+    rffill.SetNumTrees(100);
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&rffill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute tree reading (now the eventloop is actually a treeloop)
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // second event loop: the control sample is processed
+    // through the previously grown random forest,
+    //
+    // the histograms MHHadronness (quality of g/h-separation) and
+    // MHRanForest are created and displayed.
+    // MHRanForest shows the convergence of the classification error
+    // as function of the number of grown (and combined) trees
+    // and tells the user how many trees are actually needed in later
+    // classification tasks.
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist2;
+
+    plist.Replace(&tlist2);
+
+    MReadMarsFile  read2("Events", "~/MagicData/data1/CT1Data/ONTest/*.root");
+    read2.DisableAutoScheme();
+    tlist2.AddToList(&read2);
+
+    MRanForestCalc calc;
+    tlist2.AddToList(&calc);
+
+    MFillH fillh2a("MHHadronness");
+    MFillH fillh2b("MHRanForest");
+
+    tlist2.AddToList(&fillh2a);
+    tlist2.AddToList(&fillh2b);
+
+    //
+    // Execute your analysis
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist2.PrintStatistics();
+
+    plist.FindObject("MHRanForest")->DrawClone();
+    plist.FindObject("MHHadronness")->DrawClone();
+    plist.FindObject("MHHadronness")->Print();
+}
Index: /tags/Mars-V0.9/macros/ScanExtractSignalABCorr.C
===================================================================
--- /tags/Mars-V0.9/macros/ScanExtractSignalABCorr.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/ScanExtractSignalABCorr.C	(revision 9772)
@@ -0,0 +1,193 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!              Florian Goebel 07/2004
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+Bool_t HandleInput()
+{
+  TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+  while (1)
+    {
+      //
+      // While reading the input process gui events asynchronously
+      //
+      timer.TurnOn();
+      TString input = Getline("Type 'q' to exit, <return> to go on: ");
+      timer.TurnOff();
+      
+      if (input=="q\n")
+	return kFALSE;
+      
+      if (input=="\n")
+	return kTRUE;
+    };
+  
+  return kFALSE;
+}
+
+const TString defname = "/.magic/magicserv01/MAGIC/rootdata2/2004_04_22/20040422_23211_D_Mrk421_E.root";
+const TString defpedname = "/.magic/magicserv01/MAGIC/rootdata2/2004_04_22/20040422_23209_P_Mrk421_E.root";
+
+void ScanExtractSignalABCorr(const TString fname = defname,  const TString pedname = defpedname) {
+  
+  MParList plist_ped;
+  
+  MTaskList tlist_ped;
+  plist_ped.AddToList(&tlist_ped);
+  
+  MPedestalCam   pedcam;
+  plist_ped.AddToList(&pedcam);
+  
+  MReadMarsFile read("Events", pedname);
+  read.DisableAutoScheme();
+  
+  MGeomApply    geomapl_ped;
+  MGeomCamMagic geomcam_ped;
+
+  MPedCalcFromLoGain pedcalc_ped;
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+  
+  tlist_ped.AddToList(&read);
+  tlist_ped.AddToList(&geomapl_ped);
+  tlist_ped.AddToList(&pedcalc_ped);
+  
+  MEvtLoop evtloop_ped;
+  evtloop_ped.SetParList(&plist_ped);
+  
+  if (!evtloop_ped.Eventloop())
+    return;
+  
+  tlist_ped.PrintStatistics();
+  
+  
+  // now the event loop for the signal reconstruction with pedestals subtracted
+  
+  
+  MParList plist;
+  MTaskList     tlist;
+  //  MPedestalCam   pedcam;
+  plist.AddToList(&pedcam);
+  
+  MRawEvtData evtdata; 
+  plist.AddToList(&evtdata);
+  
+  MArrivalTimeCam timecam;
+  plist.AddToList(&timecam);
+  
+  MExtractedSignalCam sigcam;
+  plist.AddToList(&sigcam);
+  
+  
+  plist.AddToList(&tlist);
+  
+  MReadMarsFile read("Events", fname);
+  read.DisableAutoScheme();
+  
+  MGeomApply       geomapl;
+  MArrivalTimeCalc timetime;
+
+  MExtractSignalABcorr sigsig;
+  sigsig.SetRange(5,7,5,7);
+  
+  tlist.AddToList(&read);
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&sigsig);
+  tlist.AddToList(&timetime);
+  
+  
+  
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+  if (!evtloop.PreProcess())
+    return;
+  
+  
+  MGeomCam *geomcam = (MGeomCam*)plist->FindObject("MGeomCam");
+  
+  MHCamera display;
+  TCanvas c("Events", "Real Events", 600, 600);
+  c.SetBorderMode(0);
+  c.Divide(1,1);
+  
+  MHCamera display_time;
+  TCanvas c_time("Events_time", "Events Time", 600, 600);
+  c_time.SetBorderMode(0);
+  c_time.Divide(1,1);
+  
+  
+  display.SetGeometry(*geomcam);
+  display.SetPrettyPalette();
+  c.cd(1);
+  display.Draw();
+  gPad->cd(1);
+  
+  display_time.SetGeometry(*geomcam);
+  display_time.SetPrettyPalette();
+  c_time.cd(1);
+  display_time.Draw();
+  gPad->cd(1);
+  
+  
+  // Use this if you don't want the event to be autoscaled
+  //display.SetMinimum(0);
+  //display.SetMaximum(100);
+  
+
+  while (tlist.Process()) {
+    cout << "Event #" << read.GetNumEntry() ":" << endl;
+      
+      display.SetCamContent(sigcam,0);
+      display.SetCamError(sigcam,1);
+      
+      c.GetPad(1)->GetPad(1)->Modified(); //vielleicht fehler? 1->i ??
+      c.GetPad(1)->GetPad(1)->Update();
+      
+      
+      display_time.SetCamContent(timecam,0);
+      display_time.SetCamError(timecam,1);
+      c_time.GetPad(1)->GetPad(1)->Modified(); //vielleicht fehler? 1->i ??
+      c_time.GetPad(1)->GetPad(1)->Update();
+            
+      if (!HandleInput())
+      	break;
+  }
+  
+  evtloop.PostProcess();
+
+  TCanvas c("Events", "Real Events", 600, 600);
+  c.SetBorderMode(0);
+  c.Divide(1,1);
+  c.cd(1);
+
+  chargevpixel->Draw();
+
+}
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/ScanPulseABPed.C
===================================================================
--- /tags/Mars-V0.9/macros/ScanPulseABPed.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/ScanPulseABPed.C	(revision 9772)
@@ -0,0 +1,189 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+Bool_t HandleInput()
+{
+  TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+  while (1)
+    {
+      //
+      // While reading the input process gui events asynchronously
+      //
+      timer.TurnOn();
+      TString input = Getline("Type 'q' to exit, <return> to go on: ");
+      timer.TurnOff();
+      
+      if (input=="q\n")
+	return kFALSE;
+      
+      if (input=="\n")
+	return kTRUE;
+    };
+  
+  return kFALSE;
+}
+
+const TString defname = "/.magic/magicserv01/MAGIC/rootdata2/2004_04_22/20040422_23211_D_Mrk421_E.root";
+const TString defpedname = "/.magic/magicserv01/MAGIC/rootdata2/2004_04_22/20040422_23209_P_Mrk421_E.root";
+
+void ScanPulseABPed(Int_t ipix = 1, const TString fname = defname, const TString pedname = defpedname) {
+  
+  MParList plist_ped;
+  
+  MTaskList tlist_ped;
+  plist_ped.AddToList(&tlist_ped);
+  
+  MPedestalCam   pedcam;
+  plist_ped.AddToList(&pedcam);
+  
+  MReadMarsFile read("Events", pedname);
+  read.DisableAutoScheme();
+  tlist_ped.AddToList(&read);
+  
+  MGeomApply     geomapl_ped;
+  MGeomCamMagic  geomcam;
+  tlist_ped.AddToList(&geomapl_ped);
+
+  
+  MPedCalcFromLoGain pedcalc_ped;
+  pedcalc_ped.SetMaxHiGainVar(20);
+  pedcalc_ped.SetRange(0, 11, 1, 14);
+  pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+  tlist_ped.AddToList(&pedcalc_ped);
+  
+  MEvtLoop evtloop_ped;
+  evtloop_ped.SetParList(&plist_ped);
+  
+  if (!evtloop_ped.Eventloop())
+    return;
+  
+  tlist_ped.PrintStatistics();
+  
+  
+  // now the event loop for the signal reconstruction with pedestals subtracted
+  
+  
+  MParList plist;
+  MTaskList     tlist;
+  // MPedestalCam   pedcam;
+  plist.AddToList(&pedcam);
+  
+  MRawRunHeader runheader;
+  plist.AddToList(&runheader);
+
+  MRawEvtData evtdata; 
+  plist.AddToList(&evtdata);
+  
+  plist.AddToList(&tlist);
+  
+  MReadMarsFile read("Events", fname);
+  read.DisableAutoScheme();
+  
+  MGeomApply geomapl;
+  
+  tlist.AddToList(&read);
+  tlist.AddToList(&geomapl);
+  
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+  if (!evtloop.PreProcess())
+    return;
+
+  TString title = "Pulse in pixel: ";
+  title += ipix;
+  TCanvas c("Events", title, 600, 600);
+  c.SetBorderMode(0);
+  c.Divide(1,1);
+  c.cd(1);
+  gPad->cd(1); 
+
+  Int_t First = 1;
+
+  while (tlist.Process()) {
+
+    if (First) {
+      First = 0;
+
+      const Int_t nh = runheader.GetNumSamplesHiGain();
+      const Int_t nl = runheader.GetNumSamplesLoGain();
+      const Int_t nt = nh+nl;
+      
+      TH1D *hpulse_corr = new TH1D("hpulse_corr", title, nt, -0.5, nt+0.5);
+      hpulse_corr->SetMaximum(255);
+      hpulse_corr->SetMinimum(-10);
+      hpulse_corr->SetLineColor(2);
+      //      hpulse_corr->SetLineWidth(3);
+      
+      hpulse_corr->Draw();
+
+      TH1D *hpulse = new TH1D("hpulse", title, nt, -0.5, nt+0.5);
+      hpulse->Draw("same");
+    }
+
+    MRawEvtPixelIter pixel(&evtdata);
+    pixel.Jump(ipix);
+
+    Bool_t ABFlag = pixel.HasABFlag();
+
+    cout << "Event: " << read.GetNumEntry() << " ABFlag: " << (Int_t)ABFlag << endl;
+      
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+  
+    const Float_t ped_mean = pedcam[ipix].GetPedestal();
+    const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+
+    Float_t PedMean[2];
+    PedMean[0] = ped_mean + ABoffs;
+    PedMean[1] = ped_mean - ABoffs;
+
+    for (int slice=0; slice<nh; slice++) {
+      hpulse_corr->SetBinContent(slice+1, higains[slice]-PedMean[(slice+ABFlag)&0x1]);
+      hpulse->SetBinContent(slice+1, higains[slice]);
+    }
+    for (int slice=0; slice<nl; slice++) {
+      hpulse_corr->SetBinContent(slice+nh+1, logains[slice]-PedMean[(nh+slice+ABFlag)&0x1]);
+      hpulse->SetBinContent(slice+nh+1, logains[slice]);
+    }
+
+    c.GetPad(1)->Modified(); 
+    c.GetPad(1)->Update();
+
+    if (!HandleInput())
+      break;
+  }
+  
+  evtloop.PostProcess();
+
+}
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/bootcampstandardanalysis.C
===================================================================
--- /tags/Mars-V0.9/macros/bootcampstandardanalysis.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/bootcampstandardanalysis.C	(revision 9772)
@@ -0,0 +1,326 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 12/2003 <mailto:jlopez@ifae.es>
+!              Markus Gaug , 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  bootcampstandardanalysis.C
+//
+//  Updated version of the macro designed at the Wuerzburg bootcamp and 
+//  compatible with the latest changes in Mars for general usage at the
+//  Udine bootcamp. 
+//
+//  Needs as arguments the run number of a pedestal file ("*_P_*.root"), 
+//  one of a calibration file ("*_C_*.root") and one of a data file 
+//  ("*_D_*.root"). Performs the pedestal calculation, the calibration 
+/// constants calculation and the calibration of the data. 
+//
+//  The TString inpath has to be set correctly.
+//
+//  The macro searches for the pulser colour which corresponds to the calibration
+//  run number. If the run number is smaller than 20000, pulser colour "CT1" 
+//  is assumed, otherwise, it searches for the strings "green", "blue", "uv" or 
+//  "ct1" in the filenames. If no colour or multiple colours are found, the 
+//  execution is aborted.  
+//
+//////////////////////////////////////////////////////////////////////////////////
+const TString inpath = "/mnt/Data/rootdata/CrabNebula/2004_02_10/";
+const TString outpath = "./";
+const Int_t dpedrun  = 14607;
+const Int_t dcalrun1 = 14608;
+const Int_t dcalrun2 = 0;
+const Int_t ddatrun1 = 14609;
+const Int_t ddatrun2 = 14614;
+const Bool_t usedisplay = kTRUE;
+//
+// A switch to use the Blind Pixel
+//
+const Bool_t blindpix = kTRUE;
+//
+// A switch to use the PIN Diode 
+//
+const Bool_t pindiode = kFALSE;
+//
+void bootcampstandardanalysis(const Int_t prun=dpedrun, // pedestal file
+                              const Int_t crun1=dcalrun1, const Int_t crun2=dcalrun2, // calibration file(s)
+                              const Int_t drun1=ddatrun1, const Int_t drun2=ddatrun2 // data files(s)
+                              )
+                              
+{
+
+  //
+  // Choose the signal Extractor:
+  //
+  MExtractSlidingWindow extractor;
+  //  MExtractFixedWindowPeakSearch extractor;
+  //  MExtractFixedWindow    extractor;   
+
+  //
+  // Set Ranges or Windows
+  //
+  extractor.SetRange(2,14,5,14);
+  //  extractor.SetWindows(8,8);
+
+  //
+  // Choose the arrival time Extractor:
+  //
+  MExtractTimeFastSpline       timeext;
+  //  MExtractTimeHighestIntegral timeext;
+  //  MExtractTimeSpline          timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(3,12,6,14);
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+
+  pruns.AddRun(prun,inpath);
+
+  if (crun2==0)
+    cruns.AddRun(crun1,inpath);
+  else
+    cruns.AddRuns(crun1,crun2,inpath);
+
+  if (drun2==0)
+    druns.AddRun(drun1,inpath);
+  else
+    druns.AddRuns(drun1,drun2,inpath);
+  
+  //
+  // Now setup the tasks and tasklist for the pedestals:
+  // ---------------------------------------------------
+  //
+  MBadPixelsCam     badcam;
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  //
+  // If you want to exclude pixels from the beginning, read 
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)
+  //
+  //  badcam.AsciiRead("badpixels.dat");
+  
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+
+  MJPedestal pedloop;
+  pedloop.SetInput(&pruns);
+  pedloop.SetOutputPath(outpath.Data());
+  if (usedisplay)
+    {
+      MStatusDisplay *display = new MStatusDisplay;
+      display->SetUpdateTime(3000);
+      display->Resize(850,700);
+      pedloop.SetDisplay(display);
+    }
+  pedloop.SetBadPixels(badcam);
+  pedloop.SetExtractor(&extractor);
+
+  if (!pedloop.Process())
+    return;
+
+  /****************************************/
+  /* SECOND LOOP: CALIBRATION COMPUTATION */
+  /****************************************/
+
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MCalibrationQECam qecam;
+  MJCalibration     calloop;
+  calloop.SetInput(&cruns);
+  calloop.SetOutputPath(outpath.Data());
+  calloop.SetExtractor(&extractor);
+  //
+  // Apply rel. time calibration:
+  //
+  calloop.SetRelTimeCalibration();
+  calloop.SetTimeExtractor(&timeext);
+  //
+  // Set the corr. cams:
+  //
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop.GetBadPixels());
+  //
+  // Choose if you want to use the blind pixel and/or the pin diode
+  //
+  calloop.SetUseBlindPixel(blindpix);
+  calloop.SetUsePINDiode(pindiode);
+  //
+  // The next two commands are for the display:
+  //
+  if (usedisplay)
+      calloop.SetDisplay(display);
+  
+  //
+  // Do the event-loop:
+  //
+  if (!calloop.Process(pedloop.GetPedestalCam()))
+    return;
+  
+
+  /*************************************/
+  /* THIRD LOOP: PEDESTAL CALIBRATION  */
+  /*************************************/
+
+  MJExtractSignal pedphotloop;
+
+  pedphotloop.SetExtractor(&extractor);
+  pedphotloop.SetTimeExtractor(&timeext);
+  pedphotloop.SetInput(&pruns);
+  pedphotloop.SetOutputPath(outpath);
+  pedphotloop.SetDisplay(display);
+  pedphotloop.SetBadPixels(calloop.GetBadPixels());
+  
+  if (!pedphotloop.ProcessP(pedloop.GetPedestalCam(),calloop.GetCalibrationCam(),calloop.GetQECam()))
+    return;
+
+  /*************************************/
+  /* FOURTH LOOP: DATA CALIBRATION     */
+  /*************************************/
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  //
+  MParList  plist4;
+  MTaskList tlist4;
+  plist4.AddToList(&tlist4);
+  
+  //
+  // Now setup the tasks and tasklist to analize the data
+  // -----------------------------------------------------
+  //
+  plist4.AddToList(&geomcam);
+  //
+  // Retrieve the cameras from the previous runs:
+  //
+  plist4.AddToList(&pedloop.GetPedestalCam());
+  plist4.AddToList(&calloop.GetCalibrationCam());
+  plist4.AddToList(&calloop.GetQECam());
+  plist4.AddToList(&calloop.GetRelTimeCam());
+  plist4.AddToList(&calloop.GetBadPixels());
+  plist4.AddToList(&pedphotloop.GetPedPhotCam());
+
+  MCerPhotEvt nphot;
+  plist4.AddToList(&nphot);
+
+  MArrivalTime times;
+  plist4.AddToList(&times);
+  
+  //tasks
+  MReadMarsFile read4("Events");
+  read4.DisableAutoScheme();
+  static_cast<MRead&>(read4).AddFiles(druns);  
+  
+  MCalibrateData   photcalc;
+  photcalc.SetCalibrationMode(MCalibrateData:kFfactor);
+  MCalibrateRelTimes  timecal;
+
+  MBadPixelsTreat  badtreat;
+  badtreat.SetUseInterpolation();
+
+  tlist4.AddToList(&read4);
+  tlist4.AddToList(&geomapl);
+  tlist4.AddToList(&extractor);
+  tlist4.AddToList(&timeext);
+  tlist4.AddToList(&photcalc);
+  tlist4.AddToList(&badtreat);
+  tlist4.AddToList(&timecal);
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop4;
+  evtloop4.SetParList(&plist4);
+
+  if (!evtloop4.PreProcess())
+    return;
+  
+  TCanvas *c1 = new TCanvas;
+  MHCamera disp1(geomcam);
+  disp1.SetPrettyPalette();
+  //disp1.SetInvDeepBlueSeaPalette()
+  disp1.Draw();
+  gPad->SetLogy();
+  gPad->cd(1);
+  
+  /*
+  TCanvas *c2 = new TCanvas;
+  MHCamera disp2(geomcam);
+  disp2.SetPrettyPalette();
+  //disp2.SetInvDeepBlueSeaPalette()
+  disp2.Draw();
+  gPad->SetLogy();
+  gPad->cd(1);
+  */
+  while (tlist4.Process())
+    {
+      disp1.SetCamContent(nphot);
+      
+      gPad->Modified();
+      gPad->Update();
+
+      /*    
+      disp2.SetCamContent(times);
+      
+      gPad->Modified();
+      gPad->Update();
+      */
+
+      // Remove the comments if you want to go through the file
+      // event-by-event:
+      if (!HandleInput())
+	break;
+    }
+
+  evtloop4.PostProcess();
+  
+}
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
Index: /tags/Mars-V0.9/macros/calibClasses.C
===================================================================
--- /tags/Mars-V0.9/macros/calibClasses.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/calibClasses.C	(revision 9772)
@@ -0,0 +1,729 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  calibClasses
+//
+//  This macro draws the schemes found in htmldoc/images/CalibClasses.gif
+//  and htmldoc/images/RelTimeClasses.gif
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void calibClasses()
+{
+
+  const Float_t ell1x1 = 0.3;
+  const Float_t ell2x1 = 0.575;
+  const Float_t ell3x1 = 0.85;
+  
+  const Float_t ellr1 = 0.12;
+  const Float_t ellr2 = 0.035;
+  
+  const Float_t tex1x1 = 0.19;
+  const Float_t tex2x1 = 0.465;
+  const Float_t tex3x1 = 0.74;
+
+
+  const Float_t texsize = 0.0257913;
+  const Float_t texsize2 = 0.015;
+
+  const Float_t arr1x1 = 0.3;
+  const Float_t arr2x1 = 0.575;
+  const Float_t arr3x1 = 0.85;
+
+  const Float_t arrsize = 0.02;
+  
+  const Float_t pt1x1 = 0.175;
+  const Float_t pt2x1 = 0.45;
+  const Float_t pt3x1 = 0.725;
+
+  const Float_t pt1x2 = 0.425;
+  const Float_t pt2x2 = 0.7;
+  const Float_t pt3x2 = 0.975;
+
+  Float_t arry1  = 0.;
+  Float_t arry2  = 0.;
+  Float_t elly1  = 0.;
+  Float_t pty1   = 0.;
+  Float_t pty2   = 0.;
+  Float_t texy1  = 0.;
+  Float_t linex1 = 0.;
+  Float_t linex2 = 0.;
+  Float_t liney1 = 0.l;
+
+  TCanvas *CalibClasses = new TCanvas("CalibClasses", "Calibration Classes",89,96,758,1051);
+  CalibClasses->Range(0,0,1,1);
+  CalibClasses->SetBorderSize(2);
+  CalibClasses->SetFrameFillColor(0);
+   
+// First line:
+   TPaveText *pt = new TPaveText(0.375,0.895,0.785,0.95,"br");
+   pt->SetFillColor(18);
+   TText *text = pt->AddText("MRawEvtData");
+   pt->Draw();
+      tex = new TLatex(0.55,0.955,"C");
+   tex->SetTextSize(0.05);
+   tex->SetLineWidth(2);
+   tex->Draw();
+      tex = new TLatex(0.12,0.955,"P");
+   tex->SetTextSize(0.05);
+   tex->SetLineWidth(2);
+   tex->Draw();
+   
+   pt = new TPaveText(0.015,0.875,0.25,0.95,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MPedestalCam:");
+   text = pt->AddText("ped, RMS, #Deltaped, #DeltaRMS");
+   text->SetTextColor(kBlue);
+   pt->Draw();
+   
+
+// Second line:
+   elly1 = 0.805;
+
+   TEllipse *ellipse = new TEllipse(ell1x1,elly1,ellr1,ellr2,0,360,0);
+   ellipse->Draw();
+   
+   ellipse = new TEllipse(ell2x1,elly1,ellr1,ellr2,0,360,0);
+   ellipse->Draw();
+   
+   ellipse = new TEllipse(ell3x1,elly1,ellr1,ellr2,0,360,0);
+   ellipse->Draw();
+
+   texy1 = 0.805;
+
+      tex = new TLatex(tex1x1,texy1,"MExtractSignal:");
+   tex->SetTextSize(texsize);
+   tex->SetLineWidth(2);
+   tex->Draw();
+
+      tex = new TLatex(tex2x1,texy1,"MExtractBlindPixel:");
+   tex->SetTextSize(texsize);
+   tex->SetLineWidth(2);
+   tex->Draw();
+      tex = new TLatex(tex3x1,texy1,"MExtractPINDiode:");
+   tex->SetTextSize(texsize);
+   tex->SetLineWidth(2);
+   tex->Draw();
+
+   texy1 = 0.79;
+
+      tex = new TLatex(tex1x1+0.02,texy1,"sum FADC slices, error??");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+      tex = new TLatex(tex2x1+0.02,texy1,"sum FADC slices");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+      tex = new TLatex(tex3x1+0.02,texy1,"sum FADC slices");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+
+   arry1 = 0.89;
+   arry2 = 0.84;
+
+   TArrow *arrow = new TArrow(0.45, arry1,arr1x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   arrow         = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   arrow         = new TArrow(0.715, arry1,arr3x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   
+// Third line:
+   pty1 = 0.67;
+   pty2 = 0.73;
+   
+   pt = new TPaveText(pt1x1,pty1,pt1x2,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MExtractedSignalCam");
+   pt->Draw();
+   
+   pt = new TPaveText(pt2x1,pty1,pt2x2,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MExtractedSignalBlindPixel");
+   pt->Draw();
+   
+   pt = new TPaveText(pt3x1,pty1,pt3x2,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MExtractedSignalPINDiode");
+   pt->Draw();
+
+   arry1 = 0.77;
+   arry2 = 0.73;
+
+   arrow = new TArrow(arr1x1,arry1,arr1x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr3x1,arry1,arr3x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+
+// Fourth line:
+   elly1 = 0.6;
+
+   TEllipse *ellipse = new TEllipse(ell1x1,elly1,ellr1,ellr2,0,360,0);
+   ellipse->Draw();
+   
+   ellipse = new TEllipse(ell2x1,elly1,ellr1,ellr2,0,360,0);
+   ellipse->Draw();
+   
+   ellipse = new TEllipse(ell3x1,elly1,ellr1,ellr2,0,360,0);
+   ellipse->Draw();
+
+
+
+   texy1 = 0.6;
+
+      tex = new TLatex(tex1x1,texy1,"MHCalibrationChargeCam:");
+   tex->SetTextSize(texsize2);
+   tex->SetLineWidth(2);
+   tex->Draw();
+      tex = new TLatex(tex2x1,texy1,"MHCalibrationChargeBlindPix:");
+   tex->SetTextSize(texsize2);
+   tex->SetLineWidth(2);
+   tex->Draw();
+      tex = new TLatex(tex3x1,texy1,"MHCalibrationChargePINDiode:");
+   tex->SetTextSize(texsize2);
+   tex->SetLineWidth(2);
+   tex->Draw();
+
+   linex1 = 0.18;
+   linex2 = 0.08;
+
+   TLine *line = new TLine(linex1,texy1,linex2,texy1);
+   line->Draw();
+
+   arrow = new TArrow(linex2,texy1,linex2,0.29,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   
+   tex = new TLatex(linex2-0.01,0.35,"Pulse not in extraction window");
+   tex->SetTextSize(texsize2+0.008);
+   tex->SetTextAngle(90);
+   tex->SetTextColor(006);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   texy1 = 0.59;
+
+   tex = new TLatex(tex1x1+0.01,texy1,"Fit High-, Low-Gain, each pixel");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+      tex = new TLatex(tex1x1+0.01,texy1-0.01,"Fast Fourier Analysis");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+
+
+      tex = new TLatex(tex2x1+0.01,texy1,"Fit Single-Phe spectrum");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+      tex = new TLatex(tex3x1+0.01,texy1,"Fit Charge distribution");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+      tex = new TLatex(tex3x1+0.01,texy1-0.01,"Fast Fourier Analysis");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+
+   arry1 = 0.67;
+   arry2 = 0.63;
+
+   arrow = new TArrow(arr1x1,arry1,arr1x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr3x1,arry1,arr3x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+// Fifth line:
+   pty1 = 0.465;
+   pty2 = 0.525;
+
+   pt = new TPaveText(pt1x1,pty1-0.03,pt1x2,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MCalibrationChargeCam:");
+   pt->Draw();
+   text = pt->AddText("Conv. FADC to Phe's, error");
+   text->SetTextColor(kBlue);
+   pt->Draw();
+   text = pt->AddText("Total F-Factor to Photons");
+   text->SetTextColor(kBlue);
+   pt->Draw();
+   
+   pt = new TPaveText(pt2x1,pty1,pt2x2,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MCalibrationChargeBlindPix");
+   pt->Draw();
+   
+   pt = new TPaveText(pt3x1,pty1,pt3x2,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MCalibrationChargePINDiode");
+   pt->Draw();
+   
+
+   arry1 = 0.565;
+   arry2 = 0.525;
+
+   arrow = new TArrow(arr1x1,arry1,arr1x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr3x1,arry1,arr3x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+
+// Sixth line:
+   Float_t nellx1 = 0.39;
+   elly1 = 0.38;
+
+   ellipse = new TEllipse(0.57,elly1,0.235,0.04,0,360,0);
+   ellipse->Draw();
+
+      tex = new TLatex(nellx1,0.38,"MCalibrationChargeCalc:");
+   tex->SetTextSize(0.0328253);
+   tex->SetLineWidth(2);
+   tex->Draw();
+
+   tex = new TLatex(nellx1+0.02,0.365,"Low Gain Ped., Red. #sigma's, Nr. Phe's, total F-Factor");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   tex = new TLatex(nellx1+0.02,0.355,"#gamma-fluxes: F-Factor, BlindPixel, PIN Diode Method");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+
+   arry1 = 0.46;
+   arry2 = 0.42;
+
+   arrow = new TArrow(arr1x1,0.435,arr1x1+0.1,arry2-0.01,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr3x1,arry1,arr3x1-0.1,arry2-0.01,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   linex1 = 0.135;
+   liney1 = 0.38;
+
+   TLine *line = new TLine(linex1,0.87,linex1,liney1);
+   line->Draw();
+
+   arrow = new TArrow(linex1,liney1,0.335544,liney1,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   arrow = new TArrow(0.38,0.402,0.27,0.433,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+
+   arrow = new TArrow(0.35,0.365,0.15,0.29,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   tex = new TLatex(0.2,0.29,"Deviating Nr. Phe's");
+   tex->SetTextSize(texsize2+0.006);
+   tex->SetTextAngle(27);
+   tex->SetTextColor(006);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   tex = new TLatex(0.19,0.325,"Oscillations");
+   tex->SetTextSize(texsize2+0.006);
+   tex->SetTextAngle(27);
+   tex->SetTextColor(006);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   tex = new TLatex(0.195,0.31,"Absurd fit results");
+   tex->SetTextSize(texsize2+0.006);
+   tex->SetTextAngle(27);
+   tex->SetTextColor(006);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+// seventh line
+   pty1 = 0.215;
+   pty2 = 0.29;
+
+   pt = new TPaveText(0.015,pty1,0.25,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MBadPixelsCam:");
+   text = pt->AddText("kUnsuitableRun");
+   text->SetTextColor(kBlue);
+   text = pt->AddText("kUnreliableRun");
+   text->SetTextColor(kBlue);
+   pt->Draw();
+   
+
+   pt = new TPaveText(0.3,pty1,0.85,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MCalibrationQECam:");
+   pt->Draw();
+   text = pt->AddText("QE: Green, Blue, UV, CT1, av. Cascades(cos#theta), error");
+   text->SetTextColor(kBlue);
+   pt->Draw();
+   text = pt->AddText("QE: F-Factor, Blind Pixel, PIN Diode, Combined Method");
+   text->SetTextColor(kBlue);
+   pt->Draw();
+   
+
+   arry1 = 0.34;
+   arry2 = 0.3;
+
+   arrow = new TArrow(arr1x1+0.1,arry1+0.01,arr1x1+0.1,arry2-0.01,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2-0.01,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+   arrow = new TArrow(arr3x1-0.1,arry1+0.01,arr3x1-0.1,arry2-0.01,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+// eightth line:
+
+   Float_t nellx1 = 0.39;
+   elly1 = 0.13;
+
+   ellipse = new TEllipse(0.57,elly1,0.235,0.04,0,360,0);
+   ellipse->Draw();
+
+      tex = new TLatex(nellx1,elly1,"MCalibrate:");
+   tex->SetTextSize(0.0328253);
+   tex->SetLineWidth(2);
+   tex->Draw();
+
+   tex = new TLatex(nellx1+0.02,elly1-0.01,"Sum FADC slices to Phe's");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   tex = new TLatex(nellx1+0.02,elly1-0.02,"Phe's to photons (cos#theta), #Delta(photons)");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   arry1 = 0.21;
+   arry2 = 0.17;
+
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   Float_t linex1 = 0.27;
+   Float_t liney1 = 0.13;
+
+   TLine *line = new TLine(linex1,0.435,linex1,liney1);
+   line->Draw();
+
+   arrow = new TArrow(linex1,liney1,0.335544,liney1,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   linex1 = 0.15;
+   liney1 = 0.05;
+
+   TLine *line = new TLine(linex1,0.215,linex1,liney1);
+   line->Draw();
+
+   TLine *line = new TLine(linex1,liney1,arr2x1,liney1);
+   line->Draw();
+
+   arrow = new TArrow(arr2x1,liney1,arr2x1,0.09,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+
+   CalibClasses->Modified();
+   CalibClasses->cd();
+
+   CalibClasses->SaveAs("htmldoc/images/CalibClasses.gif");
+
+   //
+   // Relative Time classes
+   //
+
+   TCanvas *RelTimeClasses = new TCanvas("RelTimeClasses", "Relative Time Calibration Classes",89,96,758,1051);
+   RelTimeClasses->Range(0,0,1,1);
+   RelTimeClasses->SetBorderSize(2);
+   RelTimeClasses->SetFrameFillColor(0);
+   
+// First line:
+   TPaveText *pt = new TPaveText(0.375,0.895,0.785,0.95,"br");
+   pt->SetFillColor(18);
+   TText *text = pt->AddText("MRawEvtData");
+   pt->Draw();
+      tex = new TLatex(0.55,0.955,"C");
+   tex->SetTextSize(0.05);
+   tex->SetLineWidth(2);
+   tex->Draw();
+   
+
+// Second line:
+   elly1 = 0.805;
+
+   ellipse = new TEllipse(ell2x1,elly1,ellr1,ellr2,0,360,0);
+   ellipse->Draw();
+   
+   texy1 = 0.805;
+
+      tex = new TLatex(tex2x1,texy1,"MArrivalTimeCalc:");
+   tex->SetTextSize(texsize);
+   tex->SetLineWidth(2);
+   tex->Draw();
+
+   texy1 = 0.79;
+
+   tex = new TLatex(tex2x1+0.02,texy1,"Abs. Arrival Time");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   arry1 = 0.89;
+   arry2 = 0.84;
+
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   
+// Third line:
+   pty1 = 0.67;
+   pty2 = 0.73;
+   
+   pt = new TPaveText(pt2x1,pty1,pt2x2,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MArrivalTimeCam");
+   pt->Draw();
+   
+   arry1 = 0.77;
+   arry2 = 0.73;
+
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+// Fourth line:
+   elly1 = 0.6;
+
+   TEllipse *ellipse = new TEllipse(ell2x1,elly1,0.235,0.04,0,360,0);
+   ellipse->Draw();
+   
+   texy1 = 0.6;
+
+   tex = new TLatex(tex2x1-0.05,texy1,"MHCalibrationRelTimeCam:");
+   tex->SetTextSize(texsize);
+   tex->SetLineWidth(2);
+   tex->Draw();
+
+
+   arrow = new TArrow(0.35,0.465,0.15,0.39,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   tex = new TLatex(0.17,0.425,"Oscillations");
+   tex->SetTextSize(texsize2+0.006);
+   tex->SetTextAngle(27);
+   tex->SetTextColor(006);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   tex = new TLatex(0.175,0.41,"Absurd results");
+   tex->SetTextSize(texsize2+0.006);
+   tex->SetTextAngle(27);
+   tex->SetTextColor(006);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+// seventh line
+   pty1 = 0.315;
+   pty2 = 0.39;
+
+   pt = new TPaveText(0.015,pty1,0.25,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MBadPixelsCam:");
+   text = pt->AddText("kUnreliableRun");
+   text->SetTextColor(kBlue);
+   pt->Draw();
+   
+   texy1 = 0.59;
+
+   tex = new TLatex(tex2x1-0.04,texy1,"Calculate Rel. Arrival Times");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+   tex = new TLatex(tex2x1-0.04,texy1-0.01," (w.r.t. pixel 1 software idx)");
+   tex->SetTextSize(texsize2);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   arry1 = 0.67;
+   arry2 = 0.63;
+
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   arry1 = 0.56;
+   arry2 = 0.52;
+
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+// Fifth line:
+   pty1 = 0.44;
+   pty2 = 0.52;
+
+
+   pt = new TPaveText(0.3,pty1,0.85,pty2,"br");
+   pt->SetFillColor(18);
+   text = pt->AddText("MCalibrationRelTimeCam:");
+   pt->Draw();
+   text = pt->AddText("Offset, Resolution, errors");
+   text->SetTextColor(kBlue);
+   pt->Draw();
+
+
+
+// eightth line:
+
+   Float_t nellx1 = 0.39;
+   elly1 = 0.36;
+
+   ellipse = new TEllipse(0.57,elly1,0.235,0.04,0,360,0);
+   ellipse->Draw();
+
+   tex = new TLatex(nellx1,elly1,"MCalibrateTime:");
+   tex->SetTextSize(0.0328253);
+   tex->SetLineWidth(2);
+   tex->Draw();
+
+   tex = new TLatex(nellx1+0.02,elly1-0.02,"Offset correction");
+   tex->SetTextSize(texsize);
+   tex->SetTextColor(kRed);
+   tex->SetLineWidth(1);
+   tex->Draw();
+
+   arry1 = 0.44;
+   arry2 = 0.4;
+
+   arrow = new TArrow(arr2x1,arry1,arr2x1,arry2,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   Float_t linex1 = 0.25;
+   Float_t liney1 = 0.36;
+
+   arrow = new TArrow(linex1,liney1,0.335,liney1,arrsize,"|>");
+   arrow->SetFillColor(1);
+   arrow->SetFillStyle(1001);
+   arrow->Draw();
+
+   RelTimeClasses->Modified();
+   RelTimeClasses->cd();
+
+   RelTimeClasses->SaveAs("htmldoc/images/RelTimeClasses.gif");
+
+
+}
Index: /tags/Mars-V0.9/macros/calibrate_data.C
===================================================================
--- /tags/Mars-V0.9/macros/calibrate_data.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/calibrate_data.C	(revision 9772)
@@ -0,0 +1,385 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko, 03/2004 <mailto:hbartko@mppmu.mpg.de>
+!              Markus Gaug,    03/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+const TString defpath = "./";
+const TString defrout = "output_test.root";
+
+const Int_t defpedr [] = {20122};
+const Int_t defcalr [] = {20125};
+const Int_t defdatar[] = {20122};
+
+void calibrate_data(const TString inpath=defpath, 
+                    const Int_t psize=1, const Int_t pedruns[]=defpedr, 
+                    const Int_t csize=1, const Int_t calruns[]=defcalr, 
+                    const Int_t dsize=1, const Int_t dataruns[]=defdatar, 
+                    const TString resname=defrout)
+
+{
+
+//  MExtractSlidingWindow extractor;
+
+  MExtractFixedWindowPeakSearch extractor;
+  MExtractTimeFastSpline timeext;
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+  
+  for (Int_t i=0;i<psize;i++) {
+    cout << "Adding pedestal run: " << pedruns[i] << endl;
+    pruns.AddRun(pedruns[i],inpath);
+  }
+  for (Int_t i=0;i<csize;i++) {
+    cout << "Adding calibration run: " << calruns[i] << endl;
+    cruns.AddRun(calruns[i],inpath);
+  }
+  for (Int_t i=0;i<dsize;i++) {
+    cout << "Adding data run: " << dataruns[i] << endl;
+    druns.AddRun(dataruns[i],inpath);
+  }
+
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MParList plist1;
+  MTaskList tlist1;
+  plist1.AddToList(&tlist1);
+  
+  // containers
+  MPedestalCam   pedcam;
+  MBadPixelsCam  badcam;
+  //
+  // for excluding pixels from the beginning:
+  //
+  // badcam.AsciiRead("badpixels.dat");
+
+
+  plist1.AddToList(&pedcam);
+  plist1.AddToList(&badcam);
+    
+  //tasks
+  MReadMarsFile  read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(pruns);
+
+  MGeomApply     geomapl;
+  MPedCalcPedRun pedcalc;
+  MGeomCamMagic  geomcam;
+    
+  tlist1.AddToList(&read);
+  tlist1.AddToList(&geomapl);
+  tlist1.AddToList(&pedcalc);
+
+  // Create and execute the event looper
+  MEvtLoop pedloop;
+  pedloop.SetParList(&plist1);
+  pedloop.SetDisplay(display);
+
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Eventloop())
+    return;
+  
+  tlist1.PrintStatistics();
+
+  // 
+  // Now the short version: 
+  //
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MJCalibration     calloop;
+  calloop.SetInput(&cruns);
+  //  calloop.SetFullDisplay();
+  //
+  calloop.SetExtractor(&extractor);
+  //
+  // Set the corr. cams:
+  //
+  calloop.SetBadPixels(badcam);
+  //
+  // The next two commands are for the display:
+  //
+  calloop.SetDisplay(display);
+  
+  //
+  // Apply rel. time calibration:
+  //
+  calloop.SetRelTimeCalibration();
+  calloop.SetTimeExtractor(&timeext);
+  //
+  // Do the event-loop:
+  //
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  
+  if (!calloop.Process(pedcam))
+    return;
+
+  badcam.Print();
+  
+  MBadPixelsCam          &badbad  = calloop.GetBadPixels();
+  MCalibrationChargeCam  &calcam  = calloop.GetCalibrationCam();
+  MCalibrationRelTimeCam &timecam = calloop.GetRelTimeCam();
+  MCalibrationQECam      &qecam   = calloop.GetQECam();
+
+  badbad.Print();
+
+  /************************************************************************/
+  /*                THIRD LOOP: DATA CALIBRATION INTO PHOTONS             */
+  /************************************************************************/
+
+  // Create an empty Parameter List and an empty Task List
+  MParList  plist3;  
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+ 
+  // containers
+  MCerPhotEvt         photevt;
+  MPedPhotCam         pedphotcam;
+  MSrcPosCam          srccam;
+  MRawRunHeader       runhead;
+  MExtractedSignalCam sigcam;
+
+  plist3.AddToList(&geomcam );
+  plist3.AddToList(&pedcam  );
+  plist3.AddToList(&calcam  );
+  plist3.AddToList(&qecam   );
+  plist3.AddToList(&badbad  );
+  plist3.AddToList(&timecam );
+  plist3.AddToList(&sigcam  );
+  plist3.AddToList(&photevt);
+  plist3.AddToList(&pedphotcam);
+  plist3.AddToList(&srccam);
+  plist3.AddToList(&runhead);
+
+  //tasks
+  MReadMarsFile read3("Events");
+  read3.DisableAutoScheme();
+  static_cast<MRead&>(read3).AddFiles(druns);
+
+  MArrivalTimeCalc2   timecalc;
+  MCalibrateData      photcalc;     
+  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);  // !!! was only MCalibrate
+  // MPedPhotCalc     pedphotcalc;   // already done by MCalibrate Data
+  // MCerPhotCalc     cerphotcalc;  // already done by MCalibrate Data
+  
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&extractor);
+  tlist3.AddToList(&timecalc);
+  //  tlist3.AddToList(&cerphotcalc); // already done by MCalibrate Data
+  tlist3.AddToList(&photcalc);
+  // tlist3.AddToList(&pedphotcalc);   // already done by MCalibrate Data
+
+  MWriteRootFile write(resname);
+  
+  write.AddContainer("MGeomCam"              , "RunHeaders");
+  write.AddContainer("MRawRunHeader"         , "RunHeaders");
+  write.AddContainer("MSrcPosCam"            , "RunHeaders");
+  write.AddContainer("MCalibrationChargeCam" , "RunHeaders");
+  write.AddContainer("MCalibrationQECam"     , "RunHeaders");
+  //  write.AddContainer("MPedPhotCam","RunHeaders"); // Attention, was in Events - Tree!!
+  write.AddContainer("MPedestalCam"          , "RunHeaders");
+  write.AddContainer("MCalibrationRelTimeCam", "RunHeaders");
+
+  write.AddContainer("MCerPhotEvt"   , "Events");
+  write.AddContainer("MRawEvtHeader" , "Events");
+  write.AddContainer("MBadPixelsCam" , "Events");
+  write.AddContainer("MPedPhotCam"   , "Events");
+
+  tlist3.AddToList(&write);
+  
+  // Create and execute eventloop
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+    
+  cout << "*************************************************************" << endl;
+  cout << "***   COMPUTING DATA USING EXTRACTED SIGNAL (IN PHOTONS)  ***" << endl;
+  cout << "*************************************************************" << endl;
+  
+  if (!evtloop3.Eventloop())  
+    return;  
+  tlist3.PrintStatistics();
+
+}
+
+void CamDraw(TCanvas &c, MHCamera &cam, MCamEvent &evt, Int_t i, Int_t j, Int_t fit)
+{
+
+  c.cd(i);
+  gPad->SetBorderMode(0);
+  MHCamera *obj1=(MHCamera*)cam.DrawCopy("hist");
+  //  obj1->AddNotify(evt);
+  
+  c.cd(i+j);
+  gPad->SetBorderMode(0);
+  obj1->Draw();
+  ((MHCamera*)obj1)->SetPrettyPalette();
+
+  if (fit != 0)
+    {
+      c.cd(i+2*j);
+      gPad->SetBorderMode(0);
+      TH1D *obj2 = (TH1D*)obj1->Projection(obj1.GetName());
+      
+//      obj2->Sumw2();
+      obj2->Draw();
+      obj2->SetBit(kCanDelete);
+
+      const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+      const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+      const Double_t integ = obj2->Integral("width")/2.5066283;
+      const Double_t mean  = obj2->GetMean();
+      const Double_t rms   = obj2->GetRMS();
+      const Double_t width = max-min;
+
+      if (rms == 0. || width == 0. )
+        return;
+      
+      switch (fit)
+        {
+        case 1:
+          TF1 *sgaus = new TF1("sgaus","gaus(0)",min,max);
+          sgaus->SetBit(kCanDelete);
+          sgaus->SetParNames("Area","#mu","#sigma");
+          sgaus->SetParameters(integ/rms,mean,rms);
+          sgaus->SetParLimits(0,0.,integ);
+          sgaus->SetParLimits(1,min,max);
+          sgaus->SetParLimits(2,0,width/1.5);
+          obj2->Fit("sgaus","QLR");
+          obj2->GetFunction("sgaus")->SetLineColor(kYellow);
+          break;
+
+        case 2:
+          TString dgausform = "([0]-[3])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])";
+          dgausform += "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
+          TF1 *dgaus = new TF1("dgaus",dgausform.Data(),min,max);
+          dgaus->SetBit(kCanDelete);
+          dgaus->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}","A_{2}","#mu_{2}","#sigma_{2}");
+          dgaus->SetParameters(integ,(min+mean)/2.,width/4.,
+                               integ/width/2.,(max+mean)/2.,width/4.);
+          // The left-sided Gauss 
+          dgaus->SetParLimits(0,integ-1.5,integ+1.5);
+          dgaus->SetParLimits(1,min+(width/10.),mean);
+          dgaus->SetParLimits(2,0,width/2.);
+          // The right-sided Gauss 
+          dgaus->SetParLimits(3,0,integ);
+          dgaus->SetParLimits(4,mean,max-(width/10.));
+          dgaus->SetParLimits(5,0,width/2.);
+          obj2->Fit("dgaus","QLRM");
+          obj2->GetFunction("dgaus")->SetLineColor(kYellow);
+          break;
+          
+        case 3:
+          TString tgausform = "([0]-[3]-[6])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])";
+          tgausform += "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
+          tgausform += "+[6]/[8]*exp(-0.5*(x-[7])*(x-[7])/[8]/[8])";
+          TF1 *tgaus = new TF1("tgaus",tgausform.Data(),min,max);
+          tgaus->SetBit(kCanDelete);
+          tgaus->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}",
+                             "A_{2}","#mu_{2}","#sigma_{2}",
+                             "A_{3}","#mu_{3}","#sigma_{3}");
+          tgaus->SetParameters(integ,(min+mean)/2,width/4.,
+                               integ/width/3.,(max+mean)/2.,width/4.,
+                               integ/width/3.,mean,width/2.);
+          // The left-sided Gauss 
+          tgaus->SetParLimits(0,integ-1.5,integ+1.5);
+          tgaus->SetParLimits(1,min+(width/10.),mean);
+          tgaus->SetParLimits(2,width/15.,width/2.);
+          // The right-sided Gauss 
+          tgaus->SetParLimits(3,0.,integ);
+          tgaus->SetParLimits(4,mean,max-(width/10.));
+          tgaus->SetParLimits(5,width/15.,width/2.);
+          // The Gauss describing the outliers
+          tgaus->SetParLimits(6,0.,integ);
+          tgaus->SetParLimits(7,min,max);
+          tgaus->SetParLimits(8,width/4.,width/1.5);
+          obj2->Fit("tgaus","QLRM");
+          obj2->GetFunction("tgaus")->SetLineColor(kYellow);
+          break;
+        case 4:
+          obj2->Fit("pol0","Q");
+          obj2->GetFunction("pol0")->SetLineColor(kYellow);
+          break;
+        case 9:
+          break;
+        default:
+          obj2->Fit("gaus","Q");
+          obj2->GetFunction("gaus")->SetLineColor(kYellow);
+          break;
+        }
+      
+        TArrayI s0(3);
+        s0[0] = 6;
+        s0[1] = 1;
+        s0[2] = 2;
+
+        TArrayI s1(3);
+        s1[0] = 3;
+        s1[1] = 4;
+        s1[2] = 5;
+
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TH1D *half[4];
+        half[0] = obj1->ProjectionS(s0, inner, "Sector 6-1-2 Inner");
+        half[1] = obj1->ProjectionS(s1, inner, "Sector 3-4-5 Inner");
+        half[2] = obj1->ProjectionS(s0, outer, "Sector 6-1-2 Outer");
+        half[3] = obj1->ProjectionS(s1, outer, "Sector 3-4-5 Outer");
+
+        for (int i=0; i<4; i++)      
+        {
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->Draw("same");
+        }
+
+      gPad->Modified();
+      gPad->Update();
+      
+    }
+}
+
+
Index: /tags/Mars-V0.9/macros/calibration.C
===================================================================
--- /tags/Mars-V0.9/macros/calibration.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/calibration.C	(revision 9772)
@@ -0,0 +1,613 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  calibration.C
+//
+//  Needs as arguments the run number of a calibration file ("*_C_*.root") and 
+//  the run number of the corresponding pedestal file ("*_P_*.root"). 
+//
+//  The TString inpath has to be set correctly.
+//
+//  The macro searches for the pulser colour which corresponds to the calibration
+//  run number. If the run number is smaller than 20000, pulser colour "CT1" 
+//  is assumed, otherwise, it searches for the strings "green", "blue", "uv" or 
+//  "ct1" in the filenames. If no colour or multiple colours are found, the 
+//  execution is aborted.  
+//
+//  The container MBadPixelsCam is created and followed during the execution of the 
+//  rest of the macro.
+// 
+//  A first loop over the pedestal file is performed using the class MJPedestal
+//
+//  The container MCalibrationQECam is created and followed during the execution of the 
+//  rest of the macro.
+//
+//  A loop over the calibration files is performed using the class MJCalibration. 
+//  The results are displayed using the MJCalibration::SetNormalDisplay() facility, 
+//  but other displays can easily be uncommented. 
+//  The call to MJCalibration skips the relative time calibration, which can be 
+//  uncommented as well. 
+// 
+//  Last, a third loop is performed over the calibration file again in order to 
+//  "calibrate" it and test the resulting outcome.
+//
+//////////////////////////////////////////////////////////////////////////////////////////
+#include <TStyle.h>
+#include <TObject.h>
+#include <TObjectTable.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TH1.h>
+#include <TPaveStats.h>
+#include <TApplication.h>
+#include <TClass.h>
+
+#include "getExtractor.C"
+
+#include "MJPedestal.h"
+#include "MJCalibration.h"
+#include "MJCalibTest.h"
+#include "MJCalibrateSignal.h"
+#include "MRunIter.h"
+#include "MStatusDisplay.h"
+#include "MCalibrationQECamMagic.h"
+#include "MCalibrationQECam.h"
+#include "MBadPixelsCam.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MParContainer.h"
+#include "MGeomCamMagic.h"
+
+using namespace std;
+
+static TString outpath = ".";
+//static TString inpath  = "/home/rootdata/Calib/2004_07_06";
+//static TString inpath  = "/home/rootdata/Calib/2004_11_11";
+//static TString inpath  = "/home/rootdata/Calib/2004_12_18";
+static TString inpath  = "/home/rootdata/Calib/2004_09_21";
+//static TString inpath  = "/home/rootdata/Calib/1999_01_01";
+static TString badfile;
+//static TString badfile = "badpixels_only0_388_559.dat";
+//
+// the default pedestal run for the calibration
+//
+//static const Int_t   pedrun  = 43915;
+static const Int_t   pedrun  = 38995;
+//
+// the default start calibration run 
+//
+static const Int_t   calrun1 = 38997;
+//
+// the default last calibration run (if 0, only one run is taken, otherwise consecutive runs 
+// between calrun1 and calrun2)
+//
+static  const Int_t calrun2 = 0;
+//
+// the default start data run 
+//
+static const Int_t   datrun1 = 39000;
+//
+// the default last calibration run (if 0, only one run is taken, otherwise consecutive runs 
+// between calrun1 and calrun2)
+//
+static  const Int_t datrun2 = 0;
+//
+// A switch to output debugging information about Objects use
+//
+static Bool_t debug = kFALSE;
+//
+// A switch to use the Blind Pixel
+//
+static Bool_t blindpix = kTRUE;
+//
+// A switch to use the PIN Diode 
+//
+static Bool_t pindiode = kFALSE;
+//
+// Tell if you want to use the display:
+//
+static Bool_t useDisplay = kTRUE;
+//
+// Tell if you want to test the result afterwards
+//
+static Bool_t useTest = kFALSE;
+//
+// Tell if you want to test the intensity calibration
+//
+static Bool_t useIntensity  = kFALSE;
+//
+// Tell if you to calibrated interlaced calibration events
+//
+static Bool_t useInterlaced = kTRUE;
+//
+// Tell if you want to store and read the F0 and F1- files
+//
+static Bool_t useStorage    = kTRUE;
+//
+// Tell which extractor you want to use. The flags are counted according 
+// to the extractor-TDAS
+// 
+static Int_t extractorflag = 35;
+//
+Int_t calibration(const UInt_t extflag=extractorflag, const Int_t prun=pedrun, 
+                  const Int_t crun1=calrun1, const Int_t crun2=calrun2, 
+                  const Int_t drun1=datrun1, const Int_t drun2=datrun2)
+{
+
+  cout << extractorflag << endl;
+
+  MExtractor *extractor = getExtractor(extflag==35 ? 32 : extflag);
+
+  if (!extractor)
+    return 99;
+
+  extractor->SetName(Form("%s_Run_%05d",extractor->GetName(),prun));
+  const Bool_t timeandcharge = extractor->InheritsFrom("MExtractTimeAndCharge");
+
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+  gStyle->SetTitleSize(0.35,"u");
+  gStyle->SetTitleFontSize(0.9);
+  gStyle->SetTitleH(0.12);
+  gStyle->SetTitleW(0.95);
+  gStyle->SetLineWidth(1);
+
+  if (debug)
+    TObject::SetObjectStat(kTRUE);
+
+  MRunIter pruns;
+  MRunIter cruns;
+
+  pruns.AddRun(prun,inpath);
+
+  if (crun1!=0)
+    if (crun2==0)
+      cruns.AddRun(crun1,inpath);
+    else
+      cruns.AddRuns(crun1,crun2,inpath);
+
+  MStatusDisplay *display = NULL;
+
+  if (useDisplay)
+    {
+      display = new MStatusDisplay;
+      display->SetUpdateTime(3000);
+      display->Resize(850,700);
+    }
+  
+  /*****************************************/
+  /* FIRST LOOP: PURE PEDESTAL COMPUTATION */
+  /*****************************************/
+  //
+  // Hand over to the jobs a QE Cam with Cornings initialized
+  // 
+  MGeomCamMagic          geomcam;
+  MCalibrationQECamMagic qecam;
+  MBadPixelsCam          badcam;
+  badcam.InitSize(geomcam.GetNumPixels());
+  //
+  // If you want to exclude pixels from the beginning, read 
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)
+  //
+  if (!badfile.IsNull())
+    {
+      ifstream f(badfile.Data());
+      badcam.AsciiRead((istream&)f);  
+      f.close();
+    }
+
+  MJPedestal pedloop1;
+  pedloop1.SetNoStorage();
+  pedloop1.SetEnvDebug(debug);
+  pedloop1.SetExtractor(extractor);
+  pedloop1.SetExtractionFundamental();
+  pedloop1.SetInput(&pruns);
+  pedloop1.SetPathOut(outpath.Data());
+  if (useDisplay)
+    {
+      pedloop1.SetDisplay(display);
+      pedloop1.SetDataCheckDisplay();
+    }
+  pedloop1.SetBadPixels(badcam);
+  
+  if (!pedloop1.Process())
+    return 1;
+
+  /****************************************/
+  /* SECOND LOOP: CALIBRATION COMPUTATION */
+  /****************************************/
+
+  MJPedestal    pedloop2;
+  MJCalibration calloop;
+
+  if (timeandcharge)
+    {
+      /***********************************************************/
+      /* NEEDED FOR SECOND LOOP: EXTRACTOR RESOLUTION COMPUTATION */
+      /***********************************************************/
+      
+      pedloop2.SetUseData();
+      pedloop2.SetNoStorage();
+      pedloop2.SetEnvDebug(debug);
+      pedloop2.SetExtractor(extractor);
+      pedloop2.SetExtractionWithExtractorRndm();
+      pedloop2.SetPedestals(pedloop1.GetPedestalCam());  
+      pedloop2.SetInput(&pruns);
+      pedloop2.SetPathOut(outpath.Data());
+      if (useDisplay)
+        {
+          pedloop2.SetDisplay(display);
+          pedloop2.SetDataCheckDisplay();
+        }
+      pedloop2.SetBadPixels(badcam);
+      
+      if (!pedloop2.Process())
+        return 1;
+      
+      calloop.SetExtractorCam(pedloop2.GetPedestalCam());
+    }
+
+  if (crun1 == 0)
+    return 0;
+
+  MPedestalCam &pedcam = pedloop1.GetPedestalCam();
+
+  if (debug)
+    calloop.SetDebug();
+  calloop.SetEnvDebug(debug);
+  if (useIntensity)
+    calloop.SetIntensity();
+  //  calloop.SetHistsStorage();
+  calloop.SetNoStorage(!useStorage);
+  calloop.SetRelTimeCalibration(kTRUE);
+  //
+  // If you want to set a colour explicitely from outside (not recommanded!)
+  //  calloop.SetColor(MCalibrationCam::kUV);
+  //
+  // If you want to run the data-check on RAW DATA!!!, choose:
+  //  calloop.SetDataCheck();
+  // 
+  // If you want to see the data-check plots only, choose:
+  calloop.SetDataCheckDisplay();
+  //  calloop.SetNormalDisplay();
+  // 
+  // For everything, you have ever dreamed of, choose:
+  //  calloop.SetFullDisplay();
+
+  //
+  // If you want to calibrate the times as well, choose:
+  //
+  calloop.SetExtractor(extractor);
+  calloop.SetInput(&cruns);
+  calloop.SetPathOut(outpath.Data());
+  if (useDisplay)
+    calloop.SetDisplay(display);
+  calloop.SetUseBlindPixel(blindpix);
+  calloop.SetUsePINDiode(pindiode);
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(badcam);
+
+  if (!calloop.Process(pedcam))
+    return 2;
+
+  //
+  // The next lines are the use the Print() function and have 
+  // all the results as ascii-tables:
+  //
+  if (debug)
+    {
+      MCalibrationQECam     &nqecam      = calloop.GetQECam();
+      MBadPixelsCam         &badbad      = calloop.GetBadPixels();
+      MCalibrationChargeCam &chargecam   = calloop.GetCalibrationCam();
+      chargecam.Print();
+      nqecam.Print();
+      badbad.Print();
+    }
+
+  /********************************************************************/
+  /* THIRD LOOP: APPLY CALIBRATION TO THE CALIBRATION FILES FOR TESTS */
+  /********************************************************************/
+
+  if (useTest)
+    {
+      
+      MJCalibTest testloop;
+      
+      // If you want to see the data-check plots only, choose:
+      testloop.SetDataCheckDisplay();
+
+      testloop.SetExtractor(extractor);
+      testloop.SetInput(&cruns);
+      testloop.SetPathOut(outpath);
+      if (useDisplay)
+        testloop.SetDisplay(display);
+      testloop.SetBadPixels(calloop.GetBadPixels());
+      
+      if (!testloop.ProcessFile(pedloop1.GetPedestalCam()))
+        return 3;
+      
+   }
+
+  if (drun1 == 0)
+    return 4;
+
+  MRunIter druns;
+
+  if (drun2==0)
+    druns.AddRun(drun1,inpath);
+  else
+    druns.AddRuns(drun1,drun2,inpath);
+
+
+  /********************************************************************/
+  /* FOURTH LOOP: APPLY CALIBRATION TO THE PEDESTAL FILES             */
+  /********************************************************************/
+
+  if (extflag == 35)
+    {
+      delete extractor;
+      extractor = getExtractor(28);
+    }
+  
+  MJCalibrateSignal calibloop;
+
+  //  calibloop.SetExtractor(extractor);
+  calibloop.SetInputCal(&cruns);
+  calibloop.SetInput(&druns);
+  calibloop.SetPathIn(outpath);
+  if (useDisplay)
+    calibloop.SetDisplay(display);
+  //  calibloop.SetBadPixels(calloop.GetBadPixels());
+  //  calibloop.SetNoStorage(!useStorage);
+  calibloop.SetInterlaced(useInterlaced);
+  
+  if (!calibloop.ProcessFile(pedloop1.GetPedestalCam(),
+                             timeandcharge ? pedloop2.GetPedestalCam() : pedloop1.GetPedestalCam(), 
+                             timeandcharge ? pedloop2.GetPedestalCam() : pedloop1.GetPedestalCam()))
+    return 5;
+
+  if (debug)
+    TObject::SetObjectStat(kFALSE);
+
+  //
+  // Debugging at the end:
+  // 
+  if (debug)
+    gObjectTable->Print();
+
+  return 0;
+}
+
+static void Usage()
+{
+    gLog << endl;
+    gLog << "Usage:" << endl;
+    gLog << endl;
+    gLog << "   calibration [ped.run nr.] [first cal.run nr.] [last cal.run nr.] [first dat.run nr.] [last dat.run nr.]" << endl ;
+    gLog << endl;
+    gLog << "   ped.run.nr:        Run number of the pedestal file." << endl;
+    gLog << "   first cal.run nr.: Run number of the first calibration file." << endl;
+    gLog << "   last  cal.run nr.: Run number of the last  calibration file." << endl;
+    gLog << "   first dat.run nr.: Run number of the first data file to be calibrated." << endl;
+    gLog << "   last  dat.run nr.: Run number of the last  data file to be calibrated." << endl;
+    gLog << endl;
+    gLog << "All calibration runs between (first cal.run nr.) and (last cal.run nr.) will be used" << endl;
+    gLog << "If last.cal.run.nr is 0 (default), only one calibration run is taken"                  << endl;
+    gLog << endl;
+    gLog << "All data runs between (first dat.run nr.) and (last dat.run nr.) will be used" << endl;
+    gLog << "If last.dat.run.nr is 0 (default), only one data run is taken"                  << endl;
+    gLog << endl;
+    gLog << "Additional Options: " << endl;
+    gLog << "     --extractor=#    Choose one of the following possible extractors (integer)" << endl;
+    gLog << "                      (default: Nr. 33)                                        " << endl;
+    gLog << endl;
+    gLog << "    Nr.    Extractor   Parameters " << endl;
+    gLog << endl;    
+    gLog << "       MExtractFixedWindow: " << endl;
+    gLog << "           with the following parameters: " << endl;
+    gLog << "     1:           SetRange(4,7,6,9) " << endl;
+    gLog << "     2:           SetRange(4,7,5,10)" << endl;
+    gLog << "     3:           SetRange(3,8,5,10)" << endl;
+    gLog << "     4:           SetRange(2,9,4,11)" << endl;
+    gLog << "     5:           SetRange(0,13,4,13)" << endl;
+    gLog << "       MExtractFixedWindowSpline: " << endl;
+    gLog << "     6:           SetRange(3,7,5,9)" << endl;
+    gLog << "     7:           SetRange(3,7,5,11)" << endl;
+    gLog << "     8:           SetRange(3,9,5,11)" << endl;
+    gLog << "     9:           SetRange(2,10,4,12)" << endl;
+    gLog << "     10:          SetRange(0,14,4,14)" << endl;
+    gLog << "       MExtractFixedWindowPeakSearch: " << endl;
+    gLog << "                  SetRange(0,18,2,14) and the following parameters:" << endl;
+    gLog << "     11:          SetWindows(2,2,2)" << endl;
+    gLog << "                  SetOffsetFromWindow(0)" << endl;
+    gLog << "     12:          SetWindows(4,4,2)" << endl;
+    gLog << "                  SetOffsetFromWindow(1)" << endl;
+    gLog << "     13:          SetWindows(4,6,4)" << endl;
+    gLog << "                  SetOffsetFromWindow(0)" << endl;
+    gLog << "     14:          SetWindows(6,6,4)" << endl;
+    gLog << "                  SetOffsetFromWindow(1)" << endl;
+    gLog << "     15:          SetWindows(8,8,4)" << endl;
+    gLog << "                  SetOffsetFromWindow(1)" << endl;
+    gLog << "     16:          SetWindows(14,10,4)" << endl;
+    gLog << "                  SetOffsetFromWindow(2)" << endl;
+    gLog << "      MExtractTimeAndChargeSlidingWindow:" << endl;
+    gLog << "                  SetRange(0,18,2,14) and the following parameters:" << endl;
+    gLog << "     17:          SetWindowSize(2,2)" << endl;
+    gLog << "     18:          SetWindowSize(4,4)" << endl;
+    gLog << "     19:          SetWindowSize(4,6)" << endl;
+    gLog << "     20:          SetWindowSize(6,6)" << endl;
+    gLog << "     21:          SetWindowSize(8,8)" << endl;
+    gLog << "     22:          SetWindowSize(14,10)" << endl;
+    gLog << "      MExtractTimeAndChargeSpline: " << endl; 
+    gLog << "     23:          SetChargeType(MExtractTimeAndChargeSpline::kAmplitude) and:" << endl;
+    gLog << "                  SetRange(0,13,2,13) " << endl; 
+    gLog << "     24:          SetChargeType(MExtractTimeAndChargeSpline::kIntegral) and:" << endl;
+    gLog << "                  SetRiseTime(0.5); SetFallTime(0.5)" << endl;
+    gLog << "     25:          SetRiseTime(0.5); SetFallTime(1.5)" << endl;
+    gLog << "     26:          SetRiseTime(1.0); SetFallTime(3.0)" << endl;
+    gLog << "     27           SetRiseTime(1.5); SetFallTime(4.5)" << endl;
+    gLog << "      MExtractTimeAndChargeDigitalFilter" << endl;
+    gLog << "                  SetRange(0,18,2,14) and the following parameters:" << endl; 
+    gLog << "     28:          SetNameWeightsFile('msignal/cosmics_weights.dat')" << endl;
+    gLog << "     29:          SetNameWeightsFile('msignal/cosmics_weights4.dat')" << endl;
+    gLog << "     30:          SetNameWeightsFile('msignal/cosmics_weights_logain6.dat')" << endl;
+    gLog << "     31:          SetNameWeightsFile('msignal/cosmics_weights_logain4.dat')" << endl;
+    gLog << "     32:          SetNameWeightsFile('msignal/calibration_weights_UV.dat')" << endl;
+    gLog << "     33:          SetNameWeightsFile('msignal/calibration_weights_UV_logain.dat')" << endl;
+    gLog << "     34:          SetNameWeightsFile('msignal/MC_weights.dat')" << endl;
+    gLog << "     35:          SetNameWeightsFile('msignal/cosmics_weights.dat') (for cosmics) and" << endl;
+    gLog << "                  SetNameWeightsFile('msignal/calibration_weights_UV.dat') (for cal.)" << endl;
+    gLog << "      MExtractTimeAndChargeDigitalFilterPeakSearch" << endl;
+    gLog << "     36:          SetNameWeightsFile('msignal/calibration_weights_UV.dat')" << endl;
+    gLog << endl;
+    
+    gLog << "     --inpath=#          Find the data in inpath"                      << endl;
+    gLog << "     --outpath=#         Write the output containers to outpath"       << endl;
+    gLog << "     --badfile=#         Use the file # to exclude pixels from the beginning" << endl;
+    gLog << "     --debug             Use the TObjectTable for debugging    "       << endl;
+    gLog << "                             and write out the pixels as ascii tables" << endl;
+    gLog << "     --useInterlaced     Use the program to calibrate data with the interlaced cal. events" << endl;
+    gLog << "     --useTest           Use the class MJCalibTest to test the calibration on itself" << endl;
+    gLog << "     --skipBlindPix      Skip the blind pixel calibration"             << endl;
+    gLog << "     --skipPINDiode      Skip the PIN Diode   calibration"             << endl;
+}
+
+
+int main(int argc, char **argv)
+{
+
+
+  MArray::Class()->IgnoreTObjectStreamer();
+  MParContainer::Class()->IgnoreTObjectStreamer();
+  //
+  // Evaluate arguments
+  //
+  MArgs arg(argc, argv);
+  
+  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+      Usage();
+      return -1;
+    }
+  
+  debug         = arg.HasOnlyAndRemove("--debug")    || arg.HasOnlyAndRemove("-d");
+  useTest       = arg.HasOnlyAndRemove("--useTest")  || arg.HasOnlyAndRemove("-t");
+  useInterlaced = arg.HasOnlyAndRemove("--useInterlaced")  || arg.HasOnlyAndRemove("-i");
+  blindpix      = !(arg.HasOnlyAndRemove("--skipBlindPix"));
+  pindiode      = !(arg.HasOnlyAndRemove("--skipPINDiode"));
+
+  if (arg.HasOption("--extractor="))
+    extractorflag = arg.GetIntAndRemove("--extractor=");
+
+  if (arg.HasOption("--inpath="))
+    inpath = arg.GetStringAndRemove("--inpath=");
+
+  if (arg.HasOption("--outpath="))
+    outpath = arg.GetStringAndRemove("--outpath=");
+
+  if (arg.HasOption("--badfile="))
+    badfile = arg.GetStringAndRemove("--badfile=");
+
+  if (gSystem->AccessPathName(badfile,kFileExists))
+  {
+    gLog << "WARNING: the bad pixels file '" << badfile.Data() << "' doesn't exist." << endl;
+    badfile = "";
+  }
+
+  // check for the right usage of the program
+  //
+  if (arg.GetNumArguments()>6)
+    {
+      Usage();
+      return -1;
+    }
+
+  //
+  // Initialize Non-GUI (batch) mode
+  //
+  gROOT->SetBatch();
+  
+  //
+  // Switch off the display
+  //
+  useDisplay = kTRUE;
+  //
+  // check for the arguments
+  //
+  Int_t pedr  = 0;
+  Int_t calr1 = 0;
+  Int_t calr2 = 0;
+  Int_t datr1 = 0;
+  Int_t datr2 = 0;
+
+  const Int_t nargs = arg.GetNumArguments();
+
+  if (nargs>=5)
+    {
+      pedr = arg.GetArgumentInt(0);
+      calr1 = arg.GetArgumentInt(1);
+      calr2 = arg.GetArgumentInt(2);
+      datr1 = arg.GetArgumentInt(3);
+      datr2 = arg.GetArgumentInt(4);
+      return calibration(extractorflag,pedr,calr1,calr2,datr1,datr2);
+    }
+
+  if (nargs>=4)
+    {
+      pedr = arg.GetArgumentInt(0);
+      calr1 = arg.GetArgumentInt(1);
+      calr2 = arg.GetArgumentInt(2);
+      datr1 = arg.GetArgumentInt(3);
+      datr2 = arg.GetArgumentInt(4);
+      return calibration(extractorflag,pedr,calr1,calr2,datr1,0);
+    }
+
+  if (nargs>=3)
+    {
+      pedr = arg.GetArgumentInt(0);
+      calr1 = arg.GetArgumentInt(1);
+      calr2 = arg.GetArgumentInt(2);
+      return calibration(extractorflag,pedr,calr1,calr2,0);
+    }
+
+  if (nargs>=2)
+    {
+      pedr = arg.GetArgumentInt(0);
+      calr1 = arg.GetArgumentInt(1);
+      gLog << "PEDR: " << pedr << " CALR1: " << calr1 << " CALR2 " << calr2 << endl;
+      gLog << "inpath: " << inpath << endl;
+      gLog << "extractor: " << extractorflag << endl;
+      return calibration(extractorflag,pedr,calr1,0,0);
+    }
+
+  if (nargs>=1)
+    {
+      pedr = arg.GetArgumentInt(0);
+      return calibration(extractorflag,pedr,0);
+    }
+
+  return calibration(extractorflag,pedr,calr1,calr2);
+}
+
Index: /tags/Mars-V0.9/macros/collarea.C
===================================================================
--- /tags/Mars-V0.9/macros/collarea.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/collarea.C	(revision 9772)
@@ -0,0 +1,191 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Abelardo Moralejo, 2/2005 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+// 
+// Example macro on how to calculate effective areas. The input is a file 
+// containing Hillas parameters of the MC events surviving a certain kind 
+// of analysis. It must also contain a tree called "OriginalMC" with a branch
+// "MMcEvtBasic" and one entry per original simulated shower used to produce
+// the events in that input file. The current (2/2005) camera simulation in 
+// the cvs already writes out all events with the MMcEvtBasic container to
+// the Events tree. In Mars/macros/mccalibrate.C and starmc2.C you can see
+// how this branch is put to a separate tree "OriginalMC" and written out
+// to the "star" file. This will not work with star files not containing this
+// extra tree. Please contact moralejo@pd.infn.it in case of questions
+// about this new approach to the calculation of effective areas.
+//
+
+void collarea(TString filename="star_gamma_test.root", TString outname="area.root")
+{
+  MStatusDisplay *d = new MStatusDisplay;
+    // redirect logging output to GUI, kFALSE to disable stream to stdout
+  d->SetLogStream(&gLog, kTRUE);
+
+  //
+  // First loop: fill the MHMcCollectionArea::fHistAll histogram containing
+  // all the events produced at the Corsika level:
+  //
+  MParList  parlist;
+  MTaskList tasklist;
+
+  parlist.AddToList(&tasklist);
+
+  //
+  // Setup out tasks:
+  //  - First we have to read the events
+  //
+  MReadMarsFile reader("OriginalMC", filename);
+  reader.DisableAutoScheme();
+
+  //
+  // Create collection area object and add it to the task list
+  //
+  MHMcCollectionArea collarea;
+  parlist.AddToList(&collarea);
+
+  //
+  // Set the COARSE binnings in which you will divide your data, to get
+  // the collection area in these same binnings. You can set also this
+  // binnings on an existing and filled MHMcCollectionAreaObject, and
+  // call Calc again to get the effective area in other coarse bins.
+  //
+  MBinning binsTheta("binsTheta");
+  MBinning binsEnergy("binsEnergy"); // name must be standardized!
+  Int_t nbins = 8;
+  TArrayD edges(nbins+1);
+  edges[0] = 0;
+  edges[1] = 10.;
+  edges[2] = 20.;
+  edges[3] = 30.;
+  edges[4] = 40.;
+  edges[5] = 50.;
+  edges[6] = 60.;
+  edges[7] = 70.;
+  edges[8] = 80.;
+  binsTheta.SetEdges(edges);              // Theta [deg]
+  binsEnergy.SetEdgesLog(20, 2., 20000);  // Energy [GeV]
+  parlist.AddToList(&binsTheta);
+  parlist.AddToList(&binsEnergy);
+
+  // Task which fills the necessary histograms in MHMcCollectionArea
+  MMcCollectionAreaCalc effi;
+
+  // Tentative energy spectrum. This may slightly modify the calculation
+  // of effective areas. If not added to the parameter list, a flat spectrum
+  // in dN/dE will be assumed. "x" stands for the energy. The name of the 
+  // function must be standardized!
+
+  TF1 Spectrum("Spectrum", "pow(x,-5.)");
+  effi.SetSpectrum(&Spectrum);
+
+  tasklist.AddToList(&reader);
+  tasklist.AddToList(&effi);
+
+  //
+  // set up the loop for the processing
+  //
+  MEvtLoop magic;
+  magic.SetParList(&parlist);
+
+  //
+  // Start to loop over all events
+  //
+  magic.SetDisplay(d);
+
+  if (!magic.Eventloop())
+    return;
+
+  tasklist.PrintStatistics();
+
+
+  //
+  // Second loop: now fill the histogram MHMcCollectionArea::fHistSel
+  //
+
+  MParList parlist2;
+  MTaskList tasklist2;
+  parlist2.AddToList(&tasklist2);
+  parlist2.AddToList((MHMcCollectionArea*)parlist->FindObject("MHMcCollectionArea"));
+
+  MReadMarsFile reader2("Events", filename);
+  reader2.DisableAutoScheme();
+
+  tasklist2.AddToList(&reader2);
+
+  // The same task as before, now will fill MHMcCollectionArea::fHistSel
+  // and call MHMcCollectionArea::Calc in the PostProcess
+  tasklist2.AddToList(&effi);
+
+  //
+  // set up the loop for the processing
+  //
+  MEvtLoop magic2;
+  magic2.SetParList(&parlist2);
+
+  //
+  // Start to loop over all events
+  //
+  magic2.SetDisplay(d);
+
+  if (!magic2.Eventloop())
+    return;
+
+  tasklist2.PrintStatistics();
+
+  //
+  // Now the histogram we wanted to get out of the data is
+  // filled and can be displayed
+  //
+  if ((d = magic2.GetDisplay()))
+    d->AddTab("Collection Area");
+  else
+    new TCanvas("CollArea", "Result of the collection area calculation");
+
+  gStyle->SetPalette(1,0);
+  gPad->SetLogx();
+  TH2D* areaplot = ((MHMcCollectionArea*)parlist2.FindObject
+		    ("MHMcCollectionArea"))->GetHistCoarse();
+
+  areaplot->SetStats(0);
+  areaplot->SetTitle("Effective area (m^{2})");
+  areaplot->GetXaxis()->SetTitle("Energy (GeV)");
+  areaplot->GetYaxis()->SetTitle("\\theta (deg)");
+  areaplot->DrawCopy("zcol");
+
+  //
+  // Write histogram to a file in case an output
+  // filename has been supplied
+  //
+
+  if (outname.IsNull())
+    return;
+
+  TFile f(outname, "recreate");
+  if (!f)
+    return;
+
+  // Write to the output file:
+  parlist2.FindObject("MHMcCollectionArea")->Write();
+}
Index: /tags/Mars-V0.9/macros/comprob.C
===================================================================
--- /tags/Mars-V0.9/macros/comprob.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/comprob.C	(revision 9772)
@@ -0,0 +1,130 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   macro comprob.C
+!
+!   Author(s): Abelardo Moralejo
+!   Author(s): Thomas Bretz, 2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+//  This macro demonstrates one way of gamma hadron separation using the
+//  composite probability method. To use it you need a star-file (which is
+//  a file ouput by the star.C macro containing image parameters)
+//
+///////////////////////////////////////////////////////////////////////////
+void comprob()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    // Create task list and add it to the parameter list:
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // First task in list: read the star file (reference data)
+    MReadMarsFile read("Events", "star.root");
+    read.DisableAutoScheme();
+    tlist.AddToList(&read);
+
+    //
+    // Task to do the composite analysis of Hillas parameters:
+    // Add(rule, number of bins, lower limit, upper limit)
+    // For the meaning of the rule see MDataChain
+    //
+    MHCompProb compprob(500);
+    compprob.Add("MHillas.fWidth",              500,    0, 160);
+    compprob.Add("MHillas.fLength",             500,    0, 300);
+    compprob.Add("abs(MHillas.fAsym)",          500,    0, 400);
+    compprob.Add("MHillasSrc.fDist",            500,    0, 400);
+    compprob.Add("abs(MHillasSrc.fHeadTail)",   500,    0, 400);
+    compprob.Add("abs(MHillas.fM3Long)",        500,    0, 300);
+    compprob.Add("abs(MHillas.fM3Trans)",       500,    0, 150);
+    compprob.Add("MHillas.fConc1",              500,    0, 0.6);
+    compprob.Add("MHillas.fConc",               500,    0, 0.9);
+    compprob.Add("log10(MHillas.fSize)",        500,    0,   5);
+
+    plist.AddToList(&compprob);
+
+    MFillH fill(&compprob, "MMcEvt");
+
+    // Use this if you want to do it for a fixed energy range:
+    /*
+     MF filter("MMcEvt.fEnergy < 100");
+     fill->SetFilter(&filter);
+     tlist.AddToList(&filter);
+     */
+
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    // Loop over all data to fill the "normal" histograms:
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    gLog.SetDebugLevel(2);
+
+    // Loop to fill the variable bin histograms:
+    read.SetEventNum(0);
+    if (!evtloop.Eventloop())
+        return;
+
+    // ------------------------------------------------------------------
+
+    // Create task list and replace the old task list with the new one
+    MTaskList tlist2;
+    plist.Replace(&tlist2);
+
+    // First task in list: read star file (test data)
+    MReadMarsFile read2("Events", "star2.root");
+    read2.DisableAutoScheme();
+    tlist2.AddToList(&read2);
+
+    // create task to calculate composite probabilities
+    MCompProbCalc calc;
+    tlist2.AddToList(&calc);
+
+    // fill probabilities (hadroness) into histogram
+    MFillH fill2("MHHadronness");
+    tlist2.AddToList(&fill2);
+
+    // Loop to fill the hadronness histograms:
+    if (!evtloop.Eventloop())
+        return;
+
+    //
+    // Display the hadroness histograms and print some informations on
+    // the console window
+    //
+    plist.FindObject("MHHadronness")->DrawClone();
+    plist.FindObject("MHHadronness")->Print();
+}
+
Index: /tags/Mars-V0.9/macros/datatrigcheck.C
===================================================================
--- /tags/Mars-V0.9/macros/datatrigcheck.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/datatrigcheck.C	(revision 9772)
@@ -0,0 +1,227 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante, 3/2004 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  datatrigcheck 
+//
+//  This macro is the standard trigger's parameters checking stuff
+//  
+//
+/////////////////////////////////////////////////////////////////////////////
+Double_t myPoisson(Double_t *x, Double_t *par)
+{
+  Double_t a=0.0, b=0.0, c=0.0;
+  Double_t fitval = 0.0;
+
+  Int_t floorX = (Int_t)TMath::Floor(x[0]);
+  a = TMath::Power(par[0],floorX);
+  b = TMath::Exp(-par[0]);
+  c = TMath::Factorial(floorX);
+ 
+  if (c!=0)
+    fitval = par[1]*a*b/c;
+
+  return fitval;
+}
+
+Double_t myExp(Double_t *x, Double_t *par)
+{
+  Double_t a=0.0;
+  Double_t fitval = 0.0;
+
+  a = TMath::Exp(-x[0]);
+  fitval = par[0]*a;
+
+  return fitval;
+}
+
+// The macro
+//  Input:
+//   1. The directory path starting from the Period (the complete path is
+//       written in the basedir variable)
+//   2. The data filename (without extension)
+//
+void datatrigcheck(TString dirin="Period014/rootdata/2004_02_17/", TString filein="20040117_03695_D_Crab-On_E")
+{
+ 
+  // Set file name and INPUT and OUTPUT directories
+  
+  TString basedir="/data1/earth/magic/data/";
+  
+  TString filenamein(filein);
+  TString dirnamein(dirin);
+  
+  dirnamein = basedir+dirnamein;
+  filenamein = dirnamein + filein + ".root";
+  
+  // Here the output plots are saved
+  TString webdatadir = basedir + "webdata/" + filein + "/";   
+  
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  MTaskList tlist;
+  
+  plist.AddToList(&tlist);
+  
+  MReadMarsFile read("Events");
+  read.DisableAutoScheme();
+  read.AddFile(filenamein);
+  
+  tlist.AddToList(&read);
+  
+  //
+  // Extract Number of events
+  //
+  const Int_t numEvt = read.GetEntries();
+
+  cout << "Opened file " << filenamein << " with "<< numEvt << " events." << endl;
+  // ==================
+  // Create histos
+  // FIXME: should be created using MH or similar?
+  
+  // HISTcom-hTrigPatternEvt
+  // The trigger pattern is shown as a decimal number
+  // The trigger pattern consists of 16 bits (8+8 bits) generated by the trigger system. 
+  // The first 8 bits correspond to the trigger configuration before the prescaling, 
+  // the others after prescaling.
+  //    Bit structure: 
+  //          not prscd | prscaled
+  //          xxxx xxxx xxxx xxxx    <-- pattern (x=0,1)
+  //    bit   7654 3210 7654 3210
+  //
+    TH1I *hTrigPatternEvt = new TH1I("hTrigPatternEvt","Trigger Pattern vs. Event Number",numEvt,0,(Axis_t)numEvt);
+
+    // HISTcom-hTimeEvt
+    // Absolute time vs event number 
+    // The Absolute time has been calculated using the MTime->GetTime() (millisec) and the MTime->GetMjd() (nanosec)
+    TH1D *hTimeEvt = new TH1D("hTimeEvt","DAQ Time vs. Event Number",numEvt,0,(Axis_t)numEvt);
+    
+    // HISTcom-hTimeDiffEvt
+    TH1D *hTimeDiffEvt = new TH1D("hTimeDiffEvt","Differences of time vs. Event Number",numEvt-1,0,(Axis_t)numEvt-1);
+ 
+    // HISTcom-hTimeDiff
+    TH1D *hTimeDiff = new TH1D("hTimeDiff","Distribution of differences of time (ns)",200,0,1000000);
+    
+
+    TF1 *func1 = new TF1("myPoisson",myPoisson,0,10,2);
+    TF1 *func2 = new TF1("myExp",myExp,0,10,1);
+
+    cout << "*func defined" << endl;
+    func1->SetParameters(1.0,1.0);
+    func2->SetParameter(0,400.0);
+    cout << "parameters setted" << endl;
+    func1->SetParNames("MU","CONST");
+    func2->SetParNames("A");
+
+    //
+    // Create and set up the eventloop
+    //
+    MProgressBar bar;
+
+    MEvtLoop evtloop;
+    evtloop.SetProgressBar(&bar);
+    evtloop.SetParList(&plist);
+
+    Double_t tOld;  // buffer variable
+    Double_t tMin = 1E+10;
+    Double_t tMax = -1E+10;
+    Double_t DAQNumMin = 1E+10;
+    //
+    // Execute your analysis
+    //
+    //if (!evtloop.Eventloop())
+    //    return;
+    if (!evtloop.PreProcess())
+    return;
+    
+    while (tlist.Process())
+      {
+	// Create the container MRawEvtHeader where time and trigger 
+	//  info are read and stored.
+	MRawEvtHeader *evtHeader = (MRawEvtHeader *)plist->FindObject("MRawEvtHeader");
+	MTime *evtTime = (MTime *)plist->FindObject("MTime");
+
+	Long_t ms = evtTime->GetTime();
+	Double_t ns = ((evtTime->GetMjd()-TMath::Floor(evtTime->GetMjd()))*(Double_t)evtTime->kDay-(Double_t)ms)*1E+6;
+	Double_t t = (Double_t)ms+ns/1.E+6;
+	if (t<tMin) tMin=t;
+
+	// Fill the histos
+	hTrigPatternEvt->Fill(evtHeader->GetDAQEvtNumber(),evtHeader->GetTriggerID());
+ 	hTimeEvt->Fill(evtHeader->GetDAQEvtNumber(),t);
+	if (evtHeader->GetDAQEvtNumber() != 0){
+	  hTimeDiffEvt->Fill(evtHeader->GetDAQEvtNumber(),t-tOld);
+	  hTimeDiff->Fill((t-tOld)*1E+6);
+	}
+	if (t-tOld > tMax) tMax = t-tOld;
+	tOld = t;
+      }
+
+    //TString command = "./macros/create_web_folder.sh " + webdatadir + filein ;
+
+    // Create new directory with the same name of the run.
+    // Delete old content.
+    //
+    TString command = "mkdir -p " + webdatadir ;
+    system ( command.Data() ) ;
+    command = "rm -f " + webdatadir + "*.gif" ;
+    system ( command.Data() ) ;
+    command = "rm -f " + webdatadir + "*.txt" ;
+    system ( command.Data() ) ;
+
+    tlist.PrintStatistics();
+
+    // Draw Plots and save them as gif images
+    //
+    c1 = new TCanvas( "c1" );
+    hTrigPatternEvt->SetXTitle("Event");
+    hTrigPatternEvt->SetYTitle("Trigger Pattern");
+    hTrigPatternEvt->Draw();
+    c1->Print(webdatadir+hTrigPatternEvt->GetName()+".gif");
+
+    c2 = new TCanvas( "c2" );
+    hTimeEvt->SetXTitle("Event");
+    hTimeEvt->SetYTitle("Abs. time (ms)");
+    hTimeEvt->SetMinimum(tMin);
+    hTimeEvt->Draw();
+    c2->Print(webdatadir+hTimeEvt->GetName()+".gif");
+
+    c3 = new TCanvas( "c3" );
+    hTimeDiffEvt->SetXTitle("Event");
+    hTimeDiffEvt->SetYTitle("Time diff (ms)");
+    hTimeDiffEvt->SetMaximum(tMax*1.1);
+    hTimeDiffEvt->Draw();
+    c3->Print(webdatadir+hTimeDiffEvt->GetName()+".gif");
+
+    c4 = new TCanvas( "c4" );
+    hTimeDiff->SetXTitle("Time diff. (ms)");
+    hTimeDiff->SetYTitle("Events");
+    hTimeDiff->Draw();
+    c4->Print(webdatadir+hTimeDiff->GetName()+".gif");
+
+}
Index: /tags/Mars-V0.9/macros/derotatedc.C
===================================================================
--- /tags/Mars-V0.9/macros/derotatedc.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/derotatedc.C	(revision 9772)
@@ -0,0 +1,104 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// derotatedc.C
+// ============
+//
+// Derotate a MCamEvent and fill a histogram with derotated data
+// (sky-plot).
+//
+// As an input you need a merpped root file conataining DC information
+// from a camera report file. To be able to derotate you also need
+// aproproitate time-stamps and the corresponding pointing information.
+//
+// All events are filled into a 2D histograms - derotated.
+//
+// The example shows the usage of MHCamEventRot. The output is the derotated
+// sky-plot.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void derotatedc()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // Define Observatory location (for derotation)
+    MObservatory obs;
+    plist.AddToList(&obs);
+
+    // Set the camera geometry (for histogram size)
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+
+    // setup pointing position
+    MPointingPos ppos;
+    ppos.SetSkyPosition(MAstro::Hms2Hor(5, 34, 31.9), MAstro::Dms2Deg(22, 0, 52.0));
+    plist.AddToList(&ppos);
+
+    // Define which file to read
+    MReadTree read("Currents", "../dc.root");
+    read.DisableAutoScheme();
+
+    // Derotated histogram to fill
+    MHCamEventRot hist;
+
+    // Set name of time container corresponding to your data
+    hist.SetNameTime("MTimeCurrents");
+
+    // Setup fill task
+    MFillH fill(&hist, "MCameraDC");
+
+    // Set a draw option for your 2D histogram
+    //fill.SetDrawOption("colz");
+
+    // Setup tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    MStatusDisplay *d = new MStatusDisplay;
+    evtloop.SetDisplay(d);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+}
Index: /tags/Mars-V0.9/macros/dohtml.C
===================================================================
--- /tags/Mars-V0.9/macros/dohtml.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/dohtml.C	(revision 9772)
@@ -0,0 +1,134 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// dohtml.C
+// ========
+//
+// This is a service macro used to create the html-documentation from
+// source code (THtml)
+//
+// Add here all directories in which files are stored from which the
+// documentation should be created an add all macros which should be
+// converted to HTML.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void dohtml()
+{
+    //
+    //  don't forget that the shared object must have been loaded
+    //
+
+    //
+    // Do not print 'Info' messages from the root system such like
+    // TCanvas::Print
+    //
+    gErrorIgnoreLevel=kWarning;
+
+    //
+    //   create the html document class
+    //
+    THtml html;
+
+    TString sourcedir;
+    sourcedir += "manalysis:";
+    sourcedir += "mastro:";
+    sourcedir += "mbadpixels:";
+    sourcedir += "mbase:";
+    sourcedir += "mcamera:";
+    sourcedir += "mcalib:";
+    sourcedir += "mdata:";
+    sourcedir += "mfbase:";
+    sourcedir += "mfileio:";
+    sourcedir += "mfilter:";
+    sourcedir += "mfit:";
+    sourcedir += "mgeom:";
+    sourcedir += "mgui:";
+    sourcedir += "mhbase:";
+    sourcedir += "mhflux:";
+    sourcedir += "mhft:";
+    sourcedir += "mhist:";
+    sourcedir += "mhistmc:";
+    sourcedir += "mhcalib:";
+    sourcedir += "mhvstime:";
+    sourcedir += "mimage:";
+    sourcedir += "mjobs:";
+    sourcedir += "mmain:";
+    sourcedir += "mmc:";
+    sourcedir += "mmontecarlo:";
+    sourcedir += "mmuon:";
+    sourcedir += "mpointing:";
+    sourcedir += "mpedestal:";
+    sourcedir += "mranforest:";
+    sourcedir += "mraw:";
+    sourcedir += "mreflector:";
+    sourcedir += "mreport:";
+    sourcedir += "msignal:";
+    sourcedir += "mstarcam:";
+    sourcedir += "msql:";
+    sourcedir += "mtools:";
+    sourcedir += "mtrigger:";
+    sourcedir += ".:";
+
+    html.SetSourceDir(sourcedir);
+    html.SetOutputDir("htmldoc");
+
+    html.MakeAll(kTRUE);
+
+    html.SetSourceDir("macros");
+    html.Convert("merpp.C",         "MARS - Merging and Preprocessing");
+    html.Convert("readraw.C",       "MARS - How To Read A Raw");
+    html.Convert("rootlogon.C",     "MARS - rootlogon.C");
+    html.Convert("readCT1.C",       "MARS - Read and display CT1 Events");
+    html.Convert("readMagic.C",     "MARS - Read and display Magic Events");
+    html.Convert("CT1Hillas.C",     "MARS - Calculate CT1 Hillas");
+    html.Convert("MagicHillas.C",   "MARS - Calculate Magic Hillas");
+    html.Convert("collarea.C",      "MARS - Calculate Collection Area from a MC root file");
+    html.Convert("threshold.C",     "MARS - Calculate Energy Threshold from a MC root file");
+    html.Convert("trigrate.C",      "MARS - Calculate Trigger Rate from a MC root file");
+    html.Convert("star.C",          "MARS - (St)andard (A)nalysis and (R)econstruction");
+    html.Convert("starplot.C",      "MARS - Plot parameters from file created with star.C");
+    html.Convert("comprob.C",       "MARS - Calculation of composite probabilities for G/H-Seperation");
+    html.Convert("multidimdist.C",  "MARS - Calculation of multidimensional distances for G/H-Seperation");
+    html.Convert("multidimdist2.C", "MARS - Calculation of multidimensional distances for G/H-Seperation");
+    html.Convert("estimate.C",      "MARS - Shows results from the energy estimation");
+    html.Convert("estfit.C",        "MARS - Fits the coefficients of the energy estimator MEnergyEstParam");
+    html.Convert("plot.C",          "MARS - Plots 1D mars histogram");
+    html.Convert("plot2.C",         "MARS - Plots a 2D mars histogram");
+    html.Convert("starplot.C",      "MARS - Plots data from a STAR-file into a mars histogram");
+    html.Convert("testenv.C",       "MARS - Example to use TEnv and Mars Eventloops");
+    html.Convert("triglvl2.C",      "MARS - Example to use MMcTriggerLvl2 class, using filters and creating histograms");
+    html.Convert("status.C",        "MARS - Example to use the online display");
+    html.Convert("calibration.C",   "MARS - Example to use the calibration");
+    html.Convert("pedvsevent.C",    "MARS - Example to use MPedCalcPedRun");
+    html.Convert("pedphotcalc.C",   "MARS - Example to use MPedPhotCalc");
+    html.Convert("sectorvstime.C",  "MARS - Example how to plot mean value of a camera sector versus time");
+    html.Convert("calibration.C",   "MARS - Example how to use the calibrationa camera ");
+    html.Convert("bootcampstandardanalysis.C", "MARS - Example of the status of the standard analysis at the bootcamp");
+    html.Convert("readIPR.C",       "MARS - Example to read and display the IPRs from a (merpped) report file");
+    html.Convert("extendcam.C",     "MARS - Example of using MGeomCamExtend and MHexagonalFTCalc");
+    html.Convert("hft.C",           "MARS - Example of using MHexagonalFTCalc");
+}
Index: /tags/Mars-V0.9/macros/estct1.C
===================================================================
--- /tags/Mars-V0.9/macros/estct1.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/estct1.C	(revision 9772)
@@ -0,0 +1,243 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz et al,  09/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+
+void estct1()
+{
+    //
+    // This is a demonstration program which calculates the Hillas
+    // parameter out of a Magic root file (raw data file).
+    //
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList plist;
+
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadTree read("Events", "~/ct1/MC_ON2.root");
+
+    //MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    /*
+     read.AddFile("star.root");
+     read.AddFile("star2.root");
+     */
+    //read.AddFile("~/ct1/MC_ON2.root");
+
+    MEnergyEstParam eest("Hillas");
+    eest.Add("HillasSrc");
+
+    //
+    // Use this to change the binnign of the histograms to CT1-style
+    //
+    Bool_t usect1 = kTRUE;
+
+    //
+    // Here you set up the coefficients of the parametrization
+    // (MEnergyEstParam)
+    //
+    TArrayD fA(5);
+    fA[0] = -3907.74; //4916.4;     //-2414.75;
+    fA[1] = 1162.3; //149.549;    // 1134.28;
+    fA[2] = 199.351;//-558.209;   // 132.932;
+    fA[3] = 0.403192;//0.270725;   //0.292845;
+    fA[4] = 121.921;//107.001;    // 107.001;
+
+    TArrayD fB(7);
+    fB[0] =  677.821;//-8234.12;  //-4282.25;
+    fB[1] =  11.3302;//23.2153;   //  18.892;
+    fB[2] =  -0.0211177;//0.416372;  //0.193373;
+    fB[3] =  -23.0217;//332.42;    //203.803;
+    fB[4] =  -0.785242;//-0.701764; //-0.534876;
+    fB[5] = 5.6413e-5;//-0.0131774; //-0.00789539;
+    fB[6] =  -0.146595;//-0.162687; //  0.111913;
+
+    eest.SetCoeffA(fA);
+    eest.SetCoeffB(fB);
+
+    MH3 mh3e("MMcEvt.fEnergy",     "(MEnergyEst.fEnergy/MMcEvt.fEnergy-1)*(MEnergyEst.fEnergy/MMcEvt.fEnergy-1)");
+    MH3 mh3i("MMcEvt.fImpact/100", "(MEnergyEst.fImpact/MMcEvt.fImpact-1)*(MEnergyEst.fImpact/MMcEvt.fImpact-1)");
+    MH3 mh3eo("MMcEvt.fEnergy",     "MEnergyEst.fEnergy/MMcEvt.fEnergy-1");
+    MH3 mh3io("MMcEvt.fImpact/100", "MEnergyEst.fImpact/MMcEvt.fImpact-1");
+
+    MH3 mh3e2("MEnergyEst.fEnergy",     "(MEnergyEst.fEnergy/MMcEvt.fEnergy-1)*(MEnergyEst.fEnergy/MMcEvt.fEnergy-1)");
+    MH3 mh3i2("MEnergyEst.fImpact/100", "(MEnergyEst.fImpact/MMcEvt.fImpact-1)*(MEnergyEst.fImpact/MMcEvt.fImpact-1)");
+    MH3 mh3eo2("MEnergyEst.fEnergy",     "MEnergyEst.fEnergy/MMcEvt.fEnergy-1");
+    MH3 mh3io2("MEnergyEst.fImpact/100", "MEnergyEst.fImpact/MMcEvt.fImpact-1");
+
+    MH3 mhe("MMcEvt.fEnergy",     "MEnergyEst.fEnergy");
+    MH3 mhi("MMcEvt.fImpact/100", "MEnergyEst.fImpact/100");
+
+    mh3e.SetName("HistEnergy");
+    mh3i.SetName("HistImpact");
+    mh3eo.SetName("HistEnergyOffset");
+    mh3io.SetName("HistImpactOffset");
+
+    mh3e2.SetName("HistEnergy");
+    mh3i2.SetName("HistImpact");
+    mh3eo2.SetName("HistEnergyOffset");
+    mh3io2.SetName("HistImpactOffset");
+
+    mhe.SetName("HistEE");
+    mhi.SetName("HistII");
+
+    MFillH hfille(&mh3e);
+    MFillH hfilli(&mh3i);
+    MFillH hfilleo(&mh3eo);
+    MFillH hfillio(&mh3io);
+
+    MFillH hfille2(&mh3e2);
+    MFillH hfilli2(&mh3i2);
+    MFillH hfilleo2(&mh3eo2);
+    MFillH hfillio2(&mh3io2);
+
+    MFillH hfillee(&mhe);
+    MFillH hfillii(&mhi);
+
+    MBinning binsex("BinningHistEnergyX");
+    MBinning binsey("BinningHistEnergyY");
+    MBinning binsix("BinningHistImpactX");
+    MBinning binsiy("BinningHistImpactY");
+    MBinning binseox("BinningHistEnergyOffsetX");
+    MBinning binseoy("BinningHistEnergyOffsetY");
+    MBinning binsiox("BinningHistImpactOffsetX");
+    MBinning binsioy("BinningHistImpactOffsetY");
+    MBinning binseex("BinningHistEEX");
+    MBinning binsiix("BinningHistIIX");
+    MBinning binseey("BinningHistEEY");
+    MBinning binsiiy("BinningHistIIY");
+
+    binsex.SetEdgesLog(50, usect1 ? 300: 10, usect1 ? 50000 : 1e4);
+    binsey.SetEdges(50, 0, usect1 ? 0.8 : 1.75);
+    binseox.SetEdgesLog(50, usect1 ? 300 : 10, usect1 ? 50000 : 1e4);
+    binseoy.SetEdges(50, usect1 ? -0.75 : -1.75, usect1 ? 0.75 : 1.75);
+
+    binsix.SetEdges(50, 0, usect1 ? 275 : 300);
+    binsiy.SetEdges(50, 0, usect1 ? 0.2 : 1.75);
+    binsiox.SetEdges(50, 0, usect1 ? 275 : 300);
+    binsioy.SetEdges(50, usect1 ? -0.75 : -1.75, usect1 ? 0.75 : 1.75);
+
+    binseex.SetEdgesLog(50, usect1 ? 300 : 10, usect1 ? 50000 : 15e3);
+    binseey.SetEdgesLog(50, usect1 ? 300 : 1,  usect1 ? 50000 : 2e3);
+    binsiix.SetEdges(50, 0, usect1 ? 275 : 300);
+    binsiiy.SetEdges(50, 0, usect1 ? 275 : 150);
+
+    plist.AddToList(&binsex);
+    plist.AddToList(&binsey);
+    plist.AddToList(&binsix);
+    plist.AddToList(&binsiy);
+    plist.AddToList(&binseox);
+    plist.AddToList(&binseoy);
+    plist.AddToList(&binsiox);
+    plist.AddToList(&binsioy);
+    plist.AddToList(&binseex);
+    plist.AddToList(&binseey);
+    plist.AddToList(&binsiix);
+    plist.AddToList(&binsiiy);
+
+    //
+    //  Setup tasklists
+    //
+    tlist.AddToList(&read);
+
+    tlist.AddToList(&eest);
+    tlist.AddToList(&hfille);
+    tlist.AddToList(&hfilli);
+    tlist.AddToList(&hfilleo);
+    tlist.AddToList(&hfillio);
+
+    tlist.AddToList(&hfille2);
+    tlist.AddToList(&hfilli2);
+    tlist.AddToList(&hfilleo2);
+    tlist.AddToList(&hfillio2);
+
+    tlist.AddToList(&hfillee);
+    tlist.AddToList(&hfillii);
+
+    /*
+     MPrint p("MEnergyEst");
+     tlist2.AddToList(&p);
+     */
+
+    //
+    // Create and setup the eventloop
+    //
+    MProgressBar bar;
+
+    MEvtLoop evtloop;
+    evtloop.SetProgressBar(&bar);
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    const TString text = "\\sqrt{<y>}=%.0f%%";
+
+    char txt[1000];
+
+    TCanvas *c=new TCanvas("Est1", "Estimates vs. E_{true}");
+    c->Divide(2,2);
+    c->cd(1);
+    mh3i.DrawClone("PROFXnonew");
+    sprintf(txt, text.Data(), sqrt(mh3i.GetHist().GetMean(2))*100);
+    TLatex *t = new TLatex(180, 0.15, txt);
+    t->Draw();
+    c->cd(2);
+    mh3e.DrawClone("PROFXnonew");
+    sprintf(txt, text.Data(), sqrt(mh3e.GetHist().GetMean(2))*100);
+    t = new TLatex(3.5, 0.6, txt);
+    t->Draw();
+    c->cd(3);
+    mh3io.DrawClone("PROFXnonew");
+    c->cd(4);
+    mh3eo.DrawClone("PROFXnonew");
+
+    c=new TCanvas("Est2", "Estimates vs. E_{est}");
+    c->Divide(2,2);
+    c->cd(1);
+    mh3i2.DrawClone("PROFXnonew");
+    c->cd(2);
+    mh3e2.DrawClone("PROFXnonew");
+    c->cd(3);
+    mh3io2.DrawClone("PROFXnonew");
+    c->cd(4);
+    mh3eo2.DrawClone("PROFXnonew");
+
+    mhe.DrawClone("PROFX");
+    mhi.DrawClone("PROFX");
+}
Index: /tags/Mars-V0.9/macros/estfit.C
===================================================================
--- /tags/Mars-V0.9/macros/estfit.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/estfit.C	(revision 9772)
@@ -0,0 +1,239 @@
+#include <TStopwatch.h>
+#include <TMinuit.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MReadTree.h"
+#include "MHMatrix.h"
+#include "MChisqEval.h"
+#include "MMatrixLoop.h"
+#include "MParameterD.h"
+#include "MDataMember.h"
+#include "MDataElement.h"
+#include "MEnergyEstParam.h"
+
+// --------------------------------------------------------------------------
+
+void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    MEvtLoop *evtloop = (MEvtLoop*)gMinuit->GetObjectFit();
+
+    MParList  *plist  = evtloop->GetParList();
+    MTaskList *tlist  = evtloop->GetTaskList();
+
+    MChisqEval      *eval = (MChisqEval*)     plist->FindObject("MFitResult", "MParameterD");
+    MEnergyEstParam *eest = (MEnergyEstParam*)tlist->FindObject("MEnergyEstParam");
+
+    eest->SetCoeff(TArrayD(eest->GetNumCoeff(), par));
+
+    evtloop->Eventloop();
+
+    f = eval->GetVal();
+}
+
+// --------------------------------------------------------------------------
+//
+//  0: fit impact parameter only
+//  1: fit energy only
+//  2: fit all parameters with respect to the energy resolution
+//
+void estfit(Int_t evalenergy=0)
+{
+    //
+    // Fill events into a MHMatrix
+    //
+    MParList parlist;
+    MHMatrix matrix;
+
+    Int_t col = matrix.AddColumn(evalenergy?"MMcEvt.fEnergy":"MMcEvt.fImpact");
+
+    MEnergyEstParam eest("Hillas");
+    eest.Add("HillasSrc");
+    eest.InitMapping(&matrix);
+
+    MReadTree read("Events", "MC_ON2_short.root");
+    read.DisableAutoScheme();
+
+    if (!matrix.Fill(&parlist, &read))
+        return;
+
+    //
+    // Setup the tasklist used to evaluate the needed chisq
+    //
+    MTaskList tasklist;
+    parlist.AddToList(&tasklist);
+
+    MMatrixLoop loop(&matrix);
+
+    MChisqEval eval;
+    eval.SetY1(new MDataElement(&matrix, col));
+    eval.SetY2(new MDataMember(evalenergy ? "MEnergyEst.fEnergy" : "MEnergyEst.fImpact"));
+    eval.SetOwner();
+
+    tasklist.AddToList(&loop);
+    tasklist.AddToList(&eest);
+    tasklist.AddToList(&eval);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&parlist);
+
+    //
+    // Be carefull: This is not thread safe
+    //
+    TMinuit minuit(12);
+    minuit.SetPrintLevel(-1);
+    minuit.SetFCN(fcn);
+
+    // Ready for: minuit.mnexcm("SET ERR", arglist, 1, ierflg)
+    if (minuit.SetErrorDef(1))
+    {
+        cout << "SetErrorDef failed." << endl;
+        return;
+    }
+
+    //
+    // Set initial values
+    //
+    TArrayD fA(5);
+    TArrayD fB(7);
+    fA[0] =  392957;
+    fA[1] =  135;
+    fA[2] =  -37449;
+    fA[3] =  0.3464;
+    fA[4] =  1;
+    fB[0] =  1;
+    fB[1] =  1;
+    fB[2] =  1;
+    fB[3] =  1;
+    fB[4] =  1;
+    fB[5] =  1;
+    fB[6] =  1;
+     /*
+     fA[0] = 6122.97;
+     fA[1] = 144.889;
+     fA[2] = -601.256;
+     fA[3] = 0.00171985;
+     fA[4] = 116.451;
+     fB[0] =  -2368.21;
+     fB[1] =  1186.26;
+     fB[2] =  0.147235;
+     fB[3] =  144.49;
+     fB[4] =  42.7681;
+     fB[5] = -0.757817;
+     fB[6] =  0.182482;
+     */
+    /*
+     TArrayD fA(5);
+    fA[0] = 6122.97;
+    fA[1] = 144.889;
+    fA[2] = -601.256;
+    fA[3] = 0.00171985;
+    fA[4] = 116.451;
+
+    TArrayD fB(7);
+    fB[0] =  -10445.5;
+    fB[1] =  2172.05;
+    fB[2] =  0.69;
+    fB[3] =  491.2;
+    fB[4] =  4.71444;
+    fB[5] = -0.0331926;
+    fB[6] = -0.014833;
+    */
+    // Set starting values and step sizes for parameters
+    for (Int_t i=0; i<fA.GetSize(); i++)
+    {
+        TString name = "fA[";
+        name += i;
+        name += "]";
+        Double_t vinit = fA[i];
+        Double_t step  = fabs(fA[i]/3);
+
+        Double_t limlo = 0; // limlo=limup=0: no limits
+        Double_t limup = 0; 
+
+        Bool_t rc = minuit.DefineParameter(i, name, vinit, step, limlo, limup);
+        if (evalenergy==1)
+        {
+            minuit.FixParameter(i);
+            cout << "Fixed Parameter #" << i << endl;
+        }
+
+        if (!rc)
+            continue;
+
+        cout << "Error in defining parameter #" << i << endl;
+        return;
+    }
+
+    for (Int_t i=0; i<fB.GetSize(); i++)
+    {
+        TString name = "fB[";
+        name += i;
+        name += "]";
+        Double_t vinit = fB[i];
+        Double_t step  = fabs(fB[i]/3);
+
+        Double_t limlo = 0; // limlo=limup=0: no limits
+        Double_t limup = 0;
+
+        Bool_t rc = minuit.DefineParameter(i+fA.GetSize(), name, vinit, step, limlo, limup);
+        if (evalenergy==0)
+        {
+            minuit.FixParameter(i+fA.GetSize());
+            cout << "Fixed Parameter #" << i+fA.GetSize() << endl;
+        }
+
+        if (!rc)
+            continue;
+
+        cout << "Error in defining parameter #" << i+fA.GetSize() << endl;
+        return;
+    }
+
+    //
+    // Setup globals used in FCN
+    //
+    minuit.SetObjectFit(&evtloop);
+
+    cout << endl << "Fitting procedure running..." << endl;
+
+    TStopwatch clock;
+    clock.Start();
+
+    // Now ready for minimization step: minuit.mnexcm("MIGRAD", arglist, 1, ierflg)
+    gLog.SetNullOutput(kTRUE);
+    Bool_t rc = minuit.Migrad();
+    gLog.SetNullOutput(kFALSE);
+    if (rc)
+    {
+        cout << "Migrad failed." << endl;
+        return;
+    }
+
+    cout << endl;
+    clock.Stop();
+    clock.Print();
+    cout << endl;
+
+    for (Int_t i=(evalenergy==1?fA.GetSize():0); i<(evalenergy>0?fA.GetSize()+fB.GetSize():fA.GetSize()); i++)
+    //for (Int_t i=0; i<fA.GetSize()+fB.GetSize(); i++)
+    {
+        Double_t val;
+        Double_t er;
+
+        if (!minuit.GetParameter(i, val, er))
+            cout << "Error getting parameter #" << i << endl;
+
+        cout << i << ":  " << val << "  +-  " << er << endl;
+    }
+
+    /*
+     // Print results
+     Double_t amin, edm, errdef;
+     Int_t nvpar, nparx, icstat;
+     minuit.mnstat(amin, edm, errdef, nvpar, nparx, icstat);
+     minuit.mnprin(3, amin);
+     */
+}
Index: /tags/Mars-V0.9/macros/estimate.C
===================================================================
--- /tags/Mars-V0.9/macros/estimate.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/estimate.C	(revision 9772)
@@ -0,0 +1,245 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz et al,  09/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+
+void estimate()
+{
+    //
+    // This is a demonstration program which calculates the Hillas
+    // parameter out of a Magic root file (raw data file).
+    //
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList plist;
+
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    /*
+     read.AddFile("star.root");
+     read.AddFile("star2.root");
+     */
+    read.AddFile("gammas.root");
+
+    // Create a filter for the gamma events
+    MFParticleId fgamma("MMcEvt", '=', kGAMMA);
+
+    MTaskList tlist2;
+    tlist2.SetFilter(&fgamma);
+
+    MEnergyEstParam eest;
+    eest.Add("MHillasSrc");
+
+    //
+    // Use this to change the binnign of the histograms to CT1-style
+    //
+    Bool_t usect1 = kTRUE;
+
+    //
+    // Here you set up the coefficients of the parametrization
+    // (MEnergyEstParam)
+    //
+    TArrayD fA(5);
+    fA[0] =  -2539; // [cm]
+    fA[1] =    900; // [cm]
+    fA[2] =   17.5; // [cm]
+    fA[3] =      4;
+    fA[4] =   58.3;
+
+    TArrayD fB(7);
+    fB[0] =    -8.64; // [GeV]
+    fB[1] =   -0.069; // [GeV]
+    fB[2] =  0.00066; // [GeV]
+    fB[3] =    0.033; // [GeV]
+    fB[4] = 0.000226; // [GeV]
+    fB[5] =  4.14e-8; // [GeV]
+    fB[6] =    -0.06;
+
+    eest.SetCoeffA(fA);
+    eest.SetCoeffB(fB);
+
+    MH3 mh3e("MMcEvt.fEnergy",     "(MEnergyEst.fEnergy/MMcEvt.fEnergy-1)*(MEnergyEst.fEnergy/MMcEvt.fEnergy-1)");
+    MH3 mh3i("MMcEvt.fImpact/100", "(MEnergyEst.fImpact/MMcEvt.fImpact-1)*(MEnergyEst.fImpact/MMcEvt.fImpact-1)");
+    MH3 mh3eo("MMcEvt.fEnergy",     "MEnergyEst.fEnergy/MMcEvt.fEnergy-1");
+    MH3 mh3io("MMcEvt.fImpact/100", "MEnergyEst.fImpact/MMcEvt.fImpact-1");
+
+    MH3 mh3e2("MEnergyEst.fEnergy",     "(MEnergyEst.fEnergy/MMcEvt.fEnergy-1)*(MEnergyEst.fEnergy/MMcEvt.fEnergy-1)");
+    MH3 mh3i2("MEnergyEst.fImpact/100", "(MEnergyEst.fImpact/MMcEvt.fImpact-1)*(MEnergyEst.fImpact/MMcEvt.fImpact-1)");
+    MH3 mh3eo2("MEnergyEst.fEnergy",     "MEnergyEst.fEnergy/MMcEvt.fEnergy-1");
+    MH3 mh3io2("MEnergyEst.fImpact/100", "MEnergyEst.fImpact/MMcEvt.fImpact-1");
+
+    MH3 mhe("MMcEvt.fEnergy",     "MEnergyEst.fEnergy");
+    MH3 mhi("MMcEvt.fImpact/100", "MEnergyEst.fImpact/100");
+
+    mh3e.SetName("HistEnergy");
+    mh3i.SetName("HistImpact");
+    mh3eo.SetName("HistEnergyOffset");
+    mh3io.SetName("HistImpactOffset");
+
+    mh3e2.SetName("HistEnergy");
+    mh3i2.SetName("HistImpact");
+    mh3eo2.SetName("HistEnergyOffset");
+    mh3io2.SetName("HistImpactOffset");
+
+    mhe.SetName("HistEE");
+    mhi.SetName("HistII");
+
+    MFillH hfille(&mh3e);
+    MFillH hfilli(&mh3i);
+    MFillH hfilleo(&mh3eo);
+    MFillH hfillio(&mh3io);
+
+    MFillH hfille2(&mh3e2);
+    MFillH hfilli2(&mh3i2);
+    MFillH hfilleo2(&mh3eo2);
+    MFillH hfillio2(&mh3io2);
+
+    MFillH hfillee(&mhe);
+    MFillH hfillii(&mhi);
+
+    MBinning binsex("BinningHistEnergyX");
+    MBinning binsey("BinningHistEnergyY");
+    MBinning binsix("BinningHistImpactX");
+    MBinning binsiy("BinningHistImpactY");
+    MBinning binseox("BinningHistEnergyOffsetX");
+    MBinning binseoy("BinningHistEnergyOffsetY");
+    MBinning binsiox("BinningHistImpactOffsetX");
+    MBinning binsioy("BinningHistImpactOffsetY");
+    MBinning binseex("BinningHistEEX");
+    MBinning binsiix("BinningHistIIX");
+    MBinning binseey("BinningHistEEY");
+    MBinning binsiiy("BinningHistIIY");
+
+    binsex.SetEdgesLog(50, usect1 ? 300: 10, usect1 ? 50000 : 1e4);
+    binsey.SetEdges(50, 0, 1.75);
+    binseox.SetEdgesLog(50, usect1 ? 300 : 10, usect1 ? 50000 : 1e4);
+    binseoy.SetEdges(50, -1.75, 1.75);
+
+    binsix.SetEdges(50, 0, usect1 ? 450 : 300);
+    binsiy.SetEdges(50, 0, 1.75);
+    binsiox.SetEdges(50, 0, usect1 ? 450 : 300);
+    binsioy.SetEdges(50, -1.75, 1.75);
+
+    binseex.SetEdgesLog(50, usect1 ? 300 : 10, usect1 ? 50000 : 15e3);
+    binseey.SetEdgesLog(50, usect1 ? 300 : 1,  usect1 ? 50000 : 2e3);
+    binsiix.SetEdges(50, 0, usect1 ? 450 : 300);
+    binsiiy.SetEdges(50, 0, usect1 ? 450 : 150);
+
+    plist.AddToList(&binsex);
+    plist.AddToList(&binsey);
+    plist.AddToList(&binsix);
+    plist.AddToList(&binsiy);
+    plist.AddToList(&binseox);
+    plist.AddToList(&binseoy);
+    plist.AddToList(&binsiox);
+    plist.AddToList(&binsioy);
+    plist.AddToList(&binseex);
+    plist.AddToList(&binseey);
+    plist.AddToList(&binsiix);
+    plist.AddToList(&binsiiy);
+
+    //
+    //  Setup tasklists
+    //
+    tlist.AddToList(&read);
+    tlist.AddToList(&fgamma);
+    tlist.AddToList(&tlist2);
+
+    tlist2.AddToList(&eest);
+    tlist2.AddToList(&hfille);
+    tlist2.AddToList(&hfilli);
+    tlist2.AddToList(&hfilleo);
+    tlist2.AddToList(&hfillio);
+
+    tlist2.AddToList(&hfille2);
+    tlist2.AddToList(&hfilli2);
+    tlist2.AddToList(&hfilleo2);
+    tlist2.AddToList(&hfillio2);
+
+    tlist2.AddToList(&hfillee);
+    tlist2.AddToList(&hfillii);
+
+    /*
+     MPrint p("MEnergyEst");
+     tlist2.AddToList(&p);
+     */
+
+    //
+    // Create and setup the eventloop
+    //
+    MProgressBar bar;
+
+    MEvtLoop evtloop;
+    evtloop.SetProgressBar(&bar);
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    const TString text = "\\sqrt{<y>}=%.0f%%";
+
+    TCanvas *c=new TCanvas("Est1", "Estimates vs. E_{true}");
+    c->Divide(2,2);
+    c->cd(1);
+    mh3i.DrawClone("PROFXnonew");
+    TLatex *t = new TLatex(180, 1.6, Form(text, sqrt(mh3i.GetHist().GetMean(2))*100));
+    t->Draw();
+    c->cd(2);
+    mh3e.DrawClone("PROFXnonew");
+    t = new TLatex(2.7, 1.6, Form(text, sqrt(mh3e.GetHist().GetMean(2))*100));
+    t->Draw();
+    c->cd(3);
+    mh3io.DrawClone("PROFXnonew");
+    c->cd(4);
+    mh3eo.DrawClone("PROFXnonew");
+
+    c=new TCanvas("Est2", "Estimates vs. E_{est}");
+    c->Divide(2,2);
+    c->cd(1);
+    mh3i2.DrawClone("PROFXnonew");
+    c->cd(2);
+    mh3e2.DrawClone("PROFXnonew");
+    c->cd(3);
+    mh3io2.DrawClone("PROFXnonew");
+    c->cd(4);
+    mh3eo2.DrawClone("PROFXnonew");
+
+    mhe.DrawClone("PROFX");
+    mhi.DrawClone("PROFX");
+}
Index: /tags/Mars-V0.9/macros/evtrate.C
===================================================================
--- /tags/Mars-V0.9/macros/evtrate.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/evtrate.C	(revision 9772)
@@ -0,0 +1,78 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// evtrate.C
+// =========
+//
+// Example macro how to calulate the eventrate (per event) and display
+// the result versus time.
+//
+// As an input you need a merpped raw-data file containing correct times.
+// The output is the plot: Eventrate vs. time.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void evtrate()
+{
+    // Setup parameter- and tasklist
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // Setup reading task
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile("test-time.root");
+
+    // Setup event rate calculator
+    MEventRateCalc calc;
+    // Setup number of events to be averaged
+    calc.SetNumEvents(200);
+
+    // Setup histogram to be filles with rate
+    MHVsTime rate("MEventRate.fRate");
+
+    // Setup task to fill the histogram
+    MFillH fill(&rate, "MTime");
+
+    // Setup tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&calc);
+    tlist.AddToList(&fill);
+
+    // Execute your eventloop
+    MEvtLoop loop;
+    loop.SetParList(&plist);
+
+    if (!loop.Eventloop())
+        return;
+
+    // print some execution statistics
+    tlist.PrintStatistics();
+
+    // Draw result
+    rate.DrawClone();
+}
Index: /tags/Mars-V0.9/macros/extendcam.C
===================================================================
--- /tags/Mars-V0.9/macros/extendcam.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/extendcam.C	(revision 9772)
@@ -0,0 +1,235 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz,  12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// extendcam.C
+//
+// This macro demonstrates how to extend the magic camera and performes
+// a fourier transformation on it
+//
+/////////////////////////////////////////////////////////////////////////////////
+
+Bool_t HandleInput()
+{
+    // This must be there to get accesss to the GUI while the macro
+    // is still running!
+
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+TCanvas   *c;
+MHCamera *d1=new MHCamera(MGeomCamMagic());
+MHCamera *d2=new MHCamera;
+MHCamera *d3=new MHCamera;
+MHCamera *d4=new MHCamera;
+MHCamera *d5=new MHCamera;
+MHCamera *d6=new MHCamera(MGeomCamMagicXT());
+
+MCerPhotEvt *evt=0;
+MMcEvt *mc;
+
+MHexagonFreqSpace *fFreq1;
+MHexagonFreqSpace *fFreq2;
+
+Int_t PreProcess(MParList *plist)
+{
+    fFreq1 = (MHexagonFreqSpace*)plist->FindObject("MHexagonFreqSpace1");
+    if (!fFreq1)
+        return kFALSE;
+    fFreq2 = (MHexagonFreqSpace*)plist->FindObject("MHexagonFreqSpace2");
+    if (!fFreq2)
+        return kFALSE;
+
+    //Für Real-Raum
+    evt = (MCerPhotEvt*)plist->FindObject("MCerPhotEvt");
+    if (!evt)
+    {
+        cout << "Fehler: MCerPhotEvt" << endl;
+        return kFALSE;
+    }
+
+    mc = (MMcEvt*)plist->FindObject("MMcEvt");
+    if (!mc)
+    {
+        cout << "Fehler: MMcEvt" << endl;
+        return kFALSE;
+    }
+
+    c = new TCanvas("Events", "Real Events", 900, 600);
+    c->SetBorderMode(0);
+    c->Divide(3,2);
+
+    MGeomCam *geomfreq=fFreq1->NewGeomCam();
+    geomfreq->SetName("FreqSpace");
+
+    c->cd(1);
+    d1->SetPrettyPalette();
+    d1->Draw();
+    c->cd(2);
+    d2->SetGeometry(MGeomCamMagicXT());
+    d2->SetPrettyPalette();
+    d2->Draw();
+    c->cd(4);
+    d3->SetGeometry(*geomfreq);
+    d3->SetPrettyPalette();
+    d3->Draw();
+    c->cd(5);
+    d4->SetGeometry(MGeomCamMagicXT());
+    d4->SetPrettyPalette();
+    d4->Draw();
+    c->cd(3);
+    d5->SetGeometry(MGeomCamMagicXT());
+    d5->SetPrettyPalette();
+    d5->Draw();
+    c->cd(6);
+    //d6->SetGeometry(MGeomCamMagicXT());
+    d6->SetPrettyPalette();
+    d6->Draw();
+    return kTRUE;
+}
+
+MClone *cl1;
+MClone *cl2;
+MClone *cl3;
+MClone *cl4;
+
+Int_t Process()
+{
+    d1->SetCamContent(*(MCerPhotEvt*)cl1->GetClone());
+    d2->SetCamContent(*(MCerPhotEvt*)cl2->GetClone());
+    d3->SetCamContent(*fFreq2);
+    d4->SetCamContent(*(MCerPhotEvt*)cl4->GetClone());
+    d5->SetCamContent(*(MCerPhotEvt*)cl3->GetClone());
+    d6->SetCamContent(*evt);
+
+    d2->SetMaximum(-1111);
+    d4->SetMaximum(-1111);
+    d2->SetMinimum(0);
+    d4->SetMinimum(0);
+    d2->SetMaximum(TMath::Max(d2->GetMaximum(), d4->GetMaximum()));
+    d4->SetMaximum(d2->GetMaximum());
+
+    for (int i=1; i<7; i++)
+    {
+        c->GetPad(i)->GetPad(1)->Modified();
+        c->GetPad(i)->GetPad(1)->Update();
+    }
+
+    c->Modified();
+    c->Update();
+
+
+    return HandleInput();
+}
+
+void extendcam()
+{
+    MParList  plist;
+    MTaskList tlist;
+
+    MGeomCamMagicXT geom("MGeomCamMagicXT");
+    plist.AddToList(&geom);
+
+    plist.AddToList(&tlist);
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile("/home/kolodziejski/Diplomarbeit/marsdata/mcdata/*.root");
+    //read.AddFile("/home/hoehne/data/mcdata/gammas/calib/calib_gamma_zbin0.root");
+    //read.AddFile("/home/hoehne/data/mcdata/hadrons/calib/calib_proton_zbin0.root");
+
+
+    // Setup intercative task calling the functions defined above
+    MGeomApply           apply; //necessary for evt
+    MGeomCamMagicEnhance enhance;
+    // enhance.SetNameCerPhotEvtOut("MCerPhotEvt2");
+
+    MClone clone1("MCerPhotEvt", "Clone1");
+    MClone clone2("MCerPhotEvt", "Clone2");
+    MClone clone3("MCerPhotEvt", "Clone3");
+    MClone clone4("MCerPhotEvt", "Clone4");
+
+    cl1 = &clone1;
+    cl2 = &clone2;
+    cl3 = &clone3;
+    cl4 = &clone4;
+
+    MHexagonalFTCalc     ftcalc;
+    ftcalc.SetNameGeomCam("MGeomCamMagicXT");
+    // ftcalc.SetNameCerPhotEvt("MCerPhotEvt2");
+
+    MTaskInteractive mytask;
+    mytask.SetPreProcess(PreProcess);
+    mytask.SetProcess(Process);
+
+    MImgCleanStd clean1(26, 18);
+    clean1.SetMethod(MImgCleanStd::kAbsolute);
+    clean1.SetNameGeomCam("MGeomCamMagicXT");
+
+    MImgCleanStd clean2(26, 18);
+    clean2.SetMethod(MImgCleanStd::kAbsolute);
+    clean2.SetNameGeomCam("MGeomCamMagicXT");
+
+    // Setup your tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&clone1);
+    tlist.AddToList(&enhance);
+    tlist.AddToList(&clone2);
+    tlist.AddToList(&clean1);
+    tlist.AddToList(&clone3);
+    tlist.AddToList(&ftcalc);
+    tlist.AddToList(&clone4);
+    tlist.AddToList(&clean2);
+    tlist.AddToList(&mytask);
+
+    // Run your analysis
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    // Print statistics information about your loop
+    tlist.PrintStatistics();
+}
+
Index: /tags/Mars-V0.9/macros/flux.C
===================================================================
--- /tags/Mars-V0.9/macros/flux.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/flux.C	(revision 9772)
@@ -0,0 +1,625 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 4/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// This macro calculates photon fluxes as a function of                     //
+//    - energy and time                                                     //
+//    - energy and Theta                                                    //
+//                                                                          //
+// It is assumed that the data have been taken in the wobble mode.          //
+// This means that there is only one set of data, from which both           //
+// 'on' and 'off' data are constructed.                                     //
+//                                                                          //
+// Necessary input from MC :                                                //
+//    - migration matrix (E_est, E_true) as a functioin of Theta            //
+//    - effective collection areas as a function of energy and Theta        //
+//                                                                          //
+//                                                                          // 
+// The input from MC has to refer to the wobble mode too.                   // 
+//                                                                          //
+// The macro includes :                                                     // 
+//    - the calculation of Hillas parameters                                //
+//    - the calculation of the effective on time                            //
+//    - the unfolding of the distributions in the estimated energy E_est    //
+//                                                                          //
+// For testing purposes (as long as no real data, no energy estimator,      //
+// no migration matrices and no effective collection areas are available)   //
+//    - event times are generated (according to a Poissonian with dead time)//
+//    - a dummy energy estimator is provided                                //
+//    - migration matrices are generated                                    //
+//    - dummy effective collection areas are used                           //
+//                                                                          // 
+//////////////////////////////////////////////////////////////////////////////
+void flux()
+{ 
+    //--------------------------------------------------------------
+    // empty lists of parameter containers and tasks
+    //
+    MParList  parlist;
+    MTaskList tasklist;
+
+    //--------------------------------------------------------------
+    // Geometry information of the MAGIC camera
+    //
+    MGeomCamMagic geomcam;
+
+    //--------------------------------------------------------------
+    // Define the two source positions
+    //
+    MSrcPosCam source("Source");
+    MSrcPosCam antisrc("AntiSource");
+    source.SetXY(0, 0);
+    antisrc.SetXY(+240, 0);
+
+    //--------------------------------------------------------------
+    // Setup the binning for the histograms
+    //
+
+    //...............................................................
+    // These are NOT the binnings for the flux determination
+
+    MBinning binswidth("BinningWidth");
+    binswidth.SetEdges(100, 0, 0.5);   // 100 bins from 0 to 0.5 deg
+
+    MBinning binslength("BinningLength");
+    binslength.SetEdges(100, 0, 1);  // 100 bins from 0 to 1 deg
+
+    MBinning binscamera("BinningCamera");
+    binscamera.SetEdges(90, -2.25, 2.25);  // 90 bins from -2.25 to 2.25 deg
+
+    MBinning binsdist("BinningDist");
+    binsdist.SetEdges(90, 0, 2.25);    // 90 bins from 0 to 2.25 deg
+
+    MBinning binsalpha("BinningAlpha");
+    binsalpha.SetEdges(100, -100, 100);
+
+    MBinning binsasym("BinningAsym");
+    binsasym.SetEdges(100, -0.5, 0.5);   // 100 bins from -0.5 to 0.5 deg
+
+    MBinning binsasymn("BinningAsymn");
+    binsasymn.SetEdges(100, -0.005, 0.005);   // 100 bins from -0.005 to 0.005 deg
+
+    MBinning binsm3long("BinningM3Long");
+    binsm3long.SetEdges(100, -0.5, 0.5);   // 100 bins from -0.5 to 0.5 deg
+
+    MBinning binsm3trans("BinningM3Trans");
+    binsm3trans.SetEdges(100, -0.5, 0.5);   // 100 bins from -0.5 to 0.5 deg
+
+    //...............................................................
+    // These ARE the binnings for the flux determination
+
+    MBinning binsalphaflux("BinningAlphaFlux");
+    binsalphaflux.SetEdges(100, 0, 100);
+
+    MBinning binse("BinningE");
+    binse.SetEdgesLog(10, 10, 1e3);
+
+    MBinning binstheta("BinningTheta");
+    binstheta.SetEdges(7, -2.5, 32.5);
+
+    MBinning binstime("BinningTime");
+    binstime.SetEdges(5, 0, 100);
+
+    MBinning binsdifftime("BinningTimeDiff");
+    binsdifftime.SetEdges(50, 0, 0.1);
+
+
+    //--------------------------------------------------------------
+    // Fill list of parameter containers
+    //
+
+    parlist.AddToList(&tasklist);
+    parlist.AddToList(&geomcam);
+
+    parlist.AddToList(&source);
+    parlist.AddToList(&antisrc);
+
+    parlist.AddToList(&binswidth);
+    parlist.AddToList(&binslength);
+    parlist.AddToList(&binscamera);
+
+    parlist.AddToList(&binsdist);
+
+    parlist.AddToList(&binsalpha);
+
+    parlist.AddToList(&binsasym);
+    parlist.AddToList(&binsasymn);
+    parlist.AddToList(&binsm3long);
+    parlist.AddToList(&binsm3trans);
+
+    parlist.AddToList(&binsalphaflux);
+    parlist.AddToList(&binse);
+    parlist.AddToList(&binstheta);
+    parlist.AddToList(&binstime);
+    parlist.AddToList(&binsdifftime);
+
+    //--------------------------------------------------------------
+    // Setup the tasks
+    //
+
+    //.....................................
+    // input file
+    //
+    // next statement commented out
+    //    MReadMarsFile reader("Events", "~/data/Gamma*.root");
+
+    MReadMarsFile reader("Events");
+
+    //reader.AddFile("/hd31/rkb/Camera/mpi/Gamma*.root");
+    //reader.AddFile("/hd31/rkb/Camera/mpi/prot_N_*.root");
+    //reader.AddFile("/hd31/rkb/Camera/mpi/prot_NS_*.root");
+    //reader.AddFile("protondata/gamma_10_n*.root");
+    reader.AddFile("protondata/gamma_10_cn*.root");
+
+    reader.EnableBranch("MMcEvt.fTheta");
+
+    //.....................................
+    // filters
+    MFTriggerLvl1 lvl1;
+
+    //.....................................
+    // generation of event time
+    MMcTimeGenerate   rand;
+
+    //.....................................
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+    MCerPhotCalc      ncalc;
+    MImgCleanStd      clean;
+    MBlindPixelCalc   blind;
+
+    //.....................................
+    // source independent image parameters
+    MHillasCalc       hcalc;
+    MHillasExt        hext;
+    parlist.AddToList(&hext);
+
+    //.....................................
+    // source dependent image parameters
+    MHillasSrcCalc    hsrc1("Source",     "HillasSrc");
+    MHillasSrcCalc    hsrc2("AntiSource", "HillasAntiSrc");
+
+    //.....................................
+    // energy estimation
+    MEnergyEstimate   estim;
+
+    //.....................................
+    // migration matrix (MC)
+    MFillH eestetrue("MHMcEnergyMigration",  "HillasSrc");
+    eestetrue.SetTitle("Task to determine the migration matrix for the energy");
+
+    //.....................................
+    // plots of source independent parameters (length, width, delta, size, center)
+    MFillH hfill1h("MHHillas",  "MHillas");
+    hfill1h.SetTitle("Task to plot the source independent image parameters");
+    hfill1h.SetFilter(&lvl1);
+
+    MFillH hfill1x("MHHillasExt", "MHillas");
+    hfill1x.SetTitle("Task to plot the extended image parameters");
+    hfill1x.SetFilter(&lvl1);
+
+    //.....................................
+    // plots of source dependent parameters (alpha, dist)
+    MFillH hfill2s("HSource     [MHHillasSrc]", "HillasSrc");
+    hfill2s.SetTitle("Task to plot the source dependent image parameters (Source)");
+    hfill2s.SetFilter(&lvl1);
+    MFillH hfill2a("HAntiSource [MHHillasSrc]", "HillasAntiSrc");
+    hfill2a.SetTitle("Task to plot the source dependent image parameters (AntiSource)");
+    hfill2a.SetFilter(&lvl1); 
+
+    //.....................................
+    // star map
+    MFillH hfill1m("MHStarMap", "MHillas");
+    hfill1m.SetTitle("Task to plot the Star map");
+
+    //.....................................
+    const Float_t alpha0 = 15; // [deg]
+    MFAlpha fsrc ("HillasSrc",     '>', alpha0);
+    fsrc.SetTitle("Task to check alphaSrc > alpha0");
+
+    MFAlpha fasrc("HillasAntiSrc", '>', alpha0);
+    fasrc.SetTitle("Task to check alphaAntiSrc > alpha0");
+
+    //.....................................
+    // 1-D profile plots     (<Theta>,  time)
+    //                       (<Theta>, Theta)
+    MFillH fillthetabartime ("ThetabarTime  [MHThetabarTime]",  "MMcEvt");
+    fillthetabartime.SetTitle("Task to plot <Theta> vs time");
+    // fillthetabartime.SetFilter(&lvl1);
+
+    MFillH fillthetabartheta("ThetabarTheta [MHThetabarTheta]", "MMcEvt");
+    fillthetabartheta.SetTitle("Task to plot <Theta> vs theta");
+    // fillthetabartheta.SetFilter(&lvl1);
+
+    //.....................................
+    // 2-D plots     (Delta(time),  time)
+    //               (Delta(time), Theta)
+    MFillH filldtimetime ("EffOnTime  [MHTimeDiffTime]",  "MMcEvt");
+    filldtimetime.SetTitle("Task to plot Delta(time) vs time");
+    // filldtime.SetFilter(&lvl1);
+
+    MFillH filldtimetheta("EffOnTheta [MHTimeDiffTheta]", "MMcEvt");
+    filldtimetheta.SetTitle("Task to plot Delta(time) vs theta");
+    // fillontheta.SetFilter(&lvl1);
+
+    //.....................................
+    // 3-D plots     (alpha, E_est, time) 
+    MFillH fillsptime  ("SrcTime   [MHAlphaEnergyTime]",  "HillasSrc");
+    fillsptime.SetTitle("Task for 3D plots (alpha, E_est, time) (Source)");
+    fillsptime.SetFilter(&fasrc);
+
+    MFillH fillasptime ("ASrcTime  [MHAlphaEnergyTime]",  "HillasAntiSrc");
+    fillasptime.SetTitle("Task for 3D plots (alpha, E_est, time) (AntiSource)");
+    fillasptime.SetFilter(&fsrc);
+
+    //.....................................
+    // 3-D plots     (alpha, E_est, Theta) 
+    MFillH fillsptheta ("SrcTheta  [MHAlphaEnergyTheta]", "HillasSrc");
+    fillsptheta.SetTitle("Task for 3D plots (alpha, E_est, Theta) (Source)");
+    fillsptheta.SetFilter(&fasrc);
+
+    MFillH fillasptheta("ASrcTheta [MHAlphaEnergyTheta]", "HillasAntiSrc");
+    fillasptheta.SetTitle("Task for 3D plots (alpha, E_est, Theta) (AntiSource)");
+    fillasptheta.SetFilter(&fsrc);
+
+    //.....................................
+    // MFillH fethetaall("AllTheta [MHEnergyTheta]", "MMcEvt");
+    // MFillH fethetasel("SelTheta [MHEnergyTheta]", "MMcEvt");
+    // fethetasel.SetFilter(&lvl1);
+
+    // MFillH fetimeall ("AllTime  [MHEnergyTime]",  "MMcEvt");
+    // MFillH fetimesel ("SelTime  [MHEnergyTime]",  "MMcEvt");
+    // fetimesel.SetFilter(&lvl1);
+
+
+    //---------------------------------------------------------------------
+    // Setup the task list
+    //
+    tasklist.AddToList(&reader);
+
+    tasklist.AddToList(&lvl1);
+    tasklist.AddToList(&rand);
+
+    tasklist.AddToList(&pcopy);
+    tasklist.AddToList(&pnsb);
+    tasklist.AddToList(&ncalc);
+    tasklist.AddToList(&clean);
+    tasklist.AddToList(&blind);
+
+    tasklist.AddToList(&hcalc);
+    
+    tasklist.AddToList(&hsrc1);
+    tasklist.AddToList(&hsrc2);
+    tasklist.AddToList(&estim);
+    tasklist.AddToList(&eestetrue);
+
+    tasklist.AddToList(&hfill1h);
+    tasklist.AddToList(&hfill1x);
+
+    tasklist.AddToList(&hfill1m);
+    tasklist.AddToList(&hfill2s);
+    tasklist.AddToList(&hfill2a);
+
+    tasklist.AddToList(&fillthetabartime);
+    tasklist.AddToList(&fillthetabartheta);
+
+    tasklist.AddToList(&filldtimetime);
+    tasklist.AddToList(&filldtimetheta);
+
+
+
+    // tasklist.AddToList(&fethetaall);
+    // tasklist.AddToList(&fethetasel);
+    // tasklist.AddToList(&fetimeall);
+    // tasklist.AddToList(&fetimesel);
+
+    tasklist.AddToList(&fsrc);
+    tasklist.AddToList(&fasrc);
+
+    tasklist.AddToList(&fillsptime);
+    tasklist.AddToList(&fillasptime);
+
+    tasklist.AddToList(&fillsptheta);
+    tasklist.AddToList(&fillasptheta);
+
+ 
+    //----------------------------------------------------------------------
+    // Event loop
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    //
+    // loop over all events
+    //
+    if (!magic.Eventloop())
+        return;
+    //----------------------------------------------------------------------
+
+
+    tasklist.PrintStatistics(10);
+
+    
+    MHHillas *mhhillas = (MHHillas*)parlist.FindObject("MHHillas");
+    mhhillas->SetTitle("Source indep. image parameters");
+    mhhillas->DrawClone();
+    
+
+    
+    MHHillasExt *mhhillasext = (MHHillasExt*)parlist.FindObject("MHHillasExt");
+    mhhillasext->SetTitle("Extended image parameters");
+    mhhillasext->DrawClone();
+    
+    
+    MHHillasSrc *hsource = (MHHillasSrc*)parlist.FindObject("HSource");
+    hsource->SetTitle("Source dependent image parameters (Source)");
+    hsource->DrawClone();
+
+    MHHillasSrc *hantisource = (MHHillasSrc*)parlist.FindObject("HAntiSource");
+    hantisource->SetTitle("Source dependent image parameters (AntiSource)");
+    hantisource->DrawClone();
+    
+
+    /*    
+    parlist.FindObject("MHStarMap")->DrawClone();
+    */
+
+    //----------------------------------------------------------------------
+    // average Theta versus time
+    //           and versus Theta
+    // This is needed for selecting later the right collection area 
+    // (at the right Theta) for each bin in time or Theta
+    //
+    MHThetabarTime  *bartime  = (MHThetabarTime*)parlist.FindObject("ThetabarTime");
+    MHThetabarTheta *bartheta = (MHThetabarTheta*)parlist.FindObject("ThetabarTheta");
+    
+    /*    
+    bartime->DrawClone();
+    bartheta->DrawClone();
+    */
+
+     //----------------------------------------------------------------------
+     // Effective on time
+
+     //....................................
+     // get plots of time differences for different intervals in time
+     // and plots of time differences for different intervals in Theta 
+
+     MHTimeDiffTime  *dtimetime  = (MHTimeDiffTime*)parlist.FindObject("EffOnTime");
+     MHTimeDiffTheta *dtimetheta = (MHTimeDiffTheta*)parlist.FindObject("EffOnTheta");
+
+     /*
+     dtimetime->DrawClone();
+     dtimetheta->DrawClone();
+     */
+
+
+     //....................................
+     // calculate effective on time for different intervals in Time
+     //                         and for different intervals in Theta      
+
+     MHEffOnTime effontime ("Time",  "[s]");
+     MHEffOnTime effontheta("Theta", "[\\circ]");
+
+     effontime.SetupFill(&parlist);
+     effontheta.SetupFill(&parlist);
+
+
+     // Draw == 0  don't draw the individual distributions of time differences
+     //      != 0  draw them
+     Bool_t draw=kFALSE;
+     effontime.Calc (dtimetime->GetHist(), draw);
+     effontheta.Calc(dtimetheta->GetHist(),draw);
+
+
+     // plot effective on time versus Time
+     //                    and versus Theta
+     /*     
+     effontime.DrawClone();
+     effontheta.DrawClone();
+     */
+
+
+     //======================================================================
+     //
+     // A : fully differential plots (Alpha, E-est, Var)
+     //
+     //----------------------------------------------------------------------
+     // 3D-plots of alpha, E_est and time
+     //      and of alpha, E_est and Theta 
+     // with alpha calculated relative to the source position
+     //                   and relative to the anti-source position
+
+     MHAlphaEnergyTime  *evtsptime   = (MHAlphaEnergyTime*)parlist.FindObject("SrcTime");
+     MHAlphaEnergyTime  *evtasptime  = (MHAlphaEnergyTime*)parlist.FindObject("ASrcTime");
+     MHAlphaEnergyTheta *evtsptheta  = (MHAlphaEnergyTheta*)parlist.FindObject("SrcTheta");
+     MHAlphaEnergyTheta *evtasptheta = (MHAlphaEnergyTheta*)parlist.FindObject("ASrcTheta");
+
+
+     /*     
+      evtsptime->SetTitle("Source : 3D-plot Al-En-time, alpha\_{asp} .gt. alpha\_0");
+      evtsptime->DrawClone();
+      evtasptime->SetTitle("AntiSource : 3D-plot Al-En-time, alpha\_{sp} .gt. alpha\_0");
+      evtasptime->DrawClone();
+
+      evtsptheta->SetTitle("Source : 3D-plot Al-En-Theta, alpha\_{asp} .gt. alpha\_0");
+      evtsptheta->DrawClone();
+      evtasptheta->SetTitle("AntiSource : 3D-plot Al-En-Theta, alpha\_{sp} .gt. alpha\_0");
+      evtasptheta->DrawClone();
+     */
+                
+     //----------------------------------------------------------------------
+     // Difference between source and antisource (= 'gamma' sample) 
+     // for             3D-plots of alpha, E_est and time
+     //                      and of alpha, E_est and Theta 
+     // 3rd and 4th argument are name and title of the resulting histogram
+
+     MHGamma gamma;
+
+     TH3D *hsubtime  = gamma.Subtract( evtsptime->GetHist(), 
+                                       evtasptime->GetHist(),
+                        "Al-En-time", "3D-plot of Alpha,E-est,time", draw);
+
+     TH3D *hsubtheta = gamma.Subtract( evtsptheta->GetHist(), 
+                                       evtasptheta->GetHist(),
+                        "Al-En-time", "3D-plot of Alpha,E-est,Theta", draw);
+    
+
+     //----------------------------------------------------------------------
+     // get number of 'gammas' in the alpha range (lo, up) as a function of
+     //                 E_est and time
+     //        or       E_est and Theta 
+
+     Axis_t lo =   0;    // [deg]
+     Axis_t up =  10;    // [deg]
+     const TH2D &evttime  = *(gamma.GetAlphaProjection(hsubtime, 
+                              lo, up, draw));
+
+     const TH2D &evttheta = *(gamma.GetAlphaProjection(hsubtheta, 
+                              lo, up, draw));
+     
+
+     //----------------------------------------------------------------------
+     // plot migration matrix:  E-true E-est Theta
+
+
+     /*
+     MHMcEnergyMigration *migrationmatrix = 
+         (MHMcEnergyMigration*)parlist.FindObject("MHMcEnergyMigration");
+     migrationmatrix->SetTitle("Migration matrix");;
+     migrationmatrix->DrawClone();
+     */
+
+
+     //----------------------------------------------------------------------
+     // determine gamma flux from distributions of E-est :
+     //   -  do unfolding to get the distributions in E-unfold
+     //   -  divide by bin width in energy
+     //                effective ontime and
+     //                effective collection area
+     //      to get the absolute gamma flux
+    
+     //.............................................
+     // get flux spectrum for different bins in Time
+     //
+     // use dummy histogram *aeff which eventually will contain
+     //     the effective collection area as a function of Etrue and Theta
+     TH2D aeff;
+
+     // arguments of MHFlux constructor are :
+     //   - 2D histogram containing the no.of gammas as a function of
+     //     E-est and Var
+     //   - name  of variable Var ("Time" or "Theta")
+     //   - units of variable Var ( "[s]" or "[\\circ]")
+
+     // Draw == kTRUE  draw the no.of photons vs. E-est 
+     //                for the individual bins of the variable Var
+     draw=kTRUE;
+     MHFlux fluxtime(evttime, draw, "Time", "[s]");
+     fluxtime.Unfold(draw);
+     fluxtime.CalcFlux(effontime.GetHist(), bartime.GetHist(),
+                       &aeff, draw);
+     
+     fluxtime.DrawClone();
+     
+
+
+     //..............................................
+     // get flux spectrum for different bins in Theta
+     MHFlux fluxtheta(evttheta, draw, "Theta", "[\\circ]");
+     fluxtheta.Unfold(draw);
+     fluxtheta.CalcFlux(effontheta.GetHist(), bartheta.GetHist(),
+                       &aeff, draw);
+     
+     fluxtheta.DrawClone();
+     
+
+return;
+     //----------------------------------------------------------------------
+
+
+     //======================================================================
+     //
+     // B : plots integrated over E-est
+     //
+     //----------------------------------------------------------------------
+     // integrate 3D-plot of (alpha, E_est and Time) over E-est
+     //    to get 2D-plot of (alpha, Time) 
+                                   
+     Draw = kFALSE;                        
+     TH2D *evttimesp  = evtsptime.IntegrateEest ("AlphaSP vs. Time", Draw);
+     TH2D *evttimeasp = evtasptime.IntegrateEest("AlphaASP vs. Time",Draw);
+
+
+     //======================================================================
+     //
+     // C : plots integrated over Time
+     //
+     //----------------------------------------------------------------------
+     // integrate 3D-plot of (alpha, E_est and Time) over the Time
+     //    to get 2D-plot of (alpha, E_est) 
+                                   
+     Draw = kFALSE;                        
+     TH2D *evteestsp  = evtsptime.IntegrateTime ("AlphaSP vs. E-est", Draw);
+     TH2D *evteestasp = evtasptime.IntegrateTime("AlphaASP vs. E-est",Draw);
+
+
+
+     //======================================================================
+     //
+     // D : plots integrated over E-est and Time
+     //
+
+     //----------------------------------------------------------------------
+     // integrate 3D-plot of (alpha, E_est and Time) over E-est and Time
+     //    to get 1D-plot of (alpha) 
+                                   
+     Draw = kFALSE;                        
+     TH1D *evtalphasp  = evtsptime.IntegrateEestTime ("AlphaSP", Draw);
+     TH1D *evtalphaasp = evtasptime.IntegrateEestTime("AlphaASP",Draw);
+
+     //----------------------------------------------------------------------
+     // list of tasks for processing
+
+     cout << " " << endl;
+     cout << "List of tasks for processing :" << endl;
+     cout << "==============================" << endl;
+     cout << " " << endl;
+
+     // was folgt geht nicht :
+
+     // Error: Function Next() is not defined in current scope  FILE:macros/flux.C LINE:636
+
+     //while ( (task=(MTask*)Next()) )
+     //{
+     //  cout << tasklist.GetName() << " :   " << tasklist.GetTitle() << endl;
+     //}
+
+     return;
+
+     //======================================================================                
+}
+//===========================================================================
+
+
Index: /tags/Mars-V0.9/macros/fluxunfold.C
===================================================================
--- /tags/Mars-V0.9/macros/fluxunfold.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/fluxunfold.C	(revision 9772)
@@ -0,0 +1,3744 @@
+   
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// This program should be run under root :                                //
+//      root fluxunfold.C++                                               //
+//                                                                        //
+// Author(s) : T. Bretz  02/2002 <mailto:tbretz@astro.uni-wuerzburg.de>   //
+//             W. Wittek 09/2002 <mailto:wittek@mppmu.mpg.de>             //
+//                                                                        //
+// this macro is prepared to be used in the analysis :                    //
+//                                                                        //
+//      the unfolding should be called by                                 //
+//      doUnfolding(TH2D &tobeunfolded,      // (E-est, Theta)            //
+//                  TH3D &migrationmatrix,   // (E-est, E-true, Theta)    //
+//                  TH2D &unfolded)          // (E-true,Theta)            //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+
+#include <TMath.h>
+#include <TRandom3.h>
+#include <TVector.h>
+#include <TMatrixD.h>
+#include <TMatrix.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TProfile.h>
+#include <TF1.h>
+#include <iostream.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include <fstream.h>
+#include <iomanip.h>
+
+TH1 *DrawMatrixClone(const TMatrixD &m, Option_t *opt="")
+{
+    const Int_t nrows = m.GetNrows();
+    const Int_t ncols = m.GetNcols();
+
+    TMatrix m2(nrows, ncols);
+    for (int i=0; i<nrows; i++)
+        for (int j=0; j<ncols; j++)
+            m2(i, j) = m(i, j);
+
+    TH2F *hist = new TH2F(m2);
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+
+}
+
+TH1 *DrawMatrixColClone(const TMatrixD &m, Option_t *opt="", Int_t col=0)
+{
+    const Int_t nrows = m.GetNrows();
+
+    TVector vec(nrows);
+    for (int i=0; i<nrows; i++)
+        vec(i) = m(i, col);
+
+    TH1F *hist = new TH1F("TVector","",nrows,0,nrows);
+    for (int i=0; i<nrows; i++)
+    {
+      hist->SetBinContent(i+1, vec(i));
+    }
+
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+}
+
+
+void PrintTH3Content(const TH3 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+      for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+        for (Int_t k=1; k<=hist.GetNbinsZ(); k++)
+            cout << hist.GetBinContent(i,j,k) << " \t";
+      cout << endl << endl;
+    }
+}
+
+void PrintTH3Error(const TH3 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+      for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+        for (Int_t k=1; k<=hist.GetNbinsZ(); k++)
+            cout << hist.GetBinError(i, j, k) << " \t";
+      cout << endl << endl;
+    }
+}
+
+void PrintTH2Content(const TH2 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            cout << hist.GetBinContent(i,j) << " \t";
+        cout << endl << endl;
+}
+
+void PrintTH2Error(const TH2 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            cout << hist.GetBinError(i, j) << " \t";
+        cout << endl << endl;
+}
+
+void PrintTH1Content(const TH1 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        cout << hist.GetBinContent(i) << " \t";
+    cout << endl << endl;
+}
+
+void PrintTH1Error(const TH1 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        cout << hist.GetBinError(i) << " \t";
+    cout << endl << endl;
+}
+
+void CopyCol(TMatrixD &m, const TH1 &h, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        m(i, col) = h.GetBinContent(i+1);
+}
+
+void CopyCol(TH1 &h, const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        h.SetBinContent(i+1, m(i, col));
+}
+
+void CopyH2M(TMatrixD &m, const TH2 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+            m(i, j) = h.GetBinContent(i+1, j+1);
+}
+
+void CopySqr(TMatrixD &m, const TH1 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+        {
+            const Double_t bin =  h.GetBinContent(i+1, j+1);
+            m(i, j) = bin*bin;
+        }
+}
+
+Double_t GetMatrixSumRow(const TMatrixD &m, Int_t row)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(row, i);
+
+    return sum;
+}
+
+Double_t GetMatrixSumDiag(const TMatrixD &m)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, i);
+
+    return sum;
+}
+
+Double_t GetMatrixSumCol(const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, col);
+
+    return sum;
+}
+Double_t GetMatrixSum(const TMatrixD &m)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += GetMatrixSumRow(m, i);
+
+    return sum;
+}
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// fcnSmooth   (used by SmoothMigrationMatrix)                                 //
+//                                                                        //
+// is called by MINUIT                                                    //
+// for given values of the parameters it calculates                       //
+//                     the function to be minimized                       //  
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+void fcnSmooth(Int_t &npar, Double_t *gin, Double_t &f, 
+               Double_t *par, Int_t iflag);
+
+
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// fcnTikhonov2   (used by Tikhonov2)                                     //
+//                                                                        //
+// is called by MINUIT                                                    //
+// for given values of the parameters it calculates                       //
+//                     the function to be minimized                       //  
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+void fcnTikhonov2(Int_t &npar, Double_t *gin, Double_t &f, 
+                              Double_t *par, Int_t iflag);
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// MUnfold                                                                //
+//                                                                        //
+// class for unfolding a 1-dimensional distribution                       //
+//                                                                        //
+// the methods used are described in :                                    //
+//                                                                        //
+//     V.B.Anykeyev et al., NIM A303 (1991) 350                           //
+//     M. Schmelling, Nucl. Instr. and Meth. A 340 (1994) 400             //
+//     M. Schmelling : "Numerische Methoden der Datenanalyse"             //
+//                    Heidelberg, Maerz 1998                              //
+//     M.Bertero, INFN/TC-88/2 (1988)                                     //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+class MUnfold : public TObject
+{
+public:
+    TString   bintitle;
+
+    UInt_t    fNa;        // Number of bins in the distribution to be unfolded
+    UInt_t    fNb;        // Number of bins in the unfolded distribution
+
+    TMatrixD  fMigrat;    // migration matrix                  (fNa, fNb)
+    TMatrixD  fMigraterr2;// error**2 of migration matrix      (fNa, fNb)
+
+    TMatrixD  fMigOrig;    // original migration matrix         (fNa, fNb)
+    TMatrixD  fMigOrigerr2;// error**2 oforiginal migr. matrix  (fNa, fNb)
+
+    TMatrixD  fMigSmoo;    // smoothed migration matrix M       (fNa, fNb)
+    TMatrixD  fMigSmooerr2;// error**2 of smoothed migr. matrix (fNa, fNb)
+    TMatrixD  fMigChi2;    // chi2 contributions for smoothing  (fNa, fNb)
+
+    TMatrixD  fVa;        // distribution to be unfolded       (fNa)
+    TMatrixD  fVacov;     // error matrix of fVa               (fNa, fNa)
+    TMatrixD  fVacovInv; // inverse of fVacov                 (fNa, fNa)
+    Double_t  fSpurVacov; // Spur of fVacov
+
+    //    UInt_t    fVaevents;  // total number of events
+    UInt_t    fVapoints;  // number of significant measurements
+
+    TMatrixD  fVb;        // unfolded distribution             (fNb)
+    TMatrixD  fVbcov;     // error matrix of fVb               (fNb, fNb)
+
+    TMatrixD  fVEps;      // prior distribution                (fNb)
+    TMatrixDColumn fVEps0;
+
+    Double_t  fW;         // weight
+    Double_t  fWbest;     // best weight
+    Int_t     ixbest;
+
+    TMatrixD  fResult;    // unfolded distribution and errors  (fNb, 5)
+    TMatrixD  fChi2;      // chisquared contribution           (fNa, 1)
+
+    Double_t  fChisq;     // total chisquared
+    Double_t  fNdf;       // number of degrees of freedom
+    Double_t  fProb;      // chisquared probability
+
+    TMatrixD  G;          // G = M * M(transposed)             (fNa, fNa)
+    TVectorD  EigenValue; // vector of eigenvalues lambda of G (fNa)
+    TMatrixD  Eigen;      // matrix of eigen vectors of G      (fNa, fNa)
+    Double_t  RankG;      // rank of G
+    Double_t  tau;        // 1 / lambda_max
+    Double_t  EpsLambda;
+
+    // quantities stored for each weight :
+    TVectorD SpSig;       // Spur of covariance matrix of fVbcov
+    TVectorD SpAR;        // effective rank of G^tilde
+    TVectorD chisq;       // chi squared (measures agreement between
+    // fVa and the folded fVb)
+    TVectorD SecDer;      // regularization term = sum of (2nd der.)**2
+    TVectorD ZerDer;      // regularization term = sum of (fVb)**2
+    TVectorD Entrop;      // regularization term = reduced cross-entropy
+    TVectorD DAR2;        //
+    TVectorD Dsqbar;      //
+
+    Double_t SpurAR;
+    Double_t SpurSigma;
+    Double_t SecDeriv;
+    Double_t ZerDeriv;
+    Double_t Entropy;
+    Double_t DiffAR2;
+    Double_t Chisq;
+    Double_t D2bar;
+
+    TMatrixD Chi2;
+
+    //
+
+    // plots versus weight
+    Int_t    Nix;
+    Double_t xmin;
+    Double_t xmax;
+    Double_t dlogx;
+
+    TH1D *hBchisq;
+    TH1D *hBSpAR;
+    TH1D *hBDSpAR;
+    TH1D *hBSpSig;
+    TH1D *hBDSpSig;
+    TH1D *hBSecDeriv;
+    TH1D *hBDSecDeriv;
+    TH1D *hBZerDeriv;
+    TH1D *hBDZerDeriv;
+    TH1D *hBEntropy;
+    TH1D *hBDEntropy;
+    TH1D *hBDAR2;
+    TH1D *hBD2bar;
+
+    //
+    TH1D *hEigen;
+
+    // plots for the best solution
+    TH2D *fhmig;
+    TH2D *shmig;
+    TH2D *shmigChi2;
+
+    TH1D *fhb0;
+
+    TH1D *fha;
+
+    TH1D *hprior;
+
+    TH1D *hb;
+
+    Double_t CalcSpurSigma(TMatrixD &T, Double_t norm=1)
+    {
+        Double_t spursigma = 0;
+
+        for (UInt_t a=0; a<fNb; a++)
+        {
+            for (UInt_t b=0; b<fNb; b++)
+            {
+                fVbcov(a,b) = 0;
+
+                for (UInt_t c=0; c<fNa; c++)
+                    for (UInt_t d=0; d<fNa; d++)
+                        fVbcov(a,b) += T(a,d)*fVacov(d,c)*T(b,c);
+
+                fVbcov(a,b) *= norm*norm;
+            }
+            spursigma += fVbcov(a,a);
+        }
+
+        return spursigma;
+    }
+
+public:
+    // -----------------------------------------------------------------------
+    //
+    // Constructor
+    //              copy histograms into matrices
+    //
+    MUnfold(TH1D &ha, TH2D &hacov, TH2D &hmig)
+        : fVEps(hmig.GetYaxis()->GetNbins(),1), fVEps0(fVEps, 0)
+    {
+        // ha      is the distribution to be unfolded
+        // hacov   is the covariance matrix of ha
+        // hmig    is the migration matrix;
+        //         this matrix will be used in the unfolding
+        //         unless SmoothMigrationMatrix(*hmigrat) is called;
+        //         in the latter case hmigrat is smoothed
+        //         and the smoothed matrix is used in the unfolding
+
+        // Eigen values of the matrix G, which are smaller than EpsLambda
+        // will be considered as being zero
+        EpsLambda = 1.e-10;
+        fW = 0.0;
+
+        fNa  = hmig.GetXaxis()->GetNbins();
+        const Double_t alow = hmig.GetXaxis()->GetXmin();
+        const Double_t aup  = hmig.GetXaxis()->GetXmax();
+
+        fNb  = hmig.GetYaxis()->GetNbins();
+        const Double_t blow = hmig.GetYaxis()->GetXmin();
+        const Double_t bup  = hmig.GetYaxis()->GetXmax();
+
+
+        UInt_t Na = ha.GetNbinsX();
+        if (fNa != Na)
+        {
+            cout << "MUnfold::MUnfold : dimensions do not match,  fNa = ";
+            cout << fNa << ",   Na = " << Na << endl;
+        }
+
+        cout << "MUnfold::MUnfold :" << endl;
+        cout << "==================" << endl;
+        cout << "   fNa = " << fNa << ",   fNb = " << fNb << endl;
+
+        // ------------------------
+
+        fVa.ResizeTo(fNa, 1);
+        CopyCol(fVa, ha, 0);
+
+        cout << "   fVa = ";
+
+        for (UInt_t i=0; i<fNa; i++)
+            cout << fVa(i,0) << " \t";
+        cout << endl;
+
+        Double_t vaevents = GetMatrixSumCol(fVa, 0);
+        cout << "   Total number of events in fVa = " << vaevents << endl;
+
+        // ------------------------
+
+        fChi2.ResizeTo(fNa,1);
+        Chi2.ResizeTo(fNa,1);
+
+        // ------------------------
+
+        fVacov.ResizeTo(fNa, fNa);
+        fSpurVacov = 0;
+
+        CopyH2M(fVacov, hacov);
+
+        fVapoints = 0;
+        for (UInt_t i=0; i<fNa; i++)
+            if (fVa(i,0)>0 && fVacov(i,i)<fVa(i,0)*fVa(i,0))
+                fVapoints++;
+
+        fSpurVacov = GetMatrixSumDiag(fVacov);
+
+        //cout << "MUnfold::MUnfold :   fVacov = " << endl;
+        //cout << "==============================" << endl;
+        //fVacov.Print();
+
+        cout << "   Number of significant points in fVa = ";
+        cout << fVapoints << endl;
+
+        cout << "   Spur of fVacov = ";
+        cout << fSpurVacov << endl;
+
+        // ------------------------
+
+        fVacovInv.ResizeTo(fNa, fNa);
+        fVacovInv = fVacov;
+        fVacovInv.InvertPosDef();
+
+        //cout << "MUnfold::MUnfold :   fVacovInv = " << endl;
+        //cout << "==================================" << endl;
+        //fVacovInv.Print();
+
+        // ------------------------
+        // fMigrat is the migration matrix to be used in the unfolding;
+        // fMigrat may be overwritten by SmoothMigrationMatrix
+
+        fMigrat.ResizeTo(fNa, fNb); // row, col
+
+        CopyH2M(fMigrat, hmig);
+
+
+        // ------------------------
+
+        fMigraterr2.ResizeTo(fNa, fNb); // row, col
+        CopySqr(fMigraterr2, hmig);
+
+        // normaxlize
+
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            const Double_t sum = GetMatrixSumCol(fMigrat, j);
+
+            if (sum==0)
+                continue;
+
+            TMatrixDColumn col1(fMigrat, j);
+            col1 *= 1./sum;
+
+            TMatrixDColumn col2(fMigraterr2, j);
+            col2 *= 1./(sum*sum);
+        }
+
+        //cout << "MUnfold::MUnfold :   fMigrat = " << endl;
+        //cout << "===============================" << endl;
+        //fMigrat.Print();
+
+        //cout << "MUnfold::MUnfold :   fMigraterr2 = " << endl;
+        //cout << "===================================" << endl;
+        //fMigraterr2.Print();
+
+        // ------------------------
+        G.ResizeTo(fNa, fNa);
+        EigenValue.ResizeTo(fNa);
+        Eigen.ResizeTo(fNa, fNa);
+
+        fMigOrig.ResizeTo(fNa, fNb); 
+        fMigOrigerr2.ResizeTo(fNa, fNb); 
+
+        fMigSmoo.ResizeTo    (fNa, fNb); 
+        fMigSmooerr2.ResizeTo(fNa, fNb); 
+        fMigChi2.ResizeTo    (fNa, fNb); 
+
+        // ------------------------
+
+        fVEps0 = 1./fNb;
+
+        //cout << "MUnfold::MUnfold :   Default prior distribution fVEps = " << endl;
+        //cout << "========================================================" << endl;
+        //fVEps.Print();
+
+        // ------------------------
+
+        fVb.ResizeTo(fNb,1);
+        fVbcov.ResizeTo(fNb,fNb);
+
+        // ----------------------------------------------------
+        // number and range of weights to be scanned
+        Nix  = 30;
+        xmin = 1.e-5;
+        xmax = 1.e5;
+        dlogx = (log10(xmax)-log10(xmin)) / Nix;
+
+        SpSig.ResizeTo (Nix);
+        SpAR.ResizeTo  (Nix);
+        chisq.ResizeTo (Nix);
+        SecDer.ResizeTo(Nix);
+        ZerDer.ResizeTo(Nix);
+        Entrop.ResizeTo(Nix);
+        DAR2.ResizeTo  (Nix);
+        Dsqbar.ResizeTo(Nix);
+
+        //------------------------------------
+        // plots as a function of the iteration  number
+
+        hBchisq = new TH1D("Bchisq", "chisq",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSpAR  = new TH1D("BSpAR", "SpurAR",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSpAR  = new TH1D("BDSpAR", "Delta(SpurAR)",
+                            Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSpSig = new TH1D("BSpSig", "SpurSigma/SpurC",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSpSig = new TH1D("BDSpSig", "Delta(SpurSigma/SpurC)",
+                            Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSecDeriv = new TH1D("BSecDeriv", "Second Derivative squared",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSecDeriv = new TH1D("BDSecDeriv", "Delta(Second Derivative squared)",
+                               Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBZerDeriv = new TH1D("BZerDeriv", "Zero Derivative squared",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDZerDeriv = new TH1D("BDZerDeriv", "Delta(Zero Derivative squared)",
+                               Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBEntropy = new TH1D("BEntrop", "Entropy",
+                             Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDEntropy = new TH1D("BDEntrop", "Delta(Entropy)",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDAR2 = new TH1D("BDAR2", "norm(AR-AR+)",
+                          Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBD2bar = new TH1D("BD2bar", "(b_unfolded-b_ideal)**2",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        //-------------------------------------
+        // original migration matrix
+        fhmig = new TH2D("fMigrat", "Migration matrix",
+                         fNa, alow, aup, fNb, blow, bup);
+        fhmig->Sumw2();
+
+        //-------------------------------------
+        // smoothed migration matrix
+        shmig = new TH2D("sMigrat", "Smoothed migration matrix",
+                         fNa, alow, aup, fNb, blow, bup);
+        shmig->Sumw2();
+
+        //-------------------------------------
+        // chi2 contributions for smoothing of migration matrix
+        shmigChi2 = new TH2D("sMigratChi2", "Chi2 contr. for smoothing",
+                             fNa, alow, aup, fNb, blow, bup);
+
+        //-------------------------------------
+        // eigen values of matrix G = M * M(transposed)
+        hEigen = new TH1D("Eigen", "Eigen values of M*MT",
+                          fNa, 0.5, fNa+0.5);
+
+        //------------------------------------
+        // Ideal distribution
+        
+        fhb0 = new TH1D("fhb0", "Ideal distribution", fNb, blow, bup);
+        fhb0->Sumw2();
+        
+
+        //------------------------------------
+        // Distribution to be unfolded
+        fha = new TH1D("fha", "Distribution to be unfolded", fNa, alow, aup);
+        fha->Sumw2();
+
+        //------------------------------------
+        // Prior distribution
+        hprior = new TH1D("Prior", "Prior distribution", fNb, blow, bup);
+
+        //------------------------------------
+        // Unfolded distribution
+        hb = new TH1D("DataSp", "Unfolded distribution", fNb, blow, bup);
+        hb->Sumw2();
+
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Define prior distribution to be a constant
+    //
+    void SetPriorConstant()
+    {
+        fVEps0 = 1./fNb;
+
+        CopyCol(*hprior, fVEps);
+
+        //cout << "SetPriorConstant : Prior distribution fVEps = " << endl;
+        //cout << "==============================================" << endl;
+        //fVEps.Print();
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Take prior distribution from the histogram 'ha'
+    // which may have a different binning than 'hprior'
+    //
+    Bool_t SetPriorRebin(TH1D &ha)
+    {
+        // ------------------------------------------------------------------
+        //
+        // fill the contents of histogram 'ha' into the histogram 'hrior';
+        // the histograms need not have the same binning;
+        // if the binnings are different, the bin contents of histogram 'ha'
+        //    are distributed properly (linearly) over the bins of 'hprior'
+        //
+
+        const Int_t    na   = ha.GetNbinsX();
+        const Double_t alow = ha.GetBinLowEdge(1);
+        const Double_t aup  = ha.GetBinLowEdge(na+1);
+
+        const Int_t    nb   = hprior->GetNbinsX();
+        const Double_t blow = hprior->GetBinLowEdge(1);
+        const Double_t bup  = hprior->GetBinLowEdge(nb+1);
+
+        // check whether there is an overlap
+        //       between the x ranges of the 2 histograms
+        if (alow>bup || aup<blow)
+        {
+            cout << "Rebinning not possible because there is no overlap of the x ranges of the two histograms" << endl;
+            return kFALSE;
+        }
+
+        // there is an overlap
+        //********************
+        Double_t sum = 0;
+        for (Int_t j=1; j<=nb; j++)
+        {
+            const Double_t yl = hprior->GetBinLowEdge(j);
+            const Double_t yh = hprior->GetBinLowEdge(j+1);
+
+            // search bins of histogram ha which contribute
+            // to bin j of histogram hb
+            //----------------
+            Int_t il=0;
+            Int_t ih=0;
+            for (Int_t i=2; i<=na+1; i++)
+            {
+                const Double_t xl = ha.GetBinLowEdge(i);
+                if (xl>yl)
+                {
+                    il = i-1;
+
+                    //.................................
+                    ih = 0;
+                    for (Int_t k=(il+1); k<=(na+1); k++)
+                    {
+                        const Double_t xh = ha.GetBinLowEdge(k);
+                        if (xh >= yh)
+                        {
+                            ih = k-1;
+                            break;
+                        }
+                    }
+                    //.................................
+                    if (ih == 0)
+                        ih = na;
+                    break;
+                }
+            }
+            //----------------
+            if (il == 0)
+            {
+                cout << "Something is wrong " << endl;
+                cout << "          na, alow, aup = " << na << ",  " << alow
+                    << ",  " << aup << endl;
+                cout << "          nb, blow, bup = " << nb << ",  " << blow
+                    << ",  " << bup << endl;
+                return kFALSE;
+            }
+
+            Double_t content=0;
+            // sum up the contribution to bin j
+            for (Int_t i=il; i<=ih; i++)
+            {
+                const Double_t xl = ha.GetBinLowEdge(i);
+                const Double_t xh = ha.GetBinLowEdge(i+1);
+                const Double_t bina = xh-xl;
+
+                if (xl<yl  &&  xh<yh)
+                    content += ha.GetBinContent(i) * (xh-yl) / bina;
+                else
+                    if (xl<yl  &&  xh>=yh)
+                        content += ha.GetBinContent(i) * (yh-yl) / bina;
+                    else
+                        if (xl>=yl  &&  xh<yh)
+                            content += ha.GetBinContent(i);
+                        else if (xl>=yl  &&  xh>=yh)
+                            content += ha.GetBinContent(i) * (yh-xl) / bina;
+            }
+            hprior->SetBinContent(j, content);
+            sum += content;
+        }
+
+        // normalize histogram hb
+        if (sum==0)
+        {
+            cout << "histogram hb is empty; sum of weights in ha = ";
+            cout << ha.GetSumOfWeights() << endl;
+            return kFALSE;
+        }
+
+        for (Int_t j=1; j<=nb; j++)
+        {
+            const Double_t content = hprior->GetBinContent(j)/sum;
+            hprior->SetBinContent(j, content);
+            fVEps0(j-1) = content;
+        }
+
+        //cout << "SetPriorRebin : Prior distribution fVEps = " << endl;
+        //cout << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Set prior distribution to a given distribution 'hpr'
+    //
+    Bool_t SetPriorInput(TH1D &hpr)
+    {
+        CopyCol(fVEps, hpr);
+
+        const Double_t sum = GetMatrixSumCol(fVEps, 0);
+
+        if (sum<=0)
+        {
+            cout << "MUnfold::SetPriorInput: invalid prior distribution" << endl;
+            return kFALSE;
+        }
+
+        // normalize prior distribution
+        fVEps0 *= 1./sum;
+
+        CopyCol(*hprior, fVEps);
+
+        //cout << "SetPriorInput : Prior distribution fVEps = " << endl;
+        //cout << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Define prior distribution to be a power law
+    // use input distribution 'hprior' only
+    //           for defining the histogram parameters
+    //
+    Bool_t SetPriorPower(Double_t gamma)
+    {
+        // generate distribution according to a power law
+        //                        dN/dE = E^{-gamma}
+        //  or with y = lo10(E),  E = 10^y :
+        //                        dN/dy = ln10 * 10^{y*(1-gamma)}
+        TH1D hpower(*hprior);
+
+        const UInt_t   nbin = hprior->GetNbinsX();
+        const Double_t xmin = hprior->GetBinLowEdge(1);
+        const Double_t xmax = hprior->GetBinLowEdge(nbin+1);
+
+        cout << "nbin, xmin, xmax = " << nbin << ",  ";
+        cout << xmin << ",  " << xmax << endl;
+
+        TF1* fpow = new TF1("fpow", "pow(10.0, x*(1.0-[0]))", xmin,xmax);
+        fpow->SetParName  (0,"gamma");
+        fpow->SetParameter(0, gamma );
+
+        hpower.FillRandom("fpow", 100000);
+
+        // fill prior distribution
+        CopyCol(fVEps, hpower);
+
+        const Double_t sum = GetMatrixSumCol(fVEps, 0);
+        if (sum <= 0)
+        {
+            cout << "MUnfold::SetPriorPower : invalid prior distribution"  << endl;
+            return kFALSE;
+        }
+
+        // normalize prior distribution
+        fVEps0 *= 1./sum;
+        CopyCol(*hprior, fVEps);
+
+        //cout << "SetPriorPower : Prior distribution fVEps = " << endl;
+        //cout << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Set the initial weight
+    //
+    Bool_t SetInitialWeight(Double_t &weight)
+    {
+        if (weight == 0.0)
+        {
+            TMatrixD v1(fVa, TMatrixD::kTransposeMult, fVacovInv);
+            TMatrixD v2(v1, TMatrixD::kMult, fVa);
+            weight = 1./sqrt(v2(0,0));
+        }
+
+        cout << "MUnfold::SetInitialWeight : Initial Weight = "
+            << weight << endl;
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Print the unfolded distribution
+    //
+    void PrintResults()
+    {
+        cout << bintitle << endl;
+        cout << "PrintResults : Unfolded distribution fResult " << endl;
+        cout << "=============================================" << endl;
+        //cout << "val, eparab, eplus, eminus, gcc = "  << endl;
+
+        for (UInt_t i=0; i<fNb; i++)
+        {
+	  //    cout << fResult(i, 0) << " \t";
+          //  cout << fResult(i, 1) << " \t";
+          //  cout << fResult(i, 2) << " \t";
+          //  cout << fResult(i, 3) << " \t";
+          //  cout << fResult(i, 4) <<  endl;
+        }
+        cout << "Chisquared, NDF, chi2 probability, ixbest = "
+            << fChisq << ",  "
+            << fNdf << ",  " << fProb << ",  " << ixbest << endl;
+
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Schmelling  : unfolding by minimizing the function Z
+    //               by Gauss-Newton iteration
+    //
+    //               the weights are scanned between
+    //               1.e-5*fWinitial and 1.e5*fWinitial
+    //
+    Bool_t Schmelling(TH1D &hb0)
+    {
+    
+        //======================================================================
+        // copy ideal distribution
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+    
+        //-----------------------------------------------------------------------
+        // Initialization
+        // ==============
+
+        Int_t numGiteration;
+        Int_t MaxGiteration = 1000;
+
+        TMatrixD alpha;
+        alpha.ResizeTo(fNa, 1);
+
+
+        //-----------------------------------------------------------------------
+        // Newton iteration
+        // ================
+
+        Double_t dga2;
+        Double_t dga2old;
+        Double_t EpsG = 1.e-12;
+
+        TMatrixD wZdp_inv(fNa, fNa);
+        TMatrixD d(fNb, 1);
+        TMatrixD p(fNb, 1);
+
+        TMatrixD gamma (fNa, 1);
+        TMatrixD dgamma(fNa, 1);
+
+        Double_t fWinitial;
+        fWinitial = 0.0;
+        SetInitialWeight(fWinitial);
+        // for my example this fWinitial was not good; therefore :
+        fWinitial = 1.0;
+
+        Int_t ix;
+        Double_t xiter;
+
+        //--------   start  scanning weights   --------------------------
+        // if full == kFALSE   only quantities necessary for the Gauss-Newton
+        //                     iteration are calculated in SchmellCore
+        // if full == kTRUE    in addition the unfolded distribution,
+        //                     its covariance matrix and quantities like
+        //                     Chisq, SpurAR, etc. are computed in SchmellCore
+        //Bool_t full;
+        //full = kFALSE;
+        Int_t full;
+
+        cout << "Schmelling : start loop over weights" << endl;
+
+        dga2 = 1.e20;
+        for (ix=0; ix<Nix; ix++)
+        {
+            xiter = pow(10.0,log10(xmin)+ix*dlogx) * fWinitial;
+
+            //----------   start Gauss-Newton iteration   ----------------------
+            numGiteration = 0;
+
+            // if there was no convergence and the starting gamma was != 0
+            // redo unfolding for the same weight starting with gamma = 0
+            //
+            Int_t gamma0 = 0;
+            while (1)
+	    {
+              if (dga2 > EpsG)
+	      {
+                gamma0 = 1;
+                gamma.Zero();
+	      }
+
+              dga2 = 1.e20;
+
+              while (1)
+              {
+                dga2old = dga2;
+
+                full = 0;
+                SchmellCore(full, xiter, gamma, dgamma, dga2);
+
+                gamma += dgamma;
+
+                //cout << "Schmelling : ix, numGiteration, dga2, dga2old = "
+                //     << ix << ",  " << numGiteration << ",  "
+                //     << dga2 << ",  " << dga2old << endl;
+
+                numGiteration += 1;
+
+                // convergence
+                if (dga2 < EpsG)
+                    break;
+
+                // no convergence
+                if (numGiteration > MaxGiteration)
+                    break;
+
+                // gamma doesn't seem to change any more
+                if (fabs(dga2-dga2old) < EpsG/100.)
+                    break;
+              }
+              //----------   end Gauss-Newton iteration   ------------------------
+              if (dga2<EpsG || gamma0 != 0) break;
+	    }
+
+            // if Gauss-Newton iteration has not converged
+            // go to next weight
+            if (dga2 > EpsG)
+            {
+                cout << "Schmelling : Gauss-Newton iteration has not converged;"
+                    << "   numGiteration = " << numGiteration << endl;
+                cout << "             ix, dga2, dga2old = " << ix << ",  "
+                    << dga2 << ",  " << dga2old << endl;
+                continue;
+            }
+
+            //cout << "Schmelling : Gauss-Newton iteration has converged;" << endl;
+            //cout << "==================================================" << endl;
+            //cout << "             numGiteration = " << numGiteration << endl;
+            //cout << "             ix, dga2 = " << ix << ",  " << dga2 << endl;
+
+            // calculated quantities which will be useful for determining
+            // the best weight (Chisq, SpurAR, ...)
+            //full = kTRUE;
+            full = 1;
+            SchmellCore(full, xiter, gamma, dgamma, dga2);
+
+            // calculate difference between ideal and unfolded distribution
+            Double_t D2bar = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                D2bar += temp*temp;
+            }
+
+            SpAR(ix)  = SpurAR;
+            SpSig(ix) = SpurSigma;
+            chisq(ix) = Chisq;
+            SecDer(ix) = SecDeriv;
+            ZerDer(ix) = ZerDeriv;
+            Entrop(ix) = Entropy;
+            DAR2(ix)   = DiffAR2;
+            Dsqbar(ix) = D2bar;
+
+        }
+        //----------   end of scanning weights   -------------------------------
+        cout << "Schmelling : end of loop over weights" << endl;
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xbin = log10(xmin)+ix*dlogx;
+            xiter = pow(10.0,xbin) * fWinitial;
+
+            Int_t bin;
+            bin = hBchisq->FindBin( xbin );
+            hBchisq->SetBinContent(bin,chisq(ix));
+            hBSpAR->SetBinContent(bin,SpAR(ix));
+            hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+            hBSecDeriv->SetBinContent(bin,SecDer(ix));
+            hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+            hBEntropy->SetBinContent(bin,Entrop(ix));
+            hBDAR2->SetBinContent(bin,DAR2(ix));
+            hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+            if (ix > 0)
+            {
+                Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                hBDSpAR->SetBinContent(bin,DSpAR);
+
+                Double_t diff = SpSig(ix) - SpSig(ix-1);
+                Double_t DSpSig = diff;
+                hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                hBDEntropy->SetBinContent(bin,DEntrop);
+
+                Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                hBDZerDeriv->SetBinContent(bin,DZerDer);
+            }
+        }
+
+        // Select best weight
+        SelectBestWeight();
+
+        if (ixbest < 0.0)
+        {
+            cout << "Schmelling : no solution found; " << endl;
+            return kFALSE;
+        }
+
+        // do the unfolding using the best weight
+        //full = kTRUE;
+
+
+        xiter = pow(10.0,log10(xmin)+ixbest*dlogx) * fWinitial;
+
+        //----------   start Gauss-Newton iteration   ----------------------
+        numGiteration = 0;
+        gamma.Zero();
+        dga2 = 1.e20;
+
+        while (1)
+        {
+            full = 1;
+            SchmellCore(full, xiter, gamma, dgamma, dga2);
+            gamma += dgamma;
+
+            //cout << "Schmelling : sum(dgamma^2) = " << dga2 << endl;
+
+            numGiteration += 1;
+
+            if (numGiteration > MaxGiteration)
+                break;
+
+            if (dga2 < EpsG)
+                break;
+        }
+        //----------   end Gauss-Newton iteration   ------------------------
+
+
+        //-----------------------------------------------------------------------
+        // termination stage
+        // =================
+
+        cout << "Schmelling : best solution found; " << endl;
+        cout << "==================================" << endl;
+        cout << "             xiter, ixbest, numGiteration, Chisq = "
+            << xiter << ",  " << ixbest << ",  "
+            << numGiteration << ",  " << Chisq << endl;
+
+        //------------------------------------
+        //..............................................
+        // put unfolded distribution into fResult
+        //     fResult(i,0)   value in bin i
+        //     fResult(i,1)   error of value in bin i
+
+        fNdf = SpurAR;
+        fChisq = Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          fChi2(i,0) = Chi2(i,0);
+	}
+
+        UInt_t iNdf   = (UInt_t) (fNdf+0.5);
+        fProb = iNdf>0 ? TMath::Prob(fChisq, iNdf) : 0;
+
+        fResult.ResizeTo(fNb, 5);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            fResult(i, 0) = fVb(i,0);
+            fResult(i, 1) = sqrt(fVbcov(i,i));
+            fResult(i, 2) = 0.0;
+            fResult(i, 3) = 0.0;
+            fResult(i, 4) = 1.0; 
+	}
+
+        //--------------------------------------------------------
+
+        cout << "Schmelling : gamma = " << endl;
+        for (UInt_t i=0; i<fNa; i++)
+            cout << gamma(i,0) << " \t";
+        cout << endl;
+
+        return kTRUE;
+    }
+
+
+
+
+    // -----------------------------------------------------------------------
+    //
+    // SchmellCore     main part of Schmellings calculations
+    //
+    void SchmellCore(Int_t full, Double_t &xiter, TMatrixD &gamma,
+                     TMatrixD &dgamma, Double_t &dga2)
+    {
+        Double_t norm;
+        TMatrixD wZdp_inv(fNa, fNa);
+        TMatrixD d(fNb, 1);
+        TMatrixD p(fNb, 1);
+
+        //--------------------------------------------------------
+        //--      determine the probability vector p
+
+
+        TMatrixD v3(gamma, TMatrixD::kTransposeMult, fMigrat);
+        TMatrixD v4(TMatrixD::kTransposed, v3);
+        d = v4;
+        Double_t dmax  = -1.e10;
+        for (UInt_t j=0; j<fNb; j++)
+            if (d(j,0)>dmax)
+                dmax = d(j,0);
+
+        Double_t psum = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            d(j,0) -= dmax;
+            p(j,0)  = fVEps0(j)*exp(xiter*d(j,0));
+            psum += p(j,0);
+        }
+
+        p *= 1.0/psum;
+
+        //--      get the vector alpha
+
+        TMatrixD alpha(fMigrat, TMatrixD::kMult, p);
+
+        //--      determine the current normalization
+
+        TMatrixD v2   (alpha, TMatrixD::kTransposeMult, fVacovInv);
+        TMatrixD normb(v2,    TMatrixD::kMult, alpha);
+
+        TMatrixD normc(v2,    TMatrixD::kMult, fVa);
+
+        norm  = normc(0,0)/normb(0,0);
+
+        //--------------------------------------------------------
+        //--      determine the scaled slope vector s and Hessian H
+
+        TMatrixD Zp(fNa,1);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            Zp(i,0) = norm*alpha(i,0) - fVa(i,0);
+            for (UInt_t k=0; k<fNa; k++)
+                Zp(i,0) += gamma(k,0)*fVacov(k,i);
+        }
+
+
+        TMatrixD Q  (fNa, fNa);
+        TMatrixD wZdp(fNa, fNa);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                Q(i,j) = - alpha(i,0)*alpha(j,0);
+                for (UInt_t k=0; k<fNb; k++)
+                    Q(i,j) += fMigrat(i,k)*fMigrat(j,k)*p(k,0);
+                wZdp(i,j) = xiter*norm*Q(i,j) + fVacov(i,j);
+            }
+        }
+
+        //--      invert H and calculate the next Newton step
+
+        Double_t determ = 1.0;
+        wZdp_inv = wZdp;
+        wZdp_inv.Invert(&determ);
+
+        if(determ == 0.0)
+        {
+            cout << "SchmellCore: matrix inversion for H failed" << endl;
+            return;
+        }
+
+
+        dga2 = 0.0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            dgamma(i,0) = 0.0;
+            for (UInt_t j=0; j<fNa; j++)
+                dgamma(i,0) -= wZdp_inv(i,j)*Zp(j,0);
+            dga2 += dgamma(i,0)*dgamma(i,0);
+        }
+
+        if (full == 0)
+            return;
+
+        //--------------------------------------------------------
+        //--      determine chi2 and dNdf (#measurements ignored)
+        Double_t dNdf = 0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            Chi2(i,0) = 0;
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                Chi2(i,0) += fVacov(i,j) * gamma(i,0) * gamma(j,0);
+                dNdf       += fVacov(i,j) * wZdp_inv(j,i);
+            }
+        }
+        Chisq = GetMatrixSumCol(Chi2, 0);
+        SpurAR = fNa - dNdf;
+
+        //-----------------------------------------------------
+        // calculate the norm |AR - AR+|**2
+
+        TMatrixD AR(fNa, fNa);
+        DiffAR2 = 0.0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                AR(i,j) = 0.0;
+                for (UInt_t k=0; k<fNa; k++)
+                    AR(i,j) +=  fVacov(i,k) * wZdp_inv(k,j);
+                DiffAR2 += AR(i,j) * AR(i,j);
+            }
+        }
+
+        //--------------------------------------------------------
+        //--      fill distribution b(*)
+        fVb = p;
+        fVb *= norm;
+
+        //--      determine the covariance matrix of b (very expensive)
+
+        TMatrixD T(fNb,fNa);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                T(i,j) = 0.0;
+                for (UInt_t k=0; k<fNa; k++)
+                    T(i,j) += xiter*wZdp_inv(k,j)*(fMigrat(k,i)-alpha(k,0))*p(i,0);
+            }
+        }
+
+        SpurSigma = CalcSpurSigma(T, norm);
+
+        //--------------------------------------------------------
+
+        //-----------------------------------------------------
+        // calculate the second derivative squared
+
+        SecDeriv = 0;
+        for (UInt_t j=1; j<(fNb-1); j++)
+        {
+            Double_t temp =
+                + 2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+                - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+            SecDeriv += temp*temp;
+        }
+
+        ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+        Entropy = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            if (p(j,0) > 0.0)
+                Entropy += p(j,0) * log( p(j,0) );
+
+        //--------------------------------------------------------
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Smooth migration matrix
+    //              by fitting a function to the migration matrix
+    //
+    Bool_t SmoothMigrationMatrix(TH2D &hmigorig)
+    {
+        // copy histograms into matrices; the matrices will be used in fcnSmooth
+        // ------------------------
+
+      
+      //cout << "MUnfold::SmoothMigrationMatrix : fNa, fNb = " << fNa << ",  " << fNb << endl;
+
+      //cout << "MUnfold::SmoothMigrationMatrix:   fMigOrig = "  << endl;
+      //cout << "========================================"  << endl;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fMigOrig(i, j)     = hmigorig.GetBinContent(i+1, j+1);
+	        //cout << fMigOrig(i, j) << " \t";
+            }
+            //cout << endl;
+        }
+      
+
+        // ------------------------
+
+      
+        //cout << "MUnfold::SmoothMigrationMatrix :   fMigOrigerr2 = " << endl;
+        //cout << "=============================================" << endl;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fMigOrigerr2(i, j) =   hmigorig.GetBinError(i+1, j+1)
+                    * hmigorig.GetBinError(i+1, j+1);
+
+                //cout << fMigOrigerr2(i, j) << " \t";
+            }
+            //cout << endl;
+        }
+      
+
+        // ------------------------
+        // the number of free parameters (npar) is equal to 6:
+        //     a0mean, a1mean, a2mean     
+        //     <log10(Eest)>    = a0 + a1*log10(Etrue) + a2*SQR(log10(Etrue))
+        //                                                     + log10(Etrue)  
+        //     b0RMS,  b1RMS, b2RMS      
+        //     RMS(log10(Eest)) = b0 + b1*log10(Etrue) + b2*SQR(log10(Etrue))
+        // 
+        UInt_t npar = 6;
+
+        if (npar > 20)
+        {
+            cout << "MUnfold::SmoothMigrationMatrix : too many parameters,  npar = "
+                << npar << endl;
+            return kFALSE;
+        }
+
+
+        //..............................................
+        // Find reasonable starting values for a0, a1 and b0, b1
+
+        Double_t xbar   = 0.0;
+        Double_t xxbar  = 0.0;
+
+        Double_t ybarm  = 0.0;
+        Double_t xybarm = 0.0;
+
+        Double_t ybarR  = 0.0;
+        Double_t xybarR = 0.0;
+
+        Double_t Sum = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            Double_t x = (double)j + 0.5;
+
+            Double_t meany = 0.0;
+            Double_t RMSy  = 0.0;
+            Double_t sum   = 0.0;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                Double_t y = (double)i + 0.5;
+                meany +=   y * fMigOrig(i, j);
+                RMSy  += y*y * fMigOrig(i, j);
+                sum   +=       fMigOrig(i, j);
+            }
+            if (sum > 0.0)
+            {
+                meany  = meany / sum;
+                RMSy   =  RMSy / sum  - meany*meany;
+                RMSy = sqrt(RMSy);
+
+                Sum += sum;
+                xbar  +=   x * sum;
+                xxbar += x*x * sum;
+
+                ybarm  +=   meany * sum;
+                xybarm += x*meany * sum;
+
+                ybarR  +=   RMSy  * sum;
+                xybarR += x*RMSy  * sum;
+            }
+        }
+
+        if (Sum > 0.0)
+        {
+            xbar   /= Sum;
+            xxbar  /= Sum;
+
+            ybarm  /= Sum;
+            xybarm /= Sum;
+
+            ybarR  /= Sum;
+            xybarR /= Sum;
+        }
+
+        Double_t a1start = (xybarm - xbar*ybarm) / (xxbar - xbar*xbar);
+        Double_t a0start = ybarm - a1start*xbar;
+        a1start = a1start - 1.0;
+
+        Double_t b1start = (xybarR - xbar*ybarR) / (xxbar - xbar*xbar);
+        Double_t b0start = ybarR - b1start*xbar;
+
+        cout << "MUnfold::SmoothMigrationMatrix : " << endl;
+        cout << "============================" << endl;
+        cout << "a0start, a1start = " << a0start << ",  " << a1start << endl;
+        cout << "b0start, b1start = " << b0start << ",  " << b1start << endl;
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+
+        char name[20][100];
+        Double_t vinit[20];
+        Double_t  step[20];
+        Double_t limlo[20];
+        Double_t limup[20];
+        Int_t    fix[20];
+
+        sprintf(&name[0][0], "a0mean");
+        vinit[0] = a0start;
+        //vinit[0] = 1.0;
+        step[0]  = 0.1;
+        limlo[0] = 0.0;
+        limup[0] = 0.0;
+        fix[0]   = 0;
+
+        sprintf(&name[1][0], "a1mean");
+        vinit[1] = a1start;
+        //vinit[1] = 0.0;
+        step[1]  = 0.1;
+        limlo[1] = 0.0;
+        limup[1] = 0.0;
+        fix[1]   = 0;
+
+        sprintf(&name[2][0], "a2mean");
+        vinit[2] = 0.0;
+        step[2]  = 0.1;
+        limlo[2] = 0.0;
+        limup[2] = 0.0;
+        fix[2]   = 0;
+
+        sprintf(&name[3][0], "b0RMS");
+        vinit[3] = b0start;
+          //vinit[3] = 0.8;
+        step[3]  = 0.1;
+        limlo[3] = 1.e-20;
+        limup[3] = 10.0;
+        fix[3]   = 0;
+
+        sprintf(&name[4][0], "b1RMS");
+        vinit[4] = b1start;
+        //vinit[4] = 0.0;
+        step[4]  = 0.1;
+        limlo[4] = 0.0;
+        limup[4] = 0.0;
+        fix[4]   = 0;
+
+        sprintf(&name[5][0], "b2RMS");
+        vinit[5] = 0.0;
+        step[5]  = 0.1;
+        limlo[5] = 0.0;
+        limup[5] = 0.0;
+        fix[5]   = 0;
+
+
+        if ( CallMinuit(fcnSmooth, npar, name, vinit,
+                        step, limlo, limup, fix) )
+        {
+
+            // ------------------------
+            // fMigrat is the migration matrix to be used in the unfolding;
+            // fMigrat, as set by the constructor, is overwritten
+            //          by the smoothed migration matrix
+
+            for (UInt_t i=0; i<fNa; i++)
+                for (UInt_t j=0; j<fNb; j++)
+                    fMigrat(i, j) = fMigSmoo(i, j);
+
+            // ------------------------
+
+            for (UInt_t i=0; i<fNa; i++)
+                for (UInt_t j=0; j<fNb; j++)
+                    fMigraterr2(i, j) = fMigSmooerr2(i, j);
+
+
+            // normalize
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                Double_t sum = 0.0;
+                for (UInt_t i=0; i<fNa; i++)
+                    sum += fMigrat(i, j);
+
+                //cout << "SmoothMigrationMatrix : normalization fMigrat; j, sum + "
+                //     << j << ",  " << sum << endl;
+
+                if (sum == 0.0)
+                    continue;
+
+                for (UInt_t i=0; i<fNa; i++)
+                {
+                    fMigrat(i, j)     /= sum;
+                    fMigraterr2(i, j) /= (sum*sum);
+                }
+            }
+
+            cout << "MUnfold::SmoothMigrationMatrix :   fMigrat = "  << endl;
+            cout << "========================================"  << endl;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                for (UInt_t j=0; j<fNb; j++)
+                    cout << fMigrat(i, j) << " \t";
+                cout << endl;
+            }
+
+	    /*
+            cout << "MUnfold::SmoothMigrationMatrix :   fMigraterr2 = "  << endl;
+            cout << "============================================"  << endl;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                for (UInt_t j=0; j<fNb; j++)
+                    cout << fMigraterr2(i, j) << " \t";
+                cout << endl;
+            }
+	    */
+
+            // ------------------------
+
+            return kTRUE;
+        }
+
+        return kFALSE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Prepare the call to MINUIT for the minimization of the function
+    //         f = chi2*w/2 + reg, where reg is the regularization term
+    //         reg is the sum the squared 2nd derivatives
+    //                        of the unfolded distribution
+    //
+    // the corresponding fcn routine is 'fcnTikhonov2'
+    //
+    Bool_t Tikhonov2(TH1D &hb0)
+    {
+        // the number of free parameters (npar) is equal to
+        // the number of bins (fNb) of the unfolded distribution minus 1,
+        // because of the constraint that the total number of events
+        // is fixed
+        UInt_t npar = fNb-1;
+
+        if (npar > 20)
+        {
+            cout << "MUnfold::Tikhonov2 : too many parameters,  npar = "
+                << npar << ",  fNb = " << fNb << endl;
+            return kFALSE;
+        }
+
+        // copy ideal distribution
+        
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+        
+
+        //---   start w loop -----------------------------------
+
+        cout << "Tikhonov2 : start loop over weights" << endl;
+
+        Int_t ix;
+        Double_t xiter;
+
+        for (ix=0; ix<Nix; ix++)
+        {
+            fW = pow(10.0,log10(xmin)+ix*dlogx);
+
+            //..............................................
+            // Set starting values and step sizes for parameters
+
+            char name[20][100];
+            Double_t vinit[20];
+            Double_t  step[20];
+            Double_t limlo[20];
+            Double_t limup[20];
+            Int_t    fix[20];
+
+            for (UInt_t i=0; i<npar; i++)
+            {
+                sprintf(&name[i][0], "p%d", i+1);
+                vinit[i] = fVEps0(i);
+                step[i]  = fVEps0(i)/10;
+
+                // lower and upper limits  (limlo=limup=0: no limits)
+                //limlo[i] = 1.e-20;
+                limlo[i] = -1.0;
+                limup[i] = 1.0;
+                fix[i]   = 0;
+            }
+
+            // calculate solution for the weight fW
+            // flag non-convergence by chisq(ix) = 0.0
+            chisq(ix) = 0.0;
+            if ( CallMinuit(fcnTikhonov2, npar, name, vinit,
+                            step, limlo, limup, fix) )
+            {
+                // calculate difference between ideal and unfolded distribution
+                Double_t D2bar = 0.0;
+                for (UInt_t i = 0; i<fNb; i++)
+                {
+                    Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                    D2bar += temp*temp;
+                }
+
+                SpAR(ix)   = SpurAR;
+                SpSig(ix)  = SpurSigma;
+                chisq(ix)  = Chisq;
+                SecDer(ix) = SecDeriv;
+                ZerDer(ix) = ZerDeriv;
+                Entrop(ix) = Entropy;
+                DAR2(ix)   = DiffAR2;
+                Dsqbar(ix) = D2bar;
+            }
+        }
+        cout << "Tikhonov2 : end of loop over weights" << endl;
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            // test whether minimization has converged
+            if (chisq(ix) != 0.0)
+            {
+                xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+                Int_t bin;
+                bin = hBchisq->FindBin( log10(xiter) );
+                hBchisq->SetBinContent(bin,chisq(ix));
+
+                //hBSpAR->SetBinContent(bin,SpAR(ix));
+                hBSpAR->SetBinContent(bin,0.0);
+
+                hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+                hBSecDeriv->SetBinContent(bin,SecDer(ix));
+                hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+                hBEntropy->SetBinContent(bin,Entrop(ix));
+
+                //hBDAR2->SetBinContent(bin,DAR2(ix));
+                hBDAR2->SetBinContent(bin,0.0);
+
+                hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+                if (ix > 0)
+                {
+                    //Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                    //hBDSpAR->SetBinContent(bin,DSpAR);
+
+                    Double_t diff = SpSig(ix) - SpSig(ix-1);
+                    Double_t DSpSig = diff;
+                    hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                    Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                    hBDEntropy->SetBinContent(bin,DEntrop);
+
+                    Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                    hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                    Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                    hBDZerDeriv->SetBinContent(bin,DZerDer);
+                }
+            }
+        }
+
+
+        //---   end w loop -----------------------------------
+
+        // Select best weight
+        SelectBestWeight();
+
+        cout << " Tikhonov2 : after SelectBestWeight" << endl;
+
+        if (ixbest < 0.0)
+        {
+            cout << "Tikhonov2 : no result found; " << endl;
+            return kFALSE;
+        }
+
+        cout << "Tikhonov2 : best result found; " << endl;
+        cout << "===============================" << endl;
+        cout << "           ixbest = " << ixbest << endl;
+
+
+        // do a final unfolding using the best weight
+
+        fW = pow(10.0,log10(xmin)+ixbest*dlogx);
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+
+        char name[20][100];
+        Double_t vinit[20];
+        Double_t  step[20];
+        Double_t limlo[20];
+        Double_t limup[20];
+        Int_t    fix[20];
+
+        for (UInt_t i=0; i<npar; i++)
+        {
+            sprintf(&name[i][0], "p%d", i+1);
+            vinit[i] = fVEps0(i);
+            step[i]  = fVEps0(i)/10;
+
+            // lower and upper limits  (limlo=limup=0: no limits)
+            //limlo[i] = 1.e-20;
+            limlo[i] = -1.0;
+            limup[i] = 1.0;
+            fix[i]   = 0;
+        }
+
+        // calculate solution for the best weight
+        CallMinuit(fcnTikhonov2, npar, name, vinit,
+                   step, limlo, limup, fix);
+
+
+        cout << "Tikhonov : Values for best weight " << endl;
+        cout << "==================================" << endl;
+        cout << "fW, ixbest, Chisq, SpurAR, SpurSigma, SecDeriv, ZerDeriv, Entrop, DiffAR2, D2bar = " << endl;
+        cout << "      " << fW << ",  " << ixbest << ",  "
+            << Chisq << ",  " << SpurAR << ",  "
+            << SpurSigma << ",  " << SecDeriv << ",  " << ZerDeriv << ",  "
+            << Entropy << ",  " << DiffAR2 << ",  "
+            << Dsqbar(ixbest) << endl;
+
+        return kTRUE;
+
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Bertero :
+    //
+    // the unfolded distribution is calculated iteratively;
+    // the number of iterations after which the iteration is stopped
+    //            corresponds to the 'weight' in other methods
+    // a small number of iterations corresponds to strong regularization
+    // a high number to no regularization
+    //
+    // see : M.Bertero, INFN/TC-88/2 (1988)
+    //       V.B.Anykeyev et al., NIM A303 (1991) 350
+    //
+    Bool_t Bertero(TH1D &hb0)
+    {
+        // copy ideal distribution
+        
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+        
+
+        TMatrixD bold(fNb, 1);
+        bold.Zero();
+
+        //----------------------------------------------------------
+
+        Double_t db2 = 1.e20;
+
+
+        TMatrixD aminusaest(fNa, 1);
+
+        //-------   scan number of iterations   -----------------
+
+        cout << "Bertero : start loop over number of iterations" << endl;
+
+        Int_t ix;
+
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+            // calculate solution for the iteration number xiter
+            BertCore(xiter);
+
+            // calculate difference between ideal and unfolded distribution
+            Double_t D2bar = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                D2bar += temp*temp;
+            }
+
+            SpAR(ix)   = SpurAR;
+            SpSig(ix)  = SpurSigma;
+            chisq(ix)  = Chisq;
+            SecDer(ix) = SecDeriv;
+            ZerDer(ix) = ZerDeriv;
+            Entrop(ix) = Entropy;
+            DAR2(ix)   = DiffAR2;
+            Dsqbar(ix) = D2bar;
+
+            db2 = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-bold(i,0);
+                db2 += temp*temp;
+            }
+            bold = fVb;
+
+            //if (db2 < Epsdb2) break;
+
+        }
+
+        cout << "Bertero : end of loop over number of iterations" << endl;
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+            Int_t bin;
+            bin = hBchisq->FindBin( log10(xiter) );
+            hBchisq->SetBinContent(bin,chisq(ix));
+            hBSpAR->SetBinContent(bin,SpAR(ix));
+            hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+            hBSecDeriv->SetBinContent(bin,SecDer(ix));
+            hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+            hBEntropy->SetBinContent(bin,Entrop(ix));
+            hBDAR2->SetBinContent(bin,DAR2(ix));
+            hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+            if (ix > 0)
+            {
+                Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                hBDSpAR->SetBinContent(bin,DSpAR);
+
+                Double_t diff = SpSig(ix) - SpSig(ix-1);
+                Double_t DSpSig = diff;
+                hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                hBDEntropy->SetBinContent(bin,DEntrop);
+
+                Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                hBDZerDeriv->SetBinContent(bin,DZerDer);
+            }
+        }
+        //-------   end of scan of number of iterations   -----------------
+
+        // Select best weight
+        SelectBestWeight();
+
+
+        if (ixbest < 0.0)
+        {
+            cout << "Bertero : weight iteration has NOT converged; " << endl;
+            return kFALSE;
+        }
+
+        cout << "Bertero : weight iteration has converged; " << endl;
+        cout << "            ixbest = " << ixbest << endl;
+
+
+        // do a final unfolding using the best weight
+
+        // calculate solution for the iteration number xiter
+        Double_t xiter = pow(10.0,log10(xmin)+ixbest*dlogx);
+        BertCore(xiter);
+
+        cout << "Bertero : Values for best weight " << endl;
+        cout << "=================================" << endl;
+        cout << "fW, ixbest, Chisq, SpurAR, SpurSigma, SecDeriv, ZerDeriv, Entrop, DiffAR2, D2bar = " << endl;
+        cout << "      " << fW << ",  " << ixbest << ",  "
+            << Chisq << ",  " << SpurAR << ",  "
+            << SpurSigma << ",  " << SecDeriv << ",  " << ZerDeriv << ",  "
+            << Entropy << ",  " << DiffAR2 << ",  "
+            << Dsqbar(ixbest) << endl;
+
+        //----------------
+
+        fNdf   = SpurAR;
+        fChisq = Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          fChi2(i,0) = Chi2(i,0);
+	}
+
+        UInt_t iNdf   = (UInt_t) (fNdf+0.5);
+        fProb = iNdf>0 ? TMath::Prob(fChisq, iNdf) : 0;
+
+
+        fResult.ResizeTo(fNb, 5);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            fResult(i, 0) = fVb(i,0);
+            fResult(i, 1) = sqrt(fVbcov(i,i));
+            fResult(i, 2) = 0.0;
+            fResult(i, 3) = 0.0;
+            fResult(i, 4) = 1.0;
+        }
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // main part of Bertero's calculations
+    //
+    Bool_t BertCore(Double_t &xiter)
+    {
+        // ignore eigen values which are smaller than EpsLambda
+        TMatrixD G_inv(fNa, fNa);
+        TMatrixD Gtil_inv(fNa, fNa);
+        TMatrixD atil(fNb, fNa);
+        TMatrixD aminusaest(fNa, 1);
+
+        G_inv.Zero();
+        Gtil_inv.Zero();
+        SpurAR = 0.0;
+
+        // -----   loop over eigen values   ------------------
+        // calculate the approximate inverse of the matrix G
+        //cout << "flaml = " << endl;
+
+        UInt_t flagstart = 2;
+        Double_t flaml=0;
+
+        for (UInt_t l=0; l<fNa; l++)
+        {
+            if (EigenValue(l) < EpsLambda)
+                continue;
+
+            switch (flagstart)
+            {
+            case 1 :
+                // This is the expression for f(lambda) if the initial C^(0)
+                // is chosen to be zero
+                flaml = 1.0 - pow(1.0-tau*EigenValue(l),xiter);
+                break;
+
+            case 2 :
+                // This is the expression for f(lambda) if the initial C^(0)
+                // is chosen to be equal to the measured distribution
+                flaml =           1.0 - pow(1.0-tau*EigenValue(l),xiter)
+                    + EigenValue(l) * pow(1.0-tau*EigenValue(l),xiter);
+                break;
+            }
+
+            //  cout << flaml << ",  ";
+
+            for (UInt_t m=0; m<fNa; m++)
+            {
+                for (UInt_t n=0; n<fNa; n++)
+                {
+                    G_inv(m,n)    += 1.0  /EigenValue(l) * Eigen(m,l)*Eigen(n,l);
+                    Gtil_inv(m,n) += flaml/EigenValue(l) * Eigen(m,l)*Eigen(n,l);
+                }
+            }
+            SpurAR += flaml;
+        }
+        //cout << endl;
+
+
+        //cout << "Gtil_inv =" << endl;
+        //for (Int_t m=0; m<fNa; m++)
+        //{
+        //  for (Int_t n=0; n<fNa; n++)
+        //  {
+        //    cout << Gtil_inv(m,n) << ",  ";
+        //  }
+        //  cout << endl;
+        //}
+
+        //-----------------------------------------------------
+        // calculate the unfolded distribution b
+        TMatrixD v2(fMigrat, TMatrixD::kTransposeMult, Gtil_inv);
+        atil = v2;
+        TMatrixD v4(atil, TMatrixD::kMult, fVa);
+        fVb = v4;
+
+        //-----------------------------------------------------
+        // calculate AR and AR+
+        TMatrixD AR(v2, TMatrixD::kMult, fMigrat);
+
+        TMatrixD v3(fMigrat, TMatrixD::kTransposeMult, G_inv);
+        TMatrixD ARplus(v3, TMatrixD::kMult, fMigrat);
+
+
+        //-----------------------------------------------------
+        // calculate the norm |AR - AR+|**2
+
+        DiffAR2 = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            for (UInt_t k=0; k<fNb; k++)
+            {
+                Double_t tempo = AR(j,k) - ARplus(j,k);
+                DiffAR2       += tempo*tempo;
+            }
+        }
+
+        //-----------------------------------------------------
+        // calculate the second derivative squared
+
+        SecDeriv = 0;
+        for (UInt_t j=1; j<(fNb-1); j++)
+        {
+            // temp = ( 2.0*fVb(j,0)-fVb(j-1,0)-fVb(j+1,0) ) / ( 2.0*fVb(j,0) );
+            Double_t temp =    2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+                - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+            SecDeriv += temp*temp;
+        }
+
+        ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+
+        Double_t sumb = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+            sumb += fVb(j,0);
+
+        TMatrixD p(fNb,1);
+        p = fVb;
+        if (sumb > 0.0)
+            p *= 1.0/sumb;
+
+        Entropy = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            if (p(j,0) > 0.0)
+                Entropy += p(j,0) * log( p(j,0) );
+
+        //-----------------------------------------------------
+
+        TMatrixD Gb(fMigrat, TMatrixD::kMult, fVb);
+        aminusaest = fVa;
+        aminusaest -= Gb;
+    
+        TMatrixD v1(1,fNa);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            v1(0,i) = 0.0;
+            for (UInt_t j=0; j<fNa; j++)
+                v1(0,i) += aminusaest(j,0) * fVacovInv(j,i) ;
+        }
+
+        //-----------------------------------------------------
+        // calculate error matrix fVbcov of unfolded distribution
+        SpurSigma = CalcSpurSigma(atil);
+
+        //-----------------------------------------------------
+        // calculate the chi squared
+        for (UInt_t i = 0; i<fNa; i++)
+            Chi2(i,0) = v1(0,i) * aminusaest(i,0);
+
+        Chisq = GetMatrixSumCol(Chi2,0);
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Calculate the matrix G = M * M(transposed)
+    //           and its eigen values and eigen vectors
+    //
+    Bool_t CalculateG()
+    {
+        // Calculate matrix G = M*M(transposed)     (M = migration matrix)
+        //           the matrix Eigen of the eigen vectors of G
+        //           the vector EigenValues of the eigen values of G
+        //           the parameter tau = 1/lambda_max
+        //
+        TMatrixD v5(TMatrixD::kTransposed, fMigrat);
+        //TMatrixD G(fMigrat, TMatrixD::kMult, v5);
+        G.Mult(fMigrat, v5);
+
+        Eigen = G.EigenVectors(EigenValue);
+
+        RankG = 0.0;
+        for (UInt_t l=0; l<fNa; l++)
+        {
+            if (EigenValue(l) < EpsLambda) continue;
+            RankG += 1.0;
+        }
+
+        tau = 1.0 / EigenValue(0);
+
+        //  cout << "eigen values : " << endl;
+        //  for (Int_t i=0; i<fNa; i++)
+        //  {
+        //    cout << EigenValue(i) << ",  ";
+        //  }
+        //  cout << endl;
+
+        //cout << "eigen vectors : " << endl;
+        //for (Int_t i=0; i<fNa; i++)
+        //{
+        //  cout << "               vector " << i << endl;
+        //  for (Int_t j=0; j<fNa; j++)
+        //  {
+        //    cout << Eigen(j,i) << ",  ";
+        //  }
+        //  cout << endl;
+        //}
+        //cout << endl;
+
+        //cout << "G =" << endl;
+        //for (Int_t m=0; m<fNa; m++)
+        //{
+        //  for (Int_t n=0; n<fNa; n++)
+        //  {
+        //    cout << G(m,n) << ",  ";
+        //  }
+        //  cout << endl;
+        //}
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Select the best weight
+    //
+    Bool_t SelectBestWeight()
+    {
+        //-------------------------------
+        // select 'best' weight according to some criterion
+
+        Int_t ix;
+
+        Double_t DiffSpSigmax = -1.e10;
+        Int_t    ixDiffSpSigmax = -1;
+
+        Double_t DiffSigpointsmin = 1.e10;
+        Int_t    ixDiffSigpointsmin = -1;
+
+        Double_t DiffRankGmin = 1.e10;
+        Int_t    ixDiffRankGmin = -1;
+
+        Double_t D2barmin = 1.e10;
+        Int_t    ixD2barmin = -1;
+
+        Double_t DiffSpSig1min = 1.e10;
+        Int_t    ixDiffSpSig1min = -1;
+
+
+        Int_t ixmax = -1;
+
+        // first loop over all weights :
+        //       find smallest chi2
+        Double_t chisqmin = 1.e20;
+        for (ix=0; ix<Nix; ix++)
+        {
+            // consider only weights for which
+            //  - unfolding was successful
+            if (chisq(ix) != 0.0)
+            {
+                if (chisq(ix) < chisqmin)
+                    chisqmin = chisq(ix);
+            }
+        }
+        Double_t chisq0 = chisqmin > fVapoints ? chisqmin : fVapoints/2.0;
+
+        // second loop over all weights :
+        //        consider only weights for which chisq(ix) < chisq0
+        ixbest = -1;
+        for (ix=0; ix<Nix; ix++)
+        {
+            if (chisq(ix) != 0.0 && chisq(ix) < 2.0*chisq0)
+            {
+                // ixmax = highest weight with successful unfolding
+                //         (Least squares solution)
+                ixmax = ix;
+
+                SpurSigma = SpSig(ix);
+                SpurAR    = SpAR(ix);
+                Chisq    = chisq(ix);
+                D2bar     = Dsqbar(ix);
+
+                //----------------------------------
+                // search weight where SpurSigma changes most
+                //                               (as a function of the weight)
+                if (ix > 0  &&  chisq(ix-1) != 0.0)
+                {
+                    Double_t diff = SpSig(ix) - SpSig(ix-1);
+                    if (diff > DiffSpSigmax)
+                    {
+                        DiffSpSigmax   = diff;
+                        ixDiffSpSigmax = ix;
+                    }
+                }
+
+                //----------------------------------
+                // search weight where Chisq is close
+                //        to the number of significant measurements
+                Double_t DiffSigpoints = fabs(Chisq-fVapoints);
+
+                if (DiffSigpoints < DiffSigpointsmin)
+                {
+                    DiffSigpointsmin   = DiffSigpoints;
+                    ixDiffSigpointsmin = ix;
+                }
+
+                //----------------------------------
+                // search weight where Chisq is close
+                //        to the rank of matrix G
+                Double_t DiffRankG = fabs(Chisq-RankG);
+
+                if (DiffRankG < DiffRankGmin)
+                {
+                    DiffRankGmin   = DiffRankG;
+                    ixDiffRankGmin = ix;
+                }
+
+                //----------------------------------
+                // search weight where SpurSigma is close to 1.0
+                Double_t DiffSpSig1 = fabs(SpurSigma/fSpurVacov-1.0);
+
+                if (DiffSpSig1 < DiffSpSig1min)
+                {
+                    DiffSpSig1min   = DiffSpSig1;
+                    ixDiffSpSig1min = ix;
+                }
+
+                //----------------------------------
+                // search weight where D2bar is minimal
+
+                if (D2bar < D2barmin)
+                {
+                    D2barmin   = D2bar;
+                    ixD2barmin = ix;
+                }
+
+                //----------------------------------
+            }
+        }
+
+
+        // choose solution where increase of SpurSigma is biggest
+        //if ( DiffSpSigmax > 0.0)
+        //  ixbest = ixDiffSpSigmax;
+        //else
+        //  ixbest = ixDiffSigpointsmin;
+
+        // choose Least Squares Solution
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+        // ixbest = ixmax;
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+        // choose weight where chi2 is close to the number of significant
+        // measurements
+        // ixbest = ixDiffSigpointsmin;
+
+        // choose weight where chi2 is close to the rank of matrix G
+        // ixbest = ixDiffRankGmin;
+
+        // choose weight where chi2 is close to the rank of matrix G
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+           ixbest = ixDiffSpSig1min;
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+        cout << "SelectBestWeight : ixDiffSpSigmax, DiffSpSigmax = "
+            << ixDiffSpSigmax << ",  " << DiffSpSigmax << endl;
+        cout << "================== ixDiffSigpointsmin, DiffSigpointsmin = "
+            << ixDiffSigpointsmin << ",  " << DiffSigpointsmin << endl;
+
+        cout << "                   ixDiffRankGmin, DiffRankGmin = "
+            << ixDiffRankGmin << ",  " << DiffRankGmin << endl;
+
+        cout << "                   ixDiffSpSig1min, DiffSpSig1min = "
+            << ixDiffSpSig1min << ",  " << DiffSpSig1min << endl;
+
+        cout << "                   ixD2barmin, D2barmin = "
+            << ixD2barmin << ",  " << D2barmin << endl;
+        cout << "                   ixmax  = " << ixmax  << endl;
+        cout << "                   ixbest = " << ixbest << endl;
+
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Draw the plots
+    //
+    Bool_t DrawPlots()
+    {
+
+        // in the plots, mark the weight which has been selected
+        Double_t xbin = log10(xmin)+ixbest*dlogx;
+
+        TMarker *m = new TMarker();
+        m->SetMarkerSize(1);
+        m->SetMarkerStyle(20);
+
+        //-------------------------------------
+        // draw the iteration plots
+        TString ctitle = bintitle;
+        ctitle += "Plots versus weight";
+        TCanvas *c = new TCanvas("iter", ctitle, 900, 600);
+        c->Divide(3,2);
+
+        c->cd(1);
+        hBchisq->Draw();
+        gPad->SetLogy();
+        hBchisq->SetXTitle("log10(iteration number)");
+        hBchisq->SetYTitle("chisq");
+        m->DrawMarker(xbin, log10(chisq(ixbest)));
+
+        c->cd(2);
+        hBD2bar->Draw();
+        gPad->SetLogy();
+        hBD2bar->SetXTitle("log10(iteration number)");
+        hBD2bar->SetYTitle("(b_unfolded-b_ideal)**2");
+        m->DrawMarker(xbin, log10(Dsqbar(ixbest)));
+
+        /*
+         c->cd(3);
+         hBDAR2->Draw();
+         gPad->SetLogy();
+         strgx = "log10(iteration number)";
+         strgy = "norm(AR-AR+)";
+         hBDAR2->SetXTitle(strgx);
+         hBDAR2->SetYTitle(strgy);
+         m->DrawMarker(xbin, log10(DAR2(ixbest)));
+         */
+
+        c->cd(3);
+        hBSecDeriv->Draw();
+        hBSecDeriv->SetXTitle("log10(iteration number)");
+        hBSecDeriv->SetYTitle("Second Derivative squared");
+        m->DrawMarker(xbin, SecDer(ixbest));
+
+        /*
+         c->cd(8);
+         hBDSecDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Second Derivative squared)";
+         hBDSecDeriv->SetXTitle(strgx);
+         hBDSecDeriv->SetYTitle(strgy);
+         */
+
+        /*
+         c->cd(4);
+         hBZerDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Zero Derivative squared";
+         hBZerDeriv->SetXTitle(strgx);
+         hBZerDeriv->SetYTitle(strgy);
+         m->DrawMarker(xbin, ZerDer(ixbest));
+         */
+
+        /*
+         c->cd(5);
+         hBDZerDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Zero Derivative squared)";
+         hBDZerDeriv->SetXTitle(strgx);
+         hBDZerDeriv->SetYTitle(strgy);
+         */
+
+        c->cd(4);
+        hBSpAR->Draw();
+        hBSpAR->SetXTitle("log10(iteration number)");
+        hBSpAR->SetYTitle("SpurAR");
+        m->DrawMarker(xbin, SpAR(ixbest));
+
+
+        /*
+         c->cd(11);
+         hBDSpAR->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(SpurAR)";
+         hBDSpAR->SetXTitle(strgx);
+         hBDSpAR->SetYTitle(strgy);
+         */
+
+        c->cd(5);
+        hBSpSig->Draw();
+        hBSpSig->SetXTitle("log10(iteration number)");
+        hBSpSig->SetYTitle("SpurSig/SpurC");
+        m->DrawMarker(xbin, SpSig(ixbest)/fSpurVacov);
+
+        /*
+         c->cd(14);
+         hBDSpSig->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(SpurSig/SpurC)";
+         hBDSpSig->SetXTitle(strgx);
+         hBDSpSig->SetYTitle(strgy);
+         */
+
+        c->cd(6);
+        hBEntropy->Draw();
+        hBEntropy->SetXTitle("log10(iteration number)");
+        hBEntropy->SetYTitle("Entropy");
+        m->DrawMarker(xbin, Entrop(ixbest));
+
+        /*
+         c->cd(17);
+         hBDEntropy->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Entropy)";
+         hBDEntropy->SetXTitle(strgx);
+         hBDEntropy->SetYTitle(strgy);
+         */
+
+        //-------------------------------------
+
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            fha->SetBinContent(i+1, fVa(i, 0)         );
+            fha->SetBinError  (i+1, sqrt(fVacov(i, i)));
+
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fhmig->SetBinContent(i+1, j+1, fMigOrig(i, j)           );
+                fhmig->SetBinError  (i+1, j+1, sqrt(fMigOrigerr2(i, j)) );
+
+                shmig->SetBinContent(i+1, j+1, fMigrat(i, j)           );
+                shmig->SetBinError  (i+1, j+1, sqrt(fMigraterr2(i, j)) );
+                shmigChi2->SetBinContent(i+1, j+1, fMigChi2(i, j)   );
+            }
+        }
+
+        //PrintTH2Content(*shmig);
+        //PrintTH2Content(*shmigChi2);
+
+        //-------------------------------------
+        CopyCol(*hprior, fVEps);
+        CopyCol(*hb,     fVb);
+        for (UInt_t i=0; i<fNb; i++)
+            hb->SetBinError(i+1, sqrt(fVbcov(i, i)));
+
+        PrintTH1Content(*hb);
+        PrintTH1Error(*hb);
+
+        //..............................................
+        for (UInt_t i=0; i<fNa; i++)
+            hEigen->SetBinContent(i+1, EigenValue(i));
+
+        //..............................................
+        // draw the plots
+        TString cctitle = bintitle;
+        cctitle +=  "Unfolding input";
+        TCanvas *cc = new TCanvas("input", cctitle, 900, 600);
+        cc->Divide(3, 2);
+
+        // distribution to be unfolded
+        cc->cd(1);
+        fha->Draw();
+        gPad->SetLogy();
+        fha->SetXTitle("log10(E-est/GeV)");
+        fha->SetYTitle("Counts");
+
+        // superimpose unfolded distribution
+        // hb->Draw("*HSAME");
+
+        // prior distribution
+        cc->cd(2);
+        hprior->Draw();
+        gPad->SetLogy();
+        hprior->SetXTitle("log10(E-true/GeV)");
+        hprior->SetYTitle("Counts");
+
+        // migration matrix
+        cc->cd(3);
+        fhmig->Draw("box");
+        fhmig->SetXTitle("log10(E-est/GeV)");
+        fhmig->SetYTitle("log10(E-true/GeV)");
+
+        // smoothed migration matrix
+        cc->cd(4);
+        shmig->Draw("box");
+        shmig->SetXTitle("log10(E-est/GeV)");
+        shmig->SetYTitle("log10(E-true/GeV)");
+
+        // chi2 contributions for smoothing
+        cc->cd(5);
+        shmigChi2->Draw("box");
+        shmigChi2->SetXTitle("log10(E-est/GeV)");
+        shmigChi2->SetYTitle("log10(E-true/GeV)");
+
+        // Eigenvalues of matrix M*M(transposed)
+        cc->cd(6);
+        hEigen->Draw();
+        hEigen->SetXTitle("l");
+        hEigen->SetYTitle("Eigen values Lambda_l of M*M(transposed)");
+
+
+       //..............................................
+        // draw the results
+        TString crtitle = bintitle;
+        crtitle +=  "Unfolding results";
+        TCanvas *cr = new TCanvas("results", crtitle, 600, 600);
+        cr->Divide(2, 2);
+
+        // unfolded distribution
+        cr->cd(1);
+        hb->Draw();
+        gPad->SetLogy();
+        hb->SetXTitle("log10(E-true/GeV)");
+        hb->SetYTitle("Counts");
+
+	
+        // covariance matrix of unfolded distribution
+        cr->cd(2);
+        TH1 *hbcov=DrawMatrixClone(fVbcov, "lego");
+        hbcov->SetBins(fNb, hb->GetBinLowEdge(1), hb->GetBinLowEdge(fNb+1),
+                       fNb, hb->GetBinLowEdge(1), hb->GetBinLowEdge(fNb+1));
+
+        hbcov->SetName("hbcov");
+        hbcov->SetTitle("Error matrix of distribution hb");
+        hbcov->SetXTitle("log10(E-true/GeV)");
+        hbcov->SetYTitle("log10(E-true/GeV)");
+       
+	
+        // chi2 contributions
+        cr->cd(3);
+        TH1 *hchi2=DrawMatrixColClone(fChi2);
+        hchi2->SetBins(fNa, fha->GetBinLowEdge(1), fha->GetBinLowEdge(fNa+1));
+
+        hchi2->SetName("Chi2");
+        hchi2->SetTitle("chi2 contributions");
+        hchi2->SetXTitle("log10(E-est/GeV)");
+        hchi2->SetYTitle("Chisquared");
+	
+	
+        // ideal distribution
+        
+        cr->cd(4);
+        fhb0->Draw();
+        gPad->SetLogy();
+        fhb0->SetXTitle("log10(E-true/GeV)");
+        fhb0->SetYTitle("Counts");
+        
+
+        // superimpose unfolded distribution
+        hb->Draw("*Hsame");
+	
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Interface to MINUIT
+    //
+    //
+    Bool_t CallMinuit(
+                      void (*fcnx)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t),
+                      UInt_t npar, char name[20][100],
+                      Double_t vinit[20], Double_t step[20],
+                      Double_t limlo[20], Double_t limup[20], Int_t fix[20])
+    {
+        //
+        // Be carefull: This is not thread safe
+        //
+        UInt_t maxpar = 100;
+
+        if (npar > maxpar)
+        {
+            cout << "MUnfold::CallMinuit : too many parameters,  npar = " << fNb
+                << ",   maxpar = " << maxpar << endl;
+            return kFALSE;
+        }
+
+        //..............................................
+        // Set the maximum number of parameters
+        TMinuit minuit(maxpar);
+
+
+        //..............................................
+        // Set the print level
+        // -1   no output except SHOW comands
+        //  0   minimum output
+        //  1   normal output (default)
+        //  2   additional ouput giving intermediate results
+        //  3   maximum output, showing progress of minimizations
+        //
+        Int_t printLevel = -1;
+        minuit.SetPrintLevel(printLevel);
+
+        //..............................................       
+        // Printout for warnings
+        //    SET WAR      print warnings
+        //    SET NOW      suppress warnings
+        Int_t errWarn;
+        Double_t tmpwar = 0;
+        minuit.mnexcm("SET NOW", &tmpwar, 0, errWarn);
+
+        //..............................................
+        // Set the address of the minimization function
+        minuit.SetFCN(fcnx);
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+        for (UInt_t i=0; i<npar; i++)
+        {
+            if (minuit.DefineParameter(i, &name[i][0], vinit[i], step[i],
+                                       limlo[i], limup[i]))
+            {
+                cout << "MUnfold::CallMinuit: Error in defining parameter "
+                    << name << endl;
+                return kFALSE;
+            }
+        }
+
+        //..............................................
+        //Int_t NumPars = minuit.GetNumPars();
+        //cout << "MUnfold::CallMinuit :  number of free parameters = "
+        //     << NumPars << endl;
+
+        //..............................................
+        // Minimization
+        minuit.SetObjectFit(this);
+
+        //..............................................
+        // Error definition :
+        //
+        //    for chisquare function :
+        //      up = 1.0   means calculate 1-standard deviation error
+        //         = 4.0   means calculate 2-standard deviation error
+        //
+        //    for log(likelihood) function :
+        //      up = 0.5   means calculate 1-standard deviation error
+        //         = 2.0   means calculate 2-standard deviation error
+        Double_t up = 1.0;
+        minuit.SetErrorDef(up);
+
+
+
+        // Int_t errMigrad;
+        // Double_t tmp = 0;
+        // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+
+        //..............................................
+        // fix a parameter
+        for (UInt_t i=0; i<npar; i++)
+        {
+            if (fix[i] > 0)
+            {
+                Int_t parNo = i;
+                minuit.FixParameter(parNo);
+            }
+        }
+
+        //..............................................
+        // Set maximum number of iterations (default = 500)
+        Int_t maxiter = 100000;
+        minuit.SetMaxIterations(maxiter);
+
+        //..............................................
+        // minimization by the method of Migrad
+        // Int_t errMigrad;
+        // Double_t tmp = 0;
+        // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+        //..............................................       
+        // same minimization as by Migrad
+        // but switches to the SIMPLEX method if MIGRAD fails to converge
+        Int_t errMinimize;
+        Double_t tmp = 0;
+        minuit.mnexcm("MINIMIZE", &tmp, 0, errMinimize);
+
+        //..............................................       
+        // check quality of minimization
+        // istat = 0   covariance matrix not calculated
+        //         1   diagonal approximation only (not accurate)
+        //         2   full matrix, but forced positive-definite
+        //         3   full accurate covariance matrix 
+        //             (indication of normal convergence)
+        Double_t fmin, fedm, errdef;
+        Int_t    npari, nparx, istat;
+        minuit.mnstat(fmin, fedm, errdef, npari, nparx, istat);
+
+        if (errMinimize || istat < 3)
+        {
+            cout << "MUnfold::CallMinuit : Minimization failed" << endl;
+            cout << "       fmin = " << fmin   << ",   fedm = "  << fedm
+                << ",   errdef = "  << errdef << ",   istat = " << istat
+                << endl;
+            return kFALSE;
+        }
+
+        //..............................................
+        // Minos error analysis
+        // minuit.mnmnos();
+
+        //..............................................       
+        // Print current status of minimization
+        // if nkode = 0    only function value
+        //            1    parameter values, errors, limits
+        //            2    values, errors, step sizes, internal values
+        //            3    values, errors, step sizes, 1st derivatives
+        //            4    values, paraboloc errors, MINOS errors
+  
+        //Int_t nkode = 4;
+        //minuit.mnprin(nkode, fmin);
+
+        //..............................................       
+        // call fcn with IFLAG = 3 (final calculation : calculate p(chi2))
+        // iflag = 1   initial calculations only
+        //         2   calculate 1st derivatives and function
+        //         3   calculate function only
+        //         4   calculate function + final calculations
+        const char *command = "CALL";
+        Double_t iflag = 3;
+        Int_t errfcn3;
+        minuit.mnexcm(command, &iflag, 1, errfcn3); 
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the unfolded distribution
+    //
+    TMatrixD &GetVb() { return fVb; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the covariance matrix of the unfolded distribution
+    //
+    TMatrixD &GetVbcov() { return fVbcov; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the unfolded distribution + various errors
+    //
+    TMatrixD &GetResult() { return fResult; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the chisquared contributions
+    //
+    TMatrixD &GetChi2() { return fChi2; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the total chisquared
+    //
+    Double_t &GetChisq() { return fChisq; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the number of degrees of freedom
+    //
+    Double_t &GetNdf() { return fNdf; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the chisquared probability
+    //
+    Double_t &GetProb() { return fProb; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the smoothed migration matrix
+    //
+    TMatrixD &GetMigSmoo() { return fMigSmoo; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the error2 of the smoothed migration matrix
+    //
+    TMatrixD &GetMigSmooerr2() { return fMigSmooerr2; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the chi2 contributions for the smoothing
+    //
+    TMatrixD &GetMigChi2() { return fMigChi2; }
+};
+// end of definition of class MUnfold
+///////////////////////////////////////////////////
+
+
+// -----------------------------------------------------------------------
+//
+// fcnSmooth     (used by SmoothMigrationMatrix)
+//
+// is called by MINUIT
+// for given values of the parameters it calculates the function 
+//                                               to be minimized
+//
+void fcnSmooth(Int_t &npar, Double_t *gin, Double_t &f, 
+               Double_t *par, Int_t iflag)
+{
+    MUnfold &gUnfold = *(MUnfold*)gMinuit->GetObjectFit();
+
+    Double_t a0 = par[0];
+    Double_t a1 = par[1];
+    Double_t a2 = par[2];
+
+    Double_t b0 = par[3];
+    Double_t b1 = par[4];
+    Double_t b2 = par[5];
+
+    // loop over bins of log10(E-true)
+    Double_t chi2 = 0.0;
+    Int_t npoints = 0;
+    Double_t func[20];
+
+    for (UInt_t j=0; j<gUnfold.fNb; j++)
+    {
+        Double_t yj   = ((double)j) + 0.5;
+        Double_t mean = a0 + a1*yj + a2*yj*yj + yj;
+        Double_t RMS  = b0 + b1*yj + b2*yj*yj;
+
+        if (RMS <= 0.0)
+        {
+            chi2 = 1.e20;
+            break;
+        }
+
+        // loop over bins of log10(E-est)
+
+        //.......................................
+        Double_t function;
+        Double_t sum=0.0;
+        for (UInt_t i=0; i<gUnfold.fNa; i++)
+        {
+            Double_t xlow = (double)i;
+            Double_t xup  = xlow + 1.0;
+            Double_t xl  = (xlow- mean) / RMS;
+            Double_t xu  = (xup - mean) / RMS;
+            function = (TMath::Freq(xu) - TMath::Freq(xl));
+
+            //cout << "i, xl, xu, function = " <<  i <<  ",  "  << xl << ",  "
+            //     << xu  << ",  " << function << endl;
+
+            if (function < 1.e-10)
+                function = 0.0;
+
+            func[i] = function;
+            sum += function;
+        }
+
+        //      cout << "mean, RMS = "  << mean << ",  " << RMS
+        //     << ",   j , sum of function = " << j << ",  " << sum << endl;
+
+        //.......................................
+
+        for (UInt_t i=0; i<gUnfold.fNa; i++)
+        {
+            if (sum != 0.0)
+                func[i] /= sum;
+
+            gUnfold.fMigSmoo(i,j) = func[i];
+            gUnfold.fMigChi2(i,j) = 0.0;
+
+            // if relative error is greater than 30 % ignore the point
+
+            if (gUnfold.fMigOrig(i,j)     != 0 &&
+                gUnfold.fMigOrigerr2(i,j) != 0 &&
+                func[i] != 0  )
+            {
+                if (gUnfold.fMigOrigerr2(i,j)/
+                    (gUnfold.fMigOrig(i,j)*gUnfold.fMigOrig(i,j)) <= 0.09)
+                {
+                    gUnfold.fMigChi2(i,j) =   ( gUnfold.fMigOrig(i,j) - func[i] )
+                        * ( gUnfold.fMigOrig(i,j) - func[i] )
+                        /   gUnfold.fMigOrigerr2(i,j);
+                    chi2 += gUnfold.fMigChi2(i,j);
+                    npoints += 1;
+                }
+            }
+        }
+        //.......................................
+
+    }
+    f = chi2;
+
+    //cout << "fcnSmooth : f = " << f << endl;
+
+    //--------------------------------------------------------------------
+    // final calculations
+    if (iflag == 3)
+    {
+        Int_t     NDF = npoints - npar;
+        Double_t prob = TMath::Prob(chi2, NDF);
+
+        cout << "fcnSmooth : npoints, chi2, NDF, prob = " << npoints << ",  ";
+        cout << chi2 << ",  " << NDF << ",  " << prob << endl;
+        cout << "=======================================" << endl;
+    }
+}
+
+// -----------------------------------------------------------------------
+//
+// fcnTikhonov2     (used by Tikhonov2)
+//
+// is called by MINUIT
+// for given values of the parameters it calculates the function F
+// the free parameters are the first (fNb-1) elements
+//                     of the normalized unfolded distribution
+//
+void fcnTikhonov2(Int_t &npar, Double_t *gin, Double_t &f,
+                  Double_t *par, Int_t iflag)
+{
+    MUnfold &gUnfold = *(MUnfold*)gMinuit->GetObjectFit();
+
+    // (npar+1) is the number of bins of the unfolded distribuition (fNb)
+    //  npar    is the number of free parameters                    (fNb-1)
+
+    UInt_t npar1 = npar + 1;
+
+    UInt_t fNa = gUnfold.fNa;
+    UInt_t fNb = gUnfold.fNb;
+    if (npar1 != fNb)
+    {
+        cout << "fcnTikhonov2 : inconsistency in number of parameters; npar, fNb = ";
+        cout << npar << ",  " << fNb << endl;
+        //return;
+    }
+    npar1 = fNb;
+
+    TMatrixD p(npar1, 1);
+    TMatrixD &fVb = gUnfold.fVb;
+
+    // p is the normalized unfolded distribution
+    // sum(p(i,0)) from i=0 to npar is equal to 1
+    Double_t sum = 0.0;
+    for (Int_t i=0; i<npar; i++)
+    {
+        p(i,0) = par[i];
+        sum += par[i];
+    }
+    p(npar,0) = 1.0 - sum;
+
+
+    // all p(i,0) have to be greater than zero
+    for (UInt_t i=0; i<npar1; i++)
+        if (p(i,0) <= 0.0)
+        {
+            f = 1.e20;
+            return;
+        }
+
+    //.......................
+    // take least squares result for the normaliztion
+    TMatrixD alpha(gUnfold.fMigrat, TMatrixD::kMult, p);
+
+    //TMatrixD v4   (gUnfold.fVa, TMatrixD::kTransposeMult,
+    //                                 gUnfold.fVacovInv);
+    //TMatrixD norma(v4,  TMatrixD::kMult, gUnfold.fVa);
+
+    TMatrixD v5   (alpha, TMatrixD::kTransposeMult, gUnfold.fVacovInv);
+    TMatrixD normb(v5,    TMatrixD::kMult, alpha);
+
+    TMatrixD normc(v5,    TMatrixD::kMult, gUnfold.fVa);
+
+    Double_t norm  = normc(0,0)/normb(0,0);
+
+    //.......................
+
+    // b is the unnormalized unfolded distribution
+    // sum(b(i,0)) from i=0 to npar is equal to norm
+    //                       (the total number of events)
+    for (UInt_t i=0; i<npar1; i++)
+        fVb(i,0) = p(i,0) * norm;
+
+    TMatrixD Gb(gUnfold.fMigrat, TMatrixD::kMult, fVb);
+    TMatrixD v3(fNa, 1);
+    v3 = gUnfold.fVa;
+    v3 -= Gb;
+
+    TMatrixD v1(1,fNa);
+    for (UInt_t i=0; i<fNa; i++)
+    {
+        v1(0,i) = 0;
+        for (UInt_t j=0; j<fNa; j++)
+            v1(0,i) += v3(j,0) * gUnfold.fVacovInv(j,i) ;
+    }
+
+    for (UInt_t i = 0; i<fNa; i++)
+        gUnfold.Chi2(i,0) = v1(0,i) * v3(i,0);
+
+    gUnfold.Chisq = GetMatrixSumCol(gUnfold.Chi2,0);
+
+    //-----------------------------------------------------
+    // calculate 2nd derivative squared
+    // regularization term (second derivative squared)
+    gUnfold.SecDeriv = 0;
+    for (UInt_t j=1; j<(fNb-1); j++)
+     {
+         const Double_t temp =
+             + 2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+             - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+
+         gUnfold.SecDeriv += temp*temp;
+     }
+
+    gUnfold.ZerDeriv = 0;
+    for (UInt_t j=0; j<fNb; j++)
+        gUnfold.ZerDeriv += fVb(j,0) * fVb(j,0);
+
+    f = gUnfold.Chisq/2 * gUnfold.fW + gUnfold.SecDeriv;
+
+    //cout << "F=" << f      << " \tSecDeriv=" << gUnfold.SecDeriv
+    //     << " \tchi2="
+    //	  << gUnfold.Chisq << " \tfW=" << gUnfold.fW << endl;
+
+    //--------------------------------------------------------------------
+    // final calculations
+    if (iflag == 3)
+    {
+        //..............................................
+        // calculate external error matrix of the fitted parameters 'val'
+        // extend it with the covariances for y=1-sum(val)
+        Double_t emat[20][20];
+        Int_t    ndim = 20;
+        gMinuit->mnemat(&emat[0][0], ndim);
+
+        Double_t covv = 0;
+        for (UInt_t i=0; i<(gUnfold.fNb-1); i++)
+        {
+            Double_t cov = 0;
+            for (UInt_t k=0; k<(gUnfold.fNb-1); k++)
+                cov += emat[i][k];
+
+            emat[i][gUnfold.fNb-1] = -cov;
+            emat[gUnfold.fNb-1][i] = -cov;
+
+            covv += cov;
+        }
+        emat[gUnfold.fNb-1][gUnfold.fNb-1] = covv;
+
+        for (UInt_t i=0; i<gUnfold.fNb; i++)
+            for (UInt_t k=0; k<gUnfold.fNb; k++)
+                gUnfold.fVbcov(i,k) = emat[i][k] *norm*norm;
+
+        //-----------------------------------------------------
+        //..............................................
+        // put unfolded distribution into fResult
+        //     fResult(i,0)   value in bin i
+        //     fResult(i,1)   error of value in bin i
+
+        gUnfold.fResult.ResizeTo(gUnfold.fNb, 5);
+
+        Double_t sum = 0;
+        for (UInt_t i=0; i<(gUnfold.fNb-1); i++)
+        {
+            Double_t val;
+            Double_t err;
+            if (!gMinuit->GetParameter(i, val, err))
+            {
+                cout << "Error getting parameter #" << i << endl;
+                return;
+            }
+
+            Double_t eplus;
+            Double_t eminus;
+            Double_t eparab;
+            Double_t gcc;
+            gMinuit->mnerrs(i, eplus, eminus, eparab, gcc);
+
+            gUnfold.fVb(i, 0)     = val    * norm;
+
+            gUnfold.fResult(i, 0) = val    * norm;
+            gUnfold.fResult(i, 1) = eparab * norm;
+            gUnfold.fResult(i, 2) = eplus  * norm;
+            gUnfold.fResult(i, 3) = eminus * norm;
+            gUnfold.fResult(i, 4) = gcc;
+            sum += val;
+        }
+        gUnfold.fVb(gUnfold.fNb-1, 0)     = (1.0-sum) * norm;
+
+        gUnfold.fResult(gUnfold.fNb-1, 0) = (1.0-sum) * norm;
+        gUnfold.fResult(gUnfold.fNb-1, 1) =
+            sqrt(gUnfold.fVbcov(gUnfold.fNb-1,gUnfold.fNb-1));
+        gUnfold.fResult(gUnfold.fNb-1, 2) = 0;
+        gUnfold.fResult(gUnfold.fNb-1, 3) = 0;
+        gUnfold.fResult(gUnfold.fNb-1, 4) = 1;
+        //..............................................
+
+        //-----------------------------------------------------
+        // calculate 0th derivative squared
+        gUnfold.ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            gUnfold.ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+
+        gUnfold.Entropy = 0;
+        for (UInt_t j=0; j<gUnfold.fNb; j++)
+            if (p(j,0) > 0)
+                gUnfold.Entropy += p(j,0) * log( p(j,0) );
+
+
+        //-----------------------------------------------------
+        // calculate SpurSigma
+        gUnfold.SpurSigma = 0.0;
+        for (UInt_t m=0; m<fNb; m++)
+            gUnfold.SpurSigma += gUnfold.fVbcov(m,m);
+        // cout << "SpurSigma =" << SpurSigma << endl;
+
+        //-----------------------------------------------------
+        gUnfold.SpurAR  = 0;
+        gUnfold.DiffAR2 = 0;
+
+        //-----------------------------------------------------
+        gUnfold.fNdf   = gUnfold.fNa;
+        gUnfold.fChisq   = gUnfold.Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          gUnfold.fChi2(i,0) = gUnfold.Chi2(i,0);
+	}
+
+
+        UInt_t iNdf = (UInt_t) (gUnfold.fNdf+0.5);
+
+        //cout << "fcnTikhonov2 : fW, chisq (from fcnF) = "
+        //     << gUnfold.fW << ",  " << gUnfold.fChisq << endl;
+
+        gUnfold.fProb = iNdf>0 ? TMath::Prob(gUnfold.fChisq, iNdf) : 0;
+    }
+}
+
+
+// ======================================================
+//
+// SteerUnfold
+//
+void SteerUnfold(TString bintitle,
+                 TH1D &ha,     TH2D &hacov, TH2D &hmig,
+                 TH2D &hmigor, TH1D &hb0,   TH1D *hpr,
+                 TH1D &hb)
+{
+    // ha      is the distribution to be unfolded
+    // hacov   is the covariance matrix of the distribution ha
+    // hmig    is the migration matrix;
+    //         it is used in the unfolding unless it is overwritten
+    //         by SmoothMigrationMatrix by the smoothed migration matrix
+    // hmigor  is the migration matrix to be smoothed;
+    //         the smoothed migration matrix will be used in the unfolding
+    // hpr     the prior distribution
+    //         it is only used if SetPriorInput(*hpr) is called   
+    // hb      unfolded distribution
+
+    //..............................................       
+    // create an MUnfold object;
+    // fill histograms into vectors and matrices
+
+    MUnfold unfold(ha, hacov, hmig);
+    unfold.bintitle = bintitle;
+
+    //..............................................       
+    // smooth the migration matrix;
+    //        the smoothed migration matrix will be used in the unfolding
+    //        hmig is the original (unsmoothed) migration matrix
+
+    unfold.SmoothMigrationMatrix(hmigor);
+
+    //..............................................       
+    // define prior distribution (has always to be defined) 
+    // the alternatives are  :
+
+    // 1  SetPriorConstant() :   isotropic distribution
+    // 2  SetPriorPower(gamma) : dN/dE = E^{-gamma}
+    // 3  SetPriorInput(*hpr):   the distribution *hpr is used 
+    // 4  SetPriorRebin(*ha) :   use rebinned histogram ha 
+
+    UInt_t flagprior = 4;
+    cout << "SteerUnfold : flagprior = " << flagprior << endl;
+    cout << "==========================="<< endl;
+
+    Bool_t errorprior=kTRUE;
+    switch (flagprior)
+    {
+    case 1:
+        unfold.SetPriorConstant();
+        break;
+    case 2:
+        errorprior = unfold.SetPriorPower(1.5);
+        break;
+    case 3:
+        if (!hpr)
+        {
+            cout << "Error: No hpr!" << endl;
+            return;
+        }
+        errorprior = unfold.SetPriorInput(*hpr);
+        break;
+    case 4:
+        errorprior = unfold.SetPriorRebin(ha);
+        break;
+    }
+    if (!errorprior)
+    {
+        cout << "MUnfold::SetPrior... : failed.  flagprior = " ;
+        cout << flagprior << endl;
+        return;
+    }
+
+    //..............................................       
+    // calculate the matrix G = M * M(transposed)
+    //           M being the migration matrix
+
+    unfold.CalculateG();
+
+    //..............................................       
+    // call steering routine for the actual unfolding;
+    // the alternatives are :
+
+    // 1  Schmelling : minimize the function Z by Gauss-Newton iteration;
+    //                 the parameters to be fitted are gamma(i) = lambda(i)/w;
+
+    // 2  Tikhonov2 :  regularization term is sum of (2nd deriv.)**2 ;
+    //                 minimization by using MINUIT;
+    //                 the parameters to be fitted are
+    //                 the bin contents of the unfolded distribution
+
+    // 3  Bertero:     minimization by iteration
+    //                 
+
+    UInt_t flagunfold = 1;
+    cout << "SteerUnfold : flagunfold = "  << flagunfold << endl;
+    cout << "============================" << endl;
+
+
+
+    switch (flagunfold)
+    {
+    case 1: // Schmelling
+        cout << "" << endl;
+        cout << "Unfolding algorithm : Schmelling" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Schmelling(hb0))
+            cout << "MUnfold::Schmelling : failed." << endl;
+        break;
+
+    case 2: // Tikhonov2
+        cout << "" << endl;
+        cout << "Unfolding algorithm :   Tikhonov" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Tikhonov2(hb0))
+            cout << "MUnfold::Tikhonov2 : failed." << endl;
+        break;
+
+    case 3: // Bertero
+        cout << "" << endl;
+        cout << "Unfolding algorithm :    Bertero" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Bertero(hb0))
+            cout << "MUnfold::Bertero : failed." << endl;
+        break;
+    }    
+
+
+    //..............................................       
+    // Print fResult
+    unfold.PrintResults();
+
+
+    //..............................................       
+    // Draw the plots
+    unfold.DrawPlots();
+
+    //..............................................       
+    // get unfolded distribution
+    TMatrixD &Vb    = unfold.GetVb();
+    TMatrixD &Vbcov = unfold.GetVbcov();
+
+    UInt_t fNb = unfold.fNb;
+
+    for (UInt_t a=0; a<fNb; a++)
+    {
+      hb.SetBinContent(a+1, Vb(a,0));
+      hb.SetBinError(a+1, sqrt(Vbcov(a, a)) );
+    }
+
+}
+
+//__________________________________________________________________________
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// doUnfolding    (to be called in the analysis)                          //
+//                                                                        //
+// arguments :                                                            //
+//                                                                        //
+//   INPUT                                                                //
+//      TH2D &tobeunfolded : no.of excess events and its error            //
+//                           vs. (E-est, Theta)                           //
+//      TH3D &migration    : migration matrix (E-est, E_true, Theta)      //
+//                                                                        //
+//   OUITPUT                                                              //
+//      TH2D &unfolded     : no.of excess events and its error            //
+//                           vs. (E-true, Theta)                          //
+//                                                                        //
+// calls SteerUnfold to do the unfolding                                  //
+//                                                                        //
+// The "Theta" axis is only used to loop over the bins of theta           //
+// and to do the unfolding for each bin of theta. Instead of theta        //
+// any other variable (or a dummy variable) may be used.                  //
+//                                                                        //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+
+void doUnfolding(TH2D &tobeunfolded, TH3D &migration, TH2D &unfolded)
+{
+  TAxis &taxis  = *tobeunfolded.GetYaxis();
+  Int_t numybins = taxis.GetNbins();
+
+  for (Int_t m=1; m<=numybins; m++)
+  {
+    TString bintitle = "Bin ";
+    bintitle += m;
+    bintitle += ": ";
+
+    // -----------------------------------------
+    // ha : distribution to be unfolded
+
+    TH1D &ha = *tobeunfolded.ProjectionX("", m, m, "e");
+    TString title = bintitle;
+    title += "E-est distr. to be unfolded";
+    ha.SetNameTitle("ha", title);
+    TAxis &aaxis = *ha.GetXaxis();
+    Int_t na = aaxis.GetNbins();
+    Double_t alow = aaxis.GetBinLowEdge(1);
+    Double_t aup  = aaxis.GetBinLowEdge(na+1);
+
+    PrintTH1Content(ha);
+    PrintTH1Error(ha);
+
+    // -----------------------------------------
+    // covariance matrix of the distribution ha
+
+    title = bintitle;
+    title +=  "Error matrix of distribution ha";
+    TH2D hacov("hacov", title, na, alow, aup, na, alow, aup);
+    //MH::SetBinning(&hacov, &aaxis, &aaxis); 
+
+    Double_t errmin = 3.0;
+    for (Int_t i=1; i<=na; i++)
+    {
+      for (Int_t j=1; j<=na; j++)
+      {
+        hacov.SetBinContent(i, j, 0.0);
+      }
+      const Double_t content = ha.GetBinContent(i);
+      const Double_t error2  = (ha.GetBinError(i))*(ha.GetBinError(i));
+      if (content <= errmin  &&  error2 < errmin) 
+        hacov.SetBinContent(i, i, errmin);
+      else
+        hacov.SetBinContent(i, i, error2);
+    }
+
+    //PrintTH2Content(hacov);
+    
+
+    // -----------------------------------------
+    // migration matrix :
+    //           x corresponds to measured quantity
+    //           y corresponds to true quantity
+    TH2D &hmig = *(TH2D*)migration.Project3D("yxe");
+    title = bintitle;
+    title += "Migration Matrix";
+    hmig.SetNameTitle("Migrat", title);
+
+    TAxis &aaxismig = *hmig.GetXaxis();
+    Int_t namig = aaxismig.GetNbins();
+
+    if (na != namig)
+    {
+      cout << "doUnfolding : binnings are incompatible; na, namig = "
+           << na << ",  " << namig << endl;
+      return;
+    }
+
+    TAxis &baxismig = *hmig.GetYaxis();
+    Int_t nbmig = baxismig.GetNbins();
+    Double_t blow = baxismig.GetBinLowEdge(1);
+    Double_t bup  = baxismig.GetBinLowEdge(nbmig+1);
+
+    PrintTH2Content(hmig);
+    //PrintTH2Error(hmig);
+
+
+    // -----------------------------------------
+    // dummy ideal distribution
+
+    Int_t nb = nbmig;
+
+    title = bintitle;
+    title += "Dummy Ideal distribution";
+    TH1D hb0("dummyhb0", title, nb, blow, bup);;
+    //MH::SetBinning(&hb0, &baxismig); 
+    hb0.Sumw2();
+
+    for (Int_t k=1; k<=nb; k++)
+    {
+        hb0.SetBinContent(k, 1.0/nb);
+        hb0.SetBinError  (k, 0.1/nb);
+    }
+
+    //PrintTH1Content(hb0);
+
+    // -----------------------------------------
+    // here the prior distribution can be defined for the call
+    // to SetPriorInput(*hpr)
+
+    title = bintitle;
+    title += "Dummy Prior distribution";
+    TH1D hpr("hpr", title, nb, blow, bup);
+    //MH::SetBinning(&hpr, &baxismig); 
+    
+    for (Int_t k=1; k<=nb; k++)
+        hpr.SetBinContent(k, 1.0/nb);
+
+    //PrintTH1Content(hpr);
+
+
+    // -----------------------------------------
+    // unfolded distribution
+
+
+    title = bintitle;
+    title += "Unfolded distribution";
+    TH1D hb("hb", title, nb, blow, bup);
+    //MH::SetBinning(&hb, &baxismig); 
+
+    // -----------------------------------------
+    SteerUnfold(bintitle, ha, hacov, hmig, hmig, hb0, &hpr, hb);
+
+    for (Int_t k=1; k<=nb; k++)
+    {
+      Double_t content = hb.GetBinContent(k);
+      Double_t error   = hb.GetBinError(k);
+
+      unfolded.SetBinContent(k, m, content);
+      unfolded.SetBinError(k, m, error);
+    }    
+
+    delete &ha;
+    delete &hmig;
+  }
+
+}
+//========================================================================//
+
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// Main program   (for testing purposes)                                  //
+//                                                                        //
+//                defines the ideal distribution          (hb0)           //
+//                defines the migration matrix            (hMigrat)       //
+//                defines the distribution to be unfolded (hVa)           //
+//                                                                        //
+//                calls doUnfolding                                       //
+//                      to do the unfolding                               //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+void fluxunfold()
+{
+  // -----------------------------------------
+  // migration matrix :
+  //           x corresponds to measured quantity
+  //           y corresponds to true quantity
+
+    const Int_t  na   =   13;
+    //const Int_t  na   =   18;
+    const Axis_t alow = 0.25;
+    const Axis_t aup  = 3.50;
+
+    const Int_t  nb   =   11;
+    //const Int_t  nb   =   22;
+    const Axis_t blow = 0.50;
+    const Axis_t bup  = 3.25;
+
+    const Int_t  nc   =     1;
+    const Axis_t clow =   0.0;
+    const Axis_t cup  =   1.0;
+
+    Int_t m = 1;
+
+    TH3D migration("migration", "Migration Matrix", 
+                   na, alow, aup, nb, blow, bup, nc, clow, cup);
+    migration.Sumw2();
+
+    // parametrize migration matrix as
+    //     <log10(Eest)>      = a0 + a1*log10(Etrue) + a2*log10(Etrue)**2 
+    //                             + log10(Etrue) 
+    //     RMS( log10(Eest) ) = b0 + b1*log10(Etrue) + b2*log10(Etrue)**2
+    Double_t a0 = 0.0;
+    Double_t a1 = 0.0;
+    Double_t a2 = 0.0;
+
+    Double_t b0 = 0.26;
+    Double_t b1 =-0.054;
+    Double_t b2 = 0.0;
+
+    TF1 f2("f2", "gaus(0)", alow, aup);
+    f2.SetParName(0, "ampl");
+    f2.SetParName(1, "mean");
+    f2.SetParName(2, "sigma");
+
+    // loop over log10(Etrue) bins
+    TAxis &yaxis = *migration.GetYaxis();
+    for (Int_t j=1; j<=nb; j++)
+    {
+        Double_t yvalue = yaxis.GetBinCenter(j);
+
+        const Double_t mean  = a0 + a1*yvalue + a2*yvalue*yvalue + yvalue;
+        const Double_t sigma = b0 + b1*yvalue + b2*yvalue*yvalue;
+        const Double_t ampl  = 1./ ( sigma*TMath::Sqrt(2.0*TMath::Pi()));
+
+        // gaus(0) is a substitute for [0]*exp( -0.5*( (x-[1])/[2] )**2 )
+        f2.SetParameter(0, ampl);
+        f2.SetParameter(1, mean);
+        f2.SetParameter(2, sigma);
+
+        // fill temporary 1-dim histogram with the function
+        // fill the histogram using
+        //    - either FillRandom
+        //    - or using Freq
+        TH1D htemp("temp", "temp", na, alow, aup);
+        htemp.Sumw2();
+
+        for (Int_t k=0; k<1000000; k++)
+            htemp.Fill(f2.GetRandom());
+
+        // copy it into the migration matrix
+        Double_t sum = 0;
+        for (Int_t i=1; i<=na; i++)
+        {
+            const Stat_t content = htemp.GetBinContent(i);
+            migration.SetBinContent(i, j, m, content);
+            sum += content;
+        }
+
+        // normalize migration matrix
+        if (sum==0)
+            continue;
+
+        for (Int_t i=1; i<=na; i++)
+        {
+            const Stat_t content = migration.GetBinContent(i,j,m);
+            migration.SetBinContent(i,j,m,       content/sum);
+            migration.SetBinError  (i,j,m, sqrt(content)/sum);
+        }
+    }
+
+    //PrintTH3Content(migration);
+    //PrintTH3Error(migration);
+
+    // -----------------------------------------
+    // ideal distribution
+
+    TH1D hb0("hb0", "Ideal distribution", nb, blow, bup);
+    hb0.Sumw2();
+
+    // fill histogram with random numbers according to 
+    // an exponential function dN/dE = E^{-gamma}
+    //    or with y = log10(E), E = 10^y :             
+    //                          dN/dy = ln10 * 10^{y*(1-gamma)}     
+    TF1 f1("f1", "pow(10.0, x*(1.0-[0]))", blow, bup);
+    f1.SetParName(0,"gamma");
+    f1.SetParameter(0, 2.7);
+
+    // ntimes is the number of entries
+    for (Int_t k=0; k<10000; k++)
+        hb0.Fill(f1.GetRandom());
+
+    // introduce energy threshold at 50 GeV
+
+    const Double_t  lgEth = 1.70;
+    const Double_t dlgEth = 0.09;
+
+    for (Int_t j=1; j<=nb; j++)
+    {
+        const Double_t lgE = hb0.GetBinCenter(j);
+        const Double_t c   = hb0.GetBinContent(j);
+        const Double_t dc  = hb0.GetBinError(j);
+        const Double_t f   = 1.0 / (1.0 + exp( -(lgE-lgEth)/dlgEth ));
+
+        hb0.SetBinContent(j, f* c);
+        hb0.SetBinError  (j, f*dc);
+    }
+
+    //PrintTH1Content(hb0);
+
+    // -----------------------------------------
+    // generate distribution to be unfolded (ha)
+    // by smearing the ideal distribution  (hb0)
+    //
+    TH2D tobeunfolded("tobeunfolded", "Distribution to be unfolded", 
+                      na, alow, aup, nc, clow, cup);
+    tobeunfolded.Sumw2();
+
+    for (Int_t i=1; i<=na; i++)
+    {
+        Double_t cont = 0;
+        for (Int_t j=1; j<=nb; j++)
+            cont += migration.GetBinContent(i, j, m) * hb0.GetBinContent(j);
+
+        tobeunfolded.SetBinContent(i, m, cont);
+        tobeunfolded.SetBinError(i, m, sqrt(cont));
+    }
+
+    //PrintTH2Content(tobeunfolded);
+    //PrintTH2Error(tobeunfolded);
+
+    // -----------------------------------------
+    // unfolded distribution
+
+    TH2D unfolded("unfolded", "Unfolded distribution", 
+                  nb, blow, bup, nc, clow, cup);
+    unfolded.Sumw2();
+
+    // -----------------------------------------
+    doUnfolding(tobeunfolded, migration, unfolded);
+
+}
+//========================================================================//
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/getExtractor.C
===================================================================
--- /tags/Mars-V0.9/macros/getExtractor.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/getExtractor.C	(revision 9772)
@@ -0,0 +1,410 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 11/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  getExtractor.C
+//
+// This macro has to be included in another macro or code in order to be 
+// used in the following way:
+//
+// #include "getExtractor.C"
+//
+// Later, inside the macro, you can initialize one of the signal extractors, 
+// as specified in the TDAS-Extractor with the following meaning:
+//
+//      Nr.    Extractor   Parameters
+//
+//         MExtractFixedWindow:
+//             with the following parameters, if 'maxbin' defines the mean position 
+//             of the High-Gain FADC slice carrying the pulse maximum:  
+//       1:           SetRange('maxbin'-1,'maxbin'+2,'maxbin'+0.5,'maxbin'+3.5)  
+//       2:           SetRange('maxbin'-1,'maxbin'+2,'maxbin'-0.5,'maxbin'+4.5) 
+//       3:           SetRange('maxbin'-2,'maxbin'+3,'maxbin'-0.5,'maxbin'+4.5) 
+//       4:           SetRange('maxbin'-3,'maxbin'+4,'maxbin'-1.5,'maxbin'+5.5) 
+//       5:           SetRange('maxbin'-5,'maxbin'+8,'maxbin'-1.5,'maxbin'+7.5) 
+//         MExtractFixedWindowSpline:  
+//       6:           SetRange('maxbin'-1.5,'maxbin'+2.5,'maxbin','maxbin'+4) 
+//       7:           SetRange('maxbin'-1.5,'maxbin'+2.5,'maxbin'-1,'maxbin'+5) 
+//       8:           SetRange('maxbin'-2.5,'maxbin'+3.5,'maxbin'-1,'maxbin'+5) 
+//       9:           SetRange('maxbin'-3.5,'maxbin'+4.5,'maxbin'-2,'maxbin'+6) 
+//       10:          SetRange('maxbin'-5.5,'maxbin'+8.5,'maxbin'-2,'maxbin'+8) 
+//         MExtractFixedWindowPeakSearch:  
+//                    SetRange(0,18,2,14) and the following parameters: 
+//       11:          SetWindows(2,2,2) 
+//       12:          SetWindows(4,4,2) 
+//       13:          SetWindows(4,6,4) 
+//       14:          SetWindows(6,6,4) 
+//       15:          SetWindows(8,8,4) 
+//       16:          SetWindows(14,10,4) 
+//        MExtractTimeAndChargeSlidingWindow: 
+//                    SetRange(0,18,2,14) and the following parameters: 
+//       17:          SetWindowSize(2,2) 
+//       18:          SetWindowSize(4,4) 
+//       19:          SetWindowSize(4,6) 
+//       20:          SetWindowSize(6,6) 
+//       21:          SetWindowSize(8,8) 
+//       22:          SetWindowSize(14,10) 
+//        MExtractTimeAndChargeSpline:   
+//       23:          SetChargeType(MExtractTimeAndChargeSpline::kAmplitude 
+//                    SetRange(0,13,2,13)  
+//       24:          SetChargeType(MExtractTimeAndChargeSpline::kIntegral) and: 
+//                    SetRange(0,18,2,14) and the following parameters:  
+//                    SetRiseTime(0.5); SetFallTime(0.5) 
+//       25:          SetRiseTime(0.5); SetFallTime(1.5) 
+//       26:          SetRiseTime(1.0); SetFallTime(3.0) 
+//       27:          SetRiseTime(1.5); SetFallTime(4.5) 
+//        MExtractTimeAndChargeDigitalFilter 
+//                    SetRange(0,18,2,14) and the following parameters:  
+//       28:          SetNameWeightsFile('msignal/cosmics_weights.dat') 
+//       29:          SetNameWeightsFile('msignal/cosmics_weights4.dat') 
+//       30:          SetNameWeightsFile('msignal/cosmics_weights_logain.dat') 
+//       31:          SetNameWeightsFile('msignal/cosmics_weights4_logain.dat') 
+//       32:          SetNameWeightsFile('msignal/calibration_weights_UV.dat') 
+//       33:          SetNameWeightsFile('msignal/calibration_weights_UV_logain.dat') 
+//       34:          SetNameWeightsFile('msignal/MC_weights.dat') 
+//        MExtractTimeAndChargeDigitalFilterPeakSearch 
+//       35:          SetNameWeightsFile('msignal/calibration_weights_UV.dat') 
+// 
+// The extractor will also carry a meaningful name, storing all information about its 
+// initialization there.
+//
+//////////////////////////////////////////////////////////////////////////////////////////
+#include "MExtractor.h"
+#include "MExtractFixedWindowPeakSearch.h"
+#include "MExtractFixedWindow.h"
+#include "MExtractFixedWindowSpline.h"
+#include "MExtractTimeAndChargeDigitalFilter.h"
+#include "MExtractTimeAndChargeDigitalFilterPeakSearch.h"
+#include "MExtractTimeAndChargeSlidingWindow.h"
+#include "MExtractTimeAndChargeSpline.h"
+#include "MLog.h"
+
+#include <TSystem.h>
+#include <fstream>
+
+using namespace std;
+
+MExtractor *getExtractor(const UInt_t flag)
+{
+
+  MExtractor *extractor   = NULL;
+  
+  //
+  // Choose the signal Extractor:
+  //
+  // PURE CHARGE EXTRACTORS:
+  // MExtractFixedWindowPeakSearchs
+  // MExtractSlidingWindow           
+  // MExtractFixedWindow          
+  // MExtractFixedWindowSpline    
+  // MExtractAmplitudeSpline      
+  //
+  switch (flag)
+    {
+    case 1:
+    case 2:
+    case 3:
+    case 4:
+    case 5:
+      extractor = new MExtractFixedWindow();
+      break;
+    case 6:
+    case 7:
+    case 8:
+    case 9:
+    case 10:
+      extractor = new MExtractFixedWindowSpline();
+      break;
+    case 11:
+    case 12:
+    case 13:
+    case 14:
+    case 15:
+    case 16:
+      extractor = new MExtractFixedWindowPeakSearch();
+      extractor->SetRange(0,18,2,14);
+      break;
+      //
+      // PURE TIME EXTRACTORS:
+      // ATTENTION: If an extractor deriving from MExtractTimeAndCharge is
+      //            used, you may want to use the timing calculated directly
+      //            from there. 
+      //
+      // MExtractTimeHighestIntegral 
+      // MExtractTimeFastSpline      
+      // MExtractTimeSpline          
+      //
+      // COMBINED TIME AND CHARGE EXTRACTORS:
+      // MExtractTimeAndChargeDigitalFilter 
+      // MExtractTimeAndChargeSpline        
+      // MExtractTimeAndChargeSlidingWindow 
+      //
+    case 17:
+    case 18:
+    case 19:
+    case 20:
+    case 21:
+    case 22:
+      extractor = new MExtractTimeAndChargeSlidingWindow();
+      extractor->SetRange(0,18,2,14);
+      break;
+    case 23:
+    case 24:
+    case 25:
+    case 26:
+    case 27:
+      extractor = new MExtractTimeAndChargeSpline();
+      ((MExtractTimeAndChargeSpline*)extractor)->SetChargeType(MExtractTimeAndChargeSpline::kIntegral);      
+      extractor->SetRange(0,18,2,14);
+      break;
+    case 28:
+    case 29:
+    case 30:
+    case 31:
+    case 32:
+    case 33:
+    case 34:
+    case 35:
+      extractor = new MExtractTimeAndChargeDigitalFilter();
+      extractor->SetRange(0,16,3,14);
+      break;
+    case 36:
+      extractor = new MExtractTimeAndChargeDigitalFilterPeakSearch();
+      extractor->SetRange(0,20,3,14);
+      break;
+    default:
+      gLog << "No valid extractor flag chosen, cannot run..." << flag << endl;
+      return NULL;
+      break;
+    }
+
+  //
+  //  Set Ranges or Windows
+  //
+  switch (flag)
+    {
+      // MExtractFixedWindow:
+    case 1:
+      extractor->SetRange(4,7,6,9);
+      break;
+    case 2:
+      extractor->SetRange(4,7,6,11);
+      break;
+    case 3:
+      extractor->SetRange(4,9,6,11);
+      break;
+    case 4:
+      extractor->SetRange(4,11,6,13);
+      break;
+    case 5:
+      extractor->SetRange(3,16,5,14);
+      break;
+      // MExtractFixedWindowSpline:
+    case 6:
+      extractor->SetRange(4,8,6,10);
+      break;
+    case 7:
+      extractor->SetRange(4,8,5,11);
+      break;
+    case 8:
+      extractor->SetRange(4,10,5,11);
+      break;
+    case 9:
+      extractor->SetRange(3,11,5,13);
+      break;
+    case 10:
+      extractor->SetRange(3,17,4,14);
+      break;
+      // MExtractFixedWindowPeakSearch:
+    case 11:
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetWindows(2,2,2);
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetOffsetFromWindow(0);
+      break;
+    case 12:
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetWindows(4,4,2);
+      break;
+    case 13:
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetWindows(4,6,4);
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetOffsetFromWindow(0);
+      break;
+    case 14:
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetWindows(6,6,4);
+      break;
+    case 15:
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetWindows(8,8,4);
+      break;
+    case 16:
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetWindows(14,10,4);
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetOffsetFromWindow(2);
+      break;
+      // MExtractTimeAndChargeSlidingWindow
+    case 17:
+      ((MExtractTimeAndChargeSlidingWindow*)extractor)->SetWindowSize(2,2);
+      break;
+    case 18:
+      ((MExtractTimeAndChargeSlidingWindow*)extractor)->SetWindowSize(4,4);
+      break;
+    case 19:
+      ((MExtractTimeAndChargeSlidingWindow*)extractor)->SetWindowSize(4,6);
+      break;
+    case 20:
+      ((MExtractTimeAndChargeSlidingWindow*)extractor)->SetWindowSize(6,6);
+      break;
+    case 21:
+      ((MExtractTimeAndChargeSlidingWindow*)extractor)->SetWindowSize(8,8);
+      break;
+    case 22:
+      ((MExtractTimeAndChargeSlidingWindow*)extractor)->SetWindowSize(14,10);
+      break;
+      // MExtractTimeAndChargeSpline
+    case 23:
+      ((MExtractTimeAndChargeSpline*)extractor)->SetChargeType(MExtractTimeAndChargeSpline::kAmplitude);
+      extractor->SetRange(0,13,2,13);
+      extractor->SetName(Form("%s_Amplitude",extractor->GetName()));
+      break;
+    case 24:
+      ((MExtractTimeAndChargeSpline*)extractor)->SetRiseTimeHiGain(0.5); 
+      ((MExtractTimeAndChargeSpline*)extractor)->SetFallTimeHiGain(0.5);
+      extractor->SetName(Form("%s_Rise-and-Fall-Time_%2.1f_%2.1f",extractor->GetName(),0.5,0.5));
+      break;
+    case 25:
+      ((MExtractTimeAndChargeSpline*)extractor)->SetRiseTimeHiGain(0.5); 
+      ((MExtractTimeAndChargeSpline*)extractor)->SetFallTimeHiGain(1.5);
+      extractor->SetName(Form("%s_Rise-and-Fall-Time_%2.1f_%2.1f",extractor->GetName(),0.5,1.5));
+      break;
+    case 26:
+      ((MExtractTimeAndChargeSpline*)extractor)->SetRiseTimeHiGain(1.0); 
+      ((MExtractTimeAndChargeSpline*)extractor)->SetFallTimeHiGain(3.0);
+      extractor->SetName(Form("%s_Rise-and-Fall-Time_%2.1f_%2.1f",extractor->GetName(),1.0,3.0));
+      break;
+    case 27:
+      ((MExtractTimeAndChargeSpline*)extractor)->SetRiseTimeHiGain(1.5); 
+      ((MExtractTimeAndChargeSpline*)extractor)->SetFallTimeHiGain(4.5);
+      extractor->SetName(Form("%s_Rise-and-Fall-Time_%2.1f_%2.1f",extractor->GetName(),1.5,4.5));
+      break;
+      // MExtractTimeAndChargeDigitalFilter
+    case 28:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/cosmics_weights.dat");
+      break;
+    case 29:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/cosmics_weights4.dat");
+      break;
+    case 30:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/cosmics_weights_logaintest.dat");
+      break;
+    case 31:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/cosmics_weights4_logaintest.dat");
+      break;
+    case 32:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/calibration_weights_UV.dat");
+      break;
+    case 33:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/calibration_weights_UV_logaintest.dat");
+      break;
+    case 34:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/MC_weights.dat");
+      break;
+    case 35:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/calibration_weights_UV.dat");
+      break;
+    case 36:
+      ((MExtractTimeAndChargeDigitalFilter*)extractor)->SetNameWeightsFile("msignal/calibration_weights_UV.dat");
+      break;
+    default:
+      gLog << "No valid extractor flag chosen, cannot run..." << endl;
+      return NULL;
+      break;
+    }
+  
+  //
+  // Set the names of the extractors:
+  //
+  switch (flag)
+    {
+    case 1:
+    case 2:
+    case 3:
+    case 4:
+    case 5:
+    case 6:
+    case 7:
+    case 8:
+    case 9:
+    case 10:
+      break;
+    case 11:
+    case 12:
+    case 13:
+    case 14:
+    case 15:
+    case 16:
+      extractor->SetName(Form("%s_Windows_%02d_%02d",extractor->GetName(),
+                              (Int_t)((MExtractFixedWindowPeakSearch*)extractor)->GetHiGainWindowSize(),
+                              (Int_t)((MExtractFixedWindowPeakSearch*)extractor)->GetLoGainWindowSize()));
+      break;
+    case 17:
+    case 18:
+    case 19:
+    case 20:
+    case 21:
+    case 22:
+      extractor->SetName(Form("%s_Windows_%02d_%02d",extractor->GetName(),
+                              (Int_t)((MExtractTimeAndChargeSlidingWindow*)extractor)->GetWindowSizeHiGain(),
+                              (Int_t)((MExtractTimeAndChargeSlidingWindow*)extractor)->GetWindowSizeLoGain()));
+      break;
+    case 23:
+    case 24:
+    case 25:
+    case 26:
+    case 27:
+      break;
+    case 28:
+    case 29:
+    case 30:
+    case 31:
+    case 32:
+    case 33:
+    case 34:
+    case 35:
+    case 36:
+      extractor->SetName(Form("%s_Weights_%s",extractor->GetName(),
+                              gSystem->BaseName(((MExtractTimeAndChargeDigitalFilter*)extractor)->GetNameWeightsFile())));
+      break;
+    default:
+      gLog << "No valid extractor flag chosen, cannot run..." << endl;
+      return NULL;
+      break;
+    }
+
+  extractor->SetName(Form("%s_Range_%02d_%02d_%02d_%02d",extractor->GetName(),
+                          (Int_t)extractor->GetHiGainFirst(),
+                          (Int_t)extractor->GetHiGainLast(),
+                          (Int_t)extractor->GetLoGainFirst(),
+                          (Int_t)extractor->GetLoGainLast()));
+
+  gLog << "Extractor: " << flag << " with name: " << extractor->GetName() << endl;
+
+  return extractor;
+  
+}
Index: /tags/Mars-V0.9/macros/hft.C
===================================================================
--- /tags/Mars-V0.9/macros/hft.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/hft.C	(revision 9772)
@@ -0,0 +1,236 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// hft.C
+//
+// example of using MHexagonal*
+//
+///////////////////////////////////////////////////////////////////////////
+
+Bool_t HandleInput()
+{
+    // This must be there to get accesss to the GUI while the macro
+    // is still running!
+
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+//
+// Setup the data-members of your 'virtual' class
+//
+MHCamera display[5];
+
+TCanvas   *c;
+MParList  *fParList;
+MTaskList *fTaskList;
+
+MHexagonalFTCalc  hft;
+MHexagonFreqSpace *fFreq1;
+MHexagonFreqSpace *fFreq2;
+
+MGeomCam *geomfreq;
+
+TH1F histo("", "", 35, -0.5, 35);
+
+//
+// Called like all PreProcess functions of tasks. Get the access to
+// the containers necessary for you.
+//
+Int_t PreProcess(MParList *plist)
+{
+    fFreq1 = (MHexagonFreqSpace*)plist->FindObject("MHexagonFreqSpace1");
+    if (!fFreq1)
+        return kFALSE;
+    fFreq2 = (MHexagonFreqSpace*)plist->FindObject("MHexagonFreqSpace2");
+    if (!fFreq2)
+        return kFALSE;
+
+    geomfreq=fFreq1->NewGeomCam();
+    geomfreq->SetName("FreqSpace");
+    plist->AddToList(geomfreq);
+
+    //    return kTRUE;
+
+    // Get parameter and tasklist, see Process
+    fParList = plist;
+    fTaskList = (MTaskList*)plist->FindObject("MTaskList");
+
+    // Get camera geoemtry
+    MGeomCam *geomcam = (MGeomCam*)plist->FindObject("MGeomCam");
+
+    // setup canvas and camera-histograms
+    c = new TCanvas("Events", "Real Events", 900, 600);
+    c->SetBorderMode(0);
+    c->Divide(3,2);
+    for (int i=0; i<3; i++)
+    {
+        display[i].SetGeometry(*geomfreq);
+        display[i].SetPrettyPalette();
+        c->cd(i+1);
+        display[i].Draw();
+    }
+
+    display[1].SetName("In");
+    display[2].SetName("Out");
+    display[0].SetName("Freq");
+
+    return kTRUE;
+}
+
+//
+// Called like all Process functions of tasks. Process a single
+// event - here display it.
+//
+Int_t Process()
+{
+    // For simplicity we search in the Process function for the
+    // objects. This is deprectaed! Store the pointers to the objects
+    // as data member and get the pointers in PreProcess.
+    MClone *clone1 = (MClone*)fTaskList->FindObject("Clone1");
+    MClone *clone2 = (MClone*)fTaskList->FindObject("Clone2");
+    MGeomCam *geom = (MGeomCam*)fParList->FindObject("MGeomCam");
+
+    // Fill the data into your camera-histograms
+    display[1].SetCamContent(*fFreq1, 1);
+    display[2].SetCamContent(*fFreq1, 2);
+    display[0].SetCamContent(*fFreq2, 0);
+
+    display[1].SetMaximum(-1111);
+    display[2].SetMaximum(-1111);
+    display[1].SetMinimum(0);
+    display[2].SetMinimum(0);
+    display[1].SetMaximum(TMath::Max(display[1].GetMaximum(),
+                                     display[2].GetMaximum()));
+    display[2].SetMaximum(display[1].GetMaximum());
+
+    MHexagonalFT *ft = &hft.GetHFT();
+
+    histo.Reset();
+    for (int i=0; i<ft->GetNumKnots(); i++)
+    {
+        Double_t val=0;
+        fFreq2->GetPixelContent(val, i, *display[1].GetGeometry());
+        histo.Fill(ft->GetRow(i), val/(i+1));
+    }
+
+    c->cd(4);
+    histo.Draw();
+
+    c->cd(5);
+
+    TH1D *obj1 = (TH1D*)display[1].Projection("Proj1");
+    obj1->SetLineColor(kBlue);
+    obj1->Draw();
+    obj1 = (TH1D*)display[2].Projection("Proj2");
+    obj1->Draw("same");
+
+    c->cd(6);
+    display[0].DrawProjection();
+
+    // Update the display
+    for (int i=1; i<=3; i++)
+    {
+        c->GetPad(i)->GetPad(1)->Modified();
+        c->GetPad(i)->GetPad(1)->Update();
+    }
+
+    return HandleInput();
+}
+
+//
+// Called like all PostProcess functions of tasks. Delete
+// instanciated objects.
+//
+Int_t PostProcess()
+{
+    delete c;
+    delete geomfreq;
+}
+
+void hft(const char *fname="/home/hoehne/data/mcdata/hadrons/calib/calib_proton_zbin0.root")
+{
+    // Setup parameter- and tasklist
+    MParList  plist;
+    MTaskList tlist;
+
+    plist.AddToList(&tlist);
+
+    // setup reading task
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    // Clone MCerPhotEvt befor eimage cleaning
+    MClone clone1("MCerPhotEvt", "Clone1");
+
+    // Setup image cleaning
+    MImgCleanStd clean(24, 12);
+    clean.SetMethod(MImgCleanStd::kAbsolute);
+
+    // Clone MCerPhotEvt befor eimage cleaning
+    MClone clone2("MCerPhotEvt", "Clone2");
+
+    // Setup intercative task calling the functions defined above
+    MTaskInteractive  mytask;
+
+    mytask.SetPreProcess(PreProcess);
+    mytask.SetProcess(Process);
+
+    // Setup your tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&clone1);
+    tlist.AddToList(&hft);
+    tlist.AddToList(&clone2);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&mytask);
+
+    // Run your analysis
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    // Print statistics information about your loop
+    tlist.PrintStatistics();
+}
+
Index: /tags/Mars-V0.9/macros/mccalibrate.C
===================================================================
--- /tags/Mars-V0.9/macros/mccalibrate.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/mccalibrate.C	(revision 9772)
@@ -0,0 +1,294 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Abelardo Moralejo 1/2004 <mailto:moralejo@pd.infn.it>
+   !              Thomas Bretz  5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+   !
+   !   Copyright: MAGIC Software Development, 2000-2004
+   !
+   !
+   \* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMCALIBRATE - Calibration of MC data
+//
+//  This macro converts raw MC data into calibrated data (photons per pixel) 
+//  It optionally divides the output into a train and a test sample
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MImgCleanStd.h"
+
+void mccalibrate()
+{
+  //
+  // This macro reads in MC camera files and produces and output with 
+  // calibrated events (signal in photons for all pixels, in MCerPhotEvt 
+  // containers).
+  //
+
+  // ------------- user change -----------------
+  TString* CalibrationFilename;
+
+  CalibrationFilename = new TString("/users/emc/moralejo/mcdata/Period021_0.73_mirror/gammas_nonoise/Gamma_*root");  // File to be used for the calibration (must be a camera file without added noise)
+
+  Char_t* AnalysisFilename = "Gamma_zbin*w0.root";  // File to be analyzed
+
+
+  TString* OutFilename1;
+  TString* OutFilename2;
+
+  // Output file names
+  OutFilename1 = new TString("calibrated_gamma_train.root");
+  OutFilename2 = new TString("calibrated_gamma_test.root"); 
+
+  // To get only one output file, just comment out the second 
+  // one of the above lines
+
+
+  //
+  //  Set signal extractor
+  //
+  //    MExtractFixedWindowPeakSearch sigextract;
+  //    sigextract.SetWindows(6, 6, 4);
+  //
+  MExtractTimeAndChargeDigitalFilter sigextract;
+  sigextract.SetNameWeightsFile("/users/emc/moralejo/Mars/msignal/MC_weights.dat");
+  sigextract.SetRange(1, 14, 3, 14);
+
+
+  MMcCalibrationUpdate  mccalibupdate;
+  ///// User change: calibrate in photons or phe- :
+  mccalibupdate.SetSignalType(MCalibrateData::kPhe);
+  //  mccalibupdate.SetSignalType(MCalibrateData::kPhot);
+
+  // ---------------------------------------------------------------------
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  MBadPixelsCam badpix;
+  plist.AddToList(&badpix);  // Not used for now.
+ 
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+
+  if (CalibrationFilename)
+    read.AddFile(CalibrationFilename->Data());
+
+  read.DisableAutoScheme();
+
+  MGeomApply geom; 
+  // Reads in geometry from MC file and sets the right sizes for
+  // several parameter containers.
+
+  MMcPedestalCopy   pcopy; 
+  // Copies pedestal data from the MC file run fadc header to the 
+  // MPedestalCam container.
+
+  MPointingPosCalc pointcalc;
+  // Creates MPointingPos object and fills it with the telescope 
+  // orientation information taken from MMcEvt.
+
+  MCalibrateData calib; 
+  //
+  // MCalibrateData transforms signals from ADC counts into photons or phe-
+  // (this can be selected anove). In the first loop it applies a "dummy" 
+  // calibration supplied by MMcCalibrationUpdate, just to equalize inner 
+  // and outer pixels, and calculates SIZE in "equivalent number of inner 
+  // ADC counts". At the end of the first loop, in the PostProcess of 
+  // MMcCalibrationCalc (see below) the true calibration constants
+  // are calculated.
+  //
+  calib.SetCalibrationMode(MCalibrateData::kFfactor);
+  // Do not change the CalibrationMode above for MC...!
+
+  // Now set also whether to calibrate in photons or phe-:
+  calib.SetSignalType(mccalibupdate.GetSignalType());
+
+  MImgCleanStd clean;
+  //
+  // Applies tail cuts to image. Since the calibration is performed on 
+  // noiseless camera files, the precise values of the cleaning levels 
+  // are unimportant (in any case, only pixels without any C-photon will
+  // be rejected).
+  //
+
+  MHillasCalc hcalc; 
+  hcalc.Disable(MHillasCalc::kCalcHillasSrc);
+  // Calculates Hillas parameters not dependent on source position.
+
+  MMcCalibrationCalc mccalibcalc; 
+  // Calculates calibration constants to convert from ADC counts to photons.
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geom);
+
+  MF notrigger("MMcTrig.fNumFirstLevel<1");
+  MContinue skipnotrig(&notrigger);
+  tlist.AddToList(&skipnotrig);
+
+  tlist.AddToList(&pcopy);
+  tlist.AddToList(&pointcalc);
+  tlist.AddToList(&sigextract);
+  tlist.AddToList(&mccalibupdate);
+  tlist.AddToList(&calib);
+  tlist.AddToList(&clean);
+  tlist.AddToList(&hcalc);
+
+  tlist.AddToList(&mccalibcalc);
+
+  //
+  // Open output files:
+  //
+  MWriteRootFile write1(OutFilename1->Data()); // Writes output
+
+  MWriteRootFile write1_b(OutFilename1->Data());
+  write1_b.AddContainer("MMcEvtBasic", "OriginalMC", kFALSE);
+  // Add the MMcEvtBasic container only in case it exists in 
+  // the input camera files
+
+  write1.AddContainer("MGeomCam",            "RunHeaders");
+  write1.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+  write1.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+  write1.AddContainer("MMcFadcHeader",       "RunHeaders");
+  write1.AddContainer("MMcRunHeader",        "RunHeaders");
+  write1.AddContainer("MMcTrigHeader",       "RunHeaders");
+  write1.AddContainer("MRawRunHeader",       "RunHeaders");
+
+  write1.AddContainer("MMcEvt",        "Events");
+  write1.AddContainer("MMcTrig",       "Events");
+  write1.AddContainer("MPointingPos",  "Events");
+  write1.AddContainer("MRawEvtHeader", "Events");
+  write1.AddContainer("MCerPhotEvt",   "Events");
+  write1.AddContainer("MPedPhotCam",   "Events");
+
+  if (OutFilename2)
+    {
+      MWriteRootFile write2(OutFilename2->Data()); // Writes output    
+
+      MWriteRootFile write2_b(OutFilename2->Data());
+      write2_b.AddContainer("MMcEvtBasic", "OriginalMC", kFALSE);
+      // Add the MMcEvtBasic container only in case it exists in 
+      // the input camera files
+
+      write2.AddContainer("MGeomCam",            "RunHeaders");
+      write2.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+      write2.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+      write2.AddContainer("MMcFadcHeader",       "RunHeaders");
+      write2.AddContainer("MMcRunHeader",        "RunHeaders");
+      write2.AddContainer("MMcTrigHeader",       "RunHeaders");
+      write2.AddContainer("MRawRunHeader",       "RunHeaders");
+
+      write2.AddContainer("MMcEvt",        "Events");
+      write2.AddContainer("MMcTrig",       "Events");
+      write2.AddContainer("MPointingPos",  "Events");
+      write2.AddContainer("MRawEvtHeader", "Events");
+      write2.AddContainer("MCerPhotEvt",   "Events");
+      write2.AddContainer("MPedPhotCam",   "Events");
+
+      //
+      // Divide output in train and test samples, using the event number
+      // (odd/even) to achieve otherwise unbiased event samples:
+      //
+      MF filter1("{MMcEvt.fEvtNumber%2}>0.5");
+      MF filter2("{MMcEvt.fEvtNumber%2}<0.5");
+
+      write1.SetFilter(&filter1);
+      write2.SetFilter(&filter2);
+
+      write1_b.SetFilter(&filter1);
+      write2_b.SetFilter(&filter2);
+    }
+
+  //
+  // First loop: Calibration loop
+  //
+
+  MProgressBar bar;
+  bar.SetWindowName("Calibrating...");
+
+  MEvtLoop evtloop;
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (CalibrationFilename)
+    {
+      if (!evtloop.Eventloop())
+	return;
+      mccalibcalc->GetHistADC2PhotEl()->Write();
+      mccalibcalc->GetHistPhot2PhotEl()->Write();
+      // Writes out the histograms used for calibration. In case of
+      // aslit output in train and test file, this is written only
+      // in the test file for now.
+    }
+
+  //
+  // Second loop: apply calibration factors to MC events in the 
+  // file to be anlyzed:
+  //
+
+  //
+  // Change the read task by another one which reads the file we want to analyze:
+  //
+
+  MReadMarsFile read2("Events");
+  read2.AddFile(AnalysisFilename);
+  read2.DisableAutoScheme();
+  tlist.AddToListBefore(&read2, &read, "All");
+  tlist.RemoveFromList(&read);
+
+  // Now add tasks to write MMcEvtBasic to the OriginalMC tree:
+  tlist.AddToListBefore(&write1_b, &skipnotrig, "All");
+  if (OutFilename2)
+    tlist.AddToListBefore(&write2_b, &skipnotrig, "All");
+
+
+  if (OutFilename2) // Add filters to split output in train and test
+    {
+      tlist.AddToListBefore(&filter1, &write1_b, "All");
+      tlist.AddToListBefore(&filter2, &write1_b, "All");
+    }
+
+  bar.SetWindowName("Writing...");
+
+  tlist.RemoveFromList(&clean);
+  tlist.RemoveFromList(&hcalc);
+  tlist.RemoveFromList(&mccalibcalc);
+
+  tlist.AddToList(&write1);
+
+  if (OutFilename2)
+    tlist.AddToList(&write2); 
+  // Add tasks to write the Events and RunHeaders trees to output.
+
+  if (!evtloop.Eventloop())
+    return;
+
+
+  tlist.PrintStatistics();
+}
Index: /tags/Mars-V0.9/macros/mergecamera.C
===================================================================
--- /tags/Mars-V0.9/macros/mergecamera.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/mergecamera.C	(revision 9772)
@@ -0,0 +1,60 @@
+//
+// A. Moralejo, March 2003
+// This macro merges several MC camera files into one. The output files
+// are useful to run Mars over larger samples of triggered events than 
+// those contained in a single file.
+//
+
+void mergecamera(Char_t *in="Proton*root", Char_t *out="all.root")
+{
+  cout << endl
+       << "WARNING: this macro merges camera output files, but the" << endl
+       << "Run headers of the resulting file are those of the first" <<endl
+       << "merged file, and so do not represent the whole of the" << endl
+       << "merged events. Be careful not to mix files with different" << endl
+       << "parameters (primary, theta...)." << endl << endl;
+
+  //
+  // Open output file:
+  //
+  TFile* f = new TFile(out,"recreate");
+
+  //
+  // First the Events tree:
+  //
+  MMcEvt* mmcevt = new MMcEvt();;
+  MMcTrig* mmctrig = new MMcTrig();
+  MRawEvtHeader* mrawhead = new MRawEvtHeader();
+  MRawEvtData* mrawdata = new MRawEvtData();
+
+  TChain c("Events");
+  c.SetBranchAddress("MMcEvt",&mmcevt);
+  c.SetBranchAddress("MMcTrig",&mmctrig);
+  c.SetBranchAddress("MRawEvtHeader",&mrawhead);
+  c.SetBranchAddress("MRawEvtData",&mrawdata);
+  c.Add(in);
+  c.Merge(f,1000);
+
+  //
+  // Now the RunHeaders tree:
+  //
+  MMcConfigRunHeader* mcconfig = new MMcConfigRunHeader();
+  MMcCorsikaRunHeader* mccorsi = new MMcCorsikaRunHeader();
+  MMcFadcHeader* mcfadc = new MMcFadcHeader();
+  MMcRunHeader* mcrunhead = new MMcRunHeader();
+  MMcTrigHeader* mctrighead = new MMcTrigHeader();
+  MRawRunHeader* mrawrunhead = new MRawRunHeader();
+  TChain d("RunHeaders");
+  d.SetBranchAddress("MMcConfigRunHeader",&mcconfig);
+  d.SetBranchAddress("MMcCorsikaRunHeader",&mccorsi);
+  d.SetBranchAddress("MMcFadcHeader",&mcfadc);
+  d.SetBranchAddress("MMcRunHeader",&mcrunhead);
+  d.SetBranchAddress("MMcTrigHeader",&mctrighead);
+  d.SetBranchAddress("MRawRunHeader",&mrawrunhead);
+  d.Add(in);
+  d.Merge(f,1000);
+
+  f->Close();
+
+  return;
+}
Index: /tags/Mars-V0.9/macros/merpp.C
===================================================================
--- /tags/Mars-V0.9/macros/merpp.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/merpp.C	(revision 9772)
@@ -0,0 +1,103 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// merpp.C
+// =======
+//
+// This is an easy implementation of the Merging process (as root Macro)
+//
+// at the moment it reads a binary file ("rawtest.raw") which was written
+// in the DAQ raw format.
+//
+// The data are stored in root container objects (classes derived from
+// TObject like MRawRunHeader)
+//
+// This containers are written to a root file ("rawtest.root")
+//
+// It also demonstrates how you can loop over files in a single or more
+// than one directory and process them. For details see MRunIter.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void ProcessFile(TString fname)
+{
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    //
+    MTaskList tasks;
+    MParList plist;
+
+    plist.AddToList(&tasks);
+
+    //
+    // create the tasks which should be executed and add them to the list
+    // in the case you don't need parameter containers, all of them can
+    // be created by MRawFileRead::PreProcess
+    //
+    // REMARK: Don't change the order of the two instantiations.
+    //         I don't have an idea why, but here it crashes the
+    //         Interpreter.
+    //         (Using root 2.25/03, with Cint 5.14.50 on OSF1)
+    //
+    MRawFileRead  reader(fname);
+    MRawFileWrite writer(fname(0, fname.Last('.')+1) + "root", "RECREATE", fname, 1);
+    tasks.AddToList(&reader);
+    tasks.AddToList(&writer);
+
+    //
+    // create the looping object and thell it about the parameters to use
+    // and the tasks to execute
+    //
+    MEvtLoop magic;
+
+    magic.SetParList(&plist);
+
+    //
+    // Start the eventloop which reads the raw file (MRawFileRead) and
+    // write all the information into a root file (MRawFileWrite)
+    //
+    // between reading and writing we can do, transformations, checks, etc.
+    // (I'm think of a task like MRawDataCheck)
+    //
+    magic.Eventloop();
+}
+
+void merpp(const char *dirname="/home/MAGIC/online_data/rawdata/")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "*.raw", -1);
+
+    while (1)
+    {
+        TString fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+    }
+}
+
Index: /tags/Mars-V0.9/macros/multidimdist.C
===================================================================
--- /tags/Mars-V0.9/macros/multidimdist.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/multidimdist.C	(revision 9772)
@@ -0,0 +1,176 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Rudy Bock, 5/2002 <mailto:rkb@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+void multidimdist()
+{
+    //
+    // This is a demonstration program which calculates the Hillas
+    // parameter out of a Magic root file.
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // This is an example program which reads image parameters for gammas 
+    // and hadrons, builds a 'matrix' of look-alike events,
+    // and then finds quality numbers and acceptances for the same sample
+
+    // Create an empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+    MTaskList tlistg;
+    plist.AddToList(&tlistg);
+
+    //
+    // ------------- user attention -----------------
+    //
+
+    // cut used both for the matrices and the sample
+    // for more information see the documentation of MF and MDataChain
+    MF filterenergy("MMcEvt.fEnergy > 0");
+
+    // matrix limitation for look-alike events (approximate number)
+    MFEventSelector selector;
+    selector.SetNumSelectEvts(2000);
+
+    // setup an AND-Filterlist from the two filters to be used
+    // in the event selection for the filling of the matrices
+    MFilterList flist;
+    flist.AddToList(&filterenergy);
+    flist.AddToList(&selector);
+
+    //
+    // ---------------------------------------------------------------
+    //  Now set up the tasks and tasklist (first event loop, gammas)
+    // ---------------------------------------------------------------
+    //
+
+    // --------------- user change -----------------
+    //  Give the names of the star-files to be read
+    //   Here you give the trainings sample(s) for
+    //                 the hadrons
+    // ---------------------------------------------
+    MReadMarsFile read("Events");
+    read.AddFile("star_gammas.root");
+    read.AddFile("star_protons.root");
+    read.DisableAutoScheme();
+    tlistg.AddToList(&read);
+
+    MFParticleId fgamma("MMcEvt", '=', kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    MFParticleId fhadrons("MMcEvt", '!', kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    MHMatrix matrix("MatrixGammas");
+    matrix.AddColumn("MHillas.fWidth");
+    matrix.AddColumn("MHillas.fLength");
+    matrix.AddColumn("MHillas.fWidth*MHillas.fLength/MHillas.fSize");
+    matrix.AddColumn("abs(MHillas.fAsym)");
+    matrix.AddColumn("abs(MHillas.fM3Long)");
+    matrix.AddColumn("abs(MHillas.fM3Trans)");
+    matrix.AddColumn("abs(MHillasSrc.fHeadTail)");
+    matrix.AddColumn("MHillas.fConc");
+    matrix.AddColumn("MHillas.fConc1");
+    matrix.AddColumn("MHillasSrc.fDist");
+    matrix.AddColumn("log10(MHillas.fSize)");
+    matrix.AddColumn("MHillasSrc.fAlpha");
+    matrix.AddColumn("MMcEvt.fTheta");
+    plist.AddToList(&matrix);
+
+    MHMatrix matrix2("MatrixHadrons");
+    matrix2.AddColumns(matrix.GetColumns());
+    plist.AddToList(&matrix2);
+
+    MFillH fillmat("MatrixGammas");
+    fillmat.SetFilter(&fgamma);
+    tlist.AddToList(&fillmat);
+
+    MFillH fillmat2("MatrixHadrons");
+    fillmat2.SetFilter(&fhadrons);
+    tlist.AddToList(&fillmat2);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    matrix.Print("size");
+    matrix2.Print("size");
+
+    // ---------------------------------------------------------
+
+    MTaskList tlist2;
+
+    plist.Replace(&tlist2);
+
+    MReadMarsFile read2("Events");
+    read2.("gammas2.root");
+    read2.AddFile("hadrons2.root");
+    read2.DisableAutoScheme();
+    tlist2.AddToList(&read2);
+
+    MMultiDimDistCalc calc;
+    calc.SetUseNumRows(0);
+    calc.SetUseKernelMethod(kTRUE);
+    tlist2.AddToList(&calc);
+
+    MFillH fillh("MHHadronness");
+
+    /*
+     MF filter("MMcEvt.fEnergy < 100");
+     fillh.SetFilter(&filter);
+     tlist2.AddToList(&filter);
+     */
+
+    tlist2.AddToList(&fillh);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist2.PrintStatistics();
+
+    plist.FindObject("MHHadronness")->DrawClone();
+    plist.FindObject("MHHadronness")->Print();
+}
Index: /tags/Mars-V0.9/macros/multidimdist2.C
===================================================================
--- /tags/Mars-V0.9/macros/multidimdist2.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/multidimdist2.C	(revision 9772)
@@ -0,0 +1,205 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Rudy Bock, 11/2002 <mailto:rkb@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+void multidimdist2()
+{
+    //
+    // This is an example program which reads image parameters for gammas 
+    // and hadrons, builds a 'matrix' of look-alike events,
+    // and then finds quality numbers and acceptances for the same sample
+
+    // Create an empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+    MTaskList tlistg;
+    plist.AddToList(&tlistg);
+
+    //
+    // ------------- user attention -----------------
+    //
+
+    // cut used both for the matrices and the sample
+    // for more information see the documentation of MF and MDataChain
+    MF filterenergy("MMcEvt.fEnergy > 0");
+
+    // matrix limitation for look-alike events (approximate number)
+    MFEventSelector selector;
+    selector.SetNumSelectEvts(2000);
+
+    // setup an AND-Filterlist from the two filters to be used
+    // in the event selection for the filling of the matrices
+    MFilterList flist;
+    flist.AddToList(&filterenergy);
+    flist.AddToList(&selector);
+
+    //
+    // ---------------------------------------------------------------
+    //  Now set up the tasks and tasklist (first event loop, gammas)
+    // ---------------------------------------------------------------
+    //
+
+    // --------------- user change -----------------
+    //  Give the names of the star-files to be read
+    //   Here you give the trainings sample(s) for
+    //                 the gammas
+    //      If you have only _one_ single Theta
+    //            remove MMcEvt.fTheta!
+    // ---------------------------------------------
+    MReadMarsFile readg("Events", "star_gammas0.root");
+    readg.DisableAutoScheme();
+    tlistg.AddToList(&readg);
+
+    MHMatrix matrix("MatrixGammas");
+    matrix.AddColumn("MHillas.fWidth");
+    matrix.AddColumn("MHillas.fLength");
+    matrix.AddColumn("MHillas.fWidth*MHillas.fLength/MHillas.fSize");
+    matrix.AddColumn("abs(MHillas.fAsym)");
+    matrix.AddColumn("abs(MHillas.fM3Long)");
+    matrix.AddColumn("abs(MHillas.fM3Trans)");
+    matrix.AddColumn("abs(MHillasSrc.fHeadTail)");
+    matrix.AddColumn("MHillas.fConc");
+    matrix.AddColumn("MHillas.fConc1");
+    matrix.AddColumn("MHillasSrc.fDist");
+    matrix.AddColumn("log10(MHillas.fSize)");
+    matrix.AddColumn("MHillasSrc.fAlpha");
+    matrix.AddColumn("MMcEvt.fTheta");
+    plist.AddToList(&matrix);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&flist);
+    tlistg.AddToList(&flist);
+    tlistg.AddToList(&fillmatg);
+
+    //
+    // --- Create and set up the eventloop (gammas) ---
+    //
+    MEvtLoop evtloop1;
+    evtloop1.SetParList(&plist);
+
+    //
+    // --- Execute matrix buildup (gammas) ---
+    //
+    if (!evtloop1.Eventloop())
+        return;
+
+    tlistg.PrintStatistics();
+
+    //
+    // ------------------------------------------------------------------
+    //                prepare second event loop, hadrons
+    // ------------------------------------------------------------------
+    //
+    MTaskList tlisth;
+    plist.Replace(&tlisth);
+
+    // --------------- user change -----------------
+    //  Give the names of the star-files to be read
+    //   Here you give the trainings sample(s) for
+    //                 the hadrons
+    // ---------------------------------------------
+    MReadMarsFile  readh("Events", "star_protons0.root");
+    readh.DisableAutoScheme();
+    tlisth.AddToList(&readh);
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.AddColumns(matrix.GetColumns());
+    plist.AddToList(&matrixh); 
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&flist);         // filter list
+    tlisth.AddToList(&flist);
+    tlisth.AddToList(&fillmath);
+
+    //
+    // Create and set up the eventloop (protons)
+    //
+    MEvtLoop evtloop2;
+    evtloop2.SetParList(&plist);
+
+    //
+    // Execute matrix buildup (hadrons)
+    //
+    if (!evtloop2.Eventloop())
+        return;
+
+    //  sum up in log
+    tlisth.PrintStatistics();
+
+    matrix.Print("size");
+    matrixh.Print("size");
+
+    //
+    // ----------------------------------------------------------
+    //  Go through full sample again, now for getting hadronness
+    //  (third event loop)
+    // ----------------------------------------------------------
+    //
+
+    MTaskList tlist2;
+    plist.Replace(&tlist2);
+
+    // ------------------- user change --------------------
+    //    Give the names of the star-files to be read as
+    //  test samples   you should at least have one hadron
+    //          and one gamma file available
+    // ----------------------------------------------------
+    MReadMarsFile read2("Events", "star_gammas0.root");
+    read2.AddFile("star_protons0.root");
+    read2.DisableAutoScheme();
+    tlist2.AddToList(&read2);
+
+    // ---------------- user attention -----------------
+    //      Here you may change the algorithm used
+    //    You can switch from Kernel to Next Neighbor
+    //  or change the number of used shortest distances
+    //  For kernel you should always set this to 0 (all)
+    // -------------------------------------------------
+    MMultiDimDistCalc calc;
+    calc.SetUseNumRows(25);
+    calc.SetUseKernelMethod(kFALSE);
+    tlist2.AddToList(&calc);
+
+    MFillH fillh("MHHadronness");
+    fillh.SetFilter(&filterenergy);
+    tlist2.AddToList(&filterenergy);
+    tlist2.AddToList(&fillh);
+
+    //
+    // Execute analysis of gammas and hadrons
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop3;
+    evtloop3.SetProgressBar(&bar);
+    evtloop3.SetParList(&plist);
+
+    if (!evtloop3.Eventloop())
+        return;
+
+    tlist2.PrintStatistics();
+
+    plist.FindObject("MHHadronness")->DrawClone();
+    plist.FindObject("MHHadronness")->Print();
+}
Index: /tags/Mars-V0.9/macros/optPad.C
===================================================================
--- /tags/Mars-V0.9/macros/optPad.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/optPad.C	(revision 9772)
@@ -0,0 +1,268 @@
+#include <TH1.h>
+#include <TCanvas.h>
+#include <TVector.h>
+#include <TMatrix.h>
+#include <iomanip.h>
+
+void optPad()
+{
+  Int_t N = 10;
+  Double_t eps = 1.e-10;
+
+  TMatrix g(N, N);
+  g.Zero();
+
+  // hista is the normalized 1D histogram of sigmabar for ON data
+  // histb is the normalized 1D histogram of sigmabar for OFF data
+  // histc is the difference ON-OFF
+
+  TH1D *hista = new TH1D("ON",   "ON  data before padding", N, 0., 5.);
+  TH1D *histb = new TH1D("OFF",  "OFF data before padding", N, 0., 5.);
+  TH1D *histc = new TH1D("ON-OFF", "ON-OFF before padding", N, 0., 5.);
+  hista->SetMaximum( 5.0/(Double_t)N );
+  hista->SetMinimum(-1.0/(Double_t)N );
+  histb->SetMaximum( 5.0/(Double_t)N );
+  histb->SetMinimum(-1.0/(Double_t)N );
+  histc->SetMaximum( 5.0/(Double_t)N );
+  histc->SetMinimum(-1.0/(Double_t)N );
+ 
+  // at the beginning, histap is a copy of hista
+  // at the end, it will be the 1D histogram for ON data after padding
+
+  // at the beginning, histbp is a copy of histb
+  // at the end, it will be the 1D histogram for OFF data after padding
+
+  // at the beginning, histcp is a copy of histc
+  // at the end, it should be zero
+
+  TH1D *histap = new TH1D("ONp",   "ON  data after padding", N, 0., 5.);
+  TH1D *histbp = new TH1D("OFFp",  "OFF data after padding", N, 0., 5.);
+  TH1D *histcp = new TH1D("ON-OFFp", "ON-OFF after padding", N, 0., 5.);  
+  histap->SetMaximum( 5.0/(Double_t)N );
+  histap->SetMinimum(-1.0/(Double_t)N );
+  histbp->SetMaximum( 5.0/(Double_t)N );
+  histbp->SetMinimum(-1.0/(Double_t)N );
+  histcp->SetMaximum( 1.0/(Double_t)N);
+  histcp->SetMinimum(-1.0/(Double_t)N);
+
+  Double_t shoulda[] = {1.0, 2.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 1.0};
+  Double_t shouldb[] = {0.0, 0.0, 1.0, 2.0, 3.0, 2.0, 1.0, 0.0, 1.0, 2.0};
+  for (Int_t i=1; i<=N; i++)
+  {
+    hista->SetBinContent(i, shoulda[i-1]);
+    histb->SetBinContent(i, shouldb[i-1]);
+  }
+
+  // normalize histograms
+  Double_t suma, sumb, conta, contb;
+  suma = 0.0;
+  sumb = 0.0;
+  for (Int_t i=1; i<=N; i++)
+  {
+    conta = hista->GetBinContent(i);
+    contb = histb->GetBinContent(i);
+    suma += conta;
+    sumb += contb;    
+  }
+
+  for (Int_t i=1; i<=N; i++)
+  {
+    conta = hista->GetBinContent(i);
+    contb = histb->GetBinContent(i);
+
+    hista->SetBinContent(i,conta/suma);
+    histb->SetBinContent(i,contb/sumb);
+    histc->SetBinContent(i, conta/suma - contb/sumb);
+
+    histap->SetBinContent(i,conta/suma);
+    histbp->SetBinContent(i,contb/sumb);
+    histcp->SetBinContent(i, conta/suma - contb/sumb);
+  }
+
+
+  // g[k-1][j-1] (if <0.0) tells how many ON events in bin k should be padded
+  //              from sigma_k to sigma_j
+
+  // g[k-1][j-1] (if >0.0) tells how many OFF events in bin k should be padded
+  //              from sigma_k to sigma_j
+
+
+  //--------   start j loop   ------------------------------------------------
+  // loop over bins in histc, starting from the end
+  Double_t v, s, w, t, x, u, a, b, arg;
+
+  for (Int_t j=N; j >= 1; j--)
+  {
+    v = histcp->GetBinContent(j);
+    if ( fabs(v) < eps ) continue;
+    if (v >= 0.0) 
+      s = 1.0;
+    else
+      s = -1.0;
+
+    //................   start k loop   ......................................
+    // look for a bin k which may compensate the content of bin j
+    for (Int_t k=j-1; k >= 1; k--)
+    {
+      w = histcp->GetBinContent(k);
+      if ( fabs(w) < eps ) continue;
+      if (w >= 0.0) 
+        t = 1.0;
+      else
+        t = -1.0;
+
+      if (s==t) continue;
+
+      x = v + w;
+      if (x >= 0.0) 
+        u = 1.0;
+      else
+        u = -1.0;
+
+      if (u == s)
+      {
+        arg = -w;
+        g(k-1, j-1)   = arg;
+        cout << "k-1, j-1, arg = " << k-1 << ",  " << j-1 << ",  " 
+             << arg << endl;
+
+
+        //......................................
+        // this is for checking the procedure
+        if (arg < 0.0)
+        {
+          a = histap->GetBinContent(k);
+          histap->SetBinContent(k, a+arg);
+          a = histap->GetBinContent(j);
+          histap->SetBinContent(j, a-arg);
+        }
+        else
+        {
+          b = histbp->GetBinContent(k);
+          histbp->SetBinContent(k, b-arg);
+          b = histbp->GetBinContent(j);
+          histbp->SetBinContent(j, b+arg);
+        }
+        //......................................
+
+        histcp->SetBinContent(k, 0.0);
+        histcp->SetBinContent(j,   x);
+
+        //......................................
+        // redefine v 
+        v = histcp->GetBinContent(j);
+        if ( fabs(v) < eps ) break;
+        if (v >= 0.0) 
+          s = 1.0;
+        else
+          s = -1.0;
+        //......................................
+       
+        continue;
+      }
+
+      arg = v;
+      g(k-1, j-1) = arg;
+      cout << "k-1, j-1, arg = " << k-1 << ",  " << j-1 << ",  " 
+           << arg << endl;
+
+      //......................................
+      // this is for checking the procedure
+      if (arg < 0.0)
+      {
+        a = histap->GetBinContent(k);
+        histap->SetBinContent(k, a+arg);
+        a = histap->GetBinContent(j);
+        histap->SetBinContent(j, a-arg);
+      }
+      else
+      {
+        b = histbp->GetBinContent(k);
+        histbp->SetBinContent(k, b-arg);
+        b = histbp->GetBinContent(j);
+        histbp->SetBinContent(j, b+arg);
+      }
+      //......................................
+
+      histcp->SetBinContent(k,   x);
+      histcp->SetBinContent(j, 0.0);
+
+      break;
+    }
+    //................   end k loop   ......................................
+
+
+}
+  //--------   end j loop   ------------------------------------------------
+  TVector index(N);
+  index.Zero();
+
+  TVector  map(N);
+  Int_t indexold = 0;
+
+  cout << "=========================================================" << endl;
+  for (Int_t k=0; k<N-1; k++)
+  {
+    index(k) = (Double_t)indexold;
+    Int_t add = 0;
+    for (Int_t j=k+1; j<N; j++)
+    { 
+      if (fabs(g(k,j)) > eps)
+      {
+          map(indexold) = g(k, j);
+
+          cout << "k, j, indexold, map = " << k << ",  " << j << ",  "
+             << indexold << ",  " << map(indexold) << endl;;
+
+          indexold += 1;
+          add += 1;
+      }
+    }
+    if (add == 0) index(k) = 0;
+    cout << endl;
+    cout << "index(k), add = " << index(k) << ",  " << add << endl;
+  }
+
+  cout << "=========================================================" << endl;
+  cout << " " << endl;
+
+  //------------------------------------------------------------------------
+
+
+  TCanvas *c1 = new TCanvas("c1","", 600, 900);
+  c1->Divide(2,3);
+
+  c1->cd(1);
+  hista->Draw();
+
+  c1->cd(2);
+  histap->Draw();
+
+  c1->cd(3);
+  histb->Draw();
+
+  c1->cd(4);
+  histbp->Draw();
+
+  c1->cd(5);
+  histc->Draw();
+
+  c1->cd(6);
+  histcp->Draw();
+
+}
+//=========================================================================
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/pedestalstudies.C
===================================================================
--- /tags/Mars-V0.9/macros/pedestalstudies.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/pedestalstudies.C	(revision 9772)
@@ -0,0 +1,504 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+// pedestalstudies.C
+//
+// macro to study the pedestal and pedestalRMS with the number of FADC 
+// slices summed up. 
+//
+/////////////////////////////////////////////////////////////////////////////////
+const TString pedfile = "./20040303_20123_P_NewCalBoxTestLidOpen_E.root";
+
+void pedestalstudies(const TString pedname=pedfile)
+{
+
+  Int_t loops = 13;
+  Int_t stepsize = 2;
+
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+  
+  TArrayF *hmeandiffinn = new TArrayF(loops);
+  TArrayF *hrmsdiffinn  = new TArrayF(loops);
+  TArrayF *hmeandiffout = new TArrayF(loops);
+  TArrayF *hrmsdiffout  = new TArrayF(loops);
+  TArrayF *hmeaninn  = new TArrayF(loops);
+  TArrayF *hmeanout  = new TArrayF(loops);
+  TArrayF *hrmsinn   = new TArrayF(loops);
+  TArrayF *hrmsout   = new TArrayF(loops);
+  TArrayF *hmuinn    = new TArrayF(loops);
+  TArrayF *hmuout    = new TArrayF(loops);
+  TArrayF *hsigmainn = new TArrayF(loops);
+  TArrayF *hsigmaout = new TArrayF(loops);
+
+  TArrayF *hmeandiffinnerr = new TArrayF(loops);
+  TArrayF *hrmsdiffinnerr  = new TArrayF(loops);
+  TArrayF *hmeandiffouterr = new TArrayF(loops);
+  TArrayF *hrmsdiffouterr  = new TArrayF(loops);
+  TArrayF *hmeaninnerr  = new TArrayF(loops);
+  TArrayF *hmeanouterr  = new TArrayF(loops);
+  TArrayF *hrmsinnerr   = new TArrayF(loops);
+  TArrayF *hrmsouterr   = new TArrayF(loops);
+  TArrayF *hmuinnerr    = new TArrayF(loops);
+  TArrayF *hmuouterr    = new TArrayF(loops);
+  TArrayF *hsigmainnerr = new TArrayF(loops);
+  TArrayF *hsigmaouterr = new TArrayF(loops);
+
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(500);
+  display->Resize(850,700);
+      
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  for (Int_t samples=2;samples<stepsize*loops+1;samples=samples+stepsize)
+    {
+
+      plist.Reset();
+      tlist.Reset();
+      
+      //
+      // Now setup the tasks and tasklist for the pedestals:
+      // ---------------------------------------------------
+      //
+      
+      MReadMarsFile read("Events", pedname);
+      read.DisableAutoScheme();
+      
+      MGeomApply      geomapl;
+      //
+      // Set the extraction range higher:
+      //		
+      MExtractFixedWindow sigcalc;
+      sigcalc.SetRange(0,samples-1,0,1);
+  
+      MPedCalcPedRun pedcalc;
+      pedcalc.SetRange(0,samples-1,0,0);
+      pedcalc.SetWindowSize((Int_t)sigcalc.GetNumHiGainSamples());
+
+      //
+      // Additionally to calculating the pedestals, 
+      // you can fill histograms and look at them
+      //
+      MFillH fill("MHPedestalCam", "MExtractedSignalCam");
+      fill.SetNameTab(Form("%s%2d","PedCam",samples));
+
+      tlist.AddToList(&read);
+      tlist.AddToList(&geomapl);
+      tlist.AddToList(&sigcalc);
+      tlist.AddToList(&pedcalc);
+      tlist.AddToList(&fill);
+      
+      MGeomCamMagic      geomcam;
+      MPedestalCam       pedcam;
+      MBadPixelsCam      badcam;
+      badcam.AsciiRead("badpixels.dat");  
+      
+      MHPedestalCam      hpedcam;
+      MCalibrationPedCam cpedcam;
+      
+      plist.AddToList(&geomcam);
+      plist.AddToList(&pedcam);
+      plist.AddToList(&hpedcam);
+      plist.AddToList(&cpedcam);
+      plist.AddToList(&badcam);
+      
+      //
+      // Create and setup the eventloop
+      //
+      MEvtLoop evtloop;
+      
+      evtloop.SetParList(&plist);
+      evtloop.SetDisplay(display);
+
+      //
+      // Execute first analysis
+      //
+      if (!evtloop.Eventloop())
+        return;
+      
+      // 
+      // Look at one specific pixel, after all the histogram manipulations:
+      //
+      /*
+      MHGausEvents &hpix = hpedcam.GetAverageHiGainArea(0);
+      hpix.DrawClone("fourierevents");
+      
+      MHGausEvents &lpix = hpedcam.GetAverageHiGainArea(1);
+      lpix.DrawClone("fourierevents");
+
+      hpedcam[170].DrawClone("fourierevents");
+  
+      */
+
+      MHCamera dispped0  (geomcam, "Ped;Pedestal",       "Mean per Slice");
+      MHCamera dispped2  (geomcam, "Ped;PedestalRms",    "RMS per Slice");
+      MHCamera dispped4  (geomcam, "Ped;Mean",           "Fitted Mean per Slice");
+      MHCamera dispped6  (geomcam, "Ped;Sigma",          "Fitted Sigma per Slice");
+      MHCamera dispped9  (geomcam, "Ped;DeltaPedMean",   "Rel. Diff. Mean per Slice (Fit-Calc.)");
+      MHCamera dispped11 (geomcam, "Ped;DeltaRmsSigma",  "Rel. Diff. RMS per Slice (Fit-Calc.)");
+  
+      dispped0.SetCamContent(  pedcam, 0);
+      dispped0.SetCamError(    pedcam, 1);
+      dispped2.SetCamContent(  pedcam, 2);
+      dispped2.SetCamError(    pedcam, 3);
+      
+      dispped4.SetCamContent( hpedcam, 0);
+      dispped4.SetCamError(   hpedcam, 1);
+      dispped6.SetCamContent( hpedcam, 2);
+      dispped6.SetCamError(   hpedcam, 3);
+      dispped9.SetCamContent( hpedcam, 5);
+      dispped9.SetCamError(   hpedcam, 6);
+      dispped11.SetCamContent(hpedcam, 8);
+      dispped11.SetCamError(  hpedcam, 9);
+  
+      dispped0.SetYTitle("Calc. Pedestal per slice [FADC counts]");
+      dispped2.SetYTitle("Calc. Pedestal RMS per slice [FADC counts]");
+      dispped4.SetYTitle("Fitted Mean per slice [FADC counts]");
+      dispped6.SetYTitle("Fitted Sigma per slice [FADC counts]");
+      dispped9.SetYTitle("Rel. Diff. Pedestal per slice Fit-Calc [1]");
+      dispped11.SetYTitle("Rel. Diff. Pedestal RMS per slice Fit-Calc [1]");
+
+
+      // Histogram values
+      TCanvas &b1 = display->AddTab(Form("%s%d","MeanRMS",samples));
+      b1.Divide(4,3);
+
+      CamDraw(b1,dispped0,1,4,*hmeaninn,*hmeanout,*hmeaninnerr,*hmeanouterr,samples,stepsize);
+      CamDraw(b1,dispped2,2,4,*hrmsinn,*hrmsout,*hrmsinnerr,*hrmsouterr,samples,stepsize);  
+      CamDraw(b1,dispped4,3,4,*hmuinn,*hmuout,*hmuinnerr,*hmuouterr,samples,stepsize);
+      CamDraw(b1,dispped6,4,4,*hsigmainn,*hsigmaout,*hsigmainnerr,*hsigmaouterr,samples,stepsize); 
+      
+      display->SaveAsGIF(3*((samples-1)/stepsize)+2,Form("%s%d","MeanRmsSamples",samples));
+
+      // Differences
+      TCanvas &c4 = display->AddTab(Form("%s%d","RelDiff",samples));
+      c4.Divide(2,3);
+      
+      CamDraw(c4,dispped9,1,2,*hmeandiffinn,*hmeandiffout,*hmeandiffinnerr,*hmeandiffouterr,samples,stepsize);
+      CamDraw(c4,dispped11,2,2,*hrmsdiffinn,*hrmsdiffout,*hrmsdiffinnerr,*hrmsdiffouterr,samples,stepsize); 
+
+      display->SaveAsGIF(3*((samples-1)/stepsize)+3,Form("%s%d","RelDiffSamples",samples));
+
+    }
+
+  /*
+  TF1 *logg = new TF1("logg","[1]+TMath::Log(x-[0])",1.,30.,2);
+  logg->SetParameters(1.,3.5);
+  logg->SetParLimits(0,-1.,3.);
+  logg->SetParLimits(1,-1.,7.);
+  logg->SetLineColor(kRed);
+  */
+
+  TCanvas *canvas = new TCanvas("PedstudInner","Pedestal Studies Inner Pixels",600,900);
+  canvas->Divide(2,3);
+  canvas->cd(1);
+
+  TGraphErrors *gmeaninn = new TGraphErrors(hmeaninn->GetSize(),
+                                            CreateXaxis(hmeaninn->GetSize(),stepsize),hmeaninn->GetArray(),
+                                            CreateXaxisErr(hmeaninnerr->GetSize(),stepsize),hmeaninnerr->GetArray());
+  gmeaninn->Draw("A*");
+  gmeaninn->SetTitle("Calculated Mean per Slice Inner Pixels");
+  gmeaninn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeaninn->GetYaxis()->SetTitle("Calculated Mean per slice");
+  //  gmeaninn->Fit("pol0");
+  //  gmeaninn->GetFunction("pol0")->SetLineColor(kGreen);
+  //  //  gmeaninn->Fit(logg);
+
+  canvas->cd(2);
+
+  TGraphErrors *gmuinn = new TGraphErrors(hmuinn->GetSize(),
+                                          CreateXaxis(hmuinn->GetSize(),stepsize),hmuinn->GetArray(),
+                                          CreateXaxisErr(hmuinnerr->GetSize(),stepsize),hmuinnerr->GetArray());
+  gmuinn->Draw("A*");
+  gmuinn->SetTitle("Fitted Mean per Slice Inner Pixels");
+  gmuinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmuinn->GetYaxis()->SetTitle("Fitted Mean per Slice");
+  //  gmuinn->Fit("pol0");
+  //  gmuinn->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmuinn->Fit(logg);
+
+
+  canvas->cd(3);
+
+  TGraphErrors *grmsinn = new TGraphErrors(hrmsinn->GetSize(),
+                                           CreateXaxis(hrmsinn->GetSize(),stepsize),hrmsinn->GetArray(),
+                                           CreateXaxisErr(hrmsinnerr->GetSize(),stepsize),hrmsinnerr->GetArray());
+  grmsinn->Draw("A*");
+  grmsinn->SetTitle("Calculated Rms per Slice Inner Pixels");
+  grmsinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsinn->GetYaxis()->SetTitle("Calculated Rms per Slice");
+  //  //grmsinn->Fit("pol2");
+  //  //grmsinn->GetFunction("pol2")->SetLineColor(kRed);
+  //  grmsinn->Fit(logg);
+
+  canvas->cd(4);
+
+  TGraphErrors *gsigmainn = new TGraphErrors(hsigmainn->GetSize(),
+                                             CreateXaxis(hsigmainn->GetSize(),stepsize),hsigmainn->GetArray(),
+                                             CreateXaxisErr(hsigmainnerr->GetSize(),stepsize),hsigmainnerr->GetArray());
+  gsigmainn->Draw("A*");
+  gsigmainn->SetTitle("Fitted Sigma per Slice Inner Pixels");
+  gsigmainn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gsigmainn->GetYaxis()->SetTitle("Fitted Sigma per Slice");
+  //  //  gsigmainn->Fit("pol2");
+  //  //  gsigmainn->GetFunction("pol2")->SetLineColor(kRed);
+  //  gsigmainn->Fit(logg);
+
+  canvas->cd(5);
+
+  TGraphErrors *gmeandiffinn = new TGraphErrors(hmeandiffinn->GetSize(),
+                                                CreateXaxis(hmeandiffinn->GetSize(),stepsize),hmeandiffinn->GetArray(),
+                                                CreateXaxisErr(hmeandiffinnerr->GetSize(),stepsize),hmeandiffinnerr->GetArray());
+  gmeandiffinn->Draw("A*"); 
+  gmeandiffinn->SetTitle("Rel. Difference  Mean per Slice Inner Pixels");
+  gmeandiffinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeandiffinn->GetYaxis()->SetTitle("Rel. Difference Mean per Slice");
+  //  //gmeandiffinn->Fit("pol2");
+  //  //gmeandiffinn->GetFunction("pol2")->SetLineColor(kBlue);
+  //  gmeandiffinn->Fit(logg);
+
+
+  canvas->cd(6);
+
+  TGraphErrors *grmsdiffinn = new TGraphErrors(hrmsdiffinn->GetSize(),
+                                               CreateXaxis(hrmsdiffinn->GetSize(),stepsize),hrmsdiffinn->GetArray(),
+                                               CreateXaxisErr(hrmsdiffinnerr->GetSize(),stepsize),hrmsdiffinnerr->GetArray());
+  grmsdiffinn->Draw("A*");
+  grmsdiffinn->SetTitle("Rel. Difference Sigma per Slice-RMS Inner Pixels");
+  grmsdiffinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsdiffinn->GetYaxis()->SetTitle("Rel. Difference Sigma per Slice-RMS");
+  //  //grmsdiffinn->Fit("pol2");
+  //  //grmsdiffinn->GetFunction("pol2")->SetLineColor(kBlue);
+  //  grmsdiffinn->Fit(logg);
+
+  canvas->SaveAs("PedestalStudyInner.root");
+  canvas->SaveAs("PedestalStudyInner.ps");
+
+  TCanvas *canvas2 = new TCanvas("PedstudOut","Pedestal Studies Outer Pixels",600,900);
+  canvas2->Divide(2,3);
+  canvas2->cd(1);
+
+  TGraphErrors *gmeanout = new TGraphErrors(hmeanout->GetSize(),
+                                            CreateXaxis(hmeanout->GetSize(),stepsize),hmeanout->GetArray(),
+                                            CreateXaxisErr(hmeanouterr->GetSize(),stepsize),hmeanouterr->GetArray());
+  gmeanout->Draw("A*");
+  gmeanout->SetTitle("Calculated Mean per Slice Outer Pixels");
+  gmeanout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeanout->GetYaxis()->SetTitle("Calculated Mean per Slice");
+  //  gmeanout->Fit("pol0");
+  //  gmeanout->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmeanout->Fit(logg);
+
+  canvas2->cd(2);
+
+  TGraphErrors *gmuout = new TGraphErrors(hmuout->GetSize(),
+                                          CreateXaxis(hmuout->GetSize(),stepsize),hmuout->GetArray(),
+                                          CreateXaxisErr(hmuouterr->GetSize(),stepsize),hmuouterr->GetArray());
+  gmuout->Draw("A*");
+  gmuout->SetTitle("Fitted Mean per Slice Outer Pixels");
+  gmuout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmuout->GetYaxis()->SetTitle("Fitted Mean per Slice");
+  //  gmuout->Fit("pol0");
+  //  gmuout->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmuout->Fit(logg);
+
+  canvas2->cd(3);
+
+  TGraphErrors *grmsout = new TGraphErrors(hrmsout->GetSize(),
+                                           CreateXaxis(hrmsout->GetSize(),stepsize),hrmsout->GetArray(),
+                                           CreateXaxisErr(hrmsouterr->GetSize(),stepsize),hrmsouterr->GetArray());
+  grmsout->Draw("A*");
+  grmsout->SetTitle("Calculated Rms per Slice Outer Pixels");
+  grmsout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsout->GetYaxis()->SetTitle("Calculated Rms per Slice");
+  //  //grmsout->Fit("pol2");
+  //  //grmsout->GetFunction("pol2")->SetLineColor(kRed);
+  //  grmsout->Fit(logg);
+
+  canvas2->cd(4);
+
+  TGraphErrors *gsigmaout = new TGraphErrors(hsigmaout->GetSize(),
+                                             CreateXaxis(hsigmaout->GetSize(),stepsize),hsigmaout->GetArray(),
+                                             CreateXaxisErr(hsigmaouterr->GetSize(),stepsize),hsigmaouterr->GetArray());
+  gsigmaout->Draw("A*");
+  gsigmaout->SetTitle("Fitted Sigma per Slice Outer Pixels");
+  gsigmaout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gsigmaout->GetYaxis()->SetTitle("Fitted Sigma per Slice");
+  //  //gsigmaout->Fit("pol2");
+  //  //gsigmaout->GetFunction("pol2")->SetLineColor(kRed);
+  //  gsigmaout->Fit(logg);
+
+
+  canvas2->cd(5);
+
+  TGraphErrors *gmeandiffout = new TGraphErrors(hmeandiffout->GetSize(),
+                                                CreateXaxis(hmeandiffout->GetSize(),stepsize),hmeandiffout->GetArray(),
+                                                CreateXaxisErr(hmeandiffouterr->GetSize(),stepsize),hmeandiffouterr->GetArray());
+  gmeandiffout->Draw("A*");
+  gmeandiffout->SetTitle("Rel. Difference  Mean per Slice Outer Pixels");
+  gmeandiffout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeandiffout->GetYaxis()->SetTitle("Rel. Difference Mean per Slice");
+  //  //gmeandiffout->Fit("pol2");
+  //w  //gmeandiffout->GetFunction("pol2")->SetLineColor(kBlue);
+  //  gmeandiffout->Fit(logg);
+
+  canvas2->cd(6);
+
+  TGraphErrors *grmsdiffout = new TGraphErrors(hrmsdiffout->GetSize(),
+                                               CreateXaxis(hrmsdiffout->GetSize(),stepsize),hrmsdiffout->GetArray(),
+                                               CreateXaxisErr(hrmsdiffouterr->GetSize(),stepsize),hrmsdiffouterr->GetArray());
+  grmsdiffout->Draw("A*");
+  grmsdiffout->SetTitle("Rel. Difference Sigma per Slice-RMS Outer Pixels");
+  grmsdiffout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsdiffout->GetYaxis()->SetTitle("Rel. Difference Sigma per Slice-RMS");
+  //  //grmsdiffout->Fit("pol2");
+  //  //grmsdiffout->GetFunction("pol2")->SetLineColor(kBlue);
+  //  grmsdiffout->Fit(logg);
+
+
+  canvas2->SaveAs("PedestalStudyOuter.root");
+  canvas2->SaveAs("PedestalStudyOuter.ps");
+
+
+}
+
+
+void CamDraw(TCanvas &c, MHCamera &cam, Int_t i, Int_t j, TArrayF &a1, TArrayF &a2, 
+             TArrayF &a1err, TArrayF &a2err, Int_t samp, Int_t stepsize)
+{
+
+  c.cd(i);
+  MHCamera *obj1=(MHCamera*)cam.DrawCopy("hist");
+  obj1->SetDirectory(NULL);
+  
+  c.cd(i+j);
+  obj1->Draw();
+  ((MHCamera*)obj1)->SetPrettyPalette();
+
+  c.cd(i+2*j);
+  TH1D *obj2 = (TH1D*)obj1->Projection();
+  obj2->SetDirectory(NULL);
+  
+  //      obj2->Sumw2();
+  obj2->Draw();
+  obj2->SetBit(kCanDelete);
+  
+  const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+  const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+  const Double_t integ = obj2->Integral("width")/2.5066283;
+  const Double_t mean  = obj2->GetMean();
+  const Double_t rms   = obj2->GetRMS();
+  const Double_t width = max-min;
+  
+  if (rms == 0. || width == 0. )
+    return;
+  
+  TArrayI s0(6);
+  s0[0] = 6;
+  s0[1] = 1;
+  s0[2] = 2;
+  s0[3] = 3;
+  s0[4] = 4;
+  s0[5] = 5;
+  
+  TArrayI inner(1);
+  inner[0] = 0;
+  
+  TArrayI outer(1);
+  outer[0] = 1;
+      
+  // Just to get the right (maximum) binning
+  TH1D *half[2];
+  half[0] = obj1->ProjectionS(s0, inner, "Inner");
+  half[1] = obj1->ProjectionS(s0, outer, "Outer");
+
+  half[0]->SetDirectory(NULL);
+  half[1]->SetDirectory(NULL);
+  
+  for (int i=0; i<2; i++)
+    {
+      half[i]->SetLineColor(kRed+i);
+      half[i]->SetDirectory(0);
+      half[i]->SetBit(kCanDelete);
+      half[i]->Draw("same");
+      half[i]->Fit("gaus","Q+");
+
+      if (i==0)
+        {
+          a1[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParameter(1);
+          a1err[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParError(1);
+          if (a1err[(samp-1)/stepsize] > 3.)
+            a1err[(samp-1)/stepsize] = 1.;
+        }
+     if (i==1)
+       {
+         a2[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParameter(1);
+         a2err[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParError(1);
+          if (a2err[(samp-1)/stepsize] > 3.)
+            a2err[(samp-1)/stepsize] = 1.;
+       }
+    }
+  
+  
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Create the x-axis for the event graph
+//
+Float_t *CreateXaxis(Int_t n, Int_t step)
+{
+
+  Float_t *xaxis = new Float_t[n];
+
+  for (Int_t i=0;i<n;i++)
+    xaxis[i] = 2. + step*i;
+
+  return xaxis;
+                 
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Create the x-axis for the event graph
+//
+Float_t *CreateXaxisErr(Int_t n, Int_t step)
+{
+
+  Float_t *xaxis = new Float_t[n];
+
+  for (Int_t i=0;i<n;i++)
+    xaxis[i] = step/2.;
+
+  return xaxis;
+                 
+}
Index: /tags/Mars-V0.9/macros/pedestalvstime.C
===================================================================
--- /tags/Mars-V0.9/macros/pedestalvstime.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/pedestalvstime.C	(revision 9772)
@@ -0,0 +1,138 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void ProcessFile(TString fname, Int_t idx)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    MGeomApply geomapl;
+
+    MCerPhotAnal2 ncalc;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&ncalc);
+
+    MHPixVsTime hist1(idx, "Pedestal");
+    MHPixVsTime hist2(idx, "PedestalRMS");
+    hist2.SetType(1);
+    plist.AddToList(&hist1);
+    plist.AddToList(&hist2);
+
+    MFillH fill1("Pedestal",    "MPedestalCam");
+    MFillH fill2("PedestalRMS", "MPedestalCam");
+    tlist.AddToList(&fill1);
+    tlist.AddToList(&fill2);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(2,2);
+
+    c->cd(1);
+    TGraph &g1 = hist1.GetGraph();
+    TH1 *h1 = g1.GetHistogram();
+    h1->SetXTitle("Time [au]");
+    h1->SetYTitle("P [au]");
+    g1.DrawClone("A*");
+
+    c->cd(2);
+    TH1F h1f("Pedestal", "Pedestals", 21, 46, 56);
+    h1f.SetXTitle("P");
+    h1f.SetYTitle("Counts");
+    for (int i=0;i<g1.GetN(); i++)
+        h1f.Fill(g1.GetY()[i]);
+    ((TH1F*)h1f.DrawCopy())->Fit("gaus");
+
+    c->cd(3);
+    TGraph &g2 = hist2.GetGraph();
+    TH1 *h2 = g2.GetHistogram();
+    h2->SetXTitle("Time [au]");
+    h2->SetYTitle("P_{rms} [au]");
+    g2.DrawClone("A*");
+
+    c->cd(4);
+    TH1F h2f("PedestalRMS", "Pedestals RMS", 26, 0, 3.5);
+    h2f.SetXTitle("P_{rms}");
+    h2f.SetYTitle("Counts");
+    for (int i=0;i<g2.GetN(); i++)
+        h2f.Fill(g2.GetY()[i]);
+    ((TH1F*)h2f.DrawCopy())->Fit("gaus");
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+void pedestalvstime(Int_t idx=0, const char *dirname=".")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "raw*.root", -1);
+
+    TString fname;
+    while (1)
+    {
+        fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname, idx);
+        return;
+    }
+}
Index: /tags/Mars-V0.9/macros/pedphotcalc.C
===================================================================
--- /tags/Mars-V0.9/macros/pedphotcalc.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/pedphotcalc.C	(revision 9772)
@@ -0,0 +1,541 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Josep  Flix,  01/2004 <mailto:jflix@ifae.es>
+!              Javier Rico,  01/2004 <mailto:jrico@ifae.es>
+!              Markus Gaug,  03/2004 <mailto:markus@ifae.es>
+!
+!   (based on bootcampstandardanalysis.C by Javier López)
+!
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  pedphotcalc.C
+//
+//  This macro is an example of the use of MPedPhotCalc. It computes
+//  the pedestal mean and rms from pedestal files undergoing the
+//  signal extraction + calibration chain, in units of photons. It
+//  produces plots of the relevant computed quantities.
+//
+//  Needs as arguments the run number of a pedestal file ("*_P_*.root"), 
+//  one of a calibration file ("*_C_*.root").
+//  performs the pedestal calculation, the calibration 
+/// constants calculation and the calibration of the pedestals. 
+//
+//  The TString inpath has to be set correctly.
+//
+//  The macro searches for the pulser colour which corresponds to the calibration
+//  run number. If the run number is smaller than 20000, pulser colour "CT1" 
+//  is assumed, otherwise, it searches for the strings "green", "blue", "uv" or 
+//  "ct1" in the filenames. If no colour or multiple colours are found, the 
+//  execution is aborted.  
+//
+////////////////////////////////////////////////////////////////////////////////////
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MJPedestal.h"
+#include "MJCalibration.h"
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MGeomCamMagic.h"
+#include "MEvtLoop.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+#include "MExtractedSignalCam.h"
+#include "MExtractSlidingWindow.h" 
+#include "MExtractFixedWindow.h" 
+#include "MCerPhotEvt.h"
+#include "MCalibrateData.h"
+#include "MPedPhotCalc.h"
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+#include "MHCamera.h"
+#include "MRunIter.h"
+#include "MDirIter.h"
+#include "MStatusDisplay.h"
+#include "MHCamera.h"
+
+#include "TTimer.h"
+#include "TString.h"
+#include "TCanvas.h"
+#include "TStyle.h"
+#include "TF1.h"
+#include "TLegend.h"
+
+#include <iostream.h>
+#include "Getline.h"
+
+const TString inpath = "/mnt/Data/rootdata/CrabNebula/2004_02_10/";
+const Int_t dpedrun  = 14607;
+const Int_t dcalrun1 = 14608;
+const Int_t dcalrun2 = 0;
+const Bool_t usedisplay = kTRUE;
+
+
+
+void DrawProjection(MHCamera *obj1, Int_t fit) 
+{
+    TH1D *obj2 = (TH1D*)obj1->Projection(obj1->GetName());
+    obj2->SetDirectory(0);
+    obj2->Draw();
+    obj2->SetBit(kCanDelete);
+    gPad->SetLogy();
+
+    if (obj1->GetGeomCam().InheritsFrom("MGeomCamMagic"))
+    {
+        TArrayI s0(3);
+        s0[0] = 6;
+        s0[1] = 1;
+        s0[2] = 2;
+
+        TArrayI s1(3);
+        s1[0] = 3;
+        s1[1] = 4;
+        s1[2] = 5;
+
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TH1D *half[4];
+        half[0] = obj1->ProjectionS(s0, inner, "Sector 6-1-2 Inner");
+        half[1] = obj1->ProjectionS(s1, inner, "Sector 3-4-5 Inner");
+        half[2] = obj1->ProjectionS(s0, outer, "Sector 6-1-2 Outer");
+        half[3] = obj1->ProjectionS(s1, outer, "Sector 3-4-5 Outer");
+
+        for (int i=0; i<4; i++)
+        {
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->Draw("same");
+        }
+    }
+
+    const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+    const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+    const Double_t integ = obj2->Integral("width")/2.5066283;
+    const Double_t mean  = obj2->GetMean();
+    const Double_t rms   = obj2->GetRMS();
+    const Double_t width = max-min;
+
+    if (rms==0 || width==0)
+        return;
+
+    const TString dgausformula("([0]-[3])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])"
+                               "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])");
+
+    TF1 *f=0;
+    switch (fit)
+    {
+        // FIXME: MAYBE add function to TH1?
+    case 0:
+        f = new TF1("sgaus", "gaus(0)", min, max);
+        f->SetLineColor(kYellow);
+        f->SetBit(kCanDelete);
+        f->SetParNames("Area", "#mu", "#sigma");
+        f->SetParameters(integ/rms, mean, rms);
+        f->SetParLimits(0, 0,   integ);
+        f->SetParLimits(1, min, max);
+        f->SetParLimits(2, 0,   width/1.5);
+        obj2->Fit(f, "QLRM");
+        break;
+
+    case 1:
+        f = new TF1("dgaus", dgausformula, min, max);
+        f->SetLineColor(kYellow);
+        f->SetBit(kCanDelete);
+        f->SetParNames("A_{tot}", "#mu_{1}", "#sigma_{1}", "A_{2}", "#mu_{2}", "#sigma_{2}");
+        f->SetParameters(integ,         (min+mean)/2, width/4,
+                         integ/width/2, (max+mean)/2, width/4);
+        // The left-sided Gauss
+        f->SetParLimits(0, integ-1.5,      integ+1.5);
+        f->SetParLimits(1, min+(width/10), mean);
+        f->SetParLimits(2, 0,              width/2);
+        // The right-sided Gauss
+        f->SetParLimits(3, 0,    integ);
+        f->SetParLimits(4, mean, max-(width/10));
+        f->SetParLimits(5, 0,    width/2);
+        obj2->Fit(f, "QLRM");
+        break;
+
+    default:
+        obj2->Fit("gaus", "Q");
+        obj2->GetFunction("gaus")->SetLineColor(kYellow);
+        break;
+    }
+}
+
+void CamDraw(TCanvas &c, Int_t x, Int_t y, MHCamera &cam1, Int_t fit)
+{
+    c.cd(x);
+    gPad->SetBorderMode(0);
+    MHCamera *obj1=(MHCamera*)cam1.DrawCopy("hist");
+
+    c.cd(x+y);
+    gPad->SetBorderMode(0);
+    obj1->Draw();
+
+    c.cd(x+2*y);
+    gPad->SetBorderMode(0);
+    DrawProjection(obj1, fit);
+}
+
+void pedphotcalc(const Int_t prun=dpedrun, // pedestal file
+                 const Int_t crun1=dcalrun1, const Int_t crun2=dcalrun2 // calibration file(s)
+                 )
+{
+
+  MExtractFixedWindow extractor;
+  
+  MRunIter pruns;
+  MRunIter cruns;
+
+  pruns.AddRun(prun,inpath);
+
+  if (crun2==0)
+    cruns.AddRun(crun1,inpath);
+  else
+    cruns.AddRuns(crun1,crun2,inpath);
+
+  //
+  // Now setup the tasks and tasklist for the pedestals:
+  // ---------------------------------------------------
+  //
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  MStatusDisplay   *display = NULL;
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MJPedestal pedloop;
+  pedloop.SetInput(&pruns);
+  if (usedisplay)
+    {
+      display = new MStatusDisplay;
+      display->SetUpdateTime(3000);
+      display->Resize(850,700);
+      display->SetBit(kCanDelete);
+      pedloop.SetDisplay(display);
+    }
+  
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Process())
+    return;
+
+  MPedestalCam pedcam = pedloop.GetPedestalCam();
+
+  /****************************/
+  /* SECOND LOOP: CALIBRATION */
+  /****************************/
+  
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MJCalibration     calloop;
+  calloop.SetInput(&cruns);
+  //
+  // Use as signal extractor MExtractSignal:
+  //
+  calloop.SetExtractor(&extractor);
+  //
+  // The next two commands are for the display:
+  //
+  if (usedisplay)
+    {
+      calloop.SetDisplay(display);
+      calloop.SetDataCheck();
+    }
+  
+  cout << "***********************************" << endl;
+  cout << "** COMPUTING CALIBRATION FACTORS **" << endl;
+  cout << "***********************************" << endl;
+
+  if (!calloop.Process(pedcam))
+    return;
+  
+  MCalibrationChargeCam &calcam = calloop.GetCalibrationCam();
+  MCalibrationQECam     &qecam  = calloop.GetQECam();
+
+  /************************************************************************/
+  /* THIRD LOOP: PEDESTAL COMPUTATION USING EXTRACTED SIGNAL (IN PHOTONS) */
+  /************************************************************************/
+  
+  // Create an empty Parameter List and an empty Task List
+  MParList  plist3;  
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+
+  // containers
+  MCerPhotEvt    photcam;
+  MPedPhotCam    pedphotcam;
+  MExtractedSignalCam extedsig;
+  
+  plist3.AddToList(&geomcam);
+  plist3.AddToList(&pedcam );
+  plist3.AddToList(&calcam );
+  plist3.AddToList(&qecam  );
+  plist3.AddToList(&photcam);
+  plist3.AddToList(&extedsig);
+  plist3.AddToList(&pedphotcam);
+  
+  //tasks
+  MReadMarsFile read3("Events");
+  read3.DisableAutoScheme();
+  static_cast<MRead&>(read3).AddFiles(pruns);  
+
+  MCalibrateData  photcalc;
+  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);
+  MPedPhotCalc    pedphotcalc;  
+
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&extractor);
+  tlist3.AddToList(&photcalc);
+  tlist3.AddToList(&pedphotcalc);
+  
+  // Create and execute eventloop
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+    
+  cout << "*************************************************************" << endl;
+  cout << "** COMPUTING PEDESTALS USING EXTRACTED SIGNAL (IN PHOTONS) **" << endl;
+  cout << "*************************************************************" << endl;
+  
+  if (!evtloop3.Eventloop())  
+    return;  
+  tlist3.PrintStatistics();
+
+  /**********************/
+  /* PRODUCE NICE PLOTS */
+  /**********************/
+
+  if (usedisplay)
+    {
+      
+      MHCamera disp0(geomcam, "MPedPhotCam;ped", "Pedestals");
+      MHCamera disp1(geomcam, "MPedPhotCam;rms", "Sigma Pedestal");
+      
+      disp0.SetCamContent(pedphotcam, 0);
+      disp0.SetCamError  (pedphotcam, 1);
+      
+      disp1.SetCamContent(pedphotcam, 1);
+      
+      disp0.SetYTitle("Pedestal signal [photons]");
+      disp1.SetYTitle("Pedestal signal RMS [photons]");
+      
+      //
+      // Display data
+      //
+      TCanvas &c1 = display->AddTab("PedPhotCam");
+      c1.Divide(2,3);
+      
+      CamDraw(c1, 1, 2, disp0, 0);
+      CamDraw(c1, 2, 2, disp1, 1);
+      
+    }
+  
+
+#if 0
+  const UShort_t npix = 577;
+
+  // declare histograms
+  // pedestals
+  TH1F* pedhist    = new TH1F("pedhist","Pedestal",npix,0,npix);
+  TH1F* pedrmshist = new TH1F("pedrmshist","Pedestal RMS",npix,0,npix);
+  TH1F* peddist    = new TH1F("peddist","Pedestal",100,0,20);
+  TH1F* pedrmsdist = new TH1F("pedrmsdist","Pedestal RMS",100,0,15);
+  
+  // calibration factors
+  TH1F* calhist    = new TH1F("calhist","Calibration factors",npix,0,npix);
+  TH1F* caldist    = new TH1F("caldist","Calibration factors",100,0,1);
+  TH1F* qehist     = new TH1F("qehist", "Quantrum efficiencies",npix,0,npix);
+  TH1F* qedist     = new TH1F("qedist", "Quantrum efficiencies",100,0,1);
+
+  // pedestal signals
+  TH1F* pedphothist    = new TH1F("pedphothist","Pedestal Signal",npix,0,npix);
+  TH1F* pedphotrmshist = new TH1F("pedphotrmshist","Pedestal Signal RMS",npix,0,npix);
+  TH1F* pedphotdist    = new TH1F("pedphotdist","Pedestal Signal",100,-0.4,0.4);
+  TH1F* pedphotrmsdist = new TH1F("pedphotrmsdist","Pedestal Signal RMS",100,0,25);
+
+  // fill histograms
+  for(int i=0;i<npix;i++)
+    {
+      MCalibrationChargePix &calpix = (MCalibrationChargePix&)calcam[i];
+      MCalibrationQEPix     &qepix  = (MCalibrationQEPix&)    qecam[i];
+
+      const Float_t ped        = pedcam[i].GetPedestal();
+      const Float_t pedrms     = pedcam[i].GetPedestalRms();
+      const Float_t cal        = calpix.GetMeanConvFADC2Phe();
+      const Float_t qe         = qepix .GetQECascadesFFactor();
+      const Float_t pedphot    = pedphotcam[i].GetMean();
+      const Float_t pedphotrms = pedphotcam[i].GetRms();
+
+      pedhist->Fill(i,ped);
+      peddist->Fill(ped);
+      pedrmshist->Fill(i,pedrms);
+      pedrmsdist->Fill(pedrms);
+
+      calhist->Fill(i,cal);
+      caldist->Fill(cal);
+      qehist->Fill(i,qe);
+      qedist->Fill(qe);
+
+      pedphothist->Fill(i,pedphot);
+      pedphotdist->Fill(pedphot);
+      pedphotrmshist->Fill(i,pedphotrms);
+      pedphotrmsdist->Fill(pedphotrms);
+    }
+
+  // Draw
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  TCanvas* canvas = new TCanvas("canvas","pedphotcalc.C", 0, 100, 650, 800);
+  canvas->SetBorderMode(0);    // Delete the Canvas' border line     
+  canvas->cd();
+
+  canvas->Divide(2,5);
+
+  // draw pedestal histo
+  canvas->cd(1);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+
+  pedhist->SetStats(kFALSE);
+  pedhist->GetXaxis()->SetTitle("Pixel SW Id");
+  pedhist->GetYaxis()->SetTitle("Pedestal (ADC counts)");
+  pedrmshist->SetStats(kFALSE);
+  pedrmshist->SetLineColor(2);
+  pedhist->Draw();
+  pedrmshist->Draw("same");
+
+  TLegend* leg1 = new TLegend(.14,.68,.39,.88);
+  leg1->SetHeader("");
+  leg1->AddEntry(pedhist,"Pedestal","L");
+  leg1->AddEntry(pedrmshist,"Pedestal RMS","L");
+  leg1->SetFillColor(0);
+  leg1->SetLineColor(0);
+  leg1->SetBorderSize(0);
+  leg1->Draw();
+     
+  // draw pedestal distribution
+  canvas->cd(2);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  peddist->GetXaxis()->SetTitle("Pedestal (ADC counts)");
+  pedrmsdist->SetLineColor(2);
+  peddist->Draw();
+  pedrmsdist->Draw("same");
+
+  TLegend* leg2 = new TLegend(.14,.68,.39,.88);
+  leg2->SetHeader("");
+  leg2->AddEntry(pedhist,"Pedestal","L");
+  leg2->AddEntry(pedrmshist,"Pedestal RMS","L");
+  leg2->SetFillColor(0);
+  leg2->SetLineColor(0);
+  leg2->SetBorderSize(0);
+  leg2->Draw();
+
+  // draw calibration histo
+  canvas->cd(3);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  calhist->GetXaxis()->SetTitle("Pixel SW Id");
+  calhist->SetMaximum(1);
+  calhist->SetMinimum(0);
+  calhist->GetYaxis()->SetTitle("Calibration factor (phe/ADC count)");
+  calhist->SetStats(kFALSE);
+  calhist->Draw();
+
+  // draw calibration distribution
+  canvas->cd(4);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  caldist->GetXaxis()->SetTitle("Calibration factor (phe/ADC count)");
+  caldist->Draw();
+
+  // draw qe histo
+  canvas->cd(5);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  qehist->GetXaxis()->SetTitle("Pixel SW Id");
+  qehist->SetMaximum(1);
+  qehist->SetMinimum(0);
+  qehist->GetYaxis()->SetTitle("Quantum efficiency for cascades");
+  qehist->SetStats(kFALSE);
+  qehist->Draw();
+
+  // draw qe distribution
+  canvas->cd(6);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  qedist->GetXaxis()->SetTitle("Quantum efficiency for cascades");
+  qedist->Draw();
+
+  // draw pedestal signal histo
+  canvas->cd(7);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  pedphothist->GetXaxis()->SetTitle("Pixel SW Id");
+  pedphothist->GetYaxis()->SetTitle("Pedestal signal (photons)");
+  pedphothist->SetStats(kFALSE);
+  pedphothist->Draw();
+
+  // draw pedestal signal distribution
+  canvas->cd(8);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  pedphotdist->GetXaxis()->SetTitle("Pedestal signal (photons)");
+  pedphotdist->Draw();
+
+  // draw pedestal signal rms histo
+  canvas->cd(9);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  pedphotrmshist->GetXaxis()->SetTitle("Pixel SW Id");
+  pedphotrmshist->GetYaxis()->SetTitle("Pedestal signal rms (photons)");
+  pedphotrmshist->SetStats(kFALSE);
+  pedphotrmshist->Draw();
+
+  // draw pedestal signal rms distribution
+  canvas->cd(10);
+  gPad->cd();
+  gPad->SetBorderMode(0);
+  pedphotrmsdist->GetXaxis()->SetTitle("Pedestal signal rms (photons)");
+  pedphotrmsdist->Draw();
+
+  canvas->SaveAs("pedphotcalc.root");
+
+#endif
+}
Index: /tags/Mars-V0.9/macros/pedvsevent.C
===================================================================
--- /tags/Mars-V0.9/macros/pedvsevent.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/pedvsevent.C	(revision 9772)
@@ -0,0 +1,214 @@
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// Author(s): S.C. Commichau,  Javier Rico, 12/2003                        //
+//                                                                         //
+// Macro to generate pedestal vs time (event) plot for a single pixel      //
+//                                                                         // 
+/////////////////////////////////////////////////////////////////////////////
+
+
+const Int_t default_pixel = 1 ;
+
+void pedvsevent(Int_t pixel = default_pixel, 
+		TString pname = "/disc02/Data/rootdata/Miscellaneous/2003_11_29/20031128_03118_P_Park-camera-closed_E.root")
+{
+
+    TH1F* Pedestal    = new TH1F("Pedestal","Pedestals",100,0,20);
+    TH1F* PedestalRMS = new TH1F("PedestalRMS","Pedestal RMS",100,0,10);
+  
+    //Create an empty parameter list and an empty task list
+    //the tasklist is identified in the eventloop by ist name
+    MParList       plist;
+    MTaskList      tlist;
+
+    //Creates a MPedestalPix object for each pixel, i.e. it is a
+    //storage container for all Pedestal information in the camera
+    MPedestalCam   cam;  
+  
+    plist.AddToList(&cam);
+
+    //MHCamEvent hist;
+    //hist.SetType(1);
+    //plist.AddToList(&hist);
+
+    plist.AddToList(&tlist);
+
+    //Setup task and tasklist for the pedestals
+    MReadMarsFile read("Events", pname);
+    read.DisableAutoScheme();
+
+    //Apply the geometry to geometry dependant containers.
+    //MGeomApply changes the size of the arrays in the containers to a size
+    //matching the number of pixels, eg: MPedestalCam, MBlindPixels
+    //Default geometry is MGeomCamMagic
+    MGeomApply      geomapl;
+   
+    //Task to calculate pedestals
+    MPedCalcPedRun  ped;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&ped); 
+
+    //ped.SetPixel(pixel);
+    //ped.Draw();
+
+    //Create and setup the 1st Eventloop  
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //Execute first analysis, pedestals...
+     if (!tlist.PreProcess(&plist))
+         return;
+
+     const Int_t nevents = read.GetEntries();
+
+     Float_t x[nevents], rms[nevents], mean[nevents];
+
+
+     Int_t i = 0;     
+     while (tlist.Process())
+     {
+	 mean[i] = cam[pixel].GetPedestal();
+         rms[i] = cam[pixel].GetPedestalRms();
+         x[i] = i;
+	 i++; 
+     }
+
+     TGraphErrors* pedgraph = new TGraphErrors(nevents,x,mean,NULL,NULL);
+     TGraphErrors* rmsgraph = new TGraphErrors(nevents,x,rms,NULL,NULL);
+
+	 //plist.FindObject("MPedestalCam")->Print();
+    
+     tlist.PostProcess(); 
+     //if (!evtloop.Eventloop())
+     // return;
+
+     Float_t finalmean = cam[pixel].GetPedestal();
+     Float_t finalrms = cam[pixel].GetPedestalRms();
+   
+     TLine* pedline = new TLine(0,finalmean,nevents,finalmean);
+     TLine* rmsline = new TLine(0,finalrms,nevents,finalrms);
+    
+     //The draw area
+     
+
+
+     gROOT->Reset();
+     gStyle->SetOptStat(0);
+     // Set statistics options, 1111111
+     //                         |||||||
+     //                         ||||||histogram name
+     //                         |||||number of entries
+     //                         ||||mean value
+     //                         |||RMS
+     //                         ||underflows
+     //                         |overflows
+     //                         sum of bins
+     
+     // Set gPad options
+     gStyle->SetFrameBorderMode(0);
+     gStyle->SetPalette(1);
+     // Delete Frames of subCanvas' does not work, hook it Mr. gPad!
+     gStyle->SetFrameBorderSize(0);
+     gStyle->SetCanvasColor(0);
+     gStyle->SetFrameFillColor(0);
+     gStyle->SetTitleFont(102);
+     gStyle->SetTitleFillColor(0);
+     gStyle->SetTitleBorderSize(0);
+     gStyle->SetStatColor(0);
+     gStyle->SetStatBorderSize(0);
+     
+     // Set Canvas options
+     TCanvas *MyC1 = new TCanvas("MyC","Pedestal vs Event", 0, 100, 900, 500);
+     MyC->SetBorderMode(0);    // Delete the Canvas' border line
+     
+     MyC->cd();
+     gPad->SetBorderMode(0);
+     
+     //  TLine* pedline = new TLine(0,finalmean,nevents,finalmean);
+     //TLine* rmsline = new TLine(0,finalrms,nevents,finalrms);
+     
+     tlist.PrintStatistics();
+     //plist.FindObject("MPedestalCam")->Print();
+     Size_t pos = pname.Last('/')+10;
+     TString iRun = TString(pname(pos,5));
+     
+     char str[64];
+     
+     sprintf(str,"Run %s Pixel %d",iRun.Data(),pixel);
+     
+     pedgraph->SetMaximum(30);
+     pedgraph->SetMinimum(0);
+     pedgraph->SetMarkerStyle(24);
+     pedgraph->SetMarkerSize(.5);
+     pedgraph->GetXaxis()->SetTitleFont(102);
+     pedgraph->GetYaxis()->SetTitleFont(102);
+     pedgraph->GetXaxis()->SetLabelFont(102);
+     pedgraph->GetYaxis()->SetLabelFont(102);
+     pedgraph->SetTitle(str); 
+//     pedgraph->SetTitleFont(102);
+     pedgraph->GetYaxis()->SetTitleFont(102);
+     pedgraph->GetXaxis()->SetTitle("Event");
+     pedgraph->GetYaxis()->SetTitle("[FADC Counts]");
+     pedgraph->GetXaxis()->SetLimits(0,nevents-1);
+     
+     rmsgraph->SetMarkerStyle(25);
+     rmsgraph->SetMarkerSize(.5);
+     rmsgraph->SetMarkerColor(8);
+
+     pedline->SetLineColor(2);
+     rmsline->SetLineColor(4);
+     pedline->SetLineWidth(2);
+     rmsline->SetLineWidth(2);
+
+     pedgraph->Draw("AP");
+     rmsgraph->Draw("P");
+     
+     pedline->Draw("same");
+     rmsline->Draw("same");
+     
+     TLegend* leg = new TLegend(.14,.68,.39,.88);
+     leg->SetHeader("");
+     leg->AddEntry(pedgraph,"Event based Pedestal","P");
+     leg->AddEntry(pedline,"Run based Pedestal","L");
+     leg->AddEntry(rmsgraph,"Event based RMS","P");
+     leg->AddEntry(rmsline,"Run based RMS","L");
+     leg->SetFillColor(0);
+     leg->SetLineColor(1);
+     leg->SetBorderSize(1);
+
+
+     leg->Draw("same");
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/pixfirerate.C
===================================================================
--- /tags/Mars-V0.9/macros/pixfirerate.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/pixfirerate.C	(revision 9772)
@@ -0,0 +1,133 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// pixfirerate.C
+// =============
+//
+// This macro can help to  find "hot" pixels firing too often
+// or pixels firing too rarely. It plots camera displays showing how many 
+// times the FADC integral of each pixel has been found to be above pedestal
+// by 10, 20, 50, 100 or 200 ADC counts. As "pedestal"  we now use simply 
+// the signal in the first ADC slice, which seemed reasonable from a first
+// look at the available test data.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void pixfirerate(TString filename="rawfile.root")
+{
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Set update time to 5s
+    // d->SetUpdateTime(5000);
+
+    // Disable online update
+    // d->SetUpdateTime(-1);
+
+    d->SetLogStream(&gLog, kTRUE); // Disables output to stdout
+    gLog.SetOutputFile("status.log", kTRUE); // Enable output to file
+    //gLog.EnableOutputDevice(MLog::eStdout); // Enable output to stdout again
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MTaskList tlist;
+    MParList  plist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile(filename);
+    tlist.AddToList(&read);
+
+    MGeomApply geomapl;
+    tlist.AddToList(&geomapl);
+
+    // A list of threshold which should be displayed. The last entry
+    // MUST be -1.
+    Double_t threshold[] = { 10, 20, 100, 200, -1 };
+
+    Int_t cnt = 0;
+    while (threshold[cnt]>0) cnt++;
+
+    // Create the corresponding fill tasks and containers
+    for (int i=0; i<cnt; i++)
+    {
+        TString name = "Above ";
+        TString num;
+        num += threshold[i];
+        name += num.Strip(TString::kBoth);
+        TString title = "Firerate [%] of pixels with signal > ";
+        title += num.Strip(TString::kBoth);
+
+        MHTriggerLvl0 *trigmap = new MHTriggerLvl0(threshold[i], name, title);
+        MFillH *fillh = new MFillH(trigmap, "MRawEvtData");
+        trigmap->SetBit(kCanDelete);
+        fillh->SetBit(kCanDelete);
+        plist.AddToList(trigmap);
+        tlist.AddToList(fillh);
+    }
+
+    // create the eventloop
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // Make sure the display hasn't been deleted by the user while the
+    // eventloop was running.
+    //
+    if ((d = evtloop.GetDisplay()))
+    {
+        // Save data in a postscriptfile (status.ps)
+        d->SaveAsPS();
+        /*
+         * ----------- Write status to a root file ------------
+         *
+         TFile file("status.root", "RECREATE");
+         d->Write();
+         file.Close();
+         delete d;
+         */
+    }
+
+}
Index: /tags/Mars-V0.9/macros/pixsatrate.C
===================================================================
--- /tags/Mars-V0.9/macros/pixsatrate.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/pixsatrate.C	(revision 9772)
@@ -0,0 +1,120 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// pixfirerate.C
+// =============
+//
+// This macro can help to  find "hot" pixels firing too often
+// or pixels firing too rarely. It plots camera displays showing how many 
+// times the FADC integral of each pixel has been found to be above pedestal
+// by 10, 20, 50, 100 or 200 ADC counts. As "pedestal"  we now use simply 
+// the signal in the first ADC slice, which seemed reasonable from a first
+// look at the available test data.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void pixsatrate(TString filename="rawfile.root")
+{
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Set update time to 5s
+    // d->SetUpdateTime(5000);
+
+    // Disable online update
+    // d->SetUpdateTime(-1);
+
+    d->SetLogStream(&gLog, kTRUE); // Disables output to stdout
+    gLog.SetOutputFile("status.log", kTRUE); // Enable output to file
+    //gLog.EnableOutputDevice(MLog::eStdout); // Enable output to stdout again
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MTaskList tlist;
+    MParList  plist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile(filename);
+    tlist.AddToList(&read);
+
+    MGeomApply geomapl;
+    tlist.AddToList(&geomapl);
+
+    // Create histograms with saturation limits at 254
+    MHTriggerLvl0 trighi(254, "SaturationHi", "Saturation Rate of Hi Gains");
+    MHTriggerLvl0 triglo(254, "SaturationLo", "Saturation Rate of Lo Gains");
+    trighi.SetType(1);
+    triglo.SetType(2);
+
+    // craete fill tasks to fill the histogarms
+    MFillH fillhi(&trighi, "MRawEvtData");
+    MFillH filllo(&triglo, "MRawEvtData");
+    tlist.AddToList(&fillhi);
+    tlist.AddToList(&filllo);
+
+    // create eventloop
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // Make sure the display hasn't been deleted by the user while the
+    // eventloop was running.
+    //
+    if ((d = evtloop.GetDisplay()))
+    {
+        // Save data in a postscriptfile (status.ps)
+        d->SaveAsPS();
+        /*
+         * ----------- Write status to a root file ------------
+         *
+         TFile file("status.root", "RECREATE");
+         d->Write();
+         file.Close();
+         delete d;
+         */
+    }
+
+}
Index: /tags/Mars-V0.9/macros/plot.C
===================================================================
--- /tags/Mars-V0.9/macros/plot.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/plot.C	(revision 9772)
@@ -0,0 +1,146 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Rudy Bock, 5/2002 <mailto:rkb@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+//  plot.C
+//  ======
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+//  The advantage of using Mars histograms instead of root-trees is that
+//  you can fill values in your histogram which is calculated in the
+//  eventloop.
+//
+//  In this particular sample we fill a histogram with the size parameter
+//  of gammas and one with hadron's size. At the end we display both in a
+//  single plot.
+//
+//  The input is a star-macro already conatining image parameters.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void plot()
+{
+    // Create a status display for graphical output
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetLogStream(&gLog);
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+    MReadMarsFile  read("Events", "MC_OFF1.root");
+    read.AddFile("MC_ON1.root");
+    read.DisableAutoScheme();
+    tlist.AddToList(&read);
+
+    // Create a filter for Gammas
+    MFParticleId fgamma("MMcEvt", '=', MMcEvt::kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    // Create a filter for Non-Gammas
+    MFParticleId fhadrons("MMcEvt", '!', MMcEvt::kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    // -------------------------------------------------------
+    //
+    // set the name of the variable to plot and the binning
+    //
+    TString var("Hillas.fSize");
+
+    MBinning bins("BinningMH3X");
+    bins.SetEdgesLog(50, 100, 20000);
+    plist.AddToList(&bins);
+    //
+    // -------------------------------------------------------
+
+    // Create a histogram for the data from gammas and from non-gammas
+    MH3 h3g(var);
+    MH3 h3h(var);
+
+    // Add the histograms to the parameter container list
+    plist.AddToList(&h3g);
+    plist.AddToList(&h3h);
+
+    // Create a task which fills one histogram with the gamma-data
+    MFillH fillg(&h3g);
+    fillg.SetFilter(&fgamma);
+    tlist.AddToList(&fillg);
+
+    // Create a task which fills the other histogram with the non-gamma-data
+    MFillH fillh(&h3h);
+    fillh.SetFilter(&fhadrons);
+    tlist.AddToList(&fillh);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    evtloop.SetDisplay(d);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // Create a pad, check if MStatusDisplay was not closed meanwhile
+    if (evtloop.GetDisplay())
+        d->AddTab("Size");
+    else
+        MH::MakeDefCanvas("Plot");
+
+    // x-axis to logarithmic scale
+    gPad->SetLogx();
+
+    // Setup some style options of the two histograms
+    // and draw a copy of both
+    h3h.GetHist().SetLineColor(kRed);
+    MH::DrawCopy(h3h.GetHist(), h3g.GetHist(), "Size");
+
+    // Now create a new histogram, fill it with the division of the
+    // two histograms and draw also a copy of it
+    TH1D h;
+    MH::SetBinning(&h, &bins);
+    h.Divide(&h3g.GetHist(), &h3h.GetHist());
+    h.SetLineColor(kGreen);
+    h.DrawCopy("same");
+}
Index: /tags/Mars-V0.9/macros/plot2.C
===================================================================
--- /tags/Mars-V0.9/macros/plot2.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/plot2.C	(revision 9772)
@@ -0,0 +1,154 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Rudy Bock, 5/2002 <mailto:rkb@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+//  plot2.C
+//  =======
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+//  The advantage of using Mars histograms instead of root-trees is that
+//  you can fill values in your histogram which is calculated in the
+//  eventloop.
+//
+//  In this particular sample we fill a histogram with width vs length
+//  of gammas and hadrons. At the end we display both in a single plot.
+//
+//  The input is a star-macro already conatining image parameters.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void plot2()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: read in a file created with star.C
+    MReadMarsFile  read("Events", "star.root");
+    read.DisableAutoScheme();
+    tlist.AddToList(&read);
+
+    // Create a filter for the gamma events
+    MFParticleId fgamma("MMcEvt", '=', MMcEvt::kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    // Create a filter for the non-gamma events
+    MFParticleId fhadrons("MMcEvt", '!', MMcEvt::kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    // -------------------------------------------------------
+    //
+    // set the name of the variable to plot and the binning
+    //
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+
+    // Set the variables (converted to deg)
+    TString vary("MHillas.fWidth*MGeomCam.fConvMm2Deg");
+    TString varx("MHillas.fLength*MGeomCam.fConvMm2Deg");
+
+    // Set the binning
+    MBinning binsy("BinningMH3Y");
+    MBinning binsx("BinningMH3X");
+    binsy.SetEdges(11, 0, 0.3);
+    binsx.SetEdges(11, 0, 0.6);
+    plist.AddToList(&binsx);
+    plist.AddToList(&binsy);
+    //
+    // -------------------------------------------------
+
+    // Create two 2D histograms and add them to the list
+    MH3 h3g(varx, vary);
+    MH3 h3h(varx, vary);
+
+    plist.AddToList(&h3g);
+    plist.AddToList(&h3h);
+
+    // Create a task to fill one histogram with the gamma data
+    MFillH fillg(&h3g);
+    fillg.SetFilter(&fgamma);
+    tlist.AddToList(&fillg);
+
+    // Create a task to fill the other one with the non gamma data
+    MFillH fillh(&h3h);
+    fillh.SetFilter(&fhadrons);
+    tlist.AddToList(&fillh);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // Create a default canvas
+    MH::MakeDefCanvas("Plot");
+
+    // setup some style options
+    h3h.GetHist().SetMarkerColor(kRed);
+    h3h.GetHist().SetLineColor(kRed);
+    h3h.GetHist().SetFillStyle(4000);
+
+    // show a contour plot of both histograms
+    h3h.GetHist().DrawCopy("cont3");
+    h3g.GetHist().DrawCopy("cont3same");
+
+    return;
+
+    //
+    // Use this (or something similar) if you want to plot the profile
+    // histograms
+    //
+    TProfile *p = ((TH2&)h3g.GetHist()).ProfileX();
+    p->Draw("same");
+    p->SetBit(kCanDelete);
+
+    TProfile *p = ((TH2&)h3h.GetHist()).ProfileX();
+    p->SetLineColor(kRed);
+    p->SetFillStyle(4000);
+    p->Draw("same");
+    p->SetBit(kCanDelete);
+}
Index: /tags/Mars-V0.9/macros/pointing.C
===================================================================
--- /tags/Mars-V0.9/macros/pointing.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/pointing.C	(revision 9772)
@@ -0,0 +1,462 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// pointing.C
+// ==========
+//
+// This macro is a demonstartion how check plots for a subsystem
+// (here the drive) can be made using Mars.
+//
+// In this case a merpped (root-) cc-report file is read in. The data
+// of the Drive branch is extracted using MReadReports and the
+// Stream-Id feature of MTaskList (second argument in AddToList).
+//
+// The output are plots showing (hopefully) the peformance of the system.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+/*
+ class MGraph : public TGraph
+{
+public:
+    MGraph() : TGraph() {}
+    MGraph(Int_t n) : TGraph(n) {}
+    MGraph(Int_t n, const Int_t *x, const Int_t *y) : TGraph(n, x, y) {}
+    MGraph(Int_t n, const Float_t *x, const Float_t *y) : TGraph(n, x, y) {}
+    MGraph(Int_t n, const Double_t *x, const Double_t *y) : TGraph(n, x, y) {}
+    MGraph(const TVector  &vx, const TVector  &vy) : TGraph(vx, vy) {}
+    MGraph(const TVectorD &vx, const TVectorD &vy) : TGraph(vx, vy) {}
+    MGraph(const TH1 *h) : TGraph(h) {}
+    MGraph(const TF1 *f, Option_t *option="") : TGraph(f, option) {}
+    MGraph(const char *filename, const char *format="%lg %lg", Option_t *option="") : TGraph(filename, format, option) {}
+
+    void Paint(Option_t *o="")
+    {
+        if (!strstr(option,"POL") && !strstr(option,"pol"))
+        {
+            TGraph::Paint(o);
+            return;
+        }
+
+        //gPad->Range(-1.15, -1, 1.15, 1);
+
+        //gPad->Modified();
+        //gPad->Update();
+
+        TView *view = gPad->GetView();
+        if (!view)
+        {
+            cout << "No View!" << endl;
+            return;
+        }
+
+        TGraph gr;
+
+        Double_t *zd=g1->GetY();
+        Double_t *az=g2->GetY();
+
+        TMarker m;
+        m.SetMarkerStyle(kFullDotMedium);
+        m.SetMarkerColor(kRed);
+
+        for (int i=0; i<fN; i++)
+        {
+            const Double_t x = fX[i]/90;
+            const Double_t y = (fY[i]/180+1)*TMath::Pi();
+
+            Double_t r0[3] = { y*cos(x), y*sin(x), 0};
+            Double_t r1[3];
+
+            //gr.SetPoint(gr.GetN(), r0[0], r0[1]);
+
+            view->WCtoNDC(x, y);
+
+            m->PaintMarker(r1[0], r1[1]);
+        }
+    }
+};*/
+
+void pointing()
+{
+    MStatusDisplay *d = new MStatusDisplay;
+    d->SetLogStream(&gLog, kTRUE);
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+    MReadReports read;
+    read.AddTree("Drive");
+    read.AddFile("data/2004_01_26_report.root");
+    read.AddToBranchList("MReportDrive.*");
+
+    MContinue tracking("MReportDrive.fState<3.5");
+
+    // Create a task which fills one histogram with the data
+    //MHVsTime h0("MReportDrive.fMjd");
+    MHVsTime h1("MReportDrive.fNominalZd");
+    MHVsTime h2("MReportDrive.fNominalAz");
+    MHVsTime h3("MReportDrive.fState");
+    MHVsTime h7("MReportDrive.GetAbsError*60");
+    //h0.SetName("Mjd");
+    h1.SetName("Zd");
+    h2.SetName("Az");
+    h3.SetName("State");
+    h7.SetName("ControlDeviation");
+
+    MH3 h4("MReportDrive.GetAbsError*60");
+    h4.SetName("DeltaH");
+
+    MH3 h5("MReportDrive.fNominalZd","MReportDrive.GetAbsError*60");
+    h5.SetName("DeltaHvsZd");
+
+    MBinning bins("BinningDeltaH");
+    bins.SetEdges(18, 0, 3.6);
+
+    MBinning bins2("BinningDeltaHvsZdX");
+    MBinning bins3("BinningDeltaHvsZdY");
+    bins2.SetEdges(90, 0, 90);
+    bins3.SetEdges(18, 0, 3.6);
+
+    plist.AddToList(&bins);
+    plist.AddToList(&bins2);
+    plist.AddToList(&bins3);
+
+    //MFillH fill0(&h0, "MTimeDrive");
+    MFillH fill1(&h1, "MTimeDrive");
+    MFillH fill2(&h2, "MTimeDrive");
+    MFillH fill3(&h3, "MTimeDrive");
+    MFillH fill7(&h7, "MTimeDrive");
+    MFillH fill4(&h4);
+    MFillH fill5(&h5);
+
+    //fill0.SetBit(MFillH::kDoNotDisplay);
+    fill1.SetBit(MFillH::kDoNotDisplay);
+    fill2.SetBit(MFillH::kDoNotDisplay);
+    fill3.SetBit(MFillH::kDoNotDisplay);
+    fill4.SetBit(MFillH::kDoNotDisplay);
+    fill5.SetBit(MFillH::kDoNotDisplay);
+    fill7.SetBit(MFillH::kDoNotDisplay);
+
+    // -----------------------------------------------
+
+    //
+    // Setup Task list
+    //
+    tlist.AddToList(&read);
+    tlist.AddToList(&fill3);
+    tlist.AddToList(&tracking);
+    //tlist.AddToList(&fill0);
+    tlist.AddToList(&fill1);
+    tlist.AddToList(&fill2);
+    tlist.AddToList(&fill4);
+    tlist.AddToList(&fill5);
+    tlist.AddToList(&fill7);
+
+    gStyle->SetOptStat(0);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    evtloop.SetDisplay(d);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+
+    TGraph *g1 = h1.GetGraph();
+    TGraph *g2 = h2.GetGraph();
+
+    TCanvas &c = d->AddTab("Sky");
+    c.cd();
+
+    //Skyplot
+    TPad *p = new TPad("", "",0,0.32,0.5,1);
+    p->Draw();
+    p->cd();
+
+    gPad->SetTheta(-90);
+    gPad->SetPhi(90);
+    gPad->SetBorderMode(0);
+    gStyle->SetOptStat(0);
+
+    TH2F h("pol", "Telescope Tracking Positions on the Sky", 16, 0, 1, 9, 0, 1);
+    h.DrawClone("surf1pol");
+
+    gPad->Modified();
+    gPad->Update();
+
+    TView *view = gPad->GetView();
+    if (!view)
+    {
+        cout << "No View!" << endl;
+        return;
+    }
+
+    Double_t *zd=g1->GetY();
+    Double_t *az=g2->GetY();
+
+    Double_t old[2] = {0,0};
+
+    for (int i=0; i<g1->GetN(); i++)
+    {
+        az[i] += 180;
+        az[i] *= TMath::Pi()/180;
+
+        Double_t x[3] = { zd[i]*cos(az[i])/90, zd[i]*sin(az[i])/90, 0};
+        Double_t y[3];
+
+        view->WCtoNDC(x, y);
+
+        if (old[0]!=0 && old[1]!=1)
+        {
+            TLine *l = new TLine(y[0], y[1], old[0], old[1]);
+            l->SetLineColor(kBlue);
+            l->Draw();
+        }
+
+        TMarker *m = new TMarker(y[0], y[1], kFullDotMedium);
+        m->SetMarkerColor(i==g1->GetN()-1 ? kGreen : kRed);
+        m->Draw();
+
+        old[0] = y[0];
+        old[1] = y[1];
+    }
+
+    c.cd();
+
+
+/*
+    //MJD
+    p = new TPad("", "", 0.6, 0.66, 1, 1);
+    p->Draw();
+    p->cd();
+
+    MHVsTime *hvt=h0.DrawClone("nonew");
+    hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+    hvt->GetGraph()->GetHistogram()->SetXTitle("Time");
+    hvt->GetGraph()->GetHistogram()->SetYTitle("");
+    hvt->GetGraph()->GetHistogram()->SetTitle("MJD vs. Time");
+    hvt->GetGraph()->GetHistogram()->SetStats(0);
+
+    c.cd();
+*/
+
+
+    //Histogram of Control Deviation
+    p = new TPad("", "", 0, 0, 0.5, 0.32);
+    p->Draw();
+    p->cd();
+
+    gPad->SetBorderMode(0);
+    //number of entries, mean, rms and number of overflows in the statusbox
+    gStyle->SetOptStat("emro"); 
+    //gStyle->SetStatFormat(".2g");
+
+    MH3 *mh3 = (MH3*)h4.DrawClone("nonew");
+
+    TAxis *axey = mh3->GetHist()->GetYaxis();
+    TAxis *axex = mh3->GetHist()->GetXaxis();
+    axey->SetLabelSize(0.05);
+    axex->SetLabelSize(0.05);
+    axex->SetTitleSize(0.05);
+    axex->SetTitleOffset(0.85);
+
+    mh3->GetHist()->SetXTitle("\\Delta [arcmin]");
+    mh3->GetHist()->SetYTitle("");
+    mh3->GetHist()->SetTitle("Control deviation of the motors");
+    mh3->GetHist()->SetStats(1);
+
+    //insert lines for 0.5, 1 and 2 SE
+    TLine ln;
+    ln.SetLineColor(kGreen);
+    ln.DrawLine(0.5*360*60/16384., 0, 0.5*360*60/16384., h4.GetHist()->GetMaximum());
+    ln.SetLineColor(kYellow);
+    ln.DrawLine(1.0*360*60/16384., 0, 1.0*360*60/16384., h4.GetHist()->GetMaximum());
+    ln.SetLineColor(kRed);
+    ln.DrawLine(2.0*360*60/16384., 0, 2.0*360*60/16384., h4.GetHist()->GetMaximum());
+
+    c.cd();
+
+
+    //Status of the Drive System vs Time
+    p = new TPad("", "", 0.5, 0.86, 1, 1);
+    p->Draw();
+    p->cd();
+    gPad->SetBorderMode(0);
+    p->SetGridx();
+
+    hvt = (MHVsTime*)h3.DrawClone("nonew");
+    hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+
+    TH1 *hist = hvt->GetGraph()->GetHistogram();
+    TAxis *axey = hist->GetYaxis();
+    TAxis *axex = hist->GetXaxis();
+
+    hist->SetXTitle("Time");
+    hist->SetYTitle("");
+    hist->SetTitle("");//Drive Status vs. Time");
+    hist->SetStats(0);
+    hist->SetMinimum(-0.5);
+    hist->SetMaximum(4.5);
+    axey->Set(5, -0.5, 4.5);
+    axey->SetBinLabel(axey->FindFixBin(0), "Error");
+    axey->SetBinLabel(axey->FindFixBin(1), "Stopped");
+    axey->SetBinLabel(axey->FindFixBin(3), "Moving");
+    axey->SetBinLabel(axey->FindFixBin(4), "Tracking");
+    axey->SetLabelSize(0.15);
+    axex->SetLabelSize(0.08);
+    axex->SetTitleSize(0.09);
+    axex->SetTitleOffset(0.45);
+
+    c.cd();
+
+
+    //Zd vs Time
+    p = new TPad("", "", 0.5, 0.59, 1, 0.86);
+    p->Draw();
+    p->cd();
+    gPad->SetBorderMode(0);
+    p->SetGridx();
+
+    hvt = (MHVsTime*)h1.DrawClone("nonew");
+    hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+
+    TH1 *hist = hvt->GetGraph()->GetHistogram();
+    if (hvt->GetGraph()->GetN())
+    {
+        hist->SetXTitle("Time");
+        hist->SetYTitle("Zd [\\circ]");
+        hist->SetTitle("Zd vs. Time");
+        hist->SetStats(0);
+    }
+
+    TAxis *axey = hist->GetYaxis();
+    TAxis *axex = hist->GetXaxis();
+    axey->SetLabelSize(0.05);
+    axey->SetTitleSize(0.06);
+    axey->SetTitleOffset(0.6);
+    axex->SetLabelSize(0.05);
+    axex->SetTitleSize(0.06);
+    axex->SetTitleOffset(0.85);
+
+    c.cd();
+
+
+    //Controll Deviation vs Time
+    p = new TPad("", "", 0.5, 0.32, 1, 0.59);
+    p->Draw();
+    p->cd();
+    gPad->SetBorderMode(0);
+    p->SetGridx();
+
+    hvt = (MHVsTime*)h7.DrawClone("nonew L");
+    TH1 *hist = hvt->GetGraph()->GetHistogram();
+    hist->SetAxisRange(-0.5, 10.5, "Y");
+    hist->SetXTitle("Time");
+    hist->SetYTitle("\\Delta [arcmin]");
+    hist->SetTitle("Control Deviation vs. Time");
+
+    TAxis *axey = hist->GetYaxis();
+    TAxis *axex = hist->GetXaxis();
+    axey->SetLabelSize(0.05);
+    axey->SetTitleSize(0.06);
+    axey->SetTitleOffset(0.5);
+    axex->SetLabelSize(0.05);
+    axex->SetTitleSize(0.06);
+    axex->SetTitleOffset(0.8);
+
+    //insert lines for 0.5, 1 and 2 SE
+    TLine ln;
+    ln.SetLineColor(kGreen);
+    ln.DrawLine(hist->GetXaxis()->GetXmin(), 0.5*360*60/16384., hist->GetXaxis()->GetXmax(), 0.5*360*60/16384.);
+    ln.SetLineColor(kYellow);
+    ln.DrawLine(hist->GetXaxis()->GetXmin(), 1.0*360*60/16384., hist->GetXaxis()->GetXmax(), 1.0*360*60/16384.);
+    ln.SetLineColor(kRed);
+    ln.DrawLine(hist->GetXaxis()->GetXmin(), 2.0*360*60/16384., hist->GetXaxis()->GetXmax(), 2.0*360*60/16384.);
+
+    c.cd();
+
+
+    //Controll Deviation vs Zd
+    p = new TPad("", "", 0.5, 0, 1, 0.32);
+    p->Draw();
+    p->cd();
+
+    gPad->SetBorderMode(0);
+    gStyle->SetOptStat(1110);
+    gStyle->SetStatFormat(".2g");
+
+    mh3 = (MH3*)h5.DrawClone("nonew");
+
+    TAxis *axey = mh3->GetHist()->GetYaxis();
+    TAxis *axex = mh3->GetHist()->GetXaxis();
+    axey->SetLabelSize(0.05);
+    axey->SetTitleSize(0.05);
+    axey->SetTitleOffset(0.7);
+    axex->SetLabelSize(0.05);
+    axex->SetTitleSize(0.05);
+    axex->SetTitleOffset(0.85);
+
+    mh3->GetHist()->SetYTitle("Zd [\\circ]");
+    mh3->GetHist()->SetXTitle("\\Delta [arcmin]");
+    mh3->GetHist()->SetTitle("Control deviation of the motors");
+    mh3->GetHist()->SetStats(1);
+    mh3->GetHist()->Draw("box");
+
+    //insert lines for 0.5, 1 and 2 SE
+    TLine ln;
+    ln.SetLineColor(kGreen);
+    ln.DrawLine(0, 0.5*360*60/16384., 90, 0.5*360*60/16384.);
+    ln.SetLineColor(kYellow);
+    ln.DrawLine(0, 1.0*360*60/16384., 90, 1.0*360*60/16384.);
+    ln.SetLineColor(kRed);
+    ln.DrawLine(0, 2.0*360*60/16384., 90, 2.0*360*60/16384.);
+
+
+    //d.SaveAsPS(2, "rep_files/CC_2003_11_27_22_31_59-new.ps");
+    //d.SaveAsRoot(2, "~/dev/Mars/rep_files/CC_2003_11_27_22_31_59-new.root");
+
+}
Index: /tags/Mars-V0.9/macros/pointspreadfunction.C
===================================================================
--- /tags/Mars-V0.9/macros/pointspreadfunction.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/pointspreadfunction.C	(revision 9772)
@@ -0,0 +1,853 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Lopez, 12/2003 <mailto:jlopez@ifae.es>
+!   Author(s): Alex Armada,   1/2004 <mailto:armada@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+//------------------------------------------------------------------------- //
+//                                                                          //
+//  This macro fits the dc signal of a star using a two dimension gaussian  //
+//  for each dc measurement. Then the values of parameters of the fit are   //
+//  stored in histograms and shown at the end of the macro.                 //
+//                                                                          //
+//  USAGE:                                                                  //
+//  It has two arguments,                                                   //
+//  1- The first one is the dc file with the tracked star                   //
+//  2- The second one is a continuos light file used to intercalibrate      //
+//     the gain of the photomultipliers.                                    //
+//     (It's possible not to use the calibration file and then the gain     //
+//      of the pmts are supouse to be the same for all of them.             //
+//  3- The third argument is just the number of dc measurements you want    //
+//     analize. If you put 0 it just stops after each fit and show you      //
+//     results.                                                             //
+//                                                                          //
+//--------------------------------------------------------------------------// 
+
+const Int_t numPixels = 577;
+Int_t nPixelsFitted; 
+Bool_t isPixelsFitted[numPixels];
+Float_t z[numPixels],x[numPixels],y[numPixels],errorz[numPixels];
+Float_t chisquare;
+
+//______________________________________________________________________________
+//
+// Function used by Minuit to do the fit
+//
+void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    Int_t i;
+
+//calculate chisquare
+    Double_t chisq = 0;
+    Double_t delta;
+    nPixelsFitted=0;
+    for (i=1;i<numPixels; i++) {
+	if (isPixelsFitted[i])
+	{
+	    if (errorz[i] != 0.0)
+	    {
+		delta  = (z[i]-func(x[i],y[i],par))/errorz[i];
+		chisq += delta*delta;
+		nPixelsFitted++;
+	    }
+	    else
+		cout << "This should never happen errorz[" << i << "] " << errorz[i] << endl;
+	}
+    }
+    f = chisq;
+    chisquare = chisq;
+}
+
+//______________________________________________________________________________
+//
+// The 2D gaussian fucntion used to fit the spot of the star
+//
+Double_t func(float x,float y,Double_t *par)
+{
+    Double_t value=par[0]*TMath::exp(-(x-par[1])*(x-par[1])/(2*par[2]*par[2]))*TMath::exp(-(y-par[3])*(y-par[3])/(2*par[4]*par[4]));
+    return value;
+}
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+	
+        if (input=="q\n")
+            return kFALSE;
+	
+        if (input=="\n")
+            return kTRUE;
+    };
+    
+    return kFALSE;
+}
+
+
+void pointspreadfunction(TString fname, TString clname = "NULL", Int_t userNumLines = 1000)
+{
+
+
+    Float_t currmean[numPixels];
+    Float_t currsquaremean[numPixels];
+    Float_t currrms[numPixels];
+    Float_t meanofcurrmean = 0;
+
+    for (Int_t swpix=0; swpix<numPixels; swpix++)
+    {
+ 	currmean[swpix] = 0.;
+ 	currsquaremean[swpix] = 0.;
+  	currrms[swpix] = 0.;
+    }
+    
+    Int_t numLines=0;
+
+    //containers
+    MGeomCamMagic geomcam;
+    MCameraDC     curr;
+    MCameraDC     currbis;
+    
+    const Float_t conv4mm2deg = geomcam.GetConvMm2Deg();
+
+	 
+    if (clname != "NULL")
+    {
+
+	//
+	// First run over continuos light files to have a DC calibration
+	//
+
+	MParList plist0;
+	
+	MTaskList     tlist0;
+	plist0.AddToList(&tlist0);
+	
+	plist0.AddToList(&geomcam);
+	plist0.AddToList(&curr);
+	
+	MReportFileRead read0(clname);
+	read0.SetHasNoHeader();
+	read0.AddToList("MReportCurrents");
+	
+	tlist0.AddToList(&read0);
+	
+	MEvtLoop evtloop0;
+	evtloop0.SetParList(&plist0);
+	
+	
+	if (!evtloop0.PreProcess())
+	    return;
+	
+	while (tlist0.Process())
+	{
+	    for (Int_t swpix=0; swpix<numPixels; swpix++)
+	    {
+		meanofcurrmean += curr[swpix];
+		currmean[swpix] += curr[swpix];
+		currsquaremean[swpix] += curr[swpix]*curr[swpix];
+	    }
+	    numLines++;
+	}
+	
+	evtloop0.PostProcess();
+	
+	meanofcurrmean /= (numLines*numPixels);
+	for (Int_t swpix=0; swpix<numPixels; swpix++)
+	{
+	    
+	    currmean[swpix] /= numLines;
+	    currsquaremean[swpix] /= numLines;
+	    currrms[swpix] = sqrt(fabs(currsquaremean[swpix] - currmean[swpix]*currmean[swpix]));
+	    
+	    curr[swpix] = currmean[swpix];
+	    currbis[swpix] = currrms[swpix];
+	    
+	    currmean[swpix] /= meanofcurrmean;	
+	    currrms[swpix] /= meanofcurrmean;	
+	    
+	}
+	
+	
+/*     MHCamera display0(geomcam);
+       display0.SetPrettyPalette();
+       display0.Draw();
+       
+	//    curr.Print();
+       display0.SetCamContent(currbis);
+       cout << "PSF>> DC mean values drawn" << endl;
+       // Remove the comments if you want to go through the file
+       // event-by-event:
+       if (!HandleInput())
+       break;
+*/
+    }
+    else
+    {
+	// If you don't use the continuous light this is the currrms[] array 
+	// is the error associated to the currents TMinuit will use.
+	for (Int_t swpix=0; swpix<numPixels; swpix++)
+	{
+	    currmean[swpix] = 1.;
+	    currrms[swpix] = 0.2; 
+	}
+	
+    }
+
+//
+// Now we can run over the dc data to extract the psf. 
+//	
+    const Int_t maxNumLines = 10000;
+	
+    Double_t ux[maxNumLines];
+    Double_t uy[maxNumLines];
+    Double_t sx[maxNumLines];
+    Double_t sy[maxNumLines];
+    Double_t chisqu[maxNumLines];
+    Double_t time[maxNumLines];
+
+    MParList plist;
+
+    MGeomCamMagic geomcam;
+    MCameraDC     curr;
+    MTaskList     tlist;
+
+    plist.AddToList(&geomcam);
+    plist.AddToList(&curr);
+    plist.AddToList(&tlist);
+
+    MReportFileRead read(fname);
+    read.SetHasNoHeader();
+    read.AddToList("MReportCurrents");
+
+    tlist.AddToList(&read);
+    
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    
+    if (!evtloop.PreProcess())
+        return;
+    
+    MHCamera display(geomcam);
+    display.SetPrettyPalette();
+    display.Draw();
+    gPad->SetLogy();
+    gPad->cd(1);
+
+    Double_t amin,edm,errdef;
+    Int_t nvpar,nparx,icstat;
+
+    Double_t max,maxerror;
+    Double_t xmean,xsigma,ymean,ysigma;
+    Double_t xmeanerror,xsigmaerror,ymeanerror,ysigmaerror;
+
+    TEllipse ellipse;
+    ellipse.SetFillStyle(4000);
+    ellipse.SetLineWidth(2);
+    ellipse.SetLineColor(2);
+
+    ellipse.Draw();
+
+    Int_t nbinsxy = 80;
+    Float_t minxy = -600*conv4mm2deg;
+    Float_t maxxy = 600*conv4mm2deg;
+    Float_t fromdegtobin = (maxxy-minxy)/nbinsxy;
+
+    TH2D psfhist("psfhist","",nbinsxy,minxy,maxxy,nbinsxy,minxy,maxxy);
+    psfhist->GetXaxis()->SetTitle("[deg]");
+    psfhist->GetYaxis()->SetTitle("[deg]");
+    psfhist->GetZaxis()->SetTitle("DC [uA]");
+
+    TCanvas *psfcanvas = new TCanvas("psfcanvas","Point Spread Funtion 2D",200,20,900,700);
+
+
+    //
+    // Using the first dc measurement we search the pixels which contains the star and define
+    // an area to be fitted by Minuit which is 3 rings of neightbords around the peak of the star.
+    // 
+
+    tlist.Process();
+
+    Int_t numLines=0;
+    Float_t minDCStar = 6.0;
+
+    Int_t numPixelsInStar = 0;
+    Float_t maxDC = 0;
+    Int_t swpixelmaxDC;
+    
+    Bool_t isPixelsFittedTmp[numPixels];
+    
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+	isPixelsFittedTmp[swpixel] = kFALSE;
+    
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+    {
+	if(curr[swpixel] > maxDC)
+	{
+	    swpixelmaxDC = swpixel;
+	    maxDC = curr[swpixelmaxDC];
+	}
+	
+	if(curr[swpixel]>minDCStar)
+	{
+	    numPixelsInStar++;
+	    isPixelsFitted[swpixel] = kTRUE;
+	}
+	else
+	    isPixelsFitted[swpixel] = kFALSE;
+    }
+    
+    if (numPixelsInStar == 0)
+    {
+	cout << "PSF>> Warning: none pixel over minDCStar(" << minDCStar  << ')' << endl; 
+	return;
+    }
+    
+//1st neighboor ring
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+	if (isPixelsFitted[swpixel])
+	    for(Int_t next=0; next<geomcam[swpixel].GetNumNeighbors(); next++)
+		isPixelsFittedTmp[geomcam[swpixel].GetNeighbor(next)] = kTRUE;
+    
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+	if (isPixelsFittedTmp[swpixel])
+	    isPixelsFitted[swpixel] = kTRUE;
+    
+//2on neighboor ring
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+	if (isPixelsFitted[swpixel])
+	    for(Int_t next=0; next<geomcam[swpixel].GetNumNeighbors(); next++)
+		isPixelsFittedTmp[geomcam[swpixel].GetNeighbor(next)] = kTRUE;
+    
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+	if (isPixelsFittedTmp[swpixel])
+	    isPixelsFitted[swpixel] = kTRUE;
+    
+
+//3rt neighboor ring
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+	if (isPixelsFitted[swpixel])
+	    for(Int_t next=0; next<geomcam[swpixel].GetNumNeighbors(); next++)
+		isPixelsFittedTmp[geomcam[swpixel].GetNeighbor(next)] = kTRUE;
+    
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+	if (isPixelsFittedTmp[swpixel])
+	    isPixelsFitted[swpixel] = kTRUE;
+	      
+   
+    for(Int_t swpixel=1; swpixel<numPixels; swpixel++)
+	curr[swpixel] = (Float_t)isPixelsFitted[swpixel]; 
+    
+/*    MHCamera display0(geomcam);
+    display0.SetPrettyPalette();
+    display0.Draw();
+    
+    display0.SetCamContent(curr);
+    cout << "PSF>> Fitted pixels drawn" << endl;
+    // Remove the comments if you want to go through the file
+    // event-by-event:
+    if (!HandleInput())
+	break;
+*/
+
+    // Minuit initialization
+
+    TMinuit *gMinuit = new TMinuit(7);  //initialize TMinuit with a maximum of 5 params
+    gMinuit->SetFCN(fcn);
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+//    arglist[0] = -1;
+    arglist[0] = 0;
+    gMinuit->mnexcm("SET PRI", arglist ,1,ierflg);
+
+// Set starting values and step sizes for parameters
+    Double_t vstart[5];
+    Double_t step[5];
+    Double_t lowlimit[5] = {minDCStar, -2., 0.05, -2, 0.05};
+    Double_t uplimit[5] = {30., 2., 1., 2., 1.};
+
+    vstart[0] = maxDC;
+    vstart[1] = geomcam[swpixelmaxDC].GetX()*conv4mm2deg;
+    vstart[2] = 30*TMath::Sqrt(numPixelsInStar/2)*conv4mm2deg;
+    vstart[3] = geomcam[swpixelmaxDC].GetY()*conv4mm2deg;
+    vstart[4] = 30*TMath::Sqrt(numPixelsInStar/2)*conv4mm2deg;
+    
+    for(Int_t i=0; i<5; i++)
+    {
+	if (vstart[i] != 0)
+	    step[i] = TMath::Abs(vstart[i]/sqrt(2));
+	else
+	    step[i] = uplimit[i]/2;
+    }
+  
+    gMinuit->mnparm(0, "max", vstart[0], step[0], lowlimit[0], uplimit[0],ierflg);
+    gMinuit->mnparm(1, "xmean", vstart[1], step[1], lowlimit[1], uplimit[1],ierflg);
+    gMinuit->mnparm(2, "xsigma", vstart[2], step[2], lowlimit[2], uplimit[2],ierflg);
+    gMinuit->mnparm(3, "ymean", vstart[3], step[3], lowlimit[3], uplimit[3],ierflg);
+    gMinuit->mnparm(4, "ysigma", vstart[4], step[4], lowlimit[4], uplimit[4],ierflg);
+
+    while (tlist.Process() && numLines < maxNumLines)
+    {
+
+	for (Int_t swpixel=1; swpixel<577; swpixel++)
+	{
+	    
+	    x[swpixel] = geomcam[swpixel].GetX()*conv4mm2deg;
+	    y[swpixel] = geomcam[swpixel].GetY()*conv4mm2deg;
+	    z[swpixel] = curr[swpixel]/currmean[swpixel];
+	    errorz[swpixel] = TMath::Sqrt((curr[swpixel]*currrms[swpixel]/(currmean[swpixel]*currmean[swpixel]))*(curr[swpixel]*currrms[swpixel]/(currmean[swpixel]*currmean[swpixel]))+(0.1)/currmean[swpixel]*(0.1)/currmean[swpixel]);
+
+
+	    psfhist->SetBinContent((Int_t)((x[swpixel]+600*conv4mm2deg)/fromdegtobin),(Int_t)((y[swpixel]+600*conv4mm2deg)/fromdegtobin),z[swpixel]);
+	}
+	
+	psfcanvas->cd(1);
+	psfhist->Draw("lego2");
+	
+// Now ready for minimization step
+	arglist[0] = 500;
+	arglist[1] = 1.;
+	gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);
+
+// Print results
+/*	gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
+	gMinuit->mnprin(3,amin);
+*/
+	gMinuit->GetParameter(0,max,maxerror);
+	gMinuit->GetParameter(1,xmean,xmeanerror);
+	gMinuit->GetParameter(2,xsigma,xsigmaerror);
+	gMinuit->GetParameter(3,ymean,ymeanerror);
+	gMinuit->GetParameter(4,ysigma,ysigmaerror);
+
+/*	cout << endl;
+	cout << "numLine " << numLines << endl; 
+	cout << "max \t" << max <<  " +- " << maxerror << endl;
+	cout << "xmean \t" << xmean << " +- " << xmeanerror << endl;
+	cout << "xsigma \t" << TMath::Abs(xsigma) << " +- " << xsigmaerror << endl;
+	cout << "ymean \t" << ymean << " +- " << ymeanerror << endl;
+	cout << "ysigma \t" << TMath::Abs(ysigma) << " +- " << ysigmaerror << endl;
+	cout << "chisquare/ndof \t" << chisquare/(nPixelsFitted-5) << endl;
+*/
+	
+	chisqu[numLines]=chisquare/(nPixelsFitted-5);
+
+        if(chisqu[numLines]<100.)
+	{
+	    ux[numLines]=xmean;
+	    uy[numLines]=ymean;
+	    sx[numLines]=TMath::Abs(xsigma);
+	    sy[numLines]=TMath::Abs(ysigma);
+	    time[numLines]=numLines;
+
+	    display.SetCamContent(curr);
+	    gPad->cd(1);
+	    ellipse.SetX1(xmean/conv4mm2deg);
+	    ellipse.SetY1(ymean/conv4mm2deg);
+	    ellipse.SetR1(TMath::Abs(xsigma)/conv4mm2deg);
+	    ellipse.SetR2(TMath::Abs(ysigma)/conv4mm2deg);
+
+	    gPad->Modified();
+	    gPad->Update();
+
+	    // Remove the comments if you want to go through the file
+	    //event-by-event:
+	    if (userNumLines>0)
+	    {
+		if (numLines>userNumLines)
+		    break;
+	    }
+	    else
+	    {
+		if (!HandleInput())
+		    break;
+	    }
+	    numLines++;
+	}
+    }
+
+    
+    evtloop.PostProcess();
+
+    //
+    // Draw the ditributions of the sigmas the point spread function
+    //
+
+    cout<<"PSF>> Number of lines "<<numLines<<endl;
+
+    gROOT->Reset();
+    gStyle->SetCanvasColor(0);
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetPadBorderMode(0);
+    gStyle->SetFrameBorderMode(0);
+    gStyle->SetOptStat(00000000);
+
+//
+// Find in the file name the date, run and project name to put it in the title
+//
+
+    Size_t pos = fname.Last('/');
+    TString iRun = TString(fname(pos+24,5));
+    TString iYear = TString(fname(pos+4,4));
+    TString iMonth = TString(fname(pos+9,2));
+    TString iDay = TString(fname(pos+12,2));
+
+    TString iHour = TString(fname(pos+15,2));
+    TString iMin = TString(fname(pos+18,2));
+    TString iSec = TString(fname(pos+21,2));
+
+    Size_t poslast = fname.Last('.');
+    Size_t posfirst = poslast-1;
+    while (fname[posfirst] != '_')
+	posfirst--;
+
+    TString iSource = TString(fname(posfirst+1,poslast-posfirst-1));
+
+    
+    char str[100];
+    
+//    sprintf(str,"Date %s/%s/%s Run %s Source %s",iYear.Data(),iMonth.Data(),iDay.Data(),iRun.Data(),iSource.Data());
+    sprintf(str,"Date %s/%s/%s   StartTime %s:%s:%s   Run %s   Source %s",iYear.Data(),iMonth.Data(),iDay.Data(),iHour.Data(),iMin.Data(),iSec.Data(),iRun.Data(),iSource.Data());
+
+    c1 = new TCanvas("c1",str,0,0,1200,850);
+//    c1 = new TCanvas("c1","Time evolution & distributions",0,0,1200,850);
+    c1->Divide(3,2);
+
+    c1->cd(1);
+
+    TMath math;
+   
+    Double_t minmeanx, maxmeanx;
+    minmeanx = ux[math.LocMin(numLines,ux)];
+    maxmeanx = ux[math.LocMax(numLines,ux)];
+
+    Double_t minmeany, maxmeany;
+    minmeany = uy[math.LocMin(numLines,uy)];
+    maxmeany = uy[math.LocMax(numLines,uy)];
+
+    Double_t minmean, maxmean;
+    minmean = math.Min(minmeanx,minmeany);
+    maxmean = math.Max(maxmeanx,maxmeany);
+
+    Double_t diff;
+    diff = maxmean - minmean;
+    diff = 0.1*diff;
+    minmean = minmean - diff;
+    maxmean = maxmean + diff;
+
+    Double_t mintime, maxtime;
+    mintime = time[math.LocMin(numLines,time)];
+    maxtime = time[math.LocMax(numLines,time)];
+
+    TH2D *h1 = new TH2D("h1","",1,mintime-1,maxtime+1,1,minmean,maxmean);
+    h1->GetXaxis()->SetTitle("Event number");
+    h1->GetYaxis()->SetTitle("mean position (deg)");
+    h1->Draw();
+
+    TGraph *grtimeevolmeanx = new TGraph(numLines,time,ux);
+    grtimeevolmeanx->SetMarkerColor(3);
+    grtimeevolmeanx->SetMarkerStyle(20);
+    grtimeevolmeanx->SetMarkerSize (0.4);
+    grtimeevolmeanx->Draw("P");
+
+    TGraph *grtimeevolmeany = new TGraph(numLines,time,uy);
+    grtimeevolmeany->SetMarkerColor(6);
+    grtimeevolmeany->SetMarkerStyle(24);
+    grtimeevolmeany->SetMarkerSize (0.4);
+    grtimeevolmeany->Draw("P");
+
+    legmeanxy = new TLegend(0.8,0.85,0.95,0.95);
+    legmeanxy.SetTextSize(0.03);
+    legmeanxy.AddEntry(grtimeevolmeanx,"mean x","P");
+    legmeanxy.AddEntry(grtimeevolmeany,"mean y","P");
+    legmeanxy.Draw();
+
+    c1->cd(2);
+
+    TMath math;
+   
+    Double_t minsigmax, maxsigmax;
+    minsigmax = sx[math.LocMin(numLines,sx)];
+    maxsigmax = sx[math.LocMax(numLines,sx)];
+
+    Double_t minsigmay, maxsigmay;
+    minsigmay = sy[math.LocMin(numLines,sy)];
+    maxsigmay = sy[math.LocMax(numLines,sy)];
+
+    Double_t minsigma, maxsigma;
+    minsigma = math.Min(minsigmax,minsigmay);
+    maxsigma = math.Max(maxsigmax,maxsigmay);
+
+    diff = maxsigma - minsigma;
+    diff = 0.1*diff;
+    minsigma = minsigma - diff;
+    maxsigma = maxsigma + diff;
+
+    TH2D *h2 = new TH2D("h2","",1,mintime-1,maxtime+1,1,minsigma,maxsigma);
+    h2->GetXaxis()->SetTitle("Event number");
+    h2->GetYaxis()->SetTitle("PSF Rms (deg)");
+    h2->Draw();
+
+    TGraph* grtimeevolsigmax= new TGraph(numLines,time,sx);
+    grtimeevolsigmax->SetMarkerColor(3);
+    grtimeevolsigmax->SetMarkerStyle(20);
+    grtimeevolsigmax->SetMarkerSize (0.4);
+    grtimeevolsigmax->Draw("P");
+
+    TGraph* grtimeevolsigmay= new TGraph(numLines,time,sy);
+    grtimeevolsigmay->SetMarkerColor(6);
+    grtimeevolsigmay->SetMarkerStyle(24);
+    grtimeevolsigmay->SetMarkerSize (0.4);
+    grtimeevolsigmay->Draw("P");
+
+    legsigmaxy = new TLegend(0.8,0.85,0.95,0.95);
+    legsigmaxy.SetTextSize(0.03);
+    legsigmaxy.AddEntry(grtimeevolsigmax,"sigma x","P");
+    legsigmaxy.AddEntry(grtimeevolsigmay,"sigma y","P");
+    legsigmaxy.Draw();
+   
+    c1->cd(3);
+
+    Double_t minchisqu, maxchisqu;
+
+    minchisqu = chisqu[math.LocMin(numLines,chisqu)];
+    maxchisqu = chisqu[math.LocMax(numLines,chisqu)];
+
+    diff = maxchisqu - minchisqu;
+    diff = 0.1*diff;
+    minchisqu = minchisqu - diff;
+    maxchisqu = maxchisqu + diff;
+
+    TH2D *h3 = new TH2D("h3","",1,mintime-1,maxtime+1,1,minchisqu,maxchisqu);
+    h3->GetXaxis()->SetTitle("Event number");
+    h3->Draw();
+
+    TGraph * grtimeevolchisqu = new TGraph(numLines,time,chisqu);
+    grtimeevolchisqu->SetMarkerColor(215);
+    grtimeevolchisqu->SetMarkerStyle(20);
+    grtimeevolchisqu->SetMarkerSize(0.4);
+    grtimeevolchisqu->Draw("P");
+
+    legchisqu = new TLegend(0.55,0.90,0.95,0.95);
+    legchisqu.SetTextSize(0.03);
+    legchisqu.AddEntry(grtimeevolchisqu,"chi square / ndof","P");
+    legchisqu.Draw();
+
+//***************************************
+
+    const Int_t nbins = 100; 
+  
+    TH1D *xsigmahist = new TH1D("xsigmahist","",nbins,minsigma,maxsigma);
+    TH1D *ysigmahist = new TH1D("ysigmahist","",nbins,minsigma,maxsigma);
+    TH1D *xmeanhist = new TH1D("xmeanhist","",nbins,minmean,maxmean);
+    TH1D *ymeanhist = new TH1D("ymeanhist","",nbins,minmean,maxmean);
+    TH1D *chisquhist = new TH1D("chisquhist","",nbins,minchisqu,maxchisqu);
+
+    for (Int_t i=0; i<numLines; i++)
+    {
+	xsigmahist->Fill(TMath::Abs(sx[i]));
+	ysigmahist->Fill(TMath::Abs(sy[i]));
+	xmeanhist->Fill(ux[i]);
+	ymeanhist->Fill(uy[i]);
+	chisquhist->Fill(chisqu[i]);
+	
+    }
+
+    c1->cd(5);
+
+    TMath math;
+    Double_t maxsigma;
+    Int_t binmaxx, binmaxy;
+    xsigmahist->SetLineColor(3);
+    xsigmahist->SetLineWidth(2);
+    xsigmahist->SetXTitle("RMS [deg]");
+    binmaxx = xsigmahist->GetMaximumBin();
+    binmaxx = xsigmahist->GetBinContent(binmaxx);
+       
+    ysigmahist->SetLineColor(6);
+    ysigmahist->SetLineWidth(2);
+    binmaxy = ysigmahist->GetMaximumBin();
+    binmaxy = ysigmahist->GetBinContent(binmaxy);
+   
+    maxsigma = math.Max(binmaxx,binmaxy);
+    maxsigma += 1;
+
+    xsigmahist->SetMaximum(maxsigma);
+    ysigmahist->SetMaximum(maxsigma);
+    xsigmahist->DrawCopy();
+    ysigmahist->DrawCopy("Same");
+
+    TLegend *legendsigma = new TLegend(.3,.8,.95,.95);
+    legendsigma->SetTextSize(0.03);
+    char xsigmatitle[100];
+    char ysigmatitle[100];
+    sprintf(xsigmatitle,"PSF Rms on X axis -- %5.2f +/- %5.2f deg",xsigmahist->GetMean(),xsigmahist->GetRMS());
+    sprintf(ysigmatitle,"PSF Rms on Y axis -- %5.2f +/- %5.2f deg",ysigmahist->GetMean(),ysigmahist->GetRMS());
+    legendsigma->AddEntry(xsigmahist,xsigmatitle,"F");
+    legendsigma->AddEntry(ysigmahist,ysigmatitle,"F");
+    legendsigma->Draw();
+
+    c1->cd(4);
+   
+    Double_t maxmean;
+
+    xmeanhist->SetLineColor(3);
+    xmeanhist->SetLineWidth(2);
+    xmeanhist->SetXTitle("mean [deg]");
+    binmaxx = xmeanhist->GetMaximumBin();
+    binmaxx = xmeanhist->GetBinContent(binmaxx);
+
+    ymeanhist->SetLineColor(6);
+    ymeanhist->SetLineWidth(2);
+    binmaxy = ymeanhist->GetMaximumBin();
+    binmaxy = ymeanhist->GetBinContent(binmaxy);
+
+    maxmean = math.Max(binmaxx,binmaxy);
+    maxmean += 1;
+
+    xmeanhist->SetMaximum(maxmean);
+    ymeanhist->SetMaximum(maxmean);
+    xmeanhist->DrawCopy();
+    ymeanhist->DrawCopy("Same");
+
+    TLegend *legendmean = new TLegend(.35,.8,.95,.95);
+    legendmean->SetTextSize(0.03);
+    char xmeantitle[100];
+    char ymeantitle[100];
+    sprintf(xmeantitle,"mean on X axis -- %5.2f +/- %5.2f deg",xmeanhist->GetMean(),xmeanhist->GetRMS());
+    sprintf(ymeantitle,"mean on Y axis -- %5.2f +/- %5.2f deg",ymeanhist->GetMean(),ymeanhist->GetRMS());
+    legendmean->AddEntry(xmeanhist,xmeantitle,"F");
+    legendmean->AddEntry(ymeanhist,ymeantitle,"F");
+    legendmean->Draw();
+
+    //meancanvas->Modified();
+    //meancanvas->Update();
+
+    c1->cd(6);
+
+    chisquhist->SetLineColor(215);
+    chisquhist->SetLineWidth(2);
+    chisquhist->SetXTitle("chi square / ndof");
+    TAxis * axis = chisquhist->GetXaxis();
+    axis->SetLabelSize(0.025);
+    chisquhist->DrawCopy();
+    
+    TLegend *legendchisqu = new TLegend(.4,.85,.95,.95);
+    legendchisqu->SetTextSize(0.03);
+    char chisqutitle[100];
+    sprintf(chisqutitle,"chi square / ndof -- %5.2f +/- %5.2f ",chisquhist->GetMean(),chisquhist->GetRMS());
+    legendchisqu->AddEntry(chisquhist,chisqutitle,"F");
+    legendchisqu->Draw();
+    
+    
+    return;
+      
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/readCT1.C
===================================================================
--- /tags/Mars-V0.9/macros/readCT1.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readCT1.C	(revision 9772)
@@ -0,0 +1,134 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 (tbretz@uni-sw.gwdg.de)
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+void readCT1(const char *fname="~/data/CT1_97_on1.dat")
+{
+    MParList plist;
+
+    MHillas      hillas;
+    MHillasExt   hillasext;
+    MNewImagePar newimgpar;
+    MTaskList    tlist;
+
+    plist.AddToList(&hillas);
+    plist.AddToList(&hillasext);
+    plist.AddToList(&newimgpar);
+    plist.AddToList(&tlist);
+
+    MCT1ReadAscii read(fname);
+    MGeomApply    geomapl;
+    MClone        clone("MCerPhotEvt");
+    MImgCleanStd  clean;
+    MHillasCalc   hcalc;
+
+    geomapl.SetGeometry("MGeomCamCT1");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&clone);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.PreProcess())
+        return;
+
+    MGeomCam *geomcam = (MGeomCam*)plist->FindObject("MGeomCam");
+
+    Int_t icount = 0;
+
+    MHCamera display[4];
+    TCanvas c("Events", "Real Events", 600, 600);
+    c.SetBorderMode(0);
+    c.Divide(2,2);
+    for (int i=0; i<4; i++)
+    {
+        display[i].SetGeometry(*geomcam);
+        c.cd(i+1);
+        display[i].Draw();
+        gPad->cd(1);
+        hillas.Draw();
+    }
+
+    // Use this if you don't want the event to be autoscaled
+    //display.SetMinimum(0);
+    //display.SetMaximum(100);
+
+    while ((rc=tlist.Process()))
+    {
+        cout << "Event #" << icount++ << endl;
+
+        MCerPhotEvt *evt = (MCerPhotEvt*)clone.GetClone();
+        if (!evt)      // If skipped due to MInputStreamId
+            continue;
+
+        display[0].SetCamContent(*(MCerPhotEvt*)clone.GetClone());
+        display[1].SetCamContent(*(MCerPhotEvt*)plist.FindObject("MCerPhotEvt"));
+        display[2].SetCamContent(*(MCamEvent*)plist.FindObject("MCameraData"));
+        display[3].SetCamContent(*(MCamEvent*)plist.FindObject("MCameraData"));
+        TArrayF lvl(2);
+        lvl[0] = clean.GetCleanLvl2();
+        lvl[1] = clean.GetCleanLvl1();
+        display[3].SetLevels(lvl);
+
+        for (int i=1; i<=4; i++)
+        {
+            c.GetPad(i)->GetPad(1)->Modified();
+            c.GetPad(i)->GetPad(1)->Update();
+        }
+
+        hillas.Print(*geomcam);
+        hillasext.Print(*geomcam);
+        newimgpar.Print(*geomcam);
+
+        if (!HandleInput())
+            break;
+    } 
+
+    evtloop.PostProcess();
+}
Index: /tags/Mars-V0.9/macros/readCalibration.C
===================================================================
--- /tags/Mars-V0.9/macros/readCalibration.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readCalibration.C	(revision 9772)
@@ -0,0 +1,130 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 05/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  readCalibration.C
+//
+//  Needs as arguments the run number of a calibration file ("*_C_*.root") and 
+//  the run number of the corresponding pedestal file ("*_P_*.root"). 
+//
+//  The TString inpath has to be set correctly.
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+static const TString inpath = ".";
+//
+// the default start calibration run 
+//
+static const Int_t   calrun = 26209;
+//
+// Tell if you want to use the display:
+//
+static Bool_t useDisplay = kFALSE;
+//
+void readCalibration(const Int_t crun=calrun)
+{
+
+  const TString calname  = Form("%s/calib%08d.root", (const char*)inpath,crun);
+
+  if (gSystem->AccessPathName(calname, kFileExists))
+    {
+      cout << "Input file " << calname << " doesn't exist." << endl;
+      return;
+    }
+
+  MStatusDisplay = NULL;
+  
+  if (useDisplay)
+    display = new MStatusDisplay;
+
+  MPedestalCam                 pedcam;
+  MCalibrationChargeCam        chargecam;  
+  MCalibrationQECam            qecam;
+  MCalibrationRelTimeCam       relcam;
+  MBadPixelsCam                badcam;
+
+  cout << "Reading from file: " << calname << endl;
+
+  TFile calfile(calname, "READ");
+  if (chargecam.Read()<=0)
+    {
+      cout << "Unable to read MCalibrationChargeCam from " << calname << endl;
+      return;
+    }
+  if (qecam.Read()<=0)
+    {
+      cout << "Unable to read MCalibrationQECam from " << calname << endl;
+      return;
+    }
+
+  if (calfile.FindKey("MBadPixelsCam"))
+      {
+        MBadPixelsCam bad;
+        if (bad.Read()<=0)
+          {
+            cout << "Unable to read MBadPixelsCam from " << calname << endl;
+            return;
+          }
+        badcam.Merge(bad);
+      }
+  if (relcam.Read()<=0)
+    {
+      cout << "Unable to read MCalibrationRelTimeCam from " << calname << endl;
+      return;
+    }
+
+  cout << "Size of QECam: "      << qecam.GetSize() << endl;
+  cout << "Size of Chargecam: "  << chargecam.GetSize() << endl;
+  cout << "Size of RelTimeCam: "  << relcam.GetSize() << endl;
+
+   MGeomCamMagic geom;
+
+  if (useDisplay)
+    display->Read();
+  
+  for (Int_t i=0; i<relcam.GetSize(); i++)
+  {
+      MCalibrationRelTimePix &rpix = (MCalibrationRelTimePix&)relcam[i];
+      MBadPixelsPix &badpix = badcam[i];
+      if (!badpix.IsUnsuitable())
+        cout << "Number of outliers in time pixel: " << i << ": " << rpix.GetNumPickup()+rpix.GetNumBlackout() << endl;
+  } 
+
+  for (Int_t i=0; i<2; i++)
+  {  
+      TArrayF conv = chargecam.GetAveragedConvFADC2PhotPerArea(geom,qecam,i,&badcam);
+      cout << "Average Conv Factor Area idx: " << i << ":  " << conv[0] << "+-" << conv[1] << endl;
+  }
+
+  for (Int_t i=0; i<qecam.GetSize(); i++)
+    {
+      MCalibrationChargePix &cpix = (MCalibrationChargePix&)chargecam[i];
+      MCalibrationQEPix     &qpix = (MCalibrationQEPix&)    qecam[i];
+      MBadPixelsPix         &bpix  = badcam[i];
+      if (!bpix.IsUnsuitable())
+        cout << "Conversion Factor: " << cpix.GetMeanConvFADC2Phe() / qpix.GetQECascadesFFactor() << endl;
+    }
+
+}
+
Index: /tags/Mars-V0.9/macros/readIPR.C
===================================================================
--- /tags/Mars-V0.9/macros/readIPR.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readIPR.C	(revision 9772)
@@ -0,0 +1,147 @@
+///////////////////////////////////////////////////////////////////////////
+// 
+//    readIPR.C
+//
+//   This macro shows how to read the Individual Pixel Rates from 
+//   a CC report file.
+//
+//   Input: 
+//     - root file obtained merpping a .rep CC file
+//       container: MTriggerIPR
+//
+//   Output:
+//     - a camera display showing the IPRs
+//     - Some histos for checking purposes
+//   
+//   Note: 
+//     a similar macro can be used to read the following trigger containers:
+//     - MTriggerIPR        (Individual Pixel Rates)
+//     - MTriggerCell       (Rate of trigger cells)
+//     - MTriggerBit        (Output Bits from prescaler (before/after presc.)
+//     - MTriggerPrescFact  (Prescaling factors for each bit)
+//     - MTriggerLiveTime   (Values of counters for dead/livetime)
+//
+//    Author(s): Antonio Stamerra. 09/04 <antonio.stamerra@pi.infn.it>
+//
+////////////////////////////////////////////////////////////////////////////
+void readIPR(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // Create the magic geometry
+    MGeomCamMagic geom;
+    plist.AddToList(&geom);
+
+    // First Task: Read ROOT file with Trigger-REPORT data
+    MReadTree read("Trigger", fname);
+    read.DisableAutoScheme();
+
+    tlist.AddToList(&read);
+
+    // Create the container for the IPRs
+    MTriggerIPR ipr;
+    plist.AddToList(&ipr);
+
+    // Create the histo to display the IPRs
+    MHCamEvent IPRhist("IPRhist","IPRs");
+    plist.AddToList(&IPRhist);
+        
+    // create a task to fill a histogram from the container
+    MFillH fillIPR(&IPRhist, "MTriggerIPR");
+    tlist.AddToList(&fillIPR);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute the analysis
+    //
+    if (!evtloop.PreProcess())
+      return;
+    
+    if (!evtloop.Eventloop())
+      return;
+
+    tlist.PrintStatistics();
+
+    //-----------------------------------
+    // Now display the result of the loop
+    //
+
+    // create a MHCamera histo where the sum off all events is filled
+    MHCamera &h = *(MHCamera*)IPRhist.GetHistByName("sum");
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(2, 2);
+
+    MHCamera *disp1=h.Clone();
+    MHCamera *disp2=h.Clone();
+    //MHCamera *disp3=h.Clone();
+    disp2->SetCamContent(h, 1);
+    //disp3->SetCamContent(h, 2);
+
+    disp1->SetYTitle("Rate [Hz]");
+    disp2->SetYTitle("\\sigma_{Rate} [Hz]");
+    //disp3->SetYTitle("\\sigma_{Rate} [%]");
+    disp1->SetName("IPRs;avg");
+    disp2->SetName("IPRs;err");
+    //disp3->SetName("IPRs;rel");
+    disp1->SetTitle("IPRs Average");
+    disp2->SetTitle("IPRs error");
+    //disp3->SetTitle("IPRs relative error");
+
+    c->cd(1);
+    TText text(0.1, 0.95, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.03);
+    text.DrawClone();
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp1->Draw();
+    disp1->SetBit(kCanDelete);
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp2->Draw();
+    disp2->SetBit(kCanDelete);
+    //c->cd(3);
+    //gPad->SetBorderMode(0);
+    //gPad->Divide(1,1);
+    //gPad->cd(1);
+    //gPad->SetLogy();
+    //disp3->Draw();
+    //disp3->SetBit(kCanDelete);
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    disp1->Draw("EPhist");
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    disp2->Draw("Phist");
+    //c->cd(6);
+    //gPad->SetBorderMode(0);
+    //gPad->SetLogy();
+    //disp3->Draw("Phist");
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
Index: /tags/Mars-V0.9/macros/readMagic.C
===================================================================
--- /tags/Mars-V0.9/macros/readMagic.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readMagic.C	(revision 9772)
@@ -0,0 +1,229 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// readMagic.C
+// ===========
+//
+// This is a demonstration program showing how to do particular processing
+// on a single event basis. Here we simply display uncleand und cleand
+// images.
+// Therefor MInteractiveTask is used, which gives you the possibility
+// to develop new tasks without the need of compilation.
+// The input is a merpp raw-data file.
+//
+///////////////////////////////////////////////////////////////////////////
+
+Bool_t HandleInput()
+{
+    // This must be there to get accesss to the GUI while the macro
+    // is still running!
+
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+//
+// Setup the data-members of your 'virtual' class
+//
+MHCamera display[4];
+
+TCanvas   *c;
+MParList  *fParList;
+MTaskList *fTaskList;
+
+//
+// Called like all PreProcess functions of tasks. Get the access to
+// the containers necessary for you.
+//
+Int_t PreProcess(MParList *plist)
+{
+    // Get parameter and tasklist, see Process
+    fParList = plist;
+    fTaskList = (MTaskList*)plist->FindObject("MTaskList");
+
+    // Get camera geoemtry
+    MGeomCam *geomcam = (MGeomCam*)plist->FindObject("MGeomCam");
+
+    // setup canvas and camera-histograms
+    c = new TCanvas("Events", "Real Events", 600, 600);
+    c->SetBorderMode(0);
+    c->Divide(2,2);
+    for (int i=0; i<4; i++)
+    {
+        display[i].SetGeometry(*geomcam);
+        c->cd(i+1);
+        display[i].Draw();
+        gPad->cd(1);
+        plist->FindObject("MHillas")->Draw();
+    }
+    return kTRUE;
+}
+
+//
+// Called like all Process functions of tasks. Process a single
+// event - here display it.
+//
+Int_t Process()
+{
+    // For simplicity we search in the Process function for the
+    // objects. This is deprectaed! Store the pointers to the objects
+    // as data member and get the pointers in PreProcess.
+    MReadMarsFile *read = (MReadMarsFile*)fTaskList->FindObject("MRead");
+    MClone *clone = (MClone*)fTaskList->FindObject("MClone");
+    MImgCleanStd *clean = (MImgCleanStd*)fTaskList->FindObject("MImgCleanStd");
+    MGeomCam *geom = (MGeomCam*)fParList->FindObject("MGeomCam");
+
+    // Ouput event number
+    cout << "Event #" << read->GetNumEntry() << ":" << endl;
+
+    // Fill the data into your camera-histograms
+    display[0].SetCamContent(*(MCerPhotEvt*)clone->GetClone());
+    display[1].SetCamContent(*(MCerPhotEvt*)fParList->FindObject("MCerPhotEvt"));
+    display[2].SetCamContent(*(MCameraData*)fParList->FindObject("MCameraData"));
+    display[3].SetCamContent(*(MCameraData*)fParList->FindObject("MCameraData"));
+
+    // Setup the cleaning level histogram
+    TArrayF lvl(2);
+    lvl[0] = clean->GetCleanLvl2();
+    lvl[1] = clean->GetCleanLvl1();
+    display[3].SetLevels(lvl);
+
+    // Update the display
+    for (int i=1; i<=4; i++)
+    {
+        c->GetPad(i)->GetPad(1)->Modified();
+        c->GetPad(i)->GetPad(1)->Update();
+    }
+
+    // print the data on the console
+    ((MHillas*)fParList->FindObject("MHillas"))->Print(*geom);
+    ((MHillasExt*)fParList->FindObject("MHillasExt"))->Print(*geom);
+    ((MNewImagePar*)fParList->FindObject("MNewImagePar"))->Print(*geom);
+
+    // wait for 'return'
+    return HandleInput();
+}
+
+//
+// Called like all PostProcess functions of tasks. Delete
+// instanciated objects.
+//
+Int_t PostProcess()
+{
+    delete c;
+}
+
+void readMagic(const char *fname="../Proton*.root")
+{
+    // Setup parameter- and tasklist
+    MParList  plist;
+    MTaskList tlist;
+
+    plist.AddToList(&tlist);
+
+    // setup reading task
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    // setup a task making sure that all arrays are resized correctly
+    MGeomApply geomapl;
+
+    // Setup a print task calling TObject::Print
+    MPrint print1("MMcEvt");
+    MPrint print2("MRawEvtHeader");
+    // Skip them if conatainers are not found
+    print1.EnableSkip();
+    print2.EnableSkip();
+
+    // Copy MC pedestals to apropriate conatiners (if MC file)
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    // Calculate signal and pedestal from data (use MCerPhotCalc
+    // in case of MC files)
+    MCerPhotAnal2     ncalc;
+
+    // Blind Pixel Treatment (deprecated, will be replaced by
+    // MBadPixel*)
+    MBlindPixelCalc   blind;
+    blind.SetUseInterpolation();
+
+    // Clone MCerPhotEvt befor eimage cleaning
+    MClone            clone("MCerPhotEvt");
+
+    // Setup image cleaning
+    MImgCleanStd      clean;
+
+    // Setup calculation of Image parameters
+    MHillasCalc       hcalc;
+
+    // Setup intercative task calling the functions defined above
+    MTaskInteractive  mytask;
+
+    mytask.SetPreProcess(PreProcess);
+    mytask.SetProcess(Process);
+
+    // Setup your tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&print1);
+    tlist.AddToList(&print2);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&blind);
+    tlist.AddToList(&clone);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&mytask);
+
+    // Run your analysis
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    // Print statistics information about your loop
+    tlist.PrintStatistics();
+}
+
Index: /tags/Mars-V0.9/macros/readcurrents.C
===================================================================
--- /tags/Mars-V0.9/macros/readcurrents.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readcurrents.C	(revision 9772)
@@ -0,0 +1,90 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+void readcurrents(const char *fname="../currents/dcs_arcturus.dat")
+{
+    MParList plist;
+
+    MGeomCamMagic geomcam;
+    MCameraDC     cur;
+    MTaskList     tlist;
+
+    plist.AddToList(&geomcam);
+    plist.AddToList(&cur);
+    plist.AddToList(&tlist);
+
+    MReportFileRead read(fname);
+    read.SetHasNoHeader();
+    read.AddToList("MReportCurrents");
+
+    tlist.AddToList(&read);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.PreProcess())
+        return;
+
+    MHCamera display(geomcam);
+    display.Draw();
+    gPad->SetLogy();
+
+    int gifcnt = 0;
+
+    while (tlist.Process())
+    {
+        // cur.Print();
+        display.SetCamContent(cur);
+        gPad->GetPad(1)->Modified();
+        gPad->GetPad(1)->Update();
+        // Remove the comments if you want to go through the file
+        // event-by-event:
+        if (!HandleInput())
+            break;
+    } 
+
+    evtloop.PostProcess();
+}
Index: /tags/Mars-V0.9/macros/readin.C
===================================================================
--- /tags/Mars-V0.9/macros/readin.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readin.C	(revision 9772)
@@ -0,0 +1,91 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 (tbretz@uni-sw.gwdg.de)
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+void readin()
+{
+    //
+    // open the file
+    //
+    TFile input("test.root", "READ");
+
+    //
+    // open the Run Header tree
+    //
+    TTree *runtree = (TTree*) input.Get("RunHeaders") ;
+
+    if (!runtree)
+        return;
+
+    cout << " Entries in Tree RunHeaders: " << runtree->GetEntries() << endl ;
+
+    //
+    // create an instance of MRawRunHeader, enable the branch and
+    // read the header, print it
+    //
+    MRawRunHeader *runheader = new MRawRunHeader();
+    runtree->GetBranch("MRawRunHeader")->SetAddress(&runheader);
+    runtree->GetEvent(0);
+    runheader->Print();
+
+    //
+    // open the Data Tree
+    //
+    TTree *evttree = (TTree*) input.Get("Data") ;
+
+    //
+    // 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();
+
+    //
+    // enable the corresponding branches
+    //
+    evttree->GetBranch("MRawEvtHeader")->SetAddress(&evtheader);
+    evttree->GetBranch("MTime")->SetAddress(&evttime);
+    evttree->GetBranch("MRawEvtData")->SetAddress(&evtdata);
+    evttree->GetBranch("MRawCrateArray")->SetAddress(&evtcrate);
+
+    //
+    // loop over all events and print the information
+    //
+    Int_t iEnt = evttree->GetEntries();
+    cout << " Entries in Tree Data: " << iEnt << endl;
+
+    for (Int_t i = 0; i<iEnt; i++)
+    {
+      // readin event with the selected branches
+      evttree->GetEvent(i);
+
+      evtheader->Print();
+      evttime->Print();
+      evtcrate->Print();
+      evtdata->Print();
+    } 
+}
+
+
Index: /tags/Mars-V0.9/macros/readpix.C
===================================================================
--- /tags/Mars-V0.9/macros/readpix.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readpix.C	(revision 9772)
@@ -0,0 +1,97 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 (tbretz@uni-sw.gwdg.de)
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+#include <iomanip>
+
+void readpix()
+{
+    //
+    // open the file
+    //
+    TFile input("delme.root", "READ");
+
+    //
+    // open the Run Header tree
+    //
+    TTree *runtree = (TTree*) input.Get("RunHeaders") ;
+
+    if (!runtree)
+        return;
+
+    cout << " Entries in Tree RunHeaders: " << runtree->GetEntries() << endl ;
+
+    //
+    // create an instance of MRawRunHeader, enable the branch and
+    // read the header, print it
+    //
+    MRawRunHeader *runheader = new MRawRunHeader();
+    runtree->GetBranch("MRawRunHeader")->SetAddress(&runheader);
+    runtree->GetEvent(0);
+    runheader->Print();
+
+    //
+    // open the Data Tree
+    //
+    TTree *evttree = (TTree*) input.Get("Data") ;
+
+    //
+    // create the instances of the data to read in
+    //
+    MRawEvtData *evtdata = new MRawEvtData();
+
+    //
+    // enable the corresponding branches
+    //
+    evttree->GetBranch("MRawEvtData")->SetAddress(&evtdata);
+
+    evttree->GetEvent(0);
+
+    MRawEvtPixelIter pixel(evtdata);
+
+    while (pixel.Next())
+    {
+       
+       cout << "Pixel Nr: " << dec << pixel.GetPixelId() << " ";
+       cout << setfill('0') << endl;
+      
+       cout << "Hi Gains: ";
+       for (int i=0; i<evtdata->GetNumHiGainSamples(); i++)
+	  cout << setw(3) << (UInt_t)pixel.GetHiGainFadcSamples()[i];
+       cout << endl;
+      
+       cout << "Lo Gains: ";
+       if (pixel.IsLoGain())
+	  for (int i=0; i<evtdata->GetNumLoGainSamples(); i++)
+	     cout << setw(3) << (UInt_t)pixel.GetLoGainFadcSamples()[i];
+       cout << endl << endl;
+
+       if (pixel.GetPixelId() == 11)
+	 pixel.Draw();
+    };
+}
+
+
+
+
Index: /tags/Mars-V0.9/macros/readraw.C
===================================================================
--- /tags/Mars-V0.9/macros/readraw.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readraw.C	(revision 9772)
@@ -0,0 +1,95 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+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(fname, "READ");
+
+    //
+    // open the Run Header tree
+    //
+    TTree *runtree = (TTree*) input.Get("RunHeaders") ;
+
+    if (!runtree)
+        return;
+
+    cout << " Entries in Tree RunHeaders: " << runtree->GetEntries() << endl ;
+
+    //
+    // create an instance of MRawRunHeader, enable the branch and
+    // read the header, print it
+    //
+    MRawRunHeader *runheader = new MRawRunHeader();
+    runtree->GetBranch("MRawRunHeader.")->SetAddress(&runheader);
+    runtree->GetEvent(0);
+    runheader->Print();
+
+    //
+    // open the Data Tree
+    //
+    TTree *evttree = (TTree*) input.Get("Events");
+
+    //
+    // create the instances of the data to read in
+    //
+    MRawEvtHeader  *evtheader = 0;
+    MTime          *evttime   = 0;
+    MRawEvtData    *evtdata   = 0;
+    MRawCrateArray *evtcrate  = 0;
+
+    //
+    // enable the corresponding branches
+    //
+    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);
+
+    //
+    // loop over all events and print the information
+    //
+    Int_t iEnt = evttree->GetEntries();
+    cout << " Entries in Tree Data: " << iEnt << endl;
+
+    for (Int_t i = 0; i<iEnt; i++)
+    {
+      // readin event with the selected branches
+      evttree->GetEvent(i);
+
+      evtheader->Print();
+      evtdata->Print();
+
+      // Use this for real data only
+      //evttime->Print();
+      //evtcrate->Print();
+    } 
+}
+
+
Index: /tags/Mars-V0.9/macros/readrep.C
===================================================================
--- /tags/Mars-V0.9/macros/readrep.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readrep.C	(revision 9772)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// This macro demonstrates how to read a central control report file.
+// (rootification, see merpp, too)
+//
+// In a second eventloop it gives an example on how to read such a root file.
+//
+//////////////////////////////////////////////////////////////////////////////
+
+void readrep(const char *fname="CC_2003_11_04_23_53_18.rep")
+{
+    //
+    // Read a report file and write containers into a root file
+    //
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReportFileRead read(fname);
+    tlist.AddToList(&read);
+
+    read.AddToList("DAQ");
+    read.AddToList("Drive");
+    read.AddToList("Camera");
+    read.AddToList("Trigger");
+
+    MWriteRootFile write("test.root");
+    write.AddContainer("MReportCamera",      "Camera");
+    write.AddContainer("MTimeCamera",        "Camera");
+    write.AddContainer("MCameraAUX",         "Camera");
+    write.AddContainer("MCameraCalibration", "Camera");
+    write.AddContainer("MCameraCooling",     "Camera");
+    write.AddContainer("MCameraHV",          "Camera");
+    write.AddContainer("MCameraLV",          "Camera");
+    write.AddContainer("MCameraLids",        "Camera");
+    write.AddContainer("MReportTrigger",     "Trigger");
+    write.AddContainer("MTimeTrigger",       "Trigger");
+    write.AddContainer("MReportDrive",       "Drive");
+    write.AddContainer("MTimeDrive",         "Drive");
+    tlist.AddToList(&write);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // ----------------------------------------------------------------
+    //
+    // Read a report file and write containers into a root file
+    //
+    MTaskList tlist2;
+    plist.Replace(&tlist2);
+
+    // Create a tasklist to process the read events from the Camera tree
+    MTaskList list1("ProcessCamera");
+    MPrint print1("MTimeCamera");
+    list1.AddToList(&print1);
+
+    // Create a tasklist to process the read events from the Drive tree
+    MTaskList list2("ProcessDrive");
+    MPrint print2("MTimeDrive");
+    list2.AddToList(&print2);
+
+    // Tell the reader to read the trees Drive, Trigger and Camera
+    MReadReports read;
+    read.AddTree("Drive");
+    read.AddTree("Trigger");
+    read.AddTree("Camera");
+    //read.AddTree("Events", "MTime."); // for later use!
+
+    // Now (not earlier!) set the file to read!
+    read.AddFile("test.root");
+
+    // First read the events
+    tlist.AddToList(&read);
+    // Process the events from the Camera tree with the task list list1
+    tlist.AddToList(&list1, "Camera");
+    // Process the events from the Camera tree with the task list list2
+    tlist.AddToList(&list2, "Drive");
+
+    // The task lists list1 and list2 are only executed (according to
+    // their stream id - the second argument of AddToList) if a
+    // corresponding event was read and MReadReports has set the stream
+    // id accoringly. MReadReports always sets the stream id to the name
+    // of the tree from which the event was read
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute the eventloop which should print the time-stamps of the subsystem
+    // events from Drive and Camera in the correct order...
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+}
Index: /tags/Mars-V0.9/macros/readrfl.C
===================================================================
--- /tags/Mars-V0.9/macros/readrfl.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/readrfl.C	(revision 9772)
@@ -0,0 +1,106 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+Bool_t JumpTo(MTaskList &tlist, MReadRflFile &read, int runno, int evtno)
+{
+    if (runno<0 || evtno<0)
+        return tlist.Process();
+
+    return read.SearchFor(runno, evtno);
+}
+
+void readrfl(int runno=-1, int evtno=-1, const char *fname="Gamma_zbin0_90_7_50700to50704_w0.rfl")
+{
+    MParList plist;
+
+    MGeomCamMagic geomcam;
+    MRflEvtData   event;
+    MRflEvtHeader evthead;
+    MRflRunHeader runhead;
+    MTaskList     tlist;
+
+    plist.AddToList(&geomcam);
+    plist.AddToList(&event);
+    plist.AddToList(&evthead);
+    plist.AddToList(&runhead);
+    plist.AddToList(&tlist);
+
+    MReadRflFile read(fname);
+    tlist.AddToList(&read);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.PreProcess())
+        return;
+
+    MHCamera display(geomcam);
+    display.Draw();
+    gPad->cd(1);
+    event.Draw();
+
+
+
+    cout << "Runno: " << runno << "  Eventno: " << evtno << endl;
+
+    while (JumpTo(tlist, read, runno, evtno))
+    {
+        runno = -1;
+
+        cout << "Run #" << runhead.GetRunNumber() << "   ";
+        cout << "Event #" << evthead.GetEvtNumber() << endl;
+
+	display.SetCamContent(event);
+
+	gPad->Modified();
+	gPad->Update();
+	
+        if (!HandleInput())
+            break;
+    } 
+
+    evtloop.PostProcess();
+}
Index: /tags/Mars-V0.9/macros/rootlogon.C
===================================================================
--- /tags/Mars-V0.9/macros/rootlogon.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/rootlogon.C	(revision 9772)
@@ -0,0 +1,174 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// rootlogon.C
+// ===========
+//
+// This file is the startup script ("autoexec.bat") executed when root is
+// started. The definition which file to start is done in ".rootrc".
+// There are three files which are automatically processed by root at
+// startup: A systemwide .rootrc, one in your home directory and one
+// in the current directory.
+// So rootlogon.C is correctly executed if your start root from your
+// Mars directory.
+//
+// The script setupts some small environmental things and makes
+// sure that the Mars shared object (libmars.so) is loaded. This shared
+// object gives you access to all Mars features from within the root
+// interpreter.
+//
+// If libmars.so is not found in the current directory we search in the
+// directory given in "MARSSYS" environment variable.
+//
+///////////////////////////////////////////////////////////////////////////
+
+Bool_t isloaded()
+{
+    TString str = gSystem->GetLibraries("libmars.so");
+
+    return !str.IsNull();
+}
+
+void unload()
+{
+    if (!isloaded())
+        return;
+
+    cout << "Unloading 'libmars.so'... " << flush;
+    if (gSystem->Unload("libmars.so"))
+        cout << "error." << endl;
+    else
+        cout << "done." << endl << endl;
+}
+
+bool load(TString &dir)
+{
+    if (isloaded())
+        return;
+
+    cout << "\033[33m\033[1m" << "Loading '" << dir << "libmars.so'... " << "\033[0m" << flush;
+
+    if (dir.IsNull())
+        dir = "./";
+
+    if (gSystem->Load(dir+"libmars.so")!=0)
+    {
+        cout << "\033[33m\033[1m" << "error." << endl;
+        cout << "\033[0m" << endl;
+        return false;
+    }
+    else
+    {
+        MParContainer::Class()->IgnoreTObjectStreamer();
+        MArray::Class()->IgnoreTObjectStreamer();
+        cout << "\033[33m\033[1m" << "done." << endl;
+        cout << "\033[0m" << endl;
+        return true;
+    }
+}
+/*
+void make()
+{
+    unload();
+
+    if (gSystem->Exec("make"))
+    {
+        cout << "Error calling make..." << endl;
+        return;
+    }
+
+    load();
+}
+*/
+void rootlogon()
+{
+    cout << endl;
+
+    const Bool_t fileexist = !gSystem->AccessPathName("libmars.so", kFileExists);
+
+    TString dir = fileexist ? "" : gSystem->Getenv("MARSSYS");
+    if (!dir.IsNull())
+    {
+        cout << "\033[34m\033[1m" << "Searching Mars in " << dir << " (MARSSYS)" << "\033[0m" << endl << endl;
+
+        if (!dir.EndsWith("/"))
+            dir += "/";
+    }
+
+    if (!load(dir))
+        return;
+
+    gInterpreter->AddIncludePath(dir+"macros");
+    gInterpreter->AddIncludePath(dir+"manalysis");
+    gInterpreter->AddIncludePath(dir+"mastro");
+    gInterpreter->AddIncludePath(dir+"mbase");
+    gInterpreter->AddIncludePath(dir+"mbadpixels");
+    gInterpreter->AddIncludePath(dir+"mcamera");
+    gInterpreter->AddIncludePath(dir+"mcalib");
+    gInterpreter->AddIncludePath(dir+"mhcalib");
+    gInterpreter->AddIncludePath(dir+"mdata");
+    gInterpreter->AddIncludePath(dir+"mfbase");
+    gInterpreter->AddIncludePath(dir+"mfileio");
+    gInterpreter->AddIncludePath(dir+"mfilter");
+    gInterpreter->AddIncludePath(dir+"mgeom");
+    gInterpreter->AddIncludePath(dir+"mgui");
+    gInterpreter->AddIncludePath(dir+"mhbase");
+    gInterpreter->AddIncludePath(dir+"mhflux");
+    gInterpreter->AddIncludePath(dir+"mhft");
+    gInterpreter->AddIncludePath(dir+"mhist");
+    gInterpreter->AddIncludePath(dir+"mhistmc");
+    gInterpreter->AddIncludePath(dir+"mhvstime");
+    gInterpreter->AddIncludePath(dir+"mimage");
+    gInterpreter->AddIncludePath(dir+"mjobs");
+    gInterpreter->AddIncludePath(dir+"mmain");
+    gInterpreter->AddIncludePath(dir+"mmc");
+    gInterpreter->AddIncludePath(dir+"mmontecarlo");
+    gInterpreter->AddIncludePath(dir+"mmuon");
+    gInterpreter->AddIncludePath(dir+"mpedestal");
+    gInterpreter->AddIncludePath(dir+"mpointing");
+    gInterpreter->AddIncludePath(dir+"mranforest");
+    gInterpreter->AddIncludePath(dir+"mraw");
+    gInterpreter->AddIncludePath(dir+"mreflector");
+    gInterpreter->AddIncludePath(dir+"mreport");
+    gInterpreter->AddIncludePath(dir+"msignal");
+    gInterpreter->AddIncludePath(dir+"msql");
+    gInterpreter->AddIncludePath(dir+"mstarcam");
+    gInterpreter->AddIncludePath(dir+"mtools");
+    gInterpreter->AddIncludePath(dir+"mtrigger");
+
+    if (TString("linux")==gSystem->GetBuildArch())
+    {
+        TString options = " -O -pipe -Wall -Woverloaded-virtual -fno-exceptions -fPIC ";
+
+        TString s = "cd $BuildDir ; ";
+        s += "g++ -c" + options + "-Iinclude -D_REENTRANT $IncludePath $SourceFiles ; ";
+        s += "g++ $ObjectFiles -shared -Wl,-soname,$LibName.so -O -o $SharedLib";
+        gSystem->SetMakeSharedLib(s);
+    }
+
+    cout << "\033[32m" << "Welcome to the Mars Root environment." << "\033[0m" << endl;
+    cout << endl;
+}
Index: /tags/Mars-V0.9/macros/runbook.C
===================================================================
--- /tags/Mars-V0.9/macros/runbook.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/runbook.C	(revision 9772)
@@ -0,0 +1,150 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// runbook.C
+// =========
+//
+// This is an example macro how to extract the runbook information of
+// a given date from the runbook files.
+//
+// The argument is a date in regexp format, eg.
+//   .x runbook.C("2004-05-1[0-9]")
+//
+// With an MDirIter you can tell the macro which directories and files
+// should be searched.
+//
+// The output are the runbook entries matching your query.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void Wrap(TString &str)
+{
+    // Wrap lines to 80 chars
+    while (str.Length()>80)
+    {
+        TString ss = str(0, 80);
+        Int_t l = ss.Last(' ');
+        if (l<0)
+            break;
+        cout << str(0, l) << endl;
+        str.Remove(0, l);
+    }
+    cout << str << endl;
+}
+
+void ProcessFile(TString fname, TString date)
+{
+    // File processed
+    cout << fname << endl;
+
+    // Open file
+    ifstream fin(fname);
+
+    TString line;
+
+    int i=81;
+
+    TRegexp r0("20[0-2][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]");
+    TRegexp r1(date+" [0-2][0-9]:[0-5][0-9]:[0-5][0-9]");
+
+    int lcnt=0;
+
+    int print = 0;
+
+    while (!fin.eof())
+    {
+        // Read file line by line
+        char *txt=new char[i];
+        fin.getline(txt, i-1);
+
+        if (lcnt++<4)
+            continue;
+
+        if (!fin)
+            txt[i-1]=0;
+
+        line += txt;
+        delete txt;
+
+        if (line.Length()==0)
+        {
+            if (print)
+                cout << endl;
+            continue;
+        }
+
+        if (!fin)
+        {
+            i *= 2;
+            fin.clear();
+            continue;
+        }
+
+        // Check whether line matches regexp
+        if (!line(r0).IsNull())
+            print = !line(r1).IsNull();
+
+        // Wrap lines to 80 chars
+        if (print)
+            Wrap(line);
+        line = "";
+        i=81;
+    }
+    cout << "DONE." << endl;
+}
+
+void runbook(const char *d="20[0-2][0-9]-[0-1][0-9]-[0-3][0-9]")
+{
+    // Regexp to check for valid date
+    TString regexp = "20[0-2][0-9]-[0-1][0-9]-[0-3][0-9]";
+
+    if (regexp!=d)
+    {
+        TRegexp r(regexp);
+
+        TString date=d;
+        if (date(r).IsNull())
+        {
+            cout << "ERROR - Date has wrong format (2003-05-06)" << endl;
+            return;
+        }
+    }
+
+    // Tell which dierctories and files to search
+    MDirIter Next;
+    Next.AddDirectory("/home/MAGIC/online_data/runbook", "CC_*.rbk");
+
+    // Loop over files
+    TString name;
+    while (1)
+    {
+        name=Next();
+        if (name.IsNull())
+            break;
+
+        ProcessFile(name, d);
+    }
+}
Index: /tags/Mars-V0.9/macros/sectorvstime.C
===================================================================
--- /tags/Mars-V0.9/macros/sectorvstime.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sectorvstime.C	(revision 9772)
@@ -0,0 +1,100 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// sectorvstime.C
+// ==============
+//
+// In this example we plot the mean content of the right and left half of
+// camera. As an input we use a class derived from MCamEvent. Here this
+// are dc currents read directly from a camera control report file.
+//
+// The output are two histograms one for each half.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void sectorvstime()
+{
+    // Initialize Mars environment
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // Create Magic camera geometry
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+
+    // Which DC file to read?
+    MReportFileRead read("/data/MAGIC/Period013/cacodata/2004_01_26/dc_2004_01_26_05_35_10_12117_OffMrk421-1.txt");
+    read.SetHasNoHeader();
+    read.AddToList("MReportCurrents");
+
+    // Initialize histogram
+    MHSectorVsTime hist1;
+    hist1.SetNameTime("MTimeCurrents");
+
+    // Define sectors you want to display the mean from
+    TArrayI s0(3);
+    s0[0] = 6;
+    s0[1] = 1;
+    s0[2] = 2;
+
+    // Define area index [0=inner, 1=outer]
+    TArrayI inner(1);
+    inner[0] = 0;
+
+    // Don't call this if you want to have all sectors
+    hist1.SetSectors(s0);
+
+    // Don't call this if you want to have all area indices
+    hist1.SetAreaIndex(inner);
+
+    // Task to fill the histogram
+    MFillH fill1(&hist1, "MCameraDC");
+
+    // Also fill a histogram with the mean of all pixels
+    MHCamEvent hist2;
+    MFillH fill2(&hist2, "MCameraDC");
+
+    // Setup Tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&fill1);
+    tlist.AddToList(&fill2);
+
+    // Setup Eventloop
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    // Run Eventloop
+    if (!evtloop.Eventloop())
+        return;
+
+    // Print some statistics
+    tlist.PrintStatistics();
+
+    // Draw clones of the histograms
+    hist1.DrawClone();
+    hist2.DrawClone();
+}
Index: /tags/Mars-V0.9/macros/spline.C
===================================================================
--- /tags/Mars-V0.9/macros/spline.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/spline.C	(revision 9772)
@@ -0,0 +1,109 @@
+/* This macro is defined as a class for debugging (with CInt) reasons
+
+To use it at the root prompt type:
+
+root [0] .L spline.C
+root [1] TestSpline::sp()
+*/
+/* Example of a spline. You can use it as Test. If you think there are some
+   bugs in the MCubicSpline class please mail to: raducci@fisica.uniud.it */
+
+class TestSpline
+{
+public:
+    void sp();
+};
+
+void TestSpline::sp()
+{
+gROOT -> Reset();
+
+//Here are defined the points. X goes from 0 to 14 (as the fadc slices...)
+//Y are arbitrary values
+
+/* User Change */
+const Byte_t y[]={0x0F,0x10,0x2F,0x7F,0xAA,0x6C,0x14,0x13,0x15,0x18,0x21,0x12,0x11,0x14,0x13};
+/* End user Change */
+const Byte_t x[]={0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E};
+
+/*This cast is needed only to show graphically the output. Don' t needed if you
+  use the spline to calc the arrival times       */
+
+Int_t *newX = new Int_t[15];
+Int_t *newY = new Int_t[15];
+
+for (Int_t i = 0; i < 15; i++)
+{
+    newX[i] = (Int_t) x[i];
+    newY[i] = (Int_t) y[i];
+}
+
+//Canvas to display output
+TCanvas *c = new TCanvas ("c1","c1",800,600);
+
+//Graph containting only the points (displayed as stars)
+TGraph *g1 = new TGraph(15,newX,newY);
+
+g1 -> Draw("A*");
+
+//Spline constructor(specialized for 15 slices using Bytes as values. There exist another constructor.
+MCubicSpline *s = new MCubicSpline(y);
+
+//*spline and *ab are two arrays containing some values evaluated from the spline
+Double_t *spline = new Double_t[139];
+Double_t *ab     = new Double_t[139];
+Double_t step = 0.0;
+
+for (Int_t i = 0; i < 139; i++)
+{
+    spline[i] = s->Eval(step);
+    ab[i] = step;
+    step += 0.1;
+}
+
+//Graph of the sline. The points calculated are joined with a red line. If the stars lie
+//on the red line, then the Spline class is working properly
+TGraph *g2 = new TGraph(139,ab,spline);
+
+g2 -> SetLineColor(2);
+g2 -> Draw("C");
+
+//Maximum and minimum evaluation
+Double_t *mm   = new Double_t[2];
+Double_t *abmm = new Double_t[2];
+
+mm[0] = s->EvalMin();
+mm[1] = s->EvalMax();
+abmm[0] = s->EvalAbMin();
+abmm[1] = s->EvalAbMax();
+
+//Display the max and the min using two black squares. If they lie on the max and min
+//of the red line, then the Spline class is working properly
+
+TGraph *g3 = new TGraph(2,abmm,mm);
+
+g3 -> SetMarkerStyle(21);
+g3 -> Draw("P");
+
+//Test of the Cardan formula. Find the point(abval) where the Spline value is val
+Double_t val = 82.5;
+Double_t abval = s->FindVal(val, abmm[1], 'l');
+
+//Display this point. Again, if it lies on the red line, then we are right.
+//It's a black triangle
+
+TGraph *g4 = new TGraph(1,&abval,&val);
+
+g4 -> SetMarkerStyle(22);
+g4 -> Draw("P");
+
+//Free memory
+s->~MCubicSpline();
+delete [] newX;
+delete [] newY;
+delete [] spline;
+delete [] ab;
+delete [] mm;
+delete [] abmm;
+
+} 
Index: /tags/Mars-V0.9/macros/sql/fillcalib.C
===================================================================
--- /tags/Mars-V0.9/macros/sql/fillcalib.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sql/fillcalib.C	(revision 9772)
@@ -0,0 +1,172 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// fillcalib.C
+// ===========
+//
+// This macro is used to read the calibartion-/callisto-output files.
+// These files are automatically called calib00000.root.
+//
+// From this file the MBadPixelsCam and the MGeomCam is extracted. If
+// the geometry isn't found MGeomCamMagic is used as a default.
+//
+// Usage:
+//   .x fillcalib.C("/data/MAGIC/Period014/calib00000.root", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// The corresponding sequence number is extracted from the filename...
+// FIXME: MSeqeuence should be stored in the calib-file?
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b fillcalib.C+\(\"filename\"\,kFALSE\) 2>&1 | tee fillcalib.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+
+#include <TEnv.h>
+#include <TRegexp.h>
+
+#include <TFile.h>
+#include <TSQLResult.h>
+
+#include "MSQLServer.h"
+
+#include "MGeomCamMagic.h"
+#include "MBadPixelsCam.h"
+
+using namespace std;
+
+Bool_t Process(MSQLServer &serv, TString fname, Bool_t dummy)
+{
+    MBadPixelsCam badpix;
+
+    TFile file(fname, "READ");
+    if (badpix.Read("MBadPixelsCam")<=0)
+    {
+        cout << "ERROR - Reading of MBadPixelsCam failed." << endl;
+        return kFALSE;
+    }
+
+    MGeomCamMagic def;
+
+    MGeomCam *geom = (MGeomCam*)file.Get("MGeomCam");
+    if (!geom)
+    {
+        cout << "WARNING - Reading of MGeomCam failed... using default <MGeomCamMagic>" << endl;
+        geom = &def;
+    }
+
+    cout << "Camera Geometry: " << geom->ClassName() << endl;
+
+    const Short_t unsin  = badpix.GetNumUnsuitable(MBadPixelsPix::kUnsuitableRun, geom, 0);
+    const Short_t unsout = badpix.GetNumUnsuitable(MBadPixelsPix::kUnsuitableRun, geom, 1);
+
+    const Short_t unrin  = badpix.GetNumUnsuitable(MBadPixelsPix::kUnreliableRun, geom, 0);
+    const Short_t unrout = badpix.GetNumUnsuitable(MBadPixelsPix::kUnreliableRun, geom, 1);
+
+    const Short_t isoin  = badpix.GetNumIsolated(*geom, 0);
+    const Short_t isoout = badpix.GetNumIsolated(*geom, 1);
+
+    const Short_t clumax = badpix.GetNumMaxCluster(*geom);
+
+    if (unsin<0 || unsout<0 || unrin<0 || unrout<0 || isoin<0 || isoout<0 || clumax<0)
+        return kFALSE;
+
+    //     MHCamera hist(geom);
+    //     hist.SetCamContent(badpix, 1);
+    //     hist.DrawCopy();
+    //     hist.SetCamContent(badpix, 3);
+    //     hist.DrawCopy();
+
+    TString sequence = fname(TRegexp("calib[0-9]+[.]root$"));
+    if (sequence.IsNull())
+        return kTRUE;
+
+    Int_t seq = atoi(sequence.Data()+5);
+
+    cout << "Sequence #" << seq << endl;
+    cout << "  Unsuitable:   (i/o)  " << Form("%3d %3d", (int)unsin, (int)unsout) << endl; // Unbrauchbar
+    cout << "  Unreliable:   (i/o)  " << Form("%3d %3d", (int)unrin, (int)unrout) << endl; // Unzuverlaessig
+    cout << "  Isolated:     (i/o)  " << Form("%3d %3d", (int)isoin, (int)isoout) << endl; // Isolated (unbrauchbar)
+    cout << "  Max.Cluseter: (i/o)  " << Form("%3d", (int)clumax) << endl;                 // Max Cluster
+
+    if (dummy)
+        return kTRUE;
+
+    TString query = Form("INSERT MyMagic.Calibration SET"
+                         " fSequenceFirst=%d,"
+                         " fUnsuitableInner=%d, "
+                         " fUnsuitableOuter=%d, "
+                         " fUnreliableInner=%d, "
+                         " fUnreliableOuter=%d, "
+                         " fIsolatedInner=%d, "
+                         " fIsolatedOuter=%d, "
+                         " fIsolatedMaxCluster=%d",
+                         seq, (int)unsin, (int)unsout, (int)unrin,
+                         (int)unrout, (int)isoin, (int)isoout, (int)clumax);
+
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+void fillcallisto(TString fname, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLServer serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return;
+    }
+
+    cout << "fillcalib" << endl;
+    cout << "---------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    cout << (Process(serv, fname, dummy) ? "Done." : "failed!") << endl << endl;
+}
Index: /tags/Mars-V0.9/macros/sql/filldotraw.C
===================================================================
--- /tags/Mars-V0.9/macros/sql/filldotraw.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sql/filldotraw.C	(revision 9772)
@@ -0,0 +1,184 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// filldotraw.C
+// ============
+//
+// This macro is used to read a merpped raw data file or a raw data file
+// directly. The descision is taken by the file-name extension (".root" or
+// ".raw")
+//
+// Usage:
+//   .x filldotraw.C("/data/MAGIC/Period014/filename.raw", kTRUE)
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// Filling the database is done with 'UPADTE' for _all_ columns
+// matching the Run-Number!
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b filldotraw.C+\(\"filename\"\,kFALSE\) 2>&1 | tee filldotraw.log
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <iostream>
+
+#include <TEnv.h>
+#include <TFile.h>
+#include <TTree.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MSQLServer.h"
+#include "MRawRunHeader.h"
+
+using namespace std;
+
+Int_t MagicNumber(MSQLServer &serv, const MRawRunHeader &h)
+{
+    TString query(Form("SELECT fMagicNumberKEY FROM MyMagic.MagicNumber WHERE fMagicNumber=%d",
+                       h.GetMagicNumber()));
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return -1;
+    }
+
+    TSQLRow *row = res->Next();
+    if (!row)
+    {
+        cout << "ERROR - No result from query: " << query << endl;
+        return -1;
+    }
+
+    return atoi((*row)[0]);
+}
+
+Bool_t ReadRaw(TString fname, MRawRunHeader &h)
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        cout << "ERROR - Couldn't open file " << fname << endl;
+        return kFALSE;
+    }
+
+    if (!h.ReadEvt(fin))
+    {
+        cout << "ERROR - Reading header from file " << fname << endl;
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+Bool_t ReadRoot(TString fname, MRawRunHeader *h)
+{
+    TFile file(fname, "READ");
+    if (file.IsZombie())
+    {
+        cout << "ERROR - Cannot open file " << fname << endl;
+        return kFALSE;
+    }
+
+    TTree *t = (TTree*)file.Get("RunHeaders");
+    if (!t)
+    {
+        cout << "ERROR - Tree RunHeaders not found." << endl;
+        return kFALSE;
+    }
+
+    t->SetBranchAddress("MRawRunHeader.", &h);
+    t->GetEntry(0);
+
+    return kTRUE;
+}
+
+Bool_t Process(MSQLServer &serv, TString fname, Bool_t dummy)
+{
+    MRawRunHeader h;
+
+    if (fname.EndsWith(".root"))
+        ReadRoot(fname, &h);
+    if (fname.EndsWith(".raw"))
+        ReadRaw(fname, h);
+
+    if (dummy)
+    {
+        h.Print("header");
+        return kTRUE;
+    }
+
+    const Int_t key = MagicNumber(serv, h);
+    if (key<0)
+        return kFALSE;
+
+    TString query(Form("UPDATE MyMagic.RunData SET fMagicNumberKEY=%d, fFormatVersion=%d WHERE fRunNumber=%d",
+                       key, h.GetFormatVersion(), h.GetRunNumber()));
+
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+    {
+        cout << "ERROR - Query failed: " << query << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+void filldotraw(TString fname, Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLServer serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return;
+    }
+
+    cout << "filldotraw" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "File: " << fname << endl;
+    cout << endl;
+
+    cout << (Process(serv, fname, dummy) ? "Done." : "failed!") << endl << endl;
+}
Index: /tags/Mars-V0.9/macros/sql/filldotrbk.C
===================================================================
--- /tags/Mars-V0.9/macros/sql/filldotrbk.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sql/filldotrbk.C	(revision 9772)
@@ -0,0 +1,248 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// filldotrbk.C
+// ============
+//
+// This macro is used to read the central control runbook files from
+// the data center and store their contents in the runbook-database.
+//
+// Usage:
+//   .x filldotrbk.C("/data/MAGIC/Period014", kTRUE)
+//
+// While the first argument is the directory in which all subdirectories where
+// searches for CC_*.rbk files. All these files were analysed and the runbook
+// entries will be put into the DB, eg:
+//   "/data/MAGIC"                              would do it for all data
+//   "/data/MAGIC/Period019/ccdata"             would do it for one Period
+//   "/data/MAGIC/Period019/ccdata/2004_05_17"  would do it for a single day
+//   "/data/MAGIC/Period019/ccdata/file.rbk"    would do it for a single file
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. This is usefull
+// for tests.
+//
+// Before an antry is added its existance is checked... if it is added already
+// it is ignored.
+//
+// The macro can also be run without ACLiC but this is a lot slower...
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b filldotrbk.C+\(\"path\"\,kFALSE\) 2>&1 | tee filldotrbk.log
+//
+// Make sure, that database and password are corretly set in the macro.
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+///////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TEnv.h>
+#include <TRegexp.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MDirIter.h"
+#include "MSQLServer.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an entry for this date is already existing
+//
+Bool_t ExistStr(MSQLServer &serv, const char *column, const char *table, const char *test)
+{
+    TString query(Form("SELECT %s FROM %s WHERE %s='%s'", column, table, column, test));
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    TSQLRow *row;
+
+    Bool_t rc = kFALSE;
+    while ((row=res->Next()))
+    {
+        if ((*row)[0])
+        {
+            rc = kTRUE;
+            break;
+        }
+    }
+
+    delete res;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// insert the entries from this runbook file into the database
+//
+int insert(MSQLServer &serv, Bool_t dummy, TString fname)
+{
+    //cout << endl;
+    //cout << "FILE: " << fname << endl;
+
+    ifstream fin(fname);
+    if (!fin)
+    {
+        cout << "Could not open file " << fname << endl;
+        return 0;
+    }
+
+    TRegexp regexp("^.20[0-9][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].$", kFALSE);
+
+    Int_t num=0;
+
+    Bool_t valid = kFALSE;
+    TString entry;
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        TString l0 = line(regexp);
+
+        if (l0.IsNull())
+        {
+            entry += line;
+            entry += "\n";
+            continue;
+        }
+        if (!valid)
+        {
+            valid = kTRUE;
+            entry = "";
+            //cout << "First entry skipped..." << endl;
+            continue;
+        }
+
+        if (entry.Contains("Operator names: "))
+        {
+            //cout << "OPERATORS: " << entry << flush;
+            entry="";
+            continue;
+        }
+
+        if (entry.Contains("CALIBRATION RUN STATISTICS") ||
+            entry.Contains("DATA RUN STATISTICS")        ||
+            entry.Contains("PEDESTAL RUN STATISTICS"))
+        {
+            //cout << "Run entry skipped..." << endl;
+            entry ="";
+            continue;
+        }
+
+        TString date(l0(1, l0.Length()-2));
+
+        if (ExistStr(serv, "fRunBookDate", "MyMagic.RunBook", date))
+        {
+            entry ="";
+            continue;
+        }
+
+        entry.ReplaceAll("'", "\\'");
+        entry.ReplaceAll("\"", "\\\"");
+
+        // This is a sanity check for \0-bytes in .rbk-files
+        for (int i=0; i<entry.Length(); i++)
+            if ((int)entry[i]==0)
+                entry.Remove(i--);
+
+        TString query("INSERT MyMagic.RunBook (fRunBookDate, fRunBookText) VALUES (\"");
+        query += date;
+        query += "\", \"";
+        query += entry;
+        query += "\");";
+
+        if (dummy)
+        {
+            num++;
+            entry = "";
+            continue;
+        }
+
+        TSQLResult *res = serv.Query(query);
+        if (!res)
+            return 0;
+
+        delete res;
+        num++;
+
+        entry = "";
+    }
+
+    cout << fname(TRegexp("CC_.*.rbk", kFALSE)) << " <" << num << ">";
+    cout << (dummy?" DUMMY":"") << endl;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// loop over all files in this path
+//
+int filldotrbk(TString path="/data/MAGIC/Period017/ccdata", Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLServer serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return 0;
+    }
+
+    cout << endl;
+    cout << "filldotrbk" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Search Path: " << path << endl;
+    cout << endl;
+
+    if (path.EndWith(".rbk"))
+        return insert(serv, dummy, path);
+
+    MDirIter Next(path, "CC_*.rbk", -1);
+    while (1)
+    {
+        TString name = Next();
+        if (name.IsNull())
+            break;
+
+        if (!insert(serv, dummy, name))
+            return 0;
+    }
+
+    return 1;
+}
Index: /tags/Mars-V0.9/macros/sql/filldotrun.C
===================================================================
--- /tags/Mars-V0.9/macros/sql/filldotrun.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sql/filldotrun.C	(revision 9772)
@@ -0,0 +1,623 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// filldotrun.C
+// ============
+//
+// This macro is used in the datacenter to automatically fill the run-database
+// with the information stored in the .run-files written by the central
+// control.
+//
+// To following Arehucas versions are Currently supported:
+//   040505-0, 040514-0,
+//   040518-0, 040727-0,
+//   041113-0, 041209-0, 041221-0
+//
+// Usage:
+//    .x filldotrun.C+("/data/MAGIC/Period019/ccdata", kTRUE)
+//
+// While the first argument is the directory in which all subdirectories where
+// searches for CC_*.run files. All these files were analysed and the run
+// info will be put into the DB, eg:
+//   "/data/MAGIC"                              would do it for all data
+//   "/data/MAGIC/Period019/ccdata"             would do it for one Period
+//   "/data/MAGIC/Period019/ccdata/2004_05_17"  would do it for a single day
+//   "/data/MAGIC/Period019/ccdata/file.run"    would do it for a single file
+//
+// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
+// switched on and nothing will be written into the database. Instead
+// informations about the subtables are displayed. This is usefull for tests
+// when adding a new arehucas version support. If it is kFALSE the information
+// are written into the subtables and the runs info is written into the
+// rundatabase.
+//
+// In the automatic case it makes sense to check the logfiles to make sure
+// that everything is fine...
+//
+// Make sure, that database and password are corretly set in a resource
+// file called sql.rc and the resource file is found.
+//
+// Remark: Running it from the commandline looks like this:
+//   root -q -l -b filldotrun.C+\(\"path\"\,kFALSE\) 2>&1 | tee filldotrun.log
+//
+// Returns 0 in case of failure and 1 in case of success.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+
+#include <TEnv.h>
+#include <TMath.h>
+#include <TRegexp.h>
+
+#include <TSQLRow.h>
+#include <TSQLResult.h>
+
+#include "MTime.h"
+#include "MDirIter.h"
+#include "MSQLServer.h"
+
+using namespace std;
+
+Bool_t ExistStr(MSQLServer &serv, const char *column, const char *table, const char *test)
+{
+    TString query(Form("SELECT %s FROM %s WHERE %s='%s'", column, table, column, test));
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return kFALSE;
+
+    Bool_t rc = kFALSE;
+
+    TSQLRow *row=res->Next();
+    if (row && (*row)[0])
+        rc=kTRUE;
+
+    delete res;
+    return rc;
+}
+
+Int_t QueryNameKEY(MSQLServer &serv, Bool_t dummy, const char *col, const char *name, Bool_t insert=kTRUE)
+{
+    TString query;
+
+    query = Form("SELECT f%sKEY FROM MyMagic.%s WHERE f%sName='%s'", col, col, col, name);
+    TSQLResult *res = serv.Query(query);
+    if (!res)
+        return -1;
+
+    TSQLRow *row=res->Next();
+
+    Int_t rc = row && (*row)[0] ? atoi((*row)[0]) : -1;
+
+    delete res;
+
+    if (rc>=0)
+        return rc;
+
+    if (!insert)
+        return -1;
+
+    query = Form("INSERT MyMagic.%s (f%sName) VALUES (\"%s\");", col, col, name);
+
+    if (dummy)
+    {
+        cout << query << endl;
+        return 0;
+    }
+
+    res=serv.Query(query);
+    if (!res)
+        return -1;
+
+    delete res;
+
+    Int_t key = QueryNameKEY(serv, dummy, col, name, kFALSE);
+    if (key>0)
+    {
+        cout << "New " << col << ": " << name << endl;
+        return key;
+    }
+
+    cout << "ERROR: " << query << endl;
+    return kFALSE;
+}
+
+
+Int_t insert(MSQLServer &serv, Bool_t dummy, TString filename)
+{
+    ifstream fin(filename);
+    if (!fin)
+    {
+        cout << "Could not open file " << filename << endl;
+        return -1;
+    }
+
+    TString strng;
+    strng.ReadLine(fin);
+    if (strng!=TString("[CC Plain Run Summary File]"))
+    {
+        cout << filename << ": No Plain Run Summary File" << endl;
+        cout << "First Line: " << strng << endl;
+        cout << endl;
+        return -1;
+    }
+
+    strng.ReadLine(fin);
+    TRegexp reg("[0-9][0-9][0-9][0-9][0-9][0-9]-[0-9]");
+    TString arehucas = strng(reg);
+    arehucas.Prepend("20");
+    arehucas.ReplaceAll("-", "");
+
+    Int_t version = atoi(arehucas.Data());
+    if (version!=200405050 && version!=200405140 && version!=200405180
+        && version!=200407270 && version!=200411130 &&
+        version!=200412090 && version!=200412210)
+    {
+        cout << filename << ": File Version unknown - please update the macro!" << endl;
+        cout << "Second Line: " << strng << endl;
+        cout << endl;
+        return -1;
+    }
+
+    cout << "  V" << version << " " << flush;
+
+    Int_t cnt=0;
+    while (1)
+    {
+        // ========== Col 1: Run Number =========
+        //Reading the line
+        //and converting some strings to ints/floats
+        strng.ReadToDelim(fin, ' ');
+        if (!fin)
+            break;
+
+        Int_t runnumber = atoi(strng.Data());
+
+        //runnumber=0 means no valid dataset
+        //-> continue
+        if (runnumber == 0)
+        {
+            strng.ReadLine(fin);
+            cout << "Runnumber == 0" << endl;
+            continue;
+        }
+
+        //cout << "RunNo: " << runnumber << " ";
+
+        if (ExistStr(serv, "fRunNumber", "MyMagic.RunData", strng.Data()))
+        {
+            // FIXME: Maybe we can implement an switch to update mode?
+            cout << "Run #" << runnumber << " already existing... skipped." << endl;
+            strng.ReadLine(fin);
+            continue;
+        }
+
+        // ========== Col 2: Run Type =========
+        strng.ReadToDelim(fin, ' ');
+        if (strng.Contains("???"))
+            strng="n/a";
+
+        Int_t runtype = QueryNameKEY(serv, dummy, "RunType", strng.Data(), kFALSE);
+        if (runtype<0)
+        {
+            cout << "ERROR - RunType " << strng << " not available." << endl;
+            strng.ReadLine(fin);
+            continue;
+        }
+
+        //cout << runtype << " ";
+
+        // ========== Col 3,4: Start Time =========
+        TString startdate, starttime;
+        startdate.ReadToDelim(fin, ' ');
+        starttime.ReadToDelim(fin, ' ');
+        //cout << startdate << " " << starttime << " ";
+
+        // ========== Col 5,6: Stop Time =========
+        TString stopdate, stoptime;
+        stopdate.ReadToDelim(fin, ' ');
+        stoptime.ReadToDelim(fin, ' ');
+        //cout << stopdate << " " << stoptime << " ";
+
+        if (startdate.Contains("???"))
+            startdate="0000-00-00";
+        if (starttime.Contains("???"))
+            starttime="00:00:00";
+        if (stopdate.Contains("???"))
+            stopdate="0000-00-00";
+        if (stoptime.Contains("???"))
+            stoptime="00:00:00";
+
+        // ========== Col 7: Source Name =========
+        strng.ReadToDelim(fin, ' ');
+        if (strng.Contains("???"))
+            strng="Unavailable";
+
+        Int_t sourcekey = QueryNameKEY(serv, dummy, "Source", strng.Data());
+        if (sourcekey<0)
+        {
+            strng.ReadLine(fin);
+            continue;
+        }
+        //cout << sourcekey << " ";
+
+        // ========== Col 8,9: Local source position =========
+        strng.ReadToDelim(fin, ' ');
+        Float_t zd = atof(strng.Data());
+
+        strng.ReadToDelim(fin, ' ');
+        Float_t az = atof(strng.Data());
+
+        //cout << zd << " " << az << " ";
+
+        // ========== Col 10: Number of Events =========
+        strng.ReadToDelim(fin, ' ');
+        Int_t evtno = atoi(strng.Data());
+
+        //cout << evtno << " ";
+
+        // ========== Col 11: Project Name =========
+        strng.ReadToDelim(fin, ' ');
+        if (strng.Contains("???"))
+            strng="Unavailable";
+
+        Int_t projkey = QueryNameKEY(serv, dummy, "Project", strng.Data());
+        if (projkey<0)
+        {
+            strng.ReadLine(fin);
+            continue;
+        }
+        //cout << projkey << " ";
+
+        // ========== Col 12: Trigger Table Name =========
+        // starting from version 200411130: Col 12,13: Trigger Table Name =========
+        strng.ReadToDelim(fin, ' ');
+        if (strng.Contains("???"))
+            strng="n/a";
+
+        if (version >=200411130)
+        {
+            Int_t l1triggerkey = QueryNameKEY(serv, dummy, "L1TriggerTable", strng.Data());
+            if (l1triggerkey<0)
+            {
+                strng.ReadLine(fin);
+                continue;
+            }
+
+            strng.ReadToDelim(fin, ' ');
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            Int_t l2triggerkey = QueryNameKEY(serv, dummy, "L2TriggerTable", strng.Data());
+            if (l2triggerkey<0)
+            {
+                strng.ReadLine(fin);
+                continue;
+            }
+        }
+        else
+        {
+            Int_t c=0;
+
+            if (strng.Contains(":"))
+                c=1;
+
+            if (strng.Contains("L1_") && !(strng.Contains(":")))
+                c=2;
+
+            if (strng.Contains("n/a"))
+                c=3;
+
+            switch (c)
+            {
+            case 0:
+                {
+                    Int_t l2triggerkey = QueryNameKEY(serv, dummy, "L2TriggerTable", strng.Data());
+                    if (l2triggerkey<0)
+                    {
+                        strng.ReadLine(fin);
+                        continue;
+                    }
+
+                    strng="n/a";
+                    Int_t l1triggerkey = 1;
+
+                    break;
+                }
+            case 1:
+                {
+                    TString L1TT, L2TT;
+                    L2TT=strng(7,12);
+                    L1TT=strng(0,6);
+
+                    Int_t l1triggerkey = QueryNameKEY(serv, dummy, "L1TriggerTable", L1TT.Data());
+                    if (l1triggerkey<0)
+                    {
+                        strng.ReadLine(fin);
+                        continue;
+                    }
+
+                    Int_t l2triggerkey = QueryNameKEY(serv, dummy, "L2TriggerTable", L2TT.Data());
+                    if (l2triggerkey<0)
+                    {
+                        strng.ReadLine(fin);
+                        continue;
+                    }
+
+                    break;
+                }
+            case 2:
+                {
+                    Int_t l1triggerkey = QueryNameKEY(serv, dummy, "L1TriggerTable", strng.Data());
+                    if (l1triggerkey<0)
+                    {
+                        strng.ReadLine(fin);
+                        continue;
+                    }
+
+                    strng="n/a";
+                    Int_t l2triggerkey = 1;
+
+                    break;
+                }
+            case 3:
+                {
+                    Int_t l1triggerkey = 1;
+                    Int_t l2triggerkey = 1;
+                    break;
+                }
+            default:
+                {
+                    cout << "WARNING: neiter L1 nor L2 Trigger table - please check what is happening." << strng << endl;
+                    break;
+                }
+            }
+        }
+
+        // ========== Col 13-15: TrigRate, L2 UnPresc Rate, L2 Presc Rate ==========
+        strng.ReadToDelim(fin, ' ');
+        Float_t trigrate = atof(strng.Data());
+
+        strng.ReadToDelim(fin, ' ');
+        Float_t l2uprate = atof(strng.Data());
+
+        strng.ReadToDelim(fin, ' ');
+        Float_t l2prrate = atof(strng.Data());
+
+        // ========== Col 16,17: DaqRate, Storage Rate ==========
+        strng.ReadToDelim(fin, ' ');
+        Float_t daqrate = atof(strng.Data());
+
+        strng.ReadToDelim(fin, ' ');
+        Float_t storerate = atof(strng.Data());
+
+        // ========== Col 18: HV table =========
+        if (version==200405050 || version==200405140)
+            strng.ReadToDelim(fin, '\n');
+        else
+            strng.ReadToDelim(fin, ' ');
+        if (strng.Contains("???"))
+            strng="n/a";
+
+        Int_t hvkey = QueryNameKEY(serv, dummy, "HvSettings", strng.Data());
+        if (hvkey<0)
+        {
+            //strng.ReadLine(fin);
+            continue;
+        }
+
+        if (version==200405180 || version==200407270)
+            strng.ReadLine(fin);
+
+        if (version==200411130 || version==200412090 || version==200412210)
+        {
+            // ========== Col 19-35: DC and HV-values, mjd =========
+            for (int i=0 ; i<17 ; i++)
+            {
+                strng.ReadToDelim(fin, ' ');
+            }
+
+            // ========== Col 36: test-flag =========
+            strng.ReadToDelim(fin, ' ');
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            Int_t testflagkey = QueryNameKEY(serv, dummy, "TestFlag", strng.Data());
+            if (testflagkey<0)
+            {
+                strng.ReadLine(fin);
+                continue;
+            }
+
+            // ========== Col 37: light conditions =========
+            strng.ReadToDelim(fin, ' ');
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            Int_t lightcondkey = QueryNameKEY(serv, dummy, "LightConditions", strng.Data());
+            if (lightcondkey<0)
+            {
+                strng.ReadLine(fin);
+                continue;
+            }
+
+            // ========== Col 38: discriminator threshold table =========
+            strng.ReadToDelim(fin, ' ');
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            Int_t dttablekey = QueryNameKEY(serv, dummy, "DiscriminatorThresholdTable", strng.Data());
+            if (dttablekey<0)
+            {
+                strng.ReadLine(fin);
+                continue;
+            }
+
+            // ========== Col 39: trigger delay table =========
+            strng.ReadToDelim(fin, ' ');
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            Int_t triggerdelaytablekey = QueryNameKEY(serv, dummy, "TriggerDelayTable", strng.Data());
+            if (triggerdelaytablekey<0)
+            {
+                strng.ReadLine(fin);
+                continue;
+            }
+
+            // ========== Col 40,41: RA and Dec sent to drive =========
+            strng.ReadToDelim(fin, ' ');
+            strng.ReadToDelim(fin, ' ');
+
+            // ========== Col 42: Calibration Script =========
+            strng.ReadToDelim(fin, ' ');
+            if (strng.Contains("???"))
+                strng="n/a";
+
+            Int_t calibrationscriptkey = QueryNameKEY(serv, dummy, "CalibrationScript", strng.Data());
+            if (calibrationscriptkey<0)
+            {
+                strng.ReadLine(fin);
+                continue;
+            }
+
+        }
+        else
+        {
+            Int_t testflagkey, lightcondkey, dttablekey, triggerdelaytablekey, calibrationscriptkey=1;
+        }
+
+
+        //continue;
+
+        //cout << endl;
+
+        // ================================================================
+        // ========== Data read from file now access the database =========
+        // ================================================================
+
+        //assemlbe the query that is needed to insert the values of this run
+        TString query;
+        query += "INSERT MyMagic.RunData SET ";
+
+        query += Form("fRunNumber=%d, ",  runnumber);
+        query += Form("fRunTypeKEY=%d, ", runtype);
+        query += Form("fProjectKEY=%d, ", projkey);
+        query += Form("fSourceKEY=%d, ",  sourcekey);
+        query += Form("fNumEvents=%d, ",  evtno);
+        query += Form("fRunStart=\"%s %s\", ", startdate.Data(), starttime.Data());
+        query += Form("fRunStop=\"%s %s\", ", stopdate.Data(), stoptime.Data());
+        query += Form("fL1TriggerTableKEY=%d, ", l1triggerkey);
+        query += Form("fL2TriggerTableKEY=%d, ", l2triggerkey);
+        query += Form("fTestFlagKEY=%d, ", testflagkey);
+        query += Form("fCalibrationScriptKEY=%d, ", calibrationscriptkey);
+        query += Form("fTriggerDelayTableKEY=%d, ", triggerdelaytablekey);
+        query += Form("fDiscrimintorThresholdTableKEY=%d, ", dttablekey);
+        query += Form("fLightConditionsKEY=%d, ", lightcondkey);
+        query += Form("fHvSettingsKEY=%d, ", hvkey);
+        if (!TMath::IsNaN(zd) && TMath::Finite(zd))
+            query += Form("fZenithDistance=%d, ", TMath::Nint(zd));
+        if (!TMath::IsNaN(az) && TMath::Finite(az))
+            query += Form("fAzimuth=%d, ", TMath::Nint(az));
+        if (!TMath::IsNaN(storerate) && TMath::Finite(storerate))
+            query += Form("fDaqStoreRate=%d, ", TMath::Nint(storerate));
+        if (!TMath::IsNaN(daqrate) && TMath::Finite(daqrate))
+            query += Form("fDaqTriggerRate=%d, ", TMath::Nint(daqrate));
+        if (!TMath::IsNaN(trigrate) && TMath::Finite(trigrate))
+            query += Form("fMeanTriggerRate=%d, ", TMath::Nint(trigrate));
+        if (!TMath::IsNaN(l2prrate) && TMath::Finite(l2prrate))
+            query += Form("fL2RatePresc=%d, ", TMath::Nint(l2prrate));
+        if (!TMath::IsNaN(l2uprate) && TMath::Finite(l2uprate))
+            query += Form("fL2RateUnpresc=%d, ", TMath::Nint(l2uprate));
+        query += "fMagicNumberKEY=1, fExcludedFDAKEY=1";
+
+        //cout << query << endl;
+        cnt++;
+
+        //cout << query << endl;
+        //continue;
+
+        if (dummy)
+            continue;
+
+        //send query, add dataset to DB
+        TSQLResult *res = serv.Query(query);
+        if (!res)
+            return -1;
+
+        delete res;
+    }
+
+    return cnt;
+
+}
+
+// This tool will work from Period017 (2004_05_17) on...
+int filldotrun(const TString path="/data/MAGIC/Period018/ccdata", Bool_t dummy=kTRUE)
+{
+    TEnv env("sql.rc");
+
+    MSQLServer serv(env);
+    if (!serv.IsConnected())
+    {
+        cout << "ERROR - Connection to database failed." << endl;
+        return;
+    }
+    cout << "filldotrun" << endl;
+    cout << "----------" << endl;
+    cout << endl;
+    cout << "Connected to " << serv.GetName() << endl;
+    cout << "Search Path: " << path << endl;
+    cout << endl;
+
+    if (path.EndsWith(".run"))
+    {
+        cout << path(TRegexp("CC_.*.run", kFALSE)) << flush;
+        Int_t n = insert(serv, dummy, path);
+        cout << " <" << n << "> " << (dummy?"DUMMY":"") << endl;
+
+        return n<0 ? 0 : 1;
+    }
+
+    MDirIter Next(path, "CC_*.run", -1);
+    while (1)
+    {
+        TString name = Next();
+        if (name.IsNull())
+            break;
+
+        cout << name(TRegexp("CC_.*.run", kFALSE)) << flush;
+        Int_t n = insert(serv, dummy, name);
+        cout << " <" << n << "> " << (dummy?"DUMMY":"") << endl;
+
+        if (n<0)
+            return 0;
+    }
+
+    return 1;
+}
Index: /tags/Mars-V0.9/macros/sql/sql.rc
===================================================================
--- /tags/Mars-V0.9/macros/sql/sql.rc	(revision 9772)
+++ /tags/Mars-V0.9/macros/sql/sql.rc	(revision 9772)
@@ -0,0 +1,3 @@
+URL:      mysql://localhost
+User:     hercules
+Password: password
Index: /tags/Mars-V0.9/macros/star.C
===================================================================
--- /tags/Mars-V0.9/macros/star.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/star.C	(revision 9772)
@@ -0,0 +1,131 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  STAR - STandard Analysis and Reconstruction
+//
+// This macro is the standard converter to convert raw data into image
+// parameters. It is a demonstration how the star-executable implementation
+// looks like.
+//
+// As an input you need a Merpp output file (raw data).
+// All parameters are written to an output file called starfile.root.
+// For the calculation an arbitrary signal extractor (MCerPhotAnal2/Calc)
+// is used.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void star()
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+
+    // ------------- user change -----------------
+    read.AddFile("~/MC/test_sample/Gamma_zbin0_0_*.root");
+
+    MGeomApply        apply;
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    MCerPhotCalc      ncalc;
+    MCerPhotAnal2     nanal;
+
+    MFDataMember f1("MRawRunHeader.fRunType", '>', 255.5);
+    MFDataMember f2("MRawRunHeader.fRunType", '<', 255.5);
+
+    ncalc.SetFilter(&f1);
+    nanal.SetFilter(&f2);
+
+    MBlindPixelCalc   blind;
+    blind.SetUseInterpolation();
+
+    MSigmabarCalc     sgcal;
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+
+    // ------------- user change -----------------
+    MWriteRootFile write("starfile.root");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&f1);
+    tlist.AddToList(&f2);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&nanal);
+    tlist.AddToList(&blind);
+    tlist.AddToList(&sgcal);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&scalc);
+    tlist.AddToList(&write);
+
+    // ------------- user change -----------------
+    // You may use the "UPDATE" option in the constructor
+    // of MWriteRootFile to update an existing file.
+    //
+    // tlist.SetSerialNumber(1); // Serial number of telescope
+    write.AddContainer(write.AddSerialNumber("MMcEvt"),       "Events", kFALSE);
+    write.AddContainer(write.AddSerialNumber("MSigmabar"),    "Events");
+    write.AddContainer(write.AddSerialNumber("MHillas"),      "Events");
+    write.AddContainer(write.AddSerialNumber("MHillasExt"),   "Events");
+    write.AddContainer(write.AddSerialNumber("MHillasSrc"),   "Events");
+    write.AddContainer(write.AddSerialNumber("MNewImagePar"), "Events");
+    write.AddContainer(write.AddSerialNumber("MSrcPosCam"),   "RunHeaders");
+    write.AddContainer("MRawRunHeader", "RunHeaders");
+    write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+
+    //
+    // Create and set up the eventloop
+    //
+    MProgressBar bar;
+
+    MEvtLoop evtloop;
+    evtloop.SetProgressBar(&bar);
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+}
Index: /tags/Mars-V0.9/macros/starfield.C
===================================================================
--- /tags/Mars-V0.9/macros/starfield.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/starfield.C	(revision 9772)
@@ -0,0 +1,107 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 5/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// starfield.C
+// ===========
+//
+// This is a macro demonstrating how to use Mars to display a starfield.
+// It also is a tutorial for MAstroCatalog and MAstroCamera.
+//
+// For more details on this classes see the class-reference.
+//
+// If you want to display stars in a camera you need the camera geometry
+// and the mirror definition. You can get this either from a Monte Carlo
+// file containing both or create your MGeomCam object manually and
+// read a magic.def file which you will find in the camera simulation
+// program.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void ReadSetup(TString fname, MAstroCamera &cam)
+{
+    MMcConfigRunHeader *config=0;
+    MGeomCam           *geom=0;
+
+    TFile file(fname);
+    TTree *tree = (TTree*)file.Get("RunHeaders");
+    tree->SetBranchAddress("MMcConfigRunHeader", &config);
+    if (tree->GetBranch("MGeomCam"))
+        tree->SetBranchAddress("MGeomCam", &geom);
+    tree->GetEntry(0);
+
+    cam.SetMirrors(*config->GetMirrors());
+    cam.SetGeom(*geom);
+
+    /* Alternative:
+
+     MGeomCamMagic geom;
+     cam.SetGeom(geom);
+     cam.SetMirrors("magic.def");
+     */
+}
+
+void starfield()
+{
+    // Name of a MC file having MGeomCam and MMcConfigRunHeader
+    TString fname = "../Mars/Gamma_zbin7_90_7_53395to53399_w0.root";
+
+    // Time for which to get the picture
+    MTime time;
+    time.Set(2004, 2, 28, 01, 32, 15);
+
+    // Current observatory
+    MObservatory magic1;
+
+    // Right Ascension [h] and declination [deg] of source
+    // Currently 'perfect' pointing is assumed
+    const Double_t ra  = MAstro::Hms2Rad(5, 34, 31.9);
+    const Double_t dec = MAstro::Dms2Rad(22, 0, 52.0);
+
+    new TCanvas;
+
+    // --------------------------------------------------------------------------
+    // Create camera display from geometry
+    //MAstroCatalog stars;     // Use this top display a catalog
+    MAstroCamera stars;        // Use this top display a catalog on top of a camera
+    ReadSetup(fname, stars);   // Use this top display a catalog on top of a camera
+    stars.SetLimMag(6);
+    stars.SetRadiusFOV(3);
+    stars.SetRaDec(ra, dec);
+
+    // Read the stars from a star catalog. The catalogs can be downloaded
+    // from the Mars web page. For more information see class reference.
+    stars.ReadBSC("bsc5.dat");
+
+    stars.SetObservatory(magic1);
+    stars.SetTime(time);
+    stars.SetGuiActive();
+
+    // See the cooresponding Draw-function for more options
+    TObject *o = stars.Clone();
+    o->SetBit(kCanDelete);
+    o->Draw();
+
+}
Index: /tags/Mars-V0.9/macros/starmc.C
===================================================================
--- /tags/Mars-V0.9/macros/starmc.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/starmc.C	(revision 9772)
@@ -0,0 +1,295 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Abelardo Moralejo 1/2004 <mailto:moralejo@pd.infn.it>
+   !              Thomas Bretz  5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+   !
+   !   Copyright: MAGIC Software Development, 2000-2004
+   !
+   !
+   \* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  STARMC - STandard Analysis and Reconstruction (MC example)
+//
+//  This macro is a version of the standard converter to convert raw data 
+//  into image  parameters, made to show how to run analysis on MC files. 
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MImgCleanStd.h"
+
+void starmc()
+{
+  //
+  // This is a demonstration program which calculates the image 
+  // parameters from Magic Monte Carlo files (output of camera).
+
+  TString* CalibrationFilename;
+  TString* OutFilename1;
+  TString* OutFilename2;
+
+  // ------------- user change -----------------
+  //
+  // Comment line starting "CalibrationFileName" to disable calibration. In that 
+  // case the units of the MHillas.fSize parameter will be ADC counts (rather, 
+  // equivalent ADC counts in inner pixels, since we correct for the possible 
+  // differences in gain of outer pixels)
+  //
+  CalibrationFilename = new TString("/users/emc/moralejo/mcdata/Period021_0.73_mirror/gammas_nonoise/Gamma_zbin0_*.root");
+  // File to be used in the calibration (must be a camera file without added noise)
+
+
+  Char_t* AnalysisFilename = "Gamma_*w0.root";  // File to be analyzed
+
+
+
+  // ------------- user change -----------------
+  //
+  // Change output file names as desired. If you want only one output, comment
+  // the initialization of OutFilename2.
+
+  OutFilename1 = new TString("star_train.root");   // Output file name 1 (test)
+  OutFilename2 = new TString("star_test.root"); // Output file name 2 (train)
+  //
+  // Fraction of events (taken at random) which one wants to process from the 
+  // file to be analyzed (useful to make smaller files if starting sample is
+  // too large).
+  //
+  Float_t accepted_fraction = 1.;
+
+  Float_t CleanLev[2] = {5., 4.}; 
+  // User change: tail cuts for image analysis
+
+  MImgCleanStd  clean(CleanLev[0], CleanLev[1]); // Applies tail cuts to image.
+
+
+  //  User change: signal extraction
+  //
+  //  MExtractFixedWindowPeakSearch sigextract;
+  //  sigextract.SetWindows(6, 6, 4);
+
+  MExtractTimeAndChargeDigitalFilter sigextract;
+  sigextract.SetNameWeightsFile("/users/emc/moralejo/Mars/msignal/MC_weights.dat");
+  sigextract.SetRange(1, 14, 3, 14);
+
+  ////////// Calibration //////////
+
+  MMcCalibrationUpdate  mccalibupdate;
+  ///// User change: calibrate in photons or phe- :
+  mccalibupdate.SetSignalType(MCalibrateData::kPhe);
+  //  mccalibupdate.SetSignalType(MCalibrateData::kPhot);
+
+
+  MSrcPosCam src;
+  //
+  // ONLY FOR WOBBLE MODE!!
+  //   src.SetX(120.);  // units: mm
+
+  src.SetReadyToSave();
+
+  // -------------------------------------------
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  src.SetReadyToSave();
+  plist.AddToList(&src);
+
+  MBadPixelsCam badpix;
+  plist.AddToList(&badpix);
+
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+
+  if (CalibrationFilename)
+    read.AddFile(CalibrationFilename->Data());
+
+  read.DisableAutoScheme();
+
+  MGeomApply geom; // Reads in geometry from MC file and sets the right sizes for
+  // several parameter containers.
+
+  MMcPedestalCopy   pcopy; 
+  // Copies pedestal data from the MC file run fadc header to the MPedestalCam container.
+
+  MPointingPosCalc pointcalc;
+  // Creates MPointingPos object and fill it with the telescope orientation
+  // information taken from MMcEvt.
+
+  MCalibrateData calib; // Applies calibration to the data
+  calib.SetCalibrationMode(MCalibrateData::kFfactor);
+  // Do not change the CalibrationMode above for MC...!
+  calib.SetSignalType(mccalibupdate.GetSignalType());
+
+  //    MBlindPixelCalc   blind;
+  //    blind.SetUseInterpolation();
+
+  MHillasCalc       hcalc; // Calculates Hillas parameters not dependent on source position.
+  hcalc.Disable(MHillasCalc::kCalcHillasSrc);
+
+  MMcCalibrationCalc mccalibcalc;
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geom);
+  tlist.AddToList(&pcopy);
+  tlist.AddToList(&pointcalc);
+
+  tlist.AddToList(&sigextract);
+  tlist.AddToList(&mccalibupdate);
+  tlist.AddToList(&calib);
+  tlist.AddToList(&clean);
+  //    tlist.AddToList(&blind);
+  tlist.AddToList(&hcalc);
+
+  tlist.AddToList(&mccalibcalc);
+
+  //
+  // Open output files:
+  //
+
+  MWriteRootFile write1(OutFilename1->Data()); // Writes output1
+  write1.AddContainer("MRawRunHeader", "RunHeaders");
+  write1.AddContainer("MMcRunHeader",  "RunHeaders");
+  write1.AddContainer("MSrcPosCam",    "RunHeaders");
+  write1.AddContainer("MGeomCam",      "RunHeaders");
+  write1.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+  write1.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+  write1.AddContainer("MMcFadcHeader",  "RunHeaders");
+  write1.AddContainer("MMcTrigHeader",  "RunHeaders");
+
+
+  write1.AddContainer("MMcEvt",        "Events");
+  write1.AddContainer("MHillas",       "Events");
+  write1.AddContainer("MHillasExt",    "Events");
+  write1.AddContainer("MHillasSrc",    "Events");
+  write1.AddContainer("MImagePar",     "Events");
+  write1.AddContainer("MNewImagePar",  "Events");
+  write1.AddContainer("MConcentration","Events");
+  write1.AddContainer("MPointingPos",  "Events");
+
+  if (OutFilename2)
+    {
+      MWriteRootFile write2(OutFilename2->Data()); // Writes output2
+      write2.AddContainer("MRawRunHeader", "RunHeaders");
+      write2.AddContainer("MMcRunHeader",  "RunHeaders");
+      write2.AddContainer("MSrcPosCam",    "RunHeaders");
+      write2.AddContainer("MGeomCam",      "RunHeaders");
+      write2.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+      write2.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+      write2.AddContainer("MMcFadcHeader",  "RunHeaders");
+      write2.AddContainer("MMcTrigHeader",  "RunHeaders");
+
+
+      write2.AddContainer("MMcEvt",        "Events");
+      write2.AddContainer("MHillas",       "Events");
+      write2.AddContainer("MHillasExt",    "Events");
+      write2.AddContainer("MHillasSrc",    "Events");
+      write2.AddContainer("MImagePar",     "Events");
+      write2.AddContainer("MNewImagePar",  "Events");
+      write2.AddContainer("MConcentration","Events");
+      write2.AddContainer("MPointingPos",  "Events");
+
+      //
+      // Divide output in train and test samples, using the event number
+      // (odd/even) to achieve otherwise unbiased event samples:
+      //
+      
+      MF filter1("{MMcEvt.fEvtNumber%2}>0.5");
+      MF filter2("{MMcEvt.fEvtNumber%2}<0.5");
+
+      write1.SetFilter(&filter1);
+      write2.SetFilter(&filter2);
+    }
+
+  //
+  // First loop: Calibration loop
+  //
+
+  //  MProgressBar bar;
+  //  bar.SetWindowName("Calibrating...");
+
+  MEvtLoop evtloop;
+  //  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (CalibrationFilename)
+    {
+      if (!evtloop.Eventloop())
+	return;
+      mccalibcalc->GetHistADC2PhotEl()->Write();
+      mccalibcalc->GetHistPhot2PhotEl()->Write();
+    }
+
+  //
+  // Second loop: analysis loop
+  //
+
+  //
+  // Change the read task by another one which reads the file we want to analyze:
+  //
+
+  MReadMarsFile read2("Events");
+  read2.AddFile(AnalysisFilename);
+  read2.DisableAutoScheme();
+  tlist.AddToListBefore(&read2, &read);
+  tlist.RemoveFromList(&read);
+
+  //
+  // Analyzed only the desired fraction of events, skip the rest:
+  //
+  MFEventSelector eventselector;
+  Float_t rejected_fraction = 1. - accepted_fraction; 
+  eventselector.SetSelectionRatio(rejected_fraction);
+  MContinue skip(&eventselector);
+  tlist.AddToListBefore(&skip, &sigextract);
+
+  //  bar.SetWindowName("Analyzing...");
+
+  tlist.RemoveFromList(&mccalibcalc); // Removes calibration task from list.
+
+  hcalc.Enable(MHillasCalc::kCalcHillasSrc);
+
+  // Add tasks to write output:
+
+  if (OutFilename2)
+    {
+      tlist.AddToList(&filter1);
+      tlist.AddToList(&filter2);
+      tlist.AddToList(&write2); 
+    }
+
+  tlist.AddToList(&write1); 
+
+  if (!evtloop.Eventloop())
+    return;
+
+
+  tlist.PrintStatistics();
+}
Index: /tags/Mars-V0.9/macros/starmc2.C
===================================================================
--- /tags/Mars-V0.9/macros/starmc2.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/starmc2.C	(revision 9772)
@@ -0,0 +1,148 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Abelardo Moralejo 1/2004 <mailto:moralejo@pd.infn.it>
+   !              Thomas Bretz  5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+   !
+   !   Copyright: MAGIC Software Development, 2000-2004
+   !
+   !
+   \* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  STARMC2 - STandard Analysis and Reconstruction (MC example)
+//
+//  This macro converts into image  parameters an input file of MC data 
+//  previously calibrated (see mccalibrate.C).
+//  
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MImgCleanStd.h"
+
+void starmc2()
+{
+  //  Char_t* AnalysisFilename = "calibrated_gamma_train.root"; // File to be analyzed
+  Char_t* AnalysisFilename = "calibrated_gamma_test.root"; // File to be analyzed
+
+  TString* OutFilename;
+
+  // Output file name
+  //  OutFilename = new TString("star_gamma_train.root");   // Output file name
+  OutFilename = new TString("star_gamma_test.root");   // Output file name
+
+  MImgCleanStd      clean(10., 5.); // Applies tail cuts to image.
+  clean.SetMethod(MImgCleanStd::kAbsolute);
+
+  // WARNING: the tightness of the tail cuts depends on the signal extraction method
+  // used in mccalibrate.C!! (some methods result in positively biased signals)
+
+  // ------------------------------------------------------------------
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  MSrcPosCam src;
+  //
+  // FOR WOBBLE MODE!! Set source position on camera here.
+  //  src.SetX(120.);  
+  // units: mm. This 120 mm correspond to MC wobble mode w+ for zbin>0
+  //
+
+  src.SetReadyToSave();
+
+  plist.AddToList(&src);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+
+  read.AddFile(AnalysisFilename);
+  read.DisableAutoScheme();
+
+
+  MHillasCalc       hcalc; // Calculates Hillas parameters not dependent on source position.
+  hcalc.Enable(MHillasCalc::kCalcHillasSrc);
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&clean);
+  tlist.AddToList(&hcalc);
+
+  //
+  // Open output file(s):
+  //
+  MWriteRootFile write(OutFilename->Data()); // Writes output   
+  //
+  // Add MC containers only if they exist. 
+  // In this way you can also run on real calibrated data.
+  //
+  write.AddContainer("MRawRunHeader", "RunHeaders");
+  write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+  write.AddContainer("MGeomCam",      "RunHeaders", kFALSE);
+  write.AddContainer("MMcConfigRunHeader",  "RunHeaders", kFALSE);
+  write.AddContainer("MMcCorsikaRunHeader", "RunHeaders", kFALSE);
+  write.AddContainer("MMcFadcHeader",  "RunHeaders", kFALSE);
+  write.AddContainer("MMcTrigHeader",  "RunHeaders", kFALSE);
+       
+  write.AddContainer("MMcEvt",        "Events", kFALSE);
+  write.AddContainer("MPointingPos",  "Events", kFALSE);
+  write.AddContainer("MMcTrig",       "Events", kFALSE);
+  write.AddContainer("MSrcPosCam",    "Events", kFALSE);
+  write.AddContainer("MRawEvtHeader", "Events");
+  write.AddContainer("MHillas",       "Events");
+  write.AddContainer("MHillasExt",    "Events");
+  write.AddContainer("MHillasSrc",    "Events");
+  write.AddContainer("MImagePar",     "Events");
+  write.AddContainer("MNewImagePar",  "Events");
+  write.AddContainer("MConcentration","Events");
+
+  //
+  // Next line makes that the tree "OriginalMC" containing the MMcEvtBasic
+  // container for all produced Corsika events from which the events in the
+  // normal "Events" tree derive:
+  //
+  write.AddCopySource("OriginalMC");
+
+  tlist.AddToList(&write);
+
+  //
+  // analysis loop
+  //
+
+  MEvtLoop evtloop;
+  MProgressBar bar;
+  bar.SetWindowName("Analyzing...");
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (!evtloop.Eventloop())
+    return;
+
+  tlist.PrintStatistics();
+
+  return;
+}
Index: /tags/Mars-V0.9/macros/starmcstereo.C
===================================================================
--- /tags/Mars-V0.9/macros/starmcstereo.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/starmcstereo.C	(revision 9772)
@@ -0,0 +1,267 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s):  Abelardo Moralejo 1/2004 <mailto:moralejo@pd.infn.it>
+!               Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  STARMCSTEREO - STandard Analysis and Reconstruction (for MC stereo files)
+//
+//  This macro is the standard converter to convert raw data from stereo 
+//  camera simulation into image parameters
+//
+/////////////////////////////////////////////////////////////////////////////
+
+//
+// User change. 
+//
+
+Float_t ctx[7] = {0., 0., 0., 0., 0., 0., 0.}; 
+Float_t cty[7] = {-70., -40., -30., 30., 50., 60., 70.}; // in meters
+//
+// FIXME: unfortunately present version of reflector was not prepared for
+// stereo configurations and keeps no track of CT position. So the positions
+// must be set above by the user, making sure that they correspond to the
+// files one is analysing.
+//
+
+void starmcstereo(Int_t ct1 = 2, Int_t ct2 = 5)
+{
+  if (ct1 > sizeof(ctx)/sizeof(ctx[0]) || 
+      ct2 > sizeof(ctx)/sizeof(ctx[0]) )
+    {
+      cout << endl << "Wrong CT id number!" << endl;
+      return;
+    }
+
+  Int_t CT[2] = {ct1, ct2};  // Only 2-telescope analysis for the moment
+  Int_t NCTs = sizeof(CT)/sizeof(CT[0]);
+
+
+  // ------------- user change -----------------
+
+  Char_t* AnalysisFilename = "gam-yXX-00001.root";  // File to be analyzed
+  Char_t* OutFileTag      = "gammas";           // Output file tag
+
+  Float_t CleanLev[2] = {4., 3.}; // Tail cuts for image analysis
+
+  Int_t BinsHigh[2] = {5, 9}; // First and last FADC bin of the range to be integrated,
+  Int_t BinsLow[2]  = {5, 9}; // for high and low gain respectively.
+
+  // -------------------------------------------
+
+  //
+  // This is a demonstration program which calculates the image 
+  // parameters from a Magic Monte Carlo root file. Units of Size are
+  // for the moment, FADC counts.
+  //
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  MSrcPosCam src[NCTs];
+  MBadPixelsCam badpix[NCTs];
+
+  for (Int_t ict = 0; ict < NCTs; ict++)
+    {
+      TString s = "MSrcPosCam;";
+      s += CT[ict];
+      src[ict].SetName(s);
+      src[ict].SetReadyToSave();
+      plist.AddToList(&(src[ict]));
+
+      TString b = "MBadPixelsCam;";
+      b += CT[ict];
+      badpix[ict].SetName(b);
+      badpix[ict].SetReadyToSave();
+      plist.AddToList(&(badpix[ict]));
+    }
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+  read.DisableAutoScheme();
+
+  read.AddFile(AnalysisFilename);
+
+  MGeomApply*        apply = new MGeomApply[NCTs];
+
+  MMcPedestalCopy*   pcopy = new MMcPedestalCopy[NCTs];
+
+  MExtractSignal*      sigextract = new MExtractSignal[NCTs];
+
+  MMcCalibrationUpdate*  mccalibupdate = new MMcCalibrationUpdate[NCTs];
+  MCalibrate* calib = new MCalibrate[NCTs];
+
+  MImgCleanStd**     clean = new MImgCleanStd*[NCTs];
+
+  MHillasCalc*       hcalc = new MHillasCalc[NCTs];
+  MHillasSrcCalc*    scalc = new MHillasSrcCalc[NCTs];
+
+  TString outfile = "star_";
+  outfile += CT[0];
+  if (NCTs==2)
+    {
+      outfile += "_";
+      outfile += CT[1];
+    }
+
+  //
+  // We have two output files (will be later train and test sampls for random forest)
+  //
+  outfile += "_";
+  outfile += OutFileTag;
+  outfile += "_train.root";
+  MWriteRootFile    write1(outfile);
+
+  outfile = "star_";
+  outfile += CT[0];
+  if (NCTs==2)
+    {
+      outfile += "_";
+      outfile += CT[1];
+    }
+
+  outfile += "_";
+  outfile += OutFileTag; 
+  outfile += "_test.root";
+
+  MWriteRootFile write2(outfile);
+
+  for (Int_t i = 0; i < NCTs; i++)
+    {
+      apply[i]->SetSerialNumber(CT[i]);
+
+      pcopy[i]->SetSerialNumber(CT[i]);
+
+      sigextract[i]->SetSerialNumber(CT[i]);
+      sigextract[i].SetRange(BinsHigh[0], BinsHigh[1], BinsLow[0], BinsLow[1]);
+
+      mccalibupdate[i]->SetSerialNumber(CT[i]);
+      calib[i]->SetSerialNumber(CT[i]);
+
+      clean[i] = new MImgCleanStd(CleanLev[0], CleanLev[1]);
+      clean[i]->SetSerialNumber(CT[i]);
+
+      hcalc[i]->SetSerialNumber(CT[i]);
+      scalc[i]->SetSerialNumber(CT[i]);
+
+      write1.SetSerialNumber(CT[i]);
+      write2.SetSerialNumber(CT[i]);
+
+      write1.AddContainer(write1.AddSerialNumber("MMcEvt"),       "Events");
+      write1.AddContainer(write1.AddSerialNumber("MHillas"),      "Events");
+      write1.AddContainer(write1.AddSerialNumber("MHillasExt"),   "Events");
+      write1.AddContainer(write1.AddSerialNumber("MHillasSrc"),   "Events");
+      write1.AddContainer(write1.AddSerialNumber("MNewImagePar"), "Events");
+      write1.AddContainer(write1.AddSerialNumber("MSrcPosCam"),   "RunHeaders");
+      write2.AddContainer(write2.AddSerialNumber("MMcEvt"),       "Events");
+      write2.AddContainer(write2.AddSerialNumber("MHillas"),      "Events");
+      write2.AddContainer(write2.AddSerialNumber("MHillasExt"),   "Events");
+      write2.AddContainer(write2.AddSerialNumber("MHillasSrc"),   "Events");
+      write2.AddContainer(write2.AddSerialNumber("MNewImagePar"), "Events");
+      write2.AddContainer(write2.AddSerialNumber("MSrcPosCam"),   "RunHeaders");
+    }
+
+  if (NCTs==2)
+    {
+      write1.AddContainer("MStereoPar", "Events");
+      write2.AddContainer("MStereoPar", "Events");
+    }
+
+  write1.AddContainer("MRawRunHeader", "RunHeaders");
+  write1.AddContainer("MMcRunHeader",  "RunHeaders");
+
+  write2.AddContainer("MRawRunHeader", "RunHeaders");
+  write2.AddContainer("MMcRunHeader",  "RunHeaders");
+
+  tlist.AddToList(&read);
+
+  for (i = 0; i < NCTs; i++)
+    {
+      tlist.AddToList(&(apply[i]));
+      tlist.AddToList(&(pcopy[i]));
+      tlist.AddToList(&(sigextract[i]));
+      tlist.AddToList(&(mccalibupdate[i]));
+      tlist.AddToList(&(calib[i]));
+      tlist.AddToList(clean[i]);
+      tlist.AddToList(&(hcalc[i]));
+      tlist.AddToList(&(scalc[i]));
+    }
+
+  MStereoCalc stereocalc;
+  stereocalc.SetCTids(CT[0],CT[1]);
+
+  //
+  // FIXME: telescope coordinates must be introduced by the user, since
+  // they are not available nor in the camera file, neither in the reflector 
+  // output.
+  //
+
+  stereocalc.SetCT1coor(ctx[CT[0]-1],cty[CT[0]-1]);
+  stereocalc.SetCT2coor(ctx[CT[1]-1],cty[CT[1]-1]);
+
+  tlist.AddToList(&stereocalc);
+
+
+  MF filter1("{MMcEvt;1.fEvtNumber%2}<0.5");
+  MF filter2("{MMcEvt;1.fEvtNumber%2}>0.5");
+  //
+  // ^^^^ Filters to divide output in two: test and train samples.
+  //
+
+  write1.SetFilter (&filter1);
+  write2.SetFilter (&filter2);
+
+  tlist.AddToList(&filter1);
+  tlist.AddToList(&write1);
+  tlist.AddToList(&filter2);
+  tlist.AddToList(&write2);
+
+  //
+  // Create and set up the eventloop
+  //
+  MProgressBar bar;
+
+  MEvtLoop evtloop;
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  //
+  // Execute your analysis
+  //
+  if (!evtloop.Eventloop())
+    return;
+
+  for (Int_t i= 0; i < NCTs; i++ )
+    delete clean[i];
+
+  tlist.PrintStatistics();
+}
Index: /tags/Mars-V0.9/macros/starplot.C
===================================================================
--- /tags/Mars-V0.9/macros/starplot.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/starplot.C	(revision 9772)
@@ -0,0 +1,115 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz et al, 08/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+
+void starplot(const char *filename="Gamma_*.root")
+{
+    //
+    // This is a demonstration program which plots the Hillas
+    // parameter from a file created with star.C
+    //
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList plist;
+
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Use this if you want to change the binning of one of
+    // the histograms. You can use:
+    // BinningConc, BinningConc1, BinningAsym, BinningM3Long,
+    // BinningM3Trans, BinningWidth, BinningLength, BinningDist,
+    // BinningHeadTail, BinningAlpha, BinningSize, BinningDelta,
+    // BinningPixels and BinningCamera
+    //
+    // For more information see MBinning and the corresponding
+    // histograms
+    //
+    // MBinning binsalpha("BinningAlpha");
+    // binsalpha.SetEdges(90, 0, 90);       // 90 bins from 0 to 90 deg
+    // plist.AddToList(&binsalpha);
+
+    // MBinning binssize("BinningSize");
+    // binssize.SetEdgesLog(50, 1, 1e7);
+    // plist.AddToList(&binssize);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    // The first argument is the tree you want to read.
+    //   Events:     Cosmic ray events
+    //   PedEvents:  Pedestal Events
+    //   CalEvents:  Calibration Events
+    //
+    MReadMarsFile read("Events", filename);
+    read.DisableAutoScheme();
+
+    MGeomApply geomapl;
+
+    MFillH hfill1("MHHillas", "MHillas");
+    MFillH hfill2("MHHillasExt");
+    MFillH hfill3("MHStarMap", "MHillas");
+    MFillH hfill4("HistExtSource [MHHillasExt]", "MHillasSrc");
+    MFillH hfill5("HistSource [MHHillasSrc]", "MHillasSrc");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // After the analysis is finished we can display the histograms
+    //
+    plist.FindObject("MHHillas")->DrawClone();
+    plist.FindObject("MHHillasExt")->DrawClone();
+    plist.FindObject("MHStarMap")->DrawClone();
+    plist.FindObject("HistSource")->DrawClone();
+    plist.FindObject("HistExtSource")->DrawClone();
+}
+
Index: /tags/Mars-V0.9/macros/status.C
===================================================================
--- /tags/Mars-V0.9/macros/status.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/status.C	(revision 9772)
@@ -0,0 +1,189 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  Status - Example how to use the MStatusDisplay
+//
+//  Use a camera file as input
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void status()
+{
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // Set update time to 5s
+    // d->SetUpdateTime(5000);
+
+    // Disable online update
+    // d->SetUpdateTime(-1);
+
+    d->SetLogStream(&gLog, kTRUE);            // Disables output to stdout
+    gLog.SetOutputFile("status.log", kTRUE);  // Enable output to file
+    //gLog.EnableOutputDevice(MLog::eStdout); // Enable output to stdout again
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // ------------- user change -----------------
+    MDirIter files(".", "G*.root", -1);
+    //files.Print("all");
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFiles(files);
+
+    MGeomApply        geomapl;
+
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+    MCerPhotCalc      ncalc;
+
+    TArrayS blinds(0);
+
+    MBlindPixelCalc blind;
+    blind.SetPixelIndices(blinds);
+    blind.SetUseInterpolation();
+
+    MSigmabarCalc     sgcal;
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+
+    MHCamEvent hist("PedestalRms");
+    hist.SetType(1);
+    plist.AddToList(&hist);
+
+    // -------------------------------------------
+    MHTriggerLvl0 trighi(254, "SaturationHi", "Saturation Rate of Hi Gains");
+    trighi.SetType(1);
+
+    MHCamEvent maxhi("MaxIdxHi", "Index of maximum hi-gain slice");
+    MHCamEvent maxlo("MaxIdxLo", "Index of maximum lo-gain slice");
+    maxhi.SetType(3);
+    maxlo.SetType(4);
+    plist.AddToList(&maxhi);
+    plist.AddToList(&maxlo);
+
+
+    MFillH fillhi(&trighi, "MRawEvtData");
+    MFillH hfilhi("MaxIdxHi", "MRawEvtData");
+    MFillH hfillo("MaxIdxLo", "MRawEvtData");
+    MFillH hfill0("Uncleaned [MHCamEvent]", "MCerPhotEvt");
+    MFillH hfill1("Pedestals [MHCamEvent]", "MPedestalCam");
+    MFillH hfill2("PedestalRms", "MPedestalCam");
+    MFillH hfill3("MHHillas", "MHillas");
+    MFillH hfill4("MHHillasExt");
+    MFillH hfill5("MHHillasExtSrc [MHHillasExt]", "MHillasSrc");
+    MFillH hfill6("MHHillasSrc","MHillasSrc");
+    MFillH hfill7("MHNewImagePar","MNewImagePar");
+    MFillH hfill8("MHStarMap", "MHillas");
+    MFillH hfill9("Cleaned [MHCamEvent]", "MCerPhotEvt");
+
+    MContinue cont1("MNewImagePar.fNumCorePixels<0");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&hfilhi);
+    tlist.AddToList(&hfillo);
+    tlist.AddToList(&fillhi);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&blind);
+    tlist.AddToList(&hfill0);
+    //tlist.AddToList(&sgcal);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&cont1);
+    tlist.AddToList(&scalc);
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+    tlist.AddToList(&hfill6);
+    tlist.AddToList(&hfill7);
+    tlist.AddToList(&hfill8);
+    tlist.AddToList(&hfill9);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    MHCamEvent *uncl = (MHCamEvent*)plist.FindObject("Uncleaned");
+    MHCamEvent *hped = (MHCamEvent*)plist.FindObject("Pedestals");
+    MHCamEvent *hrms = (MHCamEvent*)plist.FindObject("PedestalRms");
+    uncl->PrintOutliers(3);
+    hped->PrintOutliers(1.5);
+    hrms->PrintOutliers(4);
+    trighi.PrintOutliers(2.5);
+
+    //
+    // Make sure the display hasn't been deleted by the user while the
+    // eventloop was running.
+    //
+    if ((d = evtloop.GetDisplay()))
+    {
+        // Save data in a postscriptfile (status.ps)
+        //d->SaveAsPS();
+        /*
+         * ----------- Write status to a root file ------------
+         *
+         TFile file("status.root", "RECREATE");
+         d->Write();
+         file.Close();
+         delete d;
+         */
+    }
+    /*
+     * ----------- Read status from a root file ------------
+     *
+     TFile file2("status.root", "READ");
+     MStatusDisplay *d2 = new MStatusDisplay;
+     d2->Read();
+     */
+}
Index: /tags/Mars-V0.9/macros/sumcurrents.C
===================================================================
--- /tags/Mars-V0.9/macros/sumcurrents.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sumcurrents.C	(revision 9772)
@@ -0,0 +1,162 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// sumcurrents.C
+// =============
+//
+// This is a demonstration macro to display mean DC currents for all pixels.
+// The input is cc report file. The output are histograms and plots.
+// Using the MDirIter functionality you can process more than one file
+// in one or more directories. For more information see MDirIter.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void ProcessFile(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // Create the magic geometry
+    MGeomCamMagic geom;
+    plist.AddToList(&geom);
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+    MReportFileRead read(fname);
+    read.SetHasNoHeader();
+    read.AddToList("MReportCurrents");
+    tlist.AddToList(&read);
+
+    // create a task to fill a histogram
+    MFillH fill("MHCamEvent", "MCameraDC");
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // Now display the result of the loop
+    //
+    MHCamEvent &h2 = *(MHCamEvent*)plist->FindObject("MHCamEvent");
+    MHCamera &h = *(MHCamera*)h2.GetHistByName("sum");
+;
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(3, 2);
+
+    MHCamera *disp1=h.Clone();
+    MHCamera *disp2=h.Clone();
+    MHCamera *disp3=h.Clone();
+    disp2->SetCamContent(h, 1);
+    disp3->SetCamContent(h, 2);
+
+    disp1->SetYTitle("I [nA]");
+    disp2->SetYTitle("\\sigma_{I} [\\mu A]");
+    disp3->SetYTitle("\\sigma_{I} [%]");
+    disp1->SetName("Currents;avg");
+    disp2->SetName("Currents;err");
+    disp3->SetName("Currents;rel");
+    disp1->SetTitle("Currents Average");
+    disp2->SetTitle("Currents error");
+    disp3->SetTitle("Currents relative error");
+
+    c->cd(1);
+    TText text(0.1, 0.95, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.03);
+    text.DrawClone();
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp1->Draw();
+    disp1->SetBit(kCanDelete);
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp2->Draw();
+    disp2->SetBit(kCanDelete);
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp3->Draw();
+    disp3->SetBit(kCanDelete);
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    disp1->Draw("EPhist");
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    disp2->Draw("Phist");
+    c->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    disp3->Draw("Phist");
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
+void sumcurrents(const char *dirname=".")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "dc_*.txt", -1);
+
+    TString fname;
+    while (1)
+    {
+        fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+    }
+}
Index: /tags/Mars-V0.9/macros/sumevents.C
===================================================================
--- /tags/Mars-V0.9/macros/sumevents.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sumevents.C	(revision 9772)
@@ -0,0 +1,155 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void ProcessFile(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    MGeomApply geomapl;
+    MCerPhotAnal2 ncalc;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&ncalc);
+
+    MFillH fill("MHCamEvent", "MCerPhotEvt");
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(3, 2);
+
+    MHCamEvent &h = *(MHCamEvent*)plist->FindObject("MHCamEvent");
+    MHCamera *disp0 = h.GetHistByName();
+    MHCamera *disp1 = new MHCamera(geom, "MCerPhotEvt;avg", "Cerenkov Photons Avarage");
+    MHCamera *disp2 = new MHCamera(geom, "MCerPhotEvt;err", "Cerenkov Photons Error");
+    MHCamera *disp3 = new MHCamera(geom, "MCerPhotEvt;rel", "Cerenkov Photons ERR/VAL");
+    disp1->SetBit(kCanDelete);
+    disp2->SetBit(kCanDelete);
+    disp3->SetBit(kCanDelete);
+
+    disp1->SetCamContent(*disp0, 0);
+    disp2->SetCamContent(*disp0, 1);
+    disp3->SetCamContent(*disp0, 2);
+
+    disp1->SetYTitle("S [au]");
+    disp2->SetYTitle("\\sigma_{S} [au]");
+    disp3->SetYTitle("\\sigma_{S} [%]");
+
+    TText text(0.1, 0.5, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.015);
+    text.DrawClone();
+
+    c->cd(1);
+    gStyle->SetOptStat(1111);
+    disp1->Draw("hist");
+    gPad->Update();
+
+    c->cd(2);
+    gPad->SetLogy();
+    gStyle->SetOptStat(1101);
+    disp2->Draw("hist");
+    gPad->Update();
+
+    c->cd(3);
+    gPad->SetLogy();
+    gStyle->SetOptStat(1101);
+    disp3->Draw("hist");
+    gPad->Update();
+
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp1->Draw();
+
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp2->Draw();
+
+    c->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp3->Draw();
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+void sumevents(const char *dirname=".")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "*1947*.root", -1);
+
+    TString fname;
+    while (1)
+    {
+        fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+        return;
+    }
+}
Index: /tags/Mars-V0.9/macros/sumeventserr.C
===================================================================
--- /tags/Mars-V0.9/macros/sumeventserr.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sumeventserr.C	(revision 9772)
@@ -0,0 +1,158 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void ProcessFile(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    //MPedestalSum  ncalc;
+    //MCerPhotCalc  ncalc;
+    //MCerPhotAnal  ncalc;
+    MGeomApply geomapl;
+    MCerPhotAnal2 ncalc;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&ncalc);
+
+    MFillH fill("MHCamEvent", "MCerPhotEvt");
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(3, 2);
+
+    MHCamEvent &h = *(MHCamEvent*)plist->FindObject("MHCamEvent");
+    MHCamera *disp0 = h.GetHistByName();
+    MHCamera *disp1 = new MHCamera(geom, "MCerPhotEvt;avg", "Cerenkov Photons Avarage");
+    MHCamera *disp2 = new MHCamera(geom, "MCerPhotEvt;err", "Cerenkov Photons Error");
+    MHCamera *disp3 = new MHCamera(geom, "MCerPhotEvt;rel", "Cerenkov Photons ERR/VAL");
+    disp1->SetBit(kCanDelete);
+    disp2->SetBit(kCanDelete);
+    disp3->SetBit(kCanDelete);
+
+    disp1->SetCamContent(*disp0, 0);
+    disp2->SetCamContent(*disp0, 1);
+    disp3->SetCamContent(*disp0, 2);
+
+    disp1->SetYTitle("S_{err} [au]");
+    disp2->SetYTitle("\\sigma_{S_{err}} [au]");
+    disp3->SetYTitle("\\sigma_{S_{err}} [%]");
+
+    TText text(0.1, 0.5, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.015);
+    text.DrawClone();
+
+    c->cd(1);
+    gStyle->SetOptStat(1111);
+    disp1->Draw("hist");
+    gPad->Update();
+
+    c->cd(2);
+    gPad->SetLogy();
+    gStyle->SetOptStat(1101);
+    disp2->Draw("hist");
+    gPad->Update();
+
+    c->cd(3);
+    gPad->SetLogy();
+    gStyle->SetOptStat(1101);
+    disp3->Draw("hist");
+    gPad->Update();
+
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp1->Draw();
+
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp2->Draw();
+
+    c->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp3->Draw();
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+void sumeventserr(const char *dirname=".")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "*1947*.root", -1);
+
+    TString fname;
+    while (1)
+    {
+        fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+        return;
+    }
+}
Index: /tags/Mars-V0.9/macros/sumeventsrms.C
===================================================================
--- /tags/Mars-V0.9/macros/sumeventsrms.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sumeventsrms.C	(revision 9772)
@@ -0,0 +1,159 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void ProcessFile(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    MGeomApply geomapl;
+    MPedestalSum  ncalc;
+    //MCerPhotCalc  ncalc;
+    //MCerPhotAnal  ncalc;
+    //MCerPhotAnal2 ncalc;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&ncalc);
+
+    MHCamEvent hist;
+    hist.SetType(3);
+    plist.AddToList(&hist);
+
+    MFillH fill("MHCamEvent", "MCerPhotEvt");
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(3, 2);
+
+    MHCamEvent &h = *(MHCamEvent*)plist->FindObject("MHCamEvent");
+    MHCamera *disp0 = h.GetHistByName();
+    MHCamera *disp1 = new MHCamera(geom, "MCerPhotEvt;avg", "Cerenkov Photons RMS Avarage");
+    MHCamera *disp2 = new MHCamera(geom, "MCerPhotEvt;err", "Cerenkov Photons RMS Error");
+    MHCamera *disp3 = new MHCamera(geom, "MCerPhotEvt;rel", "Cerenkov Photons RMS ERR/VAL");
+    disp1->SetBit(kCanDelete);
+    disp2->SetBit(kCanDelete);
+    disp3->SetBit(kCanDelete);
+
+    disp1->SetCamContent(*disp0, 0);
+    disp2->SetCamContent(*disp0, 1);
+    disp3->SetCamContent(*disp0, 2);
+
+    disp2->SetStats(kFALSE);
+    disp3->SetStats(kFALSE);
+
+    disp1->SetYTitle("a.u.");
+    disp2->SetYTitle("err");
+    disp3->SetYTitle("rel.err [%]");
+
+    TText text(0.1, 0.5, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.015);
+    text.DrawClone();
+
+    c->cd(1);
+    disp1->Draw("hist");
+
+    c->cd(2);
+    gPad->SetLogy();
+    disp2->Draw("hist");
+
+    c->cd(3);
+    gPad->SetLogy();
+    disp3->Draw("hist");
+
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp1->Draw();
+
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp2->Draw();
+
+    c->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp3->Draw();
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+void sumeventsrms(const char *dirname=".")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "*ped*.root", -1);
+
+    TString fname;
+    while (1)
+    {
+        fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+        return;
+    }
+}
Index: /tags/Mars-V0.9/macros/sumpedestalrms.C
===================================================================
--- /tags/Mars-V0.9/macros/sumpedestalrms.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sumpedestalrms.C	(revision 9772)
@@ -0,0 +1,157 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void ProcessFile(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    MGeomApply geomapl;
+    MCerPhotAnal2 ncalc;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&ncalc);
+
+    MHCamEvent hist;
+    hist.SetType(1);
+    plist.AddToList(&hist);
+
+    MFillH fill("MHCamEvent", "MPedestalCam");
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(3, 2);
+
+    MHCamEvent &h = *(MHCamEvent*)plist->FindObject("MHCamEvent");
+    MHCamera *disp0 = h.GetHistByName();
+    MHCamera *disp1 = new MHCamera(geom, "MPedestalCam;avg", "Pedestal-RMS Avarage");
+    MHCamera *disp2 = new MHCamera(geom, "MPedestalCam;err", "Pedestal-RMS Avarage Error");
+    MHCamera *disp3 = new MHCamera(geom, "MPedestalCam;rel", "Pedestal-RMS Avarage ERR/VAL");
+    disp1->SetBit(kCanDelete);
+    disp2->SetBit(kCanDelete);
+    disp3->SetBit(kCanDelete);
+
+    disp1->SetCamContent(*disp0, 0);
+    disp2->SetCamContent(*disp0, 1);
+    disp3->SetCamContent(*disp0, 2);
+
+    disp1->SetYTitle("P_{rms} [au]");
+    disp2->SetYTitle("\\sigma_{P_{rms}} [au]");
+    disp3->SetYTitle("\\sigma_{P_{rms}} [%]");
+
+    TText text(0.1, 0.5, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.015);
+    text.DrawClone();
+
+    c->cd(1);
+    gStyle->SetOptStat(1111);
+    disp1->Draw("hist");
+    gPad->Update();
+
+    c->cd(2);
+    gStyle->SetOptStat(1101);
+    disp2->Draw("hist");
+    gPad->Update();
+
+    c->cd(3);
+    gStyle->SetOptStat(1101);
+    disp3->Draw("hist");
+    gPad->Update();
+ 
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp1->Draw();
+
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp2->Draw();
+
+    c->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp3->Draw();
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+void sumpedestalrms(const char *dirname=".")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "*1947*.root", -1);
+
+    TString fname;
+    while (1)
+    {
+        fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+        return;
+    }
+}
Index: /tags/Mars-V0.9/macros/sumpedestals.C
===================================================================
--- /tags/Mars-V0.9/macros/sumpedestals.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/sumpedestals.C	(revision 9772)
@@ -0,0 +1,153 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+void ProcessFile(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // First Task: Read file with image parameters
+    // (created with the star.C macro)
+
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    MGeomApply geomapl;
+    MCerPhotAnal2 ncalc;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&ncalc);
+
+    MFillH fill("MHCamEvent", "MPedestalCam");
+    tlist.AddToList(&fill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(3, 2);
+
+    MHCamEvent &h = *(MHCamEvent*)plist->FindObject("MHCamEvent");
+    MHCamera *disp0 = h.GetHistByName();
+    MHCamera *disp1 = new MHCamera(geom, "MPedestalCam;avg", "Pedestals Avarage");
+    MHCamera *disp2 = new MHCamera(geom, "MPedestalCam;rms", "Pedestals Avarage Error");
+    MHCamera *disp3 = new MHCamera(geom, "MPedestalCam;rel", "Pedestals Avarage ERR/VAL");
+    disp1->SetBit(kCanDelete);
+    disp2->SetBit(kCanDelete);
+    disp3->SetBit(kCanDelete);
+
+    disp1->SetCamContent(*disp0, 0);
+    disp2->SetCamContent(*disp0, 1);
+    disp3->SetCamContent(*disp0, 2);
+
+    disp1->SetYTitle("P [au]");
+    disp2->SetYTitle("\\sigma_{P} [au]");
+    disp3->SetYTitle("\\sigma_{P} [%]");
+
+    TText text(0.1, 0.5, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.015);
+    text.DrawClone();
+
+    c->cd(1);
+    gStyle->SetOptStat(1111);
+    disp1->Draw("hist");
+    gPad->Update();
+
+    c->cd(2);
+    gStyle->SetOptStat(1101);
+    disp2->Draw("hist");
+    gPad->Update();
+
+    c->cd(3);
+    gStyle->SetOptStat(1101);
+    disp3->Draw("hist");
+    gPad->Update();
+
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp1->Draw();
+
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp2->Draw();
+
+    c->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    disp3->Draw();
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+void sumpedestals(const char *dirname=".")
+{
+    MDirIter Next;
+    Next.AddDirectory(dirname, "*1947*.root", -1);
+
+    TString fname;
+    while (1)
+    {
+        fname = Next();
+        if (fname.IsNull())
+            break;
+
+        ProcessFile(fname);
+        return;
+    }
+}
Index: /tags/Mars-V0.9/macros/tar.C
===================================================================
--- /tags/Mars-V0.9/macros/tar.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/tar.C	(revision 9772)
@@ -0,0 +1,65 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// tar.C
+// =====
+//
+// Service script. used to create the tar archive for an release. It makes
+// sure that the correct files are included and the name of the archive is
+// the name of the current directory (+.tar.gz)
+//
+///////////////////////////////////////////////////////////////////////////
+void tar()
+{
+    TString dir = gSystem->pwd();
+
+    Int_t slash = dir.Last('/');
+
+    TString name = &dir[slash+1];
+
+    if (!gSystem->AccessPathName("../"+name+".tar"))
+    {
+        cout << "File '../" << name << ".tar' existing." << endl;
+        return;
+    }
+
+    if (!gSystem->AccessPathName("../"+name+".tar.gz"))
+    {
+        cout << "File '../" << name << ".tar.gz' existing." << endl;
+        return;
+    }
+
+    gSystem->cd("..");
+
+    TString cmd = "tar cvf "+name+".tar --exclude=Makefile.depend --exclude=Root --exclude=Tag --exclude=mtemp "+name+"/.rootrc "+name+"/*";
+
+    cout << "Executing: " << cmd << endl;
+
+    gSystem->Exec(cmd);
+    gSystem->Exec("gzip -9 "+name+".tar");
+
+    gSystem->cd(name);
+}
Index: /tags/Mars-V0.9/macros/testMTrans.C
===================================================================
--- /tags/Mars-V0.9/macros/testMTrans.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/testMTrans.C	(revision 9772)
@@ -0,0 +1,453 @@
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// Description: Macro to test the class MTransCelLocCam
+//
+// Author:      Wolfgang Wittek (wittek@mppmu.mpg.de)
+// Date:        08/2004
+//                                                                         // 
+/////////////////////////////////////////////////////////////////////////////
+
+void testMTrans()
+{
+  gLog->SetNoColors();
+
+
+    MGeomCamMagic geom;
+    MObservatory  obs;
+
+    MStarCamTrans trans(geom, obs);
+
+    trans.SetGridParameters(0.50, 0.1);
+
+    /*
+    trans.PlotGridAtTheta0Phi0("Plot_2a",  0.001,135.0);
+    trans.PlotGridAtTheta0Phi0("Plot_2b",  30.00,135.0);
+    trans.PlotGridAtTheta0Phi0("Plot_2c",  60.00,135.0);
+    trans.PlotGridAtTheta0Phi0("Plot_2d",  90.00,135.0);
+
+    trans.PlotGridAtTheta0Phi0("Plot1a",  0.001, 0.0);
+    trans.PlotGridAtTheta0Phi0("Plot1b",  30.00, 0.0);
+    trans.PlotGridAtTheta0Phi0("Plot1c",  60.00, 0.0);
+    trans.PlotGridAtTheta0Phi0("Plot1d",  90.00, 0.0);
+
+    trans.PlotGridAtTheta0Phi0("Plot2a",  0.001, 90.0);
+    trans.PlotGridAtTheta0Phi0("Plot2b",  30.00, 90.0);
+    trans.PlotGridAtTheta0Phi0("Plot2c",  60.00, 90.0);
+    trans.PlotGridAtTheta0Phi0("Plot2d",  90.00, 90.0);
+
+
+    trans.PlotGridAtTheta0Phi0("Plot3a",  0.001, 180.0);
+    */
+
+    trans.PlotGridAtTheta0Phi0("Plot3b",  30.00, 180.0);
+
+    /*
+
+    trans.PlotGridAtTheta0Phi0("Plot3c",  60.00, 180.0);
+    trans.PlotGridAtTheta0Phi0("Plot3d",  90.00, 180.0);
+
+    trans.PlotGridAtTheta0Phi0("Plot4a",  0.001, 270.0);
+    trans.PlotGridAtTheta0Phi0("Plot4b",  30.00, 270.0);
+    trans.PlotGridAtTheta0Phi0("Plot4c",  60.00, 270.0);
+    trans.PlotGridAtTheta0Phi0("Plot4d",  90.00, 270.0);
+
+    trans.PlotGridAtDec0H0    ("Plot5a", 89.999, -12.0);
+    trans.PlotGridAtDec0H0    ("Plot5b", 60.000, -12.0);
+    trans.PlotGridAtDec0H0    ("Plot5c", 30.000, -12.0);
+    trans.PlotGridAtDec0H0    ("Plot5d",  0.000, -12.0);
+    trans.PlotGridAtDec0H0    ("Plot5e",-30.000, -12.0);
+
+    trans.PlotGridAtDec0H0    ("Plot6a", 89.999, -6.0);
+    trans.PlotGridAtDec0H0    ("Plot6b", 60.000, -6.0);
+    trans.PlotGridAtDec0H0    ("Plot6c", 30.000, -6.0);
+    trans.PlotGridAtDec0H0    ("Plot6d",  0.000, -6.0);
+    trans.PlotGridAtDec0H0    ("Plot6e",-30.000, -6.0);
+
+    trans.PlotGridAtDec0H0    ("Plot7a", 89.999, 0.0);
+    trans.PlotGridAtDec0H0    ("Plot7b", 60.000, 0.0);
+    trans.PlotGridAtDec0H0    ("Plot7c", 30.000, 0.0);
+    trans.PlotGridAtDec0H0    ("Plot7d",  0.000, 0.0);
+    trans.PlotGridAtDec0H0    ("Plot7e",-30.000, 0.0);
+
+    trans.PlotGridAtDec0H0    ("Plot8a", 89.999, 6.0);
+    trans.PlotGridAtDec0H0    ("Plot8b", 60.000, 6.0);
+    trans.PlotGridAtDec0H0    ("Plot8c", 30.000, 6.0);
+    trans.PlotGridAtDec0H0    ("Plot8d",  0.000, 6.0);
+    trans.PlotGridAtDec0H0    ("Plot8e",-30.000, 6.0);
+    */
+
+    //===================================================
+    // special tests
+
+    gLog << "==============================================================="
+         << endl;
+
+    Double_t th1 = 10.0;
+    Double_t ph1 = 200.0;
+    Double_t X1  = 0.0;
+    Double_t Y1  = 0.0;
+    Double_t X2  = 100.0;
+    Double_t Y2  =  50.0;
+    Double_t th2;
+    Double_t ph2;
+
+    trans.LocCamCamToLoc(th1, ph1, X1, Y1, X2, Y2, th2, ph2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+    
+    trans.Loc0CamToLoc(th1, ph1, X2, Y2, th2, ph2);    
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.Loc0LocToCam(th1, ph1, th2, ph2, X2, Y2);    
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamToLoc0(th2, ph2, X2, Y2, th1, ph1);    
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamLocToCam(th1, ph1, X1, Y1, th2, ph2, X2, Y2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.Loc0LocToCam(th1, ph1, th2, ph2, X2, Y2);    
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+    gLog << "==============================================================="
+         << endl;
+
+    //---------------------
+
+    gLog << "==============================================================="
+         << endl;
+
+    th1 =  th2;
+    ph1 =  ph2;
+    X1  = 100.0;
+    Y1  =  50.0;
+    X2  =  0.0;
+    Y2  =  0.0;
+
+    trans.LocCamCamToLoc(th1, ph1, X1, Y1, X2, Y2, th2, ph2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+    
+    trans.LocCamToLoc0(th1, ph1, X1, Y1, th2, ph2);    
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.Loc0CamToLoc(th2, ph2, X1, Y1, th1, ph1);    
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.Loc0LocToCam(th2, ph2, th1, ph1, X1, Y1);    
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamLocToCam(th1, ph1, X1, Y1, th2, ph2, X2, Y2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    Double_t de1 = 10.0;
+    Double_t ho1 = 200.0;
+    Double_t XX1  = 0.0;
+    Double_t YY1  = 0.0;
+    Double_t XX2  = 100.0;
+    Double_t YY2  =  50.0;
+    Double_t de2;
+    Double_t ho2;
+
+    trans.CelCamCamToCel(de1, ho1, XX1, YY1, XX2, YY2, de2, ho2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+    
+    trans.Cel0CamToCel(de1, ho1, XX2, YY2, de2, ho2);    
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    trans.CelCamCelToCam(de1, ho1, XX1, YY1, de2, ho2, XX2, YY2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    trans.Cel0CelToCam(de1, ho1, de2, ho2, XX2, YY2);    
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+
+    gLog << "==============================================================="
+         << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    de1 =  de2;
+    ho1 =  ho2;
+    XX1  = 100.0;
+    YY1  =  50.0;
+    XX2  =  0.0;
+    YY2  =  0.0;
+
+    trans.CelCamCamToCel(de1, ho1, XX1, YY1, XX2, YY2, de2, ho2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+    
+    trans.CelCamToCel0(de1, ho1, XX1, YY1, de2, ho2);    
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    trans.CelCamCelToCam(de1, ho1, XX1, YY1, de2, ho2, XX2, YY2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    //---------------------
+
+    gLog << "==============================================================="
+         << endl;
+
+    th1 =  70.0;
+    ph1 = 200.0;
+    X1  = 100.0;
+    Y1  =  50.0;
+    X2  = 120.0;
+    Y2  = -30.0;
+
+    Double_t th0;
+    Double_t ph0;
+
+    trans.LocCamCamToLoc(th1, ph1, X1, Y1, X2, Y2, th2, ph2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamCamToLoc(th2, ph2, X2, Y2, X1, Y1, th1, ph1);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamToLoc0(th1, ph1, X1, Y1, th0, ph0);
+    gLog << "th0, ph0 = " << th0 << ",  " << ph0 << endl;
+
+    trans.Loc0CamToLoc(th0, ph0, X1, Y1, th1, ph1);
+    gLog << "th1, ph1 = " << th1 << ",  " << ph1 << endl;
+
+    trans.Loc0CamToLoc(th0, ph0, X2, Y2, th2, ph2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamToLoc0(th2, ph2, X2, Y2, th0, ph0);
+    gLog << "th0, ph0 = " << th0 << ",  " << ph0 << endl;
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamLocToCam(th1, ph1, X1, Y1, th2, ph2, X2, Y2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamLocToCam(th2, ph2, X2, Y2, th1, ph1, X1, Y1);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamToLoc0(th1, ph1, X1, Y1, th0, ph0);
+    gLog << "th0, ph0 = " << th0 << ",  " << ph0 << endl;
+
+    trans.Loc0LocToCam(th0, ph0, th2, ph2, X2, Y2);
+
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    th1 = th2;
+    ph1 = ph2;
+    X1  = 120.0;
+    Y1  = -30.0;
+    X2  = 100.0;
+    Y2  =  50.0;
+
+    Double_t th0;
+    Double_t ph0;
+
+    trans.LocCamCamToLoc(th1, ph1, X1, Y1, X2, Y2, th2, ph2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamToLoc0(th1, ph1, X1, Y1, th0, ph0);
+    gLog << "th0, ph0 = " << th0 << ",  " << ph0 << endl;
+
+    trans.Loc0CamToLoc(th0, ph0, X2, Y2, th2, ph2);
+
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamLocToCam(th1, ph1, X1, Y1, th2, ph2, X2, Y2);
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    trans.LocCamToLoc0(th1, ph1, X1, Y1, th0, ph0);
+    gLog << "th0, ph0 = " << th0 << ",  " << ph0 << endl;
+
+    trans.Loc0LocToCam(th0, ph0, th2, ph2, X2, Y2);
+
+    gLog << "th1, ph1, X1, Y1, th2, ph2, X2, Y2 = "
+         << th1 << ",  " << ph1 << ";    " << X1 << ",  " << Y1 << ";   "
+         << th2 << ",  " << ph2 << ";    " << X2 << ",  " << Y2 << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    Double_t de1 = 10.0;
+    Double_t ho1 = 3.0;
+    Double_t XX1  = -30.0;
+    Double_t YY1  = 200.0;
+    Double_t XX2  = 100.0;
+    Double_t YY2  =  50.0;
+    Double_t de2;
+    Double_t ho2;
+
+    trans.CelCamCamToCel(de1, ho1, XX1, YY1, XX2, YY2, de2, ho2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    Double_t de0;
+    Double_t ho0;
+    trans.CelCamToCel0(de1, ho1, XX1, YY1, de0, ho0);
+    gLog << "de0, ho0 = " << de0 << ",  " << ho0 << endl;
+
+    trans.Cel0CamToCel(de0, ho0, XX2, YY2, de2, ho2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    trans.CelCamCelToCam(de1, ho1, XX1, YY1, de2, ho2, XX2, YY2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    trans.CelCamToCel0(de1, ho1, XX1, YY1, de0, ho0);
+    gLog << "de0, ho0 = " << de0 << ",  " << ho0 << endl;
+
+    trans.Cel0CelToCam(de0, ho0, de2, ho2, XX2, YY2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+
+    gLog << "==============================================================="
+         << endl;
+
+    gLog << "==============================================================="
+         << endl;
+
+    de1 = de2;
+    ho1 = ho2;
+    XX1  = 100.0;
+    YY1  =  50.0;
+    XX2  = -30.0;
+    YY2  = 200.0;
+
+    trans.CelCamCamToCel(de1, ho1, XX1, YY1, XX2, YY2, de2, ho2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    Double_t de0;
+    Double_t ho0;
+    trans.CelCamToCel0(de1, ho1, XX1, YY1, de0, ho0);
+    gLog << "de0, ho0 = " << de0 << ",  " << ho0 << endl;
+
+    trans.Cel0CamToCel(de0, ho0, XX2, YY2, de2, ho2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    trans.CelCamCelToCam(de1, ho1, XX1, YY1, de2, ho2, XX2, YY2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+    trans.CelCamToCel0(de1, ho1, XX1, YY1, de0, ho0);
+    gLog << "de0, ho0 = " << de0 << ",  " << ho0 << endl;
+
+    trans.Cel0CelToCam(de0, ho0, de2, ho2, XX2, YY2);
+    gLog << "de1, ho1, XX1, YY1, de2, ho2, XX2, YY2 = "
+         << de1 << ",  " << ho1 << ";    " << XX1 << ",  " << YY1 << ";   "
+         << de2 << ",  " << ho2 << ";    " << XX2 << ",  " << YY2 << endl;
+
+
+    gLog << "==============================================================="
+         << endl;
+
+}
+//=========================================================================
+ 
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/macros/testenv.C
===================================================================
--- /tags/Mars-V0.9/macros/testenv.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/testenv.C	(revision 9772)
@@ -0,0 +1,120 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// testenv.C
+// =========
+//
+// This example reads an config-file (steering card, input card, ...)
+// The contents of the file a forwarded to the apropriate eventloop
+// setup in your file.
+//
+// All tasks and containers in an eventloop should implement the
+// ReadEnv/WriteEnv function (for an example see the tasks used below).
+//
+// The functions gets the corresponding setup data from the file as an
+// argument and can change their behaviour and setup on this information.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void testenv()
+{
+    // Setup for all MHMatrix objects is done by:
+    // MHMatrix.Column0: ...
+    //
+    // This can be overwritten for a MHMatrix called MatrixGammas by:
+    // MatrixGammas.Column0;
+    //
+    // This can be overwritten for all MHMatrix in one Job by:
+    // Job1.MHMatrix.Column0;
+    //
+    // This can be overwritten for a MHMatrix called MatrixGammas in one Job by:
+    // Job1.MatrixGammas.Column0;
+    //
+    TEnv env(".marsrc");
+
+    //
+    // For developers: Set this to kTRUE to see how the TEnv file
+    // entries are checked.
+    //
+    Bool_t print = kFALSE;
+
+    // ------------ Job 1 -------------------
+    if (env.GetValue("Job1", kFALSE))
+    {
+        cout << "++++++++++++++++++ Job 1 +++++++++++++++++++" << endl;
+        MParList plist1;
+        MTaskList tlist1;
+
+        plist1.AddToList(&tlist1);
+
+        MReadMarsFile read1("Events");
+
+        MHMatrix matrix1("MatrixGammas");
+
+        MFillH fillm1(&matrix1);
+        plist1.AddToList(&matrix1);
+
+        tlist1.AddToList(&read1);
+        tlist1.AddToList(&fillm1);
+
+        MEvtLoop evtloop1("Job1");
+        evtloop1.SetParList(&plist1);
+        cout << "--------------------------------------------" << endl;
+        evtloop1.ReadEnv(env, "", print);
+        cout << "--------------------------------------------" << endl;
+        evtloop1.Eventloop();
+        cout << endl;
+    }
+
+    // ------------ Job 2 -------------------
+
+    if (env.GetValue("Job2", kTRUE))
+    {
+        cout << "++++++++++++++++++ Job 2 +++++++++++++++++++" << endl;
+        MParList plist2;
+        MTaskList tlist2;
+
+        plist2.AddToList(&tlist2);
+
+        MReadMarsFile read2("Events");
+
+        MHMatrix matrix2("MatrixGammas");
+
+        MFillH fillm2(&matrix2);
+        plist2.AddToList(&matrix2);
+
+        tlist2.AddToList(&read2);
+        tlist2.AddToList(&fillm2);
+
+        MEvtLoop evtloop2("Job2");
+        evtloop2.SetParList(&plist2);
+        cout << "--------------------------------------------" << endl;
+        evtloop2.ReadEnv(env, "", print);
+        cout << "--------------------------------------------" << endl;
+        evtloop2.Eventloop();
+        cout << endl;
+    }
+}
Index: /tags/Mars-V0.9/macros/threshold.C
===================================================================
--- /tags/Mars-V0.9/macros/threshold.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/threshold.C	(revision 9772)
@@ -0,0 +1,116 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+void threshold(TString filename="data/camera.root", TString outname="")
+{
+    //
+    // This macro fill the container MHMcEnergies using the task
+    // MMcThresholdCalc and shows the results.
+    //
+    MParList parlist;
+
+    MTaskList tasklist;
+    parlist.AddToList(&tasklist);
+
+    //
+    // Setup the parameter list
+    // - You need create the container MHMcEnergies.
+    //    + You need to put the number of trigger conditions when
+    //      you declarete the MHMcEnergies
+    //    + If you don't put any dimension to MHMcEnergies it works
+    //      taking only the trigger information from MMcTrig
+    //
+    const UInt_t numtrigcond = 0;
+
+    UInt_t from = numtrigcond>0 ?           1 : -numtrigcond;
+    UInt_t to   = numtrigcond>0 ? numtrigcond : -numtrigcond;
+
+    Int_t dim = to-from+1;
+
+    //
+    // Create numtriggerconditions histograms of type MHMcEnergy
+    // and store the histograms in an TObjArray
+    //
+    TObjArray hists(MParList::CreateObjList("MHMcEnergy", from, to));
+    hists.SetOwner();
+
+    //
+    // Check if the list really contains the right number of histograms
+    //
+    if (hists.GetEntriesFast() != dim)
+        return;
+
+    //
+    // Add the histograms to the paramater list.
+    //
+    parlist.AddToList(&hists);
+
+    //
+    // Setup the task list
+    // - You need the read and the MMcThresholdCalc tasks
+    // - You have to fill the histograms for the Energy threshold
+    //    + You need to put the number of trigger conditions when
+    //      you declarete the MMcThresholdCalc
+    //    + If you don't put any dimension to MMcThresholdCalc it works
+    //      like one dimension MMcThresholdCalc
+    //
+    MReadTree read("Events", filename);
+    MMcThresholdCalc calc(numtrigcond);
+
+    tasklist.AddToList(&read);
+    tasklist.AddToList(&calc);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&parlist);
+
+    //
+    // Begin the loop (if the loop wasn't succesfull
+    // don't try to draw the results
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    //
+    // Now you can display the results
+    //
+    hists.Print();
+
+    TIter Next(&hists);
+    TObject *obj;
+    while ((obj=Next()))
+        obj->DrawClone();
+
+    // Write histogram to a file in case an output filename has been supplied:
+    if (outname.IsNull())
+        return;
+
+    TFile f(outname, "recreate");
+    if (!f)
+        return;
+
+    parlist.FindObject("MHMcEnergy")->Write();
+}
Index: /tags/Mars-V0.9/macros/triglvl2.C
===================================================================
--- /tags/Mars-V0.9/macros/triglvl2.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/triglvl2.C	(revision 9772)
@@ -0,0 +1,228 @@
+//   triglvl2.C
+//  Macro to use the class MMcTriggerLvl2, which calculates the 
+//   2nd level trigger (L2T) selection parameters.
+//  Filters to select events using these parameter and 
+//  histograms with selection variables distributions are also created.
+//
+//   Inputs:
+//      - filename      name of data file
+//      - CompactNN     number of NN to define a compact pixel
+//      - fValue        comparision value for the filter
+//
+//  23/04/2003 Added example of MFEnergySlope filter
+//
+//  
+void triglvl2(char *filename = "Gamma.root")
+  //    USER:   Data File Name    ---^
+{ 
+    //
+    // first we have to create our empty lists
+    //
+    MParList  parlist;
+    MTaskList tasklist;
+
+    parlist.AddToList(&tasklist);
+
+    // 
+    // Setup our tasks:
+    //  - First we have to read the events
+    //  - Then we can fill the efficiency histograms
+    //
+    
+
+    MReadMarsFile reader("Events", filename);
+    reader.DisableAutoScheme();
+     //  reader.EnableBranch("fEnergy");
+     //  reader.EnableBranch("fImpact"); reader.EnableBranch("fTimeFirst[4]");
+     //  reader.EnableBranch("fPixelsFirst[73][4]");
+   
+    tasklist.AddToList(&reader);
+    MGeomCamMagic geocam;
+    parlist.AddToList(&geocam);
+
+    //    MHillas hillas;
+    // parlist.AddToList(&hillas);
+
+    // An instance of the class MMcTriggerLvl2 is created and added to the 
+    //  parameter list
+    MMcTriggerLvl2 cell;     
+    parlist.AddToList(&cell);
+
+    MMcEvt mevt;
+    parlist.AddToList(&mevt);
+
+    // Set the number of Next Neighbourhoods that define a compact pixel
+    //
+    cell.SetCompactNN(3);
+    //  USER:       --^
+
+    //
+    //  A filter to select events using the L2T parameters is created
+    //
+    // MF lvl2filter("MMcTriggerLvl2.fPseudoSize > 25 && MMcTriggerLvl2.fPseudoSize < 31");
+    //    MF lvl2filter("MMcTriggerLvl2.fSizeBiggerCell > 34");
+    MF lvl2filter("MMcTriggerLvl2.fSizeBiggerCell > 18");
+ 
+    //
+    // A second filter is created using the class MFTriggerLvl2
+    //
+    MFTriggerLvl2 fTrig("MMcTriggerLvl2", '>', 8);
+    //      USER:       fValue to be compared --^
+
+    //
+    // A selection on the number and energy of the events 
+    //
+    MF energyfilter("MMcEvt.fEnergy > 100");
+    MFEventSelector selector;
+    //selector.SetNumSelectEvts(4000);
+
+
+    // Filter to select events according to a give slope
+    MFEnergySlope eslope;
+
+    eslope.SetMcMinEnergy(50.);
+    eslope.SetMcMaxEnergy(400.);
+    eslope.SetNewSlope(-.5);
+
+    // A filter list is created; the filters created can be added to the list
+    //
+    MFilterList flist;
+    //flist.AddToList(&energyfilter);
+    flist.AddToList(&lvl2filter);
+    //   flist.AddToList(&selector);
+    //   flist.AddToList(&eslope);
+    //   flist.AddToList(&fTrig);
+
+    //
+    // The task to calculate the L2T parameter is added to the task list
+    //
+    MMcTriggerLvl2Calc calcps("MMcTriggerLvl2","MMcTriggerLvl2");  
+    tasklist.AddToList(&calcps);
+
+    //
+    // The filter list is added to the task list
+    //
+    tasklist.AddToList(&flist);
+
+
+    MContinue L1offline ("MMcTriggerLvl2.fLutPseudoSize < 6");
+    //    tasklist.AddToList(&L1offline);
+
+    //
+    //  Task to calculate and plot the effective area
+    //
+    MMcCollectionAreaCalc effi;
+    tasklist.AddToList(&effi);    
+    //
+    // The filter list selects events for the effective area calculation
+    //
+    effi.SetFilter(&flist);
+ 
+
+    //
+    // Filling of histos for MHMcTriggerLvl2
+    //
+    MFillH hfill1("MHMcTriggerLvl2","MMcTriggerLvl2");
+    tasklist.AddToList(&hfill1);
+    //hfill1.SetFilter(&flist);
+    //MFillH hfill2("MHMcTriggerLvl2", &mevt, &cell);
+    //tasklist.AddToList(&hfill2);
+    //hfill2.SetFilter(&flist);
+
+    
+    
+    //
+    // set up the loop for the processing
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    
+    //
+    // Start to loop over all events
+    //
+    MProgressBar bar;
+    magic.SetProgressBar(&bar);
+
+
+    if (!magic.Eventloop())
+      return;
+    /*
+    if (!magic.PreProcess())
+    return;
+    
+    while (tasklist.Process())
+      {
+	cout<< mevt.GetEnergy()<<endl;
+	
+	cell.Print();
+      }
+    */
+    //fMcEvt = (MMcEvt*)parlist->FindObject("MMcEvt");
+    //if (!fMcEvt)
+    //{
+    //cout << "MMcEvt not found... exit." << endl;
+    //*fLog << err << dbginf << "MMcEvt not found... exit." << endl;
+    //  return kFALSE;
+    //}
+    //   cout << "fMcEvt = " << fMcEvt << endl;
+
+    //parlist.FindObject("MHMcTriggerLvl2")->Fill((Double_t) fMcEvt->GetEnergy(), cell);
+
+
+    tasklist.PrintStatistics();
+ 
+    //
+    // Now the histogram we wanted to get out of the data is
+    // filled and can be displayd
+    //
+    
+
+    //parlist.FindObject("MHMcTriggerLvl2")->DrawClone("sbc");
+    //parlist.FindObject("MHMcTriggerLvl2")->DrawClone("lps");
+    //parlist.FindObject("MHMcTriggerLvl2")->DrawClone();
+    //parlist.FindObject("MHMcTriggerLvl2")->DrawClone("energy");
+    //parlist.FindObject("MHMcTriggerLvl2")->DrawClone("lut-energy");
+    //parlist.FindObject("MHMcCollectionArea")->DrawClone();
+    // Returns histogram of the class MHMcTriggerLvl2  
+    
+    MHMcTriggerLvl2 *htrig = (MHMcTriggerLvl2 *)parlist.FindObject("MHMcTriggerLvl2");
+    MHMcCollectionArea *collarea = (MHMcCollectionArea *)parlist.FindObject("MHMcCollectionArea");
+    TH1F *hps = (TH1F *)htrig->GetHistByName("fHistPseudoSize");
+    TH1F *hlps = (TH1F *)htrig->GetHistByName("fHistLutPseudoSize");
+    TH1F *hsbc = (TH1F *)htrig->GetHistSizeBiggerCell();
+    TH1F *hpsn = (TH1F *)htrig->GetHistByName("fHistPseudoSizeNorm");
+    TH1F *hlpsn = (TH1F *)htrig->GetHistByName("fHistLutPseudoSizeNorm");
+    TH1F *hsbcn = (TH1F *)htrig->GetHistSizeBiggerCellNorm();
+    TH2D *hlpse = (TH2D *)htrig->GetHistByName("fHistLutPseudoSizeEnergy");
+    TH2D *hpse = (TH2D *)htrig->GetHistByName("fHistPseudoSizeEnergy");
+    TH2D *hsbce = (TH2D *)htrig->GetHistSizeBiggerCellEnergy();
+    TH1D *hcollarea = collarea->GetHist();
+
+    // Please set rootfile as the directory where you want to store
+    // your file.root containing histograms
+    rootfile = new TString(filename);
+    if (rootfile->Index("/*.root",1)>=0){
+      rootfile->Resize(rootfile->Index("/*.root",1));
+      rootfile[0]+="_sbcmag18_CNN3.root";
+    }
+      
+    hfile = new TFile((char *)rootfile[0], "RECREATE");
+    hlps->Write();
+    hps->Write();
+    hsbc->Write();
+    hlpsn->Write();
+    hpsn->Write();
+    hsbcn->Write();
+    hlpse->Write();
+    hpse->Write();
+    hsbce->Write();
+    hcollarea->Write();
+    hfile->Close();
+    cout << "Histograms stored into " << rootfile[0] << endl;
+    
+
+}
+
+
+
Index: /tags/Mars-V0.9/macros/trigrate.C
===================================================================
--- /tags/Mars-V0.9/macros/trigrate.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/trigrate.C	(revision 9772)
@@ -0,0 +1,209 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+\* ======================================================================== */
+
+/*
+ !   Modified 4/7/2002, Abelardo Moralejo:
+ !   Added one optional input parameter: a camera .root file containing
+ !   pure NSB events. One such file is generated running the camera over an
+ !   "empty" reflector file, with the NSB option on, and asking the camera
+ !   program (see camera program manual) to do the simulation even if no
+ !   photoelectron from the shower arrives at the camera. One also needs to
+ !   write to the output file all the events, both triggered and untriggered
+ !   (see again camera manual). These nsb camera files must contain the same
+ !   trigger conditions as the proton file.
+ !
+ !   If no nsb file is supplied, the macro will assume no triggers from
+ !   pure NSB fluctuations.
+ */
+
+Float_t GetNSBEvents(TString name, Float_t *BgR, int dim)
+{
+    Int_t numnsbevents;
+
+    TFile bgfile(name);
+    TTree *events = (TTree*) bgfile.Get("Events");
+
+    TH1F h("h","",5,.5,5.5);
+
+    UInt_t from = dim>0 ?   1 : -dim;
+    UInt_t to   = dim>0 ? dim : -dim;
+
+    cout << endl << "Calculating NSB triggers from file " << name << "..." << endl << endl;
+
+    for (UInt_t i = from; i <= to; i++)
+    {
+      TString cond("MMcTrig;");
+      cond += i;
+      cond += ".";
+      TBranch *b = events->GetBranch(cond);
+      MMcTrig *mctrig;
+      b->SetAddress(&mctrig);
+
+      Int_t tottrig = 0.;
+      
+      UInt_t imax = b->GetEntries();
+
+      for (UInt_t iev = 0; iev < imax; iev++)
+	{	
+	  b->GetEvent(iev);
+	  tottrig += mctrig->GetFirstLevel();
+	}
+      // Set total number of L1 triggers:
+      BgR[dim>0? i-1: 0] = (Float_t) tottrig;
+
+      numnsbevents = (Float_t) imax;
+    }
+
+    return numnsbevents;
+}
+
+
+void trigrate(int dim=0, char *filename = "data/camera.root", 
+	      char *nsbfile = NULL)
+{
+    // The dim parameter has three possible values:
+    // dim : = 0 -> root file with 1 trigger condition.
+    //       > 0 -> number of trigger condition to be analised 
+    //              in multi conditon file.
+    //       < 0 -> selects the -dim trigger condition.
+    //
+    // first we have to create our empty lists
+    //
+    MParList  parlist;
+    MTaskList tasklist;
+
+    //
+    // Setup the parameter list.
+    //  - we do not need to create any other container. All of them
+    //    are created automatically without loss - we don't have to
+    //    access them-
+    //
+    //  - we need to create MHMcRate only. The other containers
+    //    are created automatically without loss - we don't have to
+    //    access them-
+    //  - MHMcRate must be created by us because we need the pointer
+    //    to it and if it would get created automatically it would also be
+    //    deleted automatically
+    //  - Actually, depending on using a single trigger option MonteCarlo
+    //    file or a multyple trigger option, a MHMcRate or an array of 
+    //    MHMcRate are needed.
+    //
+    parlist.AddToList(&tasklist);
+
+    //
+    // You don't have to add the MHMcRate container here by hand.
+    // But if you want to print or display these containers later on
+    // it is necessary (Rem: No printing or displaying is done in this
+    // macro yet)
+    //
+    UInt_t from = dim>0 ?   1 : -dim;
+    UInt_t to   = dim>0 ? dim : -dim;
+
+    Int_t num = to-from+1;
+
+    TObjArray hists(MParList::CreateObjList("MHMcRate", from, to));
+    hists.SetOwner();
+
+    //
+    // Check if the list really contains the right number of histograms
+    //
+    if (hists.GetEntriesFast() != num)
+        return;
+
+    // Set for each MHMcRate object the trigger condition number in the 
+    // camera file (for the case of camera files with several conditions,
+    // produced with the trigger_loop option.
+    //
+
+    if (dim < 0)
+      ((MHMcRate*)(hists[0]))->SetTriggerCondNum((Short_t)(-dim));
+    if (dim > 0)
+      for (Short_t i = from ; i <= to; i++)
+	((MHMcRate*)(hists[i-1]))->SetTriggerCondNum(i);
+
+    //
+    // Add the histograms to the paramater list.
+    //
+    parlist.AddToList(&hists);
+
+    //
+    // Setup out tasks:
+    //  - First we have to read the events
+    //  - Then we can calculate rates, for what the number of
+    //    triggered showers from a empty reflector file for the
+    //    analised trigger conditions should be set (BgR[])
+    //
+
+    MReadMarsFile reader("Events", filename);
+    tasklist.AddToList(&reader);
+
+    // Now we have to build the BgR array, containing the number 
+    // of triggers (may be more than 1 trigger/event!) from the
+    // numnsbevents simulated in the nsbfile (3rd input parameter).
+    // If no nsbfile is supplied, we assume no triggers from NSB
+
+    Float_t* BgR = new Float_t[num];
+    memset(BgR, 0, num*sizeof(Float_t));
+
+    Float_t numnsbevents = 5.e4; // some default value.
+    if (nsbfile)
+      numnsbevents = GetNSBEvents(nsbfile, BgR, dim);
+
+    cout << "Number of Trigger conditions: " << num << endl;
+
+    MMcTriggerRateCalc rate(dim, BgR, numnsbevents);
+
+    tasklist.AddToList(&rate);
+
+    //
+    // set up the loop for the processing
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    //
+    // Start to loop over all events
+    //
+    MProgressBar bar;
+    magic.SetProgressBar(&bar);
+    if (!magic.Eventloop())
+        return;
+
+    delete BgR;
+
+    hists.Print();
+
+    if (num > 1)
+      {
+	gStyle->SetOptStat(0);
+	rate->Draw();
+
+	TFile f("ratehists.root", "recreate");
+	
+	rate->GetHist(2)->Write();
+	rate->GetHist(3)->Write();
+	rate->GetHist(4)->Write();
+      }
+
+
+}
Index: /tags/Mars-V0.9/macros/unfold.C
===================================================================
--- /tags/Mars-V0.9/macros/unfold.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/unfold.C	(revision 9772)
@@ -0,0 +1,3505 @@
+   
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// This program should be run under root :                                //
+//      root unfold.C++                                                   //
+//                                                                        //
+// Author(s) : T. Bretz  02/2002 <mailto:tbretz@astro.uni-wuerzburg.de>   //
+// Author(s) : W. Wittek 09/2002 <mailto:wittek@mppmu.mpg.de>             //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+
+#include <TMath.h>
+#include <TRandom3.h>
+#include <TVector.h>
+#include <TMatrixD.h>
+#include <TMatrix.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TProfile.h>
+#include <TF1.h>
+#include <iostream.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include <fstream.h>
+#include <iomanip.h>
+
+TH1 *DrawMatrixClone(const TMatrixD &m, Option_t *opt="")
+{
+    const Int_t nrows = m.GetNrows();
+    const Int_t ncols = m.GetNcols();
+
+    TMatrix m2(nrows, ncols);
+    for (int i=0; i<nrows; i++)
+        for (int j=0; j<ncols; j++)
+            m2(i, j) = m(i, j);
+
+    TH2F *hist = new TH2F(m2);
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+
+}
+
+TH1 *DrawMatrixColClone(const TMatrixD &m, Option_t *opt="", Int_t col=0)
+{
+    const Int_t nrows = m.GetNrows();
+
+    TVector vec(nrows);
+    for (int i=0; i<nrows; i++)
+        vec(i) = m(i, col);
+
+    TH1F *hist = new TH1F("TVector","",nrows,0,nrows);
+    for (int i=0; i<nrows; i++)
+    {
+      hist->SetBinContent(i+1, vec(i));
+    }
+
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+}
+
+
+void PrintTH2Content(const TH2 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            cout << hist.GetBinContent(i,j) << " \t";
+        cout << endl << endl;
+}
+
+void PrintTH2Error(const TH2 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            cout << hist.GetBinError(i, j) << " \t";
+        cout << endl << endl;
+    }
+}
+
+void PrintTH1Content(const TH1 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        cout << hist.GetBinContent(i) << " \t";
+    cout << endl << endl;
+}
+
+void PrintTH1Error(const TH1 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        cout << hist.GetBinError(i) << " \t";
+    cout << endl << endl;
+}
+
+void CopyCol(TMatrixD &m, const TH1 &h, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        m(i, col) = h.GetBinContent(i+1);
+}
+
+void CopyCol(TH1 &h, const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        h.SetBinContent(i+1, m(i, col));
+}
+
+void CopyH2M(TMatrixD &m, const TH2 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+            m(i, j) = h.GetBinContent(i+1, j+1);
+}
+
+void CopySqr(TMatrixD &m, const TH1 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+        {
+            const Double_t bin =  h.GetBinContent(i+1, j+1);
+            m(i, j) = bin*bin;
+        }
+}
+
+Double_t GetMatrixSumRow(const TMatrixD &m, Int_t row)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(row, i);
+
+    return sum;
+}
+
+Double_t GetMatrixSumDiag(const TMatrixD &m)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, i);
+
+    return sum;
+}
+
+Double_t GetMatrixSumCol(const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, col);
+
+    return sum;
+}
+Double_t GetMatrixSum(const TMatrixD &m)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += GetMatrixSumRow(m, i);
+
+    return sum;
+}
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// fcnSmooth   (used by SmoothMigrationMatrix)                                 //
+//                                                                        //
+// is called by MINUIT                                                    //
+// for given values of the parameters it calculates                       //
+//                     the function to be minimized                       //  
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+void fcnSmooth(Int_t &npar, Double_t *gin, Double_t &f, 
+               Double_t *par, Int_t iflag);
+
+
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// fcnTikhonov2   (used by Tikhonov2)                                     //
+//                                                                        //
+// is called by MINUIT                                                    //
+// for given values of the parameters it calculates                       //
+//                     the function to be minimized                       //  
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+void fcnTikhonov2(Int_t &npar, Double_t *gin, Double_t &f, 
+                              Double_t *par, Int_t iflag);
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// MUnfold                                                                //
+//                                                                        //
+// class for unfolding a 1-dimensional distribution                       //
+//                                                                        //
+// the methods used are described in :                                    //
+//                                                                        //
+//     V.B.Anykeyev et al., NIM A303 (1991) 350                           //
+//     M. Schmelling, Nucl. Instr. and Meth. A 340 (1994) 400             //
+//     M. Schmelling : "Numerische Methoden der Datenanalyse"             //
+//                    Heidelberg, Maerz 1998                              //
+//     M.Bertero, INFN/TC-88/2 (1988)                                     //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+class MUnfold : public TObject
+{
+public:
+
+    UInt_t    fNa;        // Number of bins in the distribution to be unfolded
+    UInt_t    fNb;        // Number of bins in the unfolded distribution
+
+    TMatrixD  fMigrat;    // migration matrix                  (fNa, fNb)
+    TMatrixD  fMigraterr2;// error**2 of migration matrix      (fNa, fNb)
+
+    TMatrixD  fMigOrig;    // original migration matrix         (fNa, fNb)
+    TMatrixD  fMigOrigerr2;// error**2 oforiginal migr. matrix  (fNa, fNb)
+
+    TMatrixD  fMigSmoo;    // smoothed migration matrix M       (fNa, fNb)
+    TMatrixD  fMigSmooerr2;// error**2 of smoothed migr. matrix (fNa, fNb)
+    TMatrixD  fMigChi2;    // chi2 contributions for smoothing  (fNa, fNb)
+
+    TMatrixD  fVa;        // distribution to be unfolded       (fNa)
+    TMatrixD  fVacov;     // error matrix of fVa               (fNa, fNa)
+    TMatrixD  fVacovInv; // inverse of fVacov                 (fNa, fNa)
+    Double_t  fSpurVacov; // Spur of fVacov
+
+    //    UInt_t    fVaevents;  // total number of events
+    UInt_t    fVapoints;  // number of significant measurements
+
+    TMatrixD  fVb;        // unfolded distribution             (fNb)
+    TMatrixD  fVbcov;     // error matrix of fVb               (fNb, fNb)
+
+    TMatrixD  fVEps;      // prior distribution                (fNb)
+    TMatrixDColumn fVEps0;
+
+    Double_t  fW;         // weight
+    Double_t  fWbest;     // best weight
+    Int_t     ixbest;
+
+    TMatrixD  fResult;    // unfolded distribution and errors  (fNb, 5)
+    TMatrixD  fChi2;      // chisquared contribution           (fNa, 1)
+
+    Double_t  fChisq;     // total chisquared
+    Double_t  fNdf;       // number of degrees of freedom
+    Double_t  fProb;      // chisquared probability
+
+    TMatrixD  G;          // G = M * M(transposed)             (fNa, fNa)
+    TVectorD  EigenValue; // vector of eigenvalues lambda of G (fNa)
+    TMatrixD  Eigen;      // matrix of eigen vectors of G      (fNa, fNa)
+    Double_t  RankG;      // rank of G
+    Double_t  tau;        // 1 / lambda_max
+    Double_t  EpsLambda;
+
+    // quantities stored for each weight :
+    TVectorD SpSig;       // Spur of covariance matrix of fVbcov
+    TVectorD SpAR;        // effective rank of G^tilde
+    TVectorD chisq;       // chi squared (measures agreement between
+    // fVa and the folded fVb)
+    TVectorD SecDer;      // regularization term = sum of (2nd der.)**2
+    TVectorD ZerDer;      // regularization term = sum of (fVb)**2
+    TVectorD Entrop;      // regularization term = reduced cross-entropy
+    TVectorD DAR2;        //
+    TVectorD Dsqbar;      //
+
+    Double_t SpurAR;
+    Double_t SpurSigma;
+    Double_t SecDeriv;
+    Double_t ZerDeriv;
+    Double_t Entropy;
+    Double_t DiffAR2;
+    Double_t Chisq;
+    Double_t D2bar;
+
+    TMatrixD Chi2;
+
+    //
+
+    // plots versus weight
+    Int_t    Nix;
+    Double_t xmin;
+    Double_t xmax;
+    Double_t dlogx;
+
+    TH1D *hBchisq;
+    TH1D *hBSpAR;
+    TH1D *hBDSpAR;
+    TH1D *hBSpSig;
+    TH1D *hBDSpSig;
+    TH1D *hBSecDeriv;
+    TH1D *hBDSecDeriv;
+    TH1D *hBZerDeriv;
+    TH1D *hBDZerDeriv;
+    TH1D *hBEntropy;
+    TH1D *hBDEntropy;
+    TH1D *hBDAR2;
+    TH1D *hBD2bar;
+
+    //
+    TH1D *hEigen;
+
+    // plots for the best solution
+    TH2D *fhmig;
+    TH2D *shmig;
+    TH2D *shmigChi2;
+
+    TH1D *fhb0;
+
+    TH1D *fha;
+
+    TH1D *hprior;
+
+    TH1D *hb;
+
+    Double_t CalcSpurSigma(TMatrixD &T, Double_t norm=1)
+    {
+        Double_t spursigma = 0;
+
+        for (UInt_t a=0; a<fNb; a++)
+        {
+            for (UInt_t b=0; b<fNb; b++)
+            {
+                fVbcov(a,b) = 0;
+
+                for (UInt_t c=0; c<fNa; c++)
+                    for (UInt_t d=0; d<fNa; d++)
+                        fVbcov(a,b) += T(a,d)*fVacov(d,c)*T(b,c);
+
+                fVbcov(a,b) *= norm*norm;
+            }
+            spursigma += fVbcov(a,a);
+        }
+
+        return spursigma;
+    }
+
+public:
+    // -----------------------------------------------------------------------
+    //
+    // Constructor
+    //              copy histograms into matrices
+    //
+    MUnfold(TH1D &ha, TH2D &hacov, TH2D &hmig)
+        : fVEps(hmig.GetYaxis()->GetNbins(),1), fVEps0(fVEps, 0)
+    {
+        // ha      is the distribution to be unfolded
+        // hacov   is the covariance matrix of ha
+        // hmig    is the migration matrix;
+        //         this matrix will be used in the unfolding
+        //         unless SmoothMigrationMatrix(*hmigrat) is called;
+        //         in the latter case hmigrat is smoothed
+        //         and the smoothed matrix is used in the unfolding
+
+        // Eigen values of the matrix G, which are smaller than EpsLambda
+        // will be considered as being zero
+        EpsLambda = 1.e-10;
+        fW = 0.0;
+
+        fNa  = hmig.GetXaxis()->GetNbins();
+        const Double_t alow = hmig.GetXaxis()->GetXmin();
+        const Double_t aup  = hmig.GetXaxis()->GetXmax();
+
+        fNb  = hmig.GetYaxis()->GetNbins();
+        const Double_t blow = hmig.GetYaxis()->GetXmin();
+        const Double_t bup  = hmig.GetYaxis()->GetXmax();
+
+
+        UInt_t Na = ha.GetNbinsX();
+        if (fNa != Na)
+        {
+            cout << "MUnfold::MUnfold : dimensions do not match,  fNa = ";
+            cout << fNa << ",   Na = " << Na << endl;
+        }
+
+        cout << "MUnfold::MUnfold :" << endl;
+        cout << "==================" << endl;
+        cout << "   fNa = " << fNa << ",   fNb = " << fNb << endl;
+
+        // ------------------------
+
+        fVa.ResizeTo(fNa, 1);
+        CopyCol(fVa, ha, 0);
+
+        cout << "   fVa = ";
+
+        for (UInt_t i=0; i<fNa; i++)
+            cout << fVa(i,0) << " \t";
+        cout << endl;
+
+        Double_t vaevents = GetMatrixSumCol(fVa, 0);
+        cout << "   Total number of events in fVa = " << vaevents << endl;
+
+        // ------------------------
+
+        fChi2.ResizeTo(fNa,1);
+        Chi2.ResizeTo(fNa,1);
+
+        // ------------------------
+
+        fVacov.ResizeTo(fNa, fNa);
+        fSpurVacov = 0;
+
+        CopyH2M(fVacov, hacov);
+
+        fVapoints = 0;
+        for (UInt_t i=0; i<fNa; i++)
+            if (fVa(i,0)>0 && fVacov(i,i)<fVa(i,0)*fVa(i,0))
+                fVapoints++;
+
+        fSpurVacov = GetMatrixSumDiag(fVacov);
+
+        cout << "MUnfold::MUnfold :   fVacov = " << endl;
+        cout << "==============================" << endl;
+        fVacov.Print();
+
+        cout << "   Number of significant points in fVa = ";
+        cout << fVapoints << endl;
+
+        cout << "   Spur of fVacov = ";
+        cout << fSpurVacov << endl;
+
+        // ------------------------
+
+        fVacovInv.ResizeTo(fNa, fNa);
+        fVacovInv = fVacov;
+        fVacovInv.InvertPosDef();
+
+        cout << "MUnfold::MUnfold :   fVacovInv = " << endl;
+        cout << "==================================" << endl;
+        fVacovInv.Print();
+
+        // ------------------------
+        // fMigrat is the migration matrix to be used in the unfolding;
+        // fMigrat may be overwritten by SmoothMigrationMatrix
+
+        fMigrat.ResizeTo(fNa, fNb); // row, col
+
+        CopyH2M(fMigrat, hmig);
+
+
+        // ------------------------
+
+        fMigraterr2.ResizeTo(fNa, fNb); // row, col
+        CopySqr(fMigraterr2, hmig);
+
+        // normaxlize
+
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            const Double_t sum = GetMatrixSumCol(fMigrat, j);
+
+            if (sum==0)
+                continue;
+
+            TMatrixDColumn col1(fMigrat, j);
+            col1 *= 1./sum;
+
+            TMatrixDColumn col2(fMigraterr2, j);
+            col2 *= 1./(sum*sum);
+        }
+
+        cout << "MUnfold::MUnfold :   fMigrat = " << endl;
+        cout << "===============================" << endl;
+        fMigrat.Print();
+
+        cout << "MUnfold::MUnfold :   fMigraterr2 = " << endl;
+        cout << "===================================" << endl;
+        fMigraterr2.Print();
+
+        // ------------------------
+        G.ResizeTo(fNa, fNa);
+        EigenValue.ResizeTo(fNa);
+        Eigen.ResizeTo(fNa, fNa);
+
+        fMigOrig.ResizeTo(fNa, fNb); 
+        fMigOrigerr2.ResizeTo(fNa, fNb); 
+
+        fMigSmoo.ResizeTo    (fNa, fNb); 
+        fMigSmooerr2.ResizeTo(fNa, fNb); 
+        fMigChi2.ResizeTo    (fNa, fNb); 
+
+        // ------------------------
+
+        fVEps0 = 1./fNb;
+
+        cout << "MUnfold::MUnfold :   Default prior distribution fVEps = " << endl;
+        cout << "========================================================" << endl;
+        fVEps.Print();
+
+        // ------------------------
+
+        fVb.ResizeTo(fNb,1);
+        fVbcov.ResizeTo(fNb,fNb);
+
+        // ----------------------------------------------------
+        // number and range of weights to be scanned
+        Nix  = 30;
+        xmin = 1.e-5;
+        xmax = 1.e5;
+        dlogx = (log10(xmax)-log10(xmin)) / Nix;
+
+        SpSig.ResizeTo (Nix);
+        SpAR.ResizeTo  (Nix);
+        chisq.ResizeTo (Nix);
+        SecDer.ResizeTo(Nix);
+        ZerDer.ResizeTo(Nix);
+        Entrop.ResizeTo(Nix);
+        DAR2.ResizeTo  (Nix);
+        Dsqbar.ResizeTo(Nix);
+
+        //------------------------------------
+        // plots as a function of the iteration  number
+
+        hBchisq = new TH1D("Bchisq", "chisq",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSpAR  = new TH1D("BSpAR", "SpurAR",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSpAR  = new TH1D("BDSpAR", "Delta(SpurAR)",
+                            Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSpSig = new TH1D("BSpSig", "SpurSigma/SpurC",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSpSig = new TH1D("BDSpSig", "Delta(SpurSigma/SpurC)",
+                            Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSecDeriv = new TH1D("BSecDeriv", "Second Derivative squared",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSecDeriv = new TH1D("BDSecDeriv", "Delta(Second Derivative squared)",
+                               Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBZerDeriv = new TH1D("BZerDeriv", "Zero Derivative squared",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDZerDeriv = new TH1D("BDZerDeriv", "Delta(Zero Derivative squared)",
+                               Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBEntropy = new TH1D("BEntrop", "Entropy",
+                             Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDEntropy = new TH1D("BDEntrop", "Delta(Entropy)",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDAR2 = new TH1D("BDAR2", "norm(AR-AR+)",
+                          Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBD2bar = new TH1D("BD2bar", "(b_unfolded-b_ideal)**2",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        //-------------------------------------
+        // original migration matrix
+        fhmig = new TH2D("fMigrat", "Migration matrix",
+                         fNa, alow, aup, fNb, blow, bup);
+        fhmig->Sumw2();
+
+        //-------------------------------------
+        // smoothed migration matrix
+        shmig = new TH2D("sMigrat", "Smoothed migration matrix",
+                         fNa, alow, aup, fNb, blow, bup);
+        shmig->Sumw2();
+
+        //-------------------------------------
+        // chi2 contributions for smoothing of migration matrix
+        shmigChi2 = new TH2D("sMigratChi2", "Chi2 contr. for smoothing",
+                             fNa, alow, aup, fNb, blow, bup);
+
+        //-------------------------------------
+        // eigen values of matrix G = M * M(transposed)
+        hEigen = new TH1D("Eigen", "Eigen values of M*MT",
+                          fNa, 0.5, fNa+0.5);
+
+        //------------------------------------
+        // Ideal distribution
+        
+        fhb0 = new TH1D("fhb0", "Ideal distribution", fNb, blow, bup);
+        fhb0->Sumw2();
+        
+
+        //------------------------------------
+        // Distribution to be unfolded
+        fha = new TH1D("fha", "Distribution to be unfolded", fNa, alow, aup);
+        fha->Sumw2();
+
+        //------------------------------------
+        // Prior distribution
+        hprior = new TH1D("Prior", "Prior distribution", fNb, blow, bup);
+
+        //------------------------------------
+        // Unfolded distribution
+        hb = new TH1D("DataSp", "Unfolded distribution", fNb, blow, bup);
+        hb->Sumw2();
+
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Define prior distribution to be a constant
+    //
+    void SetPriorConstant()
+    {
+        fVEps0 = 1./fNb;
+
+        CopyCol(*hprior, fVEps);
+
+        cout << "SetPriorConstant : Prior distribution fVEps = " << endl;
+        cout << "==============================================" << endl;
+        fVEps.Print();
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Take prior distribution from the histogram 'ha'
+    // which may have a different binning than 'hprior'
+    //
+    Bool_t SetPriorRebin(TH1D &ha)
+    {
+        // ------------------------------------------------------------------
+        //
+        // fill the contents of histogram 'ha' into the histogram 'hrior';
+        // the histograms need not have the same binning;
+        // if the binnings are different, the bin contents of histogram 'ha'
+        //    are distributed properly (linearly) over the bins of 'hprior'
+        //
+
+        const Int_t    na   = ha.GetNbinsX();
+        const Double_t alow = ha.GetBinLowEdge(1);
+        const Double_t aup  = ha.GetBinLowEdge(na+1);
+
+        const Int_t    nb   = hprior->GetNbinsX();
+        const Double_t blow = hprior->GetBinLowEdge(1);
+        const Double_t bup  = hprior->GetBinLowEdge(nb+1);
+
+        // check whether there is an overlap
+        //       between the x ranges of the 2 histograms
+        if (alow>bup || aup<blow)
+        {
+            cout << "Rebinning not possible because there is no overlap of the x ranges of the two histograms" << endl;
+            return kFALSE;
+        }
+
+        // there is an overlap
+        //********************
+        Double_t sum = 0;
+        for (Int_t j=1; j<=nb; j++)
+        {
+            const Double_t yl = hprior->GetBinLowEdge(j);
+            const Double_t yh = hprior->GetBinLowEdge(j+1);
+
+            // search bins of histogram ha which contribute
+            // to bin j of histogram hb
+            //----------------
+            Int_t il=0;
+            Int_t ih=0;
+            for (Int_t i=2; i<=na+1; i++)
+            {
+                const Double_t xl = ha.GetBinLowEdge(i);
+                if (xl>yl)
+                {
+                    il = i-1;
+
+                    //.................................
+                    ih = 0;
+                    for (Int_t k=(il+1); k<=(na+1); k++)
+                    {
+                        const Double_t xh = ha.GetBinLowEdge(k);
+                        if (xh >= yh)
+                        {
+                            ih = k-1;
+                            break;
+                        }
+                    }
+                    //.................................
+                    if (ih == 0)
+                        ih = na;
+                    break;
+                }
+            }
+            //----------------
+            if (il == 0)
+            {
+                cout << "Something is wrong " << endl;
+                cout << "          na, alow, aup = " << na << ",  " << alow
+                    << ",  " << aup << endl;
+                cout << "          nb, blow, bup = " << nb << ",  " << blow
+                    << ",  " << bup << endl;
+                return kFALSE;
+            }
+
+            Double_t content=0;
+            // sum up the contribution to bin j
+            for (Int_t i=il; i<=ih; i++)
+            {
+                const Double_t xl = ha.GetBinLowEdge(i);
+                const Double_t xh = ha.GetBinLowEdge(i+1);
+                const Double_t bina = xh-xl;
+
+                if (xl<yl  &&  xh<yh)
+                    content += ha.GetBinContent(i) * (xh-yl) / bina;
+                else
+                    if (xl<yl  &&  xh>=yh)
+                        content += ha.GetBinContent(i) * (yh-yl) / bina;
+                    else
+                        if (xl>=yl  &&  xh<yh)
+                            content += ha.GetBinContent(i);
+                        else if (xl>=yl  &&  xh>=yh)
+                            content += ha.GetBinContent(i) * (yh-xl) / bina;
+            }
+            hprior->SetBinContent(j, content);
+            sum += content;
+        }
+
+        // normalize histogram hb
+        if (sum==0)
+        {
+            cout << "histogram hb is empty; sum of weights in ha = ";
+            cout << ha.GetSumOfWeights() << endl;
+            return kFALSE;
+        }
+
+        for (Int_t j=1; j<=nb; j++)
+        {
+            const Double_t content = hprior->GetBinContent(j)/sum;
+            hprior->SetBinContent(j, content);
+            fVEps0(j-1) = content;
+        }
+
+        cout << "SetPriorRebin : Prior distribution fVEps = " << endl;
+        cout << "===========================================" << endl;
+        fVEps.Print();
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Set prior distribution to a given distribution 'hpr'
+    //
+    Bool_t SetPriorInput(TH1D &hpr)
+    {
+        CopyCol(fVEps, hpr);
+
+        const Double_t sum = GetMatrixSumCol(fVEps, 0);
+
+        if (sum<=0)
+        {
+            cout << "MUnfold::SetPriorInput: invalid prior distribution" << endl;
+            return kFALSE;
+        }
+
+        // normalize prior distribution
+        fVEps0 *= 1./sum;
+
+        CopyCol(*hprior, fVEps);
+
+        cout << "SetPriorInput : Prior distribution fVEps = " << endl;
+        cout << "===========================================" << endl;
+        fVEps.Print();
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Define prior distribution to be a power law
+    // use input distribution 'hprior' only
+    //           for defining the histogram parameters
+    //
+    Bool_t SetPriorPower(Double_t gamma)
+    {
+        // generate distribution according to a power law
+        //                        dN/dE = E^{-gamma}
+        //  or with y = lo10(E),  E = 10^y :
+        //                        dN/dy = ln10 * 10^{y*(1-gamma)}
+        TH1D hpower(*hprior);
+
+        const UInt_t   nbin = hprior->GetNbinsX();
+        const Double_t xmin = hprior->GetBinLowEdge(1);
+        const Double_t xmax = hprior->GetBinLowEdge(nbin+1);
+
+        cout << "nbin, xmin, xmax = " << nbin << ",  ";
+        cout << xmin << ",  " << xmax << endl;
+
+        TF1* fpow = new TF1("fpow", "pow(10.0, x*(1.0-[0]))", xmin,xmax);
+        fpow->SetParName  (0,"gamma");
+        fpow->SetParameter(0, gamma );
+
+        hpower.FillRandom("fpow", 100000);
+
+        // fill prior distribution
+        CopyCol(fVEps, hpower);
+
+        const Double_t sum = GetMatrixSumCol(fVEps, 0);
+        if (sum <= 0)
+        {
+            cout << "MUnfold::SetPriorPower : invalid prior distribution"  << endl;
+            return kFALSE;
+        }
+
+        // normalize prior distribution
+        fVEps0 *= 1./sum;
+        CopyCol(*hprior, fVEps);
+
+        cout << "SetPriorPower : Prior distribution fVEps = " << endl;
+        cout << "===========================================" << endl;
+        fVEps.Print();
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Set the initial weight
+    //
+    Bool_t SetInitialWeight(Double_t &weight)
+    {
+        if (weight == 0.0)
+        {
+            TMatrixD v1(fVa, TMatrixD::kTransposeMult, fVacovInv);
+            TMatrixD v2(v1, TMatrixD::kMult, fVa);
+            weight = 1./sqrt(v2(0,0));
+        }
+
+        cout << "MUnfold::SetInitialWeight : Initial Weight = "
+            << weight << endl;
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Print the unfolded distribution
+    //
+    void PrintResults()
+    {
+        cout << "PrintResults : Unfolded distribution fResult " << endl;
+        cout << "=============================================" << endl;
+        cout << "val, eparab, eplus, eminus, gcc = "  << endl;
+
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            cout << fResult(i, 0) << " \t";
+            cout << fResult(i, 1) << " \t";
+            cout << fResult(i, 2) << " \t";
+            cout << fResult(i, 3) << " \t";
+            cout << fResult(i, 4) <<  endl;
+        }
+        cout << "Chisquared, NDF, chi2 probability, ixbest = "
+            << fChisq << ",  "
+            << fNdf << ",  " << fProb << ",  " << ixbest << endl;
+
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Schmelling  : unfolding by minimizing the function Z
+    //               by Gauss-Newton iteration
+    //
+    //               the weights are scanned between
+    //               1.e-5*fWinitial and 1.e5*fWinitial
+    //
+    Bool_t Schmelling(TH1D &hb0)
+    {
+    
+        //======================================================================
+        // copy ideal distribution
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+    
+        //-----------------------------------------------------------------------
+        // Initialization
+        // ==============
+
+        Int_t numGiteration;
+        Int_t MaxGiteration = 1000;
+
+        TMatrixD alpha;
+        alpha.ResizeTo(fNa, 1);
+
+
+        //-----------------------------------------------------------------------
+        // Newton iteration
+        // ================
+
+        Double_t dga2;
+        Double_t dga2old;
+        Double_t EpsG = 1.e-12;
+
+        TMatrixD wZdp_inv(fNa, fNa);
+        TMatrixD d(fNb, 1);
+        TMatrixD p(fNb, 1);
+
+        TMatrixD gamma (fNa, 1);
+        TMatrixD dgamma(fNa, 1);
+
+        Double_t fWinitial;
+        fWinitial = 0.0;
+        SetInitialWeight(fWinitial);
+        // for my example this fWinitial was not good; therefore :
+        fWinitial = 1.0;
+
+        Int_t ix;
+        Double_t xiter;
+
+        //--------   start  scanning weights   --------------------------
+        // if full == kFALSE   only quantities necessary for the Gauss-Newton
+        //                     iteration are calculated in SchmellCore
+        // if full == kTRUE    in addition the unfolded distribution,
+        //                     its covariance matrix and quantities like
+        //                     Chisq, SpurAR, etc. are computed in SchmellCore
+        //Bool_t full;
+        //full = kFALSE;
+        Int_t full;
+
+        dga2 = 1.e20;
+        for (ix=0; ix<Nix; ix++)
+        {
+            xiter = pow(10.0,log10(xmin)+ix*dlogx) * fWinitial;
+
+            //----------   start Gauss-Newton iteration   ----------------------
+            numGiteration = 0;
+
+            // if there was no convergence and the starting gamma was != 0
+            // redo unfolding for the same weight starting with gamma = 0
+            //
+            Int_t gamma0 = 0;
+            while (1)
+	    {
+              if (dga2 > EpsG)
+	      {
+                gamma0 = 1;
+                gamma.Zero();
+	      }
+
+              dga2 = 1.e20;
+
+              while (1)
+              {
+                dga2old = dga2;
+
+                full = 0;
+                SchmellCore(full, xiter, gamma, dgamma, dga2);
+
+                gamma += dgamma;
+
+                //cout << "Schmelling : ix, numGiteration, dga2, dga2old = "
+                //     << ix << ",  " << numGiteration << ",  "
+                //     << dga2 << ",  " << dga2old << endl;
+
+                numGiteration += 1;
+
+                // convergence
+                if (dga2 < EpsG)
+                    break;
+
+                // no convergence
+                if (numGiteration > MaxGiteration)
+                    break;
+
+                // gamma doesn't seem to change any more
+                if (fabs(dga2-dga2old) < EpsG/100.)
+                    break;
+              }
+              //----------   end Gauss-Newton iteration   ------------------------
+              if (dga2<EpsG || gamma0 != 0) break;
+	    }
+
+            // if Gauss-Newton iteration has not converged
+            // go to next weight
+            if (dga2 > EpsG)
+            {
+                cout << "Schmelling : Gauss-Newton iteration has not converged;"
+                    << "   numGiteration = " << numGiteration << endl;
+                cout << "             ix, dga2, dga2old = " << ix << ",  "
+                    << dga2 << ",  " << dga2old << endl;
+                continue;
+            }
+
+            //cout << "Schmelling : Gauss-Newton iteration has converged;" << endl;
+            //cout << "==================================================" << endl;
+            //cout << "             numGiteration = " << numGiteration << endl;
+            //cout << "             ix, dga2 = " << ix << ",  " << dga2 << endl;
+
+            // calculated quantities which will be useful for determining
+            // the best weight (Chisq, SpurAR, ...)
+            //full = kTRUE;
+            full = 1;
+            SchmellCore(full, xiter, gamma, dgamma, dga2);
+
+            // calculate difference between ideal and unfolded distribution
+            Double_t D2bar = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                D2bar += temp*temp;
+            }
+
+            SpAR(ix)  = SpurAR;
+            SpSig(ix) = SpurSigma;
+            chisq(ix) = Chisq;
+            SecDer(ix) = SecDeriv;
+            ZerDer(ix) = ZerDeriv;
+            Entrop(ix) = Entropy;
+            DAR2(ix)   = DiffAR2;
+            Dsqbar(ix) = D2bar;
+
+        }
+        //----------   end of scanning weights   -------------------------------
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xbin = log10(xmin)+ix*dlogx;
+            xiter = pow(10.0,xbin) * fWinitial;
+
+            Int_t bin;
+            bin = hBchisq->FindBin( xbin );
+            hBchisq->SetBinContent(bin,chisq(ix));
+            hBSpAR->SetBinContent(bin,SpAR(ix));
+            hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+            hBSecDeriv->SetBinContent(bin,SecDer(ix));
+            hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+            hBEntropy->SetBinContent(bin,Entrop(ix));
+            hBDAR2->SetBinContent(bin,DAR2(ix));
+            hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+            if (ix > 0)
+            {
+                Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                hBDSpAR->SetBinContent(bin,DSpAR);
+
+                Double_t diff = SpSig(ix) - SpSig(ix-1);
+                Double_t DSpSig = diff;
+                hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                hBDEntropy->SetBinContent(bin,DEntrop);
+
+                Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                hBDZerDeriv->SetBinContent(bin,DZerDer);
+            }
+        }
+
+        // Select best weight
+        SelectBestWeight();
+
+        if (ixbest < 0.0)
+        {
+            cout << "Schmelling : no solution found; " << endl;
+            return kFALSE;
+        }
+
+        // do the unfolding using the best weight
+        //full = kTRUE;
+
+
+        xiter = pow(10.0,log10(xmin)+ixbest*dlogx) * fWinitial;
+
+        //----------   start Gauss-Newton iteration   ----------------------
+        numGiteration = 0;
+        gamma.Zero();
+        dga2 = 1.e20;
+
+        while (1)
+        {
+            full = 1;
+            SchmellCore(full, xiter, gamma, dgamma, dga2);
+            gamma += dgamma;
+
+            //cout << "Schmelling : sum(dgamma^2) = " << dga2 << endl;
+
+            numGiteration += 1;
+
+            if (numGiteration > MaxGiteration)
+                break;
+
+            if (dga2 < EpsG)
+                break;
+        }
+        //----------   end Gauss-Newton iteration   ------------------------
+
+
+        //-----------------------------------------------------------------------
+        // termination stage
+        // =================
+
+        cout << "Schmelling : best solution found; " << endl;
+        cout << "==================================" << endl;
+        cout << "             xiter, ixbest, numGiteration, Chisq = "
+            << xiter << ",  " << ixbest << ",  "
+            << numGiteration << ",  " << Chisq << endl;
+
+        //------------------------------------
+        //..............................................
+        // put unfolded distribution into fResult
+        //     fResult(i,0)   value in bin i
+        //     fResult(i,1)   error of value in bin i
+
+        fNdf = SpurAR;
+        fChisq = Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          fChi2(i,0) = Chi2(i,0);
+	}
+
+        UInt_t iNdf   = (UInt_t) (fNdf+0.5);
+        fProb = iNdf>0 ? TMath::Prob(fChisq, iNdf) : 0;
+
+        fResult.ResizeTo(fNb, 5);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            fResult(i, 0) = fVb(i,0);
+            fResult(i, 1) = sqrt(fVbcov(i,i));
+            fResult(i, 2) = 0.0;
+            fResult(i, 3) = 0.0;
+            fResult(i, 4) = 1.0; 
+	}
+
+        //--------------------------------------------------------
+
+        cout << "Schmelling : gamma = " << endl;
+        for (UInt_t i=0; i<fNa; i++)
+            cout << gamma(i,0) << " \t";
+        cout << endl;
+
+        return kTRUE;
+    }
+
+
+
+
+    // -----------------------------------------------------------------------
+    //
+    // SchmellCore     main part of Schmellings calculations
+    //
+    void SchmellCore(Int_t full, Double_t &xiter, TMatrixD &gamma,
+                     TMatrixD &dgamma, Double_t &dga2)
+    {
+        Double_t norm;
+        TMatrixD wZdp_inv(fNa, fNa);
+        TMatrixD d(fNb, 1);
+        TMatrixD p(fNb, 1);
+
+        //--------------------------------------------------------
+        //--      determine the probability vector p
+
+
+        TMatrixD v3(gamma, TMatrixD::kTransposeMult, fMigrat);
+        TMatrixD v4(TMatrixD::kTransposed, v3);
+        d = v4;
+        Double_t dmax  = -1.e10;
+        for (UInt_t j=0; j<fNb; j++)
+            if (d(j,0)>dmax)
+                dmax = d(j,0);
+
+        Double_t psum = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            d(j,0) -= dmax;
+            p(j,0)  = fVEps0(j)*exp(xiter*d(j,0));
+            psum += p(j,0);
+        }
+
+        p *= 1.0/psum;
+
+        //--      get the vector alpha
+
+        TMatrixD alpha(fMigrat, TMatrixD::kMult, p);
+
+        //--      determine the current normalization
+
+        TMatrixD v2   (alpha, TMatrixD::kTransposeMult, fVacovInv);
+        TMatrixD normb(v2,    TMatrixD::kMult, alpha);
+
+        TMatrixD normc(v2,    TMatrixD::kMult, fVa);
+
+        norm  = normc(0,0)/normb(0,0);
+
+        //--------------------------------------------------------
+        //--      determine the scaled slope vector s and Hessian H
+
+        TMatrixD Zp(fNa,1);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            Zp(i,0) = norm*alpha(i,0) - fVa(i,0);
+            for (UInt_t k=0; k<fNa; k++)
+                Zp(i,0) += gamma(k,0)*fVacov(k,i);
+        }
+
+
+        TMatrixD Q  (fNa, fNa);
+        TMatrixD wZdp(fNa, fNa);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                Q(i,j) = - alpha(i,0)*alpha(j,0);
+                for (UInt_t k=0; k<fNb; k++)
+                    Q(i,j) += fMigrat(i,k)*fMigrat(j,k)*p(k,0);
+                wZdp(i,j) = xiter*norm*Q(i,j) + fVacov(i,j);
+            }
+        }
+
+        //--      invert H and calculate the next Newton step
+
+        Double_t determ = 1.0;
+        wZdp_inv = wZdp;
+        wZdp_inv.Invert(&determ);
+
+        if(determ == 0.0)
+        {
+            cout << "SchmellCore: matrix inversion for H failed" << endl;
+            return;
+        }
+
+
+        dga2 = 0.0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            dgamma(i,0) = 0.0;
+            for (UInt_t j=0; j<fNa; j++)
+                dgamma(i,0) -= wZdp_inv(i,j)*Zp(j,0);
+            dga2 += dgamma(i,0)*dgamma(i,0);
+        }
+
+        if (full == 0)
+            return;
+
+        //--------------------------------------------------------
+        //--      determine chi2 and dNdf (#measurements ignored)
+        Double_t dNdf = 0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            Chi2(i,0) = 0;
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                Chi2(i,0) += fVacov(i,j) * gamma(i,0) * gamma(j,0);
+                dNdf       += fVacov(i,j) * wZdp_inv(j,i);
+            }
+        }
+        Chisq = GetMatrixSumCol(Chi2, 0);
+        SpurAR = fNa - dNdf;
+
+        //-----------------------------------------------------
+        // calculate the norm |AR - AR+|**2
+
+        TMatrixD AR(fNa, fNa);
+        DiffAR2 = 0.0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                AR(i,j) = 0.0;
+                for (UInt_t k=0; k<fNa; k++)
+                    AR(i,j) +=  fVacov(i,k) * wZdp_inv(k,j);
+                DiffAR2 += AR(i,j) * AR(i,j);
+            }
+        }
+
+        //--------------------------------------------------------
+        //--      fill distribution b(*)
+        fVb = p;
+        fVb *= norm;
+
+        //--      determine the covariance matrix of b (very expensive)
+
+        TMatrixD T(fNb,fNa);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                T(i,j) = 0.0;
+                for (UInt_t k=0; k<fNa; k++)
+                    T(i,j) += xiter*wZdp_inv(k,j)*(fMigrat(k,i)-alpha(k,0))*p(i,0);
+            }
+        }
+
+        SpurSigma = CalcSpurSigma(T, norm);
+
+        //--------------------------------------------------------
+
+        //-----------------------------------------------------
+        // calculate the second derivative squared
+
+        SecDeriv = 0;
+        for (UInt_t j=1; j<(fNb-1); j++)
+        {
+            Double_t temp =
+                + 2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+                - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+            SecDeriv += temp*temp;
+        }
+
+        ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+        Entropy = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            if (p(j,0) > 0.0)
+                Entropy += p(j,0) * log( p(j,0) );
+
+        //--------------------------------------------------------
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Smooth migration matrix
+    //              by fitting a function to the migration matrix
+    //
+    Bool_t SmoothMigrationMatrix(TH2D &hmigorig)
+    {
+        // copy histograms into matrices; the matrices will be used in fcnSmooth
+        // ------------------------
+
+        cout << "MUnfold::SmoothMigrationMatrix : fNa, fNb = " << fNa << ",  " << fNb << endl;
+
+        cout << "MUnfold::SmoothMigrationMatrix:   fMigOrig = "  << endl;
+        cout << "========================================"  << endl;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fMigOrig(i, j)     = hmigorig.GetBinContent(i+1, j+1);
+                cout << fMigOrig(i, j) << " \t";
+            }
+            cout << endl;
+        }
+
+        // ------------------------
+
+        cout << "MUnfold::SmoothMigrationMatrix :   fMigOrigerr2 = " << endl;
+        cout << "=============================================" << endl;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fMigOrigerr2(i, j) =   hmigorig.GetBinError(i+1, j+1)
+                    * hmigorig.GetBinError(i+1, j+1);
+
+                cout << fMigOrigerr2(i, j) << " \t";
+            }
+            cout << endl;
+        }
+
+        // ------------------------
+        // the number of free parameters (npar) is equal to 6:
+        //     a0mean, a1mean, a2mean     
+        //     <log10(Eest)>    = a0 + a1*log10(Etrue) + a2*SQR(log10(Etrue))
+        //                                                     + log10(Etrue)  
+        //     b0RMS,  b1RMS, b2RMS      
+        //     RMS(log10(Eest)) = b0 + b1*log10(Etrue) + b2*SQR(log10(Etrue))
+        // 
+        UInt_t npar = 6;
+
+        if (npar > 20)
+        {
+            cout << "MUnfold::SmoothMigrationMatrix : too many parameters,  npar = "
+                << npar << endl;
+            return kFALSE;
+        }
+
+
+        //..............................................
+        // Find reasonable starting values for a0, a1 and b0, b1
+
+        Double_t xbar   = 0.0;
+        Double_t xxbar  = 0.0;
+
+        Double_t ybarm  = 0.0;
+        Double_t xybarm = 0.0;
+
+        Double_t ybarR  = 0.0;
+        Double_t xybarR = 0.0;
+
+        Double_t Sum = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            Double_t x = (double)j + 0.5;
+
+            Double_t meany = 0.0;
+            Double_t RMSy  = 0.0;
+            Double_t sum   = 0.0;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                Double_t y = (double)i + 0.5;
+                meany +=   y * fMigOrig(i, j);
+                RMSy  += y*y * fMigOrig(i, j);
+                sum   +=       fMigOrig(i, j);
+            }
+            if (sum > 0.0)
+            {
+                meany  = meany / sum;
+                RMSy   =  RMSy / sum  - meany*meany;
+                RMSy = sqrt(RMSy);
+
+                Sum += sum;
+                xbar  +=   x * sum;
+                xxbar += x*x * sum;
+
+                ybarm  +=   meany * sum;
+                xybarm += x*meany * sum;
+
+                ybarR  +=   RMSy  * sum;
+                xybarR += x*RMSy  * sum;
+            }
+        }
+
+        if (Sum > 0.0)
+        {
+            xbar   /= Sum;
+            xxbar  /= Sum;
+
+            ybarm  /= Sum;
+            xybarm /= Sum;
+
+            ybarR  /= Sum;
+            xybarR /= Sum;
+        }
+
+        Double_t a1start = (xybarm - xbar*ybarm) / (xxbar - xbar*xbar);
+        Double_t a0start = ybarm - a1start*xbar;
+        a1start = a1start - 1.0;
+
+        Double_t b1start = (xybarR - xbar*ybarR) / (xxbar - xbar*xbar);
+        Double_t b0start = ybarR - b1start*xbar;
+
+        cout << "MUnfold::SmoothMigrationMatrix : " << endl;
+        cout << "============================" << endl;
+        cout << "a0start, a1start = " << a0start << ",  " << a1start << endl;
+        cout << "b0start, b1start = " << b0start << ",  " << b1start << endl;
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+
+        char name[20][100];
+        Double_t vinit[20];
+        Double_t  step[20];
+        Double_t limlo[20];
+        Double_t limup[20];
+        Int_t    fix[20];
+
+        sprintf(&name[0][0], "a0mean");
+        vinit[0] = a0start;
+        //vinit[0] = 1.0;
+        step[0]  = 0.1;
+        limlo[0] = 0.0;
+        limup[0] = 0.0;
+        fix[0]   = 0;
+
+        sprintf(&name[1][0], "a1mean");
+        vinit[1] = a1start;
+        //vinit[1] = 0.0;
+        step[1]  = 0.1;
+        limlo[1] = 0.0;
+        limup[1] = 0.0;
+        fix[1]   = 0;
+
+        sprintf(&name[2][0], "a2mean");
+        vinit[2] = 0.0;
+        step[2]  = 0.1;
+        limlo[2] = 0.0;
+        limup[2] = 0.0;
+        fix[2]   = 0;
+
+        sprintf(&name[3][0], "b0RMS");
+        vinit[3] = b0start;
+          //vinit[3] = 0.8;
+        step[3]  = 0.1;
+        limlo[3] = 1.e-20;
+        limup[3] = 10.0;
+        fix[3]   = 0;
+
+        sprintf(&name[4][0], "b1RMS");
+        vinit[4] = b1start;
+        //vinit[4] = 0.0;
+        step[4]  = 0.1;
+        limlo[4] = 0.0;
+        limup[4] = 0.0;
+        fix[4]   = 0;
+
+        sprintf(&name[5][0], "b2RMS");
+        vinit[5] = 0.0;
+        step[5]  = 0.1;
+        limlo[5] = 0.0;
+        limup[5] = 0.0;
+        fix[5]   = 0;
+
+
+        if ( CallMinuit(fcnSmooth, npar, name, vinit,
+                        step, limlo, limup, fix) )
+        {
+
+            // ------------------------
+            // fMigrat is the migration matrix to be used in the unfolding;
+            // fMigrat, as set by the constructor, is overwritten
+            //          by the smoothed migration matrix
+
+            for (UInt_t i=0; i<fNa; i++)
+                for (UInt_t j=0; j<fNb; j++)
+                    fMigrat(i, j) = fMigSmoo(i, j);
+
+            // ------------------------
+
+            for (UInt_t i=0; i<fNa; i++)
+                for (UInt_t j=0; j<fNb; j++)
+                    fMigraterr2(i, j) = fMigSmooerr2(i, j);
+
+
+            // normalize
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                Double_t sum = 0.0;
+                for (UInt_t i=0; i<fNa; i++)
+                    sum += fMigrat(i, j);
+
+                //cout << "SmoothMigrationMatrix : normalization fMigrat; j, sum + "
+                //     << j << ",  " << sum << endl;
+
+                if (sum == 0.0)
+                    continue;
+
+                for (UInt_t i=0; i<fNa; i++)
+                {
+                    fMigrat(i, j)     /= sum;
+                    fMigraterr2(i, j) /= (sum*sum);
+                }
+            }
+
+            cout << "MUnfold::SmoothMigrationMatrix :   fMigrat = "  << endl;
+            cout << "========================================"  << endl;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                for (UInt_t j=0; j<fNb; j++)
+                    cout << fMigrat(i, j) << " \t";
+                cout << endl;
+            }
+
+            cout << "MUnfold::SmoothMigrationMatrix :   fMigraterr2 = "  << endl;
+            cout << "============================================"  << endl;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                for (UInt_t j=0; j<fNb; j++)
+                    cout << fMigraterr2(i, j) << " \t";
+                cout << endl;
+            }
+
+            // ------------------------
+
+            return kTRUE;
+        }
+
+        return kFALSE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Prepare the call to MINUIT for the minimization of the function
+    //         f = chi2*w/2 + reg, where reg is the regularization term
+    //         reg is the sum the squared 2nd derivatives
+    //                        of the unfolded distribution
+    //
+    // the corresponding fcn routine is 'fcnTikhonov2'
+    //
+    Bool_t Tikhonov2(TH1D &hb0)
+    {
+        // the number of free parameters (npar) is equal to
+        // the number of bins (fNb) of the unfolded distribution minus 1,
+        // because of the constraint that the total number of events
+        // is fixed
+        UInt_t npar = fNb-1;
+
+        if (npar > 20)
+        {
+            cout << "MUnfold::Tikhonov2 : too many parameters,  npar = "
+                << npar << ",  fNb = " << fNb << endl;
+            return kFALSE;
+        }
+
+        // copy ideal distribution
+        
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+        
+
+        //---   start w loop -----------------------------------
+        Int_t ix;
+        Double_t xiter;
+
+        for (ix=0; ix<Nix; ix++)
+        {
+            fW = pow(10.0,log10(xmin)+ix*dlogx);
+
+            //..............................................
+            // Set starting values and step sizes for parameters
+
+            char name[20][100];
+            Double_t vinit[20];
+            Double_t  step[20];
+            Double_t limlo[20];
+            Double_t limup[20];
+            Int_t    fix[20];
+
+            for (UInt_t i=0; i<npar; i++)
+            {
+                sprintf(&name[i][0], "p%d", i+1);
+                vinit[i] = fVEps0(i);
+                step[i]  = fVEps0(i)/10;
+
+                // lower and upper limits  (limlo=limup=0: no limits)
+                //limlo[i] = 1.e-20;
+                limlo[i] = -1.0;
+                limup[i] = 1.0;
+                fix[i]   = 0;
+            }
+
+            // calculate solution for the weight fW
+            // flag non-convergence by chisq(ix) = 0.0
+            chisq(ix) = 0.0;
+            if ( CallMinuit(fcnTikhonov2, npar, name, vinit,
+                            step, limlo, limup, fix) )
+            {
+                // calculate difference between ideal and unfolded distribution
+                Double_t D2bar = 0.0;
+                for (UInt_t i = 0; i<fNb; i++)
+                {
+                    Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                    D2bar += temp*temp;
+                }
+
+                SpAR(ix)   = SpurAR;
+                SpSig(ix)  = SpurSigma;
+                chisq(ix)  = Chisq;
+                SecDer(ix) = SecDeriv;
+                ZerDer(ix) = ZerDeriv;
+                Entrop(ix) = Entropy;
+                DAR2(ix)   = DiffAR2;
+                Dsqbar(ix) = D2bar;
+            }
+        }
+
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            // test whether minimization has converged
+            if (chisq(ix) != 0.0)
+            {
+                xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+                Int_t bin;
+                bin = hBchisq->FindBin( log10(xiter) );
+                hBchisq->SetBinContent(bin,chisq(ix));
+
+                //hBSpAR->SetBinContent(bin,SpAR(ix));
+                hBSpAR->SetBinContent(bin,0.0);
+
+                hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+                hBSecDeriv->SetBinContent(bin,SecDer(ix));
+                hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+                hBEntropy->SetBinContent(bin,Entrop(ix));
+
+                //hBDAR2->SetBinContent(bin,DAR2(ix));
+                hBDAR2->SetBinContent(bin,0.0);
+
+                hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+                if (ix > 0)
+                {
+                    //Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                    //hBDSpAR->SetBinContent(bin,DSpAR);
+
+                    Double_t diff = SpSig(ix) - SpSig(ix-1);
+                    Double_t DSpSig = diff;
+                    hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                    Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                    hBDEntropy->SetBinContent(bin,DEntrop);
+
+                    Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                    hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                    Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                    hBDZerDeriv->SetBinContent(bin,DZerDer);
+                }
+            }
+        }
+
+
+        //---   end w loop -----------------------------------
+
+        // Select best weight
+        SelectBestWeight();
+
+        cout << " Tikhonov2 : after SelectBestWeight" << endl;
+
+        if (ixbest < 0.0)
+        {
+            cout << "Tikhonov2 : no result found; " << endl;
+            return kFALSE;
+        }
+
+        cout << "Tikhonov2 : best result found; " << endl;
+        cout << "===============================" << endl;
+        cout << "           ixbest = " << ixbest << endl;
+
+
+        // do a final unfolding using the best weight
+
+        fW = pow(10.0,log10(xmin)+ixbest*dlogx);
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+
+        char name[20][100];
+        Double_t vinit[20];
+        Double_t  step[20];
+        Double_t limlo[20];
+        Double_t limup[20];
+        Int_t    fix[20];
+
+        for (UInt_t i=0; i<npar; i++)
+        {
+            sprintf(&name[i][0], "p%d", i+1);
+            vinit[i] = fVEps0(i);
+            step[i]  = fVEps0(i)/10;
+
+            // lower and upper limits  (limlo=limup=0: no limits)
+            //limlo[i] = 1.e-20;
+            limlo[i] = -1.0;
+            limup[i] = 1.0;
+            fix[i]   = 0;
+        }
+
+        // calculate solution for the best weight
+        CallMinuit(fcnTikhonov2, npar, name, vinit,
+                   step, limlo, limup, fix);
+
+
+        cout << "Tikhonov : Values for best weight " << endl;
+        cout << "==================================" << endl;
+        cout << "fW, ixbest, Chisq, SpurAR, SpurSigma, SecDeriv, ZerDeriv, Entrop, DiffAR2, D2bar = " << endl;
+        cout << "      " << fW << ",  " << ixbest << ",  "
+            << Chisq << ",  " << SpurAR << ",  "
+            << SpurSigma << ",  " << SecDeriv << ",  " << ZerDeriv << ",  "
+            << Entropy << ",  " << DiffAR2 << ",  "
+            << Dsqbar(ixbest) << endl;
+
+        return kTRUE;
+
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Bertero :
+    //
+    // the unfolded distribution is calculated iteratively;
+    // the number of iterations after which the iteration is stopped
+    //            corresponds to the 'weight' in other methods
+    // a small number of iterations corresponds to strong regularization
+    // a high number to no regularization
+    //
+    // see : M.Bertero, INFN/TC-88/2 (1988)
+    //       V.B.Anykeyev et al., NIM A303 (1991) 350
+    //
+    Bool_t Bertero(TH1D &hb0)
+    {
+        // copy ideal distribution
+        
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+        
+
+        TMatrixD bold(fNb, 1);
+        bold.Zero();
+
+        //----------------------------------------------------------
+
+        Double_t db2 = 1.e20;
+
+
+        TMatrixD aminusaest(fNa, 1);
+
+        //-------   scan number of iterations   -----------------
+
+        Int_t ix;
+
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+            // calculate solution for the iteration number xiter
+            BertCore(xiter);
+
+            // calculate difference between ideal and unfolded distribution
+            Double_t D2bar = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                D2bar += temp*temp;
+            }
+
+            SpAR(ix)   = SpurAR;
+            SpSig(ix)  = SpurSigma;
+            chisq(ix)  = Chisq;
+            SecDer(ix) = SecDeriv;
+            ZerDer(ix) = ZerDeriv;
+            Entrop(ix) = Entropy;
+            DAR2(ix)   = DiffAR2;
+            Dsqbar(ix) = D2bar;
+
+            db2 = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-bold(i,0);
+                db2 += temp*temp;
+            }
+            bold = fVb;
+
+            //if (db2 < Epsdb2) break;
+
+        }
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+            Int_t bin;
+            bin = hBchisq->FindBin( log10(xiter) );
+            hBchisq->SetBinContent(bin,chisq(ix));
+            hBSpAR->SetBinContent(bin,SpAR(ix));
+            hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+            hBSecDeriv->SetBinContent(bin,SecDer(ix));
+            hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+            hBEntropy->SetBinContent(bin,Entrop(ix));
+            hBDAR2->SetBinContent(bin,DAR2(ix));
+            hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+            if (ix > 0)
+            {
+                Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                hBDSpAR->SetBinContent(bin,DSpAR);
+
+                Double_t diff = SpSig(ix) - SpSig(ix-1);
+                Double_t DSpSig = diff;
+                hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                hBDEntropy->SetBinContent(bin,DEntrop);
+
+                Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                hBDZerDeriv->SetBinContent(bin,DZerDer);
+            }
+        }
+        //-------   end of scan of number of iterations   -----------------
+
+        // Select best weight
+        SelectBestWeight();
+
+
+        if (ixbest < 0.0)
+        {
+            cout << "Bertero : weight iteration has NOT converged; " << endl;
+            return kFALSE;
+        }
+
+        cout << "Bertero : weight iteration has converged; " << endl;
+        cout << "            ixbest = " << ixbest << endl;
+
+
+        // do a final unfolding using the best weight
+
+        // calculate solution for the iteration number xiter
+        Double_t xiter = pow(10.0,log10(xmin)+ixbest*dlogx);
+        BertCore(xiter);
+
+        cout << "Bertero : Values for best weight " << endl;
+        cout << "=================================" << endl;
+        cout << "fW, ixbest, Chisq, SpurAR, SpurSigma, SecDeriv, ZerDeriv, Entrop, DiffAR2, D2bar = " << endl;
+        cout << "      " << fW << ",  " << ixbest << ",  "
+            << Chisq << ",  " << SpurAR << ",  "
+            << SpurSigma << ",  " << SecDeriv << ",  " << ZerDeriv << ",  "
+            << Entropy << ",  " << DiffAR2 << ",  "
+            << Dsqbar(ixbest) << endl;
+
+        //----------------
+
+        fNdf   = SpurAR;
+        fChisq = Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          fChi2(i,0) = Chi2(i,0);
+	}
+
+        UInt_t iNdf   = (UInt_t) (fNdf+0.5);
+        fProb = iNdf>0 ? TMath::Prob(fChisq, iNdf) : 0;
+
+
+        fResult.ResizeTo(fNb, 5);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            fResult(i, 0) = fVb(i,0);
+            fResult(i, 1) = sqrt(fVbcov(i,i));
+            fResult(i, 2) = 0.0;
+            fResult(i, 3) = 0.0;
+            fResult(i, 4) = 1.0;
+        }
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // main part of Bertero's calculations
+    //
+    Bool_t BertCore(Double_t &xiter)
+    {
+        // ignore eigen values which are smaller than EpsLambda
+        TMatrixD G_inv(fNa, fNa);
+        TMatrixD Gtil_inv(fNa, fNa);
+        TMatrixD atil(fNb, fNa);
+        TMatrixD aminusaest(fNa, 1);
+
+        G_inv.Zero();
+        Gtil_inv.Zero();
+        SpurAR = 0.0;
+
+        // -----   loop over eigen values   ------------------
+        // calculate the approximate inverse of the matrix G
+        //cout << "flaml = " << endl;
+
+        UInt_t flagstart = 2;
+        Double_t flaml=0;
+
+        for (UInt_t l=0; l<fNa; l++)
+        {
+            if (EigenValue(l) < EpsLambda)
+                continue;
+
+            switch (flagstart)
+            {
+            case 1 :
+                // This is the expression for f(lambda) if the initial C^(0)
+                // is chosen to be zero
+                flaml = 1.0 - pow(1.0-tau*EigenValue(l),xiter);
+                break;
+
+            case 2 :
+                // This is the expression for f(lambda) if the initial C^(0)
+                // is chosen to be equal to the measured distribution
+                flaml =           1.0 - pow(1.0-tau*EigenValue(l),xiter)
+                    + EigenValue(l) * pow(1.0-tau*EigenValue(l),xiter);
+                break;
+            }
+
+            //  cout << flaml << ",  ";
+
+            for (UInt_t m=0; m<fNa; m++)
+            {
+                for (UInt_t n=0; n<fNa; n++)
+                {
+                    G_inv(m,n)    += 1.0  /EigenValue(l) * Eigen(m,l)*Eigen(n,l);
+                    Gtil_inv(m,n) += flaml/EigenValue(l) * Eigen(m,l)*Eigen(n,l);
+                }
+            }
+            SpurAR += flaml;
+        }
+        //cout << endl;
+
+
+        //cout << "Gtil_inv =" << endl;
+        //for (Int_t m=0; m<fNa; m++)
+        //{
+        //  for (Int_t n=0; n<fNa; n++)
+        //  {
+        //    cout << Gtil_inv(m,n) << ",  ";
+        //  }
+        //  cout << endl;
+        //}
+
+        //-----------------------------------------------------
+        // calculate the unfolded distribution b
+        TMatrixD v2(fMigrat, TMatrixD::kTransposeMult, Gtil_inv);
+        atil = v2;
+        TMatrixD v4(atil, TMatrixD::kMult, fVa);
+        fVb = v4;
+
+        //-----------------------------------------------------
+        // calculate AR and AR+
+        TMatrixD AR(v2, TMatrixD::kMult, fMigrat);
+
+        TMatrixD v3(fMigrat, TMatrixD::kTransposeMult, G_inv);
+        TMatrixD ARplus(v3, TMatrixD::kMult, fMigrat);
+
+
+        //-----------------------------------------------------
+        // calculate the norm |AR - AR+|**2
+
+        DiffAR2 = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            for (UInt_t k=0; k<fNb; k++)
+            {
+                Double_t tempo = AR(j,k) - ARplus(j,k);
+                DiffAR2       += tempo*tempo;
+            }
+        }
+
+        //-----------------------------------------------------
+        // calculate the second derivative squared
+
+        SecDeriv = 0;
+        for (UInt_t j=1; j<(fNb-1); j++)
+        {
+            // temp = ( 2.0*fVb(j,0)-fVb(j-1,0)-fVb(j+1,0) ) / ( 2.0*fVb(j,0) );
+            Double_t temp =    2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+                - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+            SecDeriv += temp*temp;
+        }
+
+        ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+
+        Double_t sumb = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+            sumb += fVb(j,0);
+
+        TMatrixD p(fNb,1);
+        p = fVb;
+        if (sumb > 0.0)
+            p *= 1.0/sumb;
+
+        Entropy = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            if (p(j,0) > 0.0)
+                Entropy += p(j,0) * log( p(j,0) );
+
+        //-----------------------------------------------------
+
+        TMatrixD Gb(fMigrat, TMatrixD::kMult, fVb);
+        aminusaest = fVa;
+        aminusaest -= Gb;
+    
+        TMatrixD v1(1,fNa);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            v1(0,i) = 0.0;
+            for (UInt_t j=0; j<fNa; j++)
+                v1(0,i) += aminusaest(j,0) * fVacovInv(j,i) ;
+        }
+
+        //-----------------------------------------------------
+        // calculate error matrix fVbcov of unfolded distribution
+        SpurSigma = CalcSpurSigma(atil);
+
+        //-----------------------------------------------------
+        // calculate the chi squared
+        for (UInt_t i = 0; i<fNa; i++)
+            Chi2(i,0) = v1(0,i) * aminusaest(i,0);
+
+        Chisq = GetMatrixSumCol(Chi2,0);
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Calculate the matrix G = M * M(transposed)
+    //           and its eigen values and eigen vectors
+    //
+    Bool_t CalculateG()
+    {
+        // Calculate matrix G = M*M(transposed)     (M = migration matrix)
+        //           the matrix Eigen of the eigen vectors of G
+        //           the vector EigenValues of the eigen values of G
+        //           the parameter tau = 1/lambda_max
+        //
+        TMatrixD v5(TMatrixD::kTransposed, fMigrat);
+        //TMatrixD G(fMigrat, TMatrixD::kMult, v5);
+        G.Mult(fMigrat, v5);
+
+        Eigen = G.EigenVectors(EigenValue);
+
+        RankG = 0.0;
+        for (UInt_t l=0; l<fNa; l++)
+        {
+            if (EigenValue(l) < EpsLambda) continue;
+            RankG += 1.0;
+        }
+
+        tau = 1.0 / EigenValue(0);
+
+        //  cout << "eigen values : " << endl;
+        //  for (Int_t i=0; i<fNa; i++)
+        //  {
+        //    cout << EigenValue(i) << ",  ";
+        //  }
+        //  cout << endl;
+
+        //cout << "eigen vectors : " << endl;
+        //for (Int_t i=0; i<fNa; i++)
+        //{
+        //  cout << "               vector " << i << endl;
+        //  for (Int_t j=0; j<fNa; j++)
+        //  {
+        //    cout << Eigen(j,i) << ",  ";
+        //  }
+        //  cout << endl;
+        //}
+        //cout << endl;
+
+        //cout << "G =" << endl;
+        //for (Int_t m=0; m<fNa; m++)
+        //{
+        //  for (Int_t n=0; n<fNa; n++)
+        //  {
+        //    cout << G(m,n) << ",  ";
+        //  }
+        //  cout << endl;
+        //}
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Select the best weight
+    //
+    Bool_t SelectBestWeight()
+    {
+        //-------------------------------
+        // select 'best' weight according to some criterion
+
+        Int_t ix;
+
+        Double_t DiffSpSigmax = -1.e10;
+        Int_t    ixDiffSpSigmax = -1;
+
+        Double_t DiffSigpointsmin = 1.e10;
+        Int_t    ixDiffSigpointsmin = -1;
+
+        Double_t DiffRankGmin = 1.e10;
+        Int_t    ixDiffRankGmin = -1;
+
+        Double_t D2barmin = 1.e10;
+        Int_t    ixD2barmin = -1;
+
+        Double_t DiffSpSig1min = 1.e10;
+        Int_t    ixDiffSpSig1min = -1;
+
+
+        Int_t ixmax = -1;
+
+        // first loop over all weights :
+        //       find smallest chi2
+        Double_t chisqmin = 1.e20;
+        for (ix=0; ix<Nix; ix++)
+        {
+            // consider only weights for which
+            //  - unfolding was successful
+            if (chisq(ix) != 0.0)
+            {
+                if (chisq(ix) < chisqmin)
+                    chisqmin = chisq(ix);
+            }
+        }
+        Double_t chisq0 = chisqmin > fVapoints ? chisqmin : fVapoints/2.0;
+
+        // second loop over all weights :
+        //        consider only weights for which chisq(ix) < chisq0
+        ixbest = -1;
+        for (ix=0; ix<Nix; ix++)
+        {
+            if (chisq(ix) != 0.0 && chisq(ix) < 2.0*chisq0)
+            {
+                // ixmax = highest weight with successful unfolding
+                //         (Least squares solution)
+                ixmax = ix;
+
+                SpurSigma = SpSig(ix);
+                SpurAR    = SpAR(ix);
+                Chisq    = chisq(ix);
+                D2bar     = Dsqbar(ix);
+
+                //----------------------------------
+                // search weight where SpurSigma changes most
+                //                               (as a function of the weight)
+                if (ix > 0  &&  chisq(ix-1) != 0.0)
+                {
+                    Double_t diff = SpSig(ix) - SpSig(ix-1);
+                    if (diff > DiffSpSigmax)
+                    {
+                        DiffSpSigmax   = diff;
+                        ixDiffSpSigmax = ix;
+                    }
+                }
+
+                //----------------------------------
+                // search weight where Chisq is close
+                //        to the number of significant measurements
+                Double_t DiffSigpoints = fabs(Chisq-fVapoints);
+
+                if (DiffSigpoints < DiffSigpointsmin)
+                {
+                    DiffSigpointsmin   = DiffSigpoints;
+                    ixDiffSigpointsmin = ix;
+                }
+
+                //----------------------------------
+                // search weight where Chisq is close
+                //        to the rank of matrix G
+                Double_t DiffRankG = fabs(Chisq-RankG);
+
+                if (DiffRankG < DiffRankGmin)
+                {
+                    DiffRankGmin   = DiffRankG;
+                    ixDiffRankGmin = ix;
+                }
+
+                //----------------------------------
+                // search weight where SpurSigma is close to 1.0
+                Double_t DiffSpSig1 = fabs(SpurSigma/fSpurVacov-1.0);
+
+                if (DiffSpSig1 < DiffSpSig1min)
+                {
+                    DiffSpSig1min   = DiffSpSig1;
+                    ixDiffSpSig1min = ix;
+                }
+
+                //----------------------------------
+                // search weight where D2bar is minimal
+
+                if (D2bar < D2barmin)
+                {
+                    D2barmin   = D2bar;
+                    ixD2barmin = ix;
+                }
+
+                //----------------------------------
+            }
+        }
+
+
+        // choose solution where increase of SpurSigma is biggest
+        //if ( DiffSpSigmax > 0.0)
+        //  ixbest = ixDiffSpSigmax;
+        //else
+        //  ixbest = ixDiffSigpointsmin;
+
+        // choose Least Squares Solution
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+        // ixbest = ixmax;
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+        // choose weight where chi2 is close to the number of significant
+        // measurements
+        // ixbest = ixDiffSigpointsmin;
+
+        // choose weight where chi2 is close to the rank of matrix G
+        // ixbest = ixDiffRankGmin;
+
+        // choose weight where chi2 is close to the rank of matrix G
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+           ixbest = ixDiffSpSig1min;
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+        cout << "SelectBestWeight : ixDiffSpSigmax, DiffSpSigmax = "
+            << ixDiffSpSigmax << ",  " << DiffSpSigmax << endl;
+        cout << "================== ixDiffSigpointsmin, DiffSigpointsmin = "
+            << ixDiffSigpointsmin << ",  " << DiffSigpointsmin << endl;
+
+        cout << "                   ixDiffRankGmin, DiffRankGmin = "
+            << ixDiffRankGmin << ",  " << DiffRankGmin << endl;
+
+        cout << "                   ixDiffSpSig1min, DiffSpSig1min = "
+            << ixDiffSpSig1min << ",  " << DiffSpSig1min << endl;
+
+        cout << "                   ixD2barmin, D2barmin = "
+            << ixD2barmin << ",  " << D2barmin << endl;
+        cout << "                   ixmax  = " << ixmax  << endl;
+        cout << "                   ixbest = " << ixbest << endl;
+
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Draw the plots
+    //
+    Bool_t DrawPlots()
+    {
+
+        // in the plots, mark the weight which has been selected
+        Double_t xbin = log10(xmin)+ixbest*dlogx;
+
+        TMarker *m = new TMarker();
+        m->SetMarkerSize(1);
+        m->SetMarkerStyle(20);
+
+        //-------------------------------------
+        // draw the iteration plots
+        TCanvas *c = new TCanvas("iter", "Plots versus weight", 900, 600);
+        c->Divide(3,2);
+
+        c->cd(1);
+        hBchisq->Draw();
+        gPad->SetLogy();
+        hBchisq->SetXTitle("log10(iteration number)");
+        hBchisq->SetYTitle("chisq");
+        m->DrawMarker(xbin, log10(chisq(ixbest)));
+
+        c->cd(2);
+        hBD2bar->Draw();
+        gPad->SetLogy();
+        hBD2bar->SetXTitle("log10(iteration number)");
+        hBD2bar->SetYTitle("(b_unfolded-b_ideal)**2");
+        m->DrawMarker(xbin, log10(Dsqbar(ixbest)));
+
+        /*
+         c->cd(3);
+         hBDAR2->Draw();
+         gPad->SetLogy();
+         strgx = "log10(iteration number)";
+         strgy = "norm(AR-AR+)";
+         hBDAR2->SetXTitle(strgx);
+         hBDAR2->SetYTitle(strgy);
+         m->DrawMarker(xbin, log10(DAR2(ixbest)));
+         */
+
+        c->cd(3);
+        hBSecDeriv->Draw();
+        hBSecDeriv->SetXTitle("log10(iteration number)");
+        hBSecDeriv->SetYTitle("Second Derivative squared");
+        m->DrawMarker(xbin, SecDer(ixbest));
+
+        /*
+         c->cd(8);
+         hBDSecDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Second Derivative squared)";
+         hBDSecDeriv->SetXTitle(strgx);
+         hBDSecDeriv->SetYTitle(strgy);
+         */
+
+        /*
+         c->cd(4);
+         hBZerDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Zero Derivative squared";
+         hBZerDeriv->SetXTitle(strgx);
+         hBZerDeriv->SetYTitle(strgy);
+         m->DrawMarker(xbin, ZerDer(ixbest));
+         */
+
+        /*
+         c->cd(5);
+         hBDZerDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Zero Derivative squared)";
+         hBDZerDeriv->SetXTitle(strgx);
+         hBDZerDeriv->SetYTitle(strgy);
+         */
+
+        c->cd(4);
+        hBSpAR->Draw();
+        hBSpAR->SetXTitle("log10(iteration number)");
+        hBSpAR->SetYTitle("SpurAR");
+        m->DrawMarker(xbin, SpAR(ixbest));
+
+
+        /*
+         c->cd(11);
+         hBDSpAR->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(SpurAR)";
+         hBDSpAR->SetXTitle(strgx);
+         hBDSpAR->SetYTitle(strgy);
+         */
+
+        c->cd(5);
+        hBSpSig->Draw();
+        hBSpSig->SetXTitle("log10(iteration number)");
+        hBSpSig->SetYTitle("SpurSig/SpurC");
+        m->DrawMarker(xbin, SpSig(ixbest)/fSpurVacov);
+
+        /*
+         c->cd(14);
+         hBDSpSig->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(SpurSig/SpurC)";
+         hBDSpSig->SetXTitle(strgx);
+         hBDSpSig->SetYTitle(strgy);
+         */
+
+        c->cd(6);
+        hBEntropy->Draw();
+        hBEntropy->SetXTitle("log10(iteration number)");
+        hBEntropy->SetYTitle("Entropy");
+        m->DrawMarker(xbin, Entrop(ixbest));
+
+        /*
+         c->cd(17);
+         hBDEntropy->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Entropy)";
+         hBDEntropy->SetXTitle(strgx);
+         hBDEntropy->SetYTitle(strgy);
+         */
+
+        //-------------------------------------
+
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            fha->SetBinContent(i+1, fVa(i, 0)         );
+            fha->SetBinError  (i+1, sqrt(fVacov(i, i)));
+
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fhmig->SetBinContent(i+1, j+1, fMigOrig(i, j)           );
+                fhmig->SetBinError  (i+1, j+1, sqrt(fMigOrigerr2(i, j)) );
+
+                shmig->SetBinContent(i+1, j+1, fMigrat(i, j)           );
+                shmig->SetBinError  (i+1, j+1, sqrt(fMigraterr2(i, j)) );
+                shmigChi2->SetBinContent(i+1, j+1, fMigChi2(i, j)   );
+            }
+        }
+
+        PrintTH2Content(*shmig);
+        PrintTH2Content(*shmigChi2);
+
+        //-------------------------------------
+        CopyCol(*hprior, fVEps);
+        CopyCol(*hb,     fVb);
+        for (UInt_t i=0; i<fNb; i++)
+            hb->SetBinError(i+1, sqrt(fVbcov(i, i)));
+
+        PrintTH1Content(*hb);
+        PrintTH1Error(*hb);
+
+        //..............................................
+        for (UInt_t i=0; i<fNa; i++)
+            hEigen->SetBinContent(i+1, EigenValue(i));
+
+        //..............................................
+        // draw the plots
+        TCanvas *cc = new TCanvas("input", "Unfolding input", 900, 600);
+        cc->Divide(3, 2);
+
+        // distribution to be unfolded
+        cc->cd(1);
+        fha->Draw();
+        gPad->SetLogy();
+        fha->SetXTitle("log10(E-est/GeV)");
+        fha->SetYTitle("Counts");
+
+        // superimpose unfolded distribution
+        // hb->Draw("*HSAME");
+
+        // prior distribution
+        cc->cd(2);
+        hprior->Draw();
+        gPad->SetLogy();
+        hprior->SetXTitle("log10(E-true/GeV)");
+        hprior->SetYTitle("Counts");
+
+        // migration matrix
+        cc->cd(3);
+        fhmig->Draw("box");
+        fhmig->SetXTitle("log10(E-est/GeV)");
+        fhmig->SetYTitle("log10(E-true/GeV)");
+
+        // smoothed migration matrix
+        cc->cd(4);
+        shmig->Draw("box");
+        shmig->SetXTitle("log10(E-est/GeV)");
+        shmig->SetYTitle("log10(E-true/GeV)");
+
+        // chi2 contributions for smoothing
+        cc->cd(5);
+        shmigChi2->Draw("box");
+        shmigChi2->SetXTitle("log10(E-est/GeV)");
+        shmigChi2->SetYTitle("log10(E-true/GeV)");
+
+        // Eigenvalues of matrix M*M(transposed)
+        cc->cd(6);
+        hEigen->Draw();
+        hEigen->SetXTitle("l");
+        hEigen->SetYTitle("Eigen values Lambda_l of M*M(transposed)");
+
+
+       //..............................................
+        // draw the results
+        TCanvas *cr = new TCanvas("results", "Unfolding results", 600, 600);
+        cr->Divide(2, 2);
+
+        // unfolded distribution
+        cr->cd(1);
+        hb->Draw();
+        gPad->SetLogy();
+        hb->SetXTitle("log10(E-true/GeV)");
+        hb->SetYTitle("Counts");
+
+	
+        // covariance matrix of unfolded distribution
+        cr->cd(2);
+        TH1 *hbcov=DrawMatrixClone(fVbcov, "lego");
+        hbcov->SetBins(fNb, hb->GetBinLowEdge(1), hb->GetBinLowEdge(fNb+1),
+                       fNb, hb->GetBinLowEdge(1), hb->GetBinLowEdge(fNb+1));
+
+        hbcov->SetName("hbcov");
+        hbcov->SetTitle("Error matrix of distribution hb");
+        hbcov->SetXTitle("log10(E-true/GeV)");
+        hbcov->SetYTitle("log10(E-true/GeV)");
+       
+	
+        // chi2 contributions
+        cr->cd(3);
+        TH1 *hchi2=DrawMatrixColClone(fChi2);
+        hchi2->SetBins(fNa, fha->GetBinLowEdge(1), fha->GetBinLowEdge(fNa+1));
+
+        hchi2->SetName("Chi2");
+        hchi2->SetTitle("chi2 contributions");
+        hchi2->SetXTitle("log10(E-est/GeV)");
+        hchi2->SetYTitle("Chisquared");
+	
+	
+        // ideal distribution
+        
+        cr->cd(4);
+        fhb0->Draw();
+        gPad->SetLogy();
+        fhb0->SetXTitle("log10(E-true/GeV)");
+        fhb0->SetYTitle("Counts");
+        
+
+        // superimpose unfolded distribution
+        hb->Draw("*Hsame");
+	
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Interface to MINUIT
+    //
+    //
+    Bool_t CallMinuit(
+                      void (*fcnx)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t),
+                      UInt_t npar, char name[20][100],
+                      Double_t vinit[20], Double_t step[20],
+                      Double_t limlo[20], Double_t limup[20], Int_t fix[20])
+    {
+        //
+        // Be carefull: This is not thread safe
+        //
+        UInt_t maxpar = 100;
+
+        if (npar > maxpar)
+        {
+            cout << "MUnfold::CallMinuit : too many parameters,  npar = " << fNb
+                << ",   maxpar = " << maxpar << endl;
+            return kFALSE;
+        }
+
+        //..............................................
+        // Set the maximum number of parameters
+        TMinuit minuit(maxpar);
+
+
+        //..............................................
+        // Set the print level
+        // -1   no output except SHOW comands
+        //  0   minimum output
+        //  1   normal output (default)
+        //  2   additional ouput giving intermediate results
+        //  3   maximum output, showing progress of minimizations
+        //
+        Int_t printLevel = -1;
+        minuit.SetPrintLevel(printLevel);
+
+        //..............................................       
+        // Printout for warnings
+        //    SET WAR      print warnings
+        //    SET NOW      suppress warnings
+        Int_t errWarn;
+        Double_t tmpwar = 0;
+        minuit.mnexcm("SET NOW", &tmpwar, 0, errWarn);
+
+        //..............................................
+        // Set the address of the minimization function
+        minuit.SetFCN(fcnx);
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+        for (UInt_t i=0; i<npar; i++)
+        {
+            if (minuit.DefineParameter(i, &name[i][0], vinit[i], step[i],
+                                       limlo[i], limup[i]))
+            {
+                cout << "MUnfold::CallMinuit: Error in defining parameter "
+                    << name << endl;
+                return kFALSE;
+            }
+        }
+
+        //..............................................
+        //Int_t NumPars = minuit.GetNumPars();
+        //cout << "MUnfold::CallMinuit :  number of free parameters = "
+        //     << NumPars << endl;
+
+        //..............................................
+        // Minimization
+        minuit.SetObjectFit(this);
+
+        //..............................................
+        // Error definition :
+        //
+        //    for chisquare function :
+        //      up = 1.0   means calculate 1-standard deviation error
+        //         = 4.0   means calculate 2-standard deviation error
+        //
+        //    for log(likelihood) function :
+        //      up = 0.5   means calculate 1-standard deviation error
+        //         = 2.0   means calculate 2-standard deviation error
+        Double_t up = 1.0;
+        minuit.SetErrorDef(up);
+
+
+
+        // Int_t errMigrad;
+        // Double_t tmp = 0;
+        // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+
+        //..............................................
+        // fix a parameter
+        for (UInt_t i=0; i<npar; i++)
+        {
+            if (fix[i] > 0)
+            {
+                Int_t parNo = i;
+                minuit.FixParameter(parNo);
+            }
+        }
+
+        //..............................................
+        // Set maximum number of iterations (default = 500)
+        Int_t maxiter = 100000;
+        minuit.SetMaxIterations(maxiter);
+
+        //..............................................
+        // minimization by the method of Migrad
+        // Int_t errMigrad;
+        // Double_t tmp = 0;
+        // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+        //..............................................       
+        // same minimization as by Migrad
+        // but switches to the SIMPLEX method if MIGRAD fails to converge
+        Int_t errMinimize;
+        Double_t tmp = 0;
+        minuit.mnexcm("MINIMIZE", &tmp, 0, errMinimize);
+
+        //..............................................       
+        // check quality of minimization
+        // istat = 0   covariance matrix not calculated
+        //         1   diagonal approximation only (not accurate)
+        //         2   full matrix, but forced positive-definite
+        //         3   full accurate covariance matrix 
+        //             (indication of normal convergence)
+        Double_t fmin, fedm, errdef;
+        Int_t    npari, nparx, istat;
+        minuit.mnstat(fmin, fedm, errdef, npari, nparx, istat);
+
+        if (errMinimize || istat < 3)
+        {
+            cout << "MUnfold::CallMinuit : Minimization failed" << endl;
+            cout << "       fmin = " << fmin   << ",   fedm = "  << fedm
+                << ",   errdef = "  << errdef << ",   istat = " << istat
+                << endl;
+            return kFALSE;
+        }
+
+        //..............................................
+        // Minos error analysis
+        // minuit.mnmnos();
+
+        //..............................................       
+        // Print current status of minimization
+        // if nkode = 0    only function value
+        //            1    parameter values, errors, limits
+        //            2    values, errors, step sizes, internal values
+        //            3    values, errors, step sizes, 1st derivatives
+        //            4    values, paraboloc errors, MINOS errors
+  
+        //Int_t nkode = 4;
+        //minuit.mnprin(nkode, fmin);
+
+        //..............................................       
+        // call fcn with IFLAG = 3 (final calculation : calculate p(chi2))
+        // iflag = 1   initial calculations only
+        //         2   calculate 1st derivatives and function
+        //         3   calculate function only
+        //         4   calculate function + final calculations
+        const char *command = "CALL";
+        Double_t iflag = 3;
+        Int_t errfcn3;
+        minuit.mnexcm(command, &iflag, 1, errfcn3); 
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the unfolded distribution
+    //
+    TMatrixD &GetVb() { return fVb; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the covariance matrix of the unfolded distribution
+    //
+    TMatrixD &GetVbcov() { return fVbcov; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the unfolded distribution + various errors
+    //
+    TMatrixD &GetResult() { return fResult; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the chisquared contributions
+    //
+    TMatrixD &GetChi2() { return fChi2; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the total chisquared
+    //
+    Double_t &GetChisq() { return fChisq; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the number of degrees of freedom
+    //
+    Double_t &GetNdf() { return fNdf; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the chisquared probability
+    //
+    Double_t &GetProb() { return fProb; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the smoothed migration matrix
+    //
+    TMatrixD &GetMigSmoo() { return fMigSmoo; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the error2 of the smoothed migration matrix
+    //
+    TMatrixD &GetMigSmooerr2() { return fMigSmooerr2; }
+
+    // -----------------------------------------------------------------------
+    //
+    // Return the chi2 contributions for the smoothing
+    //
+    TMatrixD &GetMigChi2() { return fMigChi2; }
+};
+// end of definition of class MUnfold
+///////////////////////////////////////////////////
+
+
+// -----------------------------------------------------------------------
+//
+// fcnSmooth     (used by SmoothMigrationMatrix)
+//
+// is called by MINUIT
+// for given values of the parameters it calculates the function 
+//                                               to be minimized
+//
+void fcnSmooth(Int_t &npar, Double_t *gin, Double_t &f, 
+               Double_t *par, Int_t iflag)
+{
+    MUnfold &gUnfold = *(MUnfold*)gMinuit->GetObjectFit();
+
+    Double_t a0 = par[0];
+    Double_t a1 = par[1];
+    Double_t a2 = par[2];
+
+    Double_t b0 = par[3];
+    Double_t b1 = par[4];
+    Double_t b2 = par[5];
+
+    // loop over bins of log10(E-true)
+    Double_t chi2 = 0.0;
+    Int_t npoints = 0;
+    Double_t func[20];
+
+    for (UInt_t j=0; j<gUnfold.fNb; j++)
+    {
+        Double_t yj   = ((double)j) + 0.5;
+        Double_t mean = a0 + a1*yj + a2*yj*yj + yj;
+        Double_t RMS  = b0 + b1*yj + b2*yj*yj;
+
+        if (RMS <= 0.0)
+        {
+            chi2 = 1.e20;
+            break;
+        }
+
+        // loop over bins of log10(E-est)
+
+        //.......................................
+        Double_t function;
+        Double_t sum=0.0;
+        for (UInt_t i=0; i<gUnfold.fNa; i++)
+        {
+            Double_t xlow = (double)i;
+            Double_t xup  = xlow + 1.0;
+            Double_t xl  = (xlow- mean) / RMS;
+            Double_t xu  = (xup - mean) / RMS;
+            function = (TMath::Freq(xu) - TMath::Freq(xl));
+
+            //cout << "i, xl, xu, function = " <<  i <<  ",  "  << xl << ",  "
+            //     << xu  << ",  " << function << endl;
+
+            if (function < 1.e-10)
+                function = 0.0;
+
+            func[i] = function;
+            sum += function;
+        }
+
+        //      cout << "mean, RMS = "  << mean << ",  " << RMS
+        //     << ",   j , sum of function = " << j << ",  " << sum << endl;
+
+        //.......................................
+
+        for (UInt_t i=0; i<gUnfold.fNa; i++)
+        {
+            if (sum != 0.0)
+                func[i] /= sum;
+
+            gUnfold.fMigSmoo(i,j) = func[i];
+            gUnfold.fMigChi2(i,j) = 0.0;
+
+            // if relative error is greater than 30 % ignore the point
+
+            if (gUnfold.fMigOrig(i,j)     != 0 &&
+                gUnfold.fMigOrigerr2(i,j) != 0 &&
+                func[i] != 0  )
+            {
+                if (gUnfold.fMigOrigerr2(i,j)/
+                    (gUnfold.fMigOrig(i,j)*gUnfold.fMigOrig(i,j)) <= 0.09)
+                {
+                    gUnfold.fMigChi2(i,j) =   ( gUnfold.fMigOrig(i,j) - func[i] )
+                        * ( gUnfold.fMigOrig(i,j) - func[i] )
+                        /   gUnfold.fMigOrigerr2(i,j);
+                    chi2 += gUnfold.fMigChi2(i,j);
+                    npoints += 1;
+                }
+            }
+        }
+        //.......................................
+
+    }
+    f = chi2;
+
+    //cout << "fcnSmooth : f = " << f << endl;
+
+    //--------------------------------------------------------------------
+    // final calculations
+    if (iflag == 3)
+    {
+        Int_t     NDF = npoints - npar;
+        Double_t prob = TMath::Prob(chi2, NDF);
+
+        cout << "fcnSmooth : npoints, chi2, NDF, prob = " << npoints << ",  ";
+        cout << chi2 << ",  " << NDF << ",  " << prob << endl;
+        cout << "=======================================" << endl;
+    }
+}
+
+// -----------------------------------------------------------------------
+//
+// fcnTikhonov2     (used by Tikhonov2)
+//
+// is called by MINUIT
+// for given values of the parameters it calculates the function F
+// the free parameters are the first (fNb-1) elements
+//                     of the normalized unfolded distribution
+//
+void fcnTikhonov2(Int_t &npar, Double_t *gin, Double_t &f,
+                  Double_t *par, Int_t iflag)
+{
+    MUnfold &gUnfold = *(MUnfold*)gMinuit->GetObjectFit();
+
+    // (npar+1) is the number of bins of the unfolded distribuition (fNb)
+    //  npar    is the number of free parameters                    (fNb-1)
+
+    UInt_t npar1 = npar + 1;
+
+    UInt_t fNa = gUnfold.fNa;
+    UInt_t fNb = gUnfold.fNb;
+    if (npar1 != fNb)
+    {
+        cout << "fcnTikhonov2 : inconsistency in number of parameters; npar, fNb = ";
+        cout << npar << ",  " << fNb << endl;
+        //return;
+    }
+    npar1 = fNb;
+
+    TMatrixD p(npar1, 1);
+    TMatrixD &fVb = gUnfold.fVb;
+
+    // p is the normalized unfolded distribution
+    // sum(p(i,0)) from i=0 to npar is equal to 1
+    Double_t sum = 0.0;
+    for (Int_t i=0; i<npar; i++)
+    {
+        p(i,0) = par[i];
+        sum += par[i];
+    }
+    p(npar,0) = 1.0 - sum;
+
+
+    // all p(i,0) have to be greater than zero
+    for (UInt_t i=0; i<npar1; i++)
+        if (p(i,0) <= 0.0)
+        {
+            f = 1.e20;
+            return;
+        }
+
+    //.......................
+    // take least squares result for the normaliztion
+    TMatrixD alpha(gUnfold.fMigrat, TMatrixD::kMult, p);
+
+    //TMatrixD v4   (gUnfold.fVa, TMatrixD::kTransposeMult,
+    //                                 gUnfold.fVacovInv);
+    //TMatrixD norma(v4,  TMatrixD::kMult, gUnfold.fVa);
+
+    TMatrixD v5   (alpha, TMatrixD::kTransposeMult, gUnfold.fVacovInv);
+    TMatrixD normb(v5,    TMatrixD::kMult, alpha);
+
+    TMatrixD normc(v5,    TMatrixD::kMult, gUnfold.fVa);
+
+    Double_t norm  = normc(0,0)/normb(0,0);
+
+    //.......................
+
+    // b is the unnormalized unfolded distribution
+    // sum(b(i,0)) from i=0 to npar is equal to norm
+    //                       (the total number of events)
+    for (UInt_t i=0; i<npar1; i++)
+        fVb(i,0) = p(i,0) * norm;
+
+    TMatrixD Gb(gUnfold.fMigrat, TMatrixD::kMult, fVb);
+    TMatrixD v3(fNa, 1);
+    v3 = gUnfold.fVa;
+    v3 -= Gb;
+
+    TMatrixD v1(1,fNa);
+    for (UInt_t i=0; i<fNa; i++)
+    {
+        v1(0,i) = 0;
+        for (UInt_t j=0; j<fNa; j++)
+            v1(0,i) += v3(j,0) * gUnfold.fVacovInv(j,i) ;
+    }
+
+    for (UInt_t i = 0; i<fNa; i++)
+        gUnfold.Chi2(i,0) = v1(0,i) * v3(i,0);
+
+    gUnfold.Chisq = GetMatrixSumCol(gUnfold.Chi2,0);
+
+    //-----------------------------------------------------
+    // calculate 2nd derivative squared
+    // regularization term (second derivative squared)
+    gUnfold.SecDeriv = 0;
+    for (UInt_t j=1; j<(fNb-1); j++)
+     {
+         const Double_t temp =
+             + 2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+             - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+
+         gUnfold.SecDeriv += temp*temp;
+     }
+
+    gUnfold.ZerDeriv = 0;
+    for (UInt_t j=0; j<fNb; j++)
+        gUnfold.ZerDeriv += fVb(j,0) * fVb(j,0);
+
+    f = gUnfold.Chisq/2 * gUnfold.fW + gUnfold.SecDeriv;
+
+    //cout << "F=" << f      << " \tSecDeriv=" << gUnfold.SecDeriv
+    //     << " \tchi2="
+    //	  << gUnfold.Chisq << " \tfW=" << gUnfold.fW << endl;
+
+    //--------------------------------------------------------------------
+    // final calculations
+    if (iflag == 3)
+    {
+        //..............................................
+        // calculate external error matrix of the fitted parameters 'val'
+        // extend it with the covariances for y=1-sum(val)
+        Double_t emat[20][20];
+        Int_t    ndim = 20;
+        gMinuit->mnemat(&emat[0][0], ndim);
+
+        Double_t covv = 0;
+        for (UInt_t i=0; i<(gUnfold.fNb-1); i++)
+        {
+            Double_t cov = 0;
+            for (UInt_t k=0; k<(gUnfold.fNb-1); k++)
+                cov += emat[i][k];
+
+            emat[i][gUnfold.fNb-1] = -cov;
+            emat[gUnfold.fNb-1][i] = -cov;
+
+            covv += cov;
+        }
+        emat[gUnfold.fNb-1][gUnfold.fNb-1] = covv;
+
+        for (UInt_t i=0; i<gUnfold.fNb; i++)
+            for (UInt_t k=0; k<gUnfold.fNb; k++)
+                gUnfold.fVbcov(i,k) = emat[i][k] *norm*norm;
+
+        //-----------------------------------------------------
+        //..............................................
+        // put unfolded distribution into fResult
+        //     fResult(i,0)   value in bin i
+        //     fResult(i,1)   error of value in bin i
+
+        gUnfold.fResult.ResizeTo(gUnfold.fNb, 5);
+
+        Double_t sum = 0;
+        for (UInt_t i=0; i<(gUnfold.fNb-1); i++)
+        {
+            Double_t val;
+            Double_t err;
+            if (!gMinuit->GetParameter(i, val, err))
+            {
+                cout << "Error getting parameter #" << i << endl;
+                return;
+            }
+
+            Double_t eplus;
+            Double_t eminus;
+            Double_t eparab;
+            Double_t gcc;
+            gMinuit->mnerrs(i, eplus, eminus, eparab, gcc);
+
+            gUnfold.fVb(i, 0)     = val    * norm;
+
+            gUnfold.fResult(i, 0) = val    * norm;
+            gUnfold.fResult(i, 1) = eparab * norm;
+            gUnfold.fResult(i, 2) = eplus  * norm;
+            gUnfold.fResult(i, 3) = eminus * norm;
+            gUnfold.fResult(i, 4) = gcc;
+            sum += val;
+        }
+        gUnfold.fVb(gUnfold.fNb-1, 0)     = (1.0-sum) * norm;
+
+        gUnfold.fResult(gUnfold.fNb-1, 0) = (1.0-sum) * norm;
+        gUnfold.fResult(gUnfold.fNb-1, 1) =
+            sqrt(gUnfold.fVbcov(gUnfold.fNb-1,gUnfold.fNb-1));
+        gUnfold.fResult(gUnfold.fNb-1, 2) = 0;
+        gUnfold.fResult(gUnfold.fNb-1, 3) = 0;
+        gUnfold.fResult(gUnfold.fNb-1, 4) = 1;
+        //..............................................
+
+        //-----------------------------------------------------
+        // calculate 0th derivative squared
+        gUnfold.ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            gUnfold.ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+
+        gUnfold.Entropy = 0;
+        for (UInt_t j=0; j<gUnfold.fNb; j++)
+            if (p(j,0) > 0)
+                gUnfold.Entropy += p(j,0) * log( p(j,0) );
+
+
+        //-----------------------------------------------------
+        // calculate SpurSigma
+        gUnfold.SpurSigma = 0.0;
+        for (UInt_t m=0; m<fNb; m++)
+            gUnfold.SpurSigma += gUnfold.fVbcov(m,m);
+        // cout << "SpurSigma =" << SpurSigma << endl;
+
+        //-----------------------------------------------------
+        gUnfold.SpurAR  = 0;
+        gUnfold.DiffAR2 = 0;
+
+        //-----------------------------------------------------
+        gUnfold.fNdf   = gUnfold.fNa;
+        gUnfold.fChisq   = gUnfold.Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          gUnfold.fChi2(i,0) = gUnfold.Chi2(i,0);
+	}
+
+
+        UInt_t iNdf = (UInt_t) (gUnfold.fNdf+0.5);
+
+        //cout << "fcnTikhonov2 : fW, chisq (from fcnF) = "
+        //     << gUnfold.fW << ",  " << gUnfold.fChisq << endl;
+
+        gUnfold.fProb = iNdf>0 ? TMath::Prob(gUnfold.fChisq, iNdf) : 0;
+    }
+}
+
+
+// ======================================================
+//
+// SteerUnfold
+//
+void SteerUnfold(TH1D &ha,     TH2D &hacov, TH2D &hmig,
+                 TH2D &hmigor, TH1D &hb0,   TH1D *hpr=NULL)
+{
+    // ha      is the distribution to be unfolded
+    // hacov   is the covariance matrix of the distribution ha
+    // hmig    is the migration matrix;
+    //         it is used in the unfolding unless it is overwritten
+    //         by SmoothMigrationMatrix by the smoothed migration matrix
+    // hmigor  is the migration matrix to be smoothed;
+    //         the smoothed migration matrix will be used in the unfolding
+    // hpr     the prior distribution
+    //         it is only used if SetPriorInput(*hpr) is called   
+
+    //..............................................       
+    // create an MUnfold object;
+    // fill histograms into vectors and matrices
+
+    MUnfold unfold(ha, hacov, hmig);
+
+    //..............................................       
+    // smooth the migration matrix;
+    //        the smoothed migration matrix will be used in the unfolding
+    //        hmig is the original (unsmoothed) migration matrix
+
+    unfold.SmoothMigrationMatrix(hmigor);
+
+    //..............................................       
+    // define prior distribution (has always to be defined) 
+    // the alternatives are  :
+
+    // 1  SetPriorConstant() :   isotropic distribution
+    // 2  SetPriorPower(gamma) : dN/dE = E^{-gamma}
+    // 3  SetPriorInput(*hpr):   the distribution *hpr is used 
+    // 4  SetPriorRebin(*ha) :   use rebinned histogram ha 
+
+    UInt_t flagprior = 4;
+    cout << "SteerUnfold : flagprior = " << flagprior << endl;
+    cout << "=========================="<< endl;
+
+    Bool_t errorprior=kTRUE;
+    switch (flagprior)
+    {
+    case 1:
+        unfold.SetPriorConstant();
+        break;
+    case 2:
+        errorprior = unfold.SetPriorPower(1.5);
+        break;
+    case 3:
+        if (!hpr)
+        {
+            cout << "Error: No hpr!" << endl;
+            return;
+        }
+        errorprior = unfold.SetPriorInput(*hpr);
+        break;
+    case 4:
+        errorprior = unfold.SetPriorRebin(ha);
+        break;
+    }
+    if (!errorprior)
+    {
+        cout << "MUnfold::SetPrior... : failed.  flagprior = " ;
+        cout << flagprior << endl;
+        return;
+    }
+
+    //..............................................       
+    // calculate the matrix G = M * M(transposed)
+    //           M being the migration matrix
+
+    unfold.CalculateG();
+
+    //..............................................       
+    // call steering routine for the actual unfolding;
+    // the alternatives are :
+
+    // 1  Schmelling : minimize the function Z by Gauss-Newton iteration;
+    //                 the parameters to be fitted are gamma(i) = lambda(i)/w;
+
+    // 2  Tikhonov2 :  regularization term is sum of (2nd deriv.)**2 ;
+    //                 minimization by using MINUIT;
+    //                 the parameters to be fitted are
+    //                 the bin contents of the unfolded distribution
+
+    // 3  Bertero:     minimization by iteration
+    //                 
+
+    UInt_t flagunfold = 1;
+    cout << "SteerUnfold : flagunfold = " << flagunfold << endl;
+    cout << "===========================" << endl;
+
+
+
+    switch (flagunfold)
+    {
+    case 1: // Schmelling
+        cout << "" << endl;
+        cout << "Unfolding algorithm : Schmelling" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Schmelling(hb0))
+            cout << "MUnfold::Schmelling : failed." << endl;
+        break;
+
+    case 2: // Tikhonov2
+        cout << "" << endl;
+        cout << "Unfolding algorithm :   Tikhonov" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Tikhonov2(hb0))
+            cout << "MUnfold::Tikhonov2 : failed." << endl;
+        break;
+
+    case 3: // Bertero
+        cout << "" << endl;
+        cout << "Unfolding algorithm :    Bertero" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Bertero(hb0))
+            cout << "MUnfold::Bertero : failed." << endl;
+        break;
+    }    
+
+
+    //..............................................       
+    // Print fResult
+    unfold.PrintResults();
+
+
+    //..............................................       
+    // Draw the plots
+    unfold.DrawPlots();
+
+    //..............................................       
+    // get unfolded distribution
+    //TMatrixD &Vb    = unfold.GetVb();
+    //TMatrixD &Vbcov = unfold.GetVbcov();
+
+}
+
+//__________________________________________________________________________
+
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// Main program                                                           //
+//                defines the ideal distribution          (hb0)           //
+//                defines the migration matrix            (hMigrat)       //
+//                defines the distribution to be unfolded (hVa)           //
+//                                                                        //
+//                calls member functions of the class MUnfold             //
+//                      to do the unfolding                               //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+void unfold()
+{
+  // -----------------------------------------
+  // migration matrix :
+  //           x corresponds to measured quantity
+  //           y corresponds to true quantity
+
+    //const Int_t  na   =   13;
+    const Int_t  na   =   18;
+    const Axis_t alow = 0.25;
+    const Axis_t aup  = 3.50;
+
+    //const Int_t  nb   =   11;
+    const Int_t  nb   =   22;
+    const Axis_t blow = 0.50;
+    const Axis_t bup  = 3.25;
+
+    TH2D hmig("Migrat", "Migration Matrix", na, alow, aup, nb, blow, bup);
+    hmig.Sumw2();
+
+    // parametrize migration matrix as
+    //     <log10(Eest)>      = a0 + a1*log10(Etrue) + a2*log10(Etrue)**2 
+    //                             + log10(Etrue) 
+    //     RMS( log10(Eest) ) = b0 + b1*log10(Etrue) + b2*log10(Etrue)**2
+    Double_t a0 = 0.0;
+    Double_t a1 = 0.0;
+    Double_t a2 = 0.0;
+
+    Double_t b0 = 0.26;
+    Double_t b1 =-0.054;
+    Double_t b2 = 0.0;
+
+    TF1 f2("f2", "gaus(0)", alow, aup);
+    f2.SetParName(0, "ampl");
+    f2.SetParName(1, "mean");
+    f2.SetParName(2, "sigma");
+
+    // loop over log10(Etrue) bins
+    TAxis &yaxis = *hmig.GetYaxis();
+    for (Int_t j=1; j<=nb; j++)
+    {
+        Double_t yvalue = yaxis.GetBinCenter(j);
+
+        const Double_t mean  = a0 + a1*yvalue + a2*yvalue*yvalue + yvalue;
+        const Double_t sigma = b0 + b1*yvalue + b2*yvalue*yvalue;
+        const Double_t ampl  = 1./ ( sigma*TMath::Sqrt(2.0*TMath::Pi()));
+
+        // gaus(0) is a substitute for [0]*exp( -0.5*( (x-[1])/[2] )**2 )
+        f2.SetParameter(0, ampl);
+        f2.SetParameter(1, mean);
+        f2.SetParameter(2, sigma);
+
+        // fill temporary 1-dim histogram with the function
+        // fill the histogram using
+        //    - either FillRandom
+        //    - or using Freq
+        TH1D htemp("temp", "temp", na, alow, aup);
+        htemp.Sumw2();
+
+        for (Int_t k=0; k<1000000; k++)
+            htemp.Fill(f2.GetRandom());
+
+        // copy it into the migration matrix
+        Double_t sum = 0;
+        for (Int_t i=1; i<=na; i++)
+        {
+            const Stat_t content = htemp.GetBinContent(i);
+            hmig.SetBinContent(i, j, content);
+            sum += content;
+        }
+
+        // normalize migration matrix
+        if (sum==0)
+            continue;
+
+        for (Int_t i=1; i<=na; i++)
+        {
+            const Stat_t content = hmig.GetBinContent(i,j);
+            hmig.SetBinContent(i,j,      content/sum);
+            hmig.SetBinError  (i,j,sqrt(content)/sum);
+        }
+    }
+
+    PrintTH2Content(hmig);
+    PrintTH2Error(hmig);
+
+    // -----------------------------------------
+    // ideal distribution
+
+    TH1D hb0("hb0", "Ideal distribution", nb, blow, bup);
+    hb0.Sumw2();
+
+    // fill histogram with random numbers according to 
+    // an exponential function dN/dE = E^{-gamma}
+    //    or with y = log10(E), E = 10^y :             
+    //                          dN/dy = ln10 * 10^{y*(1-gamma)}     
+    TF1 f1("f1", "pow(10.0, x*(1.0-[0]))", blow, bup);
+    f1.SetParName(0,"gamma");
+    f1.SetParameter(0, 2.7);
+
+    // ntimes is the number of entries
+    for (Int_t k=0; k<10000; k++)
+        hb0.Fill(f1.GetRandom());
+
+    // introduce energy threshold at 50 GeV
+
+    const Double_t  lgEth = 1.70;
+    const Double_t dlgEth = 0.09;
+
+    for (Int_t j=1; j<=nb; j++)
+    {
+        const Double_t lgE = hb0.GetBinCenter(j);
+        const Double_t c   = hb0.GetBinContent(j);
+        const Double_t dc  = hb0.GetBinError(j);
+        const Double_t f   = 1.0 / (1.0 + exp( -(lgE-lgEth)/dlgEth ));
+
+        hb0.SetBinContent(j, f* c);
+        hb0.SetBinError  (j, f*dc);
+    }
+
+    PrintTH1Content(hb0);
+
+    // -----------------------------------------
+    // here the prior distribution can be defined for the call
+    // to SetPriorInput(*hpr)
+    TH1D hpr("hpr", "Prior distribution" , nb, blow, bup);
+    for (Int_t j=1; j<=nb; j++)
+        hpr.SetBinContent(j, 1.0/nb);
+
+    PrintTH1Content(hpr);
+
+    // -----------------------------------------
+    // generate distribution to be unfolded (ha)
+    // by smearing the ideal distribution  (hb0)
+    //
+    TH1D ha("ha", "Distribution to be unfolded", na, alow, aup);
+    ha.Sumw2();
+
+    for (Int_t i=1; i<=na; i++)
+    {
+        Double_t cont = 0;
+        for (Int_t j=1; j<=nb; j++)
+            cont += hmig.GetBinContent(i, j) * hb0.GetBinContent(j);
+
+        ha.SetBinContent(i, cont);
+        ha.SetBinError(i, sqrt(cont));
+    }
+
+    PrintTH1Content(ha);
+    PrintTH1Error(ha);
+
+    // -----------------------------------------
+    // covariance matrix of the distribution ha
+    TH2D hacov("hacov", "Error matrix of distribution ha",
+               na, alow, aup, na, alow, aup);
+
+    for (Int_t i=1; i<=na; i++)
+    {
+        const Double_t content = ha.GetBinContent(i);
+        hacov.SetBinContent(i, i, content<3 ? 3.0 : content);
+    }
+
+    PrintTH2Content(hacov);
+
+    SteerUnfold(ha, hacov, hmig, hmig, hb0, &hpr);
+}
+//========================================================================//
Index: /tags/Mars-V0.9/macros/unfoldCoeff.C
===================================================================
--- /tags/Mars-V0.9/macros/unfoldCoeff.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/unfoldCoeff.C	(revision 9772)
@@ -0,0 +1,200 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Rico, 12/2005 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+// 
+// Example macro on how to calculate coefficients for unfolding and
+// effective areas.
+//.The input is a file of the MC events surviving a certain kind 
+// of analysis. It must contain the branch MEnergyEst with energy 
+// estimator.
+// It must also contain a tree called "OriginalMC" with a branch
+// "MMcEvtBasic" and one entry per original simulated shower used to produce
+// the events in that input file. 
+//
+// The macro performs 2 loops.
+// In the first one the histograms of the original MC events are filled,
+// needed by the coefficient (MMcUnfoldCoeffCalc) and effective area
+// (MMcCollectionAreaCalc) computation
+// In the second one we deal with the survivors and compute effective areas
+// and coefficients
+
+void unfoldCoeff(TString filename="/data/19990101_10002_Q_MCGamTestLZA_E_10_5.root", TString outname="coeff.root")
+{
+
+  ///////////////////////////////////////////////////////////////////
+  // First loop: over all events processed by corsika
+  ///////////////////////////////////////////////////////////////////
+  MParList  parlist;
+  MTaskList tasklist;
+  parlist.AddToList(&tasklist);
+  
+  // theta binning
+  Int_t zbins = 2;
+  TArrayD edges(zbins+1);
+  edges[0] = 0;  
+  edges[1] = 10;
+  edges[2] = 20;
+
+  MBinning binstheta("binsTheta");
+  binstheta.SetEdges(edges);               // Theta [deg]
+  
+  // energy binning
+  const Int_t ebins=10;
+  const Float_t emin=10;
+  const Float_t emax=1000;
+  
+  MBinning binsenergy("binsEnergy");  
+  binsenergy.SetEdgesLog(ebins,emin,emax); // Energy [GeV]
+  
+  parlist.AddToList(&binsenergy);
+  parlist.AddToList(&binstheta);
+  
+  // Tentative spectrum
+  TF1 spectrum("func","pow(x,-1.6)",2.,20000.);
+  
+  // Setup out tasks:
+  MReadMarsFile reader("OriginalMC", filename);
+  reader.DisableAutoScheme();
+  
+  // Create unfolding coefficients object and add it to the parameter list
+  MHMcCollectionArea aeff;
+  MHMcUnfoldCoeff coeff;
+  parlist.AddToList(&coeff);
+  parlist.AddToList(&aeff);
+  
+  // Task which fills the necessary histograms in MHMcCollectionArea
+  MMcUnfoldCoeffCalc coeffcalc;
+  MMcCollectionAreaCalc aeffcalc;
+  
+  coeffcalc.SetSpectrum(&spectrum);
+  aeffcalc.SetSpectrum(&spectrum);
+  
+  tasklist.AddToList(&reader);
+  tasklist.AddToList(&coeffcalc);
+  tasklist.AddToList(&aeffcalc);
+  
+  // set up the loop for the processing
+  MEvtLoop magic;
+  magic.SetParList(&parlist);
+  
+  if (!magic.Eventloop())
+    return;
+  
+  tasklist.PrintStatistics();
+  
+  ///////////////////////////////////////////////////////////////////
+  // Second loop: now fill the histograms of the survivors
+  ///////////////////////////////////////////////////////////////////
+    
+  MParList parlist2;
+  MTaskList tasklist2;
+  parlist2.AddToList(&tasklist2);
+  parlist2.AddToList(&coeff);
+  parlist2.AddToList(&aeff);
+  
+  MReadMarsFile reader2("Events", filename);
+  reader2.DisableAutoScheme();
+  
+  tasklist2.AddToList(&reader2);
+  tasklist2.AddToList(&aeffcalc);
+  tasklist2.AddToList(&coeffcalc);
+  
+  //
+  // set up the loop for the processing
+  //
+  MEvtLoop magic2;
+  magic2.SetParList(&parlist2);
+  
+  if (!magic2.Eventloop())
+    return;
+  
+  tasklist2.PrintStatistics();
+  
+  
+  
+  // Dummy cross-check, see if we recover the original spectrum
+  const UInt_t ncutfiles=1;
+  Char_t* cutName[ncutfiles]={"/data/19990101_10002_Q_MCGamTestLZA_E_10_5.root"};
+  
+  TChain* ccut = new TChain("Events");
+  for(Int_t i = 0; i < ncutfiles; i++)
+    ccut->Add(cutName[i]);
+  //  ccut->SetAlias("logestenergy","log10(MHillas.fSize/0.18/15.)");
+  ccut->SetAlias("logestenergy","log10(MEnergyEst.fEnergy)");
+  ccut->SetAlias("theta","MMcEvt.fTelescopeTheta*180./3.14159");
+  
+  const Double_t logemin = TMath::Log10(emin);
+  const Double_t logemax = TMath::Log10(emax);
+  TH1D* hspec = new TH1D("hspec","Spectrum",ebins,logemin,logemax);
+  hspec->Sumw2();
+  ccut->Draw("logestenergy>>hspec","theta<10","goff");
+  
+  for(Int_t i=0;i<ebins;i++)
+    {
+      const Float_t uncorrval = hspec->GetBinContent(i+1);
+      const Float_t effa   = ((TH2D*) aeff.GetHistCoarse())->GetBinContent(i+1,1);
+      const Float_t unfold = ((TH2D*)coeff.GetHistCoeff())->GetBinContent(i+1,1);
+
+      const Float_t euncorrval = hspec->GetBinError(i+1);
+      const Float_t eeffa   = ((TH2D*) aeff.GetHistCoarse())->GetBinError(i+1,1);
+      const Float_t eunfold = ((TH2D*)coeff.GetHistCoeff())->GetBinError(i+1,1);
+
+      Float_t corrval,ecorrval;
+      if(effa>0)
+	{	  
+	  corrval  = uncorrval*unfold/effa;
+	  if(uncorrval>0 && effa>0 & unfold>0)	    
+	    ecorrval = corrval*TMath::Sqrt(euncorrval/uncorrval*euncorrval/uncorrval+
+					   eeffa/effa*eeffa/effa+
+					   eunfold/unfold*eunfold/unfold);	 
+	  else
+	    ecorrval = 0;
+	}
+      else
+	{
+	  corrval = 0;
+	  ecorrval = 0;
+	}
+      hspec->SetBinContent(i+1,corrval);
+      hspec->SetBinError(i+1,ecorrval);
+    }
+  
+  // Write histogram to a file in case an output
+  // filename has been supplie
+  if (outname.IsNull())
+    return;
+  
+  TFile f(outname, "recreate");
+  if (!f)
+    return;
+  
+  coeff.GetHistAll()->Write();
+  coeff.GetHistWeight()->Write();
+  coeff.GetHistMcE()->Write();
+  coeff.GetHistEstE()->Write();
+  coeff.GetHistCoeff()->Write();
+  aeff.GetHistCoarse()->Write();
+  aeff.Write();
+  hspec->Write();
+}
Index: /tags/Mars-V0.9/macros/weights.C
===================================================================
--- /tags/Mars-V0.9/macros/weights.C	(revision 9772)
+++ /tags/Mars-V0.9/macros/weights.C	(revision 9772)
@@ -0,0 +1,138 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez, 10/2003 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// weights.C
+// =========
+//
+// This macro shows how to use the class MMcWeightEnergySpecCalc
+// to convert the energy spectrum of the MC showers generated with Corsika,
+// to a different one.
+//
+//////////////////////////////////////////////////////////////////////////////
+
+Double_t myfunction(Double_t *x, Double_t *par)
+{
+  Double_t xx = x[0];
+
+  return pow(xx,-2)*exp(-xx/20);  
+}
+
+void weights(TString filename="/up1/data/Magic-MC/CameraAll/Gammas/zbin0/Gamma_zbin0_0_7_1000to1009_w0-4:4:2.root")
+{
+
+    //
+    // PartList
+    //
+    MParList  parlist;
+    MTaskList tasklist;
+    
+    MHMcEnergyImpact h1("h1");
+    MHMcEnergyImpact h2("h2");
+    parlist.AddToList(&h1);
+    parlist.AddToList(&h2);
+
+    MBinning binsenergy("BinningEnergy");
+    binsenergy.SetEdgesLog(100, 1, 1e5);
+    parlist.AddToList(&binsenergy);
+
+    MBinning binsimpact("BinningImpact");
+    binsimpact.SetEdges(100, 0, 450);
+    parlist.AddToList(&binsimpact);
+
+    parlist.AddToList(&tasklist);
+
+
+    //
+    // TaskList
+    //
+    MReadMarsFile reader("Events", filename);
+    reader.EnableBranch("fEnergy");
+    reader.EnableBranch("fImpact");
+
+
+    // -------------------------------------------------------------
+    //
+    // Option 1. Just change the slope of the MC power law spectrum
+    //
+    //MMcWeightEnergySpecCalc wcalc(-2.0);                //<-- Uncomment me
+
+    //
+    // Option 2. A completely differente specturm pass as a TF1 function
+    //           e.g. spectrum with exponential cutoff
+    //
+    //TF1 spec("spectrum","pow(x,[0])*exp(-x/[1])");      //<-- Uncomment me
+    //spec->SetParameter(0,-2.0);                         //<-- Uncomment me
+    //spec->SetParameter(1,50);                           //<-- Uncomment me
+    //MMcWeightEnergySpecCalc wcalc(spec);                //<-- Uncomment me
+ 
+    //
+    // Option 3. A completely differente specturm pass as a cahr*
+    //           
+    //char* func = "pow(x,-2)";                           //<-- Uncomment me
+    //MMcWeightEnergySpecCalc wcalc(func);                //<-- Uncomment me
+
+    //
+    // Option 4. A completely differente specturm pass as a c++ function
+    //     
+    MMcWeightEnergySpecCalc wcalc((void*)myfunction);   //<-- Uncomment me
+    //
+    //-------------------------------------------------------------
+
+    MFillH hfill(&h1,"MMcEvt");
+    MFillH hfill2(&h2,"MMcEvt");
+    hfill2.SetWeight("MWeight");
+
+    tasklist.AddToList(&reader);
+    tasklist.AddToList(&wcalc);
+    tasklist.AddToList(&hfill);
+    tasklist.AddToList(&hfill2);
+
+    //
+    // EventLoop
+    //
+    MEvtLoop magic;
+    magic.SetParList(&parlist);
+
+    if (!magic.Eventloop())
+        return;
+
+    tasklist.PrintStatistics();
+    parlist.Print();
+
+    //
+    // Draw the Results
+    //
+    TCanvas *c = new TCanvas();
+    c->SetLogy();
+    c->SetLogx();
+
+    TH1D* hist1 = (h1->GetHist())->ProjectionX();
+    TH1D* hist2 = (h2->GetHist())->ProjectionX();
+    hist2->SetLineColor(2);
+
+    hist1->DrawClone();
+    hist2->DrawClone("same");    
+}
Index: /tags/Mars-V0.9/magic_t.xpm
===================================================================
--- /tags/Mars-V0.9/magic_t.xpm	(revision 9772)
+++ /tags/Mars-V0.9/magic_t.xpm	(revision 9772)
@@ -0,0 +1,95 @@
+/* XPM */
+static char * magic_t_xpm[] = {
+"14 14 78 1",
+" 	c None",
+".	c #545792",
+"+	c #434988",
+"@	c #434888",
+"#	c #3E4284",
+"$	c #2B3279",
+"%	c #2B3179",
+"&	c #2C3279",
+"*	c #484C8B",
+"=	c #5D6198",
+"-	c #5B5E96",
+";	c #393E81",
+">	c #9193B8",
+",	c #E2E1EA",
+"'	c #FDFDFC",
+")	c #FEFEFC",
+"!	c #F7F6F7",
+"~	c #8E8FB5",
+"{	c #6C6EA0",
+"]	c #ECECF1",
+"^	c #F5DE8A",
+"/	c #F5E192",
+"(	c #FCF7E5",
+"_	c #565A93",
+":	c #65679C",
+"<	c #C8C8DA",
+"[	c #E7E7EE",
+"}	c #F9F9F9",
+"|	c #FEFEFA",
+"1	c #FDFAF0",
+"2	c #F5DF8F",
+"3	c #9395B9",
+"4	c #4D508D",
+"5	c #474B8A",
+"6	c #2C327A",
+"7	c #383E81",
+"8	c #8385B0",
+"9	c #F5EAC1",
+"0	c #F4DF8F",
+"a	c #F8EBB8",
+"b	c #A4A4C3",
+"c	c #ADADC9",
+"d	c #3C4183",
+"e	c #524E63",
+"f	c #A09275",
+"g	c #F6E5A3",
+"h	c #9193B7",
+"i	c #DCDCE8",
+"j	c #7376A5",
+"k	c #524D66",
+"l	c #383A75",
+"m	c #52558E",
+"n	c #EEEDF2",
+"o	c #5F6299",
+"p	c #DDDDE8",
+"q	c #B1B1CB",
+"r	c #ABABC8",
+"s	c #E5E4EC",
+"t	c #2F357B",
+"u	c #AFB0CB",
+"v	c #FCFCFB",
+"w	c #8D8FB5",
+"x	c #6A6DA0",
+"y	c #7779A8",
+"z	c #4F538F",
+"A	c #FAFAFA",
+"B	c #ABACC8",
+"C	c #34397E",
+"D	c #B2B2CC",
+"E	c #2C337A",
+"F	c #8384AF",
+"G	c #7779A7",
+"H	c #BEBDD4",
+"I	c #CDCDDE",
+"J	c #8F91B7",
+"K	c #787AA8",
+"L	c #9F9FC0",
+"M	c #7D7FAB",
+".++++++++++++@",
+"#$$$$$$$$$$$$%",
+"#$$$$$$$$$$$$%",
+"#$$$$$&*=-;$$%",
+"#$$$;>,'))!~$%",
+"#$${]))))^/(_%",
+"#$:<[})|12))3%",
+"#45$67890a))b%",
+"#cd$$$efg)))h%",
+"#ij$$$klmn))o%",
+"#pq$$$$$$r)st%",
+"#uvw&$$$$x)y$%",
+"#zA)Bt$$$CDE$%",
+"FGH))IJKGLMGGG"};
Index: /tags/Mars-V0.9/magiclogo.xpm
===================================================================
--- /tags/Mars-V0.9/magiclogo.xpm	(revision 9772)
+++ /tags/Mars-V0.9/magiclogo.xpm	(revision 9772)
@@ -0,0 +1,342 @@
+/* XPM */
+static char *mag1[] = {
+/* width height ncolors chars_per_pixel */
+"176 87 248 2",
+/* colors */
+"   c #F2D25C",
+" . c #FEFAEC",
+" X c #FEF6EC",
+" o c #A69EC4",
+" O c #F2F6F4",
+" + c #524E8C",
+" @ c #F2F2F4",
+" # c #F2EEF4",
+" $ c #9E92BC",
+" % c #EECA44",
+" & c #EEC644",
+" * c #4E4674",
+" = c #968AB4",
+" - c #363E84",
+" ; c #FEEAC4",
+" : c #363A84",
+" > c #E2DAE4",
+" , c #EAC22C",
+" < c #2E367C",
+" 1 c #827EB4",
+" 2 c #2E327C",
+" 3 c #FAEAAC",
+" 4 c #FAE6AC",
+" 5 c #EAC604",
+" 6 c #7A76AC",
+" 7 c #EAC204",
+" 8 c #7A72AC",
+" 9 c #CAA234",
+" 0 c #C6C2DC",
+" q c #C6BEDC",
+" w c #F6DE94",
+" e c #726EA4",
+" r c #CEA224",
+" t c #726AA4",
+" y c #BEBAD4",
+" u c #BEB6D4",
+" i c #6A669C",
+" p c #6A629C",
+" a c #EABE07",
+" s c #B6B2CC",
+" d c #B6AECC",
+" f c #625A94",
+" g c #F6D26C",
+" h c #826A64",
+" j c #76626C",
+" k c #4E5294",
+" l c #4E4E94",
+" z c #FEFAE4",
+" x c #FEF6E4",
+" c c #F2CA54",
+" v c #9A96C4",
+" b c #464A8C",
+" n c #62526C",
+" m c #46468C",
+" M c #564E74",
+" N c #E6E6F4",
+" B c #3E4684",
+" V c #EEC63C",
+" C c #928EBC",
+" Z c #3E4284",
+" A c #FAEECC",
+" S c #3E3E84",
+" D c #FAE2A1",
+" F c #DEDAEC",
+" G c #FEEABC",
+" H c #8A86B4",
+" J c #363A7C",
+" K c #8A82B4",
+" L c #36367C",
+" P c #EAC224",
+" I c #8A7EB4",
+" U c #EABE24",
+" Y c #D6D2E4",
+" T c #D6CEE4",
+" R c #827EAC",
+" E c #2E3274",
+" W c #827AAC",
+" Q c #2E2E74",
+" ! c #FAE6A4",
+" ~ c #2E2A74",
+" ^ c #F2CE5A",
+" / c #CECADC",
+" ( c #CEC6DC",
+" ) c #7A76A4",
+" _ c #7A72A4",
+" ` c #7A6EA4",
+" ' c #DEB604",
+" ] c #C6BED4",
+" [ c #F6DE8C",
+" { c #F6DA8C",
+" } c #5E5E9C",
+" | c #F2D674",
+".  c #5E5A9C",
+".. c #7E6A6C",
+".X c #7E666C",
+".o c #AAA6CC",
+".O c #AAA2CC",
+".+ c #565694",
+".@ c #F6FAFC",
+".# c #565294",
+".$ c #F6F6FC",
+".% c #F6F2FC",
+".& c #A29EC4",
+".* c #A29AC4",
+".= c #4E4E8C",
+".- c #4E4A8C",
+".; c #EEEEF4",
+".: c #FEF6DC",
+".> c #F2CA4C",
+"., c #EEEAF4",
+".< c #FEF2DC",
+".1 c #EAE6F0",
+".2 c #9A92BC",
+".3 c #464684",
+".4 c #9A8EBC",
+".5 c #464284",
+".6 c #E6E2EC",
+".7 c #E6DEEC",
+".8 c #FEEEC8",
+".9 c #EEC634",
+".0 c #EEC234",
+".q c #FAEAC4",
+".w c #323A84",
+".e c #DEDAE4",
+".r c #DED6E4",
+".t c #2A367C",
+".y c #EAC21C",
+".u c #2A327C",
+".i c #EABE1C",
+".p c #F6E6AC",
+".a c #2E266C",
+".s c #7672AC",
+".d c #E6BE04",
+".f c #E6BA04",
+".g c #D6AE1C",
+".h c #E6B604",
+".j c #C2BEDC",
+".k c #6E6AA4",
+".l c #6E66A4",
+".z c #F6DA84",
+".x c #BAB6D4",
+".c c #F6D684",
+".v c #BAB2D4",
+".b c #66629C",
+".n c #665E9C",
+".m c #866E6C",
+".M c #B2AECC",
+".N c #B2AACC",
+".B c #5E5A94",
+".V c #FEFEFC",
+".C c #F2D26C",
+".Z c #AAA2C4",
+".A c #725E6C",
+".S c #F6F2F4",
+".D c #EECE54",
+".F c #EECA54",
+".G c #FEF2D4",
+".H c #FEEED4",
+".J c #3A4284",
+".K c #3A3E84",
+".L c #3A3A84",
+".P c #EEC62C",
+".I c #FAEEBC",
+".U c #EEC22C",
+".Y c #3E3E74",
+".T c #FAEABC",
+".R c #3E3A74",
+".E c #323A7C",
+".W c #8682B4",
+".Q c #32367C",
+".! c #867EB4",
+".~ c #32327C",
+".^ c #D2CEE4",
+"./ c #2A3274",
+".( c #EABE14",
+".) c #7E7AAC",
+"._ c #2A2E74",
+".` c #7E76AC",
+".' c #2A2A74",
+".] c #F6E2A4",
+".[ c #F6D679",
+".{ c #CAC6DC",
+".} c #CAC2DC",
+".| c #7672A4",
+"X  c #766EA4",
+"X. c #C2BED4",
+"XX c #C2BAD4",
+"Xo c #6E669C",
+"XO c #F6DA7C",
+"X+ c #BAB2CC",
+"X@ c #BAAECC",
+"X# c #92765C",
+"X$ c #9E96C1",
+"X% c #5A5A9C",
+"X& c #4A4689",
+"X* c #5A569C",
+"X= c #FEFEF4",
+"X- c #F2D264",
+"X; c #FEFAF4",
+"X: c #A6A2CC",
+"X> c #F2CE64",
+"X, c #525294",
+"X< c #9E9AC4",
+"X1 c #4A4E8C",
+"X2 c #4A4A8C",
+"X3 c #EECA4C",
+"X4 c #EAEAF4",
+"X5 c #5A4E74",
+"X6 c #9692BC",
+"X7 c #968EBC",
+"X8 c #424284",
+"X9 c #E2E2EC",
+"X0 c #E2DEEC",
+"Xq c #928AB8",
+"Xw c #464274",
+"Xe c #E2DAEC",
+"Xr c #EAC234",
+"Xt c #8E8AB4",
+"Xy c #8E86B4",
+"Xu c #3A3A7C",
+"Xi c #8E82B4",
+"Xp c #EEC224",
+"Xa c #DAD6E4",
+"Xs c #FAEAB4",
+"Xd c #EEBE24",
+"Xf c #DAD2E4",
+"Xg c #FAE6B4",
+"Xh c #323674",
+"Xj c #424687",
+"Xk c #867EAC",
+"Xl c #EABA0C",
+"Xz c #F6E29C",
+"Xx c #2A266C",
+"Xc c #F6DE9C",
+"Xv c #DEB214",
+"Xb c #FADA8C",
+"Xn c #6A66A4",
+"Xm c #D2CADF",
+"XM c #B6B2D4",
+"XN c #9A7A5C",
+"XB c #B6AED4",
+"XV c #625E9C",
+"XC c #AEAACC",
+"XZ c #AEA6CC",
+"XA c #5A5A94",
+"XS c #5A5694",
+"XD c #FAFAFC",
+"XF c #FAF6FC",
+/* pixels */
+".1XX ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ]XX.^.V.V.V.V.V.V.V.V.V.<.G.G x.V.V.V.V.V.V.V.<.G.G.<.V.V.V.V.V.V.V.V.V.V.V.V X.G.G.<X=.V.V.V.V.V.V.V.V.V.V.V.V.V.V X ;.p DXs AX;.V.V.V.V.V.V.V.V.G.G.<.V.V.V.V.V.V.V.V.V.V.V . A ;.8.<X=.V",
+"X<./.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.u.=XD.V.V.V.V.V.V.V.<.(.d.d V.V.V.V.V.V.V.8 a.d.d P ..V.V.V.V.V.V.V.V.V.V.V ^.f.d.f D.V.V.V.V.V.V.V.V.V.V.V.V.G g a.dXl.f.f a.y g.V.V.V.V.V.V.8 a.dXpX;.V.V.V.V.V.V.V.V GX-.i a.d.f.dXd.8",
+"X$._././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././.u././._ QX1XD.V.V.V.V.V.V.V.T.f.fXlXl.I.V.V.V.V.V.z.f.fXl a.G.V.V.V.V.V.V.V.V.V.V x.iXl.d.fX>.V.V.V.V.V.V.V.V.V.V.V |.d.f.f.d.f.f.f.f.f c.V.V.V.V.V.V.q.f.f.yX=.V.V.V.V.V.V.V |.f.f.f.f.f.f.f a.8",
+".*.'._.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u 2._ +.@.V.V.V.V.V.V.V D.f a.d.f.c.V.V.V.V.V.0.f.d.d.f.8.V.V.V.V.V.V.V.V.V.V 4.f.d.d.d.y x.V.V.V.V.V.V.V.V.V g.f.f.d.f.U.D ^X3.y.f |.V.V.V.V.V.V A.d.f.iX;.V.V.V.V.V.VX-.f a.d.f , V.U a.( .",
+".*._.u.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u.u.u.u._ lXD.V.V.V.V.V.V.VXO.f.f.dXl.9.V.V.V.V.8 a.f.f.d.f 4.V.V.V.V.V.V.V.V.V.VX-.f.f.f.f.f D.V.V.V.V.V.V.V.V.z.f.d.f.P.TX;.V.V.V X D.8.V.V.V.V.V.V.8.d.f.iX=.V.V.V.V.VXc.f.f.fXd !X;.VX= z.q.V",
+"X<._._.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u./ 2 Q +.@.V.V.V.V.V.V.V ^.f.d.f.d.d ;.V.V.V.z.f a.d a.fXc.V.V.V.V.V.V.V.V.V.<.(.fXp V.d.fX3.V.V.V.V.V.V.V.G.(.f.f.0.H.V.V.V.V.V.V.V.V.V.V.V.V.V.V.q a.d.yX;.V.V.V.VX=.9Xl.d.( A.V.V.V.V.V.V.V",
+".*._./ 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E.u.u.u._ lXD.V.V.V.V.V.VX; ,Xl a U.f.f.[.V.V.VX3.f aXr.fXl.[.V.V.V.V.V.V.V.V.V w.f.f.[Xc.f.f a.G.V.V.V.V.V.V.[.f.d.d.T.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.qXlXl.(X=.V.V.V.V ;.d.f.f [.V.V.V.V.V.V.V.V",
+"X$._._./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u E.u.u Q +.@.V.V.V.V.V.V x a.d.y.[Xl.f ,X=.V x.(.f &.[.f.f.D.V.V.V.V.V.V.V.V.V &.f.f.T x a.d.f D.V.V.V.V.V.VX3.fXl.UX;.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V A.d.f.yX;.V.V.V.V.p.f.d.f ;.V.V.V.V.V.V.V.V",
+".* Q.u.u.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u.u.u./.u.u._ lXD.V.V.V.V.V.V.8.f.f P.I a.d.f G.V.].f.f | !.fXl.PX=.V.V.V.V.V.V.V A.d.f PX;.V.F.f.fX-.V.V.V.V.VX;Xd.d.f ^.V.V.V.V.V.VX;.T.T.8.V.V.V.V.V.V A.dXl.(X=.V.V.V.V w.f.d.d x.V.V.V.V.V.V.V.V",
+"X$._._./.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u./ 2 2.u Q +.@.V.V.V.V.V.V.].fXl & ..9.f.f |.VX-.f.fXs A.d.f a x.V.V.V.V.V.V.VXO.f.f g.V.V.].f.d.i x.V.V.V.V ..y.f.fX-.V.V.V.V.V.V A.d.f.iX=.V.V.V.V.V A.d.f.yX;.V.V.V.V {.f.f.(X;.V.V.V.V.V.V.V.V",
+"X<._.u 2 2 E E 2 2 E 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E E 2 E.u./.u E.u._ lXD.V.V.V.V.V.V.z.f.f ^.VX>.f a &.< P.f.i x.<.d.fXl.8.V.V.V.V.V.VX; V.f.dXs.V.V x U.f.f D.V.V.V.VX;.y.d.f ^.V.V.V.V.V.V A a.f.iX=.V.V.V.V.V.8.dXl.(X=.V.V.V.V w.f.d a.G.V.V.V.V.V.V.V.V",
+"X$._._.u./.u.u.u./.u./.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u.u.u.u 2.u./.u.u Q +.@.V.V.V.V.V.VX-.f.f.[.VXz.f.f.y.[ a.fX>.VX=.P.f.f D.V.V.V.V.V.V GXl.d.f.[ D w w.9.d.f.F.V.V.V.V.VXr.f.f.i x.V.V.V.V.V ;.f.f.iX;.V.V.V.V.V.q.d.f.yX;.V.V.V.V D.f.f.f 4.V.V.V.V.V.V.V.V",
+".* Q./.u.u././.u.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u././.u./.u.u 2.u._ lXD.V.V.V.V.VX; V.f.f w.V.:.d.f.dXl.d.fXg.V.V ^.f.f.[.V.V.V.V.V.V.C.f.d.f.fXl.f.h.f a.f.d.8.V.V.V.V.[.f.d.f.[.V.V.V.V.V A.dXl.(X=.V.V.V.V.V.8.dXl.(X=.V.V.V.V.I.d.d.fX3.V.V.V.V.V.V.V.V",
+"X$._._.u./.u.u.u././.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u./.u.u./ 2 2./.u.u Q +.@.V.V.V.V.V ..(Xl.f.p.V.V ^.f.d.d.f.y x.V.V |.f.fX>.V.V.V.V.V xXd.f a a.d.( a.y a.d a.f.c.V.V.V.V A.d.d.d.d D.V.V.V.V AXl.d.yX;.V.V.V.V.V.q.d.f.yX;.V.V.V.V XXp.f.f.f.[.V.V.V.V.V.V.V",
+"X<._.u 2 E 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E.u./.u 2./ E.u._ lXD.V.V.V.V.V A.d.f a.8.V.V.].f.d.d.fX>.V.V.V w.f.d V.V.V.V.V.V.].f.f a.8X; . X .X; |.f.d.9X=.V.V.V.V.[.fXl.d a ^ DXs 4 |.fXl.(X=.V.V.V.V.V.8.dXl.(X=.V.V.V.V.VXb.f a.d.f %Xc 4 D.[ V.<",
+"X$._._./.u./.u.u./.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u.u./.u 2.u././.u.u.u Q +.@.V.V.V.V.V 4.f.d.d.<.V.V x a.f a.f D.V.V.V 4.f.f.( x.V.V.V.V ^.f.f c.V.V.V.V.V.VXsXl.f.f.T.V.V.V.V . ^.f.f.f.f.f.d.f.f.d.f.(X;.V.V.V.V.V.q.d.f.yX;.V.V.V.V.VX= ^.f.f aXlXl.f.f.f.f G",
+".* Q.u.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u././.u./.u./.u.u 2.u 2.u._ lXD.V.V.V.V.V [.h.fXpX=.V.V.V ^.f.f.f.8.V.V.V.8Xl.fXl.8.V.V.V.< a.f.f D.V.V.V.V.V.VX=Xp.f.h.C.V.V.V.V.VX=.z.y.d.f.f.f.h.f.d a &X=.V.V.V.V.V ;.d.f.(X=.V.V.V.V.V.V ..[ a.d.f.h.h.f.f.d 4",
+"X$._._.u./.u././.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u.u.u./ 2 2./././.u.u Q +.@.V.V.V.V.V.8 D.p.p.V.V.V.V.G D.p 3X;.V.V.VX= 3 !.p x.V.V.V x.p.p.p ..V.V.V.V.V.V.V.T !.p.T.V.V.V.V.V.V.V x G w.z.z [ w.p.GX=.V.V.V.V.V.V . 4 !Xg.V.V.V.V.V.V.V.V.V.:Xg w.z [ w !.qX;",
+"X<._./ 2 2 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 E 2.u.u./ 2.u 2./ 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._././.u./.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u./.u.u E./.u./.u./.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q.u.u./.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u./.u.u.u.u.u E.u E.u E.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u.u.u././.u.u./.u././.u.u./.u.u./.u.u./.u.u./.u./.u.u./ E 2./.u.u.u./.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X<._./ 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2.u Q Q Q ~.'._._._.u.u 2._._ Q.'.' Q Q 2 E 2 E 2 2 2 2 E 2.u.u./ 2./ 2./ 2.u 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._./.u.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./._.'._.E b.b RX7.OXZ.v u.{ yXBXZ.& = _ l <._._._.u././.u./.u./ 2./.u.u.u./.u.u./.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u._._.'.uX1.!XBX0XD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.rX$.b <.'._.u.u./.u./.u./.u E.u E.u 2./ E.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u._._ <XS.2XfXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXa R :._./.u.u.u 2 2./.u./.u.u./.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X<._.u E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2.u Q Q S H.r.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V TX, Q./././.u 2.u 2./ 2.u E.u 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._.u././.u.u./.u././.u.u./.u././.u.u./.u././.u.u./.u./.u._.' Q l.& @.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.$ W Q 2.u./.u././.u.u./.u./.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q.u.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u./._ JXn.xX;.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VX< 2.u./ 2.u E.u 2./ 2./ 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u._._.l F.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V d E.u.u./.u.u./.u.u.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X<._./ 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 E 2 2 Q ~X,X..V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V X X.V.V.V.VXi._ 2./ E.u E.u E./ 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._./.u././.u.u./.u././.u.u./.u././.u.u./.u./.' - v.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V xXp V.V.V.V.V @.=._.u.u.u.u./.u.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q.u.u.u.u./.u.u./.u.u./.u.u./.u.u./.u.u./.u._XS.e.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V xXsXs.I.8.8.G xX=Xg.fXl.:.V.V.V.V.& Q./ E.u 2./ 2./ E.u._ lXD.V.V.V.V.V.V @.^X4.V.V F.r.V.V.V.V.V.V.VX$.M.V.V.V.V.V.V.V.V.V.V.V.V.V.VX0 Y.V.V.V.,.1.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V u.b.7.V.V.V.V.V.V.V.V.V.V.V.V.*.{.V.V.V.V.V",
+"X$._._./.u./.u.u./.u.u./.u.u./.u.u.u.u./.u Q._ 6XF.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.GXd.f.fXl.f.f.f a a aXl a x.V.V.V.V.6 J.u.u.u./.u./.u.u.u Q +.@.V.V.V.V.V.V.* ~ _.VXD m -.%.V.V.V.V.VXF.K.n.V.V.V.V.V.V.V.V.V.V.V.V.V.@ b./ q.V.VX1Xy.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V v.'.^.V.V.V.V.V.V.V.V.V.V.V.@.K K.V.V.V.V.V",
+"X<._.u 2 2 E E 2 2 E 2 E 2 2 E E E E 2./._.5XZ.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V [.f a.i a 7 a.d.f.f.d.d g.V.V.V.V.V.V _._ E.u 2.u 2.u 2.u._ lXD.V.V.V.V.V.V.)Xx Z #.^ E.uXe.V o.!X$X4.V K.O.VXaX7X7 /.V T.NX$Xe.V.V.V.x._._.`.VX@.Q. .} NXC.vXq /.MXy.{.V.$.ZXyXCXF.V y WXM.V.MXB.2.M.VX<./.2Xq /.V.%.O.! u.V.^XCX$ /X$XX.VXa.2Xq.6",
+"X$._._.u./.u.u.u./.u./.u.u./.u.u.u.u._ ~ t @.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V {.h V .X; X.G.8.8.I.T.G.V.V.V.V.V.V.V (.t.u.u././././.u.u Q +.@.V.V.V.V.V.V } 2._.M.W < < s.VXn R JX .V Z e.$.5 b m 2XaXqXx b Y.V.V.V tX2Xo.QX4 v.tXj o.v Q ZX2 2.- S.K.V I <X* Q.!XX 2.s.M.@.L < k Q.MXZ.'X8 mX&.V e J e JX0Xy.a Z.xX%XqX0.QX8XV.^",
+".* Q./.u.u././.u.u.u./.u.u./.u./.u.u.uXy.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V 4.f a.G.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXFX1 Q.u 2.u 2./ 2.u._ lXD.V.V.V.V.VXF.J t Z fX2X  <Xq.V YX7.KX*.@ S.s d.QX4X0._.2X7 :.;.V.V.V.$ m.W.x.' o.V.5Xy.VXB._.NXC.u.6Xq 2X0 Z v.V.B mX:.' W.,.$ <Xo @.u WX:._XXXZ - > : Z i._.OXq._Xa.VX1X7X7._Xe.V.V",
+"X$._._.u./.u.u.u././.u.u./.u./.u._._.2.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.G.d.f {.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V 6._.u./.u./.u.u.u Q +.@.V.V.V.V.V.6.uX6.` QXh.x <.` Y.KXn SXAXF Z.|.& -XFX0 Q.2Xt k.V.V.V.V Y.u L -._.b.VXj K.VXM._ /XC.E.V =.t.e L o.V.b ZXDX:.~X&X4 <Xy.V._ K.Z.uXeXZ.KX0 2XS.O o., K 2.%.V +.2 =._X4.V.V",
+"X<._.u 2 E 2 E 2 2 E 2 2 2 2 2 2 QXy.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VX;Xr.f ^.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.O E.u E.u E.u E.u._ lXD.V.V.V.V.VXX.'X+.xXx S.;X2.B =.' K L.+.$ SX Xf E i.#.Q.7 W +.V.V.V.VXkX8 d u.n Q T.- m d.v.'.}XZ L.VXy Q @ f Z.|._ K.6X6.3.Y.1 :.+ e 2 /.*._Xa.O L.;X, SX$Xt.;.! E.%.VX2Xq.M ~X*.`.^",
+"X$._._./.u./.u.u./.u.u./././._._X7.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V |.f.( x.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V Y.u./.u.u.u./.u.u Q +.@.V.V.V.V.V 0.n Y.%Xn =.VXi 8 F i.+ tXy.@ ZXn.VX7 bXSXM.V.Z.!.V.V.V.V.!X<.V.V 0X%.jX$ bXy /.bX0 0 e.V d.bXD TX*X2 K.V (.=. .{.@ -.L.+XZ.V u.n.,.} tXDXa pX2XS.1XZ i.@.V WXZ.V K.= k.^",
+".* Q.u.u.u./.u.u./.u.u.u.u./ 2X6.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXs.f.f D.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.$.K./ E.u 2.u 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V #.v 2X .V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V @.u.!.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._././.u.u./.u././.u._._.&.V.O.`.* yX0.$.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V ..P.fX>.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.B._.u.u././.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.{ -X2 T.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.S BXq.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X<._.u 2 E 2 2 E 2 2 E.u Q.!.VXX <.'._ 2 < Z.+ tXqXC.{.,.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V |.fXpX=.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V p._ E.u 2./ 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.$.;.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.S.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._./.u.u./.u.u.u.u Q.+.V.6X8.'.u._./ Q Q Q._.' Q.u.E mXV.) v.x Y @.V.V.V.V.V.V.V.V.V.V.VX= w ^ ^ ^X-X-.[.[ [X3.f.( X.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V W.'.u.u./.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q.u./.u.u./././.u.u.u q.V. ._.u 2.u.u.u.u 2.u.u.u.u Q._._.'.'.u 2 :X,Xn.{.V.V.V.V.V.V.V.V.[.f.f.f.h.h.f.f.h.h.f.h.>.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V H.' E.u E.u E.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._.u.u./.u.u.u./.'Xo.V.).'.u././.u.u.u.u.u./.u./ 2.u.u 2./.u._.u._._ ~ :.x.V.V.V.V.V.VX;.0.f P ^.D VXr ,Xp.y P  .G.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXi.'.u.u.u./.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X<._./ 2 2 E 2 E 2._ ZX4.2._._ 2.u./.u./././ 2./ 2././.u./ 2./.u E.u.u./ E._ 2 RXD.V.V.V.V.VX3.f ^.V.V.VX;X; . .X;.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXy.' E.u 2.u 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._.u./.u./.u.u._.*.r L._ 2./.u 2 E 2 2.u.u 2.u.u.u E.u.u.u./.u 2 E.u.u.u./.'.b @.V.V.V.V {.h UX=.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXy.'.u.u././.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q.u.u.u.u./.u Q.3.V.4 ~.u.u E.u.u./.u E././.u./ 2.u./.u.u 2./.u.u.u./.u 2.u.u.'.+X4.V.V.V.8.dXl.I.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.W.' E.u 2./ 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._./././.u.u._Xq.V q.u././.u.u./.u./.u.u.u./ 2.u./ 2./ E./.u.u./ E.u E.u E.u.u.'XV @.V.VX=.0.h.c.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V t._.u.u./.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X<._.u 2 2 E.u._ LX0.V @.K Q.u./.u.u.u.u E.u 2./.u.u./ 2.u.u E.u.u.u 2.u./.u./ 2.u./.'X,.6.V.V.[Xl %.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXV._ E.u E.u E.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._./.u.u 2 Q.k.V.V.V.+._./ 2 E 2 E./.u E./.u.u E.u.u.u./.u 2 E./.u./.u.u.u./.u.u.u._ m.^.V 4.f a.<.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V l._.u.u.u./.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q.u././.u.u._XB.V.V.V 8._.u.u./.u 2.u.u.u./ 2.u./././ 2./.u.u.u./.u E.u E.u E._ Q Q.u ~.E vX;.U.f w.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V @Xu./ E.u 2.u 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._.u.u./._.J #.V.V.V.* Q._./.u./.u./.u./ 2.u./ 2.u 2.u.u./.u E.u E.u 2._.u.RX5 M *Xu J././XyX-.hX-.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V (.t.u.u.u././.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X<._.u E.u.u ~ i.V.V.V.V Y <.u.u.u./ 2./ 2./.u.u./ 2././ 2.u./.u 2.u./.u.u Q...h a.d.fXvXvXv.g rXl.f g.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V o._./ 2.u 2./ E.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._.u 2.u.'Xq.V.V.V.V.$ b Q 2 E.u.u 2./.u.u E.u./.u.u.u E 2.u././.u.u./.Y ' 7.f a a.d 7 7 7 5 7.g.p.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.!.'.u./.u./.u.u.u Q +.@.V.V.V.V.V.V.V T.!XnX  /.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXDXy u.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V F.KX$.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q./.u E.u.u.x.V.V.V.V.V 8.'.u E./.u.u./ 2.u.u.u./ 2./.u./.u.u.u E.u.u._Xw.f 7.X *X5X5 n.A.X.m jXu.kXF.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXA._.u E.u 2.u 2.u._ lXD.V.V.V.V.V.V.O./.QX, S.&.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V @ Q W.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V >.+XC.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._./.u./ < F.V.V.V.V.V.Z./._.u.u.u./ 2././ 2./ 2./.u./.u E.u E.u E.u.u.u 9 5X#._ Q._./._._._._._.'.+Xa.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.6.L Q.u.u./././.u.u Q +.@.V.V.V.V.V.6 J.=X4.V.V.V.VXMX%. .kX0.V oXn eX*X7Xn.+.v.V YXn.s.+ K.!X,X$.VXDX X%. .M.V.V.V.V.V.V.V #.t.!.V.M.l.kX*X7X .+XX.V FXn. .b T.V @ K. . .  /.VXV.N.V.W eXn.+XC.V.; W.  f.+.o",
+"X<._._.u.u._.K.S.V.V.V.V.V.6 :._ E.u 2./.u.u./ 2.u.u 2.u./.u E.u./.u E.u./._ h 5XN./././././././ 2.u.u._ :XB.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.O././.u 2.u 2./ 2.u._ lXD.V.V.V.V.VXB QXZ.V.V o q.V (.N o./ o.V I.aXy.n._ $X8XS.VXX.'X .|Xx.k 6 S O.@XZX. f.#.V.V.V.V.V.V.V @.t.!.VX7XxXt. .' HXAX*.V.6.o yX8X .VXq._Xa W L.6 @._Xy.V.# Q $ m.#.V 1 2X0.`.a /",
+"X$._.u.u./._X,.V.V.V.V.V.V.VXA._.u 2./.u.u E.u.u././.u E 2.u.u.u.u.u.u E.u./ E MXh./.u.u 2.u.u.u.u.u 2 2 Q E.O.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VX .' 2././.u./.u.u.u Q +.@.V.V.V.V.V s.' v.V.VX& W.VXaXn b._ o.V R <.VXk.#.V.+.+.VX. <.6 o E T u - #.VX$X, :.+.V.V.V.V.V.V.V # 2 R.V =.K.V K <.VXk k.VXF KX2.t.k.VX7._.*.nX*.V.,._Xq.V.+X,.V.  +.VXy <X: f.K.%",
+".*._./ 2 2 Q. .V.V.V.V.V.V.VXy.'./.u.u E.u./.u.u 2./.u./.u././ E.u./.u.u.u./._ Q._.u./.u./ 2 E./ E./.u.u.u._ S.%.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V @X8._ 2.u E.u E.u E.u._ lXD.V.V.V.V.V N LX8 /.%X2 K.VXSX&.x <X:.V W.K.V R.+.VX,X,.VXX JXDX<./ F.v -XD.j._X$ eX,.V.V.V.V.V.V.V @ <.!.VXq Z.VXk.K.V W k.VXq._XBX2Xn.V.{.uXj iXa.V.,._Xq.VX,. .V. X,.V.x._ b.b.}.V",
+"X$ Q.u./.u._XV.V.V.V.V.V.V.V.x./.u.u E.u.u 2./ 2./.u.u.u E.u 2.u E.u.u 2./.u.u.u.u E 2./ 2./.u.u.u.u./.u./._.uXX.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.{.u.u.u.u.u.u.u./.u.u Q +.@.V.V.V.V.V.V.Z < 2.t.' C.V.b < b.uX$.V 1 -.V WXS.V.+.+.V.j LXD.*._.e.vXu.@.{.uXj.LX1XD.V.V.V.V.V.V #.u W.VXq S.V 1.K.V.!.=.V v Q k./ t.V.v./ SX, K.V.;.uXq.VX,XA.VX% +.V o._X8X, ).,",
+"X$ ~._.u./._.b.V.V.V.V.V.V.V.;.K E.u./.u./ 2./.u E.u./.u 2./.u.u E.u./ 2 2.u.u./.u.u.u.u.u.u E.u./.u E 2.u./._ K.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VX$._./ E./ 2./ 2.u 2.u._ lXD.V.V.V.V.V.V.VX0 o v d @.V.7X$ u.} F.VXf y.VXa.{.V 0.{.V.;.xX;X0.v.$X4 uX;.V uX< / 0.V.V.V.V.V.V.V.V.x.r.V FXX.V Y y.VXf.}.V.@XZ.O ( /.VX$.w.2 8 QXX.V.v F.V.} /.V /.}.VXy :.2 W.' $",
+".*._.u./.u._XV.V.V.V.V.V.V.V.V.b.'./.u E.u.u.u.u.u E 2.u./.u.u./.u E.u././.u./.u.u./ E.u././.u./ 2 2.u./ 2 2.'X,.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.B._.u.u.u./.u.u./.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V 8./X$.| Z F.V.V.V.V.V.V.V.V.V.VXo.Q.*.).QXX",
+"X<._.u 2.u.'. .V.V.V.V.V.V.V.VX$.'./.u./.u./ E.u.u./.u.u./ E.u.u.u./.u.u E 2 2./.u.u./ 2 2.u 2./.u.u.u./.u.u./.u T.V.V.V.V.V.V.V.V.V.V.V.V.V.VXX._.u./ 2.u E.u 2./ E.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.,Xq p 1X9.V.V.V.V.V.V.V.V.V.V.V.1 H.b.`.^.V",
+".*._._.u E./ bXF.V.V.V.V.V.V.VXm <.u.u 2./ 2.u././.u 2./ 2.u E.u./ 2.u.u.u.u./ 2 2./ 2.u./.u./.u./.u./.u.u./.u QX6.V.V.V.V.V.V.V.V.V.V.V.V.V.V.k Q./.u././.u.u./.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$ Q./.u.u._ J @.V.V.V.V.V.V.V.$.3 Q.u 2./.u 2.u./.u 2./.u.u E.u./ 2 E././.u./.u.u./.u.u E.u./.u E 2./.u 2./.u ~ p.V.V.V.V.V.V.V.V.V.V.V.V.VXf.Q Q 2.u 2./ 2.u E.u 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".*._._././.u.t (.V.V.V.V.V.V.V.VXk.'._./.u./.u E 2.u./.u.u./.u 2.u./.u.u.u.u.u./ E.u.u./.u.u 2 2.u./ 2 2./ 2./.u.K.,.V.V.V.V.V.V.V.V.V.V.V.V.)._.u.u.u./.u.u./.u./.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".*._._ 2.u.u.u.O.V.V.V.V.V.V.V.V.V.!._._ 2./.u./.u.u./ E.u./.u./.u./ 2 E E.u.u.u./ 2 2./ E./.u./.u./.u.u.u.u./.u.uXB.V.V.V.V.V.V.V.V.V.V.VXe :./.u E.u E.u 2./ 2./ 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._.u.u././.'.`.V.V.V.V.V.V.V.V.V.V I.u./.u./.u 2./ 2.u 2.u./ 2.u.u./.u.u E 2./ 2.u./.u.u.u./.u.u.u././.u E.u./.'.`.V.V.V.V.V.V.V.V.V.V.V.|.'.u./.u./.u.u./.u.u.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".*._._ 2 2 2 QX2XD.V.V.V.V.V.V.V.V.V.V.N L._.u./ 2.u././ 2.u./ 2 E.u.u./.u./.u./.u.u E.u./.u E 2./.u 2./.u E.u./._ mXF.V.V.V.V.V.V.V.V.V.x.u./ 2.u 2./ 2.u E./ 2./ E.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$ Q.u.u./.u./.t /.V.V.V.V.V.V.V.V.V.V.V 0 S ~.u././.u.u.u E.u./.u.u./.u.u.u E.u.u./.u./ 2 2.u./ 2 2./ 2.u.u 2.u.u.u 0.V.V.V.V.V.V.V.VXD + Q 2.u././.u.u./.u.u./.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._./.u./.u.u.'Xy.V.V.V.V.V.V.V.V.V.V.V.V YX2.'.u E.u./.u.u.u./ 2 2 E.u./.u./ 2 2.u 2./.u./.u.u./.u./.u././ 2././.'Xq.V.V.V.V.V.V.V.VX$.'._.u 2.u E.u 2./ 2.u 2.u 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".*._._.u.u.u 2 QX2.@.V.V.V.V.V.V.V.V.V.V.V.V.6.+ ~.u E.u./ E./.u.u./.u E 2.u 2././.u./.u./.u.u./.u.u.u E.u.u./.u 2 QX*.V.V.V.V.V.V.V.6.L.u.u./.u./.u.u./.u././././.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._._ E.u./.u.u QXB.V.V.V.V.V.V.V.V.V.V.V.V.V.;.#.'._.u.u 2 E.u.u./.u./.u./.u.u E.u.u.u E 2.u./ 2./.u E.u.u 2./.u./.EX0.V.V.V.V.V.V H.'./ 2./ 2./ 2.u 2.u 2.u 2./ 2.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".* Q.u.u E.u./.u._X,XD.V.V.V.V.V.V.V.V.V.V.V.V.V.; 8 Q E.u./.u.u./.u.u.u E.u.u./.u.u E E.u.u E 2./ 2.u.u E././.u.u._ ~.*.V.V.V.V.V.M 2 E.u.u.u.u.u./././.u./.u./.u.u.u Q +.@.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X< Q./.u.u.u./.u./._X:.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXq./._.u E 2 E.u./.u.u E 2./ 2.u.u./.u.u./.u./.u./.u 2.u./.u.u.u.' i.V.V.V.V F.K.' E.u E./ 2.u 2.u E.u E.u E.u E.u._ lXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$._.u./ 2 E.u.u.u Q.3 #.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V o < Q.u./.u E 2.u E.u./.u.u././.u.u./.u.u.u E.u.u./.u 2 E./.u./.K #.V.VXDXS Q.u.u./.u.u./.u./.u.u.u.u.u.u./.u.u Q +.@.V.V.V.V.V.V.V.V.^XX.6.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V @Xn u.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V Y.^ Y.^ Y.V.V.V.V.@.l.O.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+"X$.'.u./.u E 2 E.u 2._ K.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.x J._.u.u./.u.u.u.u E.u.u.u E 2.u./ E.u.u 2./.u E.u.u 2./ 2.u.u d.V.V.`.'.u./ 2./ 2.u E.u E./ 2./ E.u 2.u 2.u._ lXD.V.V.V.V.V.V.^.=.u._.b.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.1._.2.V.V.V.V.V.V.V.V.V.V.V.V.V.V.,.K.u 2.u -.;.V.V.V @ Q.!.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V",
+".*._./.u.u.u./.u.u.u._ < T.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V /.K._./.u E.u././.u.u E E.u.u E 2.u 2././ 2.u.u././.u 2.u._.' o.VX$./.u E.u.u.u.u./.u.u.u.u./.u.u.u././.u.u Q +.@.V.V.V.V.V.V.- 2 o y q.V.{ K.v.V.;XXXB q.VXZXyXe.V (.{XC.2 # # <.*.;.N.,.$ oXqXa @.v.,.V.}.}.V.V.{Xq./XqXmX0X7.*.%.%.t R.V TXy.oXD.V.j K.v.VXFXZ.2.,.V.MXy /.VXa y uXqXa.V @.& = F.V",
+".*.'./.u./.u./.u.u.u.u._.l.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXX.L.'.u./ 2 2./ 2.u.u./.u.u./.u./.u.u./ 2./.u.u././.u.u.'.s.V.M 2./.u E.u E./ 2./ 2./ 2.u E.u E.u 2./ 2.u._ lXD.V.V.V.V.V (._ K.V.V.VXZ <X1.tX$ /.t._X7 R : b.=.%. ._ -._X7XD.tX7.+X8 FX% 2.t :.v.K.2.$ <.|.V.V.V.v._.x.V.+.3 J i.S <Xy T :X2.t KXX.uX2X7.V i._.K.{ `.u < :X0Xq.' -.uX,XDXV -Xj ZX9",
+"X< Q._ E.u.u.u E.u E E.u._.`.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V F.B.'.u.u./.u.u././.u.u./.u./.u E.u.u./.u E 2.u.u._._ R.V y 2._.u.u.u./.u.u.u.u./.u.u./.u./.u././.u.u.u Q +.@.V.V.V.V.V.N ~X$.V.V.V f < p.~XS.j.u.M Y 2XjXV._ yXV S.1XV.k.@ : <.LX9X$ Q /.6 2 _.lX2 C._ (.V.V.VX+.u qXX._.b.3.~X0.Q K.|./ p S.5X$ QX X0 0.'X<.V y._.&XD.3Xq.2._Xm.N.KXZ Q.=XS ~.*",
+"X<._.u 2 E E.u E.u.u./ 2.u Q K.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.@X ._.'._._._._.u./.u.u 2.u.u E.u.u 2.u./ 2./.u.'X .V (.K Q 2././ 2./ 2./ E.u E.u 2./ 2.u 2.u E.u E.u._ lXD.V.V.V.V.V (._.k.V.V.V.+Xj o.o 0XX :.$.{ Q i.o.ZX9.+.+.V p p.S J J.Q.rXy._.6.@ < WXZ._ <X%.V.V.V.V.v./ q.N.uX7.oXC.,.E.!.b -X<.o.M #X$ J.-XZ._XB.VXB Q.v.VX2XyX7.u.V.N S o.u 8.o.ZXa",
+"X$ ~._._._._._._._._.'._._.'.'.!.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXD.vXq tX* Z <./ Q._ Q._ Q._._ ~._._._._._ Q.'Xn.VXX.QXx._.' Q._._._._._._._._._._._._._._._._._._._.'.-.@.V.V.V.V.V.V f.aX,XV 1.`._ H I.v ] L.,XD Z.5X7.W.S.# +.V.b p.$.~XyX&X2.o QXS.n._ y.$.K.a.*.V.V.V.VX+.' y.6 L t =.2X4._XyX$.' WXy.* TX6 m S / 2.3.`XZ.Q b t <XaXq._ RXjX, F JX,.2 W.7",
+"XM.#XSX*X*XSX*XSX*. XAXSX%XS.+.+ u.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXFX0 y.*.)XVXSXSX*XAXSXSXSX*XAX%.+Xo @.,Xn.+X*XAX%. X%. XA. X%.BX%.BXA. X%.BXA.BX%.BX%. . .+ 8.V.V.V.V.V.V.VX4.W.#.= =.;.`X1.=XCXa.k @.V /.b m.lXFXi K.VX7X7.$ i 0XXXS.{ o kX,XZ.V.VXq.b.,.V.V.V.VXmXVXm.VXC kX1Xk.@.l.O.V K lX2X$XXX2XV q.VXCX,.+Xa.vX*X2X<.V H.'.-.l T.V.xXAX1XV.7",
+".V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.$.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXDXD.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V I.u.;.V.V.V.V.V.V.V.V",
+".V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.V.VXi < @.V.V.V.V.V.V.V.V"
+};
Index: /tags/Mars-V0.9/manalysis/AnalysisIncl.h
===================================================================
--- /tags/Mars-V0.9/manalysis/AnalysisIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/AnalysisIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/manalysis/AnalysisLinkDef.h
===================================================================
--- /tags/Mars-V0.9/manalysis/AnalysisLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/AnalysisLinkDef.h	(revision 9772)
@@ -0,0 +1,32 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MCameraData+;
+
+#pragma link C++ class MGeomApply+;
+
+#pragma link C++ class MHadronness+;
+
+#pragma link C++ class MCompProbCalc+;
+#pragma link C++ class MMultiDimDistCalc+;
+
+#pragma link C++ class MEnergyEstimate+;
+
+#pragma link C++ class MMatrixLoop+;
+
+#pragma link C++ class MEventRate+;
+#pragma link C++ class MEventRateCalc+;
+
+#pragma link C++ class MParameterI+;
+#pragma link C++ class MParameterD+;
+#pragma link C++ class MParameterDerr+;
+
+#pragma link C++ class MMcTriggerLvl2+;
+#pragma link C++ class MMcTriggerLvl2Calc+;
+
+#pragma link C++ class MMcCalibrationUpdate+;
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MCameraData.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MCameraData.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MCameraData.cc	(revision 9772)
@@ -0,0 +1,415 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 08/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraData
+//
+// This is a generalized class storing camera data. For example the cleaning
+// level for the image cleaning is one possibility.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraData.h"
+
+#include "MMath.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MSigmabar.h"
+
+ClassImp(MCameraData);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MSignalPix object for each pixel in the event
+//
+MCameraData::MCameraData(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCameraData";
+    fTitle = title ? title : "Generalized storage container for camera contents";
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// This is not yet implemented like it should.
+//
+
+void MCameraData::Draw(Option_t* option) 
+{
+    //
+    //   FIXME!!! Here the Draw function of the CamDisplay
+    //   should be called to add the CamDisplay to the Pad.
+    //   The drawing should be done in MCamDisplay::Paint
+    //
+
+    //    MGeomCam *geom = fType ? new MGeomCamMagic : new MGeomCamCT1;
+    //    MCamDisplay *disp = new MCamDisplay(geom);
+    //    delete geom;
+    //    disp->DrawPhotNum(this);
+}
+*/
+
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event
+// as the ratio between the measured photons and the pedestal rms.
+// In order to do the image cleaning on average in the same photon flux
+// (reconstructed photons per pixel area) for the inner and outer pixels,
+// a correction factor is applied to the outer pixels (see TDAS 02-14).
+// The correction factor assumes the ideal case that the pedestal rms 
+// scales with the inverse square root of the pixel area.
+//
+// FIXME: Should the check noise<=0 be replaced by MBadPixels?
+//
+void MCameraData::CalcCleaningLevel(const MSignalCam &evt, const MPedPhotCam &cam,
+                                    const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // Reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    const Int_t entries = evt.GetNumPixels();
+
+    // calculate cleaning levels
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &pix = evt[idx];
+
+        const Float_t noise = cam[idx].GetRms();
+
+        if (noise<=0) // fData[idx]=0, fValidity[idx]=0
+            continue;
+
+        //
+	// We calculate a correction factor which accounts for the 
+	// fact that pixels have different size (see TDAS 02-14).
+	//
+        fData[idx] = pix.GetNumPhotons() * geom.GetPixRatioSqrt(idx) / noise;
+        fValidity[idx] = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event
+// as the ratio between the measured photons and the pedestal rms.
+// In order to do the image cleaning on average in the same photon flux
+// (reconstructed photons per pixel area) for the inner and outer pixels,
+// a correction factor is applied to the outer pixels (see TDAS 02-14).
+// The correction factor takes the actual average pedestal RMS of the
+// inner and outer pixels into account.
+//
+// FIXME: Should the check noise<=0 be replaced by MBadPixels?
+//
+void MCameraData::CalcCleaningLevel2(const MSignalCam &evt, const MPedPhotCam &cam,
+                                     const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of rms with area index 0
+    const Float_t anoise0 = cam.GetArea(0).GetRms();
+    if (anoise0<=0)
+        return;
+
+    // calculate cleaning levels
+    const Int_t entries = evt.GetNumPixels();
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &pix = evt[idx];
+
+        const Float_t noise = cam[idx].GetRms();
+
+        if (noise<=0) // fData[idx]=0, fValidity[idx]=0
+            continue;
+
+        //
+	// We calculate a correction factor which accounts for the 
+	// fact that pixels have different size (see TDAS 02-14).
+	// We also take into account that the RMS does not scale 
+	// with the square root of the pixel area.
+	// 
+        const UInt_t  aidx  = geom[idx].GetAidx();
+        const Float_t ratio = cam.GetArea(aidx).GetRms()/anoise0;
+
+        fData[idx] = pix.GetNumPhotons() * geom.GetPixRatio(idx) * ratio / noise;
+        fValidity[idx] = 1;
+    }
+}
+
+
+void MCameraData::CalcCleaningLevel(const MSignalCam &evt, const MSigmabar &sgb,
+                                    const MGeomCam &geom)
+{
+    CalcCleaningLevel(evt, sgb.GetSigmabarInner(), geom);
+}
+
+void MCameraData::CalcCleaningLevel(const MSignalCam &evt, Double_t noise,
+                                    const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of noise
+    if (noise<=0)
+        return;
+
+    // calculate cleaning levels
+    const Int_t entries = evt.GetNumPixels();
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &pix = evt[idx];
+
+        //
+	// We calculate a correction factor which accounts for the 
+	// fact that pixels have different size (see TDAS 02-14).
+	//
+        fData[idx] = pix.GetNumPhotons() * geom.GetPixRatio(idx) / noise;
+        fValidity[idx] = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event
+// as the ratio between the reconstructed number of photons per area of an
+// inner pixel and the average pedestal RMS of the inner pixels (democratic
+// image cleaning, see TDAS 02-14).
+//
+// FIXME: Should the check noise<=0 be replaced by MBadPixels?
+//
+void MCameraData::CalcCleaningLevelDemocratic(const MSignalCam &evt, const MPedPhotCam &cam,
+                                              const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of rms with area index 0
+    const Float_t noise0 = cam.GetArea(0).GetRms();
+    if (noise0<=0)
+        return;
+
+    // calculate cleaning levels
+    const Int_t entries = evt.GetNumPixels();
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &pix = evt[idx];
+
+        const Float_t noise = cam[idx].GetRms();
+
+        if (noise<=0)
+            continue;
+
+        //
+        // We calculate a correction factor which accounts for the
+        // fact that pixels have different size (see TDAS 02-14).
+        //
+        fData[idx] = pix.GetNumPhotons() * geom.GetPixRatio(idx) / noise0;
+        fValidity[idx] = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event.
+// The level is the probability that the signal is a real signal (taking
+// the signal height and the fluctuation of the background into account)
+// times one minus the probability that the signal is a background
+// fluctuation (calculated from the time spread of arrival times
+// around the pixel with the highest signal)
+//
+// FIXME: Should the check noise<=0 be replaced by MBadPixels?
+//
+void MCameraData::CalcCleaningProbability(const MSignalCam &evt, const MPedPhotCam &pcam,
+                                          const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // Reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    // check validity of noise
+    const Float_t anoise0 = pcam.GetArea(0).GetRms();
+    if (anoise0<=0)
+        return;
+
+    const Int_t entries = evt.GetNumPixels();
+
+    // Find pixel with max signal
+    Int_t maxidx = 0;
+
+    // Find pixel entry with maximum signal
+    for (Int_t i=0; i<entries; i++)
+    {
+        const Double_t s0 = evt[i].GetNumPhotons()      * geom.GetPixRatio(i);
+        const Double_t s1 = evt[maxidx].GetNumPhotons() * geom.GetPixRatio(maxidx);
+        if (s0>s1)
+            maxidx = i;
+    }
+
+    const Double_t timemean = evt[maxidx].GetArrivalTime();
+    const Double_t timerms  = 0.75; //[slices] rms time spread around highest pixel
+
+    // calculate cleaning levels
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &spix = evt[idx];
+
+        const Float_t rms = pcam[idx].GetRms();
+        if (rms<=0) // fData[idx]=0, fValidity[idx]=0
+            continue;
+
+        fValidity[idx]=1;
+
+        // get signal and arrival time
+        const UInt_t  aidx     = geom[idx].GetAidx();
+        const Float_t ratio    = pcam.GetArea(aidx).GetRms()/anoise0;
+
+        const Double_t signal  = spix.GetNumPhotons() * geom.GetPixRatio(idx) * ratio / rms;
+        const Double_t time    = evt[idx].GetArrivalTime();
+
+        // if signal<0 the probability is equal 0
+        if (signal<0)
+            continue;
+
+        // Just for convinience for easy readybility
+        const Double_t means   = 0;
+        const Double_t meant   = timemean;
+
+        const Double_t sigmas  = rms;
+        const Double_t sigmat  = timerms;
+
+        // Get probabilities
+        const Double_t psignal = MMath::GaussProb(signal, sigmas, means);
+        const Double_t pbckgnd = MMath::GaussProb(time,   sigmat, meant);
+
+        // Set probability
+        fData[idx]     = psignal*(1-pbckgnd);
+        fValidity[idx] = 1;
+
+        // Make sure, that we don't run into trouble because of
+        // a little numerical uncertanty
+        if (fData[idx]>1)
+            fData[idx]=1;
+        if (fData[idx]<0)
+            fData[idx]=0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Function to calculate the cleaning level for all pixels in a given event.
+// The level is the absolute number of photons times the area-ratio.
+//
+void MCameraData::CalcCleaningAbsolute(const MSignalCam &evt, const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    // Reset arrays
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    const Int_t entries = evt.GetNumPixels();
+
+    // calculate cleaning levels
+    for (Int_t idx=0; idx<entries; idx++)
+    {
+        const MSignalPix &spix = evt[idx];
+
+        // Set probability
+        fData[idx]     = spix.GetNumPhotons() * geom.GetPixRatio(idx);
+        fValidity[idx] = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the contents of the pixel.
+//
+Bool_t MCameraData::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx<0 || idx>=fData.GetSize())
+        return kFALSE;
+
+    val = fData[idx];
+    return fValidity[idx];
+}
+
+void MCameraData::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MCameraData::DrawPixelContent - not available." << endl;
+}
+
+void MCameraData::Print(Option_t *o) const
+{
+    MParContainer::Print(o);
+    *fLog << "Size = " << fData.GetSize() << endl;
+    for (int i=0; i<fData.GetSize(); i++)
+        cout << i << ": " << fData[i] << endl;
+}
Index: /tags/Mars-V0.9/manalysis/MCameraData.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MCameraData.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MCameraData.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MCameraData
+#define MARS_MCameraData
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class MGeomCam;
+class MSigmabar;
+class MSignalCam;
+class MPedPhotCam;
+
+class MCameraData : public MParContainer, public MCamEvent
+{
+private:
+    TArrayD fData;  //
+    TArrayC fValidity;
+
+public:
+    MCameraData(const char *name=NULL, const char *title=NULL);
+    ~MCameraData() { }
+
+    UInt_t GetNumPixels() const { return fData.GetSize(); }
+
+    void CalcCleaningLevel(const MSignalCam &evt, const MPedPhotCam &fCam,
+                           const MGeomCam &geom);
+    void CalcCleaningLevel(const MSignalCam &evt, const MSigmabar &sgb,
+                           const MGeomCam &geom);
+    void CalcCleaningLevel(const MSignalCam &evt, Double_t noise,
+                           const MGeomCam &geom);
+    void CalcCleaningLevel2(const MSignalCam &evt, const MPedPhotCam &fCam,
+                            const MGeomCam &geom);
+    void CalcCleaningLevelDemocratic(const MSignalCam &evt, const MPedPhotCam &cam,
+                                     const MGeomCam &geom);
+    void CalcCleaningProbability(const MSignalCam &evt, const MPedPhotCam &pcam,
+                                 const MGeomCam &geom);
+    void CalcCleaningAbsolute(const MSignalCam &evt, const MGeomCam &geom);
+
+    const TArrayD &GetData() const { return fData; }
+    const TArrayC &GetValidity() const  { return fValidity; }
+
+    Double_t operator[](int i) { return fData[i]; }
+
+    void Print(Option_t *o="") const;
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MCameraData, 1) // Generalized storage class for camera data
+};
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MCompProbCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MCompProbCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MCompProbCalc.cc	(revision 9772)
@@ -0,0 +1,166 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz, 5/2002 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCompProbCalc
+//
+// FIXME: Use A huge matrix to evaluate variable bins instead of a
+// histogram
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MCompProbCalc.h"
+
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MDataChain.h"
+
+#include "MHCompProb.h"
+#include "MHadronness.h"
+
+ClassImp(MCompProbCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MCompProbCalc::MCompProbCalc(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MCompProbCalc";
+    fTitle = title ? title : "Composite Probabilities Loop 1/2";
+
+    fData = new TList;
+    fData->SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor
+//
+MCompProbCalc::~MCompProbCalc()
+{
+    delete fData;
+}
+
+// --------------------------------------------------------------------------
+//
+// Needs:
+//  - MHCompProb
+//  - all data values which were used to build the MHCompProb
+//  - MHadronness
+//
+Int_t MCompProbCalc::PreProcess(MParList *plist)
+{
+    MHCompProb *p = (MHCompProb*)plist->FindObject("MHCompProb");
+    if (!p)
+    {
+        *fLog << err << dbginf << "MHCompProb not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHistVar = p->GetHistVar();
+    if (fHistVar->GetSize()==0)
+    {
+        *fLog << err << dbginf << "No Entries in MHCompProb::fHistVar... aborting." << endl;
+        return kFALSE;
+    }
+
+    const TList *rules = p->GetRules();
+    if (rules->GetSize()==0)
+    {
+        *fLog << err << dbginf << "No Entries in MHCompProb::fRules... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fHistVar->GetSize() != rules->GetSize())
+    {
+        *fLog << err << dbginf << "Number of rules doesn't match number of var.bin histograms.. aborting." << endl;
+        return kFALSE;
+    }
+
+    TIter Next(rules);
+    TObject *data=NULL;
+    while ((data=Next()))
+    {
+        MDataChain *chain = new MDataChain(data->GetName());
+        if (!chain->PreProcess(plist))
+        {
+            delete chain;
+            return kFALSE;
+        }
+        fData->Add(chain);
+    }
+
+    fHadronness = (MHadronness*)plist->FindCreateObj("MHadronness");
+    if (!fHadronness)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the hadroness (composite propability)
+//  - For each data member search the bin corresponding to the data value.
+//  - The value describes with which probability this value corresponds to
+//    a hadron
+//  - For all data members multiply the probabilities.
+//  - For normalization take the n-th root of the result.
+//  - This is the hadroness stored in the MHadronness container
+//
+Int_t MCompProbCalc::Process()
+{
+    Double_t p = 1;
+
+    TIter NextH(fHistVar);
+    TIter NextD(fData);
+
+    TH1D *hist=NULL;
+
+    Int_t n = 0;
+
+    while ((hist=(TH1D*)NextH()))
+    {
+        MData *data = (MData*)NextD();
+
+        Int_t ibin = hist->FindBin(data->GetValue());
+
+        p *= hist->GetBinContent(ibin) / hist->GetEntries();
+        n++;
+    }
+
+    fHadronness->SetHadronness(pow(p, 1./n));
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/manalysis/MCompProbCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MCompProbCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MCompProbCalc.h	(revision 9772)
@@ -0,0 +1,33 @@
+#ifndef MARS_MCompProbCalc
+#define MARS_MCompProbCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcEvt;
+class MParList;
+class MHadronness;
+
+class MCompProbCalc : public MTask
+{
+private:
+    MHadronness *fHadronness; //! Output container (Hadronness)
+
+    TList *fData;           //! List of MDataChains to be used
+    TList *fHistVar;        //! List of variable bin size histograms
+
+    void Fill(TList &list);
+    void SetBinningHistVar();
+
+public:
+    MCompProbCalc(const char *name=NULL, const char *title=NULL);
+    ~MCompProbCalc();
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+    ClassDef(MCompProbCalc, 1) // Task to calculate composite probabilities
+};
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MEnergyEst.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MEnergyEst.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEnergyEst.cc	(revision 9772)
@@ -0,0 +1,57 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  1/2002 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Wolfgang Wittek 1/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MEnergyEst                                                              //
+//                                                                         //
+// Storage Container for the estimated energy                              //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MEnergyEst.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEnergyEst);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MEnergyEst::MEnergyEst(const char *name, const char *title) : fEnergy(0)
+{
+    fName  = name  ? name  : "MEnergyEst";
+    fTitle = title ? title : "Storage container for the estimated energy [GeV]";
+}
+
+void MEnergyEst::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ": Eest = " << (int)fEnergy << "GeV \t Ir = " << (int)(fImpact/100) << "m" << endl;
+}
+
Index: /tags/Mars-V0.9/manalysis/MEnergyEst.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MEnergyEst.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEnergyEst.h	(revision 9772)
@@ -0,0 +1,28 @@
+#ifndef MARS_MEnergyEst
+#define MARS_MEnergyEst
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MEnergyEst : public MParContainer
+{
+private:
+    Double_t fEnergy; // [GeV] Estimated Energy
+    Double_t fImpact; // [cm]  Estimated Impact
+
+public:
+    MEnergyEst(const char *name=NULL, const char *title=NULL);
+
+    void SetEnergy(Double_t e) { fEnergy = e; }
+    void SetImpact(Double_t i) { fImpact = i; }
+    Double_t GetEnergy() const { return fEnergy; }
+    Double_t GetImpact() const { return fImpact; }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MEnergyEst, 1) // Storage Container for the estimated Energy
+};
+
+#endif
+
Index: /tags/Mars-V0.9/manalysis/MEnergyEstParam.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MEnergyEstParam.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEnergyEstParam.cc	(revision 9772)
@@ -0,0 +1,376 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  9/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MEnergyEstParam                                                         //
+//                                                                         //
+// Task to estimate the energy using a parametrization.                    //
+// Make sure, that all source dependant containers are based on the same   //
+// set of basic hillas parameters                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MEnergyEstParam.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+#include "MHMatrix.h"
+#include "MHillasSrc.h"
+#include "MEnergyEst.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEnergyEstParam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize the coefficients with (nonsense) values
+//
+void MEnergyEstParam::InitCoefficients()
+{
+    fA.Set(5);
+    fA[0] =  -2539; // [cm]
+    fA[1] =    900; // [cm]
+    fA[2] =   17.5; // [cm]
+    fA[3] =  0.006;
+    fA[4] =   58.3;
+
+    /*
+      fA[0] =   39.667402; // [cm]
+      fA[1] =  143.081912; // [cm]
+      fA[2] = -395.501677; // [cm]
+      fA[3] =    0.006193;
+      fA[4] =    0;
+    */
+
+    fB.Set(7);
+    fB[0] =   -8.69;    // [GeV]
+    fB[1] =  -0.069;    // [GeV]
+    fB[2] =   0.000655; // [GeV]
+    fB[3] =   0.0326;   // [GeV]
+    fB[4] = 0.000225;   // [GeV]
+    fB[5] =  4.13e-8;   // [GeV]
+    fB[6] =     0.05;
+
+    /*
+      fB[0] =   45.037867; // [GeV]
+      fB[1] =    0.087222; // [GeV]
+      fB[2] =   -0.208065; // [GeV/cm]
+      fB[3] =   78.164942; // [GeV]
+      fB[4] = -159.361283; // [GeV]
+      fB[5] =   -0.130455; // [GeV/cm]
+      fB[6] =    0.051139;
+    */
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Give the name of the parameter container (MHillas)
+// storing width, length and size (Default="MHillas").
+// For the Zenith Angle MMcEvt.fTheta is used.
+//
+MEnergyEstParam::MEnergyEstParam(const char *hillas, const char *name, const char *title)
+   : fMatrix(NULL)
+{
+    fName  = name  ? name  : "MEnergyEstParam";
+    fTitle = title ? title : "Task to estimate the energy";
+
+    fHillasName = hillas;
+
+    fPairs     = new TList;
+    fEnergy    = new TList;
+    fHillasSrc = new TList;
+
+    fPairs->SetOwner();
+
+    InitCoefficients();
+
+    AddToBranchList("MMcEvt.fTelescopeTheta");
+    AddToBranchList(fHillasName+".fSize");
+    AddToBranchList(fHillasName+".fWidth");
+    AddToBranchList(fHillasName+".fLength");
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Destructor.
+//
+MEnergyEstParam::~MEnergyEstParam()
+{
+    delete fPairs;
+    delete fEnergy;
+    delete fHillasSrc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for all necessary parameter containers.
+//
+Int_t MEnergyEstParam::PreProcess(MParList *plist)
+{
+    if (!fMatrix)
+    {
+        fHillas = (MHillas*)plist->FindObject(fHillasName, "MHillas");
+        if (!fHillas)
+        {
+            *fLog << err << dbginf << fHillasName << " [MHillas] not found... aborting." << endl;
+            return kFALSE;
+        }
+
+        fMc = (MMcEvt*)plist->FindObject("MMcEvt");
+        if (!fMc)
+        {
+            *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    TObject *obj = NULL;
+    TIter Next(fPairs);
+
+    while ((obj=Next()))
+    {
+        TObject *o = plist->FindCreateObj(obj->GetTitle(), "MEnergyEst");
+        if (!o)
+            return kFALSE;
+
+        if (!fEnergy->FindObject(obj->GetTitle()))
+            fEnergy->Add(o);
+
+        if (fMatrix)
+            continue;
+
+        o = plist->FindObject(obj->GetName(), "MHillasSrc");
+        if (!o)
+        {
+            *fLog << err << dbginf << obj->GetName() << " not found... aborting." << endl;
+            return kFALSE;
+        }
+        fHillasSrc->Add(o);
+    }
+
+   return kTRUE;    
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the five coefficients for the estimation of the impact parameter.
+// Argument must ba a TArrayD of size 5.
+//
+void MEnergyEstParam::SetCoeffA(const TArrayD &arr)
+{
+    if (arr.GetSize() != fA.GetSize())
+    {
+        *fLog << err << dbginf << "Error - Wrong number of coefficients!" << endl;
+        return;
+    }
+
+    fA = arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the seven coefficients for the estimation of the energy.
+// Argument must ba a TArrayD of size 7.
+//
+void MEnergyEstParam::SetCoeffB(const TArrayD &arr)
+{
+    if (arr.GetSize() != fB.GetSize())
+    {
+        *fLog << err << dbginf << "Error - Wrong number of coefficients!" << endl;
+        return;
+    }
+
+    fB = arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the twelve coefficients for the estimation of impact and energy.
+// Argument must ba a TArrayD of size 12.
+//
+void MEnergyEstParam::SetCoeff(const TArrayD &arr)
+{
+    if (arr.GetSize() != fA.GetSize()+fB.GetSize())
+    {
+        *fLog << err << dbginf << "Error - Wrong number of coefficients!" << endl;
+        return;
+    }
+
+    fA = TArrayD(fA.GetSize(), arr.GetArray());
+    fB = TArrayD(fB.GetSize(), arr.GetArray() + fA.GetSize());
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MEnergyEstParam::GetVal(Int_t i) const
+{
+    return (*fMatrix)[fMap[i]];
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam::Process
+// will take the values from the matrix instead of the containers.
+//
+void MEnergyEstParam::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MMcEvt.fTelescopeTheta");
+    fMap[1] = fMatrix->AddColumn(fHillasName+".fWidth");
+    fMap[2] = fMatrix->AddColumn(fHillasName+".fLength");
+    fMap[3] = fMatrix->AddColumn(fHillasName+".fSize");
+
+    Int_t col = 4;
+    TIter Next(fPairs);
+    TObject *o = NULL;
+    while ((o=Next()))
+        fMap[col++] = fMatrix->AddColumn(TString(o->GetName())+".fDist");
+}
+
+void MEnergyEstParam::StopMapping()
+{
+    fMatrix = NULL; 
+    fPairs->Clear();
+    fHillasSrc->Clear();
+    fEnergy->Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a pair of input/output containers.
+//   eg. Add("MHillasSrc", "MEnergyEst");
+// Useful if you want to estimate the stuff for the source and antisource
+//
+void MEnergyEstParam::Add(const TString hillas, const TString energy)
+{
+    fPairs->Add(new TNamed(hillas, energy));
+
+    AddToBranchList(hillas+".fDist");
+}
+
+void MEnergyEstParam::Print(Option_t *opt) const
+{
+    for (int i=0; i<fA.GetSize(); i++)
+        *fLog << all << "fA[" << i << "]=" << const_cast<TArrayD&>(fA)[i] << endl;
+    for (int i=0; i<fB.GetSize(); i++)
+        *fLog << all << "fB[" << i << "]=" << const_cast<TArrayD&>(fB)[i] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Estimates the impact parameter and energy using a parameterization
+//  (see code)
+//
+Int_t MEnergyEstParam::Process()
+{
+    const Double_t theta  = fMatrix ? GetVal(0) : fMc->GetTelescopeTheta();
+    const Double_t width  = fMatrix ? GetVal(1) : fHillas->GetWidth();
+    const Double_t length = fMatrix ? GetVal(2) : fHillas->GetLength();
+    const Double_t size   = fMatrix ? GetVal(3) : fHillas->GetSize();
+
+    const Double_t k   = 1./cos(theta);
+    const Double_t k2  = k*k;
+
+    const Double_t i0 = k * (fA[3]*k+1)/(fA[3]+1);
+    const Double_t i1 = fA[0] + fA[2]*width;
+
+
+    const Double_t e0 = k2 * (fB[6]*k2+1)/(fB[6]+1);
+
+    /* MY PARAM */
+    //const Double_t e1 = fB[0] + fB[1]*size + fB[3]*length + fB[4]*size*width;
+    //const Double_t e2 = fB[2] + fB[5]*size*width;
+
+    /* MARCOS */
+    /*
+    const Double_t e1 = fB[0] + fB[1]*size + fB[3]*length + fB[4]*size*length;
+    const Double_t e2 = fB[2] + fB[5]*length;
+    */
+
+    /* DANIEL */
+    const Double_t e1 = fB[0] + fB[1]*size/(length*width) + 
+      fB[3]*length + fB[4]*size/width;
+
+    const Double_t e2 = fB[2] + fB[5]*length;
+
+    TIter NextH(fHillasSrc);
+    TIter NextE(fEnergy);
+
+    Int_t col = 4;
+
+    while (1)
+    {
+        MEnergyEst *est = (MEnergyEst*)NextE();
+        if (!est)
+            break;
+
+        const Double_t dist = fMatrix ? GetVal(col++) : ((MHillasSrc*)NextH())->GetDist();
+
+        /* DANIEL - MARCOS */
+        const Double_t ir = i0 * (i1 + fA[1]*dist); // [cm]
+        Double_t er = e0 * (e1 + e2*ir);       // [GeV]
+
+        /* THOMAS BRETZ */
+        // if (width==0) return kCONTINUE;
+        // const Double_t ir = i0 * (i1 + dist*(fA[1]/width + fA[4]/log10(size))); // [cm]
+        //Double_t er = e0 * (e1 + e2*ir);      // [GeV]
+
+        /* MKA */
+        //Double_t er = e0 * (fB[0] + fB[1]*size/width + fB[2]*ir /*+ d*leakage*/);
+
+        if (width==0)
+            return kCONTINUE;
+
+        if (TMath::IsNaN(ir))
+            *fLog << all << theta << " " << width << " " << length << " " << size << " " << dist << endl;
+        if (TMath::IsNaN(er))
+        {
+            *fLog << all << theta << " " << width << " " << length << " " << size << " " << dist << endl;
+            er = 0;
+        }
+
+	est->SetEnergy(er);
+        est->SetImpact(ir);
+        est->SetReadyToSave();
+    }
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/manalysis/MEnergyEstParam.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MEnergyEstParam.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEnergyEstParam.h	(revision 9772)
@@ -0,0 +1,69 @@
+#ifndef MARS_MEnergyEstParam
+#define MARS_MEnergyEstParam
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MHillasSrc;
+class MEnergyEst;
+class MHillas;
+class MMcEvt;
+class MHMatrix;
+
+class MEnergyEstParam : public MTask
+{
+private:
+    Int_t     fMap[100]; // FIXME!
+
+    MHMatrix *fMatrix;
+
+    TList    *fPairs;
+
+    TList    *fHillasSrc;
+    TList    *fEnergy;
+
+    MHillas  *fHillas;
+    TString   fHillasName;
+
+    TArrayD   fA;
+    TArrayD   fB;
+
+    MMcEvt   *fMc;
+
+    void InitCoefficients();
+
+    Double_t GetVal(Int_t i) const;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MEnergyEstParam(const char *hil="MHillas", const char *name=NULL, const char *title=NULL);
+    ~MEnergyEstParam();
+
+    void Add(const TString hillas, const TString energy="MEnergyEst");
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping();
+
+    Int_t GetNumCoeff() const { return fA.GetSize()+fB.GetSize(); }
+
+    void SetCoeff(const TArrayD &arr);
+    void SetCoeffA(const TArrayD &arr);
+    void SetCoeffB(const TArrayD &arr);
+
+    void SetVariables(const TArrayD &arr) { SetCoeff(arr); }
+
+    Double_t GetCoeff(Int_t i) { return i<fA.GetSize()? fA[i] : fB[i-fA.GetSize()]; }
+
+    void Print(Option_t *o=NULL) const;
+
+    ClassDef(MEnergyEstParam, 0) // Task to estimate the energy
+};
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MEnergyEstParamDanielMkn421.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MEnergyEstParamDanielMkn421.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEnergyEstParamDanielMkn421.cc	(revision 9772)
@@ -0,0 +1,401 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  9/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Wolfgang Wittek  7/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MEnergyEstParamDanielMkn421                                             //
+//                                                                         //
+// Task to estimate the energy using a parametrization.                    //
+// Make sure, that all source dependant containers are based on the same   //
+// set of basic hillas parameters                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MEnergyEstParamDanielMkn421.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MMcEvt.hxx"
+#include "MHMatrix.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MEnergyEst.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEnergyEstParamDanielMkn421);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize the coefficients with Daniel's values
+// for Mkn421
+//
+//
+void MEnergyEstParamDanielMkn421::InitCoefficients()
+{
+    // parameters for the impact parameter
+    fA.Set(4);
+    fA[0] = 12.0322;  // 
+    fA[1] =  8.29911; // 
+    fA[2] = 73.0699;  // 
+    fA[3] =  0.311375;
+
+
+    // parameters for the energy
+    fB.Set(6);
+    fB[0] =  1.23138;    // 
+    fB[1] =  0.00276497; // 
+    fB[2] = -0.0110667;  // 
+    fB[3] =  7.47538;    // 
+    fB[4] = -1.25619;    // 
+    fB[5] =  0.627699;   // 
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Give the name of the parameter container (MHillas)
+// storing width, length and size (Default="MHillas").
+// For the Zenith Angle MMcEvt.fTheta is used.
+//
+MEnergyEstParamDanielMkn421::MEnergyEstParamDanielMkn421(const char *hillas, const char *name, const char *title)
+   : fMatrix(NULL)
+{
+    fName  = name  ? name  : "MEnergyEstParamDanielMkn421";
+    fTitle = title ? title : "Task to estimate the energy (Daniel Mkn421)";
+
+    fHillasName = hillas;
+
+    fPairs     = new TList;
+    fEnergy    = new TList;
+    fHillasSrc = new TList;
+
+    fPairs->SetOwner();
+
+    InitCoefficients();
+
+    AddToBranchList("MMcEvt.fTelescopeTheta");
+    AddToBranchList(fHillasName+".fSize");
+    AddToBranchList(fHillasName+".fWidth");
+    AddToBranchList(fHillasName+".fLength");
+    AddToBranchList("MNewImagePar.fLeakage1");
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Destructor.
+//
+MEnergyEstParamDanielMkn421::~MEnergyEstParamDanielMkn421()
+{
+    delete fPairs;
+    delete fEnergy;
+    delete fHillasSrc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for all necessary parameter containers.
+//
+Int_t MEnergyEstParamDanielMkn421::PreProcess(MParList *plist)
+{
+    const MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+    {
+        *fLog << warn << dbginf << "No Camera Geometry available" << endl;
+        return kFALSE;
+    }
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+    }
+
+
+    if (!fMatrix)
+    {
+        fHillas = (MHillas*)plist->FindObject(fHillasName, "MHillas");
+        if (!fHillas)
+        {
+            *fLog << err << dbginf << fHillasName << " [MHillas] not found... aborting." << endl;
+            return kFALSE;
+        }
+
+        fMc = (MMcEvt*)plist->FindObject("MMcEvt");
+        if (!fMc)
+        {
+            *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+            return kFALSE;
+        }
+
+        fNewImagePar = (MNewImagePar*)plist->FindObject("MNewImagePar");
+        if (!fNewImagePar)
+        {
+            *fLog << err << dbginf << " object 'MNewImagePar' not found... aborting." << endl;
+            return kFALSE;
+        }
+
+    }
+
+
+    TObject *obj = NULL;
+    TIter Next(fPairs);
+
+    while ((obj=Next()))
+    {
+        TObject *o = plist->FindCreateObj(obj->GetTitle(), "MEnergyEst");
+        if (!o)
+            return kFALSE;
+
+        if (!fEnergy->FindObject(obj->GetTitle()))
+            fEnergy->Add(o);
+
+        if (fMatrix)
+            continue;
+
+        o = plist->FindObject(obj->GetName(), "MHillasSrc");
+        if (!o)
+        {
+            *fLog << err << dbginf << obj->GetName() << " not found... aborting." << endl;
+            return kFALSE;
+        }
+        fHillasSrc->Add(o);
+    }
+
+   return kTRUE;    
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the five coefficients for the estimation of the impact parameter.
+// Argument must ba a TArrayD of size 5.
+//
+void MEnergyEstParamDanielMkn421::SetCoeffA(const TArrayD &arr)
+{
+    if (arr.GetSize() != fA.GetSize())
+    {
+        *fLog << err << dbginf << "Error - Wrong number of coefficients!" << endl;
+        return;
+    }
+
+    fA = arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the seven coefficients for the estimation of the energy.
+// Argument must ba a TArrayD of size 7.
+//
+void MEnergyEstParamDanielMkn421::SetCoeffB(const TArrayD &arr)
+{
+    if (arr.GetSize() != fB.GetSize())
+    {
+        *fLog << err << dbginf << "Error - Wrong number of coefficients!" << endl;
+        return;
+    }
+
+    fB = arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the twelve coefficients for the estimation of impact and energy.
+// Argument must ba a TArrayD of size 12.
+//
+void MEnergyEstParamDanielMkn421::SetCoeff(const TArrayD &arr)
+{
+    if (arr.GetSize() != fA.GetSize()+fB.GetSize())
+    {
+        *fLog << err << dbginf << "Error - Wrong number of coefficients!" << endl;
+        return;
+    }
+
+    fA = TArrayD(fA.GetSize(), arr.GetArray());
+    fB = TArrayD(fB.GetSize(), arr.GetArray() + fA.GetSize());
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MEnergyEstParamDanielMkn421::GetVal(Int_t i) const
+{
+    return (*fMatrix)[fMap[i]];
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParamDanielMkn421::Process
+// will take the values from the matrix instead of the containers.
+//
+void MEnergyEstParamDanielMkn421::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MMcEvt.fTelescopeTheta");
+    fMap[1] = fMatrix->AddColumn(fHillasName+".fWidth");
+    fMap[2] = fMatrix->AddColumn(fHillasName+".fLength");
+    fMap[3] = fMatrix->AddColumn(fHillasName+".fSize");
+    fMap[4] = fMatrix->AddColumn("MNewImagePar.fLeakage1");
+
+    Int_t col = 5;
+    TIter Next(fPairs);
+    TObject *o = NULL;
+    while ((o=Next()))
+        fMap[col++] = fMatrix->AddColumn(TString(o->GetName())+".fDist");
+}
+
+void MEnergyEstParamDanielMkn421::StopMapping()
+{
+    fMatrix = NULL; 
+    fPairs->Clear();
+    fHillasSrc->Clear();
+    fEnergy->Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a pair of input/output containers.
+//   eg. Add("MHillasSrc", "MEnergyEst");
+// Useful if you want to estimate the stuff for the source and antisource
+//
+void MEnergyEstParamDanielMkn421::Add(const TString hillas, const TString energy)
+{
+    fPairs->Add(new TNamed(hillas, energy));
+
+    AddToBranchList(hillas+".fDist");
+}
+
+void MEnergyEstParamDanielMkn421::Print(Option_t *opt) const
+{
+    for (int i=0; i<fA.GetSize(); i++)
+        *fLog << all << "fA[" << i << "]=" << const_cast<TArrayD&>(fA)[i] << endl;
+    for (int i=0; i<fB.GetSize(); i++)
+        *fLog << all << "fB[" << i << "]=" << const_cast<TArrayD&>(fB)[i] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Estimates the impact parameter and energy using a parameterization
+//  (see code)
+//
+Int_t MEnergyEstParamDanielMkn421::Process()
+{
+
+    const Double_t theta  = fMatrix ? GetVal(0) : fMc->GetTelescopeTheta();
+
+    Double_t width  = fMatrix ? GetVal(1) : fHillas->GetWidth();
+    width *= fMm2Deg;
+
+    Double_t length = fMatrix ? GetVal(2) : fHillas->GetLength();
+    length *= fMm2Deg;
+
+    const Double_t size   = fMatrix ? GetVal(3) : fHillas->GetSize();
+    Double_t leakage= fMatrix ? GetVal(4) : fNewImagePar->GetLeakage1();
+    leakage = (leakage-0.1)<0. ? 0. : leakage-0.1;
+
+    const Double_t k   = 1./cos(theta);
+    const Double_t k2  = k*k;
+
+    const Double_t i0 = k  * (fA[3]*k + 1);
+    const Double_t e0 = k2 * (fB[4]*k + fB[5]*k2+1);
+
+    TIter NextH(fHillasSrc);
+    TIter NextE(fEnergy);
+
+    Int_t col = 5;
+
+    while (1)
+    {
+        MEnergyEst *est = (MEnergyEst*)NextE();
+        if (!est)
+            break;
+
+        Double_t dist = fMatrix ? GetVal(col++) : ((MHillasSrc*)NextH())->GetDist();
+        dist *= fMm2Deg;
+
+        Double_t ir = i0 * (fA[0] + fA[1]*dist/width + fA[2]*leakage); 
+        Double_t er = e0 * (fB[0] + fB[1]*size/width + fB[2]*ir + fB[3]*leakage);
+        er *= 1000.0;  // conversion to GeV
+
+        if (ir<0.  || er<0.)
+	{
+          ir = 0.;
+          er = 0.;
+	}
+
+        if (width==0)
+            return kCONTINUE;
+
+        if (TMath::IsNaN(ir))
+            *fLog << all << theta << " " << width << " " << length << " " << size << " " << dist << endl;
+        if (TMath::IsNaN(er))
+        {
+            *fLog << all << theta << " " << width << " " << length << " " << size << " " << dist << endl;
+            er = 0;
+        }
+
+	est->SetEnergy(er);
+        est->SetImpact(ir);
+        est->SetReadyToSave();
+
+    }
+
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MEnergyEstParamDanielMkn421.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MEnergyEstParamDanielMkn421.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEnergyEstParamDanielMkn421.h	(revision 9772)
@@ -0,0 +1,79 @@
+#ifndef MARS_MEnergyEstParamDanielMkn421
+#define MARS_MEnergyEstParamDanielMkn421
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MHillasSrc;
+class MEnergyEst;
+class MHillas;
+class MNewImagePar;
+class MMcEvt;
+class MHMatrix;
+
+class MEnergyEstParamDanielMkn421 : public MTask
+{
+private:
+    Int_t     fMap[100]; // FIXME!
+
+    MHMatrix *fMatrix;
+
+    TList    *fPairs;
+
+    TList    *fHillasSrc;
+    TList    *fEnergy;
+
+    MHillas       *fHillas;
+    MNewImagePar  *fNewImagePar;
+
+    TString   fHillasName;
+
+    TArrayD   fA;
+    TArrayD   fB;
+
+    MMcEvt   *fMc;
+
+    void InitCoefficients();
+
+    Double_t GetVal(Int_t i) const;
+    Double_t fMm2Deg;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MEnergyEstParamDanielMkn421(const char *hil="MHillas", const char *name=NULL, const char *title=NULL);
+    ~MEnergyEstParamDanielMkn421();
+
+    void Add(const TString hillas, const TString energy="MEnergyEst");
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping();
+
+    Int_t GetNumCoeff() const { return fA.GetSize()+fB.GetSize(); }
+
+    void SetCoeff(const TArrayD &arr);
+    void SetCoeffA(const TArrayD &arr);
+    void SetCoeffB(const TArrayD &arr);
+
+    Double_t GetCoeff(Int_t i) { return i<fA.GetSize()? fA[i] : fB[i-fA.GetSize()]; }
+
+    void Print(Option_t *o=NULL) const;
+
+    ClassDef(MEnergyEstParamDanielMkn421, 0) // Task to estimate the energy
+};
+
+#endif
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MEnergyEstimate.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MEnergyEstimate.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEnergyEstimate.cc	(revision 9772)
@@ -0,0 +1,175 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  1/2002 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Wolfgang Wittek 1/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MEnergyEstimate
+//
+// Task to estimate the energy by a rule, eg:
+//
+// MEnergyEstimate est;
+// est.SetRule("0.5 + (1.1*MHillas.fLength) + (2.2*MHillasSrc.fDist) + (3.3*MHillas.fSize) +"
+//             "(4.4*MHillas.fSize*MHillas.fLength) + (5.5*MHillasSrc.fDist*MHillas.fLength)");
+//
+// For description of rules, see MDataChain.
+//
+// The default rule is "MMcEvt.fEnergy"
+//
+// Output:
+//   MEnergyEst
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MEnergyEstimate.h"
+
+#include "MParList.h"
+
+#include "MDataChain.h"
+#include "MEnergyEst.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEnergyEstimate);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Initialize fData with default rule "MMcEvt.fEnergy"
+//
+MEnergyEstimate::MEnergyEstimate(const char *name, const char *title)
+    : fData(0), fEnergy(0)
+{
+    fName  = name  ? name  : "MEnergyEstimate";
+    fTitle = title ? title : "Task to estimate the energy by a rule";
+
+    fData = new MDataChain("MMcEvt.fEnergy");
+}
+
+// --------------------------------------------------------------------------
+//
+// delete fData
+//
+MEnergyEstimate::~MEnergyEstimate()
+{
+    delete fData;
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fData. Initialize a new MDataChain with rule.
+// Returns if fData->IsValid()
+//
+Bool_t MEnergyEstimate::SetRule(const char *rule)
+{
+    delete fData;
+    fData = new MDataChain(rule);
+
+    return fData->IsValid();
+}
+
+// --------------------------------------------------------------------------
+//
+// Forwards SetVariables to fData to allow optimizations.
+//
+void MEnergyEstimate::SetVariables(const TArrayD &arr)
+{
+    fData->SetVariables(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate "MEnergyEst"
+// PreProcess fData.
+//
+Int_t MEnergyEstimate::PreProcess(MParList *plist)
+{
+    fEnergy = (MEnergyEst*)plist->FindCreateObj("MEnergyEst");
+    if (!fEnergy)
+        return kFALSE;
+
+    if (!fData->PreProcess(plist))
+        return kFALSE;
+
+    *fLog << inf << "Rule for energy estimation: " << fData->GetRule() << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get value from fData and set it to fEnergy. SetReadyToSave for fEnergy.
+// Return kCONTINUE if value is NaN (Not a Number)
+//
+Int_t MEnergyEstimate::Process()
+{
+    const Double_t val = fData->GetValue();
+    if (TMath::IsNaN(val))
+        return kCONTINUE;
+
+    fEnergy->SetEnergy(val);
+    fEnergy->SetReadyToSave();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup filters.
+// Avoid trailing 0's!
+//
+// Example:
+//   test.C:
+//     MEnergyEstimate est("MyEstimator");
+//
+//   test.rc:
+//     MyEstimator.Rule: {0} + {1}
+//     MyEstimator.0: log10(MHillas.fSize)
+//     MyEstimator.1: 5.5
+//
+// For more details see MDataChain::ReadEnv
+//
+Int_t MEnergyEstimate::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    MDataChain *f = new MDataChain;
+    f->SetName(fName);
+
+    const Bool_t rc = f->ReadEnv(env, prefix, print);
+    if (rc!=kTRUE)
+    {
+        delete f;
+        return rc;
+    }
+
+    delete fData;
+    fData = f;
+
+    if (!fData->IsValid())
+    {
+        *fLog << err << "MEnergyEst::ReadEnv - ERROR: Inavlid rule from resource file." << endl;
+        return kERROR;
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysis/MEnergyEstimate.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MEnergyEstimate.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEnergyEstimate.h	(revision 9772)
@@ -0,0 +1,34 @@
+#ifndef MARS_MEnergyEstimate
+#define MARS_MEnergyEstimate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MData;
+class MEnergyEst;
+
+class MEnergyEstimate : public MTask
+{
+private:
+    MData      *fData;    //->
+    MEnergyEst *fEnergy;
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+public:
+    MEnergyEstimate(const char *name=NULL, const char *title=NULL);
+    ~MEnergyEstimate();
+
+    Bool_t SetRule(const char *rule);
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+    void SetVariables(const TArrayD &);
+
+    ClassDef(MEnergyEstimate, 0) // Task to estimate the energy by a rule
+};
+
+#endif
+
Index: /tags/Mars-V0.9/manalysis/MEventRate.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MEventRate.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEventRate.cc	(revision 9772)
@@ -0,0 +1,63 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MEventRate
+//
+// Storage Container for the event rate.
+//
+//    rate = Number of events / time in which the events were recorded
+//       r = N / t
+//       s = t / N  = 1 / r    mean time interval between consecutive events
+//
+//    for an exponential distribution of the time differences d between
+//    consecutive events:
+//
+//       s = <d>
+//       sigma(d)     = <d> = s
+//       delta(s)     = sigma(d) /sqrt(N) = s / sqrt(N)
+//       delta(s) / s = 1 / sqrt(N)
+//
+//       delta(r) / r = delta(s) / s = 1 / sqrt(N)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MEventRate.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEventRate);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MEventRate::MEventRate(const char *name, const char *title) : fRate(-1)
+{
+    fName  = name  ? name  : "MEventRate";
+    fTitle = title ? title : "Storage container for the event rate [Hz]";
+}
Index: /tags/Mars-V0.9/manalysis/MEventRate.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MEventRate.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEventRate.h	(revision 9772)
@@ -0,0 +1,26 @@
+#ifndef MARS_MEventRate
+#define MARS_MEventRate
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MEventRate : public MParContainer
+{
+private:
+    Double_t fRate;      // [Hz] Event rate
+    UInt_t   fNumEvents; // Number of events correspoding to this rate
+
+public:
+    MEventRate(const char *name=NULL, const char *title=NULL);
+
+    void SetRate(Double_t r, UInt_t n) { fRate = r; fNumEvents = n; }
+    Double_t GetRate() const { return fRate; }
+    Double_t GetError() const { return TMath::Sqrt(1./fNumEvents); }
+    UInt_t GetNumEvents() const { return fNumEvents; }
+
+    ClassDef(MEventRate, 1) // Storage Container for the event rate
+};
+
+#endif
+
Index: /tags/Mars-V0.9/manalysis/MEventRateCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MEventRateCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEventRateCalc.cc	(revision 9772)
@@ -0,0 +1,238 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MEventRateCalc
+//
+//  This task calculates the event rates from the event times and numbers.
+//
+//  The algorithm is explained in Process()
+//
+//
+//    rate = Number of events / time in which the events were recorded
+//       r = N / t
+//       s = t / N  = 1 / r    mean time interval between consecutive events
+//
+//    for an exponential distribution of the time differences d between
+//    consecutive events:
+//
+//       s = <d>
+//       sigma(d)     = <d> = s
+//       delta(s)     = sigma(d) /sqrt(N) = s / sqrt(N)
+//       delta(s) / s = 1 / sqrt(N)
+//
+//       delta(r) / r = delta(s) / s = 1 / sqrt(N)
+//
+//
+//  In addition the difference between the event time of the current event
+//  and the last event is written into a MParameterD calles MTimeDiff.
+//
+//
+//  Input Containers:
+//    MTime
+//
+//  Output Containers:
+//    MEventRate
+//    MTimeDiff [MParameterD]
+//    MTimeRate [MTime] (missing)
+//
+//  FIXME: For convinience we could implement a mode which always takes
+//         n events to calculate the event rate and sets the corresponding
+//         time. This mode could be used to UPADTE files with the event
+//         rate.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MEventRateCalc.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MTime.h"
+#include "MEventRate.h"
+#include "MParameters.h"
+
+ClassImp(MEventRateCalc);
+
+using namespace std;
+
+const TString MEventRateCalc::gsDefName  = "MEventRateCalc";
+const TString MEventRateCalc::gsDefTitle = "Calculate event rate";
+
+const TString MEventRateCalc::gsNameTime      = "MTime";
+const TString MEventRateCalc::gsNameEventRate = "MEventRate";
+const TString MEventRateCalc::gsNameTimeDiff  = "MTimeDiff";
+const TString MEventRateCalc::gsNameTimeRate  = "MTimeRate";
+
+const Int_t MEventRateCalc::gsNumEvents = 1000;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MEventRateCalc::MEventRateCalc(const char *name, const char *title)
+    : fNameEventRate(gsNameEventRate), fNameTime(gsNameTime),
+    fNameTimeRate(gsNameTimeRate), fNameTimeDiff(gsNameTimeDiff),
+    fTimes(gsNumEvents)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//   MTime
+//
+// The PreProcess searches for the following input containers:
+//   MEventRate
+//
+// Reset all times in the buffer
+//
+Int_t MEventRateCalc::PreProcess(MParList *pList)
+{
+    fTime = (MTime*)pList->FindObject(AddSerialNumber(fNameTime), "MTime");
+    if (!fTime)
+    {
+        *fLog << err << AddSerialNumber(fNameTime) << " [MTime] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRate = (MEventRate*)pList->FindCreateObj("MEventRate", AddSerialNumber(fNameEventRate));
+    if (!fRate)
+        return kFALSE;
+
+    fTimeRate = (MTime*)pList->FindCreateObj("MTime", AddSerialNumber(fNameTimeRate));
+    if (!fTimeRate)
+        return kFALSE;
+
+    fTimeDiff = (MParameterD*)pList->FindCreateObj("MParameterD", AddSerialNumber(fNameTimeDiff));
+    if (!fTimeDiff)
+        return kFALSE;
+
+    fTimes.Reset();
+
+    return kTRUE;
+}
+
+Bool_t MEventRateCalc::ReInit(MParList *pList)
+{
+    fNumFirstEvent = GetNumExecutions();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the events rate as (t1-t0)/n while t1 is the n-th event after
+// t0. If there are not yet enough events in the buffer n is the number
+// of available events. Otherwise the number setup in SetNumEvents.
+//
+Int_t MEventRateCalc::Process()
+{
+    const ULong_t exec = GetNumExecutions()-1;
+
+    //*fLog << all << fNumFirstEvent << " " << exec << endl;
+
+    // Calculate the rate
+    const UInt_t n = fTimes.GetSize();
+
+    // Get the positon in the ring-buffer
+    const UInt_t n1 = exec;
+    const UInt_t n2 = exec>=n ? exec+1 : 0;
+
+    // Store the current event time
+    fTimes[n1%n] = *fTime;
+
+    // Get the number of events
+    const UInt_t cnt = n1<n2 ? n : n1-n2;
+
+    // Calculate the rate
+    const Double_t rate = (Double_t)cnt/(fTimes[n1%n]-fTimes[n2%n]);
+
+    // Store the time difference between two consecutive events
+    fTimeDiff->SetVal(exec==0 ? -1 : fTimes[n1%n] - fTimes[(n1+n-1)%n]);
+    fTimeDiff->SetReadyToSave();
+
+    // Make sure, that the beginning of data-takeing (open
+    // a new file) doesn't effect the rate too much
+    if (exec<fNumFirstEvent+n)
+    {
+        fRate->SetRate(-1, 0);
+        return kTRUE;
+    }
+
+    // Store the rate
+    fRate->SetRate(exec>1?rate:0, cnt);
+    fRate->SetReadyToSave();
+
+    // Store the corresponding time
+    if (exec==fNumFirstEvent+n)
+        fTimeRate->SetMean(fTimes[n2%n], fTimes[n2%n]);
+    else
+        fTimeRate->SetMean(fTimes[n1%n], fTimes[n2%n]);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MEventRateCalc::StreamPrimitive(ofstream &out) const
+{
+    out << "   MEventRateCalc " << GetUniqueName() << "(";
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "\"" <<fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+    if (fTimes.GetSize()!=gsNumEvents)
+        out << "   " << GetUniqueName() << ".SetNumEvents(" << fTimes.GetSize() << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MEventRateCalc.NumEvents: 1000
+//
+Int_t MEventRateCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumEvents", print))
+    {
+        rc = kTRUE;
+        SetNumEvents(GetEnvValue(env, prefix, "NumEvents", fTimes.GetSize()));
+    }
+
+    return rc;
+}
Index: /tags/Mars-V0.9/manalysis/MEventRateCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MEventRateCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MEventRateCalc.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MEventRateCalc
+#define MARS_MEventRateCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MTime;
+class MEventRate;
+class MParameterD;
+
+class MEventRateCalc : public MTask
+{
+private:
+    static const TString gsDefName;       //! Default name of container
+    static const TString gsDefTitle;      //! Default title of container
+
+    static const TString gsNameEventRate; //! default name of rate container
+    static const TString gsNameTime;      //! Default name of time container
+    static const TString gsNameTimeDiff;  //! default name of time-diff container
+    static const TString gsNameTimeRate;  //! default name of time-rate container
+
+    static const Int_t gsNumEvents;       //! Default number of events
+
+
+    MTime       *fTime;       //! pointer to event time
+    MTime       *fTimeRate;   //! pointer to time of event rate
+    MEventRate  *fRate;       //! pointer to rate storage container
+    MParameterD *fTimeDiff;   //! Difference of time between two consecutive events
+
+    TString fNameEventRate;  // name of event rate container
+    TString fNameTime;       // name of time container
+    TString fNameTimeRate;   // name of event rate time container
+    TString fNameTimeDiff;   // name of time-diff container
+
+    TArrayD  fTimes;         //! internal array to store the last n event times
+
+    Int_t fNumFirstEvent;    //! Number of first event in file
+
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+    void  StreamPrimitive(ofstream &out) const;
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MEventRateCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetNumEvents(ULong_t num) { fTimes.Set(num); }
+
+    void SetNameEventRate(const char *name) { fNameEventRate = name; }
+    void SetNameTime(const char *name)      { fNameTime = name; }
+    void SetNameTimeDiff(const char *name)  { fNameTimeDiff = name; }
+    void SetNameTimeRate(const char *name)  { fNameTimeRate = name; }
+
+    ClassDef(MEventRateCalc, 1)// Task to calculate event rates
+};
+ 
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MFiltercutsCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MFiltercutsCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MFiltercutsCalc.cc	(revision 9772)
@@ -0,0 +1,179 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 05/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFiltercutsCalc
+//
+// This class sets the hadronness to 0.25 if the evaluttion of the cuts
+// is true, otherwise 0.75.
+//
+// The cuts can be set by AddCut (see there for mor information)
+//
+// All single cuts are linked with a logical and ('&&')
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFiltercutsCalc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MF.h"
+#include "MFDataChain.h"
+#include "MParList.h"
+#include "MFilterList.h"
+#include "MHadronness.h"
+
+ClassImp(MFiltercutsCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates the filter list.
+//
+MFiltercutsCalc::MFiltercutsCalc(const char *name, const char *title)
+    : fHadronnessName("MHadronness")
+{
+    fName  = name  ? name  : "MFiltercutsCalc";
+    fTitle = title ? title : "Class to evaluate the Supercuts";
+
+    fList = new MFilterList;
+    fList->SetOwner();
+    fList->SetBit(kMustCleanup);
+
+    gROOT->GetListOfCleanups()->Add(fList);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filter list.
+//
+MFiltercutsCalc::~MFiltercutsCalc()
+{
+    delete fList;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the filter to the list. Set the rule as its name.
+//
+void MFiltercutsCalc::AddToList(MFilter *f)
+{
+    f->SetName(f->GetRule());
+    f->SetBit(kMustCleanup);
+    fList->AddToList(f);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the rule of the list.
+//
+void MFiltercutsCalc::Print(Option_t *opt) const
+{
+    *fLog << all << underline << GetDescriptor() << ":" << endl;
+    fList->Print();
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// There is MUCH space for speed improvement!
+// Add MF(lo<name && name<up) to the filter list (&&),
+// for more details see MF::MF(), too.
+//
+void MFiltercutsCalc::AddCut(const char *name, Double_t lo, Double_t up)
+{
+    AddToList(new MFDataChain(name, '>', lo));
+    AddToList(new MFDataChain(name, '<', up));
+}
+
+// --------------------------------------------------------------------------
+//
+// There is MUCH space for speed improvement!
+// Add MF(fabs(name)<val) to the filter list (&&),
+// for more details see MF::MF(), too.
+//
+void MFiltercutsCalc::AddCut(const char *name, Double_t val)
+{
+    AddToList(new MFDataChain(Form("fabs(%s)", name), '<', val));
+}
+
+// --------------------------------------------------------------------------
+//
+// There is MUCH space for speed improvement!
+// Add 'cut' as MF(cut) to the filter list (&&),
+// for more details see MF::MF(), too.
+//
+void MFiltercutsCalc::AddCut(const char *cut)
+{
+    AddToList(new MF(cut));
+}
+
+// --------------------------------------------------------------------------
+//
+// There is MUCH space for speed improvement!
+// Add cut to filter list (&&), for more details see MF::MF(), too.
+//
+void MFiltercutsCalc::AddCut(MFilter *f)
+{
+    AddToList(f);
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for fHadronnessName [MHadronness] to store the hadronness in
+// there. PreProcess the filter list.
+//
+Int_t MFiltercutsCalc::PreProcess(MParList *pList)
+{
+    if (!fList->PreProcess(pList))
+        return kFALSE;
+
+    fHadronness = (MHadronness*)pList->FindCreateObj("MHadronness", fHadronnessName);
+    if (!fHadronness)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluate the filter list. if the Expression is true set hadronness to
+// 0.25, otherwise to 0.75.
+//
+Int_t MFiltercutsCalc::Process()
+{
+    if (!fList->Process())
+        return kFALSE;
+
+    if (fList->IsExpressionTrue())
+        fHadronness->SetHadronness(0.25);
+    else
+        fHadronness->SetHadronness(0.75);
+
+    fHadronness->SetReadyToSave();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysis/MFiltercutsCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MFiltercutsCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MFiltercutsCalc.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MFiltercutsCalc
+#define MARS_MFiltercutsCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFiltercutsCalc                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MParList;
+class MFilterList;
+class MHadronness;
+
+
+class MFiltercutsCalc : public MTask
+{
+private:
+    MFilterList *fList;       //->
+    MHadronness *fHadronness; //!
+    TString     fHadronnessName;  // name of container to store hadronness
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    void AddToList(MFilter *f);
+
+public:
+    MFiltercutsCalc(const char *name=NULL, const char *title=NULL);
+    ~MFiltercutsCalc();
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+    TString GetHadronnessName() const { return fHadronnessName; }
+
+    void AddCut(const char *name, Double_t lo, Double_t up);
+    void AddCut(const char *name, Double_t val);
+    void AddCut(const char *cut);
+    void AddCut(MFilter *f);
+
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MFiltercutsCalc, 0) // A class to evaluate Filtercuts
+};
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MFindSupercuts.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MFindSupercuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MFindSupercuts.cc	(revision 9772)
@@ -0,0 +1,1153 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek, 7/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFindSupercuts                                                       //
+//                                                                         //
+// Class for otimizing the parameters of the supercuts                     //
+//                                                                         //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MFindSupercuts.h"
+
+#include <math.h>            // fabs 
+
+#include <TFile.h>
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TStopwatch.h>
+#include <TVirtualFitter.h>
+
+#include "MBinning.h"
+#include "MContinue.h"
+#include "MSupercuts.h"
+#include "MSupercutsCalc.h"
+#include "MDataElement.h"
+#include "MDataMember.h"
+
+#include "MEvtLoop.h"
+#include "MFSelFinal.h"
+#include "MF.h"
+#include "MFEventSelector.h"
+#include "MFEventSelector2.h"
+#include "MFillH.h"
+//#include "MGeomCamCT1Daniel.h"
+#include "MFEventSelector.h"
+#include "MGeomCamMagic.h"
+#include "MH3.h"
+#include "MHSupercuts.h"
+#include "MHFindSignificance.h"
+#include "MHMatrix.h"
+#include "MHOnSubtraction.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMatrixLoop.h"
+#include "MMinuitInterface.h"
+#include "MParList.h"
+#include "MProgressBar.h"
+#include "MReadMarsFile.h"
+#include "MReadTree.h"
+#include "MTaskList.h"
+
+
+ClassImp(MFindSupercuts);
+
+using namespace std;
+
+
+//------------------------------------------------------------------------
+//
+// fcnSupercuts 
+//
+// - calculates the quantity to be minimized (using TMinuit)
+//
+// - the quantity to be minimized is (-1)*significance of the gamma signal
+//   in the alpha distribution (after cuts)
+//
+// - the parameters to be varied in the minimization are the cut parameters
+//   (par)
+//
+static void fcnSupercuts(Int_t &npar, Double_t *gin, Double_t &f, 
+                         Double_t *par, Int_t iflag)
+{
+    //cout <<  "entry fcnSupercuts" << endl;
+
+    //-------------------------------------------------------------
+    // save pointer to the MINUIT object for optimizing the supercuts
+    // because it will be overwritten 
+    // when fitting the alpha distribution in MHFindSignificance
+    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+
+    MEvtLoop *evtloopfcn = (MEvtLoop*)gMinuit->GetObjectFit();
+
+    MParList *plistfcn   = (MParList*)evtloopfcn->GetParList();
+    //MTaskList *tasklistfcn   = (MTaskList*)plistfcn->FindObject("MTaskList");
+
+    MSupercuts *super = (MSupercuts*)plistfcn->FindObject("MSupercuts");
+    if (!super)
+    {
+        gLog << "fcnSupercuts : MSupercuts object '" << "MSupercuts"
+            << "' not found... aborting" << endl;
+        return;
+    }
+
+    //
+    // transfer current parameter values to MSupercuts
+    //
+    // Attention : npar is the number of variable parameters
+    //                  not the total number of parameters
+    //
+    Double_t fMin, fEdm, fErrdef;
+    Int_t     fNpari, fNparx, fIstat;
+    gMinuit->mnstat(fMin, fEdm, fErrdef, fNpari, fNparx, fIstat);
+
+    super->SetParameters(TArrayD(fNparx, par));
+
+    //$$$$$$$$$$$$$$$$$$$$$
+    // for testing
+    //TArrayD checkparameters = super->GetParameters();
+    //gLog << "fcnsupercuts : fNpari, fNparx =" << fNpari << ",  " 
+    //     << fNparx  << endl;
+    //gLog << "fcnsupercuts : i, par, checkparameters =" << endl;
+    //for (Int_t i=0; i<fNparx; i++)
+    //{
+    //  gLog << i << ",  " << par[i] << ",  " << checkparameters[i] << endl;
+    //}
+    //$$$$$$$$$$$$$$$$$$$$$
+
+    //
+    // plot alpha with the current cuts
+    //
+    evtloopfcn->Eventloop();
+
+    //tasklistfcn->PrintStatistics(0, kTRUE);
+
+    MH3* alpha = (MH3*)plistfcn->FindObject("AlphaFcn", "MH3");
+    if (!alpha)
+        return;
+
+    TH1 &alphaHist = alpha->GetHist();
+    alphaHist.SetName("alpha-fcnSupercuts");
+
+    //-------------------------------------------
+    // set Minuit pointer to zero in order not to destroy the TMinuit
+    // object for optimizing the supercuts
+    gMinuit = NULL;
+
+    //=================================================================
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    const Double_t alphasig = 20.0;
+    const Double_t alphamin = 30.0;
+    const Double_t alphamax = 90.0;
+    const Int_t    degree   =    2;
+
+    Bool_t drawpoly;
+    Bool_t fitgauss;
+    if (iflag == 3)
+    {
+        drawpoly  = kTRUE;
+        fitgauss  = kTRUE;
+    }
+    else
+    {
+        drawpoly  = kFALSE;
+        fitgauss  = kFALSE;
+    }
+    //drawpoly  = kFALSE;
+    //fitgauss  = kFALSE;
+
+    const Bool_t print = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+    
+    const Bool_t rc = findsig.FindSigma(&alphaHist, alphamin, alphamax, degree,
+                                        alphasig, drawpoly, fitgauss, print);
+
+    //=================================================================
+
+    // reset gMinuit to the MINUIT object for optimizing the supercuts 
+    gMinuit = savePointer;
+    //-------------------------------------------
+
+    if (!rc)
+    {
+        gLog << "fcnSupercuts : FindSigma() failed" << endl;
+        f = 1.e10;
+        return;
+    }
+
+    // plot some quantities during the optimization
+    MHSupercuts *plotsuper = (MHSupercuts*)plistfcn->FindObject("MHSupercuts");
+    if (plotsuper)
+        plotsuper->Fill(&findsig);
+
+    //------------------------
+    // get significance
+    const Double_t significance = findsig.GetSignificance();
+    f = significance>0 ? -significance : 0;
+
+
+    //------------------------
+    // optimize signal/background ratio
+    //Double_t ratio = findsig.GetNbg()>0.0 ? 
+    //                 findsig.GetNex()/findsig.GetNbg() : 0.0; 
+    //f = -ratio;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFindSupercuts::MFindSupercuts(const char *name, const char *title)
+: fHowManyTrain(10000), fHowManyTest(10000), fMatrixFilter(NULL)
+{
+    fName  = name  ? name  : "MFindSupercuts";
+    fTitle = title ? title : "Optimizer of the supercuts";
+
+    //---------------------------
+    // camera geometry is needed for conversion mm ==> degree
+    //fCam = new MGeomCamCT1Daniel; 
+    fCam = new MGeomCamMagic; 
+
+    // matrices to contain the training/test samples
+    fMatrixTrain = new MHMatrix("MatrixTrain");
+    fMatrixTest  = new MHMatrix("MatrixTest");
+
+    // objects of MSupercutsCalc to which these matrices are attached
+    fCalcHadTrain = new MSupercutsCalc("SupercutsCalcTrain");
+    fCalcHadTest  = new MSupercutsCalc("SupercutsCalcTest");
+
+    // Define columns of matrices
+    fCalcHadTrain->InitMapping(fMatrixTrain);
+    fCalcHadTest->InitMapping(fMatrixTest);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MFindSupercuts::~MFindSupercuts()
+{
+    delete fCam;
+    delete fMatrixTrain;
+    delete fMatrixTest;
+    delete fCalcHadTrain;
+    delete fCalcHadTest;
+}
+
+// --------------------------------------------------------------------------
+//
+// Define the matrix 'fMatrixTrain' for the training sample
+//
+// alltogether 'howmanytrain' events are read from file 'nametrain';
+// the events are selected according to a target distribution 'hreftrain'
+//
+//
+Bool_t MFindSupercuts::DefineTrainMatrix(
+			  const TString &nametrain, MH3 &hreftrain,
+	                  const Int_t howmanytrain, const TString &filetrain)
+{
+    if (nametrain.IsNull() || howmanytrain <= 0)
+        return kFALSE;
+
+    *fLog << "=============================================" << endl;
+    *fLog << "fill training matrix from file '" << nametrain 
+          << "',   select " << howmanytrain 
+        << " events " << endl;
+    if (!hreftrain.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftrain.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", nametrain);
+    read.DisableAutoScheme();
+
+    MFEventSelector2 seltrain(hreftrain);
+    seltrain.SetNumMax(howmanytrain);
+    seltrain.SetName("selectTrain");
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetFilter(&seltrain);
+    filltrain.SetName("fillMatrixTrain");
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&seltrain);
+    tlist.AddToList(&filltrain);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrain");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrain->Print("SizeCols");
+    Int_t howmanygenerated = fMatrixTrain->GetM().GetNrows();
+    if (TMath::Abs(howmanygenerated-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MFindSupercuts::DefineTrainMatrix; no.of generated events ("
+	    << howmanygenerated 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    *fLog << "training matrix was filled" << endl;
+    *fLog << "=============================================" << endl;
+
+    //--------------------------
+    // write out training matrix
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MFindSupercuts::DefineTrainMatrix; Training matrix was written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Define the matrix for the test sample
+//
+// alltogether 'howmanytest' events are read from file 'nametest'
+//
+// the events are selected according to a target distribution 'hreftest'
+//
+//
+Bool_t MFindSupercuts::DefineTestMatrix(
+			  const TString &nametest, MH3 &hreftest,
+	                  const Int_t howmanytest, const TString &filetest)
+{
+    if (nametest.IsNull() || howmanytest<=0)
+        return kFALSE;
+
+    *fLog << "=============================================" << endl;
+    *fLog << "fill test matrix from file '" << nametest 
+          << "',   select " << howmanytest 
+          << " events " << endl;
+    if (!hreftest.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftest.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", nametest);
+    read.DisableAutoScheme();
+
+    MFEventSelector2 seltest(hreftest);
+    seltest.SetNumMax(howmanytest);
+    seltest.SetName("selectTest");
+ 
+    MFillH filltest(fMatrixTest);
+    filltest.SetFilter(&seltest);
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTest);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&seltest);
+    tlist.AddToList(&filltest);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTest");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTest->Print("SizeCols");
+    const Int_t howmanygenerated = fMatrixTest->GetM().GetNrows();
+    if (TMath::Abs(howmanygenerated-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MFindSupercuts::DefineTestMatrix; no.of generated events ("
+	    << howmanygenerated 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+    *fLog << "test matrix was filled" << endl;
+    *fLog << "=============================================" << endl;
+
+    //--------------------------
+    // write out test matrix
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MFindSupercuts::DefineTestMatrix; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices for the training and test sample respectively
+//
+//
+//
+Bool_t MFindSupercuts::DefineTrainTestMatrix(
+			  const TString &name, MH3 &href,
+	                  const Int_t howmanytrain, const Int_t howmanytest,
+                          const TString &filetrain, const TString &filetest)
+{
+    *fLog << "=============================================" << endl;
+    *fLog << "fill training and test matrix from file '" << name 
+          << "',   select "   << howmanytrain 
+          << " training and " << howmanytest << " test events " << endl;
+    if (!href.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << href.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", name);
+    read.DisableAutoScheme();
+
+    MFEventSelector2 selector(href);
+    selector.SetNumMax(howmanytrain+howmanytest);
+    selector.SetName("selectTrainTest");
+    selector.SetInverted();
+
+    MContinue cont(&selector);
+    cont.SetName("ContTrainTest");
+
+    Double_t prob =  ( (Double_t) howmanytrain )
+                   / ( (Double_t)(howmanytrain+howmanytest) );
+    MFEventSelector split;
+    split.SetSelectionRatio(prob);
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetFilter(&split);
+    filltrain.SetName("fillMatrixTrain");
+
+
+    // consider this event as candidate for a test event 
+    // only if event was not accepted as a training event
+
+    MContinue conttrain(&split);
+    conttrain.SetName("ContTrain");
+
+    MFillH filltest(fMatrixTest);
+    filltest.SetName("fillMatrixTest");
+
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+    plist.AddToList(fMatrixTest);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&cont);
+
+    tlist.AddToList(&split);
+    tlist.AddToList(&filltrain);
+    tlist.AddToList(&conttrain);
+
+    tlist.AddToList(&filltest);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrainTest");
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxev = -1;
+    if (!evtloop.Eventloop(maxev))
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrain->Print("SizeCols");
+    const Int_t generatedtrain = fMatrixTrain->GetM().GetNrows();
+    if (TMath::Abs(generatedtrain-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MFindSupercuts::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtrain 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    fMatrixTest->Print("SizeCols");
+    const Int_t generatedtest = fMatrixTest->GetM().GetNrows();
+    if (TMath::Abs(generatedtest-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MFindSupercuts::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtest 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+
+    *fLog << "training and test matrix were filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+    //--------------------------
+    // write out training matrix
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MFindSupercuts::DefineTrainTestMatrix; Training matrix was written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+    //--------------------------
+    // write out test matrix
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MFindSupercuts::DefineTrainTestMatrix; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read training and test matrices from files
+//
+//
+
+Bool_t MFindSupercuts::ReadMatrix(const TString &filetrain, const TString &filetest)
+{
+  //--------------------------
+  // read in training matrix
+
+  TFile filetr(filetrain);
+  fMatrixTrain->Read("MatrixTrain");
+  fMatrixTrain->Print("SizeCols");
+
+  *fLog << "MFindSupercuts::ReadMatrix; Training matrix was read in from file '"
+        << filetrain << "'" << endl;
+  filetr.Close();
+
+
+  //--------------------------
+  // read in test matrix
+
+  TFile filete(filetest);
+  fMatrixTest->Read("MatrixTest");
+  fMatrixTest->Print("SizeCols");
+
+  *fLog << "MFindSupercuts::ReadMatrix; Test matrix was read in from file '"
+        << filetest << "'" << endl;
+  filete.Close();
+
+  return kTRUE;  
+}
+
+
+//------------------------------------------------------------------------
+//
+// Steering program for optimizing the supercuts
+// ---------------------------------------------
+//
+//      the criterion for the 'optimum' is 
+//
+//          - a maximum significance of the gamma signal in the alpha plot, 
+//            in which the supercuts have been applied
+//
+// The various steps are :
+//
+// - setup the event loop to be executed for each call to fcnSupercuts 
+// - call TMinuit to do the minimization of (-significance) :
+//        the fcnSupercuts function calculates the significance 
+//                                             for the current cut values
+//        for this - the alpha plot is produced in the event loop, 
+//                   in which the cuts have been applied
+//                 - the significance of the gamma signal in the alpha plot 
+//                   is calculated
+//
+// Needed as input : (to be set by the Set functions)
+//
+// - fFilenameParam      name of file to which optimum values of the 
+//                       parameters are written
+//
+// - fHadronnessName     name of container where MSupercutsCalc will
+//                       put the supercuts hadronness
+//
+// - for the minimization, the starting values of the parameters are taken  
+//     - from file parSCinit (if it is != "")
+//     - or from the arrays params and/or steps 
+//
+//----------------------------------------------------------------------
+Bool_t MFindSupercuts::FindParams(TString parSCinit,
+                                     TArrayD &params, TArrayD &steps)
+{
+    // Setup the event loop which will be executed in the 
+    //                 fcnSupercuts function  of MINUIT
+    //
+    // parSCinit is the name of the file containing the initial values 
+    // of the parameters; 
+    // if parSCinit = ""   'params' and 'steps' are taken as initial values
+
+    *fLog << "=============================================" << endl;
+    *fLog << "Setup event loop for fcnSupercuts" << endl;
+
+    if (fHadronnessName.IsNull())
+    {
+      *fLog << "MFindSupercuts::FindParams; hadronness name is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrain == NULL)
+    {
+      *fLog << "MFindSupercuts::FindParams; training matrix is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrain->GetM().GetNrows() <= 0)
+    {
+      *fLog << "MFindSupercuts::FindParams; training matrix has no entries"
+            << endl;
+      return kFALSE;
+    }
+
+    MParList  parlistfcn;
+    MTaskList tasklistfcn;
+
+    // loop over rows of matrix
+    MMatrixLoop loop(fMatrixTrain);
+
+    //--------------------------------
+    // create container for the supercut parameters
+    // and set them to their initial values
+    MSupercuts super;
+
+    // take initial values from file parSCinit
+    if (parSCinit != "")
+    {
+      TFile inparam(parSCinit);
+      super.Read("MSupercuts");
+      inparam.Close();
+      *fLog << "MFindSupercuts::FindParams; initial values of parameters are taken from file "
+            << parSCinit << endl;
+    }
+
+    // take initial values from 'params' and/or 'steps'
+    else if (params.GetSize() != 0  || steps.GetSize()  != 0 )
+    {
+      if (params.GetSize()  != 0)
+      {
+        *fLog << "MFindSupercuts::FindParams; initial values of parameters are taken from 'params'"
+              << endl;
+        super.SetParameters(params);
+      }
+      if (steps.GetSize()  != 0)
+      {
+        *fLog << "MFindSupercuts::FindParams; initial step sizes are taken from 'steps'"
+              << endl;
+        super.SetStepsizes(steps);
+      }
+    }
+    else
+    {
+        *fLog << "MFindSupercuts::FindParams; initial values and step sizes are taken from the MSupercuts constructor"
+              << endl;
+    }
+
+
+    //--------------------------------
+    // calculate supercuts hadronness
+    fCalcHadTrain->SetHadronnessName(fHadronnessName);
+
+    // apply the supercuts
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue supercuts(&scfilter);
+
+    // plot |alpha|
+    const TString  mh3Name = "AlphaFcn";
+    MBinning binsalpha("Binning"+mh3Name);
+    binsalpha.SetEdges(54, -12.0, 96.0);
+
+    *fLog << warn << "WARNING------------>ALPHA IS ASSUMED TO BE IN COLUMN 7!!!!!!!!" << endl;
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alpha("MatrixTrain[7]");
+    alpha.SetName(mh3Name);
+
+    MFillH fillalpha(&alpha);
+
+    // book histograms to be filled during the optimization
+    //                              ! not in the event loop !
+    MHSupercuts plotsuper;
+    plotsuper.SetupFill(&parlistfcn);
+
+    //******************************
+    // entries in MParList (extension of old MParList)
+    
+    parlistfcn.AddToList(&tasklistfcn);
+    parlistfcn.AddToList(&super);
+    parlistfcn.AddToList(fCam);
+    parlistfcn.AddToList(fMatrixTrain);
+
+    parlistfcn.AddToList(&binsalpha);
+    parlistfcn.AddToList(&alpha);
+
+    parlistfcn.AddToList(&plotsuper);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklistfcn.AddToList(&loop);
+    tasklistfcn.AddToList(fCalcHadTrain);
+    tasklistfcn.AddToList(&supercuts);
+    tasklistfcn.AddToList(&fillalpha);
+
+
+    //******************************
+
+    MEvtLoop evtloopfcn("EvtLoopFCN");
+    evtloopfcn.SetParList(&parlistfcn);
+    *fLog << "Event loop for fcnSupercuts has been setup" << endl;
+
+    // address of evtloopfcn is used in CallMinuit()
+
+
+    //-----------------------------------------------------------------------
+    //
+    //----------   Start of minimization part   --------------------
+    //
+    // Do the minimization with MINUIT
+    //
+    // Be careful: This is not thread safe
+    //
+    *fLog << "========================================================" << endl;
+    *fLog << "Start minimization for supercuts" << endl;
+
+
+    // -------------------------------------------
+    // prepare call to MINUIT
+    //
+
+    // get initial values of parameters 
+    fVinit = super.GetParameters();
+    fStep  = super.GetStepsizes();
+
+    TString name[fVinit.GetSize()];
+    fStep.Set(fVinit.GetSize());
+    fLimlo.Set(fVinit.GetSize());
+    fLimup.Set(fVinit.GetSize());
+    fFix.Set(fVinit.GetSize());
+
+    fNpar = fVinit.GetSize();
+
+    for (UInt_t i=0; i<fNpar; i++)
+    {
+        name[i]   = "p";
+        name[i]  += i+1;
+        //fStep[i]  = TMath::Abs(fVinit[i]/10.0);
+        fLimlo[i] = -100.0;
+        fLimup[i] =  100.0;
+        fFix[i]   =     0;
+    }
+
+    // these parameters make no sense, fix them at 0.0
+    fVinit[33] = 0.0;
+    fStep[33]  = 0.0;
+    fFix[33]   = 1;
+
+    fVinit[36] = 0.0;
+    fStep[36]  = 0.0;
+    fFix[36]   = 1;
+
+    fVinit[39] = 0.0;
+    fStep[39]  = 0.0;
+    fFix[39]   = 1;
+
+    fVinit[41] = 0.0;
+    fStep[41]  = 0.0;
+    fFix[41]   = 1;
+
+    fVinit[44] = 0.0;
+    fStep[44]  = 0.0;
+    fFix[44]   = 1;
+
+    fVinit[47] = 0.0;
+    fStep[47]  = 0.0;
+    fFix[47]   = 1;
+
+    // vary only first 48 parameters
+    //for (UInt_t i=0; i<fNpar; i++)
+    //{
+    //    if (i >= 48)
+    //	{
+    //      fStep[i] = 0.0;
+    //      fFix[i]  =   1;
+    //	}
+    //}
+ 
+
+    // -------------------------------------------
+    // call MINUIT
+
+    TStopwatch clock;
+    clock.Start();
+
+    *fLog << "before calling CallMinuit" << endl;
+
+    MMinuitInterface inter;               
+    Bool_t rc = inter.CallMinuit(fcnSupercuts, name,
+                                 fVinit, fStep, fLimlo, fLimup, fFix,
+                                 &evtloopfcn, "SIMPLEX", kFALSE);
+ 
+    *fLog << "after calling CallMinuit" << endl;
+
+    *fLog << "Time spent for the minimization in MINUIT :   " << endl;;
+    clock.Stop();
+    clock.Print();
+
+    plotsuper.DrawClone();
+
+    if (!rc)
+        return kFALSE;
+
+    *fLog << "Minimization for supercuts finished" << endl;
+    *fLog << "========================================================" << endl;
+
+
+    // -----------------------------------------------------------------
+    // in 'fcnSupercuts' (IFLAG=3) the optimum parameter values were put 
+    //                    into MSupercuts
+
+    // write optimum parameter values onto file filenameParam
+    
+    TFile outparam(fFilenameParam, "RECREATE"); 
+    super.Write();
+    outparam.Close();
+
+    *fLog << "Optimum parameter values for supercuts were written onto file '"
+              << fFilenameParam << "' :" << endl;
+
+    const TArrayD &check = super.GetParameters();
+    for (Int_t i=0; i<check.GetSize(); i++)
+        *fLog << check[i] << ",  ";
+    *fLog << endl;
+
+
+
+    *fLog << "End of  supercuts optimization part" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
+
+// -----------------------------------------------------------------------
+//
+// Test the supercuts on the test sample
+//
+
+Bool_t MFindSupercuts::TestParams()
+{
+    if (fMatrixTest->GetM().GetNrows() <= 0)
+    {
+        *fLog << "MFindSupercuts::TestParams; test matrix has no entries" 
+              << endl;
+        return kFALSE;
+    }
+
+    // -------------   TEST the supercuts    ------------------------------
+    //
+    *fLog << "Test the supercuts on the test sample" << endl;
+
+    // -----------------------------------------------------------------
+    // read optimum parameter values from file filenameParam
+    // into array 'supercutsPar'
+
+    TFile inparam(fFilenameParam);
+    MSupercuts scin; 
+    scin.Read("MSupercuts");
+    inparam.Close();
+
+    *fLog << "Optimum parameter values for supercuts were read from file '";
+    *fLog << fFilenameParam << "' :" << endl;
+
+    const TArrayD &supercutsPar = scin.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+        *fLog << supercutsPar[i] << ",  ";
+    *fLog << endl;
+    //---------------------------
+
+
+    // -----------------------------------------------------------------
+    if (fHadronnessName.IsNull())
+    {
+        *fLog << "MFindSupercuts::TestParams; hadronness name is not defined... aborting";
+        *fLog << endl;
+        return kFALSE;
+    }
+
+    MParList  parlist2;
+    MTaskList tasklist2;
+
+    MSupercuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+
+    fCalcHadTest->SetHadronnessName(fHadronnessName);
+
+
+    //-------------------------------------------
+
+    MMatrixLoop loop(fMatrixTest);
+
+    // plot alpha before applying the supercuts
+    const TString  mh3NameB = "AlphaBefore";
+    MBinning binsalphabef("Binning"+mh3NameB);
+    binsalphabef.SetEdges(54, -12.0, 96.0);
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alphabefore("MatrixTest[7]");
+    alphabefore.SetName(mh3NameB);
+
+    TH1 &alphahistb = alphabefore.GetHist();
+    alphahistb.SetName("alphaBefore-TestParams");
+
+    MFillH fillalphabefore(&alphabefore);
+    fillalphabefore.SetName("FillAlphaBefore");
+
+    // apply the supercuts
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue applysupercuts(&scfilter);
+
+    // plot alpha after applying the supercuts
+    const TString  mh3NameA = "AlphaAfter";
+    MBinning binsalphaaft("Binning"+mh3NameA);
+    binsalphaaft.SetEdges(54, -12.0, 96.0);
+
+    MH3 alphaafter("MatrixTest[7]");
+    alphaafter.SetName(mh3NameA);
+
+    TH1 &alphahista = alphaafter.GetHist();
+    alphahista.SetName("alphaAfter-TestParams");
+
+    MFillH fillalphaafter(&alphaafter);
+    fillalphaafter.SetName("FillAlphaAfter");
+
+    //******************************
+    // entries in MParList
+
+    parlist2.AddToList(&tasklist2);
+
+    parlist2.AddToList(&supercuts);
+
+    parlist2.AddToList(fCam);
+    parlist2.AddToList(fMatrixTest);
+
+    parlist2.AddToList(&binsalphabef);
+    parlist2.AddToList(&alphabefore);
+
+    parlist2.AddToList(&binsalphaaft);
+    parlist2.AddToList(&alphaafter);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklist2.AddToList(&loop);
+    tasklist2.AddToList(&fillalphabefore);
+
+    tasklist2.AddToList(fCalcHadTest);
+    tasklist2.AddToList(&applysupercuts);
+
+    tasklist2.AddToList(&fillalphaafter);
+
+    //******************************
+
+    MProgressBar bar2;
+    MEvtLoop evtloop2;
+    evtloop2.SetParList(&parlist2);
+    evtloop2.SetName("EvtLoopTestParams");
+    evtloop2.SetProgressBar(&bar2);
+    Int_t maxevents2 = -1;
+    if (!evtloop2.Eventloop(maxevents2))
+        return kFALSE;
+
+    tasklist2.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // draw the alpha plots
+
+    MH3* alphaBefore = (MH3*)parlist2.FindObject(mh3NameB, "MH3");
+    TH1  &alphaHist1 = alphaBefore->GetHist();
+    alphaHist1.SetXTitle("|\\alpha|  [\\circ]");
+
+    MH3* alphaAfter = (MH3*)parlist2.FindObject(mh3NameA, "MH3");
+    TH1  &alphaHist2 = alphaAfter->GetHist();
+    alphaHist2.SetXTitle("|\\alpha|  [\\circ]");
+    alphaHist2.SetName("alpha-TestParams");
+
+    TCanvas *c = new TCanvas("AlphaAfterSC", "AlphaTest", 600, 300);
+    c->Divide(2,1);
+
+    gROOT->SetSelectedPad(NULL);
+
+    c->cd(1);
+    alphaHist1.DrawCopy();
+
+    c->cd(2);
+    alphaHist2.DrawCopy();
+
+
+
+    //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    const Double_t alphasig = 20.0;
+    const Double_t alphamin = 30.0;
+    const Double_t alphamax = 90.0;
+    const Int_t    degree   =    2;
+    const Bool_t   drawpoly  = kTRUE;
+    const Bool_t   fitgauss  = kTRUE;
+    const Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist2, alphamin, alphamax, degree, 
+                      alphasig, drawpoly, fitgauss, print);
+
+    const Double_t significance = findsig.GetSignificance();
+    const Double_t alphasi = findsig.GetAlphasi();
+
+    *fLog << "Significance of gamma signal after supercuts in test sample : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+    //-------------------------------------------
+
+
+    *fLog << "Test of supercuts part finished" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/manalysis/MFindSupercuts.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MFindSupercuts.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MFindSupercuts.h	(revision 9772)
@@ -0,0 +1,132 @@
+#ifndef MARS_MFindSupercuts
+#define MARS_MFindSupercuts
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MFilter;
+class MEvtLoop;
+class MH3;
+class MSupercutsCalc;
+class MGeomCam;
+class MHMatrix;
+/*
+#include "MFilter.h"
+#include "MEvtLoop.h"
+#include "MH3.h"
+#include "MSupercutsCalc.h"
+#include "MGeomCam.h"
+#include "MHMatrix.h"
+*/
+
+class MFindSupercuts : public MParContainer
+{
+private:
+
+  TString fFilenameTrain;
+  TString fFilenameTest;
+
+  Int_t   fHowManyTrain;
+  Int_t   fHowManyTest;
+
+  Bool_t  fUseOrigDistribution;
+
+  TString  fFilenameParam;
+
+  TString  fHadronnessName;
+
+  MSupercutsCalc *fCalcHadTrain;
+  MSupercutsCalc *fCalcHadTest;
+
+  MHMatrix          *fMatrixTrain;
+  MHMatrix          *fMatrixTest;
+  MGeomCam          *fCam;
+
+  MEvtLoop *fObjectFit;
+
+  MFilter  *fMatrixFilter; 
+
+  // to comunicate with MINUIT -----------------
+  // attention : dimensions must agree with those in 
+  //             MMinuitInterface::CallMinuit()
+  //char    fParName [80][100];
+  TArrayD fVinit;
+  TArrayD fStep;
+  TArrayD fLimlo;
+  TArrayD fLimup;
+  TArrayI fFix;
+
+  UInt_t     fNpar;
+
+  TString    fMethod;
+
+  Double_t fMin,   fEdm,   fErrdef;
+  Int_t    fNpari, fNparx, fIstat;
+  Int_t    fErrMinimize;
+  //--------------------------------------------
+
+
+public:
+  MFindSupercuts(const char *name=NULL, const char *title=NULL);
+  ~MFindSupercuts();
+
+  void SetFilenameTraining(const TString &name, const Int_t howmany) 
+      {fFilenameTrain = name;  fHowManyTrain = howmany; }
+
+  void SetFilenameTest(const TString &name, const Int_t howmany)     
+      {fFilenameTest     = name;  fHowManyTest  = howmany; }
+
+  void SetFilenameParam(const TString &name)    {fFilenameParam  = name;}
+  void SetHadronnessName(const TString &name)   {fHadronnessName = name;}
+
+  void SetMatrixFilter(MFilter *filter)          {fMatrixFilter = filter;}
+
+  Bool_t DefineTrainMatrix(const TString &name, MH3 &href,
+                           const Int_t howmany, const TString &filetrain); 
+
+  Bool_t DefineTestMatrix(const TString &name, MH3 &href,
+                          const Int_t howmany, const TString &filetest);
+
+  Bool_t DefineTrainTestMatrix(const TString &name, MH3 &href,
+			 const Int_t howmanytrain, const Int_t howmanytest, 
+                         const TString &filetrain, const TString &filetest);
+
+  MHMatrix *GetMatrixTrain() { return fMatrixTrain; }
+  MHMatrix *GetMatrixTest()  { return fMatrixTest;  }
+
+  Bool_t ReadMatrix( const TString &filetrain, const TString &filetest);
+
+  Bool_t FindParams(TString parSCinit, TArrayD &params, TArrayD &steps);
+  Bool_t TestParams();
+
+  ClassDef(MFindSupercuts, 1) // Class for optimization of the Supercuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MGeomApply.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MGeomApply.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MGeomApply.cc	(revision 9772)
@@ -0,0 +1,258 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 09/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Markus Gaug,  03/2004 <mailto:markus@ifae.es>
+!              Hendrik Bartko, 07/2003 <mailto:hbartko@mppmu.mpg.de>
+!         
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MGeomApply
+//
+//  Applies the geometry to geometry dependant containers.
+//
+//  It changes the size of the arrays in the containers to a size
+//  matching the number of pixels, eg:
+//
+//   MPedestalCam
+//   MCalibrationChargeCam
+//   MCalibrationRelTimeCam
+//   MCalibrationQECam
+//   MCalibrationPedCam
+//   MPedPhotCam
+//   MExtractedSignalCam
+//   MArrivalTimeCam
+//   MArrivalTime
+//
+//  It uses the geometry (MGeomCam) found in the parameter list.
+//  If it is not found the task tries to create the geometry
+//  specified in the constructor. The default geometry is
+//  MGeomCamMagic.
+//
+// In a standard setup all containers in the parameter list which derive
+// from MCamEvent are processed automatically in ReInit. To allow having
+// two parallel geometries in the parameter list or for MCamEvent in the
+// parameter list you can switch off the automatic procedure by adding
+// the containers to be processed using AddCamEvent().
+//
+// 
+//  Input Containers:
+//   [MGeomCam]
+//   [all MCamEvent]
+//
+//  Output Containers:
+//   [all MCamEvent]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MGeomApply.h"
+
+#include <fstream>
+
+#include <TObjString.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MCamEvent.h"
+
+ClassImp(MGeomApply);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. MGeomCamMagic is the default geometry.
+//
+MGeomApply::MGeomApply(const char *name, const char *title)
+    : fGeomName("MGeomCamMagic"), fNamesList(0), fList(0)
+{
+    fName  = name  ? name  : "MGeomApply";
+    fTitle = title ? title : "Task to apply geometry settings";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete fList if available.
+//
+MGeomApply::~MGeomApply()
+{
+    if (fList)
+        delete fList;
+    if (fNamesList)
+        delete fNamesList;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Try to find 'MGeomCam' in the Parameter List. If it is not found,
+//  try to create a fGeomName object.
+//
+Int_t MGeomApply::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (cam)
+        return kTRUE;
+
+    cam = (MGeomCam*)pList->FindCreateObj(AddSerialNumber(fGeomName), "MGeomCam");
+
+    return cam ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check the whole parameter list for MCamEvent. For all MCamEvent
+//  MCamEvent::Init(MGeomCam&) is called.
+//
+void MGeomApply::ProcessAutomatic(MParList &list, const MGeomCam &geom) const
+{
+    TIter Next(list);
+    TObject *o = 0;
+
+    while ((o=Next()))
+    {
+        MCamEvent *cam = dynamic_cast<MCamEvent*>(o);
+        if (cam)
+            cam->Init(geom);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check all containers in fNamesList and fList. For all MCamEvent
+//  MCamEvent::Init(MGeomCam&) is called.
+//
+Bool_t MGeomApply::ProcessManual(MParList &list, const MGeomCam &geom) const
+{
+    TIter NextN(fNamesList);
+    TObject *o = 0;
+
+    while ((o=NextN()))
+    {
+        TObject *cont = list.FindObject(o->GetName(), "MCamEvent");
+        if (!cont)
+        {
+            *fLog << err << o->GetName() << " [MCamEvent] not found... abort." << endl;
+            return kFALSE;
+        }
+
+        MCamEvent *cam = dynamic_cast<MCamEvent*>(o);
+        cam->Init(geom);
+    }
+
+    TIter NextL(fList);
+    while ((o=NextL()))
+    {
+        MCamEvent *cam = dynamic_cast<MCamEvent*>(o);
+        cam->Init(geom);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Try to find 'MGeomCam' in the Parameter List. If it is not found,
+//  processing is stopped.
+//
+Bool_t MGeomApply::ReInit(MParList *pList)
+{
+    MGeomCam *geom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!geom)
+    {
+       *fLog << err << GetDescriptor() << ": No MGeomCam found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // FIXME, workaround: this call to CalcPixRatio is here just to allow
+    // the use of some camera files from the 0.7 beta version in which the 
+    // array containing pixel ratios is not initialized.
+    geom->CalcPixRatio();
+
+    if (fList)
+        return ProcessManual(*pList, *geom);
+
+    ProcessAutomatic(*pList, *geom);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MGeomApply::StreamPrimitive(ofstream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    if (fGeomName.IsNull())
+        return;
+
+    out << "   " << GetUniqueName() << ".SetGeometry(\"";
+    out << fGeomName << "\");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a MCamEvent to be processed. This switches off the automatic
+// processing of all MCamEvent in the parameter list completely!
+//
+void MGeomApply::AddCamEvent(TObject *obj)
+{
+    if (!obj->InheritsFrom(MCamEvent::Class()))
+    {
+        *fLog << warn << "MGeomApply::AddCamEvent - WARNING: Object doesn't inherit from MCamEvent... ignored." << endl;
+        return;
+    }
+
+    if (!fList)
+    {
+        fList = new TList;
+        fNamesList = new TList;
+
+        fNamesList->SetOwner();
+    }
+
+    fList->Add(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a MCamEvent to be processed. This switches off the automatic
+// processing of all MCamEvent in the parameter list completely!
+//
+void MGeomApply::AddCamEvent(const char *name)
+{
+    if (!fList)
+    {
+        fList = new TList;
+        fNamesList = new TList;
+
+        fNamesList->SetOwner();
+    }
+
+    fNamesList->Add(new TObjString(name));
+}
Index: /tags/Mars-V0.9/manalysis/MGeomApply.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MGeomApply.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MGeomApply.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MGeomApply
+#define MARS_MGeomApply
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MGeomCam;
+
+class MGeomApply : public MTask
+{
+private:
+    TString fGeomName; // Name of geometry class
+
+    TList *fNamesList;
+    TList *fList;
+
+    void ProcessAutomatic(MParList &plist, const MGeomCam &geom) const;
+    Bool_t ProcessManual(MParList &plist, const MGeomCam &geom) const;
+
+    Int_t  PreProcess(MParList *plist);
+    Bool_t ReInit(MParList *pList);
+    void   StreamPrimitive(ofstream &out) const;
+
+public:
+    MGeomApply(const char *name=NULL, const char *title=NULL);
+    ~MGeomApply();
+
+    void SetGeometry(TString geom) { fGeomName = geom; }
+
+    void AddCamEvent(TObject *obj);
+    void AddCamEvent(const char *name);
+
+    ClassDef(MGeomApply, 0) // Task to apply geometry settings
+};
+    
+#endif
+
Index: /tags/Mars-V0.9/manalysis/MHPedestalCam.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MHPedestalCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MHPedestalCam.cc	(revision 9772)
@@ -0,0 +1,581 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@atsro.uni-wuerzburh.de>
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPedestalCam
+//
+// Fills the extracted pedestals of MExtractedSignalCam into
+// the MHCalibrationPix-classes MHPedestalPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray
+//   or MHCalibrationCam::fHiGainArray, respectively, depending if
+//   MArrivalTimePix::IsLoGainUsed() is set.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors
+//   and MHCalibrationCam::fAverageHiGainSectors
+//
+// Every pedestal is directly taken from MExtractedSignalCam, filled by the
+// appropriate extractor.
+//
+// The pedestals are filled into a histogram and an array, in order to perform
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors
+// and the fit probability are extracted. If none of these values are NaN's and
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%),
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are
+// taken directly (see MHCalibrationPix::BypassFit()).
+//
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup)
+//
+// The number of summed FADC slices is taken to re-normalize
+// the result to a pedestal per pixel with the formulas (see MHPedestalPix::Renorm()):
+// - Mean Pedestal        / slice = Mean Pedestal        / Number slices
+// - Mean Pedestal Error  / slice = Mean Pedestal Error  / Number slices
+// - Sigma Pedestal       / slice = Sigma Pedestal       / Sqrt (Number slices)
+// - Sigma Pedestal Error / slice = Sigma Pedestal Error / Sqrt (Number slices)
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the
+// projected fourier components follow an exponential distribution.
+//
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MPedestalCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of
+// the number involved pixels in order to be able to compare it to the average of
+// sigmas in the camera.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPedestalCam.h"
+#include "MHPedestalPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationPedCam.h"
+
+#include "TH1.h"
+
+ClassImp(MHPedestalCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes:
+// - fExtractHiGainSlices to 0.
+// - fExtractLoGainSlices to 0.
+// - the event frequency to 1200 Hz.
+// - the fRenorm flag to kTRUE
+//
+MHPedestalCam::MHPedestalCam(const char *name, const char *title) 
+    : fExtractHiGainSlices(0.), fExtractLoGainSlices(0.)
+{
+
+  fName  = name  ? name  : "MHPedestalCam";
+  fTitle = title ? title : "";
+  
+  SetPulserFrequency(1200);
+  SetRenorm();
+
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Searches pointer to:
+// - MPedestalCam
+// - MExtractedSignalCam
+//
+// Searches or creates:
+// - MCalibrationPedCam
+//
+// Retrieves from MExtractedSignalCam:
+// - number of used High Gain FADC slices (MExtractedSignalCam::GetNumUsedHiGainFADCSlices())
+// - number of used Low  Gain FADC slices (MExtractedSignalCam::GetNumUsedLoGainFADCSlices())
+//
+// Initializes, if empty to MGeomCam::GetNumPixels():
+// - MHCalibrationCam::fHiGainArray, MHCalibrationCam::fLoGainArray
+//
+// Initializes, if empty to MGeomCam::GetNumAreas() for:
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+//
+// Initializes, if empty to MGeomCam::GetNumSectors() for:
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+// 
+// Calls MHCalibrationCam::InitPedHists() for every entry in:
+// - MHCalibrationCam::fHiGainArray, MHCalibrationCam::fLoGainArray
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+//
+// Sets Titles and Names for the Histograms 
+// - MHCalibrationCam::fAverageHiGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors
+// 
+Bool_t MHPedestalCam::ReInitHists(MParList *pList)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!signal)
+    {
+      gLog << err << "Cannot find MExtractedSignalCam... abort." << endl;
+      return kFALSE;
+    }
+  
+
+  fPedestals = (MPedestalCam*)pList->FindObject("MPedestalCam");
+
+  if (!fPedestals)
+    {
+      gLog << err << "Cannot find MPedestalCam ... abort." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  fCam = (MCalibrationCam*)pList->FindObject("MCalibrationPedCam");
+  if (!fCam)
+  {
+      fCam = (MCalibrationCam*)pList->FindCreateObj(AddSerialNumber("MCalibrationPedCam"));
+      if (!fCam)
+          return kFALSE;
+
+      fCam->Init(*fGeom);
+  }
+  
+  Float_t sliceshi = signal->GetNumUsedHiGainFADCSlices();
+  Float_t sliceslo = signal->GetNumUsedLoGainFADCSlices();
+
+  if (sliceshi == 0.)
+    {
+      gLog << err << "Number of used signal slices in MExtractedSignalCam is zero  ... abort." 
+           << endl;
+      return kFALSE;
+    }
+
+  if (fExtractHiGainSlices != 0. && sliceshi != fExtractHiGainSlices )
+    {
+      gLog << err << "Number of used High Gain signal slices changed in MExtractedSignalCam  ... abort." 
+           << endl;
+      return kFALSE;
+    }
+
+  if (fExtractLoGainSlices != 0. && sliceslo != fExtractLoGainSlices )
+    {
+      gLog << err << "Number of used Low Gain signal slices changed in MExtractedSignalCam  ... abort." 
+           << endl;
+      return kFALSE;
+    }
+
+  fExtractHiGainSlices = sliceshi;
+  fExtractLoGainSlices = sliceslo;
+
+  if (fHiGainArray->GetEntries()==0)
+  {
+      fHiGainArray->Expand(npixels);
+      for (Int_t i=0; i<npixels; i++)
+      {
+	  (*fHiGainArray)[i] = new MHPedestalPix;
+          InitPedHists((MHPedestalPix&)(*this)[i],i,fExtractHiGainSlices);
+          
+          if ((*fBadPixels)[i].IsBad())
+            (*this)[i].SetExcluded();
+
+          (*fPedestals)[i].InitUseHists();
+      }
+
+  }
+
+  if (fLoGainArray->GetEntries()==0)
+  {
+      fLoGainArray->Expand(npixels);
+      for (Int_t i=0; i<npixels; i++)
+      {
+	  (*fLoGainArray)[i] = new MHPedestalPix;
+          InitPedHists((MHPedestalPix&)(*this)(i),i,fExtractLoGainSlices);
+
+          if ((*fBadPixels)[i].IsBad())
+            (*this)(i).SetExcluded();
+      }
+  }
+
+  if (fAverageHiGainAreas->GetEntries()==0)
+  {
+    fAverageHiGainAreas->Expand(nareas);
+    
+    for (Int_t j=0; j<nareas; j++)
+      {
+        (*fAverageHiGainAreas)[j] = 
+          new MHPedestalPix("AverageHiGainArea",
+                                      "Average Pedestals area idx ");
+
+        GetAverageHiGainArea(j).GetHGausHist()->SetTitle("Pedestals average Area Idx ");
+
+        InitPedHists((MHPedestalPix&)GetAverageHiGainArea(j),j,fExtractHiGainSlices);
+
+      }
+  }
+
+  if (fAverageLoGainAreas->GetEntries()==0)
+  {
+    fAverageLoGainAreas->Expand(nareas);
+    
+    for (Int_t j=0; j<nareas; j++)
+      {
+        (*fAverageLoGainAreas)[j] = 
+          new MHPedestalPix("AverageLoGainArea",
+                                      "Pedestals average Area idx ");
+
+        GetAverageLoGainArea(j).GetHGausHist()->SetTitle("Pedestals average Area Idx ");
+
+        InitPedHists((MHPedestalPix&)GetAverageLoGainArea(j),j,fExtractLoGainSlices);
+
+      }
+  }
+
+  if (fAverageHiGainSectors->GetEntries()==0)
+  {
+      fAverageHiGainSectors->Expand(nsectors);
+
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  (*fAverageHiGainSectors)[j] = 
+            new MHPedestalPix("AverageHiGainSector",
+                                        "Pedestals average sector ");
+
+          GetAverageHiGainSector(j).GetHGausHist()->SetTitle("Pedestals average Sector ");
+
+          InitPedHists((MHPedestalPix&)GetAverageHiGainSector(j),j,fExtractHiGainSlices);
+
+      }
+  }
+
+  if (fAverageLoGainSectors->GetEntries()==0)
+  {
+      fAverageLoGainSectors->Expand(nsectors);
+
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  (*fAverageLoGainSectors)[j] = 
+            new MHPedestalPix("AverageLoGainSector",
+                                        "Pedestals average sector ");
+
+          GetAverageLoGainSector(j).GetHGausHist()->SetTitle("Pedestals average Sector ");
+
+          InitPedHists((MHPedestalPix&)GetAverageLoGainSector(j),j,fExtractLoGainSlices);
+          
+      }
+  }
+
+  return kTRUE;
+}
+
+
+// -------------------------------------------------------------
+//
+// If MBadPixelsPix::IsBad():
+// - calls MHCalibrationPix::SetExcluded()
+//
+// Calls:
+// - MHGausEvents::InitBins()
+// - MHCalibrationPix::ChangeHistId(i)
+// - MHCalibrationPix::SetEventFrequency(fPulserFrequency)
+// - MHPedestalPix::SetNSlices(nslices)
+//
+void MHPedestalCam::InitPedHists(MHPedestalPix &hist, const Int_t i, const Float_t nslices)
+{
+
+  hist.InitBins();
+  hist.ChangeHistId(i);
+  hist.SetEventFrequency(fPulserFrequency);
+
+  if (fRenorm)
+    hist.SetNSlices(nslices);
+
+  hist.SetProbLimit(0.);
+
+  TH1F *h = hist.GetHGausHist();
+  h->SetTitle( Form("%s%s", h->GetTitle()," Runs: "));
+}
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MExtractedSignalCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain or LoGain histograms (MHGausEvents::FillHistAndArray()), respectively
+// with the signals MExtractedSignalCam::GetExtractedSignalHiGain() and 
+// MExtractedSignalCam::GetExtractedSignalLoGain(), respectively.
+//
+Bool_t MHPedestalCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)par;
+  if (!signal)
+    {
+      gLog << err << "No argument in MExtractedSignalCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  TArrayF sumareahi(nareas);
+  TArrayF sumarealo(nareas);
+  TArrayF sumsectorhi(nsectors);
+  TArrayD sumsectorlo(nsectors);
+  TArrayI numareahi(nareas);
+  TArrayI numarealo(nareas);
+  TArrayI numsectorhi(nsectors);
+  TArrayI numsectorlo(nsectors);
+
+  for (UInt_t i=0; i<npixels; i++)
+  {
+      MHCalibrationPix &histhi = (*this)[i];
+      MHCalibrationPix &histlo = (*this)(i);
+
+      if (histhi.IsExcluded())
+          continue;
+
+      const MExtractedSignalPix &pix = (*signal)[i];
+
+      const Float_t pedhi = pix.GetExtractedSignalHiGain();
+      const Float_t pedlo = pix.GetExtractedSignalLoGain();
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      histhi.FillHistAndArray(pedhi) ;
+      sumareahi  [aidx]   += pedhi;
+      numareahi  [aidx]   ++;
+      sumsectorhi[sector] += pedhi;
+      numsectorhi[sector] ++;
+
+      histlo.FillHistAndArray(pedlo);
+      sumarealo  [aidx]   += pedlo;
+      numarealo  [aidx]   ++;
+      sumsectorlo[sector] += pedlo;
+      numsectorlo[sector] ++;
+
+    }
+  
+  for (UInt_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+
+      MHCalibrationPix &histlo = GetAverageLoGainArea(j);
+      histlo.FillHistAndArray(numarealo[j] == 0 ? 0. : sumarealo[j]/numarealo[j]);
+    }
+  
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+      MHCalibrationPix &histlo = GetAverageLoGainSector(j);
+      histlo.FillHistAndArray(numsectorlo[j] == 0 ? 0. : sumsectorlo[j]/numsectorlo[j]);
+    }
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with Bad Pixels flags 0
+// - MHCalibrationCam::FitLoGainArrays() with Bad Pixels flags 0
+// 
+Bool_t MHPedestalCam::FinalizeHists()
+{
+
+  FitHiGainArrays((*fCam),*fBadPixels, 
+                  MBadPixelsPix::kHiGainNotFitted,
+                  MBadPixelsPix::kHiGainOscillating);
+  FitLoGainArrays((*fCam),*fBadPixels,
+                  MBadPixelsPix::kLoGainNotFitted,
+                  MBadPixelsPix::kLoGainOscillating);
+
+
+  return kTRUE;
+  
+
+}
+
+// ------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Charge
+// 1: Error of fitted Charge
+// 2: Sigma of fitted Charge
+// 3: Error of Sigma of fitted Charge
+//
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Charge distribution
+// 5: Relative differenc of calculated pedestal (per slice) and fitted (per slice)
+// 6: Error of the Relative differenc of calculated pedestal (per slice) and fitted (per slice)
+// 7: Relative difference of the error of the mean pedestal (per slice) - calculated and fitted
+// 8: Relative differenc of calculated pedestal RMS (per slice) and fitted sigma (per slice)
+// 9: Error of Relative differenc of calculated pedestal RMS (per slice) and fitted sigma (per slice)
+// 10: Relative difference of the error of the pedestal RMS (per slice) - calculated and fitted
+//
+// Localized defects:
+// ==================
+//
+// 11: Gaus fit not OK
+// 12: Fourier spectrum not OK
+//
+Bool_t MHPedestalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  if ((*this)[idx].IsExcluded())
+    return kFALSE;
+
+  const Float_t ped      = (*fPedestals)[idx].GetPedestal();
+  const Float_t rms      = (*fPedestals)[idx].GetPedestalRms();
+
+  const Float_t entsqr    =  TMath::Sqrt((Float_t)fPedestals->GetTotalEntries());
+
+  const Float_t pederr   = rms/entsqr;
+  const Float_t rmserr   = rms/entsqr/2.;
+
+  const Float_t mean     = (*this)[idx].GetMean();
+  const Float_t meanerr  = (*this)[idx].GetMeanErr();
+  const Float_t sigma    = (*this)[idx].GetSigma() ;
+  const Float_t sigmaerr = (*this)[idx].GetSigmaErr();
+
+  switch (type)
+    {
+    case 0:
+      val = mean;
+      break;
+    case 1:
+      val = meanerr;
+      break;
+    case 2:
+      val = sigma;
+      break;
+    case 3:
+      val = sigmaerr;
+      break;
+    case 4:
+      val = (*this)[idx].GetProb();
+      break;
+    case 5:
+      val = 2.*(mean-ped)/(ped+mean);
+      break;
+    case 6:
+      val = TMath::Sqrt((pederr*pederr + meanerr*meanerr) * (ped*ped + mean*mean))
+            *2./(ped+mean)/(ped+mean);
+      break;
+    case 7:
+      val = 2.*(meanerr-pederr)/(pederr + meanerr);
+      break;
+    case 8:
+      val = 2.*(sigma-rms)/(sigma+rms);
+      break;
+    case 9:
+      val = TMath::Sqrt((rmserr*rmserr + sigmaerr*sigmaerr) * (rms*rms + sigma*sigma))
+            *2./(rms+sigma)/(rms+sigma);
+      break;
+    case 10:
+      val = 2.*(sigmaerr - rmserr)/(sigmaerr + rmserr);
+      break;
+    case 11:
+      if (!(*this)[idx].IsGausFitOK())
+        val = 1.;
+      break;
+    case 12:
+      if (!(*this)[idx].IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHGausEvents::DrawClone() for pixel idx
+//
+void MHPedestalCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
Index: /tags/Mars-V0.9/manalysis/MHPedestalCam.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MHPedestalCam.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MHPedestalCam.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHPedestalCam
+#define MARS_MHPedestalCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+class MGeomCam;
+class MPedestalCam;
+class MHPedestalPix;
+class MHPedestalCam : public MHCalibrationCam
+{
+
+private:
+
+  void   InitPedHists(MHPedestalPix &hist, const Int_t i, const Float_t nslices);
+  
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  
+  Float_t fExtractHiGainSlices;           // Number of FADC slices used for high gain signal extraction
+  Float_t fExtractLoGainSlices;           // Number of FADC slices used for low  gain signal extraction
+
+  Bool_t  fRenorm;
+
+  MPedestalCam *fPedestals;               //! Pedestal Cam filled by MPedCalcPedRun
+  
+public:
+  MHPedestalCam(const char *name=NULL, const char *title=NULL);
+  ~MHPedestalCam() {}
+  
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+  
+  void SetRenorm( const Bool_t b=kTRUE )  {  fRenorm = b; }
+
+  ClassDef(MHPedestalCam, 1)	// Histogram class for Charge Camera Pedestals 
+};
+
+#endif
+
Index: /tags/Mars-V0.9/manalysis/MHPedestalPix.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MHPedestalPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MHPedestalPix.cc	(revision 9772)
@@ -0,0 +1,134 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHPedestalPix
+//
+//  Histogram class for pedestal analysis. 
+//  Stores and fits the pedestals taken from MPedestalPix on an event-by-event
+//  basis. The results are re-normalized to a value per slice with the formulae:
+//
+// - Mean Pedestal        / slice = Mean Pedestal        / Number slices
+// - Mean Pedestal Error  / slice = Mean Pedestal Error  / Number slices
+// - Sigma Pedestal       / slice = Sigma Pedestal       / Sqrt (Number slices)
+// - Sigma Pedestal Error / slice = Sigma Pedestal Error / Sqrt (Number slices)
+// 
+//  Derives from MHCalibrationPix, fits the pedestals to a Gaussian and performs
+//  a Fourier analysis.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include <TH1.h>
+
+ClassImp(MHPedestalPix);
+
+using namespace std;
+//
+const Int_t   MHPedestalPix::fgChargeNbins    = 500;
+const Axis_t  MHPedestalPix::fgChargeFirst    = -49.5;
+const Axis_t  MHPedestalPix::fgChargeLast     = 449.5;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNbins        (fgChargeNbins)
+// - the default number for fFirst        (fgChargeFirst)
+// - the default number for fLast         (fgChargeLast)
+//
+// - the default name of the  fHGausHist ("HPedestalCharge")
+// - the default title of the fHGausHist ("Distribution of Summed FADC Pedestal slices Pixel ")
+// - the default x-axis title for fHGausHist ("Sum FADC Slices")
+// - the default y-axis title for fHGausHist ("Nr. of events")
+// - TH1::Sumw2() for fHGausHist
+//
+// Initializes:
+// - fNSlices to 1
+// - fProbLimit to 0.01
+//
+MHPedestalPix::MHPedestalPix(const char *name, const char *title) 
+    : fNSlices(1.)
+{ 
+
+  fName  = name  ? name  : "MHPedestalPix";
+  fTitle = title ? title : "Histogrammed Pedestal events";
+
+  SetNbins( fgChargeNbins );
+  SetFirst( fgChargeFirst );
+  SetLast(  fgChargeLast  );
+
+  SetProbLimit(0.01);
+
+  // Create a large number of bins, later we will rebin
+  fHGausHist.SetName("HPedestalCharge");
+  fHGausHist.SetTitle("Distribution of Summed FADC Pedestal Slices Pixel ");
+  fHGausHist.SetXTitle("Sum FADC Slices");
+  fHGausHist.SetYTitle("Nr. of events");
+  fHGausHist.Sumw2();
+
+}
+
+// --------------------------------------------------------------------------
+// 
+// If mean and sigma have not yet been set, returns.
+//
+// Renormalizes the pedestal fit results by the following formulae:
+//
+// - Mean Pedestal        / slice = Mean Pedestal        / Number slices
+// - Mean Pedestal Error  / slice = Mean Pedestal Error  / Number slices
+// - Sigma Pedestal       / slice = Sigma Pedestal       / Sqrt (Number slices)
+// - Sigma Pedestal Error / slice = Sigma Pedestal Error / Sqrt (Number slices)
+// 
+void MHPedestalPix::Renorm()
+{
+
+  //
+  // One never knows...
+  //
+  if (fNSlices <= 0)
+    return;
+
+  const Float_t sqslices = TMath::Sqrt(fNSlices);
+
+  SetMean     ( GetMean()    / fNSlices  );
+  //
+  // Mean error goes with PedestalRMS/Sqrt(entries) -> scale with slices
+  // 
+  SetMeanErr  ( GetMeanErr() / fNSlices  );
+  //
+  // Sigma goes like PedestalRMS -> scale with sqrt(slices)    
+  //
+  SetSigma    ( GetSigma()   / sqslices  );
+  //
+  // Sigma error goes like PedestalRMS/2.(entries) -> scale with sqrt(slices)
+  //
+  SetSigmaErr ( GetSigmaErr() / sqslices );
+  
+}
+
Index: /tags/Mars-V0.9/manalysis/MHPedestalPix.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MHPedestalPix.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MHPedestalPix.h	(revision 9772)
@@ -0,0 +1,36 @@
+#ifndef MARS_MHPedestalPix
+#define MARS_MHPedestalPix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+class MHPedestalPix : public MHCalibrationPix
+{
+
+private:
+
+  static const Int_t   fgChargeNbins;        // Default for fNbins   (now set to: 450  )
+  static const Axis_t  fgChargeFirst;        // Default for fFirst   (now set to: -0.5 )
+  static const Axis_t  fgChargeLast;         // Default for fLast    (now set to: 449.5)
+
+  Float_t fNSlices;                         // Number of FADC slices summed in extraction
+  
+public:
+
+  MHPedestalPix(const char *name=NULL, const char *title=NULL);
+  ~MHPedestalPix() {}
+
+  // Setters
+  void SetNSlices( const Float_t n)    { fNSlices = n ; }
+  
+  // Getters
+  Float_t GetNSlices() const       { return fNSlices; }
+  
+  // Others
+  void Renorm();  
+
+  ClassDef(MHPedestalPix, 1)     // Histogram class for Charge Pedestal Pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MHadronness.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MHadronness.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MHadronness.cc	(revision 9772)
@@ -0,0 +1,71 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHadronness
+//
+// The Value must be in the range [0,1]
+// It should be the value used for gamma/hadron seperation.
+// For quality histograms look at MHHadronness
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHadronness.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHadronness);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHadronness::MHadronness(const char *name, const char *title)
+    : fHadronness(-1)
+{
+    fName  = name  ? name  : "MHadronness";
+    fTitle = title ? title : "Storage container for hadroness value";
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset hadroness, -1 indicates: invalid value
+//
+void MHadronness::Reset()
+{
+    fHadronness = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the hillas Parameters to *fLog
+//
+void MHadronness::Print(Option_t *) const
+{
+    *fLog << all << GetDescriptor() << ": Hadronness = " << fHadronness << endl;
+}
+
Index: /tags/Mars-V0.9/manalysis/MHadronness.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MHadronness.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MHadronness.h	(revision 9772)
@@ -0,0 +1,26 @@
+#ifndef MARS_MHadronness
+#define MARS_MHadronness
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHadronness : public MParContainer
+{
+private:
+    Double_t fHadronness; // [0,1] Hadronness
+
+public:
+    MHadronness(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    virtual void Print(Option_t *opt=NULL) const;
+
+    Double_t GetHadronness() const { return fHadronness; }
+    void     SetHadronness(Double_t h) { fHadronness = h; }
+
+    ClassDef(MHadronness, 1) // Storage Container for the hadroness
+};
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MMakePadHistograms.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MMakePadHistograms.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMakePadHistograms.cc	(revision 9772)
@@ -0,0 +1,350 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 09/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMakePadHistograms
+//
+//     reads calibrated data of a particular type (ON, OFF or MC)
+//     and produces the histograms for the padding
+//
+//     these histograms are further treated in MPad
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMakePadHistograms.h"
+
+#include <math.h>
+#include <stdio.h>
+
+#include <TH2.h>
+#include <TH3.h>
+#include <TCanvas.h>
+#include <TFile.h>
+
+#include "MBadPixelsCalc.h"
+#include "MBadPixelsTreat.h"
+#include "MContinue.h"
+#include "MEvtLoop.h"
+#include "MFillH.h"
+#include "MFSelBasic.h"
+#include "MGeomApply.h"
+#include "MHBadPixels.h"
+#include "MHSigmaTheta.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MProgressBar.h"
+#include "MReadMarsFile.h"
+#include "MReadReports.h"
+#include "MTaskList.h"
+//#include "MExtrapolatePointingPos.h"
+#include "MPointingPosCalc.h"
+
+ClassImp(MMakePadHistograms);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MMakePadHistograms::MMakePadHistograms(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MMakePadHistograms";
+  fTitle = title ? title : "Class to make Pad histograms";
+
+  fHSigmaTheta      = NULL;
+  fHSigmaThetaOuter = NULL;
+  fHDiffPixTheta    = NULL;
+  fHSigmaPixTheta   = NULL;
+
+  fHBadIdTheta      = NULL;
+  fHBadNTheta       = NULL;
+
+  // default values
+  fType             = "";
+  fMaxEvents        = -1;
+  fNamePedPhotCam   = "MPedPhotCamFromData";
+  fNameInputFile    = "";
+  fNameOutputFile   = "";
+  fPedestalLevel    = 3.0;
+  fUseInterpolation = kTRUE;
+  fProcessPedestal  = kTRUE;
+  fProcessTime      = kFALSE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// SetDataType. 
+//
+//    the type may be  ON, OFF or MC
+//
+void MMakePadHistograms::SetDataType(const char *type) 
+{
+  fType = type;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetMaxEvents. 
+//
+//    set the maximum number of events to be read
+//
+void MMakePadHistograms::SetMaxEvents(Int_t maxev) 
+{
+  fMaxEvents = maxev;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetNameInputFile. 
+//
+//    the input file contains the calibrated data
+//
+void MMakePadHistograms::SetNameInputFile(const char *input) 
+{
+  fNameInputFile = input;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetNameOutputFile. 
+//
+//    the output file contains the histgrams for the padding
+//
+void MMakePadHistograms::SetNameOutputFile(const char *output) 
+{
+  fNameOutputFile = output;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetNamePedPhotCam. 
+//
+//    set the name of the MPedPhotCam container;
+//    it is used in : MBadPixelsCalc, MBadPixelsTreat, MHSigmaTheta
+//
+void MMakePadHistograms::SetNamePedPhotCam(const char *name) 
+{
+  fNamePedPhotCam = name;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetPedestalLevel. 
+//
+//    set the pedestal level;
+//    it is used in : MBadPixelsCalc
+//
+void MMakePadHistograms::SetPedestalLevel(Float_t pedlevel) 
+{
+  fPedestalLevel = pedlevel;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetUseInterpolation. 
+//
+//    set the option "UseInterpolation";
+//    it is used in : MBadPixelsTreat
+//
+void MMakePadHistograms::SetUseInterpolation(Bool_t useinter) 
+{
+  fUseInterpolation = useinter;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetProcessPedestal. 
+//
+//    set the option "ProcessPedestal";
+//    it is used in : MBadPixelsTreat
+//
+void MMakePadHistograms::SetProcessPedestal(Bool_t procped) 
+{
+  fProcessPedestal = procped;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetProcessTime. 
+//
+//    set the option "ProcessTime";
+//    it is used in : MBadPixelsTreat
+//
+void MMakePadHistograms::SetProcessTime(Bool_t proctim) 
+{
+  fProcessTime = proctim;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MMakePadHistograms::MakeHistograms()
+{
+      if (fType == "")
+      {
+        *fLog << err << "MMakePadHistograms::MakeHistograms;   type of input data is not defined"
+              << endl;
+        return kFALSE;
+      }
+
+      if (fNameInputFile == "")
+      {
+        *fLog << err << "MMakePadHistograms::MakeHistograms;   name of input file is not defined"
+              << endl;
+        return kFALSE;
+      }
+
+      if (fNameOutputFile == "")
+      {
+        *fLog << err << "MMakePadHistograms::MakeHistograms;   name of output file is not defined"
+              << endl;
+        return kFALSE;
+      }
+
+      *fLog << "------------" << endl;
+      *fLog << fType << " events :" << endl;
+      *fLog << "------------" << endl;
+      *fLog << "MMakePadHistograms : calibrated " << fType
+            << "  data are read from file " << fNameInputFile << endl;
+
+
+      MTaskList tlist;
+      MParList  plist;
+
+      MReadReports read;
+      read.AddTree("Drive");
+      read.AddTree("Events","MTime.",kTRUE);
+      static_cast<MRead&>(read).AddFile(fNameInputFile);
+
+      read.AddToBranchList("MReportDrive.*");
+      read.AddToBranchList("MRawEvtHeader.*");
+
+//      MReadMarsFile  read("Events", fNameInputFile);
+//      read.DisableAutoScheme();
+
+
+      MGeomApply apply;
+
+//      MExtrapolatePointingPos extraPointing(fNameInputFile);
+      MPointingPosCalc pointposcalc;
+
+      MBadPixelsCalc badcalc;
+      badcalc.SetNamePedPhotCam(fNamePedPhotCam);
+      badcalc.SetPedestalLevel(fPedestalLevel);
+
+      MBadPixelsTreat badtreat;
+      badtreat.SetNamePedPhotCam(fNamePedPhotCam);
+      badtreat.SetUseInterpolation(fUseInterpolation);
+      badtreat.SetProcessPedestal(fProcessPedestal);
+      badtreat.SetProcessTimes(fProcessTime);
+
+      MFSelBasic selbasic;
+      MContinue contbasic(&selbasic);
+      contbasic.SetName("SelBasic");
+
+      MHBadPixels bad("BadPixels");
+      bad.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillbad("BadPixels[MHBadPixels]", "MBadPixelsCam");
+      fillbad.SetName("FillBad");
+
+      MHSigmaTheta sigth("SigmaTheta");
+      sigth.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillsigtheta ("SigmaTheta[MHSigmaTheta]", "");
+      fillsigtheta.SetName("FillSigTheta");    
+ 
+      //*****************************
+      // entries in MParList
+    
+      plist.AddToList(&tlist);
+      plist.AddToList(&bad);
+      plist.AddToList(&sigth);
+
+      //*****************************
+      // entries in MTaskList
+    
+      tlist.AddToList(&read);
+      tlist.AddToList(&apply);
+      tlist.AddToList(&pointposcalc, "Events");
+
+//      tlist.AddToList(&badcalc);  done in callisto
+//      tlist.AddToList(&badtreat); done in callisto
+
+      tlist.AddToList(&contbasic, "Events");
+      tlist.AddToList(&fillbad, "Events");
+      tlist.AddToList(&fillsigtheta, "Events");
+      //*****************************
+
+      MProgressBar bar;
+      MEvtLoop evtloop;
+      evtloop.SetParList(&plist);
+      evtloop.SetProgressBar(&bar);
+
+      //      if ( !evtloop.Eventloop(fMaxEvents) )
+      //    return kFALSE;
+      evtloop.Eventloop(fMaxEvents);
+
+      tlist.PrintStatistics(0, kTRUE);
+
+      bad.DrawClone();
+      sigth.DrawClone();
+
+      // save the histograms for the padding
+      fHSigmaTheta     = (TH2D*)sigth.GetSigmaTheta();
+      fHSigmaThetaOuter= (TH2D*)sigth.GetSigmaThetaOuter();
+      fHSigmaPixTheta  = (TH3D*)sigth.GetSigmaPixTheta();
+      fHDiffPixTheta   = (TH3D*)sigth.GetDiffPixTheta();
+
+      fHBadIdTheta = (TH2D*)bad.GetBadId();
+      fHBadNTheta  = (TH2D*)bad.GetBadN();
+
+      TFile filewrite(fNameOutputFile, "RECREATE", "");
+      fHSigmaTheta->Write();
+      fHSigmaThetaOuter->Write();
+      //fHSigmaPixTheta->Write();
+      fHDiffPixTheta->Write();
+      //fHBadIdTheta->Write();
+      //fHBadNTheta->Write();
+      filewrite.Close();
+
+      *fLog << "" << endl;
+      *fLog << "MMakePadHistograms : padding plots for " << fType
+            << "  data written onto file " << fNameOutputFile << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMakePadHistograms.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MMakePadHistograms.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMakePadHistograms.h	(revision 9772)
@@ -0,0 +1,73 @@
+#ifndef MARS_MMakePadHistograms
+#define MARS_MMakePadHistograms
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH2D;
+class TH3D;
+
+class MMakePadHistograms : public MH
+{
+private:
+
+    TString  fType;              // type of data to be padded (ON, OFF, MC)
+    Int_t    fMaxEvents;         // maximum no.of events to be read
+    TString  fNamePedPhotCam;    // name of the 'MPedPhotCam' container
+    TString  fNameInputFile;     // name of input file (calibrated data)
+    TString  fNameOutputFile;    // name of output file (Pad histograms)
+    Float_t  fPedestalLevel;     // pedestal level for MBadPixelsCalc
+    Bool_t   fUseInterpolation;  // option for MBadPixelsTreat
+    Bool_t   fProcessPedestal;   // option for MBadPixelsTreat
+    Bool_t   fProcessTime;       // option for MBadPixelsTreat
+
+
+    //----------------------------------
+    // plots needed for the padding
+
+    TH2D  *fHSigmaTheta;      // 2D-histogram (Theta, sigmabar(inner))
+    TH2D  *fHSigmaThetaOuter; // 2D-histogram (Theta, sigmabar(outer))
+    TH3D  *fHDiffPixTheta;  // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/Area)
+    TH3D  *fHSigmaPixTheta; // 3D-histogram (Theta, pixel, sigma)
+
+    TH2D  *fHBadIdTheta;    // 2D-histogram (Theta, Id of bad pixel)
+    TH2D  *fHBadNTheta;     // 2D-histogram (Theta, no.of bad pixels)
+
+
+public:
+    MMakePadHistograms(const char *name=NULL, const char *title=NULL);
+ 
+    void SetDataType(const char *);       // type of data (ON, OFF, MC) 
+    void SetMaxEvents(Int_t);             // mx. no.of events to be read 
+    void SetNameInputFile(const char *);  // Calibrated data   
+    void SetNameOutputFile(const char *); // Pad histograms 
+    void SetNamePedPhotCam(const char *); // "MPedPhotCamFromData"
+
+    // parameters for MBadPixelsCalc
+    void SetPedestalLevel(Float_t);
+
+    // parameters for MBadPixelsTreat
+    void SetUseInterpolation(Bool_t);
+    void SetProcessPedestal(Bool_t);
+    void SetProcessTime(Bool_t);
+
+    Bool_t MakeHistograms();
+
+    ClassDef(MMakePadHistograms, 0)    // class for making the padding histograms 
+}; 
+
+#endif
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMarquardt.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MMarquardt.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMarquardt.cc	(revision 9772)
@@ -0,0 +1,414 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 10/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MMarquardt                                                              //
+//                                                                         //
+// Marquardt method of solving nonlinear least-squares problems            //
+//                                                                         //
+// (see Numerical recipes (2nd ed.), W.H.Press et al., p.688 ff)           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MMarquardt.h"
+
+#include <math.h>            // fabs 
+
+#include <TVectorD.h>
+#include <TMatrixD.h>
+
+#include <TStopwatch.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParContainer.h"
+
+ClassImp(MMarquardt);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMarquardt::MMarquardt(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMarquardt";
+    fTitle = title ? title : "Marquardt minimization";
+}
+
+// -----------------------------------------------------------------------
+//
+// Set - the number of parameters
+//     - the maximum number of steps allowed in the minimization and
+//     - the change in chi2 signaling convergence
+
+void MMarquardt::SetNpar(Int_t numpar, Int_t numstepmax, Double_t loopchi2)
+{
+  fNpar       = numpar;
+  fNumStepMax = numstepmax;
+  fLoopChi2   = loopchi2;
+
+  fdParam.ResizeTo(fNpar);
+
+  fParam.ResizeTo(fNpar);
+  fGrad.ResizeTo(fNpar);
+  fCovar.ResizeTo(fNpar, fNpar);  
+
+  fmyParam.ResizeTo(fNpar);
+  fmyGrad.ResizeTo(fNpar);
+  fmyCovar.ResizeTo(fNpar, fNpar);  
+
+  fIxc.ResizeTo(fNpar);
+  fIxr.ResizeTo(fNpar);
+  fIp.ResizeTo(fNpar);
+}
+
+
+// -----------------------------------------------------------------------
+//
+// do the minimization
+//
+// fcn    is the function which calculates for a given set of parameters
+//        - the function L to be minimized
+//        - beta_k  = -1/2 * dL/da_k          (a kind of gradient of L)
+//        - alfa_kl =  1/2 * dL/(da_k da_l)   (a kind of 2nd derivative of L)
+//                              
+// Vinit  contains the starting values of the parameters
+//
+
+Int_t MMarquardt::Loop( 
+          Bool_t (*fcn)(TVectorD &, TMatrixD &, TVectorD &, Double_t &),
+          TVectorD &Vinit)
+{
+  fFunc = fcn; 
+
+  // set the initial parameter values
+  for (Int_t i=0; i<fNpar; i++)
+    fParam(i) = Vinit(i);
+
+  //-------------------------------------------
+  // first call of the function func
+  Bool_t rcfirst = FirstCall();
+  if (!rcfirst)
+  {
+    *fLog << "MMarquardt::Loop; first call of function failed " << endl;
+    return -1;
+  }
+
+  Double_t oldChi2  = fChi2;
+  Double_t fdChi2   = 1.e10;
+  Int_t    fNumStep = 0;
+
+  //-------------------------------------------
+  // do the next step in the minimization
+  Bool_t rcnext;
+  do
+  {
+    fNumStep++;
+
+    rcnext = NextStep();
+    if (!rcnext) break;
+
+    fdChi2 = fabs(oldChi2-fChi2);
+    oldChi2 = fChi2;
+  } while (fdChi2 > fLoopChi2  &&  fNumStep < fNumStepMax);
+
+  //-------------------------------------------
+  // do the final calculations
+  if (!rcnext)
+  {
+    *fLog << "MMarquardt::Loop; function call failed in step " << fNumStep
+          << endl;
+    return -2;
+  }
+
+  if (fdChi2 > fLoopChi2)
+  {
+    *fLog << "MMarquardt::Loop; minimization has not converged, fChi2, fdChi2 = "
+          << fChi2 << ",  " << fdChi2 << endl;
+    return -3;
+  }
+
+  *fLog << "MMarquardt::Loop; minimization has converged, fChi2, fdChi2, fNumStep = "
+        << fChi2 << ",  " << fdChi2 << ",  " << fNumStep << endl;
+
+
+  Bool_t rccov = CovMatrix();
+  if (!rccov)
+  {
+    *fLog << "MMarquardt::Loop; calculation of covariance matrix failed " 
+          << endl;
+    return 1;
+  }
+
+  //-------------------------------------------
+  // results
+
+  *fLog << "MMarquardt::Loop; Results of fit : fChi2, fNumStep, fdChi2 =" 
+        << fChi2 << ",  " << fNumStep << ",  " << fdChi2 << endl;
+
+  for (Int_t i=0; i<fNpar; i++)
+    fdParam(i) = sqrt(fCovar(i,i));
+
+  *fLog << "MMarquardt::Loop;   i, Param(i), dParam(i)" << endl;
+  for (Int_t i=0; i<fNpar; i++)
+  {
+    *fLog << i << "   " << fParam(i) << "   " << fdParam(i) << endl;
+  }
+
+  *fLog << "MMarquardt::Loop; Covariance matrix" << endl;
+  for (Int_t i=0; i<fNpar; i++)
+  {
+    *fLog << i;
+    for (Int_t j=0; j<fNpar; j++)
+    {
+      *fLog << fCovar(i,j) << "   ";
+    }
+    *fLog << endl;
+  }
+
+  return 0;
+}
+
+
+// -----------------------------------------------------------------------
+//
+// do 1st step of the minimization
+//
+
+Bool_t MMarquardt::FirstCall()
+{
+  fLambda = 0.001;
+  Bool_t rc = (*fFunc)(fParam, fCovar, fGrad, fChi2);
+  if (!rc) return kFALSE;
+
+  fCHIq = fChi2;
+  for (Int_t j=0; j<fNpar; j++)
+    fmyParam(j) = fParam(j);    
+
+  return kTRUE;
+}
+
+
+// -----------------------------------------------------------------------
+//
+// do one step of the minimization
+//
+
+Bool_t MMarquardt::NextStep()
+{
+  for (Int_t j=0; j<fNpar; j++)
+  {
+    for (Int_t k=0; k<fNpar; k++)
+      fmyCovar(j,k) = fCovar(j,k);
+
+    fmyCovar(j,j) *= (1.0 + fLambda);
+    fmyGrad(j) = fGrad(j);
+  }
+
+  Bool_t rgj = GaussJordan(fNpar, fmyCovar, fmyGrad);
+  if(!rgj) return kFALSE;
+
+  for (Int_t j=0; j<fNpar; j++)
+    fmyParam(j) = fParam(j) + fmyGrad(j);
+
+  Bool_t rc = (*fFunc)(fmyParam, fmyCovar, fmyGrad, fChi2);
+  if(!rc) return kFALSE;
+
+  if (fChi2 < fCHIq)
+  {
+    fLambda *= 0.1;
+    fCHIq = fChi2;
+
+    for (Int_t j=0; j<fNpar; j++)
+    {
+      for (Int_t k=0; k<fNpar; k++)
+        fCovar(j,k) = fmyCovar(j,k);
+
+      fGrad(j)  = fmyGrad(j);
+      fParam(j) = fmyParam(j);
+    }
+  }
+    else
+      fLambda *= 10.0;
+
+
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// calculate error matrix of fitted parameters
+//
+
+Bool_t MMarquardt::CovMatrix()
+{
+  Bool_t rc = (*fFunc)(fParam, fCovar, fGrad, fChi2);
+  if(!rc) return kFALSE;
+
+  for (Int_t j=0; j<fNpar; j++)
+  {
+    for (Int_t k=0; k<fNpar; k++)
+      fmyCovar(j,k) = fCovar(j,k);
+
+    fmyCovar(j,j) *= (1.0 + fLambda);
+    fmyGrad(j) = fGrad(j);
+  }
+
+  Bool_t rgj = GaussJordan(fNpar, fmyCovar, fmyGrad);
+  if(!rgj) return kFALSE;
+
+  for (Int_t j=0; j<fNpar; j++)
+  {
+    for (Int_t k=0; k<fNpar; k++)
+      fCovar(j,k) = fmyCovar(j,k);
+  }
+
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// solve normal equations 
+//
+//       sum(covar_kl * x_l) = beta_k        (k=0,... (n-1)) 
+//
+// by the Gauss-Jordan method
+// (see Numerical recipes (2nd ed.), W.H.Press et al., p.39) 
+//
+// on return :  covar contains the inverse of the input matrix covar
+//              beta  contains the result for x
+//
+// return value =  kTRUE   means OK
+//                 kFALSE  means singular matrix
+//
+                 
+Bool_t MMarquardt::GaussJordan(Int_t &n, TMatrixD &covar, TVectorD &beta)
+{
+  Int_t      i, j, k, l, ll;
+  Int_t      ic = 0;
+  Int_t      ir = 0;
+  Double_t   h, d, p;
+
+  for (j=0; j<n; j++)
+    fIp(j) = 0;
+
+  for (i=0; i<n; i++)
+  {
+    h = 0.0;
+    for (j=0; j<n; j++)
+    {
+      if (fIp(j) != 1)
+      {
+        for (k=0; k<n; k++)
+	{
+          if (fIp(k) == 0)
+	  {
+            if (fabs(covar(j,k)) >= h)
+	    {
+              h = fabs(covar(j,k));
+              ir = j;
+              ic = k;
+	    }
+	  }
+          else
+	  {
+            if (fIp(k) > 1) return kFALSE; 
+	  }
+	}
+      }
+    }
+
+    fIp(ic)++;
+    if (ir != ic)
+    {
+      for (l=0; l<n; l++)
+      {
+        d = covar(ir,l);
+        covar(ir,l) = covar(ic,l);
+        covar(ic,l) = d;
+      }
+      d = beta(ir);
+      beta(ir) = beta(ic);
+      beta(ic) = d;
+    }
+
+    fIxr(i) = ir;
+    fIxc(i) = ic;
+    if (covar(ic,ic) == 0.0) return kFALSE;
+    p = 1.0 / covar(ic,ic);
+    covar(ic,ic) = 1.0;
+
+    for (l=0; l<n; l++)
+      covar(ic,l) *= p;
+
+    beta(ic) *= p;
+
+    for (ll=0; ll<n; ll++)
+    {
+      if (ll!= ic)
+      {
+        d = covar(ll,ic);
+        covar(ll,ic) = 0.0;
+
+        for (l=0; l<n; l++)
+          covar(ll,l) -= covar(ic,l) * d;
+
+        beta(ll) -= beta(ic) * d;
+      }
+    }
+  }
+
+  for (l=n-1; l>=0; l--)
+  {
+    if (fIxr(l) != fIxc(l))
+    {
+      for (k=0; k<n; k++)
+      {
+        d = covar(k,fIxr(l));
+        covar(k,fIxr(l)) = covar(k,fIxc(l));
+        covar(k,fIxc(l)) = d;
+      }
+    }
+  }
+
+  return kTRUE;
+}
+//=========================================================================
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMarquardt.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MMarquardt.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMarquardt.h	(revision 9772)
@@ -0,0 +1,96 @@
+#ifndef MARS_MMarquardt
+#define MARS_MMarquardt
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TVectorD
+#include "TVectorD.h"
+#endif
+
+#ifndef ROOT_TMatrixD
+#include "TMatrixD.h"
+#endif
+
+
+class MMarquardt : public MParContainer
+{
+private:
+
+  Int_t fNumStepMax;  // maximum number of steps allowed in the minimization
+  Double_t fLoopChi2; // minimization will stop when the change in chi2 
+                      // is less than fLoopChi2
+
+  Int_t    fNpar;          // number of parameters
+  Int_t    fNumStep;       // number of steps made
+  Double_t fChi2;          // final chi2
+  Double_t fdChi2;         // change of chi2 in last step
+
+  // working space for Marquardt
+  TVectorD fdParam;
+
+  TVectorD fParam;
+  TMatrixD fCovar;
+  TVectorD fGrad;
+
+  TVectorD fmyParam;
+  TMatrixD fmyCovar;
+  TVectorD fmyGrad;
+
+  Double_t fCHIq;
+  Double_t fLambda;
+  Bool_t   (*fFunc)(TVectorD &, TMatrixD &, TVectorD &, Double_t &);
+
+  //working space for GaussJordan
+  TVectorD fIxc, fIxr, fIp;
+
+  Bool_t FirstCall();
+  Bool_t NextStep();
+  Bool_t CovMatrix();
+  Bool_t GaussJordan(Int_t &n, TMatrixD &covar, TVectorD &beta);
+
+
+public:
+    MMarquardt(const char *name=NULL, const char *title=NULL);
+    ~MMarquardt();
+
+    void SetNpar(Int_t npar, Int_t numstepmax, Double_t loopchi2);
+
+    Int_t Loop(Bool_t (*fcn)(TVectorD &, TMatrixD &, TVectorD &, Double_t &),
+               TVectorD &);
+
+    ClassDef(MMarquardt, 0) // Class for Marquardt minimization
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMatrixLoop.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MMatrixLoop.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMatrixLoop.cc	(revision 9772)
@@ -0,0 +1,90 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  9/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMatrixLoop
+//
+// Use this task instead of reading from a file. It loops through the rows
+// of a given MHMatrix. PreProcessing the task again starts from scratch.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMatrixLoop.h"
+
+#include "MHMatrix.h"
+#include "MLog.h"
+
+ClassImp(MMatrixLoop);
+
+const TString MMatrixLoop::gsDefName  = "MRead";
+const TString MMatrixLoop::gsDefTitle = "Loop through a MHMatrix (instead of reading from a file)";
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor. Specify the MHMatrix object you want to loop
+//  through.
+//
+MMatrixLoop::MMatrixLoop(MHMatrix *mat, const char *name, const char *title) : fMatrix(mat)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of events (rows) in the matrix
+//
+UInt_t MMatrixLoop::GetEntries()
+{
+    return fMatrix ? fMatrix->GetNumRows() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return name of MHMatrix, <n/a> if not available
+// The name of the matrix must nor contain a '/'
+//
+TString MMatrixLoop::GetFullFileName() const
+{
+    return fMatrix ? fMatrix->GetName() : "<n/a>";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MMatrixLoop::PreProcess(MParList *plist)
+{
+    fNumRow = 0;
+
+    return fMatrix ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the present row of the Matrix, stops the loop when all rows have
+// been accessed.
+//
+Int_t MMatrixLoop::Process()
+{
+    return fMatrix->SetNumRow(fNumRow++);
+}
Index: /tags/Mars-V0.9/manalysis/MMatrixLoop.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MMatrixLoop.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMatrixLoop.h	(revision 9772)
@@ -0,0 +1,38 @@
+#ifndef MARS_MMatrixLoop
+#define MARS_MMatrixLoop
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MHMatrix;
+
+class MMatrixLoop : public MRead
+{
+private:
+    // MMatrixLoop
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    MHMatrix *fMatrix;
+    Int_t     fNumRow;    //! Number of dimensions of histogram
+
+    // MRead
+    UInt_t  GetEntries();
+    TString GetFullFileName() const;
+    Bool_t  Rewind() { fNumRow=0; return kTRUE; }
+
+    virtual Int_t AddFile(const char *fname, Int_t entries=-1) { return 0; }
+    Int_t AddFiles(MDirIter &dir) { return 0; }
+
+    // MTask
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MMatrixLoop(MHMatrix *mat, const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MMatrixLoop, 0) // Task 'reading' events from a MHMatrix
+};
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MMcCalibrationUpdate.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MMcCalibrationUpdate.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMcCalibrationUpdate.cc	(revision 9772)
@@ -0,0 +1,429 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 12/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMcCalibrationUpdate
+//
+//  This task looks for the ìnformation about FADC pedestals in
+//  MMcFadcHeader and translates it to the pedestal mean and rms (in adc counts).
+//  If not already existing in the parameter list, an MCalibrationCam object
+//  is created, with the conversion factor between ADC counts and photons or 
+//  photoelectrons (depending on fSignalType) is set to 1 to allow the analysis 
+//  to proceed.
+//
+//  Then it creates and fills also the MPedPhotCam object containing the pedestal
+//  mean and rms in units of photons or photoelectrons.
+//
+//  Input Containers:
+//   MMcFadcHeader
+//   MRawRunHeader
+//  [MCalibrationChargeCam] (if it existed previously)
+//  [MCalibrationQECam] (if it existed previously)
+//
+//  Output Containers:
+//   MPedPhotCam
+//  [MCalibrationChargeCam] (if it did not exist previously)
+//  [MCalibrationQECam] (if it did not exist previously)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcCalibrationUpdate.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargeCam.h"
+
+#include "MCalibrationQEPix.h"
+#include "MCalibrationQECam.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+#include "MGeomCam.h"
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MRawRunHeader.h"
+#include "MMcRunHeader.hxx"
+#include "MMcFadcHeader.hxx"
+#include "MMcConfigRunHeader.h"
+#include "MCalibrateData.h"
+
+ClassImp(MMcCalibrationUpdate);
+
+using namespace std;
+
+MMcCalibrationUpdate::MMcCalibrationUpdate(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcCalibrationUpdate";
+    fTitle = title ? title : "Write MC pedestals and conversion factors into MCalibration Container";
+
+
+    fAmplitude = -1.;
+    fAmplitudeOuter = -1.;
+    fConversionHiLo = -1.;
+
+    fSignalType = MCalibrateData::kPhot;
+
+    fFillCalibrationCam = kTRUE;
+    fOuterPixelsGainScaling = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the run type. Return kTRUE if it is a MC run or if there
+// is no MC run header (old camera files) kFALSE in case of a different
+// run type
+//
+Bool_t MMcCalibrationUpdate::CheckRunType(MParList *pList) const
+{
+    const MRawRunHeader *run = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!run)
+    {
+        *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+        return kTRUE;
+    }
+
+    return run->IsMonteCarloRun();
+}
+
+// --------------------------------------------------------------------------
+//
+// Make sure, that there is an MCalibrationCam Object in the Parameter List.
+//
+Int_t MMcCalibrationUpdate::PreProcess(MParList *pList)
+{
+    fCalCam = (MCalibrationChargeCam*) pList->FindObject(AddSerialNumber("MCalibrationChargeCam"));
+    fQECam = (MCalibrationQECam*) pList->FindObject(AddSerialNumber("MCalibrationQECam"));
+
+    if (!fCalCam || !fQECam)
+    {
+        fCalCam = (MCalibrationChargeCam*) pList->FindCreateObj(AddSerialNumber("MCalibrationChargeCam"));
+        fQECam = (MCalibrationQECam*) pList->FindCreateObj(AddSerialNumber("MCalibrationQECam"));
+        if (!fCalCam || !fQECam)
+            return kFALSE;
+    }
+    else
+    {
+        fFillCalibrationCam = kFALSE;
+        *fLog << inf << AddSerialNumber("MCalibrationChargeCam") << " and " <<
+	  AddSerialNumber("MCalibrationQECam") << " already exist... " << endl;
+    }
+
+    fPedPhotCam = (MPedPhotCam*) pList->FindCreateObj(AddSerialNumber("MPedPhotCam"));
+    if (!fPedPhotCam)
+        return kFALSE;
+
+    fSignalCam = (MExtractedSignalCam*) pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+    if (!fSignalCam)
+    {
+        *fLog << err << AddSerialNumber("MExtractedSignalCam") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the runtype.
+// Search for MGeomCam and MMcFadcHeader.
+// Fill the MCalibrationCam object.
+//
+Bool_t MMcCalibrationUpdate::ReInit(MParList *pList)
+{
+    //
+    // If it is no MC file skip this function...
+    //
+    if (!CheckRunType(pList))
+    {
+        *fLog << inf << "This is no MC file... skipping." << endl;
+        return kTRUE;
+    }
+	
+    //
+    // Now check the existence of all necessary containers.
+    //
+    fGeom = (MGeomCam*) pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeom)
+    {
+        *fLog << err << AddSerialNumber("MGeomCam") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHeaderFadc = (MMcFadcHeader*)pList->FindObject(AddSerialNumber("MMcFadcHeader"));
+    if (!fHeaderFadc)
+    {
+        *fLog << err << AddSerialNumber("MMcFadcHeader") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    MMcRunHeader* mcrunh = (MMcRunHeader*) pList->FindObject("MMcRunHeader");
+
+    //
+    // Initialize Fadc simulation parameters:
+    //
+    if (fAmplitude < 0)
+    {
+	fAmplitude = fHeaderFadc->GetAmplitud();
+	if (mcrunh->GetCamVersion() > 60)
+	  {
+	    fAmplitudeOuter = fHeaderFadc->GetAmplitudOuter();
+	    fConversionHiLo = fHeaderFadc->GetLow2HighGain();
+	  }
+	else // old MC files, camera  < v0.7
+	  {
+	    fAmplitudeOuter = fAmplitude;
+	    fConversionHiLo = 10;  // dummy value
+	  }
+
+    }
+    else   // Check that following files have all the same FADC parameters
+    {
+      if ( fabs(fHeaderFadc->GetAmplitud()-fAmplitude) > 1.e-6 )
+	{
+	  *fLog << err << "Parameters of MMcFadcHeader are not the same for all files... aborting." << endl;
+	  return kFALSE;
+	}
+
+      if (mcrunh->GetCamVersion() > 60) // old MC files, camera < v0.7
+	{
+	  if( fabs(fHeaderFadc->GetAmplitudOuter()-fAmplitudeOuter) > 1.e-6  ||
+	      fabs(fConversionHiLo-fHeaderFadc->GetLow2HighGain())  > 1.e-6 )
+	    {
+	      *fLog << err << "Parameters of MMcFadcHeader are not the same for all files... aborting." << endl;
+	      return kFALSE;
+	    }
+	}
+    }
+
+    //
+    // If MCalibrationChargeCam and MCalibrationQECam already existed 
+    // in the parameter list before MMcCalibrationUpdate::PreProcess was 
+    // executed (from a previous calibration loop) we must not fill them, 
+    // hence nothing else has to be done in ReInit:
+    //
+    if (!fFillCalibrationCam)
+        return kTRUE;
+
+    // Now check the light collection for inner and outer pixels to
+    // calculate the ratio between the two. FIXME! Light collection
+    // depends on the incidence angle of the light w.r.t. the camera
+    // plane. For the moment we take the ratio for light impinging
+    // perpendicular to the camera plane.
+    //
+    // FIXME! We look for AddSerialNumber("MMcConfigRunHeader") but
+    // for the moment the stereo version of camera does not write one such
+    // header per telescope (it should!)
+    //
+    MMcConfigRunHeader* mcconfig = (MMcConfigRunHeader*) pList->FindObject(AddSerialNumber("MMcConfigRunHeader"));
+    if (!mcconfig)
+    {
+        *fLog << err << AddSerialNumber("MMcConfigRunHeader") << 
+	  " not found... aborting." << endl;
+        return kFALSE;
+    }
+    TArrayF innerlightcoll = mcconfig->GetLightCollectionFactor();
+    TArrayF outerlightcoll = mcconfig->GetLightCollectionFactorOuter();
+
+    // In principle outer pixels seem to have a different average light 
+    // collection efficiency than outer ones. We set here the factor between
+    // the two.
+
+    fOuterPixelsLightCollection = outerlightcoll[90] / innerlightcoll[90]; 
+    // (at angle = 90 deg)
+
+    // Set now the default conversion from ADC counts to photoelectrons 
+    // (in case no previous calibration existed in the parameter list).
+    //
+    // As default we want to have SIZE in ADC counts, or rather, in "inner pixel
+    // equivalent ADC counts".
+    //
+    // To achieve this:
+    // - In the case fSignalType==kPhot: we set the ADC to photoelectron conversion 
+    // equal to the QE, which will later make the ADC to photon conversion factor 
+    // (= ADC2PhotEl/QE) to be = 1, 
+    //
+    // - In the case fSignalType==kPhe: we set the ADC to photoelectron conversion 
+    // equal to 1, since this will be applied directly to the signals...
+
+    if (fSignalType == MCalibrateData::kPhot)
+      fADC2PhElInner = MCalibrationQEPix::gkDefaultAverageQE;
+    else
+      fADC2PhElInner = 1.;
+
+    //
+    // Set the default ADC to "photoelectrons" conversion factor for outer 
+    // pixels. One can choose not to apply the known (in MC) gain factor 
+    // between inner and outer pixels, (in case fOuterPixelsGainScaling = kFALSE),
+    // which may be useful for display purposes.
+    // If on the contrary we apply the factor, we must take into account the 
+    // different gains photoelectrons->ADC counts, given in MC by fAmplitude
+    // and fAmplitudeOuter. This "default" calibration is such that a shower
+    // completely contained in the inner part would have Size in ADC counts, 
+    // whereas one partially in the outer part would have Size in "equivalent 
+    // inner ADC counts" : the "same" shower (light density distribution) would
+    // have the same Size no matter where in the camera it lies. For this we have 
+    // also to set later (see below) the right QE for outer pixels, which may 
+    // be different from that of inner pixels.
+    //
+
+    if (fOuterPixelsGainScaling)
+      fADC2PhElOuter = fADC2PhElInner
+	* (fAmplitude / fAmplitudeOuter);
+    else
+      fADC2PhElOuter = fADC2PhElInner;
+
+
+    Int_t num = fCalCam->GetSize();
+
+    fCalCam->SetFFactorMethodValid   ( kTRUE );
+    fQECam->SetFFactorMethodValid    ( kTRUE );
+    fQECam->SetBlindPixelMethodValid ( kTRUE );
+    fQECam->SetCombinedMethodValid   ( kTRUE );
+    fQECam->SetPINDiodeMethodValid   ( kTRUE );  
+    
+    for (Int_t i=0; i<num; i++)
+    {
+        MCalibrationChargePix &calpix = (MCalibrationChargePix&)(*fCalCam)[i];
+
+	calpix.SetFFactorMethodValid();
+
+	calpix.SetConversionHiLo(fConversionHiLo);
+	calpix.SetConversionHiLoErr(0.);         // FIXME ?
+
+	//
+	// Write conversion factor ADC to photo-electrons (different for inner
+	// and outer pixels).
+	//
+	Float_t adc2photel = (fGeom->GetPixRatio(i) < fGeom->GetPixRatio(0))?
+	  fADC2PhElOuter : fADC2PhElInner;
+
+
+	calpix.SetMeanConvFADC2Phe(adc2photel);
+        calpix.SetMeanConvFADC2PheVar(0.);
+        calpix.SetMeanFFactorFADC2Phot(0.); // Not used for now.
+
+    }
+
+    //
+    // Now set the average QE for each type of pixels. Correct outer pixels
+    // for different light collection efficiency.
+    //
+    num = fQECam->GetSize();
+    for (Int_t i=0; i<num; i++)
+    {
+        MCalibrationQEPix &qepix = (MCalibrationQEPix&)(*fQECam)[i];
+
+	Float_t avqe = MCalibrationQEPix::gkDefaultAverageQE;
+
+	if (fOuterPixelsGainScaling)
+	  if (fGeom->GetPixRatio(i) < fGeom->GetPixRatio(0))
+	    avqe = MCalibrationQEPix::gkDefaultAverageQE*fOuterPixelsLightCollection;
+
+	qepix.SetAvNormFFactor(1.);
+	// This factor should convert the default average QE to average QE 
+	// for a spectrum like that of Cherenkov light. See the documentation 
+	// of MCalibrationQEPix. Here it is 1 because we calibrate using 
+	// Cherenkov light.
+
+	qepix.SetAverageQE(avqe);
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the MCerPhotPed object
+//
+// This has to be done on an event by event basis because the (calibrated) pedestal 
+// fluctuations depend on whether, for each pixel, we are using the high gain or the 
+// low gain branch.
+//
+Int_t MMcCalibrationUpdate::Process()
+{
+    const Int_t num = fCalCam->GetSize();
+
+    for (Int_t i=0; i<num; i++)
+    {
+	MExtractedSignalPix &sigpix = (*fSignalCam)[i];
+
+	//
+	// ped mean and rms per pixel, in ADC counts, according to signal 
+	// calculation (hi or low gain and number of integrated slices):
+	//
+        const Float_t pedestmean = sigpix.IsLoGainUsed()? 
+	  fSignalCam->GetNumUsedLoGainFADCSlices()*fHeaderFadc->GetPedestal(i) : 
+	  fSignalCam->GetNumUsedHiGainFADCSlices()*fHeaderFadc->GetPedestal(i);
+
+	//
+	// In some cases, depending on the camera simulation parameters, one can
+	// have very little or no noise in the FADC. In the case the rms of  
+	// pedestal is zero, the pixel will be cleaned out later in the image
+	// cleaning. To avoid this problem,we set a default value of 0.01 ADC
+	// counts for the RMS per slice:
+	//
+        const Double_t used = (Double_t)(sigpix.IsLoGainUsed() ?
+                                         fSignalCam->GetNumUsedLoGainFADCSlices() :
+                                         fSignalCam->GetNumUsedHiGainFADCSlices());
+
+        const Float_t rms0 = sigpix.IsLoGainUsed() ?
+            fHeaderFadc->GetPedestalRmsLow(i) :
+            fHeaderFadc->GetPedestalRmsHigh(i);
+
+        const Float_t pedestrms = TMath::Sqrt(used) * (rms0>0 ? rms0 : 0.01);
+
+	//
+	// Write mean pedestal and pedestal rms per pixel
+	// in number of photons:
+	//
+	MPedPhotPix &pedpix = (*fPedPhotCam)[i];
+
+        MCalibrationChargePix &calpix = (MCalibrationChargePix&)(*fCalCam)[i];
+        MCalibrationQEPix &qepix = (MCalibrationQEPix&)(*fQECam)[i];
+
+        Float_t qe       = qepix.GetAverageQE();
+
+
+	Float_t conv = (fSignalType == MCalibrateData::kPhot? 
+	  calpix.GetMeanConvFADC2Phe() / qe  :
+	  calpix.GetMeanConvFADC2Phe());
+
+	Float_t hi2lo    = calpix.GetConversionHiLo();
+
+	if (sigpix.IsLoGainUsed())
+            pedpix.Set(conv*hi2lo*pedestmean, conv*hi2lo*pedestrms);
+	else
+            pedpix.Set(conv*pedestmean, conv*pedestrms);
+
+    }
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/manalysis/MMcCalibrationUpdate.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MMcCalibrationUpdate.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMcCalibrationUpdate.h	(revision 9772)
@@ -0,0 +1,72 @@
+#ifndef MARS_MMcCalibrationUpdate
+#define MARS_MMcCalibrationUpdate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MCalibrateData
+#include "MCalibrateData.h"
+#endif
+
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MPedPhotCam;
+class MGeomCam;
+class MMcFadcHeader;
+class MExtractedSignalCam;
+
+#include "MCalibrateData.h"
+
+class MMcCalibrationUpdate : public MTask
+{
+private:
+    Bool_t CheckRunType(MParList *pList) const;
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Bool_t ReInit(MParList *pList);
+
+    MCalibrationChargeCam *fCalCam;
+    MCalibrationQECam     *fQECam;    
+    MPedPhotCam           *fPedPhotCam;
+    MGeomCam              *fGeom;
+    MMcFadcHeader         *fHeaderFadc;
+    MExtractedSignalCam   *fSignalCam;
+
+    Float_t fADC2PhElInner; // Conversion factor from ADC counts to photo-electrons
+    Float_t fADC2PhElOuter; // for inner and outer pixels.
+
+    Bool_t  fFillCalibrationCam;
+    Bool_t  fOuterPixelsGainScaling;
+
+    Float_t fAmplitude;      // FADC parameters from camera simulation (see camera manual)
+    Float_t fAmplitudeOuter; // to be read from the MMcFadcHeader.
+    Float_t fConversionHiLo; // Ratio of high to low gain.
+
+    Float_t fOuterPixelsLightCollection; 
+    // Photon collection efficiency of outer pixels w.r.t. inner ones.
+
+    MCalibrateData::SignalType_t fSignalType;  
+    // Type defined in MCalibrateData.h. Indicates whether calibration is 
+    // made in photons or in photoelectrons! Default: MCalibrateData::kPhe
+
+    
+public:
+    MMcCalibrationUpdate(const char *name=NULL, const char *title=NULL);
+
+    void SetOuterPixelsGainScaling(Bool_t tf) 
+      { fOuterPixelsGainScaling = tf; }
+
+    void SetSignalType (MCalibrateData::SignalType_t x) { fSignalType = x; }
+    MCalibrateData::SignalType_t GetSignalType () const { return fSignalType; }
+
+    ClassDef(MMcCalibrationUpdate, 0)   // Task which obtains, for MC files, the pedestal mean and rms, and the calibration factor from ADC counts to photons. 
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMcTriggerLvl2.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MMcTriggerLvl2.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMcTriggerLvl2.cc	(revision 9772)
@@ -0,0 +1,1040 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Antonio Stamerra  1/2003 <mailto:antono.stamerra@pi.infn.it>
+!   Author(s): Marcos Lopez 1/2003 <mailto:marcos@gae.ucm.es>
+!   Author(s): Nicola Galante 7/2003 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MMcTriggerLvl2                                                          //
+//   Storage container for the 2nd level trigger selection parameters      //
+//    as part of the 2nd level trigger simulation                          //
+//                                                                         //
+// input parameter:                                                        //
+//    fCompactNN number of next neighboors that define a compact pixel     //
+//                                                                         //
+//                                                                         //
+// Basic L2T Selection Parameters:                                         //
+//                                                                         //
+//    fLutPseudoSize number of compact pixels in one LUT                   //
+//    fPseudoSize Multiplicity of the bigger cluster                       //
+//    fSizeBiggerCell higher number of fired pixel in cell                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MMcTriggerLvl2.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MGeomCamMagic.h"
+
+#include "MMcTrig.hxx"
+
+#include "MMcEvt.hxx"
+
+#include "MLog.h"
+
+#include <TCanvas.h>
+
+ClassImp(MMcTriggerLvl2);
+
+using namespace std;
+
+// ---------------------------
+// Initialization of static const data members pixel_in_cell and pixel_in_lut
+
+//
+// Correspondence TABLE between pixel numbering in the trigger cells and
+// the standard spiral counting 
+// (*Note*: Pixels start to count ** from 1 ** instead of 0)
+//
+// This correspondence is valid only for MAGIC-like geometries!
+//
+//  FIXME!  These definitions should be included in a GeomTrig class
+//
+const  Int_t  MMcTriggerLvl2::gsPixelsInCell[gsNPixInCell][gsNCells] = {
+    {26,  91,  66,  71,  76,  81,  86,  269,  224,  233,  242,  251,  260,  391,  336,  347,  358,	369,  380},
+    {25,  61,  41,  45,  49,  53,  57,  215,  175,  183,  191,  199,  207,  325,  275,  285,  295,  305,  315},
+    {24,  37,  22,  25,  28,  31,  34,  167,  132,  139,  146,  153,  160,  265,  220,  229,  238,  247,  256},
+    {23,  19,   9,  11,  13,  15,  17,  125,   95,  101,  107,  113,  119,  211,  171,  179,  187,  195,  203},
+    {27,  62,  67,  72,  77,  82,  87,  270,  225,  234,  243,  252,  261,  392,  337,  348,  359,  370,  381},
+    {12,  38,  42,  46,  50,  54,  58,  216,  176,  184,  192,  200,  208,  326,  276,  286,  296,  306,  316},
+    {11,  20,  23,  26,  29,  32,  35,  168,  133,  140,  147,  154,  161,  266,  221,  230,  239,  248,  257},
+    {10,   8,  10,  12,  14,  16,  18,  126,   96,  102,  108,  114,  120,  212,  172,  180,  188,  196,  204},
+    {22,   2,   3,   4,   5,   6,   7,   90,   65,   70,   75,   80,   85,  164,  129,  136,  143,  150,  157},
+    {28,  93,  99, 105, 111, 117, 123,  271,  226,  235,  244,  253,  262,  393,  338,  349,  360,  371,  382},
+    {13,  63,  68,  73,  78,  83,  88,  217,  177,  185,  193,  201,  209,  327,  277,  287,  297,  307,  317},
+    { 4,  39,  43,  47,  51,  55,  59,  169,  134,  141,  148,  155,  162,  267,  222,  231,  240,  249,  258},
+    { 3,  21,  24,  27,  30,  33,  36,  127,   97,  103,  109,  115,  121,  213,  173,  181,  189,  197,  205},
+    { 9,   9,  11,  13,  15,  17,  19,   91,   66,   71,   76,   81,   86,  165,  130,  137,  144,  151,  158},
+    {21,   3,   4,   5,   6,   7,   2,   61,   41,   45,   49,   53,   57,  123,   93,   99,  105,  111,  117},
+    {29, 130, 137, 144, 151, 158, 165,  218,  227,  236,  245,  254,  263,  394,  339,  350,  361,  372,  383},
+    {14,  94, 100, 106, 112, 118, 124,  170,  178,  186,  194,  202,  210,  328,  278,  288,  298,  308,  318},
+    { 5,  64,  69,  74,  79,  84,  89,  128,  135,  142,  149,  156,  163,  268,  223,  232,  241,  250,  259},
+    { 1,  40,  44,  48,  52,  56,  60,   92,   98,  104,  110,  116,  122,  214,  174,  182,  190,  198,  206},
+    { 2,  22,  25,  28,  31,  34,  37,   62,   67,   72,   77,   82,   87,  166,  131,  138,  145,  152,  159},
+    { 8,  10,  12,  14,  16,  18,   8,   38,   42,   46,   50,   54,   58,  124,   94,  100,  106,  112,  118},
+    {20,  11,  13,  15,  17,  19,   9,   20,   23,   26,   29,   32,   35,   88,   63,   68,   73,   78,   83},
+    {30, 131, 138, 145, 152, 159, 166,  219,  228,  237,  246,  255,  264,  329,  279,  289,  299,  309,  319},
+    {15,  95, 101, 107, 113, 119, 125,  171,  179,  187,  195,  203,  211,  269,  224,  233,  242,  251,  260},
+    { 6,  65,  70,  75,  80,  85,  90,  129,  136,  143,  150,  157,  164,  215,  175,  183,  191,  199,  207},
+    { 7,  41,  45,  49,  53,  57,  61,   93,   99,  105,  111,  117,  123,  167,  132,  139,  146,  153,  160},
+    {19,  23,  26,  29,  32,  35,  20,   63,   68,   73,   78,   83,   88,  125,   95,  101,  107,  113,  119},
+    {37,  24,  27,  30,  33,  36,  21,   39,   43,   47,   51,   55,   59,   89,   64,   69,   74,   79,   84},
+    {31, 132, 139, 146, 153, 160, 167,  220,  229,  238,  247,  256,  265,  270,  225,  234,  243,  252,  261},
+    {16,  96, 102, 108, 114, 120, 126,  172,  180,  188,  196,  204,  212,  216,  176,  184,  192,  200,  208},
+    {17,  66,  71,  76,  81,  86,  91,  130,  137,  144,  151,  158,  165,  168,  133,  140,  147,  154,  161},
+    {18,  42,  46,  50,  54,  58,  38,   94,  100,  106,  112,  118,  124,  126,   96,  102,  108,  114,  120},
+    {36,  43,  47,  51,  55,  59,  39,   64,   69,   74,   79,   84,   89,   90,   65,   70,   75,   80,   85},
+    {32, 133, 140, 147, 154, 161, 168,  221,  230,  239,  248,  257,  266,  217,  177,  185,  193,  201,  209},
+    {33,  97, 103, 109, 115, 121, 127,  173,  181,  189,  197,  205,  213,  169,  134,  141,  148,  155,  162},
+    {35,  68,  73,  78,  83,  88,  63,   95,  101,  107,  113,  119,  125,   91,   66,   71,   76,   81,   86}
+  };
+
+//
+// corrispondence between pixels in cell and lut (pix numbering starts from 1)
+//
+const Int_t MMcTriggerLvl2::gsPixelsInLut[gsNLutInCell][gsNPixInLut] = {
+    { 1,  2,  3,  4,  6,  7,  8,  9, 12, 13, 14, 15},
+    {34, 29, 23, 16, 30, 24, 17, 10, 25, 18, 11,  5},
+    {35, 31, 26, 20, 19, 32, 27, 21, 36, 33, 28, 22},
+  };
+
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor
+//
+MMcTriggerLvl2::MMcTriggerLvl2(const char *name, const char *title):fCompactNN(2),fTriggerPattern(0)
+{
+  fName = name ? name : ClassName();
+  fTitle = title;
+
+  *fLog << "created MMcTriggerLvl2" << endl;
+
+  //
+  // Initialization of the fPixels array to zero
+  //
+  memset (fPixels,0,gsNPixInCell*gsNCells*sizeof(Int_t));
+  memset (fFiredPixel,0,gsNTrigPixels*sizeof(Int_t));
+
+  // create a new camera
+  SetNewCamera(new MGeomCamMagic);
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor
+//
+MMcTriggerLvl2::~MMcTriggerLvl2()
+{
+  delete fGeomCam;
+}
+
+// --------------------------------------------------------------------------
+//  
+//  Print functions for debugging and testing
+//
+//  Options available:
+//
+// "cell":
+//     Print out the pixel number of a given trigger cell
+//
+// "status":
+//     Print a table with the status (pixel is fired or not after Lvl1) for 
+//     all the pixels in all the trigger cells
+//
+// "check"
+//     Print a warning message when no starting pixel is found in the 
+//     CalcPseudoSize method.
+//
+//  no option:
+//     Print the value of the selection parameters
+//
+//
+void MMcTriggerLvl2::Print(Option_t *opt) const
+{
+  TString str(opt);
+
+  if (str.Contains("status", TString::kIgnoreCase)) 
+    {
+      *fLog << "    Status of cells 1-9" <<endl;
+      for(int i=0; i<gsNPixInCell; i++)
+	{
+	  for(int j=0; j<9; j++)
+	    {
+	      //      *fLog.width(3);
+	      *fLog <<gsPixelsInCell[i][j]-1 << ":" << fPixels[i][j]  << "\t ";
+	    } 
+	  *fLog << endl;
+	}      
+    }
+  else if (str.Contains("cell", TString::kIgnoreCase)) 
+    {
+      *fLog << "   Pixel numbering in cells 1-9" <<endl;
+      for (int i=0;i<gsNPixInCell;i++)
+	{
+	  for(int j=0; j<9; j++)
+	    {
+	      *fLog << gsPixelsInCell[i][j]-1 << "\t";
+	    }
+	  *fLog << endl;
+	}
+    }
+  else if (str.Contains("check", TString::kIgnoreCase)) 
+    {
+      // check when no starting pixels was found (<<--to be fixed)
+      if (fPseudoSize < 0)
+	*fLog << "  Warning: starting pixel not found. Pseudosize set to -1." << endl;
+    }
+  else 
+    {
+      *fLog << "  L2T selection parameters: " << endl;
+      *fLog << "   - LutPseudoSize  = " << fLutPseudoSize <<  endl;
+      *fLog << "   - CellPseudoSize  = " << fCellPseudoSize <<  endl;
+      *fLog << "   - PseudoSize  = " << fPseudoSize <<  endl;
+      *fLog << "   - BiggerCellSize = " << fSizeBiggerCell << endl;
+      *fLog << "   - TriggerPattern = " << fTriggerPattern << endl;
+    }
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Take the information supplied by the Lvl1 (it reads from the object MMcTrig
+// the status of all pixels after Lvl1) and pass it to the Lvl2 (fill the 
+// array fPixels)
+//
+//
+void MMcTriggerLvl2::SetLv1(MMcTrig *trig)
+{
+  if (!trig)
+    return;
+
+  fMcTrig = trig;
+
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      for(int j=0; j<gsNCells; j++)
+	{
+	  int pixel = gsPixelsInCell[i][j]-1;
+	  fPixels[i][j] = (fMcTrig->IsPixelFired(pixel,0)) ? 1 : 0;
+	  fFiredPixel[pixel]=(fMcTrig->IsPixelFired(pixel,0)) ? 1 : 0;
+	  //if (fFiredPixel[pixel]==1)
+	  //*fLog << pixel<<",";
+	}
+    }
+  //*fLog<<endl<<"Fine evento"<<endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the trigger status ( pixel fired(=1) or not(=0) ) manually for a given
+// pixel of a given cell
+//
+//
+void MMcTriggerLvl2::SetPixelFired(Int_t pixel, Int_t fired)
+{
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      for(int j=0; j<gsNCells; j++)
+	{
+	  if(gsPixelsInCell[i][j]-1==pixel) fPixels[i][j]=fired;
+	}
+    }
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Level 2 Trigger (L2T) parameters. They can be used 
+//  to select the events that have passed the L2T selection rule.
+//
+//
+void MMcTriggerLvl2::Calc()
+{
+
+  // Find the Lut and cell with the higher LutPseudoSize. 
+  int lutcell = CalcBiggerLutPseudoSize(); 
+  fMaxCell = lutcell/10;
+  int maxlut = lutcell-fMaxCell*10;
+  fLutPseudoSize = GetLutCompactPixel(fMaxCell,maxlut);
+
+  fMaxCell = CalcBiggerCellPseudoSize();  // fCellPseudoSize
+  // fMaxCell is used by the PseudoSize to find the starting pixel
+  CalcPseudoSize();
+
+  fSizeBiggerCell = GetCellNumberFired(CalcBiggerFiredCell());
+
+  //*fLog << "fLPS="<<fLutPseudoSize<<endl;
+}
+
+
+
+// --------------------------------------------------------------------------
+//  
+// For a given cell, just count how many pixels have been fired after Lvl1
+//
+Int_t MMcTriggerLvl2::GetCellNumberFired(int cell)
+{
+  int size=0;
+ 
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      size += fPixels[i][cell];
+    }
+
+  return size;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//  
+//  Find the cell which the bigger number of fired pixels
+// 
+//
+Int_t MMcTriggerLvl2::CalcBiggerFiredCell()
+{
+  int size=-1;
+  int cell=-1;
+
+  for(int j=0; j<gsNCells; j++)
+    {
+      if (GetCellNumberFired(j) > size) 
+	{
+	  size = GetCellNumberFired(j);
+	  cell = j;
+	}
+    }
+  
+  //  *fLog << "size " <<size <<" in cell " << cell << endl;
+
+  return cell;
+  
+}
+
+// --------------------------------------------------------------------------
+//  
+// Calculate the higher LutPseudoSize of one event defined as the higher number
+//   of compact pixel in the LUTs of the trigger cells.
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology (it can be 2-NN or 3-NN)
+//
+//   It returns the cell and the LUT with the bigger LutPseudoSize, coded
+//      accordingly to:   cell*10 + LUT 
+//
+Int_t MMcTriggerLvl2::CalcBiggerLutPseudoSize()
+{
+  int size=0;
+  int cell=-1;
+  int lut=-1;
+ 
+  for(int j=0; j<gsNCells; j++)
+    {
+      for(int i=0; i<gsNLutInCell; i++)
+	{
+	  if (GetLutCompactPixel(j,i) >= size) 
+	    {
+	      size = GetLutCompactPixel(j,i);
+	      cell = j;
+	      lut = i;
+	    }      
+	}
+    }
+  
+  //*fLog <<"Max cell: " << cell+1 << "  Max Lut: " << lut+1 << "  PseudoSize: " << size <<endl;
+    
+  return cell*10+lut;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+// Identify compact pixels in one LUT and calculate the LutPseudoSize 
+//   (=number of compact pixels in one LUT)
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology.  
+//   Up to now only  2NN or 3NN are considered 
+//    <!if changed: change check made by Preprocess in MMcTriggerLvl2Calc>    
+//
+//   Returns: 
+//     -1    wrong neighpix
+//     -2    wrong cell (<1 or >19)
+//     -3    wrong lut  (<1 or >3)
+//    else:
+//      the number of compact pixels in one LUT.
+//     
+Int_t MMcTriggerLvl2::GetLutCompactPixel(int cell, int lut)
+{
+  int size=0;
+  int lutpix, a[gsNPixInLut]; 
+  int neighpix= (*this).fCompactNN;
+
+  // check on input variables
+
+  if (neighpix >3 || neighpix < 2) 
+    return(-1);
+
+  if (cell<0 || cell> gsNCells-1)
+    return(-2);
+
+  if (lut<0 || lut> gsNLutInCell-1)
+    return(-3);
+
+
+  //
+  // Warning!!! Following configurations are valid only for the standard MAGIC 
+  // trigger geometry; FIXME! these should be coded somewhere else....
+  //
+
+  // LUT 1 and 2 are similar; LUT 3 differs
+  
+  for(int j=0; j< gsNPixInLut; j++)
+    {
+      lutpix = gsPixelsInLut[lut][j]-1;
+      //    *fLog << "j=" <<j<<"  lutpix="<<lutpix<<"  Cell="<<cell<<endl;
+      a[j] = fPixels[lutpix][cell]; 
+    }
+  
+  //
+  // Look for compact pixels 2NN
+  //
+  if (neighpix==2)
+    {    
+      //  case Lut 1 and 2
+      if (lut == 0 || lut == 1)
+	{
+	  if (a[0] && a[1] && a[4])
+	    size ++;
+	  if (a[1] && ((a[0] && a[4]) || 
+		       (a[4] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[6]) || 
+		       (a[6] && a[7]) )) 
+	    size ++;
+	  if (a[4] && ((a[0] && a[1]) || 
+		       (a[1] && a[5]) || 
+		       (a[5] && a[8]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2]) || 
+		       (a[2] && a[6]) || 
+		       (a[6] && a[9]) || 
+		       (a[9] && a[8]) || 
+		       (a[8] && a[4]) || 
+		       (a[4] && a[1]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3]) || 
+		       (a[3] && a[7]) || 
+		       (a[7] && a[10]) || 
+		       (a[10] && a[9]) || 
+		       (a[9] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6]) || 
+		       (a[6] && a[10]) || 
+		       (a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && ((a[4] && a[5]) || 
+		       (a[5] && a[9]) )) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6]) || 
+			(a[6] && a[7]) || 
+			(a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10]) 
+	    size ++;
+	}
+      
+      //  case Lut 3
+      if (lut==2) 
+	{
+	  if (a[0] && a[1] && a[5])
+	    size ++;
+	  if (a[1] && ((a[0] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[3] && a[4]) || 
+		       (a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[6]) || 
+		       (a[6] && a[7]) || 
+		       (a[2] && a[4]) )) 
+	    size ++;
+	  if (a[4] && ((a[2] && a[3]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2]) || 
+		       (a[2] && a[6]) || 
+		       (a[6] && a[9]) || 
+		       (a[9] && a[8]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3]) || 
+		       (a[3] && a[7]) || 
+		       (a[7] && a[10]) || 
+		       (a[10] && a[9]) || 
+		       (a[9] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6]) || 
+		       (a[6] && a[10]) || 
+		       (a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && a[5] && a[9]) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6]) || 
+			(a[6] && a[7]) || 
+			(a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10]) 
+	    size ++;    
+	}
+    }
+  
+  //
+  // Look for compact pixels 3NN 
+  //
+  if (neighpix==3)
+    {
+      //  case Lut 1 and 2
+      if (lut == 0 || lut == 1)
+	{
+	  if (a[0] && a[1] && a[4] && a[5]) // pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[1] && ((a[0] && a[4] && a[5]) || 
+		       (a[2] && a[4] && a[5]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && (a[2] && a[6] && a[7] ))  
+	    size ++;
+	  if (a[4] && ((a[0] && a[1] && a[5]) || 
+		       (a[1] && a[5] && a[8]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2] && a[6]) || 
+		       (a[2] && a[6] && a[9]) || 
+		       (a[6] && a[9] && a[8]) || 
+		       (a[9] && a[8] && a[4]) || 
+		       (a[8] && a[4] && a[1]) || 
+		       (a[4] && a[1] && a[2]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3] && a[7]) || 
+		       (a[3] && a[7] && a[10]) || 
+		       (a[7] && a[10] && a[9]) || 
+		       (a[10] && a[9] && a[5]) || 
+		       (a[9] && a[5] && a[2]) || 
+		       (a[5] && a[2] && a[3]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6] && a[10]) || 
+		       (a[6] && a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && (a[4] && a[5] && a[9] )) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6] && a[7]) || 
+			(a[6] && a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10] && a[6]) //pix 0 is compact if there is a 4NN
+	    size ++;
+	}
+      
+      //  case Lut 3
+      if (lut==2) 
+	{
+	  if (a[0] && a[1] && a[5] && a[8]) // pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[1] && (a[0] && a[5] && a[2])) //pix 0 is compact if there is a 4NN 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5] && a[6]) || 
+		       (a[3] && a[5] && a[6]) || 
+		       (a[6] && a[3] && a[4]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[4] && a[6]) || 
+		       (a[2] && a[6] && a[7]) )) 
+	    size ++;
+	  if (a[4] && (a[2] && a[3] && a[6] )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2] && a[6]) || 
+		       (a[2] && a[6] && a[9]) || 
+		       (a[6] && a[9] && a[8]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3] && a[7]) || 
+		       (a[3] && a[7] && a[10]) || 
+		       (a[7] && a[10] && a[9]) || 
+		       (a[10] && a[9] && a[5]) || 
+		       (a[9] && a[5] && a[2]) || 
+		       (a[5] && a[2] && a[3]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6] && a[10]) || 
+		       (a[6] && a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && a[5] && a[9] && a[6])  //pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[9] && ((a[8] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6] && a[7]) || 
+			(a[6] && a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10] && a[6]) //pix 0 is compact if there is a 4NN
+	    size ++;
+	}
+    }
+  
+
+  if(size<0 ||size>gsNPixInLut)
+    *fLog << "*" << size <<"-";
+  
+  return size;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+// Look for clusters and calculate the PseudoSize of one event, 
+//   defined as the multiplicity of the bigger cluster. 
+//
+//
+//
+void MMcTriggerLvl2::CalcPseudoSize()
+{
+  // Fill the fCompactPixel array with the compact pixels
+  CalcCompactPixels(fGeomCam);
+
+  // seek the LUT with higher number of compact pixels
+  //
+  //int fMaxCell = CalcBiggerCellPseudoSize();
+  int sizetemp=0;
+  int maxlut=0;
+
+  for (int i=0;i<gsNLutInCell;i++)
+    if (GetLutCompactPixel(fMaxCell,i) > sizetemp)
+      {
+        maxlut=i;
+        sizetemp = GetLutCompactPixel(fMaxCell,i);
+      }
+
+  int startpix;
+  // 
+  // seek a starting pixel for the iteration inside the lut
+  //
+  int check=1;
+  for (int pixlut=0;pixlut<gsNPixInLut;pixlut++)
+    {
+      int pixcell =gsPixelsInLut[maxlut][pixlut]-1;
+      startpix = gsPixelsInCell[pixcell][fMaxCell]-1;
+      //*fLog << "pix, compact:" << startpix << "@"<<fCompactPixel[startpix];
+      if (fCompactPixel[startpix]) // a starting pixel was found
+		break;
+      check++;
+    }
+
+  //*fLog << "check = " << check << endl;
+  // A LUT contains 12 pixels
+  if (check > gsNPixInLut)
+	  {   
+		   *fLog <<"Warning: a starting pixel was not found! - PseudoSize = "<< fPseudoSize << endl;
+	    fPseudoSize=-1;
+	    return;
+	  }
+
+  //
+  // Bulding cluster
+  //
+  Int_t cluster[gsNTrigPixels];
+  int pnt=0;
+  int pnt2=0; //pointer in the array fCluster_pix, needed for filling
+
+  memset (cluster,0,gsNTrigPixels*sizeof(Int_t));
+  memset (fCluster_pix,-1,gsNTrigPixels*sizeof(Int_t));
+
+  cluster[startpix]=1;  
+  fCluster_pix[0]=startpix; //the starting pix is the first in cluster
+  
+  // Look at neighbour pixs if they are compact (iterative search)
+  //  until the array (fCluster_pix) has no more compact pixels.
+  // pnt points to the pixel in the array fCluster_pix whose neighbors are
+  // under study; pnt2 points to the last element of this array.
+  //
+  while (fCluster_pix[pnt] != -1)
+    { 
+      const MGeomPix &pix=(*fGeomCam)[fCluster_pix[pnt]];
+
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+	    {
+	       int pix_neigh = pix.GetNeighbor(i);
+	       // check if pixel is fired and doesn't belong to cluster
+	       if (fCompactPixel[pix_neigh] && !cluster[pix_neigh])
+	         {
+	            cluster[pix_neigh] = 1;
+	            fCluster_pix[++pnt2] = pix_neigh;
+	         }
+	    }
+      pnt++;
+    }
+
+  fPseudoSize = pnt;
+
+  //if (fPseudoSize < 4)
+    //    *fLog << "fPseudoSize = " << fPseudoSize << endl;
+
+  //  *fLog << "ClusterID:" <<(*clust).GetClusterId() << " Mult:" << (*clust).GetMultiplicity()<<endl;  
+  /*
+  *fLog <<"PSize: "<< fPseudoSize << " in cell:" << fMaxCell << " lut:" <<maxlut << endl << "   Pixels: ";
+  for (int i =0;i<fPseudoSize; i++)
+    *fLog << fCluster_pix[i]+1 <<"; ";
+  *fLog << endl;
+  */
+  return;
+}
+
+// --------------------------------------------------------------------------
+//  
+//  Fill the fCompactPixels array with the pixels which are compact
+//
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology (it can be 2-NN or 3-NN)
+//
+//   Note: it is a *global* method; it looks in the all camera as a whole
+//         
+//
+void MMcTriggerLvl2::CalcCompactPixels(MGeomCam *geom)
+{
+  memset (fCompactPixel,0,gsNTrigPixels*sizeof(Int_t));
+  //  *fLog << endl << "NEW Event!";
+  for(Int_t pixid=0; pixid<gsNTrigPixels; pixid++)
+    {
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+	     continue;
+      
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Reshuffle pixneighbour order, to arrange them (anti)clockwise
+      //   around the current pixel (Bubble sorting)
+      // The NeighPixOrdered array has a doubledd size so that
+      // the content in the first index is repeated in the last one
+      // to have a closed loop
+
+      Int_t NeighPixOrdered[2*pix.GetNumNeighbors()];
+
+      for (Int_t j=0; j<pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = pix.GetNeighbor(j);
+      
+      for (Int_t j=0; j<pix.GetNumNeighbors()-1; j++)
+        {
+          for (Int_t jk=pix.GetNumNeighbors()-1;jk>j;--jk)
+            {
+               UInt_t tmp = NeighPixOrdered[j+1];
+               const MGeomPix &pixneigh = (*geom)[NeighPixOrdered[j]];
+               for (int k=0; k<pix.GetNumNeighbors(); k++)
+                 if (NeighPixOrdered[jk] == pixneigh.GetNeighbor(k))
+     		       {
+                      NeighPixOrdered[j+1] = NeighPixOrdered[jk];
+                      NeighPixOrdered[jk] = tmp;
+              	   }
+	        }
+        }
+      
+      // Duplicate second half to take into account configurations
+ 	  //  containing tha last and first pixel
+      for (Int_t j=pix.GetNumNeighbors(); j<2*pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = NeighPixOrdered[j-pix.GetNumNeighbors()];
+
+      // Look for compact pixels. 
+      // A compact pixel must have at least fCompactNN adjacent fired neighbors
+      // It checks the 6 different configurations of neighbors pixels; if
+	  // one has fCompacNN adjacent fired pixels than the pixel pixid is
+	  // promoted to compact pixel and saved into the fCompactPixel array.
+	  //
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+	    { 
+	      int j=0; // j counts the adjacent fired pixels
+	      //*fLog << pixid <<"->"<< pix.GetNeighbor(i+j) << endl;
+	      while ((i+j < 2*pix.GetNumNeighbors()) && (fFiredPixel[NeighPixOrdered[i+j]]==1) && (j < fCompactNN))
+	        j++;  
+	      if (j>=fCompactNN)	 // configuration satisfies the compact condition  
+		{
+	      	  fCompactPixel[pixid]=1; // pixel is compact
+	      	  //	  *fLog << ","<<pixid;
+		  break;
+		}
+	    }      
+    }
+
+}
+
+// --------------------------------------------------------------------------
+//  
+//  The Energy has to be given by this class to the Energy-PSSize correlation 
+//   histogram (MHMcTriggerLvl2)  
+//
+void MMcTriggerLvl2::GetEnergy(MMcEvt *fMcEvt)
+{
+   const MMcEvt &h = *(MMcEvt *)fMcEvt; 
+   fEnergy = h.GetEnergy();
+   return;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+//   Looks for a x-NN compact pattern in the whole camera
+//   We have x-NN compact pattern when a triggered pix has
+//   x-1 triggered neighbor pixels.  
+//   The variable fTriggerPattern = x is computed
+//   (x= 2,3,4,5,6,7)  
+//
+//   x=2   * *
+//
+//   x=3   * *
+//          *        *
+//            x=4   * *
+//                   *       
+//                       * *
+//                 x=5  * * *
+//          * 
+//   x=6   * * *
+//          * *
+//               * *
+//          x=7 * * *
+//               * *
+//
+void MMcTriggerLvl2::CalcTriggerPattern(MGeomCam *geom)
+{
+  fTriggerPattern=0; //initialize
+
+  for(Int_t pixid=0;pixid<gsNTrigPixels;pixid++)
+    {
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+		continue;
+      
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Look for x-NN compact pattern
+      // If a x-NN pattern exists then a pixel must have 
+      // at least x-1 adjacent neighbors (look at patterns)
+      // For each triggered pixel the number of adjacent triggered pixels 
+      // is counted.
+      //
+      int j=1;
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+		if (fFiredPixel[pix.GetNeighbor(i)]==1) j++;
+	     
+      if (j > fTriggerPattern) 
+		fTriggerPattern=j;	 
+
+      if (fTriggerPattern==7) 
+	  	break;	 // the 7-NN (max) pattern was found: exit  
+
+    } // next pixel
+}
+
+
+// --------------------------------------------------------------------------
+//  Look for the cell with higher number of Compact pixels
+//  Return the cell number (starting from 0)
+//
+Int_t MMcTriggerLvl2::CalcBiggerCellPseudoSize()
+{
+  Int_t fMaxCell=-1;
+
+  fCellPseudoSize=0;
+
+  for (Int_t i=0;i<gsNCells;i++)
+    {
+      int size = GetCellCompactPixel(i,fGeomCam);
+      if (size > fCellPseudoSize)
+        {
+          fCellPseudoSize = size;
+          fMaxCell = i;
+        }
+    }
+  
+  //*fLog << "fCellPseudoSize = " << fCellPseudoSize << " in cell N. " << fMaxCell+1 << endl;
+
+  return fMaxCell;
+}
+
+// --------------------------------------------------------------------------
+//  Compute the number of compact pixels in one cell
+//
+Int_t MMcTriggerLvl2::GetCellCompactPixel(int cell, MGeomCam *geom)
+{
+  int size=0;
+
+  // check on input variables
+
+  if (cell<0 || cell>gsNCells-1)
+    return(-2);
+
+  //*fLog << " CNN:" << fCompactNN;
+  //*fLog << "Cell: " << cell+1 << " Compat Pixels:"; 
+
+  for(Int_t id=0; id<gsNPixInCell; id++)
+    {
+      UInt_t pixid = gsPixelsInCell[id][cell]-1;
+ 
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+        continue;
+
+      //*fLog << "Fired pix:"<<pixid+1 << " ";
+
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Reshuffle pixneighbour order, to arrange them (anti)clockwise 
+      //   around the current pixel (Bubble sorting)
+      // The NeighPixOrdered has one index more so that 
+      // the content in the first index is repeated in the last one
+      // to have a closed loop
+      Int_t NeighPixOrdered[2*pix.GetNumNeighbors()];
+      for (Int_t j=0; j<pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = pix.GetNeighbor(j);
+      
+      for (Int_t j=0; j<pix.GetNumNeighbors()-1; j++)
+        {
+          for (Int_t jk=pix.GetNumNeighbors()-1;jk>j;--jk)
+            {
+              UInt_t tmp = NeighPixOrdered[j+1];                  
+              const MGeomPix &pixneigh = (*geom)[NeighPixOrdered[j]];
+              for (int k=0; k<pix.GetNumNeighbors(); k++)
+                if (NeighPixOrdered[jk] == pixneigh.GetNeighbor(k))
+                  {
+                    NeighPixOrdered[j+1] = NeighPixOrdered[jk];
+                    NeighPixOrdered[jk] = tmp;
+                  }
+            }
+        }
+
+      // Duplicate second half of the array to take into account configurations
+      // containing tha last and first pixel
+      for (Int_t j=pix.GetNumNeighbors(); j<2*pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = NeighPixOrdered[j-pix.GetNumNeighbors()];
+
+      // Look for compact pixels. 
+
+      // A compact pixel must have at least fCompactNN adjacent neighbors
+      // It checks the 6 different configurations of neighbors pixels.
+      // The neighbour pixels must belong to the cell
+
+      //      *fLog << "cell:"<< cell << "   ordered pixels:";
+      /*
+      for (int i=0;i<2*pix.GetNumNeighbors();i++)
+	{
+	  if (fFiredPixel[NeighPixOrdered[i]])
+	    *fLog << NeighPixOrdered[i]+1 << "*;";
+	  else
+	    *fLog << NeighPixOrdered[i]+1 << ";";
+	}
+      */
+      //*fLog <<endl;
+      //*fLog << pixid <<"->"<< pix.GetNumNeighbors() << " CNN="<< fCompactNN <<endl;
+
+
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+        { 
+          int j=0;
+          while ((i+j < 2*pix.GetNumNeighbors()) && (fFiredPixel[NeighPixOrdered[i+j]]==1) && (j < fCompactNN) && IsPixelInCell(NeighPixOrdered[i+j],cell) )
+            j++;  
+
+          if (j>=fCompactNN) //configuration satisfies the compact condition  
+	    {          
+	      size++; // pixel is compact
+	      //*fLog << "->" << pixid+1;
+	      break; // (new pixel)
+	    }
+	}
+    }
+  
+  //*fLog <<" - size:" << size << endl<<endl;
+  
+  return size;
+  
+}
+
+//---------------------------------------------------------------------
+//  Check if a given pixel belongs to a given cell
+//
+Bool_t MMcTriggerLvl2::IsPixelInCell(Int_t pixel, Int_t cell)
+{
+  for (int i=0; i<gsNPixInCell; i++)
+    if ((gsPixelsInCell[i][cell]-1) == pixel)
+      return kTRUE;
+  
+  return kFALSE;
+}
+
+//---------------------------------------------------------------------
+//  Check if a given pixel is in the trigger region
+//
+Bool_t MMcTriggerLvl2::IsPixelInTrigger(Int_t pixel) const
+{
+  for (int cell=0; cell<gsNCells; cell++)
+    for (int i=0; i<gsNPixInCell; i++)
+      if ((gsPixelsInCell[i][cell]-1) == pixel)
+	return kTRUE;
+  
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns, depending on the type flag:
+//
+//  0: 1,0 if the pixel is triggered (1) or not (0)
+// 
+//
+Bool_t MMcTriggerLvl2::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  // Pixel in no-trigger region are set to 0
+  val = this->IsPixelInTrigger(idx) ?  fFiredPixel[idx]+fCompactPixel[idx] : 0;
+
+  return kTRUE;
+}
+
+void MMcTriggerLvl2::DrawPixelContent(Int_t num) const
+{
+    *fLog << "MMcTriggerLvl2::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars-V0.9/manalysis/MMcTriggerLvl2.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MMcTriggerLvl2.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMcTriggerLvl2.h	(revision 9772)
@@ -0,0 +1,106 @@
+#ifndef MARS_MMcTriggerLvl2
+#define MARS_MMcTriggerLvl2
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MMcTrig;
+class MMcEvt;
+class MGeomCamMagic;
+class MGeomCam;
+class MGeomPix;
+
+class MMcTriggerLvl2 : public MParContainer, public MCamEvent
+{
+ private:
+  
+  // Global trigger variables related to the geometry and trigger structures are here defined.  
+  // FIXME!  this is a temporary solution: these variables should be defined in a GeomTrg class    
+
+  static const Int_t fNumPixCell = 36; // Number of pixels in one cell
+
+  static const Int_t gsNCells = 19;   
+  static const Int_t gsNTrigPixels = 397;   
+  static const Int_t gsNPixInCell = 36;  
+  static const Int_t gsNLutInCell = 3;  
+  static const Int_t gsNPixInLut = 12; 
+  Int_t fPixels[gsNPixInCell][gsNCells];  
+  
+  // Array with flag for triggered pixels. 1st idx:pixels in trigger cell; 2nd idx:trigger cell number      
+
+  Int_t fFiredPixel[gsNTrigPixels]; // Array with flag for triggered pixel. idx: pixel id    
+  static const Int_t gsPixelsInCell[gsNPixInCell][gsNCells];   
+  static const Int_t gsPixelsInLut[gsNLutInCell][gsNPixInLut];     
+
+  Int_t fMaxCell;  // Cell with maximum number of fired pixels
+
+  Int_t fLutPseudoSize;   // number of compact pixels in one lut   
+  Int_t fPseudoSize;   // Multiplicity of the cluster identified by the L2T    
+  Int_t fSizeBiggerCell; // Number of fired pixel in bigger cell    
+  Int_t fCompactNN;    //Number of NN pixels that define a compact pixel    
+  Int_t fCompactPixel[gsNTrigPixels]; //Array with flag for compact pixels    
+  Int_t fCluster_pix[gsNTrigPixels]; //Array with pixel in cluster   
+  Double_t fEnergy;  // Energy of the shower    
+  Int_t fTriggerPattern; // x-NN compact trigger pattern;    
+  Int_t fCellPseudoSize; // number of compact pixels in one cell    
+  //  Int_t fCellCompactPixels[fNumPixCell]; // Array with compact pixels in cell
+
+  MMcTrig *fMcTrig;   
+  MGeomCam *fGeomCam;      
+
+     
+  Int_t CalcBiggerFiredCell();   
+  Int_t CalcBiggerLutPseudoSize();   
+  void CalcPseudoSize();   
+  Int_t CalcCellPseudoSize();   
+  Int_t CalcBiggerCellPseudoSize();    
+  Int_t GetCellCompactPixel(int cell, MGeomCam *fCam);
+
+  void SetNewCamera(MGeomCam *geom) {fGeomCam = geom;}   
+
+ public:     
+
+  MMcTriggerLvl2(const char* name = NULL, const char* title = NULL);   
+  ~MMcTriggerLvl2();      
+
+  virtual void Calc();    
+  virtual void Print(Option_t *opt="") const;    
+
+  void SetLv1(MMcTrig *trig = NULL);    
+  void SetPixelFired(Int_t pixel, Int_t fired=1);     
+  void SetCompactNN(Int_t neighpix)     {fCompactNN=neighpix;}    
+
+  Int_t GetPseudoSize() const     {return fPseudoSize;}   
+  Int_t GetLutPseudoSize() const  {return fLutPseudoSize;}   
+  Int_t GetSizeBiggerCell() const {return fSizeBiggerCell;}   
+  Int_t GetCompactNN() const      {return fCompactNN;}   
+  Int_t GetCellPseudoSize() const {return fCellPseudoSize;}
+  Int_t GetMaxCell() const        {return (fMaxCell+1);} // Returns
+                     // cell with maximum number of compact pixels
+  Int_t GetCellNumberFired(int cell);   
+  Int_t GetLutCompactPixel(int cell, int lut); 
+  void CalcCompactPixels(MGeomCam *fCam);
+  void CalcTriggerPattern(MGeomCam *fCam);
+    
+  Int_t GetTriggerPattern() const {return fTriggerPattern;}    
+
+  void GetEnergy(MMcEvt *fMcEvt = NULL);     
+  Double_t GetEnergy() const    {return fEnergy;}      
+
+  Bool_t IsPixelInCell(Int_t pixel, Int_t cell);    
+  Bool_t IsPixelInTrigger(Int_t pixel) const;    
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t num) const;
+
+
+  ClassDef(MMcTriggerLvl2,0) // Container for 2nd Level Trigger selection parameters 
+    };  
+    
+#endif      
+    
Index: /tags/Mars-V0.9/manalysis/MMcTriggerLvl2Calc.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MMcTriggerLvl2Calc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMcTriggerLvl2Calc.cc	(revision 9772)
@@ -0,0 +1,209 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Antonio Stamerra  1/2003 <mailto:antono.stamerra@pi.infn.it>
+!   Author(s): Marcos Lopez 1/2003 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MTriggerLvl2Calc                                                        //
+//   This is a task to calculate the 2nd level trigger selection           //
+//   parameters                                                            //
+//                                                                         //
+//  Input containers:                                                      //
+//    MMcTriggerLvl2                                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MMcTriggerLvl2Calc.h"
+#include "MMcTriggerLvl2.h"
+#include "MHMcTriggerLvl2.h"
+
+#include "MParList.h"
+#include "MLog.h"
+#include "MLogManip.h"
+
+//#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+#include "MRawRunHeader.h"
+#include "MMcRunHeader.hxx"
+
+#include "MGeomCam.h"
+
+ClassImp(MMcTriggerLvl2Calc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//                                                                         
+//  Default constructor
+// 
+//
+MMcTriggerLvl2Calc::MMcTriggerLvl2Calc(const char *name, const char *title)
+{
+  fName  = name  ? name  : "MMcTriggerLvl2Calc";
+  fTitle = title ? title : "Task to Fill the MMcTriggerLvl2 object";  
+} 
+
+ // --------------------------------------------------------------------------
+//
+// Check for the run type. Return kTRUE if it is a MC run or if there
+// is no MC run header (old camera files) kFALSE in case of a different
+// run type
+//
+Bool_t MMcTriggerLvl2Calc::CheckRunType(MParList *pList) const
+{
+  const MRawRunHeader *run = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!run)
+    {
+      *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+      return kTRUE;
+    }
+  
+  return run->IsMonteCarloRun();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the runtype.
+// Search for .
+//
+Bool_t MMcTriggerLvl2Calc::ReInit(MParList *pList)
+{
+    //
+    // If it is no MC file skip this function...
+    //
+    if (!CheckRunType(pList))
+    {
+        *fLog << inf << "This is no MC file... skipping." << endl;
+        return kTRUE;
+    }
+        
+    //
+    // Check all necessary containers
+    //
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+     if (!fMcEvt)
+     {
+         *fLog << err << dbginf << "MMcEvt not found... exit." << endl;
+         return kFALSE;
+     }
+
+    fMcTrig = (MMcTrig*)pList->FindObject("MMcTrig");
+    if (!fMcTrig)
+    {
+        *fLog << err << dbginf << "MMcTrig not found... exit." << endl;
+        return kFALSE;
+    }
+
+    fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << dbginf << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+    // Check if fCam is a Magic geometry: only MGeomCamMagic geometry and 
+    // geometries with 577 pixels are now accepted by MMcTriggerLvl2
+    if (fCam->GetNumPixels()!= 577)
+      {
+        *fLog << dbginf << "MGeomCam has a wrong geometry; only MAGIC geometry (577 pixels) is accepted by now... aborting" <<endl;
+	return kFALSE;
+      }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//                                                                         
+//  PreProcess
+//  Check the exxistence of the MMcTriggerLvl2 containers and the correct 
+//    setting of the fCompactNN that defines a compact pixel
+//
+Int_t MMcTriggerLvl2Calc::PreProcess (MParList *pList)
+{
+
+    //    fMMcTriggerLvl2 = (MMcTriggerLvl2*)pList->FindObject("MMcTriggerLvl2");
+    fMMcTriggerLvl2 = (MMcTriggerLvl2*)pList->FindCreateObj("MMcTriggerLvl2");
+    if (!fMMcTriggerLvl2)
+    {
+        *fLog << err << dbginf << "MMcTriggerLvl2 not found... exit." << endl;
+        return kFALSE;
+    }
+
+    fMHMcTriggerLvl2 = (MHMcTriggerLvl2*)pList->FindCreateObj("MHMcTriggerLvl2");
+    if (!fMHMcTriggerLvl2)
+    {
+        *fLog << err << dbginf << "MHMcTriggerLvl2 not found... exit." << endl;
+        return kFALSE;
+    }
+
+    // Check if the variable fCompactNN has been correctly set;
+    //  accepted values for fCompactNN are (up to now) 2 and 3.
+    if (fMMcTriggerLvl2->GetCompactNN()<2 || fMMcTriggerLvl2->GetCompactNN()>3)
+      {
+	*fLog << err << dbginf << "fCompactNN is not correctly set ("<<fMMcTriggerLvl2->GetCompactNN() <<") ... exit" <<endl;
+        return kFALSE;	
+      }
+    else
+      *fLog << "Compact pixel is set with at least "<<fMMcTriggerLvl2->GetCompactNN() << " NN" <<endl;
+
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//                                                                         
+//  Process 
+// 
+//
+Int_t MMcTriggerLvl2Calc::Process()
+{
+  //  fMMcTriggerLvl2->GetEnergy(fMcEvt);
+
+  fMMcTriggerLvl2->SetLv1(fMcTrig);
+
+  fMMcTriggerLvl2->CalcCompactPixels(fCam);
+
+  fMMcTriggerLvl2->Calc();
+
+  fMMcTriggerLvl2->CalcTriggerPattern(fCam);
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//                                                                         
+//  PostProcess : Display the histogram 
+//           !to be fixed: create an histogram class!
+//
+Int_t MMcTriggerLvl2Calc::PostProcess()
+{ 
+  
+    return kTRUE;
+}
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMcTriggerLvl2Calc.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MMcTriggerLvl2Calc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMcTriggerLvl2Calc.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MMcTriggerLvl2Calc
+#define MARS_MMcTriggerLvl2Calc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class MMcEvt;
+class MMcTrig;
+
+class MMcTriggerLvl2;
+class MHMcTriggerLvl2;
+
+class MGeomCam;
+
+class MMcTriggerLvl2Calc : public MTask
+{
+ private:
+
+  MMcEvt  *fMcEvt;
+  MMcTrig *fMcTrig;
+
+  MGeomCam *fCam;
+
+  MMcTriggerLvl2 *fMMcTriggerLvl2;
+  MHMcTriggerLvl2 *fMHMcTriggerLvl2;
+
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess();
+
+  Bool_t ReInit(MParList *pList);
+  Bool_t CheckRunType(MParList *pList) const;
+
+ public:
+    MMcTriggerLvl2Calc(const char *name=NULL, const char *title=NULL);   
+
+    ClassDef(MMcTriggerLvl2Calc, 0) // Task to calculate the MMcTriggerLvl2 Parameters
+};
+
+#endif 
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMinuitInterface.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MMinuitInterface.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMinuitInterface.cc	(revision 9772)
@@ -0,0 +1,307 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 7/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MMinuitInterface                                                        //
+//                                                                         //
+// Class for interfacing with Minuit                                       //
+//                                                                         //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MMinuitInterface.h"
+
+#include <math.h>            // fabs 
+
+#include <TArrayD.h>
+#include <TArrayI.h>
+#include <TMinuit.h>
+#include <TStopwatch.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParContainer.h"
+
+ClassImp(MMinuitInterface);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMinuitInterface::MMinuitInterface(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMinuitInterface";
+    fTitle = title ? title : "Interface for Minuit";
+}
+
+// -----------------------------------------------------------------------
+//
+// Interface to MINUIT
+//
+//
+Bool_t MMinuitInterface::CallMinuit( 
+             void (*fcn)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t),
+             const TString* name, const TArrayD &vinit, const TArrayD &step2,
+             const TArrayD &limlo, const TArrayD &limup, const TArrayI &fix,
+             TObject *objectfit , const TString &method, Bool_t nulloutput)
+{
+    TArrayD step(step2);
+
+    //
+    // Be carefull: This is not thread safe
+    //
+    if (vinit.GetSize() != step.GetSize()  ||
+        vinit.GetSize() != limlo.GetSize() ||
+        vinit.GetSize() != limup.GetSize() ||
+        vinit.GetSize() != fix.GetSize())
+    {
+        *fLog << "CallMinuit: Parameter Size Mismatch" << endl;
+        return kFALSE;
+    }
+
+
+
+    //..............................................
+    // Set the maximum number of parameters
+    //TMinuit *const save = gMinuit;
+
+    TMinuit &minuit = *new TMinuit(vinit.GetSize());
+    minuit.SetName("MinuitSupercuts");
+
+
+    //..............................................
+    // Set the print level
+    // -1   no output except SHOW comands
+    //  0   minimum output
+    //  1   normal output (default)
+    //  2   additional ouput giving intermediate results
+    //  3   maximum output, showing progress of minimizations
+    //
+    minuit.SetPrintLevel(-1);
+
+    //..............................................
+    // Printout for warnings
+    //    SET WAR      print warnings
+    //    SET NOW      suppress warnings
+    Int_t errWarn;
+    Double_t tmpwar = 0;
+    minuit.mnexcm("SET NOW", &tmpwar, 0, errWarn);
+    //minuit.mnexcm("SET WAR", &tmpwar, 0, errWarn);
+
+    //..............................................
+    // Set the address of the minimization function
+    minuit.SetFCN(fcn);
+
+    //..............................................
+    // Store address of object to be used in fcn
+    minuit.SetObjectFit(objectfit );
+
+    //..............................................
+    // Set starting values and step sizes for parameters
+    for (Int_t i=0; i<vinit.GetSize(); i++)
+    {
+        if (minuit.DefineParameter(i, name[i], vinit[i], step[i],
+                                   limlo[i], limup[i]))
+        {
+            *fLog << "CallMinuit: Error in defining parameter "
+                << name[i][0] << endl;
+            return kFALSE;
+        }
+    }
+
+    //..............................................
+    //Int_t NumPars;
+    //NumPars = minuit.GetNumPars();
+    //*fLog << "CallMinuit :  number of free parameters = "
+    //     << NumPars << endl;
+
+
+    //..............................................
+        // Error definition :
+    //
+    //    for chisquare function :
+    //      up = 1.0   means calculate 1-standard deviation error
+    //         = 4.0   means calculate 2-standard deviation error
+    //
+    //    for log(likelihood) function :
+    //      up = 0.5   means calculate 1-standard deviation error
+    //         = 2.0   means calculate 2-standard deviation error
+    minuit.SetErrorDef(1.0);
+
+    // Int_t errMigrad;
+    // Double_t tmp = 0;
+    // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+    //..............................................
+    // fix a parameter
+    for (Int_t i=0; i<vinit.GetSize(); i++)
+    {
+        if (fix[i] > 0)
+        {
+            minuit.FixParameter(i);
+            step[i] = 0.0;
+        }
+    }
+
+    //..............................................
+    //NumPars = minuit.GetNumPars();
+    //*fLog << "CallMinuit :  number of free parameters = "
+    //     << NumPars << endl;
+
+    //..............................................
+    // This doesn't seem to have any effect
+    // Set maximum number of iterations (default = 500)
+    //Int_t maxiter = 100000;
+    //minuit.SetMaxIterations(maxiter);
+
+    //..............................................
+    // minimization by the method of Migrad
+    if (method.Contains("Migrad", TString::kIgnoreCase))
+    {
+        //*fLog << "call MIGRAD" << endl;
+        if (nulloutput)
+            fLog->SetNullOutput(kTRUE);
+        Double_t tmp = 0;
+        minuit.mnexcm("MIGRAD", &tmp, 0, fErrMinimize);
+        if (nulloutput)
+            fLog->SetNullOutput(kFALSE);
+        //*fLog << "return from MIGRAD" << endl;
+    }
+
+    //..............................................
+    // same minimization as by Migrad
+    // but switches to the SIMPLEX method if MIGRAD fails to converge
+    if (method.Contains("Minimize", TString::kIgnoreCase))
+    {
+        *fLog << "call MINIMIZE" << endl;
+        Double_t tmp = 0;
+        minuit.mnexcm("MINIMIZE", &tmp, 0, fErrMinimize);
+        *fLog << "return from MINIMIZE" << endl;
+    }
+
+    //..............................................
+    // minimization by the SIMPLEX method
+    if (method.Contains("Simplex", TString::kIgnoreCase))
+    {
+        *fLog << "call SIMPLEX" << endl;
+        if (nulloutput)
+            fLog->SetNullOutput(kTRUE);
+        Int_t    maxcalls  = 3000;
+        Double_t tolerance = 0.1;
+        Double_t tmp[2];
+        tmp[0] = maxcalls;
+        tmp[1] = tolerance;
+        minuit.mnexcm("SIMPLEX", &tmp[0], 2, fErrMinimize);
+        if (nulloutput)
+            fLog->SetNullOutput(kFALSE);
+        *fLog << "return from SIMPLEX" << endl;
+    }
+
+    //..............................................
+    // check quality of minimization
+    // istat = 0   covariance matrix not calculated
+    //         1   diagonal approximation only (not accurate)
+    //         2   full matrix, but forced positive-definite
+    //         3   full accurate covariance matrix
+    //             (indication of normal convergence)
+    minuit.mnstat(fMin, fEdm, fErrdef, fNpari, fNparx, fIstat);
+
+    //if (fErrMinimize != 0  ||  fIstat < 3)
+    if (fErrMinimize != 0)
+    {
+        *fLog << "CallMinuit : Minimization failed" << endl;
+        *fLog << "       fMin = " << fMin   << ",   fEdm = "  << fEdm
+            << ",   fErrdef = "  << fErrdef << ",   fIstat = " << fIstat
+            << ",   fErrMinimize = " << fErrMinimize << endl;
+        return kFALSE;
+    }
+
+    //*fLog << "CallMinuit : Minimization was successful" << endl;
+    //*fLog << "       fMin = " << fMin   << ",   fEdm = "  << fEdm
+    //     << ",   fErrdef = "  << fErrdef << ",   fIstat = " << fIstat
+    //     << ",   fErrMinimize = " << fErrMinimize << endl;
+
+
+    //..............................................
+    // minimization by the method of Migrad
+    if (method.Contains("Hesse", TString::kIgnoreCase))
+    {
+        //*fLog << "call HESSE" << endl;
+        Double_t tmp = 0;
+        minuit.mnexcm("HESSE", &tmp, 0, fErrMinimize);
+        //*fLog << "return from HESSE" << endl;
+    }
+
+    //..............................................
+    // Minos error analysis
+    if (method.Contains("Minos", TString::kIgnoreCase))
+    {
+        //*fLog << "call MINOS" << endl;
+        Double_t tmp = 0;
+        minuit.mnexcm("MINOS", &tmp, 0, fErrMinimize);
+        //*fLog << "return from MINOS" << endl;
+    }
+
+    //..............................................
+    // Print current status of minimization
+    // if nkode = 0    only function value
+    //            1    parameter values, errors, limits
+    //            2    values, errors, step sizes, internal values
+    //            3    values, errors, step sizes, 1st derivatives
+    //            4    values, parabolic errors, MINOS errors
+
+    //Int_t nkode = 4;
+    //minuit.mnprin(nkode, fmin);
+
+    //..............................................
+    // call fcn with IFLAG = 3 (final calculation : calculate p(chi2))
+    // iflag = 1   initial calculations only
+    //         2   calculate 1st derivatives and function
+    //         3   calculate function only
+    //         4   calculate function + final calculations
+    Double_t iflag = 3;
+    Int_t errfcn3;
+    minuit.mnexcm("CALL", &iflag, 1, errfcn3);
+
+    // WW : the following statements were commented out because the
+    // Minuit object will still be used;
+    // this may be changed in the future 
+    //delete &minuit;
+    //gMinuit = save;
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMinuitInterface.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MMinuitInterface.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMinuitInterface.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MMinuitInterface
+#define MARS_MMinuitInterface
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TArrayD;
+class TArrayI;
+
+class MMinuitInterface : public MParContainer
+{
+private:
+    UInt_t   fNpar;
+    Double_t fMin,   fEdm,   fErrdef;
+    Int_t    fNpari, fNparx, fIstat;
+    Int_t    fErrMinimize;
+
+public:
+    MMinuitInterface(const char *name=NULL, const char *title=NULL);
+
+    Bool_t CallMinuit(
+                      void (*fcn)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t),
+                      const TString *name, const TArrayD &vinit, const TArrayD &step,
+                      const TArrayD &limlo, const TArrayD &limup, const TArrayI &fix,
+                      TObject *fObjectFit, const TString &method, Bool_t nulloutput);
+
+    ClassDef(MMinuitInterface, 0) // Class for interfacing with Minuit
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MMultiDimDistCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MMultiDimDistCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMultiDimDistCalc.cc	(revision 9772)
@@ -0,0 +1,228 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Rudy Bock, 5/2002 <mailto:rkb@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMultiDimDistCalc
+//
+//  Calculated a multidimensional distance. It calculates the distance to
+//  all vectors in a given matrix describing Gammas and another one
+//  describing Hadrons (non gammas). The shortest distances are avaraged.
+//  How many distances are used for avaraging can be specified in the
+//  constructor.
+//
+//  * If you want to use the nearest neighbor function for calculation use:
+//      MMultiDimDistCalc::SetUseKernelMethod(kFALSE);
+//  * If you want to use the kernel function for calculation use:
+//      MMultiDimDistCalc::SetUseKernelMethod(kTRUE); <default>
+//  * To use only the n next neighbors for your calculation use:
+//      MMultiDimDistCalc::SetUseNumRows(n);
+//  * To use all reference events set the number to 0 <default>
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MMultiDimDistCalc.h"
+
+#include <fstream>
+
+#include <TVector.h>
+
+#include "MHMatrix.h" // must be before MLogManip.h
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MDataChain.h"
+#include "MDataArray.h"
+
+#include "MHadronness.h"
+
+ClassImp(MMultiDimDistCalc);
+
+using namespace std;
+
+static const TString gsDefName  = "MMultiDimDistCalc";
+static const TString gsDefTitle = "Calculate Hadronness with Nearest Neighbor/Kernel Method";
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms and the number of distances which are used for
+// avaraging in CalcDist
+//
+MMultiDimDistCalc::MMultiDimDistCalc(const char *name, const char *title)
+    : fNum(0), fUseKernel(kTRUE), fHadronnessName("MHadronness"), fData(NULL)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    /*
+     fData = new TList;
+     fData->SetOwner();
+     */
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the data chains
+//
+MMultiDimDistCalc::~MMultiDimDistCalc()
+{
+    //    delete fData;
+}
+
+// --------------------------------------------------------------------------
+//
+// Needs:
+//  - MatrixGammas  [MHMatrix]
+//  - MatrixHadrons {MHMatrix]
+//  - MHadroness
+//  - all data containers used to build the matrixes
+//
+// The matrix object can be filles using MFillH. And must be of the same
+// number of columns (with the same meaning).
+//
+Int_t MMultiDimDistCalc::PreProcess(MParList *plist)
+{
+    fMGammas = (MHMatrix*)plist->FindObject("MatrixGammas", "MHMatrix");
+    if (!fMGammas)
+    {
+        *fLog << err << dbginf << "MatrixGammas [MHMatrix] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMHadrons = (MHMatrix*)plist->FindObject("MatrixHadrons", "MHMatrix");
+    if (!fMHadrons)
+    {
+        *fLog << err << dbginf << "MatrixHadrons [MHMatrix] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fMGammas->GetM().GetNcols() != fMHadrons->GetM().GetNcols())
+    {
+        *fLog << err << dbginf << "Error matrices have different numbers of columns... aborting." << endl;
+        return kFALSE;
+    }
+
+    /*
+    TIter Next(fMGammas->GetRules());
+    TObject *data=NULL;
+    while ((data=Next()))
+    {
+        MDataChain *chain = new MDataChain(data->GetName());
+        if (!chain->PreProcess(plist))
+        {
+            delete chain;
+            return kFALSE;
+        }
+        fData->Add(chain);
+    }
+    */
+    fData = fMGammas->GetColumns();
+    if (!fData)
+    {
+        *fLog << err << dbginf << "Error matrix doesn't contain columns... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fData->PreProcess(plist))
+    {
+        *fLog << err << dbginf << "PreProcessing of the MDataArray failed for the columns failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHadronness = (MHadronness*)plist->FindCreateObj("MHadronness", fHadronnessName);
+    if (!fHadronness)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluates the avarage over the fNum shortest distances in a
+// multidimensional space to a matrix (set of vectors) describing
+// gammas and hadrons.
+// The hadroness of the event is defines as the avarage distance to the
+// set of gammas (dg) divided by the avarage distance to the set of
+// hadrons (dh). Because this value is in teh range [0, inf] it is
+// transformed into [0,1] by:
+//  H = exp(-dh/dg);
+//
+Int_t MMultiDimDistCalc::Process()
+{
+    // first copy the data from the data array to a vector event
+    TVector event;
+    *fData >> event;
+
+    Int_t numg = fNum;
+    Int_t numh = fNum;
+    if (fNum==0)
+    {
+        numg = fMGammas->GetM().GetNrows();
+        numh = fMHadrons->GetM().GetNrows();
+    }
+    if (fUseKernel)
+    {
+        numg = -numg;
+        numh = -numh;
+    }
+
+    const Double_t dg = fMGammas->CalcDist(event, numg);
+    const Double_t dh = fMHadrons->CalcDist(event, numh);
+
+    if (dg<0 || dh<0)
+    {
+        *fLog << err << "MHMatrix::CalcDist failed (dg=" << dg << ", dh=" << dh << ")... aborting" << endl;
+        return kERROR;
+    }
+
+    fHadronness->SetHadronness(dg==0 ? 0 : exp(-dh/dg));
+    fHadronness->SetReadyToSave();
+
+    return kTRUE;
+}
+
+void MMultiDimDistCalc::StreamPrimitive(ofstream &out) const
+{
+    out << "   MMultiDimDist " << GetUniqueName();
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\")";
+    }
+    out << ";" << endl;
+
+    if (fHadronnessName!="MHadronness")
+        out << "   " << GetUniqueName() << ".SetHadronnessName(\"" << fHadronnessName << "\");" << endl;
+    if (fNum!=0)
+        out << "   " << GetUniqueName() << ".SetUseNumRows(" << fNum << ");" << endl;
+    if (fUseKernel)
+        out << "   " << GetUniqueName() << ".SetUseKernelMethod();" << endl;
+}
Index: /tags/Mars-V0.9/manalysis/MMultiDimDistCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MMultiDimDistCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MMultiDimDistCalc.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MMultiDimDistCalc
+#define MARS_MMultiDimDistCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MHMatrix;
+class MParList;
+class MDataArray;
+class MHadronness;
+
+class MMultiDimDistCalc : public MTask
+{
+private:
+    Int_t  fNum;              // number of distances used for an avarage
+    Bool_t fUseKernel;        // Flag whether kernel method should be used
+
+    TString fHadronnessName;  // Name of container storing hadronness
+
+    MHMatrix   *fMGammas;     //! Gammas describing matrix
+    MHMatrix   *fMHadrons;    //! Hadrons (non gammas) describing matrix
+
+    MHadronness *fHadronness; //! Output container for calculated hadroness
+
+    MDataArray *fData;        //! Used to store the MDataChains to get the event values
+
+    void StreamPrimitive(ofstream &out) const;
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MMultiDimDistCalc(const char *name=NULL, const char *title=NULL);
+    ~MMultiDimDistCalc();
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+    TString GetHadronnessName() const { return fHadronnessName; }
+
+    void SetUseNumRows(UShort_t n=0) { fNum = n; }
+    void SetUseKernelMethod(Bool_t k=kTRUE) { fUseKernel = k; }
+
+    ClassDef(MMultiDimDistCalc, 1) // Task to calculate nearest neighbor-/kernel-hadronness
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/manalysis/MPad.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MPad.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPad.cc	(revision 9772)
@@ -0,0 +1,2690 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 10/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MPad
+//
+//  The aim of the padding is to make the noise level (NSB + electronic noise)
+//  equal for the MC, ON and OFF data samples
+//  
+//  The target noise level is determined by 'merging' the (sigmabar vs. Theta)
+//  distributions of MC, ON and OFF data.
+//
+//  The prescription on which fraction of events has to padded from
+//  bin k of sigmabar to bin j is stored in the matrices 
+//  fHgMC, fHgON and fHgOFF.
+//
+//  By the padding the number of photons, its error and the pedestal sigmas 
+//  are altered. On average, the number of photons added is zero.
+//
+//  The formulas used can be found in Thomas Schweizer's Thesis,
+//                                    Section 2.2.1
+//
+//  The padding is done as follows :
+//
+//     Increase the sigmabar according to the matrices fHg.... Then generate 
+//     a pedestal sigma for each pixel using the 3D-histogram Theta, pixel no.,
+//     Sigma^2-Sigmabar^2 (fHDiffPixTheta).
+//
+//  The padding has to be done before the image cleaning because the
+//  image cleaning depends on the pedestal sigmas.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPad.h"
+
+#include <math.h>
+#include <stdio.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+#include <TFile.h>
+#include <TVirtualPad.h>
+
+#include "MBinning.h"
+#include "MPointingPos.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MH.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MRead.h"
+#include "MFilterList.h"
+#include "MTaskList.h"
+#include "MHBadPixels.h"
+#include "MFillH.h"
+#include "MHSigmaTheta.h"
+#include "MEvtLoop.h"
+
+ClassImp(MPad);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Constructor. 
+//
+MPad::MPad(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MPad";
+  fTitle = title ? title : "Task for the padding";
+
+  fType = "";
+
+  fHSigmaTheta       = NULL;
+  fHSigmaThetaOuter  = NULL;
+
+  fHSigmaThetaMC         = NULL;
+  fHSigmaThetaOuterMC    = NULL;
+  fHDiffPixThetaMC       = NULL;
+  fHDiffPixThetaTargetMC = NULL;
+
+  fHSigmaThetaON          = NULL;
+  fHSigmaThetaOuterON     = NULL;
+  fHDiffPixThetaON        = NULL;
+  fHDiffPixThetaTargetON  = NULL;
+
+  fHSigmaThetaOFF         = NULL;
+  fHSigmaThetaOuterOFF    = NULL;
+  fHDiffPixThetaOFF       = NULL;
+  fHDiffPixThetaTargetOFF = NULL;
+
+  fHgMC  = NULL;
+  fHgON  = NULL;
+  fHgOFF = NULL;
+
+  fHgOuterMC  = NULL;
+  fHgOuterON  = NULL;
+  fHgOuterOFF = NULL;
+
+  fHSigmaPedestal = NULL;
+  fHPhotons       = NULL;
+  fHNSB           = NULL;
+
+  fNamePedPhotCam = "MPedPhotCamFromData";
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MPad::~MPad()
+{
+  delete fHSigmaTheta;
+  delete fHSigmaThetaOuter;
+
+  if (fHSigmaThetaMC)
+  {
+    delete fHSigmaThetaMC;
+    delete fHSigmaThetaOuterMC;
+    delete fHDiffPixThetaMC;
+    delete fHDiffPixThetaTargetMC;
+    delete fHgMC;
+    delete fHgOuterMC;
+  }
+
+  if (fHSigmaThetaON)
+  {
+    delete fHSigmaThetaON;
+    delete fHSigmaThetaOuterON;
+    delete fHDiffPixThetaON;
+    delete fHDiffPixThetaTargetON;
+    delete fHgON;
+    delete fHgOuterON;
+  }
+
+  if (fHSigmaThetaOFF)
+  {
+    delete fHSigmaThetaOFF;
+    delete fHSigmaThetaOuterOFF;
+    delete fHDiffPixThetaOFF;
+    delete fHDiffPixThetaTargetOFF;
+    delete fHgOFF;
+    delete fHgOuterOFF;
+  }
+
+  delete fHSigmaPedestal;
+  delete fHPhotons;
+  delete fHNSB;
+
+  delete fInfile;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetNamePedPhotCam 
+//
+//    set the name of the MPedPhotCam container
+
+void MPad::SetNamePedPhotCam(const char *name) 
+{
+  fNamePedPhotCam = name;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set type of data to be padded
+//
+//     this is not necessary if the type of the data can be recognized
+//     directly from the input
+//
+//
+void MPad::SetDataType(const char* type)
+{
+  fType = type;
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read pad histograms from a file
+//      these are the histograms generated by MMakePadHistograms
+//
+Bool_t MPad::ReadPadHistograms(TString type, TString namepad)
+{
+
+  //------------------------------------
+  Int_t OK = 0;
+
+  if (type == "ON")
+  {
+      *fLog << inf << "MPad : Read pad histograms for " << type 
+            << " data from file " << namepad << endl;
+
+      TH2D *sigth    = new TH2D;
+      TH2D *sigthout = new TH2D;
+      TH3D *diff     = new TH3D;
+
+      TFile *fInfile = new TFile(namepad);
+      fInfile->ls();
+
+      OK = sigth->Read("2D-ThetaSigmabar(Inner)"); 
+      fHSigmaThetaON = new TH2D( (const TH2D&)(*sigth) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Inner)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaON->SetNameTitle("2D-ThetaSigmabarON", 
+                                   "2D-ThetaSigmabarON (orig.)");
+      *fLog << all 
+            << "        MPad : Object '2D-ThetaSigmabar(Inner)' was read in" 
+            << endl;
+
+
+      OK = sigthout->Read("2D-ThetaSigmabar(Outer)");
+      fHSigmaThetaOuterON = new TH2D( (const TH2D&)(*sigthout) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Outer)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaOuterON->SetNameTitle("2D-ThetaSigmabarOuterON", 
+                                   "2D-ThetaSigmabarOuterON (orig.)");
+      *fLog << all 
+            << "        MPad : Object '2D-ThetaSigmabar(Outer)' was read in" 
+            << endl;
+
+
+      OK = diff->Read("3D-ThetaPixDiff");
+      fHDiffPixThetaON = new TH3D( (const TH3D&)(*diff) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '3D-ThetaPixDiff' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHDiffPixThetaON->SetNameTitle("3D-ThetaPixDiffON", 
+                                     "3D-ThetaPixDiffON (orig.)");
+      *fLog << all 
+            << "        MPad : Object '3D-ThetaPixDiff' was read in" << endl;
+
+
+      return kTRUE;
+  }
+
+  //------------------------------------
+  if (type == "OFF")
+  {
+      *fLog << inf << "MPad : Read pad histograms for " << type 
+            << " data from file " << namepad << endl;
+
+
+      TH2D *sigth    = new TH2D;
+      TH2D *sigthout = new TH2D;
+      TH3D *diff     = new TH3D;
+
+      TFile *fInfile = new TFile(namepad);
+      fInfile->ls();
+
+      OK = sigth->Read("2D-ThetaSigmabar(Inner)");
+      fHSigmaThetaOFF = new TH2D( (const TH2D&)(*sigth) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Inner)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaOFF->SetNameTitle("2D-ThetaSigmabarOFF", 
+                                    "2D-ThetaSigmabarOFF (orig.)");
+      *fLog << all 
+            << "        MPad : Object '2D-ThetaSigmabar(Inner)' was read in" 
+            << endl;
+
+
+      OK = sigthout->Read("2D-ThetaSigmabar(Outer)");
+      fHSigmaThetaOuterOFF = new TH2D( (const TH2D&)(*sigthout) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Outer)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaOuterOFF->SetNameTitle("2D-ThetaSigmabarOuterOFF", 
+                                    "2D-ThetaSigmabarOuterOFF (orig.)");
+      *fLog << all 
+            << "        MPad : Object '2D-ThetaSigmabar(Outer)' was read in" 
+            << endl;
+
+
+      OK = diff->Read("3D-ThetaPixDiff");
+      fHDiffPixThetaOFF = new TH3D( (const TH3D&)(*diff) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '3D-ThetaPixDiff' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHDiffPixThetaOFF->SetNameTitle("3D-ThetaPixDiffOFF", 
+                                      "3D-ThetaPixDiffOFF (orig.)");
+      *fLog << all 
+            << "        MPad : Object '3D-ThetaPixDiff' was read in" << endl;
+
+
+
+      return kTRUE;
+  }
+
+    //------------------------------------
+  if (type == "MC")
+  {
+
+      TH2D *sigth    = new TH2D;
+      TH2D *sigthout = new TH2D;
+      TH3D *diff     = new TH3D;
+
+      *fLog << inf << "MPad : Read pad histograms for " << type 
+            << " data from file " << namepad << endl;
+
+      TFile *fInfile = new TFile(namepad);
+      fInfile->ls();
+
+      OK = sigth->Read("2D-ThetaSigmabar(Inner)");
+      fHSigmaThetaMC = new TH2D( (const TH2D&)(*sigth) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Inner)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaMC->SetNameTitle("2D-ThetaSigmabarMC", 
+                                   "2D-ThetaSigmabarMC (orig.)");
+      *fLog << all 
+            << "       MPad : Object '2D-ThetaSigmabar(Inner)' was read in" 
+            << endl;
+
+      OK = sigthout->Read("2D-ThetaSigmabar(Outer)");
+      fHSigmaThetaOuterMC = new TH2D( (const TH2D&)(*sigthout) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '2D-ThetaSigmabar(Outer)' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHSigmaThetaOuterMC->SetNameTitle("2D-ThetaSigmabarOuterMC", 
+                                   "2D-ThetaSigmabarOuterMC (orig.)");
+      *fLog << all 
+            << "       MPad : Object '2D-ThetaSigmabar(Outer)' was read in" 
+            << endl;
+
+
+      
+      OK = diff->Read("3D-ThetaPixDiff");
+      fHDiffPixThetaMC = new TH3D( (const TH3D&)(*diff) );
+      if (!OK)
+      {
+        *fLog << all 
+              << "        MPad : Object '3D-ThetaPixDiff' not found" 
+              << endl;
+        return kFALSE;
+      }
+
+      fHDiffPixThetaMC->SetNameTitle("3D-ThetaPixDiffMC", 
+                                     "3D-ThetaPixDiffMC (orig.)");
+
+      *fLog << all 
+            << "       MPad : Object '3D-ThetaPixDiff' was read in" << endl;
+      
+      return kTRUE;
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Merge the distributions 
+//   fHSigmaTheta      2D-histogram  (Theta, sigmabar)
+//
+// ===>   of ON, OFF and MC data   <==============
+//
+// and define the matrices fHgMC, fHgON and fHgOFF 
+//
+// These matrices tell which fraction of events should be padded 
+// from bin k of sigmabar to bin j
+//
+
+Bool_t MPad::MergeONOFFMC(TString nameon, TString nameoff,
+                          TString namemc, TString fileout)
+{
+  // read the histograms produced by MMakePadHistograms
+  TH2D *hist2patternin  = NULL;
+  TH2D *hist2patternout = NULL;
+  TH3D *hist3pattern = NULL;
+
+  Bool_t OK = 0;
+
+  if (namemc != "")
+  {
+    OK = ReadPadHistograms("MC",  namemc);  
+    if (!OK) 
+    {
+      *fLog << err << "MPad::MergeONOFFMC : Pad histograms for MC not available"
+            << endl;
+      return kFALSE;
+    }
+
+    hist2patternin  = fHSigmaThetaMC;
+    hist2patternout = fHSigmaThetaOuterMC;
+    hist3pattern = fHDiffPixThetaMC;
+    *fLog << inf << "" << endl;
+    *fLog << inf << "MPad::MergeONOFFMC : Pad histograms for MC data read from file "
+             << namemc << endl;
+  }
+
+  if (nameoff != "")
+  {
+    OK = ReadPadHistograms("OFF", nameoff);
+    if (!OK) 
+    {
+      *fLog << err << "MPad::MergeONOFFMC : Pad histograms for OFF not available"
+            << endl;
+      return kFALSE;
+    }
+
+    hist2patternin  = fHSigmaThetaOFF;
+    hist2patternout = fHSigmaThetaOuterOFF;
+    hist3pattern = fHDiffPixThetaOFF;  
+    *fLog << inf << "" << endl;
+    *fLog << inf << "MPad::MergeONOFFMC : Pad histograms for OFF data read from file "
+             << nameoff << endl;
+  }
+
+  if (nameon != "")
+  {
+    OK = ReadPadHistograms("ON",  nameon);
+    if (!OK) 
+    {
+      *fLog << err << "MPad::MergeONOFFMC : Pad histograms for ON not available"
+            << endl;
+      return kFALSE;
+    }
+
+    hist2patternin  = fHSigmaThetaON;
+    hist2patternout = fHSigmaThetaOuterON;
+    hist3pattern = fHDiffPixThetaON;
+    *fLog << inf << "" << endl;
+    *fLog << inf << "MPad::MergeONOFFMC : Pad histograms for ON data read from file "
+             << nameon << endl;
+  }  
+
+  //*fLog << "hist2patternin = "  << hist2patternin << endl;
+  //*fLog << "hist2patternout = " << hist2patternout << endl;
+  //*fLog << "hist3pattern = " << hist3pattern << endl;
+
+
+  TAxis *axs = hist2patternin->GetXaxis();
+  Int_t nbinsthetas = axs->GetNbins();
+  //*fLog << "vor fHSigmaTheta : nbinsthetas = " << nbinsthetas << endl;
+
+  TArrayD edgess;
+  edgess.Set(nbinsthetas+1);
+  for (Int_t i=0; i<=nbinsthetas; i++)
+  {
+    edgess[i] = axs->GetBinLowEdge(i+1);
+    //*fLog << all << "i, theta low edge = " << i << ",  " << edgess[i] 
+    //      << endl; 
+  }
+
+
+  //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+  // for testing
+  /*
+  TAxis *xa = sigthon.GetXaxis();
+  Int_t nbitheta = xa->GetNbins();
+
+  TAxis *ya = sigthon.GetYaxis();
+  Int_t nbisig = ya->GetNbins();
+  for (Int_t i=1; i<=nbitheta; i++)
+  {
+    for (Int_t j=1; j<=nbisig; j++)
+    {
+      if (i>0)
+      {
+        sigthmc.SetBinContent( i, j, (Float_t) (625000.0+(nbisig*nbisig*nbisig-j*j*j)) );
+        sigthon.SetBinContent( i, j, (Float_t)(1.0) );
+        sigthoff.SetBinContent(  i, j, (Float_t)( (0.5*nbisig-j)*(0.5*nbisig-j)            ) );
+      }
+      else
+      {
+        sigthmc.SetBinContent( i, j, 0.0);
+        sigthon.SetBinContent( i, j, 0.0);
+        sigthoff.SetBinContent(i, j, 0.0);
+      }
+    }
+  }
+  */
+  //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+  *fLog << all << "----------------------------------------------------------------------------------" << endl;
+  *fLog << all << "MPad::MergeONOFFMC(); Merge the ON, OFF and MC histograms to obtain the target distributions for the padding"
+        << endl;
+
+
+  //-------------------------
+  fHSigmaTheta = new TH2D;
+  hist2patternin->Copy(*fHSigmaTheta);
+  fHSigmaTheta->SetNameTitle("2D-ThetaSigmabar", "2D-ThetaSigmabar (target)");
+
+  //-------------------------
+  fHSigmaThetaOuter = new TH2D;
+  hist2patternout->Copy(*fHSigmaThetaOuter);
+  fHSigmaThetaOuter->SetNameTitle("2D-ThetaSigmabarOuter", "2D-ThetaSigmabarOuter (target)");
+
+  //--------------------------
+  fHDiffPixThetaTargetMC = new TH3D;
+  hist3pattern->Copy(*fHDiffPixThetaTargetMC);
+  fHDiffPixThetaTargetMC->SetNameTitle("3D-ThetaPixDiffTargetMC", "3D-ThetaPixDiffMC (target)");
+
+  //-------------------------  
+  fHDiffPixThetaTargetON = new TH3D;
+  hist3pattern->Copy(*fHDiffPixThetaTargetON);
+  fHDiffPixThetaTargetON->SetNameTitle("3D-ThetaPixDiffTargetON", "3D-ThetaPixDiffON (target)");
+
+  //-------------------------
+  fHDiffPixThetaTargetOFF = new TH3D;
+  hist3pattern->Copy(*fHDiffPixThetaTargetOFF);
+  fHDiffPixThetaTargetOFF->SetNameTitle("3D-ThetaPixDiffTargetOFF", "3D-ThetaPixDiffOFF (target)");
+
+  *fLog << all << "MPad::MergeONOFFMC(); Histograms for the merged padding plots were booked" 
+        << endl;
+
+
+  //--------------------------
+
+  // get binning for fHgON, fHgOFF and fHgMC  from fHSigmaTheta
+  // binning in Theta
+  TAxis *ax = hist2patternin->GetXaxis();
+  Int_t nbinstheta = ax->GetNbins();
+
+  //*fLog << "nbinstheta = " << nbinstheta << endl;
+
+  TArrayD edgesx;
+  edgesx.Set(nbinstheta+1);
+  for (Int_t i=0; i<=nbinstheta; i++)
+  {
+    edgesx[i] = ax->GetBinLowEdge(i+1);
+    //*fLog << all << "i, theta low edge = " << i << ",  " << edgesx[i] 
+    //      << endl; 
+  }
+  MBinning binth;
+  binth.SetEdges(edgesx);
+
+  // binning in sigmabar
+  TAxis *ay = hist2patternin->GetYaxis();
+  Int_t nbinssig = ay->GetNbins();
+
+  //*fLog << "nbinssig = " << nbinssig << endl;
+
+  TArrayD edgesy;
+  edgesy.Set(nbinssig+1);
+  for (Int_t i=0; i<=nbinssig; i++)
+  {
+    edgesy[i] = ay->GetBinLowEdge(i+1); 
+    //*fLog << all << "i, sigmabar low edge = " << i << ",  " << edgesy[i] 
+    //      << endl; 
+  }
+  MBinning binsg;
+  binsg.SetEdges(edgesy);
+
+
+  fHgMC = new TH3D;
+  MH::SetBinning(fHgMC, &binth, &binsg, &binsg);
+  fHgMC->SetNameTitle("3D-PaddingMatrixMC", "3D-PadMatrixThetaMC");
+
+  fHgON = new TH3D;
+  MH::SetBinning(fHgON, &binth, &binsg, &binsg);
+  fHgON->SetNameTitle("3D-PaddingMatrixON", "3D-PadMatrixThetaON");
+
+  fHgOFF = new TH3D;
+  MH::SetBinning(fHgOFF, &binth, &binsg, &binsg);
+  fHgOFF->SetNameTitle("3D-PaddingMatrixOFF", "3D-PadMatrixThetaOFF");
+
+  *fLog << all << "fHg histograms were booked" << endl;
+
+  //-----------------------
+  // get binning for fHgOuterON, fHgOuterOFF and fHgOuterMC  
+  // from fHSigmaThetaOuter
+  // binning in sigmabar
+  TAxis *ayout = hist2patternout->GetYaxis();
+  Int_t nbinssigout = ayout->GetNbins();
+  TArrayD edgesyout;
+  edgesyout.Set(nbinssigout+1);
+  for (Int_t i=0; i<=nbinssigout; i++)
+  {
+    edgesyout[i] = ayout->GetBinLowEdge(i+1); 
+    //*fLog << all << "i, sigmabar low edge = " << i << ",  " << edgesyout[i] 
+    //      << endl; 
+  }
+  MBinning binsgout;
+  binsgout.SetEdges(edgesyout);
+
+
+  fHgOuterMC = new TH3D;
+  MH::SetBinning(fHgOuterMC, &binth, &binsgout, &binsgout);
+  fHgOuterMC->SetNameTitle("3D-PaddingMatrixOuterMC", "3D-PadMatrixThetaOuterMC");
+
+  fHgOuterON = new TH3D;
+  MH::SetBinning(fHgOuterON, &binth, &binsgout, &binsgout);
+  fHgOuterON->SetNameTitle("3D-PaddingMatrixOuterON", "3D-PadMatrixThetaOuterON");
+
+  fHgOuterOFF = new TH3D;
+  MH::SetBinning(fHgOuterOFF, &binth, &binsgout, &binsgout);
+  fHgOuterOFF->SetNameTitle("3D-PaddingMatrixOuterOFF", "3D-PadMatrixThetaOuterOFF");
+
+  *fLog << all << "fHgOuter histograms were booked" << endl;
+
+
+  //--------------------------------------------------------------------
+  // define the first (A), second (B) and third (C) data set
+  // (A, B, C) may be (ON, OFF, MC)
+  //               or (ON, OFF, "")
+  //               or (ON, MC,  "")
+  //               or (OFF,MC,  "")
+  // or the same sets in any other order
+
+  TString tagA = "";
+  TString tagB = "";
+  TString tagC = "";
+
+  TH2D *histA = NULL;
+  TH2D *histB = NULL;
+  TH2D *histC = NULL;
+
+  TH2D *histOuterA = NULL;
+  TH2D *histOuterB = NULL;
+  TH2D *histOuterC = NULL;
+
+  TH3D *histDiffA = NULL;
+  TH3D *histDiffB = NULL;
+  TH3D *histDiffC = NULL;
+
+  TH3D *fHgA = NULL;
+  TH3D *fHgB = NULL;
+  TH3D *fHgC = NULL;
+
+  TH3D *fHgOuterA = NULL;
+  TH3D *fHgOuterB = NULL;
+  TH3D *fHgOuterC = NULL;
+
+  if (fHSigmaThetaON)
+  {
+    tagA = "ON";
+    histA      = fHSigmaThetaON;
+    histOuterA = fHSigmaThetaOuterON;
+    histDiffA  = fHDiffPixThetaON;
+    fHgA       = fHgON;
+    fHgOuterA  = fHgOuterON;
+
+    if (fHSigmaThetaOFF)
+    {
+      tagB = "OFF";
+      histB      = fHSigmaThetaOFF;
+      histOuterB = fHSigmaThetaOuterOFF;
+      histDiffB  = fHDiffPixThetaOFF;
+      fHgB       = fHgOFF;
+      fHgOuterB  = fHgOuterOFF;
+
+      if (fHSigmaThetaMC)
+      {
+        tagC = "MC";
+        histC      = fHSigmaThetaMC;
+        histOuterC = fHSigmaThetaOuterMC;
+        histDiffC  = fHDiffPixThetaMC;
+        fHgC       = fHgMC;
+        fHgOuterC  = fHgOuterMC;
+      }
+    }
+
+    else if (fHSigmaThetaMC)
+    {
+      tagB = "MC";
+      histB      = fHSigmaThetaMC;
+      histOuterB = fHSigmaThetaOuterMC;
+      histDiffB  = fHDiffPixThetaMC;
+      fHgB       = fHgMC;
+      fHgOuterB  = fHgOuterMC;
+    }
+  }
+  
+  else if (fHSigmaThetaOFF)
+  {
+    tagA = "OFF";
+    histA      = fHSigmaThetaOFF;
+    histOuterA = fHSigmaThetaOuterOFF;
+    histDiffA  = fHDiffPixThetaOFF;
+    fHgA       = fHgOFF;
+    fHgOuterA  = fHgOuterOFF;
+
+    if (fHSigmaThetaMC)
+    {
+      tagB = "MC";
+      histB      = fHSigmaThetaMC;
+      histOuterB = fHSigmaThetaOuterMC;
+      histDiffB  = fHDiffPixThetaMC;
+      fHgB       = fHgMC;
+      fHgOuterB  = fHgOuterMC;
+    }
+
+    else
+    {
+      *fLog << err << "MPad::MergeONOFFMC; there are no data sets to be merged : tagA, tagB, tagC = "
+            << tagA << ",  " << tagB << ",  " << tagC << endl;
+      return kFALSE;
+    }
+  }
+ 
+  else
+  {
+    *fLog << err << "MPad::MergeONOFFMC; there are no data sets to be merged"
+          << endl;
+    return kFALSE;
+  }
+
+  *fLog << inf << "MPad::MergeONOFFMC; the following data sets will be merged : "
+        << tagA << "   " << tagB << "   " << tagC << endl;
+
+
+  //-------------------------------------------
+  // merge the 2D histograms (theta, Sigmabar)
+  //       from the data sets A, B and C
+  // for the inner pixels and for the outer pixels
+
+  TString canv("Inner");
+  MergeABC(tagA, tagB, tagC,  histA, histB, histC, 
+           fHSigmaTheta,      fHgA, fHgB, fHgC,    canv);
+
+  TString canvout("Outer");
+  MergeABC(tagA, tagB, tagC,  histOuterA, histOuterB, histOuterC, 
+           fHSigmaThetaOuter, fHgOuterA,  fHgOuterB,  fHgOuterC,  canvout);
+
+
+  //-------------------------------------------  
+  // Define the target distributions    fHDiffPixThetaTargetON, ..OFF,  ..MC
+  // (fHDiffPixThetaTarget.. will be used in the padding)
+
+
+  //............   start of new loop over Theta bins   ....................
+  for (Int_t j=1; j<=nbinstheta; j++)
+  {
+    // fraction of A/B/C events to be padded : fracA, fracB, fracC
+    Double_t fracA = 0.0;
+    Double_t fracB = 0.0;
+    Double_t fracC = 0.0;
+
+    fracA = fHgA->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+    fracB = fHgB->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+    if (tagC != "") fracC = fHgC->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+
+    *fLog << all << "Theta bin j : tagA, fracA, tagB, fracB, tagC, fracC = " 
+          << j << ".    " << tagA << ": " << fracA << ";  " << tagB << ": " 
+	  << fracB << ";  " << tagC << ": " << fracC << endl; 
+
+
+    //------------------------------------------------------------------
+    // for the current theta bin :
+    // define target distribution  'sigma^2-sigmabar^2 vs. pixel number'
+    // take the distribution from that sample which has the lowest 'frac.'
+    // At present, for all samples (ON, OFF, MC) the same target distribution 
+    // is used
+
+    Double_t fracmin = fracA;
+    TString tag = tagA;
+
+    if (tagB != "")
+    {
+      if (fracB < fracmin)
+      {
+        fracmin = fracB;
+        tag = tagB;
+      }
+      if (tagC != "")
+      {
+        if (fracC < fracmin)
+        {
+          fracmin = fracC;
+          tag = tagC;
+        }
+      }
+    }
+
+    *fLog << all << "MPad::MergeONOFFMC; thetabin " << j 
+          << " : sample with smallest frac = " << tag << endl; 
+
+    TH3D *hist3 = NULL;
+    if (tag == "ON")
+      hist3 = fHDiffPixThetaON;
+    else if (tag == "OFF")
+      hist3 = fHDiffPixThetaOFF;
+    else if (tag == "MC")
+      hist3 = fHDiffPixThetaMC;
+
+    ay = hist3->GetYaxis();
+    Int_t nbinspixel = ay->GetNbins();
+
+    TAxis *az = hist3->GetZaxis();
+    Int_t nbinsdiff = az->GetNbins();
+
+    for (Int_t k=1; k<=nbinspixel; k++)
+    {
+      for (Int_t l=1; l<=nbinsdiff; l++)
+      {
+        Double_t cont = hist3->GetBinContent(j, k,l);
+        fHDiffPixThetaTargetON-> SetBinContent(j, k, l, cont);  
+        fHDiffPixThetaTargetOFF->SetBinContent(j, k, l, cont);  
+        fHDiffPixThetaTargetMC-> SetBinContent(j, k, l, cont);  
+      }
+    }
+  }
+  //............   end of new loop over Theta bins   ....................
+
+  *fLog << all 
+        << "MPad::MergeONOFFMC(); The target distributions for the padding have been created" 
+        << endl;
+  *fLog << all << "----------------------------------------------------------" 
+        << endl;
+  //--------------------------------------------
+
+  fHSigmaTheta->SetDirectory(NULL);
+  fHSigmaThetaOuter->SetDirectory(NULL);
+
+  if (tagA == "MC"  ||  tagB == "MC"  ||  tagC == "MC")
+  { 
+    fHSigmaThetaMC->SetDirectory(NULL);
+    fHSigmaThetaOuterMC->SetDirectory(NULL);
+    fHDiffPixThetaMC->SetDirectory(NULL);
+    fHgMC->SetDirectory(NULL);
+    fHgOuterMC->SetDirectory(NULL);
+  }
+
+  if (tagA == "ON"  ||  tagB == "ON"  ||  tagC == "ON")
+  { 
+    fHSigmaThetaON->SetDirectory(NULL);
+    fHSigmaThetaOuterON->SetDirectory(NULL);
+    fHDiffPixThetaON->SetDirectory(NULL);
+    fHgON->SetDirectory(NULL);
+    fHgOuterON->SetDirectory(NULL);
+  }
+
+  if (tagA == "OFF"  ||  tagB == "OFF"  ||  tagC == "OFF")
+  { 
+    fHSigmaThetaOFF->SetDirectory(NULL);
+    fHSigmaThetaOuterOFF->SetDirectory(NULL);
+    fHDiffPixThetaOFF->SetDirectory(NULL);
+    fHgOFF->SetDirectory(NULL);
+    fHgOuterOFF->SetDirectory(NULL);
+  }
+
+  // write the target padding histograms onto a file  ---------
+  WritePaddingDist(fileout);     
+
+  //-------------------------------------------------------
+  TCanvas *pad = MH::MakeDefCanvas("target", "target", 600, 300); 
+  gROOT->SetSelectedPad(NULL);
+
+  pad->Divide(2, 1);
+
+  pad->cd(1);
+  gPad->SetBorderMode(0);
+  fHSigmaTheta->SetDirectory(NULL);
+  fHSigmaTheta->UseCurrentStyle();
+  fHSigmaTheta->DrawClone();
+  fHSigmaTheta->SetBit(kCanDelete);    
+
+  pad->cd(2);
+  gPad->SetBorderMode(0);
+  fHSigmaThetaOuter->SetDirectory(NULL);
+  fHSigmaThetaOuter->UseCurrentStyle();
+  fHSigmaThetaOuter->DrawClone();
+  fHSigmaThetaOuter->SetBit(kCanDelete);    
+
+  pad->Draw();
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Merge the 2D-histograms  (Theta, sigmabar) 
+//       hA, hB and hC
+//
+// - put the merged distribution into hM
+// - and define the matrices hgA, hgB and hgC 
+//
+// These matrices tell which fraction of events should be padded 
+// from bin k of sigmabar to bin j
+//
+
+Bool_t MPad::MergeABC(TString tA, TString tB, TString tC,
+                      TH2D *hA,   TH2D *hB,   TH2D *hC,   TH2D *hM,
+                      TH3D *hgA,  TH3D *hgB,  TH3D *hgC, TString canv)
+{
+  *fLog << all << "MPad::MergeABC();  Entry" << endl;
+
+  TAxis *ax = hM->GetXaxis();
+  Int_t nbinstheta = ax->GetNbins();
+
+  TAxis *ay = hM->GetYaxis();
+  Int_t nbinssig = ay->GetNbins();
+
+  TArrayD edgesy;
+  edgesy.Set(nbinssig+1);
+  for (Int_t i=0; i<=nbinssig; i++)
+  {
+    edgesy[i] = ay->GetBinLowEdge(i+1); 
+    //*fLog << all << "i, sigmabar low edge = " << i << ",  " << edgesy[i] 
+    //      << endl; 
+  }
+  MBinning binsg;
+  binsg.SetEdges(edgesy);
+
+
+  //............   loop over Theta bins   ...........................
+
+  //*fLog << all << "MPad::MergeABC(); bins of Theta, Sigmabarold, Sigmabarnew, fraction of events to be padded" << endl;
+  for (Int_t l=1; l<=nbinstheta; l++)
+  {
+    //-------------------------------------------
+    // merge A (ON) and B (OFF) distributions
+    // input : hista is the normalized 1D distr. of sigmabar for A (ON)  data
+    //         histb is the normalized 1D distr. of sigmabar for B (OFF) data
+    // output : histap    will be the merged distribution (AB)
+    //          fHga(k,j) will tell which fraction of A (ON) events should be 
+    //                    padded from bin k to bin j
+    //          fHgb(k,j) will tell which fraction of B (OFF) events should be 
+    //                    padded from bin k to bin j
+
+    TH2D * fHga = new TH2D;
+    MH::SetBinning(fHga, &binsg, &binsg);
+    TH2D * fHgb = new TH2D;
+    MH::SetBinning(fHgb, &binsg, &binsg);
+
+    TH1D *hista  = hA->ProjectionY("sigon_y", l, l, "");
+    TString tita(canv);
+    tita += "-A (orig)-";
+    tita += l;
+    hista->SetNameTitle(tita, tita); 
+    Stat_t suma = hista->Integral();
+    if (suma != 0.0) hista->Scale(1./suma);
+
+    TH1D *histap  = new TH1D( (const TH1D&)*hista );
+    TString titab(canv);
+    titab += "-AB (merged)-";
+    titab += l;
+    histap->SetNameTitle(titab, titab); 
+
+    TH1D *histb  = hB->ProjectionY("sigoff_y", l, l, "");
+    TString titb(canv);
+    titb += "-B (orig)-";
+    titb += l;
+    histb->SetNameTitle(titb, titb); 
+    Stat_t sumb = histb->Integral();
+    if (sumb != 0.0) histb->Scale(1./sumb);
+
+    if (suma == 0.0  ||  sumb == 0.0)
+    {
+      delete hista;
+      delete histb;
+      delete fHga;
+      delete fHgb;
+      delete histap;
+
+      *fLog << err 
+            << "cannot call Merge2Distributions(A=" << tA << ", B="
+            << tB << ")  for theta bin l = " 
+            << l << ";  NevA, NevB = " << suma << ",  " << sumb << endl;
+
+      // clear the corresponding area of fHSigmaTheta
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a = 0.0;
+        hM->SetBinContent(l, j, a);
+
+        //*fLog << "MPad::MergeABC; l, j, a = " << l << ",  " << j << ",  "
+        //      << a << endl;
+      }
+
+      // go to next theta bin (l)
+      continue;
+    }
+
+    //*fLog << "call Merge2Distributions(A=" << tA << ", B="
+    //      << tB << ")  for theta bin l = "
+    //      << l << endl;
+
+    TString canvab(canv);
+    canvab += "AB-";
+    canvab += l;
+    Merge2Distributions(hista, histb, histap, fHga, fHgb, nbinssig, canvab);
+
+    // fill fHgA and fHgB
+    for (Int_t k=1; k<=nbinssig; k++)
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a = fHga->GetBinContent(k,j);
+        hgA->SetBinContent(l, k, j, a);
+
+        Double_t b = fHgb->GetBinContent(k,j);
+        hgB->SetBinContent(l, k, j, b);
+      }
+
+
+    //-------------------------------------------------
+    // if there is no further distribution to be merged
+    // fill target distribution fHSigmaTheta 
+    // 
+    if (!hC)
+    {
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a = histap->GetBinContent(j);
+        hM->SetBinContent(l, j, a);
+
+        //*fLog << "MPad::MergeABC; l, j, a = " << l << ",  " << j << ",  "
+        //      << a << endl;
+      }
+
+      delete fHga;
+      delete fHgb;
+      delete histap;
+    }
+
+    //--------------   next merge (start) ----------------------------------
+    if (hC)
+    {
+
+    // now merge AB (ON-OFF) and C (MC) distributions
+    // input : histe is the result of the merging of A (ON) and B (OFF)
+    //                  distributions  
+    //         histf is the normalized 1D distr. of sigmabar for C (MC) data
+    // output : histep    will be the merged distribution (target distribution)
+    //          fHge(k,j) will tell which fraction of A (ON), B (OFF) events 
+    //                    should be padded from bin k to bin j
+    //          fHgf(k,j) will tell which fraction of C (MC) events should be 
+    //                    padded from bin k to bin j
+
+    TH2D * fHge = new TH2D;
+    MH::SetBinning(fHge, &binsg, &binsg);
+    TH2D * fHgf = new TH2D;
+    MH::SetBinning(fHgf, &binsg, &binsg);
+
+    TH1D *histe  = new TH1D( (const TH1D&)*histap);
+    TString titabm(canv);
+    titabm += "-AB (merged)-";
+    titabm += l;
+    histe->SetNameTitle(titabm, titabm); 
+
+    TH1D *histep  = new TH1D( (const TH1D&)*histe);
+    TString titabcm(canv);
+    titabcm +="-ABC (merged)-";
+    titabcm += l;
+    histep->SetNameTitle(titabcm, titabcm); 
+
+    TH1D *histf  = hC->ProjectionY("sigmc_y", l, l, "");
+    TString titc(canv);
+    titc += "-C (orig)-";
+    titc += l;
+    histf->SetNameTitle(titc, titc); 
+    Double_t sumf = histf->Integral();
+    if (sumf != 0.0) histf->Scale(1./sumf);
+
+    if (sumf == 0.0)
+    {
+      delete hista;
+      delete histb;
+      delete fHga;
+      delete fHgb;
+      delete histap;
+
+      delete histe;
+      delete histf;
+      delete fHge;
+      delete fHgf;
+      delete histep;
+
+      *fLog << err 
+            << "cannot call Merge2Distributions(AB=" << tA << "-" << tB 
+            << ", C=" << tC << ")  for theta bin l = " 
+            << l << ";  NevC = " << sumf << endl;
+
+      // go to next theta bin (l)
+      continue;
+    }
+
+    //*fLog << "call Merge2Distributions(AB=" << tA << "-" << tB 
+    //      << ", C=" << tC << ")  for theta bin l = "
+    //      << l << endl;
+
+    TString canvabc(canv);
+    canvabc += "ABC-";
+    canvabc += l;
+    Merge2Distributions(histe, histf, histep, fHge, fHgf, nbinssig, canvabc);
+
+    // update fHgA and fHgB
+    UpdateHg(fHga, histap, fHge, hgA,  nbinssig, l);
+    UpdateHg(fHgb, histap, fHge, hgB, nbinssig, l);
+
+    // fill fHgC
+    for (Int_t k=1; k<=nbinssig; k++)
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t f = fHgf->GetBinContent(k,j);
+        hgC->SetBinContent(l, k, j, f);
+      }
+
+    // fill target distribution fHSigmaTheta 
+    // 
+    for (Int_t j=1; j<=nbinssig; j++)
+    {
+      Double_t ep = histep->GetBinContent(j);
+      hM->SetBinContent(l, j, ep);
+
+      //*fLog << "MPad::MergeABC; l, j, ep = " << l << ",  " << j << ",  "
+      //      << ep << endl;
+    }
+
+
+    //-------------------------------------------
+
+    delete hista;
+    delete histb;
+    delete fHga;
+    delete fHgb;
+    delete histap;
+
+    delete histe;
+    delete histf;
+    delete fHge;
+    delete fHgf;
+    delete histep;
+
+    }
+    //--------------   next merge (end) ----------------------------------
+
+  }
+  //............   end of loop over Theta bins   ....................
+
+  *fLog << all << "MPad::MergeABC();  Return" << endl;
+
+  return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+// Merge the sigmabar distributions of 2 samples (samples A and B)
+//
+// input : the original distributions for samples A and B (hista, histb)
+//
+// output : the prescription which fraction of events should be padded
+//          from the sigmabar bin k to bin j (fHgMC, fHgON, fHgOFF)
+//
+
+Bool_t MPad::Merge2Distributions(TH1D *hista, TH1D *histb, TH1D *histap,
+                                 TH2D *fHga,  TH2D *fHgb, Int_t nbinssig,
+                                 TString canv )
+{
+  *fLog << all << "MPad::Merge2Distributions();  Entry" << endl;
+
+
+  // hista is the normalized 1D histogram of sigmabar for sample A
+  // histb is the normalized 1D histogram of sigmabar for sample B
+  // histc is the difference A-B
+
+  // at the beginning, histap is a copy of hista
+  // at the end, it will be the 1D histogram for sample A after padding
+
+  // at the beginning, histbp is a copy of histb
+  // at the end, it will be the 1D histogram for sample B after padding
+
+  // at the beginning, histcp is a copy of histc
+  // at the end, it should be the difference histap-histbp,
+  //             which should be zero
+
+  // fHga[k][j]  tells which fraction of events from sample A should be padded
+  //             from sigma_k to sigma_j
+
+
+  // fHgb[k][j]  tells which fraction of events from sample B should be padded
+  //             from sigma_k to sigma_j
+
+  //*fLog << all << "MPad::Merge2Distributions(); Entry" << endl;
+
+  Double_t eps = 1.e-10;
+
+    TH1D *histbp  = new TH1D( (const TH1D&)*histb );
+
+    TH1D *histc   = new TH1D( (const TH1D&)*hista );
+    histc->Add(histb, -1.0);
+
+    TH1D *histcp  = new TH1D( (const TH1D&)*histc );    
+
+
+  //--------   start j loop   ------------------------------------------------
+  // loop over bins in histc, 
+  // starting from the end (i.e. at the largest sigmabar)
+  Double_t v, s, w, t, x, u, a, b, arg;
+
+  //*fLog << "Content of histcp : " << endl;
+
+  for (Int_t j=nbinssig; j >= 1; j--)
+  {
+    //*fLog << "j, hista, histb , histap : " << j << ",  " 
+    //                              <<  hista->GetBinContent(j) << ",  "
+    //                              <<  histb->GetBinContent(j) << ",  "
+    //                              <<  histap->GetBinContent(j) << endl;
+
+    v = histcp->GetBinContent(j);
+    //*fLog << "cp : j, v = " << j << ",  " << v << endl;
+
+    if ( fabs(v) < eps ) continue;
+    if (v >= 0.0) 
+      s = 1.0;
+    else
+      s = -1.0;
+
+    //................   start k loop   ......................................
+    // look for a bin k which may compensate the content of bin j
+    for (Int_t k=j-1; k >= 1; k--)
+    {
+      w = histcp->GetBinContent(k);
+      if ( fabs(w) < eps ) continue;
+      if (w >= 0.0) 
+        t = 1.0;
+      else
+        t = -1.0;
+
+      // if s==t bin k cannot compensate, go to next k bin
+      if (s == t) continue;
+
+      x = v + w;
+      if (x >= 0.0) 
+        u = 1.0;
+      else
+        u = -1.0;
+
+      // if u==s bin k will partly compensate : pad the whole fraction
+      // w from bin k to bin j
+      if (u == s)
+        arg = -w;
+
+      // if u!=s bin k would overcompensate : pad only the fraction
+      // v from bin k to bin j
+      else
+        arg = v;
+
+      if (arg <=0.0)
+      {
+        fHga->SetBinContent(k, j, -arg);
+        fHgb->SetBinContent(k, j,  0.0);
+      }
+      else
+      {
+        fHga->SetBinContent(k, j,  0.0);
+        fHgb->SetBinContent(k, j,  arg);
+      }
+
+      //*fLog << all << "k, j, arg = " << k << ",  " << j 
+      //      << ",  " << arg << endl;
+
+      //......................................
+      // this is for checking the procedure
+      if (arg < 0.0)
+      {
+        a = histap->GetBinContent(k);
+        histap->SetBinContent(k, a+arg);
+        a = histap->GetBinContent(j);
+        histap->SetBinContent(j, a-arg);
+      }
+      else
+      {
+        b = histbp->GetBinContent(k);
+        histbp->SetBinContent(k, b-arg);
+        b = histbp->GetBinContent(j);
+        histbp->SetBinContent(j, b+arg);
+      }
+      //......................................
+
+      if (u == s)
+      {
+        histcp->SetBinContent(k, 0.0);
+        histcp->SetBinContent(j,   x);
+
+        v = histcp->GetBinContent(j);
+        if ( fabs(v) < eps ) break;
+
+        // bin j was only partly compensated : go to next k bin
+        continue;
+      }
+      else
+      {
+        histcp->SetBinContent(k,   x);
+        histcp->SetBinContent(j, 0.0);
+
+        // bin j was completely compensated : go to next j bin
+        break;
+      }
+
+    }
+    //................   end k loop   ......................................
+  } 
+  //--------   end j loop   ------------------------------------------------
+
+  // check results 
+
+  //*fLog << "Content of histap, histbp, histcp : " << endl;
+
+  for (Int_t j=1; j<=nbinssig; j++)
+  {
+    Double_t a = histap->GetBinContent(j);
+    Double_t b = histbp->GetBinContent(j);
+    Double_t c = histcp->GetBinContent(j);
+
+    //*fLog << "j, a, b, c = " << j << ":  " << a << ",  " << b << ",  "
+    //      << c << endl;
+
+    if( fabs(a-b)>3.0*eps  ||  fabs(c)>3.0*eps )
+      *fLog << err << "MPad::Merge2Distributions(); inconsistency in results; j, a, b, c = "
+            << j << ",  " << a << ",  " << b << ",  " << c << endl;
+  }
+
+  //---------------------------------------------------------------
+  TCanvas *pad = MH::MakeDefCanvas(canv, canv, 600, 600); 
+  gROOT->SetSelectedPad(NULL);
+
+  pad->Divide(2, 2);
+
+  pad->cd(1);
+  gPad->SetBorderMode(0);
+  hista->SetDirectory(NULL);
+  hista->UseCurrentStyle();
+  hista->DrawClone();
+  hista->SetBit(kCanDelete);    
+
+  pad->cd(2);
+  gPad->SetBorderMode(0);
+  histb->SetDirectory(NULL);
+  histb->UseCurrentStyle();
+  histb->DrawClone();
+  histb->SetBit(kCanDelete);    
+
+  pad->cd(3);
+  gPad->SetBorderMode(0);
+  histap->SetDirectory(NULL);
+  histap->UseCurrentStyle();
+  histap->DrawClone();
+  histap->SetBit(kCanDelete);    
+
+  pad->Draw();
+
+  //--------------------------------------------------------------------
+
+  delete histc;
+  delete histbp;
+  delete histcp;
+
+  *fLog << all << "MPad::Merge2Distributions();  Return" << endl;
+
+  return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Update the matrix fHgA
+// which contains the final padding prescriptions
+//
+
+Bool_t MPad::UpdateHg(TH2D *fHga, TH1D *histap, TH2D *fHge, TH3D *fHgA,
+                      Int_t nbinssig, Int_t l)
+{
+  // histap  target distribution after ON-OFF merging
+  // fHga    padding prescription for ON (or OFF) data to get to histap
+  // fHge    padding prescription to get from histap to the target
+  //         distribution after the ON-OFF-MC merging
+  // fHgA    updated padding prescription for ON (or OFF) data to get
+  //         from the original ON (or OFF) histogram to the target
+  //         distribution after the ON-OFF-MC merging
+  // l       Theta bin
+
+  Double_t eps = 1.e-10;
+
+  for (Int_t k=1; k<=nbinssig; k++)
+  {
+    Double_t na  = fHga->Integral(1, nbinssig, k, k, " ");
+    Double_t ne  = fHge->Integral(k, k, 1, nbinssig, " ");
+    Double_t nap = histap->GetBinContent(k);
+
+    if (ne <= eps) 
+    {
+      // go to next k
+      continue;
+    }
+
+    Double_t r = nap - na;
+
+    if (r >= ne-eps)
+    {
+      for (Int_t j=k+1; j<=nbinssig; j++)
+      {
+        Double_t e = fHge->GetBinContent(k,j);
+        Double_t A = fHgA->GetBinContent(l,k,j);
+        fHgA->SetBinContent(l, k, j, A + e);
+      }
+      // go to next k
+      continue;
+    }
+
+    for (Int_t j=k+1; j<=nbinssig; j++)
+    {
+      Double_t e = fHge->GetBinContent(k,j);
+      Double_t A = fHgA->GetBinContent(l,k,j);
+      fHgA->SetBinContent(l, k, j, A + r*e/ne);
+    }
+
+    if (na <= eps) 
+    {
+      // go to next k
+      continue;
+    }
+
+    for (Int_t i=1; i<k; i++)
+    {
+      Double_t a = fHga->GetBinContent(i,k);
+      Double_t A = fHgA->GetBinContent(l,i,k);
+      fHgA->SetBinContent(l, i, k, A - (ne-r)*a/na);
+    }
+
+    for (Int_t i=1; i<=nbinssig; i++)
+    {
+      if (i == k) continue;
+      for (Int_t j=i+1; j<=nbinssig; j++)
+      {
+        if (j == k) continue;
+        Double_t a = fHga->GetBinContent(i,k);
+        Double_t e = fHge->GetBinContent(k,j);
+        Double_t A = fHgA->GetBinContent(l,i,j);
+        fHgA->SetBinContent(l, i, j, A + (ne-r)*a*e/(na*ne)  );
+      }
+    }
+  }
+  
+  return kTRUE; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Write padding distributions onto a file
+//       these are the histograms produced in the member function
+//       MergeONOFFMC
+//       plus the distributions produced by MMakePadHistograms
+//
+Bool_t MPad::WritePaddingDist(TString namefileout)
+{
+  *fLog << all << "MPad::WritePaddingDist();  Padding distributions for  "; 
+
+  TFile outfile(namefileout, "RECREATE");
+
+  fHSigmaTheta->Write();
+  fHSigmaThetaOuter->Write();
+
+  if (fHSigmaThetaMC)
+  {
+    *fLog << all << " MC ";
+    fHSigmaThetaMC->Write();
+    fHSigmaThetaOuterMC->Write();
+    fHDiffPixThetaMC->Write();
+    fHDiffPixThetaTargetMC->Write();
+    fHgMC->Write();
+    fHgOuterMC->Write();
+  }
+
+  if (fHSigmaThetaON)
+  {
+    *fLog << all << " ON ";
+    fHSigmaThetaON->Write();
+    fHSigmaThetaOuterON->Write();
+    fHDiffPixThetaON->Write();
+    fHDiffPixThetaTargetON->Write();
+    fHgON->Write();
+    fHgOuterON->Write();
+  }
+
+  if (fHSigmaThetaOFF)
+  {
+    *fLog << all << " OFF ";
+    fHSigmaThetaOFF->Write();
+    fHSigmaThetaOuterOFF->Write();
+    fHDiffPixThetaOFF->Write();
+    fHDiffPixThetaTargetOFF->Write();
+    fHgOFF->Write();
+    fHgOuterOFF->Write();
+  }
+
+  *fLog << all << "  data were written onto file " 
+        << namefileout << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read padding distributions from a file
+//      thes are the distributions which were written out by
+//      the member function WritePaddingDist
+//
+Bool_t MPad::ReadPaddingDist(TString namefilein)
+{
+  *fLog << all << "MPad : Read padding histograms from file " 
+        << namefilein << endl;
+
+  Int_t OK = 0;
+
+  fInfile = new TFile(namefilein);
+  fInfile->ls();
+
+    //------------------------------------
+  
+      fHSigmaTheta = new TH2D; 
+      OK = fHSigmaTheta->Read("2D-ThetaSigmabar");
+      if (OK) 
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabar' was read in" << endl;
+      }
+
+      fHSigmaThetaOuter = new TH2D; 
+      OK =fHSigmaThetaOuter->Read("2D-ThetaSigmabarOuter");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOuter' was read in" << endl;
+      }
+
+
+    //------------------------------------
+
+      fHSigmaThetaMC = new TH2D; 
+      OK = fHSigmaThetaMC->Read("2D-ThetaSigmabarMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarMC' was read in" << endl;
+      }
+
+      fHSigmaThetaOuterMC = new TH2D; 
+      OK = fHSigmaThetaOuterMC->Read("2D-ThetaSigmabarOuterMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOuterMC' was read in" << endl;
+      }
+
+      fHDiffPixThetaMC = new TH3D;
+      OK = fHDiffPixThetaMC->Read("3D-ThetaPixDiffMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffMC' was read in" << endl;
+      }
+
+      fHDiffPixThetaTargetMC = new TH3D;
+      OK = fHDiffPixThetaTargetMC->Read("3D-ThetaPixDiffTargetMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffTargetMC' was read in" << endl;
+      }
+
+      fHgMC = new TH3D;
+      OK = fHgMC->Read("3D-PaddingMatrixMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixMC' was read in" << endl;
+      }
+
+      fHgOuterMC = new TH3D;
+      OK = fHgOuterMC->Read("3D-PaddingMatrixOuterMC");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixOuterMC' was read in" << endl;
+      }
+
+    //------------------------------------
+
+      fHSigmaThetaON = new TH2D;
+      OK =fHSigmaThetaON->Read("2D-ThetaSigmabarON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarON' was read in" << endl;
+      }
+
+      fHSigmaThetaOuterON = new TH2D;
+      OK = fHSigmaThetaOuterON->Read("2D-ThetaSigmabarOuterON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOuterON' was read in" << endl;
+      }
+
+      fHDiffPixThetaON = new TH3D;
+      OK = fHDiffPixThetaON->Read("3D-ThetaPixDiffON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffON' was read in" << endl;
+      }
+
+      fHDiffPixThetaTargetON = new TH3D;
+      OK = fHDiffPixThetaTargetON->Read("3D-ThetaPixDiffTargetON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffTargetON' was read in" << endl;
+      }
+
+      fHgON = new TH3D;
+      OK = fHgON->Read("3D-PaddingMatrixON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixON' was read in" << endl;
+      }
+
+      fHgOuterON = new TH3D;
+      OK = fHgOuterON->Read("3D-PaddingMatrixOuterON");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixOuterON' was read in" << endl;
+      }
+
+    //------------------------------------
+
+      fHSigmaThetaOFF = new TH2D;
+      OK = fHSigmaThetaOFF->Read("2D-ThetaSigmabarOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOFF' was read in" << endl;
+      }
+
+      fHSigmaThetaOuterOFF = new TH2D;
+      OK = fHSigmaThetaOuterOFF->Read("2D-ThetaSigmabarOuterOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '2D-ThetaSigmabarOuterOFF' was read in" << endl;
+      }
+
+      fHDiffPixThetaOFF = new TH3D;
+      OK = fHDiffPixThetaOFF->Read("3D-ThetaPixDiffOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffOFF' was read in" << endl;
+      }
+
+      fHDiffPixThetaTargetOFF = new TH3D;
+      OK = fHDiffPixThetaTargetOFF->Read("3D-ThetaPixDiffTargetOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-ThetaPixDiffTargetOFF' was read in" << endl;
+      }
+
+      fHgOFF = new TH3D;
+      OK = fHgOFF->Read("3D-PaddingMatrixOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixOFF' was read in" << endl;
+      }
+
+      fHgOuterOFF = new TH3D;
+      OK = fHgOuterOFF->Read("3D-PaddingMatrixOuterOFF");
+      if (OK)
+      {
+        *fLog << all 
+              << "MPad : Object '3D-PaddingMatrixOuterOFF' was read in" << endl;
+      }
+
+    //------------------------------------
+
+  return kTRUE;
+}
+
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Set the pointers and prepare the histograms
+//
+Int_t MPad::PreProcess(MParList *pList)
+{
+  if ( !fHSigmaThetaMC     && !fHSigmaThetaON     && !fHSigmaThetaOFF      ||  
+       !fHDiffPixThetaMC   && !fHDiffPixThetaON   && !fHDiffPixThetaOFF    ||
+       !fHgMC              && !fHgON              && !fHgOFF                 )
+  { 
+       *fLog << err 
+             << "MPad : There are no input histograms for the padding ... aborting." 
+             << endl;
+       return kFALSE;
+  }
+
+  fPointPos = (MPointingPos*)pList->FindObject("MPointingPos");
+  if (!fPointPos)
+    {
+       *fLog << err << dbginf << "MPad : MPointingPos not found... aborting." 
+             << endl;
+       return kFALSE;
+    }
+  
+    fPed = (MPedPhotCam*)pList->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+    if (!fPed)
+    {
+        *fLog << err << AddSerialNumber(fNamePedPhotCam) 
+              << "[MPedPhotCam] not found... aborting." << endl;
+        return kFALSE;
+    }    
+    *fLog << all << "MPad::PreProcess();  name of MPedPhotCam container = "
+	  << fNamePedPhotCam << endl;  
+   
+
+   fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+   if (!fCam)
+     {
+       *fLog << err 
+             << "MPad : MGeomCam not found (no geometry information available)... aborting." 
+             << endl;
+       return kFALSE;
+     }
+  
+   fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+   if (!fEvt)
+     {
+       *fLog << err << "MPad : MCerPhotEvt not found... aborting." 
+             << endl;
+       return kFALSE;
+     }
+
+
+   fBad = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+   if (!fBad)
+     {
+       *fLog << inf 
+             << "MPad : MBadPixelsCam container not present... continue." 
+             << endl;
+     }
+
+   
+   if (fType !="ON"  &&  fType !="OFF"  &&  fType !="MC")
+     {
+       *fLog << err 
+             << "MPad : Type of data to be padded not defined... aborting." 
+             << endl;
+       return kFALSE;
+     }
+
+
+   //--------------------------------------------------------------------
+   // histograms for checking the padding
+   //
+   // plot pedestal sigmas
+   fHSigmaPedestal = new TH2D("SigPed","Sigma: after vs. before padding", 
+                     100, 0.0, 75.0, 100, 0.0, 75.0);
+   fHSigmaPedestal->SetXTitle("Pedestal sigma before padding");
+   fHSigmaPedestal->SetYTitle("Pedestal sigma after padding");
+   fHSigmaPedestal->SetDirectory(NULL);
+   fHSigmaPedestal->UseCurrentStyle();
+   fHSigmaPedestal->GetYaxis()->SetTitleOffset(1.25);
+
+   // plot no.of photons (before vs. after padding) 
+   fHPhotons = new TH2D("Photons/area",
+                        "Photons/area: after vs.before padding", 
+                        100, -100.0, 300.0, 100, -100, 300);
+   fHPhotons->SetXTitle("no.of photons/area before padding");
+   fHPhotons->SetYTitle("no.of photons/area after padding");
+   fHPhotons->SetDirectory(NULL);
+   fHPhotons->UseCurrentStyle();
+   fHPhotons->GetYaxis()->SetTitleOffset(1.25);
+
+   // plot of added NSB
+   fHNSB = new TH1D("NSB/area","Distribution of added NSB/area", 
+                    100, -100.0, 200.0);
+   fHNSB->SetXTitle("no.of added NSB photons/area");
+   fHNSB->SetYTitle("no.of pixels");
+   fHNSB->SetDirectory(NULL);
+   fHNSB->UseCurrentStyle();
+   fHNSB->GetYaxis()->SetTitleOffset(1.25);
+
+   //--------------------------------------------------------------------
+
+  *fLog << inf << "Type of data to be padded : " << fType << endl; 
+  *fLog << inf << "Name of MPedPhotCam container : " << fNamePedPhotCam 
+        << endl; 
+
+   fIter = 10;
+
+   memset(fInf,      0, sizeof(fInf));
+   memset(fErrors,   0, sizeof(fErrors));
+   memset(fWarnings, 0, sizeof(fWarnings));
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the Padding (noise adjustment)
+//
+// input for the padding : 
+//  - the matrices fHgON, fHgOFF, fHgMC
+//  - the original distributions fHSigmaTheta, fHDiffPixTheta
+//
+
+Int_t MPad::Process()
+{
+  //*fLog << all << "Entry MPad::Process();" << endl;
+
+  // this is the conversion factor from the number of photons
+  //                                 to the number of photo electrons
+  // later to be taken from MCalibration
+  // fPEperPhoton = PW * LG * QE * 1D
+  Double_t fPEperPhoton = 0.92 * 0.94 * 0.23 * 0.9;   //  (= 0.179)
+
+  //------------------------------------------------
+  // Add pixels to MCerPhotEvt which are not yet in;
+  // set their number of photons equal to zero. 
+  // Purpose : by the padding the number of photons is changed
+  // so that cleaning and cuts may be affected.
+  // However, no big effect is expectec unless the padding is strong
+  // (strong increase of the noise level)
+  // At present comment out this code
+
+  /*
+  UInt_t imaxnumpix = fCam->GetNumPixels();
+
+  for (UInt_t i=0; i<imaxnumpix; i++)
+  {
+    Bool_t alreadythere = kFALSE;
+    UInt_t npix = fEvt->GetNumPixels();
+    for (UInt_t j=0; j<npix; j++)
+    {
+      MCerPhotPix &pix = (*fEvt)[j];
+      UInt_t id = pix.GetPixId();
+      if (i==id)
+      {
+        alreadythere = kTRUE;
+        break;
+      }
+    }
+    if (alreadythere)
+      continue;
+
+    fEvt->AddPixel(i, 0.0, (*fPed)[i].GetRms());
+  }
+  */
+
+
+  //-----------------------------------------
+  Int_t rc=0;
+  Int_t rw=0;
+
+  const UInt_t npix = fEvt->GetNumPixels();
+
+  //*fLog << all << "MPad::Process(); before padding : " << endl;
+
+  //-------------------------------------------
+  // Calculate average sigma of the event
+  //
+  fPed->ReCalc(*fCam, fBad);
+  //*fLog << "pedestalRMS, inner and outer = " << (fPed->GetArea(0)).GetRms()
+  //      << ",  " << (fPed->GetArea(1)).GetRms() << endl;
+
+
+  // inner sigmabar/sqrt(area)
+  Double_t ratioinn = fCam->GetPixRatio(0);
+  Double_t sigbarInnerold_phot = (fPed->GetArea(0)).GetRms();
+  Double_t sigbarInnerold  = sigbarInnerold_phot * fPEperPhoton * sqrt(ratioinn);
+  Double_t sigbarInnerold2 = sigbarInnerold*sigbarInnerold;
+
+  // outer sigmabar/sqrt(area)
+  Double_t ratioout = fCam->GetPixRatio(500);
+  Double_t sigbarOuterold_phot = (fPed->GetArea(1)).GetRms();
+  Double_t sigbarOuterold  = sigbarOuterold_phot * fPEperPhoton * sqrt(ratioout);
+  Double_t sigbarOuterold2 = sigbarOuterold*sigbarOuterold;
+
+  const Double_t theta = fPointPos->GetZd();
+
+  //*fLog << all << "theta = " << theta << endl;
+
+  Int_t binTheta = fHSigmaTheta->GetXaxis()->FindBin(theta);
+  if ( binTheta < 1  ||  binTheta > fHSigmaTheta->GetNbinsX() )
+  {
+    *fLog << warn 
+          << "MPad::Process(); binNumber out of range : theta, binTheta = "
+          << theta << ",  " << binTheta << endl;
+
+    rc = 2;
+    fErrors[rc]++;
+    return kCONTINUE;
+  }
+
+  //*fLog << all << "binTheta = " << binTheta << endl;
+  
+
+  //-------------------------------------------
+  // get number of events in this theta bin               (nTheta)
+  // and number of events in this sigbarInnerold_phot bin (nSigma)
+
+  Double_t nTheta;
+  Double_t nSigma;
+
+  TH2D *st = NULL;
+  if      (fType == "MC")  st = fHSigmaThetaMC;
+  else if (fType == "ON")  st = fHSigmaThetaON;
+  else if (fType == "OFF") st = fHSigmaThetaOFF;
+  else
+  {
+    *fLog << err << "MPad : illegal data type '" << fType 
+          <<  "'" << endl;
+    return kERROR;  
+  }
+
+  TH1D *hn;
+  hn = st->ProjectionY("", binTheta, binTheta, "");
+
+  //*fLog << "Title of histogram : " << st->GetTitle() << endl;
+  //for (Int_t i=1; i<=hn->GetNbinsX(); i++)
+  //{
+  //  *fLog << "bin " << i << " : no.of entries = " << hn->GetBinContent(i)
+  //        << endl;
+  //}
+
+  nTheta = hn->Integral();
+  Int_t binSigma = hn->FindBin(sigbarInnerold_phot);
+  nSigma = hn->GetBinContent(binSigma);
+
+  //*fLog << all           
+  //       << "Theta, sigbarold_phot, binTheta, binSigma, nTheta, nSigma = "
+  //       << theta << ",  " << sigbarInnerold_phot << ",  " << binTheta 
+  //       << ",  "
+  //       << binSigma << ",  " << nTheta << ",  " << nSigma   << endl;      
+
+  delete hn;
+ 
+  //-------------------------------------------
+
+  //******************************************************************
+  // has the event to be padded ?
+  // if yes : to which sigmabar should it be padded ?
+  //
+
+  TH3D *Hg = NULL;
+  if      (fType == "MC")  Hg = fHgMC;
+  else if (fType == "ON")  Hg = fHgON;
+  else if (fType == "OFF") Hg = fHgOFF;
+  else
+  {
+    *fLog << err << "MPad : illegal type of data '" << fType << "'"
+          << endl;
+    return kERROR;
+  }
+
+  Int_t binSig = Hg->GetYaxis()->FindBin(sigbarInnerold_phot);
+  //*fLog << all << "binSig, sigbarInnerold_phot = " << binSig << ",  " 
+  //        << sigbarInnerold_phot << endl;
+
+  Double_t prob;
+  TH1D *hpad = NULL;
+
+
+  hpad = Hg->ProjectionZ("zON", binTheta, binTheta, binSig, binSig, "");
+
+  //Int_t nb = hpad->GetNbinsX();
+  //for (Int_t i=1; i<=nb; i++)
+  //{
+  //  if (hpad->GetBinContent(i) != 0.0)
+  //    *fLog << all << "i, Hg = " << i << ",  " 
+  //          << hpad->GetBinContent(i) << endl;
+  //}
+
+  if (nSigma != 0.0)
+    prob = hpad->Integral() * nTheta/nSigma;
+  else
+    prob = 0.0;
+
+  //*fLog << all << "nTheta, nSigma, prob = " << nTheta << ",  " << nSigma 
+  //       << ",  " << prob << endl;
+
+  if ( prob <= 0.0  ||  gRandom->Uniform() > prob )
+  {
+    delete hpad;
+    // event should not be padded
+    //*fLog << all << "event is not padded" << endl;
+
+    rc = 0;
+    fInf[rc]++;
+    return kTRUE;
+  }
+  // event should be padded
+  //*fLog << all << "event will be padded" << endl;  
+
+
+  //-------------------------------------------
+  // for the current theta, generate a sigmabar_inner :
+  //     for MC/ON/OFF data according to the matrix fHgMC/ON/OFF
+  //
+  Double_t sigmabarInner_phot = 0;
+  Double_t sigmabarInner      = 0;
+
+  
+  //Int_t nbinsx = hpad->GetNbinsX();
+  //for (Int_t i=1; i<=nbinsx; i++)
+  //{
+  //  if (hpad->GetBinContent(i) != 0.0)
+  //    *fLog << all << "i, fHg = " << i << ",  " << hpad->GetBinContent(i) 
+  //          << endl;
+  //}
+
+  sigmabarInner_phot = hpad->GetRandom();
+  sigmabarInner = sigmabarInner_phot * fPEperPhoton * sqrt(ratioinn); 
+
+  //*fLog << all << "sigmabarInner_phot = " << sigmabarInner_phot << endl;
+
+  delete hpad;
+  
+  // new inner sigmabar2/area
+  const Double_t sigmabarInner2 = sigmabarInner*sigmabarInner;
+
+  //*fLog << all << "MPad::Process(); sigbarInnerold, sigmabarInner = " 
+  //      << sigbarInnerold << ",  "<< sigmabarInner << endl;
+
+  // Stop if target sigmabar is <= sigbarold
+  if (sigmabarInner <= sigbarInnerold)
+  {
+    *fLog << all << "MPad::Process(); target sigmabarInner is less than sigbarInnerold : "
+          << sigmabarInner << ",  " << sigbarInnerold << ",   aborting" 
+          << endl;
+
+    rc = 4;
+    fErrors[rc]++;
+    return kCONTINUE;     
+  }
+
+  //-------------------------------------------
+  // estimate a sigmabar_outer from sigmabar_inner :
+  // using the target distributions fHSigmaTheta and fHSigmaThetaOuter
+  // for sigmabar(inner) and sigmabar(outer)
+
+  Double_t innerMeantarget = 0.0;
+  Double_t outerMeantarget = 0.0;
+  Double_t innerRMStarget  = 0.0;
+  Double_t outerRMStarget  = 0.0;
+
+  // projection doesn't work
+  //TH1D *hi = fHSigmaTheta->ProjectionY("proinner", binTheta, binTheta, "e");
+  //TH1D *ho = fHSigmaThetaOuter->ProjectionY("proouter", binTheta, binTheta, "e");
+  //sigmabarOuter2 =   sigmabarInner2   + fPEperPhoton*fPEperPhoton * 
+  //                 (   ho->GetMean()*ho->GetMean()*ratioout 
+  //                   - hi->GetMean()*hi->GetMean()*ratioinn);
+
+  //innerMeantarget = hi->GetMean()*sqrt(ratioinn)*fPEperPhoton;
+  //outerMeantarget = ho->GetMean()*sqrt(ratioout)*fPEperPhoton;
+  //innerRMStarget  = hi->GetRMS(1)*sqrt(ratioinn)*fPEperPhoton;
+  //outerRMStarget  = ho->GetRMS(1)*sqrt(ratioout)*fPEperPhoton;
+
+  Double_t y      = 0.0;
+  Double_t ybar   = 0.0;
+  Double_t y2bar  = 0.0;
+  Double_t w      = 0.0;
+
+  Double_t isum   = 0.0;
+  Double_t isumy  = 0.0;
+  Double_t isumy2 = 0.0;
+  for (Int_t i=1; i<=fHSigmaTheta->GetNbinsY(); i++)
+  {
+    w = fHSigmaTheta->GetBinContent(binTheta, i);
+    y = fHSigmaTheta->GetYaxis()->GetBinCenter(i);
+    isum   += w;
+    isumy  += w * y;
+    isumy2 += w * y*y;
+  }
+  if (isum == 0.0)
+  {
+    innerMeantarget = 0.0;
+    innerRMStarget  = 0.0;
+  }    
+  else
+  {
+    ybar  = isumy /isum;
+    y2bar = isumy2/isum;
+    innerMeantarget = ybar                      * sqrt(ratioinn)*fPEperPhoton;
+    innerRMStarget  = sqrt( y2bar - ybar*ybar ) * sqrt(ratioinn)*fPEperPhoton;
+  }
+
+  Double_t osum   = 0.0;
+  Double_t osumy  = 0.0;
+  Double_t osumy2 = 0.0;
+  for (Int_t i=1; i<=fHSigmaThetaOuter->GetNbinsY(); i++)
+  {
+    w = fHSigmaThetaOuter->GetBinContent(binTheta, i);
+    y = fHSigmaThetaOuter->GetYaxis()->GetBinCenter(i);
+    osum   += w;
+    osumy  += w * y;
+    osumy2 += w * y*y;
+  }
+  if (osum == 0.0)
+  {
+    outerMeantarget = 0.0;
+    outerRMStarget  = 0.0;
+  }    
+  else
+  {
+    ybar  = osumy /osum;
+    y2bar = osumy2/osum;
+    outerMeantarget = ybar                      * sqrt(ratioout)*fPEperPhoton;
+    outerRMStarget  = sqrt( y2bar - ybar*ybar ) * sqrt(ratioout)*fPEperPhoton;
+  }
+
+
+  // new outer sigmabar2/area
+  Double_t sigmabarOuter2;
+
+  Double_t scal = ( innerMeantarget*innerRMStarget == 0.0   ||
+                    outerMeantarget*outerRMStarget == 0.0 )    ?  1.0 :
+          (outerMeantarget*outerRMStarget)/(innerMeantarget*innerRMStarget);
+  sigmabarOuter2 = outerMeantarget*outerMeantarget +
+                   scal * (sigmabarInner2 - innerMeantarget*innerMeantarget);
+
+  //*fLog << "innerMeantarget, innerRMStarget = " << innerMeantarget 
+  //      << ",  " << innerRMStarget << endl;
+
+  //*fLog << "outerMeantarget, outerRMStarget = " << outerMeantarget 
+  //      << ",  " << outerRMStarget << endl;
+
+  //*fLog << "sigmabarInner2, sigmabarOuter2, scal = " << sigmabarInner2 
+  //      << ",  " << sigmabarOuter2 << ",  " << scal << endl;
+
+  //delete hi;
+  //delete ho;
+
+  //-------------------------------------------
+  //
+  // Calculate average number of NSB photo electrons to be added (lambdabar)
+  // from the value of sigmabar, 
+  //  - using a fixed value (F2excess)  for the excess noise factor
+  
+  Double_t elNoise2;         // [photo electrons]  
+  Double_t F2excess  = 1.3;
+  Double_t lambdabar;        // [photo electrons]
+
+  //----------------
+  TH3D *sp = NULL;
+  if      (fType == "MC")  sp = fHDiffPixThetaTargetMC;
+  else if (fType == "ON")  sp = fHDiffPixThetaTargetON;
+  else if (fType == "OFF") sp = fHDiffPixThetaTargetOFF;
+
+  //----------------
+
+  Int_t bincheck = sp->GetXaxis()->FindBin(theta);
+  if (binTheta != bincheck)
+  {
+    *fLog << err 
+          << "MPad::Process(); The binnings of the 2 histograms are not identical; aborting"
+          << endl;
+    return kERROR;
+  }
+
+  // In this Theta bin, get RMS of (Sigma^2-sigmabar^2)/area for inner pixels.
+  // The average electronic noise (to be added) has to be in the order of
+  // this RMS, otherwise the electronic noise of an individual pixel 
+  // (elNoise2Pix) may become negative
+
+  //----------------
+
+
+  // Attention : maximum ID of inner pixels hard coded !!!
+  Int_t idmaxpixinner = 396;
+  Int_t binmaxpixinner = 
+        sp->GetYaxis()->FindBin( (Double_t)idmaxpixinner );
+
+  TH1D *hnoise = NULL;
+    hnoise = sp->ProjectionZ("", binTheta, binTheta, 0, binmaxpixinner, "");
+
+  Double_t RMS_phot = hnoise->GetRMS(1);  
+  Double_t RMS = RMS_phot * fPEperPhoton * fPEperPhoton;
+  delete hnoise;
+
+  elNoise2 = TMath::Min(2.0*RMS,  sigmabarInner2 - sigbarInnerold2);
+  //*fLog << all << "RMS_phot, elNoise2 = " << RMS_phot << ",  "
+  //      << elNoise2 << endl; 
+
+  lambdabar = (sigmabarInner2 - sigbarInnerold2 - elNoise2) / F2excess;  
+
+  if (lambdabar <= 0.0)
+  {
+    rc = 3;
+    fErrors[rc]++;
+  }
+
+  //*fLog << "lambdabar = " << lambdabar << endl;
+
+  // This value of lambdabar is the same for all pixels;
+  // note that lambdabar is the NSB p.e. density
+
+  //----------   start loop over pixels   ---------------------------------
+  // do the padding for each pixel
+  //
+  // pad only pixels   - which are used 
+  //
+
+  Double_t sigma2      = 0;
+
+  Double_t diff_phot   = 0;
+  Double_t diff        = 0;
+
+  Double_t addSig2_phot= 0;
+  Double_t addSig2     = 0;
+
+  Double_t elNoise2Pix = 0;
+
+
+  // throw the Sigma for the pixels from the distribution fHDiffPixTheta
+  // MC  : from fHDiffPixThetaTargetMC
+  // ON  : from fHDiffPixThetaTaregtON
+  // OFF : from fHDiffPixThetaTargetOFF
+
+
+  Double_t sigbarold2;
+  Double_t sigmabar2;
+
+  for (UInt_t i=0; i<npix; i++) 
+  {   
+
+    MCerPhotPix &pix = (*fEvt)[i];
+    if ( !pix.IsPixelUsed() )
+      continue;
+
+    //if ( pix.GetNumPhotons() == 0.0)
+    //{
+    //  *fLog << warn 
+    //        << "MPad::Process(); no.of photons is 0 for used pixel" 
+    //        << endl;
+    //  continue;
+    //}
+
+    Int_t j = pix.GetPixId();
+
+    // GetPixRatio returns (area of pixel 0 / area of current pixel)
+    Double_t ratio = fCam->GetPixRatio(j);
+
+    if (ratio > 0.5)
+    {
+      sigbarold2 = sigbarInnerold2;
+      sigmabar2  = sigmabarInner2;
+    }
+    else
+    {
+      sigbarold2 = sigbarOuterold2;
+      sigmabar2  = sigmabarOuter2;
+    }
+
+    MPedPhotPix &ppix = (*fPed)[j];
+
+    // count number of pixels treated
+    fWarnings[0]++;
+
+
+    Double_t oldsigma_phot = ppix.GetRms();
+    Double_t oldsigma = oldsigma_phot * fPEperPhoton * sqrt(ratio);
+    Double_t oldsigma2 = oldsigma*oldsigma;
+
+    //---------------------------------
+    // throw the Sigma for this pixel 
+    //
+    Int_t binPixel = sp->GetYaxis()->FindBin( (Double_t)j );
+
+    Int_t count;
+    Bool_t ok;
+
+    TH1D *hdiff = NULL;
+
+     hdiff = sp->ProjectionZ("", binTheta, binTheta,
+                                 binPixel, binPixel, "");
+     Double_t integral =  hdiff->Integral();
+     // if there are no entries in hdiff, diff cannot be thrown
+     // in this case diff will be set to the old difference
+     if ( integral == 0 )
+     {
+       //*fLog << warn << "MPad::Process(); fType = " << fType 
+       //      << ", projection of '"
+       //      << sp->GetName() << "' for Theta bin " 
+       //      << binTheta << "  and pixel " << j  
+       //      << " has no entries; set diff equal to the old difference  " 
+       //      << endl;
+
+       diff = TMath::Max(oldsigma2 - sigbarold2,
+                         lambdabar*F2excess + oldsigma2 - sigmabar2);
+
+       rc = 2;
+       fWarnings[rc]++;
+     }
+
+     // start of else -------------------
+     else
+     {
+       count = 0;
+       ok = kFALSE;
+       for (Int_t m=0; m<fIter; m++)
+       {
+         count += 1;
+         diff_phot = hdiff->GetRandom();
+
+         //*fLog << "after GetRandom : j, m, diff_phot = " << j << " : "
+         //      << m << ",  " << diff_phot << endl;
+
+         diff = diff_phot * fPEperPhoton * fPEperPhoton;
+ 
+         // the following condition ensures that elNoise2Pix > 0.0 
+         if ( (diff + sigmabar2 - oldsigma2
+                                - lambdabar*F2excess) > 0.0 )
+         {
+           ok = kTRUE;
+           break;
+         }
+       }
+
+       if (!ok)
+       {
+         //*fLog << all << "theta, j, count, sigmabar2, diff, oldsigma2, ratio, lambdabar = " 
+         //      << theta << ",  " 
+         //      << j << ",  " << count << ",  " << sigmabar2 << ",  " 
+         //      << diff << ",  " << oldsigma2 << ",  " << ratio << ",  "
+         //      << lambdabar << endl;
+         diff = lambdabar*F2excess + oldsigma2 - sigmabar2; 
+
+         rw = 1;
+         fWarnings[rw]++;
+       }
+     }
+     // end of else --------------------
+
+    delete hdiff;
+    sigma2 = diff + sigmabar2;
+
+
+    //---------------------------------
+    // get the additional sigma^2 for this pixel (due to the padding)
+
+    addSig2 = (sigma2 - oldsigma2) / ratio;
+    addSig2_phot = addSig2 / (fPEperPhoton * fPEperPhoton);
+
+    //---------------------------------
+    // get the additional electronic noise for this pixel
+
+    elNoise2Pix = addSig2 - lambdabar*F2excess/ratio;
+
+
+    //---------------------------------
+    // throw actual number of additional NSB photo electrons (NSB)
+    //       and its RMS (sigmaNSB) 
+
+    Double_t NSB0 = gRandom->Poisson(lambdabar/ratio);
+    Double_t arg  = NSB0*(F2excess-1.0) + elNoise2Pix;
+    Double_t sigmaNSB0;
+
+    if (arg >= 0.0)
+    {
+      sigmaNSB0 = sqrt( arg );
+    }
+    else
+    {
+      sigmaNSB0 = 0.0000001;      
+      if (arg < -1.e-10)
+      {
+        *fLog << warn << "MPad::Process(); argument of sqrt < 0 : "
+              << arg << endl;
+      }
+    }
+
+
+    //---------------------------------
+    // smear NSB0 according to sigmaNSB0
+    // and subtract lambdabar because of AC coupling
+
+    Double_t NSB = gRandom->Gaus(NSB0, sigmaNSB0) - lambdabar/ratio;
+    Double_t NSB_phot = NSB / fPEperPhoton;
+
+    //---------------------------------
+ 
+    // add additional NSB to the number of photons
+    Double_t oldphotons_phot = pix.GetNumPhotons();
+    Double_t oldphotons = oldphotons_phot * fPEperPhoton;
+    Double_t newphotons = oldphotons + NSB;
+    Double_t newphotons_phot = newphotons / fPEperPhoton;    
+    pix.SetNumPhotons(	newphotons_phot );
+
+
+    fHNSB->Fill( NSB_phot*ratio );
+    fHPhotons->Fill( oldphotons_phot*ratio, 
+                     newphotons_phot*ratio );
+
+
+    // error: add sigma of padded noise quadratically
+    Double_t olderror_phot = pix.GetErrorPhot();
+    Double_t newerror_phot = 
+                           sqrt( olderror_phot*olderror_phot + addSig2_phot );
+    pix.SetErrorPhot( newerror_phot );
+
+
+    Double_t newsigma = sqrt( sigma2 / ratio ); 
+    Double_t newsigma_phot = newsigma / fPEperPhoton; 
+    ppix.SetRms( newsigma_phot );
+
+    fHSigmaPedestal->Fill( oldsigma_phot, newsigma_phot );
+  } 
+  //----------   end of loop over pixels   ---------------------------------
+
+
+  //*fLog << all << "MPad::Process(); after padding : " << endl;
+
+  // Calculate sigmabar again and crosscheck
+  fPed->ReCalc(*fCam, fBad);
+  //*fLog << "pedestalRMS, inner and outer = " << (fPed->GetArea(0)).GetRms()
+  //      << ",  " << (fPed->GetArea(1)).GetRms() << endl;
+
+  //*fLog << all << "Exit MPad::Process();" << endl;
+
+  rc = 0;
+  fErrors[rc]++;
+
+  return kTRUE;
+  //******************************************************************
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MPad::PostProcess()
+{
+    if (GetNumExecutions() != 0)
+    {
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    if (fWarnings[0] == 0 ) fWarnings[0] = 1;
+
+    *fLog << " " << setw(7) << fWarnings[1] << " (" << setw(3) 
+          << (int)(fWarnings[1]*100/fWarnings[0])
+          << "%) Pixel: iteration to find acceptable sigma failed" 
+          << ", fIter = " << fIter << endl;
+
+    *fLog << " " << setw(7) << fWarnings[2] << " (" << setw(3) 
+          << (int)(fWarnings[2]*100/fWarnings[0]) 
+          << "%) Pixel: No data for generating Sigma^2-Sigmabar^2" << endl;
+
+
+    *fLog << " " << setw(7) << fErrors[2] << " (" << setw(3) 
+          << (int)(fErrors[2]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: Zenith angle out of range" << endl;
+
+    *fLog << " " << setw(7) << fErrors[4] << " (" << setw(3) 
+          << (int)(fErrors[4]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: new sigma <= old sigma" << endl;
+
+    *fLog << " " << setw(7) << fErrors[3] << " (" << setw(3) 
+          << (int)(fErrors[3]*100/GetNumExecutions()) 
+          << "%) lambdabar = 0" << endl;
+
+    *fLog << " " << setw(7) << fInf[0] << " (" << setw(3) 
+          << (int)(fInf[0]*100/GetNumExecutions()) 
+          << "%) Evts didn't have to be padded" << endl;
+
+    *fLog << " " << fErrors[0] << " (" 
+          << (int)(fErrors[0]*100/GetNumExecutions()) 
+          << "%) Evts were successfully padded!" << endl;
+    *fLog << endl;
+
+    }
+
+    //---------------------------------------------------------------
+    TCanvas &c = *(MH::MakeDefCanvas("Pad", "", 900, 1200)); 
+    c.Divide(3, 4);
+    gROOT->SetSelectedPad(NULL);
+
+    c.cd(1);
+    fHNSB->DrawCopy();
+    fHNSB->SetBit(kCanDelete);    
+
+    c.cd(2);
+    fHSigmaPedestal->DrawCopy();
+    fHSigmaPedestal->SetBit(kCanDelete);    
+
+    c.cd(3);
+    fHPhotons->DrawCopy();
+    fHPhotons->SetBit(kCanDelete);    
+
+    //--------------------------------------------------------------------
+
+    if (fHgON)
+    {
+      c.cd(4);
+      TH2D *m1;
+      m1 = (TH2D*) ((TH3*)fHgON)->Project3D("zy");
+      m1->SetDirectory(NULL);
+      m1->UseCurrentStyle();
+      m1->SetTitle("(fHgON) Sigmabar-new vs. Sigmabar-old (ON, all  \\Theta)");
+      m1->SetXTitle("Sigmabar-old");
+      m1->SetYTitle("Sigmabar-new");
+
+      m1->DrawCopy("box");
+      m1->SetBit(kCanDelete);;
+    }
+
+    if (fHgOFF)
+    {
+      c.cd(5);
+      TH2D *m2;
+      m2 = (TH2D*) ((TH3*)fHgOFF)->Project3D("zy");
+      m2->SetDirectory(NULL);
+      m2->UseCurrentStyle();
+      m2->SetTitle("(fHgOFF) Sigmabar-new vs. Sigmabar-old (OFF, all  \\Theta)");
+      m2->SetXTitle("Sigmabar-old");
+      m2->SetYTitle("Sigmabar-new");
+
+      m2->DrawCopy("box");
+      m2->SetBit(kCanDelete);;
+    }
+
+    if (fHgMC)
+    {
+      c.cd(6);
+      TH2D *m3;
+      m3 = (TH2D*) ((TH3*)fHgMC)->Project3D("zy");
+      m3->SetDirectory(NULL);
+      m3->UseCurrentStyle();
+      m3->SetTitle("(fHgMC) Sigmabar-new vs. Sigmabar-old (MC, all  \\Theta)");
+      m3->SetXTitle("Sigmabar-old");
+      m3->SetYTitle("Sigmabar-new");
+
+      m3->DrawCopy("box");
+      m3->SetBit(kCanDelete);;
+    }
+
+    //--------------------------------------------------------------------
+
+    if (fHgOuterON)
+    {
+      c.cd(7);
+      TH2D *m1;
+      m1 = (TH2D*) ((TH3*)fHgOuterON)->Project3D("zy");
+      m1->SetDirectory(NULL);
+      m1->UseCurrentStyle();
+      m1->SetTitle("(fHgOuterON) Sigmabar-new vs. Sigmabar-old (ON, all  \\Theta)");
+      m1->SetXTitle("Sigmabar-old");
+      m1->SetYTitle("Sigmabar-new");
+
+      m1->DrawCopy("box");
+      m1->SetBit(kCanDelete);;
+    }
+
+    if (fHgOuterOFF)
+    {
+      c.cd(8);
+      TH2D *m2;
+      m2 = (TH2D*) ((TH3*)fHgOuterOFF)->Project3D("zy");
+      m2->SetDirectory(NULL);
+      m2->UseCurrentStyle();
+      m2->SetTitle("(fHgOuterOFF) Sigmabar-new vs. Sigmabar-old (OFF, all  \\Theta)");
+      m2->SetXTitle("Sigmabar-old");
+      m2->SetYTitle("Sigmabar-new");
+
+      m2->DrawCopy("box");
+      m2->SetBit(kCanDelete);;
+    }
+
+    if (fHgOuterMC)
+    {
+      c.cd(9);
+      TH2D *m3;
+      m3 = (TH2D*) ((TH3*)fHgOuterMC)->Project3D("zy");
+      m3->SetDirectory(NULL);
+      m3->UseCurrentStyle();
+      m3->SetTitle("(fHgOuterMC) Sigmabar-new vs. Sigmabar-old (MC, all  \\Theta)");
+      m3->SetXTitle("Sigmabar-old");
+      m3->SetYTitle("Sigmabar-new");
+
+      m3->DrawCopy("box");
+      m3->SetBit(kCanDelete);;
+    }
+
+    //--------------------------------------------------------------------
+
+    c.cd(10);
+    fHSigmaTheta->SetDirectory(NULL);
+    fHSigmaTheta->UseCurrentStyle();
+    fHSigmaTheta->DrawCopy();
+    fHSigmaTheta->SetBit(kCanDelete);    
+
+    c.cd(11);
+    fHSigmaThetaOuter->SetDirectory(NULL);
+    fHSigmaThetaOuter->UseCurrentStyle();
+    fHSigmaThetaOuter->DrawCopy();
+    fHSigmaThetaOuter->SetBit(kCanDelete);    
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MPad.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MPad.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPad.h	(revision 9772)
@@ -0,0 +1,131 @@
+#ifndef MARS_MPad
+#define MARS_MPad
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TH2D;
+class TH3D;
+
+class MGeomCam;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MPointingPos;
+class MParList;
+class MBadPixelsCam;
+class MRead;
+class MFilterList;
+
+
+class MPad : public MTask
+{
+private:
+    MGeomCam       *fCam;
+    MCerPhotEvt    *fEvt; 
+    MPointingPos   *fPointPos;
+    MPedPhotCam    *fPed;
+    MBadPixelsCam  *fBad;
+
+    TString  fNamePedPhotCam; // name of the 'MPedPhotCam' container
+    TString  fType;           // type of data to be padded
+    TFile    *fInfile;        // input file containing padding histograms
+
+    Int_t          fIter;
+
+    Int_t          fInf[9];
+    Int_t          fErrors[9];
+    Int_t          fWarnings[3];
+
+    //----------------------------------
+    // plots used for the padding
+    // for all plots it is assumed that the pedestal RMS is given in units of "number of photons"
+
+    // original distributions
+    TH2D  *fHSigmaThetaMC;     // 2D-histogram (sigmabar_inner vs. Theta)
+    TH2D  *fHSigmaThetaON;     // 2D-histogram (sigmabar_inner vs. Theta)
+    TH2D  *fHSigmaThetaOFF;    // 2D-histogram (sigmabar_inner vs. Theta)
+
+    TH2D  *fHSigmaThetaOuterMC;   // 2D-histogram (sigmabar_outer vs. Theta)
+    TH2D  *fHSigmaThetaOuterON;   // 2D-histogram (sigmabar_outer vs. Theta)
+    TH2D  *fHSigmaThetaOuterOFF;  // 2D-histogram (sigmabar_outer vs. Theta)
+
+    TH3D  *fHDiffPixThetaMC;   // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+    TH3D  *fHDiffPixThetaON;   // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+    TH3D  *fHDiffPixThetaOFF;  // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+
+    //---------------------
+    // target distributions
+    TH2D  *fHSigmaTheta;       // 2D-histogram (sigmabar_inner vs. Theta)
+    TH2D  *fHSigmaThetaOuter;  // 2D-histogram (sigmabar_outer vs. Theta)
+
+    TH3D  *fHDiffPixThetaTargetMC;   // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+    TH3D  *fHDiffPixThetaTargetON;   // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+    TH3D  *fHDiffPixThetaTargetOFF;  // 3D-histogram (Theta, pixel, (sigma^2-sigmabar^2)/area )
+
+    //---------------------
+    // matrices according to which the padding is performed
+    TH3D  *fHgMC;        // matrix (Theta, sigbarold, sigbarnew) for MC data
+    TH3D  *fHgON;        // matrix (Theta, sigbarold, sigbarnew) for ON data
+    TH3D  *fHgOFF;       // matrix (Theta, sigbarold, sigbarnew) for OFF data
+
+    TH3D  *fHgOuterMC;   // matrix (Theta, sigbarold, sigbarnew) for MC data
+    TH3D  *fHgOuterON;   // matrix (Theta, sigbarold, sigbarnew) for ON data
+    TH3D  *fHgOuterOFF;  // matrix (Theta, sigbarold, sigbarnew) for OFF data
+
+    //-------------------------------
+    // plots for checking the padding
+    TH2D  *fHSigmaPedestal; // 2D-histogram : pedestal sigma after
+                            //                versus before padding
+    TH2D  *fHPhotons;       // 2D-histogram : no.of photons/area after
+                            //                versus before padding
+    TH1D  *fHNSB;           // 1D-histogram : additional NSB/area
+
+    //-------------------------------
+    Bool_t MergeABC(TString tA, TString tB, TString tC,
+                    TH2D *hA,   TH2D *hB,   TH2D *hC,   TH2D *hM,
+                    TH3D *hgA,  TH3D *hgB,  TH3D *hgC,  TString canv);
+
+    Bool_t Merge2Distributions(TH1D *hista, TH1D *histb, TH1D *histap,
+                               TH2D *fHga,  TH2D *fHgb,  Int_t nbinssig,
+                               TString canv);
+
+    Bool_t UpdateHg(TH2D *fHga, TH1D *histap, TH2D *fHge, TH3D *fHgA,
+                    Int_t nbinssig, Int_t l); 
+
+public:
+    MPad(const char *name=NULL, const char *title=NULL);
+    ~MPad();
+
+    void SetDataType(const char *type);       // type of data to be padded
+    void SetNamePedPhotCam(const char *name); // name of MPedPhotCam container
+
+    Bool_t ReadPadHistograms(TString type, TString filein);
+
+    Bool_t MergeONOFFMC(TString nameon="", TString nameoff="",
+                        TString namemc="", TString fileout="");
+
+    Bool_t WritePaddingDist(TString fileout);
+    Bool_t ReadPaddingDist(TString  filein);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    ClassDef(MPad, 0)    // task for the padding 
+}; 
+
+#endif
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MPadding.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MPadding.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPadding.cc	(revision 9772)
@@ -0,0 +1,554 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner, 10/2002   <mailto:magicsoft@rwagner.de>
+!   Author(s): Wolfgang Wittek, 01/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003    <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MPadding                                                               //
+//  (developped from MApplyPadding)                                        //
+//                                                                         //
+//  This task applies padding to a given Sigmabar target value.            //
+//  The task checks whether the data stream it is applied to has to be     //
+//  padded or not and if so, Gaussian noise with the difference in Sigma   //
+//  is produced and added to the particular event. The number of photons,  // 
+//  its error and the pedestal sigmas are altered.                         //
+//                                                                         //
+//  The padding has to be done before the image cleaning because the       //
+//  image cleaning depends on the pedestal sigmas.                         //
+//                                                                         //
+//  There are several ways of defining the sigmabar value to which the     // 
+//  events are padded:                                                     //
+//                                                                         //
+//  1) Set a fixed level (fFixedSigmabar) by calling 'SetTargetLevel'.     //
+//                                                                         //
+//  2) By calling 'SetDefiningHistogram', give a TH1D histogram            //
+//     (fHSigmabarMax) which defines the Sigmabar as a function of Theta.  //
+//                                                                         //
+//  3) By calling 'SetSigmaThetaHist', give a TH2D histogram               //
+//     (fHSigmaTheta) which contains the Sigmabar distribution for the     //
+//     different bins in Theta. For a given event, the sigmabar value to   //
+//     be used for the padding is thrown from this distribution.           //
+//                                                                         //
+//  Workaround :                                                           //  
+//  If none of these options is specified then PreProcess will try to read // 
+//  in a propriety format ASCII database for the CT1 test. The name of     // 
+//  this file is set by 'SetDatabaseFile'. From the data in this file a    //
+//  TH1D histogram (fHSigmabarMax) is generated.                           //
+//                                                                         //
+//  This implementation is still PRELIMINARY and requires some workarounds //
+//  put in SPECIFICALLY FOR THE CT1 TESTS, since a database to access is   //
+//  missing. It is not the FINAL MAGIC VERSION.                            //
+//                                                                         //
+//  For random numbers gRandom is used.                                    //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MPadding.h"
+
+#include <stdio.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+#include <TProfile.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MSigmabar.h"
+
+#include "MMcEvt.hxx"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+ClassImp(MPadding);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MPadding::MPadding(const char *name, const char *title)
+    : fRunType(0), fGroup(0), fFixedSigmabar(0), fHSigMaxAllocated(kFALSE), fHSigmabarMax(NULL), fHSigmaTheta(NULL)
+{
+    fName  = name  ? name  : "MPadding";
+    fTitle = title ? title : "Task for the padding";
+
+    //--------------------------------------------------------------------
+    // plot pedestal sigmas for testing purposes
+    fHSigmaPedestal = new TH2D("SigPed", "Padded vs orig. sigma",
+                               100, 0.0, 5.0, 100, 0.0, 5.0);
+   fHSigmaPedestal->SetXTitle("Orig. Pedestal sigma");
+   fHSigmaPedestal->SetYTitle("Padded Pedestal sigma");
+
+   // plot no.of photons (before vs. after padding) for testing purposes
+   fHPhotons = new TH2D("Photons", "Photons after vs.before padding",
+                        100, -10.0, 90.0, 100, -10, 90);
+   fHPhotons->SetXTitle("No.of photons before padding");
+   fHPhotons->SetYTitle("No.of photons after padding");
+
+   // plot of added NSB
+   fHNSB = new TH1D("NSB", "Distribution of added NSB", 100, -10.0, 10.0);
+   fHNSB->SetXTitle("No.of added NSB photons");
+   fHNSB->SetYTitle("No.of pixels");
+
+   fHSigmaOld = new TH2D;
+   fHSigmaOld->SetNameTitle("fHSigmaOld", "Sigma before padding");
+   fHSigmaOld->SetXTitle("Theta");
+   fHSigmaOld->SetYTitle("Sigma");
+
+   fHSigmaNew = new TH2D;
+   fHSigmaNew->SetNameTitle("fHSigmaNew", "Sigma after padding");
+   fHSigmaNew->SetXTitle("Theta");
+   fHSigmaNew->SetYTitle("Sigma");
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MPadding::~MPadding()
+{
+   delete fHSigmaPedestal;
+   delete fHPhotons;
+   delete fHNSB;
+   delete fHSigmaOld;
+   delete fHSigmaNew;
+   if (fHSigMaxAllocated && fHSigmabarMax)
+       delete fHSigmabarMax;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can provide a TH1D* histogram containing 
+//     - the target Sigmabar in bins of theta. 
+// Be sure to use the same binning as for the analysis
+//
+Bool_t MPadding::SetDefiningHistogram(TH1D *histo)
+{
+    if (fHSigmabarMax)
+    {
+        *fLog << warn << "MPadding - SigmabarMax already set.";
+        return kFALSE;
+    }
+
+    fHSigmabarMax  = histo;
+
+    fFixedSigmabar = 0;
+    fHSigmaTheta   = NULL;
+
+    *fLog << inf << "MPadding - Use Defining Histogram.";
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can provide a TH2D* histogram containing 
+//     - the Sigmabar distribution in bins of theta. 
+//
+Bool_t MPadding::SetSigmaThetaHist(TH2D *histo)
+{
+    if (fHSigmaTheta)
+    {
+        *fLog << warn << "MPadding - SigmaTheta already set.";
+        return kFALSE;
+    }
+
+    fHSigmaTheta   = histo;
+
+    fFixedSigmabar = 0;
+    if (fHSigMaxAllocated)
+    {
+        fHSigMaxAllocated = kFALSE;
+        delete fHSigmabarMax;
+    }
+    fHSigmabarMax  = NULL;
+
+    *fLog << inf << "MPadding - Use Sigma Theta Histogram.";
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+void MPadding::SetTargetLevel(Double_t sigmabar)
+{
+    fFixedSigmabar = sigmabar;
+
+    fHSigmaTheta   = NULL;
+    if (fHSigMaxAllocated)
+    {
+        fHSigMaxAllocated = kFALSE;
+        delete fHSigmabarMax;
+    }
+    fHSigmabarMax = NULL;
+
+    *fLog << inf << "MPadding - Use fixed sigmabar: fFixedSigmabar = ";
+    *fLog << fFixedSigmabar << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  check if MEvtHeader exists in the Parameter list already.
+//  if not create one and add them to the list
+//
+Int_t MPadding::PreProcess(MParList *pList)
+{
+  fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+  if (!fMcEvt)
+    {
+       *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+       return kFALSE;
+     }
+  
+   fPed = (MPedPhotCam*)pList->FindObject("MPedPhotCam");
+   if (!fPed)
+     {
+       *fLog << err << dbginf << "MPedPhotCam not found... aborting." << endl;
+       return kFALSE;
+     }
+  
+   fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+   if (!fCam)
+     {
+       *fLog << err << dbginf << "MGeomCam not found (no geometry information available)... aborting." << endl;
+       return kFALSE;
+     }
+  
+   fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+   if (!fEvt)
+     {
+       *fLog << err << dbginf << "MCerPhotEvt not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fSigmabar = (MSigmabar*)pList->FindCreateObj("MSigmabar");
+   if (!fSigmabar)
+     {
+       *fLog << err << dbginf << "MSigmabar not found... aborting." << endl;
+       return kFALSE;
+     }
+   
+   // Get Theta Binning  
+   MBinning* binstheta  = (MBinning*)pList->FindObject("BinningTheta");
+   if (!binstheta)
+     {
+       *fLog << err << dbginf << "BinningTheta not found... aborting." << endl;
+       return kFALSE;      
+     }
+
+   // Get Sigma Binning  
+   MBinning* binssigma  = (MBinning*)pList->FindObject("BinningSigmabar");
+   if (!binssigma)
+     {
+       *fLog << err << dbginf << "BinningSigmabar not found... aborting." << endl;
+       return kFALSE;      
+     }
+
+   MH::SetBinning(fHSigmaOld, binstheta, binssigma);
+   MH::SetBinning(fHSigmaNew, binstheta, binssigma);
+
+   //************************************************************************
+   // Create fSigmabarMax histogram
+   // (only if no fixed Sigmabar target value and no histogram have been 
+   // provided)
+   //
+   if (fFixedSigmabar==0 && !fHSigmabarMax && !fHSigmaTheta)
+   {
+       *fLog << inf << "MPadding - Creating fSigmabarMax histogram: ";
+       *fLog << "fFixedSigmabar=" << fFixedSigmabar << ", ";
+       *fLog << "fHSigmabarMax = " << fHSigmabarMax << endl;
+
+       // FIXME: Not deleted
+     fHSigmabarMax = new TH1D;
+     fHSigmabarMax->SetNameTitle("fHSigmabarMax", "Sigmabarmax for this analysis");
+
+     fHSigMaxAllocated = kTRUE;
+
+     MH::SetBinning(fHSigmabarMax, binstheta);
+
+     // -------------------------------------------------
+     // read in SigmabarParams
+     // workaround--proprietary file format--CT1test only BEGIN
+     // -------------------------------------------------
+     
+     FILE *f=fopen(fDatabaseFilename, "r");
+     if(!f) {
+         *fLog << err << dbginf << "Database file '" << fDatabaseFilename;
+         *fLog << "' was not found (specified by MPadding::SetDatabaseFile) ...aborting." << endl;
+         return kFALSE;
+     }
+
+     TAxis &axe = *fHSigmabarMax->GetXaxis();
+
+     char line[80];
+     while ( fgets(line, sizeof(line), f) != NULL) {
+         if (line[0]=='#')
+             continue;
+
+         Float_t sigmabarMin, sigmabarMax, thetaMin, thetaMax, ra, dec2;
+         Int_t type, group, mjd, nr;
+
+         sscanf(line,"%d %d %f %f %d %d %f %f %f %f",
+                &type, &group, &ra, &dec2, &mjd, &nr,
+                &sigmabarMin, &sigmabarMax, &thetaMin, &thetaMax);
+
+         if (group!=fGroup && type!=1) //selected ON group or OFF
+             continue;
+
+         const Int_t from = axe.FindFixBin(thetaMin);
+         const Int_t to   = axe.FindFixBin(thetaMax);
+
+         // find out which bin(s) we have to look at
+         for (Int_t i=from; i<to+1; i++)
+             if (sigmabarMax > fHSigmabarMax->GetBinContent(i))
+                 fHSigmabarMax->SetBinContent(i, sigmabarMax);
+     }//while
+  
+   } //fFixedSigmabar
+   //************************************************************************
+
+   if (!fHSigmabarMax && !fHSigmaTheta && fFixedSigmabar==0)
+   {
+       *fLog << err << "ERROR: Sigmabar for padding not defined... aborting." << endl;
+       return kFALSE;
+   }
+
+   return kTRUE;
+}
+
+Double_t MPadding::CalcOtherSig(const Double_t mySig, const Double_t theta) const
+{
+  //
+  // Get sigmabar which we have to pad to
+  //
+  const TAxis   &axe     = *fHSigmabarMax->GetXaxis();
+  const Int_t    binnum  =  axe.FindFixBin(theta);
+  const Bool_t   inrange =  theta>=axe.GetXmin() && theta<=axe.GetXmax();
+
+  if ((fHSigmabarMax || fHSigmaTheta) && !inrange)
+  {
+      *fLog << err << dbginf;
+      *fLog << "Theta of current event is beyond the limits, Theta = ";
+      *fLog << theta << " ...skipping." <<endl;
+      return -1;
+  }
+
+
+  //
+  // get target sigma for the current Theta from the histogram fHSigmabarMax
+  //
+  if (fHSigmabarMax != NULL) 
+      return fHSigmabarMax->GetBinContent(binnum);
+
+  //
+  // for the current Theta, 
+  // generate a sigma according to the histogram fHSigmaTheta
+  //
+  if (fHSigmaTheta != NULL)
+  {
+      Double_t otherSig = -1;
+
+      TH1D* fHSigma = fHSigmaTheta->ProjectionY("", binnum, binnum, "");
+
+      if (fHSigma->GetEntries()>0)
+          otherSig = fHSigma->GetRandom();
+
+      delete fHSigma;
+
+      return otherSig;
+  }
+
+  //
+  // use a fixed target sigma
+  //
+  return fFixedSigmabar;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the padding  (mySig ==> otherSig)
+// 
+Int_t MPadding::Padding(const Double_t quadraticDiff, const Double_t theta)
+{
+   const UInt_t npix = fEvt->GetNumPixels();
+
+   // pad only pixels   - which are used (before image cleaning)
+   //                   - and for which the no.of photons is != 0.0
+   //
+   for (UInt_t i=0; i<npix; i++) 
+   {   
+     MCerPhotPix &pix = (*fEvt)[i];
+     if ( !pix.IsPixelUsed() )
+       continue;
+/*
+     if ( pix.GetNumPhotons() == 0)
+     {
+       *fLog << "MPadding::Process(); no.of photons is 0 for used pixel" 
+             << endl;
+       continue;
+     }
+*/
+     const Double_t area = fCam->GetPixRatio(pix.GetPixId());
+
+     // add additional NSB to the number of photons
+     const Double_t NSB = sqrt(quadraticDiff*area) * gRandom->Gaus(0, 1);
+     const Double_t oldphotons = pix.GetNumPhotons();
+     const Double_t newphotons = oldphotons + NSB;
+     pix.SetNumPhotons(	newphotons );
+
+     fHNSB->Fill( NSB/sqrt(area) );
+     fHPhotons->Fill( newphotons/sqrt(area), oldphotons/sqrt(area) );
+
+     // error: add sigma of padded noise quadratically
+     const Double_t olderror = pix.GetErrorPhot();
+     const Double_t newerror = sqrt( olderror*olderror + quadraticDiff*area );
+     pix.SetErrorPhot( newerror );
+
+     MPedPhotPix &ppix = (*fPed)[i];
+
+     ppix.SetRms(0);
+
+     const Double_t oldsigma = ppix.GetRms();
+     const Double_t newsigma = sqrt( oldsigma*oldsigma + quadraticDiff*area );
+     ppix.SetRms( newsigma );
+
+     fHSigmaPedestal->Fill( oldsigma, newsigma );
+     fHSigmaOld->Fill( theta, oldsigma );
+     fHSigmaNew->Fill( theta, newsigma );
+   } //for
+
+   return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculate Sigmabar for current event
+// Then apply padding
+// 
+// 1) have current event
+// 2) get sigmabar(theta)
+// 3) pad event
+//
+Int_t MPadding::Process()
+{
+    const Double_t theta = kRad2Deg*fMcEvt->GetTelescopeTheta();
+
+    //
+    // Calculate sigmabar of event
+    //
+    Double_t mySig = fSigmabar->Calc(*fCam, *fPed, *fEvt);
+
+    //$$$$$$$$$$$$$$$$$$$$$$$$$$
+    mySig = 0.0;  // FIXME?
+    //$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+    const Double_t otherSig = CalcOtherSig(mySig, theta);
+
+    // Skip event if target sigma is zero
+    if (otherSig<=0)
+        return kCONTINUE;
+
+    // Determine quadratic difference other-mine
+    const Double_t quadraticDiff = otherSig*otherSig - mySig*mySig;
+
+    if (quadraticDiff < 0) {
+        *fLog << err << "ERROR - MPadding: Event has higher Sigmabar=" << mySig;
+        *fLog << " than Sigmabarmax=" << otherSig << " @ Theta =" << theta;
+        *fLog << " ...skipping." << endl;
+        return kCONTINUE; //skip
+    }
+
+    if (quadraticDiff == 0)
+        return kTRUE; //no padding necessary.
+
+    //
+    // quadratic difference is > 0, do the padding;
+    //
+    Padding(quadraticDiff, theta);
+
+    // Calculate Sigmabar again and crosscheck
+    //mySig = fSigmabar->Calc(*fCam, *fPed, *fEvt);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draws some histograms if IsGraphicalOutputEnabled
+//
+Bool_t MPadding::PostProcess()
+{
+    if (!IsGraphicalOutputEnabled())
+        return kTRUE;
+
+    TCanvas &c = *MH::MakeDefCanvas("Padding", "", 600, 900);
+    c.Divide(2,3);
+    gROOT->SetSelectedPad(NULL);
+
+    if (fHSigmabarMax != NULL)
+    {
+        c.cd(1);
+        fHSigmabarMax->DrawClone();
+    }
+    else if (fHSigmaTheta != NULL)
+    {
+        c.cd(1);
+        fHSigmaTheta->DrawClone();
+    }
+
+    c.cd(3);
+    fHSigmaPedestal->DrawClone();
+
+    c.cd(5);
+    fHPhotons->DrawClone();
+
+    c.cd(2);
+    fHNSB->DrawClone();
+
+    c.cd(4);
+    fHSigmaOld->DrawClone();     
+
+    c.cd(6);
+    fHSigmaNew->DrawClone();     
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysis/MPadding.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MPadding.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPadding.h	(revision 9772)
@@ -0,0 +1,68 @@
+#ifndef MARS_MPadding
+#define MARS_MPadding
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TH1D;
+class TH2D;
+class MGeomCam;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MMcEvt;
+class MSigmabar;
+class MParList;
+
+class MPadding : public MTask
+{
+private:
+    MGeomCam     *fCam;
+    MCerPhotEvt  *fEvt;
+    MSigmabar    *fSigmabar;
+    MMcEvt       *fMcEvt;
+    MPedPhotCam  *fPed;
+
+    Int_t     fRunType;
+    Int_t     fGroup;
+
+    TString   fDatabaseFilename; // data file used for generating fHSigmabarMax histogram
+    Double_t  fFixedSigmabar;    // fixed sigmabar value
+
+    Bool_t    fHSigMaxAllocated; // flag whether MPadding allocated it
+    TH1D     *fHSigmabarMax;     // histogram (sigmabarmax vs. Theta)
+    TH2D     *fHSigmaTheta;      // 2D-histogram (sigmabar vs. Theta)
+    TH2D     *fHSigmaPedestal;   //-> for testing: plot of padded vs orig. pedestal sigmas
+    TH2D     *fHPhotons;         //-> for testing: no.of photons after versus before padding
+    TH2D     *fHSigmaOld;        //-> histogram (sigma vs. Theta) before padding
+    TH2D     *fHSigmaNew;        //-> histogram (sigma vs. Theta) after padding
+    TH1D     *fHNSB;             //-> histogram of added NSB
+
+    Double_t CalcOtherSig(const Double_t mySig, const Double_t theta) const;
+    Bool_t   Padding(const Double_t quadDiff, const Double_t theta);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MPadding(const char *name=NULL, const char *title=NULL);
+    ~MPadding();
+
+    void SetRunType(Int_t runtype) { fRunType =  runtype; }
+    void SetGroup(Int_t group)     { fGroup   =  group; }
+
+    Bool_t SetDefiningHistogram(TH1D *hist);
+    void SetDatabaseFile(char *filename) { fDatabaseFilename = filename; }
+
+    Bool_t SetSigmaThetaHist(TH2D *histo);
+
+    void SetTargetLevel(Double_t sigmabar);
+
+    ClassDef(MPadding, 0)   // task for the padding
+}; 
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/manalysis/MParameters.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MParameters.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MParameters.cc	(revision 9772)
@@ -0,0 +1,92 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 03/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MParameterD, MParameterI
+//
+// Storage Container for doubles and ints
+//
+// This classes can be used for intermidiate variables which we don't want
+// to have in a special container.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MParameters.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MParameterD);
+ClassImp(MParameterI);
+ClassImp(MParameterDerr);
+//ClassImp(MParameter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MParameterD::MParameterD(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MParameterD";
+    fTitle = title ? title : "Storgare container for general parameters (double)";
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MParameterDerr::MParameterDerr(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MParameterDerr";
+    fTitle = title ? title : "Storgare container for general parameters (double) and its error";
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MParameterI::MParameterI(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MParameterI";
+    fTitle = title ? title : "Storgare container for general parameters (integer)";
+}
+
+void MParameterD::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":  Val=" << fVal << endl;
+}
+
+void MParameterDerr::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":  Val=" << fVal << "  Err=" << fErr << endl;
+}
+
+void MParameterI::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":  Val=" << fVal << endl;
+}
Index: /tags/Mars-V0.9/manalysis/MParameters.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MParameters.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MParameters.h	(revision 9772)
@@ -0,0 +1,120 @@
+#ifndef MARS_MParameters
+#define MARS_MParameters
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MParameterD : public MParContainer
+{
+private:
+    Double_t fVal;
+
+public:
+    MParameterD(const char *name=NULL, const char *title=NULL);
+
+    void SetVal(Double_t v) { fVal = v; }
+    Double_t GetVal() const { return fVal; }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MParameterD, 1) // Container to hold a generalized parameters (double)
+};
+
+class MParameterDerr : public MParContainer
+{
+private:
+    Double_t fVal;
+    Double_t fErr;
+
+public:
+    MParameterDerr(const char *name=NULL, const char *title=NULL);
+
+    void SetVal(Double_t v, Double_t e) { fVal = v; fErr = e; }
+    Double_t GetVal() const { return fVal; }
+    Double_t GetErr() const { return fErr; }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MParameterDerr, 1) // Container to hold a generalized parameters (double) and its Error
+};
+
+class MParameterI : public MParContainer
+{
+private:
+    Int_t fVal;
+
+public:
+    MParameterI(const char *name=NULL, const char *title=NULL);
+
+    void SetVal(Int_t v) { fVal = v; }
+    Int_t GetVal() const { return fVal; }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MParameterI, 1) // Container to hold a generalized parameters (integer)
+};
+/*
+class MParameters : public MParContainer
+{
+private:
+    TObjArray fList;
+    TObjArray fNames;
+
+public:
+    MParameters(const char *name=NULL, const char *title=NULL)
+    {
+        fName  = name  ? name  : "MParameters";
+        fTitle = title ? title : "Additional temporary parameters";
+
+        SetReadyToSave();
+    }
+
+    MParamaterI &AddInteger(const TString name, const TString title, Int_t val=0)
+    {
+        MParameterI &p = *new MParameterI(name, title);
+        p.SetValue(val);
+
+        fList.Add(&p);
+
+        TNamed &n = *new TNamed(name, title);
+        fNames.Add(&n);
+
+        return p;
+    }
+
+    MParameterD &AddDouble(const TString name, const TString title, Double_t val=0)
+    {
+        MParameterD &p = *new MParameterD(name, title);
+        p.SetValue(val);
+
+        fList.Add(&p);
+
+        TNamed &n = *new TNamed(name, title);
+        fNames.Add(&n);
+
+        return p;
+    }
+
+    const TObjArray &GetList()
+    {
+        fList.SetNames(&fNames);
+        return fList;
+    }
+
+    MParameterD *GetParameterD(const TString &name)
+    {
+        fList.SetNames(&fNames);
+        return (MParamaterD*)fList.FindObject(name);
+    }
+
+    MParameterI *GetParameterI(const TString &name)
+    {
+        fList.SetNames(&fNames);
+        return (MParameterI*)fList.FindObject(name);
+    }
+
+    ClassDef(MParameters, 1) // List to hold generalized parameters (MParameterD/I)
+    }
+    */
+#endif
Index: /tags/Mars-V0.9/manalysis/MPedCalUpdate.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MPedCalUpdate.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPedCalUpdate.cc	(revision 9772)
@@ -0,0 +1,236 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 03/2004 <mailto:tbretz@astro.uni.wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MPedCalUpdate
+//
+//  This task reads files stored by MJ* storing pedestals (F2) and
+//  calibration constants (F1) while an eventloop is running.
+//
+//  The update is done according to the run-number. The information
+//  which ped/cal files corresponds to which run-number is stored in
+//  an ascii file. In a next step this ascii file can be created
+//  automatically (hopefully from the Database)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedCalUpdate.h"
+
+#include <fstream>
+#include <TFile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+#include "MPedPhotCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MBadPixelsCam.h"
+
+ClassImp(MPedCalUpdate);
+
+using namespace std;
+
+static const TString gsDefName  = "MPedCalUpdate";
+static const TString gsDefTitle = "";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MPedCalUpdate::MPedCalUpdate(const char *fname, const char *name, const char *title)
+    : fPedPhot(0), fCalCam(0), fFileName(fname)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fLast=0;
+}
+
+Bool_t MPedCalUpdate::ReadPed(const char *fname)
+{
+    TFile file(fname, "READ");
+    if (fPedPhot->Read()<=0)
+    {
+        *fLog << err << "Unable to read MPedPhotCam from " << fname << endl;
+        return kFALSE;
+    }
+
+    if (file.FindKey("MBadPixelsCam"))
+    {
+        MBadPixelsCam bad;
+        if (bad.Read()<=0)
+        {
+            *fLog << err << "Unable to read MBadPixelsCam from " << fname << endl;
+            return kFALSE;
+        }
+        fBadPix->Merge(bad);
+    }
+    return kTRUE;
+}
+
+Bool_t MPedCalUpdate::ReadCal(const char *fname)
+{
+    TFile file(fname, "READ");
+    if (fCalCam->Read()<=0)
+    {
+        *fLog << err << "Unable to read MCalibrationChargeCam from " << fname << endl;
+        return kFALSE;
+    }
+
+    if (file.FindKey("MBadPixelsCam"))
+    {
+        MBadPixelsCam bad;
+        if (bad.Read()<=0)
+        {
+            *fLog << "Unable to read MBadPixelsCam from " << fname << endl;
+            return kFALSE;
+        }
+        fBadPix->Merge(bad);
+    }
+    return kTRUE;
+}
+
+Bool_t MPedCalUpdate::ReadPC(TString &line)
+{
+    const Int_t f = line.First(' ');
+    if (f<0)
+    {
+        *fLog << err << "Entry for pedestal file not found!" << endl;
+        return kFALSE;
+    }
+
+    const Int_t l = line.Last(' ')+1;
+    if (l<0)
+    {
+        *fLog << err << "Entry for calibration file not found!" << endl;
+        return kFALSE;
+    }
+
+    const TString fname1 = line(0, f);
+    const TString fname2 = line(l, line.Length());
+
+    TString mid(line(f, l-f));
+    mid=mid.Strip(TString::kBoth);
+    if (!mid.IsNull())
+    {
+        *fLog << err << "Found three filenames '" << fname1 << "' '" << mid << "' '" << fname2 << "'" << endl;
+        return kFALSE;
+    }
+
+    if (!ReadPed(fname1))
+        return kFALSE;
+
+    if (!ReadCal(fname2))
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MPedCalUpdate::ReInit(MParList *pList)
+{
+    MRawRunHeader *header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!header)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+    fPedPhot = (MPedPhotCam*)pList->FindCreateObj("MPedPhotCam");
+    if (!fPedPhot)
+        return kFALSE;
+    fBadPix = (MBadPixelsCam*)pList->FindCreateObj("MBadPixelsCam");
+    if (!fBadPix)
+        return kFALSE;
+    fCalCam = (MCalibrationChargeCam*)pList->FindCreateObj("MCalibrationChargeCam");
+    if (!fCalCam)
+        return kFALSE;
+
+    const Int_t run = header->GetRunNumber();
+
+    ifstream fin(fFileName);
+    if (!fin)
+    {
+        *fLog << err << "Cannot open file: " << fFileName << endl;
+        return kFALSE;
+    }
+
+    Int_t last = 0;
+
+    TString readline;
+
+    while (1)
+    {
+        // Read line from file
+        TString line;
+        line.ReadLine(fin);
+        if (!fin && !readline.IsNull() && fLast!=last)
+        {
+            *fLog << dbg << "Reading line " << readline << endl;
+            fLast = last;
+            return ReadPC(readline);
+        }
+
+        if (!fin)
+            break;
+
+        line = line.Strip(TString::kBoth);
+
+        // Interprete line
+        Int_t len, num;
+        if (sscanf(line.Data(), "%d %n", &num, &len)!=1)
+            continue;
+
+        // Check whether entries are in increasing order
+        if (num<=last)
+        {
+            *fLog << err << "Runs must be in increasing order..." << endl;
+            return kFALSE;
+        }
+        last = num;
+
+        // Check if a new set of files must be read
+        if (num<=run)
+        {
+            readline=line;
+            readline.Remove(0, len);
+            continue;
+        }
+
+        // This is the case if the correct files were already read
+        if (fLast==num)
+            return kTRUE;
+
+        // Read files given in new line
+        *fLog << dbg << "Reading line " << readline << endl;
+        fLast = num;
+        return ReadPC(readline);
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysis/MPedCalUpdate.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MPedCalUpdate.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPedCalUpdate.h	(revision 9772)
@@ -0,0 +1,35 @@
+#ifndef MARS_MPedCalUpdate
+#define MARS_MPedCalUpdate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MPedPhotCam;
+class MCalibrationChargeCam;
+class MBadPixelsCam;
+
+class MPedCalUpdate : public MTask
+{
+private:
+    MPedPhotCam           *fPedPhot;
+    MCalibrationChargeCam *fCalCam;
+    MBadPixelsCam         *fBadPix;
+
+    TString fFileName;
+
+    Int_t fLast;
+
+    Bool_t ReadCal(const char *name);
+    Bool_t ReadPed(const char *name);
+    Bool_t ReadPC(TString &line);
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MPedCalUpdate(const char *filename, const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MPedCalUpdate, 1) // Task to update Pedestals and Cal-Constants while an eventloop is running
+}; 
+
+#endif
+
Index: /tags/Mars-V0.9/manalysis/MPedestalCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MPedestalCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPedestalCalc.cc	(revision 9772)
@@ -0,0 +1,229 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix 11/2002 <mailto:jflix@ifae.es>
+!   Author(s): Thomas Bretz 11/2002 <mailto:tbretz@astro.uni-wuerburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MPedestalCalc
+//
+//  Task to calculate the pedestals from the event stream.
+//
+//  From the events two streams of pedestals are created like in the
+//  following table
+//  MRawEvtData:    1   2   3   4   5   6   7   8   9  10  11  12
+//  MPedestalCam;1: ------1------   ------2------   ------3------...
+//  MPedestalCam;2:         ------1------   ------2------  ------...
+//
+//  Input Containers:
+//   MRawEvtData
+//
+//  Output Containers:
+//   MPedestalCam;1
+//   MPedestalCam;2
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MHFadcCam.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MPedestalCalc);
+
+MPedestalCalc::MPedestalCalc(const char *name, const char *title)
+    : fNumBranches(2), fTimeSlot(6), fHists(NULL)
+{
+    fName  = name  ? name  : "MPedestalCalc";
+    fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
+
+    AddToBranchList("fHiGainPixId");
+    AddToBranchList("fLoGainPixId");
+    AddToBranchList("fHiGainFadcSamples");
+    AddToBranchList("fLoGainFadcSamples");
+}
+
+Int_t MPedestalCalc::PreProcess(MParList *pList)
+{
+    if (fHists)
+    {
+        *fLog << err << "ERROR - Previous PostProcess not called." << endl;
+        return kFALSE;
+    }
+
+    fHists = new MHFadcCam[fNumBranches];
+    fStart = new MTime    [fNumBranches];
+
+    fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvt)
+    {
+        *fLog << dbginf << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindCreateObj("MPedestalCam");
+    if (!fPedestals)
+        return kFALSE;
+
+    fPedTime = (MTime*)pList->FindCreateObj("MTime", "MPedestalTime");
+    if (!fPedTime)
+        return kFALSE;
+
+    //
+    // Fixme: FindCreateObj --> FindObject
+    //
+    fEvtTime = (MTime*)pList->FindCreateObj("MTime", "MRawEvtTime");
+    if (!fEvtTime)
+        return kFALSE;
+
+    for (int i=0; i<fNumBranches; i++)
+        fStart[i].SetTime(fTimeSlot*10/fNumBranches*i, 0);
+
+    fPedTime->SetDuration(fTimeSlot);
+    fEvtTime->SetTime(0, 0);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Checks whether the current event exceed the validity range of a pedestal
+//  in one of the streams. If this is the case the data from the histogram
+//  is dumped as pedestals into the corresponding containers and the
+//  histograms are reset.
+//
+//  Then the current event is filled into the histograms.
+//
+Int_t MPedestalCalc::Process()
+{
+    //
+    // Time when filling of stream a/b must be restarted
+    //
+    for (int i=0; i<fNumBranches; i++)
+    {
+        Check(i);
+        Fill(i);
+    }
+
+    fEvtTime->SetTime(fEvtTime->GetTimeLo()+10, 0);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill the event in the histogram if the current time of the
+//  event is _after_ the start time for filling
+//
+void MPedestalCalc::Fill(Int_t i)
+{
+    if (*fEvtTime < fStart[i])
+        return;
+
+    fHists[i].Fill(fRawEvt);
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the current time of the event is equal or after the time
+//  which is given by the start time plus the validity range
+//  calculate the corresponding set of pedestals and reset the
+//  histograms
+//
+void MPedestalCalc::Check(Int_t i)
+{
+    if (*fEvtTime-fStart[i] < fTimeSlot*10)
+        return;
+
+    Calc(i);
+
+    fStart[i] = *fEvtTime;
+    fHists[i].ResetHistograms();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes all dynamicly allocated arrays
+//
+Bool_t MPedestalCalc::PostProcess()
+{
+    delete fHists;
+    delete fStart;
+
+    fHists=NULL;
+
+    return kTRUE;
+}
+
+/*
+ #include "MRawEvtData.h"
+ */
+// --------------------------------------------------------------------------
+//
+//  Dumps the mean, rms and their errors from the filled histograms into
+//  the Pedestal container. Sets the ReadyToSaveFlag of the MPedestalCam
+//  container.
+//
+void MPedestalCalc::Calc(Int_t i) const
+{
+    // FIXME! Fit +- 3 sigma to avoid outliers...
+
+    MRawEvtPixelIter pixel(fRawEvt);
+    while (pixel.Next())
+    {
+        const UInt_t pixid = pixel.GetPixelId();
+
+        const TH1 &h = *fHists[i].GetHistHi(pixid);
+
+        const Int_t   entries = (Int_t)h.GetEntries();
+        const Float_t meanhi  = h.GetMean();
+        const Float_t rmshi   = h.GetRMS();
+
+        const Float_t meanhierr = rmshi/sqrt(entries);
+        const Float_t rmshierr  = rmshi/sqrt(entries*2);
+
+        MPedestalPix &pix = (*fPedestals)[pixid];
+        pix.SetPedestal(meanhi, rmshi);
+        pix.SetPedestalRms(meanhierr, rmshierr);
+    }
+
+    *fPedTime = fStart[i];
+
+    fPedTime->SetReadyToSave();
+    fPedestals->SetReadyToSave();
+
+    /*
+     *fLog << i << "[" << fHists[i].GetHistHi(0)->GetEntries()/fRawEvt->GetNumHiGainSamples() << "]:  ";
+     *fLog << fEvtTime->GetTimeLo() << ": Calc [";
+     *fLog << fStart[i].GetTimeLo() << " < ";
+     *fLog << fStart[i].GetTimeLo()+fTimeSlot*10 << "]" << endl;
+     */
+}
Index: /tags/Mars-V0.9/manalysis/MPedestalCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MPedestalCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPedestalCalc.h	(revision 9772)
@@ -0,0 +1,59 @@
+#ifndef MARS_MPedestalCalc
+#define MARS_MPedestalCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPedestalCalc                                                           //
+//                                                                         //
+// Implementation of ped. Eval. defined in Jan 02                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MHFadCam
+#include "MHFadcCam.h"
+#endif
+
+class MTime;
+class MRawEvtData;
+class MPedestalCam;
+
+class MPedestalCalc : public MTask 
+{
+private:
+    Int_t   fNumBranches;
+    Float_t fTimeSlot;
+
+    MRawEvtData  *fRawEvt;
+    MPedestalCam *fPedestals;  //
+
+    MHFadcCam *fHists;         //[fNumBranches]
+
+    MTime     *fPedTime; // time of the pedestal event
+    MTime     *fEvtTime; // time of the current event
+    MTime     *fStart;   //[fNumBranches] starting time of the current pedestal
+
+
+    void Calc(Int_t i) const;
+    void Fill(Int_t i);
+    void Check(Int_t i);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MPedestalCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetTimeSlot(Float_t newslot) { fTimeSlot = newslot; }
+    void SetNumBranches(Int_t num) { fNumBranches = num; }
+
+    ClassDef(MPedestalCalc, 0) // Task to calculate the pestels from pedestal events
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/manalysis/MPedestalSum.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MPedestalSum.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPedestalSum.cc	(revision 9772)
@@ -0,0 +1,227 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo 7/2002  <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz 2002  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MPedestalSum
+//
+//   This is a task which calculates the number of photons from the FADC
+//   time slices. It weights the each slice according to the numbers in
+//   the array fWeight (default: all slices added up with weight 1).
+//
+//   The weights are rescaled, such that sum(weigths)=num slices
+//
+//  Input Containers:
+//   MRawRunHeader, MRawEvtData, MPedestalCam
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MPedestalSum.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcRunHeader.hxx"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"       // MRawEvtData::GetNumPixels
+#include "MCerPhotEvt.h"
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MPedestalSum);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MPedestalSum::MPedestalSum(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPedestalSum";
+    fTitle = title ? title : "Calculate pixel signal from FADC data";
+
+    AddToBranchList("MRawEvtData.fHiGainPixId");
+    AddToBranchList("MRawEvtData.fLoGainPixId");
+    AddToBranchList("MRawEvtData.fHiGainFadcSamples");
+    AddToBranchList("MRawEvtData.fLoGainFadcSamples");
+
+    SetDefaultWeights();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawRunHeader
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//  - MCerPhotEvt
+//
+Int_t MPedestalSum::PreProcess(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << dbginf << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+    fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvt)
+    {
+        *fLog << dbginf << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindCreateObj("MCerPhotEvt");
+    if (!fCerPhotEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the run type and camera version.
+// If the file is a MC file and the used camera version is <= 40
+// we enable a fix for truncated pedestal means in this version.
+//
+Bool_t MPedestalSum::ReInit(MParList *pList)
+{
+    /*
+    const MRawRunHeader *runheader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!runheader)
+    {
+        *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+        return kTRUE;
+    }
+
+    if (fRunHeader->GetNumSamplesHiGain() != fWeight.GetSize())
+    {
+        *fLog << dbginf << "Number of FADC slices (" << fRunHeader->GetNumSamplesHiGain() <<") is different from assumed one (" << fWeight.GetSize() << ")... aborting." << endl;
+        return kFALSE;
+    }
+
+    Bool_t fIsMcFile = runheader->GetRunType() == kRTMonteCarlo;
+    if (!fIsMcFile)
+        return kTRUE;
+
+    ScalePedestals();
+
+    MMcRunHeader *mcrunheader = (MMcRunHeader*)pList->FindObject("MMcRunHeader");
+    if (!mcrunheader)
+    {
+        *fLog << warn << dbginf << "Warning - cannot check for camera version, MC run header not found." << endl;
+        return kTRUE;
+    }
+
+    fEnableFix = kFALSE;
+    if (mcrunheader->GetCamVersion() <= 40)
+        fEnableFix = kTRUE;
+     */
+    return kTRUE;
+}
+
+void MPedestalSum::ScalePedestals()
+{
+    Int_t n = 577; //FIXME: fPedestals->GetNumPixel();
+
+    for (int idx=0; idx<n; idx++)
+    {
+        MPedestalPix &ped = (*fPedestals)[idx];
+
+        const Double_t offset = fEnableFix ? ped.GetPedestal()-0.5 : ped.GetPedestal();
+        ped.Set(offset*fSumWeights, ped.GetPedestalRms()*sqrt(fSumQuadWeights));
+    }
+
+    fPedestals->SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MCerPhotEvt container.
+//
+Int_t MPedestalSum::Process()
+{
+    //fCerPhotEvt->InitSize(fRawEvt->GetNumPixels());
+
+//    if (fIsMcFile)
+//        ScalePedestals();
+
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    while (pixel.Next())
+    {
+        const UInt_t idx = pixel.GetPixelId();
+
+        const int n = fRunHeader->GetNumSamplesHiGain();
+
+        //
+        // Calculate pixel signal unless it has all FADC slices empty:
+        //
+        Byte_t *ptr = pixel.GetHiGainSamples();
+
+        Float_t nphot = 0;
+        Float_t nerr  = 0;
+        for(Int_t i=0; i<n; i++)
+        {
+            nphot += ptr[i];
+            nerr  += ptr[i]*ptr[i];
+        }
+
+        nphot /= n;
+
+        fCerPhotEvt->AddPixel(idx, nphot, sqrt(nerr/n-nphot*nphot));
+
+        // FIXME! Handling of Lo Gains is missing!
+    }
+
+    fCerPhotEvt->FixSize();
+    fCerPhotEvt->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set default values for the number of slices and weights:
+//
+void MPedestalSum::SetDefaultWeights()
+{
+    const Float_t dummy[15] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
+    fWeight.Set(15, dummy);
+}
Index: /tags/Mars-V0.9/manalysis/MPedestalSum.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MPedestalSum.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPedestalSum.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MPedestalSum
+#define MARS_MPedestalSum
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPedestalSum                                                            //
+//                                                                         //
+// Integrates the desired ADC time slices of one pixel and substracts the  //
+// pedestal (offset) value                                                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MPedestalCam;
+class MCerPhotEvt;
+class MRawRunHeader;
+
+class MPedestalSum : public MTask
+{
+    MPedestalCam   *fPedestals;  // Pedestals of all pixels in the camera
+    MRawEvtData    *fRawEvt;     // raw event data (time slices)
+    MCerPhotEvt    *fCerPhotEvt; // Cerenkov Photon Event used for calculation
+    MRawRunHeader  *fRunHeader;  // RunHeader information
+ 
+    Bool_t          fEnableFix;  // fix for a bug in files from older camera versions (<=40)
+    Bool_t          fIsMcFile;
+
+    TArrayF         fWeight;  // Weights for adding up the ADC slices
+    Float_t         fSumWeights;
+    Float_t         fSumQuadWeights;
+
+    void SetDefaultWeights();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Bool_t ReInit(MParList *pList);
+    void ScalePedestals();
+
+public:
+    MPedestalSum(const char *name=NULL, const char *title=NULL);
+
+    // FIXME: The array size should be checked!
+    void   SetWeights(const TArrayF &w) { fWeight = w; }
+
+    ClassDef(MPedestalSum, 0)   // Task to calculate cerenkov photons from raw data
+};
+ 
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MPedestalWorkaround.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MPedestalWorkaround.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPedestalWorkaround.cc	(revision 9772)
@@ -0,0 +1,552 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Sabrina Stark   12/2003 <mailto:lstark@particle.phys.ethz.ch>
+!              Wolfgang Wittek 12/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPedestalWorkaround                                                     //
+//                                                                         //
+// copies the pedestal value and the pedestal RMS                          //
+//        from the container MPedPhotCam                                   //
+//        into the contaier  MPedestalCam                                  //
+//                                                                         //
+// put the zenith angle into MMcEvt;                                       //
+//     the zenith angle is taken from the runbooks                         //
+//     (1 fixed zenith angle for a given run)                              //
+//                                                                         //
+// this workaround is necessary                                            //
+// - as long as the analysis classes                                       //
+//   take the pedestals from MPedestalCam; in the long run they have to    //
+//   be taken from MPedPhotCam                                             //
+// - and as long as the container for the zenith angle is not defined      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalWorkaround.h"
+
+#include <stdio.h>
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MGeomCam.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+#include "MMcEvt.hxx"
+#include "MRawRunHeader.h"
+
+using namespace std;
+
+ClassImp(MPedestalWorkaround);
+
+MPedestalWorkaround::MPedestalWorkaround(const char *name, const char *title)
+{
+    fName = name ? name : "MPedestalWorkaround";
+    fTitle = title ? title : "Storage of pedestal values and RMS in units of photons";
+   
+}
+
+// ------------------------------------------------------------------------
+//
+
+Int_t MPedestalWorkaround::PreProcess(MParList *pList)
+{
+  /*
+   fPed = (MPedestalCam*)pList->FindObject("MPedestalCam");
+   if (!fPed)
+     {
+       *fLog << err << "MPedestalCam not found... aborting." << endl;
+       return kFALSE;
+     }
+  */
+
+   fPedPhot = (MPedPhotCam*)pList->FindObject("MPedPhotCam");
+   if (!fPedPhot)
+     {
+       *fLog << err << "MPedPhotCam not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+   if (!fCam)
+     {
+       *fLog << err << "MGeomCam not found (no geometry information available)... aborting." << endl;
+       return kFALSE;
+     }
+
+   fRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+   if (!fRun)
+   {
+       *fLog << err << "MRawRunHeader not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   fMcEvt = (MMcEvt*)pList->FindCreateObj("MMcEvt");
+   if (!fMcEvt)
+   {
+       *fLog << err << "MMcEvt not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+Int_t MPedestalWorkaround::Process()
+{
+  //-------------------------------------------------------------------
+  // copy the pedestal and the pedestal RMS 
+  // from MPedPhotCam into MPedestalCam   
+
+  // set pedestalRMS = 0 if it is too high
+  UInt_t imaxnumpix = fCam->GetNumPixels();
+  for (UInt_t i=0; i<imaxnumpix; i++)
+  {
+    Double_t val = (*fPedPhot)[i].GetRms();
+    if (val < 0.0 || val > 10.0)
+      (*fPedPhot)[i].SetRms(0.0);
+  }
+
+
+  //-------------------------------------------------------------------
+  // put the zenith angle into MMcEvt
+
+  Double_t thetadeg;
+  Double_t thetarad;
+
+
+  /*
+  Int_t run = fRun->GetRunNumber();
+
+  if      (run == 3127)  thetadeg = 27.2;  // Crab
+  else if (run == 3128)  thetadeg = 25.6;
+  else if (run == 3129)  thetadeg = 24.3;
+  else if (run == 3130)  thetadeg = 23.9;
+
+
+  else if (run == 3132)  thetadeg = 22.9;
+  else if (run == 3133)  thetadeg = 22.8;
+  else if (run == 3134)  thetadeg = 22.3;
+  else if (run == 3135)  thetadeg = 21.9;
+  else if (run == 3136)  thetadeg = 21.5;
+  else if (run == 3137)  thetadeg = 21.1;
+  else if (run == 3138)  thetadeg = 20.8;
+  else if (run == 3139)  thetadeg = 20.4;
+
+  else if (run == 3140)  thetadeg = 19.5;
+  else if (run == 3141)  thetadeg = 19.4;
+  else if (run == 3142)  thetadeg = 19.0;
+  else if (run == 3143)  thetadeg = 18.6;
+  else if (run == 3144)  thetadeg = 13.0;
+  else if (run == 3145)  thetadeg = 12.4;
+  else if (run == 3146)  thetadeg = 12.1;
+  else if (run == 3147)  thetadeg = 11.7;
+  else if (run == 3148)  thetadeg = 11.3;
+  else if (run == 3149)  thetadeg = 11.9;
+
+  else if (run == 3150)  thetadeg = 10.6;
+  else if (run == 3151)  thetadeg = 10.3;
+  else if (run == 3152)  thetadeg = 10.0;
+  else if (run == 3153)  thetadeg =  9.6;
+  else if (run == 3154)  thetadeg =  9.3;
+  else if (run == 3155)  thetadeg =  9.0;
+  else if (run == 3156)  thetadeg =  8.7;
+  else if (run == 3157)  thetadeg =  8.4;
+  else if (run == 3158)  thetadeg =  8.1;
+  else if (run == 3159)  thetadeg =  7.9;
+
+  else if (run == 3160)  thetadeg =  7.7;
+  else if (run == 3161)  thetadeg =  7.3;
+  else if (run == 3162)  thetadeg =  7.2;
+  else if (run == 3163)  thetadeg =  7.0;
+  else if (run == 3164)  thetadeg =  6.8;
+  else if (run == 3165)  thetadeg =  6.7;
+  else if (run == 3166)  thetadeg =  6.6;
+  else if (run == 3167)  thetadeg =  6.5;
+  else if (run == 3168)  thetadeg =  6.4;
+  else if (run == 3169)  thetadeg =  6.4;
+
+  else if (run == 3170)  thetadeg =  6.4;
+  else if (run == 3171)  thetadeg =  6.4;
+  else if (run == 3172)  thetadeg =  6.5;
+  else if (run == 3173)  thetadeg =  6.6;
+  else if (run == 3174)  thetadeg =  6.7;
+
+  else if (run == 3176)  thetadeg =  7.1;
+  else if (run == 3177)  thetadeg =  7.4;
+  else if (run == 3178)  thetadeg =  7.6;
+  else if (run == 3179)  thetadeg =  7.9;
+
+
+  else if (run == 3182)  thetadeg =  8.4;
+  else if (run == 3183)  thetadeg =  8.9;
+  else if (run == 3184)  thetadeg =  9.2;
+  else if (run == 3185)  thetadeg =  9.5;
+  else if (run == 3186)  thetadeg =  9.8;
+  else if (run == 3187)  thetadeg = 10.5;
+  else if (run == 3188)  thetadeg = 10.9;
+  else if (run == 3189)  thetadeg = 11.2;
+
+  else if (run == 3190)  thetadeg = 11.6;
+  else if (run == 3191)  thetadeg = 11.6;
+  else if (run == 3192)  thetadeg = 12.4;
+  else if (run == 3193)  thetadeg = 12.7;
+  else if (run == 3194)  thetadeg = 13.1;
+  else if (run == 3195)  thetadeg = 13.5;
+  else if (run == 3196)  thetadeg = 13.9;
+  else if (run == 3197)  thetadeg = 14.3;
+  else if (run == 3198)  thetadeg = 14.7;
+  else if (run == 3199)  thetadeg = 15.1;
+
+  else if (run == 3200)  thetadeg = 15.6;
+  else if (run == 3201)  thetadeg = 16.0;
+  else if (run == 3202)  thetadeg = 16.5;
+  else if (run == 3203)  thetadeg = 16.9;
+  else if (run == 3204)  thetadeg = 17.3;
+  else if (run == 3205)  thetadeg = 17.7;
+  else if (run == 3206)  thetadeg = 18.2;
+  else if (run == 3207)  thetadeg = 18.6;
+  else if (run == 3208)  thetadeg = 19.0;
+  else if (run == 3209)  thetadeg = 19.4;
+
+  else if (run == 3210)  thetadeg = 19.9;
+  else if (run == 3211)  thetadeg = 20.4;
+  else if (run == 3212)  thetadeg = 20.8;
+  else if (run == 3213)  thetadeg = 21.2;
+  else if (run == 3214)  thetadeg = 21.7;
+  else if (run == 3215)  thetadeg = 22.2;
+  else if (run == 3216)  thetadeg = 25.6;  // Off Crab1
+  else if (run == 3217)  thetadeg = 25.0;
+  else if (run == 3218)  thetadeg = 24.5;
+  else if (run == 3219)  thetadeg = 24.0;
+
+  else if (run == 3220)  thetadeg = 23.5;
+  else if (run == 3221)  thetadeg = 22.5;
+  else if (run == 3222)  thetadeg = 22.1;
+
+  else if (run == 3225)  thetadeg = 15.1;
+  else if (run == 3226)  thetadeg = 15.0;
+  else if (run == 3227)  thetadeg = 14.5;
+  else if (run == 3228)  thetadeg = 14.1;
+  else if (run == 3229)  thetadeg = 13.8;
+
+  else if (run == 3230)  thetadeg = 13.3;
+  else if (run == 3231)  thetadeg = 13.0;
+  else if (run == 3232)  thetadeg = 12.6;
+  else if (run == 3233)  thetadeg = 12.3;
+  else if (run == 3234)  thetadeg = 12.0;
+  else if (run == 3235)  thetadeg = 11.6;
+  else if (run == 3236)  thetadeg = 11.3;
+  else if (run == 3237)  thetadeg = 11.0;
+  else if (run == 3238)  thetadeg = 10.8;
+  else if (run == 3239)  thetadeg = 10.4;
+
+  else if (run == 3240)  thetadeg = 10.1;
+  else if (run == 3241)  thetadeg =  9.9;
+  else if (run == 3242)  thetadeg =  9.6;
+  else if (run == 3243)  thetadeg =  9.4;
+  else if (run == 3244)  thetadeg =  9.2;
+  else if (run == 3245)  thetadeg =  9.0;
+  else if (run == 3246)  thetadeg =  8.9;
+  else if (run == 3247)  thetadeg =  8.8;
+  else if (run == 3248)  thetadeg =  8.7;
+  else if (run == 3249)  thetadeg =  8.6;
+
+  else if (run == 3250)  thetadeg =  8.6;
+  else if (run == 3251)  thetadeg =  8.6;
+  else if (run == 3252)  thetadeg =  8.6;
+  else if (run == 3253)  thetadeg =  8.7;
+  else if (run == 3254)  thetadeg =  8.8;
+  else if (run == 3255)  thetadeg =  8.9;
+  else if (run == 3256)  thetadeg =  9.1;
+  else if (run == 3257)  thetadeg =  9.3;
+  else if (run == 3258)  thetadeg =  9.5;
+  else if (run == 3259)  thetadeg =  9.7;
+  else if (run == 3260)  thetadeg =  9.9;
+
+  else if (run == 3261)  thetadeg = 10.2;
+  else if (run == 3262)  thetadeg = 10.5;
+  else if (run == 3263)  thetadeg = 10.8;
+  else if (run == 3264)  thetadeg = 11.1;
+  else if (run == 3265)  thetadeg = 11.4;
+  else if (run == 3266)  thetadeg = 11.8;
+  else if (run == 3267)  thetadeg = 12.1;
+  else if (run == 3268)  thetadeg = 12.5;
+  else if (run == 3269)  thetadeg = 12.8;
+
+  else if (run == 3270)  thetadeg = 13.2;
+  else if (run == 3271)  thetadeg = 13.5;
+  else if (run == 3272)  thetadeg = 13.9;
+  else if (run == 3273)  thetadeg = 14.0;
+  else if (run == 3274)  thetadeg = 14.4;
+
+  else if (run == 3284)  thetadeg =  7.0;  // Crab
+  else if (run == 3285)  thetadeg =  7.2;
+  else if (run == 3286)  thetadeg =  7.4;
+  else if (run == 3287)  thetadeg =  7.5;
+  else if (run == 3288)  thetadeg =  8.4;
+  else if (run == 3289)  thetadeg =  9.0;
+
+  else if (run == 3290)  thetadeg =  9.4;
+  else if (run == 3291)  thetadeg =  9.8;
+  else if (run == 3292)  thetadeg = 10.2;
+  else if (run == 3293)  thetadeg = 10.5;
+  else if (run == 3294)  thetadeg = 10.9;
+  else if (run == 3295)  thetadeg = 11.3;
+  else if (run == 3296)  thetadeg = 11.8;
+  else if (run == 3297)  thetadeg = 12.2;
+  else if (run == 3298)  thetadeg = 12.6;
+  else if (run == 3299)  thetadeg = 13.0;
+
+  else if (run == 3300)  thetadeg = 13.5;
+  else if (run == 3301)  thetadeg = 13.9;
+  else if (run == 3302)  thetadeg = 14.3;
+  else if (run == 3303)  thetadeg = 14.8;
+  else if (run == 3304)  thetadeg = 15.2;
+  else if (run == 3305)  thetadeg = 15.7;
+  else if (run == 3306)  thetadeg = 16.2;
+  else if (run == 3307)  thetadeg = 16.6;
+  else if (run == 3308)  thetadeg = 17.1;
+  else if (run == 3309)  thetadeg = 17.6;
+
+  else if (run == 3310)  thetadeg = 17.9;
+  else if (run == 3311)  thetadeg = 18.4;
+  else if (run == 3312)  thetadeg = 18.9;
+  else if (run == 3313)  thetadeg = 19.3;
+  else if (run == 3314)  thetadeg = 19.8;
+  else if (run == 3315)  thetadeg = 20.1;
+  else if (run == 3316)  thetadeg = 20.7;
+  else if (run == 3317)  thetadeg = 21.2;
+  else if (run == 3318)  thetadeg = 21.7;
+  else if (run == 3319)  thetadeg = 22.1;
+
+  else if (run == 3320)  thetadeg = 22.5;
+  else if (run == 3321)  thetadeg = 23.1;
+  else if (run == 3322)  thetadeg = 23.6;
+  else if (run == 3323)  thetadeg = 24.1;
+  else if (run == 3324)  thetadeg = 24.6;
+  else if (run == 3325)  thetadeg = 24.9;
+  else if (run == 3326)  thetadeg = 25.5;
+  else if (run == 3327)  thetadeg = 26.0;
+  else if (run == 3328)  thetadeg = 26.0;
+  else if (run == 3329)  thetadeg = 26.6;
+
+  else if (run == 3330)  thetadeg = 26.6;
+  else if (run == 3331)  thetadeg = 27.1;
+  else if (run == 3332)  thetadeg = 27.7;
+  else if (run == 3333)  thetadeg = 28.2;
+  else if (run == 3334)  thetadeg = 28.5;
+
+  else if (run == 3340)  thetadeg = 10.5;
+  else if (run == 3341)  thetadeg = 10.3;
+  else if (run == 3342)  thetadeg =  9.6;
+  else if (run == 3343)  thetadeg =  9.2;
+  else if (run == 3344)  thetadeg =  8.9;
+  else if (run == 3345)  thetadeg =  8.6;
+  else if (run == 3346)  thetadeg =  8.3;
+  else if (run == 3347)  thetadeg =  8.0;
+  else if (run == 3348)  thetadeg =  7.7;
+  else if (run == 3349)  thetadeg =  7.5;
+
+  else if (run == 3350)  thetadeg =  7.2;
+  else if (run == 3351)  thetadeg =  7.0;
+  else if (run == 3352)  thetadeg =  6.8;
+  else if (run == 3353)  thetadeg =  6.7;
+  else if (run == 3354)  thetadeg =  6.6;
+  else if (run == 3355)  thetadeg =  6.5;
+  else if (run == 3356)  thetadeg =  6.4;
+  else if (run == 3357)  thetadeg =  6.4;
+  else if (run == 3358)  thetadeg =  6.4;
+  else if (run == 3359)  thetadeg =  6.5;
+
+  else if (run == 3360)  thetadeg =  6.6;
+
+  else if (run == 3362)  thetadeg =  6.7;
+  else if (run == 3363)  thetadeg =  6.8;
+  else if (run == 3364)  thetadeg =  7.0;
+  else if (run == 3365)  thetadeg =  7.2;
+  else if (run == 3366)  thetadeg =  7.5;
+  else if (run == 3367)  thetadeg =  7.7;
+  else if (run == 3368)  thetadeg =  8.0;
+  else if (run == 3369)  thetadeg =  8.3;
+
+  else if (run == 3370)  thetadeg =  8.6;
+  else if (run == 3371)  thetadeg =  9.0;
+  else if (run == 3372)  thetadeg =  9.3;
+  else if (run == 3373)  thetadeg =  9.6;
+  else if (run == 3374)  thetadeg = 10.0;
+  else if (run == 3375)  thetadeg = 10.4;
+  else if (run == 3376)  thetadeg = 10.7;
+  else if (run == 3377)  thetadeg = 11.1;
+  else if (run == 3378)  thetadeg = 11.5;
+  else if (run == 3379)  thetadeg = 11.9;
+
+  else if (run == 3380)  thetadeg = 12.3;
+  else if (run == 3381)  thetadeg = 12.7;
+  else if (run == 3382)  thetadeg = 13.1;
+  else if (run == 3383)  thetadeg = 13.5;
+  else if (run == 3384)  thetadeg = 13.9;
+  else if (run == 3385)  thetadeg = 14.3;
+  else if (run == 3386)  thetadeg = 14.7;
+  else if (run == 3387)  thetadeg = 15.2;
+  else if (run == 3388)  thetadeg = 15.6;
+  else if (run == 3389)  thetadeg = 16.0;
+
+  else if (run == 3390)  thetadeg = 16.4;
+  else if (run == 3391)  thetadeg = 16.7;
+  else if (run == 3392)  thetadeg = 17.9;
+  else if (run == 3393)  thetadeg = 18.3;
+  else if (run == 3394)  thetadeg = 18.7;
+  else if (run == 3395)  thetadeg = 19.2;
+  else if (run == 3396)  thetadeg = 19.6;
+  else if (run == 3397)  thetadeg = 20.0;
+  else if (run == 3398)  thetadeg = 20.5;
+  else if (run == 3399)  thetadeg = 20.9;
+
+  else if (run == 3400)  thetadeg = 21.4;
+  else if (run == 3401)  thetadeg = 21.8;
+  else if (run == 3402)  thetadeg = 22.1;
+  else if (run == 3403)  thetadeg = 22.6;
+  else if (run == 3404)  thetadeg = 23.1;
+  else if (run == 3405)  thetadeg = 23.4;
+  else if (run == 3406)  thetadeg = 23.9;
+  else if (run == 3407)  thetadeg = 24.3;
+  else if (run == 3408)  thetadeg = 24.7;
+  else if (run == 3409)  thetadeg = 26.9;
+
+  else if (run == 3410)  thetadeg = 27.3;
+  else if (run == 3411)  thetadeg = 27.7;
+  else if (run == 3412)  thetadeg = 28.2;
+  else if (run == 3413)  thetadeg = 28.7;
+  else if (run == 3414)  thetadeg = 29.1;
+  else if (run == 3415)  thetadeg = 29.2;
+  else if (run == 3416)  thetadeg = 30.0;
+  else if (run == 3417)  thetadeg = 18.5;  // Off Crab1
+  else if (run == 3418)  thetadeg = 18.4;
+  else if (run == 3419)  thetadeg = 17.5;
+
+  else if (run == 3420)  thetadeg = 17.2;
+  else if (run == 3421)  thetadeg = 16.8;
+  else if (run == 3422)  thetadeg = 16.4;
+  else if (run == 3423)  thetadeg = 16.0;
+  else if (run == 3424)  thetadeg = 15.6;
+  else if (run == 3425)  thetadeg = 15.3;
+  else if (run == 3426)  thetadeg = 14.9;
+  else if (run == 3427)  thetadeg = 14.5;
+  else if (run == 3428)  thetadeg = 14.1;
+  else if (run == 3429)  thetadeg = 13.7;
+
+  else if (run == 3430)  thetadeg = 13.4;
+  else if (run == 3431)  thetadeg = 13.0;
+  else if (run == 3432)  thetadeg = 12.7;
+  else if (run == 3433)  thetadeg = 12.3;
+  else if (run == 3434)  thetadeg = 12.0;
+  else if (run == 3435)  thetadeg = 12.0;
+  else if (run == 3436)  thetadeg = 11.6;
+  else if (run == 3437)  thetadeg = 11.3;
+  else if (run == 3438)  thetadeg = 11.0;
+  else if (run == 3439)  thetadeg = 10.7;
+
+  else if (run == 3440)  thetadeg = 10.4;
+  else if (run == 3441)  thetadeg = 10.1;
+  else if (run == 3442)  thetadeg =  9.9;
+  else if (run == 3443)  thetadeg =  9.8;
+  else if (run == 3444)  thetadeg = 30.8;  // Mkn 421
+  else if (run == 3445)  thetadeg = 30.6;
+  else if (run == 3446)  thetadeg = 29.7;
+  else if (run == 3447)  thetadeg = 29.3;
+  else if (run == 3448)  thetadeg = 28.9;
+  else if (run == 3449)  thetadeg = 28.5;
+
+  else if (run == 3450)  thetadeg = 28.1;
+  else if (run == 3451)  thetadeg = 27.7;
+  else if (run == 3452)  thetadeg = 27.3;
+  else if (run == 3453)  thetadeg = 26.9;
+  else if (run == 3454)  thetadeg = 26.5;
+  else if (run == 3455)  thetadeg = 26.1;
+  else if (run == 3456)  thetadeg = 25.7;
+  else if (run == 3457)  thetadeg = 25.3;
+  else if (run == 3458)  thetadeg = 24.9;
+  else if (run == 3459)  thetadeg = 24.5;
+
+  else if (run == 3460)  thetadeg = 24.1;
+
+  else if (run == 3463)  thetadeg = 23.2;
+  else if (run == 3464)  thetadeg = 22.8;
+  else if (run == 3465)  thetadeg = 22.4;
+  else if (run == 3466)  thetadeg = 22.0;
+  else if (run == 3467)  thetadeg = 21.6;
+  else if (run == 3468)  thetadeg = 21.2;
+  else if (run == 3469)  thetadeg = 20.8;
+
+  else if (run == 3470)  thetadeg = 20.4;
+  else if (run == 3471)  thetadeg = 20.1;
+  else if (run == 3472)  thetadeg = 19.7;
+  else if (run == 3473)  thetadeg = 19.3;
+  else if (run == 3474)  thetadeg = 18.9;
+  else if (run == 3475)  thetadeg = 18.5;
+  else if (run == 3476)  thetadeg = 18.2;
+  else if (run == 3477)  thetadeg = 18.1;
+  else if (run == 3478)  thetadeg = 17.7;
+
+
+  else if (run == 3480)  thetadeg = 17.5;
+  else if (run == 3481)  thetadeg = 17.1;
+  else if (run == 3482)  thetadeg = 16.7;
+  else if (run == 3483)  thetadeg = 16.3;
+  else if (run == 3484)  thetadeg = 16.0;
+  else if (run == 3485)  thetadeg = 15.6;
+  else if (run == 3486)  thetadeg = 15.3;
+  else if (run == 3487)  thetadeg = 15.0;
+  else if (run == 3488)  thetadeg = 14.8;
+  else if (run == 3489)  thetadeg = 14.8;
+  
+  else
+  {
+    *fLog << warn << "MPedestalWorkaround : no zenith angle for run number = "
+          << run << endl;
+    thetadeg = 90.0;
+  }
+
+  thetarad = thetadeg / kRad2Deg;
+  */
+
+  thetadeg = 10.0;
+  thetarad = thetadeg / kRad2Deg;
+  fMcEvt->SetTelescopeTheta(thetarad);
+  
+  return kTRUE;
+}
+
+Int_t MPedestalWorkaround::PostProcess()
+{
+    return kTRUE;
+}
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MPedestalWorkaround.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MPedestalWorkaround.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPedestalWorkaround.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MPedestalWorkaround
+#define MARS_MPedestalWorkaround
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPedestalWorkaround                                                     //
+//                                                                         //
+// Temporary copy of pedestal values and RMS into MPedestalCam from        //
+// MPedPhotCam in order to have the pedestal RMS in units of number of     // 
+// photons                                                                  //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MPedestalCam;
+class MPedPhotCam;
+class MGeomCam;
+class MParList;
+class MMcEvt;
+class MRawRunHeader;
+
+class MPedestalWorkaround : public MTask 
+{
+private:
+
+    MPedestalCam  *fPed;  
+    MPedPhotCam   *fPedPhot; 
+    MGeomCam      *fCam;  
+    MMcEvt        *fMcEvt;
+    MRawRunHeader *fRun;  
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MPedestalWorkaround(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MPedestalWorkaround, 0) // Task to copy pedestal RMS
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/manalysis/MPointingCorr.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MPointingCorr.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPointingCorr.cc	(revision 9772)
@@ -0,0 +1,134 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  03/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MPointingCorr                                                          //
+//                                                                         //
+//  This is a task to do the pointing correction                           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MPointingCorr.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+#include "MSrcPosCam.h"
+#include "MGeomCam.h"
+#include "MParameters.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MPointingCorr);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MPointingCorr::MPointingCorr(const char *name, const char *title,
+                             const char *srcname)
+{
+    fName  = name  ? name  : "MPointingCorr";
+    fTitle = title ? title : "Task to do the pointing correction";
+
+    fSrcName = srcname;
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+// 
+// 
+//
+Int_t MPointingCorr::PreProcess(MParList *pList)
+{
+    MGeomCam *geom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << GetDescriptor() << ": No Camera Geometry available. Using mm-scale for histograms." << endl;
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+    }
+
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << dbginf << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHourAngle = (MParameterD*)pList->FindObject("HourAngle", "MParameterD");
+    if (!fHourAngle)
+    {
+        *fLog << dbginf << "HourAngle not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    fSrcPos = (MSrcPosCam*)pList->FindObject(fSrcName, "MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << dbginf << fSrcName << " [MSrcPosCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the pointing correction
+//
+// the parametrization is for Mkn421 2001 data (Daniel Kranich)
+// 
+Int_t MPointingCorr::Process()
+{
+   // fhourangle is the hour angle [degrees]
+   // (cx, cy) is the source position in the camera [mm]
+   //
+   Float_t fhourangle = fHourAngle->GetVal();
+
+   //*fLog << "MPointingCorr::Process; fhourangle = " 
+   //      << fhourangle << endl;
+
+   Float_t cx = -0.05132 - 0.001064 * fhourangle 
+                         - 3.530e-6 * fhourangle * fhourangle;
+   cx /= fMm2Deg;
+
+   Float_t cy = -0.04883 - 0.0003175* fhourangle
+                         - 2.165e-5 * fhourangle * fhourangle;
+   cy /= fMm2Deg;
+
+   fSrcPos->SetXY(cx, cy);
+
+   //*fLog << "MPointingCorr::Process; fhourangle, cx, cy, fMm2Deg = "
+   //      << fhourangle << ",  " << cx << ",  " << cy << ",  " 
+   //      << fMm2Deg << endl;
+
+   return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysis/MPointingCorr.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MPointingCorr.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MPointingCorr.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifndef MARS_MPointingCorr
+#define MARS_MPointingCorr
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPointingCorr                                                           //
+//                                                                         //
+// Task to do the pointing correction                                      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcEvt;
+class MSrcPosCam;
+class MParameterD;
+
+class MPointingCorr : public MTask
+{
+private:
+    MMcEvt       *fMcEvt;       
+    MSrcPosCam   *fSrcPos;
+    TString       fSrcName;
+    MParameterD  *fHourAngle;
+
+    Float_t       fMm2Deg;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MPointingCorr(const char *name=NULL, const char *title=NULL,
+                  const char *srcname="MSrcPosCam");
+
+    ClassDef(MPointingCorr, 0)   // Task to do the pointing correction
+};
+
+#endif
Index: /tags/Mars-V0.9/manalysis/MSigmabar.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MSigmabar.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSigmabar.cc	(revision 9772)
@@ -0,0 +1,265 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner,   10/2002 <mailto:magicsoft@rwagner.de>
+!   Author(s): Wolfgang Wittek, 01/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz,    04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MSigmabar                                                               //
+//                                                                         //
+// This is the storage container to hold information about                 //
+// "average" pedestal RMS                                                  //
+//                                                                         //
+// The "average" pedestal RMS is calculated as                             //
+//     <pedRMS> = sqrt( sum_i( (pedRMS_i)^2/area_i ) / no.of pixels )      //
+//                                                                         //
+//     which is the sqrt of the average (pedRMS^2 per area)                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MSigmabar.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+ClassImp(MSigmabar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MSigmabar::MSigmabar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MSigmabar";
+    fTitle = title ? title : "Storage container for Sigmabar";
+}
+
+// --------------------------------------------------------------------------
+//
+MSigmabar::~MSigmabar()
+{
+  // do nothing special.
+}
+
+void MSigmabar::Reset()
+{
+    fSigmabar      = -1;
+    fInnerPixels   = -1;
+    fOuterPixels   = -1;
+    fSigmabarInner = -1;
+    fSigmabarOuter = -1;
+
+    memset(fSigmabarSector, 0, sizeof(fSigmabarSector));
+    memset(fSigmabarInnerSector, 0, sizeof(fSigmabarInnerSector));
+    memset(fSigmabarOuterSector, 0, sizeof(fSigmabarOuterSector));
+}
+
+// --------------------------------------------------------------------------
+//
+// Actual calculation of sigmabar. This is done for each of the six sectors
+// separately due to their possibly different HV behavior. Also inner and
+// outer pixels are treated separately.
+//
+// Preliminary! Works for CT1 test, for real MAGIC crosschecks still have
+// to be done. Also implementation details will be updated, like 
+// determination of sector to which a respective pixel belongs
+//
+Float_t MSigmabar::Calc(const MGeomCam &geom, const MPedPhotCam &ped, 
+                        const MCerPhotEvt &evt)
+{
+    Int_t innerPixels[6];
+    Int_t outerPixels[6];
+    Float_t innerSum[6];
+    Float_t outerSum[6];
+
+    memset(innerPixels, 0, sizeof(innerPixels));
+    memset(outerPixels, 0, sizeof(outerPixels));
+    memset(innerSum, 0, sizeof(innerSum));
+    memset(outerSum, 0, sizeof(outerSum));
+
+    //
+    // sum up sigma^2/area for each sector, 
+    // separately for inner and outer region;
+    //
+    // consider all pixels with Cherenkov photon information
+    // and require "Used"
+    //
+
+    const UInt_t npix = evt.GetNumPixels();
+
+    //*fLog << "MSigmabar : npix = " << npix << endl;
+
+    for (UInt_t i=0; i<npix; i++)
+    {
+        MCerPhotPix &cerpix = evt.operator[](i);
+        if (!cerpix.IsPixelUsed())
+            continue;
+
+	/*
+         if ( cerpix.GetNumPhotons() == 0 )
+         {
+         *fLog << "MSigmabar::Calc(); no.of photons is 0 for used pixel"
+         << endl;
+         continue;
+         }
+	*/
+
+        const Int_t idx = cerpix.GetPixId();
+        if (idx == 0)
+	{
+          //*fLog << "MSigmabar : id = 0;  pixel '0' is used, ignore it" 
+	  //      << endl;
+          continue;
+        }
+
+        // ratio is the area of pixel 0
+        //          divided by the area of the current pixel
+        const Double_t ratio = geom.GetPixRatio(idx);
+
+        //*fLog << "pixel id, ratio = " << idx << ",  " << ratio << endl;
+
+        const MGeomPix &gpix = geom[idx];
+
+        // This is wrong : rounding has to be done on positive values
+        //Int_t sector = (Int_t)(atan2(gpix.GetY(),gpix.GetX())*6 
+        //               / (TMath::Pi()*2));
+        //if (sector<0)
+        //    sector+=6;
+
+        Float_t sectorf = atan2(gpix.GetY(),gpix.GetX()) * 6.0 
+                          / (TMath::Pi()*2);
+        if (sectorf < 0.0)
+          sectorf += 6.0;
+        Int_t sector = (Int_t)sectorf;
+
+        // count only those pixels which have a sigma != 0.0
+        const Float_t sigma = ped[idx].GetRms();
+
+        if ( sigma <= 0 )
+            continue;
+
+        //if (area < 1.5)
+        if (ratio > 0.5)
+        {
+            innerPixels[sector]++;
+            innerSum[sector]+= sigma*sigma * ratio;
+        }
+        else
+        {
+            outerPixels[sector]++;
+            outerSum[sector]+= sigma*sigma * ratio;
+        }
+    }
+
+    fInnerPixels   = 0;
+    fOuterPixels   = 0;
+    Double_t fSumInner = 0;
+    Double_t fSumOuter = 0;
+    for (UInt_t i=0; i<6; i++)
+    {
+        fSumInner      += innerSum[i];
+        fInnerPixels   += innerPixels[i];
+        fSumOuter      += outerSum[i];
+        fOuterPixels   += outerPixels[i];
+    }
+
+    if (fInnerPixels > 0) fSigmabarInner = sqrt(fSumInner / fInnerPixels);
+    if (fOuterPixels > 0) fSigmabarOuter = sqrt(fSumOuter / fOuterPixels);
+
+    //
+    // this is the sqrt of the average sigma^2/area 
+    //
+    fSigmabar = (fInnerPixels+fOuterPixels)<=0 ? 0:
+                sqrt( (fSumInner+fSumOuter)/(fInnerPixels+fOuterPixels) );
+
+    for (UInt_t i=0; i<6; i++)
+    {
+        const Double_t ip  = innerPixels[i];
+        const Double_t op  = outerPixels[i];
+        const Double_t iss = innerSum[i];
+        const Double_t oss = outerSum[i];
+
+        const Double_t sum = ip + op;
+        fSigmabarInnerSector[i] = ip <=0 ? 0 :        sqrt(iss/ip);
+        fSigmabarOuterSector[i] = op <=0 ? 0 :        sqrt(oss/op);
+        fSigmabarSector[i]      = sum<=0 ? 0 : sqrt((iss+oss)/sum);
+    }
+
+    //TString opt = "";
+    //Print(opt);
+
+  return fSigmabarInner;
+}
+
+// --------------------------------------------------------------------------
+//
+void MSigmabar::Print(Option_t *) const
+{
+  *fLog << all << endl;
+  *fLog << "Total number of inner pixels is " << fInnerPixels << endl;
+  *fLog << "Total number of outer pixels is " << fOuterPixels << endl;
+  *fLog << endl;
+
+  *fLog << "Sigmabar     Overall : " << fSigmabar << "   ";
+  *fLog << " Sectors: ";
+  for (Int_t i=0;i<6;i++)
+      *fLog << fSigmabarSector[i] << ", ";
+  *fLog << endl;
+
+
+  *fLog << "Sigmabar     Inner   : " << fSigmabarInner << "   ";
+  *fLog << " Sectors: ";
+  for (Int_t i=0;i<6;i++)
+      *fLog << fSigmabarInnerSector[i] << ", ";
+  *fLog << endl;
+
+
+  *fLog << "Sigmabar     Outer   : " << fSigmabarOuter << "   ";
+  *fLog << " Sectors: ";
+  for (Int_t i=0;i<6;i++)
+      *fLog << fSigmabarOuterSector[i] << ", ";
+  *fLog << endl;
+
+}
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MSigmabar.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MSigmabar.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSigmabar.h	(revision 9772)
@@ -0,0 +1,56 @@
+#ifndef MARS_MSigmabar
+#define MARS_MSigmabar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGeomCam;
+class MParList;
+class MCerPhotEvt;
+class MPedPhotCam;
+
+class MSigmabar : public MParContainer
+{
+private:
+    Float_t fSigmabar;          // Sigmabar ( sqrt(average pedestalRMS^2) ) 
+    Float_t fSigmabarInner;     // --only for inner pixels
+    Float_t fSigmabarOuter;     // --only for outer pixels  
+
+    Float_t fSigmabarSector[6]; // --for the 6 sectors of the camera
+    Float_t fSigmabarInnerSector[6];
+    Float_t fSigmabarOuterSector[6];
+
+    Int_t  fInnerPixels;       // Overall number of inner pixels
+    Int_t  fOuterPixels;       // Overall number of outer pixels
+
+public:
+    MSigmabar(const char *name=NULL, const char *title=NULL);
+    ~MSigmabar();
+    
+    void Reset();
+
+    void Print(Option_t *) const;
+ 
+    Float_t GetSigmabar() const       { return fSigmabar;       }
+    Float_t GetSigmabarInner() const  { return fSigmabarInner;  }
+    Float_t GetSigmabarOuter() const  { return fSigmabarOuter;  }
+    Float_t GetSigmabarSector(const Int_t sector) const 
+                              { return fSigmabarSector[sector]; } 
+  
+    //   void SetSigmabar(Float_t f, Float_t i, Float_t o) 
+    //      { fSigmabar = f; fSigmabarInner = i; fSigmabarOuter = o; }
+    //    void SetSigmabarInner(Float_t f) { fSigmabarInner = f; }
+    //    void SetSigmabarOuter(Float_t f) { fSigmabarOuter = f; }   
+
+    Float_t Calc(const MGeomCam &geom, const MPedPhotCam &ped, const MCerPhotEvt &evt);
+      
+    ClassDef(MSigmabar, 1)  // Storage Container for Sigmabar
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MSigmabarCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MSigmabarCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSigmabarCalc.cc	(revision 9772)
@@ -0,0 +1,186 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner, 10/2002 <rwagner@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 4/2003 <tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSigmabarCalc
+//
+//  This task calculates Sigmabar using the MSigmabar container and stores
+//  its extremal values together with the corresponding Theta values       
+//  in MSigmabarParam. For the time being, Theta is taken from a Monte
+//  Carlo container. This is preliminary and to be changed ASAP.
+//
+//  Input Containers:
+//   MGeomCam
+//   MPedPhotCam
+//   MRawRunHeader
+//   MPointingPos
+//   MCerPhotEvt
+//
+//  Output Containers:
+//   MSigmabar
+//   MSigmabarParam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSigmabarCalc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MPedPhotCam.h"
+
+#include "MSigmabar.h"
+#include "MSigmabarParam.h"
+
+#include "MPointingPos.h"
+
+ClassImp(MSigmabarCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MSigmabarCalc::MSigmabarCalc(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MSigmabarCalc";
+    fTitle = title ? title : "Task to calculate Sigmabar";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+//  check if necessary containers exists in the Parameter list already.
+//  if not create one and add them to the list
+//
+Int_t MSigmabarCalc::PreProcess(MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed = (MPedPhotCam*)pList->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+    if (!fPed)
+    {
+        *fLog << err << "MPedPhotCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // This is needed for determining min/max Theta
+    fPointPos = (MPointingPos*)pList->FindObject(AddSerialNumber("MPointingPos"));
+    if (!fPointPos)
+    {
+        *fLog << warn << "MPointingPos not found... aborting." << endl;
+        fThetaMin =  0;
+        fThetaMax = 90;
+    }
+
+    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fEvt)
+      {
+	*fLog << err << "MCerPhotEvt not found... aborting." << endl;
+	return kFALSE;
+      }
+
+    fSig = (MSigmabar*)pList->FindCreateObj(AddSerialNumber("MSigmabar"));
+    if (!fSig)
+        return kFALSE;
+
+    // FIXME: This might have to change in a
+    //        'more-than-one-telescope-environment'
+    fSigParam = (MSigmabarParam*)pList->FindCreateObj(AddSerialNumber("MSigmabarParam"));
+    if (!fSigParam)
+        return kFALSE;
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculating a new Sigmabar is not necessary on event basis as long as
+// we deal with CT1 data. Therefore, the real calculation is done in
+// the ReInit function. Process just takes care for finding the extremal
+// values. Preliminary.
+//
+Int_t MSigmabarCalc::Process()
+{
+    const Double_t rc = fSig->Calc(*fCam, *fPed, *fEvt);
+
+    if (rc>fSigmabarMax) fSigmabarMax=rc;
+    if (rc<fSigmabarMin) fSigmabarMin=rc;
+
+    if (!fPointPos)
+        return kTRUE;
+
+    const Double_t theta = fPointPos->GetZd();
+
+    if (theta>fThetaMax) fThetaMax=theta;
+    if (theta<fThetaMin) fThetaMin=theta;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates Sigmabar (for CT1 only needed at Reinit, i.e. when reading
+// a new file)
+//
+Bool_t MSigmabarCalc::ReInit(MParList *pList)
+{
+    fSigParam->SetParams(1, fSigmabarMin, fSigmabarMax, fThetaMin, fThetaMax);
+    fSigParam->SetRunNumber(fRun->GetRunNumber());
+
+    Reset();
+
+    return kTRUE;
+}
+
+void MSigmabarCalc::Reset()
+{
+    if (!fPointPos)
+        return;
+
+    fThetaMin    = FLT_MAX;
+    fThetaMax    = 0;
+    fSigmabarMin = FLT_MAX;
+    fSigmabarMax = 0;
+}
+
Index: /tags/Mars-V0.9/manalysis/MSigmabarCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MSigmabarCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSigmabarCalc.h	(revision 9772)
@@ -0,0 +1,68 @@
+#ifndef MARS_MSigmabarCalc
+#define MARS_MSigmabarCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+#ifndef MARS_MPointingPos
+#include "MPointingPos.h"
+#endif
+
+#ifndef MARS_MPedPhotCam
+#include "MPedPhotCam.h"
+#endif
+
+#ifndef MARS_MSigmabar
+#include "MSigmabar.h"
+#endif
+
+#ifndef MARS_MSigmabarParam
+#include "MSigmabarParam.h"
+#endif
+
+#ifndef MARS_MRawRunHeader
+#include "MRawRunHeader.h"
+#endif
+
+class MSigmabarCalc : public MTask
+{
+private:
+    MPointingPos   *fPointPos;
+    MCerPhotEvt    *fEvt;
+    MGeomCam       *fCam;
+    MPedPhotCam   *fPed;
+    MRawRunHeader  *fRun;
+    MSigmabar      *fSig;
+    MSigmabarParam *fSigParam;
+
+    Double_t fSigmabarMin; // Parametrization
+    Double_t fSigmabarMax;
+    Double_t fThetaMin;
+    Double_t fThetaMax;
+
+    TString  fNamePedPhotCam; // name of the 'MPedPhotCam' container
+
+    void Reset();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MSigmabarCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetNamePedPhotCam(const char *name)  { fNamePedPhotCam = name; }
+
+    ClassDef(MSigmabarCalc, 0) // task for calculating sigmabar
+}; 
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/manalysis/MSigmabarParam.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MSigmabarParam.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSigmabarParam.cc	(revision 9772)
@@ -0,0 +1,82 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner  10/2002 <mailto:magicsoft@rwagner.de>
+!
+!   Copyright: MAGIC Software Development, 2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MSigmabarParam                                                          //
+//                                                                         //
+// Storage Container for parameters characterizing a distribution of       //
+// events in the Sigmabar-Theta plane                                      //
+//                                                                         //
+// For CT1 tests, we just store Sigmabar_max, Sigmabar_min, Theta_max,     //
+// Theta_min. Later MJD and perhaps more than two points on the            //
+// distribution might follow.                                              //
+//                                                                         //
+//  This implementation is still PRELIMINARY and requires some workarounds //
+//  put in SPECIFICALLY FOR THE CT1 TESTS, since a database to access is   //
+//  missing. It is not the FINAL MAGIC VERSION.                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MSigmabarParam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSigmabarParam);
+
+using namespace std;
+
+MSigmabarParam::MSigmabarParam(const char *name, const char *title) : fSigmabarMin(0), fSigmabarMax(0), fMjdMin(0), fMjdMax(0), fThetaMin(0), fThetaMax(0), fRunNumber(0)
+{
+    fName  = name  ? name  : "MSigmabarParam";
+    fTitle = title ? title : "Storage container for characterizing a distribution of events in the Sigmabar-Theta plane";      
+}
+
+MSigmabarParam::~MSigmabarParam()
+{
+  // nothing special yet
+}
+
+void MSigmabarParam::SetRunNumber(Int_t r)
+{
+  fRunNumber = r;
+}
+
+void MSigmabarParam::SetParams(Int_t r, Double_t si, Double_t sx, Double_t ti, Double_t tx, Double_t mi, Double_t mx)
+{
+  fSigmabarMin = si;
+  fSigmabarMax = sx;
+  fThetaMin = ti;
+  fThetaMax = tx;
+  fMjdMin = mi;
+  fMjdMax = mx;
+  //fRunNumber = r;
+}
+
+void MSigmabarParam::Print(Option_t *) const
+{
+  *fLog << endl << "Run " << fRunNumber << " | " 
+       << "Sigmabar Min, Max: " << fSigmabarMin << " " << fSigmabarMax 
+       << "| Theta Min, Max: " << fThetaMin << " " << fThetaMax << endl;
+}
Index: /tags/Mars-V0.9/manalysis/MSigmabarParam.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MSigmabarParam.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSigmabarParam.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MSigmabarParam
+#define MARS_MSigmabarParam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MSigmabarParam : public MParContainer
+{
+private:
+  Double_t fSigmabarMin;
+  Double_t fSigmabarMax;
+  Double_t fMjdMin;
+  Double_t fMjdMax;
+  Double_t fThetaMin;
+  Double_t fThetaMax;
+  Int_t    fRunNumber;
+
+public:
+  
+  MSigmabarParam(const char *name=NULL, const char *title=NULL);
+  ~MSigmabarParam();
+  
+  //  void Print(Option_t *) const;
+
+  void SetRunNumber(Int_t r);
+  
+  void SetParams(Int_t r, Double_t si, Double_t sx, Double_t ti, Double_t tx, Double_t mi=0, Double_t mx=0);
+
+  Double_t GetSigmabarMin() const { return fSigmabarMin; }
+  Double_t GetSigmabarMax() const { return fSigmabarMax; }
+  Double_t GetThetaMin() const { return fThetaMin; }
+  Double_t GetThetaMax() const { return fThetaMax; }
+
+  void Print(Option_t *o="") const;
+      
+  ClassDef(MSigmabarParam, 1)  // Storage container for characterizing a distribution of events in the Sigmabar-Theta plane
+
+};
+
+#endif
+
Index: /tags/Mars-V0.9/manalysis/MSourcePosfromStarPos.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MSourcePosfromStarPos.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSourcePosfromStarPos.cc	(revision 9772)
@@ -0,0 +1,888 @@
+
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Wolfgang Wittek 02/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSourcePosfromStarPos
+//
+//  This is a task which
+//  - calculates the position of the source in the camera
+//    from the position of a known star in the camera
+//  - and puts the source position into the container MSrcPosCam
+//
+//  Input :
+//   ASCII file containing for each run 
+//   - the run number
+//   - the direction (theta, phi) the telescope is pointing to in [deg]
+//   - the position  (xStar, yStar)   of a known star in the camera in [mm]
+//   - the error     (dxStar, dyStar) of this position in [mm]
+//
+//  Output Containers :
+//   MSrcPosCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <TList.h>
+#include <TSystem.h>
+#include <TMatrixD.h>
+
+#include <fstream>
+
+#include "MSourcePosfromStarPos.h"
+
+#include "MParList.h"
+#include "MRawRunHeader.h"
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MPointingPos.h"
+#include "MMcEvt.hxx"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MObservatory.h"
+
+ClassImp(MSourcePosfromStarPos);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MSourcePosfromStarPos::MSourcePosfromStarPos(
+                                         const char *name, const char *title)
+  : fIn(NULL)
+{
+    fName  = name  ? name  : "MSourcePosfromStarPos";
+    fTitle = title ? title : "Calculate source position from star position";
+
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    fRuns  = 0;
+    fSize  = 100;
+
+    fRunNr.Set(fSize);
+
+    fThetaTel.Set(fSize);
+    fPhiTel.Set(fSize);
+    fdThetaTel.Set(fSize);
+    fdPhiTel.Set(fSize);
+
+    Int_t fRows = 1;
+    fDecStar.Set(fRows);
+    fRaStar.Set(fRows);
+    fxStar.ResizeTo(fRows,fSize);
+    fyStar.ResizeTo(fRows,fSize);
+    fdxStar.ResizeTo(fRows,fSize);
+    fdyStar.ResizeTo(fRows,fSize);
+
+    fStars     = 0;
+    fStarsRead = 0;
+    fDecSource = 0.0;
+    fRaSource  = 0.0;
+
+    // these are the default values when starting the excution;
+    // later these locations contain the values of the last event
+    fxSourceold  =  25.0;
+    fySourceold  = -40.0;
+    fThetaradold =  25.0/kRad2Deg;
+    fPhiradold   = 180.0/kRad2Deg;
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filename list and the input stream if one exists.
+//
+MSourcePosfromStarPos::~MSourcePosfromStarPos()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the sky coordinates of the source and of the star
+//
+// Input :
+// declination in units of     (Deg,  Min, Sec)
+// right ascension in units of (Hour, Min, Sec)
+//
+
+void MSourcePosfromStarPos::SetSourceAndStarPosition(
+	 TString  nameSource,
+	 Double_t decSourceDeg, Double_t decSourceMin, Double_t decSourceSec, 
+         Double_t raSourceHour, Double_t raSourceMin,  Double_t raSourceSec,
+	 TString nameStar,
+	 Double_t decStarDeg,   Double_t decStarMin,   Double_t decStarSec, 
+         Double_t raStarHour,   Double_t raStarMin,    Double_t raStarSec  )
+{
+  *fLog << "MSourcePosfromStarPos::SetSourceAndStarPosition :" << endl;
+  *fLog << "       Source (dec) : "  << nameSource << "   " << decSourceDeg << ":" 
+        << decSourceMin << ":" << decSourceSec << endl;
+  *fLog << "       Source (ra)  : "  << nameSource  << "   " << raSourceHour << ":" 
+        << raSourceMin  << ":" << raSourceSec << endl;
+
+  *fLog << "       Star  (dec) : "  << nameStar   << "   " << decStarDeg << ":" 
+        << decStarMin << ":"   << decStarSec << endl;
+  *fLog << "       Star  (ra)  : "  << nameStar   << "   " << raStarHour << ":" 
+        << raStarMin << ":"    << raStarSec  << endl;
+
+  // convert into radians
+  fDecSource = (decSourceDeg + decSourceMin/60.0 + decSourceSec/3600.0)
+               / kRad2Deg;
+  fRaSource  = (raSourceHour + raSourceMin/60.0  + raSourceSec/3600.0)
+               * 360.0 / (24.0 * kRad2Deg);
+
+  fStars += 1;
+  fDecStar.Set(fStars);
+  fRaStar.Set(fStars);
+  fxStar.ResizeTo(fStars,fSize);
+  fyStar.ResizeTo(fStars,fSize);
+  fdxStar.ResizeTo(fStars,fSize);
+  fdyStar.ResizeTo(fStars,fSize);
+
+  fDecStar[fStars-1] = (decStarDeg + decStarMin/60.0 + decStarSec/3600.0)
+                       / kRad2Deg;
+  fRaStar[fStars-1]  = (raStarHour + raStarMin/60.0  + raStarSec/3600.0)
+                       * 360.0 / (24.0 * kRad2Deg);
+
+  *fLog << all << "MSourcePosfromStarPos::SetSourceAndStarPosition; fStars = "
+        << fStars << endl;
+  *fLog << all << "       fDecSource, fRaSource, fDecStar, fRaStar were set to : [radians]  "
+        << fDecSource << ",  " << fRaSource << ",  "
+        << fDecStar[fStars-1] << ",  " << fRaStar[fStars-1] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the sky coordinates of another star
+//
+// Input :
+// declination in units of     (Deg,  Min, Sec)
+// right ascension in units of (Hour, Min, Sec)
+//
+
+void MSourcePosfromStarPos::AddStar(
+	 TString nameStar,
+	 Double_t decStarDeg,   Double_t decStarMin,   Double_t decStarSec, 
+         Double_t raStarHour,   Double_t raStarMin,    Double_t raStarSec  )
+{
+  *fLog << "MSourcePosfromStarPos::AddStar :" << endl;
+  *fLog << "       Star (dec)  : "  << nameStar   << "   " << decStarDeg << ":" 
+        << decStarMin << ":"   << decStarSec << endl;
+  *fLog << "       Star (ra)   : "  << nameStar   << "   " << raStarHour << ":" 
+        << raStarMin << ":"    << raStarSec  << endl;
+
+  // convert into radians
+  fStars += 1;
+  fDecStar.Set(fStars);
+  fRaStar.Set(fStars);
+  fxStar.ResizeTo(fStars,fSize);
+  fyStar.ResizeTo(fStars,fSize);
+  fdxStar.ResizeTo(fStars,fSize);
+  fdyStar.ResizeTo(fStars,fSize);
+
+  fDecStar[fStars-1] = (decStarDeg + decStarMin/60.0 + decStarSec/3600.0)
+                       / kRad2Deg;
+  fRaStar[fStars-1]  = (raStarHour + raStarMin/60.0  + raStarSec/3600.0)
+                       * 360.0 / (24.0 * kRad2Deg);
+
+  *fLog << all << "MSourcePosfromStarPos::AddStar; fStars = " << fStars 
+        << endl;
+  *fLog << all << "       fDecStar, fRaStar were set to : [radians]  "
+        << fDecStar[fStars-1] << ",  " << fRaStar[fStars-1] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MSourcePosfromStarPos::PreProcess(MParList *pList)
+{
+    MGeomCam *geom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!geom)
+    {
+        *fLog << err << "MSourcePosfromStarPos : MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+    fMm2Deg = geom->GetConvMm2Deg();
+    // fDistCameraReflector is the distance of the camera from the reflector center in [mm]
+    fDistCameraReflector = kRad2Deg / fMm2Deg;   
+        *fLog << all << "MSourcePosfromStarPos::PreProcess; fMm2Deg, fDistCameraReflector = " 
+              << fMm2Deg << ",  " << fDistCameraReflector << endl;
+
+    fObservatory = (MObservatory*)pList->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+    {
+        *fLog << err << "MObservatory not found...  aborting" << endl;
+        return kFALSE;
+    }
+
+    fRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MSourcePosfromStarPos::PreProcess; MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+
+   fPointPos = (MPointingPos*)pList->FindCreateObj("MPointingPos");
+   if (!fPointPos)
+   {
+       *fLog << err << "MSourcePosfromStarPos::PreProcess; MPointingPos not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+   if (!fMcEvt)
+   {
+       *fLog << all << "MSourcePosfromStarPos::PreProcess; MMcEvt not found... continue." << endl;
+   }
+   else
+   {
+       *fLog << all << "MSourcePosfromStarPos::PreProcess; MMcEvt was found... continue." << endl;
+   }
+
+
+    fSrcPos = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << "MSourcePosfromStarPos::PreProcess; MSrcPosCam not found...  aborting" << endl;
+        return kFALSE;
+    }
+
+    //---------------------------------------------------------------------
+    // read all files and call ReadData() to read and store the information
+    //
+
+    *fLog << all << "---------------------------------" << endl;
+    while(1)
+    {
+      if (!OpenNextFile()) 
+      {
+        *fLog << "there is no more file to open" << endl;
+        break;
+      }
+
+      *fLog << "read data" << endl;
+
+      // read "fStarsRead" = no.of (x,y) pairs to be read
+      *fIn >> fStarsRead;
+
+      while (1)
+      {
+        if (fIn->eof())
+        {
+          *fLog << "eof encountered; open next file" << endl;
+
+          if (!OpenNextFile()) break;
+        }
+
+        // FIXME! Set InputStreamID
+      
+        ReadData();
+      }
+    }
+
+    *fLog << "all data were read" << endl;
+    FixSize();
+
+    if (fDecSource == 0.0  ||  fRaSource == 0.0  ||  fStars == 0) 
+    {
+      *fLog << warn << "MSourcePosfromStarPos::PreProcess; there are no sky coordinates defined for the source or from stars; fStars, fStarsRead = " 
+            << fStars << ",  " << fStarsRead 
+            << endl;
+    }
+    *fLog << all << "---------------------------------" << endl;
+
+    //-------------------------------------------------------------
+
+    return kTRUE;
+}
+
+//=========================================================================
+//
+// SourcefromStar
+//
+// this routine calculates the position of a source (for example Crab) in the camera
+// from the position of a star (for example ZetaTauri) in the camera. The latter 
+// position may have been determined by analysing the DC currents in the different
+// pixels.
+//
+// Input  : thetaTel, phiTel          the direction the telescope is pointing to,
+//                                    in local coordinates
+//          f                         the distance between camera and reflector
+//          decStar, raStar           the position of the star in sky coordinates
+//          decSource, raSource       the position of the source in sky coordinates
+//          xStar, yStar              the position of the star in the camera
+//          dxStar, dyStar            error of the position of the star in the camera
+//
+// Output : xSource, ySource       the calculated position of the source in the camera
+//          dxSource, dySource     error of the calculated position of the source in 
+//                                 the camera
+//
+// Useful formulas can be found in TDAS 00-11 and TDAS 01-05
+//
+
+void MSourcePosfromStarPos::SourcefromStar(Double_t &f,
+		    TArrayD  &decStar,     TArrayD  &raStar,
+		    Double_t &decSource,   Double_t &raSource,
+                    Double_t &thetaTel,    Double_t &phiTel,    
+		    TArrayD  &xStar,       TArrayD  &yStar,
+		    TArrayD  &dxStar,      TArrayD  &dyStar,
+		    Double_t &xSource,     Double_t &ySource,
+		    Double_t &dxSource,    Double_t &dySource)
+{
+  /*
+  *fLog << "MSourcePosfromStarPos::SourcefromStar :  printout in degrees" << endl;
+  *fLog << "       decStar, raStar = " << decStar[0]*kRad2Deg << ",  " 
+        << raStar[0]*kRad2Deg << endl;
+  *fLog << "       decSource, raSource = " << decSource*kRad2Deg << ",  " 
+        << raSource*kRad2Deg << endl;
+  *fLog << "       thetaTel, phiTel = " << thetaTel*kRad2Deg << ",  " 
+        << phiTel*kRad2Deg << endl;
+  *fLog << "       xStar, yStar = " << xStar[0]*fMm2Deg << ",  " 
+        << yStar[0]*fMm2Deg << endl;
+
+  *fLog << "MSourcePosfromStarPos::SourcefromStar :  printout in radians and mm" << endl;
+  *fLog << "       decStar, raStar = " << decStar[0] << ",  " 
+        << raStar[0] << endl;
+  *fLog << "       decSource, raSource = " << decSource << ",  " 
+        << raSource << endl;
+  *fLog << "       thetaTel, phiTel = " << thetaTel << ",  " 
+        << phiTel << endl;
+  *fLog << "       xStar, yStar = " << xStar[0] << ",  " 
+        << yStar[0] << endl;
+  */
+
+  // the units are assumed to be radians for theta, phi, dec and ra
+  //            and                   mm for f, x and y
+
+
+  // calculate rotation angle alpha of sky image in camera 
+  // (see TDAS 00-11, eqs. (18) and (20))
+  // a1 = cos(Lat), a3 = -sin(Lat), where Lat is the geographical latitude of La Palma
+  Double_t a1 =  0.876627;
+  Double_t a3 = -0.481171;
+
+  Double_t denom =  1./ sqrt( sin(thetaTel)*sin(phiTel) * sin(thetaTel)*sin(phiTel) +
+			      ( a1*cos(thetaTel)+a3*sin(thetaTel)*cos(phiTel) ) * 
+                              ( a1*cos(thetaTel)+a3*sin(thetaTel)*cos(phiTel) )   );
+  Double_t cosal = - (a3 * sin(thetaTel) + a1 * cos(thetaTel) * cos(phiTel)) * denom;
+  Double_t sinal =    a1 * sin(phiTel) * denom;
+
+  *fLog << "old thetaTel, phiTel, cosal, sinal = " << thetaTel << ",  "
+        << phiTel << ",  " << cosal << ",  " << sinal << endl;
+
+
+  fObservatory->RotationAngle(thetaTel, phiTel, sinal, cosal);
+
+  *fLog << "new thetaTel, phiTel, cosal, sinal = " << thetaTel << ",  "
+        << phiTel << ",  " << cosal << ",  " << sinal << endl;
+
+
+  // calculate coordinates of source in system B (see TDAS 00-11, eqs. (2))
+  // note that right ascension and hour angle go into opposite directions
+  Double_t xB0 =  cos(decSource) * cos(-raSource);
+  Double_t yB0 =  cos(decSource) * sin(-raSource);
+  Double_t zB0 = -sin(decSource);
+
+  //*fLog << "xB0, yB0, zB0 = " << xB0 << ",  " << yB0 << ",  "
+  //      << zB0 << endl;
+
+  //-----------------------------------------------------
+  // loop over stars
+  Double_t sumx  = 0.0;
+  Double_t sumy  = 0.0;
+  Double_t sumwx = 0.0;
+  Double_t sumwy = 0.0;
+
+  for (Int_t i=0; i<decStar.GetSize(); i++)
+  {
+    // calculate weights
+    Double_t weightx = 1.0 / (dxStar[i]*dxStar[i]);
+    Double_t weighty = 1.0 / (dyStar[i]*dyStar[i]);
+    sumwx += weightx;
+    sumwy += weighty;
+
+    //*fLog << "weightx, weighty = " << weightx << ",  " << weighty << endl;
+
+    // calculate coordinates of star in system B (see TDAS 00-11, eqs. (2))
+    // note that right ascension and hour angle go into opposite directions
+    Double_t xB  =  cos(decStar[i]) * cos(-raStar[i]);
+    Double_t yB  =  cos(decStar[i]) * sin(-raStar[i]);
+    Double_t zB  = -sin(decStar[i]);
+
+
+    //*fLog << "xB, yB, zB = " << xB << ",  " << yB << ",  "
+    //    << zB << endl;
+
+ 
+    // calculate coordinates of star in a system with the basis vectors e1, e2, e3
+    // where  e1 is in the direction (r0 x a)
+    //        e2 is in the direction (e1 x r0)
+    //   and  e3 is in the direction -r0;
+    // r0 is the direction to the source
+    // and a is the earth rotation axis (pointing to the celestial north pole)
+    // 
+    Double_t x = (-xB*yB0 + xB0*yB) / sqrt( xB0*xB0 + yB0*yB0 );
+    Double_t y = ( xB*xB0*zB0 + yB*yB0*zB0 - zB*(xB0*xB0 + yB0*yB0) ) 
+                                    / sqrt( xB0*xB0 + yB0*yB0 );
+    Double_t z = -(xB*xB0 + yB*yB0 + zB*zB0);
+
+    //*fLog << "x, y, z = " << x << ",  " << y << ",  "
+    //    << z << endl;
+
+
+    // calculate coordinates of star in camera
+    Double_t xtilde = -f/z * (cosal*x - sinal*y);
+    Double_t ytilde = -f/z * (sinal*x + cosal*y);
+
+    //*fLog << "i, xtilde, ytile = " << i << " : " << xtilde << ",  " 
+    //      << ytilde << endl;
+
+
+    // calculate coordinates of source in camera
+    // note : in real camera signs are inverted (therefore s = -1.0)
+    Double_t s = -1.0;
+
+    Double_t xs = xStar[i] - s * xtilde;
+    Double_t ys = yStar[i] - s * ytilde;
+
+    *fLog << "i, xs, ys = " << i << " : " << xs << ",  " 
+          << ys << endl;
+
+    sumx += xs * weightx;
+    sumy += ys * weighty;
+  }
+  //-----------------------------------------------------
+
+  xSource  = sumx / sumwx;
+  ySource  = sumy / sumwy;
+  dxSource = 1.0 / sqrt(sumwx);
+  dySource = 1.0 / sqrt(sumwy);
+    
+  /*
+  Int_t run = fRun->GetRunNumber();
+  *fLog << all << "MSourcePosfromStarPos::SourcefromStar; run, xSource, ySource = "
+        << run << " : "
+        << xSource << " +- " << dxSource << ",   " 
+        << ySource << " +- " << dySource << endl; 
+   */
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the source position and put it into MSrcPosCam
+//
+//
+Bool_t MSourcePosfromStarPos::ReInit(MParList *pList)
+{
+  Int_t run = fRun->GetRunNumber();
+  *fLog << all << "MSourcePosfromStarPos::ReInit; run = " << run << endl;
+
+  // temporary solution for MC
+  // copy (theta, phi) from MMcEvt into MPointingPos
+  if (fRun->GetRunType() > 255.5)
+  {
+    *fLog << all << "                     these are MC data" << endl;
+    Double_t thetarad = fMcEvt->GetTelescopeTheta();
+    Double_t phirad   = fMcEvt->GetTelescopePhi();
+    fPointPos->SetLocalPosition(thetarad*kRad2Deg, phirad*kRad2Deg);
+    fPointPos->SetReadyToSave();
+    return kTRUE;    
+  }
+
+  //-------------------------------------------------------------------
+  // search this run in the list 
+  for (Int_t i=0; i<fSize; i++)
+  {
+    if (run == fRunNr[i])
+    {
+      //-----------------------------------------
+      // put the zenith angle into MPointingPos
+
+      Double_t thetarad = fThetaTel[i];
+      Double_t phirad   = fPhiTel[i];
+
+      if (fabs(thetarad*kRad2Deg+1.0) < 0.001)
+        thetarad = fThetaradold;
+      else
+        fThetaradold = thetarad;
+      if (fabs(phirad*kRad2Deg+1.0) < 0.001)
+        phirad = fPhiradold;
+      else
+        fPhiradold = phirad;
+
+      fPointPos->SetLocalPosition(thetarad*kRad2Deg, phirad*kRad2Deg);
+      fPointPos->SetReadyToSave();
+
+      *fLog << all << "theta, phi = " << thetarad*kRad2Deg << ",  "
+            << phirad*kRad2Deg << " deg" << endl;
+       
+      //-----------------------------------------
+      // Get source position and put it into MSrcPosCam
+
+      
+      if (fStars > 0  && fStars == fStarsRead)
+      {
+        TArrayD xStar(fxStar.GetNrows());
+        TArrayD dxStar(fdxStar.GetNrows());
+        TArrayD yStar(fyStar.GetNrows());
+        TArrayD dyStar(fdyStar.GetNrows());
+        for (Int_t j=0; j<fxStar.GetNrows(); j++)
+        {
+          xStar[j]  = fxStar(j, i);
+          dxStar[j] = fdxStar(j, i);
+          yStar[j]  = fyStar(j, i);
+          dyStar[j] = fdyStar(j, i);
+        }
+
+        SourcefromStar( fDistCameraReflector,
+                        fDecStar, fRaStar, fDecSource, fRaSource,
+                        thetarad, phirad,   
+         	        xStar,          yStar,
+		        dxStar,         dyStar,
+		        fxSource,       fySource,
+		        fdxSource,      fdySource);
+      
+        fSrcPos->SetXY(fxSource, fySource);
+
+        fxSourceold = fxSource;
+        fySourceold = fySource;
+
+        *fLog << all << "MSourcePosfromStarPos::ReInit; fRunNr, fxSource, fySource = "
+              << fRunNr[i] << ",  " << fxSource << " +- " << fdxSource 
+              << ",  " << fySource  << " +- "  << fdySource << endl;
+       
+        fSrcPos->SetReadyToSave();       
+      }
+      else
+      {
+        // set default values
+        fxSource = fxSourceold;
+        fySource = fySourceold;
+        fSrcPos->SetXY(fxSource, fySource);
+        fSrcPos->SetReadyToSave();       
+
+
+        *fLog << warn << "MSourcePosfromStarPos::ReInit;  no information on source position for run number = "
+              << run << endl;
+        *fLog << warn << "       set xSource, ySource = " << fxSource << ",  "
+              << fySource << " mm" << endl;
+      }
+      
+
+      return kTRUE;
+    }
+  }
+  //-------------------------------------------------------------------  
+
+    // set default values
+    fxSource = fxSourceold;
+    fySource = fySourceold;
+    fSrcPos->SetXY(fxSource, fySource);
+    fSrcPos->SetReadyToSave();       
+
+    Double_t thetarad = fThetaradold;
+    Double_t phirad = fPhiradold;
+    fPointPos->SetLocalPosition(thetarad*kRad2Deg, phirad*kRad2Deg);
+    fPointPos->SetReadyToSave();
+
+
+    *fLog << warn << "MSourcePosfromStarPos::ReInit;  no information on theta, phi and source position for run number = "
+          << run << endl;
+    *fLog << warn << "       set xSource, ySource = " << fxSource << ",  "
+          << fySource << " mm" << endl;
+    *fLog << warn << "       set theta, phi = " << thetarad*kRad2Deg << ",  "
+          << phirad*kRad2Deg << " deg" << endl;
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MSourcePosfromStarPos::Process()
+{
+  //Int_t run = fRun->GetRunNumber();
+  //*fLog << "MSourcePosfromStarPos::Process; run = " << run << endl;
+    
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MSourcePosfromStarPos::PostProcess()
+{
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// read the data from the ASCII file and store them
+//
+void MSourcePosfromStarPos::FixSize()
+{
+    fSize = fRuns;
+    if (fRuns <= 0)
+      fSize = 1;
+
+    fRunNr.Set(fSize);
+
+    fThetaTel.Set(fSize);
+    fPhiTel.Set(fSize);
+    fdThetaTel.Set(fSize);
+    fdPhiTel.Set(fSize);
+
+    Int_t fRows = fxStar.GetNrows();
+    fxStar.ResizeTo(fRows, fSize);
+    fyStar.ResizeTo(fRows, fSize);
+    fdxStar.ResizeTo(fRows, fSize);
+    fdyStar.ResizeTo(fRows, fSize);
+
+  *fLog << "MSourcePosfromStarPos::FixSize; fix size of arrays : fStars = "
+        << fStars << ",  fRuns = " << fRuns << ",  fRows = " << fRows
+        << ",  fSize = " << fSize << endl;
+  if (fRuns > 0)
+  {
+    *fLog << "       first run : " << fRunNr[0] << ",  last run : "
+          << fRunNr[fRuns-1] << endl;
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// read the data from the ASCII file and store them
+//
+void MSourcePosfromStarPos::ReadData()
+{
+  Float_t val;
+  Int_t   ival;
+
+  // extend size of arrays if necessary
+  if ( fRuns >= fSize )
+  {
+    fSize += 100;
+
+    fRunNr.Set(fSize);
+
+    fThetaTel.Set(fSize);
+    fPhiTel.Set(fSize);
+    fdThetaTel.Set(fSize);
+    fdPhiTel.Set(fSize);
+    
+    Int_t fRows = fxStar.GetNrows();
+    fxStar.ResizeTo(fRows, fSize);
+    fyStar.ResizeTo(fRows, fSize);
+    fdxStar.ResizeTo(fRows, fSize);
+    fdyStar.ResizeTo(fRows, fSize);
+
+    *fLog << "MSourcePosfromStarPos::ReadData(); size of arrays has been increased to (fRows, fSize) = ("
+          << fRows << ",  " << fSize << ")" << endl;
+  }
+
+  //-------------------
+  // read header line
+  //*fIn >> val;
+
+  //*fLog << "val =" << val << endl;
+
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //*fIn >> val;
+  //-------------------
+
+
+
+  while(1)
+  {
+    *fIn >> ival;
+
+    if (fIn->eof())
+      return;
+
+    // run number must be greater than 10000
+    if (TMath::Abs(ival) < 10000)
+    {
+      *fLog << err << "===========> Error when reading file with theta and phi <========="
+	    << "             ival = " << ival << endl;
+    }          
+    else
+      break;
+  }  
+
+  fRuns += 1;
+  //*fLog << fRuns <<"th run : " << ival << endl;  
+
+  fRunNr.AddAt(ival, fRuns-1);
+
+  //*fLog << "check : fRuns, fRunNr[fRuns-1], fRunNr[fRuns] = " << fRuns << ",  "
+  //      << fRunNr[fRuns-1] << ",  " << fRunNr[fRuns] << endl;
+
+ 
+  // read mjdS, hmsS, mjdE, hmsE
+  // these data are present only for ON data (fStars > 0)
+  /*
+  if (fStars > 0)
+  {
+    *fIn >> val; 
+    *fIn >> val; 
+    *fIn >> val; 
+    *fIn >> val; 
+
+    *fIn >> val; 
+    *fIn >> val; 
+    *fIn >> val; 
+    *fIn >> val; 
+  }
+  */
+
+  *fIn >> val;
+  fThetaTel.AddAt(val/kRad2Deg, fRuns-1);
+  //*fLog << "val, fThetaTel[fRuns-1] = " << val << ",  "
+  //      << fThetaTel[fRuns-1] << endl;
+
+
+  *fIn >> val;
+  fPhiTel.AddAt(val/kRad2Deg, fRuns-1);
+  //*fLog << "val, fPhiTel[fRuns-1] = " << val << ",  "
+  //      << fPhiTel[fRuns-1] << endl;
+
+
+  //*fIn >> val;
+  //fdThetaTel.AddAt(val/kRad2Deg, fRuns-1);
+  //*fIn >> val;
+  //fdPhiTel.AddAt(val/kRad2Deg, fRuns-1);
+
+  // input is in [deg], convert to [mm]
+
+  //*fLog << "ReadData : fStarsRead = " << fStarsRead << endl;
+
+    for (Int_t i=0; i<fStarsRead; i++)
+    {
+      *fIn >> val;
+      if (i<fStars) fxStar(i, fRuns-1) = val;
+
+      *fIn >> val;
+      if (i<fStars) fyStar(i, fRuns-1) = val;
+
+      //*fIn >> val;
+      // if (i < fStars) fdxStar(i, fRuns-1) = val;
+      if (i < fStars) fdxStar(i, fRuns-1) = 1.0;
+
+      //*fIn >> val;
+      // if (i < fStars) fdyStar(i, fRuns-1) = val;
+      if (i < fStars) fdyStar(i, fRuns-1) = 1.0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add this file as the last entry in the chain
+//
+Int_t MSourcePosfromStarPos::AddFile(const char *txt, Int_t)
+{
+    TNamed *name = new TNamed(txt, "");
+    fFileNames->AddLast(name);
+
+    *fLog << "MSourcePosfromStarPos::AddFile; add file '" << txt << "'"
+          << endl;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Bool_t MSourcePosfromStarPos::OpenNextFile()
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existence of a next file to read
+    //
+    TNamed *file = (TNamed*)fFileNames->First();
+    if (!file)
+        return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const char *name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    fIn = new ifstream(expname);
+    delete [] expname;
+
+    const Bool_t noexist = !(*fIn);
+
+
+    if (noexist)
+        *fLog << dbginf << "Cannot open file '" << name << "'" << endl;
+    else
+        *fLog << "Open file: '" << name << "'" << endl;
+
+    //
+    // Remove this file from the list of pending files
+    //
+    fFileNames->Remove(file);
+
+    return !noexist;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MSourcePosfromStarPos.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MSourcePosfromStarPos.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSourcePosfromStarPos.h	(revision 9772)
@@ -0,0 +1,129 @@
+#ifndef MARS_MSourcePosfromStarPos
+#define MARS_MSourcePosfromStarPos
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MSourcePosfromStarPos                                                   //
+//                                                                         //
+// Task to calculate the position of the source in the camera from
+//      the position of a known star in the camera
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TMatrixD
+#include <TMatrixD.h>
+#endif
+
+class TList;
+class MRawRunHeader;
+class MPointingPos;
+class MMcEvt;
+class MGeomCam;
+class MSrcPosCam;
+class MObservatory;
+
+
+class MSourcePosfromStarPos : public MTask
+{
+ private:
+    const MRawRunHeader *fRun;      //!
+    const MGeomCam      *fGeomCam;  //! Camera Geometry used to calculate Hillas
+    MMcEvt              *fMcEvt;       //!
+    MPointingPos        *fPointPos;       //!
+    MSrcPosCam          *fSrcPos;         //!
+    MObservatory        *fObservatory;    //!
+
+    ifstream    *fIn;             // input file
+    TList       *fFileNames;      // array which contains the \0-terminated file names
+
+    Double_t fMm2Deg;
+    Double_t fDistCameraReflector;
+
+    Int_t   fRuns;                // current number of runs
+    Int_t   fSize;                // final   number of runs
+    Int_t   fStars;               // number of stars
+    Int_t   fStarsRead;           // number of (x,y) pairs to be read
+
+
+    Double_t fDecSource;  // sky coordinates of source
+    Double_t fRaSource;
+    Double_t fxSource;    // estimated position of source in camera
+    Double_t fySource;
+    Double_t fdxSource;
+    Double_t fdySource;
+
+    TArrayI fRunNr;       // list of run numbers
+    TArrayD fThetaTel;    // for each run : theta, phi, ...
+    TArrayD fPhiTel;
+    TArrayD fdThetaTel;
+    TArrayD fdPhiTel;
+
+    TArrayD  fDecStar;   // sky coordinates of stars
+    TArrayD  fRaStar;
+    TMatrixD fxStar;     // for each run : positions of stars in camera (from DC currents)
+    TMatrixD fyStar;
+    TMatrixD fdxStar;
+    TMatrixD fdyStar;
+
+    Double_t fxSourceold;  
+    Double_t fySourceold;
+    Double_t fThetaradold;
+    Double_t fPhiradold;
+
+    Bool_t OpenNextFile();
+    void   ReadData();
+    void   FixSize();
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MSourcePosfromStarPos(const char *name=NULL, const char *title=NULL);
+    ~MSourcePosfromStarPos();
+
+    void SetSourceAndStarPosition(
+	 TString  nameSource,
+	 Double_t decSourceDeg, Double_t decSourceMin, Double_t decSourceSec, 
+         Double_t raSourceHour, Double_t raSourceMin,  Double_t raSourceSec,
+	 TString  nameStar,
+	 Double_t decStarDeg,   Double_t decStarMin,   Double_t decStarSec, 
+         Double_t raStarHour,   Double_t raStarMin,    Double_t raStarSec  );
+
+    Int_t  AddFile(const char *fname, Int_t dummy=-1);
+
+    void AddStar(
+	 TString  nameStar,
+	 Double_t decStarDeg,   Double_t decStarMin,   Double_t decStarSec, 
+         Double_t raStarHour,   Double_t raStarMin,    Double_t raStarSec  );
+
+    void SourcefromStar(Double_t &, 
+      TArrayD  &, TArrayD  &, Double_t &, Double_t &, Double_t &, Double_t &, 
+      TArrayD  &, TArrayD  &, TArrayD  &, TArrayD  &, Double_t &, Double_t &, 
+      Double_t &, Double_t & );
+
+    ClassDef(MSourcePosfromStarPos, 0) // Task to calculate the source position from a star position
+};
+
+#endif
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MSupercuts.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MSupercuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSupercuts.cc	(revision 9772)
@@ -0,0 +1,388 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 08/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 08/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MSupercuts                                                         //
+//                                                                         //
+//   this is the container for the parameters of the supercuts             //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MSupercuts.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSupercuts);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+MSupercuts::MSupercuts(const char *name, const char *title)
+  : fParameters(104), fStepsizes(104),
+    fLengthUp(fParameters.GetArray()),   fLengthLo(fParameters.GetArray()+8),
+    fWidthUp(fParameters.GetArray()+16), fWidthLo(fParameters.GetArray()+24),
+    fDistUp(fParameters.GetArray()+32),  fDistLo(fParameters.GetArray()+40),
+    fAsymUp(fParameters.GetArray()+48),  fAsymLo(fParameters.GetArray()+56),
+    fConcUp(fParameters.GetArray()+64),  fConcLo(fParameters.GetArray()+72),
+    fLeakage1Up(fParameters.GetArray()+80), fLeakage1Lo(fParameters.GetArray()+88),
+    fAlphaUp(fParameters.GetArray()+96)
+{
+    fName  = name  ? name  : "MSupercuts";
+    fTitle = title ? title : "Container for the supercut parameters";
+
+    // set supercut parameters to their default values
+    InitParameters();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// set default values for the supercut parameters
+//
+void MSupercuts::InitParameters()
+{
+    //---------------------------------------------------
+    //  these are the default values
+
+    fLengthUp[0] =  0.2;
+    fLengthUp[1] =  0.0;
+    fLengthUp[2] =  0.0;
+    fLengthUp[3] =  0.0;
+    fLengthUp[4] =  0.0;
+    fLengthUp[5] =  0.0;
+    fLengthUp[6] =  0.0;
+    fLengthUp[7] =  0.0;
+
+    fLengthLo[0] =  0.;
+    fLengthLo[1] =  0.;
+    fLengthLo[2] =  0.;
+    fLengthLo[3] =  0.;
+    fLengthLo[4] =  0.;
+    fLengthLo[5] =  0.;
+    fLengthLo[6] =  0.;
+    fLengthLo[7] =  0.;
+
+    fWidthUp[0] =  0.1;
+    fWidthUp[1] =  0.0;
+    fWidthUp[2] =  0.0;
+    fWidthUp[3] =  0.0;
+    fWidthUp[4] =  0.0;
+    fWidthUp[5] =  0.0;
+    fWidthUp[6] =  0.0;
+    fWidthUp[7] =  0.0;
+
+    fWidthLo[0] =  0.;
+    fWidthLo[1] =  0.;
+    fWidthLo[2] =  0.;
+    fWidthLo[3] =  0.;
+    fWidthLo[4] =  0.;
+    fWidthLo[5] =  0.;
+    fWidthLo[6] =  0.;
+    fWidthLo[7] =  0.;
+
+    fDistUp[0] =  1.e10;
+    fDistUp[1] =  0.0;
+    fDistUp[2] =  0.0;
+    fDistUp[3] =  0.0;
+    fDistUp[4] =  0.0;
+    fDistUp[5] =  0.0;
+    fDistUp[6] =  0.0;
+    fDistUp[7] =  0.0;
+
+    fDistLo[0] =  0.0;
+    fDistLo[1] =  0.0;
+    fDistLo[2] =  0.0;
+    fDistLo[3] =  0.0;
+    fDistLo[4] =  0.0;
+    fDistLo[5] =  0.0;
+    fDistLo[6] =  0.0;
+    fDistLo[7] =  0.0;
+    
+
+    // dummy values
+
+    fAsymUp[0] =  1.e10;
+    fAsymUp[1] =  0.0;
+    fAsymUp[2] =  0.0;
+    fAsymUp[3] =  0.0;
+    fAsymUp[4] =  0.0;
+    fAsymUp[5] =  0.0;
+    fAsymUp[6] =  0.0;
+    fAsymUp[7] =  0.0;
+
+    fAsymLo[0] = -1.e10;
+    fAsymLo[1] =  0.0;
+    fAsymLo[2] =  0.0;
+    fAsymLo[3] =  0.0;
+    fAsymLo[4] =  0.0;
+    fAsymLo[5] =  0.0;
+    fAsymLo[6] =  0.0;
+    fAsymLo[7] =  0.0;
+
+    fConcUp[0] =  1.e10;
+    fConcUp[1] =  0.0;
+    fConcUp[2] =  0.0;
+    fConcUp[3] =  0.0;
+    fConcUp[4] =  0.0;
+    fConcUp[5] =  0.0;
+    fConcUp[6] =  0.0;
+    fConcUp[7] =  0.0;
+
+    fConcLo[0] = -1.e10;
+    fConcLo[1] =  0.0;
+    fConcLo[2] =  0.0;
+    fConcLo[3] =  0.0;
+    fConcLo[4] =  0.0;
+    fConcLo[5] =  0.0;
+    fConcLo[6] =  0.0;
+    fConcLo[7] =  0.0;
+
+    fLeakage1Up[0] =  1.e10;
+    fLeakage1Up[1] =  0.0;
+    fLeakage1Up[2] =  0.0;
+    fLeakage1Up[3] =  0.0;
+    fLeakage1Up[4] =  0.0;
+    fLeakage1Up[5] =  0.0;
+    fLeakage1Up[6] =  0.0;
+    fLeakage1Up[7] =  0.0;
+
+    fLeakage1Lo[0] = -1.e10;
+    fLeakage1Lo[1] =  0.0;
+    fLeakage1Lo[2] =  0.0;
+    fLeakage1Lo[3] =  0.0;
+    fLeakage1Lo[4] =  0.0;
+    fLeakage1Lo[5] =  0.0;
+    fLeakage1Lo[6] =  0.0;
+    fLeakage1Lo[7] =  0.0;
+
+    fAlphaUp[0] = 13.123440; 
+    fAlphaUp[1] = 0;
+    fAlphaUp[2] = 0;
+    fAlphaUp[3] = 0;
+    fAlphaUp[4] = 0;
+    fAlphaUp[5] = 0;
+    fAlphaUp[6] = 0;
+    fAlphaUp[7] = 0;
+
+    //---------------------------------------------------
+    // fStepsizes 
+    // if == 0.0    the parameter will be fixed in the minimization
+    //    != 0.0    initial step sizes for the parameters
+
+    // LengthUp
+    fStepsizes[0] = 0.02;
+    fStepsizes[1] = 0.0;
+    fStepsizes[2] = 0.0;
+    fStepsizes[3] = 0.0;
+    fStepsizes[4] = 0.0;
+    fStepsizes[5] = 0.0;
+    fStepsizes[6] = 0.0;
+    fStepsizes[7] = 0.0;
+
+    // LengthLo
+    fStepsizes[8]  = 0.0;
+    fStepsizes[9]  = 0.0;
+    fStepsizes[10] = 0.0;
+    fStepsizes[11] = 0.0;
+    fStepsizes[12] = 0.0;
+    fStepsizes[13] = 0.0;
+    fStepsizes[14] = 0.0;
+    fStepsizes[15] = 0.0;
+
+    // WidthUp
+    fStepsizes[16] = 0.01;
+    fStepsizes[17] = 0.0;
+    fStepsizes[18] = 0.0;
+    fStepsizes[19] = 0.0;
+    fStepsizes[20] = 0.0;
+    fStepsizes[21] = 0.0;
+    fStepsizes[22] = 0.0;
+    fStepsizes[23] = 0.0;
+
+    // WidthLo
+    fStepsizes[24] = 0.0;
+    fStepsizes[25] = 0.0;
+    fStepsizes[26] = 0.0;
+    fStepsizes[27] = 0.0;
+    fStepsizes[28] = 0.0;
+    fStepsizes[29] = 0.0;
+    fStepsizes[30] = 0.0;
+    fStepsizes[31] = 0.0;
+
+    // DistUp
+    fStepsizes[32] = 0.0;
+    fStepsizes[33] = 0.0;
+    fStepsizes[34] = 0.0;
+    fStepsizes[35] = 0.0;
+    fStepsizes[36] = 0.0;
+    fStepsizes[37] = 0.0;
+    fStepsizes[38] = 0.0;
+    fStepsizes[39] = 0.0;
+
+    // DistLo
+    fStepsizes[40] = 0.0;
+    fStepsizes[41] = 0.0;
+    fStepsizes[42] = 0.0;
+    fStepsizes[43] = 0.0;
+    fStepsizes[44] = 0.0;
+    fStepsizes[45] = 0.0;
+    fStepsizes[46] = 0.0;
+    fStepsizes[47] = 0.0;
+
+    // AsymUp
+    fStepsizes[48] = 0.0;
+    fStepsizes[49] = 0.0;
+    fStepsizes[50] = 0.0;
+    fStepsizes[51] = 0.0;
+    fStepsizes[52] = 0.0;
+    fStepsizes[53] = 0.0;
+    fStepsizes[54] = 0.0;
+    fStepsizes[55] = 0.0;
+
+    // AsymLo
+    fStepsizes[56] = 0.0;
+    fStepsizes[57] = 0.0;
+    fStepsizes[58] = 0.0;
+    fStepsizes[59] = 0.0;
+    fStepsizes[60] = 0.0;
+    fStepsizes[61] = 0.0;
+    fStepsizes[62] = 0.0;
+    fStepsizes[63] = 0.0;
+
+    // ConcUp
+    fStepsizes[64] = 0.0;
+    fStepsizes[65] = 0.0;
+    fStepsizes[66] = 0.0;
+    fStepsizes[67] = 0.0;
+    fStepsizes[68] = 0.0;
+    fStepsizes[69] = 0.0;
+    fStepsizes[70] = 0.0;
+    fStepsizes[71] = 0.0;
+
+    // ConcLo
+    fStepsizes[72] = 0.0;
+    fStepsizes[73] = 0.0;
+    fStepsizes[74] = 0.0;
+    fStepsizes[75] = 0.0;
+    fStepsizes[76] = 0.0;
+    fStepsizes[77] = 0.0;
+    fStepsizes[78] = 0.0;
+    fStepsizes[79] = 0.0;
+
+    // Leakage1Up
+    fStepsizes[80] = 0.0;
+    fStepsizes[81] = 0.0;
+    fStepsizes[82] = 0.0;
+    fStepsizes[83] = 0.0;
+    fStepsizes[84] = 0.0;
+    fStepsizes[85] = 0.0;
+    fStepsizes[86] = 0.0;
+    fStepsizes[87] = 0.0;
+
+    // Leakage1Lo
+    fStepsizes[88] = 0.0;
+    fStepsizes[89] = 0.0;
+    fStepsizes[90] = 0.0;
+    fStepsizes[91] = 0.0;
+    fStepsizes[92] = 0.0;
+    fStepsizes[93] = 0.0;
+    fStepsizes[94] = 0.0;
+    fStepsizes[95] = 0.0;
+
+    // AlphaUp
+    fStepsizes[96]  = 0.0;
+    fStepsizes[97]  = 0.0;
+    fStepsizes[98]  = 0.0;
+    fStepsizes[99]  = 0.0;
+    fStepsizes[100] = 0.0;
+    fStepsizes[101] = 0.0;
+    fStepsizes[102] = 0.0;
+    fStepsizes[103] = 0.0;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the parameter values from the array 'd'
+//
+//
+Bool_t MSupercuts::SetParameters(const TArrayD &d)
+{
+    if (d.GetSize() != fParameters.GetSize())
+    {
+        *fLog << err << "Sizes of d and of fParameters are different : "
+              << d.GetSize() << ",  " << fParameters.GetSize() << endl;
+        return kFALSE;
+    }
+
+    fParameters = d;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the step sizes from the array 'd'
+//
+//
+Bool_t MSupercuts::SetStepsizes(const TArrayD &d)
+{
+    if (d.GetSize() != fStepsizes.GetSize())
+    {
+        *fLog << err << "Sizes of d and of fStepsizes are different : "
+              << d.GetSize() << ",  " << fStepsizes.GetSize() << endl;
+        return kFALSE;
+    }
+
+    fStepsizes = d;
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MSupercuts.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MSupercuts.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSupercuts.h	(revision 9772)
@@ -0,0 +1,69 @@
+#ifndef MARS_MSupercuts
+#define MARS_MSupercuts
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MSupercuts : public MParContainer
+{
+private:
+    TArrayD fParameters; // supercut parameters
+    TArrayD fStepsizes;  // step sizes of supercut parameters
+
+    Double_t *fLengthUp; //!
+    Double_t *fLengthLo; //!
+    Double_t *fWidthUp;  //!
+    Double_t *fWidthLo;  //!
+    Double_t *fDistUp;   //!
+    Double_t *fDistLo;   //!
+    Double_t *fAsymUp;   //!
+    Double_t *fAsymLo;   //!
+
+    Double_t *fConcUp;   //!
+    Double_t *fConcLo;   //!
+    Double_t *fLeakage1Up;   //!
+    Double_t *fLeakage1Lo;   //!
+
+    Double_t *fAlphaUp;  //!
+
+
+public:
+    MSupercuts(const char *name=NULL, const char *title=NULL);
+
+    void InitParameters();
+
+    Bool_t SetParameters(const TArrayD &d);
+    Bool_t SetStepsizes(const TArrayD &d);
+
+    const TArrayD &GetParameters() const { return fParameters; }
+    const TArrayD &GetStepsizes()  const { return fStepsizes;  }
+
+    const Double_t *GetLengthUp() const { return fLengthUp; }
+    const Double_t *GetLengthLo() const { return fLengthLo; }
+    const Double_t *GetWidthUp() const  { return fWidthUp; }
+    const Double_t *GetWidthLo() const  { return fWidthLo; }
+    const Double_t *GetDistUp() const   { return fDistUp; }
+    const Double_t *GetDistLo() const   { return fDistLo; }
+    const Double_t *GetAsymUp() const   { return fAsymUp; }
+    const Double_t *GetAsymLo() const   { return fAsymLo; }
+
+    const Double_t *GetConcUp() const   { return fConcUp; }
+    const Double_t *GetConcLo() const   { return fConcLo; }
+
+    const Double_t *GetLeakage1Up() const   { return fLeakage1Up; }
+    const Double_t *GetLeakage1Lo() const   { return fLeakage1Lo; }
+
+    const Double_t *GetAlphaUp() const  { return fAlphaUp; }
+
+    ClassDef(MSupercuts, 1) // A container for the Supercut parameters
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/manalysis/MSupercutsCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysis/MSupercutsCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSupercutsCalc.cc	(revision 9772)
@@ -0,0 +1,346 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MSupercutsCalc
+//
+//   this class calculates the hadronness for the supercuts
+//   the parameters of the supercuts are taken
+//                  from the container MSupercuts
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSupercutsCalc.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "TFile.h"
+#include "TArrayD.h"
+
+#include "MParList.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MMcEvt.hxx"
+#include "MGeomCam.h"
+#include "MHadronness.h"
+#include "MHMatrix.h"
+#include "MSupercuts.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSupercutsCalc);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+
+MSupercutsCalc::MSupercutsCalc(const char *hilname, 
+                                     const char *hilsrcname, 
+                                     const char *name, const char *title)
+  : fHadronnessName("MHadronness"), fHilName(hilname), fHilSrcName(hilsrcname),
+    fHilExtName("MHillasExt"), fNewParName("MNewImagePar"), 
+    fSuperName("MSupercuts") 
+{
+    fName  = name  ? name  : "MSupercutsCalc";
+    fTitle = title ? title : "Class to evaluate the Supercuts";
+
+    fMatrix = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MSupercutsCalc::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    fHadronness = (MHadronness*)pList->FindCreateObj("MHadronness", fHadronnessName);
+    if (!fHadronness)
+    {
+        *fLog << err << fHadronnessName << " [MHadronness] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSuper = (MSupercuts*)pList->FindObject(fSuperName, "MSupercuts");
+    if (!fSuper)
+    {
+        *fLog << err << fSuperName << " [MSupercuts] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fMatrix)
+        return kTRUE;
+
+    //-----------------------------------------------------------
+    fHil = (MHillas*)pList->FindObject(fHilName, "MHillas");
+    if (!fHil)
+    {
+        *fLog << err << fHilName << " [MHillas] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject(fHilExtName, "MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << fHilExtName << " [MHillasExt] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << fHilSrcName << " [MHillasSrc] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject(fNewParName, "MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << fNewParName << " [MNewImagePar] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculation of upper and lower limits
+//
+Double_t MSupercutsCalc::CtsMCut(const Double_t* a,  Double_t ls, Double_t ct,
+                                    Double_t ls2, Double_t dd2) const
+{
+    // define cut-function
+    //
+    //    dNOMLOGSIZE = 5.0 (=log(150.0)
+    //    dNOMCOSZA   = 1.0
+    //
+    //      a: array of cut parameters
+    //     ls: log(SIZE) - dNOMLOGSIZE
+    //    ls2: ls^2
+    //     ct: Cos(ZA.) - dNOMCOSZA
+    //    dd2: DIST^2
+    const Double_t limit =
+        a[0] + a[1] * dd2 + a[2] * ct  +
+        ls  * (a[3] + a[4] * dd2 + a[5] * ct) +
+        ls2 * (a[6] + a[7] * dd2);
+
+    //*fLog << "MSupercutsCalc::CtsMCut; *a = "
+    //      << *a     << ",  " << *(a+1) << ",  " << *(a+2) << ",  "
+    //      << *(a+3) << ",  " << *(a+4) << ",  " << *(a+5) << ",  "
+    //      << *(a+6) << ",  " << *(a+7) << endl;
+
+    //*fLog << "MSupercutsCalc::CtsMCut; ls, ls2, ct, dd2, limit = " << ls
+    //      << ",  " << ls2 << ",  " << ct << ",  " << dd2 << ",  "
+    //      << limit << endl;
+
+    return limit;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MSupercutsCalc::GetVal(Int_t i) const
+{
+
+    Double_t val = (*fMatrix)[fMap[i]];
+
+
+    //*fLog << "MSupercutsCalc::GetVal; i, fMatrix, fMap, val = "
+    //    << i << ",  " << fMatrix << ",  " << fMap[i] << ",  " << val << endl;
+
+
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam::Process
+// will take the values from the matrix instead of the containers.
+//
+void MSupercutsCalc::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MMcEvt.fTelescopeTheta");
+    fMap[1] = fMatrix->AddColumn("MHillas.fWidth");
+    fMap[2] = fMatrix->AddColumn("MHillas.fLength");
+    fMap[3] = fMatrix->AddColumn("MHillas.fSize");
+    fMap[4] = fMatrix->AddColumn("MHillas.fMeanX");
+    fMap[5] = fMatrix->AddColumn("MHillas.fMeanY");
+    fMap[6] = fMatrix->AddColumn("MHillasSrc.fDist");
+    fMap[7] = fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+    fMap[8] = fMatrix->AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    fMap[9] = fMatrix->AddColumn("MNewImagePar.fConc");
+    fMap[10]= fMatrix->AddColumn("MNewImagePar.fLeakage1");
+}
+
+// ---------------------------------------------------------------------------
+//
+// Evaluate dynamical supercuts 
+// 
+//          set hadronness to 0.25 if cuts are fullfilled
+//                            0.75 otherwise
+//
+Int_t MSupercutsCalc::Process()
+{
+    const Double_t kNomLogSize = 4.1;
+    const Double_t kNomCosZA   = 1.0;
+
+    const Double_t theta   = fMatrix ? GetVal(0) : fMcEvt->GetTelescopeTheta();
+    const Double_t width0  = fMatrix ? GetVal(1) : fHil->GetWidth();
+    const Double_t length0 = fMatrix ? GetVal(2) : fHil->GetLength();
+    const Double_t size    = fMatrix ? GetVal(3) : fHil->GetSize();
+    const Double_t meanx   = fMatrix ? GetVal(4) : fHil->GetMeanX();
+    const Double_t meany   = fMatrix ? GetVal(5) : fHil->GetMeanY();
+    const Double_t dist0   = fMatrix ? GetVal(6) : fHilSrc->GetDist();
+
+    Double_t help;
+    if (!fMatrix)
+      help = TMath::Sign(fHilExt->GetM3Long(), 
+	      		 fHilSrc->GetCosDeltaAlpha());
+    const Double_t asym0   = fMatrix ? GetVal(8) : help;
+    const Double_t conc    = fMatrix ? GetVal(9) : fNewPar->GetConc();
+    const Double_t leakage = fMatrix ? GetVal(10): fNewPar->GetLeakage1();
+
+    const Double_t newdist = dist0 * fMm2Deg;
+
+    const Double_t dist2   = meanx*meanx + meany*meany;
+    const Double_t dist    = sqrt(dist2) * fMm2Deg;
+    const Double_t dd2     = dist*dist;
+
+
+    const Double_t dmls    = log(size) - kNomLogSize;
+    const Double_t dmls2   = dmls * dmls;
+
+    const Double_t dmcza   = cos(theta) - kNomCosZA;
+
+    const Double_t length  = length0 * fMm2Deg;
+    const Double_t width   = width0  * fMm2Deg;
+    const Double_t asym    = asym0   * fMm2Deg;
+
+    /*
+    *fLog << "newdist, length, width, asym, dist, conc, leakage = " 
+          << newdist << ",  " << length << ",  " << width << ",  "
+          << asym    << ",  " << dist   << ",  " << conc  << ",  " << leakage
+          << endl;
+  
+    *fLog << "upper cuts in newdist, length, width, asym, dist, conc, leakage = " 
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLengthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLengthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetWidthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetWidthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLeakage1Up(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLeakage1Lo(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << endl;
+    */
+
+
+    if (
+        //dist    < 1.05                                                     &&
+        //newdist < 1.05                                                     &&
+
+        newdist < CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) &&
+        newdist > CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        length  < CtsMCut (fSuper->GetLengthUp(), dmls, dmcza, dmls2, dd2) &&
+        length  > CtsMCut (fSuper->GetLengthLo(), dmls, dmcza, dmls2, dd2) &&
+
+        width   < CtsMCut (fSuper->GetWidthUp(),  dmls, dmcza, dmls2, dd2) &&
+        width   > CtsMCut (fSuper->GetWidthLo(),  dmls, dmcza, dmls2, dd2) &&
+
+        asym    < CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) &&
+        asym    > CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        dist    < CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) &&
+        dist    > CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        conc    < CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) &&
+        conc    > CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        leakage < CtsMCut (fSuper->GetLeakage1Up(),dmls, dmcza, dmls2, dd2) &&
+        leakage > CtsMCut (fSuper->GetLeakage1Lo(),dmls, dmcza, dmls2, dd2)  ) 
+
+      fHadronness->SetHadronness(0.25);
+    else
+      fHadronness->SetHadronness(0.75);
+
+    //*fLog << "SChadroness = " << fHadronness->GetHadronness() << endl;
+
+    fHadronness->SetReadyToSave();
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/MSupercutsCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysis/MSupercutsCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/MSupercutsCalc.h	(revision 9772)
@@ -0,0 +1,82 @@
+#ifndef MARS_MSupercutsCalc
+#define MARS_MSupercutsCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MParList;
+class MHillas;
+class MHillasSrc;
+class MHillasExt;
+class MNewImagePar;
+class MMcEvt;
+class MCerPhotEvt;
+class MGeomCam;
+class MHadronness;
+class MHMatrix;
+class MSupercuts;
+
+class MSupercutsCalc : public MTask
+{
+private:
+    MHillas       *fHil;
+    MHillasSrc    *fHilSrc;
+    MHillasExt    *fHilExt;
+    MNewImagePar  *fNewPar;
+    MMcEvt        *fMcEvt;
+    MHadronness   *fHadronness; //! output container for hadronness
+    MSupercuts *fSuper;      // container for supercut parameters
+
+    TString  fHadronnessName;   // name of container to store hadronness
+    TString  fHilName;
+    TString  fHilSrcName;
+    TString  fHilExtName;
+    TString  fNewParName;
+    TString  fSuperName;        // name of container for supercut parameters
+
+    Double_t fMm2Deg;           //!
+
+    Int_t     fMap[11];         //!
+    MHMatrix *fMatrix;          //!
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Double_t GetVal(Int_t i) const;
+
+    Double_t CtsMCut(const Double_t* a, Double_t ls, Double_t ct,
+                     Double_t ls2, Double_t dd2) const;
+
+public:
+    MSupercutsCalc(const char *hilname="MHillas",
+                      const char *hilsrcname="MHillasSrc",
+                      const char *name=NULL, const char *title=NULL);
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+    TString GetHadronnessName() const { return fHadronnessName; }
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping() { InitMapping(NULL); }
+
+
+    ClassDef(MSupercutsCalc, 0) // A class to evaluate the Supercuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysis/Makefile
===================================================================
--- /tags/Mars-V0.9/manalysis/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/manalysis/Makefile	(revision 9772)
@@ -0,0 +1,51 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Analysis
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mmc -I../mraw -I../mgeom -I../mfilter \
+	   -I../mdata -I../mhbase -I../mhist -I../mgui -I../mimage   \
+           -I../mhistmc -I../mfileio -I../mmain -I../mcalib \
+           -I../msignal -I../mpointing -I../mtools -I../mfbase       \
+           -I../mbadpixels -I../mastro -I../mpedestal
+# mcalib: MGeomApply (MCalibrationCam)
+
+SRCFILES = MGeomApply.cc \
+           MCameraData.cc \
+           MEnergyEstimate.cc \
+           MHadronness.cc \
+           MMatrixLoop.cc \
+           MCompProbCalc.cc \
+           MMultiDimDistCalc.cc \
+           MEventRate.cc \
+           MEventRateCalc.cc \
+           MParameters.cc \
+	   MMcTriggerLvl2.cc \
+	   MMcTriggerLvl2Calc.cc \
+           MMcCalibrationUpdate.cc
+
+############################################################
+
+all:  $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
Index: /tags/Mars-V0.9/manalysisct1/AnalysisCT1Incl.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/AnalysisCT1Incl.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/AnalysisCT1Incl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/manalysisct1/AnalysisCT1LinkDef.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/AnalysisCT1LinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/AnalysisCT1LinkDef.h	(revision 9772)
@@ -0,0 +1,18 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+// Doesn't compile: Please replace MBlindPixels by MBadPixel*
+//#pragma link C++ class MCT1PadSchweizer+;
+//#pragma link C++ class MCT1PadONOFF+;
+
+#pragma link C++ class MCT1PointingCorrCalc+;
+#pragma link C++ class MCT1Supercuts+;
+#pragma link C++ class MCT1SupercutsCalc+;
+#pragma link C++ class MCT1FindSupercuts+;
+#pragma link C++ class MCT1ReadPreProc+;
+#pragma link C++ class MCT1ReadAscii+;
+
+#endif
Index: /tags/Mars-V0.9/manalysisct1/MCT1FindSupercuts.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1FindSupercuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1FindSupercuts.cc	(revision 9772)
@@ -0,0 +1,1153 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek, 7/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCT1FindSupercuts                                                       //
+//                                                                         //
+// Class for otimizing the parameters of the supercuts                     //
+//                                                                         //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1FindSupercuts.h"
+
+#include <math.h>            // fabs 
+
+#include <TFile.h>
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TStopwatch.h>
+#include <TVirtualFitter.h>
+
+#include "MBinning.h"
+#include "MContinue.h"
+#include "MCT1Supercuts.h"
+#include "MCT1SupercutsCalc.h"
+#include "MDataElement.h"
+#include "MDataMember.h"
+
+#include "MEvtLoop.h"
+#include "MFCT1SelFinal.h"
+#include "MF.h"
+#include "MFEventSelector.h"
+#include "MFEventSelector2.h"
+#include "MFillH.h"
+//#include "MGeomCamCT1Daniel.h"
+#include "MFEventSelector.h"
+#include "MGeomCamCT1.h"
+#include "MH3.h"
+#include "MHCT1Supercuts.h"
+#include "MHFindSignificance.h"
+#include "MHMatrix.h"
+#include "MHOnSubtraction.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMatrixLoop.h"
+#include "MMinuitInterface.h"
+#include "MParList.h"
+#include "MProgressBar.h"
+#include "MReadMarsFile.h"
+#include "MReadTree.h"
+#include "MTaskList.h"
+
+
+ClassImp(MCT1FindSupercuts);
+
+using namespace std;
+
+
+//------------------------------------------------------------------------
+//
+// fcnSupercuts 
+//
+// - calculates the quantity to be minimized (using TMinuit)
+//
+// - the quantity to be minimized is (-1)*significance of the gamma signal
+//   in the alpha distribution (after cuts)
+//
+// - the parameters to be varied in the minimization are the cut parameters
+//   (par)
+//
+static void fcnSupercuts(Int_t &npar, Double_t *gin, Double_t &f, 
+                         Double_t *par, Int_t iflag)
+{
+    //cout <<  "entry fcnSupercuts" << endl;
+
+    //-------------------------------------------------------------
+    // save pointer to the MINUIT object for optimizing the supercuts
+    // because it will be overwritten 
+    // when fitting the alpha distribution in MHFindSignificance
+    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+
+    MEvtLoop *evtloopfcn = (MEvtLoop*)gMinuit->GetObjectFit();
+
+    MParList *plistfcn   = (MParList*)evtloopfcn->GetParList();
+    //MTaskList *tasklistfcn   = (MTaskList*)plistfcn->FindObject("MTaskList");
+
+    MCT1Supercuts *super = (MCT1Supercuts*)plistfcn->FindObject("MCT1Supercuts");
+    if (!super)
+    {
+        gLog << "fcnSupercuts : MCT1Supercuts object '" << "MCT1Supercuts"
+            << "' not found... aborting" << endl;
+        return;
+    }
+
+    //
+    // transfer current parameter values to MCT1Supercuts
+    //
+    // Attention : npar is the number of variable parameters
+    //                  not the total number of parameters
+    //
+    Double_t fMin, fEdm, fErrdef;
+    Int_t     fNpari, fNparx, fIstat;
+    gMinuit->mnstat(fMin, fEdm, fErrdef, fNpari, fNparx, fIstat);
+
+    super->SetParameters(TArrayD(fNparx, par));
+
+    //$$$$$$$$$$$$$$$$$$$$$
+    // for testing
+    //TArrayD checkparameters = super->GetParameters();
+    //gLog << "fcnsupercuts : fNpari, fNparx =" << fNpari << ",  " 
+    //     << fNparx  << endl;
+    //gLog << "fcnsupercuts : i, par, checkparameters =" << endl;
+    //for (Int_t i=0; i<fNparx; i++)
+    //{
+    //  gLog << i << ",  " << par[i] << ",  " << checkparameters[i] << endl;
+    //}
+    //$$$$$$$$$$$$$$$$$$$$$
+
+    //
+    // plot alpha with the current cuts
+    //
+    evtloopfcn->Eventloop();
+
+    //tasklistfcn->PrintStatistics(0, kTRUE);
+
+    MH3* alpha = (MH3*)plistfcn->FindObject("AlphaFcn", "MH3");
+    if (!alpha)
+        return;
+
+    TH1 &alphaHist = alpha->GetHist();
+    alphaHist.SetName("alpha-fcnSupercuts");
+
+    //-------------------------------------------
+    // set Minuit pointer to zero in order not to destroy the TMinuit
+    // object for optimizing the supercuts
+    gMinuit = NULL;
+
+    //=================================================================
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    const Double_t alphasig = 20.0;
+    const Double_t alphamin = 30.0;
+    const Double_t alphamax = 90.0;
+    const Int_t    degree   =    2;
+
+    Bool_t drawpoly;
+    Bool_t fitgauss;
+    if (iflag == 3)
+    {
+        drawpoly  = kTRUE;
+        fitgauss  = kTRUE;
+    }
+    else
+    {
+        drawpoly  = kFALSE;
+        fitgauss  = kFALSE;
+    }
+    //drawpoly  = kFALSE;
+    //fitgauss  = kFALSE;
+
+    const Bool_t print = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+    
+    const Bool_t rc = findsig.FindSigma(&alphaHist, alphamin, alphamax, degree,
+                                        alphasig, drawpoly, fitgauss, print);
+
+    //=================================================================
+
+    // reset gMinuit to the MINUIT object for optimizing the supercuts 
+    gMinuit = savePointer;
+    //-------------------------------------------
+
+    if (!rc)
+    {
+        gLog << "fcnSupercuts : FindSigma() failed" << endl;
+        f = 1.e10;
+        return;
+    }
+
+    // plot some quantities during the optimization
+    MHCT1Supercuts *plotsuper = (MHCT1Supercuts*)plistfcn->FindObject("MHCT1Supercuts");
+    if (plotsuper)
+        plotsuper->Fill(&findsig);
+
+    //------------------------
+    // get significance
+    const Double_t significance = findsig.GetSignificance();
+    f = significance>0 ? -significance : 0;
+
+
+    //------------------------
+    // optimize signal/background ratio
+    //Double_t ratio = findsig.GetNbg()>0.0 ? 
+    //                 findsig.GetNex()/findsig.GetNbg() : 0.0; 
+    //f = -ratio;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCT1FindSupercuts::MCT1FindSupercuts(const char *name, const char *title)
+: fHowManyTrain(10000), fHowManyTest(10000), fMatrixFilter(NULL)
+{
+    fName  = name  ? name  : "MCT1FindSupercuts";
+    fTitle = title ? title : "Optimizer of the supercuts";
+
+    //---------------------------
+    // camera geometry is needed for conversion mm ==> degree
+    //fCam = new MGeomCamCT1Daniel; 
+    fCam = new MGeomCamCT1; 
+
+    // matrices to contain the training/test samples
+    fMatrixTrain = new MHMatrix("MatrixTrain");
+    fMatrixTest  = new MHMatrix("MatrixTest");
+
+    // objects of MCT1SupercutsCalc to which these matrices are attached
+    fCalcHadTrain = new MCT1SupercutsCalc("SupercutsCalcTrain");
+    fCalcHadTest  = new MCT1SupercutsCalc("SupercutsCalcTest");
+
+    // Define columns of matrices
+    fCalcHadTrain->InitMapping(fMatrixTrain);
+    fCalcHadTest->InitMapping(fMatrixTest);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MCT1FindSupercuts::~MCT1FindSupercuts()
+{
+    delete fCam;
+    delete fMatrixTrain;
+    delete fMatrixTest;
+    delete fCalcHadTrain;
+    delete fCalcHadTest;
+}
+
+// --------------------------------------------------------------------------
+//
+// Define the matrix 'fMatrixTrain' for the training sample
+//
+// alltogether 'howmanytrain' events are read from file 'nametrain';
+// the events are selected according to a target distribution 'hreftrain'
+//
+//
+Bool_t MCT1FindSupercuts::DefineTrainMatrix(
+			  const TString &nametrain, MH3 &hreftrain,
+	                  const Int_t howmanytrain, const TString &filetrain)
+{
+    if (nametrain.IsNull() || howmanytrain <= 0)
+        return kFALSE;
+
+    *fLog << "=============================================" << endl;
+    *fLog << "fill training matrix from file '" << nametrain 
+          << "',   select " << howmanytrain 
+          << " events " << endl;
+    if (!hreftrain.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftrain.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", nametrain);
+    read.DisableAutoScheme();
+
+    MFEventSelector2 seltrain(hreftrain);
+    seltrain.SetNumMax(howmanytrain);
+    seltrain.SetName("selectTrain");
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetFilter(&seltrain);
+    filltrain.SetName("fillMatrixTrain");
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&seltrain);
+    tlist.AddToList(&filltrain);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrain");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrain->Print("SizeCols");
+    Int_t howmanygenerated = fMatrixTrain->GetM().GetNrows();
+    if (TMath::Abs(howmanygenerated-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MCT1FindSupercuts::DefineTrainMatrix; no.of generated events ("
+	    << howmanygenerated 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    *fLog << "training matrix was filled" << endl;
+    *fLog << "=============================================" << endl;
+
+    //--------------------------
+    // write out training matrix
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MCT1FindSupercuts::DefineTrainMatrix; Training matrix was written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Define the matrix for the test sample
+//
+// alltogether 'howmanytest' events are read from file 'nametest'
+//
+// the events are selected according to a target distribution 'hreftest'
+//
+//
+Bool_t MCT1FindSupercuts::DefineTestMatrix(
+			  const TString &nametest, MH3 &hreftest,
+	                  const Int_t howmanytest, const TString &filetest)
+{
+    if (nametest.IsNull() || howmanytest<=0)
+        return kFALSE;
+
+    *fLog << "=============================================" << endl;
+    *fLog << "fill test matrix from file '" << nametest 
+          << "',   select " << howmanytest 
+          << " events " << endl;
+    if (!hreftest.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftest.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", nametest);
+    read.DisableAutoScheme();
+
+    MFEventSelector2 seltest(hreftest);
+    seltest.SetNumMax(howmanytest);
+    seltest.SetName("selectTest");
+ 
+    MFillH filltest(fMatrixTest);
+    filltest.SetFilter(&seltest);
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTest);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&seltest);
+    tlist.AddToList(&filltest);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTest");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTest->Print("SizeCols");
+    const Int_t howmanygenerated = fMatrixTest->GetM().GetNrows();
+    if (TMath::Abs(howmanygenerated-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MCT1FindSupercuts::DefineTestMatrix; no.of generated events ("
+	    << howmanygenerated 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+    *fLog << "test matrix was filled" << endl;
+    *fLog << "=============================================" << endl;
+
+    //--------------------------
+    // write out test matrix
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MCT1FindSupercuts::DefineTestMatrix; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices for the training and test sample respectively
+//
+//
+//
+Bool_t MCT1FindSupercuts::DefineTrainTestMatrix(
+			  const TString &name, MH3 &href,
+	                  const Int_t howmanytrain, const Int_t howmanytest,
+                          const TString &filetrain, const TString &filetest)
+{
+    *fLog << "=============================================" << endl;
+    *fLog << "fill training and test matrix from file '" << name 
+          << "',   select "   << howmanytrain 
+          << " training and " << howmanytest << " test events " << endl;
+    if (!href.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << href.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", name);
+    read.DisableAutoScheme();
+
+    MFEventSelector2 selector(href);
+    selector.SetNumMax(howmanytrain+howmanytest);
+    selector.SetName("selectTrainTest");
+    selector.SetInverted();
+
+    MContinue cont(&selector);
+    cont.SetName("ContTrainTest");
+
+    Double_t prob =  ( (Double_t) howmanytrain )
+                   / ( (Double_t)(howmanytrain+howmanytest) );
+    MFEventSelector split;
+    split.SetSelectionRatio(prob);
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetFilter(&split);
+    filltrain.SetName("fillMatrixTrain");
+
+
+    // consider this event as candidate for a test event 
+    // only if event was not accepted as a training event
+
+    MContinue conttrain(&split);
+    conttrain.SetName("ContTrain");
+
+    MFillH filltest(fMatrixTest);
+    filltest.SetName("fillMatrixTest");
+
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+    plist.AddToList(fMatrixTest);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&cont);
+
+    tlist.AddToList(&split);
+    tlist.AddToList(&filltrain);
+    tlist.AddToList(&conttrain);
+
+    tlist.AddToList(&filltest);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrainTest");
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxev = -1;
+    if (!evtloop.Eventloop(maxev))
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrain->Print("SizeCols");
+    const Int_t generatedtrain = fMatrixTrain->GetM().GetNrows();
+    if (TMath::Abs(generatedtrain-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MCT1FindSupercuts::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtrain 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    fMatrixTest->Print("SizeCols");
+    const Int_t generatedtest = fMatrixTest->GetM().GetNrows();
+    if (TMath::Abs(generatedtest-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MCT1FindSupercuts::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtest 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+
+    *fLog << "training and test matrix were filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+    //--------------------------
+    // write out training matrix
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MCT1FindSupercuts::DefineTrainTestMatrix; Training matrix was written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+    //--------------------------
+    // write out test matrix
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MCT1FindSupercuts::DefineTrainTestMatrix; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read training and test matrices from files
+//
+//
+
+Bool_t MCT1FindSupercuts::ReadMatrix(const TString &filetrain, const TString &filetest)
+{
+  //--------------------------
+  // read in training matrix
+
+  TFile filetr(filetrain);
+  fMatrixTrain->Read("MatrixTrain");
+  fMatrixTrain->Print("SizeCols");
+
+  *fLog << "MCT1FindSupercuts::ReadMatrix; Training matrix was read in from file '"
+        << filetrain << "'" << endl;
+  filetr.Close();
+
+
+  //--------------------------
+  // read in test matrix
+
+  TFile filete(filetest);
+  fMatrixTest->Read("MatrixTest");
+  fMatrixTest->Print("SizeCols");
+
+  *fLog << "MCT1FindSupercuts::ReadMatrix; Test matrix was read in from file '"
+        << filetest << "'" << endl;
+  filete.Close();
+
+  return kTRUE;  
+}
+
+
+//------------------------------------------------------------------------
+//
+// Steering program for optimizing the supercuts
+// ---------------------------------------------
+//
+//      the criterion for the 'optimum' is 
+//
+//          - a maximum significance of the gamma signal in the alpha plot, 
+//            in which the supercuts have been applied
+//
+// The various steps are :
+//
+// - setup the event loop to be executed for each call to fcnSupercuts 
+// - call TMinuit to do the minimization of (-significance) :
+//        the fcnSupercuts function calculates the significance 
+//                                             for the current cut values
+//        for this - the alpha plot is produced in the event loop, 
+//                   in which the cuts have been applied
+//                 - the significance of the gamma signal in the alpha plot 
+//                   is calculated
+//
+// Needed as input : (to be set by the Set functions)
+//
+// - fFilenameParam      name of file to which optimum values of the 
+//                       parameters are written
+//
+// - fHadronnessName     name of container where MCT1SupercutsCalc will
+//                       put the supercuts hadronness
+//
+// - for the minimization, the starting values of the parameters are taken  
+//     - from file parSCinit (if it is != "")
+//     - or from the arrays params and/or steps 
+//
+//----------------------------------------------------------------------
+Bool_t MCT1FindSupercuts::FindParams(TString parSCinit,
+                                     TArrayD &params, TArrayD &steps)
+{
+    // Setup the event loop which will be executed in the 
+    //                 fcnSupercuts function  of MINUIT
+    //
+    // parSCinit is the name of the file containing the initial values 
+    // of the parameters; 
+    // if parSCinit = ""   'params' and 'steps' are taken as initial values
+
+    *fLog << "=============================================" << endl;
+    *fLog << "Setup event loop for fcnSupercuts" << endl;
+
+    if (fHadronnessName.IsNull())
+    {
+      *fLog << "MCT1FindSupercuts::FindParams; hadronness name is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrain == NULL)
+    {
+      *fLog << "MCT1FindSupercuts::FindParams; training matrix is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrain->GetM().GetNrows() <= 0)
+    {
+      *fLog << "MCT1FindSupercuts::FindParams; training matrix has no entries"
+            << endl;
+      return kFALSE;
+    }
+
+    MParList  parlistfcn;
+    MTaskList tasklistfcn;
+
+    // loop over rows of matrix
+    MMatrixLoop loop(fMatrixTrain);
+
+    //--------------------------------
+    // create container for the supercut parameters
+    // and set them to their initial values
+    MCT1Supercuts super;
+
+    // take initial values from file parSCinit
+    if (parSCinit != "")
+    {
+      TFile inparam(parSCinit);
+      super.Read("MCT1Supercuts");
+      inparam.Close();
+      *fLog << "MCT1FindSupercuts::FindParams; initial values of parameters are taken from file "
+            << parSCinit << endl;
+    }
+
+    // take initial values from 'params' and/or 'steps'
+    else if (params.GetSize() != 0  || steps.GetSize()  != 0 )
+    {
+      if (params.GetSize()  != 0)
+      {
+        *fLog << "MCT1FindSupercuts::FindParams; initial values of parameters are taken from 'params'"
+              << endl;
+        super.SetParameters(params);
+      }
+      if (steps.GetSize()  != 0)
+      {
+        *fLog << "MCT1FindSupercuts::FindParams; initial step sizes are taken from 'steps'"
+              << endl;
+        super.SetStepsizes(steps);
+      }
+    }
+    else
+    {
+        *fLog << "MCT1FindSupercuts::FindParams; initial values and step sizes are taken from the MCT1Supercits constructor"
+              << endl;
+    }
+
+
+    //--------------------------------
+    // calculate supercuts hadronness
+    fCalcHadTrain->SetHadronnessName(fHadronnessName);
+
+    // apply the supercuts
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue supercuts(&scfilter);
+
+    // plot |alpha|
+    const TString  mh3Name = "AlphaFcn";
+    MBinning binsalpha("Binning"+mh3Name);
+    binsalpha.SetEdges(54, -12.0, 96.0);
+
+    *fLog << warn << "WARNING------------>ALPHA IS ASSUMED TO BE IN COLUMN 7!!!!!!!!" << endl;
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alpha("MatrixTrain[7]");
+    alpha.SetName(mh3Name);
+
+    MFillH fillalpha(&alpha);
+
+    // book histograms to be filled during the optimization
+    //                              ! not in the event loop !
+    MHCT1Supercuts plotsuper;
+    plotsuper.SetupFill(&parlistfcn);
+
+    //******************************
+    // entries in MParList (extension of old MParList)
+    
+    parlistfcn.AddToList(&tasklistfcn);
+    parlistfcn.AddToList(&super);
+    parlistfcn.AddToList(fCam);
+    parlistfcn.AddToList(fMatrixTrain);
+
+    parlistfcn.AddToList(&binsalpha);
+    parlistfcn.AddToList(&alpha);
+
+    parlistfcn.AddToList(&plotsuper);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklistfcn.AddToList(&loop);
+    tasklistfcn.AddToList(fCalcHadTrain);
+    tasklistfcn.AddToList(&supercuts);
+    tasklistfcn.AddToList(&fillalpha);
+
+
+    //******************************
+
+    MEvtLoop evtloopfcn("EvtLoopFCN");
+    evtloopfcn.SetParList(&parlistfcn);
+    *fLog << "Event loop for fcnSupercuts has been setup" << endl;
+
+    // address of evtloopfcn is used in CallMinuit()
+
+
+    //-----------------------------------------------------------------------
+    //
+    //----------   Start of minimization part   --------------------
+    //
+    // Do the minimization with MINUIT
+    //
+    // Be careful: This is not thread safe
+    //
+    *fLog << "========================================================" << endl;
+    *fLog << "Start minimization for supercuts" << endl;
+
+
+    // -------------------------------------------
+    // prepare call to MINUIT
+    //
+
+    // get initial values of parameters 
+    fVinit = super.GetParameters();
+    fStep  = super.GetStepsizes();
+
+    TString name[fVinit.GetSize()];
+    fStep.Set(fVinit.GetSize());
+    fLimlo.Set(fVinit.GetSize());
+    fLimup.Set(fVinit.GetSize());
+    fFix.Set(fVinit.GetSize());
+
+    fNpar = fVinit.GetSize();
+
+    for (UInt_t i=0; i<fNpar; i++)
+    {
+        name[i]   = "p";
+        name[i]  += i+1;
+        //fStep[i]  = TMath::Abs(fVinit[i]/10.0);
+        fLimlo[i] = -100.0;
+        fLimup[i] =  100.0;
+        fFix[i]   =     0;
+    }
+
+    // these parameters make no sense, fix them at 0.0
+    fVinit[33] = 0.0;
+    fStep[33]  = 0.0;
+    fFix[33]   = 1;
+
+    fVinit[36] = 0.0;
+    fStep[36]  = 0.0;
+    fFix[36]   = 1;
+
+    fVinit[39] = 0.0;
+    fStep[39]  = 0.0;
+    fFix[39]   = 1;
+
+    fVinit[41] = 0.0;
+    fStep[41]  = 0.0;
+    fFix[41]   = 1;
+
+    fVinit[44] = 0.0;
+    fStep[44]  = 0.0;
+    fFix[44]   = 1;
+
+    fVinit[47] = 0.0;
+    fStep[47]  = 0.0;
+    fFix[47]   = 1;
+
+    // vary only first 48 parameters
+    //for (UInt_t i=0; i<fNpar; i++)
+    //{
+    //    if (i >= 48)
+    //	{
+    //      fStep[i] = 0.0;
+    //      fFix[i]  =   1;
+    //	}
+    //}
+ 
+
+    // -------------------------------------------
+    // call MINUIT
+
+    TStopwatch clock;
+    clock.Start();
+
+    *fLog << "before calling CallMinuit" << endl;
+
+    MMinuitInterface inter;               
+    Bool_t rc = inter.CallMinuit(fcnSupercuts, name,
+                                 fVinit, fStep, fLimlo, fLimup, fFix,
+                                 &evtloopfcn, "SIMPLEX", kFALSE);
+ 
+    *fLog << "after calling CallMinuit" << endl;
+
+    *fLog << "Time spent for the minimization in MINUIT :   " << endl;;
+    clock.Stop();
+    clock.Print();
+
+    plotsuper.DrawClone();
+
+    if (!rc)
+        return kFALSE;
+
+    *fLog << "Minimization for supercuts finished" << endl;
+    *fLog << "========================================================" << endl;
+
+
+    // -----------------------------------------------------------------
+    // in 'fcnSupercuts' (IFLAG=3) the optimum parameter values were put 
+    //                    into MCT1Supercuts
+
+    // write optimum parameter values onto file filenameParam
+    
+    TFile outparam(fFilenameParam, "RECREATE"); 
+    super.Write();
+    outparam.Close();
+
+    *fLog << "Optimum parameter values for supercuts were written onto file '"
+              << fFilenameParam << "' :" << endl;
+
+    const TArrayD &check = super.GetParameters();
+    for (Int_t i=0; i<check.GetSize(); i++)
+        *fLog << check[i] << ",  ";
+    *fLog << endl;
+
+
+
+    *fLog << "End of  supercuts optimization part" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
+
+// -----------------------------------------------------------------------
+//
+// Test the supercuts on the test sample
+//
+
+Bool_t MCT1FindSupercuts::TestParams()
+{
+    if (fMatrixTest->GetM().GetNrows() <= 0)
+    {
+        *fLog << "MCT1FindSupercuts::TestParams; test matrix has no entries" 
+              << endl;
+        return kFALSE;
+    }
+
+    // -------------   TEST the supercuts    ------------------------------
+    //
+    *fLog << "Test the supercuts on the test sample" << endl;
+
+    // -----------------------------------------------------------------
+    // read optimum parameter values from file filenameParam
+    // into array 'supercutsPar'
+
+    TFile inparam(fFilenameParam);
+    MCT1Supercuts scin; 
+    scin.Read("MCT1Supercuts");
+    inparam.Close();
+
+    *fLog << "Optimum parameter values for supercuts were read from file '";
+    *fLog << fFilenameParam << "' :" << endl;
+
+    const TArrayD &supercutsPar = scin.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+        *fLog << supercutsPar[i] << ",  ";
+    *fLog << endl;
+    //---------------------------
+
+
+    // -----------------------------------------------------------------
+    if (fHadronnessName.IsNull())
+    {
+        *fLog << "MCT1FindSupercuts::TestParams; hadronness name is not defined... aborting";
+        *fLog << endl;
+        return kFALSE;
+    }
+
+    MParList  parlist2;
+    MTaskList tasklist2;
+
+    MCT1Supercuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+
+    fCalcHadTest->SetHadronnessName(fHadronnessName);
+
+
+    //-------------------------------------------
+
+    MMatrixLoop loop(fMatrixTest);
+
+    // plot alpha before applying the supercuts
+    const TString  mh3NameB = "AlphaBefore";
+    MBinning binsalphabef("Binning"+mh3NameB);
+    binsalphabef.SetEdges(54, -12.0, 96.0);
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alphabefore("MatrixTest[7]");
+    alphabefore.SetName(mh3NameB);
+
+    TH1 &alphahistb = alphabefore.GetHist();
+    alphahistb.SetName("alphaBefore-TestParams");
+
+    MFillH fillalphabefore(&alphabefore);
+    fillalphabefore.SetName("FillAlphaBefore");
+
+    // apply the supercuts
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue applysupercuts(&scfilter);
+
+    // plot alpha after applying the supercuts
+    const TString  mh3NameA = "AlphaAfter";
+    MBinning binsalphaaft("Binning"+mh3NameA);
+    binsalphaaft.SetEdges(54, -12.0, 96.0);
+
+    MH3 alphaafter("MatrixTest[7]");
+    alphaafter.SetName(mh3NameA);
+
+    TH1 &alphahista = alphaafter.GetHist();
+    alphahista.SetName("alphaAfter-TestParams");
+
+    MFillH fillalphaafter(&alphaafter);
+    fillalphaafter.SetName("FillAlphaAfter");
+
+    //******************************
+    // entries in MParList
+
+    parlist2.AddToList(&tasklist2);
+
+    parlist2.AddToList(&supercuts);
+
+    parlist2.AddToList(fCam);
+    parlist2.AddToList(fMatrixTest);
+
+    parlist2.AddToList(&binsalphabef);
+    parlist2.AddToList(&alphabefore);
+
+    parlist2.AddToList(&binsalphaaft);
+    parlist2.AddToList(&alphaafter);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklist2.AddToList(&loop);
+    tasklist2.AddToList(&fillalphabefore);
+
+    tasklist2.AddToList(fCalcHadTest);
+    tasklist2.AddToList(&applysupercuts);
+
+    tasklist2.AddToList(&fillalphaafter);
+
+    //******************************
+
+    MProgressBar bar2;
+    MEvtLoop evtloop2;
+    evtloop2.SetParList(&parlist2);
+    evtloop2.SetName("EvtLoopTestParams");
+    evtloop2.SetProgressBar(&bar2);
+    Int_t maxevents2 = -1;
+    if (!evtloop2.Eventloop(maxevents2))
+        return kFALSE;
+
+    tasklist2.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // draw the alpha plots
+
+    MH3* alphaBefore = (MH3*)parlist2.FindObject(mh3NameB, "MH3");
+    TH1  &alphaHist1 = alphaBefore->GetHist();
+    alphaHist1.SetXTitle("|\\alpha|  [\\circ]");
+
+    MH3* alphaAfter = (MH3*)parlist2.FindObject(mh3NameA, "MH3");
+    TH1  &alphaHist2 = alphaAfter->GetHist();
+    alphaHist2.SetXTitle("|\\alpha|  [\\circ]");
+    alphaHist2.SetName("alpha-TestParams");
+
+    TCanvas *c = new TCanvas("AlphaAfterSC", "AlphaTest", 600, 300);
+    c->Divide(2,1);
+
+    gROOT->SetSelectedPad(NULL);
+
+    c->cd(1);
+    alphaHist1.DrawCopy();
+
+    c->cd(2);
+    alphaHist2.DrawCopy();
+
+
+
+    //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    const Double_t alphasig = 20.0;
+    const Double_t alphamin = 30.0;
+    const Double_t alphamax = 90.0;
+    const Int_t    degree   =    2;
+    const Bool_t   drawpoly  = kTRUE;
+    const Bool_t   fitgauss  = kTRUE;
+    const Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist2, alphamin, alphamax, degree, 
+                      alphasig, drawpoly, fitgauss, print);
+
+    const Double_t significance = findsig.GetSignificance();
+    const Double_t alphasi = findsig.GetAlphasi();
+
+    *fLog << "Significance of gamma signal after supercuts in test sample : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+    //-------------------------------------------
+
+
+    *fLog << "Test of supercuts part finished" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1FindSupercuts.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1FindSupercuts.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1FindSupercuts.h	(revision 9772)
@@ -0,0 +1,130 @@
+#ifndef MARS_MCT1FindSupercuts
+#define MARS_MCT1FindSupercuts
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MFilter;
+class MEvtLoop;
+class MH3;
+class MCT1SupercutsCalc;
+class MGeomCam;
+class MHMatrix;
+/*
+#include "MFilter.h"
+#include "MEvtLoop.h"
+#include "MH3.h"
+#include "MCT1SupercutsCalc.h"
+#include "MGeomCam.h"
+#include "MHMatrix.h"
+*/
+
+class MCT1FindSupercuts : public MParContainer
+{
+private:
+
+  TString fFilenameTrain;
+  TString fFilenameTest;
+
+  Int_t   fHowManyTrain;
+  Int_t   fHowManyTest;
+
+  TString  fFilenameParam;
+
+  TString  fHadronnessName;
+
+  MCT1SupercutsCalc *fCalcHadTrain;
+  MCT1SupercutsCalc *fCalcHadTest;
+
+  MHMatrix          *fMatrixTrain;
+  MHMatrix          *fMatrixTest;
+  MGeomCam          *fCam;
+
+  MEvtLoop *fObjectFit;
+
+  MFilter  *fMatrixFilter; 
+
+  // to comunicate with MINUIT -----------------
+  // attention : dimensions must agree with those in 
+  //             MMinuitInterface::CallMinuit()
+  //char    fParName [80][100];
+  TArrayD fVinit;
+  TArrayD fStep;
+  TArrayD fLimlo;
+  TArrayD fLimup;
+  TArrayI fFix;
+
+  UInt_t     fNpar;
+
+  TString    fMethod;
+
+  Double_t fMin,   fEdm,   fErrdef;
+  Int_t    fNpari, fNparx, fIstat;
+  Int_t    fErrMinimize;
+  //--------------------------------------------
+
+
+public:
+  MCT1FindSupercuts(const char *name=NULL, const char *title=NULL);
+  ~MCT1FindSupercuts();
+
+  void SetFilenameTraining(const TString &name, const Int_t howmany) 
+      {fFilenameTrain = name;  fHowManyTrain = howmany; }
+
+  void SetFilenameTest(const TString &name, const Int_t howmany)     
+      {fFilenameTest     = name;  fHowManyTest  = howmany; }
+
+  void SetFilenameParam(const TString &name)    {fFilenameParam  = name;}
+  void SetHadronnessName(const TString &name)   {fHadronnessName = name;}
+
+  void SetMatrixFilter(MFilter *filter)          {fMatrixFilter = filter;}
+
+  Bool_t DefineTrainMatrix(const TString &name, MH3 &href,
+                           const Int_t howmany, const TString &filetrain); 
+
+  Bool_t DefineTestMatrix(const TString &name, MH3 &href,
+                          const Int_t howmany, const TString &filetest);
+
+  Bool_t DefineTrainTestMatrix(const TString &name, MH3 &href,
+			 const Int_t howmanytrain, const Int_t howmanytest, 
+                         const TString &filetrain, const TString &filetest);
+
+  MHMatrix *GetMatrixTrain() { return fMatrixTrain; }
+  MHMatrix *GetMatrixTest()  { return fMatrixTest;  }
+
+  Bool_t ReadMatrix( const TString &filetrain, const TString &filetest);
+
+  Bool_t FindParams(TString parSCinit, TArrayD &params, TArrayD &steps);
+  Bool_t TestParams();
+
+  ClassDef(MCT1FindSupercuts, 1) // Class for optimization of the Supercuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1PadONOFF.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1PadONOFF.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1PadONOFF.cc	(revision 9772)
@@ -0,0 +1,1819 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 06/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MCT1PadONOFF
+//
+//  This task applies padding such that for a given pixel and for a given
+//  Theta bin the resulting distribution of the pedestal sigma is identical
+//  to the distributions given by fHSigmaPixTheta and fHDiffPixTheta.
+//
+//  The number of photons, its error and the pedestal sigmas are altered.
+//  On average, the number of photons added is zero.
+//
+//  The formulas used can be found in Thomas Schweizer's Thesis,
+//                                    Section 2.2.1
+//
+//  There are 2 options for the padding :
+//
+//  1) fPadFlag = 1 :
+//     Generate first a Sigmabar using the 2D-histogram Sigmabar vs. Theta
+//     (fHSigmaTheta). Then generate a pedestal sigma for each pixel using
+//     the 3D-histogram Theta, pixel no., Sigma^2-Sigmabar^2
+//     (fHDiffPixTheta).
+//
+//     This is the preferred option as it takes into account the
+//     correlations between the Sigma of a pixel and Sigmabar.
+//
+//  2) fPadFlag = 2 :
+//     Generate a pedestal sigma for each pixel using the 3D-histogram
+//     Theta, pixel no., Sigma (fHSigmaPixTheta).
+//
+//
+//  The padding has to be done before the image cleaning because the
+//  image cleaning depends on the pedestal sigmas.
+//
+//  For random numbers gRandom is used.
+//
+//  This implementation has been tested for CT1 data. For MAGIC some
+//  modifications are necessary.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1PadONOFF.h"
+
+#include <math.h>
+#include <stdio.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+#include <TFile.h>
+
+#include "MBinning.h"
+#include "MSigmabar.h"
+#include "MMcEvt.hxx"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MBlindPixels.h"
+
+#include "MRead.h"
+#include "MFilterList.h"
+#include "MTaskList.h"
+#include "MBlindPixelCalc.h"
+#include "MHBlindPixels.h"
+#include "MFillH.h"
+#include "MHSigmaTheta.h"
+#include "MEvtLoop.h"
+
+ClassImp(MCT1PadONOFF);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCT1PadONOFF::MCT1PadONOFF(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MCT1PadONOFF";
+  fTitle = title ? title : "Task for the ON-OFF padding";
+
+  fPadFlag = 1;
+  *fLog << "MCT1PadONOFF: fPadFlag = " << fPadFlag << endl;
+
+  fType = "";
+
+  fHSigmaTheta       = NULL;
+  fHSigmaThetaON     = NULL;
+  fHSigmaThetaOFF    = NULL;
+
+  fHSigmaPixTheta    = NULL;
+  fHSigmaPixThetaON  = NULL;
+  fHSigmaPixThetaOFF = NULL;
+
+  fHDiffPixTheta     = NULL;
+  fHDiffPixThetaON   = NULL;
+  fHDiffPixThetaOFF  = NULL;
+
+  fHgON  = NULL;
+  fHgOFF = NULL;
+
+  fHBlindPixIdTheta = NULL;
+  fHBlindPixNTheta  = NULL;
+
+  fHSigmaPedestal = NULL;
+  fHPhotons       = NULL;
+  fHNSB           = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MCT1PadONOFF::~MCT1PadONOFF()
+{
+  if (fHBlindPixIdTheta   != NULL) delete fHBlindPixIdTheta;
+  if (fHBlindPixNTheta    != NULL) delete fHBlindPixNTheta;
+
+  if (fHSigmaTheta    != NULL) delete fHSigmaTheta;
+  if (fHSigmaPixTheta != NULL) delete fHSigmaPixTheta;
+  if (fHDiffPixTheta  != NULL) delete fHDiffPixTheta;
+
+  if (fHSigmaPedestal != NULL) delete fHSigmaPedestal;
+  if (fHPhotons       != NULL) delete fHPhotons;
+  if (fHNSB           != NULL) delete fHNSB;
+
+  if (fInfile         != NULL) delete fInfile;
+}
+
+// --------------------------------------------------------------------------
+//
+// Merge the distributions of ON and OFF data
+//
+//   fHSigmaTheta    2D-histogram  (Theta, sigmabar)
+//   fHSigmaPixTheta 3D-hiostogram (Theta, pixel, sigma)
+//   fHDiffPixTheta  3D-histogram  (Theta, pixel, sigma^2-sigmabar^2)
+//   fHBlindPixIdTheta 2D-histogram  (Theta, blind pixel Id)
+//   fHBlindPixNTheta  2D-histogram  (Theta, no.of blind pixels )
+//
+// and define the target distributions for the padding
+//
+Bool_t MCT1PadONOFF::MergeHistograms(TH2D *sigthon,     TH2D *sigthoff,
+                                  TH3D *sigpixthon,  TH3D *sigpixthoff,
+                                  TH3D *diffpixthon, TH3D *diffpixthoff,
+                                  TH2D *blindidthon, TH2D *blindidthoff,
+                                  TH2D *blindnthon,  TH2D *blindnthoff)
+{
+  *fLog << "----------------------------------------------------------------------------------" << endl;
+  *fLog << "Merge the ON and OFF histograms to obtain the target distributions for the padding"
+        << endl;
+
+  //-------------------------------------------------------------
+  // merge the distributions of ON and OFF events
+  // to obtain the target distribution fHSigmaTheta
+  //
+
+  Double_t eps = 1.e-10;
+
+  fHSigmaTheta = new TH2D( (TH2D&)*sigthon );
+  fHSigmaTheta->SetNameTitle("2D-ThetaSigmabar", "2D-ThetaSigmabar (target)");
+
+  // get binning for fHgON and fHgOFF from sigthon
+  // binning in Theta
+  TAxis *ax = sigthon->GetXaxis();
+  Int_t nbinstheta = ax->GetNbins();
+  TArrayD edgesx;
+  edgesx.Set(nbinstheta+1);
+  for (Int_t i=0; i<=nbinstheta; i++)
+  {
+    edgesx[i] = ax->GetBinLowEdge(i+1);
+    // *fLog << "i, theta low edge = " << i << ",  " << edgesx[i] << endl; 
+  }
+  MBinning binth;
+  binth.SetEdges(edgesx);
+
+  // binning in sigmabar
+  TAxis *ay = sigthon->GetYaxis();
+  Int_t nbinssig = ay->GetNbins();
+  TArrayD edgesy;
+  edgesy.Set(nbinssig+1);
+  for (Int_t i=0; i<=nbinssig; i++)
+  {
+    edgesy[i] = ay->GetBinLowEdge(i+1); 
+    // *fLog << "i, sigmabar low edge = " << i << ",  " << edgesy[i] << endl; 
+  }
+  MBinning binsg;
+  binsg.SetEdges(edgesy);
+
+
+  fHgON = new TH3D;
+  MH::SetBinning(fHgON, &binth, &binsg, &binsg);
+  fHgON->SetNameTitle("3D-PaddingMatrixON", "3D-PadMatrixThetaON");
+
+  fHgOFF = new TH3D;
+  MH::SetBinning(fHgOFF, &binth, &binsg, &binsg);
+  fHgOFF->SetNameTitle("3D-PaddingMatrixOFF", "3D-PadMatrixThetaOFF");
+
+  //............   loop over Theta bins   ...........................
+
+  // hista is the normalized 1D histogram of sigmabar for ON data
+  // histb is the normalized 1D histogram of sigmabar for OFF data
+  // histc is the difference ON-OFF
+
+  // at the beginning, histap is a copy of hista
+  // at the end, it will be the 1D histogram for ON data after padding
+
+  // at the beginning, histbp is a copy of histb
+  // at the end, it will be the 1D histogram for OFF data after padding
+
+  // at the beginning, histcp is a copy of histc
+  // at the end, it should be zero
+
+  *fLog << "MCT1PadONOFF::MergeHistograms; bins of Theta, Sigmabarold, Sigmabarnew, fraction of events to be padded" << endl;
+  for (Int_t l=1; l<=nbinstheta; l++)
+  {
+    TH1D *hista  = sigthon->ProjectionY("sigon_y", l, l, "");
+    Stat_t suma = hista->Integral();
+    hista->Scale(1./suma);
+
+    TH1D *histap  = new TH1D( (const TH1D&)*hista );
+
+    TH1D *histb  = sigthoff->ProjectionY("sigoff_y", l, l, "");
+    Stat_t sumb = histb->Integral();
+    histb->Scale(1./sumb);
+
+    TH1D *histbp  = new TH1D( (const TH1D&)*histb );
+
+    TH1D *histc   = new TH1D( (const TH1D&)*hista );
+    histc->Add(histb, -1.0);
+
+    TH1D *histcp  = new TH1D( (const TH1D&)*histc );    
+
+
+  // calculate matrix g
+
+  // fHg[k][j] (if <0.0) tells how many ON events in bin k should be padded
+  //              from sigma_k to sigma_j
+
+
+  // fHg[k][j] (if >0.0) tells how many OFF events in bin k should be padded
+  //              from sigma_k to sigma_j
+
+  //--------   start j loop   ------------------------------------------------
+  // loop over bins in histc, starting from the end
+  Double_t v, s, w, t, x, u, a, b, c, arg;
+
+  for (Int_t j=nbinssig; j >= 1; j--)
+  {
+    v = histcp->GetBinContent(j);
+    if ( fabs(v) < eps ) continue;
+    if (v >= 0.0) 
+      s = 1.0;
+    else
+      s = -1.0;
+
+    //................   start k loop   ......................................
+    // look for a bin k which may compensate the content of bin j
+    for (Int_t k=j-1; k >= 1; k--)
+    {
+      w = histcp->GetBinContent(k);
+      if ( fabs(w) < eps ) continue;
+      if (w >= 0.0) 
+        t = 1.0;
+      else
+        t = -1.0;
+
+      if (s==t) continue;
+
+      x = v + w;
+      if (x >= 0.0) 
+        u = 1.0;
+      else
+        u = -1.0;
+
+      if (u == s)
+      {
+        arg = -w;
+
+        if (arg <=0.0)
+	{
+          fHgON->SetBinContent (l, k, j, -arg);
+          fHgOFF->SetBinContent(l, k, j,  0.0);
+	}
+        else
+	{
+          fHgON->SetBinContent (l, k, j,  0.0);
+          fHgOFF->SetBinContent(l, k, j,  arg);
+	}
+
+
+        *fLog << "l, k, j, arg = " << l << ",  " << k << ",  " << j 
+              << ",  " << arg << endl;
+
+	//        g(k-1, j-1)   = arg;
+        //cout << "k-1, j-1, arg = " << k-1 << ",  " << j-1 << ",  " 
+        //     << arg << endl;
+
+        //......................................
+        // this is for checking the procedure
+        if (arg < 0.0)
+        {
+          a = histap->GetBinContent(k);
+          histap->SetBinContent(k, a+arg);
+          a = histap->GetBinContent(j);
+          histap->SetBinContent(j, a-arg);
+        }
+        else
+        {
+          b = histbp->GetBinContent(k);
+          histbp->SetBinContent(k, b-arg);
+          b = histbp->GetBinContent(j);
+          histbp->SetBinContent(j, b+arg);
+        }
+        //......................................
+
+        histcp->SetBinContent(k, 0.0);
+        histcp->SetBinContent(j,   x);
+
+        //......................................
+        // redefine v 
+        v = histcp->GetBinContent(j);
+        if ( fabs(v) < eps ) break;
+        if (v >= 0.0) 
+          s = 1.0;
+        else
+          s = -1.0;
+        //......................................
+       
+        continue;
+      }
+
+      arg = v;
+
+      if (arg <=0.0)
+      {
+        fHgON->SetBinContent (l, k, j, -arg);
+        fHgOFF->SetBinContent(l, k, j,  0.0);
+      }
+      else
+      {
+        fHgON->SetBinContent (l, k, j,  0.0);
+        fHgOFF->SetBinContent(l, k, j,  arg);
+      }
+
+      *fLog << "l, k, j, arg = " << l << ",  " << k << ",  " << j 
+            << ",  " << arg << endl;
+
+      //g(k-1, j-1) = arg;
+      //cout << "k-1, j-1, arg = " << k-1 << ",  " << j-1 << ",  " 
+      //     << arg << endl;
+
+      //......................................
+      // this is for checking the procedure
+      if (arg < 0.0)
+      {
+        a = histap->GetBinContent(k);
+        histap->SetBinContent(k, a+arg);
+        a = histap->GetBinContent(j);
+        histap->SetBinContent(j, a-arg);
+      }
+      else
+      {
+        b = histbp->GetBinContent(k);
+
+        histbp->SetBinContent(k, b-arg);
+        b = histbp->GetBinContent(j);
+        histbp->SetBinContent(j, b+arg);
+      }
+      //......................................
+
+      histcp->SetBinContent(k,   x);
+      histcp->SetBinContent(j, 0.0);
+
+      break;
+    }
+    //................   end k loop   ......................................
+  } 
+  //--------   end j loop   ------------------------------------------------
+
+  // check results for this Theta bin
+  for (Int_t j=1; j<=nbinssig; j++)
+  {
+    a = histap->GetBinContent(j);
+    b = histbp->GetBinContent(j);
+    c = histcp->GetBinContent(j);
+
+    if( fabs(a-b)>3.0*eps  ||  fabs(c)>3.0*eps )
+      *fLog << "MCT1PadONOFF::Read; inconsistency in results; a, b, c = "
+            << a << ",  " << b << ",  " << c << endl;
+  }
+    
+
+  // fill target distribution SigmaTheta
+  // for this Theta bin
+  //
+  for (Int_t j=1; j<=nbinssig; j++)
+  {
+    a = histap->GetBinContent(j);
+    fHSigmaTheta->SetBinContent(l, j, a);
+  }
+
+  delete hista;
+  delete histb;
+  delete histc;
+
+  delete histap;
+  delete histbp;
+  delete histcp;
+  }
+  //............   end of loop over Theta bins   ....................
+
+  
+  // target distributions for MC
+  //        SigmaPixTheta and DiffPixTheta
+  //        BlindPixIdTheta and BlindPixNTheta     
+  // are calculated as averages of the ON and OFF distributions
+
+  fHSigmaThetaON = sigthon;
+  fHSigmaThetaON->SetNameTitle("2D-ThetaSigmabarON", "2D-ThetaSigmabarON (target)");
+
+  fHSigmaThetaOFF = sigthoff;
+  fHSigmaThetaOFF->SetNameTitle("2D-ThetaSigmabarOFF", "2D-ThetaSigmabarOFF (target)");
+
+
+  fHBlindPixNTheta = new TH2D( (TH2D&)*blindnthon );
+  fHBlindPixNTheta->SetNameTitle("2D-ThetaBlindN", "2D-ThetaBlindN (target)");
+
+  fHBlindPixIdTheta = new TH2D( (TH2D&)*blindidthon );
+  fHBlindPixIdTheta->SetNameTitle("2D-ThetaBlindId", "2D-ThetaBlindId (target)");
+
+  fHSigmaPixTheta = new TH3D( (TH3D&)*sigpixthon );
+  fHSigmaPixTheta->SetNameTitle("3D-ThetaPixSigma", "3D-ThetaPixSigma (target)");
+
+  fHSigmaPixThetaON = sigpixthon;
+  fHSigmaPixThetaON->SetNameTitle("3D-ThetaPixSigmaON", "3D-ThetaPixSigmaON (target)");
+
+  fHSigmaPixThetaOFF = sigpixthoff;
+  fHSigmaPixThetaOFF->SetNameTitle("3D-ThetaPixSigmaOFF", "3D-ThetaPixSigmaOFF (target)");
+
+  fHDiffPixTheta = new TH3D( (TH3D&)*diffpixthon );
+  fHDiffPixTheta->SetNameTitle("3D-ThetaPixDiff", "3D-ThetaPixDiff (target)");
+
+  fHDiffPixThetaON = diffpixthon;
+  fHDiffPixThetaON->SetNameTitle("3D-ThetaPixDiffON", "3D-ThetaPixDiffON (target)");
+
+  fHDiffPixThetaOFF = diffpixthoff;
+  fHDiffPixThetaOFF->SetNameTitle("3D-ThetaPixDiffOFF", "3D-ThetaPixDiffOFF (target)");
+
+
+  for (Int_t j=1; j<=nbinstheta; j++)
+  {
+    // fraction of ON/OFF events to be padded to a sigmabar 
+    // of the OFF/ON events : fracON, fracOFF
+
+    Double_t fracON  = fHgON->Integral (j, j, 1, nbinssig, 1, nbinssig, "");
+    Double_t fracOFF = fHgOFF->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+
+    TAxis *ax;
+    TAxis *ay;
+    TAxis *az;
+
+    Double_t entON;
+    Double_t entOFF;
+
+    Double_t normON;
+    Double_t normOFF;
+
+    // set ranges for 2D-projections of 3D-histograms
+    ax = sigpixthon->GetXaxis();
+    ax->SetRange(j, j);
+    ax = sigpixthoff->GetXaxis();
+    ax->SetRange(j, j);
+
+    ax = diffpixthon->GetXaxis();
+    ax->SetRange(j, j);
+    ax = diffpixthoff->GetXaxis();
+    ax->SetRange(j, j);
+
+    TH2D *hist;
+    TH2D *histOFF;
+
+    TH1D *hist1;
+    TH1D *hist1OFF;
+
+    // weights for ON and OFF distrubtions when
+    // calculating the weighted average
+    Double_t facON  = 0.5 * (1. - fracON + fracOFF);
+    Double_t facOFF = 0.5 * (1. + fracON - fracOFF);
+  
+    *fLog << fracON << ",  " << fracOFF << ",  "
+          << facON  << ",  " << facOFF  << endl; 
+    //-------------------------------------------
+    ay = blindnthon->GetYaxis();
+    Int_t nbinsn = ay->GetNbins();
+
+    hist1    = (TH1D*)blindnthon->ProjectionY ("", j, j, "");
+    hist1->SetName("dummy");
+    hist1OFF = (TH1D*)blindnthoff->ProjectionY("", j, j, "");
+
+    // number of events in this theta bin
+    entON  = hist1->Integral();
+    entOFF = hist1OFF->Integral();
+
+    *fLog << "BlindPixNTheta : j, entON, entOFF = " << j << ",  " 
+          << entON  << ",  " << entOFF  << endl;
+
+    normON  = entON<=0.0  ? 0.0 : 1.0/entON;
+    normOFF = entOFF<=0.0 ? 0.0 : 1.0/entOFF;
+
+    hist1->Scale(normON);
+    hist1OFF->Scale(normOFF);
+
+    // weighted average of ON and OFF distributions
+    hist1->Scale(facON);
+    hist1->Add(hist1OFF, facOFF); 
+
+    for (Int_t k=1; k<=nbinsn; k++)
+      {
+        Double_t cont = hist1->GetBinContent(k);
+        fHBlindPixNTheta->SetBinContent(j, k, cont);  
+      }
+
+    delete hist1;
+    delete hist1OFF;
+
+    //-------------------------------------------
+    ay = blindidthon->GetYaxis();
+    Int_t nbinsid = ay->GetNbins();
+
+    hist1    = (TH1D*)blindidthon->ProjectionY ("", j, j, "");
+    hist1->SetName("dummy");
+    hist1OFF = (TH1D*)blindidthoff->ProjectionY("", j, j, "");
+
+    hist1->Scale(normON);
+    hist1OFF->Scale(normOFF);
+
+    // weighted average of ON and OFF distributions
+    hist1->Scale(facON);
+    hist1->Add(hist1OFF, facOFF); 
+
+    for (Int_t k=1; k<=nbinsid; k++)
+      {
+        Double_t cont = hist1->GetBinContent(k);
+        fHBlindPixIdTheta->SetBinContent(j, k, cont);  
+      }
+
+    delete hist1;
+    delete hist1OFF;
+
+    //-------------------------------------------
+    ay = sigpixthon->GetYaxis();
+    Int_t nbinspix = ay->GetNbins();
+
+    az = sigpixthon->GetZaxis();
+    Int_t nbinssigma = az->GetNbins();
+
+    hist    = (TH2D*)sigpixthon->Project3D("zy");
+    hist->SetName("dummy");
+    histOFF = (TH2D*)sigpixthoff->Project3D("zy");
+
+    hist->Scale(normON);
+    histOFF->Scale(normOFF);
+
+    // weighted average of ON and OFF distributions
+
+    hist->Scale(facON);
+    hist->Add(histOFF, facOFF); 
+
+    for (Int_t k=1; k<=nbinspix; k++)
+      for (Int_t l=1; l<=nbinssigma; l++)
+      {
+        Double_t cont = hist->GetBinContent(k,l);
+        fHSigmaPixTheta->SetBinContent(j, k, l, cont);  
+      }
+
+    delete hist;
+    delete histOFF;
+
+    //-------------------------------------------
+    ay = diffpixthon->GetYaxis();
+    Int_t nbinspixel = ay->GetNbins();
+
+    az = diffpixthon->GetZaxis();
+    Int_t nbinsdiff = az->GetNbins();
+
+    hist    = (TH2D*)diffpixthon->Project3D("zy");
+    hist->SetName("dummy");
+    histOFF = (TH2D*)diffpixthoff->Project3D("zy");
+
+    hist->Scale(normON);
+    histOFF->Scale(normOFF);
+
+    // weighted average of ON and OFF distributions
+    hist->Scale(facON);
+    hist->Add(histOFF, facOFF); 
+
+    for (Int_t k=1; k<=nbinspixel; k++)
+      for (Int_t l=1; l<=nbinsdiff; l++)
+      {
+        Double_t cont = hist->GetBinContent(k,l);
+        fHDiffPixTheta->SetBinContent(j, k, l, cont);  
+      }
+
+    delete hist;
+    delete histOFF;
+
+    //-------------------------------------------
+  }
+
+
+  *fLog << "The target distributions for the padding have been created" 
+        << endl;
+  *fLog << "----------------------------------------------------------" 
+        << endl;
+  //--------------------------------------------
+
+  fHSigmaTheta->SetDirectory(NULL);
+  fHSigmaThetaON->SetDirectory(NULL);
+  fHSigmaThetaOFF->SetDirectory(NULL);
+
+  fHSigmaPixTheta->SetDirectory(NULL);
+  fHSigmaPixThetaON->SetDirectory(NULL);
+  fHSigmaPixThetaOFF->SetDirectory(NULL);
+
+  fHDiffPixTheta->SetDirectory(NULL);
+  fHDiffPixThetaON->SetDirectory(NULL);
+  fHDiffPixThetaOFF->SetDirectory(NULL);
+
+  fHBlindPixIdTheta->SetDirectory(NULL);
+  fHBlindPixNTheta->SetDirectory(NULL);
+
+
+  fHgON->SetDirectory(NULL);
+  fHgOFF->SetDirectory(NULL);
+
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Read target distributions from a file
+//
+//
+Bool_t MCT1PadONOFF::ReadTargetDist(const char* namefilein)
+{
+  *fLog << "Read padding histograms from file " << namefilein << endl;
+
+  fInfile = new TFile(namefilein);
+  fInfile->ls();
+
+    //------------------------------------
+
+      fHSigmaTheta = 
+      (TH2D*) gROOT->FindObject("2D-ThetaSigmabar");
+      if (!fHSigmaTheta)
+	{
+          *fLog << "Object '2D-ThetaSigmabar' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '2D-ThetaSigmabar' was read in" << endl;
+
+      fHSigmaThetaON = 
+      (TH2D*) gROOT->FindObject("2D-ThetaSigmabarON");
+      if (!fHSigmaThetaON)
+	{
+          *fLog << "Object '2D-ThetaSigmabarON' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '2D-ThetaSigmabarON' was read in" << endl;
+
+      fHSigmaThetaOFF = 
+      (TH2D*) gROOT->FindObject("2D-ThetaSigmabarOFF");
+      if (!fHSigmaThetaOFF)
+	{
+          *fLog << "Object '2D-ThetaSigmabarOFF' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '2D-ThetaSigmabarOFF' was read in" << endl;
+
+      fHSigmaPixTheta = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigma");
+      if (!fHSigmaPixTheta)
+	{
+          *fLog << "Object '3D-ThetaPixSigma' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '3D-ThetaPixSigma' was read in" << endl;
+
+      fHSigmaPixThetaON = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigmaON");
+      if (!fHSigmaPixThetaON)
+	{
+          *fLog << "Object '3D-ThetaPixSigmaON' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '3D-ThetaPixSigmaON' was read in" << endl;
+
+      fHSigmaPixThetaOFF = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigmaOFF");
+      if (!fHSigmaPixThetaOFF)
+	{
+          *fLog << "Object '3D-ThetaPixSigmaOFF' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '3D-ThetaPixSigmaOFF' was read in" << endl;
+
+      fHDiffPixTheta = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiff");
+      if (!fHDiffPixTheta)
+	{
+          *fLog << "Object '3D-ThetaPixDiff' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '3D-ThetaPixDiff' was read in" << endl;
+
+      fHDiffPixThetaON = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiffON");
+      if (!fHDiffPixThetaON)
+	{
+          *fLog << "Object '3D-ThetaPixDiffON' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '3D-ThetaPixDiffON' was read in" << endl;
+
+      fHDiffPixThetaOFF = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiffOFF");
+      if (!fHDiffPixThetaOFF)
+	{
+          *fLog << "Object '3D-ThetaPixDiffOFF' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '3D-ThetaPixDiffOFF' was read in" << endl;
+
+      fHgON = 
+      (TH3D*) gROOT->FindObject("3D-PaddingMatrixON");
+      if (!fHgON)
+	{
+          *fLog << "Object '3D-PaddingMatrixON' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '3D-PaddingMatrixON' was read in" << endl;
+
+      fHgOFF = 
+      (TH3D*) gROOT->FindObject("3D-PaddingMatrixOFF");
+      if (!fHgOFF)
+	{
+          *fLog << "Object '3D-PaddingMatrixOFF' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '3D-PaddingMatrixOFF' was read in" << endl;
+
+
+      fHBlindPixIdTheta = 
+      (TH2D*) gROOT->FindObject("2D-ThetaBlindId");
+      if (!fHBlindPixIdTheta)
+	{
+          *fLog << "Object '2D-ThetaBlindId' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '2D-ThetaBlindId' was read in" << endl;
+
+      fHBlindPixNTheta = 
+      (TH2D*) gROOT->FindObject("2D-ThetaBlindN");
+      if (!fHBlindPixNTheta)
+	{
+          *fLog << "Object '2D-ThetaBlindN' not found on root file" << endl;
+          return kFALSE;
+	}
+      *fLog << "Object '2D-ThetaBlindN' was read in" << endl;
+
+
+    //------------------------------------
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Write target distributions onto a file
+//
+//
+Bool_t MCT1PadONOFF::WriteTargetDist(const char* namefileout)
+{
+  *fLog << "Write padding histograms onto file " << namefileout << endl;
+
+  TFile outfile(namefileout, "RECREATE");
+
+  fHBlindPixNTheta->Write();
+  fHBlindPixIdTheta->Write();
+
+  fHSigmaTheta->Write();
+  fHSigmaThetaON->Write();
+  fHSigmaThetaOFF->Write();
+
+  fHSigmaPixTheta->Write();
+  fHSigmaPixThetaON->Write();
+  fHSigmaPixThetaOFF->Write();
+
+  fHDiffPixTheta->Write();
+  fHDiffPixThetaON->Write();
+  fHDiffPixThetaOFF->Write();
+
+  fHgON->Write();
+  fHgOFF->Write();
+
+  *fLog << "MCT1PadONOFF::WriteTargetDist; target histograms written onto file "
+        << namefileout << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set type of data to be padded
+//
+//     this is not necessary if the type of the data can be recognized
+//     directly from the input
+//
+//
+void MCT1PadONOFF::SetDataType(const char* type)
+{
+  fType = type;
+  *fLog << "MCT1PadONOFF::SetDataType(); type of data to be padded : " 
+        << fType << endl; 
+
+  return;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the option for the padding
+//
+//  There are 2 options for the padding :
+//
+//  1) fPadFlag = 1 :
+//     Generate first a Sigmabar using the 2D-histogram Sigmabar vs. Theta
+//     (fHSigmaTheta). Then generate a pedestal sigma for each pixel using
+//     the 3D-histogram Theta, pixel no., Sigma^2-Sigmabar^2
+//     (fHDiffPixTheta).
+//
+//     This is the preferred option as it takes into account the
+//     correlations between the Sigma of a pixel and Sigmabar.
+//
+//  2) fPadFlag = 2 :
+//     Generate a pedestal sigma for each pixel using the 3D-histogram
+//     Theta, pixel no., Sigma (fHSigmaPixTheta).
+//
+void MCT1PadONOFF::SetPadFlag(Int_t padflag)
+{
+  fPadFlag = padflag;
+  *fLog << "MCT1PadONOFF::SetPadFlag(); choose option " << fPadFlag << endl; 
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the pointers and prepare the histograms
+//
+Int_t MCT1PadONOFF::PreProcess(MParList *pList)
+{
+  if ( !fHSigmaTheta       ||  !fHSigmaThetaON    ||  !fHSigmaThetaOFF    ||  
+       !fHSigmaPixTheta    ||  !fHSigmaPixThetaON ||  !fHSigmaPixThetaOFF ||
+       !fHDiffPixTheta     ||  !fHDiffPixThetaON  ||  !fHDiffPixThetaOFF  ||
+       !fHBlindPixIdTheta  ||  !fHBlindPixNTheta  ||
+       !fHgON              ||  !fHgOFF)
+  { 
+       *fLog << err << "At least one of the histograms needed for the padding is not defined ... aborting." << endl;
+       return kFALSE;
+  }
+
+  fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+  if (!fMcEvt)
+    {
+       *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+       return kFALSE;
+     }
+  
+   fPed = (MPedPhotCam*)pList->FindObject("MPedPhotCam");
+   if (!fPed)
+     {
+       *fLog << err << "MPedPhotCam not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+   if (!fCam)
+     {
+       *fLog << err << "MGeomCam not found (no geometry information available)... aborting." << endl;
+       return kFALSE;
+     }
+  
+   fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+   if (!fEvt)
+     {
+       *fLog << err << "MCerPhotEvt not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fSigmabar = (MSigmabar*)pList->FindCreateObj("MSigmabar");
+   if (!fSigmabar)
+     {
+       *fLog << err << "MSigmabar not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fBlinds = (MBlindPixels*)pList->FindCreateObj("MBlindPixels");
+   if (!fBlinds)
+     {
+       *fLog << err << "MBlindPixels not found... aborting." << endl;
+       return kFALSE;
+     }
+   
+   if (fType !="ON"  &&  fType !="OFF"  &&  fType !="MC")
+     {
+       *fLog << err << "Type of data to be padded not defined... aborting." << endl;
+       return kFALSE;
+     }
+
+
+   //--------------------------------------------------------------------
+   // histograms for checking the padding
+   //
+   // plot pedestal sigmas
+   fHSigmaPedestal = new TH2D("SigPed","Sigma: after vs. before padding", 
+                     100, 0.0, 5.0, 100, 0.0, 5.0);
+   fHSigmaPedestal->SetXTitle("Pedestal sigma before padding");
+   fHSigmaPedestal->SetYTitle("Pedestal sigma after padding");
+
+   // plot no.of photons (before vs. after padding) 
+   fHPhotons = new TH2D("Photons","Photons: after vs.before padding", 
+                        100, -10.0, 90.0, 100, -10, 90);
+   fHPhotons->SetXTitle("no.of photons before padding");
+   fHPhotons->SetYTitle("no.of photons after padding");
+
+   // plot of added NSB
+   fHNSB = new TH1D("NSB","Distribution of added NSB", 100, -10.0, 10.0);
+   fHNSB->SetXTitle("no.of added NSB photons");
+   fHNSB->SetYTitle("no.of pixels");
+
+
+   //--------------------------------------------------------------------
+
+   fIter = 20;
+
+   memset(fErrors, 0, sizeof(fErrors));
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the Padding
+// idealy the events to be padded should have been generated without NSB
+// 
+Int_t MCT1PadONOFF::Process()
+{
+  // *fLog << "Entry MCT1PadONOFF::Process();" << endl;
+
+  //------------------------------------------------
+  // add pixels to MCerPhotEvt which are not yet in;
+  // set their number of photons equal to zero
+
+  UInt_t imaxnumpix = fCam->GetNumPixels();
+
+  for (UInt_t i=0; i<imaxnumpix; i++)
+  {
+    Bool_t alreadythere = kFALSE;
+    UInt_t npix = fEvt->GetNumPixels();
+    for (UInt_t j=0; j<npix; j++)
+    {
+      MCerPhotPix &pix = (*fEvt)[j];
+      UInt_t id = pix.GetPixId();
+      if (i==id)
+      {
+        alreadythere = kTRUE;
+        break;
+      }
+    }
+    if (alreadythere)
+      continue;
+
+    fEvt->AddPixel(i, 0.0, (*fPed)[i].GetRms());
+  }
+
+
+
+  //-----------------------------------------
+  Int_t rc=0;
+  Int_t rw=0;
+
+  const UInt_t npix = fEvt->GetNumPixels();
+
+  //fSigmabar->Calc(*fCam, *fPed, *fEvt);
+  // *fLog << "before padding : " << endl;
+  //fSigmabar->Print("");
+
+
+  //$$$$$$$$$$$$$$$$$$$$$$$$$$
+  // to simulate the situation that before the padding the NSB and 
+  // electronic noise are zero : set Sigma = 0 for all pixels
+  //for (UInt_t i=0; i<npix; i++) 
+  //{   
+  //  MCerPhotPix &pix = fEvt->operator[](i);      
+  //  Int_t j = pix.GetPixId();
+
+  //  MPedPhotPix &ppix = fPed->operator[](j);
+  //  ppix.SetRms(0.0);
+  //}
+  //$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+  //-------------------------------------------
+  // Calculate average sigma of the event
+  //
+  Double_t sigbarold = fSigmabar->Calc(*fCam, *fPed, *fEvt);
+  Double_t sigbarold2 = sigbarold*sigbarold;
+  //fSigmabar->Print("");
+
+  // for MC data : expect sigmabar to be zero before the padding
+  if (fType == "MC")
+  {
+    if (sigbarold > 0)
+    {
+      // *fLog << "MCT1PadONOFF::Process(); sigmabar of event to be padded is > 0 : "
+      //      << sigbarold << ". Stop event loop " << endl;
+      // input data should have sigmabar = 0; stop event loop
+  
+      rc = 1;
+      fErrors[rc]++;
+      return kCONTINUE; 
+    }
+  }
+
+  const Double_t theta = kRad2Deg*fMcEvt->GetTelescopeTheta();
+  // *fLog << "theta = " << theta << endl;
+
+  Int_t binTheta = fHBlindPixNTheta->GetXaxis()->FindBin(theta);
+  if ( binTheta < 1  ||  binTheta > fHBlindPixNTheta->GetNbinsX() )
+  {
+    // *fLog << "MCT1PadONOFF::Process(); binNumber out of range : theta, binTheta = "
+    //      << theta << ",  " << binTheta << ";  Skip event " << endl;
+    // event cannot be padded; skip event
+
+    rc = 2;
+    fErrors[rc]++;
+    return kCONTINUE;
+  }
+
+  //-------------------------------------------
+  // get number of events in this theta bin
+  // and number of events in this sigbarold bin
+
+  Double_t nTheta;
+  Double_t nSigma;
+  if (fType == "ON")
+  {
+    TH1D *hn;
+
+    hn = fHSigmaThetaON->ProjectionY("", binTheta, binTheta, "");
+    nTheta = hn->Integral();
+    Int_t binSigma = hn->FindBin(sigbarold);
+    nSigma = hn->GetBinContent(binSigma);
+
+    // *fLog << "Theta, sigbarold, binTheta, binSigma, nTheta, nSigma = "
+    //      << theta << ",  " << sigbarold << ",  " << binTheta << ",  "
+    //      << binSigma << ",  " << nTheta << ",  " << nSigma   << endl;      
+
+    delete hn;
+  }
+
+  else if (fType == "OFF")
+  {
+    TH1D *hn;
+
+    hn = fHSigmaThetaOFF->ProjectionY("", binTheta, binTheta, "");
+    nTheta = hn->Integral();
+    Int_t binSigma = hn->FindBin(sigbarold);
+    nSigma = hn->GetBinContent(binSigma);
+
+    // *fLog << "Theta, sigbarold, binTheta, binSigma, nTheta, nSigma = "
+    //      << theta << ",  " << sigbarold << ",  " << binTheta << ",  "
+    //      << binSigma << ",  " << nTheta << ",  " << nSigma   << endl;      
+
+    delete hn;
+  }
+
+  else
+  {
+    nTheta = 0.0;
+    nSigma = 0.0;
+  }
+
+  //-------------------------------------------
+  // for the current theta, 
+  // generate blind pixels according to the histograms 
+  //          fHBlindPixNTheta and fHBlindPixIDTheta
+  // do this only for MC data
+
+
+  if (fType == "MC")
+  {
+
+  // numBlind is the number of blind pixels in this event
+  TH1D *nblind;
+  UInt_t numBlind;
+
+  nblind = fHBlindPixNTheta->ProjectionY("", binTheta, binTheta, "");
+  if ( nblind->Integral() == 0.0 )
+  {
+    // *fLog << "MCT1PadONOFF::Process(); projection for Theta bin " 
+    //      << binTheta << " has no entries; Skip event " << endl;
+    // event cannot be padded; skip event
+    delete nblind;
+
+    rc = 7;
+    fErrors[rc]++;
+    return kCONTINUE;
+  }
+  else
+  {
+    numBlind = (Int_t) (nblind->GetRandom()+0.5);
+  }
+  delete nblind;
+
+  //warn Code commented out due no compilation errors on Alpha OSF (tgb)
+
+  // throw the Id of numBlind different pixels in this event
+  TH1D *hblind;
+  UInt_t idBlind;
+  UInt_t listId[npix];
+  UInt_t nlist = 0;
+  Bool_t equal;
+
+  hblind = fHBlindPixIdTheta->ProjectionY("", binTheta, binTheta, "");
+  if ( hblind->Integral() > 0.0 )
+    for (UInt_t i=0; i<numBlind; i++)
+    {
+      while(1)
+      {
+        idBlind = (Int_t) (hblind->GetRandom()+0.5);
+        equal = kFALSE;
+        for (UInt_t j=0; j<nlist; j++)
+          if (idBlind == listId[j])
+	  { 
+            equal = kTRUE;
+            break;
+	  }
+        if (!equal) break;
+      }
+      listId[nlist] = idBlind;
+      nlist++;
+
+      fBlinds->SetPixelBlind(idBlind);
+      // *fLog << "idBlind = " << idBlind << endl;
+    }
+  fBlinds->SetReadyToSave();
+
+  delete hblind;
+
+  }
+
+  //******************************************************************
+  // has the event to be padded ?
+  // if yes : to which sigmabar should it be padded ?
+  //
+
+  Int_t binSig = fHgON->GetYaxis()->FindBin(sigbarold);
+  // *fLog << "binSig, sigbarold = " << binSig << ",  " << sigbarold << endl;
+
+  Double_t prob;
+  TH1D *hpad = NULL;
+  if (fType == "ON")
+  {
+    hpad = fHgON->ProjectionZ("zON", binTheta, binTheta, binSig, binSig, "");
+
+    //Int_t nb = hpad->GetNbinsX();
+    //for (Int_t i=1; i<=nb; i++)
+    //{
+    //  if (hpad->GetBinContent(i) != 0.0)
+    //    *fLog << "i, fHgON = " << i << ",  " << hpad->GetBinContent(i) << endl;
+    //}
+
+    if (nSigma != 0.0)
+      prob = hpad->Integral() * nTheta/nSigma;
+    else
+      prob = 0.0;
+
+    // *fLog << "nTheta, nSigma, prob = " << nTheta << ",  " << nSigma 
+    //      << ",  " << prob << endl;
+  }
+  else if (fType == "OFF")
+  {
+    hpad = fHgOFF->ProjectionZ("zOFF", binTheta, binTheta, binSig, binSig, "");
+    if (nSigma != 0.0)
+      prob = hpad->Integral() * nTheta/nSigma;
+    else
+      prob = 0.0;
+  }
+  else
+    prob = 1.0;
+
+  if ( fType != "MC"  &&
+       (prob <= 0.0  ||  gRandom->Uniform() > prob) )
+  {
+    delete hpad;
+    // event should not be padded
+    // *fLog << "event is not padded" << endl;
+
+    rc = 8;
+    fErrors[rc]++;
+    return kTRUE;
+  }
+  // event should be padded
+  // *fLog << "event is padded" << endl;  
+
+
+  //-------------------------------------------
+  // for the current theta, generate a sigmabar 
+  //
+  // for ON/OFF data according to the matrix fHgON/OFF
+  // for MC data     according to the histogram fHSigmaTheta
+  //
+  Double_t sigmabar=0;
+  if (fType == "ON"  ||  fType == "OFF")
+  {
+    //Int_t nbinsx = hpad->GetNbinsX();
+    //for (Int_t i=1; i<=nbinsx; i++)
+    //{
+    //  if (hpad->GetBinContent(i) != 0.0)
+    //    *fLog << "i, fHg = " << i << ",  " << hpad->GetBinContent(i) << endl;
+    //}
+
+    sigmabar = hpad->GetRandom();
+
+    // *fLog << "sigmabar = " << sigmabar << endl;
+
+    delete hpad;
+  }
+
+  else if (fType == "MC")
+  {
+    Int_t bincheck = fHSigmaTheta->GetXaxis()->FindBin(theta);
+
+    if (binTheta != bincheck)
+    {
+      cout << "The binnings of the 2 histograms are not identical; aborting"
+           << endl;
+      return kERROR;
+    }
+
+    TH1D *hsigma;
+
+    hsigma = fHSigmaTheta->ProjectionY("", binTheta, binTheta, "");
+    if ( hsigma->Integral() == 0.0 )
+    {
+      *fLog << "MCT1PadONOFF::Process(); projection for Theta bin " 
+            << binTheta << " has no entries; Skip event " << endl;
+      // event cannot be padded; skip event
+      delete hsigma;
+
+      rc = 3;
+      fErrors[rc]++;
+      return kCONTINUE;
+    }
+    else
+    {
+      sigmabar = hsigma->GetRandom();
+       // *fLog << "Theta, bin number = " << theta << ",  " << binTheta  
+       //      << ",  sigmabar = " << sigmabar << endl
+    }
+    delete hsigma;
+  }
+
+  const Double_t sigmabar2 = sigmabar*sigmabar;
+
+  //-------------------------------------------
+
+  // *fLog << "MCT1PadONOFF::Process(); sigbarold, sigmabar = " 
+  //      << sigbarold << ",  "<< sigmabar << endl;
+
+  // Skip event if target sigmabar is <= sigbarold
+  if (sigmabar <= sigbarold)
+  {
+    *fLog << "MCT1PadONOFF::Process(); target sigmabar is less than sigbarold : "
+          << sigmabar << ",  " << sigbarold << ",   Skip event" << endl;
+
+    rc = 4;
+    fErrors[rc]++;
+    return kCONTINUE;     
+  }
+
+
+  //-------------------------------------------
+  //
+  // Calculate average number of NSB photons to be added (lambdabar)
+  // from the value of sigmabar, 
+  //  - making assumptions about the average electronic noise (elNoise2) and
+  //  - using a fixed value (F2excess)  for the excess noise factor
+  
+  Double_t elNoise2;         // [photons]  
+  Double_t F2excess  = 1.3;
+  Double_t lambdabar;        // [photons]
+
+
+
+  Int_t bincheck = fHDiffPixTheta->GetXaxis()->FindBin(theta);
+  if (binTheta != bincheck)
+  {
+    cout << "The binnings of the 2 histograms are not identical; aborting"
+         << endl;
+    return kERROR;
+  }
+
+  // Get RMS of (Sigma^2-sigmabar^2) in this Theta bin.
+  // The average electronic noise (to be added) has to be well above this RMS,
+  // otherwise the electronic noise of an individual pixel (elNoise2Pix)
+  // may become negative
+
+  TH1D *hnoise;
+  if (fType == "MC")
+    hnoise = fHDiffPixTheta->ProjectionZ("", binTheta, binTheta, 0, 9999, "");
+  else if (fType == "ON")
+    hnoise = fHDiffPixThetaOFF->ProjectionZ("", binTheta, binTheta, 0, 9999, "");
+  else if (fType == "OFF")
+    hnoise = fHDiffPixThetaON->ProjectionZ("", binTheta, binTheta, 0, 9999, "");
+  else
+  {
+    *fLog << "MCT1PadONOFF::Process; illegal data type... aborting" << endl;
+    return kERROR;
+  }
+
+  Double_t RMS = hnoise->GetRMS(1);  
+  delete hnoise;
+
+  elNoise2 = TMath::Min(RMS,  sigmabar2 - sigbarold2);
+  // *fLog << "elNoise2 = " << elNoise2 << endl; 
+
+  lambdabar = (sigmabar2 - sigbarold2 - elNoise2) / F2excess;     // [photons]
+
+  // This value of lambdabar is the same for all pixels;
+  // note that lambdabar is normalized to the area of pixel 0
+
+  //----------   start loop over pixels   ---------------------------------
+  // do the padding for each pixel
+  //
+  // pad only pixels   - which are used (before image cleaning)
+  //
+  Double_t sig         = 0;
+  Double_t sigma2      = 0;
+  Double_t diff        = 0;
+  Double_t addSig2     = 0;
+  Double_t elNoise2Pix = 0;
+
+
+  for (UInt_t i=0; i<npix; i++) 
+  {   
+    MCerPhotPix &pix = (*fEvt)[i];
+    if ( !pix.IsPixelUsed() )
+      continue;
+
+    //if ( pix.GetNumPhotons() == 0.0)
+    //{
+    //  *fLog << "MCT1PadONOFF::Process(); no.of photons is 0 for used pixel" 
+    //        << endl;
+    //  continue;
+    //}
+
+    Int_t j = pix.GetPixId();
+
+    // GetPixRatio returns (area of pixel 0 / area of current pixel)
+    Double_t ratioArea = 1.0 / fCam->GetPixRatio(j);
+
+    MPedPhotPix &ppix = (*fPed)[j];
+    Double_t oldsigma = ppix.GetRms();
+    Double_t oldsigma2 = oldsigma*oldsigma;
+
+    //---------------------------------
+    // throw the Sigma for this pixel 
+    //
+    Int_t binPixel = fHDiffPixTheta->GetYaxis()->FindBin( (Double_t)j );
+
+    Int_t count;
+    Bool_t ok;
+
+    TH1D *hdiff;
+    TH1D *hsig;
+
+    switch (fPadFlag)
+    {
+    case 1 :
+      // throw the Sigma for this pixel from the distribution fHDiffPixTheta
+
+      if (fType == "MC")
+        hdiff = fHDiffPixTheta->ProjectionZ("", binTheta, binTheta,
+                                                binPixel, binPixel, "");
+      else if (fType == "ON") 
+        hdiff = fHDiffPixThetaOFF->ProjectionZ("", binTheta, binTheta,
+                                                   binPixel, binPixel, "");
+      else 
+        hdiff = fHDiffPixThetaON->ProjectionZ("", binTheta, binTheta,
+                                                  binPixel, binPixel, "");
+
+     if ( hdiff->Integral() == 0 )
+      {
+        *fLog << "MCT1PadONOFF::Process(); projection for Theta bin " 
+              << binTheta << "  and pixel bin " << binPixel  
+              << " has no entries;  aborting " << endl;
+        delete hdiff;
+
+        rc = 5;
+        fErrors[rc]++;
+        return kCONTINUE;     
+      }
+
+      count = 0;
+      ok = kFALSE;
+      for (Int_t m=0; m<fIter; m++)
+      {
+        count += 1;
+        diff = hdiff->GetRandom();
+        // the following condition ensures that elNoise2Pix > 0.0 
+
+        if ( (diff + sigmabar2 - oldsigma2/ratioArea
+                               - lambdabar*F2excess) > 0.0 )
+	{
+          ok = kTRUE;
+          break;
+	}
+      }
+      if (!ok)
+      {
+        // *fLog << "theta, j, count, sigmabar, diff = " << theta << ",  " 
+        //      << j << ",  " << count << ",  " << sigmabar << ",  " 
+        //      << diff << endl;
+        diff = lambdabar*F2excess + oldsigma2/ratioArea - sigmabar2;
+
+        rw = 1;
+        fWarnings[rw]++;
+      }
+      else
+      {
+        rw = 0;
+        fWarnings[rw]++;
+      }
+
+      delete hdiff;
+      sigma2 = diff + sigmabar2;
+      break;
+
+    case 2 :
+      // throw the Sigma for this pixel from the distribution fHSigmaPixTheta
+
+      if (fType == "MC")
+        hsig = fHSigmaPixTheta->ProjectionZ("", binTheta, binTheta,
+                                                binPixel, binPixel, "");
+      else if (fType == "ON")
+        hsig = fHSigmaPixThetaOFF->ProjectionZ("", binTheta, binTheta,
+                                                   binPixel, binPixel, "");
+      else 
+        hsig = fHSigmaPixThetaON->ProjectionZ("", binTheta, binTheta,
+                                                  binPixel, binPixel, "");
+
+      if ( hsig->Integral() == 0 )
+      {
+        *fLog << "MCT1PadONOFF::Process(); projection for Theta bin " 
+              << binTheta << "  and pixel bin " << binPixel  
+              << " has no entries;  aborting " << endl;
+        delete hsig;
+
+        rc = 6;
+        fErrors[rc]++;
+        return kCONTINUE;     
+      }
+
+      count = 0;
+      ok = kFALSE;
+      for (Int_t m=0; m<fIter; m++)
+      {
+        count += 1;
+
+        sig = hsig->GetRandom();
+        sigma2 = sig*sig/ratioArea;
+        // the following condition ensures that elNoise2Pix > 0.0 
+
+        if ( (sigma2-oldsigma2/ratioArea-lambdabar*F2excess) > 0.0 )
+	{
+          ok = kTRUE;
+          break;
+	}
+      }
+      if (!ok)
+      {
+        // *fLog << "theta, j, count, sigmabar, sig = " << theta << ",  " 
+        //      << j << ",  " << count << ",  " << sigmabar << ",  " 
+        //      << sig << endl;
+        sigma2 = lambdabar*F2excess + oldsigma2/ratioArea; 
+
+        rw = 1;
+        fWarnings[rw]++;
+      }
+      else
+      {
+        rw = 0;
+        fWarnings[rw]++;
+      }
+
+      delete hsig;
+      break;
+    }
+
+    //---------------------------------
+    // get the additional sigma^2 for this pixel (due to the padding)
+
+    addSig2 = sigma2*ratioArea - oldsigma2;
+
+
+    //---------------------------------
+    // get the additional electronic noise for this pixel
+
+    elNoise2Pix = addSig2 - lambdabar*F2excess*ratioArea;
+
+
+    //---------------------------------
+    // throw actual number of additional NSB photons (NSB)
+    //       and its RMS (sigmaNSB) 
+
+    Double_t NSB0 = gRandom->Poisson(lambdabar*ratioArea);
+    Double_t arg  = NSB0*(F2excess-1.0) + elNoise2Pix;
+    Double_t sigmaNSB0;
+
+    if (arg >= 0.0)
+    {
+      sigmaNSB0 = sqrt( arg );
+    }
+    else
+    {
+      sigmaNSB0 = 0.0000001;      
+      if (arg < -1.e-10)
+      {
+        *fLog << "MCT1PadONOFF::Process(); argument of sqrt < 0 : "
+              << arg << endl;
+      }
+    }
+
+
+    //---------------------------------
+    // smear NSB0 according to sigmaNSB0
+    // and subtract lambdabar because of AC coupling
+
+    Double_t NSB = gRandom->Gaus(NSB0, sigmaNSB0) - lambdabar*ratioArea;
+
+    //---------------------------------
+ 
+    // add additional NSB to the number of photons
+    Double_t oldphotons = pix.GetNumPhotons();
+    Double_t newphotons = oldphotons + NSB;
+    pix.SetNumPhotons(	newphotons );
+
+
+    fHNSB->Fill( NSB/sqrt(ratioArea) );
+    fHPhotons->Fill( oldphotons/sqrt(ratioArea), newphotons/sqrt(ratioArea) );
+
+
+    // error: add sigma of padded noise quadratically
+    Double_t olderror = pix.GetErrorPhot();
+    Double_t newerror = sqrt( olderror*olderror + addSig2 );
+    pix.SetErrorPhot( newerror );
+
+
+    Double_t newsigma = sqrt( oldsigma2 + addSig2 ); 
+    ppix.SetRms( newsigma );
+
+    fHSigmaPedestal->Fill( oldsigma, newsigma );
+  } 
+  //----------   end of loop over pixels   ---------------------------------
+
+  // Calculate sigmabar again and crosscheck
+
+  //fSigmabar->Calc(*fCam, *fPed, *fEvt);
+  // *fLog << "after padding : " << endl;
+  //fSigmabar->Print("");
+
+  rc = 0;
+  fErrors[rc]++;
+  return kTRUE;
+  //******************************************************************
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MCT1PadONOFF::PostProcess()
+{
+    if (GetNumExecutions() != 0)
+    {
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    int temp;
+    if (fWarnings[0] != 0.0)    
+      temp = (int)(fWarnings[1]*100/fWarnings[0]);
+    else
+      temp = 100;
+
+    *fLog << " " << setw(7) << fWarnings[1] << " (" << setw(3) 
+          << temp 
+          << "%) Warning : iteration to find acceptable sigma failed" 
+          << ", fIter = " << fIter << endl;
+
+    *fLog << " " << setw(7) << fErrors[1] << " (" << setw(3) 
+          << (int)(fErrors[1]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: Sigmabar_old > 0" << endl;
+
+    *fLog << " " << setw(7) << fErrors[2] << " (" << setw(3) 
+          << (int)(fErrors[2]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: Zenith angle out of range" << endl;
+
+    *fLog << " " << setw(7) << fErrors[3] << " (" << setw(3) 
+          << (int)(fErrors[3]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: No data for generating Sigmabar" << endl;
+
+    *fLog << " " << setw(7) << fErrors[4] << " (" << setw(3) 
+          << (int)(fErrors[4]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: Target sigma <= Sigmabar_old" << endl;
+
+    *fLog << " " << setw(7) << fErrors[5] << " (" << setw(3) 
+          << (int)(fErrors[5]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: No data for generating Sigma^2-Sigmabar^2" << endl;
+
+    *fLog << " " << setw(7) << fErrors[6] << " (" << setw(3) 
+          << (int)(fErrors[6]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: No data for generating Sigma" << endl;
+
+    *fLog << " " << setw(7) << fErrors[7] << " (" << setw(3) 
+          << (int)(fErrors[7]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: No data for generating Blind pixels" << endl;
+
+    *fLog << " " << setw(7) << fErrors[8] << " (" << setw(3) 
+          << (int)(fErrors[8]*100/GetNumExecutions()) 
+          << "%) Evts didn't have to be padded" << endl;
+
+    *fLog << " " << fErrors[0] << " (" 
+          << (int)(fErrors[0]*100/GetNumExecutions()) 
+          << "%) Evts were successfully padded!" << endl;
+    *fLog << endl;
+
+    }
+
+    //---------------------------------------------------------------
+    TCanvas &c = *(MH::MakeDefCanvas("PadONOFF", "", 900, 1200)); 
+    c.Divide(3, 4);
+    gROOT->SetSelectedPad(NULL);
+
+    c.cd(1);
+    fHNSB->SetDirectory(NULL);
+    fHNSB->DrawCopy();
+    fHNSB->SetBit(kCanDelete);    
+
+    c.cd(2);
+    fHSigmaPedestal->SetDirectory(NULL);
+    fHSigmaPedestal->DrawCopy();
+    fHSigmaPedestal->SetBit(kCanDelete);    
+
+    c.cd(3);
+    fHPhotons->SetDirectory(NULL);
+    fHPhotons->DrawCopy();
+    fHPhotons->SetBit(kCanDelete);    
+
+    //--------------------------------------------------------------------
+
+
+    c.cd(4);
+    fHSigmaTheta->SetDirectory(NULL);
+    fHSigmaTheta->SetTitle("(Target) 2D : Sigmabar, \\Theta");
+    fHSigmaTheta->DrawCopy();     
+    fHSigmaTheta->SetBit(kCanDelete);     
+
+
+    //--------------------------------------------------------------------
+
+
+    c.cd(7);
+    fHBlindPixNTheta->SetDirectory(NULL);
+    fHBlindPixNTheta->SetTitle("(Target) 2D : no.of blind pixels, \\Theta");
+    fHBlindPixNTheta->DrawCopy();     
+    fHBlindPixNTheta->SetBit(kCanDelete);     
+
+    //--------------------------------------------------------------------
+
+
+    c.cd(10);
+    fHBlindPixIdTheta->SetDirectory(NULL);
+    fHBlindPixIdTheta->SetTitle("(Target) 2D : blind pixel Id, \\Theta");
+    fHBlindPixIdTheta->DrawCopy();     
+    fHBlindPixIdTheta->SetBit(kCanDelete);     
+
+
+    //--------------------------------------------------------------------
+    // draw the 3D histogram (target): Theta, pixel, Sigma^2-Sigmabar^2
+
+    c.cd(5);
+    TH2D *l1;
+    l1 = (TH2D*) ((TH3*)fHDiffPixTheta)->Project3D("zx");
+    l1->SetDirectory(NULL);
+    l1->SetTitle("(Target) Sigma^2-Sigmabar^2 vs. \\Theta (all pixels)");
+    l1->SetXTitle("\\Theta [\\circ]");
+    l1->SetYTitle("Sigma^2-Sigmabar^2");
+
+    l1->DrawCopy("box");
+    l1->SetBit(kCanDelete);;
+
+    c.cd(8);
+    TH2D *l2;
+    l2 = (TH2D*) ((TH3*)fHDiffPixTheta)->Project3D("zy");
+    l2->SetDirectory(NULL);
+    l2->SetTitle("(Target) Sigma^2-Sigmabar^2 vs. pixel number (all \\Theta)");
+    l2->SetXTitle("pixel");
+    l2->SetYTitle("Sigma^2-Sigmabar^2");
+
+    l2->DrawCopy("box");
+    l2->SetBit(kCanDelete);;
+
+    //--------------------------------------------------------------------
+    // draw the 3D histogram (target): Theta, pixel, Sigma
+
+    c.cd(6);
+    TH2D *k1;
+    k1 = (TH2D*) ((TH3*)fHSigmaPixTheta)->Project3D("zx");
+    k1->SetDirectory(NULL);
+    k1->SetTitle("(Target) Sigma vs. \\Theta (all pixels)");
+    k1->SetXTitle("\\Theta [\\circ]");
+    k1->SetYTitle("Sigma");
+
+    k1->DrawCopy("box");
+    k1->SetBit(kCanDelete);
+
+    c.cd(9);
+    TH2D *k2;
+    k2 = (TH2D*) ((TH3*)fHSigmaPixTheta)->Project3D("zy");
+    k2->SetDirectory(NULL);
+    k2->SetTitle("(Target) Sigma vs. pixel number (all \\Theta)");
+    k2->SetXTitle("pixel");
+    k2->SetYTitle("Sigma");
+
+    k2->DrawCopy("box");
+    k2->SetBit(kCanDelete);;
+
+
+    //--------------------------------------------------------------------
+
+    c.cd(11);
+    TH2D *m1;
+    m1 = (TH2D*) ((TH3*)fHgON)->Project3D("zy");
+    m1->SetDirectory(NULL);
+    m1->SetTitle("(Target) Sigmabar-new vs. Sigmabar-old (ON, all  \\Theta)");
+    m1->SetXTitle("Sigmabar-old");
+    m1->SetYTitle("Sigmabar-new");
+
+    m1->DrawCopy("box");
+    m1->SetBit(kCanDelete);;
+
+    c.cd(12);
+    TH2D *m2;
+    m2 = (TH2D*) ((TH3*)fHgOFF)->Project3D("zy");
+    m2->SetDirectory(NULL);
+    m2->SetTitle("(Target) Sigmabar-new vs. Sigmabar-old (OFF, all  \\Theta)");
+    m2->SetXTitle("Sigmabar-old");
+    m2->SetYTitle("Sigmabar-new");
+
+    m2->DrawCopy("box");
+    m2->SetBit(kCanDelete);;
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1PadONOFF.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1PadONOFF.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1PadONOFF.h	(revision 9772)
@@ -0,0 +1,104 @@
+#ifndef MARS_MCT1PadONOFF
+#define MARS_MCT1PadONOFF
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TH2D;
+class TH3D;
+
+class MGeomCam;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MMcEvt;
+class MSigmabar;
+class MParList;
+class MBlindPixels;
+class MRead;
+class MFilterList;
+
+
+class MCT1PadONOFF : public MTask
+{
+private:
+    MGeomCam       *fCam;
+    MCerPhotEvt    *fEvt; 
+    MSigmabar      *fSigmabar;
+    MMcEvt         *fMcEvt;
+    MPedPhotCam   *fPed;
+    MBlindPixels   *fBlinds;
+
+    TString        fType;           // type of data to be padded
+    TFile          *fInfile;        // input file containing padding histograms
+
+    Int_t          fPadFlag;
+    Int_t          fIter;
+
+    Int_t          fErrors[9];
+    Int_t          fWarnings[2];
+
+
+    // plots used for the padding
+    TH2D           *fHBlindPixIdTheta; // 2D-histogram (blind pixel Id vs. Theta)
+    TH2D           *fHBlindPixNTheta; // 2D-histogram (no.of blind pixels vs. Theta)
+
+    TH2D           *fHSigmaTheta;       // 2D-histogram (sigmabar vs. Theta)
+    TH2D           *fHSigmaThetaON;     // 2D-histogram (sigmabar vs. Theta)
+    TH2D           *fHSigmaThetaOFF;    // 2D-histogram (sigmabar vs. Theta)
+
+    TH3D           *fHSigmaPixTheta;    // 3D-histogram (Theta, pixel, sigma)
+    TH3D           *fHSigmaPixThetaON;  // 3D-histogram (Theta, pixel, sigma)
+    TH3D           *fHSigmaPixThetaOFF; // 3D-histogram (Theta, pixel, sigma)
+
+    TH3D           *fHDiffPixTheta;     // 3D-histogram (Theta, pixel, sigma^2-sigmabar^2)
+    TH3D           *fHDiffPixThetaON;   // 3D-histogram (Theta, pixel, sigma^2-sigmabar^2)
+    TH3D           *fHDiffPixThetaOFF;  // 3D-histogram (Theta, pixel, sigma^2-sigmabar^2)
+
+    TH3D           *fHgON;           // matrix (Theta, sigbarold, sigbarnew) for ON data
+    TH3D           *fHgOFF;          // matrix (Theta, sigbarold, sigbarnew) for OFF data
+
+    // plots for checking the padding
+    TH2D           *fHSigmaPedestal; // 2D-histogram : pedestal sigma after
+                                     //                versus before padding
+    TH2D           *fHPhotons;       // 2D-histogram : no.of photons after
+                                     //                versus before padding
+    TH1D           *fHNSB;           // 1D-histogram : additional NSB
+
+
+public:
+    MCT1PadONOFF(const char *name=NULL, const char *title=NULL);
+    ~MCT1PadONOFF();
+
+    Bool_t MergeHistograms(TH2D *sigthon,     TH2D *sigthoff,
+                           TH3D *sigpixthon,  TH3D *sigpixthoff,
+                           TH3D *diffpixthon, TH3D *diffpixthoff,
+                           TH2D *blindidthon, TH2D *blindidthoff,
+                           TH2D *blindnthon,  TH2D *blindnthoff);
+
+    Bool_t ReadTargetDist(const char *filein);
+    Bool_t WriteTargetDist(const char *fileout);
+
+    void SetDataType(const char *type);   // type of data to be padded
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+    
+    void SetPadFlag(Int_t padflag);
+
+    ClassDef(MCT1PadONOFF, 0)    // task for the ON-OFF padding 
+}; 
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1PadSchweizer.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1PadSchweizer.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1PadSchweizer.cc	(revision 9772)
@@ -0,0 +1,897 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner, 10/2002 <mailto:magicsoft@rwagner.de>
+!   Author(s): Wolfgang Wittek, 02/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MCT1PadSchweizer
+//
+//  This task applies padding such that for a given pixel and for a given
+//  Theta bin the resulting distribution of the pedestal sigma is identical
+//  to the distributions given by fHSigmaPixTheta and fHDiffPixTheta.
+//
+//  The number of photons, its error and the pedestal sigmas are altered.
+//  On average, the number of photons added is zero.
+//
+//  The formulas used can be found in Thomas Schweizer's Thesis,
+//                                    Section 2.2.1
+//
+//  There are 2 options for the padding :
+//
+//  1) fPadFlag = 1 :
+//     Generate first a Sigmabar using the 2D-histogram Sigmabar vs. Theta
+//     (fHSigmaTheta). Then generate a pedestal sigma for each pixel using
+//     the 3D-histogram Theta, pixel no., Sigma^2-Sigmabar^2
+//     (fHDiffPixTheta).
+//
+//     This is the preferred option as it takes into account the
+//     correlations between the Sigma of a pixel and Sigmabar.
+//
+//  2) fPadFlag = 2 :
+//     Generate a pedestal sigma for each pixel using the 3D-histogram
+//     Theta, pixel no., Sigma (fHSigmaPixTheta).
+//
+//
+//  The padding has to be done before the image cleaning because the
+//  image cleaning depends on the pedestal sigmas.
+//
+//  For random numbers gRandom is used.
+//
+//  This implementation has been tested for CT1 data. For MAGIC some
+//  modifications are necessary.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1PadSchweizer.h"
+
+#include <stdio.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+
+#include "MBinning.h"
+#include "MSigmabar.h"
+#include "MMcEvt.hxx"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MBlindPixels.h"
+
+ClassImp(MCT1PadSchweizer);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCT1PadSchweizer::MCT1PadSchweizer(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MCT1PadSchweizer";
+  fTitle = title ? title : "Task for the padding (Schweizer)";
+
+  fHSigmaTheta    = NULL;
+  fHSigmaPixTheta = NULL;
+  fHDiffPixTheta  = NULL;
+  fHBlindPixIdTheta = NULL;
+  fHBlindPixNTheta  = NULL;
+
+  fHSigmaPedestal = NULL;
+  fHPhotons       = NULL;
+  fHNSB           = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MCT1PadSchweizer::~MCT1PadSchweizer()
+{
+  if (fHSigmaPedestal != NULL) delete fHSigmaPedestal;
+  if (fHPhotons != NULL)       delete fHPhotons;
+  if (fHNSB != NULL)           delete fHNSB;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the references to the histograms to be used in the padding
+// 
+// fHSigmaTheta    2D-histogram  (Theta, sigmabar)
+// fHSigmaPixTheta 3D-hiostogram (Theta, pixel, sigma)
+// fHDiffPixTheta  3D-histogram  (Theta, pixel, sigma^2-sigmabar^2)
+// fHBlindPixIdTheta 2D-histogram  (Theta, blind pixel Id)
+// fHBlindPixNTheta  2D-histogram  (Theta, no.of blind pixels )
+//
+//
+void MCT1PadSchweizer::SetHistograms(TH2D *hist2, TH3D *hist3, TH3D *hist3Diff,
+                                  TH2D *hist2Pix, TH2D *hist2PixN)
+{
+    fHSigmaTheta    = hist2;
+    fHSigmaPixTheta = hist3;
+    fHDiffPixTheta  = hist3Diff;
+    fHBlindPixIdTheta = hist2Pix;
+    fHBlindPixNTheta  = hist2PixN;
+
+    fHSigmaTheta->SetDirectory(NULL);
+    fHSigmaPixTheta->SetDirectory(NULL);
+    fHDiffPixTheta->SetDirectory(NULL);
+    fHBlindPixIdTheta->SetDirectory(NULL);
+    fHBlindPixNTheta->SetDirectory(NULL);
+
+    Print();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the option for the padding
+//
+//  There are 2 options for the padding :
+//
+//  1) fPadFlag = 1 :
+//     Generate first a Sigmabar using the 2D-histogram Sigmabar vs. Theta
+//     (fHSigmaTheta). Then generate a pedestal sigma for each pixel using
+//     the 3D-histogram Theta, pixel no., Sigma^2-Sigmabar^2
+//     (fHDiffPixTheta).
+//
+//     This is the preferred option as it takes into account the
+//     correlations between the Sigma of a pixel and Sigmabar.
+//
+//  2) fPadFlag = 2 :
+//     Generate a pedestal sigma for each pixel using the 3D-histogram
+//     Theta, pixel no., Sigma (fHSigmaPixTheta).
+//
+void MCT1PadSchweizer::SetPadFlag(Int_t padflag)
+{
+  fPadFlag = padflag;
+  *fLog << "MCT1PadSchweizer::SetPadFlag(); choose option " << fPadFlag << endl; 
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the pointers and prepare the histograms
+//
+Int_t MCT1PadSchweizer::PreProcess(MParList *pList)
+{
+  if ( !fHSigmaTheta  || !fHSigmaPixTheta  || !fHDiffPixTheta  ||
+       !fHBlindPixIdTheta  ||  !fHBlindPixNTheta)
+  { 
+       *fLog << err << "At least one of the histograms needed for the padding is not defined ... aborting." << endl;
+       return kFALSE;
+  }
+
+  fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+  if (!fMcEvt)
+    {
+       *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+       return kFALSE;
+     }
+  
+   fPed = (MPedPhotCam*)pList->FindObject("MPedPhotCam");
+   if (!fPed)
+     {
+       *fLog << err << "MPedPhotCam not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+   if (!fCam)
+     {
+       *fLog << err << "MGeomCam not found (no geometry information available)... aborting." << endl;
+       return kFALSE;
+     }
+  
+   fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+   if (!fEvt)
+     {
+       *fLog << err << "MCerPhotEvt not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fSigmabar = (MSigmabar*)pList->FindCreateObj("MSigmabar");
+   if (!fSigmabar)
+     {
+       *fLog << err << "MSigmabar not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fBlinds = (MBlindPixels*)pList->FindCreateObj("MBlindPixels");
+   if (!fBlinds)
+     {
+       *fLog << err << "MBlindPixels not found... aborting." << endl;
+       return kFALSE;
+     }
+   
+
+   //--------------------------------------------------------------------
+   // histograms for checking the padding
+   //
+   // plot pedestal sigmas
+   fHSigmaPedestal = new TH2D("SigPed","Sigma: after vs. before padding", 
+                     100, 0.0, 5.0, 100, 0.0, 5.0);
+   fHSigmaPedestal->SetXTitle("Pedestal sigma before padding");
+   fHSigmaPedestal->SetYTitle("Pedestal sigma after padding");
+
+   // plot no.of photons (before vs. after padding) 
+   fHPhotons = new TH2D("Photons","Photons: after vs.before padding", 
+                        100, -10.0, 90.0, 100, -10, 90);
+   fHPhotons->SetXTitle("no.of photons before padding");
+   fHPhotons->SetYTitle("no.of photons after padding");
+
+   // plot of added NSB
+   fHNSB = new TH1D("NSB","Distribution of added NSB", 100, -10.0, 10.0);
+   fHNSB->SetXTitle("no.of added NSB photons");
+   fHNSB->SetYTitle("no.of pixels");
+
+
+   //--------------------------------------------------------------------
+
+   memset(fErrors, 0, sizeof(fErrors));
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the Padding
+// idealy the events to be padded should have been generated without NSB
+// 
+Int_t MCT1PadSchweizer::Process()
+{
+  //*fLog << "Entry MCT1PadSchweizer::Process();" << endl;
+
+  //------------------------------------------------
+  // add pixels to MCerPhotEvt which are not yet in;
+  // set their numnber of photons equal to zero
+
+  UInt_t imaxnumpix = fCam->GetNumPixels();
+
+  for (UInt_t i=0; i<imaxnumpix; i++)
+  {
+    Bool_t alreadythere = kFALSE;
+    UInt_t npix = fEvt->GetNumPixels();
+    for (UInt_t j=0; j<npix; j++)
+    {
+      MCerPhotPix &pix = (*fEvt)[j];
+      UInt_t id = pix.GetPixId();
+      if (i==id)
+      {
+        alreadythere = kTRUE;
+        break;
+      }
+    }
+    if (alreadythere)
+      continue;
+
+    fEvt->AddPixel(i, 0.0, (*fPed)[i].GetRms());
+  }
+
+
+
+  //-----------------------------------------
+  Int_t rc=0;
+
+  const UInt_t npix = fEvt->GetNumPixels();
+
+  //fSigmabar->Calc(*fCam, *fPed, *fEvt);
+  //*fLog << "before padding : " << endl;
+  //fSigmabar->Print("");
+
+
+  //$$$$$$$$$$$$$$$$$$$$$$$$$$
+  // to simulate the situation that before the padding the NSB and 
+  // electronic noise are zero : set Sigma = 0 for all pixels
+  //for (UInt_t i=0; i<npix; i++) 
+  //{   
+  //  MCerPhotPix &pix = fEvt->operator[](i);      
+  //  Int_t j = pix.GetPixId();
+
+  //  MPedPhotPix &ppix = fPed->operator[](j);
+  //  ppix.SetRms(0.0);
+  //}
+  //$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+  //-------------------------------------------
+  // Calculate average sigma of the event
+  //
+  Double_t sigbarold = fSigmabar->Calc(*fCam, *fPed, *fEvt);
+  Double_t sigbarold2 = sigbarold*sigbarold;
+  //fSigmabar->Print("");
+
+  if (sigbarold > 0)
+  {
+    //*fLog << "MCT1PadSchweizer::Process(); sigmabar of event to be padded is > 0 : "
+    //      << sigbarold << ". Stop event loop " << endl;
+    // input data should have sigmabar = 0; stop event loop
+  
+    rc = 1;
+    fErrors[rc]++;
+    return kCONTINUE; 
+  }
+
+  const Double_t theta = kRad2Deg*fMcEvt->GetTelescopeTheta();
+  // *fLog << "theta = " << theta << endl;
+
+
+  //-------------------------------------------
+  // for the current theta, 
+  // generate blind pixels according to the histograms 
+  //          fHBlindPixNTheta and fHBlindPixIDTheta
+  //
+
+
+  Int_t binPix = fHBlindPixNTheta->GetXaxis()->FindBin(theta);
+
+  if ( binPix < 1  ||  binPix > fHBlindPixNTheta->GetNbinsX() )
+  {
+    //*fLog << "MCT1PadSchweizer::Process(); binNumber out of range : theta, binPix = "
+    //      << theta << ",  " << binPix << ";  Skip event " << endl;
+    // event cannot be padded; skip event
+
+    rc = 2;
+    fErrors[rc]++;
+    return kCONTINUE;
+  }
+
+  // numBlind is the number of blind pixels in this event
+  TH1D *nblind;
+  UInt_t numBlind;
+
+  nblind = fHBlindPixNTheta->ProjectionY("", binPix, binPix, "");
+  if ( nblind->GetEntries() == 0.0 )
+  {
+    *fLog << "MCT1PadSchweizer::Process(); projection for Theta bin " 
+          << binPix << " has no entries; Skip event " << endl;
+    // event cannot be padded; skip event
+    delete nblind;
+
+    rc = 7;
+    fErrors[rc]++;
+    return kCONTINUE;
+  }
+  else
+  {
+    numBlind = (Int_t) (nblind->GetRandom()+0.5);
+  }
+  delete nblind;
+
+
+  // throw the Id of numBlind different pixels in this event
+  TH1D *hblind;
+  UInt_t idBlind;
+  UInt_t listId[npix];
+  UInt_t nlist = 0;
+  Bool_t equal;
+
+  hblind = fHBlindPixIdTheta->ProjectionY("", binPix, binPix, "");
+  if ( hblind->GetEntries() > 0.0 )
+    for (UInt_t i=0; i<numBlind; i++)
+    {
+      while(1)
+      {
+        idBlind = (Int_t) (hblind->GetRandom()+0.5);
+        equal = kFALSE;
+        for (UInt_t j=0; j<nlist; j++)
+          if (idBlind == listId[j])
+	  { 
+            equal = kTRUE;
+            break;
+	  }
+        if (!equal) break;
+      }
+      listId[nlist] = idBlind;
+      nlist++;
+
+      fBlinds->SetPixelBlind(idBlind);
+      //*fLog << "idBlind = " << idBlind << endl;
+    }
+  fBlinds->SetReadyToSave();
+
+  delete hblind;
+
+
+  //-------------------------------------------
+  // for the current theta, 
+  // generate a sigmabar according to the histogram fHSigmaTheta
+  //
+  Double_t sigmabar=0;
+  Int_t binNumber = fHSigmaTheta->GetXaxis()->FindBin(theta);
+
+  if (binPix != binNumber)
+  {
+    cout << "The binnings of the 2 histograms are not identical; aborting"
+         << endl;
+    return kERROR;
+  }
+
+  TH1D *hsigma;
+
+  hsigma = fHSigmaTheta->ProjectionY("", binNumber, binNumber, "");
+  if ( hsigma->GetEntries() == 0.0 )
+  {
+    *fLog << "MCT1PadSchweizer::Process(); projection for Theta bin " 
+          << binNumber << " has no entries; Skip event " << endl;
+    // event cannot be padded; skip event
+    delete hsigma;
+
+    rc = 3;
+    fErrors[rc]++;
+    return kCONTINUE;
+  }
+  else
+  {
+    sigmabar = hsigma->GetRandom();
+     //*fLog << "Theta, bin number = " << theta << ",  " << binNumber      //      << ",  sigmabar = " << sigmabar << endl
+  }
+  delete hsigma;
+
+  const Double_t sigmabar2 = sigmabar*sigmabar;
+
+  //-------------------------------------------
+
+  //*fLog << "MCT1PadSchweizer::Process(); sigbarold, sigmabar = " 
+  //      << sigbarold << ",  "<< sigmabar << endl;
+
+  // Skip event if target sigmabar is <= sigbarold
+  if (sigmabar <= sigbarold)
+  {
+    *fLog << "MCT1PadSchweizer::Process(); target sigmabar is less than sigbarold : "
+          << sigmabar << ",  " << sigbarold << ",   Skip event" << endl;
+
+    rc = 4;
+    fErrors[rc]++;
+    return kCONTINUE;     
+  }
+
+
+  //-------------------------------------------
+  //
+  // Calculate average number of NSB photons to be added (lambdabar)
+  // from the value of sigmabar, 
+  //  - making assumptions about the average electronic noise (elNoise2) and
+  //  - using a fixed value (F2excess)  for the excess noise factor
+  
+  Double_t elNoise2;         // [photons]  
+  Double_t F2excess  = 1.3;
+  Double_t lambdabar;        // [photons]
+
+
+
+  Int_t binTheta = fHDiffPixTheta->GetXaxis()->FindBin(theta);
+  if (binTheta != binNumber)
+  {
+    cout << "The binnings of the 2 histograms are not identical; aborting"
+         << endl;
+    return kERROR;
+  }
+
+  // Get RMS of (Sigma^2-sigmabar^2) in this Theta bin.
+  // The average electronic noise (to be added) has to be well above this RMS,
+  // otherwise the electronic noise of an individual pixel (elNoise2Pix)
+  // may become negative
+
+  TH1D *hnoise = fHDiffPixTheta->ProjectionZ("", binTheta, binTheta,
+                                                          0, 9999, "");
+  Double_t RMS = hnoise->GetRMS(1);  
+  delete hnoise;
+
+  elNoise2 = TMath::Min(RMS,  sigmabar2 - sigbarold2);
+  //*fLog << "elNoise2 = " << elNoise2 << endl; 
+
+  lambdabar = (sigmabar2 - sigbarold2 - elNoise2) / F2excess;     // [photons]
+
+  // This value of lambdabar is the same for all pixels;
+  // note that lambdabar is normalized to the area of pixel 0
+
+  //----------   start loop over pixels   ---------------------------------
+  // do the padding for each pixel
+  //
+  // pad only pixels   - which are used (before image cleaning)
+  //
+  Double_t sig         = 0;
+  Double_t sigma2      = 0;
+  Double_t diff        = 0;
+  Double_t addSig2     = 0;
+  Double_t elNoise2Pix = 0;
+
+
+  for (UInt_t i=0; i<npix; i++) 
+  {   
+    MCerPhotPix &pix = (*fEvt)[i];
+    if ( !pix.IsPixelUsed() )
+      continue;
+
+    //if ( pix.GetNumPhotons() == 0.0)
+    //{
+    //  *fLog << "MCT1PadSchweizer::Process(); no.of photons is 0 for used pixel" 
+    //        << endl;
+    //  continue;
+    //}
+
+    Int_t j = pix.GetPixId();
+
+    // GetPixRatio returns (area of pixel 0 / area of current pixel)
+    Double_t ratioArea = 1.0 / fCam->GetPixRatio(j);
+
+    MPedPhotPix &ppix = (*fPed)[j];
+    Double_t oldsigma = ppix.GetRms();
+    Double_t oldsigma2 = oldsigma*oldsigma;
+
+    //---------------------------------
+    // throw the Sigma for this pixel 
+    //
+    Int_t binPixel = fHDiffPixTheta->GetYaxis()->FindBin( (Double_t)j );
+
+    Int_t count;
+    Bool_t ok;
+
+    TH1D *hdiff;
+    TH1D *hsig;
+
+    switch (fPadFlag)
+    {
+    case 1 :
+      // throw the Sigma for this pixel from the distribution fHDiffPixTheta
+
+      hdiff = fHDiffPixTheta->ProjectionZ("", binTheta, binTheta,
+                                              binPixel, binPixel, "");
+      if ( hdiff->GetEntries() == 0 )
+      {
+        *fLog << "MCT1PadSchweizer::Process(); projection for Theta bin " 
+              << binTheta << "  and pixel bin " << binPixel  
+              << " has no entries;  aborting " << endl;
+        delete hdiff;
+
+        rc = 5;
+        fErrors[rc]++;
+        return kCONTINUE;     
+      }
+
+      count = 0;
+      ok = kFALSE;
+      for (Int_t m=0; m<20; m++)
+      {
+        count += 1;
+        diff = hdiff->GetRandom();
+        // the following condition ensures that elNoise2Pix > 0.0 
+
+        if ( (diff + sigmabar2 - oldsigma2/ratioArea
+                               - lambdabar*F2excess) > 0.0 )
+	{
+          ok = kTRUE;
+          break;
+	}
+      }
+      if (!ok)
+      {
+
+        *fLog << "theta, j, count, sigmabar, diff = " << theta << ",  " 
+              << j << ",  " << count << ",  " << sigmabar << ",  " 
+              << diff << endl;
+        diff = lambdabar*F2excess + oldsigma2/ratioArea - sigmabar2;
+      }
+      delete hdiff;
+      sigma2 = diff + sigmabar2;
+      break;
+
+    case 2 :
+      // throw the Sigma for this pixel from the distribution fHSigmaPixTheta
+
+      hsig = fHSigmaPixTheta->ProjectionZ("", binTheta, binTheta,
+                                              binPixel, binPixel, "");
+      if ( hsig->GetEntries() == 0 )
+      {
+        *fLog << "MCT1PadSchweizer::Process(); projection for Theta bin " 
+              << binTheta << "  and pixel bin " << binPixel  
+              << " has no entries;  aborting " << endl;
+        delete hsig;
+
+        rc = 6;
+        fErrors[rc]++;
+        return kCONTINUE;     
+      }
+
+      count = 0;
+      ok = kFALSE;
+      for (Int_t m=0; m<20; m++)
+      {
+        count += 1;
+
+        sig = hsig->GetRandom();
+        sigma2 = sig*sig/ratioArea;
+        // the following condition ensures that elNoise2Pix > 0.0 
+
+        if ( (sigma2-oldsigma2/ratioArea-lambdabar*F2excess) > 0.0 )
+	{
+          ok = kTRUE;
+          break;
+	}
+      }
+      if (!ok)
+      {
+
+        *fLog << "theta, j, count, sigmabar, sig = " << theta << ",  " 
+              << j << ",  " << count << ",  " << sigmabar << ",  " 
+              << sig << endl;
+        sigma2 = lambdabar*F2excess + oldsigma2/ratioArea; 
+      }
+      delete hsig;
+      break;
+    }
+
+    //---------------------------------
+    // get the additional sigma^2 for this pixel (due to the padding)
+
+    addSig2 = sigma2*ratioArea - oldsigma2;
+
+
+    //---------------------------------
+    // get the additional electronic noise for this pixel
+
+    elNoise2Pix = addSig2 - lambdabar*F2excess*ratioArea;
+
+
+    //---------------------------------
+    // throw actual number of additional NSB photons (NSB)
+    //       and its RMS (sigmaNSB) 
+
+    Double_t NSB0 = gRandom->Poisson(lambdabar*ratioArea);
+    Double_t arg  = NSB0*(F2excess-1.0) + elNoise2Pix;
+    Double_t sigmaNSB0;
+
+    if (arg >= 0)
+    {
+      sigmaNSB0 = sqrt( arg );
+    }
+    else
+    {
+      *fLog << "MCT1PadSchweizer::Process(); argument of sqrt < 0 : "
+            << arg << endl;
+      sigmaNSB0 = 0.0000001;      
+    }
+
+
+    //---------------------------------
+    // smear NSB0 according to sigmaNSB0
+    // and subtract lambdabar because of AC coupling
+
+    Double_t NSB = gRandom->Gaus(NSB0, sigmaNSB0) - lambdabar*ratioArea;
+
+    //---------------------------------
+ 
+    // add additional NSB to the number of photons
+    Double_t oldphotons = pix.GetNumPhotons();
+    Double_t newphotons = oldphotons + NSB;
+    pix.SetNumPhotons(newphotons);
+
+
+    fHNSB->Fill( NSB/sqrt(ratioArea) );
+    fHPhotons->Fill( oldphotons/sqrt(ratioArea), newphotons/sqrt(ratioArea) );
+
+
+    // error: add sigma of padded noise quadratically
+    Double_t olderror = pix.GetErrorPhot();
+    Double_t newerror = sqrt(olderror*olderror + addSig2);
+    pix.SetErrorPhot(newerror);
+
+
+    Double_t newsigma = sqrt(oldsigma2 + addSig2);
+    ppix.SetRms(newsigma);
+
+    fHSigmaPedestal->Fill(oldsigma, newsigma);
+  } 
+  //----------   end of loop over pixels   ---------------------------------
+
+  // Calculate sigmabar again and crosscheck
+
+
+  //fSigmabar->Calc(*fCam, *fPed, *fEvt);
+  //*fLog << "after padding : " << endl;
+  //fSigmabar->Print("");
+
+
+  //*fLog << "Exit MCT1PadSchweizer::Process();" << endl;
+
+  rc = 0;
+  fErrors[rc]++;
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MCT1PadSchweizer::PostProcess()
+{
+    if (GetNumExecutions() != 0)
+    {
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fErrors[1] << " (" << setw(3) 
+          << (int)(fErrors[1]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: Sigmabar_old > 0" << endl;
+
+    *fLog << " " << setw(7) << fErrors[2] << " (" << setw(3) 
+          << (int)(fErrors[2]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: Zenith angle out of range" << endl;
+
+    *fLog << " " << setw(7) << fErrors[3] << " (" << setw(3) 
+          << (int)(fErrors[3]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: No data for generating Sigmabar" << endl;
+
+    *fLog << " " << setw(7) << fErrors[4] << " (" << setw(3) 
+          << (int)(fErrors[4]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: Target sigma <= Sigmabar_old" << endl;
+
+    *fLog << " " << setw(7) << fErrors[5] << " (" << setw(3) 
+          << (int)(fErrors[5]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: No data for generating Sigma^2-Sigmabar^2" << endl;
+
+    *fLog << " " << setw(7) << fErrors[6] << " (" << setw(3) 
+          << (int)(fErrors[6]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: No data for generating Sigma" << endl;
+
+    *fLog << " " << setw(7) << fErrors[7] << " (" << setw(3) 
+          << (int)(fErrors[7]*100/GetNumExecutions()) 
+          << "%) Evts skipped due to: No data for generating Blind pixels" << endl;
+
+    *fLog << " " << fErrors[0] << " (" 
+          << (int)(fErrors[0]*100/GetNumExecutions()) 
+          << "%) Evts survived the padding!" << endl;
+    *fLog << endl;
+
+    }
+
+    //---------------------------------------------------------------
+    TCanvas &c = *(MH::MakeDefCanvas("PadSchweizer", "", 900, 1200)); 
+    c.Divide(3, 4);
+    gROOT->SetSelectedPad(NULL);
+
+    c.cd(1);
+    fHNSB->SetDirectory(NULL);
+    fHNSB->DrawCopy();
+    fHNSB->SetBit(kCanDelete);    
+
+    c.cd(2);
+    fHSigmaPedestal->SetDirectory(NULL);
+    fHSigmaPedestal->DrawCopy();
+    fHSigmaPedestal->SetBit(kCanDelete);    
+
+    c.cd(3);
+    fHPhotons->SetDirectory(NULL);
+    fHPhotons->DrawCopy();
+    fHPhotons->SetBit(kCanDelete);    
+
+    //--------------------------------------------------------------------
+
+
+    c.cd(4);
+    fHSigmaTheta->SetDirectory(NULL);
+    fHSigmaTheta->SetTitle("(Input) 2D : Sigmabar, \\Theta");
+    fHSigmaTheta->DrawCopy();     
+    fHSigmaTheta->SetBit(kCanDelete);     
+
+    //--------------------------------------------------------------------
+
+
+    c.cd(7);
+    fHBlindPixNTheta->SetDirectory(NULL);
+    fHBlindPixNTheta->SetTitle("(Input) 2D : no.of blind pixels, \\Theta");
+    fHBlindPixNTheta->DrawCopy();     
+    fHBlindPixNTheta->SetBit(kCanDelete);     
+
+    //--------------------------------------------------------------------
+
+
+    c.cd(10);
+    fHBlindPixIdTheta->SetDirectory(NULL);
+    fHBlindPixIdTheta->SetTitle("(Input) 2D : blind pixel Id, \\Theta");
+    fHBlindPixIdTheta->DrawCopy();     
+    fHBlindPixIdTheta->SetBit(kCanDelete);     
+
+
+    //--------------------------------------------------------------------
+    // draw the 3D histogram (input): Theta, pixel, Sigma^2-Sigmabar^2
+
+    c.cd(5);
+    TH2D *l1;
+    l1 = (TH2D*) ((TH3*)fHDiffPixTheta)->Project3D("zx");
+    l1->SetDirectory(NULL);
+    l1->SetTitle("(Input) Sigma^2-Sigmabar^2 vs. \\Theta (all pixels)");
+    l1->SetXTitle("\\Theta [\\circ]");
+    l1->SetYTitle("Sigma^2-Sigmabar^2");
+
+    l1->DrawCopy("box");
+    l1->SetBit(kCanDelete);;
+
+    c.cd(8);
+    TH2D *l2;
+    l2 = (TH2D*) ((TH3*)fHDiffPixTheta)->Project3D("zy");
+    l2->SetDirectory(NULL);
+    l2->SetTitle("(Input) Sigma^2-Sigmabar^2 vs. pixel number (all \\Theta)");
+    l2->SetXTitle("pixel");
+    l2->SetYTitle("Sigma^2-Sigmabar^2");
+
+    l2->DrawCopy("box");
+    l2->SetBit(kCanDelete);;
+
+    //--------------------------------------------------------------------
+    // draw the 3D histogram (input): Theta, pixel, Sigma
+
+    c.cd(6);
+    TH2D *k1;
+    k1 = (TH2D*) ((TH3*)fHSigmaPixTheta)->Project3D("zx");
+    k1->SetDirectory(NULL);
+    k1->SetTitle("(Input) Sigma vs. \\Theta (all pixels)");
+    k1->SetXTitle("\\Theta [\\circ]");
+    k1->SetYTitle("Sigma");
+
+    k1->DrawCopy("box");
+    k1->SetBit(kCanDelete);
+
+    c.cd(9);
+    TH2D *k2;
+    k2 = (TH2D*) ((TH3*)fHSigmaPixTheta)->Project3D("zy");
+    k2->SetDirectory(NULL);
+    k2->SetTitle("(Input) Sigma vs. pixel number (all \\Theta)");
+    k2->SetXTitle("pixel");
+    k2->SetYTitle("Sigma");
+
+    k2->DrawCopy("box");
+    k2->SetBit(kCanDelete);;
+
+
+    //--------------------------------------------------------------------
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1PadSchweizer.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1PadSchweizer.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1PadSchweizer.h	(revision 9772)
@@ -0,0 +1,80 @@
+#ifndef MARS_MCT1PadSchweizer
+#define MARS_MCT1PadSchweizer
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TH2D;
+class TH3D;
+
+class MGeomCam;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MMcEvt;
+class MSigmabar;
+class MParList;
+class MBlindPixels;
+
+class MCT1PadSchweizer : public MTask
+{
+private:
+    MGeomCam       *fCam;
+    MCerPhotEvt    *fEvt; 
+    MSigmabar      *fSigmabar;
+    MMcEvt         *fMcEvt;
+    MPedPhotCam   *fPed;
+    MBlindPixels   *fBlinds;
+
+    Int_t          fPadFlag;
+    Int_t          fRunType;
+    Int_t          fGroup;
+
+    Int_t          fErrors[8];
+
+    // plots used for the padding
+    TH2D           *fHBlindPixIdTheta; // 2D-histogram (blind pixel Id vs. Theta)
+    TH2D           *fHBlindPixNTheta; // 2D-histogram (no.of blind pixels vs. Theta)
+    TH2D           *fHSigmaTheta;    // 2D-histogram (sigmabar vs. Theta)
+    TH3D           *fHSigmaPixTheta; // 3D-histogram (Theta, pixel, sigma)
+    TH3D           *fHDiffPixTheta;  // 3D-histogram (Theta, pixel, sigma^2-sigmabar^2)
+
+    // plots for checking the padding
+    TH2D           *fHSigmaPedestal; // 2D-histogram : pedestal sigma after
+                                     //                versus before padding
+    TH2D           *fHPhotons;       // 2D-histogram : no.of photons after
+                                     //                versus before padding
+    TH1D           *fHNSB;           // 1D-histogram : additional NSB
+
+
+public:
+    MCT1PadSchweizer(const char *name=NULL, const char *title=NULL);
+    ~MCT1PadSchweizer();
+
+    void SetHistograms(TH2D *hist2, TH3D *hist3, TH3D *hist3Diff,
+                       TH2D *hist2Pix, TH2D *hist2PixN);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+    
+    void SetPadFlag(Int_t padflag);
+
+    ClassDef(MCT1PadSchweizer, 0)    // task for the padding (Schweizer)
+}; 
+
+#endif
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1PointingCorrCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1PointingCorrCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1PointingCorrCalc.cc	(revision 9772)
@@ -0,0 +1,218 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  03/2003 <mailto:wittek@mppmu.mpg.de>
+!              Nadia Tonello    05/2003 <mailto:tonello@mppmu.mpg.de>
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MCT1PointingCorrCalc                                                   //
+//                                                                         //
+//  This is a task to do the CT1 pointing correction.                      // 
+//                                                                         //
+//  NT: You can correct the Mkn421 data (default setting), or the 1ES1959  //
+//      data.                                                              // 
+//      To change to the correction needed for 1ES1959,  you have to call  //
+//      the member funcion: SetPointedSource                               //
+//                                                                         //
+//  Example:                                                               //
+//      MCT1PointingCorrCalc correct;                                      //
+//      correct.SetPointedSource(MCT1PointingCorrectionCalc::K1959)        //
+//                                                                         // 
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MCT1PointingCorrCalc.h"
+
+#include "MParList.h"
+
+#include "MSrcPosCam.h"
+#include "MGeomCam.h"
+#include "MParameters.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCT1PointingCorrCalc);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCT1PointingCorrCalc::MCT1PointingCorrCalc(const char *srcname,
+                                           const char *name, const char *title)
+  : fSrcName(srcname), fPoiSource(k421)
+{
+    fName  = name  ? name  : "MCT1PointingCorrCalc";
+    fTitle = title ? title : "Task to do the CT1 pointing correction";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MCT1PointingCorrCalc::PreProcess(MParList *pList)
+{
+    MGeomCam *geom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << GetDescriptor() << ": No Camera Geometry available. Using mm-scale for histograms." << endl;
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+    }
+
+   fHourAngle = (MParameterD*)pList->FindObject("HourAngle", "MParameterD");
+    if (!fHourAngle)
+    {
+        *fLog << err << "HourAngle [MParameterD] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    fSrcPos = (MSrcPosCam*)pList->FindObject(fSrcName, "MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << fSrcName << " [MSrcPosCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//Implemented Daniel Kranich's pointing correction for Mkn421 (2001 data)
+//
+
+void MCT1PointingCorrCalc::PointCorr421()
+{
+   //*fLog << "MCT1PointingCorrCalc::Process; fhourangle = " 
+   //      << fhourangle << endl;
+
+   Float_t fhourangle = fHourAngle->GetVal();
+
+   Float_t cx = -0.05132 - 0.001064 * fhourangle 
+                         - 3.530e-6 * fhourangle * fhourangle;
+   cx /= fMm2Deg;
+
+   Float_t cy = -0.04883 - 0.0003175* fhourangle
+                         - 2.165e-5 * fhourangle * fhourangle;
+   cy /= fMm2Deg;
+
+   fSrcPos->SetXY(cx, cy);
+
+   //*fLog << "MCT1PointingCorrCal::Process; fhourangle, cx, cy, fMm2Deg = "
+   //      << fhourangle << ",  " << cx << ",  " << cy << ",  " 
+   //      << fMm2Deg << endl;
+
+   fSrcPos->SetReadyToSave();
+   return;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// NT :Implemente Daniel Kranich's pointing correction for 1ES1959 (2002 data)
+
+void MCT1PointingCorrCalc::PointCorr1959()
+{
+   //*fLog << "MCT1PointingCorrCalc::Process; fhourangle = " 
+   //      << fhourangle << endl;
+
+   Float_t fhourangle = fHourAngle->GetVal();
+
+   Float_t cx = -0.086 - 0.00091 * fhourangle ;
+   cx /= fMm2Deg;
+
+   Float_t cy = -0.083 - 0.001 * fhourangle ;
+   cy /= fMm2Deg;
+
+   fSrcPos->SetXY(cx, cy);
+
+   //*fLog << "MCT1PointingCorrCal::Process; fhourangle, cx, cy, fMm2Deg = "
+   //      << fhourangle << ",  " << cx << ",  " << cy << ",  " 
+   //      << fMm2Deg << endl;
+
+   fSrcPos->SetReadyToSave();
+   return;
+
+}
+// --------------------------------------------------------------------------
+//
+// Do the pointing correction
+//
+Int_t MCT1PointingCorrCalc::Process()
+{
+   // fhourangle is the hour angle [degrees]
+   // (cx, cy) is the source position in the camera [mm]
+   //
+   switch (fPoiSource)
+    {
+    case k421:
+        PointCorr421();
+    case k1959:
+        PointCorr1959();
+    }  
+   return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1PointingCorrCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1PointingCorrCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1PointingCorrCalc.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MCT1PointingCorrCalc
+#define MARS_MCT1PointingCorrCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCT1PointingCorrCalc                                                    //
+//                                                                         //
+// Task to do the pointing correction                                      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MSrcPosCam;
+class MParameterD;
+
+
+class MCT1PointingCorrCalc : public MTask
+{
+public:
+    typedef enum {
+        k421,
+        k1959
+    } PointedSource_t;
+
+private:
+
+    MSrcPosCam   *fSrcPos;
+    TString       fSrcName;
+    MParameterD  *fHourAngle;
+
+    PointedSource_t fPoiSource;
+    Float_t       fMm2Deg;
+
+    void PointCorr421();
+    void PointCorr1959();
+
+public:
+
+    MCT1PointingCorrCalc(const char *srcname="MSrcPosCam",
+                         const char *name=NULL, const char *title=NULL);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    void SetPointedSource(PointedSource_t s) { fPoiSource = s; }
+ 
+    ClassDef(MCT1PointingCorrCalc, 0)   // Task to do the CT1 pointing correction for Mkn421 2001 data or 1ES1959 2002 data
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1ReadAscii.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1ReadAscii.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1ReadAscii.cc	(revision 9772)
@@ -0,0 +1,304 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer, 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCT1ReadAscii
+//
+// Reads a ascii file with CT1 data. The file description and some example
+// files can be found on the Magic homepage.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1ReadAscii.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TList.h>
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+ClassImp(MCT1ReadAscii);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates an array which stores the file names of
+// the files which should be read. If a filename is given it is added
+// to the list.
+//
+MCT1ReadAscii::MCT1ReadAscii(const char *fname,
+			     const char *name, 
+                             const char *title)
+    : fIn(NULL)
+{
+    fName  = name  ? name  : "MCT1ReadAscii";
+    fTitle = title ? title : "Task to loop over events in CT1 ascii file";
+
+    //
+    // remember file name for opening the file in the preprocessor
+    //
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    if (fname)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filename list and the input stream if one exists.
+//
+MCT1ReadAscii::~MCT1ReadAscii()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add this file as the last entry in the chain
+//
+Int_t MCT1ReadAscii::AddFile(const char *txt, Int_t)
+{
+    TNamed *name = new TNamed(txt, "");
+    fFileNames->AddLast(name);
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Bool_t MCT1ReadAscii::OpenNextFile()
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existance of a next file to read
+    //
+    TNamed *file = (TNamed*)fFileNames->First();
+    if (!file)
+        return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const char *name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    fIn = new ifstream(expname);
+
+    const Bool_t noexist = !(*fIn);
+    if (noexist)
+    {
+        *fLog << err << "Cannot open file " << expname << ": ";
+        *fLog << strerror(errno) << endl;
+    }
+    else
+        *fLog << inf << "Open file: '" << name << "'" << endl;
+
+    delete [] expname;
+
+    //
+    // Remove this file from the list of pending files
+    //
+    fFileNames->Remove(file);
+
+    return !noexist;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open the first file in the list. Check for the output containers or create
+// them if they don't exist.
+//
+// Initialize the size of the MPedPhotCam container to 127 pixels (CT1 camera)
+//
+Int_t MCT1ReadAscii::PreProcess(MParList *pList)
+{
+    //
+    // Preprocessing
+    //
+
+    //
+    // Try to open at least one (the first) file
+    //
+    if (!OpenNextFile())
+        return kFALSE;
+
+    //
+    //  look for the MCerPhotEvt class in the plist
+    //
+    fNphot = (MCerPhotEvt*)pList->FindCreateObj("MCerPhotEvt");
+    if (!fNphot)
+        return kFALSE;
+
+    //
+    //  look for the pedestal class in the plist
+    //
+    fPedest = (MPedPhotCam*)pList->FindCreateObj("MPedPhotCam");
+    if (!fPedest)
+        return kFALSE;
+
+    MGeomCam *geom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!geom)
+    {
+        *fLog << err << "MGeomCam not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fPedest->Init(*geom);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read apedestal entry (line) from the file
+//
+void MCT1ReadAscii::ReadPedestals()
+{
+    //
+    // skip the next 4 values
+    //
+    Float_t val;
+
+    *fIn >> val;
+    *fIn >> val;
+    *fIn >> val;
+    *fIn >> val;
+
+    //
+    //    read in the next 127 numbers as the pedestals
+    //
+    for (Int_t i = 0; i<127; i++)
+    {
+        *fIn >> val;
+
+        if (val>0)
+            (*fPedest)[i].Set(0, val);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a data entry (line) from the file
+//
+void MCT1ReadAscii::ReadData()
+{
+    //
+    // five unsused numbers
+    //
+    Int_t val;
+
+    *fIn >> val;   // ener
+    *fIn >> val;   // zenang
+    *fIn >> val;   // sec1
+    *fIn >> val;   // sec2
+
+    //
+    // read in the number of cerenkov photons and add the 'new' pixel
+    // too the list with it's id, number of photons and error
+    //
+    for (Int_t i = 0; i<127; i++ )
+    {
+        Float_t nphot;
+
+        *fIn >> nphot;
+
+        if (nphot > 0.0)
+            fNphot->AddPixel(i, nphot, (*fPedest)[i].GetRms());
+    }
+    fNphot->FixSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the event number and depending on this number decide if
+// pedestals or event data has to be read.
+//
+// If the end of the file is reached try to open the next in the list. If
+// there is now next file stop the eventloop.
+//
+Int_t MCT1ReadAscii::Process()
+{
+    //
+    // FIXME. This function should switch between reading pedestals and
+    // reading event data by the 'switch entry'.
+    // After reading it should set the InputStreamID correctly.
+    // (should use MPedPhotCam )
+    //
+ 
+    //
+    // read in the event nr
+    //
+    Int_t evtnr;
+    *fIn >> evtnr;
+
+    //
+    // check if we are done. Try to open the next file in chain.
+    // If it was possible start reading. If not break the event loop
+    //
+    if (fIn->eof())
+        return OpenNextFile() ? kCONTINUE : kFALSE;
+
+    //
+    // if the first number is negativ this is a pedestal line:
+    // read in pedestals
+    //
+    // FIXME! Set InputStreamID
+
+    if (evtnr < 0)
+    {
+        ReadPedestals();
+        return kCONTINUE;
+    }
+
+    ReadData();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysisct1/MCT1ReadAscii.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1ReadAscii.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1ReadAscii.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MCT1ReadAscii
+#define MARS_MCT1ReadAscii
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TList;
+class MCerPhotEvt;
+class MPedPhotCam;
+
+class MCT1ReadAscii : public MTask
+{
+private:
+    ifstream    *fIn;        // the inputfile
+    MCerPhotEvt *fNphot;     // the data container for all data.
+    MPedPhotCam *fPedest;    // CT1 pedestals
+    TList       *fFileNames; // Array which stores the \0-terminated filenames
+
+    Bool_t OpenNextFile();
+
+    void ReadPedestals();
+    void ReadData();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MCT1ReadAscii(const char *filename=NULL,
+                  const char *name=NULL,
+                  const char *title=NULL);
+
+    ~MCT1ReadAscii();
+
+    Int_t AddFile(const char *fname, Int_t dummy=-1);
+
+    ClassDef(MCT1ReadAscii, 0)	// Reads the CT1 data file
+};
+
+#endif
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1ReadPreProc.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1ReadPreProc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1ReadPreProc.cc	(revision 9772)
@@ -0,0 +1,1171 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCT1ReadPreProc
+//
+// Reads a output file of the CT1 preproc.
+//
+// Implements usage of a selector (see MRead) Use such a filter to skip
+// events before reading! But never use a filter which needs read data
+// as input...
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//    MCerPhotEvt     the data container for all data.
+//    MPedPhotCam     CT1 pedestals
+//    MMcEvt          monte carlo data container for MC files
+//    MMcTrig         mc data container for trigger information
+//    MSrcPosCam      source position in the camera
+//    MBadPixelsCam   Array holding blind pixels
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1ReadPreProc.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TList.h>
+#include <TSystem.h>
+#include <TRandom3.h>
+
+#define LINUX
+#define HISTO void
+#define HBOOK_FILE int
+#include "defines.h"
+#include "structures.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MFilter.h"
+
+#include "MParList.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MRawRunHeader.h"
+#include "MTaskList.h"
+
+#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+#include "MBinning.h"
+
+#include "MParameters.h"
+
+ClassImp(MCT1ReadPreProc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates an array which stores the file names of
+// the files which should be read. If a filename is given it is added
+// to the list.
+//
+MCT1ReadPreProc::MCT1ReadPreProc(const char *fname, const char *name,
+                                 const char *title) : fIn(NULL), fEntries(0)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Reads a CT1 preproc data file";
+
+    //
+    // remember file name for opening the file in the preprocessor
+    //
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    if (fname)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filename list and the input stream if one exists.
+//
+MCT1ReadPreProc::~MCT1ReadPreProc()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add this file as the last entry in the chain
+//
+Int_t MCT1ReadPreProc::AddFile(const char *txt, int)
+{
+    const char *name = gSystem->ExpandPathName(txt);
+
+    TString fname(name);
+    delete [] name;
+
+    if (!CheckHeader(fname))
+    {
+        *fLog << warn << "WARNING - Problem reading header... ignored." << endl;
+        return 0;
+    }
+
+    const Int_t n = GetNumEvents(fname);
+    if (n==0)
+    {
+        *fLog << warn << "WARNING - File contains no data... ignored." << endl;
+        return 0;
+    }
+
+    fEntries += n;
+
+    *fLog << inf << "File " << txt << " contains " << n << " events (Total=" << fEntries << ")" << endl;
+
+    fFileNames->AddLast(new TNamed(txt, ""));
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print data from the header to the screen and analyse the header data,
+// means store and copy the needed data into Mars structures and
+// data members
+//
+void MCT1ReadPreProc::ProcessRunHeader(const struct outputpars &outpars)
+{
+    if (outpars.inumpixels != iMAXNUMPIX)
+        *fLog << warn << "WARNING! File doesn't contain " << iMAXNUMPIX << " Pixels... maybe corrupt." << endl;
+
+    fNumEventsInRun = 0;
+
+    //
+    // ------------------- Output some stuff -----------------------
+    //
+
+    // int     itelescope;       // number of the CT which took the data
+    *fLog << inf << "Telescope: CT" << outpars.itelescope;
+
+    // float   flongitude_deg;   // longitude (counted positive towards West) of CT position */
+    // float   flatitude_deg;    // latitude (counted positive towards North) of CT position */
+    *fLog << " located @ Longitude=" << outpars.flongitude_deg;
+    *fLog << "deg  Latitude=" << outpars.flatitude_deg << "deg" << endl;
+
+    // int     irunnum;          // run number (from parameters file)
+    fRawRunHeader->SetRunNumber(outpars.irunnum);
+    fRawRunHeader->SetReadyToSave();
+
+    // enum    onoroff {NEITHER_ON_NOR_OFF, OFF_SOURCE, ON_SOURCE} eruntype; // runtype
+    *fLog << "Run:       #" << outpars.irunnum << "  (";
+    switch (outpars.eruntype)
+    {
+    case NEITHER_ON_NOR_OFF: *fLog << "unknown";    break;
+    case OFF_SOURCE:         *fLog << "off-source"; break;
+    case ON_SOURCE:          *fLog << "on-source";  break;
+    default:                 *fLog << (int)outpars.eruntype; break;
+    }
+    *fLog << ", ";
+    switch (outpars.etrackmode)
+    {
+    case NORMAL:  *fLog << "normal tracking";  break;
+    case REVERSE: *fLog << "reverse tracking"; break;
+    case DUNNO:   *fLog << "unknown tracking"; break;
+    default:      *fLog << (int)outpars.etrackmode; break;
+    }
+    *fLog << ")" << endl;
+
+    //double  dsourcera_hours;  // right ascension of observed source in hours
+    //double  dsourcedec_deg;   // declination of observed source in degrees
+    *fLog << "Source:    RA=" << outpars.dsourcera_hours << "h  DEC=";
+    *fLog << outpars.dsourcedec_deg << "deg" << endl;
+
+    //int     inummuonpixels;   // number of pixels in the muon shield
+    //int     inumcointdcs;     // number of coincidence tdcs recorded in the runfile
+    //float   fpixdiameter_deg; // smallest pixel diameter (degrees) (from parameters file) */
+
+    // enum    axes {RA, DEC, ALT, AZ} ese1_is; // name of the axis to which shaft encoder 1 is attached (implies the type of mount)
+    *fLog << "Shaftencoder 1 @ ";
+    switch (outpars.ese1_is)
+    {
+    case RA:  *fLog << "RA";  break;
+    case DEC: *fLog << "DEC"; break;
+    case ALT: *fLog << "ALT"; break;
+    case AZ:  *fLog << "AZ";  break;
+    default:  *fLog << (int)outpars.ese1_is; break;
+    }
+    *fLog << endl;
+
+    // int     isezeropos[2];       // zero position of shaftencoders 1 and 2 (from parameters file)
+    *fLog << "SE Zero:   SE(1)=" << outpars.isezeropos[0] << "  ";
+    *fLog << "SE(2)=" << outpars.isezeropos[1] << endl;
+
+    // int     iaz_rev_track_corr;  // correction for the azimuth shaft encoder (ALT/AZ mount only) in reverse tracking mode
+    // int     ialt_rev_track_corr; // correction for the altitude shaft encoder (ALT/AZ mount only) in reverse tracking mode
+    *fLog << "Reverse tracking corrections: SE(az)=" << outpars.iaz_rev_track_corr;
+    *fLog << "  SE(alt)=" << outpars.ialt_rev_track_corr << endl;
+
+    // float   fbendingcorr;        // bending correction factor (ALT/AZ mount only)
+    // float   fextinction;         // atmospheric extinction (typically taken from the Carlsberg Meridian Circle data)
+    *fLog << "Bending: Correction factor=" << outpars.fbendingcorr << "  ";
+    *fLog << "Extinction=" << outpars.fextinction << endl;
+
+    // Boolean bdontusepix[iMAXNUMPIX]; // bdontusepix is set true if the pixel should not be used in image analysis, otherwise it is true;
+
+    fBlinds->Clear();
+    *fLog << "Don't use pixels: ";
+    for (int i=0; i<iMAXNUMPIX; i++)
+        if (outpars.bdontusepix[i])
+        {
+            *fLog << i << " ";
+            (*fBlinds)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+        }
+    *fLog << endl;
+
+    *fLog << "Exclude pixels: ";
+    // Boolean bexcludepix[iMAXNUMPIX];
+    for (int i=0; i<iMAXNUMPIX; i++)
+        if (outpars.bexcludepix[i])
+        {
+            *fLog << i << " ";
+            (*fBlinds)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+        }
+    *fLog << endl;
+
+    // save blind pixels for all events of this run
+    fBlnd.Set(iMAXNUMPIX);
+    for (int i=0; i<iMAXNUMPIX; i++)
+        fBlnd[i] = (*fBlinds)[i].IsBad() ? 1 : 0;
+
+    fBlinds->SetReadyToSave();
+
+    /* bexcludepix[] is set TRUE (== exclude from pedestal, Laser
+     * calibration and the further analysis) when the Mean value
+     * of a pixel inside a pedestal Run is larger than 50 or ( || )
+     * if the pedestal RMS value of this pixel is larger than 5.0
+     * This is reflected in the (new for versions >= 0.4)
+     * variable "pixonoff" in the ntuple written by preproc:
+     * preproc.nt.hbook
+     *
+     * When the pixel is excluded by the user it will get a -2 otherwise
+     * pixonoff = 0.
+     * Additive to this a -1 is added when preproc excludes the pixel
+     * for a given Run. So the actual value tells you whether you caught
+     * it already by hand or not.
+     *
+     * A plot of pixonoff may also be handy to tell you the status of your
+     * ADC equipment. */
+
+    // float   fphotoel_per_adccnt[iMAXNUMPIX]; // conversion factors for the pixel signals */
+    /*
+    float padc = outpars.fphotoel_per_adccnt[0];
+    *fLog << "Phe/ADC (pixel 0): " << padc << endl;
+    for (int i=0; i<iMAXNUMPIX; i++)
+        *fLog << outpars.fphotoel_per_adccnt[i] << " ";
+    *fLog << endl;
+    */
+    /*
+     --- USEFULL? NEEDED? ---
+     int     irubminusutc_usecs;              // difference between rubidium clock and UTC in microseconds
+     int     isum_thresh_phot;                // threshold for the total sum of photoelectrons filter
+     int     i2out_thresh_phot;               // threshold for the two-pixels-out-of-all software
+     int     imuoncut_thresh_adccnt[iMAXNUMMUONPIX]; // thresholds for the muon cut
+     Boolean bmuon_suppression;               // "Dolby" noise reduction flag
+     float   ftolerated_pointerror_deg;       // maximum tolerated pointing error in the position
+     */
+
+    // float fxpointcorr_deg; // pointing correction (to be added along the camera x axis) e.g. from point run */
+    // float fypointcorr_deg; // pointing correction (to be added along the camera y axis) e.g. from point run */
+    *fLog << "Pointing correction: dx=" << outpars.fxpointcorr_deg << "deg  ";
+    *fLog << "dy=" << outpars.fypointcorr_deg << "deg" << endl;
+
+    // FIXME? Is x-y echanged between Mars CT1 geometry and CT1 definition?
+    fSrcPos->SetXY(-outpars.fypointcorr_deg/fGeom->GetConvMm2Deg(),
+                   -outpars.fxpointcorr_deg/fGeom->GetConvMm2Deg());
+    fSrcPos->SetReadyToSave();
+
+    /*
+     --- USEFULL? NEEDED? ---
+     float   fcamera_align_angle_deg;         // the angle between the camera y-axis and the meridian when a culminating object is observed (defined counter-clockwise looking at the sky)
+     int     iratecalc_numevents_odd;         // number of events used in the rate calculation (must be odd)
+     int     inumpedfile;                     // number of the pedestal file used
+     int     inumpedrun;                      // number of the pedestal run used in the file (starting at 0)
+     int     inumcalfile;                     // number of the calibration file used
+     int     inumlaserrun;                    // number of the laserrun used in the file (starting at 0)
+     int     inumtellogfile;                  // number of the TelLog file to be used
+     int     inumtellogrun;                   // number of the tellog entry (Runnumber) used from the log file
+     int     imcparticle;                     // CORSIKA-coded Monte Carlo particle type.
+    */
+
+    // ----- preprocessing results -----
+
+    // int     istart_mjdate_day;                 // MJD of run start (first event) */
+    // int     iend_mjdate_day;                   // MJD of run end (last event) */
+    // int     irunduration_secs;                 // difference between start and end time (secs) */
+    *fLog << "Run Time: From " << outpars.istart_mjdate_day << " to ";
+    *fLog << outpars.iend_mjdate_day << " (MJD),  Duration=";
+    *fLog << outpars.irunduration_secs/3600 << "h";
+    *fLog << (outpars.irunduration_secs/60)%60 << "m";
+    *fLog << outpars.irunduration_secs%60 << "s" << endl;
+    fRawRunHeader->SetRunTime(outpars.istart_mjdate_day, outpars.iend_mjdate_day);
+    fRawRunHeader->SetReadyToSave();
+
+    /*
+     --- USEFULL? NEEDED? ---
+     int     iproc_mjdate;                      // MJD of data processing (i.e. creation of this file)
+     */
+
+    // int     iproc_evts;                        // number of events processed */
+    *fLog << "Number of processed events: " << outpars.iproc_evts << endl;
+
+    // --- USEFULL? NEEDED? ---
+    // double  dactual_sourcera_hours;            // for off runs: the false source (that should have been) observed */
+
+    // float   frms_pedsig_phot[iMAXNUMPIX];      // standard deviation of the calibrated signals from the pedestal run */
+    fPedest->Init(*fGeom);
+
+    fPedRMS.Set(iMAXNUMPIX);
+
+    *fLog << "PedestalRMS : ";
+    for (Int_t i=0; i<iMAXNUMPIX; i++)
+    {
+        (*fPedest)[i].Set(0, outpars.frms_pedsig_phot[i]);
+        *fLog << outpars.frms_pedsig_phot[i] << " "; 
+        fPedRMS[i] = outpars.frms_pedsig_phot[i];
+    }
+    *fLog << endl;
+
+    fPedest->SetReadyToSave();
+
+    // Used to communicate the mean over all pixels
+    // pedestal RMS into the Runs NTuple, as it might
+    // be used for e.g. quality cuts.
+    // float   fpedrms_mean;
+    *fLog << "Pedestal RMS: " << outpars.fpedrms_mean << endl;
+
+    // The average current over the active pixels
+    // for this run. This is done separately for
+    // ON and OF runs.
+    //float   fcurrent_mean;
+
+    // enum eERRORTOLERANCE {CAUTIOUS=0, GOODPHYSICS, TANK} eerrortolerance;
+    /* 0 == "cautious", exits on any reason (but tells in
+     * the .err file,
+     * 1 == "goodphysics", exits when physics could be affected
+     * by the error,
+     * 2 == "tank", never exits except on coredumps and when
+     * all files have been processed. Do not use such files for
+     * physics analysis!
+     *
+     * NOTE: the capital letter words are the enums, the small letter
+     * words must be used inside the parameter file. */
+
+    // enum eMCTRIGGERFLAG {ALL=0, FLAG, NOFLAG} emctriggerflag;
+    /* all: all events which survive the filter are written to the
+     *      events NTuple.
+     * flag: When Dorota's triggerflag is set to 1 for a particular
+     *       event, it shall be written to the output. All others shall
+     *       just be disregarded. (Default)
+     * noflag: Opposite of 'flag': only events with triggerflag = 0 shall
+     *         be treated further. */
+
+    *fLog << "Particle Id #" << outpars.imcparticle << endl;
+    *fLog << "Right Ascension: " << outpars.dsourcera_hours << "h" << endl;
+    *fLog << "Declination: " << outpars.dsourcedec_deg << "deg" << endl;
+
+    // Next statement commented out because bmontecarlo was set wrongly
+    //fIsMcFile = outpars.bmontecarlo==TRUE;
+    fIsMcFile = (outpars.dsourcera_hours==0 && outpars.dsourcedec_deg==0 &&
+                 outpars.imcparticle != 0);
+
+    if (fIsMcFile != (outpars.bmontecarlo==TRUE))
+    {
+        *fLog << "File tells you that it is a ";
+        *fLog << (outpars.bmontecarlo ? "Monte Carlo" : "Real Data");
+        *fLog << " file." << endl;
+    }
+
+    *fLog << "File detected as a ";
+    *fLog << (fIsMcFile ? "Monte Carlo" : "Real Data");
+    *fLog << " file." << endl;
+    *fLog << " " << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read CT1 PreProc File Header:
+//
+Int_t MCT1ReadPreProc::ReadRunHeader()
+{
+    char cheadertitle[iHEADERTITLELENGTH];
+    fIn->read(cheadertitle, iHEADERTITLELENGTH);
+
+    TString s = cheadertitle;
+    TString m = cTITLE_TEMPLATE;
+
+    if (!s.BeginsWith(m(0, m.First('%'))))
+        return kFALSE;
+
+    *fLog << cheadertitle << flush;
+
+    // cTITLE_TEMPLATE "PREPROC V%f/S%f CT %d RUN %d %d PROCMJD %d\n"
+    struct outputpars outpars;
+
+    int dummy;
+
+    Float_t fpreprocversion, structversion;
+    sscanf(cheadertitle, cTITLE_TEMPLATE,
+           &fpreprocversion,    &structversion,
+           &outpars.itelescope, &outpars.irunnum,
+           &dummy/*&outpars.eruntype*/, &outpars.iproc_mjdate);
+
+    if (fpreprocversion<0.6)
+    {
+        *fLog << err << "Sorry, only files from PreProc V0.6 and newer are supported." << endl;
+        return kFALSE;
+    }
+
+    //
+    // This is a stupid way of getting rid of numerical uncertanties when
+    // comparing floating point numbers (Argh...)
+    //
+    TString s1 = Form("%.2f", structversion);
+    TString s2 = Form("%.2f", STRUCT_VERSION);
+
+    if (s1 != s2)
+    {
+        *fLog << warn << "WARNING: Version of C-structures of file (V";
+        *fLog << s1 << ") not identical with current structures (V";
+        *fLog << s2 << ")" << endl;
+    }
+
+    fIn->read((char*)&outpars, sizeof(struct outputpars));
+
+    ProcessRunHeader(outpars);
+
+    //rwagner: ReInit whenever new run commences
+    // rc==-1 means: ReInit didn't work out
+
+    MTaskList *tlist = (MTaskList*)fParList->FindCreateObj("MTaskList");
+    if (!tlist)
+        return -1;
+
+    if (!tlist->ReInit(fParList))
+        return -1;
+
+    return kTRUE;
+}
+
+Int_t MCT1ReadPreProc::ReadRunFooter()
+{
+    char cheadertitle[iHEADERTITLELENGTH];
+    fIn->read(cheadertitle, iHEADERTITLELENGTH);
+    /*
+     sscanf(cheadertitle, cEND_EVENTS_TEMPLATE,
+     &filterres.ifilter_passed_evts);
+     */
+
+    TString s = cheadertitle;
+    TString m = cEND_EVENTS_TEMPLATE;
+    Int_t p = m.First('%');
+
+
+    if (!s.BeginsWith(m(0,p)))
+    {
+        fIn->seekg(-iHEADERTITLELENGTH, ios::cur);
+        return 0;
+    }
+
+    *fLog << inf << cheadertitle << flush;
+
+    struct filterresults filterres;
+    fIn->read((char*)&filterres, sizeof(struct filterresults));
+    /*
+     int   imax_alt_arcs;            // maximum altitude reached during the run
+     int   iaz_at_max_alt_arcs;      // azimuth at the time the max. alt. was reached
+     int   itimeaverage_alt_arcs;    // altitude averaged over the runtime
+     int   icoord_inconsist_evts;    // number of events with time-coordinate inconsistency in this run
+     int   ifilter_passed_evts;      // number of events which passed the filter
+     int   imuon_fail_evts;          // number of events rejected as muons (other filters passed)
+     int   i2out_fail_evts;          // number of events which failed in the two out of all pixels software trigger
+     int   imuon_and_2out_fail_evts; // number of events failing in both muon and 2out filter
+     int   isum_fail_evts;           // number of events which failed the sum-of-all-calibrated ADC counts filter
+     int   isum_and_muon_fail_evts;  // number of events which failed in both the sum and the muon filter
+     int   isum_and_2out_fail_evts;  // number of events which failed in both the sum and the 2out filter
+     int   iall_filters_fail_evts;   // number of events which failed in all filters
+     float favg_event_rate_hz;       // average rate before filtering
+     float fstddev_event_rate_hz;    // standard deviation of the rate before filtering
+     */
+
+    if (fNumEventsInRun!=(UInt_t)filterres.ifilter_passed_evts)
+    {
+        *fLog << err << "ERROR! Number of events in run (" << (UInt_t)filterres.ifilter_passed_evts;
+        *fLog << ") doesn't match number of read events (";
+        *fLog << fNumEventsInRun << ")" << endl;
+        *fLog << "       File corrupted." << endl;
+        return -1;
+    }
+
+    fNumFilterEvts += fNumEventsInRun;
+    fNumRuns++;
+
+    *fLog << inf << "Read " << fNumEventsInRun << " events from run (Total=";
+    *fLog << fNumFilterEvts << "/" << fEntries << " [";
+    *fLog << 100*fNumFilterEvts/fEntries << "%], Runs=" << fNumRuns << ")";
+    *fLog << endl;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Bool_t MCT1ReadPreProc::OpenNextFile()
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existence of a next file to read
+    //
+    if (fNumFile >= (UInt_t)fFileNames->GetSize())
+        return kFALSE;
+
+    TNamed *file = (TNamed*)fFileNames->At(fNumFile);
+
+    //TNamed *file = (TNamed*)fFileNames->GetFirst();
+    //if (!file)
+    //    return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const TString name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    const TString fname(expname);
+    delete [] expname;
+
+    //
+    // Remove this file from the list of pending files
+    //
+    //fFileNames->Remove(file);
+
+    *fLog << inf << "Open file: '" << name << "'" << endl;
+
+    if (!CheckHeader(fname))
+        return kFALSE;
+
+    fNumFile++;
+
+    fIn = new ifstream(fname);
+    if (!*fIn)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "-----------------------------------------------------------------------" << endl;
+
+    switch (ReadRunHeader())
+    {
+    case kFALSE:
+        *fLog << warn << "Unable to read first run header... skipping file." << endl;
+        return kFALSE;
+    case -1:
+        *fLog << warn << "ReInit of Tasklist didn't succeed." << endl;
+        return kFALSE;
+    default:
+        *fLog << "After opening next file: Number of Events #" << fNumEventsInRun << endl;
+        return kTRUE;
+    }
+}
+
+Bool_t MCT1ReadPreProc::CheckHeader(const TString fname) const
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        *fLog << dbginf << err << "ERROR - Cannot open file '" << fname << "'" << endl;
+        return kFALSE;
+    }
+
+    char cheadertitle[iHEADERTITLELENGTH];
+    fin.read(cheadertitle, iHEADERTITLELENGTH);
+
+    Float_t fpreprocversion, structversion;
+    Int_t dummyi;
+
+    sscanf(cheadertitle, cTITLE_TEMPLATE,
+           &fpreprocversion, &structversion,
+           &dummyi, &dummyi, &dummyi, &dummyi);
+
+    if (fpreprocversion < 0.6)
+    {
+        *fLog << dbginf << err << "ERROR - You must use PreProc V0.6 or higher." << endl;
+        return kFALSE;
+    }
+
+    if (STRUCT_VERSION > structversion)
+    {
+        *fLog << warn << "WARNING: Version of C-structures of file (V";
+        *fLog << structversion << ") newer than current structures (V";
+        *fLog << STRUCT_VERSION << ")" << endl;
+    }
+
+    *fLog << "Current structures: " << STRUCT_VERSION << "  ";
+    *fLog << "Structures in file: " << structversion << "  ";
+    *fLog << "Used preproc version: " << fpreprocversion << endl;
+
+    return kTRUE;
+}
+
+
+Int_t MCT1ReadPreProc::GetNumEvents(const TString fname) const
+{
+    *fLog << inf << "Scanning file " << fname << " for size" << flush;
+
+    ifstream fin(fname);
+    if (!fin)
+    {
+        *fLog << dbginf << err << "ERROR - Opening file." << endl;
+        return 0;
+    }
+
+    const TString m(cEND_EVENTS_TEMPLATE);
+    const Int_t p = m.First('%');
+    const TString test = m(0, p);
+
+    Int_t nevts = 0;
+    Int_t nruns = 0;
+
+    while (!fin.eof() && fin.peek()!=EOF)
+    {
+        fin.seekg(iHEADERTITLELENGTH, ios::cur);
+        fin.seekg(sizeof(struct outputpars), ios::cur);
+
+        while (1)
+        {
+            if (fin.peek()==cEND_EVENTS_TEMPLATE[0])
+            {
+                char cheadertitle[iHEADERTITLELENGTH];
+                fin.read(cheadertitle, iHEADERTITLELENGTH);
+
+                const TString s = cheadertitle;
+                if (s.BeginsWith(test))
+                {
+                    fin.seekg(sizeof(struct filterresults), ios::cur);
+                    nruns++;
+                    break;
+                }
+
+                fin.seekg(-iHEADERTITLELENGTH, ios::cur);
+            }
+
+            fin.seekg(sizeof(struct eventrecord), ios::cur);
+            if (fin.eof())
+                break;
+
+            nevts++;
+        }
+        *fLog << "." << flush;
+    }
+
+    *fLog << "done." << endl;
+    *fLog << "Found " << nevts << " events in " << nruns << " runs." << endl;
+
+    return nevts;
+}
+
+Bool_t MCT1ReadPreProc::Rewind()
+{
+    fNumFilterEvts = 0;
+    fNumEvents     = 0;
+    fNumRuns       = 0;
+    fNumFile       = 0;
+    if (fIn)
+        delete fIn;
+
+    fIn=NULL;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open the first file in the list. Check for the output containers or create
+// them if they don't exist.
+//
+// Initialize the size of the MPedPhotCam container to 127 pixels (CT1 camera)
+//
+Int_t MCT1ReadPreProc::PreProcess(MParList *pList)
+{
+    fParList = pList;
+
+    //
+    //  look for the HourAngle container in the plist
+    //
+    fHourAngle = (MParameterD*)pList->FindCreateObj("MParameterD", "HourAngle");
+    if (!fHourAngle)
+        return kFALSE;
+    fHourAngle->SetTitle("Store the CT1 hour angle [deg]");
+
+    //
+    //  look for the ThetaOrig container in the plist
+    //
+    fThetaOrig = (MParameterD*)pList->FindCreateObj("MParameterD", "ThetaOrig");
+    if (!fThetaOrig)
+        return kFALSE;
+    fThetaOrig->SetTitle("Store the original CT1 zenith angle [rad]");
+
+    //
+    //  look for the MCerPhotEvt class in the plist
+    //
+    fNphot = (MCerPhotEvt*)pList->FindCreateObj("MCerPhotEvt");
+    if (!fNphot)
+        return kFALSE;
+
+    //
+    //  look for the pedestal class in the plist
+    //
+    fPedest = (MPedPhotCam*)pList->FindCreateObj("MPedPhotCam");
+    if (!fPedest)
+        return kFALSE;
+
+    //
+    //  look for the time class in the plist
+    //
+    fTime = (MTime*)pList->FindCreateObj("MTime");
+    if (!fTime)
+        return kFALSE;
+
+    //
+    //  look for the pedestal class in the plist
+    //
+    fBlinds = (MBadPixelsCam*)pList->FindCreateObj("MBadPixelsCam");
+    if (!fBlinds)
+        return kFALSE;
+
+    //
+    //  look for the source position in the camera
+    //
+    fSrcPos = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam");
+    if (!fSrcPos)
+        return kFALSE;
+
+    //
+    //  look for the camera geometry
+    //
+    fGeom = (MGeomCam*)pList->FindCreateObj("MGeomCamCT1", "MGeomCam");
+    if (!fGeom)
+        return kFALSE;
+
+    //
+    //  look for the mc event class
+    //
+    fMcEvt = (MMcEvt*)pList->FindCreateObj("MMcEvt");
+    if (!fMcEvt)
+        return kFALSE;
+
+    //
+    //  look for the mc trigger class
+    //
+    fMcTrig = (MMcTrig*)pList->FindCreateObj("MMcTrig");
+    if (!fMcTrig)
+        return kFALSE;
+
+    //
+    //  look for the raw run header class
+    //
+    fRawRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
+    if (!fRawRunHeader)
+        return kFALSE;
+
+    fBinningT = (MBinning*)pList->FindObject("BinningTheta");
+
+    Rewind();
+
+    fPedest->Init(*fGeom);
+
+    return GetSelector() ? GetSelector()->CallPreProcess(pList) : kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Smear Theta uniformly in a bin of Theta
+//   theta [rad]
+//   SmearTheta [rad]
+//
+Double_t MCT1ReadPreProc::SmearTheta(Double_t theta)
+{
+    if (!fBinningT)
+        return theta;
+
+    const Int_t bin = fBinningT->FindLoEdge(theta * 180/TMath::Pi());
+    if (bin<0)
+        return theta;
+
+    // smear Theta within the Theta bin
+    const Double_t low = fBinningT->GetEdges()[bin];
+    const Double_t up  = fBinningT->GetEdges()[bin+1];
+
+    // "up-": Do not allow the upper edge
+    return (up - gRandom->Uniform() * (up-low)) * TMath::Pi()/180;
+}
+
+// --------------------------------------------------------------------------
+//
+// Discretize Theta according to the binning in Theta
+//   theta [rad]
+//   DiscreteTheta [rad]  (= bin center)
+//
+Double_t MCT1ReadPreProc::DiscreteTheta(Double_t theta)
+{
+    if (!fBinningT)
+        return theta;
+
+    const Int_t bin = fBinningT->FindLoEdge(theta * 180/TMath::Pi());
+    if (bin<0)
+        return theta;
+
+    const Double_t low = fBinningT->GetEdges()[bin];
+    const Double_t up  = fBinningT->GetEdges()[bin+1];
+
+    return 0.5*(up+low) * TMath::Pi()/180;
+}
+
+// --------------------------------------------------------------------------
+//
+// Analyse the event data, means store and copy the needed data into
+// Mars structures and data members
+//
+Bool_t MCT1ReadPreProc::ProcessEvent(const struct eventrecord &event)
+{
+    /*
+    if (fRawRunHeader->GetRunNumber() == 1)
+    {
+        *fLog << "eventrecord" << endl;
+        *fLog << "isecs_since_midday = " << event.isecs_since_midday << endl;
+        *fLog << "isecfrac_200ns     = " << event.isecfrac_200ns << endl;
+        *fLog << "snot_ok_flags      = " << event.snot_ok_flags << endl;
+        *fLog << "ialt_arcs          = " << event.ialt_arcs << endl;
+        *fLog << "iaz_arcs           = " << event.iaz_arcs << endl;
+        *fLog << "ipreproc_alt_arcs  = " << event.ipreproc_alt_arcs << endl;
+        *fLog << "ipreproc_az_arcs   = " << event.ipreproc_az_arcs << endl;
+        *fLog << "ifieldrot_arcs     = " << event.ifieldrot_arcs << endl;
+
+        *fLog << "srate_millihz      = " << event.srate_millihz << endl;
+        *fLog << "fhourangle         = " << event.fhourangle << endl;
+        *fLog << "fmcenergy_tev      = " << event.fmcenergy_tev << endl;
+        *fLog << "fmcsize_phel       = " << event.fmcsize_phel << endl;
+        *fLog << "imcimpact_m        = " << event.imcimpact_m << endl;
+        *fLog << "imcparticle        = " << event.imcparticle << endl;
+        *fLog << "imctriggerflag     = " << event.imctriggerflag << endl;
+    }
+    */
+
+    // reset blind pixels for this event
+    fBlinds->Clear();
+    for (int i=0; i<iMAXNUMPIX; i++)
+        if (fBlnd[i]==1)
+            (*fBlinds)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+
+    // reset pedestal RMS for this event
+    for (Int_t i=0; i<iMAXNUMPIX; i++)
+        (*fPedest)[i].Set(0, fPedRMS[i]);
+
+    //  int   isecs_since_midday; // seconds passed since midday before sunset (JD of run start)
+    //  int   isecfrac_200ns;     // fractional part of isecs_since_midday
+    fTime->SetCT1Time((UInt_t)fRawRunHeader->GetRunStart().GetMjd(), event.isecfrac_200ns, event.isecs_since_midday);
+    fTime->SetReadyToSave();
+
+    /*
+     --- USEFULL? NEEDED? ---
+     short snot_ok_flags;      // the bits in these two bytes are flags for additional information on the event: Everything OK =: all Bits = 0
+
+     // for ALT-AZ mount telescopes: rotation angle of the field of
+     // view; this angle is defined mathematically positive looking
+     // towards the sky as the angle between the hour circle through
+     // the object being tracked and the line through pixel 1 and 2
+     int   ifieldrot_arcs;
+
+     // event rate in milli Hertz before filtering calculated by
+     // iratecalc_numevents_odd/(time[i+iratecalc_numevents_odd/2] -
+     // time[i-iratecalc_numevents_odd/2])
+     // For the first and the last iratecalc_numevents_odd/2
+     // events the rate is assumed to be constant
+     unsigned short srate_millihz;
+
+     // This is the angle between the observation of this event and the
+     // culmination point. It is going to be written into the events NTuple.
+     float fhourangle;
+     */
+
+    //
+    // read in the number of cerenkov photons and add the 'new' pixel
+    // too the list with it's id, number of photons and error
+    // number of photoelectrons measured in each pixel only the
+    // actual number of pixels (outputpars.inumpixels) is written out
+    // short spixsig_10thphot[iMAXNUMPIX];
+    //
+    for (Int_t i=0; i<iMAXNUMPIX; i++)
+    {
+      //*fLog << event.spixsig_10thphot[i] << " ";
+
+      if (event.spixsig_10thphot[i]==0)
+            continue;
+
+        fNphot->AddPixel(i, 0.1*event.spixsig_10thphot[i], (*fPedest)[i].GetRms());
+    }
+    fNphot->FixSize();
+    fNphot->SetReadyToSave();
+
+    // int ipreproc_alt_arcs; // "should be" alt according to preproc (arcseconds)
+    // int ipreproc_az_arcs;  // "should be" az according to preproc (arcseconds)
+
+    // smear Theta in its Theta bin
+    const Double_t theta = TMath::Pi()*(0.5-1./180*event.ialt_arcs/3600);
+    fThetaOrig->SetVal(theta);
+
+    // store hour angle
+    fHourAngle->SetVal(event.fhourangle);
+
+    fMcEvt->Fill(event.isecs_since_midday,     //0, /*fEvtNum*/
+                 fIsMcFile ? event.imcparticle : 0, /*corsika particle type*/
+                 fIsMcFile ? event.fmcenergy_tev*1000 : 0,
+		 0, /* fThi0 */
+		 0, /* fFirTar */
+                 0, /* fzFirInt */
+		 // 0, /* fThet*/
+		 // rwagner: The following should be theta, right? Check with
+		 // altitude fill some lines down...
+		 0, // altitude (arcseconds)
+                 0, /* fPhii */
+                 0, /* fCorD */
+                 0, /* fCorX */
+                 0, /* fCorY */
+                 fIsMcFile ? event.imcimpact_m*100 : 0,
+                 TMath::Pi()/180*event.iaz_arcs/3600, // azimuth (arcseconds)
+		 // fIsMcFile ? SmearTheta(theta) : theta,
+                 DiscreteTheta(theta),
+                 0, /* fTFirst */
+		 0, /* fTLast */
+		 0, /* fL_Nmax */
+		 0, /* fL_t0 */
+		 0, /* fL_tmax */
+		 0, /* fL_a */
+		 0, /* fL_b */
+		 0, /* fL_c */
+		 0, /* fL_chi2 */
+		 0, /* uiPin */
+		 0, /* uiPat */
+		 0, /* uiPre */
+		 0, /* uiPco */
+		 0, /* uiPelS */
+                 (int)(fIsMcFile ? event.fmcsize_phel : 0), /* uiPelC, Simulated SIZE */
+		 0, /* elec */
+		 0, /* muon */
+		 0  /* other */
+                 );
+
+    fMcTrig->SetFirstLevel(event.imctriggerflag);    // MC data from Dorota get a triggerflag: 1 means triggered, 0 not. */
+
+    fMcTrig->SetReadyToSave();
+    fMcEvt->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Because of the file format of the preproc output we have to check at any
+// event where in the file stream we are...
+//
+Bool_t MCT1ReadPreProc::CheckFilePosition()
+{
+    //
+    // Means: If no file is open (first call) try to open the first file
+    //
+    if (!fIn)
+        return kFALSE;
+
+    //
+    // Because we can have 0-event runs in the file we loop as often
+    // as we don't find a new footer-header combination.
+    //
+    while (1)
+    {
+        //
+        // If the first character isn't the first of the footer it must be
+        // an event
+        //
+        if (fIn->peek()!=cEND_EVENTS_TEMPLATE[0])
+            return kTRUE;
+
+        //
+        // Try reading the footer. If this isn't successful...
+        // must be an event
+        //
+        switch (ReadRunFooter())
+        {
+        case -1:
+            return kFALSE;
+        case 0:
+            return kTRUE;
+        }
+
+        *fLog << inf << "Footer found." << endl;
+
+        const char c = fIn->peek();
+
+        //
+        // No after reading the footer check if we reached the end of the file
+        //
+        if (fIn->eof() || c==EOF)
+        {
+            *fLog << "End of file." << endl;
+            return kFALSE;
+        }
+
+        //
+        // If the eof isn't reached a new header must follow. Check for it.
+        //
+        if (c!=cTITLE_TEMPLATE[0])
+        {
+            *fLog << inf << "Error finding new run header in file (possible EOF)... skipping rest of file." << endl;
+            return kFALSE;
+        }
+
+        *fLog << "-----------------------------------------------------------------------" << endl;
+
+
+        if (ReadRunHeader() < 0)
+        {
+            *fLog << warn << "ReInit of Tasklist didn't succeed." << endl;
+            return kFALSE;
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the event number and depending on this number decide if
+// pedestals or event data has to be read.
+//
+// If the end of the file is reached try to open the next in the list. If
+// there is now next file stop the eventloop.
+//
+Int_t MCT1ReadPreProc::Process()
+{
+    //
+    // Check where in the file we are. If neither a new event, nor a
+    // footer/header combination is detected go to the next file.
+    //
+    if (!CheckFilePosition())
+        if (!OpenNextFile())
+            return kFALSE;
+
+    //
+    // Check for a selector. If one is given and returns kFALSE
+    // skip this event.
+    //
+    if (GetSelector())
+    {
+        //
+        // Make sure selector is processed
+        //
+        if (!GetSelector()->CallProcess())
+        {
+            *fLog << err << dbginf << "Processing Selector failed." << endl;
+            return kFALSE;
+        }
+
+        //
+        // Skip Event
+        //
+        if (!GetSelector()->IsConditionTrue())
+        {
+            fIn->seekg(sizeof(struct eventrecord), ios::cur);
+
+            fNumEvents++;
+            fNumEventsInRun++;
+
+            return kCONTINUE;
+        }
+    }
+
+    // event data to be read from the file
+    struct eventrecord event;
+
+
+
+    // read the eventrecord from the file
+    fIn->read((char*)&event, sizeof(struct eventrecord));
+
+    switch (ProcessEvent(event))
+    {
+    case kFALSE:
+        return kFALSE;
+    case kCONTINUE:
+        return kCONTINUE;
+    }
+
+    fNumEvents++;
+    fNumEventsInRun++;
+
+    return kTRUE;
+}
+
+Int_t MCT1ReadPreProc::PostProcess()
+{
+    *fLog << all;
+    *fLog << "Number events passed the filter: " << fNumFilterEvts << endl;
+    *fLog << "Number of Events read from file: " << fNumEvents << endl;
+    *fLog << "Number of Runs read from file:   " << fNumRuns << endl;
+    *fLog << "Number of events detected first: " << fEntries << endl;
+
+    if (fNumEvents!=fNumFilterEvts)
+    {
+        *fLog << warn << "WARNING! Number of events in file doesn't match number of read events..." << endl;
+        *fLog << "         File might be corrupt." << endl;
+    }
+
+    delete fIn;
+    fIn = NULL;
+
+    return GetSelector() ? GetSelector()->CallPostProcess() : kTRUE;
+}
Index: /tags/Mars-V0.9/manalysisct1/MCT1ReadPreProc.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1ReadPreProc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1ReadPreProc.h	(revision 9772)
@@ -0,0 +1,104 @@
+#ifndef MARS_MCT1ReadPreProc
+#define MARS_MCT1ReadPreProc
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class TList;
+class MTime;
+class MMcEvt;
+class MMcTrig;
+class MGeomCam;
+class MSrcPosCam;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MBadPixelsCam;
+class MRawRunHeader;
+class MTaskList;
+class MParList;
+class MParameterD;
+class MBinning;
+
+struct outputpars;
+struct eventrecord;
+
+class MCT1ReadPreProc : public MRead
+{
+private:
+    ifstream *fIn;          // the inputfile
+    TList    *fFileNames;   // Array which stores the \0-terminated filenames
+
+    MGeomCam      *fGeom;    // camera geometry
+    MCerPhotEvt   *fNphot;   // the data container for all data.
+    MPedPhotCam   *fPedest;  // ct1 pedestals
+    MTime         *fTime;    // event time
+    MMcEvt        *fMcEvt;   // monte carlo data container for MC files
+    MMcTrig       *fMcTrig;  // mc data container for trigger information
+    MSrcPosCam    *fSrcPos;  // source position in the camera
+    MBadPixelsCam *fBlinds;  // Array holding blind pixels
+    MRawRunHeader *fRawRunHeader; // raw run header
+    MParList      *fParList;      // parameter list
+    MParameterD   *fHourAngle;    // hour angle [deg]
+    MParameterD   *fThetaOrig;    // original zenith angle [rad]
+    MBinning      *fBinningT;     // Theta binning for the smearing
+
+    Bool_t fIsMcFile;       // Flag whether current run is a MC run
+
+    UInt_t fNumFile;
+    UInt_t fNumEvents;      // number of events counted in all runs in all files
+    UInt_t fNumEventsInRun; // number of events in the counted in th ecurrent run
+    UInt_t fNumRuns;        // number of processed runs of all files
+    UInt_t fEntries;        // entries of all files succesfully added
+    UInt_t fNumFilterEvts;  // number of events mentioned in the runs footers
+
+    TArrayF fPedRMS;
+    TArrayI fBlnd;
+
+    Bool_t OpenNextFile();
+
+    Int_t  GetNumEvents(const TString name) const;
+    Bool_t CheckHeader(const TString fname) const;
+
+    void   ReadPedestals();
+    Int_t  ReadRunHeader();
+    Int_t  ReadRunFooter();
+    Bool_t CheckFilePosition();
+    void   ProcessRunHeader(const struct outputpars &outpars);
+    Bool_t ProcessEvent(const struct eventrecord &event);
+
+    Double_t SmearTheta(Double_t theta);
+    Double_t DiscreteTheta(Double_t theta);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t Rewind();
+
+public:
+    MCT1ReadPreProc(const char *filename=NULL,
+                    const char *name=NULL,
+                    const char *title=NULL);
+
+    ~MCT1ReadPreProc();
+
+    Int_t AddFile(const char *fname, int i=0);
+
+    UInt_t GetEntries() { return fEntries; }
+
+    ClassDef(MCT1ReadPreProc, 0) // Reads the CT1 preproc data file
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1Supercuts.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1Supercuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1Supercuts.cc	(revision 9772)
@@ -0,0 +1,388 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 08/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 08/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MCT1Supercuts                                                         //
+//                                                                         //
+//   this is the container for the parameters of the supercuts             //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1Supercuts.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCT1Supercuts);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+MCT1Supercuts::MCT1Supercuts(const char *name, const char *title)
+  : fParameters(104), fStepsizes(104),
+    fLengthUp(fParameters.GetArray()),   fLengthLo(fParameters.GetArray()+8),
+    fWidthUp(fParameters.GetArray()+16), fWidthLo(fParameters.GetArray()+24),
+    fDistUp(fParameters.GetArray()+32),  fDistLo(fParameters.GetArray()+40),
+    fAsymUp(fParameters.GetArray()+48),  fAsymLo(fParameters.GetArray()+56),
+    fConcUp(fParameters.GetArray()+64),  fConcLo(fParameters.GetArray()+72),
+    fLeakage1Up(fParameters.GetArray()+80), fLeakage1Lo(fParameters.GetArray()+88),
+    fAlphaUp(fParameters.GetArray()+96)
+{
+    fName  = name  ? name  : "MCT1Supercuts";
+    fTitle = title ? title : "Container for the supercut parameters";
+
+    // set supercut parameters to their default values
+    InitParameters();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// set default values for the supercut parameters
+//
+void MCT1Supercuts::InitParameters()
+{
+    //---------------------------------------------------
+    //  these are Daniel's original values for Mkn 421
+
+    fLengthUp[0] =  0.315585;
+    fLengthUp[1] =  0.001455;
+    fLengthUp[2] =  0.203198;
+    fLengthUp[3] =  0.005532;
+    fLengthUp[4] = -0.001670;
+    fLengthUp[5] = -0.020362;
+    fLengthUp[6] =  0.007388;
+    fLengthUp[7] = -0.013463;
+
+    fLengthLo[0] =  0.151530;
+    fLengthLo[1] =  0.028323;
+    fLengthLo[2] =  0.510707;
+    fLengthLo[3] =  0.053089;
+    fLengthLo[4] =  0.013708;
+    fLengthLo[5] =  2.357993;
+    fLengthLo[6] =  0.000080;
+    fLengthLo[7] = -0.007157;
+
+    fWidthUp[0] =  0.145412;
+    fWidthUp[1] = -0.001771;
+    fWidthUp[2] =  0.054462;
+    fWidthUp[3] =  0.022280;
+    fWidthUp[4] = -0.009893;
+    fWidthUp[5] =  0.056353;
+    fWidthUp[6] =  0.020711;
+    fWidthUp[7] = -0.016703;
+
+    fWidthLo[0] =  0.089187;
+    fWidthLo[1] = -0.006430;
+    fWidthLo[2] =  0.074442;
+    fWidthLo[3] =  0.003738;
+    fWidthLo[4] = -0.004256;
+    fWidthLo[5] = -0.014101;
+    fWidthLo[6] =  0.006126;
+    fWidthLo[7] = -0.002849;
+
+    fDistUp[0] =  1.787943;
+    fDistUp[1] =  0;
+    fDistUp[2] =  2.942310;
+    fDistUp[3] =  0.199815;
+    fDistUp[4] =  0;
+    fDistUp[5] =  0.249909;
+    fDistUp[6] =  0.189697;
+    fDistUp[7] =  0;
+
+    fDistLo[0] =  0.589406;
+    fDistLo[1] =  0;
+    fDistLo[2] = -0.083964;
+    fDistLo[3] = -0.007975;
+    fDistLo[4] =  0;
+    fDistLo[5] =  0.045374;
+    fDistLo[6] = -0.001750;
+    fDistLo[7] =  0;
+    
+
+    // dummy values
+
+    fAsymUp[0] =  1.e10;
+    fAsymUp[1] =  0.0;
+    fAsymUp[2] =  0.0;
+    fAsymUp[3] =  0.0;
+    fAsymUp[4] =  0.0;
+    fAsymUp[5] =  0.0;
+    fAsymUp[6] =  0.0;
+    fAsymUp[7] =  0.0;
+
+    fAsymLo[0] = -1.e10;
+    fAsymLo[1] =  0.0;
+    fAsymLo[2] =  0.0;
+    fAsymLo[3] =  0.0;
+    fAsymLo[4] =  0.0;
+    fAsymLo[5] =  0.0;
+    fAsymLo[6] =  0.0;
+    fAsymLo[7] =  0.0;
+
+    fConcUp[0] =  1.e10;
+    fConcUp[1] =  0.0;
+    fConcUp[2] =  0.0;
+    fConcUp[3] =  0.0;
+    fConcUp[4] =  0.0;
+    fConcUp[5] =  0.0;
+    fConcUp[6] =  0.0;
+    fConcUp[7] =  0.0;
+
+    fConcLo[0] = -1.e10;
+    fConcLo[1] =  0.0;
+    fConcLo[2] =  0.0;
+    fConcLo[3] =  0.0;
+    fConcLo[4] =  0.0;
+    fConcLo[5] =  0.0;
+    fConcLo[6] =  0.0;
+    fConcLo[7] =  0.0;
+
+    fLeakage1Up[0] =  1.e10;
+    fLeakage1Up[1] =  0.0;
+    fLeakage1Up[2] =  0.0;
+    fLeakage1Up[3] =  0.0;
+    fLeakage1Up[4] =  0.0;
+    fLeakage1Up[5] =  0.0;
+    fLeakage1Up[6] =  0.0;
+    fLeakage1Up[7] =  0.0;
+
+    fLeakage1Lo[0] = -1.e10;
+    fLeakage1Lo[1] =  0.0;
+    fLeakage1Lo[2] =  0.0;
+    fLeakage1Lo[3] =  0.0;
+    fLeakage1Lo[4] =  0.0;
+    fLeakage1Lo[5] =  0.0;
+    fLeakage1Lo[6] =  0.0;
+    fLeakage1Lo[7] =  0.0;
+
+    fAlphaUp[0] = 13.123440; 
+    fAlphaUp[1] = 0;
+    fAlphaUp[2] = 0;
+    fAlphaUp[3] = 0;
+    fAlphaUp[4] = 0;
+    fAlphaUp[5] = 0;
+    fAlphaUp[6] = 0;
+    fAlphaUp[7] = 0;
+
+    //---------------------------------------------------
+    // fStepsizes 
+    // if == 0.0    the parameter will be fixed in the minimization
+    //    != 0.0    initial step sizes for the parameters
+
+    // LengthUp
+    fStepsizes[0] = 0.03;
+    fStepsizes[1] = 0.0002;
+    fStepsizes[2] = 0.02;
+    fStepsizes[3] = 0.0006;
+    fStepsizes[4] = 0.0002;
+    fStepsizes[5] = 0.002;
+    fStepsizes[6] = 0.0008;
+    fStepsizes[7] = 0.002;
+
+    // LengthLo
+    fStepsizes[8]  = 0.02;
+    fStepsizes[9]  = 0.003;
+    fStepsizes[10] = 0.05;
+    fStepsizes[11] = 0.006;
+    fStepsizes[12] = 0.002;
+    fStepsizes[13] = 0.3;
+    fStepsizes[14] = 0.0001;
+    fStepsizes[15] = 0.0008;
+
+    // WidthUp
+    fStepsizes[16] = 0.02;
+    fStepsizes[17] = 0.0002;
+    fStepsizes[18] = 0.006;
+    fStepsizes[19] = 0.003;
+    fStepsizes[20] = 0.002;
+    fStepsizes[21] = 0.006;
+    fStepsizes[22] = 0.002;
+    fStepsizes[23] = 0.002;
+
+    // WidthLo
+    fStepsizes[24] = 0.009;
+    fStepsizes[25] = 0.0007;
+    fStepsizes[26] = 0.008;
+    fStepsizes[27] = 0.0004;
+    fStepsizes[28] = 0.0005;
+    fStepsizes[29] = 0.002;
+    fStepsizes[30] = 0.0007;
+    fStepsizes[31] = 0.003;
+
+    // DistUp
+    fStepsizes[32] = 0.2;
+    fStepsizes[33] = 0.0;
+    fStepsizes[34] = 0.3;
+    fStepsizes[35] = 0.02;
+    fStepsizes[36] = 0.0;
+    fStepsizes[37] = 0.03;
+    fStepsizes[38] = 0.02;
+    fStepsizes[39] = 0.0;
+
+    // DistLo
+    fStepsizes[40] = 0.06;
+    fStepsizes[41] = 0.0;
+    fStepsizes[42] = 0.009;
+    fStepsizes[43] = 0.0008;
+    fStepsizes[44] = 0.0;
+    fStepsizes[45] = 0.005;
+    fStepsizes[46] = 0.0002;
+    fStepsizes[47] = 0.0;
+
+    // AsymUp
+    fStepsizes[48] = 0.0;
+    fStepsizes[49] = 0.0;
+    fStepsizes[50] = 0.0;
+    fStepsizes[51] = 0.0;
+    fStepsizes[52] = 0.0;
+    fStepsizes[53] = 0.0;
+    fStepsizes[54] = 0.0;
+    fStepsizes[55] = 0.0;
+
+    // AsymLo
+    fStepsizes[56] = 0.0;
+    fStepsizes[57] = 0.0;
+    fStepsizes[58] = 0.0;
+    fStepsizes[59] = 0.0;
+    fStepsizes[60] = 0.0;
+    fStepsizes[61] = 0.0;
+    fStepsizes[62] = 0.0;
+    fStepsizes[63] = 0.0;
+
+    // ConcUp
+    fStepsizes[64] = 0.0;
+    fStepsizes[65] = 0.0;
+    fStepsizes[66] = 0.0;
+    fStepsizes[67] = 0.0;
+    fStepsizes[68] = 0.0;
+    fStepsizes[69] = 0.0;
+    fStepsizes[70] = 0.0;
+    fStepsizes[71] = 0.0;
+
+    // ConcLo
+    fStepsizes[72] = 0.0;
+    fStepsizes[73] = 0.0;
+    fStepsizes[74] = 0.0;
+    fStepsizes[75] = 0.0;
+    fStepsizes[76] = 0.0;
+    fStepsizes[77] = 0.0;
+    fStepsizes[78] = 0.0;
+    fStepsizes[79] = 0.0;
+
+    // Leakage1Up
+    fStepsizes[80] = 0.0;
+    fStepsizes[81] = 0.0;
+    fStepsizes[82] = 0.0;
+    fStepsizes[83] = 0.0;
+    fStepsizes[84] = 0.0;
+    fStepsizes[85] = 0.0;
+    fStepsizes[86] = 0.0;
+    fStepsizes[87] = 0.0;
+
+    // Leakage1Lo
+    fStepsizes[88] = 0.0;
+    fStepsizes[89] = 0.0;
+    fStepsizes[90] = 0.0;
+    fStepsizes[91] = 0.0;
+    fStepsizes[92] = 0.0;
+    fStepsizes[93] = 0.0;
+    fStepsizes[94] = 0.0;
+    fStepsizes[95] = 0.0;
+
+    // AlphaUp
+    fStepsizes[96]  = 0.0;
+    fStepsizes[97]  = 0.0;
+    fStepsizes[98]  = 0.0;
+    fStepsizes[99]  = 0.0;
+    fStepsizes[100] = 0.0;
+    fStepsizes[101] = 0.0;
+    fStepsizes[102] = 0.0;
+    fStepsizes[103] = 0.0;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the parameter values from the array 'd'
+//
+//
+Bool_t MCT1Supercuts::SetParameters(const TArrayD &d)
+{
+    if (d.GetSize() != fParameters.GetSize())
+    {
+        *fLog << err << "Sizes of d and of fParameters are different : "
+              << d.GetSize() << ",  " << fParameters.GetSize() << endl;
+        return kFALSE;
+    }
+
+    fParameters = d;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the step sizes from the array 'd'
+//
+//
+Bool_t MCT1Supercuts::SetStepsizes(const TArrayD &d)
+{
+    if (d.GetSize() != fStepsizes.GetSize())
+    {
+        *fLog << err << "Sizes of d and of fStepsizes are different : "
+              << d.GetSize() << ",  " << fStepsizes.GetSize() << endl;
+        return kFALSE;
+    }
+
+    fStepsizes = d;
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1Supercuts.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1Supercuts.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1Supercuts.h	(revision 9772)
@@ -0,0 +1,69 @@
+#ifndef MARS_MCT1Supercuts
+#define MARS_MCT1Supercuts
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MCT1Supercuts : public MParContainer
+{
+private:
+    TArrayD fParameters; // supercut parameters
+    TArrayD fStepsizes;  // step sizes of supercut parameters
+
+    Double_t *fLengthUp; //!
+    Double_t *fLengthLo; //!
+    Double_t *fWidthUp;  //!
+    Double_t *fWidthLo;  //!
+    Double_t *fDistUp;   //!
+    Double_t *fDistLo;   //!
+    Double_t *fAsymUp;   //!
+    Double_t *fAsymLo;   //!
+
+    Double_t *fConcUp;   //!
+    Double_t *fConcLo;   //!
+    Double_t *fLeakage1Up;   //!
+    Double_t *fLeakage1Lo;   //!
+
+    Double_t *fAlphaUp;  //!
+
+
+public:
+    MCT1Supercuts(const char *name=NULL, const char *title=NULL);
+
+    void InitParameters();
+
+    Bool_t SetParameters(const TArrayD &d);
+    Bool_t SetStepsizes(const TArrayD &d);
+
+    const TArrayD &GetParameters() const { return fParameters; }
+    const TArrayD &GetStepsizes()  const { return fStepsizes;  }
+
+    const Double_t *GetLengthUp() const { return fLengthUp; }
+    const Double_t *GetLengthLo() const { return fLengthLo; }
+    const Double_t *GetWidthUp() const  { return fWidthUp; }
+    const Double_t *GetWidthLo() const  { return fWidthLo; }
+    const Double_t *GetDistUp() const   { return fDistUp; }
+    const Double_t *GetDistLo() const   { return fDistLo; }
+    const Double_t *GetAsymUp() const   { return fAsymUp; }
+    const Double_t *GetAsymLo() const   { return fAsymLo; }
+
+    const Double_t *GetConcUp() const   { return fConcUp; }
+    const Double_t *GetConcLo() const   { return fConcLo; }
+
+    const Double_t *GetLeakage1Up() const   { return fLeakage1Up; }
+    const Double_t *GetLeakage1Lo() const   { return fLeakage1Lo; }
+
+    const Double_t *GetAlphaUp() const  { return fAlphaUp; }
+
+    ClassDef(MCT1Supercuts, 1) // A container for the Supercut parameters
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1SupercutsCalc.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1SupercutsCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1SupercutsCalc.cc	(revision 9772)
@@ -0,0 +1,348 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MCT1SupercutsCalc                                                     //
+//                                                                         //
+//   this class calculates the hadronness for the supercuts                //
+//   the parameters of the supercuts are taken                             //
+//                  from the container MCT1Supercuts                       //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCT1SupercutsCalc.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "TFile.h"
+#include "TArrayD.h"
+
+#include "MParList.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MMcEvt.hxx"
+#include "MCerPhotEvt.h"
+#include "MGeomCam.h"
+#include "MHadronness.h"
+#include "MHMatrix.h"
+#include "MCT1Supercuts.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCT1SupercutsCalc);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+
+MCT1SupercutsCalc::MCT1SupercutsCalc(const char *hilname, 
+                                     const char *hilsrcname, 
+                                     const char *name, const char *title)
+  : fHadronnessName("MHadronness"), fHilName(hilname), fHilSrcName(hilsrcname),
+    fHilExtName("MHillasExt"), fNewParName("MNewImagePar"), 
+    fSuperName("MCT1Supercuts") 
+{
+    fName  = name  ? name  : "MCT1SupercutsCalc";
+    fTitle = title ? title : "Class to evaluate the Supercuts";
+
+    fMatrix = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MCT1SupercutsCalc::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    fHadronness = (MHadronness*)pList->FindCreateObj("MHadronness", fHadronnessName);
+    if (!fHadronness)
+    {
+        *fLog << err << fHadronnessName << " [MHadronness] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSuper = (MCT1Supercuts*)pList->FindObject(fSuperName, "MCT1Supercuts");
+    if (!fSuper)
+    {
+        *fLog << err << fSuperName << " [MCT1Supercuts] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fMatrix)
+        return kTRUE;
+
+    //-----------------------------------------------------------
+    fHil = (MHillas*)pList->FindObject(fHilName, "MHillas");
+    if (!fHil)
+    {
+        *fLog << err << fHilName << " [MHillas] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject(fHilExtName, "MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << fHilExtName << " [MHillasExt] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << fHilSrcName << " [MHillasSrc] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject(fNewParName, "MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << fNewParName << " [MNewImagePar] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculation of upper and lower limits
+//
+Double_t MCT1SupercutsCalc::CtsMCut(const Double_t* a,  Double_t ls, Double_t ct,
+                                    Double_t ls2, Double_t dd2) const
+{
+    // define cut-function
+    //
+    //    dNOMLOGSIZE = 4.1 (=log(60.0)
+    //    dNOMCOSZA   = 1.0
+    //
+    //      a: array of cut parameters
+    //     ls: log(SIZE) - dNOMLOGSIZE
+    //    ls2: ls^2
+    //     ct: Cos(ZA.) - dNOMCOSZA
+    //    dd2: DIST^2
+    const Double_t limit =
+        a[0] + a[1] * dd2 + a[2] * ct  +
+        ls  * (a[3] + a[4] * dd2 + a[5] * ct) +
+        ls2 * (a[6] + a[7] * dd2);
+
+    //*fLog << "MCT1SupercutsCalc::CtsMCut; *a = "
+    //      << *a     << ",  " << *(a+1) << ",  " << *(a+2) << ",  "
+    //      << *(a+3) << ",  " << *(a+4) << ",  " << *(a+5) << ",  "
+    //      << *(a+6) << ",  " << *(a+7) << endl;
+
+    //*fLog << "MCT1SupercutsCalc::CtsMCut; ls, ls2, ct, dd2, limit = " << ls
+    //      << ",  " << ls2 << ",  " << ct << ",  " << dd2 << ",  "
+    //      << limit << endl;
+
+    return limit;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MCT1SupercutsCalc::GetVal(Int_t i) const
+{
+
+    Double_t val = (*fMatrix)[fMap[i]];
+
+
+    //*fLog << "MCT1SupercutsCalc::GetVal; i, fMatrix, fMap, val = "
+    //    << i << ",  " << fMatrix << ",  " << fMap[i] << ",  " << val << endl;
+
+
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam::Process
+// will take the values from the matrix instead of the containers.
+//
+void MCT1SupercutsCalc::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MMcEvt.fTelescopeTheta");
+    fMap[1] = fMatrix->AddColumn("MHillas.fWidth");
+    fMap[2] = fMatrix->AddColumn("MHillas.fLength");
+    fMap[3] = fMatrix->AddColumn("MHillas.fSize");
+    fMap[4] = fMatrix->AddColumn("MHillas.fMeanX");
+    fMap[5] = fMatrix->AddColumn("MHillas.fMeanY");
+    fMap[6] = fMatrix->AddColumn("MHillasSrc.fDist");
+    fMap[7] = fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+    fMap[8] = fMatrix->AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    fMap[9] = fMatrix->AddColumn("MNewImagePar.fConc");
+    fMap[10]= fMatrix->AddColumn("MNewImagePar.fLeakage1");
+}
+
+// ---------------------------------------------------------------------------
+//
+// Evaluate dynamical supercuts 
+// 
+//          set hadronness to 0.25 if cuts are fullfilled
+//                            0.75 otherwise
+//
+Int_t MCT1SupercutsCalc::Process()
+{
+    const Double_t kNomLogSize = 4.1;
+    const Double_t kNomCosZA   = 1.0;
+
+    const Double_t theta   = fMatrix ? GetVal(0) : fMcEvt->GetTelescopeTheta();
+    const Double_t width0  = fMatrix ? GetVal(1) : fHil->GetWidth();
+    const Double_t length0 = fMatrix ? GetVal(2) : fHil->GetLength();
+    const Double_t size    = fMatrix ? GetVal(3) : fHil->GetSize();
+    const Double_t meanx   = fMatrix ? GetVal(4) : fHil->GetMeanX();
+    const Double_t meany   = fMatrix ? GetVal(5) : fHil->GetMeanY();
+    const Double_t dist0   = fMatrix ? GetVal(6) : fHilSrc->GetDist();
+
+    Double_t help;
+    if (!fMatrix)
+      help = TMath::Sign(fHilExt->GetM3Long(), 
+	      		 fHilSrc->GetCosDeltaAlpha());
+    const Double_t asym0   = fMatrix ? GetVal(8) : help;
+    const Double_t conc    = fMatrix ? GetVal(9) : fNewPar->GetConc();
+    const Double_t leakage = fMatrix ? GetVal(10): fNewPar->GetLeakage1();
+
+    const Double_t newdist = dist0 * fMm2Deg;
+
+    const Double_t dist2   = meanx*meanx + meany*meany;
+    const Double_t dist    = sqrt(dist2) * fMm2Deg;
+    const Double_t dd2     = dist*dist;
+
+
+    const Double_t dmls    = log(size) - kNomLogSize;
+    const Double_t dmls2   = dmls * dmls;
+
+    const Double_t dmcza   = cos(theta) - kNomCosZA;
+
+    const Double_t length  = length0 * fMm2Deg;
+    const Double_t width   = width0  * fMm2Deg;
+    const Double_t asym    = asym0   * fMm2Deg;
+
+    /*
+    *fLog << "newdist, length, width, asym, dist, conc, leakage = " 
+          << newdist << ",  " << length << ",  " << width << ",  "
+          << asym    << ",  " << dist   << ",  " << conc  << ",  " << leakage
+          << endl;
+  
+    *fLog << "upper cuts in newdist, length, width, asym, dist, conc, leakage = " 
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLengthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLengthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetWidthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetWidthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLeakage1Up(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLeakage1Lo(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << endl;
+    */
+
+
+    if (
+        //dist    < 1.05                                                     &&
+        //newdist < 1.05                                                     &&
+
+        newdist < CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) &&
+        newdist > CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        length  < CtsMCut (fSuper->GetLengthUp(), dmls, dmcza, dmls2, dd2) &&
+        length  > CtsMCut (fSuper->GetLengthLo(), dmls, dmcza, dmls2, dd2) &&
+
+        width   < CtsMCut (fSuper->GetWidthUp(),  dmls, dmcza, dmls2, dd2) &&
+        width   > CtsMCut (fSuper->GetWidthLo(),  dmls, dmcza, dmls2, dd2) &&
+
+        asym    < CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) &&
+        asym    > CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        dist    < CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) &&
+        dist    > CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        conc    < CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) &&
+        conc    > CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        leakage < CtsMCut (fSuper->GetLeakage1Up(),dmls, dmcza, dmls2, dd2) &&
+        leakage > CtsMCut (fSuper->GetLeakage1Lo(),dmls, dmcza, dmls2, dd2)  ) 
+
+      fHadronness->SetHadronness(0.25);
+    else
+      fHadronness->SetHadronness(0.75);
+
+    //*fLog << "SChadroness = " << fHadronness->GetHadronness() << endl;
+
+    fHadronness->SetReadyToSave();
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MCT1SupercutsCalc.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MCT1SupercutsCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MCT1SupercutsCalc.h	(revision 9772)
@@ -0,0 +1,82 @@
+#ifndef MARS_MCT1SupercutsCalc
+#define MARS_MCT1SupercutsCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MParList;
+class MHillas;
+class MHillasSrc;
+class MHillasExt;
+class MNewImagePar;
+class MMcEvt;
+class MCerPhotEvt;
+class MGeomCam;
+class MHadronness;
+class MHMatrix;
+class MCT1Supercuts;
+
+class MCT1SupercutsCalc : public MTask
+{
+private:
+    MHillas       *fHil;
+    MHillasSrc    *fHilSrc;
+    MHillasExt    *fHilExt;
+    MNewImagePar  *fNewPar;
+    MMcEvt        *fMcEvt;
+    MHadronness   *fHadronness; //! output container for hadronness
+    MCT1Supercuts *fSuper;      // container for supercut parameters
+
+    TString  fHadronnessName;   // name of container to store hadronness
+    TString  fHilName;
+    TString  fHilSrcName;
+    TString  fHilExtName;
+    TString  fNewParName;
+    TString  fSuperName;        // name of container for supercut parameters
+
+    Double_t fMm2Deg;           //!
+
+    Int_t     fMap[11];         //!
+    MHMatrix *fMatrix;          //!
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Double_t GetVal(Int_t i) const;
+
+    Double_t CtsMCut(const Double_t* a, Double_t ls, Double_t ct,
+                     Double_t ls2, Double_t dd2) const;
+
+public:
+    MCT1SupercutsCalc(const char *hilname="MHillas",
+                      const char *hilsrcname="MHillasSrc",
+                      const char *name=NULL, const char *title=NULL);
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+    TString GetHadronnessName() const { return fHadronnessName; }
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping() { InitMapping(NULL); }
+
+
+    ClassDef(MCT1SupercutsCalc, 0) // A class to evaluate the Supercuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MFCT1SelBasic.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MFCT1SelBasic.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MFCT1SelBasic.cc	(revision 9772)
@@ -0,0 +1,261 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFCT1SelBasic
+//
+//  This is a class to evaluate basic cuts
+//
+//  to be called after the calibration (when the number of photons is
+//               available for all pixels)
+//
+//  The basic cuts are :
+//
+//      remove bad runs
+//      thetamin < theta < thetamax
+//      software trigger fullfilled (with minimum no.of photons = minphotons)
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MFCT1SelBasic.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+#include "MCerPhotEvt.h"
+#include "MRawRunHeader.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFCT1SelBasic);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFCT1SelBasic::MFCT1SelBasic(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFCT1SelBasic";
+    fTitle = title ? title : "Filter to evaluate basic cuts";
+
+    // default values of cuts
+    SetCuts(13.0, 0.0, 60.0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the cut values
+// 
+//
+void MFCT1SelBasic::SetCuts(Float_t minphotons, 
+                            Float_t thetamin, Float_t thetamax)
+{
+    fMinPhotons = minphotons;
+    fThetaMin   = thetamin;
+    fThetaMax   = thetamax;
+
+    *fLog << inf << "MFCT1SelBasic cut values : fMinPhotons, fThetaMin, fThetaMax = ";
+    *fLog << fMinPhotons <<",  " << fThetaMin << ",  " << fThetaMax << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the pointers
+// 
+//
+Int_t MFCT1SelBasic::PreProcess(MParList *pList)
+{
+    fRawRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRawRun)
+    {
+        *fLog << dbginf << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << dbginf << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+    if (!fEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << dbginf << "MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    memset(fCut, 0, sizeof(fCut));
+
+    return kTRUE;
+}
+
+Int_t MFCT1SelBasic::Set(Int_t rc)
+{
+    fCut[rc]++;
+    fResult=kTRUE;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluate basic cuts
+// 
+//     bad events    : fResult = kTRUE;
+//     good events   : fResult = kFALSE;
+//
+Int_t MFCT1SelBasic::Process()
+{
+    const Double_t theta = kRad2Deg*fMcEvt->GetTelescopeTheta();
+
+    fResult  = kFALSE;
+
+    // remove bad runs for MC gammas
+    if (fMcEvt->GetEnergy() == 0.0  &&  fMcEvt->GetImpact() == 0.0)
+    {
+      if (fRawRun->GetRunNumber() == 601  ||
+          fRawRun->GetRunNumber() == 613  ||
+          fRawRun->GetRunNumber() == 614    )
+	return Set(1);
+    }
+
+    if (theta<fThetaMin)
+        return Set(2);
+
+    if (theta>fThetaMax)
+        return Set(3);
+
+    if (!SwTrigger())
+        return Set(4);
+
+    fCut[0]++;
+
+    return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+// Software trigger
+// 
+// require 2 neighboring pixels (which are not in the outermost ring), 
+//                       each having at least 'fMinPhotons' photons
+// 
+// 
+Bool_t MFCT1SelBasic::SwTrigger()
+{
+    const Int_t entries = fEvt->GetNumPixels();
+ 
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MCerPhotPix &pix = (*fEvt)[i];
+
+        const Int_t id = pix.GetPixId();
+        if (!pix.IsPixelUsed())
+            continue;
+
+        const Double_t photons = pix.GetNumPhotons();
+        if (photons < fMinPhotons)
+            continue;
+
+        // this pixel is used and has the required no.of photons
+        // check whether this is also true for a neigboring pixel
+
+        const MGeomPix &gpix = (*fCam)[id];
+        if ( gpix.IsInOutermostRing() )
+            continue;
+
+        const Int_t nneighbors = gpix.GetNumNeighbors();
+        for (Int_t n=0; n<nneighbors; n++)
+        {
+            const Int_t id1 =  gpix.GetNeighbor(n);
+            if ( !fEvt->IsPixelUsed(id1) )
+                continue;
+
+            const MGeomPix &gpix1 = (*fCam)[id1];
+            if ( gpix1.IsInOutermostRing() )
+                continue;
+
+            const MCerPhotPix &pix1 = *fEvt->GetPixById(id1);
+
+            const Double_t photons1 = pix1.GetNumPhotons();
+            if (photons1 >= fMinPhotons)
+                return kTRUE;
+        }
+    }
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Basic selections.
+//
+Int_t MFCT1SelBasic::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: bad run " << endl;
+
+    *fLog << " " << setw(7) << fCut[2] << " (" << setw(3) ;
+    *fLog << (int)(fCut[2]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Zenith angle < " << fThetaMin << endl;
+
+    *fLog << " " << setw(7) << fCut[3] << " (" << setw(3) ;
+    *fLog << (int)(fCut[3]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Zenith angle > " << fThetaMax << endl;
+
+    *fLog << " " << setw(7) << fCut[4] << " (" << setw(3) ;
+    *fLog << (int)(fCut[4]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Software trigger not fullfilled" ;
+    *fLog << " (with fMinPhotons = " << fMinPhotons << ")" << endl;
+
+    *fLog << " " << fCut[0] << " (" << (int)(fCut[0]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts survived Basic selections!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysisct1/MFCT1SelFinal.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MFCT1SelFinal.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MFCT1SelFinal.cc	(revision 9772)
@@ -0,0 +1,193 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  04/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFCT1SelFinal
+//
+//  WHAT ARE THE FINAL CUTS?
+//
+//  This is a class to evaluate the Final Cuts
+//  (these cuts define the final sample of gammas;
+//   relevant for the calculation of the effective collection areas)
+//
+//  to be called after the calculation of the hadroness
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFCT1SelFinal.h"
+
+#include <math.h>
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+#include "MCerPhotEvt.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MHadronness.h"
+
+ClassImp(MFCT1SelFinal);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFCT1SelFinal::MFCT1SelFinal(const char *hilsrcname,
+                             const char *name, const char *title)
+    : fHilSrcName(hilsrcname), fHadronnessName("MHadronness")
+{
+    fName  = name  ? name  : "MFCT1SelFinal";
+    fTitle = title ? title : "Class to evaluate the Final Cuts";
+
+    // default values of cuts
+    SetCuts(1.0, 100.0, 10.);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set cut values
+// 
+//
+void MFCT1SelFinal::SetCuts(Float_t hadmax, Float_t alphamax, Float_t distmax) 
+{ 
+    fHadronnessMax =   hadmax;
+    fAlphaMax      = alphamax;
+    fDistMax       =  distmax;
+
+    *fLog << inf << "MFCT1SelFinal cut values : fHadronnessMax, fAlphaMax, fDistMax = ";
+    *fLog << fHadronnessMax << ",  " << fAlphaMax << ",  " << fDistMax <<  endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the pointers
+//
+Int_t MFCT1SelFinal::PreProcess(MParList *pList)
+{
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+      *fLog << dbginf << "MHillasSrc object " << fHilSrcName << " not found... aborting." << endl;
+      return kFALSE;
+    }
+
+    fHadronness = (MHadronness*)pList->FindObject(fHadronnessName, "MHadronness");
+    if (!fHadronness)
+    {
+      *fLog << dbginf << "MHadronness not found... aborting." << endl;
+      return kFALSE;
+    }
+
+    MGeomCam *cam = (MGeomCam*)pList->FindCreateObj("MGeomCamCT1","MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    memset(fCut, 0, sizeof(fCut));
+
+    return kTRUE;
+}
+
+Int_t MFCT1SelFinal::Set(Int_t rc)
+{
+    fCut[rc]++;
+    fResult=kTRUE;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluate final cuts
+// 
+// if cuts are fulfilled set fResult = kTRUE
+//
+Int_t MFCT1SelFinal::Process()
+{
+    const Double_t modalpha = fabs( fHilSrc->GetAlpha() );
+    const Double_t h = fHadronness->GetHadronness();
+
+    fResult = kFALSE;
+
+    if (h>fHadronnessMax)
+        return Set(1);
+
+    if (modalpha>fAlphaMax)
+        return Set(2);
+
+    if (fMm2Deg*fHilSrc->GetDist()>fDistMax)
+        return Set(3);
+
+    fCut[0]++;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Final selections.
+//
+Int_t MFCT1SelFinal::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/GetNumExecutions());
+    *fLog << "%) Evts skipped due to: hadronness > "<< fHadronnessMax;
+    *fLog << " (hadronness from '" << fHadronnessName << "')" << endl;
+
+    *fLog << " " << setw(7) << fCut[2] << " (" << setw(3) ;
+    *fLog << (int)(fCut[2]*100/GetNumExecutions());
+    *fLog << "%) Evts skipped due to: |ALPHA| > " << fAlphaMax;
+    *fLog << " [degrees]" << endl;
+
+    *fLog << " " << setw(7) << fCut[3] << " (" << setw(3) ;
+    *fLog << (int)(fCut[3]*100/GetNumExecutions());
+    *fLog << "%) Evts skipped due to: DIST > " << fDistMax;
+    *fLog << " [degrees]" << endl;
+
+    *fLog << " " << fCut[0] << " (" ;
+    *fLog << (int)(fCut[0]*100/GetNumExecutions());
+    *fLog << "%) Evts survived Final selections!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysisct1/MFCT1SelFinal.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MFCT1SelFinal.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MFCT1SelFinal.h	(revision 9772)
@@ -0,0 +1,70 @@
+#ifndef MARS_MFCT1SelFinal
+#define MARS_MFCT1SelFinal
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MSelFinal                                                               //
+//                                                                         //
+// Class to evaluate final cuts                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MHillas;
+class MHillasSrc;
+class MHadronness;
+
+class MFCT1SelFinal : public MFilter
+{
+private:
+    MHillasSrc  *fHilSrc;       
+    MHadronness *fHadronness;       
+
+    TString      fHilName;
+    TString      fHilSrcName;
+    TString      fHadronnessName;
+ 
+    Float_t      fHadronnessMax;
+    Float_t      fAlphaMax;
+    Float_t      fDistMax;
+
+    Double_t     fMm2Deg;   // conversion mm to degrees in camera
+
+    Int_t        fCut[4];
+
+    Bool_t       fResult;
+
+    Int_t Set(Int_t rc);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t IsExpressionTrue() const  { return fResult; }
+
+public:
+    MFCT1SelFinal(const char *HilSrcName="MHillasSrc",
+                  const char *name=NULL, const char *title=NULL);
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+
+    void SetCuts(Float_t hadmax, Float_t alphamax, Float_t distmax); 
+
+    ClassDef(MFCT1SelFinal, 0)   // Class to evaluate final cuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/MFCT1SelStandard.cc
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MFCT1SelStandard.cc	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MFCT1SelStandard.cc	(revision 9772)
@@ -0,0 +1,221 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFCT1SelStandard
+//
+//  This is a class to evaluate the Standard Cuts
+//
+//  WHAT ARE THE STANDARD CUTS?                                                                       //
+//
+//  to be called after the calculation of the image parameters
+//               before the g/h separation
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MFCT1SelStandard.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotEvt.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+
+ClassImp(MFCT1SelStandard);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFCT1SelStandard::MFCT1SelStandard(const char *hilsrcname,
+                                   const char *name, const char *title)
+    : fHilName("MHillas"), fHilSrcName(hilsrcname), fImgParName("MNewImagePar")
+{
+    fName  = name  ? name  : "MFCT1SelStandard";
+    fTitle = title ? title : "Class to evaluate the Standard Cuts";
+
+    // default values of cuts
+    SetCuts(92, 4, 60, 0.4, 1.05, 0.0, 0.0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the values for the cuts 
+// 
+//
+void MFCT1SelStandard::SetCuts(Float_t usedpixelsmax, Float_t corepixelsmin,
+                               Float_t sizemin, Float_t distmin, Float_t distmax,
+                               Float_t lengthmin, Float_t widthmin)
+{ 
+    fUsedPixelsMax = usedpixelsmax;
+    fCorePixelsMin = corepixelsmin;
+    fSizeMin       = sizemin;
+    fDistMin       = distmin;
+    fDistMax       = distmax;
+    fLengthMin     = lengthmin;
+    fWidthMin      = widthmin;
+
+    *fLog << inf << "MFCT1SelStandard cut values : fUsedPixelsMax, fCorePixelsMin = ";
+    *fLog << fUsedPixelsMax << ",  " << fCorePixelsMin << endl;
+    *fLog << inf << "     fSizeMin, fDistMin, fDistMax = " << fSizeMin ;
+    *fLog << ",  " << fDistMin << ",  " << fDistMax << endl;
+    *fLog << inf << "     fLengthMin, fWidthMin = " << fLengthMin ;
+    *fLog << ",  " << fWidthMin << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// MISSING
+//
+Int_t MFCT1SelStandard::PreProcess(MParList *pList)
+{
+    fHil = (MHillas*)pList->FindObject(fHilName, "MHillas");
+    if (!fHil)
+    {
+        *fLog << err << fHilName << " [MHillas] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << fHilSrcName << " [MHillasSrc] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewImgPar = (MNewImagePar*)pList->FindObject(fImgParName, "MNewImagePar");
+    if (!fNewImgPar)
+    {
+        *fLog << err << fImgParName << " [MNewImagePar] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    memset(fCut, 0, sizeof(fCut));
+
+    return kTRUE;
+}
+
+Bool_t MFCT1SelStandard::Set(Int_t rc)
+{
+    fResult = kTRUE;
+    fCut[rc]++;
+    return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+// Evaluate standard cuts
+// 
+// if selections are fulfilled set fResult = kTRUE;
+// 
+//
+Int_t MFCT1SelStandard::Process()
+{
+    const Double_t length     = fHil->GetLength() * fMm2Deg;
+    const Double_t width      = fHil->GetWidth()  * fMm2Deg;
+    const Double_t dist       = fHilSrc->GetDist()* fMm2Deg;
+    //const Double_t delta      = fHil->GetDelta()  * kRad2Deg;
+    const Double_t size       = fHil->GetSize();
+    const Int_t numusedpixels = fNewImgPar->GetNumUsedPixels();
+    const Int_t numcorepixels = fNewImgPar->GetNumCorePixels();
+
+    fResult  = kFALSE;
+
+    if (numusedpixels>=fUsedPixelsMax || numcorepixels<=fCorePixelsMin)
+        return Set(1);
+
+    if (size<=fSizeMin )
+        return Set(2);
+
+    if (dist<fDistMin || dist>fDistMax)
+        return Set(3);
+
+    if (length<=fLengthMin || width<=fWidthMin)
+        return Set(4);
+
+    fCut[0]++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Standard selections.
+//
+Int_t MFCT1SelStandard::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3);
+    *fLog << (int)(fCut[1]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Used pixels >= " << fUsedPixelsMax ;
+    *fLog << " or Core pixels <= " << fCorePixelsMin << endl;
+
+    *fLog << " " << setw(7) << fCut[2] << " (" << setw(3) ;
+    *fLog << (int)(fCut[2]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: SIZE <= " << fSizeMin << endl;
+
+    *fLog << " " << setw(7) << fCut[3] << " (" << setw(3) ;
+    *fLog << (int)(fCut[3]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: DIST < " << fDistMin;
+    *fLog << " or DIST > " << fDistMax << endl;
+
+    *fLog << " " << setw(7) << fCut[4] << " (" << setw(3) ;
+    *fLog << (int)(fCut[4]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: LENGTH <= " << fLengthMin;
+    *fLog << " or WIDTH <= " << fWidthMin << endl;
+
+    *fLog << " " << fCut[0] << " (" ;
+    *fLog << (int)(fCut[0]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts survived Standard selections!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/manalysisct1/MFCT1SelStandard.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/MFCT1SelStandard.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/MFCT1SelStandard.h	(revision 9772)
@@ -0,0 +1,78 @@
+#ifndef MARS_MFCT1SelStandard
+#define MARS_MFCT1SelStandard
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFCT1SelStandard                                                        //
+//                                                                         //
+// Class to evaluate standard cuts                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MHillas;
+class MHillasSrc;
+class MNewImagePar;
+
+class MFCT1SelStandard : public MFilter
+{
+private:
+    MHillas      *fHil;
+    MHillasSrc   *fHilSrc;
+    MNewImagePar *fNewImgPar;
+
+    TString      fHilName;
+    TString      fHilSrcName;
+    TString      fImgParName;
+
+    Float_t      fUsedPixelsMax;
+    Float_t      fCorePixelsMin;
+    Float_t      fSizeMin;
+    Float_t      fDistMin;
+    Float_t      fDistMax;
+    Float_t      fLengthMin;
+    Float_t      fWidthMin;
+
+    Double_t     fMm2Deg;    // conversion mm to degrees in camera
+
+    Int_t        fCut[5];
+
+    Bool_t       fResult;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t IsExpressionTrue() const  { return fResult; }
+
+    Bool_t Set(Int_t rc);
+
+public:
+    MFCT1SelStandard(const char *HilSrcName="MHillasSrc",
+                     const char *name=NULL, const char *title=NULL);
+
+    void SetHillasName(const char *name) { fHilName = name; }
+    void SetImgParName(const char *name) { fImgParName = name; }
+
+    void SetCuts(Float_t usedpixelsmax, Float_t corepixelsmin,
+                 Float_t sizemin, Float_t distmin, Float_t distmax,
+                 Float_t lengthmin, Float_t widthmin);
+
+    ClassDef(MFCT1SelStandard, 0)   // Class to evaluate standard cuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/manalysisct1/Makefile
===================================================================
--- /tags/Mars-V0.9/manalysisct1/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/Makefile	(revision 9772)
@@ -0,0 +1,45 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = AnalysisCT1
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mdata -I../mfbase -I../mgeom     \
+           -I../mfileio -I../mfilter -I../manalysis -I../mpedestal -I../mmc \
+           -I../mhist -I../mpointing -I../mimage -I../mgui -I../mbadpixels  \
+           -I../mraw
+
+SRCFILES = MCT1FindSupercuts.cc \
+           MCT1PointingCorrCalc.cc \
+           MCT1Supercuts.cc \
+           MCT1SupercutsCalc.cc \
+           MCT1ReadPreProc.cc \
+           MCT1ReadAscii.cc
+
+# Doesn't compile: Please replace MBlindPixels by MBadPixel*
+#           MCT1PadONOFF.cc \
+#           MCT1PadSchweizer.cc \
+
+############################################################
+
+all:  $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/manalysisct1/structures.h
===================================================================
--- /tags/Mars-V0.9/manalysisct1/structures.h	(revision 9772)
+++ /tags/Mars-V0.9/manalysisct1/structures.h	(revision 9772)
@@ -0,0 +1,882 @@
+/******************************************************************/
+/*              GGG   AAA   M   M M   M  AAA   SSS                */
+/*             G   G A   A  MM MM MM MM A   A S   S               */
+/*             G     A   A  M M M M M M A   A  SS                 */
+/*             G  GG AAAAA  M   M M   M AAAAA   SS                */
+/*             G   G A   A  M   M M   M A   A S   S               */
+/*              GGG  A   A  M   M M   M A   A  SSS                */
+/*       Gamma Astronomer's Munich Madrid Analysis Suite          */
+/*   An Atmospheric Cherenkov Telescope Data Analysis Software    */
+/*  MPI f"ur Physik, M"unchen & Universidad Complutense, Madrid   */
+/******************************************************************/
+
+/******************************************************************/
+/* This File belongs to the programs                              */
+/*                                                                */
+/*  P R E P R O C E S S O R   and   I M A G E R                   */
+/*                                                                */
+/* Purpose: provide the structure definitions common to both      */
+/*          programs, especially the output structures of the     */
+/*          preprocessor                                          */ 
+/*                                                                */
+/******************************************************************/
+
+/******************************************************************/
+/* @(#) File name structures.h
+   @(#) latest SID 0.5  
+   @(#) Date of latest delta 26/6/00  
+   Author: D. Petry 
+   changed by M. Kestel */
+/******************************************************************/
+
+#ifndef _structures_h_
+#define _structures_h_ "__structures_h__"
+
+#define STRUCT_VERSION 0.6
+
+#define iHEADERTITLELENGTH 60
+/* length of the string written at the beginning of the */
+/* output for each runfile */
+#define cTITLE_TEMPLATE "PREPROC V%f/S%f CT %d RUN %d %d PROCMJD %d\n"
+
+#define cEND_EVENTS_TEMPLATE "EVENTS AFTER FILTER = %d\n"
+
+#define iMAXNUMPIX 127
+/* maximum value for the number of camera pixels (excl. muon shield) */
+#define iMAXNUMMUONPIX 5 
+/* maximum value for the number of pixels in the muon shield */
+#define iMAXNUMCOINTDCS 5
+/* maximum value for the number of coincidence tdcs */
+
+
+#define iBADMACTIME_BIT 1
+/* snot_ok_flags is ORed with this number to set the bit which 
+ * indicates that the mactime measurement didn't work */
+#define iBADRUBTIME_BIT 2 
+/* snot_ok_flags is ORed with this number to set the bit which 
+ * indicates that the Rubidium time measurement didn't work */
+#define iBADPOINTING_BIT 4 
+/* snot_ok_flags is ORed with this number to set the bit which 
+ * indicates that the shaft encoder values were inconsistent with 
+ * time OR source coordinates */
+#define iMUON_BIT 8
+ /* snot_ok_flags is ORed with this number to set the bit which 
+  * indicates that the event didn't pass the muon filter 
+  * (for test puposes) */
+
+#define i2OUTFAIL_BIT 16 
+/* snot_ok_flags is ORed with this number to set the bit which 
+ * indicates that the event didn't pass the "two out of all" 
+ * software trigger */
+#define iSUMFAIL_BIT 32 
+/* snot_ok_flags is ORed with this number to set the bit which
+ * indicates that the event didn't pass the "sum of all
+ * photoelectrons" filter */
+
+#define iPARTICLETYPE_FACTOR 1024 
+/* for MC data: the particle type multiplied with this number 
+ * is ORed with snot_ok_flags */
+
+enum onoroff {NEITHER_ON_NOR_OFF, OFF_SOURCE, ON_SOURCE};
+enum trackmodes {NORMAL, REVERSE, DUNNO};
+enum axes {RA, DEC, ALT, AZ};
+enum eERRORTOLERANCE {CAUTIOUS=0, GOODPHYSICS, TANK};
+enum eMCTRIGGERFLAG {ALL=0, FLAG, NOFLAG};
+ 
+struct outputpars {
+  /* preprocessing parameters that are passed to imager.
+   * Note: Not all parameters from the parameter file are passed to
+   * imager, only those that are repeated in this struct outputpars 
+   * here !! That's why these two structs must be the same for both
+   * preproc and imager. */
+
+  int     itelescope;
+  /* number of the CT which took the data (from parameters file */
+  /* crosschecked with run file name) */
+  float   flongitude_deg;
+  /* longitude (counted positive towards West) of CT position */
+  float   flatitude_deg;
+  /* latitude (counted positive towards North) of CT position */
+  int     irunnum;
+  /* run number (from parameters file cross checked with run */
+  /* file name) */
+  enum onoroff eruntype;
+#ifdef LINUX
+  int dummy;
+#endif
+  /* indicates if the */
+  /* run is on- or off source (from runfile cross checked with */
+  /* file name) */
+  double  dsourcera_hours;
+  /* right ascension of observed source in hours */
+  double  dsourcedec_deg; 
+  /* declination of observed source in degrees */
+  int     inumpixels; 
+  /* number of pixels in the camera (from parameters file cross */
+  /* checked with run file, calibration file and pedestal file) */
+  int     inummuonpixels;
+  /* number of pixels in the muon shield (from parameters file */
+  /* cross checked with run file, calibration file and pedestal */
+  /* file) */
+  int     inumcointdcs;
+  /* number of coincidence tdcs recorded in the runfile (from */
+  /* parameters file cross checked */
+  /* with run file) */
+  float   fpixdiameter_deg;
+  /* smallest pixel diameter (degrees) (from parameters file) */ 
+  enum axes ese1_is;
+  /* name of the axis to which shaft encoder 1 is attached */
+  /* (implies the type of mount) */
+  int     isezeropos[2];
+  /* zero position of shaftencoders 1 and 2 (from parameters file) */
+  int     iaz_rev_track_corr;
+  /* correction for the azimuth shaft encoder (ALT/AZ mount */
+  /* only) in reverse tracking mode */
+  int     ialt_rev_track_corr;
+  /* correction for the altitude shaft encoder (ALT/AZ mount */
+  /* only) in reverse tracking mode */
+  float   fbendingcorr;
+  /* bending correction factor (ALT/AZ mount only) */
+  float   fextinction;
+  /* atmospheric extinction (typically taken from the Carlsberg */
+  /* Meridian Circle data) */
+  Boolean bdontusepix[iMAXNUMPIX];
+  /* bdontusepix is set true if the pixel should due to whatever
+   * reason not be used in image analysis, otherwise it is true; 
+   * 
+   * bdontusepix is set by the user inside preproc.par and is 
+   * untouched by preproc (version >= 0.4). */
+  Boolean bexcludepix[iMAXNUMPIX];
+  /* bexcludepix[] is set TRUE (== exclude from pedestal, Laser 
+   * calibration and the further analysis) when the Mean value
+   * of a pixel inside a pedestal Run is larger than 50 or ( || )
+   * if the pedestal RMS value of this pixel is larger than 5.0
+   * This is reflected in the (new for versions >= 0.4) 
+   * variable "pixonoff" in the ntuple written by preproc:
+   * preproc.nt.hbook
+   *
+   * When the pixel is excluded by the user it will get a -2 otherwise 
+   * pixonoff = 0.
+   * Additive to this a -1 is added when preproc excludes the pixel
+   * for a given Run. So the actual value tells you whether you caught 
+   * it already by hand or not.
+   *
+   * A plot of pixonoff may also be handy to tell you the status of your
+   * ADC equipment. */
+  float   fphotoel_per_adccnt[iMAXNUMPIX];
+  /* conversion factors for the pixel signals */
+  int     irubminusutc_usecs;
+  /* difference between rubidium clock and UTC in microseconds */
+  int     isum_thresh_phot;
+  /* threshold for the total sum of photoelectrons filter */
+  /* from the parameters file */
+  int     i2out_thresh_phot;
+  /* threshold for the two-pixels-out-of-all software */
+  /* trigger from parameters file */
+  int     imuoncut_thresh_adccnt[iMAXNUMMUONPIX]; 
+  /* thresholds for the muon cut */
+  Boolean bmuon_suppression;
+  /* "Dolby" noise reduction flag */
+  float   ftolerated_pointerror_deg;
+  /* maximum tolerated pointing error in the position 
+   * check in iprocessdata */
+  float   fxpointcorr_deg;
+  /* pointing correction (to be added along the camera
+   * x axis) e.g. from point run */ 
+  float   fypointcorr_deg;  
+  /* pointing correction (to be added along the camera 
+   * y axis) e.g. from point run */ 
+  float   fcamera_align_angle_deg;
+  /* the angle between the camera y-axis and the meridian 
+   * when a culminating object is observed (defined 
+   * counter-clockwise looking at the sky) */ 
+  int     iratecalc_numevents_odd;
+  /* number of events used in the rate calculation (must be odd) */
+  int     inumpedfile;
+  /* number of the pedestal file used */
+  int     inumpedrun;
+  /* number of the pedestal run used in the file (starting at 0) */
+  int     inumcalfile;
+  /* number of the calibration file used */
+  int     inumlaserrun;
+  /* number of the laserrun used in the file (starting at 0) */ 
+  int     inumtellogfile;
+  /* number of the TelLog file to be used */
+  int     inumtellogrun;
+  /* number of the tellog entry (Runnumber) used from the log file */
+  int imcparticle; /* CORSIKA-coded Monte Carlo particle type.
+		    * This is given once per run. */
+
+  /* preprocessing results: */
+
+  int     istart_mjdate_day;
+  /* MJD of run start (first event) */
+  int     iend_mjdate_day;
+  /* MJD of run end (last event) */
+  int     irunduration_secs;
+  /* difference between start and end time (secs) */
+  int     iproc_mjdate; 
+  /* MJD of data processing (i.e. creation of this file) */ 
+  enum trackmodes etrackmode;
+  /* tracking mode (for ALT/AZ CTs) */
+  int     iproc_evts;
+#ifdef LINUX
+  int dummy2;
+#endif
+  /* number of events processed */
+  double  dactual_sourcera_hours;
+  /* for off runs: the false source (that should have been) observed */
+  float   frms_pedsig_phot[iMAXNUMPIX];
+  /* standard deviation of the calibrated signals from the pedestal run */ 
+  float   fpedrms_mean; /* Used to communicate the mean over all pixels 
+			 * pedestal RMS into the Runs NTuple, as it might 
+			 * be used for e.g. quality cuts. */
+  float   fcurrent_mean; /* The average current over the active pixels
+			  * for this run. This is done separately for
+			  * ON and OF runs. */
+
+  enum eERRORTOLERANCE eerrortolerance;
+  /* 0 == "cautious", exits on any reason (but tells in 
+   * the .err file,
+   * 1 == "goodphysics", exits when physics could be affected
+   * by the error,
+   * 2 == "tank", never exits except on coredumps and when
+   * all files have been processed. Do not use such files for
+   * physics analysis! 
+   *
+   * NOTE: the capital letter words are the enums, the small letter
+   * words must be used inside the parameter file. */
+  enum eMCTRIGGERFLAG emctriggerflag;
+  /* all: all events which survive the filter are written to the 
+   *      events NTuple. 
+   * flag: When Dorota's triggerflag is set to 1 for a particular
+   *       event, it shall be written to the output. All others shall
+   *       just be disregarded. (Default)
+   * noflag: Opposite of 'flag': only events with triggerflag = 0 shall
+   *         be treated further. */
+  Boolean bmontecarlo;
+  /* if TRUE we have a monte carlo dataset before us, if FALSE 
+   * (default value) it is just normal data. */
+};
+
+struct filterresults {
+  int     imax_alt_arcs;
+  /* maximum altitude reached during the run */
+  int     iaz_at_max_alt_arcs;
+  /* azimuth at the time the max. alt. was reached */
+  int     itimeaverage_alt_arcs;
+  /* altitude averaged over the runtime */
+  int     icoord_inconsist_evts;
+  /* number of events with time-coordinate */
+  /* inconsistency in this run */
+  int     ifilter_passed_evts;
+  /* number of events which passed the filter */
+  int     imuon_fail_evts;
+  /* number of events rejected as muons (other filters passed) */
+  int     i2out_fail_evts;
+  /* number of events which failed in the two out of all */
+  /* pixels software trigger */
+  int     imuon_and_2out_fail_evts;
+  /* number of events failing in both muon and */
+  /* 2out filter */  
+  int     isum_fail_evts;
+  /* number of events which failed the sum-of-all-calibrated */
+  /* ADC counts filter */
+  int     isum_and_muon_fail_evts;
+  /* number of events which failed in both the sum and */
+  /* the muon filter */
+  int     isum_and_2out_fail_evts;
+  /* number of events which failed in both the sum and */
+  /* the 2out filter */
+  int     iall_filters_fail_evts;
+  /* number of events which failed in all filters */ 
+  float   favg_event_rate_hz;
+  /* average rate before filtering */
+  float   fstddev_event_rate_hz;
+  /* standard deviation of the rate before filtering */
+
+};
+
+struct eventrecord {
+  int   isecs_since_midday;
+  /* seconds passed since midday before sunset (JD of run start) */
+  int   isecfrac_200ns;
+  /* fractional part of isecs_since_midday */
+  short snot_ok_flags;
+  /* the bits in these two bytes are flags for additional */
+  /* information on the event: Everything OK =: all Bits = 0 */
+  int   ialt_arcs;
+  /* altitude (arcseconds) */
+  int   iaz_arcs;
+  /* azimuth (arcseconds) */
+  int   ipreproc_alt_arcs;
+  /* "should be" alt according to preproc (arcseconds) */
+  int   ipreproc_az_arcs;
+  /* "should be" az according to preproc (arcseconds) */
+  int   ifieldrot_arcs;
+  /* for ALT-AZ mount telescopes: rotation angle of the field of 
+   * view; this angle is defined mathematically positive looking 
+   * towards the sky as the angle between the hour circle through 
+   * the object being tracked and the line through pixel 1 and 2 */
+  unsigned short srate_millihz;
+  /* event rate in milli Hertz before filtering calculated by 
+   * iratecalc_numevents_odd/(time[i+iratecalc_numevents_odd/2] - 
+   * time[i-iratecalc_numevents_odd/2]) 
+   * For the first and the last iratecalc_numevents_odd/2 
+   * events the rate is assumed to be constant */
+  float fhourangle; /* This is the angle between the observation of this
+		     * event and the culmination point. It is going to 
+		     * be written into the events NTuple. */
+  float fmcenergy_tev; /* Simulated Energy.... dropping through to
+			* the Events NTuple. */
+  float fmcsize_phel; /* Simulated SIZE.... dropping through to
+			* the Events NTuple. */
+  int imcimpact_m;
+  /* MC data contain the impact parameter, which is given here in 
+   * meters. */
+  int imcparticle;
+  /* MC data know which particle they are.... all in CORSIKA standard. */
+  int imctriggerflag;
+  /* MC data from Dorota get a triggerflag: 1 means triggered, 0 not. */
+  short spixsig_10thphot[iMAXNUMPIX];
+  /* number of photoelectrons measured in each pixel only the 
+   * actual number of pixels (outputpars.inumpixels) is written out */
+};
+
+struct camera { /* camera parameters for imaging */
+  int inumpixels;
+  int inumrings;
+  double dpixdiameter_deg;
+  double dxc[iMAXNUMPIX]; 
+/* Pixel coordinates in camera coordinate system (x points from
+ * pixel 1 to 2). */
+  double dyc[iMAXNUMPIX];
+  /* The numbering of the pixels in these arrays starts at 0! */
+  double dxpointcorr_deg; 
+  /* correction of the pixel coordinates; to be added to dxc[] 
+   * to get correct value */
+  double dypointcorr_deg; 
+  /* correction of the pixel coordinates; to be added to dxc[] 
+   * to get correct value */
+};
+
+
+/* two structures for better file handling */
+struct inputfile {
+  char cname[iMAXFILENAMELENGTH];
+  /* filename (including path) */
+  FILE *pointer;
+  /* filepointer */
+  char ccannotopentext[161];
+  /* Error text printed when file cannot be opened */
+  int  icannotopencode; 
+  /* Error code for the exit statement when file could not be opened */
+  int  iearlyeofcode;
+  /* Error code for the exit statement for unexpected EOF */
+  int  ierroratclosecode;
+  /* Error code for the exit statement for error while trying to close */
+};
+
+struct outputfile {
+  char cname[iMAXFILENAMELENGTH]; /* filename (including path) */
+  FILE *pointer;  /* filepointer */
+  char ccannotopentext[161]; 
+  /* Error text printed when file cannot be opened */
+  int  icannotopencode; 
+  /* Error code for the exit statement when file could not be opened */
+  int  icannotwritecode; 
+  /* Error code for the exit statement for failed fprintf */
+  int  ierroratclosecode; 
+  /* Error code for the exit statement for error while trying to close */
+};
+
+struct P2ALLHISTOS {
+
+  HISTO *p2adchist;
+  HISTO *p2pedonhist;
+  HISTO *p2pedofhist;
+  HISTO *p2pedonmeanhist;
+  HISTO *p2pedofmeanhist;
+  HISTO *p2pedonjitthist;
+  HISTO *p2pedofjitthist;
+  HISTO *p2calonhist;
+  HISTO *p2calofhist;
+  HISTO *p2calonmeanhist;
+  HISTO *p2calofmeanhist;
+  HISTO *p2calonjitthist;
+  HISTO *p2calofjitthist;
+  HISTO *p2phehist;
+  HISTO *p2zenonhist;
+  HISTO *p2zenofhist;
+  HISTO *p2corrpedhist;
+  HISTO *p2pedfwhmhist;
+};
+
+struct CALNT_DAT { 
+  /* the structure for an entry in the calibration ntuple */
+  float CTrunnum;
+  float runtype;
+  float ALT_deg; /* the ALT taken from the first event of the run */
+  float extinct; /* extinction */
+  float RtiSecBF; /* runtime in seconds before filter */
+  float pixnum;  /* number of the pixel for which the following 
+		  * data is given */
+  float pixonoff; /* Quantity telling whether this pixel was switched
+		   * off by the user (-= 2.) or by preproc (-= 1.).
+		   * If ON, its value = 0. */
+  float ped_adcc; /* the standard deviation of the pedestal as 
+		   * calculated by TIJARAFE */
+  float pedrmsac; /* the standard deviation of the pedestal in
+		   * ADC counts as calculated by TIJARAFE */
+  float pedrmsPE; /* the calibrated ped RMS in photoelectrons 
+		   * which is also given to the imager */
+  float las_adcc; /* the mean signal for this pixel from the 
+		   * laser run */
+  float lasrmsac; /* RMS of the laser events after cleaning from cosmics */
+  float conv_fac; /* conversion factor = <Q>/Var(Q) * F^2 */
+  float F;        /* The F from the line before */
+  float rel_gain; /* the relative gain of the pixel */
+  float numtrig;  /* number of events in which the pixel was 
+		   * above trigger threshold */
+  float num3sig;  /* number of events in which the pixel was 
+		   * 3 sigma above its pedestal */ 
+  float HV1;      /* Adjustment of HV1 for this run, if available. */
+  float HV2;      /* Adjustment of HV2 for this run, if available. */
+  float ThrCurr;
+  float AvgCurr;  /* the sum of all currents during this run (with the
+		   * particular runtype in question) from the TelLog 
+		   * file. The currents are averaged over the 2-minute
+		   * intervals but summed over all pixels with currents
+		   * higher than the threshold current value. This sum
+		   * is then stored in the runs ntuple. 
+		   * Same for the scaler values --> */
+  float AvgScal;
+};
+
+struct inputpars {
+  Boolean bkeywordgiven[iNUMKEYWORDS+1]; /* if a valid keyword 
+					  * is given in the 
+					  * parameters file 
+					  * the corresponding
+					  * element in this 
+					  * array is set to true */ 
+  int     itelescope;       /* number of the CT which took the data */
+  float   flongitude_deg;   /* longitude (counted positive 
+			     * towards West) of CT position */
+  float   flatitude_deg;    /* latitude (counted positive 
+			     * towards North) of CT position */
+  int     ifirstrunnum;     /* first run number to which these 
+			     * parameters apply*/
+  int     ilastrunnum;      /* last run number to which these 
+			     * parameters apply, */
+                            /* i.e. this run will be processed 
+			     * with these parameters */
+  int     inumpixels;       /* number of pixels in the camera */
+  int     inummuonpixels;   /* number of pixels in the muon shield */
+  int     inumcointdcs;     /* number of coincidence tdcs recorded 
+			     * in the runfile */
+  float   fpixdiameter_deg; /* smallest pixel diameter (degrees) */
+  enum axes ese1_is;        /* name of the axis to which shaft
+			     * encoder 1 is attached
+			     * (implies the type of mount) (the 
+			     * type axes is declared in structures.h) */
+  float   fdegrees_per_step[2]; /* angular resolution of shaft 
+				 * encoders 1 and 2 */
+  int     isezeropos[2];    /* zero position of shaftencoders 1 and 
+			     * 2 from parameters file */
+  int     iaz_rev_track_corr; /* correction for the azimuth shaft 
+			       * encoder (ALT/AZ mount only) in 
+			       * reverse tracking mode */
+  int     ialt_rev_track_corr; /* correction for the altitude 
+				* shaft encoder (ALT/AZ mount only) 
+				* in reverse tracking mode */
+  float   fbendingcorr;     /* bending correction factor 
+			     * (ALT/AZ mount only) */
+  Boolean bdontusepix[iMAXNUMPIX]; /* bdontusepix is set true 
+				    * if the pixel should due 
+				    * to whatever reason not be 
+				    * used in image analysis, 
+				    * otherwise it is false;
+				    * this is a copy of the 
+				    * input from the parameters file */
+  Boolean bdontusepix_in_trig[iMAXNUMPIX]; /* is set true if the 
+					    * pixel should due 
+					    * to whatever reason not 
+					    * be used in the two out 
+					    * of all trigger, otherwise 
+					    * it is false; this is a 
+					    * copy of the input from 
+					    * the parameters file */
+  float   fphotoel_per_adccnt[iMAXNUMPIX]; /* conversion factors for 
+					    * the pixel signals */
+  float   fextinction;      /* atmospheric extinction (typically 
+			     * taken from the Carlsberg Meridian
+			     * Circle data) */
+  int     irubminusutc_usecs; /* difference between rubidium clock 
+			       * and UTC in microseconds */
+  int     isum_thresh_phot; /* threshold for the total sum of 
+			     * photoelectrons filter from the 
+			     * parameters file */
+  int     i2out_thresh_phot; /* threshold for the 
+			      * two-pixels-out-of-all software 
+			      * trigger from parameters file */
+  int     imuoncut_thresh_adccnt[iMAXNUMMUONPIX]; /* thresholds for 
+						   * the muon cut */
+  Boolean bmuon_suppression;       /* if true, the events which do 
+				    * not pass the muon cut are not 
+				    * written to the output */
+  float   ftolerated_pointerror_deg; /* maximum tolerated pointing 
+				      * error in the position check 
+				      * in iprocessdata */
+  float   fxpointcorr_deg;  /* pointing correction (to be added 
+			     * along the camera x axis) e.g. 
+			     * from point run */ 
+  float   fypointcorr_deg;  /* pointing correction (to be added 
+			     * along the camera y axis) e.g. 
+			     * from point run */ 
+  float   fcamera_align_angle_deg; /* the angle between the camera 
+				    * y-axis and the meridian when 
+				    * a culminating object is 
+				    * observed (defined 
+				    * counter-clockwise looking at 
+				    * the sky) */ 
+  int     iratecalc_numevents_odd; /* number of events used in the 
+				    * rate calculation (must be odd) */
+  enum pedsearchdirs {MATCH=0, BEFORE, AFTER, PINGPONG, 
+		      PEAKFWHM, NONE} epedsearchdir ; 
+  /* MATCH = only same number as run file (if ipedendofsearch is 0) or 
+     exactly ipedendofsearch;
+     BEFORE = search backwards until pedendofsearch; 
+     AFTER = search forward until pedendofsearch, 
+     PINGPONG = Try to fibnd the matching partner, try run#-1, run#+1,
+     run#-2, run#+2 etc. up to the third argument, the partnerfindrange 
+     NONE = use none of both. This is only useful for Monte Carlo
+     Analysis, for everything else it is highly unrecommended.*/
+  int     ipedendofsearch;  /* pedestal file number until which to 
+			     * search (see epedsearchdir) */
+  int     ipedsearchdepth;  /* depth, until which preproc should
+			     * try to find TelPed* partnerfiles */
+  enum    pedsearchdirs ecalsearchdir; 
+  /* MATCH = only same number as run file (if ipedendofsearch is 0) or 
+     exactly ipedendofsearch;
+     BEFORE = search backwards until pedendofsearch; 
+     AFTER = search forward until pedendofsearch, 
+     PINGPONG = Try to fibnd the matching partner, try run#-1, run#+1,
+     run#-2, run#+2 etc. up to the third argument, the partnerfindrange 
+     NONE = use none of both. This is only useful for Monte Carlo
+     Analysis, for everything else it is highly unrecommended.*/
+  int     icalendofsearch;  /* calibration file number until which 
+			     * to search (see ecalsearchdir)*/
+  int     icalsearchdepth;  /* depth, until which preproc should
+			     * try to find TelCal* partnerfiles */
+  double  dsourcera_hours;  /* right ascension of observed source 
+			     * in hours */
+  double  dsourcedec_deg;   /* declination of observed source in 
+			     * degrees */
+  float   fpadlevel_phot_pix[iMAXNUMPIX];   /* if > 0., software 
+					     * padding to this 
+					     * level is applied 
+					     * for the given pixel */
+  float   fseed1; /* seed for random generators */
+  float   fseed2;
+
+  int iswap_partner_of_pix[iMAXNUMPIX]; /* if >= 0, pixel i is 
+					 * swapped with 
+					 * iswap_partner_of_pix[i] 
+					 * in ireadrunfile, -pedfile, 
+					 * -calfile (internal 
+					 * numbering starting at 0)*/
+
+  Boolean bnewhistograms; /* set to true if new histograms shall be booked */
+  Boolean bhisto_on; /* set to true if histogramming is on */
+
+  enum eERRORTOLERANCE eerrortolerance; 
+  /* 0 == "cautious", exits on any reason (but tells in 
+   * the .err file,
+   * 1 == "normal", exits when physics could be affected
+   * by the error,
+   * 2 == "tank", never exits except on coredumps and when
+   * all files have been processed. Do not use such files for
+   * physics analysis! 
+   *
+   * NOTE: the capital letter words are the enums, the small letter
+   * words are to be used inside the parameter file. */
+  Boolean bmontecarlo;
+  /* if TRUE we have a monte carlo dataset before us, if FALSE 
+   * (default value) it is just normal data. */
+  enum eMCTRIGGERFLAG emctriggerflag;
+  /* all: all events which survive the filter are written to the 
+   *      events NTuple. 
+   * flag: When Dorota's triggerflag is set to 1 for a particular
+   *       event, it shall be written to the output. All others shall
+   *       just be disregarded. (Default)
+   * noflag: Opposite of 'flag': only events with triggerflag = 0 shall
+   *         be treated further. */
+  char mcfile[FILENAME_MAX];
+  float fmean_nsb_pe_pix[iMAXNUMPIX];
+  Boolean bfitmypedrms;
+  /* If TRUE, the pedestal MEAN and SIGMA=sqrt(MEAN) is fitted
+   * from pickup corrected pedestal data and not calculated from 
+   * the pickup corrected ADC values, as it was done up to 
+   * ~November 2000. */
+};
+
+struct calibrationdata { /* Calibration (Laser Run) Data to be read 
+			  * from the Te?Cal files */
+  int iid; /* no useful information, is long in the Macintosh format */
+  int itelescope; /* number of the CT which took the data */
+  int irunnum; /* run number from the file name */
+  enum onoroff eruntype; /* indicates if the run is on- or off 
+			  * (taken from filename) */
+  int inumruns; /* number of laser runs recorded in this file, is 
+		 * long in the Macintosh format */
+  char cname[iMAXFILENAMELENGTH]; /* copy of the filename used when 
+				   * the data was read */
+  double dmean_adc[iMAXNUMLASERRUNS][iMAXNUMPIX]; 
+  /* means of pixel signals over all shots calculated by TIJARAFE /
+   * Roberto: in processdata.c this number is recalculated. */
+  double dmean_lasoutput[iMAXNUMLASERRUNS][iMAXNUMLASEREVENTS]; 
+  /* This new (April 26 2000) quantity monitors the laser mean
+   * output recorded in events, which are not considered cosmics. */
+  double dmean_alladc[iMAXNUMPIX]; 
+  /* means of pixel signals over all triggers calculated by 
+   * preproc. */
+  double dmean_laserjitter[iMAXNUMPIX]; 
+  /* Here we calc. the deviation from the actual lasergain in a 
+   * single laser shot to the laser mean as averaged over the camera */
+  double drms_adc[iMAXNUMPEDRUNS][iMAXNUMPIX];
+  /* the standard deviations of the pixel signals */
+  int inumpixels; /* number of pixels in the camera, short in 
+		   * Macintosh format */
+  int inumevents[iMAXNUMLASERRUNS]; /* number laser shots, 
+				     * short in Macintosh format */
+  int ipixsig_adc[iMAXNUMLASERRUNS][iMAXNUMLASEREVENTS][iMAXNUMPIX]; 
+  /* the signals obtained from each pixel for each laser shot and 
+   * each laser run, unsigned short in the Macintosh format */
+};
+
+struct pedestaldata { /* Pedestal Run Data to be read from the 
+		       * Te?Ped files */
+  int iid; /* no useful information, is long in the Macintosh 
+	    * format */
+  int itelescope; /* number of the CT which took the data */
+  int irunnum; /* run number from the file name */
+  enum onoroff eruntype; /* indicates if the run is on- or of 
+			  * (taken from filename) */
+  int inumruns; /* number of pedestal events recorded in this file, 
+		 * is long in the Macintosh format */
+  char cname[iMAXFILENAMELENGTH]; /* copy of the filename used 
+				   * when the data was read */
+  double dmean_adc[iMAXNUMPEDRUNS][iMAXNUMPIX]; 
+  /* means of pixel signals over all triggers calculated by 
+   * TIJARAFE using a sigma cut of 2 */
+  double dmean_alladc[iMAXNUMPIX]; 
+  /* means of pixel signals over all triggers calculated by 
+   * preproc. */
+  double dmean_allPE[iMAXNUMPIX]; 
+  /* means of pixel signals over all triggers calculated by 
+   * preproc. */
+  double dmean_pedlevel[iMAXNUMPEDRUNS][iMAXNUMPEDEVENTS]; 
+  /* This new (preproc_0.4) quantity monitors the pedestal mean
+   * output recorded in events, which are not considered cosmics. 
+   * The calc.ing is done inside processdata.c */
+  double dmean_pedlevelPE[iMAXNUMPEDRUNS][iMAXNUMPEDEVENTS]; 
+  /* This new (preproc_0.4) quantity monitors the pedestal mean
+   * output recorded in events, which are not considered cosmics. 
+   * The calc.ing is done inside processdata.c */
+  double dmean_pedoffset[iMAXNUMPIX]; 
+  /* Mean Offset from the ADC spectrum of a pixel to the mean of the
+   * pedestal events. */
+  double dmean_pedoffsetPE[iMAXNUMPIX]; 
+  /* Mean Offset from the ADC spectrum of a pixel to the mean of the
+   * pedestal events. */
+  double drms_adc[iMAXNUMPEDRUNS][iMAXNUMPIX];
+  /* the standard deviations of the pixel signals used in the 
+   * sigma cut mentioned above */
+  double drms_alladc[iMAXNUMPIX];
+  /* The RMS value of the as-is ADC spectrum for all events inside a 
+   * Pedestal file. */
+  double drms_allPE[iMAXNUMPIX];
+  /* The RMS value of the as-is ADC spectrum for all events inside a 
+   * Pedestal file. */
+  double drms_nopickup[iMAXNUMPIX];
+  /* the standard deviations of the pixel signals' deviation from
+   * the events' mean (in ADC counts, of course...)  ---
+   * This is the same as the RMS of the pickup corrected pedestals! */
+  double drms_nopickupPE[iMAXNUMPIX];
+  /* the standard deviations of the pixel signals' deviation from
+   * the events' mean (in ADC counts, of course...)  ---
+   * This is the same as the RMS of the pickup corrected pedestals! */
+  int inumpixels; /* number of pixels in the camera, short in 
+		   * Macintosh format */
+  int inumevents[iMAXNUMPEDRUNS]; /* number of random triggers, 
+				   * short in Macintosh format */
+  int ipixsig_adc[iMAXNUMPEDRUNS][iMAXNUMPEDEVENTS][iMAXNUMPIX]; 
+  /* the signals obtained from each pixel for each random trigger 
+   * and each pedestal event, short in the Macintosh format */
+}; 
+
+struct runfiledata { /* Data read from Te?Run files */
+  int iformatid; /* Format ID of the data, long in Macintosh format */
+  int iversid;   /* Version ID of the data, long in Macintosh format */
+  int irevid;    /* Revision ID..., long in Macintosh format */
+  int itelescope; /* number of the CT which took the data */
+  int irunnum; /* run number from the file name */
+  int irunnumx; /* number read from the file, long in Macintosh format */
+  int inumevents; /* number of events recorded in this run, long in 
+		   * Macintosh format */
+  char cname[iMAXFILENAMELENGTH]; /* copy of the filename used when 
+				   * the data was read */
+  int ieventheaderlength; /* number of bytes in the event header,
+			   * long in Macintosh format */
+  int ieventheaderoffset; /* unknown meaning, long in Macintosh 
+			   * format */
+  int isignalslength; /* number of bytes used by the pixel signals, 
+		       * long in Macintosh format */
+  int isignalsoffset; /* unknown meaning, long in Macintosh format */
+  int itdccountslength; /* number of bytes used by the TDC signals, 
+			 * long in Macintosh format */
+  int itdccountsoffset; /* unknown meaning, long in Macintosh format */
+  int iobservtime_mins; /* (planned) observational time (minutes), 
+			 * short in Macintosh format */
+  enum onoroff eruntype; /* indicates if the run is on- or off-source; 
+			  * in the Macintosh format, this is a short
+			  * where 1 means off and 2 means on */
+  int ileapsecs; /* Leap seconds, introduced into UTC in order to 
+		  * keep track of some very small differences 
+		  * accumulated through the years. */
+  int ihv1;
+  int ihv2; /* these two numbers represent the HV adjustment made
+	     * by the shiftpersonnel. The last three items are 
+	     * only read for Roberto files, but not for Tijarafe 
+	     * files, as e.g. the HVs are not written out correctly. */
+  char cdummy[40]; /* unknown meaning */
+  int imactime_secs[iMAXNUMRUNEVENTS]; 
+  /* Macintosh time (time_t mydatum) in seconds since 1970, this is 
+   * put together from two Macintosh shorts and converted to the time 
+   * format required by SYSTEM */
+  unsigned int uigpstime_secs[iMAXNUMRUNEVENTS]; 
+  /* GPS time (time_t mydatum) in seconds since 1970, this is 
+   * put together from two Macintosh shorts and converted to the time 
+   * format required by SYSTEM 
+   * This time is new from Roberto and is coming from the PC-GPS card.
+   * There is another flag available in the runheader, which gives an
+   * overall flag for the run, whether or not the GPS time had been
+   * working. It is, however, not a good idea to use this flag, as 
+   * the workability of this card can also be dedued from the GPS time
+   * itself. This allows to check for failures on a event-by-event 
+   * basis, which seems more reasonable than using the global flag. */
+  unsigned int uigpstime_usecs[iMAXNUMRUNEVENTS]; 
+  /* GPS microseconds -- available from the card, that's why it is 
+   * put to the data, here it is.
+   * This is put together from two Macintosh shorts and converted
+   * to the time format required by SYSTEM */
+  unsigned int uirubsecs_secs[iMAXNUMRUNEVENTS]; 
+  /* the seconds of the Rubidium clock time this is put together 
+   * from two Macintosh shorts and converted to the time format 
+   * required by SYSTEM */
+  unsigned int uirubsecfrac_200ns[iMAXNUMRUNEVENTS]; 
+  /* the fractional part of the Rubidium clock time second, this is 
+   * put together from two Macintosh shorts, unit is 200 ns */
+  int isepos[2][iMAXNUMRUNEVENTS]; 
+  /* positions of shaft encoders 1 and 2, short in Macintosh format */
+  float fhourangle; /* This is the angle between the observation of this
+		     * event and the culmination point. It is going to 
+		     * be written into the events NTuple. */
+  int ieventnumber[iMAXNUMRUNEVENTS]; 
+/* number of the event, short in Macintosh format */
+  int inumpixels; /* number of pixels in the camera, short in 
+		   * Macintosh format */
+  int inummuonpixels; /* number of pixels in  the muon shield; 
+		       * the sum of inumpixels and inummuonpixels is 
+		       * part of the event record but should be the 
+		       * same for all events, so it is not put into 
+		       * an array */
+  int inumcointdcs; /* number of coincidence TDCs for which counts 
+		     * were recorded, short in Macintosh format
+                     * this value is part of the event record but 
+		     * should be the same for all events, so it is 
+		     * not put into an array */
+  int ipixsig_adc[iMAXNUMRUNEVENTS][iMAXNUMPIX]; 
+  /* signals from the camera photo multipliers (ADC counts) */
+  int imuonpixsig_adc[iMAXNUMRUNEVENTS][iMAXNUMMUONPIX]; 
+  /* signals from the muon shield photo multipliers (ADC counts) */
+  int itdcsig_cnts[iMAXNUMRUNEVENTS][iMAXNUMCOINTDCS]; 
+  /* counts from the coincidence TDCs if itdccountslength > 0 */
+};
+
+struct TELLOGDATA {
+  int irunnum; /* The runnumber which we are interested in. 
+		* Only data for this runnumber are written into 
+		* this structure and then copied to the calnt NTuple.
+		* 
+		* This runnumber is generally the closest match 
+		* inside the TelLog file. */
+  float pixel_timeaveraged_current[127];
+  float pixel_timeaveraged_scaler[127];
+};
+
+/************************************************
+ * structures in output file                    *
+ * (Konopelko files format)                     *
+ * (from structures.h file 4.4)                 *
+ ************************************************/
+struct mcbankheader { /* Once in every file */
+  int iparticle_type;  
+  /* Primary particle type: 0 = gamma; +-1= e+-; 
+   * +-2 = mu+-; +-3 = p+-, n; +-4 = pi+- */
+  int inum_cts;
+  /* Number of simulated telescopes */
+  int inum_nfl_shifts; 
+  /* Number of NFL shifts for hadrons (per event) */
+  int itrigger_thresh_phot; 
+  /* Only images with two pixels above this threshold are 
+   * in the MC data file */
+  int imin_signal;
+  /* "Tail cut" = smallest signal saved */
+  int inum_sim_showers; 
+  /* Total number of showers simulated for this file */
+  float fatmothick_gcm2; 
+  /* Atmosphere above the telescope [g/cm2] */
+  float fcos_zenangle;
+  /* Cosine of the zenith angle */
+  float fnfl_shift_radius_deg; 
+  /* Maximum angular radius within which a shifted 
+   * hadron shower is sampled [degrees] */
+  float fenergybin_bound_tev[iNUMENERGYBINS+1]; 
+  /* Boundaries for the 14 energy bins [TeV] 
+   * (newline after the first 8 numbers) */
+  float fzenithanglebin_bound[iNUMZENANGLEBINS+1]; 
+  /* Boundaries for the 11 zenith angle bins [degrees] */
+  int inum_show_in_bin[iNUMENERGYBINS]; 
+  /* Number of simulated (or saved) showers 
+   * per energy bin (newline after the first 8 numbers) */
+  float fmaxdist_impact_m[iNUMIMPACTBINS]; 
+  /* Maximum distance of the impact point to the 
+   * central telescope [m] for each energy bin 
+   * (newline after the first 8 numbers) */
+  int inumpixels_for_ct[iMAXNUMCTS]; 
+  /* Number of pixels in the camera of each simulated CT */
+  float fpixwidth_deg_ct[iMAXNUMCTS]; 
+  /* Pixel width [degrees] for each CT */
+  float fmirrsize_m2_ct[iMAXNUMCTS];  
+  /* Mirror area [m^2] for each CT  */
+  float fmean_nsb_phot_ct[iMAXNUMCTS]; 
+  /* Mean signal caused by the NSB in each pixel for each CT 
+   * [photoelectrons]. This is the simulation of the NSB, 
+   * not the electronic noise */
+  float fphes_per_photon_ct[iMAXNUMCTS]; 
+  /* Conversion factor photoelectron per photon */
+  float frelative_x_ct[iMAXNUMCTS]; 
+  /* x position relative to the central CT for each CT */
+  float frelative_y_ct[iMAXNUMCTS]; 
+  /* y position relative to the central CT for each CT */
+}; 
+#endif
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mars.cc
===================================================================
--- /tags/Mars-V0.9/mars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mars.cc	(revision 9772)
@@ -0,0 +1,147 @@
+#include <TApplication.h>
+
+#include "MAGIC.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCameraDisplay.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MParContainer.h"
+
+#ifdef HAVE_XPM
+#include "MLogo.h"
+#endif
+
+using namespace std;
+/*
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,02)
+#include <TRootGuiFactory.h>
+#include <TPluginManager.h>
+void InitGuiFactory()
+{
+    if (gROOT->IsBatch())
+        gROOT->SetBatch(kFALSE);
+
+    //
+    // Must be loaded by hand, because it is not loaded by TGApplication.
+    // We could also use TApplication instead, but TApplication doesn't
+    // deal with the DISPLAY variable in a convient way.
+    //
+    TPluginHandler *h;
+    if ((h = gROOT->GetPluginManager()->FindHandler("TGuiFactory", "root")))
+    {
+        if (h->LoadPlugin() == -1)
+            return;
+        gGuiFactory = (TGuiFactory*)h->ExecPlugin(0);
+    }
+}
+#endif
+*/
+
+// **********************************************************************
+//
+//    MARS main program  
+//
+//    The only job of the main program is the initialisation of ROOT and 
+//    the start of the guiinterface for the mars program
+//
+//    started by  h. kornmayer      january, 3rd  2001 
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "                    MARS V" << MARSVER              << endl;
+    gLog << "    Magic Analysis and Reconstruction Software"     << endl;
+    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
+    gLog << "               Using ROOT v" << ROOTVER             << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   mars [-h] [-?] [-a0] [-vn]" << endl << endl;
+    gLog << "     -a0: Do not use Ansii codes." << endl;
+    gLog << "     -vn: Verbosity level n [default=2]" << endl;
+    gLog << "     -?/-h: This help" << endl << endl;
+}
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+
+    if (arg.HasOption("-?") || arg.HasOption("-h"))
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Set verbosity to highest level.
+    //
+    gLog.SetDebugLevel(arg.HasOption("-v") ? arg.GetIntAndRemove("-v") : 2);
+
+    if (arg.HasOption("-a") && arg.GetIntAndRemove("-a")==0)
+        gLog.SetNoColors();
+
+#ifdef HAVE_XPM
+    MLogo logo;
+    logo.Popup();
+#endif
+
+    //
+    // initialise ROOT
+    //
+    TApplication app("Mars", &argc, argv);
+    if (gROOT->IsBatch() || !gClient)
+    {
+        gLog << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Swtich of TObjectStreamer in our base classes derived from TObject
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    /*
+    TGApplication app("Mars", &argc, argv);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,02)
+    InitGuiFactory();
+#endif
+    */
+
+#ifdef HAVE_XPM
+    logo.Popdown();
+#endif
+
+    //
+    // start the main window
+    //
+    new MCameraDisplay;
+
+    //
+    // run the application
+    //
+    app.Run();
+
+    gLog << all << endl;
+
+    return 0;
+}
+ 
+
Index: /tags/Mars-V0.9/mars.rc
===================================================================
--- /tags/Mars-V0.9/mars.rc	(revision 9772)
+++ /tags/Mars-V0.9/mars.rc	(revision 9772)
@@ -0,0 +1,90 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#
+#  This is a resource file for the Mars executable. You can here setup
+#   setup the tasks of the eventloops executed in the Mars executable -
+#   if supported by these tasks.
+#
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# -------------------------------------------------------------------------
+# Define here which signal extractor you are going to use for the
+# whole calibration chain
+# -------------------------------------------------------------------------
+ExtractSignal: MExtractTimeAndChargeDigitalFilter
+# -------------------------------------------------------------------------
+# Define here an extractor which can be used for the December 04 data.
+# -------------------------------------------------------------------------
+#ExtractSignal: MExtractTimeAndChargeSpline, MExtractTimeAndChargeDigitalFilterPeakSearch, MExtractTimeAndChargeSlidingWindow
+# -------------------------------------------------------------------------
+# Define here parameters valid for all extractors above
+# -------------------------------------------------------------------------
+#ExtractSignal.HiGainFirst:         0
+#ExtractSignal.HiGainLast:         15
+#ExtractSignal.LoGainFirst:         3
+#ExtractSignal.LoGainLast:         14
+#ExtractSignal.SaturationLimit:   250
+#ExtractSignal.OffsetLoGain:     1.51
+#ExtractSignal.OffsetLoGain:        0
+#ExtractSignal.LoGainSwitch:      150
+#ExtractSignal.LoGainStartShift: -2.8
+#ExtractSignal.LoGainStartShift: -2.8
+# -------------------------------------------------------------------------
+# Define here parameters valid for the spline:
+# -------------------------------------------------------------------------
+#ExtractSignal.Resolution:        0.05
+#ExtractSignal.RiseTimeHiGain:    0.5
+#ExtractSignal.FallTimeHiGain:    1.5
+#ExtractSignal.LoGainStretch:     1.5
+#ExtractSignal.ExtractionType: Integral <default>
+#ExtractSignal.ExtractionType: Amplitude
+# -------------------------------------------------------------------------
+# Define here parameters valid for the sliding window:
+# -------------------------------------------------------------------------
+#ExtractSignal.HiGainWindowSize:     6
+#ExtractSignal.LoGainWindowSize:     6
+# -------------------------------------------------------------------------
+# Define here parameters valid for the digital filter with peak search:
+# -------------------------------------------------------------------------
+#ExtractSignal.OffsetLeftFromPeak:   3
+#ExtractSignal.OffsetRightFromPeak:  3
+#ExtractSignal.PeakSearchWindowSize: 2
+#ExtractSignal.HiGainFailureLimit:  10
+#ExtractSignal.LoGainFailureLimit:  25
+
+# -------------------------------------------------------------------------
+# In the case of the Digital filter you have to overwrite the default
+# weights file depending on what you are extracting
+# -------------------------------------------------------------------------
+#ExtractSignal.WeightsFile: msignal/cosmics_weights.dat
+
+# -------------------------------------------------------------------------
+# Setup level for determining of bad pixels
+# -------------------------------------------------------------------------
+#MBadPixelsCalc.PedestalLevel:         3.0
+#MBadPixelsCalc.PedestalLevelVariance: 3.0
+#MBadPixelsTreat.NumMinNeighbors:      3
+#MBadPixelsTreat.UseInterpolation:     yes
+#MBadPixelsTreat.ProcessPedestalEvt:   yes
+#MBadPixelsTreat.ProcessPedestalRun:   no
+#MBadPixelsTreat.ProcessTimes:         yes
+#MBadPixelsTreat.UseCentralPixel:      no
+#MBadPixelsTreat.HardTreatment:        no
+
+# -------------------------------------------------------------------------
+# This is how you can setup the Image cleaning used in the Camera Display
+# -------------------------------------------------------------------------
+MImgCleanStd.CleanMethod: Scaled
+MImgCleanStd.CleanLevel1: 4.5
+MImgCleanStd.CleanLevel2: 3.0
Index: /tags/Mars-V0.9/marslogo.xpm
===================================================================
--- /tags/Mars-V0.9/marslogo.xpm	(revision 9772)
+++ /tags/Mars-V0.9/marslogo.xpm	(revision 9772)
@@ -0,0 +1,363 @@
+/* XPM */
+static char *marslogo[] = {
+/* width height ncolors chars_per_pixel */
+"100 100 256 2",
+/* colors */
+"   c #E99C39",
+" . c #71705B",
+" X c #113A42",
+" o c #DBAF21",
+" O c #9A8A76",
+" + c #928282",
+" @ c #7B815E",
+" # c #AD6A4A",
+" $ c #172834",
+" % c #6C7F8E",
+" & c #444B49",
+" * c #1C3B46",
+" = c #785944",
+" - c #28485F",
+" ; c #EA8651",
+" : c #C8714A",
+" > c #8A7145",
+" , c #515759",
+" < c #9E6145",
+" 1 c #061837",
+" 2 c #4F5157",
+" 3 c #636464",
+" 4 c #485750",
+" 5 c #9E962A",
+" 6 c #2C2A24",
+" 7 c #3D464F",
+" 8 c #B17854",
+" 9 c #DBC313",
+" 0 c #647789",
+" q c #867A3A",
+" w c #A7705E",
+" e c #9F7656",
+" r c #D2BE14",
+" t c #82604A",
+" y c #3E4D5D",
+" u c #544C16",
+" i c #A7AB99",
+" p c #C58443",
+" a c #C9B40B",
+" s c #88803F",
+" d c #263542",
+" f c #5C6877",
+" g c #8A7A02",
+" h c #9C7160",
+" j c #9D9C2F",
+" k c #6E6622",
+" l c #5C6463",
+" z c #999F8B",
+" x c #152A3B",
+" c c #A0937E",
+" v c #E9C313",
+" b c #E9B81D",
+" n c #B4833F",
+" m c #90624A",
+" M c #02051B",
+" N c #655244",
+" B c #D1B819",
+" V c #AD7642",
+" C c #AA6853",
+" Z c #2A2A2B",
+" A c #646550",
+" S c #988602",
+" D c #3C4B4D",
+" F c #64693C",
+" G c #5A5850",
+" H c #263F5F",
+" J c #B4A11A",
+" K c #AB8339",
+" L c #3B3C42",
+" P c #D2814F",
+" I c #5A5146",
+" U c #3F5D7E",
+" Y c #2A4A70",
+" T c #273D4C",
+" R c #BABAAE",
+" E c #C88C3B",
+" W c #64716A",
+" Q c #635C1D",
+" ! c #3A3202",
+" ~ c #E8A92C",
+" ^ c #7C783C",
+" / c #746952",
+" ( c #8F5D45",
+" ) c #51524A",
+" _ c #C89D34",
+" ` c #C3AE25",
+" ' c #BAA830",
+" ] c #D17951",
+" [ c #020203",
+" { c #BC8B3C",
+" } c #D46A4A",
+" | c #B0A026",
+".  c #113643",
+".. c #32618B",
+".X c #141525",
+".o c #16253E",
+".O c #776705",
+".+ c #050C20",
+".@ c #92674E",
+".# c #3F4345",
+".$ c #6A5E02",
+".% c #8B7B5E",
+".& c #797174",
+".* c #A96E4A",
+".= c #8E8643",
+".- c #9E826A",
+".; c #CA9232",
+".: c #71696C",
+".> c #255B81",
+"., c #08131C",
+".< c #827716",
+".1 c #B3A81B",
+".2 c #BE704E",
+".3 c #E87A53",
+".4 c #9C8B0B",
+".5 c #DC7951",
+".6 c #D1943C",
+".7 c #18191B",
+".8 c #9A863E",
+".9 c #9C8040",
+".0 c #C5A926",
+".q c #8F6A5B",
+".w c #C87751",
+".e c #9E961A",
+".r c #06203E",
+".t c #DECA10",
+".y c #485A61",
+".u c #EA8C44",
+".i c #B69A8B",
+".p c #DD8155",
+".a c #7E6E4A",
+".s c #334249",
+".d c #DB9A35",
+".f c #9E7D4F",
+".g c #0D3D69",
+".h c #DBAA21",
+".j c #5A5941",
+".k c #785F4E",
+".l c #967947",
+".z c #1A4A6F",
+".x c #D2714A",
+".c c #EBA234",
+".v c #B1933D",
+".b c #323234",
+".n c #826851",
+".m c #293335",
+".M c #165282",
+".N c #4D6376",
+".B c #687876",
+".V c #716054",
+".C c #6A7039",
+".Z c #364E52",
+".A c #83695F",
+".S c #34567B",
+".D c #0A2834",
+".F c #31484D",
+".G c #1D3C61",
+".H c #406380",
+".J c #4E5C70",
+".K c #69651A",
+".L c #B49A3C",
+".P c #171A30",
+".I c #151403",
+".U c #0B0C0D",
+".Y c #C26A4A",
+".T c #3F5261",
+".R c #314B71",
+".E c #B8694A",
+".W c #AB9B15",
+".Q c #324B5E",
+".! c #AB6447",
+".~ c #7E6E56",
+".^ c #757782",
+"./ c #B38A3E",
+".( c #DCBA1A",
+".) c #A89C89",
+"._ c #DD9339",
+".` c #484003",
+".' c #E4764A",
+".] c #425253",
+".[ c #5B6351",
+".{ c #666973",
+".} c #403C26",
+".| c #827E74",
+"X  c #E9943E",
+"X. c #AA8B42",
+"XX c #072130",
+"Xo c #596070",
+"XO c #654D47",
+"X+ c #607184",
+"X@ c #877065",
+"X# c #323C43",
+"X$ c #594A45",
+"X% c #675E56",
+"X& c #273D42",
+"X* c #92928A",
+"X= c #E9BE19",
+"X- c #4E4544",
+"X; c #32425A",
+"X: c #67574C",
+"X> c #E28A4E",
+"X, c #35536A",
+"X< c #CE8A4E",
+"X1 c #728692",
+"X2 c #071A29",
+"X3 c #DB8B3D",
+"X4 c #8C801A",
+"X5 c #061428",
+"X6 c #BD9F33",
+"X7 c #4D4B46",
+"X8 c #C1A123",
+"X9 c #E7AF24",
+"X0 c #968A52",
+"Xq c #715145",
+"Xw c #C2AE06",
+"Xe c #8C9048",
+"Xr c #51574D",
+"Xt c #D29D37",
+"Xy c #2E2E2E",
+"Xu c #9F8B3D",
+"Xi c #C5B420",
+"Xp c #D1A922",
+"Xa c #D5A126",
+"Xs c #8F7155",
+"Xd c #EED506",
+"Xf c #815944",
+"Xg c #AEA831",
+"Xh c #415872",
+"Xj c #BD9536",
+"Xk c #928305",
+"Xl c #242424",
+"Xz c #705947",
+"Xx c #595E4E",
+"Xc c #788A8A",
+"Xv c #DB8343",
+"Xb c #D38D3B",
+"Xn c #919132",
+"Xm c #6A763A",
+"XM c #A17142",
+"XN c #5A5B5C",
+"XB c #E9CA0E",
+"XV c #C07750",
+"XC c #EA7F55",
+"XZ c #365C6A",
+"XA c #AA9605",
+"XS c #685742",
+"XD c #1D1E20",
+"XF c #1A313E",
+"XG c #B56E4F",
+"XH c #D3B220",
+"XJ c #907066",
+"XK c #0B3143",
+"XL c #272202",
+"XP c #082940",
+"XI c #193554",
+"XU c #9E684C",
+/* pixels */
+"XlXlXlXy Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z ZXy",
+"XlXlXlXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXlXDXy",
+"Xy.bXl.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U Z",
+".b.bXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXyXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXy.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M.U.U.+.,.,XXX2X5.,.+.+.U.+ [ M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXy.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M.,.,XXXXXF $ xXF. XFXF.FX&.FX& * xXF.D x.D.DX2X2., M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXyXD [.U [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U.+XX.D X X.FX&X&.F.F.s.F.].].].].FX& * * * X. . .DXX.,.+ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U [ [ [ [ [ [ [ [ [ [Xl",
+"XyXy.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.+.UXX.D $X&X&X& *.F.F.Z 4.]Xr.[.B %.B.B.[ D D.s.sX&.FX& *XF.D.DX2X5.+.U [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6XD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U.U.,XXXF dX&X&X&X&X&.mX#.Z 4 W ..C.B @X* z z z.| F.[Xr & & 4.] 4 DX&X&. . .D.DX5.U M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z ZXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.+.D xX&.F.s.F.sX&X# dXF.m.b A.| i z zX*.).).).) c @ / /.V.jXx.jXx.[Xr & &.F.sX& *XKXXXX.+ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6XD [.U [ [ [ [ [ [ [ [.U [ [ [ [ [ [ [ [ [ [ [ [ [ [.,XI *.s D.#.s.s.sX#.m.m.m.b.: + R i i.).).) c O O.% / / /XxXx G.[ A.j & & &.ZX&X& XXP.DX5 M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U [Xl",
+"XyXy.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.,.,.DX& 7.s.#.s.#.s.#.s.b.b.b.b.b.kX@.i.i.i.-.- h m m.n t N.j I I.[.[X% / A I I & & D D.s X. XKXXX5 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6XD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.+ $X&X&X#.FX- & &X7 &X7X7X7XO IX$X-X-X7 IXzXz N NXS N.V.VXz.j.j I.j.jX: AXzXSXS N.j I uX7 &.#X#.m * XXPX2 1.+ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"Xy.bXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.,.D.FX#X#X#.# &X7Xr I NXOXq =Xf ( ( = =XOXOX$X$X$X$X$ I NXS N NXzXzXzXS.~.n.kXzXz NXO N I I ) &.b.bX&X& XXKXKXX.+ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"Xy 6XD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U.+XP d.Z.mX#X#.#X7X7.jXS =XfXfXf ( < ( (XfXf =XqXqXqXq NXqXf = = =.k = t =.n.aXf = =XSXq N N I I &.}X#.FX& *XKXKXPX5 M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z ZXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U x. .F.Q.sX#X#X# & I I = = ( < < < < < < < <.! < < < ( < ( < ( ( m m ( ( ( t t = = = =XzXz NXq N NX7 &.F &.s.s X X XXKX2X5.+ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXyXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M x.FX;.s.s.#.#.#.#X7XO NXfXf ( ( < < < < < <.! <.! < ( < < < < ( ( ( ( ( ( ( t t.nXf = = =XzXq NXS N I & & & & &X&X#X& XXKXPXXX5 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [., -.s.s.s.s 7 & &X7 IXOXq t ( < < < < < < <XUXM.! <.! < < <XM < < <XU ( (XfXfXf t t = = =Xz =XSXqXzXS IX-X7X7 & &X#X#X#X& X XXK.r [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" 6XyXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ xXF.Z.Z D.F D &X7 &X$ N =Xf ( ( < < m <XU < <.!.! <.! < < <.* < < < < < <Xf ( (Xf (Xf = =XzXzXSXSXSXS N IX7 &X7X7.#.s.s.F.s * X.DXP.+ M [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z ZXD [ [ [ [ [ [ [ [ [ [ [ [.+X2.F.Z.T.] 2 4.] )X7 IXS = m m < < ( ( ( ( m < < < < m < ( ( ( ( ( (Xf tXfXfXfXfXfXf = =XzXzXO NXS N N N I IX7 ) &X7 &.#.}.s.#.s.s.m. .D.r.+ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXy.7 [ [ [ [ [ [ [ [ [ [ [.UXF T 7.Q.] 2 2 , ) ).j IXS ( <.! < <XfXf =XqXf ( ( ( ( tXfXfXqXqXzXqXqXSXSXSXq N NXq NXS NXO.jX$X$ I I N I I I )X7X7X7X7 & & & & & &.#X&. XKX2.+ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"Xy.bXD [ [ [ [ [ [ [ [ [ [ [.,X&.F.# 7 4 , 2 2 , ) I I = <.! <.! <Xf =XqXqXf ( ( ( ( t t =XqXOXqXO N I I IXO I I N I N IX$ IX7X7X$ I N I I.jX7X$X7X7X- & & & &X7 &.FX# X. .DX5 [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6XD [ [ [ [ [ [ [ [ [ [X5 x.s.s & & 2 4 ,XN G GXOXO = <.!.!.!.!Xf = = tXf ( (XfXf.n tXf =Xz =XqXS N N N N N.j I IX$X7X7X7.#X7X7X7 I I ).j ) )X7X7 & & & &X-X7 u &X-X#X&XK.rX5 [ [ [ [ [ [ [ [ [ [ [Xl",
+".b.b.7 [ [ [ [ [ [ [ [ [ M -.Z D 7X- 2 4 G G G G IXO NXq <.!.E #.! ( ( ( ( = < < ( ( t t =Xz =XzXzXS = = =Xf I I I IX7X7X-.s.} & & & & ) ) I I IX7X7X7 & &X7X7 I IX7X7.F.s * XXP M [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6XD [ [ [ [ [ [ [ [ [ d.Z.Z &.#.#.# ) IX7X7 IX$ N NXz.!.!.E.!.!.!.! < < < < < < < < (XzXzXSXzXS NXzXz =XS I N I IX7X7.#.sX#.s.# & &X7X7 IX7X7X7 )X7.j ) )X$ I I I IX7 &X# TXPX5.+ [ [ [ [ [ [ [ [ [Xl",
+" Z ZXD [ [ [ [ [ [ [ [ M T.Z.].# &X-X-X7 IX7X$ IX$ N N = <.E.E.!.!.!.E < < <XU < <XU < <Xf =.kXSXS IXzXSXSXO N I I IX7 & &.#X#.#.#X7X7 &X7 )X7X$X7 )X7XrXrX7 I.j N N IX7 &.s T.  1X5 [ [ [ [ [ [ [ [ [Xl",
+"Xy 6XD [ [ [ [ [ [ [.+ $.F.] & & &X-X7X-X$ I I IXqXqXfXf.!.E.E.E.Y.E.E.E.!.! # # #.E.! #XU < ( mXfXSXSXzXS I N I IX7 &X7 &.# D D & &X7X7X7X7X7 )X7X7X7X$ I IXSXSXSXS NX7 ) &.Z.GXP.r.+ [ [ [ [ [ [ [ [Xl",
+" Z Z.7 [ [ [ [ [ [ [XX -.]X7X7X- &X-X-X$XO N N N = (Xf <.!.!.Y.Y.E.E.E.E.E.!.E.E.E.Y.E.2.2.E.Y #.!.@ m mXfXzXzXz I IX- &X7 & & & & &X7 ) ) &X7 &X7X7 ) N IXq =XzXzX:XS I I 4 D -XKXP.+ [ [ [ [ [ [ [ [Xl",
+" Z 6XD [ [ [ [ [ [ [XFX,.]X7 &X7X-X$X$ I I IXOXOXf ( ( <.!.E.E.E.Y.E.E.E #.!XG.!.Y.2.2 :.Y.Y.2.2.EXUXUXU < t ( t =XS I I IX7 &X7 &X7X7 &X7X7X7X7X7 & IXSXzXz = =XzXzXz I I.].T T.gXKX2.+ [ [ [ [ [ [ [Xl",
+"XyXy.7 [ [ [ [ [ [.+X;.y.]Xr )X7 I = =XqXz NXfXf ( ( < < #.E.E.2.2 :.w :.E.*.E.E : : : : : : :XV : :.E.EXGXG # # # # m (.kXS.jX7X7X7X7 D & )X7X7X7.jXz t t.nXf = =XzXz N G ).Z T H.zXP 1 [ [ [ [ [ [ [Xl",
+" ZXyXD [ [ [ [ [.P x.y 4X7 ) I = t m.@ m < (XU <XU #.! #.E.2.E.2XG : : :.x.x : : : :.x :.xXV.E.2.2XGXU < #.! ( (XU # #.E.!XU <XzXSX7 ) &X7X7 IXSXqXf m m m m t t t =XzXz N ) & -.Q Y.M.g M M [ [ [ [ [Xl",
+".bXyXD [ [ [ [ [ * T.y.y ) ).j t mXUXUXU C.! # # #.EXG.E.2.Y.E.Y.!.E.2 :.x p.x.x.x.x.x ].xXG.EXG.2 #.@ <XU <XqXf mXU.EXG.Y.Y #.n = ) )X7X7X7XSX: (Xf ( m.@ ( ( t t = =X:X% 2.].FX,XZ.M.MX5.+ [ [ [ [ [Xl",
+"Xy 6XD [ [ [ [ [X;.Q.y ) )X: =XUXU C #XU.E.EXGXG.EXG.2.2.2.2.2.! <.!.!XG :.Y.Y.2.x ].x.x.x.Y.2.2 : : < m <XfXz = <XUXUXUXG.E.* t = IX$X7X$ I t t < ( < m m ( ( t t.k =XzXz ) 4.FX,.S...>.rX5 [ [ [ [ [Xl",
+" ZXy.7 [ [ [ [.,Xh.J.] &X: m.q.*.*.!.! C.EXG.2.2.2.2.Y.2 :.2.E <.@ ( < #.EXG #.E :.x :.w.x.x.x.x.x :.@ < m =Xq = <XUXU.!.*.*.!.@ tX$X7 I I = <XU < <.@ mXU m ( ( t t = =Xz GXN.ZX,.S.....gXK [ [ [ [ [Xl",
+" Z 6XD [ [ [.IX& l fXxXx.nXUXUXU C.!.!.* #.2XVXV.2.2 :XV.2 : V.!.!.! # :.x.2.2 : ].x.wXV.xXv ]Xv ]XG.!XU.@ m tXf t < # # # #XGXU mXSXS.a t.@XM.*XUXMXM < m.@ ( t m t =.k =X: G 2.T.N.N.H.>.z.7.U.I.U [Xl",
+" Z Z.7 [ [.`Xk.eXgXg |XgX8 VXU.*XU.!.E.E #.EXVXa.h o.h.h.h.hXa < #.EXG :.x : :XV.x.x.;.h oX9.hX9 o.2XM.*XU.@.n t = ( # # # VXpX8.0 J J.0XwXpXpXpXpXpXpXj.@ < ( m t.n = = =X% GXr.yXnXgXg j jXkXkXk.OXL 6",
+"XyXyXD [ [.$XBXBXdXBXdXdXd nXU.!.!.!.!.!.E.E p 9XdXBXdXdXBXd.( #.2 : :.x.x.5.x.'.x.'.dXdXdXdXdXdXBXb m < <.E.E.E < m m m <.9XBXdXBXdXBXdXBXdXBXdXBXdXB 9XH./ m ( ( m t.V.kX:X% |.1.tXdXdXdXdXBXdXB 9XA.<",
+" ZXy.7 [.`XAXdXdXdXdXdXdXd {.!.!.!.!.E.E.Y.Y.hXBXdXdXdXdXdXBX= :.x.x.x.x.'.'.'.'.'.u bXdXdXdXdXdXd.hXM mXU.2 : : :XG.E # VX8XBXdXdXdXdXdXdXdXdXdXdXdXdXdXB oXM m (.q.AXf.A /.9.t.tXdXdXdXdXdXdXdXdXd.t.W",
+"XyXyXD [ gXBXdXdXdXdXdXdXd.0 V.E.E.E.E.Y } }XBXdXdXdXdXdXd v.d ].'.x.5.3.'.'.'.'XC ~XBXdXBXdXdXdXdXB K ( ( #.x.x.x : } } EX=XdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXB K m m m (.A.k.9 BXdXdXdXdXdXdXdXdXdXdXd 9.<",
+"XyXy.7 [.4XdXdXdXdXdXdXdXd v n #.EXGXG.2.x._XdXdXdXdXdXdXd b.'.'.5.'.'.3XC.3.'.'.uX=XdXdXdXdXdXdXdXd n < (XG.x.x.x :.x :Xb vXdXdXdXdXB.hX9.h o bXdXdXdXdXdXd K m m m.A.k.9XiXdXdXdXdXd `Xg | j S.4XdXw u",
+" ZXy.7 [ SXdXdXdXdXdXdXdXdXB pXGXV.2.2.x ]XdXdXdXdXdXdXdXdX9.'.'.'.3.3.3.3XC.3.3X9XdXdXdXdXdXdXdXdXdXb.Y.2.2 }.x.Y :.x.YX3XBXdXdXdXd b.E #.E.E.;XdXdXdXdXdXd KXU m.A (.A BXdXdXdXdXB r W.S.>.g.U [ J S.}",
+"XyXy.7 [.4XdXdXdXdXdXdXdXdXB p.2XV.2XV ]X3XdXdXdXdXdXdXdXd b.'.'.'.3.3XC.3.3.3.u bXdXdXdXBXdXdXdXdXd._.'.x :.x : : : : }XbXBXdXdXdXd o.Y.2.E.!.;XdXdXdXdXdXd {.@.q.@ m.l.(XdXdXdXd 9Xe.N.N.H.g.+ [XLXL 6",
+" Z 6XD.IXAXdXdXdXdXdXdXdXdXB pXV.2XV.2 P bXdXdXdXdXdXdXdXd b.3.3.3.3.3.3.3.3.3X XBXdXdXBXBXdXdXdXdXdXa.x.x : : :.x : : :.d vXdXdXdXB.h.2.EXG.! pXdXdXdXdXdXd nXs.@.q.qX6XBXdXBXdXd.t @.N.N U.z.+.U [ [Xl",
+"XyXy.7 u 9XdXdXdXdXdXdXdXdXBX<XGXV.2.wX3 vXdXdXdXBXdXdXdXd b.3.'.3.3XC.3XC.3.3  XdXdXB ~ bXdXdXBXdXdX=X3.x ] : ].x.x.w pX9XdXdXdXd o p.2.2.E #.;XdXdXdXdXdXd nXU h.qX@.0XdXdXdXdXd 9 @.N.N.H.z., M [ [Xl",
+" Z 6XD.OXBXdXBXdXa.(XdXdXdXB pXV.2XV P ~XBXdXdXdXdXdXdXd v.u.3.'.3.3.3XCXC.3X X=XdXdXd.c.cXdXdXdXdXdXdX3 ].w P ].x ] ]XbX=XdXdXdXd.h.2.E.2.2.EXbXdXdXdXdXd o e hXU.q.q.0XdXdXdXdXdXd a W.N.H.zX5.+ [ [Xl",
+"XyXy.7.OXdXdXdXdX. BXBXdXdXBX<.2XV P.hXBXdXdXBXdXdXdXBXd bXC.3.3.3.3XCXCXC.u vXdXdXd b.'.u vXdXdXdXdXdX3 ] ] ].wXV : ] P vXdXdXdXd.hXV.2.2XG.;X=XdXdXdXBX9 V w.q.q.q h.fX=XdXdXdXBXdXdXi f.N.z.r.+ [ [Xl",
+".b.bXD.OXdXdXdXBX.XHXdXdXdXB EXVXV.pX=XdXdXdX9 vXdXdXdXdX=.3XC.3.3XC.3.3XC  XdXdXdXB ~.'.'X=XdXdXdXdXd._.x ].w.w.2.x.w PX=XdXdXdXd o pXVXV E.(XdXdXdXdXdX6 C w hXJ h.q.qXiXBXdXdXdXdXdXd jXeXZ.r.+ [ [Xl",
+".b.bXD.OXdXdXd.1.% BXdXdXdXB o pXVX9XBXdXdXBX  vXdXdXdXd bXC.3.3XCXCXCXC.u bXdXdXd b.u.3.' vXdXdXdXdXdX3.5.x.wXV.w.w.2 pX=XdXdXdXdX= oXpXp oXdXdXdXBXd b n w h h h hXJXJX..(XdXdXdXdXdXd.t 9XnXFX5 [ [Xl",
+"Xy.b.`.4XBXdXd s.AXHXdXdXdXdXBX<.wXdXdXdXd b.u vXdXdXdXdX=XC.3.3.3XCXCXC  XdXdXdXd.c.3.3XCX=XdXdXdXdXB.cXv ].x.x.2 #.! E vXdXdXdXdXdXBXdXdXdXdXdXd v o.;XU C w h h hXJX@XJ.v vXdXdXdXdXdXdXd r.KX5 [ [Xl",
+" Z Z.<XBXdXdXd s.AXHXdXdXdXd v.6X<XdXdXB vXC   vXdXdXdXB b ;XC ;.3XC.3XC.cXdXdXdXBX XC.3.3 vXdXdXdXdXdXB.6.2.2 w.@ t.qXBXdXdXdXdXdXdXdXdXdXdXdXdXBXt 8 w w w h h hXJXJXJ.qXJ 'XBXdXdXdXdXdXdXd.tX& [ [Xl",
+" Z Z.<XdXdXdXd.=X@XHXdXdXdXdXB.6 bXdXdXBX>XCXBXdXdXdXd b.uXC ;XC.3.3.3  XBXdXdXd.cXC.3.3.3 ~XBXdXdXdXdXB.dXG w w t =.nXdXdXdXdXdXdXdXdXdXdXdXdXd b 8 wXU w w w hXJXJXJXJXJ.AXJ ` vXdXdXBXdXdXdXd a !.UXl",
+"XyXyX4XdXdXdXd.=.qXHXdXdXdXd vXtXBXdXB bX>.pXdXdXdXdXd bXC.3XC.3.3.3XC ~XdXdXdXd.cX .uX .u  X=XdXdXdXdXB._ w t.kXzXz.VXdXdXdXdXBXB.( 9XdXdXdXdXd b 8 w w w w w h h hXJXJXJXJ.A.| '.(XBXdXdXdXdXdXBXAXLXl",
+".bXyX4XdXdXdXdX0.q.(XdXdXdXdXdX=XdXdXB.c.p.pXdXdXdXdXd bXC.3.3.3.3.3.u vXdXdXdXdXBX= vX= v bXBXdXdXdXdXB.6 CX%X:XqXq.kXdXdXdXdXd r.9Xu bXBXdXdXdXBXj w w C w h h h.- hXJXJX@.A.&.%X0 `XBXdXdXdXdXdXwXLXl",
+".b.}.4XdXBXdXB s.A.0XBXdXdXdXdXdXdXdX=._ ].pXdXdXdXdXd bXCXC.3.3XC.3.uXdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXB.d hXzX:X: G.VXdXdXdXdXdXH.a.a EXdXdXdXdXdXt h w C h h h h hXJXJXJX@X@.&.:.& . 9XdXdXdXdXdXwXLXl",
+" Z.KXHXdXdXd ` /.A.8.(XdXBXdXdXdXdXBXtX<.5.5XdXdXdXdXd b ;.3.3.3XC.u bXdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXH hX:Xq 2X: |XBXdXdXdXd B.a.V 8XdXdXdXdXd _ w C w w w.- h hXJXJXJX@X@.&.:.:Xo 9XdXdXBXdXdXwXLXl",
+"XyX4XdXdXdXd jXN /X@.0XdXdXdXdXdXdXBX<.w ] ~XdXdXdXd vX XCXC.3.3.3X XdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXdXdX= >X:XN 2 AXBXdXdXdXd v qX%X%XsXdXdXdXdXdX=./ wXU h h h h h hXJXJX@X@.&.:.:Xo 9XdXdXdXdXdXwXLXl",
+"XyX4XdXdXdXd 5XN.V /XpXdXdXdXdXdXd.6XV.w ]XdXdXdXdXdX=.3.3.3.3XCX  bXdXdXdX=    X       .cX X X9XdXBXdXd.t.@XN 2 2.CXBXdXdXdXd 9 IXr GXsX8XdXdXdXdXd _ w C C h h h h h.qXJ.A.A.A.:.: l.(XdXdXdXdXdXwXLXl",
+".bX4XdXdXdXd 5 2Xz.k.0XdXdXdXdXdXB.2.2.w ]XdXdXdXdXd b.p.p.3.3.3.cXdXdXdX=.cXCXCXCXCXCXCXC.3XC.cXdXdXdXdX= >X: I y AXBXdXdXdXd 9 2 ) ).k.9XdXdXdXBXd o n w h h h h.v.L eXJXJ.A.&.: /.=.tXdXdXdXdXB.$.U 6",
+".bX4XdXdXdXBXn 2.V.k _XdXdXdXdXB.(XGXGXV ]XdXdXdXdXdX=.5.5.5.p ; ~XdXdXdX9XC.3XCXCXCXCXC.3.3.3 ~XdXdXdXd 9.lXN I y.CXBXdXdXdXd 9.T & & G.lXBXdXdXdXdXBXpXU.@ h h e.0XBX6X.X.X..8.=XuXiXBXdXdXdXB 9.I [Xl",
+".}.WXdXdXd a.C &X:Xz |XdXdXdXB.( nXGXG.w.xXdXBXdXdXd b.p ].5.p.cXBXdXd v  XC.3XCXCXC.3.3.3.3XC ~XdXdXdXdXBXj G GX7 sXBXdXdXdXd 9.] y &.].C BXdXdXdXdXdXH hXU h.q e.(XdXB.( 9.( 9 9 9XBXdXdXd vXA S [ [Xl",
+" QXBXdXdXdXk * DX:X%.WXBXBXB 9 nXU.EXG.w.5XdXdXdXdXd b ] ].pX>XBXdXdXdX9.pXC.3.3.3.3XC.3.3.3XC ~XdXdXdXdXdXBX%XrXxXiXdXdXdXdXd r.] y & 7X7 K vXdXdXdXd o hXUXJ.q.LXdXdXdXdXdXdXdXdXdXdXdXdXBXwXL.U [ [Xl",
+" kXdXdXdXd.< $.s I IX7 4 GXqXqX:Xq C C.w vXdXdXdXdXd ] ] ].xX3XdXdXdXd ~.3.3.5.3XCXC.3.3.3.p.p.cXBXdXdXdXdXdX: I IXwXdXdXdXdXd , 2 , 2 2.T.=XBXdXdXdXdXB _ hXU.q.LXdXdXdXdXdXdXdXdXdXd v 9.1.m [ [ [ [Xl",
+" Q B a a a.$.+XF ) ) &.sX- )X7X-.#Xf (X<.( vX= vX= v ] ] ] ]X= v v v bXC.3.p.3.3XC.3XC.3XC.3.3XvX9 vX=X=X=.( G I.j.1 B B B B B.T ,XN A GX%.8.( 9.(X= v 9Xj.q.q.q.vX= 9.( 9 r.( B r B r F.FX&., [ [ [ [Xl",
+".} Q Q.`.`XL M $X-X7 7X# LX7 &.#.#XO (.2X<.6._.d.6._ P ] ] ]._X3X X ._.5.5.5.5.p.p.p.p.p.5.5.5.pX<.6 p { K.9 IX7 & F F.K.C.C.CXr ,X%X%.V.kXs.8.8 KX../X..f.q.q.q.lXu.8.8X0 q q ^XmXm.C -XKXK.+ [ [ [ [Xl",
+"Xy 6XD.U [ [ [.P & & 7X#.#X-.#.# LXOXfXG.2XV.w ]XV P.w P.5 ] ].5 ].5.3.p.3.p.5.5.5.p.p.p.5.p ] ] ].2.*.!.@ =X-X- 7.sX# T.s D D & 2 2X:.A.nXs.n.n.n.qXUXs.q.q.A.n.A.A.A.V.VXN , D.F.F * XXK.r.+ [ [ [ [Xl",
+"XyXyXD [ [ [ [.,.# 7X7 &.#.#.#.#.#X: = CXGXGXG.2.2 ].w.w.w :.x.x ].5 ].5 ].5.5.5.5.5.5.5 ] ] ].wXV w.@.@ tX:X- 7 7X# d T TX;.F.# 7 ,XN.n.A.@.n mX@.q.q.q.A.n.kX%X%X%X%X%X% , 4.Q TXIXK.r.r 1 [ [ [ [ [Xl",
+" 6 6XD [ [ [ [ [XFX#X7 &.#.#.#.# LXOXO t C C CXU C.w.wXVXVXV.2 ] ] P ].x ].x :.w ].x.5.5 ].w.wXV C.A t.kXq GX- & 7X; T H d T T 7 D GX%.k t t /.A.n.q.A.V /.VXN , , y ,X%XN ,.].Q *.GXP 1 1.+ [ [ [ [ [Xl",
+".b.bXD [ [ [ [ [ $XFX$X7.#.#X-.#.#X-X$XqXU.* m ( <XV.2XV.w.2XV ].w ].w P ] ]XV.2 P.w.x ] ]XV.2.2 w.kXz.VXOX$ 2X- 7.s.Q.F T d H 7 yXN G.A.V.V.V.V.AX@.kXNXNXNX% 2.T.T 2XNXN 2 &.Z * *.r 1 M M [ [ [ [ [Xl",
+" 6 6XD [ [ [ [ [X5XD.#X$X-X-X-.# LX-X-X$XqXqXf =XfXU.q C.2XGXGXVXV.w P.w ]XVXV.2.w ] ] ].2XV.2XGXUXqX:XqX:X-X-X- 7.s 7 7X;X;X; D y 2X:X:XqX:X:X:X%X%X% G 2 I 2 y y.F y GXN 2 D TXI. .r 1.+ M [ [ [ [ [Xl",
+"XyXy.7 [ [ [ [ [ M.,X# &X7 IX7X7X-X-X-X-X7X7X$X$XO N NXq m C.E.2.2 ].w.w.w.2.2 :.2XV.2.2.2.2.2 C mX$XOXOXOX-.# LX;.#X7 &X# 7 7 7 7X-X$X$ 2X-X- 7 2 2 2 & & y &.F.F.s.F ) ) D.s TXKXK 1.+ M [ [ [ [ [ [Xl",
+" Z 6XD [ [ [ [ [ [ [XlX#X$ I N I IX$X$X$X$X$ IX$X7X7X7X-XO ( mXU C.E.2.2.2.2.E.E.Y.2.Y.Y.EXGXGXU mXqX$XOX$X$X- 7 L 7 7X- &X# 7 7.# 7X-X-.#X; 7 7 7 7 7 7 7 7.s TX;X#.s & & T T. XP.r M M [ [ [ [ [ [ [Xl",
+" Z Z.7 [ [ [ [ [ [ [.PX&X- N N N NXOXOX$X$X$XO IX-X-X7X-X-XzXq ( m.!.! :.2.Y.E.E.E.E.YXGXG C C.q mXqXOXOXOX$ 2X- 7 7 7 7X- L.s 7 L 7 &X- LX; L 7 T.s L.s.sX# TX# d TX;.# 7 T d. .r 1 M M [ [ [ [.U [ [Xl",
+"XyXyXD [ [ [ [ [ [ [., $.}X$ IXSXzXq N N NXOXOXqX$X-X-X-X7X-X-XOXO ( ( #.EXG.E.E.EXG.E.Y # <XU t = IXOX$X$X$X-X7X- &X- 7 L L.s L.# 7 L L L.s 7.sX#X; dX# d d T d T dX#X#X# dXFXP 1X5 M [ [ [ [ [ [ [ [Xl",
+" Z 6.7 [.U [ [ [ [ [ [.+ dX$X$XS = =Xf = = =XzXz NXO N NX$X-X-X-X$X$XOXqXq <.Y.EXG.EXG # C m tXqXOX-X-X-X$X$X$X$X7X- 7 L L LX;X#X# L.#X#X#X#X;X#X& d d d d d d d * TXI dXF. XK 1X5 M [ [ [ [ [ [ [ [ [Xl",
+"XyXyXD [ [ [ [ [ [ [ [ [.X.# &XOXOXz =Xf t t t t =XzXzXqXOXOXOXOX$XOX$XOX$ (XG # # # # C m.@ t ( tXqX$X$X$X-X7X-.# L.#.#.# LX#X#X# L LX; L LX#X# d.b d d d d xXFXF xXK. . XP 1 1 M M [ [ [ [ [ [ [ [ [Xl",
+"XyXyXD [ [ [ [ [ [ [ [ [.U.b.#XOXOXSXz =.n t t t = = =XzXq N N NXO N IX$X$XfXUXU # #.* # m m m.n tXq I IX7X$X7 &.# L.#.# L L LX#X# L L L 7.sX#X#X# dXF.o.o d.oXF x x. XKXKXP 1 1 M [ [ [ [ [ [ [ [ [ [Xl",
+"XyXy.7 [ [ [ [ [ [ [ [ [ [XDXlX7X$ IXSXzXf t =XfXf t t = = = =XzXq N N NXOXz =Xf m mXUXU.@ m mXf =X$.# &X-X7 &X-.# LX-.#.#X#X# L.# 7 LX#X# LX#X# d.b dXF xXF x x x.D.D.DXP 1X5 M [ [ [ [ [ [ [ [ [ [ [Xl",
+"Xy.bXD [ [ [ [ [ [ [ [ [ [ M.7 LX7 N IXOXz =Xf t.n = = = = = = = =XzXzXz NX%X:X:XqXf t m m m tXqXOX-.s.#.#X7X7X7 & &X-X7.# L L 7.# 7.#X#X#.#X#.# d d d. . .  x xXPXK xXP.DX5 M M [ [ [ [ [.U [ [ [ [ [Xl",
+"XyXy.7 [ [ [ [ [ [ [ [ [ [ [.+.}.#X$ IXO = = = =Xf = = = =Xf = = =XzXzXqX:XqX: NXz =.k t t t tXzXOX-.#.#X7X7X7X7X7X7 &.#.#X#.#.s.#.#X#X#X#.# L L d d d. XFXF x x.DXKXPXX.r.+ M [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"Xy ZXD [ [ [ [ [ [ [ [ [ [ [ [XDXyX- & IXSXS NXz =XzXzXz = =XzXqXqXSXq NX: N N I NX: N NXz =Xz N I IX$ I I I I I IX7X-.#X-.#.#.#.#.s L.#.s.#X# LX& d d Z x $ xXPXP.DXXX5X5 M [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6XD [ [ [ [ [ [ [ [ [ [ [ [ [.U Z.bX7 IX7XO NXSXzXSXSXzXSXSXO NXqX: N N I N N N I N I N NXS I N I NXO N I IX7.jX7X7X7X7X7 & &X7.#.#.#.s.#X#X#X& d d x x x xXX.DXX 1 M M [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z Z.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [.X ZX7X-X$ I I N NXqXSXzXq N N NX:Xz N N I N N I I N I I N N I N I N N N IX7X$ )X7X7X7X7X7X7X7X-.#X-.s.#.sX#.bX&.b d x $ $ xXXXXXXX5 M [ [ [ [ [ [ [.U [ [ [ [ [ [ [Xl",
+"XyXyXD [ [ [ [ [ [ [ [ [ [ [ [ [ [.U.X.} &X- IX7 I N I IXS I N I IXS N I N IXO I IX7 I I I I I I I I.j I I I IX7 IX7X7 )X7X7X7X7X7 &.#.#.#.#.sX#X& d d $ x x.DXXXXX5.+ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" ZXy.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.7.bX#X-X- &X7X7 ) I I I I I I I I I IX7X7X-X-X- &X7 IX7 I.j I I ) I ) I I I I ) I ) & &X7X7 & &X-.#.#.s.sX& d *.o x.o.oX5.+.+ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXyXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.7.7.#.#.# & &X7 2 ) I G ) ) ) )X7X7X7X7X-.# &X-X7X$ I I I.j GXrXr G G G ) 2 ) 2.] y y D D D D &.#.#.F.F d d x x x $X5 M M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+".bXyXD [ [ [ [ [ [ [ [ [ [ [ [ [.U [ [ [.+.X.}.#.# & yX7 2 ) ) G G ) ).]X7X7X7X7.#.#X7X7X7 I I I I G G G G GXN , 2 2 2 2 2.T y y 7 y.Q & 7.s.F.F T d x.o $XX.X [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" 6 6XD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.X L.#X- &X7 2 2 2 2 2 )XrX7X7X7X7Xr.j NXO IXOXOXNXN lXoXo 3 f.NXoXo.J.JXhXhXh.RX, y.Q yX;X;X; d dXIXF.D 1 1X5 M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"Xy Z.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U Z.m.m LX7X7 2 2XNXN lXN 2 ,XNXNX%X%X:X% 3 lX+X+X+.^.^.B.^.{.{.{ f fXo.N.JXh.SXhX,X, - - H.GXIXP.r 1 M M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6XD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M M.X d.#.#X-X-XNXNXN lXNXNX% 3 3 3 3.{ 0 0 % %Xc.^.^.^.&.:.&.{.{.{.{ f f.JX,Xh.R.R.R.R HXK x 1X5 M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z ZXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.+XD L.b LX- 2 2 )XN 2 2.JX%.{XNXoX+ 0 %X1X1Xc.^.^.&.&.:.{.{.{ 3 3Xo.NXhXhXZ.S.S.R Y.G.r.r 1.+ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXyXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M.+.P.o Z.b L L.#X- 7 7 2 2 y.TX+ % % %X1.^.&.&.& 3Xo 3XoXo.J.J.N U U.H...S.S.G.G.r.+ M M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"Xy ZXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M M.X 1.P.o.b dX#X#X; y 2Xh f f 0X+ f fX+ f.NXhXhXh.T.SXh.S.S.S Y YXI.o 1X5 M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+".b.bXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U [ [ [ [ [ [ M M.X 1.o.b d dX; 7 7 2XNXoXo f U.H.H.N U.R.R.R.R.R.R.S Y YXI.oX5 M M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [.U [ [ [ [ [ [Xl",
+" Z 6.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M.+.+.P 1.P.o d d LX;X; 7 y.R.R.R.RX; H HXI.GXIXIXI.o.rX5.+ M M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXyXD [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M M M M.+.+.+.X.P.P.P.P.P.P 1.P 1 1 1 1.+.+ M M M M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z Z.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ M M [ M M M M M M M M M [ M [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+" Z 6.7 [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [Xl",
+"XyXyXl.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U.U [Xl",
+" Z ZXy.b.bXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXy.bXy.bXy.bXy.bXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXyXy.b L"
+};
Index: /tags/Mars-V0.9/mastro/AstroIncl.h
===================================================================
--- /tags/Mars-V0.9/mastro/AstroIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mastro/AstroIncl.h	(revision 9772)
@@ -0,0 +1,7 @@
+#ifndef __CINT__
+
+#include <TArrayC.h>
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mastro/AstroLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mastro/AstroLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mastro/AstroLinkDef.h	(revision 9772)
@@ -0,0 +1,16 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MVector3+;
+
+#pragma link C++ class MAstro+;
+#pragma link C++ class MAstroSky2Local+;
+#pragma link C++ class MAstroCatalog+;
+#pragma link C++ class MAstroCamera+;
+
+#pragma link C++ class MObservatory+;
+
+#endif
Index: /tags/Mars-V0.9/mastro/MAstro.cc
===================================================================
--- /tags/Mars-V0.9/mastro/MAstro.cc	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MAstro.cc	(revision 9772)
@@ -0,0 +1,579 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MAstro
+// ------
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MAstro.h"
+
+#include <iostream>
+
+#include <TVector3.h> // TVector3
+
+#include "MTime.h"    // MTime::GetGmst
+
+#include "MAstroCatalog.h" // FIXME: replace by MVector3!
+
+using namespace std;
+
+ClassImp(MAstro);
+
+Double_t MAstro::Trunc(Double_t val)
+{
+    // dint(A) - truncate to nearest whole number towards zero (double)
+    return val<0 ? TMath::Ceil(val) : TMath::Floor(val);
+}
+
+Double_t MAstro::Round(Double_t val)
+{
+    // dnint(A) - round to nearest whole number (double)
+    return val<0 ? TMath::Ceil(val-0.5) : TMath::Floor(val+0.5);
+}
+
+Double_t MAstro::Hms2Sec(Int_t deg, UInt_t min, Double_t sec, Char_t sgn)
+{
+    const Double_t rc = TMath::Sign((60.0 * (60.0 * (Double_t)TMath::Abs(deg) + (Double_t)min) + sec), (Double_t)deg);
+    return sgn=='-' ? -rc : rc;
+}
+
+Double_t MAstro::Dms2Rad(Int_t deg, UInt_t min, Double_t sec, Char_t sgn)
+{
+    // pi/(180*3600):  arcseconds to radians
+    //#define DAS2R 4.8481368110953599358991410235794797595635330237270e-6
+    return Hms2Sec(deg, min, sec, sgn)*TMath::Pi()/(180*3600)/**DAS2R*/;
+}
+
+Double_t MAstro::Hms2Rad(Int_t hor, UInt_t min, Double_t sec, Char_t sgn)
+{
+    // pi/(12*3600):  seconds of time to radians
+//#define DS2R 7.2722052166430399038487115353692196393452995355905e-5
+    return Hms2Sec(hor, min, sec, sgn)*TMath::Pi()/(12*3600)/**DS2R*/;
+}
+
+Double_t MAstro::Dms2Deg(Int_t deg, UInt_t min, Double_t sec, Char_t sgn)
+{
+    return Hms2Sec(deg, min, sec, sgn)/3600.;
+}
+
+Double_t MAstro::Hms2Deg(Int_t hor, UInt_t min, Double_t sec, Char_t sgn)
+{
+    return Hms2Sec(hor, min, sec, sgn)/240.;
+}
+
+Double_t MAstro::Dms2Hor(Int_t deg, UInt_t min, Double_t sec, Char_t sgn)
+{
+    return Hms2Sec(deg, min, sec, sgn)/54000.;
+}
+
+Double_t MAstro::Hms2Hor(Int_t hor, UInt_t min, Double_t sec, Char_t sgn)
+{
+    return Hms2Sec(hor, min, sec, sgn)/3600.;
+}
+
+void MAstro::Day2Hms(Double_t day, Char_t &sgn, UShort_t &hor, UShort_t &min, UShort_t &sec)
+{
+    /* Handle sign */
+    sgn = day<0?'-':'+';
+
+    /* Round interval and express in smallest units required */
+    Double_t a = Round(86400. * TMath::Abs(day)); // Days to seconds
+
+    /* Separate into fields */
+    const Double_t ah = Trunc(a/3600.);
+    a -= ah * 3600.;
+    const Double_t am = Trunc(a/60.);
+    a -= am * 60.;
+    const Double_t as = Trunc(a);
+
+    /* Return results */
+    hor = (UShort_t)ah;
+    min = (UShort_t)am;
+    sec = (UShort_t)as;
+}
+
+void MAstro::Rad2Hms(Double_t rad, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec)
+{
+    Day2Hms(rad/(TMath::Pi()*2), sgn, deg, min, sec);
+}
+
+void MAstro::Rad2Dms(Double_t rad, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec)
+{
+    Rad2Hms(rad*15, sgn, deg, min, sec);
+}
+
+void MAstro::Deg2Dms(Double_t d, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec)
+{
+    Day2Hms(d/24, sgn, deg, min, sec);
+}
+
+void MAstro::Deg2Hms(Double_t d, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec)
+{
+    Rad2Hms(d/360, sgn, deg, min, sec);
+}
+
+void MAstro::Hor2Dms(Double_t h, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec)
+{
+    Day2Hms(h*15/24, sgn, deg, min, sec);
+}
+
+void MAstro::Hor2Hms(Double_t h, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec)
+{
+    Day2Hms(h/24, sgn, deg, min, sec);
+}
+
+void MAstro::Day2Hm(Double_t day, Char_t &sgn, UShort_t &hor, Double_t &min)
+{
+    /* Handle sign */
+    sgn = day<0?'-':'+';
+
+    /* Round interval and express in smallest units required */
+    Double_t a = Round(86400. * TMath::Abs(day)); // Days to seconds
+
+    /* Separate into fields */
+    const Double_t ah = Trunc(a/3600.);
+    a -= ah * 3600.;
+
+    /* Return results */
+    hor = (UShort_t)ah;
+    min = a/60.;
+}
+
+void MAstro::Rad2Hm(Double_t rad, Char_t &sgn, UShort_t &deg, Double_t &min)
+{
+    Day2Hm(rad/(TMath::Pi()*2), sgn, deg, min);
+}
+
+void MAstro::Rad2Dm(Double_t rad, Char_t &sgn, UShort_t &deg, Double_t &min)
+{
+    Rad2Hm(rad*15, sgn, deg, min);
+}
+
+void MAstro::Deg2Dm(Double_t d, Char_t &sgn, UShort_t &deg, Double_t &min)
+{
+    Day2Hm(d/24, sgn, deg, min);
+}
+
+void MAstro::Deg2Hm(Double_t d, Char_t &sgn, UShort_t &deg, Double_t &min)
+{
+    Rad2Hm(d/360, sgn, deg, min);
+}
+
+void MAstro::Hor2Dm(Double_t h, Char_t &sgn, UShort_t &deg, Double_t &min)
+{
+    Day2Hm(h*15/24, sgn, deg, min);
+}
+
+void MAstro::Hor2Hm(Double_t h, Char_t &sgn, UShort_t &deg, Double_t &min)
+{
+    Day2Hm(h/24, sgn, deg, min);
+}
+
+// --------------------------------------------------------------------------
+//
+// Interpretes a string ' - 12 30 00.0' or '+ 12 30 00.0'
+// as floating point value -12.5 or 12.5. If interpretation is
+// successfull kTRUE is returned, otherwise kFALSE. ret is not
+// touched if interpretation was not successfull. The successfull
+// interpreted part is removed from the TString.
+//
+Bool_t MAstro::String2Angle(TString &str, Double_t &ret)
+{
+    Char_t  sgn;
+    Int_t   d, len;
+    UInt_t  m;
+    Float_t s;
+
+    // Skip whitespaces before %c and after %f
+    int n=sscanf(str.Data(), " %c %d %d %f %n", &sgn, &d, &m, &s, &len);
+
+    if (n!=4 || (sgn!='+' && sgn!='-'))
+        return kFALSE;
+
+    str.Remove(0, len);
+
+    ret = Dms2Deg(d, m, s, sgn);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interpretes a string '-12:30:00.0', '12:30:00.0' or '+12:30:00.0'
+// as floating point value -12.5, 12.5 or 12.5. If interpretation is
+// successfull kTRUE is returned, otherwise kFALSE. ret is not
+// touched if interpretation was not successfull.
+//
+Bool_t MAstro::Coordinate2Angle(const TString &str, Double_t &ret)
+{
+    Char_t  sgn = str[0]=='-' ? '-' : '+';
+    Int_t   d;
+    UInt_t  m;
+    Float_t s;
+
+    const int n=sscanf(str[0]=='+'||str[0]=='-' ? str.Data()+1 : str.Data(), "%d:%d:%f", &d, &m, &s);
+
+    if (n!=3)
+        return kFALSE;
+
+    ret = Dms2Deg(d, m, s, sgn);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns val=-12.5 as string '-12:30:00'
+//
+TString MAstro::Angle2Coordinate(Double_t val)
+{
+    Char_t  sgn;
+    UShort_t d,m,s;
+
+    Deg2Dms(val, sgn, d, m, s);
+
+    return Form("%c%02d:%02d:%02d", sgn, d, m, s);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return year y, month m and day d corresponding to Mjd.
+//
+void MAstro::Mjd2Ymd(UInt_t mjd, UShort_t &y, Byte_t &m, Byte_t &d)
+{
+    // Express day in Gregorian calendar
+    const ULong_t jd   = mjd + 2400001;
+    const ULong_t n4   = 4*(jd+((6*((4*jd-17918)/146097))/4+1)/2-37);
+    const ULong_t nd10 = 10*(((n4-237)%1461)/4)+5;
+
+    y = n4/1461L-4712;
+    m = ((nd10/306+2)%12)+1;
+    d = (nd10%306)/10+1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return Mjd corresponding to year y, month m and day d.
+//
+Int_t MAstro::Ymd2Mjd(UShort_t y, Byte_t m, Byte_t d)
+{
+    // Month lengths in days
+    static int months[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
+
+    // Validate month
+    if (m<1 || m>12)
+        return -1;
+
+    // Allow for leap year
+    months[1] = (y%4==0 && (y%100!=0 || y%400==0)) ? 29 : 28;
+
+    // Validate day
+    if (d<1 || d>months[m-1])
+        return -1;
+
+    // Precalculate some values
+    const Byte_t  lm = 12-m;
+    const ULong_t lm10 = 4712 + y - lm/10;
+
+    // Perform the conversion
+    return 1461L*lm10/4 + (306*((m+9)%12)+5)/10 - (3*((lm10+188)/100))/4 + d - 2399904;
+}
+
+// --------------------------------------------------------------------------
+//
+//  theta0, phi0    [rad]: polar angle/zenith distance, azimuth of 1st object
+//  theta1, phi1    [rad]: polar angle/zenith distance, azimuth of 2nd object
+//  AngularDistance [rad]: Angular distance between two objects
+//
+Double_t MAstro::AngularDistance(Double_t theta0, Double_t phi0, Double_t theta1, Double_t phi1)
+{
+    TVector3 v0(1);
+    v0.Rotate(phi0, theta0);
+
+    TVector3 v1(1);
+    v1.Rotate(phi1, theta1);
+
+    return v0.Angle(v1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MTime::GetGmst() Better use MTime::GetGmst() directly
+//
+Double_t MAstro::UT2GMST(Double_t ut1)
+{
+    return MTime(ut1).GetGmst();
+}
+
+// --------------------------------------------------------------------------
+//
+// RotationAngle 
+// 
+// calculates the angle for the rotation of the sky coordinate system
+// with respect to the local coordinate system. This is identical
+// to the rotation angle of the sky image in the camera.
+//
+//  sinl  [rad]: sine of observers latitude
+//  cosl  [rad]: cosine of observers latitude
+//  theta [rad]: polar angle/zenith distance
+//  phi   [rad]: rotation angle/azimuth
+//
+// Return sin/cos component of angle
+//
+// The convention is such, that the rotation angle is -pi/pi if
+// right ascension and local rotation angle are counted in the
+// same direction, 0 if counted in the opposite direction.
+//
+// (In other words: The rotation angle is 0 when the source culminates)
+//
+// Using vectors it can be done like:
+//    TVector3 v, p;
+//    v.SetMagThetaPhi(1, theta, phi);
+//    p.SetMagThetaPhi(1, TMath::Pi()/2-latitude, 0);
+//    v = v.Cross(l)); 
+//    v.RotateZ(-phi);
+//    v.Rotate(-theta)
+//    rho = TMath::ATan2(v(2), v(1));
+//
+// For more information see TDAS 00-11, eqs. (18) and (20)
+//
+void MAstro::RotationAngle(Double_t sinl, Double_t cosl, Double_t theta, Double_t phi, Double_t &sin, Double_t &cos)
+{
+    const Double_t sint = TMath::Sin(theta);
+    const Double_t cost = TMath::Cos(theta);
+
+    const Double_t snlt = sinl*sint;
+    const Double_t cslt = cosl*cost;
+
+    const Double_t sinp = TMath::Sin(phi);
+    const Double_t cosp = TMath::Cos(phi);
+
+    const Double_t v1 = sint*sinp;
+    const Double_t v2 = cslt - snlt*cosp;
+
+    const Double_t denom = TMath::Sqrt(v1*v1 + v2*v2);
+
+    sin =   cosl*sinp      / denom; // y-component
+    cos = (snlt-cslt*cosp) / denom; // x-component
+}
+
+// --------------------------------------------------------------------------
+//
+// RotationAngle 
+// 
+// calculates the angle for the rotation of the sky coordinate system
+// with respect to the local coordinate system. This is identical
+// to the rotation angle of the sky image in the camera.
+//
+//  sinl  [rad]: sine of observers latitude
+//  cosl  [rad]: cosine of observers latitude
+//  theta [rad]: polar angle/zenith distance
+//  phi   [rad]: rotation angle/azimuth
+//
+// Return angle [rad] in the range -pi, pi
+//
+// The convention is such, that the rotation angle is -pi/pi if
+// right ascension and local rotation angle are counted in the
+// same direction, 0 if counted in the opposite direction.
+//
+// (In other words: The rotation angle is 0 when the source culminates)
+//
+// Using vectors it can be done like:
+//    TVector3 v, p;
+//    v.SetMagThetaPhi(1, theta, phi);
+//    p.SetMagThetaPhi(1, TMath::Pi()/2-latitude, 0);
+//    v = v.Cross(l)); 
+//    v.RotateZ(-phi);
+//    v.Rotate(-theta)
+//    rho = TMath::ATan2(v(2), v(1));
+//
+// For more information see TDAS 00-11, eqs. (18) and (20)
+//
+Double_t MAstro::RotationAngle(Double_t sinl, Double_t cosl, Double_t theta, Double_t phi)
+{
+    const Double_t snlt = sinl*TMath::Sin(theta);
+    const Double_t cslt = cosl*TMath::Cos(theta);
+
+    const Double_t sinp = TMath::Sin(phi);
+    const Double_t cosp = TMath::Cos(phi);
+
+    return TMath::ATan2(cosl*sinp, snlt-cslt*cosp);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Kepler - solve the equation of Kepler
+//
+Double_t MAstro::Kepler(Double_t m, Double_t ecc)
+{
+    m *= TMath::DegToRad();
+
+    Double_t delta = 0;
+    Double_t e = m;
+    do {
+        delta = e - ecc * sin(e) - m;
+        e -= delta / (1 - ecc * cos(e));
+    } while (fabs(delta) > 1e-6);
+
+    return e;
+}
+
+// --------------------------------------------------------------------------
+//
+// GetMoonPhase - calculate phase of moon as a fraction:
+//  Returns -1 if calculation failed
+//
+Double_t MAstro::GetMoonPhase(Double_t mjd)
+{
+    /****** Calculation of the Sun's position. ******/
+
+    // date within epoch
+    const Double_t epoch = 44238;       // 1980 January 0.0
+    const Double_t day = mjd - epoch;
+    if (day<0)
+    {
+        cout << "MAstro::GetMoonPhase - Day before Jan 1980" << endl;
+        return -1;
+    }
+
+    // mean anomaly of the Sun
+    const Double_t n = fmod(day*360/365.2422, 360);
+
+    const Double_t elonge = 278.833540; // ecliptic longitude of the Sun at epoch 1980.0
+    const Double_t elongp = 282.596403; // ecliptic longitude of the Sun at perigee
+
+    // convert from perigee co-ordinates to epoch 1980.0
+    const Double_t m = fmod(n + elonge - elongp + 360, 360);
+
+    // solve equation of Kepler
+    const Double_t eccent = 0.016718; // eccentricity of Earth's orbit
+    const Double_t k   = Kepler(m, eccent);
+    const Double_t ec0 = sqrt((1 + eccent) / (1 - eccent)) * tan(k / 2);
+    // true anomaly
+    const Double_t ec  = 2 * atan(ec0) * TMath::RadToDeg();
+
+    // Sun's geocentric ecliptic longitude
+    const Double_t lambdasun = fmod(ec + elongp + 720, 360);
+
+
+    /****** Calculation of the Moon's position. ******/
+
+    // Moon's mean longitude.
+    const Double_t mmlong  = 64.975464;  // moon's mean lonigitude at the epoch
+    const Double_t ml      = fmod(13.1763966*day + mmlong + 360, 360);
+    // Moon's mean anomaly.
+    const Double_t mmlongp = 349.383063; // mean longitude of the perigee at the epoch
+    const Double_t mm      = fmod(ml - 0.1114041*day - mmlongp + 720, 360);
+    // Evection.
+    const Double_t ev   = 1.2739 * sin((2 * (ml - lambdasun) - mm)*TMath::DegToRad());
+    // Annual equation.
+    const Double_t sinm = TMath::Sin(m*TMath::DegToRad());
+    const Double_t ae   = 0.1858 * sinm;
+    // Correction term.
+    const Double_t a3   = 0.37 * sinm;
+    // Corrected anomaly.
+    const Double_t mmp  = (mm + ev - ae - a3)*TMath::DegToRad();
+    // Correction for the equation of the centre.
+    const Double_t mec  = 6.2886 * sin(mmp);
+    // Another correction term.
+    const Double_t a4   = 0.214 * sin(2 * mmp);
+    // Corrected longitude.
+    const Double_t lp   = ml + ev + mec - ae + a4;
+    // Variation.
+    const Double_t v    = 0.6583 * sin(2 * (lp - lambdasun)*TMath::DegToRad());
+    // True longitude.
+    const Double_t lpp  = lp + v;
+    // Age of the Moon in degrees.
+    const Double_t age  = (lpp - lambdasun)*TMath::DegToRad();
+
+    // Calculation of the phase of the Moon.
+    return (1 - TMath::Cos(age)) / 2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the Period to which the time belongs to. The Period is defined
+// as the number of synodic months ellapsed since the first full moon
+// after Jan 1st 1980 (which was @ MJD=44240.37917)
+//
+Double_t MAstro::GetMoonPeriod(Double_t mjd)
+{
+    const Double_t synmonth = 29.53058868; // synodic month (new Moon to new Moon)
+    const Double_t epoch0   = 44240.37917; // First full moon after 1980/1/1
+
+    const Double_t et = mjd-epoch0; // Ellapsed time
+    return et/synmonth;
+}
+
+// --------------------------------------------------------------------------
+//
+// To get the moon period as defined for MAGIC observation we take the
+// nearest integer mjd, eg:
+//   53257.8 --> 53258
+//   53258.3 --> 53258
+// Which is the time between 13h and 12:59h of the following day. To
+// this day-period we assign the moon-period at midnight. To get
+// the MAGIC definition we now substract 284.
+//
+// For MAGIC observation period do eg:
+//   GetMagicPeriod(53257.91042)
+// or
+//   MTime t;
+//   t.SetMjd(53257.91042);
+//   GetMagicPeriod(t.GetMjd());
+// or
+//   MTime t;
+//   t.Set(2004, 1, 1, 12, 32, 11);
+//   GetMagicPeriod(t.GetMjd());
+//
+Int_t MAstro::GetMagicPeriod(Double_t mjd)
+{
+    const Double_t mmjd   = (Double_t)TMath::Nint(mjd);
+    const Double_t period = GetMoonPeriod(mmjd);
+
+    return (Int_t)TMath::Floor(period)-284;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the distance in x,y between two polar-vectors (eg. Alt/Az, Ra/Dec)
+// projected on aplain in a distance dist. For Magic this this the distance
+// of the camera plain (1700mm) dist also determins the unit in which
+// the TVector2 is returned.
+//
+// v0 is the reference vector (eg. the vector to the center of the camera)
+// v1 is the vector to which we determin the distance on the plain
+//
+//  (see also MStarCamTrans::Loc0LocToCam())
+//
+TVector2 MAstro::GetDistOnPlain(const TVector3 &v0, TVector3 v1, Double_t dist)
+{
+    v1.RotateZ(-v0.Phi());
+    v1.RotateY(-v0.Theta());
+    v1.RotateZ(-TMath::Pi()/2); // exchange x and y
+    v1 *= dist/v1.Z();
+
+    return v1.XYvector(); //TVector2(v1.Y(), -v1.X());//v1.XYvector();
+}
Index: /tags/Mars-V0.9/mastro/MAstro.h
===================================================================
--- /tags/Mars-V0.9/mastro/MAstro.h	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MAstro.h	(revision 9772)
@@ -0,0 +1,73 @@
+#ifndef MARS_MAstro
+#define MARS_MAstro
+
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+class TVector3;
+
+class MAstro
+{
+private:
+    static Double_t Round(Double_t val);
+    static Double_t Trunc(Double_t val);
+
+    static Double_t Kepler(Double_t m, Double_t ecc);
+
+public:
+    // Angle/Time conversion functions
+    static Double_t Hms2Sec(Int_t deg, UInt_t min, Double_t sec, char sgn='+');
+    static Double_t Dms2Rad(Int_t deg, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Hms2Rad(Int_t hor, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Dms2Deg(Int_t deg, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Hms2Deg(Int_t hor, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Dms2Hor(Int_t deg, UInt_t min, Double_t sec, Char_t sgn='+');
+    static Double_t Hms2Hor(Int_t hor, UInt_t min, Double_t sec, Char_t sgn='+');
+
+    static void Day2Hms(Double_t day, Char_t &sgn, UShort_t &hor, UShort_t &min, UShort_t &sec);
+    static void Rad2Dms(Double_t rad, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec);
+    static void Rad2Hms(Double_t rad, Char_t &sgn, UShort_t &hor, UShort_t &min, UShort_t &sec);
+    static void Deg2Dms(Double_t deg, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec);
+    static void Deg2Hms(Double_t deg, Char_t &sgn, UShort_t &hor, UShort_t &min, UShort_t &sec);
+    static void Hor2Dms(Double_t hor, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec);
+    static void Hor2Hms(Double_t hor, Char_t &sgn, UShort_t &hor, UShort_t &min, UShort_t &sec);
+
+    static void Day2Hm(Double_t day, Char_t &sgn, UShort_t &hor, Double_t &min);
+    static void Rad2Dm(Double_t rad, Char_t &sgn, UShort_t &deg, Double_t &min);
+    static void Rad2Hm(Double_t rad, Char_t &sgn, UShort_t &hor, Double_t &min);
+    static void Deg2Dm(Double_t deg, Char_t &sgn, UShort_t &deg, Double_t &min);
+    static void Deg2Hm(Double_t deg, Char_t &sgn, UShort_t &hor, Double_t &min);
+    static void Hor2Dm(Double_t rad, Char_t &sgn, UShort_t &deg, Double_t &min);
+    static void Hor2Hm(Double_t rad, Char_t &sgn, UShort_t &hor, Double_t &min);
+
+    // Angle treatment functions
+    static Bool_t  String2Angle(TString &str, Double_t &ret);
+    static Bool_t  Coordinate2Angle(const TString &str, Double_t &ret);
+    static TString Angle2Coordinate(Double_t val);
+
+    static Double_t AngularDistance(Double_t theta0, Double_t phi0, Double_t theta1, Double_t phi1);
+
+    // Time treatment functions
+    static void  Mjd2Ymd(UInt_t mjd, UShort_t &y, Byte_t &m, Byte_t &d);
+    static Int_t Ymd2Mjd(UShort_t y, Byte_t m, Byte_t d);
+
+    static Double_t UT2GMST(Double_t ut1);
+
+    // Rotation angle between local and sky coordinate system
+    static void     RotationAngle(Double_t sinl, Double_t cosl, Double_t theta, Double_t phi, Double_t &sin, Double_t &cos);
+    static Double_t RotationAngle(Double_t sinl, Double_t cosl, Double_t theta, Double_t phi);
+
+    static Double_t GetMoonPhase(Double_t mjd);
+    static Double_t GetMoonPeriod(Double_t mjd);
+    static Int_t    GetMagicPeriod(Double_t mjd);
+
+    static TVector2 GetDistOnPlain(const TVector3 &v0, TVector3 v1, Double_t dist=1);
+
+    ClassDef(MAstro, 0)
+};
+
+#endif
Index: /tags/Mars-V0.9/mastro/MAstroCamera.cc
===================================================================
--- /tags/Mars-V0.9/mastro/MAstroCamera.cc	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MAstroCamera.cc	(revision 9772)
@@ -0,0 +1,566 @@
+/*====================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Robert Wagner, 7/2004 <mailto:rwagner@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MAstroCamera
+// ============
+//
+// A tools displaying stars from a catalog in the camera display.
+// PRELIMINARY!!
+//
+//
+// Usage:
+// ------
+// For a usage example see macros/starfield.C
+//
+// To be able to reflect the star-light you need the geometry of the
+// mirror and the distance of the plain screen.
+//
+// You can get the mirror geometry from a MC file and the distance of
+// the screen from MGeomCam.
+//
+//
+// Algorithm:
+// ----------
+// The calculation of the position of the reflection in the camera is
+// done by:
+//   - Rotation of the star-field such that the camera is looking into
+//     the pointing direction
+//   - Calculation of the reflected star-light vector by calling
+//     MGeomMirror::GetReflection (which returns the point at which
+//     the vector hits the camera plain)
+//   - Depending on the draw-option you get each reflected point, the
+//     reflection on a virtual ideal mirror or the reflection on each
+//     individual mirror
+//
+//
+// GUI:
+// ----
+//  * You can use the the cursor keys to change the pointing position
+//    and plus/minus to change the time by a quarter of an hour.
+//
+// ToDo:
+// -----
+//  * possibility to overwrite distance from mirror to screen
+//  * read the mirror geometry directly from the MC input file
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MAstroCamera.h"
+
+#include <errno.h>        // strerror
+#include <fstream>        // ifstream
+
+#include <KeySymbols.h>   // kKey_*
+
+#include <TH2.h>          // TH2D
+#include <TMarker.h>      // TMarker
+#include <TVirtualPad.h>  // gPad
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomMirror.h"
+
+#include "MTime.h"
+#include "MAstroSky2Local.h"
+#include "MObservatory.h"
+
+#include "../mhist/MHCamera.h" // FIXME: This dependancy is very bad!
+                      // HOW TO GET RID OF IT? Move MHCamera to mgeom?
+
+#include "MStarPos.h"
+
+ClassImp(MAstroCamera);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Create a virtual MGeomMirror which is in the center of the coordinate
+// system and has a normal vector in z-direction.
+//
+MAstroCamera::MAstroCamera() : fGeom(0), fMirrors(0)
+{
+    fMirror0 = new MGeomMirror;
+    fMirror0->SetMirrorContent(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fGeom, fMirrors and the virtual 0-Mirror fMirror0
+//
+MAstroCamera::~MAstroCamera()
+{
+    if (fGeom)
+        delete fGeom;
+    if (fMirrors)
+        delete fMirrors;
+
+    delete fMirror0;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a list of mirrors. The Mirrors must be of type MGeomMirror and
+// stored in a TClonesArray
+//
+void MAstroCamera::SetMirrors(TClonesArray &arr)
+{
+    if (arr.GetClass()!=MGeomMirror::Class())
+    {
+      cout << "ERROR - TClonesArray doesn't contain objects of type MGeomMirror... ignored." << endl;
+      return;
+    }
+
+    const Int_t n = arr.GetSize();
+
+    if (!fMirrors)
+        fMirrors = new TClonesArray(MGeomMirror::Class(), n);
+
+    fMirrors->ExpandCreate(n);
+
+    for (int i=0; i<n; i++)
+        memcpy((*fMirrors)[i], arr[i], sizeof(MGeomMirror));
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Read the mirror geometry from a MC .def file. The following
+// structure is expected:
+//
+// #*  TYPE=1  (MAGIC)
+// #*      i  f   sx   sy   x   y   z   thetan  phin 
+// #* 
+// #*       i : number of the mirror
+// #*       f : focal distance of that mirror
+// #*      sx : curvilinear coordinate of mirror's center in X[cm]
+// #*      sy : curvilinear coordinate of mirror's center in X[cm]
+// #*       x : x coordinate of the center of the mirror [cm]
+// #*       y : y coordinate of the center of the mirror [cm]
+// #*       z : z coordinate of the center of the mirror [cm]
+// #*  thetan : polar theta angle of the direction where the mirror points to
+// #*    phin : polar phi angle of the direction where the mirror points to
+// #*      xn : xn coordinate of the normal vector in the center (normalized)
+// #*      yn : yn coordinate of the normal vector in the center (normalized)
+// #*      zn : zn coordinate of the normal vector in the center (normalized)
+// #
+// define_mirrors
+//   1 1700.9200   25.0002   75.0061   25.0000   75.0000    0.9207 0.02328894 1.24904577 -0.00736394 -0.02209183 0.99972882
+//   2 ...
+//
+void MAstroCamera::SetMirrors(const char *fname)
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        gLog << err << "Cannot open file " << fname << ": ";
+        gLog << strerror(errno) << endl;
+        return;
+    }
+
+    TString line;
+    while (1)
+    {
+        line.ReadLine(fin);
+        if (!fin)
+            return;
+
+        line = line.Strip(TString::kBoth);
+
+        if (line.BeginsWith("n_mirrors"))
+        {
+            Int_t n;
+            sscanf(line.Data(), "%*s %d", &n);
+
+            if (!fMirrors)
+                fMirrors = new TClonesArray(MGeomMirror::Class(), n);
+
+            fMirrors->ExpandCreate(n);
+            continue;
+        }
+
+
+        Int_t id;
+        Float_t f, sx, sy, x, y, z, thetan, phin, xn, yn, zn;
+
+        const Int_t n = sscanf(line.Data(), "%d %f %f %f %f %f %f %f %f %f %f %f",
+                               &id, &f, &sx, &sy, &x, &y, &z, &thetan,
+                               &phin, &xn, &yn, &zn);
+        if (n!=12)
+            continue;
+
+        new ((*fMirrors)[id-1]) MGeomMirror;
+        ((MGeomMirror*)(*fMirrors)[id-1])->SetMirrorContent(id, f, sx, sy, x, y, z, thetan, phin, xn, yn, zn);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the camera geometry. The MGeomCam object is cloned.
+//
+void MAstroCamera::SetGeom(const MGeomCam &cam)
+{
+    if (fGeom)
+        delete fGeom;
+
+    fGeom = (MGeomCam*)cam.Clone();
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert To Pad coordinates (see MAstroCatalog)
+//
+Int_t MAstroCamera::ConvertToPad(const TVector3 &w, TVector2 &v) const
+{
+    /*
+     --- Use this to plot the 'mean grid' instead of the grid of a
+         theoretical central mirror ---
+
+        TVector3 spot;
+        const Int_t num = fConfig->GetNumMirror();
+        for (int i=0; i<num; i++)
+        spot += fConfig->GetMirror(i).GetReflection(w, fGeom->GetCameraDist())*1000;
+        spot *= 1./num;
+        */
+
+    const TVector3 spot = fMirror0->GetReflection(w, fGeom->GetCameraDist())*1000;
+    v.Set(spot(0), spot(1));
+
+    const Float_t max = fGeom->GetMaxRadius()*0.70;
+    return v.X()>-max && v.Y()>-max && v.X()<max && v.Y()<max;
+}
+
+// --------------------------------------------------------------------------
+//
+// Find an object with a given name in the list of primitives of this pad.
+//
+TObject *FindObjectInPad(const char *name, TVirtualPad *pad)
+{
+    if (!pad)
+        pad = gPad;
+
+    if (!pad)
+        return NULL;
+
+    TObject *o;
+
+    TIter Next(pad->GetListOfPrimitives());
+    while ((o=Next()))
+    {
+        if (o->InheritsFrom(gROOT->GetClass(name)))
+            return o;
+
+        if (o->InheritsFrom("TPad"))
+            if ((o = FindObjectInPad(name, (TVirtualPad*)o)))
+                return o;
+    }
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Options:
+//
+//  '*' Draw the mean of the reflections on all mirrors
+//  '.' Draw a dot for the reflection on each individual mirror
+//  'h' To create a TH2D of the star-light which is displayed
+//  'c' Use the underlaying MHCamera as histogram
+//  '0' Draw the reflection on a virtual perfect mirror
+//  '=' Draw '0' or '*' propotional to the star magnitude
+//
+// If the Pad contains an object MHCamera of type MHCamera it is used.
+// Otherwise a new object is created.
+//
+// FIXME: Add Project functionand change treating MHCamera and
+//        TH2D accordingly
+//
+void MAstroCamera::AddPrimitives(TString o)
+{
+    if (!fTime || !fObservatory || !fMirrors)
+    {
+      cout << "Missing data..." << endl;
+        return;
+    }
+
+    if (o.IsNull())
+        o = "*.";
+
+    const Bool_t hasnull = o.Contains("0", TString::kIgnoreCase);
+    const Bool_t hashist = o.Contains("h", TString::kIgnoreCase);
+    const Bool_t hasmean = o.Contains("*", TString::kIgnoreCase);
+    const Bool_t hasdot  = o.Contains(".", TString::kIgnoreCase);
+    const Bool_t usecam  = o.Contains("c", TString::kIgnoreCase);
+    const Bool_t resize  = o.Contains("=", TString::kIgnoreCase);
+
+    // Get camera
+    MHCamera *camera=(MHCamera*)FindObjectInPad("MHCamera", gPad);
+    if (camera)
+    {
+        if (!camera->GetGeometry() || camera->GetGeometry()->IsA()!=fGeom->IsA())
+            camera->SetGeometry(*fGeom);
+    }
+    else
+    {
+        camera = new MHCamera(*fGeom);
+        camera->SetName("MHCamera");
+        camera->SetStats(0);
+        camera->SetInvDeepBlueSeaPalette();
+        camera->SetBit(kCanDelete);
+        camera->Draw();
+    }
+
+    camera->SetTitle(GetPadTitle());
+
+    gPad->cd(1);
+
+    if (!usecam)
+    {
+        if (camera->GetEntries()==0)
+            camera->SetBit(MHCamera::kNoLegend);
+    }
+    else
+    {
+        camera->Reset();
+        camera->SetYTitle("arb.cur");
+    }
+
+    TH2 *h=0;
+    if (hashist)
+    {
+        TH2F hist("","", 90, -650, 650, 90, -650, 650);
+        hist.SetMinimum(0);
+        h = (TH2*)hist.DrawCopy("samecont1");
+    }
+
+    const TRotation rot(GetGrid(kTRUE));
+
+    MVector3 *radec;
+    TIter Next(&fList);
+
+    while ((radec=(MVector3*)Next()))
+    {
+        const Double_t mag = radec->Magnitude();
+        if (mag>GetLimMag())
+            continue;
+
+        TVector3 star(*radec);
+
+        // Rotate Star into telescope system
+        star *= rot;
+
+        TVector3 mean;
+
+        Int_t num = 0;
+
+        MGeomMirror *mirror = 0;
+        TIter NextM(fMirrors);
+        while ((mirror=(MGeomMirror*)NextM()))
+        {
+  	    const TVector3 spot = mirror->GetReflection(star, fGeom->GetCameraDist())*1000;
+            
+            // calculate mean of all 'stars' hitting the camera plane
+            // by taking the sum of the intersection points between
+            // the light vector and the camera plane
+            mean += spot;
+
+            if (hasdot)
+            {
+                TMarker *m=new TMarker(spot(0), spot(1), 1);
+                m->SetMarkerColor((Int_t)(6*mirror->GetMirrorCenter().Mag())+51);
+                m->SetMarkerStyle(kDot);
+                fMapG.Add(m);
+            }
+            if (h)
+                h->Fill(spot(0), spot(1), pow(10, -mag/2.5));
+
+            if (usecam)
+                camera->Fill(spot(0), spot(1), pow(10, -mag/2.5));
+
+            num++;
+        }
+
+        // transform meters into millimeters (camera display works with mm)
+        mean *= 1./num;
+        DrawStar(mean(0), mean(1), *radec, hasmean?kBlack:-1, Form("x=%.1fmm y=%.1fmm", mean(0), mean(1)), resize);
+        if (hasnull)
+        {
+            TVector3 star(*radec);
+            star *= rot;
+            const TVector3 spot = fMirror0->GetReflection(star, fGeom->GetCameraDist())*1000;
+            DrawStar(spot(0), spot(1), *radec, hasmean?kBlack:-1, Form("x=%.1fmm y=%.1fmm", mean(0), mean(1)), resize);
+            // This can be used to get the abberation...
+            //cout << TMath::Hypot(spot(0), spot(1)) << " " << TMath::Hypot(mean(0)-spot(0), mean(1)-spot(1)) << endl;
+        }
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fills a TList with all stars found under current presets
+// (Coordinates, Time, FOV). The list is emptied before the filling is done.
+// Currently, the mean spot when averaging over all mirrors is used.
+//
+void MAstroCamera::FillStarList(TList* list)
+{
+    if (!fTime || !fObservatory || !fMirrors) {
+      cout << "Missing data..." << endl;
+      return;
+    }
+
+    if (!list) {
+      cout << "Missing storage list for stars found..." << endl;
+      return;
+    }
+
+    list->Delete(); // dump old list... (otherwise the same stars would pile up)
+   
+    const TRotation rot(GetGrid(kTRUE));
+    MVector3 *radec;
+    TIter Next(&fList);
+
+    while ((radec=(MVector3*)Next())) {
+      const Double_t mag = radec->Magnitude();
+      if (mag>GetLimMag())
+	continue;
+      TVector3 star(*radec);
+      // Rotate Star into telescope system
+      star *= rot;
+      TVector3 mean;
+      Int_t num = 0;
+      MGeomMirror *mirror = 0;
+      TIter NextM(fMirrors);
+      while ((mirror=(MGeomMirror*)NextM())) {
+	const TVector3 spot = mirror->GetReflection(star, fGeom->GetCameraDist())*1000;
+	mean += spot;
+	num++;
+      }
+      mean *= 1./num;
+      MStarPos *starpos = new MStarPos;
+      starpos->SetExpValues(mag,mean(0),mean(1));
+
+      // Do _not_ remove this, name needs to be 
+      // transferred to the starpos.
+      const TString name = radec->GetName();
+      starpos->SetName(name.IsNull() ? "n/a" : name.Data());
+
+      const TVector3 spot = fMirror0->GetReflection(star, fGeom->GetCameraDist())*1000;
+      starpos->SetIdealValues(mag,spot(0),spot(1));
+      list->Add(starpos);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Uses fRaDec as a reference point.
+//
+// Return dZd and dAz corresponding to the distance from x,y to fRaDec
+//
+// Before calling this function you should correct for abberation. In
+// case of MAGIC you can do this by:
+//    x /= 1.0713;
+//    y /= 1.0713;
+//
+// x [mm]: x coordinate in the camera plane (assuming a perfect mirror)
+// y [mm]: y coordinate in the camera plane (assuming a perfect mirror)
+//
+// We assume (0, 0) to be the center of the FOV
+//
+// dzd [deg]: Delta Zd
+// daz [deg]: Delta Az
+//
+void MAstroCamera::GetDiffZdAz(Double_t x, Double_t y, Double_t &dzd, Double_t &daz)
+{
+    // Reflect the corrected pixel on a perfect mirror
+    TVector3 v(x, y, fGeom->GetCameraDist()*1000);
+    TVector3 spot = fMirror0->GetReflection(v);
+    
+    // Derotate into the local coordinate system
+    const MAstroSky2Local rot(*fTime, *fObservatory);
+    const TRotation align(AlignCoordinates(rot*fRaDec).Inverse());
+    spot *= align;
+
+    cout << "Zd="<<spot.Theta()*TMath::RadToDeg() << " ";
+    cout << "Az="<<spot.Phi()  *TMath::RadToDeg()+360 << endl;
+
+    // Derotatet the center of the camera
+    TVector3 c(0, 0, 1);
+    c *= align;
+
+    dzd = (spot.Theta()-c.Theta())*TMath::RadToDeg();
+    daz = (spot.Phi()  -c.Phi())  *TMath::RadToDeg();
+
+    if (daz> 180) daz -= 360;
+    if (daz<-180) daz += 360;
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a gui event on the camera
+//
+void MAstroCamera::ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2)
+{
+    // if (mp1>0 && mp2>0)
+    // {
+    //     // Calculate World coordinates from pixel
+    //     Double_t x = gPad->AbsPixeltoX(mp1);
+    //     Double_t y = gPad->AbsPixeltoY(mp2);
+    //
+    //     // Correct for abberation
+    //     x /= 1.0713;
+    //     y /= 1.0713;
+    //
+    //     Double_t dzd, daz;
+    //     GetDiffZdAz(x, y, dzd, daz);
+    //
+    //     cout << "dZd="<< dzd << " " << "dAz="<< daz << endl;
+    // }
+    //
+    // For MAGIC the distance of the mean of the light distribution
+    // to the Mirror0 reflection of the star (Abberation) can be
+    // expressed as:  dr = 0.0713*r = r/14.03
+    //                   +-0.0002
+
+    if (event==kKeyPress && fTime)
+        switch (mp2)
+        {
+        case kKey_Plus:
+            fTime->SetMjd(fTime->GetMjd()+0.25/24);
+            Update(kTRUE);
+            return;
+
+        case kKey_Minus:
+            fTime->SetMjd(fTime->GetMjd()-0.25/24);
+            Update(kTRUE);
+            return;
+        }
+
+    MAstroCatalog::ExecuteEvent(event, mp1, mp2);
+}
Index: /tags/Mars-V0.9/mastro/MAstroCamera.h
===================================================================
--- /tags/Mars-V0.9/mastro/MAstroCamera.h	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MAstroCamera.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MAstroCamera
+#define MARS_MAstroCamera
+
+#ifndef MARS_MAstroCatalog
+#include "MAstroCatalog.h"
+#endif
+
+class TClonesArray;
+class TList;
+
+class MTime;
+class MGeomCam;
+class MGeomMirror;
+class MObservatory;
+
+class MAstroCamera : public MAstroCatalog
+{
+private:
+    MGeomCam     *fGeom;
+    TClonesArray *fMirrors;
+
+    MGeomMirror  *fMirror0;     //!
+
+    Int_t  ConvertToPad(const TVector3 &w, TVector2 &v) const;
+    void   AddPrimitives(TString o);
+    void   SetRangePad(Option_t *o) { }
+    void   ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2);
+
+public:
+    MAstroCamera();
+    ~MAstroCamera();
+
+    void SetMirrors(TClonesArray &arr);
+    void SetMirrors(const char *fname);
+    void SetGeom(const MGeomCam &cam);
+
+    void FillStarList(TList *list);
+
+    void GetDiffZdAz(Double_t x, Double_t y, Double_t &dzd, Double_t &daz);
+
+    ClassDef(MAstroCamera, 1) // Display class to display stars on the camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mastro/MAstroCatalog.cc
===================================================================
--- /tags/Mars-V0.9/mastro/MAstroCatalog.cc	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MAstroCatalog.cc	(revision 9772)
@@ -0,0 +1,1398 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 03/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Robert Wagner, 08/2004 <mailto:rwagner@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MAstroCatalog
+//  =============
+//
+//  THIS IMPLEMENTATION IS PRELIMINARY AND WILL BE MERGED WITH
+//  SOME PARTS OF THE DRIVE SOFTWARE SOON!
+//
+//
+//  Catalogs:
+//  ---------
+//
+//  To be able to use this class you need a catalog file suppored by
+//  MAstroCatalog.
+//  Catalog files can be found at
+//  http://magic.astro.uni-wuerzburg.de/mars/catalogs.html
+//  You must copy the file into the directory from which you start your macro
+//  or give an abolute path loading the catalog.
+//
+//
+//  Usage:
+//  ------
+//
+//  To display a starfield you must have a supported catalog, then do:
+//
+//    MTime time;
+//    // Time for which to get the picture
+//    time.Set(2004, 2, 28, 20, 14, 7);
+//    // Current observatory
+//    MObservatory magic1;
+//    // Right Ascension [h] and declination [deg] of source
+//    // Currently 'perfect' pointing is assumed
+//    const Double_t ra  = MAstro::Hms2Rad(5, 34, 31.9);
+//    const Double_t dec = MAstro::Dms2Rad(22, 0, 52.0);
+//    MAstroCatalog stars;
+//    // Magnitude up to which the stars are loaded from the catalog
+//    stars.SetLimMag(6);
+//    // Radius of FOV around the source position to load the stars
+//    stars.SetRadiusFOV(3);
+//    // Source position
+//    stars.SetRaDec(ra, dec);
+//    // Catalog to load (here: Bright Star Catalog V5)
+//    stars.ReadBSC("bsc5.dat");
+//    // Obersavatory and time to also get local coordinate information
+//    stars.SetObservatory(magic1);
+//    stars.SetTime(time);
+//    // Enable interactive GUI
+//    stars.SetGuiActive();
+//    //Clone the catalog due to the validity range of the instance
+//    TObject *o = stars.Clone();
+//    o->SetBit(kCanDelete);
+//    o->Draw();
+//
+//  If no time and/or Obervatory location is given no local coordinate
+//  information is displayed.
+//
+//
+//  Coordinate Transformation:
+//  -------------------------
+//  The conversion from sky coordinates to local coordinates is done using
+//  MAstroSky2Local which does a simple rotation of the coordinate system.
+//  This is inaccurate in the order of 30arcsec due to ignorance of all
+//  astrometrical corrections (nutation, precission, abberation, ...)
+//
+//
+//  GUI:
+//  ----
+//    * If the gui is interactive you can use the cursor keys to change
+//      the position you are looking at and with plus/minus you
+//      can (un)zoom the FOV (Field Of View)
+//    * The displayed values mean the following:
+//        + alpha: Right Ascension
+//        + delta: Declination
+//        + theta: zenith distance / zenith angle
+//        + phi:   azimuth angle
+//        + rho:   angle of rotation sky-coordinate system vs local-
+//                 coordinate system
+//        + time of display
+//    * Move the mouse on top of the grid points or the stars to get
+//      more setailed information.
+//    * Enable the event-info in a canvas to see the current
+//      ObjectInfo=tooltip-text
+//    * call SetNoToolTips to supress the tooltips
+//    * the blue lines are the local coordinat system
+//    * the red lines are sky coordinate system
+//
+//
+//  ToDo:
+//  -----
+//   - replace MVetcor3 by a more convinient class. Maybe use TExMap, too.
+//   - change tooltips to multi-line tools tips as soon as root
+//     supports them
+//   - a derived class is missing which supports all astrometrical
+//     correction (base on slalib and useable in Cosy)
+//   - Implement a general loader for heasarc catlogs, see
+//     http://heasarc.gsfc.nasa.gov/W3Browse/star-catalog/
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAstroCatalog.h"
+
+#include <errno.h>      // strerror
+#include <fstream>      // ifstream
+#include <stdlib.h>     // ati, atof
+#include <limits.h>     // INT_MAX (Suse 7.3/gcc 2.95)
+
+#include <KeySymbols.h> // kKey_*
+
+#include <TLine.h>      // TLine
+#include <TMarker.h>    // TMarker
+#include <TCanvas.h>    // TCanvas
+#include <TArrayI.h>    // TArrayI
+#include <TGToolTip.h>  // TGToolTip
+#include <TPaveText.h>  // TPaveText
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MString.h"
+#include "MAstro.h"
+#include "MAstroSky2Local.h"
+#include "MObservatory.h"
+
+#undef DEBUG
+//#define DEBUG
+
+#ifdef DEBUG
+#include <TStopwatch.h>
+#endif
+
+ClassImp(MAstroCatalog);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor. Set Default values:
+//   fLimMag    = 99
+//   fRadiusFOV = 90
+//
+MAstroCatalog::MAstroCatalog() : fLimMag(99), fRadiusFOV(90), fToolTip(0), fObservatory(0), fTime(0)
+{
+    fList.SetOwner();
+    fMapG.SetOwner();
+    fToolTip = gROOT->IsBatch() || !gClient ? 0 : new TGToolTip(0, "", 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete fTime, fObservatory. Disconnect signal. delete tooltip.
+// Delete Map with gui primitives
+//
+MAstroCatalog::~MAstroCatalog()
+{
+    // First disconnect the EventInfo...
+    // FIXME: There must be an easier way!
+    TIter Next(gROOT->GetListOfCanvases());
+    TCanvas *c;
+    while ((c=(TCanvas*)Next()))
+        c->Disconnect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)", this,
+                      "EventInfo(Int_t,Int_t,Int_t,TObject*)");
+
+    // Now delete the data members
+    if (fTime)
+        delete fTime;
+    if (fObservatory)
+        delete fObservatory;
+
+    if (fToolTip)
+    {
+        fToolTip->Hide();
+        delete fToolTip;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Snippet to for reading catalog files.
+//
+TString MAstroCatalog::FindToken(TString &line, Char_t tok)
+{
+    Ssiz_t token = line.First(tok);
+    if (token<0)
+    {
+        const TString copy(line);
+        line = "";
+        return copy;
+    }
+
+    const TString res = line(0, token);
+    line.Remove(0, token+1);
+    return res;
+}
+
+// --------------------------------------------------------------------------
+//
+// return int correspoding to TSubString
+//
+Int_t MAstroCatalog::atoi(const TSubString &sub)
+{
+    return atoi(TString(sub));
+}
+
+// --------------------------------------------------------------------------
+//
+// return float correspoding to TSubString
+//
+Float_t MAstroCatalog::atof(const TSubString &sub)
+{
+    return atof(TString(sub));
+}
+
+// --------------------------------------------------------------------------
+//
+// return int correspoding to TString
+//
+Int_t MAstroCatalog::atoi(const TString &s)
+{
+    return std::atoi(s);
+}
+
+// --------------------------------------------------------------------------
+//
+// return float correspoding to TString
+//
+Float_t MAstroCatalog::atof(const TString &s)
+{
+    return std::atof(s);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a xephem catalog, set bit kHasChahanged.
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+//
+Int_t MAstroCatalog::ReadXephem(TString catalog)
+{
+    gLog << inf << "Reading Xephem catalog: " << catalog << endl;
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    Int_t add =0;
+    Int_t cnt =0;
+    Int_t line=0;
+
+    Double_t maxmag=0;
+
+    while (1)
+    {
+        TString row;
+        row.ReadLine(fin);
+        if (!fin)
+            break;
+
+        line++;
+
+        if (row[0]=='#')
+            continue;
+
+        TString line(row);
+
+        TString name  = FindToken(line);
+        TString dummy = FindToken(line);
+        TString r     = FindToken(line);
+        TString d     = FindToken(line);
+        TString m     = FindToken(line);
+        TString epoch = FindToken(line);
+
+        if (name.IsNull() || r.IsNull() || d.IsNull() || m.IsNull() || epoch.IsNull())
+        {
+            gLog << warn << "Invalid Entry Line #" << line << ": " << row << endl;
+            continue;
+        }
+
+        cnt++;
+
+        const Double_t mag = atof(m);
+
+        maxmag = TMath::Max(maxmag, mag);
+
+        if (mag>fLimMag)
+            continue;
+
+        if (epoch!="2000")
+        {
+            gLog << warn << "Epoch != 2000... skipped." << endl;
+            continue;
+        }
+
+        Double_t ra0, dec0;
+        MAstro::Coordinate2Angle(r, ra0);
+        MAstro::Coordinate2Angle(d, dec0);
+
+        ra0  *= TMath::Pi()/12;
+        dec0 *= TMath::Pi()/180;
+
+        if (AddObject(ra0, dec0, mag, name))
+            add++;
+    }
+    gLog << inf << "Read " << add << " out of " << cnt << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a NGC2000 catalog. set bit kHasChanged
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+//
+Int_t MAstroCatalog::ReadNGC2000(TString catalog)
+{
+    gLog << inf << "Reading NGC2000 catalog: " << catalog << endl;
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t n  =0;
+
+    Double_t maxmag=0;
+
+    while (1)
+    {
+        TString row;
+        row.ReadLine(fin);
+        if (!fin)
+            break;
+
+        cnt++;
+
+        const Int_t   rah  = atoi(row(13, 2));
+        const Float_t ram  = atof(row(16, 4));
+        const Char_t  decs = row(22);
+        const Int_t   decd = atoi(row(23, 2));
+        const Int_t   decm = atoi(row(26, 2));
+        const TString m    = row(43, 4);
+
+        if (m.Strip().IsNull())
+            continue;
+
+        n++;
+
+        const Double_t mag = atof(m);
+
+        maxmag = TMath::Max(maxmag, mag);
+
+        if (mag>fLimMag)
+            continue;
+
+        const Double_t ra  = MAstro::Hms2Rad(rah,  (int)ram, fmod(ram, 1)*60);
+        const Double_t dec = MAstro::Dms2Rad(decd, decm, 0, decs);
+
+        if (AddObject(ra, dec, mag, row(0,8)))
+            add++;
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a Bright Star Catalog catalog. set bit kHasChanged
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+//
+Int_t MAstroCatalog::ReadBSC(TString catalog)
+{
+    gLog << inf << "Reading Bright Star Catalog (BSC5) catalog: " << catalog << endl;
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t n  =0;
+
+    Double_t maxmag=0;
+
+    while (1)
+    {
+        TString row;
+        row.ReadLine(fin);
+        if (!fin)
+            break;
+
+        cnt++;
+
+        const Int_t   rah    = atoi(row(75, 2));
+        const Int_t   ram    = atoi(row(77, 2));
+        const Float_t ras    = atof(row(79, 4));
+        const Char_t  decsgn = row(83);
+        const Int_t   decd   = atoi(row(84, 2));
+        const Int_t   decm   = atoi(row(86, 2));
+        const Int_t   decs   = atoi(row(88, 2));
+        const TString m      = row(102, 5);
+
+        if (m.Strip().IsNull())
+            continue;
+
+        n++;
+
+        const Double_t mag = atof(m.Data());
+
+        maxmag = TMath::Max(maxmag, mag);
+
+        if (mag>fLimMag)
+            continue;
+
+        const Double_t ra  = MAstro::Hms2Rad(rah, ram, ras);
+        const Double_t dec = MAstro::Dms2Rad(decd, decm, decs, decsgn);
+
+        if (AddObject(ra, dec, mag, row(4,9)))
+            add++;
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a ascii heasarc ppm catalog. set bit kHasChanged
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+// If the second argument is given all survived stars are written
+// to a file outname. This files will contain an apropriate compressed
+// file format. You can read such files again using ReadCompressed.
+//
+// FIXME: A General loader for heasarc catlogs is missing, see
+//        http://heasarc.gsfc.nasa.gov/W3Browse/star-catalog/
+//
+Int_t MAstroCatalog::ReadHeasarcPPM(TString catalog, TString outname)
+{
+    gLog << inf << "Reading Heasarc PPM catalog: " << catalog << endl;
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    ofstream *fout = outname.IsNull() ? 0 : new ofstream(outname);
+    if (fout && !*fout)
+    {
+        gLog << warn << "Cannot open output file " << outname << ": ";
+        gLog << strerror(errno) << endl;
+        delete fout;
+        fout = 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t n  =0;
+
+    Double_t maxmag=0;
+
+    while (1)
+    {
+        TString row;
+        row.ReadLine(fin);
+        if (!fin)
+            break;
+
+        cnt++;
+
+        if (!row.BeginsWith("PPM "))
+            continue;
+
+        const TString name = row(0, row.First('|'));
+        row = row(row.First('|')+1, row.Length());
+        row = row(row.First('|')+1, row.Length());
+
+        const TString vmag = row(0, row.First('|'));
+
+        n++;
+        const Double_t mag = atof(vmag.Data());
+        maxmag = TMath::Max(maxmag, mag);
+        if (mag>fLimMag)
+            continue;
+
+        row = row(row.First('|')+1, row.Length());
+        row = row(row.First('|')+1, row.Length());
+
+        row = row(row.First('|')+1, row.Length());
+        row = row(row.First('|')+1, row.Length());
+
+        row = row(row.First('|')+1, row.Length());
+        row = row(row.First('|')+1, row.Length());
+
+        const TString ra = row(0, row.First('|'));
+        row = row(row.First('|')+1, row.Length());
+        const TString de = row(0, row.First('|'));
+        row = row(row.First('|')+1, row.Length());
+
+        Char_t sgn;
+        Int_t d, m;
+        Float_t s;
+        if (sscanf(ra.Data(), "%d %d %f", &d, &m, &s)!=3)
+        {
+            // gLog << "Error loading entry in line " << i << endl;
+            continue;
+        }
+        const Double_t ra0 = MAstro::Hms2Rad(d, m, s);
+
+        if (sscanf(de.Data(), "%c%d %d %f", &sgn, &d, &m, &s)!=4)
+        {
+            // gLog << "Error loading entry in line " << i << endl;
+            continue;
+        }
+        const Double_t de0 = MAstro::Dms2Rad(d, m, s, sgn);
+
+        if (!AddObject(ra0, de0, mag, name))
+            continue;
+
+        add++;
+
+        if (fout)
+            ((MVector3*)fList.Last())->WriteBinary(*fout);
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from a MAstroCatalog compressed catalog. set bit kHasChanged
+// Already read data is not deleted. To delete the stored data call
+// Delete().
+//
+Int_t MAstroCatalog::ReadCompressed(TString catalog)
+{
+    SetBit(kHasChanged);
+
+    gLog << inf << "Reading MAstroCatalog compressed catalog: " << catalog << endl;
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open catalog file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return 0;
+    }
+
+    Int_t add=0;
+    Int_t cnt=0;
+    Int_t n  =0;
+
+    Double_t maxmag=0;
+
+    MVector3 entry;
+
+    while (1)
+    {
+        cnt++;
+
+        entry.ReadBinary(fin);
+        if (!fin)
+            break;
+
+        n++;
+
+        const Double_t mag = entry.Magnitude();
+        maxmag = TMath::Max(maxmag, mag);
+        if (mag>fLimMag)
+            continue;
+
+        if (entry.Angle(fRaDec)*TMath::RadToDeg()>fRadiusFOV)
+            continue;
+
+        fList.Add(entry.Clone());
+        add++;
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add an object to the star catalog manually. Return true if the object
+// was added and false otherwise (criteria is the FOV)
+//
+Bool_t MAstroCatalog::AddObject(Float_t ra, Float_t dec, Float_t mag, TString name)
+{
+    MVector3 *star = new MVector3;
+    star->SetRaDec(ra, dec, mag);
+    star->SetName(name);
+
+    if (star->Angle(fRaDec)*TMath::RadToDeg()>fRadiusFOV)
+    {
+        delete star;
+        return 0;
+    }
+
+    SetBit(kHasChanged);
+    fList.AddLast(star);
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set Range of pad. If something has changed create and draw new primitives.
+// Paint all gui primitives.
+//
+void MAstroCatalog::Paint(Option_t *o)
+{
+    SetRangePad(o);
+
+    if (TestBit(kHasChanged))
+        DrawPrimitives(o);
+
+    fMapG.Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set Range of pad if pad available. If something has changed create
+// and draw new primitives. Paint all gui primitives to the Drawable with
+// Id id. This can be used to be able to
+//
+/*
+void MAstroCatalog::PaintImg(Int_t id, Option_t *o)
+{
+    if (gPad)
+        SetRangePad(o);
+
+    if (TestBit(kHasChanged))
+    {
+        if (id>0)
+            gPad=0;
+        DrawPrimitives(o);
+    }
+
+    fMapG.Paint(id, fRadiusFOV);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Set Range of pad. If something has changed create and draw new primitives.
+// Paint all gui primitives.
+//
+// Because in some kind of multi-threaded environments gPad doesn't stay
+// the same in a single thread (because it might be changed in the same
+// thread inside a gui updating timer for example) we have to secure the
+// usage of gPad with a bit. This is also not multi-thread safe against
+// calling this function, but the function should work well in multi-
+// threaded environments. Never call this function from different threads
+// simultaneously.
+//
+void MAstroCatalog::PaintImg(unsigned char *buf, int w, int h, Option_t *o)
+{
+    if (!o)
+        o = "local mirrorx yellow * =";
+
+    if (TestBit(kHasChanged))
+    {
+        SetBit(kDrawingImage);
+        DrawPrimitives(o);
+        ResetBit(kDrawingImage);
+    }
+
+    fMapG.Paint(buf, w, h, fRadiusFOV);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a black marker at the position of the star. Create a corresponding
+// tooltip with the coordinates.
+// x, y: Pad Coordinates to draw star
+// v: Sky position (Ra/Dec) of the star
+// col: Color of marker (<0 mean transparent)
+// txt: additional tooltip text
+// resize: means resize the marker according to the magnitude
+//
+void MAstroCatalog::DrawStar(Double_t x, Double_t y, const TVector3 &v, Int_t col, const char *txt, Bool_t resize)
+{
+    const Double_t ra  = v.Phi()*TMath::RadToDeg()/15;
+    const Double_t dec = (TMath::Pi()/2-v.Theta())*TMath::RadToDeg();
+
+    const Double_t mag = -2.5*log10(v.Mag());
+
+    MString str;
+    str.Print("%s:  Ra=%.2fh  Dec=%.1fd  Mag=%.1f", v.GetName(), ra, dec, mag);
+    if (txt)
+    {
+        str += "  (";
+        str += txt;
+        str += ")";
+    }
+
+    // draw star on the camera display
+    TMarker *tip=new TMarker(x, y, col<0 ? kDot : kFullDotMedium);;
+    tip->SetMarkerColor(col);
+    fMapG.Add(tip, new TString(str));
+
+    if (!resize)
+        return;
+
+    tip->SetMarkerSize((10 - (mag>1 ? mag : 1))/15);
+    tip->SetMarkerStyle(kCircle);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set pad as modified.
+//
+void MAstroCatalog::Update(Bool_t upd)
+{
+    SetBit(kHasChanged);
+    if (gPad && TestBit(kMustCleanup))
+    {
+        gPad->Modified();
+        if (upd)
+            gPad->Update();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the observation time. Necessary to use local coordinate
+// system. The MTime object is cloned.
+//
+void MAstroCatalog::SetTime(const MTime &time)
+{
+    if (fTime)
+        delete fTime;
+    fTime=(MTime*)time.Clone();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the observatory location. Necessary to use local coordinate
+// system. The MObservatory object is cloned.
+//
+void MAstroCatalog::SetObservatory(const MObservatory &obs)
+{
+    if (fObservatory)
+        delete fObservatory;
+    fObservatory=new MObservatory;
+    obs.Copy(*fObservatory);
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert the vector to pad coordinates. After conversion
+// the x- coordinate of the vector must be the x coordinate
+// of the pad - the same for y. If the coordinate is inside
+// the current draw area return kTRUE, otherwise kFALSE.
+// If it is an invalid coordinate return kERROR
+//
+Int_t MAstroCatalog::ConvertToPad(const TVector3 &w0, TVector2 &v) const
+{
+    TVector3 w(w0);
+
+    // Stretch such, that the Z-component is alwas the same. Now
+    // X and Y contains the intersection point between the star-light
+    // and the plain of a virtual plain screen (ccd...)
+    if (TestBit(kPlainScreen))
+        w *= 1./w(2);
+
+    w *= TMath::RadToDeg(); // FIXME: *conversion factor?
+    v.Set(TestBit(kMirrorX) ? -w(0) : w(0),
+          TestBit(kMirrorY) ? -w(1) : w(1));
+
+    if (w(2)<0)
+        return kERROR;
+
+    if (TestBit(kDrawingImage) || !gPad)
+        return v.Mod2()<fRadiusFOV*fRadiusFOV;
+
+    return v.X()>gPad->GetX1() && v.Y()>gPad->GetY1() &&
+           v.X()<gPad->GetX2() && v.Y()<gPad->GetY2();
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert theta/phi coordinates of v by TRotation into new coordinate
+// system and convert the coordinated to pad by ConvertToPad.
+// The result is retunred in v.
+//
+Int_t MAstroCatalog::Convert(const TRotation &rot, TVector2 &v) const
+{
+    MVector3 w;
+    w.SetMagThetaPhi(1, v.Y(), v.X());
+    w *= rot;
+
+    return ConvertToPad(w, v);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a line from v to v+(dx,dy) using Convert/ConvertToPad to get the
+// corresponding pad coordinates.
+//
+Bool_t MAstroCatalog::DrawLine(const TVector2 &v, Int_t dx, Int_t dy, const TRotation &rot, Int_t type)
+{
+    const TVector2 add(dx*TMath::DegToRad(), dy*TMath::DegToRad());
+
+    // Define all lines in the same direction
+    const TVector2 va(dy==1?v:v+add);
+    const TVector2 vb(dy==1?v+add:v);
+
+    TVector2 v0(va);
+    TVector2 v1(vb);
+
+    const Int_t rc0 = Convert(rot, v0);
+    const Int_t rc1 = Convert(rot, v1);
+
+    // Both are kFALSE or both are kERROR
+    if ((rc0|rc1)==kFALSE || (rc0&rc1)==kERROR)
+        return kFALSE;
+
+    TLine *line = new TLine(v0.X(), v0.Y(), v1.X(), v1.Y());
+    line->SetLineStyle(kDashDotted); //kDashed, kDotted, kDashDotted
+    line->SetLineColor(kWhite+type*2);
+    fMapG.Add(line);
+
+    if (dx!=0)
+        return kTRUE;
+
+    const TVector2 deg = va*TMath::RadToDeg();
+
+    MString txt;
+    if (type==1)
+        txt.Print("Ra=%.2fh  Dec=%.1fd", fmod(deg.X()/15+48, 24),  fmod(90-deg.Y()+270,180)-90);
+    else
+        txt.Print("Zd=%.1fd  Az=%.1fd",  fmod(deg.Y()+270,180)-90, fmod(deg.X()+720, 360));
+
+    TMarker *tip=new TMarker(v0.X(), v0.Y(), kDot);
+    tip->SetMarkerColor(kWhite+type*2);
+    fMapG.Add(tip, new TString(txt));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use "local" draw option to align the display to the local
+// coordinate system instead of the sky coordinate system.
+// dx, dy are arrays storing recuresively all touched points
+// stepx, stepy are the step-size of the current grid.
+//
+void MAstroCatalog::Draw(const TVector2 &v0, const TRotation &rot, TArrayI &dx, TArrayI &dy, Int_t stepx, Int_t stepy, Int_t type)
+{
+    // Calculate the end point
+    const TVector2 v1 = v0 + TVector2(dx[0]*TMath::DegToRad(), dy[0]*TMath::DegToRad());
+
+    // Check whether the point has already been touched.
+    Int_t idx[] = {1, 1, 1, 1};
+
+    Int_t dirs[4][2] = { {0, stepy}, {stepx, 0}, {0, -stepy}, {-stepx, 0} };
+
+    // Check for ambiguities.
+    for (int i=0; i<dx.GetSize(); i++)
+    {
+        for (int j=0; j<4; j++)
+        {
+            const Bool_t rcx0 = (dx[i]+720)%360==(dx[0]+dirs[j][0]+720)%360;
+            const Bool_t rcy0 = (dy[i]+360)%180==(dy[0]+dirs[j][1]+360)%180;
+            if (rcx0&&rcy0)
+                idx[j] = 0;
+        }
+    }
+
+    // Enhance size of array by 1, copy current
+    // position as last entry
+    dx.Set(dx.GetSize()+1);
+    dy.Set(dy.GetSize()+1);
+
+    dx[dx.GetSize()-1] = dx[0];
+    dy[dy.GetSize()-1] = dy[0];
+
+    // Store current positon
+    const Int_t d[2] = { dx[0], dy[0] };
+
+    for (int i=0; i<4; i++)
+        if (idx[i])
+        {
+            // Calculate new position
+            dx[0] = d[0]+dirs[i][0];
+            dy[0] = d[1]+dirs[i][1];
+
+            // Draw corresponding line and iterate through grid
+            if (DrawLine(v1, dirs[i][0], dirs[i][1], rot, type))
+                Draw(v0, rot, dx, dy, stepx, stepy, type);
+
+            dx[0]=d[0];
+            dy[0]=d[1];
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a grid recursively around the point v0 (either Ra/Dec or Zd/Az)
+// The points in the grid are converted by a TRotation and CovertToPad
+// to pad coordinates. The type arguemnts is neccessary to create the
+// correct tooltip (Ra/Dec, Zd/Az) at the grid-points.
+// From the pointing position the step-size of teh gris is caluclated.
+//
+void MAstroCatalog::DrawGrid(const TVector3 &v0, const TRotation &rot, Int_t type)
+{
+    TArrayI dx(1);
+    TArrayI dy(1);
+
+    // align to 1deg boundary
+    TVector2 v(v0.Phi()*TMath::RadToDeg(), v0.Theta()*TMath::RadToDeg());
+    v.Set((Float_t)TMath::Nint(v.X()), (Float_t)TMath::Nint(v.Y()));
+
+    // calculate stepsizes based on visible FOV
+    Int_t stepx = 1;
+
+    if (v.Y()<fRadiusFOV || v.Y()>180-fRadiusFOV)
+        stepx=36;
+    else
+    {
+        // This is a rough estimate how many degrees are visible
+        const Float_t m = log(fRadiusFOV/180.)/log(90./(fRadiusFOV+1)+1);
+        const Float_t t = log(180.)-m*log(fRadiusFOV);
+        const Float_t f = m*log(90-fabs(90-v.Y()))+t;
+        const Int_t nx = (Int_t)(exp(f)+0.5);
+        stepx = nx<4 ? 1 : nx/4;
+        if (stepx>36)
+            stepx=36;
+    }
+
+    const Int_t ny = (Int_t)(fRadiusFOV+1);
+    Int_t stepy = ny<4 ? 1 : ny/4;
+
+    // align stepsizes to be devisor or 180 and 90
+    while (180%stepx)
+        stepx++;
+    while (90%stepy)
+        stepy++;
+
+    // align to step-size boundary (search for the nearest one)
+    Int_t dv = 1;
+    while ((int)(v.X())%stepx)
+    {
+        v.Set(v.X()+dv, v.Y());
+        dv = -TMath::Sign(TMath::Abs(dv)+1, dv);
+    }
+
+    dv = 1;
+    while ((int)(v.Y())%stepy)
+    {
+        v.Set(v.X(), v.Y()+dv);
+        dv = -TMath::Sign(TMath::Abs(dv)+1, dv);
+    }
+
+    // draw...
+    v *= TMath::DegToRad();
+
+    Draw(v, rot, dx, dy, stepx, stepy, type);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get a rotation matrix which aligns the pointing position
+// to the center of the x,y plain
+//
+TRotation MAstroCatalog::AlignCoordinates(const TVector3 &v) const
+{
+    TRotation trans;
+    trans.RotateZ(-v.Phi());
+    trans.RotateY(-v.Theta());
+    trans.RotateZ(-TMath::Pi()/2);
+    return trans;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the rotation matrix which converts either sky or
+// local coordinates to coordinates which pole is the current
+// pointing direction.
+//
+TRotation MAstroCatalog::GetGrid(Bool_t local)
+{
+    const Bool_t enable = fTime && fObservatory;
+
+    // If sky coordinate view is requested get rotation matrix and
+    // draw corresponding sky-grid and if possible local grid
+    if (!local)
+    {
+        const TRotation trans(AlignCoordinates(fRaDec));
+
+        DrawGrid(fRaDec, trans, 1);
+
+        if (enable)
+        {
+            const MAstroSky2Local rot(*fTime, *fObservatory);
+            DrawGrid(rot*fRaDec, trans*rot.Inverse(), 2);
+        }
+
+        // Return the correct rotation matrix
+        return trans;
+    }
+
+    // If local coordinate view is requested get rotation matrix and
+    // draw corresponding sky-grid and if possible local grid
+    if (local && enable)
+    {
+        const MAstroSky2Local rot(*fTime, *fObservatory);
+
+        const TRotation trans(AlignCoordinates(rot*fRaDec));
+
+        DrawGrid(fRaDec,     trans*rot, 1);
+        DrawGrid(rot*fRaDec, trans,     2);
+
+        // Return the correct rotation matrix
+        return trans*rot;
+    }
+
+    return TRotation();
+}
+
+// --------------------------------------------------------------------------
+//
+// Create the title for the pad.
+//
+TString MAstroCatalog::GetPadTitle() const
+{
+    const Double_t ra  = fRaDec.Phi()*TMath::RadToDeg();
+    const Double_t dec = (TMath::Pi()/2-fRaDec.Theta())*TMath::RadToDeg();
+
+    TString txt;
+    txt += Form("\\alpha=%.2fh ",      fmod(ra/15+48, 24));
+    txt += Form("\\delta=%.1f\\circ ", fmod(dec+270,180)-90);
+    txt += Form("/ FOV=%.1f\\circ",    fRadiusFOV);
+
+    if (!fTime || !fObservatory)
+        return txt;
+
+    const MAstroSky2Local rot(*fTime, *fObservatory);
+    const TVector3 loc = rot*fRaDec;
+
+    const Double_t rho = rot.RotationAngle(fRaDec.Phi(), TMath::Pi()/2-fRaDec.Theta());
+
+    const Double_t zd = TMath::RadToDeg()*loc.Theta();
+    const Double_t az = TMath::RadToDeg()*loc.Phi();
+
+    txt.Prepend("#splitline{");
+    txt += Form("  \\theta=%.1f\\circ ", fmod(zd+270,180)-90);
+    txt += Form("\\phi=%.1f\\circ ",     fmod(az+720, 360));
+    txt += Form(" / \\rho=%.1f\\circ",   rho*TMath::RadToDeg());
+    txt += "}{<";
+    txt += fTime->GetSqlDateTime();
+    txt += ">}";
+    return txt;
+}
+
+// --------------------------------------------------------------------------
+//
+// To overlay the catalog make sure, that in any case you are using
+// the 'same' option.
+//
+// If you want to overlay this on top of any picture which is created
+// by derotation of the camera plain you have to use the 'mirror' option
+// the compensate the mirroring of the image in the camera plain.
+//
+// If you have already compensated this by x=-x and y=-y when creating
+// the histogram you can simply overlay the catalog.
+//
+// To overlay the catalog on a 2D histogram the histogram must have
+// units of degrees (which are plain, like you directly convert the
+// camera units by multiplication to degrees)
+//
+// To be 100% exact you must use the option 'plain' which assumes a plain
+// screen. This is not necessary for the MAGIC-camera because the
+// difference between both is less than 1e-3.
+//
+// You should always be aware of the fact, that the shown stars and the
+// displayed grid is the ideal case, like a reflection on a virtual
+// perfectly aligned central mirror. In reality the star-positions are
+// smeared to the edge of the camera the more the distance to the center
+// is, such that the center of gravity of the light distribution might
+// be more far away from the center than the display shows.
+//
+// If you want the stars to be displayed as circles with a size
+// showing their magnitude use "*" as an option.
+//
+// Use 'white'  to display white instead of black stars
+// Use 'yellow' to display white instead of black stars
+//
+//
+void MAstroCatalog::AddPrimitives(TString o)
+{
+    const Bool_t same   = o.Contains("same",    TString::kIgnoreCase);
+    const Bool_t local  = o.Contains("local",   TString::kIgnoreCase);
+    const Bool_t mirx   = o.Contains("mirrorx", TString::kIgnoreCase);
+    const Bool_t miry   = o.Contains("mirrory", TString::kIgnoreCase);
+    const Bool_t mirror = o.Contains("mirror",  TString::kIgnoreCase) && !mirx && !miry;
+    const Bool_t size   = o.Contains("*",       TString::kIgnoreCase);
+    const Bool_t white  = o.Contains("white",   TString::kIgnoreCase);
+    const Bool_t yellow = o.Contains("yellow",  TString::kIgnoreCase) && !white;
+
+    // X is vice versa, because ra is defined anti-clockwise
+    mirx || mirror ? ResetBit(kMirrorX) : SetBit(kMirrorX);
+    miry || mirror ? SetBit(kMirrorY) : ResetBit(kMirrorY);
+
+    const TRotation rot(GetGrid(local));
+
+    TIter Next(&fList);
+    MVector3 *v=0;
+    while ((v=(MVector3*)Next()))
+    {
+        if (v->Magnitude()>fLimMag)
+            continue;
+
+        TVector2 s(v->Phi(), v->Theta());
+        if (Convert(rot, s)==kTRUE)
+            DrawStar(s.X(), s.Y(), *v, yellow?kYellow:(white?kWhite:kBlack), 0, size);
+    }
+
+    if (!same && !TestBit(kDrawingImage) && gPad)
+    {
+        TPaveText *pv = new TPaveText(0.01, 0.90, 0.63, 0.99, "brNDC");
+        pv->AddText(GetPadTitle());
+        fMapG.Add(pv);
+    }
+
+    TMarker *mk=new TMarker(0, 0, kMultiply);
+    mk->SetMarkerColor(white||yellow?kWhite:kBlack);
+    mk->SetMarkerSize(1.5);
+    fMapG.Add(mk);
+}
+
+// --------------------------------------------------------------------------
+//
+// Do nothing if 'same' option given.
+// Otherwise set pad-range such that x- and y- coordinates have the same
+// step-size
+//
+void MAstroCatalog::SetRangePad(Option_t *o)
+{
+    if (TString(o).Contains("same", TString::kIgnoreCase))
+        return;
+
+    const Double_t edge = fRadiusFOV/TMath::Sqrt(2.);
+    //gPad->Range(-edge, -edge, edge, edge);
+
+    const Float_t w = gPad->GetWw();
+    const Float_t h = gPad->GetWh();
+
+    if (w<h)
+        gPad->Range(-edge, -edge*h/w, edge, edge*h/w);
+    else
+        gPad->Range(-edge*w/h, -edge, edge*w/h, edge);
+}
+
+// --------------------------------------------------------------------------
+//
+// First delete all gui elements.
+// Set the correct range of the pad.
+// Create all gui primitives
+// If "this" is not in the current pad add it to the current pad.
+// Reset vit kHasChanged
+//
+void MAstroCatalog::DrawPrimitives(Option_t *o)
+{
+    fMapG.Delete();
+
+    if (!TestBit(kDrawingImage) && gPad)
+        SetRangePad(o);
+
+#ifdef DEBUG
+    TStopwatch clk;
+    clk.Start();
+#endif
+    AddPrimitives(o);
+#ifdef DEBUG
+    clk.Stop();
+    clk.Print();
+#endif
+
+    // Append to a possible second pad
+    if (!TestBit(kDrawingImage) && gPad && !gPad->GetListOfPrimitives()->FindObject(this))
+        AppendPad(o);
+
+    ResetBit(kHasChanged);
+}
+
+// --------------------------------------------------------------------------
+//
+// Append "this" to current pad
+// set bit kHasChanged to recreate all gui elements
+// Connect signal
+//
+void MAstroCatalog::Draw(Option_t *o)
+{
+    // Append to first pad
+    AppendPad(o);
+
+    // If contents have not previously changed make sure that
+    // all primitives are recreated.
+    SetBit(kHasChanged);
+
+    // Connect all TCanvas::ProcessedEvent to this->EventInfo
+    // This means, that after TCanvas has processed an event
+    // EventInfo of this class is called, see TCanvas::HandleInput
+    gPad->GetCanvas()->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",
+                               "MAstroCatalog", this,
+                               "EventInfo(Int_t,Int_t,Int_t,TObject*)");
+}
+
+// --------------------------------------------------------------------------
+//
+// This function was connected to all created canvases. It is used
+// to redirect GetObjectInfo into our own status bar.
+//
+// The 'connection' is done in Draw. It seems that 'connected'
+// functions must be public.
+//
+void MAstroCatalog::EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected)
+{
+    TCanvas *c = (TCanvas*)gTQSender;
+
+    gPad = c ? c->GetSelectedPad() : NULL;
+    if (!gPad)
+        return;
+
+
+    // Try to find a corresponding object with kCannotPick set and
+    // an available TString (for a tool tip)
+    TString str;
+    if (!selected || selected==this)
+        selected =  fMapG.PickObject(px, py, str);
+
+    if (!selected)
+        return;
+
+    // Handle some gui events
+    switch (event)
+    {
+    case kMouseMotion:
+        if (fToolTip && !fToolTip->IsMapped() && !str.IsNull())
+            ShowToolTip(px, py, str);
+        break;
+
+    case kMouseLeave:
+        if (fToolTip && fToolTip->IsMapped())
+            fToolTip->Hide();
+        break;
+
+    case kKeyPress:
+        ExecuteEvent(kKeyPress, px, py);
+        break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Handle keyboard events.
+//
+void MAstroCatalog::ExecuteEventKbd(Int_t keycode, Int_t keysym)
+{
+    Double_t dra =0;
+    Double_t ddec=0;
+
+    switch (keysym)
+    {
+    case kKey_Left:
+        dra = -TMath::DegToRad();
+        break;
+    case kKey_Right:
+        dra = +TMath::DegToRad();
+        break;
+    case kKey_Up:
+        ddec = +TMath::DegToRad();
+        break;
+    case kKey_Down:
+        ddec = -TMath::DegToRad();
+        break;
+    case kKey_Plus:
+        SetRadiusFOV(fRadiusFOV+1);
+        break;
+    case kKey_Minus:
+        SetRadiusFOV(fRadiusFOV-1);
+        break;
+
+    default:
+        return;
+    }
+
+    const Double_t r = fRaDec.Phi();
+    const Double_t d = TMath::Pi()/2-fRaDec.Theta();
+
+    SetRaDec(r+dra, d+ddec);
+
+    gPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a gui event on the camera
+//
+void MAstroCatalog::ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2)
+{
+    if (!TestBit(kGuiActive))
+        return;
+
+    if (event==kKeyPress)
+        ExecuteEventKbd(mp1, mp2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Displays a tooltip
+//
+void MAstroCatalog::ShowToolTip(Int_t px, Int_t py, const char *txt)
+{
+    if (TestBit(kNoToolTips))
+        return;
+
+    Int_t x=0;
+    Int_t y=0;
+
+    const Window_t id1 = gVirtualX->GetWindowID(gPad->GetCanvasID());
+    const Window_t id2 = fToolTip->GetParent()->GetId();
+
+    Window_t id3;
+    gVirtualX->TranslateCoordinates(id1, id2, px, py, x, y, id3);
+
+    // Show tool tip
+    fToolTip->SetText(txt);
+    fToolTip->Show(x+4, y+4);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate distance to primitive by checking all gui elements
+//
+Int_t MAstroCatalog::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    return fMapG.DistancetoPrimitive(px, py);
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns string containing info about the object at position (px,py).
+// Returned string will be re-used (lock in MT environment).
+//
+char *MAstroCatalog::GetObjectInfo(Int_t px, Int_t py) const
+{
+    return fMapG.GetObjectInfo(px, py);
+}
Index: /tags/Mars-V0.9/mastro/MAstroCatalog.h
===================================================================
--- /tags/Mars-V0.9/mastro/MAstroCatalog.h	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MAstroCatalog.h	(revision 9772)
@@ -0,0 +1,151 @@
+#ifndef MARS_MAstroCatalog
+#define MARS_MAstroCatalog
+
+#ifndef MARS_MVector3
+#include "MVector3.h"
+#endif
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+#ifndef MARS_MGMap
+#include <MGMap.h>
+#endif
+
+class MTime;
+class MObservatory;
+class TArrayI;
+class TGToolTip;
+
+class MAstroCatalog : public TObject
+{
+private:
+    Double_t   fLimMag;    // [1]   Limiting Magnitude
+    Double_t   fRadiusFOV; // [deg] Radius of Field of View
+
+    TGToolTip *fToolTip;   //! The tooltip currently displayed
+
+    void ShowToolTip(Int_t px, Int_t py, const char *txt);
+
+    TString FindToken(TString &line, Char_t tok=',');
+
+    Int_t   atoi(const TSubString &sub);
+    Float_t atof(const TSubString &sub);
+    Int_t   atoi(const TString &s);
+    Float_t atof(const TString &s);
+
+//#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,03)
+    Bool_t fPlainScreen;  //! Just a dummy!!!! ([Set,Is]Freezed)
+    Bool_t fNoToolTips;   //! Just a dummy!!!! ([Set,Is]Freezed)
+//#endif
+
+    virtual Int_t ConvertToPad(const TVector3 &w, TVector2 &v) const;
+    virtual void  AddPrimitives(TString o);
+    virtual void  SetRangePad(Option_t *o);
+
+    Int_t  Convert(const TRotation &rot, TVector2 &v) const;
+    void   Draw(const TVector2 &v0, const TRotation &rot, TArrayI &dx, TArrayI &dy, Int_t stepx, Int_t stepy, Int_t type);
+    void   DrawPrimitives(Option_t *o);
+    Bool_t DrawLine(const TVector2 &v0, Int_t dx, Int_t dy, const TRotation &rot, Int_t type);
+    void   DrawGrid(const TVector3 &v0, const TRotation &rot, Int_t type);
+    void   Paint(Option_t *o="");
+    Int_t  DistancetoPrimitive(Int_t px, Int_t py);
+
+protected:
+    enum {
+        kHasChanged   = BIT(15), // Display has changed
+        kGuiActive    = BIT(16), // GUI is interactive
+        kPlainScreen  = BIT(17), // View is a plain screen view
+        kMirrorX      = BIT(18), // Mirror display in X
+        kMirrorY      = BIT(19), // Mirror display in Y
+        kNoToolTips   = BIT(20), // suppress tooltips
+        kDrawingImage = BIT(21)  // just drawing into a bitmap
+    };
+
+    MGMap    fMapG;              //! A map with all gui primitives and tooltips
+
+    TList    fList;              // List of stars loaded
+    MVector3 fRaDec;             // pointing position
+
+    MObservatory *fObservatory;  // Possible obervatory location
+    MTime        *fTime;         // Possible observation time
+
+    TRotation AlignCoordinates(const TVector3 &v) const;
+    virtual TString GetPadTitle() const;
+    TRotation GetGrid(Bool_t local);
+    void      DrawStar(Double_t x, Double_t y, const TVector3 &v, Int_t col, const char *txt=0, Bool_t resize=kFALSE);
+    void      Update(Bool_t upd=kFALSE);
+
+    void      ExecuteEventKbd(Int_t keycode, Int_t keysym);
+    void      ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2);
+    char     *GetObjectInfo(Int_t px, Int_t py) const;
+
+public:
+    MAstroCatalog();
+    ~MAstroCatalog();
+
+    void SetTime(const MTime &time);
+    void SetObservatory(const MObservatory &obs);
+    void SetLimMag(Double_t mag) { fLimMag=mag; Update(); } // *MENU* *ARGS={mag=>fLimMag}
+    void SetRadiusFOV(Double_t deg)
+    {
+        //const Double_t max = TestBit(kPlainScreen) ? 90 : 55;
+        const Double_t max = TestBit(kPlainScreen) ? 180 : 90;
+        if (deg>max)
+            deg=max;
+        if (deg<1)
+            deg=1;
+
+        fRadiusFOV=deg;
+
+        Update();
+    } // *MENU* *ARGS={deg=>fRadiusFOV}
+    void SetRadiusFOV(Double_t pixsize, Double_t w, Double_t h)
+    {
+        // pixsize [arcsec/pixel]
+        // w       [pixel]
+        // h       [pixel]
+        const Double_t scale = TMath::Hypot(w, h)/2;
+        SetRadiusFOV(scale*pixsize/3600);
+    } // Set Radius of FOV using the pixsize [arcsec/pix], width and height [pixel] of image
+
+    void SetRaDec(Double_t ra, Double_t dec) { fRaDec.SetRaDec(ra, dec, 1); Update(); }
+    void SetRaDec(const TVector3 &v)         { fRaDec=v; Update(); }
+    void SetGuiActive(Bool_t b=kTRUE)        { b ? SetBit(kGuiActive) : ResetBit(kGuiActive); }
+
+    void   SetPlainScreen(Bool_t b=kTRUE)    { b ? SetBit(kPlainScreen) : ResetBit(kPlainScreen); Update(); } // *TOGGLE* *GETTER=IsPlainScreen
+    Bool_t IsPlainScreen() const             { return TestBit(kPlainScreen); }
+
+    void   SetNoToolTips(Bool_t b=kTRUE)     { b ? SetBit(kNoToolTips) : ResetBit(kNoToolTips); } // *TOGGLE* *GETTER=HasNoToolTips
+    Bool_t HasNoToolTips() const             { return TestBit(kNoToolTips); }
+
+    Double_t GetLimMag() const { return fLimMag; } // Get Limiting Magnitude
+    Double_t GetRadiusFOV() const { return fRadiusFOV; } // Get maximum radius of Field Of View
+
+    void Delete(Option_t *o="") { fList.Delete(); fMapG.Delete(); } // Delete list of stars
+
+    Int_t ReadXephem(TString catalog = "/usr/X11R6/lib/xephem/catalogs/YBS.edb");
+    Int_t ReadNGC2000(TString catalog = "ngc2000.dat");
+    Int_t ReadBSC(TString catalog = "bsc5.dat");
+    Int_t ReadHeasarcPPM(TString catalog = "heasarc_ppm.tdat", TString fout="");
+    Int_t ReadCompressed(TString catalog);
+    Bool_t AddObject(Float_t ra, Float_t dec, Float_t mag, TString name="");
+
+    void Print(Option_t *o="") const { fList.Print(); } // Print all stars
+
+    TList *GetList() { return &fList; } // Return list of stars
+
+    //void PaintImg(Int_t id=0, Option_t *o="");
+    void PaintImg(unsigned char *buf, int w=768, int h=576, Option_t *o=0);
+    void Draw(Option_t *o="");
+    void SetDrawOption(Option_t *option="")
+    {
+        TObject::SetDrawOption(option);
+        Update(kTRUE);
+    } //*MENU*
+
+    virtual void EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected=0);
+
+    ClassDef(MAstroCatalog, 1) // Display class for star catalogs
+};
+
+#endif
Index: /tags/Mars-V0.9/mastro/MAstroSky2Local.cc
===================================================================
--- /tags/Mars-V0.9/mastro/MAstroSky2Local.cc	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MAstroSky2Local.cc	(revision 9772)
@@ -0,0 +1,140 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MAstroSky2Local
+// ---------------
+//
+// Rotation Matrix to convert sky coordinates to ideal local coordinates
+// for example:
+//
+//   const Double_t ra  = MAstro::Hms2Rad(5, 34, 31.9);
+//   const Double_t dec = MAstro::Dms2Rad(22, 0, 52.0);
+//
+//   MTime time;
+//   time.Set(2004, 1, 26, 00, 20, 00);
+//
+//   MObservatory obs(MObservatory::kMagic1);
+//
+//   TVector3 v;
+//   v.SetMagThetaPhi(1, TMath::Pi()/2-dec, ra);
+//
+//   v *= MAstroSky2Local(time, obs);
+//
+//   Double_t azimuth   = v.Phi();
+//   Double_t zdistance = v.Theta();
+//
+// To get the inverse matrix for an inverse transformation you can use:
+//
+//   MAstroSky2Local::Invert()
+//
+// or simply do:
+//
+//   v *= MAstroSky2Local(time, obs).Inverse();
+//
+// Reminder: This tranformation only does a simple coordinate
+//           transformation. It completely ignores all other atrometric
+//           effects, like nutation, abberation, precission, ...
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MAstroSky2Local.h"
+
+#include "MAstro.h"
+#include "MTime.h"
+#include "MObservatory.h"
+
+using namespace std;
+
+ClassImp(MAstroSky2Local);
+
+// --------------------------------------------------------------------------
+//
+// Initialize the rotation matrix R as:
+//
+//   R = A*B*C*D
+//
+// with
+//
+//       |1  0  0|
+//   A = |0 -1  0|    (Change counting direction of rotation angle)
+//       |0  0  1|
+//
+//   B = RotZ(r1)     (Change rotation angle such, that phi=0 is identical
+//                     for both coordinate systems)
+//
+//   C = RotY(r2)     (Make zenith and sky pole the same point)
+//
+//   D = RotZ(180deg) (Align rottaion angle to N=0, E=90)
+//
+// with
+//
+//   r1 = gmst + longitude   with   gmst fraction of day, see MTime::GetGmst
+//                                  logitude of observers location
+//
+//   r2 = latitude-90deg     with   latitude of observers location
+//
+void MAstroSky2Local::Init(Double_t gmst, const MObservatory &obs)
+{
+    RotateZ(gmst + obs.GetElong());
+    RotateY(obs.GetPhi()-TMath::Pi()/2);
+    RotateZ(TMath::Pi());
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize MAstroSky2Local for a given time an a defined observatory
+// For more information see class description
+// For more information about gmst see MTime::GetGmst()
+//
+MAstroSky2Local::MAstroSky2Local(Double_t gmst, const MObservatory &obs) : TRotation(1, 0, 0, 0, -1, 0, 0, 0, 1)
+{
+    Init(gmst, obs);
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize MAstroSky2Local for a given time an a defined observatory
+// For more information see class description
+//
+MAstroSky2Local::MAstroSky2Local(const MTime &t, const MObservatory &obs) : TRotation(1, 0, 0, 0, -1, 0, 0, 0, 1)
+{
+    Init(t.GetGmst(), obs);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the corresponding rotation angle of the sky coordinate system
+// seen with an Alt/Az telescope.
+//
+// For more information see MAstro::RotationAngle
+//
+Double_t MAstroSky2Local::RotationAngle(Double_t ra, Double_t dec) const
+{
+    TVector3 v;
+    v.SetMagThetaPhi(1, TMath::Pi()/2-dec, ra);
+    v *= *this;
+
+    return MAstro::RotationAngle(ZZ(), XZ(), v.Theta(), v.Phi());
+}
Index: /tags/Mars-V0.9/mastro/MAstroSky2Local.h
===================================================================
--- /tags/Mars-V0.9/mastro/MAstroSky2Local.h	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MAstroSky2Local.h	(revision 9772)
@@ -0,0 +1,25 @@
+#ifndef MARS_MAstroSky2Local
+#define MARS_MAstroSky2Local
+
+#ifndef ROOT_TRotation
+#include <TRotation.h>
+#endif
+
+class MTime;
+class MObservatory;
+
+class MAstroSky2Local : public TRotation
+{
+private:
+    void Init(Double_t gmst, const MObservatory &obs);
+
+public:
+    MAstroSky2Local(Double_t gmst,  const MObservatory &obs);
+    MAstroSky2Local(const MTime &t, const MObservatory &obs);
+
+    Double_t RotationAngle(Double_t ra, Double_t dec) const;
+
+    ClassDef(MAstroSky2Local, 1) // Rotation Matrix to convert sky coordinates to ideal local coordinates
+};
+
+#endif
Index: /tags/Mars-V0.9/mastro/MObservatory.cc
===================================================================
--- /tags/Mars-V0.9/mastro/MObservatory.cc	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MObservatory.cc	(revision 9772)
@@ -0,0 +1,164 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner  10/2002 <mailto:magicsoft@rwagner.de>
+!   Author(s): Thomas Bretz   2/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MObservatory
+//
+// BE EXTREMLY CARFEFULL CHANGING THIS CLASS! THE TRACKING SYSTEM IS BASED
+// ON IT!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MObservatory.h"
+
+#include <TVector3.h>
+
+#include "MTime.h"
+#include "MAstro.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MObservatory);
+
+using namespace std;
+
+void MObservatory::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MObservatory";
+    fTitle = title ? title : "Storage container for coordinates of an observatory";   
+}
+
+MObservatory::MObservatory(const char *name, const char *title)
+{
+    Init(name, title);
+
+    SetLocation(kMagic1);
+}
+
+MObservatory::MObservatory(LocationName_t key, const char *name, const char *title)
+{
+    Init(name, title);
+
+    SetLocation(key);
+}
+
+// --------------------------------------------------------------------------
+//
+// BE EXTREMLY CARFEFULL CHANGING THIS CLASS! THE TRACKING SYSTEM IS BASED
+// ON IT!
+//
+void MObservatory::SetLocation(LocationName_t name)
+{
+    switch (name)
+    {
+        // BE EXTREMLY CARFEFULL CHANGING THIS CLASS!
+        // THE TRACKING SYSTEM IS BASED ON IT!
+    case kMagic1:
+        // Values taken from the GPS Receiver (avg 24h)
+        // on 29/04/2004 at 17h30 in the counting house
+        fLatitude  = MAstro::Dms2Rad(28, 45, 42.462, '+');
+        fLongitude = MAstro::Dms2Rad(17, 53, 26.525, '-');
+        fHeight    = 2199.4; // m
+        fObservatoryName = "Observatorio del Roque de los Muchachos (Magic1)";
+        break;
+
+    case kWuerzburgCity:
+        fLatitude  = MAstro::Dms2Rad(51, 38, 48.0);
+        fLongitude = MAstro::Dms2Rad( 9, 56, 36.0);
+        fHeight    = 300;
+        fObservatoryName = "Wuerzburg City";
+        break;
+    }
+
+    fSinLatitude = TMath::Sin(fLatitude);
+    fCosLatitude = TMath::Cos(fLatitude);
+}
+
+void MObservatory::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << underline << fObservatoryName << ":" << endl;
+    *fLog << "Latitude:  " << TMath::Abs(fLatitude*kRad2Deg)  << " deg " << (fLatitude  > 0 ? "W" : "E") << endl;
+    *fLog << "Longitude: " << TMath::Abs(fLongitude*kRad2Deg) << " deg " << (fLongitude < 0 ? "N" : "S") << endl;
+    *fLog << "Height:    " << fHeight << "m" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the corresponding rotation angle of the sky coordinate system
+// seen with an Alt/Az telescope.
+//
+// For more information see MAstro::RotationAngle
+//
+void MObservatory::RotationAngle(Double_t theta, Double_t phi, Double_t &sin, Double_t &cos) const
+{
+    MAstro::RotationAngle(fSinLatitude, fCosLatitude, theta, phi, sin, cos);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the corresponding rotation angle of the sky coordinate system
+// seen with an Alt/Az telescope.
+//
+// For more information see MAstro::RotationAngle
+//
+Double_t MObservatory::RotationAngle(Double_t theta, Double_t phi) const
+{
+    return MAstro::RotationAngle(fSinLatitude, fCosLatitude, theta, phi);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Setup the observatory location from resource file:
+//    MObservatory.Name: Magic1, WuerzburgCity
+//
+Int_t MObservatory::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (IsEnvDefined(env, prefix, "Name", print))
+    {
+        TString name = GetEnvValue(env, prefix, "Name", "Magic1");
+        name = name.Strip(TString::kBoth);
+
+        if (name==(TString)"Magic1")
+        {
+            SetLocation(kMagic1);
+            return kTRUE;
+        }
+
+        if (name==(TString)"WuerzburgCity")
+        {
+            SetLocation(kWuerzburgCity);
+            return kTRUE;
+        }
+
+        *fLog << err << "MObservatory::ReadEnv - ERROR: Observatory " << name << " unknown." << endl;
+        return kERROR;
+    }
+
+    return kFALSE;
+
+}
Index: /tags/Mars-V0.9/mastro/MObservatory.h
===================================================================
--- /tags/Mars-V0.9/mastro/MObservatory.h	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MObservatory.h	(revision 9772)
@@ -0,0 +1,79 @@
+#ifndef MARS_MObservatory
+#define MARS_MObservatory
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MTime;
+
+class MObservatory : public MParContainer
+{
+public:
+    enum LocationName_t
+    {
+        kMagic1,
+        kWuerzburgCity
+    };
+
+private:
+    LocationName_t fObservatoryKey;  //!
+
+    TString  fObservatoryName;       //! Name of the observatory
+
+    Double_t fLongitude;             //! [rad] Longitude of observatory (+ east)
+    Double_t fLatitude;              //! [rad] Latitude of observatory (+ north)
+
+    Double_t fSinLatitude;           //! Sin component for faster access
+    Double_t fCosLatitude;           //! Cos component for faster access
+
+    Double_t fHeight;                //! [m] height of observatory
+
+    void Init(const char *name, const char *title);
+
+public:
+    MObservatory(const char *name=NULL, const char *title=NULL);
+    MObservatory(LocationName_t key, const char *name=NULL, const char *title=NULL);
+
+    void Copy(TObject &obj) const
+    {
+        MObservatory &obs = (MObservatory&)obj;
+        obs.fObservatoryName = fObservatoryName;
+        obs.fLongitude = fLongitude;
+        obs.fLatitude = fLatitude;
+        obs.fSinLatitude = fSinLatitude;
+        obs.fCosLatitude = fCosLatitude;
+        obs.fHeight = fHeight;
+    }
+
+    void SetLocation(LocationName_t name);
+
+    void Print(Option_t *o=0) const;
+
+    const TString &GetObservatoryName() const { return fObservatoryName; }
+
+    Double_t GetLatitudeDeg() const     { return fLatitude*kRad2Deg; }  //[deg]
+    Double_t GetLongitudeDeg() const    { return fLongitude*kRad2Deg; } //[deg]
+
+    Double_t GetLatitudeRad() const     { return fLatitude; }           //[rad]
+    Double_t GetLongitudeRad() const    { return fLongitude; }          //[rad]
+
+    Double_t GetPhi() const             { return fLatitude; }           //[rad]
+    Double_t GetElong() const           { return fLongitude; }          //[rad]
+
+    Double_t GetSinPhi() const          { return fSinLatitude; }
+    Double_t GetCosPhi() const          { return fCosLatitude; }
+
+    Double_t GetHeight() const          { return fHeight; }
+
+    void RotationAngle(Double_t theta, Double_t phi, Double_t &sin, Double_t &cos) const;
+    Double_t RotationAngle(Double_t theta, Double_t phi) const;
+
+    LocationName_t GetObservatoryKey() const { return fObservatoryKey; }
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MObservatory, 0) // class storing observatory locations
+};
+
+#endif
Index: /tags/Mars-V0.9/mastro/MVector3.cc
===================================================================
--- /tags/Mars-V0.9/mastro/MVector3.cc	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MVector3.cc	(revision 9772)
@@ -0,0 +1,64 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 03/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MVector3
+//  ========
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MVector3.h"
+
+#include <iostream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MVector3);
+
+using namespace std;
+
+void MVector3::WriteBinary(ostream &out) const
+{
+    const Double_t t = Theta();
+    const Double_t p = Phi();
+    const Float_t  m = Mag();
+    out.write((char*)&t, 8);
+    out.write((char*)&p, 8);
+    out.write((char*)&m, 4);
+    out << fName << endl;
+}
+
+void MVector3::ReadBinary(istream &in)
+{
+    Double_t t, p;
+    Float_t  m;
+
+    in.read((char*)&t, 8);
+    in.read((char*)&p, 8);
+    in.read((char*)&m, 4);
+    fName.ReadLine(in);
+
+    SetMagThetaPhi(m, t, p);
+}
Index: /tags/Mars-V0.9/mastro/MVector3.h
===================================================================
--- /tags/Mars-V0.9/mastro/MVector3.h	(revision 9772)
+++ /tags/Mars-V0.9/mastro/MVector3.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MVector3
+#define MARS_MVector3
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+class MVector3 : public TVector3
+{
+private:
+    enum VectorType_t
+    {
+        kIsInvalid,
+        kIsRaDec,
+        kIsZdAz,
+        kIsAltAz,
+        kIsArbitrary
+    };
+
+    VectorType_t fType;
+
+    TString fName;
+
+    void SetThetaPhiMag(Double_t theta, Double_t phi, Double_t mag)
+    {
+        SetMagThetaPhi(TMath::Power(10, -mag/2.5), theta, phi);
+    }
+
+public:
+    MVector3() { fType=kIsInvalid; }
+    MVector3(Double_t theta, Double_t phi, Double_t mag=0)
+    {
+        SetThetaPhiMag(theta, phi, mag);
+        fType=kIsArbitrary;
+    }
+    MVector3(const TVector3 &v3) : TVector3(v3) { fType=kIsArbitrary; }
+    Double_t Magnitude() const { return -2.5*TMath::Log10(Mag()); }
+
+    void SetRaDec(Double_t ra, Double_t dec, Double_t mag=0)
+    {
+        fType = kIsRaDec;
+        SetThetaPhiMag(TMath::Pi()/2-dec, ra, mag);
+    }
+    void SetName(const TString &str) { fName = str.Strip(TString::kBoth); }
+    void SetZdAz(Double_t zd, Double_t az, Double_t mag=0)
+    {
+        fType = kIsZdAz;
+        SetThetaPhiMag(zd, az, mag);
+    }
+    void SetAltAz(Double_t alt, Double_t az, Double_t mag=0)
+    {
+        fType = kIsAltAz;
+        SetThetaPhiMag(TMath::Pi()/2-alt, az, mag);
+    }
+
+    const char *GetName() const { return fName; }
+
+    void WriteBinary(ostream &out) const;
+    void ReadBinary(istream &in);
+
+    ClassDef(MVector3, 1) // A specialized TVector3 storing a star-name
+};
+
+#endif
Index: /tags/Mars-V0.9/mastro/Makefile
===================================================================
--- /tags/Mars-V0.9/mastro/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mastro/Makefile	(revision 9772)
@@ -0,0 +1,50 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Astro
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES =  -I. -I../mbase -I../mgeom -I../mtemp -I../mstarcam
+# mgeom (MAstroCamera): MGeomCam, MGeomMirror
+
+SRCFILES = MVector3.cc \
+	   MAstro.cc \
+	   MAstroSky2Local.cc \
+	   MAstroCatalog.cc \
+           MAstroCamera.cc \
+           MObservatory.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mbadpixels/BadPixelsIncl.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/BadPixelsIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/BadPixelsIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mbadpixels/BadPixelsLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/BadPixelsLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/BadPixelsLinkDef.h	(revision 9772)
@@ -0,0 +1,19 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MBadPixelsPix+;
+#pragma link C++ class MBadPixelsCam+;
+
+#pragma link C++ class MBadPixelsIntensityCam+;
+
+#pragma link C++ class MBadPixelsCalc+;
+#pragma link C++ class MBadPixelsTreat+;
+#pragma link C++ class MBadPixelsMerge+;
+
+#pragma link C++ class MMcBadPixelsSet+;
+#pragma link C++ class MHBadPixels+;
+
+#endif
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsCalc.cc
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsCalc.cc	(revision 9772)
@@ -0,0 +1,314 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2004 <mailto:tbretz@astro.uni.wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MBadPixelsCalc
+//
+//
+// The job of the task is to determin bad pixels event-wise. This must be
+// redone for each event. This particular task is for what is explained
+// below.
+// New algorithms may enter new tasks.
+//
+//
+// Check the pedestal RMS of every pixel with respect to the mean
+// pedestal RMS of the camera.
+//
+// The pixels can be set as blind if the pedestalRMS is too big or 0.
+//
+// If you don't want to use this option set the PedestalLevel<=0;
+//
+//     MBadPixelsCalc calc;
+//     calc.SetPedestalLevel(-1);
+//
+//
+//  Input Containers:
+//   [MPedPhotCam]
+//   [MGeomCam]
+//
+//  Output Containers:
+//   MBadPixels
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsCalc.h"
+
+#include <TEnv.h>
+
+#include "MArrayI.h"
+#include "MArrayD.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+//#include "MSigmabar.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MBadPixelsCalc);
+
+using namespace std;
+
+static const TString gsDefName  = "MBadPixelsCalc";
+static const TString gsDefTitle = "Find hot spots (star, broken pixels, etc)";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MBadPixelsCalc::MBadPixelsCalc(const char *name, const char *title)
+    : fPedestalLevel(3), fPedestalLevelVariance(-1), fNamePedPhotCam("MPedPhotCam")
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MBadPixelsCalc::PreProcess (MParList *pList)
+{
+    fBadPixels = (MBadPixelsCam*)pList->FindCreateObj(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+        return kFALSE;
+
+    if (fPedestalLevel>0)
+    {
+        fPedPhotCam = (MPedPhotCam*)pList->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+        if (!fPedPhotCam)
+        {
+	  *fLog << err << fNamePedPhotCam << "[MPedPhotCam] not found... aborting." << endl;
+            return kFALSE;
+        }
+
+        fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+        if (!fGeomCam)
+        {
+            *fLog << err << "MGeomCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    *fLog << inf << "Name of MPedPhotCam to get pedestal rms from: " << fNamePedPhotCam << endl;
+    if (fPedestalLevel)
+        *fLog << "Checking mean 'pedestal rms' against absolute value with level " << fPedestalLevel << endl;
+    if (fPedestalLevelVariance)
+        *fLog << "Checking mean 'pedestal rms' against its variance with level " << fPedestalLevelVariance << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check the pedestal RMS of every pixel with respect to the mean pedestal RMS 
+// of the camera (Sigmabar).
+//
+// The pixels can be set as blind if the pedestalRMS is too big or 0.
+//
+// If you don't want to use this option set the PedestalLevel<=0;
+//
+//     MBadPixelsCalc calc;
+//     calc.SetPedestalLevel(-1);
+/*
+void MBadPixelsCalc::CheckPedestalRMS() const
+{
+    const Int_t entries = fPedPhotCam->GetSize();
+
+    const Float_t meanPedRMS = fSigmabar->GetSigmabar();
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        //
+        // get pixel as entry from list
+        //
+        const Double_t nratio    = fGeomCam->GetPixRatio(i);
+        const Double_t pixPedRms = (*fPedPhotCam)[i].GetRms();
+
+        if (pixPedRms*nratio > fPedestalLevel * meanPedRMS || pixPedRms == 0)
+            (*fBadPixels)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+    }
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Check the pedestal Rms of the pixels: compute with 2 iterations the mean 
+// for inner and outer pixels. Set as blind the pixels with too small or 
+// too high pedestal Rms with respect to the mean.
+// 
+Bool_t MBadPixelsCalc::CheckPedestalRms() const
+{
+    const Int_t entries = fPedPhotCam->GetSize();
+
+    const Int_t na = fGeomCam->GetNumAreas();
+
+    MArrayD meanrms(na);
+    MArrayI npix(na);
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        const Double_t rms = (*fPedPhotCam)[i].GetRms();
+
+        if (rms<=0 || rms>=200*fGeomCam->GetPixRatioSqrt(i))
+            continue;
+
+        const Byte_t aidx = (*fGeomCam)[i].GetAidx();
+
+        meanrms[aidx] += rms;
+        npix[aidx]++;
+    }
+
+    //if no pixel has a minimum signal, return
+    for (int i=0; i<na; i++)
+    {
+        if (npix[i]==0 || meanrms[i]==0)
+        {
+            //fErrors[1]++;          //no valid Pedestals Rms
+            return kFALSE;
+        }
+
+        meanrms[i] /= npix[i];
+        npix[i]=0;
+    }
+
+    MArrayD meanrms2(na);
+    MArrayD varrms2(na);
+    for (Int_t i=0; i<entries; i++)
+    {
+        const Double_t rms = (*fPedPhotCam)[i].GetRms();
+        const Byte_t  aidx = (*fGeomCam)[i].GetAidx();
+
+        //Calculate the corrected means:
+
+        if (rms<=0.5*meanrms[aidx] || rms>=1.5*meanrms[aidx])
+            continue;
+
+        meanrms2[aidx] += rms;
+        varrms2 [aidx] += rms*rms;
+        npix[aidx]++;
+    }
+
+    //if no pixel has a minimum signal, return
+    MArrayD lolim1(na), lolim2(na); // Precalcualtion of limits
+    MArrayD uplim1(na), uplim2(na); // for speeed reasons
+    for (int i=0; i<na; i++)
+    {
+        if (npix[i]==0 || meanrms2[i]==0)
+        {
+            //fErrors[1]++;          //no valid Pedestals Rms
+            return kFALSE;
+        }
+
+        meanrms2[i] /= npix[i];
+
+        if (fPedestalLevel>0)
+        {
+            lolim1[i]  = meanrms2[i]/fPedestalLevel;
+            uplim1[i]  = meanrms2[i]*fPedestalLevel;
+        }
+
+        if (fPedestalLevelVariance>0)
+        {
+            varrms2[i] /= npix[i];
+            varrms2[i]  = TMath::Sqrt(varrms2[i]-meanrms2[i]*meanrms2[i]);
+
+            lolim2[i]   = meanrms2[i]-fPedestalLevelVariance*varrms2[i];
+            uplim2[i]   = meanrms2[i]+fPedestalLevelVariance*varrms2[i];
+        }
+    }
+
+    Int_t bads = 0;
+
+    //Blind the Bad Pixels
+    for (Int_t i=0; i<entries; i++)
+    {
+        const Double_t rms = (*fPedPhotCam)[i].GetRms();
+        const Byte_t  aidx = (*fGeomCam)[i].GetAidx();
+
+        if ((fPedestalLevel<0         || (rms>lolim1[aidx] && rms<=uplim1[aidx])) &&
+            (fPedestalLevelVariance<0 || (rms>lolim2[aidx] && rms<=uplim2[aidx])))
+            continue;
+
+        (*fBadPixels)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+        bads++;
+    }
+
+
+    // Check if the number of pixels to blind is > 60% of total number of pixels
+    //
+    //    if (bads>0.6*entries)
+    //    {
+    //    fErrors[2]++;
+    //    return kFALSE;
+    //    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MBadPixelsCalc::Process()
+{
+    if (fPedestalLevel>0 || fPedestalLevelVariance)
+    {
+        CheckPedestalRms();
+        //fPedPhotCam->ReCalc(*fGeomCam, fBadPixels);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MBadPixelsCalc.PedestalLevel:         3.0
+//   MBadPixelsCalc.PedestalLevelVariance: 3.0
+//
+Int_t MBadPixelsCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "PedestalLevel", print))
+    {
+        rc = kTRUE;
+        SetPedestalLevel(GetEnvValue(env, prefix, "PedestalLevel", fPedestalLevel));
+    }
+
+    if (IsEnvDefined(env, prefix, "PedestalLevelVariance", print))
+    {
+        rc = kTRUE;
+        SetPedestalLevelVariance(GetEnvValue(env, prefix, "PedestalLevelVariance", fPedestalLevelVariance));
+    }
+    return rc;
+}
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsCalc.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsCalc.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MBadPixelsCalc
+#define MARS_MBadPixelsCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MBadPixelsCam;
+class MGeomCam;
+class MPedPhotCam;
+
+class MBadPixelsCalc : public MTask
+{
+private:
+    MGeomCam      *fGeomCam;    //! Input container storing the pixel sizes
+    MPedPhotCam   *fPedPhotCam; //! Input container storing the pedestal and pedestal rms of all pixels
+    MBadPixelsCam *fBadPixels;  //! Output container holding the bad pixels
+
+    Float_t fPedestalLevel;
+    Float_t fPedestalLevelVariance;
+
+    TString fNamePedPhotCam; // name of the 'MPedPhotCam' container
+   
+    //    void CheckPedestalRMS() const;
+    Bool_t CheckPedestalRms() const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    MBadPixelsCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetPedestalLevel(Float_t f)         { fPedestalLevel=f; }
+    void SetPedestalLevelVariance(Float_t f) { fPedestalLevelVariance=f; }
+    void SetNamePedPhotCam(const char *name) { fNamePedPhotCam = name; }
+
+    ClassDef(MBadPixelsCalc, 1) // Task to find bad pixels (star, broken pixels, etc)
+}; 
+
+#endif
+
+
+
+
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsCam.cc
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsCam.cc	(revision 9772)
@@ -0,0 +1,755 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Markus Gaug  3/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MBadPixelsCam                           
+//
+//
+// Storage container to store bad pixel of the camera...
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsCam.h"
+
+#include <iostream>
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MBadPixelsPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MBadPixelsCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MBadPixelsCam::MBadPixelsCam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MBadPixelsCam";
+    fTitle = title ? title : "Storage container to store bad pixel information";
+
+    fArray = new TClonesArray("MBadPixelsPix", 1);
+}
+
+MBadPixelsCam::MBadPixelsCam(const MBadPixelsCam &cam)
+{
+    fName  = "MBadPixelsCam";
+    fTitle = "Storage container to store bad pixel information";
+
+    fArray = new TClonesArray("MBadPixelsPix", 1);
+    cam.Copy(*this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the array conatining the bad pixel information
+//
+MBadPixelsCam::~MBadPixelsCam()
+{
+    delete fArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MBadPixelsCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MBadPixelsCam
+//
+Int_t MBadPixelsCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MBadPixelsCam::Copy(TObject &object) const
+{
+    MBadPixelsCam &cam = (MBadPixelsCam&)object;
+
+    const Int_t n = GetSize();
+
+    if (n==0)
+        return;
+
+    cam.InitSize(n);
+    for (int i=0; i<n; i++)
+        (*this)[i].Copy(cam[i]);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MBadPixelsPix &MBadPixelsCam::operator[](Int_t i)
+{
+    return *static_cast<MBadPixelsPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MBadPixelsPix &MBadPixelsCam::operator[](Int_t i) const
+{
+    return *static_cast<MBadPixelsPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Merge two MBadPixelsCam together, see also MBadPixelsPix::Merge
+//
+void MBadPixelsCam::Merge(const MBadPixelsCam &cam)
+{
+    const Int_t n = cam.GetSize();
+    if (n==0)
+    {
+        *fLog << warn << "MBadPixelsCam::Merge: Container empty." << endl;
+        return;
+    }
+
+    if (GetSize()==0)
+        InitSize(n);
+
+    if (n!=GetSize())
+    {
+        *fLog << warn << "MBadPixelsCam::Merge: Size mismatch... ignored." << endl;
+        return;
+    }
+
+    for (int i=0; i<n; i++)
+        (*this)[i].Merge(cam[i]);
+}
+
+// --------------------------------------------------------------------------
+//
+// Clear the contents of all bad pixels (set=0 means Ok)
+//
+void MBadPixelsCam::Clear(Option_t *o)
+{
+    fArray->ForEach(TObject, Clear)();
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset event depending bits
+//
+void MBadPixelsCam::Reset()
+{
+    fArray->ForEach(MParContainer, Reset)();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the number of pixels with the given type-flags.
+//
+// The second argument aidx is the area index (see MGeomCam, MGeomPix)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type, const MGeomCam *geom, Int_t aidx) const
+{
+    const UInt_t n = GetSize();
+
+    if (aidx>=0 && geom->GetNumPixels()!=n)
+    {
+        *fLog << err << GetDescriptor() << "ERROR - Geometry (" << geom->ClassName() << ") size mismatch!" << endl;
+        return -1;
+    }
+
+    Short_t rc = 0;
+    for (UInt_t i=0; i<n; i++)
+    {
+        if (aidx>=0 && (*geom)[i].GetAidx()!=aidx)
+            continue;
+
+        if ((*this)[i].IsUnsuitable(type))
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Counts the number of neighbors matching NOT UnsuitableType type
+//
+Short_t MBadPixelsCam::GetNumSuitableNeighbors(MBadPixelsPix::UnsuitableType_t type, const MGeomPix &pix) const
+{
+    const Int_t n2 = pix.GetNumNeighbors();
+
+    Int_t cnt=0;
+    for (int j=0; j<n2; j++)
+    {
+        const Int_t id2 = pix.GetNeighbor(j);
+        if (!(*this)[id2].IsUnsuitable(type))
+            cnt++;
+    }
+
+    return cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the number of pixels which are - under no circumstances -
+// interpolatable, called isolated. This means that a pixel (its own status
+// doesn't matter) has less than two reliable neighbor pixels.
+//
+// The second argument aidx is the area index (see MGeomCam, MGeomPix)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumIsolated(MBadPixelsPix::UnsuitableType_t type, const MGeomCam &geom, Int_t aidx) const
+{
+    const Int_t n = geom.GetNumPixels();
+
+    if (n!=GetSize())
+    {
+        *fLog << err << GetDescriptor() << "ERROR - Geometry (" << geom.ClassName() << ") size mismatch!" << endl;
+        return -1;
+    }
+
+    Short_t rc = 0;
+    for (int i=0; i<n; i++)
+    {
+        const MGeomPix &pix = geom[i];
+        if (aidx>=0 && pix.GetAidx()!=aidx)
+            continue;
+
+        if (GetNumSuitableNeighbors(type, pix)<2)
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a helper function which calculates the size of a single cluster
+// by iterative calling.
+//
+// If a pixel matches the criterias the counter is increased by 1 and
+// the function is called for all its neighbors. If
+//
+// The second argument aidx is the area index (see MGeomCam, MGeomPix)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type, TObjArray &list, Int_t idx, Int_t aidx) const
+{
+    const MGeomPix *pix = (MGeomPix*)list[idx];
+    if (!pix)
+        return 0;
+
+    if (GetNumSuitableNeighbors(type, *pix)>1)
+        return 0;
+
+    if (aidx>=0 && pix->GetAidx()!=aidx)
+        return 1;
+
+    list.RemoveAt(idx);
+
+    Short_t cnt = 1;
+    const Int_t n = pix->GetNumNeighbors();
+    for (int i=0; i<n; i++)
+        cnt += GetNumMaxCluster(type, list, pix->GetNeighbor(i), aidx);
+
+    return cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the size of the biggest cluster with the given USuitableType
+// type and the given area index.
+//
+// The second argument aidx is the area index (see MGeomCam, MGeomPix)
+// The default (or any value less than 0) means: all
+//
+// Returns -1 if the geometry doesn't match.
+//
+Short_t MBadPixelsCam::GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type, const MGeomCam &geom, Int_t aidx) const
+{
+    const Int_t n = geom.GetNumPixels();
+
+    if (n!=GetSize())
+    {
+        *fLog << err << GetDescriptor() << "ERROR - Geometry (" << geom.ClassName() << ") size mismatch!" << endl;
+        return -1;
+    }
+
+    TObjArray list(n);
+    for (int i=0; i<n; i++)
+        list.AddAt(&geom[i], i);
+
+    Short_t max = 0;
+    for (int i=0; i<n; i++)
+        max = TMath::Max(GetNumMaxCluster(type, list, i, aidx), max);
+
+    return max;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of all bad pixels
+//
+void MBadPixelsCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  *fLog << "Pixels without problems:" << endl;
+    
+  Int_t count = 0;
+  Int_t full  = 0;
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if (!(*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          *fLog << i << " ";
+	  full++;
+          count ++;
+        }
+      
+      if (count == 0)
+	continue;
+      
+      if (!(full % 25))
+	{
+	  full = 0;
+	  *fLog << endl;
+	}
+    }
+  *fLog << endl;
+  *fLog << count << " normal pixels" << endl;
+  *fLog << endl;
+
+  *fLog << "Pixels unsuited for the whole run:" << endl;
+  
+  full  = 0;
+  count = 0;
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          *fLog << i << " ";
+	  full++;
+          count ++;
+        }
+      
+      if (count == 0)
+        continue;
+      
+      if (!(full % 25))
+	{
+	  full = 0;
+	  *fLog << endl;
+	}
+    }
+
+  *fLog << endl;
+  *fLog << count << " unsuited pixels per run :-(" << endl;
+  *fLog << endl;
+  
+  *fLog << "Pixels unsuited for this event:" << endl;
+
+  full  = 0;
+  count = 0;
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableEvt))
+        {
+          *fLog << i << " ";
+	  full++;
+          count ++;
+        }
+      
+      if (count == 0)
+        continue;
+      
+      if (!(full % 25))
+	{
+	  full  = 0;
+	  *fLog << endl;
+	}
+    }
+
+  *fLog << endl;
+  *fLog << count << " unsuited pixels per event :-(" << endl;
+  *fLog << endl;
+  
+  full  = 0;
+  count = 0;
+  
+  *fLog << all << "Pixels unreliable for the whole run:" << endl;
+  
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+        {
+          *fLog << i << " ";
+	  full++;
+          count ++;
+        }
+      
+      if (count == 0)
+        continue;
+      
+      if (!(full % 25))
+	{
+	  full  = 0;
+	  *fLog << endl;
+	}
+    }
+  
+  *fLog << endl;
+  *fLog << count << " unreliable pixels :-(" << endl;
+  *fLog << endl;
+  *fLog << endl;
+  *fLog << all << "Unsuited pixels statistics:" << endl;
+  *fLog << endl;
+  
+  PrintBadPixels(MBadPixelsPix::kChargeIsPedestal,"Signal smaller 3 Pedestal RMS");
+  PrintBadPixels(MBadPixelsPix::kChargeSigmaNotValid,"Signal smaller 3 Pedestal RMS");
+  PrintBadPixels(MBadPixelsPix::kChargeRelErrNotValid,"Signal Rel. error too large");
+  PrintBadPixels(MBadPixelsPix::kLoGainSaturation,"Low Gain Saturation");
+  PrintBadPixels(MBadPixelsPix::kMeanTimeInFirstBin,"Mean Arr. Time In First Extraction Bin");
+  PrintBadPixels(MBadPixelsPix::kMeanTimeInLast2Bins,"Mean Arr. Time In Last 2 Extraction Bins");
+  PrintBadPixels(MBadPixelsPix::kDeviatingNumPhes,"Deviating Number of Photo-electrons");
+  PrintBadPixels(MBadPixelsPix::kDeviatingNumPhots,"Deviating Number of Photons");
+  PrintBadPixels(MBadPixelsPix::kHiGainOverFlow,"High-Gain Histogram Overflow");
+  PrintBadPixels(MBadPixelsPix::kLoGainOverFlow,"Low-Gain Histogram Overflow");
+
+  *fLog << endl;
+  *fLog << all << "Unreliable pixels statistics:" << endl;
+  *fLog << endl;
+  
+  PrintBadPixels(MBadPixelsPix::kChargeSigmaNotValid,"Signal Sigma smaller Pedestal RMS");
+  PrintBadPixels(MBadPixelsPix::kHiGainNotFitted    ,"High Gain Signals could not be fitted");
+  PrintBadPixels(MBadPixelsPix::kLoGainNotFitted    ,"Low  Gain Signals could not be fitted");
+  PrintBadPixels(MBadPixelsPix::kRelTimeNotFitted   ,"Relative Arr. Times could not be fitted");
+  PrintBadPixels(MBadPixelsPix::kHiGainOscillating  ,"High Gain Signals Oscillation");
+  PrintBadPixels(MBadPixelsPix::kLoGainOscillating  ,"Low  Gain Signals Oscillation");
+  PrintBadPixels(MBadPixelsPix::kRelTimeOscillating ,"Relative Arr. Times Oscillation");
+  PrintBadPixels(MBadPixelsPix::kDeviatingFFactor   ,"Deviating global F-Factor");
+}
+
+void MBadPixelsCam::PrintBadPixels( MBadPixelsPix::UncalibratedType_t typ, const char *text) const 
+{
+
+
+  *fLog << "Pixels with " << text << ": " << endl;
+  UInt_t count = 0;
+  UInt_t full  = 0;
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      if ((*this)[i].IsUncalibrated(typ))
+        {
+          *fLog << i << " ";
+	  full++;
+          count++;
+        }
+      
+      if (count == 0)
+        continue;
+      
+      if (!(full % 25))
+	{
+	  full  = 0;
+	  *fLog << endl;
+	}
+    }
+  
+  *fLog << endl;
+  *fLog << Form("%3i",count) << " pixels in total " << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read from an ascii file of the format:
+//    pixel1 pixel2 pixel3 pixel4
+// while pixel1,2,3,4 are the pixel indices used in the software.
+//
+// To read the pixels corresponding to a given run you can give run!=0
+// and a file of the format:
+//   1234: 17 193 292
+//   1235: 17 193 292 293
+//
+void MBadPixelsCam::AsciiRead(istream &fin, UInt_t run=0)
+{
+
+    Int_t len;
+    TString str;
+
+    while (1)
+    {
+        str.ReadLine(fin);
+
+        if (str.IsNull())
+          {
+            *fLog << warn << GetDescriptor() 
+                  << ": Cannot apply AsciiRead from istream pointer. "
+                  << "Either file does not exist or file is empty! " << endl;
+            return;
+          }
+
+        Int_t r;
+
+        const Int_t n = sscanf(str.Data(), " %d : %n", &r, &len);
+        if (n!=1)
+            return;
+
+        if (run==0 || run && (UInt_t)r==run)
+            break;
+    }
+
+    str.Remove(0, len);
+
+    while (1)
+    {
+        Int_t idx;
+        const Int_t n = sscanf(str.Data(), " %d %n", &idx, &len);
+
+        if (n!=1)
+            break;
+
+        str.Remove(0, len);
+
+        if (idx>=GetSize())
+            InitSize(idx+1);
+
+        (*this)[idx].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the information into an ascii file. If a run-number is given the
+// run-number will lead the line.
+//
+Bool_t MBadPixelsCam::AsciiWrite(ostream &fout, UInt_t run=0) const
+{
+    if (run)
+        fout << run << ":";
+
+    for (int i=0; i<GetSize(); i++)
+        if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+            fout << " " << i;
+
+    if (run && GetSize())
+        fout << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The types are the following:
+// 0: MBadPixelsPix::GetInfo()[0]
+// 1: MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableRun)
+// 2: MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableEvt)
+// 3: MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnreliableRun)
+// 4: MBadPixelsPix::IsHiGainBad()
+// 5: MBadPixelsPix::IsLoGainBad()
+// 6: MBadPixelsPix::GetUnsuitableCalLevel()
+// 7: MBadPixelsPix::GetUnreliableCalLevel()
+// 8: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainNotFitted)
+// 9: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainNotFitted)
+// 10: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainOscillating)
+// 11: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainOscillating)
+// 12: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainSaturation )
+// 13: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kChargeIsPedestal )
+// 14: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kChargeErrNotValid)
+// 15: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kChargeRelErrNotValid)
+// 16: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid )
+// 17: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kMeanTimeInFirstBin  )
+// 18: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kMeanTimeInLast2Bins )
+// 19: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes    )
+// 20: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kRelTimeNotFitted    )
+// 21: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kRelTimeOscillating  )
+// 22: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kDeviatingNumPhots   )
+// 23: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainOverFlow      )
+// 24: MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainOverFlow      )
+//
+Bool_t MBadPixelsCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx >= GetSize())
+    return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      return (*this)[idx].GetInfo()[0];
+    case 1:
+      if  (!(*this)[idx].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        return kFALSE;
+      val = 1;
+      break;
+    case 2:
+      if  (!(*this)[idx].IsUnsuitable(MBadPixelsPix::kUnsuitableEvt))
+        return kFALSE;
+      val = 1;
+      break;
+    case 3:
+      if  (!(*this)[idx].IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+          return kFALSE;
+      val = 1;
+      break;
+    case 4:
+      if  (!(*this)[idx].IsHiGainBad())
+        return kFALSE;
+      val = 1;
+      break;
+    case 5:
+      if  (!(*this)[idx].IsLoGainBad())
+        return kFALSE;
+      val = 1;
+      break;
+    case 6:
+      if  ((*this)[idx].GetUnsuitableCalLevel())
+        val = (*this)[idx].GetUnsuitableCalLevel();
+      else
+        return kFALSE;
+      break;
+    case 7:
+      if  ((*this)[idx].GetUnreliableCalLevel())
+        val = (*this)[idx].GetUnreliableCalLevel();
+      else
+        return kFALSE;
+      break;
+    case 8:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kHiGainNotFitted))
+        return kFALSE;
+      val = 1;
+      break;
+    case 9:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainNotFitted))
+        return kFALSE;
+      val = 1;
+      break;
+    case 10:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kHiGainOscillating))
+        return kFALSE;
+      val = 1;
+      break;
+    case 11:
+      if (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainOscillating))
+        return kFALSE;
+      val = 1;
+      break;
+    case 12:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainSaturation ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 13:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeIsPedestal ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 14:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeErrNotValid))
+        return kFALSE;
+      val = 1;
+      break;
+    case 15:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeRelErrNotValid))
+        return kFALSE;
+      val = 1;
+      break;
+    case 16:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 17:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kMeanTimeInFirstBin  ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 18:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kMeanTimeInLast2Bins ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 19:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 20:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kRelTimeNotFitted ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 21:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kRelTimeOscillating))
+        return kFALSE;
+      val = 1;
+      break;
+    case 22:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhots))
+        return kFALSE;
+      val = 1;
+      break;
+    case 23:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kHiGainOverFlow    ))
+        return kFALSE;
+      val = 1;
+      break;
+    case 24:
+      if  (!(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainOverFlow   ))
+        return kFALSE;
+      val = 1;
+      break;
+    default:
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+void MBadPixelsCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MBadPixelsCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsCam.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsCam.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MBadPixelsCam
+#define MARS_MBadPixelsCam
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class MGeomPix;
+class TClonesArray;
+
+class MBadPixelsCam : public MParContainer, public MCamEvent
+{
+private:
+    TClonesArray *fArray; //-> 
+
+    Short_t GetNumSuitableNeighbors(MBadPixelsPix::UnsuitableType_t type, const MGeomPix &pix) const;
+    Short_t GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type, TObjArray &list, Int_t idx, Int_t aidx) const;
+
+    void PrintBadPixels( MBadPixelsPix::UncalibratedType_t typ, const char *text) const;
+    
+public:
+    MBadPixelsCam(const char *name=NULL, const char *title=NULL);
+    MBadPixelsCam(const MBadPixelsCam &cam);
+    ~MBadPixelsCam();
+
+    void Reset();
+    void Clear(Option_t *o="");
+    void Print(Option_t *o="") const;
+    void Copy(TObject &object) const;
+
+    void InitSize(const UInt_t i);
+    Int_t GetSize() const;
+
+    MBadPixelsPix &operator[](Int_t i);
+    const MBadPixelsPix &operator[](Int_t i) const;
+
+    void Merge(const MBadPixelsCam &cam);
+
+    Short_t GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type, const MGeomCam *geom, Int_t aidx=-1) const;
+    Short_t GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type) const { return GetNumUnsuitable(type, 0); }
+    Short_t GetNumIsolated(MBadPixelsPix::UnsuitableType_t type, const MGeomCam &geom, Int_t aidx=-1) const;
+    Short_t GetNumIsolated(const MGeomCam &geom, Int_t aidx=-1) const { return GetNumIsolated(MBadPixelsPix::kUnsuitableRun, geom, aidx); }
+    Short_t GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type, const MGeomCam &geom, Int_t aidx=-1) const;
+    Short_t GetNumMaxCluster(const MGeomCam &geom, Int_t aidx=-1) { return GetNumMaxCluster(MBadPixelsPix::kUnsuitableRun, geom, aidx); }
+
+    void   AsciiRead(istream &fin, UInt_t run);
+    void   AsciiRead(istream &fin) { AsciiRead(fin, 0); }
+    Bool_t AsciiWrite(ostream &out, UInt_t run) const;
+    Bool_t AsciiWrite(ostream &out) const { return AsciiWrite(out, 0); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MBadPixelsCam, 1)	//Storage container to store bad pixel of the camera...
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsIntensityCam.cc
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsIntensityCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsIntensityCam.cc	(revision 9772)
@@ -0,0 +1,269 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MBadPixelsIntensityCam                                               
+//                                                               
+// Base class for intensity calibration results 
+//
+// Contains TClonesArrays for the following objects:
+// - fCams:  Array of classes derived from MBadPixelsCam, one entry 
+//           per calibration camera result. Has to be created
+//
+// See also: MCalibrationIntensityChargeCam, MCalibrationIntensityQECam,
+//           MCalibrationIntensityRelTimeCam,
+//           MCalibrationCam, MCalibrationPix, 
+//           MCalibrationQECam, MCalibrationQEPix,
+//           MHCalibrationChargePix, MHCalibrationChargeCam              
+//           MCalibrationChargeBlindPix, MCalibrationChargePINDiode
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsIntensityCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MGeomCam.h"
+
+ClassImp(MBadPixelsIntensityCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes and sets owner of:
+// - fCams
+// - Initializes fCams to entry 
+//
+MBadPixelsIntensityCam::MBadPixelsIntensityCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MBadPixelsIntensityCam";
+  fTitle = title ? title : "Base container for the Intensity Calibration";
+  
+  fCams = new TOrdCollection;
+  fCams->SetOwner();
+
+  InitSize(1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the cameras if they exist
+//
+MBadPixelsIntensityCam::~MBadPixelsIntensityCam()
+{
+  if (fCams)
+    delete fCams;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new MBadPixelsCam to fCams, give it the name "name" and initialize
+// it with geom.
+//
+void MBadPixelsIntensityCam::AddToList( const char* name, const MGeomCam &geom) 
+{
+  InitSize(GetSize()+1);
+  GetCam()->SetName(name);
+  GetCam()->Init(geom);
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MBadPixelsIntensityCam::Copy(TObject& object) const
+{
+  
+  MBadPixelsIntensityCam &calib = (MBadPixelsIntensityCam&)object;
+  
+  MParContainer::Copy(calib);
+  
+  const UInt_t n = GetSize();
+  if (n != 0)
+    {
+      calib.InitSize(n);
+      for (UInt_t i=0; i<n; i++)
+        GetCam(i)->Copy(*(calib.GetCam(i)));
+    }
+  
+}
+
+// -----------------------------------------------------
+//
+// Calls Clear() for all entries fCams
+//
+void MBadPixelsIntensityCam::Clear(Option_t *o)
+{
+
+  fCams->ForEach(MBadPixelsCam, Clear)(); 
+
+  return;
+}
+
+// -----------------------------------------------------
+//
+// Calls Print(o) for all entries fCams
+//
+void MBadPixelsIntensityCam::Print(Option_t *o) const
+{
+  fCams->ForEach(MBadPixelsCam, Print)(o); 
+}
+
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollection using the 
+// function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MBadPixelsIntensityCam::InitSize(const UInt_t i)
+{
+
+  const UInt_t save = GetSize();
+
+  if (i==save)
+    return;
+  
+  if (i>save)
+    Add(save,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MBadPixelsCams in the ranges from - to. In order to initialize
+// from MBadPixelsCam derived containers, overwrite this function
+//
+void MBadPixelsIntensityCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MBadPixelsCam,i);
+}
+
+
+// -------------------------------------------------------------------
+//
+// If size is still 0, Intialize a first Cam.
+// Calls Init(geom) for all fCams
+//
+void MBadPixelsIntensityCam::Init(const MGeomCam &geom)
+{
+  if (GetSize() == 0)
+    InitSize(1);
+
+  fCams->ForEach(MBadPixelsCam,Init)(geom);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fCams 
+// independently if the MBadPixelsCam is filled with values or not.
+//
+Int_t MBadPixelsIntensityCam::GetSize() const 
+{
+  return fCams->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+MBadPixelsPix &MBadPixelsIntensityCam::operator[](Int_t i)
+{
+  return (*GetCam())[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+const MBadPixelsPix &MBadPixelsIntensityCam::operator[](Int_t i) const 
+{
+  return (*GetCam())[i];
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get i-th camera 
+//
+MBadPixelsCam *MBadPixelsIntensityCam::GetCam(Int_t i)
+{
+  return static_cast<MBadPixelsCam*>(i==-1 ? fCams->Last() : fCams->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th camera 
+//
+const MBadPixelsCam *MBadPixelsIntensityCam::GetCam(Int_t i) const 
+{
+  return static_cast<MBadPixelsCam*>(i==-1 ? fCams->Last() : fCams->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get camera with name 'name' 
+//
+MBadPixelsCam *MBadPixelsIntensityCam::GetCam(const char *name )
+{
+  return static_cast<MBadPixelsCam*>(fCams->FindObject(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get camera with name 'name' 
+//
+const MBadPixelsCam *MBadPixelsIntensityCam::GetCam(const char *name ) const 
+{
+  return static_cast<MBadPixelsCam*>(fCams->FindObject(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls GetPixelContent for the current entry in fCams
+//
+Bool_t MBadPixelsIntensityCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  return GetCam()->GetPixelContent(val,idx,cam,type);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls DrawPixelContent for the current entry in fCams
+//
+void MBadPixelsIntensityCam::DrawPixelContent( Int_t num ) const
+{
+  return GetCam()->DrawPixelContent(num);
+}
+
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsIntensityCam.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsIntensityCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsIntensityCam.h	(revision 9772)
@@ -0,0 +1,79 @@
+#ifndef MARS_MBadPixelsIntensityCam
+#define MARS_MBadPixelsIntensityCam
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+class TOrdCollection;
+class MGeomCam;
+class MBadPixelsIntensityCam : public MParContainer, public MCamEvent
+{
+private:
+
+  TOrdCollection *fCams;        //-> Array of MBadPixelsCams, one per pulse colour and intensity
+
+  void Add(const UInt_t from, const UInt_t to);
+  
+public:
+
+  MBadPixelsIntensityCam(const char *name=NULL, const char *title=NULL);
+  ~MBadPixelsIntensityCam();
+  
+  void  Clear ( Option_t *o="" );
+  void  Print ( Option_t *o="" ) const;
+  void  Copy  ( TObject& object) const;  
+  
+  void AddToList( const char* name, const MGeomCam &geom );
+
+  // Getters
+  Int_t GetSize() const;
+
+        MBadPixelsCam *GetCam     ( Int_t i=-1);
+  const MBadPixelsCam *GetCam     ( Int_t i=-1) const;
+
+        MBadPixelsCam *GetCam     ( const char *name );
+  const MBadPixelsCam *GetCam     ( const char *name ) const;
+
+        MBadPixelsPix &operator[] ( Int_t i );
+  const MBadPixelsPix &operator[] ( Int_t i )  const;
+ 
+  Short_t GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type,const MGeomCam *geom,Int_t aidx=-1) 
+	const { return GetCam()->GetNumUnsuitable(type,geom,aidx); }
+  Short_t GetNumUnsuitable(MBadPixelsPix::UnsuitableType_t type) 
+	const { return GetCam()->GetNumUnsuitable(type); }
+  Short_t GetNumIsolated(MBadPixelsPix::UnsuitableType_t type,const MGeomCam &geom,Int_t aidx=-1) 
+	const { return GetCam()->GetNumIsolated(type,geom,aidx); }
+  Short_t GetNumIsolated(const MGeomCam &geom,Int_t aidx=-1) 
+	const { return GetCam()->GetNumIsolated(geom, aidx); }
+  Short_t GetNumMaxCluster(MBadPixelsPix::UnsuitableType_t type,const MGeomCam &geom,Int_t aidx=-1) 
+	const { return GetCam()->GetNumMaxCluster(type,geom,aidx); }
+  Short_t GetNumMaxCluster(const MGeomCam &geom,Int_t aidx=-1)
+        { return GetCam()->GetNumMaxCluster(geom, aidx); }
+  
+  void   AsciiRead(istream &fin, UInt_t run) 
+	{ GetCam()->AsciiRead(fin,run); }
+  void   AsciiRead(istream &fin) 
+	{GetCam()->AsciiRead(fin); }
+  Bool_t AsciiWrite(ostream &out, UInt_t run) 
+	const { return GetCam()->AsciiWrite(out,run); }
+  Bool_t AsciiWrite(ostream &out) 
+	const { return GetCam()->AsciiWrite(out); }
+  
+  // Inits
+  void Init   ( const MGeomCam &geom );
+  void InitSize( const UInt_t i );
+
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam,Int_t type=0) const;
+  void   DrawPixelContent( Int_t num) const;
+
+  ClassDef(MBadPixelsIntensityCam, 1) // Base Container Intensity BadPixels Results
+};
+
+#endif
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsMerge.cc
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsMerge.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsMerge.cc	(revision 9772)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 02/2004 <mailto:tbretz@astro.uni.wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MBadPixelsMerge
+//  ===============
+//
+//  Merges in ReInit two bad pixel containers together:
+//   1) The contents of the container given in the constructor is in ReInit
+//      merged into MBadPixelsCam from the parameter list (aka run-headers)
+//   2) MBadPixelsCam from the parameter list (aka run-headers) is merged
+//      into the container given in the constructor. While the contents
+//      to which 1) refers are still untouched.
+//
+//
+// An explanation taken from Mantis:
+// --------------------------------
+// In my eyes everything works a supposed to do. We have different sources
+// for bad-pixels, eg from Pedestal calculation, from the calibration
+// constant calculation, manual setting and so on. If processing data we
+// have to take care of all this different sources. Therefor we have to
+// store the bad pixels from this sources (eg. from calibration). In
+// addition MBadPixelsCam is read from the file containing the data (once
+// per file). Now always after a new (data-)file has been opened the bad
+// pixels from (for example) the calibration file have to be merged into
+// the container loaded from the (data-)file which is stored in the
+// parameter list. Copying the pointer would totally overwrite the pixels
+// loaded (automatically by MReadMarsFile) from the data-file. All this is
+// done using a copy of the original MBadPixelsCam (fSource). In addition
+// fDest is initialized to the pointer given as argument to the
+// constructor. To keep track of all bad pixels the instance this pointer
+// is pointing to is used to collect all bad pixels used so far.
+//
+//
+// ToDo:
+//   - Take a setup file (ReadEnv-implementation) as input
+//
+//
+//  Input Containers:
+//   MBadPixelsCam
+//
+//  Output Containers:
+//   MBadPixelsCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsMerge.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MBadPixelsCam.h"
+
+ClassImp(MBadPixelsMerge);
+
+using namespace std;
+
+const TString MBadPixelsMerge::fgDefName  = "MBadPixelsMerge";
+const TString MBadPixelsMerge::fgDefTitle = "Merge extra- and intra-loop pixels";
+
+// --------------------------------------------------------------------------
+//
+// Constructor. A copy of the given MBadPixelsCam is created. This copy
+// is - in ReInit - merged into the MBadPixelsCam which is found in the
+// parameter list. In addition the pointer is stored and all MBadPixelsCam
+// which are processed in ReInit are merged into this container.
+//
+MBadPixelsMerge::MBadPixelsMerge(MBadPixelsCam *bad, const char *name, const char *title)
+    : fDest(bad)
+{
+    fName  = name  ? name  : fgDefName.Data();
+    fTitle = title ? title : fgDefTitle.Data();
+
+    fSource = new MBadPixelsCam(*bad);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the copy of the primer MBadPixelsCam
+//
+MBadPixelsMerge::~MBadPixelsMerge()
+{
+    delete fSource;
+}
+
+// --------------------------------------------------------------------------
+//
+// 1) Get MBadPixelCam from the parameter list, if it doesn't yet exist,
+//    it will be created.
+// 2) Merge MBasPixelsCam into the primer container given in the constructor
+// 3) Merge the primer container given in the constructor into MBadPixelsCam
+//
+Bool_t MBadPixelsMerge::ReInit(MParList *pList)
+{
+    MBadPixelsCam *cam = (MBadPixelsCam*)pList->FindCreateObj("MBadPixelsCam");
+    if (!cam)
+        return kFALSE;
+
+    fDest->Merge(*cam);
+    cam->Merge(*fSource);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsMerge.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsMerge.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsMerge.h	(revision 9772)
@@ -0,0 +1,29 @@
+#ifndef MARS_MBadPixelsMerge
+#define MARS_MBadPixelsMerge
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MBadPixelsCam;
+
+class MBadPixelsMerge : public MTask
+{
+private:
+    static const TString fgDefName;  //!
+    static const TString fgDefTitle; //!
+
+    MBadPixelsCam *fDest;            //!
+    MBadPixelsCam *fSource;          //->
+
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MBadPixelsMerge(MBadPixelsCam *bad, const char *name=NULL, const char *title=NULL);
+    ~MBadPixelsMerge();
+
+    ClassDef(MBadPixelsMerge, 0) //Merge extra- and intra-loop pixels
+}; 
+
+#endif
+
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsPix.cc
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsPix.cc	(revision 9772)
@@ -0,0 +1,185 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Markus Gaug,  3/2004 <mailto:markus@ifae.es>
+! 
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+// MBadPixelsPix
+//
+// The bits of an integer array fInfo are used to declare and inform about 
+// possible defects in a pixel. Default and absence of defects create an array
+// of zeros. 
+//
+// The first index (fInfo[0]) holds general information which is coded as follows:
+// * BIT(1): Unsuitable Run: The pixel is not suited for analysis for the entire run
+// * BIT(2): Unsuitable Evt: The pixel is not suited for analysis for the current event
+// * BIT(3): Unreliable Run: The pixel can in principle be used for analysis, although 
+//                           previous analysis steps have yielded certain inconsistencies
+//
+// These bits can be called with the enum MBadPixelsPix::UnsuitableTupe_t in combination 
+// with the function IsUnsuitable(MBadPixelsPix::UnsuitableTupe_t), e.g. 
+// MBadPixelsPix::IsUnsuitalbe(MBadPixelsPix::kUnsuitableRun) asks if the first bit is set. 
+//
+// The second index (fInfo[1]) hold information acquired during the calibration. The bits 
+// are coded in the following form:
+//
+// * Set bits leading to an unreliable flag:
+// 
+// BIT(1 ): kHiGainNotFitted     :  Any High Gain signal is calibrated without a Gauss Fit to the signal distribution
+// BIT(2 ): kLoGainNotFitted     :  Any Low  Gain signal is calibrated without a Gauss Fit to the signal distribution
+// BIT(3 ): kRelTimeNotFitted    :  Any High Gain signal's arrival times are calibrated without a Gauss Fit
+// BIT(4 ): kHiGainOscillating   :  The High Gain signals fourier transform showed abnormal behavior  
+// BIT(5 ): kLoGainOscillating   :  The Low  Gain signals fourier transform showed abnormal behavior  
+// BIT(6 ): kRelTimeOscillating  :  The High Gain arrival times fourier transform showed abnormal behavior  
+// BIT(14): kDeviatingNumPhes    :  The calculated number of photo-electrons deviates too much from the mean - inconsistency
+// BIT(16): kDeviatingFFactor    :  The calculated overall F-Factor deviates too much from the mean - inconsistency
+// BIT(15): kDeviatingNumPhots   :  The calculated number of calibrated photons deviates too much from the mean - inconsistency
+//
+// * Set bits leading to an unsuitable flag:
+//
+// BIT(7 ): kLoGainSaturation    :  The Low  Gain signals were saturated during calibration
+// BIT(8 ): kChargeIsPedestal    :  The calibration signal contained only pedestals - presumably dead pixel
+// BIT(9 ): kChargeErrNotValid   :  The absolute error of the derived charge has given non-sense - presumably pedestal
+// BIT(10): kChargeRelErrNotValid:  The relative error of the derived charge was too large or too small
+// BIT(11): kChargeSigmaNotValid :  The sigma of the pedestal distribution smaller than the pedestal RMS - presumably a pixel with a star in its FOV only during the pedestal taking 
+// BIT(12): kMeanTimeInFirstBin  :  The signal has its mean maximum in the first used FADC slice - signal extractor bad
+// BIT(13): kMeanTimeInLast2Bins :  The signal has its mean maximum in the last two used FADC slice - signal extractor bad
+// BIT(19): kHiGainOverFlow      :  The Hi-Gain calibration histogram showed overflow without saturating the FADC
+// BIT(20): kLoGainOverFlow      :  The Lo-Gain calibration histogram showed overflow 
+//
+// * Set bits leading to not useable low-gain signal:
+//
+// BIT(17): kConversionHiLoNotValid: The calibrated Conversion between Hi-Gain and Low Gain gives absurd results
+//
+// These bits can be called with the enum MBadPixelsPix::UncalibratedType_t in combination 
+// with the function IsUncalibrated(MBadPixelsPix::UncalibratedTupe_t), e.g. 
+// MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainNotCalibrated) asks if the Hi Gain signal
+// could be calibrated.
+//
+// The third index (fInfo[2]) holds information about possible hardware mulfunctionning. The bits 
+// are coded in the following form:
+// BIT(1 ): kHVNotNominal :  The HV deviates more than 3% from the nominal value.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MBadPixelsPix);
+
+using namespace std;
+
+const Int_t MBadPixelsPix::fgRunMask =
+    MBadPixelsPix::kUnsuitableRun |
+    MBadPixelsPix::kUnreliableRun;
+
+// ------------------------------------------------------------------------
+//
+// Initialize Pixel to be Ok.
+//
+MBadPixelsPix::MBadPixelsPix(const char* name, const char* title)
+{
+    fName  = name  ? name  : "MBadPixelsPix";
+    fTitle = title ? title : "Container storing bad pixel information for a single pixel";
+
+    fInfo.Set(3);
+
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate all bits which are not run-wise. This will be called for
+// all entries in the parameter list, just before each time the task-list
+// is executed.
+//
+void MBadPixelsPix::Reset()
+{
+    fInfo[0] &= fgRunMask;
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values (set=0 which mean Pixel OK)
+//
+void MBadPixelsPix::Clear(Option_t *o)
+{
+    fInfo.Reset(0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Merge (bitwise or) the information in pix into this pixel.
+//
+void MBadPixelsPix::Merge(const MBadPixelsPix &pix)
+{
+  const Int_t n = pix.fInfo.GetSize();
+  if (n>fInfo.GetSize())
+    fInfo.Set(n);
+  
+  for (int i=0; i<n; i++)
+    fInfo[i] |= pix.fInfo[i];
+}
+
+
+/****************************************************************************
+           This is a collection of possible defects for later use
+ ****************************************************************************/
+
+/*
+ 1  PMT defective.
+ 2  Preamplifier defective.
+ 3  Optical link defective.
+ 4  HV cannot be set.
+ 7  HV unstable.
+ 5  HV readout defective.
+ 8  DC unstable.
+ 6  DC readout defective.
+ 9  Discriminator threshold cannot be set.
+ 10  Trigger delay cannot be set.
+ 11  Discriminator gives no output.
+ <-? 12  Pixel out of L1T.
+ 13  FADC defective.
+ 14  FADC board digital information defective.
+ */
+
+/*
+ 1  Pixel shows no signal
+ */
+
+/*
+
+Hardware defects which cannot be detected automatically by software. This might be stored at least in the data-base. I think we should wait until we implement these things...
+Preamplifier defective.
+Optical link defective.
+HV cannot be set.
+HV readout defective.
+DC readout defective.
+Discriminator threshold cannot be set.
+Trigger delay cannot be set.
+Discriminator gives no output.
+FADC defective.
+FADC board digital information defective.
+Pixel out of L1T. (this is an important information, but not necessarily a defect, is it?)
+
+*/
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsPix.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsPix.h	(revision 9772)
@@ -0,0 +1,130 @@
+#ifndef MARS_MBadPixelsPix
+#define MARS_MBadPixelsPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MBadPixelsPix : public MParContainer
+{
+private:
+    TArrayI fInfo;
+
+public:
+    MBadPixelsPix(const char* name=NULL, const char* title=NULL);
+
+    enum UnsuitableType_t {
+        kUnsuitableRun = BIT(1),
+        kUnsuitableEvt = BIT(2),
+        kUnsuitable    = kUnsuitableRun|kUnsuitableEvt,
+        kUnreliableRun = BIT(3),
+        kUnreliableEvt = BIT(4),
+        kUnreliable    = kUnreliableRun|kUnreliableEvt
+    };
+
+    static const Int_t fgRunMask; // All types which are not event wise determined
+
+    // All types are initialized to normal behaviour
+    enum UncalibratedType_t {
+      kHiGainNotFitted          = BIT(1),
+      kLoGainNotFitted          = BIT(2), 
+      kRelTimeNotFitted         = BIT(3),
+      kHiGainOscillating        = BIT(4),
+      kLoGainOscillating        = BIT(5),
+      kRelTimeOscillating       = BIT(6),
+      kLoGainSaturation         = BIT(7),
+      kChargeIsPedestal         = BIT(8),
+      kChargeErrNotValid        = BIT(9),
+      kChargeRelErrNotValid     = BIT(10),
+      kChargeSigmaNotValid      = BIT(11),
+      kMeanTimeInFirstBin       = BIT(12),
+      kMeanTimeInLast2Bins      = BIT(13), 
+      kDeviatingNumPhes         = BIT(14),
+      kDeviatingNumPhots        = BIT(15),
+      kDeviatingFFactor         = BIT(16),
+      kDeviatingTimeResolution  = BIT(17),
+      kConversionHiLoNotValid   = BIT(18),
+      kHiGainOverFlow           = BIT(19),
+      kLoGainOverFlow           = BIT(20),
+      kHiLoNotFitted            = BIT(21),
+      kHiLoOscillating          = BIT(22)
+    };
+    
+    // This is just a start..
+    enum HardwareType_t {
+      kHVNotNominal             = BIT(1)
+    };
+    
+      
+    void Reset();
+    void Clear(Option_t *o="");
+    void Copy(TObject &object) const
+    {
+        static_cast<MBadPixelsPix&>(object).fInfo = fInfo;
+    }
+
+    // Setter
+    void SetUnsuitable  (UnsuitableType_t   typ) { fInfo[0] |= typ; }
+    void SetUncalibrated(UncalibratedType_t typ) { fInfo[1] |= typ; }
+    void SetHardware    (HardwareType_t     typ) { fInfo[2] |= typ; }
+
+    // Getter
+    Bool_t IsUnsuitable  (UnsuitableType_t   typ) const { return fInfo[0]&typ; }
+    Bool_t IsUncalibrated(UncalibratedType_t typ) const { return fInfo[1]&typ; }
+    Bool_t IsHardwareBad (HardwareType_t     typ) const { return fInfo[2]&typ; }
+
+    Bool_t IsUnsuitable() const { return fInfo[0]&kUnsuitable; }
+    Bool_t IsUnreliable() const { return fInfo[0]&kUnreliable; }
+
+    Bool_t IsOK()  const { return fInfo[0]==0; }
+    Bool_t IsBad() const { return fInfo[0]!=0; }
+
+    Bool_t IsLoGainBad() const { return IsUnsuitable  (kUnsuitableRun      )
+				     || IsUncalibrated(kLoGainSaturation   ) 
+				     || IsUncalibrated(kConversionHiLoNotValid) 
+				     || IsUncalibrated(kLoGainOscillating  ) ; }
+    Bool_t IsHiGainBad() const { return IsUnsuitable  (kUnsuitableRun      )
+  				     || IsUncalibrated(kHiGainOscillating  ) ; }
+
+    Int_t  GetUnsuitableCalLevel() const   {
+      if (!IsUnsuitable())                        return 0;
+      if (IsUncalibrated( kChargeIsPedestal    )) return 1;
+      if (IsUncalibrated( kChargeRelErrNotValid)) return 2;
+      if (IsUncalibrated( kLoGainSaturation    )) return 3;
+      if (IsUncalibrated( kMeanTimeInFirstBin  )) return 4;
+      if (IsUncalibrated( kMeanTimeInLast2Bins )) return 5;
+      if (IsUncalibrated( kDeviatingNumPhots   )) return 6;
+      if (IsUncalibrated( kHiGainOverFlow      )) return 7;
+      if (IsUncalibrated( kLoGainOverFlow      )) return 8;
+      return 9;
+    }
+    
+    Int_t  GetUnreliableCalLevel() const   {
+      if (!IsUnreliable() || IsUnsuitable())      return 0;
+      if (IsUncalibrated( kChargeSigmaNotValid )) return 1;
+      if (IsUncalibrated( kDeviatingNumPhes    )) return 2;
+      if (IsUncalibrated( kHiGainNotFitted     )) return 3;
+      if (IsUncalibrated( kLoGainNotFitted     )) return 4;
+      if (IsUncalibrated( kRelTimeNotFitted    )) return 5;
+      if (IsUncalibrated( kHiGainOscillating   )) return 6;
+      if (IsUncalibrated( kLoGainOscillating   )) return 7;
+      if (IsUncalibrated( kRelTimeOscillating  )) return 8;
+      if (IsUncalibrated( kDeviatingFFactor    )) return 9;
+      return 10;
+    }
+    
+        
+    
+    void Merge(const MBadPixelsPix &pix);
+
+    const TArrayI &GetInfo() const { return fInfo; }
+
+    ClassDef(MBadPixelsPix, 1)	// Storage Container for bad pixel information of a single pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsTreat.cc
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsTreat.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsTreat.cc	(revision 9772)
@@ -0,0 +1,617 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 12/2001 <mailto:blanch@ifae.es>
+!   Author(s): Thomas Bretz 08/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MBadPixelsTreat
+//
+//  You can use MBadPixelsTreat::SetUseInterpolation to replaced the
+//  bad pixels by the average of its neighbors instead of unmapping
+//  them. If you want to include the central pixel use
+//  MBadPixelsTreat::SetUseCentralPixel. The bad pixels are taken from
+//  an existing MBadPixelsCam.
+//
+//  It check if there are enough neighbors to calculate the mean
+//  If not, unmap the pixel. The minimum number of good neighbors
+//  should be set using SetNumMinNeighbors
+//
+//  If you want to interpolate unreliable pixels and  unsuitable
+//  (broken) pixels use SetHardTreatment().
+//
+//
+// Options:
+// --------
+//   SetHardTreatment:      Also interpolate unreliable pixels not only unsuitable
+//   SetUseInterpolation:   Interpolate pixels instead of unmapping them
+//   SetUseCentralPixel:    also use the pixel itself for interpolation
+//   SetProcessPedestalRun: process the pedestals once per run/file
+//   SetProcessPedestalEvt: process the pedestal once per event
+//   SetProcessTimes:       also do some rough interpolation of the arrival time
+//
+//
+//  Input Containers:
+//   MSignalCam
+//   MPedPhotCam
+//   MBadPixelsCam
+//   [MGeomCam]
+//
+//  Output Containers:
+//   MSignalCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsTreat.h"
+
+#include <fstream>
+
+#include <TEnv.h>
+#include <TObjString.h>
+
+#include "MArrayD.h" // Used instead of TArrayD because operator[] has no range check
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+#include "MBadPixelsPix.h"
+#include "MBadPixelsCam.h"
+
+//#include "MArrivalTime.h"
+
+ClassImp(MBadPixelsTreat);
+
+using namespace std;
+
+static const TString gsDefName  = "MBadPixelsTreat";
+static const TString gsDefTitle = "Task to treat bad pixels (interpolation, unmapping)";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MBadPixelsTreat::MBadPixelsTreat(const char *name, const char *title)
+  : fFlags(0), fNumMinNeighbors(3)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetUseInterpolation();
+    SetProcessPedestal();
+    SetProcessTimes();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the status of a pixel. If kHardTreatment is set a pixel must
+// be unsuitable or uriliable to be treated. If not it is treated only if 
+// it is unsuitable
+// (IsBad() checks for any flag)
+//
+Bool_t MBadPixelsTreat::IsPixelBad(Int_t idx) const
+{
+    return TESTBIT(fFlags, kHardTreatment) ? (*fBadPixels)[idx].IsBad():(*fBadPixels)[idx].IsUnsuitable();
+}
+
+void MBadPixelsTreat::AddNamePedPhotCam(const char *name)
+{
+    fNamePedPhotCams.Add(new TObjString(name));
+}
+
+// --------------------------------------------------------------------------
+//
+//  - Try to find or create MBlindPixels in parameter list.
+//  - get the MSignalCam from the parlist (abort if missing)
+//  - if no pixels are given by the user try to determin the starfield
+//    from the monte carlo run header.
+//
+Int_t MBadPixelsTreat::PreProcess (MParList *pList)
+{
+    fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+    {
+        *fLog << err << AddSerialNumber("MBadPixelsCam") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MSignalCam*)pList->FindObject(AddSerialNumber("MSignalCam"));
+    if (!fEvt)
+    {
+        *fLog << err << AddSerialNumber("MSignalCam") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = 0;
+    if (!IsUseInterpolation())
+        return kTRUE;
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+    {
+        *fLog << err << AddSerialNumber("MGeomCam") << " not found - can't use interpolation... abort." << endl;
+        *fLog << " Use MBadPixelsTreat::SetUseInterpolation(kFALSE) to switch interpolation" << endl;
+        *fLog << " off and use unmapping instead." << endl;
+        return kFALSE;
+    }
+
+    const Bool_t proc = IsProcessPedestalEvt() || IsProcessPedestalRun();
+
+    if (fNamePedPhotCams.GetSize()>0 && !proc)
+    {
+        *fLog << err << "Pedestal list contains entries, but pedestal treatment is switched off... abort." << endl;
+        return kFALSE;
+    }
+
+    if (proc)
+    {
+        if (fNamePedPhotCams.GetSize()==0)
+        {
+            *fLog << inf << "No container names specified... using default: MPedPhotCam." << endl;
+            AddNamePedPhotCam();
+        }
+
+        fPedPhotCams.Clear();
+
+        TIter Next(&fNamePedPhotCams);
+        TObject *o=0;
+        while ((o=Next()))
+        {
+            TObject *p = pList->FindObject(AddSerialNumber(o->GetName()), "MPedPhotCam");
+            if (!p)
+            {
+                *fLog << err << AddSerialNumber(o->GetName()) << " [MPedPhotCam] not found... aborting." << endl;
+                return kFALSE;
+            }
+
+            fPedPhotCams.Add(p);
+        }
+    }
+
+    if (IsProcessPedestalEvt())
+        *fLog << inf << "Processing Pedestals once per event..." << endl;
+    if (IsProcessPedestalRun())
+        *fLog << inf << "Processing Pedestals once per run..." << endl;
+    if (IsProcessTimes())
+        *fLog << inf << "Processing Arrival Times once per event..." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Replaces each pixel (signal, signal error, pedestal, pedestal rms)
+//  by the average of its surrounding pixels.
+//  If TESTBIT(fFlags, kUseCentralPixel) is set the central pixel is also
+//  included.
+//
+void MBadPixelsTreat::InterpolateSignal() const
+{
+    const UShort_t entries = fGeomCam->GetNumPixels();
+
+    //
+    // Create arrays (FIXME: Check if its possible to create it only once)
+    //
+    MArrayD nphot(entries);
+    MArrayD perr(entries);
+ 
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        MSignalPix *pix = fEvt->GetPixById(i);
+
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (pix && !IsPixelBad(i))
+            continue;
+
+        //
+        // Get a pointer to this pixel. If it is not yet existing
+        // create a new entry for this pixel in MSignalCam
+        //
+        if (!pix)
+        {
+            pix = fEvt->AddPixel(i, 0, 0);
+            (*fBadPixels)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+        }
+
+        //
+        // Get the corresponding geometry and pedestal
+        //
+        const MGeomPix &gpix = (*fGeomCam)[i];
+
+        // Do Not-Use-Central-Pixel
+        const Bool_t nucp = !TESTBIT(fFlags, kUseCentralPixel);
+
+        Int_t num = nucp ? 0 : 1;
+
+        nphot[i]  = nucp ? 0 : pix->GetNumPhotons();
+        perr[i]   = nucp ? 0 : Pow2(pix->GetErrorPhot());
+
+        //
+	// The values are rescaled to the small pixels area for the right comparison
+        //
+        const Double_t ratio = fGeomCam->GetPixRatio(i);
+
+        nphot[i] *= ratio;
+        perr[i]  *= ratio;
+
+        //
+        // Loop over all its neighbors
+        //
+        const Int_t n = gpix.GetNumNeighbors();
+        for (int j=0; j<n; j++)
+        {
+            const UShort_t nidx = gpix.GetNeighbor(j);
+
+            //
+            // Do not use blind neighbors
+            //
+            if (IsPixelBad(nidx))
+                continue;
+
+            //
+            // Check whether the neighbor has a signal stored
+            //
+            const MSignalPix *evtpix = fEvt->GetPixById(nidx);
+            if (!evtpix)
+                continue;
+
+            //
+            // Get the geometry for the neighbor
+            //
+            const Double_t nratio = fGeomCam->GetPixRatio(nidx);
+
+            //
+	    //The error is calculated as the quadratic sum of the errors
+	    //
+            nphot[i] += nratio*evtpix->GetNumPhotons();
+            perr[i]  += nratio* Pow2(evtpix->GetErrorPhot());
+
+            num++;
+        }
+
+	// Check if there are enough neighbors to calculate the mean
+        // If not, unmap the pixel. The maximum number of blind neighbors
+        // should be 2
+        if (num<fNumMinNeighbors)
+        {
+            pix->SetPixelUnmapped();
+            continue;
+        }
+
+        //
+        // Now the mean is calculated and the values rescaled back
+        // to the pixel area
+        //
+	nphot[i] /= (num*ratio);
+        perr[i]   = TMath::Sqrt(perr[i]/(num*ratio));
+ 
+        pix->Set(nphot[i], perr[i]);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+void MBadPixelsTreat::InterpolatePedestals(MPedPhotCam &pedphot) const
+{
+    const Int_t entries = pedphot.GetSize();
+
+    // Create arrays (FIXME: Check if its possible to create it only once)
+    MArrayD ped(entries);
+    MArrayD rms(entries);
+
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (!IsPixelBad(i))
+            continue;
+
+        //
+        // Get the corresponding geometry and pedestal
+        //
+        const MGeomPix    &gpix = (*fGeomCam)[i];
+        const MPedPhotPix &ppix = pedphot[i];
+
+        // Do Not-Use-Central-Pixel
+        const Bool_t nucp = !TESTBIT(fFlags, kUseCentralPixel);
+
+        Int_t num = nucp ? 0 : 1;
+
+        ped[i] = nucp ? 0 : ppix.GetMean();
+        rms[i] = nucp ? 0 : Pow2(ppix.GetRms());
+
+        //
+        // The values are rescaled to the small pixels area for the right comparison
+        //
+        const Double_t ratio = fGeomCam->GetPixRatio(i);
+
+        ped[i] *= ratio;
+        rms[i] *= ratio;
+
+        //
+        // Loop over all its neighbors
+        //
+        const Int_t n = gpix.GetNumNeighbors();
+        for (int j=0; j<n; j++)
+        {
+            const UShort_t nidx = gpix.GetNeighbor(j);
+
+            //
+            // Do not use blind neighbors
+            //
+            if (IsPixelBad(nidx))
+                continue;
+
+            //
+            // Get the geometry for the neighbor
+            //
+            const Double_t    nratio = fGeomCam->GetPixRatio(nidx);
+            const MPedPhotPix &nppix = pedphot[nidx];
+
+            //
+            //The error is calculated as the quadratic sum of the errors
+            //
+            ped[i] += nratio*nppix.GetMean();
+            rms[i] += nratio*Pow2(nppix.GetRms());
+
+            num++;
+        }
+
+        // Check if there are enough neighbors to calculate the mean
+        // If not, unmap the pixel. The minimum number of good neighbors
+        // should be fNumMinNeighbors
+        if (num < fNumMinNeighbors)
+        {
+            MSignalPix *pix =fEvt->GetPixById(i);
+            if (!pix)
+                pix = fEvt->AddPixel(i, 0, 0);
+            pix->SetPixelUnmapped();
+            continue;
+        }
+
+        //
+        // Now the mean is calculated and the values rescaled back
+        // to the pixel area
+        //
+        ped[i] /=  (num*ratio);
+        rms[i]  = TMath::Sqrt(rms[i]/(num*ratio));
+
+        pedphot[i].Set(ped[i], rms[i]);
+    }
+    pedphot.SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+// loop over all MPedPhotCam and interpolate them
+//
+void MBadPixelsTreat::InterpolatePedestals() const
+{
+    TIter Next(&fPedPhotCams);
+    MPedPhotCam *cam=0;
+    while ((cam=(MPedPhotCam*)Next()))
+    {
+        InterpolatePedestals(*cam);
+        cam->ReCalc(*fGeomCam, fBadPixels);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+void MBadPixelsTreat::InterpolateTimes() const
+{
+    Int_t n = fEvt->GetNumPixels();
+
+    for (int i=0; i<n; i++)
+    {
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (!IsPixelBad(i))
+            continue;
+
+        //
+        // Get the corresponding geometry and pedestal
+        //
+        const MGeomPix &gpix = (*fGeomCam)[i];
+
+        MArrayD time(gpix.GetNumNeighbors());
+
+        Int_t n0 = 0;
+        for (unsigned int j=0; j<time.GetSize(); j++)
+        {
+            const Double_t t = (*fEvt)[j].GetArrivalTime();
+            if (t>=0)
+                time[n0++] = t;
+        }
+
+        Int_t p0=-1;
+        Int_t p1=-1;
+
+        Double_t min=FLT_MAX;
+        for (int j=0; j<n0; j++)
+            for (int k=0; k<j; k++)
+            {
+                const Double_t diff = TMath::Abs(time[j] - time[k]);
+
+                if (diff>=min && diff<250)
+                    continue;
+
+                p0  = j;
+                p1  = k;
+                min = diff;
+            }
+
+        // FIXME: Request a minimum number of neighbors to take action?
+        if (p0>=0 && p1>=0 && TMath::Abs(time[p0] - time[p1])<250)
+            (*fEvt)[i].SetArrivalTime((time[p0]+time[p1])/2);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Removes all blind pixels from the analysis by setting their state
+//  to unused.
+//
+void MBadPixelsTreat::Unmap() const
+{
+    const UShort_t entries = fEvt->GetNumPixels();
+
+    //
+    // remove the pixels in fPixelsIdx if they are set to be used,
+    // (set them to 'unused' state)
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        if (IsPixelBad(i))
+            (*fEvt)[i].SetPixelUnmapped();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Interpolate Pedestals if kProcessPedestal not set
+//
+Bool_t MBadPixelsTreat::ReInit(MParList *pList)
+{
+    if (IsUseInterpolation() && IsProcessPedestalRun())
+        InterpolatePedestals();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Treat the blind pixels
+//
+Int_t MBadPixelsTreat::Process()
+{
+    if (IsUseInterpolation())
+    {
+        InterpolateSignal();
+        if (IsProcessPedestalEvt())
+            InterpolatePedestals();
+        if (IsProcessTimes())
+            InterpolateTimes();
+    }
+    else
+        Unmap();
+
+    return kTRUE;
+}
+
+void MBadPixelsTreat::StreamPrimitive(ofstream &out) const
+{
+    out << "   MBadPixelsTreat " << GetUniqueName();
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl;
+
+    if (IsUseInterpolation())
+        out << "   " << GetUniqueName() << ".SetUseInterpolation();" << endl;
+    if (IsUseCentralPixel())
+        out << "   " << GetUniqueName() << ".SetUseCentralPixel();" << endl;
+    if (IsProcessPedestalRun())
+        out << "   " << GetUniqueName() << ".SetProcessPedestalRun();" << endl;
+    if (IsProcessPedestalEvt())
+        out << "   " << GetUniqueName() << ".SetProcessPedestalEvt();" << endl;
+    if (IsProcessTimes())
+        out << "   " << GetUniqueName() << ".SetProcessTimes();" << endl;
+    if (IsHardTreatment())
+        out << "   " << GetUniqueName() << ".SetHardTreatment();" << endl;
+    if (fNumMinNeighbors!=3)
+        out << "   " << GetUniqueName() << ".SetNumMinNeighbors(" << (int)fNumMinNeighbors << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MBadPixelsTreat.UseInterpolation:    no
+//   MBadPixelsTreat.UseCentralPixel:     no
+//   MBadPixelsTreat.HardTreatment:       no
+//   MBadPixelsTreat.ProcessPedestalRun:  no
+//   MBadPixelsTreat.ProcessPedestalEvt:  no
+//   MBadPixelsTreat.NumMinNeighbors:     3
+//
+Int_t MBadPixelsTreat::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "UseInterpolation", print))
+    {
+        rc = kTRUE;
+        SetUseInterpolation(GetEnvValue(env, prefix, "UseInterpolation", IsUseInterpolation()));
+    }
+    if (IsEnvDefined(env, prefix, "UseCentralPixel", print))
+    {
+        rc = kTRUE;
+        SetUseCentralPixel(GetEnvValue(env, prefix, "UseCentralPixel", IsUseCentralPixel()));
+    }
+    if (IsEnvDefined(env, prefix, "HardTreatment", print))
+    {
+        rc = kTRUE;
+        SetHardTreatment(GetEnvValue(env, prefix, "HardTreatment", IsHardTreatment()));
+    }
+    if (IsEnvDefined(env, prefix, "ProcessPedestalRun", print))
+    {
+        rc = kTRUE;
+        SetProcessPedestalRun(GetEnvValue(env, prefix, "ProcessPedestalRun", IsProcessPedestalRun()));
+    }
+    if (IsEnvDefined(env, prefix, "ProcessPedestalEvt", print))
+    {
+        rc = kTRUE;
+        SetProcessPedestalEvt(GetEnvValue(env, prefix, "ProcessPedestalEvt", IsProcessPedestalEvt()));
+    }
+    if (IsEnvDefined(env, prefix, "ProcessTimes", print))
+    {
+        rc = kTRUE;
+        SetProcessTimes(GetEnvValue(env, prefix, "ProcessTimes", IsProcessTimes()));
+    }
+    if (IsEnvDefined(env, prefix, "NumMinNeighbors", print))
+    {
+        rc = kTRUE;
+        SetNumMinNeighbors(GetEnvValue(env, prefix, "NumMinNeighbors", fNumMinNeighbors));
+    }
+    return rc;
+}
Index: /tags/Mars-V0.9/mbadpixels/MBadPixelsTreat.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MBadPixelsTreat.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MBadPixelsTreat.h	(revision 9772)
@@ -0,0 +1,104 @@
+#ifndef MARS_MBadPixelsTreat
+#define MARS_MBadPixelsTreat
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MSignalCam;
+class MPedPhotCam;
+class MBadPixelsCam;
+
+class MBadPixelsTreat : public MTask
+{
+private:
+    MGeomCam      *fGeomCam;   //!
+    MSignalCam    *fEvt;       //!
+    MBadPixelsCam *fBadPixels; //!
+
+    TList fPedPhotCams;
+
+    Byte_t fFlags;       // flag for the method which is used
+    Byte_t fNumMinNeighbors;
+
+    TList fNamePedPhotCams;
+
+    enum
+    {
+        kUseInterpolation   = 1,
+        kUseCentralPixel    = 2,
+        kProcessPedestalRun = 3,
+        kProcessPedestalEvt = 4,
+        kProcessTimes       = 5,
+        kHardTreatment      = 6
+    };
+
+    static Double_t Pow2(Double_t x) { return x*x; }
+
+    void InterpolateTimes() const;
+    void InterpolateSignal() const;
+    void InterpolatePedestals(MPedPhotCam &pedphot) const;
+    void InterpolatePedestals() const;
+
+    void   Unmap() const;
+    Bool_t IsPixelBad(Int_t idx) const;
+
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+    void   StreamPrimitive(ofstream &out) const;
+
+public:
+    MBadPixelsTreat(const char *name=NULL, const char *title=NULL);
+
+    void SetUseInterpolation(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kUseInterpolation) : CLRBIT(fFlags, kUseInterpolation);
+    }
+    void SetUseCentralPixel(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kUseCentralPixel) : CLRBIT(fFlags, kUseCentralPixel);
+    }
+    void SetProcessPedestalRun(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kProcessPedestalRun) : CLRBIT(fFlags, kProcessPedestalRun);
+    }
+    void SetProcessPedestalEvt(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kProcessPedestalEvt) : CLRBIT(fFlags, kProcessPedestalEvt);
+    }
+    void SetProcessPedestal(Bool_t b=kTRUE)
+    {
+        SetProcessPedestalRun(!b);
+        SetProcessPedestalEvt(b);
+    }
+    void SetProcessTimes(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kProcessTimes) : CLRBIT(fFlags, kProcessTimes);
+    }
+    void SetHardTreatment(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kHardTreatment) : CLRBIT(fFlags, kHardTreatment);
+    }
+
+    Bool_t IsHardTreatment() const      { return TESTBIT(fFlags, kHardTreatment); }
+    Bool_t IsProcessPedestalRun() const { return TESTBIT(fFlags, kProcessPedestalRun); }
+    Bool_t IsProcessPedestalEvt() const { return TESTBIT(fFlags, kProcessPedestalEvt); }
+    Bool_t IsProcessTimes() const       { return TESTBIT(fFlags, kProcessTimes); }
+    Bool_t IsUseCentralPixel() const    { return TESTBIT(fFlags, kUseCentralPixel); }
+    Bool_t IsUseInterpolation() const   { return TESTBIT(fFlags, kUseInterpolation); }
+
+    void SetNumMinNeighbors(Byte_t num) { fNumMinNeighbors=num; }
+    void AddNamePedPhotCam(const char *name="MPedPhotCam");
+    void SetNamePedPhotCam(const char *name)
+    {
+        AddNamePedPhotCam(name);
+    } // Deprecated! Use AddNamePedPhotCam instead (directly)
+
+    ClassDef(MBadPixelsTreat, 1) // Task to treat bad pixels (interpolation, unmapping)
+}; 
+
+#endif
+
Index: /tags/Mars-V0.9/mbadpixels/MHBadPixels.cc
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MHBadPixels.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MHBadPixels.cc	(revision 9772)
@@ -0,0 +1,255 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHBadPixels
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHBadPixels.h" 
+
+#include <TCanvas.h>
+
+#include "MPointingPos.h"
+#include "MBadPixelsCam.h"
+#include "MGeomCam.h"
+#include "MPedPhotCam.h"
+#include "MParList.h"
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHBadPixels);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+//  Constructor.
+//
+MHBadPixels::MHBadPixels(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHBadPixels";
+    fTitle = title ? title : "Histogram for Bad Pixels vs. Theta";
+
+    fBadId = new TH2D;
+    fBadId->SetName("2D-IdBadPixels");
+    fBadId->SetTitle("2D-IdBadPixels");
+    fBadId->SetDirectory(NULL);
+    fBadId->UseCurrentStyle();
+    fBadId->SetXTitle("\\Theta [\\circ]");
+    fBadId->SetYTitle("pixel Id");
+    fBadId->SetTitleOffset(1.2, "Y");
+
+    fBadN = new TH2D;
+    fBadN->SetName("2D-NBadPixels");
+    fBadN->SetTitle("2D-NBadPixels");
+    fBadN->SetDirectory(NULL);
+    fBadN->UseCurrentStyle();
+    fBadN->SetXTitle("\\Theta [\\circ]");
+    fBadN->SetYTitle("number of bad pixels");
+    fBadN->SetTitleOffset(1.2, "Y");
+
+    // define default binnings
+    fBinsTheta = new MBinning;
+    fBinsTheta->SetEdgesCos(10,  0.0,  90.0);    // theta
+
+    fBinsPix = new MBinning;
+    fBinsPix->SetEdges(578, -0.5, 577.5);    // pixel id
+
+    SetBinning(fBadId, fBinsTheta, fBinsPix);
+    SetBinning(fBadN,  fBinsTheta, fBinsPix);
+
+    //-----------------------------------------
+    fNamePedPhotCam = "MPedPhotCamFromData";
+}
+
+
+// -------------------------------------------------------------------------
+//
+//  Destructor.
+//
+MHBadPixels::~MHBadPixels()
+{
+  delete fBadId;
+  delete fBadN;
+
+  delete fBinsTheta;
+  delete fBinsPix;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHBadPixels::SetupFill(const MParList *plist)
+{
+    fCam = (MGeomCam*)plist->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fCam)    
+    {
+        *fLog << err << "MHBadPixels::SetupFill; MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+    *fLog << "MHBadPixels::SetupFill; fCam = " << fCam << endl;
+
+    fPointPos = (MPointingPos*)plist->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+    
+    fPedPhot = (MPedPhotCam*)plist->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+    if (!fPedPhot)
+    {
+        *fLog << err << AddSerialNumber(fNamePedPhotCam) 
+              << "[MPedPhotCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+    fPedPhot->InitSize(fCam->GetNumPixels());
+
+
+    //----------------------------------------------------
+    *fLog << inf << "Name of MPedPhotCam container : " << fNamePedPhotCam
+          << endl;
+
+
+    //----------------------------------------------------
+    // redefine the binnings
+    
+    // Get Theta Binning
+    const MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta", "MBinning");
+    if (!binstheta)
+    {
+        *fLog << err << "Object 'BinningTheta' [MBinning] not found... use default binning." << endl;
+        binstheta = fBinsTheta;
+    }
+
+    // Define binning for pixel number
+    const UInt_t npix1 = fPedPhot->GetSize()+1;
+    //*fLog << "MHBadPixels::SetupFill(); npix1 = " << npix1 << endl;
+    MBinning binspix("BinningPixel");
+    binspix.SetEdges(npix1, -0.5, npix1-0.5);
+
+    // Set binnings in histograms
+    SetBinning(fBadId, binstheta, &binspix);
+    SetBinning(fBadN,  binstheta, &binspix);
+
+    *fLog << "MHBadPixels::SetupFill(); binnings were set" << endl;
+    
+
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+// 
+// Fill the histograms
+//
+
+Bool_t MHBadPixels::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+        return kFALSE;
+
+    Double_t theta = fPointPos->GetZd();
+
+    const MBadPixelsCam *fBadPixels = (MBadPixelsCam*)par;
+
+    const UInt_t entries = fPedPhot->GetSize(); 
+    UInt_t nb = 0;
+    for (UInt_t i=0; i<entries; i++)
+    {
+      //*fLog << "MHBadPixels::Fill; i = " << i << endl;
+
+      if ( (*fBadPixels)[i].IsUnsuitable() )
+      {
+	//*fLog << "MHBadPixels::Fill; (UnSuitable) " << endl;
+
+          fBadId->Fill(theta, i, w);
+          nb++;
+      }   
+    }
+    fBadN->Fill(theta, nb, w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------
+//
+// Draw the histograms
+//
+void MHBadPixels::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(2,2);
+
+    TH1D *h;
+
+    pad->cd(1);
+    fBadId->Draw(option);
+
+    pad->cd(2);
+    fBadN->Draw(option);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = ((TH2*)fBadId)->ProjectionY("ProjY-pixId", -1, 9999, "");
+    h->SetDirectory(NULL);
+    h->SetTitle("Distribution of bad pixel Id");
+    h->SetXTitle("Id of bad pixel");
+    h->SetYTitle("No. of events");
+    h->SetTitleOffset(1.2, "Y");
+    h->Draw(option);
+    h->SetBit(kCanDelete);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    h = ((TH2*)fBadN)->ProjectionY("ProjY-pixN", -1, 9999, "");
+    h->SetDirectory(NULL);
+    h->SetTitle("Distribution of no.of bad pixels");
+    h->SetXTitle("No. of bad pixels");
+    h->SetYTitle("No. of events");
+    h->SetTitleOffset(1.2, "Y");
+    h->Draw(option);
+    h->SetBit(kCanDelete);
+
+    pad->Modified();
+    pad->Update();
+}
+//==========================================================================
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mbadpixels/MHBadPixels.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MHBadPixels.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MHBadPixels.h	(revision 9772)
@@ -0,0 +1,54 @@
+#ifndef MARS_MHBadPixels
+#define MARS_MHBadPixels
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MPedPhotCam;
+class MPointingPos;
+class MParList;
+class MGeomCam;
+
+class MHBadPixels : public MH
+{
+private:
+    MGeomCam      *fCam;      //!
+    MPedPhotCam   *fPedPhot;  //!
+    MPointingPos  *fPointPos; //!
+
+    TString  fNamePedPhotCam; //! name of the 'MPedPhotCam' container
+    MBinning *fBinsTheta;     //!
+    MBinning *fBinsPix;       //!
+
+    TH2D          *fBadId; // 2D-histogram : pixel Id vs. Theta
+    TH2D          *fBadN;  // 2D-histogram : no.of bad pixels vs. Theta
+
+public:
+    MHBadPixels(const char *name=NULL, const char *title=NULL);
+    ~MHBadPixels();
+
+    void SetNamePedPhotCam(const char *name)  { fNamePedPhotCam = name; }
+
+    const TH2D *GetBadId()       { return fBadId; }
+    const TH2D *GetBadId() const { return fBadId; }
+
+    const TH2D *GetBadN()       { return fBadN; }
+    const TH2D *GetBadN() const { return fBadN; }
+
+    TH2 *GetBadIdByName(const TString name) { return fBadId; }
+    TH2 *GetBadNByName(const TString name)  { return fBadN; }
+
+    void Draw(Option_t* option = "");
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    ClassDef(MHBadPixels, 1)  // Histogram of bad pixel Id vs. Theta
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mbadpixels/MMcBadPixelsSet.cc
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MMcBadPixelsSet.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MMcBadPixelsSet.cc	(revision 9772)
@@ -0,0 +1,147 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch    12/2001 <mailto:blanch@ifae.es>
+!   Author(s): Thomas Bretz    08/2002 <mailto:tbretz@astro.uni.wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMcBadPixelsSet
+//
+//  This task tries to identify the starfield from the
+//  MMcRunHeader container and tries to identifies it. If it is known
+//  (eg. Crab) the fixed build in pixel numbers are used as blind
+//  pixels.
+//
+//  Implemented star fields (for the MAGIC camera only):
+//   - Crab: 400, 401, 402, 437, 438, 439
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MBadPixels
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcBadPixelsSet.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MMcRunHeader.hxx"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MMcBadPixelsSet);
+
+using namespace std;
+
+static const TString gsDefName  = "MMcBadPixelsSet";
+static const TString gsDefTitle = "Set predefined star fields";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMcBadPixelsSet::MMcBadPixelsSet(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MMcBadPixelsSet::PreProcess (MParList *pList)
+{
+    fBadPixels = (MBadPixelsCam*)pList->FindCreateObj(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+        return kFALSE;
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+    {
+        *fLog << err << dbginf << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  - Check whether pixels to disable are available. If pixels are
+//    given by the user nothing more is done.
+//  - Otherwise try to determin the blind pixels from the starfield
+//    given in MMcRunHeader.
+//
+Bool_t MMcBadPixelsSet::ReInit(MParList *pList)
+{
+    if (!fGeomCam->InheritsFrom("MGeomCamMagic"))
+    {
+        *fLog << warn << "MMcBadPixelsSet::ReInit: Warning - Starfield only implemented for Magic standard Camera... no action." << endl;
+        return kTRUE;
+    }
+
+    //
+    // Set as blind some particular pixels because of a particular
+    // Star Field of View.
+    //
+    MMcRunHeader *mcrun = (MMcRunHeader*)pList->FindObject("MMcRunHeader");
+    if (!mcrun)
+    {
+        *fLog << warn << "MMcBadPixelsSet::ReInit: Warning - No run header available... no action." << endl;
+        return kTRUE;
+    }
+
+    Int_t rah, ram, ras;
+    Int_t ded, dem, des;
+    mcrun->GetStarFieldRa(&rah, &ram, &ras);
+    mcrun->GetStarFieldDec(&ded, &dem, &des);
+
+    if (rah!=5 || ram!=34 || ras!=32 || ded!=22 || dem!=0 || des!=55)
+    {
+        *fLog << warn << "Warning - Starfield unknown..." << endl;
+        return kTRUE;
+    }
+
+    //
+    // Case for Crab Nebula FOV
+    //
+    (*fBadPixels)[400].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+    (*fBadPixels)[401].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+    (*fBadPixels)[402].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+    (*fBadPixels)[437].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+    (*fBadPixels)[438].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+    (*fBadPixels)[439].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+
+    *fLog << inf;
+    *fLog << "FOV is centered at CRAB NEBULA: Setting 6 blind pixels" << endl;
+    *fLog << "to avoid bias values of analysis due to CRAB NEBULA:" << endl;
+    *fLog << "   Pixels: 400, 401, 402, 437, 438, 439" << endl;
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mbadpixels/MMcBadPixelsSet.h
===================================================================
--- /tags/Mars-V0.9/mbadpixels/MMcBadPixelsSet.h	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/MMcBadPixelsSet.h	(revision 9772)
@@ -0,0 +1,30 @@
+#ifndef MARS_MMcBadPixelsSet
+#define MARS_MMcBadPixelsSet
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MBadPixelsCam;
+
+class MMcBadPixelsSet : public MTask
+{
+private:
+    MBadPixelsCam *fBadPixels;  //!
+    MGeomCam      *fGeomCam;    //!
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MMcBadPixelsSet(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MMcBadPixelsSet, 1) // Task to deal with known MC star-fields
+}; 
+
+#endif
+
+
+
+
Index: /tags/Mars-V0.9/mbadpixels/Makefile
===================================================================
--- /tags/Mars-V0.9/mbadpixels/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mbadpixels/Makefile	(revision 9772)
@@ -0,0 +1,50 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = BadPixels
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../manalysis -I../mgeom -I../mgui \
+           -I../mmc -I../mpedestal -I../msignal -I../mpointing \
+           -I../mhbase
+# MBadPixelsCalc  (manalysis): MPedPhotCam, MSigmabar
+# MBadPixelsCalc  (mgeom):     MGeomCam
+# MBadPixelsCam   (mgui):      MCamEvent
+# MMcBadPixelsSet (mmc):       MMcRunHeader
+# MBadPixelsTreat (mpedestal): MPedPhot*
+# MBadPixelsTreat (msignal):   MArrivalTime
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MBadPixelsPix.cc \
+           MBadPixelsCam.cc \
+           MBadPixelsIntensityCam.cc \
+           MBadPixelsMerge.cc \
+           MBadPixelsCalc.cc \
+           MBadPixelsTreat.cc \
+           MMcBadPixelsSet.cc \
+           MHBadPixels.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mbase/BaseIncl.h
===================================================================
--- /tags/Mars-V0.9/mbase/BaseIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/BaseIncl.h	(revision 9772)
@@ -0,0 +1,12 @@
+#ifndef __CINT__
+
+/*
+#include <fstream.h>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include <TGListBox.h>
+*/
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mbase/BaseLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mbase/BaseLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/BaseLinkDef.h	(revision 9772)
@@ -0,0 +1,78 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+// Global constants
+#pragma link C++ global kCONTINUE;
+#pragma link C++ global kRad2Deg;
+
+// Logging
+#pragma link C++ global gLog;
+
+#pragma link C++ class MLog+;
+#pragma link C++ class MLogPlugin+;
+#pragma link C++ class MLogHtml+;
+
+// Basic Network Tools
+#pragma link C++ class MReadSocket+;
+
+// Basic Tools
+#pragma link C++ namespace MMath;
+#pragma link C++ class MString+;
+#pragma link C++ class MEnv+;
+#pragma link C++ class MIter+;
+#pragma link C++ class MDirIter+;
+#pragma link C++ class MRunIter+;
+
+// Mars core
+#pragma link C++ class MInputStreamID+;
+
+#pragma link C++ class MParContainer+;
+#pragma link C++ class MParList+;
+
+#pragma link C++ class MTask+;
+#pragma link C++ class MTaskEnv+;
+#pragma link C++ class MTaskInteractive+;
+#pragma link C++ class MTaskList+;
+
+#pragma link C++ class MFilter+;
+
+#pragma link C++ class MEvtLoop+;
+
+// Mars core (GUI part)
+#pragma link C++ class MStatusArray+;
+#pragma link C++ class MStatusDisplay+;
+#pragma link C++ class MProgressBar+;
+#pragma link C++ class MSearch+;
+
+#pragma link C++ class MGTask+;
+#pragma link C++ class MGList+;
+#pragma link C++ class MGMap+;
+#pragma link C++ class MGGroupFrame+;
+
+// Root enhancements
+//#pragma link C++ class MGraph+;
+
+// Basic containers
+#pragma link C++ class MArray;
+#pragma link C++ class MArrayB;
+#pragma link C++ class MArrayS;
+#pragma link C++ class MArrayD;
+#pragma link C++ class MArrayF;
+#pragma link C++ class MArrayI;
+
+#pragma link C++ class MTime+;
+#pragma link C++ function operator<<(ostream&, const MTime&);
+#pragma link C++ function operator>>(istream&, MTime&);
+
+#pragma link C++ class MArgs+;
+#pragma link C++ class MArgsEntry+;
+
+// Tool tasks
+#pragma link C++ class MClone+;
+#pragma link C++ class MPrint+;
+#pragma link C++ class MContinue+;
+
+#endif
Index: /tags/Mars-V0.9/mbase/MAGIC.h
===================================================================
--- /tags/Mars-V0.9/mbase/MAGIC.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MAGIC.h	(revision 9772)
@@ -0,0 +1,32 @@
+#ifndef MARS_MAGIC
+#define MARS_MAGIC
+///////////////////////////////////////////////////////////////////////////////
+//
+//     Magic.h
+//
+//     defines MAGIC base informations
+//
+///////////////////////////////////////////////////////////////////////////////
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+
+//
+// Check here if Mars can be compiled with the present root version
+//
+#ifndef __CINT__
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,06)
+#error Your root version is too old to compile Mars, use root>=3.05/06
+#endif
+#endif
+
+//
+// Values for the eventloop control
+//
+const Int_t kCONTINUE = 2;
+const Int_t kSKIP     = 2;
+const Int_t kERROR    = 3;
+
+const Double_t kRad2Deg = 180.0/3.1415926535897932384626433832795028841971693993751;
+
+#endif
Index: /tags/Mars-V0.9/mbase/MArgs.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MArgs.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArgs.cc	(revision 9772)
@@ -0,0 +1,430 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 7/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2003-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArgs
+//
+// This is a helper class for executables to parse command line arguments
+//
+// Arguments beginning with a trailing '-' are called 'options'.
+// Arguments without a trailing '-' are considered 'arguments'
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArgs.h"
+
+#include <stdlib.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MArgsEntry);
+ClassImp(MArgs);
+
+using namespace std;
+
+void MArgsEntry::Print(const Option_t *o) const
+{
+    gLog << all << *this << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes:
+//  fName: The name of the executable
+//  fArgv: A TList containing all other command line arguments
+//
+//  If root==kFALSE all root commandline options are deleted from
+//  the list, namely: -b
+//
+MArgs::MArgs(int argc, char **argv, Bool_t root) : fArgc(argc)
+{
+    // FIXME: argv has no const-qualifier to be idetical with
+    //        TApplication.
+    fName = argv[0];
+
+    fArgv = new TList;
+    fArgv->SetOwner();
+
+    for (int i=1; i<argc; i++)
+    {
+        MArgsEntry &o = *new MArgsEntry(argv[i]);
+        dynamic_cast<TString&>(o) = o.Strip(TString::kBoth);
+        fArgv->Add(&o);
+    }
+
+    if (root)
+        return;
+
+    HasOnlyAndRemove("-b");
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes fArgv.
+//
+MArgs::~MArgs()
+{
+    delete fArgv;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print everything parsed.
+// Using 'options' as option only 'options' are printed.
+// Using 'arguments' as option only 'arguments' are printed.
+//
+void MArgs::Print(const Option_t *o) const
+{
+    gLog << all << underline << fName << ":" << endl;
+
+    const TString str(o);
+
+    if (!str.CompareTo("options", TString::kIgnoreCase))
+    {
+        TIter Next(fArgv);
+        TString *s = NULL;
+        while ((s=dynamic_cast<TString*>(Next())))
+            if (s->BeginsWith("-"))
+                gLog << *s << endl;
+        return;
+    }
+
+    if (!str.CompareTo("arguments", TString::kIgnoreCase))
+    {
+        TIter Next(fArgv);
+        TString *s = NULL;
+        while ((s=dynamic_cast<TString*>(Next())))
+            if (!s->BeginsWith("-"))
+                gLog << *s << endl;
+        return;
+    }
+
+    fArgv->Print();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Integer corresponding to the command line argument 'name'
+//  eg. executable -argument 5
+//      GetInt("argument") will return 5
+//
+Int_t MArgs::GetInt(const TString name) const
+{
+    return atoi(GetString(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the floating point value corresponding to the command line argument
+// 'name'
+//  eg. executable -argument 5.7
+//      GetFloat("argument") will return 5.7
+//
+Double_t MArgs::GetFloat(const TString name) const
+{
+    return atof(GetString(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the TString corresponding to the command line argument 'name'
+//  eg. executable -argument=last
+//      GetString("-argument=") will return "last"
+//
+TString MArgs::GetString(const TString name) const
+{
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (s->BeginsWith(name))
+            return s->Data()+s->Index(name)+name.Length();
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Integer corresponding to the command line argument 'name'
+//  eg. executable -argument5
+//      GetIntAndRemove("-argument") will return 5
+// and removes the argument from the internal list.
+//
+Int_t MArgs::GetIntAndRemove(const TString name)
+{
+    return atoi(GetStringAndRemove(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the floating point value corresponding to the command line argument
+// 'name'
+//  eg. executable -argument5.7
+//      GetFloatAndRemove("-argument") will return 5.7
+// and removes the argument from the internal list.
+//
+Double_t MArgs::GetFloatAndRemove(const TString name)
+{
+    return atof(GetStringAndRemove(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the TString corresponding to the command line argument 'name'
+//  eg. executable -argument=last
+//      GetStringAndRemove("-argument=") will return "last"
+// and removes the argument from the internal list.
+//
+TString MArgs::GetStringAndRemove(const TString n)
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (s->BeginsWith(name))
+        {
+            TString str = s->Data()+s->Index(name)+name.Length();
+            delete fArgv->Remove(dynamic_cast<TObject*>(s));
+            return str;
+        }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Integer corresponding to the i-th argument. This is ment
+// for enumerations like
+//  executable 1 7 2
+//  GetArgumentInt(1) will return 7
+//
+Int_t MArgs::GetArgumentInt(Int_t i) const
+{
+    return atoi(GetArgumentStr(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the floating point value corresponding to the i-th argument.
+// This is ment for enumerations like
+//  executable 1.7 7.5 2.3
+//  GetArgumentFloat(1) will return 7.5
+//
+Float_t MArgs::GetArgumentFloat(Int_t i) const
+{
+    return atof(GetArgumentStr(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns GetIntAndRemove. If HasOption returns kFALSE def is returned.
+//
+Int_t MArgs::GetIntAndRemove(const TString name, Int_t def)
+{
+    if (!HasOption(name))
+        return def;
+    return GetIntAndRemove(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns GetFloatAndRemove. If HasOption returns kFALSE def is returned.
+//
+Double_t MArgs::GetFloatAndRemove(const TString name, Double_t def)
+{
+    if (!HasOption(name))
+        return def;
+    return GetFloatAndRemove(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns GetStringAndRemove. If HasOption returns kFALSE def is returned.
+//
+TString MArgs::GetStringAndRemove(const TString name, const TString def)
+{
+    if (!HasOption(name))
+        return def;
+    return GetStringAndRemove(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the TString corresponding to the i-th argument.
+// This is ment for enumerations like
+//  executable file1 file2 file3
+//  GetArgumentStr(1) will return "file2"
+// Only arguments without a trailing '-' are considered
+//
+TString MArgs::GetArgumentStr(Int_t i) const
+{
+    Int_t num = 0;
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+    {
+        if (s->BeginsWith("-"))
+            continue;
+
+        if (i==num++)
+            return *s;
+    }
+
+    return "";
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of arguments without a trainling '-'
+//
+Int_t MArgs::GetNumArguments() const
+{
+    Int_t num = 0;
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (!s->BeginsWith("-"))
+            num++;
+
+    return num;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of arguments with a trainling '-'
+//
+Int_t MArgs::GetNumOptions() const
+{
+    Int_t num = 0;
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (s->BeginsWith("-"))
+            num++;
+
+    return num;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the total number of entries
+//
+Int_t MArgs::GetNumEntries() const
+{
+    return fArgv->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an argument beginning with 'n' is existing, eg:
+//  executable -value5
+//  executable -value
+//  HasOption("-value") will return true in both cases
+//
+Bool_t MArgs::Has(const TString n) const
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (s->BeginsWith(name))
+            return kTRUE;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an argument beginning with 'n' is existing, eg:
+//  executable -value5
+//   HasOption("-value") will return false
+//  executable -value
+//   HasOption("-value") will return true
+//
+Bool_t MArgs::HasOnly(const TString n) const
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (*s==name)
+            return kTRUE;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an argument beginning with 'n' is exists and a
+// corresponding option is available, eg.
+//  executable -value5
+//  HasOption("-value") will return true
+// but:
+//  executable -value
+//  HasOption("-value") will return false
+//
+Bool_t MArgs::HasOption(const TString n) const
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (s->BeginsWith(name) && s->Length()>name.Length())
+            return kTRUE;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether an argument beginning with 'n' is exists and a
+// corresponding option is available, eg.
+//  executable -value5
+//  HasOption("-value") will return false
+// but:
+//  executable -value
+//  HasOption("-value") will return true
+//
+// The argument is removed from the internal list.
+//
+Bool_t MArgs::HasOnlyAndRemove(const TString n)
+{
+    const TString name = n.Strip(TString::kBoth);
+
+    Bool_t rc = kFALSE;
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (*s==name)
+        {
+            delete fArgv->Remove(dynamic_cast<TObject*>(s));
+            rc = kTRUE;
+        }
+
+    return rc;
+}
Index: /tags/Mars-V0.9/mbase/MArgs.h
===================================================================
--- /tags/Mars-V0.9/mbase/MArgs.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArgs.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MArgs
+#define MARS_MArgs
+
+#ifndef ROOT_TNamed
+#include <TNamed.h>
+#endif
+
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+
+class MArgsEntry : public TString, public TObject
+{
+public:
+    MArgsEntry(const char *c) : TString(c), TObject() {}
+
+    void Print(const Option_t *o) const;
+
+    ClassDef(MArgsEntry, 0)
+};
+
+class MArgs : public TNamed
+{
+private:
+    Int_t  fArgc;
+    TList *fArgv; //->
+
+public:
+    MArgs(int argc, char **argv, Bool_t root=kFALSE);
+    ~MArgs();
+
+    void Print(const Option_t *o="") const;
+
+    // FIXME: Add max, min option
+    // FIXME: Add default option
+
+    Int_t    GetInt(const TString name) const;
+    Double_t GetFloat(const TString name) const;
+    TString  GetString(const TString name) const;
+
+    Int_t    GetIntAndRemove(const TString name);
+    Double_t GetFloatAndRemove(const TString name);
+    TString  GetStringAndRemove(const TString name);
+
+    Int_t    GetIntAndRemove(const TString name, Int_t def);
+    Double_t GetFloatAndRemove(const TString name, Double_t def);
+    TString  GetStringAndRemove(const TString name, const TString def);
+
+    Bool_t   Has(const TString name) const;
+    Bool_t   HasOnly(const TString name) const;
+    Bool_t   HasOption(const TString name) const;
+    Bool_t   HasOnlyAndRemove(const TString name);
+
+    TString  GetArgumentStr(Int_t i) const;
+    Int_t    GetArgumentInt(Int_t i) const;
+    Float_t  GetArgumentFloat(Int_t i) const;
+    Int_t    GetNumArguments() const;
+    Int_t    GetNumOptions() const;
+    Int_t    GetNumEntries() const;
+
+    ClassDef(MArgs, 0)  //Class to parse command line arguments
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MArray.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MArray.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArray.cc	(revision 9772)
@@ -0,0 +1,41 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// MArray                                                                   //
+//                                                                          //
+// This is an abstract base class for TObject derived Arrays. In principal  //
+// it is almost the same than TArray. The difference is that this array     //
+// base classed is derived from TObject which makes storage of variable     //
+// sized arrays possible with splitlevel=1.                                 //
+//                                                                          //
+// This should not be needed anymore for root >3.00                         //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MArray.h"
+
+ClassImp(MArray);
+
Index: /tags/Mars-V0.9/mbase/MArray.h
===================================================================
--- /tags/Mars-V0.9/mbase/MArray.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArray.h	(revision 9772)
@@ -0,0 +1,35 @@
+#ifndef MARS_MArray
+#define MARS_MArray
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MArray                                                                  //
+//                                                                         //
+// Abstract array base class for TObject derived Arrays                    //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+class MArray : public TObject
+{
+protected:
+    UInt_t fN; // Number of array elements
+
+public:
+   MArray()                              { fN = 0; }
+   MArray(UInt_t n)                      { fN = n; }
+   MArray(const MArray &a)               { fN = a.fN; }
+   virtual ~MArray()                     { fN = 0; }
+
+   MArray &operator=(const MArray &rhs)  { fN = rhs.fN; return *this; }
+
+   UInt_t       GetSize() const          { return fN; }
+   virtual void Set(UInt_t n) = 0;
+   
+   ClassDef(MArray, 1)  //Abstract array base class for TObject derived Arrays
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MArrayB.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayB.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayB.cc	(revision 9772)
@@ -0,0 +1,38 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayB
+//
+// Array of Byte_t. It is almost the same than TArrayC, but it containes
+// Byte_t instead of Char_t and it can be stored with splitlevel=1 to a
+// a root-file because of it's derivement from MArray (TObject)                                                                                    //
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayB.h"
+
+ClassImp(MArrayB);
+
Index: /tags/Mars-V0.9/mbase/MArrayB.h
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayB.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayB.h	(revision 9772)
@@ -0,0 +1,178 @@
+#ifndef MARS_MArrayB
+#define MARS_MArrayB
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MArrayB                                                                 //
+//                                                                         //
+// Array of Byte_t                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MArray
+#include "MArray.h"
+#endif
+
+#include <string.h>
+
+class MArrayB : public MArray
+{
+private:
+    Byte_t *fArray; //[fN] Array of fN chars
+
+public:
+
+    MArrayB()
+    {
+        fN     = 0;
+        fArray = NULL;
+    }
+
+    MArrayB(UInt_t n)
+    {
+        fN     = 0;
+        fArray = NULL;
+
+        Set(n);
+    }
+
+    MArrayB(UInt_t n, Byte_t *array)
+    {
+        // Create TArrayC object and initialize it with values of array.
+        fN     = 0;
+        fArray = NULL;
+
+        Set(n, array);
+    }
+
+    MArrayB(const MArrayB &array)
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    UInt_t GetSize() const
+    {
+        return fN;
+    }
+
+    MArrayB &operator=(const MArrayB &rhs)
+    {
+        // TArrayC assignment operator.
+        if (this != &rhs)
+            Set(rhs.fN, rhs.fArray);
+        return *this;
+    }
+
+    virtual ~MArrayB()
+    {
+        // Delete TArrayC object.
+        delete [] fArray;
+        fArray = NULL;
+    }
+
+    void Adopt(UInt_t n, Byte_t *array)
+    {
+        // Adopt array arr into TArrayC, i.e. don't copy arr but use it directly
+        // in TArrayC. User may not delete arr, TArrayC dtor will do it.
+        if (fArray)
+            delete [] fArray;
+
+        fN     = n;
+        fArray = array;
+    }
+
+    void AddAt(Byte_t c, UInt_t i)
+    {
+        // Add char c at position i. Check for out of bounds.
+        fArray[i] = c;
+    }
+
+    void AddAt(Byte_t *array, UInt_t i, UInt_t n)
+    {
+        // Add char c at position i. Check for out of bounds.
+        memcpy(fArray+i, array, n*sizeof(Byte_t));
+    }
+
+    Byte_t     At(UInt_t i)
+    {
+        return fArray[i];
+    }
+
+    Byte_t    *GetArray() const
+    {
+        return fArray;
+    }
+
+    void Reset()
+    {
+        memset(fArray, 0, fN*sizeof(Byte_t));
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        Byte_t *temp = fArray;
+        if (n == 0)
+            fArray = 0;
+        else
+        {
+            fArray = new Byte_t[n];
+            if (n < fN)
+                memcpy(fArray,temp, n*sizeof(Byte_t));
+            else
+            {
+                memcpy(fArray,temp,fN*sizeof(Byte_t));
+                memset(&fArray[fN],0,(n-fN)*sizeof(Byte_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, Byte_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new Byte_t[fN];
+
+        memcpy(fArray,array, n*sizeof(Byte_t));
+    }
+
+    Byte_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const Byte_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    ClassDef(MArrayB, 1)  //Array of Byte_t
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MArrayD.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayD.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayD.cc	(revision 9772)
@@ -0,0 +1,73 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayD
+//
+// Array of Double_t. It is almost the same than TArrayD but derives from
+// TObject
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayD.h"
+#include "TArrayD.h"
+
+ClassImp(MArrayD);
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArrayD::StripZeros(TArrayD &arr)
+{
+
+  const Int_t n = arr.GetSize();
+  
+  for (Int_t i=n-1; i>=0; i--)
+    if (arr[i] != 0)
+        {
+          arr.Set(i+1);
+          break;
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArrayD::StripZeros()
+{
+    const Int_t n = GetSize();
+
+    for (Int_t i=n-1; i>=0; i--)
+      if ((*this)[i] != 0)
+        {
+          Set(i+1);
+          break;
+        }
+}
+
Index: /tags/Mars-V0.9/mbase/MArrayD.h
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayD.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayD.h	(revision 9772)
@@ -0,0 +1,165 @@
+#ifndef MARS_MArrayD
+#define MARS_MArrayD
+
+#ifndef MARS_MArray
+#include "MArray.h"
+#endif
+
+#include <string.h>
+
+class TArrayD;
+class MArrayD : public MArray
+{
+private:
+    Double_t *fArray; //[fN] Array of fN chars
+
+public:
+
+    MArrayD()
+    {
+        fN     = 0;
+        fArray = NULL;
+    }
+
+    MArrayD(UInt_t n)
+    {
+        fN     = 0;
+        fArray = NULL;
+        Set(n);
+    }
+
+    MArrayD(UInt_t n, Double_t *array)
+    {
+        // Create TArrayC object and initialize it with values of array.
+        fN     = 0;
+        fArray = NULL;
+        Set(n, array);
+    }
+
+    MArrayD(const MArrayD &array)
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    UInt_t GetSize() const
+    {
+        return fN;
+    }
+
+    MArrayD &operator=(const MArrayD &rhs)
+    {
+        // TArrayC assignment operator.
+        if (this != &rhs)
+            Set(rhs.fN, rhs.fArray);
+        return *this;
+    }
+
+    virtual ~MArrayD()
+    {
+        // Delete TArrayC object.
+        delete [] fArray;
+        fArray = NULL;
+    }
+
+    void Adopt(UInt_t n, Double_t *array)
+    {
+        // Adopt array arr into TArrayC, i.e. don't copy arr but use it directly
+        // in TArrayC. User may not delete arr, TArrayC dtor will do it.
+        if (fArray)
+            delete [] fArray;
+
+        fN     = n;
+        fArray = array;
+    }
+
+    void AddAt(Double_t c, UInt_t i)
+    {
+        // Add char c at position i. Check for out of bounds.
+        fArray[i] = c;
+    }
+
+    Double_t     At(UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    Double_t    *GetArray() const
+    {
+        return fArray;
+    }
+
+    void Reset()
+    {
+        memset(fArray, 0, fN*sizeof(Double_t));
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        Double_t *temp = fArray;
+        if (n == 0)
+            fArray = NULL;
+        else
+        {
+            fArray = new Double_t[n];
+            if (n < fN)
+                memcpy(fArray, temp, n*sizeof(Double_t));
+            else
+            {
+                memcpy(fArray, temp, fN*sizeof(Double_t));
+                memset(&fArray[fN], 0, (n-fN)*sizeof(Double_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, Double_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new Double_t[fN];
+
+        memcpy(fArray, array, n*sizeof(Double_t));
+    }
+
+    Double_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const Double_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    static void  StripZeros(TArrayD &arr);
+    void  StripZeros();
+
+    ClassDef(MArrayD, 1)  //Array of Double_t
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MArrayF.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayF.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayF.cc	(revision 9772)
@@ -0,0 +1,73 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayF
+//
+// Array of Float_t. It is almost the same than TArrayF but derives from
+// TObject
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayF.h"
+#include "TArrayF.h"
+
+ClassImp(MArrayF);
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArrayF::StripZeros(TArrayF &arr)
+{
+
+  const Int_t n = arr.GetSize();
+  
+  for (Int_t i=n-1; i>=0; i--)
+    if (arr[i] != 0)
+        {
+          arr.Set(i+1);
+          break;
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArrayF::StripZeros()
+{
+    const Int_t n = GetSize();
+
+    for (Int_t i=n-1; i>=0; i--)
+      if ((*this)[i] != 0)
+        {
+          Set(i+1);
+          break;
+        }
+}
+
Index: /tags/Mars-V0.9/mbase/MArrayF.h
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayF.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayF.h	(revision 9772)
@@ -0,0 +1,171 @@
+#ifndef MARS_MArrayF
+#define MARS_MArrayF
+
+#ifndef MARS_MArray
+#include "MArray.h"
+#endif
+
+#include <string.h>
+
+class TArrayF;
+class MArrayF : public MArray
+{
+private:
+    Float_t *fArray; //[fN] Array of fN chars
+
+public:
+
+    MArrayF()
+    {
+        fN     = 0;
+        fArray = NULL;
+    }
+
+    MArrayF(UInt_t n)
+    {
+        fN     = 0;
+        fArray = NULL;
+        Set(n);
+    }
+
+    MArrayF(UInt_t n, Float_t *array)
+    {
+        // Create TArrayC object and initialize it with values of array.
+        fN     = 0;
+        fArray = NULL;
+        Set(n, array);
+    }
+
+    MArrayF(const MArrayF &array)
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    UInt_t GetSize() const
+    {
+        return fN;
+    }
+
+    MArrayF &operator=(const MArrayF &rhs)
+    {
+        // TArrayC assignment operator.
+        if (this != &rhs)
+            Set(rhs.fN, rhs.fArray);
+        return *this;
+    }
+
+    virtual ~MArrayF()
+    {
+        // Delete TArrayC object.
+        delete [] fArray;
+        fArray = NULL;
+    }
+
+    void Adopt(UInt_t n, Float_t *array)
+    {
+        // Adopt array arr into TArrayC, i.e. don't copy arr but use it directly
+        // in TArrayC. User may not delete arr, TArrayC dtor will do it.
+        if (fArray)
+            delete [] fArray;
+
+        fN     = n;
+        fArray = array;
+    }
+
+    void AddAt(Float_t c, UInt_t i)
+    {
+        // Add char c at position i. Check for out of bounds.
+        fArray[i] = c;
+    }
+
+    Float_t     At(UInt_t i) const 
+    {
+        return fArray[i];
+    }
+
+    Float_t    *GetArray() const
+    {
+        return fArray;
+    }
+
+    void Reset()
+    {
+        memset(fArray, 0, fN*sizeof(Float_t));
+    }
+
+    void Reset(Float_t f)
+    {
+        for (UInt_t i=0; i<fN; i++)
+            fArray[i] = f;
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        Float_t *temp = fArray;
+        if (n == 0)
+            fArray = NULL;
+        else
+        {
+            fArray = new Float_t[n];
+            if (n < fN)
+                memcpy(fArray, temp, n*sizeof(Float_t));
+            else
+            {
+                memcpy(fArray, temp, fN*sizeof(Float_t));
+                memset(&fArray[fN], 0, (n-fN)*sizeof(Float_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, Float_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new Float_t[fN];
+
+        memcpy(fArray, array, n*sizeof(Float_t));
+    }
+
+    Float_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const Float_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    static void  StripZeros(TArrayF &arr);
+    void  StripZeros();
+
+    ClassDef(MArrayF, 1)  //Array of Float_t
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MArrayI.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayI.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayI.cc	(revision 9772)
@@ -0,0 +1,39 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayI
+//
+// Array of Int_t. It is almost the same than TArrayI but derives from
+// TObject
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayI.h"
+
+ClassImp(MArrayI);
+
Index: /tags/Mars-V0.9/mbase/MArrayI.h
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayI.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayI.h	(revision 9772)
@@ -0,0 +1,161 @@
+#ifndef MARS_MArrayI
+#define MARS_MArrayI
+
+#ifndef MARS_MArray
+#include "MArray.h"
+#endif
+
+#include <string.h>
+
+class MArrayI : public MArray
+{
+private:
+    Int_t *fArray; //[fN] Array of fN chars
+
+public:
+
+    MArrayI()
+    {
+        fN     = 0;
+        fArray = NULL;
+    }
+
+    MArrayI(UInt_t n)
+    {
+        fN     = 0;
+        fArray = NULL;
+        Set(n);
+    }
+
+    MArrayI(UInt_t n, Int_t *array)
+    {
+        // Create TArrayC object and initialize it with values of array.
+        fN     = 0;
+        fArray = NULL;
+        Set(n, array);
+    }
+
+    MArrayI(const MArrayI &array)
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    UInt_t GetSize() const
+    {
+        return fN;
+    }
+
+    MArrayI &operator=(const MArrayI &rhs)
+    {
+        // TArrayC assignment operator.
+        if (this != &rhs)
+            Set(rhs.fN, rhs.fArray);
+        return *this;
+    }
+
+    virtual ~MArrayI()
+    {
+        // Delete TArrayC object.
+        delete [] fArray;
+        fArray = NULL;
+    }
+
+    void Adopt(UInt_t n, Int_t *array)
+    {
+        // Adopt array arr into TArrayC, i.e. don't copy arr but use it directly
+        // in TArrayC. User may not delete arr, TArrayC dtor will do it.
+        if (fArray)
+            delete [] fArray;
+
+        fN     = n;
+        fArray = array;
+    }
+
+    void AddAt(Int_t c, UInt_t i)
+    {
+        // Add char c at position i. Check for out of bounds.
+        fArray[i] = c;
+    }
+
+    Int_t     At(UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    Int_t    *GetArray() const
+    {
+        return fArray;
+    }
+
+    void Reset()
+    {
+        memset(fArray, 0, fN*sizeof(Int_t));
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        Int_t *temp = fArray;
+        if (n == 0)
+            fArray = NULL;
+        else
+        {
+            fArray = new Int_t[n];
+            if (n < fN)
+                memcpy(fArray, temp, n*sizeof(Int_t));
+            else
+            {
+                memcpy(fArray, temp, fN*sizeof(Int_t));
+                memset(&fArray[fN], 0, (n-fN)*sizeof(Int_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, Int_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new Int_t[fN];
+
+        memcpy(fArray, array, n*sizeof(Int_t));
+    }
+
+    Int_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const Int_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    ClassDef(MArrayI, 1)  //Array of Int_t
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MArrayS.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayS.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayS.cc	(revision 9772)
@@ -0,0 +1,40 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MArrayS
+//
+// Array of UShort_t. It is almost the same than TArrayS, but it containes
+// UShort_t instead of Short_t and it can be stored with splitlevel=1 to a
+// a root-file because of it's derivement from MArray (TObject)                                                                                    //
+//
+// Another advantage is: operator[] has no range check!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayS.h"
+
+ClassImp(MArrayS);
+
Index: /tags/Mars-V0.9/mbase/MArrayS.h
===================================================================
--- /tags/Mars-V0.9/mbase/MArrayS.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MArrayS.h	(revision 9772)
@@ -0,0 +1,169 @@
+#ifndef MARS_MArrayS
+#define MARS_MArrayS
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MArrayS                                                                 //
+//                                                                         //
+// Array of UShort_t                                                       //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MArray
+#include "MArray.h"
+#endif
+
+#include <string.h>
+
+class MArrayS : public MArray
+{
+private:
+    UShort_t *fArray; //[fN] Array of fN chars
+
+public:
+
+    MArrayS()
+    {
+        fN     = 0;
+        fArray = NULL;
+    }
+
+    MArrayS(UInt_t n)
+    {
+        fN     = 0;
+        fArray = NULL;
+        Set(n);
+    }
+
+    MArrayS(UInt_t n, UShort_t *array)
+    {
+        // Create TArrayC object and initialize it with values of array.
+        fN     = 0;
+        fArray = NULL;
+        Set(n, array);
+    }
+
+    MArrayS(const MArrayS &array)
+    {
+        // Copy constructor.
+        fArray = NULL;
+        Set(array.fN, array.fArray);
+    }
+
+    UInt_t GetSize() const
+    {
+        return fN;
+    }
+
+    MArrayS &operator=(const MArrayS &rhs)
+    {
+        // TArrayC assignment operator.
+        if (this != &rhs)
+            Set(rhs.fN, rhs.fArray);
+        return *this;
+    }
+
+    virtual ~MArrayS()
+    {
+        // Delete TArrayC object.
+        delete [] fArray;
+        fArray = NULL;
+    }
+
+    void Adopt(UInt_t n, UShort_t *array)
+    {
+        // Adopt array arr into TArrayC, i.e. don't copy arr but use it directly
+        // in TArrayC. User may not delete arr, TArrayC dtor will do it.
+        if (fArray)
+            delete [] fArray;
+
+        fN     = n;
+        fArray = array;
+    }
+
+    void AddAt(UShort_t c, UInt_t i)
+    {
+        // Add char c at position i. Check for out of bounds.
+        fArray[i] = c;
+    }
+
+    UShort_t     At(UInt_t i)
+    {
+        return fArray[i];
+    }
+
+    UShort_t    *GetArray() const
+    {
+        return fArray;
+    }
+
+    void Reset()
+    {
+        memset(fArray, 0, fN*sizeof(UShort_t));
+    }
+
+    void Set(UInt_t n)
+    {
+        // Set size of this array to n chars.
+        // A new array is created, the old contents copied to the new array,
+        // then the old array is deleted.
+
+        if (n==fN)
+            return;
+
+        UShort_t *temp = fArray;
+        if (n == 0)
+            fArray = NULL;
+        else
+        {
+            fArray = new UShort_t[n];
+            if (n < fN)
+                memcpy(fArray, temp, n*sizeof(UShort_t));
+            else
+            {
+                memcpy(fArray, temp, fN*sizeof(UShort_t));
+                memset(&fArray[fN], 0, (n-fN)*sizeof(UShort_t));
+            }
+        }
+
+        if (fN)
+            delete [] temp;
+
+        fN = n;
+    }
+
+    void Set(UInt_t n, UShort_t *array)
+    {
+        // Set size of this array to n chars and set the contents.
+        if (!array)
+            return;
+
+        if (fArray && fN != n)
+        {
+            delete [] fArray;
+            fArray = 0;
+        }
+        fN = n;
+
+        if (fN == 0)
+            return;
+
+        if (!fArray)
+            fArray = new UShort_t[fN];
+
+        memcpy(fArray, array, n*sizeof(UShort_t));
+    }
+
+    UShort_t &operator[](UInt_t i)
+    {
+        return fArray[i];
+    }
+    const UShort_t &operator[](UInt_t i) const
+    {
+        return fArray[i];
+    }
+
+    ClassDef(MArrayS, 1)  //Array of UShort_t
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MClone.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MClone.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MClone.cc	(revision 9772)
@@ -0,0 +1,174 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  07/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MClone                                                                  //
+//                                                                          //
+//  This task clones a given paramter container. You can either specify     //
+//  the name of the container which should be cloned or a pointer to the    //
+//  container. If you specify a name the preprocessing tries to find the    //
+//  corresponding container in the parameter list.                          //
+//  Cloning in this context means duplicating the object in memory. This    //
+//  may be used if you change an object in the eventloop (eg. the image     //
+//  cleaning is changing the image) and you want to compare both 'version'  //
+//  of this object afterwards.                                              //
+//  The cloned object can be accessed by using MClone::GetClone.            //
+//  To clone the container more than once use several instances of MClone.  //
+//  The object does only exist until a new object is cloned. It is deleted  //
+//  in the destructor.                                                      //
+//                                                                          //
+//  To use MClone you must make sure, that TObject::Clone is correctly      //
+//  working for this class (maybe you have to overload it)                  //
+//                                                                          //
+//  Input Containers:                                                       //
+//   MParContainer                                                          //
+//                                                                          //
+//  Output Containers:                                                      //
+//   -/-                                                                    //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MClone.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MClone);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes name and title of the object. It is called by all
+// constructors.
+//
+void MClone::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MClone";
+    fTitle = title ? title : "Task to clone a parameter container for later usage";
+
+    fClone  = NULL;
+    fObject = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. Remembers the name to search for in the parameter list.
+//
+MClone::MClone(const char *obj, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fObjName = obj;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. Remember the pointer of the object which has to be cloned.
+//
+MClone::MClone(const TObject *obj, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fObject  = obj;
+    fObjName = obj->GetName();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. Deletes the cloned object.
+//
+MClone::~MClone()
+{
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Checks the parameter list for the existance of the parameter container. If
+//  the name of it was given in the constructor.
+//
+Int_t MClone::PreProcess(MParList *pList)
+{
+    //
+    // The pointer is already given by the user.
+    //
+    if (fObject)
+        return kTRUE;
+
+    //
+    // Try to find the parameter container with the given name in the list
+    //
+    fObject = pList->FindObject(fObjName);
+    if (fObject)
+        return kTRUE;
+
+    //
+    // If it couldn't get found stop Eventloop
+    //
+    *fLog << err << dbginf << fObjName << " not found... aborting." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete the cloned object if one is existing
+//
+void MClone::Clear(Option_t *)
+{
+    //
+    // Check if an object has been initialized
+    //
+    if (!fClone)
+        return;
+
+    //
+    // Delete it and set the pointer to NULL for the sanity check (above)
+    //
+    delete fClone;
+    fClone = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes an existing clone and clones the object (parameter container)
+//  again.
+//
+Int_t MClone::Process()
+{
+    //
+    // Delete an existing clone
+    //
+    Clear();
+
+    //
+    // Clone the given parameter container
+    //
+    fClone = fObject->Clone();
+
+    return kTRUE;
+} 
+
Index: /tags/Mars-V0.9/mbase/MClone.h
===================================================================
--- /tags/Mars-V0.9/mbase/MClone.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MClone.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MClone
+#define MARS_MClone
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class MClone : public MTask
+{
+private:
+    const TObject *fObject; // pointer to container which has to be cloned
+    TString fObjName;       // given name to search for in the parameterlist
+
+    TObject* fClone;        // pointer to the cloned object. deletion is handled by MClone
+
+    void Init(const char *name, const char *title);
+
+public:
+    MClone(const char *obj,    const char *name=NULL, const char *title=NULL);
+    MClone(const TObject *obj, const char *name=NULL, const char *title=NULL);
+    ~MClone();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    TObject *GetClone() const  { return fClone; }
+    const TObject *GetObject() const { return fObject; }
+
+    void Clear(Option_t *opt=NULL);
+
+    ClassDef(MClone, 0) // Task to clone (duplicate) an object in memory
+};
+    
+#endif
+
Index: /tags/Mars-V0.9/mbase/MContinue.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MContinue.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MContinue.cc	(revision 9772)
@@ -0,0 +1,286 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 10/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MContinue
+//
+// Does nothing than return kCONTINUE in the Process-function
+// (use with filters). For more details see the description of the
+// constructors.
+//
+// To invert the meaning of the contained filter call SetInverted()
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   -/-
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MContinue.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MF.h"
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MContinue);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Use this constructor if a rule (see MF for more details) shell be used.
+// MContinue will create a MF object and use it as a filter for the
+// instance. The MF-Task is added to the tasklist in front of the MContinue
+// instance and also automatically deleted, eg.
+//   MContinue cont("MHillas.fSize<20");
+//   tasklist.AddToList(&cont);
+// would skip all events which fullfill "MHillas.fSize<20" from this point
+// in the tasklist.
+// It is not necessary to put the filter in the tasklist. The PreProcess
+// will search for the filter and if it isn't found in the tasklist it
+// is added to the tasklist in front of MContinue.
+//
+// Use the default constructor (or an empty rule) if you want to read the
+// rule from a resource file.
+//
+MContinue::MContinue(const TString rule, const char *name, const char *title)
+    : fTaskList(0)
+{
+    fName  = name  ? name  : "MContinue";
+    fTitle = title ? title : "Task returning kCONTINUE";
+
+    if (rule.IsNull())
+        return;
+
+    SetBit(kIsOwner);
+
+    MTask::SetFilter(new MF(rule, TString("MF(")+fName+")"));
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this if you have a filter. Would be the same as if you would call:
+//   MContinue cont;
+//   cont.SetFilter(f);
+// It is not necessary to put the filter in the tasklist. The PreProcess
+// will search for the filter and if it isn't found in the tasklist it
+// is added to the tasklist in front of MContinue.
+//
+MContinue::MContinue(MFilter *f, const char *name, const char *title)
+    : fTaskList(0)
+{
+    fName  = name  ? name  : "MContinue";
+    fTitle = title ? title : "Task returning kCONTINUE";
+
+    SetFilter(f);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete the filter if it was created automatically
+//
+MContinue::~MContinue()
+{
+    if (TestBit(kIsOwner))
+        delete GetFilter();
+}
+
+// --------------------------------------------------------------------------
+//
+//  PreProcess tries to find the tasklist MTaskList, adds the filter
+//  before this instance to the tasklist and preprocesses the filter.
+//
+Int_t MContinue::PreProcess(MParList *list)
+{
+    ResetBit(kFilterIsPrivate);
+
+    if (!GetFilter())
+    {
+        if (IsAllowEmpty())
+        {
+            *fLog << warn << GetDescriptor() << " - WARNING: Empty filter found... task removed." << endl;
+            return kSKIP;
+        }
+
+        *fLog << err << dbginf << "Unknown fatal Error! (fFilter=NULL?!?)" << endl;
+        return kFALSE;
+    }
+
+    fTaskList = (MTaskList*)list->FindTaskListWithTask(this);
+    if (!fTaskList)
+    {
+        *fLog << err << dbginf << "ERROR - MTasklist not found... abort." << endl;
+        return kFALSE;
+    }
+
+    if (fTaskList->FindObject(GetFilter()))
+    {
+        *fLog << inf << dbginf << "The filter is already in the tasklist..." << endl;
+        return kTRUE;
+    }
+
+    if (!fTaskList->AddToListBefore(GetFilter(), this))
+    {
+        *fLog << err << dbginf << "ERROR - Adding filter before MContinue... abort." << endl;
+        return kFALSE;
+    }
+
+    // Make sure, that everything is correctly propageted to the childs
+    GetFilter()->SetDisplay(fDisplay);
+    GetFilter()->SetLogStream(fLog);
+
+    // Remeber that the filter is not already in tasklist
+    SetBit(kFilterIsPrivate);
+
+    return GetFilter()->CallPreProcess(list);
+}
+
+// --------------------------------------------------------------------------
+//
+// Propagate display to filter (if set)
+//
+void MContinue::SetDisplay(MStatusDisplay *d)
+{
+    if (GetFilter())
+        GetFilter()->SetDisplay(d);
+
+    MTask::SetDisplay(d);
+}
+
+// --------------------------------------------------------------------------
+//
+// Propagate log stream to filter (if set)
+//
+void MContinue::SetLogStream(MLog *lg)
+{
+    if (GetFilter())
+        GetFilter()->SetLogStream(lg);
+
+    MTask::SetLogStream(lg);
+}
+
+// --------------------------------------------------------------------------
+//
+// If the filter was added to the tasklist automatically it is removed
+// from the tasklist.
+//
+Int_t MContinue::PostProcess()
+{
+    if (!TestBit(kFilterIsPrivate))
+        return kTRUE;
+
+    if (fTaskList->RemoveFromList(GetFilter()))
+        return kTRUE;
+
+    *fLog << err << "ERROR: MContinue::PostProcess - Cannot remove Filter from tasklist" << endl;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If a filter is setup, call its 'IsInverted' to invert its meaning
+// (boolean "not")
+//
+void MContinue::SetInverted(Bool_t i)
+{
+    if (GetFilter())
+        GetFilter()->SetInverted(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// If a filter is setup, its IsInverted status is returned. If now filter
+// has been setup yet, kFALSE is returned.
+//
+Bool_t MContinue::IsInverted() const
+{
+    return GetFilter() ? GetFilter()->IsInverted() : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup filters.
+// Avoid trailing 0's!
+//
+// Example:
+//   test.C:
+//     MContinue cont("", "MyContinue");
+//
+//   test.rc:
+//     MyContinue.Condition: {0} && {1}
+//     MyContinue.Inverted: yes
+//     MyContinue.0: MHillas.fSize>1000
+//     MyContinue.1: MHillas.fSize<10000
+//   or (the syntax might change in the future!)
+//     MyContinue.Condition: <MMyClass>
+//     MMyClass.Variable1: ...
+//     MMyClass.Variable2: ...
+//
+// For more details see MF::ReadEnv
+//
+Int_t MContinue::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    MFilter *f = 0;
+    if (IsEnvDefined(env, prefix, "Condition", print))
+    {
+        TString txt = GetEnvValue(env, prefix, "Condition", "");
+        txt = txt.Strip(TString::kBoth);
+        if (txt.BeginsWith("<") && txt.EndsWith(">"))
+        {
+            const TString name = txt(1, txt.Length()-2);
+            f = (MFilter*)GetNewObject(name, MFilter::Class());
+            if (!f)
+                return kERROR;
+        }
+    }
+
+    if (!f)
+        f = new MF;
+    f->SetName(fName);
+
+    const Bool_t rc = f->ReadEnv(env, prefix, print);
+    if (rc!=kTRUE)
+    {
+        delete f;
+        return rc;
+    }
+
+    if (TestBit(kIsOwner))
+        delete GetFilter();
+
+    SetBit(kIsOwner);
+    MTask::SetFilter(f);
+
+    f->SetName(Form("MF:%s", fName.Data()));
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mbase/MContinue.h
===================================================================
--- /tags/Mars-V0.9/mbase/MContinue.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MContinue.h	(revision 9772)
@@ -0,0 +1,56 @@
+#ifndef MARS_MContinue
+#define MARS_MContinue
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MContinue                                                               //
+//                                                                         //
+// Does nothing than return kCONTINUE in the Process-fucntion              //
+// (use with filters)                                                      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MLog;
+class MFilter;
+class MTaskList;
+class MStatusDisplay;
+
+class MContinue : public MTask
+{
+private:
+    MTaskList *fTaskList;  //! pointer to the present tasklist
+
+    // MTask
+    Int_t PreProcess(MParList *list);
+    Int_t Process() { return kCONTINUE; }
+    Int_t PostProcess();
+
+    // MContinue
+    enum { kIsOwner = BIT(14), kFilterIsPrivate = BIT(15), kAllowEmpty = BIT(16) };
+
+public:
+    MContinue(const TString rule="", const char *name=NULL, const char *title=NULL);
+    MContinue(MFilter *f, const char *name=NULL, const char *title=NULL);
+    ~MContinue();
+
+    // MContinue
+    void SetAllowEmpty(Bool_t b=kTRUE) { b ? SetBit(kAllowEmpty) : ResetBit(kAllowEmpty); }
+    Bool_t IsAllowEmpty() const { return TestBit(kAllowEmpty); }
+
+
+    void SetInverted(Bool_t i=kTRUE);
+    Bool_t IsInverted() const;
+
+    // MParContainer
+    void SetDisplay(MStatusDisplay *d);
+    void SetLogStream(MLog *lg);
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MContinue, 1) //Task returning kCONTINUE
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MDirIter.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MDirIter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MDirIter.cc	(revision 9772)
@@ -0,0 +1,419 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MDirIter
+//
+// Iterator for files in several directories (with filters)
+//
+// Use this class if you want to get all filenames in a directory
+// one-by-one.
+//
+// You can specify more than one directory (also recursivly) and you
+// can use filters (eg. *.root)
+//
+// Here is an example which will print all *.root files in the current
+// directory and all its subdirectories and all Gamma*.root files in
+// the directory ../data.
+//
+// ------------------------------------------------------------------------
+//
+//  // Instatiate the iterator
+//  MDirIter Next();
+//
+//  // Add the current directory (for *.root files) and recursive
+//  // directories with the same filter
+//  Next.AddDirectory(".", "*.root", kTRUE);
+//  // Add the directory ../data, too (filter only Gamma*.root files)
+//  Next.AddDirectory("../data", "Gamma*.root");
+//
+//  TString name;
+//  while (!(name=Next()).IsNull())
+//     cout << name << endl;
+//
+// ------------------------------------------------------------------------
+//
+// WARNING: If you specify relative directories (like in the example) the
+//          result may depend on the current working directory! Better use
+//          absolute paths.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDirIter.h"
+
+#include <iostream>
+
+#include <TNamed.h>
+#include <TRegexp.h>
+#include <TSystem.h>
+
+ClassImp(MDirIter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Add a directory, eg dir="../data"
+//  Using a filter (wildcards) will only return files matching this filter.
+//  recursive is the number of recursive directories (use 0 for none and -1
+//  for all)
+//  Returns the number of directories added.
+//  If a directory is added using a filter and the directory is already
+//  existing without a filter the filter is replaced.
+//  If any directory to be added is already existing with a different
+//  filter a new entry is created, eg:
+//   already existing:  ../data <*.root>
+//   new entry:         ../data <G*>
+//  The filters are or'ed.
+//
+Int_t MDirIter::AddDirectory(const char *d, const char *filter, Int_t recursive)
+{
+    TString dir(d);
+
+    // Sanity check
+    if (dir.IsNull())
+        return 0;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
+    if (dir[dir.Length()-1]!='/')
+        dir += '/';
+#else
+    if (!dir.EndsWith("/"))
+        dir += '/';
+#endif
+    gSystem->ExpandPathName(dir);
+
+    // Try to find dir in the list of existing dirs
+    TObject *o = fList.FindObject(dir);
+    if (o)
+    {
+        const TString t(o->GetTitle());
+
+        // Check whether the existing dir has an associated filter
+        if (t.IsNull())
+        {
+            // Replace old filter by new one
+            ((TNamed*)o)->SetTitle(filter);
+            return 0;
+        }
+
+        // If the filters are the same no action is taken
+        if (t==filter)
+            return 0;
+    }
+
+    fList.Add(new TNamed((const char*)dir, filter ? filter : ""));
+
+    // No recuresive directories, return
+    if (recursive==0)
+        return 1;
+
+    Int_t rc = 1;
+
+    // Create an iterator to iterate over all entries in the directory
+    MDirIter Next(dir);
+
+    TString c;
+    while (!(c=Next(kTRUE)).IsNull())
+    {
+        // Do not process . and .. entries
+        if (c.EndsWith("/.") || c.EndsWith("/.."))
+            continue;
+
+        // If entry is a directory add it with a lower recursivity
+        if (IsDir(c)==0)
+            rc += AddDirectory(c, filter, recursive-1);
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds all entries from iter to this object
+//
+void MDirIter::Add(const MDirIter &iter)
+{
+    TIter Next(&iter.fList);
+    TObject *o=0;
+    while ((o=Next()))
+        fList.Add(o->Clone());
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the pointer to the current directory. If the pointer is NULL
+//  a new directory is opened. If no new directory can be opened NULL is
+//  returned.
+//
+void *MDirIter::Open()
+{
+    // Check whether a directory is already open
+    if (fDirPtr)
+        return fDirPtr;
+
+    // Get Next entry of list
+    fCurrentPath=fNext();
+
+    // Open directory if new entry was found
+    return fCurrentPath ? gSystem->OpenDirectory(fCurrentPath->GetName()) : NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Close directory is opened. Set fDirPtr=NULL
+//
+void MDirIter::Close()
+{
+    if (fDirPtr)
+        gSystem->FreeDirectory(fDirPtr);
+    fDirPtr = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Returns the concatenation of 'dir' and 'name'
+//
+TString MDirIter::ConcatFileName(const char *dir, const char *name) const
+{
+    return TString(dir)+name;
+}
+
+// --------------------------------------------------------------------------
+//
+// As the filter string may contain a + character, we have to replace
+// this filter by a new filter contaning a \+ at all locations where a +
+// was in the original filter.
+//
+// We replace:
+//   .  by  \\.
+//   +  by  \\+
+//   *  by  [^\\/:]*
+//   ?  by  .
+//
+// And surround the filter by ^ and $.
+//
+// For more details you can have a look at the template:
+//  TRegexp::MakeWildcard
+//
+const TRegexp MDirIter::MakeRegexp(TString n) const
+{
+    n.Prepend("^");
+    n.ReplaceAll(".", "\\.");
+    n.ReplaceAll("+", "\\+");
+    n.ReplaceAll("*", "[^\\/:]*");
+    n.ReplaceAll("?", ".");
+    n.Append("$");
+
+    return TRegexp(n, kFALSE);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the given name n matches the filter f.
+// Filters are of the form TRegexp(f, kTRUE)
+//
+Bool_t MDirIter::MatchFilter(const TString &n, const TString &f) const
+{
+
+    return f.IsNull() || !n(MakeRegexp(f)).IsNull();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether fqp is a directory.
+// Returns -1 if fqp couldn't be accesed, 0 if it is a directory,
+// 1 otherwise
+//
+Int_t MDirIter::IsDir(const char *fqp) const
+{
+    Long_t t[4];
+    if (gSystem->GetPathInfo(fqp, t, t+1, t+2, t+3))
+        return -1;
+
+    if (t[2]==3)
+        return 0;
+
+    return 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the current entry in the directory n is valid or not.
+// Entries must:
+//  - not be . or ..
+//  - match the associated filter
+//  - match the global filter
+//  - not be a directory
+//  - have read permission
+//
+Bool_t MDirIter::CheckEntry(const TString n) const
+{
+    // Check . and ..
+    if (n=="." || n=="..")
+        return kFALSE;
+
+    // Check associated filter
+    if (!MatchFilter(n, fCurrentPath->GetTitle()))
+        return kFALSE;
+
+    // Check global filter
+    if (!MatchFilter(n, fFilter))
+         return kFALSE;
+
+    // Check for file or directory
+    const TString fqp = ConcatFileName(fCurrentPath->GetName(), n);
+    if (IsDir(fqp)<=0)
+        return kFALSE;
+
+    // Check for rread perissions
+    return !gSystem->AccessPathName(fqp, kReadPermission);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset the iteration and strat from scratch. To do this correctly we have
+// to reset the list of directories to iterate _and_ to close the current
+// directory. When you call Next() the next time the first directory will
+// be reopened again and you'll get the first entry.
+//
+// Do not try to only close the current directory or to reset the directory
+// list only. This might not give the expected result!
+//
+void  MDirIter::Reset()
+{
+    Close();
+    fNext.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Next file in the directory which is valid (see Check())
+// nocheck==1 returns the next entry unchecked
+//
+TString MDirIter::Next(Bool_t nocheck)
+{
+    fDirPtr = Open();
+    if (!fDirPtr)
+        return "";
+
+    // Get next entry in dir, if existing check validity
+    const char *n = gSystem->GetDirEntry(fDirPtr);
+    if (n)
+        return nocheck || CheckEntry(n) ? ConcatFileName(fCurrentPath->GetName(), n) : Next();
+
+    // Otherwise close directory and try to get next entry
+    Close();
+    return Next();
+}
+
+// --------------------------------------------------------------------------
+//
+// Print a single entry in the list
+//
+void MDirIter::PrintEntry(const TObject &o) const
+{
+    TString p = o.GetName();
+    TString f = o.GetTitle();
+    cout << p;
+    if (!f.IsNull())
+        cout << " <" << f << ">";
+    cout << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print all scheduled directories. If "all" is specified also all
+// matching entries are printed.
+//
+void MDirIter::Print(const Option_t *o) const
+{
+    TString s(o);
+    if (s.Contains("dbg", TString::kIgnoreCase))
+        fList.Print();
+
+    if (!s.Contains("all", TString::kIgnoreCase))
+    {
+        TIter Next(&fList);
+        TObject *o=NULL;
+        while ((o=Next()))
+            PrintEntry(*o);
+        return;
+    }
+
+    MDirIter Next(*this);
+    TString name;
+    TString d;
+    while (!(name=Next()).IsNull())
+    {
+        const TString p = Next.fCurrentPath->GetName();
+        if (p!=d)
+        {
+            d=p;
+            PrintEntry(*Next.fCurrentPath);
+        }
+        cout << " " << name << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over all contents (files). Sort the files alphabetically.
+// Delete the contents of this DirIter and add all sorted files
+// to this DirIter.
+//
+void MDirIter::Sort()
+{
+    MDirIter Next(*this);
+
+    TList l;
+    l.SetOwner();
+
+    TString name;
+    while (!(name=Next()).IsNull())
+        l.Add(new TNamed(name.Data(), ""));
+
+    l.Sort();
+
+    fList.Delete();
+    Close();
+    fFilter = "";
+
+    TIter NextN(&l);
+    TObject *o=0;
+    while ((o=NextN()))
+    {
+        TString dir  = o->GetName();
+        TString name = o->GetName();
+
+        const Int_t last = dir.Last('/');
+        if (last<0)
+            continue;
+
+        dir.Remove(last);
+        name.Remove(0, last+1);
+
+        AddDirectory(dir, name);
+    }
+}
Index: /tags/Mars-V0.9/mbase/MDirIter.h
===================================================================
--- /tags/Mars-V0.9/mbase/MDirIter.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MDirIter.h	(revision 9772)
@@ -0,0 +1,74 @@
+#ifndef MARS_MDirIter
+#define MARS_MDirIter
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MDirIter : public TObject
+{
+private:
+    TObjArray fList;
+    TString   fFilter;
+
+    TIter     fNext;        //!
+    void     *fDirPtr;      //!
+    TObject  *fCurrentPath; //!
+
+    void   *Open();
+    void    Close();
+    Bool_t  CheckEntry(const TString n) const;
+    Int_t   IsDir(const char *dir) const;
+    Bool_t  MatchFilter(const TString &name, const TString &filter) const;
+    TString ConcatFileName(const char *dir, const char *name) const;
+    void    PrintEntry(const TObject &o) const;
+    const   TRegexp MakeRegexp(TString n) const;
+
+public:
+    MDirIter() : fNext(&fList), fDirPtr(NULL)
+    {
+        fList.SetOwner();
+    }
+    MDirIter(const MDirIter &dir) : fNext(&fList), fDirPtr(NULL)
+    {
+        fList.SetOwner();
+
+        TObject *o=NULL;
+        TIter Next(&dir.fList);
+        while ((o=Next()))
+            AddDirectory(o->GetName(), o->GetTitle());
+    }
+    MDirIter(const char *dir, const char *filter="", Int_t rec=0) : fNext(&fList), fDirPtr(NULL)
+    {
+        fList.SetOwner();
+        AddDirectory(dir, filter, rec);
+    }
+    ~MDirIter()
+    {
+        Close();
+    }
+
+    void Sort();
+
+    Int_t AddDirectory(const char *dir, const char *filter="", Int_t recursive=0);
+    void  Add(const MDirIter &iter);
+    void  Reset();
+
+    TString Next(Bool_t nocheck=kFALSE);
+    TString operator()(Bool_t nocheck=kFALSE) { return Next(nocheck); }
+
+    void SetFilter(const char *f="") { fFilter = f; }
+    UInt_t GetNumEntries() const
+    {
+        UInt_t n = 0;
+        MDirIter Next(*this);
+        while (!Next().IsNull()) n++;
+        return n;
+    }
+
+    void Print(const Option_t *o="") const;
+
+    ClassDef(MDirIter, 1) // Iterator for files in several directories (with filters)
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MEnv.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MEnv.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MEnv.cc	(revision 9772)
@@ -0,0 +1,83 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  2/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MEnv
+//
+// It is a slightly changed version of TEnv. It logs all resources which are
+// touched, so that you can print all untouched resources by
+// PrintUntouched()
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MEnv.h"
+
+#include <TObjString.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEnv);
+
+using namespace std;
+
+Int_t MEnv::GetValue(const char *name, Int_t dflt)
+{
+    if (!fChecked.FindObject(name))
+        fChecked.Add(new TObjString(name));
+    return TEnv::GetValue(name, dflt);
+}
+
+Double_t MEnv::GetValue(const char *name, Double_t dflt)
+{
+    if (!fChecked.FindObject(name))
+        fChecked.Add(new TObjString(name));
+    return TEnv::GetValue(name, dflt);
+}
+
+const char *MEnv::GetValue(const char *name, const char *dflt)
+{
+    if (!fChecked.FindObject(name))
+        fChecked.Add(new TObjString(name));
+    return TEnv::GetValue(name, dflt);
+}
+
+void MEnv::PrintUntouched() const
+{
+    int i=0;
+    gLog << inf << flush;
+    gLog.Separator("Untouched Resources");
+    TIter Next(GetTable());
+    TObject *o=0;
+    while ((o=Next()))
+        if (!fChecked.FindObject(o->GetName()))
+        {
+            gLog << warn << " - Resource " << o->GetName() << " not touched" << endl;
+            i++;
+        }
+    if (i==0)
+        gLog << inf << "None." << endl;
+    else
+        gLog << inf << i << " resources have not been touched." << endl;
+}
Index: /tags/Mars-V0.9/mbase/MEnv.h
===================================================================
--- /tags/Mars-V0.9/mbase/MEnv.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MEnv.h	(revision 9772)
@@ -0,0 +1,30 @@
+#ifndef MARS_MEnv
+#define MARS_MEnv
+
+#ifndef ROOT_TEnv
+#include <TEnv.h>
+#endif
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+class MEnv : public TEnv
+{
+private:
+    TOrdCollection fChecked;
+
+public:
+    MEnv(const char *name="") : TEnv(name) { fChecked.SetOwner(); }
+
+    Int_t       GetValue(const char *name, Int_t dflt);
+    Double_t    GetValue(const char *name, Double_t dflt);
+    const char *GetValue(const char *name, const char *dflt);
+
+    void PrintUntouched() const;
+
+    ClassDef(MEnv, 0) // A slightly more advanced version of TEnv
+};
+    
+#endif
+
Index: /tags/Mars-V0.9/mbase/MEvtLoop.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MEvtLoop.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MEvtLoop.cc	(revision 9772)
@@ -0,0 +1,1079 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MEvtLoop
+//
+// This class is the core of each event processing.
+// First you must set the parameter list to use. The parameter list
+// must contain the task list (MTaskList) to use. The name of the task
+// list can be specified if you call Eventloop. The standard name is
+// "MTaskList". The name you specify must match the name of the MTaskList
+// object.
+//
+// If you call Eventloop() first all PreProcess functions - with the
+// parameter list as an argument - of the tasks in the task list are
+// executed. If one of them returns kFALSE then the execution is stopped.
+// If the preprocessing was ok, The Process function of the tasks are
+// executed as long as one function returns kSTOP. Only the tasks which
+// are marked as "All" or with a string which matches the MInputStreamID
+// of MTaskList are executed. If one tasks returns kCONTINUE the pending
+// tasks in the list are skipped and the execution in continued with
+// the first one in the list.
+// Afterwards the PostProcess functions are executed.
+//
+// If you want to display the progress in a gui you can use SetProgressBar
+// and a TGProgressBar or a MProgressBar. If you set a MStatusDisplay
+// using SetDisplay, the Progress bar from this display is used.
+//
+// You can create a macro from a completely setup eventloop by:
+//   evtloop.MakeMacro("mymacro.C");
+//
+// You will always need to check the macro, it will not run, but it
+// should have al important information.
+//
+//
+// You can also write all this information to a root file:
+//   TFile file("myfile.root");
+//   evtloop.Write("MyEvtloopKey");
+//
+// You can afterwards read the information from an open file by:
+//   evtloop.Read("MyEvtloopKey");
+//
+// To lookup the information write it to a file using MakeMacro
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MEvtLoop.h"
+
+#include <time.h>           // time_t
+#include <fstream>          // ofstream, SavePrimitive
+
+#include <TEnv.h>           // TEnv
+#include <TRint.h>          // gApplication, TRint::Class()
+#include <TTime.h>          // TTime
+#include <TFile.h>          // gFile
+#include <TThread.h>        // TThread::Self()
+#include <TDatime.h>        // TDatime
+#include <TSystem.h>        // gSystem
+#include <TStopwatch.h>
+#include <TGProgressBar.h>  
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#ifdef __MARS__
+#include "MRead.h"           // for setting progress bar
+#include "MProgressBar.h"    // MProgressBar::GetBar
+#include "MStatusDisplay.h"  // MStatusDisplay::GetBar
+#endif
+
+ClassImp(MEvtLoop);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// default constructor
+//
+MEvtLoop::MEvtLoop(const char *name) : fParList(NULL), fProgress(NULL)
+{
+    fName = name;
+
+    gROOT->GetListOfCleanups()->Add(this); // To remove fDisplay
+    SetBit(kMustCleanup);
+
+    *fLog << inf << underline << "Instantiated MEvtLoop (" << name << "), using ROOT v" << ROOTVER << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// destructor
+//
+MEvtLoop::~MEvtLoop()
+{
+    if (TestBit(kIsOwner) && fParList)
+        delete fParList;
+}
+
+void MEvtLoop::SetParList(MParList *p)
+{
+    if (!p)
+        return;
+
+    p->SetBit(kMustCleanup);
+    fParList = p;
+}
+
+// --------------------------------------------------------------------------
+//
+// If the evntloop knows its tasklist search for the task there,
+// otherwise return NULL.
+//
+MTask *MEvtLoop::FindTask(const char *name) const
+{
+    return fTaskList ? fTaskList->FindTask(name) : NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// If the evntloop knows its tasklist search for the task there,
+// otherwise return NULL.
+//
+MTask *MEvtLoop::FindTask(const MTask *obj) const
+{
+    return fTaskList ? fTaskList->FindTask(obj) : NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  if you set the Eventloop as owner the destructor of the given parameter
+//  list is calles by the destructor of MEvtLoop, otherwise not.
+//
+void MEvtLoop::SetOwner(Bool_t enable)
+{
+    enable ? SetBit(kIsOwner) : ResetBit(kIsOwner);
+}
+
+void MEvtLoop::SetProgressBar(TGProgressBar *bar)
+{
+    fProgress = bar;
+    if (fProgress)
+        fProgress->SetBit(kMustCleanup);
+}
+
+#ifdef __MARS__
+// --------------------------------------------------------------------------
+//
+//  Specify an existing MProgressBar object. It will display the progress
+//  graphically. This will make thing about 1-2% slower.
+//
+void MEvtLoop::SetProgressBar(MProgressBar *bar)
+{
+    SetProgressBar(bar->GetBar());
+}
+#endif
+
+void MEvtLoop::SetDisplay(MStatusDisplay *d)
+{
+    MParContainer::SetDisplay(d);
+    if (!d)
+        fProgress=NULL;
+    else
+    {
+        d->SetBit(kMustCleanup);
+
+        // Get pointer to update Progress bar
+        fProgress = fDisplay->GetBar();
+    }
+
+    if (fParList)
+        fParList->SetDisplay(d);
+}
+
+// --------------------------------------------------------------------------
+//
+// The proprocessing part of the eventloop. Be careful, this is
+// for developers or use in special jobs only!
+//
+Bool_t MEvtLoop::PreProcess(const char *tlist)
+{
+    fTaskList = NULL;
+
+    //
+    // check if the needed parameter list is set.
+    //
+    if (!fParList)
+    {
+        *fLog << err << dbginf << "Parlist not initialized." << endl;
+        return kFALSE;
+    }
+
+    //
+    //  check for the existance of the specified task list
+    //  the default name is "MTaskList"
+    //
+    fTaskList = (MTaskList*)fParList->FindObject(tlist, "MTaskList");
+    if (!fTaskList)
+    {
+        *fLog << err << dbginf << "Cannot find tasklist '" << tlist << "' in parameter list." << endl;
+        return kFALSE;
+    }
+
+    if (fLog != &gLog)
+        fParList->SetLogStream(fLog);
+
+#ifdef __MARS__
+    //
+    // Check whether display is still existing
+    //
+    if (fDisplay)
+    {
+        // Lock display to prevent user from deleting it
+        fDisplay->Lock();
+        // Don't display context menus
+        fDisplay->SetNoContextMenu();
+        // Set window and icon name
+        fDisplay->SetWindowName(TString("Status Display: ")+fName);
+        fDisplay->SetIconName(fName);
+        // Start automatic update
+        fDisplay->StartUpdate();
+        // Cascade display through childs
+        if (!TestBit(kPrivateDisplay))
+            fParList->SetDisplay(fDisplay);
+    }
+#endif
+
+    //
+    //  execute the preprocess of all tasks
+    //  connect the different tasks with the right containers in
+    //  the parameter list
+    //
+    if (!fTaskList->PreProcess(fParList))
+    {
+        *fLog << err << "Error detected while PreProcessing." << endl;
+        return kFALSE;
+    }
+
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+Bool_t MEvtLoop::ProcessGuiEvents(Int_t num)
+{
+    if (gROOT->IsBatch())
+        return kTRUE;
+
+    //
+    // Check status of display
+    //
+    Bool_t rc = kTRUE;
+
+    if (fDisplay)
+        switch (fDisplay->CheckStatus())
+        {
+        case MStatusDisplay::kLoopNone:
+            break;
+        case MStatusDisplay::kLoopStop:
+            rc = kFALSE;
+            fDisplay->ClearStatus();
+            break;
+        //
+        // If the display is not on the heap (means: not created
+        // with the new operator) the object is deleted somewhere
+        // else in the code. It is the responsibility of the
+        // application which instantiated the object to make
+        // sure that the correct action is taken. This can be
+        // done by calling MStatusDisplay::CheckStatus()
+        //
+        // Because we are synchronous we can safely delete it here!
+        //
+        // Close means: Close the display but leave analysis running
+        // Exit means: Close the display and stop analysis
+        //
+        case MStatusDisplay::kFileClose:
+        case MStatusDisplay::kFileExit:
+            rc = fDisplay->CheckStatus() == MStatusDisplay::kFileClose;
+
+            if (fDisplay->IsOnHeap())
+                delete fDisplay;
+
+            //
+            // This makes the display really disappear physically on
+            // the screen in case of MStatusDisplay::kFileClose
+            //
+            gSystem->ProcessEvents();
+
+            return rc;
+        default:
+            *fLog << warn << "MEvtloop: fDisplay->CheckStatus() has returned unknown status #" << fDisplay->CheckStatus() << "... cleared." << endl;
+            fDisplay->ClearStatus();
+            break;
+        }
+
+    //
+    // Check System time (don't loose too much time by updating the GUI)
+    //
+
+    // FIXME: Not thread safe (if you have more than one eventloop running)
+    static Int_t start = num;
+    static TTime t1 = gSystem->Now();
+    static TTime t2 = t1;
+
+    //
+    // No update < 20ms
+    //
+    const TTime t0 = gSystem->Now();
+    if (t0-t1 < (TTime)20)
+        return rc;
+    t1 = t0;
+
+    //
+    // Update current speed each 1.5 second
+    //
+    if (fDisplay && t0-t2>(TTime)1500)
+    {
+        const Float_t speed = 1000.*(num-start)/(long int)(t0-t2);
+        TString txt = "Processing...";
+        if (speed>0)
+        {
+            txt += " (";
+            txt += (Int_t)speed;
+            txt += "Evts/s";
+            if (fNumEvents>0)
+            {
+                txt += ", est: ";
+                txt += (int)((fNumEvents-num)/speed/60)+1;
+                txt += "min";
+            }
+            //txt += (int)fmod(entries/(1000.*(num-start)/(long int)(t0-t2)), 60);
+            //txt += "s";
+            txt += ")";
+        }
+        fDisplay->SetStatusLine1(txt);
+        start = num;
+        t2 = t0;
+    }
+
+    //
+    // Set new progress bar position
+    //
+    if (fProgress && fNumEvents>0)
+        fProgress->SetPosition((Double_t)num/fNumEvents);
+
+    // FIXME: This is a workaround, because TApplication::Run is not
+    //        thread safe against ProcessEvents. We assume, that if
+    //        we are not in the Main-Thread ProcessEvents() is
+    //        called by the TApplication Event Loop...
+    if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+    {
+        //
+        // Handle GUI events (display changes)
+        //
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,06)
+        gSystem->ProcessEvents();
+#else
+        if (fDisplay)
+            gSystem->ProcessEvents();
+        else
+            if (fProgress)
+                gClient->ProcessEventsFor(fProgress);
+#endif
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// The processing part of the eventloop. Be careful, this is
+// for developers or use in special jobs only!
+//
+Int_t MEvtLoop::Process(UInt_t maxcnt)
+{
+    if (!fTaskList)
+        return kFALSE;
+
+    //
+    //   loop over all events and process all tasks for
+    //   each event
+    //
+    *fLog << all <<"Eventloop running (";
+
+    if (maxcnt==0)
+        *fLog << "all";
+    else
+        *fLog << dec << maxcnt;
+
+    *fLog << " events)..." << flush;
+
+    UInt_t entries = kMaxUInt;
+    fNumEvents = 0;
+
+    if (fProgress && !gROOT->IsBatch())
+    {
+        fProgress->Reset();
+        fProgress->SetRange(0, 1);
+
+#ifdef __MARS__
+        MRead *read = (MRead*)fTaskList->FindObject("MRead");
+        if (read && read->GetEntries()>0)
+            entries = read->GetEntries();
+#endif
+
+        if (maxcnt>0)
+            fNumEvents = TMath::Min(maxcnt, entries);
+        else
+            if (entries!=kMaxUInt)
+                fNumEvents = entries;
+    }
+
+    if (fDisplay)
+    {
+        fDisplay->SetStatusLine1("Processing...");
+        fDisplay->SetStatusLine2("");
+    }
+
+    //
+    // start a stopwatch
+    //
+    TStopwatch clock;
+    clock.Start();
+
+    //
+    // This is the MAIN EVENTLOOP which processes the data
+    // if maxcnt==0 the number of processed events is counted
+    // else only maxcnt events are processed
+    //
+    UInt_t numcnts = 0;
+    UInt_t dummy   = maxcnt;
+
+    Int_t rc=kTRUE;
+    if (maxcnt==0)
+        // process first and increment if sucessfull
+        while (1)
+        {
+            rc=fTaskList->Process();
+            if (rc!=kTRUE && rc!=kCONTINUE)
+                break;
+
+            numcnts++;
+            if (!ProcessGuiEvents(++dummy))
+                break;
+        }
+    else
+        // check for number and break if unsuccessfull
+        while (dummy--)
+        {
+            rc=fTaskList->Process();
+            if (rc!=kTRUE && rc!=kCONTINUE)
+                break;
+
+            numcnts++;
+            if (!ProcessGuiEvents(maxcnt - dummy))
+                break;
+        }
+
+    //
+    // stop stop-watch, print results
+    //
+    clock.Stop();
+
+    if (fProgress && !gROOT->IsBatch())
+    {
+        //fProgress->SetPosition(maxcnt>0 ? TMath::Min(maxcnt, entries) : entries);
+        fProgress->SetPosition(1);
+
+        // FIXME: This is a workaround, because TApplication::Run is not
+        //        thread safe against ProcessEvents. We assume, that if
+        //        we are not in the Main-Thread ProcessEvents() is
+        //        called by the TApplication Event Loop...
+        if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+        {
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,06)
+            gSystem->ProcessEvents();
+#else
+            gClient->ProcessEventsFor(fDisplay ? fDisplay->GetBar() : fProgress);
+#endif
+        }
+    }
+
+    *fLog << all << "Ready!" << endl << endl;
+
+    *fLog << dec << endl << "CPU  - Time: ";
+    *fLog << clock.CpuTime() << "s" << " for " << numcnts << " Events";
+    if (numcnts>0)
+        *fLog << " --> " << numcnts/clock.CpuTime() << " Events/s";
+    *fLog << endl << "Real - Time: ";
+    *fLog << clock.RealTime() << "s" << " for " << numcnts << " Events";
+    if (numcnts>0)
+        *fLog << " --> " << numcnts/clock.RealTime() << " Events/s";
+
+    *fLog << endl << endl;
+
+    return rc!=kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+//  The postprocessing part of the eventloop. Be careful, this is
+// for developers or use in special jobs only!
+//
+Bool_t MEvtLoop::PostProcess() const
+{
+    //
+    //  execute the post process of all tasks
+    //
+    return fTaskList ? fTaskList->PostProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// See class description above. Returns kTRUE if PreProcessing,
+// Processing and PostProcessing was successfull.
+// kFALSE is retuned if something was not successfull, eg:
+//   PreProcess or PostProcess returned kFALSE
+//   process returned kERRR
+//
+// maxcnt==0 means: all events
+// tlist is the name of the task-list to be used. Be carefull, this
+// feature is not finally implemented - it will only work if no
+// task will access the tasklist.
+//
+Bool_t MEvtLoop::Eventloop(UInt_t maxcnt, const char *tlist)
+{
+    TDatime d;
+    *fLog << inf << underline << "Eventloop: " << fName << " started at " << d.AsString() << endl;
+
+    Bool_t rc = PreProcess(tlist);
+
+    //
+    // If all Tasks were PreProcesses successfully start Processing.
+    //
+    if (rc)
+        rc = Process(maxcnt);
+
+    //
+    // Now postprocess all tasks. Only successfully preprocessed tasks
+    // are postprocessed. If the Postprocessing of one task fails
+    // return an error.
+    //
+    if (!PostProcess())
+    {
+        *fLog << err << "Error detected while PostProcessing." << endl;
+        rc = kFALSE;
+    }
+
+    if (!fDisplay)
+        return rc;
+
+    // Set status lines
+    fDisplay->SetStatusLine1(fName);
+    fDisplay->SetStatusLine2(rc ? "Done." : "Error!");
+    // Stop automatic update
+    fDisplay->StopUpdate();
+    // Reallow context menus
+    fDisplay->SetNoContextMenu(kFALSE);
+    // Reallow user to exit window by File menu
+    fDisplay->UnLock();
+
+    //
+    // If postprocessing of all preprocessed tasks was sucefully return rc.
+    // This gives an error in case the preprocessing has failed already.
+    // Otherwise the eventloop is considered: successfully.
+    //
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  After you setup (or read) an Evtloop you can use MakeMacro() to write
+//  the eventloop setup as a macro. The default name is "evtloop.C". The
+//  default extension is .C If the extension is not given, .C is added.
+//  If the last character in the argument is a '+' the file is not closed.
+//  This is usefull if you have an eventloop which runs three times and
+//  you want to write one macro. If the first character is a '+' no
+//  opening is written, eg:
+//
+//     MEvtLoop evtloop;
+//     // some setup
+//     evtloop.MakeMacro("mymacro+");
+//     // replace the tasklist the first time
+//     evtloop.MakeMacro("+mymacro+");
+//     // replace the tasklist the second time
+//     evtloop.MakeMacro("+mymacro");
+//
+void MEvtLoop::MakeMacro(const char *filename)
+{
+    TString name(filename);
+
+    name = name.Strip(TString::kBoth);
+
+    Bool_t open  = kTRUE;
+    Bool_t close = kTRUE;
+    if (name[0]=='+')
+    {
+        open = kFALSE;
+        name.Remove(0, 1);
+        name = name.Strip(TString::kBoth);
+    }
+
+    if (name[name.Length()-1]=='+')
+    {
+        close = kFALSE;
+        name.Remove(name.Length()-1, 1);
+        name = name.Strip(TString::kBoth);
+    }
+
+    if (!name.EndsWith(".C"))
+        name += ".C";
+
+    ofstream fout;
+
+    if (!open)
+    {
+        fout.open(name, ios::app);
+        fout << endl;
+        fout << "   // ----------------------------------------------------------------------" << endl;
+        fout << endl;
+    }
+    else
+    {
+        fout.open(name);
+
+        time_t t = time(NULL);
+        fout <<
+            "/* ======================================================================== *\\" << endl <<
+            "!" << endl <<
+            "! *" << endl <<
+            "! * This file is part of MARS, the MAGIC Analysis and Reconstruction" << endl <<
+            "! * Software. It is distributed to you in the hope that it can be a useful" << endl <<
+            "! * and timesaving tool in analysing Data of imaging Cerenkov telescopes." << endl <<
+            "! * It is distributed WITHOUT ANY WARRANTY." << endl <<
+            "! *" << endl <<
+            "! * Permission to use, copy, modify and distribute this software and its" << endl <<
+            "! * documentation for any purpose is hereby granted without fee," << endl <<
+            "! * provided that the above copyright notice appear in all copies and" << endl <<
+            "! * that both that copyright notice and this permission notice appear" << endl <<
+            "! * in supporting documentation. It is provided \"as is\" without express" << endl <<
+            "! * or implied warranty." << endl <<
+            "! *" << endl <<
+            "!" << endl <<
+            "!" << endl <<
+            "!   Author(s): Thomas Bretz et al. <mailto:tbretz@astro.uni-wuerzburg.de>" << endl <<
+            "!" << endl <<
+            "!   Copyright: MAGIC Software Development, 2000-2005" << endl <<
+            "!" << endl <<
+            "!" << endl <<
+            "\\* ======================================================================== */" << endl << endl <<
+            "// ------------------------------------------------------------------------" << endl <<
+            "//" << endl <<
+            "//     This macro was automatically created on" << endl<<
+            "//             " << ctime(&t) <<
+            "//        with the MEvtLoop::MakeMacro tool." << endl <<
+            "//" << endl <<
+            "// ------------------------------------------------------------------------" << endl << endl <<
+            "void " << name(0, name.Length()-2) << "()" << endl <<
+            "{" << endl;
+    }
+
+    SavePrimitive(fout, (TString)"" + (open?"open":"") + (close?"close":""));
+
+    if (!close)
+        return;
+
+    fout << "}" << endl;
+
+    *fLog << inf << "Macro '" << name << "' written." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MEvtLoop::StreamPrimitive(ofstream &out) const
+{
+    out << "   MEvtLoop " << GetUniqueName();
+    if (fName!="Evtloop")
+        out << "(\"" << fName << "\")";
+    out << ";" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+void MEvtLoop::SavePrimitive(ofstream &out, Option_t *opt)
+{
+    TString options = opt;
+    options.ToLower();
+
+    if (HasDuplicateNames("MEvtLoop::SavePrimitive"))
+    {
+        out << "   // !" << endl;
+        out << "   // ! WARNING - Your eventloop (MParList, MTaskList, ...) contains more than" << endl;
+        out << "   // ! one object (MParContainer, MTask, ...) with the same name. The created macro" << endl;
+        out << "   // ! may need manual intervention before it can be used." << endl;
+        out << "   // !" << endl;
+        out << endl;
+    }
+
+    if (!options.Contains("open"))
+    {
+        if (gListOfPrimitives)
+        {
+            *fLog << err << "MEvtLoop::SavePrimitive - Error: old file not closed." << endl;
+            gListOfPrimitives->ForEach(TObject, ResetBit)(BIT(15));
+            delete gListOfPrimitives;
+        }
+        gListOfPrimitives = new TList;
+    }
+
+    if (fParList)
+        fParList->SavePrimitive(out);
+
+    MParContainer::SavePrimitive(out);
+
+    if (fParList)
+        out << "   " << GetUniqueName() << ".SetParList(&" << fParList->GetUniqueName() << ");" << endl;
+    else
+        out << "   // fParList empty..." << endl;
+    out << "   if (!" << GetUniqueName() << ".Eventloop())" << endl;
+    out << "      return;" << endl;
+
+    if (!options.Contains("close"))
+        return;
+
+    gListOfPrimitives->ForEach(TObject, ResetBit)(BIT(15));
+    delete gListOfPrimitives;
+    gListOfPrimitives = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get a list of all conmtainer names which are somehow part of the
+// eventloop. Chack for duplicate members and print a warning if
+// duplicates are found. Return kTRUE if duplicates are found, otherwise
+// kFALSE;
+//
+Bool_t MEvtLoop::HasDuplicateNames(TObjArray &arr, const TString txt) const
+{
+    arr.Sort();
+
+    TIter Next(&arr);
+    TObject *obj;
+    TString name;
+    Bool_t found = kFALSE;
+    while ((obj=Next()))
+    {
+        if (name==obj->GetName())
+        {
+            if (!found)
+            {
+                *fLog << warn << endl;
+                *fLog << " ! WARNING (" << txt << ")" << endl;
+                *fLog << " ! Your eventloop (MParList, MTaskList, ...) contains more than" << endl;
+                *fLog << " ! one object (MParContainer, MTask, ...) with the same name." << endl;
+                *fLog << " ! Creating a macro from it using MEvtLoop::MakeMacro may create" << endl;
+                *fLog << " ! a macro which needs manual intervention before it can be used." << endl;
+                found = kTRUE;
+            }
+            *fLog << " ! Please rename: " << obj->GetName() << endl;
+        }
+        name = obj->GetName();
+    }
+
+    return found;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get a list of all conmtainer names which are somehow part of the
+// eventloop. Chack for duplicate members and print a warning if
+// duplicates are found. Return kTRUE if duplicates are found, otherwise
+// kFALSE;
+//
+Bool_t MEvtLoop::HasDuplicateNames(const TString txt) const
+{
+    if (!fParList)
+        return kFALSE;
+
+    TObjArray list;
+    list.SetOwner();
+
+    fParList->GetNames(list);
+
+    return HasDuplicateNames(list, txt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Reads a saved eventloop from a file. The default name is "Evtloop".
+// Therefor an open file must exist (See TFile for more information)
+//
+//  eg:
+//        TFile file("myfile.root", "READ");
+//        MEvtLoop evtloop;
+//        evtloop.Read();
+//        evtloop.MakeMacro("mymacro");
+//
+Int_t MEvtLoop::Read(const char *name)
+{
+    if (!gFile)
+    {
+        *fLog << err << "MEvtloop::Read: No file found. Please create a TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsOpen())
+    {
+        *fLog << err << "MEvtloop::Read: File not open. Please open the TFile first." << endl;
+        return 0;
+    }
+
+    Int_t n = 0;
+    TObjArray list;
+
+    n += TObject::Read(name);
+
+    if (n==0)
+    {
+        *fLog << err << "MEvtloop::Read: No objects read." << endl;
+        return 0;
+    }
+
+    n += list.Read((TString)name+"_names");
+
+    fParList->SetNames(list);
+
+    HasDuplicateNames(list, "MEvtLoop::Read");
+
+    *fLog << inf << "Eventloop '" << name << "' read from file." << endl;
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// If available print the contents of the parameter list.
+//
+void MEvtLoop::Print(Option_t *opt) const
+{
+    if (fParList)
+        fParList->Print();
+    else
+        *fLog << all << "MEvtloop: No Parameter List available." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Writes a eventloop to a file. The default name is "Evtloop".
+// Therefor an open file must exist (See TFile for more information)
+//
+//  eg:
+//        TFile file("myfile.root", "RECREATE");
+//        MEvtLoop evtloop;
+//        evtloop.Write();
+//        file.Close();
+//
+Int_t MEvtLoop::Write(const char *name, Int_t option, Int_t bufsize) const
+{
+    if (!gFile)
+    {
+        *fLog << err << "MEvtloop::Write: No file found. Please create a TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsOpen())
+    {
+        *fLog << err << "MEvtloop::Write: File not open. Please open the TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsWritable())
+    {
+        *fLog << err << "MEvtloop::Write: File not writable." << endl;
+        return 0;
+    }
+
+    Int_t n = 0;
+
+    TObjArray list;
+    list.SetOwner();
+
+    fParList->GetNames(list);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,02,00)
+    n += const_cast<MEvtLoop*>(this)->TObject::Write(name, option, bufsize);
+#else
+    n += TObject::Write(name, option, bufsize);
+#endif
+
+    if (n==0)
+    {
+        *fLog << err << "MEvtloop::Read: No objects written." << endl;
+        return 0;
+    }
+
+    n += list.Write((TString)name+"_names", kSingleKey);
+
+    HasDuplicateNames(list, "MEvtLoop::Write");
+
+    *fLog << inf << "Eventloop written to file as " << name << "." << endl;
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the contents/setup of a parameter container/task from a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+//
+// With the argument prefix you can overwrite the name of the MEvtLoop object
+// as prefix - use with extreme care! The prifix argument must not end with
+// a dot!
+//
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Int_t MEvtLoop::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+//    if (!prefix.IsNull())
+//        *fLog << warn << "WARNING - Second argument in MEvtLoop::ReadEnv has no meaning... ignored." << endl;
+
+    if (prefix.IsNull())
+        prefix = fName;
+    prefix += ".";
+
+    *fLog << inf << "Reading resources for " << prefix /*TEnv::fRcName << " from " << env.GetRcName()*/ << endl;
+
+    fLog->ReadEnv(env, prefix, print);
+
+    if (!fParList)
+    {
+        *fLog << warn << "WARNING - No parameter list to propagate resources to." << endl;
+        return kTRUE;
+    }
+
+    if (fParList->ReadEnv(env, prefix, print)==kERROR)
+    {
+        *fLog << err << "ERROR - Reading Environment file." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls 'ReadEnv' with a TEnv initialized with the given file name.
+// If 'config=0' kTRUE is returned.
+//
+Bool_t MEvtLoop::ReadEnv(const char *config, Bool_t print)
+{
+    if (!config)
+        return kTRUE;
+
+    const Bool_t fileexist = !gSystem->AccessPathName(config, kFileExists);
+    if (!fileexist)
+    {
+        *fLog << warn << "WARNING - resource file '" << config << "' not found... no resources applied." << endl;
+        return kFALSE;
+    }
+
+    return ReadEnv(TEnv(config), "", print);
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the contents/setup of a parameter container/task to a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_t MEvtLoop::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    if (!prefix.IsNull())
+        *fLog << warn << "WARNING - Second argument in MEvtLoop::WriteEnv has no meaning... ignored." << endl;
+
+    prefix = fName;
+    prefix += ".";
+
+    *fLog << inf << "Writing resources: " << prefix /*TEnv::fRcName << " to " << env.GetRcName()*/ << endl;
+
+    fLog->WriteEnv(env, prefix, print);
+
+    if (!fParList)
+    {
+        *fLog << warn << "WARNING - No parameter list to get resources from." << endl;
+        return kTRUE;
+    }
+
+
+    if (fParList->WriteEnv(env, prefix, print)!=kTRUE)
+    {
+        *fLog << err << "ERROR - Writing Environment file." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+void MEvtLoop::RecursiveRemove(TObject *obj)
+{
+    if (obj==fParList)
+    {
+        fParList=NULL;
+        fTaskList=NULL;
+    }
+
+    if (obj==fProgress)
+        fProgress = NULL;
+
+    if (obj==fDisplay)
+        SetDisplay(NULL);
+
+    if (obj==fLog)
+    {
+        if (fParList)
+            fParList->SetLogStream(NULL);
+        SetLogStream(NULL);
+    }
+}
Index: /tags/Mars-V0.9/mbase/MEvtLoop.h
===================================================================
--- /tags/Mars-V0.9/mbase/MEvtLoop.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MEvtLoop.h	(revision 9772)
@@ -0,0 +1,94 @@
+#ifndef MARS_MEvtLoop
+#define MARS_MEvtLoop
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MEvtLoop                                                                //
+//                                                                         //
+// Class to execute the tasks in a tasklist                                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MTask;
+class MParList;
+class MTaskList;
+class TGProgressBar;
+#ifdef __MARS__
+class MProgressBar;
+#endif
+
+class MEvtLoop : public MParContainer
+{
+private:
+    MParList  *fParList;
+    MTaskList *fTaskList;      //!
+
+    TGProgressBar *fProgress;  //!
+
+    ULong_t fNumEvents;        //!
+
+    enum { kIsOwner = BIT(14), kPrivateDisplay = BIT(15) };
+
+    Bool_t HasDuplicateNames(const TString txt) const;
+    Bool_t HasDuplicateNames(TObjArray &arr, const TString txt) const;
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Bool_t ProcessGuiEvents(Int_t num);
+
+public:
+    MEvtLoop(const char *name="Evtloop");
+    virtual ~MEvtLoop();
+
+    void       SetParList(MParList *p);
+    MParList  *GetParList() const  { return fParList; }
+    MTaskList *GetTaskList() const { return fTaskList; }
+
+    MTask *FindTask(const char *name) const;
+    MTask *FindTask(const MTask *obj) const;
+
+    MStatusDisplay *GetDisplay() { return fDisplay; }
+    void SetDisplay(MStatusDisplay *d);
+    void SetPrivateDisplay(Bool_t b=kTRUE) { b ? SetBit(kPrivateDisplay) : ResetBit(kPrivateDisplay); } // Prevent status display from being cascaded in PreProcess
+
+    void SetOwner(Bool_t enable=kTRUE);
+
+    void SetProgressBar(TGProgressBar *bar);
+#ifdef __MARS__
+    void SetProgressBar(MProgressBar *bar);
+#endif
+
+    Bool_t PreProcess(const char *tlist="MTaskList");
+    Int_t  Process(UInt_t maxcnt);
+    Bool_t PostProcess() const;
+
+    Bool_t Eventloop(UInt_t maxcnt=0, const char *tlist="MTaskList");
+
+    void MakeMacro(const char *filename="evtloop.C");
+
+    void SavePrimitive(ofstream &out, Option_t *o="");
+
+    Int_t Read(const char *name="Evtloop");
+    Int_t Write(const char *name="Evtloop", Int_t option=0, Int_t bufsize=0) const;
+    Int_t Write(const char *name="Evtloop", Int_t option=0, Int_t bufsize=0)
+    {
+        return const_cast<MEvtLoop*>(this)->Write(name, option, bufsize);
+    }
+
+    void Print(Option_t *opt="") const;
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix="", Bool_t print=kFALSE);
+    Bool_t WriteEnv(TEnv &env, TString prefix="", Bool_t print=kFALSE) const;
+
+    Bool_t ReadEnv(const char *config, Bool_t print=kFALSE);
+
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MEvtLoop, 1) // Class to execute the tasks in a tasklist
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MFilter.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MFilter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MFilter.cc	(revision 9772)
@@ -0,0 +1,110 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFilter
+//
+//   This is a base class which defines an interface to create your own
+//   filters. To do it derive a class from MFilter.
+//
+//   You can invert the meaning of a filter (logical NOT '!') by calling
+//   SetInverted().
+//
+//   You can create two types of Filters:
+//    - static Filters and
+//    - dynamic Filters
+//
+//   Static Filters:
+//    A static filter is a filter which value doesn't change dynamically,
+//    which mean only once while running through your tasklist. To create
+//    a static filter override the Process-function of MFilter (this is
+//    the function in which the filer-value should be updated). If
+//    necessary you can also overwrite Pre-/PostProcess. The process
+//    function should calculate the return value of IsExpressionTrue.
+//    IsExpressionTrue should simply return this value. This kind of
+//    filter must be added to the tasklist at a point which is forseen to
+//    update the value of the filter (eg. after the reading task).
+//
+//   Dynamic Filters:
+//    A dynamic filter is a filter which returns a value which must be
+//    calculated at the time the filter is called. To create such a
+//    filter you have to overwrite IsExpressionTrue only. If there is
+//    no need for a 'one-point' update this filter must not be added to
+//    the tasklist.
+//
+//   Usage:
+//    A Filter is connected to a task by calling MTask::SetFilter. The
+//    task is now executed when IsExpressionTrue returns a value
+//    (different from kFALSE) only.
+//
+//   Remarks:
+//    - Make sure, that all tasks which depends on this filter are either
+//      collected in a MTaskList-object or are conected to the same
+//      filter.
+//    - If you want to use different filters (combined logically) for one
+//      task please look for the MFilterList class.
+//    - Be careful, the return value of IsExpressionTrue is NOT a real
+//      boolean. You can return other values, too.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFilter.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFilter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor for a filter. Initializes fInverted with kFALSE
+//
+MFilter::MFilter(const char *name, const char *title) : fInverted(kFALSE)
+{
+    fName  = name  ? name  : "MFilter";
+    fTitle = title ? title : "Base Class for a filter";
+}
+
+// --------------------------------------------------------------------------
+//
+//  return the Rule corresponding to this filter (see MF and MDataChain)
+//
+TString MFilter::GetRule() const
+{
+    return Form("(%s)", ClassName()); //"<GetRule n/a for " + fName + ">";
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is used to print the output in the PostProcess/Finalize.
+//  Or everywhere else in a nice fashioned and unified way.
+//
+void MFilter::PrintSkipped(UInt_t n, const char *str)
+{
+    *fLog << " " << setw(7) << n << " (";
+    *fLog << setw(3) << TMath::Nint(100.*n/GetNumExecutions());
+    *fLog << "%) Evts fullfilled: " << str << endl;
+}
Index: /tags/Mars-V0.9/mbase/MFilter.h
===================================================================
--- /tags/Mars-V0.9/mbase/MFilter.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MFilter.h	(revision 9772)
@@ -0,0 +1,33 @@
+#ifndef MARS_MFilter
+#define MARS_MFilter
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class MFilter : public MTask
+{
+private:
+    Bool_t fInverted;
+
+    virtual Bool_t IsExpressionTrue() const = 0;
+
+public:
+    MFilter(const char *name=NULL, const char *title=NULL);
+
+    virtual TString GetRule() const;
+    virtual TString GetDataMember() const { return ""; }
+
+    Bool_t IsConditionTrue() const { return fInverted ? !IsExpressionTrue() : IsExpressionTrue(); }
+
+    void SetInverted(Bool_t i=kTRUE) { fInverted=i; }
+    Bool_t IsInverted() const  { return fInverted; }
+
+    void PrintSkipped(UInt_t n, const char *str);
+
+    ClassDef(MFilter, 1)		// Abstract base class for the filters
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MGGroupFrame.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MGGroupFrame.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGGroupFrame.cc	(revision 9772)
@@ -0,0 +1,139 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  11/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MGGroupFrame                                                            //
+//                                                                         //
+// This is a group frame derived from TGGroupFrame with some               //
+// enhancements:                                                           //
+//  - It holds a list which deletes all it's members in ~MGGroupFrame      //
+//    (use AddToList to add an object.                                     //
+//  - You can access the members of the list by their widget id (if they   //
+//    have one)                                                            //
+//  - All messages from associated GUI elemets are redirectd to a given    //
+//    task.                                                                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MGGroupFrame.h"
+
+#include "MGList.h"
+#include "MGTask.h"
+
+ClassImp(MGGroupFrame);
+
+// --------------------------------------------------------------------------
+//
+//  For a detailed description check TGGroupFrame::TGGroupFrame.
+//  All messages from associated GUI elements are redirected to the given
+//  task.
+//  Creates a MGList object to store Widgets. Use AddToList to Add
+//  objects.
+//
+MGGroupFrame::MGGroupFrame(MGTask *task,
+                           const TGWindow *p, TGString *title,
+                           UInt_t options, GContext_t norm,
+                           FontStruct_t font, ULong_t back)
+    : TGGroupFrame(p, title, options, norm, font, back), TGWidget(-1)
+{
+    fWidgetFlags = 0;
+    fMsgWindow   = p;
+    fTask        = task;
+
+    fList = new MGList;
+}
+
+// --------------------------------------------------------------------------
+//
+//  For a detailed description check TGGroupFrame::TGGroupFrame.
+//  All messages from associated GUI elements are redirected to the given
+//  task.
+//  Creates a MGList object to store Widgets. Use AddToList to Add
+//  objects.
+//
+MGGroupFrame::MGGroupFrame(MGTask *task,
+                           const TGWindow *p, const char *title,
+                           UInt_t options, GContext_t norm,
+                           FontStruct_t font, ULong_t back)
+: TGGroupFrame(p, title, options, norm, font, back), TGWidget(-1)
+{
+    fWidgetFlags = 0;
+    fMsgWindow   = p;
+    fTask        = task;
+
+    fList = new MGList;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deleted the MGList object and all its members.
+//
+MGGroupFrame::~MGGroupFrame()
+{
+    fList->SetOwner();
+    delete fList;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add an object to the MGList. All the objects in MGList are deleted
+//  in the destructor MGGroupFrame automatically.
+//  You can add all object which have to exist until the Group Frame is
+//  destroyed (eg. TGLayoutElements)
+//  If an object is also derived from TGWidget you can get a pointer
+//  to it by its widget Id (use FindWidget)
+//
+void MGGroupFrame::AddToList(TObject *obj)
+{
+    fList->Add(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+//  To get an object which has a widget id (is derived from TGWidget) by
+//  its widget id use FindWidget with the widget id of the object you
+//  are searching for. If no object with this widget id exists NULL
+//  is returned. See also MGList::FindWidget(Int_t)
+//
+TObject *MGGroupFrame::FindWidget(Int_t id) const
+{
+    return fList->FindWidget(id);
+}
+
+// --------------------------------------------------------------------------
+//
+//  If you associate an object with this MGGroupFrame object, like in the
+//  following example:
+//
+//   MGGroupFrame *f = new MGGroupFrame(...);
+//   TGTextEntry *entry = new TGTextEntry(...);
+//   entry->Associate(f);
+//
+//  All messages send to the group frame by the GUI elent are redirected
+//  to the task corresponing to the MGGroupFrame.
+//
+Bool_t MGGroupFrame::ProcessMessage(Long_t msg, Long_t param1, Long_t param2)
+{
+    return fTask->ProcessMessage(GET_MSG(msg), GET_SUBMSG(msg), param1, param2);
+}
Index: /tags/Mars-V0.9/mbase/MGGroupFrame.h
===================================================================
--- /tags/Mars-V0.9/mbase/MGGroupFrame.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGGroupFrame.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MGGroupFrame
+#define MARS_MGGroupFrame
+
+#ifndef ROOT_TGFrame
+#include <TGFrame.h>
+#endif
+#ifndef ROOT_TGWidget
+#include <TGWidget.h>
+#endif
+
+class MGTask;
+class MGList;
+
+class MGGroupFrame : public TGGroupFrame, public TGWidget
+{
+    MGTask *fTask;
+    MGList *fList;
+
+public:
+    MGGroupFrame(MGTask *task,
+                 const TGWindow *p, TGString *title,
+                 UInt_t options = kVerticalFrame,
+                 GContext_t norm=GetDefaultGC()(),
+                 FontStruct_t font=GetDefaultFontStruct(),
+                 ULong_t back=GetDefaultFrameBackground());
+    MGGroupFrame(MGTask *task,
+                 const TGWindow *p, const char *title,
+                 UInt_t options = kVerticalFrame,
+                 GContext_t norm=GetDefaultGC()(),
+                 FontStruct_t font=GetDefaultFontStruct(),
+                 ULong_t back=GetDefaultFrameBackground());
+    virtual ~MGGroupFrame();
+
+    void     AddToList(TObject *obj);
+    TObject *FindWidget(Int_t id) const;
+
+    virtual Bool_t ProcessMessage(Long_t msg, Long_t param1, Long_t param2);
+
+    ClassDef(MGGroupFrame, 0) // An interface to widgets in a group frame (makes live easier)
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MGList.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MGList.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGList.cc	(revision 9772)
@@ -0,0 +1,306 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  11/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MGList                                                                 //
+//                                                                         //
+//  This is a TList object which has some enhancements for GUI elements.   //
+//  Use GetWidget to search for a GUI element with a given widget id.      //
+//  Add checkes for the existances of a GUI element with the same widget   //
+//  id (for IDs>=0).                                                       //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MGList.h"
+
+#include <iostream>
+
+#include <TROOT.h>
+#include <TClass.h>
+#include <TGClient.h>
+#include <TGWidget.h>
+#include <TGPicture.h>
+
+ClassImp(MGList);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Add the list to the global list of cleanups
+//  objects in the list.
+//
+MGList::MGList() : TList()
+{
+    // Make sure that all object deleted are also deleted from this list
+    gROOT->GetListOfCleanups()->Add(this);
+    // Make sure that this doesn't remain in ListOfCleanups after deletion
+    SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Before destroying the list with all its contents free all TGPicture
+//  objects in the list.
+//
+MGList::~MGList()
+{
+    DeletePictures();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Free/Delete all TGPicture store in list.
+//
+void MGList::DeletePictures()
+{
+    TObject *obj;
+    TIter Next(this);
+    while ((obj=Next()))
+    {
+        if (!obj->InheritsFrom(TGPicture::Class()))
+            continue;
+
+        //
+        // Remove the object first. Otherwise we would remove
+        // a non existing object...
+        //
+        Remove(obj);
+        gClient->FreePicture((TGPicture*)obj);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Delete all pictures. Call TList::Delete.
+//
+void MGList::Delete(Option_t *option)
+{
+    DeletePictures();
+    TList::Delete(option);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Does a dynamic cast from a TObject to a TGWidget. This is necesary
+//  if a class derived from TObject inherits also from TGWidget and
+//  you have only a pointer to the TObject available.
+//
+TGWidget *MGList::GetWidget(TObject *obj) const
+{
+    //
+    // - IsA gives a pointer to the parent class entry in the dictionary
+    // - DynamicCast tries to cast obj of class type obj->IsA to one
+    //   of its base classes TGWidget
+    // - This method is ment for dynamic casts (multi inheritance)
+    //
+    //  If this functions makes trouble check for the correct inheritance
+    //  first via obj->InheritsFrom(TGWidget::Class())
+    //
+    //  The root implementation is used, because for space reasons
+    //  the C++ dynamic_cast<TGWidget*> is turned off by the option
+    //  -fno-rtti, which could be used in 'plain' C++
+    //
+
+    //
+    // FIXME: This should not be necessary but it is, why??
+    //
+    // TRY: TGPicture *pic = gClient->GetPicture("pic");
+    //      cout << pic->IsA()->DynamicCast(TGWidget::Class(), pic) << endl;
+    //
+    //      Is this another bug in root?
+    //
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,07)
+    if (!obj->InheritsFrom(TGWidget::Class()))
+        return NULL;
+#endif
+
+    return (TGWidget*)obj->IsA()->DynamicCast(TGWidget::Class(), obj);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Returns kTRUE if the object is derived from TGWidget and a widget
+//  with the TGWidget id of this object is already in the list.
+//  If the object is not derived from TGWidget or no TGWidget object
+//  with the same widget id is existing in the list kFALSE is returned.
+//  If the TGWidget has an object id < 0 kFALSE is always retuned.
+//
+Bool_t MGList::IsExisting(TObject *obj) const
+{
+    const TGWidget *wid = GetWidget(obj);
+
+    //
+    // check whether it is a TGWidget
+    //
+    if (!wid)
+        return kFALSE;
+
+    const Int_t id = wid->WidgetId();
+
+    //
+    // check whether is has a valid id
+    // (not id=-1, which is the standard id)
+    //
+    if (id < 0)
+        return kFALSE;
+
+    //
+    // check whether Widget id is already existing in the list
+    //
+    return FindWidget(id) ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the given object obj is derived from TGWidget and a TGWidget with
+//  the same widget id is already existing in the list the object is
+//  ignored, otherwise it is added to the list via TList::Add(TObject *)
+//
+void MGList::Add(TObject *obj)
+{
+    if (IsExisting(obj))
+    {
+        // FIXME: Replace by gLog
+        const Int_t id = GetWidget(obj)->WidgetId();
+        cout << "Widget with id #" << id << " (";
+        cout << FindWidget(id)->ClassName() << ") already in list... ";
+        cout << obj->GetName() << " ignored." << endl;
+        return;
+    }
+
+    TList::Add(obj);
+    obj->SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the given object obj is derived from TGWidget and a TGWidget with
+//  the same widget id is already existing in the list the object is
+//  ignored, otherwise it is added to the list via
+//  TList::Add(TObject *, Option_t *)
+//
+void MGList::Add(TObject *obj, Option_t *opt)
+{
+    if (IsExisting(obj))
+    {
+        Int_t id = GetWidget(obj)->WidgetId();
+        cout << "Widget with id #" << id << " (";
+        cout << FindWidget(id)->ClassName() << ") already in list... ";
+        cout << obj->GetName() << " ignored." << endl;
+        return;
+    }
+
+    TList::Add(obj, opt);
+    obj->SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Adds the picture physically to the list. The list takes care of that
+//   - The picture is freed as often as it was retrieved from gClient
+//
+void MGList::AddPicture(TGPicture *pic, const char *name)
+{
+    //
+    // Check whether the picture exists
+    //
+    if (!pic)
+    {
+        cout << "Warning: Requested picture '" << name << "' not found... ignored." << endl;
+        cout << "    Please copy " << name << " to $HOME or $HOME/icons or add" << endl;
+        cout << "      Unix.*.Gui.IconPath: ~/Path/To/The/Picture" << endl;
+        cout << "    to [$HOME/].rootrc."  << endl;
+        return;
+    }
+
+    //
+    // Add the picture to the list
+    //
+    TList::Add(pic);
+    pic->SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This gets a picture from the picture pool of the TGClient-object.
+//  The pictures are freed automatically in the dstructor of the list.
+//  The picture counts itself how often it got used, so that only
+//  the first call to GetPicture will craete it and the last call to
+//  FreePicture will destroy it. If you access the picture only via
+//  MGList::GetPicture you don't have to care about.
+//
+//  Don't try to call FreePicture by yourself for a picture gotten by
+//  GetPicture. This is independant of the kIsOwner bit.
+//
+const TGPicture *MGList::GetPicture(const char *name)
+{
+    TGPicture *pic = const_cast<TGPicture*>(gClient->GetPicture(name));
+    AddPicture(pic, name);
+    return pic;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This gets a picture from the picture pool of the TGClient-object.
+//  The pictures are freed automatically in the dstructor of the list.
+//  The picture counts itself how often it got used, so that only
+//  the first call to GetPicture will craete it and the last call to
+//  FreePicture will destroy it. If you access the picture only via
+//  MGList::GetPicture you don't have to care about.
+//
+//  Don't try to call FreePicture by yourself for a picture gotten by
+//  GetPicture. This is independant of the kIsOwner bit.
+//
+const TGPicture *MGList::GetPicture(const char *name, Int_t width, Int_t height)
+{
+    TGPicture *pic = const_cast<TGPicture*>(gClient->GetPicture(name, width, height));
+    AddPicture(pic, name);
+    return pic;
+}
+// --------------------------------------------------------------------------
+//
+//  Search the list for a object derived from TGidget which has the given
+//  widget id. Returns a pointer to this object otherwise NULL.
+//  For IDs < 0 the function returns always NULL.
+//
+TObject *MGList::FindWidget(Int_t id) const
+{
+    if (id<0)
+        return NULL;
+
+    TObject *obj;
+    TIter Next(this);
+    while ((obj=Next()))
+    {
+        const TGWidget *wid = GetWidget(obj);
+
+        if (!wid)
+            continue;
+
+        if (id == wid->WidgetId())
+            return obj;
+    }
+    return NULL;
+}
Index: /tags/Mars-V0.9/mbase/MGList.h
===================================================================
--- /tags/Mars-V0.9/mbase/MGList.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGList.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MGList
+#define MARS_MGList
+
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+
+class TGWidget;
+class TGPicture;
+
+class MGList : public TList
+{
+private:
+    TGWidget *GetWidget(TObject *obj) const;
+    Bool_t    IsExisting(TObject *obj) const;
+
+    void      AddPicture(TGPicture *pic, const char *name);
+    void      DeletePictures();
+
+public:
+    MGList();
+    ~MGList();
+
+    void Add(TObject *obj);
+    void Add(TObject *obj, Option_t *opt);
+
+    void Delete(Option_t *option="");
+
+    const TGPicture *GetPicture(const char *name);
+    const TGPicture *GetPicture(const char *name, Int_t width, Int_t height);
+
+    TObject *FindWidget(Int_t id) const;
+
+    ClassDef(MGList, 0)
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MGMap.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MGMap.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGMap.cc	(revision 9772)
@@ -0,0 +1,582 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 05/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MGMap
+//  =====
+//
+// This Map of TObjects connects TObjects with a TString. It can be used
+// to create maps which displays tooltips it the mouse is above the objects.
+//
+// It is also a tool to convert TObjects which are drawn into
+// a bitmap or to draw them into a TGFrame. Because in both cases the
+// support for drawing such object must be programmed explicitly only
+// simple objects (TLine, TMarker, etc) are supported.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MGMap.h"
+
+#include <limits.h>  // INT_MAX
+
+#include <TPad.h>    // gPad, TPad::GetMaxDistance()
+
+#include <TLine.h>
+#include <TMarker.h>
+
+#include <TGToolTip.h>
+
+ClassImp(MGMap);
+
+using namespace std;
+
+//
+// THIS IS A WORKAROUND TO GET A MORE DIRECT ACCESS TO TGX11
+//
+/*
+#include <TGX11.h>
+class MGX11 : public TGX11
+{
+public:
+    ULong_t GetGc(Int_t which) const
+    {
+        return (ULong_t)*TGX11::GetGC(which);
+    }
+    void DrawLine(Drawable_t id, TObject *o, Int_t dx, Int_t dy, Float_t r)
+    {
+        TLine *l = dynamic_cast<TLine*>(o);
+        if (!l)
+            return;
+
+        SetLineColor(l->GetLineColor());
+        SetLineWidth(l->GetLineWidth());
+        SetLineStyle(l->GetLineStyle());
+
+        if (l->GetLineColor()==kRed)
+            SetLineColor(50);
+        if (l->GetLineColor()==kBlue)
+            SetLineColor(9);
+
+        gVirtualX->DrawLine(id, GetGc(0),
+                            dx+(l->GetX1()/r), dy-(l->GetY1()/r),
+                            dx+(l->GetX2()/r), dy-(l->GetY2()/r));
+    }
+    void DrawMarker(Drawable_t id, TObject *o, Int_t dx, Int_t dy, Float_t r)
+    {
+        TMarker *m = dynamic_cast<TMarker*>(o);
+        if (!m)
+            return;
+
+        SetLineColor(m->GetMarkerColor());
+        SetLineStyle(kSolid);
+        SetLineWidth(1);
+
+        const Double_t x = dx+(m->GetX()/r);
+        const Double_t y = dy-(m->GetY()/r);
+        const Int_t l = (Int_t)(m->GetMarkerSize()*5)+1;
+
+        switch (m->GetMarkerStyle())
+        {
+        case kPlus:
+            gVirtualX->DrawLine(id, GetGc(0), x-l, y, x+l, y);
+            gVirtualX->DrawLine(id, GetGc(0), x, y-l, x, y+l);
+            break;
+        case kCircle:
+            for (int i=0; i<8; i++)
+                gVirtualX->DrawLine(id, GetGc(0),
+                                    x+l*cos(i*TMath::TwoPi()/8),
+                                    y+l*sin(i*TMath::TwoPi()/8),
+                                    x+l*cos(((i+1)%8)*TMath::TwoPi()/8),
+                                    y+l*sin(((i+1)%8)*TMath::TwoPi()/8));
+            break;
+        case kCross:
+            gVirtualX->DrawLine(id, GetGc(0), x-l, y-l, x+l, y+l);
+            gVirtualX->DrawLine(id, GetGc(0), x-l, y+l, x+l, y-l);
+            break;
+        }
+    }
+};
+*/
+// --------------------------------------------------------------------------
+//
+// Constructor. For more details see TExMap
+//
+MGMap::MGMap(Int_t mapSize) : TExMap(mapSize)//, fToolTip(0)
+{
+//    fToolTip = new TGToolTip(0, "", 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes all objects of the map if kIsOwner is set via
+// SetOwner.
+//
+MGMap::~MGMap()
+{
+    if (TestBit(kIsOwner))
+        Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Add an TObject to be drawn and if necessary a corresponding TString
+// to the Map. You must take care of deleting both objects if SetOwner()
+// was not called. Otherwise MGMap takes the ownership of the objects.
+//
+void MGMap::Add(TObject *k, TString *v)
+{
+    TExMap::Add((ULong_t)GetSize(), (Long_t)k, (Long_t)v);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete all objects stored in the TExMap
+//
+void MGMap::Delete(Option_t *opt)
+{
+    Long_t key, val;
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        delete (TObject*)(key);
+        if (val)
+            delete (TString*)(val);
+        /*
+         Long_t key2, val2;
+         TExMapIter map2(&fMapG);
+         while (map2.Next(key2, val2))
+         if (val==val2)
+         {
+         delete (TObject*)key;
+         fMapG.Remove(key);
+         }
+         */
+    }
+    TExMap::Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint all TObjects (which are supported) to a drawable with Id id.
+// Scale is the distance of the center of your drawable to one edge in
+// user coordinates.
+//
+// FIXME: Currently the width and height is hardcoded to 768x576 -
+//        find a way to get it from the drawable.
+//
+/*
+void MGMap::Paint(Drawable_t id, Float_t scale)
+{
+    if (id==0 && gPad)
+        id = gVirtualX->GetWindowID(gPad->GetPixmapID());
+
+    const Int_t w = 768;
+    const Int_t h = 576;
+
+    scale /= TMath::Hypot((float)w, (float)h)/2;
+
+    Long_t key, val;
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        TObject *o = (TObject*)key;
+        ((MGX11*)gVirtualX)->DrawLine(id,   o, w/2, h/2, scale);
+        ((MGX11*)gVirtualX)->DrawMarker(id, o, w/2, h/2, scale);
+    }
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Convert root colors to arbitrary bitmap coordinates
+//
+UChar_t MGMap::Color(int col)
+{
+    switch (col)
+    {
+    case kBlack:  return 0;
+    case kWhite:  return 0xff;
+    case kYellow: return 0x0f;
+    case kRed:    return 2;
+    case kGreen:  return 2<<2;
+    case kBlue:   return 2<<4;
+    default:
+        return 0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a line into the buffer (size w*h) from (x1, y1) to (x2, y2) with
+// the color col and the line style style (default: solid)
+//
+void MGMap::DrawLine(UChar_t *buf, int w, int h, Float_t x1, Float_t y1, Float_t x2, Float_t y2, UChar_t col, Int_t style)
+{
+    const Int_t    step = style==kSolid?1:3;
+    const Double_t len  = TMath::Hypot(x2-x1, y2-y1);
+    const Double_t dx   = (x2-x1)/len*step;
+    const Double_t dy   = (y2-y1)/len*step;
+
+    Double_t x = x1;
+    Double_t y = y1;
+
+    for (int i=0; i<len; i+=step)
+    {
+        x+= dx;
+        y+= dy;
+
+        const Int_t iy = TMath::Nint(y);
+        if (iy<0 || iy>=h)
+            continue;
+
+        const Int_t ix = TMath::Nint(x);
+        if (ix<0 || ix>=w)
+            continue;
+
+        buf[ix+iy*w] = col;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a box into the buffer (size w*h) from (x1, y1) to (x2, y2) with
+// the color col and the line style style (default: solid)
+//
+void MGMap::DrawBox(UChar_t *buf, int w, int h, Float_t x1, Float_t y1, Float_t x2, Float_t y2, UChar_t col, Int_t style)
+{
+    DrawLine(buf, w, h, x1, y1, x2, y1, col, style);
+    DrawLine(buf, w, h, x1, y2, x2, y1, col, style);
+    DrawLine(buf, w, h, x1, y1, x1, y2, col, style);
+    DrawLine(buf, w, h, x2, y1, x2, y2, col, style);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a circle into the buffer (size w*h) around (x, y) with radius r and
+// the color col.
+//
+void MGMap::DrawCircle(UChar_t *buf, int w, int h, Float_t x, Float_t y, Float_t r, UChar_t col)
+{
+    const Int_t n = TMath::Nint(sqrt(2.)*r*TMath::Pi()/2);
+    for (int i=0; i<n-1; i++)
+    {
+        const Double_t angle = TMath::TwoPi()*i/n;
+
+        const Double_t dx = r*cos(angle);
+        const Double_t dy = r*sin(angle);
+
+        const Int_t x1 = TMath::Nint(x+dx);
+        const Int_t x2 = TMath::Nint(x-dx);
+
+        const Int_t y1 = TMath::Nint(y+dy);
+        if (y1>=0 && y1<h)
+        {
+            if (x1>=0 && x1<w)
+                buf[x1+y1*w] = col;
+
+            if (x2>=0 && x2<w)
+                buf[x2+y1*w] = col;
+        }
+
+        const Int_t y2 = TMath::Nint(y-dy);
+        if (y2>=0 && y2<h)
+        {
+            if (x1>=0 && x1<w)
+                buf[x1+y2*w] = col;
+
+            if (x2>=0 && x2<w)
+                buf[x2+y2*w] = col;
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a dot into the buffer (size w*h) at (x, y) with color col.
+//
+void MGMap::DrawDot(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, UChar_t col)
+{
+    const Int_t x1 = TMath::Nint(cx);
+    const Int_t y1 = TMath::Nint(cy);
+
+    if (x1>=0 && y1>=0 && x1<w && y1<h)
+        buf[x1+y1*w] = col;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a line into the buffer. The TObject must be a TLine.
+// Currently only solid and non sloid line are supported.
+//
+void MGMap::DrawLine(TObject *o, UChar_t *buf, int w, int h, Double_t scale)
+{
+    TLine *l = dynamic_cast<TLine*>(o);
+    if (!l)
+        return;
+
+    const Double_t x1 = 0.5*w-(l->GetX1()/scale);
+    const Double_t x2 = 0.5*w-(l->GetX2()/scale);
+    const Double_t y1 = 0.5*h-(l->GetY1()/scale);
+    const Double_t y2 = 0.5*h-(l->GetY2()/scale);
+
+    const Int_t col = Color(l->GetLineColor());
+    DrawLine(buf, w, h, x1, y1, x2, y2, col, l->GetLineStyle());
+}
+
+void MGMap::DrawMultiply(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, Float_t size, UChar_t col)
+{
+    DrawLine(buf, w, h, cx-size, cy-size, cx+size, cy+size, col);
+    DrawLine(buf, w, h, cx+size, cy-size, cx-size, cy+size, col);
+}
+
+void MGMap::DrawCross(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, Float_t size, UChar_t col)
+{
+    DrawLine(buf, w, h, cx-size, cy, cx+size, cy, col);
+    DrawLine(buf, w, h, cx, cy-size, cx, cy+size, col);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw marker into the buffer. The TObject must be a TMarker.
+// Currently kCircle, kMultiply and KDot are supported.
+//
+void MGMap::DrawMarker(TObject *o, UChar_t *buf, int w, int h, Double_t scale)
+{
+    TMarker *m = dynamic_cast<TMarker*>(o);
+    if (!m)
+        return;
+
+    Double_t x = 0.5*w-(m->GetX()/scale);
+    Double_t y = 0.5*h-(m->GetY()/scale);
+
+    Int_t col = Color(m->GetMarkerColor());
+
+    switch (m->GetMarkerStyle())
+    {
+    case kCircle:
+        DrawCircle(buf, w, h, x, y, m->GetMarkerSize()*2+1, col);
+        break;
+    case kDot:
+        DrawDot(buf, w, h, x, y, col);
+        break;
+    case kMultiply:
+        DrawMultiply(buf, w, h, x, y, m->GetMarkerSize()*2+1, col);
+        break;
+    case kCross:
+        DrawCross(buf, w, h, x, y, m->GetMarkerSize()*2+1, col);
+        break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint all elements to the pad by calling their Paint() function
+//
+void MGMap::Paint(Option_t *o)
+{
+    Long_t key, val;
+    TExMapIter map(this);
+    while (map.Next(key, val))
+        ((TObject*)key)->Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint all objects into a buffer of w*h UChar_ts. The scale
+// gives you the conversio factor to convert pad coordinates into
+// buffer pixels - it is the distance from the center of the buffer
+// to one of its edges.
+//
+void MGMap::Paint(UChar_t *buf, int w, int h, Float_t scale)
+{
+    scale /= TMath::Hypot((float)w, (float)h)/2;
+
+    Long_t key, val;
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        TObject *o = (TObject*)key;
+        DrawLine(o, buf, w, h, scale);
+        DrawMarker(o, buf, w, h, scale);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for an object at px, py. Return the pointer to it
+// if found. Set str accordingly if a corresponding TString is found.
+//
+TObject *MGMap::PickObject(Int_t px, Int_t py, TString &str) const
+{
+    Long_t key, val;
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        if (!val)
+            continue;
+
+        TObject *o=(TObject*)key;
+        if (o->DistancetoPrimitive(px, py)>TPad::GetMaxPickDistance())
+            continue;
+
+        str = *(TString*)val;
+        return o;
+    }
+    return NULL;
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns string containing info about the object at position (px,py).
+// Returned string will be re-used (lock in MT environment).
+// The text will be truncated to 128 charcters
+//
+char *MGMap::GetObjectInfo(Int_t px, Int_t py) const
+{
+    TString str;
+    PickObject(px, py, str);
+
+    static char txt[129];
+    txt[128]=0;
+
+    return strncpy(txt, str.Data(), 128);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate distance to primitive by checking all gui elements
+//
+Int_t MGMap::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    Int_t min = INT_MAX;
+
+    Long_t key, val;
+    TExMapIter map(this);
+    while (map.Next(key, val))
+    {
+        TObject *o=(TObject*)key;
+
+        const Int_t d = o->DistancetoPrimitive(px, py);
+
+        if (d<TPad::GetMaxPickDistance())
+            return 0;
+
+        if (d<min)
+            min=d;
+    }
+
+    return min;
+}
+
+// --------------------------------------------------------------------------
+//
+// Displays a tooltip
+//
+/*
+void MGMap::ShowToolTip(Int_t px, Int_t py, const char *txt)
+{
+    if (TestBit(kNoToolTips))
+        return;
+
+    Int_t x=0;
+    Int_t y=0;
+
+    const Window_t id1 = gVirtualX->GetWindowID(gPad->GetCanvasID());
+    const Window_t id2 = fToolTip->GetParent()->GetId();
+
+    Window_t id3;
+    gVirtualX->TranslateCoordinates(id1, id2, px, py, x, y, id3);
+
+    // Show tool tip
+    fToolTip->SetText(txt);
+    fToolTip->Show(x+4, y+4);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// This function was connected to all created canvases. It is used
+// to redirect GetObjectInfo into our own status bar.
+//
+// The 'connection' is done in Draw. It seems that 'connected'
+// functions must be public.
+//
+/*
+void MGMap::EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected)
+{
+    TVirtualPad *c = (TVirtualPad*)gTQSender; // gTQSender==TCanvas
+
+    gPad = c ? c->GetSelectedPad() : NULL;
+    if (!gPad)
+        return;
+
+    // Try to find a corresponding object with kCannotPick set and
+    // an available TString (for a tool tip)
+    TString str;
+    if (!selected || selected==this)
+        selected =  PickObject(px, py, str);
+
+    if (!selected)
+        return;
+
+    // Handle some gui events
+    switch (event)
+    {
+    case kMouseMotion:
+        if (!fToolTip->IsMapped() && !str.IsNull())
+            ShowToolTip(px, py, str);
+        break;
+
+    case kMouseLeave:
+        if (fToolTip->IsMapped())
+            fToolTip->Hide();
+        break;
+
+    default:
+        ExecuteEvent(event, px, py);
+        break;
+    }
+}
+*/
+
+/*
+void MAstroCatalog::RecursiveRemove(TObject *obj)
+{
+    ULong_t hash;
+    Long_t key, val;
+
+    TExMapIter map(&fMapG);
+    while (map.Next(hash, key, val))
+    {
+        if (key != (Long_t)obj)
+            continue;
+
+        fMapG.Remove(hash, key);
+        delete (TObject*)(key);
+        if (val)
+            delete (TString*)(val);
+        break;
+    }
+}
+*/
Index: /tags/Mars-V0.9/mbase/MGMap.h
===================================================================
--- /tags/Mars-V0.9/mbase/MGMap.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGMap.h	(revision 9772)
@@ -0,0 +1,63 @@
+#ifndef MARS_MGMap
+#define MARS_MGMap
+
+#ifndef ROOT_GuiTypes
+#include <GuiTypes.h> // Drawable_t
+#endif
+#ifndef ROOT_TExMap
+#include <TExMap.h>
+#endif
+
+class TString;
+class TGToolTip;
+
+#include <iostream>
+
+class MGMap : public TExMap
+{
+private:
+    //    TGToolTip *fToolTip;   //! The tooltip currently displayed
+
+    enum {
+        kIsOwner    = BIT(14),
+        // kNoToolTips = BIT(15), // suppress tooltips
+    };
+
+    //    void ShowToolTip(Int_t px, Int_t py, const char *txt);
+
+public:
+    MGMap(Int_t mapSize = 100);
+    ~MGMap();
+
+    void     SetOwner(Bool_t o=kTRUE) { o ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+    void     Add(TObject *k, TString *v=0);
+    void     Delete(Option_t *opt = "");
+    void     Clear(Option_t *o="") { TExMap::Delete(); }
+
+    //    void   SetNoToolTips(Bool_t b=kTRUE) { b ? SetBit(kNoToolTips) : ResetBit(kNoToolTips); } // *TOGGLE* *GETTER=HasNoToolTips
+    //    Bool_t HasNoToolTips() const         { return TestBit(kNoToolTips); }
+
+    void     Paint(Option_t *o="");
+    void     Paint(UChar_t *buf, int w, int h, Float_t scale);
+    //void     Paint(Drawable_t id, Float_t scale);
+
+    void     DrawLine(TObject *o, UChar_t *buf, int w, int h, Double_t scale);
+    void     DrawMarker(TObject *o, UChar_t *buf, int w, int h, Double_t scale);
+
+    //void     EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected);
+    TObject *PickObject(Int_t px, Int_t py, TString &str) const;
+    char    *GetObjectInfo(Int_t px, Int_t py) const;
+    Int_t    DistancetoPrimitive(Int_t px, Int_t py);
+
+    static UChar_t Color(int col);
+    static void    DrawCircle(UChar_t *buf, int w, int h, Float_t x, Float_t y, Float_t r, UChar_t col);
+    static void    DrawLine(UChar_t *buf, int w, int h, Float_t x1, Float_t y1, Float_t x2, Float_t y2, UChar_t col, Int_t style=1);
+    static void    DrawBox(UChar_t *buf, int w, int h, Float_t x1, Float_t y1, Float_t x2, Float_t y2, UChar_t col, Int_t style=1);
+    static void    DrawDot(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, UChar_t col);
+    static void    DrawMultiply(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, Float_t size, UChar_t col);
+    static void    DrawCross(UChar_t *buf, int w, int h, Float_t cx, Float_t cy, Float_t size, UChar_t col);
+
+    ClassDef(MGMap, 1) // Special TExMap supporting enhanced drawing and bitmap drawing
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MGMenu.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MGMenu.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGMenu.cc	(revision 9772)
@@ -0,0 +1,235 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2003 <mailto:tbretz@astro-uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGMenu, MGPopupMenu
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MGMenu.h"
+
+
+MGMenuEntry::MGMenuEntry(TGMenuEntry *ent)
+{
+    memcpy(this, ent, sizeof(*ent));
+}
+
+// -------------------------------------------------------------
+//
+// Return the keycode corresponding to the hot string of
+// a TGmenuEntry
+//
+UInt_t MGPopupMenu::GetKeyCode(TGMenuEntry *el)
+{
+    TGHotString *str = MGMenuEntry(el).GetLabel();
+    return gVirtualX->KeysymToKeycode(str->GetHotChar());
+}
+
+// -------------------------------------------------------------
+//
+// Bind all hot keys used in this popup menu subsequentlt
+// to the TGMainFrame and send a HandleKey message to the
+// TGWindow
+//
+void MGPopupMenu::BindKeys(const TGWindow *w, TGMainFrame *frame)
+{
+    TIter Next(fEntryList);
+    TGMenuEntry *el;
+
+    //
+    // Loop Through all entries
+    //
+    while ((el=(TGMenuEntry*)Next()))
+    {
+        switch (el->GetType())
+        {
+            //
+            // For seperators and labels nothing to do
+            //
+        case kMenuSeparator:
+        case kMenuLabel:
+            continue;
+
+            //
+            // For an entry and a popup menu bind the hot key
+            // In case of a popup menu call BindKeys subsequently
+            //
+        case kMenuEntry:
+        case kMenuPopup:
+            frame->BindKey(w, GetKeyCode(el), kKeyMod1Mask);
+            if (el->GetType()==kMenuPopup)
+                MGMenuEntry(el).GetPopup()->BindKeys(w, frame);
+            continue;
+        }
+    }
+}
+
+/*
+ kMenuActiveMask  = BIT(0),
+ kMenuEnableMask  = BIT(1),
+ kMenuDefaultMask = BIT(2),
+ kMenuCheckedMask = BIT(3),
+ kMenuRadioMask   = BIT(4),
+ kMenuHideMask    = BIT(5)
+ */
+
+// -------------------------------------------------------------
+//
+//  Handle a keyboard event. Return kFALSE in case of a
+//  successfully send message, which means: close all open
+//  popups.
+//
+Bool_t MGPopupMenu::HandleKey(Event_t *evt)
+{
+    //
+    // Loop through all entries in this popup menu. If the entry is
+    // an open popup menu send the key event to the open popup.
+    //
+    TIter Next(fEntryList);
+    TGMenuEntry *el;
+    while ((el=(TGMenuEntry*)Next()))
+    {
+        if (el->GetType()==kMenuPopup && el->GetStatus()&kMenuActiveMask)
+            return MGMenuEntry(el).GetPopup()->HandleKey(evt);
+    }
+
+    Next.Reset();
+
+    //
+    // If no open popup is found search the pressed key in this
+    // popup menu.
+    //
+    while ((el=(TGMenuEntry*)Next()))
+    {
+        switch (el->GetType())
+        {
+            //
+            // Do nothing
+            //
+        case kMenuSeparator:
+        case kMenuLabel:
+            continue;
+
+            //
+            // If the keycode corresponds to the hot key
+            // of this entry and the entry is enabled activate the entry
+            // and send the corresponding message/
+            //
+        case kMenuEntry:
+            if (GetKeyCode(el)==evt->fCode && el->GetStatus()&kMenuEnableMask)
+            {
+                Activate(el);
+                SendMessage(fMsgWindow, MK_MSG(kC_COMMAND, kCM_MENU),
+                            el->GetEntryId(), (Long_t)MGMenuEntry(el).GetUserData());
+                return kFALSE;
+            }
+            continue;
+
+            //
+            // If the keycode corresponds to the hot key
+            // of this popup menu activate the popup menu.
+            //
+        case kMenuPopup:
+            if (GetKeyCode(el)!=evt->fCode)
+                continue;
+
+            Activate(el);
+            HandleTimer(NULL);
+            return kTRUE;
+        }
+    }
+    return kTRUE;
+}
+
+// -------------------------------------------------------------
+//
+// Bind the keys of all popups subsequently to the given main
+// frame. The menu bar hot keys are already bound by TGMenuBar.
+// Bind the Escape key to close the popups, too.
+//
+void MGMenuBar::BindKeys(TGMainFrame *frame)
+{
+    TGFrameElement *el=NULL;
+    TIter Next(fList);
+    while ((el = (TGFrameElement *)Next()))
+        ((MGPopupMenu*)((TGMenuTitle *) el->fFrame)->GetMenu())->BindKeys(this, frame);
+
+    frame->BindKey(this, 9/*ESC*/, 0);
+}
+
+// -------------------------------------------------------------
+//
+// Handle the keyboard event send to this menu bar.
+//
+Bool_t MGMenuBar::HandleKey(Event_t *event)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,02,00)
+    //
+    // If this isn't a pressed key do nothing
+    //
+    if (event->fType != kGKeyPress)
+        return kTRUE;
+
+    //
+    // Check whether one popup is alreadu open
+    //
+    TGFrameElement *el=NULL;
+    TIter Next(fList);
+    while ((el = (TGFrameElement *)Next()))
+    {
+        if (!((TGMenuTitle*)el->fFrame)->GetState())
+            continue;
+
+        TGMenuTitle &f = *(TGMenuTitle*)el->fFrame;
+
+        //
+        // If a open popup is found redirect the key event to this
+        // popup menu
+        //
+        Bool_t rc = ((MGPopupMenu*)f.GetMenu())->HandleKey(event);
+
+        //
+        // If a message could be successfully send or the escape key
+        // was pressed close the popup.
+        //
+        if (rc && event->fCode!=9/*ESC*/)
+            return kTRUE;
+
+        f.SetState(kFALSE);
+        gVirtualX->GrabPointer(0, 0, 0, 0, kFALSE);  // ungrab pointer
+        gVirtualX->SetKeyAutoRepeat(kTRUE); // set in TGMainFrame::HandleKey
+        fCurrent = 0;
+        return kTRUE;
+    }
+#endif
+
+    return TGMenuBar::HandleKey(event);
+}
+
+void MGMenuBar::BindKeys(Bool_t b)
+{
+#if ROOT_VERSION_CODE >= ROOT_VERSION(4,02,00)
+    TGMenuBar::BindKeys(b);
+#endif
+}  // root>=4.02.00
Index: /tags/Mars-V0.9/mbase/MGMenu.h
===================================================================
--- /tags/Mars-V0.9/mbase/MGMenu.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGMenu.h	(revision 9772)
@@ -0,0 +1,54 @@
+#ifndef MARS_MGMenu
+#define MARS_MGMenu
+
+#ifndef ROOT_TGMenu
+#include <TGMenu.h>
+#endif
+
+class MGPopupMenu;
+
+class MGMenuEntry : public TGMenuEntry
+{
+    /*
+     Workaround for the protected data mambers of TGMenuEntry
+     */
+public:
+    MGMenuEntry(TGMenuEntry *ent);
+    ~MGMenuEntry()
+    {
+        fLabel=0;
+    }
+
+    MGPopupMenu *GetPopup() { return (MGPopupMenu*)fPopup; }
+    TGHotString *GetLabel() { return fLabel; }
+    void *GetUserData()     { return fUserData; }
+};
+
+class MGPopupMenu : public TGPopupMenu
+{
+public:
+    MGPopupMenu(const TGWindow* p = 0, UInt_t w = 10, UInt_t h = 10, UInt_t options = 0) :
+        TGPopupMenu(p, w, h, options)
+    {
+    }
+
+    UInt_t GetKeyCode(TGMenuEntry *el);
+
+    void BindKeys(const TGWindow *w, TGMainFrame *frame);
+
+    Bool_t HandleKey(Event_t *evt);
+};
+
+class MGMenuBar : public TGMenuBar
+{
+public:
+    MGMenuBar(const TGWindow* p, UInt_t w, UInt_t h, UInt_t options = kHorizontalFrame|kRaisedFrame) :
+        TGMenuBar(p, w, h, options) {}
+
+    void BindKeys(TGMainFrame *frame);                   // root<=3.10.02
+    void BindKeys(Bool_t b);
+
+    Bool_t HandleKey(Event_t *event);
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MGTask.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MGTask.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGTask.cc	(revision 9772)
@@ -0,0 +1,183 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  11/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MGTask                                                                //
+//                                                                         //
+//   A MTask with several enhancments for a graphical interface.           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MGTask.h"
+
+#include <TMethod.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGGroupFrame.h"
+
+ClassImp(MGTask);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. Initialized fFrame with NULL.
+//
+MGTask::MGTask(const char *name, const char *title)
+    : fFrame(NULL)
+{
+    fName  = name  ? name  : "MGTask";
+    fTitle = title ? title : "Base class for all tasks with graphical I/O.";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes the GUI if one was created.
+//
+MGTask::~MGTask()
+{
+    if (fFrame)
+        delete fFrame;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Hides the graphical interface if existing and calls
+//  MTask::CallPreProcess
+//
+Int_t MGTask::CallPreProcess(MParList *plist)
+{
+    HideGui();
+
+    return MTask::CallPreProcess(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Shows the graphical interface if existing and calls
+//  MTask::CallPostProcess
+//
+Int_t MGTask::CallPostProcess()
+{
+    ShowGui();
+
+    return MTask::CallPostProcess();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Widget from the MGGroupFrame (GUI) with the Id id.
+//
+TObject *MGTask::FindWidget(Int_t id) const
+{
+    return fFrame->FindWidget(id);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Process a message. Redirect gui events (eg by calling
+//  TGButton->Associate()) to the MGGroupFrame when Creating the GUI in
+//  CreateGuiElements. And process the messages in the overwritten
+//  ProcessMessage function.
+//
+Bool_t MGTask::ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2)
+{
+    fLog->setf(ios::showbase);
+    *fLog << all << "Task " << GetDescriptor() << " received gui msg " << hex;
+    *fLog << msg << " " << submsg << " " << param1 << " " << param2 << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Show the gui (and its gui elements) of the task if existing.
+//
+void MGTask::ShowGui()
+{
+    if (fFrame)
+        fFrame->MapWindow();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Hide the gui (and its gui elements) of the task if existing.
+//
+void MGTask::HideGui()
+{
+    if (fFrame)
+        fFrame->UnmapWindow();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check whether a gui for this task was already created.
+//  If not create a MGGroupFrame to group the gui elements and add it
+//  to the given frame with the given layout hints.
+//  Now call the overwritten function CreateGuiElements to fill the group
+//  frame.
+//
+void MGTask::CreateGui(TGCompositeFrame *f, TGLayoutHints *layout)
+{
+    //
+    // Check whether frame already exists
+    //
+    if (fFrame)
+    {
+        *fLog << warn << GetDescriptor() << " Gui already created... skipped." << endl;
+        return;
+    }
+
+    //
+    // Check whether a gui is implemented for this class
+    //  - IsA gives a pointer to the dictionary entry of the mostly
+    //    inherited class of this Task
+    //  - GetMethodAllAny checks for the existance of CreateGuiElements
+    //    in the class and all its base classes
+    //  - now get the dictionary entry of the corresponding class
+    //    (in which the mathos was found)
+    //  - if method isn't overwritten the result is the dictionary
+    //    entry for MGTask.
+    //
+    TMethod *method = IsA()->GetMethodAllAny("CreateGuiElements");
+    if (method->GetClass() == MGTask::Class())
+    {
+        *fLog << warn << "Sorry, " << GetDescriptor();
+        *fLog << " doesn't override CreateGuiElements." << endl;
+        return;
+    }
+
+    //
+    //  create group frame
+    //
+    fFrame = new MGGroupFrame(this, f, ClassName());
+    f->AddFrame(fFrame, layout);
+
+    //
+    // add gui elements
+    //
+    CreateGuiElements(fFrame);
+}
Index: /tags/Mars-V0.9/mbase/MGTask.h
===================================================================
--- /tags/Mars-V0.9/mbase/MGTask.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MGTask.h	(revision 9772)
@@ -0,0 +1,50 @@
+#ifndef MARS_MGTask
+#define MARS_MGTask
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MTask                                                                   //
+//                                                                         //
+// Abstract base class for a task                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class TGLayoutHints;
+class TGCompositeFrame;
+
+class MGGroupFrame;
+
+class MGTask : public MTask
+{
+private:
+    MGGroupFrame *fFrame;     //!
+
+    virtual void CreateGuiElements(MGGroupFrame *f) {}
+
+    void ShowGui();
+    void HideGui();
+
+protected:
+    TObject *FindWidget(Int_t id) const;
+
+public:
+    MGTask(const char *name=NULL, const char *title=NULL);
+    virtual ~MGTask();
+
+    Int_t CallPreProcess(MParList *plist);
+    Int_t CallPostProcess();
+
+    virtual Bool_t ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2);
+
+    void CreateGui(TGCompositeFrame *f, TGLayoutHints *layout=NULL);
+
+    ClassDef(MGTask, 0) // Abstract base class for a task having a gui
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MInputStreamID.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MInputStreamID.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MInputStreamID.cc	(revision 9772)
@@ -0,0 +1,51 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// MInpuStreamID                                                            //
+//                                                                          //
+// This is a ID which is assigned to tasks and to a task list.              //
+// It depends on this ID whether a task is executed by the                  //
+// MTaskList::Process member funtion or not.                                //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MInputStreamID.h"
+
+ClassImp(MInputStreamID);
+
+// --------------------------------------------------------------------------
+//
+// (default) constructor
+//
+MInputStreamID::MInputStreamID(const char *name, const char *title)
+{
+    fName = name ? name : ClassName();
+    fTitle = title;
+
+    fStreamId = "All";
+}
+
Index: /tags/Mars-V0.9/mbase/MInputStreamID.h
===================================================================
--- /tags/Mars-V0.9/mbase/MInputStreamID.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MInputStreamID.h	(revision 9772)
@@ -0,0 +1,46 @@
+#ifndef MARS_MInputStreamID
+#define MARS_MInputStreamID
+
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MInpuStreamID                                                     //
+//                                                                   //
+// Assigns an ID to tasks or a task list                             //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+// -----------------------------------------------------------------------
+
+class MInputStreamID : public MParContainer
+{
+private:
+    TString fStreamId;	//! which type of task should be processed?
+
+public:
+    MInputStreamID(const char *name=NULL, const char *title=NULL);
+
+    Bool_t HasStreamId() const { return fStreamId.CompareTo("all", TString::kIgnoreCase)!=0; }
+
+    const TString &GetStreamId() const { return fStreamId; }
+    void SetStreamId(const char *t)    { fStreamId = t; }
+
+    Bool_t operator==(MInputStreamID &id) const
+    {
+        return fStreamId == id.fStreamId;
+    }
+
+    Bool_t operator!=(MInputStreamID &id) const
+    {
+        return fStreamId != id.fStreamId;
+    }
+
+    ClassDef(MInputStreamID, 0)	//Assigns an Id to tasks or a task list
+};
+
+// ---------------------------------------------------------------------
+
+#endif
Index: /tags/Mars-V0.9/mbase/MIter.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MIter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MIter.cc	(revision 9772)
@@ -0,0 +1,65 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  08/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// MIter                                                                    //
+//                                                                          //
+// This is the original MIter, but returns a MParContainer instead of a     //
+// TObject.                                                                 //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MIter.h"
+
+ClassImp(MIter);
+
+//______________________________________________________________________________
+MIter::MIter(const MIter &iter)
+{
+   // Copy a MIter. This involves allocating a new MIterator of the right
+   // sub class and assigning it with the original.
+
+   if (iter.fIterator) {
+      fIterator = iter.GetCollection()->MakeIterator();
+      fIterator->operator=(*iter.fIterator);
+   } else
+      fIterator = 0;
+}
+
+//______________________________________________________________________________
+MIter &MIter::operator=(const MIter &rhs)
+{
+   // Assigning an MIter to another. This involves allocatiing a new MIterator
+   // of the right sub class and assigning it with the original.
+
+   if (this != &rhs) {
+      if (rhs.fIterator) {
+         delete fIterator;
+         fIterator = rhs.GetCollection()->MakeIterator();
+         fIterator->operator=(*rhs.fIterator);
+      }
+   }
+   return *this;
+}
Index: /tags/Mars-V0.9/mbase/MIter.h
===================================================================
--- /tags/Mars-V0.9/mbase/MIter.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MIter.h	(revision 9772)
@@ -0,0 +1,43 @@
+#ifndef MARS_MIter
+#define MARS_MIter
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MIter                                                                   //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TIterator
+#include <TIterator.h>
+#endif
+
+class MParContainer;
+
+class MIter
+{
+private:
+   TIterator *fIterator;         //collection iterator
+
+protected:
+   MIter() : fIterator(0) { }
+
+public:
+   MIter(const TCollection *col, Bool_t dir = kIterForward)
+        : fIterator(col ? col->MakeIterator(dir) : 0) { }
+   MIter(TIterator *it) : fIterator(it) { }
+   MIter(const MIter &iter);
+   MIter &operator=(const MIter &rhs);
+   virtual            ~MIter() { SafeDelete(fIterator) }
+   MParContainer     *operator()() { return (MParContainer*)(fIterator ? fIterator->Next() : 0); }
+   MParContainer     *Next() { return (MParContainer*)(fIterator ? fIterator->Next() : 0); }
+   const TCollection *GetCollection() const { return fIterator ? fIterator->GetCollection() : 0; }
+   Option_t          *GetOption() const { return fIterator ? fIterator->GetOption() : ""; }
+   void               Reset() { if (fIterator) fIterator->Reset(); }
+
+   ClassDef(MIter,0)  //Iterator wrapper
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MLog.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MLog.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLog.cc	(revision 9772)
@@ -0,0 +1,711 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MLog
+//
+// This is what we call the logging-system.
+//
+// It is derived from the C++ streaming classes and can handle our
+// logging. The log output can be redirected to stdout, stderr, any other
+// stream or a root window.
+//
+// There is a global log-instance which you can use like cout, id is gLog.
+// A log-instance of your choice (gLog by default) is destributed to all
+// Task which are used in an eventloop, so that you can redirect the output
+// of one eventloop to where you want..
+//
+// The MLog stream has the advantage, that it can be used like the common
+// C++ streams (for example cout). It can redirect the stream to different
+// outputs (console, file, GUI) if necessary at the same time.
+//
+// It supports different debug levels. The debug level of the current
+// stream contents is set by SetDebugLevel, the output level of the
+// current stream can be set by SetOutputLevel.
+//
+// The header file MLogManip.h contains so called manipulators (like flush
+// or setw from iomanip.h) which can manipulate these levels from within
+// stream, for example:
+//    gLog << debug(3) << "Hallo World " << endl;
+// sets the debug level of the following stream to 3
+//
+// edev(), ddev() can be used to enable/disable an output device from
+// within the stream. The enumerations are defined in MLog::_flags
+//
+// Commonly used abbreviations are also defined:
+//    dbginf  Prints source file name and line number. Used for output
+//            which people may like to look up in the code
+//    all     Is streamed to the output in any case. Used for outputs
+//            which are requested by the user (eg TObject::Print)
+//    err     Should be used for fatal errors which stops the current
+//            processing, eg:
+//              gLog << err << "ERROR: TObject::Copy - Stopped" << endl;
+//    warn    Warning means an error occured, but it is not clear whether
+//            this results further procesing or not.
+//    inf     Informs the user about what's going on. Mostly usefull for
+//            debugging, but in general not necessary at all.
+//    dbg     Use this for your private purpose to mark something as debug
+//            output. This is _not_ ment to be persistent!
+//
+// If your console is capable of ANSI colors the stream is displayed
+// in several colors:
+//    all:    default
+//    err:    red
+//    warn:   yellow/brown
+//    inf:    green
+//    dbg:    blue (and all other levels)
+//
+// If you have a dark background on your console you might want to set
+// an environment variable, eg:
+//    export MARSDEFINES=-DHAVE_DARKBACKGROUND
+// and recompile MLog.
+//
+// If your console can display it also 'underline' can be used. This
+// underlines a text till the next 'endl', eg:
+//    gLog << underline << "This is important!" << endl;
+//
+// To switch off ANSI support call: SetNoColors()
+//
+// gLog is a global stream defined like cout or cerr
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MLog.h"
+
+#include <stdlib.h>     // mkstemp
+
+#include <fstream>
+#include <iomanip>
+
+#include <TROOT.h>      // gROOT->GetListOfCleanups()
+
+#ifdef _REENTRANT
+#include <TMutex.h>
+#endif
+#include <TGTextView.h>
+
+#include "MArgs.h"
+#include "MParContainer.h"
+
+#include "MLogHtml.h"
+
+ClassImp(MLog);
+
+using namespace std;
+
+#undef DEBUG
+//#define DEBUG
+
+
+// root 3.02:
+// check for TObjectWarning, TObject::Info, gErrorIgnoreLevel
+
+const char MLog::kESC = '\033'; // (char)27
+const char *const MLog::kEsc       = "\033[";
+const char *const MLog::kReset     = "\033[0m";
+const char *const MLog::kRed       = "\033[31m";
+const char *const MLog::kGreen     = "\033[32m";
+#ifdef HAVE_DARKBACKGROUND
+const char *const MLog::kYellow    = "\033[33m\033[1m";
+#else
+const char *const MLog::kYellow    = "\033[33m";
+#endif
+const char *const MLog::kBlue      = "\033[34m";
+const char *const MLog::kUnderline = "\033[4m";;
+const char *const MLog::kBlink     = "\033[5m";;
+const char *const MLog::kBright    = "\033[1m";;
+const char *const MLog::kDark      = "\033[2m";;
+
+//
+// This is the definition of the global log facility
+//
+MLog gLog;
+
+// --------------------------------------------------------------------------
+//
+// this strange usage of an unbufferd buffer is a workaround
+// to make it work on Alpha and Linux!
+//
+void MLog::Init()
+{
+
+    //
+    // Creat drawing semaphore
+    //
+#ifdef _REENTRANT
+    fMuxGui    = new TMutex;
+    fMuxStream = new TMutex;
+#endif
+
+    fPlugins = new TList;
+    gROOT->GetListOfCleanups()->Add(fPlugins);
+    fPlugins->SetBit(kMustCleanup);
+
+    setp(&fBuffer, &fBuffer+1);
+    *this << '\0';
+}
+
+// --------------------------------------------------------------------------
+//
+// default constructor which initializes the streamer and sets the device
+// which is used for the output (i)
+//
+MLog::MLog(int i) : ostream(this), fPPtr(fBase), fEPtr(fBase+bsz), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(i), fIsNull(kFALSE), fOut(NULL), fOutAllocated(kFALSE), fGui(NULL), fNumLines(0)
+{
+    Init();
+}
+
+// --------------------------------------------------------------------------
+//
+// default constructor which initializes the streamer and sets the given
+// ofstream as the default output device
+//
+MLog::MLog(ofstream &out) : ostream(this), fPPtr(fBase), fEPtr(fBase+bsz), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eFile), fIsNull(kFALSE), fOut(&out), fOutAllocated(kFALSE), fGui(NULL), fNumLines(0)
+{
+    Init();
+}
+
+// --------------------------------------------------------------------------
+//
+// default constructor which initializes the streamer and sets the given
+// TGTextView as the default output device
+//
+MLog::MLog(TGTextView &out) : ostream(this), fPPtr(fBase), fEPtr(fBase+bsz), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eGui), fOut(NULL), fOutAllocated(kFALSE), fGui(&out), fNumLines(0)
+{
+    Init();
+}
+
+// --------------------------------------------------------------------------
+//
+// default constructor which initializes the streamer and opens a file with
+// the given name. Dependend on the flag the file is set as output device
+// or not.
+//
+MLog::MLog(const char *fname, int flag) : ostream(this), fPPtr(fBase), fEPtr(fBase+bsz), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eFile), fIsNull(kFALSE), fGui(NULL), fNumLines(0)
+{
+    Init();
+
+    AllocateFile(fname);
+    CheckFlag(eFile, flag);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor, destroying the gui mutex.
+//
+MLog::~MLog()
+{
+    DeallocateFile();
+
+#ifdef DEBUG
+    TIter Next(fPlugins);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        cout << "Delete: " << o->GetName() << std::flush;
+        cout << " [" << o->ClassName() << "]" << endl;
+        delete o;
+    }
+
+    cout << "Delete: fPlugins " << fPlugins << "..." << std::flush;
+#endif
+
+    delete fPlugins;
+#ifdef DEBUG
+    cout << "done." << endl;
+#endif
+
+#ifdef _REENTRANT
+    delete fMuxStream;
+    delete fMuxGui;
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// copyt constructor
+//
+/*
+MLog::MLog(MLog const& log)
+{
+//    fOutputLevel = log.fOutputLevel;
+//    fDebugLevel  = log.fDebugLevel;
+//    fDevice      = log.fDevice;
+}
+*/
+
+void MLog::Underline()
+{
+    SetBit(kIsUnderlined);
+
+    fPlugins->ForEach(MLogPlugin, Underline)();
+
+    if (TestBit(eNoColors))
+        return;
+
+    if (fDevice&eStdout)
+        cout << kUnderline;
+
+    if (fDevice&eStderr)
+        cerr << kUnderline;
+}
+
+void MLog::Output(ostream &out, int len)
+{
+    if (!TestBit(eNoColors))
+        switch (fOutputLevel)
+        {
+            // do not output reset. Otherwise we reset underline in 0-mode
+            // case 1: out << MLog::kReset; break; // all
+        case 0:  break; // all = background color
+        case 1:  out << MLog::kRed;     break;  // err
+        case 2:  out << MLog::kYellow;  break;  // warn
+        case 3:  out << MLog::kGreen;   break;  // inf
+        default: out << MLog::kBlue;    break;  // all others (dbg)
+        }
+
+    if (len>0)
+    {
+        // Check for EOL
+        const Int_t endline = fBase[len-1]=='\n' ? 1 : 0;
+        // output text to screen (without trailing '\n')
+        out << TString(fBase, len-endline);
+        // reset colors if working with colors
+        if (!TestBit(eNoColors))
+            out << kReset;
+        // output EOL of check found EOL
+        if (endline)
+        {
+            out << '\n';
+            // Check whether text was underlined
+            if (TestBit(kIsUnderlined) && TestBit(eNoColors))
+            {
+                out << setw(len-1) << setfill('-') << "" << "\n";
+                ResetBit(kIsUnderlined);
+            }
+        }
+    }
+    out.flush();
+}
+
+void MLog::AddGuiLine(const TString &line)
+{
+    // add a new TString* to the array of gui lines
+    TString **newstr = new TString*[fNumLines+1];
+    memcpy(newstr, fGuiLines, fNumLines*sizeof(TString*));
+    if (fNumLines>0)
+        delete fGuiLines;
+    fGuiLines = newstr;
+
+    // add Gui line as last line of array
+    fGuiLines[fNumLines++] = new TString(line);
+}
+
+// --------------------------------------------------------------------------
+//
+// This is the function which writes the stream physically to a device.
+// If you want to add a new device this must be done here.
+//
+void MLog::WriteBuffer()
+{
+    //
+    // restart writing to the buffer at its first char
+    //
+    const int len = fPPtr - fBase;
+
+    fPPtr = fBase;
+
+    if (fIsNull)
+        return;
+
+    if (fDevice&eStdout)
+        Output(cout, len);
+
+    if (fDevice&eStderr)
+        Output(cerr, len);
+
+    if (fDevice&eFile && fOut)
+        fOut->write(fBase, len);
+
+    fPlugins->ForEach(MLogPlugin, SetColor)(fOutputLevel);
+    fPlugins->ForEach(MLogPlugin, WriteBuffer)(fBase, len);
+
+    if (fDevice&eGui && fGui)
+    {
+        // check whether the current text was flushed or endl'ed
+        const Int_t endline = fBase[len-1]=='\n' ? 1 : 0;
+
+        // for the gui remove trailing characters ('\n' or '\0')
+        fBase[len-endline]='\0';
+
+        // add new text to line storage
+        fGuiLine += fBase;
+
+        if (endline)
+        {
+            AddGuiLine(fGuiLine);
+            fGuiLine = "";
+
+            // Check whether text should be underlined
+            if (endline && TestBit(kIsUnderlined))
+            {
+                AddGuiLine("");
+                fGuiLines[fNumLines-1]->Append('-', fGuiLines[fNumLines-2]->Length());
+                ResetBit(kIsUnderlined);
+            }
+        }
+    }
+}
+
+void MLog::UpdateGui()
+{
+    if (fNumLines==0)
+        return;
+
+    // lock mutex
+    if (!LockUpdate("UpdateGui"))
+    {
+        Warning("UpdateGui", "Execution skipped");
+        return;
+    }
+
+    TGText &txt=*fGui->GetText();
+
+    // copy lines to TGListBox
+    for (int i=0; i<fNumLines; i++)
+    {
+        // Replace all tabs by 7 white spaces
+        fGuiLines[i]->ReplaceAll("\t", "       ");
+        txt.InsText(TGLongPosition(0, txt.RowCount()), *fGuiLines[i]);
+        delete fGuiLines[i];
+    }
+    delete fGuiLines;
+
+    fNumLines=0;
+
+    // cut text box top 1000 lines
+    //    while (txt.RowCount()>1000)
+    //        txt.DelLine(1);
+
+    // show last entry
+    fGui->Layout();
+    fGui->SetVsbPosition(txt.RowCount()-1);
+
+    // tell a main loop, that list box contents have changed
+    fGui->SetBit(kHasChanged);
+
+    // release mutex
+    UnLockUpdate("UpdateGui");
+}
+
+bool MLog::LockUpdate(const char *msg)
+{
+#ifdef _REENTRANT
+    if (fMuxGui->Lock()==13)
+    {
+        Info("LockUpdate", "%s - mutex is already locked by this thread\n", msg);
+        return false;
+    }
+#endif
+    return true;
+}
+
+bool MLog::UnLockUpdate(const char *msg)
+{
+#ifdef _REENTRANT
+    if (fMuxGui->UnLock()==13)
+    {
+        Info("UnLockUpdate", "%s - tried to unlock mutex locked by other thread\n", msg);
+        return false;
+    }
+#endif
+    return true;
+}
+
+bool MLog::Lock(const char *msg)
+{
+#ifdef _REENTRANT
+    if (fMuxStream->Lock()==13)
+    {
+        Error("Lock", "%s - mutex is already locked by this thread\n", msg);
+        return false;
+    }
+//    while (fMuxStream->Lock()==13)
+//        usleep(1);
+//    {
+//        Error("Lock", "%s - mutex is already locked by this thread\n", msg);
+//        return false;
+//    }
+#endif
+    return true;
+}
+
+bool MLog::UnLock(const char *msg)
+{
+#ifdef _REENTRANT
+    if (fMuxStream->UnLock()==13)
+    {
+        Error("UnLock", "%s - tried to unlock mutex locked by other thread\n", msg);
+        return false;
+    }
+#endif
+    return true;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is called to flush the buffer of the streaming devices
+//
+int MLog::sync()
+{
+    if (!LockUpdate("sync"))
+        usleep(1);
+    WriteBuffer();
+    UnLockUpdate("sync");
+
+    if (fDevice&eStdout)
+    {
+        if (!TestBit(eNoColors))
+            cout << kReset;
+        cout.flush();
+    }
+
+    if (fDevice&eStderr)
+        cerr.flush();
+
+    if (fDevice&eFile && fOut)
+        fOut->flush();
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function comes from streambuf and should
+// output the buffer to the device (flush, endl)
+// or handle a buffer overflow (too many chars)
+// If a real overflow happens i contains the next
+// chars which doesn't fit into the buffer anymore.
+// If the buffer is not really filled i is EOF(-1).
+//
+int MLog::overflow(int i) // i=EOF means not a real overflow
+{
+    //
+    // no output if
+    //
+    if (fOutputLevel <= fDebugLevel)
+    {
+        if (!LockUpdate("overflow"))
+            usleep(1);
+
+        *fPPtr++ = (char)i;
+
+        if (fPPtr == fEPtr)
+            WriteBuffer();
+
+        UnLockUpdate("overflow");
+    }
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print usage information setup in Setup()
+//
+void MLog::Usage()
+{
+    //                 1         2         3         4         5         6         7         8
+    //        12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    *this << "   -v#                       Verbosity level # [default=2]" << endl;
+    *this << "   -a, --no-colors           Do not use Ansii color codes" << endl;
+    *this << "   --log[=file]              Write log-out to ascii-file [default: prgname.log]" << endl;
+    *this << "   --html[=file]             Write log-out to html-file [default: prgname.html]" << endl;
+    *this << "   --debug[=n]               Enable root debugging [default: gDebug=1]" << endl;
+    *this << "   --null                    Null output (supresses all output)" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup MLog and global debug output from command line arguments.
+//
+void MLog::Setup(MArgs &arg)
+{
+    // FXIME: This is not really at a place where it belongs to!
+    gDebug = arg.HasOption("--debug=") ? arg.GetIntAndRemove("--debug=") : 0;
+    if (gDebug==0 && arg.HasOnlyAndRemove("--debug"))
+        gDebug=1;
+
+    TString f1 = arg.GetStringAndRemove("--log=", "");
+    if (f1.IsNull() && arg.HasOnlyAndRemove("--log"))
+        f1 = Form("%s.log", arg.GetName());
+    if (!f1.IsNull())
+    {
+        SetOutputFile(f1);
+        EnableOutputDevice(eFile);
+    }
+
+    TString f2 = arg.GetStringAndRemove("--html=", "");
+    if (f2.IsNull() && arg.HasOnlyAndRemove("--html"))
+        f2 = Form("%s.html", arg.GetName());
+    if (!f2.IsNull())
+    {
+        MLogHtml *html = new MLogHtml(f2);
+        html->SetBit(kCanDelete);
+        AddPlugin(html);
+    }
+
+    const Bool_t null = arg.HasOnlyAndRemove("--null");
+    if (null)
+        SetNullOutput();
+
+    if (arg.HasOnlyAndRemove("--no-colors") || arg.HasOnlyAndRemove("-a"))
+        SetNoColors();
+
+    SetDebugLevel(arg.GetIntAndRemove("-v", 2));
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv:
+//   MLog.VerbosityLevel: 0, 1, 2, 3, 4
+//   MLog.DebugLevel: 0, 1, 2, 3, 4
+//   MLog.NoColors
+//
+// Depending on your setup it might be correct to use something like:
+//   Job1.MLog.VerbosityLevel: 1
+//   Job1.DebugLevel: 2
+//   Job1.MLog.NoColors
+//
+void MLog::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    MParContainer mlog("MLog");
+
+    if (mlog.IsEnvDefined(env, prefix+"MLog", "VerbosityLevel", print))
+        SetDebugLevel(mlog.GetEnvValue(env, prefix+"MLog", "VerbosityLevel", 2));
+    else
+        if (mlog.IsEnvDefined(env, "MLog", "VerbosityLevel", print))
+            SetDebugLevel(mlog.GetEnvValue(env, "MLog", "VerbosityLevel", 2));
+
+    if (mlog.IsEnvDefined(env, prefix+"MLog", "DebugLevel", print))
+        gDebug = mlog.GetEnvValue(env, prefix+"MLog", "DebugLevel", 0);
+    else
+        if (mlog.IsEnvDefined(env, "MLog", "DebugLevel", print))
+            gDebug = mlog.GetEnvValue(env, "MLog", "DebugLevel", 0);
+
+    if (mlog.IsEnvDefined(env, prefix+"MLog", "NoColors", print))
+        SetNoColors(mlog.GetEnvValue(env, prefix+"MLog", "NoColors", kFALSE));
+    else
+        if (mlog.IsEnvDefined(env, "MLog", "NoColors", print))
+            SetNoColors(mlog.GetEnvValue(env, "MLog", "NoColors", kFALSE));
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv:
+//   MLog.VerbosityLevel: 0, 1, 2, 3, 4
+//   MLog.DebugLevel: 0, 1, 2, 3, 4
+//   MLog.NoColors
+//
+// Depending on your setup it might be correct to use something like:
+//   Job1.MLog.VerbosityLevel: 1
+//   Job1.DebugLevel: 2
+//   Job1.MLog.NoColors
+//
+void MLog::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    if (!prefix.IsNull())
+        prefix += ".";
+    prefix += "MLog";
+
+    cout << "MLog::WriteEnv: not yet implemented!" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Create a new instance of an file output stream
+// an set the corresponding flag
+//
+void MLog::AllocateFile(const char *fname)
+{
+    // gcc 3.2:
+    char *txt = (char*)"logXXXXXX";
+
+    TString n(fname ? fname : txt);
+    gSystem->ExpandPathName(n);
+    fOut = new ofstream(n.Data());
+    fOutAllocated = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// if fout was allocated by this instance of MLooging
+// delete it.
+//
+void MLog::DeallocateFile()
+{
+    if (fOutAllocated)
+        delete fOut;
+}
+
+// --------------------------------------------------------------------------
+//
+// if necessary delete the old in stance of the file
+// output stream and create a new one
+//
+void MLog::ReallocateFile(const char *fname)
+{
+    DeallocateFile();
+    AllocateFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// This function checks if a device should get enabled or disabled.
+//
+void MLog::CheckFlag(Flags_t chk, int flag)
+{
+    if (flag==-1)
+        return;
+
+    flag ? EnableOutputDevice(chk) : DisableOutputDevice(chk);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a plugin to which the output should be redirected, eg. MLogHtml
+// The user has to take care of its deletion. If the plugin is deleted
+// (and the kMustCleanup bit was not reset accidentaly) the plugin
+// is automatically removed from the list of active plugins.
+//
+// If MLog should take the ownership call plug->SetBit(kCanDelete);
+//
+void MLog::AddPlugin(MLogPlugin *plug)
+{
+    fPlugins->Add(plug);
+
+    // Make sure that it is recursively deleted from all objects in ListOfCleanups
+    plug->SetBit(kMustCleanup);
+}
Index: /tags/Mars-V0.9/mbase/MLog.h
===================================================================
--- /tags/Mars-V0.9/mbase/MLog.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLog.h	(revision 9772)
@@ -0,0 +1,226 @@
+#ifndef MARS_MLog
+#define MARS_MLog
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#include <TSystem.h>
+
+#include <iostream>  // base classes for MLog
+
+#define bsz    160 // two standard lines
+
+class MArgs;
+
+class TEnv;
+class TMutex;
+class TGTextView;
+
+class MLogPlugin;
+
+class MLog : public std::streambuf, public std::ostream, public TObject
+{
+public:
+    typedef enum _flags {
+        eStdout   = 0x001,
+        eStderr   = 0x002,
+        eFile     = 0x004,
+        eGui      = 0x008,
+        eNoColors = 0x400  //BIT(15)
+    } Flags_t;
+
+    enum ELogBits {
+        kHasChanged = BIT(14)  // if gui has changed
+    };
+
+private:
+    enum {
+        kIsUnderlined = BIT(15)
+    };
+    static const char kESC;
+    static const char *const kEsc;
+    static const char *const kReset;
+    static const char *const kRed;
+    static const char *const kGreen;
+    static const char *const kYellow;
+    static const char *const kBlue;
+    static const char *const kUnderline;
+    static const char *const kBlink;
+    static const char *const kBright;
+    static const char *const kDark;
+
+    char        fBuffer;      //!
+    char        fBase[bsz+1]; //! Buffer to store the data in
+    char       *fPPtr;        //! Pointer to present position in buffer
+    const char *fEPtr;        //! Pointer to end of buffer
+
+    UInt_t fOutputLevel;      //! Present output level of the stream
+    UInt_t fDebugLevel;       //! Present global debug level
+    UInt_t fDevice;           //! Flag to indicate the present streams
+
+    Bool_t fIsNull;           //! Switch output completely off
+
+    ofstream   *fOut;          //! possible file output stream
+    Bool_t      fOutAllocated; //! flag if fout is created by MLogging
+    TGTextView *fGui;          //! Text View output
+
+    Bool_t     fIsDirectGui;  //! Pipe text directly to the GUI (for single threaded environments)
+    TString  **fGuiLines;     //! Lines to pipe to gui
+    Int_t      fNumLines;     //!
+    TString    fGuiLine;      //!
+
+#ifdef _REENTRANT
+    TMutex *fMuxGui;          //! Mutex locking access of TGListBox
+    TMutex *fMuxStream;       //! Mutex locking access to streaming
+#endif
+
+    TList *fPlugins;
+
+    void Init();
+
+    void WriteBuffer();
+    int sync();
+    int overflow(int i); // i=EOF means not a real overflow
+
+    void AllocateFile(const char *f);
+    void DeallocateFile();
+    void ReallocateFile(const char *f);
+    void CheckFlag(Flags_t chk, int flag);
+    void Output(ostream &out, int len);
+    void AddGuiLine(const TString& line);
+
+public:
+    MLog(int i=eStdout);
+    MLog(ofstream &out);
+    MLog(TGTextView &out);
+    MLog(const char *fname, int flag=-1);
+
+    MLog(MLog const& log) : ostream((std::streambuf*)&log)
+    {
+        fOutputLevel = log.fOutputLevel;
+        fDebugLevel  = log.fDebugLevel;
+        fDevice      = log.fDevice;
+    }
+    ~MLog();
+
+    bool LockUpdate(const char *msg);
+    bool UnLockUpdate(const char *msg);
+
+    bool Lock(const char *msg="");
+    bool UnLock(const char *msg="");
+
+    void EnableDirectGui()  { fIsDirectGui = kTRUE; }
+    void DisableDirectGui() { fIsDirectGui = kFALSE; }
+    void UpdateGui();
+
+    void Underline();
+
+    void SetDebugLevel(int i)           { fDebugLevel  =  i;  }
+    int  GetDebugLevel() const          { return fDebugLevel; }
+    void SetOutputLevel(int i)          { fOutputLevel =  i;  }
+    void SetOutputDevice(int i)         { fDevice      =  i;  }
+    void EnableOutputDevice(Flags_t f)  { fDevice     |=  f;  }
+    void DisableOutputDevice(Flags_t f) { fDevice     &= ~f;  }
+    void operator=(ofstream &out)       { SetOutputFile(out); }
+    void operator=(TGTextView *out)     { SetOutputGui(out);  }
+
+    Bool_t IsOutputDeviceEnabled(int i) const { return fDevice & i; }
+
+    void SetOutputGui(TGTextView *out, int flag=-1)
+    {
+        fGui = out;
+        CheckFlag(eGui, flag);
+    }
+
+    void SetOutputFile(ofstream &out, int flag=-1)
+    {
+        //
+        // Set new output file by a given stream. The new output
+        // file is not deleted automatically. If no flag is specified
+        // the state of the file-device stream is unchanged.
+        // if the a flag is specified the state is changed
+        // in correspondance to the flag
+        //
+        DeallocateFile();
+        fOut = &out;
+        CheckFlag(eFile, flag);
+    }
+
+    void SetOutputFile(const char *f=NULL, int flag=-1)
+    {
+        //
+        // Set new output file by name. The new output file must
+        // not be deleted by the user. If no flag is specified
+        // the state of the file-device stream is unchanged.
+        // if the a flag is specified the state is changed
+        // in correspondance to the flag
+        //
+        ReallocateFile(f);
+        CheckFlag(eFile, flag);
+    }
+
+    ofstream &GetOutputFile()
+    {
+        //
+        // Get the file output stream from MLogging
+        // if no file output stream is existing yet it will be created.
+        // For the creating a C-Temporary file name is used.
+        // if the stream is created here the user must not delete it
+        //
+        // What a pitty, but it seems, that there is now way to ask
+        // an ofstream for the corresponding file name. Elsewhise
+        // I would implement a GetFileName-function, too.
+        //
+        if (!fOut)
+            ReallocateFile(NULL);
+        return *fOut;
+    }
+
+    // FIXME: Switch off colors when on....
+    void SetNullOutput(Bool_t n=kTRUE) { fIsNull = n; }
+
+    void SetNoColors(Bool_t flag=kTRUE) { flag ? SetBit(eNoColors) : ResetBit(eNoColors); }
+
+    void Setup(MArgs &arg);
+    void Usage();
+
+    void ReadEnv(const TEnv &env, TString prefix="", Bool_t print=kFALSE);
+    void WriteEnv(TEnv &env, TString prefix="", Bool_t print=kFALSE) const;
+
+    MLog &Separator(TString str="", int outlvl=0)
+    {
+        if (!str.IsNull())
+        {
+            const Int_t l = (78-str.Length())/2-3;
+            str.Prepend("={ ");
+            str.Prepend('-', l);
+            str.Append(" }=");
+            str.Append('-', l);
+        }
+        if (str.Length()<78)
+            str.Append('-', 78-str.Length());
+
+        const int save = fOutputLevel;
+        SetOutputLevel(outlvl);
+        (*this) << str << std::endl;
+        fOutputLevel = save;
+
+        return *this;
+    }
+
+    void AddPlugin(MLogPlugin *plug);
+
+    ClassDef(MLog, 0) // This is what we call 'The logging system'
+};
+
+//
+// This is the definition of a global output stream, which by
+// default pipes all output to the stdout
+//
+R__EXTERN MLog gLog;
+
+#endif
Index: /tags/Mars-V0.9/mbase/MLogHtml.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MLogHtml.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLogHtml.cc	(revision 9772)
@@ -0,0 +1,129 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MLogHtml
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MLogHtml.h"
+
+#include <fstream>  // ofstream
+#include <iostream> // cout
+
+#include "MTime.h"
+
+ClassImp(MLogHtml);
+
+using namespace std;
+
+MLogHtml::MLogHtml(const char *name) : fUnderline(0), fColor(-1)
+{
+    fOut = new ofstream(name);
+    if (!*fOut)
+    {
+        delete fOut;
+        fOut = NULL;
+
+        cerr << "Cannot open file " << name << ": " << strerror(errno) << endl;
+        return;
+    }
+
+    MTime time;
+    time.Now();
+
+    *fOut << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" << endl;
+    *fOut << endl;
+    *fOut << "<html>" << endl;
+    *fOut << "<head>" << endl;
+    *fOut << "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">" << endl;
+    *fOut << "    <meta name=\"Author\" content=\"Mars-MLogHtml" << MARSVER << "\">" << endl;
+    *fOut << "    <title>MARS - Logging, created " << time << "</title>" << endl;
+    *fOut << "</head>" << endl;
+    *fOut << endl;
+    *fOut << "<pre>" << endl;
+    //*fOut << "<body background=\"background.gif" text="#000000" bgcolor="#000099" link="#1122FF" vlink="#8888FF" alink="#FF0000">
+}
+
+MLogHtml::~MLogHtml()
+{
+    if (!fOut)
+        return;
+
+    *fOut << "</font>" << endl;
+    *fOut << "</pre>" << endl;
+    *fOut << endl;
+    *fOut << "</html>" << endl;
+
+    delete fOut;
+}
+
+void MLogHtml::Underline()
+{
+    if (!fOut)
+        return;
+
+    *fOut << "<u>";
+    fUnderline = kTRUE;
+}
+
+void MLogHtml::SetColor(Int_t col)
+{
+    if (!fOut)
+        return;
+
+    if (fColor>0 && fColor!=col)
+        *fOut << "</font>";
+
+    if (fColor==col)
+        return;
+
+    switch (col)
+    {
+    case 0:  break;
+    case 1:  *fOut << "<font color=#aa0000>"; break;  // err
+    case 2:  *fOut << "<font color=#00aaaa>"; break;  // warn
+    case 3:  *fOut << "<font color=#00aa00>"; break;  // inf
+    default: *fOut << "<font color=#0000aa>"; break;  // all others (dbg)
+    }
+
+    fColor=col;
+}
+
+void MLogHtml::WriteBuffer(const char *str, int len)
+{
+    if (!fOut)
+    {
+        cout.write(str, len);
+        return;
+    }
+
+    fOut->write(str, len);
+    if (fUnderline)
+    {
+        *fOut << "</u>";
+        fUnderline = kFALSE;
+    }
+}
Index: /tags/Mars-V0.9/mbase/MLogHtml.h
===================================================================
--- /tags/Mars-V0.9/mbase/MLogHtml.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLogHtml.h	(revision 9772)
@@ -0,0 +1,33 @@
+#ifndef MARS_MLogHtml
+#define MARS_MLogHtml
+
+#ifndef MARS_MLogPlugin
+#include "MLogPlugin.h"
+#endif
+
+class MLogHtml : public MLogPlugin
+{
+private:
+    ofstream *fOut;
+
+    Bool_t fUnderline;
+    Int_t  fColor;
+
+    enum { kFontOpen=BIT(15) };
+
+public:
+    MLogHtml(const char *name);
+    MLogHtml() : fOut(0)
+    {
+    }
+
+    ~MLogHtml();
+
+    void Underline();
+    void SetColor(int col);
+    void WriteBuffer(const char *str, int len);
+
+    ClassDef(MLogHtml, 0) // Logger Plugin for HTML
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MLogManip.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MLogManip.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLogManip.cc	(revision 9772)
@@ -0,0 +1,126 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+#include "MLog.h"
+#include "MLogManip.h"
+/*
+// ----------------------------------------------------------------
+//            Definitions of the manipulator functions
+// ----------------------------------------------------------------
+
+ostream& __omanip_debug(ostream& lout, int i)
+{
+    //
+    // get the streambuf of the stream
+    // get the pointer to the parent class by casting
+    // set the output level of the logging stream
+    //
+    // Be careful: This manipulator can only be used in MLogging
+    // streams - in other streams SetOutputLevel is a call
+    // of a non existing function
+    //
+    // Be careful 2: The change is valid for everything which is
+    // in the present buffer. This means it can also affect a
+    // part of the stream which is already in the stream but not flushed
+    // to the output device. A flush occures either if you tell a stream
+    // to flush (flush, endl) or if an buffer overflow occures, the
+    // last behaviour could be changed if someone want to have a dynamic
+    // buffer.
+    //
+    MLog *log=(MLog*)lout.rdbuf();
+    log->SetOutputLevel(i);
+    return lout;
+}
+
+ostream& __omanip_device(ostream& lout, int i)
+{
+    //
+    // get the streambuf of the stream
+    // get the pointer to the parent class by casting
+    // set the output device of the logging stream, more than
+    // one output device can be ored together
+    //
+    // Be careful: This manipulator can only be used in MLogging
+    // streams - in other streams SetOutputLevel is a call
+    // of a non existing function
+    //
+    MLog *log=(MLog*)lout.rdbuf();
+    log->SetOutputDevice(i);
+    return lout;
+}
+
+ostream& __omanip_edev(ostream& lout, int i)
+{
+    //
+    // get the streambuf of the stream
+    // get the pointer to the parent class by casting
+    // Enable an output device of the logging stream, it should
+    // be possible to enable more than one output device at the
+    // same time by oring them together
+    //
+    // Be careful: This manipulator can only be used in MLogging
+    // streams - in other streams SetOutputLevel is a call
+    // of a non existing function
+    //
+    MLog *log=(MLog*)lout.rdbuf();
+    log->EnableOutputDevice((MLog::_flags)i);
+    return lout;
+}
+
+ostream& __omanip_ddev(ostream& lout, int i)
+{
+    //
+    // get the streambuf of the stream
+    // get the pointer to the parent class by casting
+    // Disable an output device of the logging stream, it should
+    // be possible to disable more than one output device at the
+    // same time by oring them together
+    //
+    // Be careful: This manipulator can only be used in MLogging
+    // streams - in other streams SetOutputLevel is a call
+    // of a non existing function
+    //
+    MLog *log=(MLog*)lout.rdbuf();
+    log->DisableOutputDevice((MLog::_flags)i);
+    return lout;
+}
+
+ostream& underline(ostream& lout)
+{
+    //
+    // get the streambuf of the stream
+    // get the pointer to the parent class by casting
+    // Disable an output device of the logging stream, it should
+    // be possible to disable more than one output device at the
+    // same time by oring them together
+    //
+    // Be careful: This manipulator can only be used in MLogging
+    // streams - in other streams SetOutputLevel is a call
+    // of a non existing function
+    //
+    MLog *log=(MLog*)lout.rdbuf();
+    log->Underline();
+    return lout;
+}
+*/
Index: /tags/Mars-V0.9/mbase/MLogManip.h
===================================================================
--- /tags/Mars-V0.9/mbase/MLogManip.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLogManip.h	(revision 9772)
@@ -0,0 +1,92 @@
+#ifndef MARS_MLogManip
+#define MARS_MLogManip
+
+#include <iomanip>
+
+#include "MLog.h"
+
+// --------------------- simple manipulators -----------------------
+
+enum MLogManip {
+    underline
+};
+
+inline std::ostream &operator<<(std::ostream &lout, MLogManip u)
+{
+    MLog *log=dynamic_cast<MLog*>(lout.rdbuf());
+    if (log)
+        log->Underline();
+    return lout;
+}
+
+
+// ----------------------------- debug -----------------------------
+
+struct _Debug { int level; };
+
+const _Debug all  = { 0 }; // use this for output in any case
+const _Debug err  = { 1 }; // use this for fatal errors (red)
+const _Debug warn = { 2 }; // use this for wrnings (yellow)
+const _Debug inf  = { 3 }; // use this for informations (green)
+const _Debug dbg  = { 4 }; // use this for debug messages (blue)
+
+inline _Debug debug(int level)
+{
+    _Debug d;
+    d.level = level;
+    return d;
+}
+
+inline std::ostream &operator<<(std::ostream &lout, _Debug d)
+{
+    MLog *log=dynamic_cast<MLog*>(lout.rdbuf());
+    if (log)
+        log->SetOutputLevel(d.level);
+    return lout;
+}
+
+// ------------------------------- edev ----------------------------
+
+struct _EnableDev { MLog::_flags dev; };
+
+inline _EnableDev edev(MLog::_flags i)
+{
+    _EnableDev e;
+    e.dev = i;
+    return e;
+}
+
+inline std::ostream &operator<<(std::ostream &lout, _EnableDev e)
+{
+    MLog *log=dynamic_cast<MLog*>(lout.rdbuf());
+    if (log)
+        log->EnableOutputDevice(e.dev);
+    return lout;
+}
+
+// ------------------------------- sdev ----------------------------
+
+struct _DisableDev { MLog::_flags dev; };
+
+inline _DisableDev ddev(MLog::_flags i)
+{
+    _DisableDev d;
+    d.dev = i;
+    return d;
+}
+
+inline std::ostream &operator<<(std::ostream &lout, _DisableDev d)
+{
+    MLog *log=dynamic_cast<MLog*>(lout.rdbuf());
+    if (log)
+        log->EnableOutputDevice(d.dev);
+    return lout;
+}
+
+// ------------------------------ Macros ---------------------------
+
+#ifndef __CINT__
+#define dbginf __FILE__ << " l." << dec << __LINE__ << ": "
+#endif
+
+#endif
Index: /tags/Mars-V0.9/mbase/MLogPlugin.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MLogPlugin.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLogPlugin.cc	(revision 9772)
@@ -0,0 +1,35 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MLogPlugin
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MLogPlugin.h"
+
+ClassImp(MLogPlugin);
+
+using namespace std;
Index: /tags/Mars-V0.9/mbase/MLogPlugin.h
===================================================================
--- /tags/Mars-V0.9/mbase/MLogPlugin.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLogPlugin.h	(revision 9772)
@@ -0,0 +1,18 @@
+#ifndef MARS_MLogPlugin
+#define MARS_MLogPlugin
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+
+class MLogPlugin : public TObject
+{
+public:
+    virtual void SetColor(int col) { }
+    virtual void Underline() { }
+    virtual void WriteBuffer(const char *str, int len) = 0;
+
+    ClassDef(MLogPlugin, 0) // Base for a logger plugin
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MLogo.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MLogo.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLogo.cc	(revision 9772)
@@ -0,0 +1,209 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  05/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// MLogo                                                                    //
+//                                                                          //
+// X based logo displayer. Displays a given logo after a call to Popup()    //
+// until Popdown() or the destructor is called, but for a minimum of a      //
+// given number of milliseconds.                                            //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#ifdef HAVE_XPM
+#include "MLogo.h"
+
+#include <unistd.h>    // usleep
+#include <iostream.h>  // cout
+#include <sys/time.h>  // gettimeofday
+
+#ifndef XpmSuccess
+#define XpmSuccess       0
+#endif
+#ifndef XpmColorError
+#define XpmColorError    1
+#endif
+
+MLogo::MLogo(int millisec)
+   : fDisplay(0), fLogoWindow(0), fLogoPixmap(0), fMilliSec(millisec)
+{
+    // millisec: time of minimum stayup
+}
+
+void MLogo::Wait() const
+{
+    struct timeval tv;
+
+    gettimeofday(&tv, 0);
+
+    tv.tv_sec  -= fPopupTime.tv_sec;
+    tv.tv_usec -= fPopupTime.tv_usec;
+
+    while (tv.tv_usec < 0)
+    {
+        tv.tv_usec += 1000000;
+        tv.tv_sec--;
+    }
+
+    while (tv.tv_sec > 0)
+        tv.tv_usec += 1000000;
+
+    long sleep = fMilliSec*1000-tv.tv_usec;
+
+    if (sleep <= 0)
+        return;
+
+    usleep(sleep);
+}
+
+Pixmap MLogo::GetLogo() const
+{
+#ifdef XpmVersion
+    int depth = PlanesOfScreen(XDefaultScreenOfDisplay(fDisplay));
+
+    if (depth <= 1)
+        return 0;
+
+    XWindowAttributes win_attr;
+    XGetWindowAttributes(fDisplay, fLogoWindow, &win_attr);
+
+    XpmAttributes attr;
+    attr.valuemask = XpmVisual | XpmColormap | XpmDepth;
+    attr.visual    = win_attr.visual;
+    attr.colormap  = win_attr.colormap;
+    attr.depth     = win_attr.depth;
+
+#ifdef XpmColorKey              // Not available in XPM 3.2 and earlier
+
+    switch (depth)
+    {
+    case 0:
+        attr.valuemask &= ~XpmColorKey;
+        break;
+    case 1:
+        attr.color_key = XPM_MONO;
+        break;
+    case 2:
+        attr.color_key = XPM_GRAY;
+        break;
+    case 3:
+    case 4:
+        attr.color_key = XPM_GRAY4;
+        break;
+    default:
+        attr.color_key = XPM_COLOR;
+    }
+#endif // defined(XpmColorKey)
+
+
+    Pixmap logo;
+#ifdef USE_MAGICLOGO
+#include "../magiclogo.xpm"
+    int ret = XpmCreatePixmapFromData(fDisplay, fLogoWindow,
+                                      mag1, &logo, 0, &attr);
+#else
+#include "../marslogo.xpm"
+    int ret = XpmCreatePixmapFromData(fDisplay, fLogoWindow,
+                                      marslogo, &logo, 0, &attr);
+#endif
+    XpmFreeAttributes(&attr);
+
+    if (ret == XpmSuccess || ret == XpmColorError)
+        return logo;
+
+    if (logo)
+        XFreePixmap(fDisplay, logo);
+#endif
+    return 0;
+}
+
+void MLogo::Popup()
+{
+#ifdef XpmVersion
+    if (fLogoWindow || fLogoPixmap || fDisplay)
+#endif
+        return;
+
+    fDisplay = XOpenDisplay("");
+    if (!fDisplay)
+        return;
+
+    int screen = DefaultScreen(fDisplay);
+
+    fLogoWindow = XCreateSimpleWindow(fDisplay, DefaultRootWindow(fDisplay),
+                                      -100, -100, 50, 50, 0,
+                                      BlackPixel(fDisplay, screen),
+                                      WhitePixel(fDisplay, screen));
+    fLogoPixmap = GetLogo();
+
+    Window root;
+    int x, y;
+    unsigned int w, h, bw, depth;
+    XGetGeometry(fDisplay, fLogoPixmap,
+                 &root, &x, &y, &w, &h, &bw, &depth);
+
+    Screen *xscreen = XDefaultScreenOfDisplay(fDisplay);
+    x = (WidthOfScreen(xscreen) - w) / 2;
+    y = (HeightOfScreen(xscreen) - h) / 2;
+
+    XMoveResizeWindow(fDisplay, fLogoWindow, x, y, w, h);
+    XSync(fDisplay, False);   // make sure move & resize is done before mapping
+
+    unsigned long valmask  = CWBackPixmap | CWOverrideRedirect;
+
+    XSetWindowAttributes xswa;
+    xswa.background_pixmap = fLogoPixmap;
+    xswa.override_redirect = True;
+    XChangeWindowAttributes(fDisplay, fLogoWindow, valmask, &xswa);
+
+    XMapRaised(fDisplay, fLogoWindow);
+    XSync(fDisplay, False);
+
+    gettimeofday(&fPopupTime, 0);
+}
+
+void MLogo::Popdown()
+{
+    if (fLogoWindow && fLogoPixmap && fDisplay)
+        Wait();
+
+    if (fLogoWindow)
+    {
+        XUnmapWindow(fDisplay, fLogoWindow);
+        XDestroyWindow(fDisplay, fLogoWindow);
+        fLogoWindow = 0;
+    }
+    if (fLogoPixmap)
+    {
+        XFreePixmap(fDisplay, fLogoPixmap);
+        fLogoPixmap = 0;
+    }
+    if (fDisplay)
+    {
+        XSync(fDisplay, False);
+        XCloseDisplay(fDisplay);
+        fDisplay = 0;
+    }
+}
+#endif
Index: /tags/Mars-V0.9/mbase/MLogo.h
===================================================================
--- /tags/Mars-V0.9/mbase/MLogo.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MLogo.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MLogo
+#define MARS_MLogo
+
+#ifdef HAVE_XPM
+
+#ifndef __CINT__
+
+#include <X11/Xlib.h>
+
+#include "Xpm.h"
+
+class MLogo
+{
+    Display *fDisplay;         // display handle
+    Window   fLogoWindow;      // window handle
+    Pixmap   fLogoPixmap;      // pixmap handle
+    long     fMilliSec;        // stayup time
+
+    struct timeval fPopupTime; // time of popup
+
+    void   Wait() const;
+    Pixmap GetLogo() const;
+
+public:
+    MLogo(int millisec=777);
+    ~MLogo()
+    {
+        Popdown();
+    }
+
+    void Popup();
+    void Popdown();
+};
+
+#endif // __CINT__
+#endif // HAVE_XPM
+#endif // MARS_MLogo
Index: /tags/Mars-V0.9/mbase/MMath.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MMath.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MMath.cc	(revision 9772)
@@ -0,0 +1,222 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMath
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMath.h"
+
+// --------------------------------------------------------------------------
+//
+// Calculate Significance as
+// significance = (s-b)/sqrt(s+k*k*b) mit k=s/b
+//
+// s: total number of events in signal region
+// b: number of background events in signal region
+// 
+Double_t MMath::Significance(Double_t s, Double_t b)
+{
+    const Double_t k = b==0 ? 0 : s/b;
+    const Double_t f = s+k*k*b;
+
+    return f==0 ? 0 : (s-b)/TMath::Sqrt(f);
+}
+
+// --------------------------------------------------------------------------
+//
+// Symmetrized significance - this is somehow analog to
+// SignificanceLiMaSigned
+//
+// Returns Significance(s,b) if s>b otherwise -Significance(b, s);
+// 
+Double_t MMath::SignificanceSym(Double_t s, Double_t b)
+{
+    return s>b ? Significance(s, b) : -Significance(b, s);
+}
+
+// --------------------------------------------------------------------------
+//
+//  calculates the significance according to Li & Ma
+//  ApJ 272 (1983) 317, Formula 17
+//
+//  s                    // s: number of on events
+//  b                    // b: number of off events
+//  alpha = t_on/t_off;  // t: observation time
+//
+//  The significance has the same (positive!) value for s>b and b>s.
+//
+//  Returns -1 if sum<0 or alpha<0 or the argument of sqrt<0
+//  Returns  0 if s+b==0, s==0 or b==0
+//
+// Here is some eMail written by Daniel Mazin about the meaning of the arguments:
+//
+//  > Ok. Here is my understanding:
+//  > According to Li&Ma paper (correctly cited in MMath.cc) alpha is the
+//  > scaling factor. The mathematics behind the formula 17 (and/or 9) implies
+//  > exactly this. If you scale OFF to ON first (using time or using any other
+//  > method), then you cannot use formula 17 (9) anymore. You can just try
+//  > the formula before scaling (alpha!=1) and after scaling (alpha=1), you
+//  > will see the result will be different.
+//
+//  > Here are less mathematical arguments:
+//
+//  >  1) the better background determination you have (smaller alpha) the more
+//  > significant is your excess, thus your analysis is more sensitive. If you
+//  > normalize OFF to ON first, you loose this sensitivity.
+//
+//  >  2) the normalization OFF to ON has an error, which naturally depends on
+//  > the OFF and ON. This error is propagating to the significance of your
+//  > excess if you use the Li&Ma formula 17 correctly. But if you normalize
+//  > first and use then alpha=1, the error gets lost completely, you loose
+//  > somehow the criteria of goodness of the normalization.
+//
+Double_t MMath::SignificanceLiMa(Double_t s, Double_t b, Double_t alpha)
+{
+    const Double_t sum = s+b;
+
+    if (s==0 || b==0 || sum==0)
+        return 0;
+
+    if (sum<0 || alpha<=0)
+        return -1;
+
+    const Double_t l = s*TMath::Log(s/sum*(alpha+1)/alpha);
+    const Double_t m = b*TMath::Log(b/sum*(alpha+1)      );
+
+    return l+m<0 ? -1 : TMath::Sqrt((l+m)*2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates MMath::SignificanceLiMa(s, b, alpha). Returns 0 if the
+// calculation has failed. Otherwise the Li/Ma significance which was
+// calculated. If s<b a negative value is returned.
+//
+Double_t MMath::SignificanceLiMaSigned(Double_t s, Double_t b, Double_t alpha)
+{
+    const Double_t sig = SignificanceLiMa(s, b, alpha);
+    if (sig<=0)
+        return 0;
+
+    return TMath::Sign(sig, s-alpha*b);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns: 2/(sigma*sqrt(2))*integral[0,x](exp(-(x-mu)^2/(2*sigma^2)))
+//
+Double_t MMath::GaussProb(Double_t x, Double_t sigma, Double_t mean)
+{
+    static const Double_t sqrt2 = TMath::Sqrt(2.);
+    return TMath::Erf((x-mean)/(sigma*sqrt2));
+}
+
+// --------------------------------------------------------------------------
+//
+// This function reduces the precision to roughly 0.5% of a Float_t by
+// changing its bit-pattern (Be carefull, in rare cases this function must
+// be adapted to different machines!). This is usefull to enforce better
+// compression by eg. gzip.
+//
+void MMath::ReducePrecision(Float_t &val)
+{
+    UInt_t &f = (UInt_t&)val;
+
+    f += 0x00004000;
+    f &= 0xffff8000;
+}
+
+// -------------------------------------------------------------------------
+//
+// Quadratic interpolation
+//
+// calculate the parameters of a parabula such that
+//    y(i) = a + b*x(i) + c*x(i)^2
+//
+// If the determinant==0 an empty TVector3 is returned.
+//
+TVector3 MMath::GetParab(const TVector3 &x, const TVector3 &y)
+{
+    Double_t x1 = x(0);
+    Double_t x2 = x(1);
+    Double_t x3 = x(2);
+
+    Double_t y1 = y(0);
+    Double_t y2 = y(1);
+    Double_t y3 = y(2);
+
+    const double det =
+        + x2*x3*x3 + x1*x2*x2 + x3*x1*x1
+        - x2*x1*x1 - x3*x2*x2 - x1*x3*x3;
+
+
+    if (det==0)
+        return TVector3();
+
+    const double det1 = 1.0/det;
+
+    const double ai11 = x2*x3*x3 - x3*x2*x2;
+    const double ai12 = x3*x1*x1 - x1*x3*x3;
+    const double ai13 = x1*x2*x2 - x2*x1*x1;
+
+    const double ai21 = x2*x2 - x3*x3;
+    const double ai22 = x3*x3 - x1*x1;
+    const double ai23 = x1*x1 - x2*x2;
+
+    const double ai31 = x3 - x2;
+    const double ai32 = x1 - x3;
+    const double ai33 = x2 - x1;
+
+    return TVector3((ai11*y1 + ai12*y2 + ai13*y3) * det1,
+                    (ai21*y1 + ai22*y2 + ai23*y3) * det1,
+                    (ai31*y1 + ai32*y2 + ai33*y3) * det1);
+}
+
+Double_t MMath::InterpolParabLin(const TVector3 &vx, const TVector3 &vy, Double_t x)
+{
+    const TVector3 c = GetParab(vx, vy);
+    return c(0) + c(1)*x + c(2)*x*x;
+}
+
+Double_t MMath::InterpolParabLog(const TVector3 &vx, const TVector3 &vy, Double_t x)
+{
+    const Double_t l0 = TMath::Log10(vx(0));
+    const Double_t l1 = TMath::Log10(vx(1));
+    const Double_t l2 = TMath::Log10(vx(2));
+
+    const TVector3 vx0(l0, l1, l2);
+    return InterpolParabLin(vx0, vy, TMath::Log10(x));
+}
+
+Double_t MMath::InterpolParabCos(const TVector3 &vx, const TVector3 &vy, Double_t x)
+{
+    const Double_t l0 = TMath::Cos(vx(0));
+    const Double_t l1 = TMath::Cos(vx(1));
+    const Double_t l2 = TMath::Cos(vx(2));
+
+    const TVector3 vx0(l0, l1, l2);
+    return InterpolParabLin(vx0, vy, TMath::Cos(x));
+}
Index: /tags/Mars-V0.9/mbase/MMath.h
===================================================================
--- /tags/Mars-V0.9/mbase/MMath.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MMath.h	(revision 9772)
@@ -0,0 +1,28 @@
+#ifndef MARS_MMath
+#define MARS_MMath
+
+#ifndef ROOT_TMath
+#include <TMath.h>
+#endif
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+namespace MMath
+{
+    Double_t GaussProb(Double_t x, Double_t sigma, Double_t mean=0);
+
+    Double_t Significance(Double_t s, Double_t b);
+    Double_t SignificanceSym(Double_t s, Double_t b);
+    Double_t SignificanceLiMa(Double_t s, Double_t b, Double_t alpha=1);
+    Double_t SignificanceLiMaSigned(Double_t s, Double_t b, Double_t alpha=1);
+
+    void ReducePrecision(Float_t &val);
+
+    TVector3 GetParab(const TVector3 &x, const TVector3 &y);
+    Double_t InterpolParabLin(const TVector3 &vx, const TVector3 &vy, Double_t x);
+    Double_t InterpolParabLog(const TVector3 &vx, const TVector3 &vy, Double_t x);
+    Double_t InterpolParabCos(const TVector3 &vx, const TVector3 &vy, Double_t x);
+}
+
+#endif
Index: /tags/Mars-V0.9/mbase/MParContainer.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MParContainer.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MParContainer.cc	(revision 9772)
@@ -0,0 +1,904 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MParContainer
+//
+// The MParContainer class is the base class for all MARS parameter
+// containers. At the moment it is almost the same than ROOT's TNamed.
+// A TNamed contains the essential elements (name, title)
+// to identify a derived object in lists like our MParList or MTaskList.
+// The main difference is that the name and title isn't stored and read
+// to and from root files ("//!")
+//
+// MParContainer has several enhancements compared to TNamed:
+//  - GetDescriptor():        returns name and class type
+//  - GetUniqueName():        returns a unique name (used in StreamPrimitive)
+//  - SetLogStream(MLog *lg): Set a logging stream to which loggingis stored
+//  - Reset():                Reset content of class in an eventloop
+//  - IsReadyToSave():        The contents are ready to be saved to a file
+//  - IsSavedAsPrimitive():   A unique name for this instance is already
+//                            existing
+//  - SetVariables():         Can be overloaded if the containers stores
+//                            coefficients (to be used in fits)
+//  - SetDisplay():           Set a display for redirecting graphical output
+//  - GetNames():             Get Name/Title from instance and store it in
+//                            a TObjArray (used to store the names of the
+//                            conteiners in a file
+//  - SetNames():             vice versa
+//  - ReadEnv(), WriteEnv():  Function which is used for automatical setup
+//    IsEnvDefined()          from a TEnv file
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MParContainer.h"
+
+#include <ctype.h>        // isdigit
+#include <fstream>        // ofstream
+
+#include <TEnv.h>         // Env::Lookup
+#include <TClass.h>       // IsA
+#include <TObjArray.h>    // TObjArray
+#include <TBaseClass.h>   // GetClassPointer
+#include <TMethodCall.h>  // TMethodCall, AsciiWrite
+#include <TDataMember.h>  // TDataMember, AsciiWrite
+#include <TVirtualPad.h>  // gPad
+
+#include "MString.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+TList *gListOfPrimitives; // forard declaration in MParContainer.h
+
+#undef DEBUG
+//#define DEBUG
+
+ClassImp(MParContainer);
+
+using namespace std;
+
+TObjArray MParContainer::fgListMethodCall;
+
+MParContainer::MParContainer(const char *name, const char *title) :
+    fName(name), fTitle(title), fLog(&gLog), fDisplay(NULL), fReadyToSave(kFALSE)
+{
+    fgListMethodCall.SetOwner();
+}
+
+MParContainer::MParContainer(const TString &name, const TString &title) :
+    fName(name), fTitle(title), fLog(&gLog), fDisplay(NULL), fReadyToSave(kFALSE)
+{
+    fgListMethodCall.SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+//  MParContainer copy ctor
+//
+MParContainer::MParContainer(const MParContainer &named)
+{
+    fName  = named.fName;
+    fTitle = named.fTitle;
+
+    fLog = named.fLog;
+
+    fReadyToSave = named.fReadyToSave;
+
+    fDisplay = named.fDisplay;
+}
+
+MParContainer::~MParContainer()
+{
+#ifdef DEBUG
+    if (fName.IsNull() || fName==(TString)"MTime")
+        return;
+
+    *fLog << all << "Deleting " << GetDescriptor() << endl;
+    if (TestBit(kMustCleanup) && gROOT && gROOT->MustClean())
+    {
+        *fLog << "Recursive Remove..." << flush;
+        if (TestBit(kCanDelete))
+            *fLog << "kCanDelete..." << flush;
+        TIter Next(gROOT->GetListOfCleanups());
+        TObject *o=0;
+        while ((o=Next()))
+            *fLog << dbg << o->GetName() << " [" << o->ClassName() << "]" << endl;
+        *fLog << dbg << "Removing..." << flush;
+        gROOT->GetListOfCleanups()->RecursiveRemove(this);
+        *fLog << "Removed." << endl;
+    }
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+//  MParContainer assignment operator.
+//
+MParContainer& MParContainer::operator=(const MParContainer& rhs)
+{
+    if (this == &rhs)
+        return *this;
+
+    TObject::operator=(rhs);
+
+    fName  = rhs.fName;
+    fTitle = rhs.fTitle;
+
+    fLog = rhs.fLog;
+    fReadyToSave = rhs.fReadyToSave;
+
+    return *this;
+}
+
+// --------------------------------------------------------------------------
+//
+// Make a clone of an object using the Streamer facility.
+// If newname is specified, this will be the name of the new object
+//
+TObject *MParContainer::Clone(const char *newname) const
+{
+
+   MParContainer *named = (MParContainer*)TObject::Clone();
+   if (newname && strlen(newname)) named->SetName(newname);
+   return named;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Compare two MParContainer objects. Returns 0 when equal, -1 when this is
+//  smaller and +1 when bigger (like strcmp).
+//
+Int_t MParContainer::Compare(const TObject *obj) const
+{
+    if (this == obj) return 0;
+    return fName.CompareTo(obj->GetName());
+}
+
+// --------------------------------------------------------------------------
+//
+//  Copy this to obj.
+//
+void MParContainer::Copy(TObject &obj)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+const
+#endif
+{
+    MParContainer &cont = (MParContainer&)obj;
+
+    TObject::Copy(obj);
+
+    cont.fName  = fName;
+    cont.fTitle = fTitle;
+
+    cont.fLog = fLog;
+    cont.fReadyToSave = fReadyToSave;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Encode MParContainer into output buffer.
+//
+void MParContainer::FillBuffer(char *&buffer)
+{
+    fName.FillBuffer(buffer);
+    fTitle.FillBuffer(buffer);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the name of the object. If the name of the object is not the
+// class name it returns the object name and in []-brackets the class name.
+//
+const TString MParContainer::GetDescriptor() const
+{
+    return GetDescriptor(*this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the name of the object. If the name of the object is not the
+// class name it returns the object name and in []-brackets the class name.
+//
+const TString MParContainer::GetDescriptor(const TObject &o)
+{
+    //
+    // Because it returns a (const char*) we cannot return a casted
+    // local TString. The pointer would - immediatly after return -
+    // point to a random memory segment, because the TString has gone.
+    //
+    MString desc;
+    desc.Print("%s [%s]", o.GetName(), o.ClassName());
+    return (TString)o.GetName()==o.ClassName() ? o.ClassName() : desc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return a unique name for this container. It is created from
+//  the container name and the unique Id. (This is mostly used
+//  in the StreamPrimitive member functions)
+//
+const TString MParContainer::GetUniqueName() const
+{
+    TString ret = ToLower(fName);
+
+    if (isdigit(ret[ret.Length()-1]))
+        ret+="_";
+
+    ret+=GetUniqueID();
+
+    return ret;
+}
+
+// --------------------------------------------------------------------------
+//
+//  List MParContainer name and title.
+//
+void MParContainer::ls(Option_t *) const
+{
+    TROOT::IndentLevel();
+    *fLog << all << GetDescriptor() << " " << GetTitle() << ": kCanDelete=";
+    *fLog << Int_t(TestBit(kCanDelete)) << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print MParContainer name and title.
+//
+void MParContainer::Print(Option_t *) const
+{
+    *fLog << all << GetDescriptor() << " " << GetTitle() << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Change (i.e. set) the name of the MParContainer.
+//  WARNING !!
+//  If the object is a member of a THashTable, THashList container
+//  The HashTable must be Rehashed after SetName
+//  For example the list of objects in the current directory is a THashList
+//
+void MParContainer::SetName(const char *name)
+{
+    fName = name;
+    ResetBit(kIsSavedAsPrimitive);
+    if (gPad && TestBit(kMustCleanup)) gPad->Modified();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Change (i.e. set) all the MParContainer parameters (name and title).
+//  See also WARNING in SetName
+//
+void MParContainer::SetObject(const char *name, const char *title)
+{
+    fName  = name;
+    fTitle = title;
+    ResetBit(kIsSavedAsPrimitive);
+    if (gPad && TestBit(kMustCleanup)) gPad->Modified();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Change (i.e. set) the title of the MParContainer.
+//
+void MParContainer::SetTitle(const char *title)
+{
+    fTitle = title;
+    ResetBit(kIsSavedAsPrimitive);
+    if (gPad && TestBit(kMustCleanup)) gPad->Modified();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return size of the MParContainer part of the TObject.
+//
+Int_t MParContainer::Sizeof() const
+{
+    Int_t nbytes = fName.Sizeof() + fTitle.Sizeof();
+    return nbytes;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If you want to use Ascii-Input/-Output (eg. MWriteAsciiFile) of a
+//  container, overload this function.
+//
+void MParContainer::AsciiRead(istream &fin)
+{
+    *fLog << warn << "To use the the ascii input of " << GetName();
+    *fLog << " you have to overload " << ClassName() << "::AsciiRead." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Write out a data member given as a TDataMember object to an output stream.
+//
+Bool_t MParContainer::WriteDataMember(ostream &out, const TDataMember *member, Double_t scale) const
+{
+    if (!member)
+        return kFALSE;
+
+    if (!member->IsPersistent() || member->Property()&kIsStatic)
+        return kFALSE;
+
+    /*const*/ TMethodCall *call = ((TDataMember*)member)->GetterMethod(); //FIXME: Root
+    if (!call)
+    {
+        *fLog << warn << "Sorry, no getter method found for " << member->GetName() << endl;
+        return kFALSE;
+    }
+
+    // For debugging: out << member->GetName() << ":";
+
+    switch (call->ReturnType())
+    {
+    case TMethodCall::kLong:
+        Long_t l;
+        call->Execute((void*)this, l); // FIXME: const, root
+        out << l << " ";
+        return kTRUE;
+
+    case TMethodCall::kDouble:
+        Double_t d;
+        call->Execute((void*)this, d); // FIXME: const, root
+        out << (scale*d) << " ";
+        return kTRUE;
+
+    default:
+    //case TMethodCall::kString:
+    //case TMethodCall::kOther:
+        /* someone may want to enhance this? */
+        return kFALSE;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Write out a data member given by name to an output stream.
+//
+Bool_t MParContainer::WriteDataMember(ostream &out, const char *member, Double_t scale) const
+{
+    /*const*/ TClass *cls = IsA()->GetBaseDataMember(member);
+    if (!cls)
+        return kFALSE;
+
+    return WriteDataMember(out, cls->GetDataMember(member), scale);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Write out a data member from a given TList of TDataMembers.
+//  returns kTRUE when at least one member was successfully written
+//
+Bool_t MParContainer::WriteDataMember(ostream &out, const TList *list) const
+{
+    Bool_t rc = kFALSE;
+
+    TDataMember *data = NULL;
+
+    TIter Next(list);
+    while ((data=(TDataMember*)Next()))
+        rc |= WriteDataMember(out, data);
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If you want to use Ascii-Input/-Output (eg. MWriteAsciiFile) of a
+//  container, you may overload this function. If you don't overload it
+//  the data member of a class are written to the file in the order of
+//  appearance in the class header (be more specfic: root dictionary)
+//  Only data members which are of integer (Bool_t, Int_t, ...) or
+//  floating point (Float_t, Double_t, ...) type are written.
+//  returns kTRUE when at least one member was successfully written
+//
+Bool_t MParContainer::AsciiWrite(ostream &out) const
+{
+    // *fLog << warn << "To use the the ascii output of " << GetName();
+    // *fLog << " you have to overload " << ClassName() << "::AsciiWrite." << endl;
+
+    Bool_t rc = WriteDataMember(out, IsA()->GetListOfDataMembers());
+
+    TIter NextBaseClass(IsA()->GetListOfBases());
+    TBaseClass *base;
+    while ((base = (TBaseClass*) NextBaseClass()))
+    {
+        /*const*/ TClass *cls = base->GetClassPointer();
+
+        if (!cls)
+            continue;
+
+        if (cls->GetClassVersion())
+            rc |= WriteDataMember(out, cls->GetListOfDataMembers());
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// This virtual function is called for all parameter containers which are
+// found in the parameter list automatically each time the tasklist is
+// executed.
+//
+// By overwriting this function you can invalidate the contents of a
+// container before each execution of the tasklist:
+//
+// For example:
+//   void MHillas::Reset()
+//   {
+//      fWidth = -1;
+//   }
+//
+// (While -1 is obviously a impossible value for fWidth you can immediatly
+// see - if you Print() the contents of this container - that MHillasCalc
+// has not caluclated the width in this runthrough of the tasklist)
+//
+// Overwriting MParConatiner::Reset() in your container makes it
+// unnecessary to call any Clear() or Reset() manually in your task and
+// you make sure, that you don't keep results of previous runs of your
+// tasklist by chance.
+//
+// MParContainer::Reset() itself does nothing.
+//
+void MParContainer::Reset()
+{
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the pointer to the TClass (from the root dictionary) which
+// corresponds to the class with name name.
+//
+// Make sure, that a new object of this type can be created.
+//
+// In case of failure return NULL
+//
+TClass *MParContainer::GetConstructor(const char *name) const
+{
+    //
+    // try to get class from root environment
+    //
+    TClass *cls = gROOT->GetClass(name);
+    Int_t rc = 0;
+    if (!cls)
+        rc =1;
+    else
+    {
+        if (!cls->Property())
+            rc = 5;
+        if (!cls->Size())
+            rc = 4;
+        if (!cls->IsLoaded())
+            rc = 3;
+        if (!cls->HasDefaultConstructor())
+            rc = 2;
+    }
+
+    if (!rc)
+        return cls;
+
+    *fLog << err << dbginf << GetDescriptor() << " - Cannot create new instance of class '" << name << "': ";
+    switch (rc)
+    {
+    case 1:
+        *fLog << "gROOT->GetClass() returned NULL." << endl;
+        return NULL;
+    case 2:
+        *fLog << "no default constructor." << endl;
+        return NULL;
+    case 3:
+        *fLog << "not loaded." << endl;
+        return NULL;
+    case 4:
+        *fLog << "zero size." << endl;
+        return NULL;
+    case 5:
+        *fLog << "no property." << endl;
+        return NULL;
+    }
+
+    *fLog << "rtlprmft." << endl;
+
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a new object of class 'name'. Make sure that the object
+// derives from the class base.
+//
+// In case of failure return NULL
+//
+// The caller is responsible of deleting the object!
+//
+MParContainer *MParContainer::GetNewObject(const char *name, TClass *base) const
+{
+    return base ? GetNewObject(name, base->GetName()) : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a new object of class 'name'. Make sure that the object
+// derives from the class base.
+//
+// In case of failure return NULL
+//
+// The caller is responsible of deleting the object!
+//
+MParContainer *MParContainer::GetNewObject(const char *name, const char *base) const
+{
+    TClass *cls = GetConstructor(name);
+    if (!cls || !base)
+        return NULL;
+
+    if (!cls->InheritsFrom(base))
+    {
+        *fLog << err;
+        *fLog << dbginf << GetDescriptor() << " - Cannot create new instance of class '" << name << "': ";
+        *fLog << " - Class " << cls->GetName() << " doesn't inherit from " << base << endl;
+        return NULL;
+    }
+
+    //
+    // create the parameter container of the the given class type
+    //
+    TObject *obj = (TObject*)cls->New();
+    if (!obj)
+    {
+        *fLog << err;
+        *fLog << dbginf << GetDescriptor() << " - Cannot create new instance of class '" << name << "': ";
+        *fLog << " - Class " << cls->GetName() << " has no default constructor." << endl;
+        *fLog << " - An abstract member functions of a base class is not overwritten." << endl;
+        return NULL;
+    }
+
+    return (MParContainer*)obj;
+}
+
+TMethodCall *MParContainer::GetterMethod(const char *name) const
+{
+    const TString n(name);
+    const Int_t pos1 = n.First('.');
+
+    const TString part1 = pos1<0 ? n : n(0, pos1);
+    const TString part2 = pos1<0 ? TString("") : n(pos1+1, n.Length());
+
+    TClass *cls = IsA()->GetBaseDataMember(part1);
+    if (cls)
+    {
+        TDataMember *member = cls->GetDataMember(part1);
+        if (!member)
+        {
+            *fLog << err << "Datamember '" << part1 << "' not in " << GetDescriptor() << endl;
+            return NULL;
+        }
+
+        // This handles returning references of contained objects, eg
+        // class X { TObject fO; TObject &GetO() { return fO; } };
+        if (!member->IsBasic() && !part2.IsNull())
+        {
+            cls = gROOT->GetClass(member->GetTypeName());
+            if (!cls)
+            {
+                *fLog << err << "Datamember " << part1 << " [";
+                *fLog << member->GetTypeName() << "] not in dictionary." << endl;
+                return NULL;
+            }
+            if (!cls->InheritsFrom(MParContainer::Class()))
+            {
+                *fLog << err << "Datamember " << part1 << " [";
+                *fLog << member->GetTypeName() << "] does not inherit from ";
+                *fLog << "MParContainer." << endl;
+                return NULL;
+            }
+
+            const MParContainer *sub = (MParContainer*)((ULong_t)this+member->GetOffset());
+            return sub->GetterMethod(part2);
+        }
+
+        if (member->IsaPointer())
+        {
+            *fLog << warn << "Data-member " << part1 << " is a pointer..." << endl;
+            *fLog << dbginf << "Not yet implemented!" << endl;
+            //TClass *test = gROOT->GetClass(member->GetTypeName());
+            return 0;
+        }
+
+        TMethodCall *call = member->GetterMethod();
+        if (call)
+            return call;
+    }
+
+    *fLog << inf << "No standard access for '" << part1 << "' in ";
+    *fLog << GetDescriptor() << " or one of its base classes." << endl;
+
+    TMethodCall *call = NULL;
+
+    *fLog << "Trying to find MethodCall '" << ClassName();
+    *fLog << "::Get" << part1 << "' instead..." << flush;
+    call = new TMethodCall(IsA(), (TString)"Get"+part1, "");
+    if (call->GetMethod())
+    {
+        fgListMethodCall.Add(call);
+        *fLog << "found." << endl;
+        return call;
+    }
+    *fLog << endl;
+
+    delete call;
+
+    *fLog << "Trying to find MethodCall '" << ClassName();
+    *fLog << "::" << part1 << "' instead..." << flush;
+    call = new TMethodCall(IsA(), part1, "");
+    if (call->GetMethod())
+    {
+        fgListMethodCall.Add(call);
+        *fLog << "found." << endl;
+        return call;
+    }
+    *fLog << endl;
+
+    delete call;
+
+    *fLog << err << "Sorry, no getter method found for " << part1 << endl;
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MParContainer::SavePrimitive(ofstream &out, Option_t *o)
+{
+    static UInt_t uid = 0;
+
+    if (IsSavedAsPrimitive())
+        return;
+
+    SetUniqueID(uid++);
+    SetBit(kIsSavedAsPrimitive);
+
+    if (gListOfPrimitives && !gListOfPrimitives->FindObject(this))
+        gListOfPrimitives->Add(this);
+
+    StreamPrimitive(out);
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates the string written by SavePrimitive and returns it.
+//
+void MParContainer::StreamPrimitive(ofstream &out) const
+{
+    out << "   // Using MParContainer::StreamPrimitive" << endl;
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << fName << "\", \"" << fTitle << "\");" << endl;
+}
+
+void MParContainer::GetNames(TObjArray &arr) const
+{
+    arr.AddLast(new TNamed(fName, fTitle));
+}
+
+void MParContainer::SetNames(TObjArray &arr)
+{
+    TNamed *name = (TNamed*)arr.First();
+
+    fName  = name->GetName();
+    fTitle = name->GetTitle();
+
+    delete arr.Remove(name);
+    arr.Compress();
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new instance of this class. The idea is to create a clone of
+// this class in its initial state.
+//
+MParContainer *MParContainer::New() const
+{
+    return (MParContainer*)IsA()->New();
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the contents/setup of a parameter container/task from a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+// Return values:
+//  kTRUE:  Environment string found
+//  kFALSE: Environment string not found
+//  kERROR: Error occured, eg. environment invalid
+//
+// Overload this if you don't want to control the level of setup-string. In
+// this case ReadEnv gets called with the different possibilities, see TestEnv.
+//
+Int_t MParContainer::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (!IsEnvDefined(env, prefix, "", print))
+        return kFALSE;
+
+    *fLog << warn << "WARNING - " << fName << ": Resource " << prefix << " found, but no " << ClassName() << "::ReadEnv." << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the contents/setup of a parameter container/task to a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_t MParContainer::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    if (!IsEnvDefined(env, prefix, "", print))
+        return kFALSE;
+
+    *fLog << warn << "WARNING - Resource " << prefix+fName << " found, but " << ClassName() << "::WriteEnv not overloaded." << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Take the prefix and call ReadEnv for:
+//   prefix.containername
+//   prefix.classname
+//   containername
+//   classname
+//
+//  The existance of an environment variable is done in this order. If
+//  ReadEnv return kTRUE the existance of the container setup is assumed and
+//  the other tests are skipped. If kFALSE is assumed the sequence is
+//  continued. In case of kERROR failing of the setup from a file is assumed.
+//
+// Overload this if you want to control the handling of level of setup-string
+// mentioned above. In this case ReadEnv gets never called if you don't call
+// it explicitly.
+//
+Int_t MParContainer::TestEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (print)
+        *fLog << all << "Testing Prefix+ContName: " << prefix+GetName() << endl;
+    Int_t rc = ReadEnv(env, prefix+GetName(), print);
+    if (rc==kERROR || rc==kTRUE)
+        return rc;
+
+    // Check For: Job4.MClassName.Varname
+    if (print)
+        *fLog << all << "Testing Prefix+ClasName: " << prefix+ClassName() << endl;
+    rc = ReadEnv(env, prefix+ClassName(), print);
+    if (rc==kERROR || rc==kTRUE)
+        return rc;
+
+    // Check For: ContainerName.Varname
+    if (print)
+        *fLog << all << "Testing ContName: " << GetName() << endl;
+    rc = ReadEnv(env, GetName(), print);
+    if (rc==kERROR || rc==kTRUE)
+        return rc;
+
+    // Check For: MClassName.Varname
+    if (print)
+        *fLog << all << "Testing ClassName: " << ClassName() << endl;
+    rc = ReadEnv(env, ClassName(), print);
+    if (rc==kERROR || rc==kTRUE)
+        return rc;
+
+    // Not found
+    return kFALSE;
+}
+
+Bool_t MParContainer::IsEnvDefined(const TEnv &env, TString prefix, TString postfix, Bool_t print) const
+{
+    if (!postfix.IsNull())
+        postfix.Insert(0, ".");
+
+    return IsEnvDefined(env, prefix+postfix, print);
+}
+
+Bool_t MParContainer::IsEnvDefined(const TEnv &env, TString name, Bool_t print) const
+{
+    if (print)
+        *fLog << all << GetDescriptor() << " - " << name << "... " << flush;
+
+    if (!((TEnv&)env).Defined(name))
+    {
+        if (print)
+            *fLog << "not found." << endl;
+        return kFALSE;
+    }
+
+    if (print)
+        *fLog << "found." << endl;
+
+    return kTRUE;
+}
+
+Int_t MParContainer::GetEnvValue(const TEnv &env, TString prefix, TString postfix, Int_t dflt) const
+{
+    return GetEnvValue(env, prefix+"."+postfix, dflt);
+}
+
+Double_t MParContainer::GetEnvValue(const TEnv &env, TString prefix, TString postfix, Double_t dflt) const
+{
+    return GetEnvValue(env, prefix+"."+postfix, dflt);
+}
+
+const char *MParContainer::GetEnvValue(const TEnv &env, TString prefix, TString postfix, const char *dflt) const
+{
+    return GetEnvValue(env, prefix+"."+postfix, dflt);
+}
+
+Int_t MParContainer::GetEnvValue(const TEnv &env, TString prefix, Int_t dflt) const
+{
+    return ((TEnv&)env).GetValue(prefix, dflt);
+}
+
+Double_t MParContainer::GetEnvValue(const TEnv &env, TString prefix, Double_t dflt) const
+{
+    return ((TEnv&)env).GetValue(prefix, dflt);
+}
+
+const char *MParContainer::GetEnvValue(const TEnv &env, TString prefix, const char *dflt) const
+{
+    return ((TEnv&)env).GetValue(prefix, dflt);
+}
Index: /tags/Mars-V0.9/mbase/MParContainer.h
===================================================================
--- /tags/Mars-V0.9/mbase/MParContainer.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MParContainer.h	(revision 9772)
@@ -0,0 +1,189 @@
+#ifndef MARS_MParContainer
+#define MARS_MParContainer
+
+//////////////////////////////////////////////////////////////////////////
+//                                                                      //
+// MParContainer                                                        //
+//                                                                      //
+// The basis for all parameter containers                               //
+//                                                                      //
+//////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+// gcc 3.2
+#include <iosfwd>
+//class ofstream;
+//class ifstream;
+
+class TEnv;
+class TArrayD;
+class TDataMember;
+class TMethodCall;
+
+class MLog;
+class MStatusDisplay;
+
+class MParContainer : public TObject
+{
+private:
+    static TObjArray fgListMethodCall; //!
+
+protected:
+    TString fName;        // parameter container identifier (name)
+    TString fTitle;       // parameter container title
+
+    MLog   *fLog;         // The general log facility for this object, initialized with the global object
+
+    // This data member was added later, because for calculating the
+    // Checksum root (3.02/07) ignores ClassDef=0 all data members
+    // which are not persistent (//!) are used. To make the two
+    // class versions CheckSum-compatible (only getting rid of a
+    // warning) this member is persistent.
+    MStatusDisplay *fDisplay; //!
+
+private:
+    enum {
+        kIsSavedAsPrimitive = BIT(15)
+    };
+
+    Bool_t  fReadyToSave; // should be set to true if the contents of the container is changed somehow
+
+    TClass *GetConstructor(const char *name) const;
+
+public:
+    enum {
+        kEnableGraphicalOutput = BIT(16)
+    };
+
+    MParContainer(const char *name="", const char *title="");
+    MParContainer(const TString &name, const TString &title);
+    MParContainer(const MParContainer &named);
+    MParContainer& operator=(const MParContainer& rhs);
+    virtual ~MParContainer();
+
+    virtual TObject    *Clone(const char *newname="") const;
+    virtual Int_t       Compare(const TObject *obj) const;
+    virtual void        Copy(TObject &named)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+const
+#endif
+        ;
+    virtual void        FillBuffer(char *&buffer);
+
+    static const TString GetDescriptor(const TObject &o);
+
+    virtual const TString GetDescriptor() const;
+    virtual const TString GetUniqueName() const;
+    virtual const char   *GetName() const       { return fName.Data(); }
+    virtual const char   *GetTitle() const      { return fTitle.Data(); }
+    virtual ULong_t       Hash() const          { return fName.Hash(); }
+    virtual Bool_t        IsSortable() const    { return kTRUE; }
+
+    virtual void   SetName(const char *name); // *MENU*
+    virtual void   SetObject(const char *name, const char *title);
+    virtual void   SetTitle(const char *title=""); // *MENU*
+    virtual void   ls(Option_t *option="") const;
+    virtual void   Print(Option_t *option="") const;
+    virtual Int_t  Sizeof() const;
+    virtual void   SavePrimitive(ofstream &out, Option_t *o="");
+
+    virtual MParContainer *New() const;
+    virtual void   SetLogStream(MLog *lg) { fLog = lg; }
+    virtual void   Reset();
+    virtual Bool_t IsReadyToSave() const             { return fReadyToSave; }
+    virtual void   SetReadyToSave(Bool_t flag=kTRUE) { fReadyToSave=flag; }
+    virtual Bool_t IsSavedAsPrimitive() const        { return TestBit(kIsSavedAsPrimitive); }
+    virtual void   EnableGraphicalOutput(Bool_t flag=kTRUE) { flag ? SetBit(kEnableGraphicalOutput) : ResetBit(kEnableGraphicalOutput);}
+    virtual Bool_t IsGraphicalOutputEnabled() const  { return TestBit(kEnableGraphicalOutput); }
+    virtual void   SetVariables(const TArrayD &)     { AbstractMethod("SetVariables(const TArrayD&)"); }
+
+    virtual void SetDisplay(MStatusDisplay *d) { fDisplay = d; }
+
+    // FIXME: Change to ostream! Seems to be difficult, because
+    //        MTaskListStreamPrimitive calls SavePrimitive(ofstream&).
+    //        Maybe with a cast?
+    virtual void StreamPrimitive(ofstream &out) const;
+
+    TMethodCall *GetterMethod(const char *name) const;
+
+    Bool_t WriteDataMember(ostream &out, const char *member, Double_t scale=1) const;
+    Bool_t WriteDataMember(ostream &out, const TDataMember *member, Double_t scale=1) const;
+    Bool_t WriteDataMember(ostream &out, const TList *list) const;
+
+    virtual void AsciiRead(istream &fin);
+    virtual Bool_t AsciiWrite(ostream &out) const;
+
+    Int_t Read(const char *name=NULL) { return TObject::Read(name?name:(const char*)fName); }
+
+    virtual void GetNames(TObjArray &arr) const;
+    virtual void SetNames(TObjArray &arr);
+
+    virtual Int_t  TestEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    virtual Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    virtual Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+    Bool_t ReadEnv(const TEnv &env, Bool_t print=kFALSE) { return ReadEnv(env, "", print); }
+    Bool_t WriteEnv(TEnv &env, Bool_t print=kFALSE) const { return WriteEnv(env, "", print); }
+
+    Bool_t IsEnvDefined(const TEnv &env, TString prefix, TString postfix, Bool_t print) const;
+    Bool_t IsEnvDefined(const TEnv &env, TString name, Bool_t print) const;
+
+    Int_t       GetEnvValue(const TEnv &env, TString prefix, TString postfix, Int_t dflt) const;
+    Double_t    GetEnvValue(const TEnv &env, TString prefix, TString postfix, Double_t dflt) const;
+    const char *GetEnvValue(const TEnv &env, TString prefix, TString postfix, const char *dflt) const;
+
+    Int_t       GetEnvValue(const TEnv &env, TString prefix, Int_t dflt) const;
+    Double_t    GetEnvValue(const TEnv &env, TString prefix, Double_t dflt) const;
+    const char *GetEnvValue(const TEnv &env, TString prefix, const char *dflt) const;
+
+    MParContainer *GetNewObject(const char *name, const char *base) const;
+    MParContainer *GetNewObject(const char *name, TClass *base=MParContainer::Class()) const;
+
+    ClassDef(MParContainer, 0)  //The basis for all parameter containers
+};
+
+//!
+//! Maybe we can add a static parameter list to MEvtLoop
+//! Also we can derive MEvtLoop from MTaskList to have a static tasklist, too
+//!
+
+// FIXME: Move as (persistent) static data member to MParContainer
+R__EXTERN TList *gListOfPrimitives; // instantiation in MEvtLoop
+
+/*
+class MParContainer : public TNamed
+{
+protected:
+    MLog    *fLog;         //! The general log facility for this object, initialized with the global object
+
+private:
+    Bool_t   fReadyToSave; //! should be set to true if the contents of the container is changed somehow
+
+public:
+    MParContainer(const char *name="", const char *title="") : TNamed(name, title), fLog(&gLog), fReadyToSave(kFALSE) { }
+    MParContainer(const TString &name, const TString &title) : TNamed(name, title), fLog(&gLog), fReadyToSave(kFALSE) { }
+
+    void SetLogStream(MLog *lg)                      { fLog = lg; }
+
+    virtual void   Reset()                           {  }
+
+    virtual Bool_t IsReadyToSave()                   { return fReadyToSave; }
+    virtual void   SetReadyToSave(Bool_t flag=kTRUE) { fReadyToSave=flag; }
+
+    virtual void AsciiRead(ifstream &fin);
+    virtual void AsciiWrite(ofstream &fout) const;
+
+    ClassDef(MParContainer, 0)  //The basis for all parameter containers
+};
+*/
+#endif
+
+
Index: /tags/Mars-V0.9/mbase/MParList.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MParList.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MParList.cc	(revision 9772)
@@ -0,0 +1,990 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MParList                                                                //
+//                                                                         //
+// This class contains a list of different parameter containers.           //
+//                                                                         //
+// A parameter container is an object which is derived from                //
+// MParContainer.                                                          //
+//                                                                         //
+// Normally a parameter container is used for data exchange between two    //
+// tasks at runtime.                                                       //
+//                                                                         //
+// You can add every parameter container (Named object) to the             //
+// instance and access it from somewhere else via its Name.                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MParList.h"
+
+#include <fstream>     // ofstream, SavePrimitive
+
+#include <TNamed.h>
+#include <TClass.h>
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIter.h"
+#include "MTaskList.h"
+
+ClassImp(MParList);
+
+using namespace std;
+
+static const TString gsDefName  = "MParList";
+static const TString gsDefTitle = "A list of Parameter Containers";
+
+// --------------------------------------------------------------------------
+//
+//  default constructor
+//  creates an empty list
+//
+MParList::MParList(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    //
+    // This sets a flag that the list is the owner, which means
+    // that the destructor of the list deletes all it's objects
+    //
+    fContainer  = new TOrdCollection;
+    fAutodelete = new TOrdCollection;
+
+    gROOT->GetListOfCleanups()->Add(fContainer);
+    gROOT->GetListOfCleanups()->Add(fAutodelete);
+    fContainer->SetBit(kMustCleanup);
+    fAutodelete->SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Copy constructor. It copies all entries of the parameter list, but it
+//  takes care of, that the automatically created entries are only deleted
+//  once. (doesn't copy the list which holds the automatically created
+//  entries)
+//
+MParList::MParList(MParList &ts)
+{
+    fContainer->AddAll(ts.fContainer);
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the 'IsOwner' bit is set (via SetOwner()) all containers are deleted
+//  by the destructor
+//
+MParList::~MParList()
+{
+    //
+    // Case:
+    //  1) MParList is owner of the containers:
+    //     All container are stored in fContainer, and become deleted by
+    //     'delete fContainer'. Some of these containers, which were
+    //     created automatically are stored in fAutodelete, too. To prevent
+    //     double deletion this containers are not deleted by the destructor
+    //     of fAutodelete.
+    //  2) MParList is not owner of the containers:
+    //     The containers which were Added by AddToList are not touched.
+    //     Only the containers which were created automatically are also
+    //     automatically deleted.
+    //
+    IsOwner() ? fContainer->SetOwner() : fAutodelete->SetOwner();
+
+    TIter Next(fContainer);
+    TObject *o;
+    while ((o=Next()))
+        if (o->TestBit(kCanDelete))
+            delete fContainer->Remove(o);
+
+    // FIXME? If fContainer is owner do we have to remove the object
+    //   from fAutodelete due to the acces when checking for a
+    //   garbage collection?
+
+    delete fContainer;
+    delete fAutodelete;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the 'IsOwner' bit is set (via SetOwner()) all containers are deleted
+//  by the destructor
+//
+void MParList::SetOwner(Bool_t enable)
+{
+    enable ? SetBit(kIsOwner) : ResetBit(kIsOwner);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the logging streamer of the parameter list and all contained
+//  parameter containers
+//
+void MParList::SetLogStream(MLog *log)
+{
+    fContainer->ForEach(MParContainer, SetLogStream)(log);
+    MParContainer::SetLogStream(log);
+}
+
+void MParList::SetDisplay(MStatusDisplay *d)
+{
+    fContainer->ForEach(MParContainer, SetDisplay)(d);
+    MParContainer::SetDisplay(d);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add a single container to the list.
+//
+//  If 'where' is given, the object will be added after this.
+//
+Bool_t MParList::AddToList(MParContainer *cont, MParContainer *where)
+{
+    //
+    //  check if the object (you want to add) exists
+    //
+    if (!cont)
+        return kFALSE;
+
+    //
+    // Get Name of new container
+    //
+    const char *name = cont->GetName();
+
+    //
+    // Check if the new container is already existing in the list
+    //
+    const TObject *objn = fContainer->FindObject(name);
+    const TObject *objt = fContainer->FindObject(cont);
+
+    if (objn || objt)
+    {
+        //
+        // If the container is already in the list ignore it.
+        //
+        if (objt || objn==cont)
+        {
+            *fLog << warn << dbginf << "Warning: Container '" << cont->GetName() << ", 0x" << (void*)cont;
+            *fLog << "' already existing in '" << GetName() << "'... ignoring." << endl;
+            return kTRUE;
+        }
+
+        //
+        // Otherwise add it to the list, but print a warning message
+        //
+        *fLog << warn << dbginf << "Warning: Container with the same name '" << cont->GetName();
+        *fLog << "' already existing in '" << GetName() << "'." << endl;
+        *fLog << "You may not be able to get a pointer to container task by name." << endl;
+    }
+
+    //
+    //  check if you want to add the new parameter container somewhere
+    //  special (in that case you specify "where")
+    //
+    if (where)
+    {
+        if (!fContainer->FindObject(where))
+        {
+            *fLog << dbginf << "Error: Cannot find parameter container after which the new one should be added!" << endl;
+            return kFALSE;
+        }
+    }
+
+    if (!cont->InheritsFrom(MParContainer::Class()))
+    {
+        *fLog << dbginf << "Error: Cantainer MUST derive from MParContainer!" << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Adding " << name << " to " << GetName() << "... " << flush;
+
+    cont->SetBit(kMustCleanup);
+    fContainer->Add(cont);
+    *fLog << "Done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add all entries of the TObjArray to the list.
+//
+void MParList::AddToList(TObjArray *list)
+{
+    //
+    //  check if the object (you want to add) exists
+    //
+    if (!list)
+        return;
+
+    MIter Next(list);
+
+    MParContainer *cont = NULL;
+    while ((cont=Next()))
+    {
+        cont->SetBit(kMustCleanup);
+        AddToList(cont);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object with the same name in the list and replace it with
+//  the new one. If the kIsOwner flag is set and the object was not
+//  created automatically, the object is deleted.
+//
+Bool_t MParList::Replace(MParContainer *cont)
+{
+    //
+    //  check if the object (you want to add) exists
+    //
+    if (!cont)
+        return kFALSE;
+
+    TObject *obj = FindObject(cont->GetName());
+    if (!obj)
+    {
+        *fLog << warn << "No object with the same name '";
+        *fLog << cont->GetName() << "' in list... adding." << endl;
+        return AddToList(cont);
+    }
+
+    fContainer->Remove(obj);
+
+    if (IsOwner() && !fAutodelete->FindObject(obj))
+        delete obj;
+
+    *fLog << inf << "MParContainer '" << cont->GetName() << "' found and replaced..." << endl;
+
+    return AddToList(cont);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object with the same name in the list and remove it.
+//  If the kIsOwner flag is set and the object was not created
+//  automatically, the object is deleted.
+//
+void MParList::Remove(MParContainer *cont)
+{
+    //
+    //  check if the object (you want to add) exists
+    //
+    if (!cont)
+        return;
+
+    TObject *obj = fContainer->Remove(cont);
+    if (!obj)
+    {
+        *fLog << warn << "Object not found in list..." << endl;
+        return;
+    }
+
+    *fLog << inf << "MParContainer '" << cont->GetName() << "' removed..." << endl;
+
+    if (IsOwner() && !fAutodelete->FindObject(obj))
+        delete obj;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object in the list.
+//  'name' is the name of the object you are searching for.
+//
+TObject *MParList::FindObject(const char *name) const
+{
+    return fContainer->FindObject(name);
+}
+
+// --------------------------------------------------------------------------
+//
+//  check if the object is in the list or not
+//
+TObject *MParList::FindObject(const TObject *obj) const
+{
+    return fContainer->FindObject(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object in the list and check for the correct inheritance.
+//  'name' is the name of the object you are searching for.
+//
+// In words: Find object name and check whether it inherits from classname
+//
+TObject *MParList::FindObject(const char *name, const char *classname) const
+{
+    TObject *obj = fContainer->FindObject(name);
+
+    if (!obj)
+        return NULL;
+
+    if (obj->InheritsFrom(classname))
+        return obj;
+
+    *fLog << dbginf << warn << "Found object '" << name << "' doesn't ";
+    *fLog << "inherit from " << "'" << classname << "'" << endl;
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  check if the object is in the list or not and check for the correct
+//  inheritance
+//
+TObject *MParList::FindObject(const TObject *obj, const char *classname) const
+{
+    TObject *nobj = fContainer->FindObject(obj);
+
+    if (!nobj)
+        return NULL;
+
+    if (nobj->InheritsFrom(classname))
+        return nobj;
+
+    *fLog << dbginf << warn << "Found object '" << nobj->GetName() << "' ";
+    *fLog << "doesn't inherit from " << "'" << classname << "'" << endl;
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Searches for the tasklist tlist (default: MTaskList) and returns
+//  a task with the given name found in this list. If one of both isn't
+//  found NULL is returned
+//
+MTask *MParList::FindTask(const char *name, const char *tlist) const
+{
+    TObject *l = FindObject(tlist, "MTaskList");
+    return (MTask*)(l ? l->FindObject(name) : NULL);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find a tasklist which contains a task with name name
+//
+MTaskList *MParList::FindTaskListWithTask(const char *name) const
+{
+    TIter Next(fContainer);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        MTaskList *l1 = dynamic_cast<MTaskList*>(o);
+        if (!l1)
+            continue;
+
+        MTaskList *l2 = l1->FindTaskList(name);
+        if (l2)
+            return l2;
+    }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find a tasklist which contains a task task
+//
+MTaskList *MParList::FindTaskListWithTask(const MTask *task) const
+{
+    TIter Next(fContainer);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        MTaskList *l1 = dynamic_cast<MTaskList*>(o);
+        if (!l1)
+            continue;
+
+        MTaskList *l2 = l1->FindTaskList(task);
+        if (l2)
+            return l2;
+    }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  returns the ClassName without anything which is behind that last ';' in
+//  string.
+//
+TString MParList::GetClassName(const char *classname)
+{
+    TString cname(classname);
+    const char *semicolon = strrchr(cname, ';');
+
+    if (semicolon)
+        cname.Remove(semicolon-cname);
+
+    return cname;
+}
+
+// --------------------------------------------------------------------------
+//
+//  returns the ObjectName. It is created from a class and object name.
+//  If no object name is given the objectname is the same than the
+//  class name. Leading dots are removed from the object name
+//
+TString MParList::GetObjectName(const char *classname, const char *objname)
+{
+    TString cname(classname);
+    const char *semicolon = strrchr(cname, ';');
+
+    TString oname(objname ? objname : classname);
+
+    if (semicolon)
+    {
+        //
+        // Remove leading dots from objectname (eg. "MMcTrig;5.")
+        //
+        Int_t sz = oname.Sizeof()-2;
+
+        while (sz>=0 && oname[sz]=='.')
+            oname.Remove(sz--);
+    }
+    return oname;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object in the list.
+//  'name' is the name of the object you are searching for.
+//  If the object doesn't exist we try to create one from the
+//  dictionary. If this isn't possible NULL is returned.
+//
+//  An object which was created automatically is deleted automatically in
+//  the destructor of the parameter list, too. This means, that if an
+//  object should survive (eg. Histograms) you MUST create it by yourself
+//  and add it to the parameter list.
+//
+//  By default (you don't specify an object name) the object name is
+//  the same as the classname
+//
+//  If the classname (default classname) is of the structure
+//  "Name;something" - containing a semicolon - evarything which is
+//  after the last appearance of a semicolon is stripped to get the
+//  Name of the Class. Normally this is used to number your objects.
+//  "Name;1", "Name;2", ... If a semicolon is detected leading dots
+//  are stripped from the object-name (eg. "name;5.")
+//
+// In words: Create object of type classname and set its name to objname.
+//           If an object with objname already exists return it.
+//
+MParContainer *MParList::FindCreateObj(const char *classname, const char *objname)
+{
+    //
+    // If now object name (name of the object to identify it in the
+    // List) is given use it's classname as the objectname
+    //
+
+    //
+    // Check if the classname is a 'numbered' name (like: "MTime;2")
+    // if so strip the number from the classname.
+    //
+    // Becareful: We check for the last occurance of a ';' only and we
+    // also don't check if a number follows or something else.
+    //
+    // Rem: I use a TString to make the code more readyble and to get
+    // the new object deleted automatically
+    //
+    TString cname = GetClassName(classname);
+    TString oname = GetObjectName(classname, objname);
+
+    //
+    // Try to find a object with this object name which is already
+    // in the List. If we can find one we are done.
+    //
+    MParContainer *pcont = (MParContainer*)FindObject(oname);
+
+    if (pcont)
+    {
+        if (pcont->InheritsFrom(cname))
+            return pcont;
+
+        *fLog << err << "Warning: Object '" << oname << "' found in list doesn't inherit from " << cname << "." << endl;
+        return NULL;
+    }
+
+    //
+    // if object is not existing in the list try to create one
+    //
+    *fLog << inf << "Object '" << oname << "' ";
+    if (oname!=cname)
+        *fLog << "[" << cname << "] ";
+    *fLog << "not yet in " << GetName() << "... creating." << endl;
+
+    //
+    // try to get class from root environment
+    //
+    TClass *cls = gROOT->GetClass(cname);
+    Int_t rc = 0;
+    if (!cls)
+        rc =1;
+    else
+    {
+        if (!cls->Property())
+            rc = 5;
+        if (!cls->Size())
+            rc = 4;
+        if (!cls->IsLoaded())
+            rc = 3;
+        if (!cls->HasDefaultConstructor())
+            rc = 2;
+    }
+
+    if (rc)
+    {
+        *fLog << err << dbginf << "Cannot create new instance of class '" << cname << "': ";
+        switch (rc)
+        {
+        case 1:
+            *fLog << "gROOT->GetClass() returned NULL." << endl;
+            return NULL;
+        case 2:
+            *fLog << "no default constructor." << endl;
+            return NULL;
+        case 3:
+            *fLog << "not loaded." << endl;
+            return NULL;
+        case 4:
+            *fLog << "zero size." << endl;
+            return NULL;
+        case 5:
+            *fLog << "no property." << endl;
+            return NULL;
+        }
+    }
+
+    if (!cls->InheritsFrom(MParContainer::Class()))
+    {
+        *fLog << " - Class doesn't inherit from MParContainer." << endl;
+        return NULL;
+    }
+
+    //
+    // create the parameter container of the the given class type
+    //
+    pcont = (MParContainer*)cls->New();
+    if (!pcont)
+    {
+        *fLog << " - Class has no default constructor." << endl;
+        *fLog << " - An abstract member functions of a base class is not overwritten." << endl;
+        return NULL;
+    }
+
+    //
+    // Set the name of the container
+    //
+    pcont->SetName(oname);
+
+    //
+    // Now add the object to the parameter list
+    //
+    AddToList(pcont);
+
+    //
+    // The object was automatically created. This makes sure, that such an
+    // object is deleted together with the list
+    //
+    fAutodelete->Add(pcont);
+
+    //
+    //  Find an object in the list.
+    //  'name' is the name of the object you are searching for.
+    //
+    return pcont;
+}
+
+// --------------------------------------------------------------------------
+//
+//   print some information about the current status of MParList
+//
+void MParList::Print(Option_t *t) const
+{
+    *fLog << all << underline << GetDescriptor() << ":" << endl;
+
+    MParContainer *obj = NULL;
+    MIter Next(fContainer);
+    while ((obj=Next()))
+    {
+        *fLog << " " << obj->GetDescriptor();
+        if (fAutodelete->FindObject(obj))
+            *fLog << " <autodel>";
+        *fLog << endl;
+    }
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Sets the flags off all containers in the list (and the list
+//   itself) to unchanged
+//
+void MParList::SetReadyToSave(Bool_t flag)
+{
+    fContainer->ForEach(MParContainer, SetReadyToSave)(flag);
+    MParContainer::SetReadyToSave(flag);
+}
+
+// --------------------------------------------------------------------------
+//
+//   Reset all containers in the list
+//
+void MParList::Reset()
+{
+    fContainer->ForEach(MParContainer, Reset)();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This finds numbered objects. The objects are returned in a copy of a
+//  TObjArray.
+//
+//  If from only is given (or to=0) object are assumed numbered
+//  from 1 to from.
+//
+TObjArray MParList::FindObjectList(const char *name, UInt_t first, const UInt_t last) const
+{
+    TObjArray list;
+
+    if (first>0 && last<first)
+    {
+        *fLog << err << dbginf << "Cannot create entries backwards (last<first)...skipped." << endl;
+        return list;
+    }
+
+    const UInt_t len = strlen(name);
+
+    char *auxname = new char[len+7];
+    strcpy(auxname, name);
+
+    if (first==0 && last!=0)
+        first = 1;
+
+    //
+    // If only 'from' is specified the number of entries are ment
+    //
+    for (UInt_t i=first; i<=last; i++)
+    {
+        if (first!=0 || last!=0)
+            sprintf(auxname+len, ";%d", i);
+
+        TObject *obj = FindObject(auxname);
+        if (!obj)
+            continue;
+
+        list.AddLast(obj);
+    }
+    delete auxname;
+
+    return list;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This finds numbered objects. The objects are returned in a copy of a
+//  TObjArray. If one of the objects doesn't exist it is created from the
+//  meaning of cname and oname (s. FindCreateObj)
+//
+//  If from only is given (or to=0) object are assumed numbered
+//  from 1 to from.
+//
+TObjArray MParList::FindCreateObjList(const char *cname, UInt_t first, const UInt_t last, const char *oname)
+{
+    TObjArray list;
+
+    if (first>0 && last<first)
+    {
+        *fLog << err << dbginf << "Cannot create entries backwards (last<first)...skipped." << endl;
+        return list;
+    }
+
+    const UInt_t len = strlen(cname);
+
+    char *auxname = new char[len+7];
+    strcpy(auxname, cname);
+
+    //
+    // If only 'from' is specified the number of entries are ment
+    //
+    if (first==0 && last!=0)
+        first = 1;
+
+    for (UInt_t i=first; i<=last; i++)
+    {
+        if (first!=0 || last!=0)
+            sprintf(auxname+len, ";%d", i);
+
+        TObject *obj = FindCreateObj(auxname, oname);
+        if (!obj)
+            break;
+
+        list.AddLast(obj);
+    }
+    delete auxname;
+
+    return list;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This finds numbered objects. The objects are returned in a copy of a
+//  TObjArray. If one of the objects doesn't exist it is created from the
+//  meaning of cname and oname (s. FindCreateObj)
+//
+//  If from only is given (or to=0) object are assumed numbered
+//  from 1 to from.
+//
+//  Remark: Because it is static the object are only created and not added to
+//  the parameter list. You must also take care of deleting these objects!
+//  This function is mainly made for use in root macros. Don't use it in
+//  compiled programs if you are not 100% sure what you are doing.
+//
+TObjArray MParList::CreateObjList(const char *cname, UInt_t first, const UInt_t last, const char *oname)
+{
+    TObjArray list;
+
+    if (first>0 && last<first)
+    {
+        gLog << err << dbginf << "Cannot create entries backwards (last<first)...skipped." << endl;
+        return list;
+    }
+
+    //
+    // try to get class from root environment
+    //
+    TClass *cls = gROOT->GetClass(cname);
+    if (!cls)
+    {
+        //
+        // if class is not existing in the root environment
+        //
+        gLog << dbginf << "Class '" << cname << "' not existing in dictionary." << endl;
+        return list;
+    }
+
+    const UInt_t len = strlen(cname);
+
+    char *auxname = new char[len+7];
+    strcpy(auxname, cname);
+
+    //
+    // If only 'from' is specified the number of entries are ment
+    //
+    if (first==0 && last!=0)
+        first = 1;
+
+    for (UInt_t i=first; i<=last; i++)
+    {
+        if (first!=0 || last!=0)
+            sprintf(auxname+len, ";%d", i);
+
+        //
+        // create the parameter container of the the given class type
+        //
+        MParContainer *pcont = (MParContainer*)cls->New();
+        if (!pcont)
+        {
+            gLog << err << dbginf << "Cannot create new instance of class '" << cname << "' (Maybe no def. constructor)" << endl;
+            return list;
+        }
+
+        //
+        // Set the name of the container
+        //
+        pcont->SetName(auxname);
+
+        //
+        // Add new object to the return list
+        //
+        list.AddLast(pcont);
+    }
+    delete auxname;
+
+    return list;
+}
+
+void MParList::SavePrimitive(ofstream &out, Option_t *o)
+{
+    Bool_t saved = IsSavedAsPrimitive();
+
+    MParContainer::SavePrimitive(out);
+
+    MIter Next(fContainer);
+
+    MParContainer *cont = NULL;
+    while ((cont=Next()))
+    {
+        //
+        // Because it was automatically created don't store its primitive
+        // I guess it will be automatically created again
+        //
+        if (fAutodelete->FindObject(cont) || cont->IsSavedAsPrimitive())
+            continue;
+
+        cont->SavePrimitive(out, "");
+
+        out << "   " << GetUniqueName() << ".";
+        out << (cont->InheritsFrom("MTaskList") && saved ? "Replace" : "AddToList");
+        out << "(&" << cont->GetUniqueName() << ");" << endl << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MParList::StreamPrimitive(ofstream &out) const
+{
+    out << "   MParList " << GetUniqueName();
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds one TNamed object per object in the list. The TNamed object must
+// be deleted by the user.
+//
+void MParList::GetNames(TObjArray &arr) const
+{
+    MParContainer::GetNames(arr);
+    fContainer->ForEach(MParContainer, GetNames)(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets name and title of each object in the list from the objects in
+// the array.
+//
+void MParList::SetNames(TObjArray &arr)
+{
+    MParContainer::SetNames(arr);
+    fContainer->ForEach(MParContainer, SetNames)(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the contents/setup of a parameter container/task from a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Int_t MParList::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (print)
+        *fLog << all << "MParList::ReadEnv: " << prefix << endl;
+
+    MParContainer *cont = NULL;
+
+    MIter Next(fContainer);
+    while ((cont=Next()))
+    {
+        if (cont->InheritsFrom("MTaskList"))
+        {
+            if (cont->ReadEnv(env, prefix, print)==kERROR)
+                return kERROR;
+            continue;
+        }
+
+        if (cont->TestEnv(env, prefix, print)==kERROR)
+            return kERROR;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the contents/setup of a parameter container/task to a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_t MParList::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    MParContainer *cont = NULL;
+
+    MIter Next(fContainer);
+    while ((cont=Next()))
+        if (!cont->WriteEnv(env, prefix, print))
+            return kFALSE;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Can be used to create an iterator over all containers, eg:
+//   MParList plist;
+//   TIter Next(plist); // Be aware: Use a object here rather than a pointer!
+//   TObject *o=0;
+//   while ((o=Next()))
+//   {
+//       [...]
+//   }
+//
+MParList::operator TIterator*() const
+{
+    return new TOrdCollectionIter(fContainer);
+}
Index: /tags/Mars-V0.9/mbase/MParList.h
===================================================================
--- /tags/Mars-V0.9/mbase/MParList.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MParList.h	(revision 9772)
@@ -0,0 +1,107 @@
+#ifndef MARS_MParList
+#define MARS_MParList
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MParList                                                                //
+//                                                                         //
+// List of parameter containers (MParContainer)                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TClass;
+class TOrdCollection;
+
+class MLog;
+class MTask;
+class MTaskList;
+
+class MParList : public MParContainer
+{
+private:
+    TOrdCollection *fContainer;	 // Collection of Parameter and Data Containers
+    TOrdCollection *fAutodelete; //! All what this list contains is deleted in the destructor
+
+    static TString GetClassName(const char *classname);
+    static TString GetObjectName(const char *classname, const char *objname);
+
+    enum { kIsOwner = BIT(14) };
+
+    void StreamPrimitive(ofstream &out) const;
+
+public:
+    enum { kDoNotReset = BIT(17), kIsProcessing = BIT(18) };
+
+    MParList(const char *name=NULL, const char *title=NULL);
+    MParList(MParList &ts);
+
+    virtual ~MParList();
+
+    Bool_t AddToList(MParContainer *obj, MParContainer *where = NULL);
+    void   AddToList(TObjArray *list);
+
+    Bool_t Replace(MParContainer *obj);
+    void   Remove(MParContainer *obj);
+
+    void SetLogStream(MLog *log);
+    void SetDisplay(MStatusDisplay *d);
+
+    TObject   *FindObject(const char *name) const;
+    TObject   *FindObject(const TObject *obj) const;
+
+    TObject   *FindObject(const char *name, const char *classname) const;
+    TObject   *FindObject(const TObject *obj, const char *classname) const;
+
+    MTask     *FindTask(const char *name, const char *tlist="MTaskList") const;
+    MTaskList *FindTaskListWithTask(const char *name) const;
+    MTaskList *FindTaskListWithTask(const MTask *task) const;
+
+    MParContainer *FindCreateObj(const char *classname, const char *objname=NULL);
+
+    TObjArray FindObjectList(const char *name, UInt_t first, const UInt_t last) const;
+    TObjArray FindObjectList(const char *name, const UInt_t num) const
+    {
+        return FindObjectList(name, 0, num);
+    }
+
+    TObjArray FindCreateObjList(const char *cname, UInt_t first, const UInt_t last, const char *oname=NULL);
+    TObjArray FindCreateObjList(const char *cname, const UInt_t num, const char *oname=NULL)
+    {
+        return FindCreateObjList(cname, 0, num, oname);
+    }
+
+    static TObjArray CreateObjList(const char *cname, UInt_t first, const UInt_t last, const char *oname=NULL);
+    static TObjArray CreateObjList(const char *cname, const UInt_t num, const char *oname=NULL)
+    {
+        return CreateObjList(cname, 0, num, oname);
+    }
+
+    void Reset();
+    void SetReadyToSave(Bool_t flag=kTRUE);
+
+    void SetOwner(Bool_t enable=kTRUE);
+    Bool_t IsOwner() const { return TestBit(kIsOwner); }
+
+    void Print(Option_t *t = NULL) const;
+
+    void GetNames(TObjArray &arr) const;
+    void SetNames(TObjArray &arr);
+
+    void SavePrimitive(ofstream &out, Option_t *o="");
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+    operator TIterator*() const;
+
+    ClassDef(MParList, 1) // list of parameter containers (MParContainer)
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MPrint.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MPrint.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MPrint.cc	(revision 9772)
@@ -0,0 +1,157 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  10/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MPrint                                                                  //
+//                                                                          //
+//  This task calls the Print() function of a parameter container, to       //
+//  print some information event by event.                                  //
+//  Overload TObject::Print()                                               //
+//                                                                          //
+//  Input Containers:                                                       //
+//   MParContainer                                                          //
+//                                                                          //
+//  Output Containers:                                                      //
+//   -/-                                                                    //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MPrint.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MPrint);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes name and title of the object. It is called by all
+// constructors.
+//
+void MPrint::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPrint";
+    fTitle = title ? title : "Task to print a parameter container";
+
+    fObject = NULL;
+}
+
+MPrint::MPrint()
+{
+    Init(0, 0);
+    SetBit(kSeparator);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. Remembers the name to search for in the parameter list
+//  of the object to be printed. The object must be derived from TObject and
+//  TObject::Print(Option_t *) const
+//  must be overloaded. You can also set an option string to use
+//  when calling TObject::Print
+//  If you want that the MPrint instance is removed from the tasklist
+//  if the container to be printed is not found in the PreProcess, call:
+//     MPrint::EnableSkip();
+//
+MPrint::MPrint(const char *obj, const char *option,
+               const char *name, const char *title)
+{
+    Init(name, title);
+    SetOption(option);
+
+    fObjName = obj;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. Remember the pointer of the object which has to be
+//  printed. The object must be derived from TObject and
+//  TObject::Print(Option_t *) const
+//  must be overloaded. You can also set an option string to use
+//  when calling TObject::Print
+//  if the container to be printed is not found in the PreProcess, call:
+//     MPrint::EnableSkip();
+//
+MPrint::MPrint(const TObject *obj, const char *option,
+               const char* name, const char *title)
+{
+    Init(name, title);
+    SetOption(option);
+
+    fObject  = obj;
+    fObjName = obj->GetName();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Checks the parameter list for the existance of the parameter container. If
+//  the name of it was given in the constructor.
+//
+Int_t MPrint::PreProcess(MParList *pList)
+{
+    //
+    // The pointer is already given by the user.
+    //
+    if (fObject || TestBit(kSeparator))
+        return kTRUE;
+
+    //
+    // Try to find the parameter container with the given name in the list
+    //
+    fObject = pList->FindObject(fObjName);
+    if (fObject)
+        return kTRUE;
+
+    //
+    // If it couldn't get found stop Eventloop
+    //
+    if (TestBit(kSkip))
+    {
+        *fLog << warn << fObjName << " not found... removing task from list." << endl;
+        return kSKIP;
+    }
+    else
+    {
+        *fLog << err << fObjName << " not found... aborting." << endl;
+        return kFALSE;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calls overloaded TObject::Print
+//
+Int_t MPrint::Process()
+{
+    if (TestBit(kSeparator))
+        gLog.Separator() << endl;
+    else
+        fObject->Print(fOption);
+    return kTRUE;
+} 
+
Index: /tags/Mars-V0.9/mbase/MPrint.h
===================================================================
--- /tags/Mars-V0.9/mbase/MPrint.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MPrint.h	(revision 9772)
@@ -0,0 +1,36 @@
+#ifndef MARS_MPrint
+#define MARS_MPrint
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class MPrint : public MTask
+{
+private:
+    const TObject *fObject;  // pointer to container which has to be printed
+    TString fObjName;        // given name to search for in the parameterlist
+    TString fOption;         // Print option
+
+    enum { kSkip = BIT(14), kSeparator = BIT(15) };
+
+    void Init(const char *name, const char *title);
+
+public:
+    MPrint();
+    MPrint(const char *obj,    const char *option="", const char *name=NULL, const char *title=NULL);
+    MPrint(const TObject *obj, const char *option="", const char *name=NULL, const char *title=NULL);
+
+    void SetOption(Option_t *option) { fOption = option; }
+    void EnableSkip(Bool_t skip=kTRUE) { skip ? SetBit(kSkip) : ResetBit(kSkip); }
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    ClassDef(MPrint, 0) // Task to call Print() function
+};
+    
+#endif
+
Index: /tags/Mars-V0.9/mbase/MProgressBar.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MProgressBar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MProgressBar.cc	(revision 9772)
@@ -0,0 +1,90 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 9/2002 <mailto:tbretz@astro-uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MProgressBar
+//
+// Simple window with progress bar. Can be used in an eventloop.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MProgressBar.h"
+
+#include <TSystem.h>        // gSystem
+#include <TGProgressBar.h>  // TGHProgressBar
+
+#include "MGList.h"
+
+ClassImp(MProgressBar);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Opens a window with a progress bar. Get a pointer
+// to the bar by calling GetBar. This pointer can be used for the
+// eventloop.
+//
+// Be carefull: killing or closing the window while the progress meter
+//   is still in use may cause segmentation faults. Please kill the window
+//   always by deleting the corresponding object.
+//
+MProgressBar::MProgressBar() : TGTransientFrame(gClient->GetRoot(), gClient->GetRoot(), 1, 1)
+{
+    fList = new MGList;
+    fList->SetOwner();
+
+    //SetMWMHints(0, 0, 0);
+
+    SetWMSizeHints(150, 15, 640, 480, 10, 10); // set the smallest and biggest size of the Main frame
+    Move(rand()%100+50, rand()%100+50);
+    Resize(150, 30);
+
+    TGLayoutHints *laybar=new TGLayoutHints(kLHintsExpandX|kLHintsExpandY, 2,2,2,2);
+    fList->Add(laybar);
+
+    fBar=new TGHProgressBar(this);
+    fBar->ShowPosition();
+    AddFrame(fBar, laybar);
+    fList->Add(fBar);
+
+    Layout();
+
+    MapSubwindows();
+
+    SetWindowName("Progress");
+    SetIconName("Progress");
+
+    MapWindow();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destruct the window with all its tiles. Also the Progress Bar object
+// is deleted.
+//
+MProgressBar::~MProgressBar()
+{
+    delete fList;
+} 
+
Index: /tags/Mars-V0.9/mbase/MProgressBar.h
===================================================================
--- /tags/Mars-V0.9/mbase/MProgressBar.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MProgressBar.h	(revision 9772)
@@ -0,0 +1,33 @@
+#ifndef MARS_MProgressBar
+#define MARS_MProgressBar
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TGFrame
+#include <TGFrame.h>
+#endif
+
+class MGList;
+class TGProgressBar;
+class TGHProgressBar;
+
+class MProgressBar : public TGTransientFrame
+{
+private:
+    MGList         *fList;
+    TGHProgressBar *fBar;
+
+public:
+     MProgressBar();
+     virtual ~MProgressBar();
+
+     TGProgressBar *GetBar() const { return (TGProgressBar*)fBar; }
+
+     ClassDef(MProgressBar, 0)   // A simple progress bar window for the Eventloop
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mbase/MReadSocket.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MReadSocket.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MReadSocket.cc	(revision 9772)
@@ -0,0 +1,314 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni.wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MReadSocket
+//
+// This class acts like a standard C++ istream, but read from a socket
+// (ifstream works similar)
+//
+// ios::io_state:
+// --------------
+// eof()  or ios::eofbit:  Connection closed or not established
+// fail() or ios::failbit: Error trying to establish connection or
+//                         waiting for data in underflow() timed out
+// good() tells you that everything is ok and we can read from the stream
+//
+// Example:
+// --------
+//
+//    Double_t d;
+//
+//    MReadSocket sin(1024); // open port 1024
+//
+//    sin >> d;
+//    sin.read((char*)&d, sizeof(Double_t));
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReadSocket.h"
+
+#include <unistd.h>          // usleep
+
+#include <TMath.h>           // TMath::Min
+#include <TTime.h>           // TTime
+#include <TDatime.h>         // TDatime
+#include <TSystem.h>         // gSystem
+#include <TSocket.h>         // TSocket
+#include <TServerSocket.h>   // TServerSocket
+
+ClassImp(MReadSocket);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// You can use the constructor in two ways:
+//
+//    MReadSocket read(7000);
+// This opens the socket and blocks until the connection has been
+// established.
+//
+//    MReadSocket read;
+// Returns immidiatly. The connection will be opend by calling
+//    read.Open(7000);
+//
+MReadSocket::MReadSocket(int port, int mtu) : istream(this), fMtu(mtu), fTimeout(2500), fServSock(NULL), fRxSocket(NULL)
+{
+    fBuffer = new char[mtu];
+
+    setg(fBuffer, fBuffer, fBuffer+1);
+
+    clear(ios::eofbit);
+
+    if (port>0)
+        Open(port);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. Close an possible open connection and delete the fBuffer
+//
+MReadSocket::~MReadSocket()
+{
+    Close();
+    delete fBuffer;
+}
+
+void MReadSocket::OpenServerSocket(int port)
+{
+    if (fServSock)
+        return;
+
+    cout << "Starting server socket on port #" << port << "..." << endl;
+
+    while (!fServSock)
+    {
+        fServSock=new TServerSocket(port, kTRUE);
+        if (fServSock->IsValid())
+            continue;
+
+        cout << "ServerSocket not valid: ";
+        switch (fServSock->GetErrorCode())
+        {
+        case  0: cout << "No error." << endl; break;
+        case -1: cout << "low level socket() call failed." << endl; break;
+        case -2: cout << "low level bind() call failed." << endl; break;
+        case -3: cout << "low level listen() call failed." << endl; break;
+        default: cout << "Unknown." << endl; break;
+        }
+
+        Close();
+        clear(ios::failbit);
+        return;
+    }
+
+    fServSock->SetOption(kNoBlock, 1);
+}
+
+void MReadSocket::OpenConnection(Bool_t block)
+{
+    do
+    {
+        const TTime timeout = gSystem->Now() + TTime(5000);
+
+        TDatime now;
+        cout << now.AsString() << ": Waiting for connection..." << endl;
+
+        //
+        // fRxSocket<0  means: No connection,non-blocking mode
+        // fRxSocket==0 means: Error
+        // This is only done until timeout is reached
+        //
+        while (fRxSocket==0 && gSystem->Now()<timeout)
+        {
+            fRxSocket = fServSock->Accept();
+            if (fRxSocket==0)
+            {
+                cout << "MReadSocket::OpenConnection: ERROR - TServerSock::Accept()" << endl;
+                setstate(ios::failbit);
+                return;
+            }
+            if ((Long_t)fRxSocket<0)
+                fRxSocket=NULL;
+
+            usleep(10);
+        }
+
+        //
+        // No connection has been established. Restart waiting for
+        // connection except we are in non-blocking mode.
+        //
+        if (fRxSocket==0)
+            continue;
+
+        //
+        // Check if the established connection is valid
+        //
+        if (fRxSocket->IsValid())
+        {
+            cout << "Connection established..." << endl;
+            fRxSocket->SetOption(kNoBlock, 1);
+            clear();
+            return;
+        }
+
+        cout << "TSocket: Connection not valid..." << endl;
+        delete fRxSocket;
+        fRxSocket=NULL;
+        setstate(ios::failbit);
+        return;
+
+    } while (block);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Open the connectionj on port port. Wait until the connection has
+//  been established. If an error occures and the connection cannot
+//  be established return kFALSE. To check whether an error occured
+//  use operator!() or operator void*() or fail()
+//
+Bool_t MReadSocket::Open(int port, Bool_t block)
+{
+    //
+    // If no port is given use the port given in the constructor
+    //
+    if (port<=0)
+        port = fPort;
+
+    //
+    // Remember port for later uses
+    //
+    if (fPort<=0)
+        fPort = port;
+
+    //
+    // Check whether a connection has already been established
+    //
+    if (fServSock)
+    {
+        //
+        // Check whether the connection has the right port
+        //
+        if (fServSock->GetLocalPort()!=port)
+            Close();
+    }
+
+    //
+    // Check whether port is valid
+    //
+    if (port<=0)
+    {
+        cout << "Invalid port #" << port << "!" << endl;
+        clear(ios::failbit);
+        return kFALSE;
+    }
+
+    //
+    // Start server socket...
+    //
+    OpenServerSocket(port);
+    if (!fServSock)
+        return kFALSE;
+
+    OpenConnection(block);
+    if (!fRxSocket)
+        return kFALSE;
+
+    underflow();
+    return kTRUE;
+}
+
+void MReadSocket::Close()
+{
+    if (fRxSocket)
+    {
+        delete fRxSocket;
+        fRxSocket=NULL;
+    }
+    if (fServSock)
+    {
+        const Int_t port = fServSock->GetLocalPort();
+
+        delete fServSock;
+        fServSock=NULL;
+
+        cout << "Connection on Port #" << port << " closed." << endl;
+    }
+
+    clear(ios::eofbit);
+}
+
+// --------------------------------------------------------------------------
+//
+// This is called to flush the buffer of the streaming devices
+//
+int MReadSocket::sync()
+{
+    cout << "sync" << endl;
+    return 0;
+}
+
+int MReadSocket::underflow()
+{
+    // FIXME:     vvvvv is this correct?
+    if (fail() || eof())
+    {
+        setg(fBuffer, fBuffer, fBuffer+fMtu);
+        return 0;
+    }
+
+    //
+    // This simple trick should do its job, because the
+    // TCP/IP stream is buffered already
+    //
+    const TTime timeout = fTimeout+gSystem->Now();
+
+    Int_t len=-1;
+    while (len<0 && gSystem->Now()<timeout)
+    {
+        Int_t l;
+        fRxSocket->GetOption(kBytesToRead, l);
+        if (l==0)
+        {
+            gSystem->Sleep(1);
+            continue;
+        }
+        len = fRxSocket->RecvRaw(fBuffer, TMath::Min(fMtu, l));
+    }
+
+    if (len<0)
+    {
+        cout << "MReadSocket: TSocket::RecvRaw - Connection timed out." << endl;
+        setstate(ios::failbit);
+        memset(fBuffer, 0, fMtu);
+        len = fMtu;
+    }
+
+    setg(fBuffer, fBuffer, fBuffer+len);
+    return 0;
+}
Index: /tags/Mars-V0.9/mbase/MReadSocket.h
===================================================================
--- /tags/Mars-V0.9/mbase/MReadSocket.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MReadSocket.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MReadSocket
+#define MARS_MReadSocket
+
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+#ifndef ROOT_TTime
+#include <TTime.h>
+#endif
+
+#include <iostream>  // base classes for MReadSocket
+
+class TSocket;
+class TServerSocket;
+
+class MReadSocket : public std::streambuf, public std::istream
+{
+private:
+    char *fBuffer; //!
+
+    int   fPort;
+    int   fMtu;
+    TTime fTimeout;
+
+    TServerSocket  *fServSock;
+    TSocket        *fRxSocket;
+
+    void OpenServerSocket(int port);
+    void OpenConnection(Bool_t block);
+
+    int underflow();
+    int sync();
+
+public:
+    MReadSocket(int port=-1, int mtu=1500);
+    MReadSocket(MReadSocket const& log) : istream((std::streambuf*)&log)
+    {
+    }
+    ~MReadSocket();
+
+    Bool_t Open(int port=-1, Bool_t block=kFALSE);
+    void   Close();
+
+    void SetTimeout(UInt_t millisec) { fTimeout = millisec; }
+
+    ClassDef(MReadSocket, 0) // This is what we call 'The logging system'
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MRunIter.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MRunIter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MRunIter.cc	(revision 9772)
@@ -0,0 +1,142 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Javier Rico,  4/2004 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRunIter
+//
+//  Use this to iterate over run-files giving only the run-number.
+//
+//  You need the specify the run-file root-directory (eg /data/MAGIC).
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRunIter.h"
+
+#include <TSystem.h>
+#include <iostream>
+
+ClassImp(MRunIter);
+
+using namespace std;
+
+Int_t MRunIter::AddRun(UInt_t run, const char *path)
+{
+    TString p(path);
+
+    if (p.IsNull())
+        p = fPath;
+
+    if (p.IsNull())
+        p = ".";
+
+    // R. DeLosReyes and T. Bretz
+    // Changes to read the DAQ numbering format. Changes takes place
+    // between runs 35487 and 00035488 (2004_08_30)
+    const char *fmt;
+    if(fIsStandardFile)
+      {
+        fmt = "%05d-%s";
+        fIsRawFile = kFALSE;
+      }
+    else
+      fmt = run>35487 ? "*_%08d_*_%s" : "*_%05d_*_%s";
+
+    MDirIter Next;
+    Next.AddDirectory(p, Form(fmt, run,fIsRawFile?"*.raw":"*.root"), -1);
+
+    const TString name(Next());
+    if (name.IsNull())
+        return 0;
+
+    AddRunNumber(run);
+
+    return AddDirectory(gSystem->DirName(name), gSystem->BaseName(name), -1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add runs specified in a character chain with the format:
+// run1,run2-run3,run4-run5,...
+// e.g  if runrange="100,105-107,110-112,115" 
+// runs 100,105,106,107,110,111,112 and 115 are included in the iterator list
+//
+Int_t MRunIter::AddRuns(const char* runrange, const char* path)
+{ 
+    const TString chcopy(runrange);
+  
+    Ssiz_t last=0;
+    Int_t  lowrun=-1;
+    UInt_t totdir=0;
+  
+    // loop over the elements of the character chain 
+    for (Int_t i=0;i<chcopy.Length();i++)
+    {
+        // look for a digit, a '-' or a ',' 
+        const char c=chcopy[i];
+        if (! ((c>='0' && c<='9') || c=='-' || c==','))
+            return totdir;
+        
+        // if '-' is found, save the previous number as initial run
+        if (c=='-' && lowrun<0 && i>last)
+        {
+            const TSubString chrun = chcopy(last,i-last);
+            lowrun=atoi(chrun.Data());	  	  
+            last=i+1;
+            continue;
+        }
+        // if ',' or the end of the string are found, save the previous run or run range
+        if (c==',' && i>last)
+        {
+            const TSubString chrun = chcopy(last,i-last);
+            const Int_t up=atoi(chrun.Data());
+            if(lowrun>=0 && lowrun<=up)
+                totdir+=AddRuns(lowrun,up,path);
+            else if(lowrun<0)
+                totdir+=AddRun(up,path);
+            
+            lowrun=-1;
+            last=i+1;
+            continue;
+        }
+  
+        // if find two continous separators exit
+        if ((c=='-' && i==last) || (c==',' && i==last))
+            return totdir;
+    }
+  
+    // save last run range
+    const TSubString chrun = chcopy(last,chcopy.Length()-last);
+    const Int_t upprun=atoi(chrun.Data());
+    if(lowrun>=0 && lowrun<=upprun)
+    {
+        totdir+=AddRuns(lowrun,upprun,path);
+        return totdir;
+    }
+  
+    if(lowrun<0)
+        totdir+=AddRun(upprun,path);
+  
+    return totdir;
+}
Index: /tags/Mars-V0.9/mbase/MRunIter.h
===================================================================
--- /tags/Mars-V0.9/mbase/MRunIter.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MRunIter.h	(revision 9772)
@@ -0,0 +1,89 @@
+#ifndef MARS_MRunIter
+#define MARS_MRunIter
+
+#ifndef MARS_MDirIter
+#include "MDirIter.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MRunIter : public MDirIter
+{
+private:
+    TString fPath;
+    TArrayI fRuns;
+
+    Bool_t fIsRawFile;
+    Bool_t fIsStandardFile;
+
+    void AddRunNumber(UInt_t run)
+    {
+        fRuns.Set(fRuns.GetSize()+1);
+        fRuns[fRuns.GetSize()-1] = run;
+
+        SortRuns();
+
+    }
+
+    void SortRuns()
+    {
+        const int n = GetNumRuns();
+
+        TArrayI idx(n);
+        TMath::Sort(n, fRuns.GetArray(), idx.GetArray(), kFALSE);
+
+        for (int i=0; i<n; i++)
+            idx[i] = fRuns[idx[i]];
+
+        fRuns = idx;
+    }
+
+public:
+    MRunIter(const char *path=0) : fPath(path), fIsRawFile(0), fIsStandardFile(kFALSE) { }
+
+    void SetRawFile(Bool_t filetype) { fIsRawFile = filetype; }
+    void SetStandardFile(Bool_t filetype) { fIsStandardFile = filetype; }
+
+    Int_t AddRun(UInt_t run, const char *path=0);
+    Int_t AddRuns(const char* runrange, const char *path=0);
+    Int_t AddRuns(UInt_t from, UInt_t to, const char *path=0)
+    {
+        Int_t n = 0;
+
+        for (UInt_t i=from; i<=to; i++)
+            AddRun(i, path);
+
+        return n;
+    }
+
+    UInt_t GetNumRuns() const { return fRuns.GetSize(); }
+    const TArrayI &GetRuns() const { return fRuns; }
+
+    TString GetRunsAsString() const {
+        TString txt;
+        for (int i=0; i<fRuns.GetSize(); i++)
+        {
+            txt += "#";
+            txt += fRuns[i];
+            if (i!=fRuns.GetSize()-1)
+                txt += " ";
+        }
+        return txt;
+    }
+    TString GetRunsAsFileName() const {
+        TString txt;
+        for (int i=0; i<fRuns.GetSize(); i++)
+        {
+            txt += fRuns[i];
+            if (i!=fRuns.GetSize()-1)
+                txt += "_";
+        }
+        return txt;
+    }
+
+    ClassDef(MRunIter, 1) // Iterator for runs
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MSearch.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MSearch.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MSearch.cc	(revision 9772)
@@ -0,0 +1,210 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 9/2002 <mailto:tbretz@astro-uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MSearch
+//
+// Simple search dialog (usefull for TGTextViews)
+//
+// Sends: kC_USER, KS_START, mp1, txt
+//
+//   with mp1: bit0 on=case sensitive
+//             bit1 on=backward
+//        mp2: char* pointing to the text to search for
+//
+// WARNING: Do not store mp2, immeditaly copy the text to a local
+//          location!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSearch.h"
+
+#include <TSystem.h>      // gSystem
+#include <TGLabel.h>      // TGLabel
+#include <TGButton.h>     // TGButton
+#include <TGTextEntry.h>  // TGTextEntry
+
+#include "MGList.h"
+
+ClassImp(MSearch);
+
+enum
+{
+    kSearchText, kCase, kDirection, kSearch, kCancel
+};
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. w is the window which will receive the message.
+// Id is currently useless.
+//
+MSearch::MSearch(const TGWindow *w, Int_t id) : TGTransientFrame(gClient->GetRoot(), gClient->GetRoot(), 1, 1), TGWidget(id)
+{
+    Associate(w);
+
+    fList = new MGList;
+    fList->SetOwner();
+
+    // set the smallest and biggest size of the Main frame
+    SetWMSizeHints(320, 110, 250, 50, 0, 0);
+    Move(rand()%100+50, rand()%100+50);
+
+    // -------------------------------------------------------------
+
+    TGLayoutHints *lay4=new TGLayoutHints(kLHintsNormal|kLHintsExpandX);
+    TGLayoutHints *lay0=new TGLayoutHints(kLHintsNormal|kLHintsExpandX, 4, 8, 4);
+    TGLayoutHints *lay1=new TGLayoutHints(kLHintsNormal,  6, 4, 8);
+    TGLayoutHints *lay2=new TGLayoutHints(kLHintsNormal, 69, 4, 4, 4);
+    TGLayoutHints *lay3=new TGLayoutHints(kLHintsNormal, 69, 4, 4, 4);
+    TGLayoutHints *lay5=new TGLayoutHints(kLHintsNormal,  5, 5, 5);
+    TGLayoutHints *lay7=new TGLayoutHints(kLHintsCenterX);
+
+    // -------------------------------------------------------------
+    //  Create Widgets
+    // -------------------------------------------------------------
+
+    TGHorizontalFrame  *f = new TGHorizontalFrame(this, 1, 1);
+    TGLabel        *label = new TGLabel(this, "Find Text:");
+    TGTextEntry    *entry = new TGTextEntry(f, "", kSearchText);
+    TGCheckButton   *box1 = new TGCheckButton(this, "Match upper/lower case", kCase);
+    TGCheckButton   *box2 = new TGCheckButton(this, "Search backward", kDirection);
+    TGHorizontalFrame *f2 = new TGHorizontalFrame(this, 1, 1);
+    TGHorizontalFrame *f3 = new TGHorizontalFrame(f2, 1, 1);
+    TGTextButton    *txt1 = new TGTextButton(f3, "Search", kSearch);
+    TGTextButton    *txt2 = new TGTextButton(f3, "Cancel", kCancel);
+
+    txt1->Associate(this);
+    txt2->Associate(this);
+
+    // -------------------------------------------------------------
+    //  Layout the widgets in the frame
+    // -------------------------------------------------------------
+
+    AddFrame(f, lay4);
+    f->AddFrame(label, lay1);
+    f->AddFrame(entry, lay0);
+    AddFrame(box1, lay2);
+    AddFrame(box2, lay3);
+    AddFrame(f2, lay4);
+    f2->AddFrame(f3, lay7);
+    f3->AddFrame(txt1, lay5);
+    f3->AddFrame(txt2, lay5);
+
+    // -------------------------------------------------------------
+
+    entry->Associate(this);
+    txt1->Associate(this);
+    txt1->Associate(this);
+
+    // -------------------------------------------------------------
+
+    fList->Add(lay0);
+    fList->Add(lay1);
+    fList->Add(lay2);
+    fList->Add(lay3);
+    fList->Add(lay4);
+    fList->Add(lay5);
+    fList->Add(lay7);
+    fList->Add(f);
+    fList->Add(f2);
+    fList->Add(f3);
+    fList->Add(label);
+    fList->Add(entry);
+    fList->Add(box1);
+    fList->Add(box2);
+    fList->Add(txt1);
+    fList->Add(txt2);
+
+    // -------------------------------------------------------------
+
+    Layout();
+
+    MapSubwindows();
+
+    SetWindowName("Search in Text");
+    SetIconName("Search");
+
+    MapWindow();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destruct the window with all its tiles and widgets.
+//
+MSearch::~MSearch()
+{
+    delete fList;
+}
+
+// --------------------------------------------------------------------------
+//
+// Send the search message to the associated TGWindow.
+// See class description.
+//
+Bool_t MSearch::SendSearch()
+{
+    if (!fMsgWindow)
+        return kTRUE;
+
+    const TGCheckButton &b1 = *(TGCheckButton*)fList->FindWidget(kCase);
+    const TGCheckButton &b2 = *(TGCheckButton*)fList->FindWidget(kDirection);
+    const TGTextEntry   &e  = *(TGTextEntry*)  fList->FindWidget(kSearchText);
+
+    const Long_t msg = MK_MSG(kC_USER, (EWidgetMessageTypes)kS_START);
+    const Long_t mp1 = (b1.GetState()<<1) | b2.GetState();
+    const Long_t mp2 = (Long_t)e.GetText();
+
+    SendMessage(fMsgWindow, msg, mp1, mp2);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Process messages from the widgets.
+//
+Bool_t MSearch::ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2)
+{
+    // Can be found in WidgetMessageTypes.h
+    switch (GET_MSG(msg))
+    {
+    case kC_COMMAND:
+        switch (GET_SUBMSG(msg))
+        {
+        case kCM_BUTTON:
+            switch (mp1)
+            {
+            case kSearch:
+                return SendSearch();
+            case kCancel:
+                delete this;
+                return kTRUE;
+            }
+            return kTRUE;
+
+        }
+        return kTRUE;
+    }
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mbase/MSearch.h
===================================================================
--- /tags/Mars-V0.9/mbase/MSearch.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MSearch.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MSearch
+#define MARS_MSearch
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TGFrame
+#include <TGFrame.h>
+#endif
+
+#ifndef ROOT_TGWidget
+#include <TGWidget.h>
+#endif
+
+enum EMarsWidgetMessageTypes {
+    kS_START = 1
+};
+
+class MGList;
+
+class MSearch : public TGTransientFrame, public TGWidget
+{
+private:
+    MGList *fList;
+
+    Bool_t SendSearch();
+    void CloseWindow() { delete this; }
+
+public:
+    MSearch(const TGWindow *w, Int_t id=-1);
+    virtual ~MSearch();
+
+    Bool_t ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2);
+
+    ClassDef(MSearch, 0)   // A simple progress bar window for the Eventloop
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mbase/MStatusArray.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MStatusArray.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MStatusArray.cc	(revision 9772)
@@ -0,0 +1,187 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 03/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MStatusArray
+//
+//  Helper class for MStatusDisplay
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MStatusArray.h"
+
+#include <TClass.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MStatusArray);
+
+using namespace std;
+
+TObject *MStatusArray::DisplayIn(Option_t *o) const
+{
+    MStatusDisplay *d = 0;
+    if (TString(o).IsNull())
+        d = new MStatusDisplay;
+
+    if (!d)
+        d = (MStatusDisplay*)gROOT->GetListOfSpecials()->FindObject(o);
+
+    if (!d)
+        return 0;
+
+    if (d->Display(*this))
+        return d;
+
+    delete d;
+    return 0;
+}
+
+TObject *MStatusArray::FindObjectInPad(TVirtualPad *pad, const char *object, TClass *cls) const
+{
+    TObject *o = pad->FindObject(object);
+    if (o && o->InheritsFrom(cls))
+        return o;
+
+    TIter Next(pad->GetListOfPrimitives());
+    while ((o=Next()))
+    {
+        if (o==pad || !o->InheritsFrom(TVirtualPad::Class()))
+            continue;
+
+        if ((o = FindObjectInPad((TVirtualPad*)o, object, cls)))
+            if (o->InheritsFrom(cls))
+                return o;
+    }
+    return 0;
+}
+
+// FIXME: Move to a general class MMARS (TROOT) and unify with MParContainer
+TClass *MStatusArray::GetClass(const char *name) const
+{
+    TClass *cls = gROOT->GetClass(name);
+    Int_t rc = 0;
+    if (!cls)
+        rc =1;
+    else
+    {
+        if (!cls->Property())
+            rc = 5;
+        if (!cls->Size())
+            rc = 4;
+        if (!cls->IsLoaded())
+            rc = 3;
+        if (!cls->HasDefaultConstructor())
+            rc = 2;
+    }
+
+    if (rc==0)
+        return cls;
+
+    gLog << err << dbginf << "Class '" << name << "' not in dictionary: ";
+    switch (rc)
+    {
+    case 1:
+        gLog << "gROOT->GetClass() returned NULL." << endl;
+        return NULL;
+    case 2:
+        gLog << "no default constructor." << endl;
+        return NULL;
+    case 3:
+        gLog << "not loaded." << endl;
+        return NULL;
+    case 4:
+        gLog << "zero size." << endl;
+        return NULL;
+    case 5:
+        gLog << "no property." << endl;
+        return NULL;
+    }
+
+    gLog << "THIS SHOULD NEVER HAPPEN!" << endl;
+
+    return 0;
+}
+
+TCanvas *MStatusArray::FindCanvas(const char *name) const
+{
+    TObject *o = TObjArray::FindObject(name);
+    if (!o)
+        return 0;
+
+    return o->InheritsFrom(TCanvas::Class()) ? (TCanvas*)o : 0;
+}
+
+
+TObject *MStatusArray::FindObjectInCanvas(const char *object, const char *base, const char *canvas) const
+{
+    TClass *cls = GetClass(base);
+    if (!cls)
+        return 0;
+
+    TCanvas *c = canvas ? FindCanvas(canvas) : 0;
+    if (canvas)
+    {
+        if (!c)
+            return 0;
+
+        TObject *o = FindObjectInPad(c, object, cls);
+        if (!o)
+            return 0;
+
+        return o->InheritsFrom(cls) ? o : 0;
+    }
+
+    TObject *o=0;
+    TIter Next(this);
+    while ((o=Next()))
+    {
+        if (!o->InheritsFrom(TVirtualPad::Class()))
+            continue;
+
+        if ((o=FindObjectInPad((TVirtualPad*)c, object, cls)))
+            return o;
+    }
+
+    return NULL;
+}
+
+TObject *MStatusArray::FindObjectInCanvas(const char *object, const char *canvas) const
+{
+    return FindObjectInCanvas(object, object, canvas);
+}
+
+TObject *MStatusArray::FindObject(const char *object, const char *base) const
+{
+    return FindObjectInCanvas(object, base, 0);
+}
+
+TObject *MStatusArray::FindObject(const char *object) const
+{
+    return FindObjectInCanvas(object, object, 0);
+}
Index: /tags/Mars-V0.9/mbase/MStatusArray.h
===================================================================
--- /tags/Mars-V0.9/mbase/MStatusArray.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MStatusArray.h	(revision 9772)
@@ -0,0 +1,34 @@
+#ifndef MARS_MStatusArray
+#define MARS_MStatusArray
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class TClass;
+class TCanvas;
+class TVirtualPad;
+
+class MStatusArray : public TObjArray
+{
+private:
+    TObject *FindObjectInPad(TVirtualPad *pad, const char *object, TClass *base) const;
+    TClass  *GetClass(const char *name) const;
+
+public:
+    TObject *DisplayIn(Option_t *o=0) const;         // *MENU*
+    TObject *Display() const { return DisplayIn(); } // *MENU*
+
+    TCanvas *FindCanvas(const char *name) const;
+
+    TObject *FindObjectInCanvas(const char *object, const char *base, const char *canvas) const;
+    TObject *FindObjectInCanvas(const char *object, const char *canvas) const;
+
+    TObject *FindObject(const char *object, const char *base) const;
+    TObject *FindObject(const char *object) const;
+    TObject *FindObject(const TObject *o) const { return 0; }
+
+    ClassDef(MStatusArray, 0) // Helper class for status display
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MStatusDisplay.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MStatusDisplay.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MStatusDisplay.cc	(revision 9772)
@@ -0,0 +1,2510 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2003-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MStatusDisplay
+//
+// This status display can be used (and is used) to display results in
+// a tabbed window. The window can be written to and read from a root file
+// (see Read and Write) or printed as a postscript file (see SaveAsPS).
+//
+// To write gif files of C-Macros use SaveAsGif() or SaveAsC().
+// Direct printing to the default printer (via lpr) can be done by
+// PrintToLpr().
+//
+// It has also to half status lines which can be used to display the status
+// or something going on. Together with the status lines it has a progress
+// bar which can display the progress of a job or loop.
+// Access the progress bar by GetProgressBar()
+//
+// To add a new tab and get a pointer to the newly created TCanvas
+// use AddTab.
+//
+// If you have a MStatusDisplay and you are not sure whether it was
+// destroyed by the user meanwhile use:
+//   gROOT->GetListOfSpecials()->FindObject(pointer);
+// Each MStatusDisplay is added to list list by its constructor and
+// removed from the list by the destructor.
+//
+// You can redirect an output to a MLog-logstream by calling SetLogStream().
+// To disable redirction call SetLogStream(NULL)
+//
+// Because updates to the tabs are only done/displayed if a tab is active
+// using the gui doesn't make things slower (<1%) if the first (legend
+// tab) is displayed. This gives you the possibility to look into
+// the current progress of a loop without loosing more time than the
+// single update of the tab.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MStatusDisplay.h"
+
+#include <fstream>                // fstream
+
+#include <TH1.h>                  // TH1::AddDirectory
+#include <TLine.h>                // TLine
+#include <TText.h>                // TText
+#include <TFile.h>                // gFile
+#include <TFrame.h>               // TFrame
+#include <TStyle.h>               // gStyle
+#include <TCanvas.h>              // TCanvas
+#include <TSystem.h>              // gSystem
+#include <TDatime.h>              // TDatime
+#include <TRandom.h>              // TRandom
+#include <TThread.h>              // TThread::Self()
+#include <TBrowser.h>             // TBrowser
+#include <TObjArray.h>            // TObjArray
+#include <TPostScript.h>          // TPostScript
+#include <TMethodCall.h>          // TMethodCall
+
+//#include <TRint.h>                // gApplication, TRint::Class()
+#include <TInterpreter.h>         // gInterpreter
+
+#include <TGTab.h>                // TGTab
+#include <TGLabel.h>              // TGLabel
+#include <TG3DLine.h>             // TGHorizontal3DLine
+#include <TGButton.h>             // TGPictureButton
+#include <TGTextView.h>           // TGTextView
+#include <TGComboBox.h>           // TGComboBox
+#include <TGStatusBar.h>          // TGStatusBar
+#include <TGFileDialog.h>         // TGFileDialog
+#include <TGProgressBar.h>        // TGHProgressBar
+#include <TRootEmbeddedCanvas.h>  // TRootEmbeddedCanvas
+
+#include "MString.h"
+
+#include "MLog.h"                 // MLog
+#include "MLogManip.h"            // inf, warn, err
+
+#include "MGList.h"               // MGList
+#include "MGMenu.h"               // MGMenu, TGMenu
+#include "MSearch.h"              // MSearch
+#include "MParContainer.h"        // MParContainer::GetDescriptor
+#include "MStatusArray.h"         // MStatusArray
+
+#undef DEBUG
+//#define DEBUG
+
+ClassImp(MStatusDisplay);
+
+using namespace std;
+
+// ------------ Workaround for a non working TGTextView::Search -------------
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,05)
+class MGTextView : public TGTextView
+{
+public:
+    MGTextView(const TGWindow *parent, UInt_t w, UInt_t h, Int_t id = -1,
+               UInt_t sboptions = 0, ULong_t back = GetWhitePixel()) :
+    TGTextView(parent, w, h, id, sboptions, back) {}
+    MGTextView(const TGWindow *parent, UInt_t w, UInt_t h, TGText *text,
+               Int_t id = -1, UInt_t sboptions = 0, ULong_t back = GetWhitePixel()) :
+    TGTextView(parent, w, h, text, id, sboptions, back) {}
+    MGTextView(const TGWindow *parent, UInt_t w, UInt_t h, const char *string,
+               Int_t id = -1, UInt_t sboptions = 0, ULong_t back = GetWhitePixel()) :
+    TGTextView(parent, w, h, string, id, sboptions, back) {}
+
+    void Mark(Long_t xPos, Long_t yPos) { TGTextView::Mark(xPos, yPos); }
+    void UnMark()                       { TGTextView::UnMark(); }
+
+    Bool_t Search(const char *string, Bool_t direction, Bool_t caseSensitive)
+    {
+        // Taken from TGTextView::Search and modified.
+
+        TGLongPosition pos, pos2;
+        pos2.fX = pos2.fY = 0;
+        if (fIsMarked) {
+            if (!direction)
+            {
+                pos2.fX = fMarkedStart.fX;
+                pos2.fY = fMarkedStart.fY;
+            }
+            else
+            {
+                pos2.fX = fMarkedEnd.fX + 1;
+                pos2.fY = fMarkedEnd.fY;
+            }
+        }
+        if (!fText->Search(&pos, pos2, string, direction, caseSensitive))
+            return kFALSE;
+        UnMark();
+        fIsMarked = kTRUE;
+        fMarkedStart.fY = fMarkedEnd.fY = pos.fY;
+        fMarkedStart.fX = pos.fX;
+        fMarkedEnd.fX = fMarkedStart.fX + strlen(string);
+        pos.fY = ToObjYCoord(fVisible.fY);
+        if ((fMarkedStart.fY < pos.fY) ||
+            (ToScrYCoord(fMarkedStart.fY) >= (Int_t)fCanvas->GetHeight()))
+            pos.fY = fMarkedStart.fY;
+        pos.fX = ToObjXCoord(fVisible.fX, pos.fY);
+        if ((fMarkedStart.fX < pos.fX) ||
+            (ToScrXCoord(fMarkedStart.fX, pos.fY) >= (Int_t)fCanvas->GetWidth()))
+            pos.fX = fMarkedStart.fX;
+
+        SetVsbPosition((ToScrYCoord(pos.fY) + fVisible.fY)/fScrollVal.fY);
+        SetHsbPosition((ToScrXCoord(pos.fX, pos.fY) + fVisible.fX)/fScrollVal.fX);
+        DrawRegion(0, (Int_t)ToScrYCoord(fMarkedStart.fY), fCanvas->GetWidth(),
+                   UInt_t(ToScrYCoord(fMarkedEnd.fY+1) - ToScrYCoord(fMarkedEnd.fY)));
+
+        return kTRUE;
+    }
+};
+#else
+#define MGTextView TGTextView
+#endif
+
+// --------------------------------------------------------------------------
+
+// --------------------------------------------------------------------------
+//
+// Add menu bar to the GUI
+//
+void MStatusDisplay::AddMenuBar()
+{
+    //
+    // File Menu
+    //
+    MGPopupMenu *filemenu = new MGPopupMenu(gClient->GetRoot());
+    // filemenu->AddEntry("Save &As...", kFileSaveAs);
+    filemenu->AddEntry("New Can&vas",   kFileCanvas);
+    filemenu->AddEntry("New &Browser",  kFileBrowser);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("Save status.&ps",   kFileSaveAsPS);
+    filemenu->AddEntry("Save status.&gif",  kFileSaveAsGIF);
+    filemenu->AddEntry("Save status.&C",    kFileSaveAsC);
+    filemenu->AddEntry("Save status.&root", kFileSaveAsRoot);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("&Open...",             kFileOpen);
+    filemenu->AddEntry("Save &As...",          kFileSaveAs);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("Re&set",               kFileReset);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("Print with &lpr",      kFilePrint);
+    //filemenu->AddEntry("Set printer &name",    kFilePrinterName);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("C&lose", kFileClose);
+    filemenu->AddEntry("E&xit", kFileExit);
+    filemenu->Associate(this);
+
+    //
+    // Tab Menu
+    //
+    MGPopupMenu *tabmenu = new MGPopupMenu(gClient->GetRoot());
+    tabmenu->AddEntry("Next [&+]",           kTabNext);
+    tabmenu->AddEntry("Previous [&-]",       kTabPrevious);
+    tabmenu->AddSeparator();
+    tabmenu->AddEntry("Save tab-i.&ps",   kTabSaveAsPS);
+    tabmenu->AddEntry("Save tab-i.&gif",  kTabSaveAsGIF);
+    tabmenu->AddEntry("Save tab-i.&C",    kTabSaveAsC);
+    tabmenu->AddEntry("Save tab-i.&root", kTabSaveAsRoot);
+    tabmenu->AddSeparator();
+    tabmenu->AddEntry("Save tab &As...",         kTabSaveAs);
+    tabmenu->AddSeparator();
+    tabmenu->AddEntry("Re&move",             kTabRemove);
+    tabmenu->AddSeparator();
+    tabmenu->AddEntry("Print with &lpr",     kTabPrint);
+    tabmenu->Associate(this);
+
+    //
+    // Loop Menu
+    //
+    MGPopupMenu *loopmenu = new MGPopupMenu(gClient->GetRoot());
+    loopmenu->AddEntry("&Stop", kLoopStop);
+    loopmenu->Associate(this);
+
+    //
+    // Loop Menu
+    //
+    MGPopupMenu *sizemenu = new MGPopupMenu(gClient->GetRoot());
+    sizemenu->AddEntry("Fit to 640x&480",   kSize640);
+    sizemenu->AddEntry("Fit to 800x&600",   kSize800);
+    sizemenu->AddEntry("Fit to 960x7&20",   kSize960);
+    sizemenu->AddEntry("Fit to 1024x&768",  kSize1024);
+    sizemenu->AddEntry("Fit to 1280x&1024", kSize1280);
+    sizemenu->Associate(this);
+
+    //
+    // Log Menu
+    //
+    MGPopupMenu *logmenu = new MGPopupMenu(gClient->GetRoot());
+    logmenu->AddEntry("&Copy Selected", kLogCopy);
+    logmenu->AddEntry("Cl&ear all",     kLogClear);
+    logmenu->AddSeparator();
+    logmenu->AddEntry("Select &All",    kLogSelect);
+    logmenu->AddSeparator();
+    logmenu->AddEntry("&Find...",       kLogFind);
+    logmenu->AddSeparator();
+    logmenu->AddEntry("&Save",          kLogSave);
+    logmenu->AddEntry("Save &append",   kLogAppend);
+    logmenu->Associate(this);
+
+    //
+    // Menu Bar
+    //
+    TGLayoutHints *layitem = new TGLayoutHints(kLHintsNormal, 0, 4, 0, 0);
+    fList->Add(layitem);
+
+    MGMenuBar *menubar = new MGMenuBar(this, 1, 1, kHorizontalFrame);
+    menubar->AddPopup("&File", filemenu, layitem);
+    menubar->AddPopup("Lo&g",  logmenu,  layitem);
+    menubar->AddPopup("&Size", sizemenu, layitem);
+    menubar->AddPopup("&Tab",  tabmenu,  layitem);
+    menubar->AddPopup("&Loop", loopmenu, layitem);
+    menubar->BindKeys(this);
+    AddFrame(menubar);
+
+    //
+    // Line below menu bar
+    //
+    TGLayoutHints *laylinesep  = new TGLayoutHints(kLHintsTop|kLHintsExpandX);
+    fList->Add(laylinesep);
+
+    TGHorizontal3DLine *linesep = new TGHorizontal3DLine(this);
+    AddFrame(linesep, laylinesep);
+
+    //
+    // Add everything to autodel list
+    //
+    fList->Add(filemenu);
+    fList->Add(loopmenu);
+    fList->Add(sizemenu);
+    fList->Add(menubar);
+    fList->Add(tabmenu);
+    fList->Add(logmenu);
+    fList->Add(linesep);
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds an empty TGCompositeFrame which might be filled by the user
+//
+void MStatusDisplay::AddUserFrame()
+{
+    TGLayoutHints *lay=new TGLayoutHints(kLHintsExpandX);
+    fList->Add(lay);
+
+    fUserFrame = new TGCompositeFrame(this, 1, 1);
+    AddFrame(fUserFrame, lay);
+    fList->Add(fUserFrame);
+}
+
+char *rot128(char *c)
+{
+    char *rc=c;
+    while (*c) *c++ += 128;
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the title tab
+//
+void MStatusDisplay::AddMarsTab()
+{
+    // Create Tab1
+    TGCompositeFrame *f = fTab->AddTab("-=MARS=-");
+
+    // Add list of tabs
+
+    TGComboBox *filter = new TGComboBox(f, kTabs);
+    fList->Add(filter);
+    filter->Associate(this);
+    filter->AddEntry("-=MARS=-", 0);
+    filter->Select(0);
+
+    TGLayoutHints *lay3 = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 10, 5);
+    fList->Add(lay3);
+    f->AddFrame(filter, lay3);
+
+    // Add MARS version
+    TGLabel *l = new TGLabel(f, MString::Form("Official Release: V%s", MARSVER));
+    fList->Add(l);
+
+    filter->SetWidth(l->GetWidth());
+    filter->SetHeight(4*l->GetHeight()/3);
+
+    TGLayoutHints *layb = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 5, 5);
+    fList->Add(layb);
+    f->AddFrame(l, layb);
+
+    // Add root version
+    l = new TGLabel(f, MString::Form("Using ROOT v%s", ROOTVER));
+    fList->Add(l);
+
+    TGLayoutHints *lay = new TGLayoutHints(kLHintsCenterX|kLHintsTop);
+    fList->Add(lay);
+    f->AddFrame(l, lay);
+
+    // Add Mars logo picture
+    const TGPicture *pic2 = fList->GetPicture("marslogo.xpm");
+    if (pic2)
+    {
+        TGPictureButton *mars  = new TGPictureButton(f, pic2, kPicMars);
+        fList->Add(mars);
+        mars->Associate(this);
+
+        TGLayoutHints *lay2 = new TGLayoutHints(kLHintsCenterX|kLHintsCenterY, 10, 10, 5, 5);
+        fList->Add(lay2);
+        f->AddFrame(mars, lay2);
+    }
+
+    // Add date and time
+    TDatime d;
+    l = new TGLabel(f, d.AsString());
+    fList->Add(l);
+    f->AddFrame(l, lay);
+
+    // Add copyright notice
+    l = new TGLabel(f, "(c) MAGIC Software Development, 2000-2004");
+    fList->Add(l);
+    f->AddFrame(l, layb);
+
+    TGLayoutHints *layc = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 0, 5);
+    fList->Add(layc);
+
+    char *txt = "<< Thomas Bretz >>";
+    l = new TGLabel(f, txt);
+    fList->Add(l);
+    f->AddFrame(l, layc);
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds the logbook tab to the GUI if it was not added previously.
+//
+// The logbook is updated four times a second only if the tab is visible.
+//
+// You can redirect an output to a MLog-logstream by calling SetLogStream().
+// To disable redirction call SetLogStream(NULL)
+//
+// if enable==kFALSE the stdout is disabled/enabled. Otherwise stdout
+// is ignored.
+//
+void MStatusDisplay::SetLogStream(MLog *log, Bool_t enable)
+{
+    if (gROOT->IsBatch())
+        return;
+
+    if (log && fLogBox==NULL)
+    {
+        fLogIdx = fTab->GetNumberOfTabs();
+
+        // Create Tab1
+        TGCompositeFrame *f = AddRawTab("-Logbook-");//fTab->AddTab("-Logbook-");
+
+        // Create Text View
+        fLogBox = new MGTextView(f, 1, 1); // , -1, 0, TGFrame::GetDefaultFrameBackground());
+        if (fFont)
+            fLogBox->SetFont(fFont);
+        //fLogBox->Associate(this);
+
+        // Add List box to the tab
+        TGLayoutHints *lay = new TGLayoutHints(kLHintsNormal|kLHintsExpandX|kLHintsExpandY,2,2,2,2);
+        f->AddFrame(fLogBox, lay);
+
+        // layout and map tab
+        Layout();
+        MapSubwindows();
+
+        // make it visible
+        // FIXME: This is a workaround, because TApplication::Run is not
+        //        thread safe against ProcessEvents. We assume, that if
+        //        we are not in the Main-Thread ProcessEvents() is
+        //        called by the TApplication Event Loop...
+        if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+            gClient->ProcessEventsFor(fTab);
+    }
+
+    if (log)
+    {
+        fLog = log;
+
+        log->SetOutputGui(fLogBox, kTRUE);
+        log->EnableOutputDevice(MLog::eGui);
+        if (!enable)
+            log->DisableOutputDevice(MLog::eStdout);
+
+        fLogTimer.Start();
+    }
+    else
+    {
+        fLogTimer.Stop();
+
+        fLog->DisableOutputDevice(MLog::eGui);
+        fLog->SetOutputGui(NULL);
+        if (!enable)
+            fLog->EnableOutputDevice(MLog::eStdout);
+
+        fLog = &gLog;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the Tabs and the predifined Tabs to the GUI
+//
+void MStatusDisplay::AddTabs()
+{
+    fTab = new TGTab(this, 300, 300);
+
+    AddMarsTab();
+
+    // Add fTab to Frame
+    TGLayoutHints *laytabs = new TGLayoutHints(kLHintsNormal|kLHintsExpandX|kLHintsExpandY, 5, 5, 5);
+    AddFrame(fTab, laytabs);
+
+    fList->Add(fTab);
+    fList->Add(laytabs);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the progress bar to the GUI. The Progress Bar range is set to
+// (0,1) as default.
+//
+void MStatusDisplay::AddProgressBar()
+{
+    TGLayoutHints *laybar=new TGLayoutHints(kLHintsExpandX, 5, 5, 5, 5);
+    fList->Add(laybar);
+
+    fBar=new TGHProgressBar(this);
+    fBar->SetRange(0, 1);
+    fBar->ShowPosition();
+    AddFrame(fBar, laybar);
+    fList->Add(fBar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the progress bar position between 0 and 1. The Progress bar range
+// is assumed to be (0,1)
+//
+void MStatusDisplay::SetProgressBarPosition(Float_t p)
+{
+    fBar->SetPosition(p);
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds the status bar to the GUI
+//
+void MStatusDisplay::AddStatusBar()
+{
+    fStatusBar = new TGStatusBar(this, 1, 1);
+
+    //
+    // Divide it like the 'Golden Cut' (goldener Schnitt)
+    //
+    //     1-a     a
+    // 1: ------|----
+    //
+    // a/(1-a) = (1-a)/1
+    // a^2+a-1 = 0
+    //       a = (-1+-sqrt(1+4))/2 = sqrt(5)/2-1/2 = 0.618
+    //
+    Int_t p[2] = {38, 62};
+
+    fStatusBar->SetParts(p, 2);
+
+    TGLayoutHints *layb = new TGLayoutHints(kLHintsNormal|kLHintsExpandX, 5, 4, 0, 3);
+    AddFrame(fStatusBar, layb);
+
+    fList->Add(fStatusBar);
+    fList->Add(layb);
+}
+
+// --------------------------------------------------------------------------
+//
+// Change the text in the status line 1
+//
+void MStatusDisplay::SetStatusLine1(const char *txt)
+{
+    if (gROOT->IsBatch())
+        return;
+    fStatusBar->SetText(txt, 0);
+
+    // FIXME: This is a workaround, because TApplication::Run is not
+    //        thread safe against ProcessEvents. We assume, that if
+    //        we are not in the Main-Thread ProcessEvents() is
+    //        called by the TApplication Event Loop...
+    if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+        gClient->ProcessEventsFor(fStatusBar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Change the text in the status line 2
+//
+void MStatusDisplay::SetStatusLine2(const char *txt)
+{
+    if (gROOT->IsBatch())
+        return;
+
+    fStatusBar->SetText(txt, 1);
+
+    // FIXME: This is a workaround, because TApplication::Run is not
+    //        thread safe against ProcessEvents. We assume, that if
+    //        we are not in the Main-Thread ProcessEvents() is
+    //        called by the TApplication Event Loop...
+    if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+        gClient->ProcessEventsFor(fStatusBar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Display information about the name of a container
+//
+void MStatusDisplay::SetStatusLine2(const MParContainer &cont)
+{
+    SetStatusLine2(MString::Form("%s: %s", cont.GetDescriptor().Data(), cont.GetTitle()));
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Opens a window with a progress bar. Get a pointer
+// to the bar by calling GetBar. This pointer can be used for the
+// eventloop.
+//
+// Be carefull: killing or closing the window while the progress meter
+//   is still in use may cause segmentation faults. Please kill the window
+//   always by deleting the corresponding object.
+//
+// Update time default: 10s
+//
+MStatusDisplay::MStatusDisplay(Long_t t)
+: TGMainFrame(NULL, 1, 1), fName("MStatusDisplay"), fLog(&gLog), fTab(NULL), fTimer(this, t, kTRUE), fStatus(kLoopNone), fLogIdx(-1), fLogTimer(this, 250, kTRUE), fLogBox(NULL), fIsLocked(0)
+{
+    // p==NULL means: Take gClient->GetRoot() if not in batch mode
+    // see TGWindow::TGWindow()
+
+    //
+    // This is a possibility for the user to check whether this
+    // object has already been deleted. It will be removed
+    // from the list in the destructor.
+    //
+//    gROOT->GetListOfSpecials()->Add(this);
+
+    fFont = gVirtualX->LoadQueryFont("7x13bold");
+    fMutex = new TMutex;
+
+    //
+    // In case we are in batch mode use a list of canvases
+    // instead of the Root Embedded Canvases in the TGTab
+    //
+    fBatch = new TList;
+    fBatch->SetOwner();
+
+    //
+    // Create a list handling GUI widgets
+    //
+    fList = new MGList;
+    fList->SetOwner();
+
+    //
+    // Create the layout hint for the root embedded canavses
+    //
+    fLayCanvas = new TGLayoutHints(kLHintsExpandX|kLHintsExpandY);
+    fList->Add(fLayCanvas);
+
+    //
+    // Add Widgets (from top to bottom)
+    //
+    if (gClient) // BATCH MODE
+    {
+        AddMenuBar();
+        AddUserFrame();
+        AddTabs();
+        AddProgressBar();
+        AddStatusBar();
+    }
+
+    //
+    // set the smallest and biggest size of the Main frame
+    // and move it to its appearance position
+    SetWMSizeHints(570, 480, 1280, 980, 1, 1);
+    MoveResize(rand()%100+570, rand()%100+480, 570, 480);
+
+    //
+    // Now do an automatic layout of the widgets and display the window
+    //
+    Layout();
+    MapSubwindows();
+
+    SetWindowName("Status Display");
+    SetIconName("Status Display");
+
+    MapWindow();
+
+    // FIXME: This is a workaround, because TApplication::Run is not
+    //        thread safe against ProcessEvents. We assume, that if
+    //        we are not in the Main-Thread ProcessEvents() is
+    //        called by the TApplication Event Loop...
+    if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+        gSystem->ProcessEvents();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destruct the window with all its tiles. Also the Progress Bar object
+// is deleted.
+//
+MStatusDisplay::~MStatusDisplay()
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,01)
+    fTab = NULL; // See HandleEvent
+#endif
+
+    //
+    // Delete object from global object table so it cannot
+    // be deleted by chance a second time
+    //
+    gInterpreter->DeleteGlobal(this);
+
+    //
+    // This is a possibility for the user to check whether this
+    // object has already been deleted. It has been added
+    // to the list in the constructor.
+    //
+    gROOT->GetListOfSpecials()->Remove(this);
+
+    SetLogStream(NULL);
+
+    //
+    // Delete the list of objects corresponding to this object
+    //
+    delete fList;
+
+    //
+    // Delete the list of canvases used in batch mode
+    // instead of the Root Embedded Canvases in the TGTab
+    //
+    delete fBatch;
+
+    //
+    // Delete the font used for the logging window
+    //
+    if (fFont)
+        gVirtualX->DeleteFont(fFont);
+
+    //
+    // Delete mutex
+    //
+    delete fMutex;
+}
+
+// --------------------------------------------------------------------------
+//
+// Takes a TGCompositeFrame as argument. Searches for the first
+// TRootEmbeddedCanvas which is contained by it and returns a pointer
+// to the corresponding TCanvas. If it isn't found NULL is returned.
+//
+TRootEmbeddedCanvas *MStatusDisplay::GetEmbeddedCanvas(TGCompositeFrame *cf) const
+{
+    TIter Next(cf->GetList());
+
+    TGFrameElement *f;
+    while ((f=(TGFrameElement*)Next()))
+        if (f->fFrame->InheritsFrom(TRootEmbeddedCanvas::Class()))
+            return (TRootEmbeddedCanvas*)f->fFrame;
+
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Takes a TGCompositeFrame as argument. Searches for the first
+// TRootEmbeddedCanvas which is contained by it and returns a pointer
+// to the corresponding TCanvas. If it isn't found NULL is returned.
+//
+TCanvas *MStatusDisplay::GetCanvas(TGCompositeFrame *cf) const
+{
+    TRootEmbeddedCanvas *ec = GetEmbeddedCanvas(cf);
+    return ec ? ec->GetCanvas() : NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns GetCanvas of the i-th Tab.
+//
+TCanvas *MStatusDisplay::GetCanvas(int i) const
+{
+    if (gROOT->IsBatch())
+        return (TCanvas*)fBatch->At(i-1);
+
+    if (i<0 || i>=fTab->GetNumberOfTabs())
+    {
+        *fLog << warn << "MStatusDisplay::GetCanvas: Out of range." << endl;
+        return NULL;
+    }
+
+    return GetCanvas(fTab->GetTabContainer(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns j-th pad of the i-th Tab. 
+// Sets the pad to fill an entire window.
+//
+// This function can be used if single pad's out of an MStatusDisplay 
+// have to be stored to file. 
+//
+// ATTENTION: This function modifies the requested tab in MStatusDisplay itself!
+//
+TVirtualPad *MStatusDisplay::GetFullPad(const Int_t i, const Int_t j)
+{
+  
+  TVirtualPad *vpad = GetCanvas(i)->GetPad(j);
+  if (vpad)
+    vpad->SetPad(0.,0.,1.,1.);
+  else
+    *fLog << warn << "MStatusDisplay::GetFullPad: Pad is out of range." << endl;
+
+  return vpad;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Searches for a TRootEmbeddedCanvas in the TGCompositeFramme of the
+// Tab with the name 'name'. Returns the corresponding TCanvas or
+// NULL if something isn't found.
+//
+TCanvas *MStatusDisplay::GetCanvas(const TString &name) const
+{
+    if (gROOT->IsBatch())
+        return (TCanvas*)fBatch->FindObject(name);
+
+    TGFrameElement *f;
+    TIter Next(fTab->GetList());
+    while ((f=(TGFrameElement*)Next()))
+    {
+        TObject *frame = f->fFrame;
+        if (!frame->InheritsFrom(TGTabElement::Class()))
+            continue;
+
+        TGTabElement *tab = (TGTabElement*)frame;
+        if (tab->GetString()==name)
+            break;
+    }
+
+    // Search for the next TGCompositeFrame in the list
+    while ((f=(TGFrameElement*)Next()))
+    {
+        TObject *frame = f->fFrame;
+        if (frame->InheritsFrom(TGCompositeFrame::Class()))
+            return GetCanvas((TGCompositeFrame*)frame);
+    }
+
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls TCanvas::cd(), for the canvas returned by GetCanvas.
+//
+Bool_t MStatusDisplay::CdCanvas(const TString &name)
+{
+    TCanvas *c = GetCanvas(name);
+    if (!c)
+        return kFALSE;
+
+    c->cd();
+    return kTRUE;
+}
+
+TGCompositeFrame *MStatusDisplay::AddRawTab(const char *name)
+{
+    // Add new tab
+    TGCompositeFrame *f = fTab->AddTab(name);
+
+    TGComboBox *box = (TGComboBox*)fList->FindWidget(kTabs);
+    box->AddEntry(name, box->GetListBox()->GetNumberOfEntries());
+
+    // layout and map new tab
+    Layout();
+    MapSubwindows();
+    Layout();
+
+    // display new tab in the main frame
+    // FIXME: This is a workaround, because TApplication::Run is not
+    //        thread safe against ProcessEvents. We assume, that if
+    //        we are not in the Main-Thread ProcessEvents() is
+    //        called by the TApplication Event Loop...
+    if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+        gClient->ProcessEventsFor(fTab);
+
+    *fLog << inf << "Adding Raw Tab '" << name << "' (" << f->GetWidth() << "x";
+    *fLog << f->GetHeight() << ")" << endl;
+
+    // return pointer to new canvas
+    return f;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function was connected to all created canvases. It is used
+// to redirect GetObjectInfo into our own status bar.
+//
+// The 'connection' is done in AddTab
+//
+void MStatusDisplay::EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected)
+{
+    //  Writes the event status in the status bar parts
+    if (!selected)
+        return;
+
+    TCanvas *c = (TCanvas*)gTQSender;
+
+    TVirtualPad* save=gPad;
+
+    gPad = c ? c->GetSelectedPad() : NULL;
+
+    if (gPad)
+        SetStatusLine2(selected->GetObjectInfo(px,py));
+
+    gPad=save;
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds a new tab with the name 'name'. Adds a TRootEmbeddedCanvas to the
+// tab and returns a reference to the corresponding TCanvas.
+//
+TCanvas &MStatusDisplay::AddTab(const char *name)
+{
+    if (gROOT->IsBatch())
+    {
+        TCanvas *c = new TCanvas(name, name);
+        fBatch->Add(c);
+        return *c;
+    }
+
+    // Add new tab
+    TGCompositeFrame *f = fTab->AddTab(name);
+
+    // create root embedded canvas and add it to the tab
+    TRootEmbeddedCanvas *ec = new TRootEmbeddedCanvas(name, f, f->GetWidth(), f->GetHeight(), 0);
+    f->AddFrame(ec, fLayCanvas);
+    fList->Add(ec);
+
+    // set background and border mode of the canvas
+    TCanvas &c = *ec->GetCanvas();
+
+    c.SetFillColor(16/*165*//*17*//*203*/);
+    c.SetBorderMode(0);
+
+    // If kNoContextMenu set set kNoContextMenu of the canvas
+    if (TestBit(kNoContextMenu))
+        c.SetBit(kNoContextMenu);
+
+    // Connect all TCanvas::ProcessedEvent to this->EventInfo
+    // This means, that after TCanvas has processed an event
+    // EventInfo of this class is called, see TCanvas::HandleInput
+    c.Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",
+              "MStatusDisplay", this, "EventInfo(Int_t,Int_t,Int_t,TObject*)");
+
+    TGComboBox *box = (TGComboBox*)fList->FindWidget(kTabs);
+    box->AddEntry(name, box->GetListBox()->GetNumberOfEntries());
+
+    // layout and map new tab
+    Layout();          // seems to layout the TGCompositeFrame
+    MapSubwindows();   // maps the TGCompositeFrame
+    Layout();          // layout the embedded canvas in the frame
+
+    // display new tab in the main frame
+    // FIXME: This is a workaround, because TApplication::Run is not
+    //        thread safe against ProcessEvents. We assume, that if
+    //        we are not in the Main-Thread ProcessEvents() is
+    //        called by the TApplication Event Loop...
+    if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+        gClient->ProcessEventsFor(fTab);
+
+    *fLog << inf << "Adding Tab '" << name << "' (" << f->GetWidth() << "x";
+    *fLog << f->GetHeight() << ", TCanvas=" << &c << ")" << endl;
+
+    // return pointer to new canvas
+    return c;
+}
+
+// --------------------------------------------------------------------------
+//
+// Update a canvas in a tab, takes the corresponding TGCompositeFrame
+// as an argument. This is necessary, because not all functions
+// changing the contents of a canvas or pad can call SetModified()
+// for the corresponding tab. If this is not called correctly the
+// tab won't be updated calling TCanvas::Update(). So we simply
+// redraw it by our own (instead we could recursively call
+// TPad::Modified() for everything contained by the TCanvas and
+// call TCanvas::Update() afterwards)
+//
+void MStatusDisplay::UpdateTab(TGCompositeFrame *f)
+{
+    if (!f)
+        return;
+
+    TCanvas *c=GetCanvas(f);
+    if (!c)
+        return;
+
+    //
+    // If we are in a multithreaded environment (gThreadXAR) we
+    // have to make sure, that thus function is called from
+    // the main thread.
+    //
+    if (gThreadXAR)
+    {
+        // Tell the X-Requester how to call this method
+        TString str = MString::Form("%d", (ULong_t)f);
+
+        TMethodCall call(IsA(), "UpdateTab", "NULL");
+        void *arr[4] = { NULL, &call, this, (void*)(const char*)str };
+
+        // If this is not the main thread return
+        if (((*gThreadXAR)("METH", 4, arr, NULL)))
+            return;
+    }
+
+    //
+    // Secure calls to update the tabs against itself, at least
+    // c->Paint() or c->Flush() may crash X (bad drawable).
+    // This makes sure, that a X call is not interuppted by
+    // another X-call which was started from an gui interrrupt
+    // in the same thread
+    //
+    if (fMutex->TryLock())
+        return;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,02)
+    TPad *padsav = (TPad*)gPad;
+    if (!gPad)
+        c->cd();
+#endif
+
+    if (!c->IsBatch())
+        c->FeedbackMode(kFALSE);  // Goto double buffer mode
+
+    //
+    // Doing this ourself gives us the possibility to repaint
+    // the canvas in any case (Paint() instead of PaintModified())
+    //
+    c->Paint();                   // Repaint all pads
+    c->Flush();                   // Copy all pad pixmaps to the screen
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,02)
+    if (padsav)
+        padsav->cd();
+    else
+        gPad=NULL;
+#endif
+
+    //c->SetCursor(kCross);
+
+    // Old version
+    //c->Modified();
+    //c->Update();
+    //c->Paint();
+
+    fMutex->UnLock();
+}
+
+// --------------------------------------------------------------------------
+//
+// Saves the given canvas (pad) or all pads (num<0) as a temporary
+// postscript file and prints it using 'lpr'. If a printer name is set
+// via SetPrinter 'lpr -Pname' is used.
+//
+Int_t MStatusDisplay::PrintToLpr(Int_t num)
+{
+    TString name = "mars";
+
+    for (int i=0; i<6; i++)
+        name += (char)(gRandom->Uniform(25)+65);
+
+    name += ".ps";
+
+    const Int_t pages = SaveAsPS(num, name);
+
+    SetStatusLine1("Printing...");
+    SetStatusLine2("");
+
+    if (!pages)
+    {
+        *fLog << warn << "MStatusDisplay::PrintToLpr: Sorry, couldn't save file as temporary postscript!" << endl;
+        SetStatusLine2("Failed!");
+        return 0;
+    }
+
+    TString cmd="lpr ";
+    if (!fPrinter.IsNull())
+    {
+        cmd += "-P";
+        cmd += fPrinter;
+        cmd += " ";
+    }
+    cmd += name;
+
+    gSystem->Exec(cmd);
+    gSystem->Unlink(name);
+
+    SetStatusLine2(MString::Form("Done (%dpage(s))", pages));
+
+    return pages;
+}
+
+// --------------------------------------------------------------------------
+//
+// Remove tab no i if this tab contains a TRootEmbeddedCanvas
+//
+void MStatusDisplay::RemoveTab(int i)
+{
+    TGCompositeFrame *f = fTab->GetTabContainer(i);
+    if (!f)
+        return;
+
+    TRootEmbeddedCanvas *ec = GetEmbeddedCanvas(f);
+    if (!ec)
+        return;
+
+    TCanvas *c = ec->GetCanvas();
+    if (!c)
+        return;
+
+    const TString name(c->GetName());
+
+    f->RemoveFrame(ec);
+    delete fList->Remove(ec);
+
+    fTab->RemoveTab(i);
+    fTab->SetTab(0);
+
+    TGComboBox *box = (TGComboBox*)fList->FindWidget(kTabs);
+    box->RemoveEntry(i);
+    for (int j=i; j<box->GetListBox()->GetNumberOfEntries(); j++)
+    {
+        TGTextLBEntry *entry = (TGTextLBEntry *)box->GetListBox()->Select(j+1, kFALSE);
+        box->AddEntry(entry->GetText()->GetString(), j);
+        box->RemoveEntry(j+1);
+    }
+    box->GetListBox()->Select(0);
+
+    // Looks strange...
+    // const Int_t n = fTab->GetNumberOfTabs();
+    // fTab->SetTab(i<=n-1 ? i : i-1);
+
+    // layout and map new tab
+    Layout();          // seems to layout the TGCompositeFrame
+    MapSubwindows();   // maps the TGCompositeFrame
+    Layout();          // layout the embedded canvas in the frame
+
+    // display new tab in the main frame
+    // FIXME: This is a workaround, because TApplication::Run is not
+    //        thread safe against ProcessEvents. We assume, that if
+    //        we are not in the Main-Thread ProcessEvents() is
+    //        called by the TApplication Event Loop...
+    if (!TThread::Self()/*gApplication->InheritsFrom(TRint::Class())*/)
+        gClient->ProcessEventsFor(fTab);
+
+    *fLog << inf << "Removed Tab #" << i << " '" << name << "'" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this to check whether the MStatusDisplay still contains the
+// TCanvas c. It could be removed meanwhile by menu usage.
+//
+Bool_t MStatusDisplay::HasCanvas(const TCanvas *c) const
+{
+    if (!c)
+        return kFALSE;
+
+    if (gROOT->IsBatch())
+        return (Bool_t)fBatch->FindObject(c);
+
+    for (int i=1; i<fTab->GetNumberOfTabs(); i++)
+        if (c==GetCanvas(i))
+            return kTRUE;
+    return kFALSE;
+}
+
+/*
+    if (...)
+       fMenu->AddPopup("&CaOs", fCaOs, NULL);
+    else
+       fMenu->RemovePopup("CaOs");
+    fMenu->Resize(fMenu->GetDefaultSize());
+    MapSubwindows();
+    MapWindow();
+ */
+
+void MStatusDisplay::Reset()
+{
+    if (gROOT->IsBatch())
+    {
+        fBatch->Delete();
+        return;
+    }
+
+    for (int i=fTab->GetNumberOfTabs()-1; i>0; i--)
+        RemoveTab(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the kC_COMMAND, kCM_MENU  messages
+//
+Bool_t MStatusDisplay::ProcessMessageCommandMenu(Long_t id)
+{
+    switch (id)
+    {
+    case kLoopStop:
+    case kFileClose:
+    case kFileExit:
+        if (id==kFileExit || id==kFileClose)
+            if (Close())
+                delete this;
+        fStatus = (Status_t)id;
+        return kTRUE;
+
+    case kFileCanvas:
+        new TCanvas;
+        return kTRUE;
+
+    case kFileBrowser:
+        new TBrowser;
+        return kTRUE;
+
+    case kFileReset:
+        Reset();
+        return kTRUE;
+
+    case kFileOpen:
+        Open();
+        return kTRUE;
+
+    case kFileSaveAs:
+        SaveAs();
+        return kTRUE;
+
+    case kFileSaveAsPS:
+        SaveAsPS();
+        return kTRUE;
+
+    case kFileSaveAsGIF:
+        SaveAsGIF();
+        return kTRUE;
+
+    case kFileSaveAsC:
+        SaveAsC();
+        return kTRUE;
+
+    case kFileSaveAsRoot:
+        SaveAsRoot();
+        return kTRUE;
+
+    case kFilePrint:
+        PrintToLpr();
+        return kTRUE;
+
+    case kTabSaveAs:
+        SaveAs(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsPS:
+        SaveAsPS(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsGIF:
+        SaveAsGIF(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsC:
+        SaveAsC(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabSaveAsRoot:
+        SaveAsRoot(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabPrint:
+        PrintToLpr(fTab->GetCurrent());
+        return kTRUE;
+
+    case kTabNext:
+        fTab->SetTab(fTab->GetCurrent()+1);
+        return kTRUE;
+
+    case kTabPrevious:
+        fTab->SetTab(fTab->GetCurrent()-1);
+        return kTRUE;
+
+    case kTabRemove:
+        RemoveTab(fTab->GetCurrent());
+        return kTRUE;
+
+    case kSize640:
+        Resize(570, 480);
+        return kTRUE;
+    case kSize800:
+        Resize(740, 600);
+        return kTRUE;
+    case kSize960:
+        Resize(880, 700);
+        return kTRUE;
+    case kSize1024:
+        Resize(980, 768);
+        return kTRUE;
+    case kSize1280:
+        Resize(1280, 980);
+        return kTRUE;
+
+    case kLogClear:
+        fLogBox->Clear();
+        return kTRUE;
+    case kLogCopy:
+        fLogBox->Copy();
+        return kTRUE;
+    case kLogSelect:
+        fLogBox->SelectAll();
+        return kTRUE;
+    case kLogFind:
+        new MSearch(this);
+        return kTRUE;
+    case kLogSave:
+        SetStatusLine1("Saving log...");
+        SetStatusLine2("");
+        *fLog << inf << "Saving log... " << flush;
+        if (fLogBox->GetText()->Save("statusdisplay.log"))
+        {
+            *fLog << "done." << endl;
+            SetStatusLine2("done.");
+        }
+        else
+        {
+            *fLog << "failed!" << endl;
+            SetStatusLine2("Failed!");
+        }
+        return kTRUE;
+
+    case kLogAppend:
+        SetStatusLine1("Appending logg...");
+        SetStatusLine2("");
+        *fLog << inf << "Appending log... " << flush;
+        if (fLogBox->GetText()->Append("statusdisplay.log"))
+        {
+            *fLog << "done." << endl;
+            SetStatusLine2("done.");
+        }
+        else
+        {
+            *fLog << "failed!" << endl;
+            SetStatusLine2("Failed!");
+        }
+        return kTRUE;
+#ifdef DEBUG
+    default:
+        cout << "Command-Menu #" << id << endl;
+#endif
+    }
+    return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the kC_COMMAND messages
+//
+Bool_t MStatusDisplay::ProcessMessageCommand(Long_t submsg, Long_t mp1, Long_t mp2)
+{
+    switch (submsg)
+    {
+    case kCM_MENU: // 1
+        return ProcessMessageCommandMenu(mp1); // mp2=userdata
+    case kCM_TAB:  // 8
+        /*
+         for (int i=0; i<fTab->GetNumberOfTabs(); i++)
+         fTab->GetTabContainer(i)->UnmapWindow();
+         */
+        UpdateTab(fTab->GetTabContainer(mp1));
+        //fTab->GetTabContainer(mp1)->MapWindow();
+
+        /*
+        if (mp1>0)
+            fMenu->AddPopup("&CaOs", fCaOs, NULL);
+        else
+            fMenu->RemovePopup("CaOs");
+        fMenu->Resize(fMenu->GetDefaultSize());
+        MapSubwindows();
+        MapWindow();
+        */
+        return kTRUE;
+    case kCM_COMBOBOX: // 7
+        if (mp1==kTabs)
+            fTab->SetTab(mp2);
+        return kTRUE;
+#ifdef DEBUG
+    case kCM_MENUSELECT: // 2
+        cout << "Command-Menuselect #" << mp1 << " (UserData=" << (void*)mp2 << ")" << endl;
+        return kTRUE;
+
+    case kCM_BUTTON: // 3
+        cout << "Command-Button." << endl;
+        return kTRUE;
+
+    case kCM_CHECKBUTTON: // 4
+        cout << "Command-CheckButton." << endl;
+        return kTRUE;
+
+    case kCM_RADIOBUTTON: // 5
+        cout << "Command-RadioButton." << endl;
+        return kTRUE;
+
+    case kCM_LISTBOX: // 6
+        cout << "Command-Listbox #" << mp1 << " (LineId #" << mp2 << ")" << endl;
+        return kTRUE;
+    default:
+        cout << "Command: " << "Submsg:" << submsg << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+#endif
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the kC_TEXTVIEW messages
+//
+Bool_t MStatusDisplay::ProcessMessageTextview(Long_t submsg, Long_t mp1, Long_t mp2)
+{
+    // kC_TEXTVIEW, kTXT_ISMARKED, widget id, [true|false]                  //
+    // kC_TEXTVIEW, kTXT_DATACHANGE, widget id, 0                           //
+    // kC_TEXTVIEW, kTXT_CLICK2, widget id, position (y << 16) | x)         //
+    // kC_TEXTVIEW, kTXT_CLICK3, widget id, position (y << 16) | x)         //
+    // kC_TEXTVIEW, kTXT_F3, widget id, true                                //
+    // kC_TEXTVIEW, kTXT_OPEN, widget id, 0                                 //
+    // kC_TEXTVIEW, kTXT_CLOSE, widget id, 0                                //
+    // kC_TEXTVIEW, kTXT_SAVE, widget id, 0                                 //
+#ifdef DEBUG
+    switch (submsg)
+    {
+    case kTXT_ISMARKED:
+        cout << "Textview-IsMarked #" << mp1 << " " << (mp2?"yes":"no") << endl;
+        return kTRUE;
+
+    case kTXT_DATACHANGE:
+        cout << "Textview-DataChange #" << mp1 << endl;
+        return kTRUE;
+
+    case kTXT_CLICK2:
+        cout << "Textview-Click2 #" << mp1 << " x=" << (mp2&0xffff) << " y= " << (mp2>>16) << endl;
+        return kTRUE;
+
+    case kTXT_CLICK3:
+        cout << "Textview-Click3 #" << mp1 << " x=" << (mp2&0xffff) << " y= " << (mp2>>16) << endl;
+        return kTRUE;
+
+    case kTXT_F3:
+        cout << "Textview-F3 #" << mp1 << endl;
+        return kTRUE;
+
+    case kTXT_OPEN:
+        cout << "Textview-Open #" << mp1 << endl;
+        return kTRUE;
+
+    case kTXT_CLOSE:
+        cout << "Textview-Close #" << mp1 << endl;
+        return kTRUE;
+
+    case kTXT_SAVE:
+        cout << "Textview-Save #" << mp1 << endl;
+        return kTRUE;
+
+    default:
+        cout << "Textview: " << "Submsg:" << submsg << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+    }
+#endif
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the kC_USER messages
+//
+Bool_t MStatusDisplay::ProcessMessageUser(Long_t submsg, Long_t mp1, Long_t mp2)
+{
+    // kS_START, case sensitive | backward<<1, char *txt
+    switch (submsg)
+    {
+    case kS_START:
+        fLogBox->Search((char*)mp2, !(mp1&2>>1), mp1&1);
+        return kTRUE;
+#ifdef DEBUG
+    default:
+        cout << "User: " << "Submsg:" << submsg << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+#endif
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process the messages from the GUI
+//
+Bool_t MStatusDisplay::ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2)
+{
+    // Can be found in WidgetMessageTypes.h
+#ifdef DEBUG
+    cout << "Msg: " << GET_MSG(msg) << " Submsg:" << GET_SUBMSG(msg);
+    cout << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+#endif
+    switch (GET_MSG(msg))
+    {
+    case kC_COMMAND:  // 1
+        return ProcessMessageCommand(GET_SUBMSG(msg), mp1, mp2);
+
+    case kC_TEXTVIEW: // 9
+        return ProcessMessageTextview(GET_SUBMSG(msg), mp1, mp2);
+
+    case kC_USER:     // 1001
+        return ProcessMessageUser(GET_SUBMSG(msg), mp1, mp2);
+    }
+#ifdef DEBUG
+    cout << "Msg: " << GET_MSG(msg) << " Submsg:" << GET_SUBMSG(msg);
+    cout << " Mp1=" << mp1 << " Mp2=" << mp2 << endl;
+#endif
+    return kTRUE;
+}
+
+Bool_t MStatusDisplay::Close()
+{
+    // Got close message for this MainFrame. Calls parent CloseWindow()
+    // (which destroys the window) and terminate the application.
+    // The close message is generated by the window manager when its close
+    // window menu item is selected.
+
+    // CloseWindow must be overwritten because otherwise CloseWindow
+    // and the destructor are calling DestroyWindow which seems to be
+    // in conflict with the TRootEmbeddedCanvas.
+
+    // FIXME: Make sure that the Status Display is deleted from every
+    //        where (eg Eventloop) first!
+
+    //gLog << dbg << fName << " is on heap: " << (int)IsOnHeap() << endl;
+
+    if (TestBit(kExitLoopOnExit) || TestBit(kExitLoopOnClose))
+    {
+        //gLog << dbg << "CloseWindow() calling ExitLoop." << endl;
+        gSystem->ExitLoop();
+    }
+
+    if (fIsLocked<=0 && IsOnHeap())
+        return kTRUE;
+
+    fStatus = kFileExit;
+    return kFALSE;
+}
+
+void MStatusDisplay::CloseWindow()
+{
+    Close();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls SetBit(kNoContextMenu) for all TCanvas objects found in the
+// Tabs.
+//
+void MStatusDisplay::SetNoContextMenu(Bool_t flag)
+{
+    if (fIsLocked>1 || gROOT->IsBatch())
+        return;
+
+    flag ? SetBit(kNoContextMenu) : ResetBit(kNoContextMenu);
+
+    for (int i=1; i<fTab->GetNumberOfTabs(); i++)
+    {
+        TCanvas *c = GetCanvas(i);
+        if (c)
+            flag ? c->SetBit(kNoContextMenu) : c->ResetBit(kNoContextMenu);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Updates the canvas (if existing) in the currenly displayed Tab.
+// The update intervall is controlled by StartUpdate and StopUpdate
+//
+Bool_t MStatusDisplay::HandleTimer(TTimer *timer)
+{
+    if (gROOT->IsBatch())
+        return kTRUE;
+
+    const Int_t c = fTab->GetCurrent();
+
+    // Skip Legend Tab
+    if (c==0)
+        return kTRUE;
+
+    // Update a canvas tab (if visible)
+    if (timer==&fTimer && c!=fLogIdx)
+    {
+        UpdateTab(fTab->GetCurrentContainer());
+        return kTRUE;
+    }
+
+    // update the logbook tab (if visible)
+    if (timer==&fLogTimer && c==fLogIdx)
+    {
+        fLog->UpdateGui();
+
+        /*
+        if (!fLogBox->TestBit(kHasChanged))
+            return kTRUE;
+
+            fLogBox->ResetBit(kHasChanged);
+            */
+        return kTRUE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draws a clone of a canvas into a new canvas. Taken from TCanvas.
+//
+void MStatusDisplay::DrawClonePad(TCanvas &newc, TCanvas &oldc) const
+{
+    //copy pad attributes
+    newc.Range(oldc.GetX1(),oldc.GetY1(),oldc.GetX2(),oldc.GetY2());
+    newc.SetTickx(oldc.GetTickx());
+    newc.SetTicky(oldc.GetTicky());
+    newc.SetGridx(oldc.GetGridx());
+    newc.SetGridy(oldc.GetGridy());
+    newc.SetLogx(oldc.GetLogx());
+    newc.SetLogy(oldc.GetLogy());
+    newc.SetLogz(oldc.GetLogz());
+    newc.SetBorderSize(oldc.GetBorderSize());
+    newc.SetBorderMode(oldc.GetBorderMode());
+    ((TAttLine&)oldc).Copy((TAttLine&)newc);
+    ((TAttFill&)oldc).Copy((TAttFill&)newc);
+    ((TAttPad&)oldc).Copy((TAttPad&)newc);
+
+    // This must be there: Otherwise GetDrawOption() won't work
+    TVirtualPad *padsav = gPad;
+    oldc.cd();
+
+    const Bool_t store = TH1::AddDirectoryStatus();
+    TH1::AddDirectory(kFALSE);
+
+    //copy primitives
+    TObject *obj;
+    TIter next(oldc.GetListOfPrimitives());
+    while ((obj=next()))
+    {
+        // Old line - I think it is not necessary anymore because of the cd()
+        //gROOT->SetSelectedPad(&newc);
+
+        // Now make a clone of the object
+        TObject *clone = obj->Clone();
+
+        // Clone also important bits (FIXME: Is this correct)
+        clone->SetBit(obj->TestBits(kCannotPick|kNoContextMenu));
+
+        // Now make sure that the clones are deleted at a later time
+        clone->SetBit(kCanDelete|kMustCleanup);
+
+        // FIXME: This is a workaround for the problem with the MAstroCatalog in
+        // MHFalseSource. It doesn't harm. We'll still try to find the reason
+        if (clone->IsA()==TPad::Class())
+            gROOT->GetListOfCleanups()->Add(clone);
+
+        // Add the clone and its draw-option to the current pad
+        TVirtualPad *save2 = gPad;
+        gPad = &oldc; // Don't do this before Clone()!
+        newc.GetListOfPrimitives()->Add(clone, obj->GetDrawOption());
+        gPad = save2;
+    }
+    newc.Modified();
+    newc.Update();
+
+    TH1::AddDirectory(store);
+
+    padsav->cd();
+}
+
+Bool_t MStatusDisplay::Display(const TObjArray &list)
+{
+    TIter Next(&list);
+
+    TObject *o=Next();
+    if (!o)
+    {
+        *fLog << err << "MStatusDisplay::Display: No entry in TObjArray." << endl;
+        return kFALSE;
+    }
+
+    fTitle = o->GetTitle();
+
+    TCanvas *c;
+    while ((c=(TCanvas*)Next()))
+        //if (!GetCanvas(c->GetName()))
+            DrawClonePad(AddTab(c->GetName()), *c);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reads the contents of a saved MStatusDisplay from a file.
+//
+Int_t MStatusDisplay::Read(const char *name)
+{
+    if (!gFile)
+    {
+        *fLog << warn << "MStatusDisplay::Read: No file found. Please create a TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsOpen())
+    {
+        *fLog << warn << "MStatusDisplay::Read: File not open. Please open the TFile first." << endl;
+        return 0;
+    }
+
+    MStatusArray list;
+
+    const Int_t n = list.Read(name);
+    if (n==0)
+    {
+        *fLog << warn << "MStatusDisplay::Read: No objects read." << endl;
+        return 0;
+    }
+
+    if (!Display(list))
+    {
+        *fLog << err << "MStatusDisplay::Display: No entry in " << name << "." << endl;
+        return 0;
+    }
+
+    *fLog << inf << "MStatusDisplay: Key " << name << " with " << n << " keys read from file." << endl;
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Writes the contents of a MStatusDisplay to a file.
+//
+Int_t MStatusDisplay::Write(Int_t num, const char *name, Int_t option, Int_t bufsize) const
+{
+    if (!gFile)
+    {
+        *fLog << warn << "MStatusDisplay::Write: No file found. Please create a TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsOpen())
+    {
+        *fLog << warn << "MStatusDisplay::Write: File not open. Please open the TFile first." << endl;
+        return 0;
+    }
+
+    if (!gFile->IsWritable())
+    {
+        *fLog << warn << "MStatusDisplay::Write: File not writable." << endl;
+        return 0;
+    }
+
+    if (num==0)
+    {
+        *fLog << warn << "MStatusDisplay::Write: Tab doesn't contain an embedded Canvas... skipped." << endl;
+        return 0;
+    }
+
+    if (!gROOT->IsBatch() && num>=fTab->GetNumberOfTabs())
+    {
+        *fLog << warn << "MStatusDisplay::Write: Tab doesn't exist... skipped." << endl;
+        return 0;
+    }
+    if (gROOT->IsBatch() && num>fBatch->GetSize())
+    {
+        *fLog << warn << "MStatusDisplay::Write: Tab doesn't exist... skipped." << endl;
+        return 0;
+    }
+
+    MStatusArray list;
+
+    TNamed named;
+    named.SetTitle(fTitle);
+    list.Add(&named);
+
+    const Int_t max  = gROOT->IsBatch() ? fBatch->GetSize()+1 : fTab->GetNumberOfTabs();
+    const Int_t from = num<0 ?   1 : num;
+    const Int_t to   = num<0 ? max : num+1;
+
+    TCanvas *c;
+    for (int i=from; i<to; i++)
+        if ((c = GetCanvas(i)))
+            list.Add(c);
+
+    const Int_t n = list.Write(name, kSingleKey);
+
+    //*fLog << inf << "MStatusDisplay: " << n << " keys written to file as key " << name << "." << endl;
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this to start the synchronous (GUI eventloop driven) tab update.
+// Can also be used to change the update intervall. If millisec<0
+// the intervall given in SetUpdateTime is used. If the intervall in
+// SetUpdateTime is <0 nothing is done. (Call SetUpdateTime(-1) to
+// disable the automatic update in a MEventloop.
+//
+void MStatusDisplay::StartUpdate(Int_t millisec)
+{
+    if (fIsLocked>1)
+        return;
+
+    if (fTimer.GetTime()<TTime(0))
+        return;
+    fTimer.Start(millisec);
+}
+
+// --------------------------------------------------------------------------
+//
+// Stops the automatic GUI update
+//
+void MStatusDisplay::StopUpdate()
+{
+    if (fIsLocked>1)
+        return;
+
+    fTimer.Stop();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the update interval for the GUI update, see StartUpdate.
+//
+void MStatusDisplay::SetUpdateTime(Long_t t)
+{
+    fTimer.SetTime(t);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the background color in a canvas
+//
+void MStatusDisplay::CanvasSetFillColor(TPad &p, Int_t col) const
+{
+    TObject *obj;
+
+    // See also TPad::UseCurrentStyle
+    TIter Next(p.GetListOfPrimitives());
+    while ((obj=Next()))
+    {
+        if (obj->InheritsFrom(TPad::Class()))
+            CanvasSetFillColor(*(TPad*)obj, col);
+        if (obj->InheritsFrom(TFrame::Class()))
+            ((TFrame*)obj)->SetFillColor(col);
+    }
+
+    p.SetFillColor(col);
+}
+
+void MStatusDisplay::AddExtension(TString &name, const TString &ext, Int_t num) const
+{
+    if (name.IsNull())
+    {
+        name = "status";
+        if (num>0)
+        {
+            name += "-";
+            name += num;
+        }
+    }
+
+    if (name.EndsWith("."+ext))
+        return;
+
+    name += ".";
+    name += ext;
+}
+
+Bool_t MStatusDisplay::CheckTabForCanvas(int num) const
+{
+    if (gROOT->IsBatch())
+        return num>0 && num<=fBatch->GetSize() || num<0;
+
+    if (num>=fTab->GetNumberOfTabs())
+    {
+        *fLog << warn << "Tab #" << num << " doesn't exist..." << endl;
+        return kFALSE;
+    }
+    if (num==0)
+    {
+        *fLog << warn << "Tab #" << num << " doesn't contain an embedded canvas..." << endl;
+        return kFALSE;
+    }
+    if (fTab->GetNumberOfTabs()<2 || !gPad)
+    {
+        *fLog << warn << "Sorry, you must have at least one existing canvas (gPad!=NULL)" << endl;
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Insert the following two lines into the postscript header:
+//
+//   %%DocumentPaperSizes: a4
+//   %%Orientation: Landscape
+//
+void MStatusDisplay::UpdatePSHeader(const TString &name) const
+{
+    const TString newstr("%%DocumentPaperSizes: a4\n%%Orientation: Landscape\n");
+
+    ifstream fin(name);
+    ofstream fout(name+".$$$");
+
+    char c;
+
+    TString str;
+    fin >> str >> c;                // Read "%!PS-Adobe-2.0\n"
+    fout << str << endl << newstr;
+
+    // Doing it in blocks seems not to gain much for small (MB) files
+    while (fin)
+    {
+        fin.read(&c, 1);
+        fout.write(&c, 1);
+    }
+
+    gSystem->Unlink(name);
+    gSystem->Rename(name+".$$$", name);
+/*
+    //
+    // Old style algorithm. Shifts blocks inside a single file --- SLOW!
+    //
+    const Int_t l = newstr.Length();
+
+    Long_t t[4]; // { id, size, flags, modtime }
+    gSystem->GetPathInfo(name, t, t+1, t+2, t+3);
+
+    char *c[2] = { new char[l], new char[l] };
+
+    fstream f(name, ios::in|ios::out);
+
+    TString str;
+    f >> str >> c[0][0];     // Read "%!PS-Adobe-2.0\n" (Mini Header)
+    f.read(c[0], l);
+    f.seekp(-l, ios::cur);
+    f.write(newstr, l);
+
+    int i=0;
+    while (1)
+    {
+        f.read(c[(i+1)%2], l);
+        f.seekp(-l, ios::cur);
+
+        if (f)
+        {
+            f.write(c[i%2],l);
+            i++;
+            i%=2;
+            continue;
+        }
+
+        const Int_t ssz   = str.Length()+1;        // Length of Mini-Header
+        const Int_t block = t[1]-ssz;              // Length of block to be shifted
+        const Int_t size  = block%l;               // Reminder
+        const Int_t pos   = (block/l)*l + ssz + 1; // Position to start writing
+
+        f.clear();
+        f.seekp(pos);
+        f.write(c[i%2], l);
+        f.write(c[(i+1)%2], size);
+        break;
+    }
+
+    delete c[1];
+    delete c[0];
+*/
+}
+
+// --------------------------------------------------------------------------
+//
+// In case of num<0 all tabs are written into the PS file. If num>0
+// the canvas in the corresponding tab is written to the file.
+// Name is the name of the file (with or without extension).
+//
+// Returns the number of pages written.
+//
+// To write all tabs you can also use SaveAsPS(name)
+//
+// If the third argument is given a bottom line is drawn with the text
+// under it. If no argument is given a bottom line is drawn if
+// fTitle (SetTitle) is not empty.
+//
+Int_t MStatusDisplay::SaveAsPS(Int_t num, TString name, const TString addon)
+{
+    SetStatusLine1("Writing Postscript file...");
+    SetStatusLine2("");
+
+    if (!CheckTabForCanvas(num))
+    {
+        SetStatusLine2("Failed!");
+        return 0;
+    }
+
+    AddExtension(name, "ps", num);
+
+    if (num<0)
+        *fLog << inf << "Open ps-File: " << name << endl;
+
+    TPad       *padsav = (TPad*)gPad;
+    TVirtualPS *psave  = gVirtualPS;
+
+    TDatime d;
+
+    TPostScript ps(name, 112);
+    ps.SetBit(TPad::kPrintingPS);
+    ps.PrintFast(13, "/nan {1} def ");
+
+    gVirtualPS = &ps;
+
+    //
+    // Create a list to delete the canvas clones
+    //
+    TList l;
+    l.SetOwner();
+
+    //
+    // Create some GUI elements for a page legend
+    //
+    TLine line;
+
+    int page = 1;
+
+    //
+    // Maintain tab numbers
+    //
+    const Int_t max  = gROOT->IsBatch() ? fBatch->GetSize()+1 : fTab->GetNumberOfTabs();
+    const Int_t from = num<0 ?   1 : num;
+    const Int_t to   = num<0 ? max : num+1;
+
+    for (int i=from; i<to; i++)
+    {
+        TCanvas *c;
+        if (!(c = GetCanvas(i)))
+        {
+            if (num<0)
+                *fLog << inf << " - ";
+            *fLog << "Tab #" << i << " doesn't contain an embedded Canvas... skipped." << endl;
+            continue;
+        }
+
+        SetStatusLine2(MString::Form("Tab #%d", i));
+
+        //
+        // Init page and page size, make sure, that the canvas in the file
+        // has the same Aspect Ratio than on the screen.
+        //
+        ps.NewPage();
+
+        //
+        // 28 is used here to scale the canvas into a height of 28,
+        // such that the page title can be set above the canvas...
+        //
+        Float_t psw = 28.0; // A4 - width (29.7)
+        Float_t psh = 21.0; // A4 - height (21.0)
+
+        const Float_t cw = c->GetWw();
+        const Float_t ch = c->GetWh();
+
+        if (psw/psh>cw/ch)
+            psw = cw/ch*psh;
+        else
+            psh = ch/cw*psw;
+
+        ps.Range(psw, psh); // A4
+
+        //
+        // Clone canvas and change background color and schedule for
+        // deletion
+        //
+        TCanvas *n = (TCanvas*)c->Clone();
+        CanvasSetFillColor(*n, kWhite);
+        l.Add(n);
+
+        //
+        // Paint canvas into root file
+        //
+        if (num<0)
+            *fLog << inf << " - ";
+        *fLog << inf << "Writing Tab #" << i << ": " << c->GetName() << " (" << c << ") ";
+        if (num>0)
+            *fLog << "to " << name;
+        *fLog << "... " << flush;
+
+        n->SetBatch(kTRUE);
+        n->Paint();
+
+        //
+        // Use the canvas as coordinate system for the overlaying text
+        //
+        gPad = n;
+        //n->cd();
+
+        //
+        // Print overlaying text (NDC = %)
+        //
+        ps.SetTextColor(kBlack);
+        ps.SetTextSize(0.015);
+        ps.SetTextFont(22);
+        ps.SetTextAlign(11); // left top
+        ps.TextNDC(0, 1.015, TString("  ")+n->GetName());
+        ps.SetTextAlign(21); // cent top
+        ps.TextNDC(0.5, 1.015, TString("MARS - Magic Analysis and Reconstruction Software - ")+d.AsString());
+        ps.SetTextAlign(31); // right top
+        ps.TextNDC(1, 1.015, MString::Form("Page No.%i (%i)  ", page++, i));
+        line.PaintLineNDC(0, 1.01, 1, 1.01);
+
+        TString txt(addon.IsNull() ? fTitle : addon);
+        if (!txt.IsNull())
+        {
+            line.PaintLineNDC(0, -0.00, 1, -0.00);
+            ps.SetTextAlign(11); // left top
+            ps.TextNDC(0, -0.015, TString("  ")+txt);
+            ps.SetTextAlign(31); // right top
+            ps.TextNDC(1, -0.015, "(c) 2000-2004, Thomas Bretz  ");
+        }
+
+        //
+        // Finish drawing page
+        //
+        n->SetBatch(kFALSE);
+        *fLog << "done." << endl;
+    }
+
+    gPad = NULL; // Important!
+    l.Delete();
+
+    ps.Close();
+
+    SetStatusLine2("Updating header of PS file...");
+
+    if (num<0)
+        *fLog << " - Updating header of PS file... " << flush;
+    UpdatePSHeader(name);
+    if (num<0)
+        *fLog << inf << "done." << endl;
+
+    gVirtualPS = psave;
+    if (padsav)
+        padsav->cd();
+
+    if (num<0)
+        *fLog << inf << "done." << endl;
+
+    SetStatusLine2(MString::Form("Done (%dpages)", page-1));
+
+    return page-1;
+}
+
+Bool_t MStatusDisplay::SaveAsGIF(Int_t num, TString name)
+{
+    if (gROOT->IsBatch())
+    {
+        *fLog << warn << "Sorry, writing gif-files is not available in batch mode." << endl;
+        return 0;
+    }
+    SetStatusLine1("Writing GIF file...");
+    SetStatusLine2("");
+
+    if (!CheckTabForCanvas(num))
+    {
+        SetStatusLine2("Failed!");
+        return 0;
+    }
+
+    AddExtension(name, "gif", num);
+
+    if (num<0)
+        *fLog << inf << "Writing gif-Files..." << endl;
+
+    TPad *padsav = (TPad*)gPad;
+
+    int page = 1;
+
+    //
+    // Maintain tab numbers
+    //
+    const Int_t from = num<0 ? 1 : num;
+    const Int_t to   = num<0 ? fTab->GetNumberOfTabs() : num+1;
+
+    for (int i=from; i<to; i++)
+    {
+        TCanvas *c;
+        if (!(c = GetCanvas(i)))
+        {
+            if (num<0)
+                *fLog << inf << " - ";
+            *fLog << "Tab #" << i << " doesn't contain an embedded Canvas... skipped." << endl;
+            continue;
+        }
+
+        SetStatusLine2(MString::Form("Tab #%d", i));
+
+        //
+        // Clone canvas and change background color and schedule for
+        // deletion
+        //
+        //TCanvas *n = (TCanvas*)c->Clone();
+        //CanvasSetFillColor(*n, kWhite);
+
+        //
+        // Paint canvas into root file
+        //
+        TString writename = name;
+        if (num<0)
+        {
+            TString numname = "-";
+            numname += i;
+            writename.Insert(name.Last('.'), numname);
+        }
+        if (num<0)
+            *fLog << inf << " - ";
+        *fLog << inf << "Writing Tab #" << i << " to " << writename << ": " << c->GetName() << " (" << c << ") ";
+        if (num>0)
+            *fLog << "to " << name;
+        *fLog << "..." << flush;
+
+        c->Draw();
+        c->SaveAs(writename);
+        /*
+         n->Draw();
+         n->SaveAs(writename);
+         delete n;
+         */
+
+        if (num<0)
+            *fLog << "done." << endl;
+    }
+
+    padsav->cd();
+
+    *fLog << inf << "done." << endl;
+
+    SetStatusLine2("Done.");
+
+    return page-1;
+}
+
+Bool_t MStatusDisplay::SaveAsC(Int_t num, TString name)
+{
+    SetStatusLine1("Writing C++ file...");
+    SetStatusLine2("");
+
+    if (!CheckTabForCanvas(num))
+    {
+        SetStatusLine2("Failed!");
+        return 0;
+    }
+
+    AddExtension(name, "C", num);
+
+    if (num<0)
+        *fLog << inf << "Writing C-Files..." << endl;
+
+    TPad *padsav = (TPad*)gPad;
+
+    int page = 1;
+
+    //
+    // Maintain tab numbers
+    //
+    const Int_t from = num<0 ? 1 : num;
+    const Int_t to   = num<0 ? fTab->GetNumberOfTabs() : num+1;
+
+    for (int i=from; i<to; i++)
+    {
+        TCanvas *c;
+        if (!(c = GetCanvas(i)))
+        {
+            if (num<0)
+                *fLog << inf << " - ";
+            *fLog << "Tab #" << i << " doesn't contain an embedded Canvas... skipped." << endl;
+            continue;
+        }
+
+        SetStatusLine2(MString::Form("Tab #%d", i));
+
+        //
+        // Clone canvas and change background color and schedule for
+        // deletion
+        //
+        TCanvas *n = (TCanvas*)c->Clone();
+        CanvasSetFillColor(*n, kWhite);
+
+        //
+        // Paint canvas into root file
+        //
+        TString writename = name;
+        if (num<0)
+        {
+            TString numname = "-";
+            numname += i;
+            writename.Insert(name.Last('.'), numname);
+        }
+        if (num<0)
+            *fLog << inf << " - ";
+        *fLog << inf << "Writing Tab #" << i << " to " << writename << ": " << c->GetName() << " (" << n << ") ";
+        if (num>0)
+            *fLog << "to " << name;
+        *fLog << "..." << flush;
+
+        n->SaveSource(writename, "");
+        delete n;
+
+        if (num<0)
+            *fLog << "done." << endl;
+    }
+
+    padsav->cd();
+
+    *fLog << inf << "done." << endl;
+
+    SetStatusLine2("Done.");
+
+    return page-1;
+}
+
+// --------------------------------------------------------------------------
+//
+// In case of num<0 all tabs are written into the PS file. If num>0
+// the canvas in the corresponding tab is written to the file.
+// Name is the name of the file (with or without extension).
+//
+// Returns the number of keys written.
+//
+// To write all tabs you can also use SaveAsPS(name)
+//
+Int_t MStatusDisplay::SaveAsRoot(Int_t num, TString name)
+{
+    SetStatusLine1("Writing root file...");
+    SetStatusLine2("");
+
+    if (!CheckTabForCanvas(num))
+    {
+        SetStatusLine2("Failed!");
+        return 0;
+    }
+
+    AddExtension(name, "root", num);
+
+    TFile *fsave = gFile;
+    TFile file(name, "RECREATE", "MARS - Status Window Contents", 9);
+    const Int_t keys = Write(num);
+    gFile = fsave;
+
+    SetStatusLine2("Done.");
+
+    return keys;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Opens a save as dialog
+//
+Int_t MStatusDisplay::SaveAs(Int_t num)
+{
+    static const char *gSaveAsTypes[] =
+    {
+        "PostScript",   "*.ps",
+        "Gif files",    "*.gif",
+        "Macro files",  "*.C",
+        "ROOT files",   "*.root",
+        "All files",    "*",
+        NULL,           NULL
+    };
+
+    static TString dir(".");
+
+    TGFileInfo fi; // fFileName and fIniDir deleted in ~TGFileInfo
+
+    fi.fFileTypes = (const char**)gSaveAsTypes;
+    fi.fIniDir    = StrDup(dir);
+
+    new TGFileDialog(fClient->GetRoot(), this, kFDSave, &fi);
+
+    if (!fi.fFilename)
+        return 0;
+
+    dir = fi.fIniDir;
+
+    const TString name(fi.fFilename);
+
+    if (name.EndsWith(".root")) return SaveAsRoot(num, name);
+    if (name.EndsWith(".ps"))   return SaveAsPS(num, name);
+    if (name.EndsWith(".gif"))  return SaveAsGIF(num, name);
+    if (name.EndsWith(".C"))    return SaveAsC(num, name);
+
+    Warning("MStatusDisplay::SaveAs", "Unknown Extension: %s", fi.fFilename);
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Open contents of a MStatusDisplay with key name from file fname.
+//
+Int_t MStatusDisplay::Open(TString fname, const char *name)
+{
+    TFile file(fname, "READ");
+    if (file.IsZombie())
+    {
+        gLog << warn << "WARNING - Cannot open file " << fname << endl;
+        return 0;
+    }
+
+    return Read(name);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Opens an open dialog
+//
+Int_t MStatusDisplay::Open()
+{
+    static const char *gOpenTypes[] =
+    {
+        "ROOT files", "*.root",
+        "All files",  "*",
+        NULL,           NULL
+    };
+
+    static TString dir(".");
+
+    TGFileInfo fi; // fFileName and fIniDir deleted in ~TGFileInfo
+
+    fi.fFileTypes = (const char**)gOpenTypes;
+    fi.fIniDir    = StrDup(dir);
+
+    new TGFileDialog(fClient->GetRoot(), this, kFDSave, &fi);
+
+    if (!fi.fFilename)
+        return 0;
+
+    dir = fi.fIniDir;
+
+    return Open(fi.fFilename);
+}
+
+Bool_t MStatusDisplay::HandleConfigureNotify(Event_t *evt)
+{
+    //
+    // The initialization of the GUI is not yet enough finished...
+    //
+    if (!fTab)
+        return kTRUE;
+
+    UInt_t w = evt->fWidth;
+    UInt_t h = evt->fHeight;
+
+    /*
+     cout << "Old: " << GetWidth() << " " << GetHeight() << " " << GetBorderWidth() << endl;
+     cout << "New: " << w << " " << h << " ";
+     cout << "New: " << GetDefaultWidth() << " " << GetDefaultHeight() << " " << endl;
+     */
+
+    Bool_t wchanged = w!=GetWidth();
+    Bool_t hchanged = h!=GetHeight();
+
+    if (!wchanged && !hchanged)
+    {
+        Layout();
+        // FIXME: Make sure that this doesn't result in endless loops.
+        return kTRUE;
+    }
+
+
+    if (GetWidth()==1 && GetHeight()==1)
+        return kTRUE;
+
+    // calculate the constant part of the window
+    const UInt_t cw = GetWidth() -fTab->GetWidth();
+    const UInt_t ch = GetHeight()-fTab->GetHeight();
+
+    // calculate new size of frame (canvas @ 1:sqrt(2))
+    if (hchanged)
+        w = (UInt_t)((h-ch)*sqrt(2.)+.5)+cw;
+    else
+        h = (UInt_t)((w-cw)/sqrt(2.)+.5)+ch;
+
+    // resize frame
+    Resize(w, h);
+
+    return kTRUE;
+}
+
+Bool_t MStatusDisplay::HandleEvent(Event_t *event)
+{
+    // Instead  of doing this in CloseWindow (called from HandleEvent)
+    // we do it here. This makes sure, that handle event doesn't
+    // execute code after deleting this.
+    if (event->fType==kDestroyNotify)
+    {
+        if (Close())
+        delete this;
+//        Close();
+        return kTRUE;
+    }
+
+    const Bool_t rc = TGMainFrame::HandleEvent(event);
+
+    //
+    // This fixes a bug in older root versions which makes
+    // TCanvas crash if gPad==NULL. So we make sure, that
+    // gPad!=NULL -- be carfull, this may have other side
+    // effects.
+    //
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,01)
+    if (!gPad && fTab)
+        for (int i=0; i<fTab->GetNumberOfTabs(); i++)
+        {
+            TCanvas *c = GetCanvas(i);
+            if (c)
+            {
+                c->cd();
+                gLog << dbg << "MStatusDisplay::HandleEvent - Workaround: gPad=" << gPad << "." << endl;
+                break;
+            }
+        }
+#endif
+
+    return rc;
+}
Index: /tags/Mars-V0.9/mbase/MStatusDisplay.h
===================================================================
--- /tags/Mars-V0.9/mbase/MStatusDisplay.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MStatusDisplay.h	(revision 9772)
@@ -0,0 +1,212 @@
+#ifndef MARS_MStatusDisplay
+#define MARS_MStatusDisplay
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TGFrame
+#include <TGFrame.h>
+#endif
+
+#ifndef ROOT_TTimer
+#include <TTimer.h>
+#endif
+
+class MLog;
+class MGList;
+class MParContainer;
+
+class TPad;
+class TTimer;
+class TMutex;
+class TCanvas;
+
+class TGTab;
+class TGTextView;
+class TGStatusBar;
+class TGProgressBar;
+class TGHProgressBar;
+class TGCompositeFrame;
+class TRootEmbeddedCanvas;
+
+class MStatusDisplay : public TGMainFrame
+{
+    friend class MStatusArray;
+public:
+    typedef enum {
+        // kFile
+        kFileBrowser, kFileCanvas, kFileOpen, kFileSave, kFileSaveAs, kFileSaveAsPS,
+        kFileSaveAsRoot, kFileSaveAsGIF, kFileSaveAsC, kFilePrint,
+        kFilePrinterName, kFileClose, kFileExit, kFileReset,
+        // kLoop
+        kLoopNone, kLoopStop,
+        // kTab
+        kTabSave, kTabSaveAs, kTabSaveAsPS, kTabSaveAsRoot, kTabSaveAsGIF,
+        kTabSaveAsC, kTabPrint, kTabNext, kTabPrevious, kTabRemove,
+        // kSize
+        kSize640, kSize800, kSize960, kSize1024, kSize1280,
+        // kLog
+        kLogCopy, kLogClear, kLogSelect, kLogFind, kLogSave, kLogAppend,
+        // kPic
+        kPicMagic, kPicMars,
+        // kGui
+        kSearch, kTabs
+    } Status_t;
+
+    enum
+    {
+        // TGMainFrame::kDontCallClose = BIT(14)
+        kExitLoopOnExit  = BIT(15),
+        kExitLoopOnClose = BIT(16)
+     };
+
+protected:
+    TString fName;  // status display identifier (name) (gROOT->FindObject())
+    TString fTitle; // status display title
+
+    MLog             *fLog;
+    MGList           *fList;
+    TGCompositeFrame *fUserFrame;
+
+    Bool_t ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2);
+
+private:
+    TGHProgressBar   *fBar;
+    TGTab            *fTab;
+    TGLayoutHints    *fLayCanvas;
+
+    TTimer  fTimer;
+    TMutex *fMutex;
+
+    TGStatusBar *fStatusBar;
+
+    Status_t fStatus;
+
+    TString fPrinter;
+
+    Int_t fLogIdx;
+    TTimer fLogTimer;
+    TGTextView *fLogBox;
+
+    FontStruct_t fFont;
+
+    UInt_t fIsLocked;
+
+    TList *fBatch;          //!
+
+    void AddMenuBar();
+    void AddUserFrame();
+    void AddTabs();
+    void AddProgressBar();
+    void AddStatusBar();
+    void AddMarsTab();
+    void AddLogTab();
+
+    TCanvas *GetCanvas(TGCompositeFrame *f) const;
+
+    Bool_t ProcessMessageCommandMenu(Long_t mp1);
+    Bool_t ProcessMessageCommand(Long_t submsg, Long_t mp1, Long_t mp2);
+    Bool_t ProcessMessageTextview(Long_t submsg, Long_t mp1, Long_t mp2);
+    Bool_t ProcessMessageUser(Long_t submsg, Long_t mp1, Long_t mp2);
+    Bool_t Close();
+    void   CloseWindow();
+    Bool_t HandleConfigureNotify(Event_t *);
+    Bool_t HandleEvent(Event_t *event);
+
+    Bool_t HandleTimer(TTimer *timer=NULL);
+    void UpdateTab(TGCompositeFrame *f);
+
+    void DrawClonePad(TCanvas &newc, TCanvas &oldc) const;
+    void CanvasSetFillColor(TPad &c, Int_t col) const;
+    Bool_t Display(const TObjArray &list);
+
+    void AddExtension(TString &name, const TString &ext, Int_t num) const;
+
+    void UpdatePSHeader(const TString &name) const;
+
+    void RemoveTab(int i);
+
+    TRootEmbeddedCanvas *GetEmbeddedCanvas(TGCompositeFrame *cf) const;
+
+public:
+     MStatusDisplay(Long_t t=1000);
+     virtual ~MStatusDisplay();
+
+     void SetLogStream(MLog *log, Bool_t enable=kFALSE);
+
+     void StartUpdate(Int_t millisec=-1);
+     void StopUpdate();
+     void SetUpdateTime(Long_t t);
+
+     void SetProgressBarPosition(Float_t p);
+     TGProgressBar *GetBar() const { return (TGProgressBar*)fBar; }
+
+     void SetStatusLine1(const char *txt);
+     void SetStatusLine2(const char *txt);
+     void SetStatusLine2(const MParContainer &cont);
+
+     void SetPrinter(const TString &lpr) { fPrinter = lpr; }
+
+     virtual void SetName(const char *name) { fName = name; }
+     virtual void SetTitle(const char *title="") { fTitle = title; }
+     virtual const char *GetName() const { return fName.Data(); }
+     virtual const char *GetTitle() const { return fTitle.Data(); }
+
+     TCanvas &AddTab(const char *name);
+     TGCompositeFrame *AddRawTab(const char *name);
+
+     Bool_t   HasCanvas(const TCanvas *c) const;
+     TCanvas *GetCanvas(int i) const;
+     TCanvas *GetCanvas(const TString &name) const;
+     TVirtualPad *GetFullPad(const Int_t canvas, const Int_t pad);
+
+     Int_t Write(Int_t num, const char *name="MStatusDisplay", Int_t option=0, Int_t bufsize=0) const;
+
+     Int_t Read(const char *name="MStatusDisplay");
+     Int_t Write(const char *name="MStatusDisplay", Int_t option=0, Int_t bufsize=0)
+     {
+         return Write(-1, name, option, bufsize);
+     }
+     Int_t Write(const char *name="MStatusDisplay", Int_t option=0, Int_t bufsize=0) const
+     {
+         return Write(-1, name, option, bufsize);
+     }
+
+     Bool_t CdCanvas(const TString &name);
+     void   Update() { HandleTimer(&fTimer); HandleTimer(&fLogTimer); }
+
+     void SetNoContextMenu(Bool_t flag=kTRUE);
+
+     Int_t  SaveAsPS(TString name="", const TString addon="") { return SaveAsPS(-1, name, addon); }
+     Bool_t SaveAsGIF(TString name="") { return SaveAsGIF(-1, name); }
+     Bool_t SaveAsC(TString name="") { return SaveAsC(-1, name); }
+     Int_t  SaveAsRoot(TString name="") { return SaveAsRoot(-1, name); }
+     Int_t  PrintToLpr() { return PrintToLpr(-1); }
+
+     Int_t  SaveAsPS(Int_t num, TString name="", const TString addon="");
+     Bool_t SaveAsGIF(Int_t num, TString name="");
+     Bool_t SaveAsC(Int_t num, TString name="");
+     Int_t  SaveAsRoot(Int_t num, TString name="");
+     Int_t  PrintToLpr(Int_t num);
+
+     Int_t  SaveAs(Int_t num=-1);
+     Int_t  Open(TString fname, const char *name="MStatusDisplay");
+     Int_t  Open();
+
+     Status_t CheckStatus() const { return fStatus; }
+     void ClearStatus() { fStatus = kLoopNone; }
+
+     void Lock() { fIsLocked++; }
+     void UnLock() { if (fIsLocked>0) fIsLocked--; }
+
+     void Reset();
+
+     Bool_t CheckTabForCanvas(int num) const;
+
+     void EventInfo(Int_t event, Int_t px, Int_t py, TObject *selected);
+
+     ClassDef(MStatusDisplay, 0)   // Window for a status display
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MString.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MString.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MString.cc	(revision 9772)
@@ -0,0 +1,130 @@
+/*====================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MString
+// =======
+//
+// If you are using root Form() command you must be aware of the fact that
+// it uses a global buffer. This buffer is recreated depending on the
+// length which is necessary to form the string. This recreation is not
+// thread safe and it might result in crashes if used in multi-threaded
+// environments.
+//
+// To get around this problem MString implements a Print() member function
+// which form a string like Form does. This formation is done in a
+// internal buffer. Because this buffer must be recreated and
+// deleted each time Print() is called this might be slower than Form().
+// The advantage is, that the buffer is not global and a call to Print()
+// from different threads is safe. However accessing the same
+// M/TString-object must still be locked with a mutex.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MString.h"
+
+ClassImp(MString);
+
+// --------------------------------------------------------------------------
+//
+// Thread safe replacement for Form, use it like:
+//
+//  MString string;
+//  string.Print("MyString has %d bytes", 128);
+//
+// As a special feature the function returns the reference to the MString
+// so that you can directly work with it, eg.
+//
+//  string.Print("  MyString has %d bytes  ", 128).Strip(TString::kBoth);
+//
+MString &MString::Print(const char *fmt, va_list &ap)
+{
+    Int_t n=256;
+
+    char *ret=0;
+
+    while (1)
+    {
+        ret = new char[n+1];
+        Int_t sz = vsnprintf(ret, n, fmt, ap);
+        if (sz<=n)
+            break;
+
+        n *= 2;
+        delete [] ret;
+    };
+
+    va_end(ap);
+
+    *static_cast<TString*>(this) = ret;
+
+    delete [] ret;
+
+    return *this;
+}
+
+// --------------------------------------------------------------------------
+//
+// Thread safe replacement for Form, use it like:
+//
+//  MString string;
+//  string.Print("MyString has %d bytes", 128);
+//
+// As a special feature the function returns the reference to the MString
+// so that you can directly work with it, eg.
+//
+//  string.Print("  MyString has %d bytes  ", 128).Strip(TString::kBoth);
+//
+MString &MString::Print(const char *fmt, ...)
+{
+    va_list ap;
+    va_start(ap, fmt);
+
+    return Print(fmt, ap);
+}
+
+// --------------------------------------------------------------------------
+//
+// Thread safe replacement for Form, use it like:
+//
+//  MString string;
+//  string.Print("MyString has %d bytes", 128);
+//
+// As a special feature the function returns the reference to the MString
+// so that you can directly work with it, eg.
+//
+//  string.Print("  MyString has %d bytes  ", 128).Strip(TString::kBoth);
+//
+// The static version of this function returns a copy(!) of the resulting
+// M/TString.
+//
+MString MString::Form(const char *fmt, ...)
+{
+    va_list ap;
+    va_start(ap, fmt);
+
+    MString ret;
+    ret.Print(fmt, ap);
+    return ret;
+}
Index: /tags/Mars-V0.9/mbase/MString.h
===================================================================
--- /tags/Mars-V0.9/mbase/MString.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MString.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MString
+#define MARS_MString
+
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#include <stdio.h>
+#include <stdarg.h>
+
+class MString : public TString
+{
+public:
+    MString &Print(const char *fmt, va_list &ap);
+    MString &Print(const char *fmt, ...);
+    static MString Form(const char *fmt, ...);
+
+    ClassDef(MString, 1) // Tool to make Form() thread safe against other TStrings
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MTask.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MTask.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTask.cc	(revision 9772)
@@ -0,0 +1,524 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MTask
+//
+//   Base class for all tasks which can perfomed in a tasklist
+//   For each event processed in the eventloop all the different
+//   tasks in the tasklist will be processed.
+//
+//   So all tasks must inherit from this baseclass.
+//
+//   The inheritance from MInputStreamID is used to indicate the
+//   type of event that this task is for. If it is "All" it is executed
+//   independantly of the actual ID of the task list.
+//
+//   Inside this abstract class, there are three fundamental function:
+//
+//   - PreProcess():   executed before the eventloop starts. Here you
+//                     can initiate different things, open files, etc.
+//                     As an argument this function gets a pointer to the
+//                     parameter list. You can stop the execution by
+//                     returning kFALSE instead of kTRUE. If an error
+//                     occured and you return kFALSE make sure, that
+//                     any action is closed correctly and all newly
+//                     created object are deleted. The PostProcess in
+//                     such a case won't be executed by the Tasklist or
+//                     Eventloop.
+//
+//   - Process():      executed for each event in the eventloop. Do it
+//                     one task after the other (as they occur in the
+//                     tasklist). Only the tasks with a Stream ID
+//                     which matches the actual ID of the tasklist
+//                     are executed. A task can return kFALSE to
+//                     stop the execuition of the tasklist or
+//                     kCONTINUE to skip the pending tasks. If you want
+//                     to stop the eventloop and wants the eventloop to
+//                     return the status 'failed' return kERROR.
+//
+//   - ReInit()        The idea is, that
+//                       a) we have one file per run
+//                       b) each file contains so called run-headers which
+//                          stores information 'per run', eg MRawRunHeader
+//                          or the bad pixels
+//                       c) this information must be evaluated somehow each
+//                          time a new file is opened.
+//
+//                     If you use MReadMarsFile or MCT1ReadPreProc it is
+//                     called each time a new file has been opened and the
+//                     new run headers have been read before the first
+//                     event of these file is preprocessed.
+//
+//   - PostProcess():  executed after the eventloop. Here you can close
+//                     output files, start display of the run parameter,
+//                     etc. PostProcess is only executed in case of
+//                     PreProcess was successfull (returned kTRUE)
+//
+//
+//  Remark: Using a MTask in your tasklist doesn't make much sense,
+//          because it is doing nothing. However it is a nice tool
+//          to count something (exspecially if used together with a
+//          filter)
+//
+//
+//  Version 1:
+//  ----------
+//   - first version
+//
+//  Version 2:
+//  ----------
+//   - added fSerialNumber
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTask.h"
+
+#include <fstream>
+
+#include <TBaseClass.h> // OverwritesProcess
+#include <TStopwatch.h> // TStopwatch
+
+#include "MString.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MFilter.h"
+#include "MStatusDisplay.h"
+
+ClassImp(MTask);
+
+using namespace std;
+
+MTask::MTask(const char *name, const char *title)
+    : fFilter(NULL), fSerialNumber(0), fIsPreprocessed(kFALSE),
+    fStopwatch(0)
+{
+    fName  = name  ? name  : "MTask";
+    fTitle = title ? title : "Base class for all tasks (dummy task).";
+
+    fListOfBranches = new TList;
+    fListOfBranches->SetOwner();
+
+    fStopwatch = new TStopwatch;
+}
+
+MTask::~MTask()
+{
+    delete fStopwatch;
+    delete fListOfBranches;
+}
+
+void MTask::SetFilter(MFilter *filter)
+{
+    fFilter=filter;
+    if (filter)
+        AddToBranchList(filter->GetDataMember());
+}
+
+// --------------------------------------------------------------------------
+//
+// This adds a branch to the list for the auto enabeling schmeme.
+// This makes it possible for MReadTree to decide which branches
+// are really needed for the eventloop. Only the necessary branches
+// are read from disk which speeds up the calculation enormously.
+//
+// You can use TRegExp expressions like "*.fEnergy", but the
+// recommended method is to call this function for exactly all
+// branches you want to have, eg:
+//  AddToBranchList("MMcTrig.fNumFirstLevel");
+//  AddToBranchList("MMcTrig;1.fNumFirstLevel");
+//  AddToBranchList("MMcTrig;2.fNumFirstLevel");
+//
+// We agreed on the convetion, that all branches are stored with
+// a trailing dot '.' so that always the Master Branch name
+// (eg. MMcTrig) is part of the branch name.
+//
+// Remark: The common place to call AddToBranchList is the
+//         constructor of the derived classes (tasks)
+//
+void MTask::AddToBranchList(const char *b)
+{
+    if (fListOfBranches->FindObject(b))
+        return;
+
+    fListOfBranches->Add(new TNamed(b, ""));
+}
+
+// --------------------------------------------------------------------------
+//
+// Using this overloaded member function you may cascade several branches
+// in acomma seperated list, eg: "MMcEvt.fTheta,MMcEvt.fEnergy"
+//
+// For moredetailed information see AddToBranchList(const char *b);
+//
+void MTask::AddToBranchList(const TString &str)
+{
+    TString s = str;
+
+    while (!s.IsNull())
+    {
+        Int_t fst = s.First(',');
+
+        if (fst<0)
+            fst = s.Length();
+
+        AddToBranchList((const char*)TString(s(0, fst)));
+
+        s.Remove(0, fst+1);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy constructor.
+//
+MTask::MTask(MTask &t)
+{
+    fFilter = t.fFilter;
+    fListOfBranches->AddAll(t.fListOfBranches);
+}
+
+// --------------------------------------------------------------------------
+//
+// Mapper function for PreProcess.
+// Sets the preprocessed flag dependend on the return value of PreProcess.
+// Resets number of executions and cpu consumtion timer.
+// If task has already been preprocessed return kTRUE.
+//
+Int_t MTask::CallPreProcess(MParList *plist)
+{
+    if (fIsPreprocessed)
+        return kTRUE;
+
+    // This does not reset the counter!
+    fStopwatch->Reset();
+    fNumExec0 = GetNumExecutionsTotal();
+
+    *fLog << all << GetDescriptor() << "... " << flush;
+    if (fDisplay)
+        fDisplay->SetStatusLine2(*this);
+
+    switch (PreProcess(plist))
+    {
+    case kFALSE:
+        return kFALSE;
+
+    case kTRUE:
+        fIsPreprocessed = kTRUE;
+        return kTRUE;
+
+    case kSKIP:
+        return kSKIP;
+    }
+
+    *fLog << err << dbginf << "PreProcess of " << GetDescriptor();
+    *fLog << " returned an unknown value... aborting." << endl;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Mapper function for Process.
+// Executes Process dependent on the existance of a filter and its possible
+// return value.
+// If Process is executed, the execution counter is increased.
+// Count cpu consumtion time.
+//
+Int_t MTask::CallProcess()
+{
+    //
+    // Check for the existance of a filter. If a filter is existing
+    // check for its value. If the value is kFALSE don't execute
+    // this task.
+    //
+    const Bool_t exec = fFilter ? fFilter->IsConditionTrue() : kTRUE;
+
+    if (!exec)
+        return kTRUE;
+
+    fStopwatch->Start(kFALSE);
+    const Int_t rc = Process();
+    fStopwatch->Stop();
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Mapper function for PreProcess.
+// Calls Postprocess dependent on the state of the preprocessed flag,
+// resets this flag.
+//
+Int_t MTask::CallPostProcess()
+{
+    if (!fIsPreprocessed)
+        return kTRUE;
+
+    fIsPreprocessed = kFALSE;
+
+    *fLog << all << GetDescriptor() << "... " << flush;
+    if (fDisplay)
+        fDisplay->SetStatusLine2(*this);
+
+    return PostProcess();
+}
+
+// --------------------------------------------------------------------------
+//
+// This is reinit function
+//
+// This function is called asynchronously if the tasks in the tasklist need
+// reinitialization. This for example happens when the eventloop switches
+// from one group of events to another one (eg. switching between events
+// of different runs means reading a new run header and a new run header
+// may mean that some value must be reinitialized)
+//
+// the virtual implementation returns kTRUE
+//
+Bool_t MTask::ReInit(MParList *pList)
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is processed before the eventloop starts
+//
+// It is the job of the PreProcess to connect the tasks
+// with the right container in the parameter list.
+//
+// the virtual implementation returns kTRUE
+//
+Int_t MTask::PreProcess(MParList *pList)
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is processed for every event in the eventloop
+//
+// the virtual implementation returns kTRUE
+//
+Int_t MTask::Process()
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is processed after the eventloop starts
+//
+// the virtual implementation returns kTRUE
+//
+Int_t MTask::PostProcess()
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the name of the object. If the name of the object is not the
+// class name it returns the object name and in []-brackets the class name.
+// If a serial number is set (!=0) the serial number is added to the
+// name (eg. ;1)
+//
+const TString MTask::GetDescriptor() const
+{
+    //
+    // Because it returns a (const char*) we cannot return a casted
+    // local TString. The pointer would - immediatly after return -
+    // point to a random memory segment, because the TString has gone.
+    //
+    if (fName==ClassName())
+        return fSerialNumber==0 ? ClassName() : MString::Form("%s;%d", ClassName(), fSerialNumber);
+
+    return fSerialNumber>0 ?
+        MString::Form("%s;%d [%s]", fName.Data(), fSerialNumber, ClassName()) :
+        MString::Form("%s [%s]", fName.Data(), ClassName());
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the total number of calls to since PreProcess(). If Process() was
+//  not called due to a set filter this is not counted.
+//
+UInt_t MTask::GetNumExecutions() const
+{
+    return GetNumExecutionsTotal()-fNumExec0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the total number of calls to Process(). If Process() was not
+//  called due to a set filter this is not counted.
+//
+UInt_t MTask::GetNumExecutionsTotal() const
+{
+    return (UInt_t)fStopwatch->Counter()-1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return total CPU execution time in seconds of calls to Process().
+//  If Process() was not called due to a set filter this is not counted.
+//
+Double_t MTask::GetCpuTime() const
+{
+    return fStopwatch->CpuTime();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return total real execution time in seconds of calls to Process().
+//  If Process() was not called due to a set filter this is not counted.
+//
+Double_t MTask::GetRealTime() const
+{
+    return fStopwatch->RealTime();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints the relative time spent in Process() (relative means relative to
+//  its parent Tasklist) and the number of times Process() was executed.
+//  Don't wonder if the sum of the tasks in a tasklist is not 100%,
+//  because only the call to Process() of the task is measured. The
+//  time of the support structure is ignored. The faster your analysis is
+//  the more time is 'wasted' in the support structure.
+//  Only the CPU time is displayed. This means that exspecially task
+//  which have a huge part of file i/o will be underestimated in their
+//  relative wasted time.
+//  For convinience the lvl argument results in a number of spaces at the
+//  beginning of the line. So that the structur of a tasklist can be
+//  identified. If a Tasklist or task has filter applied the name of the
+//  filter is printer in <>-brackets behind the number of executions.
+//  Use MTaskList::PrintStatistics without an argument.
+//  For tasks which don't overwrite Process() no action is perfomed.
+//
+void MTask::PrintStatistics(const Int_t lvl, Bool_t title, Double_t time) const
+{
+    if (!OverwritesProcess() && IsA()!=MTask::Class())
+        return;
+
+    *fLog << all << setfill(' ') << setw(lvl) << " ";
+
+    if (GetCpuTime()>0 && time>0 && GetCpuTime()>=0.001*time)
+        *fLog << Form("%5.1f", GetCpuTime()/time*100) << "% ";
+    else
+        *fLog << "       ";
+
+    if (HasStreamId())
+        *fLog << GetStreamId() << ":";
+    *fLog << GetDescriptor() << "\t";
+    *fLog << dec << GetNumExecutions();
+    if (fFilter)
+        *fLog << " <" << fFilter->GetName() << ">";
+    if (title)
+        *fLog << "\t" << fTitle;
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// First call MParContainer::SavePrimitive which should stream the primitive
+// to the output stream. Then, if a filter is set, stream first the filter
+// and afterwards set the filter for this task.
+//
+void MTask::SavePrimitive(ofstream &out, Option_t *o)
+{
+    MParContainer::SavePrimitive(out);
+    if (!fFilter)
+        return;
+
+    /*
+     If we don't stream filter which are not in the task list itself
+     (which means: already streamed) we may be able to use
+     SavePrimitive as some kind of validity check for the macros
+
+     fFilter->SavePrimitive(out);
+     */
+    out << "   " << GetUniqueName() << ".SetFilter(&" << fFilter->GetUniqueName() <<");" << endl;
+    if (fSerialNumber>0)
+        out << "   " << GetUniqueName() << ".SetSerialNumber(" << fSerialNumber <<");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the class given in the argument overwrites MTask::Process.
+// This function calls itself recursively. If you want to call it,
+// leave out the argument.
+//
+Bool_t MTask::OverwritesProcess(TClass *cls) const
+{
+    if (!cls)
+        cls = IsA();
+
+    //
+    // Check whether we reached the base class MTask
+    //
+    if (cls==MTask::Class())
+        return kFALSE;
+
+    //
+    // Check whether the class cls overwrites Process
+    //
+    if (cls->GetMethodAny("Process"))
+        return kTRUE;
+
+    //
+    // If the class itself doesn't overload it check all it's base classes
+    //
+    TBaseClass *base=NULL;
+    TIter NextBase(cls->GetListOfBases());
+    while ((base=(TBaseClass*)NextBase()))
+    {
+        if (OverwritesProcess(base->GetClassPointer()))
+            return kTRUE;
+    }
+
+    return kFALSE;
+}
+
+void MTask::SetDisplay(MStatusDisplay *d)
+{
+    if (fFilter)
+        fFilter->SetDisplay(d);
+    MParContainer::SetDisplay(d);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is used to print the output in the PostProcess/Finalize.
+//  Or everywhere else in a nice fashioned and unified way.
+//
+void MTask::PrintSkipped(UInt_t n, const char *str)
+{
+    *fLog << " " << setw(7) << n << " (";
+    *fLog << Form("%5.1f", 100.*n/GetNumExecutions());
+    *fLog << "%) Evts skipped: " << str << endl;
+}
Index: /tags/Mars-V0.9/mbase/MTask.h
===================================================================
--- /tags/Mars-V0.9/mbase/MTask.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTask.h	(revision 9772)
@@ -0,0 +1,113 @@
+#ifndef MARS_MTask
+#define MARS_MTask
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MTask                                                                   //
+//                                                                         //
+// Abstract base class for a task                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MInputStreamID
+#include "MInputStreamID.h"
+#endif
+
+class TList;
+class TStopwatch;
+
+class MFilter;
+class MParList;
+
+class MTask : public MInputStreamID
+{
+private:
+    TList *fListOfBranches; //! List of Branch names for auto enabeling scheme
+
+    MFilter *fFilter;       // Filter for conditional task execution
+    Byte_t   fSerialNumber; // Serial number having more than one detector of the same type
+
+    Bool_t fIsPreprocessed; //! Indicates the success of the PreProcessing (set by MTaskList)
+
+    TStopwatch *fStopwatch; //! Count the execution time and number of executions
+    UInt_t      fNumExec0;  //! Total number of executions at PreProcess
+
+    virtual Int_t PreProcess(MParList *pList);
+    virtual Int_t Process();
+    virtual Int_t PostProcess();
+
+protected:
+    void AddToBranchList(const char *b);
+    void AddToBranchList(const TString &str);
+    void AddToBranchList(const char *master, const char *sub, const UInt_t first, const UInt_t last)
+    {
+        if (first==0 && last==0)
+        {
+            AddToBranchList(sub);
+            return;
+        }
+
+        for (unsigned int i=first; i<last+1; i++)
+            AddToBranchList(Form("%s;%d.%s", master, i, sub));
+    }
+    void AddToBranchList(TString &master, TString &sub, const UInt_t first, const UInt_t last)
+    {
+        AddToBranchList((const char*)master, (const char*)sub, first, last);
+    }
+    void AddToBranchList(const char *master, const char *sub, const UInt_t num)
+    {
+        AddToBranchList(master, sub, 0, num);
+    }
+    void AddToBranchList(TString &master, TString &sub, const UInt_t num)
+    {
+        AddToBranchList(master, sub, 0, num);
+    }
+
+public:
+    MTask(const char *name=NULL, const char *title=NULL);
+    MTask(MTask &t);
+    virtual ~MTask();
+
+    const TList *GetListOfBranches() const { return fListOfBranches; }
+    Bool_t OverwritesProcess(TClass *cls=NULL) const;
+
+    // Filter functions
+    virtual void SetFilter(MFilter *filter);
+    const MFilter *GetFilter() const        { return fFilter; }
+    MFilter *GetFilter()                    { return fFilter; } // for MContinue only
+
+    // Display functions
+    void SetDisplay(MStatusDisplay *d);
+
+    // Function for parallel executions
+    static TString AddSerialNumber(const char *str, UInt_t num) { TString s(str); if (num==0) return s; s += ";"; s += num; return s; }
+    static TString AddSerialNumber(const TString &str, UInt_t num) { return AddSerialNumber((const char*)str, num); }
+    TString AddSerialNumber(const char *str) const { return AddSerialNumber(str, fSerialNumber); }
+    TString AddSerialNumber(const TString &str) const { return AddSerialNumber(str, fSerialNumber); }
+
+    virtual void SetSerialNumber(Byte_t num) { fSerialNumber = num;  }
+    Byte_t GetSerialNumber() const           { return fSerialNumber; }
+
+    const TString GetDescriptor() const;
+
+    // Task execution statistics
+    UInt_t   GetNumExecutions() const;
+    UInt_t   GetNumExecutionsTotal() const;
+    Double_t GetCpuTime() const;
+    Double_t GetRealTime() const;
+    virtual void PrintStatistics(const Int_t lvl=0, Bool_t title=kFALSE, Double_t time=0) const;
+    virtual void PrintSkipped(UInt_t n, const char *str);
+
+    // Task overwrite functions
+    virtual Bool_t ReInit(MParList *pList);
+
+    virtual Int_t CallPreProcess(MParList *plist);
+    virtual Int_t CallProcess();
+    virtual Int_t CallPostProcess();
+
+    void SavePrimitive(ofstream &out, Option_t *o="");
+
+    ClassDef(MTask, 2) //Abstract base class for a task
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MTaskEnv.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MTaskEnv.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTaskEnv.cc	(revision 9772)
@@ -0,0 +1,194 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTaskEnv
+//
+// This class is used if a task - at runtime - should be replaced or setup
+// from a resource file, eg.
+//
+//
+// resources.rc:
+//   MyTask: MThisIsMyClass
+//   MyTask.Resource1: yes
+//   MyTask.Resource2: 50
+//
+// macro.C:
+//   MTaskList list;
+//
+//   MDefaultTask def;
+//   MTaskEnv taskenv("MyTask");
+//   taskenv.SetDefault(&def);
+//
+//   list.AddToList(&taskenv);
+//   [...]
+//   evtloop.ReadEnv("resource.rc");
+//
+// In this case MTaskEnv will act like MDefaultTask if nothing is found in the
+// resource file. If the task is setup via the resource file like in the
+// example above it will act like a MThisIsMyClass setup with Resource1 and
+// Resource2.
+//
+//
+// You can also skip the task completely if you setup (in lower case letters!)
+//
+// resources.rc:
+//   MyTask: <dummy>
+//
+//
+// A third option is to setup a MTaskEnv to be skipped except a task is
+// initialized through the resource file:
+//   MTaskEnv taskenv("MyTask");
+//   taskenv.SetDefault(0);
+//
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   -/-
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTaskEnv.h"
+
+#include <TClass.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTaskEnv);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. Takes name and title of the interactive task
+//
+MTaskEnv::MTaskEnv(const char *name, const char *title) : fTask(0)
+{
+    fName  = name  ? name  : "MTaskEnv";
+    fTitle = title ? title : "Task setup from Environment file";
+}
+
+MTaskEnv::~MTaskEnv()
+{
+    if (TestBit(kIsOwner))
+        delete fTask;
+}
+
+MTask *MTaskEnv::GetTask(const char *name) const
+{
+    MTask *task = (MTask*)GetNewObject(name, MTask::Class());
+    if (!task)
+        return NULL;
+
+    task->SetName(fName);
+    task->SetTitle(fTitle);
+
+    return task;
+}
+
+void MTaskEnv::SetDefault(const char *def)
+{
+    if (TestBit(kIsOwner) && fTask)
+        delete fTask;
+
+    fTask = GetTask(def);
+    if (!fTask)
+        *fLog << err << dbginf << "ERROR - No default Task setup..." << endl;
+
+    SetBit(kIsOwner);
+}
+
+Bool_t MTaskEnv::ReInit(MParList *list)
+{
+    *fLog << fTask->ClassName() << " <MTaskEnv>... " << flush;
+    return fTask->ReInit(list);
+}
+
+Int_t MTaskEnv::PreProcess(MParList *list)
+{
+    if (TestBit(kIsDummy))
+    {
+        *fLog << inf << "Dummy Task... skipped." << endl;
+        return kSKIP;
+    }
+
+    if (!fTask)
+    {
+        *fLog << err << GetDescriptor() << " - ERROR: No task setup." << endl;
+        return kFALSE;
+    }
+
+    *fLog << fTask->ClassName() << " <MTaskEnv>... " << flush;
+    return fTask->CallPreProcess(list);
+}
+
+Int_t MTaskEnv::Process()
+{
+    return fTask->CallProcess();
+}
+
+Int_t MTaskEnv::PostProcess()
+{
+    *fLog << fTask->ClassName() << " <MTaskEnv>... " << flush;
+    return fTask->CallPostProcess();
+}
+
+Int_t MTaskEnv::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (!IsEnvDefined(env, prefix, print))
+        return fTask ? fTask->ReadEnv(env, prefix, print) : kFALSE;
+
+    TString task = GetEnvValue(env, prefix, "");
+    task.ReplaceAll("\015", "");
+    task = task.Strip(TString::kBoth);
+
+    if (task=="<dummy>")
+    {
+        if (TestBit(kIsOwner) && fTask)
+            delete fTask;
+        fTask = 0;
+        SetBit(kIsDummy);
+        return kTRUE;
+    }
+
+    fTask = GetTask(task.Data());
+    if (!fTask)
+    {
+        *fLog << err << GetDescriptor() << " - ERROR: No task matching '";
+        *fLog << task << "' could be setup." << endl;
+        return kERROR;
+    }
+
+    ResetBit(kIsDummy);
+    SetBit(kIsOwner);
+
+    return fTask->ReadEnv(env, prefix, print);
+}
+
+Bool_t MTaskEnv::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    return fTask->WriteEnv(env, prefix, print);
+}
Index: /tags/Mars-V0.9/mbase/MTaskEnv.h
===================================================================
--- /tags/Mars-V0.9/mbase/MTaskEnv.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTaskEnv.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MTaskEnv
+#define MARS_MTaskEnv
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MFilter;
+class MTaskList;
+
+class MTaskEnv : public MTask
+{
+private:
+    MTask *fTask;
+
+    enum { kIsOwner = BIT(14), kIsDummy = BIT(15) };
+
+    MTask *GetTask(const char *name) const;
+
+    Bool_t ReInit(MParList *list);
+
+    Int_t  PreProcess(MParList *list);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+    Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+public:
+    MTaskEnv(const char *name=NULL, const char *title=NULL);
+    ~MTaskEnv();
+
+    void SetOwner(Bool_t b=kTRUE) { b ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+
+    void SetDefault(MTask *task=0) { fTask = task; if (fTask) { fTask->SetName(fName); ResetBit(kIsDummy); } else SetBit(kIsDummy); }
+    void SetDefault(const char *def);
+
+    MTask *GetTask() { return fTask; }
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MTaskEnv, 0) // Task which can be setup from an environment file
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MTaskInteractive.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MTaskInteractive.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTaskInteractive.cc	(revision 9772)
@@ -0,0 +1,165 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTaskInteractive
+//
+// If you want to create a new task inside a macro you will have to compile
+// your macro using macro.C++, because the root interpreter cannot use
+// uncompiled classes. To workaround this problem you can write simple
+// funcions (which can be handled by CINT) and use MTaskInteractive.
+//
+// This is a simple way to develop new code in a macro without need
+// to compile it.
+//
+// Example:
+//    Int_t Process()
+//    {
+//       gLog << "Processing..." << endl;
+//       return kTRUE;
+//    }
+//
+//    void main()
+//    {
+//       MTaskInteractive task;
+//       task.SetProcess(Process);
+//       MTaskList list;
+//       list.AddToList(&task);
+//    }
+//
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   -/-
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTaskInteractive.h"
+
+#include <Api.h>
+#include <TMethodCall.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTaskInteractive);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. Takes name and title of the interactive task
+//
+MTaskInteractive::MTaskInteractive(const char *name, const char *title) :
+    fPreProcess(NULL), fProcess(NULL), fPostProcess(NULL)
+{
+    fName  = name  ? name  : "MTaskInteractive";
+    fTitle = title ? title : "Interactive task";
+
+    fCall[0] = 0;
+    fCall[1] = 0;
+    fCall[2] = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Free all resources.
+//
+MTaskInteractive::~MTaskInteractive()
+{
+    Free(0);
+    Free(1);
+    Free(2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls the function and returns its return value.
+// Called by PreProcess, Process, PostProcess and ReInit.
+//
+inline Int_t MTaskInteractive::Return(Int_t no, void *params)
+{
+    // Static function called when SetFCN is called in interactive mode
+    if (!fCall[no])
+    {
+        gLog << err << dbginf << "Return(" << no << ") - TMethodCall not set." << endl;
+        return kFALSE;
+    }
+
+    Long_t result;
+    fCall[no]->SetParamPtrs(params);
+    fCall[no]->Execute(result);
+
+    return result;
+}
+
+// --------------------------------------------------------------------------
+//
+// Generalized function to set the functions of your interactive task.
+// Called by SetPreProcess, SetProcess, SetPostProcess and SetReInit
+//
+Bool_t MTaskInteractive::Set(void *fcn, Int_t no, const char *params)
+{
+    // this function is called by CINT instead of the function above
+    if (!fcn)
+        return kFALSE;
+
+    char *funcname = G__p2f2funcname(fcn);
+    if (!funcname)
+        return kFALSE;
+
+    Free(no);
+
+    fCall[no] = new TMethodCall;
+    fCall[no]->InitWithPrototype(funcname, params);
+
+    gLog << inf << GetDescriptor() << ": Using " << funcname << " as ";
+    switch (no)
+    {
+    case 0:
+        gLog << "Pre";
+        break;
+    case 2:
+        gLog << "Post";
+        break;
+
+    }
+    gLog << "Process-function." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+//
+void MTaskInteractive::Free(Int_t no)
+{
+    if (!fCall[no])
+        return;
+    delete fCall[no];
+    fCall[no] = 0;
+}
Index: /tags/Mars-V0.9/mbase/MTaskInteractive.h
===================================================================
--- /tags/Mars-V0.9/mbase/MTaskInteractive.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTaskInteractive.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MTaskInteractive
+#define MARS_MTaskInteractive
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MFilter;
+class MTaskList;
+
+class MTaskInteractive : public MTask
+{
+private:
+    TMethodCall *fCall[3];
+
+    Int_t (*fPreProcess)(MParList *list);
+    Int_t (*fProcess)();
+    Int_t (*fPostProcess)();
+
+    Int_t PreProcess(MParList *list) { if (fCall[0]) return Return(0, &list); return fPreProcess  ? (*fPreProcess)(list) : kTRUE; }
+    Int_t Process()                  { if (fCall[1]) return Return(1);        return fProcess     ? (*fProcess)()        : kTRUE; }
+    Int_t PostProcess()              { if (fCall[2]) return Return(2);        return fPostProcess ? (*fPostProcess)()    : kTRUE; }
+
+    Int_t Return(Int_t no, void *param=NULL);
+    Bool_t Set(void *fcn, Int_t no, const char *params);
+    void   Free(Int_t no);
+
+public:
+    MTaskInteractive(const char *name=NULL, const char *title=NULL);
+    ~MTaskInteractive();
+
+    // This is to be used in compiled code
+    void SetPreProcess(Int_t (*func)(MParList *list)) { fPreProcess = func;  Free(0); }
+    void SetProcess(Int_t (*func)())                  { fProcess = func;     Free(1);  }
+    void SetPostProcess(Int_t (*func)())              { fPostProcess = func; Free(2);  }
+
+    // This is for usage in CINT
+    void SetPreProcess(void *fcn)  { Set(fcn, 0, "MParList*"); fPreProcess =0; }
+    void SetProcess(void *fcn)     { Set(fcn, 1, "");          fProcess    =0; }
+    void SetPostProcess(void *fcn) { Set(fcn, 2, "");          fPostProcess=0; }
+
+    ClassDef(MTaskInteractive, 0) // Interactive task
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MTaskList.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MTaskList.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTaskList.cc	(revision 9772)
@@ -0,0 +1,929 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTaskList
+//
+// Collection of tasks.
+//
+// A tasklist is necessary to run the eventloop. It contains the scheduled
+// tasks, which should be executed in your program.
+//
+// To add a task use AddToList.
+//
+// The tasklist itself is a task, too. You can add a tasklist to another
+// tasklist. This makes sense, if you want to filter the execution of
+// more than one task of your tasklist using the same filter.
+//
+// The tasks in the list are idetified by their names. If more than one
+// task has the same name, the tasklist will still work correctly, but
+// you might run into trouble trying to get a pointer to a task by name
+// from the list.
+//
+// Remark: The Process function is only executed if the class of your task
+//         overloads Process() or if the task itself is a MTask. This
+//         means if you have a task without Process() (only PreProcess
+//         and PostProcess no time is lost during execution)
+//
+// Warning:
+//  Be carefull if you are writing your tasklist
+//  (eg. MWriteRootFile("file.root", "MTaskList")) to a file. You may
+//  not be able to initialize a new working tasklist from a file if
+//   a) Two Paramerer containers with the same names are existing in the
+//      MParList.
+//   b) You used a container somewhere which is not part of MParList.
+//      (eg. You specified a pointer to a MH container in MFillH which is
+//      not added to the parameter list.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTaskList.h"
+
+#include <fstream>           // ofstream, SavePrimitive
+
+#include <TSystem.h>         // gSystem
+#include <TOrdCollection.h>  // TOrdCollection
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIter.h"
+#include "MFilter.h"
+#include "MParList.h"
+#include "MInputStreamID.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MTaskList);
+
+using namespace std;
+
+const TString MTaskList::gsDefName  = "MTaskList";
+const TString MTaskList::gsDefTitle = "A list for tasks to be executed";
+
+// --------------------------------------------------------------------------
+//
+// the name for the task list must be the same for all task lists
+// because the task list (at the moment) is identified by exactly
+// this name in the parameter list (by MEvtLoop::SetParList)
+//
+MTaskList::MTaskList(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fTasks = new TList;
+
+    gROOT->GetListOfCleanups()->Add(fTasks);
+    gROOT->GetListOfCleanups()->Add(&fTasksProcess);
+    fTasks->SetBit(kMustCleanup);
+    fTasksProcess.SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//   CopyConstructor
+//   creates a new TaskList and put the contents of an existing
+//   TaskList in the new TaskList.
+//
+MTaskList::MTaskList(MTaskList &ts)
+{
+    fTasks->AddAll(ts.fTasks);
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the 'IsOwner' bit is set (via SetOwner()) all tasks are deleted
+//  by the destructor
+//
+MTaskList::~MTaskList()
+{
+    if (TestBit(kIsOwner))
+        fTasks->SetOwner();
+
+    delete fTasks;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the 'IsOwner' bit is set (via SetOwner()) all containers are deleted
+//  by the destructor
+//
+void MTaskList::SetOwner(Bool_t enable)
+{
+    enable ? SetBit(kIsOwner) : ResetBit(kIsOwner);
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Set the logging stream for the all tasks in the list and the tasklist
+//  itself.
+//
+void MTaskList::SetLogStream(MLog *log)
+{
+    fTasks->ForEach(MTask, SetLogStream)(log);
+    MTask::SetLogStream(log);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the display for the all tasks in the list and the tasklist itself.
+//
+void MTaskList::SetDisplay(MStatusDisplay *d)
+{
+    fTasks->ForEach(MTask, SetDisplay)(d);
+    MTask::SetDisplay(d);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the serial number for the all tasks in the list and the tasklist
+//  itself.
+//
+void MTaskList::SetSerialNumber(Byte_t num)
+{
+    fTasks->ForEach(MTask, SetSerialNumber)(num);
+    MTask::SetSerialNumber(num);
+}
+
+Bool_t MTaskList::CheckAddToList(MTask *task, const char *type, const MTask *where) const
+{
+    //
+    // Sanity check
+    //
+    if (!task)
+    {
+        *fLog << err << "ERROR - task argument=NULL." << endl;
+        return kFALSE;
+    }
+
+    //
+    // Get Name of new task
+    //
+    const char *name = task->GetName();
+
+    //
+    // Check if the new task is already existing in the list
+    //
+    const TObject *objn = fTasks->FindObject(name);
+    const TObject *objt = fTasks->FindObject(task);
+
+    if (objn || objt)
+    {
+        //
+        // If the task is already in the list ignore it.
+        //
+        if (objt || objn==task)
+        {
+            *fLog << warn << dbginf << "Warning: Task '" << task->GetName() << ", 0x" << (void*)task;
+            *fLog << "' already existing in '" << GetName() << "'... ignoring." << endl;
+            return kTRUE;
+        }
+
+        //
+        // Otherwise add it to the list, but print a warning message
+        //
+        *fLog << warn << dbginf << "Warning: Task '" << task->GetName();
+        *fLog << "' already existing in '" << GetName() << "'." << endl;
+        *fLog << "You may not be able to get a pointer to this task by name." << endl;
+    }
+
+    if (!where)
+        return kTRUE;
+
+    if (fTasks->FindObject(where))
+        return kTRUE;
+
+    *fLog << err << dbginf << "Error: Cannot find task after which the new task should be scheduled!" << endl;
+    return kFALSE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// schedule task for execution, before 'where'.
+// 'type' is the event type which should be processed
+//
+Bool_t MTaskList::AddToListBefore(MTask *task, const MTask *where, const char *type)
+{
+    if (task==this)
+    {
+        *fLog << warn << "WARNING - You cannot add a tasklist to itself.  This" << endl;
+        *fLog << "          would create infinite recursions...ignored." << endl;
+        return kFALSE;
+
+    }
+
+    // FIXME: We agreed to put the task into list in an ordered way.
+    if (!CheckAddToList(task, type, where))
+        return kFALSE;
+
+    *fLog << inf << "Adding " << task->GetName() << " to " << GetName() << " for " << type << "... " << flush;
+    task->SetStreamId(type);
+    task->SetBit(kMustCleanup);
+    fTasks->AddBefore((TObject*)where, task);
+    *fLog << "Done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// schedule task for execution, after 'where'.
+// 'type' is the event type which should be processed
+//
+Bool_t MTaskList::AddToListAfter(MTask *task, const MTask *where, const char *type)
+{
+    if (task==this)
+    {
+        *fLog << warn << "WARNING - You cannot add a tasklist to itself.  This" << endl;
+        *fLog << "          would create infinite recursions...ignored." << endl;
+        return kFALSE;
+
+    }
+
+    // FIXME: We agreed to put the task into list in an ordered way.
+    if (!CheckAddToList(task, type, where))
+        return kFALSE;
+
+    *fLog << inf << "Adding " << task->GetName() << " to " << GetName() << " for " << type << "... " << flush;
+    task->SetStreamId(type);
+    task->SetBit(kMustCleanup);
+    fTasks->AddAfter((TObject*)where, task);
+    *fLog << "Done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// schedule task for execution, 'type' is the event type which should
+// be processed
+//
+Bool_t MTaskList::AddToList(MTask *task, const char *type)
+{
+    if (task==this)
+    {
+        *fLog << warn << "WARNING - You cannot add a tasklist to itself.  This" << endl;
+        *fLog << "          would create infinite recursions...ignored." << endl;
+        return kFALSE;
+
+    }
+
+    // FIXME: We agreed to put the task into list in an ordered way.
+    if (!CheckAddToList(task, type))
+        return kFALSE;
+
+    *fLog << inf << "Adding " << task->GetName() << " to " << GetName() << " for " << type << "... " << flush;
+    task->SetStreamId(type);
+    task->SetBit(kMustCleanup);
+    fTasks->Add(task);
+    *fLog << "Done." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object in the list.
+//  'name' is the name of the object you are searching for.
+//
+TObject *MTaskList::FindObject(const char *name) const
+{
+    return fTasks->FindObject(name);
+}
+
+// --------------------------------------------------------------------------
+//
+//  check if the object is in the list or not
+//
+TObject *MTaskList::FindObject(const TObject *obj) const
+{
+    return fTasks->FindObject(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// find recursively a tasklist which contains a task with name task
+//
+MTaskList *MTaskList::FindTaskList(const char *task)
+{
+    if (FindObject(task))
+        return this;
+
+    TIter Next(fTasks);
+    TObject *o = 0;
+    while ((o=Next()))
+    {
+        MTaskList *l = dynamic_cast<MTaskList*>(o);
+        if (!l)
+            continue;
+
+        if (l->FindObject(task))
+            return l;
+    }
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// find recursively a tasklist which contains a task task
+//
+MTaskList *MTaskList::FindTaskList(const MTask *task)
+{
+    if (FindObject(task))
+        return this;
+
+    TIter Next(fTasks);
+    TObject *o = 0;
+    while ((o=Next()))
+    {
+        MTaskList *l = dynamic_cast<MTaskList*>(o);
+        if (!l)
+            continue;
+
+        if (l->FindObject(task))
+            return l;
+    }
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  removes a task from the list (used in PreProcess).
+//  if kIsOwner is set the task is deleted. (see SetOwner())
+//
+void MTaskList::Remove(MTask *task)
+{
+    TObject *obj = fTasks->Remove(task);
+
+    if (TestBit(kIsOwner))
+        delete obj;
+}
+
+// --------------------------------------------------------------------------
+//
+//  do pre processing (before eventloop) of all tasks in the task-list
+//  Only if a task overwrites the Process function the task is
+//  added to the fTaskProcess-List. This makes the execution of the
+//  tasklist a little bit (only a little bit) faster, bacause tasks
+//  doing no Processing are not Processed.
+//
+Int_t MTaskList::PreProcess(MParList *pList)
+{
+    *fLog << all << "Preprocessing... " << flush;
+    if (fDisplay)
+    {
+        // Set status lines
+        fDisplay->SetStatusLine1("PreProcessing...");
+        fDisplay->SetStatusLine2("");
+    }
+
+    fParList = pList;
+
+    //
+    // Make sure, that the ReadyToSave flag is not reset from a tasklist
+    // running as a task in another tasklist.
+    //
+    const Bool_t noreset = fParList->TestBit(MParList::kDoNotReset);
+    if (!noreset)
+        fParList->SetBit(MParList::kDoNotReset);
+
+    //
+    //  create the Iterator over the tasklist
+    //
+    TIter Next(fTasks);
+
+    MTask *task=NULL;
+
+    //
+    // loop over all tasks for preproccesing
+    //
+    while ((task=(MTask*)Next()))
+    {
+        //
+        // PreProcess the task and check for it's return value.
+        //
+        switch (task->CallPreProcess(fParList))
+        {
+        case kFALSE:
+            return kFALSE;
+
+        case kTRUE:
+            // Handle GUI events (display changes, mouse clicks)
+            if (fDisplay)
+                gSystem->ProcessEvents();
+            continue;
+
+        case kSKIP:
+            Remove(task);
+            continue;
+        }
+
+        *fLog << err << dbginf << "PreProcess of " << task->GetDescriptor();
+        *fLog << " returned an unknown value... aborting." << endl;
+        return kFALSE;
+    }
+
+    *fLog << all << endl;
+
+    //
+    // Reset the ReadyToSave flag.
+    //
+    if (!noreset)
+    {
+        fParList->SetReadyToSave(kFALSE);
+        fParList->ResetBit(MParList::kDoNotReset);
+    }
+
+    //
+    // loop over all tasks to fill fTasksProcess
+    //
+    Next.Reset();
+    fTasksProcess.Clear();
+    while ((task=(MTask*)Next()))
+        if (task->IsA()==MTask::Class() || task->OverwritesProcess())
+            fTasksProcess.Add(task);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  do reinit of all tasks in the task-list
+//
+Bool_t MTaskList::ReInit(MParList *pList)
+{ 
+    *fLog << all << "Reinit... " << flush;
+
+    if (!pList)
+        pList = fParList;
+
+    //
+    // Make sure, that the ReadyToSave flag is not reset from a tasklist
+    // running as a task in another tasklist.
+    //
+    const Bool_t noreset = pList->TestBit(MParList::kDoNotReset);
+    if (!noreset)
+        pList->SetBit(MParList::kDoNotReset);
+
+    //
+    //  create the Iterator over the tasklist
+    //
+    TIter Next(fTasks);
+
+    MTask *task=NULL;
+
+    //
+    // loop over all tasks for reinitialization
+    //
+    while ((task=(MTask*)Next()))
+    {
+        *fLog << all << task->GetName() << "... " << flush;
+
+        if (!task->ReInit(pList/*?pList:fParList*/))
+        {
+            *fLog << err << "ERROR - ReInit of Task '" << task->GetDescriptor() << "' failed." << endl;
+            return kFALSE;
+        }
+    }
+
+    *fLog << all << endl;
+
+    //
+    // Reset the ReadyToSave flag.
+    //
+    if (!noreset)
+    {
+        pList->SetReadyToSave(kFALSE);
+        pList->ResetBit(MParList::kDoNotReset);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// do the event execution of all tasks in the task-list
+//
+Int_t MTaskList::Process()
+{
+    //
+    // Check whether there is something which can be processed, otherwise
+    // stop the eventloop.
+    //
+    if (fTasksProcess.GetSize()==0)
+    {
+        *fLog << warn << "Warning: No entries in " << GetDescriptor() << " for Processing." << endl;
+        return kFALSE;
+    }
+
+    //
+    // Reset the ReadyToSave flag.
+    // Reset all containers.
+    //
+    // Make sure, that the parameter list is not reset from a tasklist
+    // running as a task in another tasklist.
+    //
+    const Bool_t noreset = fParList->TestBit(MParList::kIsProcessing);
+    if (!noreset)
+    {
+        fParList->SetBit(MParList::kIsProcessing);
+        fParList->Reset();
+    }
+
+    //
+    //  create the Iterator for the TaskList
+    //
+    TIter Next(&fTasksProcess);
+    MTask *task=NULL;
+
+    //
+    // loop over all tasks for processing
+    //
+    Int_t rc = kTRUE;
+    while ( (task=(MTask*)Next()) )
+    {
+        //
+        // if the task has the wrong stream id skip it.
+        //
+        if (GetStreamId() != task->GetStreamId() &&
+            task->GetStreamId() !=  "All")
+            continue;
+
+        //
+        // if it has the right stream id execute the CallProcess() function
+        // and check what the result of it is.
+        // The CallProcess() function increases the execution counter and
+        // calls the Process() function dependent on the existance and
+        // return value of a filter.
+        //
+        switch (task->CallProcess())
+        {
+        case kTRUE:
+            //
+            // everything was OK: go on with the next task
+            //
+            continue;
+
+        case kFALSE:
+            //
+            // an error occured: stop eventloop
+            //
+            rc = kFALSE;
+            *fLog << inf << task->GetDescriptor() << " has stopped execution of " << GetDescriptor() << "." << endl;
+            break;
+
+        case kERROR:
+            //
+            // an error occured: stop eventloop and return: failed
+            //
+            *fLog << err << "Fatal error occured while Process() of " << task->GetDescriptor() << "... stopped." << endl;
+            rc = kERROR;
+            break;
+
+        case kCONTINUE:
+            //
+            // something occured: skip the rest of the tasks for this event
+            //
+            rc = kCONTINUE;
+            break;
+
+        default:
+            *fLog << warn << dbginf << "Unknown return value from MTask::Process()... ignored." << endl;
+            continue;
+        }
+        break;
+    }
+
+    if (!noreset)
+    {
+        fParList->SetReadyToSave(kFALSE);
+        fParList->ResetBit(MParList::kIsProcessing);
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  do post processing (before eventloop) of all tasks in the task-list
+//  only tasks which have successfully been preprocessed are postprocessed.
+//
+Int_t MTaskList::PostProcess()
+{
+    *fLog << all << "Postprocessing... " << flush;
+    if (fDisplay)
+    {
+        // Set status lines
+        fDisplay->SetStatusLine1("PostProcessing...");
+        fDisplay->SetStatusLine2("");
+    }
+
+    //
+    // Make sure, that the ReadyToSave flag is not reset from a tasklist
+    // running as a task in another tasklist.
+    //
+    const Bool_t noreset = fParList->TestBit(MParList::kDoNotReset);
+    if (!noreset)
+    {
+        fParList->SetBit(MParList::kDoNotReset);
+        fParList->Reset();
+    }
+
+    //
+    //  create the Iterator for the TaskList
+    //
+    TIter Next(fTasks);
+
+    MTask *task=NULL;
+
+    //
+    //  loop over all tasks for postprocessing
+    //  only tasks which have successfully been preprocessed are postprocessed.
+    //
+    while ( (task=(MTask*)Next()) )
+    {
+        if (!task->CallPostProcess())
+            return kFALSE;
+
+        // Handle GUI events (display changes, mouse clicks)
+        if (fDisplay)
+            gSystem->ProcessEvents();
+    }
+
+    *fLog << all << endl;
+
+    //
+    // Reset the ReadyToSave flag.
+    //
+    if (!noreset)
+    {
+        fParList->SetReadyToSave(kFALSE);
+        fParList->ResetBit(MParList::kDoNotReset);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints the number of times all the tasks in the list has been.
+//  For convinience the lvl argument results in a number of spaces at the
+//  beginning of the line. So that the structur of a tasklist can be
+//  identified. If a Tasklist or task has filter applied the name of the
+//  filter is printer in <>-brackets behind the number of executions.
+//  Use MTaskList::PrintStatistics without an argument.
+//
+void MTaskList::PrintStatistics(const Int_t lvl, Bool_t title, Double_t time) const
+{
+    if (lvl==0)
+    {
+        *fLog << all << underline << "Process execution Statistics:" << endl;
+        *fLog << GetDescriptor();
+        if (GetFilter())
+            *fLog << " <" << GetFilter()->GetName() << ">";
+        if (title)
+            *fLog << "\t" << fTitle;
+        if (time>=0)
+            *fLog << Form(" %5.1f", GetCpuTime()/time*100) << "%";
+        else
+            *fLog << " 100.0%";
+        *fLog << endl;
+    }
+    else
+        MTask::PrintStatistics(lvl, title, time);
+
+    //
+    //  create the Iterator for the TaskList
+    //
+    fTasks->ForEach(MTask, PrintStatistics)(lvl+1, title, GetCpuTime());
+
+    if (lvl==0)
+        *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call 'Print()' of all tasks
+//
+void MTaskList::Print(Option_t *t) const
+{
+    *fLog << all << underline << GetDescriptor() << ":" << endl;
+
+    fTasks->Print();
+
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MTaskList::StreamPrimitive(ofstream &out) const
+{
+    out << "   MTaskList " << GetUniqueName();
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl << endl;
+
+    MIter Next(fTasks);
+
+    MParContainer *cont = NULL;
+    while ((cont=Next()))
+    {
+        cont->SavePrimitive(out, "");
+        out << "   " << GetUniqueName() << ".AddToList(&";
+        out << cont->GetUniqueName() << ");" << endl << endl;
+    }
+}
+
+void MTaskList::GetNames(TObjArray &arr) const
+{
+    MParContainer::GetNames(arr);
+    fTasks->ForEach(MParContainer, GetNames)(arr);
+}
+
+void MTaskList::SetNames(TObjArray &arr)
+{
+    MParContainer::SetNames(arr);
+    fTasks->ForEach(MParContainer, SetNames)(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the contents/setup of a parameter container/task from a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Int_t MTaskList::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (print)
+        *fLog << all << "MTaskList::ReadEnv: " << prefix << " (" << (int)print << ")" << endl;
+
+    MParContainer *cont = NULL;
+
+    MIter Next(fTasks);
+    while ((cont=Next()))
+    {
+        if (cont->InheritsFrom("MTaskList"))
+        {
+            if (cont->ReadEnv(env, prefix, print)==kERROR)
+                return kERROR;
+            continue;
+        }
+
+        if (cont->TestEnv(env, prefix, print)==kERROR)
+            return kERROR;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the contents/setup of a parameter container/task to a TEnv
+// instance (steering card/setup file).
+// The key to search for in the file should be of the syntax:
+//    prefix.vname
+// While vname is a name which is specific for a single setup date
+// (variable) of this container and prefix is something like:
+//    evtloopname.name
+// While name is the name of the containers/tasks in the parlist/tasklist
+//
+// eg.  Job4.MImgCleanStd.CleaningLevel1:  3.0
+//      Job4.MImgCleanStd.CleaningLevel2:  2.5
+//
+// If this cannot be found the next step is to search for
+//      MImgCleanStd.CleaningLevel1:  3.0
+// And if this doesn't exist, too, we should search for:
+//      CleaningLevel1:  3.0
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_t MTaskList::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
+{
+    MParContainer *cont = NULL;
+
+    MIter Next(fTasks);
+    while ((cont=Next()))
+        if (!cont->WriteEnv(env, prefix, print))
+            return kFALSE;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Removes a task from the tasklist. Returns kFALSE if the object was not
+// found in the list.
+//
+Bool_t MTaskList::RemoveFromList(MTask *task)
+{
+    TObject *obj = fTasks->Remove(task);
+
+    //
+    // If the task was found in the list try to remove it from the second
+    // list, too.
+    //
+    if (obj)
+        fTasksProcess.Remove(task);
+
+    return obj ? kTRUE : kFALSE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Find an object with the same name in the list and replace it with
+//  the new one. If the kIsOwner flag is set and the object was not
+//  created automatically, the object is deleted.
+//
+Bool_t MTaskList::Replace(MTask *task)
+{
+    //
+    //  check if the object (you want to add) exists
+    //
+    if (!task)
+        return kFALSE;
+
+    if (task==this)
+    {
+        *fLog << warn << "WARNING - You cannot add a tasklist to itself.  This" << endl;
+        *fLog << "          would create infinite recursions...ignored." << endl;
+        return kFALSE;
+
+    }
+
+    MTask *obj = (MTask*)FindObject(task->GetName());
+    if (!obj)
+    {
+        *fLog << warn << "No object with the same name '";
+        *fLog << task->GetName() << "' in list... adding." << endl;
+        return AddToList(task);
+    }
+
+    if (task==obj)
+        return kTRUE;
+
+    *fLog << inf << "Adding " << task->GetName() << " to " << GetName() << " for " << obj->GetStreamId() << "... " << flush;
+    task->SetStreamId(obj->GetStreamId());
+    task->SetBit(kMustCleanup);
+    fTasks->AddAfter((TObject*)obj, task);
+    *fLog << "Done." << endl;
+
+    RemoveFromList(obj);
+
+    if (TestBit(kIsOwner))
+        delete obj;
+
+    //*fLog << inf << "MTask '" << task->GetName() << "' found and replaced..." << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mbase/MTaskList.h
===================================================================
--- /tags/Mars-V0.9/mbase/MTaskList.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTaskList.h	(revision 9772)
@@ -0,0 +1,89 @@
+#ifndef MARS_MTaskList
+#define MARS_MTaskList
+
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MTaskList                                                         //
+//                                                                   //
+// Collection of tasks to be processed in the eventloop              //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MLog;
+class MParList;
+class MInputStreamID;
+
+class MTaskList : public MTask
+{
+private:
+    static const TString gsDefName;  // default name
+    static const TString gsDefTitle; // default title
+
+    TList    *fTasks;        // Container for the ordered list of different tasks
+    TList     fTasksProcess; //! Task which overload the Process function
+    MParList *fParList;      //! The parameter list given in PreProcess
+
+    enum { kIsOwner = BIT(14) };
+
+    void   Remove(MTask *task);
+    void   StreamPrimitive(ofstream &out) const;
+    Bool_t CheckAddToList(MTask *task, const char *tType, const MTask *where=NULL) const;
+
+public:
+    MTaskList(const char *name=NULL, const char *title=NULL);
+    MTaskList(MTaskList &ts);
+
+    ~MTaskList();
+
+    void SetLogStream(MLog *log);
+    void SetDisplay(MStatusDisplay *d);
+
+    Bool_t AddToListBefore(MTask *task, const MTask *where, const char *tType="All");
+    Bool_t AddToListAfter(MTask *task, const MTask *where, const char *tType="All");
+    Bool_t AddToList(MTask *task, const char *tType="All");
+
+    void SetSerialNumber(Byte_t num);
+
+    Bool_t Replace(MTask *obj);
+    Bool_t RemoveFromList(MTask *task);
+
+    TObject *FindObject(const char *name) const;
+    TObject *FindObject(const TObject *obj) const;
+
+    MTask *FindTask(const char *name) const
+    {
+        return (MTask*)FindObject(name);
+    }
+    MTask *FindTask(const MTask *obj) const
+    {
+        return (MTask*)FindObject(obj);
+    }
+    MTaskList *FindTaskList(const char *task);
+    MTaskList *FindTaskList(const MTask *task);
+
+    Bool_t ReInit(MParList *pList=NULL);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    void Print(Option_t *opt = "") const;
+    void PrintStatistics(const Int_t lvl=0, Bool_t title=kFALSE, Double_t time=-1) const;
+    void SetOwner(Bool_t enable=kTRUE);
+
+    const TList *GetList() const { return fTasks; }
+
+    void GetNames(TObjArray &arr) const;
+    void SetNames(TObjArray &arr);
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+    ClassDef(MTaskList, 1) //collection of tasks to be performed in the eventloop
+};
+
+#endif
Index: /tags/Mars-V0.9/mbase/MTime.cc
===================================================================
--- /tags/Mars-V0.9/mbase/MTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTime.cc	(revision 9772)
@@ -0,0 +1,732 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTime
+//
+// A generalized MARS time stamp.
+//
+//
+// We do not use floating point values here, because of several reasons:
+//  - having the times stored in integers only is more accurate and
+//    more reliable in comparison conditions
+//  - storing only integers gives similar bit-pattern for similar times
+//    which makes compression (eg gzip algorithm in TFile) more
+//    successfull
+//
+// Note, that there are many conversion function converting the day time
+// into a readable string. Also a direct interface to SQL time strings
+// is available.
+//
+// If you are using MTime containers as axis lables in root histograms
+// use GetAxisTime(). Make sure that you use the correct TimeFormat
+// on your TAxis (see GetAxisTime())
+//
+//
+// WARNING: Be carefull changing this class. It is also used in the
+//          MAGIC drive software cosy as VERY IMPORTANT stuff!
+//
+// Remarke: If you encounter strange behaviour, check the casting.
+//          Note, that on Linux machines ULong_t and UInt_t is the same.
+//
+//
+// Version 1:
+// ----------
+//  - first version
+//
+// Version 2:
+// ----------
+//  - removed fTimeStamp[2]
+//
+// Version 3:
+// ----------
+//  - removed fDurtaion - we may put it back when it is needed
+//  - complete rewrite of the data members (old ones completely replaced)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTime.h"
+
+#include <iomanip>
+
+#ifndef __USE_XOPEN
+#define __USE_XOPEN // on some systems needed for strptime
+#endif
+
+#include <time.h>     // struct tm
+#include <sys/time.h> // struct timeval
+
+#include <TTime.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MAstro.h"
+
+ClassImp(MTime);
+
+using namespace std;
+
+const UInt_t MTime::kHour = 3600000;         // [ms] one hour
+const UInt_t MTime::kDay  = MTime::kHour*24; // [ms] one day
+
+// --------------------------------------------------------------------------
+//
+// Constructor. Calls SetMjd(d) for d>0 in all other cases the time
+// is set to the current UTC time.
+//
+MTime::MTime(Double_t d)
+{
+    Init(0, 0);
+    if (d<=0)
+        Now();
+    else
+        SetMjd(d);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return date as year(y), month(m), day(d)
+//
+void MTime::GetDate(UShort_t &y, Byte_t &m, Byte_t &d) const
+{
+    MAstro::Mjd2Ymd((Long_t)fTime<0?fMjd-1:fMjd, y, m, d);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return date as year(y), month(m), day(d). If the time is afternoon
+// (>=13:00:00) the date of the next day is returned.
+//
+void MTime::GetDateOfSunrise(UShort_t &y, Byte_t &m, Byte_t &d) const
+{
+    MAstro::Mjd2Ymd(fMjd, y, m, d);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the time in the range [0h, 24h) = [0h0m0.000s - 23h59m59.999s]
+//
+void MTime::GetTime(Byte_t &h, Byte_t &m, Byte_t &s, UShort_t &ms) const
+{
+    Long_t tm = GetTime24();
+    ms  = tm%1000;            // [ms]
+    tm /= 1000;               // [s]
+    s   = tm%60;              // [s]
+    tm /= 60;                 // [m]
+    m   = tm%60;              // [m]
+    tm /= 60;                 // [h]
+    h   = tm;                 // [h]
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return time as MJD (=JD-24000000.5)
+//
+Double_t MTime::GetMjd() const
+{
+    return fMjd+(Double_t)(fNanoSec/1e6+(Long_t)fTime)/kDay;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a time which is expressed in milliseconds since 01/01/1995 0:00h
+// This is compatible with root's definition used in gSystem->Now()
+// and TTime.
+// Note, gSystem->Now() returns local time, such that it may differ
+// from GetRootTime() (if you previously called MTime::Now())
+//
+TTime MTime::GetRootTime() const
+{
+    return (ULong_t)((GetMjd()-49718)*kDay);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a time which is expressed in seconds since 01/01/1995 0:00h
+// This is compatible with root's definition used in TAxis.
+// Note, a TAxis always displayes (automatically) given times in
+// local time (while here we return UTC) such, that you may encounter
+// strange offsets. You can get rid of this by calling:
+//    TAxis::SetTimeFormat("[your-format] %F1995-01-01 00:00:00 GMT");
+//
+Double_t MTime::GetAxisTime() const
+{
+    return (GetMjd()-49718)*kDay/1000;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a time expressed in MJD, Time of Day (eg. 23:12.779h expressed
+// in milliseconds) and a nanosecond part.
+//
+Bool_t MTime::SetMjd(UInt_t mjd, ULong_t ms, UInt_t ns)
+{
+    // [d]  mjd  (eg. 52320)
+    // [ms] time (eg. 17h expressed in ms)
+    // [ns] time (ns part of time)
+
+    if (ms>kDay-1 || ns>999999)
+        return kFALSE;
+
+    const Bool_t am = ms<kHour*13; // day of sunrise?
+
+    fMjd     = am ? mjd : mjd + 1;
+    fTime    = (Long_t)(am ? ms  : ms-kDay);
+    fNanoSec = ns;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to given MJD (eg. 52080.0915449892)
+//
+void MTime::SetMjd(Double_t m)
+{
+    const UInt_t   mjd  = (UInt_t)TMath::Floor(m);
+    const Double_t frac = fmod(m, 1)*kDay; // [ms] Fraction of day
+    const UInt_t   ns   = (UInt_t)fmod(frac*1e6, 1000000);
+
+    SetMjd(mjd, (ULong_t)TMath::Floor(frac), ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to given time and date
+//
+Bool_t MTime::Set(UShort_t y, Byte_t m, Byte_t d, Byte_t h, Byte_t min, Byte_t s, UShort_t ms, UInt_t ns)
+{
+    if (h>23 || min>59 || s>59 || ms>999 || ns>999999)
+        return kFALSE;
+
+    const Int_t mjd = MAstro::Ymd2Mjd(y, m, d);
+    if (mjd<0)
+        return kFALSE;
+
+    const ULong_t tm = ((((h*60+min)*60)+s)*1000)+ms;
+
+    return SetMjd(mjd, tm, ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to time expressed in a 'struct timeval'
+//
+void MTime::Set(const struct timeval &tv)
+{
+    const UInt_t mjd = (UInt_t)TMath::Floor(1000.*tv.tv_sec/kDay) + 40587;
+
+    const Long_t tm  = tv.tv_sec%(24*3600)*1000 + tv.tv_usec/1000;
+    const UInt_t ms  = tv.tv_usec%1000;
+
+    SetMjd(mjd, tm, ms*1000);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "dd.mm.yyyy hh:mm:ss.fff"
+//
+Bool_t MTime::SetString(const char *str)
+{
+    if (!str)
+        return kFALSE;
+
+    UInt_t y, mon, d, h, m, s, ms;
+    const Int_t n = sscanf(str, "%02u.%02u.%04u %02u:%02u:%02u.%03u",
+                           &d, &mon, &y, &h, &m, &s, &ms);
+
+    return n==7 ? Set(y, mon, d, h, m, s, ms) : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "yyyy-mm-dd hh:mm:ss"
+//
+Bool_t MTime::SetSqlDateTime(const char *str)
+{
+    if (!str)
+        return kFALSE;
+
+    UInt_t y, mon, d, h, m, s;
+    const Int_t n = sscanf(str, "%04u-%02u-%02u %02u:%02u:%02u",
+                           &y, &mon, &d, &h, &m, &s);
+
+    return n==6 ? Set(y, mon, d, h, m, s) : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "yyyymmddhhmmss"
+//
+Bool_t MTime::SetSqlTimeStamp(const char *str)
+{
+    if (!str)
+        return kFALSE;
+
+    UInt_t y, mon, d, h, m, s;
+    const Int_t n = sscanf(str, "%04u%02u%02u%02u%02u%02u",
+                           &y, &mon, &d, &h, &m, &s);
+
+    return n==6 ? Set(y, mon, d, h, m, s) : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to time expressed as in CT1 PreProc files
+//
+void MTime::SetCT1Time(UInt_t mjd, UInt_t t1, UInt_t t0)
+{
+    // int   isecs_since_midday; // seconds passed since midday before sunset (JD of run start)
+    // int   isecfrac_200ns;     // fractional part of isecs_since_midday
+    // fTime->SetTime(isecfrac_200ns, isecs_since_midday);
+    fNanoSec         = (200*t1)%1000000;
+    const ULong_t ms = (200*t1)/1000000 + t0+12*kHour;
+
+    fTime = (Long_t)(ms<13*kHour ? ms : ms-kDay);
+
+    fMjd = mjd+1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the magic time. Make sure, that the MJD is set correctly.
+// It must be the MJD of the corresponding night. You can set it
+// by Set(2003, 12, 24);
+//
+// It is highly important, that the time correspoding to the night is
+// between 13:00:00.0 (day of dawning) and 12:59:59.999 (day of sunrise)
+//
+Bool_t MTime::UpdMagicTime(Byte_t h, Byte_t m, Byte_t s, UInt_t ns)
+{
+    if (h>23 || m>59 || s>59 || ns>999999999)
+         return kFALSE;
+
+    const ULong_t tm = ((((h*60+m)*60)+s)*1000)+ns/1000000;
+
+    fTime = (Long_t)(tm<kHour*13 ? tm  : tm-kDay); // day of sunrise?
+    fNanoSec = ns%1000000;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Conversion from Universal Time to Greenwich mean sidereal time,
+//  with rounding errors minimized.
+//
+//  The result is the Greenwich Mean Sidereal Time (radians)
+//
+//  There is no restriction on how the UT is apportioned between the
+//  date and ut1 arguments.  Either of the two arguments could, for
+//  example, be zero and the entire date+time supplied in the other.
+//  However, the routine is designed to deliver maximum accuracy when
+//  the date argument is a whole number and the ut argument lies in
+//  the range 0 to 1, or vice versa.
+//
+//  The algorithm is based on the IAU 1982 expression (see page S15 of
+//  the 1984 Astronomical Almanac).  This is always described as giving
+//  the GMST at 0 hours UT1.  In fact, it gives the difference between
+//  the GMST and the UT, the steady 4-minutes-per-day drawing-ahead of
+//  ST with respect to UT.  When whole days are ignored, the expression
+//  happens to equal the GMST at 0 hours UT1 each day.
+//
+//  In this routine, the entire UT1 (the sum of the two arguments date
+//  and ut) is used directly as the argument for the standard formula.
+//  The UT1 is then added, but omitting whole days to conserve accuracy.
+//
+//  The extra numerical precision delivered by the present routine is
+//  unlikely to be important in an absolute sense, but may be useful
+//  when critically comparing algorithms and in applications where two
+//  sidereal times close together are differenced.
+//
+Double_t MTime::GetGmst() const
+{
+    const Double_t ut = (Double_t)(fNanoSec/1e6+(Long_t)fTime)/kDay;
+
+    // Julian centuries since J2000.
+    const Double_t t = (ut -(51544.5-fMjd)) / 36525.0;
+
+    // GMST at this UT1
+    const Double_t r1 = 24110.54841+(8640184.812866+(0.093104-6.2e-6*t)*t)*t;
+    const Double_t r2 = 86400.0*ut;
+
+    const Double_t sum = (r1+r2)/(24*3600);
+
+    return fmod(sum, 1)*TMath::TwoPi();//+TMath::TwoPi();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the time to the current system time. The timezone is ignored.
+// If everything is set correctly you'll get UTC.
+//
+void MTime::Now()
+{
+#ifdef __LINUX__
+    struct timeval tv;
+    if (gettimeofday(&tv, NULL)<0)
+        Clear();
+    else
+        Set(tv);
+#else
+    Clear();
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "dd.mm.yyyy hh:mm:ss.fff"
+//
+TString MTime::GetString() const
+{
+    UShort_t y, ms;
+    Byte_t mon, d, h, m, s;
+
+    GetDate(y, mon, d);
+    GetTime(h, m, s, ms);
+
+    return TString(Form("%02d.%02d.%04d %02d:%02d:%02d.%03d", d, mon, y, h, m, s, ms));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a string format'd with strftime:
+// Here is a short summary of the most important formats. For more
+// information see the man page (or any other description) of
+// strftime...
+//
+//  %a  The abbreviated weekday name according to the current locale.
+//  %A  The full weekday name according to the current locale.
+//  %b  The abbreviated month name according to the current locale.
+//  %B  The full month name according to the current locale.
+//  %c  The preferred date and time representation for the current locale.
+//  %d  The day of the month as a decimal number (range  01 to 31).
+//  %e  Like %d, the day of the month as a decimal number,
+//      but a leading zero is replaced by a space.
+//  %H  The hour as a decimal number using a 24-hour clock (range 00 to 23)
+//  %k  The hour (24-hour clock) as a decimal number (range 0 to 23);
+//      single digits are preceded by a blank.
+//  %m  The month as a decimal number (range 01 to 12).
+//  %M  The minute as a decimal number (range 00 to 59).
+//  %R  The time in 24-hour notation (%H:%M).  For a
+//      version including the seconds, see %T below.
+//  %S  The second as a decimal number (range 00 to 61).
+//  %T  The time in 24-hour notation (%H:%M:%S).
+//  %x  The preferred date representation for the current
+//      locale without the time.
+//  %X  The preferred time representation for the current
+//      locale without the date.
+//  %y  The year as a decimal number without a century (range 00 to 99).
+//  %Y  The year as a decimal number including the century.
+//  %+  The date and time in date(1) format.
+//
+// The default is: Tuesday 16.February 2004 12:17:22
+//
+// The maximum size of the return string is 128 (incl. NULL)
+//
+TString MTime::GetStringFmt(const char *fmt) const
+{
+    if (!fmt)
+        fmt = "%A %e.%B %Y %H:%M:%S";
+
+    UShort_t y, ms;
+    Byte_t mon, d, h, m, s;
+
+    GetDate(y, mon, d);
+    GetTime(h, m, s, ms);
+
+    struct tm time;
+    time.tm_sec   = s;
+    time.tm_min   = m;
+    time.tm_hour  = h;
+    time.tm_mday  = d;
+    time.tm_mon   = mon-1;
+    time.tm_year  = y-1900;
+    time.tm_isdst = 0;
+
+    // recalculate tm_yday and tm_wday
+    mktime(&time);
+
+    char ret[128];
+    return TString(strftime(ret, 127, fmt, &time) ? ret : "");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the time according to the format fmt.
+// Default is "%A %e.%B %Y %H:%M:%S"
+//
+// For more information see GetStringFmt
+//
+Bool_t MTime::SetStringFmt(const char *time, const char *fmt)
+{
+    if (!fmt)
+        fmt = "%A %e.%B %Y %H:%M:%S";
+
+    struct tm t;
+    memset(&t, 0, sizeof(struct tm));
+    strptime(time, fmt, &t);
+
+    return Set(t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "yyyy-mm-dd hh:mm:ss"
+//
+TString MTime::GetSqlDateTime() const
+{
+    return GetStringFmt("%Y-%m-%d %H:%M:%S");
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "yyyymmddhhmmss"
+//
+TString MTime::GetSqlTimeStamp() const
+{
+    return GetStringFmt("%Y%m%d%H%M%S");
+}
+
+// --------------------------------------------------------------------------
+//
+// Return contents as a TString of the form:
+//   "yyyymmdd_hhmmss"
+//
+TString MTime::GetFileName() const
+{
+    return GetStringFmt("%Y%m%d_%H%M%S");
+}
+
+// --------------------------------------------------------------------------
+//
+// Print MTime as string
+//
+void MTime::Print(Option_t *) const
+{
+    UShort_t yea, ms;
+    Byte_t mon, day, h, m, s;
+
+    GetDate(yea, mon, day);
+    GetTime(h, m, s, ms);
+
+    *fLog << all << GetDescriptor() << ": ";
+    *fLog << GetString() << Form(" (+%dns)", fNanoSec) << endl;
+} 
+
+istream &MTime::ReadBinary(istream &fin)
+{
+    UShort_t y;
+    Byte_t mon, d, h, m, s;
+
+    fin.read((char*)&y,   2);
+    fin.read((char*)&mon, 1);
+    fin.read((char*)&d,   1);
+    fin.read((char*)&h,   1);
+    fin.read((char*)&m,   1);
+    fin.read((char*)&s,   1); // Total=7
+
+    Set(y, mon, d, h, m, s, 0);
+
+    return fin;
+}
+
+void MTime::AddMilliSeconds(UInt_t ms)
+{
+    fTime += ms;
+
+    fTime += 11*kHour;
+    fMjd  += (Long_t)fTime/kDay;
+    fTime  = (Long_t)fTime%kDay;
+    fTime -= 11*kHour;
+}
+
+void MTime::Plus1ns()
+{
+    fNanoSec++;
+
+    if (fNanoSec<1000000)
+        return;
+
+    fNanoSec = 0;
+    fTime += 1;
+
+    if ((Long_t)fTime<(Long_t)kDay*13)
+        return;
+
+    fTime = 11*kDay;
+    fMjd++;
+}   
+
+void MTime::Minus1ns()
+{
+    if (fNanoSec>0)
+    {
+        fNanoSec--;
+        return;
+    }
+
+    fTime -= 1;
+    fNanoSec = 999999;
+
+    if ((Long_t)fTime>=-(Long_t)kDay*11)
+        return;
+
+    fTime = 13*kDay-1;
+    fMjd--;
+}   
+
+/*
+MTime MTime::operator-(const MTime &tm1)
+{
+    const MTime &tm0 = *this;
+
+    MTime t0 = tm0>tm1 ? tm0 : tm1;
+    const MTime &t1 = tm0>tm1 ? tm1 : tm0;
+
+    if (t0.fNanoSec<t1.fNanoSec)
+    {
+        t0.fNanoSec += 1000000;
+        t0.fTime -= 1;
+    }
+
+    t0.fNanoSec -= t1.fNanoSec;
+    t0.fTime    -= t1.fTime;
+
+    if ((Long_t)t0.fTime<-(Long_t)kHour*11)
+    {
+        t0.fTime += kDay;
+        t0.fMjd--;
+    }
+
+    t0.fMjd -= t1.fMjd;
+
+    return t0;
+}
+
+void MTime::operator-=(const MTime &t)
+{
+    *this = *this-t;
+}
+
+MTime MTime::operator+(const MTime &t1)
+{
+    MTime t0 = *this;
+
+    t0.fNanoSec += t1.fNanoSec;
+
+    if (t0.fNanoSec>999999)
+    {
+        t0.fNanoSec -= 1000000;
+        t0.fTime += kDay;
+    }
+
+    t0.fTime += t1.fTime;
+
+    if ((Long_t)t0.fTime>=(Long_t)kHour*13)
+    {
+        t0.fTime -= kDay;
+        t0.fMjd++;
+    }
+
+    t0.fMjd += t1.fMjd;
+
+    return t0;
+}
+
+void MTime::operator+=(const MTime &t)
+{
+    *this = *this+t;
+}
+*/
+
+void MTime::SetMean(const MTime &t0, const MTime &t1)
+{
+    // This could be an operator+
+    *this = t0;
+
+    fNanoSec += t1.fNanoSec;
+
+    if (fNanoSec>999999)
+    {
+        fNanoSec -= 1000000;
+        fTime += kDay;
+    }
+
+    fTime += t1.fTime;
+
+    if ((Long_t)fTime>=(Long_t)kHour*13)
+    {
+        fTime -= kDay;
+        fMjd++;
+    }
+
+    fMjd += t1.fMjd;
+
+    // This could be an operator/
+    if ((Long_t)fTime<0)
+    {
+        fTime += kDay;
+        fMjd--;
+    }
+
+    Int_t reminder = fMjd%2;
+    fMjd /= 2;
+
+    fTime += reminder*kDay;
+    reminder = (Long_t)fTime%2;
+    fTime /= 2;
+
+    fNanoSec += reminder*1000000;
+    fNanoSec /= 2;
+
+    fTime += 11*kHour;
+    fMjd  += (Long_t)fTime/kDay;
+    fTime  = (Long_t)fTime%kDay;
+    fTime -= 11*kHour;
+}
+
+void MTime::SetMean(Double_t t0, Double_t t1)
+{
+    const Double_t mean = (t0+t1)*(500./kDay);
+    SetMjd(mean);
+}
+
+void MTime::AsciiRead(istream &fin)
+{
+    fin >> *this;
+}
+
+Bool_t MTime::AsciiWrite(ostream &out) const
+{
+    out << *this;
+    return out;
+}
Index: /tags/Mars-V0.9/mbase/MTime.h
===================================================================
--- /tags/Mars-V0.9/mbase/MTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mbase/MTime.h	(revision 9772)
@@ -0,0 +1,228 @@
+#ifndef MARS_MTime
+#define MARS_MTime
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MTime                                                                   //
+//                                                                         //
+// A generalized MARS time stamp                                           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef _CPP_IOSFWD
+#include <iosfwd>
+#endif
+
+#ifndef ROOT_TTime
+#include <TTime.h>
+#endif
+
+struct timeval;
+
+class MTime : public MParContainer
+{
+public:
+    static const UInt_t kHour; // [ms] one hour
+    static const UInt_t kDay;  // [ms] one day
+
+private:
+    UInt_t fMjd;     // [d]  Day in the century        (Day of sun rise)
+    TTime  fTime;    // [ms] Time of Day               (-11h<=x<13h)
+    UInt_t fNanoSec; // [ns] NanoSec part of TimeOfDay (<1000000)
+
+
+    ULong_t GetTime24() const
+    {
+        return (Long_t)fTime<0 ? (Long_t)fTime+kDay : (ULong_t)fTime;
+    }
+    void Init(const char *name, const char *title)
+    {
+        fName  = name  ? name  : "MTime";
+        fTitle = title ? title : "Generalized time stamp";
+    }
+
+public:
+    MTime(const char *name=NULL, const char *title=NULL)
+    {
+        Init(name, title);
+        Clear();
+    }
+    MTime(const struct timeval &tm)
+    {
+        Init(NULL, NULL);
+        Set(tm);
+    }
+    MTime(Double_t mjd);
+    MTime(const MTime& t) : fMjd(t.fMjd), fTime(t.fTime), fNanoSec(t.fNanoSec)
+    {
+        Init(NULL, NULL);
+    }
+
+    void operator=(const MTime &t)
+    {
+        fMjd     = t.fMjd;
+        fTime    = t.fTime;
+        fNanoSec = t.fNanoSec;
+    }
+
+    void Clear(const Option_t *o="") { fMjd=0; fTime=0; fNanoSec=0; }
+
+    void Print(Option_t *t=NULL) const;
+
+    void Now();
+
+    // Setter functions
+    Bool_t   Set(UShort_t y, Byte_t m, Byte_t d, Byte_t h=13, Byte_t min=0, Byte_t s=0, UShort_t ms=0, UInt_t ns=0);
+    void     Set(const struct timeval &tv);
+    Bool_t   SetString(const char *str);
+    Bool_t   SetSqlDateTime(const char *str);
+    Bool_t   SetSqlTimeStamp(const char *str);
+    void     SetCT1Time(UInt_t mjd, UInt_t t1, UInt_t t0);
+    Bool_t   SetStringFmt(const char *time, const char *fmt);
+    Bool_t   UpdMagicTime(Byte_t h, Byte_t m, Byte_t s, UInt_t ns);
+    Bool_t   SetMjd(UInt_t mjd, ULong_t ms, UInt_t ns=0);
+    void     SetMjd(Double_t m);
+
+    // Getter functions
+    Double_t GetMjd() const;
+    Double_t GetGmst() const;
+    TString  GetString() const;
+    TString  GetStringFmt(const char *fmt=0) const;
+    TString  GetSqlDateTime() const;
+    TString  GetSqlTimeStamp() const;
+    TString  GetFileName() const;
+    void     GetDate(UShort_t &y, Byte_t &m, Byte_t &d) const;
+    void     GetDateOfSunrise(UShort_t &y, Byte_t &m, Byte_t &d) const;
+    TTime    GetRootTime() const;
+    Double_t GetAxisTime() const;
+    Long_t   GetTime() const { return (Long_t)fTime; } // [ms] Time of Day returned in the range [-11h, 13h)
+    void     GetTime(Byte_t &h, Byte_t &m, Byte_t &s, UShort_t &ms) const;
+    void     GetTime(Byte_t &h, Byte_t &m, Byte_t &s) const
+    {
+        UShort_t ms;
+        GetTime(h, m, s, ms);
+    }
+
+    UInt_t Year() const  { UShort_t y; Byte_t m, d; GetDate(y,m,d); return y; }
+    UInt_t Month() const { UShort_t y; Byte_t m, d; GetDate(y,m,d); return m; }
+    UInt_t Day() const   { UShort_t y; Byte_t m, d; GetDate(y,m,d); return d; }
+    UInt_t Hour() const  { Byte_t h, m, s; GetTime(h,m,s); return h; }
+    UInt_t Min() const   { Byte_t h, m, s; GetTime(h,m,s); return m; }
+    UInt_t Sec() const   { Byte_t h, m, s; GetTime(h,m,s); return s; }
+
+    Bool_t IsMidnight() const { return (Long_t)fTime==0 && fNanoSec==0; }
+
+    // I/O functions
+    istream &ReadBinary(istream &fin);
+
+    void AsciiRead(istream &fin);
+    Bool_t AsciiWrite(ostream &out) const;
+
+    // Conversion functions
+    operator double() const;   //[s]
+    double operator()() const; //[s]
+
+    // Calculation functions
+    void AddMilliSeconds(UInt_t ms);
+    void Minus1ns();
+    void Plus1ns();
+    void SetMean(const MTime &t0, const MTime &t1);
+    void SetMean(Double_t t0, Double_t t1);
+    /*
+     MTime operator-(const MTime &tm1);
+     void operator-=(const MTime &t);
+     MTime operator+(const MTime &t1);
+     void operator+=(const MTime &t);
+     */
+
+    // Base comparison operators
+    bool operator<(const MTime &t) const;
+    bool operator>(const MTime &t) const;
+
+    // Derived comparison operators
+    bool operator<=(const MTime &t) const;
+    bool operator>=(const MTime &t) const;
+    bool operator==(const MTime &t) const;
+    bool operator!=(const MTime &t) const;
+    bool operator!() const;
+
+    ClassDef(MTime, 3)	//A generalized MARS time stamp
+};
+
+inline ostream &operator<<(ostream &out, const MTime &t)
+{
+    out << t.GetString();
+    return out;
+}
+
+inline istream &operator>>(istream &in, MTime &t)
+{
+    TString date, time;
+    date.ReadToDelim(in, ' ');
+    time.ReadToDelim(in, ' ');
+    t.SetString(Form("%s %s", date.Data(), time.Data()));
+    return in;
+}
+
+inline MTime::operator double() const   //[s]
+{
+    return ((Double_t)fMjd*kDay+(Long_t)fTime+fNanoSec/1e6)/1000;
+}
+
+inline double MTime::operator()() const //[s]
+{
+    return operator double();
+}
+
+inline bool MTime::operator<(const MTime &t) const
+{
+    if (fMjd<t.fMjd)
+        return true;
+    if (fMjd==t.fMjd && fTime<t.fTime)
+        return true;
+    if (fMjd==t.fMjd && fTime==t.fTime && fNanoSec<t.fNanoSec)
+        return true;
+    return false;
+}
+
+inline bool MTime::operator>(const MTime &t) const
+{
+    if (fMjd>t.fMjd)
+        return true;
+    if (fMjd==t.fMjd && fTime>t.fTime)
+        return true;
+    if (fMjd==t.fMjd && fTime==t.fTime && fNanoSec>t.fNanoSec)
+        return true;
+    return false;
+}
+
+inline bool MTime::operator<=(const MTime &t) const
+{
+    return !operator>(t);
+}
+
+inline bool MTime::operator>=(const MTime &t) const
+{
+    return !operator<(t);
+}
+
+inline bool MTime::operator==(const MTime &t) const
+{
+    return fNanoSec==t.fNanoSec && fTime==t.fTime && fMjd==t.fMjd;
+}
+
+inline bool MTime::operator!=(const MTime &t) const
+{
+    return fNanoSec!=t.fNanoSec || fTime!=t.fTime || fMjd!=t.fMjd;
+}
+
+inline bool MTime::operator!() const
+{
+    return fNanoSec==0 && (ULong_t)fTime==0 && fMjd==0;
+}
+
+#endif
Index: /tags/Mars-V0.9/mbase/Makefile
===================================================================
--- /tags/Mars-V0.9/mbase/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mbase/Makefile	(revision 9772)
@@ -0,0 +1,68 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mfileio -I../mfbase -I../mastro
+# mfileio:  MRead  (MEvtLoop)
+# mfbase:   MF     (MContinue)
+# mastro:   MAstro (MTime)
+
+CINT = Base
+
+SRCFILES = MLogo.cc \
+           MArgs.cc \
+           MString.cc \
+           MMath.cc \
+           MEnv.cc \
+	   MLog.cc \
+           MLogManip.cc \
+           MLogPlugin.cc \
+           MLogHtml.cc \
+           MParContainer.cc \
+	   MParList.cc \
+	   MInputStreamID.cc \
+           MTask.cc \
+           MTaskEnv.cc \
+           MTaskInteractive.cc \
+	   MTaskList.cc \
+           MFilter.cc \
+           MEvtLoop.cc \
+           MProgressBar.cc \
+           MSearch.cc \
+           MGMenu.cc \
+           MGMap.cc \
+           MIter.cc \
+           MDirIter.cc \
+           MRunIter.cc \
+           MReadSocket.cc \
+           MGGroupFrame.cc \
+           MGList.cc \
+           MGTask.cc \
+           MStatusArray.cc \
+           MStatusDisplay.cc \
+	   MArray.cc \
+	   MArrayB.cc \
+	   MArrayS.cc \
+	   MArrayD.cc \
+	   MArrayF.cc \
+	   MArrayI.cc \
+           MTime.cc \
+           MClone.cc \
+           MContinue.cc \
+           MPrint.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mcalib/CalibIncl.h
===================================================================
--- /tags/Mars-V0.9/mcalib/CalibIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/CalibIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mcalib/CalibLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mcalib/CalibLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/CalibLinkDef.h	(revision 9772)
@@ -0,0 +1,52 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MCalibColorSet+;
+#pragma link C++ class MCalibColorSteer+;
+#pragma link C++ class MCalibCalcFromPast+;
+#pragma link C++ class MCalibrationPattern+;
+#pragma link C++ class MCalibrationPatternDecode+;
+
+#pragma link C++ class MCalibrateData+;
+#pragma link C++ class MCalibrateRelTimes+;
+
+#pragma link C++ class MCalibConstCam+;
+#pragma link C++ class MCalibConstPix+;
+
+#pragma link C++ class MCalibrationIntensityCam+;
+#pragma link C++ class MCalibrationIntensityChargeCam+;
+#pragma link C++ class MCalibrationIntensityBlindCam+;
+#pragma link C++ class MCalibrationIntensityQECam+;
+#pragma link C++ class MCalibrationIntensityRelTimeCam+;
+#pragma link C++ class MCalibrationIntensityTestCam+;
+#pragma link C++ class MCalibrationCam+;
+#pragma link C++ class MCalibrationPix+;
+#pragma link C++ class MCalibrationRelTimeCalc+;
+#pragma link C++ class MCalibrationRelTimeCam+;
+#pragma link C++ class MCalibrationRelTimePix+;
+#pragma link C++ class MCalibrationPulseTimeCam+;
+#pragma link C++ class MCalibrationPedCam+;
+#pragma link C++ class MCalibrationHiLoCam+;
+#pragma link C++ class MCalibrationHiLoPix+;
+#pragma link C++ class MCalibrationQECamMagic+;
+#pragma link C++ class MCalibrationQECam+;
+#pragma link C++ class MCalibrationQEPix+;
+#pragma link C++ class MCalibrationTestCalc+;
+#pragma link C++ class MCalibrationTestCam+;
+#pragma link C++ class MCalibrationTestPix+;
+#pragma link C++ class MCalibrationChargeCalc+;
+#pragma link C++ class MCalibrationChargeCam+;
+#pragma link C++ class MCalibrationChargePix+;
+#pragma link C++ class MCalibrationBlindCam+;
+#pragma link C++ class MCalibrationBlindPix+;
+#pragma link C++ class MCalibrationBlindCamOneOldStyle+;
+#pragma link C++ class MCalibrationBlindCamTwoNewStyle+;
+#pragma link C++ class MCalibrationBlindCamThreeNewStyle+;
+#pragma link C++ class MCalibrationChargePINDiode+;
+
+#pragma link C++ class MMcCalibrationCalc+;
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibCalcFromPast.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibCalcFromPast.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibCalcFromPast.cc	(revision 9772)
@@ -0,0 +1,321 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 12/2004 <mailto:markus@ifae.es>
+!         
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MCalibCalcFromPast
+//
+//  Steers the occurrance of interlaced calibration events in one data run
+// 
+//  Input Containers:
+//   MParList
+//   MCalibrationIntensityChargeCam
+//   MCalibrationIntensityRelTimeCam
+//   MBadPixelsIntensityCam 
+//
+//  Output Containers:
+//   MCalibrationIntensityChargeCam
+//   MCalibrationIntensityRelTimeCam
+//   MBadPixelsIntensityCam 
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibCalcFromPast.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MHCalibrationCam.h"
+
+#include "MCalibrationIntensityChargeCam.h"
+#include "MCalibrationIntensityBlindCam.h"
+#include "MCalibrationIntensityQECam.h"
+#include "MCalibrationIntensityRelTimeCam.h"
+
+#include "MBadPixelsIntensityCam.h"
+
+#include "MCalibrationChargeCalc.h"
+#include "MCalibrationRelTimeCalc.h"
+#include "MCalibrateData.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MCalibCalcFromPast);
+
+using namespace std;
+
+const UInt_t MCalibCalcFromPast::fgNumEventsDump = 500;
+// --------------------------------------------------------------------------
+//
+//  Default constructor. 
+//
+// Sets:
+// - fNumEventsDump to fgNumEventsDump
+//
+MCalibCalcFromPast::MCalibCalcFromPast(const char *name, const char *title)
+    : fGeom(NULL), fParList(NULL), 
+      fIntensCharge(NULL), fIntensBlind(NULL), fIntensRelTime(NULL), fIntensBad(NULL),
+      fChargeCalc(NULL), fRelTimeCalc(NULL), fCalibrate(NULL),
+      fNumEvents(0), fNumCam(0)
+{
+
+  fName  = name  ? name  : "MCalibCalcFromPast";
+  fTitle = title ? title : "Task to steer the processing of interlaced calibration events";
+
+  SetNumEventsDump();
+}
+
+// -----------------------------------------------------------------------------------
+//
+// The following container are searched for and execution aborted if not in MParList:
+//  - MTaskList
+//
+Int_t MCalibCalcFromPast::PreProcess(MParList *pList)
+{
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "MGeomCam not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fParList = pList;
+  if (!fParList)
+    {
+      *fLog << err << "MParList not found... abort." << endl;
+      return kFALSE;
+    }
+
+  // 
+  // Look for the MBadPixels Intensity Cam
+  //
+  fIntensBad = (MBadPixelsIntensityCam*)pList->FindCreateObj("MBadPixelsIntensityCam");
+  if (fIntensBad)
+    *fLog << inf << "Found MBadPixelsIntensityCam ... " << flush;
+  else
+    return kFALSE;
+  
+  // 
+  // Look for the MFillH-class "MHCalibrationBlindCam". In case yes, initialize the 
+  // corresponding IntensityCam
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationBlindCam")))
+  {
+
+    *fLog << inf << "Found MHCalibrationBlindCam ... " << flush;
+
+    fIntensBlind = (MCalibrationIntensityBlindCam*)pList->FindCreateObj("MCalibrationIntensityBlindCam");
+    if (!fIntensBlind)
+      {
+        *fLog << err << "Could not find nor create MCalibrationIntensitBlindCam abort... " << endl;
+        return kFALSE;
+      }
+  }
+  
+  // 
+  // Look for the MFillH-class "MHCalibrationChargeCam". In case yes, initialize the 
+  // corresponding IntensityCam
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationChargeCam")))
+  {
+
+    fIntensCharge = (MCalibrationIntensityChargeCam*)pList->FindCreateObj("MCalibrationIntensityChargeCam");
+    fIntensQE     = (MCalibrationIntensityQECam*)    pList->FindCreateObj("MCalibrationIntensityQECam");
+
+    if (!fChargeCalc)
+      fChargeCalc   = (MCalibrationChargeCalc*)pList->FindObject("MCalibrationChargeCalc");
+
+    if (!fCalibrate)
+      fCalibrate   = (MCalibrateData*)pList->FindObject("MCalibrateData");
+    
+    *fLog << inf << "Found MHCalibrationChargeCam ... " << flush;
+
+    if (!fIntensCharge)
+      {
+        *fLog << err << "Could not find nor create MCalibrationIntensityChargeCam abort... " << endl;
+        return kFALSE;
+      }
+    
+    if (!fIntensQE)
+      {
+        *fLog << err << "Could not find nor create MCalibrationIntensityQECam abort... " << endl;
+        return kFALSE;
+      }
+    
+    if (!fChargeCalc)
+      {
+        *fLog << err << "Could not find MCalibrationChargeCalc abort... " << endl;
+        return kFALSE;
+      }
+
+    if (!fCalibrate)
+      {
+        *fLog << err << "Could not find MCalibrateData abort... " << endl;
+        return kFALSE;
+      }
+  }
+      
+  // 
+  // Look for the MFillH name "FillRelTimeCam". In case yes, initialize the 
+  // corresponding IntensityCam
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationRelTimeCam")))
+  {
+
+    fIntensRelTime = (MCalibrationIntensityRelTimeCam*)pList->FindCreateObj("MCalibrationIntensityRelTimeCam");
+    if (!fRelTimeCalc)
+      fRelTimeCalc   = (MCalibrationRelTimeCalc*)pList->FindObject(AddSerialNumber("MCalibrationRelTimeCalc"));
+
+    *fLog << inf << "Found MHCalibrationRelTimeCam ... " << flush;
+
+    if (!fIntensRelTime)
+      {
+        *fLog << err << "Could not find nor create MCalibrationIntensityRelTimeCam abort... " << endl;
+        return kFALSE;
+      }
+
+    if (!fRelTimeCalc)
+      {
+        *fLog << err << "Could not find MCalibrationRelTimeCalc abort... " << endl;
+        return kFALSE;
+      }
+  }
+      
+  fNumCam    = 0;
+  fNumEvents = 0;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// - Initializes new containers in the 
+// - Intensity Cams, if the number of calibration events has reach fNumEventsDump. 
+// - Executes Finalize() of the MCalibration*Calc classes in that case.
+// - Sets the latest MCalibrationChargeCam as update class into MCalibrateData
+// - Initialize new MCalibration*Cams into the intensity cams.
+// 
+Int_t MCalibCalcFromPast::Process()
+{
+
+  if (fNumEvents++ < fNumEventsDump)
+    return kTRUE;
+  
+  fNumEvents = 0;
+  //
+  // Finalize Possible calibration histogram classes...
+  //
+  *fLog << inf << GetDescriptor() << " : Finalize calibration histograms..." << endl;
+  if (Finalize("MHCalibrationChargeCam"))      *fLog << "MHCalibrationChargeCam ready" << flush;
+  if (Finalize("MHCalibrationChargeBlindCam")) *fLog << "MHCalibrationChargeBlindCam ready" << flush;
+  if (Finalize("MHCalibrationRelTimeCam"))     *fLog << "MHCalibrationRelTimeCam ready" << flush;  
+
+  //
+  // Finalize possible calibration calculation tasks
+  //
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() << " : Finalize calibration calculations..." << endl;
+  if (fChargeCalc)
+    fChargeCalc->Finalize();
+  if (fRelTimeCalc)
+    fRelTimeCalc->Finalize();
+  if (fCalibrate)
+    fCalibrate->UpdateConversionFactors((MCalibrationChargeCam*)fIntensCharge->GetCam());
+
+  ReInitialize();
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Searches for name in the MParList and calls, if existing: 
+// - MHCalibrationCam::Finalize()
+// - MHCalibrationCam::ResetHists()
+//
+Bool_t MCalibCalcFromPast::Finalize(const char* name)
+{
+
+  MHCalibrationCam *hist = (MHCalibrationCam*)fParList->FindObject(name);
+  if (hist)
+    {
+      hist->Finalize();
+      hist->ResetHists();
+      return kTRUE;
+    }
+
+  return kFALSE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Re-Intitializes new containers inside the Intensity Cams. 
+// From now on, a call to the IntensityCam functions returns pointers 
+// to the newly created Containers.
+//
+Bool_t MCalibCalcFromPast::ReInitialize()
+{
+
+  *fLog << endl;
+  
+  fNumCam++;
+
+  if (fIntensBad)
+    {
+      fIntensBad->AddToList(Form("MBadPixelsCam%04d",fNumCam),*fGeom);
+      *fLog << inf << "New MBadPixelsCam Nr. " << fNumCam << endl;
+    }
+
+  if (fIntensCharge)
+    {
+      fIntensCharge->AddToList(Form("MCalibrationChargeCam%04d",fNumCam),*fGeom);
+      *fLog << inf << "New MCalibrationChargeCam Nr.  " << fNumCam << endl;
+    }
+  if (fIntensQE)
+    {
+      fIntensQE->AddToList(Form("MCalibrationQECam%04d",fNumCam),*fGeom);
+      *fLog << inf << "New MCalibrationQECam Nr.  " << fNumCam << endl;
+    }
+  if (fIntensBlind)
+    {
+      fIntensBlind->AddToList(Form("MCalibrationBlindCam%04d",fNumCam),*fGeom);
+      *fLog << inf << "New MCalibrationBlindCam Nr. " << fNumCam << endl;
+    }
+
+  return kTRUE;
+
+}
+
+Int_t MCalibCalcFromPast::PostProcess()
+{
+  *fLog << inf << GetDescriptor() 
+        << ": Number of Calibration Cams: " << fNumCam << endl;
+  return kTRUE;
+  
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibCalcFromPast.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibCalcFromPast.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibCalcFromPast.h	(revision 9772)
@@ -0,0 +1,65 @@
+#ifndef MARS_MCalibCalcFromPast
+#define MARS_MCalibCalcFromPast
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MGeomCam;
+class MPedCalcFromLoGain;
+class MCalibrationChargeCalc;
+class MCalibrationRelTimeCalc;
+class MCalibrateData;
+class MCalibrationIntensityChargeCam;
+class MCalibrationIntensityBlindCam;
+class MCalibrationIntensityQECam;
+class MCalibrationIntensityRelTimeCam;
+class MBadPixelsIntensityCam;
+class MCalibCalcFromPast : public MTask
+{
+private:
+
+  static const UInt_t fgNumEventsDump;               //! Default for fNumEventsDump
+  
+  MGeomCam                        *fGeom;            //! Camera Geometry
+  MParList                        *fParList;         //! Parameter List
+  MCalibrationIntensityChargeCam  *fIntensCharge;    //! Intensity Charge Cam (to be created)
+  MCalibrationIntensityBlindCam   *fIntensBlind;     //! Intensity Blind  Cam (to be created)
+  MCalibrationIntensityQECam      *fIntensQE;        //! Intensity QE     Cam (to be created)
+  MCalibrationIntensityRelTimeCam *fIntensRelTime;   //! Intensity Rel. Time Cam (to be created)
+  MBadPixelsIntensityCam          *fIntensBad;       //! Intensity Bad Pixels Cam (to be created)
+  
+  MCalibrationChargeCalc          *fChargeCalc;      //! Charge Calibration Task
+  MCalibrationRelTimeCalc         *fRelTimeCalc;     //! Rel. Times Calibratio Task
+  MCalibrateData                  *fCalibrate;       //! Data Calibration Task
+                                                     
+  UInt_t fNumEventsDump;       // Number of event after which the MCalibrationCams gets updated
+  UInt_t fNumEvents;           //! Event counter only for calibration events
+  UInt_t fNumCam;              //! Number of currently used Calibration Cam
+  
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  PostProcess();  
+
+  Bool_t ReInitialize();
+  Bool_t Finalize(const char* name);
+
+public:
+
+  MCalibCalcFromPast(const char *name=NULL, const char *title=NULL);
+  ~MCalibCalcFromPast() {}
+  
+  UInt_t GetNumEventsDump() const   {  return fNumEventsDump;   }
+  
+  void SetNumEventsDump( const UInt_t i=fgNumEventsDump )   { fNumEventsDump = i; }
+  
+  void SetCalibrate    ( MCalibrateData          *c )  { fCalibrate   = c; }
+  void SetChargeCalc   ( MCalibrationChargeCalc  *c )  { fChargeCalc  = c; }
+  void SetRelTimeCalc  ( MCalibrationRelTimeCalc *c )  { fRelTimeCalc = c; }
+  
+  ClassDef(MCalibCalcFromPast, 1) // Task to steer the processing of interlace calibration events
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MCalibColorSet.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibColorSet.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibColorSet.cc	(revision 9772)
@@ -0,0 +1,564 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!         
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MCalibColorSet
+//
+//  Sets the color for events depending on the color which was used for
+//  the run. This is a workaround for runs which were taken before the
+//  digital module could deliver the color 'per event'
+// 
+//  Input Containers:
+//   MRawRunHeader
+//
+//  Output Containers:
+//   MCalibrationPattern
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibColorSet.h"
+
+#include <stdlib.h>   // needed for atoi on some platforms
+
+#include <TRegexp.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationCam.h"
+#include "MCalibrationPattern.h"
+#include "MRawRunHeader.h"
+
+ClassImp(MCalibColorSet);
+
+using namespace std;
+
+const Int_t  MCalibColorSet::gkIFAEBoxInaugurationRun = 20113;
+const Int_t  MCalibColorSet::gkMCRunLimit             = 1000;
+const UInt_t MCalibColorSet::gkFirstRunWithFinalBits  = 45626;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. MGeomCamMagic is the default geometry.
+//
+MCalibColorSet::MCalibColorSet(const char *name, const char *title)
+    : fPattern(0), fHeader(0), fIsExplicitColor(kFALSE)
+{
+  fName  = name  ? name  : "MCalibColorSet";
+  fTitle = title ? title : "Task to set workaround missing colors calibration events";
+
+  Clear();
+}
+
+void MCalibColorSet::Clear(const Option_t *o)
+{
+  
+  fIsValid         = kFALSE;
+
+  if (fIsExplicitColor)
+    return;
+
+  fColor           = MCalibrationCam::kNONE;
+  fStrength        = -1.;
+}
+
+
+// -----------------------------------------------------------------------------------
+//
+// The following container are searched for and execution aborted if not in MParList:
+//  - MCalibrationPattern
+//
+Int_t MCalibColorSet::PreProcess(MParList *pList)
+{
+
+  fPattern = (MCalibrationPattern*)pList->FindObject("MCalibrationPattern");
+  if (!fPattern)
+    {
+      *fLog << err << "MCalibrationPattern not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+  if (!fHeader)
+    {
+      *fLog << err << "MRawEvtHeader not found... abort." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if str contains regexp.
+// If so or pat to pattern and set color to col.
+// Otherwise do nothing.
+//
+// Normally this function is much to simple (more arguments than lines!)
+// but in this particular case it is worth to have it to avois chaotic
+// repitions of the same piece of code for many many times.
+//
+void MCalibColorSet::CheckAndSet(const TString &str, const char *regexp, MCalibrationCam::PulserColor_t col, Float_t strength)
+{
+    if (!str.Contains(TRegexp(regexp)))
+        return;
+
+    fStrength = strength;
+    fColor    = col;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+// - MRawRunHeader
+//
+// If Runnumber < gkIFAEBoxInaugurationRun, set colour pattern: 0
+//
+// If Runnumber > gkIFAEBoxInaugurationRun, search for colour in 
+// the project name: Set colour pattern according to the following 
+// convention: 
+//    Green: assume slot 1  ( 5 Leds Green)
+//    Blue:  assume slot 14 ( 5 Leds Blue )
+//    UV:    assume slot 12 ( 5 Leds UV   )
+//    CT1:   take  'slot 17'
+//
+Bool_t MCalibColorSet::ReInit(MParList *pList)
+{
+
+  Clear();
+
+  MRawRunHeader *header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!header)
+    {
+      *fLog << err << "MRawRunHeader not found... abort." << endl;
+      return kFALSE;
+    }
+  
+  if (header->IsMonteCarloRun())
+    return kTRUE;
+
+  if (header->GetRunNumber() > gkFirstRunWithFinalBits)
+    return kTRUE;
+
+  //
+  // Consider the case that a pedestal run is interleaved in the calibration run sequence ... prepare
+  // to skip this run.
+  //
+  if (header->GetRunType() == MRawRunHeader::kRTPedestal)
+    {
+      *fLog << warn << "New run is a pedestal run... need intensity calibration to treat this case!" << endl;
+      fColor = MCalibrationCam::kNONE;
+      fIsValid = kTRUE;      
+      return kTRUE;
+    }
+ 
+  if (fIsExplicitColor)
+    {
+      fIsValid = kTRUE;
+      return kTRUE;
+    }
+
+  const Int_t num = header->GetRunNumber();
+
+  if (num<gkIFAEBoxInaugurationRun)
+    {
+      *fLog << inf << "Run taken before inauguration of IFAE-box... using CT1 pulser." << endl;
+      fColor    = MCalibrationCam::kCT1;
+      fStrength = 10.;
+      fIsValid  = kTRUE;
+      return kTRUE;
+    }
+  
+  fColor    = MCalibrationCam::kNONE;
+  fStrength = 0.;
+
+  switch (num)
+    {
+    case 22246:
+    case 22253:
+    case 25792:
+    case 26402:
+    case 35415:
+    case 44768:
+    case 44976:
+    case 45082:
+    case 45083:
+    case 45089:
+    case 45090:
+    case 45091:
+    case 45094:
+    case 45119:
+    case 45249:
+    case 45253:
+    case 45262:
+    case 45274:
+    case 45275:
+    case 45276:
+    case 45365:
+    case 45366:
+    case 45367:
+    case 45368:
+    case 45369:
+    case 45370:
+    case 45371:
+    case 45382:
+    case 45401:
+    case 45419:
+    case 45432:
+    case 45471:
+    case 45485:
+    case 45489:
+    case 45557:
+    case 45562:
+    case 45571:
+    case 45579:
+    case 45607:
+      //    case 31756:
+      fColor = MCalibrationCam::kBLUE;
+      fStrength = 1.;
+      break;
+      
+    case 30090:
+    case 31745:
+    case 31746:
+    case 31747:
+    case 31748:
+    case 20660:
+    case 20661:
+    case 26408:
+    case 26409:
+    case 26412:
+    case 26568:
+    case 26924:
+    case 45051:
+    case 45084:
+    case 45085:
+    case 45092:
+    case 45227:
+    case 45241:
+    case 45250:
+    case 45254:
+    case 45263:
+    case 45372:
+    case 45373:
+    case 45608:
+      fColor = MCalibrationCam::kGREEN;
+      fStrength = 5.;
+      break;
+      
+    case 45086:
+    case 45088:
+    case 45111:
+    case 45115:
+    case 45216:
+    case 45218:
+    case 45226:
+    case 45240:
+    case 45251:
+    case 45278:
+    case 45336:
+    case 45341:
+    case 45358:
+    case 45374:
+    case 45375:
+    case 45376:
+    case 45377:
+    case 45381:
+    case 45400:
+    case 45418:
+    case 45431:
+    case 45470:
+    case 45484:
+    case 45490:
+    case 45556:
+    case 45561:
+    case 45570:
+    case 45578:
+    case 45614:
+    case 45618:
+      fColor = MCalibrationCam::kUV;
+      fStrength = 10.;
+      break;
+      
+    case 43914:
+    case 43916:
+    case 43918:
+    case 43920:
+    case 43922:
+      fColor = MCalibrationCam::kCT1;
+      fStrength = 20.;
+      break;
+
+    case 27474:
+      *fLog << err << "Sorry, run 27474 was taken with CLOSED LIDS. It should not be used! " << endl;
+      return kFALSE;
+      break;
+
+    case 40493:
+    case 45116:
+    case 45609:
+    case 45219:
+      *fLog << err << dec << "Sorry, run " << num 
+            << " was taken with a combination of colours used to flat-field ";
+      *fLog << err << "the camera. It cannot be used for the standard calibration " << endl;
+      return kFALSE;
+      break;
+      
+    case 45605:
+      *fLog << err << "Sorry, run 45605 was taken with the continuous light source." << endl;
+      *fLog << err << "It cannot be used for calibration. Try to run a pedestal extraction on it." << endl;
+      return kFALSE;
+      break;
+
+    case 45606:
+      *fLog << err << "Sorry, run 45606 was taken with mal-functionning pulser." << endl;
+      *fLog << err << "It cannot be used for calibration. Try to run a pedestal extraction on it." << endl;
+      return kFALSE;
+      break;
+
+    }
+  
+  if (fColor != MCalibrationCam::kNONE)
+  {
+      *fLog << inf << "Color determined from the run-number... ";
+      switch (fColor)
+      {
+      case MCalibrationCam::kGREEN: *fLog << "Green."; break;
+      case MCalibrationCam::kBLUE:  *fLog << "Blue.";  break;
+      case MCalibrationCam::kUV:    *fLog << "UV.";    break;
+      case MCalibrationCam::kCT1:   *fLog << "CT1.";   break;
+      default: break;
+      }
+      *fLog << endl;
+      fIsValid  = kTRUE;
+      return kTRUE;
+  }
+
+  TString proj = header->GetProjectName();
+  proj.ToLower();
+
+  // Possible green combinations
+  CheckAndSet(proj, "0.1led[s]?gree", MCalibrationCam::kGREEN, 0.1);
+  CheckAndSet(proj, "1led[s]?gree",   MCalibrationCam::kGREEN, 1. );
+  CheckAndSet(proj, "2led[s]?gree",   MCalibrationCam::kGREEN, 2. );
+  CheckAndSet(proj, "3led[s]?gree",   MCalibrationCam::kGREEN, 3. );
+  CheckAndSet(proj, "5led[s]?gree",   MCalibrationCam::kGREEN, 5. );
+  CheckAndSet(proj, "6led[s]?gree",   MCalibrationCam::kGREEN, 6. );
+  CheckAndSet(proj, "7led[s]?gree",   MCalibrationCam::kGREEN, 7. );
+  CheckAndSet(proj, "8led[s]?gree",   MCalibrationCam::kGREEN, 8. );
+
+  // Possible blue combinations
+  CheckAndSet(proj, "0.1led[s]?blue", MCalibrationCam::kBLUE, 0.1);
+  CheckAndSet(proj, "1led[s]?blue",   MCalibrationCam::kBLUE,  1.);
+  CheckAndSet(proj, "2led[s]?blue",   MCalibrationCam::kBLUE,  2.);
+  CheckAndSet(proj, "3led[s]?blue",   MCalibrationCam::kBLUE,  3.);
+  CheckAndSet(proj, "5led[s]?blue",   MCalibrationCam::kBLUE,  5.);
+  CheckAndSet(proj, "6led[s]?blue",   MCalibrationCam::kBLUE,  6.);
+  CheckAndSet(proj, "7led[s]?blue",   MCalibrationCam::kBLUE,  7.);
+  CheckAndSet(proj, "8led[s]?blue",   MCalibrationCam::kBLUE,  8.);
+  CheckAndSet(proj, "10led[s]?blue",  MCalibrationCam::kBLUE, 10.);
+  CheckAndSet(proj, "15led[s]?blue",  MCalibrationCam::kBLUE, 15.);
+  CheckAndSet(proj, "20led[s]?blue",  MCalibrationCam::kBLUE, 20.);
+  CheckAndSet(proj, "21led[s]?blue",  MCalibrationCam::kBLUE, 21.);
+  CheckAndSet(proj, "22led[s]?blue",  MCalibrationCam::kBLUE, 22.);
+  CheckAndSet(proj, "23led[s]?blue",  MCalibrationCam::kBLUE, 23.);
+
+  // Possible UV combinations
+  CheckAndSet(proj, "1led[s]?uv",     MCalibrationCam::kUV,  1.);
+  CheckAndSet(proj, "2led[s]?uv",     MCalibrationCam::kUV,  2.);
+  CheckAndSet(proj, "3led[s]?uv",     MCalibrationCam::kUV,  3.);
+  CheckAndSet(proj, "5led[s]?uv",     MCalibrationCam::kUV,  5.);
+  CheckAndSet(proj, "6led[s]?uv",     MCalibrationCam::kUV,  6.);
+  CheckAndSet(proj, "7led[s]?uv",     MCalibrationCam::kUV,  7.);
+  CheckAndSet(proj, "8led[s]?uv",     MCalibrationCam::kUV,  8.);
+  CheckAndSet(proj, "10led[s]?uv",    MCalibrationCam::kUV, 10.);
+  CheckAndSet(proj, "11led[s]?uv",    MCalibrationCam::kUV, 11.);
+  CheckAndSet(proj, "12led[s]?uv",    MCalibrationCam::kUV, 12.);
+  CheckAndSet(proj, "13led[s]?uv",    MCalibrationCam::kUV, 13.);
+
+  // Possible slot combinations
+  TRegexp slot("slot");
+  if (proj.Contains(slot))
+  {
+      proj.ReplaceAll("slot","");
+      UInt_t nr = 0;
+      TRegexp slotnr("^[0-9]");
+
+      if (proj.Contains(slotnr))
+      {
+          proj.Replace(2,99,"");
+          proj.ReplaceAll("u","");
+          proj.ReplaceAll("v","");
+          proj.ReplaceAll("g","");
+          nr = atoi(proj.Data())-1;
+
+          fColor = nr < 2 ? MCalibrationCam::kGREEN :
+              ( nr < 3 )  ? MCalibrationCam::kBLUE :
+              ( nr < 5 )  ? MCalibrationCam::kUV :
+              ( nr < 11 ) ? MCalibrationCam::kBLUE :
+              ( nr < 13 ) ? MCalibrationCam::kUV :
+              ( nr < 14 ) ? MCalibrationCam::kBLUE :
+              ( nr < 16 ) ? MCalibrationCam::kGREEN :
+              MCalibrationCam::kCT1;
+
+	  switch (nr)
+	    {
+	    case 0: 
+	      fStrength = 5;
+	      break;
+	    case 1: 
+	      fStrength = 2.;
+	      break;
+	    case 2: 
+	      fStrength = 5.;
+	      break;
+	    case 3: 
+	      fStrength = 1.;
+	      break;
+	    case 4: 
+	      fStrength = 2.;
+	      break;
+	    case 5: 
+	      fStrength = 5.;
+	      break;
+	    case 6: 
+	      fStrength = 5.;
+	      break;
+	    case 7: 
+	      fStrength = 2.;
+	      break;
+	    case 8: 
+	      fStrength = 0.2;
+	      break;
+	    case 9: 
+	      fStrength = 0.;
+	      break;
+	    case 10: 
+	      fStrength = 1.;
+	      break;
+	    case 11: 
+	      fStrength = 5.;
+	      break;
+	    case 12: 
+	      fStrength = 5.;
+	      break;
+	    case 13: 
+	      fStrength = 5.;
+	      break;
+	    case 14: 
+	      fStrength = 1;
+	      break;
+	    case 15: 
+	      fStrength = 0.2;
+	      break;
+	    }
+      }
+  }
+
+  if (fColor == MCalibrationCam::kNONE)
+  {
+      CheckAndSet(proj, "gree", MCalibrationCam::kGREEN, 1.);
+      CheckAndSet(proj, "blue", MCalibrationCam::kBLUE,  1.);
+      CheckAndSet(proj, "uv",   MCalibrationCam::kUV,    1.);
+      CheckAndSet(proj, "ct1",  MCalibrationCam::kCT1,   1.);
+
+      if (fColor != MCalibrationCam::kNONE)
+          *fLog << inf << "Color determined from project-name (" << proj << ")... ";
+      else
+          if (proj.Contains("cl",TString::kIgnoreCase))
+          {
+              *fLog << err;
+              *fLog << "This run has been taken with the continuous light source." << endl;
+              *fLog << "It cannot be used for calibration. Try to run a pedestal extraction on it." << endl;
+              return kFALSE;
+          }
+  }
+  else
+      *fLog << inf << "Color and Intensity determined from project-name (" << proj << ")... ";
+
+  if (fColor == MCalibrationCam::kNONE)
+  {
+      *fLog << err;
+      *fLog << "Sorry, calibration run " << num << " was taken before the events could be" << endl;
+      *fLog << "flagged with a color by the digital modul and no color" << endl;
+      *fLog << "could be determined... abort." << endl;
+      return kFALSE;
+  }
+
+  switch (fColor)
+  {
+  case MCalibrationCam::kGREEN: *fLog << "Green.";  break;
+  case MCalibrationCam::kBLUE:  *fLog << "Blue.";   break;
+  case MCalibrationCam::kUV:    *fLog << "UV.";     break;
+  case MCalibrationCam::kCT1:   *fLog << "CT1.";    break;
+  default: break;
+  }
+  *fLog << endl;
+
+  fIsValid = kTRUE;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the pattern to MCalibrationPattern from outside, if fIsValid is set.
+//
+Int_t MCalibColorSet::Process()
+{
+
+  if (fIsValid)
+    {
+      if (fColor == MCalibrationCam::kNONE)
+        return kCONTINUE;
+
+      fPattern->SetPulserColor(fColor);
+      fPattern->SetPulserStrength(fStrength);
+    }
+  
+  return kTRUE;
+}
+
+Int_t MCalibColorSet::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (IsEnvDefined(env, prefix, "ExplicitColor", print))
+    {
+      TString dat = GetEnvValue(env, prefix, "ExplicitColor", "");
+      if (dat.BeginsWith("green", TString::kIgnoreCase))
+        SetExplicitColor(MCalibrationCam::kGREEN);
+      if (dat.BeginsWith("blue", TString::kIgnoreCase))
+        SetExplicitColor(MCalibrationCam::kBLUE);
+      if (dat.BeginsWith("uv", TString::kIgnoreCase))
+        SetExplicitColor(MCalibrationCam::kUV);
+      if (dat.BeginsWith("ct1", TString::kIgnoreCase))
+        SetExplicitColor(MCalibrationCam::kCT1);
+      rc = kTRUE;
+    }
+
+  return rc;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibColorSet.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibColorSet.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibColorSet.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MCalibColorSet
+#define MARS_MCalibColorSet
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MParList;
+class MCalibrationPattern;
+class MRawEvtHeader;
+
+class MCalibColorSet : public MTask
+{
+private:
+
+  static const Int_t gkIFAEBoxInaugurationRun; //! Run number of first IFAE box calibration (set to: 20113)
+  static const Int_t gkMCRunLimit;             //! Maximum MC run number (now set to: 1000)
+  static const UInt_t gkFirstRunWithFinalBits; //! Run number of first functionning digital modules 
+  
+  MCalibrationPattern *fPattern;               //! Calibration Pattern with the pulse pattern information
+  MRawEvtHeader       *fHeader;                //! Event header with the project name
+  
+  MCalibrationCam::PulserColor_t fColor;       //  Pulser Color to be set
+  Float_t                        fStrength;    //  Pulser Strength to be set
+
+  Bool_t fIsValid;                             //  Have to set the pulse pattern?
+  Bool_t fIsExplicitColor;                     //  Is colour set explicitely from outside (for MC)? 
+  
+  void CheckAndSet(const TString &str, const char *regexp, MCalibrationCam::PulserColor_t col, Float_t strength);
+
+  Bool_t ReInit(MParList *pList);
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MCalibColorSet(const char *name=NULL, const char *title=NULL);
+  
+  void Clear(const Option_t *o="");
+
+  void SetExplicitColor( const MCalibrationCam::PulserColor_t col, const Float_t strength=10.) 
+    {
+      fIsExplicitColor = kTRUE;
+      fColor    = col;
+      fStrength = 10.;
+    }
+  
+  ClassDef(MCalibColorSet, 0) // Task to workaround missing colors
+};
+    
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MCalibColorSteer.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibColorSteer.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibColorSteer.cc	(revision 9772)
@@ -0,0 +1,387 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 09/2004 <mailto:markus@ifae.es>
+!         
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MCalibColorSteer
+//
+//  Steers the occurrance of different calibration colours in one calibration 
+//  run. 
+// 
+//  Input Containers:
+//   MCalibrationPattern
+//   MParList
+//   MCalibrationIntensityChargeCam
+//   MCalibrationIntensityRelTimeCam
+//   MBadPixelsIntensityCam 
+//
+//  Output Containers:
+//   MCalibrationIntensityChargeCam
+//   MCalibrationIntensityRelTimeCam
+//   MBadPixelsIntensityCam 
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibColorSteer.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MHCalibrationCam.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationBlindCam.h"
+
+#include "MCalibrationIntensityChargeCam.h"
+#include "MCalibrationIntensityBlindCam.h"
+#include "MCalibrationIntensityQECam.h"
+#include "MCalibrationIntensityRelTimeCam.h"
+
+#include "MBadPixelsIntensityCam.h"
+
+#include "MCalibrationChargeCalc.h"
+#include "MCalibrationRelTimeCalc.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MCalibrationPattern.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MCalibColorSteer);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. 
+//
+MCalibColorSteer::MCalibColorSteer(const char *name, const char *title)
+    : fCalibPattern(NULL), fGeom(NULL), fParList(NULL), 
+      fIntensCharge(NULL), fIntensRelTime(NULL), fIntensBad(NULL),
+      fBad(NULL), fChargeCalc(NULL), fRelTimeCalc(NULL), fPattern(0)
+{
+
+  fName  = name  ? name  : "MCalibColorSteer";
+  fTitle = title ? title : "Task to steer the processing of different colours in the calibration events";
+
+}
+
+// -----------------------------------------------------------------------------------
+//
+// The following container are searched for and execution aborted if not in MParList:
+//  - MCalibrationPattern
+//  - MTaskList
+//
+Int_t MCalibColorSteer::PreProcess(MParList *pList)
+{
+
+  fCalibPattern = (MCalibrationPattern*)pList->FindObject("MCalibrationPattern");
+  if (!fCalibPattern)
+    {
+      *fLog << err << "MCalibrationPattern not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!fRunHeader)
+    {
+      *fLog << err << "MRawRunHeader not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fEvtHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+  if (!fEvtHeader)
+    {
+      *fLog << err << "MRawEvtHeader not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "MGeomCam not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fParList = pList;
+  if (!fParList)
+    {
+      *fLog << err << "MParList not found... abort." << endl;
+      return kFALSE;
+    }
+
+  MTaskList *tlist = (MTaskList*)pList->FindObject("MTaskList");
+  if (!tlist)
+    {
+      *fLog << err << "MTaskList not found... abort." << endl;
+      return kFALSE;
+    }
+
+  // 
+  // Look for the MBadPixels Intensity Cam
+  //
+  fIntensBad = (MBadPixelsIntensityCam*)pList->FindCreateObj("MBadPixelsIntensityCam");
+  if (fIntensBad)
+    *fLog << inf << "Found MBadPixelsIntensityCam ... " << flush;
+  else
+    return kFALSE;
+  
+  // 
+  // Look for the MBadPixels Intensity Cam
+  //
+  fBad = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (fBad)
+    {
+      *fLog << inf << "Found also MBadPixelsCam ... " << flush;
+      fIntensBad->GetCam()->Merge(*fBad);
+    }
+  else
+    return kFALSE;
+  
+  // 
+  // Look for the MCalibrationIntensityBlindCam
+  //
+  fIntensBlind = (MCalibrationIntensityBlindCam*)pList->FindCreateObj("MCalibrationIntensityBlindCam");
+
+  if (fIntensBlind)
+    *fLog << inf << "Found MCalibrationIntensityBlindCam ... " << flush;
+  else
+    return kFALSE;
+  
+  // 
+  // Look for the MFillH name "FillChargeCam". In case yes, initialize the 
+  // corresponding IntensityCam
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationChargeCam")))
+  {
+
+    fIntensCharge = (MCalibrationIntensityChargeCam*)pList->FindCreateObj("MCalibrationIntensityChargeCam");
+    fIntensQE     = (MCalibrationIntensityQECam*)    pList->FindCreateObj("MCalibrationIntensityQECam");
+
+    fChargeCalc   = (MCalibrationChargeCalc*)tlist->FindObject("MCalibrationChargeCalc");
+
+    *fLog << inf << "Found MHCalibrationChargeCam ... " << flush;
+
+    if (!fIntensCharge)
+      {
+        *fLog << err << "Could not find nor create MCalibrationIntensityChargeCam abort... " << endl;
+        return kFALSE;
+      }
+    
+    if (!fIntensQE)
+      {
+        *fLog << err << "Could not find nor create MCalibrationIntensityQECam abort... " << endl;
+        return kFALSE;
+      }
+    
+    if (!fChargeCalc)
+      {
+        *fLog << err << "Could not find MCalibrationChargeCalc abort... " << endl;
+        return kFALSE;
+      }
+  }
+      
+  // 
+  // Look for the MFillH name "FillRelTimeCam". In case yes, initialize the 
+  // corresponding IntensityCam
+  //
+  if (pList->FindObject(AddSerialNumber("MHCalibrationRelTimeCam")))
+  {
+
+    fIntensRelTime = (MCalibrationIntensityRelTimeCam*)pList->FindCreateObj("MCalibrationIntensityRelTimeCam");
+    fRelTimeCalc   = (MCalibrationRelTimeCalc*)tlist->FindObject(AddSerialNumber("MCalibrationRelTimeCalc"));
+
+    *fLog << inf << "Found MHCalibrationRelTimeCam ... " << flush;
+
+    if (!fIntensRelTime)
+      {
+        *fLog << err << "Could not find nor create MCalibrationIntensityRelTimeCam abort... " << endl;
+        return kFALSE;
+      }
+
+    if (!fRelTimeCalc)
+      {
+        *fLog << err << "Could not find MCalibrationRelTimeCalc abort... " << endl;
+        return kFALSE;
+      }
+  }
+      
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reads the pattern from MCalibrationPattern and initializes new containers in the 
+// Intensity Cams, if the pattern has changed. Executes Finalize of the 
+// MCalibration*Calc classes in that case.
+//
+Int_t MCalibColorSteer::Process()
+{
+
+  const UInt_t pattern = fEvtHeader->GetPulserSlotPattern();
+
+  if (fPattern == 0)
+    {
+      fPattern = pattern;
+      return kTRUE;
+    }
+
+  if (pattern == 0 || pattern == fPattern)
+    return kTRUE;
+
+  *fLog << inf << GetDescriptor() << " : old pattern: " << fPattern << flush;
+
+  fPattern = pattern;
+  
+  *fLog << " : new pattern: " << pattern << flush;
+
+  //
+  // Finalize Possible calibration histogram classes...
+  //
+  *fLog << inf << GetDescriptor() << " : Finalize calibration histograms..." << flush;
+  if (Finalize("MHCalibrationChargeCam"))      *fLog << "MHCalibrationChargeCam";
+  if (Finalize("MHCalibrationChargeBlindCam")) *fLog << "MHCalibrationChargeBlindCam";
+  if (Finalize("MHCalibrationRelTimeCam"))     *fLog << "MHCalibrationRelTimeCam";  
+  if (Finalize("MHCalibrationTestCam"))        *fLog << "MHCalibrationChargeCam";  
+  if (Finalize("MHCalibrationTestTimeCam"))    *fLog << "MHCalibrationChargeCam";  
+
+  //
+  // Finalize possible calibration calculation tasks
+  //
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() << " : Finalize calibration calculations..." << flush;
+  if (fChargeCalc)
+    fChargeCalc->Finalize();
+  if (fRelTimeCalc)
+    fRelTimeCalc->Finalize();
+
+  ReInitialize();
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Searches for name in the MParList and calls, if existing: 
+// - MHCalibrationCam::Finalize()
+// - MHCalibrationCam::ResetHists()
+//
+Bool_t MCalibColorSteer::Finalize(const char* name)
+{
+
+  MHCalibrationCam *hist = (MHCalibrationCam*)fParList->FindObject(name);
+  if (hist)
+    {
+      hist->Finalize();
+      hist->ResetHists();
+      hist->SetColor( fCalibPattern->GetPulserColor());
+      return kTRUE;
+    }
+
+  return kFALSE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Re-Intitializes new containers inside the Intensity Cams. 
+// From now on, a call to the IntensityCam functions returns pointers 
+// to the newly created Containers.
+//
+Bool_t MCalibColorSteer::ReInitialize()
+{
+
+  *fLog << endl;
+
+  TString namep = GetNamePattern();
+
+  if (fIntensBad)
+    {
+      fIntensBad->AddToList(Form("MBadPixelsCam%s",namep.Data()),*fGeom);
+      *fLog << inf << "New MBadPixelsCam with " << namep << endl;
+      fIntensBad->GetCam()->Merge(*fBad);
+      *fLog << inf << "Merged new MBadPixelsCam with first of list" << endl;
+    }
+  if (fIntensCharge)
+    {
+      fIntensCharge->AddToList(Form("MCalibrationChargeCam%s",namep.Data()),*fGeom);
+      MCalibrationCam *cam = fIntensCharge->GetCam();
+      cam->SetPulserColor(fCalibPattern->GetPulserColor());
+      *fLog << inf << "New MCalibrationChargeCam with name: " << cam->GetName() << endl;
+    }
+  if (fIntensQE)
+    {
+      fIntensQE->AddToList(Form("MCalibrationQECam%s",namep.Data()),*fGeom);
+      *fLog << inf << "New MCalibrationQECam with: " << namep << endl;
+    }
+
+  if (fIntensBlind)
+    {
+      fIntensBlind->AddToList(Form("MCalibrationBlindCam%s",namep.Data()),*fGeom);
+      MCalibrationCam *cam = fIntensBlind->GetCam();
+      cam->SetPulserColor(fCalibPattern->GetPulserColor());
+      *fLog << inf << "New MCalibrationBlindCam with name: " << cam->GetName() << endl;
+    }
+
+  if (fIntensRelTime)
+    {
+      fIntensRelTime->AddToList(Form("MCalibrationRelTimeCam%s",namep.Data()),*fGeom);
+      MCalibrationCam *cam = fIntensRelTime->GetCam();
+      cam->SetPulserColor(fCalibPattern->GetPulserColor());
+      *fLog << inf << "New MCalibrationRelTimeCam with name: " << cam->GetName() << endl;
+    }
+
+  return kTRUE;
+
+}
+
+TString MCalibColorSteer::GetNamePattern()
+{
+
+  const Float_t strength = fCalibPattern->GetPulserStrength();
+  const MCalibrationCam::PulserColor_t col = fCalibPattern->GetPulserColor();
+
+  TString result = Form("%2.1f",strength);
+  
+  switch (col)
+    {
+    case MCalibrationCam::kCT1:
+      result += "CT1";
+      break;
+    case MCalibrationCam::kGREEN:
+      result += "GREEN";
+      break;
+    case MCalibrationCam::kBLUE:
+      result += "BLUE";
+      break;
+    case MCalibrationCam::kUV:
+      result += "UV";
+      break;
+    default:
+      break;
+    }
+  return result;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibColorSteer.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibColorSteer.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibColorSteer.h	(revision 9772)
@@ -0,0 +1,59 @@
+#ifndef MARS_MCalibColorSteer
+#define MARS_MCalibColorSteer
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MGeomCam;
+class MCalibrationPattern;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MCalibrationChargeCalc;
+class MCalibrationRelTimeCalc;
+class MCalibrationIntensityChargeCam;
+class MCalibrationIntensityBlindCam;
+class MCalibrationIntensityQECam;
+class MCalibrationIntensityRelTimeCam;
+class MBadPixelsIntensityCam;
+class MBadPixelsCam;
+class MCalibColorSteer : public MTask
+{
+private:
+
+
+  MCalibrationPattern             *fCalibPattern;    //!
+  MRawEvtHeader                   *fEvtHeader;       //!
+  MRawRunHeader                   *fRunHeader;       //!
+  MGeomCam                        *fGeom;            //!
+  MParList                        *fParList;         //!
+  MCalibrationIntensityChargeCam  *fIntensCharge;    //!
+  MCalibrationIntensityBlindCam   *fIntensBlind;     //!  
+  MCalibrationIntensityQECam      *fIntensQE;        //!
+  MCalibrationIntensityRelTimeCam *fIntensRelTime;   //!
+  MBadPixelsIntensityCam          *fIntensBad;       //!
+  MBadPixelsCam                   *fBad;             //!
+  
+  MCalibrationChargeCalc          *fChargeCalc;      //!
+  MCalibrationRelTimeCalc         *fRelTimeCalc;     //!
+                                                     
+  UInt_t fPattern;                                   
+  
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  
+  Bool_t ReInitialize();
+  Bool_t Finalize(const char* name);
+  TString GetNamePattern();
+  
+public:
+
+    MCalibColorSteer(const char *name=NULL, const char *title=NULL);
+    ~MCalibColorSteer() {}
+
+    ClassDef(MCalibColorSteer, 1) // Task to steer the processing of multiple calibration colours
+};
+    
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MCalibConstCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibConstCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibConstCam.cc	(revision 9772)
@@ -0,0 +1,275 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug    01/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibConstCam                                                          //
+//                                                                         //
+// Hold the temporary conversion factors for MCalibrateDatara              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibConstCam.h"
+#include "MCalibConstPix.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MCalibConstCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Creates a TClonesArray of MCalibConstPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MCalibConstCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibConstPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MCalibConstCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibConstPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MCalibConstCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+MCalibConstCam::MCalibConstCam(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MCalibConstCam";
+  fTitle = title ? title : "Temporary Storage for Calibration Constants";
+  
+  fArray            = new TClonesArray("MCalibConstPix", 1);
+  fAverageAreas     = new TClonesArray("MCalibConstPix", 1);
+  fAverageSectors   = new TClonesArray("MCalibConstPix", 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the following TClonesArray's of MCalibConstPix containers:
+// - fArray
+// - fAverageAreas
+// - fAverageSectors
+//  
+MCalibConstCam::~MCalibConstCam()
+{
+  delete fArray;
+  delete fAverageAreas;
+  delete fAverageSectors;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MCalibConstCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageAreas
+//
+void MCalibConstCam::InitAverageAreas(const UInt_t i)
+{
+  fAverageAreas->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageSectors
+//
+void MCalibConstCam::InitAverageSectors(const UInt_t i)
+{
+  fAverageSectors->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MCalibConstCam::Init(const MGeomCam &geom)
+{
+  InitSize          (geom.GetNumPixels() );
+  InitAverageAreas  (geom.GetNumAreas()  );
+  InitAverageSectors(geom.GetNumSectors());
+}
+
+// --------------------------------------------------------------------------
+//
+// This function returns the current size of the TClonesArray 
+// independently if the MCalibConstPix is filled with values or not.
+//
+// Get the size of the MCalibConstCam
+//
+Int_t MCalibConstCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageAreas
+// independently if the MCalibConstPix is filled with values or not.
+//
+const Int_t MCalibConstCam::GetNumAverageArea() const
+{
+  return fAverageAreas->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageSectors
+// independently if the MCalibConstPix is filled with values or not.
+//
+const Int_t MCalibConstCam::GetNumAverageSector() const
+{
+  return fAverageSectors->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MCalibConstPix &MCalibConstCam::operator[](Int_t i)
+{
+    return *static_cast<MCalibConstPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MCalibConstPix &MCalibConstCam::operator[](Int_t i) const
+{
+    return *static_cast<MCalibConstPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MCalibConstPix &MCalibConstCam::GetAverageArea(UInt_t i)
+{
+  return *static_cast<MCalibConstPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MCalibConstPix &MCalibConstCam::GetAverageArea(UInt_t i) const 
+{
+  return *static_cast<MCalibConstPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MCalibConstPix &MCalibConstCam::GetAverageSector(UInt_t i)
+{
+  return *static_cast<MCalibConstPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MCalibConstPix &MCalibConstCam::GetAverageSector(UInt_t i) const 
+{
+  return *static_cast<MCalibConstPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------
+//
+// Calls the ForEach macro for the TClonesArray fArray with the argument Clear()
+// 
+// Loops over the fAverageAreas, calling the function Clear() for 
+// every entry in fAverageAreas
+//
+// Loops over the fAverageSectors, calling the function Clear() for 
+// every entry in fAverageSectors
+// 
+void MCalibConstCam::Clear(Option_t *o)
+{
+    { fArray->ForEach(TObject, Clear)(); }
+    { fAverageAreas->ForEach(TObject, Clear)(); }
+    { fAverageSectors->ForEach(TObject, Clear)(); }
+  
+}
+
+void MCalibConstCam::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << endl;
+    int id = 0;
+
+    TIter Next(fArray);
+    MCalibConstPix *pix;
+    while ((pix=(MCalibConstPix*)Next()))
+    {
+        *fLog << id 
+	      << Form(": Conversion Factor: %4.3f  Global F-Factor: %4.3f",pix->GetCalibConst(),pix->GetCalibFFactor()) 
+	      << endl;
+        id++;
+    }
+}
+
+
+Bool_t MCalibConstCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (GetSize() <= idx)
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+      val = (*this)[idx].GetCalibConst();
+      break;
+    case 1:
+      val = (*this)[idx].GetCalibFFactor();
+      break;
+    case 2:
+      val = (*this)[idx].GetCalibConst()*cam.GetPixRatio(idx);
+      break;
+    default:
+      return kFALSE;
+    }
+
+    return val>0.;
+}
+
+void MCalibConstCam::DrawPixelContent(Int_t idx) const
+{
+    *fLog << warn << "MCalibConstCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibConstCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibConstCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibConstCam.h	(revision 9772)
@@ -0,0 +1,55 @@
+#ifndef MARS_MCalibConstCam
+#define MARS_MCalibConstCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+
+class MGeomCam;
+class MCalibConstPix;
+class MCalibConstCam : public MParContainer, public MCamEvent
+{
+private:
+
+  TClonesArray *fArray;           //-> Array of MCalibConstPix, one per pixel
+  TClonesArray *fAverageAreas;    //-> Array of MCalibConstPix, one per pixel area
+  TClonesArray *fAverageSectors;  //-> Array of MCalibConstPix, one per camera sector
+
+public:
+
+  MCalibConstCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibConstCam();
+  
+  void Clear(Option_t *o="");
+  
+  // Getters 
+        MCalibConstPix &GetAverageArea   ( UInt_t i );
+  const MCalibConstPix &GetAverageArea   ( UInt_t i )            const;
+  const Int_t           GetNumAverageArea()                      const;
+        MCalibConstPix &GetAverageSector ( UInt_t i );
+  const MCalibConstPix &GetAverageSector ( UInt_t i )            const;
+  const Int_t           GetNumAverageSector()                    const;
+  Int_t                 GetSize          ()                      const;
+
+        MCalibConstPix &operator[]     ( Int_t i             );
+  const MCalibConstPix &operator[]     ( Int_t i             ) const;
+
+  void  Init                           ( const MGeomCam &geom);
+  void  InitSize                       ( const UInt_t i      );
+  void  InitAverageAreas               ( const UInt_t i      );
+  void  InitAverageSectors             ( const UInt_t i      );
+
+  void Print(Option_t *o="") const;
+  
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void  DrawPixelContent(Int_t idx) const;
+
+  ClassDef(MCalibConstCam, 0)	// Temporary Storage for calibration constants
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibConstPix.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibConstPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibConstPix.cc	(revision 9772)
@@ -0,0 +1,42 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug    01/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCalibConstPix
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MCalibConstPix.h"
+
+ClassImp(MCalibConstPix);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCalibConstPix::MCalibConstPix()
+{
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibConstPix.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibConstPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibConstPix.h	(revision 9772)
@@ -0,0 +1,36 @@
+#ifndef MARS_MCalibConstPix
+#define MARS_MCalibConstPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCalibConstPix : public MParContainer
+{
+private:
+
+    Float_t fCalibConst;        // conversion factor (modified after each interlaced cal. update)
+    Float_t fCalibFFactor;      // global F-Factor   (modified after each interlaced cal. update)
+
+public:
+ 
+    MCalibConstPix();
+    
+    void Clear(Option_t *o="")
+      {
+	fCalibConst   = -1.;
+	fCalibFFactor = -1.;
+      }
+    
+    // Getters
+    Float_t GetCalibConst()   const { return fCalibConst;   }
+    Float_t GetCalibFFactor() const { return fCalibFFactor; }
+
+    // Setters
+    void SetCalibConst  ( const Float_t f )  { fCalibConst   = f; }
+    void SetCalibFFactor( const Float_t f )  { fCalibFFactor = f; }
+
+    ClassDef(MCalibConstPix, 0) // Temporay Storage Calibraion Constant of one pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrateData.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrateData.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrateData.cc	(revision 9772)
@@ -0,0 +1,889 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez    12/2003 <mailto:jlopez@ifae.es>
+!   Author(s): Javier Rico     01/2004 <mailto:jrico@ifae.es>
+!   Author(s): Wolfgang Wittek 02/2004 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Markus Gaug     04/2004 <mailto:markus@ifae.es>
+!   Author(s): Hendrik Bartko  08/2004 <mailto:hbartko@mppmu.mpg.de>
+!   Author(s): Thomas Bretz    08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrateData
+//
+//   This task takes the integrated charge from MExtractedSignal and applies
+//   the calibration constants from MCalibrationCam to convert the summed FADC 
+//   slices into photons. The number of photons obtained is stored in MSignalCam. 
+//   Optionally, the calibration of pedestals from an MPedestalCam container into 
+//   an MPedPhotCam container can be chosen with the member functions 
+//   SetPedestalType(). Default is 'kRun', i.e. calibration of pedestals from a 
+//   dedicated pedestal run.
+//   In case, the chosen pedestal type is kRun or kEvent, in ReInit() the MPedPhotCam 
+//   container is filled using the information from MPedestalCam, MExtractedSignalCam, 
+//   MCalibrationChargeCam and MCalibrationQECam
+//
+//   Selection of different calibration methods is allowed through the 
+//   SetCalibrationMode() member function (default: kFfactor)
+//
+//   The calibration modes which exclude non-valid pixels are the following: 
+//
+//     kFfactor:    calibrates using the F-Factor method
+//     kBlindpixel: calibrates using the BlindPixel method
+//     kBlindpixel: calibrates using the BlindPixel method
+//     kFlatCharge: perform a charge flat-flatfielding. Outer pixels are area-corrected.
+//     kDummy:      calibrates with fixed conversion factors of 1 and errors of 0.
+//
+//   The calibration modes which include all pixels regardless of their validity is:
+//
+//     kNone:       calibrates with fixed conversion factors of 1 and errors of 0.
+//
+//   Use the kDummy and kNone methods ONLY FOR DEBUGGING!
+//
+//
+//   This class can calibrate data and/or pedestals. To switch off calibration of data
+//   set the Calibration Mode to kSkip. To switch on pedestal calibration call either
+//     SetPedestalFlag(MCalibrateData::kRun)    (calibration is done once in ReInit)
+//     SetPedestalFlag(MCalibrateData::kEvent)  (calibration is done for each event)
+//
+//   By calling AddPedestal() you can control the name of the
+//   MPedestalCam and/or MPedPhotCam container which is used.
+//
+//   Assume you want to calibrate "MPedestalCam" once and "MPedestalFromLoGain" [MPedestalCam]
+//   event-by-event, so:
+//     MCalibrateData cal1;
+//     cal1.SetCalibrationMode(MCalibrateData::kSkip);
+//     cal1.SetPedestalFlag(MCalibrateData::kRun);
+//     MCalibrateData cal2;
+//     cal2.SetCalibrationMode(MCalibrateData::kSkip);
+//     cal2.AddPedestal("FromLoGain");
+//     cal2.SetPedestalFlag(MCalibrateData::kEvent);
+//
+//
+//   Input Containers:
+//    [MPedestalCam]
+//    [MExtractedSignalCam]
+//    [MCalibrationChargeCam]
+//    [MCalibrationQECam]
+//    MBadPixelsCam
+//
+//   Output Containers:
+//    [MPedPhotCam]
+//    [MSignalCam]
+//
+// See also: MJCalibration, MJPedestal, MJExtractSignal, MJExtractCalibTest
+// 
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateData.h"
+
+#include <fstream>
+
+#include <TEnv.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MH.h"
+
+#include "MGeomCam.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+#include "MCalibConstCam.h"
+#include "MCalibConstPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MSignalCam.h"
+
+ClassImp(MCalibrateData);
+
+using namespace std;
+
+const Float_t MCalibrateData::fgCalibConvMinLimit = 0.01;
+const Float_t MCalibrateData::fgCalibConvMaxLimit = 5.;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets all pointers to NULL
+// 
+// Initializes:
+// - fCalibrationMode to kDefault
+// - fPedestalFlag to kNo
+//
+MCalibrateData::MCalibrateData(CalibrationMode_t calmode,const char *name, const char *title) 
+    : fGeomCam(NULL),   fBadPixels(NULL), fCalibrations(NULL), 
+      fQEs(NULL), fSignals(NULL), fCerPhotEvt(NULL), fCalibConstCam(NULL),
+      fPedestalFlag(kNo), fSignalType(kPhot), fRenormFactor(1.)
+{
+
+  fName  = name  ? name  : "MCalibrateData";
+  fTitle = title ? title : "Task to calculate the number of photons in one event";
+  
+  SetCalibrationMode(calmode);
+  
+  SetCalibConvMinLimit();
+  SetCalibConvMaxLimit();
+
+  fNamesPedestal.SetOwner();
+}
+
+void MCalibrateData::AddPedestal(const char *name)
+{
+    TString ped(name);
+    TString pho(name);
+    ped.Prepend("MPedestal");
+    pho.Prepend("MPedPhot");
+
+    fNamesPedestal.Add(new TNamed(ped, pho));
+}
+
+void MCalibrateData::AddPedestal(const char *pedestal, const char *pedphot)
+{
+    fNamesPedestal.Add(new TNamed(pedestal, pedphot));
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//
+//  - MGeomCam
+//  - MPedestalCam
+//  - MCalibrationChargeCam
+//  - MCalibrationQECam
+//  - MExtractedSignalCam
+//  - MBadPixelsCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedPhotCam
+//  - MSignalCam
+//
+Int_t MCalibrateData::PreProcess(MParList *pList)
+{
+    // input containers
+
+    fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+    {
+        *fLog << err << AddSerialNumber("MBadPixelsCam") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+    fSignals    = 0;
+    fCerPhotEvt = 0;
+    if (fCalibrationMode>kSkip)
+    {
+        fSignals = (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+        if (!fSignals)
+        {
+            *fLog << err << AddSerialNumber("MExtractedSignalCam") << " not found ... aborting" << endl;
+            return kFALSE;
+        }
+
+        fCerPhotEvt = (MSignalCam*)pList->FindCreateObj(AddSerialNumber("MSignalCam"));
+        if (!fCerPhotEvt)
+            return kFALSE;
+
+        fCalibConstCam = (MCalibConstCam*)pList->FindCreateObj(AddSerialNumber("MCalibConstCam"));
+        if (!fCalibConstCam)
+            return kFALSE;
+    }
+
+    fCalibrations = 0;
+    fQEs          = 0;
+    if (fCalibrationMode>kNone)
+    {
+        fCalibrations = (MCalibrationChargeCam*)pList->FindObject(AddSerialNumber("MCalibrationChargeCam"));
+        if (!fCalibrations)
+        {
+            *fLog << err << AddSerialNumber("MCalibrationChargeCam") << " not found ... aborting." << endl;
+            return kFALSE;
+        }
+
+        fQEs = (MCalibrationQECam*)pList->FindObject(AddSerialNumber("MCalibrationQECam"));
+        if (!fQEs)
+        {
+            *fLog << err << AddSerialNumber("MCalibrationQECam") << " not found ... aborting." << endl;
+            return kFALSE;
+        }
+
+    }
+
+    if (fNamesPedestal.GetSize()>0 && fPedestalFlag==kNo)
+    {
+        *fLog << warn << "Pedestal list contains entries, but mode is set to kNo... setting to kEvent." << endl;
+        fPedestalFlag = kEvent;
+    }
+
+    if (fPedestalFlag)
+    {
+        if (fNamesPedestal.GetSize()==0)
+        {
+            *fLog << inf << "No container names specified... using default: MPedestalCam and MPedPhotCam." << endl;
+            AddPedestal();
+        }
+
+        fPedestalCams.Clear();
+        fPedPhotCams.Clear();
+
+        TIter Next(&fNamesPedestal);
+        TObject *o=0;
+        while ((o=Next()))
+        {
+            TObject *pedcam = pList->FindObject(AddSerialNumber(o->GetName()), "MPedestalCam");
+            if (!pedcam)
+            {
+                *fLog << err << AddSerialNumber(o->GetName()) << " [MPedestalCam] not found ... aborting" << endl;
+                return kFALSE;
+            }
+            TObject *pedphot = pList->FindCreateObj("MPedPhotCam", AddSerialNumber(o->GetTitle()));
+            if (!pedphot)
+                return kFALSE;
+
+            fPedestalCams.Add(pedcam);
+            fPedPhotCams.Add(pedphot);
+        }
+    }
+
+    switch (fSignalType)
+      {
+      case kPhe:
+        fRenormFactor = MCalibrationQEPix::gkDefaultAverageQE;
+        break;
+      case kPhot:
+        fRenormFactor = 1.;
+        break;
+      }
+
+    fCalibConsts.Reset();
+    fCalibFFactors.Reset();
+    fHiLoConv.Reset();
+    fHiLoConvErr.Reset();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit searches for the following input containers:
+//
+//  - MGeomCam
+//
+// Check for validity of the selected calibration method, switch to a 
+// different one in case of need
+//
+// Fill the MPedPhotCam container using the information from MPedestalCam,
+// MExtractedSignalCam and MCalibrationCam
+//
+Bool_t MCalibrateData::ReInit(MParList *pList)
+{
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+    {
+        *fLog << err << "No MGeomCam found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // Sizes might have changed
+    if (fPedestalFlag)
+    {
+        TIter Next(&fPedestalCams);
+        MPedestalCam *cam=0;
+        while ((cam=(MPedestalCam*)Next()))
+        if ((Int_t)cam->GetSize() != fSignals->GetSize())
+        {
+            *fLog << err << "Size mismatch of " << cam->GetDescriptor() << " and MCalibrationCam... abort." << endl;
+            return kFALSE;
+        }
+    }
+
+    if(fCalibrationMode == kBlindPixel && !fQEs->IsBlindPixelMethodValid())
+    {
+        *fLog << warn << "Blind pixel calibration method not valid, switching to F-factor method" << endl;
+        fCalibrationMode = kFfactor;
+    }
+
+    if(fCalibrationMode == kPinDiode && !fQEs->IsPINDiodeMethodValid())
+    {
+        *fLog << warn << "PIN diode calibration method not valid, switching to F-factor method" << endl;
+        fCalibrationMode = kFfactor;
+    }
+
+    if(fCalibrationMode == kCombined && !fQEs->IsCombinedMethodValid())
+    {
+        *fLog << warn << "Combined calibration method not valid, switching to F-factor method" << endl;
+        fCalibrationMode = kFfactor;
+    }
+
+    //
+    // output information or warnings:
+    //
+    switch(fCalibrationMode)
+    {
+    case kBlindPixel:
+        break;
+    case kFfactor:
+        break;
+    case kPinDiode:
+        *fLog << err << "PIN Diode Calibration mode not yet available!" << endl;
+        return kFALSE;
+        break;
+    case kCombined:
+        *fLog << err << "Combined Calibration mode not yet available!" << endl;
+        return kFALSE;
+        break;
+    case kFlatCharge:
+        *fLog << warn << "WARNING - Flat-fielding charges - only for muon calibration!" << endl;
+        break;
+    case kDummy:
+        *fLog << warn << "WARNING - Dummy calibration, no calibration applied!" << endl;
+        break;
+    case kNone:
+        *fLog << warn << "WARNING - No calibration applied!" << endl;
+        break;
+    default:
+        *fLog << warn << "WARNING - Calibration mode value (" << fCalibrationMode << ") not known" << endl;
+        return kFALSE;
+    }
+
+    //
+    // output information or warnings:
+    //
+    switch(fSignalType)
+    {
+    case kPhe:
+      *fLog << warn << "WARNING - Renormalization to photo-electrons applied!" << endl;
+      break;
+    case kPhot:
+      break;
+    }
+    
+    const Int_t npixels = fGeomCam->GetNumPixels();
+
+    if (fCalibrationMode > kNone)
+      {
+        
+        if (fCalibrations->GetSize() != npixels)
+          {
+            *fLog << err << GetDescriptor()
+                  << ": Size mismatch between MGeomCam and MCalibrationChargeCam ... abort!" << endl;
+            return kFALSE;
+          }
+        
+        if (fBadPixels->GetSize() != npixels)
+          {
+            *fLog << err << GetDescriptor()
+                  << ": Size mismatch between MGeomCam and MBadPixelsCam ... abort!" << endl;
+            return kFALSE;
+          }
+        
+        if (fBadPixels->GetSize() != npixels)
+          {
+            *fLog << err << GetDescriptor()
+                  << ": Size mismatch between MGeomCam and MBadPixelsCam ... abort!" << endl;
+            return kFALSE;
+          }
+      }
+    
+    fCalibConsts  .Set(npixels);
+    fCalibFFactors.Set(npixels);
+    fHiLoConv     .Set(npixels);
+    fHiLoConvErr  .Set(npixels);
+    
+    if (!UpdateConversionFactors())
+      return kFALSE;
+
+    if (TestPedestalFlag(kRun))
+        Calibrate(kFALSE, kTRUE);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the conversion factors and F-Factors from MCalibrationCams into 
+// the arrays. Later, the here pre-calcualted conversion factors get simply 
+// copied from memory. 
+//
+// This function can be called from outside in case that the MCalibrationCams 
+// have been updated...
+//
+Bool_t MCalibrateData::UpdateConversionFactors( const MCalibrationChargeCam *updatecam)
+{
+
+    *fLog << inf << GetDescriptor() 
+          << ": Updating Conversion Factors... " << endl;
+    
+    fCalibConsts.Reset();
+    fCalibFFactors.Reset();
+    fHiLoConv.Reset();
+    fHiLoConvErr.Reset();
+    
+    //
+    // For the moment, we use only a dummy zenith for the calibration:
+    //
+    const Float_t zenith = -1.;
+
+    UInt_t skip = 0;
+
+    for (UInt_t pixidx=0; pixidx<fGeomCam->GetNumPixels(); pixidx++)
+      {
+
+        Float_t hiloconv     = 1.;
+        Float_t hiloconverr  = 0.;
+        Float_t calibConv    = 1.;
+        Float_t calibConvVar = 0.;
+        Float_t calibFFactor = 0.;
+
+        Float_t calibQE       = 1.;
+        Float_t calibQEVar    = 0.;
+
+        Float_t calibUpdate   = 1.;
+
+	MCalibConstPix &cpix  = (*fCalibConstCam)[pixidx];
+	    
+        if(fCalibrationMode!=kNone)
+          {
+            if ((*fBadPixels)[pixidx].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+              {
+                skip++;
+		calibConv = -1.;
+                continue;
+             }
+            
+            MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*fCalibrations)[pixidx];
+            MCalibrationChargePix &avpix = (MCalibrationChargePix&)fCalibrations->GetAverageArea(0);
+            
+            hiloconv   = pix.GetConversionHiLo   ();
+            hiloconverr= pix.GetConversionHiLoErr();
+            
+            calibConv    = pix.GetMeanConvFADC2Phe();
+            calibConvVar = pix.GetMeanConvFADC2PheVar();
+            calibFFactor = pix.GetMeanFFactorFADC2Phot();
+            
+            MCalibrationQEPix &qe = (MCalibrationQEPix&) (*fQEs)[pixidx];
+
+            if (updatecam)
+              {
+                MCalibrationChargePix &upix = (MCalibrationChargePix&)(*updatecam)[pixidx];
+                //
+                // Correct for the possible change in amplification of the individual pixels chain
+                // 
+                const Float_t pixmean = upix.GetConvertedMean();
+                calibUpdate = (pixmean == 0.) ? 1. : pix.GetConvertedMean() / pixmean;
+                //
+                // Correct for global shifts in light emission
+                // 
+                MCalibrationChargePix &ugpix = (MCalibrationChargePix&)updatecam->GetAverageArea(0);
+
+                const Float_t globmean = avpix.GetConvertedMean();
+                calibUpdate = (globmean == 0.) ? 1. : ugpix.GetConvertedMean() / globmean;
+
+                MBadPixelsPix         &ubad  = (MBadPixelsPix&)        updatecam->GetAverageBadArea(0);
+                if (ubad.IsUncalibrated(MBadPixelsPix::kChargeIsPedestal))
+                  {
+                    *fLog << warn << GetDescriptor() << "Probably calibration pulses have been lost!!!!" << endl;
+                    *fLog << warn << "Will not update calib. factors any more!!!!" << endl;
+                    calibUpdate = 1.;
+                  }
+              }
+            
+            switch(fCalibrationMode)
+              {
+              case kFlatCharge:
+                {
+                  calibConv    = avpix.GetConvertedMean() 
+                              / (pix.GetConvertedMean() * fGeomCam->GetPixRatio(pixidx));
+                  calibConvVar = (avpix.GetMeanRelVar() + pix.GetMeanRelVar()) * calibConv * calibConv;
+                  if (pix.IsFFactorMethodValid())
+                    {
+                      const Float_t convmin1 = qe.GetQECascadesFFactor(zenith)/pix.GetMeanConvFADC2Phe();
+                      if (convmin1 > 0)
+                        calibFFactor *= TMath::Sqrt(convmin1);
+                      else
+                        calibFFactor = -1.;
+                    }
+                  break;
+                }
+              case kBlindPixel:
+                if (!qe.IsBlindPixelMethodValid())
+                  {
+                    skip++;
+                    continue;
+                  }
+                calibQE     = qe.GetQECascadesBlindPixel   ( zenith );
+                calibQEVar  = qe.GetQECascadesBlindPixelVar( zenith );
+                break;
+                
+              case kPinDiode:
+                if (!qe.IsPINDiodeMethodValid())
+                  {
+                    skip++;
+                    continue;
+                  }
+                calibQE     = qe.GetQECascadesPINDiode   ( zenith );
+                calibQEVar  = qe.GetQECascadesPINDiodeVar( zenith );
+                break;
+                
+              case kFfactor:
+                if (!pix.IsFFactorMethodValid())
+                  {
+                    skip++;
+                    continue;
+                  }
+                calibQE     = qe.GetQECascadesFFactor   ( zenith );
+                calibQEVar  = qe.GetQECascadesFFactorVar( zenith );
+                break;
+                
+              case kCombined:
+                if (!qe.IsCombinedMethodValid())
+                  {
+                    skip++;
+                    continue;
+                  }
+                calibQE     = qe.GetQECascadesCombined   ( zenith );
+                calibQEVar  = qe.GetQECascadesCombinedVar( zenith );
+                break;
+                
+              case kDummy:
+                hiloconv    = 1.;
+                hiloconverr = 0.;
+                calibUpdate = 1.;
+                break;
+              } /* switch calibration mode */
+          } /* if(fCalibrationMode!=kNone) */
+        else
+          {
+            calibConv  = 1./fGeomCam->GetPixRatio(pixidx);
+          }
+        
+        calibConv /= calibQE;
+
+        if (calibConv != 0. && calibQE != 0.)
+          {
+            // Now doing:
+            calibConvVar  = calibConvVar/(calibConv*calibConv) + calibQEVar/(calibQE*calibQE);
+            calibConvVar *= (calibConv*calibConv);
+            // The above two lines had been commented by TB and replaced by the following line 
+            // (without notice to me!) but it is simply wrong!
+            //          calibConvVar += calibQEVar*(calibConv*calibConv)/(calibQE*calibQE);
+          }
+
+	calibConv    *= fRenormFactor * calibUpdate;
+	calibFFactor *= TMath::Sqrt(fRenormFactor);
+
+        fHiLoConv     [pixidx] = hiloconv;
+        fHiLoConvErr  [pixidx] = hiloconverr;        
+        fCalibConsts  [pixidx] = calibConv;
+        fCalibFFactors[pixidx] = calibFFactor;
+
+	if (calibConv < fCalibConvMinLimit || calibConv > fCalibConvMaxLimit)
+	  {
+	    (*fBadPixels)[pixidx].SetUnsuitable(MBadPixelsPix::kUnsuitableRun);  
+	    calibConv    = -1.;
+	    calibFFactor = -1.;
+	  }
+	cpix.SetCalibConst(calibConv);
+	cpix.SetCalibFFactor(calibFFactor);
+
+      } /*     for (Int_t pixidx=0; pixidx<fGeomCam->GetNumPixels(); pixidx++) */
+    
+    if (skip>fGeomCam->GetNumPixels()*0.9)
+    {
+        *fLog << warn << GetDescriptor() 
+              << ": WARNING - GetConversionFactor has skipped more than 90% of the pixels... abort." << endl;
+        return kFALSE;
+    }
+
+    
+
+    //    Print();
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Apply the conversion factors and F-Factors from the arrays to the data. 
+//
+// The flags 'data' and 'pedestal' decide whether the signal and/or the pedetals
+// shall be calibrated, respectively. 
+//
+Int_t MCalibrateData::Calibrate(Bool_t data, Bool_t pedestal) const
+{
+    if (!data && !pedestal)
+        return kTRUE;
+
+    const UInt_t  npix       = fSignals->GetSize();
+    const Float_t slices     = fSignals->GetNumUsedHiGainFADCSlices();
+    const Float_t sqrtslices = TMath::Sqrt(slices);
+
+    Int_t numsatlo=0;
+    Int_t numsathi=0;
+
+    for (UInt_t pixidx=0; pixidx<npix; pixidx++)
+    {
+      
+      if (data)
+        {
+            const MExtractedSignalPix &sig = (*fSignals)[pixidx];
+
+            Float_t signal    = 0.;
+            Float_t signalErr = 0.;
+
+            if (sig.IsLoGainUsed())
+            {
+              if (fHiLoConv[pixidx] < 0.5)
+                {
+                  signal    = sig.GetExtractedSignalHiGain()*1.5;
+                  signalErr = sig.GetExtractedSignalHiGain()*0.5;
+                }
+              else
+                {
+                  const Float_t siglo = sig.GetExtractedSignalLoGain();
+
+                  if (siglo > 0.1) // low-gain signal has been extracted successfully
+                    {
+                      signal    = siglo*fHiLoConv   [pixidx];
+                      signalErr = siglo*fHiLoConvErr[pixidx];
+                    }
+                  else  // low-gain signal has not been extracted successfully, get a rough estimate from the high-gain
+                    {
+                      signal    = sig.GetExtractedSignalHiGain()*1.5;
+                      signalErr = sig.GetExtractedSignalHiGain()*0.5;
+                    }
+                }
+            }
+            else
+            {
+                if (sig.GetExtractedSignalHiGain() <= 9999.)
+                    signal = sig.GetExtractedSignalHiGain();
+            }
+
+            const Float_t nphot    = signal                         * fCalibConsts  [pixidx];
+            const Float_t nphotErr = TMath::Sqrt(TMath::Abs(nphot)) * fCalibFFactors[pixidx];
+            
+            fCerPhotEvt->AddPixel(pixidx, nphot, nphotErr);
+
+            if (sig.GetNumHiGainSaturated() > 0)
+                numsathi++;
+
+            if (sig.GetNumLoGainSaturated() > 0)
+                numsatlo++;
+        } /* if (data) */
+      
+
+        if (pedestal)
+        {
+            TIter NextPed(&fPedestalCams);
+            TIter NextPhot(&fPedPhotCams);
+
+            MPedestalCam *pedestal = 0;
+            MPedPhotCam  *pedphot  = 0;
+            
+            const Float_t pedmeancalib = slices    *fCalibConsts[pixidx];
+            const Float_t pedrmscalib  = sqrtslices*fCalibConsts[pixidx];
+
+            while ((pedestal=(MPedestalCam*)NextPed()) &&
+                   (pedphot =(MPedPhotCam*)NextPhot()))
+            {
+              // pedestals/(used FADC slices)   in [number of photons]
+              const Float_t mean = (*pedestal)[pixidx].GetPedestal()   *pedmeancalib;
+              const Float_t rms  = (*pedestal)[pixidx].GetPedestalRms()*pedrmscalib;
+              
+              (*pedphot)[pixidx].Set(mean, rms);
+              pedphot->SetReadyToSave();
+            }
+        } /* if (pedestal) */
+    }
+
+    if (data)
+    {
+        fCerPhotEvt->SetNumPixelsSaturated(numsathi, numsatlo);
+        fCerPhotEvt->SetReadyToSave();
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the calibration factors to the extracted signal according to the 
+// selected calibration method
+//
+Int_t MCalibrateData::Process()
+{
+    return Calibrate(fCalibrationMode!=kSkip, TestPedestalFlag(kEvent));
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MCalibrateData::StreamPrimitive(ofstream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    if (TestPedestalFlag(kEvent))
+        out << "   " << GetUniqueName() << ".EnablePedestalType(MCalibrateData::kEvent)" << endl;
+    if (TestPedestalFlag(kRun))
+        out << "   " << GetUniqueName() << ".EnablePedestalType(MCalibrateData::kRun)" << endl;
+
+    if (fCalibrationMode != kDefault)
+    {
+        out << "   " << GetUniqueName() << ".SetCalibrationMode(MCalibrateData::";
+        switch (fCalibrationMode)
+        {
+        case kSkip:       out << "kSkip";               break;
+        case kNone:       out << "kNone";               break;
+        case kFlatCharge: out << "kFlatCharge";         break;
+        case kBlindPixel: out << "kBlindPixel";         break;
+        case kFfactor:    out << "kFfactor";            break;
+        case kPinDiode:   out << "kPinDiode";           break;
+        case kCombined:   out << "kCombined";           break;
+        case kDummy:      out << "kDummy";              break;
+        default:          out << (int)fCalibrationMode; break;
+        }
+        out << ")" << endl;
+    }
+
+    TIter Next(&fNamesPedestal);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        out << "   " << GetUniqueName() << ".AddPedestal(\"";
+        out << o->GetName() << "\", \"" << o->GetTitle() << "\");" << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MJPedestal.MCalibrateDate.PedestalFlag: no,run,event
+//   MJPedestal.MCalibrateDate.CalibrationMode: skip,none,flatcharge,blindpixel,ffactor,pindiode,combined,dummy,default
+//
+Int_t MCalibrateData::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "PedestalFlag", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "PedestalFlag", "");
+        s.ToLower();
+        if (s.BeginsWith("no"))
+            SetPedestalFlag(kNo);
+        if (s.BeginsWith("run"))
+            SetPedestalFlag(kRun);
+        if (s.BeginsWith("event"))
+            SetPedestalFlag(kEvent);
+    }
+
+    if (IsEnvDefined(env, prefix, "CalibrationMode", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "CalibrationMode", "");
+        s.ToLower();
+        if (s.BeginsWith("skip"))
+            SetCalibrationMode(kSkip);
+        if (s.BeginsWith("none"))
+            SetCalibrationMode(kNone);
+        if (s.BeginsWith("flatcharge"))
+            SetCalibrationMode(kFlatCharge);
+        if (s.BeginsWith("blindpixel"))
+            SetCalibrationMode(kBlindPixel);
+        if (s.BeginsWith("ffactor"))
+            SetCalibrationMode(kFfactor);
+        if (s.BeginsWith("pindiode"))
+            SetCalibrationMode(kPinDiode);
+        if (s.BeginsWith("combined"))
+            SetCalibrationMode(kCombined);
+        if (s.BeginsWith("dummy"))
+            SetCalibrationMode(kDummy);
+        if (s.BeginsWith("default"))
+            SetCalibrationMode();
+    }
+
+    if (IsEnvDefined(env, prefix, "SignalType", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "SignalType", "");
+        s.ToLower();
+        if (s.BeginsWith("phot"))
+            SetSignalType(kPhot);
+        if (s.BeginsWith("phe"))
+            SetSignalType(kPhe);
+        if (s.BeginsWith("default"))
+            SetSignalType();
+    }
+
+    if (IsEnvDefined(env, prefix, "CalibConvMinLimit", print))
+    {
+        fCalibConvMinLimit = GetEnvValue(env, prefix, "CalibConvMinLimit", fCalibConvMinLimit);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "CalibConvMaxLimit", print))
+    {
+        fCalibConvMaxLimit = GetEnvValue(env, prefix, "CalibConvMaxLimit", fCalibConvMaxLimit);
+        rc = kTRUE;
+    }
+
+    return rc;
+}
+
+void MCalibrateData::Print(Option_t *o) const 
+{
+  
+  *fLog << all << GetDescriptor() << ":" << endl;
+  
+  for (UInt_t pixidx=0; pixidx<fGeomCam->GetNumPixels(); pixidx++)
+    {
+      *fLog << all
+            << Form("%s%3i","Pixel: ",pixidx)
+            << Form("%s%4.2f","  CalibConst: ",fCalibConsts[pixidx])
+            << Form("%s%4.2f","  F-Factor: ",fCalibFFactors[pixidx])
+            << Form("%s%4.2f","  HiLoConv: ",fHiLoConv[pixidx])
+            << endl;
+    }
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrateData.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrateData.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrateData.h	(revision 9772)
@@ -0,0 +1,125 @@
+#ifndef MARS_MCalibrateData
+#define MARS_MCalibrateData
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MGeomCam;
+class MBadPixelsCam;
+class MPedestalCam;
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MExtractedSignalCam;
+
+class MPedPhotCam;
+class MSignalCam;
+class MCalibConstCam;
+
+class MCalibrateData : public MTask
+{
+private:
+
+  static const Float_t  fgCalibConvMinLimit; //! Minimum limit for conv. factor
+  static const Float_t  fgCalibConvMaxLimit; //! Maximum limit for conv. factor
+
+  Float_t  fCalibConvMinLimit;           // Minimum limit for conv. factor
+  Float_t  fCalibConvMaxLimit;           // Maximum limit for conv. factor
+    
+  MGeomCam              *fGeomCam;       //! Camera geometry container
+  MBadPixelsCam         *fBadPixels;     //! Bad Pixels information
+  MCalibrationChargeCam *fCalibrations;  //! Calibration constants
+  MCalibrationQECam     *fQEs;           //! Quantum efficiencies
+  MExtractedSignalCam   *fSignals;       //! Integrated charge in FADCs counts
+  MSignalCam            *fCerPhotEvt;    //! Cerenkov Photon Event used for calculation
+  MCalibConstCam        *fCalibConstCam; //! Temporary calib consts storage
+  
+  UShort_t fCalibrationMode;             // Flag defining the calibration mode (CalibrationMode_t)
+  Byte_t   fPedestalFlag;                // Flags defining to calibrate the pedestal each event or each run
+  Byte_t   fSignalType;                  // Flag defining the signal type (kphot or kphe)
+  
+  Float_t  fRenormFactor;                // Possible renormalization factor for signals (-> phes)
+  
+  TList   fNamesPedestal;                // Names of input and output pedestal conatainer
+  TList   fPedestalCams;                 //! List of pointers to input MPedestalCam
+  TList   fPedPhotCams;                  //! List of pointers to corresponding output MPedPhotCam
+
+  MArrayF fCalibConsts;                  //! Array of calibration constants for each pixel, calculated only once!
+  MArrayF fCalibFFactors;                //! Array of calibration F-Factors for each pixel, calculated only once!  
+  MArrayF fHiLoConv;                     //! Array of calibration constants for each pixel, calculated only once!
+  MArrayF fHiLoConvErr;                  //! Array of calibration F-Factors for each pixel, calculated only once!  
+  
+  Int_t  Calibrate(Bool_t data, Bool_t pedestal) const;
+  
+  Int_t  PreProcess(MParList *pList);
+  Bool_t ReInit(MParList *pList);
+  Int_t  Process();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  void   StreamPrimitive(ofstream &out) const;
+  
+public:
+
+    enum CalibrationMode_t
+    {
+        kSkip       =  0,
+        kNone       =  1,
+        kFlatCharge =  2,
+        kBlindPixel =  3,
+        kFfactor    =  4,
+        kPinDiode   =  5,
+        kCombined   =  6,
+        kDummy      =  7
+    };
+
+  static const CalibrationMode_t kDefault = kFfactor;
+  
+  enum PedestalType_t
+  {
+      kNo    = BIT(0),
+      kRun   = BIT(1),
+      kEvent = BIT(2)
+  };
+  
+  enum SignalType_t
+  {
+      kPhe,
+      kPhot
+  };
+  
+  MCalibrateData(CalibrationMode_t calmode=kDefault,
+                 const char *name=NULL, const char *title=NULL);
+  
+  void   AddPedestal(const char *name="Cam");
+  void   AddPedestal(const char *pedestal, const char *pedphot);
+
+  void   EnablePedestalType(PedestalType_t i)     { fPedestalFlag |=  i;      }
+
+  Int_t  GetSize() const { return fCalibConsts.GetSize(); }
+
+  void   Print(Option_t *o="") const;
+
+  void   SetPedestalFlag(PedestalType_t i=kRun)   { fPedestalFlag  =  i;      }
+  Bool_t TestPedestalFlag(PedestalType_t i) const { return fPedestalFlag&i ? kTRUE : kFALSE; }
+  
+  void   SetCalibrationMode ( CalibrationMode_t calmode=kDefault ) { fCalibrationMode=calmode; }
+  void   SetSignalType      ( SignalType_t      sigtype=kPhe    ) { fSignalType     =sigtype; }  
+
+  void   SetCalibConvMinLimit( const Float_t f=fgCalibConvMinLimit ) { fCalibConvMinLimit = f; }
+  void   SetCalibConvMaxLimit( const Float_t f=fgCalibConvMaxLimit ) { fCalibConvMaxLimit = f; }
+    
+  Bool_t UpdateConversionFactors( const MCalibrationChargeCam *updatecam=NULL);
+
+  ClassDef(MCalibrateData, 1)   // Task to calibrate FADC counts into photons or photo-electrons
+};
+
+#endif   /* MCalibrateData */
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mcalib/MCalibrateRelTimes.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrateRelTimes.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrateRelTimes.cc	(revision 9772)
@@ -0,0 +1,170 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrateRelTimes
+//
+//   This task takes the extracted arrival times from MArrivalTimeCam for each  
+//   pixel and applies the offset calibrated in MCalibrationRelTimeCam 
+//   The calibrated arrival time and its error gets stored in MSignalCam. 
+//
+//   Input Containers:
+//    MArrivalTimeCam 
+//    MCalibrationRelTimeCam
+//
+//   Output Containers:
+//    MSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateRelTimes.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MH.h"
+
+#include "MGeomCam.h"
+
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimePix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+ClassImp(MCalibrateRelTimes);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrateRelTimes::MCalibrateRelTimes(const char *name, const char *title) 
+    : fGeomCam(NULL), fCalibrations(NULL), fBadPixels(NULL), fSignals(NULL), 
+      fArrivalTime(NULL)
+{
+    fName  = name  ? name  : "MCalibrateRelTimes";
+    fTitle = title ? title : "Task to calculate the calibrated arrival times of photons in one event";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MGeomCam
+//  - MCalibrationRelTimesCam
+//  - MArrivalTimeCam
+//  - MBadPixelsCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MArrivalTime
+//
+Int_t MCalibrateRelTimes::PreProcess(MParList *pList)
+{
+
+    fSignals = (MArrivalTimeCam*)pList->FindObject(AddSerialNumber("MArrivalTimeCam"));
+
+    if (!fSignals)
+    {
+      *fLog << err << AddSerialNumber("MArrivalTimeCam") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+    fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+      *fLog << warn << AddSerialNumber("MBadPixelsCam") << " not found ... no action" << endl;
+    
+
+    fCalibrations = (MCalibrationRelTimeCam*)pList->FindObject(AddSerialNumber("MCalibrationRelTimeCam"));
+    if (!fCalibrations)
+      {
+        *fLog << err << AddSerialNumber("MCalibrationRelTimeCam") << " not found ... aborting." << endl;
+        return kFALSE;
+      }
+
+
+    fArrivalTime = (MSignalCam*)pList->FindCreateObj(AddSerialNumber("MSignalCam"));
+    if (!fArrivalTime)
+        return kFALSE;
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the calibration factors to the extracted signal according to the 
+// selected calibration method
+//
+Int_t MCalibrateRelTimes::Process()
+{
+    /*
+     if (fCalibrations->GetNumPixels() != (UInt_t)fSignals->GetSize())
+     {
+     // FIXME: MArrivalTime must be of variable size -
+     //        like MSignalCam - because we must be able
+     //        to reduce size by zero supression
+     //        For the moment this check could be done in ReInit...
+     *fLog << err << "MArrivalTime and MCalibrationCam have different sizes... abort." << endl;
+     return kFALSE;
+     }
+     */
+
+    const UInt_t npix = fSignals->GetSize();
+
+    for (UInt_t pixidx=0; pixidx<npix; pixidx++)
+    {
+        MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*fCalibrations)[pixidx];
+
+        if (fBadPixels && (*fBadPixels)[pixidx].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+            continue;
+
+        const Float_t offset    = pix.GetTimeOffset();
+
+        MArrivalTimePix &sig = (*fSignals)[pixidx];
+
+        Float_t signal;
+
+        if (sig.IsLoGainUsed())
+	  signal = sig.GetArrivalTimeLoGain();
+        else
+	  signal = sig.GetArrivalTimeHiGain();
+
+        const Float_t time = signal - offset;
+
+        (*fArrivalTime)[pixidx].SetArrivalTime(time);
+
+    } /* for (UInt_t pixidx=0; pixidx<npix; pixidx++) */
+
+    fArrivalTime->SetReadyToSave();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrateRelTimes.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrateRelTimes.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrateRelTimes.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MCalibrateRelTimes
+#define MARS_MCalibrateRelTimes
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrateRelTimes                                                      //
+//                                                                         //
+// Calculates the relative arrival time and applies the offset,            //
+// stored in MCalibrationRelTimePix                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MBadPixelsCam;
+class MCalibrationRelTimeCam;
+class MArrivalTimeCam;
+class MSignalCam;
+
+class MCalibrateRelTimes : public MTask
+{
+private:
+    MGeomCam               *fGeomCam;      // Camera geometry container
+    MCalibrationRelTimeCam *fCalibrations; // Calibration rel. time constants
+    MBadPixelsCam          *fBadPixels;    // Bad Pixels information
+    MArrivalTimeCam        *fSignals;      // Extracted Arrival Time
+    MSignalCam             *fArrivalTime;  // Calibrated arrival times
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+
+    MCalibrateRelTimes(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MCalibrateRelTimes, 0)   // Task to calculate calibrated relative arrival times
+};
+ 
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindCam.cc	(revision 9772)
@@ -0,0 +1,199 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   07/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationBlindCam                                               
+//                                                               
+// Base class for Blind Pixels Calibration results. Derived classes intialize
+// the actual values of the MCalibrationBlindPix's. 
+//
+// Contains TOrdCollections for the following objects:
+// - fPixels:    Array of classes derived from MCalibrationBlindPix, one entry 
+//               per blind pixel. 
+//
+// All TOrdCollections have to enlarged by the corresponding calls to (e.g. in MGeomApply): 
+// - InitSize()
+//
+// See also: MCalibrationBlindCamOneOldStyle, MCalibrationBlindCamTwoNewStyle
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationBlindPix.h"
+
+#include <TOrdCollection.h>
+
+#include "MLogManip.h"
+
+ClassImp(MCalibrationBlindCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationBlindCam::MCalibrationBlindCam(Int_t nblind,const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationBlindCam";
+  fTitle = title ? title : "Calibration Information of blinded pixels in camera";
+
+  InitSize(nblind);
+
+}
+
+void MCalibrationBlindCam::Add(const UInt_t a, const UInt_t b)
+{
+
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationBlindPix,i);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MCalibrationBlindCam::Copy(TObject& object) const
+{
+  
+  MCalibrationBlindCam &calib = (MCalibrationBlindCam&)object;
+  
+  MCalibrationCam::Copy(calib);
+
+  /*  
+  const UInt_t n = GetSize();
+  if (n != 0)
+    {
+      calib.InitSize(n);
+      for (UInt_t i=0; i<n; i++)
+        (*this)[i].Copy(calib[i]);
+    }
+  */
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Return true, if any of the blind pixels have an available photon flux
+//
+Bool_t MCalibrationBlindCam::IsFluxInsidePlexiglassAvailable() const
+{
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      MCalibrationBlindPix &bp = (MCalibrationBlindPix&)(*this)[i];      
+      if (bp.IsFluxInsidePlexiglassAvailable())
+        return kTRUE;
+    }
+  
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns weighted average of the flux calculated by each blind pixel
+//
+Float_t MCalibrationBlindCam::GetFluxInsidePlexiglass() const
+{
+
+  Float_t flux    = 0.;
+  Float_t fluxvar = 0.;  
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      MCalibrationBlindPix &bp = (MCalibrationBlindPix&)(*this)[i];
+      if (bp.IsFluxInsidePlexiglassAvailable())
+        {
+          const Float_t weight = 1./ 
+                                bp.GetFluxInsidePlexiglassErr() 
+                                / bp.GetFluxInsidePlexiglassErr();
+          flux    += weight * bp.GetFluxInsidePlexiglass();
+          fluxvar += weight;
+        }
+    }
+  return fluxvar > 0.0001 ? flux / fluxvar : -1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns weighted variance of the flux calculated by each blind pixel
+//
+Float_t MCalibrationBlindCam::GetFluxInsidePlexiglassVar() const
+{
+
+  Float_t fluxvar = 0.;  
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      MCalibrationBlindPix &bp = (MCalibrationBlindPix&)(*this)[i];
+      if (bp.IsFluxInsidePlexiglassAvailable())
+        {
+          const Float_t weight = 1./ 
+                                bp.GetFluxInsidePlexiglassErr() 
+                                / bp.GetFluxInsidePlexiglassErr();
+          fluxvar += weight;
+        }
+    }
+  return fluxvar > 0.0001 ? 1. / fluxvar : -1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns weighted rel. variance of the flux calculated by each blind pixel
+//
+Float_t MCalibrationBlindCam::GetFluxInsidePlexiglassRelVar() const
+{
+
+  Float_t flux    = 0.;
+  Float_t fluxvar = 0.;  
+
+  for (Int_t i=0; i<GetSize(); i++)
+    {
+      MCalibrationBlindPix &bp = (MCalibrationBlindPix&)(*this)[i];
+      if (bp.IsFluxInsidePlexiglassAvailable())
+        {
+          const Float_t weight = 1./ 
+                                bp.GetFluxInsidePlexiglassErr() 
+                                / bp.GetFluxInsidePlexiglassErr();
+          flux    += weight * bp.GetFluxInsidePlexiglass();
+          fluxvar += weight;
+        }
+    }
+
+  return fluxvar > 0.0001 ? flux * fluxvar : -1.;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set color to this class and to the MCalibrationBlindPix's
+//
+void  MCalibrationBlindCam::SetPulserColor ( const MCalibrationCam::PulserColor_t col )
+{
+
+  fPulserColor = col;
+  fPixels->ForEach(MCalibrationBlindPix, SetColor)(col);
+
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindCam.h	(revision 9772)
@@ -0,0 +1,34 @@
+#ifndef MARS_MCalibrationBlindCam
+#define MARS_MCalibrationBlindCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationBlindCam : public MCalibrationCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+
+public:
+
+  MCalibrationBlindCam(Int_t nblind=1,const char *name=NULL, const char *title=NULL);
+  
+  void Copy(TObject& object) const;
+
+  // Inits
+  void  Init ( const MGeomCam &geom ) {}
+
+  Bool_t IsFluxInsidePlexiglassAvailable () const;
+
+  Float_t GetFluxInsidePlexiglass    () const;
+  Float_t GetFluxInsidePlexiglassVar () const;
+  Float_t GetFluxInsidePlexiglassRelVar() const;
+
+  void  SetPulserColor( const MCalibrationCam::PulserColor_t col );
+  
+  ClassDef(MCalibrationBlindCam, 2) // Container Blind Pixels Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindCamOneOldStyle.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindCamOneOldStyle.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindCamOneOldStyle.cc	(revision 9772)
@@ -0,0 +1,176 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   07/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationBlindCamOneOldStyle                                               
+//                                                               
+// Blind Pixels Calibration camera until run 31693. The blind pixel camera 
+// consisted then only of one non-coated blind pixel with poorly known 
+// quantum efficiency read out in hardware ID 560.
+//
+// See also: MCalibrationBlindCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindCamOneOldStyle.h"
+#include "MCalibrationBlindPix.h"
+
+ClassImp(MCalibrationBlindCamOneOldStyle);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// - CreatePixs();
+// - CreateAreas();   
+// - CreateAtts();   
+// - CreateQEs();     
+// - CreateCollEffs();
+//
+MCalibrationBlindCamOneOldStyle::MCalibrationBlindCamOneOldStyle(const char *name)
+    : MCalibrationBlindCam(1,name,"One Blind Pixel in camera - old style")
+{
+
+  CreatePixs    ();    
+  CreateAreas   ();   
+  CreateAtts    ();   
+  CreateQEs     ();     
+  CreateCollEffs();
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Only one blind pixel with ID 559
+//
+void MCalibrationBlindCamOneOldStyle::CreatePixs() 
+{
+
+  (*this)[0].SetPixId(559);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Only one blind pixel with exactly 100 mm^2 area
+//
+void MCalibrationBlindCamOneOldStyle::CreateAreas() 
+{
+  
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)(*this)[0];
+  pix.SetArea(100.);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with poorly known qe's: average of David measurments with 
+// 4% error.
+//
+void MCalibrationBlindCamOneOldStyle::CreateQEs() 
+{
+  
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)(*this)[0];
+
+  Float_t qe[4];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.154;
+  qe[    MCalibrationCam::kBLUE  ] = 0.226;
+  qe[    MCalibrationCam::kUV    ] = 0.247;
+  qe[    MCalibrationCam::kCT1   ] = 0.247;
+
+  pix.SetQE(4,qe);  
+
+  Float_t qeerr[4];
+
+  qeerr[ MCalibrationCam::kGREEN ] = 0.005;
+  qeerr[ MCalibrationCam::kBLUE  ] = 0.007;
+  qeerr[ MCalibrationCam::kUV    ] = 0.01;
+  qeerr[ MCalibrationCam::kCT1   ] = 0.01;
+
+  pix.SetQEErr(4,qeerr);  
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with poorly known coll.eff's: email from Eckart with 
+// estimates depending on colour, but 5% error (maybe more??)
+//
+void MCalibrationBlindCamOneOldStyle::CreateCollEffs() 
+{
+
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)(*this)[0];
+
+  Float_t colleff[4];
+
+  colleff[MCalibrationCam::kGREEN ] = 0.99;
+  colleff[MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[MCalibrationCam::kUV    ] = 0.90;
+  colleff[MCalibrationCam::kCT1   ] = 0.90;
+
+  pix.SetCollEff(4,colleff);  
+
+  Float_t collefferr[4];
+
+  collefferr[MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[MCalibrationCam::kUV    ] = 0.05;
+  collefferr[MCalibrationCam::kCT1   ] = 0.05;
+  
+  pix.SetCollEffErr(4,collefferr);  
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with very well known attenuation 0.01 (datasheet delivered 
+// with filter, precision better than 1%
+//
+void MCalibrationBlindCamOneOldStyle::CreateAtts() 
+{
+
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)(*this)[0];
+
+  Float_t att[4];
+
+  att[MCalibrationCam::kGREEN ] = 1.97;
+  att[MCalibrationCam::kBLUE  ] = 1.96;
+  att[MCalibrationCam::kUV    ] = 1.95;
+  att[MCalibrationCam::kCT1   ] = 1.95;
+
+  pix.SetAtt(4,att);
+
+  Float_t atterr[4];
+
+  atterr[MCalibrationCam::kGREEN ] = 0.01;
+  atterr[MCalibrationCam::kBLUE  ] = 0.01;
+  atterr[MCalibrationCam::kUV    ] = 0.01;
+  atterr[MCalibrationCam::kCT1   ] = 0.01;
+  
+  pix.SetAttErr(4,atterr);
+
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindCamOneOldStyle.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindCamOneOldStyle.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindCamOneOldStyle.h	(revision 9772)
@@ -0,0 +1,25 @@
+#ifndef MARS_MCalibrationBlindCamOneOldStyle
+#define MARS_MCalibrationBlindCamOneOldStyle
+
+#ifndef MARS_MCalibrationBlindCam
+#include "MCalibrationBlindCam.h"
+#endif
+
+class MCalibrationBlindCamOneOldStyle : public MCalibrationBlindCam
+{
+private:
+
+  void CreatePixs();
+  void CreateAreas();
+  void CreateAtts();
+  void CreateQEs();
+  void CreateCollEffs();
+  
+public:
+
+  MCalibrationBlindCamOneOldStyle(const char *name=NULL);
+  
+  ClassDef(MCalibrationBlindCamOneOldStyle, 1) // Container Blind Pixel Calibration Results - until run 31693
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindCamThreeNewStyle.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindCamThreeNewStyle.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindCamThreeNewStyle.cc	(revision 9772)
@@ -0,0 +1,284 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   07/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationBlindCamThreeNewStyle                                               
+//                                                               
+// Blind Pixels Calibration camera after run 43308. The blind pixel camera 
+// consisted then of three non-coated blind pixels with very well known 
+// quantum efficiency read out in hardware ID 0,1 and 2 (stored in MRawEvtData2).
+//
+// See also: MCalibrationBlindCam, MHCalibrationChargeBlindCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindCamThreeNewStyle.h"
+#include "MCalibrationBlindPix.h"
+
+ClassImp(MCalibrationBlindCamThreeNewStyle);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// - CreatePixs();
+// - CreateAreas();   
+// - CreateAtts();   
+// - CreateQEs();     
+// - CreateCollEffs();
+//
+MCalibrationBlindCamThreeNewStyle::MCalibrationBlindCamThreeNewStyle(const char *name)
+    : MCalibrationBlindCam(3,name,"Three Blind Pixels in camera - new style")
+{
+  CreatePixs    ();    
+  CreateAreas   ();   
+  CreateAtts    ();   
+  CreateQEs     ();     
+  CreateCollEffs();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Three blind pixels with ID 0,1 and 2 (software)
+//
+void MCalibrationBlindCamThreeNewStyle::CreatePixs() 
+{
+
+  (*this)[0].SetPixId(0);
+  (*this)[1].SetPixId(1);
+  (*this)[2].SetPixId(2);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Three blind pixels with exactly 100 mm^2 area
+//
+void MCalibrationBlindCamThreeNewStyle::CreateAreas() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];
+  pix0.SetArea(100.);
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+  pix1.SetArea(100.);
+
+  MCalibrationBlindPix &pix2 = (MCalibrationBlindPix&)(*this)[2];
+  pix2.SetArea   (0.196);
+  pix2.SetAreaErr(0.008);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Three blind pixels with very well known qe's: David's measurments with 
+// 1% error.
+//
+void MCalibrationBlindCamThreeNewStyle::CreateQEs() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t qe[4];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.166;
+  qe[    MCalibrationCam::kBLUE  ] = 0.240;
+  qe[    MCalibrationCam::kUV    ] = 0.273;
+  qe[    MCalibrationCam::kCT1   ] = 0.273;
+
+  pix0.SetQE(4,qe);  
+
+  Float_t qeerr[4];
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix0.SetQEErr(4,qeerr);  
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.155;
+  qe[    MCalibrationCam::kBLUE  ] = 0.228;
+  qe[    MCalibrationCam::kUV    ] = 0.261;
+  qe[    MCalibrationCam::kCT1   ] = 0.261;
+
+  pix1.SetQE(4,qe);  
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix1.SetQEErr(4,qeerr);  
+
+  MCalibrationBlindPix &pix2 = (MCalibrationBlindPix&)(*this)[2];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.160;
+  qe[    MCalibrationCam::kBLUE  ] = 0.235;
+  qe[    MCalibrationCam::kUV    ] = 0.264;
+  qe[    MCalibrationCam::kCT1   ] = 0.264;
+
+  pix2.SetQE(4,qe);  
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix2.SetQEErr(4,qeerr);  
+
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with poorly known coll.eff's: email from Eckart with 
+// estimates depending on colour, but 5% error (maybe more??)
+//
+void MCalibrationBlindCamThreeNewStyle::CreateCollEffs() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t colleff[4];
+
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix0.SetCollEff(4,colleff);  
+
+  Float_t collefferr[4];
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+
+  pix0.SetCollEffErr(4,collefferr);  
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+  
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix1.SetCollEff(4,colleff);  
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+  
+  pix1.SetCollEffErr(4,collefferr);    
+
+  MCalibrationBlindPix &pix2 = (MCalibrationBlindPix&)(*this)[2];
+  
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix2.SetCollEff(4,colleff);  
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+  
+  pix2.SetCollEffErr(4,collefferr);    
+
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel has a very well known attenuation 0.01 (datasheet delivered 
+// with filter, precision better than 1%
+//
+// The second blind pixel is not yet so well known, the company does not reply.
+// Attenuation: 0.001 (datasheet not delivered with filter, precision guaranteed to 5%)
+//
+void MCalibrationBlindCamThreeNewStyle::CreateAtts() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t att[4];
+
+  att[MCalibrationCam::kGREEN ] = 1.97;
+  att[MCalibrationCam::kBLUE  ] = 1.96;
+  att[MCalibrationCam::kUV    ] = 1.95;
+  att[MCalibrationCam::kCT1   ] = 1.95;
+
+  pix0.SetAtt(4,att);
+
+  Float_t atterr[4];
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.01;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.01;
+  atterr[    MCalibrationCam::kUV    ] = 0.01;
+  atterr[    MCalibrationCam::kCT1   ] = 0.01;
+
+  pix0.SetAttErr(4,atterr);
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];  
+
+  att[MCalibrationCam::kGREEN ] = 3.00;
+  att[MCalibrationCam::kBLUE  ] = 3.00;
+  att[MCalibrationCam::kUV    ] = 3.00;
+  att[MCalibrationCam::kCT1   ] = 3.00;
+
+  pix1.SetAtt(4,att);
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.15;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.15;
+  atterr[    MCalibrationCam::kUV    ] = 0.15;
+  atterr[    MCalibrationCam::kCT1   ] = 0.15;
+
+  pix1.SetAttErr(4,atterr);
+  
+  MCalibrationBlindPix &pix2 = (MCalibrationBlindPix&)(*this)[2];  
+
+  att[MCalibrationCam::kGREEN ] = 0.;
+  att[MCalibrationCam::kBLUE  ] = 0.;
+  att[MCalibrationCam::kUV    ] = 0.; 
+  att[MCalibrationCam::kCT1   ] = 0.;
+
+  pix2.SetAtt(4,att);
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.;
+  atterr[    MCalibrationCam::kUV    ] = 0.;
+  atterr[    MCalibrationCam::kCT1   ] = 0.;
+
+  pix2.SetAttErr(4,atterr);
+  
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindCamThreeNewStyle.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindCamThreeNewStyle.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindCamThreeNewStyle.h	(revision 9772)
@@ -0,0 +1,25 @@
+#ifndef MARS_MCalibrationBlindCamThreeNewStyle
+#define MARS_MCalibrationBlindCamThreeNewStyle
+
+#ifndef MARS_MCalibrationBlindCam
+#include "MCalibrationBlindCam.h"
+#endif
+
+class MCalibrationBlindCamThreeNewStyle : public MCalibrationBlindCam
+{
+private:
+
+  void CreatePixs();
+  void CreateAreas();
+  void CreateAtts();
+  void CreateQEs();
+  void CreateCollEffs();
+  
+public:
+
+  MCalibrationBlindCamThreeNewStyle(const char *name=NULL);
+
+  ClassDef(MCalibrationBlindCamThreeNewStyle, 1) // Container Blind Pixel Calibration Results - after run 43307
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindCamTwoNewStyle.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindCamTwoNewStyle.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindCamTwoNewStyle.cc	(revision 9772)
@@ -0,0 +1,230 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   07/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationBlindCamTwoNewStyle                                               
+//                                                               
+// Blind Pixels Calibration camera after run 31693. The blind pixel camera 
+// consisted then of two non-coated blind pixel with very well known 
+// quantum efficiency read out in hardware ID 560 and 561.
+//
+// See also: MCalibrationBlindCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindCamTwoNewStyle.h"
+#include "MCalibrationBlindPix.h"
+
+ClassImp(MCalibrationBlindCamTwoNewStyle);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// - CreatePixs();
+// - CreateAreas();   
+// - CreateAtts();   
+// - CreateQEs();     
+// - CreateCollEffs();
+//
+MCalibrationBlindCamTwoNewStyle::MCalibrationBlindCamTwoNewStyle(const char *name)
+    : MCalibrationBlindCam(2,name,"Two Blind Pixels in camera - new style")
+{
+  CreatePixs    ();    
+  CreateAreas   ();   
+  CreateAtts    ();   
+  CreateQEs     ();     
+  CreateCollEffs();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Two blind pixels with ID 559 and 560 (software)
+//
+void MCalibrationBlindCamTwoNewStyle::CreatePixs() 
+{
+
+  (*this)[0].SetPixId(559);
+  (*this)[1].SetPixId(560);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Two blind pixels with exactly 100 mm^2 area
+//
+void MCalibrationBlindCamTwoNewStyle::CreateAreas() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];
+  pix0.SetArea(100.);
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+  pix1.SetArea(100.);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Two blind pixels with very well known qe's: David's measurments with 
+// 1% error.
+//
+void MCalibrationBlindCamTwoNewStyle::CreateQEs() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t qe[4];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.166;
+  qe[    MCalibrationCam::kBLUE  ] = 0.240;
+  qe[    MCalibrationCam::kUV    ] = 0.273;
+  qe[    MCalibrationCam::kCT1   ] = 0.273;
+
+  pix0.SetQE(4,qe);  
+
+  Float_t qeerr[4];
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix0.SetQEErr(4,qeerr);  
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+
+  qe[    MCalibrationCam::kGREEN ] = 0.155;
+  qe[    MCalibrationCam::kBLUE  ] = 0.228;
+  qe[    MCalibrationCam::kUV    ] = 0.261;
+  qe[    MCalibrationCam::kCT1   ] = 0.261;
+
+  pix1.SetQE(4,qe);  
+
+  qeerr[    MCalibrationCam::kGREEN ] = 0.004;
+  qeerr[    MCalibrationCam::kBLUE  ] = 0.005;
+  qeerr[    MCalibrationCam::kUV    ] = 0.006;
+  qeerr[    MCalibrationCam::kCT1   ] = 0.006;
+
+  pix1.SetQEErr(4,qeerr);  
+
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel with poorly known coll.eff's: email from Eckart with 
+// estimates depending on colour, but 5% error (maybe more??)
+//
+void MCalibrationBlindCamTwoNewStyle::CreateCollEffs() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t colleff[4];
+
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix0.SetCollEff(4,colleff);  
+
+  Float_t collefferr[4];
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+
+  pix0.SetCollEffErr(4,collefferr);  
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];
+  
+  colleff[    MCalibrationCam::kGREEN ] = 0.99;
+  colleff[    MCalibrationCam::kBLUE  ] = 0.93;
+  colleff[    MCalibrationCam::kUV    ] = 0.90;
+  colleff[    MCalibrationCam::kCT1   ] = 0.90;
+
+  pix1.SetCollEff(4,colleff);  
+
+  collefferr[    MCalibrationCam::kGREEN ] = 0.05;
+  collefferr[    MCalibrationCam::kBLUE  ] = 0.05;
+  collefferr[    MCalibrationCam::kUV    ] = 0.05;
+  collefferr[    MCalibrationCam::kCT1   ] = 0.05;
+  
+  pix1.SetCollEffErr(4,collefferr);    
+}
+
+// --------------------------------------------------------------------------
+//
+// One blind pixel has a very well known attenuation 0.01 (datasheet delivered 
+// with filter, precision better than 1%
+//
+// The second blind pixel is not yet so well known, the company does not reply.
+// Attenuation: 0.001 (datasheet not delivered with filter, precision guaranteed to 5%)
+//
+void MCalibrationBlindCamTwoNewStyle::CreateAtts() 
+{
+
+  MCalibrationBlindPix &pix0 = (MCalibrationBlindPix&)(*this)[0];  
+
+  Float_t att[4];
+
+  att[MCalibrationCam::kGREEN ] = 1.97;
+  att[MCalibrationCam::kBLUE  ] = 1.96;
+  att[MCalibrationCam::kUV    ] = 1.95;
+  att[MCalibrationCam::kCT1   ] = 1.95;
+
+  pix0.SetAtt(4,att);
+
+  Float_t atterr[4];
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.01;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.01;
+  atterr[    MCalibrationCam::kUV    ] = 0.01;
+  atterr[    MCalibrationCam::kCT1   ] = 0.01;
+
+  pix0.SetAttErr(4,atterr);
+
+  MCalibrationBlindPix &pix1 = (MCalibrationBlindPix&)(*this)[1];  
+
+  att[MCalibrationCam::kGREEN ] = 3.00;
+  att[MCalibrationCam::kBLUE  ] = 3.00;
+  att[MCalibrationCam::kUV    ] = 3.00;
+  att[MCalibrationCam::kCT1   ] = 3.00;
+
+  pix1.SetAtt(4,att);
+
+  atterr[    MCalibrationCam::kGREEN ] = 0.15;
+  atterr[    MCalibrationCam::kBLUE  ] = 0.15;
+  atterr[    MCalibrationCam::kUV    ] = 0.15;
+  atterr[    MCalibrationCam::kCT1   ] = 0.15;
+
+  pix1.SetAttErr(4,atterr);
+  
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindCamTwoNewStyle.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindCamTwoNewStyle.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindCamTwoNewStyle.h	(revision 9772)
@@ -0,0 +1,25 @@
+#ifndef MARS_MCalibrationBlindCamTwoNewStyle
+#define MARS_MCalibrationBlindCamTwoNewStyle
+
+#ifndef MARS_MCalibrationBlindCam
+#include "MCalibrationBlindCam.h"
+#endif
+
+class MCalibrationBlindCamTwoNewStyle : public MCalibrationBlindCam
+{
+private:
+
+  void CreatePixs();
+  void CreateAreas();
+  void CreateAtts();
+  void CreateQEs();
+  void CreateCollEffs();
+  
+public:
+
+  MCalibrationBlindCamTwoNewStyle(const char *name=NULL);
+
+  ClassDef(MCalibrationBlindCamTwoNewStyle, 1) // Container Blind Pixel Calibration Results - after run 31693
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindPix.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindPix.cc	(revision 9772)
@@ -0,0 +1,552 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                               
+// MCalibrationBlindPix    
+//
+// Storage container of the fit results of the Blind Pixel signal 
+// (from MHCalibrationChargeBlindPix). 
+//
+// The Flux is calculated in photons per mm^2 in the camera plane. 
+//
+// Currently, the following numbers are implemented:
+// - fArea: 100 mm^2
+// - Average QE of Blind Pixel: 
+//    fQEGreen: 0.154
+//    fQEBlue : 0.226
+//    fQEUV   : 0.247
+//    fQECT1  : 0.247
+// - Average QE Error of Blind Pixel: 
+//    fQEGreenErr: 0.015;
+//    fQEBlueErr : 0.02;
+//    fQEUVErr   : 0.02;
+//    fQECT1Err  : 0.02;
+// - Attenuation factor Blind Pixel:
+//    fAttGreen :  1.97;
+//    fAttBlue  :  1.96;
+//    fAttUV    :  1.95;
+//    fAttCT1   :  1.95;
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationBlindPix.h"
+
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationBlindPix);
+
+using namespace std;
+
+const Float_t MCalibrationBlindPix::fgArea       = 100;
+const Float_t MCalibrationBlindPix::fgAttGreen   = 1.97;
+const Float_t MCalibrationBlindPix::fgAttBlue    = 1.96;
+const Float_t MCalibrationBlindPix::fgAttUV      = 1.95;
+const Float_t MCalibrationBlindPix::fgAttCT1     = 1.95;
+const Float_t MCalibrationBlindPix::fgAttErr     = 0.01;
+const Float_t MCalibrationBlindPix::fgQEGreen    = 0.154;
+const Float_t MCalibrationBlindPix::fgQEBlue     = 0.226;
+const Float_t MCalibrationBlindPix::fgQEUV       = 0.247;
+const Float_t MCalibrationBlindPix::fgQECT1      = 0.247;
+const Float_t MCalibrationBlindPix::fgQEErrGreen = 0.005;
+const Float_t MCalibrationBlindPix::fgQEErrBlue  = 0.007;
+const Float_t MCalibrationBlindPix::fgQEErrUV    = 0.01;
+const Float_t MCalibrationBlindPix::fgQEErrCT1   = 0.01;
+const Float_t MCalibrationBlindPix::fgCollEffGreen = 0.99; 
+const Float_t MCalibrationBlindPix::fgCollEffBlue  = 0.93; 
+const Float_t MCalibrationBlindPix::fgCollEffUV    = 0.90; 
+const Float_t MCalibrationBlindPix::fgCollEffCT1   = 0.90; 
+const Float_t MCalibrationBlindPix::fgCollEffErr   = 0.05; 
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Calls:
+// - Clear()
+//
+// For backward-compatibility reasons, quantum eff., coll. eff. and att. 
+// are intialized from the static members. This should, however, be 
+// overwritten by a class deriving from MCalibrationBlindCam. 
+//
+MCalibrationBlindPix::MCalibrationBlindPix(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationBlindPix";
+  fTitle = title ? title : "Container of the fit results of the blind pixel";
+
+  Clear();
+
+  fArea = fgArea;
+  fAreaErr = 0.;
+
+  Float_t att[MCalibrationCam::gkNumPulserColors];
+
+  att [ MCalibrationCam::kGREEN ] = fgAttGreen; 
+  att [ MCalibrationCam::kBLUE  ] = fgAttBlue; 
+  att [ MCalibrationCam::kUV    ] = fgAttUV; 
+  att [ MCalibrationCam::kCT1   ] = fgAttCT1; 
+
+  SetAtt(MCalibrationCam::gkNumPulserColors,att);
+
+  Float_t atterr[MCalibrationCam::gkNumPulserColors];
+
+  atterr [ MCalibrationCam::kGREEN ] = fgAttErr; 
+  atterr [ MCalibrationCam::kBLUE  ] = fgAttErr; 
+  atterr [ MCalibrationCam::kUV    ] = fgAttErr; 
+  atterr [ MCalibrationCam::kCT1   ] = fgAttErr; 
+  
+  SetAttErr(MCalibrationCam::gkNumPulserColors,atterr);
+
+  Float_t qe[MCalibrationCam::gkNumPulserColors];
+
+  qe [ MCalibrationCam::kGREEN ] = fgQEGreen; 
+  qe [ MCalibrationCam::kBLUE  ] = fgQEBlue; 
+  qe [ MCalibrationCam::kUV    ] = fgQEUV; 
+  qe [ MCalibrationCam::kCT1   ] = fgQECT1; 
+
+  SetQE(MCalibrationCam::gkNumPulserColors,qe);  
+
+  Float_t qeerr[MCalibrationCam::gkNumPulserColors];
+
+  qeerr [ MCalibrationCam::kGREEN ] = fgQEErrGreen; 
+  qeerr [ MCalibrationCam::kBLUE  ] = fgQEErrBlue; 
+  qeerr [ MCalibrationCam::kUV    ] = fgQEErrUV; 
+  qeerr [ MCalibrationCam::kCT1   ] = fgQEErrCT1; 
+
+  SetQEErr(MCalibrationCam::gkNumPulserColors,qeerr);  
+
+  Float_t colleff[MCalibrationCam::gkNumPulserColors];
+
+  colleff [ MCalibrationCam::kGREEN ] = fgCollEffGreen; 
+  colleff [ MCalibrationCam::kBLUE  ] = fgCollEffBlue; 
+  colleff [ MCalibrationCam::kUV    ] = fgCollEffUV; 
+  colleff [ MCalibrationCam::kCT1   ] = fgCollEffCT1; 
+
+  SetCollEff(MCalibrationCam::gkNumPulserColors,colleff);  
+
+  Float_t collefferr[MCalibrationCam::gkNumPulserColors];
+
+  collefferr [ MCalibrationCam::kGREEN ] = fgCollEffErr; 
+  collefferr [ MCalibrationCam::kBLUE  ] = fgCollEffErr; 
+  collefferr [ MCalibrationCam::kUV    ] = fgCollEffErr; 
+  collefferr [ MCalibrationCam::kCT1   ] = fgCollEffErr; 
+
+  SetCollEffErr(MCalibrationCam::gkNumPulserColors,collefferr);  
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all flags to kFALSE
+// - all variables to -1.
+// - the fColor to MCalibrationCam::kNONE
+//
+// Calls: 
+// - MCalibrationPix::Clear()
+//
+void MCalibrationBlindPix::Clear(Option_t *o)
+{
+
+  fFluxInsidePlexiglass    = -1.;
+  fFluxInsidePlexiglassVar = -1.;
+  fLambda                  = -1.;
+  fLambdaCheck             = -1.;
+  fLambdaVar               = -1.;
+  fMu0                     = -1.;
+  fMu0Err                  = -1.;
+  fMu1                     = -1.;
+  fMu1Err                  = -1.;
+  fSigma0                  = -1.;
+  fSigma0Err               = -1.;
+  fSigma1                  = -1.;
+  fSigma1Err               = -1.;
+
+  SetOscillating                   ( kFALSE );
+  SetExcluded                      ( kFALSE );
+  SetChargeFitValid                ( kFALSE );
+  SetPedestalFitOK                 ( kFALSE );
+  SetSinglePheFitOK                ( kFALSE );
+  SetFluxInsidePlexiglassAvailable ( kFALSE );
+  
+  SetColor(MCalibrationCam::kNONE);
+
+  MCalibrationPix::Clear();
+}
+
+void  MCalibrationBlindPix::SetFluxInsidePlexiglassAvailable( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kFluxInsidePlexiglassAvailable) : CLRBIT(fFlags,kFluxInsidePlexiglassAvailable);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the Oscillating Bit from outside 
+//
+void  MCalibrationBlindPix::SetOscillating( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kOscillating) : CLRBIT(fFlags,kOscillating);
+}
+
+// -----------------------------------------------------
+//
+// copy 'constructor'
+//
+void MCalibrationBlindPix::Copy(TObject& object) const
+{
+
+  MCalibrationBlindPix &pix = (MCalibrationBlindPix&)object;
+
+  //
+  // Copy the data members
+  //
+  pix.fPixId      = fPixId;
+  pix.fFlags      = fFlags;
+  pix.fArea       = fArea;
+  pix.fAreaErr    = fAreaErr;                     
+  pix.fColor      = fColor;
+
+  //
+  // Copy arrays
+  //
+  pix.fAtt        = fAtt;
+  pix.fAttErr     = fAttErr;
+  pix.fQE         = fQE;
+  pix.fQEErr      = fQEErr;
+  pix.fCollEff    = fCollEff;
+  pix.fCollEffErr = fCollEffErr;
+
+  pix.fLambda                  = fLambda;
+  pix.fLambdaCheck             = fLambdaCheck;
+  pix.fLambdaCheckErr          = fLambdaCheckErr;
+  pix.fLambdaVar               = fLambdaVar;
+  pix.fFluxInsidePlexiglass    = fFluxInsidePlexiglass;
+  pix.fFluxInsidePlexiglassVar = fFluxInsidePlexiglassVar;
+  pix.fMu0       = fMu0;
+  pix.fMu0Err    = fMu0Err;
+  pix.fMu1       = fMu1;
+  pix.fMu1Err    = fMu1Err;
+  pix.fSigma0    = fSigma0;
+  pix.fSigma0Err = fSigma0Err;
+  pix.fSigma1    = fSigma1;
+  pix.fSigma1Err = fSigma1Err;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the ChargeFitValid Bit from outside 
+//
+void  MCalibrationBlindPix::SetChargeFitValid( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kChargeFitValid) : CLRBIT(fFlags,kChargeFitValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the PedestalFitValid Bit from outside 
+//
+void  MCalibrationBlindPix::SetPedestalFitOK( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kPedestalFitOK) : CLRBIT(fFlags,kPedestalFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the SinglePheFitValid Bit from outside 
+//
+void  MCalibrationBlindPix::SetSinglePheFitOK( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kSinglePheFitOK) : CLRBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fFluxInsidePlexiglassVar is smaller than 0.
+// Return square root of fFluxInsidePlexiglassVar
+// 
+const Float_t MCalibrationBlindPix::GetFluxInsidePlexiglassErr() const
+{
+  if (fFluxInsidePlexiglassVar < 0.)
+    return -1.;
+  
+  return TMath::Sqrt(fFluxInsidePlexiglassVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fFluxInsidePlexiglassVar is smaller than 0.
+// Return -1 if fFluxInsidePlexiglass    is 0.
+// Return fFluxInsidePlexiglassVar / fFluxInsidePlexiglass^2
+// 
+const Float_t MCalibrationBlindPix::GetFluxInsidePlexiglassRelVar() const
+{
+  if (fFluxInsidePlexiglassVar < 0.)
+    return -1.;
+
+  if (fFluxInsidePlexiglass == 0.)
+    return -1.;
+  
+  return fFluxInsidePlexiglassVar / (fFluxInsidePlexiglass * fFluxInsidePlexiglass) ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fLambdaVar is smaller than 0.
+// Return square root of fLambdaVar
+// 
+const Float_t MCalibrationBlindPix::GetLambdaErr() const
+{
+  if (fLambdaVar < 0.)
+    return -1.;
+  
+  return TMath::Sqrt(fLambdaVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fLambdaVar is smaller than 0.
+// Return -1 if fLambda    is 0.
+// Return fLambdaVar / (fLambda * fLambda )
+// 
+const Float_t  MCalibrationBlindPix::GetLambdaRelVar() const
+{
+  if (fLambdaVar < 0.)
+    return -1.;
+  
+  if (fLambda  == 0.)
+    return -1.;
+  
+  return fLambdaVar / fLambda / fLambda ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fAreaErr^2 / (fArea^2 )
+// 
+const Float_t MCalibrationBlindPix::GetAreaRelVar() const
+{
+  return fAreaErr*fAreaErr/fArea/fArea;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return TMath::Power(10,fAtt[fColor])
+//
+const Float_t MCalibrationBlindPix::GetAtt() const
+{
+  return TMath::Power(10,fAtt[fColor]);   
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fAttErr[fColor] is smaller than 0.
+// Error of TMath::Power(10,fAtt[fColor]) = TMath::Power(10,fAtt[fColor])*ln(10.)*fAttErr[fColor]
+// Return fAttErr^2 / (fAtt^2 )
+// 
+const Float_t MCalibrationBlindPix::GetAttRelVar() const
+{
+
+  const Float_t err = fAttErr[fColor];
+
+  if (err < 0.)
+    return -1.;
+  
+  return err*err*2.3;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fQE[fColor]
+//
+const Float_t MCalibrationBlindPix::GetQE() const
+{
+  return fQE[fColor];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fQEErr[fColor] is smaller than 0.
+// Return fQEErr^2 / (fQE^2 )
+// 
+const Float_t MCalibrationBlindPix::GetQERelVar() const
+{
+
+  if (fQEErr[fColor] < 0.)
+    return -1.;
+  
+  return fQEErr[fColor]* fQEErr[fColor] / GetQE() / GetQE();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fCollEff[fColor]
+//
+const Float_t MCalibrationBlindPix::GetCollEff() const
+{
+  return fCollEff[fColor];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fCollEffErr[fColor] is smaller than 0.
+// Return fCollEffErr^2 / (fCollEff^2 )
+// 
+const Float_t MCalibrationBlindPix::GetCollEffRelVar() const
+{
+
+  if (fCollEffErr[fColor] < 0.)
+    return -1.;
+  
+  return fCollEffErr[fColor]* fCollEffErr[fColor] / GetCollEff() / GetCollEff();
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kChargeFitValid
+//
+const Bool_t MCalibrationBlindPix::IsChargeFitValid()  const 
+{
+    return TESTBIT(fFlags,kChargeFitValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kOscillating
+//
+const Bool_t MCalibrationBlindPix::IsOscillating()  const 
+{
+    return TESTBIT(fFlags,kOscillating);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kPedestalFitValid
+//
+const Bool_t MCalibrationBlindPix::IsPedestalFitOK()  const 
+{
+    return TESTBIT(fFlags,kPedestalFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kSinglePheFitValid
+//
+const Bool_t MCalibrationBlindPix::IsSinglePheFitOK()  const 
+{
+    return TESTBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kFluxInsidePlexiglassAvailable
+//
+const Bool_t  MCalibrationBlindPix::IsFluxInsidePlexiglassAvailable()   const
+{
+  return TESTBIT(fFlags,kFluxInsidePlexiglassAvailable);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return kFALSE if IsChargeFitValid() is kFALSE
+//
+// Calculate fFluxInsidePlexiglass with the formula:
+// - fFluxInsidePlexiglass    = fLambda 
+//                            / GetCollEff()
+//                            / GetQE() 
+//                            * GetAtt()
+//                            / fArea 
+// - fFluxInsidePlexiglassVar = sqrt( fLambdaVar / ( fLambda * fLambda ) 
+//                             + GetQERelVar() 
+//                             + GetCollEffRelVar()
+//                             + GetAttRelVar()
+//                               ) * fFluxInsidePlexiglass * * fFluxInsidePlexiglass
+//
+// If the fFluxInsidePlexiglass is smaller than 0., return kFALSE
+// If the Variance is smaller than 0., return kFALSE
+//
+// SetFluxInsidePlexiglassAvailable() and return kTRUE
+//
+Bool_t MCalibrationBlindPix::CalcFluxInsidePlexiglass()
+{
+
+  if (IsChargeFitValid())
+    return kFALSE;
+  
+
+  //
+  // Start calculation of number of photons 
+  // The blind pixel has exactly 100 mm^2 area (with negligible error), 
+  //
+  fFluxInsidePlexiglass    = fLambda / GetQE() * GetAtt() / GetCollEff() / fArea;   
+
+  if (fFluxInsidePlexiglass < 0.)
+      return kFALSE;
+
+  fFluxInsidePlexiglassVar = GetLambdaRelVar() + GetQERelVar() + GetAttRelVar() + GetCollEffRelVar() + GetAreaRelVar();
+
+  //
+  // Finish calculation of errors -> convert from relative variance to absolute variance
+  //
+  fFluxInsidePlexiglassVar *= fFluxInsidePlexiglass * fFluxInsidePlexiglass;
+
+  if (fFluxInsidePlexiglassVar < 0.)
+      return kFALSE;
+
+  SetFluxInsidePlexiglassAvailable(kTRUE);  
+
+  *fLog << inf << GetDescriptor() 
+      << ": BlindPix #" << fPixId << ": Flux [ph/mm^2] inside Plexiglass: "
+      << Form("%5.3f +- %5.3f",fFluxInsidePlexiglass, GetFluxInsidePlexiglassErr()) << endl;
+
+  return kTRUE;
+}
+
+void MCalibrationBlindPix::Print(Option_t *opt) const
+{
+  
+  *fLog << all << GetDescriptor() 
+        << Form("BlindPixel: %3i"         ,GetPixId())
+        << Form("  Lambda: %4.2f +- %4.2f",GetLambda(),GetLambdaErr())
+        << Form("  Mu0: %4.2f +- %4.2f"   ,GetMu0(),   GetMu0Err())
+        << Form("  Mu1: %4.2f +- %4.2f"   ,GetMu1(),   GetMu1Err())
+        << Form("  Sigma0: %4.2f +- %4.2f",GetSigma0(),GetSigma0Err())
+        << Form("  Sigma1: %4.2f +- %4.2f",GetSigma1(),GetSigma1Err())
+        << endl;
+  *fLog << all
+        << " Pedestal Fit OK? :" << IsPedestalFitOK() 
+        << Form("  Lambda (Check): %4.2f +- %4.2f",GetLambdaCheck(),GetLambdaCheckErr())
+        << endl;
+  *fLog << all
+        << " Flux available? :" << IsFluxInsidePlexiglassAvailable() 
+        << Form("  Flux: %4.2f +- %4.2f",GetFluxInsidePlexiglass(),GetFluxInsidePlexiglassErr())
+        << endl;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationBlindPix.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationBlindPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationBlindPix.h	(revision 9772)
@@ -0,0 +1,146 @@
+#ifndef MARS_MCalibrationBlindPix
+#define MARS_MCalibrationBlindPix
+
+#ifndef ROOT_MArrayF
+#include <MArrayF.h>
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationBlindPix : public MCalibrationPix
+{
+private:
+
+  static const Float_t fgArea;         //! The Blind Pixel area in mm^2
+  static const Float_t fgAttGreen;     //! Attenuation Filter at 520 nm 
+  static const Float_t fgAttBlue ;     //! Attenuation Filter at 460 nm 
+  static const Float_t fgAttUV   ;     //! Attenuation Filter at 370 nm 
+  static const Float_t fgAttCT1  ;     //! Attenuation Filter at 370 nm
+  static const Float_t fgAttErr;       //! Error Att. Filter at all w.l.
+  static const Float_t fgQEGreen;      //! Quantum Efficiency at 520 nm
+  static const Float_t fgQEBlue ;      //! Quantum Efficiency at 460 nm
+  static const Float_t fgQEUV   ;      //! Quantum Efficiency at 370 nm
+  static const Float_t fgQECT1  ;      //! Quantum Efficiency at 370 nm
+  static const Float_t fgQEErrGreen;   //! Uncertainty QEUnCoated at 520 nm 
+  static const Float_t fgQEErrBlue;    //! Uncertainty QEUnCoated at 460 nm 
+  static const Float_t fgQEErrUV   ;   //! Uncertainty QEUnCoated at 370 nm 
+  static const Float_t fgQEErrCT1  ;   //! Uncertainty QEUnCoated at 370 nmu
+  static const Float_t fgCollEffGreen; //! Collecttion Efficiency
+  static const Float_t fgCollEffBlue;  //! Collecttion Efficiency
+  static const Float_t fgCollEffUV;    //! Collecttion Efficiency
+  static const Float_t fgCollEffCT1;   //! Collecttion Efficiency
+  static const Float_t fgCollEffErr;   //! Uncertainty Collection Efficiency
+
+  Float_t fArea;                       // Blind Pixel Area
+  Float_t fAreaErr;                    // Blind Pixel Area Error
+  MArrayF fAtt;                        // Attenuation filter (per color)
+  MArrayF fAttErr;                     // Error attnuation filter (per color)
+  MArrayF fQE;                         // Quantum eff. (per color)
+  MArrayF fQEErr;                      // Error Quantum eff. (per color)
+  MArrayF fCollEff;                    // Coll eff. (per color)
+  MArrayF fCollEffErr;                 // Error coll. eff. (per color)
+                                        
+  Float_t fLambda;                     // Mean Poisson fit
+  Float_t fLambdaCheck;                // Mean Pedestal Check (Gauss) fit
+  Float_t fLambdaCheckErr;             // Error mean pedestal Check fit
+  Float_t fLambdaVar;                  // Variance lambda Poisson fit
+  Float_t fFluxInsidePlexiglass;       // Number photons in INNER PIXEL inside the plexiglass
+  Float_t fFluxInsidePlexiglassVar;    // Variance number of photons in INNER PIXEL 
+  Float_t fMu0;                        // Position pedestal peak
+  Float_t fMu0Err;                     // Error pos. pedestal-peak
+  Float_t fMu1;                        // Position first photo-electron peak
+  Float_t fMu1Err;                     // Error pos. first photo-electon peak
+  Float_t fSigma0;                     // Width pedestal peak
+  Float_t fSigma0Err;                  // Error width pedestal peak
+  Float_t fSigma1;                     // Width first photo-electron peak  
+  Float_t fSigma1Err;                  // Error width first photo-electron peak  
+
+  enum { kOscillating, kPedestalFitOK, kSinglePheFitOK, kChargeFitValid, 
+         kFluxInsidePlexiglassAvailable };   // Possible validity flags 
+
+  MCalibrationCam::PulserColor_t fColor;     // Colour of the used pulser light
+
+public:
+
+  MCalibrationBlindPix(const char *name=NULL, const char *title=NULL);
+  
+  Bool_t CalcFluxInsidePlexiglass();
+  void   Clear(Option_t *o="");
+  void   Copy(TObject& object) const;
+  
+  // Getters
+  const Float_t GetAreaRelVar   () const;
+  const Float_t GetAtt          () const; 
+  const Float_t GetAttRelVar    () const; 
+  const Float_t GetQE           () const; 
+  const Float_t GetQERelVar     () const; 
+  const Float_t GetCollEff      () const;
+  const Float_t GetCollEffRelVar() const;   
+
+  const MCalibrationCam::PulserColor_t GetColor () const { return fColor;                }
+  const Float_t GetLambda                       () const { return fLambda;               }
+  const Float_t GetLambdaErr                    () const;
+  const Float_t GetLambdaRelVar                 () const;  
+  const Float_t GetLambdaCheck                  () const { return fLambdaCheck;          }
+  const Float_t GetLambdaCheckErr               () const { return fLambdaCheckErr;       }
+  const Float_t GetFluxInsidePlexiglass         () const { return fFluxInsidePlexiglass; }
+  const Float_t GetFluxInsidePlexiglassErr      () const;
+  const Float_t GetFluxInsidePlexiglassRelVar   () const;  
+  const Float_t GetMu0                          () const { return fMu0;                  }
+  const Float_t GetMu0Err                       () const { return fMu0Err;               }
+  const Float_t GetMu1                          () const { return fMu1;                  }
+  const Float_t GetMu1Err                       () const { return fMu1Err;               }
+  const Float_t GetSigma0                       () const { return fSigma0;               }
+  const Float_t GetSigma0Err                    () const { return fSigma0Err;            } 
+  const Float_t GetSigma1                       () const { return fSigma1;               }
+  const Float_t GetSigma1Err                    () const { return fSigma1Err;            }
+
+  const Bool_t  IsOscillating                   () const;
+  const Bool_t  IsChargeFitValid                () const;
+  const Bool_t  IsPedestalFitOK                 () const;
+  const Bool_t  IsSinglePheFitOK                () const;
+  const Bool_t  IsFluxInsidePlexiglassAvailable () const;
+
+  void Print(Option_t *opt=NULL) const;
+  
+  // Setters
+  void SetArea      ( Float_t f )               { fArea    = f; }
+  void SetAreaErr   ( Float_t f )               { fAreaErr = f; }  
+  
+  void SetAtt       ( Int_t n, Float_t *array ) { fAtt       .Set(n,array); }
+  void SetAttErr    ( Int_t n, Float_t *array ) { fAttErr    .Set(n,array); }
+  void SetQE        ( Int_t n, Float_t *array ) { fQE        .Set(n,array); }
+  void SetQEErr     ( Int_t n, Float_t *array ) { fQEErr     .Set(n,array); }
+  void SetCollEff   ( Int_t n, Float_t *array ) { fCollEff   .Set(n,array); }
+  void SetCollEffErr( Int_t n, Float_t *array ) { fCollEffErr.Set(n,array); }
+  
+  void SetColor          ( const MCalibrationCam::PulserColor_t color ) { fColor      = color; }
+  void SetLambda         ( const Float_t f )                            { fLambda         = f; }
+  void SetLambdaVar      ( const Float_t f )                            { fLambdaVar      = f; }
+  void SetLambdaCheck    ( const Float_t f )                            { fLambdaCheck    = f; }
+  void SetLambdaCheckErr ( const Float_t f )                            { fLambdaCheckErr = f; }
+  void SetMu0            ( const Float_t f )                            { fMu0            = f; }
+  void SetMu0Err         ( const Float_t f )                            { fMu0Err         = f; }
+  void SetMu1            ( const Float_t f )                            { fMu1            = f; }
+  void SetMu1Err         ( const Float_t f )                            { fMu1Err         = f; }
+  void SetSigma0         ( const Float_t f )                            { fSigma0         = f; }
+  void SetSigma0Err      ( const Float_t f )                            { fSigma0Err      = f; }
+  void SetSigma1         ( const Float_t f )                            { fSigma1         = f; }
+  void SetSigma1Err      ( const Float_t f )                            { fSigma1Err      = f; }
+
+  void SetOscillating    ( const Bool_t  b=kTRUE );
+  void SetChargeFitValid ( const Bool_t  b=kTRUE );
+  void SetPedestalFitOK  ( const Bool_t  b=kTRUE );
+  void SetSinglePheFitOK ( const Bool_t  b=kTRUE );
+  void SetFluxInsidePlexiglassAvailable( const Bool_t b=kTRUE);
+
+  ClassDef(MCalibrationBlindPix, 2)	// Container Calibration Results Blind Pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationCam.cc	(revision 9772)
@@ -0,0 +1,586 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationCam                                               
+//                                                               
+// Base class for Camera Calibration results. 
+//
+// Contains TOrdCollections for the following objects:
+// - fPixels:         Array of classes derived from MCalibrationPix, one entry 
+//                    per pixel. Has to be created
+// - fAverageAreas:   Array of classes derived from MCalibrationPix, one entry
+//                    per pixel AREA. Has to be created
+// - fAverageSectors: Array of classes derived from MCalibrationPix, one entry
+//                    per camera SECTOR. Has to be created
+//
+// - fAverageBadAreas: Array of classes derived from MBadPixelsPix, one entry
+//                     per pixel AREA. Is created automatically. 
+// - fAverageBadSectors: Array of classes derived from MBadPixelsPix, one entry
+//                    per camera SECTOR. Is created automatically.
+//
+// All TOrdCollections have to enlarged by the corresponding calls to (e.g. in MGeomApply): 
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors() 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCalibrationPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationCam);
+
+using namespace std;
+
+const Int_t MCalibrationCam::gkNumPulserColors = 4;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Set the following pointer to NULL:
+// - fPixels
+// - fAverageAreas
+// - fAverageSectors
+//
+// Initializes:
+// - fPulserColor to kNONE 
+// - fNumHiGainFADCSlices to 0.
+// - fNumLoGainFADCSlices to 0.
+//
+// Creates a TOrdCollection of MBadPixelsPix containers for the TOrdCollection's: 
+// - fAverageBadAreas
+// - fAverageBadSectors
+// all initialized to 1 entry
+//
+// Later, a call to InitAverageAreas() and InitAverageSectors() (or Init()) 
+// has to be performed in order to get the dimension correctly.
+//
+MCalibrationCam::MCalibrationCam(const char *name, const char *title)
+    : fPulserColor(kNONE)
+{
+
+  fPixels = new TOrdCollection;
+  fPixels->SetOwner();
+
+  fAverageAreas = new TOrdCollection;
+  fAverageAreas->SetOwner();
+  
+  fAverageSectors = new TOrdCollection;
+  fAverageSectors->SetOwner();
+
+  fAverageBadAreas = new TOrdCollection;
+  fAverageBadAreas->SetOwner();
+  
+  fAverageBadSectors = new TOrdCollection;
+  fAverageBadSectors->SetOwner();
+
+  fNumHiGainFADCSlices.Set(1);
+  fNumLoGainFADCSlices.Set(1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the following TOrdCollection's of MCalibrationPix containers (if exist):
+// - fPixels
+// - fAverageAreas
+// - fAverageSectors
+//  
+// Deletes the following TOrdCollection's of MBadPixelsPix containers (if exist):
+// - fAverageBadAreas
+// - fAverageBadSectors
+//
+MCalibrationCam::~MCalibrationCam()
+{
+
+  //
+  // delete fPixels should delete all Objects stored inside
+  //
+  if (fPixels)
+    delete fPixels;
+
+  if (fAverageAreas)
+    delete fAverageAreas;
+
+  if (fAverageSectors)
+    delete fAverageSectors;
+
+  if (fAverageBadAreas)
+    delete fAverageBadAreas;
+
+  if (fAverageBadSectors)
+    delete fAverageBadSectors;
+  
+}
+
+// --------------------------------------
+//
+// Calls the ForEach macro for the TOrdCollection fPixels with the argument Clear()
+// 
+// Loops over the fAverageAreas, calling the function Clear() for 
+// every entry in:
+// - fAverageAreas
+// - fAverageBadAreas
+// 
+// Loops over the fAverageSectors, calling the function Clear() for 
+// every entry in:
+// - fAverageSectors
+// - fAverageBadSectors
+// 
+void MCalibrationCam::Clear(Option_t *o)
+{
+
+  {  fPixels        ->ForEach(TObject, Clear)();  }
+  {  fAverageAreas  ->ForEach(TObject, Clear)();  }
+  {  fAverageSectors->ForEach(TObject, Clear)();  }
+  
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MCalibrationCam::Copy(TObject& object) const
+{
+  
+  MCalibrationCam &calib = (MCalibrationCam&)object;
+  
+  MParContainer::Copy(calib);
+  
+  calib.fPulserColor = fPulserColor;
+  
+  const Int_t n = GetSize();
+  if (n != 0)
+    {
+      calib.InitSize(n);
+      for (int i=0; i<n; i++)
+        (*this)[i].Copy(calib[i]);
+    }
+  
+  const Int_t n2 = GetAverageAreas();
+  if (n2 != 0)
+    {
+      calib.InitAverageAreas(n2);
+      for (int i=0; i<n2; i++)
+        {
+          GetAverageArea   (i).Copy(calib.GetAverageArea(i));
+          GetAverageBadArea(i).Copy(calib.GetAverageBadArea(i));
+          calib.fNumUnsuitable      [i] = fNumUnsuitable[i];
+          calib.fNumUnreliable      [i] = fNumUnreliable[i];
+          calib.fNumHiGainFADCSlices[i] = fNumHiGainFADCSlices[i];
+          calib.fNumLoGainFADCSlices[i] = fNumLoGainFADCSlices[i];
+        }
+    }
+  
+  const Int_t n3 = GetAverageSectors();
+  if (n3 != 0)
+    {
+      calib.InitAverageSectors(n3);
+      for (int i=0; i<n3; i++)
+        {
+          GetAverageSector   (i).Copy(calib.GetAverageSector(i));
+          GetAverageBadSector(i).Copy(calib.GetAverageBadSector(i));
+        }
+    }
+}
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollection using the 
+// virtual function Add().
+//
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationCam::InitSize(const UInt_t i)
+{
+
+  const UInt_t save = GetSize();
+
+  if (i==save)
+    return;
+  
+  if (i>save)
+    Add(save,i);
+}
+
+void MCalibrationCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationPix,i);
+}
+
+void MCalibrationCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationPix,i);
+}
+
+void MCalibrationCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationPix,i);
+}
+
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollections
+// - fAverageAreas
+// - fAverageBadAreas
+// using the virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationCam::InitAverageAreas(const UInt_t i)
+{
+
+  const UInt_t save = GetAverageAreas();
+
+  if (i==save)
+    return;
+  
+  fNumUnsuitable.Set(i);
+  fNumUnreliable.Set(i);
+  fNumHiGainFADCSlices.Set(i);
+  fNumLoGainFADCSlices.Set(i);
+
+  if (i < save)
+    return;
+
+  for (UInt_t j=save; j<i; j++)
+    fAverageBadAreas->AddAt(new MBadPixelsPix,j);
+  
+  AddArea(save,i);
+
+  for (UInt_t j=save; j<i; j++)
+    GetAverageArea(j).SetPixId(j);
+
+}
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollections
+// - fAverageSectors
+// - fAverageBadSectors
+// using the virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationCam::InitAverageSectors(const UInt_t i)
+{
+
+  const UInt_t save = GetAverageSectors();
+
+  if (i==save)
+    return;
+  
+  if (i < save)
+    return;
+
+  for (UInt_t j=save; j<i; j++)
+    fAverageBadSectors->AddAt(new MBadPixelsPix,j);
+  
+  AddSector(save,i);
+
+  for (UInt_t j=save; j<i; j++)
+    GetAverageSector(j).SetPixId(j);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MCalibrationCam::Init(const MGeomCam &geom)
+{
+  InitSize          (geom.GetNumPixels() );
+  InitAverageAreas  (geom.GetNumAreas()  );
+  InitAverageSectors(geom.GetNumSectors());
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the number of un-suitable pixels per area index and -1 if 
+// the area index exceeds the initialized array.
+//
+const Int_t MCalibrationCam::GetNumUnsuitable( const Int_t  aidx ) const
+{
+  if (aidx < 0)
+    {
+      Int_t num = 0;
+      for (Int_t i=0;i<fNumUnsuitable.GetSize();i++)
+        num += fNumUnsuitable[i];
+      return num;
+    }
+  
+  return aidx > fNumUnsuitable.GetSize() ? -1 : fNumUnsuitable[aidx]; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the number of un-reliable pixels per area index and -1 if 
+// the area index exceeds the initialized array.
+//
+const Int_t MCalibrationCam::GetNumUnreliable( const Int_t  aidx ) const
+{
+  if (aidx < 0)
+    {
+      Int_t num = 0;
+      for (Int_t i=0;i<fNumUnreliable.GetSize();i++)
+        num += fNumUnreliable[i];
+      return num;
+    }
+
+  return aidx > fNumUnreliable.GetSize() ? -1 : fNumUnreliable[aidx]; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mean number of High-Gain FADC slices per area index and -1 if 
+// the area index exceeds the initialized array.
+//
+const Float_t MCalibrationCam::GetNumHiGainFADCSlices( const Int_t  aidx ) const
+{
+  if (aidx < 0)
+    return -1;
+
+  return aidx > fNumHiGainFADCSlices.GetSize() ? -1 : fNumHiGainFADCSlices[aidx]; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mean number of Low-Gain FADC slices per area index and -1 if 
+// the area index exceeds the initialized array.
+//
+const Float_t MCalibrationCam::GetNumLoGainFADCSlices( const Int_t  aidx ) const
+{
+  if (aidx < 0)
+    return -1;
+
+  return aidx > fNumLoGainFADCSlices.GetSize() ? -1 : fNumLoGainFADCSlices[aidx]; 
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageAreas
+// independently if the MCalibrationPix is filled with values or not.
+//
+const Int_t MCalibrationCam::GetAverageAreas() const
+{
+  return fAverageAreas->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageSectors
+// independently if the MCalibrationPix is filled with values or not.
+//
+const Int_t MCalibrationCam::GetAverageSectors() const
+{
+  return fAverageSectors->GetSize();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MCalibrationPix &MCalibrationCam::operator[](UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fPixels->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MCalibrationPix &MCalibrationCam::operator[](UInt_t i) const
+{
+  return *static_cast<MCalibrationPix*>(fPixels->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fPixels 
+// independently if the MCalibrationPix is filled with values or not.
+//
+const Int_t MCalibrationCam::GetSize() const
+{
+  return fPixels->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MCalibrationPix &MCalibrationCam::GetAverageArea(const UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fAverageAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MCalibrationPix &MCalibrationCam::GetAverageArea(const UInt_t i) const 
+{
+  return *static_cast<MCalibrationPix*>(fAverageAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MCalibrationPix &MCalibrationCam::GetAverageSector(const UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fAverageSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MCalibrationPix &MCalibrationCam::GetAverageSector(const UInt_t i) const 
+{
+  return *static_cast<MCalibrationPix*>(fAverageSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MBadPixelsPix &MCalibrationCam::GetAverageBadArea(const UInt_t i)
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MBadPixelsPix &MCalibrationCam::GetAverageBadArea(const UInt_t i) const 
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MBadPixelsPix &MCalibrationCam::GetAverageBadSector(const UInt_t i)
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MBadPixelsPix &MCalibrationCam::GetAverageBadSector(const UInt_t i) const 
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadSectors->At(i));
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Dummy needed for compilation with MCamEvent
+//
+Bool_t MCalibrationCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Calls MCalibrationPix::DrawClone()
+//
+void MCalibrationCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
+
+void MCalibrationCam::SetNumHiGainFADCSlices( const Float_t i, const Int_t aidx)
+{
+  if (aidx < 0)
+    return;
+
+  if (aidx < fNumHiGainFADCSlices.GetSize())
+    fNumHiGainFADCSlices[aidx] = i;  
+}
+
+void MCalibrationCam::SetNumLoGainFADCSlices( const Float_t i, const Int_t aidx)
+{
+  if (aidx < 0)
+    return;
+  if (aidx < fNumLoGainFADCSlices.GetSize())
+    fNumLoGainFADCSlices[aidx] = i; 
+}
+
+void MCalibrationCam::SetNumUnsuitable( const UInt_t i, const Int_t aidx)
+{
+  if (aidx < 0)
+    return;
+
+  if (aidx < fNumUnsuitable.GetSize())
+    fNumUnsuitable[aidx] = i;  
+}
+
+void MCalibrationCam::SetNumUnreliable( const UInt_t i, const Int_t aidx)
+{
+  if (aidx < 0)
+    return;
+  if (aidx < fNumUnreliable.GetSize())
+    fNumUnreliable[aidx] = i; 
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationCam.h	(revision 9772)
@@ -0,0 +1,107 @@
+#ifndef MARS_MCalibrationCam
+#define MARS_MCalibrationCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class TOrdCollection;
+
+class MCalibrationPix;
+class MBadPixelsPix;
+class MBadPixelsCam;
+class MGeomCam;
+class MCalibrationCam : public MParContainer, public MCamEvent
+{
+public:
+
+  enum PulserColor_t { 
+	kCT1  =0, 
+	kGREEN=1, 
+	kBLUE =2, 
+	kUV   =3, 
+	kNONE =4 
+	};                                  //! Possible Pulser colours
+  static const Int_t gkNumPulserColors;     //! Number of Pulser colours (now set to: 4)
+  
+protected:
+
+  TArrayI fNumUnsuitable;            // Number uncalibrated Pixels per area index 
+  TArrayI fNumUnreliable;            // Number unreliable   Pixels per area index 
+
+  TArrayF fNumHiGainFADCSlices;      // Number High-Gain FADC slices used by extractor      
+  TArrayF fNumLoGainFADCSlices;      // Number Low -Gain FADC slices used by extractor
+  
+  PulserColor_t fPulserColor;        // Colour of the pulsed LEDs
+
+  TOrdCollection *fPixels;            //-> Array of MCalibrationPix, one per pixel
+  TOrdCollection *fAverageAreas;      // Array of MCalibrationPix, one per pixel area
+  TOrdCollection *fAverageSectors;    // Array of MCalibrationPix, one per camera sector
+  TOrdCollection *fAverageBadAreas;   // Array of MBadPixelsPix,   one per pixel area
+  TOrdCollection *fAverageBadSectors; // Array of MBadPixelsPix,   one per camera sector
+
+  virtual void Add(const UInt_t a, const UInt_t b);
+  virtual void AddArea(const UInt_t a, const UInt_t b);
+  virtual void AddSector(const UInt_t a, const UInt_t b);
+  
+  void  InitAverageSectors     ( const UInt_t i               );
+  virtual void  InitAverageAreas       ( const UInt_t i               );
+
+public:
+
+  MCalibrationCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationCam();
+  
+  void Clear           ( Option_t *o="");
+  void Copy(TObject& object) const;
+  
+  void DrawPixelContent( Int_t num) const;
+
+  // Getters
+  const Int_t            GetAverageAreas        ()                     const;
+        MCalibrationPix &GetAverageArea         ( const UInt_t i     );
+  const MCalibrationPix &GetAverageArea         ( const UInt_t i     ) const;
+        MBadPixelsPix   &GetAverageBadArea      ( const UInt_t i     );
+  const MBadPixelsPix   &GetAverageBadArea      ( const UInt_t i     ) const;
+  const Int_t            GetAverageSectors      ()                     const;  
+        MCalibrationPix &GetAverageSector       ( const UInt_t i     );
+  const MCalibrationPix &GetAverageSector       ( const UInt_t i     ) const;  
+        MBadPixelsPix   &GetAverageBadSector    ( const UInt_t i     );
+  const MBadPixelsPix   &GetAverageBadSector    ( const UInt_t i     ) const;
+  const Float_t          GetNumHiGainFADCSlices ( const Int_t aidx=0 ) const;
+  const Float_t          GetNumLoGainFADCSlices ( const Int_t aidx=0 ) const;
+  const Int_t            GetNumUnsuitable       ( const Int_t aidx=-1) const;
+  const Int_t            GetNumUnreliable       ( const Int_t aidx=-1) const;
+
+        Bool_t           GetPixelContent        ( Double_t &val, Int_t idx, const MGeomCam &cam, 
+	                                          Int_t type=0       ) const;
+  const PulserColor_t    GetPulserColor         ()                     const { return fPulserColor; }
+  const Int_t            GetSize                ()                     const;
+
+        MCalibrationPix &operator[]             ( UInt_t i );
+  const MCalibrationPix &operator[]             ( UInt_t i )           const;
+
+  // Inits
+  void  Init                   ( const MGeomCam &geom         );
+  void  InitSize               ( const UInt_t i               );
+
+  // Setters
+  void  SetNumHiGainFADCSlices ( const Float_t f, const Int_t aidx=0 );
+  void  SetNumLoGainFADCSlices ( const Float_t f, const Int_t aidx=0 );
+  void  SetNumUnsuitable       ( const UInt_t i,  const Int_t aidx   );  
+  void  SetNumUnreliable       ( const UInt_t i,  const Int_t aidx   ); 
+  virtual void  SetPulserColor( const PulserColor_t col=kCT1 )  { fPulserColor = col; }
+  
+  ClassDef(MCalibrationCam, 5)	// Base class Container for Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationChargeCalc.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationChargeCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationChargeCalc.cc	(revision 9772)
@@ -0,0 +1,2256 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationChargeCalc
+//
+//   Task to calculate the calibration conversion factors and quantum efficiencies 
+//   from the fit results to the summed FADC slice distributions delivered by 
+//   MCalibrationChargeCam, MCalibrationChargePix, MCalibrationChargeBlindPix and 
+//   MCalibrationChargePINDiode, calculated and filled by MHCalibrationChargeCam, 
+//   MHCalibrationChargePix, MHCalibrationChargeBlindPix and MHCalibrationChargePINDiode.
+//
+//   PreProcess(): Initialize pointers to MCalibrationChargeCam, MCalibrationChargeBlindPix
+//                 MCalibrationChargePINDiode and  MCalibrationQECam
+//
+//                 Initialize pulser light wavelength
+//               
+//   ReInit():     MCalibrationCam::InitSize(NumPixels) is called from MGeomApply (which allocates
+//                 memory in a TClonesArray of type MCalibrationChargePix)
+//                 Initializes pointer to MBadPixelsCam
+//
+//   Process():    Nothing to be done, histograms getting filled by MHCalibrationChargeCam
+//
+//   PostProcess(): - FinalizePedestals()
+//                  - FinalizeCharges()
+//                  - FinalizeFFactorMethod()
+//                  - FinalizeBadPixels()
+//                  - FinalizeBlindCam()
+//                  - FinalizePINDiode()
+//                  - FinalizeFFactorQECam()
+//                  - FinalizeBlindPixelQECam()
+//                  - FinalizePINDiodeQECam()
+//
+//  Input Containers:
+//   MCalibrationChargeCam
+//   MCalibrationChargeBlindPix
+//   MCalibrationChargePINDiode
+//   MCalibrationQECam
+//   MPedestalCam
+//   MBadPixelsCam
+//   MGeomCam
+//   MTime
+//
+//  Output Containers:
+//   MCalibrationChargeCam
+//   MCalibrationChargeBlindPix
+//   MCalibrationChargePINDiode
+//   MCalibrationQECam
+//   MBadPixelsCam
+//
+//
+//  Preliminary description of the calibration in photons (email from 12/02/04)
+//
+//  Why calibrating in photons:
+//  ===========================
+//  
+//  At the Barcelona meeting in 2002, we decided to calibrate the camera in
+//  photons. This for the following reasons:
+//  
+//  * The physical quantity arriving at the camera are photons. This is
+//    the direct physical information from the air shower. The photons
+//    have a flux and a spectrum.
+//  
+//  * The photon fluxes depend mostly on the shower energy (with
+//    corrections deriving from the observation conditions), while the photon
+//    spectra depend mostly on the observation conditions: zenith angle,
+//    quality of the air, also the impact parameter of the shower.
+//  
+//  * The photomultiplier, in turn, has different response properties
+//    (quantum efficiencies) for photons of different colour. (Moreover,
+//    different pixels have slightly different quantum efficiencies).
+//    The resulting number of photo-electrons is then amplified (linearly)
+//    with respect to the photo-electron flux.
+//  
+//  * In the ideal case, one would like to disentagle the effects
+//    of the observation conditions from the primary particle energy (which
+//    one likes to measure). To do so, one needs:
+//  
+//    1) A reliable calibration relating the FADC counts to the photo-electron
+//       flux -> This is accomplished with the F-Factor method.
+//  
+//    2) A reliable calibration of the wavelength-dependent quantum efficiency
+//       -> This is accomplished with the combination of the three methods,
+//          together with QE-measurements performed by David in order to do
+//          the interpolation.
+//  
+//    3) A reliable calibration of the observation conditions. This means:
+//       - Tracing the atmospheric conditions   -> LIDAR
+//       - Tracing the observation zenith angle -> Drive System
+//
+//    4) Some knowlegde about the impact parameter:
+//       - This is the only part which cannot be accomplished well with a
+//         single telescope. We would thus need to convolute the spectrum
+//         over the distribution of impact parameters.
+//  
+//  
+//  How an ideal calibration would look like:
+//  =========================================
+//  
+//  We know from the combined PIN-Diode and Blind-Pixel Method the response of
+//  each pixel to well-measured light fluxes in three representative
+//  wavelengths (green, blue, UV). We also know the response to these light
+//  fluxes in photo-electrons. Thus, we can derive:
+//  
+//  - conversion factors to photo-electrons
+//  - conversion factors to photons in three wavelengths.
+//  
+//  Together with David's measurements and some MC-simulation, we should be
+//  able to derive tables for typical Cherenkov-photon spectra - convoluted
+//  with the impact parameters and depending on the athmospheric conditions
+//  and the zenith angle (the "outer parameters").
+//  
+//  From these tables we can create "calibration tables" containing some
+//  effective quantum efficiency depending on these outer parameters and which
+//  are different for each pixel.
+//  
+//  In an ideal MCalibrate, one would thus have to convert first the FADC
+//  slices to Photo-electrons and then, depending on the outer parameters,
+//  look up the effective quantum efficiency and get the mean number of
+//  photons which is then used for the further analysis.
+//  
+//  How the (first) MAGIC calibration should look like:
+//  ===================================================
+//  
+//  For the moment, we have only one reliable calibration method, although
+//  with very large systematic errors. This is the F-Factor method. Knowing
+//  that the light is uniform over the whole camera (which I would not at all
+//  guarantee in the case of the CT1 pulser), one could in principle already
+//  perform a relative calibration of the quantum efficiencies in the UV.
+//  However, the spread in QE at UV is about 10-15% (according to the plot
+//  that Abelardo sent around last time. The spread in photo-electrons is 15%
+//  for the inner pixels, but much larger (40%) for the outer ones.
+//  
+//  I'm not sure if we can already say that we have measured the relative
+//  difference in quantum efficiency for the inner pixels and produce a first
+//  QE-table for each pixel. To so, I would rather check in other wavelengths
+//  (which we can do in about one-two weeks when the optical transmission of
+//  the calibration trigger is installed).
+//  
+//  Thus, for the moment being, I would join Thomas proposal to calibrate in
+//  photo-electrons and apply one stupid average quantum efficiency for all
+//  pixels. This keeping in mind that we will have much preciser information
+//  in about one to two weeks.
+//  
+//  
+//  What MCalibrate should calculate and what should be stored:
+//  ===========================================================
+//  
+//  It is clear that in the end, MCerPhotEvt will store photons.
+//  MCalibrationCam stores the conversionfactors to photo-electrons and also
+//  some tables of how to apply the conversion to photons, given the outer
+//  parameters. This is not yet implemented and not even discussed.
+//  
+//  To start, I would suggest that we define the "average quantum efficiency"
+//  (maybe something like 25+-3%) and apply them equally to all
+//  photo-electrons. Later, this average factor can be easily replaced by a
+//  pixel-dependent factor and later by a (pixel-dependent) table.
+//  
+//  
+//  
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargeCalc.h"
+
+#include <TSystem.h>
+#include <TH1.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MStatusDisplay.h"
+
+#include "MCalibrationPattern.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MHCamera.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCalibrationIntensityChargeCam.h"
+#include "MCalibrationIntensityQECam.h"
+#include "MCalibrationIntensityBlindCam.h"
+
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationChargeBlindCam.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationBlindPix.h"
+#include "MCalibrationBlindCam.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+#include "MExtractedSignalBlindPixel.h"
+#include "MExtractedSignalPINDiode.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+ClassImp(MCalibrationChargeCalc);
+
+using namespace std;
+
+const Float_t MCalibrationChargeCalc::fgChargeLimit            = 2.5;
+const Float_t MCalibrationChargeCalc::fgChargeErrLimit         = 0.;
+const Float_t MCalibrationChargeCalc::fgChargeRelErrLimit      = 1.;
+const Float_t MCalibrationChargeCalc::fgLambdaErrLimit         = 0.2;
+const Float_t MCalibrationChargeCalc::fgLambdaCheckLimit       = 0.5;
+const Float_t MCalibrationChargeCalc::fgPheErrLimit            = 4.5;
+const Float_t MCalibrationChargeCalc::fgFFactorErrLimit        = 4.5;
+const TString MCalibrationChargeCalc::fgNamePedestalCam = "MPedestalCam";
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets the pointer to fQECam and fGeom to NULL
+// 
+// Calls AddToBranchList for: 
+// - MRawEvtData.fHiGainPixId   
+// - MRawEvtData.fLoGainPixId   
+// - MRawEvtData.fHiGainFadcSamples
+// - MRawEvtData.fLoGainFadcSamples
+//
+// Initializes:
+// - fChargeLimit       to fgChargeLimit 
+// - fChargeErrLimit    to fgChargeErrLimit   
+// - fChargeRelErrLimit to fgChargeRelErrLimit
+// - fFFactorErrLimit   to fgFFactorErrLimit
+// - fLambdaCheckLimit  to fgLambdaCheckLimit 
+// - fLambdaErrLimit    to fgLambdaErrLimit 
+// - fNamePedestalCam   to fgNamePedestalCam
+// - fPheErrLimit       to fgPheErrLimit  
+// - fPulserColor       to MCalibrationCam::kCT1
+// - fOutputPath        to "."
+// - fOutputFile        to "ChargeCalibStat.txt"
+// - flag debug         to kFALSE
+//
+// Sets all checks
+//
+// Calls:
+// - Clear()
+//
+MCalibrationChargeCalc::MCalibrationChargeCalc(const char *name, const char *title)
+    : fGeom(NULL), fSignal(NULL), fCalibPattern(NULL)
+{
+        
+  fName  = name  ? name  : "MCalibrationChargeCalc";
+  fTitle = title ? title : "Task to calculate the calibration constants and MCalibrationCam ";
+  
+  AddToBranchList("MRawEvtData.fHiGainPixId");
+  AddToBranchList("MRawEvtData.fLoGainPixId");
+  AddToBranchList("MRawEvtData.fHiGainFadcSamples");
+  AddToBranchList("MRawEvtData.fLoGainFadcSamples");
+  
+  SetChargeLimit       ();
+  SetChargeErrLimit    ();  
+  SetChargeRelErrLimit ();
+  SetFFactorErrLimit   ();
+  SetLambdaCheckLimit  ();
+  SetLambdaErrLimit    ();
+  SetNamePedestalCam   ();
+  SetPheErrLimit       ();
+  SetOutputPath        ();
+  SetOutputFile        ();
+  SetDebug       ( kFALSE );
+
+  SetCheckDeadPixels       ();
+  SetCheckDeviatingBehavior();
+  SetCheckExtractionWindow ();
+  SetCheckHistOverflow     ();
+  SetCheckOscillations     ();
+
+  Clear();
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - all variables to 0., 
+// - all flags to kFALSE
+// - all pointers to NULL
+// - the pulser colour to kNONE
+// - fBlindPixelFlags to 0
+// - fPINDiodeFlags   to 0
+//
+void MCalibrationChargeCalc::Clear(const Option_t *o)
+{
+  
+    fNumHiGainSamples          = 0.;
+    fNumLoGainSamples          = 0.;
+    fSqrtHiGainSamples         = 0.;
+    fSqrtLoGainSamples         = 0.;
+    fNumInnerFFactorMethodUsed = 0;
+
+    fNumProcessed              = 0;
+
+    fIntensBad   = NULL;
+    fBadPixels   = NULL;
+    fIntensCam   = NULL;
+    fCam         = NULL;
+    fHCam        = NULL;
+    fIntensQE    = NULL;
+    fQECam       = NULL;
+    fIntensBlind = NULL;
+    fBlindCam    = NULL;
+    fHBlindCam   = NULL;
+    fPINDiode    = NULL;
+    fPedestals   = NULL;
+
+    SetPulserColor ( MCalibrationCam::kNONE );
+
+    fStrength    = 0.;
+    fBlindPixelFlags.Set(0);
+    fPINDiodeFlags  .Set(0);
+    fResultFlags    .Set(0);
+}
+
+
+// -----------------------------------------------------------------------------------
+//
+// The following container are searched for and execution aborted if not in MParList:
+//  - MPedestalCam
+//  - MCalibrationPattern
+//  - MExtractedSignalCam
+//
+Int_t MCalibrationChargeCalc::PreProcess(MParList *pList)
+{
+  
+  /*
+  if (IsInterlaced())
+    {
+      fTrigPattern = (MTriggerPattern*)pList->FindObject("MTriggerPattern");
+      if (!fTrigPattern)
+        {
+          *fLog << err << "MTriggerPattern not found... abort." << endl;
+          return kFALSE;
+        }
+    }
+  */
+
+  fCalibPattern = (MCalibrationPattern*)pList->FindObject("MCalibrationPattern");
+  if (!fCalibPattern)
+    {
+      *fLog << err << "MCalibrationPattern not found... abort." << endl;
+      return kFALSE;
+    }
+
+  // 
+  // Containers that have to be there.
+  //
+  fSignal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!fSignal)
+    {
+      *fLog << err << "MExtractedSignalCam not found... aborting" << endl;
+      return kFALSE;
+    }
+
+  if (fPedestals)
+    return kTRUE;
+
+  fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber(fNamePedestalCam), "MPedestalCam");
+  if (!fPedestals)
+    {
+      *fLog << err << GetDescriptor() << ": " << fNamePedestalCam << " not found... aborting" << endl;
+      return kFALSE;
+    }
+
+  fPulserColor = MCalibrationCam::kNONE;
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+//  - MGeomCam
+// -  MCalibrationIntensityChargeCam or MCalibrationChargeCam
+//  - MCalibrationIntensityQECam or MCalibrationQECam 
+//  - MBadPixelsIntensityCam or MBadPixelsCam
+// 
+// Search for the following input containers and give a warning if not existing:
+//  - MCalibrationBlindPix
+//  - MCalibrationChargePINDiode
+//
+// It retrieves the following variables from MCalibrationChargeCam:
+//
+//  - fNumHiGainSamples 
+//  - fNumLoGainSamples 
+//
+// It defines the PixId of every pixel in:
+//
+// - MCalibrationIntensityChargeCam 
+// - MCalibrationChargeCam 
+// - MCalibrationQECam
+//
+// It sets all pixels in excluded which have the flag fBadBixelsPix::IsBad() set in:
+// 
+// - MCalibrationChargePix
+// - MCalibrationQEPix
+//
+// Sets the pulser colour and tests if it has not changed w.r.t. fPulserColor in:
+//
+// - MCalibrationChargeCam
+// - MCalibrationBlindPix (if existing)
+// - MCalibrationChargePINDiode (if existing)
+//
+Bool_t MCalibrationChargeCalc::ReInit(MParList *pList )
+{
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "No MGeomCam found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fIntensCam = (MCalibrationIntensityChargeCam*)pList->FindObject(AddSerialNumber("MCalibrationIntensityChargeCam"));
+  if (fIntensCam)
+    *fLog << inf << "Found MCalibrationIntensityChargeCam ... " << endl;
+  else
+    {
+      fCam = (MCalibrationChargeCam*)pList->FindObject(AddSerialNumber("MCalibrationChargeCam"));
+      if (!fCam)
+        {
+          *fLog << err << "Cannot find MCalibrationChargeCam ... abort." << endl;
+          *fLog << err << "Maybe you forget to call an MFillH for the MHCalibrationChargeCam before..." << endl;
+          return kFALSE;
+        }
+    }
+  
+  fHCam = (MHCalibrationChargeCam*)pList->FindObject(AddSerialNumber("MHCalibrationChargeCam"));
+  if (!fHCam)
+    {
+      *fLog << err << "Cannot find MHCalibrationChargeCam ... abort." << endl;
+      *fLog << err << "Maybe you forget to call an MFillH for the MHCalibrationChargeCam before..." << endl;
+      return kFALSE;
+    }
+
+  fIntensQE = (MCalibrationIntensityQECam*)pList->FindObject(AddSerialNumber("MCalibrationIntensityQECam"));
+  if (fIntensQE)
+    *fLog << inf << "Found MCalibrationIntensityQECam ... " << endl;
+  else
+    {
+      fQECam = (MCalibrationQECam*)pList->FindObject(AddSerialNumber("MCalibrationQECam"));
+      if (!fQECam)
+        {
+          *fLog << err << "Cannot find MCalibrationQECam ... abort." << endl;
+          *fLog << err << "Maybe you forget to call an MFillH for the MHCalibrationQECam before..." << endl;
+          return kFALSE;
+        }
+    }
+  
+  fIntensBlind = (MCalibrationIntensityBlindCam*)pList->FindObject(AddSerialNumber("MCalibrationIntensityBlindCam"));
+  if (fIntensBlind)
+    *fLog << inf << "Found MCalibrationIntensityBlindCam ... " << endl;
+  else
+    {
+      fBlindCam = (MCalibrationBlindCam*)pList->FindObject(AddSerialNumber("MCalibrationBlindCam"));
+      if (!fBlindCam)
+        *fLog << warn << GetDescriptor() 
+              << ": No MCalibrationBlindCam found... no Blind Pixel method! " << endl;
+    }
+  
+  fHBlindCam = (MHCalibrationChargeBlindCam*)pList->FindObject(AddSerialNumber("MHCalibrationChargeBlindCam"));  
+  if (!fHBlindCam)
+    *fLog << warn << GetDescriptor() 
+          << ": No MHCalibrationChargeBlindCam found... no Blind Pixel method! " << endl;
+
+  fIntensBad = (MBadPixelsIntensityCam*)pList->FindObject(AddSerialNumber("MBadPixelsIntensityCam"));
+  if (fIntensBad)
+    *fLog << inf << "Found MBadPixelsIntensityCam ... " << endl;
+  else
+    {
+      fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+      if (!fBadPixels)
+        {
+          *fLog << err << "Cannot find MBadPixelsCam ... abort." << endl;
+          return kFALSE;
+        }
+    }
+  
+  // 
+  // Optional Containers 
+  //
+  fPINDiode = (MCalibrationChargePINDiode*)pList->FindObject("MCalibrationChargePINDiode");
+  if (!fPINDiode)
+    *fLog << warn << GetDescriptor() 
+          << ": No MCalibrationChargePINDiode found... no PIN Diode method! " << endl;
+  
+  MCalibrationQECam     *qecam     = fIntensQE      
+    ? (MCalibrationQECam*)    fIntensQE->GetCam()   : fQECam;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  UInt_t npixels     = fGeom->GetNumPixels();
+  
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*chargecam)[i];
+      MCalibrationQEPix     &pqe = (MCalibrationQEPix&)    (*qecam)    [i];
+      MBadPixelsPix         &bad = (*badcam)   [i];
+      
+      if (bad.IsBad())
+        {
+          pix.SetExcluded();
+          pqe.SetExcluded();
+          continue;
+        }
+      
+      if (IsDebug())
+        pix.SetDebug();
+    }
+
+  return kTRUE;
+}
+
+// ----------------------------------------------------------------------------------
+//  
+// Set the correct colour to the charge containers
+// 
+Int_t MCalibrationChargeCalc::Process()
+{
+
+  const MCalibrationCam::PulserColor_t col = fCalibPattern->GetPulserColor();
+  const Float_t strength = fCalibPattern->GetPulserStrength();
+  const Float_t strdiff  = TMath::Abs(strength-fStrength);
+
+  if (col == fPulserColor && strdiff < 0.05 )
+    {
+      fNumProcessed++;
+      return kTRUE;
+    }
+  
+  if (col == MCalibrationCam::kNONE)
+    return kTRUE;
+  
+
+  //
+  // Now retrieve the colour and check if not various colours have been used
+  //
+  if (!fIntensCam)
+    {
+      if (fPulserColor != MCalibrationCam::kNONE)
+        {
+          *fLog << warn << "Multiple colours used simultaneously!" ;
+          fHCam->Finalize();
+          if (fHBlindCam)
+            fHBlindCam->Finalize();
+
+          Finalize();
+
+          fHCam->ResetHists();
+          if (fHBlindCam)
+            fHBlindCam->ResetHists();
+
+          *fLog << inf << "Starting next calibration... " << flush;
+
+          fHCam->SetColor(col);
+          if (fHBlindCam)
+            fHBlindCam->SetColor(col);
+
+          fCam->SetPulserColor(col);
+          if (fBlindCam)
+            fBlindCam->SetPulserColor(col);
+        }
+    }
+  
+  fPulserColor = col;
+  fStrength    = strength;
+
+  *fLog << inf << "Found new colour ... " << flush;
+  
+  switch (col)
+    {
+    case MCalibrationCam::kGREEN: *fLog << "Green";  break;
+    case MCalibrationCam::kBLUE:  *fLog << "Blue";   break;
+    case MCalibrationCam::kUV:    *fLog << "UV";     break;
+    case MCalibrationCam::kCT1:   *fLog << "CT1";    break;
+    default: break;
+    }
+
+  *fLog << inf << " with strength: " << strength << endl;
+  
+  fHCam->SetColor(col);
+  if (fHBlindCam)
+    fHBlindCam->SetColor(col);
+
+  MCalibrationBlindCam  *blindcam  = fIntensBlind   
+    ? (MCalibrationBlindCam*)fIntensBlind->GetCam() : fBlindCam;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+
+  chargecam->SetPulserColor(col);
+
+  if (blindcam)
+    blindcam->SetPulserColor(col);
+  if (fPINDiode)
+    fPINDiode->SetColor(col);
+
+  fNumProcessed = 0;
+  
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// Return if number of executions is null.
+//
+Int_t MCalibrationChargeCalc::PostProcess()
+{
+
+  if (GetNumExecutions() < 1)
+    return kTRUE;
+
+  if (fPulserColor == MCalibrationCam::kNONE)
+    return kTRUE;
+  
+  if (fNumProcessed == 0)
+    return kTRUE;
+
+  *fLog << endl;
+
+  return Finalize();
+}
+
+// -----------------------------------------------------------------------
+//
+// Return kTRUE if fPulserColor is kNONE
+//
+// First loop over pixels, average areas and sectors, call:
+//  - FinalizePedestals() 
+//  - FinalizeCharges()
+// for every entry. Count number of valid pixels in loop and return kFALSE
+// if there are none (the "Michele check").
+//
+// Call FinalizeBadPixels()
+//
+// Call FinalizeFFactorMethod() (second and third loop over pixels and areas)
+//
+// Call FinalizeBlindCam() 
+// Call FinalizePINDiode()
+//
+// Call  FinalizeFFactorQECam() (fourth loop over pixels and areas)
+// Call  FinalizeBlindPixelQECam() (fifth loop over pixels and areas)
+// Call  FinalizePINDiodeQECam() (sixth loop over pixels and areas)
+//
+// Call  FinalizeUnsuitablePixels()
+//  
+// Call MParContainer::SetReadyToSave() for fIntensCam, fCam, fQECam, fBadPixels and 
+//                                          fBlindCam and fPINDiode if they exist
+//
+// Print out some statistics
+//
+Int_t MCalibrationChargeCalc::Finalize()
+{
+  
+  fNumHiGainSamples  =  fSignal->GetNumUsedHiGainFADCSlices();
+  fNumLoGainSamples  =  fSignal->GetNumUsedLoGainFADCSlices();
+
+  fSqrtHiGainSamples =  TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples =  TMath::Sqrt(fNumLoGainSamples);
+  
+  if (fPINDiode)
+    if (!fPINDiode->IsValid())
+      {
+        *fLog << warn << GetDescriptor() 
+              << ": MCalibrationChargePINDiode is declared not valid... no PIN Diode method! " << endl;
+        fPINDiode = NULL;
+      }
+
+  MCalibrationBlindCam  *blindcam  = fIntensBlind   
+    ? (MCalibrationBlindCam*)fIntensBlind->GetCam() : fBlindCam;
+  MCalibrationQECam     *qecam     = fIntensQE      
+    ? (MCalibrationQECam*)    fIntensQE->GetCam()   : fQECam;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  //
+  // First loop over pixels, call FinalizePedestals and FinalizeCharges
+  //
+  Int_t   nvalid      = 0;
+
+  for (Int_t pixid=0; pixid<fPedestals->GetSize(); pixid++)
+    {
+
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*chargecam)[pixid];
+      //
+      // Check if the pixel has been excluded from the fits
+      //
+      if (pix.IsExcluded())
+        continue;
+
+      MPedestalPix  &ped = (*fPedestals)[pixid];
+      MBadPixelsPix &bad = (*badcam)    [pixid];
+
+      const Int_t aidx    = (*fGeom)[pixid].GetAidx();
+
+      FinalizePedestals(ped,pix,aidx);
+
+      if (FinalizeCharges(pix,bad,"pixel  "))
+        nvalid++;
+    }
+
+  *fLog << endl;  
+  //
+  // The Michele check ...
+  //
+  if (nvalid == 0)
+  {
+    if (!fIntensCam)
+      {
+        *fLog << warn << GetDescriptor() << ": All pixels have non-valid calibration. " 
+              << "Did you forget to fill the histograms "
+              << "(filling MHCalibrationChargeCam from MExtractedSignalCam using MFillH) ? " << endl;
+        *fLog << warn << GetDescriptor() << ": Or, maybe, you have used a pedestal run " 
+              << "instead of a calibration run " << endl;
+        return kFALSE;
+      }
+  }
+
+  for (UInt_t aidx=0; aidx<fGeom->GetNumAreas(); aidx++)
+    {
+
+      const MPedestalPix     &ped = fPedestals->GetAverageArea(aidx);
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)chargecam->GetAverageArea(aidx);
+
+      FinalizePedestals(ped,pix,aidx);
+      FinalizeCharges(pix, chargecam->GetAverageBadArea(aidx),"area id");
+    }
+  
+  *fLog << endl;
+
+  for (UInt_t sector=0; sector<fGeom->GetNumSectors(); sector++)
+    {
+
+      const MPedestalPix     &ped = fPedestals->GetAverageSector(sector);
+
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)chargecam->GetAverageSector(sector);
+      FinalizePedestals(ped,pix, 0);
+    }
+  
+  *fLog << endl;
+
+  //
+  // Finalize Bad Pixels
+  // 
+  FinalizeBadPixels();
+
+  // 
+  // Finalize F-Factor method
+  //
+  if (FinalizeFFactorMethod())
+    chargecam->SetFFactorMethodValid(kTRUE);
+  else
+    {
+      *fLog << warn << "Could not calculate the photons flux from the F-Factor method " << endl;
+      chargecam->SetFFactorMethodValid(kFALSE); 
+      if (!fIntensCam)
+	return kFALSE;
+    }
+
+  *fLog << endl;
+  // 
+  // Finalize Blind Pixel
+  //
+  qecam->SetBlindPixelMethodValid(FinalizeBlindCam());
+
+  // 
+  // Finalize PIN Diode
+  //
+  qecam->SetBlindPixelMethodValid(FinalizePINDiode());
+
+  //
+  // Finalize QE Cam
+  //
+  FinalizeFFactorQECam();
+  FinalizeBlindPixelQECam();
+  FinalizePINDiodeQECam();
+  FinalizeCombinedQECam();
+
+  //
+  // Re-direct the output to an ascii-file from now on:
+  //
+  MLog *oldlog = fLog;
+  MLog asciilog;
+  if (!fOutputFile.IsNull())
+  {
+      asciilog.SetOutputFile(GetOutputFile(),kTRUE);
+      SetLogStream(&asciilog);
+  }
+
+  //
+  // Finalize calibration statistics
+  //
+  FinalizeUnsuitablePixels();
+
+  chargecam->SetReadyToSave();
+  qecam    ->SetReadyToSave();
+  badcam   ->SetReadyToSave();
+  
+  if (blindcam)
+    blindcam->SetReadyToSave();
+  if (fPINDiode)
+    fPINDiode->SetReadyToSave();
+  
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Fatal errors statistics:" << endl;  
+
+  PrintUncalibrated(MBadPixelsPix::kChargeIsPedestal,    
+                    Form("%s%2.1f%s","Signal less than ",fChargeLimit," Pedestal RMS:                "));
+  PrintUncalibrated(MBadPixelsPix::kChargeRelErrNotValid,
+                    Form("%s%2.1f%s","Signal Error bigger than ",fChargeRelErrLimit," times Mean Signal:   "));
+  PrintUncalibrated(MBadPixelsPix::kLoGainSaturation,    
+                    "Low Gain Saturation:                              ");
+  PrintUncalibrated(MBadPixelsPix::kMeanTimeInFirstBin, 
+                    Form("%s%2.1f%s","Mean Abs. Arr. Time in First ",1.," Bin(s):          "));
+  PrintUncalibrated(MBadPixelsPix::kMeanTimeInLast2Bins, 
+                    Form("%s%2.1f%s","Mean Abs. Arr. Time in Last ",2.," Bin(s):           "));
+  PrintUncalibrated(MBadPixelsPix::kHiGainOverFlow,    
+                    "Pixels with High Gain Overflow:                   ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainOverFlow,    
+                    "Pixels with Low Gain Overflow :                   ");
+
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Unreliable errors statistics:" << endl;  
+
+  PrintUncalibrated(MBadPixelsPix::kChargeSigmaNotValid, 
+                    "Signal Sigma smaller than Pedestal RMS: ");
+  PrintUncalibrated(MBadPixelsPix::kHiGainOscillating,   
+                    "Changing Hi Gain signal over time:      ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainOscillating,   
+                    "Changing Lo Gain signal over time:      ");
+  PrintUncalibrated(MBadPixelsPix::kHiGainNotFitted,     
+                    "Unsuccesful Gauss fit to the Hi Gain:   ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainNotFitted,     
+                    "Unsuccesful Gauss fit to the Lo Gain:   ");
+  PrintUncalibrated(MBadPixelsPix::kDeviatingNumPhes,    
+                    "Deviating number of phes:               ");
+  PrintUncalibrated(MBadPixelsPix::kDeviatingFFactor,    
+                    "Deviating F-Factor:                     ");
+
+  if (!fOutputFile.IsNull())
+      SetLogStream(oldlog);
+
+  return kTRUE;
+}
+
+// ----------------------------------------------------------------------------------
+//  
+// Retrieves pedestal and pedestal RMS from MPedestalPix 
+// Retrieves total entries from MPedestalCam
+// Sets pedestal*fNumHiGainSamples and pedestal*fNumLoGainSamples in MCalibrationChargePix
+// Sets pedRMS *fSqrtHiGainSamples and pedRMS *fSqrtLoGainSamples in MCalibrationChargePix
+//
+// If the flag MCalibrationPix::IsHiGainSaturation() is set, call also: 
+// - MCalibrationChargePix::CalcLoGainPedestal()
+//
+void MCalibrationChargeCalc::FinalizePedestals(const MPedestalPix &ped, MCalibrationChargePix &cal, const Int_t aidx)
+{
+  
+  //
+  // get the pedestals
+  //
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t prms   = ped.GetPedestalRms();
+  const Int_t   num    = fPedestals->GetTotalEntries();
+  
+  //
+  // RMS error set by PedCalcFromLoGain, 0 in case MPedCalcPedRun was used.
+  //
+  const Float_t prmserr = num>0 ? prms/TMath::Sqrt(2.*num) : ped.GetPedestalRmsError();
+
+  //
+  // set them in the calibration camera
+  //
+  if (cal.IsHiGainSaturation())
+    {
+      cal.SetPedestal(pedes   * fNumLoGainSamples,
+                      prms    * fSqrtLoGainSamples,
+                      prmserr * fSqrtLoGainSamples);
+      cal.CalcLoGainPedestal(fNumLoGainSamples);
+    }
+  else
+    {
+
+      cal.SetPedestal(pedes   * fNumHiGainSamples,
+                      prms    * fSqrtHiGainSamples,
+                      prmserr * fSqrtHiGainSamples);
+    }
+  
+}
+
+// ----------------------------------------------------------------------------------------------------
+//
+// Check fit results validity. Bad Pixels flags are set if:
+//
+// 1) Pixel has a mean smaller than fChargeLimit*PedRMS    ( Flag: MBadPixelsPix::kChargeIsPedestal)
+// 2) Pixel has a mean error smaller than fChargeErrLimit  ( Flag: MBadPixelsPix::kChargeErrNotValid)
+// 3) Pixel has mean smaller than fChargeRelVarLimit times its mean error 
+//                                                         ( Flag: MBadPixelsPix::kChargeRelErrNotValid)
+// 4) Pixel has a sigma bigger than its Pedestal RMS       ( Flag: MBadPixelsPix::kChargeSigmaNotValid )
+// 
+// Further returns if flags: MBadPixelsPix::kUnsuitableRun is set
+// 
+// Calls MCalibrationChargePix::CalcReducedSigma() and sets flag:  MBadPixelsPix::kChargeIsPedestal 
+//       and returns kFALSE if not succesful. 
+// 
+// Calls MCalibrationChargePix::CalcFFactor() and sets flag: MBadPixelsPix::kDeviatingNumPhes) 
+//       and returns kFALSE if not succesful.
+//
+// Calls MCalibrationChargePix::CalcConvFFactor()and sets flag: MBadPixelsPix::kDeviatingNumPhes) 
+//       and returns kFALSE if not succesful.
+//
+Bool_t MCalibrationChargeCalc::FinalizeCharges(MCalibrationChargePix &cal, MBadPixelsPix &bad, const char* what)
+{
+
+  if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+    return kFALSE;
+
+  if (cal.GetMean() < fChargeLimit*cal.GetPedRms())
+    {
+      *fLog << warn
+            << Form("Fitted Charge: %5.2f < %2.1f",cal.GetMean(),fChargeLimit)
+            << Form(" * Pedestal RMS %5.2f in %s%3i",cal.GetPedRms(),what,cal.GetPixId()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeIsPedestal);
+    }
+  
+   if (cal.GetMean() < fChargeRelErrLimit*cal.GetMeanErr()) 
+    {
+      *fLog << warn
+            << Form("Fitted Charge: %4.2f < %2.1f",cal.GetMean(),fChargeRelErrLimit)
+            << Form(" * its error %4.2f in %s%3i",cal.GetMeanErr(),what,cal.GetPixId()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeRelErrNotValid );
+    }
+
+  if (cal.GetSigma() < cal.GetPedRms())
+    {
+      *fLog << warn
+            << Form("Sigma of Fitted Charge: %6.2f <",cal.GetSigma())
+	    << Form(" Ped. RMS=%5.2f in %s%3i",cal.GetPedRms(),what,cal.GetPixId()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeSigmaNotValid );
+      return kFALSE;
+    }
+
+  if (!cal.CalcReducedSigma())
+    {
+      *fLog << warn 
+            << Form("Could not calculate the reduced sigma in %s:               ",what)
+            << Form("         %4i",cal.GetPixId()) 
+            << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeSigmaNotValid );
+      return kFALSE;
+    }
+
+  if (!cal.CalcFFactor())
+    {
+      *fLog << warn 
+            << Form("Could not calculate the F-Factor in %s:                    ",what)
+            << Form("         %4i",cal.GetPixId()) 
+            << endl;
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      return kFALSE;
+    }
+
+  if (cal.GetPheFFactorMethod() < 0.)
+    {
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      bad.SetUnsuitable(MBadPixelsPix::kUnsuitableRun);
+      cal.SetFFactorMethodValid(kFALSE);
+      return kFALSE;
+    }
+
+  if (!cal.CalcConvFFactor())
+    {
+      *fLog << warn 
+            << Form("Could not calculate the Conv. FADC counts to Phes in %s:  ",what)
+            << Form("         %4i",cal.GetPixId()) 
+            << endl;
+      bad.SetUncalibrated(MBadPixelsPix::kDeviatingNumPhes);
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+
+
+// -----------------------------------------------------------------------------------
+//
+// Sets pixel to MBadPixelsPix::kUnsuitableRun, if one of the following flags is set:
+// - MBadPixelsPix::kChargeIsPedestal
+// - MBadPixelsPix::kChargeRelErrNotValid 
+// - MBadPixelsPix::kMeanTimeInFirstBin 
+// - MBadPixelsPix::kMeanTimeInLast2Bins 
+// - MBadPixelsPix::kDeviatingNumPhes
+// - MBadPixelsPix::kHiGainOverFlow
+// - MBadPixelsPix::kLoGainOverFlow
+//
+// - Call MCalibrationPix::SetExcluded() for the bad pixels
+//
+// Sets pixel to MBadPixelsPix::kUnreliableRun, if one of the following flags is set:
+// - MBadPixelsPix::kChargeSigmaNotValid 
+//
+void MCalibrationChargeCalc::FinalizeBadPixels()
+{
+  
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      
+      MBadPixelsPix    &bad    = (*badcam)   [i];
+      MCalibrationPix  &pix    = (*chargecam)[i];
+
+      if (IsCheckDeadPixels())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kChargeIsPedestal))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun   );
+ 
+          if (bad.IsUncalibrated( MBadPixelsPix::kChargeErrNotValid ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+
+          if (bad.IsUncalibrated( MBadPixelsPix::kChargeRelErrNotValid ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+        }
+      
+      if (IsCheckExtractionWindow())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kMeanTimeInFirstBin ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+          
+          if (bad.IsUncalibrated( MBadPixelsPix::kMeanTimeInLast2Bins ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+        }
+      
+      if (IsCheckDeviatingBehavior())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kDeviatingNumPhes ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+        }
+      
+      if (IsCheckHistOverflow())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kHiGainOverFlow   ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+          
+          if (bad.IsUncalibrated( MBadPixelsPix::kLoGainOverFlow   ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+        }
+      
+      if (bad.IsUnsuitable(   MBadPixelsPix::kUnsuitableRun    ))
+        pix.SetExcluded();
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kChargeSigmaNotValid ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+//
+// First loop: Calculate a mean and mean RMS of photo-electrons per area index 
+//             Include only pixels which are not MBadPixelsPix::kUnsuitableRun nor 
+//             MBadPixelsPix::kChargeSigmaNotValid (see FinalizeBadPixels()) and set 
+//             MCalibrationChargePix::SetFFactorMethodValid(kFALSE) in that case.
+//              
+// Second loop: Get mean number of photo-electrons and its RMS including 
+//              only pixels with flag MCalibrationChargePix::IsFFactorMethodValid() 
+//              and further exclude those deviating by more than fPheErrLimit mean 
+//              sigmas from the mean (obtained in first loop). Set 
+//              MBadPixelsPix::kDeviatingNumPhes if excluded.
+//
+//              For the suitable pixels with flag MBadPixelsPix::kChargeSigmaNotValid 
+//              set the number of photo-electrons as the mean number of photo-electrons
+//              calculated in that area index.
+// 
+//              Set weighted mean and variance of photo-electrons per area index in: 
+//              average area pixels of MCalibrationChargeCam (obtained from: 
+//              MCalibrationChargeCam::GetAverageArea() )
+// 
+//              Set weighted mean  and variance of photo-electrons per sector in:
+//              average sector pixels of MCalibrationChargeCam (obtained from: 
+//              MCalibrationChargeCam::GetAverageSector() )
+// 
+//
+// Third loop: Set mean number of photo-electrons and its RMS in the pixels
+//             only excluded as: MBadPixelsPix::kChargeSigmaNotValid 
+// 
+Bool_t MCalibrationChargeCalc::FinalizeFFactorMethod()
+{
+
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  TArrayF lowlim        (nareas);
+  TArrayF upplim        (nareas);
+  TArrayD areavars      (nareas);
+  TArrayD areaweights   (nareas);
+  TArrayD sectorweights (nsectors);
+  TArrayD areaphes      (nareas);
+  TArrayD sectorphes    (nsectors);
+  TArrayI numareavalid  (nareas);
+  TArrayI numsectorvalid(nsectors);
+
+  //
+  // First loop: Get mean number of photo-electrons and the RMS
+  //             The loop is only to recognize later pixels with very deviating numbers
+  //
+  MHCamera camphes(*fGeom,"Camphes","Phes in Camera");
+
+  for (Int_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*chargecam)[i];
+      MBadPixelsPix         &bad =                         (*badcam)[i];
+      
+      if (!pix.IsFFactorMethodValid())
+        continue;
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          pix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+
+      if (bad.IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid))
+        continue;
+      
+      const Float_t nphe  = pix.GetPheFFactorMethod();
+      const Int_t   aidx  = (*fGeom)[i].GetAidx();
+
+      camphes.Fill(i,nphe);
+      camphes.SetUsed(i);
+
+      areaphes    [aidx] += nphe;
+      areavars    [aidx] += nphe*nphe;
+      numareavalid[aidx] ++;
+    } 
+
+  for (Int_t i=0; i<nareas; i++)
+    {
+      if (numareavalid[i] == 0)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid number of photo-electrons found "
+                << "in area index: " << i << endl;
+          continue;
+        }
+
+      if (numareavalid[i] == 1)
+        areavars[i] = 0.;
+      else if (numareavalid[i] == 0)
+        {
+          areaphes[i]    = -1.;
+          areaweights[i] = -1.;
+        }
+      else
+        {
+          areavars[i] = (areavars[i] - areaphes[i]*areaphes[i]/numareavalid[i]) / (numareavalid[i]-1);
+          areaphes[i] = areaphes[i] / numareavalid[i];
+        }
+      
+      if (areavars[i] < 0.)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid variance of photo-electrons found "
+                << "in area index: " << i << endl;
+          continue;
+        }
+      
+      lowlim  [i] = areaphes[i] - fPheErrLimit*TMath::Sqrt(areavars[i]);
+      upplim  [i] = areaphes[i] + fPheErrLimit*TMath::Sqrt(areavars[i]);
+
+      TH1D *hist = camphes.ProjectionS(TArrayI(),TArrayI(1,&i),"_py",100);
+      hist->Fit("gaus","Q");
+      const Float_t mean  = hist->GetFunction("gaus")->GetParameter(1);
+      const Float_t sigma = hist->GetFunction("gaus")->GetParameter(2);
+      const Int_t   ndf   = hist->GetFunction("gaus")->GetNDF();
+
+      if (IsDebug())
+        hist->DrawClone();
+
+      if (ndf < 2)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the number of photo-electrons " 
+                << "in the camera with area index: " << i << endl;
+          *fLog << warn << GetDescriptor() << ": Number of dof.: " << ndf << " is smaller than 2 " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;
+          delete hist;
+          continue;
+        }
+      
+      const Double_t prob = hist->GetFunction("gaus")->GetProb();
+
+      if (prob < 0.001)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the number of photo-electrons " 
+                << "in the camera with area index: " << i << endl;
+          *fLog << warn << GetDescriptor() << ": Fit probability " << prob 
+                << " is smaller than 0.001 " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;
+          delete hist;
+          continue;
+        }
+      
+      if (mean < 0.)
+        {
+          *fLog << inf << GetDescriptor() << ": Fitted mean number of photo-electrons " 
+                << "with area idx " << i << ": " << mean << " is smaller than 0. " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;          
+          delete hist;
+          continue;
+        }
+      
+      *fLog << inf << GetDescriptor() << ": Mean number of phes with area idx " << i << ": "
+            << Form("%7.2f+-%6.2f",mean,sigma) << endl;
+
+      lowlim  [i] = mean  - fPheErrLimit*sigma;
+      upplim  [i] = mean  + fPheErrLimit*sigma;
+
+      delete hist;
+    }
+
+  *fLog << endl;
+
+  numareavalid.Reset();
+  areaphes    .Reset();
+  areavars    .Reset();
+  //
+  // Second loop: Get mean number of photo-electrons and its RMS excluding 
+  //              pixels deviating by more than fPheErrLimit sigma. 
+  //              Set the conversion factor FADC counts to photo-electrons
+  // 
+  for (Int_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*chargecam)[i];
+
+      if (!pix.IsFFactorMethodValid())
+        continue;
+
+      MBadPixelsPix         &bad =           (*badcam)[i];
+
+      if (bad.IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid))
+        continue;
+
+      const Float_t nvar  = pix.GetPheFFactorMethodVar();
+      if (nvar <= 0.)
+        {
+          pix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+      
+      const Int_t   aidx   = (*fGeom)[i].GetAidx();
+      const Int_t   sector = (*fGeom)[i].GetSector();
+      const Float_t area   = (*fGeom)[i].GetA();
+      const Float_t nphe   = pix.GetPheFFactorMethod();
+
+      if ( nphe < lowlim[aidx] || nphe > upplim[aidx] )
+        {
+          *fLog << warn << "Number of phes: "
+                << Form("%7.2f out of %3.1f sigma limit: ",nphe,fPheErrLimit)
+                << Form("[%7.2f,%7.2f] pixel%4i",lowlim[aidx],upplim[aidx],i) << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingNumPhes );
+          if (IsCheckDeviatingBehavior())
+            {
+              bad.SetUnsuitable  ( MBadPixelsPix::kUnreliableRun    );
+              //              pix.SetFFactorMethodValid(kFALSE);
+            }
+          continue;
+        }
+      
+      areaweights   [aidx]   += nphe*nphe;
+      areaphes      [aidx]   += nphe;
+      numareavalid  [aidx]   ++;
+
+      if (aidx == 0)
+        fNumInnerFFactorMethodUsed++;
+
+      sectorweights [sector] += nphe*nphe/area/area;
+      sectorphes    [sector] += nphe/area;
+      numsectorvalid[sector] ++;
+    } 
+
+  *fLog << endl;
+
+  for (Int_t aidx=0; aidx<nareas; aidx++)
+    {
+
+      MCalibrationChargePix &apix = (MCalibrationChargePix&)chargecam->GetAverageArea(aidx);
+
+      if (numareavalid[aidx] == 1)
+        areaweights[aidx] = 0.;
+      else if (numareavalid[aidx] == 0)
+        {
+          areaphes[aidx]    = -1.;
+          areaweights[aidx] = -1.;
+        }
+      else
+        {
+          areaweights[aidx] = (areaweights[aidx] - areaphes[aidx]*areaphes[aidx]/numareavalid[aidx])
+                            / (numareavalid[aidx]-1);
+          areaphes[aidx]    /=  numareavalid[aidx];
+        }
+      
+      if (areaweights[aidx] < 0. || areaphes[aidx] <= 0.)
+        {
+          *fLog << warn << GetDescriptor() 
+                << ": Mean number phes from area index " << aidx << " could not be calculated: "
+                << " Mean: "  << areaphes[aidx] 
+                << " Variance: " << areaweights[aidx]    << endl;
+          apix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+      
+      *fLog << inf << GetDescriptor() 
+            << ": Average total phes for area idx " << aidx << ": "
+            << Form("%7.2f +- %6.2f",areaphes[aidx],TMath::Sqrt(areaweights[aidx])) << endl;
+                    
+      apix.SetPheFFactorMethod   ( areaphes[aidx] );
+      apix.SetPheFFactorMethodVar( areaweights[aidx] / numareavalid[aidx] );      
+      apix.SetFFactorMethodValid ( kTRUE );
+
+    }
+
+  *fLog << endl;
+
+  for (Int_t sector=0; sector<nsectors; sector++)
+    {
+
+      if (numsectorvalid[sector] == 1)
+        sectorweights[sector] = 0.;
+      else if (numsectorvalid[sector] == 0)
+        {
+          sectorphes[sector]    = -1.;
+          sectorweights[sector] = -1.;
+        }
+      else
+        {
+          sectorweights[sector] = (sectorweights[sector] 
+                                   - sectorphes[sector]*sectorphes[sector]/numsectorvalid[sector]
+                                  ) 
+                                / (numsectorvalid[sector]-1.);
+          sectorphes[sector]     /=  numsectorvalid[sector];
+        }
+      
+      MCalibrationChargePix &spix = (MCalibrationChargePix&)chargecam->GetAverageSector(sector);
+
+      if (sectorweights[sector] < 0. || sectorphes[sector] <= 0.)
+        {
+          *fLog << warn << GetDescriptor() 
+                <<": Mean number phes/area for sector " << sector << " could not be calculated: "
+                << " Mean: "  << sectorphes[sector] 
+                << " Variance: "             << sectorweights[sector]    << endl;
+          spix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+
+      *fLog << inf << GetDescriptor() 
+            << ": Avg number phes/mm^2 in sector " << sector << ": "
+            << Form("%5.3f+-%4.3f",sectorphes[sector],TMath::Sqrt(sectorweights[sector]))
+            << endl;
+
+      spix.SetPheFFactorMethod   ( sectorphes[sector] );
+      spix.SetPheFFactorMethodVar( sectorweights[sector] / numsectorvalid[sector]);      
+      spix.SetFFactorMethodValid ( kTRUE );
+
+    }
+
+  //
+  // Third loop: Set mean number of photo-electrons and its RMS in the pixels
+  //             only excluded as: MBadPixelsPix::kChargeSigmaNotValid 
+  // 
+  for (Int_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*chargecam)[i];
+      MBadPixelsPix         &bad =                         (*badcam)[i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+      
+      if (bad.IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid))
+        {
+          const Int_t            aidx = (*fGeom)[i].GetAidx();
+          MCalibrationChargePix &apix = (MCalibrationChargePix&)chargecam->GetAverageArea(aidx);
+
+          pix.SetPheFFactorMethod   ( apix.GetPheFFactorMethod()    );
+          pix.SetPheFFactorMethodVar( apix.GetPheFFactorMethodVar() );
+
+          if (!pix.CalcConvFFactor())
+            {
+              *fLog << warn << GetDescriptor() 
+                    << ": Could not calculate the Conv. FADC counts to Phes in pixel:  "
+                    << Form("         %4i",pix.GetPixId()) 
+                    << endl;
+              bad.SetUncalibrated( MBadPixelsPix::kDeviatingNumPhes );
+              if (IsCheckDeviatingBehavior())
+                bad.SetUnsuitable  ( MBadPixelsPix::kUnsuitableRun    );
+            }
+
+        }
+    }
+  
+  return kTRUE;
+}
+
+
+
+// ------------------------------------------------------------------------
+//
+// Returns kFALSE if pointer to MCalibrationBlindCam is NULL
+//
+// The check returns kFALSE if:
+//
+// 1) fLambda and fLambdaCheck are separated relatively to each other by more than fLambdaCheckLimit
+// 2) BlindPixel has an fLambdaErr greater than fLambdaErrLimit
+// 
+// Calls:
+// - MCalibrationBlindPix::CalcFluxInsidePlexiglass()
+//
+Bool_t MCalibrationChargeCalc::FinalizeBlindCam()
+{
+
+  MCalibrationBlindCam  *blindcam = fIntensBlind   
+    ? (MCalibrationBlindCam*)fIntensBlind->GetCam() : fBlindCam;
+
+  if (!blindcam)
+    return kFALSE;  
+
+  Int_t   nvalid  = 0;
+
+  for (Int_t i=0; i<blindcam->GetSize(); i++)
+    {
+      
+      MCalibrationBlindPix &blindpix = (MCalibrationBlindPix&)(*blindcam)[i];
+
+      if (!blindpix.IsValid())
+        continue;
+      
+      const Float_t lambda      = blindpix.GetLambda();
+      const Float_t lambdaerr   = blindpix.GetLambdaErr();
+      const Float_t lambdacheck = blindpix.GetLambdaCheck();
+
+      if (2.*(lambdacheck-lambda)/(lambdacheck+lambda) > fLambdaCheckLimit)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%4.2f%s%4.2f%s%4.2f%s%2i",": Lambda: ",lambda," and Lambda-Check: ",
+                    lambdacheck," differ by more than ",fLambdaCheckLimit," in the Blind Pixel Nr.",i)
+                << endl;
+          blindpix.SetValid(kFALSE);
+          continue;
+        }
+      
+      if (lambdaerr > fLambdaErrLimit) 
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%4.2f%s%4.2f%s%2i",": Error of Fitted Lambda: ",lambdaerr," is greater than ",
+                        fLambdaErrLimit," in Blind Pixel Nr.",i) << endl;
+          blindpix.SetValid(kFALSE);
+          continue;
+        }
+      
+      if (!blindpix.CalcFluxInsidePlexiglass())
+        {
+          *fLog << warn << "Could not calculate the flux of photons from Blind Pixel Nr." << i << endl;
+          blindpix.SetValid(kFALSE);
+          continue;
+        }
+      
+      nvalid++;
+    }
+
+  if (!nvalid)
+    return kFALSE;
+  
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns kFALSE if pointer to MCalibrationChargePINDiode is NULL
+//
+// The check returns kFALSE if:
+//
+// 1) PINDiode has a fitted charge smaller than fChargeLimit*PedRMS
+// 2) PINDiode has a fit error smaller than fChargeErrLimit
+// 3) PINDiode has a fitted charge smaller its fChargeRelErrLimit times its charge error
+// 4) PINDiode has a charge sigma smaller than its Pedestal RMS
+// 
+// Calls:
+// - MCalibrationChargePINDiode::CalcFluxOutsidePlexiglass()
+//
+Bool_t MCalibrationChargeCalc::FinalizePINDiode()
+{
+
+  if (!fPINDiode)
+    return kFALSE;  
+
+  if (fPINDiode->GetMean() < fChargeLimit*fPINDiode->GetPedRms())
+    {
+      *fLog << warn << GetDescriptor() << ": Fitted Charge is smaller than "
+            << fChargeLimit << " Pedestal RMS in PINDiode " << endl;
+      return kFALSE;
+    }
+  
+  if (fPINDiode->GetMeanErr() < fChargeErrLimit) 
+    {
+      *fLog << warn << GetDescriptor() << ": Error of Fitted Charge is smaller than "
+            << fChargeErrLimit << " in PINDiode " << endl;
+      return kFALSE;
+    }
+      
+  if (fPINDiode->GetMean() < fChargeRelErrLimit*fPINDiode->GetMeanErr()) 
+    {
+      *fLog << warn << GetDescriptor() << ": Fitted Charge is smaller than "
+            << fChargeRelErrLimit << "* its error in PINDiode " << endl;
+      return kFALSE;
+    }
+      
+  if (fPINDiode->GetSigma() < fPINDiode->GetPedRms())
+    {
+      *fLog << warn << GetDescriptor() 
+            << ": Sigma of Fitted Charge smaller than Pedestal RMS in PINDiode " << endl;
+      return kFALSE;
+    }
+
+
+  if (!fPINDiode->CalcFluxOutsidePlexiglass())
+    {
+      *fLog << warn << "Could not calculate the flux of photons from the PIN Diode, "
+            << "will skip PIN Diode Calibration " << endl;
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Calculate the average number of photons outside the plexiglass with the 
+// formula: 
+// 
+// av.Num.photons(area index) = av.Num.Phes(area index) 
+//                            / MCalibrationQEPix::GetDefaultQE(fPulserColor) 
+//                            / MCalibrationQEPix::GetPMTCollectionEff()
+//                            / MCalibrationQEPix::GetLightGuidesEff(fPulserColor)
+//                            / MCalibrationQECam::GetPlexiglassQE()
+//
+// Calculate the variance on the average number of photons assuming that the error on the 
+// Quantum efficiency is reduced by the number of used inner pixels, but the rest of the 
+// values keeps it ordinary error since it is systematic.
+//
+// Loop over pixels: 
+//
+// - Continue, if not MCalibrationChargePix::IsFFactorMethodValid() and set:
+//                    MCalibrationQEPix::SetFFactorMethodValid(kFALSE,fPulserColor)
+//
+// - Call MCalibrationChargePix::CalcMeanFFactor(av.Num.photons) and set: 
+//        MCalibrationQEPix::SetFFactorMethodValid(kFALSE,fPulserColor) if not succesful
+//
+// - Calculate the quantum efficiency with the formula:
+// 
+//   QE = ( Num.Phes / av.Num.photons ) * MGeomCam::GetPixRatio()
+//
+// - Set QE in MCalibrationQEPix::SetQEFFactor ( QE, fPulserColor );
+//
+// - Set Variance of QE in  MCalibrationQEPix::SetQEFFactorVar ( Variance, fPulserColor );
+// - Set bit MCalibrationQEPix::SetFFactorMethodValid(kTRUE,fPulserColor) 
+//
+// - Call MCalibrationQEPix::UpdateFFactorMethod()
+//
+void MCalibrationChargeCalc::FinalizeFFactorQECam()
+{
+
+  if (fNumInnerFFactorMethodUsed < 2)
+    {
+      *fLog << warn << GetDescriptor() 
+            << ": Could not calculate F-Factor Method: Less than 2 inner pixels valid! " << endl;
+      return;
+    }
+  
+  MCalibrationQECam     *qecam     = fIntensQE      
+    ? (MCalibrationQECam*)    fIntensQE->GetCam()   : fQECam;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  MCalibrationChargePix &avpix = (MCalibrationChargePix&)chargecam->GetAverageArea(0);
+  MCalibrationQEPix     &qepix = (MCalibrationQEPix&)    qecam->GetAverageArea(0);
+
+  const Float_t avphotons   = avpix.GetPheFFactorMethod()       
+                           / qepix.GetDefaultQE(fPulserColor) 
+                           / qepix.GetPMTCollectionEff()
+                           / qepix.GetLightGuidesEff(fPulserColor)
+                           / qecam->GetPlexiglassQE();
+
+  const Float_t avphotrelvar = avpix.GetPheFFactorMethodRelVar() 
+                            + qepix.GetDefaultQERelVar(fPulserColor) / fNumInnerFFactorMethodUsed
+                            + qepix.GetPMTCollectionEffRelVar()
+                            + qepix.GetLightGuidesEffRelVar(fPulserColor)
+                            + qecam->GetPlexiglassQERelVar();
+
+  const UInt_t nareas   = fGeom->GetNumAreas();
+
+  //
+  // Set the results in the MCalibrationChargeCam
+  //
+  chargecam->SetNumPhotonsFFactorMethod (avphotons);
+
+  if (avphotrelvar > 0.)
+    chargecam->SetNumPhotonsFFactorMethodErr(TMath::Sqrt( avphotrelvar * avphotons * avphotons));  
+
+  TArrayF lowlim           (nareas);
+  TArrayF upplim           (nareas);
+  TArrayD avffactorphotons (nareas);
+  TArrayD avffactorphotvar (nareas);
+  TArrayI numffactor       (nareas);
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+
+  MHCamera camffactor(*fGeom,"Camffactor","F-Factor in Camera");
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*chargecam)[i];
+      MCalibrationQEPix     &qepix = (MCalibrationQEPix&)    (*qecam)    [i];
+      MBadPixelsPix         &bad   =                         (*badcam)   [i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+
+      const Float_t photons = avphotons / fGeom->GetPixRatio(i);
+      const Float_t qe      = pix.GetPheFFactorMethod() / photons ;
+
+      const Float_t qerelvar = avphotrelvar +  pix.GetPheFFactorMethodRelVar();
+
+      qepix.SetQEFFactor    ( qe            , fPulserColor );
+      qepix.SetQEFFactorVar ( qerelvar*qe*qe, fPulserColor );      
+      qepix.SetFFactorMethodValid(  kTRUE   , fPulserColor );
+
+      if (!qepix.UpdateFFactorMethod( qecam->GetPlexiglassQE() ))
+        *fLog << warn << GetDescriptor() 
+              << ": Cannot update Quantum efficiencies with the F-Factor Method" << endl;
+
+      //
+      // The following pixels are those with deviating sigma, but otherwise OK, 
+      // probably those with stars during the pedestal run, but not the cal. run.
+      //
+      if (!pix.CalcMeanFFactor( photons , avphotrelvar ))
+        {
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingFFactor );
+          if (IsCheckDeviatingBehavior())
+            bad.SetUnsuitable  ( MBadPixelsPix::kUnreliableRun    );
+          continue;
+        }
+
+      const Int_t aidx = (*fGeom)[i].GetAidx();
+      const Float_t ffactor = pix.GetMeanFFactorFADC2Phot();
+
+      camffactor.Fill(i,ffactor);
+      camffactor.SetUsed(i);
+
+      avffactorphotons[aidx] += ffactor;
+      avffactorphotvar[aidx] += ffactor*ffactor;
+      numffactor[aidx]++;
+    }
+
+  for (UInt_t i=0; i<nareas; i++)
+    {
+
+      if (numffactor[i] == 0)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid total F-Factor found "
+                << "in area index: " << i << endl;
+          continue;
+        }
+
+      avffactorphotvar[i] = (avffactorphotvar[i] - avffactorphotons[i]*avffactorphotons[i]/numffactor[i]) 
+                          / (numffactor[i]-1.);
+      avffactorphotons[i] = avffactorphotons[i] / numffactor[i];
+
+      if (avffactorphotvar[i] < 0.)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid variance of total F-Factor found "
+                << "in area index: " << i << endl;
+          continue;
+        }
+
+      lowlim  [i] = 1.;   // Lowest known F-Factor of a PMT
+      upplim  [i] = avffactorphotons[i] + fFFactorErrLimit*TMath::Sqrt(avffactorphotvar[i]);
+
+      TArrayI area(1);
+      area[0] = i;
+
+      TH1D *hist = camffactor.ProjectionS(TArrayI(),area,"_py",100);
+      hist->Fit("gaus","Q");
+      const Float_t mean  = hist->GetFunction("gaus")->GetParameter(1);
+      const Float_t sigma = hist->GetFunction("gaus")->GetParameter(2);
+      const Int_t   ndf   = hist->GetFunction("gaus")->GetNDF();
+
+      if (IsDebug())
+        camffactor.DrawClone();
+
+      if (ndf < 2)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the F-Factor " 
+                << "in the camera with area index: " << i << endl;
+          *fLog << warn << GetDescriptor() << ": Number of dof.: " << ndf << " is smaller than 2 " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;
+          delete hist;
+          continue;
+        }
+      
+      const Double_t prob = hist->GetFunction("gaus")->GetProb();
+
+      if (prob < 0.001)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the F-Factor " 
+                << "in the camera with area index: " << i << endl;
+          *fLog << warn << GetDescriptor() << ": Fit probability " << prob 
+                << " is smaller than 0.001 " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;
+          delete hist;
+          continue;
+        }
+
+      *fLog << inf << GetDescriptor() << ": Mean F-Factor " 
+          << "with area index #" << i << ": "
+            << Form("%4.2f+-%4.2f",mean,sigma) << endl;
+
+      lowlim  [i] = 1.;
+      upplim  [i] = mean  + fFFactorErrLimit*sigma;
+
+      delete hist;
+    }
+  
+  *fLog << endl;
+  
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*chargecam)[i];
+      MBadPixelsPix         &bad   =                         (*badcam)   [i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+      
+      const Float_t ffactor = pix.GetMeanFFactorFADC2Phot();
+      const Int_t   aidx   = (*fGeom)[i].GetAidx();
+
+      if ( ffactor < lowlim[aidx] || ffactor > upplim[aidx] )
+        {
+          *fLog << warn << "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 );
+          if (IsCheckDeviatingBehavior())
+            bad.SetUnsuitable  ( MBadPixelsPix::kUnreliableRun    );
+        }
+    }
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*chargecam)[i];
+      MCalibrationQEPix     &qepix = (MCalibrationQEPix&)    (*qecam)    [i];
+      MBadPixelsPix         &bad   =                         (*badcam)   [i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          qepix.SetFFactorMethodValid(kFALSE,fPulserColor);
+          pix.SetFFactorMethodValid(kFALSE);
+          pix.SetExcluded();
+          continue;
+        }
+    }
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Loop over pixels: 
+//
+// - Continue, if not MCalibrationBlindPix::IsFluxInsidePlexiglassAvailable() and set:
+//                    MCalibrationQEPix::SetBlindPixelMethodValid(kFALSE,fPulserColor)
+//
+// - Calculate the quantum efficiency with the formula:
+// 
+//   QE =  Num.Phes / MCalibrationBlindPix::GetFluxInsidePlexiglass() 
+//        / MGeomPix::GetA() * MCalibrationQECam::GetPlexiglassQE()
+//
+// - Set QE in MCalibrationQEPix::SetQEBlindPixel ( QE, fPulserColor );
+// - Set Variance of QE in  MCalibrationQEPix::SetQEBlindPixelVar ( Variance, fPulserColor );
+// - Set bit MCalibrationQEPix::SetBlindPixelMethodValid(kTRUE,fPulserColor) 
+//
+// - Call MCalibrationQEPix::UpdateBlindPixelMethod()
+//
+void MCalibrationChargeCalc::FinalizeBlindPixelQECam()
+{
+
+
+  MCalibrationBlindCam  *blindcam  = fIntensBlind
+    ? (MCalibrationBlindCam*) fIntensBlind->GetCam(): fBlindCam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+  MCalibrationQECam     *qecam     = fIntensQE      
+    ? (MCalibrationQECam*)    fIntensQE->GetCam()   : fQECam;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+
+  if (!blindcam)
+    return;
+
+  //
+  // Set the results in the MCalibrationChargeCam
+  //
+  if (!blindcam || !(blindcam->IsFluxInsidePlexiglassAvailable()))
+    {
+  
+      const Float_t photons = blindcam->GetFluxInsidePlexiglass() * (*fGeom)[0].GetA()
+                           / qecam->GetPlexiglassQE();
+      chargecam->SetNumPhotonsBlindPixelMethod(photons);
+          
+      const Float_t photrelvar = blindcam->GetFluxInsidePlexiglassRelVar() 
+                              + qecam->GetPlexiglassQERelVar();
+ 
+      if (photrelvar > 0.)
+        chargecam->SetNumPhotonsBlindPixelMethodErr(TMath::Sqrt( photrelvar * photons * photons));  
+    }
+  
+  //
+  //  With the knowledge of the overall photon flux, calculate the 
+  //  quantum efficiencies after the Blind Pixel and PIN Diode method
+  //
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationQEPix     &qepix = (MCalibrationQEPix&)    (*qecam)    [i];
+      
+      if (!blindcam || !(blindcam->IsFluxInsidePlexiglassAvailable()))
+        {
+          qepix.SetBlindPixelMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+
+      MBadPixelsPix         &bad   =                         (*badcam)   [i];
+
+      if (bad.IsUnsuitable (MBadPixelsPix::kUnsuitableRun))
+        {
+          qepix.SetBlindPixelMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*chargecam)[i];
+      MGeomPix              &geo   =                         (*fGeom)    [i];
+
+      const Float_t qe        = pix.GetPheFFactorMethod() 
+                             / blindcam->GetFluxInsidePlexiglass() 
+                             / geo.GetA() 
+                             * qecam->GetPlexiglassQE();
+
+      const Float_t qerelvar = blindcam->GetFluxInsidePlexiglassRelVar() 
+                               + qecam->GetPlexiglassQERelVar()
+                               + pix.GetPheFFactorMethodRelVar();
+
+      qepix.SetQEBlindPixel    ( qe            , fPulserColor );
+      qepix.SetQEBlindPixelVar ( qerelvar*qe*qe, fPulserColor );      
+      qepix.SetBlindPixelMethodValid(  kTRUE   , fPulserColor );
+
+      if (!qepix.UpdateBlindPixelMethod( qecam->GetPlexiglassQE()))
+        *fLog << warn << GetDescriptor() 
+              << ": Cannot update Quantum efficiencies with the Blind Pixel Method" << endl;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Loop over pixels: 
+//
+// - Continue, if not MCalibrationChargePINDiode::IsFluxOutsidePlexiglassAvailable() and set:
+//                    MCalibrationQEPix::SetPINDiodeMethodValid(kFALSE,fPulserColor)
+//
+// - Calculate the quantum efficiency with the formula:
+// 
+//   QE =  Num.Phes / MCalibrationChargePINDiode::GetFluxOutsidePlexiglass() / MGeomPix::GetA()
+//
+// - Set QE in MCalibrationQEPix::SetQEPINDiode ( QE, fPulserColor );
+// - Set Variance of QE in  MCalibrationQEPix::SetQEPINDiodeVar ( Variance, fPulserColor );
+// - Set bit MCalibrationQEPix::SetPINDiodeMethodValid(kTRUE,fPulserColor) 
+//
+// - Call MCalibrationQEPix::UpdatePINDiodeMethod()
+//
+void MCalibrationChargeCalc::FinalizePINDiodeQECam()
+{
+  
+  const UInt_t npixels  = fGeom->GetNumPixels();
+
+  MCalibrationQECam     *qecam     = fIntensQE      
+    ? (MCalibrationQECam*)    fIntensQE->GetCam()   : fQECam;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  if (!fPINDiode)
+    return;
+
+  //
+  //  With the knowledge of the overall photon flux, calculate the 
+  //  quantum efficiencies after the PIN Diode method
+  //
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationQEPix     &qepix = (MCalibrationQEPix&)    (*qecam)    [i];
+
+      if (!fPINDiode)
+        {
+          qepix.SetPINDiodeMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      if (!fPINDiode->IsFluxOutsidePlexiglassAvailable())
+        {
+          qepix.SetPINDiodeMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+
+      MBadPixelsPix         &bad   =                         (*badcam)   [i];
+
+      if (!bad.IsUnsuitable (MBadPixelsPix::kUnsuitableRun))
+        {
+          qepix.SetPINDiodeMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*chargecam)[i];
+      MGeomPix              &geo =                           (*fGeom)    [i];
+      
+      const Float_t qe       =  pix.GetPheFFactorMethod() 
+                               / fPINDiode->GetFluxOutsidePlexiglass() 
+                               / geo.GetA();
+
+      const Float_t qerelvar = fPINDiode->GetFluxOutsidePlexiglassRelVar() + pix.GetPheFFactorMethodRelVar();
+
+      qepix.SetQEPINDiode    ( qe            , fPulserColor );
+      qepix.SetQEPINDiodeVar ( qerelvar*qe*qe, fPulserColor );      
+      qepix.SetPINDiodeMethodValid(  kTRUE   , fPulserColor );
+
+      if (!qepix.UpdatePINDiodeMethod())
+        *fLog << warn << GetDescriptor() 
+              << ": Cannot update Quantum efficiencies with the PIN Diode Method" << endl;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Loop over pixels: 
+//
+// - Call MCalibrationQEPix::UpdateCombinedMethod()
+//
+void MCalibrationChargeCalc::FinalizeCombinedQECam()
+{
+  
+  const UInt_t npixels  = fGeom->GetNumPixels();
+
+  MCalibrationQECam     *qecam     = fIntensQE      
+    ? (MCalibrationQECam*)    fIntensQE->GetCam()   : fQECam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationQEPix     &qepix = (MCalibrationQEPix&)    (*qecam)    [i];
+      MBadPixelsPix         &bad   =                         (*badcam)   [i];
+
+      if (!bad.IsUnsuitable (MBadPixelsPix::kUnsuitableRun))
+        {
+          qepix.SetPINDiodeMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      qepix.UpdateCombinedMethod();
+    }
+}
+
+// -----------------------------------------------------------------------------------------------
+//
+// - Print out statistics about BadPixels of type UnsuitableType_t 
+// - store numbers of bad pixels of each type in fCam or fIntensCam
+//
+void MCalibrationChargeCalc::FinalizeUnsuitablePixels()
+{
+  
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Charge Calibration status:" << endl;
+  *fLog << dec << setfill(' ');
+
+  const Int_t nareas = fGeom->GetNumAreas();
+
+  TArrayI counts(nareas);
+
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)fIntensBad->GetCam()  : fBadPixels;
+  MCalibrationChargeCam *chargecam = fIntensCam 
+    ? (MCalibrationChargeCam*)fIntensCam->GetCam()  : fCam;
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*badcam)[i];
+      if (!bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          const Int_t aidx = (*fGeom)[i].GetAidx();
+          counts[aidx]++;
+        }
+    }
+
+  if (fGeom->InheritsFrom("MGeomCamMagic"))
+    *fLog << " " << setw(7) << "Successfully calibrated Pixels: " 
+          << Form("%s%3i%s%3i","Inner: ",counts[0]," Outer: ",counts[1]) << endl;
+  
+  counts.Reset();
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      MBadPixelsPix &bad =  (*badcam)[i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          const Int_t aidx = (*fGeom)[i].GetAidx();
+          counts[aidx]++;
+        }
+    }
+
+  for (Int_t aidx=0; aidx<nareas; aidx++)
+    chargecam->SetNumUnsuitable(counts[aidx], aidx);
+
+  if (fGeom->InheritsFrom("MGeomCamMagic"))
+    *fLog << " " << setw(7) << "Uncalibrated Pixels:            " 
+          << Form("%s%3i%s%3i","Inner: ",counts[0]," Outer: ",counts[1]) << endl;
+
+  counts.Reset();
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+
+      MBadPixelsPix &bad = (*badcam)[i];
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+        {
+          const Int_t aidx = (*fGeom)[i].GetAidx();
+          counts[aidx]++;
+        }
+    }
+
+  for (Int_t aidx=0; aidx<nareas; aidx++)
+    chargecam->SetNumUnreliable(counts[aidx], aidx);
+
+  *fLog << " " << setw(7) << "Unreliable Pixels:              "
+        << Form("%s%3i%s%3i","Inner: ",counts[0]," Outer: ",counts[1]) << endl;
+
+}
+
+// -----------------------------------------------------------------------------------------------
+//
+// Print out statistics about BadPixels of type UncalibratedType_t 
+// 
+void MCalibrationChargeCalc::PrintUncalibrated(MBadPixelsPix::UncalibratedType_t typ, const char *text) const 
+{
+  
+  UInt_t countinner = 0;
+  UInt_t countouter = 0;
+
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)fIntensBad->GetCam()  : fBadPixels;
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*badcam)[i];
+
+      if (bad.IsUncalibrated(typ))
+        {
+          if (fGeom->GetPixRatio(i) == 1.)
+            countinner++;
+          else
+            countouter++;
+        }
+    }
+
+  *fLog << " " << setw(7) << text  
+        << Form("%s%3i%s%3i","Inner: ",countinner," Outer: ",countouter) << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the path for output file
+// 
+void MCalibrationChargeCalc::SetOutputPath(TString path)
+{
+  fOutputPath = path;
+  if (fOutputPath.EndsWith("/"))
+    fOutputPath = fOutputPath(0, fOutputPath.Length()-1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the output file
+// 
+void MCalibrationChargeCalc::SetOutputFile(TString file)
+{ 
+  fOutputFile = file; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the output file
+// 
+const char* MCalibrationChargeCalc::GetOutputFile()
+{
+  return Form("%s/%s", (const char*)fOutputPath, (const char*)fOutputFile);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the environment for the following data members:
+// - fChargeLimit
+// - fChargeErrLimit
+// - fChargeRelErrLimit
+// - fDebug
+// - fFFactorErrLimit
+// - fLambdaErrLimit
+// - fLambdaCheckErrLimit
+// - fPheErrLimit
+// 
+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;
+    }
+  if (IsEnvDefined(env, prefix, "CheckDeadPixels", print))
+    {
+      SetCheckDeadPixels(GetEnvValue(env, prefix, "CheckDeadPixels", IsCheckDeadPixels()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckDeviatingBehavior", print))
+    {
+      SetCheckDeviatingBehavior(GetEnvValue(env, prefix, "CheckDeviatingBehavior", IsCheckDeviatingBehavior()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckExtractionWindow", print))
+    {
+      SetCheckExtractionWindow(GetEnvValue(env, prefix, "CheckExtractionWindow", IsCheckExtractionWindow()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckHistOverflow", print))
+    {
+      SetCheckHistOverflow(GetEnvValue(env, prefix, "CheckHistOverflow", IsCheckHistOverflow()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "CheckOscillations", print))
+    {
+      SetCheckOscillations(GetEnvValue(env, prefix, "CheckOscillations", IsCheckOscillations()));
+      rc = kTRUE;
+    }
+  
+  return rc;
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationChargeCalc.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationChargeCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationChargeCalc.h	(revision 9772)
@@ -0,0 +1,217 @@
+#ifndef MARS_MCalibrationChargeCalc
+#define MARS_MCalibrationChargeCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrationChargeCalc                                                   //
+//                                                                         //
+// Integrates the time slices of the all pixels of a calibration event     //
+// and substract the pedestal value                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+class MCalibrationPattern;
+class MPedestalCam;
+class MPedestalPix;
+class MCalibrationChargePINDiode;
+class MHCalibrationChargeBlindCam;
+class MCalibrationIntensityBlindCam;
+class MCalibrationBlindCam;
+class MCalibrationChargePix;
+class MCalibrationIntensityChargeCam;
+class MCalibrationChargeCam;
+class MHCalibrationChargeCam;
+class MCalibrationIntensityQECam;
+class MCalibrationQECam;
+class MGeomCam;
+class MExtractedSignalCam;
+class MBadPixelsIntensityCam;
+class MBadPixelsCam;
+
+class MCalibrationChargeCalc : public MTask
+{
+private:
+
+  static const Float_t fgChargeLimit;          //! Default for fChargeLimit        (now set to: 2.5)
+  static const Float_t fgChargeErrLimit;       //! Default for fChargeErrLimit     (now set to: 0.)
+  static const Float_t fgChargeRelErrLimit;    //! Default for fChargeRelErrLimit  (now set to: 1.)
+  static const Float_t fgLambdaCheckLimit;     //! Default for fLambdaCheckLimit   (now set to: 0.2)
+  static const Float_t fgLambdaErrLimit;       //! Default for fLabmdaErrLimit     (now set to: 0.5)
+  static const Float_t fgPheErrLimit;          //! Default for fPheErrLimit        (now set to: 4.5)
+  static const Float_t fgFFactorErrLimit;      //! Default for fFFactorErrLimit    (now set to: 4.5)
+ 
+  static const TString fgNamePedestalCam;      //! "MPedestalCam"
+  
+  // Variables
+  Float_t fChargeLimit;                        // Limit acceptance mean charge  (in units of PedRMS)
+  Float_t fChargeErrLimit;                     // Limit acceptance charge error (in abs. numbers)
+  Float_t fChargeRelErrLimit;                  // Limit acceptance rel. error mean (in abs. numbers)
+  Float_t fLambdaCheckLimit;                   // Limit rel. diff. lambda and lambdacheck in Blind Pixel
+  Float_t fLambdaErrLimit;                     // Limit acceptance lambda error in Blind Pixel
+  Float_t fNumHiGainSamples;                   // Number High-Gain FADC slices used by extractor
+  Float_t fNumLoGainSamples;                   // Number Low -Gain FADC slices used by extractor
+  Float_t fPheErrLimit;                        // Limit acceptance nr. phe's w.r.t. area idx mean (in sigmas)
+  Float_t fFFactorErrLimit;                    // Limit acceptance F-Factor w.r.t. area idx mean 
+  Float_t fSqrtHiGainSamples;                  // Square root nr. High-Gain FADC slices used by extractor
+  Float_t fSqrtLoGainSamples;                  // Square root nr. Low -Gain FADC slices used by extractor 
+
+  MCalibrationCam::PulserColor_t fPulserColor; // Calibration LEDs colour 
+  Float_t fStrength;                           // Calibration LEDs strength 
+
+  Int_t   fNumInnerFFactorMethodUsed;          // Number of inner pixels used for F-Factor Method calibration
+
+  Byte_t  fFlags;                              // Bit-field for the general flags
+  TArrayC fResultFlags;                        // Bit-fields for the fitting results   (one field per area index)
+  TArrayC fBlindPixelFlags;                    // Bit-fields for the blind pixel flags (one field per blind pixel)
+  TArrayC fPINDiodeFlags;                      // Bit-fields for the PIN Diode flags   (one field per PIN Diode  )
+  
+  TString fOutputPath;                         // Path to the output file
+  TString fOutputFile;                         // Name of the output file  
+  TString fNamePedestalCam;                    // Name of the 'MPedestalCam' container
+
+  Int_t   fNumProcessed;                       // Number of processed events (for Intensity calibration)
+  
+  // Pointers
+  MBadPixelsIntensityCam         *fIntensBad;      //!  Bad Pixels  
+  MBadPixelsCam                  *fBadPixels;      //!  Bad Pixels
+  MCalibrationIntensityChargeCam *fIntensCam;      //!  Intensity Calibration results of all pixels   
+  MCalibrationChargeCam          *fCam;            //!  Calibrated Charges results of all pixels
+  MHCalibrationChargeCam         *fHCam;           //!  Charges histograms of all pixels   
+  MCalibrationIntensityBlindCam  *fIntensBlind;    //!  Intensity Calibration results of the Blind Pixels
+  MCalibrationBlindCam           *fBlindCam;       //!  Calibrated Charges of the Blind Pixels
+  MHCalibrationChargeBlindCam    *fHBlindCam;      //!  Charges histograms of the Blind Pixels  
+  MCalibrationChargePINDiode     *fPINDiode;       //!  Calibrated Charges of the PIN Diode
+  MCalibrationIntensityQECam     *fIntensQE;       //!  Intensity Calibration Quantum Efficiencies of all pixels
+  MCalibrationQECam              *fQECam;          //!  Calibrated Quantum Efficiencies of all pixels 
+  MGeomCam                       *fGeom;           //!  Camera geometry
+  MExtractedSignalCam            *fSignal;         //! Extracted Signal
+  MCalibrationPattern            *fCalibPattern;   //! Calibration DM pattern
+  MPedestalCam                   *fPedestals;      //! Pedestals all pixels (calculated previously from ped.file)
+
+  // enums
+  enum  Check_t
+    {
+      kCheckDeadPixels,
+      kCheckExtractionWindow,
+      kCheckHistOverflow,
+      kCheckDeviatingBehavior,
+      kCheckOscillations
+    };                                         // Possible Checks
+
+  Byte_t fCheckFlags;                          // Bit-field to hold the possible check flags
+  
+  enum  { kDebug,
+          kPheFitOK, kFFactorFitOK, kBlindPixelFitOK, kBlindPixelPedFitOK, kPINDiodeFitOK };
+
+  // functions
+  void   FinalizePedestals       ( const MPedestalPix    &ped, MCalibrationChargePix &cal, const Int_t aidx );
+  Bool_t FinalizeCharges         ( MCalibrationChargePix &cal, MBadPixelsPix &bad, const char* what);
+  Bool_t FinalizePINDiode        ();
+  Bool_t FinalizeBlindCam        ();  
+  Bool_t FinalizeFFactorMethod   ();
+  void   FinalizeBadPixels       ();
+  void   FinalizeFFactorQECam    ();  
+  void   FinalizeBlindPixelQECam ();
+  void   FinalizePINDiodeQECam   ();
+  void   FinalizeCombinedQECam   ();
+  void   FinalizeUnsuitablePixels();
+
+  const char* GetOutputFile();
+
+  // Query checks
+  Bool_t IsCheckDeadPixels       () const { return TESTBIT(fCheckFlags,kCheckDeadPixels);        }
+  Bool_t IsCheckDeviatingBehavior() const { return TESTBIT(fCheckFlags,kCheckDeviatingBehavior); }
+  Bool_t IsCheckExtractionWindow () const { return TESTBIT(fCheckFlags,kCheckExtractionWindow);  }
+  Bool_t IsCheckHistOverflow     () const { return TESTBIT(fCheckFlags,kCheckHistOverflow);      }
+  Bool_t IsCheckOscillations     () const { return TESTBIT(fCheckFlags,kCheckOscillations);      }
+
+  void   PrintUncalibrated( MBadPixelsPix::UncalibratedType_t typ, const char *text) const;
+
+  // Global fit results
+  void   SetPheFitOK          ( const Int_t aidx, const Bool_t b=kTRUE ) {
+    b ? SETBIT(fResultFlags[aidx], kPheFitOK) 
+      : CLRBIT(fResultFlags[aidx], kPheFitOK);      }
+  void   SetFFactorFitOK      ( const Int_t aidx, const Bool_t b=kTRUE ) {
+    b ? SETBIT(fResultFlags[aidx], kFFactorFitOK) 
+      : CLRBIT(fResultFlags[aidx], kFFactorFitOK);  }
+  void   SetBlindPixelFitOK   ( const Int_t  idx, const Bool_t b=kTRUE ) {
+    b ? SETBIT(fBlindPixelFlags[idx], kBlindPixelFitOK) 
+      : CLRBIT(fBlindPixelFlags[idx], kBlindPixelFitOK); }
+  void   SetBlindPixelPedFitOK( const Int_t  idx, const Bool_t b=kTRUE ) {
+    b ? SETBIT(fBlindPixelFlags[idx], kBlindPixelPedFitOK) 
+      : CLRBIT(fBlindPixelFlags[idx], kBlindPixelPedFitOK); }
+  void   SetPINDiodeFitOK     ( const Int_t  idx, const Bool_t b=kTRUE ) {
+    b ? SETBIT(fPINDiodeFlags[idx], kPINDiodeFitOK) 
+      : CLRBIT(fPINDiodeFlags[idx], kPINDiodeFitOK); }
+
+  Int_t  PreProcess (MParList *pList);
+  Bool_t ReInit     (MParList *pList); 
+  Int_t  Process    ();
+  Int_t  PostProcess();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+
+  MCalibrationChargeCalc(const char *name=NULL, const char *title=NULL);
+
+  void Clear(const Option_t *o="");
+
+  Int_t Finalize();
+
+  Bool_t IsDebug() const   {  return TESTBIT(fFlags,kDebug); }
+  
+  void SetChargeLimit       ( const Float_t f=fgChargeLimit            ) { fChargeLimit       = f;     }
+  void SetChargeErrLimit    ( const Float_t f=fgChargeErrLimit         ) { fChargeErrLimit    = f;     }
+  void SetChargeRelErrLimit ( const Float_t f=fgChargeRelErrLimit      ) { fChargeRelErrLimit = f;     }
+
+  // Checks
+  void SetCheckDeadPixels( const Bool_t b=kTRUE ) {
+    b ? SETBIT(fCheckFlags,kCheckDeadPixels)
+      : CLRBIT(fCheckFlags,kCheckDeadPixels); }
+  void SetCheckDeviatingBehavior( const Bool_t b=kTRUE ) {
+    b ? SETBIT(fCheckFlags,kCheckDeviatingBehavior)
+      : CLRBIT(fCheckFlags,kCheckDeviatingBehavior); }
+  void SetCheckExtractionWindow( const Bool_t b=kTRUE ) {
+    b ? SETBIT(fCheckFlags,kCheckExtractionWindow)
+      : CLRBIT(fCheckFlags,kCheckExtractionWindow); }
+  void SetCheckHistOverflow( const Bool_t b=kTRUE ) {
+    b ? SETBIT(fCheckFlags,kCheckHistOverflow)
+      : CLRBIT(fCheckFlags,kCheckHistOverflow); }
+  void SetCheckOscillations( const Bool_t b=kTRUE ) {
+    b ? SETBIT(fCheckFlags,kCheckOscillations)
+      : CLRBIT(fCheckFlags,kCheckOscillations); }
+  void SetDebug            ( const Bool_t b=kTRUE ) { 
+    b ? SETBIT(fFlags, kDebug) 
+      : CLRBIT(fFlags, kDebug); }
+
+  void SetPedestals(MPedestalCam *cam) { fPedestals=cam; }
+									 
+  void SetFFactorErrLimit   ( const Float_t f=fgFFactorErrLimit        ) { fFFactorErrLimit   = f;     }
+  void SetLambdaErrLimit    ( const Float_t f=fgLambdaErrLimit         ) { fLambdaErrLimit    = f;     }
+  void SetLambdaCheckLimit  ( const Float_t f=fgLambdaCheckLimit       ) { fLambdaCheckLimit  = f;     }
+  void SetNamePedestalCam   ( const char *name=fgNamePedestalCam.Data()) { fNamePedestalCam   = name;  }
+  void SetOutputPath        ( TString path="."                   );
+  void SetOutputFile        ( TString file="ChargeCalibStat.txt" );
+  void SetPheErrLimit       ( const Float_t f=fgPheErrLimit            ) { fPheErrLimit       = f;     }  
+  void SetPulserColor       ( const MCalibrationCam::PulserColor_t col ) { fPulserColor       = col;   }
+
+  ClassDef(MCalibrationChargeCalc, 1)   // Task calculating Calibration Containers and Quantum Efficiencies
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationChargeCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationChargeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationChargeCam.cc	(revision 9772)
@@ -0,0 +1,1125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationChargeCam                                               
+//                                                               
+// Storage container for charge calibration results from the signal distribution 
+// fits (see MHCalibrationChargeCam and MHCalibrationChargePix), the calculation 
+// of reduced sigmas and number of photo-electrons (this class) and conversion 
+// factors sum FADC slices to photo-electrons (see MCalibrationChargeCalc)
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationChargePix &avpix = (MCalibrationChargePix&)(*fChargeCam)[i]
+// 
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationChargePix &avpix = (MCalibrationChargePix&)fChargeCam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationChargePix &avpix = (MCalibrationChargePix&)fChargeCam->GetAverageSector(i)
+//
+// Note the averageing has been done on an event-by-event basis. Resulting 
+// Sigma's of the Gauss fit have been multiplied with the square root of the number 
+// of involved pixels in order to make a direct comparison possible with the mean of 
+// sigmas. 
+//
+// Final numbers of uncalibrated or unreliable pixels can be retrieved via the commands:
+// GetNumUncalibrated(aidx) and GetNumUnreliable(aidx) where aidx is the area index (0 for 
+// inner and 1 for outer pixels in the MAGIC camera).
+//
+// The following "calibration" constants are used for the calibration of each pixel 
+// (see MCalibrate):
+//
+// - MCalibrationQEPix::GetMeanConvFADC2Phe(): The mean conversion factor from the 
+//   summed FADC slices to the number of photo-electrons (in first order independent 
+//   on colour and intensity)
+// - MCalibrationQEPix::GetMeanFFactorFADC2Phot(): The mean F-Factor of the total  
+//   readout chain dividing the signal to noise of the incoming number of photons 
+//   (= sqrt(number photons)) by the signal to noise of the outgoing summed FADC slices 
+//   signal (= MCalibrationPix::GetMean() / MCalibrationChargePix::GetRSigma() )
+//
+// The following calibration constants can be retrieved directly from this class:
+//
+// - GetConversionFactorFFactor    ( Int_t idx, Float_t &mean, Float_t &err, Float_t &sigma );
+//
+// where: 
+// - idx is the pixel software ID
+// - "mean" is the mean conversion constant, to be multiplied with the retrieved signal 
+//   in order to get a calibrated number of PHOTONS. 
+// - "err" is the pure statistical uncertainty about the MEAN
+// - "sigma", if mulitplied with the square root of signal, gives the approximate sigma of the 
+//   retrieved mean number of incident Cherenkov photons.
+//
+// Note, Conversion is ALWAYS (included the F-Factor method!) from summed FADC slices to PHOTONS.
+//
+// See also: MCalibrationChargePix, MCalibrationChargeCalc, MCalibrationQECam
+//           MHCalibrationChargePix, MHCalibrationChargeCam              
+//           MCalibrationBlindPix, MCalibrationChargePINDiode
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+#include <TOrdCollection.h>
+#include <TH1D.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+#include "MHCamera.h"
+
+ClassImp(MCalibrationChargeCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls:
+// - Clear()
+//
+MCalibrationChargeCam::MCalibrationChargeCam(const char *name, const char *title)
+{
+  fName  = name  ? name  : "MCalibrationChargeCam";
+  fTitle = title ? title : "Storage container for the Calibration Information in the camera";
+  
+  Clear();
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Creates new MCalibrationCam only for the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//
+TObject *MCalibrationChargeCam::Clone(const char *) const
+{
+
+  //
+  // FIXME, this might be done faster and more elegant, by direct copy.
+  //
+  MCalibrationChargeCam *cam = new MCalibrationChargeCam(fName,fTitle);
+
+  cam->fNumUnsuitable        = fNumUnsuitable;
+  cam->fNumUnreliable        = fNumUnreliable;
+  cam->fNumHiGainFADCSlices  = fNumHiGainFADCSlices;
+  cam->fNumLoGainFADCSlices  = fNumLoGainFADCSlices;
+  cam->fPulserColor          = fPulserColor;
+
+  cam->fFlags                = fFlags;
+
+  cam->fNumPhotonsBlindPixelMethod      = fNumPhotonsBlindPixelMethod;
+  cam->fNumPhotonsFFactorMethod         = fNumPhotonsFFactorMethod;
+  cam->fNumPhotonsPINDiodeMethod        = fNumPhotonsPINDiodeMethod;
+  cam->fNumPhotonsBlindPixelMethodErr   = fNumPhotonsBlindPixelMethodErr;
+  cam->fNumPhotonsFFactorMethodErr      = fNumPhotonsFFactorMethodErr;
+  cam->fNumPhotonsPINDiodeMethodErr     = fNumPhotonsPINDiodeMethodErr;
+
+  for (Int_t i=0; i<GetSize(); i++)
+    cam->fPixels->AddAt((*this)[i].Clone(),i);
+  
+  for (Int_t i=0; i<GetAverageAreas(); i++)
+    {
+      cam->fAverageAreas->AddAt(GetAverageArea(i).Clone(),i);
+      cam->fAverageBadAreas->AddAt(GetAverageBadArea(i).Clone(),i);
+    }
+  for (Int_t i=0; i<GetAverageSectors(); i++)
+    {
+      cam->fAverageSectors->AddAt(GetAverageSector(i).Clone(),i);
+      cam->fAverageBadSectors->AddAt(GetAverageBadSector(i).Clone(),i);
+    }
+
+  return cam;
+}
+*/
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationChargePix's in the ranges from - to to fPixels
+//
+void MCalibrationChargeCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    {
+      fPixels->AddAt(new MCalibrationChargePix,i);
+      (*this)[i].SetPixId(i);
+    }
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationChargePix's in the ranges from - to to fAverageAreas
+//
+void MCalibrationChargeCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    {
+      fAverageAreas->AddAt(new MCalibrationChargePix,i);
+      GetAverageArea(i).SetPixId(i);
+    }
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationChargePix's in the ranges from - to to fAverageSectors
+//
+void MCalibrationChargeCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    {
+      fAverageSectors->AddAt(new MCalibrationChargePix,i);
+      GetAverageSector(i).SetPixId(i);
+    }
+}
+
+
+// --------------------------------------
+//
+// Sets all variable to 0.
+// Sets all flags to kFALSE
+// Calls MCalibrationCam::Clear()
+//
+void MCalibrationChargeCam::Clear(Option_t *o)
+{
+
+  SetFFactorMethodValid    ( kFALSE );
+
+  fNumPhotonsBlindPixelMethod    = 0.; 
+  fNumPhotonsFFactorMethod       = 0.; 
+  fNumPhotonsPINDiodeMethod      = 0.; 
+  fNumPhotonsBlindPixelMethodErr = 0.; 
+  fNumPhotonsFFactorMethodErr    = 0.;  
+  fNumPhotonsPINDiodeMethodErr   = 0.;  
+
+  MCalibrationCam::Clear();
+
+  return;
+}
+
+// -----------------------------------------------
+//
+// Sets the kFFactorMethodValid bit from outside
+//
+void MCalibrationChargeCam::SetFFactorMethodValid(const Bool_t b)
+{
+    b ? SETBIT(fFlags, kFFactorMethodValid) : CLRBIT(fFlags, kFFactorMethodValid); 
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Test bit kFFactorMethodValid
+//
+Bool_t  MCalibrationChargeCam::IsFFactorMethodValid()   const
+{
+  return TESTBIT(fFlags,kFFactorMethodValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not FitValid
+//
+void MCalibrationChargeCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << "Calibrated pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationChargePix *pix;
+  while ((pix=(MCalibrationChargePix*)Next()))
+    {
+      
+      if (!pix->IsExcluded()) 
+	{                            
+
+          *fLog << all 
+                << Form("%s%3i","Pixel: ",pix->GetPixId())
+                << Form("%s%4.2f%s%4.2f","  Ped.Rms: ",pix->GetPedRms(),"+-",pix->GetPedRmsErr())
+		<< Form("%s%4.2f%s%4.2f","  Charge: " ,pix->GetConvertedMean(),"+-",pix->GetConvertedSigma())
+		<< Form("%s%4.2f%s%4.2f","  Red.Sigma: ",pix->GetConvertedRSigma(),"+-",pix->GetConvertedRSigmaErr())
+		<< Form("%s%4.2f%s%4.2f","  Num.Phes: ",pix->GetPheFFactorMethod(),"+-",pix->GetPheFFactorMethodErr()) 
+		<< Form("%s%4.2f%s%4.2f","  Conv.FADC2Phe: ",pix->GetMeanConvFADC2Phe(),"+-",pix->GetMeanConvFADC2PheErr())
+                << " Saturated? :" << pix->IsHiGainSaturation() 
+		<< Form("%s%4.2f%s%4.2f","  Conv.HiLo: ",pix->GetConversionHiLo(),"+-",pix->GetConversionHiLoErr())
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+  
+   
+  *fLog << all << endl;
+  *fLog << all << "Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationChargePix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+        *fLog << all << pix->GetPixId() << " ";
+        id++;
+
+        if (!(id % 25))
+          *fLog << endl;
+      }
+  }
+  
+  *fLog << endl;
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  *fLog << all << endl;
+  *fLog << all << "Averaged Areas:" << endl;
+  *fLog << all << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationChargePix*)Next5()))
+  {
+    *fLog << all << Form("%s%3i","Area Idx: ",pix->GetPixId())
+          << "   Ped.  Rms: "            << pix->GetPedRms()        << " +- " << pix->GetPedRmsErr() 
+          << "   Mean signal: "          << pix->GetMean()    << " +- " << pix->GetMeanErr() 
+          << "   Sigma signal: "         << pix->GetSigma()    << " +- "<< pix->GetSigmaErr() 
+          << "   Reduced Sigma: "        << pix->GetRSigma() 
+          << "   Nr Phe's: "             << pix->GetPheFFactorMethod() 
+          << endl;
+  }
+
+  *fLog << all << endl;
+  *fLog << all << "Averaged Sectors:" << endl;
+  *fLog << all << endl;
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationChargePix*)Next6()))
+  {
+    *fLog << all << Form("%s%3i","Sector: ",pix->GetPixId())
+          << "   Ped.  Rms: "            << pix->GetPedRms()        << " +- " << pix->GetPedRmsErr() 
+          << "   Mean signal: "          << pix->GetMean()    << " +- " << pix->GetMeanErr() 
+          << "   Sigma signal: "         << pix->GetSigma()    << " +- "<< pix->GetSigmaErr() 
+          << "   Reduced Sigma: "        << pix->GetRSigma() 
+          << "   Nr Phe's: "             << pix->GetPheFFactorMethod() 
+          << endl;
+  }
+  *fLog << all << endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Charge                              (see MCalibrationPix::GetMean())
+// 1: Error of fitted Charge                     (see MCalibrationPix::GetMeanErr())
+// 2: Sigma of fitted Charge                     (see MCalibrationPix::GetSigma())
+// 3: Error of Sigma of fitted Charge            (see MCalibrationPix::GetSigmaErr())
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Probability Gauss fit Charge distribution  (see MCalibrationPix::GetProb())
+// 5: Reduced Sigma of fitted Charge             (see MCalibrationChargePix::GetRSigma())
+// 6: Error Reduced Sigma of fitted Charge       (see MCalibrationChargePix::GetRSigmaErr())
+// 7: Reduced Sigma per Charge                   (see MCalibrationChargePix::GetRSigmaPerCharge())
+// 8: Error of Reduced Sigma per Charge          (see MCalibrationChargePix::GetRSigmaPerChargeErr())
+//
+// Results of the F-Factor calibration Method:
+// ===========================================
+//
+//  9: Nr. Photo-electrons from F-Factor Method  (see MCalibrationChargePix::GetPheFFactorMethod())
+// 10: Error Nr. Photo-el. from F-Factor Method  (see MCalibrationChargePix::GetPheFFactorMethodErr())
+// 11: Conversion factor   from F-Factor Method  (see MCalibrationChargePix::GetMeanConvFADC2Phe()
+// 12: Error conv. factor  from F-Factor Method  (see MCalibrationChargePix::GetMeanConvFADC2PheErr()
+// 13: Overall F-Factor    from F-Factor Method  (see MCalibrationChargePix::GetMeanFFactorFADC2Phot()
+// 14: Error F-Factor      from F-Factor Method  (see MCalibrationChargePix::GetMeanFFactorFADC2PhotErr()
+// 15: Pixels valid calibration F-Factor-Method  (see MCalibrationChargePix::IsFFactorMethodValid())           
+//
+// Results of the Low-Gain vs. High-Gain Conversion:
+// =================================================
+//
+// 16: Mean Signal Hi-Gain / Mean Signal Lo-Gain (see MCalibrationPix::GetHiLoMeansDivided())
+// 17: Error Signal High-Gain / Signal Low Gain  (see MCalibrationPix::GetHiLoMeansDividedErr())
+// 18: Sigma High-Gain / Sigma Low Gain          (see MCalibrationPix::GetHiLoSigmasDivided())
+// 19: Error Sigma High-Gain / Sigma Low Gain    (see MCalibrationPix::GetHiLoSigmasDividedErr())
+//                                                
+// Localized defects:                             
+// ==================
+//
+// 20: Excluded Pixels
+// 21: Number of pickup   events in the Hi Gain  (see MCalibrationPix::GetHiGainNumPickup())
+// 22: Number of pickup   events in the Lo Gain  (see MCalibrationPix::GetLoGainNumPickup())
+// 23: Number of blackout events in the Hi Gain  (see MCalibrationPix::GetHiGainNumBlackout())
+// 24: Number of blackout events in the Lo Gain  (see MCalibrationPix::GetLoGainNumBlackout())
+//
+// Other classifications of pixels:
+// ================================
+//
+// 25: Pixels with saturated High-Gain           (see MCalibrationPix::IsHiGainSaturation())
+//
+// Calculated absolute arrival times (very low precision!):
+// ========================================================
+//
+// 26: Absolute Arrival time of the signal       (see MCalibrationChargePix::GetAbsTimeMean())
+// 27: RMS Ab.  Arrival time of the signal       (see MCalibrationChargePix::GetAbsTimeRms())
+//
+// Used Pedestals:
+// ===============
+//
+// 28: Pedestal for entire signal extr. range    (see MCalibrationChargePix::Ped())
+// 29: Error Pedestal entire signal extr. range  (see MCalibrationChargePix::PedErr())
+// 30: Ped. RMS entire signal extraction range   (see MCalibrationChargePix::PedRms())
+// 31: Error Ped. RMS entire signal extr. range  (see MCalibrationChargePix::PedRmsErr())
+//
+// Special variables (for data check):
+// ====================================
+//
+// 32: HiGain RMS divided by Mean for every pixel (with inclusion of the excluded pixels)
+//
+Bool_t MCalibrationChargeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetConvertedMean();
+      break;
+    case 1:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetConvertedMeanErr();
+      break;
+    case 2:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetConvertedSigma();
+      break;
+    case 3:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetConvertedSigmaErr();
+      break;
+    case 4:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetProb();
+      break;
+    case 5:
+      if (pix.IsExcluded())
+        return kFALSE;
+      if (pix.GetRSigma() == -1.)
+	  return kFALSE;
+      val = pix.GetConvertedRSigma();
+      break;
+    case 6:
+      if (pix.IsExcluded())
+        return kFALSE;    
+      if (pix.GetRSigma() == -1.)
+	  return kFALSE;
+      val = pix.GetConvertedRSigmaErr();
+      break;
+    case 7:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetRSigmaPerCharge();
+      break;
+    case 8:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val =  pix.GetRSigmaPerChargeErr();
+      break;
+    case 9:
+      if (pix.IsExcluded() || !pix.IsFFactorMethodValid())
+        return kFALSE;
+      val = pix.GetPheFFactorMethod();
+      break;
+    case 10:
+      if (pix.IsExcluded() || !pix.IsFFactorMethodValid())
+        return kFALSE;
+      val = pix.GetPheFFactorMethodErr();
+      break;
+    case 11:
+      if (pix.IsExcluded() || !pix.IsFFactorMethodValid())
+        return kFALSE;
+      val = pix.GetMeanConvFADC2Phe();
+      break;
+    case 12:
+      if (pix.IsExcluded() || !pix.IsFFactorMethodValid())
+        return kFALSE;
+      val = pix.GetMeanConvFADC2PheErr();
+      break;
+    case 13:
+      if (pix.IsExcluded() || !pix.IsFFactorMethodValid())
+        return kFALSE;
+      val = pix.GetMeanFFactorFADC2Phot();
+      break;
+    case 14:
+      if (pix.IsExcluded() || !pix.IsFFactorMethodValid())
+        return kFALSE;
+      val = pix.GetMeanFFactorFADC2PhotErr();
+      break;
+    case 15:
+      if (pix.IsExcluded())
+        return kFALSE;
+      if (pix.IsFFactorMethodValid())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 16:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoMeansDivided();
+      break;
+    case 17:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoMeansDividedErr();
+      break;
+    case 18:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoSigmasDivided();
+      break;
+    case 19:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoSigmasDividedErr();
+      break;
+    case 20:
+      if (pix.IsExcluded())
+        val = 1.;
+      else
+        return kFALSE;
+      break;
+    case 21:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainNumPickup();
+      break;
+    case 22:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetLoGainNumPickup();
+      break;
+    case 23:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainNumBlackout();
+      break;
+    case 24:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetLoGainNumBlackout();
+      break;
+    case 25:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.IsHiGainSaturation();
+      break;
+    case 26:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetAbsTimeMean();
+      break;
+    case 27:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetAbsTimeRms();
+      break;
+    case 28:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetPed();
+      break;
+    case 29:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetPedErr();
+      break;
+    case 30:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetPedRms();
+      break;
+    case 31:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetPedErr()/2.;
+      break;
+    case 32:
+      val = pix.GetMean() == 0. ? 0. : pix.GetRms()/pix.GetMean();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+}
+
+
+
+Bool_t MCalibrationChargeCam::GetConversionFactorFFactor(Int_t ipx, Float_t &mean, Float_t &err, Float_t &ffactor)
+{
+
+  MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[ipx];
+
+  Float_t conv = pix.GetMeanConvFADC2Phe();
+
+  if (conv < 0.)
+    return kFALSE;
+
+  mean    = conv;
+  err     = pix.GetMeanConvFADC2PheErr();
+  ffactor = pix.GetMeanFFactorFADC2Phot();
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average conversion factor FADC counts to photons for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index). The MCalibrationQECam container is necessary for 
+// the quantum efficiency information. 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged conversion factors (default: -1.)
+// arr[1]: Error (rms) of averaged conversion factors (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedConvFADC2PhotPerArea  ( const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                           const UInt_t ai,  MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  MHCamera convcam(geom,"ConvFactors","Conversion Factors;Conv Factor [phot/FADC cnts];channels");
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+
+      if (bad && (*bad)[i].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes))
+        continue; 
+
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+      
+      const MCalibrationQEPix &qepix = (MCalibrationQEPix&)qecam[i];
+      if (!qepix.IsAverageQEFFactorAvailable())
+        continue;
+      
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t conv = pix.GetMeanConvFADC2Phe()/qepix.GetQECascadesFFactor();
+
+      mean  += conv;
+      mean2 += conv*conv;
+      nr    ++;
+
+      convcam.Fill(i,conv);
+      convcam.SetUsed(i);
+    }
+
+  Float_t mn  = nr   ? mean/nr : -1.;
+  Float_t sg  = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0.;
+
+  const Int_t aidx = (Int_t)ai;
+
+  TH1D *h = convcam.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+  h->SetDirectory(NULL);
+
+  TF1 *fit = NULL;
+
+  if (geom.InheritsFrom("MGeomCamMagic"))
+    {
+
+      fit = new TF1("fit","gaus",0.4,5.);
+      
+      // Fix the ranges, as found by Nadia
+      if(aidx == 0)
+        {h->Fit("fit","REQ", "",0.4,1.5);}
+      else
+        {h->Fit("fit","REQ", "",1.,5.);}
+    }
+  else
+    {
+      h->Fit("gaus","Q");
+      fit = h->GetFunction("gaus");
+    }
+
+  Float_t ci2   = fit->GetChisquare();
+  Float_t sigma = fit->GetParameter(2);
+  
+  if (ci2 > 500. || sigma > sg)
+    {
+      if (geom.InheritsFrom("MGeomCamMagic"))
+        {
+          // Fix the ranges, as found by Nadia
+          if(aidx == 0)
+            {h->Fit("fit","REQ", "",0.4,1.5);}
+          else
+            {h->Fit("fit","REQ", "",1.,5.);}
+        }
+      else
+        {
+          h->Fit("gaus","MREQ");
+          fit = h->GetFunction("gaus");
+        }
+      
+      ci2   = fit->GetChisquare();
+      sigma = fit->GetParameter(2);
+    }
+  
+  const Int_t ndf = fit->GetNDF();
+
+  if (ci2 < 500. && sigma < sg && ndf > 2)
+    {
+      mn  = fit->GetParameter(1);
+      sg  = sigma;
+    }
+  
+  *fLog << inf << "Conversion Factors to photons area idx: " << aidx << ":" << endl;
+  *fLog << inf << "Mean: " << Form("%4.3f",mn) 
+        << "+-" << Form("%4.3f",fit->GetParError(1))
+        << "  Sigma: " << Form("%4.3f",sg) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+        << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+  
+  delete fit;
+  delete h;
+  gROOT->GetListOfFunctions()->Remove(fit);
+
+  TArrayF arr(2);
+  arr[0] = mn;
+  arr[1] = sg;
+
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average conversion factor FADC counts to equiv. photo-electrons for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index). The MCalibrationQECam container is necessary for 
+// the quantum efficiency information. 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged conversion factors (default: -1.)
+// arr[1]: Error (rms) of averaged conversion factors (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedConvFADC2PhePerArea  ( const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                           const UInt_t ai,  MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  MHCamera convcam(geom,"ConvFactors","Conversion Factors;Conv Factor [phe/FADC cnts];channels");
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+
+      if (bad && (*bad)[i].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes))
+        continue; 
+
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+      
+      const MCalibrationQEPix &qepix = (MCalibrationQEPix&)qecam[i];
+      if (!qepix.IsAverageQEFFactorAvailable())
+        continue;
+      
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t conv = pix.GetMeanConvFADC2Phe()/qepix.GetQECascadesFFactor()*MCalibrationQEPix::gkDefaultAverageQE;
+
+      mean  += conv;
+      mean2 += conv*conv;
+      nr    ++;
+
+      convcam.Fill(i,conv);
+      convcam.SetUsed(i);
+    }
+
+  Float_t mn  = nr   ? mean/nr : -1.;
+  Float_t sg  = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0.;
+
+  const Int_t aidx = (Int_t)ai;
+
+  TH1D *h = convcam.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+  h->SetDirectory(NULL);
+
+  TF1 *fit = NULL;
+
+  if (geom.InheritsFrom("MGeomCamMagic"))
+    {
+
+      fit = new TF1("fit","gaus",0.01,1.);
+      
+      // Fix the ranges, as found by Nadia
+      if(aidx == 0)
+        {h->Fit("fit","REQ", "",0.07,0.3);}
+      else
+        {h->Fit("fit","REQ", "",0.15,1.0);}
+    }
+  else
+    {
+      h->Fit("gaus","Q");
+      fit = h->GetFunction("gaus");
+    }
+
+  Float_t ci2   = fit->GetChisquare();
+  Float_t sigma = fit->GetParameter(2);
+  
+  if (ci2 > 500. || sigma > sg)
+    {
+      if (geom.InheritsFrom("MGeomCamMagic"))
+        {
+          // Fix the ranges, as found by Nadia
+          if(aidx == 0)
+            {h->Fit("fit","REQ", "",0.07,0.3);}
+          else
+            {h->Fit("fit","REQ", "",0.15,1.0);}
+        }
+      else
+        {
+          h->Fit("gaus","MREQ");
+          fit = h->GetFunction("gaus");
+        }
+      
+      ci2   = fit->GetChisquare();
+      sigma = fit->GetParameter(2);
+    }
+  
+  const Int_t ndf = fit->GetNDF();
+
+  if (ci2 < 500. && sigma < sg && ndf > 2)
+    {
+      mn  = fit->GetParameter(1);
+      sg  = sigma;
+    }
+  
+  *fLog << inf << "Conversion Factors to equiv. photo-electrons area idx: " << aidx << ":" << endl;
+  *fLog << inf << "Mean: " << Form("%4.3f",mn) 
+        << "+-" << Form("%4.3f",fit->GetParError(1))
+        << "  Sigma: " << Form("%4.3f",sg) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+        << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+  
+  delete fit;
+  delete h;
+  gROOT->GetListOfFunctions()->Remove(fit);
+
+  TArrayF arr(2);
+  arr[0] = mn;
+  arr[1] = sg;
+
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average conversion factor FADC counts to photons for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index). The MCalibrationQECam container is necessary for 
+// the quantum efficiency information. 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged conversion factors (default: -1.)
+// arr[1]: Error (rms) of averaged conversion factors (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedConvFADC2PhotPerSector( const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                             const UInt_t sec, MBadPixelsCam *bad)
+{
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sector != sec)
+        continue;
+
+      const MCalibrationQEPix &qepix = (MCalibrationQEPix&)qecam[i];
+      if (!qepix.IsAverageQEFFactorAvailable())
+        continue;
+      
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t conv = pix.GetMeanConvFADC2Phe();
+      const Float_t qe = qepix.GetQECascadesFFactor();
+
+      mean  += conv/qe;
+      mean2 += conv*conv/qe/qe;
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}  
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average mean arrival times for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index). 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged mean arrival times (default: -1.)
+// arr[1]: Error (rms) of averaged mean arrival times (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedArrivalTimeMeanPerArea(const MGeomCam &geom,
+                                                                 const UInt_t ai,  MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t time = pix.GetAbsTimeMean();
+
+      mean  += time   ;
+      mean2 += time*time;
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average mean arrival times for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index).
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged mean arrival times (default: -1.)
+// arr[1]: Error (rms) of averaged mean arrival times (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedArrivalTimeMeanPerSector(const MGeomCam &geom,
+                                                                   const UInt_t sec, MBadPixelsCam *bad)
+{
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sector != sec)
+        continue;
+
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t time = pix.GetAbsTimeMean();
+
+      mean  += time;
+      mean2 += time*time;
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}  
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average arrival time RMSs for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index). 
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged arrival time RMSs (default: -1.)
+// arr[1]: Error (rms) of averaged arrival time RMSs (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedArrivalTimeRmsPerArea  ( const MGeomCam &geom,
+                                                                   const UInt_t ai,  MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t rms = pix.GetAbsTimeRms();
+
+      mean  += rms;
+      mean2 += rms*rms;
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average arrival time RMSs for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index).
+// If the bad pixel container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged arrival time RMSs (default: -1.)
+// arr[1]: Error (rms) of averaged arrival time RMSs (default: 0.)
+//
+TArrayF MCalibrationChargeCam::GetAveragedArrivalTimeRmsPerSector( const MGeomCam &geom, const UInt_t sec, MBadPixelsCam *bad)
+{
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sector != sec)
+        continue;
+
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[i];
+      const Float_t rms = pix.GetAbsTimeRms();
+
+      mean  += rms;
+      mean2 += rms*rms;
+      nr    ++;
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+
+  return arr;
+}  
Index: /tags/Mars-V0.9/mcalib/MCalibrationChargeCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationChargeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationChargeCam.h	(revision 9772)
@@ -0,0 +1,76 @@
+#ifndef MARS_MCalibrationChargeCam
+#define MARS_MCalibrationChargeCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationQECam;
+class MCalibrationChargeCam : public MCalibrationCam
+{
+private:
+  
+  Byte_t  fFlags;                         // Bit-field to hold the flags
+
+  Float_t fNumPhotonsBlindPixelMethod;    // Average nr. photons from Blind Pixel Method (Inner Pixel)
+  Float_t fNumPhotonsFFactorMethod;       // Average nr. photons from F-Factor Method (Inner Pixel)
+  Float_t fNumPhotonsPINDiodeMethod;      // Average nr. photons from PIN Diode Method (Inner Pixel)
+  Float_t fNumPhotonsBlindPixelMethodErr; // Error av. nr. photons from Blind Pixel Method
+  Float_t fNumPhotonsFFactorMethodErr;    // Error av. nr. photons from F-Factor Method
+  Float_t fNumPhotonsPINDiodeMethodErr;   // Error av. nr. photons from PIN Diode Method
+  
+  enum  { kFFactorMethodValid };
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+  
+public:
+
+  MCalibrationChargeCam(const char *name=NULL, const char *title=NULL);
+  
+  void   Clear ( Option_t *o="" );
+  
+  // Getters
+  Bool_t  GetConversionFactorFFactor( Int_t ipx, Float_t &mean, Float_t &err, Float_t &ffactor );
+  Bool_t  GetPixelContent           ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+
+  Float_t GetNumPhotonsBlindPixelMethod   () const { return fNumPhotonsBlindPixelMethod;    }
+  Float_t GetNumPhotonsFFactorMethod      () const { return fNumPhotonsFFactorMethod;       }     
+  Float_t GetNumPhotonsPINDiodeMethod     () const { return fNumPhotonsPINDiodeMethod;      }    
+  Float_t GetNumPhotonsBlindPixelMethodErr() const { return fNumPhotonsBlindPixelMethodErr; }
+  Float_t GetNumPhotonsFFactorMethodErr   () const { return fNumPhotonsFFactorMethodErr;    }     
+  Float_t GetNumPhotonsPINDiodeMethodErr  () const { return fNumPhotonsPINDiodeMethodErr;   }    
+  Bool_t  IsFFactorMethodValid            () const;
+
+  TArrayF GetAveragedConvFADC2PhotPerArea    (const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                              const UInt_t ai=0,  MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedConvFADC2PhePerArea     (const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                              const UInt_t ai=0,  MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedConvFADC2PhotPerSector  (const MGeomCam &geom, const MCalibrationQECam &qecam,
+                                              const UInt_t sec=0, MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedArrivalTimeMeanPerArea  (const MGeomCam &geom,
+                                              const UInt_t ai=0,  MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedArrivalTimeMeanPerSector(const MGeomCam &geom,
+                                              const UInt_t sec=0, MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedArrivalTimeRmsPerArea   (const MGeomCam &geom,
+                                              const UInt_t ai=0,  MBadPixelsCam *bad=NULL);
+  TArrayF GetAveragedArrivalTimeRmsPerSector (const MGeomCam &geom,
+                                              const UInt_t sec=0, MBadPixelsCam *bad=NULL);
+  
+  // Prints
+  void   Print(Option_t *o="") const;
+
+  // Setters   
+  void  SetFFactorMethodValid           ( const Bool_t  b=kTRUE );
+  void  SetNumPhotonsBlindPixelMethod   ( const Float_t f )  { fNumPhotonsBlindPixelMethod    = f; } 
+  void  SetNumPhotonsFFactorMethod      ( const Float_t f )  { fNumPhotonsFFactorMethod       = f; }      
+  void  SetNumPhotonsPINDiodeMethod     ( const Float_t f )  { fNumPhotonsPINDiodeMethod      = f; }   
+  void  SetNumPhotonsBlindPixelMethodErr( const Float_t f )  { fNumPhotonsBlindPixelMethodErr = f; } 
+  void  SetNumPhotonsFFactorMethodErr   ( const Float_t f )  { fNumPhotonsFFactorMethodErr    = f; }      
+  void  SetNumPhotonsPINDiodeMethodErr  ( const Float_t f )  { fNumPhotonsPINDiodeMethodErr   = f; }   
+  
+  ClassDef(MCalibrationChargeCam, 5) // Container Charge Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationChargePINDiode.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationChargePINDiode.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationChargePINDiode.cc	(revision 9772)
@@ -0,0 +1,434 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                     
+// MCalibrationChargePINDiode       
+//                                  
+// Storage container of the fit results of the PIN Diode signal 
+// (from MHCalibrationChargePINDiode). The PIN Diode is not yet working, so 
+// is the documentation for the moment.
+//
+// The Flux is calculated in photons per mm^2 in the camera plane. 
+//
+// Currently, the following numbers are implemented:
+//
+// Area of PIN Diode   Ap: 63.5 +- 0.1 mm^2 
+// Transparency of window T: 0.88 +- 0.05
+//
+// Ratio of areas: 
+//
+// Distance of PIN Diode to pulser D1:   1.139  +- 0.005 m
+// Distance of Inner Pixel to pulser D2: 18.135 +- 0.015 m
+//
+//                          D1*D1
+// gkSolidAngleRatio   =   -------- = 7.06 * 10^-5
+//                         Ap*T*D2*D2
+//
+// gkSolidAngleRatioErr = 0.4 * 10^-5
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationChargePix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationChargePINDiode);
+
+using namespace std;
+
+const Float_t MCalibrationChargePINDiode::fgChargeToPhotons    = -1.; 
+const Float_t MCalibrationChargePINDiode::fgChargeToPhotonsErr = -1.; 
+const Float_t MCalibrationChargePINDiode::gkAbsorptionWindow   = 0.88; 
+const Float_t MCalibrationChargePINDiode::gkSolidAngleRatio    = 0.0000705;
+const Float_t MCalibrationChargePINDiode::gkSolidAngleRatioErr = 0.000004;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEGreen    = 0.84;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEBlue     = 0.74;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEUV       = 0.40;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQECT1      = 0.40;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEGreenErr = 0.015;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEBlueErr  = 0.015;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEUVErr    = 0.015;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQECT1Err   = 0.015;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - fCalibFlags to 0
+// - fChargeToPhotons to fgChargeToPhotons
+// - fChargeToPhotonsVar to fgChargeToPhotonsErr*fgChargeToPhotonsErr
+// 
+// Calls:
+// - Clear()
+//
+MCalibrationChargePINDiode::MCalibrationChargePINDiode(const char *name, const char *title)
+    : fCalibFlags(0)
+{
+
+  fName  = name  ? name  : "MCalibrationChargePINDiode";
+  fTitle = title ? title : "Container of the fit results of MHCalibrationChargePINDiode";
+
+  SetChargeToPhotons();
+  SetChargeToPhotonsErr();
+
+  Clear();
+
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all flags to kFALSE
+// - all variables to -1.
+//
+// Calls: 
+// - MCalibrationPix::Clear()
+//
+void MCalibrationChargePINDiode::Clear(Option_t *o)
+{
+
+  SetOscillating        ( kFALSE );
+  SetChargeFitValid     ( kFALSE );
+  SetTimeFitValid       ( kFALSE );
+  SetColor              ( MCalibrationCam::kNONE );
+    
+  fAbsTimeMean              =  -1.;
+  fAbsTimeRms               =  -1.;
+  fFluxOutsidePlexiglass    =  -1.;  
+  fFluxOutsidePlexiglassVar =  -1.;
+  fNumPhotons               =  -1.;
+  fNumPhotonsVar            =  -1.;
+  fPed                      =  -1.;
+  fPedRms                   =  -1.;
+  fRmsChargeMean            =  -1.;
+  fRmsChargeMeanErr         =  -1.;
+  fRmsChargeSigma           =  -1.;  
+  fRmsChargeSigmaErr        =  -1.;
+
+  MCalibrationPix::Clear();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the pedestals from outside
+//
+void MCalibrationChargePINDiode::SetPedestal(Float_t ped, Float_t pedrms)
+{
+
+  fPed    = ped;    
+  fPedRms = pedrms;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Oscillating Bit from outside 
+//
+void  MCalibrationChargePINDiode::SetOscillating( const Bool_t b)
+{
+    b ? SETBIT(fCalibFlags,kOscillating) : CLRBIT(fCalibFlags,kOscillating);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the ChargeFitValid Bit from outside 
+//
+void MCalibrationChargePINDiode::SetChargeFitValid(Bool_t b )    
+{ 
+  b ?  SETBIT(fCalibFlags, kChargeFitValid) : CLRBIT(fCalibFlags, kChargeFitValid); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the TimeFitValid Bit from outside 
+//
+void MCalibrationChargePINDiode::SetTimeFitValid(Bool_t b )    
+{ 
+  b ?  SETBIT(fCalibFlags, kTimeFitValid) : CLRBIT(fCalibFlags, kTimeFitValid); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the FluxOutsidePlexiglassAvailable Bit from outside 
+//
+void MCalibrationChargePINDiode::SetFluxOutsidePlexiglassAvailable (const Bool_t b)
+{
+  b ?  SETBIT(fCalibFlags, kFluxOutsidePlexiglassAvailable) 
+    : CLRBIT(fCalibFlags, kFluxOutsidePlexiglassAvailable); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fFluxOutsidePlexiglassVar is smaller than 0.
+// Return square root of fFluxOutsidePlexiglassVar
+// 
+Float_t MCalibrationChargePINDiode::GetFluxOutsidePlexiglassErr() const
+{
+  if (fFluxOutsidePlexiglassVar < 0.)
+    return -1.;
+  
+  return TMath::Sqrt(fFluxOutsidePlexiglassVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fFluxOutsidePlexiglassVar is smaller than 0.
+// Return -1 if fFluxOutsidePlexiglass is 0.
+// Return  fFluxOutsidePlexiglassVar / fFluxOutsidePlexiglass^2
+// 
+Float_t MCalibrationChargePINDiode::GetFluxOutsidePlexiglassRelVar() const
+{
+  if (fFluxOutsidePlexiglassVar < 0.)
+    return -1.;
+  
+  if (fFluxOutsidePlexiglass == 0.)
+    return -1.;
+  
+  return fFluxOutsidePlexiglassVar / (fFluxOutsidePlexiglass * fFluxOutsidePlexiglass );
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fNumPhotonsVar is smaller than 0.
+// Return square root of fNumPhotonsVar
+// 
+Float_t MCalibrationChargePINDiode::GetNumPhotonsErr() const
+{
+  if (fNumPhotonsVar < 0.)
+    return -1.;
+  
+  return TMath::Sqrt(fNumPhotonsVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if fNumPhotonsVar is smaller than 0.
+// Return -1 if fNumPhotons    is 0.
+// Return fNumPhotonsVar / (fNumPhotons^2 )
+// 
+Float_t MCalibrationChargePINDiode::GetNumPhotonsRelVar() const
+{
+  if (fNumPhotonsVar < 0.)
+    return -1.;
+  
+  if (fNumPhotons  == 0.)
+    return -1.;
+  
+  return  fNumPhotonsVar / fNumPhotons / fNumPhotons ;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPINDiodeQEGreenErr is smaller than 0.
+// Return -1 if gkPINDiodeQEGreen    is 0.
+// Return gkPINDiodeQEGreenErr^2 / (gkPINDiodeQEGreen^2 )
+// 
+const Float_t MCalibrationChargePINDiode::GetPINDiodeQEGreenRelVar() const
+{
+  if (gkPINDiodeQEGreenErr < 0.)
+    return -1.;
+  
+  if (gkPINDiodeQEGreen  == 0.)
+    return -1.;
+  
+  return gkPINDiodeQEGreenErr * gkPINDiodeQEGreenErr / gkPINDiodeQEGreen / gkPINDiodeQEGreen ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPINDiodeQEBlueErr is smaller than 0.
+// Return -1 if gkPINDiodeQEBlue    is 0.
+// Return gkPINDiodeQEBlueErr^2 / gkPINDiodeQEBlue^2
+// 
+const Float_t MCalibrationChargePINDiode::GetPINDiodeQEBlueRelVar() const
+{
+  if (gkPINDiodeQEBlueErr < 0.)
+    return -1.;
+  
+  if (gkPINDiodeQEBlue  == 0.)
+    return -1.;
+  
+  return gkPINDiodeQEBlueErr * gkPINDiodeQEBlueErr / gkPINDiodeQEBlue / gkPINDiodeQEBlue ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPINDiodeQEUVErr is smaller than 0.
+// Return -1 if gkPINDiodeQEUV    is 0.
+// Return gkPINDiodeQEUVErr ^2 / gkPINDiodeQEUV^2 
+// 
+const Float_t MCalibrationChargePINDiode::GetPINDiodeQEUVRelVar() const
+{
+  if (gkPINDiodeQEUVErr < 0.)
+    return -1.;
+  
+  if (gkPINDiodeQEUV  == 0.)
+    return -1.;
+  
+  return gkPINDiodeQEUVErr * gkPINDiodeQEUVErr / gkPINDiodeQEUV / gkPINDiodeQEUV ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPINDiodeQECT1Err is smaller than 0.
+// Return -1 if gkPINDiodeQECT1    is 0.
+// Return gkPINDiodeQECT1Err ^2 / gkPINDiodeQECT1^2
+// 
+const Float_t MCalibrationChargePINDiode::GetPINDiodeQECT1RelVar() const
+{
+  if (gkPINDiodeQECT1Err < 0.)
+    return -1.;
+  
+  if (gkPINDiodeQECT1  == 0.)
+    return -1.;
+  
+  return gkPINDiodeQECT1Err * gkPINDiodeQECT1Err / gkPINDiodeQECT1 / gkPINDiodeQECT1 ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkSolidAngleRatioErr is smaller than 0.
+// Return -1 if gkSolidAngleRatio    is 0.
+// Return gkSolidAngleRatioErr ^2 / gkSolidAngleRatio^2
+// 
+const Float_t MCalibrationChargePINDiode::GetSolidAngleRatioRelVar() const
+{
+  if (gkSolidAngleRatioErr < 0.)
+    return -1.;
+  
+  if (gkSolidAngleRatio  == 0.)
+    return -1.;
+  
+  return gkSolidAngleRatioErr * gkSolidAngleRatioErr / gkSolidAngleRatio / gkSolidAngleRatio ;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Test bit kChargeFitValid
+//
+Bool_t MCalibrationChargePINDiode::IsChargeFitValid() const 
+{
+  return TESTBIT(fCalibFlags, kChargeFitValid);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kFluxOutsidePlexiglassAvailable
+//
+Bool_t  MCalibrationChargePINDiode::IsFluxOutsidePlexiglassAvailable()   const
+{
+  return TESTBIT(fFlags,kFluxOutsidePlexiglassAvailable);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Test bit kTimeFitValid
+//
+Bool_t MCalibrationChargePINDiode::IsTimeFitValid()   const 
+{
+  return TESTBIT(fCalibFlags, kTimeFitValid);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kOscillating
+//
+Bool_t MCalibrationChargePINDiode::IsOscillating()   const 
+{
+  return TESTBIT(fCalibFlags, kOscillating);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Return kFALSE if IsChargeFitValid() is kFALSE
+//
+// Calculate fFluxOutsidePlexiglass with the formula:
+// - fFluxOutsidePlexiglass    = fNumPhotons*gkSolidAngleRatio / gkPINDiodeQE (of the corr. colour) 
+// - fFluxOutsidePlexiglassVar = sqrt( fNumPhotonsVar / ( fNumPhotons * fNumPhotons ) 
+//                             + ( gkSolidAngleRatioErr * gkSolidAngleRatioErr / gkSolidAngleRatio / gkSolidAngleRatio )
+//                             + ( gkPINDiodeQEErr * gkPINDiodeQEErr / gkPINDiodeQE / gkPINDiodeQE )
+//                               ) * fFluxOutsidePlexiglass * * fFluxOutsidePlexiglass
+//
+// If the fFluxOutsidePlexiglass is smaller than 0., return kFALSE
+// If the Variance is smaller than 0., return kFALSE
+//
+// SetFluxOutsidePlexiglassAvailable() and return kTRUE
+//
+Bool_t MCalibrationChargePINDiode::CalcFluxOutsidePlexiglass()
+{
+
+  if (IsChargeFitValid())
+    return kFALSE;
+  
+  //
+  // Start calculation of number of photons per mm^2 on an inner pixel:
+  // Correct for the distance between camera and PIN Diode and for different areas.
+  //
+  switch (fColor)
+    {
+    case MCalibrationCam::kGREEN:
+      fFluxOutsidePlexiglass    = fNumPhotons           * gkSolidAngleRatio           * gkPINDiodeQEGreen;
+      fFluxOutsidePlexiglassVar = GetNumPhotonsRelVar() + GetSolidAngleRatioRelVar()  + GetPINDiodeQEGreenRelVar();
+      break;
+    case MCalibrationCam::kBLUE:
+      fFluxOutsidePlexiglass    = fNumPhotons           * gkSolidAngleRatio           * gkPINDiodeQEBlue;
+      fFluxOutsidePlexiglassVar = GetNumPhotonsRelVar() + GetSolidAngleRatioRelVar()  + GetPINDiodeQEBlueRelVar();
+      break; 
+    case MCalibrationCam::kUV:
+      fFluxOutsidePlexiglass    = fNumPhotons           * gkSolidAngleRatio          * gkPINDiodeQEUV;
+      fFluxOutsidePlexiglassVar = GetNumPhotonsRelVar() + GetSolidAngleRatioRelVar() + GetPINDiodeQEUVRelVar();
+      break;
+    case MCalibrationCam::kCT1:
+    default:
+      fFluxOutsidePlexiglass    = fNumPhotons           * gkSolidAngleRatio          * gkPINDiodeQECT1;
+      fFluxOutsidePlexiglassVar = GetNumPhotonsRelVar() + GetSolidAngleRatioRelVar() + GetPINDiodeQECT1RelVar();
+      break;
+    }
+
+  //
+  // Finish calculation of errors -> convert from relative variance to absolute variance
+  //
+  fFluxOutsidePlexiglassVar *= fFluxOutsidePlexiglass * fFluxOutsidePlexiglass;
+
+  if (fFluxOutsidePlexiglass < 0.)
+      return kFALSE;
+
+  if (fFluxOutsidePlexiglassVar < 0.)
+      return kFALSE;
+
+  SetFluxOutsidePlexiglassAvailable();  
+
+  *fLog << inf << endl;
+  *fLog << inf << " Mean Photon flux [ph/mm^2] outside Plexiglass: " 
+        << Form("%5.3f%s%5.3f",fFluxOutsidePlexiglass," +- ",GetFluxOutsidePlexiglassErr()) << endl;
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationChargePINDiode.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationChargePINDiode.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationChargePINDiode.h	(revision 9772)
@@ -0,0 +1,114 @@
+#ifndef MARS_MCalibrationChargePINDiode
+#define MARS_MCalibrationChargePINDiode
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationChargePINDiode : public MCalibrationPix
+{
+private:
+
+  static const Float_t fgChargeToPhotons;     //! Default for fChargeToPhotons
+  static const Float_t fgChargeToPhotonsErr;  //! Default for fChargeToPhotonsVar
+  static const Float_t gkPINDiodeQEGreen;     //! Quantum Efficiency at 520 nm
+  static const Float_t gkPINDiodeQEBlue;      //! Quantum Efficiency at 460 nm
+  static const Float_t gkPINDiodeQEUV;        //! Quantum Efficiency at 370 nm
+  static const Float_t gkPINDiodeQECT1;       //! Quantum Efficiency at 370 nm
+  static const Float_t gkPINDiodeQEGreenErr;  //! Uncertainty QE at 520 nm
+  static const Float_t gkPINDiodeQEBlueErr;   //! Uncertainty QE at 460 nm
+  static const Float_t gkPINDiodeQEUVErr;     //! Uncertainty QE at 370 nm
+  static const Float_t gkPINDiodeQECT1Err;    //! Uncertainty QE at 370 nmu
+  static const Float_t gkAbsorptionWindow;    //! Absorption of the protection window (incl. EMS-wires)
+  static const Float_t gkSolidAngleRatio;     //! Solid angles ratio PIN Diode - inner pixel
+  static const Float_t gkSolidAngleRatioErr;  //! Error solid angle ratio PIN Diode - inn. pix.
+
+  Float_t fAbsTimeMean;               // Mean Absolute Arrival Time
+  Float_t fAbsTimeRms;                // RMS Mean Absolute Arrival Time
+  Byte_t  fCalibFlags;                // Bit-field for the class-own bits
+  Float_t fChargeLimit;               // Limit (in units of PedRMS) for acceptance fitted mean charge
+  Float_t fChargeErrLimit;            // Limit (in units of PedRMS) for acceptance fitted charge sigma
+  Float_t fChargeRelErrLimit;         // Limit (in units of Error of fitted charge) for acceptance fitted mean  
+  Float_t fChargeToPhotons;           // Mean conv. PIN Diode charge to number of incident photons
+  Float_t fChargeToPhotonsVar;        // Variance of mean conv. PIN Diode charge to nr. incident photons
+  Float_t fNumPhotons;                // Number photons incidident on PIN Diode
+  Float_t fNumPhotonsVar;             // Variance nr. photons incid. on PIN Diode
+  Float_t fFluxOutsidePlexiglass;     // Mean number photons in INNER PIXEL outside plexiglass
+  Float_t fFluxOutsidePlexiglassVar;  // Error on nr. photons in INNER PIXEL outside plexiglass
+  Float_t fPed;                       // Mean pedestal (from MPedestalPix)
+  Float_t fPedRms;                    // Pedestal  RMS (from MPedestalPix)
+  Float_t fRmsChargeMean;             // Mean of RMS of summed FADC slices distribution 
+  Float_t fRmsChargeMeanErr;          // Error on Mean RMS summed FADC slices distribution 
+  Float_t fRmsChargeSigma;            // Sigma of RMS of summed FADC slices distribution    
+  Float_t fRmsChargeSigmaErr;         // Error on Sigma RMS summed FADC slices distribution 
+  MCalibrationCam::PulserColor_t fColor; // Colour of the pulsed LEDs
+
+  enum  { kOscillating,
+          kChargeFitValid, kTimeFitValid, 
+	  kFluxOutsidePlexiglassAvailable  }; // Possible bits to be set
+
+  const Float_t GetPINDiodeQEGreenRelVar() const; 
+  const Float_t GetPINDiodeQEBlueRelVar () const; 
+  const Float_t GetPINDiodeQEUVRelVar   () const; 
+  const Float_t GetPINDiodeQECT1RelVar  () const;
+  const Float_t GetSolidAngleRatioRelVar() const; 
+
+ public:
+
+  MCalibrationChargePINDiode(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationChargePINDiode() {}
+  
+  void   Clear(Option_t *o="");
+  Bool_t CalcFluxOutsidePlexiglass();
+
+  // Getters
+  Float_t GetAbsTimeMean                  () const { return fAbsTimeMean;           }
+  Float_t GetAbsTimeRms                   () const { return fAbsTimeRms;            }
+  MCalibrationCam::PulserColor_t GetColor () const { return fColor;                 }
+  Float_t GetFluxOutsidePlexiglass        () const { return fFluxOutsidePlexiglass; }
+  Float_t GetFluxOutsidePlexiglassErr     () const;
+  Float_t GetFluxOutsidePlexiglassRelVar  () const;  
+  Float_t GetNumPhotons                   () const { return fNumPhotons;            } 
+  Float_t GetNumPhotonsErr                () const;
+  Float_t GetNumPhotonsRelVar             () const;
+  Float_t GetPed                          () const { return fPed;                   }
+  Float_t GetPedRms                       () const { return fPedRms;                }
+
+  Bool_t  IsChargeFitValid                () const;
+  Bool_t  IsTimeFitValid                  () const;
+  Bool_t  IsOscillating                   () const;
+  Bool_t  IsFluxOutsidePlexiglassAvailable() const;
+  
+  // Setters
+  void SetAbsTimeMean        ( const Float_t f      )                 { fAbsTimeMean        = f;   }
+  void SetAbsTimeRms         ( const Float_t f      )                 { fAbsTimeRms         = f;   }
+  void SetChargeToPhotons    ( const Float_t f=fgChargeToPhotons    ) { fChargeToPhotons    = f;   }  
+  void SetChargeToPhotonsErr ( const Float_t f=fgChargeToPhotonsErr ) { fChargeToPhotonsVar = f*f; }  
+  void SetColor              ( const MCalibrationCam::PulserColor_t color) { fColor = color;   }
+  void SetPedestal           (       Float_t ped, Float_t pedrms    );
+  void SetRmsChargeMean      ( const Float_t f      )                 { fRmsChargeMean      = f;   }
+  void SetRmsChargeMeanErr   ( const Float_t f      )                 { fRmsChargeMeanErr   = f;   }
+  void SetRmsChargeSigma     ( const Float_t f      )                 { fRmsChargeSigma     = f;   }
+  void SetRmsChargeSigmaErr  ( const Float_t f      )                 { fRmsChargeSigmaErr  = f;   }
+  void SetOscillating        ( const Bool_t b=kTRUE );
+  void SetChargeFitValid     ( const Bool_t b=kTRUE );
+  void SetTimeFitValid       ( const Bool_t b=kTRUE );
+  void SetFluxOutsidePlexiglassAvailable ( const Bool_t b = kTRUE );
+
+  ClassDef(MCalibrationChargePINDiode, 1)	// Container Charge Calibration Results PIN Diode
+};
+
+#endif   /* MARS_MCalibrationChargePINDiode */
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationChargePix.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationChargePix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationChargePix.cc	(revision 9772)
@@ -0,0 +1,1077 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         
+// MCalibrationChargePix                                                   
+//                                                                         
+// Storage container of the calibrated Charge of one pixel.
+//                                                                         
+// The following values are initialized to meaningful values:
+//
+// - The Electronic Rms to 1.5 per FADC slice
+// - The uncertainty about the Electronic RMS to 0.3 per slice
+// - The F-Factor is assumed to have been measured in Munich to 1.13 - 1.17.
+//   with the Munich definition of the F-Factor, thus:
+//   F = Sigma(Out)/Mean(Out) * Mean(In)/Sigma(In)
+//   Mean F-Factor (gkFFactor)     = 1.15
+//   Error F-Factor (gkFFactorErr) = 0.02
+//
+// The following variables are calculated inside this class:
+// -  fLoGainPedRmsSquare and fLoGainPedRmsSquareVar (see CalcLoGainPedestal())
+// -  fRSigmaSquare and fRSigmaSquareVar             (see CalcReducedSigma()  )
+// -  fPheFFactorMethod and fPheFFactorMethodVar     (see CalcFFactor()       )
+// -  fMeanConvFADC2Phe and fMeanConvFADC2PheVar     (see CalcConvFFactor()  )
+//
+// The following variables are set by MHCalibrationChargeCam:
+// -  fAbsTimeMean and fAbsTimeRms
+// -  all variables in MCalibrationPix
+//
+// The following variables are set by MCalibrationChargeCalc:
+// - fPed, fPedVar and fPedRms                         
+// - fMeanConvFADC2Phe
+// - fConvFADC2PheVar 
+// - fSigmaConvFADC2Phe
+// - fTotalFFactorFFactorMethod 
+// - fTotalFFactorFFactorMethodVar 
+//
+// The following variables are not yet implemented:
+// - fConversionHiLo and fConversionHiLoVar (now set fixed to 10. +- 2.5)
+//
+//  Error of all variables are calculated by error-propagation. Note that internally, 
+//  all error variables contain Variances in order to save the CPU-intensive square rooting 
+// 
+//  Low-Gain variables are stored internally unconverted, i.e. directly from the summed 
+//  FADC slices extraction results, but can be retrieved converted to High-Gain amplifications 
+//  by calls to: GetConvertedMean() or GetConvertedSigma()
+// 
+// See also: MCalibrationChargeCam, MCalibrationChargeCalc,
+//           MHCalibrationChargeCam, MHCalibrationChargePix
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargePix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MBadPixelsPix.h"
+
+ClassImp(MCalibrationChargePix);
+
+using namespace std;
+
+const Float_t MCalibrationChargePix::gkElectronicPedRms    = 1.0;
+const Float_t MCalibrationChargePix::gkElectronicPedRmsErr = 0.35;
+const Float_t MCalibrationChargePix::gkFFactor             = 1.15;
+const Float_t MCalibrationChargePix::gkFFactorErr          = 0.02;
+
+const Float_t MCalibrationChargePix::fgConversionHiLo           = 10.;
+const Float_t MCalibrationChargePix::fgConversionHiLoErr        = 2.5;
+const Float_t MCalibrationChargePix::fgPheFFactorMethodLimit    = 1.;
+const Float_t MCalibrationChargePix::fgConvFFactorRelErrLimit   = 0.85;
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Sets:
+// - fCalibFlags to 0
+// - fConversionHiLo to fgConversionHiLo
+// - fConversionHiLoVar to square of fgConversionHiLoErr
+// - fConvFFactorelErrLimit to fgConvFFactorRelErrLimit*fgConvFFactorelErrLimit
+// - fPheFFactorLimit to fgPheFFactorLimit
+// 
+// Calls:
+// - Clear()
+//
+MCalibrationChargePix::MCalibrationChargePix(const char *name, const char *title)
+    : fCalibFlags(0)
+{
+
+  fName  = name  ? name  : "MCalibrationChargePix";
+  fTitle = title ? title : "Container of the fit results of MHCalibrationChargePixs ";
+
+  //
+  // At the moment, we don't have a database, yet, 
+  // so we get it from the configuration file
+  //
+  SetConversionHiLo();
+  SetConversionHiLoErr();
+
+  SetPheFFactorMethodLimit();
+  SetConvFFactorRelErrLimit();
+  
+  Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all flags to kFALSE
+// - all variables to -1.
+//
+// Calls: 
+// - MCalibrationPix::Clear()
+//
+void MCalibrationChargePix::Clear(Option_t *o)
+{
+
+  SetFFactorMethodValid     ( kFALSE );
+
+  fRSigmaSquare                     =  -1.;
+  fRSigmaSquareVar                  =  -1.;
+  
+  fPed                              =  -1.;
+  fPedRms                           =  -1.;
+  fPedVar                           =  -1.;
+
+  fLoGainPedRmsSquare               =  -1.;
+  fLoGainPedRmsSquareVar            =  -1.;
+
+  fAbsTimeMean                      =  -1.;
+  fAbsTimeRms                       =  -1.;
+
+  fPheFFactorMethod                 =  -1.;
+  fPheFFactorMethodVar              =  -1.;
+
+  fMeanConvFADC2Phe                 =  -1.;
+  fMeanConvFADC2PheVar              =  -1.;
+  fMeanFFactorFADC2Phot             =  -1.;
+  fMeanFFactorFADC2PhotVar          =  -1.;  
+
+  MCalibrationPix::Clear();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set F-Factor Method Validity Bit from outside 
+//
+void MCalibrationChargePix::SetFFactorMethodValid(const Bool_t b )
+{ 
+  b ?  SETBIT(fCalibFlags, kFFactorMethodValid) : CLRBIT(fCalibFlags, kFFactorMethodValid); 
+}    
+
+// --------------------------------------------------------------------------
+//
+// Set pedestals from outside (done by MCalibrationChargeCalc)
+//
+void MCalibrationChargePix::SetPedestal(const Float_t ped, const Float_t pedrms, const Float_t pederr)
+{
+
+  fPed       = ped;    
+  fPedRms    = pedrms;
+  fPedVar    = pederr*pederr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set pedestals from outside (done by MCalibrationChargeCalc)
+//
+void MCalibrationChargePix::SetPed(const Float_t ped, const Float_t pederr)
+{
+
+  fPed       = ped;    
+  fPedVar    = pederr*pederr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set pedestals RMS from outside (done by MHCalibrationChargeCam)
+//
+void MCalibrationChargePix::SetPedRMS( const Float_t pedrms, const Float_t pedrmserr)
+{
+  
+  fPedRms    = pedrms;
+  fPedRmsVar = pedrmserr*pedrmserr;
+  
+}
+
+
+// -------------------------------------------------------------------------------
+//
+// Get the conversion Error Hi-Gain to Low-Gain:
+// - If fConversionHiLoVar is smaller than 0 (i.e. has not yet been set), return -1.
+//  
+Float_t MCalibrationChargePix::GetConversionHiLoErr()  const
+{
+  if (fConversionHiLoVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fConversionHiLoVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance of the conversion factor between higain and logain:
+// - If fConversionHiLo    is 0,              return -1.
+// - If fConversionHiLoVar is smaller than 0, return -1.
+// - Else returns: fConversionHiLoVar / fConversionHiLo^2
+//
+const Float_t MCalibrationChargePix::GetConversionHiLoRelVar() const 
+{
+
+  if (fConversionHiLoVar < 0.)
+    return -1.;
+
+  if (fConversionHiLo == 0.)
+    return -1.;
+
+  return fConversionHiLoVar / (fConversionHiLo * fConversionHiLo);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance of the electronics pedestal RMS
+// - returns rel. variance of gkElectronicPedRms
+//
+const Float_t MCalibrationChargePix::GetElectronicPedRmsRelVar() const 
+{
+  return gkElectronicPedRmsErr * gkElectronicPedRmsErr / gkElectronicPedRms / gkElectronicPedRms;
+}
+ 
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance of the conversion factor between higain and logain:
+// - If gkFFactor    is 0,              return -1.
+// - If gkFFactorErr is smaller than 0, return -1.
+// - Else returns: gkFFactorErr^2 / gkFFactor*^2
+//
+const Float_t MCalibrationChargePix::GetFFactorRelVar() const 
+{
+
+  if (gkFFactorErr < 0.)
+    return -1.;
+
+  if (gkFFactor == 0.)
+    return -1.;
+
+  return gkFFactorErr * gkFFactorErr / (gkFFactor * gkFFactor);
+}
+ 
+
+// --------------------------------------------------------------------------
+//
+// Get the pedestals RMS: 
+// - Test bit kHiGainSaturation: 
+//   If yes, return square root of fLoGainPedRmsSquare (if greater than 0, otherwise -1.), 
+//   If no,  return fPedRms
+//
+Float_t  MCalibrationChargePix::GetPedRms()  const
+{
+
+  if (IsHiGainSaturation())
+    if (fLoGainPedRmsSquare < 0.)
+      return -1.;
+    else
+      return TMath::Sqrt(fLoGainPedRmsSquare);
+  
+  return fPedRms;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Error of the pedestals RMS: 
+// - Test bit kHiGainSaturation: 
+//   If yes, return square root of (0.25*fLoGainPedRmsSquareVar/ fLoGainPedRmsSquare) (if greater than 0, otherwise -1.)
+//   If no , return square root of (fPedVar) (if greater than 0, otherwise -1.), divided by 2. 
+//
+Float_t  MCalibrationChargePix::GetPedRmsErr()  const
+{
+  if (IsHiGainSaturation())
+    if (fLoGainPedRmsSquareVar < 0.)
+      return -1.;
+    else
+      return TMath::Sqrt(0.25*fLoGainPedRmsSquareVar/fLoGainPedRmsSquare);
+  else
+    if (fPedVar < 0.)
+      return -1.;
+    else
+      return TMath::Sqrt(fPedVar)/2.;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Mean Charge converted to High Gain amplification: 
+// Returns fLoGainMean multiplied with fConversionHiLo if IsHiGainSaturation(), 
+//         else return fHiGainMean
+//
+Float_t MCalibrationChargePix::GetConvertedMean()  const 
+{
+
+  if (IsHiGainSaturation())
+    return fLoGainMean * fConversionHiLo;
+
+  return fHiGainMean;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Error of the converted Low Gain Mean: 
+//
+// Returns -1 if the variable fLoGainMean or fLoGainMeanVar are smaller than 0.
+//
+// Returns the square root of the quadratic sum of the relative variances of 
+// the fLoGainMean and fConversionHiLo, mulitplied with GetConvertedMean()
+// in case of HiGain Saturation, 
+// else return GetMeanErr()
+//
+Float_t MCalibrationChargePix::GetConvertedMeanErr()  const
+{
+
+  if (IsHiGainSaturation())
+    {
+      const Float_t logainrelvar = GetLoGainMeanRelVar();
+      
+      if (logainrelvar < 0.)
+        return -1.;
+
+      return TMath::Sqrt(logainrelvar + GetConversionHiLoRelVar()) * GetConvertedMean();
+    }
+  else
+    return GetMeanErr();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Sigma converted to High Gain amplification: 
+// Returns fLoGainSigma multiplied with fConversionHiLo if IsHiGainSaturation()
+// else return fHiGainSigma
+//
+Float_t MCalibrationChargePix::GetConvertedSigma()  const 
+{
+  
+  if (IsHiGainSaturation())
+    return fLoGainSigma * fConversionHiLo;
+  else
+    return fHiGainSigma;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Error of the converted Sigma: 
+//
+// Returns -1 if the variable fLoGainSigma or fLoGainSigmaVar are smaller than 0.
+//
+// if IsHiGainSaturatio()
+// returns the square root of the quadratic sum of the relative variances of 
+// the fLoGainSigma and fConversionHiLo, mulitplied with GetConvertedSigma()
+// else returns GetSigmaErr()
+//
+Float_t MCalibrationChargePix::GetConvertedSigmaErr()  const
+{
+
+  if (IsHiGainSaturation())
+    {
+      if (fLoGainSigmaVar < 0.)
+        return -1.;
+      
+      if (fLoGainSigma < 0.)
+        return -1.;
+      
+      const Float_t sigmaRelVar =  fLoGainSigmaVar
+                                /( fLoGainSigma * fLoGainSigma );
+
+      return TMath::Sqrt(sigmaRelVar+GetConversionHiLoRelVar()) * GetConvertedSigma();
+    }
+  else
+    return GetSigmaErr();
+
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the converted reduced Sigma: 
+// - If fRSigmaSquare is smaller than 0 (i.e. has not yet been set), return -1.
+// - Test bit kHiGainSaturation: 
+//   If yes, return square root of fRSigmaSquare, multiplied with fConversionHiLo, 
+//   If no , return square root of fRSigmaSquare
+//
+Float_t MCalibrationChargePix::GetConvertedRSigma()  const
+{
+  if (fRSigmaSquare < 0)
+    return -1;
+
+  const Float_t rsigma = TMath::Sqrt(fRSigmaSquare);
+  
+  return IsHiGainSaturation() ? rsigma*fConversionHiLo : rsigma ;
+} 
+
+// --------------------------------------------------------------------------
+//
+// Get the error of the converted reduced Sigma: 
+// - If fRSigmaSquareVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Calculate the absolute variance of the reduced sigma with the formula:
+//   reduced sigma variance = 0.25 * fRSigmaSquareVar / fRSigmaSquare
+// - Test bit kHiGainSaturation: 
+//   If yes, returns the square root of the quadratic sum of the relative variances of the 
+//           reduced sigma and fConversionHiLo, mulitplied with GetRSigma()
+//   Else returns the square root of rel. (0.25*fRSigmaSquareVar / fRSigmaSquare)
+//
+Float_t MCalibrationChargePix::GetConvertedRSigmaErr()  const
+{
+
+  if (fRSigmaSquareVar < 0)
+    return -1;
+
+  //
+  // SigmaSquareVar = 4. * Sigma * Sigma * Var(sigma)
+  // ==> Var(sigma) = 0.25 * SigmaSquareVar / (Sigma * Sigma)
+  //
+  const Float_t rsigmaVar = 0.25 * fRSigmaSquareVar / fRSigmaSquare;
+
+  if (IsHiGainSaturation())
+    return TMath::Sqrt(rsigmaVar/fRSigmaSquare + GetConversionHiLoRelVar()) * GetRSigma();
+  else
+    return TMath::Sqrt(rsigmaVar);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the reduced Sigma: 
+// - If fRSigmaSquare is smaller than 0 (i.e. has not yet been set), return -1.
+//
+Float_t MCalibrationChargePix::GetRSigma()  const
+{
+  if (fRSigmaSquare < 0)
+    return -1;
+
+  return TMath::Sqrt(fRSigmaSquare);
+  
+} 
+
+// --------------------------------------------------------------------------
+//
+// Get the error of the reduced Sigma: 
+// - If fRSigmaSquareVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Calculate the absolute variance of the reduced sigma with the formula:
+//   reduced sigma variance = 0.25 * fRSigmaSquareVar / fRSigmaSquare
+//
+Float_t MCalibrationChargePix::GetRSigmaErr()  const
+{
+
+  if (fRSigmaSquareVar < 0)
+    return -1;
+
+  //
+  // SigmaSquareVar = 4. * Sigma * Sigma * Var(sigma)
+  // ==> Var(sigma) = 0.25 * SigmaSquareVar / (Sigma * Sigma)
+  //
+  return TMath::Sqrt(0.25 * fRSigmaSquareVar / fRSigmaSquare);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the reduced Sigma per Charge: 
+// - If GetRSigma() is smaller or equal 0. (i.e. has not yet been set), return -1.
+// - If GetMean() is 0. or -1. (i.e. has not yet been set), return -1.
+// - Return GetRSigma() / GetMean() 
+//
+Float_t MCalibrationChargePix::GetRSigmaPerCharge()  const 
+{
+  
+  const Float_t rsigma = GetRSigma();
+
+  if (rsigma <= 0)
+    return -1.;
+  
+
+  const Float_t mean   = GetMean();
+  
+  if (mean == 0. || mean == -1.)
+    return -1.;
+  
+  return rsigma / mean;
+} 
+
+
+// --------------------------------------------------------------------------
+//
+// Get the error of the reduced Sigma per Charge: 
+// - If GetRSigmaRelVar() is smaller or equal 0. (i.e. has not yet been set), return -1.
+// - If GetMeanRelVar() is smaller or equal 0. (i.e. has not yet been set), return -1.
+// - Return the propagated error of GetRSigmaPerCharge() 
+//
+Float_t MCalibrationChargePix::GetRSigmaPerChargeErr()  const 
+{
+  
+  const Float_t rsigmarelvar  = GetRSigmaRelVar();
+
+  if (rsigmarelvar <= 0)
+    return -1.;
+  
+
+  const Float_t meanrelvar   = GetMeanRelVar();
+  
+  if (meanrelvar <= 0.)
+    return -1.;
+  
+  return TMath::Sqrt(rsigmarelvar + meanrelvar) * GetRSigmaPerCharge();
+} 
+
+// --------------------------------------------------------------------------
+//
+// Get the reduced Sigma Square: 
+// - If fRSigmaSquare is smaller than 0 (i.e. has not yet been set), return -1.
+// - Test bit kHiGainSaturation: 
+//   If yes, return fRSigmaSquare, multiplied with fConversionHiLo^2, 
+//   If no , return fRSigmaSquare
+//
+Float_t MCalibrationChargePix::GetConvertedRSigmaSquare()  const
+{
+  if (fRSigmaSquare < 0)
+    return -1;
+
+  return IsHiGainSaturation() ? fRSigmaSquare*fConversionHiLo*fConversionHiLo : fRSigmaSquare ;
+} 
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance of the reduced Sigma: 
+// - If fRSigmaSquareVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Calculate the relative variance of the reduced sigma squares with the formula:
+//   reduced sigma rel. variance = 0.25 * fRSigmaSquareVar / fRSigmaSquare / fRSigmaSquare
+// - Test bit kHiGainSaturation: 
+//   If yes, returns the sum of the relative variances of the reduced sigma and fConversionHiLo
+//   Else returns the relative variance of the reduced sigma
+//
+Float_t MCalibrationChargePix::GetRSigmaRelVar()  const
+{
+
+  if (fRSigmaSquareVar < 0)
+    return -1;
+
+  //
+  // SigmaSquareVar = 4. * Sigma * Sigma * Var(sigma)
+  // ==> Var(sigma) = 0.25 * SigmaSquareVar / (Sigma * Sigma)
+  //
+  return 0.25 * fRSigmaSquareVar / ( fRSigmaSquare * fRSigmaSquare );
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the error on the number of photo-electrons (F-Factor Method):
+// - If fPheFFactorMethodVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Else returns the square root of fPheFFactorMethodVar
+//
+Float_t MCalibrationChargePix::GetPheFFactorMethodErr()  const
+{
+  if (fPheFFactorMethodVar < 0.)
+    return -1.;
+  return TMath::Sqrt(fPheFFactorMethodVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the error on the mean total F-Factor of the signal readout (F-Factor Method):
+// - If fMeanFFactorFADC2PhotVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Else returns the square root of fMeanFFactorFADC2PhotVar
+//
+Float_t MCalibrationChargePix::GetMeanFFactorFADC2PhotErr()  const
+{
+  if (fMeanFFactorFADC2PhotVar < 0.)
+    return -1.;
+  return TMath::Sqrt(fMeanFFactorFADC2PhotVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the relative variance on the number of photo-electrons (F-Factor Method):
+// - If fPheFFactorMethodVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - If fPheFFactorMethod    is 0, return -1.
+// - Else returns fPheFFactorMethodVar / fPheFFactorMethod^2
+//
+Float_t MCalibrationChargePix::GetPheFFactorMethodRelVar()  const
+{
+  if (fPheFFactorMethodVar < 0.)
+    return -1.;
+  if (fPheFFactorMethod  == 0.)
+    return -1.;
+
+  return fPheFFactorMethodVar / (fPheFFactorMethod * fPheFFactorMethod);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the error on the mean conversion factor (FFactor  Method):
+// - If fMeanConvFADC2PheVar is smaller than 0 (i.e. has not yet been set), return -1.
+// - Else returns the square root of fMeanConvFADC2PheVar
+//
+Float_t MCalibrationChargePix::GetMeanConvFADC2PheErr()  const
+{
+  if (fMeanConvFADC2PheVar < 0.)
+    return -1.;
+  return TMath::Sqrt(fMeanConvFADC2PheVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kFFactorMethodValid
+//
+Bool_t MCalibrationChargePix::IsFFactorMethodValid()   const
+{ 
+  return TESTBIT(fCalibFlags, kFFactorMethodValid);     
+}
+
+
+// ----------------------------------------------------------------------------
+// 
+// - If fSigma  is smaller than 0 (i.e. has not yet been set), return kFALSE
+// - If fPedRms is smaller than 0 (i.e. has not yet been set), return kFALSE
+//
+// Calculate the reduced sigma of the low-Gain FADC slices:
+// - Test bit IsHiGainSaturation() for the Sigma: 
+//   If yes, take fLoGainSigma and fLoGainSigmaVar 
+//   If no , take fHiGainSigma and fHiGainSigmaVar 
+//
+// - Test bit IsHiGainSaturation() for the pedRMS: 
+//   If yes, take fLoGainPedRmsSquare and fLoGainPedRmsSquareVar
+//   If no , take fPedRms and fPedVar
+//
+// - Calculate the reduced sigma with the formula:
+//   fRSigmaSquare = Sigma*Sigma - pedRMS*pedRMS
+// 
+// - If fRSigmaSquare is smaller than 0, give a warning and return kFALSE
+//
+// - Calculate the variance of the reduced sigma with the formula:
+//   fRSigmaSquareVar = 4.* (sigmaVar*Sigma*Sigma + pedRmsVar*pedRMS*pedRMS)
+//
+// A back-transformation to the corr. amplification factor of the High-Gain is done 
+// in GetRSigma() and GetRSigmaErr()
+//
+Bool_t MCalibrationChargePix::CalcReducedSigma()
+{
+
+  if (GetSigma() < 0.)
+    return kFALSE;
+  
+  if (GetPedRms() < 0.)
+    return kFALSE;
+
+  const Float_t sigma           = IsHiGainSaturation() ? fLoGainSigma           : fHiGainSigma   ;
+  const Float_t sigmavar        = IsHiGainSaturation() ? fLoGainSigmaVar        : fHiGainSigmaVar;
+  const Float_t pedRmsSquare    = IsHiGainSaturation() ? fLoGainPedRmsSquare    : fPedRms*fPedRms;
+  const Float_t pedRmsSquareVar = IsHiGainSaturation() ? fLoGainPedRmsSquareVar : 0.25*fPedVar*pedRmsSquare;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " HiGainSaturation: " << IsHiGainSaturation() 
+            << " Sigma: " << sigma 
+            << " Var.Sigma: " << sigmavar
+            << " PedRmsSquare: " << pedRmsSquare
+            << " pedRmsSquareVar: " << pedRmsSquareVar
+            << endl;
+    }
+  
+  const Float_t sigmaSquare    =      sigma     * sigma;
+  const Float_t sigmaSquareVar = 4. * sigmavar  * sigmaSquare;
+
+  //
+  // Calculate the reduced sigmas
+  //
+  fRSigmaSquare = sigmaSquare - pedRmsSquare;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Red.Sigma Square: " << fRSigmaSquare
+            << endl;
+    }
+  
+  if (fRSigmaSquare <= 0.)
+    {
+      if (IsDebug())
+        *fLog << warn 
+              << "WARNING: Cannot calculate the reduced sigma: smaller than 0 in pixel " 
+              << fPixId << endl;
+      return kFALSE;
+    }
+
+  
+  fRSigmaSquareVar = 4. * (sigmaSquareVar + pedRmsSquareVar);
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Var.Red.Sigma Square: " << fRSigmaSquareVar
+            << endl;
+    }
+
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------
+//
+// If fRSigmaSquare is smaller than 0 (i.e. has not yet been set),
+// return kFALSE
+//
+// Calculate the number of photo-electrons with the F-Factor method:
+// - Test bit IsHiGainSaturation() for the Mean Sum of FADC slices: 
+//   If yes, take fLoGainMean and fLoGainMeanVar 
+//   If no , take fHiGainMean and fHiGainMeanVar 
+//
+// - Test bit IsHiGainSaturation() for the pedRMS: 
+//   If yes, take fLoGainPedRmsSquare and fLoGainPedRmsSquareVar
+//   If no , take fPedRms and fPedVar
+//
+// - Calculate the number of photo-electrons with the formula:
+//   fPheFFactorMethod   = gkFFactor*gkFFactor * Mean * Mean  / fRSigmaSquare
+//
+// - Calculate the Variance on the photo-electrons with the formula:
+//   fPheFFactorMethodVar =  (  4. * gkFFactorErr * gkFFactorErr / ( gkFFactor * gkFFactor ) 
+//                            + 4. * Mean Var.   / ( Mean * Mean )
+//                            + fRSigmaSquareVar / fRSigmaSquare
+//                            ) * fPheFFactorMethod * fPheFFactorMethod
+//
+// - If fPheFFactorMethod is less than fPheFFactorMethodLimit, 
+//   set kFFactorMethodValid to kFALSE and return kFALSE
+//
+Bool_t MCalibrationChargePix::CalcFFactor()
+{
+
+  if (fRSigmaSquare < 0.)
+    return kFALSE;
+  
+  //
+  // Square all variables in order to avoid applications of square root
+  //
+  const Float_t meanSquare          =     GetMean()    * GetMean();
+  const Float_t meanSquareRelVar    = 4.* GetMeanRelVar();
+
+  const Float_t ffactorsquare       =     gkFFactor    * gkFFactor;
+  const Float_t ffactorsquareRelVar = 4.* GetFFactorRelVar();
+
+  const Float_t rsigmaSquareRelVar  =     fRSigmaSquareVar / fRSigmaSquare / fRSigmaSquare;
+  //
+  // Calculate the number of phe's from the F-Factor method
+  // (independent on Hi Gain or Lo Gain)
+  //
+  fPheFFactorMethod = ffactorsquare * meanSquare / fRSigmaSquare;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " F-Factor Square: " << ffactorsquare
+            << " Mean Square: " << meanSquare
+            << " Red.Sigma Square: " << fRSigmaSquare
+            << " Photo-electrons: " << fPheFFactorMethod
+            << endl;
+    }
+
+  if (fPheFFactorMethod < fPheFFactorMethodLimit)
+    return kFALSE;
+  
+  //
+  // Calculate the Error of Nphe
+  //
+  const Float_t pheRelVar = ffactorsquareRelVar + meanSquareRelVar + rsigmaSquareRelVar;
+  fPheFFactorMethodVar    = pheRelVar * fPheFFactorMethod * fPheFFactorMethod;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Rel.Var.F-Factor Square: " << ffactorsquareRelVar
+            << " Rel.Var. Mean Square: " << meanSquareRelVar
+            << " Rel.Var. Red.Sigma Square: " << rsigmaSquareRelVar
+            << " Rel.Var. Photo-electrons: " << pheRelVar
+            << endl;
+    }
+
+  if (fPheFFactorMethodVar < 0. )
+    return kFALSE;
+
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------
+//
+// If fPheFFactorMethod is smaller than 0 (i.e. has not yet been set),
+// return kFALSE
+//
+// If GetCovertedMean() is smaller than 0 (i.e. has not yet been set),
+// return kFALSE
+//
+// Calculate fMeanConvFADC2Phe with the following formula:
+//
+//      fMeanConvFADC2Phe    =  fPheFFactorMethod / GetConvMean();
+//
+// Calculate the rel. variance of fMeanConvFADC2Phe, taking into account that 
+// in the calculation of the number of phe's one mean square has already been used. 
+// Now, dividing by another mean, one mean calcels out, one cannot directly propagate
+// the errors, but instead havs to take into account this cancellation:
+// 
+//     convrelvar = ffactorsquareRelVar + GetMeanRelVar() + rsigmaSquareRelVar;
+//
+// If confrelvar is smaller than 0. or greater than fConvFFactorRelVarLimit, 
+// return kFALSE
+// 
+// Calculate the variance of fMeanConvFADC2Phe with the formula:
+//
+//    fMeanConvFADC2PheVar =  convrelvar * fMeanConvFADC2Phe * fMeanConvFADC2Phe;
+// 
+// Set kFFactorMethodValid to kTRUE and 
+// return kTRUE
+//
+Bool_t MCalibrationChargePix::CalcConvFFactor()
+{
+  
+  if (fPheFFactorMethod <= 0.)
+    return kFALSE;
+
+  const Float_t convmean = GetConvertedMean();
+
+  if (convmean <= 0.)
+    return kFALSE;
+  
+  fMeanConvFADC2Phe    =  fPheFFactorMethod / convmean;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Converted Mean: " << convmean 
+            << " Conversion FADC2Phe: " << fMeanConvFADC2Phe
+            << endl;
+    }
+
+  const Float_t ffactorsquareRelVar = 4.* GetFFactorRelVar();
+  const Float_t rsigmaSquareRelVar  = fRSigmaSquareVar / fRSigmaSquare / fRSigmaSquare;
+  //
+  // In the calculation of the number of phe's one mean square has already been used. 
+  // Now, we divide by another mean, so one mean calcels out, we cannot directly propagate
+  // the errors, but have to take account of this cancellation:
+  // 
+  Float_t convrelvar = ffactorsquareRelVar + GetMeanRelVar() + rsigmaSquareRelVar;
+  const Float_t limit = IsHiGainSaturation() ? fConvFFactorRelVarLimit * 4. : fConvFFactorRelVarLimit;
+
+  //
+  // Also have to take into account the pixels labelled MBadPixelsPix::kChargeSigmaNotValid which do not 
+  // have a fRSigmaSquareVar, calculate their error directly!
+  //
+  if (fRSigmaSquareVar < 0.)
+    convrelvar = GetMeanRelVar() + GetPheFFactorMethodRelVar();
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Rel.Var.Red.Sigma: " << rsigmaSquareRelVar
+            << " Rel.Var.Mean: " << GetMeanRelVar()
+            << " Rel.Var.F-Factor: " << ffactorsquareRelVar
+            << " Rel.Var.Conversion FADC2Phe: " << convrelvar
+            << endl;
+    }
+
+  if (convrelvar > limit || convrelvar < 0.)
+    {
+      *fLog << warn << GetDescriptor() << ":  Conv. F-Factor Method Rel. Var.: " 
+            << Form("%4.3f out of limits: [0,%3.2f] in pixel:%4i",convrelvar,limit,fPixId) << endl;
+      return kFALSE;
+    }
+  
+  fMeanConvFADC2PheVar =  convrelvar * fMeanConvFADC2Phe * fMeanConvFADC2Phe;
+  
+  SetFFactorMethodValid(kTRUE);
+  return kTRUE;
+}
+
+// ----------------------------------------------------------------------------------
+//
+// If photflux is smaller or equal 0, return kFALSE
+//
+// Calculate the total F-Factor with the formula:
+//   fMeanFFactorFADC2Phot = Sqrt ( fRSigmaSquare ) / GetMean()  * sqrt(nphotons)
+//
+// Calculate the error of the total F-Factor
+//
+Bool_t MCalibrationChargePix::CalcMeanFFactor( const Float_t nphotons, const Float_t nphotonsrelvar )
+{
+
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Number photons: " << nphotons
+            << " Rel.Var.Number photons: " << nphotonsrelvar
+            << " Red.Sigma Square: " << fRSigmaSquare
+            << " Mean: " << GetMean()
+            << endl;
+    }
+
+
+  if (nphotons <= 0.)
+    {
+      *fLog << warn << GetDescriptor() << ": Assumed photon flux is smaller or equal 0." << endl;
+      return kFALSE;
+    }
+
+  if (nphotonsrelvar < 0.)
+    {
+      *fLog << warn << GetDescriptor() << ": Assumed photon flux variance is smaller than 0." << endl;
+      return kFALSE;
+    }
+
+  fMeanFFactorFADC2Phot =  TMath::Sqrt(fRSigmaSquare * nphotons) / GetMean() ;
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " F-Factor FADC2Phot: " << fMeanFFactorFADC2Phot
+            << endl;
+    }
+
+  if (fMeanFFactorFADC2Phot < 0.)
+    {
+      *fLog << warn << GetDescriptor() << ": F-Factor photons to FADC counts smaller than 0." << endl;
+      return kFALSE;
+    }
+  
+  const Float_t ffactorrelvar = 0.25 * fRSigmaSquareVar / ( fRSigmaSquare * fRSigmaSquare) 
+                              + GetMeanRelVar() 
+                              + 0.25 * nphotonsrelvar;
+  
+  fMeanFFactorFADC2PhotVar    = ffactorrelvar * fMeanFFactorFADC2Phot * fMeanFFactorFADC2Phot;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Rel.Var.Red.Sigma: " << 0.25 * fRSigmaSquareVar / ( fRSigmaSquare * fRSigmaSquare) 
+            << " Rel.Var.Mean: " << GetMeanRelVar()
+            << " Rel.Var.photons: " << 0.25 * nphotonsrelvar
+            << " Rel.Var.F-Factor FADC2Phot: " << ffactorrelvar
+            << endl;
+    }
+
+  return kTRUE;
+}
+
+
+// ----------------------------------------------------------------------------
+// 
+// - If fPed    is smaller than 0 (i.e. has not yet been set), return.
+// - If fPedVar is smaller than 0 (i.e. has not yet been set), return.
+//
+// Calculate the electronic pedestal RMS with the formula:
+//  - elec. pedestal = gkElectronicPedRms * sqrt(logainsamples)
+// 
+// Calculate the night sky background ped. RMS contribution ("NSB") in the high-gain 
+// from the high gain Pedestal RMS with the formula:
+// - HiGain NSB square      = fPedRms * fPedRms - elec.ped.* elec.ped.
+// - Var(HiGain NSB square) = fPedVar * fPedRms * fPedRms + 4.*elecPedRmsVar * elec.ped.* elec.ped.
+//
+// If HiGain NSB square is smaller than 0., set it to zero. (but not the error!)
+//
+// Convert the NSB ped. RMS contribution to the low-gain with the formula:
+// - LoGain NSB square      =  HiGain NSB square / (fConversionHiLo*fConversionHiLo)
+// - Var(LoGain NSB square) = ( Var(HiGain NSB square) / (HiGain NSB square * HiGain NSB square)
+//                              + GetConversionHiLoRelVar()   
+//                            ) * LoGain NSB square * LoGain NSB square
+//
+// - Low Gain Ped RMS Square       = LoGain NSB square      + elec.ped. square
+//   Var (Low Gain Ped RMS Square) = Var(LoGain NSB square) + Var(elec.ped. square)
+//
+void MCalibrationChargePix::CalcLoGainPedestal(Float_t logainsamples)
+{
+
+  if (fPedRms < 0.)
+    return;
+
+  if (fPedVar < 0.)
+    return;
+
+  const Float_t elecPedRms     = gkElectronicPedRms * TMath::Sqrt(logainsamples);
+  const Float_t elecPedRmsVar  = GetElectronicPedRmsRelVar() * elecPedRms * elecPedRms;
+  
+  Float_t pedRmsSquare         = fPedRms * fPedRms;
+  Float_t pedRmsSquareVar      = fPedVar * pedRmsSquare; // fPedRmsErr = fPedErr/2.
+  
+  //
+  // We do not know the Low Gain Pedestal RMS, so we have to retrieve it 
+  // from the High Gain:  
+  //
+  // We extract the pure NSB contribution:
+  //
+  const Float_t elecRmsSquare    =    elecPedRms    * elecPedRms;
+  const Float_t elecRmsSquareVar = 4.*elecPedRmsVar * elecRmsSquare;
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " Ped.Rms Square:  " << pedRmsSquare 
+            << " Elec.Rms Square: " << elecRmsSquare 
+            << " Ped.Rms.Square Var.: " << pedRmsSquareVar 
+            << " Elec.Rms Square Var.: " << elecRmsSquareVar 
+            << endl;
+    }
+  
+
+  Float_t higainNsbSquare     =  pedRmsSquare    - elecRmsSquare;
+  Float_t higainNsbSquareVar  = (pedRmsSquareVar + elecRmsSquareVar);
+
+  if (higainNsbSquare < 0.001)
+    higainNsbSquare = 0.;
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " HiGain NSB Square:  " << higainNsbSquare
+            << " Var.HiGain NSB Square:  " << higainNsbSquareVar
+            << endl;
+    }
+  
+  //
+  // Now, we divide the NSB by the conversion factor and 
+  // add it quadratically to the electronic noise
+  //
+  const Float_t conversionSquare        =     fConversionHiLo    * fConversionHiLo;
+  const Float_t conversionSquareRelVar  = 4.* GetConversionHiLoRelVar();
+
+  const Float_t logainNsbSquare         =   higainNsbSquare       / conversionSquare;
+  //
+  // Calculation of variance of: c = a/b
+  //                    Delta(c)^2 = ( Delta(a)^2 + a^2/b^2*(Delta(b)^2 )  / b^2
+  //
+  const Float_t logainNsbSquareVar      = ( higainNsbSquareVar 
+                                         + conversionSquareRelVar * higainNsbSquare * higainNsbSquare ) 
+                                          / conversionSquare / conversionSquare;
+    
+  fLoGainPedRmsSquare    = logainNsbSquare    + elecRmsSquare;
+  fLoGainPedRmsSquareVar = logainNsbSquareVar + elecRmsSquareVar;
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << "ID: " << GetPixId() 
+            << " LoGain Ped Rms Square:  " << fLoGainPedRmsSquare
+            << " Var.Ped Rms Square:  " << fLoGainPedRmsSquareVar
+            << endl;
+    }
+  
+  
+}
+ 
Index: /tags/Mars-V0.9/mcalib/MCalibrationChargePix.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationChargePix.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationChargePix.h	(revision 9772)
@@ -0,0 +1,119 @@
+#ifndef MARS_MCalibrationChargePix
+#define MARS_MCalibrationChargePix
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationChargePix : public MCalibrationPix
+{
+private:
+
+  static const Float_t gkElectronicPedRms;     //! Electronic component of ped. RMS from opt. receiver on (now set to: 1.)
+  static const Float_t gkElectronicPedRmsErr;  //! Error Electr. component ped. RMS (now set to: 0.35)
+  static const Float_t gkFFactor;              //! Laboratory F-factor PMTs         (now set to: 1.15)
+  static const Float_t gkFFactorErr;           //! Laboratory F-factor Error PMTs   (now set to: 0.02)
+
+  static const Float_t fgConversionHiLo;         //! Default fConversionHiLo          (now set to: 10.)
+  static const Float_t fgConversionHiLoErr;      //! Default fConversionHiLoVar       (now set to: 2.5)
+  static const Float_t fgPheFFactorMethodLimit;  //! Default fPheFFactorMethodLimit   (now set to: 5.)
+  static const Float_t fgConvFFactorRelErrLimit; //! Default fConvFFactorRelErrLimit  (now set to: 0.35)  
+  
+  Float_t fAbsTimeMean;                     // Mean Absolute Arrival Time
+  Float_t fAbsTimeRms;                      // RMS Mean Absolute Arrival Time
+  Byte_t  fCalibFlags;                      // Bit-field for the class-own bits
+  Float_t fConversionHiLo;                  // Conversion factor betw. Hi Gain and Lo Gain  
+  Float_t fConversionHiLoVar;               // Variance Conversion factor betw. Hi and Lo Gain
+  Float_t fConvFFactorRelVarLimit;          // Limit for acceptance rel. variance Conversion FADC2Phe
+  Float_t fLoGainPedRmsSquare;              // Pedestal RMS square of Low Gain
+  Float_t fLoGainPedRmsSquareVar;           // Pedestal RMS square Variance of Low Gain
+  Float_t fMeanConvFADC2Phe;                // Conversion factor (F-factor method)
+  Float_t fMeanConvFADC2PheVar;             // Variance conversion factor (F-factor method)
+  Float_t fMeanFFactorFADC2Phot;            // Total mean F-Factor to photons (F-factor method)
+  Float_t fMeanFFactorFADC2PhotVar;         // Variance mean F-Factor photons (F-factor method)  
+  Float_t fPed;                             // Pedestal (from MPedestalPix) times number FADC slices
+  Float_t fPedVar;                          // Variance of pedestal 
+  Float_t fPedRms;                          // Pedestal RMS (from MPedestalPix) times sqrt nr. FADC slices
+  Float_t fPedRmsVar;                       // Pedestal RMS (from MPedestalPix) times sqrt nr. FADC slices
+  Float_t fPheFFactorMethod;                // Number Phe's calculated (F-factor method)
+  Float_t fPheFFactorMethodVar;             // Variance number of Phe's (F-factor method)
+  Float_t fPheFFactorMethodLimit;           // Min. number Photo-electrons for pix to be accepted.
+  Float_t fRSigmaSquare;                    // Square of Reduced sigma
+  Float_t fRSigmaSquareVar;                 // Variance Reduced sigma
+  
+  enum  { kFFactorMethodValid   };          // Possible bits to be set
+
+  const Float_t GetElectronicPedRmsRelVar() const;
+  const Float_t GetConversionHiLoRelVar()  const;
+  const Float_t GetFFactorRelVar()     const;
+  
+public:
+
+  MCalibrationChargePix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationChargePix() {}
+  
+  void Clear(Option_t *o="");
+
+  // Setter
+  void SetAbsTimeMean ( const Float_t f ) { fAbsTimeMean = f; }
+  void SetAbsTimeRms  ( const Float_t f ) { fAbsTimeRms  = f; }
+  void SetConversionHiLo    ( const Float_t c=fgConversionHiLo    )        { fConversionHiLo    = c;       }
+  void SetConversionHiLoErr ( const Float_t e=fgConversionHiLoErr )        { fConversionHiLoVar = e*e;     }
+  void SetConvFFactorRelErrLimit   ( const Float_t f=fgConvFFactorRelErrLimit) { fConvFFactorRelVarLimit = f*f;}
+  void SetFFactorMethodValid   ( const Bool_t b = kTRUE );
+  void SetMeanConvFADC2Phe      ( const Float_t f)                          { fMeanConvFADC2Phe       = f; }
+  void SetMeanConvFADC2PheVar   ( const Float_t f)                          { fMeanConvFADC2PheVar    = f; }
+  void SetMeanFFactorFADC2Phot  ( const Float_t f)                          { fMeanFFactorFADC2Phot   = f; }
+  void SetPedestal              ( const Float_t ped, const Float_t pedrms, const Float_t pederr);
+  void SetPed                   ( const Float_t ped, const Float_t pederr);  
+  void SetPedRMS              ( const Float_t pedrms, const Float_t pedrmserr);  
+  void SetPheFFactorMethod      ( const Float_t f)                          { fPheFFactorMethod       = f; }
+  void SetPheFFactorMethodVar   ( const Float_t f)                          { fPheFFactorMethodVar    = f; }  
+  void SetPheFFactorMethodLimit ( const Float_t f=fgPheFFactorMethodLimit ) { fPheFFactorMethodLimit  = f; }
+  
+  // Getters
+  Float_t GetAbsTimeMean             () const { return fAbsTimeMean;             }
+  Float_t GetAbsTimeRms              () const { return fAbsTimeRms;              }
+  Float_t GetConversionHiLo          () const { return fConversionHiLo;          }
+  Float_t GetConversionHiLoErr       () const;
+  Float_t GetConvertedMean           () const;
+  Float_t GetConvertedMeanErr        () const;
+  Float_t GetConvertedSigma          () const;
+  Float_t GetConvertedSigmaErr       () const;
+  Float_t GetConvertedRSigma         () const;
+  Float_t GetConvertedRSigmaErr      () const;
+  Float_t GetConvertedRSigmaSquare   () const;  
+  Float_t GetMeanConvFADC2Phe        () const { return fMeanConvFADC2Phe;        } 
+  Float_t GetMeanConvFADC2PheErr     () const;
+  Float_t GetMeanConvFADC2PheVar     () const { return fMeanConvFADC2PheVar;     }
+  Float_t GetMeanFFactorFADC2Phot    () const { return fMeanFFactorFADC2Phot;    }
+  Float_t GetMeanFFactorFADC2PhotErr () const;
+  Float_t GetMeanFFactorFADC2PhotVar () const { return fMeanFFactorFADC2PhotVar; }    
+  Float_t GetPed                     () const { return fPed;                     }
+  Float_t GetPedErr                  () const { return TMath::Sqrt(fPedVar);     }
+  Float_t GetPedRms                  () const;
+  Float_t GetPedRmsErr               () const;
+  Float_t GetPheFFactorMethod        () const { return fPheFFactorMethod;        }    
+  Float_t GetPheFFactorMethodErr     () const;
+  Float_t GetPheFFactorMethodVar     () const { return fPheFFactorMethodVar;     }
+  Float_t GetPheFFactorMethodRelVar  () const;
+  Float_t GetRSigma                  () const;
+  Float_t GetRSigmaErr               () const;
+  Float_t GetRSigmaRelVar            () const;
+  Float_t GetRSigmaPerCharge         () const;
+  Float_t GetRSigmaPerChargeErr      () const;
+
+  Bool_t IsFFactorMethodValid        () const;
+
+  // Calculations
+  void   CalcLoGainPedestal       ( const Float_t logainsamples);
+  Bool_t CalcReducedSigma  (  );
+  Bool_t CalcFFactor       (  );
+  Bool_t CalcConvFFactor   (  );  
+  Bool_t CalcMeanFFactor   ( const Float_t nphotons, const Float_t nphotonsrelvar );
+  
+  ClassDef(MCalibrationChargePix, 2)	// Container Charge Calibration Results Pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationHiLoCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationHiLoCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationHiLoCam.cc	(revision 9772)
@@ -0,0 +1,281 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationHiLoCam                                               
+//                                                               
+// Storage container for ratio between higain and logain charge extraction
+// calibration results of the whole camera.
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationHiLoPix &avpix = (MCalibrationHiLoPix&)(*fHiLoCam)[i]
+// 
+// The following "calibration" constants can be retrieved from each pixel:
+// - GetHiLoRatio(): The mean signal ratio between high-gain and low-gain
+// - GetHiLoRatioErr(): The Gauss sigma of histogrammed signal ratios
+//
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationHiLoPix &avpix = (MCalibrationHiLoPix&)fRelCam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationHiLoPix &avpix = (MCalibrationHiLoPix&)fRelCam->GetAverageSector(i)
+//
+// Note the averageing has been done on an event-by-event basis. Resulting 
+// Sigma's of the Gauss fit have been multiplied with the square root of the number 
+// of involved pixels in order to make a direct comparison possible with the mean of 
+// sigmas. 
+//
+// See also: MHCalibrationHiLoPix, MHCalibrationHiLoCam              
+//                                                                         
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: HiLo Ratio
+// 1: Error of HiLo Ratio
+// 2: Sigma of HiLo Ratio == Resolution 
+// 3: Error of Sigma of HiLo Ratio
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to distribution
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationHiLoCam.h"
+#include "MCalibrationCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationHiLoPix.h"
+
+ClassImp(MCalibrationHiLoCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationHiLoCam::MCalibrationHiLoCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationHiLoCam";
+  fTitle = title ? title : "Container for High Gain vs. Low Gain amplification ratio";
+  
+}
+
+void MCalibrationHiLoCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationHiLoPix,i);
+}
+
+
+void MCalibrationHiLoCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationHiLoPix,i);
+}
+
+void MCalibrationHiLoCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationHiLoPix,i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not Valid
+//
+void MCalibrationHiLoCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << "Calibrated pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationHiLoPix *pix;
+  while ((pix=(MCalibrationHiLoPix*)Next()))
+    {
+      
+      if (!pix->IsExcluded()) 
+	{                            
+
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":            Ratio: ",pix->GetHiLoChargeRatio()," +- ",pix->GetHiLoChargeRatioErr(),
+                        "   Sigma: ",pix->GetHiLoChargeRatioSigma()," +- ",pix->GetHiLoChargeRatioSigmaErr())
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+  
+   
+  *fLog << all << endl;
+  *fLog << all << "Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationHiLoPix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+	  *fLog << all << pix->GetPixId() << endl;
+	  id++;
+      }
+  }
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationHiLoPix*)Next5()))
+  {
+    *fLog << all 
+          << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Average Area   ",pix->GetPixId(),
+                  ":  Ratio: ",pix->GetHiLoChargeRatio()," +- ",pix->GetHiLoChargeRatioErr(),
+                  "   Sigma: ",pix->GetHiLoChargeRatioSigma()," +- ",pix->GetHiLoChargeRatioSigmaErr())
+          << endl;
+  }
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationHiLoPix*)Next5()))
+  {
+    *fLog << all 
+          << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Average Sector ",pix->GetPixId(),
+                  ":  Ratio: ",pix->GetHiLoChargeRatio()," +- ",pix->GetHiLoChargeRatioErr(),
+                  "   Sigma: ",pix->GetHiLoChargeRatioSigma()," +- ",pix->GetHiLoChargeRatioSigmaErr())
+          << endl;
+  }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted HiLo
+// 1: Error of fitted HiLo
+// 2: Sigma of fitted HiLo
+// 3: Error of Sigma of fitted HiLo
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to HiLo distribution
+//
+Bool_t MCalibrationHiLoCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ MCalibrationHiLoPix &pix = (MCalibrationHiLoPix&)(*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatio();
+      break;
+    case 1:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatioErr();
+      break;
+    case 2:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatioSigma();
+      break;
+    case 3:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatioSigmaErr();
+      break;
+    case 4:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoChargeRatioProb();
+      break;
+    case 5:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiff();
+      break;
+    case 6:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiffErr();
+      break;
+    case 7:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiffSigma();
+      break;
+    case 8:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiffSigmaErr();
+      break;
+    case 9:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiLoTimeDiffProb();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationHiLoCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationHiLoCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationHiLoCam.h	(revision 9772)
@@ -0,0 +1,29 @@
+#ifndef MARS_MCalibrationHiLoCam
+#define MARS_MCalibrationHiLoCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationHiLoCam : public MCalibrationCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+
+public:
+
+  MCalibrationHiLoCam(const char *name=NULL, const char *title=NULL);
+
+  // Prints
+  void Print(Option_t *o="") const;
+
+  // Others
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+
+  ClassDef(MCalibrationHiLoCam, 1)	// Container Rel. Arrival Time Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationHiLoPix.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationHiLoPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationHiLoPix.cc	(revision 9772)
@@ -0,0 +1,54 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrationHiLoPix                                                     //
+//                                                                         //
+// Storage container for high-gain vs. low-gain charge calibration results // 
+// of one Pixel (PMT).                                                     //
+// The following "calibration" constants can be retrieved:                 //
+// - GetHiLoRatio(): The mean conversion High-gain vs. Low-gain
+//   with which the low-gain result has to be multiplied
+// - GetHiLoSigma(): The Gauss sigma of histogrammed High-gain vs. Low-gain ratios
+//
+// See also: MHCalibrationHiLoPix, MHCalibrationHiLoCam              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationHiLoPix.h"
+
+ClassImp(MCalibrationHiLoPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MCalibrationHiLoPix::MCalibrationHiLoPix(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationHiLoPix";
+  fTitle = title ? title : "Results of MHCalibrationHiLoPix ";
+
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationHiLoPix.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationHiLoPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationHiLoPix.h	(revision 9772)
@@ -0,0 +1,33 @@
+#ifndef MARS_MCalibrationHiLoPix
+#define MARS_MCalibrationHiLoPix
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationHiLoPix : public MCalibrationPix
+{
+private:
+
+public:
+
+  MCalibrationHiLoPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationHiLoPix() {}
+  
+  Float_t GetHiLoChargeRatio()         const { return GetHiGainMean();     }
+  Float_t GetHiLoChargeRatioErr()      const { return GetHiGainMeanErr();  }
+  Float_t GetHiLoChargeRatioSigma()    const { return GetHiGainSigma();    }
+  Float_t GetHiLoChargeRatioSigmaErr() const { return GetHiGainSigmaErr(); }
+  Float_t GetHiLoChargeRatioProb()     const { return GetHiGainProb();     }
+									   
+  Float_t GetHiLoTimeDiff()            const { return GetLoGainMean();     }
+  Float_t GetHiLoTimeDiffErr()         const { return GetLoGainMeanErr();  }
+  Float_t GetHiLoTimeDiffSigma()       const { return GetLoGainSigma();    }
+  Float_t GetHiLoTimeDiffSigmaErr()    const { return GetLoGainSigmaErr(); }
+  Float_t GetHiLoTimeDiffProb()        const { return GetLoGainProb();     }
+
+  ClassDef(MCalibrationHiLoPix, 1)	// Container HiLo conversion Calibration Results Pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityBlindCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityBlindCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityBlindCam.cc	(revision 9772)
@@ -0,0 +1,92 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityBlindCam                                               
+//                                                               
+// Storage container for intensity charge calibration results. 
+// 
+// Individual MCalibrationBlindCam's can be retrieved with: 
+// - GetCam() yielding the current cam.
+// - GetCam("name") yielding the current camera with name "name".
+// - GetCam(i) yielding the i-th camera.
+//
+// See also: MCalibrationIntensityCam, MCalibrationBlindCam,
+//           MCalibrationBlindPix, MCalibrationChargeCalc, MCalibrationQECam
+//           MHCalibrationChargeBlindPix, MHCalibrationChargeBlindCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityBlindCam.h"
+#include "MCalibrationBlindCam.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MCalibrationIntensityBlindCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationIntensityBlindCam::MCalibrationIntensityBlindCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityBlindCam";
+  fTitle = title ? title : "Results of the Intensity Calibration";
+
+  InitSize(1);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationBlindCam's in the ranges from - to. 
+//
+void MCalibrationIntensityBlindCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationBlindCam,i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls TOrdCollection::Expand() for fCams and initialze one MCalibrationBlindCam
+// and copy the entries
+// 
+void MCalibrationIntensityBlindCam::InitSize(const UInt_t n)
+{
+
+  MCalibrationBlindCam *oldcam = NULL;
+
+  if (n>1)
+    oldcam = (MCalibrationBlindCam*)GetCam();
+
+  MCalibrationIntensityCam::InitSize(n);
+
+  MCalibrationBlindCam *newcam = (MCalibrationBlindCam*)GetCam();  
+  
+  if (oldcam)
+    oldcam->Copy(*newcam);
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityBlindCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityBlindCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityBlindCam.h	(revision 9772)
@@ -0,0 +1,23 @@
+#ifndef MARS_MCalibrationIntensityBlindCam
+#define MARS_MCalibrationIntensityBlindCam
+
+#ifndef MARS_MCalibrationIntensityCam
+#include "MCalibrationIntensityCam.h"
+#endif
+
+class MCalibrationIntensityBlindCam : public MCalibrationIntensityCam
+{
+private:
+
+  void Add(const UInt_t from, const UInt_t tox);
+
+public:
+
+  MCalibrationIntensityBlindCam(const char *name=NULL, const char *title=NULL);
+
+  void InitSize( const UInt_t n );
+  
+  ClassDef(MCalibrationIntensityBlindCam, 1) // Container Intensity Blind Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityCam.cc	(revision 9772)
@@ -0,0 +1,425 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityCam                                               
+//                                                               
+// Base class for intensity calibration results 
+//
+// Contains TOrdCollections for the following objects:
+// - fCams:  Array of classes derived from MCalibrationCam, one entry 
+//           per calibration camera result. Has to be created
+//
+// See also: MCalibrationIntensityChargeCam, MCalibrationIntensityQECam,
+//           MCalibrationIntensityRelTimeCam,
+//           MCalibrationCam, MCalibrationPix, 
+//           MCalibrationQECam, MCalibrationQEPix,
+//           MHCalibrationChargePix, MHCalibrationChargeCam              
+//           MCalibrationChargeBlindPix, MCalibrationChargePINDiode
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MGeomCam.h"
+
+ClassImp(MCalibrationIntensityCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Set the following pointer to NULL:
+// - fCams
+//
+MCalibrationIntensityCam::MCalibrationIntensityCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityCam";
+  fTitle = title ? title : "Base container for the Intensity Calibration";
+
+  fCams = new TOrdCollection;
+  fCams->SetOwner();
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Deletes the histograms if they exist
+//
+MCalibrationIntensityCam::~MCalibrationIntensityCam()
+{
+  if (fCams)
+    delete fCams;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new MCalibrationCam to fCams, give it the name "name" and initialize
+// it with geom.
+//
+void MCalibrationIntensityCam::AddToList( const char* name, const MGeomCam &geom) 
+{
+  InitSize(GetSize()+1);
+  GetCam()->SetName(name);
+  GetCam()->Init(geom);
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MCalibrationIntensityCam::Copy(TObject& object) const
+{
+  
+  MCalibrationIntensityCam &calib = (MCalibrationIntensityCam&)object;
+  
+  MParContainer::Copy(calib);
+  
+  calib.fOffsets = fOffsets;
+  calib.fSlopes  = fSlopes;
+  
+  const UInt_t n = GetSize();
+  if (n != 0)
+    {
+      calib.InitSize(n);
+      for (UInt_t i=0; i<n; i++)
+        GetCam(i)->Copy(*(calib.GetCam(i)));
+    }
+  
+}
+
+// -----------------------------------------------------
+//
+// Calls Clear() for all entries fCams
+//
+void MCalibrationIntensityCam::Clear(Option_t *o)
+{
+
+  fCams->ForEach(MCalibrationCam, Clear)(); 
+
+  return;
+}
+
+// -----------------------------------------------------
+//
+// Calls Print(o) for all entries fCams
+//
+void MCalibrationIntensityCam::Print(Option_t *o) const
+{
+  fCams->ForEach(MCalibrationCam, Print)(o); 
+}
+
+// -----------------------------------------------------
+//
+// Not yet installed...
+//
+void MCalibrationIntensityCam::DrawHiLoFits()
+{
+
+  /*
+  if (!fOffsets)
+    fOffsets = new TH1D("pp","Offsets of the HiGain LoGain Fit",100,-600.,400.);
+  if (!fSlopes)
+    fSlopes  = new TH1D("mm","Slopes of the HiGain LoGain Fit",100,-2.,2.);
+  if (!fOffvsSlope)
+    fOffvsSlope = new TH2D("aa","Slopes vs Offsets of the HiGain LoGain Fit",100,-600.,400.,100,-2.,2.);
+  
+  TIter Next(fPixels);
+  MCalibrationPix *pix;
+  MHCalibrationPixel *hist;
+  while ((pix=(MCalibrationPix*)Next()))
+    {
+      hist = pix->GetHist();
+      hist->FitHiGainvsLoGain();
+      fOffsets->Fill(hist->GetOffset(),1.);
+      fSlopes->Fill(hist->GetSlope(),1.);
+      fOffvsSlope->Fill(hist->GetOffset(),hist->GetSlope(),1.);
+    }
+
+   TCanvas *c1 = new TCanvas();
+
+   c1->Divide(1,3);
+   c1->cd(1);
+   fOffsets->Draw();
+   gPad->Modified();
+   gPad->Update();
+
+   c1->cd(2);
+  fSlopes->Draw();
+  gPad->Modified();
+  gPad->Update();
+
+  c1->cd(3);
+  fOffvsSlope->Draw("col1");
+  gPad->Modified();
+  gPad->Update();
+  */
+}
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollection using the 
+// virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationIntensityCam::InitSize(const UInt_t i)
+{
+
+  const UInt_t save = GetSize();
+
+  if (i==save)
+    return;
+  
+  if (i>save)
+    Add(save,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationCams in the ranges from - to. In order to initialize
+// from MCalibrationCam derived containers, overwrite this function
+//
+void MCalibrationIntensityCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationCam,i);
+}
+
+// -------------------------------------------------------------------
+//
+// If size is still 0, Intialize a first Cam.
+// Calls Init(geom) for all fCams
+//
+void MCalibrationIntensityCam::Init(const MGeomCam &geom)
+{
+  if (GetSize() == 0)
+    InitSize(1);
+
+  fCams->ForEach(MCalibrationCam,Init)(geom);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fCams 
+// independently if the MCalibrationCam is filled with values or not.
+//
+const Int_t MCalibrationIntensityCam::GetSize() const 
+{
+  return fCams->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+MCalibrationPix &MCalibrationIntensityCam::operator[](UInt_t i)
+{
+  return (*GetCam())[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel from current camera
+//
+const MCalibrationPix &MCalibrationIntensityCam::operator[](UInt_t i) const 
+{
+  return (*GetCam())[i];
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageAreas of the current camera.
+//
+const Int_t MCalibrationIntensityCam::GetAverageAreas() const
+{
+  return GetCam()->GetAverageAreas();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area from the current camera
+//
+MCalibrationPix  &MCalibrationIntensityCam::GetAverageArea(UInt_t i)
+{
+  return GetCam()->GetAverageArea(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area from the current camera
+//
+const MCalibrationPix  &MCalibrationIntensityCam::GetAverageArea(UInt_t i) const
+{
+  return GetCam()->GetAverageArea(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area from the current camera
+//
+MBadPixelsPix  &MCalibrationIntensityCam::GetAverageBadArea(UInt_t i)
+{
+  return GetCam()->GetAverageBadArea(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area from the current camera
+//
+const MBadPixelsPix  &MCalibrationIntensityCam::GetAverageBadArea(UInt_t i) const
+{
+  return GetCam()->GetAverageBadArea(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageSectors or the current camera
+//
+const Int_t MCalibrationIntensityCam::GetAverageSectors() const
+{
+  return GetCam()->GetAverageSectors();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector from the current camera
+//
+MCalibrationPix  &MCalibrationIntensityCam::GetAverageSector(UInt_t i)
+{
+  return GetCam()->GetAverageSector(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector from the current camera
+//
+const MCalibrationPix  &MCalibrationIntensityCam::GetAverageSector(UInt_t i) const
+{
+  return GetCam()->GetAverageSector(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector from the current camera
+//
+MBadPixelsPix  &MCalibrationIntensityCam::GetAverageBadSector(UInt_t i)
+{
+  return GetCam()->GetAverageBadSector(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector from the current camera
+//
+const MBadPixelsPix  &MCalibrationIntensityCam::GetAverageBadSector(UInt_t i) const
+{
+  return GetCam()->GetAverageBadSector(i);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get i-th camera 
+//
+MCalibrationCam *MCalibrationIntensityCam::GetCam(Int_t i)
+{
+  return static_cast<MCalibrationCam*>(i==-1 ? fCams->Last() : fCams->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th camera 
+//
+const MCalibrationCam *MCalibrationIntensityCam::GetCam(Int_t i) const 
+{
+  return static_cast<MCalibrationCam*>(i==-1 ? fCams->Last() : fCams->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get camera with name 'name' 
+//
+MCalibrationCam *MCalibrationIntensityCam::GetCam(const char *name )
+{
+  return static_cast<MCalibrationCam*>(fCams->FindObject(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get camera with name 'name' 
+//
+const MCalibrationCam *MCalibrationIntensityCam::GetCam(const char *name ) const 
+{
+  return static_cast<MCalibrationCam*>(fCams->FindObject(name));
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls GetPixelContent for the current entry in fCams
+//
+Bool_t MCalibrationIntensityCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  return GetCam()->GetPixelContent(val,idx,cam,type);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls DrawPixelContent for the current entry in fCams
+//
+void MCalibrationIntensityCam::DrawPixelContent( Int_t num ) const
+{
+  return GetCam()->DrawPixelContent(num);
+}
+
+Int_t MCalibrationIntensityCam::CountNumEntries(const MCalibrationCam::PulserColor_t col) const 
+{
+  
+  Int_t size = 0;
+
+  if (col == MCalibrationCam::kNONE)
+    return GetSize();
+  else
+    for (Int_t i=0;i<GetSize();i++)
+      {
+        const MCalibrationCam *cam = GetCam(i);
+        if (cam->GetPulserColor() == col)
+          size++;
+      }
+
+  return size;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityCam.h	(revision 9772)
@@ -0,0 +1,96 @@
+#ifndef MARS_MCalibrationIntensityCam
+#define MARS_MCalibrationIntensityCam
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class TOrdCollection;
+class MCalibrationPix;
+class MBadPixelsPix;
+class MGeomCam;
+class MCalibrationIntensityCam : public MParContainer, public MCamEvent
+{
+private:
+  
+  MArrayD fOffsets;           //! Arrays of Higain-vs-LoGain fit result Offsets
+  MArrayD fSlopes;            //! Arrays of Higain-vs-LoGain fit result Slopes
+
+protected:  
+
+  TOrdCollection *fCams;        // Array of MCalibrationCams, one per pulse colour and intensity
+
+  virtual void Add(const UInt_t from, const UInt_t to);
+  virtual void InitSize( const UInt_t n );
+  
+public:
+
+  MCalibrationIntensityCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationIntensityCam();
+  
+  void  Clear ( Option_t *o="" );
+  void  Copy(TObject& object) const;  
+  
+  void AddToList( const char* name, const MGeomCam &geom );
+
+  Int_t CountNumEntries(const MCalibrationCam::PulserColor_t col) const;  
+
+  // Draws
+  void DrawHiLoFits();
+  void DrawPixelContent( Int_t num) const;
+  
+  // Getters
+  Bool_t GetPixelContent( Double_t &val, Int_t idx, const MGeomCam &cam,Int_t type=0) const;
+  const Int_t GetSize() const;
+
+  const Int_t            GetAverageAreas     ()            const;	 
+        MCalibrationPix &GetAverageArea      ( UInt_t i );
+  const MCalibrationPix &GetAverageArea      ( UInt_t i )  const;
+        MBadPixelsPix   &GetAverageBadArea   ( UInt_t i );
+  const MBadPixelsPix   &GetAverageBadArea   ( UInt_t i )  const;
+  const Int_t            GetAverageSectors   ()            const;
+        MCalibrationPix &GetAverageSector    ( UInt_t i );
+  const MCalibrationPix &GetAverageSector    ( UInt_t i )  const;
+        MBadPixelsPix   &GetAverageBadSector ( UInt_t i );
+  const MBadPixelsPix   &GetAverageBadSector ( UInt_t i )  const;
+
+        MCalibrationCam *GetCam              ( Int_t i=-1);
+  const MCalibrationCam *GetCam              ( Int_t i=-1) const;
+
+        MCalibrationCam *GetCam              ( const char *name );
+  const MCalibrationCam *GetCam              ( const char *name ) const;
+
+        MCalibrationPix &operator[]          ( UInt_t i );
+  const MCalibrationPix &operator[]          ( UInt_t i )  const;
+ 
+  const Float_t GetNumHiGainFADCSlices ( const Int_t aidx=0 ) const { return GetCam()->GetNumHiGainFADCSlices(aidx); }
+  const Float_t GetNumLoGainFADCSlices ( const Int_t aidx=0 ) const { return GetCam()->GetNumLoGainFADCSlices(aidx); }
+  const Int_t   GetNumUnsuitable       ( const Int_t aidx=-1) const { return GetCam()->GetNumUnsuitable(aidx);       }
+  const Int_t   GetNumUnreliable       ( const Int_t aidx=-1) const { return GetCam()->GetNumUnreliable(aidx);       }
+  
+  // Inits
+  void  Init   ( const MGeomCam &geom );
+  
+  // Prints
+  void   Print(Option_t *o="")         const;
+
+  // Setters
+  void  SetNumHiGainFADCSlices( const Float_t f, const Int_t aidx=0) { GetCam()->SetNumHiGainFADCSlices(f,aidx); }
+  void  SetNumLoGainFADCSlices( const Float_t f, const Int_t aidx=0) { GetCam()->SetNumLoGainFADCSlices(f,aidx); }
+  void  SetNumUnsuitable      ( const UInt_t i,  const Int_t aidx  ) { GetCam()->SetNumUnsuitable(i,aidx);       }
+  void  SetNumUnreliable      ( const UInt_t i,  const Int_t aidx  ) { GetCam()->SetNumUnreliable(i,aidx);       }
+  void  SetPulserColor        ( const MCalibrationCam::PulserColor_t col=MCalibrationCam::kCT1) {
+                                                                GetCam()->SetPulserColor(col);            }
+
+  ClassDef(MCalibrationIntensityCam, 1) // Base Container Intensity Calibration Results
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityChargeCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityChargeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityChargeCam.cc	(revision 9772)
@@ -0,0 +1,1166 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityChargeCam                                               
+//                                                               
+// Storage container for intensity charge calibration results. 
+// 
+// Individual MCalibrationChargeCam's can be retrieved with: 
+// - GetCam() yielding the current cam.
+// - GetCam("name") yielding the current camera with name "name".
+// - GetCam(i) yielding the i-th camera.
+//
+// See also: MCalibrationIntensityCam, MCalibrationChargeCam,
+//           MCalibrationChargePix, MCalibrationChargeCalc, MCalibrationQECam
+//           MCalibrationBlindCam, MCalibrationChargePINDiode
+//           MHCalibrationChargePix, MHCalibrationChargeCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityChargeCam.h"
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TGraphErrors.h>
+#include <TOrdCollection.h>
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHCamera.h"
+
+#include "MGeomCamMagic.h"
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+ClassImp(MCalibrationIntensityChargeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationIntensityChargeCam::MCalibrationIntensityChargeCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityChargeCam";
+  fTitle = title ? title : "Results of the Intensity Calibration";
+  
+  InitSize(1);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationChargeCam's in the ranges from - to. 
+//
+void MCalibrationIntensityChargeCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationChargeCam,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the number of photo-electrons vs. 
+// the extracted signal of pixel "pixid". 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPheVsCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF phe(size);
+  TArrayF pheerr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (cam->GetPulserColor() != col)
+          continue;
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      phe[cnt]    = pix.GetPheFFactorMethod();
+      pheerr[cnt] = pix.GetPheFFactorMethodErr();
+      //
+      // For the calculation of Q, we have to use the 
+      // converted value!
+      //
+      sig   [cnt] = pix.GetConvertedMean();
+      sigerr[cnt] = pix.GetConvertedMeanErr();
+      cnt++;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     sig.GetArray(),phe.GetArray(),
+                                     sigerr.GetArray(),pheerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("Q [FADC counts]");
+  gr->GetYaxis()->SetTitle("photo-electrons [1]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the mean effective number of photo-electrons divided by 
+// the mean charge of that pixel vs. the mean number of photo-electrons.
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPhePerCharge( const UInt_t pixid, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumValidEntries(pixid,col);
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF phepersig(size);
+  TArrayF phepersigerr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (cam->GetPulserColor() != col)
+          continue;
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      // For the calculation of Q, we have to use the 
+      // converted value!
+      //
+      const Int_t aidx = geom[pixid].GetAidx();
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+
+      const Float_t q    = pix.GetConvertedMean();
+      const Float_t qerr = pix.GetConvertedMeanErr();
+      //
+      const Float_t phe    = apix.GetPheFFactorMethod();
+      const Float_t pheerr = apix.GetPheFFactorMethodErr();
+
+      sig[cnt]       = phe;
+      sigerr[cnt]    = pheerr;
+
+
+      phepersig[cnt] = q > 0.00001 ? phe/q : -1.;
+
+      Float_t var = 0.;
+
+      if (q > 0.00001 && phe > 0.00001)
+        {
+          var = pheerr * pheerr / phe / phe + qerr*qerr/q/q;
+          if (var > 0.00001)
+            var = TMath::Sqrt(var)*phepersig[cnt];
+        }
+      phepersigerr[cnt] = var;
+      cnt++;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     sig.GetArray(),phepersig.GetArray(),
+                                     sigerr.GetArray(),phepersigerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("<photo-electrons> [1]");
+  gr->GetYaxis()->SetTitle("<phes> / <Q> [FADC cts^{-1}]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the mean effective number of photo-electrons divided by 
+// the mean charge of that pixel vs. the mean number of photo-electrons.
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPhePerChargePerArea( const Int_t aidx, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF phepersig(size);
+  TArrayF phepersigerr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (cam->GetPulserColor() != col)
+          continue;
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Float_t phe          = apix.GetPheFFactorMethod();
+      const Float_t pherelvar    = apix.GetPheFFactorMethodRelVar();
+      const Float_t pheerr       = apix.GetPheFFactorMethodErr();
+
+      sig[cnt]       = phe;
+      sigerr[cnt]    = pheerr;
+
+      Double_t sig  = 0.;
+      Double_t sig2 = 0.;
+      Int_t    num  = 0;
+
+      for (Int_t i=0; i<cam->GetSize(); i++)
+        {
+          const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[i];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+          //
+          //
+          if (aidx != geom[i].GetAidx())
+            continue;
+          
+          sig  += pix.GetConvertedMean();
+          sig2 += pix.GetConvertedMean() * pix.GetConvertedMean();
+          num++;
+        }
+      
+      if (num > 1)
+        {
+          sig           /= num;
+
+          Double_t var = (sig2 - sig*sig*num) / (num-1);
+          var /= sig*sig;
+          var += pherelvar;
+
+          phepersig[cnt] = phe/sig;
+          if (var > 0.)
+            phepersigerr[cnt] = TMath::Sqrt(var) * phepersig[cnt];
+          else
+            phepersigerr[cnt] = 0.;
+        }
+      else
+        {
+          phepersig[cnt]    = -1.;
+          phepersigerr[cnt] = 0.;
+        }
+      cnt++;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     sig.GetArray(),phepersig.GetArray(),
+                                     sigerr.GetArray(),phepersigerr.GetArray());
+  gr->SetTitle(Form("Conv. Factors Area %d Average",aidx));
+  gr->GetXaxis()->SetTitle("<photo-electrons> [1]");
+  gr->GetYaxis()->SetTitle("<phes> / <Q> [FADC cts^{-1}]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the number of photo-electrons vs. 
+// the extracted signal over all pixels with area index "aidx". 
+//
+// The points represent the means of the pixels values, while the error bars
+// the sigma of the pixels values.  
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPheVsChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumEntries(col);
+  
+  TArrayF phe(size);
+  TArrayF pheerr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (cam->GetPulserColor() != col)
+          continue;
+
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(cam->GetAverageArea(aidx));
+
+      phe[cnt]    = pix.GetPheFFactorMethod();
+      pheerr[cnt] = pix.GetPheFFactorMethodErr();
+      //
+      // For the calculation of Q, we have to use the 
+      // converted value!
+      //
+      sig   [cnt] = pix.GetConvertedMean();
+      sigerr[cnt] = pix.GetConvertedMeanErr();
+
+      cnt++;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                      sig.GetArray(),phe.GetArray(),
+                                      sigerr.GetArray(),pheerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Area Index ",aidx));
+  gr->GetXaxis()->SetTitle("Q [FADC counts]");
+  gr->GetYaxis()->SetTitle("photo-electrons [1]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the 'Razmik plot' of pixel "pixid". 
+// The Razmik plot shows the value of 'R' vs. 1/Q where:
+//
+//        sigma^2         F^2
+//  R =   -------    =  ------
+//         <Q>^2        <m_pe>
+//
+// and 1/Q is the inverse (mean) extracted signal
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetRazmikPlot( const UInt_t pixid )
+{
+  
+  const Int_t size = GetSize();
+  
+  TArrayF r(size);
+  TArrayF rerr(size);
+  TArrayF oneoverq(size);
+  TArrayF oneoverqerr(size);
+  
+  for (Int_t i=0;i<size;i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      // For the calculation of R, use the un-converted values, like 
+      // in the calibration, since: 
+      //                 C^2*sigma^2     sigma^2
+      //  R(lowgain) =   -----------  =  ------  = R
+      //                 C^2*<Q>^2       <Q>^2
+      //
+      const Float_t mean = pix.GetMean();
+      const Float_t meanerr = pix.GetMeanErr();
+      const Float_t rsigma = pix.GetRSigma();
+      const Float_t rsigmaerr = pix.GetRSigmaErr();
+      r[i]    = rsigma*rsigma/mean/mean;
+      const Float_t rrelvar = 4.*rsigmaerr*rsigmaerr/rsigma/rsigma + 4.*meanerr*meanerr/mean/mean;
+      rerr[i] = rrelvar * r[i] * r[i];
+      rerr[i] = rerr[i] <= 0 ? 0. : TMath::Sqrt(rerr[i]);
+      //
+      // For the calculation of 1/Q, we have to use the 
+      // converted value!
+      //
+      const Float_t q  = pix.GetConvertedMean();
+      const Float_t qe = pix.GetConvertedMeanErr();
+      oneoverq   [i] = 1./q;
+      oneoverqerr[i] = qe / (q * q);
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     oneoverq.GetArray(),r.GetArray(),
+                                     oneoverqerr.GetArray(),rerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("1/Q [FADC counts^{-1}]");
+  gr->GetYaxis()->SetTitle("\\sigma_{red}^{2}/Q^{2} [1]");
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a 2-dimensional histogram with the fit results of the 
+// 'Razmik plot' for each pixel of area index "aidx" (see GetRazmikPlot())
+// 
+// The results of the polynomial fit of grade 1 are: 
+//
+// x-axis: Offset (Parameter 0 of the polynomial)
+// y-axis: Slope  (Parameter 1 of the polynomial)
+//
+// The offset is a measure of how well-known the supposed additional contributions 
+// to the value "reduced sigma" are. Because a photo-multiplier is a linear instrument, 
+// the excess fluctuations are linear w.r.t. the signal amplitude and can be expressed by 
+// the proportionality constant F (the "F-Factor"). 
+// Adding noise from outside (e.g. night sky background) modifies the recorded noise, but 
+// not the mean extracted signal, due to the AC-coupling. Thus, noise contributions from outside
+// (e.g. calculating the pedestal RMS)have to be subtracted from the recorded signal fluctuations 
+// in order to retrieve the linearity relation: 
+//
+// sigma(signal)^2 / mean(signal)^2  = sigma^2 / <Q>^2 = F^2 / <n_phe>               (1) 
+//
+// Any systematic offset in the sigma(signal) will produce an offset in the "Razmik plot"), 
+// characterized by the Offset of the polynomial fit. Thus, in an ideal case, all pixels have their
+// "offset" centered very closely around zero.
+//
+// The "slope" is the proportionality constant F^2, multiplied with the conversion factor 
+// phe's to mean signal (because the "Razmik plot" plots the left side of eq. (1) w.r.t. 
+// 1/<Q> instead of 1/<n_phe>. However, the mean number of photo-electrons <n_phe> can be 
+// expressed by <Q> with the relation:
+//
+//  <n_phe> = c_phe * <Q>                                                            (2)
+//
+// Thus: 
+//
+// 1/<n_phe> = 1/c_phe * 1/<Q>                                                       (3) 
+// 
+// and:
+//
+// Slope = F^2 / c_phe
+//
+// In the ideal case of having equal photo-multipliers and a perfectly flat-fielded camera,
+// the "slope" -values should thus all be closely centered around F^2/c_phe. 
+// 
+TH2F *MCalibrationIntensityChargeCam::GetRazmikPlotResults( const Int_t aidx, const MGeomCam &geom)
+{
+  
+  TH2F *hist = new TH2F("hist","R vs. Inverse Charges - Fit results",45,-0.02,0.02,45,0.,30.);
+  hist->SetXTitle("Offset [FADC counts^{-1}]");
+  hist->SetYTitle("F^{2} / <n_phe>/<Q> [FADC count / phe]");  
+  hist->SetFillColor(kRed+aidx);
+
+  MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam();
+
+  for (Int_t npix=0;npix<cam->GetSize();npix++)
+    {
+
+      if (geom[npix].GetAidx() == aidx)
+        {
+          TGraph *gr = GetRazmikPlot(npix);
+          gr->Fit("pol1","Q");
+          hist->Fill(gr->GetFunction("pol1")->GetParameter(0),gr->GetFunction("pol1")->GetParameter(1));
+        }
+    }
+  return hist;
+}
+
+
+// --------------------------------------------------------------------
+//
+// Returns the number of camera entries matching the required colour 
+// and the requirement that pixel "pixid" has been correctly calibrated
+//
+Int_t MCalibrationIntensityChargeCam::CountNumValidEntries(const UInt_t pixid, const MCalibrationCam::PulserColor_t col) const
+{
+
+  Int_t nvalid = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      const MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+      const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+
+      if (col == MCalibrationCam::kNONE)
+        {
+          if (pix.IsFFactorMethodValid())
+            nvalid++;
+        }
+      else
+        {
+          if (cam->GetPulserColor() == col)
+            {
+              if (pix.IsFFactorMethodValid())
+                nvalid++;
+            }
+        }
+    }
+  
+  return nvalid;
+}
+
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the development of the number of 
+// photo-electrons vs. camera number for pixel 'pixid' 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetVarVsTime( const Int_t pixid , const Option_t *varname )
+{
+  
+  const Int_t size = GetSize();
+
+  if (size == 0)
+    return NULL;
+  
+  TString option(varname);
+  option.ToLower();
+
+  TArrayF nr(size);
+  TArrayF nrerr(size);
+  TArrayF var   (size);
+  TArrayF varerr(size);
+  
+  for (Int_t i=0;i<size;i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[pixid];
+      //
+      nr[i]    = i;
+      nrerr[i] = 0.;
+      var[i]    = -1.;
+      varerr[i] = -1.;
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      if (option.Contains("rsigma"))
+        {
+          var   [i] = pix.GetRSigma();
+          varerr[i] = pix.GetRSigmaErr();
+        }
+      if (option.Contains("abstime"))
+        {
+          var   [i] = pix.GetAbsTimeMean();
+          varerr[i] = pix.GetAbsTimeRms();
+        }
+      if (option.Contains("blackout"))
+        {
+          var   [i] = pix.GetNumBlackout();
+          varerr[i] = 0.;
+        }
+      if (option.Contains("pickup"))
+        {
+          var   [i] = pix.GetNumPickup();
+          varerr[i] = 0.;
+        }
+      if (option.Contains("outlier"))
+        {
+          var   [i] = pix.GetNumPickup() + pix.GetNumBlackout();
+          varerr[i] = 0.;
+        }
+      if (option.Contains("conversionhilo"))
+        {
+          var   [i] = pix.GetConversionHiLo();
+          varerr[i] = pix.GetConversionHiLoErr();
+        }
+      if (option.Contains("convertedmean"))
+        {
+          var   [i] = pix.GetConvertedMean();
+          varerr[i] = pix.GetConvertedMeanErr();
+        }
+      if (option.Contains("convertedsigma"))
+        {
+          var   [i] = pix.GetConvertedSigma();
+          varerr[i] = pix.GetConvertedSigmaErr();
+        }
+      if (option.Contains("convertedrsigma"))
+        {
+          var   [i] = pix.GetConvertedRSigma();
+          varerr[i] = pix.GetConvertedRSigmaErr();
+        }
+      if (option.Contains("meanconvfadc2phe"))
+        {
+          var   [i] = pix.GetMeanConvFADC2Phe();
+          varerr[i] = pix.GetMeanConvFADC2PheErr();
+        }
+      if (option.Contains("meanffactorfadc2phot"))
+        {
+          var   [i] = pix.GetMeanFFactorFADC2Phot();
+          varerr[i] = pix.GetMeanFFactorFADC2PhotErr();
+        }
+      if (option.Contains("ped"))
+        {
+          var   [i] = pix.GetPed();
+          varerr[i] = pix.GetPedErr();
+        }
+      if (option.Contains("pedrms"))
+        {
+          var   [i] = pix.GetPedRms();
+          varerr[i] = pix.GetPedRmsErr();
+        }
+      if (option.Contains("pheffactormethod"))
+        {
+          var   [i] = pix.GetPheFFactorMethod();
+          varerr[i] = pix.GetPheFFactorMethodErr();
+        }
+      if (option.Contains("rsigmapercharge"))
+        {
+          var   [i] = pix.GetRSigmaPerCharge();
+          varerr[i] = pix.GetRSigmaPerChargeErr();
+        }
+  }
+  
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     nr.GetArray(),var.GetArray(),
+                                     nrerr.GetArray(),varerr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  //  gr->GetYaxis()->SetTitle("<Q> [FADC cnts]");
+  return gr;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns a TGraphErrors with a pre-defined variable with name (handed over in 'opt')
+// per area index 'aidx' vs. the calibration camera number 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetVarPerAreaVsTime( const Int_t aidx, const MGeomCam &geom, const Option_t *varname)
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+
+  TString option(varname);
+  option.ToLower();
+
+  TArrayF vararea(size);
+  TArrayF varareaerr(size);
+  TArrayF nr(size);
+  TArrayF nrerr(size);
+  
+  TH1D *h = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      Double_t variab   = 0.;
+      Double_t variab2  = 0.;
+      Double_t variance = 0.;
+      Int_t    num      = 0;
+      Float_t  pvar     = 0.;
+
+      MHCamera camcharge(geom,"CamCharge","Variable;;channels");
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+          //
+          //
+          if (aidx != geom[j].GetAidx())
+            continue;
+
+          pvar = 0.;
+          
+          if (option.Contains("rsigma"))
+            pvar = pix.GetRSigma();
+          if (option.Contains("abstime"))
+            pvar = pix.GetAbsTimeMean();
+          if (option.Contains("conversionhilo"))
+            pvar = pix.GetConversionHiLo();
+          if (option.Contains("convertedmean"))
+            pvar = pix.GetConvertedMean();
+          if (option.Contains("convertedsigma"))
+            pvar = pix.GetConvertedSigma();
+          if (option.Contains("convertedrsigma"))
+            pvar = pix.GetConvertedRSigma();
+          if (option.Contains("meanconvfadc2phe"))
+            pvar = pix.GetMeanConvFADC2Phe();
+          if (option.Contains("meanffactorfadc2phot"))
+            pvar = pix.GetMeanFFactorFADC2Phot();
+          if (option.Contains("ped"))
+            pvar = pix.GetPed();
+          if (option.Contains("pedrms"))
+            pvar = pix.GetPedRms();
+          if (option.Contains("pheffactormethod"))
+            pvar = pix.GetPheFFactorMethod();
+          if (option.Contains("rsigmapercharge"))
+            pvar = pix.GetRSigmaPerCharge();
+
+          variab  += pvar;
+          variab2 += pvar*pvar;
+          num++;
+          
+          camcharge.Fill(j,pvar);
+          camcharge.SetUsed(j);
+        }
+      
+      if (num > 1)
+        {
+          variab  /= num;
+          variance = (variab2 - variab*variab*num) / (num-1);
+
+          vararea[i] = variab;
+          if (variance > 0.)
+            varareaerr[i] = TMath::Sqrt(variance);
+          else
+            varareaerr[i] = 999999999.;
+
+          //
+          // Make also a Gauss-fit to the distributions. The RMS can be determined by 
+          // outlier, thus we look at the sigma and the RMS and take the smaller one, afterwards.
+          // 
+          h = camcharge.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+          h->SetDirectory(NULL);
+          h->Fit("gaus","QL");
+          TF1 *fit = h->GetFunction("gaus");
+
+          Float_t ci2   = fit->GetChisquare();
+          Float_t sigma = fit->GetParameter(2);
+
+          if (ci2 > 500. || sigma > varareaerr[i])
+            {
+              h->Fit("gaus","QLM");
+              fit = h->GetFunction("gaus");
+
+              ci2   = fit->GetChisquare();
+              sigma = fit->GetParameter(2);
+            }
+          
+          const Float_t mean  = fit->GetParameter(1);
+          const Float_t ndf   = fit->GetNDF();
+          
+          *fLog << inf << "Camera Nr: " << i << endl;
+          *fLog << inf << option.Data() << " area idx: " << aidx << " Results: " << endl;
+          *fLog << inf << "Mean: " << Form("%4.3f",mean) 
+                << "+-" << Form("%4.3f",fit->GetParError(1))
+                << "  Sigma: " << Form("%4.3f",sigma) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+                << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+          delete h;
+          gROOT->GetListOfFunctions()->Remove(fit);
+
+          if (sigma < varareaerr[i] && ndf > 2)
+            {
+              vararea   [i] = mean;
+              varareaerr[i] = sigma;
+            }
+        }
+      else
+        {
+          vararea[i]    = -1.;
+          varareaerr[i] = 0.;
+        }
+
+      nr[i] = i;
+      nrerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     nr.GetArray(),vararea.GetArray(),
+                                     nrerr.GetArray(),varareaerr.GetArray());
+  gr->SetTitle(Form("%s Area %3i Average",option.Data(),aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  //  gr->GetYaxis()->SetTitle("<Q> [1]");      
+  return gr;
+}
+
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the mean effective number of photon
+// vs. the calibration camera number. With the string 'method', different
+// calibration methods can be called.
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPhotVsTime( const Option_t *method )
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+
+  TString option(method);
+
+  TArrayF photarr(size);
+  TArrayF photarrerr(size);
+  TArrayF nr(size);
+  TArrayF nrerr(size);
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      Float_t phot    = 0.;
+      Float_t photerr = 0.;
+
+      if (option.Contains("BlindPixel"))
+        {
+          phot    = cam->GetNumPhotonsBlindPixelMethod();
+          photerr = cam->GetNumPhotonsBlindPixelMethodErr();
+        }
+      if (option.Contains("FFactor"))
+        {
+          phot    = cam->GetNumPhotonsFFactorMethod();
+          photerr = cam->GetNumPhotonsFFactorMethodErr();
+        }
+      if (option.Contains("PINDiode"))
+        {
+          phot    = cam->GetNumPhotonsPINDiodeMethod();
+          photerr = cam->GetNumPhotonsPINDiodeMethodErr();
+        }
+
+      photarr[i]       = phot;
+      photarrerr[i]    = photerr;
+
+      nr[i] = i;
+      nrerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     nr.GetArray(),photarr.GetArray(),
+                                     nrerr.GetArray(),photarrerr.GetArray());
+  gr->SetTitle("Photons Average");
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<N_phot> [1]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the mean effective number of photo-electrons per 
+// area index 'aidx' vs. the calibration camera number 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetPhePerAreaVsTime( const Int_t aidx, const MGeomCam &geom)
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF phearea(size);
+  TArrayF pheareaerr(size);
+  TArrayF time(size);
+  TArrayF timeerr(size);
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Float_t phe          = apix.GetPheFFactorMethod();
+      const Float_t pheerr       = apix.GetPheFFactorMethodErr();
+
+      phearea[i]       = phe;
+      pheareaerr[i]    = pheerr;
+
+      time[i] = i;
+      timeerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     time.GetArray(),phearea.GetArray(),
+                                     timeerr.GetArray(),pheareaerr.GetArray());
+  gr->SetTitle(Form("Phes Area %d Average",aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<N_phes> [1]");      
+  return gr;
+}
+
+// -------------------------------------------------------------------
+//
+// Returns a TGraphErrors with the event-by-event averaged charge per 
+// area index 'aidx' vs. the calibration camera number 
+//
+TGraphErrors *MCalibrationIntensityChargeCam::GetChargePerAreaVsTime( const Int_t aidx, const MGeomCam &geom)
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TArrayF chargearea(size);
+  TArrayF chargeareaerr(size);
+  TArrayF nr(size);
+  TArrayF nrerr(size);
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Float_t charge          = apix.GetConvertedMean();
+      const Float_t chargeerr       = apix.GetConvertedSigma();
+
+      chargearea[i]       = charge;
+      chargeareaerr[i]    = chargeerr;
+
+      nr[i]    = i;
+      nrerr[i] = 0.;
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                     nr.GetArray(),chargearea.GetArray(),
+                                     nrerr.GetArray(),chargeareaerr.GetArray());
+  gr->SetTitle(Form("Averaged Charges Area Idx %d",aidx));
+  gr->GetXaxis()->SetTitle("Camera Nr.");
+  gr->GetYaxis()->SetTitle("<Q> [FADC cnts]");      
+  return gr;
+}
+
+TH1F *MCalibrationIntensityChargeCam::GetVarFluctuations( const Int_t aidx, const MGeomCam &geom, const Option_t *varname )
+{
+  
+  const Int_t size = GetSize();
+  
+  if (size == 0)
+    return NULL;
+  
+  TString option(varname);
+  
+  TH1F *hist = new TH1F("hist",Form("%s - Rel. Fluctuations %s Pixel",option.Data(),aidx ? "Outer" : "Inner"),
+                        200,0.,100.);
+  hist->SetXTitle("Relative Fluctuation [%]");
+  hist->SetYTitle("Nr. channels [1]");  
+  hist->SetFillColor(kRed+aidx);
+
+  MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam();
+
+  //
+  // Loop over pixels
+  //
+  for (Int_t npix=0;npix<cam->GetSize();npix++)
+    {
+      if (geom[npix].GetAidx() != aidx)
+        continue;
+
+      Double_t variab   = 0.;
+      Double_t variab2  = 0.;
+      Double_t variance = 0.;
+      Int_t    num      = 0;
+      Float_t  pvar     = 0.;
+      Float_t  relrms   = 99.9;
+      //
+      // Loop over the Cams for each pixel
+      //
+      for (Int_t i=0; i<GetSize(); i++)
+        {
+          MCalibrationChargeCam *cam = (MCalibrationChargeCam*)GetCam(i);
+          //
+          // Get the calibration pix from the calibration cam
+          //
+          MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[npix];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+
+          if (option.Contains("RSigma"))
+            pvar = pix.GetRSigma();
+          if (option.Contains("AbsTime"))
+            pvar = pix.GetAbsTimeMean();
+          if (option.Contains("ConversionHiLo"))
+            pvar = pix.GetConversionHiLo();
+          if (option.Contains("ConvertedMean"))
+            pvar = pix.GetConvertedMean();
+          if (option.Contains("ConvertedSigma"))
+            pvar = pix.GetConvertedSigma();
+          if (option.Contains("ConvertedRSigma"))
+            pvar = pix.GetConvertedRSigma();
+          if (option.Contains("MeanConvFADC2Phe"))
+            pvar = pix.GetMeanConvFADC2Phe();
+          if (option.Contains("MeanFFactorFADC2Phot"))
+            pvar = pix.GetMeanFFactorFADC2Phot();
+          if (option.Contains("Ped"))
+            pvar = pix.GetPed();
+          if (option.Contains("PedRms"))
+            pvar = pix.GetPedRms();
+          if (option.Contains("PheFFactorMethod"))
+            pvar = pix.GetPheFFactorMethod();
+          if (option.Contains("RSigmaPerCharge"))
+            pvar = pix.GetRSigmaPerCharge();
+
+          variab  += pvar;
+          variab2 += pvar*pvar;
+          num++;
+        }
+
+      if (num > 1)
+        {
+          variab  /= num;
+          variance = (variab2 - variab*variab*num) / (num-1);
+
+          if (variance > 0.)
+            relrms = TMath::Sqrt(variance)/variab * 100.;
+        }
+      hist->Fill(relrms);
+    }
+  return hist;
+}
+
+void MCalibrationIntensityChargeCam::DrawRazmikPlot( const UInt_t pixid )
+{
+  TGraphErrors *gr = GetRazmikPlot(pixid );
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+
+}
+void MCalibrationIntensityChargeCam::DrawPheVsCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col)
+{
+  TGraphErrors *gr = GetPheVsCharge(pixid,col);
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPhePerCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col)
+{
+  TGraphErrors *gr = GetPhePerCharge(pixid,MGeomCamMagic(),col); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPhePerChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col)
+{
+  TGraphErrors *gr = GetPhePerChargePerArea(aidx,MGeomCamMagic(),col); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPheVsChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col)
+{
+  TGraphErrors *gr = GetPheVsChargePerArea(aidx,col); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawRazmikPlotResults( const Int_t aidx)
+{
+  TH2F *h = GetRazmikPlotResults(aidx,MGeomCamMagic()); 
+  h->SetBit(kCanDelete);
+  h->Draw();
+}
+
+void MCalibrationIntensityChargeCam::DrawChargePerAreaVsTime( const Int_t aidx)
+{
+  TGraphErrors *gr = GetChargePerAreaVsTime(aidx,MGeomCamMagic()); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPhePerAreaVsTime( const Int_t aidx)
+{
+  TGraphErrors *gr = GetPhePerAreaVsTime(aidx,MGeomCamMagic()); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawPhotVsTime( const Option_t *method)
+{
+  TGraphErrors *gr = GetPhotVsTime(method); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+
+void MCalibrationIntensityChargeCam::DrawVarPerAreaVsTime( const Int_t aidx, const Option_t *varname )
+{
+  TGraphErrors *gr = GetVarPerAreaVsTime(aidx,MGeomCamMagic(),varname ); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawVarVsTime( const Int_t pixid , const Option_t *varname )
+{
+  TGraphErrors *gr = GetVarVsTime(pixid,varname ); 
+  gr->SetBit(kCanDelete);
+  gr->Draw("A*");
+}
+void MCalibrationIntensityChargeCam::DrawVarFluctuations( const Int_t aidx, const Option_t *varname)
+{
+  TH1F *h = GetVarFluctuations( aidx,MGeomCamMagic(),varname); 
+  h->SetBit(kCanDelete);
+  h->Draw();
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityChargeCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityChargeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityChargeCam.h	(revision 9772)
@@ -0,0 +1,69 @@
+#ifndef MARS_MCalibrationIntensityChargeCam
+#define MARS_MCalibrationIntensityChargeCam
+
+#ifndef MARS_MCalibrationIntensityCam
+#include "MCalibrationIntensityCam.h"
+#endif
+
+#ifndef MARS_MCalibrationChargeCam
+#include "MCalibrationChargeCam.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class TGraphErrors;
+class TH2F;
+class TH1F;
+class MGeomCam;
+class MCalibrationIntensityChargeCam : public MCalibrationIntensityCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+
+public:
+
+  MCalibrationIntensityChargeCam(const char *name=NULL, const char *title=NULL);
+
+  Int_t CountNumValidEntries(const UInt_t pixid, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE) const;
+  
+  // Graphs
+
+  TGraphErrors *GetRazmikPlot( const UInt_t pixid );
+  TGraphErrors *GetPheVsCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+  TGraphErrors *GetPhePerCharge( const UInt_t pixid, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+  TGraphErrors *GetPhePerChargePerArea( const Int_t aidx, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+  TGraphErrors *GetPheVsChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+  TH2F         *GetRazmikPlotResults( const Int_t aidx, const MGeomCam &geom );
+
+  TGraphErrors *GetChargePerAreaVsTime( const Int_t aidx, const MGeomCam &geom );  
+  TGraphErrors *GetPhePerAreaVsTime( const Int_t aidx, const MGeomCam &geom );
+  TGraphErrors *GetPhotVsTime( const Option_t *method="FFactor" );
+
+  TGraphErrors *GetVarPerAreaVsTime( const Int_t aidx, const MGeomCam &geom, const Option_t *varname );
+  TGraphErrors *GetVarVsTime( const Int_t pixid , const Option_t *varname );
+  TH1F         *GetVarFluctuations( const Int_t aidx, const MGeomCam &geom, const Option_t *varname);
+  
+  // Draws
+  void DrawRazmikPlot( const UInt_t pixid );
+  void DrawPheVsCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);       // *MENU*
+  void DrawPhePerCharge( const UInt_t pixid, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);      // *MENU*
+  void DrawPhePerChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE); // *MENU*
+  void DrawPheVsChargePerArea( const Int_t aidx, const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);  // *MENU*
+  void DrawRazmikPlotResults( const Int_t aidx );                          // *MENU*
+
+  void DrawChargePerAreaVsTime( const Int_t aidx);                         // *MENU*
+  void DrawPhePerAreaVsTime( const Int_t aidx );                           // *MENU*
+  void DrawPhotVsTime( const Option_t *method="FFactor");                  // *MENU*
+
+  void DrawVarPerAreaVsTime( const Int_t aidx, const Option_t *varname );  // *MENU*
+  void DrawVarVsTime( const Int_t pixid , const Option_t *varname );       // *MENU*
+  void DrawVarFluctuations( const Int_t aidx, const Option_t *varname);    // *MENU*
+  
+
+  ClassDef(MCalibrationIntensityChargeCam, 1) // Container Intensity Charge Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityQECam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityQECam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityQECam.cc	(revision 9772)
@@ -0,0 +1,91 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityQECam                                               
+//                                                               
+// Storage container for intensity charge calibration results. 
+// 
+// Individual MCalibrationQECam's can be retrieved with: 
+// - GetCam() yielding the current cam.
+// - GetCam("name") yielding the current camera with name "name".
+// - GetCam(i) yielding the i-th camera.
+//
+// See also: MCalibrationIntensityCam, MCalibrationQECam,
+//           MCalibrationQEPix, MCalibrationChargeCalc
+//           MHCalibrationChargePix, MHCalibrationChargeCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityQECam.h"
+#include "MCalibrationQECam.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MCalibrationIntensityQECam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationIntensityQECam::MCalibrationIntensityQECam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityQECam";
+  fTitle = title ? title : "Results of the Intensity Calibration";
+  
+  InitSize(1);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationQECams in the ranges from - to. 
+//
+void MCalibrationIntensityQECam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationQECam,i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls TObjArray::Expand() for fCams and initialze one MCalibrationQECam
+// and copy the entries
+// 
+void MCalibrationIntensityQECam::InitSize(const UInt_t n)
+{
+
+  MCalibrationQECam *oldcam = NULL;
+
+  if (n>1)
+    oldcam = (MCalibrationQECam*)GetCam();
+
+  MCalibrationIntensityCam::InitSize(n);
+  
+  MCalibrationQECam *newcam = (MCalibrationQECam*)GetCam();  
+  
+  if (oldcam)
+    oldcam->Copy(*newcam);
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityQECam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityQECam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityQECam.h	(revision 9772)
@@ -0,0 +1,72 @@
+#ifndef MARS_MCalibrationIntensityQECam
+#define MARS_MCalibrationIntensityQECam
+
+#ifndef MARS_MCalibrationIntensityCam
+#include "MCalibrationIntensityCam.h"
+#endif
+
+#ifndef MARS_MCalibrationQECam
+#include "MCalibrationQECam.h"
+#endif
+
+class MCalibrationIntensityQECam : public MCalibrationIntensityCam
+{
+private:
+
+  void Add(const UInt_t from, const UInt_t to);
+
+public:
+
+  MCalibrationIntensityQECam(const char *name=NULL, const char *title=NULL);
+
+  void InitSize( const UInt_t n );
+
+  const MArrayD &GetCorningBlues   () const {
+    return ((MCalibrationQECam*)GetCam())->GetCorningBlues();  }
+  const MArrayD &GetCorningReds    () const {
+    return ((MCalibrationQECam*)GetCam())->GetCorningReds();   }
+  
+  Float_t GetPlexiglassQE          () const {
+    return ((MCalibrationQECam*)GetCam())->GetPlexiglassQE();  }    
+  Float_t GetPlexiglassQERelVar    () const {
+    return ((MCalibrationQECam*)GetCam())->GetPlexiglassQERelVar();  }
+
+  Bool_t  IsBlindPixelMethodValid  () const {
+    return ((MCalibrationQECam*)GetCam())->IsBlindPixelMethodValid();  }
+  Bool_t  IsFFactorMethodValid     () const {
+    return ((MCalibrationQECam*)GetCam())->IsFFactorMethodValid();  }
+  Bool_t  IsCombinedMethodValid    () const {
+    return ((MCalibrationQECam*)GetCam())->IsCombinedMethodValid();  }
+  Bool_t  IsPINDiodeMethodValid    () const {
+    return ((MCalibrationQECam*)GetCam())->IsPINDiodeMethodValid();  }
+          
+  Bool_t  IsBlindPixelMethodValid  ( MCalibrationCam::PulserColor_t col ) const {
+    return ((MCalibrationQECam*)GetCam())->IsBlindPixelMethodValid(col);  }
+  Bool_t  IsFFactorMethodValid     ( MCalibrationCam::PulserColor_t col ) const {
+    return ((MCalibrationQECam*)GetCam())->IsFFactorMethodValid(col);  }
+  Bool_t  IsCombinedMethodValid    ( MCalibrationCam::PulserColor_t col ) const {
+    return ((MCalibrationQECam*)GetCam())->IsCombinedMethodValid(col);  }
+  Bool_t  IsPINDiodeMethodValid    ( MCalibrationCam::PulserColor_t col ) const {
+    return ((MCalibrationQECam*)GetCam())->IsPINDiodeMethodValid(col);  }
+
+  void    SetBlindPixelMethodValid ( const Bool_t  b=kTRUE ) {
+    ((MCalibrationQECam*)GetCam())->SetBlindPixelMethodValid(b);  }
+  void    SetBlindPixelMethodValid ( const Bool_t  b, MCalibrationCam::PulserColor_t col) {
+    ((MCalibrationQECam*)GetCam())->SetBlindPixelMethodValid(b,col);  }
+  void    SetCombinedMethodValid   ( const Bool_t  b=kTRUE ) {
+    ((MCalibrationQECam*)GetCam())->SetCombinedMethodValid(b);  }
+  void    SetCombinedMethodValid   ( const Bool_t  b, MCalibrationCam::PulserColor_t col) {
+    ((MCalibrationQECam*)GetCam())->SetCombinedMethodValid(b,col);  }
+  void    SetFFactorMethodValid    ( const Bool_t  b=kTRUE ) {
+    ((MCalibrationQECam*)GetCam())->SetFFactorMethodValid(b);  }
+  void    SetFFactorMethodValid    ( const Bool_t  b, MCalibrationCam::PulserColor_t col) {
+    ((MCalibrationQECam*)GetCam())->SetFFactorMethodValid(b,col);  }
+  void    SetPINDiodeMethodValid   ( const Bool_t  b=kTRUE ) {
+    ((MCalibrationQECam*)GetCam())->SetPINDiodeMethodValid(b);  }
+  void    SetPINDiodeMethodValid   ( const Bool_t  b, MCalibrationCam::PulserColor_t col) {
+    ((MCalibrationQECam*)GetCam())->SetPINDiodeMethodValid(b,col);  }
+
+  ClassDef(MCalibrationIntensityQECam, 1) // Container Intensity Rel.Times Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityRelTimeCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityRelTimeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityRelTimeCam.cc	(revision 9772)
@@ -0,0 +1,484 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityRelTimeCam                                               
+//                                                               
+// Storage container for intensity charge calibration results. 
+// 
+// Individual MCalibrationRelTimeCam's can be retrieved with: 
+// - GetCam() yielding the current cam.
+// - GetCam("name") yielding the current camera with name "name".
+// - GetCam(i) yielding the i-th camera.
+//
+// See also: MCalibrationIntensityCam, MCalibrationRelTimeCam,
+//           MCalibrationRelTimePix, MCalibrationRelTimeCalc, MCalibrationQECam
+//           MHCalibrationRelTimePix, MHCalibrationRelTimeCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityRelTimeCam.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationRelTimePix.h"
+#include "MCalibrationChargePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MHCamera.h"
+
+#include "MLogManip.h"
+
+#include <TOrdCollection.h>
+#include <TGraphErrors.h>
+#include <TH1D.h>
+#include <TF1.h>
+
+ClassImp(MCalibrationIntensityRelTimeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationIntensityRelTimeCam::MCalibrationIntensityRelTimeCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityRelTimeCam";
+  fTitle = title ? title : "Results of the Intensity Calibration";
+  
+  InitSize(1);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationRelTimeCam's in the ranges from - to. 
+//
+void MCalibrationIntensityRelTimeCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationRelTimeCam,i);
+}
+
+TGraphErrors *MCalibrationIntensityRelTimeCam::GetTimeResVsCharge( const UInt_t pixid, const MCalibrationIntensityChargeCam &chargecam, const MCalibrationCam::PulserColor_t col)
+{
+
+  if (chargecam.GetSize() != GetSize())
+    {
+      *fLog << err << GetDescriptor() << ": Size mismatch between MCalibrationIntensityRelTimeCam "
+            << "and MCalibrationIntensityChargeCam. " << endl;
+      return NULL;
+    }
+  
+  Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+
+  if (size != chargecam.CountNumEntries(col))
+    {
+      *fLog << err << GetDescriptor() << ": Size mismatch in colour between MCalibrationIntensityRelTimeCam "
+            << "and MCalibrationIntensityChargeCam. " << endl;
+      return NULL;
+    }
+  
+  const Int_t nvalid = chargecam.CountNumValidEntries(pixid,col);
+
+  if (nvalid == 0)
+    {
+      *fLog << err << GetDescriptor() << ": Only un-calibrated events in pixel: " << pixid << endl;
+      return NULL;
+    }
+
+  TArrayF res(nvalid);
+  TArrayF reserr(nvalid);
+  TArrayF sig(nvalid);
+  TArrayF sigerr(nvalid);
+
+  const Float_t sqrt2   = 1.414;
+  const Float_t fadc2ns = 3.333;
+  
+  Int_t cnt = 0;
+  
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationChargeCam *cam     = (MCalibrationChargeCam*)chargecam.GetCam(i);
+      MCalibrationRelTimeCam *relcam = (MCalibrationRelTimeCam*)GetCam(i);
+
+      if (col != MCalibrationCam::kNONE)
+        if (relcam->GetPulserColor() != col)
+          continue;
+      //
+      // Get the calibration pix from the calibration cam
+      //
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)(*cam)[pixid];
+      MCalibrationRelTimePix &relpix = (MCalibrationRelTimePix&)(*relcam)[pixid];
+      //
+      // Don't use bad pixels
+      //
+      if (!pix.IsFFactorMethodValid())
+        continue;
+      //
+      res[cnt]    = relpix.GetTimePrecision() / sqrt2 * fadc2ns;
+      reserr[cnt] = relpix.GetTimePrecisionErr() / sqrt2 * fadc2ns;
+      //
+      sig   [cnt] = pix.GetPheFFactorMethod();
+      sigerr[cnt] = pix.GetPheFFactorMethodErr();
+      cnt++;
+    }
+
+  TGraphErrors *gr = new TGraphErrors(nvalid,
+                                     sig.GetArray(),res.GetArray(),
+                                     sigerr.GetArray(),reserr.GetArray());
+  gr->SetTitle(Form("%s%3i","Pixel ",pixid));
+  gr->GetXaxis()->SetTitle("<Photo-electrons> [1]");
+  gr->GetYaxis()->SetTitle("Time Resolution [ns]");      
+  return gr;
+}
+
+
+TGraphErrors *MCalibrationIntensityRelTimeCam::GetTimeResVsChargePerArea( const Int_t aidx,const MCalibrationIntensityChargeCam &chargecam, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col)
+{
+  
+  Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+
+  if (size != chargecam.CountNumEntries(col))
+    {
+      *fLog << err << GetDescriptor() << ": Size mismatch in colour between MCalibrationIntensityRelTimeCam "
+            << "and MCalibrationIntensityChargeCam. " << endl;
+      return NULL;
+    }
+
+  if (col == MCalibrationCam::kBLUE)
+    size -= 5;
+  if (col == MCalibrationCam::kNONE)
+    size -= 5;
+  
+  const Float_t sqrt2   = 1.414;
+  const Float_t fadc2ns = 3.333;
+  const Float_t norm    = fadc2ns / sqrt2;
+
+  TArrayD res(size);
+  TArrayD reserr(size);
+  TArrayD sig(size);
+  TArrayD sigerr(size);
+  
+  Int_t cnt = 0;
+
+  TH1D *h = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationRelTimeCam *relcam = (MCalibrationRelTimeCam*)GetCam(i);
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)chargecam.GetCam(i);
+
+      if (relcam->GetPulserColor() != col && col != MCalibrationCam::kNONE)
+        continue;
+
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Double_t phe          = (Double_t)apix.GetPheFFactorMethod();
+      const Double_t pheerr       = (Double_t)apix.GetPheFFactorMethodErr();
+
+      if (relcam->GetPulserColor() == MCalibrationCam::kBLUE)
+	if (aidx == 0)
+	  {
+	    if (phe > 100. && phe < 190.)
+	      continue;
+	  }
+	else
+	  {
+	    if (phe > 200. && phe < 480.)
+	      continue;
+	  }
+
+      if (relcam->GetPulserColor() == MCalibrationCam::kUV)
+	*fLog << inf << "NUMBER: " << i << endl;
+
+      sig[cnt]       = phe;
+      sigerr[cnt]    = pheerr;
+
+      Double_t resol  = 0.;
+      Double_t resol2 = 0.;
+      Double_t var    = 0.;
+      Int_t    num    = 0;
+
+      MHCamera camres(geom,"CamRes","Time Resolution;Time Resolution [ns];channels");
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[j];
+          const MCalibrationRelTimePix &relpix = (MCalibrationRelTimePix&)(*relcam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+          //
+          //
+          if (aidx != geom[j].GetAidx())
+            continue;
+          
+          const Double_t pres = (Double_t)relpix.GetTimePrecision();
+
+          resol  += pres;
+          resol2 += pres;
+          num++;
+          
+          camres.Fill(j,pres);
+          camres.SetUsed(j);
+        }
+      
+      if (num > 100)
+        {
+          resol /= num;
+          var  = (resol2 - resol*resol*num) / (num-1);
+
+          res[cnt] = resol;
+          if (var > 0.)
+            reserr[cnt] = TMath::Sqrt(var);
+          else
+            reserr[cnt] = 0.;
+
+          //
+          // Make also a Gauss-fit to the distributions. The RMS can be determined by 
+          // outlier, thus we look at the sigma and the RMS and take the smaller one, afterwards.
+          // 
+          h = camres.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+          h->SetDirectory(NULL);
+          h->Fit("gaus","QL");
+          TF1 *fit = h->GetFunction("gaus");
+
+          Double_t ci2   = fit->GetChisquare();
+          Double_t sigma = fit->GetParameter(2);
+
+          if (ci2 > 500. || sigma > reserr[cnt])
+            {
+              h->Fit("gaus","QLM");
+              fit = h->GetFunction("gaus");
+
+              ci2   = fit->GetChisquare();
+              sigma = fit->GetParameter(2);
+            }
+          
+          const Double_t mean  = fit->GetParameter(1);
+          const Int_t ndf      = fit->GetNDF();
+          
+          *fLog << inf << "Mean number photo-electrons: " << sig[cnt] << endl;
+          *fLog << inf << "Time Resolution area idx: " << aidx << " Results: " << endl;
+          *fLog << inf << "Mean: " << Form("%4.3f",mean) 
+                << "+-" << Form("%4.3f",fit->GetParError(1))
+                << "  Sigma: " << Form("%4.3f",sigma) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+                << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+
+          delete h;
+          gROOT->GetListOfFunctions()->Remove(fit);
+
+          if ((sigma < reserr[cnt] || reserr[cnt]<0.001) && ndf > 2)
+            {
+              res   [cnt] = mean;
+              reserr[cnt] = sigma;
+            }
+	  else
+	    *fLog << warn << "Do not take fit results, but Mean and RMS: " << Form("%4.3f",res[cnt]) << "+-" << Form("%4.3f",reserr[cnt]) << endl;
+
+          res[cnt]    *= norm;
+          reserr[cnt] *= norm;
+	  cnt++;
+        }
+   }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                      sig.GetArray(),res.GetArray(),
+                                      sigerr.GetArray(),reserr.GetArray());
+  gr->SetTitle(Form("%s%3i","Area Index ",aidx));
+  gr->GetXaxis()->SetTitle("<phes> [1]");
+  gr->GetYaxis()->SetTitle("Time Resolution [ns]");      
+  return gr;
+}
+
+TGraphErrors *MCalibrationIntensityRelTimeCam::GetTimeResVsSqrtPhePerArea( const Int_t aidx,const MCalibrationIntensityChargeCam &chargecam, const MGeomCam &geom, const MCalibrationCam::PulserColor_t col)
+{
+  
+  const Int_t size = CountNumEntries(col);
+  
+  if (size == 0)
+    return NULL;
+
+  const Int_t asiz = chargecam.CountNumEntries(col);
+
+  if (size != asiz)
+    {
+      *fLog << err << GetDescriptor() << ": Size mismatch in colour between MCalibrationIntensityRelTimeCam "
+            << "and MCalibrationIntensityChargeCam. " << endl;
+      return NULL;
+    }
+  
+  const Float_t sqrt2   = 1.414;
+  const Float_t fadc2ns = 3.333;
+  const Float_t norm    = fadc2ns / sqrt2;
+
+  TArrayF res(size);
+  TArrayF reserr(size);
+  TArrayF sig(size);
+  TArrayF sigerr(size);
+  
+  Int_t cnt = 0;
+
+  TH1D *h = 0;
+
+  for (Int_t i=0;i<GetSize();i++)
+    {
+      //
+      // Get the calibration cam from the intensity cam
+      //
+      MCalibrationRelTimeCam *relcam = (MCalibrationRelTimeCam*)GetCam(i);
+      MCalibrationChargeCam *cam = (MCalibrationChargeCam*)chargecam.GetCam(i);
+
+      if (relcam->GetPulserColor() != col && col != MCalibrationCam::kNONE)
+        continue;
+
+      const MCalibrationChargePix &apix = (MCalibrationChargePix&)cam->GetAverageArea(aidx);
+      const Float_t phe          = apix.GetPheFFactorMethod();
+      const Float_t phesq        = phe > 0. ? TMath::Sqrt(phe) : 0.;
+      const Float_t phesqerr     = phe > 0. ? 0.5*apix.GetPheFFactorMethodErr()/phesq : 0.;
+
+      sig[cnt]       = phesq;
+      sigerr[cnt]    = phesqerr;
+
+      Double_t resol  = 0.;
+      Double_t resol2 = 0.;
+      Double_t var    = 0.;
+      Int_t    num    = 0;
+
+      MHCamera camres(geom,"CamRes","Time Resolution;Time Resolution [ns];channels");
+      //
+      // Get the area calibration pix from the calibration cam
+      //
+      for (Int_t j=0; j<cam->GetSize(); j++)
+        {
+          const MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)[j];
+          const MCalibrationRelTimePix &relpix = (MCalibrationRelTimePix&)(*relcam)[j];
+          //
+          // Don't use bad pixels
+          //
+          if (!pix.IsFFactorMethodValid())
+            continue;
+          //
+          //
+          if (aidx != geom[j].GetAidx())
+            continue;
+          
+          const Float_t pres = relpix.GetTimePrecision();
+
+          resol  += pres;
+          resol2 += pres;
+          num++;
+          
+          camres.Fill(j,pres);
+          camres.SetUsed(j);
+        }
+      
+      if (num > 1)
+        {
+          resol /= num;
+          var  = (resol2 - resol*resol*num) / (num-1);
+
+          res[cnt] = resol;
+          if (var > 0.)
+            reserr[cnt] = TMath::Sqrt(var);
+          else
+            reserr[cnt] = 0.;
+
+          //
+          // Make also a Gauss-fit to the distributions. The RMS can be determined by 
+          // outlier, thus we look at the sigma and the RMS and take the smaller one, afterwards.
+          // 
+          h = camres.ProjectionS(TArrayI(),TArrayI(1,&aidx),"_py",750);
+          h->SetDirectory(NULL);
+          h->Fit("gaus","QL");
+          TF1 *fit = h->GetFunction("gaus");
+
+          Float_t ci2   = fit->GetChisquare();
+          Float_t sigma = fit->GetParameter(2);
+
+          if (ci2 > 500. || sigma > reserr[cnt])
+            {
+              h->Fit("gaus","QLM");
+              fit = h->GetFunction("gaus");
+
+              ci2   = fit->GetChisquare();
+              sigma = fit->GetParameter(2);
+            }
+          
+          const Float_t mean  = fit->GetParameter(1);
+          const Float_t ndf   = fit->GetNDF();
+
+          
+          *fLog << inf << "Sqrt Mean number photo-electrons: " << sig[cnt] << endl;
+          *fLog << inf << "Time Resolution area idx: " << aidx << " Results: " << endl;
+          *fLog << inf << "Mean: " << Form("%4.3f",mean) 
+                << "+-" << Form("%4.3f",fit->GetParError(1))
+                << "  Sigma: " << Form("%4.3f",sigma) << "+-" << Form("%4.3f",fit->GetParError(2)) 
+                << "  Chisquare: " << Form("%4.3f",fit->GetChisquare()) << "  NDF  : " << ndf << endl;          
+
+          delete h;
+          gROOT->GetListOfFunctions()->Remove(fit);
+
+          if (sigma < reserr[cnt] && ndf > 2)
+            {
+              res   [cnt] = mean;
+              reserr[cnt] = sigma;
+            }
+
+          res[cnt]    *= norm;
+          reserr[cnt] *= norm;
+        }
+      else
+        {
+          res[cnt]    = -1.;
+          reserr[cnt] = 0.;
+        }
+      cnt++;
+   }
+  
+  TGraphErrors *gr = new TGraphErrors(size,
+                                      sig.GetArray(),res.GetArray(),
+                                      sigerr.GetArray(),reserr.GetArray());
+  gr->SetTitle(Form("%s%3i","Area Index ",aidx));
+  gr->GetXaxis()->SetTitle("Sqrt(<phes>) [1]");
+  gr->GetYaxis()->SetTitle("Time Resolution [ns]");      
+  return gr;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityRelTimeCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityRelTimeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityRelTimeCam.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MCalibrationIntensityRelTimeCam
+#define MARS_MCalibrationIntensityRelTimeCam
+
+#ifndef MARS_MCalibrationIntensityCam
+#include "MCalibrationIntensityCam.h"
+#endif
+
+#ifndef MARS_MCalibrationIntensityChargeCam
+#include "MCalibrationIntensityChargeCam.h"
+#endif
+
+class TGraphErrors;
+class MCalibrationIntensityRelTimeCam : public MCalibrationIntensityCam
+{
+private:
+
+  void Add(const UInt_t from, const UInt_t to);
+
+public:
+
+  MCalibrationIntensityRelTimeCam(const char *name=NULL, const char *title=NULL);
+
+  TGraphErrors *GetTimeResVsCharge( const UInt_t pixid, const MCalibrationIntensityChargeCam &chargecam,
+                                    const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+
+  TGraphErrors *GetTimeResVsChargePerArea( const Int_t aidx, const MCalibrationIntensityChargeCam &chargecam,
+                                           const MGeomCam &geom,
+                                           const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+
+  TGraphErrors *GetTimeResVsSqrtPhePerArea( const Int_t aidx, const MCalibrationIntensityChargeCam &chargecam,
+                                           const MGeomCam &geom,
+                                           const MCalibrationCam::PulserColor_t col=MCalibrationCam::kNONE);
+
+  ClassDef(MCalibrationIntensityRelTimeCam, 1) // Container Intensity Rel.Times Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityTestCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityTestCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityTestCam.cc	(revision 9772)
@@ -0,0 +1,71 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationIntensityTestCam                                               
+//                                                               
+// Storage container for intensity charge calibration results. 
+// 
+// Individual MCalibrationTestCam's can be retrieved with: 
+// - GetCam() yielding the current cam.
+// - GetCam("name") yielding the current camera with name "name".
+// - GetCam(i) yielding the i-th camera.
+//
+// See also: MCalibrationIntensityCam, MCalibrationTestCam,
+//           MCalibrationTestPix, MCalibrationTestCalc, MCalibrationQECam
+//           MHCalibrationTestCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationIntensityTestCam.h"
+#include "MCalibrationTestCam.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MCalibrationIntensityTestCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationIntensityTestCam::MCalibrationIntensityTestCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationIntensityTestCam";
+  fTitle = title ? title : "Results of the Intensity Calibration";
+  
+  InitSize(1);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationTestCam's in the ranges from - to. 
+//
+void MCalibrationIntensityTestCam::Add(const UInt_t from, const UInt_t to)
+{
+  for (UInt_t i=from; i<to; i++)
+    fCams->AddAt(new MCalibrationTestCam,i);
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationIntensityTestCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationIntensityTestCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationIntensityTestCam.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MCalibrationIntensityTestCam
+#define MARS_MCalibrationIntensityTestCam
+
+#ifndef MARS_MCalibrationIntensityCam
+#include "MCalibrationIntensityCam.h"
+#endif
+
+class MCalibrationIntensityTestCam : public MCalibrationIntensityCam
+{
+private:
+  
+  void Add(const UInt_t from, const UInt_t to);
+  
+public:
+
+  MCalibrationIntensityTestCam(const char *name=NULL, const char *title=NULL);
+  
+  ClassDef(MCalibrationIntensityTestCam, 1) // Container Intensity Rel.Times Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationPattern.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPattern.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPattern.cc	(revision 9772)
@@ -0,0 +1,57 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz  12/2004 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationPattern
+//
+//  A container to store the decoded calibration pattern.
+//
+// The idea is, that this container will never change the meaning of its
+// variables, while the calibration pattern itself could.
+//
+// If new 'features' are necessary the decoding (MCalibrationPatternDecode)
+// must be changed to correctly decode the pattern into the existing
+// MCalibrationPattern. If new information is decoded you may have to
+// add new variables to this container. Don't forget to increase the
+// class version number (ClassDef) and document your change HERE.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPattern.h"
+
+ClassImp(MCalibrationPattern);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MCalibrationPattern::MCalibrationPattern(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCalibrationPattern";
+    fTitle = title ? title : "Container for decoded calibration pattern";
+
+    Reset();
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationPattern.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPattern.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPattern.h	(revision 9772)
@@ -0,0 +1,63 @@
+#ifndef MARS_MCalibrationPattern
+#define MARS_MCalibrationPattern
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationPattern : public MParContainer
+{
+    friend class MCalibrationPatternDecode;
+
+public:
+
+    enum CLColor_t 
+      {
+        kCLUV       = BIT(0),
+        kCLGreen    = BIT(1),
+        kCLAmber    = BIT(2),
+        kCLRed      = BIT(3),
+        kCLRedAmber   = kCLRed & kCLAmber,
+        kCLRedGreen   = kCLRed & kCLGreen,
+        kCLRedUV      = kCLRed & kCLUV   ,
+        kCLAmberGreen = kCLAmber & kCLGreen,
+        kCLAmberUV    = kCLAmber & kCLUV   ,
+        kCLGreenUV    = kCLGreen & kCLUV   ,
+        kCLRedAmberGreen = kCLRedAmber & kCLGreen,
+        kCLRedGreenUV    = kCLRedGreen & kCLUV,
+        kCLAmberGreenUV  = kCLAmberGreen & kCLUV,
+        kCLAll           = kCLRedAmberGreen & kCLUV,
+	kCLNone    = BIT(4)
+      };
+    
+private:
+
+    UShort_t  fCLStrength;     // Continuous light strenth  
+    CLColor_t fCLColor;        // Color (combinations) of the continuous light
+    Float_t   fPulserStrength; // Strength of the pulsed light (in nr. of equiv. LEDs)
+    
+    MCalibrationCam::PulserColor_t fPulserColor; // Colour of the pulsed light
+
+public:
+
+    MCalibrationPattern(const char *name=0, const char *title=0);
+
+    void Reset() { fCLStrength=0; fCLColor=kCLNone; fPulserColor=MCalibrationCam::kNONE; fPulserStrength=0.; }
+
+    UShort_t   GetCLStrength()     const { return fCLStrength; }
+    CLColor_t  GetCLColor()        const { return fCLColor; }
+    Float_t    GetPulserStrength() const { return fPulserStrength; }
+
+    const MCalibrationCam::PulserColor_t GetPulserColor() const { return fPulserColor; }
+
+    void SetPulserColor   ( const MCalibrationCam::PulserColor_t col) { fPulserColor = col; }
+    void SetPulserStrength( const Float_t strength ) { fPulserStrength = strength; }
+
+    ClassDef(MCalibrationPattern, 1) // Container storing the decoded calibration pattern
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationPatternDecode.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPatternDecode.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPatternDecode.cc	(revision 9772)
@@ -0,0 +1,178 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz 12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationPatternDecode
+//
+//  Decodes the trigger pattern from MRawEvtData into MCalibrationPattern.
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+// This can be changed using the information about the file-type.
+//
+// Input:
+//   MRawEvtData
+//
+// Output:
+//   MCalibrationPattern
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPatternDecode.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+#include "MCalibrationPattern.h"
+
+ClassImp(MCalibrationPatternDecode);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MCalibrationPatternDecode::MCalibrationPatternDecode(const char *name, const char *title)
+    : fRunHeader(0), fEvtHeader(0), fPattern(0)
+{
+    fName  = name  ? name  : "MCalibrationPatternDecode";
+    fTitle = title ? title : "Task to decode Trigger Pattern";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MCalibrationPatternDecode::PreProcess(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
+    if (!fRunHeader)
+    {
+	*fLog << err << "MRawRunHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    fEvtHeader = (MRawEvtHeader *)pList->FindObject("MRawEvtHeader");
+    if (!fEvtHeader)
+    {
+	*fLog << err << "MRawEvtHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    fPattern = (MCalibrationPattern*)pList->FindCreateObj("MCalibrationPattern");
+    if (!fPattern)
+    {
+	*fLog << err << "MCalibratinPattern not found... abort." << endl;
+	return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+// This can be changed using the information about the file-type.
+//
+Int_t MCalibrationPatternDecode::Process()
+{
+    // No setting necessary because MCalibrationPattern::reset() has
+    // been called just before
+    if (fRunHeader->GetFormatVersion()<5)
+      return kTRUE;
+
+    UInt_t pattern = fEvtHeader->GetCalibrationPattern();
+
+    fPattern->fCLStrength = pattern & 0xff;
+    fPattern->fCLColor    = (MCalibrationPattern::CLColor_t)((pattern>>8)&0xf);
+    
+    const UInt_t pulserpattern = (pattern >> 16) & 0xffff;
+
+    fPattern->fPulserColor =  MCalibrationCam::kNONE;    
+
+    if ((pulserpattern & kGreenAndBlue) || (pulserpattern & kBlueAndUV) || (pulserpattern & kGreenAndUV))
+      fPattern->fPulserColor =  MCalibrationCam::kNONE;
+    if (pulserpattern & kCT1Pulser)
+      fPattern->fPulserColor =  MCalibrationCam::kCT1;
+    if (pulserpattern & kAnyUV)
+      fPattern->fPulserColor =  MCalibrationCam::kUV;
+    if (pulserpattern & kAnyGreen)
+      fPattern->fPulserColor =  MCalibrationCam::kGREEN;
+    if (pulserpattern & kAnyBlue)
+      fPattern->fPulserColor =  MCalibrationCam::kBLUE;
+
+    Float_t strength = 0.;
+
+    switch (fPattern->fPulserColor)
+      {
+      case MCalibrationCam::kNONE:
+	break;
+      case MCalibrationCam::kGREEN:
+        if (pulserpattern & kSlot1Green)
+          strength += 5.;
+        if (pulserpattern & kSlot2Green)
+          strength += 2.;
+        if (pulserpattern & kSlot15Green)
+          strength += 1.;
+        if (pulserpattern & kSlot16AttGreen)
+          strength += 0.2;
+	break;      
+      case MCalibrationCam::kBLUE:
+        if (pulserpattern & kSlot3Blue)
+          strength += 5.1;
+        if (pulserpattern & kSlot6Blue)
+          strength += 5.2;
+        if (pulserpattern & kSlot7Blue)
+          strength += 5.4;
+        if (pulserpattern & kSlot8Blue)
+          strength += 2.;
+        if (pulserpattern & kSlot9AttBlue)
+          strength += 0.25;
+        if (pulserpattern & kSlot10Blue)
+          strength += 0.;
+        if (pulserpattern & kSlot11Blue)
+          strength += 1.;
+        if (pulserpattern & kSlot14Blue)
+          strength += 5.8;
+	break;      
+      case MCalibrationCam::kUV:
+        if (pulserpattern & kSlot4UV)
+          strength += 1.;
+        if (pulserpattern & kSlot5UV)
+          strength += 2.;
+        if (pulserpattern & kSlot12UV)
+          strength += 5.1;
+        if (pulserpattern & kSlot13UV)
+          strength += 5.2;
+	break;      
+      case MCalibrationCam::kCT1:
+	strength = 20.;
+	break;      
+      }
+  
+    fPattern->fPulserStrength = strength;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationPatternDecode.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPatternDecode.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPatternDecode.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MCalibrationPatternDecode
+#define MARS_MCalibrationPatternDecode
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MRawEvtHeader;
+class MRawRunHeader;
+class MCalibrationPattern;
+
+class MCalibrationPatternDecode : public MTask
+{
+private:
+
+    enum PulserColorCode_t 
+      {
+        kSlot1Green     = BIT(0),
+        kSlot2Green     = BIT(1),
+        kSlot3Blue      = BIT(2),
+        kSlot4UV        = BIT(3),
+        kSlot5UV        = BIT(4),
+        kSlot6Blue      = BIT(5),
+        kSlot7Blue      = BIT(6),
+        kSlot8Blue      = BIT(7),
+        kSlot9AttBlue   = BIT(8),
+        kSlot10Blue     = BIT(9),
+        kSlot11Blue     = BIT(10),
+        kSlot12UV       = BIT(11),
+        kSlot13UV       = BIT(12),
+        kSlot14Blue     = BIT(13),
+        kSlot15Green    = BIT(14),
+        kSlot16AttGreen = BIT(15),
+        kCT1Pulser      = BIT(16),
+        kAnyGreen       = kSlot1Green  | kSlot2Green | kSlot15Green | kSlot16AttGreen,
+        kAnyUV          = kSlot4UV     | kSlot5UV    | kSlot12UV    | kSlot13UV,
+        kAnyBlue        = kSlot3Blue   | kSlot6Blue  | kSlot7Blue   | kSlot8Blue 
+                        | kSlot9AttBlue| kSlot10Blue | kSlot11Blue  | kSlot14Blue, 
+        kGreenAndBlue   = kAnyGreen & kAnyBlue,
+        kBlueAndUV      = kAnyBlue  & kAnyUV,
+        kGreenAndUV     = kAnyGreen & kAnyUV,
+        kIFAEPulser     = kAnyGreen | kAnyBlue | kAnyUV,
+        kAny            = kAnyGreen | kAnyBlue | kAnyUV | kCT1Pulser
+      };
+
+    MRawRunHeader   *fRunHeader;
+    MRawEvtHeader   *fEvtHeader;
+    MCalibrationPattern *fPattern;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+
+    MCalibrationPatternDecode(const char *name=0, const char *title=0);
+
+    ClassDef(MCalibrationPatternDecode, 1) // Task to decode the Trigger Pattern
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationPedCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPedCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPedCam.cc	(revision 9772)
@@ -0,0 +1,152 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationPedCam                                               
+//                                                               
+// Hold the pedestal Calibration results obtained from MHPedestalCam of the camera:
+//                                                               
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Pedestal
+// 1: Error of fitted Pedestal
+// 2: Sigma of fitted Pedestal
+// 3: Error of Sigma of fitted Pedestal
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Pedestal distribution
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPedCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationPix.h"
+
+ClassImp(MCalibrationPedCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Creates a TClonesArray of MCalibrationPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MCalibrationRelTimeCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MCalibrationRelTimeCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MCalibrationRelTimeCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+MCalibrationPedCam::MCalibrationPedCam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCalibrationPedCam";
+    fTitle = title ? title : "Storage container for the Pedestal Calibration Results in the camera";
+
+}
+
+// --------------------------------------------------------------------------
+//
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Pedestal
+// 1: Error of fitted Pedestal
+// 2: Sigma of fitted Pedestal
+// 3: Error of Sigma of fitted Pedestal
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Pedestal distribution
+//
+Bool_t MCalibrationPedCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ if ((*this)[idx].IsExcluded())
+   return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      val = (*this)[idx].GetHiGainMean();
+      break;
+    case 1:
+      val = (*this)[idx].GetHiGainMeanErr();
+      break;
+    case 2:
+      val = (*this)[idx].GetHiGainSigma();
+      break;
+    case 3:
+      val = (*this)[idx].GetHiGainSigmaErr();
+      break;
+    case 4:
+      val = (*this)[idx].GetHiGainProb();
+      break;
+    case 5:
+      val = (*this)[idx].GetLoGainMean();
+      break;
+    case 6:
+      val = (*this)[idx].GetLoGainMeanErr();
+      break;
+    case 7:
+      val = (*this)[idx].GetLoGainSigma();
+      break;
+    case 8:
+      val = (*this)[idx].GetLoGainSigmaErr();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+  
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationPedCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPedCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPedCam.h	(revision 9772)
@@ -0,0 +1,20 @@
+#ifndef MARS_MCalibrationPedCam
+#define MARS_MCalibrationPedCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationPedCam : public MCalibrationCam
+{
+public:
+
+  MCalibrationPedCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationPedCam() {}
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  
+  ClassDef(MCalibrationPedCam, 1)	// Container Pedestal Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationPix.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPix.cc	(revision 9772)
@@ -0,0 +1,461 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                     
+// MCalibrationPix                                     
+//                                                     
+// Base Storage container for a calibration pixel. Holds mean and sigmas,  
+// their errors, the fit probability and the number of pickup events for 
+// the high-gain and the low-gain derived values.    
+//                                                                         
+// Errors are stored internally as variances, but are returned and filled 
+// as square root of the variances. 
+//
+// Calls to GetMean(), GetMeanErr(), GetSigma(), GetSigmaErr(), GetProb() or 
+// GetNumPickup() and GetNumBlackout() test first the bit kHiGainSaturation 
+// before returning the high-gain or low-gain value, analogue for the 
+// corr. Setters.
+//
+// The three flags: kValid, kExcluded and kHiGainSaturation may be set.
+// The colors: kGREEN, kBLUE, kUV and kCT1 may be set. 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPix.h"
+
+ClassImp(MCalibrationPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Sets:
+// - fPixId to -1
+// - fFlags to 0
+//
+// Calls:
+// - Clear()
+//
+MCalibrationPix::MCalibrationPix(const char *name, const char *title)
+    : fPixId(-1),
+      fFlags(0)
+{
+
+  fName  = name  ? name  : "MCalibrationPix";
+  fTitle = title ? title : "Container of the fit results of MHCalibrationPixs ";
+
+  Clear();
+
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all variables to -1
+// - all flags to kFALSE
+//
+void MCalibrationPix::Clear(Option_t *o)
+{
+
+  fHiGainNumBlackout   =  -1 ;
+  fHiGainNumPickup     =  -1 ;
+  fHiGainMean          =  -1.;
+  fHiGainMeanVar       =  -1.;
+  fHiGainProb          =  -1.;
+  fHiGainRms           =  -1.;
+  fHiGainSigma         =  -1.;
+  fHiGainSigmaVar      =  -1.;
+
+  fLoGainNumBlackout   =  -1 ;
+  fLoGainNumPickup     =  -1 ;
+  fLoGainMean          =  -1.;
+  fLoGainMeanVar       =  -1.;
+  fLoGainProb          =  -1.;
+  fLoGainRms           =  -1.;
+  fLoGainSigma         =  -1.;
+  fLoGainSigmaVar      =  -1.;
+
+  SetHiGainSaturation  ( kFALSE );
+  SetExcluded          ( kFALSE );
+  SetValid             ( kFALSE );
+  SetDebug             ( kFALSE );
+
+}
+
+
+// -----------------------------------------------------
+//
+// copy 'constructor'
+//
+void MCalibrationPix::Copy(TObject& object) const
+{
+
+  MCalibrationPix &pix = (MCalibrationPix&)object;
+
+  //
+  // Copy the data members
+  //
+  pix.fPixId             = fPixId;
+  pix.fFlags             = fFlags;
+  pix.fHiGainMean        = fHiGainMean;
+  pix.fHiGainMeanVar     = fHiGainMeanVar;
+  pix.fHiGainNumBlackout = fHiGainNumBlackout;
+  pix.fHiGainNumPickup   = fHiGainNumPickup;
+  pix.fHiGainSigma       = fHiGainSigma;
+  pix.fHiGainSigmaVar    = fHiGainSigmaVar;
+  pix.fHiGainProb        = fHiGainProb;
+  pix.fLoGainMean        = fLoGainMean;
+  pix.fLoGainMeanVar     = fLoGainMeanVar;
+  pix.fLoGainNumBlackout = fLoGainNumBlackout;
+  pix.fLoGainNumPickup   = fLoGainNumPickup;
+  pix.fLoGainSigma       = fLoGainSigma;
+  pix.fLoGainSigmaVar    = fLoGainSigmaVar;
+  pix.fLoGainProb        = fLoGainProb;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the Hi Gain Saturation Bit from outside
+//
+void MCalibrationPix::SetHiGainSaturation(Bool_t b)
+{
+    b ?  SETBIT(fFlags, kHiGainSaturation) : CLRBIT(fFlags, kHiGainSaturation); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Valid Bit from outside 
+//
+void MCalibrationPix::SetDebug(Bool_t b )
+{ 
+    b ?  SETBIT(fFlags, kDebug) : CLRBIT(fFlags, kDebug); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Excluded Bit from outside 
+//
+void MCalibrationPix::SetExcluded(Bool_t b )
+{ 
+    b ?  SETBIT(fFlags, kExcluded) : CLRBIT(fFlags, kExcluded); 
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Valid Bit from outside 
+//
+void MCalibrationPix::SetValid(Bool_t b )
+{ 
+    b ?  SETBIT(fFlags, kValid) : CLRBIT(fFlags, kValid); 
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Mean is smaller than 0.5
+// Return -1, if the HiGain Mean is -1.         (has not yet been set) 
+// Return fHiGainMean / fLoGainMean
+//
+Float_t MCalibrationPix::GetHiLoMeansDivided() const
+{
+  
+  if (IsHiGainSaturation())
+    return -1.;
+
+  if (fLoGainMean <= 0.5)
+    return -1.;
+
+  if (fHiGainMean == -1.)
+    return -1.;
+  
+  return fHiGainMean / fLoGainMean;
+  
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Mean or its variance is smaller than 0.5 (has not yet been set)
+// Return -1, if the HiGain Mean or its variance is -1.         (has not yet been set) 
+// Return propagated error of GetHiLoMeansDivided()
+//
+Float_t MCalibrationPix::GetHiLoMeansDividedErr() const
+{
+  
+  if (IsHiGainSaturation())
+    return -1.;
+
+  if (fLoGainMean <= 0.5)
+    return -1.;
+
+  if (fHiGainMean == -1.)
+    return -1.;
+  
+  if (fLoGainMeanVar <= 0.)
+    return -1.;
+
+  if (fHiGainMeanVar <= 0.)
+    return -1.;
+  
+  const Float_t lomeansquare = fLoGainMean * fLoGainMean;
+  const Float_t deltaHi = fHiGainMeanVar / lomeansquare;
+  const Float_t deltaLo = fLoGainMeanVar / (lomeansquare * lomeansquare) * fHiGainMean * fHiGainMean;
+
+  return TMath::Sqrt(deltaHi + deltaLo);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Sigma is smaller than 0.01 
+// Return -1, if the HiGain Sigma is -1.         (has not yet been set) 
+// Return fHiGainSigma / fLoGainSigma
+//
+Float_t MCalibrationPix::GetHiLoSigmasDivided() const
+{
+  
+  if (IsHiGainSaturation())
+    return -1.;
+
+  if (fLoGainSigma <= 0.01)
+    return -1.;
+
+  if (fHiGainSigma == -1.)
+    return -1.;
+  
+  return fHiGainSigma / fLoGainSigma;
+  
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Sigma variance is smaller than 0.
+// Return -1, if the LoGain Sigma is smaller than 0.01
+// Return -1, if the HiGain Sigma or its variance is -1.         (has not yet been set) 
+// Return propagated error of GetHiLoSigmasDivided()
+//
+Float_t MCalibrationPix::GetHiLoSigmasDividedErr() const
+{
+  
+  if (IsHiGainSaturation())
+    return -1.;
+
+  if (fLoGainSigma <= 0.01) 
+    return -1.;
+
+  if (fHiGainSigma == -1.)
+    return -1.;
+  
+  if (fLoGainSigmaVar <= 0.)
+    return -1.;
+
+  if (fHiGainSigmaVar <= 0.)
+    return -1.;
+  
+  const Float_t losigmasquare = fLoGainSigma * fLoGainSigma;
+  const Float_t deltaHi = fHiGainSigmaVar / losigmasquare;
+  const Float_t deltaLo = fLoGainSigmaVar / (losigmasquare * losigmasquare) * fHiGainSigma * fHiGainSigma;
+
+  return TMath::Sqrt(deltaHi + deltaLo);
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the Relative Variance of either High Gain or Low Gain Mean 
+// depending on IsHighGainSaturation()
+//
+// If variance is smaller than 0. return -1.
+//
+Float_t MCalibrationPix::GetMeanRelVar()  const
+{
+
+  if (IsHiGainSaturation())
+    if (fLoGainMeanVar < 0. || fLoGainMean < 0.)
+      return -1.;
+    else
+      return fLoGainMeanVar / (fLoGainMean * fLoGainMean);
+  else
+    if (fHiGainMeanVar < 0. || fHiGainMean < 0.)
+      return -1.;
+    else
+      return fHiGainMeanVar / (fHiGainMean * fHiGainMean);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Square of either High Gain or Low Gain Mean 
+// depending on IsHighGainSaturation()
+//
+Float_t MCalibrationPix::GetMeanSquare()  const
+{
+
+  if (IsHiGainSaturation())
+    return fLoGainMean == -1. ? -1. : fLoGainMean * fLoGainMean;
+  else
+    return fHiGainMean == -1. ? -1. : fHiGainMean * fHiGainMean;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the Relative Variance of either High Gain or Low Gain Sigma 
+// depending on IsHighGainSaturation()
+//
+// If variance is smaller than 0. return -1.
+//
+Float_t MCalibrationPix::GetSigmaRelVar()  const
+{
+
+  if (IsHiGainSaturation())
+    if (fLoGainSigmaVar < 0.)
+      return -1.;
+    else
+      return fLoGainSigmaVar / (fLoGainSigma * fLoGainSigma);
+  else
+    if (fHiGainSigmaVar < 0.)
+      return -1.;
+    else
+      return fHiGainSigmaVar / (fHiGainSigma * fHiGainSigma);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the High Gain Mean Error: Takes square root of fHiGainMeanVar
+//
+Float_t MCalibrationPix::GetHiGainMeanErr()  const
+{
+  if (fHiGainMeanVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fHiGainMeanVar);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the High Gain Sigma Error: Takes square root of fHiGainSigmaVar
+//
+Float_t MCalibrationPix::GetHiGainSigmaErr()  const
+{
+  if (fHiGainSigmaVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fHiGainSigmaVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Mean Error: Takes square root of fLoGainMeanVar
+//
+Float_t MCalibrationPix::GetLoGainMeanErr()  const
+{
+  if (fLoGainMeanVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fLoGainMeanVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Mean Rel Variance
+//
+Float_t MCalibrationPix::GetLoGainMeanRelVar()  const
+{
+  if (fLoGainMeanVar < 0.)
+    return -1.;
+  if (fLoGainMean   == 0.)
+    return -1.;
+
+  return fLoGainMeanVar / ( fLoGainMean * fLoGainMean);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the High Gain Mean Rel Variance
+//
+Float_t MCalibrationPix::GetHiGainMeanRelVar()  const
+{
+  if (fHiGainMeanVar < 0.)
+    return -1.;
+  if (fHiGainMean   == 0.)
+    return -1.;
+
+  return fHiGainMeanVar / ( fHiGainMean * fHiGainMean);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Sigma Error: Takes square root of fHiGainSigmaVar
+//
+Float_t MCalibrationPix::GetLoGainSigmaErr()  const
+{
+  if (fLoGainSigmaVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fLoGainSigmaVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kHiGainSaturation
+//
+Bool_t MCalibrationPix::IsHiGainSaturation()    const
+{ 
+  return TESTBIT(fFlags,kHiGainSaturation);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kDebug
+//
+Bool_t MCalibrationPix::IsDebug()     const
+{ 
+   return TESTBIT(fFlags,kDebug);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kExcluded
+//
+Bool_t MCalibrationPix::IsExcluded()     const
+{ 
+   return TESTBIT(fFlags,kExcluded);  
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kValid
+//
+Bool_t MCalibrationPix::IsValid()     const
+{ 
+   return TESTBIT(fFlags,kValid);  
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationPix.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPix.h	(revision 9772)
@@ -0,0 +1,124 @@
+#ifndef MARS_MCalibrationPix
+#define MARS_MCalibrationPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCalibrationPix : public MParContainer
+{
+protected:
+
+  Int_t   fPixId;             // Software PixId (needed to get Id in calls to Next())
+  UInt_t  fFlags;             // Flag for the set bits
+  Float_t fHiGainMean;        // Mean from fit to high gain values
+  Float_t fHiGainMeanVar;     // Error of mean from fit to high gain values
+  Float_t fHiGainNumBlackout; // Number blackout events in high-gain
+  Float_t fHiGainNumPickup;   // Number pickup events in high-gain
+  Float_t fHiGainRms;         // Histogram RMS of the high gain values
+  Float_t fHiGainSigma;       // Sigma from fit to high gain values
+  Float_t fHiGainSigmaVar;    // Error of sigma from fit to high gain values
+  Float_t fHiGainProb;        // Probability of fit to high gain values
+  Float_t fLoGainMean;        // Mean from fit to high gain values
+  Float_t fLoGainMeanVar;     // Error of mean from fit to low gain values
+  Float_t fLoGainNumBlackout; // Number blackout events in low-gain
+  Float_t fLoGainNumPickup;   // Number pickup events in low-gain
+  Float_t fLoGainRms;         // Histogram RMS of the low-gain values  
+  Float_t fLoGainSigma;       // Sigma of from fit to low gain values
+  Float_t fLoGainSigmaVar;    // Error of sigma from fit to low gain values
+  Float_t fLoGainProb;        // Probability of fit to low gain values
+
+  enum { kHiGainSaturation, kExcluded, kValid, kDebug };   // Possible bits to be sets
+
+public:
+
+  MCalibrationPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationPix() {}
+  
+  void Clear(Option_t *o="");
+  void Copy(TObject& object) const;
+  
+  // Setter
+  void SetPixId( const Int_t i )   { fPixId = i; }
+
+  void SetHiGainMean        ( const Float_t f ) { fHiGainMean        = f; }
+  void SetHiGainMeanVar     ( const Float_t f ) { fHiGainMeanVar     = f; }
+  void SetHiGainNumBlackout ( const Float_t f ) { fHiGainNumBlackout = f; }
+  void SetHiGainNumPickup   ( const Float_t f ) { fHiGainNumPickup   = f; }
+  void SetHiGainProb        ( const Float_t f ) { fHiGainProb        = f; }
+  void SetHiGainRms         ( const Float_t f ) { fHiGainRms         = f; }
+  void SetHiGainSigma       ( const Float_t f ) { fHiGainSigma       = f; }  
+  void SetHiGainSigmaVar    ( const Float_t f ) { fHiGainSigmaVar    = f; }
+  void SetLoGainMean        ( const Float_t f ) { fLoGainMean        = f; }
+  void SetLoGainMeanVar     ( const Float_t f ) { fLoGainMeanVar     = f; }
+  void SetLoGainNumBlackout ( const Float_t f ) { fLoGainNumBlackout = f; }  
+  void SetLoGainNumPickup   ( const Float_t f ) { fLoGainNumPickup   = f; }
+  void SetLoGainProb        ( const Float_t f ) { fLoGainProb        = f; }
+  void SetLoGainRms         ( const Float_t f ) { fLoGainRms         = f; }
+  void SetLoGainSigma       ( const Float_t f ) { fLoGainSigma       = f; }
+  void SetLoGainSigmaVar    ( const Float_t f ) { fLoGainSigmaVar    = f; }
+  void SetMean       ( const Float_t f ) { IsHiGainSaturation() ? fLoGainMean        = f : fHiGainMean        = f      ; }
+  void SetMeanVar    ( const Float_t f ) { IsHiGainSaturation() ? fLoGainMeanVar     = f : fHiGainMeanVar     = f  ;  }
+  void SetNumBlackout( const Float_t f ) { IsHiGainSaturation() ? fLoGainNumBlackout = f : fHiGainNumBlackout = f ; }  
+  void SetNumPickup  ( const Float_t f ) { IsHiGainSaturation() ? fLoGainNumPickup   = f : fHiGainNumPickup   = f ; }
+  void SetProb       ( const Float_t f ) { IsHiGainSaturation() ? fLoGainProb        = f : fHiGainProb        = f      ; }
+  void SetSigma      ( const Float_t f ) { IsHiGainSaturation() ? fLoGainSigma       = f : fHiGainSigma       = f     ; }
+  void SetSigmaVar   ( const Float_t f ) { IsHiGainSaturation() ? fLoGainSigmaVar    = f : fHiGainSigmaVar    = f  ; }
+
+  void SetDebug           ( const Bool_t  b = kTRUE );  
+  void SetExcluded        ( const Bool_t  b = kTRUE );
+  void SetHiGainSaturation( const Bool_t  b = kTRUE );
+  void SetValid           ( const Bool_t  b = kTRUE );
+  
+  // Getters
+  Float_t GetHiGainMean       () const { return fHiGainMean   ;     }
+  Float_t GetHiGainMeanErr    () const;
+  Float_t GetHiGainMeanVar    () const { return fHiGainMeanVar;     }
+  Float_t GetHiGainMeanRelVar () const;
+  Float_t GetHiGainProb       () const { return fHiGainProb   ;     }
+  Float_t GetHiGainRms        () const { return fHiGainRms    ;     }  
+  Float_t GetHiGainSigma      () const { return fHiGainSigma  ;     }
+  Float_t GetHiGainSigmaErr   () const;
+  Float_t GetHiGainSigmaVar   () const { return fHiGainSigmaVar;    }
+  Float_t GetHiGainNumPickup  () const { return fHiGainNumPickup;   }
+  Float_t GetHiGainNumBlackout() const { return fHiGainNumBlackout; }  
+  Float_t GetHiLoMeansDivided         () const;
+  Float_t GetHiLoMeansDividedErr      () const;
+  Float_t GetHiLoSigmasDivided        () const;
+  Float_t GetHiLoSigmasDividedErr     () const;
+
+  virtual Float_t GetLoGainMean       () const { return fLoGainMean;        }
+  virtual Float_t GetLoGainMeanErr    () const;
+  virtual Float_t GetLoGainMeanVar    () const { return fLoGainMeanVar;     }
+  virtual Float_t GetLoGainMeanRelVar () const;  
+  virtual Float_t GetLoGainProb       () const { return fLoGainProb;        }
+  virtual Float_t GetLoGainRms        () const { return fLoGainRms  ;       }
+  virtual Float_t GetLoGainSigma      () const { return fLoGainSigma;       }  
+  virtual Float_t GetLoGainSigmaErr   () const;
+  virtual Float_t GetLoGainSigmaVar   () const { return fLoGainSigmaVar;    }
+  virtual Float_t GetLoGainNumPickup  () const { return fLoGainNumPickup;   }
+  virtual Float_t GetLoGainNumBlackout() const { return fLoGainNumBlackout; }  
+
+  Float_t GetMean       () const { return IsHiGainSaturation() ? GetLoGainMean()        : GetHiGainMean()     ;   }
+  Float_t GetMeanErr    () const { return IsHiGainSaturation() ? GetLoGainMeanErr()     : GetHiGainMeanErr()  ;   }
+  Float_t GetMeanRelVar () const;
+  Float_t GetMeanSquare () const;  
+  Float_t GetRms        () const { return IsHiGainSaturation() ? GetLoGainRms()         : GetHiGainRms()      ;   }
+  Float_t GetProb       () const { return IsHiGainSaturation() ? GetLoGainProb()        : GetHiGainProb()     ;   }
+  Float_t GetSigma      () const { return IsHiGainSaturation() ? GetLoGainSigma()       : GetHiGainSigma()    ;   }
+  Float_t GetSigmaErr   () const { return IsHiGainSaturation() ? GetLoGainSigmaErr()    : GetHiGainSigmaErr() ;   }
+  Float_t GetSigmaRelVar() const;
+  Float_t GetNumPickup  () const { return IsHiGainSaturation() ? GetLoGainNumPickup()   : GetHiGainNumPickup();   }
+  Float_t GetNumBlackout() const { return IsHiGainSaturation() ? GetLoGainNumBlackout() : GetHiGainNumBlackout(); }
+  Int_t   GetPixId      () const { return fPixId ;  }
+  
+  Bool_t  IsHiGainSaturation() const;
+  Bool_t  IsDebug   ()         const;
+  Bool_t  IsExcluded()         const;
+  Bool_t  IsValid   ()         const;
+
+  ClassDef(MCalibrationPix, 2)	// Base Container for Calibration Results Pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationPulseTimeCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPulseTimeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPulseTimeCam.cc	(revision 9772)
@@ -0,0 +1,259 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationPulseTimeCam                                               
+//                                                               
+// Storage container for relative arrival time calibration results         
+// of the whole camera.
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationPix &avpix = (MCalibrationPix&)(*fPulseCam)[i]
+// 
+// The following "calibration" constants can be retrieved from each pixel:
+// - GetTimeOffset(): The mean offset in relative times, 
+//   has to be added to any calculated relative time in the camera. 
+// - GetTimePrecision(): The Gauss sigma of histogrammed relative arrival 
+//   times for the calibration run. Gives an estimate about the timing 
+//   resolution.
+//
+// ALL RELATIVE TIMES HAVE TO BE CALCULATED W.R.T. PIXEL IDX 1 
+// (HARDWARE NUMBER: 2) !!
+//
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationPix &avpix = (MCalibrationPix&)fPulseCam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationPix &avpix = (MCalibrationPix&)fPulseCam->GetAverageSector(i)
+//
+// Note the averageing has been done on an event-by-event basis. Resulting 
+// Sigma's of the Gauss fit have been multiplied with the square root of the number 
+// of involved pixels in order to make a direct comparison possible with the mean of 
+// sigmas. 
+//
+// See also: MHCalibrationPix, MHCalibrationPulseTimeCam              
+//                                                                         
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Mean Time Offset
+// 1: Error of Mean Time Offset
+// 2: Sigma of Time Offset == Time Resolution 
+// 3: Error of Sigma of Time Offset
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Pulse. Arrival Time distribution
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationPulseTimeCam.h"
+#include "MCalibrationCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationPix.h"
+
+ClassImp(MCalibrationPulseTimeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationPulseTimeCam::MCalibrationPulseTimeCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationPulseTimeCam";
+  fTitle = title ? title : "Container for Pulse Time Information";
+  
+}
+
+void MCalibrationPulseTimeCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationPix,i);
+}
+
+
+void MCalibrationPulseTimeCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationPix,i);
+}
+
+void MCalibrationPulseTimeCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationPix,i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not Valid
+//
+void MCalibrationPulseTimeCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << "Calibrated pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationPix *pix;
+  while ((pix=(MCalibrationPix*)Next()))
+    {
+      
+      if (!pix->IsExcluded()) 
+	{                            
+
+          *fLog << all 
+                << Form("Pix  %4i:  Mean Time: %4.2f+-%4.2f Time Jitter: %4.2f+-%4.2f",pix->GetPixId(),
+                        pix->GetMean(),pix->GetMeanErr(),pix->GetSigma(),pix->GetSigmaErr())
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+  
+   
+  *fLog << all << endl;
+  *fLog << all << "Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationPix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+	  *fLog << all << pix->GetPixId() << endl;
+	  id++;
+      }
+  }
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationPix*)Next5()))
+  {
+    *fLog << all 
+	  << Form("Pix  %4i:  Mean Time: %4.2f+-%4.2f Time Jitter: %4.2f+-%4.2f",pix->GetPixId(),
+		  pix->GetMean(),pix->GetMeanErr(),pix->GetSigma(),pix->GetSigmaErr())
+          << endl;
+  }
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationPix*)Next5()))
+  {
+    *fLog << all 
+	  << Form("Pix  %4i:  Mean Time: %4.2f+-%4.2f Time Jitter: %4.2f+-%4.2f",pix->GetPixId(),
+		  pix->GetMean(),pix->GetMeanErr(),pix->GetSigma(),pix->GetSigmaErr())
+          << endl;
+  }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted PulseTime
+// 1: Error of fitted PulseTime
+// 2: Sigma of fitted PulseTime
+// 3: Error of Sigma of fitted PulseTime
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to PulseTime distribution
+//
+Bool_t MCalibrationPulseTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ MCalibrationPix &pix = (MCalibrationPix&)(*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainMean();
+      break;
+    case 1:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainMeanErr();
+      break;
+    case 2:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainSigma();
+      break;
+    case 3:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetHiGainSigmaErr();
+      break;
+    case 4:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetProb();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationPulseTimeCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationPulseTimeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationPulseTimeCam.h	(revision 9772)
@@ -0,0 +1,29 @@
+#ifndef MARS_MCalibrationPulseTimeCam
+#define MARS_MCalibrationPulseTimeCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationPulseTimeCam : public MCalibrationCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+
+public:
+
+  MCalibrationPulseTimeCam(const char *name=NULL, const char *title=NULL);
+
+  // Prints
+  void Print(Option_t *o="") const;
+  
+  // Others
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+
+  ClassDef(MCalibrationPulseTimeCam, 2)	// Container Pulse Time Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationQECam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationQECam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationQECam.cc	(revision 9772)
@@ -0,0 +1,925 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationQECam                                               
+//                                                               
+// Storage container for the calibrated Quantum Efficiency of the whole camera.
+//
+// For a complete description of the quantum efficiency calibration process, 
+// see MCalibrationQEPix.
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationQEPix &avpix = (MCalibrationQEPix&)(*fQECam)[i]
+// 
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationQEPix &avpix = (MCalibrationQEPix&)fQECam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationQEPix &avpix = (MCalibrationQEPix&)fQECam->GetAverageSector(i)
+//
+// The following "calibration" constants are used for the calibration of each pixel:
+//
+// - MCalibrationQEPix::GetQECascadesBlindPixel(): The mean quantum efficiency folded 
+//   into a cascades spectrum obtained with the Blind Pixel Method. 
+// - MCalibrationQEPix::GetQECascadesFFactor(): The mean quantum efficiency folded 
+//   into a cascades spectrum obtained with the F-Factor Method
+// - MCalibrationQEPix::GetQECascadesPINDiode(): The mean quantum efficiency folded 
+//   into a cascades spectrum obtained with the PIN Diode Method
+// - MCalibrationQEPix::GetQECascadesCombined(): The mean quantum efficiency folded 
+//   into a cascades spectrum obtained with the combination of the three methods
+//
+// The following "calibration" constants have been measured to obtain the above values:
+//
+// - MCalibrationQEPix::GetQEBlindPixel( MCalibrationCam::PulserColor_t color ): 
+//   The mean quantum efficiency obtained with the calibration pulser color 
+//   (e.g. kGREEN, kBLUE, kUV, kCT1) after the Blind Pixel Method
+// - MCalibrationQEPix::GetQEFFactor( MCalibrationCam::PulserColor_t color ): 
+//   The mean quantum efficiency obtained with the calibration pulser color
+//   (e.g. kGREEN, kBLUE, kUV, kCT1) after the F-Factor Method
+// - MCalibrationQEPix::GetQEPINDiode( MCalibrationCam::PulserColor_t color ): 
+//   The mean quantum efficiency obtained with the calibration pulser color 
+//   (e.g. kGREEN, kBLUE, kUV, kCT1) after the PIN Diode Method
+// - MCalibrationQEPix::GetQECombined( MCalibrationCam::PulserColor_t color ): 
+//   The mean quantum efficiency obtained with the calibration pulser color 
+//   (e.g. kGREEN, kBLUE, kUV, kCT1) after the combination of the three methods
+//
+// See also: MCalibrationQEPix, MCalibrationChargeCam, MCalibrationChargeCalc
+//           MCalibrationChargeBlindPix, MCalibrationChargePINDiode, MCalibrationChargePix
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+#include <TOrdCollection.h>
+#include <TGraphErrors.h>
+#include <TH2D.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationQECam);
+
+using namespace std;
+
+const Float_t MCalibrationQECam::gkPlexiglassQE    = 0.92;
+const Float_t MCalibrationQECam::gkPlexiglassQEErr = 0.01;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationQECam::MCalibrationQECam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCalibrationQECam";
+    fTitle = title ? title : "Storage container for the calibrated Quantum Efficiency of the camera";
+
+    fFlags.Set(MCalibrationCam::gkNumPulserColors);
+
+    Clear();
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationQEPix's in the ranges from - to to fPixels
+//
+void MCalibrationQECam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationQEPix,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationQEPix's in the ranges from - to to fAverageAreas
+//
+void MCalibrationQECam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationQEPix,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationQEPix's in the ranges from - to to fAverageSectors
+//
+void MCalibrationQECam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationQEPix,i);
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets all bits to kFALSE
+// 
+// Calls:
+// - MCalibrationCam::Clear()
+//
+void MCalibrationQECam::Clear(Option_t *o)
+{
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kGREEN);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kGREEN);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kGREEN);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kGREEN);
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kBLUE);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kBLUE);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kBLUE);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kBLUE);
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kUV);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kUV);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kUV);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kUV);
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kCT1);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kCT1);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kCT1);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kCT1);
+
+  MCalibrationCam::Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MCalibrationQECam::Copy(TObject& object) const
+{
+  
+  MCalibrationQECam &qecam = (MCalibrationQECam&)object;
+  
+  MCalibrationCam::Copy(qecam);
+  
+  qecam.fFlags        = fFlags;
+  qecam.fCorningBlues = fCorningBlues;
+  qecam.fCorningReds  = fCorningReds;
+  
+}
+
+// --------------------------------------------------------------------
+//
+// Types used by MCalibrate and MCalibrateData: 
+// ============================================
+//
+// 0: Mean Quantum Efficiency for cascades, obtained with the F-Factor method
+// 1: Error of the Mean QE for cascades, obtained with the F-Factor method
+// 2: Mean Quantum Efficiency for cascades, obtained with the Blind Pixel method
+// 3: Error of the Mean QE for cascades, obtained with the Blind Pixel method
+// 4: Mean Quantum Efficiency for cascades, obtained with the PIN Diode method
+// 5: Error of the Mean QE for cascades, obtained with the PIN Diode method
+// 6: Mean Quantum Efficiency for cascades, obtained with combination of the 3 methods
+// 7: Error of the Mean QE for cascades, obtained with combination of the 3 methods
+// 8: Availabiliy of Quantum Efficiency for cascades, F-Factor method
+// 9: Availabiliy of Quantum Efficiency for cascades, F-Factor method
+// 10: Availabiliy of Quantum Efficiency for cascades, F-Factor method
+// 11: Availabiliy of Quantum Efficiency for cascades, F-Factor method
+//
+// Types filled by MCalibrationChargeCalc in combination of MCalibrationChargePix:
+// ===============================================================================
+//
+// 12: Mean Quantum Efficiency obtained with F-Factor Method ( color: kCT1)
+// 13: Error of the Mean QE obtained with F-Factor Method ( color: kCT1)
+// 14: Mean Quantum Efficiency obtained with F-Factor Method ( color: kGREEN)
+// 15: Error of the Mean QE obtained with F-Factor Method ( color: kGREEN)
+// 16: Mean Quantum Efficiency obtained with F-Factor Method ( color: kBLUE)
+// 17: Error of the Mean QE obtained with F-Factor Method ( color: kBLUE)
+// 18: Mean Quantum Efficiency obtained with F-Factor Method ( color: kUV)
+// 19: Error of the Mean QE obtained with F-Factor Method ( color: kUV)
+//
+// Types filled by MCalibrationChargeCalc in combination of MCalibrationChargeBlindPix:
+// ====================================================================================
+//
+// 20: Mean Quantum Efficiency obtained with Blind Pixel Method ( color: kCT1)
+// 21: Error of the Mean QE obtained with Blind Pixel Method ( color: kCT1)
+// 22: Mean Quantum Efficiency obtained with Blind Pixel Method ( color: kGREEN)
+// 23: Error of the Mean QE obtained with Blind Pixel Method ( color: kGREEN)
+// 24: Mean Quantum Efficiency obtained with Blind Pixel Method ( color: kBLUE)
+// 25: Error of the Mean QE obtained with Blind Pixel Method ( color: kBLUE)
+// 26: Mean Quantum Efficiency obtained with Blind Pixel Method ( color: kUV)
+// 27: Error of the Mean QE obtained with Blind Pixel Method ( color: kUV)
+//
+// Types filled by MCalibrationChargeCalc in combination of MCalibrationChargePINDiode:
+// ====================================================================================
+//
+// 28: Mean Quantum Efficiency obtained with PIN Diode Method ( color: kCT1)
+// 29: Error of the Mean QE obtained with PIN Diode Method ( color: kCT1)
+// 30: Mean Quantum Efficiency obtained with PIN Diode Method ( color: kGREEN)
+// 31: Error of the Mean QE obtained with PIN Diode Method ( color: kGREEN)
+// 32: Mean Quantum Efficiency obtained with PIN Diode Method ( color: kBLUE)
+// 33: Error of the Mean QE obtained with PIN Diode Method ( color: kBLUE)
+// 34: Mean Quantum Efficiency obtained with PIN Diode Method ( color: kUV)
+// 35: Error of the Mean QE obtained with PIN Diode Method ( color: kUV)
+//
+// Types filled by MCalibrationChargeCalc in combination of MCalibrationQEPix:
+// ===========================================================================
+//
+// 36: Mean Quantum Efficiency obtained with combination of 3 methods ( color: kCT1)
+// 37: Error of the Mean QE obtained with combination of 3 methods ( color: kCT1)
+// 38: Mean Quantum Efficiency obtained with combination of 3 methods ( color: kGREEN)
+// 39: Error of the Mean QE obtained with combination of 3 methods ( color: kGREEN)
+// 40: Mean Quantum Efficiency obtained with combination of 3 methods ( color: kBLUE)
+// 41: Error of the Mean QE obtained with combination of 3 methods ( color: kBLUE)
+// 42: Mean Quantum Efficiency obtained with combination of 3 methods ( color: kUV)
+// 43: Error of the Mean QE obtained with combination of 3 methods ( color: kUV)
+//
+Bool_t MCalibrationQECam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[idx];
+
+  if (pix.IsExcluded())
+    return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      if (!pix.IsAverageQEFFactorAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesFFactor();
+      break;
+    case 1:
+      if (!pix.IsAverageQEFFactorAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesFFactorErr();
+      break;
+    case 2:
+      if (!pix.IsAverageQEBlindPixelAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesBlindPixel();
+      break;
+    case 3:
+      if (!pix.IsAverageQEBlindPixelAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesBlindPixelErr();
+      break;
+    case 4:
+      if (!pix.IsAverageQEPINDiodeAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesPINDiode();
+      break;
+    case 5:
+      if (!pix.IsAverageQEPINDiodeAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesPINDiodeErr();
+      break;
+    case 6:
+      if (!pix.IsAverageQECombinedAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesCombined();
+      break;
+    case 7:
+      if (!pix.IsAverageQECombinedAvailable())
+        return kFALSE;
+      val = pix.GetQECascadesCombinedErr();
+      break;
+    case 8:
+      if (pix.IsAverageQEFFactorAvailable())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 9:
+      if (pix.IsAverageQEBlindPixelAvailable())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 10:
+      if (pix.IsAverageQEPINDiodeAvailable())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 11:
+      if (pix.IsAverageQECombinedAvailable())
+        val = 1;
+      else
+        return kFALSE;
+      break;
+    case 12:
+      val = pix.GetQEFFactor(kCT1);
+      break;
+    case 13:
+      val = pix.GetQEFFactorErr(kCT1);
+      break;
+    case 14:
+      val = pix.GetQEFFactor(kGREEN);
+      break;
+    case 15:
+      val = pix.GetQEFFactorErr(kGREEN);
+      break;
+    case 16:
+      val = pix.GetQEFFactor(kBLUE);
+      break;
+    case 17:
+      val = pix.GetQEFFactorErr(kBLUE);
+      break;
+    case 18:
+      val = pix.GetQEFFactor(kUV);
+      break;
+    case 19:
+      val = pix.GetQEFFactorErr(kUV);
+      break;
+    case 20:
+      val = pix.GetQEBlindPixel(kCT1);
+      break;
+    case 21:
+      val = pix.GetQEBlindPixelErr(kCT1);
+      break;
+    case 22:
+      val = pix.GetQEBlindPixel(kGREEN);
+      break;
+    case 23:
+      val = pix.GetQEBlindPixelErr(kGREEN);
+      break;
+    case 24:
+      val = pix.GetQEBlindPixel(kBLUE);
+      break;
+    case 25:
+      val = pix.GetQEBlindPixelErr(kBLUE);
+      break;
+    case 26:
+      val = pix.GetQEBlindPixel(kUV);
+      break;
+    case 27:
+      val = pix.GetQEBlindPixelErr(kUV);
+      break;
+    case 28:
+      val = pix.GetQEPINDiode(kCT1);
+      break;
+    case 29:
+      val = pix.GetQEPINDiodeErr(kCT1);
+      break;
+    case 30:
+      val = pix.GetQEPINDiode(kGREEN);
+      break;
+    case 31:
+      val = pix.GetQEPINDiodeErr(kGREEN);
+      break;
+    case 32:
+      val = pix.GetQEPINDiode(kBLUE);
+      break;
+    case 33:
+      val = pix.GetQEPINDiodeErr(kBLUE);
+      break;
+    case 34:
+      val = pix.GetQEPINDiode(kUV);
+      break;
+    case 35:
+      val = pix.GetQEPINDiodeErr(kUV);
+      break;
+    case 36:
+      val = pix.GetQECombined(kCT1);
+      break;
+    case 37:
+      val = pix.GetQECombinedErr(kCT1);
+      break;
+    case 38:
+      val = pix.GetQECombined(kGREEN);
+      break;
+    case 39:
+      val = pix.GetQECombinedErr(kGREEN);
+      break;
+    case 40:
+      val = pix.GetQECombined(kBLUE);
+      break;
+    case 41:
+      val = pix.GetQECombinedErr(kBLUE);
+      break;
+    case 42:
+      val = pix.GetQECombined(kUV);
+      break;
+    case 43:
+      val = pix.GetQECombinedErr(kUV);
+      break;
+    default:
+      return kFALSE;
+    }
+  return val!=-1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkPlexiglassQEErr is smaller than 0.
+// Return -1 if gkPlexiglassQE    is 0.
+// Return gkPlexiglassQEErr^2 / gkPlexiglassQE^2
+// 
+Float_t MCalibrationQECam::GetPlexiglassQERelVar() const
+{
+  if (gkPlexiglassQEErr < 0.)
+    return -1.;
+  
+  if (gkPlexiglassQE  == 0.)
+    return -1.;
+  
+  return gkPlexiglassQEErr * gkPlexiglassQEErr / gkPlexiglassQE / gkPlexiglassQE ;
+}
+
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the four colours have the bit kBlindPixelMethodValid set,
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsBlindPixelMethodValid () const  
+{
+  if (IsBlindPixelMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the four colours have the bit kCombinedMethodValid set,
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsCombinedMethodValid () const
+{
+  if (IsCombinedMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the four colours have the bit kFFactorMethodValid set,
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsFFactorMethodValid () const
+{
+  if (IsFFactorMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the four colours have the bit kPINDiodeMethodValid set,
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsPINDiodeMethodValid () const
+{
+  if (IsPINDiodeMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the bit kBlindPixelMethodValid is set for colour "col"
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsBlindPixelMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fFlags[ MCalibrationCam::kGREEN ],kBlindPixelMethodValid);
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the bit kCombinedMethodValid is set for colour "col"
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsCombinedMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fFlags[ MCalibrationCam::kGREEN ],kCombinedMethodValid);
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the bit kFFactorMethodValid is set for colour "col"
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsFFactorMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fFlags[ MCalibrationCam::kGREEN ],kFFactorMethodValid);
+}
+
+// --------------------------------------------------------------------------------
+//
+// Returns kTRUE if ANY of the bit kPINDiodeMethodValid is set for colour "col"
+// otherwise kFALSE
+// 
+Bool_t MCalibrationQECam::IsPINDiodeMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fFlags[ MCalibrationCam::kGREEN ],kPINDiodeMethodValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the 
+// - MCalibrationQEPix::GetQECascadesFFactor() 
+// - MCalibrationQEPix::GetQECascadesBlindPixel() 
+// - MCalibrationQEPix::GetQECascadesPINDiode() 
+// - MCalibrationQEPix::GetQECascadesCombined()
+// for all pixels 
+//
+void MCalibrationQECam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << endl;
+  *fLog << all << "Quantum Efficiencies averaged over cascades spectra, measured with F-Factor method:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationQEPix *pix;
+  while ((pix=(MCalibrationQEPix*)Next()))
+    {
+      
+      if (!pix->IsExcluded() && pix->IsAverageQEFFactorAvailable()) 
+	{
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":  QE: ",pix->GetQECascadesFFactor()," +- ",pix->GetQECascadesFFactorErr())
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " succesful pixels :-))" << endl;
+  id = 0;
+  
+  *fLog << all << endl;
+  *fLog << all << "Quantum Efficiencies averaged over cascades spectra, " 
+        << "measured with Blind Pixel method:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next2(fPixels);
+    while ((pix=(MCalibrationQEPix*)Next2()))
+      {
+        
+      if (!pix->IsExcluded() && pix->IsAverageQEBlindPixelAvailable()) 
+	{
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":  QE: ",pix->GetQECascadesBlindPixel()," +- ",pix->GetQECascadesBlindPixelErr())
+		<< endl;
+          id++;
+	}
+      }
+
+  *fLog << all << id << " succesful pixels :-))" << endl;
+  id = 0;
+  
+  *fLog << all << endl;
+  *fLog << all << "Quantum Efficiencies averaged over cascades spectra, " 
+        << "measured with PIN Diode method:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next3(fPixels);
+    while ((pix=(MCalibrationQEPix*)Next3()))
+      {
+        
+      if (!pix->IsExcluded() && pix->IsAverageQEPINDiodeAvailable()) 
+	{
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":  QE: ",pix->GetQECascadesPINDiode()," +- ",pix->GetQECascadesPINDiodeErr())
+		<< endl;
+          id++;
+	}
+      }
+
+  *fLog << all << id << " succesful pixels :-))" << endl;
+  id = 0;
+
+    
+  *fLog << all << endl;
+  *fLog << all << "Quantum Efficiencies averaged over cascades spectra, " 
+        << "measured with combination of the 3 methods:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next4(fPixels);
+    while ((pix=(MCalibrationQEPix*)Next4()))
+      {
+        
+      if (!pix->IsExcluded() && pix->IsAverageQECombinedAvailable()) 
+	{
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":  QE: ",pix->GetQECascadesCombined()," +- ",pix->GetQECascadesCombinedErr())
+		<< endl;
+          id++;
+	}
+      }
+
+  *fLog << all << id << " succesful pixels :-))" << endl;
+  id = 0;
+
+  *fLog << all << endl;
+  *fLog << all << "Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  TIter Next5(fPixels);
+  while ((pix=(MCalibrationQEPix*)Next5()))
+  {
+      if (pix->IsExcluded())
+      {
+	  *fLog << all << pix->GetPixId() << endl;
+	  id++;
+      }
+  }
+  *fLog << all << id << " Excluded pixels " << endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the Blind Pixel Method, 
+// for all colours (kGREEN, kBLUE, kUV, kCT1)
+// 
+void MCalibrationQECam::SetBlindPixelMethodValid ( const Bool_t b ) 
+{
+  SetBlindPixelMethodValid ( b, MCalibrationCam::kGREEN);
+  SetBlindPixelMethodValid ( b, MCalibrationCam::kBLUE );
+  SetBlindPixelMethodValid ( b, MCalibrationCam::kUV   );
+  SetBlindPixelMethodValid ( b, MCalibrationCam::kCT1  );
+}
+
+// ----------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the combination of the 3 methods
+// for all colours (kGREEN, kBLUE, kUV, kCT1)
+// 
+void MCalibrationQECam::SetCombinedMethodValid ( const Bool_t b ) 
+{
+  SetCombinedMethodValid ( b, MCalibrationCam::kGREEN);
+  SetCombinedMethodValid ( b, MCalibrationCam::kBLUE );
+  SetCombinedMethodValid ( b, MCalibrationCam::kUV   );
+  SetCombinedMethodValid ( b, MCalibrationCam::kCT1  );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the F-Factor Method
+// for all colours (kGREEN, kBLUE, kUV, kCT1)
+// 
+void MCalibrationQECam::SetFFactorMethodValid ( const Bool_t b ) 
+{
+  SetFFactorMethodValid ( b, MCalibrationCam::kGREEN);
+  SetFFactorMethodValid ( b, MCalibrationCam::kBLUE );
+  SetFFactorMethodValid ( b, MCalibrationCam::kUV   );
+  SetFFactorMethodValid ( b, MCalibrationCam::kCT1  );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the PIN Diode Method, 
+// for all colours (kGREEN, kBLUE, kUV, kCT1)
+// 
+void MCalibrationQECam::SetPINDiodeMethodValid ( const Bool_t b ) 
+{
+  SetPINDiodeMethodValid ( b, MCalibrationCam::kGREEN);
+  SetPINDiodeMethodValid ( b, MCalibrationCam::kBLUE );
+  SetPINDiodeMethodValid ( b, MCalibrationCam::kUV   );
+  SetPINDiodeMethodValid ( b, MCalibrationCam::kCT1  );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the Blind Pixel Method, 
+// for colour "col"
+// 
+void MCalibrationQECam::SetBlindPixelMethodValid ( const Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fFlags[ MCalibrationCam::kGREEN ],kBlindPixelMethodValid);
+  else
+    CLRBIT(fFlags[ MCalibrationCam::kGREEN ],kBlindPixelMethodValid);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the combination of 3 methods
+// for colour "col"
+// 
+void MCalibrationQECam::SetCombinedMethodValid ( const Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fFlags[ MCalibrationCam::kGREEN ],kCombinedMethodValid);
+  else
+    CLRBIT(fFlags[ MCalibrationCam::kGREEN ],kCombinedMethodValid);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the F-Factor Method, 
+// for colour "col"
+// 
+void MCalibrationQECam::SetFFactorMethodValid ( const Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fFlags[ MCalibrationCam::kGREEN ],kFFactorMethodValid);
+  else
+    CLRBIT(fFlags[ MCalibrationCam::kGREEN ],kFFactorMethodValid);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the validity flag (according to b) for the PIN Diode Method, 
+// for colour "col"
+// 
+void MCalibrationQECam::SetPINDiodeMethodValid ( const Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fFlags[ MCalibrationCam::kGREEN ],kPINDiodeMethodValid);
+  else
+    CLRBIT(fFlags[ MCalibrationCam::kGREEN ],kPINDiodeMethodValid);    
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns a TGraphErrors correlating the corning blues with the 
+// calcualted quantum efficiency of each pixel, obtained with the F-Factor 
+// method.
+// 
+TGraphErrors *MCalibrationQECam::GetGraphQEvsCorningBlues() const
+{
+
+  const UInt_t size = GetSize();
+
+  if (fCorningBlues.GetSize() == 0)
+    {
+      *fLog << warn << "Size of intialized Cornings Blue is zero, please use MCalibrationQECamMagic" << endl;
+      return NULL;
+    }
+  
+  if (fCorningBlues.GetSize() != size)
+    *fLog << warn << "Sizes mismatch, cannot create Graph!! " << endl;
+
+  TArrayD qes(size);
+  TArrayD qeerrs(size);
+  TArrayD corns(size);
+  TArrayD cornerrs(size);
+  
+  Int_t cnt = 0;
+  
+  for (UInt_t i=0; i<size; i++)
+    {
+      MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[i];
+      if (pix.IsFFactorMethodValid() && fCorningBlues[i] > 0. && pix.GetQECascadesFFactorErr() > 0.)
+        {
+          qes   [i] = pix.GetQECascadesFFactor();
+          qeerrs[i] = pix.GetQECascadesFFactorErr();
+          corns [i] = fCorningBlues[i];
+          cornerrs[i] = 0.05;
+          cnt++;
+        }
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(cnt,
+                                     corns.GetArray(),qes.GetArray(),
+                                      cornerrs.GetArray(),qeerrs.GetArray());
+  return gr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns a TGraphErrors correlating the corning reds with the 
+// calcualted quantum efficiency of each pixel, obtained with the F-Factor 
+// method.
+// 
+TGraphErrors *MCalibrationQECam::GetGraphQEvsCorningReds() const
+{
+
+  const UInt_t size = GetSize();
+
+  if (fCorningReds.GetSize() == 0)
+    {
+      *fLog << warn << "Size of intialized Cornings Red is zero, please use MCalibrationQECamMagic" << endl;
+      return NULL;
+    }
+  
+  if (fCorningReds.GetSize() != size)
+    *fLog << warn << "Sizes mismatch, cannot create Graph!! " << endl;
+
+  TArrayD qes(size);
+  TArrayD qeerrs(size);
+  TArrayD corns(size);
+  TArrayD cornerrs(size);
+
+  Int_t cnt = 0;
+
+  for (UInt_t i=0; i<size; i++)
+    {
+      MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[i];
+      if (pix.IsFFactorMethodValid() && fCorningReds[i] > 0. && pix.GetQECascadesFFactorErr() > 0.)
+        {
+          qes     [i] = pix.GetQECascadesFFactor();
+          qeerrs  [i] = pix.GetQECascadesFFactorErr();
+          corns   [i] = fCorningReds[i];
+          cornerrs[i] = 0.05;
+          cnt++;
+        }
+      
+    }
+  
+  TGraphErrors *gr = new TGraphErrors(cnt,
+                                      corns.GetArray(),qes.GetArray(),
+                                      cornerrs.GetArray(),qeerrs.GetArray());
+  
+  return gr;
+}
+
+TH2D *MCalibrationQECam::GetHistQEvsCorningBlues( const Int_t nbins, const Axis_t first, const Axis_t last ) const
+{
+
+  const UInt_t size = GetSize();
+
+  if (fCorningBlues.GetSize() == 0)
+    return NULL;
+  
+  if (fCorningBlues.GetSize() != size)
+    *fLog << warn << "Sizes mismatch, cannot create Graph!! " << endl;
+
+  TH2D *h = new TH2D("hist","QE vs. Corning Blue",nbins,first,last,nbins,0.,0.35);
+  
+  for (UInt_t i=0; i<size; i++)
+    {
+      MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[i];
+      if (pix.IsFFactorMethodValid() && fCorningBlues[i] > 0.)
+        h->Fill(fCorningBlues[i],pix.GetQECascadesFFactor());
+    }
+  
+  return h;
+}
+
+TH2D *MCalibrationQECam::GetHistQEvsCorningReds( const Int_t nbins, const Axis_t first, const Axis_t last ) const
+{
+
+  const UInt_t size = GetSize();
+
+  if (fCorningReds.GetSize() == 0)
+    return NULL;
+  
+  if (fCorningReds.GetSize() != size)
+    *fLog << warn << "Sizes mismatch, cannot create Graph!! " << endl;
+
+  TH2D *h = new TH2D("hist","QE vs. Corning Red",nbins,first,last,nbins,0.,0.35);
+
+  for (UInt_t i=0; i<size; i++)
+    {
+      MCalibrationQEPix &pix = (MCalibrationQEPix&)(*this)[i];
+      if (pix.IsFFactorMethodValid() && fCorningReds[i] > 0.)
+        h->Fill(fCorningReds[i],pix.GetQECascadesFFactor());
+    }
+  
+  return h;
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationQECam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationQECam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationQECam.h	(revision 9772)
@@ -0,0 +1,88 @@
+#ifndef MARS_MCalibrationQECam
+#define MARS_MCalibrationQECam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TGraphErrors;
+class TH2D;
+class MCalibrationQECam : public MCalibrationCam
+{
+private:
+
+  static const Float_t gkPlexiglassQE   ;  //! Quantum Efficiency Plexiglass (now set to: 0.96)
+  static const Float_t gkPlexiglassQEErr;  //! Uncertainty QE Plexiglass     (now set to: 0.01)
+
+  TArrayC fFlags;                          //  Contains validity bits 
+
+  enum { kBlindPixelMethodValid, kFFactorMethodValid,
+         kPINDiodeMethodValid, kCombinedMethodValid }; // Possible validity bits
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+
+  
+protected:
+
+  MArrayD fCorningBlues;                   // Corning blues of the pixels (if available) 
+  MArrayD fCorningReds;                    // Corning reds  of the pixels (if available) 
+
+public:
+
+  MCalibrationQECam(const char *name=NULL, const char *title=NULL);
+
+  void Clear( Option_t *o=""  );
+  void Copy ( TObject& object ) const;
+
+  TGraphErrors *GetGraphQEvsCorningBlues() const;
+  TGraphErrors *GetGraphQEvsCorningReds() const;  
+  
+  TH2D *GetHistQEvsCorningBlues( const Int_t nbins=50, const Axis_t first=6., const Axis_t last=17.) const;
+  TH2D *GetHistQEvsCorningReds( const Int_t nbins=50, const Axis_t first=0., const Axis_t last=25.) const;  
+  
+  // Others
+  Bool_t  GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0 ) const;
+
+  Float_t GetPlexiglassQE          () const { return gkPlexiglassQE; }
+  Float_t GetPlexiglassQERelVar    () const; 
+
+  const MArrayD &GetCorningBlues   () const { return fCorningBlues;  }
+  const MArrayD &GetCorningReds    () const { return fCorningReds;   }
+  
+  Bool_t  IsBlindPixelMethodValid  () const;
+  Bool_t  IsFFactorMethodValid     () const;  
+  Bool_t  IsCombinedMethodValid    () const;  
+  Bool_t  IsPINDiodeMethodValid    () const;  
+          
+  Bool_t  IsBlindPixelMethodValid  ( MCalibrationCam::PulserColor_t col ) const;
+  Bool_t  IsFFactorMethodValid     ( MCalibrationCam::PulserColor_t col ) const;  
+  Bool_t  IsCombinedMethodValid    ( MCalibrationCam::PulserColor_t col ) const;  
+  Bool_t  IsPINDiodeMethodValid    ( MCalibrationCam::PulserColor_t col ) const;  
+
+  // Prints
+  void    Print(Option_t *o="")       const;
+  
+  // Setters (without color only for MC!)
+  void    SetBlindPixelMethodValid ( const Bool_t  b=kTRUE );
+  void    SetBlindPixelMethodValid ( const Bool_t  b, MCalibrationCam::PulserColor_t col);
+  void    SetCombinedMethodValid   ( const Bool_t  b=kTRUE );
+  void    SetCombinedMethodValid   ( const Bool_t  b, MCalibrationCam::PulserColor_t col);
+  void    SetFFactorMethodValid    ( const Bool_t  b=kTRUE );  
+  void    SetFFactorMethodValid    ( const Bool_t  b, MCalibrationCam::PulserColor_t col);  
+  void    SetPINDiodeMethodValid   ( const Bool_t  b=kTRUE );  
+  void    SetPINDiodeMethodValid   ( const Bool_t  b, MCalibrationCam::PulserColor_t col);  
+
+  ClassDef(MCalibrationQECam, 2) // Container Quantum Efficieny Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationQECamMagic.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationQECamMagic.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationQECamMagic.cc	(revision 9772)
@@ -0,0 +1,1247 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationQECamMagic                                               
+//                                                               
+// Storage container for the calibrated Quantum Efficiency of the whole camera
+// with Corning Blue and Corning Red values initialized for the MAGIC camera.
+// The values are valid for the camera after July 5, 2004.
+//
+// The following plots display the distributions of the cornings: 
+// * The corning blue w.r.t. the pixel index:
+//   One can see the selection of pixels such that the highest corning blue values 
+//   are located towards the center of the camera.
+// * The corning red w.r.t. the pixel index:
+//   One can see that there is a population in the outmost ring of inner pixels
+//   with much lower corning reds. This characteristic is also valid for the 
+//   quantum efficiency in the green. 
+// * The corning blue vs. the corning red for the inner and outer pixels,
+//   respectively. The two populations are clearly visible for the inner pixels, 
+//   while for the outer ones, there is only one population with a bigger spread.
+//   The blue line marks the distinction of the two populations as used in 
+//   MCalibrationChargeCalc.
+//
+//Begin_Html
+/*
+<img src="images/Cornings.gif">
+*/
+//End_Html
+//
+// See also: MCalibrationQECam, MCalibrationQEPix, MCalibrationChargeCalc
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationQECamMagic.h"
+#include "MCalibrationQECam.h"
+
+ClassImp(MCalibrationQECamMagic);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationQECamMagic::MCalibrationQECamMagic(const char *name, const char *title)
+    : MCalibrationQECam(name,title)
+{
+  
+  CreateCorningReds();
+  CreateCorningBlues();
+
+}
+
+void MCalibrationQECamMagic::CreateCorningReds()
+{
+  
+  Double_t creds[577];
+
+  creds[0]   = -1.;
+  creds[1]   = 1.6;
+  creds[2]   = 8.7;
+  creds[3]   = 6.8;
+  creds[4]   = 10.3;
+  creds[5]   = 8.7;
+  creds[6]   = -1.;
+  creds[7]   = 1.3;
+  creds[8]   = 0.4;
+  creds[9]   = 7.7 ;
+  creds[10]  = 9.8;
+  creds[11]  = 5.9;
+  creds[12]  = 7.4;
+  creds[13]  = 7.4;
+  creds[14]  = 7.0;
+  creds[15]  = 7.2;
+  creds[16]  = 6.8;
+  creds[17]  = 6.9;
+  creds[18]  = 6.6;
+  creds[19]  = 1.8;
+  creds[20]  = 4.9;
+  creds[21]  = 7.1;
+  creds[22]  = 7.7;
+  creds[23]  = 8.9;
+  creds[24]  = 11.9;
+  creds[25]  = 1.6;
+  creds[26]  = 9.3;
+  creds[27]  = 5.8;
+  creds[28]  = 9.0;
+  creds[29]  = 6.5;
+  creds[30]  = 6.1;
+  creds[31]  = 8.1;
+  creds[32]  = 6.7;
+  creds[33]  = 7.0;
+  creds[34]  = 7.1;
+  creds[35]  = 7.8;
+  creds[36]  = 6.9;
+  creds[37]  = 0.9;
+  creds[38]  = 3.3;
+  creds[39]  = 7.1;
+  creds[40]  = 5.8;
+  creds[41]  = 4.4;
+  creds[42]  = 8.1;
+  creds[43]  = 6.0;
+  creds[44]  = 6.3;
+  creds[45]  = 6.0;
+  creds[46]  = 8.0;
+  creds[47]  = 0.6;
+  creds[48]  = 7.2;
+  creds[49]  = 5.6;
+  creds[50]  = 7.3;
+  creds[51]  = 8.0;
+  creds[52]  = 9.1;
+  creds[53]  = 1.4;
+  creds[54]  = 6.9;
+  creds[55]  = 9.1;
+  creds[56]  = 6.4;
+  creds[57]  = 6.1;
+  creds[58]  = 6.2;
+  creds[59]  = 7.7;
+  creds[60]  = 5.1;
+  creds[61]  = 7.9;
+  creds[62]  = 6.9;
+  creds[63]  = 3.3;
+  creds[64]  = 3.7;
+  creds[65]  = 5.8;
+  creds[66]  = 8.0;
+  creds[67]  = 7.3;
+  creds[68]  = 7.3;
+  creds[69]  = 9.1;
+  creds[70]  = 4.0;
+  creds[71]  = 8.2;
+  creds[72]  = 8.7;
+  creds[73]  = 9.1;
+  creds[74]  = 8.2;
+  creds[75]  = 9.0;
+  creds[76]  = 7.8;
+  creds[77]  = 7.5;
+  creds[78]  = 1.3;
+  creds[79]  = 6.9;
+  creds[80]  = 8.7;
+  creds[81]  = 7.6;
+  creds[82]  = 5.6;
+  creds[83]  = 10.4;
+  creds[84]  = 6.1;
+  creds[85]  = 0.9;
+  creds[86]  = 7.7;
+  creds[87]  = 7.4;
+  creds[88]  = 6.9;
+  creds[89]  = 7.0;
+  creds[90]  = 3.3;
+  creds[91]  = 7.1;
+  creds[92]  = 5.8;
+  creds[93]  = 7.2;
+  creds[94]  = 5.4;
+  creds[95]  = 7.4;
+  creds[96]  = 6.6;
+  creds[97]  = 0.0;
+  creds[98]  = 6.9;
+  creds[99]  = 7.3;
+  creds[100] = 8.7;
+  creds[101] = 6.5;
+  creds[102] = 5.8;
+  creds[103] = 6.1;
+  creds[104] = 6.6;
+  creds[105] = 8.7;
+  creds[106] = 6.8;
+  creds[107] = 7.0;
+  creds[108] = 7.4;
+  creds[109] = 7.1;
+  creds[110] = 8.8;
+  creds[111] = 7.0;
+  creds[112] = 8.3;
+  creds[113] = 3.5;
+  creds[114] = 7.4;
+  creds[115] = 8.7;
+  creds[116] = 7.6;
+  creds[117] = 7.6;
+  creds[118] = 6.6;
+  creds[119] = 5.9;
+  creds[120] = 6.8;
+  creds[121] = 0.4;
+  creds[122] = 7.5;
+  creds[123] = 5.7;
+  creds[124] = 1.6;
+  creds[125] = 6.2;
+  creds[126] = 7.4;
+  creds[127] = 7.3;
+  creds[128] = 8.5;
+  creds[129] = 6.9;
+  creds[130] = 7.3;
+  creds[131] = 6.8;
+  creds[132] = 6.6;
+  creds[133] = 6.5;
+  creds[134] = 5.7;
+  creds[135] = 5.8;
+  creds[136] = 6.2;
+  creds[137] = 5.8;
+  creds[138] = 6.1;
+  creds[139] = 7.2;
+  creds[140] = 6.0;
+  creds[141] = 7.7;
+  creds[142] = 6.7;
+  creds[143] = 4.3;
+  creds[144] = 7.2;
+  creds[145] = 7.0;
+  creds[146] = 7.4;
+  creds[147] = 5.4;
+  creds[148] = 6.5;
+  creds[149] = 5.9;
+  creds[150] = 5.5;
+  creds[151] = 7.0;
+  creds[152] = 7.0;
+  creds[153] = 6.5;
+  creds[154] = 5.6;
+  creds[155] = 5.6;
+  creds[156] = 7.8;
+  creds[157] = 7.2;
+  creds[158] = 5.7;
+  creds[159] = 5.9;
+  creds[160] = 5.9;
+  creds[161] = 5.8;
+  creds[162] = 1.2;
+  creds[163] = 7.9;
+  creds[164] = 7.7;
+  creds[165] = 9.5;
+  creds[166] = 6.4;
+  creds[167] = 6.6;
+  creds[168] = 7.1;
+  creds[169] = 6.3;
+  creds[170] = 7.4;
+  creds[171] = 4.0;
+  creds[172] = 6.2;
+  creds[173] = 6.4;
+  creds[174] = 3.8;
+  creds[175] = 7.5;
+  creds[176] = 8.0;
+  creds[177] = 7.0;
+  creds[178] = 6.0;
+  creds[179] = 6.5;
+  creds[180] = 7.1;
+  creds[181] = 4.7;
+  creds[182] = 9.7;
+  creds[183] = 6.1;
+  creds[184] = 6.7;
+  creds[185] = 6.2;
+  creds[186] = 6.7;
+  creds[187] = 6.1;
+  creds[188] = 4.9;
+  creds[189] = 5.8;
+  creds[190] = 6.4;
+  creds[191] = 6.5;
+  creds[192] = 7.1;
+  creds[193] = 8.1;
+  creds[194] = 5.5;
+  creds[195] = 7.1;
+  creds[196] = 6.5;
+  creds[197] = 6.7;
+  creds[198] = 7.0;
+  creds[199] = 7.5;
+  creds[200] = 6.5;
+  creds[201] = 6.5;
+  creds[202] = 6.8;
+  creds[203] = 5.6;
+  creds[204] = 6.9;
+  creds[205] = 6.6;
+  creds[206] = 7.4;
+  creds[207] = 6.1;
+  creds[208] = 6.8;
+  creds[209] = 8.1;
+  creds[210] = 7.6;
+  creds[211] = 6.2;
+  creds[212] = 6.9;
+  creds[213] = 5.8;
+  creds[214] = 7.0;
+  creds[215] = 5.7;
+  creds[216] = 4.1;
+  creds[217] = 2.4;
+  creds[218] = 1.1;
+  creds[219] = 6.5;
+  creds[220] = 5.9;
+  creds[221] = 6.4;
+  creds[222] = 7.3;
+  creds[223] = 7.5;
+  creds[224] = 1.2;
+  creds[225] = 4.2;
+  creds[226] = 6.4;
+  creds[227] = 6.9;
+  creds[228] = 7.1;
+  creds[229] = 4.4;
+  creds[230] = 7.4;
+  creds[231] = 6.9;
+  creds[232] = 5.3;
+  creds[233] = 2.0;
+  creds[234] = 6.3;
+  creds[235] = 7.6;
+  creds[236] = 8.2;
+  creds[237] = 9.1;
+  creds[238] = 6.3;
+  creds[239] = 5.9;
+  creds[240] = 7.2;
+  creds[241] = 5.4;
+  creds[242] = 9.1;
+  creds[243] = 5.3;
+  creds[244] = 5.0;
+  creds[245] = 7.2;
+  creds[246] = 4.5;
+  creds[247] = 5.3;
+  creds[248] = 9.0;
+  creds[249] = 5.9;
+  creds[250] = 9.1;
+  creds[251] = 7.4;
+  creds[252] = 4.8;
+  creds[253] = 5.5;
+  creds[254] = 3.9;
+  creds[255] = 7.1;
+  creds[256] = 6.3;
+  creds[257] = 4.3;
+  creds[258] = 6.2;
+  creds[259] = 5.1;
+  creds[260] = -1.;
+  creds[261] = 1.2;
+  creds[262] = 7.8;
+  creds[263] = 0.4;
+  creds[264] = 5.7;
+  creds[265] = 4.2;
+  creds[266] = 7.8;
+  creds[267] = 8.6;
+  creds[268] = 4.2;
+  creds[269] = 6.7;
+  creds[270] = 6.7;
+  creds[271] = 5.2;
+  creds[272] = 7.1;
+  creds[273] = 0.2;
+  creds[274] = 1.2;
+  creds[275] = 6.0;
+  creds[276] = 4.1;
+  creds[277] = 0.9;
+  creds[278] = 1.7;
+  creds[279] = 6.8;
+  creds[280] = 3.8;
+  creds[281] = 1.8;
+  creds[282] = 6.3;
+  creds[283] = 4.1;
+  creds[284] = 2.4;
+  creds[285] = 7.2;
+  creds[286] = 2.2;
+  creds[287] = 6.6;
+  creds[288] = 6.1;
+  creds[289] = 2.6;
+  creds[290] = 5.2;
+  creds[291] = 1.4;
+  creds[292] = 4.0;
+  creds[293] = 2.6;
+  creds[294] = 3.0;
+  creds[295] = 6.6;
+  creds[296] = 7.6;
+  creds[297] = 5.6;
+  creds[298] = 7.3;
+  creds[299] = 7.3;
+  creds[300] = 7.8;
+  creds[301] = 1.5;
+  creds[302] = 3.3;
+  creds[303] = 0.6;
+  creds[304] = 5.9;
+  creds[305] = 7.0;
+  creds[306] = 6.3;
+  creds[307] = 3.9;
+  creds[308] = 2.4;
+  creds[309] = 5.8;
+  creds[310] = 7.4;
+  creds[311] = 1.5;
+  creds[312] = 4.1;
+  creds[313] = 4.5;
+  creds[314] = 4.5;
+  creds[315] = 6.6;
+  creds[316] = 6.0;
+  creds[317] = 6.0;
+  creds[318] = 8.8;
+  creds[319] = 5.6;
+  creds[320] = 4.1;
+  creds[321] = 4.6;
+  creds[322] = 1.4;
+  creds[323] = 2.1;
+  creds[324] = 5.5;
+  creds[325] = 3.4;
+  creds[326] = 6.0;
+  creds[327] = 3.6;
+  creds[328] = 7.3;
+  creds[329] = 6.4;
+  creds[330] = 7.1;
+  creds[331] = 8.1;
+  creds[332] = 1.1;
+  creds[333] = 2.8;
+  creds[334] = 1.3;
+  creds[335] = 1.6;
+  creds[336] = 1.6;
+  creds[337] = 1.6;
+  creds[338] = 1.1;
+  creds[339] = 1.3;
+  creds[340] = 1.3;
+  creds[341] = 1.2;
+  creds[342] = 0.6;
+  creds[343] = 8.0;
+  creds[344] = 1.9;
+  creds[345] = -1.;
+  creds[346] = 2.4;
+  creds[347] = 1.4;
+  creds[348] = 6.1;
+  creds[349] = 1.9;
+  creds[350] = 1.6;
+  creds[351] = 1.5;
+  creds[352] = 1.0;
+  creds[353] = 1.4;
+  creds[354] = 1.3;
+  creds[355] = 1.1;
+  creds[356] = 1.1;
+  creds[357] = 1.4;
+  creds[358] = 1.8;
+  creds[359] = 1.1;
+  creds[360] = 1.6;
+  creds[361] = 1.4;
+  creds[362] = 1.4;
+  creds[363] = 7.9;
+  creds[364] = 2.0;
+  creds[365] = 1.4;
+  creds[366] = 7.6;
+  creds[367] = 1.1;
+  creds[368] = 1.4;
+  creds[369] = 1.3;
+  creds[370] = 0.8;
+  creds[371] = 3.4;
+  creds[372] = 0.9;
+  creds[373] = 6.2;
+  creds[374] = 0.4;
+  creds[375] = 1.1;
+  creds[376] = 1.4;
+  creds[377] = 1.2;
+  creds[378] = 1.4;
+  creds[379] = 2.2;
+  creds[380] = 2.0;
+  creds[381] = 1.6;
+  creds[382] = 2.2;
+  creds[383] = 8.5;
+  creds[384] = 1.9;
+  creds[385] = 1.0;
+  creds[386] = 1.8;
+  creds[387] = 5.8;
+  creds[388] = 1.1;
+  creds[389] = 2.4;
+  creds[390] = 2.4;
+  creds[391] = 4.6;
+  creds[392] = 1.2;
+  creds[393] = -1.;
+  creds[394] = 1.2;
+  creds[395] = 0.6;
+  creds[396] = 1.5;
+  creds[397] = 1.0;
+  creds[398] = 6.8;
+  creds[399] = 17.4;
+  creds[400] = 18.6;
+  creds[401] = 2.3;
+  creds[402] = 7.7;
+  creds[403] = 2.2;
+  creds[404] = 4.6;
+  creds[405] = 4.0;
+  creds[406] = 11.7;
+  creds[407] = 5.0;
+  creds[408] = 10.6;
+  creds[409] = 17.7;
+  creds[410] = 6.9;
+  creds[411] = 6.3;
+  creds[412] = 6.7;
+  creds[413] = 1.9;
+  creds[414] = 15.8;
+  creds[415] = 4.9;
+  creds[416] = 24.7;
+  creds[417] = 12.0;
+  creds[418] = 9.7;
+  creds[419] = 19.3;
+  creds[420] = 13.0;
+  creds[421] = 1.6;
+  creds[422] = 4.4;
+  creds[423] = 2.8;
+  creds[424] = 16.5;
+  creds[425] = 6.1;
+  creds[426] = 8.1;
+  creds[427] = 1.7;
+  creds[428] = 6.2;
+  creds[429] = 8.1;
+  creds[430] = 14.5;
+  creds[431] = 2.5;
+  creds[432] = 12.9;
+  creds[433] = 7.4;
+  creds[434] = 7.9;
+  creds[435] = 5.1;
+  creds[436] = 6.5;
+  creds[437] = 12.3;
+  creds[438] = 8.4;
+  creds[439] = 2.2;
+  creds[440] = 5.0;
+  creds[441] = 2.9;
+  creds[442] = 10.4;
+  creds[443] = 13.1;
+  creds[444] = 5.6;
+  creds[445] = 8.0;
+  creds[446] = 5.9;
+  creds[447] = 8.1;
+  creds[448] = 6.8;
+  creds[449] = 6.9;
+  creds[450] = 12.3;
+  creds[451] = 9.1;
+  creds[452] = 2.7;
+  creds[453] = 2.7;
+  creds[454] = 4.2;
+  creds[455] = 4.9;
+  creds[456] = 10.9;
+  creds[457] = 7.2;
+  creds[458] = 18.3;
+  creds[459] = 6.1;
+  creds[460] = 7.7;
+  creds[461] = 2.7;
+  creds[462] = 17.6;
+  creds[463] = 3.8;
+  creds[464] = 12.6;
+  creds[465] = 9.3;
+  creds[466] = 9.2;
+  creds[467] = 7.0;
+  creds[468] = 7.9;
+  creds[469] = 14.6;
+  creds[470] = 13.6;
+  creds[471] = 0.9;
+  creds[472] = 8.1;
+  creds[473] = 9.3;
+  creds[474] = 3.0;
+  creds[475] = 24.7;
+  creds[476] = 19.5;
+  creds[477] = 6.2;
+  creds[478] = 6.9;
+  creds[479] = 11.7;
+  creds[480] = 11.3;
+  creds[481] = 7.3;
+  creds[482] = 12.8;
+  creds[483] = 11.3;
+  creds[484] = 3.9;
+  creds[485] = 4.4;
+  creds[486] = 5.9;
+  creds[487] = 7.3;
+  creds[488] = 7.1;
+  creds[489] = 1.4;
+  creds[490] = 12.6;
+  creds[491] = 9.6;
+  creds[492] = 10.7;
+  creds[493] = 13.5;
+  creds[494] = 1.9;
+  creds[495] = 9.8;
+  creds[496] = 5.6;
+  creds[497] = 6.2;
+  creds[498] = 14.0;
+  creds[499] = 5.4;
+  creds[500] = 8.4;
+  creds[501] = 16.2;
+  creds[502] = 15.1;
+  creds[503] = 9.7;
+  creds[504] = 13.0;
+  creds[505] = 12.3;
+  creds[506] = 7.4;
+  creds[507] = 3.7;
+  creds[508] = 7.2;
+  creds[509] = 9.6;
+  creds[510] = 21.1;
+  creds[511] = 2.3;
+  creds[512] = 13.5;
+  creds[513] = 14.3;
+  creds[514] = 3.5;
+  creds[515] = 6.7;
+  creds[516] = 7.8;
+  creds[517] = 6.2;
+  creds[518] = 8.3;
+  creds[519] = 6.3;
+  creds[520] = 5.8;
+  creds[521] = 4.6;
+  creds[522] = 1.8;
+  creds[523] = 6.2;
+  creds[524] = 11.;
+  creds[525] = 1.8;
+  creds[526] = 5.4;
+  creds[527] = 8.5;
+  creds[528] = 12.9;
+  creds[529] = 4.3;
+  creds[530] = 15.5;
+  creds[531] = 1.7;
+  creds[532] = 3.2;
+  creds[533] = 9.9;
+  creds[534] = 4.8;
+  creds[535] = 8.0;
+  creds[536] = 9.9;
+  creds[537] = 4.4;
+  creds[538] = 5.6;
+  creds[539] = 13.5;
+  creds[540] = 11.7;
+  creds[541] = 18.7;
+  creds[542] = 6.5;
+  creds[543] = 11.7;
+  creds[544] = 12.7;
+  creds[545] = 4.2;
+  creds[546] = 7.3;
+  creds[547] = 14.9;
+  creds[548] = 6.8;
+  creds[549] = 4.8;
+  creds[550] = 7.1;
+  creds[551] = 6.2;
+  creds[552] = 2.3;
+  creds[553] = 16.9;
+  creds[554] = 6.8;
+  creds[555] = 14.6;
+  creds[556] = 20.5;
+  creds[557] = 7.0;
+  creds[558] = 5.7;
+  creds[559] = 6.6;
+  creds[560] = 13.5;
+  creds[561] = 11.0;
+  creds[562] = 4.2;
+  creds[563] = 10.6;
+  creds[564] = 6.5;
+  creds[565] = 6.5;
+  creds[566] = 1.7;
+  creds[567] = 8.2;
+  creds[568] = 5.1;
+  creds[569] = 5.6;
+  creds[570] = 9.1;
+  creds[571] = 0.6;
+  creds[572] = 19.1;
+  creds[573] = 5.7;
+  creds[574] = 6.0;
+  creds[575] = 3.9;
+  creds[576] = 2.6;
+
+  fCorningReds.Set(577,creds);
+}
+
+void MCalibrationQECamMagic::CreateCorningBlues()
+{
+ 
+  Double_t cblues[577];
+
+  cblues[0]   = -1.;
+  cblues[1]   = 12.0;
+  cblues[2]   = 12.2;
+  cblues[3]   = 12.6;
+  cblues[4]   = 12.7;
+  cblues[5]   = 12.8;
+  cblues[6]   = -1.;
+  cblues[7]   = 10.8;
+  cblues[8]   = 9.0;
+  cblues[9]   = 12.2;
+  cblues[10]  = 12.3;
+  cblues[11]  = 11.7;
+  cblues[12]  = 12.0;
+  cblues[13]  = 12.1;
+  cblues[14]  = 12.0;
+  cblues[15]  = 12.6;
+  cblues[16]  = 12.2;
+  cblues[17]  = 12.6;
+  cblues[18]  = 12.6;
+  cblues[19]  = 11.5;
+  cblues[20]  = 11.1;
+  cblues[21]  = 11.2;
+  cblues[22]  = 12.1;
+  cblues[23]  = 12.8;
+  cblues[24]  = 12.7;
+  cblues[25]  = 12.8;
+  cblues[26]  = 13.0;
+  cblues[27]  = 13.0;
+  cblues[28]  = 12.0;
+  cblues[29]  = 12.4;
+  cblues[30]  = 12.0;
+  cblues[31]  = 12.1;
+  cblues[32]  = 12.0;
+  cblues[33]  = 12.2;
+  cblues[34]  = 12.0;
+  cblues[35]  = 12.5;
+  cblues[36]  = 12.4;
+  cblues[37]  = 10.3;
+  cblues[38]  = 10.8;
+  cblues[39]  = 11.4;
+  cblues[40]  = 11.7;
+  cblues[41]  = 12.1;
+  cblues[42]  = 12.0;
+  cblues[43]  = 12.4;
+  cblues[44]  = 13.0;
+  cblues[45]  = 12.7;
+  cblues[46]  = 12.8;
+  cblues[47]  = 10.5;
+  cblues[48]  = 12.1;
+  cblues[49]  = 12.1;
+  cblues[50]  = 12.4;
+  cblues[51]  = 12.3;
+  cblues[52]  = 12.4;
+  cblues[53]  = 11.7;
+  cblues[54]  = 12.8;
+  cblues[55]  = 12.0;
+  cblues[56]  = 12.5;
+  cblues[57]  = 12.2;
+  cblues[58]  = 12.3;
+  cblues[59]  = 12.3;
+  cblues[60]  = 12.6;
+  cblues[61]  = 11.6;
+  cblues[62]  = 11.9;
+  cblues[63]  = 11.8;
+  cblues[64]  = 10.7;
+  cblues[65]  = 10.9;
+  cblues[66]  = 12.1;
+  cblues[67]  = 12.5;
+  cblues[68]  = 12.4;
+  cblues[69]  = 12.1;
+  cblues[70]  = 12.2;
+  cblues[71]  = 13.1;
+  cblues[72]  = 12.5;
+  cblues[73]  = 12.4;
+  cblues[74]  = 12.6;
+  cblues[75]  = 12.5;
+  cblues[76]  = 12.1;
+  cblues[77]  = 12.5;
+  cblues[78]  = 12.3;
+  cblues[79]  = 12.0;
+  cblues[80]  = 12.4;
+  cblues[81]  = 12.4;
+  cblues[82]  = 12.0;
+  cblues[83]  = 12.3;
+  cblues[84]  = 12.1;
+  cblues[85]  = 11.3;
+  cblues[86]  = 12.0;
+  cblues[87]  = 12.0;
+  cblues[88]  = 12.4;
+  cblues[89]  = 12.3;
+  cblues[90]  = 12.0;
+  cblues[91]  = 11.4;
+  cblues[92]  = 11.7;
+  cblues[93]  = 11.9;
+  cblues[94]  = 11.4;
+  cblues[95]  = 11.1;
+  cblues[96]  = 11.9;
+  cblues[97]  = 9.2;
+  cblues[98]  = 12.4;
+  cblues[99]  = 11.5;
+  cblues[100] = 12.3;
+  cblues[101] = 11.0;
+  cblues[102] = 12.0;
+  cblues[103] = 11.8;
+  cblues[104] = 12.5;
+  cblues[105] = 11.6;
+  cblues[106] = 12.3;
+  cblues[107] = 11.2;
+  cblues[108] = 12.4;
+  cblues[109] = 11.5;
+  cblues[110] = 12.1;
+  cblues[111] = 11.0;
+  cblues[112] = 12.1;
+  cblues[113] = 11.6;
+  cblues[114] = 12.0;
+  cblues[115] = 11.4;
+  cblues[116] = 12.0;
+  cblues[117] = 11.7;
+  cblues[118] = 12.6;
+  cblues[119] = 11.4;
+  cblues[120] = 12.3;
+  cblues[121] = 10.9;
+  cblues[122] = 12.1;
+  cblues[123] = 11.8;
+  cblues[124] = 12.2;
+  cblues[125] = 11.5;
+  cblues[126] = 12.1;
+  cblues[127] = 11.7;
+  cblues[128] = 11.4;
+  cblues[129] = 11.5;
+  cblues[130] = 11.2;
+  cblues[131] = 11.8;
+  cblues[132] = 11.3;
+  cblues[133] = 11.5;
+  cblues[134] = 11.1;
+  cblues[135] = 11.7;
+  cblues[136] = 11.2;
+  cblues[137] = 11.6;
+  cblues[138] = 11.8;
+  cblues[139] = 11.4;
+  cblues[140] = 11.6;
+  cblues[141] = 11.1;
+  cblues[142] = 11.9;
+  cblues[143] = 11.4;
+  cblues[144] = 11.5;
+  cblues[145] = 11.6;
+  cblues[146] = 11.9;
+  cblues[147] = 11.0;
+  cblues[148] = 11.6;
+  cblues[149] = 11.9;
+  cblues[150] = 11.5;
+  cblues[151] = 11.8;
+  cblues[152] = 11.4;
+  cblues[153] = 11.9;
+  cblues[154] = 11.0;
+  cblues[155] = 11.7;
+  cblues[156] = 11.9;
+  cblues[157] = -1.;
+  cblues[158] = 11.4;
+  cblues[159] = 11.0;
+  cblues[160] = 11.9;
+  cblues[161] = 11.6;
+  cblues[162] = 11.4;
+  cblues[163] = 11.6;
+  cblues[164] = 11.0;
+  cblues[165] = 11.6;
+  cblues[166] = 11.4;
+  cblues[167] = 11.5;
+  cblues[168] = 11.9;
+  cblues[169] = 10.9;
+  cblues[170] = 10.8;
+  cblues[171] = 10.3;
+  cblues[172] = 10.9;
+  cblues[173] = 11.4;
+  cblues[174] = 11.5;
+  cblues[175] = 11.7;
+  cblues[176] = 11.9;
+  cblues[177] = 11.6;
+  cblues[178] = 10.4;
+  cblues[179] = 11.6;
+  cblues[180] = 11.5;
+  cblues[181] = 11.7;
+  cblues[182] = 11.6;
+  cblues[183] = 11.7;
+  cblues[184] = 11.5;
+  cblues[185] = 11.7;
+  cblues[186] = 11.6;
+  cblues[187] = 11.3;
+  cblues[188] = 11.3;
+  cblues[189] = 11.2;
+  cblues[190] = 11.5;
+  cblues[191] = 11.7;
+  cblues[192] = 11.8;
+  cblues[193] = 11.2;
+  cblues[194] = 11.9;
+  cblues[195] = 11.3;
+  cblues[196] = 11.2;
+  cblues[197] = 11.0;
+  cblues[198] = 11.4;
+  cblues[199] = 11.5;
+  cblues[200] = 11.5;
+  cblues[201] = 11.7;
+  cblues[202] = 11.6;
+  cblues[203] = 11.7;
+  cblues[204] = 11.4;
+  cblues[205] = 11.6;
+  cblues[206] = 11.3;
+  cblues[207] = 11.5;
+  cblues[208] = 11.8;
+  cblues[209] = 11.6;
+  cblues[210] = 11.9;
+  cblues[211] = 11.2;
+  cblues[212] = 11.1;
+  cblues[213] = 11.4;
+  cblues[214] = 11.6;
+  cblues[215] = 11.3;
+  cblues[216] = 11.5;
+  cblues[217] = 10.1;
+  cblues[218] = 9.5;
+  cblues[219] = 10.0;
+  cblues[220] = 10.8;
+  cblues[221] = 10.4;
+  cblues[222] = 10.4;
+  cblues[223] = 10.3;
+  cblues[224] = 11.8;
+  cblues[225] = 10.4;
+  cblues[226] = 11.5;
+  cblues[227] = 10.3;
+  cblues[228] = 10.3;
+  cblues[229] = 10.6;
+  cblues[230] = 10.8;
+  cblues[231] = 10.6;
+  cblues[232] = 10.5;
+  cblues[233] = 10.5;
+  cblues[234] = 11.3;
+  cblues[235] = 11.7;
+  cblues[236] = 10.9;
+  cblues[237] = 10.6;
+  cblues[238] = 10.8;
+  cblues[239] = 10.7;
+  cblues[240] = 10.9;
+  cblues[241] = 10.5;
+  cblues[242] = 10.8;
+  cblues[243] = 11.1;
+  cblues[244] = 11.2;
+  cblues[245] = 10.6;
+  cblues[246] = 10.6;
+  cblues[247] = 10.9;
+  cblues[248] = 10.6;
+  cblues[249] = 10.3;
+  cblues[250] = 10.6;
+  cblues[251] = 10.7;
+  cblues[252] = 11.5;
+  cblues[253] = 11.8;
+  cblues[254] = 10.8;
+  cblues[255] = 10.4;
+  cblues[256] = 10.6;
+  cblues[257] = 10.6;
+  cblues[258] = 10.5;
+  cblues[259] = 10.3;
+  cblues[260] = -1.;
+  cblues[261] = 11.1;
+  cblues[262] = 10.7;
+  cblues[263] = 10.6;
+  cblues[264] = 10.5;
+  cblues[265] = 10.7;
+  cblues[266] = 10.3;
+  cblues[267] = 10.2;
+  cblues[268] = 10.4;
+  cblues[269] = 10.2;
+  cblues[270] = 11.4;
+  cblues[271] = 10.9;
+  cblues[272] = 11.5;
+  cblues[273] = 8.9;
+  cblues[274] = 8.3;
+  cblues[275] = 8.9;
+  cblues[276] = 13.7;
+  cblues[277] = 8.4;
+  cblues[278] = 9.6;
+  cblues[279] = 10.0;
+  cblues[280] = 9.0;
+  cblues[281] = 12.2;
+  cblues[282] = 9.9;
+  cblues[283] = 9.0;
+  cblues[284] = 10.0;
+  cblues[285] = 10.1;
+  cblues[286] = 9.5;
+  cblues[287] = 10.0;
+  cblues[288] = 10.8;
+  cblues[289] = 10.8;
+  cblues[290] = 10.3;
+  cblues[291] = 11.6;
+  cblues[292] = 9.8;
+  cblues[293] = 10.1;
+  cblues[294] = 9.8;
+  cblues[295] = 9.6;
+  cblues[296] = 9.2;
+  cblues[297] = 9.7;
+  cblues[298] = 10.2;
+  cblues[299] = 10.2;
+  cblues[300] = 10.9;
+  cblues[301] = 12.1;
+  cblues[302] = 10.0;
+  cblues[303] = 9.8;
+  cblues[304] = 9.6;
+  cblues[305] = 10.9;
+  cblues[306] = 10.3;
+  cblues[307] = 10.2;
+  cblues[308] = 9.4;
+  cblues[309] = 9.8;
+  cblues[310] = 10.8;
+  cblues[311] = 12.3;
+  cblues[312] = 9.6;
+  cblues[313] = 9.5;
+  cblues[314] = 9.0;
+  cblues[315] = 10.3;
+  cblues[316] = 10.4;
+  cblues[317] = 10.9;
+  cblues[318] = 9.9;
+  cblues[319] = 10.0;
+  cblues[320] = 10.1;
+  cblues[321] = 8.1;
+  cblues[322] = 12.1;
+  cblues[323] = 10.1;
+  cblues[324] = 10.1;
+  cblues[325] = 9.3;
+  cblues[326] = 10.1;
+  cblues[327] = 9.4;
+  cblues[328] = 9.6;
+  cblues[329] = 10.6;
+  cblues[330] = 10.7;
+  cblues[331] = 10.2;
+  cblues[332] = 11.5;
+  cblues[333] = 11.9;
+  cblues[334] = 11.9;
+  cblues[335] = 11.8;
+  cblues[336] = 13.1;
+  cblues[337] = 10.9;
+  cblues[338] = 10.4;
+  cblues[339] = 11.7;
+  cblues[340] = 11.5;
+  cblues[341] = 10.6;
+  cblues[342] = 9.5;
+  cblues[343] = 11.5;
+  cblues[344] = 11.9;
+  cblues[345] = -1.;
+  cblues[346] = 10.3;
+  cblues[347] = 8.0;
+  cblues[348] = 11.0;
+  cblues[349] = 12.1;
+  cblues[350] = 12.0;
+  cblues[351] = 12.1;
+  cblues[352] = 11.2;
+  cblues[353] = 11.2;
+  cblues[354] = 12.4;
+  cblues[355] = 11.0;
+  cblues[356] = 11.6;
+  cblues[357] = 11.4;
+  cblues[358] = 10.6;
+  cblues[359] = 11.0;
+  cblues[360] = 11.8;
+  cblues[361] = 12.4;
+  cblues[362] = 12.4;
+  cblues[363] = 12.2;
+  cblues[364] = 9.8;
+  cblues[365] = 11.7;
+  cblues[366] = 9.8;
+  cblues[367] = 11.4;
+  cblues[368] = 12.0;
+  cblues[369] = 11.7;
+  cblues[370] = 10.9;
+  cblues[371] = 11.2;
+  cblues[372] = 10.6;
+  cblues[373] = 10.0;
+  cblues[374] = 10.0;
+  cblues[375] = 10.6;
+  cblues[376] = 11.2;
+  cblues[377] = 12.0;
+  cblues[378] = 11.3;
+  cblues[379] = 12.5;
+  cblues[380] = 12.0;
+  cblues[381] = 11.4;
+  cblues[382] = 12.0;
+  cblues[383] = 13.6;
+  cblues[384] = 12.6;
+  cblues[385] = 10.9;
+  cblues[386] = 12.0;
+  cblues[387] = 10.0;
+  cblues[388] = 11.4;
+  cblues[389] = 11.6;
+  cblues[390] = 10.3;
+  cblues[391] = 8.5;
+  cblues[392] = 11.7;
+  cblues[393] = -1.;
+  cblues[394] = 12.1;
+  cblues[395] = 10.5;
+  cblues[396] = 12.1;
+  cblues[397] = 9.5;
+  cblues[398] = 9.9;
+  cblues[399] = 12.9;
+  cblues[400] = 12.4;
+  cblues[401] = 11.3;
+  cblues[402] = 10.8;
+  cblues[403] = 11.2;
+  cblues[404] = 9.2;
+  cblues[405] = 10.7;
+  cblues[406] = 13.6;
+  cblues[407] = 11.6;
+  cblues[408] = 11.2;
+  cblues[409] = 11.1;
+  cblues[410] = 11.6;
+  cblues[411] = 10.4;
+  cblues[412] = 12.0;
+  cblues[413] = 12.0;
+  cblues[414] = 10.6;
+  cblues[415] = 11.2;
+  cblues[416] = 11.6;
+  cblues[417] = 10.2;
+  cblues[418] = 11.3;
+  cblues[419] = 9.1;
+  cblues[420] = 11.6;
+  cblues[421] = 11.0;
+  cblues[422] = 10.6;
+  cblues[423] = 12.5;
+  cblues[424] = 12.0;
+  cblues[425] = 11.1;
+  cblues[426] = 11.5;
+  cblues[427] = 11.2;
+  cblues[428] = 10.2;
+  cblues[429] = 11.8;
+  cblues[430] = 10.8;
+  cblues[431] = 11.1;
+  cblues[432] = 11.0;
+  cblues[433] = 11.5;
+  cblues[434] = 11.9;
+  cblues[435] = 9.5;
+  cblues[436] = 11.3;
+  cblues[437] = 11.2;
+  cblues[438] = 11.4;
+  cblues[439] = 10.1;
+  cblues[440] = 11.0;
+  cblues[441] = 10.8;
+  cblues[442] = 9.3;
+  cblues[443] = 12.6;
+  cblues[444] = 9.9;
+  cblues[445] = 9.8;
+  cblues[446] = 10.4;
+  cblues[447] = 11.3;
+  cblues[448] = 12.0;
+  cblues[449] = 11.0;
+  cblues[450] = 11.7;
+  cblues[451] = 12.0;
+  cblues[452] = 9.1;
+  cblues[453] = 11.2;
+  cblues[454] = 10.6;
+  cblues[455] = 12.3;
+  cblues[456] = 10.9;
+  cblues[457] = 9.7;
+  cblues[458] = 11.2;
+  cblues[459] = 12.2;
+  cblues[460] = 12.5;
+  cblues[461] = 9.0;
+  cblues[462] = 11.6;
+  cblues[463] = 11.3;
+  cblues[464] = 10.8;
+  cblues[465] = 10.7;
+  cblues[466] = 12.1;
+  cblues[467] = 11.9;
+  cblues[468] = 12.2;
+  cblues[469] = 11.6;
+  cblues[470] = 11.5;
+  cblues[471] = 10.3;
+  cblues[472] = 11.8;
+  cblues[473] = 10.7;
+  cblues[474] = 10.4;
+  cblues[475] = 11.9;
+  cblues[476] = 11.2;
+  cblues[477] = 10.7;
+  cblues[478] = 10.4;
+  cblues[479] = 10.4;
+  cblues[480] = 11.3;
+  cblues[481] = 11.6;
+  cblues[482] = 10.1;
+  cblues[483] = 9.4;
+  cblues[484] = 12.3;
+  cblues[485] = 11.2;
+  cblues[486] = 9.6;
+  cblues[487] = 10.5;
+  cblues[488] = 11.7;
+  cblues[489] = 10.5;
+  cblues[490] = 11.5;
+  cblues[491] = 10.4;
+  cblues[492] = 12.1;
+  cblues[493] = 13.0;
+  cblues[494] = 10.9;
+  cblues[495] = 11.0;
+  cblues[496] = 11.0;
+  cblues[497] = 12.5;
+  cblues[498] = 12.3;
+  cblues[499] = 12.8;
+  cblues[500] = 12.2;
+  cblues[501] = 10.6;
+  cblues[502] = 11.6;
+  cblues[503] = 11.6;
+  cblues[504] = 11.6;
+  cblues[505] = 10.9;
+  cblues[506] = 11.9;
+  cblues[507] = 9.4;
+  cblues[508] = 12.1;
+  cblues[509] = 12.4;
+  cblues[510] = 11.6;
+  cblues[511] = 10.2;
+  cblues[512] = 11.4;
+  cblues[513] = 11.9;
+  cblues[514] = 9.6;
+  cblues[515] = 11.1;
+  cblues[516] = 12.3;
+  cblues[517] = 9.7;
+  cblues[518] = 12.4;
+  cblues[519] = 9.6;
+  cblues[520] = 10.6;
+  cblues[521] = 10.3;
+  cblues[522] = 11.1;
+  cblues[523] = 10.7;
+  cblues[524] = 13.3;
+  cblues[525] = 9.7;
+  cblues[526] = 10.8;
+  cblues[527] = 12.0;
+  cblues[528] = 12.3;
+  cblues[529] = 12.6;
+  cblues[530] = 11.9;
+  cblues[531] = 10.8;
+  cblues[532] = 10.2;
+  cblues[533] = 11.0;
+  cblues[534] = 10.8;
+  cblues[535] = 9.8;
+  cblues[536] = 11.6;
+  cblues[537] = 10.8;
+  cblues[538] = 9.9;
+  cblues[539] = 12.4;
+  cblues[540] = 10.4;
+  cblues[541] = 11.6;
+  cblues[542] = 11.1;
+  cblues[543] = 10.5;
+  cblues[544] = 11.1;
+  cblues[545] = 11.5;
+  cblues[546] = 11.6;
+  cblues[547] = 11.2;
+  cblues[548] = 9.7;
+  cblues[549] = 10.9;
+  cblues[550] = 11.7;
+  cblues[551] = 10.7;
+  cblues[552] = 10.2;
+  cblues[553] = 11.1;
+  cblues[554] = 10.2;
+  cblues[555] = 11.8;
+  cblues[556] = 12.2;
+  cblues[557] = 10.5;
+  cblues[558] = 11.2;
+  cblues[559] = 10.1;
+  cblues[560] = 12.3;
+  cblues[561] = 11.6;
+  cblues[562] = 9.9;
+  cblues[563] = 10.5;
+  cblues[564] = 11.3;
+  cblues[565] = 11.8;
+  cblues[566] = 10.7;
+  cblues[567] = 11.1;
+  cblues[568] = 11.8;
+  cblues[569] = 10.5;
+  cblues[570] = 11.8;
+  cblues[571] = 9.6;
+  cblues[572] = 11.1;
+  cblues[573] = 11.0;
+  cblues[574] = 11.8;
+  cblues[575] = 11.4;
+  cblues[576] = 10.2;
+
+  fCorningBlues.Set(577,cblues);
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationQECamMagic.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationQECamMagic.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationQECamMagic.h	(revision 9772)
@@ -0,0 +1,27 @@
+#ifndef MARS_MCalibrationQECamMagic
+#define MARS_MCalibrationQECamMagic
+
+#ifndef MARS_MCalibrationQECam
+#include "MCalibrationQECam.h"
+#endif
+
+class MCalibrationQECamMagic : public MCalibrationQECam
+{
+private:
+
+  void CreateCorningReds();
+  void CreateCorningBlues();
+
+public:
+
+  MCalibrationQECamMagic(const char *name=NULL, const char *title=NULL);
+
+  ClassDef(MCalibrationQECamMagic, 1) // Container Quantum Efficieny for MAGIC
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationQEPix.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationQEPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationQEPix.cc	(revision 9772)
@@ -0,0 +1,1379 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                      
+// MCalibrationQEPix                                                    
+//                                                                      
+// Storage container of the calibrated Quantrum Efficiency of one pixel. 
+// This container (like MCalibrationQECam) is designed to persist during 
+// several eventloops over different calibration files, especially those 
+// with different colour LEDs. This class contains all measured Quantum 
+// Efficiencies with the calibration system for each individual pixel.
+// 
+// At the moment, this calibration works in the following steps:
+//
+// 1)  MHCalibrationChargeCam extracts mean and sigma (and its errors) of 
+//     the summed FADC slices distribution and stores them in MCalibrationCam 
+//     
+// 2)  MHCalibrationChargeBlindPix extracts the mean of a Poisson fit to the 
+//     single photo-electron spectrum and stores it in MCalibrationChargeBlindPix
+//     
+// 3)  MHCalibrationChargePINDiode extracts the mean of a charge distribution 
+//     of the signals collected by the PIN Diode and stores it in 
+//     MCalibrationChargePINDiode
+//     
+// 4)  MCalibrationChargeCalc calculates for every pixel the number of 
+//     photo-electrons with the F-Factor method and stores them in MCalibrationChargePix
+//
+// 5)  MCalibrationChargeCalc calculates the (weighted) average number of photo-
+//     electrons from the pixels with the area index 0 (Inner pixels for the MAGIC 
+//     camera) and divides this number by gkDefaultQEGreen, gkDefaultQEBlue, 
+//     gkDefaultQEUV or gkDefaultQECT1, depending on the used pulser LED colour, 
+//     and further by MCalibrationQECam::gkPlexiglassQE. The obtained number is then 
+//     divided further by MGeomCam::GetPixRatio(pixel idx) (1. for inner pixels) and 
+//     gives the NUMBER OF PHOTONS incident on every pixel light guide OUTSIDE THE PLEXIGLASS 
+//     of the camera, obtained with the F-Factor method. (In the case of the MAGIC camera, 
+//     this number is thus BY CONSTRUCTION four times bigger for the outer pixels than for 
+//     the inner ones.)
+//
+// 6)  MCalibrationChargeCalc calculates the mean photon flux per mm^2 in the camera 
+//     from the MCalibrationChargeBlindPix and multiplies it with the light guides area 
+//     of each pixel (MGeomPix::GetA()) and divides it by the quantum efficiency of the 
+//     plexi-glass (MCalibrationQECam::gkPlexiglassQE). The obtained number gives the 
+//     NUMBER OF PHOTONS incident on every pixel light guide OUTSIDE THE PLEXIGLASS of the camera, 
+//     obtained with the Blind Pixel method. 
+//
+// 7)  MCalibrationChargeCalc calculates the mean photon flux per mm^2 in the camera 
+//     from the MCalibrationChargePINDiode and multiplies it with the light guides area 
+//     of each pixel (MGeomPix::GetA()).  The obtained number gives the NUMBER OF PHOTONS 
+//     incident on every pixels light guid OUTSIDE THE PLEXIGLASS of the camera, 
+//     obtained with the PIN Diode method. 
+//
+// 8)  Each of the three photons numbers is divided by the mean sum of FADC counts 
+//     and defined as MEASURED QUANTUM EFFICIENCY AT A GIVEN COLOUR. They are stored 
+//     in the variables SetQEBlindPixel(qe, color), SetQEFFactor(qe,color) and 
+//     SetQEPINDiode(qe,color) 
+//
+// 9)  Errors are propagated and corresponding variances get stored in 
+//     SetQEBlindPixelVar(var,color), SetQEFFactorVar(var,color) and 
+//     SetQEPINDiodeVar(var,color).
+//
+// 10) After every eventloop, MCalibrationChargeCalc calls the functions UpdateBlindPixelMethod(),
+//     UpdateFFactorMethod() and UpdatePINDiodeMethod() which calculate the ratio 
+//     measured QE / gkDefaultQEGreen (or gkDefaultQEBlue or gkDefaultQEUV or gkDefaultQECT1) 
+//     and calculates an weighted average of these quantum-efficiency normalizations obtained
+//     by one of the three methods.
+//
+// 11) A call to GetQECascadesBlindPixel(zenith), GetQECascadesFFactor(zenith) or 
+//     GetQECascadesPINDiode(zenith) returns then the normalization multiplied with an average QE 
+//     folded into a cascades spectrum. This number should be dependent on zenith angle, but 
+//     this feature is not yet implemented, instead a fixed number gkDefaultAverageQE is used. 
+// 
+// The number gkDefaultAverageQE = 0.18 +- 0.02 can be obtained in the following way: 
+//
+// * Transmission probability Plexiglass: 0.92
+//
+// * Averaged QE coated PMTs: zenith     value
+//                              0.       0.237
+//                             20.       0.237
+//                             40.       0.236
+//                             60.       0.234
+// (from D.Paneque et al., NIM A 504, 2003, 109-115, see following figure with the 
+//  photon spectra at 2200 m altitude:)
+//
+//Begin_Html
+/*
+<img src="images/Photon_spectrum.png">
+*/
+//End_Html
+// 
+// * PMT photoelectron collection efficiency: 0.9
+// (from D.Paneque, email 14.2.2004)
+//
+// * Light guides efficiency: 0.94
+// (from D.Paneque, email 14.2.2004)
+// 
+// "Concerning the light guides effiency estimation... Daniel Ferenc 
+//  is preparing some work (simulations) to estimate it. Yet so far, he has 
+//  been busy with other stuff, and this work is still Unfinished.
+//
+//  The estimation I did comes from:
+//  1) Reflectivity of light guide walls is 85 % (aluminum)
+//  2) At ZERO degree light incidence, 37% of the light hits such walls 
+//    (0.15X37%= 5.6% of light lost)
+//  3) When increasing the light incidence angle, more and more light hits 
+//     the walls.
+//
+//  However, the loses due to larger amount of photons hitting the walls is more 
+//  or less counteracted by the fact that more and more photon trajectories cross 
+//  the PMT photocathode twice, increasing the effective sensitivity of the PMT.
+//
+//Begin_Html
+/*
+<img src="images/Normalized_Cherenkov_phe_spectrums_20deg_60deg_coatedPMT.png">
+*/
+//End_Html
+//
+// The plot shows the normalized spectrum of photo-electrons preceding from 
+// a typical spectrum of Cherenkov photons produced by an atmospheric shower. The 
+// green line is for observation zenith angles of 20 deg. and the red line for 
+// 60 deg. The overall effective QE drops from about 20.8 to about 19.8. 
+//
+// Jurgen Gebauer did some quick measurements about this issue. I attach a 
+// plot. You can see that the angular dependence is (more or less) in agreement with a 
+// CosTheta function (below 20-25 degrees), which is the variation of the entrance 
+// window cross section. So, in first approximation, no losses when increasing light 
+// incidence angle; and therefore, the factor 0.94.
+//
+//Begin_Html
+/*
+<img src="images/JuergensMeasurementWithCosThetaCurve.png">
+*/
+//End_Html
+//
+// The Quantum efficiencies for individual colours have been taken from: 
+// D. Paneque et al., A Method to enhance the sensitivity of photomultipliers 
+//                    of air Cherenkov Telescopes, NIM A 504, 2003, 109-115
+// (see following figure)
+//
+//Begin_Html
+/*
+<img src="images/QE_Paneque.png">
+*/
+//End_Html
+//
+// The Transmission of the Plexiglass window has been provided by Eckart and is 
+// displayed in the next plot. The above red curve has to be taken since it corresponds
+// to the glass type set on the camera.
+//
+//Begin_Html
+/*
+<img src="images/Transmission_Plexiglass.jpg">
+*/
+//End_Html
+//
+// See also: MJCalibration, MCalibrationChargeCalc, 
+//           MCalibrationChargeCam, MCalibrationChargePix, 
+//           MHCalibrationChargeCam, MHCalibrationChargePix,
+//           MHCalibrationChargePINDiode, MHCalibrationChargeBlindPix
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationQEPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationQEPix);
+
+using namespace std;
+
+const Float_t MCalibrationQEPix::gkDefaultQEGreen      = 0.192;
+const Float_t MCalibrationQEPix::gkDefaultQEBlue       = 0.27;
+const Float_t MCalibrationQEPix::gkDefaultQEUV         = 0.285;
+const Float_t MCalibrationQEPix::gkDefaultQECT1        = 0.285;
+const Float_t MCalibrationQEPix::gkDefaultQEGreenErr   = 0.007;
+const Float_t MCalibrationQEPix::gkDefaultQEBlueErr    = 0.01 ;
+const Float_t MCalibrationQEPix::gkDefaultQEUVErr      = 0.012;
+const Float_t MCalibrationQEPix::gkDefaultQECT1Err     = 0.012;
+const Float_t MCalibrationQEPix::gkDefaultAverageQE    = 0.184;     
+const Float_t MCalibrationQEPix::gkDefaultAverageQEErr = 0.02 ;  
+const Float_t MCalibrationQEPix::gkPMTCollectionEff    = 0.90 ;
+const Float_t MCalibrationQEPix::gkPMTCollectionEffErr = 0.05 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffGreen    = 0.94 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffGreenErr = 0.03 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffBlue     = 0.94 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffBlueErr  = 0.03 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffUV       = 0.94 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffUVErr    = 0.03 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffCT1      = 0.94 ;
+const Float_t MCalibrationQEPix::gkLightGuidesEffCT1Err   = 0.03 ;
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Initializes all TArrays to MCalibrationCam::gkNumPulserColors
+//
+// Calls:
+// - Clear()
+//
+MCalibrationQEPix::MCalibrationQEPix(const char *name, const char *title)
+    :  fAverageQE ( gkDefaultAverageQE )
+{
+
+  fName  = name  ? name  : "MCalibrationQEPix";
+  fTitle = title ? title : "Container of the calibrated quantum efficiency ";
+
+  fQEBlindPixel    .Set( MCalibrationCam::gkNumPulserColors ); 
+  fQEBlindPixelVar .Set( MCalibrationCam::gkNumPulserColors );
+  fQECombined      .Set( MCalibrationCam::gkNumPulserColors );    
+  fQECombinedVar   .Set( MCalibrationCam::gkNumPulserColors ); 
+  fQEFFactor       .Set( MCalibrationCam::gkNumPulserColors );     
+  fQEFFactorVar    .Set( MCalibrationCam::gkNumPulserColors );  
+  fQEPINDiode      .Set( MCalibrationCam::gkNumPulserColors );    
+  fQEPINDiodeVar   .Set( MCalibrationCam::gkNumPulserColors );
+  fValidFlags      .Set( MCalibrationCam::gkNumPulserColors );
+
+  Clear();
+
+}
+
+// -----------------------------------------------------
+//
+// copy 'constructor'
+//
+void MCalibrationQEPix::Copy(TObject& object) const
+{
+
+  MCalibrationQEPix &pix = (MCalibrationQEPix&)object;
+
+  MCalibrationPix::Copy(pix);
+  //
+  // Copy the rest of the data members
+  //
+  pix.fQEBlindPixel      = fQEBlindPixel;
+  pix.fQEBlindPixelVar   = fQEBlindPixelVar;
+  pix.fQECombined        = fQECombined;
+  pix.fQECombinedVar     = fQECombinedVar;
+  pix.fQEFFactor         = fQEFFactor;
+  pix.fQEFFactorVar      = fQEFFactorVar;
+  pix.fQEPINDiode        = fQEPINDiode;
+  pix.fQEPINDiodeVar     = fQEPINDiodeVar;
+                                     
+  pix.fAvNormBlindPixel    = fAvNormBlindPixel;
+  pix.fAvNormBlindPixelVar = fAvNormBlindPixelVar;
+  pix.fAvNormCombined      = fAvNormCombined;
+  pix.fAvNormCombinedVar   = fAvNormCombinedVar;
+  pix.fAvNormFFactor       = fAvNormFFactor;
+  pix.fAvNormFFactorVar    = fAvNormFFactorVar;
+  pix.fAvNormPINDiode      = fAvNormPINDiode;
+  pix.fAvNormPINDiodeVar   = fAvNormPINDiodeVar;
+  pix.fAverageQE           = fAverageQE;
+
+  pix.fValidFlags          = fValidFlags;
+  pix.fAvailableFlags      = fAvailableFlags;
+  
+}
+
+// ----------------------------------------------------------------------------------------------
+// 
+// Search all available QE's of a certain colour after the blind pixel method, 
+// compare them to the default QE of that colour and 
+// add up a weighted average (wav) and a sum of weights (sumw)
+//
+// FIXME: This has to be replaced by a decent fit the QE-spectrum!
+//
+void MCalibrationQEPix::AddAverageBlindPixelQEs(const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw )
+{
+
+  if (IsBlindPixelMethodValid (col))
+  {
+    const Float_t newavqe    =   GetQEBlindPixel      (col) / GetDefaultQE      (col) 
+                               / GetLightGuidesEff    (col) / GetPMTCollectionEff(); 
+    const Float_t newavqevar = ( GetQEBlindPixelRelVar(col) + GetDefaultQERelVar(col) 
+                               + GetLightGuidesEffRelVar(col) + GetPMTCollectionEffRelVar()  ) 
+                               * newavqe * newavqe;
+    const Float_t weight     = 1./newavqevar;
+
+    wav  += newavqe * weight;
+    sumw += weight;
+  }
+}
+
+
+// ----------------------------------------------------------------------------------------------
+// 
+// Search all available QE's of a certain colour after the F-Factor method, 
+// compare them to the default QE of that colour and 
+// add up a weighted average (wav) and a sum of weights (sumw)
+//
+// FIXME: This has to be replaced by a decent fit the QE-spectrum!
+//
+void MCalibrationQEPix::AddAverageFFactorQEs(const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw )
+{
+
+  if (IsFFactorMethodValid (col))
+  {
+    const Float_t newavqe    =   GetQEFFactor(col)       / GetDefaultQE (col) 
+                               / GetLightGuidesEff    (col) / GetPMTCollectionEff(); 
+    const Float_t newavqevar = ( GetQEFFactorRelVar(col) + GetDefaultQERelVar(col) 
+                               + GetLightGuidesEffRelVar(col) + GetPMTCollectionEffRelVar()  ) 
+                               * newavqe * newavqe;
+    const Float_t weight     = 1./newavqevar;
+
+    wav  += newavqe *weight;
+    sumw += weight;
+
+  }
+
+
+}
+
+// ----------------------------------------------------------------------------------------------
+// 
+// Search all available QE's of a certain colour after the PIN Diode method, 
+// compare them to the default QE of that colour and 
+// add up a weighted average (wav) and a sum of weights (sumw)
+//
+// FIXME: This has to be replaced by a decent fit the QE-spectrum!
+//
+void MCalibrationQEPix::AddAveragePINDiodeQEs(const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw )
+{
+
+  if (IsPINDiodeMethodValid (col))
+  {
+    const Float_t newavqe    =   GetQEPINDiode(col)       / GetDefaultQE (col) 
+                               / GetLightGuidesEff    (col) / GetPMTCollectionEff(); 
+    const Float_t newavqevar = ( GetQEPINDiodeRelVar(col) + GetDefaultQERelVar(col) 
+                               + GetLightGuidesEffRelVar(col) + GetPMTCollectionEffRelVar()  ) 
+                               * newavqe * newavqe;
+    const Float_t weight     = 1./newavqevar;
+    wav  += newavqe *weight;
+    sumw += weight;
+  }
+}
+
+
+
+// ------------------------------------------------------------------------
+//
+// Sets all quantum efficiencies to the gkDefaultQE*
+// Sets all Variances to the square root of gkDefaultQE*Err
+// Sets all flags to kFALSE
+// Sets all fAvNorm-Variables to 1.;
+// Sets all fAvNorm-Variances to 0.;
+// 
+// Calls:
+// - MCalibrationPix::Clear()
+//
+void MCalibrationQEPix::Clear(Option_t *o)
+{
+
+  SetAverageQEBlindPixelAvailable ( kFALSE );
+  SetAverageQEFFactorAvailable    ( kFALSE );
+  SetAverageQECombinedAvailable   ( kFALSE );
+  SetAverageQEPINDiodeAvailable   ( kFALSE );
+
+  fQEBlindPixel    [ MCalibrationCam::kGREEN ] = gkDefaultQEGreen;  
+  fQEBlindPixelVar [ MCalibrationCam::kGREEN ] = gkDefaultQEGreenErr*gkDefaultQEGreenErr;
+  fQEFFactor       [ MCalibrationCam::kGREEN ] = gkDefaultQEGreen;     
+  fQEFFactorVar    [ MCalibrationCam::kGREEN ] = gkDefaultQEGreenErr*gkDefaultQEGreenErr;
+  fQECombined      [ MCalibrationCam::kGREEN ] = gkDefaultQEGreen;    
+  fQECombinedVar   [ MCalibrationCam::kGREEN ] = gkDefaultQEGreenErr*gkDefaultQEGreenErr; 
+  fQEPINDiode      [ MCalibrationCam::kGREEN ] = gkDefaultQEGreen;    
+  fQEPINDiodeVar   [ MCalibrationCam::kGREEN ] = gkDefaultQEGreenErr*gkDefaultQEGreenErr; 
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kGREEN);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kGREEN);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kGREEN);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kGREEN);
+
+  fQEBlindPixel    [ MCalibrationCam::kBLUE ] = gkDefaultQEBlue;  
+  fQEBlindPixelVar [ MCalibrationCam::kBLUE ] = gkDefaultQEBlueErr*gkDefaultQEBlueErr;
+  fQEFFactor       [ MCalibrationCam::kBLUE ] = gkDefaultQEBlue;     
+  fQEFFactorVar    [ MCalibrationCam::kBLUE ] = gkDefaultQEBlueErr*gkDefaultQEBlueErr;
+  fQECombined      [ MCalibrationCam::kBLUE ] = gkDefaultQEBlue;    
+  fQECombinedVar   [ MCalibrationCam::kBLUE ] = gkDefaultQEBlueErr*gkDefaultQEBlueErr; 
+  fQEPINDiode      [ MCalibrationCam::kBLUE ] = gkDefaultQEBlue;    
+  fQEPINDiodeVar   [ MCalibrationCam::kBLUE ] = gkDefaultQEBlueErr*gkDefaultQEBlueErr; 
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kBLUE);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kBLUE);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kBLUE);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kBLUE);
+
+  fQEBlindPixel    [ MCalibrationCam::kUV ] = gkDefaultQEUV;  
+  fQEBlindPixelVar [ MCalibrationCam::kUV ] = gkDefaultQEUVErr*gkDefaultQEUVErr;
+  fQEFFactor       [ MCalibrationCam::kUV ] = gkDefaultQEUV;     
+  fQEFFactorVar    [ MCalibrationCam::kUV ] = gkDefaultQEUVErr*gkDefaultQEUVErr;
+  fQECombined      [ MCalibrationCam::kUV ] = gkDefaultQEUV;    
+  fQECombinedVar   [ MCalibrationCam::kUV ] = gkDefaultQEUVErr*gkDefaultQEUVErr; 
+  fQEPINDiode      [ MCalibrationCam::kUV ] = gkDefaultQEUV;    
+  fQEPINDiodeVar   [ MCalibrationCam::kUV ] = gkDefaultQEUVErr*gkDefaultQEUVErr; 
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kUV);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kUV);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kUV);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kUV);
+
+  fQEBlindPixel    [ MCalibrationCam::kCT1 ] = gkDefaultQECT1;  
+  fQEBlindPixelVar [ MCalibrationCam::kCT1 ] = gkDefaultQECT1Err*gkDefaultQECT1Err;
+  fQEFFactor       [ MCalibrationCam::kCT1 ] = gkDefaultQECT1;     
+  fQEFFactorVar    [ MCalibrationCam::kCT1 ] = gkDefaultQECT1Err*gkDefaultQECT1Err;
+  fQECombined      [ MCalibrationCam::kCT1 ] = gkDefaultQECT1;    
+  fQECombinedVar   [ MCalibrationCam::kCT1 ] = gkDefaultQECT1Err*gkDefaultQECT1Err; 
+  fQEPINDiode      [ MCalibrationCam::kCT1 ] = gkDefaultQECT1;    
+  fQEPINDiodeVar   [ MCalibrationCam::kCT1 ] = gkDefaultQECT1Err*gkDefaultQECT1Err; 
+
+  SetBlindPixelMethodValid ( kFALSE, MCalibrationCam::kCT1);
+  SetFFactorMethodValid    ( kFALSE, MCalibrationCam::kCT1);
+  SetCombinedMethodValid   ( kFALSE, MCalibrationCam::kCT1);
+  SetPINDiodeMethodValid   ( kFALSE, MCalibrationCam::kCT1);
+
+  fAvNormBlindPixel     = -1.;     
+  fAvNormBlindPixelVar  = 0.;  
+  fAvNormCombined       = -1.;       
+  fAvNormCombinedVar    = 0.;    
+  fAvNormFFactor        = -1.;        
+  fAvNormFFactorVar     = 0.;     
+  fAvNormPINDiode       = -1.;       
+  fAvNormPINDiodeVar    = 0.;    
+
+  MCalibrationPix::Clear();
+}
+
+
+// -----------------------------------------------------------------
+//
+// Return the average Default QE (depending on zenith angle)
+// FIXME: The zenith angle dependency is not yet implemented
+//
+const Float_t MCalibrationQEPix::GetAverageQE( const Float_t zenith ) const 
+{
+  //  return gkDefaultAverageQE ;
+  return fAverageQE; 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the average Default QE (depending on zenith angle)
+// FIXME: The zenith angle dependency is not yet implemented
+//
+const Float_t MCalibrationQEPix::GetAverageQERelVar( const Float_t zenith ) const 
+{
+  return gkDefaultAverageQEErr * gkDefaultAverageQEErr / (gkDefaultAverageQE * gkDefaultAverageQE ); 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the average normalization (Blind Pixel Method)
+// FIXME: The zenith angle dependency is not yet implemented
+//
+const Float_t MCalibrationQEPix::GetAvNormBlindPixelRelVar( ) const 
+{
+  return fAvNormBlindPixelVar / (fAvNormBlindPixel * fAvNormBlindPixel ); 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the average normalization (Combined Method)
+// FIXME: The zenith angle dependency is not yet implemented
+//
+const Float_t MCalibrationQEPix::GetAvNormCombinedRelVar( ) const 
+{
+  return fAvNormCombinedVar / (fAvNormCombined * fAvNormCombined ); 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the average normalization (F-Factor Method)
+//
+const Float_t MCalibrationQEPix::GetAvNormFFactorRelVar( ) const 
+{
+  return fAvNormFFactorVar / (fAvNormFFactor * fAvNormFFactor ); 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the average normalization (PIN Diode Method)
+// FIXME: The zenith angle dependency is not yet implemented
+//
+const Float_t MCalibrationQEPix::GetAvNormPINDiodeRelVar( ) const 
+{
+  return fAvNormPINDiodeVar / (fAvNormPINDiode * fAvNormPINDiode ); 
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the default Quantum efficiency for pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetDefaultQE( const MCalibrationCam::PulserColor_t col )  const
+{
+  switch (col)
+    {
+    case MCalibrationCam::kGREEN:
+      return gkDefaultQEGreen;
+      break;
+    case MCalibrationCam::kBLUE:
+      return gkDefaultQEBlue;
+      break;
+    case MCalibrationCam::kUV:
+      return gkDefaultQEUV;
+      break;
+    case MCalibrationCam::kCT1:
+      return gkDefaultQECT1;
+      break;
+    default:
+      return gkDefaultQECT1;
+      break;
+    }
+  return -1.;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the relative variance of the default Quantum efficiency for pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetDefaultQERelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  switch (col)
+    {
+    case MCalibrationCam::kGREEN:
+      return gkDefaultQEGreenErr * gkDefaultQEGreenErr / (gkDefaultQEGreen * gkDefaultQEGreen );
+      break;
+    case MCalibrationCam::kBLUE:
+      return gkDefaultQEBlueErr  * gkDefaultQEBlueErr  / (gkDefaultQEBlue  * gkDefaultQEBlue  );
+      break;
+    case MCalibrationCam::kUV:
+      return gkDefaultQEUVErr    * gkDefaultQEUVErr    / (gkDefaultQEUV    * gkDefaultQEUV    );
+      break;
+    case MCalibrationCam::kCT1:
+      return gkDefaultQECT1Err   * gkDefaultQECT1Err   / (gkDefaultQECT1   * gkDefaultQECT1   );
+      break;
+    default: 
+      return gkDefaultQECT1Err   * gkDefaultQECT1Err   / (gkDefaultQECT1   * gkDefaultQECT1   );
+      break;
+    }
+  return -1.;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the light guides efficiency depending on the pulser colour "col"
+// FIXME: Lacking detailed measurement, these number are not yet available 
+//        for the individual colours and therefore, only one same number is 
+//        returned, namely gkLightGuidesEff
+//
+Float_t MCalibrationQEPix::GetLightGuidesEff( const MCalibrationCam::PulserColor_t col )  const
+{
+  switch (col)
+    {
+    case MCalibrationCam::kGREEN:
+      return gkLightGuidesEffGreen;
+      break;
+    case MCalibrationCam::kBLUE:
+      return gkLightGuidesEffBlue;
+      break;
+    case MCalibrationCam::kUV:
+      return gkLightGuidesEffUV;
+      break;
+    case MCalibrationCam::kCT1:
+      return gkLightGuidesEffCT1;
+      break;
+    default:
+      return gkLightGuidesEffCT1;
+      break;
+    }
+  return -1.;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the relative variance of the light guides efficiency depending on the 
+// pulser colour "col"
+// FIXME: Lacking detailed measurement, these number are not yet available 
+//        for the individual colours and therefore, only one same number is 
+//        returned, namely gkLightGuidesEffErr^2 / gkLightGuidesEff^2
+//
+Float_t MCalibrationQEPix::GetLightGuidesEffRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  switch (col)
+    {
+    case MCalibrationCam::kGREEN:
+      return gkLightGuidesEffGreenErr * gkLightGuidesEffGreenErr / gkLightGuidesEffGreen / gkLightGuidesEffGreen;
+      break;
+    case MCalibrationCam::kBLUE:
+      return gkLightGuidesEffBlueErr  * gkLightGuidesEffBlueErr / gkLightGuidesEffBlue / gkLightGuidesEffBlue;
+      break;
+    case MCalibrationCam::kUV:
+      return gkLightGuidesEffUVErr  * gkLightGuidesEffUVErr / gkLightGuidesEffUV / gkLightGuidesEffUV;
+      break;
+    case MCalibrationCam::kCT1:
+      return gkLightGuidesEffCT1Err * gkLightGuidesEffCT1Err / gkLightGuidesEffCT1 / gkLightGuidesEffCT1;
+      break;
+    default: 
+      return gkLightGuidesEffCT1Err * gkLightGuidesEffCT1Err / gkLightGuidesEffCT1 / gkLightGuidesEffCT1;
+      break;
+    }
+  return -1.;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the light guides efficiency for Cherenkov spectra, 
+// depending on the zenith angle of the telescope
+// FIXME: Lacking detailed measurement, these number are not yet available 
+//        for the individual colours and therefore, only one same number is 
+//        returned, namely gkLightGuidesEffBlue
+//
+Float_t MCalibrationQEPix::GetLightGuidesEff( const Float_t zenith )  const
+{
+  return gkLightGuidesEffBlue;
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the relative variance of the light guides efficiency for Cherenkov spectra 
+// depending on the zenith angle of the telescope 
+// FIXME: Lacking detailed measurement, these number are not yet available 
+//        for the individual colours and therefore, only one same number is 
+//        returned, namely gkLightGuidesEffBlueErr^2 / gkLightGuidesBlueEff^2
+//
+Float_t MCalibrationQEPix::GetLightGuidesEffRelVar( const Float_t zenith )  const
+{
+  return gkLightGuidesEffBlueErr  * gkLightGuidesEffBlueErr / gkLightGuidesEffBlue / gkLightGuidesEffBlue;
+}
+
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the calculated Quantum efficiency with the blind pixel method, 
+// obtained with pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetQEBlindPixel( const MCalibrationCam::PulserColor_t col )  const
+{
+  return fQEBlindPixel[col];
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the calculated Quantum efficiency with the blind pixel method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEBlindPixelErr( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEBlindPixelVar[col] < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fQEBlindPixelVar[col]);
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the relative variance of the calculated Quantum efficiency with the blind pixel method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+// Tests for quantum efficiency equal to  0. and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEBlindPixelRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEBlindPixelVar[col] < 0.)
+    return -1.;
+  if (fQEBlindPixel[col] < 0.)
+      return -1.;
+  return fQEBlindPixelVar[col] / ( fQEBlindPixel[col] * fQEBlindPixel[col] );
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the calculated Quantum efficiency with the combination of the three methods
+// obtained with pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetQECombined( const MCalibrationCam::PulserColor_t col )  const
+{
+  return fQECombined[col];
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the calculated Quantum efficiency with the combination of the three methods
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQECombinedErr( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQECombinedVar[col] < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fQECombinedVar[col]);
+
+}
+
+
+// ----------------------------------------------------------------------------------------
+//
+// Get the relative variance of the calculated Quantum efficiency with the combination of 
+// the three methods, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+// Tests for quantum efficiency equal to  0. and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQECombinedRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQECombinedVar[col] < 0.)
+    return -1.;
+  if (fQECombined[col] < 0.)
+      return -1.;
+  return fQECombinedVar[col] / ( fQECombined[col] * fQECombined[col] );
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the calculated Quantum efficiency with the F-Factor method
+// obtained with pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetQEFFactor( const MCalibrationCam::PulserColor_t col )  const
+{
+  return fQEFFactor[col];
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the calculated Quantum efficiency with the F-Factor method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEFFactorErr( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEFFactorVar[col] < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fQEFFactorVar[col]);
+
+}
+
+
+// ----------------------------------------------------------------------------------------
+//
+// Get the relative variance of the calculated Quantum efficiency with the F-Factor method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+// Tests for quantum efficiency equal to  0. and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEFFactorRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEFFactorVar[col] < 0.)
+    return -1.;
+  if (fQEFFactor[col] < 0.)
+      return -1.;
+  return fQEFFactorVar[col] / ( fQEFFactor[col] * fQEFFactor[col] );
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the calculated Quantum efficiency with the PIN-Diode method
+// obtained with pulser colour "col"
+//
+Float_t MCalibrationQEPix::GetQEPINDiode( const MCalibrationCam::PulserColor_t col )  const
+{
+  return fQEPINDiode[col];
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the calculated Quantum efficiency with the PIN Diode method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEPINDiodeErr( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEPINDiodeVar[col] < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fQEPINDiodeVar[col]);
+
+}
+
+// ----------------------------------------------------------------------------------------
+//
+// Get the relative variance of the calculated Quantum efficiency with the PIN Diode method, 
+// obtained with pulser colour "col"
+// Tests for variances smaller than 0. (e.g. if it has not yet been set) 
+// and returns -1. in that case
+// Tests for quantum efficiency equal to  0. and returns -1. in that case
+//
+Float_t MCalibrationQEPix::GetQEPINDiodeRelVar( const MCalibrationCam::PulserColor_t col )  const
+{
+
+  if (fQEPINDiodeVar[col] < 0.)
+    return -1.;
+  if (fQEPINDiode[col] < 0.)
+      return -1.;
+  return fQEPINDiodeVar[col] / ( fQEPINDiode[col] * fQEPINDiode[col] );
+
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the averaged Quantum efficiency folded over the cascade spectrum, obtained 
+// with the blind pixel method and averaged over the results from the different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesBlindPixel( const Float_t zenith  )  const
+{
+  return fAvNormBlindPixel * GetAverageQE ( zenith );
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the variance of the averaged Quantum efficiency folded over the cascade spectrum, 
+// obtained with the blind pixel method and averaged over the results from the 
+// different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesBlindPixelVar( const Float_t zenith  )  const
+{
+  return ( GetAvNormBlindPixelRelVar()  + GetAverageQERelVar(zenith)) 
+    * GetQECascadesBlindPixel(zenith) * GetQECascadesBlindPixel(zenith);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the averaged Quantum efficiency folded over the cascade spectrum, 
+// obtained with the blind pixel method and averaged over the results from the 
+// different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesBlindPixelErr( const Float_t zenith  )  const
+{
+  const Float_t var = GetQECascadesBlindPixelVar(zenith);
+  
+  if (var < 0.)
+    return -1.;
+
+  return TMath::Sqrt(var);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the averaged Quantum efficiency folded over the cascade spectrum, obtained 
+// with the combination of the three methods and averaged over the results 
+// from the different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesCombined( const Float_t zenith  )  const
+{
+  return fAvNormCombined * GetAverageQE ( zenith );
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the averaged Quantum efficiency folded over the cascade spectrum, 
+// obtained with the combined method and averaged over the results from the 
+// different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesCombinedErr( const Float_t zenith  )  const
+{
+  const Float_t var = GetQECascadesCombinedVar(zenith);
+  
+  if (var < 0.)
+    return -1.;
+
+  return TMath::Sqrt(var);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the variance of the averaged Quantum efficiency folded over the cascade spectrum, 
+// obtained with the combination of the three methods and averaged over the results from the 
+// different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesCombinedVar( const Float_t zenith  )  const
+{
+  return ( GetAvNormCombinedRelVar()  + GetAverageQERelVar(zenith)) 
+    * GetQECascadesCombined(zenith) * GetQECascadesCombined(zenith);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the averaged Quantum efficiency folded over the cascade spectrum, obtained 
+// with the F-Factor method and averaged over the results from the different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesFFactor( const Float_t zenith  )  const
+{
+  return fAvNormFFactor * GetAverageQE ( zenith );
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the averaged Quantum efficiency folded over the cascade spectrum, 
+// obtained with the F-Factor method and averaged over the results from the 
+// different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesFFactorErr( const Float_t zenith  )  const
+{
+  const Float_t var = GetQECascadesFFactorVar(zenith);
+  
+  if (var < 0.)
+    return -1.;
+
+  return TMath::Sqrt(var);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the variance of the averaged Quantum efficiency folded over the cascade spectrum, 
+// obtained with the F-Factor method and averaged over the results from the 
+// different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesFFactorVar( const Float_t zenith  )  const
+{
+  return ( GetAvNormFFactorRelVar()  + GetAverageQERelVar(zenith)) 
+    * GetQECascadesFFactor(zenith) * GetQECascadesFFactor(zenith);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the averaged Quantum efficiency folded over the cascade spectrum, obtained 
+// with the PIN Diode method and averaged over the results from the different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesPINDiode( const Float_t zenith  )  const
+{
+  return fAvNormPINDiode * GetAverageQE ( zenith );
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the error on the averaged Quantum efficiency folded over the cascade spectrum, 
+// obtained with the PIN Diode method and averaged over the results from the 
+// different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesPINDiodeErr( const Float_t zenith  )  const
+{
+  const Float_t var = GetQECascadesPINDiodeVar(zenith);
+  
+  if (var < 0.)
+    return -1.;
+
+  return TMath::Sqrt(var);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Get the variance of the averaged Quantum efficiency folded over the cascade spectrum, 
+// obtained with the PIN Diode method and averaged over the results from the 
+// different colours.
+//
+Float_t MCalibrationQEPix::GetQECascadesPINDiodeVar( const Float_t zenith  )  const
+{
+  return ( GetAvNormPINDiodeRelVar()  + GetAverageQERelVar(zenith)) 
+    * GetQECascadesPINDiode(zenith) * GetQECascadesPINDiode(zenith);
+}
+
+// -----------------------------------------------------------------
+//
+// Return the overall collection efficiency of the PMT
+//
+Float_t MCalibrationQEPix::GetPMTCollectionEff() const 
+{
+  return gkPMTCollectionEff; 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the collection efficiency of the PMT
+//
+Float_t MCalibrationQEPix::GetPMTCollectionEffRelVar() const 
+{
+  return gkPMTCollectionEffErr * gkPMTCollectionEffErr / gkPMTCollectionEff / gkPMTCollectionEff; 
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the average QE can be obtained from the blind pixel method
+//
+Bool_t MCalibrationQEPix::IsAverageQEBlindPixelAvailable() const
+{
+  return TESTBIT(fAvailableFlags,kAverageQEBlindPixelAvailable);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the average QE can be obtained from the combination of the three methods
+//
+Bool_t MCalibrationQEPix::IsAverageQECombinedAvailable() const
+{
+  return TESTBIT(fAvailableFlags,kAverageQECombinedAvailable);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the average QE can be obtained from the F-Factor method
+//
+Bool_t MCalibrationQEPix::IsAverageQEFFactorAvailable() const
+{
+  return TESTBIT(fAvailableFlags,kAverageQEFFactorAvailable);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the average QE can be obtained from the PIN Diode method
+//
+Bool_t MCalibrationQEPix::IsAverageQEPINDiodeAvailable() const
+{
+  return TESTBIT(fAvailableFlags,kAverageQEPINDiodeAvailable);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if any of the three colours has already been calibrated with the blind pixel method
+//
+Bool_t MCalibrationQEPix::IsBlindPixelMethodValid () const
+{
+
+  if (IsBlindPixelMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsBlindPixelMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if any of the three colours has already been calibrated with the combination 
+// of the three methods
+//
+Bool_t MCalibrationQEPix::IsCombinedMethodValid () const
+{
+  if (IsCombinedMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsCombinedMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if any of the three colours has already been calibrated with the F-Factor method
+//
+Bool_t MCalibrationQEPix::IsFFactorMethodValid () const
+{
+  if (IsFFactorMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsFFactorMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+
+// ------------------------------------------------------------------------------
+//
+// Test if any of the three colours has already been calibrated with the PIN Diode method
+//
+Bool_t MCalibrationQEPix::IsPINDiodeMethodValid () const
+{
+  if (IsPINDiodeMethodValid (MCalibrationCam::kGREEN))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kBLUE ))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kUV   ))
+    return kTRUE;
+  if (IsPINDiodeMethodValid (MCalibrationCam::kCT1  ))
+    return kTRUE;
+
+  return kFALSE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the colour "col" has already been calibrated with the Blind Pixel method
+//
+Bool_t MCalibrationQEPix::IsBlindPixelMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fValidFlags[ col ],kBlindPixelMethodValid);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the colour "col" has already been calibrated with the combination of 
+// the three methods
+//
+Bool_t MCalibrationQEPix::IsCombinedMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fValidFlags[ col ],kCombinedMethodValid);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the colour "col" has already been calibrated with the F-Factor method
+//
+Bool_t MCalibrationQEPix::IsFFactorMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fValidFlags[ col ],kFFactorMethodValid);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Test if the colour "col" has already been calibrated with the PIN Diode method
+//
+Bool_t MCalibrationQEPix::IsPINDiodeMethodValid (MCalibrationCam::PulserColor_t col)  const
+{
+  return TESTBIT(fValidFlags[ col ],kPINDiodeMethodValid);
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit Average QE Blind Pixel method available from outside (only for MC!)
+//
+void MCalibrationQEPix::SetAverageQEBlindPixelAvailable ( Bool_t b ) 
+{
+  if (b) 
+    SETBIT(fAvailableFlags,kAverageQEBlindPixelAvailable);
+  else
+    CLRBIT(fAvailableFlags,kAverageQEBlindPixelAvailable);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit Average QE combination of three methods available from outside (only for MC!)
+//
+void MCalibrationQEPix::SetAverageQECombinedAvailable ( Bool_t b ) 
+{
+  if (b) 
+    SETBIT(fAvailableFlags,kAverageQECombinedAvailable);
+  else
+    CLRBIT(fAvailableFlags,kAverageQECombinedAvailable);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit Average QE F-Factor method available from outside (only for MC!)
+//
+void MCalibrationQEPix::SetAverageQEFFactorAvailable ( Bool_t b ) 
+{
+  if (b) 
+    SETBIT(fAvailableFlags,kAverageQEFFactorAvailable);
+  else
+    CLRBIT(fAvailableFlags,kAverageQEFFactorAvailable);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit Average QE PIN Diode method available from outside (only for MC!)
+//
+void MCalibrationQEPix::SetAverageQEPINDiodeAvailable ( Bool_t b ) 
+{
+  if (b) 
+    SETBIT(fAvailableFlags,kAverageQEPINDiodeAvailable);
+  else
+    CLRBIT(fAvailableFlags,kAverageQEPINDiodeAvailable);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit QE Blind Pixel method available from colour "col"
+//
+void MCalibrationQEPix::SetBlindPixelMethodValid ( Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fValidFlags[ col ],kBlindPixelMethodValid);
+  else
+    CLRBIT(fValidFlags[ col ],kBlindPixelMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit QE Combination of three methods available from colour "col"
+//
+void MCalibrationQEPix::SetCombinedMethodValid ( Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fValidFlags[ col ],kCombinedMethodValid);
+  else
+    CLRBIT(fValidFlags[ col ],kCombinedMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit QE F-Factor method available from colour "col"
+//
+void MCalibrationQEPix::SetFFactorMethodValid ( Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fValidFlags[ col ],kFFactorMethodValid);
+  else
+    CLRBIT(fValidFlags[ col ],kFFactorMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Set the bit QE PIN Diode method available from colour "col"
+//
+void MCalibrationQEPix::SetPINDiodeMethodValid ( Bool_t b,  MCalibrationCam::PulserColor_t col ) 
+{
+  if (b) 
+    SETBIT(fValidFlags[ col ],kPINDiodeMethodValid);
+  else
+    CLRBIT(fValidFlags[ col ],kPINDiodeMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the Blind Pixel Method: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateBlindPixelMethod( const Float_t plex )
+{
+
+  Float_t weightedav = 0.;
+  Float_t sumweights = 0.;
+
+  AddAverageBlindPixelQEs(MCalibrationCam::kGREEN, weightedav, sumweights);
+  AddAverageBlindPixelQEs(MCalibrationCam::kBLUE , weightedav, sumweights);
+  AddAverageBlindPixelQEs(MCalibrationCam::kUV   , weightedav, sumweights);
+  AddAverageBlindPixelQEs(MCalibrationCam::kCT1  , weightedav, sumweights);
+
+  if (weightedav == 0. || sumweights == 0.)
+    return kFALSE;
+
+  fAvNormBlindPixel     = weightedav / plex / sumweights;
+  fAvNormBlindPixelVar  = 1./ sumweights;
+
+  SetAverageQEBlindPixelAvailable();
+
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the Combination of the three Methods: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateCombinedMethod()
+{
+  
+  fAvNormCombinedVar = 0.;
+  fAvNormCombined    = 0.;
+  
+  if (fAvNormBlindPixel > 0. && fAvNormBlindPixelVar > 0.)
+    {
+      const Float_t weight = 1./fAvNormBlindPixelVar;
+      fAvNormCombinedVar  += weight;
+      fAvNormCombined     += fAvNormBlindPixel*weight;
+    }
+  
+  if (fAvNormFFactor    > 0. && fAvNormFFactorVar > 0. )
+    {
+      const Float_t weight = 1./fAvNormFFactorVar;
+      fAvNormCombinedVar  += weight;
+      fAvNormCombined     += fAvNormFFactor*weight;
+    }
+  
+  if (fAvNormPINDiode > 0. && fAvNormPINDiodeVar > 0. )
+    {
+      const Float_t weight = 1./fAvNormPINDiodeVar;
+      fAvNormCombinedVar  += weight;
+      fAvNormCombined     += fAvNormPINDiode*weight;
+    }
+  
+  fAvNormCombined = ( fAvNormCombinedVar > 0.) ? -1. : fAvNormCombined/fAvNormCombinedVar ;
+  
+  if (fAvNormCombined > 0.)
+    SetAverageQECombinedAvailable();
+
+  return kTRUE;
+  
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the F-Factor Method: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateFFactorMethod( const Float_t plex )
+{
+
+  Float_t weightedav = 0.;
+  Float_t sumweights = 0.;
+
+  AddAverageFFactorQEs(MCalibrationCam::kGREEN, weightedav, sumweights);
+  AddAverageFFactorQEs(MCalibrationCam::kBLUE , weightedav, sumweights);
+  AddAverageFFactorQEs(MCalibrationCam::kUV   , weightedav, sumweights);
+  AddAverageFFactorQEs(MCalibrationCam::kCT1  , weightedav, sumweights);
+ 
+  if (weightedav == 0. || sumweights == 0.)
+    return kFALSE;
+
+  fAvNormFFactor     = weightedav / plex / sumweights;
+  fAvNormFFactorVar  = 1./ sumweights;
+  
+  SetAverageQEFFactorAvailable();
+
+  return kTRUE;
+  
+  
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the PIN Diode Method: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdatePINDiodeMethod()
+{
+  
+  Float_t weightedav = 0.;
+  Float_t sumweights = 0.;
+
+  AddAveragePINDiodeQEs(MCalibrationCam::kGREEN, weightedav, sumweights);
+  AddAveragePINDiodeQEs(MCalibrationCam::kBLUE , weightedav, sumweights);
+  AddAveragePINDiodeQEs(MCalibrationCam::kUV   , weightedav, sumweights);
+  AddAveragePINDiodeQEs(MCalibrationCam::kCT1  , weightedav, sumweights);
+
+  if (weightedav == 0. || sumweights == 0.)
+    return kFALSE;
+
+  fAvNormPINDiode     = weightedav / sumweights;
+  fAvNormPINDiodeVar  = 1./ sumweights ;
+
+  SetAverageQEPINDiodeAvailable();
+
+  return kTRUE;
+
+  
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationQEPix.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationQEPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationQEPix.h	(revision 9772)
@@ -0,0 +1,177 @@
+#ifndef MARS_MCalibrationQEPix
+#define MARS_MCalibrationQEPix
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationQEPix : public MCalibrationPix
+{
+private:
+
+  static const Float_t gkDefaultQEGreen;      //! Default QE at 520 nm (now set to: 0.192)
+  static const Float_t gkDefaultQEBlue;       //! Default QE at 460 nm (now set to: 0.27 )
+  static const Float_t gkDefaultQEUV;         //! Default QE at 370 nm (now set to: 0.285)
+  static const Float_t gkDefaultQECT1;        //! Default QE at 370 nm (now set to: 0.285)
+  static const Float_t gkDefaultQEGreenErr;   //! Uncertainty Def. QE  at 520 nm (now set to: 0.05)
+  static const Float_t gkDefaultQEBlueErr;    //! Uncertainty Def. QE  at 460 nm (now set to: 0.07)
+  static const Float_t gkDefaultQEUVErr;      //! Uncertainty Def. QE  at 370 nm (now set to: 0.07)
+  static const Float_t gkDefaultQECT1Err;     //! Uncertainty Def. QE  at 370 nm (now set to: 0.07)
+  static const Float_t gkLightGuidesEffGreen;    //! Default Light guides efficiency at 520 nm
+  static const Float_t gkLightGuidesEffGreenErr; //! Uncertainty Def. Light guides efficiency at 520 nm
+  static const Float_t gkLightGuidesEffBlue;     //! Default Light guides efficiency at 460 nm
+  static const Float_t gkLightGuidesEffBlueErr;  //! Uncertainty Def. Light guides efficiency at 460 nm
+  static const Float_t gkLightGuidesEffUV;       //! Default Light guides efficiency at 370 nm
+  static const Float_t gkLightGuidesEffUVErr;    //! Uncertainty Def. Light guides efficiency at 370 nm
+  static const Float_t gkLightGuidesEffCT1;      //! Default Light guides efficiency at 370 nm
+  static const Float_t gkLightGuidesEffCT1Err;   //! Uncertainty Def. Light guides efficiency at 370 nm
+  static const Float_t gkPMTCollectionEff;    //! Default Collection efficiency of the PMTs
+  static const Float_t gkPMTCollectionEffErr; //! Uncertainty Def. Collection efficiency of the PMTs (0.01)
+  
+  MArrayF fQEBlindPixel;                     // Calibrated QEs    (Blind Pixel Method)
+  MArrayF fQEBlindPixelVar;                  // Variance cal. QEs (Blind Pixel Method)
+  MArrayF fQECombined;                       // Calibrated QEs    (Combined Method)
+  MArrayF fQECombinedVar;                    // Variance cal. QEs (Combined Method)
+  MArrayF fQEFFactor;                        // Calibrated QEs    (F-Factor Method)
+  MArrayF fQEFFactorVar;                     // Variance cal. QEs (F-Factor Method)
+  MArrayF fQEPINDiode;                       // Calibrated QEs    (PIN Diode Method)
+  MArrayF fQEPINDiodeVar;                    // Variance cal. QEs (PIN Diode Method)
+                                             
+  Float_t fAvNormBlindPixel;                 // Normalization w.r.t. default QE (Blind Pixel Method)
+  Float_t fAvNormBlindPixelVar;              // Variance norm. w.r.t. def. QE (Blind Pixel Method)
+  Float_t fAvNormCombined;                   // Normalization w.r.t. default QE (Combined Method)
+  Float_t fAvNormCombinedVar;                // Variance norm. w.r.t. def. QE (Combined Method)
+  Float_t fAvNormFFactor;                    // Normalization w.r.t. default QE (F-Factor Method)
+  Float_t fAvNormFFactorVar;                 // Variance norm. w.r.t. def. QE (F-Factor Method)
+  Float_t fAvNormPINDiode;                   // Normalization w.r.t. default QE (PIN Diode Method)
+  Float_t fAvNormPINDiodeVar;                // Variance norm. w.r.t. def. QE (PIN Diode Method)
+  Float_t fAverageQE;                        // Average QE for Cascade spectrum (default 0.18)
+
+  TArrayC fValidFlags;                       // Bit-field for valid flags, one array entry for each color
+  Byte_t  fAvailableFlags;                   // Bit-field for available flags
+  
+  enum { kBlindPixelMethodValid, kFFactorMethodValid, 
+	 kPINDiodeMethodValid, kCombinedMethodValid,
+         kAverageQEBlindPixelAvailable, kAverageQEFFactorAvailable,
+         kAverageQEPINDiodeAvailable, kAverageQECombinedAvailable  };
+
+  void  AddAverageBlindPixelQEs( const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw );
+  void  AddAverageFFactorQEs  ( const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw );
+  void  AddAveragePINDiodeQEs  ( const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw );
+
+  const Float_t GetAvNormBlindPixelRelVar()  const;
+  const Float_t GetAvNormCombinedRelVar()  const;
+  const Float_t GetAvNormFFactorRelVar()  const;
+  const Float_t GetAvNormPINDiodeRelVar()  const;  
+
+public:
+
+  static const Float_t gkDefaultAverageQE;    //! Default QE folded into Cascade spectrum (now set to: 0.18)
+  static const Float_t gkDefaultAverageQEErr; //! Uncertainty Def. QE Cascade spectrum    (now set to: 0.02)
+
+  MCalibrationQEPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationQEPix() {}
+  
+  void Clear(Option_t *o="");
+  void Copy (TObject& object) const;  
+
+  // Getters
+  const Float_t GetAverageQE     ( const Float_t zenith=0. ) const;  
+  const Float_t GetAverageQERelVar( const Float_t zenith=0. ) const;
+  
+  Float_t GetDefaultQE                   ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetDefaultQERelVar             ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetLightGuidesEff              ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetLightGuidesEffRelVar        ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetLightGuidesEff              ( const Float_t zenith=0.)                   const;
+  Float_t GetLightGuidesEffRelVar        ( const Float_t zenith=0.)                   const;
+  Float_t GetQEBlindPixel                ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetQEBlindPixelErr             ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetQEBlindPixelRelVar          ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetQECascadesBlindPixel        ( const Float_t zenith=0.)                   const;
+  Float_t GetQECascadesBlindPixelErr     ( const Float_t zenith=0.)                   const;
+  Float_t GetQECascadesBlindPixelVar     ( const Float_t zenith=0.)                   const;
+  Float_t GetQECascadesCombined          ( const Float_t zenith=0.)                   const;  
+  Float_t GetQECascadesCombinedErr       ( const Float_t zenith=0.)                   const;
+  Float_t GetQECascadesCombinedVar       ( const Float_t zenith=0.)                   const;    
+  Float_t GetQECascadesFFactor           ( const Float_t zenith=0.)                   const;  
+  Float_t GetQECascadesFFactorErr        ( const Float_t zenith=0 )                   const;
+  Float_t GetQECascadesFFactorVar        ( const Float_t zenith=0 )                   const;    
+  Float_t GetQECascadesPINDiode          ( const Float_t zenith=0.)                   const;
+  Float_t GetQECascadesPINDiodeErr       ( const Float_t zenith=0.)                   const;
+  Float_t GetQECascadesPINDiodeVar       ( const Float_t zenith=0.)                   const;  
+  Float_t GetQECombined                  ( const MCalibrationCam::PulserColor_t col ) const;        
+  Float_t GetQECombinedErr               ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetQECombinedRelVar            ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetQEFFactor                   ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetQEFFactorErr                ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetQEFFactorRelVar             ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetQEPINDiode                  ( const MCalibrationCam::PulserColor_t col ) const;        
+  Float_t GetQEPINDiodeErr               ( const MCalibrationCam::PulserColor_t col ) const;
+  Float_t GetQEPINDiodeRelVar            ( const MCalibrationCam::PulserColor_t col ) const;  
+  Float_t GetPMTCollectionEff()                                                       const;
+  Float_t GetPMTCollectionEffRelVar()                                                 const;
+
+  Bool_t  IsAverageQEBlindPixelAvailable ()                                           const;
+  Bool_t  IsAverageQECombinedAvailable   ()                                           const;  
+  Bool_t  IsAverageQEFFactorAvailable    ()                                           const;  
+  Bool_t  IsAverageQEPINDiodeAvailable   ()                                           const;  
+  Bool_t  IsBlindPixelMethodValid        ()                                           const;
+  Bool_t  IsBlindPixelMethodValid        ( const MCalibrationCam::PulserColor_t col ) const;
+  Bool_t  IsCombinedMethodValid          ()                                           const;  
+  Bool_t  IsCombinedMethodValid          ( const MCalibrationCam::PulserColor_t col ) const;  
+  Bool_t  IsFFactorMethodValid           ()                                           const;  
+  Bool_t  IsFFactorMethodValid           ( const MCalibrationCam::PulserColor_t col ) const;  
+  Bool_t  IsPINDiodeMethodValid          ()                                           const;  
+  Bool_t  IsPINDiodeMethodValid          ( const MCalibrationCam::PulserColor_t col ) const;  
+
+  // Setters 
+  void SetAverageQE            ( const Float_t f )  { fAverageQE            = f; }
+  void SetAvNormBlindPixel     ( const Float_t f )  { fAvNormBlindPixel     = f; }      
+  void SetAvNormBlindPixelVar  ( const Float_t f )  { fAvNormBlindPixelVar  = f; }   
+  void SetAvNormCombined       ( const Float_t f )  { fAvNormCombined       = f; }        
+  void SetAvNormCombinedVar    ( const Float_t f )  { fAvNormCombinedVar    = f; }     
+  void SetAvNormFFactor        ( const Float_t f )  { fAvNormFFactor        = f; }         
+  void SetAvNormFFactorVar     ( const Float_t f )  { fAvNormFFactorVar     = f; }      
+  void SetAvNormPINDiode       ( const Float_t f )  { fAvNormPINDiode       = f; }        
+  void SetAvNormPINDiodeVar    ( const Float_t f )  { fAvNormPINDiodeVar    = f; }     
+  void SetAverageQEBlindPixelAvailable   ( const Bool_t b=kTRUE );
+  void SetAverageQECombinedAvailable     ( const Bool_t b=kTRUE );
+  void SetAverageQEFFactorAvailable      ( const Bool_t b=kTRUE );
+  void SetAverageQEPINDiodeAvailable     ( const Bool_t b=kTRUE );
+  void SetBlindPixelMethodValid          ( const Bool_t b, const MCalibrationCam::PulserColor_t col);
+  void SetCombinedMethodValid            ( const Bool_t b, const MCalibrationCam::PulserColor_t col);
+  void SetFFactorMethodValid             ( const Bool_t b, const MCalibrationCam::PulserColor_t col);  
+  void SetPINDiodeMethodValid            ( const Bool_t b, const MCalibrationCam::PulserColor_t col);  
+  void SetQEBlindPixel    ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEBlindPixel   [col] = f; }
+  void SetQEBlindPixelVar ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEBlindPixelVar[col] = f; }
+  void SetQECombined      ( Float_t f, MCalibrationCam::PulserColor_t col) { fQECombined     [col] = f; }
+  void SetQECombinedVar   ( Float_t f, MCalibrationCam::PulserColor_t col) { fQECombinedVar  [col] = f; }
+  void SetQEFFactor       ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEFFactor      [col] = f; }
+  void SetQEFFactorVar    ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEFFactorVar   [col] = f; }
+  void SetQEPINDiode      ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEPINDiode     [col] = f; }
+  void SetQEPINDiodeVar   ( Float_t f, MCalibrationCam::PulserColor_t col) { fQEPINDiodeVar  [col] = f; }
+
+  // Updates
+  Bool_t  UpdateBlindPixelMethod( const Float_t plex );
+  Bool_t  UpdateCombinedMethod  ();
+  Bool_t  UpdateFFactorMethod   ( const Float_t plex );
+  Bool_t  UpdatePINDiodeMethod  ();
+
+  ClassDef(MCalibrationQEPix, 3)     // Container Quantum Efficieny Calibration Results Pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCalc.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCalc.cc	(revision 9772)
@@ -0,0 +1,559 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationRelTimeCalc
+//
+//   Task to finalize the relative time calibration obtained 
+//   from the fit results to the summed FADC slice distributions delivered by 
+//   MCalibrationRelTimeCam, calculated and filled by MHCalibrationRelTimeCam, 
+//
+//   PreProcess(): Initialize pointers to MCalibrationRelTimeCam, 
+//               
+//   ReInit():     Initializes pointer to MBadPixelsCam
+//
+//   Process():    Nothing to be done, histograms getting filled by MHCalibrationChargeCam
+//
+//   PostProcess(): - FinalizeRelTimes()
+//                  - FinalizeBadPixels()
+//
+//  Input Containers:
+//   MCalibrationRelTimeCam
+//   MBadPixelsCam
+//   MGeomCam
+//
+//  Output Containers:
+//   MCalibrationRelTimeCam
+//   MBadPixelsCam
+//
+//  
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationRelTimeCalc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MStatusDisplay.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationIntensityRelTimeCam.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimePix.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+
+ClassImp(MCalibrationRelTimeCalc);
+
+using namespace std;
+
+const Float_t MCalibrationRelTimeCalc::fgRelTimeResolutionLimit = 1.0;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets all pointers to NULL
+// 
+// Initializes:
+// - fRelTimeResolutionLimit to fgRelTimeResolutionimit
+// - fOutputPath        to "."
+// - fOutputFile        to "TimeCalibStat.txt"
+//
+// Calls:
+// - Clear()
+//
+MCalibrationRelTimeCalc::MCalibrationRelTimeCalc(const char *name, const char *title)
+    : fGeom(NULL), fFlags(0)
+{
+        
+  fName  = name  ? name  : "MCalibrationRelTimeCalc";
+  fTitle = title ? title : "Task to finalize the relative time calibration";
+  
+  SetRelTimeResolutionLimit();
+  SetOutputPath();
+  SetOutputFile("");
+ 
+  Clear();
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - all flags to kFALSE
+// - all pointers to NULL
+//
+void MCalibrationRelTimeCalc::Clear(const Option_t *o)
+{
+
+  fIntensBad  = NULL;
+  fBadPixels  = NULL;
+  fCam        = NULL;
+  fIntensCam  = NULL;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+//  - MGeomCam
+//  - MCalibrationIntensityRelTimeCam or MCalibrationRelTimeCam 
+//  - MBadPixelsIntensityCam or MBadPixelsCam
+// 
+// It defines the PixId of every pixel in:
+//
+// - MCalibrationRelTimeCam 
+//
+// It sets all pixels in excluded which have the flag fBadBixelsPix::IsBad() set in:
+// 
+// - MCalibrationRelTimePix
+//
+Bool_t MCalibrationRelTimeCalc::ReInit(MParList *pList )
+{
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "No MGeomCam found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fIntensBad = (MBadPixelsIntensityCam*)pList->FindObject(AddSerialNumber("MBadPixelsIntensityCam"));
+  if (fIntensBad)
+    *fLog << inf << "Found MBadPixelsIntensityCam ... " << endl;
+  else
+    {
+      fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+      if (!fBadPixels)
+        {
+          *fLog << err << "Cannot find MBadPixelsCam ... abort." << endl;
+          return kFALSE;
+        }
+    }
+
+  fIntensCam = (MCalibrationIntensityRelTimeCam*)pList->FindObject(AddSerialNumber("MCalibrationIntensityRelTimeCam"));
+  if (fIntensCam)
+    *fLog << inf << "Found MCalibrationIntensityRelTimeCam ... " << endl;
+  else
+    {
+      fCam = (MCalibrationRelTimeCam*)pList->FindObject(AddSerialNumber("MCalibrationRelTimeCam"));
+      if (!fCam)
+        {
+          *fLog << err << "Cannot find MCalibrationRelTimeCam ... abort." << endl;
+          *fLog << err << "Maybe you forget to call an MFillH for the MHCalibrationRelTimeCam before..." << endl;
+          return kFALSE;
+        }
+    }
+  
+  UInt_t npixels     = fGeom->GetNumPixels();
+  
+  MCalibrationRelTimeCam *relcam = fIntensCam 
+    ? (MCalibrationRelTimeCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam          *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*relcam)[i];
+      MBadPixelsPix          &bad =                          (*badcam)[i];
+      
+      if (bad.IsBad())
+        {
+          pix.SetExcluded();
+          continue;
+        }
+
+      if (IsDebug())
+        pix.SetDebug();
+    }
+
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// Return if number of executions is null.
+//
+Int_t MCalibrationRelTimeCalc::PostProcess()
+{
+
+  if (GetNumExecutions()==0)
+    return kFALSE;
+
+  return Finalize();
+}
+
+// -----------------------------------------------------------------------
+//
+// First loop over pixels, average areas and sectors, call: 
+//  - FinalizeRelTimes()
+// for every entry. Count number of valid pixels in loop and return kFALSE
+// if there are none (the "Michele check").
+//
+// Call FinalizeBadPixels()
+//
+// Call MParContainer::SetReadyToSave() for fCam
+//
+// Print out some statistics
+//
+Int_t MCalibrationRelTimeCalc::Finalize()
+{
+  
+  //
+  // First loop over pixels, call FinalizePedestals and FinalizeRelTimes
+  //
+  FinalizeRelTimes();
+
+  //
+  // Finalize Bad Pixels
+  // 
+  FinalizeBadPixels();
+
+  //
+  // Re-direct the output to an ascii-file from now on:
+  //
+  MLog *asciilog = fOutputFile.IsNull() ? 0 : new MLog;
+  if (asciilog)
+  {
+      asciilog->SetOutputFile(GetOutputFile(),kTRUE);
+      SetLogStream(asciilog);
+  }
+
+  //
+  // Finalize calibration statistics
+  //
+  FinalizeUnsuitablePixels();
+
+  if (fIntensCam)
+    fIntensCam->SetReadyToSave();
+  else
+    fCam      ->SetReadyToSave();
+
+  if (fIntensBad)
+    fIntensBad->SetReadyToSave();
+  else
+    fBadPixels->SetReadyToSave();
+
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Errors statistics:" << endl;  
+
+  PrintUncalibrated(MBadPixelsPix::kDeviatingTimeResolution,    
+                    Form("%s%2.1f%s","Time resolution less than ",fRelTimeResolutionLimit," FADC slices from Mean:   "));
+  PrintUncalibrated(MBadPixelsPix::kRelTimeOscillating,   
+                    "Pixels with changing Rel. Times   over time:      ");
+  PrintUncalibrated(MBadPixelsPix::kRelTimeNotFitted,     
+                    "Pixels with unsuccesful Gauss fit to the times:   ");
+
+  if (asciilog)
+  {
+      SetLogStream(&gLog);
+      delete asciilog;
+  }
+
+  return kTRUE;
+}
+
+
+// ----------------------------------------------------------------------------------------------------
+//
+//
+// First loop: Calculate a mean and mean RMS of time resolution per area index 
+//             Include only pixels which are not MBadPixelsPix::kUnsuitableRun or 
+//             MBadPixelsPix::kUnreliableRun (see FinalizeBadPixels())
+//              
+// Second loop: Exclude those deviating by more than fRelTimeResolutionLimit FADC slices
+//              from the mean (obtained in first loop). Set 
+//              MBadPixelsPix::kDeviatingTimeResolution if excluded.
+// 
+void MCalibrationRelTimeCalc::FinalizeRelTimes()
+{
+
+  MCalibrationRelTimeCam *relcam = fIntensCam 
+    ? (MCalibrationRelTimeCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+
+  TArrayF lowlim       (nareas);
+  TArrayF upplim       (nareas);
+  TArrayF areasum      (nareas);
+  //  Float_t areasum2     [nareas];
+  TArrayI numareavalid (nareas);
+  TArrayI useunreliable(nareas);
+
+  //
+  // Apero loop: Count number of unreliable pixels:
+  //     
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      MBadPixelsPix &bad = (*badcam)[i];      
+      const Int_t  aidx  = (*fGeom)[i].GetAidx();
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+        continue;
+
+      numareavalid[aidx] ++;
+    }
+  
+  for (UInt_t aidx=0; aidx<nareas; aidx++)
+    if (numareavalid[aidx] < 100)
+      useunreliable[aidx] = 1;
+
+  numareavalid.Reset();
+  //
+  // First loop: Get mean time resolution the RMS
+  //             The loop is only to recognize later pixels with very deviating numbers
+  //
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*relcam)[i];
+      MBadPixelsPix          &bad =                          (*badcam)[i];
+      
+      if (pix.IsExcluded())
+        continue;
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+
+      const Int_t   aidx  = (*fGeom)[i].GetAidx();
+
+      if (!useunreliable[aidx])
+        if (bad.IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+          continue;
+
+      const Float_t res   = pix.GetTimePrecision();
+
+      areasum     [aidx] += res;
+      //      areasum2    [aidx] += res*res;
+      numareavalid[aidx] ++;
+    }
+
+
+  for (UInt_t aidx=0; aidx<nareas; aidx++)
+    {
+      if (numareavalid[aidx] < 20)
+        {
+          *fLog << warn << GetDescriptor() << ": Less than 20 pixels with valid time resolution found "
+                << "in area index: " << aidx << endl;
+          continue;
+        }
+ 
+      // Calculate the rms out of sum2:
+      /*
+      areasum2[aidx]  = (areasum2[aidx] - areasum[aidx]*areasum[aidx]/numareavalid[aidx]);
+      areasum2[aidx] /= (numareavalid[aidx]-1.);
+      */
+      areasum [aidx] /= numareavalid[aidx];
+      lowlim  [aidx]  = 0.;
+      upplim  [aidx]  = areasum [aidx] + fRelTimeResolutionLimit;
+      
+    }
+  *fLog << endl;  
+
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*relcam)[i];
+      MBadPixelsPix          &bad =                          (*badcam)[i];
+      
+      if (pix.IsExcluded())
+        continue;
+      
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+      
+      const Float_t res    = pix.GetTimePrecision();
+      const Int_t   aidx   = (*fGeom)[i].GetAidx();
+      
+      if ( res < lowlim[aidx] || res > upplim[aidx] )
+        {
+          *fLog << warn << "Deviating time resolution: "
+            << Form("%4.2f",res) << " out of accepted limits ["
+                << Form("%4.2f,%4.2f",lowlim[aidx],upplim[aidx]) << "] in pixel " << i << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingTimeResolution);
+          pix.SetExcluded();
+        }
+    }
+}
+
+
+// -----------------------------------------------------------------------------------
+//
+// Sets pixel to MBadPixelsPix::kUnsuitableRun, if one of the following flags is set:
+// - MBadPixelsPix::kRelTimeIsPedestal
+// - MBadPixelsPix::kRelTimeErrNotValid 
+// - MBadPixelsPix::kRelTimeRelErrNotValid 
+//
+// - Call MCalibrationPix::SetExcluded() for the bad pixels
+//
+void MCalibrationRelTimeCalc::FinalizeBadPixels()
+{
+  
+  MCalibrationRelTimeCam *relcam = fIntensCam 
+    ? (MCalibrationRelTimeCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      
+      MBadPixelsPix          &bad =                          (*badcam)[i];
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*relcam)[i];
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kDeviatingTimeResolution))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun   );
+ 
+      if (bad.IsUncalibrated( MBadPixelsPix::kRelTimeNotFitted))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun   );
+ 
+      if (bad.IsUncalibrated( MBadPixelsPix::kRelTimeOscillating))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun   );
+ 
+      if (bad.IsUnsuitable(   MBadPixelsPix::kUnsuitableRun    ))
+        pix.SetExcluded();
+
+    }
+}
+
+
+// -----------------------------------------------------------------------------------------------
+//
+// - Print out statistics about BadPixels of type UnsuitableType_t 
+// - store numbers of bad pixels of each type in fIntensCam or fCam
+//
+void MCalibrationRelTimeCalc::FinalizeUnsuitablePixels()
+{
+  
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Rel. Times Calibration status:" << endl;
+  *fLog << dec << setfill(' ');
+
+  MCalibrationRelTimeCam *relcam = fIntensCam 
+    ? (MCalibrationRelTimeCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  const Int_t nareas = fGeom->GetNumAreas();
+
+  TArrayI counts(nareas);
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*badcam)[i];
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          const Int_t aidx = (*fGeom)[i].GetAidx();
+          counts[aidx]++;
+        }
+    }
+
+  for (Int_t aidx=0; aidx<nareas; aidx++)
+    relcam->SetNumUnsuitable(counts[aidx], aidx);
+
+  if (fGeom->InheritsFrom("MGeomCamMagic"))
+    *fLog << " " << setw(7) << "Uncalibrated Pixels:            " 
+          << Form("%s%3i%s%3i","Inner: ",counts[0]," Outer: ",counts[1]) << endl;
+
+  counts.Reset();
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*badcam)[i];
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+        {
+          const Int_t aidx = (*fGeom)[i].GetAidx();
+          counts[aidx]++;
+        }
+    }
+
+  for (Int_t aidx=0; aidx<nareas; aidx++)
+    relcam->SetNumUnreliable(counts[aidx], aidx);
+
+  *fLog << " " << setw(7) << "Unreliable Pixels:              "
+        << Form("%s%3i%s%3i","Inner: ",counts[0]," Outer: ",counts[1]) << endl;
+
+}
+
+// -----------------------------------------------------------------------------------------------
+//
+// Print out statistics about BadPixels of type UncalibratedType_t 
+// 
+void MCalibrationRelTimeCalc::PrintUncalibrated(MBadPixelsPix::UncalibratedType_t typ, const char *text) const 
+{
+  
+  MBadPixelsCam         *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  UInt_t countinner = 0;
+  UInt_t countouter = 0;
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*badcam)[i];
+      if (bad.IsUncalibrated(typ))
+        {
+          if (fGeom->GetPixRatio(i) == 1.)
+            countinner++;
+          else
+            countouter++;
+        }
+    }
+
+  *fLog << " " << setw(7) << text  
+        << Form("%s%3i%s%3i","Inner: ",countinner," Outer: ",countouter) << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the path for output file
+// 
+void MCalibrationRelTimeCalc::SetOutputPath(TString path)
+{
+  fOutputPath = path;
+  if (fOutputPath.EndsWith("/"))
+    fOutputPath = fOutputPath(0, fOutputPath.Length()-1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the output file
+// 
+const char* MCalibrationRelTimeCalc::GetOutputFile()
+{
+  return Form("%s/%s", (const char*)fOutputPath, (const char*)fOutputFile);
+}
Index: /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCalc.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCalc.h	(revision 9772)
@@ -0,0 +1,80 @@
+#ifndef MARS_MCalibrationRelTimeCalc
+#define MARS_MCalibrationRelTimeCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCalibrationRelTimeCalc
+//
+// Integrates the time slices of the all pixels of a calibration event
+// and substract the pedestal value
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+
+class MCalibrationIntensityRelTimeCam;
+class MCalibrationRelTimeCam;
+class MGeomCam;
+class MBadPixelsIntensityCam;
+class MBadPixelsCam;
+
+class MCalibrationRelTimeCalc : public MTask
+{
+private:
+
+  static const Float_t fgRelTimeResolutionLimit; //! Default for fRelTimeResolutionLimit (now set to: 0.75)
+ 
+  // Variables
+  Float_t fRelTimeResolutionLimit;               //  Limit acceptance rel. time resolution (in FADC slices)
+  TString fOutputPath;                           //  Path to the output file
+  TString fOutputFile;                           //  Name of the output file  
+  
+  // Pointers
+  MBadPixelsIntensityCam     *fIntensBad;        //  Bad Pixels Intensity Cam
+  MBadPixelsCam              *fBadPixels;        //  Bad Pixels 
+  MCalibrationIntensityRelTimeCam *fIntensCam;   //  Calibrated RelTimes for different intensities
+  MCalibrationRelTimeCam     *fCam;              //  Calibrated RelTimes of all pixels 
+  MGeomCam                   *fGeom;             //! Camera geometry
+
+  enum  { kDebug };                              //  Possible flags
+
+  Byte_t  fFlags;                                //  Bit-field for the general flags
+  
+  // functions
+  const char* GetOutputFile       ();
+  void   FinalizeAverageResolution();
+  void   FinalizeRelTimes         ();
+  void   FinalizeBadPixels        ();
+  void   FinalizeUnsuitablePixels ();
+
+  void   PrintUncalibrated( MBadPixelsPix::UncalibratedType_t typ, const char *text) const;
+
+  Bool_t ReInit     (MParList *pList); 
+  Int_t  Process    () { return kTRUE; }
+  Int_t  PostProcess();
+
+public:
+
+  MCalibrationRelTimeCalc(const char *name=NULL, const char *title=NULL);
+
+  void Clear(const Option_t *o="");
+  
+  Int_t Finalize();
+  
+  Bool_t IsDebug() const  {  return TESTBIT(fFlags,kDebug); }
+
+  void SetDebug                 ( const Bool_t  b=kTRUE ) { b ? SETBIT(fFlags,kDebug) : CLRBIT(fFlags,kDebug); }   
+  void SetOutputPath            ( TString path="."                         );
+  void SetOutputFile            ( TString file="TimeCalibStat.txt"         ) { fOutputFile          = file; }
+  void SetRelTimeResolutionLimit( const Float_t f=fgRelTimeResolutionLimit ) { fRelTimeResolutionLimit = f; }
+
+  ClassDef(MCalibrationRelTimeCalc, 1)   // Task finalizing the relative time Calibration 
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCam.cc	(revision 9772)
@@ -0,0 +1,262 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationRelTimeCam                                               
+//                                                               
+// Storage container for relative arrival time calibration results         
+// of the whole camera.
+//
+// Individual pixels have to be cast when retrieved e.g.:
+// MCalibrationRelTimePix &avpix = (MCalibrationRelTimePix&)(*fRelCam)[i]
+// 
+// The following "calibration" constants can be retrieved from each pixel:
+// - GetTimeOffset(): The mean offset in relative times, 
+//   has to be added to any calculated relative time in the camera. 
+// - GetTimePrecision(): The Gauss sigma of histogrammed relative arrival 
+//   times for the calibration run. Gives an estimate about the timing 
+//   resolution.
+//
+// ALL RELATIVE TIMES HAVE TO BE CALCULATED W.R.T. PIXEL IDX 1 
+// (HARDWARE NUMBER: 2) !!
+//
+// Averaged values over one whole area index (e.g. inner or outer pixels for 
+// the MAGIC camera), can be retrieved via: 
+// MCalibrationRelTimePix &avpix = (MCalibrationRelTimePix&)fRelCam->GetAverageArea(i)
+//
+// Averaged values over one whole camera sector can be retrieved via: 
+// MCalibrationRelTimePix &avpix = (MCalibrationRelTimePix&)fRelCam->GetAverageSector(i)
+//
+// Note the averageing has been done on an event-by-event basis. Resulting 
+// Sigma's of the Gauss fit have been multiplied with the square root of the number 
+// of involved pixels in order to make a direct comparison possible with the mean of 
+// sigmas. 
+//
+// See also: MHCalibrationRelTimePix, MHCalibrationRelTimeCam              
+//                                                                         
+// The calculated values (types of GetPixelContent) are:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Mean Time Offset
+// 1: Error of Mean Time Offset
+// 2: Sigma of Time Offset == Time Resolution 
+// 3: Error of Sigma of Time Offset
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Rel. Arrival Time distribution
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationCam.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationRelTimePix.h"
+
+ClassImp(MCalibrationRelTimeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrationRelTimeCam::MCalibrationRelTimeCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationRelTimeCam";
+  fTitle = title ? title : "Container for Relative Time Calibration Information";
+  
+}
+
+void MCalibrationRelTimeCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationRelTimePix,i);
+}
+
+
+void MCalibrationRelTimeCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationRelTimePix,i);
+}
+
+void MCalibrationRelTimeCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationRelTimePix,i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not Valid
+//
+void MCalibrationRelTimeCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << "Calibrated pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationRelTimePix *pix;
+  while ((pix=(MCalibrationRelTimePix*)Next()))
+    {
+      
+      if (!pix->IsExcluded()) 
+	{                            
+
+          *fLog << all 
+                << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
+                        ":            Offset: ",pix->GetTimeOffset()," +- ",pix->GetTimeOffsetErr(),
+                        "   Precision: ",pix->GetTimePrecision()," +- ",pix->GetTimePrecisionErr())
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+  
+   
+  *fLog << all << endl;
+  *fLog << all << "Excluded pixels:" << endl;
+  *fLog << all << endl;
+  
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationRelTimePix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+	  *fLog << all << pix->GetPixId() << endl;
+	  id++;
+      }
+  }
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationRelTimePix*)Next5()))
+  {
+    *fLog << all 
+          << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Average Area   ",pix->GetPixId(),
+                  ":  Offset: ",pix->GetTimeOffset()," +- ",pix->GetTimeOffsetErr(),
+                  "   Precision: ",pix->GetTimePrecision()," +- ",pix->GetTimePrecisionErr())
+          << endl;
+  }
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationRelTimePix*)Next5()))
+  {
+    *fLog << all 
+          << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Average Sector ",pix->GetPixId(),
+                  ":  Offset: ",pix->GetTimeOffset()," +- ",pix->GetTimeOffsetErr(),
+                  "   Precision: ",pix->GetTimePrecision()," +- ",pix->GetTimePrecisionErr())
+          << endl;
+  }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted RelTime
+// 1: Error of fitted RelTime
+// 2: Sigma of fitted RelTime
+// 3: Error of Sigma of fitted RelTime
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to RelTime distribution
+//
+Bool_t MCalibrationRelTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetMean();
+      break;
+    case 1:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetMeanErr();
+      break;
+    case 2:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetSigma();
+      break;
+    case 3:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetSigmaErr();
+      break;
+    case 4:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetProb();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationRelTimeCam.h	(revision 9772)
@@ -0,0 +1,29 @@
+#ifndef MARS_MCalibrationRelTimeCam
+#define MARS_MCalibrationRelTimeCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationRelTimeCam : public MCalibrationCam
+{
+private:
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+
+public:
+
+  MCalibrationRelTimeCam(const char *name=NULL, const char *title=NULL);
+
+  // Prints
+  void Print(Option_t *o="") const;
+  
+  // Others
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+
+  ClassDef(MCalibrationRelTimeCam, 2)	// Container Rel. Arrival Time Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationRelTimePix.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationRelTimePix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationRelTimePix.cc	(revision 9772)
@@ -0,0 +1,59 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrationRelTimePix                                                  //
+//                                                                         //
+// Storage container for relative arrival time calibration results         // 
+// of one Pixel (PMT).                                                     //
+// The following "calibration" constants can be retrieved:                 //
+// - GetTimeOffset(): The mean offset in relative times, 
+//   has to be added to any calculated relative time in the camera. 
+// - GetTimePrecision(): The Gauss sigma of histogrammed relative arrival 
+//   times for the calibration run. Gives an estimate about the timing 
+//   resolution.
+//
+// ALL RELATIVE TIMES HAVE TO BE CALCULATED W.R.T. PIXEL IDX 1 
+// (HARDWARE NUMBER: 2) !!
+//
+// See also: MHCalibrationRelTimePix, MHCalibrationRelTimeCam              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationRelTimePix.h"
+
+ClassImp(MCalibrationRelTimePix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MCalibrationRelTimePix::MCalibrationRelTimePix(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationRelTimePix";
+  fTitle = title ? title : "Results of MHCalibrationRelTimePix ";
+
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationRelTimePix.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationRelTimePix.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationRelTimePix.h	(revision 9772)
@@ -0,0 +1,26 @@
+#ifndef MARS_MCalibrationRelTimePix
+#define MARS_MCalibrationRelTimePix
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+class MCalibrationRelTimePix : public MCalibrationPix
+{
+private:
+
+public:
+
+  MCalibrationRelTimePix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationRelTimePix() {}
+  
+  Float_t GetTimeOffset()       const { return GetMean();        }
+  Float_t GetTimeOffsetErr()    const { return GetMeanErr();     }
+  Float_t GetTimePrecision()    const { return GetSigma();       }
+  Float_t GetTimePrecisionErr() const { return GetSigmaErr();    }
+
+  ClassDef(MCalibrationRelTimePix, 1)	// Container Rel. Arrival Time Calibration Results Pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationTestCalc.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationTestCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationTestCalc.cc	(revision 9772)
@@ -0,0 +1,679 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  08/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrationTestCalc
+//
+//   PreProcess(): Initialize pointers to MHCalibrationTestCam
+//               
+//   ReInit():     MCalibrationCam::InitSize(NumPixels) is called from MGeomApply (which allocates
+//                 memory in a TClonesArray of type MCalibrationChargePix)
+//                 Initializes pointer to MBadPixelsCam
+//
+//   Process():    Nothing to be done, histograms getting filled by MHCalibrationTestCam
+//
+//   PostProcess(): Print out interpolation results to file
+//
+//  Input Containers:
+//   MHCalibrationTestCam
+//   MBadPixelsCam
+//   MGeomCam
+//
+//  Output Containers:
+//   none
+//  
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationTestCalc.h"
+
+#include <TSystem.h>
+#include <TH1.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MHCamera.h"
+
+#include "MHCalibrationTestCam.h"
+#include "MHCalibrationPix.h"
+
+#include "MCalibrationIntensityTestCam.h"
+#include "MCalibrationTestCam.h"
+#include "MCalibrationTestPix.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MCalibrationTestCalc);
+
+using namespace std;
+
+const Float_t MCalibrationTestCalc::fgPhotErrLimit = 4.5;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets the pointer to fTestCam and fGeom to NULL
+// Sets outputpath to "."
+// Sets outputfile to "TestCalibStat.txt"
+// Sets fPhotErrLimit to fgPhotErrLimit  
+//
+// Calls:
+// - Clear()
+//
+MCalibrationTestCalc::MCalibrationTestCalc(const char *name, const char *title)
+    : fIntensBad(NULL), fBadPixels(NULL), 
+      fTestCam(NULL), fIntensCam(NULL), fCam(NULL), 
+      fGeom(NULL)
+{
+        
+  fName  = name  ? name  : "MCalibrationTestCalc";
+  fTitle = title ? title : "Task to output the results of MHCalibrationTestCam ";
+  
+  SetPhotErrLimit();
+
+  SetOutputPath();
+  SetOutputFile();
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+// - MGeomCam
+// - MHCalibrationTestCam
+// - MCalibrationIntensityTestCam or MCalibrationTestCam 
+// - MBadPixelsIntensityCam or MBadPixelsCam
+// 
+Bool_t MCalibrationTestCalc::ReInit(MParList *pList )
+{
+
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "No MGeomCam found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fTestCam = (MHCalibrationTestCam*)pList->FindObject("MHCalibrationTestCam");
+  if (!fTestCam)
+    {
+      *fLog << err << "Cannot find MHCalibrationTestCam... aborting" << endl;
+      *fLog << err << "Maybe you forget to call an MFillH for the MHCalibrationTestCam before..." << endl;
+      return kFALSE;
+    }
+
+  fIntensCam = (MCalibrationIntensityTestCam*)pList->FindObject(AddSerialNumber("MCalibrationIntensityTestCam"));
+  if (fIntensCam)
+    *fLog << inf << "Found MCalibrationIntensityTestCam ... " << endl;
+  else
+    {
+      fCam = (MCalibrationTestCam*)pList->FindObject(AddSerialNumber("MCalibrationTestCam"));
+      if (!fCam)
+        {
+          *fLog << err << "Cannot find MCalibrationTestCam ... abort." << endl;
+          *fLog << err << "Maybe you forget to call an MFillH for the MHCalibrationTestCam before..." << endl;
+          return kFALSE;
+        }
+    }
+
+  fIntensBad = (MBadPixelsIntensityCam*)pList->FindObject(AddSerialNumber("MBadPixelsIntensityCam"));
+  if (fIntensBad)
+    *fLog << inf << "Found MBadPixelsIntensityCam ... " << endl;
+  else
+    {
+      fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+      if (!fBadPixels)
+        {
+          *fLog << err << "Cannot find MBadPixelsCam ... abort." << endl;
+          return kFALSE;
+        }
+    }
+
+
+  return kTRUE;
+}
+
+// ----------------------------------------------------------------------------------
+//  
+// Nothing to be done in Process, but have a look at MHCalibrationTestCam, instead
+// 
+Int_t MCalibrationTestCalc::Process()
+{
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// Return if number of executions is null.
+//
+// Print out some statistics
+//
+Int_t MCalibrationTestCalc::PostProcess()
+{
+
+  if (GetNumExecutions()==0)
+    return kTRUE;
+
+  MCalibrationTestCam *testcam = fIntensCam 
+    ? (MCalibrationTestCam*)fIntensCam->GetCam()  : fCam;
+
+  //
+  // Re-direct the output to an ascii-file from now on:
+  //
+  MLog asciilog;
+  asciilog.SetOutputFile(GetOutputFile(),kTRUE);
+  SetLogStream(&asciilog);
+  //
+  // Finalize calibration statistics
+  //
+  FinalizeCalibratedPhotons();
+  FinalizeNotInterpolated();
+  const Int_t maxbad = CalcMaxNumBadPixelsCluster();
+
+
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Pixel Interpolation status:" << endl;
+
+  if (fGeom->InheritsFrom("MGeomCamMagic"))
+    {
+      *fLog << " " << setw(7) << "Not interpolateable Pixels: " 
+            << Form("%s%3i%s%3i","Inner: ",testcam->GetNumUninterpolated(0),
+                    " Outer: ",testcam->GetNumUninterpolated(1)) << endl;
+      *fLog << " " << setw(7) << "Biggest not-interpolateable cluster: " 
+            << maxbad << endl;
+    }
+  
+  testcam->SetNumUninterpolatedInMaxCluster(maxbad);
+
+  *fLog << endl;  
+  SetLogStream(&gLog);
+
+  return kTRUE;
+}
+
+
+// ------------------------------------------------------------------------
+//
+//
+// First loop: Calculate a mean and mean RMS of calibrated photons per area index 
+//             Include only MHCalibrationTestPix's which are not empty (not interpolated)
+//              
+// Second loop: Get weighted mean number of calibrated photons and its RMS
+//              excluding those deviating by more than fPhotErrLimit 
+//              sigmas from the mean (obtained in first loop). Set 
+//              MBadPixelsPix::kDeviatingNumPhots if excluded.
+// 
+void MCalibrationTestCalc::FinalizeCalibratedPhotons() const
+{
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  MCalibrationTestCam *testcam = fIntensCam 
+    ? (MCalibrationTestCam*)fIntensCam->GetCam()  : fCam;
+  MBadPixelsCam       *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  TArrayD lowlim      (nareas);
+  TArrayD upplim      (nareas);
+  TArrayD areaphotons (nareas); 
+  TArrayD sectorphotons(nsectors);
+  TArrayD areavars    (nareas); 
+  TArrayD sectorvars  (nsectors);
+  TArrayD fittedmean  (nareas); 
+  TArrayD fittedsigma (nareas);
+  TArrayI numareavalid(nareas); 
+  TArrayI numsectorvalid(nsectors);
+
+  //
+  // First loop: Get mean number of calibrated photons and the RMS
+  //             The loop is only to recognize later pixels with very deviating numbers
+  //
+  MHCamera camphotons(*fGeom,"Camphotons","Photons in Camera");
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MHCalibrationPix     &hist = (*fTestCam)[i];
+      MCalibrationTestPix  &pix =  (MCalibrationTestPix&)(*testcam)[i];
+      //
+      // We assume that the pixels have been interpolated so far. 
+      // The MBadPixelsCam does not give any more information
+      //
+      if (hist.IsEmpty())
+        {
+          pix.SetExcluded();
+          continue;
+        }
+
+      const Double_t nphot    = hist.GetMean();
+      const Double_t nphoterr = hist.GetMeanErr();
+      const Int_t    aidx     = (*fGeom)[i].GetAidx();
+
+      camphotons.Fill(i,nphot);
+      camphotons.SetUsed(i);
+
+      pix.SetNumPhotons   ( nphot    );
+      pix.SetNumPhotonsErr( nphoterr );
+
+      areaphotons [aidx] += nphot;
+      areavars    [aidx] += nphot*nphot;
+      numareavalid[aidx] ++;
+    } 
+
+  for (UInt_t aidx=0; aidx<nareas; aidx++)
+    {
+      if (numareavalid[aidx] == 0)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid number of calibrated photons found "
+                << "in area index: " << aidx << endl;
+          continue;
+        }
+
+      if (numareavalid[aidx] == 1)
+        areavars[aidx]  = 0.;
+      else if (numareavalid[aidx] == 0)
+        {
+          areaphotons[aidx] = -1.;
+          areavars[aidx]    = -1.;
+        }
+      else
+        {
+          areavars[aidx]    = (areavars[aidx] - areaphotons[aidx]*areaphotons[aidx]/numareavalid[aidx]) 
+                            / (numareavalid[aidx]-1.);
+          areaphotons[aidx] = areaphotons[aidx] / numareavalid[aidx];
+        }
+      
+      if (areavars[aidx] < 0.)
+        {
+          *fLog << warn << GetDescriptor() << ": No pixels with valid variance of calibrated photons found "
+                << "in area index: " << aidx << endl;
+          continue;
+        }
+
+      const Float_t areamean = areaphotons[aidx];
+      const Float_t areaerr  = TMath::Sqrt(areavars[aidx]);
+      
+      MCalibrationTestPix &avpix = (MCalibrationTestPix&)testcam->GetAverageArea(aidx);
+      avpix.SetNumPhotons   (areamean);
+      avpix.SetNumPhotonsErr(areaerr );
+
+      lowlim [aidx] = areamean - fPhotErrLimit*areaerr;
+      upplim [aidx] = areamean + fPhotErrLimit*areaerr;
+
+      TArrayI area(1);
+      area[0] = aidx;
+
+      TH1D *hist = camphotons.ProjectionS(TArrayI(),area,"_py",100);
+      hist->Fit("gaus","Q");
+      const Double_t mean  = hist->GetFunction("gaus")->GetParameter(1);
+      const Double_t sigma = hist->GetFunction("gaus")->GetParameter(2);
+      const Int_t    ndf   = hist->GetFunction("gaus")->GetNDF();
+
+      if (ndf < 2)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the number of calibrated photons " 
+                << "in the camera with area index: " << aidx << endl;
+          *fLog << warn << GetDescriptor() << ": Number of dof.: " << ndf << " is smaller than 2 " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;
+          delete hist;
+          continue;
+        }
+      
+      const Double_t prob = hist->GetFunction("gaus")->GetProb();
+
+      if (prob < 0.001)
+        {
+          *fLog << warn << GetDescriptor() << ": Cannot use a Gauss fit to the number of calibrated photons " 
+                << "in the camera with area index: " << aidx << endl;
+          *fLog << warn << GetDescriptor() << ": Fit probability " << prob 
+                << " is smaller than 0.001 " << endl;
+          *fLog << warn << GetDescriptor() << ": Will use the simple mean and rms " << endl;
+          delete hist;
+          continue;
+        }
+      
+      fittedmean [aidx] = mean;
+      fittedsigma[aidx] = sigma;
+      
+      avpix.SetNumPhotons   (mean );
+      avpix.SetNumPhotonsErr(sigma);
+
+      lowlim  [aidx] = mean  - fPhotErrLimit*sigma;
+      upplim  [aidx] = mean  + fPhotErrLimit*sigma;
+
+      *fLog << inf << GetDescriptor() 
+            << ": Fitted number of calib. equiv. Cher. photons in area index " << aidx 
+            << ": "  << Form("%7.2f +- %6.2f",fittedmean[aidx],fittedsigma[aidx]) << endl;
+
+      delete hist;
+    }
+
+  *fLog << endl;
+
+  numareavalid.Reset();
+  areaphotons .Reset();
+  areavars    .Reset();
+
+  //
+  // Second loop: Get mean number of calibrated photons and its RMS excluding 
+  //              pixels deviating by more than fPhotErrLimit sigma. 
+  // 
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MHCalibrationPix &hist    = (*fTestCam)[i];
+      MCalibrationTestPix  &pix =  (MCalibrationTestPix&) (*testcam)[i];
+
+      const Int_t    aidx         = (*fGeom)[i].GetAidx();
+      const Int_t    sector       = (*fGeom)[i].GetSector();
+      const Double_t nphot        = hist.GetMean();
+      const Double_t nphotpera    = nphot            / (*fGeom)[i].GetA();
+      const Double_t nphotperaerr = hist.GetMeanErr()/ (*fGeom)[i].GetA();
+
+      pix.SetNumPhotonsPerArea   ( nphotpera    );
+      pix.SetNumPhotonsPerAreaErr( nphotperaerr );
+
+      if ( nphot < lowlim[aidx] || nphot > upplim[aidx] )
+        {
+          *fLog << warn << GetDescriptor() << ": Number of photons: " 
+                << Form("%8.2f out of %3.1f sigma limit: ",nphot,fPhotErrLimit)
+                << Form("[%8.2f,%8.2f] pixel%4i",lowlim[aidx],upplim[aidx],i) << endl;
+          MBadPixelsPix &bad = (*badcam)[i];
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingNumPhots );
+          bad.SetUnsuitable  ( MBadPixelsPix::kUnsuitableRun     );
+          continue;
+        }
+      
+      areavars     [aidx] += nphotpera*nphotpera;
+      areaphotons  [aidx] += nphotpera;
+      numareavalid [aidx] ++;
+
+      sectorvars    [sector] += nphotpera*nphotpera;
+      sectorphotons [sector] += nphotpera;
+      numsectorvalid[sector] ++;
+    } 
+
+  *fLog << endl;
+
+  for (UInt_t aidx=0; aidx<nareas; aidx++)
+    {
+      
+      if (numareavalid[aidx] == 1)
+        areavars[aidx] = 0.;
+      else if (numareavalid[aidx] == 0)
+        {
+          areaphotons[aidx] = -1.;
+          areavars[aidx]    = -1.;
+        }
+      else
+        {
+          areavars[aidx] = (areavars[aidx] - areaphotons[aidx]*areaphotons[aidx]/numareavalid[aidx]) 
+                         / (numareavalid[aidx]-1.);
+          areaphotons[aidx] /=  numareavalid[aidx];
+        }
+      
+
+      MCalibrationTestPix &avpix = (MCalibrationTestPix&)testcam->GetAverageArea(aidx);
+
+      if (areavars[aidx] < 0. || areaphotons[aidx] <= 0.)
+        {
+          *fLog << warn << GetDescriptor() 
+                << ": Mean number of photons per area in area index " 
+                << aidx << " could not be calculated! Mean: " << areaphotons[aidx] 
+                << " Variance: " << areavars[aidx] << endl;
+          avpix.SetExcluded();
+          continue;
+        }
+
+      const Float_t areaerr = TMath::Sqrt(areavars[aidx]);
+      
+      avpix.SetNumPhotonsPerArea   (areaphotons[aidx]);
+      avpix.SetNumPhotonsPerAreaErr(areaerr );
+
+      *fLog << inf << GetDescriptor() << ": Mean number of equiv. Cher. photons "
+            << "per area in area idx " << aidx << ": "  
+            << Form("%5.3f+-%5.4f  [ph/mm^2]",areaphotons[aidx],areaerr) << endl;
+    }
+
+  *fLog << endl;
+
+  for (UInt_t sector=0; sector<nsectors; sector++)
+    {
+      
+      if (numsectorvalid[sector] == 1)
+        sectorvars[sector] = 0.;
+      else if (numsectorvalid[sector] == 0)
+        {
+          sectorphotons[sector]  = -1.;
+          sectorvars[sector]     = -1.;
+        }
+      else
+        {
+          sectorvars[sector] = (sectorvars[sector] 
+                               - sectorphotons[sector]*sectorphotons[sector]/numsectorvalid[sector]
+                               ) 
+                             / (numsectorvalid[sector]-1.);
+          sectorphotons[sector] /=  numsectorvalid[sector];
+        }
+      
+      MCalibrationTestPix &avpix = (MCalibrationTestPix&)testcam->GetAverageSector(sector);
+
+      if (sectorvars[sector] < 0. || sectorphotons[sector] <= 0.)
+        {
+          *fLog << warn << GetDescriptor() 
+                << ": Mean number of calibrated photons per area in sector " 
+                << sector << " could not be calculated! Mean: " << sectorphotons[sector] 
+                << " Variance: " << sectorvars[sector] << endl;
+          avpix.SetExcluded();
+          continue;
+        }
+      
+  
+      const Float_t sectorerr = TMath::Sqrt(sectorvars[sector]);
+
+      avpix.SetNumPhotonsPerArea   (sectorphotons[sector]);
+      avpix.SetNumPhotonsPerAreaErr(sectorerr );
+
+      *fLog << inf << GetDescriptor() << ": Mean number of equiv. Cher. photons "
+            << "per area in sector " << sector << ":   "  
+            << Form("%5.3f+-%5.4f  [ph/mm^2]",sectorphotons[sector],sectorerr) << endl;
+    }
+
+  return;
+}
+
+
+// -----------------------------------------------------------------------------------------------
+//
+// Print out statistics about not interpolated pixels
+// 
+void MCalibrationTestCalc::FinalizeNotInterpolated() 
+{
+  
+  MCalibrationTestCam *testcam = fIntensCam 
+    ? (MCalibrationTestCam*)fIntensCam->GetCam()  : fCam;
+
+  const Int_t areas  = fGeom->GetNumAreas();
+  TArrayI *newarr[areas];
+
+  for (Int_t aidx=0; aidx<areas; aidx++)
+    newarr[aidx] = new TArrayI(0);
+
+  for (Int_t i=0; i<testcam->GetSize(); i++)
+    {
+      const Int_t aidx = (*fGeom)[i].GetAidx();
+      MCalibrationTestPix &pix = (MCalibrationTestPix&)(*testcam)[i];
+      if (pix.IsExcluded())
+        {
+          const Int_t size = newarr[aidx]->GetSize();
+          newarr[aidx]->Set(size+1);
+          newarr[aidx]->AddAt(i,size);
+        }
+    }
+
+  Int_t num = 0;
+
+  for (Int_t aidx = 0; aidx<areas; aidx++)
+    {
+      *fLog << endl;
+      *fLog << " " << setw(7)
+            << "Not interpolated pixels by in area idx " << aidx << ": ";
+      for (Int_t i=0; i<newarr[aidx]->GetSize(); i++)
+        {
+          *fLog << newarr[aidx]->At(i) << " ";
+          num++;
+        }
+      testcam->SetNumUninterpolated(newarr[aidx]->GetSize(),aidx);
+      *fLog << endl;
+    }
+  
+  *fLog << " " << setw(7) << num << " total not interpolateable pixels " << endl;
+  
+}
+
+Int_t MCalibrationTestCalc::CalcMaxNumBadPixelsCluster()
+{
+
+  MCalibrationTestCam *testcam = fIntensCam 
+    ? (MCalibrationTestCam*)fIntensCam->GetCam()  : fCam;
+
+  TArrayI arr(0);
+  
+  for (Int_t i=0; i<testcam->GetSize(); i++)
+    {
+      MCalibrationTestPix &pix = (MCalibrationTestPix&)(*testcam)[i];
+      if (pix.IsExcluded())
+        {
+        const Int_t s = arr.GetSize();
+        arr.Set(s+1);
+        arr[s] = i;
+        }
+    }
+  
+  const Int_t size = arr.GetSize();
+  
+  if (size == 0)
+    return 0;
+  
+  if (size == 1)
+    return 1;
+
+  TArrayI knownpixels(0);
+  Int_t clustersize    = 1;
+  Int_t oldclustersize = 0;
+  //
+  // Loop over the not-interpolateable pixels:
+  //
+  for (Int_t i=0; i<size; i++)
+    {
+
+      const Int_t id   = arr[i];
+      const Int_t knownsize = knownpixels.GetSize();
+      knownpixels.Set(knownsize+1);
+      knownpixels[knownsize] = id;
+      LoopNeighbours(arr, knownpixels, clustersize, id);
+      if (clustersize > oldclustersize)
+        oldclustersize = clustersize;
+      clustersize = 1;
+    }
+
+  return oldclustersize; 
+
+}
+
+
+void MCalibrationTestCalc::LoopNeighbours( const TArrayI &arr, TArrayI &knownpixels, Int_t &clustersize, const Int_t idx )
+{
+  
+  const MGeomPix &pix = (*fGeom)[idx];
+  const Byte_t neighbours = pix.GetNumNeighbors();
+
+  // 
+  // Loop over the next neighbours: 
+  // - Check if they are already in the list of known pixels
+  // - If not, call loopneighbours for the rest
+  // - grow clustersize for those
+  //
+  for (Int_t i=0;i<neighbours;i++)
+    {
+      const Int_t newid = pix.GetNeighbor(i);
+      Bool_t known = kFALSE;
+
+      for (Int_t j=knownpixels.GetSize()-1;j>=0;j--)
+        if (newid == knownpixels.At(j))
+          {
+            known = kTRUE;
+            break;
+          }
+      if (known)
+        continue;
+
+      for (Int_t k=0;k<arr.GetSize();k++)
+        if (newid == arr.At(k))
+          {
+            // This is an unknown, new pixel in the cluster!!
+            clustersize++;
+            const Int_t knownsize = knownpixels.GetSize();
+            knownpixels.Set(knownsize+1);
+            knownpixels[knownsize] = newid;
+            LoopNeighbours(arr, knownpixels, clustersize, newid);
+          }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the path for output file
+// 
+void MCalibrationTestCalc::SetOutputPath(TString path)
+{
+  fOutputPath = path;
+  if (fOutputPath.EndsWith("/"))
+    fOutputPath = fOutputPath(0, fOutputPath.Length()-1);
+}
+
+void MCalibrationTestCalc::SetOutputFile(TString file)
+{ 
+  fOutputFile        = file; 
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the output file
+// 
+const char* MCalibrationTestCalc::GetOutputFile()
+{
+  return Form("%s/%s", (const char*)fOutputPath, (const char*)fOutputFile);
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationTestCalc.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationTestCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationTestCalc.h	(revision 9772)
@@ -0,0 +1,71 @@
+#ifndef MARS_MCalibrationTestCalc
+#define MARS_MCalibrationTestCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrationTestCalc                                                   //
+//                                                                         //
+// Integrates the time slices of the all pixels of a calibration event     //
+// and substract the pedestal value                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MHCalibrationTestCam;
+class MCalibrationIntensityTestCam;
+class MCalibrationTestCam;
+class MBadPixelsIntensityCam;
+class MBadPixelsCam;
+class MGeomCam;
+
+class MCalibrationTestCalc : public MTask
+{
+private:
+
+  static const Float_t fgPhotErrLimit;  //! Default for fPhotErrLimit (now set to: 4.)
+
+  // Variables
+  Float_t fPhotErrLimit;               // Limit acceptance nr. cal. phots w.r.t. area idx mean (in sigmas)
+
+  TString fOutputPath;                 // Path to the output file
+  TString fOutputFile;                 // Name of the output file  
+  
+  // Pointers
+  MBadPixelsIntensityCam       *fIntensBad;   //! Bad Pixels
+  MBadPixelsCam                *fBadPixels;   //! Bad Pixels 
+  MHCalibrationTestCam         *fTestCam;     //! Calibrated Photons in the camera
+  MCalibrationIntensityTestCam *fIntensCam;   //! Storage Calibrated Photons in the camera
+  MCalibrationTestCam          *fCam;         //! Storage Calibrated Photons in the camera
+  MGeomCam                     *fGeom;        //! Camera geometry
+
+  // functions
+  const char* GetOutputFile();
+
+  void   FinalizeNotInterpolated();
+  void   FinalizeCalibratedPhotons() const;
+  Int_t  CalcMaxNumBadPixelsCluster();
+  void   LoopNeighbours( const TArrayI &arr, TArrayI &known, Int_t &clustersize, const Int_t idx );
+  
+  Bool_t ReInit     (MParList *pList); 
+  Int_t  Process    ();
+  Int_t  PostProcess();
+
+public:
+
+  MCalibrationTestCalc(const char *name=NULL, const char *title=NULL);
+
+  void SetOutputFile  ( TString file="TestCalibStat.txt" );
+  void SetOutputPath  ( TString path="."                 );
+  void SetPhotErrLimit( const Float_t f=fgPhotErrLimit   ) { fPhotErrLimit = f; }  
+  
+  ClassDef(MCalibrationTestCalc, 1)   // Task retrieving the results of MHCalibrationTestCam
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationTestCam.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationTestCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationTestCam.cc	(revision 9772)
@@ -0,0 +1,310 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationTestCam                                               
+//                                                               
+// Storage container for calibrated photons, with calibration applied on the 
+// same calibration run (see MHCalibrationTestCam and MHCalibrationTestPix).
+//
+// See also: MCalibrationTestPix, MCalibrationTestCalc, MCalibrationQECam
+//           MHCalibrationTestPix, MHCalibrationTestCam              
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationTestCam.h"
+#include "MCalibrationTestPix.h"
+
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MCalibrationTestCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets all pointers to 0
+// 
+// Creates a TClonesArray of MCalibrationTestPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MCalibrationTestCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationTestPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MCalibrationTestCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationTestPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MCalibrationTestCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+// Calls:
+// - Clear()
+//
+MCalibrationTestCam::MCalibrationTestCam(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationTestCam";
+  fTitle = title ? title : "Storage container for the Calibration Test Information in the camera";
+  
+  Clear();
+}
+
+// --------------------------------------
+//
+// Sets all variable to 0.
+// Sets all flags to kFALSE
+// Calls MCalibrationCam::Clear()
+//
+void MCalibrationTestCam::Clear(Option_t *o)
+{
+
+  fNumUninterpolatedInMaxCluster = 0; 
+
+  return;
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationTestPix's in the ranges from - to to fPixels
+//
+void MCalibrationTestCam::Add(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fPixels->AddAt(new MCalibrationTestPix,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationTestPix's in the ranges from - to to fAverageAreas
+//
+void MCalibrationTestCam::AddArea(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageAreas->AddAt(new MCalibrationTestPix,i);
+}
+
+// -------------------------------------------------------------------
+//
+// Add MCalibrationTestPix's in the ranges from - to to fAverageSectors
+//
+void MCalibrationTestCam::AddSector(const UInt_t a, const UInt_t b)
+{
+  for (UInt_t i=a; i<b; i++)
+    fAverageSectors->AddAt(new MCalibrationTestPix,i);
+}
+
+
+// -------------------------------------------------------------------
+//
+// Initialize the objects inside the TOrdCollections
+// - fAverageAreas
+// - fAverageBadAreas
+// using the virtual function Add().
+//
+// InitSize can only increase the size, but not shrink. 
+// 
+// It can be called more than one time. New Containers are 
+// added only from the current size to the argument i.
+//
+void MCalibrationTestCam::InitAverageAreas(const UInt_t i)
+{
+
+  const UInt_t save = GetAverageAreas();
+
+  if (i==save)
+    return;
+  
+  fNumUninterpolated.Set(i);
+  
+  MCalibrationCam::InitAverageAreas(i);
+  
+  return;
+  
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Print first the well fitted pixels 
+// and then the ones which are not FitValid
+//
+void MCalibrationTestCam::Print(Option_t *o) const
+{
+
+  *fLog << all << GetDescriptor() << ":" << endl;
+  int id = 0;
+  
+  *fLog << all << "Calibrated (or interpolated) pixels:" << endl;
+  *fLog << all << endl;
+
+  TIter Next(fPixels);
+  MCalibrationTestPix *pix;
+  while ((pix=(MCalibrationTestPix*)Next()))
+    {
+      
+      if (!pix->IsExcluded()) 
+	{                            
+
+          *fLog << all 
+                << Form("%s%3i","Pixel: ",pix->GetPixId())
+		<< Form("%s%4.2f%s%4.2f","  Num.Photons: ",pix->GetNumPhotons(),"+-",pix->GetNumPhotonsErr()) 
+		<< Form("%s%4.2f%s%4.2f","  Num.Photons/mm^2: ",pix->GetNumPhotonsPerArea()
+                        ,"+-",pix->GetNumPhotonsPerAreaErr()) 
+		<< endl;
+          id++;
+	}
+    }
+  
+  *fLog << all << id << " pixels" << endl;
+  id = 0;
+  
+   
+  *fLog << all << endl;
+  *fLog << all << "Not interpolated pixels:" << endl;
+  *fLog << all << endl;
+  
+  id = 0;
+
+  TIter Next4(fPixels);
+  while ((pix=(MCalibrationTestPix*)Next4()))
+  {
+      if (pix->IsExcluded())
+      {
+        *fLog << all << pix->GetPixId() << " ";
+        id++;
+
+        if (!(id % 25))
+          *fLog << endl;
+      }
+  }
+  
+  *fLog << endl;
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  *fLog << all << endl;
+  *fLog << all << "Averaged Areas:" << endl;
+  *fLog << all << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationTestPix*)Next5()))
+  {
+    *fLog << all << Form("%s%3i","Area Idx: ",pix->GetPixId())
+          << Form("%s%4.2f%s%4.2f","  Num.Photons: ",pix->GetNumPhotons(),"+-",pix->GetNumPhotonsErr()) 
+          << Form("%s%4.2f%s%4.2f","  Num.Photons/mm^2: ",pix->GetNumPhotonsPerArea()
+                  ,"+-",pix->GetNumPhotonsPerAreaErr()) 
+          << endl;
+  }
+
+  *fLog << all << endl;
+  *fLog << all << "Averaged Sectors:" << endl;
+  *fLog << all << endl;
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationTestPix*)Next6()))
+  {
+    *fLog << all << Form("%s%3i","Sector: ",pix->GetPixId())
+          << Form("%s%4.2f%s%4.2f","  Num.Photons: ",pix->GetNumPhotons(),"+-",pix->GetNumPhotonsErr()) 
+          << Form("%s%4.2f%s%4.2f","  Num.Photons/mm^2: ",pix->GetNumPhotonsPerArea()
+                  ,"+-",pix->GetNumPhotonsPerAreaErr()) 
+          << endl;
+  }
+  *fLog << all << endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// 0: Number Photons
+// 1: Error Number Photons
+// 2: Number photons per area
+// 3: Error Number Photons per area
+// 4: Pixels which are not interpolateable
+//
+Bool_t MCalibrationTestCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (idx > GetSize())
+    return kFALSE;
+
+  Float_t area = cam[idx].GetA();
+
+ if (area == 0)
+    return kFALSE;
+
+ MCalibrationTestPix &pix = (MCalibrationTestPix&)(*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetNumPhotons();
+      break;
+    case 1:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetNumPhotonsErr();
+      break;
+    case 2:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetNumPhotonsPerArea();
+      break;
+    case 3:
+      if (pix.IsExcluded())
+        return kFALSE;
+      val = pix.GetNumPhotonsPerAreaErr();
+      break;
+    case 4:
+      if (!pix.IsExcluded())
+        return kFALSE;
+      val = 1;
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+}
+
+void  MCalibrationTestCam::SetNumUninterpolated( const UInt_t i, const Int_t aidx ) 
+{
+
+  if (aidx < 0)
+    return;
+
+  if (aidx < fNumUninterpolated.GetSize())
+    fNumUninterpolated[aidx] = i;  
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationTestCam.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationTestCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationTestCam.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MCalibrationTestCam
+#define MARS_MCalibrationTestCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationTestCam : public MCalibrationCam
+{
+private:
+  
+  TArrayI fNumUninterpolated;             // Number uninterpolated Pixels per area index 
+  Int_t   fNumUninterpolatedInMaxCluster; // Number of not interpolateable pixels in biggest cluster
+
+  void Add(const UInt_t a, const UInt_t b);
+  void AddArea(const UInt_t a, const UInt_t b);
+  void AddSector(const UInt_t a, const UInt_t b);
+  
+public:
+
+  MCalibrationTestCam(const char *name=NULL, const char *title=NULL);
+  
+  void Clear (Option_t *o="");
+  
+  const Int_t                GetNumUninterpolated ( Int_t aidx ) const { 
+	return fNumUninterpolated[aidx];  }
+  const Int_t                GetNumUninterplatedInMaxCluster ()  const { 
+	return fNumUninterpolatedInMaxCluster; }
+  Bool_t                     GetPixelContent      ( Double_t &val, Int_t idx, 
+	                                            const MGeomCam &cam, Int_t type=0) const;
+  
+  void  InitAverageAreas       ( const UInt_t i);
+
+  // Prints
+  void  Print (Option_t *o="") const;
+
+  // Setters   
+  void  SetNumUninterpolated            ( const UInt_t i, const Int_t aidx );
+  void  SetNumUninterpolatedInMaxCluster( const UInt_t i ) { fNumUninterpolatedInMaxCluster = i; }
+
+  // Draw
+  void DrawPixelContent( Int_t num) const {}
+  
+  ClassDef(MCalibrationTestCam, 1) // Container Test Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/MCalibrationTestPix.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationTestPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationTestPix.cc	(revision 9772)
@@ -0,0 +1,75 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   08/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                     
+// MCalibrationTestPix                                     
+//                                                     
+// Base Storage container for the test result of a calibration pixel. 
+// Holds calibrated number of photons, number of photons per area (mm^2) and 
+// their errors. Not interpolateable pixels are declared excluded.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationTestPix.h"
+
+ClassImp(MCalibrationTestPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Sets:
+// - fPixId to -1
+//
+// Calls:
+// - Clear()
+//
+MCalibrationTestPix::MCalibrationTestPix(const char *name, const char *title)
+    : fPixId(-1)
+{
+
+  fName  = name  ? name  : "MCalibrationTestPix";
+  fTitle = title ? title : "Container of the fit results of MHCalibrationTestPix ";
+
+  Clear();
+
+}
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all data members to -1
+// - all excluded to kFALSE
+//
+void MCalibrationTestPix::Clear(Option_t *o)
+{
+
+  fNumPhotons           =  -1.;
+  fNumPhotonsErr        =  -1.;
+  fNumPhotonsPerArea    =  -1.;
+  fNumPhotonsPerAreaErr =  -1.;
+
+  SetExcluded          ( kFALSE );
+}
+
Index: /tags/Mars-V0.9/mcalib/MCalibrationTestPix.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MCalibrationTestPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MCalibrationTestPix.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MCalibrationTestPix
+#define MARS_MCalibrationTestPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCalibrationTestPix : public MParContainer
+{
+private:
+
+  Int_t   fPixId;                // Software PixId (needed to get Id in calls to Next())
+  Bool_t  fExcluded;             // If pixels is excluded or not (not interpolateable)
+
+  Float_t fNumPhotons;           // Number of calibrated photons
+  Float_t fNumPhotonsErr;        // Error Number of calibrated photons
+  Float_t fNumPhotonsPerArea;    // Number of calibrated photons per mm^2     
+  Float_t fNumPhotonsPerAreaErr; // Error Number of calibrated photons per mm^2
+
+public:
+
+  MCalibrationTestPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationTestPix() {}
+  
+  void Clear(Option_t *o="");
+  
+  // Getters
+  Float_t GetNumPhotons          () const { return fNumPhotons;           }
+  Float_t GetNumPhotonsErr       () const { return fNumPhotonsErr;        }
+  Float_t GetNumPhotonsPerArea   () const { return fNumPhotonsPerArea;    }
+  Float_t GetNumPhotonsPerAreaErr() const { return fNumPhotonsPerAreaErr; }
+  Int_t   GetPixId               () const { return fPixId;                }
+  
+  Bool_t  IsExcluded             () const { return fExcluded;             }
+
+  // Setters
+  void SetPixId               ( const Int_t   i )       { fPixId                = i; }
+  void SetExcluded            ( const Bool_t  b=kTRUE ) { fExcluded             = b; }
+  void SetNumPhotons          ( const Float_t f )       { fNumPhotons           = f; }          
+  void SetNumPhotonsErr       ( const Float_t f )       { fNumPhotonsErr        = f; }       
+  void SetNumPhotonsPerArea   ( const Float_t f )       { fNumPhotonsPerArea    = f; }   
+  void SetNumPhotonsPerAreaErr( const Float_t f )       { fNumPhotonsPerAreaErr = f; }
+
+
+  ClassDef(MCalibrationTestPix, 1)	// Container for Calibration Test Results Pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mcalib/MMcCalibrationCalc.cc
===================================================================
--- /tags/Mars-V0.9/mcalib/MMcCalibrationCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MMcCalibrationCalc.cc	(revision 9772)
@@ -0,0 +1,355 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 12/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMcCalibrationCalc
+//
+//  Input Containers:
+//   MMcConfigRunHeader
+//   MRawRunHeader
+//   MMcFadcHeader
+//   MHillas
+//   MNewImagePar
+//   MMcEvt
+//
+//  Output Containers:
+//  (containers mus exist already, they are filled with new values).
+//   MCalibrationChargeCam
+//   MCalibrationQECam  
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcCalibrationCalc.h"
+
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargeCam.h"
+
+#include "MCalibrationQEPix.h"
+#include "MCalibrationQECam.h"
+
+#include "MGeomCam.h"
+#include "MRawRunHeader.h"
+#include "MMcConfigRunHeader.h"
+
+#include "MHillas.h"
+#include "MImagePar.h"
+#include "MNewImagePar.h"
+
+#include "MMcEvt.hxx"
+#include "MMcFadcHeader.hxx"
+
+ClassImp(MMcCalibrationCalc);
+
+using namespace std;
+
+MMcCalibrationCalc::MMcCalibrationCalc(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcCalibrationCalc";
+    fTitle = title ? title : "Calculate and write conversion factors into MCalibrationChargeCam and MCalibrationQECam containers";
+
+    fHistADC2PhotEl = new TH1F(AddSerialNumber("ADC2PhotEl"), "log10(fPhotElfromShower/fSize)", 1500, -3., 3.);
+    fHistADC2PhotEl->SetXTitle("log_{10}(fPhotElfromShower / fSize) [photel/ADC count]");
+
+
+    fHistPhot2PhotEl = new TH1F(AddSerialNumber("Phot2PhotEl"), "Photon conversion efficiency", 1000, 0., 1.);
+    fHistPhot2PhotEl->SetXTitle("Overall photon conversion efficiency [photoelectron/photon]");
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the run type. Return kTRUE if it is a MC run or if there
+// is no MC run header (old camera files) kFALSE in case of a different
+// run type
+//
+Bool_t MMcCalibrationCalc::CheckRunType(MParList *pList) const
+{
+    const MRawRunHeader *run = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!run)
+    {
+        *fLog << warn << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+        return kTRUE;
+    }
+
+    return  run->IsMonteCarloRun();
+}
+
+// --------------------------------------------------------------------------
+//
+// Make sure, that there is an MCalibrationCam Object in the Parameter List.
+//
+Int_t MMcCalibrationCalc::PreProcess(MParList *pList)
+{
+    fHistADC2PhotEl->Reset();
+    fHistPhot2PhotEl->Reset();
+
+    fADC2PhotEl = 0;
+    fPhot2PhotEl = 0;
+
+    fCalCam = (MCalibrationChargeCam*) pList->FindObject(AddSerialNumber("MCalibrationChargeCam"));
+    if (!fCalCam)
+    {
+        *fLog << err << AddSerialNumber("MCalibrationChargeCam") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fQECam = (MCalibrationQECam*) pList->FindObject(AddSerialNumber("MCalibrationQECam"));
+    if (!fQECam)
+    {
+        *fLog << err << AddSerialNumber("MCalibrationQECam") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHillas = (MHillas*) pList->FindObject(AddSerialNumber("MHillas"));
+    if ( !fHillas)
+    {
+        *fLog << err << AddSerialNumber("MHillas") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNew = (MNewImagePar*)pList->FindObject(AddSerialNumber("MNewImagePar"));
+    if (!fNew)
+    {
+        *fLog << err << AddSerialNumber("MNewImagePar") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPar = (MImagePar*)pList->FindObject(AddSerialNumber("MImagePar"));
+    if (!fPar)
+    {
+        *fLog << err << AddSerialNumber("MImagePar") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*) pList->FindObject(AddSerialNumber("MMcEvt"));
+    if (!fMcEvt)
+    {
+        *fLog << err << AddSerialNumber("MMcEvt") << "not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the runtype.
+// Search for MGeomCam and MMcFadcHeader.
+//
+Bool_t MMcCalibrationCalc::ReInit(MParList *pList)
+{
+  //
+  // If it is no MC file display error and exit
+  //
+  if (!CheckRunType(pList))
+  {
+      *fLog << err << "MMcCalibrationCalc can only be used with MC files... aborting." << endl;
+      return kFALSE;
+  }
+
+  //
+  // Now check the existence of all necessary containers.
+  //
+  fGeom = (MGeomCam*) pList->FindObject(AddSerialNumber("MGeomCam"));
+  if (!fGeom)
+  {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  fHeaderFadc = (MMcFadcHeader*)pList->FindObject(AddSerialNumber("MMcFadcHeader"));
+  if (!fHeaderFadc)
+  {
+      *fLog << err << AddSerialNumber("MMcFadcHeader") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  for (UInt_t ipix = 0; ipix < fGeom->GetNumPixels(); ipix++)
+  {
+      if (fHeaderFadc->GetPedestalRmsHigh(ipix) > 0 ||
+	  fHeaderFadc->GetPedestalRmsLow(ipix)  > 0 )
+      {
+          *fLog << err << "Trying to calibrate the data using a Camera file produced with added noise." << endl;
+          *fLog << "Please use a noiseless file for calibration... aborting." << endl << endl;
+	  return kFALSE;
+      }
+  }
+
+  // Now check the light collection for inner and outer pixels to
+  // calculate the ratio between the two. FIXME! Light collection
+  // depends on the incidence angle of the light w.r.t. the camera
+  // plane. For the moment we take the ratio for light impinging
+  // perpendicular to the camera plane.
+  //
+  // FIXME! We should look for AddSerialNumber("MMcConfigRunHeader") but
+  // for the moment the stereo version of camera does not write one such
+  // header per telescope (it should!)
+  //
+  MMcConfigRunHeader* mcconfig = (MMcConfigRunHeader*) pList->FindObject("MMcConfigRunHeader");
+  if (!mcconfig)
+    {
+      *fLog << err << "MMcConfigRunHeader" << " not found... aborting." << endl;
+      return kFALSE;
+    }
+  TArrayF innerlightcoll = mcconfig->GetLightCollectionFactor();
+  TArrayF outerlightcoll = mcconfig->GetLightCollectionFactorOuter();
+
+  // In principle outer pixels seem to have a different average light 
+  // collection efficiency than outer ones. We set here the factor between
+  // the two.
+
+  fOuterPixelsLightCollection = outerlightcoll[90] / innerlightcoll[90]; 
+  // (at angle = 90 deg)
+
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Obtain average ratio of photons in camera to image Size.
+//
+Int_t MMcCalibrationCalc::Process()
+{
+    //
+    // Exclude events with some saturated pixel
+    //
+    if (fPar->GetNumSatPixelsHG()>0)
+        return kTRUE;
+
+    const Float_t size = fHillas->GetSize(); 
+    const Float_t innersize = fNew->GetInnerSize();
+
+    // Size will at this point be in ADC counts (still uncalibrated)
+    //
+    // Exclude events with low Size (larger fluctuations)
+    // FIXME? The present cut (1000 "inner-pixel-counts") is somehow
+    // arbitrary. Might it be optimized?
+    //   
+
+    if (size < 1000)
+        return kTRUE;
+
+    //
+    // PATCH: Convert number of photoelectrons in camera to the approximate number 
+    // of photoelectrons that would have been registered if all pixels had the same
+    // light collection efficiency as inner ones (called here "corrected_photel").
+    //
+ 
+    const Float_t inner_photel = (Float_t) fMcEvt->GetPhotElfromShower() * innersize / size;
+    const Float_t outer_photel = (Float_t) fMcEvt->GetPhotElfromShower() - inner_photel;
+
+    const Float_t corrected_photel = inner_photel + outer_photel / fOuterPixelsLightCollection;
+
+
+    //    fHistADC2PhotEl->Fill(TMath::Log10(fMcEvt->GetPhotElfromShower()/size));
+
+    fHistADC2PhotEl->Fill(TMath::Log10(corrected_photel/size));
+    fHistPhot2PhotEl->Fill( corrected_photel / (Float_t) fMcEvt->GetPassPhotCone() );
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the MCalibrationCam object
+//
+Int_t MMcCalibrationCalc::PostProcess()
+{
+    const Stat_t n = fHistADC2PhotEl->GetEntries();
+    if (n<1)
+    {
+        *fLog << err << "No events read... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPhot2PhotEl = fHistPhot2PhotEl->GetMean();   // Average quantum efficiency
+
+    //
+    // Find peak of log10(photel/Size) histogram:
+    //
+    const Int_t reach = 2;
+    Stat_t summax = 0;
+    Int_t  mode   = 0;
+    for (Int_t ibin = 1+reach; ibin <= fHistADC2PhotEl->GetNbinsX()-reach; ibin++)
+    {
+        const Stat_t sum = fHistADC2PhotEl->Integral(ibin-reach, ibin+reach);
+
+        if (sum <= summax)
+            continue;
+
+        summax = sum;
+        mode = ibin;
+    }
+
+    fADC2PhotEl = TMath::Power(10, fHistADC2PhotEl->GetBinCenter(mode));
+
+    const Int_t num = fCalCam->GetSize();
+
+    for (int i=0; i<num; i++)
+    {
+        MCalibrationChargePix &calpix = (MCalibrationChargePix&)(*fCalCam)[i];
+	MCalibrationQEPix     &qepix  = (MCalibrationQEPix&)    (*fQECam) [i];
+
+	Float_t qe = fPhot2PhotEl;
+	if (fGeom->GetPixRatio(i) < 1.)
+	  qe *= fOuterPixelsLightCollection;
+	qepix.SetAverageQE(qe);
+
+	qepix.SetAvNormFFactor(1.);
+	// This factor should convert the default average QE for different colors to 
+        // average QE for a spectrum like that of Cherenkov light (see the documentration 
+	// of MCalibrationQEPix). 
+	// Here we obtain average QE using already a Cherenkov spectrum so AvNormFFactor
+	// must be 1.
+
+	
+	Float_t factor = fADC2PhotEl;
+
+	//
+	// We take into account the (possibly) different gain of outer pixels:
+	// FIXME: we are now assuming that all inner pixels have the same gain, and all 
+	// outer pixels have the same gain (different from inner ones though). This can 
+        // only be like this in camera 0.7, but may change in future versions of camera.
+	//
+
+	if (fGeom->GetPixRatio(i) < 1.)
+	  factor *= fHeaderFadc->GetAmplitud()/fHeaderFadc->GetAmplitudOuter();
+
+        calpix.SetMeanConvFADC2Phe(factor);
+        calpix.SetMeanConvFADC2PheVar(0.);
+
+        calpix.SetMeanFFactorFADC2Phot(0.);
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mcalib/MMcCalibrationCalc.h
===================================================================
--- /tags/Mars-V0.9/mcalib/MMcCalibrationCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/MMcCalibrationCalc.h	(revision 9772)
@@ -0,0 +1,55 @@
+#ifndef MARS_MMcCalibrationCalc
+#define MARS_MMcCalibrationCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MGeomCam;
+class MHillas;
+class MImagePar;
+class MNewImagePar;
+class MMcEvt;
+class MMcFadcHeader;
+
+class TH1F;
+
+class MMcCalibrationCalc : public MTask
+{
+private:
+    MCalibrationChargeCam     *fCalCam;
+    MCalibrationQECam         *fQECam;    
+    MGeomCam                  *fGeom;
+    MHillas                   *fHillas;
+    MNewImagePar              *fNew;
+    MImagePar                 *fPar;
+    MMcEvt                    *fMcEvt;
+    MMcFadcHeader             *fHeaderFadc;
+
+    Float_t fADC2PhotEl;   // Conversion factor (photel / ADC count). FOR INER PIXELS
+    Float_t fPhot2PhotEl;  // Conversion factor (photons / photoelectron) = average QE. FOR INER PIXELS
+    Long_t  fEvents;
+    Float_t fOuterPixelsLightCollection; // Light collection efficiency (plexiglas, light guide) of 
+                                         // outer pixels w.r.t inner ones
+
+    TH1F*   fHistADC2PhotEl;
+    TH1F*   fHistPhot2PhotEl; // Histograms for monitoring the calibration.
+
+    Bool_t CheckRunType(MParList *pList) const;
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MMcCalibrationCalc(const char *name=NULL, const char *title=NULL);
+
+    TH1F*   GetHistADC2PhotEl() { return fHistADC2PhotEl; }
+    TH1F*   GetHistPhot2PhotEl() { return fHistPhot2PhotEl; }
+
+    ClassDef(MMcCalibrationCalc, 0)   // Task which obtains, for MC files, the calibration factor from ADC counts to photons. 
+};
+
+#endif
Index: /tags/Mars-V0.9/mcalib/Makefile
===================================================================
--- /tags/Mars-V0.9/mcalib/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mcalib/Makefile	(revision 9772)
@@ -0,0 +1,79 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Calib
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../mhcalib -I../mhbase \
+           -I../manalysis -I../mraw -I../mtools -I../mmc -I../mhist  \
+           -I../mimage -I../msignal -I../mbadpixels -I../mpedestal 
+# mhbase:    MBinning MH 
+# mgui:      MCamEvent (McalibrationCam)
+# mgeom:     MGeomCam (McalibrationCam - necessary?)
+# manalysis: MExtractedSignal, MCerPhotEvt (move to mcalib?)
+# mraw:      MRawRunHeader, MRawEvtHeader, MRawEvtPixelIter (3xMCalibrationCalc)
+# mmc:       MMcFadcHeader, MMcEvt
+# mimage     MHillas
+
+SRCFILES = MCalibColorSet.cc \
+	   MCalibColorSteer.cc \
+	   MCalibCalcFromPast.cc \
+	   MCalibrateData.cc \
+	   MCalibConstCam.cc \
+	   MCalibConstPix.cc \
+	   MCalibrationPattern.cc \
+	   MCalibrationPatternDecode.cc \
+	   MCalibrateRelTimes.cc \
+           MCalibrationIntensityCam.cc \
+           MCalibrationIntensityChargeCam.cc \
+           MCalibrationIntensityBlindCam.cc \
+           MCalibrationIntensityQECam.cc \
+           MCalibrationIntensityRelTimeCam.cc \
+           MCalibrationIntensityTestCam.cc \
+           MCalibrationCam.cc \
+           MCalibrationPix.cc  \
+           MCalibrationPulseTimeCam.cc \
+           MCalibrationRelTimeCam.cc \
+           MCalibrationRelTimePix.cc \
+	   MCalibrationRelTimeCalc.cc \
+           MCalibrationQECamMagic.cc \
+           MCalibrationQECam.cc \
+           MCalibrationQEPix.cc  \
+           MCalibrationPedCam.cc \
+	   MCalibrationTestCalc.cc \
+	   MCalibrationTestCam.cc \
+	   MCalibrationTestPix.cc \
+	   MCalibrationHiLoCam.cc \
+	   MCalibrationHiLoPix.cc \
+	   MCalibrationChargeCalc.cc \
+           MCalibrationChargeCam.cc \
+           MCalibrationChargePix.cc  \
+           MCalibrationBlindCam.cc  \
+           MCalibrationBlindPix.cc  \
+           MCalibrationBlindCamOneOldStyle.cc  \
+           MCalibrationBlindCamTwoNewStyle.cc  \
+           MCalibrationBlindCamThreeNewStyle.cc  \
+           MCalibrationChargePINDiode.cc  \
+	   MMcCalibrationCalc.cc 
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mcamera/CameraIncl.h
===================================================================
--- /tags/Mars-V0.9/mcamera/CameraIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/CameraIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mcamera/CameraLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mcamera/CameraLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/CameraLinkDef.h	(revision 9772)
@@ -0,0 +1,17 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MCameraCooling+;
+#pragma link C++ class MCameraAUX+;
+#pragma link C++ class MCameraLid+;
+#pragma link C++ class MCameraLids+;
+#pragma link C++ class MCameraHV+;
+#pragma link C++ class MCameraLV+;
+#pragma link C++ class MCameraDC+;
+#pragma link C++ class MCameraCalibration+;
+#pragma link C++ class MCameraPowerSupply+;
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraAUX.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraAUX.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraAUX.cc	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraAUX
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraAUX.h"
+
+ClassImp(MCameraAUX);
+
+using namespace std;
Index: /tags/Mars-V0.9/mcamera/MCameraAUX.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraAUX.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraAUX.h	(revision 9772)
@@ -0,0 +1,32 @@
+#ifndef MARS_MCameraAUX
+#define MARS_MCameraAUX
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCameraAUX : public MParContainer
+{
+    friend class MReportCamera;
+private:
+    Bool_t fRequestCaosLEDs; // Requested status: o=off, 1=on, bAux_CaOsLEDs_Off/On
+    Bool_t fRequestFansFADC; // Requested status: o=off, 1=on, bAux_FADC_FANs_Off/On
+    Bool_t fStatusCaosLEDs;  // Monitored status: o=off, 1=on, Cam.CaOs.LED_state
+    Bool_t fStatusFansFADC;  // Monitored status: o=off, 1=on, Cam.FADC.Fans_state
+
+public:
+    MCameraAUX()
+    {
+        fName  = "MCameraAUX";
+        fTitle = "Container storing information about the Camera auxiliary system";
+    }
+
+    Bool_t GetRequestCaosLEDs() const { return fRequestCaosLEDs; }
+    Bool_t GetRequestFansFADC() const { return fRequestFansFADC; }
+    Bool_t GetStatusCaosLEDs() const  { return fStatusCaosLEDs;  }
+    Bool_t GetStatusFansFADC() const  { return fStatusFansFADC;  }
+
+    ClassDef(MCameraAUX, 1) // Container storing information about the Camera auxiliary system
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraCalibration.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraCalibration.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraCalibration.cc	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraCalibration
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraCalibration.h"
+
+ClassImp(MCameraCalibration);
+
+using namespace std;
Index: /tags/Mars-V0.9/mcamera/MCameraCalibration.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraCalibration.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraCalibration.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MCameraCalibration
+#define MARS_MCameraCalibration
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCameraCalibration : public MParContainer
+{
+    friend class MReportCamera;
+private:
+    Byte_t fStatus;           // CaCo monitored calibration state: o=off, 1=on, CamCalib_state
+    Byte_t fStatusCANbus;     // CaCo monitored CANbus state: o=off, 1=on, Cal.CanBus_state
+    Byte_t fStatusIO;         // CaCo monitored I/O state: o=off, 1=on, Cal.IO_state
+    Byte_t fStatusLoVoltage;  // CaCo monitored LV PS state: o=off, 1=on, Cal.LV_state
+
+    Bool_t fRequestHiVoltage; // Requested status: o=off, 1=on, bcalib_HV_Off/On
+    Bool_t fRequestLoVoltage; // Requested status: o=off, 1=on, bcalib_LV_Off/On
+    Bool_t fRequestContLight; // Requested status: o=off, 1=on, bcalib_ContinuousLight_Off/On
+    Bool_t fRequestPinDiode;  // Requested status: o=off, 1=on, bcalib_PinDiode_Off/On
+
+public:
+    MCameraCalibration()
+    {
+        fName  = "MCameraCalibration";
+        fTitle = "Container storing information about the Camera calibration system";
+    }
+
+    Byte_t GetStatus() const           { return fStatus; }
+    Byte_t GetStatusCANbus() const     { return fStatusCANbus; }
+    Byte_t GetStatusIO() const         { return fStatusIO; }
+    Byte_t GetStatusLoVoltage() const  { return fStatusLoVoltage; }
+
+    Bool_t GetRequestHiVoltage() const { return fRequestHiVoltage; }
+    Bool_t GetRequestLoVoltage() const { return fRequestLoVoltage; }
+    Bool_t GetRequestContLight() const { return fRequestContLight; }
+    Bool_t GetRequestPinDiode() const  { return fRequestPinDiode; }
+
+    ClassDef(MCameraCalibration, 1) // Container storing information about the Camera calibration system
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraCooling.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraCooling.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraCooling.cc	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraCooling
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraCooling.h"
+
+ClassImp(MCameraCooling);
+
+using namespace std;
Index: /tags/Mars-V0.9/mcamera/MCameraCooling.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraCooling.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraCooling.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MCameraCooling
+#define MARS_MCameraCooling
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCameraCooling : public MParContainer
+{
+    friend class MReportCamera;
+private:
+    Byte_t  fStatus;              // CaCo Monitored cooling status: 0-9, Cam.COOLING_state
+
+    Bool_t  fStatusPressureHi;    // 0=ok,  1=Obstruct
+    Bool_t  fStatusPressureLo;    // 0=ok,  1=leakage
+    Bool_t  fStatusPump;          // 0=off, 1=on
+    Bool_t  fStatusRefrigrerator; // 0=off, 1=on
+    Bool_t  fStatusValve;         // 0=recirculate, 1=new
+    Bool_t  fStatusResistor;      // 0=off, 1=on
+    Bool_t  fStatusFans;          // 0=off, 1=on
+
+    Float_t fTempCenter;          // [deg C] Temperature at the camera center
+    Float_t fTempWall;            // [deg C] Temperature at the camera wall
+    Float_t fTempOptLink;         // [deg C] Temperature at the optical link
+    Float_t fTempWater;           // [deg C] Temperature of the water in the water tank
+
+    Byte_t  fHumWall;             // [%] Relative humidity at camera wall
+    Byte_t  fHumCenter;           // [%] Relative humidity camera center
+
+public:
+    MCameraCooling()
+    {
+        fName  = "MCameraCooling";
+        fTitle = "Container storing information about the Camera cooling system";
+    }
+
+    Byte_t  GetStatus() const              { return fStatus;              }
+
+    Bool_t  GetStatusPressureHi() const    { return fStatusPressureHi;    }
+    Bool_t  GetStatusPressureLo() const    { return fStatusPressureLo;    }
+    Bool_t  GetStatusPump() const          { return fStatusPump;          }
+    Bool_t  GetStatusRefrigrerator() const { return fStatusRefrigrerator; }
+    Bool_t  GetStatusValve() const         { return fStatusValve;         }
+    Bool_t  GetStatusResistor() const      { return fStatusResistor;      }
+    Bool_t  GetStatusFans() const          { return fStatusFans;          }
+
+    Float_t GetTempCenter() const          { return fTempCenter;          }
+    Float_t GetTempWall() const            { return fTempWall;            }
+    Float_t GetTempOptLink() const         { return fTempOptLink;         }
+    Float_t GetTempWater() const           { return fTempWater;           }
+
+    Byte_t  GetHumWall() const             { return fHumWall;             }
+    Byte_t  GetHumCenter() const           { return fHumCenter;           }
+
+    ClassDef(MCameraCooling, 1) // Container storing information about the Camera cooling
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraDC.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraDC.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraDC.cc	(revision 9772)
@@ -0,0 +1,86 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraDC (PRELIMINARY)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraDC.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCameraDC);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCameraDC::MCameraDC(Int_t size, const char *name, const char *title)
+    : fArray(size)
+{
+    fName  = name  ? name  : "MCameraDC";
+    fTitle = title ? title : "Storage container for the pixel currents";
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the dc currents
+//
+void MCameraDC::Print(Option_t *) const
+{
+    *fLog << all << underline << GetDescriptor() << endl;
+    for (int i=0; i<fArray.GetSize(); i++)
+        *fLog << " " << GetCurrent(i);
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the minimum dc current
+//
+Float_t MCameraDC::GetMin() const
+{
+    Float_t val = (UInt_t)-1;
+    for (int i=0; i<fArray.GetSize(); i++)
+        val = TMath::Min(val, GetCurrent(i));
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the maximum dc current
+//
+Float_t MCameraDC::GetMax() const
+{
+    Float_t val = 0;
+    for (int i=0; i<fArray.GetSize(); i++)
+        val = TMath::Max(val, GetCurrent(i));
+    return val;
+}
Index: /tags/Mars-V0.9/mcamera/MCameraDC.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraDC.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraDC.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MCameraDC
+#define MARS_MCameraDC
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MCameraDC : public MParContainer, public MCamEvent
+{
+private:
+    TArrayF fArray; // [nA] Unsigned Int!
+
+public:
+    MCameraDC(Int_t size=577, const char *name=NULL, const char *title=NULL);
+
+    void SetCurrent(Int_t i, Float_t val) { fArray[i] = (Int_t)val; }
+    Float_t GetCurrent(Int_t i) const { return (*this)[i]; }
+    Float_t &operator[](Int_t i) { return (Float_t&)fArray[i]; }
+    const Float_t &operator[](Int_t i) const { return (*const_cast<MCameraDC*>(this))[i]; }
+
+    Float_t GetMin() const;
+    Float_t GetMax() const;
+
+    void Print(Option_t *opt=NULL) const;
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+        val = fArray[idx];
+        return val>0;
+    }
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MCameraDC, 1) // Storage Container for the Currents (PRELIMINARY)
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraHV.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraHV.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraHV.cc	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraHV
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraHV.h"
+
+ClassImp(MCameraHV);
+
+using namespace std;
Index: /tags/Mars-V0.9/mcamera/MCameraHV.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraHV.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraHV.h	(revision 9772)
@@ -0,0 +1,63 @@
+#ifndef MARS_MCameraHV
+#define MARS_MCameraHV
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class MCameraHV : public MParContainer, public MCamEvent
+{
+    friend class MReportCamera;
+private:
+    Byte_t  fStatus;        // CaCo monitored status of the High Voltage [0-9], Cam.HV.PS_state
+    Bool_t  fStatusRamping; // CaCo monitored status of ramping the HV, Cam.HV_state
+
+    Short_t fVoltageA;      // [V] Measured voltage of power supply A, hvps1
+    Short_t fVoltageB;      // [V] Measured voltage of power supply B, hvps2
+
+    Byte_t fCurrentA;       // [mA] Measured current of power supply A, curr1
+    Byte_t fCurrentB;       // [mA] Measured current of power supply B, curr2
+
+    TArrayS fHV;            // [V] Measured high Voltages for all PMTs
+
+public:
+    MCameraHV() : fHV(577)
+    {
+        fName  = "MCameraHV";
+        fTitle = "Container storing information about the Camera HV";
+    }
+
+    Byte_t  GetStatus() const { return fStatus; }
+    Bool_t  GetStatusRamping() const { return fStatusRamping; }
+
+    Short_t GetVoltageA() const { return fVoltageA; }
+    Short_t GetVoltageB() const { return fVoltageB; }
+
+    Byte_t  GetCurrentA() const { return fCurrentA; }
+    Byte_t  GetCurrentB() const { return fCurrentB; }
+
+    Float_t GetMean() const { return fHV.GetSum()/fHV.GetSize(); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+        val = fHV[idx];
+        return val>0;
+    }
+
+    Double_t operator[](const UInt_t idx) { return fHV[idx]; }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MCameraHV, 1) // Container storing information about the Camera HV
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraLV.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraLV.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraLV.cc	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraLV
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraLV.h"
+
+ClassImp(MCameraLV);
+
+using namespace std;
Index: /tags/Mars-V0.9/mcamera/MCameraLV.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraLV.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraLV.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MCameraLV
+#define MARS_MCameraLV
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCameraPowerSupply
+#include <MCameraPowerSupply.h>
+#endif
+
+class MCameraLV : public MParContainer
+{
+    friend class MReportCamera;
+private:
+    Byte_t  fStatus;                  // CaCo monitored LV PS status:  , Cam.LV_state
+    Bool_t  fRequestPowerSupply;      // Requested status: o=off, 1=on, blv_ps_status
+
+    Float_t fTemp;                    // Measured status: o=off, 1=on, blv_temp
+    Byte_t  fHumidity;                // Measured status: o=off, 1=on, blv_RelativeHumidity
+
+    MCameraPowerSupply fPowerSupplyA; // power supply camera part A
+    MCameraPowerSupply fPowerSupplyB; // power supply camera part B
+
+public:
+    MCameraLV()
+    {
+        fName  = "MCameraLV";
+        fTitle = "Container storing information about the Camera LV";
+    }
+
+    Byte_t  GetStatus() const { return fStatus; }
+    Bool_t  GetRequestPowerSupply() const { return fRequestPowerSupply; }
+
+    Float_t GetTemp() const { return fTemp; }
+    Byte_t  GetHumidity() const { return fHumidity; }
+
+    const MCameraPowerSupply &GetPowerSupplyA() const { return fPowerSupplyA; }
+    const MCameraPowerSupply &GetPowerSupplyB() const { return fPowerSupplyB; }
+
+    ClassDef(MCameraLV, 1) // Container storing information about the Camera LV
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraLid.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraLid.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraLid.cc	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraLid
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraLid.h"
+
+ClassImp(MCameraLid);
+
+using namespace std;
Index: /tags/Mars-V0.9/mcamera/MCameraLid.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraLid.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraLid.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MCameraLid
+#define MARS_MCameraLid
+
+// Derived from MParContainer instead of TObject
+// to supress writing fUniqueId and fBits
+#ifndef MARS_MParContainer
+#include <MParContainer.h>
+#endif
+
+class MCameraLid : public MParContainer
+{
+    friend class MReportCamera;
+private:
+     Bool_t fLimitOpen;        // 0=not active, 1= active
+     Bool_t fLimitClose;       // 0=not active, 1= active
+
+     Bool_t fSafetyLimitOpen;  // 0=not active, 1= active
+     Bool_t fSafetyLimitClose; // 0=not active, 1= active
+
+     Byte_t fStatusLid;        // 0=positioning, 1=open, 2=closed
+     Byte_t fStatusMotor;      // 0=stopped, 1=opening, 2=closing
+
+public:
+    MCameraLid()
+    {
+        fName  = "MCameraLid";
+        fTitle = "Container storing information about a Camera lid";
+    }
+
+    Bool_t GetLimitOpen() const        { return fLimitOpen;        }
+    Bool_t GetLimitClose() const       { return fLimitClose;       }
+
+    Bool_t GetSafetyLimitOpen() const  { return fSafetyLimitOpen;  }
+    Bool_t GetSafetyLimitClose() const { return fSafetyLimitClose; }
+
+    Byte_t GetStatusLid() const        { return fStatusLid;        }
+    Byte_t GetStatusMotor() const      { return fStatusMotor;      }
+
+    ClassDef(MCameraLid, 1) // Container storing information about a Camera lid
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraLids.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraLids.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraLids.cc	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraLids
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraLids.h"
+
+ClassImp(MCameraLids);
+
+using namespace std;
Index: /tags/Mars-V0.9/mcamera/MCameraLids.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraLids.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraLids.h	(revision 9772)
@@ -0,0 +1,35 @@
+#ifndef MARS_MCameraLids
+#define MARS_MCameraLids
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCameraLid
+#include "MCameraLid.h"
+#endif
+
+class MCameraLids : public MParContainer
+{
+    friend class MReportCamera;
+private:
+    MCameraLid fLidA;
+    MCameraLid fLidB;
+
+    Byte_t fStatus; // CaCo monitored lid status, Cam.LID_state [0-9]
+public:
+    MCameraLids()
+    {
+        fName  = "MCameraLids";
+        fTitle = "Container storing information about the Camera lids";
+    }
+
+    Byte_t GetStatus() const { return fStatus; }
+
+    const MCameraLid &GetLidA() const { return fLidA; }
+    const MCameraLid &GetLidB() const { return fLidB; }
+
+    ClassDef(MCameraLids, 1) // Container storing information about the Camera lids
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/MCameraPowerSupply.cc
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraPowerSupply.cc	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraPowerSupply.cc	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraPowerSupply
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraPowerSupply.h"
+
+ClassImp(MCameraPowerSupply);
+
+using namespace std;
Index: /tags/Mars-V0.9/mcamera/MCameraPowerSupply.h
===================================================================
--- /tags/Mars-V0.9/mcamera/MCameraPowerSupply.h	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/MCameraPowerSupply.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MCameraPowerSupply
+#define MARS_MCameraPowerSupply
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCameraPowerSupply : public MParContainer
+{
+    friend class MReportCamera;
+private:
+    Float_t fVoltagePos5V;         // [V] voltage_pos5  (+5V)
+    Float_t fVoltagePos12V;        // [V] voltage_pos12 (+12V)
+    Float_t fVoltageNeg12V;        // [V] voltage_neg12 (-12V)
+    Float_t fVoltageOptLinkPos12V; // [V] volatge_opt_link_pos12 (+12V)
+
+    Float_t fCurrentPos5V;         // [A] current_pos5  (+5V)
+    Float_t fCurrentPos12V;        // [A] current_pos12 (+12V)
+    Float_t fCurrentNeg12V;        // [A] current_neg12 (-12V)
+    Float_t fCurrentOptLinkPos12V; // [A] current_opt_link_pos12 (+12V)
+
+public:
+    MCameraPowerSupply()
+    {
+        fName  = "MCameraPowerSupply";
+        fTitle = "Container storing information about the Camera power supply";
+    }
+
+    Float_t GetVoltagePos5V() const         { return fVoltagePos5V; }
+    Float_t GetVoltagePos12V() const        { return fVoltagePos12V; }
+    Float_t GetVoltageNeg12V() const        { return fVoltageNeg12V; }
+    Float_t GetVoltageOptLinkPos12V() const { return fVoltageOptLinkPos12V; }
+
+    Float_t GetCurrentPos5V() const         { return fCurrentPos5V; }
+    Float_t GetCurrentPos12V() const        { return fCurrentPos12V; }
+    Float_t GetCurrentNeg12V() const        { return fCurrentNeg12V; }
+    Float_t GetCurrentOptLinkPos12V() const { return fCurrentOptLinkPos12V; }
+
+    ClassDef(MCameraPowerSupply, 1) // Container storing information about the Camera power supply
+};
+
+#endif
Index: /tags/Mars-V0.9/mcamera/Makefile
===================================================================
--- /tags/Mars-V0.9/mcamera/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mcamera/Makefile	(revision 9772)
@@ -0,0 +1,40 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Camera
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui
+# mgui - MCameraDC <MCamEvent>
+
+SRCFILES = MCameraAUX.cc \
+	   MCameraCalibration.cc\
+	   MCameraCooling.cc \
+	   MCameraHV.cc \
+	   MCameraLV.cc \
+	   MCameraDC.cc \
+	   MCameraLid.cc \
+	   MCameraLids.cc \
+	   MCameraPowerSupply.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mdata/DataIncl.h
===================================================================
--- /tags/Mars-V0.9/mdata/DataIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/DataIncl.h	(revision 9772)
@@ -0,0 +1,10 @@
+#ifndef __CINT__
+
+//#include <fstream>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include <TGListBox.h>
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mdata/DataLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mdata/DataLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/DataLinkDef.h	(revision 9772)
@@ -0,0 +1,16 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MData+;
+#pragma link C++ class MDataArray+;
+#pragma link C++ class MDataElement+;
+#pragma link C++ class MDataList+;
+#pragma link C++ class MDataValue+;
+#pragma link C++ class MDataMember+;
+#pragma link C++ class MDataChain+;
+#pragma link C++ class MDataFormula+;
+
+#endif
Index: /tags/Mars-V0.9/mdata/MData.cc
===================================================================
--- /tags/Mars-V0.9/mdata/MData.cc	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MData.cc	(revision 9772)
@@ -0,0 +1,86 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MData
+//
+//   This base class defines an interface to a generalized value.
+//   This value can be a simple number, it can also be a data member
+//   of a class or some kind of concatenation of MData objects.
+//
+//   A class inheriting from MData must implement:
+//
+//    - Double_t GetValue() const
+//      which return the value corresponding to the object
+//
+//    - Bool_t IsValid() const
+//      should tell whether the object is valid (eg if the object parses
+//      a string the result might be invalid)
+//
+//    - Bool_t PreProcess(const MParList *plist)
+//      which can be used to get some necessary data (befor processing)
+//      from the parlist.
+//
+//    - TString GetRule()
+//      returns the rule as a text which would recreate the same structure
+//      when used in a MDataChain
+//
+//    - TString GetDataMember()
+//      returns the names (seperated by a comma) used by this class. This
+//      is mainly used for the AutoScheme when reading data from a file.
+//      (s.MReadTree)
+//
+//    - void SetVariables(const TArrayD &arr)
+//      is used to distribute variable numbers through lists holding
+//      MDatas to its counterpart (mainly to MDataValue)
+//
+//   The 'must' ist represented by the =0 in the class header. In the C++
+//   language this is called an abstract member function. Because the
+//   class contains abstract member function which makes it impossible
+//   to create an instance of this class one calls it also:
+//   abstract base class
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MData.h"
+
+#include <fstream>
+
+#include "MLog.h"
+
+ClassImp(MData);
+
+using namespace std;
+
+Bool_t MData::AsciiWrite(ostream &out) const
+{
+    out << GetValue() << " ";
+    return kTRUE;
+}
+
+void MData::Print(Option_t *opt) const
+{
+    *fLog << GetRule() << flush;
+}
Index: /tags/Mars-V0.9/mdata/MData.h
===================================================================
--- /tags/Mars-V0.9/mdata/MData.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MData.h	(revision 9772)
@@ -0,0 +1,33 @@
+#ifndef MARS_MData
+#define MARS_MData
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MData                                                                  //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MParList;
+
+class MData : public MParContainer
+{
+public:
+    virtual Double_t GetValue() const = 0;
+    virtual Bool_t   IsValid() const = 0;
+    virtual Bool_t   PreProcess(const MParList *plist) = 0;
+    virtual TString  GetRule() const = 0;
+    virtual TString  GetDataMember() const { return ""; }
+
+    Double_t operator()() { return GetValue(); }
+
+    void Print(Option_t *opt = "") const;
+    Bool_t AsciiWrite(ostream &out) const;
+
+    ClassDef(MData, 0) // A Base class for a generalized value
+};
+
+#endif
Index: /tags/Mars-V0.9/mdata/MDataArray.cc
===================================================================
--- /tags/Mars-V0.9/mdata/MDataArray.cc	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataArray.cc	(revision 9772)
@@ -0,0 +1,242 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  08/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MDataArray
+//
+//   An Array of MData derived classes.
+//   It can be used, eg, in MHMatrix for description of the columns.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataArray.h"
+
+#include <fstream>
+
+#include <TVector.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDataChain.h"
+
+ClassImp(MDataArray);
+
+using namespace std;
+
+static const TString gsDefName  = "MDataArray";
+static const TString gsDefTitle = "Array to store MData cntainers";
+
+// --------------------------------------------------------------------------
+//
+// Constructor
+//
+MDataArray::MDataArray(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    gROOT->GetListOfCleanups()->Add(&fList);
+    fList.SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new data rule as a new entry (MDataChain)
+//
+void MDataArray::AddEntry(const TString rule)
+{
+    TObject *obj = new MDataChain(rule);
+    obj->SetBit(kCanDelete);
+    fList.Add(obj);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new data as a new entry (MData). If the destructor of MDataArray
+// should delete the object set its bit kCanDelete
+//
+void MDataArray::AddEntry(MData *data)
+{
+    data->SetBit(kMustCleanup);
+    fList.Add(data);
+}
+
+// --------------------------------------------------------------------------
+//
+// Try to find a MData which has the same rule (GetRule()).
+// Be carefull: This may already fail if the rule is A*B and you are
+// searching for B*A - FIXME: A more intelligent comaparton (based on
+// IsEqual()) should be developed.
+//
+// Returns the index in the array, -1 if rule was not found.
+//
+Int_t MDataArray::FindRule(const char *rule) const
+{
+    const MDataChain data(rule);
+    if (!data.IsValid())
+        return -1;
+
+    const TString r(data.GetRule());
+
+    TIter Next(&fList);
+    const MData *d = NULL;
+    while ((d=(MData*)Next()))
+        if (d->GetRule()==r)
+            return fList.IndexOf(d);
+
+    return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the i-th entry
+//
+MData &MDataArray::operator[](Int_t i) const
+{
+    return (MData&)*((TObjArray)fList)[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data value of the i-th entry
+//
+Double_t MDataArray::operator()(Int_t i) const
+{
+    return (*this)[i].GetValue();
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcesses all members in the list
+//
+Bool_t MDataArray::PreProcess(const MParList *plist)
+{
+    if (fList.GetSize()==0)
+    {
+        *fLog << err << "Error - No Column specified... aborting." << endl;
+        return kFALSE;
+    }
+
+    TIter Next(&fList);
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+        if (!data->PreProcess(plist))
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the rules for all entries of the array
+//
+void MDataArray::Print(Option_t *opt) const
+{
+    Int_t n=0;
+
+    const Int_t w = 1+(Int_t)TMath::Log10(fList.GetEntries());
+
+    TIter Next(&fList);
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+    {
+        *fLog << all << " " << fName << "[" << setw(w) << n++ << "] = " << flush;
+        data->Print();
+        *fLog << endl;
+    }
+}
+
+Bool_t MDataArray::AsciiWrite(ostream &out) const
+{
+    ((TObjArray)fList).ForEach(MParContainer, AsciiWrite)(out);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MDataArray::StreamPrimitive(ofstream &out) const
+{
+    out << "   MDataArray " << GetUniqueName();
+
+    if (fName!=gsDefName)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\")";
+    }
+    out << ";" << endl;
+
+    TIter Next(&fList);
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+        out << "   " << GetUniqueName() << ".AddEntry(\"" << data->GetRule() << "\");" << endl;
+}
+
+TString MDataArray::GetRule(int i) const
+{
+    return (*this)[i].GetRule();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data members existing in this array in a comma-seperated list
+// (This is mainly used for MTask::AddToBranchList)
+//
+TString MDataArray::GetDataMember() const
+{
+    TString str;
+
+    TIter Next(&fList);
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+    {
+        if (data->GetDataMember().IsNull())
+            continue;
+
+        str += ",";
+        str += data->GetDataMember();
+    }
+    return str;
+}
+
+void MDataArray::GetData(TVector &v) const
+{
+    Int_t ncols = GetNumEntries();
+
+    v.ResizeTo(ncols);
+
+    // same as: for (int i=0; i<ncols; i++) <should be faster>
+    while (ncols--)
+        v(ncols) = (*this)(ncols);
+}
+
+void MDataArray::SetVariables(const TArrayD &arr)
+{
+    fList.ForEach(MData, SetVariables)(arr);
+}
Index: /tags/Mars-V0.9/mdata/MDataArray.h
===================================================================
--- /tags/Mars-V0.9/mdata/MDataArray.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataArray.h	(revision 9772)
@@ -0,0 +1,65 @@
+#ifndef MARS_MDataArray
+#define MARS_MDataArray
+
+/////////////////////////////////////////////////////////////////////////////
+//              
+//  MDataArray  
+//
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class TVector;
+
+class MData;
+class MParList;
+
+class MDataArray : public MParContainer
+{
+    TObjArray fList;
+
+    void StreamPrimitive(ofstream &out) const;
+
+public:
+    MDataArray(const char *name=NULL, const char *title=NULL);
+
+    void AddEntry(const TString rule);
+    void AddEntry(MData *data);
+
+    Int_t FindRule(const char *rule) const;
+
+    MData &operator[](Int_t i) const;
+    Double_t operator()(Int_t i) const;
+
+    void GetData(TVector &v) const;
+
+    void operator>>(TVector &v) const
+    {
+        GetData(v);
+    }
+
+    TString GetRule(int i) const;
+
+    Bool_t PreProcess(const MParList *plist);
+
+    TString GetDataMember() const;
+
+    void Print(Option_t *opt = "") const;
+    Bool_t AsciiWrite(ostream &out) const;
+
+    Int_t GetNumEntries() const { return fList.GetEntries(); }
+
+    void Clear(Option_t *option="")  { fList.Clear(option); }
+    void Delete(Option_t *option="") { fList.Delete(option); }
+
+    void SetVariables(const TArrayD &arr);
+
+    ClassDef(MDataArray, 1) // An array of MData containers
+};
+
+#endif
Index: /tags/Mars-V0.9/mdata/MDataChain.cc
===================================================================
--- /tags/Mars-V0.9/mdata/MDataChain.cc	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataChain.cc	(revision 9772)
@@ -0,0 +1,935 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MDataChain
+// ==========
+//
+// With this chain you can concatenate simple mathematical operations on
+// members of mars containers.
+//
+//
+// Rules
+// -----
+//
+// In the constructor you can give rule, like
+//   "HillasSource.fDist / MHillas.fLength"
+// Where MHillas/HillasSource is the name of the parameter container in
+// the parameter list and fDist/fLength is the name of the data members
+// in the containers. The result will be fDist divided by fLength.
+//
+// In case you want to access a data-member which is a data member object
+// you can acces it with (Remark: it must derive from MParContainer):
+//   "MCameraLV.fPowerSupplyA.fVoltagePos5V"
+//
+// You can also use parantheses:
+//   "HillasDource.fDist / (MHillas.fLength + MHillas.fWidth)"
+//
+//
+// Operators
+// ---------
+//
+// The allowed operations are: +, -, *, /, %, ^ and ** for ^
+//
+// While a%b returns the floating point reminder of a/b.
+// While a^b returns a to the power of b
+//
+// Priority
+// --------
+//
+//  The priority of the operators is build in as:
+//    ^ (highest),  %, *, /, +, -
+//
+//  Priorities are evaluated before parsing the rule by inserting
+//  artificial paranthesis. If you find ANY problem with this please
+//  report it immediatly! It is highly recommended to check the result!
+//
+// You can also use mathmatical operators, eg:
+//   "5*log10(MMcEvt.fEnergy*MHillas.fSize)"
+//
+// The allowed operators are:
+//   exp(x)    e^x
+//   log(x)    natural logarithm of x
+//   pow10(x)  10^x
+//   log2(x)   logarithm of x to base two
+//   log10(x)  logarithm of x to base ten
+//   cos(x)    cosine of x
+//   sin(x)    sine of x
+//   tan(x)    tangent of x
+//   cosh(x)   hyperbolic cosine of x
+//   sinh(x)   hyperbolic sine of x
+//   tanh(x)   hyperbolic tangent of x
+//   acosh(x)  arc hyperbolic cosine of x
+//   asinh(x)  arc hyperbolic sine of x
+//   atanh(x)  arc hyperbolic tangent of x
+//   acos(x)   arc cosine (inverse cosine) of x
+//   asin(x)   arc sine (inverse sine) of x
+//   atan(x)   arc tangent (inverse tangent) of x
+//   sqrt(x)   square root of x
+//   sqr(x)    square of x
+//   abs(x)    absolute value of x, |x|
+//   floor(x)  round down to the nearest integer (floor(9.9)=9)
+//   ceil(x)   round up   to the nearest integer (floor(9.1)=10)
+//   round(x)  round      to the nearest integer
+//   r2d(x)    transform radians to degrees
+//   d2r(x)    transform degrees to radians
+//   rand(x)   returns a uniform deviate on the interval ( 0, x ].
+//             (gRandom->Uniform(x) is returned)
+//   randp(x)  returns gRandom->Poisson(x)
+//   rande(x)  returns gRandom->Exp(x)
+//   randi(x)  returns gRandom->Integer(x)
+//   randg(x)  returns gRandom->Gaus(0, x)
+//   randl(x)  returns gRandom->Landau(0, x)
+//   isnan(x)  return 1 if x is NaN (Not a Number) otherwise 0
+//   finite(x) return 1 if the number is a valid double (not NaN, inf)
+//
+// NaN (Not a Number) means normally a number which is to small to be
+// stored in a floating point variable (eg. 0<x<1e-56 or similar) or
+// a number which function is not defined (like asin(1.5))
+//
+// inf is the symbol for an infinite number.
+//
+//
+// Constants
+// ---------
+//
+// Constants are implemented in ParseDataMember, namely:
+//   kPi:       TMath::Pi()
+//   kRad2Deg:  180/kPi
+//   kDeg2Rad:  kPi/180
+//
+// You can also defined constants which are defined in TMath by:
+//   kLn10       for   static Double_t TMath::Ln10();
+//   kLogE       for   static Double_t TMath::LogE();
+//   kRadToDeg   for   static Double_t TMath::RadToDeg();
+//   kDegToRad   for   static Double_t TMath::DegToRad();
+//   ...
+//
+// Remark:
+//  In older root versions only Pi() and E() are implemented
+//  in TMath.
+//
+//
+// Variable Parameters
+// ------------------------
+// If you want to use variables, eg for fits you can use [0], [1], ...
+// These values are initialized with 0 and set by calling
+// SetVariables().
+//
+//
+// Multi-argument functions
+// ------------------------
+// You can use multi-argument functions, too. The access is implemented
+// via TFormula, which slows down thing a lot. If you can avoid usage
+// of such expression you accelerate the access a lot. Example:
+//   "TMath::Hypot(MHillas.fMeanX, MHillas.MeanY)"
+//   "pow(MHillas.fMeanX*MHillas.MeanY, -1.2)"
+// It should be possible to use all functions which are accessible
+// via the root-dictionary.
+//
+//
+// REMARK:
+//  - All the random functions are returning 0 if gRandom==0
+//  - You may get better results if you are using a TRandom3
+//
+// To Do:
+//  - The possibility to use other objects inheriting from MData
+//    is missing.
+//  - By automatic pre-adding parantheses to the rule it would be possible
+//    to implement priorities for operators.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MDataChain.h"
+
+#include <ctype.h>        // isalnum, ...
+#include <stdlib.h>       // strtod, ...
+
+#include <TRegexp.h>
+#include <TRandom.h>
+#include <TMethodCall.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDataList.h"
+#include "MDataValue.h"
+#include "MDataMember.h"
+#include "MDataFormula.h"
+#include "MDataElement.h"
+
+ClassImp(MDataChain);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Constructor which takes a rule and a surrounding operator as argument
+//
+MDataChain::MDataChain(const char *rule, OperatorType_t op)
+    : fOperatorType(op)
+{
+    fName  = "MDataChain";
+    fTitle = rule;
+
+    fMember=ParseString(rule);
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor taking a rule as an argument. For more details see
+// class description
+//
+MDataChain::MDataChain(const char *rule, const char *name, const char *title)
+    : fMember(NULL), fOperatorType(kENoop)
+{
+    fName  = name  ? name  : "MDataChain";
+    fTitle = title ? title : rule;
+
+    if (TString(rule).IsNull())
+        return;
+
+    *fLog << inf << "Parsing rule... " << flush;
+    if (!(fMember=ParseString(rule)))
+    {
+        *fLog << err << dbginf << "Parsing '" << rule << "' failed." << endl;
+        return;
+    }
+    *fLog << inf << "found: " << GetRule() << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcesses all members in the list
+//
+Bool_t MDataChain::PreProcess(const MParList *pList)
+{
+    return fMember ? fMember->PreProcess(pList) : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether at least one member has the ready-to-save flag.
+//
+Bool_t MDataChain::IsReadyToSave() const
+{
+    *fLog << all << "fM=" << fMember << "/" << (int)fMember->IsReadyToSave() << " " << endl;
+    return fMember ? fMember->IsReadyToSave() : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete filters.
+//
+MDataChain::~MDataChain()
+{
+    if (fMember)
+        delete fMember;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the number of alphanumeric characters (including '.' and ';')
+// in the given string
+//
+Int_t MDataChain::IsAlNum(TString txt)
+{
+    int l = txt.Length();
+    for (int i=0; i<l; i++)
+    {
+        if (!isalnum(txt[i]) && txt[i]!='.' && txt[i]!=':' && txt[i]!=';' &&
+	    /*txt[i]!='['&&txt[i]!=']'&&*/
+            ((txt[i]!='-' && txt[i]!='+') || i!=0))
+            return i;
+    }
+
+    return l;
+}
+
+Int_t MDataChain::GetBracket(TString txt, char open, char close)
+{
+    Int_t first=1;
+    for (int cnt=0; first<txt.Length(); first++)
+    {
+        if (txt[first]==open)
+            cnt++;
+        if (txt[first]==close)
+            cnt--;
+        if (cnt==-1)
+            break;
+    }
+    return first;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compare a given text with the known operators. If no operator match
+// kENoop is retunred, otherwise the corresponding OperatorType_t
+//
+MDataChain::OperatorType_t MDataChain::ParseOperator(TString txt) const
+{
+    txt.ToLower();
+
+    if (txt=="abs")    return kEAbs;
+    if (txt=="fabs")   return kEAbs;
+    if (txt=="log")    return kELog;
+    if (txt=="log2")   return kELog2;
+    if (txt=="log10")  return kELog10;
+    if (txt=="sin")    return kESin;
+    if (txt=="cos")    return kECos;
+    if (txt=="tan")    return kETan;
+    if (txt=="sinh")   return kESinH;
+    if (txt=="cosh")   return kECosH;
+    if (txt=="tanh")   return kETanH;
+    if (txt=="asin")   return kEASin;
+    if (txt=="acos")   return kEACos;
+    if (txt=="atan")   return kEATan;
+    if (txt=="asinh")  return kEASinH;
+    if (txt=="acosh")  return kEACosH;
+    if (txt=="atanh")  return kEATanH;
+    if (txt=="sqrt")   return kESqrt;
+    if (txt=="sqr")    return kESqr;
+    if (txt=="exp")    return kEExp;
+    if (txt=="pow10")  return kEPow10;
+    if (txt=="sgn")    return kESgn;
+    if (txt=="floor")  return kEFloor;
+    if (txt=="r2d")    return kERad2Deg;
+    if (txt=="d2r")    return kEDeg2Rad;
+    if (txt=="rand")   return kERandom;
+    if (txt=="randp")  return kERandomP;
+    if (txt=="rande")  return kERandomE;
+    if (txt=="randi")  return kERandomI;
+    if (txt=="randg")  return kERandomG;
+    if (txt=="randl")  return kERandomL;
+    if (txt=="isnan")  return kEIsNaN;
+    if (txt=="finite") return kEFinite;
+    if (txt[0]=='-')   return kENegative;
+    if (txt[0]=='+')   return kEPositive;
+
+    return kENoop;
+}
+
+// --------------------------------------------------------------------------
+//
+// Here the names of data members are interpreted. This can be used to
+// check for constants.
+//
+MData *MDataChain::ParseDataMember(TString txt)
+{
+    //txt.ToLower();
+
+    if (txt=="kRad2Deg") return new MDataValue(kRad2Deg);
+    if (txt=="kDeg2Rad") return new MDataValue(1./kRad2Deg);
+
+    if (!txt.BeginsWith("k"))
+        return new MDataMember(txt.Data());
+
+    const TString name = txt(1, txt.Length());
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,01,00)
+    TMethodCall call(TMath::Class(), name, "");
+#else
+    static TClass *const tmath = TClass::GetClass("TMath");
+    TMethodCall call(tmath, name, "");
+#endif
+
+    switch (call.ReturnType())
+    {
+    case TMethodCall::kLong:
+        Long_t l;
+        call.Execute(l);
+        return new MDataValue(l);
+    case TMethodCall::kDouble:
+        Double_t d;
+        call.Execute(d);
+        return new MDataValue(d);
+    default:
+        break;
+    }
+
+    return new MDataMember(txt.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Remove all whitespaces
+// Replace all kind of double +/- by a single + or -
+//
+void MDataChain::SimplifyString(TString &txt) const
+{
+    txt.ReplaceAll(" ",  "");
+    txt.ReplaceAll("**", "^");
+
+    while (txt.Contains("--") || txt.Contains("++") ||
+           txt.Contains("+-") || txt.Contains("-+"))
+    {
+        txt.ReplaceAll("--", "+");
+        txt.ReplaceAll("++", "+");
+        txt.ReplaceAll("-+", "-");
+        txt.ReplaceAll("+-", "-");
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add Parenthesis depending on the priority of the operators. The
+// priorities are defined by the default of the second argument.
+//
+void MDataChain::AddParenthesis(TString &test, const TString op) const
+{
+    // Signiture of an exponential number 1e12
+    static const TRegexp rexp("[.0123456789]e[+-][0123456789]");
+
+    const TString low = op(1, op.Length());
+    if (low.Length()==0)
+        return;
+
+    int offset = 0;
+    while (1)
+    {
+        const TString check = test(offset, test.Length());
+        if (check.IsNull())
+            break;
+
+        const Ssiz_t pos = check.First(op[0]);
+        if (pos<0)
+            break;
+
+        int cnt=0;
+
+        int i;
+        for (i=pos-1; i>=0; i--)
+        {
+            if (check[i]==')')
+                cnt++;
+            if (check[i]=='(')
+                cnt--;
+            if (cnt>0 || low.First(check[i])<0)
+                continue;
+
+            // Check if operator belongs to an exponential number
+            const TString sub(check(i-2, 4));
+            if (!sub(rexp).IsNull())
+                continue;
+            break;
+        }
+
+        cnt=0;
+        int j;
+        for (j=pos; j<check.Length(); j++)
+        {
+            if (check[j]=='(')
+                cnt++;
+            if (check[j]==')')
+                cnt--;
+            if (cnt>0 || low.First(check[j])<0)
+                continue;
+
+            // Check if operator belongs to an exponential number
+            const TString sub(check(j-2, 4));
+            if (!sub(rexp).IsNull())
+                continue;
+            break;
+        }
+
+        const TString sub = test(offset+i+1, j-i-1);
+
+        // Check if it contains operators,
+        // otherwise we can simply skip it
+        if (sub.First("%^/*+-")>=0)
+        {
+            test.Insert(offset+j,   ")");
+            test.Insert(offset+i+1, "(");
+            offset += 2;
+        }
+        offset += j+1;
+    }
+
+    AddParenthesis(test, low);
+}
+
+// --------------------------------------------------------------------------
+//
+// Core of the data chain. Here the chain is constructed out of the rule.
+//
+MData *MDataChain::ParseString(TString txt, Int_t level)
+{
+    if (level==0)
+    {
+        SimplifyString(txt);
+        AddParenthesis(txt);
+    }
+
+    MData *member0=NULL;
+
+    char type=0;
+    int nlist = 0;
+
+    while (!txt.IsNull())
+    {
+        MData *newmember = NULL;
+
+        txt = txt.Strip(TString::kBoth);
+
+        switch (txt[0])
+        {
+        case '(':
+            {
+                //
+                // Search for the corresponding parantheses
+                //
+                const Int_t first=GetBracket(txt, '(', ')');
+                if (first==txt.Length())
+                {
+                    *fLog << err << dbginf << "Syntax Error: ')' missing." << endl;
+                    if (member0)
+                        delete member0;
+                    return NULL;
+                }
+
+                //
+                // Make a copy of the 'interieur' and delete the substring
+                // including the brackets
+                //
+                TString sub = txt(1, first-1);
+                txt.Remove(0, first+1);
+
+                //
+                // Parse the substring
+                //
+                newmember = ParseString(sub, level+1);
+                if (!newmember)
+                {
+                    *fLog << err << dbginf << "Parsing '" << sub << "' failed." << endl;
+                    if (member0)
+                        delete member0;
+                    return NULL;
+                }
+            }
+            break;
+
+        case ')':
+            *fLog << err << dbginf << "Syntax Error: Too many ')'" << endl;
+            if (member0)
+                delete member0;
+            return NULL;
+
+        case '+':
+        case '-':
+        case '*':
+        case '/':
+        case '%':
+        case '^':
+            if (member0)
+            {
+                //
+                // Check for the type of the symbol
+                //
+                char is = txt[0];
+                txt.Remove(0, 1);
+
+                //
+                // If no filter is available or the available filter
+                // is of a different symbols we have to create a new
+                // data list with the new symbol
+                //
+                if (/*!member0->InheritsFrom(MDataMember::Class()) ||*/ type!=is)
+                {
+                    MDataList *list = new MDataList(is);
+                    list->SetName(Form("List_%c_%d", is, 10*level+nlist++));
+
+                    list->SetOwner();
+                    list->AddToList(member0);
+
+                    member0 = list;
+
+                    type = is;
+                }
+                continue;
+            }
+
+            if (txt[0]!='-' && txt[0]!='+')
+            {
+                *fLog << err << dbginf << "Syntax Error: First argument of '";
+                *fLog << txt[0] << "' opartor missing." << endl;
+                if (member0)
+                    delete member0;
+                return NULL;
+            }
+
+            // FALLTHROU
+
+        case '0':
+        case '1':
+        case '2':
+        case '3':
+        case '4':
+        case '5':
+        case '6':
+        case '7':
+        case '8':
+        case '9':
+        case '[':
+        case ']':
+            if ((txt[0]!='-' && txt[0]!='+') || isdigit(txt[1]) || txt[1]=='.')
+            {
+                if (!txt.IsNull() && txt[0]=='[')
+                {
+                    Int_t first = GetBracket(txt, '[', ']');
+                    TString op  = txt(1, first-1);
+                    txt.Remove(0, first+1);
+
+                    newmember = new MDataValue(0, atoi(op));
+                    break;
+                }
+
+                char *end;
+                Double_t num = strtod(txt.Data(), &end);
+                if (!end || txt.Data()==end)
+                {
+                    *fLog << err << dbginf << "Error trying to convert '" << txt << "' to value." << endl;
+                    if (member0)
+                        delete member0;
+                    return NULL;
+                }
+
+                txt.Remove(0, end-txt.Data());
+
+                newmember = new MDataValue(num);
+                break;
+            }
+
+            // FALLTHROUH
+
+        default:
+            int i = IsAlNum(txt);
+
+            if (i==0)
+            {
+                *fLog << err << dbginf << "Syntax Error: Name of data member missing in '" << txt << "'" << endl;
+                if (member0)
+                    delete member0;
+                return NULL;
+            }
+
+            TString text = txt(0, i);
+
+            txt.Remove(0, i);
+            txt = txt.Strip(TString::kBoth);
+
+            if (!txt.IsNull() && txt[0]=='[')
+            {
+                Int_t first = GetBracket(txt, '[', ']');
+                TString op  = txt(1, first-1);
+                txt.Remove(0, first+1);
+
+                newmember = new MDataElement(text, atoi(op));
+                break;
+            }
+            if ((txt.IsNull() || txt[0]!='(') && text[0]!='-' && text[0]!='+')
+            {
+                newmember = ParseDataMember(text.Data());
+                break;
+            }
+
+            OperatorType_t op = ParseOperator(text);
+
+            Int_t first = GetBracket(txt, '(', ')');
+            TString sub = op==kENegative || op==kEPositive ? text.Remove(0,1) + txt : txt(1, first-1);
+            txt.Remove(0, first+1);
+
+            if (op==kENoop)
+            {
+                newmember = new MDataFormula(Form("%s(%s)", (const char*)text, (const char*)sub));
+                if (newmember->IsValid())
+                    break;
+
+                *fLog << err << dbginf << "Syntax Error: Operator '" << text << "' unknown." << endl;
+                if (member0)
+                    delete member0;
+                return NULL;
+            }
+
+            newmember = new MDataChain(sub, op);
+            if (!newmember->IsValid())
+            {
+                *fLog << err << dbginf << "Syntax Error: Error parsing contents '" << sub << "' of operator " << text << endl;
+                delete newmember;
+                if (member0)
+                    delete member0;
+                return NULL;
+            }
+        }
+
+        if (!member0)
+        {
+            member0 = newmember;
+            continue;
+        }
+
+        if (!member0->InheritsFrom(MDataList::Class()))
+            continue;
+
+        ((MDataList*)member0)->AddToList(newmember);
+    }
+
+    return member0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the value described by the rule
+//
+Double_t MDataChain::GetValue() const
+{
+    if (!fMember)
+    {
+        //*fLog << warn << "MDataChain not valid." << endl;
+        return 0;
+    }
+
+    const Double_t val = fMember->GetValue();
+
+    switch (fOperatorType)
+    {
+    case kEAbs:      return TMath::Abs(val);
+    case kELog:      return TMath::Log(val);
+    case kELog2:     return TMath::Log2(val);
+    case kELog10:    return TMath::Log10(val);
+    case kESin:      return TMath::Sin(val);
+    case kECos:      return TMath::Cos(val);
+    case kETan:      return TMath::Tan(val);
+    case kESinH:     return TMath::SinH(val);
+    case kECosH:     return TMath::CosH(val);
+    case kETanH:     return TMath::TanH(val);
+    case kEASin:     return TMath::ASin(val);
+    case kEACos:     return TMath::ACos(val);
+    case kEATan:     return TMath::ATan(val);
+    case kEASinH:    return TMath::ASinH(val);
+    case kEACosH:    return TMath::ACosH(val);
+    case kEATanH:    return TMath::ATanH(val);
+    case kESqrt:     return TMath::Sqrt(val);
+    case kESqr:      return val*val;
+    case kEExp:      return TMath::Exp(val);
+    case kEPow10:    return TMath::Power(10, val);
+    case kESgn:      return val<0 ? -1 : 1;
+    case kENegative: return -val;
+    case kEPositive: return val;
+    case kEFloor:    return TMath::Floor(val);
+    case kECeil:     return TMath::Ceil(val);
+    case kERound:    return TMath::Nint(val);
+    case kERad2Deg:  return val*180/TMath::Pi();
+    case kEDeg2Rad:  return val*TMath::Pi()/180;
+    case kERandom:   return gRandom ? gRandom->Uniform(val)      : 0;
+    case kERandomP:  return gRandom ? gRandom->Poisson(val)      : 0;
+    case kERandomE:  return gRandom ? gRandom->Exp(val)          : 0;
+    case kERandomI:  return gRandom ? gRandom->Integer((int)val) : 0;
+    case kERandomG:  return gRandom ? gRandom->Gaus(0, val)   : 0;
+    case kERandomL:  return gRandom ? gRandom->Landau(0, val) : 0;
+    case kEIsNaN:    return TMath::IsNaN(val);
+    case kEFinite:   return TMath::Finite(val);
+    case kENoop:     return val;
+    }
+
+    *fLog << warn << "No Case for " << fOperatorType << " available." << endl;
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Builds a rule from all the chain members. This is a rule which could
+// be used to rebuild the chain.
+//
+TString MDataChain::GetRule() const
+{
+    if (!fMember)
+        return "<n/a>";
+
+    TString str;
+
+    Bool_t bracket = fOperatorType!=kENoop && !fMember->InheritsFrom(MDataList::Class());
+
+    switch (fOperatorType)
+    {
+    case kEAbs:      str += "abs"   ; break;
+    case kELog:      str += "log"   ; break;
+    case kELog2:     str += "log2"  ; break;
+    case kELog10:    str += "log10" ; break;
+    case kESin:      str += "sin"   ; break;
+    case kECos:      str += "cos"   ; break;
+    case kETan:      str += "tan"   ; break;
+    case kESinH:     str += "sinh"  ; break;
+    case kECosH:     str += "cosh"  ; break;
+    case kETanH:     str += "tanh"  ; break;
+    case kEASin:     str += "asin"  ; break;
+    case kEACos:     str += "acos"  ; break;
+    case kEATan:     str += "atan"  ; break;
+    case kEASinH:    str += "asinh" ; break;
+    case kEACosH:    str += "acosh" ; break;
+    case kEATanH:    str += "atanh" ; break;
+    case kESqrt:     str += "sqrt"  ; break;
+    case kESqr:      str += "sqr"   ; break;
+    case kEExp:      str += "exp"   ; break;
+    case kEPow10:    str += "pow10" ; break;
+    case kESgn:      str += "sgn"   ; break;
+    case kENegative: str += "-"     ; break;
+    case kEPositive: str += "+"     ; break;
+    case kEFloor:    str += "floor" ; break;
+    case kECeil:     str += "ceil"  ; break;
+    case kERound:    str += "round" ; break;
+    case kERad2Deg:  str += "r2d"   ; break;
+    case kEDeg2Rad:  str += "d2r"   ; break;
+    case kERandom:   str += "rand"  ; break;
+    case kERandomP:  str += "randp" ; break;
+    case kERandomE:  str += "rande" ; break;
+    case kERandomI:  str += "randi" ; break;
+    case kERandomG:  str += "randg" ; break;
+    case kERandomL:  str += "randl" ; break;
+    case kEIsNaN:    str += "isnan" ; break;
+    case kEFinite:   str += "finite"; break;
+    case kENoop:
+        break;
+    }
+
+    if (bracket)
+        str += "(";
+
+    str += fMember->GetRule();
+
+    if (bracket)
+        str += ")";
+
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the chain.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MDataChain::GetDataMember() const
+{
+    return fMember->GetDataMember();
+}
+
+void MDataChain::SetVariables(const TArrayD &arr)
+{
+    return fMember->SetVariables(arr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup data chain.
+//
+// Assuming your MDataChain is called (Set/GetName): MyData
+//
+// Now setup the condition, eg:
+//     MyData.Rule: log10(MHillas.fSize)
+// or
+//     MyData.Rule: log10(MHillas.fSize) - 4.1
+//
+// If you want to use more difficult rules you can split the
+// condition into subrules. Subrules are identified
+// by {}-brackets. Avoid trailing 0's! For example:
+//
+//     MyData.Rule: log10(MHillas.fSize) + {0} - {1}
+//     MyData.0: 5.5*MHillas.fSize
+//     MyData.1: 2.3*log10(MHillas.fSize)
+//
+// The numbering must be continous and start with 0. You can use
+// a subrules more than once. All {}-brackets are simply replaced
+// by the corresponding conditions. The rules how conditions can
+// be written can be found in the class description of MDataChain.
+//
+Int_t MDataChain::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (!IsEnvDefined(env, prefix, "Rule", print))
+        return rc;
+
+    TString rule = GetEnvValue(env, prefix, "Rule", "");
+    rule.ReplaceAll(" ", "");
+
+    Int_t idx=0;
+    while (1)
+    {
+        TString cond;
+        if (IsEnvDefined(env, prefix, Form("%d", idx), print))
+        {
+            cond += "(";
+            cond += GetEnvValue(env, prefix, Form("%d", idx), "");
+            cond += ")";
+        }
+
+        if (cond.IsNull())
+            break;
+
+        rule.ReplaceAll(Form("{%d}", idx), cond);
+        idx++;
+    }
+
+    if (fMember)
+    {
+        delete fMember;
+        fMember = 0;
+    }
+
+    if (rule.IsNull())
+    {
+        *fLog << warn << "MDataChain::ReadEnv - ERROR: Empty rule found." << endl;
+        return kERROR;
+    }
+
+    if (!(fMember=ParseString(rule)))
+    {
+        *fLog << err << "MDataChain::ReadEnv - ERROR: Parsing '" << rule << "' failed." << endl;
+        return kERROR;
+    }
+
+    if (print)
+    {
+        *fLog << inf << "found: ";
+        fMember->Print();
+        *fLog << endl;
+    }
+
+    return kTRUE;
+}
+/*
+void MDataChain::ReconstructElements()
+{
+    if (!fMember)
+        return;
+
+    if (fMember->InheritsFrom(MDataElement::Class()))
+    {
+        MData *data = ((MDataElement*)fMember)->CloneColumn();
+        delete fMember;
+        fMember = data;
+    }
+
+    fMember->ReconstructElements();
+}
+*/
Index: /tags/Mars-V0.9/mdata/MDataChain.h
===================================================================
--- /tags/Mars-V0.9/mdata/MDataChain.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataChain.h	(revision 9772)
@@ -0,0 +1,75 @@
+#ifndef MARS_MDataChain
+#define MARS_MDataChain
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MDataList                                                              //
+//                                                                         //
+//  List of several filters                                                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class MDataChain : public MData
+{
+private:
+    MData *fMember; // Filter
+
+    // PLEASE, always add new enums to the end of the enumeration,
+    // otherwise you would break loading old data chains...
+    typedef enum {
+        kENoop,
+        kELog, kELog2, kELog10,
+        kEAbs,
+        kESin, kECos, kETan, kESinH, kECosH, kETanH,
+        kEASin, kEACos, kEATan, kEASinH, kEACosH, kEATanH,
+        kESqrt, kESqr, kEPow10, kEExp,
+        kESgn,
+        kEPositive,
+        kENegative,
+        kEFloor, kECeil, kERound,
+        kERad2Deg, kEDeg2Rad, kERandom,
+        kERandomP, kERandomE, kERandomI, kERandomG, kERandomL,
+        kEIsNaN, kEFinite
+    } OperatorType_t;
+
+    OperatorType_t fOperatorType;
+
+    OperatorType_t ParseOperator(TString txt) const;
+
+    Int_t IsAlNum(TString txt);
+    Int_t GetBracket(TString txt, char open, char close);
+
+    void   SimplifyString(TString &txt) const;
+    void   AddParenthesis(TString &test, const TString op="^%*/+-") const;
+    MData *ParseString(TString txt, Int_t level=0);
+    MData *ParseDataMember(TString txt);
+
+    MDataChain(const char *rule, OperatorType_t op);
+
+public:
+    MDataChain(const char *rule=NULL, const char *name=NULL, const char *title=NULL);
+    ~MDataChain();
+
+    // MData
+    Double_t GetValue() const;
+
+    Bool_t IsValid() const { return fMember ? kTRUE : kFALSE; }
+    Bool_t PreProcess(const MParList *plist);
+
+    TString GetRule() const;
+    TString GetDataMember() const;
+    //void    ReconstructElements() { if (fMember) fMember->ReconstructElements(); }
+
+    // MParContainer
+    Bool_t IsReadyToSave() const;
+    void SetVariables(const TArrayD &arr);
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MDataChain, 1) // A chain/concatenation of MData objects
+};
+
+#endif
Index: /tags/Mars-V0.9/mdata/MDataElement.cc
===================================================================
--- /tags/Mars-V0.9/mdata/MDataElement.cc	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataElement.cc	(revision 9772)
@@ -0,0 +1,121 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MDataElement
+//
+//  This MData class is used for accessing a column of an MHMatrix object.
+//    eg. MDataElement("Matrix", 5)
+//  will return the 5th column of the MHMatrix object called Matrix.
+//
+//  The row which is accessed must be set before by using
+//  MHMatrix::SetNumRow. If you want to loop through a matrix use
+//  MMatrixLoop.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataElement.h"
+
+#include <fstream>
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MDataElement);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Specify the name of the MHMatrix-object and the column you want to
+// access.
+//
+MDataElement::MDataElement(const char *member, Int_t col)
+    : fMatrixName(member), fNumCol(col), fMatrix(NULL)
+{
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the pointer of the MHMatrix-object and the column you want to
+// access.
+//
+MDataElement::MDataElement(MHMatrix *mat, Int_t col)
+    : fMatrixName(mat->GetName()), fNumCol(col), fMatrix(mat)
+{
+}
+
+// --------------------------------------------------------------------------
+//
+// returns the value you requested
+//
+Double_t MDataElement::GetValue() const
+{
+    return fMatrix ? (*fMatrix)[fNumCol] : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the pointer to the MHMatrix isn't yet set search for it in the
+// parameter list.
+//
+Bool_t MDataElement::PreProcess(const MParList *plist)
+{
+    if (fMatrix)
+        return kTRUE;
+
+    fMatrix = (MHMatrix*)plist->FindObject(fMatrixName, "MHMatrix");
+    if (!fMatrix)
+    {
+        *fLog << err << "MHMatrix '" << fMatrixName << "' not in parameter list... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the ready-to-save flag of the data member container
+//
+Bool_t MDataElement::IsReadyToSave() const
+{
+    return IsValid() ? fMatrix->IsReadyToSave() : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the rule used to identify this object in a datachain
+//
+TString MDataElement::GetRule() const
+{
+    TString rule = fMatrixName + "[";
+    rule += fNumCol;
+    rule += "]";
+    return rule;
+}
Index: /tags/Mars-V0.9/mdata/MDataElement.h
===================================================================
--- /tags/Mars-V0.9/mdata/MDataElement.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataElement.h	(revision 9772)
@@ -0,0 +1,43 @@
+#ifndef MARS_MDataElement
+#define MARS_MDataElement
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MDataElement                                                           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class MHMatrix;
+
+class MDataElement : public MData
+{
+private:
+    TString   fMatrixName;
+    Int_t     fNumCol;
+
+    MHMatrix *fMatrix;
+
+public:
+    MDataElement(const char *member=NULL, Int_t col=-1);
+    MDataElement(MHMatrix *mat, Int_t col=-1);
+
+    Double_t GetValue() const;
+    Bool_t PreProcess(const MParList *plist);
+
+    Bool_t IsValid() const { return kTRUE; }
+    Bool_t IsReadyToSave() const;
+
+    //void Print(Option_t *opt = "") const;
+    TString GetRule() const;
+
+    Double_t operator()() { return GetValue(); }
+
+    void SetVariables(const TArrayD &arr) { }
+
+    ClassDef(MDataElement, 1) // MData object corresponding to a element of an MHMatrix
+};
+
+#endif
Index: /tags/Mars-V0.9/mdata/MDataFormula.cc
===================================================================
--- /tags/Mars-V0.9/mdata/MDataFormula.cc	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataFormula.cc	(revision 9772)
@@ -0,0 +1,318 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 04/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MDataFormula
+//
+// A MDataFormula is a wrapper for TFormula. It should have access to all
+// multi-argument functions, to formulas and to single-argument functions
+// unknown by MDataChain intrinsically.
+//
+// eg.
+//  MDataFormula("myfunc(MParams.fValue)");
+//  MDataFormula("TMath::Hypot(MParams.fX, MParams.fY)");
+//  MDataFormula("TMath::Pow(MParams.fX, 7.5)");
+//  MDataFormula("TMath::Pow(MParams.fX, [6])");
+//
+// Using this should be rather slow. If you can create a 'plain' Data-Chain
+// this should be much faster.
+//
+// To do:
+//  - implement SetVariables to be used in functions like "gaus(0)" or
+//    "pol0(1)"
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataFormula.h"
+
+#include <TArrayD.h>
+#include <TFormula.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDataChain.h"
+
+ClassImp(MDataFormula);
+
+using namespace std;
+
+TString MDataFormula::Parse(const char *rule)
+{
+    TString txt(rule);
+
+    Int_t pos1 = txt.First('(');
+    if (pos1<0)
+    {
+        *fLog << err << dbginf << "Syntax Error: '(' not found in " << txt << endl;
+        return "";
+    }
+
+    Int_t pos2 = txt.Last(')');
+    if (pos2<0)
+    {
+        *fLog << err << dbginf << "Syntax Error: ')' not found in " << txt << endl;
+        return "";
+    }
+
+    if (pos2<pos1+1)
+    {
+        *fLog << err << dbginf << "Syntax Error: '(' not behind ')' in " << txt << endl;
+        return "";
+    }
+
+    //TObject *func = gROOT->GetListOfFunctions()->FindObject(txt(0, pos1));
+
+    TString args = txt(pos1+1, pos2-pos1);
+    Int_t num = 0;
+
+    while (args.Length()>0 && num<5)
+    {
+        const Int_t last = args.First(',');
+        const Int_t len = last<0 ? args.Last(')') : last;
+        if (len<0)
+        {
+            *fLog << err << dbginf << "Syntax Error: ',' found after ')'" << endl;
+            return "";
+        }
+
+        const TString arg = args(0, len);
+
+        MDataChain *chain = new MDataChain(arg);
+        if (!chain->IsValid())
+        {
+            delete chain;
+            return "";
+        }
+        fMembers.AddLast(chain);
+
+        txt.ReplaceAll(arg, Form("[%d]", num++));
+        pos1 += len;
+
+        args.Remove(0, len+1);
+    }
+
+    return txt;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Default Constructor. Not for usage!
+//
+MDataFormula::MDataFormula(const char *rule, const char *name, const char *title) : fFormula(0)
+{
+    fName  = name  ? name  : "MDataFormula";
+    fTitle = title ? title : rule;
+
+    fMembers.SetOwner();
+
+    if (!rule)
+        return;
+
+    const TString txt=Parse(rule);
+    if (txt.IsNull())
+    {
+        fMembers.Delete();
+        return;
+    }
+
+    fFormula = new TFormula;
+    if (fFormula->Compile(txt))
+    {
+        *fLog << err << dbginf << "Syntax Error: TFormula::Compile failed for " << txt << endl;
+        delete fFormula;
+        fFormula = 0;
+        return;
+    }
+
+    gROOT->GetListOfFunctions()->Remove(fFormula);
+}
+
+// --------------------------------------------------------------------------
+//
+//   Destructor
+//
+MDataFormula::~MDataFormula()
+{
+    if (fFormula)
+        delete fFormula;
+}
+
+// --------------------------------------------------------------------------
+//
+//   CopyConstructor
+//
+MDataFormula::MDataFormula(MDataFormula &ts)
+{
+    TFormula *f = ts.fFormula;
+
+    fName  = "MDataFormula";
+    fTitle = f ? f->GetExpFormula() : (TString)"";
+
+    fFormula = f ? (TFormula*)f->Clone() : 0;
+    gROOT->GetListOfFunctions()->Add(fFormula);
+
+    fMembers.SetOwner();
+
+    TObject *o = NULL;
+    TIter Next(&ts.fMembers);
+    while ((o=Next()))
+        fMembers.AddLast(o->Clone());
+}
+
+// --------------------------------------------------------------------------
+//
+//  Evaluates and returns the result of the member list.
+//  The expression is evaluated step by step, eg:
+//  ((member[0] # member[1]) # member[3]) # member[4])
+//  The '#' stands for the boolean operation which is specified in
+//  the constructor.
+//
+Double_t MDataFormula::GetValue() const
+{
+    TArrayD val(fMembers.GetSize());
+
+    MData *member = NULL;
+
+    Int_t i=0;
+    TIter Next(&fMembers);
+    while ((member=(MData*)Next()))
+        val[i++] = member->GetValue();
+
+    return fFormula->EvalPar(0, val.GetArray());
+}
+
+Bool_t MDataFormula::IsValid() const
+{
+    TIter Next(&fMembers);
+
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+        if (!data->IsValid())
+            return kFALSE;
+
+    return fFormula ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether at least one member has the ready-to-save flag.
+//
+Bool_t MDataFormula::IsReadyToSave() const
+{
+    TIter Next(&fMembers);
+
+    MData *data = NULL;
+
+    while ((data=(MData*)Next()))
+        if (data->IsReadyToSave())
+            return kTRUE;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcesses all members in the list
+//
+Bool_t MDataFormula::PreProcess(const MParList *plist)
+{
+    TIter Next(&fMembers);
+
+    MData *member=NULL;
+
+    //
+    // loop over all members
+    //
+    while ((member=(MData*)Next()))
+        if (!member->PreProcess(plist))
+        {
+            *fLog << err << "Error - Preprocessing Data Member ";
+            *fLog << member->GetName() << " in " << fName << endl;
+            return kFALSE;
+        }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Builds a rule from all the list members. This is a rule which could
+// be used to rebuild the list using the constructor of a MDataChain
+//
+TString MDataFormula::GetRule() const
+{
+    if (!fFormula)
+        return "<empty>";
+
+    TString rule = fFormula->GetExpFormula();
+
+    MData *member = NULL;
+
+    Int_t i=0;
+    TIter Next(&fMembers);
+    while ((member=(MData*)Next()))
+    {
+        TString r = member->GetRule();
+        r.ReplaceAll("]", "\\]");
+        rule.ReplaceAll(Form("[%d]", i++), r);
+    }
+    rule.ReplaceAll("\\]", "]");
+
+    return rule;
+}
+/*
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the chain.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MDataFormula::GetDataMember() const
+{
+    TString str;
+
+    TIter Next(&fMembers);
+
+    MData *member=(MData*)Next();
+
+    if (!member->GetDataMember().IsNull())
+        str += member->GetDataMember();
+
+    while ((member=(MData*)Next()))
+    {
+        if (!member->GetDataMember().IsNull())
+        {
+            str += ",";
+            str += member->GetDataMember();
+        }
+    }
+
+    return str;
+}
+
+void MDataFormula::SetVariables(const TArrayD &arr)
+{
+    fMembers.ForEach(MData, SetVariables)(arr);
+}
+*/
Index: /tags/Mars-V0.9/mdata/MDataFormula.h
===================================================================
--- /tags/Mars-V0.9/mdata/MDataFormula.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataFormula.h	(revision 9772)
@@ -0,0 +1,43 @@
+#ifndef MARS_MDataFormula
+#define MARS_MDataFormula
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class TFormula;
+class MParList;
+
+class MDataFormula : public MData
+{
+private:
+    TFormula      *fFormula;    // TFormula
+    TOrdCollection fMembers;	// List of arguments
+
+    TString Parse(const char *rule);
+
+public:
+    MDataFormula(const char *rule=0, const char *name=0, const char *title=0);
+    MDataFormula(MDataFormula &ts);
+    ~MDataFormula();
+
+    Bool_t IsValid() const;// { return fFormula ? kTRUE : kFALSE; }
+    Bool_t IsReadyToSave() const;
+
+    Double_t GetValue() const;
+    Bool_t PreProcess(const MParList *plist);
+
+    //    void Print(Option_t *opt = "") const;
+    TString GetRule() const;
+    //    TString GetDataMember() const;
+
+    //void SetVariables(const TArrayD &arr);
+
+    ClassDef(MDataFormula, 1) // A concatenation of MData objects by one operator
+};
+
+#endif
Index: /tags/Mars-V0.9/mdata/MDataList.cc
===================================================================
--- /tags/Mars-V0.9/mdata/MDataList.cc	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataList.cc	(revision 9772)
@@ -0,0 +1,401 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MDataList
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MDataList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MDataList);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//   Default Constructor. Not for usage!
+//
+MDataList::MDataList()
+{
+    fSign = kENone;
+
+    gROOT->GetListOfCleanups()->Add(&fMembers);
+    fMembers.SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//   Constructor.
+//
+//   Specify the operation which is used to evaluate the
+//   result of this list.
+//
+//   Options:
+//      *,  /,  -,  +
+//
+MDataList::MDataList(char type)
+{
+    switch (type)
+    {
+    case '*':
+        fSign = kEMult;
+        return;
+    case '/':
+        fSign = kEDiv;
+        return;
+    case '-':
+        fSign = kEMinus;
+        return;
+    case '+':
+        fSign = kEPlus;
+        return;
+    case '%':
+        fSign = kEModul;
+        return;
+    case '^':
+        fSign = kEPow;
+        return;
+    default:
+        fSign = kENone;
+    }
+
+    gROOT->GetListOfCleanups()->Add(&fMembers);
+    fMembers.SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+//   CopyConstructor
+//
+MDataList::MDataList(MDataList &ts)
+{
+    fMembers.AddAll(&ts.fMembers);
+    fSign = ts.fSign;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Evaluates and returns the result of the member list.
+//  The expression is evaluated step by step, eg:
+//  ((member[0] # member[1]) # member[3]) # member[4])
+//  The '#' stands for the boolean operation which is specified in
+//  the constructor.
+//
+Double_t MDataList::GetValue() const
+{
+    TIter Next(&fMembers);
+
+    MData *member=(MData*)Next();
+
+    if (!member)
+        return kTRUE;
+
+    Double_t val = member->GetValue();
+
+    //
+    // loop over all members
+    //
+    switch (fSign)
+    {
+    case kENone:
+        return 0;
+
+    case kEPlus:
+        while ((member=(MData*)Next()))
+            val += member->GetValue();
+        break;
+
+    case kEMinus:
+        while ((member=(MData*)Next()))
+            val -= member->GetValue();
+        break;
+
+    case kEMult:
+        while ((member=(MData*)Next()))
+            val *= member->GetValue();
+        break;
+
+    case kEDiv:
+        while ((member=(MData*)Next()))
+        {
+            const Double_t d = member->GetValue();
+            if (d==0)
+            {
+                *fLog << warn << "Warning: Division by zero: " << member->GetRule() << endl;
+                return 0;
+            }
+            val /= d;
+        }
+        break;
+
+    case kEModul:
+        while ((member=(MData*)Next()))
+        {
+            const Double_t d = member->GetValue();
+            if (d==0)
+            {
+                *fLog << warn << "Warning: Modulo division by zero: " << member->GetRule() << endl;
+                return 0;
+            }
+            val = fmod(val, d);
+        }
+        break;
+    case kEPow:
+        while ((member=(MData*)Next()))
+            val = pow(val, member->GetValue());
+        break;
+    }
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether at least one member has the ready-to-save flag.
+//
+Bool_t MDataList::IsReadyToSave() const
+{
+    TIter Next(&fMembers);
+
+    MData *data = NULL;
+
+    while ((data=(MData*)Next()))
+        if (data->IsReadyToSave())
+            return kTRUE;
+
+    return kFALSE;
+}
+
+Bool_t MDataList::IsValid() const
+{
+    TIter Next(&fMembers);
+
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+        if (!data->IsValid())
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to add a new member to the list call this function with the
+// pointer to the member to be added.
+//
+Bool_t MDataList::AddToList(MData *member)
+{
+    if (!member)
+        return kTRUE;
+
+    if (fMembers.FindObject(member))
+    {
+        *fLog << warn << dbginf << "Filter already existing... skipped." << endl;
+        return kTRUE;
+    }
+
+    member->SetBit(kMustCleanup);
+    fMembers.Add(member);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcesses all members in the list
+//
+Bool_t MDataList::PreProcess(const MParList *plist)
+{
+    TIter Next(&fMembers);
+
+    MData *member=NULL;
+
+    //
+    // loop over all members
+    //
+    while ((member=(MData*)Next()))
+        if (!member->PreProcess(plist))
+        {
+            *fLog << err << "Error - Preprocessing Data Member ";
+            *fLog << member->GetName() << " in " << fName << endl;
+            return kFALSE;
+        }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// If you want to use a verbose output ("and") instead of a symbolic ("&")
+// one the option string must conatin a "v"
+//
+/*
+void MDataList::Print(Option_t *opt) const
+{
+    *fLog << "(";
+
+    TIter Next(&fMembers);
+
+    TObject *member=Next();
+
+    //
+    // loop over all members
+    //
+    if (!member)
+    {
+        *fLog << "<empty>)" << flush;
+        return;
+    }
+
+    member->Print();
+
+    while ((member=Next()))
+    {
+        switch (fSign)
+        {
+        case kENone:
+            break;
+
+        case kEPlus:
+            *fLog << "+";
+            break;
+
+        case kEMinus:
+            *fLog << "-";
+            break;
+
+        case kEMult:
+            *fLog << "*";
+            break;
+
+        case kEDiv:
+            *fLog << "/";
+            break;
+        }
+
+        member->Print();
+    }
+
+    *fLog << ")" << flush;
+    }
+    */
+
+// --------------------------------------------------------------------------
+//
+// Builds a rule from all the list members. This is a rule which could
+// be used to rebuild the list using the constructor of a MDataChain
+//
+TString MDataList::GetRule() const
+{
+    TIter Next(&fMembers);
+
+    MData *member=(MData*)Next();
+
+    //
+    // loop over all members
+    //
+    if (!member)
+        return "(<empty>)";
+
+    TString str = "(";
+
+    str += member->GetRule();
+
+    while ((member=(MData*)Next()))
+    {
+        switch (fSign)
+        {
+        case kENone:
+            break;
+
+        case kEPlus:
+            str += "+";
+            break;
+
+        case kEMinus:
+            str += "-";
+            break;
+
+        case kEMult:
+            str += "*";
+            break;
+
+        case kEDiv:
+            str += "/";
+            break;
+
+        case kEModul:
+            str += "%";
+            break;
+
+        case kEPow:
+            str += "^";
+            break;
+        }
+
+        str += member->GetRule();
+    }
+
+    str += ")";
+
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the chain.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MDataList::GetDataMember() const
+{
+    TString str;
+
+    TIter Next(&fMembers);
+
+    MData *member=(MData*)Next();
+
+    if (!member->GetDataMember().IsNull())
+        str += member->GetDataMember();
+
+    while ((member=(MData*)Next()))
+    {
+        if (!member->GetDataMember().IsNull())
+        {
+            str += ",";
+            str += member->GetDataMember();
+        }
+    }
+
+    return str;
+}
+
+void MDataList::SetVariables(const TArrayD &arr)
+{
+    fMembers.ForEach(MData, SetVariables)(arr);
+}
Index: /tags/Mars-V0.9/mdata/MDataList.h
===================================================================
--- /tags/Mars-V0.9/mdata/MDataList.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataList.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MDataList
+#define MARS_MDataList
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MDataList                                                              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class MParList;
+
+class MDataList : public MData
+{
+private:
+    TOrdCollection fMembers;	// Container for the filters
+
+    typedef enum { kENone, kEPlus, kEMinus, kEMult, kEDiv, kEModul, kEPow } SignType_t;
+    SignType_t fSign;
+
+    enum { kIsOwner = BIT(14) };
+
+public:
+    MDataList();
+    MDataList(char type);
+    MDataList(MDataList &ts);
+    ~MDataList()
+    {
+        if (TestBit(kIsOwner))
+            fMembers.SetOwner();
+    }
+
+    Bool_t AddToList(MData *member);
+    void SetOwner(Bool_t enable=kTRUE) { enable ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+
+    Bool_t IsValid() const;// { return fMembers.GetSize() ? kTRUE : kFALSE; }
+    Bool_t IsReadyToSave() const;
+
+    Double_t GetValue() const;
+    Bool_t PreProcess(const MParList *plist);
+
+//    void Print(Option_t *opt = "") const;
+    TString GetRule() const;
+    TString GetDataMember() const;
+
+    void SetVariables(const TArrayD &arr);
+
+    ClassDef(MDataList, 1) // A concatenation of MData objects by one operator
+};
+
+#endif
Index: /tags/Mars-V0.9/mdata/MDataMember.cc
===================================================================
--- /tags/Mars-V0.9/mdata/MDataMember.cc	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataMember.cc	(revision 9772)
@@ -0,0 +1,204 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MDataMember
+//
+//   This objects corresponds to the data member of another object.
+//   You can either specify the object as a string, eg "MHillas.fWidth"
+//   where MHillas is the name of the container in the parameterlist
+//   and fWidth is it's data member, or you can specify it by giving
+//   the pointer corresponding to the instance of your object and
+//   a TMethodCall pointer corresponding to the Member function returning
+//   the requested value.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataMember.h"
+
+#include <fstream>
+
+#include <TMethodCall.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MDataMember);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  obj is a pointer to the instance of your class from which the data
+//  should be requested. TMethodCall (s. root dox) is a pointer
+//  to a TMethodCall object which should be the getter function for
+//  the data you want to get.
+//
+MDataMember::MDataMember(MParContainer *obj, TMethodCall *call)
+{
+    fObject = obj;
+    fCall   = call;
+
+    if (fCall->ReturnType()==TMethodCall::kLong)
+        SetBit(kIsInt);
+    else
+        ResetBit(kIsInt);
+
+    fDataMember = (TString)obj->GetName() + "." + call->GetName();
+}
+
+// --------------------------------------------------------------------------
+//
+//  obj is a pointer to the instance of your class from which the data
+//  should be requested. TMethodCall (s. root dox) is a pointer
+//  to a TMethodCall object which should be the getter function for
+//  the data you want to get.
+//
+MDataMember::MDataMember(MParContainer *obj, const TString call)
+{
+    fObject = obj;
+    fCall   = obj->GetterMethod(call);
+
+    if (fCall->ReturnType()==TMethodCall::kLong)
+        SetBit(kIsInt);
+    else
+        ResetBit(kIsInt);
+
+    fDataMember = (TString)obj->GetName() + "." + call;
+}
+
+// --------------------------------------------------------------------------
+//
+// returns the value you requested
+//
+Double_t MDataMember::GetValue() const
+{
+    if (!fCall)
+    {
+        *fLog << err << "No TMethodCall for " << fDataMember << " of ";
+        *fLog << fObject->GetName() << " available... returning 0." << endl;
+        return 0;
+    }
+
+    switch (fCall->ReturnType())
+    {
+    case TMethodCall::kLong:
+        Long_t l;
+        fCall->Execute(fObject, l);
+        return (Double_t)l;
+
+    case TMethodCall::kDouble:
+        Double_t v;
+        fCall->Execute(fObject, v);
+        return v;
+
+    default:
+        *fLog << err << "DataMember " << fDataMember << " of ";
+        *fLog << fObject->GetName() << " neither int nor float... returning 0." << endl;
+        return 0;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// If a string was given PreProcess try to resolv the object name and
+// tries to get it from the parlist. And also tries to resolve
+// the data member (variable) name you requested and tries to get a
+// corresponding TMethodCall from the root Dictionary.
+// Remark: If your Data Member is called fDataMember the corresponding
+//         getter Method in your class must be calles fDataMember
+//
+Bool_t MDataMember::PreProcess(const MParList *plist)
+{
+    // The following change has to be checked :
+    // In order that fCall is initialized properly
+    // the original statement "if (fCall)" is replaced by the statement
+    if (fCall && !fObject)
+            return kTRUE;
+
+    TString cname(fDataMember);
+    TString mname(fDataMember);
+
+    const char *dot = strrchr(cname, '.');
+
+    if (dot)
+    {
+        const int pos = dot-cname;
+
+        cname.Remove(pos);
+        mname.Remove(0, pos+1);
+    }
+
+    fObject = (MParContainer*)plist->FindObject(cname);
+    if (!fObject)
+    {
+        *fLog << err << "Object '" << cname << "' not in parameter list... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCall = fObject->GetterMethod(mname);
+
+    return fCall ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the ready-to-save flag of the data member container
+//
+Bool_t MDataMember::IsReadyToSave() const
+{
+    return IsValid() ? fObject->IsReadyToSave() : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the name of the data member without an CR.
+//
+/*
+void MDataMember::Print(Option_t *opt) const
+{
+    *fLog << fName << flush;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Builds a rule which cn be used in a MDataChain to describe this object
+//
+TString MDataMember::GetRule() const
+{
+    return fDataMember;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the data member.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MDataMember::GetDataMember() const
+{
+    return fDataMember;
+}
Index: /tags/Mars-V0.9/mdata/MDataMember.h
===================================================================
--- /tags/Mars-V0.9/mdata/MDataMember.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataMember.h	(revision 9772)
@@ -0,0 +1,50 @@
+#ifndef MARS_MDataMember
+#define MARS_MDataMember
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MDataMember                                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class MDataMember : public MData
+{
+private:
+    TString fDataMember;
+
+    MParContainer *fObject;
+    TMethodCall   *fCall;
+
+    enum { kIsInt = BIT(14) };
+
+public:
+    MDataMember(const char *member=NULL) : fObject(NULL), fCall(NULL)
+    {
+        fDataMember = member;
+    }
+
+    MDataMember(MParContainer *obj, TMethodCall *call);
+    MDataMember(MParContainer *obj, const TString call);
+
+    Double_t GetValue() const;
+    Bool_t PreProcess(const MParList *plist);
+
+    Bool_t IsValid() const { return fCall ? kTRUE : kFALSE; }
+    Bool_t IsReadyToSave() const;
+
+    //void Print(Option_t *opt = "") const;
+    TString GetRule() const;
+    TString GetDataMember() const;
+
+    Bool_t IsInt() const { return TestBit(kIsInt); }
+
+    void SetVariables(const TArrayD &arr) { }
+
+    ClassDef(MDataMember, 1) // MData object corresponding to a single data member of a Mars container
+};
+
+#endif
Index: /tags/Mars-V0.9/mdata/MDataValue.cc
===================================================================
--- /tags/Mars-V0.9/mdata/MDataValue.cc	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataValue.cc	(revision 9772)
@@ -0,0 +1,68 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MDataValue
+//
+//   An MData object which corresponds to a simple value like 5.5, or 7.9
+//   it can be set as variable object by giving it an index in the
+//   constructor, only in this case SetVariables takes action
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataValue.h"
+
+#include <TArrayD.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MDataValue);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Return the value as a string
+//
+TString MDataValue::GetRule() const
+{
+    if (fIndex>=0)
+    {
+        TString str("[");
+        str += fIndex;
+        str += "]";
+        return str;
+    }
+
+    TString str;
+    str += fValue;
+    return str.Strip(TString::kBoth);
+}
+
+void MDataValue::SetVariables(const TArrayD &arr)
+{
+    if (fIndex>=0 && fIndex<arr.GetSize())
+        fValue = arr[fIndex];
+}
Index: /tags/Mars-V0.9/mdata/MDataValue.h
===================================================================
--- /tags/Mars-V0.9/mdata/MDataValue.h	(revision 9772)
+++ /tags/Mars-V0.9/mdata/MDataValue.h	(revision 9772)
@@ -0,0 +1,34 @@
+#ifndef MARS_MDataValue
+#define MARS_MDataValue
+
+#ifndef MARS_MData
+#include "MData.h"
+#endif
+
+class TArrayD;
+
+class MDataValue : public MData
+{
+private:
+    Double_t fValue;
+    Int_t    fIndex;
+
+public:
+    MDataValue(Double_t v = 0, Int_t idx=-1) : fValue(v), fIndex(idx)
+    {
+    }
+
+    Double_t GetValue() const { return fValue; }
+    Bool_t PreProcess(const MParList *plist) { return kTRUE; }
+
+    Bool_t IsValid() const { return kTRUE; }
+    Bool_t IsReadyToSave() const { return kFALSE; }
+
+    TString GetRule() const;
+
+    void SetVariables(const TArrayD &arr);
+
+    ClassDef(MDataValue, 1) // MData object corresponding to a single value
+};
+
+#endif
Index: /tags/Mars-V0.9/mdata/Makefile
===================================================================
--- /tags/Mars-V0.9/mdata/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mdata/Makefile	(revision 9772)
@@ -0,0 +1,33 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mhbase
+
+CINT     = Data
+
+SRCFILES = MData.cc \
+	   MDataArray.cc \
+           MDataElement.cc \
+	   MDataMember.cc \
+	   MDataValue.cc \
+	   MDataList.cc \
+	   MDataChain.cc \
+           MDataFormula.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
+
Index: /tags/Mars-V0.9/merpp.cc
===================================================================
--- /tags/Mars-V0.9/merpp.cc	(revision 9772)
+++ /tags/Mars-V0.9/merpp.cc	(revision 9772)
@@ -0,0 +1,422 @@
+#include <TSystem.h>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MRawFileRead.h"
+#include "MSqlInsertRun.h"
+#include "MRawFileWrite.h"
+#include "MReportFileReadCC.h"
+#include "MWriteRootFile.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+#include "MTime.h"
+#include "MArray.h"
+#include "MRawEvtData.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawCrateArray.h"
+
+#include "MFDataMember.h"
+
+using namespace std;
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// This is an easy implementation of the Merging process                    //
+// (as compilable prog)                                                     //
+//                                                                          //
+// at the moment it reads a binary file ("rawtest.bin") which was written   //
+// in the DAQ raw format.                                                   //
+//                                                                          //
+// The data are stored in root container objects (classes derived from      //
+// TObject like MRawRunHeader)                                              //
+//                                                                          //
+// This containers are written to a root file ("rawtest.root")              //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "                MERPP - MARS V" << MARSVER          << endl;
+    gLog << "     MARS - Merging and Preprocessing Program"      << endl;
+    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
+    gLog << "               Using ROOT v" << ROOTVER             << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " merpp [options] inputfile[.rep,[.raw],[.txt]] [outputfile[.root]]" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   inputfile.raw             Magic DAQ binary file." << endl;
+    gLog << "   inputfile.rep             Magic Central Control report file." << endl;
+    gLog << "   inputfile.txt             Magic DC currents file." << endl;
+    gLog << "   ouputfile.root            Merpped root file." << endl << endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << " File Options:" << endl;
+    gLog << "   -c#                       Compression level #=1..9 [default=2]" << endl;
+    gLog << "   -f                        Force overwrite of an existing file" << endl;
+    gLog << "   -u, --update              Update an existing file." << endl << endl;
+    gLog << " Raw Data Options:" << endl;
+    gLog << "   -ff                       Force merpp to ignore broken events" << endl;
+    gLog << "   --interleave=#            Process only each i-th event [default=1]" << endl << endl;
+//    gLog << "   --sql=mysql://user:password@url  Insert run into database" << endl << endl;
+    gLog << " Report File Options:" << endl;
+    gLog << "   --auto-time               Take time automatically from MRawRunHeader" << endl;
+    gLog << "                             (overwrites --start= and/or --stop=)" << endl;
+    gLog << "   --start=date/time         Start event time" << endl;
+    gLog << "   --stop=date/time          Stop  event time" << endl;
+    gLog << "   --run=#                   Only data corresponding to this run number" << endl;
+    gLog << "                             (from RUN-REPORT)" << endl;
+    gLog << "   --runfile=#               Allow only run-control files" << endl;
+    gLog << "                             (from .rep header)" << endl;
+    gLog << "   --sumfile                 Check for an all night summary file" << endl;
+    gLog << "                             (from .rep header)" << endl;
+    gLog << "   --allfiles                Don't check file type <default>" << endl << endl;
+    gLog << " REMARK: - At the moment you can process a .raw _or_ a .rep file, only!" << endl;
+    gLog << "         - 'date/time' has the format 'yyyy-mm-dd/hh:mm:ss.mmm'" << endl << endl;
+}
+
+// FIXME: Move to MTime (maybe 'InterpreteCmdline')
+MTime AnalyseTime(TString str)
+{
+    Int_t y=0, ms=0, mon=0, d=0, h=0, m=0, s=0;
+
+    const Int_t n = sscanf(str.Data(), "%d-%d-%d/%d:%d:%d.%d", &y, &mon, &d, &h, &m, &s, &ms);
+
+    if (n<6 || n>7)
+    {
+        gLog << warn << "'" << str << "' no valid Time... ignored." << endl;
+        return MTime();
+    }
+
+    MTime t;
+    t.Set(y, mon, d, h, m, s, ms);
+    return t;
+}
+
+void GetTimeFromFile(const char *fname, MTime &start, MTime &stop)
+{
+    TFile f(fname, "READ");
+
+    TTree *t = (TTree*)f.Get("RunHeaders");
+    if (t->GetEntries()!=1)
+    {
+        gLog << warn << "WARNING - File " << fname << " contains no or more than one entry in RunHeaders... Times unchanged." << endl;
+        return;
+    }
+
+    MRawRunHeader *h = 0;
+    t->SetBranchAddress("MRawRunHeader.", &h);
+    t->GetEntry(0);
+    if (!h)
+    {
+        gLog << warn << "WARNING - File " << fname << " did not contain RunHeaders.MRawRunHeader... Times unchanged." << endl;
+        return;
+    }
+
+    if (!start)
+        start = h->GetRunStart();
+    if (!stop)
+        stop = h->GetRunEnd();
+}
+
+int main(const int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    gLog.Setup(arg);
+
+    const Int_t  kComprlvl   = arg.GetIntAndRemove("-c", 2);
+    const Bool_t kInterleave = arg.GetIntAndRemove("--interleave=", 1);
+    const Bool_t kForce      = arg.HasOnlyAndRemove("-f");
+    const Bool_t kForceProc  = arg.HasOnlyAndRemove("-ff");
+    const Int_t  kRunNumber  = arg.GetIntAndRemove("--run=", -1);
+    const Bool_t kAutoTime   = arg.HasOnlyAndRemove("--auto-time");
+          Int_t  kRunFile    = arg.GetIntAndRemove("--runfile=", -1);
+          Bool_t kUpdate     = arg.HasOnlyAndRemove("--update") || arg.HasOnlyAndRemove("-u");
+
+    MTime kTimeStart;
+    MTime kTimeStop;
+    if (arg.HasOption("--star="))
+        kTimeStart = AnalyseTime(arg.GetStringAndRemove("--start="));
+    if (arg.HasOption("--stop="))
+        kTimeStop = AnalyseTime(arg.GetStringAndRemove("--stop="));
+
+//    const TString kSqlDataBase(arg.GetStringAndRemove("--sql="));
+
+    if (arg.HasOnlyAndRemove("--sumfile"))
+        kRunFile = 0;
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()<1 || arg.GetNumArguments()>2)
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // This is to make argv[i] more readable insidethe code
+    //
+    TString kNamein  = arg.GetArgumentStr(0);
+    TString kNameout = arg.GetArgumentStr(1);
+
+    const Bool_t isreport = kNamein.EndsWith(".rep");
+    const Bool_t isdc     = kNamein.EndsWith(".txt");
+    const Bool_t israw    = !isreport && !isdc;
+
+    if (!kNamein.EndsWith(".raw") && israw)
+        kNamein += ".raw";
+
+    if (kNameout.IsNull())
+        kNameout = kNamein(0, kNamein.Last('.'));
+
+    if (!kNameout.EndsWith(".root"))
+        kNameout += ".root";
+
+//    if (!kSqlDataBase.IsNull() && !israw)
+//        gLog << warn << "WARNING - Option '--sql=' only valid for raw-files... ignored." << endl;
+
+    //
+    // Initialize Non-GUI (batch) mode
+    //
+    gROOT->SetBatch();
+
+    //
+    // check whether the given files are OK.
+    //
+    if (gSystem->AccessPathName(kNamein, kFileExists))
+    {
+        gLog << err << "Sorry, the input file '" << kNamein << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    const Bool_t fileexist = !gSystem->AccessPathName(kNameout, kFileExists);
+    const Bool_t writeperm = !gSystem->AccessPathName(kNameout, kWritePermission);
+
+    if (fileexist && !writeperm)
+    {
+        gLog << err << "Sorry, you don't have write permission for '" << kNameout << "'." << endl;
+        return -1;
+    }
+
+    if (fileexist && !kUpdate && !kForce)
+    {
+        gLog << err << "Sorry, file '" << kNameout << "' already existing." << endl;
+        return -1;
+    }
+
+    if (!fileexist && kUpdate)
+    {
+        gLog << warn << "File '" << kNameout << "' doesn't yet exist." << endl;
+        kUpdate=kFALSE;
+    }
+
+    //
+    // Evaluate possible start-/stop-time
+    //
+    if (kAutoTime && kUpdate && (isreport || isdc))
+        GetTimeFromFile(kNameout, kTimeStart, kTimeStop);
+
+    if (kTimeStart)
+        gLog << inf << "Start Time: " << kTimeStart << endl;
+    if (kTimeStop)
+        gLog << inf << "Stop  Time: " << kTimeStop << endl;
+
+    //
+    // Ignore TObject Streamer (bits, uniqueid) for MArray and MParContainer
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    //
+    MParList plist;
+
+    MTaskList tasks;
+    tasks.SetOwner();
+    plist.AddToList(&tasks);
+
+    //
+    // ---- The following is only necessary to supress some output ----
+    /*
+    MRawRunHeader runheader;
+    plist.AddToList(&runheader);
+
+    MRawEvtHeader evtheader;
+    plist.AddToList(&evtheader);
+
+    MRawEvtData evtdata;
+    plist.AddToList(&evtdata);
+
+    MRawCrateArray cratearray;
+    plist.AddToList(&cratearray);
+
+    MTime evttime;
+    plist.AddToList(&evttime);
+    */
+
+    //
+    // create the tasks which should be executed and add them to the list
+    // in the case you don't need parameter containers, all of them can
+    // be created by MRawFileRead::PreProcess
+    //
+    MTask   *read   = 0;
+    MFilter *filter = 0;
+    MTask   *write  = 0;
+
+    const TString option(kUpdate ? "UPDATE" : "RECREATE");
+    if (isreport || isdc)
+    {
+        MWriteRootFile *w = new MWriteRootFile(kNameout, option, "Magic root-file", kComprlvl);
+        if (isdc)
+        {
+            w->AddContainer("MTimeCurrents",      "Currents");
+            w->AddContainer("MCameraDC",          "Currents");
+            w->AddContainer("MReportCurrents",    "Currents");
+        }
+        else
+        {
+            w->AddContainer("MReportCamera",      "Camera");
+            w->AddContainer("MTimeCamera",        "Camera");
+            w->AddContainer("MCameraAUX",         "Camera");
+            w->AddContainer("MCameraCalibration", "Camera");
+            w->AddContainer("MCameraCooling",     "Camera");
+            w->AddContainer("MCameraHV",          "Camera");
+            w->AddContainer("MCameraLV",          "Camera");
+            w->AddContainer("MCameraLids",        "Camera");
+            w->AddContainer("MReportTrigger",     "Trigger");
+            w->AddContainer("MTimeTrigger",       "Trigger");
+            w->AddContainer("MTriggerBit",        "Trigger");
+            w->AddContainer("MTriggerIPR",        "Trigger");
+            w->AddContainer("MTriggerCell",       "Trigger");
+            w->AddContainer("MTriggerPrescFact",  "Trigger");
+            w->AddContainer("MTriggerLiveTime",   "Trigger");
+            w->AddContainer("MReportDrive",       "Drive");
+            w->AddContainer("MTimeDrive",         "Drive");
+            w->AddContainer("MReportCC",          "CC");
+            w->AddContainer("MTimeCC",            "CC");
+            w->AddContainer("MReportStarguider",  "Starguider");
+            w->AddContainer("MTimeStarguider",    "Starguider");
+            // w->AddContainer("MReportDAQ",         "DAQ");
+            // w->AddContainer("MTimeDAQ",           "DAQ");
+        }
+        write = w;
+
+        MReportFileReadCC *r = new MReportFileReadCC(kNamein);
+        r->SetTimeStart(kTimeStart);
+        r->SetTimeStop(kTimeStop);
+        if (isdc)
+        {
+            r->SetHasNoHeader();
+            r->AddToList("MReportCurrents");
+        }
+        else
+        {
+            r->SetRunNumber(kRunFile);
+            r->AddToList("MReportCC");
+            //r->AddToList("MReportDAQ");
+            r->AddToList("MReportDrive");
+            r->AddToList("MReportCamera");
+            r->AddToList("MReportTrigger");
+            r->AddToList("MReportStarguider");
+            if (kRunNumber>0)
+            {
+                r->AddToList("MReportRun");
+                filter = new MFDataMember("MReportRun.fRunNumber", '=', kRunNumber);
+                w->SetFilter(filter);
+            }
+        }
+        read = r;
+    }
+    else
+    {
+        read  = new MRawFileRead(kNamein);
+        static_cast<MRawFileRead*>(read)->SetInterleave(kInterleave);
+        static_cast<MRawFileRead*>(read)->SetForceMode(kForceProc);
+        write = new MRawFileWrite(kNameout, option, "Magic root-file", kComprlvl);
+    }
+
+    tasks.AddToList(read);
+    if (filter)
+        tasks.AddToList(filter);
+    /*
+    if (israw && !kSqlDataBase.IsNull())
+    {
+        MSqlInsertRun *ins = new MSqlInsertRun(kSqlDataBase);
+        ins->SetUpdate();
+        tasks.AddToList(ins);
+    }*/
+    tasks.AddToList(write);
+
+    //
+    // create the looping object and tell it about the parameters to use
+    // and the tasks to execute
+    //
+    MEvtLoop magic;
+    magic.SetParList(&plist);
+
+    //
+    // Start the eventloop which reads the raw file (MRawFileRead) and
+    // write all the information into a root file (MRawFileWrite)
+    //
+    // between reading and writing we can do, transformations, checks, etc.
+    // (I'm think of a task like MRawDataCheck)
+    //
+    if (!magic.Eventloop())
+    {
+        gLog << err << "ERROR: Merging and preprocessing failed!" << endl;
+        return -1;
+    }
+
+    tasks.PrintStatistics();
+
+    gLog << all << "Merpp finished successfull!" << endl;
+    return 0;
+}
Index: /tags/Mars-V0.9/mfbase/FBaseIncl.h
===================================================================
--- /tags/Mars-V0.9/mfbase/FBaseIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/FBaseIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mfbase/FBaseLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mfbase/FBaseLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/FBaseLinkDef.h	(revision 9772)
@@ -0,0 +1,16 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MFilterList+;
+
+#pragma link C++ class MF+;
+#pragma link C++ class MFEventSelector+;
+#pragma link C++ class MFEventSelector2+;
+#pragma link C++ class MFDataChain+;
+#pragma link C++ class MFDataMember+;
+#pragma link C++ class MFRealTimePeriod+;
+
+#endif
Index: /tags/Mars-V0.9/mfbase/MF.cc
===================================================================
--- /tags/Mars-V0.9/mfbase/MF.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MF.cc	(revision 9772)
@@ -0,0 +1,546 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  01/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MF                                                              
+//
+// With this filter you can filter in all variables from Mars parameter
+// containers.
+//
+// In the constructor you can give the filter rule, like
+//   "MHillas.fLength < 15"
+// Where MHillas is the name of the parameter container in the parameter
+// list and fLength is the name of the data member which should be used
+// for the filter rule. If the name of the container is use specified
+// (MyHillas) the name to give would be:
+//   "MyHillas.fLength < 15"
+//
+// Also more difficult rules are allowed, like:
+//   "MHillas.fWidth<0.5 && MHillas.fLength<0.6"
+//
+// You can also use parantheses:
+//   "MHillas.fSize>200 || (MHillas.fWidth<0.5 && MHillas.fLength<0.6)"
+//
+// If you want to use mathematic expressions (as defined in MDataChain)
+// you must encapsulate it in {}-parantheses, eg:
+//   "{log10(MHillas.fSize)}>3"
+//
+// For more details on available functions and expressions see MDataChain!
+//
+// The allowed logigal conditionals are:
+//   &&: logical and
+//   ||: logical or
+//   ^:  exclusive or
+//
+// As conditional signs, for now, only:
+//   <, >
+// are allowed.
+//
+//   -------->  '==' is NOT supported!
+//
+//
+// Warning: There is no priority rule build in. So better use parantheses
+//   to get correct results. The rule is parsed/evaluated from the left
+//   to the right, which means:
+//
+//   "MHillas.fSize>200 || MHillas.fWidth<0.5 && MHillas.fLength<0.6"
+//
+//    is parses as
+//
+//   "(MHillas.fSize>200 || MHillas.fWidth<0.5) && MHillas.fLength<0.6"
+//
+//
+// FIXME: The possibility to use also complete filters is missing.
+//        Maybe we can use gInterpreter->Calc("") for this.
+//        gROOT->ProcessLineFast("line");
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MF.h"
+
+#include <ctype.h>        // isalnum, ...
+#include <stdlib.h>       // strtod, ...
+#include <fstream>        // ofstream, ...
+
+#include <TMethodCall.h>
+
+#include "MParList.h"
+
+#include "MFilterList.h"
+#include "MFDataChain.h"
+#include "MFDataMember.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MF);
+
+using namespace std;
+
+const TString MF::gsDefName  = "MF";
+const TString MF::gsDefTitle = "Filter setup by a text-rule";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. Don't use.
+//
+MF::MF() : fF(NULL)
+{
+    fName  = gsDefName.Data();
+    fTitle = gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor. For the text describing the filter rule please see
+// the class description above.
+//
+MF::MF(const char *text, const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    *fLog << inf << "Parsing filter rule... " << flush;
+    if (!(fF=ParseString(text, 1)))
+    {
+        *fLog << err << dbginf << "Parsing '" << text << "' failed." << endl;
+        return;
+    }
+
+    *fLog << inf << "found: ";
+    fF->Print();
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete filters.
+//
+MF::~MF()
+{
+    if (fF)
+        delete fF;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the number of alphanumeric characters (including '.')
+// in the given string
+//
+Int_t MF::IsAlNum(TString txt) const
+{
+    int l = txt.Length();
+    for (int i = 0; i<l; i++)
+        if (!isalnum(txt[i]) && txt[i]!='.' && txt[i]!=';')
+            return i;
+
+    return l;
+}
+
+MFilter *MF::ParseRule(TString &txt, MFilter *filter0, Int_t level) const
+{
+    // For backward compatibility
+    txt.ReplaceAll("{", "(");
+    txt.ReplaceAll("}", ")");
+
+    const Int_t fg = txt.First('>');
+    const Int_t lg = txt.First('>');
+    const Int_t fl = txt.First('<');
+    const Int_t ll = txt.First('<');
+
+    if (fg<0 && fl<0)
+    {
+        MFilter *f = (MFilter*)GetNewObject(txt, MFilter::Class());
+        if (!f)
+        {
+            *fLog << err << dbginf << "Syntax Error: '" << txt << "' is neither a MFilter nor conditional sign found." << endl;
+            return NULL;
+        }
+        // FIXME: Search object through list...?
+        txt = "";
+        return f;
+    }
+
+    if (fg>=0 && fl>=0)
+    {
+        *fLog << err << dbginf << "Syntax Error: Two coditional signs found in " << txt << endl;
+        *fLog << "Currently you have to enclose all conditions in parantheses, like: \"(x<y) && (z<5)\"" << endl;
+        return NULL;
+    }
+    if (fg!=lg || fl!=ll)
+    {
+        *fLog << err << dbginf << "Syntax Error: Coditional sign found twice " << txt << endl;
+        return NULL;
+    }
+
+    const Int_t cond = fg<0 ? fl : fg;
+
+    const TString rule1 = txt(0, cond);
+    const TString rule2 = txt(cond+1, txt.Length());
+
+    Int_t lvl = gLog.GetDebugLevel();
+    gLog.SetDebugLevel(1);
+    MFilter *f = new MFDataChain(rule1.Data(), txt[cond], rule2.Data());
+    f->SetName(Form("Chain%02d%c", level, txt[cond]));
+    gLog.SetDebugLevel(lvl);
+
+    txt = "";
+    return f;
+}
+// --------------------------------------------------------------------------
+//
+// Parse a text string. Returns a corresponding filter of filter list.
+//
+MFilter *MF::ParseString(TString txt, Int_t level)
+{
+    MFilter *filter0=NULL;
+
+    TString type;
+    int nlist = 0;
+
+    while (!txt.IsNull())
+    {
+        MFilter *newfilter = NULL;
+
+        txt = txt.Strip(TString::kBoth);
+
+        //*fLog << all << setw(level) << " " << "Text: " << level << " '" << txt << "'" << endl;
+
+        switch (txt[0])
+        {
+        case '(':
+            {
+                //
+                // Search for the corresponding parantheses
+                //
+                Int_t first=1;
+                for (int cnt=0; first<txt.Length(); first++)
+                {
+                    if (txt[first]=='(')
+                        cnt++;
+                    if (txt[first]==')')
+                        cnt--;
+
+                    if (cnt==-1)
+                        break;
+                }
+
+                if (first==txt.Length())
+                {
+                    *fLog << err << dbginf << "Syntax Error: ')' missing." << endl;
+                    if (filter0)
+                        delete filter0;
+                    return NULL;
+                }
+
+                //
+                // Make a copy of the 'interieur' and delete the substringä
+                // including the parantheses
+                //
+                TString sub = txt(1, first-1);
+                txt.Remove(0, first+1);
+
+                //
+                // Parse the substring
+                //
+                newfilter = ParseString(sub, level+1);
+                if (!newfilter)
+                {
+                    *fLog << err << dbginf << "Parsing '" << sub << "' failed." << endl;
+                    if (filter0)
+                        delete filter0;
+                    return NULL;
+                }
+            }
+            break;
+
+        case ')':
+            *fLog << err << dbginf << "Syntax Error: Too many ')'" << endl;
+            if (filter0)
+                delete filter0;
+            return NULL;
+
+
+        case '&':
+        case '|':
+        case '^':
+            if (filter0)
+            {
+                //
+                // Check for the type of the conditional
+                //
+                TString is = txt[0];
+                txt.Remove(0, 1);
+
+                if (is==txt[0] && is!='^')
+                {
+                    is += txt[0];
+                    txt.Remove(0, 1);
+                }
+
+                //
+                // If no filter is available or the available filter
+                // is of a different conditional we have to create a new
+                // filter list with the new conditional
+                //
+                if (!filter0->InheritsFrom(MFilterList::Class()) || type!=is)
+                {
+                    MFilterList *list = new MFilterList(is);
+                    list->SetName(Form("List_%s_%d", (const char*)is, 10*level+nlist++));
+
+                    list->SetOwner();
+                    list->AddToList(filter0);
+                    filter0 = list;
+
+                    type = is;
+                }
+                continue;
+            }
+
+            *fLog << err << dbginf << "Syntax Error: First argument of condition missing." << endl;
+            if (filter0)
+                delete filter0;
+            return NULL;
+
+        default:
+            newfilter = ParseRule(txt, filter0, level++);
+            if (!newfilter)
+            {
+                if (filter0)
+                    delete filter0;
+                return NULL;
+            }
+        }
+
+        if (!filter0)
+        {
+            filter0 = newfilter;
+            continue;
+        }
+
+        if (!filter0->InheritsFrom(MFilterList::Class()))
+            continue;
+
+        ((MFilterList*)filter0)->AddToList(newfilter);
+    }
+
+    return filter0;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcess all filters.
+//
+Int_t MF::PreProcess(MParList *plist)
+{
+    if (!fF)
+    {
+        if (IsAllowEmpty())
+            return kTRUE;
+
+        *fLog << err << dbginf << "No filter rule available." << endl;
+        return kFALSE;
+    }
+
+    if (!fF->CallPreProcess(plist))
+    {
+        *fLog << err << dbginf << "PreProcessing filters in ";
+        *fLog << fName << " failed." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process all filters.
+//
+Int_t MF::Process()
+{
+    return fF ? fF->CallProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Postprocess all filters.
+//
+Int_t MF::PostProcess()
+{
+    return fF ? fF->CallPostProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the result of the filter rule. If no filter available the
+// condition is always true
+//
+Bool_t MF::IsExpressionTrue() const
+{
+    return fF ? fF->IsConditionTrue() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the chain.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MF::GetDataMember() const
+{
+  return fF ? fF->GetDataMember() : (TString)"";
+}
+
+void MF::StreamPrimitive(ofstream &out) const
+{
+    out << "   MF " << GetUniqueName();
+
+    if (!fF)
+    {
+        out << ";" << endl;
+        return;
+    }
+
+    out << "(\"" << fF->GetRule() << "\"";
+        if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the rule.
+// if now filter is set up '<n/a>' is printed.
+//
+void MF::Print(Option_t *opt) const
+{
+    *fLog << all << underline << GetDescriptor() << endl;
+    if (fF)
+        fF->Print();
+    else
+        *fLog << "<n/a>";
+    *fLog << endl << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for corresponding entries in resource file and setup filters.
+//
+// Assuming your MF-filter is called (Set/GetName): MyFilter
+//
+// First you can setup whether the filter is inverted or not:
+//     MyFilter.Inverted: yes, no  <default=no>
+//
+// Now setup the condition, eg:
+//     MyFilter.Condition: MHillas.fSize<1000
+// or
+//     MyFilter.Condition: MHillas.fSize>500 && MHillas.fSize<10000
+//
+// If you want to use more difficult filters you can split the
+// condition into subcondistions. Subcondistions are identified
+// by {}-brackets. Avoid trailing 0's! For example:
+//
+//     MyFilter.Condition: MHillas.fSize>500 && {0} && {1}
+//     MyFilter.0: MHillas.fSize>1000
+//     MyFilter.1: MHillas.fSize<10000
+//
+// The numbering must be continous and start with 0. You can use
+// a subcondition more than once. All {}-brackets are simply replaced
+// by the correspodning conditions. The rules how conditions can
+// be written can be found in the class description of MF and MDataChain.
+//
+Int_t MF::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Inverted", print))
+    {
+        rc = kTRUE;
+        SetInverted(GetEnvValue(env, prefix, "Inverted", IsInverted()));
+    }
+
+    if (!IsEnvDefined(env, prefix, "Condition", print))
+    {
+        if (rc)
+        {
+            *fLog << warn << GetDescriptor() << " ::ReadEnv - WARNING: No condition found." << endl;
+            SetAllowEmpty();
+        }
+        return rc;
+    }
+
+    TString rule = GetEnvValue(env, prefix, "Condition", "");
+    rule.ReplaceAll(" ", "");
+
+    Int_t idx=0;
+    while (1)
+    {
+        TString cond;
+        if (IsEnvDefined(env, prefix, Form("%d", idx), print))
+        {
+            cond += "(";
+            cond += GetEnvValue(env, prefix, Form("%d", idx), "");
+            cond += ")";
+        }
+
+        if (cond.IsNull())
+            break;
+
+        rule.ReplaceAll(Form("{%d}", idx), cond);
+        idx++;
+    }
+
+    if (fF)
+    {
+        delete fF;
+        fF = 0;
+    }
+
+    if (rule.IsNull())
+    {
+        *fLog << warn << GetDescriptor() << " ::ReadEnv - WARNING: Empty condition found." << endl;
+        SetAllowEmpty();
+        return kTRUE;
+    }
+
+    SetAllowEmpty(kFALSE);
+
+    if (!(fF=ParseString(rule, 1)))
+    {
+        *fLog << err << "MF::ReadEnv - ERROR: Parsing '" << rule << "' failed." << endl;
+        return kERROR;
+    }
+
+    if (print)
+    {
+        *fLog << inf << "found: ";
+        fF->Print();
+        *fLog << endl;
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mfbase/MF.h
===================================================================
--- /tags/Mars-V0.9/mfbase/MF.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MF.h	(revision 9772)
@@ -0,0 +1,66 @@
+#ifndef MARS_MF
+#define MARS_MF
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MF                                                                      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MParList;
+class TMethodCall;
+
+class MF : public MFilter
+{
+private:
+    static const TString gsDefName;  //!
+    static const TString gsDefTitle; //!
+
+    MFilter *fF; // Filter
+
+    Int_t IsRule(TString &txt, TString &rule) const;
+    Int_t IsVal(const TString &txt) const;
+    Int_t IsAlNum(TString txt) const;
+
+    MFilter *ParseRule(TString &txt, MFilter *filter0, Int_t level) const;
+    MFilter *ParseString(TString txt, Int_t level);
+
+    void StreamPrimitive(ofstream &out) const;
+
+    enum { kAllowEmpty = BIT(14) };
+
+public:
+    MF();
+    MF(const char *text, const char *name=NULL, const char *title=NULL);
+    ~MF();
+
+    // MF
+    void SetAllowEmpty(Bool_t b=kTRUE) { b ? SetBit(kAllowEmpty) : ResetBit(kAllowEmpty); }
+    Bool_t IsAllowEmpty() const { return TestBit(kAllowEmpty); }
+
+    // MFilter
+    TString GetRule() const { return fF ? fF->GetRule() : MFilter::GetRule(); }
+    TString GetDataMember() const;
+
+    Bool_t IsExpressionTrue() const;
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // TObject
+    void Print(Option_t *opt="") const;
+
+    // MParContainer
+    void SetVariables(const TArrayD &arr) { if (fF) fF->SetVariables(arr); }
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MF, 0) // A Filter for cuts in any data member
+};
+
+#endif
Index: /tags/Mars-V0.9/mfbase/MFDataChain.cc
===================================================================
--- /tags/Mars-V0.9/mfbase/MFDataChain.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFDataChain.cc	(revision 9772)
@@ -0,0 +1,191 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  11/2002 <mailto:tbretz@astro.uni-wueruburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MFDataChain                                                              
+//
+// With this filter you can filter in all variables from Mars parameter
+// containers using rules (for more details see MDataChain).
+//
+// In the constructor you can give the filter variable, like
+//   "sqrt(MHillas.fLength*MHillas.fLength)"
+// Where MHillas is the name of the parameter container in the parameter
+// list and fLength is the name of the data member which should be used
+// for the filter rule. If the name of the container is use specified
+// (MyHillas) the name to give would be:
+//   "MyHillas.fLength"
+//
+// For example:
+//   MFDataChain filter("sqr(MHillas.fLength)", '<', 150);
+//   MFDataChain filter("MHillas.fLength", '<', "MHillas.fWidth");
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFDataChain.h"
+
+#include <fstream>
+
+#include <TMethodCall.h>
+
+#include "MParList.h"
+
+#include "MDataValue.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFDataChain);
+
+using namespace std;
+
+MFDataChain::MFDataChain(const char *name, const char *title)
+    : fCond(0)
+{
+    fName  = name  ? name  : "MFDataChain";
+    fTitle = title ? title : "Filter using any data member of a class";
+}
+
+// --------------------------------------------------------------------------
+//
+MFDataChain::MFDataChain(const char *rule, const char type, const Double_t val,
+                         const char *name, const char *title)
+    : fData(rule), fCond(new MDataValue(val))
+{
+    fName  = name  ? name  : "MFDataChain";
+    fTitle = title ? title : "Filter using any data member of a class";
+
+    //AddToBranchList(member);
+
+    fFilterType = (type=='<' ? kELowerThan : kEGreaterThan);
+
+    if (type!='<' && type!='>')
+        *fLog << warn << dbginf << "Warning: Neither '<' nor '>' specified... using '>'." << endl;
+}
+
+MFDataChain::MFDataChain(const char *rule, const char type, const char *cond,
+                         const char *name, const char *title)
+    : fData(rule), fCond(new MDataChain(cond))
+{
+    fName  = name  ? name  : "MFDataChain";
+    fTitle = title ? title : "Filter using any data member of a class";
+
+    //AddToBranchList(member);
+
+    fFilterType = (type=='<' ? kELowerThan : kEGreaterThan);
+
+    if (type!='<' && type!='>')
+        *fLog << warn << dbginf << "Warning: Neither '<' nor '>' specified... using '>'." << endl;
+}
+
+MFDataChain::~MFDataChain()
+{
+    if (fCond)
+        delete fCond;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDataChain::PreProcess(MParList *plist)
+{
+    if (!fCond)
+    {
+        *fLog << "No condition available - don't call default constructor!" << endl;
+        return kFALSE;
+    }
+    return fData.PreProcess(plist) && fCond->PreProcess(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDataChain::Process()
+{
+    const Double_t data = fData.GetValue();
+    const Double_t cond = fCond->GetValue();
+
+    switch (fFilterType)
+    {
+    case kELowerThan:
+        fResult = (data < cond);
+        return kTRUE;
+    case kEGreaterThan:
+        fResult = (data > cond);
+        return kTRUE;
+    }
+
+    return kFALSE;
+}
+
+void MFDataChain::Print(Option_t *) const
+{
+    *fLog << GetRule() << flush;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Crahses if default constructor called.
+//
+void MFDataChain::StreamPrimitive(ofstream &out) const
+{
+    out << "   MFDataChain " << GetUniqueName() << "(\"";
+    out << fData.GetRule() << "\", '";
+    out << (fFilterType==kELowerThan?"<":">");
+    out << "', ";
+
+    if (fCond->InheritsFrom(MDataValue::Class()))
+        out << ((MDataValue*)fCond)->GetValue();
+    else
+        out << "\"" << fCond->GetRule() << "\"";
+
+    out << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Crahses if default constructor called.
+//
+TString MFDataChain::GetRule() const
+{
+    TString ret(fData.GetRule());
+    ret += fFilterType==kELowerThan?"<":">";
+
+    TString str;
+    str += fCond->GetRule();
+    ret += str.Strip(TString::kBoth);
+    return ret;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Crahses if default constructor called.
+//
+TString MFDataChain::GetDataMember() const
+{
+    if (!fData.IsValid())
+        return "";
+
+    TString ret(fData.GetDataMember());
+    ret += ",";
+    ret += fCond->GetDataMember();
+    return ret;
+}
Index: /tags/Mars-V0.9/mfbase/MFDataChain.h
===================================================================
--- /tags/Mars-V0.9/mfbase/MFDataChain.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFDataChain.h	(revision 9772)
@@ -0,0 +1,60 @@
+#ifndef MARS_MFDataChain
+#define MARS_MFDataChain
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFDataChain                                                                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+#ifndef MARS_MDataChain
+#include "MDataChain.h"
+#endif
+
+class MParList;
+
+class MFDataChain : public MFilter
+{
+private:
+    MDataChain fData;
+    MData     *fCond;
+
+    typedef enum { kELowerThan, kEGreaterThan } FilterType_t;
+    FilterType_t fFilterType;
+
+    Bool_t  fResult;           //!
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MFDataChain(const char *name=NULL, const char *title=NULL);
+    MFDataChain(const char *rule, const char type, const Double_t val,
+                const char *name=NULL, const char *title=NULL);
+    MFDataChain(const char *rule, const char type, const char *cond,
+                const char *name=NULL, const char *title=NULL);
+    ~MFDataChain();
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    void Print(Option_t *opt = "") const;
+
+    TString GetRule() const;
+    TString GetDataMember() const;
+
+    void SetVariables(const TArrayD &arr)
+    {
+        fData.SetVariables(arr);
+        if (fCond)
+            fCond->SetVariables(arr);
+    }
+
+    ClassDef(MFDataChain, 1) // A Filter for cuts in any data member
+};
+
+#endif
Index: /tags/Mars-V0.9/mfbase/MFDataMember.cc
===================================================================
--- /tags/Mars-V0.9/mfbase/MFDataMember.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFDataMember.cc	(revision 9772)
@@ -0,0 +1,173 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  01/2002 <mailto:tbretz@astro.uni-wueruburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MFDataMember                                                              
+//
+// With this filter you can filter in all variables from Mars parameter
+// containers.
+//
+// In the constructor you can give the filter variable, like
+//   "MHillas.fLength"
+// Where MHillas is the name of the parameter container in the parameter
+// list and fLength is the name of the data member which should be used
+// for the filter rule. If the name of the container is use specified
+// (MyHillas) the name to give would be:
+//   "MyHillas.fLength"
+//
+// For example:
+//   MFDataMember filter("MHillas.fLength", '<', 150);
+//
+// You can test '<', '>' and '='. Warning: Using '=' may give strange results
+// in case you are comparing floating point values.
+//
+// In case the data member is detected to be an integer value, both
+// the data member and the val given as argument in the constructor
+// are castet to Long_t.
+//
+// To test != use the SetInverted() member function.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFDataMember.h"
+
+#include <fstream>
+
+#include <TMethodCall.h>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFDataMember);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MFDataMember::MFDataMember(const char *member, const char type, const Double_t val,
+                           const char *name, const char *title)
+    : fData(member), fValue(val)
+{
+    fName  = name  ? name  : "MFDataMember";
+    fTitle = title ? title : "Filter using any data member of a class";
+
+    AddToBranchList(member);
+
+    switch (type)
+    {
+    case '>': fFilterType = kEGreaterThan; break;
+    case '<': fFilterType = kELowerThan;   break;
+    case '=': fFilterType = kEEqual;       break;
+    default:  fFilterType = kEGreaterThan; break;
+    }
+
+    if (type!='<' && type!='=' && type!='>')
+        *fLog << warn << dbginf << "Warning: Neither '<' nor '=' nor '>' specified... using '>'." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDataMember::PreProcess(MParList *plist)
+{
+    return fData.PreProcess(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDataMember::Process()
+{
+    if (fData.IsInt())
+    {
+        switch (fFilterType)
+        {
+        case kELowerThan:
+            fResult = ((Long_t)fData.GetValue() < (Long_t)fValue);
+            return kTRUE;
+        case kEGreaterThan:
+            fResult = ((Long_t)fData.GetValue() > (Long_t)fValue);
+            return kTRUE;
+        case kEEqual:
+            fResult = ((Long_t)fData.GetValue() == (Long_t)fValue);
+            return kTRUE;
+        }
+    }
+    else
+    {
+        switch (fFilterType)
+        {
+        case kELowerThan:
+            fResult = (fData.GetValue() < fValue);
+            return kTRUE;
+        case kEGreaterThan:
+            fResult = (fData.GetValue() > fValue);
+            return kTRUE;
+        case kEEqual:
+            fResult = (fData.GetValue() == fValue);
+            return kTRUE;
+        }
+    }
+
+    return kFALSE;
+}
+
+void MFDataMember::Print(Option_t *) const
+{
+    *fLog << GetRule() << flush;
+}
+
+void MFDataMember::StreamPrimitive(ofstream &out) const
+{
+    out << "   MFDataMember " << GetUniqueName() << "(\"";
+    out << fData.GetRule() << "\", '";
+    switch (fFilterType)
+    {
+    case kEGreaterThan: out << '>'; break;
+    case kELowerThan:   out << '<'; break;
+    case kEEqual:       out << '='; break;
+    }
+    out << "', " << fValue << ");" << endl;
+}
+
+TString MFDataMember::GetRule() const
+{
+    TString ret = fData.GetRule();
+    switch (fFilterType)
+    {
+    case kEGreaterThan: ret +='>'; break;
+    case kELowerThan:   ret +='<'; break;
+    case kEEqual:       ret +='='; break;
+    }
+
+    TString str;
+    str += fValue;
+
+    return ret+str.Strip(TString::kBoth);
+}
+
+TString MFDataMember::GetDataMember() const
+{
+    return fData.GetDataMember();
+}
Index: /tags/Mars-V0.9/mfbase/MFDataMember.h
===================================================================
--- /tags/Mars-V0.9/mfbase/MFDataMember.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFDataMember.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MFDataMember
+#define MARS_MFDataMember
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+#ifndef MARS_MDataMember
+#include "MDataMember.h"
+#endif
+
+class MParList;
+
+class MFDataMember : public MFilter
+{
+private:
+    MDataMember fData;
+
+    typedef enum { kELowerThan, kEGreaterThan, kEEqual } FilterType_t;
+    FilterType_t fFilterType;
+
+    Bool_t  fResult;           //!
+    Double_t fValue;
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    enum {
+        kIsInt = BIT(14)
+    };
+    MFDataMember(const char *member, const char type, const Double_t val,
+                 const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    void Print(Option_t *opt = "") const;
+
+    TString GetRule() const;
+    TString GetDataMember() const;
+
+    void SetVariables(const TArrayD &arr) { fData.SetVariables(arr); }
+
+    ClassDef(MFDataMember, 1) // A Filter for cuts in any data member
+};
+
+#endif
Index: /tags/Mars-V0.9/mfbase/MFEventSelector.cc
===================================================================
--- /tags/Mars-V0.9/mfbase/MFEventSelector.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFEventSelector.cc	(revision 9772)
@@ -0,0 +1,228 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 01/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MFEventSelector
+//
+// This is a filter to make a selection of events from a file. At the
+// present implementation you can only use a random selection.
+//
+// This filter can be used for a random split...
+//
+// If you want to fill only 50% of your events into a histogram please use:
+//   MFEventSelector sel;
+//   sel.SetSelectionRatio(0.5);
+//   MFillH filler(...);
+//   filler.SetFilter(&sel);
+//   tlist.AddToList(&sel);
+//   tlist.AddToList(&filler);
+//
+// To get around 2000 events from all events use (Remark: This will only
+// work if the parlist has an entry called MTaskList which has a task
+// MRead inheriting from MRead):
+//   MFEventSelector sel;
+//   sel.SetNumSelectEvts(2000);
+//   MFillH filler(...);
+//   filler.SetFilter(&sel);
+//   tlist.AddToList(&sel);
+//   tlist.AddToList(&filler);
+//
+// If you don't have MRead available you have to set the number of
+// total events manually, using sel.SetNumTotalEvts(10732);
+//
+// The random number is generated using gRandom->Uniform(). You may
+// control this procedure using the global object gRandom.
+//
+// Because of the random numbers this works best for huge samples...
+//
+// Don't try to use this filter for the reading task: This won't work!
+//
+// Remark: You can also use the filter together with MContinue
+//
+//
+// FIXME: Merge MFEventSelector and MFEventSelector2
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFEventSelector.h"
+
+#include <TRandom.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MRead.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFEventSelector);
+
+using namespace std;
+
+static const TString gsDefName  = "MFEventSelector";
+static const TString gsDefTitle = "Filter to select events";
+
+// --------------------------------------------------------------------------
+//
+// Constructor. For the text describing the filter rule please see
+// the class description above.
+//
+MFEventSelector::MFEventSelector(const char *name, const char *title)
+: fNumTotalEvts(-1), fNumSelectEvts(-1), fSelRatio(-1), fNumSelectedEvts(0)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set a probability with which events are selected. Eg, f=0.5
+// will select roughly half of all events.
+//
+void MFEventSelector::SetSelectionRatio(Float_t f)
+{
+    if (f < 0)
+    {
+        *fLog << warn << "MFEventSelector::SetSelectionRatio: WARNING - Probability less than 0... set to 0." << endl;
+        f = 0;
+    }
+
+    if (f > 1)
+    {
+        *fLog << warn << "MFEventSelector::SetSelectionRatio: WARNING - Probability greater than 1... set to 1." << endl;
+        f = 1;
+    }
+    fSelRatio = f;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcess all filters.
+//
+Int_t MFEventSelector::PreProcess(MParList *plist)
+{
+    fNumSelectedEvts = 0;
+
+    // In the case a ratio was set by the user we are done.
+    if (fSelRatio>0)
+        return kTRUE;
+
+    // If the number of total events wasn't set try to get it
+    if (fNumTotalEvts<0)
+    {
+        MTaskList *tlist = (MTaskList*)plist->FindObject("MTaskList");
+        if (!tlist)
+        {
+            *fLog << err << "Can't determin total number of events... no MTaskList." << endl;
+            return kFALSE;
+        }
+
+        MRead *read = (MRead*)tlist->FindObject("MRead");
+        if (!read)
+        {
+            *fLog << err << "Can't determin total number of events from 'MRead'." << endl;
+            return kFALSE;
+        }
+        fNumTotalEvts = read->GetEntries();
+
+        SetBit(kNumTotalFromFile);
+    }
+
+    // Calculate selection probability
+    fSelRatio = (Double_t)fNumSelectEvts/fNumTotalEvts;
+
+    *fLog << inf << "MFEventSelector:  Selection probability = " << fNumSelectEvts;
+    *fLog << "/" << fNumTotalEvts << " = " << Form("%.2f", fSelRatio) << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process all filters, FIXME: Make it fit the requested number of events
+// exactly like it is done in MFEventSelector2. This can be done by merging
+// both classes!
+//
+Int_t MFEventSelector::Process()
+{
+    fResult = gRandom->Uniform() < fSelRatio;
+
+    if (!fResult)
+        return kTRUE;
+
+    fNumSelectedEvts++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Postprocess all filters.
+//
+Int_t MFEventSelector::PostProcess()
+{
+    //---------------------------------
+    if (GetNumExecutions() != 0)
+    {
+        const Double_t sel = (Double_t)fNumSelectedEvts/GetNumExecutions();
+        const UInt_t   non = GetNumExecutions()-fNumSelectedEvts;
+
+        *fLog << inf << dec << setfill(' ') << endl;
+        *fLog << GetDescriptor() << " execution statistics:" << endl;
+
+        *fLog << " " << setw(7) << non << " (" << setw(3);
+        *fLog << (int)(100*(1-sel)) << "%) Events not selected" << endl;
+
+        *fLog << " " << setw(7) << fNumSelectedEvts << " (";
+        *fLog << (int)(100*sel) << "%) Events selected!" << endl;
+        *fLog << endl;
+    }
+
+    //---------------------------------
+    if (TestBit(kNumTotalFromFile))
+        fNumTotalEvts = -1;
+
+    return kTRUE;
+}
+
+void MFEventSelector::StreamPrimitive(ofstream &out) const
+{
+    /*
+    out << "   MF " << GetUniqueName();
+
+    if (!fFilter)
+    {
+        out << ";" << endl;
+        return;
+    }
+
+    out << "(\"" << fFilter->GetRule() << "\"";
+        if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+    */
+}
Index: /tags/Mars-V0.9/mfbase/MFEventSelector.h
===================================================================
--- /tags/Mars-V0.9/mfbase/MFEventSelector.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFEventSelector.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MFEventSelector
+#define MARS_MFEventSelector
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MParList;
+
+class MFEventSelector : public MFilter
+{
+private:
+    Int_t   fNumTotalEvts;    // Number of total events from which are selected
+    Int_t   fNumSelectEvts;   // Number of events to be selected
+    Float_t fSelRatio;        // Selection Probability
+
+    Int_t   fNumSelectedEvts; //! Number of events which have been selected
+
+    Bool_t  fResult;          //! Reseult of a single selection
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    enum { kNumTotalFromFile = BIT(14) };
+
+public:
+    MFEventSelector(const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    void SetNumTotalEvts(Int_t n)  { fNumTotalEvts = n; ResetBit(kNumTotalFromFile); }
+    void SetNumSelectEvts(Int_t n) { fNumSelectEvts = n; }
+    void SetSelectionRatio(Float_t f);
+
+    ClassDef(MFEventSelector, 0) // A filter to do a random selection of events
+};
+
+#endif
Index: /tags/Mars-V0.9/mfbase/MFEventSelector2.cc
===================================================================
--- /tags/Mars-V0.9/mfbase/MFEventSelector2.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFEventSelector2.cc	(revision 9772)
@@ -0,0 +1,596 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz,   01/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek 11/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MFEventSelector2
+//
+// This is a filter to make a selection of events from a file, according to
+// a certain requested distribution in a given parameter (or combination
+// of parameters). The distribution is passed to the class through a histogram
+// of the relevant parameter(s) contained in an object of type MH3. The filter
+// will return true or false in each event such that the final distribution
+// of the parameter(s) for the events surviving the filter is the desired one. 
+// The selection of which events are kept in each bin of the parameter(s) is 
+// made at random (obviously the selection probability depends on the 
+// values of the parameters, and is dictated by the input histogram).
+//
+// This procedure requires the determination of the original distribution
+// of the given parameters for the total sample of events on the input file.
+// If the event loop contains a filter with name "FilterSelector2", this
+// filter will be applied when determining the original distribution.
+//
+// See Constructor for more instructions and also the example below:
+//
+// --------------------------------------------------------------------
+//
+// void select()
+// {
+//     MParList plist;
+//     MTaskList tlist;
+// 
+//     MStatusDisplay *d=new MStatusDisplay;
+// 
+//     plist.AddToList(&tlist);
+// 
+//     MReadTree read("Events", "myinputfile.root");
+//     read.DisableAutoScheme();
+//     // Accelerate execution...
+//     // read.EnableBranch("MMcEvt.fTelescopeTheta");
+// 
+//     // create nominal distribution (theta converted into degrees)
+//     MH3 nomdist("r2d(MMcEvt.fTelescopeTheta)");
+//     MBinning binsx;
+//     binsx.SetEdges(5, 0, 45);   // five bins from 0deg to 45deg
+//     MH::SetBinning(&nomdist.GetHist(), &binsx);
+//
+//     // use this to create a nominal distribution in 2D
+//     //  MH3 nomdist("r2d(MMcEvt.fTelescopeTheta)", "MMcEvt.fEnergy");
+//     //  MBinning binsy;
+//     //  binsy.SetEdgesLog(5, 10, 10000);
+//     //  MH::SetBinning((TH2*)&nomdist.GetHist(), &binsx, &binsy);
+//
+//     // Fill the nominal distribution with whatever you want:
+//     for (int i=0; i<nomdist.GetNbins(); i++)
+//         nomdist.GetHist().SetBinContent(i, i*i);
+// 
+//     MFEventSelector2 test(nomdist);
+//     test.SetNumMax(9999);  // total number of events selected
+//     MContinue cont(&test);
+// 
+//     MEvtLoop run;
+//     run.SetDisplay(d);
+//     run.SetParList(&plist);
+//     tlist.AddToList(&read);
+//     tlist.AddToList(&cont);
+// 
+//     if (!run.Eventloop())
+//         return;
+// 
+//     tlist.PrintStatistics();
+// }
+// 
+// --------------------------------------------------------------------
+//
+// The random number is generated using gRandom->Rndm(). You may
+// control this procedure using the global object gRandom.
+//
+// Because of the random numbers this works best for huge samples...
+//
+// Don't try to use this filter for the reading task or as a selector
+// in the reading task: This won't work!
+//
+// Remark: You can also use the filter together with MContinue
+//
+//
+// FIXME: Merge MFEventSelector and MFEventSelector2
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFEventSelector2.h"
+
+#include <TRandom.h>        // gRandom
+#include <TCanvas.h>        // TCanvas
+
+#include "MH3.h"            // MH3
+#include "MRead.h"          // MRead
+#include "MEvtLoop.h"       // MEvtLoop
+#include "MTaskList.h"      // MTaskList
+#include "MBinning.h"       // MBinning
+#include "MContinue.h"      // 
+#include "MFillH.h"         // MFillH
+#include "MParList.h"       // MParList
+#include "MStatusDisplay.h" // MStatusDisplay
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFEventSelector2);
+
+using namespace std;
+
+const TString MFEventSelector2::gsDefName  = "MFEventSelector2";
+const TString MFEventSelector2::gsDefTitle = "Filter to select events with a given distribution";
+
+// --------------------------------------------------------------------------
+//
+// Constructor. Takes a reference to an MH3 which gives you
+//  1) The nominal distribution. The distribution is renormalized, so
+//     that the absolute values do not matter. To crop the distribution
+//     to a nominal value of total events use SetNumMax
+//  2) The parameters histogrammed in MH3 are those on which the
+//     event selector will work, eg
+//       MH3 hist("MMcEvt.fTelescopeTheta", "MMcEvt.fEnergy");
+//     Would result in a redistribution of Theta and Energy.
+//  3) Rules are also accepted in the argument of MH3, for instance: 
+//       MH3 hist("MMcEvt.fTelescopeTheta");
+//     would result in redistributing Theta, while
+//       MH3 hist("cos(MMcEvt.fTelescopeTheta)");
+//     would result in redistributing cos(Theta).
+//
+//  If the reference distribution doesn't contain entries (GetEntries()==0)
+//     the original distribution will be used as the nominal distribution;
+//     note that also in this case a dummy nominal distribution has to be
+//     provided in the first argument (the dummy distribution defines the
+//     variable(s) of interest, their binnings and their requested ranges;
+//     events outside these ranges won't be accepted).
+//
+//  Set default name of filter to be applied when determining the original
+//  distribution for all data on the input file to "FilterSelector2"
+//
+MFEventSelector2::MFEventSelector2(MH3 &hist, const char *name, const char *title)
+    : fHistOrig(NULL), fHistNom(&hist), fHistRes(NULL),
+    fDataX(hist.GetRule('x')), fDataY(hist.GetRule('y')),
+    fDataZ(hist.GetRule('z')), fNumMax(-1), fCanvas(0),
+    fFilterName("FilterSelector2"), fHistIsProbability(kFALSE),
+    fUseOrigDist(kTRUE)
+{
+    fName  = name  ? (TString)name  : gsDefName;
+    fTitle = title ? (TString)title : gsDefTitle;
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete fHistRes if instatiated
+//
+MFEventSelector2::~MFEventSelector2()
+{
+    if (fHistRes)
+        delete fHistRes;
+}
+
+//---------------------------------------------------------------------------
+//
+// Recreate a MH3 from fHistNom used as a template. Copy the Binning
+// from fHistNom to the new histogram, and return a pointer to the TH1
+// base class of the MH3.
+//
+TH1 &MFEventSelector2::InitHistogram(MH3* &hist)
+{
+    // if fHistRes is already allocated delete it first
+    if (hist)
+        delete hist;
+
+    // duplicate the fHistNom histogram
+    hist = (MH3*)fHistNom->New();
+
+    // copy binning from one histogram to the other one
+    MH::SetBinning(&hist->GetHist(), &fHistNom->GetHist());
+
+    return hist->GetHist();
+}
+
+// --------------------------------------------------------------------------
+//
+// Try to read the present distribution from the file. Therefore the
+// Reading task of the present loop is used in a new eventloop.
+//
+Bool_t MFEventSelector2::ReadDistribution(MRead &read, MFilter *filter)
+{
+    if (read.GetEntries() > kMaxUInt) // FIXME: LONG_MAX ???
+    {
+        *fLog << err << "kIntMax exceeded." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator("MFEventSelector2::ReadDistribution");
+    *fLog << " - Start of eventloop to generate the original distribution..." << endl;
+
+    if (filter != NULL)
+        *fLog << " - filter used: " << filter->GetDescriptor() << endl;
+
+
+    MEvtLoop run("ReadDistribution");
+
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    run.SetParList(&plist);
+
+    MBinning binsx("BinningMH3X");
+    MBinning binsy("BinningMH3Y");
+    MBinning binsz("BinningMH3Z");
+    binsx.SetEdges(fHistNom->GetHist(), 'x');
+    binsy.SetEdges(fHistNom->GetHist(), 'y');
+    binsz.SetEdges(fHistNom->GetHist(), 'z');
+    plist.AddToList(&binsx);
+    plist.AddToList(&binsy);
+    plist.AddToList(&binsz);
+
+    MFillH fill(fHistOrig);
+    fill.SetName("FillHistOrig");
+    fill.SetBit(MFillH::kDoNotDisplay);
+    tlist.AddToList(&read);
+
+    MContinue contfilter(filter);
+    if (filter != NULL)
+    {
+      contfilter.SetName("ContFilter");
+      tlist.AddToList(&contfilter);
+    }
+
+    tlist.AddToList(&fill);
+    run.SetDisplay(fDisplay);
+    if (!run.Eventloop())
+    {
+        *fLog << err << dbginf << "Evtloop failed... abort." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    *fLog << inf;
+    *fLog << "MFEventSelector2::ReadDistribution:" << endl;
+    *fLog << " - Original distribution has " << fHistOrig->GetHist().GetEntries() << " entries." << endl;
+    *fLog << " - End of eventloop to generate the original distribution." << endl;
+    fLog->Separator();
+
+    return read.Rewind();
+}
+
+// --------------------------------------------------------------------------
+//
+// After reading the histograms the arrays used for the random event
+// selection are created. If a MStatusDisplay is set the histograms are
+// displayed there.
+//
+void MFEventSelector2::PrepareHistograms()
+{
+    TH1 &ho = fHistOrig->GetHist();
+
+    //-------------------
+    // if requested
+    // set the nominal distribution equal to the original distribution
+
+    const Bool_t fUseOrigDist = fHistNom->GetHist().GetEntries()==0;
+    TH1 *hnp =  fUseOrigDist ? (TH1*)(fHistOrig->GetHist()).Clone() : 
+                              &fHistNom->GetHist();
+
+    TH1 &hn = *hnp;
+    //--------------------
+
+    // normalize to number of counts in primary distribution
+    hn.Scale(1./hn.Integral());
+
+    MH3 *h3 = NULL;
+    TH1 &hist = InitHistogram(h3);
+
+    hist.Divide(&hn, &ho);
+    hist.Scale(1./hist.GetMaximum());
+
+    if (fCanvas)
+    {
+        fCanvas->Clear();
+        fCanvas->Divide(2,2);
+
+        fCanvas->cd(1);
+        gPad->SetBorderMode(0);
+        hn.DrawCopy();
+
+        fCanvas->cd(2);
+        gPad->SetBorderMode(0);
+        ho.DrawCopy();
+    }
+    hn.Multiply(&ho, &hist);
+    hn.SetTitle("Resulting Nominal Distribution");
+
+    if (fNumMax>0)
+    {
+        *fLog << inf;
+        *fLog << "MFEventSelector2::PrepareHistograms:" << endl;
+        *fLog << " - requested number of events = " << fNumMax << endl;
+        *fLog << " - maximum number of events possible = " << hn.Integral() << endl;
+
+        if (fNumMax > hn.Integral())
+	{
+            *fLog << warn << "WARNING - Requested no.of events (" << fNumMax;
+            *fLog << ") is too high... reduced to " << hn.Integral() << endl;
+	}
+        else
+            hn.Scale(fNumMax/hn.Integral());
+    }
+
+    hn.SetEntries(hn.Integral()+0.5);
+    if (fCanvas)
+    {
+        fCanvas->cd(3);
+        gPad->SetBorderMode(0);
+        hn.DrawCopy();
+
+        fCanvas->cd(4);
+        gPad->SetBorderMode(0);
+        fHistRes->Draw();
+    }
+    delete h3;
+
+    const Int_t num = fHistRes->GetNbins();
+    fIs.Set(num);
+    fNom.Set(num);
+    for (int i=0; i<num; i++)
+    {
+        fIs[i]  = (Long_t)(ho.GetBinContent(i+1)+0.5);
+        fNom[i] = (Long_t)(hn.GetBinContent(i+1)+0.5);
+    }
+
+    if (fUseOrigDist)
+      delete hnp;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcess the data rules extracted from the MH3 nominal distribution
+//
+Bool_t MFEventSelector2::PreProcessData(MParList *parlist)
+{
+    switch (fHistNom->GetDimension())
+    {
+    case 3:
+        if (!fDataZ.PreProcess(parlist))
+        {
+            *fLog << err << "Preprocessing of rule for z-axis failed... abort." << endl;
+            return kFALSE;
+        }
+        // FALLTHROUGH!
+    case 2:
+        if (!fDataY.PreProcess(parlist))
+        {
+            *fLog << err << "Preprocessing of rule for y-axis failed... abort." << endl;
+            return kFALSE;
+        }
+        // FALLTHROUGH!
+    case 1:
+        if (!fDataX.PreProcess(parlist))
+        {
+            *fLog << err << "Preprocessing of rule for x-axis failed... abort." << endl;
+            return kFALSE;
+        }
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcess the filter. Means:
+//  1) Preprocess the rules
+//  2) Read The present distribution from the file.
+//  3) Initialize the histogram for the resulting distribution
+//  4) Prepare the random selection
+//  5) Repreprocess the reading and filter task.
+//
+Int_t MFEventSelector2::PreProcess(MParList *parlist)
+{
+    memset(fCounter, 0, sizeof(fCounter));
+
+    MTaskList *tasklist = (MTaskList*)parlist->FindObject("MTaskList");
+    if (!tasklist)
+    {
+        *fLog << err << "MTaskList not found... abort." << endl;
+        return kFALSE;
+    }
+
+    if (!PreProcessData(parlist))
+        return kFALSE;
+
+    fHistNom->SetTitle(fHistIsProbability ? "ProbabilityDistribution" : 
+                                            "Users Nominal Distribution");
+
+    if (fHistIsProbability)
+        return kTRUE;
+
+    InitHistogram(fHistOrig);
+    InitHistogram(fHistRes);
+
+    fHistOrig->SetTitle("Primary Distribution");
+    fHistRes->SetTitle("Resulting Distribution");
+
+    // Initialize online display if requested
+    fCanvas = fDisplay ? &fDisplay->AddTab(GetName()) : NULL;
+    if (fCanvas)
+        fHistOrig->Draw();
+
+    // Generate primary distribution
+    MRead *read = (MRead*)tasklist->FindObject("MRead");
+    if (!read)
+    {
+        *fLog << err << "MRead not found in tasklist... abort." << endl;
+        return kFALSE;
+    }
+
+    MFilter *filter = (MFilter*)tasklist->FindObject(fFilterName);
+    if (!filter || !filter->InheritsFrom(MFilter::Class()))
+    {
+        *fLog << inf << "No filter will be used when making the original distribution" << endl;
+        filter = NULL;
+    }
+
+    if (!ReadDistribution(*read, filter))
+        return kFALSE;
+
+    // Prepare histograms and arrays for selection
+    PrepareHistograms();
+
+    *fLog << all << "PreProcess..." << flush;
+
+    if (filter != NULL)
+    {
+      const Int_t rcf = filter->CallPreProcess(parlist);
+      if (rcf!=kTRUE)
+        return rcf;
+    }
+
+    const Int_t rcr = read->CallPreProcess(parlist);
+    return rcr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Part of Process(). Select() at the end checks whether a selection should
+// be done or not. Under-/Overflowbins are rejected.
+//
+Bool_t MFEventSelector2::Select(Int_t bin)
+{
+    // under- and overflow bins are not accepted
+    if (bin<0)
+        return kFALSE;
+
+    Bool_t rc = kFALSE;
+
+    if (gRandom->Rndm()*fIs[bin]<=fNom[bin])
+    {
+        // how many events do we still want to read in this bin
+        fNom[bin] -= 1;
+        rc = kTRUE;
+
+        // fill bin (same as Fill(valx, valy, valz))
+        TH1 &h = fHistRes->GetHist();
+        h.AddBinContent(bin+1);
+        h.SetEntries(h.GetEntries()+1);
+    }
+
+    // how many events are still pending to be read
+    fIs[bin] -= 1;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MFEventSelector2::SelectProb(Int_t ibin) const
+{
+    //
+    // If value is outside histogram range, accept event
+    //
+    return ibin<0 ? kTRUE : 
+           fHistNom->GetHist().GetBinContent(ibin) > gRandom->Uniform();
+}
+
+// --------------------------------------------------------------------------
+//
+// fIs[i] contains the distribution of the events still to be read from
+// the file. fNom[i] contains the number of events in each bin which
+// are requested.
+// The events are selected by:
+//     gRandom->Rndm()*fIs[bin]<=fNom[bin]
+//
+Int_t MFEventSelector2::Process()
+{
+    // get x,y and z (0 if fData not valid)
+    const Double_t valx=fDataX.GetValue();
+    const Double_t valy=fDataY.GetValue();
+    const Double_t valz=fDataZ.GetValue();
+
+    // don't except the event if it is outside the axis range
+    // of the requested distribution
+    const Int_t ibin = fHistNom->FindFixBin(valx, valy, valz)-1;
+    if (!fHistIsProbability)
+    {
+      if (ibin < 0)
+      {
+        fResult = kFALSE;
+        fCounter[1] += 1;
+        return kTRUE;
+      }
+    }
+
+    // check whether a selection should be made
+    fResult = fHistIsProbability ? SelectProb(ibin) : Select(ibin);
+    if (!fResult)
+    {
+      fCounter[2] += 1;
+      return kTRUE;
+    }
+
+    fCounter[0] += 1;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Update online display if set.
+//
+Int_t MFEventSelector2::PostProcess()
+{
+    //---------------------------------
+
+    if (GetNumExecutions()>0)
+    {
+        *fLog << inf << endl;
+        *fLog << GetDescriptor() << " execution statistics:" << endl;
+        *fLog << dec << setfill(' ');
+
+        *fLog << " " << setw(7) << fCounter[1] << " (" << setw(3)
+              << (int)((Float_t)(fCounter[1]*100)/(Float_t)(GetNumExecutions())+0.5)
+              << "%) Events not selected due to under/over flow" << endl;
+
+        *fLog << " " << setw(7) << fCounter[2] << " (" << setw(3)
+              << (int)((Float_t)(fCounter[2]*100)/(Float_t)(GetNumExecutions())+0.5)
+              << "%) Events not selected due to requested distribution" 
+              << endl;
+
+        *fLog << " " << fCounter[0] << " ("
+              << (int)((Float_t)(fCounter[0]*100)/(Float_t)(GetNumExecutions())+0.5)
+              << "%) Events selected" << endl;
+        *fLog << endl;
+    }
+
+    //---------------------------------
+
+    if (fDisplay && fDisplay->HasCanvas(fCanvas))
+    {
+        fCanvas->cd(4);
+        fHistRes->DrawClone("nonew");
+        fCanvas->Modified();
+        fCanvas->Update();
+    }
+
+    return kTRUE;
+}
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mfbase/MFEventSelector2.h
===================================================================
--- /tags/Mars-V0.9/mfbase/MFEventSelector2.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFEventSelector2.h	(revision 9772)
@@ -0,0 +1,75 @@
+#ifndef MARS_MFEventSelector2
+#define MARS_MFEventSelector2
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFEventSelector2                                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+#ifndef MARS_MDataChain
+#include "MDataChain.h"
+#endif
+
+class TH1;
+class TCanvas;
+
+class MH3;
+class MRead;
+
+class MFEventSelector2 : public MFilter
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    MH3       *fHistOrig; // original distribution of the events
+    MH3       *fHistNom;  // nominal distribution
+    MH3       *fHistRes;  // resulting distribution
+    MDataChain fDataX;    // data rule for the x-axis
+    MDataChain fDataY;    // data rule for the y-axis
+    MDataChain fDataZ;    // data rule for the z-axis
+    Long_t     fNumMax;   // Maximum number of selected events
+    TArrayL    fIs;       //! array storing the original distribution
+    TArrayL    fNom;      //! array storing the nominal distribution
+    TCanvas   *fCanvas;   //! canvas for online display
+
+    TString    fFilterName; // name of the MFilter object to be used when determining the original distribution
+
+    Bool_t fResult;
+    Bool_t fHistIsProbability;
+    Bool_t fUseOrigDist;    // flag indicating that in the selection the original distribution is not changed
+
+    Int_t  fCounter[3];
+
+    TH1   &InitHistogram(MH3* &hist);
+    Bool_t ReadDistribution(MRead &read, MFilter *filter);
+    void   PrepareHistograms();
+    Bool_t PreProcessData(MParList *parlist);
+    Bool_t Select(Int_t bin);
+    Bool_t SelectProb(Int_t bin) const;
+
+    Int_t PreProcess(MParList *parlist);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MFEventSelector2(MH3 &hist, const char *name=NULL, const char *title=NULL);
+    ~MFEventSelector2();
+
+    MH3 *GetHistOrig() { return fHistOrig; }
+
+    void SetNumMax(Long_t max=-1) { fNumMax = max; }
+    void SetHistIsProbability(Bool_t b=kTRUE) { fHistIsProbability=b; }
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    ClassDef(MFEventSelector2, 0) // FIXME!
+};
+
+#endif
Index: /tags/Mars-V0.9/mfbase/MFRealTimePeriod.cc
===================================================================
--- /tags/Mars-V0.9/mfbase/MFRealTimePeriod.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFRealTimePeriod.cc	(revision 9772)
@@ -0,0 +1,59 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFRealTimePeriod
+//
+//  This filter allows the execution of tasks in real time intervals. If
+//  a timeout (given in milliseconds in the constructor) was exceeded
+//  the return value for IsExpression is set to kTRUE and the timer is
+//  reset.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFRealTimePeriod.h"
+
+#include <TTime.h>
+#include <TSystem.h>
+
+ClassImp(MFRealTimePeriod);
+
+// --------------------------------------------------------------------------
+//
+// Check, whether the current time is greater than the stored time plus
+// the timeout time. If this is the case the return value of
+// IsExpressionTrue is set to kTRUE and the stored time is reset to the
+// current time. To get the current time gSystem->Now() is used.
+//
+Int_t MFRealTimePeriod::Process()
+{
+    const ULong_t t = (ULong_t)gSystem->Now();
+
+    fResult = t>fTime+fMilliSec;
+
+    if (fResult)
+        fTime=t;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mfbase/MFRealTimePeriod.h
===================================================================
--- /tags/Mars-V0.9/mfbase/MFRealTimePeriod.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFRealTimePeriod.h	(revision 9772)
@@ -0,0 +1,31 @@
+#ifndef MARS_MFRealTimePeriod
+#define MARS_MFRealTimePeriod
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MFRealTimePeriod : public MFilter
+{
+private:
+    ULong_t fTime;     //!
+    Bool_t  fResult;   //!
+
+    ULong_t fMilliSec;
+
+public:
+    MFRealTimePeriod(UInt_t millis=1000) : fTime(0), fMilliSec(millis)
+    {
+        fName  = "MFRealTimePeriod";
+        fTitle = "Filter allowing execution of a task only after a given real time interval";
+    }
+
+    void SetTime(UInt_t millis) { fMilliSec = millis; }
+
+    Int_t Process();
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    ClassDef(MFRealTimePeriod, 0) //Filter allowing execution of a task only after a given real time interval
+};
+
+#endif
Index: /tags/Mars-V0.9/mfbase/MFilterList.cc
===================================================================
--- /tags/Mars-V0.9/mfbase/MFilterList.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFilterList.cc	(revision 9772)
@@ -0,0 +1,474 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFilterList
+//
+// A filter list can be used to concatenate filter (derived from MFilter)
+// by a logical or bitwise operator. For more details see the constructor.
+//
+// The list is setup by adding filters to the list calling AddToList().
+// For example in the case of the default constructor ("&&") all results
+// are logically and'd together and the result of this and is returned.
+//
+// Because the meaning of all filters can be inverted calling SetInverted()
+// which is defined in the base class MFilter you can use this list to
+// invert the meaning of a filter, by eg:
+//
+//    MF anyfilter("MHillas.fAlpha");
+//
+//    MFilterList alist;
+//    alist.AddToList(&anyfilter);
+//
+//    alist.SetInverted();
+//
+//  or do
+//
+//    MFilterList alist(&anyfilter);
+//
+//
+// Adding the filterlist to the eventloop will process all contained filters.
+// Doing this as early as possible is a simple way of processing all filters.
+//
+// If you want to make the list delete all contained filters you may make
+// the list owner of the filters by calling SetOwner()
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFilterList.h"
+
+#include <fstream>
+
+#include <TString.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIter.h"
+
+ClassImp(MFilterList);
+
+using namespace std;
+
+static const TString gsDefName  = "MFilterList";
+static const TString gsDefTitle = "List combining filters logically.";
+
+// --------------------------------------------------------------------------
+//
+// Wrapper to simplify constructors.
+//
+void MFilterList::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    gROOT->GetListOfCleanups()->Add(&fFilters);
+    fFilters.SetBit(kMustCleanup);
+
+    fFilterType = kEAnd;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Default Constructor.
+//
+//   Specify the boolean operation which is used to evaluate the
+//   result of this list. If no operation is specified "land" is
+//   used.
+//
+//   Options:
+//      and,  &  : is a bitwise and
+//      or,   |  : is a bitwise or
+//      xor,  ^  : is a bitwise exclusive or
+//      land, && : is a logical and
+//      lor,  || : is a logical or
+//
+//   The bitwise operators are implemented for convinience. They may not
+//   make much sense. Maybe IsExpressionTrue should change its return
+//   type from Bool_t to Int_t.
+//
+MFilterList::MFilterList(const char *type, const char *name, const char *title)
+{
+    Init(name, title);
+
+    TString str(type);
+
+    if (!str.CompareTo("OR", TString::kIgnoreCase)  || !str.CompareTo("|"))
+        fFilterType = kEOr;
+    if (!str.CompareTo("XOR", TString::kIgnoreCase) || !str.CompareTo("^"))
+        fFilterType = kEXor;
+    if (!str.CompareTo("LAND", TString::kIgnoreCase) || !str.CompareTo("&&"))
+        fFilterType = kELAnd;
+    if (!str.CompareTo("LOR", TString::kIgnoreCase) || !str.CompareTo("||"))
+        fFilterType = kELOr;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Constructor.
+//
+// Setup an '&&' filter list, adds the filter to the list and
+// call MFilterList::SetInverted()
+//
+// To be used as a logical NOT.
+//
+MFilterList::MFilterList(MFilter *f, const char *name, const char *title)
+{
+    Init(name, title);
+
+    SetInverted();
+    AddToList(f);
+}
+
+// --------------------------------------------------------------------------
+//
+//   CopyConstructor
+//
+MFilterList::MFilterList(MFilterList &ts)
+{
+    fFilters.AddAll(&ts.fFilters);
+    fFilterType = ts.fFilterType;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Evaluates and returns the result of the filter list.
+//  The expression is evaluated step by step, eg:
+//  ((filter[0] # filter[1]) # filter[3]) # filter[4])
+//  The '#' stands for the boolean operation which is specified in
+//  the constructor.
+//
+Bool_t MFilterList::IsExpressionTrue() const
+{
+    TIter Next(&fFilters);
+
+    MFilter *filter=(MFilter*)Next();
+
+    if (!filter)
+        return kTRUE;
+
+    Bool_t rc = filter->IsConditionTrue();
+
+    //
+    // loop over all filters
+    //
+    switch (fFilterType)
+    {
+    case kEAnd:
+        while ((filter=(MFilter*)Next()))
+            rc &= filter->IsConditionTrue();
+        break;
+
+    case kEOr:
+        while ((filter=(MFilter*)Next()))
+            rc |= filter->IsConditionTrue();
+        break;
+
+    case kEXor:
+        while ((filter=(MFilter*)Next()))
+            rc ^= filter->IsConditionTrue();
+        break;
+
+    case kELAnd:
+        while ((filter=(MFilter*)Next()))
+            rc = (rc && filter->IsConditionTrue());
+        break;
+
+    case kELOr:
+        while ((filter=(MFilter*)Next()))
+            rc = (rc || filter->IsConditionTrue());
+        break;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to add a new filter to the list call this function with the
+// pointer to the filter to be added. 
+//
+Bool_t MFilterList::AddToList(MFilter *filter)
+{
+    if (!filter)
+        return kTRUE;
+
+    const char *name = filter->GetName();
+
+    if (fFilters.FindObject(filter))
+    {
+        *fLog << warn << dbginf << "Filter already existing... skipped." << endl;
+        return kTRUE;
+    }
+
+    if (fFilters.FindObject(name))
+        *fLog << inf << "MFilterList::AddToList - '" << name << "' exists in List already..." << endl;
+
+    *fLog << inf << "Adding " << name << " to " << GetName() << "... " << flush;
+
+    filter->SetBit(kMustCleanup);
+    fFilters.Add(filter);
+
+    *fLog << "Done." << endl;
+
+    AddToBranchList(filter->GetDataMember());
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to add a new filters from a TCollection to the list call
+// this function.
+//
+Bool_t MFilterList::AddToList(const TCollection &col)
+{
+    TIter Next(&col);
+    MFilter *f=0;
+    Int_t idx=0;
+    while ((f=(MFilter*)Next()))
+    {
+        if (!f->InheritsFrom(MFilter::Class()))
+        {
+            *fLog << warn << "WARNING - An object in TCollection doesn't inherit from MFilter... ignored." << endl;
+            continue;
+        }
+
+        f->SetName(Form("F%d", idx++));
+        if (!AddToList(f))
+            return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcesses all filters in the list
+//
+Int_t MFilterList::PreProcess(MParList *pList)
+{
+    TIter Next(&fFilters);
+
+    MFilter *filter=NULL;
+
+    //
+    // loop over all filters
+    //
+    while ((filter=(MFilter*)Next()))
+        if (!filter->CallPreProcess(pList))
+        {
+            *fLog << err << "Error - Preprocessing Filter ";
+            *fLog << filter->GetName() << " in " << fName << endl;
+            return kFALSE;
+        }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Processes (updates) all filters in the list.
+//
+Int_t MFilterList::Process()
+{
+    TIter Next(&fFilters);
+
+    MFilter *filter=NULL;
+
+    //
+    // loop over all filters
+    //
+    while ((filter=(MFilter*)Next()))
+        if (!filter->CallProcess())
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PostProcesses all filters in the list.
+//
+Int_t MFilterList::PostProcess()
+{
+    TIter Next(&fFilters);
+
+    MFilter *filter=NULL;
+
+    //
+    // loop over all filters
+    //
+    while ((filter=(MFilter*)Next()))
+        if (!filter->CallPostProcess())
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to use a verbose output ("and") instead of a symbolic ("&")
+// one the option string must conatin a "v"
+//
+void MFilterList::Print(Option_t *opt) const
+{
+    *fLog << all << GetRule(opt) << flush;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MFilterList::StreamPrimitive(ofstream &out) const
+{
+    out << "   MFilterList " << ToLower(fName) << "(\"";
+
+    switch (fFilterType)
+    {
+    case kEAnd:
+        out << "&";
+        break;
+
+    case kEOr:
+        out  << "|";
+        break;
+
+    case kEXor:
+        out  << "^";
+        break;
+
+    case kELAnd:
+        out << "&&";
+        break;
+
+    case kELOr:
+        out << "||";
+        break;
+    }
+
+    out << "\"";
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl << endl;
+
+    MIter Next(&fFilters);
+
+    MParContainer *cont = NULL;
+    while ((cont=Next()))
+    {
+        cont->SavePrimitive(out, "");
+
+        out << "   " << ToLower(fName) << ".AddToList(&";
+        out << cont->GetUniqueName() << ");" << endl << endl;
+    }
+}
+
+TString MFilterList::GetRule(Option_t *opt) const
+{
+    TString str(opt);
+    const Bool_t verbose = str.Contains("V", TString::kIgnoreCase);
+
+    TString ret = "(";
+
+    TIter Next(&fFilters);
+
+    MFilter *filter=(MFilter*)Next();
+
+    //
+    // loop over all filters
+    //
+    if (!filter)
+        return "<empty>";
+
+    ret += filter->GetRule();
+
+    while ((filter=(MFilter*)Next()))
+    {
+        switch (fFilterType)
+        {
+        case kEAnd:
+            ret += (verbose?" and ":" & ");
+            break;
+
+        case kEOr:
+            ret += (verbose?" or ":" | ");
+            break;
+
+        case kEXor:
+            ret += (verbose?" xor ":" ^ ");
+            break;
+
+        case kELAnd:
+            ret += (verbose?" land ":" && ");
+            break;
+
+        case kELOr:
+            ret += (verbose?" lor ":" || ");
+            break;
+        }
+
+        ret += filter->GetRule();
+    }
+
+    return ret+")";
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data members existing in this array in a comma-seperated list
+// (This is mainly used for MTask::AddToBranchList)
+//
+TString MFilterList::GetDataMember() const
+{
+    TString str;
+
+    TIter Next(&fFilters);
+    MFilter *filter = NULL;
+    while ((filter=(MFilter*)Next()))
+    {
+        if (filter->GetDataMember().IsNull())
+            continue;
+
+        str += ",";
+        str += filter->GetDataMember();
+    }
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over all set filters and distribute arr to their SetVariables.
+// Make sure, that the values are unique (not two filters using the
+// same index in the array with different meanings)
+//
+void MFilterList::SetVariables(const TArrayD &arr)
+{
+    fFilters.ForEach(MFilter, SetVariables)(arr);
+}
Index: /tags/Mars-V0.9/mfbase/MFilterList.h
===================================================================
--- /tags/Mars-V0.9/mfbase/MFilterList.h	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/MFilterList.h	(revision 9772)
@@ -0,0 +1,66 @@
+#ifndef MARS_MFilterList
+#define MARS_MFilterList
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MFilterList                                                            //
+//                                                                         //
+//  List of several filters                                                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MParList;
+
+class MFilterList : public MFilter
+{
+private:
+    TOrdCollection fFilters;	// Container for the filters
+
+    typedef enum { kEAnd, kEOr, kEXor, kELAnd, kELOr } FilterType_t;
+    FilterType_t fFilterType;
+
+    enum { kIsOwner = BIT(14) };
+
+    void StreamPrimitive(ofstream &out) const;
+
+    void Init(const char *name, const char *title);
+
+public:
+    MFilterList(const char *type="&&", const char *name=NULL, const char *title=NULL);
+    MFilterList(MFilter *f, const char *name=NULL, const char *title=NULL);
+    MFilterList(MFilterList &ts);
+    ~MFilterList()
+    {
+        if (TestBit(kIsOwner))
+            fFilters.SetOwner();
+    }
+
+    Bool_t AddToList(MFilter *filter);
+    Bool_t AddToList(const TCollection &col);
+    void SetOwner(Bool_t enable=kTRUE) { enable ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+
+    Bool_t IsExpressionTrue() const;
+
+    void Print(Option_t *opt = "") const;
+
+    TString GetRule() const { return GetRule(""); }
+    TString GetRule(Option_t *opt) const;
+    TString GetDataMember() const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    void SetVariables(const TArrayD &arr);
+
+    ClassDef(MFilterList, 1)		// List to combine several filters logically
+};
+
+#endif
Index: /tags/Mars-V0.9/mfbase/Makefile
===================================================================
--- /tags/Mars-V0.9/mfbase/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mfbase/Makefile	(revision 9772)
@@ -0,0 +1,31 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mdata -I../mfileio -I../mhbase
+
+CINT     = FBase
+
+SRCFILES = MF.cc \
+           MFilterList.cc \
+           MFEventSelector.cc \
+           MFEventSelector2.cc \
+	   MFDataChain.cc \
+	   MFDataMember.cc \
+           MFRealTimePeriod.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mfileio/FileIOIncl.h
===================================================================
--- /tags/Mars-V0.9/mfileio/FileIOIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/FileIOIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mfileio/FileIOLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mfileio/FileIOLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/FileIOLinkDef.h	(revision 9772)
@@ -0,0 +1,20 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MChain+;
+#pragma link C++ class MRead+;
+#pragma link C++ class MReadTree+;
+#pragma link C++ class MReadReports+;
+#pragma link C++ class MReadMarsFile+;
+#pragma link C++ class MReadRflFile+;
+
+#pragma link C++ class MRootFileBranch+;
+
+#pragma link C++ class MWriteFile+;
+#pragma link C++ class MWriteAsciiFile+;
+#pragma link C++ class MWriteRootFile+;
+
+#endif
Index: /tags/Mars-V0.9/mfileio/MChain.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MChain.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MChain.cc	(revision 9772)
@@ -0,0 +1,71 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MChain
+//
+// Helper class for MReadTree
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MChain.h"
+
+ClassImp(MChain);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// This is the code from TChain::LoadTree but skips the
+// notification in LoadTree. If LoadTree raises the notification
+// a flag is set and the notification is done by hand. This
+// is done to be able to catch the return value from Notify. If
+// it has not been successfull -15 is returned.
+// This is to support return values from Notify()/Reinit().
+// The status can be checked afterward by HasError/HasFatalError/GetError
+//
+Long64_t MChain::LoadTree(Long64_t entry)
+{
+    TObject *notify = GetNotify();
+
+    SetNotify(this);
+
+    Long64_t rc = TChain::LoadTree(entry);
+
+    // <0: LoadTree failed
+    // =0: LoadTree was ok
+    // >0: Notify failed
+    fLastError = rc;
+
+    if (rc>=0 && fNotified && notify)
+    {
+        fLastError = notify->Notify() ? 0 : kFatalError;
+        if (fLastError==kFatalError)
+            rc = -15;
+    }
+
+    SetNotify(notify);
+
+    return rc;
+}
Index: /tags/Mars-V0.9/mfileio/MChain.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MChain.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MChain.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MChain
+#define MARS_MChain
+
+#ifndef ROOT_TChain
+#include <TChain.h>
+#endif
+
+class MChain : public TChain
+{
+public:
+    // Taken from TChain::LoadTree --- may have to be updated for different root versions
+    enum {
+        kCannotAccessTree = -4,  // Tree not found in file
+        kCannotAccessFile = -3,  // File access impossible
+        kOutOfRange       = -2,  // Event doesn't exist
+        kNoError          =  0,  // LoadTree succeeded
+        kFatalError       =  1   // LoadTree succeeded, but Notify() returned fatal error
+    };
+
+private:
+    Bool_t   fNotified;
+    Long64_t fLastError; // <0: LoadTree failed, =0: LoadTree was ok, >0: Notify failed
+
+public:
+    MChain() : TChain(), fNotified(kFALSE), fLastError(0) {}
+    MChain(const char *name, const char *title="") : TChain(name, title), fNotified(kFALSE), fLastError(0) {}
+
+    // Restart from scratch
+    void ResetTree() { fTree = 0; fTreeNumber = -1; }
+
+    // Function to be notified and setting the notifier
+    virtual Bool_t Notify() { fNotified = kTRUE; return kTRUE; }
+    virtual void   SetNotify(TObject *obj) { fNotify = obj; fNotified = kFALSE; }
+
+    // Overwrite LoadTree (for different root versions)
+    Int_t    LoadTree(Int_t entry) { return (Int_t)LoadTree((Long64_t)entry); }
+    Long64_t LoadTree(Long64_t entry);
+
+    // Handling for last error of LoadTree
+    Long64_t GetLastError() const { return fLastError; };
+    Bool_t   HasFatalError() const { return fLastError==kFatalError; }
+    Bool_t   HasError() const { return fLastError==0 ? kFALSE : kTRUE; }
+
+    ClassDef(MChain, 1) // Class derived from TChain to give access to Notify-return value
+};
+
+#endif
Index: /tags/Mars-V0.9/mfileio/MRead.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MRead.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MRead.cc	(revision 9772)
@@ -0,0 +1,149 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRead
+//
+// Base class for all reading tasks
+//
+// You can set a selector. Depending on the impelementation in the derived
+// class it can be used to skip events, if the filter return kFALSE.
+// Make sure that the selector (filter) doesn't need information which
+// doesn't exist before reading an event!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRead.h"
+
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+
+ClassImp(MRead);
+
+using namespace std;
+
+Bool_t MRead::Rewind()
+{
+    *fLog << err << "ERROR - Rewind() not implemented for " << GetDescriptor() << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the name of the file we are actually reading from.
+//
+TString MRead::GetFileName() const
+{
+    TString name(GetFullFileName());
+    if (name.IsNull())
+        return "<n/a>";
+    name.Remove(0, name.Last('/')+1);
+    return name;
+}
+
+Int_t MRead::AddFiles(MDirIter &files)
+{
+    files.Reset();
+
+    Int_t rc = 0;
+
+    TString str;
+    while (!(str=files.Next()).IsNull())
+    {
+        const Int_t num = AddFile(str);
+        if (num<0)
+            *fLog << warn << "Warning: AddFile(\"" << str << "\") returned " << num << "... skipped." << endl;
+        else
+            rc += num;
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv:
+//   File0, File1, File2, ..., File10, ..., File100, ...
+//
+// Searching stops if the first key isn't found in the TEnv
+//
+// Enclosing quotation marks (") are removed
+//
+// Number of entries at the moment not supported
+//
+Int_t MRead::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    //
+    // Search (beginning with 0) all keys
+    //
+    int i=0;
+    while (1)
+    {
+        TString idx = "File";
+        idx += i;
+
+        // Output if print set to kTRUE
+        if (!IsEnvDefined(env, prefix, idx, print))
+            break;
+
+        // Try to get the file name
+        TString name = GetEnvValue(env, prefix, idx, "");
+        if (name.IsNull())
+        {
+            *fLog << warn << prefix+"."+idx << " empty." << endl;
+            continue;
+        }
+
+        if (name.BeginsWith("\"") && name.EndsWith("\""))
+        {
+            name.Remove(name.Last('\"'), 1);
+            name.Remove(name.First('\"'), 1);
+        }
+
+        *fLog << inf << "Add File: " << name << endl;
+
+        AddFile(name);
+        i++;
+    }
+
+    return i!=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the file exists and has read permission. Derived classes
+// should also check whether its file type is correct.
+//
+// Returning 0 means: file doesn't exist.
+// A returned number corresponds to different file types (1 if only
+// one exists)
+//
+Byte_t MRead::IsFileValid(const char *name)
+{
+    return !gSystem->AccessPathName(name, kFileExists) ? 1 : 0;
+}
Index: /tags/Mars-V0.9/mfileio/MRead.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MRead.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MRead.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MRead
+#define MARS_MRead
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MFilter;
+class MDirIter;
+
+class MRead : public MTask
+{
+private:
+    MFilter *fSelector;
+
+public:
+    MRead() : fSelector(NULL) {}
+
+    virtual UInt_t  GetEntries() = 0;
+    virtual TString GetFileName() const;
+    virtual TString GetFullFileName() const = 0;
+    virtual Bool_t  Rewind();
+
+    static Byte_t IsFileValid(const char *name);
+
+    void SetSelector(MFilter *f) { fSelector = f; }
+    MFilter *GetSelector() { return fSelector; }
+
+    virtual Int_t AddFile(const char *fname, Int_t entries=-1) { return -1; }
+    Int_t AddFiles(MDirIter &dir);
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    ClassDef(MRead, 0)	// Base class for a reading task
+};
+
+#endif
Index: /tags/Mars-V0.9/mfileio/MReadMarsFile.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MReadMarsFile.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MReadMarsFile.cc	(revision 9772)
@@ -0,0 +1,251 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadMarsFile
+//
+// This task works more or less like MReadTree, but in addition PreProcess
+// reads all the information from the 'RunHeader' tree.
+//
+// Warning: Until now this works only for 'one run header per file'
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadMarsFile.h"
+
+#include <fstream>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MRawRunHeader.h"
+
+#include "MMcRunHeader.hxx"
+
+ClassImp(MReadMarsFile);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. Don't use it.
+//
+MReadMarsFile::MReadMarsFile() : fRun(NULL)
+{
+    fName  = "MRead";
+    fTitle = "Read tree and run headers from Mars file.";
+}
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. It creates a MReadTree object to read the
+//  RunHeaders and disables Auto Scheme for this tree.
+//
+MReadMarsFile::MReadMarsFile(const char *tname, const char *fname,
+                             const char *name, const char *title)
+    : MReadTree(tname, fname)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Read tree and run headers from Mars file.";
+
+    //
+    // open the input stream
+    //
+    fRun = new MReadTree("RunHeaders", fname, "RunHeaders");
+
+    //
+    // This disables the auto scheme. because reading new runheader is done
+    // at a low frequency we don't loose time if we always read all
+    // runheaders
+    //
+    fRun->DisableAutoScheme();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deleted the MReadTree object for the RunHeaders
+//
+MReadMarsFile::~MReadMarsFile()
+{
+    delete fRun;
+}
+
+Byte_t MReadMarsFile::IsFileValid(const char *name)
+{
+    ifstream fin(name);
+    if (!fin)
+        return 0;
+
+    Char_t c[4];
+    fin.read(c, 4);
+    if (!fin)
+        return 0;
+
+    if (!(c[0]=='r'&& c[1]=='o' && c[2]=='o' && c[3]=='t'))
+        return 0;
+
+    TFile f(name, "READ");
+
+    TTree *t = (TTree*)f.Get("Events");
+    if (!t)
+        return 0;
+
+    // FIXME: Replace numbers by enum! Maybe use bits?
+    if (t->FindBranch("MRawEvtData."))
+        return t->FindBranch("MMcEvt.") ? 2 : 1;
+
+    if (t->FindBranch("MCerPhotEvt."))
+        return t->FindBranch("MMcEvt.") ? 4 : 3;
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  see MReadTree::AddFile, too. The file is also added to the chain for
+//  the run headers. If adding file gives a different result for both
+//  chains -1 is returned, otherwise the number of files which were added.
+//
+Int_t MReadMarsFile::AddFile(const char *fname, Int_t entries)
+{
+    //
+    // FIXME! A check is missing whether the file already exists or not.
+    //
+    //
+    // returns the number of file which were added
+    //
+    Int_t n1 = fRun->AddFile(fname);
+    Int_t n2 = MReadTree::AddFile(fname, entries);
+
+    return n1 != n2 ? -1 : n1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Sort the files by their file-names
+//
+void MReadMarsFile::SortFiles()
+{
+    fRun->SortFiles();
+    MReadTree::SortFiles();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This overload MReadTree::Notify. Before the MReadTree Notify
+//  TObjects are called the RunHeaders of the next files are read.
+//  
+//  WARNING: This doesn't work correctly yet, if the files are not read in
+//           increasing order.
+//
+Bool_t MReadMarsFile::Notify()
+{
+    UInt_t runtype = 0xffff;
+
+    const MRawRunHeader *rawheader = (MRawRunHeader*)fParList->FindObject("MRawRunHeader");
+    if (rawheader)
+        runtype = rawheader->GetRunType();
+
+    //
+    // Try to read the new run headers. If reading the new run header
+    // was successfull call the ReInits
+    //
+    const Int_t idx = GetFileIndex();
+    fRun->SetEventNum(idx<0?0:idx); // Assumption: One Entry per File!
+    if (!fRun->Process())
+    {
+        *fLog << err << "ERROR - Cannot read new runheaders #" << idx;
+        *fLog << " after reading event #" << GetNumEntry() << endl;
+        return kFALSE;
+    }
+
+    if (!MReadTree::Notify())
+        return kFALSE;
+
+    if (rawheader && runtype!=0xffff && runtype != rawheader->GetRunType())
+    {
+        *fLog << warn << "Warning - You are mixing files with different run types (";
+        *fLog << runtype << ", " << rawheader->GetRunType() << ")" << endl;
+    }
+
+    const MMcRunHeader *mcheader = (MMcRunHeader*)fParList->FindObject("MMcRunHeader");
+    if (mcheader)
+    {
+        if (mcheader->GetCamVersion()==50)
+        {
+            *fLog << warn << "Warning - You are using a file created with Camera 0.5." << endl;
+            *fLog << "In this camera version some events have undefined Impact-Values" << endl;
+            *fLog << "(MMcEvt::fImpact) Please don't use it for MC studies using the" << endl;
+            *fLog << "impact parameter." << endl;
+        }
+    }
+
+    MTaskList *tlist = (MTaskList*)fParList->FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << err << dbginf << "ERROR - MTaskList not found in Parameter List." << endl;
+        return kFALSE;
+    }
+
+    if (tlist->ReInit())
+        return kTRUE;
+
+    //MReadTree::Notify();
+
+    *fLog << err << "ERROR - ReInit of '" << tlist->GetDescriptor() << "' failed." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  PreProcessed the MReadTree to read the run headers and its base class.
+//  see MReadTree::PreProcess for more information
+//
+Int_t MReadMarsFile::PreProcess(MParList *pList)
+{
+    fParList = pList;
+
+    if (!fRun->PreProcess(pList))
+    {
+        *fLog << err << "Error - PreProcessing MReadMarsFile::fRun... aborting." << endl;
+        return kFALSE;
+    }
+
+    /*
+    const Int_t idx = GetFileIndex();
+    fRun->SetEventNum(idx<0?0:idx); // Assumption: One Entry per File!
+    if (!fRun->Process())
+    {
+        *fLog << err << "Error - Processing MReadMarsFile::fRun... aborting." << endl;
+        return kFALSE;
+    }
+    */
+    return MReadTree::PreProcess(pList);
+}
Index: /tags/Mars-V0.9/mfileio/MReadMarsFile.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MReadMarsFile.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MReadMarsFile.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MReadMarsFile
+#define MARS_MReadMarsFile
+
+#ifndef MARS_MReadTree
+#include "MReadTree.h"
+#endif
+
+class MParList;
+class MTaskList;
+
+class MReadMarsFile : public MReadTree
+{
+private:
+    MReadTree *fRun;
+    MParList  *fParList;  //! Parlist for reinitialization
+
+    Bool_t Notify();
+
+    Int_t PreProcess(MParList *pList);
+  
+public:
+    MReadMarsFile();
+    MReadMarsFile(const char *treename, const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+    ~MReadMarsFile();
+
+    static Byte_t IsFileValid(const char *name);
+
+    void SortFiles();
+
+    Int_t AddFile(const char *fname, Int_t entries=-1);
+
+    Bool_t Rewind() { if (fRun) fRun->Rewind(); MReadTree::Rewind(); return kTRUE; }
+
+    ClassDef(MReadMarsFile, 1)	// Reads a tree from file(s) and the information from the 'RunHeader'-tree
+};
+
+#endif
Index: /tags/Mars-V0.9/mfileio/MReadReports.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MReadReports.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MReadReports.cc	(revision 9772)
@@ -0,0 +1,428 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadReports
+//
+// Read from a file events from different trees ordered in time, eg:
+//
+// Having a file with:
+//
+//      Tree1         Tree2         Tree3
+//      ------------  ------------  -----------
+//      (0) MTime[0]
+//                    (0) MTime[1]
+//      (1) MTime[2]
+//      (2) MTime[3]
+//                                  (0) MTime[1]
+//      (3) MTime[4]
+//
+// MReadReports will read the events in the tree in the following order:
+//   <0> (0) from Tree1
+//   <1> (0) from Tree2
+//   <2> (1) from Tree1
+//   <3> (2) from Tree1
+//   <4> (0) from Tree3
+//   <5> (3) from Tree1
+//   ...
+//
+// To tell MReadReports which Trees to read use: MReadReports::AddTree()
+// To schedule a file for reading use MReadReports::AddFile()
+//
+// All calls to AddTree _must_ be before the calls to AddFile!
+//
+// After reading from a tree with the name 'TreeName' the stream id of
+// the main tasklist ('MTaskList' found in MParList in PreProcess) is
+// set to this name. This means that only tasks having this stream id
+// are executed.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadReports.h"
+
+#include <TChain.h>
+#include <TChainElement.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MReadMarsFile.h"
+
+ClassImp(MReadReports);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Set fName and fTitle. Instatiate fTrees and fChains.
+// Call SetOwner for fTrees and fChains
+//
+MReadReports::MReadReports() : fEnableAutoScheme(kFALSE)
+{
+    fName  = "MRead";
+    fTitle = "Reads events and reports from a root file ordered in time";
+
+    fTrees  = new MTaskList("MReadReports");
+    fChains = new TList;
+
+    fTrees->SetOwner();
+    fChains->SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor, delete everything which was allocated by this task...
+//
+MReadReports::~MReadReports()
+{
+    TObject *o=0;
+    TIter NextC(fChains);
+    while ((o=NextC()))
+    {
+        delete *GetTime((TChain*)o);
+        delete  GetTime((TChain*)o);
+    }
+
+    delete fTrees;
+    delete fChains;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of entries in all trees.
+//
+UInt_t MReadReports::GetEntries()
+{
+    UInt_t n=0;
+
+    TIter NextT(fTrees->GetList());
+    MReadTree *tree=0;
+    while ((tree=(MReadTree*)NextT()))
+        n += tree->GetEntries();
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// In case of a Master Tree GetFileName() of the MReadMarsFile is returned.
+// If no master is available "<MReadReports>" is returned.
+//
+TString MReadReports::GetFullFileName() const
+{
+    if (!TestBit(kHasMaster))
+        return "<MReadReports>";
+
+    TIter NextT(fTrees->GetList());
+    MReadTree *tree=0;
+    while ((tree=(MReadTree*)NextT()))
+        if (tree->InheritsFrom("MReadMarsFile"))
+            return tree->GetFileName();
+
+    return "<n/a>";
+
+}
+
+void MReadReports::AddToBranchList(const char *name)
+{
+    MTask::AddToBranchList(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Schedule the contents of this tree for reading. As a default the time
+// branch which is used for the ordering is assumed to by "MTime"+tree.
+// If this is not the case you can overwrite the default specifying the
+// name in time.
+//
+// All calls to AddTree _must_ be BEFORE the calls to AddFile!
+//
+// To be done: A flag(?) telling whether the headers can be skipped.
+//
+void MReadReports::AddTree(const char *tree, const char *time, Bool_t master)
+{
+    /*
+    if (fTrees->GetNumTasks()>0)
+    {
+        *fLog << warn << "WARNING - AddTree must be called before AddFile... ignored." << endl;
+        *fLog << dbg << fTrees->GetNumTasks() << endl;
+        return kFALSE;
+    }
+    */
+
+    if (master && TestBit(kHasMaster))
+    {
+        *fLog << warn << GetDescriptor() << " already has a master tree... ignored." << endl;
+        master = kFALSE;
+    }
+
+    MReadTree *t = master ? new MReadMarsFile(tree) : new MReadTree(tree);
+    t->SetName(tree);
+    t->SetTitle(time?time:"");
+    if (master)
+        SetBit(kHasMaster);
+
+    if (!fEnableAutoScheme)
+        t->DisableAutoScheme();
+
+    //FIXME!
+    //t->DisableAutoScheme();
+
+    fTrees->AddToList(t);
+    //    return kTRUE;
+}
+
+MReadTree *MReadReports::GetReader(const char *tree) const
+{
+    return (MReadTree*)fTrees->FindObject(tree);
+}
+
+// --------------------------------------------------------------------------
+//
+// Schedule a file or several files (using widcards) for reading.
+//
+// All calls to AddTree _must_ be BEFORE the calls to AddFile!
+//
+Int_t MReadReports::AddFile(const char *fname, Int_t entries)
+{
+    Int_t n=0;
+
+    TIter NextT(fTrees->GetList());
+    MReadTree *tree=0;
+    while ((tree=(MReadTree*)NextT()))
+        n += tree->AddFile(fname, entries);
+
+    return n;
+}
+
+// --------------------------------------------------------------------------
+//
+// Find MTaskList and store a pointer to it in fList.
+// Delete all entries in fChains.
+// Create all chains to read the time in the trees in advance.
+// Enable only the time-branch in this chains.
+// PreProcess fTrees (a MTaskList storing MReadTree tasks for reading)
+//
+Int_t MReadReports::PreProcess(MParList *plist)
+{
+    fChains->Delete();
+
+    Int_t i=0;
+
+    TIter NextT(fTrees->GetList());
+    MReadTree *tree=0;
+    while ((tree=(MReadTree*)NextT()))
+    {
+        if (!((TChain*)tree->fChain)->GetFile())
+        {
+            *fLog << warn << "No files or no tree '" << tree->GetName() << "'... skipped." << endl;
+            fTrees->RemoveFromList(tree);
+            continue;
+        }
+
+        if (tree->GetEntries()==0)
+        {
+            *fLog << warn << "No events in tree '" << tree->GetName() << "'... skipped." << endl;
+            fTrees->RemoveFromList(tree);
+            continue;
+        }
+
+        TString tn(tree->GetTitle());
+        if (tn.IsNull())
+        {
+            tn += "MTime";
+            tn += tree->GetName();
+            tn += ".";
+        }
+
+        TString tn2(tn);
+        tn2 += "*";
+
+        // FIXME: Should be tree->AddToBranchList such that
+        //        each run a new 'table' is created, but
+        //        MRead is searching for MTaskList in the
+        //        parameter list.
+        //AddToBranchList((const char*)tn2);
+
+        //
+        // SetBranchStatus wants to have a pointer to a pointer
+        //
+        MTime **tx = new MTime*;
+        *tx = new MTime;
+
+        TChain *c=new TChain(tree->GetName());
+        c->SetBranchStatus("*", 0);
+        c->SetBranchAddress(tn, tx);
+        tn+="*";
+        c->SetBranchStatus(tn, 1);
+        c->Add((TChain*)tree->fChain);
+        c->GetEntry(0);
+
+        fChains->Add(c);
+
+        i++;
+    }
+
+    if (i==0)
+    {
+        *fLog << err << "Files do not contain any valid tree... abort." << endl;
+        return kFALSE;
+    }
+
+    fPosEntry.Set(i);
+
+    return fTrees->CallPreProcess(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the MTime corresponding to this TChain...
+//
+MTime** MReadReports::GetTime(TChain *c) const
+{
+    TChainElement *e=(TChainElement*)c->GetStatus()->At(1);
+    return (MTime**)e->GetBaddress();
+}
+
+// --------------------------------------------------------------------------
+//
+// Do not use if fChains->GetSize()==0 !!!
+//
+Int_t MReadReports::FindNextTime()
+{
+    Int_t i=0;
+
+    TIter NextC(fChains);
+    TChain *c=0;
+
+    Int_t nmin=0;
+    MTime tmin(**GetTime((TChain*)NextC()));
+
+    while ((c=(TChain*)NextC()))
+    {
+        MTime &t = **GetTime(c);
+        i++;
+
+        if (t >= tmin)
+            continue;
+
+        tmin = t;
+        nmin = i;
+    }
+    return nmin;
+}
+
+/*
+Bool_t MReadReports::Notify()
+{
+    Bool_t same = kTRUE;
+    for (int i=1; i<fPosTree.GetSize(); i++)
+        if (fPosTree[i]!=fPosTree[0])
+        {
+            same = kFALSE;
+            break;
+        }
+
+    Int_t tn = chain->GetTreeNumber();
+
+    Bool_t read=kFALSE;
+    if (fPosTree[nmin] != tn)
+    {
+        fPosTree[nmin] = tn;
+        read = kTRUE;
+    }
+
+    if (!same || !read)
+        return kTRUE;
+
+
+    *fLog << dbg << "Read Run Headers!" << endl;
+
+    return kTRUE;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Check which is the next tree to read from. Read an event from this tree.
+// Sets the StreamId accordingly.
+//
+Int_t MReadReports::Process()
+{
+    while (fChains->GetSize())
+    {
+        const Int_t nmin=FindNextTime();
+
+        TChain *chain = (TChain*)fChains->At(nmin);
+
+        MTask *task = (MTask*)fTrees->GetList()->At(nmin);
+
+        //Int_t before = chain->GetTreeNumber();
+        if (chain->GetEntry(++fPosEntry[nmin])>0)
+        {
+            const Int_t rc = task->CallProcess();
+            if (rc)
+                return rc;
+        }
+
+        *fLog << dbg << "Removing chain " << chain->GetName() << " from list." << endl;
+
+        delete *GetTime(chain);        // Delete MTime*
+        delete  GetTime(chain);        // Delete MTime-instance
+        delete fChains->Remove(chain); // Remove chain from TList
+
+        // FIXME: Maybe MTaskList should have a member function to
+        //        reorder the tasks?
+
+        // Move this task to the end of the list so that nmin still
+        // corresponds to the correct task in the list.
+        const_cast<TList*>(fTrees->GetList())->Remove(task);
+        const_cast<TList*>(fTrees->GetList())->AddLast(task);
+    }
+
+    return kFALSE; 
+}
+
+// --------------------------------------------------------------------------
+//
+// PostProcess all MReadTree tasks in fTrees.
+//
+Int_t MReadReports::PostProcess()
+{
+    return fTrees->CallPostProcess();
+}
+
+// --------------------------------------------------------------------------
+//
+// PrintStatistics of this task and of the MReadTree tasks in fTress
+//
+void MReadReports::PrintStatistics(const Int_t lvl, Bool_t title, Double_t time) const
+{
+    MRead::PrintStatistics(lvl, title, time);
+    fTrees->PrintStatistics(lvl+1, title, GetCpuTime());
+}
Index: /tags/Mars-V0.9/mfileio/MReadReports.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MReadReports.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MReadReports.h	(revision 9772)
@@ -0,0 +1,63 @@
+#ifndef MARS_MReadReports
+#define MARS_MReadReports
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class TChain;
+class MTime;
+class MTaskList;
+class MReadTree;
+
+class MReadReports : public MRead
+{
+private:
+    MTaskList *fTrees;    // Hold the trees which are scheduled for reading
+    TList     *fChains;   // Hold TChains to read the times in advance
+
+    TArrayL    fPosEntry; // Store the position in each tree/chain
+    TArrayL    fPosTree;  // Number of Tree in file.
+
+    Bool_t     fEnableAutoScheme;
+
+    MTime** GetTime(TChain *c) const;
+    Int_t   FindNextTime();
+
+    UInt_t  GetEntries();
+    TString GetFullFileName() const;
+
+    Int_t   PreProcess(MParList *plist);
+    Int_t   Process();
+    Int_t   PostProcess();
+
+    enum {
+        kHasMaster = BIT(14)
+    };
+
+public:
+    MReadReports(); 
+    ~MReadReports(); 
+
+    void  AddTree(const char *tree, const char *time=NULL, Bool_t master=kFALSE);
+    void  AddTree(const char *tree, Bool_t master)
+    {
+        AddTree(tree, NULL, master);
+    }
+    Int_t AddFile(const char *fname, Int_t entries=-1);
+    void  AddToBranchList(const char *name);
+
+    void  PrintStatistics(const Int_t lvl=0, Bool_t title=kFALSE, Double_t time=0) const;
+
+    void  EnableAutoScheme(Bool_t e=kTRUE) { fEnableAutoScheme = e; } // Must be called BEFORE AddTree!
+
+    MReadTree *GetReader(const char *tree) const;
+
+    ClassDef(MReadReports, 0) // Reads events and reports from a root file ordered in time
+};
+
+#endif
Index: /tags/Mars-V0.9/mfileio/MReadRflFile.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MReadRflFile.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MReadRflFile.cc	(revision 9772)
@@ -0,0 +1,449 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadRflFile
+//
+// Reads a output file of the reflector program
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadRflFile.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TSystem.h>
+
+#include "structures_rfl.h"
+
+#include "MParList.h"
+#include "MRflEvtData.h"
+#include "MRflEvtHeader.h"
+#include "MRflRunHeader.h"
+#include "MRflSinglePhoton.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MReadRflFile);
+
+using namespace std;
+
+// ------------------------------------------------
+const char PROGNAME[] = "reflector";
+#define SIZE_OF_FLAGS           13
+#define SIZE_OF_SIGNATURE       13
+#define FLAG_START_OF_RUN       "\nSTART---RUN\n"
+#define FLAG_START_OF_EVENT     "\nSTART-EVENT\n"
+#define FLAG_END_OF_EVENT       "\nEND---EVENT\n"
+#define FLAG_END_OF_RUN         "\nEND-----RUN\n"
+#define FLAG_END_OF_FILE        "\nEND----FILE\n"
+#define FLAG_END_OF_STDIN       "\nEND---STDIN\n"
+// ------------------------------------------------
+
+Bool_t MReadRflFile::FlagIsA(const  char *s1, const char *flag)
+{
+    return strncmp(s1, flag, SIZE_OF_FLAGS)==0;
+}
+
+Bool_t MReadRflFile::ReadEvtHeader()
+{
+    if (fCurrentVersion <= 0.5)
+    {
+        RflEventHeader_old revth;
+        fIn->read((char*)&revth, sizeof(RflEventHeader_old));
+        fEvtHeader->SetEvtNumber((int)revth.EvtNumber);
+//        *fLog << "Event Number: " << revth.EvtNumber;
+//        *fLog << "  Primary ID: " << revth.PrimaryID;
+//        *fLog << "  Run Number: " << revth.RunNumber << endl;
+        return (bool)*fIn;
+    }
+    else
+    {
+        RflEventHeader revth;
+        fIn->read((char*)&revth, sizeof(RflEventHeader));
+        fEvtHeader->SetEvtNumber((int)revth.EvtNumber);
+//        *fLog << "Event Number: " << revth.EvtNumber;
+//        *fLog << "  Primary ID: " << revth.PrimaryID;
+//        *fLog << "  Run Number: " << revth.RunNumber << endl;
+        return (bool)*fIn;
+    }
+}
+
+enum {
+    kError,
+    kEndOfFile,
+    kStartOfRun,
+    kEndOfRun,
+    kStartOfEvtData,
+    kEndOfEvtData,
+    kUndefined
+};
+
+
+int MReadRflFile::ReadFlag()
+{
+    char flag[SIZE_OF_FLAGS];
+    fIn->read(flag, SIZE_OF_FLAGS);
+
+    if (!fIn)
+        return kError;
+
+    //*fLog << "<" << TString(&flag[1], 11)  << ">" <<endl;
+
+    if (FlagIsA(flag, FLAG_END_OF_FILE))
+        return kEndOfFile;
+    if (FlagIsA(flag, FLAG_END_OF_RUN))
+        return kEndOfRun;
+    if (FlagIsA(flag, FLAG_START_OF_RUN))
+        return kStartOfRun;
+    if (FlagIsA(flag, FLAG_END_OF_EVENT))
+        return kEndOfEvtData;
+    if (FlagIsA(flag, FLAG_START_OF_EVENT))
+        return kStartOfEvtData;
+
+    return kUndefined;
+}
+
+Bool_t MReadRflFile::ReadEvtData()
+{
+    Bool_t rc = kFALSE;
+    while (1)
+    {
+        cphoton data; // FIRST READ "START OF EVENT"
+        fIn->read((char*)&data, SIZE_OF_FLAGS);
+        if (!*fIn)
+            break;
+
+        if (FlagIsA((char*)&data, FLAG_END_OF_EVENT))
+        {
+            rc = kTRUE;
+            break;
+        }
+
+        fIn->read((char*)&data+SIZE_OF_FLAGS, sizeof(cphoton)-SIZE_OF_FLAGS);
+        if (!*fIn)
+            break;
+
+        MRflSinglePhoton &ph = fEvtData->GetNewPhoton();
+        ph.SetXY(data.x*10, data.y*10);
+        ph.SetCosUV(data.u, data.v);
+        ph.SetTime(data.t);
+        ph.SetHeight(data.h);
+        ph.SetInclinationAngle(data.phi);
+    }
+
+    fEvtData->FixSize();
+    return rc;
+}
+
+Int_t MReadRflFile::EvalFlag()
+{
+    const Int_t flag = ReadFlag();
+
+    switch (flag)
+    {
+    case kEndOfFile:
+        fCurrentVersion = ReadVersion();
+        if (fCurrentVersion<0)
+        {
+            *fLog << inf << "Found end of file...Everything OK." << endl;
+            break;
+        }
+
+        *fLog << warn << "Found flag of end of file, but file goes on..." << endl;
+        if (ReadFlag()<0)
+            return kError;
+        /* FALLTHROU */
+    case kStartOfRun:
+        if (fCurrentVersion>0.5)
+        {
+            RflRunHeader rrunh;
+            fIn->read((char*)&rrunh, sizeof(RflRunHeader));
+            if (*fIn)
+            {
+                *fLog << inf << "FIXME: Call ReInit" << endl;
+
+                fRunHeader->SetRunNumber((int)rrunh.RunNumber);
+                *fLog << underline << "RunHeader:" << endl;
+                *fLog << " Run Number:   " << rrunh.RunNumber << endl;
+                *fLog << " Date:         " << rrunh.date << endl;
+                *fLog << " Corsika Ver.: " << rrunh.Corsika_version << endl;
+
+                break;
+            }
+
+            *fLog << err << "Error! found end of file... But no EOF flag. Exiting." << endl;
+            return kError;
+        }
+        return kUndefined;
+
+    case kStartOfEvtData:
+    case kEndOfRun:
+        break;
+
+    case kError:
+        *fLog << err << "ERROR - Flag 'error'" << endl;
+        return kError;
+
+    case kUndefined:
+        *fLog << err << "ERROR - Flag 'undefined'" << endl;
+        return kError;
+
+    default:
+        *fLog << err << "ERROR - Unhandled flag" << endl;
+        return kError;
+
+    }
+    return flag;
+}
+
+Int_t MReadRflFile::Process()
+{
+    for (;;)
+    {
+        switch (EvalFlag())
+        {
+        case kError:
+            return kFALSE;
+
+        case kEndOfFile:
+            if (!OpenNextFile())
+                return kFALSE;
+            /* FALLTHROU */
+        case kStartOfRun:
+        case kEndOfRun:
+            continue;
+
+        case kStartOfEvtData:
+            break;
+        }
+        break;
+    }
+
+    if (!ReadEvtHeader())
+        return kFALSE;
+
+    return ReadEvtData();
+}
+
+Int_t MReadRflFile::PreProcess(MParList *plist)
+{
+    fEvtData=(MRflEvtData*)plist->FindCreateObj("MRflEvtData");
+    if (!fEvtData)
+        return kFALSE;
+
+    fEvtHeader=(MRflEvtHeader*)plist->FindCreateObj("MRflEvtHeader");
+    if (!fEvtHeader)
+        return kFALSE;
+
+    fRunHeader=(MRflRunHeader*)plist->FindCreateObj("MRflRunHeader");
+    if (!fRunHeader)
+        return kFALSE;
+
+    Rewind();
+
+    return OpenNextFile();
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Bool_t MReadRflFile::OpenNextFile()
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existence of a next file to read
+    //
+    if (fNumFile >= (UInt_t)fFileNames->GetSize())
+    {
+        *fLog << inf << GetDescriptor() << ": No unread files anymore..." << endl;
+        return kFALSE;
+    }
+
+    TNamed *file = (TNamed*)fFileNames->At(fNumFile);
+
+    //TNamed *file = (TNamed*)fFileNames->GetFirst();
+    //if (!file)
+    //    return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    fFileName = file->GetName();
+    const TString expname = fFileName;
+    gSystem->ExpandPathName(expname);
+
+    //
+    // Remove this file from the list of pending files
+    //
+    //fFileNames->Remove(file);
+
+    *fLog << inf << "Open file: '" << fFileName << "'" << endl;
+
+    fIn = new ifstream(expname);
+    if (!*fIn)
+    {
+        *fLog << err << "Cannot open file " << expname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator(fFileName);
+
+    fCurrentVersion = ReadVersion();
+    if (fCurrentVersion<0)
+    {
+        cout << "ERROR reading signature." << endl;
+        return kFALSE;
+    }
+    cout << "Version " << fCurrentVersion << endl << endl;
+
+    fNumFile++;
+    return kTRUE;
+}
+
+/****************************************************/
+
+float MReadRflFile::ReadVersion()
+{
+    char sign[20];
+    fIn->read(sign, SIZE_OF_SIGNATURE);
+    if (!*fIn)
+        return -1;
+
+    if (strncmp(sign, PROGNAME, strlen(PROGNAME)) != 0)
+    {
+        /* For the ascii tail of the file! : */
+        if (strncmp(sign, "\n############", SIZE_OF_SIGNATURE))
+            cout << "ERROR: Signature of .rfl file is not correct: " << sign << endl;
+
+        return -1;
+    }
+
+    float version;
+    sscanf(sign, "%*s %f", &version);
+
+    //If the version is < 0.6 the signature had one more byte
+    if (version < 0.6)
+        *fIn >> sign[0];
+
+    return version;
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates an array which stores the file names of
+// the files which should be read. If a filename is given it is added
+// to the list.
+//
+MReadRflFile::MReadRflFile(const char *fname, const char *name,
+                           const char *title) : fIn(NULL), fEntries(0)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Reads a Reflector output file";
+
+    //
+    // remember file name for opening the file in the preprocessor
+    //
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    if (fname)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the filename list and the input stream if one exists.
+//
+MReadRflFile::~MReadRflFile()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add this file as the last entry in the chain
+//
+Int_t MReadRflFile::AddFile(const char *txt, int)
+{
+    const char *name = gSystem->ExpandPathName(txt);
+
+    TString fname(name);
+    delete [] name;
+/*
+    if (!CheckHeader(fname))
+    {
+        *fLog << warn << "WARNING - Problem reading header... ignored." << endl;
+        return;
+    }
+
+    const Int_t n = GetNumEvents(fname);
+    if (n==0)
+    {
+        *fLog << warn << "WARNING - File contains no data... ignored." << endl;
+        return;
+    }
+
+    fEntries += n;
+
+    *fLog << inf << "File " << txt << " contains " << n << " events (Total=" << fEntries << ")" << endl;
+*/
+    fFileNames->AddLast(new TNamed(txt, ""));
+    return 1;
+}
+
+
+Bool_t MReadRflFile::SearchFor(Int_t runno, Int_t eventno)
+{
+    if (!fEvtHeader)
+        return kFALSE;
+
+    fNumFile = 0;
+    if (!OpenNextFile())
+        return kFALSE;
+
+    while (1)
+    {
+        fEvtData->Reset();
+        if (!Process())
+            return kFALSE;
+
+        if (fEvtHeader->GetEvtNumber()==eventno &&
+            fRunHeader->GetRunNumber()==runno)
+            return kTRUE;
+    }
+}
Index: /tags/Mars-V0.9/mfileio/MReadRflFile.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MReadRflFile.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MReadRflFile.h	(revision 9772)
@@ -0,0 +1,62 @@
+#ifndef MARS_MReadRflFile
+#define MARS_MReadRflFile
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class TList;
+class MRflEvtData;
+class MRflEvtHeader;
+class MRflRunHeader;
+
+class MReadRflFile : public MRead
+{
+private:
+    ifstream *fIn;          // the inputfile
+    TList    *fFileNames;   // Array which stores the \0-terminated filenames
+
+    MRflEvtData *fEvtData;        //!
+    MRflEvtHeader *fEvtHeader;
+    MRflRunHeader *fRunHeader;
+
+    UInt_t fNumFile;
+    UInt_t fEntries; // TO BE IMPLEMENTED
+    TString fFileName;
+
+    Float_t fCurrentVersion; //! Version of currently open rfl file
+
+    float  ReadVersion();
+    Bool_t ReadEvtHeader();
+    Bool_t ReadEvtData();
+    int    ReadFlag();
+    Bool_t FlagIsA(const  char *s1, const char *flag);
+    Int_t  EvalFlag();
+    Bool_t OpenNextFile();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MReadRflFile(const char *filename=NULL,
+                 const char *name=NULL,
+                 const char *title=NULL);
+
+    ~MReadRflFile();
+
+    Int_t AddFile(const char *fname, int i=0);
+
+    Bool_t Rewind() { fNumFile=0; return kTRUE; }
+    UInt_t GetEntries() { return fEntries; }
+    TString GetFullFileName() const { return fFileName; }
+
+    Bool_t SearchFor(Int_t runno, Int_t eventno);
+
+    ClassDef(MReadRflFile, 0) // Reads reflector files
+};
+
+#endif
Index: /tags/Mars-V0.9/mfileio/MReadTree.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MReadTree.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MReadTree.cc	(revision 9772)
@@ -0,0 +1,1216 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MReadTree
+//
+// This tasks opens all branches in a specified tree and creates the
+// corresponding parameter containers if not already existing in the
+// parameter list.
+//
+// The Process function reads one events from the tree. To go through the
+// events of one tree make sure that the event number is increased from
+// outside. It makes also possible to go back by decreasing the number.
+//
+// If you don't want to start reading the first event you have to call
+// MReadTree::SetEventNum after instantiating your MReadTree-object.
+//
+// To make reading much faster (up to a factor of 10 to 20) you can
+// ensure that only the data you are really processing is enabled by
+// calling MReadTree::UseLeaf.
+//
+// If the chain switches from one file to another file all
+// TObject::Notify() functions are called of TObject objects which were
+// added to the Notifier list view MReadTree::AddNotify. If MReadTree
+// is the owner (viw MReadTree::SetOwner) all this objects are deleted
+// by the destructor of MReadTree
+//
+//
+// ToDo:
+// -----
+//  - Auto Scheme and Branch choosing doesn't work for memory trees
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MReadTree.h"
+
+#include <fstream>
+
+#include <TFile.h>           // TFile::GetName
+#include <TSystem.h>         // gSystem->ExpandPath
+#include <TChainElement.h>
+#include <TOrdCollection.h>
+
+#include "MChain.h"
+#include "MFilter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MStatusDisplay.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MReadTree);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. Use this constructor (ONLY) if you want to
+//  access a memory tree (a TTree not stored in a file) created by
+//  MWriteRootFile or manually.
+//
+MReadTree::MReadTree(TTree *tree)
+    : fNumEntry(0), fNumEntries(0), fBranchChoosing(kFALSE), fAutoEnable(kTRUE)
+{
+    fName  = "MRead";
+    fTitle = "Task to loop over all events in one single tree";
+
+    fVetoList = new TList;
+    fVetoList->SetOwner();
+
+    fNotify = new TList;
+
+    fChain = NULL;
+
+    fTree = tree;
+    SetBit(kChainWasChanged);
+
+    if (fTree)
+        fAutoEnable = kFALSE;
+    /*
+    if (!fTree)
+        return;
+
+    TIter Next(fTree->GetListOfBranches());
+    TBranch *b=0;
+    while ((b=(TBranch*)Next()))
+        b->ResetAddress();
+    */
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. It creates an TChain instance which represents the
+//  the Tree you want to read and adds the given file (if you gave one).
+//  More files can be added using MReadTree::AddFile.
+//  Also an empty veto list is created. This list is used if you want to
+//  veto (disable or "don't enable") a branch in the tree, it vetos also
+//  the creation of the corresponding object.
+//  An empty list of TObjects are also created. This objects are called
+//  at any time the TChain starts to read from another file.
+//
+MReadTree::MReadTree(const char *tname, const char *fname,
+                     const char *name, const char *title)
+    : fNumEntry(0), fNumEntries(0), fBranchChoosing(kFALSE), fAutoEnable(kTRUE)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Task to loop over all events in one single tree";
+
+    fVetoList = new TList;
+    fVetoList->SetOwner();
+
+    fNotify = new TList;
+
+    //
+    // open the input stream
+    //
+    fChain = new MChain(tname);
+    fTree = fChain;
+
+    // root 3.02:
+    // In TChain::Addfile remove the limitation that the file name must contain
+    // the string ".root". ".root" is necessary only in case one wants to specify
+    // a Tree in a subdirectory of a Root file with eg, the format:
+
+    if (fname)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. It deletes the TChain and veto list object
+//
+MReadTree::~MReadTree()
+{
+    //
+    // Delete all the pointers to pointers to the objects where the
+    // branche data gets stored. FIXME: When PreProcessed twice this
+    // creates a memory leak!
+    //
+    if (fChain) // FIXME: MEMORY LEAK for fTree!=0
+    {
+        TIter Next(fChain->GetStatus());
+
+        TChainElement *element = NULL;
+        while ((element=(TChainElement*)Next()))
+            if (element->GetBaddress())
+                delete (MParContainer**)element->GetBaddress();
+
+        //
+        // Delete the chain and the veto list
+        //
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,00)
+        if (fChain->GetFile())
+            delete fChain->GetFile();
+#endif
+        delete fChain;
+    }
+
+    /* This is AND MUST be done in PostProcess. See there for more details
+    else
+    {
+        TIter Next(fTree->GetListOfBranches());
+
+        TBranch *element = NULL;
+        while ((element=(TBranch*)Next()))
+            if (element->GetAddress())
+                delete (MParContainer**)element->GetAddress();
+        }
+    */
+
+    delete fNotify;
+    delete fVetoList;
+}
+
+Byte_t MReadTree::IsFileValid(const char *name)
+{
+    ifstream fin(name);
+    if (!fin)
+        return 0;
+
+    Char_t c[4];
+    fin.read(c, 4);
+    if (!fin)
+        return 0;
+
+    return c[0]=='r'&& c[1]=='o' && c[2]=='o' && c[3]=='t' ? 1 : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// This check whether all branches in the tree have the same size. If
+// this is not the case the events in the different branches cannot
+// be ordered correctly.
+//
+Bool_t MReadTree::CheckBranchSize()
+{
+    TArrayI entries(fTree->GetListOfBranches()->GetSize());
+    Int_t num=0;
+
+    TIter Next(fTree->GetListOfBranches());
+
+    TBranch *element = NULL;
+    while ((element=(TBranch*)Next()))
+        entries[num++] = (Int_t)element->GetEntries();
+
+    // Check the number of entries of the branches pair-wise
+    for (int i=0; i<num; i++)
+        for (int j=i; j<num; j++)
+        {
+            if (entries[i]==entries[j])
+                continue;
+
+            *fLog << err << "ERROR - File corruption detected:" << endl;
+            *fLog << "  Due to several circumstances (such at a bug in MReadTree or wrong" << endl;
+            *fLog << "  usage of the file UPDATE mode) you may have produced a file in which" << endl;
+            *fLog << "  at least two branches in the same tree (" << fTree->GetName() << ") have different" << endl;
+            *fLog << "  number of entries. Sorry, but this file (" << GetFileName() << ")" << endl;
+            *fLog << "  is unusable." << endl;
+            return kFALSE;
+        }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the owner flag is set all TObjects which are scheduled via
+//  AddNotify are deleted by the destructor of MReadTree
+//
+void MReadTree::SetOwner(Bool_t flag)
+{
+    flag ? fNotify->SetBit(kIsOwner) : fNotify->ResetBit(kIsOwner);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This function is called each time MReadTree changes the file to read
+//  from. It calls all TObject::Notify() functions which are scheduled
+//  via AddNotify.
+//
+//  For unknown reasons root stores the SetAutoDelete-Flag in
+//  a branch having a custom streamer (eg. MRawEvtData).
+//  It is not allowed that a container which is in the parameter
+//  list gets a new address. Therefor we reset all the autodel flags.
+//
+//  MAKE SURE THAT ALL YOPUR CUSTOM STREAMERS TAKE CARE OF ALL MEMORY
+//
+Bool_t MReadTree::Notify()
+{
+    //
+    // Do a consistency check for all branches
+    //
+    if (!CheckBranchSize())
+        return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Switching to #" << GetFileIndex();
+    *fLog << " '" << GetFileName() << "' (before event #";
+    *fLog << GetNumEntry()-1 << ")" << endl;
+
+    if (fDisplay)
+    {
+        TString txt = GetFileName();
+        txt += " @ ";
+        txt += GetNumEntry()-1;
+        fDisplay->SetStatusLine2(txt);
+    }
+
+    //
+    // For unknown reasons root stores the SetAutoDelete-Flag in
+    // a branch having a custom streamer (eg. MRawEvtData).
+    // It is not allowed that a container which is in the parameter
+    // list gets a new address. Therefor we reset all the autodel flags.
+    //
+    // MAKE SURE THAT ALL YOPUR CUSTOM STREAMERS TAKE CARE OF ALL MEMORY
+    //
+    TIter NextB(fTree->GetListOfBranches());
+    TBranch *b=0;
+    while ((b=(TBranch*)NextB()))
+        if (b->IsAutoDelete())
+        {
+            *fLog << warn << "Branch " << b->GetName() << "->IsAutoDelete() set... resetting." << endl;
+            b->SetAutoDelete(kFALSE);
+        }
+
+    if (!fNotify)
+        return kTRUE;
+
+    TIter NextN(fNotify);
+    TObject *o=NULL;
+    while ((o=NextN()))
+        if (!o->Notify())
+        {
+            *fLog << err << "Calling Notify() for object " << o->GetName() << " failed... abort." << endl;
+            return kFALSE;
+        }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If you want to read the given tree over several files you must add
+//  the files here before PreProcess is called. Be careful: If the tree
+//  doesn't have the same contents (branches) it may confuse your
+//  program (trees which are are not existing in later files are not read
+//  anymore, tree wich are not existing in the first file are never read)
+//
+//  Name may use the wildcarding notation, eg "xxx*.root" means all files
+//  starting with xxx in the current file system directory.
+//
+//  AddFile returns the number of files added to the chain.
+//
+//  For more information see TChain::Add
+//
+Int_t MReadTree::AddFile(const char *fname, Int_t entries)
+{
+    if (!fChain)
+    {
+        *fLog << err << "MReadTree::AddFile - ERROR: You cannot add a file, because MReadTree" << endl;
+        *fLog <<        "                            handles a memory based tree or its default" << endl;
+        *fLog <<        "                            constructor was called." << endl;
+        return 0;
+    }
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,01)
+    //
+    // This is a workaround to get rid of crashed if the file doesn't
+    // exist due to non initialized TFile::fProcessIDs
+    //
+    //  (Code taken from TFile::TFile
+    //
+    TString newname; // char-array must overcome comming block
+
+    if (strrchr(fname, '?') || strrchr(fname, '*'))
+    {
+        *fLog << warn;
+        *fLog<< "WARNING: Using widcards with older root versions:" << endl;
+        *fLog << "  You may encounter crashes closing the files..." << endl;
+    }
+    else
+    {
+        const char *name;
+
+        if ((name = gSystem->ExpandPathName(fname)))
+        {
+            newname = name;
+            delete [] name;
+        }
+
+        if (newname.IsNull())
+        {
+            *fLog << err << dbginf << "Error expanding path " << fname << "." << endl;
+            return 0;
+        }
+
+        if (gSystem->AccessPathName(newname, kFileExists))
+        {
+            *fLog << err << "ERROR - File '" << fname << "' does not exist." << endl;
+            return 0;
+        }
+
+        fname = newname.Data();
+    }
+#endif
+
+    //
+    // FIXME! A check is missing whether the file already exists or not.
+    //
+    const Int_t numfiles = fChain->Add(fname, entries<0?TChain::kBigNumber:entries);
+
+    if (numfiles>0)
+    {
+        SetBit(kChainWasChanged);
+        *fLog << inf << GetDescriptor() << ": Added " << fname << " <" << numfiles << ">" << endl;
+    }
+    else
+        *fLog << warn << "WARNING: '" << fname << "' not added to " << GetDescriptor() << endl;
+
+    return numfiles;
+}
+
+/*
+ // --------------------------------------------------------------------------
+ //
+ //
+ Int_t MReadTree::AddFile(const TChainElement &obj)
+ {
+     return AddFile(obj.GetTitle(), obj.GetEntries());
+ }
+*/
+
+// --------------------------------------------------------------------------
+//
+// Adds all files from another MReadTree to this instance
+//
+// Returns the number of file which were added
+//
+Int_t MReadTree::AddFiles(const MReadTree &read)
+{
+    if (!fChain)
+    {
+        *fLog << err << "MReadTree::AddFiles - ERROR: You cannot add a file, because MReadTree" << endl;
+        *fLog <<        "                             handles a memory based tree or its default" << endl;
+        *fLog <<        "                             constructor was called." << endl;
+        return 0;
+    }
+
+    const Int_t rc = fChain->Add(read.fChain);
+
+    if (rc>0)
+        SetBit(kChainWasChanged);
+
+    /*
+     Int_t rc = 0;
+
+     TIter Next(read.fChain->GetListOfFiles());
+     TObject *obj = NULL;
+     while ((obj=Next()))
+         rc += AddFile(*(TChainElement*)obj);
+    */
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Sort the files by their file-names
+//
+void MReadTree::SortFiles()
+{
+    if (fChain)
+        fChain->GetListOfFiles()->Sort();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This function is called if Branch choosing method should get enabled.
+//  Branch choosing means, that only the enabled branches are read into
+//  memory. To use an enableing scheme we have to disable all branches first.
+//  This is done, if this function is called the first time.
+//
+void MReadTree::EnableBranchChoosing()
+{
+    if (fBranchChoosing)
+        return;
+
+    *fLog << inf << GetDescriptor() << ": Branch choosing enabled (only enabled branches are read)." << endl;
+    fTree->SetBranchStatus("*", kFALSE); // *CHANGED-fChain-to-fTree*
+    fBranchChoosing = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The first time this function is called all branches are disabled.
+// The given branch is enabled. By enabling only the branches you
+// are processing you can speed up your calculation many times (up to
+// a factor of 10 or 20)
+//
+void MReadTree::EnableBranch(const char *name)
+{
+    if (!fChain)
+    {
+        *fLog << warn << "MReadTree::EnableBranch - WARNING: EnableBranch doesn't work with memory based trees... ignored." << endl;
+        return;
+    }
+
+    if (fChain->GetListOfFiles()->GetEntries()==0)
+    {
+        *fLog << err << "Chain contains no file... Branch '";
+        *fLog << name << "' ignored." << endl;
+        return;
+    }
+
+    EnableBranchChoosing();
+
+    TNamed branch(name, "");
+    SetBranchStatus(&branch, kTRUE);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set branch status of branch name
+//
+void MReadTree::SetBranchStatus(const char *name, Bool_t status)
+{
+    fTree->SetBranchStatus(name, status); // *CHANGED-fChain-to-fTree*
+
+    *fLog << inf << (status ? "Enabled" : "Disabled");
+    *fLog << " subbranch '" << name << "'." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether a branch with the given name exists in the chain
+// and sets the branch status of this branch corresponding to status.
+//
+void MReadTree::SetBranchStatus(TObject *branch, Bool_t status)
+{
+    //
+    // Get branch name
+    //
+    const char *name = branch->GetName();
+
+    //
+    // Check whether this branch really exists
+    //
+    TString bn(name);
+    if (bn.EndsWith("*"))
+        bn.Remove(bn.Length()-1);
+
+    if (fTree->GetBranch(bn)) // *CHANGED-fChain-to-fTree*
+        SetBranchStatus(name, status);
+
+    //
+    // Remove trailing '.' if one and try to enable the subbranch without
+    // the master branch name. This is to be compatible with older mars
+    // and camera files.
+    //
+    const char *dot = strrchr(name, '.');
+    if (!dot)
+        return;
+
+    if (fTree->GetBranch(dot+1)) // *CHANGED-fChain-to-fTree*
+        SetBranchStatus(dot+1, status);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the status of all branches in the list to status.
+//
+void MReadTree::SetBranchStatus(const TList *list, Bool_t status)
+{
+    //
+    // Loop over all subbranches in this master branch
+    //
+    TIter Next(list);
+
+    TObject *obj;
+    while ((obj=Next()))
+        SetBranchStatus(obj, status);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is the implementation of the Auto Enabling Scheme.
+//  For more information see MTask::AddBranchToList.
+//  This function loops over all tasks and its filters in the tasklist
+//  and enables all branches which are requested by the tasks and its
+//  filters.
+//
+//  To enable 'unknown' branches which are not in the branchlist of
+//  the tasks you can call EnableBranch
+//
+void MReadTree::EnableBranches(MParList *plist)
+{
+    //
+    // check whether branch choosing must be switched on
+    //
+    EnableBranchChoosing();
+
+    //
+    // request the tasklist from the parameter list.
+    // FIXME: Tasklist can have a different name
+    //
+    const MTaskList *tlist = (MTaskList*)plist->FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << warn << GetDescriptor() << "Cannot use auto enabeling scheme for branches. 'MTaskList' not found." << endl;
+        return;
+    }
+
+    //
+    // This loop is not necessary. We could do it like in the commented
+    // loop below. But this loop makes sure, that we don't try to enable
+    // one branch several times. This would not harm, but we would get
+    // an output for each attempt. To have several outputs for one subbranch
+    // may confuse the user, this we don't want.
+    // This loop creates a new list of subbranches and for each branch
+    // which is added we check before whether it already exists or not.
+    //
+    TList list;
+
+    MTask *task;
+    TIter NextTask(tlist->GetList());
+    while ((task=(MTask*)NextTask()))
+    {
+        TObject *obj;
+
+        TIter NextTBranch(task->GetListOfBranches());
+        while ((obj=NextTBranch()))
+            if (!list.FindObject(obj->GetName()))
+                list.Add(obj);
+
+        const MFilter *filter = task->GetFilter();
+
+        if (!filter)
+            continue;
+
+        TIter NextFBranch(filter->GetListOfBranches());
+        while ((obj=NextFBranch()))
+            if (!list.FindObject(obj->GetName()))
+                list.Add(obj);
+    }
+
+    SetBranchStatus(&list, kTRUE);
+/*
+    //
+    // Loop over all tasks iand its filters n the task list.
+    //
+    MTask *task;
+    TIter NextTask(tlist->GetList());
+    while ((task=(MTask*)NextTask()))
+    {
+        SetBranchStatus(task->GetListOfBranches(), kTRUE);
+
+        const MFilter *filter = task->GetFilter();
+        if (!filter)
+           continue;
+
+        SetBranchStatus(filter->GetListOfBranches(), kTRUE);
+
+    }
+*/
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the chain has been changed (by calling AddFile or using a file
+//  in the constructors argument) the number of entries is newly
+//  calculated from the files in the chain - this may take a while.
+//  The number of entries is returned.
+//
+UInt_t MReadTree::GetEntries()
+{
+    if (TestBit(kChainWasChanged))
+    {
+        // *CHANGED-fChain-to-fTree*
+        *fLog << inf << "Scanning chain " << fTree->GetName() << "... " << flush;
+        fNumEntries = (UInt_t)fTree->GetEntries();
+        *fLog << fNumEntries << " events found." << endl;
+        ResetBit(kChainWasChanged);
+    }
+    return fNumEntries==TChain::kBigNumber ? 0 : fNumEntries;
+}
+
+// --------------------------------------------------------------------------
+//
+//  The disables all subbranches of the given master branch.
+//
+void MReadTree::DisableSubBranches(TBranch *branch)
+{
+    //
+    // This is not necessary, it would work without. But the output
+    // may confuse the user...
+    //
+    if (fAutoEnable || fBranchChoosing)
+        return;
+
+    SetBranchStatus(branch->GetListOfBranches(), kFALSE);
+}
+
+// --------------------------------------------------------------------------
+//
+//  The PreProcess loops (till now) over the branches in the given tree.
+//  It checks if the corresponding containers (containers with the same
+//  name than the branch name) are existing in the Parameter Container List.
+//  If not, a container of objec type 'branch-name' is created (everything
+//  after the last semicolon in the branch name is stripped). Only
+//  branches which don't have a veto (see VetoBranch) are enabled If the
+//  object isn't found in the root dictionary (a list of classes known by the
+//  root environment) the branch is skipped and an error message is printed
+//  out.
+//  If a selector is specified it is preprocessed after the
+//  MReadTree::PreProcess
+//
+Int_t MReadTree::PreProcess(MParList *pList)
+{
+    fTaskList = (MTaskList*)pList->FindObject("MTaskList");
+    if (!fTaskList)
+        *fLog << warn << "WARNING - Standard tasklist MTaskList not found... ignoring Stream-ID." << endl;
+
+    //
+    // Make sure, that all the following calls doesn't result in
+    // Notifications. This may be dangerous, because the notified
+    // tasks are not preprocessed.
+    //
+    fTree->SetNotify(NULL); //*CHANGED-fChain-to-fTree*
+
+    //
+    // It seems, that TFile and TTree are not completely independant if
+    // many times the same file is openes (MReadReports) and some of
+    // the files in the chains don't have one tree. TChain::fTreeNumber
+    // is already set before LoadTree from GetFile is called and
+    // it crashes. ResetTree makes sure, that the tree number is -1
+    //
+    if (fChain) // *CHANGED-fChain-to-fTree*
+        fChain->ResetTree();
+    // Maybe this would be enough, but the above might be safer...
+    //if (fChain->GetTreeNumber()==0)
+    //    fChain->ResetTree();
+
+    //
+    // check for files and for the tree!
+    //
+    if (fChain && !fChain->GetFile()) // *CHANGED-fChain-to-fTree*
+    {
+        *fLog << err << GetDescriptor() << ": No file or no tree with name " << fChain->GetName() << " in file." << endl;
+        return kFALSE;
+    }
+
+    //
+    // get number of events in this tree
+    //
+    if (!GetEntries())
+    {
+        *fLog << err << GetDescriptor() << ": No entries found in file(s)" << endl;
+        return kFALSE;
+    }
+
+    //
+    // output logging information
+    //
+    *fLog << inf << fNumEntries << " entries found in file(s)." << endl;
+
+    //
+    // Get all branches of this tree and
+    // create the Iterator to loop over all branches
+    //
+    TIter Next(fTree->GetListOfBranches()); // *CHANGED-fChain-to-fTree*
+    TBranch *branch=NULL;
+
+    Int_t num=0;
+
+    //
+    // loop over all tasks for processing
+    //
+    while ( (branch=(TBranch*)Next()) )
+    {
+        //
+        // Get Name of Branch and Object
+        //
+        const char *bname = branch->GetName();
+
+        TString oname(bname);
+        if (oname.EndsWith("."))
+            oname.Remove(oname.Length()-1);
+
+        //
+        // Check if enabeling the branch is allowed
+        //
+        if (fVetoList->FindObject(oname))
+        {
+            *fLog << inf << "Master branch " << bname << " has veto... skipped." << endl;
+            DisableSubBranches(branch);
+            continue;
+        }
+
+        //
+        // Create a pointer to the pointer to the object in which the
+        // branch data is stored. The pointers are stored in the TChain
+        // object and we get the pointers from there to delete it.
+        //
+        MParContainer **pcont= new MParContainer*;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,06)
+        const char *classname = oname;
+#else
+        const char *classname = branch->GetClassName();
+#endif
+
+        //
+        // check if object is existing in the list
+        //
+        *pcont=pList->FindCreateObj(classname, oname);
+
+        if (!*pcont)
+        {
+            //
+            // if class is not existing in the (root) environment
+            // we cannot proceed reading this branch
+            //
+            *fLog << warn << dbginf << "Warning: Class '" << classname;
+            *fLog << "' for " << oname << " not existing in dictionary. Branch skipped." << endl;
+            DisableSubBranches(branch);
+            continue;
+        }
+
+        //
+        // Check whether a Pointer to a pointer already exists.
+        // If we created one already, delete it.
+        //
+        // *CHANGED-fChain-to-fTree*
+        if (fChain)
+        {
+            TChainElement *element = (TChainElement*)fChain->GetStatus()->FindObject(bname);
+            if (element)
+                delete (MParContainer**)element->GetBaddress();
+        }
+        /* This can't be done here for memory trees - see
+           PostProcess for more details.
+        else
+        {
+            TBranch *branch = (TBranch*)fTree->GetBranch(bname);
+            if (branch)
+            {
+                *fLog << bname << " " << (void*)branch->GetAddress() << " " << pcont << endl;
+                delete (MParContainer**)branch->GetAddress();
+            }
+        }
+        */
+
+        //
+        // here pcont is a pointer the to container in which the data from
+        // the actual branch should be stored - enable branch.
+        //
+        fTree->SetBranchAddress(bname, pcont); // *CHANGED-fChain-to-fTree*
+
+        *fLog << inf << "Master branch address '" << bname << "' ";
+        if ((TString)bname!=(TString)classname)
+            *fLog << "[" << classname << "] ";
+        *fLog << "setup for reading." << endl;
+
+        //*fLog << "Branch " << bname << " autodel: " << (int)branch->IsAutoDelete() << endl;
+        //branch->SetAutoDelete();
+
+        num++;
+    }
+
+    *fLog << inf << GetDescriptor() << " setup " << num << " master branches addresses." << endl;
+
+    //
+    // If auto enabling scheme isn't disabled, do auto enabling
+    //
+    if (fAutoEnable)
+        EnableBranches(pList);
+
+    //
+    // Now we can start notifying. Reset tree makes sure, that TChain thinks
+    // that the correct file is not yet initialized and reinitilizes it
+    // as soon as the first event is read. This is necessary to call
+    // the notifiers when the first event is read, but after the
+    // PreProcess-function.
+    //
+    if (fChain)
+        fChain->ResetTree(); // *CHANGED-fChain-to-fTree*
+
+    fTree->SetNotify(this); // *CHANGED-fChain-to-fTree*
+
+    const Int_t rc = GetSelector() ? GetSelector()->CallPreProcess(pList) : kTRUE;
+    if (rc!=kTRUE || fChain)
+        return rc;
+
+    return Notify();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the ready to save flag of all containers which branchaddresses are
+//  set for. This is necessary to copy data.
+//
+void MReadTree::SetReadyToSave(Bool_t flag)
+{
+    if (!fChain)
+        return;
+
+    TIter Next(fChain->GetStatus());
+
+    TChainElement *element = NULL;
+    while ((element=(TChainElement*)Next()))
+    {
+        //
+        // Check whether the branch is enabled
+        //
+        if (!element->GetStatus())
+            continue;
+
+        //
+        // Get the pointer to the pointer of the corresponding container
+        //
+        MParContainer **pcont = (MParContainer**)element->GetBaddress();
+
+        //
+        // Check whether the pointer is not NULL
+        //
+        if (!pcont || !*pcont)
+            continue;
+
+        //
+        // Set the ready to save status of the container.
+        //
+        (*pcont)->SetReadyToSave(flag);
+    }
+
+    //
+    // Set the ready to save status of this task (used?), too
+    //
+    MTask::SetReadyToSave(flag);
+}
+
+// --------------------------------------------------------------------------
+//
+//  The Process-function reads one event from the tree (this contains all
+//  enabled branches) and increases the position in the file by one event.
+//  (Remark: The position can also be set by some member functions
+//  If the end of the file is reached the Eventloop is stopped.
+//  In case an event selector is given its value is checked before
+//  reading the event. If it returns kAFLSE the event is skipped.
+//
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,06)
+#include "MRawEvtData.h"
+#endif
+Int_t MReadTree::Process()
+{
+    //
+    // This is necessary due to a bug in TChain::LoadTree in root.
+    // will be fixed in 3.03
+    //
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,01)
+    if (fNumEntry >= GetEntries())
+        return kFALSE;
+#endif
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,06)
+    //
+    // This fixes 99.9% of a memory leak using a root version prior
+    // to 3.02/??
+    //
+    TChainElement *element=NULL;
+    TIter Next(fChain->GetStatus());
+    while ((element=(TChainElement*)Next()))
+    {
+        MParContainer **c = (MParContainer**)element->GetBaddress();
+        if (!c) continue;
+        if ((*c)->InheritsFrom(MRawEvtData::Class()))
+            static_cast<MRawEvtData*>(*c)->DeletePixels(kFALSE);
+
+    }
+#endif
+
+    if (GetSelector())
+    {
+        //
+        // Make sure selector is processed
+        //
+        if (!GetSelector()->CallProcess())
+        {
+            *fLog << err << dbginf << "Processing Selector failed." << endl;
+            return kFALSE;
+        }
+
+        //
+        // Skip Event
+        //
+        if (!GetSelector()->IsConditionTrue())
+        {
+            fNumEntry++;
+            return kCONTINUE;
+        }
+    }
+
+    const Bool_t rc = fTree->GetEntry(fNumEntry++) != 0; // *CHANGED-fChain-to-fTree*
+
+    if (fTaskList)
+        fTaskList->SetStreamId(fTree->GetName()); // *CHANGED-fChain-to-fTree*
+
+    if (rc)
+    {
+        SetReadyToSave();
+        return kTRUE;
+    }
+
+    if (fChain)
+        switch (fChain->GetLastError())
+        {
+        case MChain::kFatalError:
+            *fLog << err << GetDescriptor() << " - ERROR: Notify() failed." << endl;
+            return kERROR;
+        case MChain::kCannotAccessFile:
+            *fLog << err << GetDescriptor() << " - ERROR: TChain::LoadTree is unable to access requested file." << endl;
+            return kERROR;
+        case MChain::kCannotAccessTree:
+            *fLog << err << GetDescriptor() << " - ERROR: TChain::LoadTree is unable to access requested tree." << endl;
+            return kERROR;
+        case MChain::kOutOfRange: // no more events available
+            return kFALSE;
+        case MChain::kNoError:    // go on!
+            return kTRUE;
+        }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If a selector is given the selector is post processed
+//
+Int_t MReadTree::PostProcess()
+{
+    // In the case of a memory tree I don't know how we can
+    // make a decision in PreProcess between a self allocated
+    // memory address or a pending address set long before.
+    // So we delete the stuff in PostProcess and not the destructor
+    // (which might seg faullt if PreProcess has never been called)
+    if (!fChain)
+    {
+        TIter Next(fTree->GetListOfBranches());
+        TBranch *b=0;
+        while ((b=(TBranch*)Next()))
+        {
+            if (b->GetAddress())
+            {
+                delete b->GetAddress();
+                b->ResetAddress();
+            }
+        }
+    }
+
+    return GetSelector() ? GetSelector()->CallPostProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Event with the current EventNumber fNumEntry
+//
+Bool_t MReadTree::GetEvent()
+{
+    Bool_t rc = fTree->GetEntry(fNumEntry) != 0; // *CHANGED-fChain-to-fTree*
+
+    if (rc)
+        SetReadyToSave();
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Decrease the number of the event which is read by Process() next
+// by one or more
+//
+Bool_t MReadTree::DecEventNum(UInt_t dec)
+{
+    if (fNumEntry-dec >= GetEntries())
+    {
+        *fLog << warn << GetDescriptor() << ": DecEventNum, WARNING - Event " << fNumEntry << "-";
+        *fLog << dec << "=" << (Int_t)fNumEntry-dec << " out of Range (>=";
+        *fLog << GetEntries() << ")." << endl;
+        return kFALSE;
+    }
+
+    fNumEntry -= dec;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Increase the number of the event which is read by Process() next
+// by one or more
+//
+Bool_t MReadTree::IncEventNum(UInt_t inc)
+{
+    if (fNumEntry+inc >= GetEntries())
+    {
+        *fLog << warn << GetDescriptor() << ": IncEventNum, WARNING - Event " << fNumEntry << "+";
+        *fLog << inc << "=" << (Int_t)fNumEntry+inc << " out of Range (>=";
+        *fLog << GetEntries() << ")." << endl;
+        return kFALSE;
+    }
+
+    fNumEntry += inc;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function makes Process() read event number nr next
+//
+// Remark: You can use this function after instatiating you MReadTree-object
+//         to set the event number from which you want to start reading.
+//
+Bool_t MReadTree::SetEventNum(UInt_t nr)
+{
+    if (nr!=0 && nr >= GetEntries())
+    {
+        *fLog << warn << GetDescriptor() << ": SetEventNum, WARNING - " << nr << " out of Range." << endl;
+        return kFALSE;
+    }
+
+    fNumEntry = nr;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  For the branch with the given name:
+//   1) no object is automatically created
+//   2) the branch address for this branch is not set
+//      (because we lack the object, see 1)
+//   3) The whole branch (exactly: all its subbranches) are disabled
+//      this means are not read in memory by TTree:GetEntry
+//
+void MReadTree::VetoBranch(const char *name)
+{
+    fVetoList->Add(new TNamed(name, ""));
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the name of the file we are actually reading from.
+//
+TString MReadTree::GetFullFileName() const
+{
+    const TFile *file = fChain ? fChain->GetFile() : fTree->GetCurrentFile();
+
+    if (!file)
+        return "<unknown>";
+
+    return file->GetName();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the number of the file in the chain, -1 in case of an error
+//
+Int_t MReadTree::GetFileIndex() const
+{
+    return fChain ? fChain->GetTreeNumber() : 0;
+    /*
+    const TString filename = fChain->GetFile()->GetName();
+
+    int i=0;
+    TObject *file = NULL;
+
+    TIter Next(fChain->GetListOfFiles());
+    while ((file=Next()))
+    {
+        if (filename==gSystem->ExpandPathName(file->GetTitle()))
+            return i;
+        i++;
+    }
+    return -1;
+    */
+}
+
+// --------------------------------------------------------------------------
+//
+//  This schedules a TObject which Notify(9 function is called in case
+//  of MReadTree (TChain) switches from one file in the chain to another
+//  one.
+//
+void MReadTree::AddNotify(TObject *obj)
+{
+    fNotify->Add(obj);
+}
+
+void MReadTree::Print(Option_t *o) const
+{
+    *fLog << all << underline << GetDescriptor() << ":" << endl << dec;
+    *fLog << " Files [Tree]:" << endl;
+
+    int i = 0;
+    TIter Next(fChain->GetListOfFiles());
+    TObject *obj = NULL;
+    while ((obj=Next()))
+        *fLog << " " << i++ << ") " << obj->GetTitle() << " [" << obj->GetName() << "]" << endl;
+
+    *fLog << " Total Number of Entries: " << fNumEntries << endl;
+    *fLog << " Next Entry to read: " << fNumEntry << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MReadTree::StreamPrimitive(ofstream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << fChain->GetName() << "\", \"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    TIter Next(fChain->GetListOfFiles());
+    TObject *obj = NULL;
+    while ((obj=Next()))
+        out << "   " << GetUniqueName() << ".AddFile(\"" << obj->GetTitle() << "\");" << endl;
+
+    if (!fAutoEnable)
+        out << "   " << GetUniqueName() << ".DisableAutoScheme();" << endl;
+
+    if (fNumEntry!=0)
+       out << "   " << GetUniqueName() << ".SetEventNum(" << fNumEntry << ");" << endl;
+
+
+}
Index: /tags/Mars-V0.9/mfileio/MReadTree.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MReadTree.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MReadTree.h	(revision 9772)
@@ -0,0 +1,95 @@
+#ifndef MARS_MReadTree
+#define MARS_MReadTree
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MChain;
+class TBranch;
+class TTree;
+class MTaskList;
+
+class MReadTree : public MRead
+{
+    friend class MReadReports;
+
+private:
+    MChain *fChain;            // Pointer to tree==fTree (only if fTree inherits from MChain)
+    TTree  *fTree;             // Pointer to tree
+
+    UInt_t  fNumEntry;         // Number of actual entry in chain
+    UInt_t  fNumEntries;       // Number of Events in chain
+
+    Bool_t  fBranchChoosing;   // Flag for branch choosing method
+    Bool_t  fAutoEnable;       // Flag for auto enabeling scheme
+
+    TList  *fVetoList;         //-> List of Branches which are not allowed to get enabled
+    TList  *fNotify;           //-> List of TObjects to notify when switching files
+
+    MTaskList *fTaskList;      // Tasklist to set StreamId
+
+    enum { kChainWasChanged = BIT(14) };
+
+private:
+    void SetBranchStatus(const TList *list, Bool_t status);
+    void SetBranchStatus(TObject *branch, Bool_t status);
+    void SetBranchStatus(const char *name, Bool_t status);
+
+    void DisableSubBranches(TBranch *b);
+    void EnableBranches(MParList *plist);
+    void EnableBranchChoosing();
+
+    Bool_t CheckBranchSize();
+
+    virtual void SetReadyToSave(Bool_t flag=kTRUE);
+    virtual void StreamPrimitive(ofstream &out) const;
+
+    enum { kIsOwner = BIT(14) };
+
+public:
+    MReadTree(TTree *tree=0);
+    MReadTree(const char *treename, const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+    ~MReadTree();
+
+    static Byte_t IsFileValid(const char *name);
+
+    virtual void SortFiles();
+
+    void   DisableAutoScheme() { fAutoEnable = kFALSE; }
+    void   EnableBranch(const char *name);
+    void   VetoBranch(const char *name);
+
+    Bool_t GetEvent();
+
+    Bool_t DecEventNum(UInt_t dec=1); // decrease number of event (position in tree)
+    Bool_t IncEventNum(UInt_t inc=1); // increase number of event (position in tree)
+    Bool_t SetEventNum(UInt_t nr);    // set number of event (position in tree)
+
+    UInt_t GetNumEntry() const { return fNumEntry; }
+    UInt_t GetEntries();
+
+    //TString GetFileName() const;
+    TString GetFullFileName() const;
+    Int_t   GetFileIndex() const;
+
+    virtual void AddNotify(TObject *obj);
+    virtual void SetOwner(Bool_t flag=kTRUE);
+
+    virtual Int_t AddFile(const char *fname, Int_t entries=-1);
+    virtual Int_t AddFiles(const MReadTree &read);
+    Int_t AddFiles(MDirIter &dir) { return MRead::AddFiles(dir); }
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t Notify();
+    Bool_t Rewind() { SetEventNum(0); return kTRUE; }
+    void   Print(Option_t *opt="") const;
+
+    ClassDef(MReadTree, 1)	// Reads a tree from file(s)
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mfileio/MWriteAsciiFile.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MWriteAsciiFile.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MWriteAsciiFile.cc	(revision 9772)
@@ -0,0 +1,319 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 06/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MWriteAsciiFile
+//
+// If you want to store a single container into an Ascii file you have
+// to use this class. You must know the name of the file you wanne write
+// (you should know it) and the name of the container you want to write.
+// This can be the name of the class or a given name, which identifies
+// the container in a parameter container list (MParList).
+// The container is written to the ascii file if its ReadyToSave flag is
+// set (MParContainer)
+//
+// You can write more than one container in one line of the file, see
+// AddContainer.
+//
+// You can also write single data members of a container (like fWidth
+// of MHillas). For more details see AddContainer. Make sure, that a
+// getter method for the data member exist. The name of the method
+// must be the same than the data member itself, but the f must be
+// replaced by a Get.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MWriteAsciiFile.h"
+
+#include <fstream>
+
+#include <TMethodCall.h> // TMethodCall, AsciiWrite
+
+#include "MIter.h"
+
+#include "MDataList.h"   // MDataList
+#include "MDataChain.h"  // MDataChain
+#include "MDataValue.h"  // MDataValue
+#include "MDataMember.h" // MDataMember
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MWriteAsciiFile);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Init. Replaces the same code used in all constructors.
+//
+void MWriteAsciiFile::Init(const char *filename, const char *name, const char *title)
+{
+    fName  = name  ? name  : "MWriteAsciiFile";
+    fTitle = title ? title : "Task to write one container to an ascii file";
+
+    fNameFile = filename;
+
+    fOut = new ofstream(fNameFile);
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the name of the ascii output file 'filename' and the name
+// of the container you want to write. (Normally this is the name
+// of the class (eg. MHillas) but it can also be a different name which
+// identifies the container in the parameter list.
+// Because you cannot write more than one container there is no Add-function
+// like in MWriteRootFile.
+//
+//  For Example: MWriteAsciiFile("file.txt", "MHillas");
+//
+MWriteAsciiFile::MWriteAsciiFile(const char *filename, const char *contname,
+                                 const char *name, const char *title)
+{
+    Init(filename, name, title);
+
+    if (contname)
+       AddColumns(contname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify a the name of the ascii output file 'filename' and a pointer to
+// the container you want to write. 
+// Because you cannot write more than one container there is no Add-function
+// like in MWriteRootFile.
+//
+//  For Example: MHillas hillas;
+//               MWriteAsciiFile("file.txt", &hillas);
+//
+//
+MWriteAsciiFile::MWriteAsciiFile(const char *filename, MParContainer *cont,
+                                 const char *name, const char *title)
+{
+    Init(filename, name, title);
+
+    if (cont)
+        AddColumns(cont);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete the output file if necessary (it is closed
+// automatically by its destructor.
+//
+MWriteAsciiFile::~MWriteAsciiFile()
+{
+    fAutoDel.SetOwner();
+    delete fOut;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return open state of the file
+//
+Bool_t MWriteAsciiFile::IsFileOpen() const
+{
+    return (bool)(*fOut);
+}
+
+// --------------------------------------------------------------------------
+//
+// Tries to get all containers from the ParList which were given by name
+// adds them to the list of pointers to the container which should be
+// written to the ascii file.
+//
+Bool_t MWriteAsciiFile::GetContainer(MParList *plist)
+{
+    TObject *obj=NULL;
+
+    TIter Next(&fList);
+    while ((obj=Next()))
+    {
+        //
+        // MData is the highest class in the inheritance tree
+        //
+        if (obj->InheritsFrom(MData::Class()))
+        {
+            if (!((MData*)obj)->PreProcess(plist))
+                return kFALSE;
+            continue;
+        }
+
+        //
+        // MParContainer is the next class in the inheritance tree
+        //
+        if (obj->InheritsFrom(MParContainer::Class()))
+            continue;
+
+        //
+        // It is neither a MData nor a MParContainer, it must be a TNamed
+        //
+        TObject *o = plist->FindObject(obj->GetName());
+        if (!o)
+            return kFALSE;
+
+        fList[fList.IndexOf(obj)] = o;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if the containers are ready for writing. If so write them.
+// The containers are written in one line, one after each other.
+// If not all containers are written (because of the IsReadyToSave-flag)
+// a warning message is print.
+//
+Bool_t MWriteAsciiFile::CheckAndWrite()
+{
+    MParContainer *obj = NULL;
+
+    //
+    // Check for the Write flag
+    //
+    Bool_t write = kFALSE;
+    MIter Next(&fList);
+    while ((obj=Next()))
+        if (obj->IsReadyToSave())
+        {
+            write = kTRUE;
+            break;
+        }
+
+    //
+    // Do not write if not at least one ReadyToSave-flag set
+    //
+    if (!write)
+        return kTRUE;
+
+    Bool_t written = kFALSE;
+    Int_t num = fList.GetEntries();
+
+    Next.Reset();
+    while ((obj=Next()))
+    {
+        if (written)
+            *fOut << " ";
+
+        //
+        // Write container to file
+        //
+        if (!obj->AsciiWrite(*fOut))
+            continue;
+
+        //
+        // Store that at least one container was written
+        //
+        written = kTRUE;
+
+        num--;
+    }
+
+    if (written)
+    {
+        *fOut << endl;
+
+        if (num!=0)
+            *fLog << warn << "WARNING - Number of objects written mismatch!" << endl;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a rule to be written as a column to the ascii file.
+// For more information about rules see MDataChain.
+//
+//  eg: MWriteAsciiFile::AddColumn("log10(MHillas.fEnergy)/2")
+//
+void MWriteAsciiFile::AddColumn(const TString rule)
+{
+    MDataChain *chain = new MDataChain(rule);
+    fList.Add(chain);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add another column to be written to the ascii file. The columns will be
+// output one after each other in one line.
+// Specify the name of the data member to be written (eg fWidth) and
+// a possible scale factor (eg. to transform millimeters to degrees)
+//
+//  eg:
+//       MMcEvt evt;
+//       MWriteAsciiFile::AddColumn(&evt, "fImpact", 0.01);
+//
+void MWriteAsciiFile::AddColumn(MParContainer *cont, const TString member, Double_t scale)
+{
+    MData *data = new MDataMember(cont, member);
+
+    if (scale!=1)
+    {
+        MDataList  *list = new MDataList('*');
+        MDataValue *val  = new MDataValue(scale);
+
+        list->SetOwner();
+        list->AddToList(data);
+        list->AddToList(val);
+
+        data = list;
+    }
+    fList.Add(data);
+    fAutoDel.Add(data);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add another container (by name) to be written to the ascii file.
+// The container will be output one after each other in one line.
+// The output will be done either by MParContainer::AsciiWrite or
+// by the corresponding overloaded function.
+//
+//  eg: MWriteAsciiFile::AddColumns("MMcEvt")
+//
+void MWriteAsciiFile::AddColumns(const TString cont)
+{
+    TNamed *name = new TNamed(cont, cont);
+    fList.Add(name);
+    fAutoDel.Add(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add another container (by pointer) to be written to the ascii file.
+// The container will be output one after each other in one line.
+// The output will be done either by MParContainer::AsciiWrite or
+// by the corresponding overloaded function.
+//
+//  eg:
+//      MMcEvt evt;
+//      MWriteAsciiFile::AddColumns(&evt);
+//
+void MWriteAsciiFile::AddColumns(MParContainer *cont)
+{
+    fList.Add(cont);
+}
Index: /tags/Mars-V0.9/mfileio/MWriteAsciiFile.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MWriteAsciiFile.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MWriteAsciiFile.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MWriteAsciiFile
+#define MARS_MWriteAsciiFile
+
+#ifndef MARS_MWriteFile
+#include "MWriteFile.h"
+#endif
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MData;
+
+class MWriteAsciiFile : public MWriteFile
+{
+private:
+    ofstream *fOut;     //! ascii file
+
+    TString fNameFile;  // name of the ascii file
+
+    TObjArray fList;    // list of rules and containers to be written
+    TObjArray fAutoDel; //! List of object to be deleted in the destructor
+
+    virtual Bool_t CheckAndWrite();
+    virtual Bool_t IsFileOpen() const;
+    virtual Bool_t GetContainer(MParList *pList);
+    virtual const char *GetFileName() const { return fNameFile; }
+
+    void Init(const char *filename, const char *name, const char *title);
+
+public:
+    MWriteAsciiFile(const char *filename, const char *contname,
+                    const char *name=NULL, const char *title=NULL);
+    MWriteAsciiFile(const char *filename, MParContainer *cont=NULL,
+                    const char *name=NULL, const char *title=NULL);
+    ~MWriteAsciiFile();
+
+    void AddColumn(const TString rule);
+    void AddColumn(MParContainer *cont, const TString member="", Double_t scale=1);
+    void AddColumns(const TString name);
+    void AddColumns(MParContainer *cont);
+
+    ClassDef(MWriteAsciiFile, 0) // Class to write data into an ascii file
+};
+
+#endif
Index: /tags/Mars-V0.9/mfileio/MWriteFile.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MWriteFile.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MWriteFile.cc	(revision 9772)
@@ -0,0 +1,114 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MWriteFile
+//
+// This is a base class for writing tasks. If you want to implement
+// writing out parameter containers in a new file format, this is a good
+// starting point.
+// The class defines a generalized interface between writing out data in
+// an eventloop and your file format.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MWriteFile.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MWriteFile);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Tries to open the given output file.
+// The derived class should retrieve needed containers from the parameter
+// list.
+// instance of the container which should be written.
+// If the container has already the HasChanged flag it is immediatly written
+// to the output file.
+//
+Int_t MWriteFile::PreProcess(MParList *pList)
+{
+    //
+    // test whether file is now open or not
+    //
+    if (!IsFileOpen())
+    {
+        *fLog << err << dbginf << "Cannot open file '" << GetFileName() << "'" << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "File '" << GetFileName() << "' open for writing." << endl;
+
+    //
+    // Get the containers (pointers) from the parameter list you want to write
+    //
+    if (!GetContainer(pList))
+        return kFALSE;
+
+    //
+    // write the container if it is already in changed state
+    //
+    return CheckAndWrite();
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks if the SetReadyToSave flag of the output container is set. If it
+// is set the container should be written to the output.
+//
+Bool_t MWriteFile::ReInit(MParList *pList)
+{
+    return CheckAndWrite();
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks if the SetReadyToSave flag of the output container is set. If it is
+// set the container should be written to the output.
+//
+Int_t MWriteFile::Process()
+{
+    return CheckAndWrite();
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks if the SetReadyToSave flag of the output container is set. If it is
+// set the container should be written to the output.
+//
+Int_t MWriteFile::PostProcess()
+{
+    //
+    // check if the container changed state is set
+    //
+    return CheckAndWrite();
+}
Index: /tags/Mars-V0.9/mfileio/MWriteFile.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MWriteFile.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MWriteFile.h	(revision 9772)
@@ -0,0 +1,27 @@
+#ifndef MARS_MWriteFile
+#define MARS_MWriteFile
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MWriteFile : public MTask
+{
+protected:
+    Bool_t ReInit(MParList *pList);
+
+private:
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    virtual Bool_t      IsFileOpen() const = 0;
+    virtual Bool_t      CheckAndWrite() = 0;
+    virtual Bool_t      GetContainer(MParList *pList) = 0;
+    virtual const char *GetFileName() const = 0;
+
+
+    ClassDef(MWriteFile, 0)	// Base class for tasks to write single containers to several output formats
+};
+
+#endif
Index: /tags/Mars-V0.9/mfileio/MWriteRootFile.cc
===================================================================
--- /tags/Mars-V0.9/mfileio/MWriteRootFile.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MWriteRootFile.cc	(revision 9772)
@@ -0,0 +1,1099 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MWriteRootFile
+//
+// This is a writer to store several containers to a root file.
+// The containers are added with AddContainer.
+// To understand how it works, see base class MWriteFile
+//
+// Warning: Look at the Warning in MTaskList.
+//
+// There is a special mode of operation which opens a new file for each new
+// file read by the reading task (opening the new file is initiated by
+// ReInit()) For more details se the corresponding constructor.
+//
+// Memory based trees
+// ------------------
+// It is possible to store the data into memory (TTrees) instead of
+// writing the data into a file. To do this either call the default
+// constructor or specify 'memory' as option in the constructor.
+//
+// Afterwards the tree can be found using
+// gROOT->GetListOfFiles()->FindObject("treename")
+//
+// Currently(!) the tree is not deleted at all! Please make sure to
+// delete it if it is not used anymore - otherwise you could wast a LOT
+// of memory. Please consider that this behaviour might change in the
+// future.
+//
+// Such trees are usefull if you want to use more basic root-tools
+// like TMultiLayerPerceptron or TEventList.
+//
+// If you want to process such memory based Trees using Mars make sure,
+// that you don't need data from the RunHeader tree because you can
+// only use MReadTree but not MReadMarsFile with such a tree.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MWriteRootFile.h"
+
+#include <fstream>
+
+#include <TFile.h>
+#include <TTree.h>
+#include <TRegexp.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRead.h"
+#include "MParList.h"
+#include "MStatusDisplay.h"
+
+ClassImp(MRootFileBranch);
+ClassImp(MWriteRootFile);
+
+using namespace std;
+
+const TString MWriteRootFile::gsDefName  = "MWriteRootFile";
+const TString MWriteRootFile::gsDefTitle = "Task which writes a root-output file";
+
+void MWriteRootFile::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    //
+    // Set the Arrays the owner of its entries. This means, that the
+    // destructor of the arrays will delete all its entries.
+    //
+    fBranches.SetOwner();
+    fCopies.SetOwner();
+
+    //
+    // Believing the root user guide, TTree instances are owned by the
+    // directory (file) in which they are. This means we don't have to
+    // care about their destruction.
+    //
+    //fTrees.SetOwner();
+
+    gROOT->GetListOfCleanups()->Add(this); // To remove fDisplay
+    SetBit(kMustCleanup);
+}
+
+// --------------------------------------------------------------------------
+//
+// Try to get the file from gROOT->GetListOfFiles.
+// If it is found fOut is set to it and returned.
+// Otherwise a new file is opened and returned.
+//
+TFile *MWriteRootFile::OpenFile(const char *name, Option_t *option, const char *title, Int_t comp)
+{
+    TFile *file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(name));
+    if (!file)
+    {
+        file = new TFile(name, option, title, comp);
+        if (!file->IsOpen())
+        {
+            delete file;
+            return NULL;
+        }
+
+        file->SetOption(option); // IMPORTANT!
+        ResetBit(kIsNotOwner);
+        return file;
+    }
+
+    fOut = file;
+    fOut->SetBit(kMustCleanup);
+    SetBit(kIsNotOwner);
+
+    *fLog << inf;
+    *fLog << "File '" << name << "' already open... using." << endl;
+    *fLog << "Make sure that you do NOT write to trees which are" << endl;
+    *fLog << "scheduled already by a different MWriteRootFile..." << endl;
+    return fOut;
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It is there to support some root stuff.
+// Don't use it.
+//
+MWriteRootFile::MWriteRootFile() : fOut(NULL)
+{
+    Init();
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this constructor to run in a special mode.
+//
+// In this mode for each input file a new output file is written. This
+// happens in ReInit.
+//
+// comp:        Compression Level (see TFile, TBranch)
+// rule:        Rule to create output file name (see GetNewFileName())
+// overwrite:   Allow newly created file to overwrite old files ("RECREATE")
+// ftitle:      File title stored in the file (see TFile)
+// name, title: Name and title of this object
+//
+MWriteRootFile::MWriteRootFile(const Int_t comp,
+                               const char *rule,
+                               const Option_t *option,
+                               const char *ftitle,
+                               const char *name,
+                               const char *title) : fSplitRule(rule)
+{
+    Init(name, title);
+
+    //
+    // Open a TFile in dummy mode! This is necessary to be able to create
+    // the trees and branches, which are then (in ReInit) moved to
+    // a valid file. (Stupid workaround - but does a good job)
+    //
+    fOut = OpenFile("/dev/null", option, ftitle, comp);
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the name of the root file. You can also give an option ("UPDATE"
+// and "RECREATE" would make sense only) as well as the file title and
+// compression factor. To a more detaild description of the options see
+// TFile.
+//
+// To create a memory based TTree use
+//   fname  = name of TTree
+//   option = "memory"
+// Make sure you do not read from a tree with the same name!
+//
+MWriteRootFile::MWriteRootFile(const char *fname,
+                               const Option_t *option,
+                               const char *ftitle,
+                               const Int_t comp,
+                               const char *name,
+                               const char *title) : fOut(NULL)
+{
+    Init(name, title);
+
+    TString opt(option);
+    opt.ToLower();
+
+    //
+    // Check if we are writing to memory
+    //
+    if (opt.Contains("memory", TString::kIgnoreCase))
+    {
+        fSplitRule = fname;
+        return;
+    }
+
+    //
+    // If no name is given we open the TFile in some kind of dummy mode...
+    //
+    if (!fname)
+    {
+        fOut = new TFile("/dev/null", "READ", ftitle, comp);
+        return;
+    }
+
+    TString str(fname);
+    if (!str.EndsWith(".root", TString::kIgnoreCase))
+        str += ".root";
+
+    //
+    // Open the rootfile
+    //
+    fOut = OpenFile(str, opt, ftitle, comp);
+}
+
+// --------------------------------------------------------------------------
+//
+// Prints some statistics about the file to the screen. And closes the file
+// properly.
+//
+void MWriteRootFile::Close()
+{
+    //
+    // Print some statistics to the looging out.
+    //
+    if (fOut && !TestBit(kIsNotOwner))
+    {
+        Print();
+
+        //
+        // If the file is still open (no error) write the keys. This is necessary
+        // for appearance of the all trees and branches.
+        //
+        if (IsFileOpen())
+            fOut->Write();
+
+        //
+        // Delete the file. This'll also close the file (if open)
+        //
+        delete fOut;
+
+        //
+        // Remark:
+        // - Trees are automatically deleted by the the file
+        //   (unless file.SetDirectory(0) was called)
+        // - Branches are automatically deleted by the tree destructor
+        //
+        *fLog << inf << "Output File closed and object deleted." << endl;
+    }
+
+    fOut = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// call Close()
+//
+MWriteRootFile::~MWriteRootFile()
+{
+    Close();
+}
+
+// --------------------------------------------------------------------------
+//
+// Prints all trees with the actually number of written entries to log-out.
+//
+void MWriteRootFile::Print(Option_t *) const
+{
+    if (!fOut)
+        return;
+
+    *fLog << all << underline << "File: " << GetFileName() << dec << endl;
+
+    if (fTrees.GetEntries()==0)
+    {
+        *fLog << "  No contents." << endl;
+        return;
+    }
+
+    TObject *obj;
+    TIter NextBranch(&fBranches);
+    while ((obj=NextBranch()))
+    {
+        MRootFileBranch *b = (MRootFileBranch*)obj;
+
+        if (!b->GetTree() || b->GetTree()->TestBit(kIsNewTree))
+            continue;
+
+        TBranch *branch = b->GetBranch();
+
+        TString name = b->GetTree()->GetName();
+        name += '.';
+        name += branch->GetName();
+
+        *fLog << " + " << name.Strip(TString::kTrailing, '.') << ": \t" << (ULong_t)branch->GetEntries() << " entries." << endl;
+    }
+
+    TTree *t = NULL;
+    TIter NextTree(&fTrees);
+    while ((t=(TTree*)NextTree()))
+        if (t->TestBit(kIsNewTree))
+            *fLog << " + " << t->GetName() << ": \t" << (ULong_t)t->GetEntries() << " entries." << endl;
+
+    TIter NextKey(fOut->GetList());
+    while ((obj=NextKey()))
+    {
+        if (!obj->InheritsFrom(TTree::Class()))
+            continue;
+
+        if (fTrees.FindObject(obj) && obj->TestBit(kIsNewTree))
+            continue;
+
+        *fLog << " - " << obj->GetName() << ": \t" << (ULong_t)((TTree*)obj)->GetEntries() << " entries." << endl;
+    }
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new Container to list of containers which should be written to the
+// file. Give the name of the container which will identify the container
+// in the parameterlist. tname is the name of the tree to which the
+// container should be written (Remark: one tree can hold more than one
+// container). The default is the same name as the container name.
+// You can slso specify a title for the tree. This is only
+// used the first time this tree in 'mentioned'. As default the title
+// is the name of the tree.
+//
+void MWriteRootFile::AddContainer(const char *cname, const char *tname, Bool_t must)
+{
+    if (!fOut && !tname)
+        tname = fSplitRule;
+
+    TIter Next(&fBranches);
+    TObject *o=0;
+    while ((o=Next()))
+        if (TString(o->GetName())==TString(tname) && TString(o->GetTitle())==TString(cname))
+        {
+            *fLog << warn;
+            *fLog << "WARNING - Container '" << cname << "' in Tree '" << tname << "' already scheduled... ignored." << endl;
+            return;
+        }
+
+    //
+    // create a new entry in the list of branches to write and
+    // add the entry to the list.
+    //
+    MRootFileBranch *entry = new MRootFileBranch(AddSerialNumber(cname), tname, must);
+    fBranches.AddLast(entry);
+
+    if (tname && tname[0])
+        AddToBranchList(Form("%s.%s", (const char*)AddSerialNumber(cname), tname));
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new Container to list of containers which should be written to the
+// file. Give the pointer to the container. tname is the name of the tree to
+// which the container should be written (Remark: one tree can hold more than
+// one container). The default is the same name as the container name.
+// You can slso specify a title for the tree. This is only
+// used the first time this tree in 'mentioned'. As default the title
+// is the name of the tree.
+//
+void MWriteRootFile::AddContainer(MParContainer *cont, const char *tname, Bool_t must)
+{
+    if (!fOut && !tname)
+        tname = fSplitRule;
+
+    TIter Next(&fBranches);
+    TObject *o=0;
+    while ((o=Next()))
+        if (TString(o->GetName())==TString(tname) &&
+            static_cast<MRootFileBranch*>(o)->GetContainer()==cont)
+        {
+            *fLog << warn;
+            *fLog << "WARNING - Container " << cont << " in Tree '" << tname << "' already scheduled... ignored." << endl;
+            return;
+        }
+
+    //
+    // create a new entry in the list of branches to write and
+    // add the entry to the list.
+    //
+    MRootFileBranch *entry = new MRootFileBranch(cont, tname, must);
+    fBranches.AddLast(entry);
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to copy a full tree (or some branches of some trees)
+// completely from one file to another one you can use this
+//
+void MWriteRootFile::AddCopySource(const char *tname, const char *bname)
+{
+    fCopies.Add(new TNamed(tname, bname?bname:"*"));
+    fCopies.Sort();
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new Container to list of containers which should be written to the
+// file. Give the pointer to the container. tname is the name of the tree to
+// which the container should be written (Remark: one tree can hold more than
+// one container). The default is the same name as the container name.
+// You can slso specify a title for the tree. This is only
+// used the first time this tree in 'mentioned'. As default the title
+// is the name of the tree.
+//
+Bool_t MWriteRootFile::GetContainer(MParList *pList)
+{
+    //
+    // loop over all branches which are 'marked' as branches to get written.
+    //
+    MRootFileBranch *entry;
+
+    TIter Next(&fBranches);
+    while ((entry=(MRootFileBranch*)Next()))
+    {
+        //
+        // Get the pointer to the container. If the pointer is NULL it seems,
+        // that the user identified the container by name.
+        //
+        MParContainer *cont = entry->GetContainer();
+        if (!cont)
+        {
+            //
+            // Get the name and try to find a container with this name
+            // in the parameter list.
+            //
+            const char *cname = entry->GetContName();
+            cont = (MParContainer*)pList->FindObject(cname);
+            if (!cont)
+            {
+                //
+                // No corresponding container is found
+                //
+                if (entry->MustHave())
+                {
+                    *fLog << err << "Cannot find parameter container '" << cname << "'." << endl;
+                    return kFALSE;
+                }
+
+                *fLog << inf << "Unnecessary parameter container '" << cname << "' not found..." << endl;
+                delete fBranches.Remove(entry);
+                continue;
+            }
+
+            //
+            // The container is found. Put the pointer into the entry.
+            //
+            entry->SetContainer(cont);
+        }
+
+        //
+        // Get container name, tree name and tree title of this entry.
+        //
+        const char *cname = cont->GetName();
+        const char *tname = entry->GetName();
+        const TString ttitle(Form("Tree containing %s", cont->GetDescriptor().Data()));
+
+        //
+        // if the tree name is NULL this idetifies it to use the default:
+        // the container name.
+        //
+        if (tname[0] == '\0')
+            tname = cname;
+
+        //
+        // Check if the tree is already existing (part of the file or memory)
+        //
+        TTree *tree = fOut ? (TTree*)fOut->Get(tname) : dynamic_cast<TTree*>(gROOT->FindObject(tname));
+        if (!fOut && tree)
+        {
+            if (tree->GetCurrentFile())
+            {
+                *fLog << err;
+                *fLog << "ERROR - You are trying to write data into a memory stored root tree," << endl;
+                *fLog << "        because you either called the default constructor  or  have" << endl;
+                *fLog << "        instantiated MWriteRootFile using the write option 'memory'." << endl;
+                *fLog << "        This  tree   '" << tname << "'   is  already  existing  in" << endl;
+                *fLog << "        memory  (gROOT->FindObject)  and is already belonging  to a" << endl;
+                *fLog << "        file (" << tree->GetCurrentFile()->GetName() << ")." << endl;
+                *fLog << "        This can  - for example -  happen if you are reading from a" << endl;
+                *fLog << "        tree with the same name.  The easiest solution in this case" << endl;
+                *fLog << "        is to change the name of the tree you want to write to." << endl;
+                *fLog << endl;
+                return kFALSE;
+            }
+            *fLog << inf << "Tree '" << tname << "' found already in Memory... using." << endl;
+        }
+
+        if (!tree)
+        {
+            //
+            // if the tree doesn't exist create a new tree. Use the tree
+            // name as title if title is NULL.
+            // And add the tree to the list of trees
+            //
+            TDirectory *save = gDirectory;
+            if (fOut)
+                fOut->cd();
+            else
+                gROOT->cd();
+
+            tree = new TTree(tname, ttitle, fOut ? 99 : 1);
+            fTrees.AddLast(tree);
+
+            //
+            // If the tree does not already exist in the file mark this
+            // tree as a branch created by MWriteRootFile
+            //
+            tree->SetBit(kIsNewTree);
+
+            *fLog << inf << "Tree " << tname << " created in " << gDirectory->GetName() << endl;
+
+            gDirectory = save;
+        }
+
+        //
+        // In case the file is opened as 'UPDATE' the tree may still not
+        // be in the list. Because it neither was created previously,
+        // nor this time, so the corresponding entries is marked as a
+        // single branch to be filled. --> Add it to the list of trees.
+        //
+        if (!fTrees.FindObject(tree))
+            fTrees.AddLast(tree);
+
+        //
+        // Now we have a valid tree. Search the list of trees for this tree
+        // Add a pointer to the entry in the tree list to this branch-entry
+        //
+        entry->SetTree(tree);
+
+        TString branchname(cname);
+        branchname.Append(".");
+
+        //
+        // Try to get the branch from the file. 
+        // If the branch already exists the user specified one branch twice.
+        //
+        TBranch *branch = tree->GetBranch(branchname);
+        if (branch)
+        {
+            *fLog << inf << "Branch '" << cname << "' already existing... updating." << endl;
+            branch->SetAddress(entry->GetAddress());
+
+            if (!fSplitRule.IsNull() && fOut)
+            {
+                *fLog << warn << endl;
+                *fLog << "WARNING: You are updating an existing branch. For this case" << endl;
+                *fLog << "         file-splitting mode  is  not  allowed...  disabled!" << endl;
+                *fLog << endl;
+                fSplitRule = "";
+            }
+        }
+        else
+        {
+            //
+            // Create a new branch in the actual tree. The branch has the name
+            // container name. The type of the container is given by the
+            // ClassName entry in the container. The Address is the address of a
+            // pointer to the container (gotten from the branch entry). As
+            // Basket size we specify a (more or less) common default value.
+            // The containers should be written in Splitlevel=1
+            //
+            *fLog << inf << "Creating Branch '" << cname << "' ";
+            if ((TString)cname!=(TString)cont->ClassName())
+                *fLog << "[" << cont->ClassName() << "] ";
+            *fLog << "in tree " << tree->GetName() << "... " << flush;
+
+            branch = tree->Branch(branchname, cont->ClassName(), entry->GetAddress());
+
+            //
+            // If the branch couldn't be created we have a problem.
+            //
+            if (!branch)
+            {
+                *fLog << endl;
+                *fLog << err << "Unable to create branch '" << cname << "'." << endl;
+                return kFALSE;
+            }
+
+            *fLog << "done." << endl;
+
+            if (!tree->TestBit(kIsNewTree) && !fSplitRule.IsNull())
+            {
+                *fLog << warn << endl;
+                *fLog << "WARNING:   You  have  created  a new branch  in  an existing tree." << endl;
+                *fLog << "     For this case file-splitting mode is not allowed... disabled!" << endl;
+                *fLog << endl;
+                fSplitRule= "";
+            }
+        }
+
+        //
+        // Tell the entry also which branch belongs to it (this is necessary
+        // for branches belonging to already existing tree, UPDATE-mode)
+        //
+        entry->SetBranch(branch);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks all given containers (branch entries) for the write flag.
+// If the write flag is set the corresponding Tree is marked to get filled.
+// All Trees which are marked to be filled are filled with all their
+// branches.
+// In case of a file opened in 'UPDATE' mode, single branches can be
+// filled, too. WARNING - for the moment there is no check whether
+// you filled the correct number of events into the branch, so that
+// each of the other branches in the tree has the correct corresponding
+// number of new entries in the new branch!
+// Be carefull: If only one container (corresponding to a branch) of a tree
+// has the write flag, all containers in this tree are filled!
+//
+Bool_t MWriteRootFile::CheckAndWrite()
+{
+    TObject *obj;
+
+    //
+    // Loop over all branch entries
+    //
+    TIter NextBranch(&fBranches);
+    while ((obj=NextBranch()))
+    {
+        MRootFileBranch *b = (MRootFileBranch*)obj;
+
+        //
+        // Check for the Write flag
+        //
+        if (!b->GetContainer()->IsReadyToSave())
+            continue;
+
+        //
+        // If the write flag of the branch entry is set, set the write flag of
+        // the corresponding tree entry.
+        //
+        if (b->GetTree()->TestBit(kIsNewTree))
+            b->GetTree()->SetBit(kFillTree);
+        else
+        {
+            if (!b->GetBranch()->Fill())
+            {
+                *fLog << err << "ERROR - Zero bytes written to branch '" << b->GetBranch()->GetName() << "'... abort." << endl;
+                return kFALSE;
+            }
+        }
+    }
+
+    //
+    // Loop over all tree entries
+    //
+    const Int_t n = fTrees.GetEntriesFast();
+
+    for (int idx=0; idx<n; idx++)
+    {
+        TTree *t = (TTree*)fTrees[idx];
+
+        //
+        // Check the write flag of the tree
+        //
+        if (!t->TestBit(kFillTree))
+            continue;
+
+        //
+        // If the write flag is set, fill the tree (with the corresponding
+        // branches/containers), delete the write flag and increase the number
+        // of written/filled entries.
+        //
+        t->ResetBit(kFillTree);
+
+        if (!t->Fill())
+        {
+            *fLog << err << "ERROR - Zero bytes written to tree '" << t->GetName() << "'... abort." << endl;
+            return kFALSE;
+        }
+    }
+
+    //
+    // If we are writing into memory we don't split into seperate files
+    //
+    if (!fOut || TestBit(kIsNotOwner))
+        return kTRUE;
+
+    //
+    // For more information see TTree:ChangeFile()
+    //
+    TTree *t0 = (TTree*)fTrees[0];
+    if (!t0 || fOut==t0->GetCurrentFile())
+        return kTRUE;
+
+    *fLog << warn << endl;
+    *fLog << "WARNING - MWriteRootFile:   Root's  TTree/TFile   has  opened   a  new  file" << endl;
+    *fLog << "  automatically.  You can change this behaviour using TTree::SetMaxTreeSize." << endl;
+    *fLog << "  You won't be able to read splitted  files  correctly with MReadMarsFile if" << endl;
+    *fLog << "  they have more than one entry in 'RunHeaders' or you try to read more than" << endl;
+    *fLog << "  one of such sequences at once." << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open a new file with the ame fname. Move all trees and branches from the
+// old file to the new file.
+//
+Bool_t MWriteRootFile::ChangeFile(const char *fname)
+{
+    const Int_t   compr = fOut ? fOut->GetCompressionLevel() : 0;
+    const TString title = fOut ? fOut->GetTitle()            : "";
+    const TString opt   = fOut ? fOut->GetOption()           : "";
+
+    // Open new file with old setup
+    TFile *newfile = OpenFile(fname, opt, title, compr);
+    if (newfile && newfile==fOut)
+    {
+        *fLog << inf << "Found open file " << fname << "... using." << endl;
+        return kTRUE;
+    }
+
+    if (!newfile)
+    {
+        *fLog << err << "ERROR - Cannot open new file " << fname << endl;
+         return kFALSE;
+    }
+
+    *fLog << inf << "Open new file " << fname << " (Title=" << title << ", Option=" << opt << ", Compression=" << compr << ")" << endl;
+
+    // Print statistics of old file
+    const TString n = GetFileName();
+    if (!n.IsNull() && n!=TString("/dev/null"))
+        Print();
+
+    if (fOut->IsOpen())
+        fOut->Write();
+
+    // Move all trees from the old file to the new file
+    TObject *obj=0;
+    while ((obj = fOut->GetList()->First()))
+    {
+        // Remove obj from old file (otherwise deleting
+        // the old file will delete the objs)
+        fOut->GetList()->Remove(obj);
+
+        // If this is not a tree do nothing.
+        if (!obj->InheritsFrom(TTree::Class()))
+            continue;
+
+        // process all trees in the old file
+        TTree *t = (TTree*)obj;
+
+        // reset and move to new file (this is done implicitly for all branches)
+        t->Reset();
+        t->SetDirectory(newfile);
+    }
+
+    // Close/delete the old file (keys already written above)
+    delete fOut;
+
+    // Replace current with new file
+    fOut = newfile;
+
+    // Change current directory to new file
+    gFile = fOut;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// A rule looks like:
+//   "outputpath{s/source/destination}"
+//
+// outpath:                the output path into which the files are written
+// {s/source/destination}  a substitution rule for the filename
+//   while source can be a regular expression everything which matches this
+//   regular expression (see TRegexp) will be replaced by destination.
+//   Warning: The algorithm is recursive you may create endless loops!
+//
+// Example:
+//   inputfile: /data/MAGIC/Period016/rootdata/20040621_23210_D_Mkn421_E.root
+//   rule:      /outpath/{s/_D_/_Y_}
+//   outfile:   /outpath/20040621_23210_Y_Mkn421_E.root
+//
+// If you need more difficult rules please send me an eMail...
+//
+TString MWriteRootFile::GetNewFileName(const char *inname) const
+{
+    // Remove the path from the filename
+    TString fname(inname);
+    if (fname.Last('/')>=0)
+        fname.Remove(0, fname.Last('/')+1);
+
+    // Make a copy of the rule
+    TString rule(fSplitRule);
+
+    // [characte class], ^ do not, [^{}] do not match { and }, [^{}]+ match at least not one { or }
+    const TRegexp subst0("{s/[^{}/]+/[^{}/]+}");
+
+    TString path;
+    Bool_t first = kTRUE;
+
+    Ssiz_t idx=0;
+    while (1)
+    {
+        // Find a substitution exprsssion
+        Ssiz_t len = 0;
+        idx = subst0.Index(rule, &len);
+        if (idx<0)
+            break;
+
+        // If the first substitution expression is found in the rule
+        // determin the path from everything before
+        if (first)
+        {
+            path=rule(0, idx);
+            first = kFALSE;
+        }
+
+        // Extract a substitution expression
+        TString expr = rule(idx, len);
+        rule.Remove(idx, len);
+
+        expr.Remove(0,3);
+        expr.Remove(expr.Length()-1);
+
+        // In all cases this is well defined (see Regexp)
+        const Ssiz_t pos = expr.First('/');
+
+        // Split substitution rule into source and destination
+        const TString src  = expr(0, pos);
+        const TString dest = expr(pos+1, expr.Length());
+
+        // Replace source by destination
+        const TRegexp regexp(src);
+        while (1)
+        {
+            idx = regexp.Index(fname, &len);
+            if (idx<0)
+                break;
+
+            fname.Replace(idx, len, dest);
+        }
+    }
+
+    // Check if we have a trailing '/'
+    if (!path.IsNull() && path[path.Length()-1]!='/')
+        path.Append("/");
+
+    //inname.Prepend(path);
+
+    // Create full qualified pathname
+    path += fname;
+    return path;
+}
+
+// --------------------------------------------------------------------------
+//
+// Writes a copy of the TTree t to the currently open file using
+// TTree::CloneTree()
+//
+void MWriteRootFile::CopyTree(TTree &t) const
+{
+    TString out = "Copy of tree ";
+    out += t.GetName();
+    out += " in progress...";
+
+    if (fDisplay)
+        fDisplay->SetStatusLine2(out);
+
+    *fLog << inf << out << flush;
+
+    TTree *clone=t.CloneTree();
+    clone->Write();
+    delete clone;
+
+    *fLog << "done." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Make all copies requested from the currently open file into the new
+// file.
+//
+Bool_t MWriteRootFile::MakeCopies(const char *fname) const
+{
+    if (fCopies.GetEntries()==0)
+        return kTRUE;
+
+    TFile *file = dynamic_cast<TFile*>(gROOT->GetListOfFiles()->FindObject(fname));
+    if (!file)
+    {
+        *fLog << err << "ERROR - MakeCopies: File " << fname << " not found in gROOT->GetListOfFiles()... abort." << endl;
+        return kFALSE;
+    }
+
+    TIter Next(&fCopies);
+    TObject *o=0;
+    TTree   *t=0;
+
+    fOut->cd();
+    while ((o=Next()))
+    {
+        TTree *gettree = dynamic_cast<TTree*>(file->Get(o->GetName()));
+        if (!gettree)
+        {
+            *fLog << err << "ERROR - MakeCopies: Tree " << o->GetName() << " not found in file " << fname << "... abort." << endl;
+            return kFALSE;
+        }
+
+        gettree->SetBranchStatus(o->GetTitle(), 1);
+
+        // First Execution
+        if (t==gettree)
+            continue;
+
+        // Check if its the first call
+        if (t)
+            CopyTree(*t);
+        t = gettree;
+    }
+
+    if (t)
+        CopyTree(*t);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit. If file splitting is not allowed call MWriteFile::ReInit.
+//
+// In other cases get MRead from the TaskList (splitting is switched of if
+// this is impossible).
+//
+// Convert the input- into a new output file-name.
+//
+// Open a new file, change all trees to the new file (calling ChangeFile()),
+// and close the old one.
+//
+// Call MWriteFile::ReInit()
+//
+Bool_t MWriteRootFile::ReInit(MParList *pList)
+{
+    MRead *read = (MRead*)pList->FindTask("MRead");
+    if (fSplitRule.IsNull() && fCopies.GetEntries()>0 && fOut)
+    {
+        if (!read)
+        {
+            *fLog << err;
+            *fLog << "ERROR: No Task 'MRead' found in the tasklist.  This task is" << endl;
+            *fLog << "  necessary to  get the filename.  Without  a filename file" << endl;
+            *fLog << "  AddCopySource cannot be used... abort." << endl;
+            *fLog << endl;
+            return kFALSE;
+        }
+        if (!MakeCopies(read->GetFullFileName()))
+            return kFALSE;
+
+    }
+
+    if (fSplitRule.IsNull() || !(fOut || TestBit(kIsNotOwner)))
+        return MWriteFile::ReInit(pList);
+
+    if (!read)
+    {
+        *fLog << warn;
+        *fLog << "WARNING: No Task 'MRead' found in the tasklist.  This task is" << endl;
+        *fLog << "  necessary  to  get  the filename.  Without  a filename file" << endl;
+        *fLog << "  file splitting is not allowed... disabled!" << endl;
+        *fLog << endl;
+        fSplitRule = "";
+        return kTRUE;
+    }
+
+
+    const TString oldname = read->GetFullFileName();
+    const TString newname = GetNewFileName(oldname);
+    if (!ChangeFile(newname))
+        return kFALSE;
+
+    if (!MakeCopies(oldname))
+        return kFALSE;
+
+    return MWriteFile::ReInit(pList);
+}
+
+// --------------------------------------------------------------------------
+//
+// return open state of the root file. If the file is 'memory' kTRUE is
+// returned.
+//
+Bool_t MWriteRootFile::IsFileOpen() const
+{
+    if (!fOut)
+        return kTRUE;
+
+    const char *n = fOut->GetName();
+    return n==0 || *n==0 ? kTRUE : fOut->IsOpen();
+}
+
+// --------------------------------------------------------------------------
+//
+// return name of the root-file. If the file is "memory" "<memory>" is
+// returned.
+//
+const char *MWriteRootFile::GetFileName() const
+{
+    if (!fOut)
+        return "<memory>";
+
+    const char *n = fOut->GetName();
+    return n==0 || *n==0 ? "<dummy>" : n;
+}
+
+// --------------------------------------------------------------------------
+//
+// cd into file. See TFile::cd(). If the file is "memory" kTRUE is returned.
+//
+Bool_t MWriteRootFile::cd(const char *path)
+{
+    return fOut ? fOut->cd(path) : kTRUE;
+}
+
+void MWriteRootFile::RecursiveRemove(TObject *obj)
+{
+    if (obj==fOut)
+        fOut=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MWriteRootFile::StreamPrimitive(ofstream &out) const
+{
+    out << "   MWriteRootFile " << GetUniqueName();
+    if (fOut)
+    {
+        out << "(\"";
+        out << fOut->GetName() << "\", \"";
+        out << fOut->GetOption() << "\", \"";
+        out << fOut->GetTitle() << "\", ";
+        out << fOut->GetCompressionLevel();
+        out << ")";
+    }
+    out << ";" << endl;
+
+    if (fName!=gsDefName)
+        out << "   " << GetUniqueName() << ".SetName(\"" << fName << "\");" << endl;
+    if (fTitle!=gsDefTitle)
+        out << "   " << GetUniqueName() << ".SetTitle(\"" << fTitle << "\");" << endl;
+
+    MRootFileBranch *entry;
+    TIter Next(&fBranches);
+    while ((entry=(MRootFileBranch*)Next()))
+    {
+        out << "   " << GetUniqueName() << ".AddContainer(";
+
+        if  (entry->GetContainer())
+        {
+            entry->GetContainer()->SavePrimitive(out);
+            out << "&" << entry->GetContainer()->GetUniqueName();
+        }
+        else
+            out << "\"" << entry->GetContName() << "\"";
+
+        out << ", \"" << entry->GetName() << "\"";
+        if (!entry->MustHave())
+            out << ", kFALSE";
+
+        out <<");" << endl;
+    }
+}
+
Index: /tags/Mars-V0.9/mfileio/MWriteRootFile.h
===================================================================
--- /tags/Mars-V0.9/mfileio/MWriteRootFile.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/MWriteRootFile.h	(revision 9772)
@@ -0,0 +1,143 @@
+#ifndef MARS_MWriteRootFile
+#define MARS_MWriteRootFile
+
+#ifndef MARS_MWriteFile
+#include "MWriteFile.h"
+#endif
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class TFile;
+class TTree;
+class TBranch;
+
+class MRootFileBranch : public TNamed
+{
+private:
+    TTree         *fTree;       //!
+    TBranch       *fBranch;     //!
+
+    MParContainer *fContainer;
+
+    Bool_t         fMust;
+
+    void Init(const char *name, Bool_t must)
+    {
+        SetName(name?name:"");
+        fMust = must;
+    }
+
+public:
+    MRootFileBranch() : fTree(NULL), fBranch(NULL), fContainer(NULL), fMust(0)
+    {
+        Init(NULL, kFALSE);
+        fTitle = "";
+    }
+
+    MRootFileBranch(const char *cname, const char *tname=NULL, Bool_t must=kFALSE)
+        : fTree(NULL), fBranch(NULL), fContainer(NULL), fMust(0)
+    {
+        Init(tname, must);
+        fTitle = cname;
+    }
+
+    MRootFileBranch(MParContainer *cont, const char *tname=NULL, Bool_t must=kFALSE)
+        : fTree(NULL), fBranch(NULL), fMust(0)
+    {
+        Init(tname, must);
+        fTitle = "";
+        fContainer = cont;
+    }
+
+    TTree         *GetTree() const      { return fTree; }
+    MParContainer *GetContainer() const { return fContainer; }
+    void          *GetAddress()         { return &fContainer; }
+    TBranch       *GetBranch() const    { return fBranch; }
+    const char    *GetContName() const  { return fTitle; }
+    Bool_t         MustHave() const     { return fMust; }
+
+    void SetContainer(MParContainer *cont) { fContainer = cont; }
+    void SetTree(TTree *tree)              { fTree = tree; }
+    void SetBranch(TBranch *branch)        { fBranch = branch; }
+
+    ClassDef(MRootFileBranch, 1) // Storage container for MWriteRootFile to store TBranch informations
+};
+
+class MWriteRootFile : public MWriteFile
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    TFile *fOut;             // Current file
+
+    TObjArray fBranches;     // List of Branch setup (MRootFileBranch)
+    TObjArray fTrees;        //! List of trees
+    TObjArray fCopies;       // Branches and tree to copy
+
+    TString fSplitRule;      // file splitting allowed if rule existing (done in ReInit)
+
+    enum {
+        kIsNotOwner = BIT(14), // MWriteRootFile is not owner of fOut
+        kFillTree   = BIT(14),
+        // Be carefull these bits are already in use!
+        // TBranch::kAutoDelete = BIT(15)
+        // TBranchElement::kDeleteObject = BIT(16)
+        kIsNewTree  = BIT(17)
+    };
+
+    // File handling
+    void    Close();
+    TString GetNewFileName(const char *inname) const;
+    Bool_t  ChangeFile(const char *fname);
+    TFile  *OpenFile(const char *name, Option_t *option, const char *title, Int_t comp);
+    void    CopyTree(TTree &t) const;
+    Bool_t  MakeCopies(const char *oldname) const;
+
+    // MWrite
+    Bool_t      CheckAndWrite();
+    Bool_t      IsFileOpen() const;
+    Bool_t      GetContainer(MParList *pList);
+    const char *GetFileName() const;
+
+    // MTask
+    Bool_t ReInit(MParList *pList);
+    void   StreamPrimitive(ofstream &out) const;
+
+    // Constructor
+    void Init(const char *name=0, const char *title=0);
+
+public:
+    MWriteRootFile();
+    MWriteRootFile(const Int_t comp,
+                   const char *rule,
+                   const Option_t *opt="RECREATE",
+                   const char *ftitle="Untitled",
+                   const char *name=NULL,
+                   const char *title=NULL);
+    MWriteRootFile(const char *fname,
+                   const Option_t *opt="RECREATE",
+                   const char *ftitle="Untitled",
+                   const Int_t comp=2,
+                   const char *name=NULL,
+                   const char *title=NULL);
+    ~MWriteRootFile();
+
+    void AddContainer(const char *cname,   const char *tname=NULL, Bool_t must=kTRUE);
+    void AddContainer(MParContainer *cont, const char *tname=NULL, Bool_t must=kTRUE);
+    void AddCopySource(const char *tname, const char *bname=NULL);
+
+    void Print(Option_t *t=NULL) const;
+
+    Bool_t cd(const char *path=0);
+
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MWriteRootFile, 1)	// Task to write data into a root file
+};
+
+#endif
Index: /tags/Mars-V0.9/mfileio/Makefile
===================================================================
--- /tags/Mars-V0.9/mfileio/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/Makefile	(revision 9772)
@@ -0,0 +1,39 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mraw -I../mmc -I../mreflector -I../mgui \
+	   -I../mdata -I../mbadpixels
+#mraw:       MRawRunHeader (MReadMaraFile)
+#mmc:        MMcRunHeader  (MReadMarsFile)
+#mreflector: MRfl*         (MReadRflFile)
+#mgui:       MCamEvent     (MReadRflFile)
+#mdata:      MData*        (MWriteAsciiFile)
+
+CINT     = FileIO
+
+SRCFILES = MRead.cc \
+           MChain.cc \
+	   MReadTree.cc \
+           MReadReports.cc \
+           MReadMarsFile.cc \
+           MReadRflFile.cc \
+           MWriteFile.cc \
+           MWriteAsciiFile.cc \
+           MWriteRootFile.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mfileio/defines.h
===================================================================
--- /tags/Mars-V0.9/mfileio/defines.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/defines.h	(revision 9772)
@@ -0,0 +1,788 @@
+/******************************************************************/
+/*              GGG   AAA   M   M M   M  AAA   SSS                */
+/*             G   G A   A  MM MM MM MM A   A S   S               */
+/*             G     A   A  M M M M M M A   A  SS                 */
+/*             G  GG AAAAA  M   M M   M AAAAA   SS                */
+/*             G   G A   A  M   M M   M A   A S   S               */
+/*              GGG  A   A  M   M M   M A   A  SSS                */
+/*       Gamma Astronomer's Munich Madrid Analysis Suite          */
+/*   An Atmospheric Cherenkov Telescope Data Analysis Software    */
+/*  MPI f"ur Physik, M"unchen & Universidad Complutense, Madrid   */
+/******************************************************************/
+
+/******************************************************************/
+/* This File belongs to the programs                              */
+/*                                                                */
+/*  P R E P R O C E S S O R   and   I M A G E R                   */
+/*                                                                */
+/* Purpose: provide the structure definitions common to both      */
+/*          programs, especially the output structures of the     */
+/*          preprocessor                                          */ 
+/*                                                                */
+/******************************************************************/
+
+#ifndef _defines_h_
+#define _defines_h_ "__defines_h__"
+
+#define cIDSTRING(x,y,z) "@(#) GAMMAS "#x" version "#y", date "#z"."
+#define CAT(x,y) #x#y
+#define XCAT(x,y) CAT(x,y)
+
+#define Boolean int
+
+#ifndef TRUE
+#define TRUE 1
+#endif
+#ifndef FALSE
+#define FALSE 0
+#endif
+
+/*************** DEFINES ******************************************/
+
+/* General defines */
+
+#define cHELLOSTRING(x,y) "This is preproc.\nVersion "#x", date "#y"\n\n"
+#define PREPROCVERSIONSTRING(x) "V"#x  
+
+#define dDEG_PER_HOUR 15.
+#define dRAD_PER_DEG 0.0174532925199 /* = 3.14159265359/180. */
+#define dSECS_PER_DAY 86400.
+#define SQUARE(x) ((x) * (x))
+
+/* defines for histograms and ntuple creation */
+
+#define HMAX 2000000 /* memory reserved for pawc common block 
+		     * used by hbook */
+#define DAB -999 /* if a histogramm parameter is to be Defined 
+		  * At Booking enter -999 */
+#define iADCHISTID 1000 /* id of the first histogram for ADC 
+			 * count spectra */
+#define cADCHISTTITLE "Pixel signals before calibration;pixel \
+number;ADC counts"
+#define iADCHIST_BINS 127 /* This is a good guess. bparametersok()
+			   * will look at parameters for the bins 
+			   * in X direction and adjust the other,
+			   * similar histograms acoordingly. */
+#define fADCHIST_LOLIMX 0.5
+#define fADCHIST_HILIMX 127.5 /* For both of them, see above. */
+
+
+
+#define iPHEHISTID 2000 /* id of the first histogram for photo 
+			 *electron spectra */
+#define cPHEHISTTITLE "Pixel signals after calibration;pixel \
+number;photo electrons"
+#define iPHEHIST_BINS 127 /* This is a good guess. bparametersok()
+			   * will look at parameters for the bins 
+			   * in X direction and adjust the other,
+			   * similar histograms acoordingly. */
+#define fPHEHIST_LOLIMX 0.5
+#define fPHEHIST_HILIMX 127.5 /* For both of them, see above. */
+
+#define iPEDONHISTID 12000 /* id of the first histogram for the 
+			    *signals taken in pedestalruns for ON */
+#define iPEDOFHISTID 11000 /* id of the first histogram for the 
+			    *signals taken in pedestalruns for OF */
+#define cPEDONHISTTITLE "Pixel signals from ON pedestal runs;\
+pixel number;ADC Counts"
+#define cPEDOFHISTTITLE "Pixel signals from OF pedestal runs;\
+pixel number;ADC Counts"
+#define iPEDONMEANHISTID 14000 /* id of the first histogram for the 
+				*signals taken in pedestalruns for ON */
+#define iPEDOFMEANHISTID 13000 /* id of the first histogram for the 
+				*signals taken in pedestalruns for OF */
+#define cPEDONMEANHISTTITLE "Pedestal Means from ON pedestal runs;\
+Event Index;ADC Counts"
+#define cPEDOFMEANHISTTITLE "Pedestal Means from OF pedestal runs;\
+Event Index;ADC Counts"
+#define iPEDONJITTHISTID 16000 /* id of the first histogram for the 
+				*signals taken in pedestalruns for ON */
+#define iPEDOFJITTHISTID 15000 /* id of the first histogram for the 
+				*signals taken in pedestalruns for OF */
+#define cPEDONJITTHISTTITLE "Deviation from Pedestal Means from \
+ON pedestal runs;Pixel Number;ADC Counts"
+#define cPEDOFJITTHISTTITLE "Deviation from Pedestal Means from \
+OF pedestal runs;Pixel Number;ADC Counts"
+#define iCALONHISTID 18000 /* id of the first histogram for the 
+			    *signals taken in laserruns for ON */
+#define iCALOFHISTID 17000 /* id of the first histogram for the 
+			    *signals taken in plaserruns for OF */
+#define cCALONHISTTITLE "Pixel signals from ON laser runs;\
+pixel number;ADC Counts"
+#define cCALOFHISTTITLE "Pixel signals from OF laser runs;\
+Pixel Number;ADC Counts"
+#define iCALONMEANHISTID 20000 /* id of the first histogram for the 
+				*signals taken in laserruns for ON */
+#define iCALOFMEANHISTID 19000 /* id of the first histogram for the 
+			    *signals taken in plaserruns for OF */
+#define cCALONMEANHISTTITLE "Laser Means from ON laser runs;\
+Event Index;ADC Counts"
+#define cCALOFMEANHISTTITLE "Laser Means from OF laser runs;\
+Event Index;ADC Counts"
+#define iCALONJITTHISTID 22000 /* id of the first histogram for the 
+				*signals taken in laserruns for ON */
+#define iCALOFJITTHISTID 21000 /* id of the first histogram for the 
+			    *signals taken in plaserruns for OF */
+#define cCALONJITTHISTTITLE "Deviation from Laser Means from \
+ON laser runs;Pixel Number;ADC counts"
+#define cCALOFJITTHISTTITLE "Deviation from Laser Means from \
+OF laser runs;Pixel Number;ADC counts"
+#define iZENONHISTID 200 /* id of the histogram for the zenith 
+			  * angle distribution before filter ON */
+#define iZENOFHISTID 100 /* id of the histogram for the zenith 
+			  * angle distribution before filter OF */
+#define cZENONHISTTITLE "zenith angle distribution before filter \
+ON;zenith angle;number of events ON"
+#define cZENOFHISTTITLE "zenith angle distribution before filter \
+OFF;zenith angle;number of events OFF"
+#define iZENHISTNUMBINS 90
+#define fZENHISTLOLIM 0.
+#define fZENHISTHILIM 90.
+/* defines for noise pickup correction of pedestal (added D.K.)
+ */
+#define iCORRPEDHISTID 400 /* id of histogram for pedestal correction values
+			      (noise pickup) */
+#define cCORRPEDHISTTIT "Pickup Correction;ADC counts;Nr. of Events"
+#define iCPEDFWHMHISTID 410 /* id of the histogram for FWHM of pedestal
+			       correction values (noise pickup) */
+#define cCPEDFWHMHISTTIT "FWHM of Pickup Correction;ADC counts;Nr. of Events"
+#define fMIN_CORRPEDHIST -20.
+#define fMAX_CORRPEDHIST 20.
+#define iCORRPEDHIST_BINS 80
+#define fMIN_CPEDFWHMHIST 0.
+#define fMAX_CPEDFWHMHIST 20
+#define iCPEDFWHMHIST_BINS 40
+#define iBIAS 50             /* is used to make the pedestals peak at 'iBIAS' */
+#define dPEDCORRSIZELIMIT 500. /* maximum event SIZE for which noise-pickup is
+				  corrected */
+/* end: defines for noise pickup correction of pedestal
+ */
+
+/* MKA May 8 2000: Version > 0.4 */
+#define cHISTOFILENAME ".hbook" 
+#define cCALNTFILENAME ".nt.hbook"
+#define cOUTDIRNAME "preproc_out/"
+#define cPROJECTNAME "check"
+#define iCALIBNTUPLE_ID  3
+#define iRECL 1024 /* the record length of the calibration ntuple */ 
+
+#define iPARTNERSEARCHDEPTH 20 /* Default search depth if not specified. */
+/* various parameters */
+
+#ifdef ALPHA
+#define iMAXNUMLASERRUNS 4 /* maximum number of laser runs 
+			    * recorded in one file 
+			    * (90 degrees * 4 minutes/degree / 20 minutes) */
+#endif
+#ifdef LINUX
+#define iMAXNUMLASERRUNS 6 /* maximum number of laser runs 
+			    * recorded in one file 
+			    * (90 degrees * 4 minutes/degree / 20 minutes) */
+#endif
+#define iMAXNUMLASEREVENTS 250 /* maximum number of laser shots
+				* recorded for one laser run */
+#ifdef ALPHA
+#define iMAXNUMPEDRUNS 4 /* maximum number of pedestal runs 
+			   * recorded in one file */
+#endif
+#ifdef LINUX
+#define iMAXNUMPEDRUNS 26 /* maximum number of pedestal runs 
+			   * recorded in one file */
+#endif
+#define iMAXNUMPEDEVENTS 500 /* maximum number of random triggers 
+			      * recorded for one pedestal run */
+#define iMAXNUMRUNEVENTS 40000 /* maximum number of events recorded 
+				* in one run data file */
+#define iNUMRMSFITXBINS 100 /* Bins in the (vector)histogram for the 
+			     * fit of the Pedestal RMS */
+#define iRMSFITXSTRETCH 50 /* strectch of the (vector)histogram for the 
+			     * fit of the Pedestal RMS */
+/* Attention: for iNUMRMSFITXBINS and iRMSFITXSTRETCH the following
+ * requirement must be fulfilled:
+ * A width of 1 must be achieveble as an integer multiple of the
+ * binwidth, i.e. 5 or 6 times (iRMSFITXSTRETCH/iNUMRMSFITXBINS) must
+ * make up 1. */
+
+#define iRMSFITXOFFSET 2 /* half a bin offset to the left: Start a bin 
+			 * with center at 0 at 1./2. binwidth earlier */
+
+#define iMAXFILENAMELENGTH 400
+/* general limit on the length of filename strings (including path) */ 
+#define iMAXNUMDIRENTRIES 1028 /* MKA: Nonsens to limit this; we 
+				* rewrite this in the future. 
+				* Make a chained list and allocate
+				* memory for it dynamically. Free
+				* this memory afterwards. 
+				* Put on to-do-list Nov 6 1999 */
+/* the maximum number of filenames expected in a directory to 
+ * be read by ireaddir() */
+#define cDIRFILENAME "preproc.dir" 
+/* intermediate file used by ireaddir() */
+#define iMAXNUMCALFILEOFFSET 400 /* That is the number of Runs, which 
+				  * is searched back to find a TelCal 
+				  * file for analysis. */
+
+#define iMAXNUMPEDFILEOFFSET 400 /* That is the number of Runs, which 
+				  * is searched back to find a TelPed 
+				  * file for analysis. */ 
+
+#define iMAXNUMTELLOGFILEOFFSET 400 /* That is the number of Runs, which 
+				     * is searched back to find a TelLog 
+				     * file for analysis. */
+
+/* keywords, numbers of arguments, values and ranges of values 
+   which define the syntax in the parameters file
+   
+   in order to introduce a new input parameter, you have to 
+   a) increase iNUMKEYWORDS
+   b) #define the keyword (cKEYWORDXX), the format for the 
+      arguments (cKEYWORDXXARG)
+      the number of arguments (iKEYWORDXXNUMARG), 
+      the minimum and maximum value 
+      (iMIN..., iMAX...) for numerical arguments
+   c) for enum-type arguments look at keywords 10 or 11 to see 
+      what to #define
+      (iKEYWORDXXARGYNUMVAL = the number of values the arguments 
+      no. Y of keyword no. XX can take, 
+      cKEYWORDXXARGYVALS  = enumeration of the different values 
+      (strings) the argument can have
+   d) put entries into the initialization of the arrays ckeyword, 
+      ckeywordarg, ikeywordnumarg, fargvalmin, fargvalmax, and 
+      for enum-type arguments declare a new array keywordXXvalues 
+      as for keywords 10 and 11
+   e) include the new parameter into the structure inputpars, 
+      and, if you wish to, in outputpars also.
+   f) add the corresponding case to the switch(k) statement in main()
+   g) modify bparametersok(), bprintinputpars() and 
+      vsetinputparsunfilled()
+   h) program the transfer of the parameter from inputpars to 
+      outputpars if necessary
+      .... to be continued  */
+
+
+#define iNUMKEYWORDS 46  /* the number of different kewords 
+			  * defined for use in the
+                          * parameters file */
+
+#define cKEYWORD01                "iTELESCOPE"
+/* keyword no. 1, this keyword must have this number, don't change it */
+#define cKEYWORD01ARG             "%d"
+#define iKEYWORD01NUMARG 1 /* number of arguments */
+#define iMINTELESCOPEID 1 /* minimum value */
+#define iMAXTELESCOPEID 2 /* maximum value */
+
+#define cKEYWORD02                "iRUNNUM"
+/* keyword no. 2, this keyword must have this number, don't change it */
+#define cKEYWORD02ARG             "%d"
+#define iKEYWORD02NUMARG 1
+#define iMINRUNNUM 0 /* minimum value */
+#define iMAXRUNNUM 99999 /* maximum value */
+
+#define cKEYWORD03                "inumpixels"
+/* keyword no. 3 */
+#define cKEYWORD03ARG             "%d"
+#define iKEYWORD03NUMARG 1
+#define iMINNUMPIX 37 /* minimum value for the number of camera 
+		       * pixels (excl. muon shield) */
+/* #define iMAXNUMPIX ..  maximum value defined in structures.h */
+
+#define cKEYWORD04                "fpixdiameter_deg"
+/* keyword no. 4 */
+#define cKEYWORD04ARG             "%f"
+#define iKEYWORD04NUMARG 1
+#define fMINPIXDIA_DEG 0.1 /* minimum value */
+#define fMAXPIXDIA_DEG 1.0 /* maximum value */
+
+#define cKEYWORD05                "ise1zeropos"
+/* keyword no. 5 */
+#define cKEYWORD05ARG             "%d"
+#define iKEYWORD05NUMARG 1
+#define iMINSE1POS 0 /* minimum value */
+#define iMAXSE1POS 50000 /* maximum value */
+
+#define cKEYWORD06                "ise2zeropos"
+/* keyword no. 6 */
+#define cKEYWORD06ARG             "%d"
+#define iKEYWORD06NUMARG 1
+#define iMINSE2POS 0 /* minimum value */
+#define iMAXSE2POS 50000 /* maximum value */
+
+#define cKEYWORD07               "idontusepix"
+/* keyword no. 7 */
+#define cKEYWORD07ARG             "%d"
+#define iKEYWORD07NUMARG 1 
+#define iMINPIXNUM 1 /* in the parameters file counting of the 
+		      * pixels starts at 1 */
+/* maximum value of this parameter is iMAXNUMPIX */
+/* negative parameters in the range -iMINPIXNUM to -iMAXNUMPIX 
+ * are also allowed: */
+/* they switch the pixel back on */
+
+#define cKEYWORD08               "isum_thresh_phot"
+/* keyword no. 8 */
+#define cKEYWORD08ARG             "%d"
+#define iKEYWORD08NUMARG 1
+#define iMINSUMTHRESH_PHOT 0 /* minimum value */
+#define iMAXSUMTHRESH_PHOT 65536 /* maximum value */
+
+#define cKEYWORD09              "i2out_thresh_phot"
+/* keyword no. 9 */
+#define cKEYWORD09ARG             "%d"
+#define iKEYWORD09NUMARG 1
+#define iMIN2OUTTHRESH_PHOT 0 /* minimum value */
+#define iMAX2OUTTHRESH_PHOT 65536 /* maximum value */
+
+#define cKEYWORD10               "usecalfile"
+/* keyword no. 10 */
+#define cKEYWORD10ARG             "%s %d %d"
+#define iKEYWORD10NUMARG 3 /* first arg: search direction, 
+			    * second arg: end of search or
+			    * search depth in case of 
+			    * pingpong method */
+#define iKEYWORD10ARG1NUMVAL 5
+#define cKEYWORD10ARG1VALS "match", "before", "after", "pingpong", "none"
+/* minimum and maximum value of the second argument are 
+ * identical with iMINRUNNUM and iMAXRUNNUM */
+
+#define cKEYWORD11               "usepedfile"
+/* keyword no. 11 */
+#define cKEYWORD11ARG             "%s %d %d"
+#define iKEYWORD11NUMARG 3 /* first arg: search direction,
+			    * second arg: end of search or
+			    * search depth in case of 
+			    * pingpong method */
+#define iKEYWORD11ARG1NUMVAL 5
+#define cKEYWORD11ARG1VALS "match", "before", "after", "pingpong", "none"
+/* minimum and maximum value of the second argument are 
+ * identical with iMINRUNNUM and iMAXRUNNUM */
+
+#define cKEYWORD12                "inummuonpixels"
+/* keyword no. 12 */
+#define cKEYWORD12ARG             "%d"
+#define iKEYWORD12NUMARG 1
+#define iMINNUMMUONPIX 0 /* minimum value */
+/* #define iMAXNUMMUONPIX ..  maximum value defined in structures.h */
+
+#define cKEYWORD13                "inumcointdcs"
+/* keyword no. 13 */
+#define cKEYWORD13ARG             "%d"
+#define iKEYWORD13NUMARG 1
+#define iMINNUMCOINTDCS 0 /* minimum value */
+/* #define iMAXNUMCOINTDCS ..  maximum value defined in structures.h */
+
+#define cKEYWORD14                "fphotoel_per_adccnt"
+/* keyword no. 14 */
+#define cKEYWORD14ARG             "%s %f"
+#define iKEYWORD14NUMARG 2
+#define fMINPHOTOEL_PER_ADCCNT 0.1 /* minimum value for the 
+				    * second argument */
+#define fMAXPHOTOEL_PER_ADCCNT 999.0 /* maximum value for the 
+				      * second argument */
+/* as first argument either a single integer number or a 
+ * range may be given (format: e.g. 10-20) minimum and 
+ * maximum value of the first argument are identical with 
+ * iMINPIXNUM and the number of pixels in the camera */
+
+#define cKEYWORD15               "bmuon_suppression"       
+/* keyword no. 15 */
+#define cKEYWORD15ARG             "%s"
+#define iKEYWORD15NUMARG 1 /* this keyword is a switch */
+#define iKEYWORD15ARG1NUMVAL 2
+#define cKEYWORD15ARG1VALS "off", "on" /* the order of this 
+					* enumeration is essential 
+					* to make off equivalent 
+					* to FALSE */
+
+#define cKEYWORD16                "ftolerated_pointerror_deg"
+/* keyword no. 16 */
+#define cKEYWORD16ARG             "%f"
+#define iKEYWORD16NUMARG 1
+#define fMINTOLERATED_POINTERROR_DEG 0. /* minimum value for 
+					 * the maximum tolerated 
+					 * pointing error in the 
+					 * position check in 
+					 * iprocessdata */
+#define fMAXTOLERATED_POINTERROR_DEG 180. /* maximum value */
+
+#define cKEYWORD17                "iratecalc_numevents_odd"
+/* keyword no. 17 */
+#define cKEYWORD17ARG             "%d"
+#define iKEYWORD17NUMARG 1
+#define iMINRATECALC_NUMEVENTS_ODD 3 /* minimum value for the 
+				      * number of events used 
+				      * in the event rate 
+				      * calculation */
+#define iMAXRATECALC_NUMEVENTS_ODD 999 /* maximum value */
+
+#define cKEYWORD18                "fdegrees_per_step1"
+/* keyword no. 18 */
+#define cKEYWORD18ARG             "%f"
+#define iKEYWORD18NUMARG 1
+#define fMINDEGREES_PER_STEP 0.0001 /* minimum value for the 
+				     * resolution of shaft encoder 1 */
+#define fMAXDEGREES_PER_STEP 0.1 /* maximum value */
+
+#define cKEYWORD19                "fdegrees_per_step2"
+/* keyword no. 19 */
+#define cKEYWORD19ARG             "%f"
+#define iKEYWORD19NUMARG 1
+/* minimum and maximum values as for keyword 18 */
+
+#define cKEYWORD20               "se1_is"
+/* keyword no. 20 */
+#define cKEYWORD20ARG             "%s"
+#define iKEYWORD20NUMARG 1 
+#define iKEYWORD20ARG1NUMVAL 4
+#define cKEYWORD20ARG1VALS "RA", "DEC", "ALT", "AZ"
+
+#define cKEYWORD21                "flongitude_deg"
+/* keyword no. 21 */
+#define cKEYWORD21ARG             "%f"
+#define iKEYWORD21NUMARG 1
+#define fMIN_LONG_DEG 0. /* minimum value for the longitude 
+			  * of the telescope position */
+#define fMAX_LONG_DEG 359.99999 /* maximum value (the 
+				 * longitude is counted 
+				 * positive towards West */
+
+#define cKEYWORD22                "flatitude_deg"
+/* keyword no. 22 */
+#define cKEYWORD22ARG             "%f"
+#define iKEYWORD22NUMARG 1
+#define fMIN_LAT_DEG  -90.0 /* minimum value for the latitude 
+			     * of the telescope position */
+#define fMAX_LAT_DEG +90.0 /* maximum value */
+
+#define cKEYWORD23                "irubminusutc_usecs"
+/* keyword no. 23 */
+#define cKEYWORD23ARG             "%d"
+#define iKEYWORD23NUMARG 1
+#define iMINRUBMINUSUTC_USECS -60E6 /* minimum value for the 
+				     * time difference between 
+				     * rubidium clock and UTC*/
+#define iMAXRUBMINUSUTC_USECS 60e6 /* maximum value */
+
+#define cKEYWORD24                "iaz_rev_track_corr"
+/* keyword no. 24 */
+#define cKEYWORD24ARG             "%d"
+#define iKEYWORD24NUMARG 1
+#define iMINAZ_REV_TRACK_CORR -1000 /* minimum value for the 
+				     * correction of the az 
+				     * shaft encoder values 
+				     * in reverse tracking mode
+				     * see Calc_corr in TIJARAFE */
+#define iMAXAZ_REV_TRACK_CORR 1000 /* maximum value */
+
+#define cKEYWORD25                "ialt_rev_track_corr"
+/* keyword no. 25 */
+#define cKEYWORD25ARG             "%d"
+#define iKEYWORD25NUMARG 1
+#define iMINALT_REV_TRACK_CORR -1000 /* minimum value for the 
+				      * correction of the alt 
+				      * shaft encoder values 
+				      * in reverse tracking mode
+				      * see Calc_corr in TIJARAFE */
+#define iMAXALT_REV_TRACK_CORR 1000 /* maximum value */
+
+#define cKEYWORD26                "fbendingcorr"
+/* keyword no. 26 */
+#define cKEYWORD26ARG             "%f"
+#define iKEYWORD26NUMARG 1
+#define fMINBENDINGCORR  -0.5 /* minimum value for the bending 
+			       * correction factor for the alt 
+			       * shaft encoder values
+			       * see Calc_corr in TIJARAFE */
+#define fMAXBENDINGCORR 0.5 /* maximum value */
+
+#define cKEYWORD27                "fextinction"
+/* keyword no. 27 */
+#define cKEYWORD27ARG             "%f"
+#define iKEYWORD27NUMARG 1
+#define fMINEXTINCTION  0. /* minimum value for the 
+			    * atmospheric extinction */
+#define fMAXEXTINCTION  1. /* maximum value */
+
+#define cKEYWORD28                "dsource_ra_hours"
+/* keyword no. 28 */
+#define cKEYWORD28ARG             "%lf"
+#define iKEYWORD28NUMARG 1
+#define fMINRA_HOURS 0.0   /* minimum value for the right 
+			    * ascension of the assumed source */
+#define fMAXRA_HOURS 23.99999999 /* maximum value */
+
+#define cKEYWORD29                "dsource_dec_deg"
+/* keyword no. 29 */
+#define cKEYWORD29ARG             "%lf"
+#define iKEYWORD29NUMARG 1
+#define fMINDEC_DEG -90.0 /* minimum value for the 
+			   * declination of the assumed source */
+#define fMAXDEC_DEG 90.0        /* maximum value */
+
+#define cKEYWORD30                "imuoncut_thresh_adccnt"
+/* keyword no. 30 */
+#define cKEYWORD30ARG             "%s %d"
+#define iKEYWORD30NUMARG 2
+#define iMINMUONCUT_THRESH_ADCCNT 0 /* minimum value for the 
+				     * second argument */
+#define iMAXMUONCUT_THRESH_ADCCNT 65536 /* maximum value for 
+					 * the second argument */
+/* as first argument either a single integer number or a 
+ * range may be given (format: e.g. 3-5) minimum and maximum 
+ * value of the first argument are the number of pixels in 
+ * the camera +1 and the number of pixels in the camera + 
+ * the number of muonpixels in the camera */
+
+#define cKEYWORD31                "fxpointcorr_deg"
+/* keyword no. 31 */
+#define cKEYWORD31ARG             "%f"
+#define iKEYWORD31NUMARG 1
+#define fMINRAPOINTERROR_DEG -10. /* minimum value for the 
+				   * pointing error correction 
+				   * along camera x axis as known 
+				   * from e.g. a pointrun */
+#define fMAXRAPOINTERROR_DEG +10. /* maximum value */
+
+#define cKEYWORD32                "fypointcorr_deg"
+/* keyword no. 32 */
+#define cKEYWORD32ARG             "%f"
+#define iKEYWORD32NUMARG 1
+#define fMINDECPOINTERROR_DEG -10. /* minimum value for the 
+				    * pointing error correction 
+				    * along camera y axis as known 
+				    * from e.g. a pointrun */
+#define fMAXDECPOINTERROR_DEG +10. /* maximum value */
+
+#define cKEYWORD33                "fcamera_align_angle_deg"
+/* keyword no. 33 */
+#define cKEYWORD33ARG             "%f"
+#define iKEYWORD33NUMARG 1
+#define fMINCAMALIGNANGLE_DEG -180. /* minimum value for the 
+				     * angle between the camera 
+				     * y-axis and the meridian 
+				     * when a culminating object
+				     * is observed (defined 
+				     * counter-clockwise looking 
+				     * at the sky) */
+#define fMAXCAMALIGNANGLE_DEG 180. /* maximum value */
+
+#define cKEYWORD34               "bhistograms"
+/* keyword no. 34 */
+#define cKEYWORD34ARG             "%s"
+#define iKEYWORD34NUMARG 1 /* this keyword is a threefold switch */
+#define iKEYWORD34ARG1NUMVAL 3
+#define cKEYWORD34ARG1VALS "off", "on", "new" /* the order of this 
+					       * enumeration is 
+					       * essential to make 
+					       * off equivalent to FALSE */
+
+#define cKEYWORD35                "iadc_histopars"
+/* keyword no. 35 */
+#define cKEYWORD35ARG             "%d %f %f"
+#define iKEYWORD35NUMARG 3
+#define iMINBINS 3
+#define iMAXBINS 300
+#define fMIN_ADCHIST_LOLIM -50.5
+#define fMAX_ADCHIST_LOLIM 1000.
+#define fMIN_ADCHIST_HILIM 0.5
+#define fMAX_ADCHIST_HILIM 65535.5
+
+#define cKEYWORD36                "iphe_histopars"
+/* keyword no. 36 */
+#define cKEYWORD36ARG             "%d %f %f"
+#define iKEYWORD36NUMARG 3
+#define fMIN_PHEHIST_LOLIM -10000.
+#define fMAX_PHEHIST_LOLIM 1000.
+#define fMIN_PHEHIST_HILIM -1000.
+#define fMAX_PHEHIST_HILIM 10000.
+
+#define cKEYWORD37                "idontusepix_in_trig"
+/* keyword no. 37 */
+#define cKEYWORD37ARG             "%s"
+#define iKEYWORD37NUMARG 1    /* in the parameters file 
+			       * counting of the pixels starts at 1
+                              * minimum value is iMINPIXNUM 
+                              * maximum value of this parameter 
+			      * is iMAXNUMPIX the pixel can only be 
+			      * taken back into trigger by resetting all
+                              * parameters */
+
+#define cKEYWORD38                "fpadlevel_phot_pix"
+/* keyword no. 38 */
+#define cKEYWORD38ARG             "%s %f"
+#define iKEYWORD38NUMARG 2
+#define fMINPADLEVEL_PHOT  0. /* minimum value for the software 
+			       * padding level for each pixel */
+#define fMAXPADLEVEL_PHOT  100. /* maximum value */
+
+#define cKEYWORD39                "frandomseeds"
+/* keyword no. 39 */
+#define cKEYWORD39ARG             "%f %f "
+#define iKEYWORD39NUMARG 2
+#define fMINSEED 1. /* minimum value for the maximum tolerated 
+		     * pointing error in the position check in 
+		     * iprocessmcdata */
+#define fMAXSEED 1.e10 /* maximum value */
+
+#define cKEYWORD40                "iswap_pixels"
+/* keyword no. 40 */
+#define cKEYWORD40ARG             "%d %d " /* the number of the 
+					    * two pixels for which 
+					    * the numbering should 
+					    * be swapped (in 
+					    * ireadrunfile, 
+					    * -pedfile, -calfile) */
+#define iKEYWORD40NUMARG 2
+/* the minimum value for this argument is iMINPIXNUM, the maximum 
+ * is iMAXNUMPIX */
+
+#define cKEYWORD41                "%"
+/* keyword no. 41 */
+#define cKEYWORD41ARG             "\n" /* using this keyword, 
+					* comments can be added 
+					* to the parameter file */
+#define iKEYWORD41NUMARG 0
+
+#define cKEYWORD42           "errortolerance"
+/* keyword no. 42 */
+#define cKEYWORD42ARG        "%s"
+#define iKEYWORD42NUMARG 1
+#define iKEYWORD42ARG1NUMVAL 3
+#define cKEYWORD42ARG1VALS "cautious", "goodphysics", "tank"
+/* cautious: exits on any reason 
+ * normal: the usual way: exit only, when the physics would 
+ *         be affected
+ * tank: exits only when all runs are processed. Otherwise
+ *       it goes through everything, even through the pain of 
+ *       a coredump. */
+
+#define cKEYWORD43           "montecarlo"
+/* keyword no. 43 */
+#define cKEYWORD43ARG        "%s"
+#define iKEYWORD43NUMARG 1
+#define iKEYWORD43ARG1NUMVAL 3
+#define cKEYWORD43ARG1VALS "all", "flag", "noflag"
+/* Whenever this one is specified, there shell apply certain 
+ * limitations: No pedestal and calibration files shall be read in. 
+ * Maybe more.... 
+ * Arguments:
+ * all: all events which survive the filter are written to the 
+ *      events NTuple. 
+ * flag: When Dorota's triggerflag is set to 1 for a particular
+ *       event, it shall be written to the output. All others shall
+ *       just be disregarded.
+ * noflag: Opposite of 'flag': only events with triggerflag = 0 shall
+ *         be treated further. */
+
+#define cKEYWORD44           "mcfile"
+/* keyword no. 44 */
+#define cKEYWORD44ARG        "%s"
+#define iKEYWORD44NUMARG 1
+
+#define cKEYWORD45           "fmean_nsb_pe_pix"
+/* keyword no. 45 */
+#define cKEYWORD45ARG             "%s %f"
+#define iKEYWORD45NUMARG 2
+#define fMIN_NSB_PE_PIX  0.
+#define fMAX_NSB_PE_PIX  2000000000. /* some ridiculous number...*/
+
+#define cKEYWORD46           "fitmypedrms"
+/* keyword no. 46 */
+/* Setting this keyword in the parameterfile shall trigger the 
+ * pedestal MEAN and SIGMA=sqrt(MEAN) to be fitted from pickup
+ * corrected pedestal data and not calculated from the pickup 
+ * corrected ADC values, as it was done up to ~November 2000. */
+
+/* Macintosh variable formats */
+#define lMACSIZEOFSHORT  2L
+#define lMACSIZEOFLONG   4L
+#define lMACSIZEOFDOUBLE 8L
+
+/* Time Offsets */
+#define iMACTIMEOFFSET 2082844800 /* offset to be subtracted 
+				   * from the Macintosh time 
+				   * read from the various data 
+				   * files to get DECSTATION/ALPHA 
+				   * time */
+
+/* TIJARAFE filename conventions */
+
+#define cCALFILENAME_TEMPLATE "Te%1sCal_*%s_%2s_*"
+#define cLOGFILENAME_TEMPLATE "Te%1sLog_*%s_%2s_*"
+#define cPEDFILENAME_TEMPLATE "Te%1sPed_*%s_%2s_???????_*"
+#define cRUNFILENAME_TEMPLATE "Te%1sRun_*%s_%2s_*"
+#define cPOIFILENAME_TEMPLATE "Te%1sPoi_*%s_%2s_*"
+#define cCTIDPOSITION_TIJ "2" /* element of the filename character 
+			   * array which contains the telescope id
+			   * a length of 1 character is assumed */
+#define cRUNNUMPOSITION_TIJ "7" /* element of the filename character 
+			     * array which contains the run number */
+#define cRUNNUMLENGTH_TIJ "4" /* number of characters in the run number */
+#define cRUNTYPEPOSITION_TIJ "12" /* element of the filename character 
+			       * array which contains the ON or OF 
+			       * string a length of 2 characters is 
+			       * assumed */
+#define iTIJ_DUMMYLENGTH 20
+
+/* ROBERTO filename conventions */
+
+#define cCTIDPOSITION_ROB "2" /* element of the filename character 
+			       * array which contains the telescope id
+			       * a length of 1 character is assumed */
+#define cRUNNUMPOSITION_ROB "7" /* element of the filename character 
+				 * array which contains the run number */
+#define cRUNNUMLENGTH_ROB "5" /* number of characters in the run number */
+#define cRUNTYPEPOSITION_ROB "13" /* element of the filename character 
+				   * array which contains the ON or OF 
+				   * string a length of 2 characters is 
+				   * assumed */
+#define iROB_DUMMYLENGTH 26
+
+/* Razmick's Method's F Factor for the PMTs: */
+/* #define FIXED_F_VALUE 1.09 */
+/* #define FIXED_F_VALUE 1.15 */
+#define FIXED_F_VALUE 1.075
+
+/* Monte Carlo defines, that _MUST_ be exactly the same as in
+ * zorp's defines.h. */
+#define iMAXNUMCTS 1
+#define iNUMENERGYBINS 19
+#define iNUMIMPACTBINS 60
+#define iNUMZENANGLEBINS 24
+#define iMAXNUMNFLSHIFTS 1
+#define fMAXIMPACTPAR 600.
+
+/* exit codes */
+
+#define iERRORINPROCESSDATA 100
+#define iERRORINMAKEFILENAME 101
+#define iERRORCT2TRACKMODE 102
+#define iERRORGAINZERO 103
+
+/*************** GLOBAL VARIABLES *********************************/
+
+#define FILEHANDLING_VERSION 4.2
+
+#endif
+
+#ifdef _defines_h_
+
+extern char G_cfilehandlingident[];
+extern char G_filehandhfilehident[];
+
+extern char G_cfatalerrortext[22];
+extern Boolean G_bhbook_is_init;
+extern float G_fpreprocversion;
+extern char G_preprocident[];
+extern char G_preprocstrucident[];
+extern char G_preprocfilehident[];
+
+extern char *calnt_var_list[22];
+extern char cprojectname[40];
+
+extern HBOOK_FILE calnt;
+extern HBOOK_FILE calhb;
+extern int G_oferfloweventID;
+extern int G_oferfloweventoffset;
+extern float pixcoords[271][2]; /* For the 2-dim camera pictures of the 
+				 * overflow events */
+#endif
Index: /tags/Mars-V0.9/mfileio/structures_rfl.h
===================================================================
--- /tags/Mars-V0.9/mfileio/structures_rfl.h	(revision 9772)
+++ /tags/Mars-V0.9/mfileio/structures_rfl.h	(revision 9772)
@@ -0,0 +1,262 @@
+#ifndef __RFL_HEADER__
+#define __RFL_HEADER__
+
+
+/*  Event header of reflector files ver <= 0.5  */ 
+typedef struct
+{   float	EvtNumber;
+    float	PrimaryID;
+    float	Etotal;   
+    float	Thick0;   
+    float	FirstTarget;
+    float	zFirstInt;
+    float	p[3];     
+    float	Theta; 
+    float	Phi; 
+
+    float	NumRndSeq;
+    float	RndData[10][3];
+  
+    float	RunNumber;
+    float	DateRun;
+    float	Corsika_version;
+
+    float	NumObsLev;  /* Should be 1 for MAGIC simulation */
+    float	HeightLev;  /* Observation Level */
+
+    /* Changed meaning of next 9 variables. June 2002, A.Moralejo: */
+    float       num_mirrors;
+    float       mean_reflectivity;
+    float       longi_Nmax;
+    float       longi_t0;
+    float       longi_tmax;
+    float       longi_a;
+    float       longi_b;
+    float       longi_c;
+    float       longi_chi2;
+
+    float	SlopeSpec;
+    float	ELowLim;   
+    float	EUppLim;   
+
+    float	ThetaMin;
+    float	ThetaMax;
+    float	PhiMin;
+    float	PhiMax;
+
+    float	CWaveLower;       
+    float	CWaveUpper;       
+    float	CorePos[2][20];   
+    float	TimeFirst;
+    float	TimeLast;
+
+    /* AM, 23/05/2002: Changed meaning of following
+     * three variables (which were unused before): 
+     */
+    float	telescopePhi;    /* rad */
+    float	telescopeTheta;  /* rad */
+  
+    float	ViewConeRadius; /* Degrees.
+				 * Radius of "view cone" when the primaries'
+				 * directions generated by Corsika lie within
+				 * a cone around a fixed direction. This is
+				 * only possible with Corsika>6 versions. In
+				 * that case, PhiMin=PhiMax  and 
+				 * ThetaMin=ThetaMax (also in this header) 
+				 * indicate the axis of this cone.   
+				 * If ViewConeRadius==0, it means that
+				 * the VIEWCONE option was not used.
+				 */
+
+
+    float	CORSIKAPhs;	/*  Original photons written by Corsika	*/
+    float	AtmAbsPhs;	/*  Photons absorbed by the atmosphere	*/
+    float	MirrAbsPhs;	/*  Photons absorbed by the mirror	*/
+    float	OutOfMirrPhs;	/*  Photons outside the mirror		*/
+    float	BlackSpotPhs;	/*  Photons lost in the "black spot"	*/
+    float	OutOfChamPhs;	/*  Photons outside the camera		*/
+    float	CPhotons;	/*  Photons reaching the camera         */
+
+}   RflEventHeader_old;
+
+
+/* Reflector files run header (same as CORSIKA's cer files run header): */
+
+typedef struct
+{   char RUNH[4];
+    float RunNumber;
+    float date;
+    float Corsika_version;
+    float NumObsLev;
+    float HeightLev[10];
+    float SlopeSpec;  /* Slope of primaries' energy spectrum */
+    float ELowLim;  
+    float EUppLim;    /* Limits of energy range for generation */
+    float EGS4_flag;
+    float NKG_flag;
+    float Ecutoffh;  
+    float Ecutoffm;  
+    float Ecutoffe;  
+    float Ecutoffg;  
+    /* Physical constants and interaction flags (see CORSIKA manual): */
+    float C[50];
+    float wobble_mode;
+    float atmospheric_model;
+    float dummy1[18]; /* not used */
+    float CKA[40];
+    float CETA[5];
+    float CSTRBA[11];
+    float dummy2[104]; /* not used */
+    float AATM[5];
+    float BATM[5];
+    float CATM[5];
+    float NFL[4];
+
+}   RflRunHeader;
+
+
+/*  Event header of reflector_0.6 files: */ 
+
+typedef struct			
+{   char	EVTH[4];
+    float	EvtNumber;
+    float	PrimaryID;
+    float	Etotal;   
+    float	Thick0;   
+    float	FirstTarget;
+    float	zFirstInt;
+    float	p[3];     
+    float	Theta; 
+    float	Phi; 
+
+    float	NumRndSeq;
+    float	RndData[10][3];
+  
+    float	RunNumber;
+    float	DateRun;
+    float	Corsika_version;
+
+    float	NumObsLev;
+    float	HeightLev[10]; 
+
+    float	SlopeSpec;
+    float	ELowLim;   
+    float	EUppLim;   
+
+    float	Ecutoffh;  
+    float	Ecutoffm;  
+    float	Ecutoffe;  
+    float	Ecutoffg;  
+
+    float	NFLAIN;
+    float	NFLDIF;
+    float	NFLPI0;
+    float	NFLPIF;
+    float	NFLCHE;
+    float	NFRAGM; 
+ 
+    float	Bx;
+    float	By;
+  
+    float	EGS4yn;
+    float	NKGyn;
+    float	GHEISHAyn;
+    float	VENUSyn;
+    float	CERENKOVyn;
+    float	NEUTRINOyn;
+    float	HORIZONTyn;
+    float	COMPUTER;
+
+    float	ThetaMin;
+    float	ThetaMax;
+    float	PhiMin;
+    float	PhiMax;
+
+    float	CBunchSize;
+    float	CDetInX,CDetInY;
+    float	CSpacInX,CSpacInY;
+    float	CLenInX,CLenInY;
+    float	COutput;
+
+    float	AngleNorthX;
+    float	MuonInfo;
+
+    float	StepLength;
+    float	CWaveLower;       
+    float	CWaveUpper;       
+    float	Multipl;       
+    float	CorePos[2][20];   
+    float       SIBYLL[2];
+    float       QGSJET[2];
+    float       DPMJET[2];
+    float       VENUS_cross;
+    float       mu_mult_scat;
+    float       NKG_range;
+    float       EFRCTHN[2];
+    float       WMAX[2];
+    float       rthin_rmax;
+
+    float       viewcone_angles[2]; 
+    /* (degrees) Inner and outer angles in 
+     * Corsika's VIEWCONE option. This is
+     * only possible with Corsika>6 versions. In
+     * that case, PhiMin=PhiMax  and 
+     * ThetaMin=ThetaMax (also in this header) 
+     * indicate the axis of this cone.   
+     */
+
+    /* ^^^ Up to here, the info from the CORSIKA event header. */
+
+    /* Telescope orientation: */
+    float	telescopePhi;    /* rad */
+    float	telescopeTheta;  /* rad */
+
+    /* Time of first and last photon: */
+    float	TimeFirst;
+    float	TimeLast;
+
+    /* 6 parameters and chi2 of the NKG fit to the longitudinal 
+     * particle distribution (see CORSIKA manual for explanation): 
+     */
+    float       longi_Nmax;
+    float       longi_t0;
+    float       longi_tmax;
+    float       longi_a;
+    float       longi_b;
+    float       longi_c;
+    float       longi_chi2;
+
+    /* Now the photon statistics of the event: */
+    float	CORSIKAPhs;	/*  Original photons written by Corsika	*/
+    float	AtmAbsPhs;	/*  Photons absorbed by the atmosphere	*/
+    float	MirrAbsPhs;	/*  Photons absorbed by the mirror	*/
+    float	OutOfMirrPhs;	/*  Photons outside the mirror		*/
+    float	BlackSpotPhs;	/*  Photons lost in the "black spot"	*/
+    float	OutOfChamPhs;	/*  Photons outside the camera		*/
+    float	CPhotons;	/*  Photons reaching the camera         */
+ 
+    /* Now follow the fraction of photons reaching the camera produced by
+     * electrons, muons and other particles respectively: 
+     */ 
+    float       elec_cph_fraction;
+    float       muon_cph_fraction;
+    float       other_cph_fraction;
+
+    float       dummy[7];      /* not used */
+}   RflEventHeader;
+
+/*Photons data estructure*/
+typedef struct
+{   float w,                    /*  cphoton wavelength (nm)             */
+      x, y,			/*  (camera) imp. point (cm)            */
+      u, v,			/*  direction cosines                   */
+      t,			/*  arrival time (ns)                   */
+      h,			/*  production height (cm)              */
+      phi;			/*  (camera) inc. angle (rad)           */
+    }   cphoton;
+
+#endif
+
+
+
+
Index: /tags/Mars-V0.9/mfilter/FilterIncl.h
===================================================================
--- /tags/Mars-V0.9/mfilter/FilterIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/FilterIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mfilter/FilterLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mfilter/FilterLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/FilterLinkDef.h	(revision 9772)
@@ -0,0 +1,19 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MFTriggerLvl1+;
+#pragma link C++ class MFTriggerLvl2+;
+#pragma link C++ class MFGeomag+;
+#pragma link C++ class MFDeltaT+;
+#pragma link C++ class MFParticleId+;
+
+#pragma link C++ class MFSoftwareTrigger+;
+#pragma link C++ class MFCosmics+;
+#pragma link C++ class MFSupercuts+;
+
+#pragma link C++ class MFEnergySlope+;
+
+#endif
Index: /tags/Mars-V0.9/mfilter/MFAlpha.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFAlpha.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFAlpha.cc	(revision 9772)
@@ -0,0 +1,129 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  01/2002 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MFAlpha                                                               //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MFAlpha.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MHillasSrc.h"
+
+ClassImp(MFAlpha);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MFAlpha::MFAlpha(const char *cname, const char type, const Float_t val,
+                 const char *name, const char *title) : fHillas(NULL)
+{
+    fContName = cname;
+    Init(type, val, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+MFAlpha::MFAlpha(MHillasSrc *hillas, const char type, const Float_t val,
+                 const char *name, const char *title) : fHillas(hillas)
+{
+    Init(type, val, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+void MFAlpha::Init(const char type, const Float_t val,
+                   const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFAlpha";
+    fTitle = title ? title : "Filter using the alpha angle";
+
+    fFilterType = (type=='<' ? kELowerThan : kEGreaterThan);
+
+    if (type!='<' && type!='>')
+        *fLog << warn << dbginf << "Warning: Neither '<' nor '>' specified... using '>'." << endl;
+
+    fValue = val;
+
+    AddToBranchList(Form("%s.fAlpha", (const char*)fContName));
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFAlpha::PreProcess(MParList *pList)
+{
+    if (fHillas)
+        return kTRUE;
+
+    fHillas = (MHillasSrc*)pList->FindObject(fContName);
+    if (fHillas)
+        return kTRUE;
+
+    *fLog << err << dbginf << fContName << " [MHillas] not found... aborting." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFAlpha::Process()
+{
+    const Float_t alpha = fabs(fHillas->GetAlpha());
+
+    switch (fFilterType)
+    {
+    case kELowerThan:
+        fResult = (alpha < fValue);
+        break;
+    case kEGreaterThan:
+        fResult = (alpha > fValue);
+        break;
+    }
+
+    return kTRUE;
+}
+
+void MFAlpha::StreamPrimitive(ofstream &out) const
+{
+    if (fHillas)
+        fHillas->SavePrimitive(out);
+
+    out << "   MFParticleId " << GetUniqueName() << "(";
+
+    if (fHillas)
+        out << "&" << fHillas->GetUniqueName();
+    else
+        out << "\"" << fContName << "\"";
+
+    out << ", '" << (fFilterType==kELowerThan?"<":">") << "', " << fValue << ");" << endl;
+
+}
Index: /tags/Mars-V0.9/mfilter/MFAlpha.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFAlpha.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFAlpha.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MFAlpha
+#define MARS_MFAlpha
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFAlpha                                                                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MParList;
+class MHillasSrc;
+
+class MFAlpha : public MFilter
+{
+private:
+    MHillasSrc *fHillas;
+    TString fContName;
+
+    typedef enum { kELowerThan, kEGreaterThan } FilterType_t;
+    FilterType_t fFilterType;
+
+    Bool_t  fResult; //!
+    Float_t fValue; // [deg]
+
+    void Init(const char type, const Float_t val,
+              const char *name, const char *title);
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MFAlpha(const char *cname="MHillas", const char type='>', const Float_t deg=15,
+            const char *name=NULL, const char *title=NULL);
+    MFAlpha(MHillasSrc *hillas, const char type='>', const Float_t deg=15,
+            const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    ClassDef(MFAlpha, 1) // A Filter for cuts in fabs(alpha)
+};
+
+#endif
Index: /tags/Mars-V0.9/mfilter/MFCT1SelBasic.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFCT1SelBasic.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFCT1SelBasic.h	(revision 9772)
@@ -0,0 +1,68 @@
+#ifndef MARS_MFCT1SelBasic
+#define MARS_MFCT1SelBasic
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFCT1SelBasic                                                           //
+//                                                                         //
+// Class to evaluate basic cuts                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcEvt;
+class MGeomCam;
+class MCerPhotEvt;
+class MPedestalCam;
+class MRawRunHeader;
+
+class MFCT1SelBasic : public MFilter
+{
+private:
+    const MMcEvt        *fMcEvt;       
+    const MGeomCam      *fCam;      // Camera Geometry 
+    const MCerPhotEvt   *fEvt;      // Cerenkov Photon Event 
+    //const MPedestalCam  *fPed;      // Pedestal information
+    const MRawRunHeader *fRawRun;
+
+    Float_t     fMinPhotons;
+    Float_t     fThetaMin;
+    Float_t     fThetaMax;
+
+    Int_t       fCut[5];
+
+    Bool_t      fResult;
+
+    Int_t Set(Int_t rc);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    Bool_t SwTrigger();
+
+public:
+    MFCT1SelBasic(const char *name=NULL, const char *title=NULL);
+
+    void SetCuts(Float_t minphotons, Float_t thetamin, Float_t thetamax);
+
+    ClassDef(MFCT1SelBasic, 0)   // Class to evaluate basic cuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mfilter/MFCosmics.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFCosmics.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFCosmics.cc	(revision 9772)
@@ -0,0 +1,209 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MFCosmics
+//
+//   Filter to reject cosmics by the criterion that at least 
+//   fMaxEmptyPixels of the pixels have values of lower than 3 Pedestal RMS. 
+//   fMaxEmptyPixels is set to 0.4 by default which is slightly higher 
+//   than the number of outer pixels in MAGIC (for the case that 
+//   the outer pixels have some defect).
+//
+//  Input Containers:
+//   MRawEvtData
+//   MPedestalCam
+//   MExtractedSignalCam
+//
+//  Output Containers:
+//   -/-
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MFCosmics.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MFCosmics);
+
+using namespace std;
+
+const TString MFCosmics::fgNamePedestalCam = "MPedestalCam";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MFCosmics::MFCosmics(const char *name, const char *title)
+    : fPedestals(NULL), fSignals(NULL), fRawEvt(NULL),
+    fNamePedestalCam(fgNamePedestalCam), fMaxEmptyPixels(0.2)
+{
+    fName  = name  ? name  : "MFCosmics";
+    fTitle = title ? title : "Filter to reject cosmics";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//  - MExtractedSignalCam
+//
+Int_t MFCosmics::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvt)
+    {
+      *fLog << err << "MRawEvtData not found... aborting." << endl;
+      return kFALSE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindObject(fNamePedestalCam, "MPedestalCam");
+    if (!fPedestals)
+    {
+        *fLog << err << fNamePedestalCam << " [MPedestalCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSignals = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+    if (!fSignals)
+    {
+        *fLog << err << "MExtractedSignalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    memset(fCut, 0, sizeof(fCut));
+    
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Initialize number of used FADC slices
+//
+Bool_t MFCosmics::ReInit(MParList *pList)
+{
+    fSqrtHiGainSamples = TMath::Sqrt((Float_t) fSignals->GetNumUsedHiGainFADCSlices());
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Retrieve the integral of the FADC time slices and compare them to the 
+// pedestal values.
+//
+Int_t MFCosmics::Process()
+{
+    fResult = CosmicsRejection();
+
+    fCut[fResult ? 0 : 1]++;
+    return kTRUE;
+}
+
+// ---------------------------------------------------------
+//
+// Cosmics rejection: 
+// 
+// Requiring less than fMaxEmptyPixels pixels to have values 
+// lower than 3 Pedestal RMS. 
+// 
+// fMaxEmptyPixels is set to 230 by default which is slightly higher 
+// than the number of outer pixels in MAGIC (for the case that 
+// the outer pixels have some defect).
+//
+Bool_t MFCosmics::CosmicsRejection() const
+{
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    Int_t cosmicpix = 0;
+    Int_t allpix    = 0;
+
+    //
+    // Create a first loop to sort out the cosmics ...
+    //
+    while (pixel.Next())
+    {
+        const UInt_t idx = pixel.GetPixelId();
+
+        MExtractedSignalPix &sig =  (*fSignals)[idx];
+        MPedestalPix        &ped =  (*fPedestals)[idx];
+
+        const Float_t pedrms = ped.GetPedestalRms()*fSqrtHiGainSamples;
+        const Float_t sumhi  = sig.GetExtractedSignalHiGain();
+
+	allpix++;
+
+        //
+        // We consider a pixel as presumably due to cosmics
+        // if its sum of FADC slices is lower than 3 pedestal RMS
+        //
+        if (sumhi < 3.*pedrms )
+            cosmicpix++;
+    }
+
+    //
+    // If the camera contains more than fMaxEmptyPixels
+    // presumed pixels due to cosmics, then the event is discarted.
+    //
+    return cosmicpix > fMaxEmptyPixels*allpix;
+}
+
+Int_t MFCosmics::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    *fLog << " " << setw(7) << fCut[0] << " (" << setw(3) ;
+    *fLog << (int)(fCut[0]*100/GetNumExecutions()) ;
+    *fLog << "%) Detected cosmics " ;
+    *fLog << " (with fMaxEmptyPixels = " << fMaxEmptyPixels*100 << "%)" << endl;
+
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/GetNumExecutions()) ;
+    *fLog << "%) No cosmics!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mfilter/MFCosmics.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFCosmics.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFCosmics.h	(revision 9772)
@@ -0,0 +1,54 @@
+#ifndef MARS_MFCosmics
+#define MARS_MFCosmics
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MRawEvtData;
+
+class MPedestalCam;
+class MExtractedSignalCam;
+
+class MFCosmics : public MFilter
+{
+private:
+    static const TString fgNamePedestalCam;
+
+    MPedestalCam        *fPedestals; // Pedestals of all pixels in the camera
+    MExtractedSignalCam *fSignals;   // Calibration events of all pixels in the camera
+
+    MRawEvtData         *fRawEvt;    // raw event data (time slices)
+
+    TString fNamePedestalCam;
+
+    Int_t   fCut[2];
+    Bool_t  fResult;
+
+    Float_t fMaxEmptyPixels;         // Maximum number of empty pixels before declaring event as cosmic
+    Float_t fSqrtHiGainSamples;      // Square root of the number of used Hi-Gain Samples
+
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+    Bool_t CosmicsRejection() const;
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+  
+public:
+    MFCosmics(const char *name=NULL, const char *title=NULL);
+
+    void    SetMaxEmptyPixels(const Float_t n) { fMaxEmptyPixels = n;    }
+    Float_t GetMaxEmptyPixels() const          { return fMaxEmptyPixels; }
+
+    void SetNamePedestalCam(const char *name) { fNamePedestalCam = name; }
+
+    ClassDef(MFCosmics, 0)   // Filter to perform a cosmics rejection
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/mfilter/MFDeltaT.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFDeltaT.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFDeltaT.cc	(revision 9772)
@@ -0,0 +1,165 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  09/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFDeltaT
+//
+//  for more details see Construtor and Process()
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFDeltaT.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MFDeltaT);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Constructor. First argument is the upper limit of the filter (default=0.5).
+// Second argument is the name of the parameter container storing the time.
+// (default="MTime")
+//
+MFDeltaT::MFDeltaT(Float_t max, const char *time,
+                   const char *name, const char *title)
+{
+    Init(name, title, max, time);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. Initializes upper limit of the filter (default=0.5)
+// and name of the parameter container storing the time (default="MTime")
+//
+MFDeltaT::MFDeltaT(const char *name, const char *title)
+{
+    Init(name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+void MFDeltaT::Init(const char *name, const char *title,
+                    Float_t max, const char *time)
+{
+    fName  = name  ? name  : "MFDeltaT";
+    fTitle = title ? title : "Filter for time differences of consecutive events";
+
+    fUpperLimit = max;
+    fNameTime   = time;
+
+    fErrors.Set(6);
+
+    AddToBranchList(Form("%s.*", (const char*)fNameTime));
+}
+
+// --------------------------------------------------------------------------
+//
+// Return result of conditional
+//
+Bool_t MFDeltaT::IsExpressionTrue() const
+{
+    return fResult;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for fNameTime [MTime]
+//
+Int_t MFDeltaT::PreProcess(MParList *pList)
+{
+    fErrors.Reset();
+
+    fTime = (MTime*)pList->FindObject(fNameTime, "MTime");
+    if (fTime)
+        return kTRUE;
+
+    *fLog << err << fNameTime << " [MTime] not found... aborting." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the consition. The consition is true if the time difference
+// between two consecutive events are >0 or <= upper limit.
+//
+Int_t MFDeltaT::Process()
+{
+    fResult = kFALSE;
+
+    Int_t i=0;
+
+    if (GetNumExecutions()>0)
+    {
+        if (*fTime-fLastTime>fUpperLimit)
+            i=1;
+        if (*fTime<fLastTime)
+            i=2;
+        if (*fTime==fLastTime)
+            i=3;
+        if (fTime->IsMidnight())
+            i=4;
+        if (*fTime==MTime())
+            i=5;
+    }
+
+    fLastTime = *fTime;
+
+    fResult = i==0;
+    fErrors[i]++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print some statistics.
+//
+Int_t MFDeltaT::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " filter statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    PrintSkipped(fErrors[2], "Delta-T  < 0");
+    PrintSkipped(fErrors[3], "Delta-T == 0");
+    PrintSkipped(fErrors[1], Form("Delta-T  > %.2fs", fUpperLimit));
+    PrintSkipped(fErrors[4], "MTime is midnight");
+    PrintSkipped(fErrors[5], "MTime not initialized");
+    *fLog << " " << (int)fErrors[0] << " (";
+    *fLog << Form("5.1f", 100.*fErrors[0]/GetNumExecutions());
+    *fLog << "%) Evts fullfilled filter condition!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mfilter/MFDeltaT.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFDeltaT.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFDeltaT.h	(revision 9772)
@@ -0,0 +1,50 @@
+#ifndef MARS_MFDeltaT
+#define MARS_MFDeltaT
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class MTime;
+class MParList;
+
+class MFDeltaT : public MFilter
+{
+private:
+    MTime  *fTime;     //!
+    TString fNameTime;
+
+    Float_t fUpperLimit;
+
+    MTime  fLastTime;  //!
+    Bool_t fResult;    //!
+
+    TArrayI fErrors;
+
+    void Init(const char *name, const char *title, Float_t max=0.5, const char *time="MTime");
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MFDeltaT(Float_t max, const char *time="MTime", const char *name=0, const char *title=0);
+    MFDeltaT(const char *name=0, const char *title=0);
+
+    void SetUpperLimit(Float_t max) { fUpperLimit=max; }
+    Float_t GetUpperLimit() const { return fUpperLimit; }
+
+    Bool_t IsExpressionTrue() const;
+
+    ClassDef(MFDeltaT, 1) // A Filter for time differences of consecutive events
+};
+
+#endif
Index: /tags/Mars-V0.9/mfilter/MFEnergySlope.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFEnergySlope.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFEnergySlope.cc	(revision 9772)
@@ -0,0 +1,181 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Antonio Stamerra  02/2003 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MFEnergySlope                                                         //
+//                                                                         //
+//  A filter to select MC events (generated with a energy slope MCSlope)   //
+//   with a different energy slope NewSlope set by the user.               //
+//                                                                         //
+//  The new slope is set by the user with SetSlope().                      //
+//  Only negative slopes are admitted; positive ones are internally        //
+//   converted.                                                            //
+//  Events are selected following the new energy power slope, and the      //
+//   sample is normalized to the number of events at:                      //
+//    1. McMaxEnergy, if abs(NewSlope) < abs(McSlope);                     //
+//    2. McMinEnergy, if abs(NewSlope) > abs(McSlope);                     //
+//   Mc{Max,Min}Energy are set with SetMcMinEnergy() and SetMcMaxEnergy(); //
+//    with GeV values.                                                     //
+//  Default values are the min/max energy of the MC sample.                //
+//                                                                         //
+//  With this filter the statistics of the MC sample is reduced.           //
+//  camera ver.0.6 and reflector ver.0.6 are required to fetch             //
+//   the correct MC information                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MFEnergySlope.h"
+
+#include <fstream>
+#include <TRandom.h>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+ClassImp(MFEnergySlope);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//     Constructor
+//
+MFEnergySlope::MFEnergySlope(const char *name, const char *title):
+  fNumSelectedEvts(0), fNewSlope(-1), fMcMinEnergy(-1.), fMcMaxEnergy(-1.)
+{
+  //    fContName = cname;
+  fName  = name  ? name  : "MFEnergySlope";
+  fTitle = title ? title : "Filter to select energy with given slope";
+}
+
+// --------------------------------------------------------------------------
+//
+//   Preprocess
+//  
+//  MC slope and min/max energy are read
+//  Normalization factor is computed
+//
+Int_t MFEnergySlope::PreProcess(MParList *pList)
+{
+ 
+    MMcCorsikaRunHeader *runheader = (MMcCorsikaRunHeader*)pList->FindObject("MMcCorsikaRunHeader");
+
+    if (!runheader)
+      {
+	*fLog << err << dbginf << fName << " [MMcCorsikaRunHeader] not found... aborting." << endl;
+	return kFALSE;
+      }
+    //
+    // Read info from the MC sample (it must be generated with 
+    //   reflector ver.0.6 and camera ver. 0.6)
+    //
+    fMcSlope = runheader->GetSlopeSpec();    
+    if (fMcMinEnergy<0)
+      fMcMinEnergy = runheader->GetELowLim();
+    if (fMcMinEnergy<0)
+      fMcMaxEnergy = runheader->GetEUppLim();
+
+    *fLog << inf;
+    *fLog << "MFEnergySlope::PreProcess: fetched MC info:" << endl;
+    *fLog << "  E Slope:     " << fMcSlope << endl;
+    *fLog << "  E Min:       " << fMcMinEnergy << endl;
+    *fLog << "  E Max:       " << fMcMaxEnergy << endl;
+    *fLog << "  New E Slope: " << fNewSlope << endl;
+    
+    // Slope is used with positive values in the code
+    if (fNewSlope < 0)
+      fNewSlope *= -1; 
+    if (fMcSlope < 0)
+      fMcSlope *= -1;
+
+
+  // Set normalization on energy  
+    fN0 = pow(fNewSlope>fMcSlope?fMcMinEnergy:fMcMaxEnergy,fNewSlope-fMcSlope);
+
+  *fLog << "Normalization factor:" <<fN0 << endl;
+
+  //---
+    fEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fEvt)
+      {
+	*fLog << err << dbginf << fName << " [MMcEvt] not found... aborting." << endl;
+        return kFALSE;
+      }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//  
+//  Select events randomly according to the MC ("old") and required ("new") 
+//    energy slope.
+//  Old E slope is fMcSlope
+//  New E slope is set by the user (fval; fNewSlope)
+//  If old and new energy slope are the same skip the selection. 
+//  The MC energy slope and lower and upper limits are taken from the
+//  run header (requires reflector ver.>0.6 and camera ver.>0.6) 
+//
+Int_t MFEnergySlope::Process()
+{
+  fResult = kTRUE;
+
+  // Energy slopes are the same: skip it
+  if (fNewSlope == fMcSlope)
+    return kTRUE;
+  
+  //  The value of the normalized spectrum is compared with a 
+  //   random value in [0,1]; 
+  //   if the latter is higher the event is accepted
+  const Float_t energy = fEvt->GetEnergy();
+
+  /*
+  //
+  // If energy bounds different from MC ones are selected, then
+  // events outside these bounds are rejected, as their slope has
+  // not been changed.
+  //
+  if (energy > fMcMaxEnergy || energy < fMcMinEnergy)
+    {
+      fResult = kFALSE;
+      return kTRUE;
+    }
+  */
+
+  const Float_t Nexp = fN0 * pow(energy,fMcSlope-fNewSlope);
+  const Float_t Nrnd = gRandom->Uniform();
+
+  fResult = Nexp > Nrnd;
+
+  if (!fResult)
+      return kTRUE;
+
+  fNumSelectedEvts++;
+  return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mfilter/MFEnergySlope.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFEnergySlope.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFEnergySlope.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MFEnergySlope
+#define MARS_MFEnergySlope
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFEnergySlope                                                           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MParList;
+class MMcEvt;
+class MMcCorsikaRunHeader;
+
+class MFEnergySlope : public MFilter
+{
+private:
+    Int_t fNumSelectedEvts; // counter for number of selected events
+
+    MMcEvt *fEvt;           // Events used to determin energy slope
+
+    Bool_t fResult;         // Result returned by IsExpressionTrue
+    Float_t fNewSlope;      // New slope set by user
+
+    Float_t fMcSlope;       // Original energy slope from MC data
+    Float_t fMcMinEnergy;   // Starting energy of MC data
+    Float_t fMcMaxEnergy;   // Ending energy of MC data
+
+    Float_t fN0;            // Normalization factor
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MFEnergySlope(const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    // Slope is used with positive values in the code 
+    void SetNewSlope(Float_t f) {fNewSlope = TMath::Abs(f);}
+    void SetMcSlope(Float_t f) {fMcSlope = TMath::Abs(f);}
+
+    void SetMcMinEnergy(Float_t f) {fMcMinEnergy = f;}
+    void SetMcMaxEnergy(Float_t f) {fMcMaxEnergy = f;}
+
+    ClassDef(MFEnergySlope, 0) // A Filter to select events with a given energy slope
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mfilter/MFGeomag.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFGeomag.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFGeomag.cc	(revision 9772)
@@ -0,0 +1,207 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): R.K.Bock 11/2003 <mailto:rkb@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFGeomag
+//
+//  A filter to reject Monte Carlo events based on phi/theta/charge of the
+//  incident particle. Uses tables calculated by Adrian Biland, which contain
+//  three parameters, used with rigidity (= particle momentum / charge) :
+//         rig < min_rig:   reject unconditionally
+//         rig > max_rig:   accept unconditionally
+//         rig in between:  reject it with 'probability'
+//  the two tables, for + and - rigidity, are stored in ASCII form in mfilter/
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFGeomag.h"
+
+#include <fstream>        //for ifstream
+
+#include <TRandom.h>      //for gRandom
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MFGeomag);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MFGeomag::MFGeomag(const char *name, const char *title) : fMcEvt(NULL)
+{
+    fName  = name  ? name  : "MFGeomag";
+    fTitle = title ? title : "Filter using geomagnetic field";
+
+    fGammaElectron = kFALSE;  // logical variable, will not take gammas as electrons (default)
+
+    AddToBranchList("MMcEvt.fPartId");
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFGeomag::PreProcess(MParList *pList)
+{
+    //  reading of tables (variables defined as 'private')
+    TString marssys(gSystem->Getenv("MARSSYS"));
+    if (!marssys.IsNull() && !marssys.EndsWith("/"))
+        marssys += "/";
+
+    //
+    // Read gcminus.txt
+    //
+    TString filename(marssys);
+    filename += "mfilter/gcplus.txt";
+
+    ifstream geomagp(filename);
+
+    if (!geomagp)
+    {
+        *fLog << err << "ERROR - file " << filename << " not found." << endl;
+        return kFALSE;
+    }
+    for (int i=0; i<1152; i++)
+    {
+        Float_t dummy;
+        geomagp >> dummy >> dummy >> fRigMin[i] >> fRigMax[i] >> fProb[i];
+    }
+    *fLog << inf << endl;
+    *fLog << "gcplus.txt - first line: ";
+    *fLog << Form ("FRigMin=%8f  fRigMax=%8f  fProb=%8f",
+                   fRigMin[0], fRigMax[0], fProb[0]) << endl;
+
+    //
+    // Read gcminus.txt
+    //
+    filename = marssys;
+    filename += "mfilter/gcminus.txt";
+
+    ifstream geomagm(filename);
+    if (!geomagm)
+    {
+        *fLog << err << "ERROR - file " << filename << " not found." << endl;
+        return kFALSE;
+    }
+    for (int i=1152; i<2304; i++)
+    {
+        Float_t dummy;
+        geomagm >> dummy >> dummy >> fRigMin[i] >> fRigMax[i] >> fProb[i];
+    }
+    *fLog << "gcminus.txt - first line: ";
+    *fLog << Form ("fRigMin=%8f  fRigMax=%8f  fProb=%8f",
+                   fRigMin[1152], fRigMax[1152], fProb[1152]) << endl;
+
+    //
+    if (fMcEvt)
+        return kTRUE;
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+void MFGeomag::SetGammElec()
+{
+    fGammaElectron = kTRUE;  // logical variable, will take gammas as electrons
+    *fLog <<" MFGeomag called to treat gammas as electrons" << endl;
+    return;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFGeomag::Process()
+{
+    fResult = kFALSE;
+
+    const Float_t en =  fMcEvt->GetEnergy();       // for rigidity (set P = E)
+    Float_t rig = en;
+    const Float_t az =  fMcEvt->GetTelescopePhi(); // charge theta phi are entries in table
+    const Float_t th =  fMcEvt->GetTelescopeTheta();
+
+    Int_t indadd=0;              //first part of table (positive particles)
+    switch (fMcEvt->GetPartId())
+    {
+    case MMcEvt::kGAMMA:
+        if (!fGammaElectron)     //accept gammas if not set to electrons
+            return kTRUE;
+        indadd = 1152;           //second part of table (negative particles)
+        break;
+
+    case MMcEvt::kHELIUM:
+        rig /= 2;                //double charge
+        break;
+
+    case MMcEvt::kPROTON:                //protons
+    case MMcEvt::kPOSITRON:              //positrons
+        break;
+
+    case MMcEvt::kELECTRON:              //electrons
+        indadd = 1152;           //second part of table (negative particles)
+        break;
+
+    default:
+        *fLog << err << " Unknown Monte Carlo Particle Id#: "<< fMcEvt->GetPartId() << endl;
+        return kFALSE;
+    }
+
+    // here is the cut for charged particles using the table
+
+    int it=(int)(th*11.459156);    // table steps are in 5 deg = 1/11.459 rads
+    int ia=(int)(az*11.459156);
+
+    ia = (ia+36) % 72;             // azimuth definitions differ by 180 deg
+
+    const Float_t r1=fRigMin[72*it+ia+indadd];
+    if (rig<=r1)
+    {
+        fResult=kTRUE;   // reject
+        return kTRUE;
+    }
+
+    const Float_t r2=fRigMax[72*it+ia+indadd];
+    if (rig>=r2)
+        return kTRUE;   // accept
+
+    const Float_t pr=fProb[72*it+ia+indadd];
+
+    // accept if above intermediate threshold
+    const Float_t rnd = (r2-r1)/2 * gRandom->Rndm(0);
+
+    if ((rig-r1)*pr < rnd)
+        fResult = kTRUE;                // pretty good approximation
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mfilter/MFGeomag.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFGeomag.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFGeomag.h	(revision 9772)
@@ -0,0 +1,35 @@
+#ifndef MARS_MFGeomag
+#define MARS_MFGeomag
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcEvt;
+class MParList;
+
+class MFGeomag : public MFilter
+{
+private:
+    MMcEvt *fMcEvt;
+
+    Bool_t fResult;    //!
+    Bool_t fGammaElectron;  // switches gammas to electrons
+
+    Float_t fRigMin[2*1152];    //tables to contain cut limits
+    Float_t fRigMax[2*1152];
+    Float_t fProb  [2*1152];
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MFGeomag(const char *name=NULL, const char *title=NULL);
+
+    void  SetGammElec();    // allows to use gammas like electrons
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    ClassDef(MFGeomag,0) // Filter for MC particles, by geomagnetic field
+};
+
+#endif
Index: /tags/Mars-V0.9/mfilter/MFParticleId.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFParticleId.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFParticleId.cc	(revision 9772)
@@ -0,0 +1,153 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  07/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFParticleId
+//
+//  A filter to choose between different particle types, identified by
+//  their monte carlo particle type. For a list of idetifiers see
+//  mmc/MMcEvt.h
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFParticleId.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MFParticleId);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MFParticleId::MFParticleId(const char *cname, const char type, const Int_t val,
+                           const char *name, const char *title) : fMcEvt(NULL)
+{
+    fContName = cname;
+    Init(type, val, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+MFParticleId::MFParticleId(MMcEvt *mcevt, const char type, const Int_t val,
+                           const char *name, const char *title) : fMcEvt(mcevt)
+{
+    Init(type, val, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+void MFParticleId::Init(const char type, const Int_t val,
+                        const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFParticleId";
+    fTitle = title ? title : "Filter using monte carlo particle id";
+
+    fFilterType = (type=='=' ? kEEqual : kENotEqual);
+
+    if (type!='=' && type!='!')
+        *fLog << warn << dbginf << "Warning: Neither '=' nor '!' specified... using '>'." << endl;
+
+    fValue = val;
+
+    AddToBranchList(Form("%s.fPartId", (const char*)fContName));
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MFParticleId::IsExpressionTrue() const
+{
+    return fResult;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFParticleId::PreProcess(MParList *pList)
+{
+    if (fMcEvt)
+        return kTRUE;
+
+    fMcEvt = (MMcEvt*)pList->FindObject(fContName);
+    if (fMcEvt)
+        return kTRUE;
+
+    *fLog << err << dbginf << fContName << " [MMcEvt] not found... aborting." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFParticleId::Process()
+{
+    const Int_t id = fMcEvt->GetPartId();
+
+    switch (fFilterType)
+    {
+    case kEEqual:
+        fResult = (id == fValue);
+        return kTRUE;
+    case kENotEqual:
+        fResult = (id != fValue);
+        return kTRUE;
+    }
+
+    *fLog << err << dbginf << "Operation unknown..." << endl;
+    return kFALSE;
+}
+
+void MFParticleId::StreamPrimitive(ofstream &out) const
+{
+    if (fMcEvt)
+        fMcEvt->SavePrimitive(out);
+
+    out << "   MFParticleId " << GetUniqueName() << "(";
+
+    if (fMcEvt)
+        out << "&" << fMcEvt->GetUniqueName();
+    else
+        out << "\"" << fContName << "\"";
+
+    out << ", '" << (fFilterType==kEEqual?"=":"!") << "', ";
+
+    switch (fValue)
+    {
+    case MMcEvt::kGAMMA:    out << "MMcEvt::kGAMMA";    break;
+    case MMcEvt::kPOSITRON: out << "MMcEvt::kPOSITRON"; break;
+    case MMcEvt::kELECTRON: out << "MMcEvt::kELECTRON"; break;
+    case MMcEvt::kPROTON:   out << "MMcEvt::kPROTON";   break;
+    case MMcEvt::kHELIUM:   out << "MMcEvt::kHELIUM";   break;
+    case MMcEvt::kOXYGEN:   out << "MMcEvt::kOXYGEN";   break;
+    case MMcEvt::kIRON:     out << "MMcEvt::kIRON";     break;
+    default:
+        out << fValue;
+    }
+    out << ");" << endl;
+}
Index: /tags/Mars-V0.9/mfilter/MFParticleId.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFParticleId.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFParticleId.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MFParticleId
+#define MARS_MFParticleId
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFParticleId                                                           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcEvt;
+class MParList;
+
+class MFParticleId : public MFilter
+{
+private:
+    MMcEvt *fMcEvt;
+    TString fContName;
+
+    typedef enum { kEEqual, kENotEqual } FilterType_t;
+    FilterType_t fFilterType;
+
+    Bool_t fResult;    //!
+    Int_t  fValue;
+
+    void Init(const char type, const Int_t val,
+              const char *name, const char *title);
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MFParticleId(const char *cname="MMcEvt", const char type='=', const Int_t val=0,
+                 const char *name=NULL, const char *title=NULL);
+    MFParticleId(MMcEvt *mcevt, const char type='=', const Int_t val=0,
+                 const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const;
+
+    ClassDef(MFParticleId, 1) // A Filter for the (corsika) particle Id
+};
+
+#endif
Index: /tags/Mars-V0.9/mfilter/MFSelBasic.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSelBasic.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSelBasic.cc	(revision 9772)
@@ -0,0 +1,285 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFSelBasic
+//
+//  This is a class to evaluate basic cuts
+//
+//  to be called after the calibration (when the number of photons is
+//               available for all pixels)
+//
+//  The basic cuts are :
+//
+//      remove bad runs
+//      thetamin < theta < thetamax
+//      phimin   < phi   < phimax
+//      software trigger fullfilled (with minimum no.of photons = minphotons)
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MFSelBasic.h"
+
+#include "MParList.h"
+
+#include "MPointingPos.h"
+
+#include "MCerPhotEvt.h"
+#include "MRawRunHeader.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFSelBasic);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFSelBasic::MFSelBasic(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFSelBasic";
+    fTitle = title ? title : "Filter to evaluate basic cuts";
+
+    // default values of cuts
+    SetCuts(20.0, 0.0, 60.0, 0.0, 360.0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the cut values
+// 
+//
+void MFSelBasic::SetCuts(Float_t minphotons, 
+                         Float_t thetamin, Float_t thetamax,
+                         Float_t phimin,   Float_t phimax)
+{
+    fMinPhotons = minphotons;
+
+    fThetaMin   = thetamin;
+    fThetaMax   = thetamax;
+
+    fPhiMin   = phimin;
+    fPhiMax   = phimax;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the pointers
+// 
+//
+Int_t MFSelBasic::PreProcess(MParList *pList)
+{
+    fRawRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRawRun)
+    {
+        *fLog << dbginf << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointPos = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << dbginf << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+    if (!fEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << dbginf << "MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    memset(fCut, 0, sizeof(fCut));
+
+    //-------------------------
+    *fLog << inf << "MFSelBasic cut values : fMinPhotons, fThetaMin, fThetaMax, fPhiMin, fPhiMax = ";
+    *fLog << fMinPhotons << ",  " << fThetaMin << ",  " << fThetaMax << ",  " 
+          << fPhiMin     << ",  " << fPhiMax   << endl;
+    //-------------------------
+
+    return kTRUE;
+}
+
+Int_t MFSelBasic::Set(Int_t rc)
+{
+    fCut[rc]++;
+    fResult=kTRUE;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluate basic cuts
+// 
+//     bad events    : fResult = kTRUE;
+//     good events   : fResult = kFALSE;
+//
+Int_t MFSelBasic::Process()
+{
+    const Double_t theta = fPointPos->GetZd();
+    const Double_t phi   = fPointPos->GetAz();
+
+    fResult  = kFALSE;
+
+    // remove bad runs for MC gammas
+    //if (fMcEvt->GetEnergy() == 0.0  &&  fMcEvt->GetImpact() == 0.0)
+    //{
+    //  if (fRawRun->GetRunNumber() == 601  ||
+    //      fRawRun->GetRunNumber() == 613  ||
+    //      fRawRun->GetRunNumber() == 614    )
+    //	return Set(1);
+    //}
+
+    if (theta<fThetaMin)
+        return Set(2);
+
+    if (theta>fThetaMax)
+        return Set(3);
+
+    if (phi<fPhiMin)
+        return Set(5);
+
+    if (phi>fPhiMax)
+        return Set(6);
+
+    if (!SwTrigger())
+        return Set(4);
+
+    fCut[0]++;
+
+    return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+// Software trigger
+// 
+// require 2 neighboring pixels (which are not in the outermost ring), 
+//                       each having at least 'fMinPhotons' photons
+// 
+// 
+Bool_t MFSelBasic::SwTrigger()
+{
+    const Int_t entries = fEvt->GetNumPixels();
+ 
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MCerPhotPix &pix = (*fEvt)[i];
+
+        const Int_t id = pix.GetPixId();
+        if (!pix.IsPixelUsed())
+            continue;
+
+        const Double_t photons = pix.GetNumPhotons();
+        if (photons < fMinPhotons)
+            continue;
+
+        // this pixel is used and has the required no.of photons
+        // check whether this is also true for a neigboring pixel
+
+        const MGeomPix &gpix = (*fCam)[id];
+        if ( gpix.IsInOutermostRing() )
+            continue;
+
+        const Int_t nneighbors = gpix.GetNumNeighbors();
+        for (Int_t n=0; n<nneighbors; n++)
+        {
+            const Int_t id1 =  gpix.GetNeighbor(n);
+            if ( !fEvt->IsPixelUsed(id1) )
+                continue;
+
+            const MGeomPix &gpix1 = (*fCam)[id1];
+            if ( gpix1.IsInOutermostRing() )
+                continue;
+
+            const MCerPhotPix &pix1 = *fEvt->GetPixById(id1);
+
+            const Double_t photons1 = pix1.GetNumPhotons();
+            if (photons1 >= fMinPhotons)
+                return kTRUE;
+        }
+    }
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Basic selections.
+//
+Int_t MFSelBasic::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: bad run " << endl;
+
+    *fLog << " " << setw(7) << fCut[2] << " (" << setw(3) ;
+    *fLog << (int)(fCut[2]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Zenith angle < " << fThetaMin << endl;
+
+    *fLog << " " << setw(7) << fCut[3] << " (" << setw(3) ;
+    *fLog << (int)(fCut[3]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Zenith angle > " << fThetaMax << endl;
+
+    *fLog << " " << setw(7) << fCut[5] << " (" << setw(3) ;
+    *fLog << (int)(fCut[5]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Azimuth angle < " << fPhiMin << endl;
+
+    *fLog << " " << setw(7) << fCut[6] << " (" << setw(3) ;
+    *fLog << (int)(fCut[6]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Azimuth angle > " << fPhiMax << endl;
+
+    *fLog << " " << setw(7) << fCut[4] << " (" << setw(3) ;
+    *fLog << (int)(fCut[4]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Software trigger not fullfilled" ;
+    *fLog << " (with fMinPhotons = " << fMinPhotons << ")" << endl;
+
+    *fLog << " " << fCut[0] << " (" << (int)(fCut[0]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts survived Basic selections!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mfilter/MFSelBasic.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSelBasic.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSelBasic.h	(revision 9772)
@@ -0,0 +1,73 @@
+#ifndef MARS_MFSelBasic
+#define MARS_MFSelBasic
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFSelBasic                                                           //
+//                                                                         //
+// Class to evaluate basic cuts                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MPointingPos;
+class MGeomCam;
+class MCerPhotEvt;
+//class MPedPhotCam;
+class MRawRunHeader;
+
+class MFSelBasic : public MFilter
+{
+private:
+    const MPointingPos  *fPointPos;       
+    const MGeomCam      *fCam;      // Camera Geometry 
+    const MCerPhotEvt   *fEvt;      // Cerenkov Photon Event 
+    //    const MPedPhotCam   *fPed;      // Pedestal information
+    const MRawRunHeader *fRawRun;
+
+    Float_t     fMinPhotons;
+    Float_t     fThetaMin;
+    Float_t     fThetaMax;
+
+    Float_t     fPhiMin;
+    Float_t     fPhiMax;
+
+    Int_t       fCut[7];
+
+    Bool_t      fResult;
+
+    Int_t Set(Int_t rc);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    Bool_t SwTrigger();
+
+public:
+    MFSelBasic(const char *name=NULL, const char *title=NULL);
+
+    void SetCuts(Float_t minphotons=0.0, 
+                 Float_t thetamin=0.0, Float_t thetamax=90.0,
+                 Float_t phimin=0.0,   Float_t phimax=360.0);
+
+    ClassDef(MFSelBasic, 0)   // Class to evaluate basic cuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mfilter/MFSelFinal.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSelFinal.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSelFinal.cc	(revision 9772)
@@ -0,0 +1,196 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  04/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFSelFinal
+//
+//  WHAT ARE THE FINAL CUTS?
+//
+//  This is a class to evaluate the Final Cuts
+//  (these cuts define the final sample of gammas;
+//   relevant for the calculation of the effective collection areas)
+//
+//  to be called after the calculation of the hadroness
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFSelFinal.h"
+
+#include <math.h>
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+#include "MCerPhotEvt.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MHadronness.h"
+
+ClassImp(MFSelFinal);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFSelFinal::MFSelFinal(const char *hilsrcname,
+                             const char *name, const char *title)
+    : fHilSrcName(hilsrcname), fHadronnessName("MHadronness")
+{
+    fName  = name  ? name  : "MFSelFinal";
+    fTitle = title ? title : "Class to evaluate the Final Cuts";
+
+    // default values of cuts
+    SetCuts(1.0, 100.0, 10.);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set cut values
+// 
+//
+void MFSelFinal::SetCuts(Float_t hadmax, Float_t alphamax, Float_t distmax) 
+{ 
+    fHadronnessMax =   hadmax;
+    fAlphaMax      = alphamax;
+    fDistMax       =  distmax;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the pointers
+//
+Int_t MFSelFinal::PreProcess(MParList *pList)
+{
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+      *fLog << dbginf << "MHillasSrc object " << fHilSrcName << " not found... aborting." << endl;
+      return kFALSE;
+    }
+
+    fHadronness = (MHadronness*)pList->FindObject(fHadronnessName, "MHadronness");
+    if (!fHadronness)
+    {
+      *fLog << dbginf << "MHadronness not found... aborting." << endl;
+      return kFALSE;
+    }
+
+    MGeomCam *cam = (MGeomCam*)pList->FindCreateObj("MGeomCamMagic","MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    memset(fCut, 0, sizeof(fCut));
+
+    //----------------------
+    *fLog << inf << "MFSelFinal cut values : fHadronnessMax, fAlphaMax, fDistMax = ";
+    *fLog << fHadronnessMax << ",  " << fAlphaMax << ",  " << fDistMax <<  endl;
+    //----------------------
+
+    return kTRUE;
+}
+
+Int_t MFSelFinal::Set(Int_t rc)
+{
+    fCut[rc]++;
+    fResult=kTRUE;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluate final cuts
+// 
+// if cuts are fulfilled set fResult = kTRUE
+//
+Int_t MFSelFinal::Process()
+{
+    const Double_t modalpha = fabs( fHilSrc->GetAlpha() );
+    const Double_t h = fHadronness->GetHadronness();
+
+    fResult = kFALSE;
+
+    if (h>fHadronnessMax)
+        return Set(1);
+
+    if (modalpha>fAlphaMax)
+        return Set(2);
+
+    if (fMm2Deg*fHilSrc->GetDist()>fDistMax)
+        return Set(3);
+
+    fCut[0]++;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Final selections.
+//
+Int_t MFSelFinal::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/GetNumExecutions());
+    *fLog << "%) Evts skipped due to: hadronness > "<< fHadronnessMax;
+    *fLog << " (hadronness from '" << fHadronnessName << "')" << endl;
+
+    *fLog << " " << setw(7) << fCut[2] << " (" << setw(3) ;
+    *fLog << (int)(fCut[2]*100/GetNumExecutions());
+    *fLog << "%) Evts skipped due to: |ALPHA| > " << fAlphaMax;
+    *fLog << " [degrees]" << endl;
+
+    *fLog << " " << setw(7) << fCut[3] << " (" << setw(3) ;
+    *fLog << (int)(fCut[3]*100/GetNumExecutions());
+    *fLog << "%) Evts skipped due to: DIST > " << fDistMax;
+    *fLog << " [degrees]" << endl;
+
+    *fLog << " " << fCut[0] << " (" ;
+    *fLog << (int)(fCut[0]*100/GetNumExecutions());
+    *fLog << "%) Evts survived Final selections!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mfilter/MFSelFinal.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSelFinal.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSelFinal.h	(revision 9772)
@@ -0,0 +1,70 @@
+#ifndef MARS_MFSelFinal
+#define MARS_MFSelFinal
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MSelFinal                                                               //
+//                                                                         //
+// Class to evaluate final cuts                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MHillas;
+class MHillasSrc;
+class MHadronness;
+
+class MFSelFinal : public MFilter
+{
+private:
+    MHillasSrc  *fHilSrc;       
+    MHadronness *fHadronness;       
+
+    TString      fHilName;
+    TString      fHilSrcName;
+    TString      fHadronnessName;
+ 
+    Float_t      fHadronnessMax;
+    Float_t      fAlphaMax;
+    Float_t      fDistMax;
+
+    Double_t     fMm2Deg;   // conversion mm to degrees in camera
+
+    Int_t        fCut[4];
+
+    Bool_t       fResult;
+
+    Int_t Set(Int_t rc);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t IsExpressionTrue() const  { return fResult; }
+
+public:
+    MFSelFinal(const char *HilSrcName="MHillasSrc",
+                  const char *name=NULL, const char *title=NULL);
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+
+    void SetCuts(Float_t hadmax, Float_t alphamax, Float_t distmax); 
+
+    ClassDef(MFSelFinal, 0)   // Class to evaluate final cuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mfilter/MFSelStandard.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSelStandard.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSelStandard.cc	(revision 9772)
@@ -0,0 +1,224 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFSelStandard
+//
+//  This is a class to evaluate the Standard Cuts
+//
+//  WHAT ARE THE STANDARD CUTS?                                                                       //
+//
+//  to be called after the calculation of the image parameters
+//               before the g/h separation
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MFSelStandard.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotEvt.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+
+ClassImp(MFSelStandard);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFSelStandard::MFSelStandard(const char *hilsrcname,
+                                   const char *name, const char *title)
+    : fHilName("MHillas"), fHilSrcName(hilsrcname), fImgParName("MNewImagePar")
+{
+    fName  = name  ? name  : "MFSelStandard";
+    fTitle = title ? title : "Class to evaluate the Standard Cuts";
+
+    // default values of cuts
+    SetCuts(92, 4, 60, 0.4, 1.05, 0.0, 0.0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the values for the cuts 
+// 
+//
+void MFSelStandard::SetCuts(Float_t usedpixelsmax, Float_t corepixelsmin,
+                               Float_t sizemin, Float_t distmin, Float_t distmax,
+                               Float_t lengthmin, Float_t widthmin)
+{ 
+    fUsedPixelsMax = usedpixelsmax;
+    fCorePixelsMin = corepixelsmin;
+    fSizeMin       = sizemin;
+    fDistMin       = distmin;
+    fDistMax       = distmax;
+    fLengthMin     = lengthmin;
+    fWidthMin      = widthmin;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// MISSING
+//
+Int_t MFSelStandard::PreProcess(MParList *pList)
+{
+    fHil = (MHillas*)pList->FindObject(fHilName, "MHillas");
+    if (!fHil)
+    {
+        *fLog << err << fHilName << " [MHillas] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << fHilSrcName << " [MHillasSrc] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewImgPar = (MNewImagePar*)pList->FindObject(fImgParName, "MNewImagePar");
+    if (!fNewImgPar)
+    {
+        *fLog << err << fImgParName << " [MNewImagePar] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    memset(fCut, 0, sizeof(fCut));
+
+    //--------------------
+    *fLog << inf << "MFSelStandard cut values : fUsedPixelsMax, fCorePixelsMin = ";
+    *fLog << fUsedPixelsMax << ",  " << fCorePixelsMin << endl;
+    *fLog << inf << "     fSizeMin, fDistMin, fDistMax = " << fSizeMin ;
+    *fLog << ",  " << fDistMin << ",  " << fDistMax << endl;
+    *fLog << inf << "     fLengthMin, fWidthMin = " << fLengthMin ;
+    *fLog << ",  " << fWidthMin << endl;
+    //--------------------
+
+    return kTRUE;
+}
+
+Bool_t MFSelStandard::Set(Int_t rc)
+{
+    fResult = kTRUE;
+    fCut[rc]++;
+    return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+// Evaluate standard cuts
+// 
+// if selections are fulfilled set fResult = kTRUE;
+// 
+//
+Int_t MFSelStandard::Process()
+{
+    const Double_t length     = fHil->GetLength() * fMm2Deg;
+    const Double_t width      = fHil->GetWidth()  * fMm2Deg;
+    const Double_t dist       = fHilSrc->GetDist()* fMm2Deg;
+    //const Double_t delta      = fHil->GetDelta()  * kRad2Deg;
+    const Double_t size       = fHil->GetSize();
+    const Int_t numusedpixels = fNewImgPar->GetNumUsedPixels();
+    const Int_t numcorepixels = fNewImgPar->GetNumCorePixels();
+
+    fResult  = kFALSE;
+
+    if (numusedpixels>=fUsedPixelsMax || numcorepixels<fCorePixelsMin)
+        return Set(1);
+
+    if (size<=fSizeMin )
+        return Set(2);
+
+    if (dist<fDistMin || dist>fDistMax)
+        return Set(3);
+
+    if (length<=fLengthMin || width<=fWidthMin)
+        return Set(4);
+
+    fCut[0]++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Standard selections.
+//
+Int_t MFSelStandard::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3);
+    *fLog << (int)(fCut[1]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: Used pixels >= " << fUsedPixelsMax ;
+    *fLog << " or Core pixels < " << fCorePixelsMin << endl;
+
+    *fLog << " " << setw(7) << fCut[2] << " (" << setw(3) ;
+    *fLog << (int)(fCut[2]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: SIZE <= " << fSizeMin << endl;
+
+    *fLog << " " << setw(7) << fCut[3] << " (" << setw(3) ;
+    *fLog << (int)(fCut[3]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: DIST < " << fDistMin;
+    *fLog << " or DIST > " << fDistMax << endl;
+
+    *fLog << " " << setw(7) << fCut[4] << " (" << setw(3) ;
+    *fLog << (int)(fCut[4]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts skipped due to: LENGTH <= " << fLengthMin;
+    *fLog << " or WIDTH <= " << fWidthMin << endl;
+
+    *fLog << " " << fCut[0] << " (" ;
+    *fLog << (int)(fCut[0]*100/GetNumExecutions()) ;
+    *fLog << "%) Evts survived Standard selections!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mfilter/MFSelStandard.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSelStandard.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSelStandard.h	(revision 9772)
@@ -0,0 +1,78 @@
+#ifndef MARS_MFSelStandard
+#define MARS_MFSelStandard
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFSelStandard                                                        //
+//                                                                         //
+// Class to evaluate standard cuts                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MHillas;
+class MHillasSrc;
+class MNewImagePar;
+
+class MFSelStandard : public MFilter
+{
+private:
+    MHillas      *fHil;
+    MHillasSrc   *fHilSrc;
+    MNewImagePar *fNewImgPar;
+
+    TString      fHilName;
+    TString      fHilSrcName;
+    TString      fImgParName;
+
+    Float_t      fUsedPixelsMax;
+    Float_t      fCorePixelsMin;
+    Float_t      fSizeMin;
+    Float_t      fDistMin;
+    Float_t      fDistMax;
+    Float_t      fLengthMin;
+    Float_t      fWidthMin;
+
+    Double_t     fMm2Deg;    // conversion mm to degrees in camera
+
+    Int_t        fCut[5];
+
+    Bool_t       fResult;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t IsExpressionTrue() const  { return fResult; }
+
+    Bool_t Set(Int_t rc);
+
+public:
+    MFSelStandard(const char *HilSrcName="MHillasSrc",
+                     const char *name=NULL, const char *title=NULL);
+
+    void SetHillasName(const char *name) { fHilName = name; }
+    void SetImgParName(const char *name) { fImgParName = name; }
+
+    void SetCuts(Float_t usedpixelsmax, Float_t corepixelsmin,
+                 Float_t sizemin, Float_t distmin, Float_t distmax,
+                 Float_t lengthmin, Float_t widthmin);
+
+    ClassDef(MFSelStandard, 0)   // Class to evaluate standard cuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mfilter/MFSoftwareTrigger.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSoftwareTrigger.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSoftwareTrigger.cc	(revision 9772)
@@ -0,0 +1,500 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFSoftwareTrigger
+//
+//  This is a class to evaluate a software trigger
+//
+//  The number of required pixels is setup by:
+//   SetNumNeighbors(4)   // default
+//
+//  The Threshold is setup by:
+//    SetThreshold(5)     // default
+//
+//  Time window for coincidence:
+//    SetTimeWindow(3.3)
+// To switch off time-coincidence use
+//    SetTimeWindow(-1)
+//   or
+//    SetTimeWindow()
+//
+//  kSinglePixelsNeighbors <default>
+//  ----------------------
+//    Checks whether there is at least one pixel above threshold which
+//    has fNumNeighbors direct neighbors which are also above threshold.
+//    The outermost ring of pixels is ignord. Only 'used' pixels are
+//    taken into account.
+//
+//  kAnyPattern 
+//  -----------
+//    Checks whether it find a cluster of pixels above fThreshold which
+//    has a size bigger/equal than fNumNeighbors. The layout (pattern) of
+//    the cluster is ignored. Unmapped pixels are ignored.
+//
+//  WARNING: Using trigger type kAllPattern resets the BIT(21) bit
+//           of all pixels in MSignalCam
+//
+//
+//  Input:
+//    MSignalCam
+//    MGeomCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFSoftwareTrigger.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalCam.h"
+//#include "MArrivalTime.h"
+
+ClassImp(MFSoftwareTrigger);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFSoftwareTrigger::MFSoftwareTrigger(const char *name, const char *title)
+    : fCam(NULL), fEvt(NULL), fThreshold(5),
+    fTimeWindow(0.5), fNumNeighbors(4), fType(kSinglePixelNeighbors)
+{
+    fName  = name  ? name  : "MFSoftwareTrigger";
+    fTitle = title ? title : "Filter for software trigger";
+}
+
+// --------------------------------------------------------------------------
+//
+// This function recursively finds all pixels of one island and sets
+// BIT(14) for the pixel.
+//
+//  1) Check whether a pixel with the index idx exists, is unused
+//     and has not yet BIT(14) set
+//  2) Set BIT(14) to the pixel
+//  3) Loop over all its neighbors taken from the geometry geom. For all
+//     neighbors recursively call this function (CountPixels)
+//  4) Sum the number of valid neighbors newly found
+//
+// Returns the size of the cluster
+//
+Int_t MFSoftwareTrigger::CountPixels(Int_t idx, Float_t tm0) const
+{
+    // Try to get the pixel information of a pixel with this index
+    MSignalPix *pix = fEvt->GetPixById(idx);
+
+    // If a pixel with this index is not existing... do nothing.
+    if (!pix)
+        return 0;
+
+    // If pixel already assigned to a cluster
+    if (pix->TestBit(kWasChecked))
+        return 0;
+
+    if (pix->IsPixelUnmapped())
+        return 0;
+
+    // Assign the new island number num to this used pixel
+    pix->SetBit(kWasChecked);
+
+    // Get the size of this pixel and check threshold
+    const Double_t size = pix->GetNumPhotons()*fCam->GetPixRatio(idx);
+    if (size<fThreshold)
+        return 0;
+
+    const Float_t tm1 = pix->GetArrivalTime();
+    if (TMath::Abs(tm1-tm0)>fTimeWindow)
+        return 0;
+
+    //pix->SetBit(kAboveThreshold);
+
+    Int_t num = 1;
+
+    // Get the geometry information (neighbors) of this pixel
+    const MGeomPix &gpix = (*fCam)[idx];
+
+    // Now do the same with all its neighbors and sum the
+    // sizes which they correspond to
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+        num += CountPixels(gpix.GetNeighbor(i), tm1);
+
+    // return size of this (sub)cluster
+    return num;
+}
+/*
+Int_t MFSoftwareTrigger::CountCoincidencePixels(Int_t idx) const
+{
+    // Try to get the pixel information of a pixel with this index
+    MSignalPix *pix = fEvt->GetPixById(idx);
+
+    // If a pixel with this index is not existing... do nothing.
+    if (!pix)
+        return 0;
+
+    // If pixel already assigned to a cluster
+    if (pix->TestBit(kWasChecked))
+        return 0;
+
+    if (pix->IsPixelUnmapped())
+        return 0;
+
+    // Assign the new island number num to this used pixel
+    pix->SetBit(kWasChecked);
+
+    // Get the size of this pixel and check threshold
+    const Double_t size = pix->GetNumPhotons();
+    if (size<fThreshold)
+        return 0;
+
+    Int_t num = 1;
+
+    // Get the geometry information (neighbors) of this pixel
+    const MGeomPix &gpix = (*fCam)[idx];
+
+    // Now do the same with all its neighbors and sum the
+    // sizes which they correspond to
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+        num += CountPixels(gpix.GetNeighbor(i));
+
+    // return size of this (sub)cluster
+    return num;
+}
+*/
+void MFSoftwareTrigger::ResetBits(Int_t bits) const
+{
+    TObject *obj=0;
+
+    TIter Next(*fEvt);
+    while ((obj=Next()))
+        obj->ResetBit(bits);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check if there is at least one pixel which fullfills the condition
+//
+Bool_t MFSoftwareTrigger::ClusterTrigger() const
+{
+    ResetBits(kWasChecked);
+
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        const MSignalPix &pix = (*fEvt)[idx];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        // Check if trigger condition is fullfilled for this pixel
+        if (CountPixels(idx, pix.GetArrivalTime()) >= fNumNeighbors)
+            return kTRUE;
+    }
+
+/*
+    // Reset bit
+    MSignalPix *pix=0;
+
+    // We could loop over all indices which looks more straight
+    // forward but should be a lot slower (assuming zero supression)
+    TIter Next(*fEvt);
+    while ((pix=static_cast<MSignalPix*>(Next())))
+    {
+        // Check if trigger condition is fullfilled for this pixel
+        const Int_t idx = pix->GetPixId();
+        if (CountPixels(idx, (*fTme)[idx]) >= fNumNeighbors)
+            return kTRUE;
+    }
+  */
+    return kFALSE;
+}
+/*
+Int_t MFSoftwareTrigger::CheckCoincidence(Int_t idx, Float_t tm0) const
+{
+    // Try to get the pixel information of a pixel with this index
+    MSignalPix *pix = fEvt->GetPixById(idx);
+
+    // If a pixel with this index is not existing... do nothing.
+    if (!pix)
+        return 0;
+
+    // If pixel already assigned to a cluster
+    if (pix->TestBit(kWasChecked))
+        return 0;
+
+    if (pix->IsPixelUnmapped())
+        return 0;
+
+    // Assign the new island number num to this used pixel
+    pix->SetBit(kWasChecked);
+
+    const Double_t size = pix->GetNumPhotons();
+    if (size<fThreshold)
+        return 0;
+
+    const Float_t tm1 = (*fTme)[idx];
+    if (TMath::Abs(tm1-tm0)>fTimeWindow)
+        return 0;
+
+    pix->SetBit(kIsCoincident);
+
+
+    Int_t num = 1;
+
+    // Get the geometry information (neighbors) of this pixel
+    const MGeomPix &gpix = (*fCam)[idx];
+
+    Int_t cnt = 0;
+
+    // Now do the same with all its neighbors and sum the
+    // sizes which they correspond to
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+    {
+        const Int_t rc = CheckCoincidence(gpix.GetNeighbor(i), tm0);
+        if (fEvt->GetPixById(gpix.GetNeighbor(i))->TestBit(kIsCoincident))
+            cnt++;
+        num += rc;
+    }
+
+    // return size of this (sub)cluster
+    return cnt<2 ? 0 : num;
+
+}
+
+Bool_t MFSoftwareTrigger::MagicLvl1Trigger() const
+{
+    // Reset bit
+    MSignalPix *pix=0;
+
+    // We could loop over all indices which looks more straight
+    // forward but should be a lot slower (assuming zero supression)
+    TIter Next(*fEvt);
+    while ((pix=static_cast<MSignalPix*>(Next())))
+    {
+        ResetBits(kWasChecked|kIsCoincident);
+
+        const Int_t idx = pix->GetPixId();
+        if (CheckCoincidence(idx, (*fTme)[idx])<fNumNeighbors)
+            continue;
+
+        return kTRUE;
+    }
+    return kFALSE;
+}
+*/
+
+const MSignalPix *MFSoftwareTrigger::CheckPixel(Int_t i) const
+{
+    const MSignalPix &pix = (*fEvt)[i];
+
+    if (!pix.IsPixelUsed())
+        return NULL;
+
+    if (pix.GetNumPhotons()*fCam->GetPixRatio(i)<fThreshold)
+        return NULL;
+
+    if ((*fCam)[i].IsInOutermostRing())
+        return NULL;
+
+    return &pix;
+}
+
+// --------------------------------------------------------------------------
+//
+// Software single pixel coincidence trigger
+//
+Bool_t MFSoftwareTrigger::SwTrigger() const
+{
+    const Int_t entries = fEvt->GetNumPixels();
+ 
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MSignalPix *pix0 = CheckPixel(i);
+        if (!pix0)
+            continue;
+
+        Int_t num = 1;
+
+        const MGeomPix &gpix = (*fCam)[i];
+
+        const Int_t nneighbors = gpix.GetNumNeighbors();
+        for (Int_t n=0; n<nneighbors; n++)
+        {
+            const Int_t idx1 = gpix.GetNeighbor(n);
+
+            const MSignalPix *pix1 = CheckPixel(idx1);
+            if (!pix1)
+                continue;
+
+            const Float_t t0 = pix0->GetArrivalTime();
+            const Float_t t1 = pix1->GetArrivalTime();
+
+            if (TMath::Abs(t0-t1)>fTimeWindow)
+                continue;
+
+            if (++num==fNumNeighbors)
+                return kTRUE;
+        }
+    }
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Request pointer to MSignalCam and MGeomCam from paremeter list
+//
+Int_t MFSoftwareTrigger::PreProcess(MParList *pList)
+{
+    fEvt = (MSignalCam*)pList->FindObject("MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << "MSignalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    memset(fCut, 0, sizeof(fCut));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluate software trigger
+//
+Int_t MFSoftwareTrigger::Process()
+{
+    switch (fType)
+    {
+    case kSinglePixelNeighbors:
+        fResult = SwTrigger();
+        break;
+    case kAnyPattern:
+        fResult = ClusterTrigger();
+        break;
+    }
+
+    fCut[fResult ? 0 : 1]++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Basic selections.
+//
+Int_t MFSoftwareTrigger::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    TString type;
+    switch (fType)
+    {
+    case kSinglePixelNeighbors:
+        type = " single pixel trigger";
+        break;
+    case kAnyPattern:
+        type = " any pattern trigger";
+        break;
+    }
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << " Threshold=" << fThreshold << ", Number=" << (int)fNumNeighbors;
+    if (fTimeWindow>0)
+        *fLog << ", Time Window=" << fTimeWindow;
+    *fLog << endl;
+    *fLog << dec << setfill(' ');
+
+    *fLog << " " << setw(7) << fCut[0] << " (" << setw(3) ;
+    *fLog << (int)(fCut[0]*100/GetNumExecutions());
+    *fLog << "%) Evts fullfilled" << type << endl;
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/GetNumExecutions());
+    *fLog << "%) Evts didn't fullfill" << type << "."  << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MFSoftwareTrigger.Threshold:    5
+//   MFSoftwareTrigger.NumNeighbors: 4
+//   MFSoftwareTrigger.TimeWindow: 3.3
+//   MFSoftwareTrigger.TriggerType: SinglePixel, AnyPattern
+//
+// To switch off time-coincidence use
+//   MFSoftwareTrigger.TimeWindow: -1
+//
+Int_t MFSoftwareTrigger::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "Threshold", print))
+    {
+        rc = kTRUE;
+        SetThreshold(GetEnvValue(env, prefix, "Threshold", fThreshold));
+    }
+    if (IsEnvDefined(env, prefix, "NumNeighbors", print))
+    {
+        rc = kTRUE;
+        SetNumNeighbors(GetEnvValue(env, prefix, "NumNeighbors", fNumNeighbors));
+    }
+    if (IsEnvDefined(env, prefix, "TimeWindow", print))
+    {
+        rc = kTRUE;
+        SetTimeWindow(GetEnvValue(env, prefix, "TimeWindow", fTimeWindow));
+    }
+
+    if (IsEnvDefined(env, prefix, "TriggerType", print))
+    {
+        TString dat = GetEnvValue(env, prefix, "TriggerType", "");
+        dat = dat.Strip(TString::kBoth);
+        dat.ToLower();
+
+        if (dat == (TString)"singlepixel")
+            SetTriggerType(kSinglePixelNeighbors);
+        if (dat == (TString)"anypattern")
+            SetTriggerType(kAnyPattern);
+
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: /tags/Mars-V0.9/mfilter/MFSoftwareTrigger.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSoftwareTrigger.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSoftwareTrigger.h	(revision 9772)
@@ -0,0 +1,72 @@
+#ifndef MARS_MFSoftwareTrigger
+#define MARS_MFSoftwareTrigger
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcEvt;
+class MGeomCam;
+class MSignalCam;
+class MSignalPix;
+class MArrivalTime;
+
+class MFSoftwareTrigger : public MFilter
+{
+public:
+    enum TriggerType_t {
+        kSinglePixelNeighbors,
+        kAnyPattern/*,
+        kMagicLvl1*/
+    };
+
+private:
+    const MGeomCam     *fCam; // Camera Geometry
+    const MSignalCam   *fEvt; // Cerenkov Photon Event
+    const MArrivalTime *fTme;
+
+    Float_t     fThreshold;     // nuber of minimum required photons
+    Float_t     fTimeWindow;    // Window for time coincidence
+    Byte_t      fNumNeighbors;  // number of required neighbours
+
+    Int_t       fCut[2];
+
+    Bool_t      fResult;
+
+    TriggerType_t fType;
+
+    enum {
+        kWasChecked     = BIT(21),
+        kAboveThreshold = BIT(22),
+        kIsCoincident   = BIT(23)
+    };
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    void ResetBits(Int_t bits) const;
+    const MSignalPix *CheckPixel(Int_t i) const;
+    Bool_t SwTrigger() const;
+    Bool_t SwCoincidence() const;
+    //Int_t CheckCoincidence(Int_t idx, Float_t tm0) const;
+    //Bool_t MagicLvl1Trigger() const;
+    Int_t  CountPixels(Int_t idx, Float_t tm) const;
+    Bool_t ClusterTrigger() const;
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+public:
+    MFSoftwareTrigger(const char *name=NULL, const char *title=NULL);
+
+    void SetThreshold(Float_t min)          { fThreshold    = min; }
+    void SetNumNeighbors(Byte_t num)        { fNumNeighbors = num; }
+    void SetTimeWindow(Float_t win=-1)      { fTimeWindow   = win; }
+    void SetTriggerType(TriggerType_t type) { fType = type; }
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MFSoftwareTrigger, 0) // Filter for software trigger
+};
+
+#endif
Index: /tags/Mars-V0.9/mfilter/MFSupercuts.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSupercuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSupercuts.cc	(revision 9772)
@@ -0,0 +1,318 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFSupercuts
+//
+//   this class calculates the hadronness for the supercuts
+//   the parameters of the supercuts are taken
+//                  from the container MSupercuts
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFSupercuts.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "TFile.h"
+#include "TArrayD.h"
+
+#include "MParList.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MGeomCam.h"
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFSupercuts);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+
+MFSupercuts::MFSupercuts(const char *name, const char *title)
+    : fHil(0), fHilSrc(0), fHilExt(0), fNewPar(0), fMatrix(0), fVariables(84)
+{
+    fName  = name  ? name  : "MFSupercuts";
+    fTitle = title ? title : "Class to evaluate the Supercuts";
+
+    fMatrix = NULL;
+
+    AddToBranchList("MHillas.fWidth");
+    AddToBranchList("MHillas.fLength");
+    AddToBranchList("MHillasSrc.fDist");
+    AddToBranchList("MHillas.fSize");
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFSupercuts::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    if (fMatrix)
+        return kTRUE;
+
+    //-----------------------------------------------------------
+    fHil = (MHillas*)pList->FindObject("MHillas");
+    if (!fHil)
+    {
+        *fLog << err << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject("MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << "MHillasExt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject("MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << "MHillasSrc not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject("MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << "MNewImagePar not found... aborting." << endl;
+        return kFALSE;
+    }
+/*
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+  */
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MFSupercuts::GetVal(Int_t i) const
+{
+    return (*fMatrix)[fMap[i]];
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam::Process
+// will take the values from the matrix instead of the containers.
+//
+void MFSupercuts::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    //fMap[0]  = fMatrix->AddColumn("MPointingPos.fZd");
+    fMap[0]  = fMatrix->AddColumn("MHillas.fWidth*MGeomCam.fConvMm2Deg");
+    fMap[1]  = fMatrix->AddColumn("MHillas.fLength*MGeomCam.fConvMm2Deg");
+    fMap[2]  = fMatrix->AddColumn("MHillasSrc.fDist*MGeomCam.fConvMm2Deg");
+    fMap[3]  = fMatrix->AddColumn("log10(MHillas.fSize)");
+    //fMap[7]  = fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+    /*
+     fMap[8]  = fMatrix->AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+     fMap[9]  = fMatrix->AddColumn("MNewImagePar.fConc");
+     fMap[10] = fMatrix->AddColumn("MNewImagePar.fLeakage1");
+     */
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculation of upper and lower limits
+//
+Double_t MFSupercuts::CtsMCut(const Double_t* a,  Double_t ls, Double_t ct,
+                                    Double_t ls2, Double_t dd2) const
+{
+    // define cut-function
+    //
+    //    dNOMLOGSIZE = 5.0 (=log(150.0)
+    //    dNOMCOSZA   = 1.0
+    //
+    //      a: array of cut parameters
+    //     ls: log(SIZE) - dNOMLOGSIZE
+    //    ls2: ls^2
+    //     ct: Cos(ZA.) - dNOMCOSZA
+    //    dd2: DIST^2
+    const Double_t limit =
+        a[0] + a[1] * dd2 + a[2] * ct  +
+        ls  * (a[3] + a[4] * dd2 + a[5] * ct) +
+        ls2 * (a[6] + a[7] * dd2);
+
+    return limit;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Evaluate dynamical supercuts 
+// 
+//          set hadronness to 0.25 if cuts are fullfilled
+//                            0.75 otherwise
+//
+Int_t MFSupercuts::Process()
+{
+    //  const Double_t kNomLogSize = 4.1;
+    //  const Double_t kNomCosZA   = 1.0;
+
+    //  const Double_t theta   = fMatrix ? GetVal(0) : fMcEvt->GetTelescopeTheta();
+    //  const Double_t meanx   = fMatrix ? GetVal(4) : fHil->GetMeanX()*fMm2Deg;
+    //  const Double_t meany   = fMatrix ? GetVal(5) : fHil->GetMeanY()*fMm2Deg;
+    //  const Double_t asym0   = fMatrix ? GetVal(8) : TMath::Sign(fHilExt->GetM3Long(), fHilSrc->GetCosDeltaAlpha());;
+    //  const Double_t conc    = fMatrix ? GetVal(9) : fNewPar->GetConc();
+    //  const Double_t leakage = fMatrix ? GetVal(10): fNewPar->GetLeakage1();
+    //  const Double_t asym    = asym0   * fMm2Deg;
+
+    const Double_t width   = fMatrix ? GetVal(0) : fHil->GetWidth()*fMm2Deg;
+    const Double_t length  = fMatrix ? GetVal(1) : fHil->GetLength()*fMm2Deg;
+    const Double_t dist    = fMatrix ? GetVal(2) : fHilSrc->GetDist()*fMm2Deg;
+    const Double_t lgsize  = fMatrix ? GetVal(3) : log10(fHil->GetSize());
+
+    const Double_t dist2     = dist*dist;
+    const Double_t lgsize2   = lgsize * lgsize;
+    const Double_t cost      = 0; // cos(theta*TMath::DegToRad()) - kNomCosZA;
+
+    fResult =
+        // Length cuts
+        length > CtsMCut(fVariables.GetArray()+ 0, lgsize, cost, lgsize2, dist2) &&
+        length < CtsMCut(fVariables.GetArray()+ 8, lgsize, cost, lgsize2, dist2) &&
+        // Width cuts
+        width  > CtsMCut(fVariables.GetArray()+16, lgsize, cost, lgsize2, dist2) &&
+        width  < CtsMCut(fVariables.GetArray()+24, lgsize, cost, lgsize2, dist2) &&
+        // Dist cuts
+        dist   > CtsMCut(fVariables.GetArray()+32, lgsize, cost, lgsize2, dist2) &&
+        dist   < CtsMCut(fVariables.GetArray()+40, lgsize, cost, lgsize2, dist2);
+
+        /*
+         asym    < CtsMCut(&fVariables[42], dmls, dmcza, dmls2, dd2) &&
+         asym    > CtsMCut(&fVariables[49], dmls, dmcza, dmls2, dd2) &&
+
+         conc    < CtsMCut(&fVariables[56], dmls, dmcza, dmls2, dd2) &&
+         conc    > CtsMCut(&fVariables[63], dmls, dmcza, dmls2, dd2) &&
+
+         leakage < CtsMCut(&fVariables[70], dmls, dmcza, dmls2, dd2) &&
+         leakage > CtsMCut(&fVariables[77], dmls, dmcza, dmls2, dd2))
+         */
+
+    return kTRUE;
+}
+
+TString MFSupercuts::GetDataMember() const
+{
+    return "MHillas.fWidth,MHillas.fLength,MHillasSrc.fDist,MHillas.fSize";
+}
+
+void MFSupercuts::SetVariables(const TArrayD &arr)
+{
+    fVariables = arr;
+}
+
+Bool_t MFSupercuts::CoefficentsRead(const char *fname)
+{
+    ifstream fin(fname);
+    if (!fin)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    for (int i=0; i<fVariables.GetSize(); i++)
+    {
+        fin >> fVariables[i];
+        if (!fin)
+        {
+            *fLog << err << "ERROR - Not enough coefficients in file " << fname << endl;
+            return kERROR;
+        }
+    }
+    return kTRUE;
+}
+
+Bool_t MFSupercuts::CoefficentsWrite(const char *fname) const
+{
+    ofstream fout(fname);
+    if (!fout)
+    {
+        *fLog << err << "Cannot open file " << fname << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    for (int i=0; i<fVariables.GetSize(); i++)
+        fout << setw(11) << fVariables[i] << endl;
+
+    return kTRUE;
+}
+
+Int_t MFSupercuts::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (IsEnvDefined(env, prefix, "File", print))
+    {
+        const TString fname = GetEnvValue(env, prefix, "File", "");
+        if (!CoefficentsRead(fname))
+            return kERROR;
+
+        return kTRUE;
+    }
+
+    Bool_t rc = kFALSE;
+    for (int i=0; i<fVariables.GetSize(); i++)
+    {
+        if (IsEnvDefined(env, prefix, Form("Param%d", i), print))
+        {
+            fVariables[i] = GetEnvValue(env, prefix, Form("Param%d", i), 0);
+            rc = kTRUE;
+        }
+    }
+    return rc;
+}
Index: /tags/Mars-V0.9/mfilter/MFSupercuts.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFSupercuts.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFSupercuts.h	(revision 9772)
@@ -0,0 +1,67 @@
+#ifndef MARS_MFSupercuts
+#define MARS_MFSupercuts
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MParList;
+class MHillas;
+class MHillasSrc;
+class MHillasExt;
+class MNewImagePar;
+class MCerPhotEvt;
+class MGeomCam;
+class MHadronness;
+class MHMatrix;
+
+class MFSupercuts : public MFilter
+{
+private:
+    MHillas       *fHil;        //!
+    MHillasSrc    *fHilSrc;     //!
+    MHillasExt    *fHilExt;     //!
+    MNewImagePar  *fNewPar;     //!
+
+    Double_t       fMm2Deg;     //!
+    Bool_t fResult;             //!
+
+    Int_t     fMap[11];         //!
+    MHMatrix *fMatrix;          //!
+
+    TArrayD fVariables;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    Double_t GetVal(Int_t i) const;
+
+    Double_t CtsMCut(const Double_t* a, Double_t ls, Double_t ct,
+                     Double_t ls2, Double_t dd2) const;
+
+    TString GetDataMember() const;
+    //TString GetRule() const { return "<MFSupercuts>"; }
+
+public:
+    MFSupercuts(const char *name=NULL, const char *title=NULL);
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping() { InitMapping(NULL); }
+
+    void SetVariables(const TArrayD &arr);
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    Bool_t CoefficentsRead(const char *fname);
+    Bool_t CoefficentsWrite(const char *fname) const;
+
+    ClassDef(MFSupercuts, 0) // A filter to evaluate the Supercuts
+};
+
+#endif
Index: /tags/Mars-V0.9/mfilter/MFTriggerLvl1.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFTriggerLvl1.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFTriggerLvl1.cc	(revision 9772)
@@ -0,0 +1,135 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  07/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MFTriggerLvl1                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MFTriggerLvl1.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcTrig.hxx"
+
+ClassImp(MFTriggerLvl1);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MFTriggerLvl1::MFTriggerLvl1(const char *cname, const char type, const Int_t val,
+                             const char *name, const char *title) : fMcTrig(NULL)
+{
+    fContName = cname;
+    Init(type, val, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+MFTriggerLvl1::MFTriggerLvl1(MMcTrig *mctrig, const char type, const Int_t val,
+                             const char *name, const char *title) : fMcTrig(mctrig)
+{
+    Init(type, val, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+void MFTriggerLvl1::Init(const char type, const Int_t val,
+                         const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFTriggerLvl1";
+    fTitle = title ? title : "Filter using number of 1st level triggers";
+
+    fFilterType = (type=='<' ? kELowerThan : kEGreaterThan);
+
+    if (type!='<' && type!='>')
+        *fLog << warn << dbginf << "Warning: Neither '<' nor '>' specified... using '>'." << endl;
+
+    fValue = val;
+
+    AddToBranchList(Form("%s.fNumFirstLevel", (const char*)fContName));
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MFTriggerLvl1::IsExpressionTrue() const
+{
+    return fResult;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFTriggerLvl1::PreProcess(MParList *pList)
+{
+    if (fMcTrig)
+        return kTRUE;
+
+    fMcTrig = (MMcTrig*)pList->FindObject(fContName);
+    if (fMcTrig)
+        return kTRUE;
+
+    *fLog << err << dbginf << fContName << " [MMcTrig] not found... aborting." << endl;
+        return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFTriggerLvl1::Process()
+{
+    const Int_t lvl1 = fMcTrig->GetFirstLevel();
+
+    switch (fFilterType)
+    {
+    case kELowerThan:
+        fResult = (lvl1 < fValue);
+        break;
+    case kEGreaterThan:
+        fResult = (lvl1 > fValue);
+        break;
+    }
+
+    return kTRUE;
+}
+
+void MFTriggerLvl1::StreamPrimitive(ofstream &out) const
+{
+    if (fMcTrig)
+        fMcTrig->SavePrimitive(out);
+
+    out << "   MFTriggerLvl1 " << GetUniqueName() << "(";
+
+    if (fMcTrig)
+        out << "&" << fMcTrig->GetUniqueName();
+    else
+        out << "\"" << fContName << "\"";
+
+    out << ", '" << (fFilterType==kELowerThan?"<":">") << "', " << fValue << ");" << endl;
+
+}
Index: /tags/Mars-V0.9/mfilter/MFTriggerLvl1.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFTriggerLvl1.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFTriggerLvl1.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MFTriggerLvl1
+#define MARS_MFTriggerLvl1
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFTriggerLvl1                                                           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcTrig;
+class MParList;
+
+class MFTriggerLvl1 : public MFilter
+{
+private:
+    MMcTrig *fMcTrig;
+    TString fContName;
+
+    typedef enum { kELowerThan, kEGreaterThan } FilterType_t;
+    FilterType_t fFilterType; 
+
+    Bool_t fResult;             //!
+    Int_t  fValue;
+
+    void Init(const char type, const Int_t val,
+              const char *name, const char *title);
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MFTriggerLvl1(const char *cname="MMcTrig", const char type='>', const Int_t val=0,
+                  const char *name=NULL, const char *title=NULL);
+    MFTriggerLvl1(MMcTrig *mctrig, const char type='>', const Int_t val=0,
+                  const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const;
+
+    ClassDef(MFTriggerLvl1, 1) // A Filter for the Level 1 Trigger
+};
+
+#endif
Index: /tags/Mars-V0.9/mfilter/MFTriggerLvl2.cc
===================================================================
--- /tags/Mars-V0.9/mfilter/MFTriggerLvl2.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFTriggerLvl2.cc	(revision 9772)
@@ -0,0 +1,143 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Antonio Stamerra  02/2003 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MFTriggerLvl2                                                         //
+//                                                                         //
+//  A Filter for the 2nd Level trigger, using the MMcTriggerLvl2 Class     //
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFTriggerLvl2.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcTriggerLvl2.h"
+
+ClassImp(MFTriggerLvl2);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MFTriggerLvl2::MFTriggerLvl2(const char *cname, const char type, const Int_t val,
+                             const char *name, const char *title) : fcell(NULL)
+{
+    fContName = cname;
+    Init(type, val, name, title);
+}
+
+// --------------------------------------------------------------------------
+ //
+MFTriggerLvl2::MFTriggerLvl2(MMcTriggerLvl2 *triglvl2, const char type, const Int_t val,
+                             const char *name, const char *title) : fcell(triglvl2)
+{
+    Init(type, val, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+void MFTriggerLvl2::Init(const char type, const Int_t val,
+                         const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFTriggerLvl2";
+    fTitle = title ? title : "Filter using 2nd level trigger selection";
+
+    fFilterType = (type=='<' ? kELowerThan : kEGreaterThan);
+
+    if (type!='<' && type!='>')
+        *fLog << warn << dbginf << "Warning: Neither '<' nor '>' specified... using '>'." << endl;
+
+    fValue = val;
+
+} 
+// --------------------------------------------------------------------------
+//
+Bool_t MFTriggerLvl2::IsExpressionTrue() const
+{
+    return fResult;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFTriggerLvl2::PreProcess(MParList *pList)
+{
+    if (fcell)
+        return kTRUE;
+
+    fcell = (MMcTriggerLvl2*)pList->FindObject(fContName);
+    if (fcell)
+        return kTRUE;
+
+    *fLog << err << dbginf << fContName << " [MMcTriggerLvl2] not found... aborting." << endl;
+
+        return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFTriggerLvl2::Process()
+{
+
+  //
+  //  The variable fLutPseudoSize of the class MMcTriggerLvl2 is used 
+  //   for the selection
+  //
+
+  const Int_t lvl2 = fcell->GetLutPseudoSize();
+
+    switch (fFilterType)
+    {
+    case kELowerThan:
+        fResult = (lvl2 < fValue);
+        break;
+    case kEGreaterThan:
+        fResult = (lvl2 > fValue);
+        break;
+    }
+
+    return kTRUE;
+}
+
+void MFTriggerLvl2::StreamPrimitive(ofstream &out) const
+{
+   if (fcell)
+        fcell->SavePrimitive(out);
+
+    out << "   MFTriggerLvl2 " << GetUniqueName() << "(";
+
+    if (fcell)
+        out << "&" << fcell->GetUniqueName();
+    else
+        out << "\"" << fContName << "\"";
+
+    out << ", '" << (fFilterType==kELowerThan?"<":">") << "', " << fValue << ");" << endl;
+
+}
Index: /tags/Mars-V0.9/mfilter/MFTriggerLvl2.h
===================================================================
--- /tags/Mars-V0.9/mfilter/MFTriggerLvl2.h	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/MFTriggerLvl2.h	(revision 9772)
@@ -0,0 +1,55 @@
+#ifndef MARS_MFTriggerLvl2
+#define MARS_MFTriggerLvl2
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFTriggerLvl2
+//
+// auth. A.stamerra 
+// created 30.01.03                                                       //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcTrig;
+class MParList;
+class MMcTriggerLvl2;
+
+class MFTriggerLvl2 : public MFilter
+{
+private:
+
+    TString fContName;
+
+    MMcTriggerLvl2 *fcell;
+
+    typedef enum { kELowerThan, kEGreaterThan } FilterType_t;
+    FilterType_t fFilterType; 
+
+    Bool_t fResult;             //!
+    Int_t  fValue;
+
+    void Init(const char type, const Int_t val,
+              const char *name, const char *title);
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+
+    MFTriggerLvl2(const char *cname="MMcTriggerLvl2", const char type='>', const Int_t val=0,
+                  const char *name=NULL, const char *title=NULL);
+    MFTriggerLvl2(MMcTriggerLvl2 *triglvl2, const char type='>', const Int_t val=0,
+                  const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const;
+
+    ClassDef(MFTriggerLvl2, 1) // A Filter for the Level 2 Trigger
+};
+
+#endif
Index: /tags/Mars-V0.9/mfilter/Makefile
===================================================================
--- /tags/Mars-V0.9/mfilter/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/Makefile	(revision 9772)
@@ -0,0 +1,36 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mfbase -I../mraw -I../mmc -I../mdata \
+           -I../manalysis -I../mfileio  -I../mgeom -I../mimage      \
+           -I../mhbase -I../mmain -I../mgui -I../msignal -I../mpointing  \
+           -I../mpedestal
+
+CINT     = Filter
+
+SRCFILES = MFTriggerLvl1.cc \
+	   MFTriggerLvl2.cc \
+           MFSupercuts.cc \
+	   MFGeomag.cc \
+           MFDeltaT.cc \
+	   MFParticleId.cc \
+           MFSoftwareTrigger.cc \
+           MFCosmics.cc \
+	   MFEnergySlope.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mfilter/gcminus.txt
===================================================================
--- /tags/Mars-V0.9/mfilter/gcminus.txt	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/gcminus.txt	(revision 9772)
@@ -0,0 +1,1152 @@
+       2.5       2.5    10.420    11.182     0.538
+       2.5       7.5    10.400    11.162     0.528
+       2.5      12.5    10.380    11.140     0.521
+       2.5      17.5    10.360    11.120     0.526
+       2.5      22.5    10.342    11.104     0.528
+       2.5      27.5    10.324    11.084     0.532
+       2.5      32.5    10.306    11.068     0.528
+       2.5      37.5    10.290    11.048     0.530
+       2.5      42.5    10.274    11.034     0.524
+       2.5      47.5    10.260    11.018     0.528
+       2.5      52.5    10.246    11.004     0.528
+       2.5      57.5    10.234    10.992     0.528
+       2.5      62.5    10.224    10.982     0.538
+       2.5      67.5    10.214    10.974     0.534
+       2.5      72.5    10.208    10.964     0.534
+       2.5      77.5    10.202    10.958     0.545
+       2.5      82.5    10.196    10.954     0.538
+       2.5      87.5    10.194    10.948     0.538
+       2.5      92.5    10.194    10.948     0.549
+       2.5      97.5    10.194    10.948     0.552
+       2.5     102.5    10.196    10.950     0.562
+       2.5     107.5    10.200    10.952     0.553
+       2.5     112.5    10.206    10.958     0.561
+       2.5     117.5    10.212    10.966     0.568
+       2.5     122.5    10.222    10.972     0.565
+       2.5     127.5    10.232    10.982     0.563
+       2.5     132.5    10.244    10.996     0.577
+       2.5     137.5    10.256    11.006     0.568
+       2.5     142.5    10.270    11.020     0.584
+       2.5     147.5    10.286    11.038     0.582
+       2.5     152.5    10.302    11.054     0.593
+       2.5     157.5    10.320    11.070     0.605
+       2.5     162.5    10.338    11.088     0.595
+       2.5     167.5    10.358    11.106     0.599
+       2.5     172.5    10.378    11.128     0.603
+       2.5     177.5    10.398    11.148     0.613
+       2.5     182.5    10.418    11.168     0.611
+       2.5     187.5    10.438    11.188     0.611
+       2.5     192.5    10.458    11.206     0.618
+       2.5     197.5    10.478    11.226     0.607
+       2.5     202.5    10.498    11.248     0.616
+       2.5     207.5    10.516    11.266     0.613
+       2.5     212.5    10.536    11.286     0.611
+       2.5     217.5    10.552    11.304     0.617
+       2.5     222.5    10.570    11.318     0.620
+       2.5     227.5    10.584    11.336     0.614
+       2.5     232.5    10.598    11.348     0.616
+       2.5     237.5    10.612    11.364     0.606
+       2.5     242.5    10.622    11.374     0.601
+       2.5     247.5    10.632    11.384     0.604
+       2.5     252.5    10.640    11.394     0.613
+       2.5     257.5    10.648    11.400     0.601
+       2.5     262.5    10.652    11.404     0.596
+       2.5     267.5    10.654    11.406     0.593
+       2.5     272.5    10.656    11.410     0.594
+       2.5     277.5    10.654    11.408     0.586
+       2.5     282.5    10.652    11.406     0.586
+       2.5     287.5    10.646    11.402     0.577
+       2.5     292.5    10.640    11.396     0.582
+       2.5     297.5    10.632    11.388     0.571
+       2.5     302.5    10.622    11.380     0.575
+       2.5     307.5    10.612    11.370     0.565
+       2.5     312.5    10.598    11.356     0.559
+       2.5     317.5    10.584    11.344     0.563
+       2.5     322.5    10.570    11.328     0.554
+       2.5     327.5    10.554    11.312     0.551
+       2.5     332.5    10.536    11.296     0.545
+       2.5     337.5    10.518    11.276     0.546
+       2.5     342.5    10.500    11.260     0.542
+       2.5     347.5    10.480    11.240     0.537
+       2.5     352.5    10.460    11.220     0.539
+       2.5     357.5    10.440    11.202     0.533
+       7.5       2.5    10.432    11.210     0.445
+       7.5       7.5    10.372    11.154     0.440
+       7.5      12.5    10.314    11.094     0.431
+       7.5      17.5    10.258    11.040     0.435
+       7.5      22.5    10.204    10.982     0.424
+       7.5      27.5    10.152    10.932     0.428
+       7.5      32.5    10.102    10.880     0.434
+       7.5      37.5    10.054    10.832     0.445
+       7.5      42.5    10.010    10.788     0.437
+       7.5      47.5     9.970    10.746     0.436
+       7.5      52.5     9.934    10.706     0.453
+       7.5      57.5     9.900    10.672     0.451
+       7.5      62.5     9.870    10.638     0.453
+       7.5      67.5     9.846    10.612     0.467
+       7.5      72.5     9.824    10.590     0.473
+       7.5      77.5     9.808    10.570     0.472
+       7.5      82.5     9.796    10.554     0.485
+       7.5      87.5     9.788    10.544     0.489
+       7.5      92.5     9.784    10.538     0.496
+       7.5      97.5     9.784    10.540     0.508
+       7.5     102.5     9.790    10.542     0.521
+       7.5     107.5     9.800    10.552     0.529
+       7.5     112.5     9.814    10.564     0.539
+       7.5     117.5     9.834    10.582     0.553
+       7.5     122.5     9.858    10.606     0.570
+       7.5     127.5     9.886    10.632     0.576
+       7.5     132.5     9.918    10.664     0.584
+       7.5     137.5     9.954    10.700     0.598
+       7.5     142.5     9.996    10.740     0.602
+       7.5     147.5    10.040    10.784     0.610
+       7.5     152.5    10.088    10.832     0.621
+       7.5     157.5    10.138    10.882     0.637
+       7.5     162.5    10.192    10.936     0.642
+       7.5     167.5    10.248    10.992     0.653
+       7.5     172.5    10.306    11.050     0.664
+       7.5     177.5    10.368    11.112     0.664
+       7.5     182.5    10.428    11.172     0.683
+       7.5     187.5    10.492    11.236     0.694
+       7.5     192.5    10.554    11.298     0.691
+       7.5     197.5    10.616    11.360     0.699
+       7.5     202.5    10.678    11.422     0.699
+       7.5     207.5    10.738    11.482     0.704
+       7.5     212.5    10.796    11.540     0.710
+       7.5     217.5    10.852    11.596     0.710
+       7.5     222.5    10.904    11.650     0.702
+       7.5     227.5    10.954    11.700     0.716
+       7.5     232.5    10.998    11.744     0.697
+       7.5     237.5    11.040    11.784     0.707
+       7.5     242.5    11.076    11.822     0.694
+       7.5     247.5    11.106    11.852     0.678
+       7.5     252.5    11.132    11.880     0.679
+       7.5     257.5    11.152    11.900     0.671
+       7.5     262.5    11.166    11.916     0.656
+       7.5     267.5    11.174    11.924     0.656
+       7.5     272.5    11.176    11.928     0.638
+       7.5     277.5    11.172    11.924     0.625
+       7.5     282.5    11.162    11.916     0.623
+       7.5     287.5    11.146    11.902     0.611
+       7.5     292.5    11.124    11.882     0.594
+       7.5     297.5    11.096    11.854     0.578
+       7.5     302.5    11.064    11.824     0.566
+       7.5     307.5    11.028    11.790     0.549
+       7.5     312.5    10.986    11.752     0.543
+       7.5     317.5    10.942    11.706     0.521
+       7.5     322.5    10.892    11.662     0.512
+       7.5     327.5    10.840    11.612     0.495
+       7.5     332.5    10.786    11.556     0.483
+       7.5     337.5    10.730    11.504     0.478
+       7.5     342.5    10.672    11.448     0.474
+       7.5     347.5    10.612    11.390     0.463
+       7.5     352.5    10.552    11.328     0.451
+       7.5     357.5    10.492    11.272     0.456
+      12.5       2.5    10.446    11.258     0.320
+      12.5       7.5    10.348    11.158     0.326
+      12.5      12.5    10.254    11.064     0.321
+      12.5      17.5    10.162    10.976     0.327
+      12.5      22.5    10.074    10.884     0.314
+      12.5      27.5     9.990    10.800     0.331
+      12.5      32.5     9.912    10.722     0.336
+      12.5      37.5     9.838    10.646     0.337
+      12.5      42.5     9.772    10.572     0.345
+      12.5      47.5     9.708    10.506     0.343
+      12.5      52.5     9.652    10.444     0.366
+      12.5      57.5     9.602    10.392     0.370
+      12.5      62.5     9.556    10.340     0.380
+      12.5      67.5     9.518    10.296     0.398
+      12.5      72.5     9.486    10.260     0.408
+      12.5      77.5     9.460    10.228     0.417
+      12.5      82.5     9.440    10.204     0.445
+      12.5      87.5     9.428    10.190     0.459
+      12.5      92.5     9.420    10.178     0.459
+      12.5      97.5     9.422    10.174     0.487
+      12.5     102.5     9.428    10.180     0.487
+      12.5     107.5     9.444    10.190     0.504
+      12.5     112.5     9.464    10.210     0.525
+      12.5     117.5     9.492    10.238     0.547
+      12.5     122.5     9.528    10.272     0.559
+      12.5     127.5     9.570    10.314     0.567
+      12.5     132.5     9.620    10.362     0.588
+      12.5     137.5     9.678    10.418     0.605
+      12.5     142.5     9.742    10.482     0.616
+      12.5     147.5     9.812    10.552     0.627
+      12.5     152.5     9.888    10.630     0.650
+      12.5     157.5     9.970    10.712     0.674
+      12.5     162.5    10.058    10.800     0.685
+      12.5     167.5    10.152    10.894     0.706
+      12.5     172.5    10.250    10.992     0.722
+      12.5     177.5    10.352    11.094     0.730
+      12.5     182.5    10.456    11.200     0.753
+      12.5     187.5    10.564    11.306     0.763
+      12.5     192.5    10.672    11.414     0.784
+      12.5     197.5    10.780    11.522     0.792
+      12.5     202.5    10.886    11.630     0.793
+      12.5     207.5    10.992    11.736     0.806
+      12.5     212.5    11.094    11.838     0.796
+      12.5     217.5    11.194    11.936     0.803
+      12.5     222.5    11.286    12.030     0.809
+      12.5     227.5    11.374    12.116     0.817
+      12.5     232.5    11.454    12.196     0.798
+      12.5     237.5    11.526    12.270     0.798
+      12.5     242.5    11.590    12.334     0.788
+      12.5     247.5    11.644    12.388     0.774
+      12.5     252.5    11.688    12.434     0.761
+      12.5     257.5    11.722    12.468     0.743
+      12.5     262.5    11.746    12.492     0.716
+      12.5     267.5    11.760    12.506     0.708
+      12.5     272.5    11.760    12.508     0.684
+      12.5     277.5    11.752    12.500     0.674
+      12.5     282.5    11.732    12.482     0.640
+      12.5     287.5    11.700    12.454     0.610
+      12.5     292.5    11.660    12.416     0.590
+      12.5     297.5    11.610    12.372     0.567
+      12.5     302.5    11.550    12.316     0.540
+      12.5     307.5    11.484    12.252     0.518
+      12.5     312.5    11.408    12.182     0.488
+      12.5     317.5    11.328    12.104     0.461
+      12.5     322.5    11.240    12.018     0.437
+      12.5     327.5    11.148    11.934     0.402
+      12.5     332.5    11.052    11.842     0.387
+      12.5     337.5    10.954    11.748     0.375
+      12.5     342.5    10.852    11.648     0.357
+      12.5     347.5    10.750    11.550     0.352
+      12.5     352.5    10.648    11.454     0.335
+      12.5     357.5    10.546    11.352     0.328
+      17.5       2.5    10.456    11.312     0.124
+      17.5       7.5    10.318    11.114     0.141
+      17.5      12.5    10.186    11.050     0.148
+      17.5      17.5    10.060    10.926     0.185
+      17.5      22.5     9.942    10.744     0.207
+      17.5      27.5     9.832    10.632     0.232
+      17.5      32.5     9.728    10.392     0.295
+      17.5      37.5     9.632    10.484     0.244
+      17.5      42.5     9.544    10.390     0.253
+      17.5      47.5     9.464    10.302     0.274
+      17.5      52.5     9.392    10.162     0.301
+      17.5      57.5     9.330    10.146     0.309
+      17.5      62.5     9.272    10.080     0.324
+      17.5      67.5     9.224    10.024     0.332
+      17.5      72.5     9.184     9.974     0.357
+      17.5      77.5     9.152     9.934     0.373
+      17.5      82.5     9.126     9.900     0.390
+      17.5      87.5     9.110     9.876     0.418
+      17.5      92.5     9.102     9.860     0.435
+      17.5      97.5     9.100     9.854     0.432
+      17.5     102.5     9.108     9.858     0.456
+      17.5     107.5     9.126     9.870     0.476
+      17.5     112.5     9.152     9.892     0.500
+      17.5     117.5     9.186     9.926     0.516
+      17.5     122.5     9.232     9.968     0.549
+      17.5     127.5     9.286    10.024     0.566
+      17.5     132.5     9.350    10.088     0.580
+      17.5     137.5     9.424    10.160     0.606
+      17.5     142.5     9.508    10.246     0.629
+      17.5     147.5     9.602    10.342     0.657
+      17.5     152.5     9.706    10.446     0.681
+      17.5     157.5     9.818    10.560     0.706
+      17.5     162.5     9.940    10.684     0.739
+      17.5     167.5    10.070    10.814     0.761
+      17.5     172.5    10.208    10.954     0.786
+      17.5     177.5    10.354    11.098     0.809
+      17.5     182.5    10.504    11.250     0.828
+      17.5     187.5    10.658    11.404     0.845
+      17.5     192.5    10.830    11.560     0.871
+      17.5     197.5    10.978    11.718     0.881
+      17.5     202.5    11.132    11.876     0.882
+      17.5     207.5    11.288    12.032     0.895
+      17.5     212.5    11.440    12.182     0.895
+      17.5     217.5    11.698    12.328     0.879
+      17.5     222.5    11.836    12.466     0.873
+      17.5     227.5    11.964    12.596     0.877
+      17.5     232.5    11.974    12.714     0.886
+      17.5     237.5    12.082    12.822     0.881
+      17.5     242.5    12.176    12.916     0.876
+      17.5     247.5    12.264    12.996     0.872
+      17.5     252.5    12.338    13.062     0.845
+      17.5     257.5    12.370    13.112     0.827
+      17.5     262.5    12.404    13.144     0.795
+      17.5     267.5    12.420    13.162     0.765
+      17.5     272.5    12.418    13.164     0.732
+      17.5     277.5    12.402    13.148     0.694
+      17.5     282.5    12.368    13.118     0.659
+      17.5     287.5    12.320    13.072     0.612
+      17.5     292.5    12.256    13.012     0.585
+      17.5     297.5    12.176    12.938     0.530
+      17.5     302.5    12.086    12.852     0.480
+      17.5     307.5    11.980    12.754     0.429
+      17.5     312.5    11.866    12.644     0.380
+      17.5     317.5    11.744    12.526     0.345
+      17.5     322.5    11.614    12.404     0.311
+      17.5     327.5    11.476    12.278     0.277
+      17.5     332.5    11.332    12.072     0.257
+      17.5     337.5    11.186    12.006     0.200
+      17.5     342.5    11.038    11.866     0.164
+      17.5     347.5    10.890    11.726     0.129
+      17.5     352.5    10.742    11.586     0.126
+      17.5     357.5    10.598    11.448     0.136
+      22.5       2.5    10.440    11.370     0.151
+      22.5       7.5    10.260    11.202     0.153
+      22.5      12.5    10.092    10.970     0.162
+      22.5      17.5     9.934    10.884     0.141
+      22.5      22.5     9.786    10.728     0.144
+      22.5      27.5     9.652    10.534     0.143
+      22.5      32.5     9.528    10.466     0.130
+      22.5      37.5     9.416    10.284     0.129
+      22.5      42.5     9.316    10.228     0.125
+      22.5      47.5     9.226    10.122     0.181
+      22.5      52.5     9.144     9.848     0.267
+      22.5      57.5     9.074     9.918     0.232
+      22.5      62.5     9.012     9.858     0.258
+      22.5      67.5     8.958     9.788     0.289
+      22.5      72.5     8.914     9.714     0.302
+      22.5      77.5     8.878     9.674     0.319
+      22.5      82.5     8.850     9.634     0.347
+      22.5      87.5     8.830     9.604     0.364
+      22.5      92.5     8.820     9.582     0.388
+      22.5      97.5     8.818     9.572     0.401
+      22.5     102.5     8.826     9.572     0.416
+      22.5     107.5     8.846     9.586     0.454
+      22.5     112.5     8.874     9.612     0.474
+      22.5     117.5     8.914     9.648     0.499
+      22.5     122.5     8.964     9.698     0.520
+      22.5     127.5     9.028     9.762     0.559
+      22.5     132.5     9.104     9.838     0.569
+      22.5     137.5     9.192     9.926     0.608
+      22.5     142.5     9.294    10.032     0.648
+      22.5     147.5     9.410    10.150     0.668
+      22.5     152.5     9.538    10.280     0.704
+      22.5     157.5     9.680    10.426     0.743
+      22.5     162.5     9.836    10.582     0.769
+      22.5     167.5    10.004    10.752     0.807
+      22.5     172.5    10.182    10.934     0.851
+      22.5     177.5    10.382    11.124     0.884
+      22.5     182.5    10.572    11.324     0.896
+      22.5     187.5    10.900    11.530     0.905
+      22.5     192.5    11.096    11.740     0.907
+      22.5     197.5    11.342    11.952     0.925
+      22.5     202.5    11.500    12.166     0.916
+      22.5     207.5    11.704    12.376     0.929
+      22.5     212.5    11.904    12.582     0.923
+      22.5     217.5    12.142    12.780     0.925
+      22.5     222.5    12.328    12.970     0.928
+      22.5     227.5    12.464    13.146     0.924
+      22.5     232.5    12.670    13.308     0.918
+      22.5     237.5    12.788    13.452     0.919
+      22.5     242.5    12.922    13.580     0.909
+      22.5     247.5    13.030    13.688     0.894
+      22.5     252.5    13.126    13.774     0.886
+      22.5     257.5    13.202    13.838     0.862
+      22.5     262.5    13.148    13.880     0.847
+      22.5     267.5    13.164    13.900     0.823
+      22.5     272.5    13.158    13.898     0.784
+      22.5     277.5    13.130    13.872     0.722
+      22.5     282.5    13.080    13.824     0.656
+      22.5     287.5    13.008    13.756     0.588
+      22.5     292.5    12.916    13.664     0.519
+      22.5     297.5    12.804    13.560     0.426
+      22.5     302.5    12.674    13.438     0.346
+      22.5     307.5    12.528    13.300     0.251
+      22.5     312.5    12.366    13.150     0.110
+      22.5     317.5    12.194    12.988     0.106
+      22.5     322.5    12.012    12.818     0.107
+      22.5     327.5    11.818    12.558     0.124
+      22.5     332.5    11.624    12.460     0.117
+      22.5     337.5    11.422    12.276     0.122
+      22.5     342.5    11.220    12.090     0.138
+      22.5     347.5    11.018    11.906     0.149
+      22.5     352.5    10.820    11.724     0.144
+      22.5     357.5    10.626    11.544     0.144
+      27.5       2.5    10.360    11.340     0.255
+      27.5       7.5    10.132    11.222     0.246
+      27.5      12.5     9.922    11.016     0.234
+      27.5      17.5     9.730    10.844     0.230
+      27.5      22.5     9.558    10.670     0.209
+      27.5      27.5     9.406    10.508     0.196
+      27.5      32.5     9.272    10.356     0.179
+      27.5      37.5     9.156     9.748     0.277
+      27.5      42.5     9.054     9.632     0.270
+      27.5      47.5     8.966     9.964     0.126
+      27.5      52.5     8.888     9.854     0.137
+      27.5      57.5     8.820     9.754     0.146
+      27.5      62.5     8.762     9.664     0.184
+      27.5      67.5     8.710     9.440     0.249
+      27.5      72.5     8.668     9.384     0.274
+      27.5      77.5     8.632     9.454     0.268
+      27.5      82.5     8.604     9.394     0.284
+      27.5      87.5     8.584     9.366     0.338
+      27.5      92.5     8.574     9.340     0.347
+      27.5      97.5     8.572     9.326     0.379
+      27.5     102.5     8.580     9.324     0.403
+      27.5     107.5     8.598     9.334     0.418
+      27.5     112.5     8.628     9.360     0.454
+      27.5     117.5     8.672     9.400     0.475
+      27.5     122.5     8.726     9.454     0.519
+      27.5     127.5     8.796     9.524     0.552
+      27.5     132.5     8.880     9.610     0.570
+      27.5     137.5     8.982     9.716     0.602
+      27.5     142.5     9.098     9.836     0.640
+      27.5     147.5     9.232     9.974     0.668
+      27.5     152.5     9.386    10.130     0.731
+      27.5     157.5     9.556    10.306     0.784
+      27.5     162.5     9.744    10.498     0.825
+      27.5     167.5     9.952    10.708     0.870
+      27.5     172.5    10.176    10.932     0.910
+      27.5     177.5    10.538    11.172     0.899
+      27.5     182.5    10.818    11.424     0.924
+      27.5     187.5    11.058    11.686     0.924
+      27.5     192.5    11.258    11.954     0.937
+      27.5     197.5    12.134    12.228     0.596
+      27.5     202.5    12.408    12.504     0.708
+      27.5     207.5    12.680    12.778     0.673
+      27.5     212.5    12.946    13.044     0.694
+      27.5     217.5    13.204    13.302     0.714
+      27.5     222.5    13.448    13.548     0.700
+      27.5     227.5    13.676    13.776     0.700
+      27.5     232.5    13.258    13.986     0.951
+      27.5     237.5    14.070    14.174     0.673
+      27.5     242.5    14.230    14.338     0.685
+      27.5     247.5    14.364    14.474     0.636
+      27.5     252.5    13.906    14.582     0.914
+      27.5     257.5    13.994    14.662     0.895
+      27.5     262.5    14.060    14.712     0.877
+      27.5     267.5    14.004    14.732     0.860
+      27.5     272.5    14.006    14.720     0.796
+      27.5     277.5    13.948    14.676     0.717
+      27.5     282.5    13.876    14.606     0.625
+      27.5     287.5    13.776    14.512     0.486
+      27.5     292.5    13.648    14.388     0.335
+      27.5     297.5    13.496    14.242     0.080
+      27.5     302.5    13.320    14.074     0.037
+      27.5     307.5    13.122    13.888     0.039
+      27.5     312.5    12.908    13.688     0.046
+      27.5     317.5    12.676    13.474     0.050
+      27.5     322.5    12.432    13.250     0.037
+      27.5     327.5    12.178    13.020     0.069
+      27.5     332.5    11.914    12.786     0.126
+      27.5     337.5    11.650    12.442     0.182
+      27.5     342.5    11.382    12.316     0.186
+      27.5     347.5    11.116    11.978     0.227
+      27.5     352.5    10.854    11.858     0.213
+      27.5     357.5    10.602    11.638     0.236
+      32.5       2.5    10.640    11.466     0.123
+      32.5       7.5    10.382    11.130     0.128
+      32.5      12.5    10.158    11.002     0.126
+      32.5      17.5     9.966    10.780     0.118
+      32.5      22.5     9.804    10.598     0.118
+      32.5      27.5     9.252     9.800     0.883
+      32.5      32.5     9.120    10.240     0.375
+      32.5      37.5     8.734    10.086     0.322
+      32.5      42.5     8.672     9.438     0.366
+      32.5      47.5     8.624     9.822     0.164
+      32.5      52.5     8.582     9.646     0.175
+      32.5      57.5     8.542     9.594     0.194
+      32.5      62.5     8.504     9.496     0.139
+      32.5      67.5     8.468     9.408     0.113
+      32.5      72.5     8.436     9.200     0.228
+      32.5      77.5     8.408     9.264     0.224
+      32.5      82.5     8.386     9.168     0.266
+      32.5      87.5     8.368     9.154     0.290
+      32.5      92.5     8.358     9.116     0.309
+      32.5      97.5     8.358     9.112     0.337
+      32.5     102.5     8.366     9.106     0.359
+      32.5     107.5     8.386     9.116     0.397
+      32.5     112.5     8.414     9.140     0.441
+      32.5     117.5     8.458     9.180     0.454
+      32.5     122.5     8.516     9.238     0.488
+      32.5     127.5     8.590     9.314     0.514
+      32.5     132.5     8.680     9.408     0.563
+      32.5     137.5     8.790     9.522     0.609
+      32.5     142.5     8.920     9.658     0.659
+      32.5     147.5     9.072     9.818     0.713
+      32.5     152.5     9.246     9.998     0.755
+      32.5     157.5     9.444    10.202     0.815
+      32.5     162.5     9.666    10.428     0.874
+      32.5     167.5    10.072    10.678     0.901
+      32.5     172.5    10.320    10.948     0.914
+      32.5     177.5    10.624    11.240     0.938
+      32.5     182.5    11.454    11.550     0.563
+      32.5     187.5    11.778    11.874     0.667
+      32.5     192.5    11.456    12.208     0.955
+      32.5     197.5    12.456    12.552     0.708
+      32.5     202.5    12.800    12.898     0.714
+      32.5     207.5    13.144    13.240     0.792
+      32.5     212.5    13.480    13.578     0.796
+      32.5     217.5    13.804    13.904     0.860
+      32.5     222.5    14.112    14.212     0.860
+      32.5     227.5    14.412    14.500     0.841
+      32.5     232.5    14.664    14.764     0.840
+      32.5     237.5    14.898    14.998     0.820
+      32.5     242.5    15.094    15.200     0.811
+      32.5     247.5    15.258    15.370     0.750
+      32.5     252.5    15.386    15.502     0.707
+      32.5     257.5    14.940    15.596     0.930
+      32.5     262.5    14.976    15.650     0.899
+      32.5     267.5    15.018    15.666     0.855
+      32.5     272.5    14.930    15.642     0.787
+      32.5     277.5    14.868    15.580     0.660
+      32.5     282.5    14.768    15.482     0.440
+      32.5     287.5    14.632    15.348     0.201
+      32.5     292.5    14.462    15.180     0.050
+      32.5     297.5    14.260    14.984     0.052
+      32.5     302.5    14.030    14.762     0.060
+      32.5     307.5    13.772    14.516     0.056
+      32.5     312.5    13.492    14.256     0.068
+      32.5     317.5    13.190    13.666     0.105
+      32.5     322.5    12.872    13.698     0.061
+      32.5     327.5    12.540    13.262     0.125
+      32.5     332.5    12.196    12.978     0.228
+      32.5     337.5    11.844    12.692     0.318
+      32.5     342.5    11.488    12.408     0.393
+      32.5     347.5    11.132    12.256     0.413
+      32.5     352.5    10.774    11.982     0.412
+      32.5     357.5    10.928    11.718     0.127
+      37.5       2.5    11.154    11.470     0.013
+      37.5       7.5    10.888    11.196     0.013
+      37.5      12.5    10.640    10.944     0.013
+      37.5      17.5     9.336    10.712     0.728
+      37.5      22.5     9.278    10.500     0.584
+      37.5      27.5     8.702    10.218     0.689
+      37.5      32.5     8.942    10.048     0.548
+      37.5      37.5     9.000     9.700     0.540
+      37.5      42.5     9.002     9.824     0.280
+      37.5      47.5     8.634     9.448     0.555
+      37.5      52.5     8.064     9.504     0.522
+      37.5      57.5     8.170     9.252     0.246
+      37.5      62.5     8.188     9.350     0.164
+      37.5      67.5     8.204     9.096     0.155
+      37.5      72.5     8.204     9.170     0.116
+      37.5      77.5     8.196     9.102     0.170
+      37.5      82.5     8.186     9.030     0.209
+      37.5      87.5     8.178     8.966     0.246
+      37.5      92.5     8.178     8.956     0.275
+      37.5      97.5     8.190     8.932     0.318
+      37.5     102.5     8.180     8.922     0.372
+      37.5     107.5     8.202     8.926     0.403
+      37.5     112.5     8.232     8.948     0.427
+      37.5     117.5     8.272     8.988     0.469
+      37.5     122.5     8.332     9.046     0.501
+      37.5     127.5     8.422     9.126     0.531
+      37.5     132.5     8.508     9.226     0.577
+      37.5     137.5     8.620     9.350     0.622
+      37.5     142.5     8.760     9.500     0.651
+      37.5     147.5     8.926     9.674     0.725
+      37.5     152.5     9.120     9.878     0.794
+      37.5     157.5     9.344    10.110     0.883
+      37.5     162.5     9.606    10.372     0.930
+      37.5     167.5    10.040    10.664     0.913
+      37.5     172.5    10.888    10.984     0.562
+      37.5     177.5    11.234    11.332     0.592
+      37.5     182.5    11.606    11.704     0.673
+      37.5     187.5    11.998    12.096     0.714
+      37.5     192.5    12.408    12.506     0.755
+      37.5     197.5    12.830    12.928     0.816
+      37.5     202.5    13.258    13.352     0.851
+      37.5     207.5    13.690    13.778     0.909
+      37.5     212.5    14.104    14.194     0.889
+      37.5     217.5    14.504    14.596     0.891
+      37.5     222.5    14.882    14.976     0.936
+      37.5     227.5    15.234    15.332     0.878
+      37.5     232.5    15.556    15.654     0.898
+      37.5     237.5    15.840    15.940     0.880
+      37.5     242.5    16.084    16.186     0.843
+      37.5     247.5    16.284    16.390     0.830
+      37.5     252.5    16.432    16.546     0.789
+      37.5     257.5    16.528    16.654     0.714
+      37.5     262.5    16.026    16.712     0.924
+      37.5     267.5    16.062    16.720     0.842
+      37.5     272.5    15.988    16.678     0.722
+      37.5     277.5    15.902    16.588     0.469
+      37.5     282.5    15.768    16.450     0.059
+      37.5     287.5    15.590    16.266     0.024
+      37.5     292.5    15.368    16.042     0.006
+      37.5     297.5    15.108    15.780     0.006
+      37.5     302.5    14.810    15.486     0.000
+      37.5     307.5    14.480    15.170     0.006
+      37.5     312.5    14.120    14.350     0.009
+      37.5     317.5    13.734    14.010     0.101
+      37.5     322.5    13.322    14.152     0.060
+      37.5     327.5    12.888    13.590     0.439
+      37.5     332.5    12.464    13.270     0.533
+      37.5     337.5    12.334    13.094     0.187
+      37.5     342.5    11.816    12.744     0.190
+      37.5     347.5    11.242    12.404     0.513
+      37.5     352.5    10.966    12.076     0.616
+      37.5     357.5    11.438    11.764     0.031
+      42.5       2.5    11.060    11.382     0.205
+      42.5       7.5    10.748    11.070     0.217
+      42.5      12.5    10.472    10.794     0.199
+      42.5      17.5    10.234    10.550     0.171
+      42.5      22.5    10.030    10.336     0.150
+      42.5      27.5     9.844    10.146     0.113
+      42.5      32.5     9.684     9.976     0.041
+      42.5      37.5     8.314     9.822     0.809
+      42.5      42.5     7.784     9.682     0.778
+      42.5      47.5     8.408     9.544     0.546
+      42.5      52.5     8.580     9.434     0.319
+      42.5      57.5     8.200     9.316     0.464
+      42.5      62.5     7.806     9.038     0.448
+      42.5      67.5     7.836     9.128     0.241
+      42.5      72.5     7.962     9.044     0.150
+      42.5      77.5     7.996     8.842     0.137
+      42.5      82.5     8.016     8.904     0.162
+      42.5      87.5     8.006     8.850     0.239
+      42.5      92.5     8.012     8.718     0.309
+      42.5      97.5     8.014     8.778     0.309
+      42.5     102.5     8.024     8.764     0.327
+      42.5     107.5     8.044     8.756     0.393
+      42.5     112.5     8.072     8.784     0.419
+      42.5     117.5     8.114     8.814     0.457
+      42.5     122.5     8.172     8.880     0.494
+      42.5     127.5     8.248     8.960     0.551
+      42.5     132.5     8.348     9.064     0.587
+      42.5     137.5     8.480     9.196     0.612
+      42.5     142.5     8.616     9.356     0.654
+      42.5     147.5     8.794     9.546     0.742
+      42.5     152.5     9.006     9.770     0.846
+      42.5     157.5     9.302    10.030     0.909
+      42.5     162.5     9.728    10.328     0.920
+      42.5     167.5    10.566    10.662     0.542
+      42.5     172.5    10.936    11.034     0.571
+      42.5     177.5    11.344    11.444     0.660
+      42.5     182.5    11.786    11.886     0.720
+      42.5     187.5    12.258    12.358     0.760
+      42.5     192.5    12.768    12.852     0.833
+      42.5     197.5    13.274    13.362     0.864
+      42.5     202.5    13.786    13.880     0.936
+      42.5     207.5    14.300    14.398     0.878
+      42.5     212.5    14.812    14.906     0.915
+      42.5     217.5    15.298    15.394     0.958
+      42.5     222.5    15.760    15.858     0.918
+      42.5     227.5    16.278    16.288     0.800
+      42.5     232.5    16.576    16.678     0.941
+      42.5     237.5    16.918    17.022     0.942
+      42.5     242.5    17.208    17.314     0.906
+      42.5     247.5    17.446    17.554     0.926
+      42.5     252.5    17.614    17.734     0.850
+      42.5     257.5    17.726    17.854     0.797
+      42.5     262.5    17.254    17.912     0.927
+      42.5     267.5    17.242    17.906     0.780
+      42.5     272.5    17.184    17.838     0.508
+      42.5     277.5    17.066    17.708     0.031
+      42.5     282.5    16.892    17.514     0.000
+      42.5     287.5    16.658    16.658     1.000
+      42.5     292.5    16.374    16.374     1.000
+      42.5     297.5    16.042    16.042     1.000
+      42.5     302.5    15.666    15.666     1.000
+      42.5     307.5    15.248    15.248     1.000
+      42.5     312.5    14.794    15.102     0.000
+      42.5     317.5    14.300    14.544     0.156
+      42.5     322.5    13.764    14.334     0.537
+      42.5     327.5    13.532    13.932     0.455
+      42.5     332.5    12.806    13.572     0.287
+      42.5     337.5    12.966    13.192     0.044
+      42.5     342.5    12.582    12.892     0.026
+      42.5     347.5    12.180    12.500     0.025
+      42.5     352.5    11.784    12.100     0.152
+      42.5     357.5    11.408    11.726     0.220
+      47.5       2.5    10.430    10.958     0.458
+      47.5       7.5    10.066    10.608     0.472
+      47.5      12.5     9.822    10.338     0.469
+      47.5      17.5     9.664    10.132     0.402
+      47.5      22.5     9.524     9.970     0.363
+      47.5      27.5     7.426     9.830     0.879
+      47.5      32.5     7.652     9.716     0.868
+      47.5      37.5     9.282     9.602     0.169
+      47.5      42.5     9.198     9.494     0.122
+      47.5      47.5     9.116     9.396     0.057
+      47.5      52.5     7.508     9.082     0.917
+      47.5      57.5     8.164     9.198     0.497
+      47.5      62.5     7.158     8.914     0.780
+      47.5      67.5     7.510     9.016     0.568
+      47.5      72.5     7.612     8.932     0.276
+      47.5      77.5     7.730     8.720     0.212
+      47.5      82.5     7.820     8.672     0.178
+      47.5      87.5     7.850     8.734     0.188
+      47.5      92.5     7.868     8.688     0.232
+      47.5      97.5     7.880     8.630     0.277
+      47.5     102.5     7.894     8.634     0.319
+      47.5     107.5     7.914     8.622     0.381
+      47.5     112.5     7.942     8.646     0.403
+      47.5     117.5     7.982     8.680     0.450
+      47.5     122.5     8.038     8.736     0.481
+      47.5     127.5     8.114     8.816     0.527
+      47.5     132.5     8.210     8.922     0.590
+      47.5     137.5     8.336     9.058     0.634
+      47.5     142.5     8.486     9.226     0.705
+      47.5     147.5     8.678     9.432     0.759
+      47.5     152.5     8.904     9.674     0.896
+      47.5     157.5     9.448     9.962     0.922
+      47.5     162.5     9.726    10.292     0.908
+      47.5     167.5    10.572    10.672     0.560
+      47.5     172.5    11.000    11.100     0.640
+      47.5     177.5    11.474    11.576     0.706
+      47.5     182.5    11.992    12.098     0.755
+      47.5     187.5    12.556    12.658     0.882
+      47.5     192.5    13.156    13.250     0.872
+      47.5     197.5    13.764    13.864     0.940
+      47.5     202.5    14.392    14.490     0.939
+      47.5     207.5    15.116    15.116     1.000
+      47.5     212.5    15.728    15.728     1.000
+      47.5     217.5    16.318    16.318     1.000
+      47.5     222.5    16.866    16.876     0.800
+      47.5     227.5    17.392    17.392     1.000
+      47.5     232.5    17.844    17.856     0.833
+      47.5     237.5    18.262    18.262     1.000
+      47.5     242.5    18.594    18.606     0.833
+      47.5     247.5    18.870    18.884     0.714
+      47.5     252.5    18.966    19.088     0.951
+      47.5     257.5    19.084    19.218     0.866
+      47.5     262.5    19.118    19.270     0.737
+      47.5     267.5    18.624    19.244     0.671
+      47.5     272.5    18.540    19.134     0.034
+      47.5     277.5    18.384    18.940     0.000
+      47.5     282.5    18.154    18.154     1.000
+      47.5     287.5    17.858    17.858     1.000
+      47.5     292.5    17.498    17.498     1.000
+      47.5     297.5    17.082    17.082     1.000
+      47.5     302.5    16.610    16.610     1.000
+      47.5     307.5    16.086    16.086     1.000
+      47.5     312.5    15.510    15.510     1.000
+      47.5     317.5    14.874    15.064     0.547
+      47.5     322.5    14.460    14.726     0.827
+      47.5     327.5    14.170    14.366     0.041
+      47.5     332.5    13.732    14.072     0.053
+      47.5     337.5    13.200    13.524     0.272
+      47.5     342.5    12.632    12.968     0.375
+      47.5     347.5    12.046    12.416     0.449
+      47.5     352.5    11.460    11.882     0.483
+      47.5     357.5    10.906    11.388     0.494
+      52.5       2.5     8.470     9.446     0.916
+      52.5       7.5     8.342     9.216     0.913
+      52.5      12.5     8.020     9.048     0.911
+      52.5      17.5     7.826     8.948     0.907
+      52.5      22.5     7.798     8.932     0.880
+      52.5      27.5     7.454     9.008     0.873
+      52.5      32.5     7.290     9.114     0.855
+      52.5      37.5     7.514     9.186     0.812
+      52.5      42.5     8.794     9.200     0.305
+      52.5      47.5     7.476     9.172     0.853
+      52.5      52.5     7.136     9.126     0.868
+      52.5      57.5     7.166     9.062     0.862
+      52.5      62.5     7.752     8.922     0.644
+      52.5      67.5     8.124     8.738     0.381
+      52.5      72.5     7.156     8.682     0.720
+      52.5      77.5     7.522     8.624     0.314
+      52.5      82.5     7.620     8.702     0.194
+      52.5      87.5     7.698     8.538     0.164
+      52.5      92.5     7.744     8.594     0.216
+      52.5      97.5     7.774     8.556     0.263
+      52.5     102.5     7.788     8.520     0.290
+      52.5     107.5     7.810     8.524     0.339
+      52.5     112.5     7.836     8.532     0.388
+      52.5     117.5     7.882     8.562     0.432
+      52.5     122.5     7.940     8.608     0.485
+      52.5     127.5     8.000     8.692     0.538
+      52.5     132.5     8.102     8.800     0.579
+      52.5     137.5     8.222     8.938     0.662
+      52.5     142.5     8.384     9.112     0.728
+      52.5     147.5     8.576     9.328     0.843
+      52.5     152.5     8.826     9.588     0.911
+      52.5     157.5     9.386     9.900     0.899
+      52.5     162.5     9.684    10.266     0.914
+      52.5     167.5    10.588    10.690     0.549
+      52.5     172.5    11.074    11.178     0.654
+      52.5     177.5    11.622    11.728     0.755
+      52.5     182.5    12.234    12.338     0.846
+      52.5     187.5    12.904    13.002     0.878
+      52.5     192.5    13.608    13.708     0.960
+      52.5     197.5    14.436    14.444     0.750
+      52.5     202.5    15.196    15.196     1.000
+      52.5     207.5    15.948    15.948     1.000
+      52.5     212.5    16.684    16.684     1.000
+      52.5     217.5    17.390    17.390     1.000
+      52.5     222.5    18.054    18.054     1.000
+      52.5     227.5    18.666    18.666     1.000
+      52.5     232.5    19.214    19.214     1.000
+      52.5     237.5    19.692    19.692     1.000
+      52.5     242.5    20.090    20.090     1.000
+      52.5     247.5    20.406    20.406     1.000
+      52.5     252.5    20.616    20.634     0.889
+      52.5     257.5    20.626    20.770     0.917
+      52.5     262.5    20.636    20.808     0.674
+      52.5     267.5    20.198    20.744     0.253
+      52.5     272.5    20.082    20.558     0.000
+      52.5     277.5    19.872    19.872     1.000
+      52.5     282.5    19.578    19.578     1.000
+      52.5     287.5    19.204    19.204     1.000
+      52.5     292.5    18.754    18.754     1.000
+      52.5     297.5    18.234    18.234     1.000
+      52.5     302.5    17.650    17.650     1.000
+      52.5     307.5    16.998    16.998     1.000
+      52.5     312.5    16.264    16.264     1.000
+      52.5     317.5    15.768    15.768     1.000
+      52.5     322.5    15.236    15.350     0.070
+      52.5     327.5    14.646    14.968     0.280
+      52.5     332.5    13.894    14.238     0.535
+      52.5     337.5    12.946    13.404     0.742
+      52.5     342.5    11.422    12.350     0.828
+      52.5     347.5    10.340    10.882     0.705
+      52.5     352.5     9.872    10.156     0.690
+      52.5     357.5     8.664     9.744     0.919
+      57.5       2.5     9.104     9.164     0.467
+      57.5       7.5     8.340     8.924     0.736
+      57.5      12.5     8.118     8.710     0.753
+      57.5      17.5     7.804     8.520     0.844
+      57.5      22.5     7.598     8.368     0.888
+      57.5      27.5     7.310     8.264     0.916
+      57.5      32.5     7.078     8.234     0.926
+      57.5      37.5     7.998     8.326     0.640
+      57.5      42.5     7.196     8.562     0.861
+      57.5      47.5     8.284     8.772     0.381
+      57.5      52.5     7.244     8.870     0.825
+      57.5      57.5     8.572     8.888     0.196
+      57.5      62.5     8.584     8.860     0.065
+      57.5      67.5     7.386     8.818     0.691
+      57.5      72.5     7.970     8.690     0.308
+      57.5      77.5     7.436     8.550     0.614
+      57.5      82.5     7.450     8.634     0.243
+      57.5      87.5     7.568     8.534     0.182
+      57.5      92.5     7.628     8.428     0.190
+      57.5      97.5     7.682     8.400     0.248
+      57.5     102.5     7.704     8.440     0.285
+      57.5     107.5     7.728     8.440     0.329
+      57.5     112.5     7.756     8.444     0.355
+      57.5     117.5     7.792     8.468     0.464
+      57.5     122.5     7.866     8.510     0.463
+      57.5     127.5     7.918     8.584     0.535
+      57.5     132.5     8.008     8.696     0.599
+      57.5     137.5     8.132     8.834     0.638
+      57.5     142.5     8.280     9.012     0.730
+      57.5     147.5     8.482     9.236     0.883
+      57.5     152.5     8.732     9.510     0.920
+      57.5     157.5     9.334     9.842     0.921
+      57.5     162.5    10.142    10.242     0.580
+      57.5     167.5    10.608    10.714     0.642
+      57.5     172.5    11.156    11.264     0.722
+      57.5     177.5    11.786    11.896     0.855
+      57.5     182.5    12.508    12.608     0.900
+      57.5     187.5    13.288    13.390     0.941
+      57.5     192.5    14.232    14.232     1.000
+      57.5     197.5    15.112    15.112     1.000
+      57.5     202.5    16.014    16.014     1.000
+      57.5     207.5    16.914    16.914     1.000
+      57.5     212.5    17.792    17.792     1.000
+      57.5     217.5    18.634    18.634     1.000
+      57.5     222.5    19.422    19.422     1.000
+      57.5     227.5    20.142    20.142     1.000
+      57.5     232.5    20.784    20.784     1.000
+      57.5     237.5    21.340    21.340     1.000
+      57.5     242.5    21.798    21.798     1.000
+      57.5     247.5    22.156    22.156     1.000
+      57.5     252.5    22.404    22.404     1.000
+      57.5     257.5    22.380    22.536     0.962
+      57.5     262.5    22.052    22.544     0.748
+      57.5     267.5    21.998    21.998     1.000
+      57.5     272.5    21.836    21.836     1.000
+      57.5     277.5    21.566    21.566     1.000
+      57.5     282.5    21.190    21.190     1.000
+      57.5     287.5    20.720    20.720     1.000
+      57.5     292.5    20.160    20.160     1.000
+      57.5     297.5    19.520    19.520     1.000
+      57.5     302.5    18.800    18.800     1.000
+      57.5     307.5    17.988    17.988     1.000
+      57.5     312.5    17.106    17.106     1.000
+      57.5     317.5    16.506    16.660     0.156
+      57.5     322.5    15.776    16.090     0.516
+      57.5     327.5    14.680    15.070     0.815
+      57.5     332.5    13.848    13.848     1.000
+      57.5     337.5    13.078    13.078     1.000
+      57.5     342.5    12.294    12.294     1.000
+      57.5     347.5    11.500    11.500     1.000
+      57.5     352.5    10.700    10.700     1.000
+      57.5     357.5     9.896     9.896     1.000
+      62.5       2.5    10.332    10.332     1.000
+      62.5       7.5     9.452     9.452     1.000
+      62.5      12.5     8.696     8.754     0.448
+      62.5      17.5     7.984     8.518     0.551
+      62.5      22.5     7.744     8.304     0.632
+      62.5      27.5     7.488     8.118     0.737
+      62.5      32.5     7.242     7.974     0.817
+      62.5      37.5     7.006     7.886     0.902
+      62.5      42.5     7.114     7.884     0.894
+      62.5      47.5     7.338     8.044     0.822
+      62.5      52.5     7.886     8.378     0.537
+      62.5      57.5     8.192     8.610     0.340
+      62.5      62.5     8.370     8.698     0.189
+      62.5      67.5     7.338     8.706     0.810
+      62.5      72.5     7.290     8.664     0.681
+      62.5      77.5     7.896     8.638     0.205
+      62.5      82.5     7.214     8.584     0.498
+      62.5      87.5     7.398     8.528     0.232
+      62.5      92.5     7.508     8.440     0.204
+      62.5      97.5     7.598     8.434     0.196
+      62.5     102.5     7.642     8.400     0.269
+      62.5     107.5     7.674     8.372     0.309
+      62.5     112.5     7.698     8.380     0.364
+      62.5     117.5     7.736     8.400     0.407
+      62.5     122.5     7.784     8.434     0.489
+      62.5     127.5     7.850     8.504     0.529
+      62.5     132.5     7.948     8.610     0.601
+      62.5     137.5     8.060     8.748     0.645
+      62.5     142.5     8.204     8.920     0.746
+      62.5     147.5     8.406     9.154     0.858
+      62.5     152.5     8.754     9.440     0.915
+      62.5     157.5     9.702     9.790     0.568
+      62.5     162.5    10.116    10.220     0.538
+      62.5     167.5    10.626    10.738     0.536
+      62.5     172.5    11.242    11.354     0.786
+      62.5     177.5    11.980    12.076     0.875
+      62.5     182.5    12.800    12.904     0.942
+      62.5     187.5    13.828    13.828     1.000
+      62.5     192.5    14.830    14.830     1.000
+      62.5     197.5    15.884    15.884     1.000
+      62.5     202.5    16.964    16.964     1.000
+      62.5     207.5    18.040    18.040     1.000
+      62.5     212.5    19.088    19.088     1.000
+      62.5     217.5    20.086    20.086     1.000
+      62.5     222.5    21.014    21.014     1.000
+      62.5     227.5    21.858    21.858     1.000
+      62.5     232.5    22.606    22.606     1.000
+      62.5     237.5    23.246    23.246     1.000
+      62.5     242.5    23.768    23.768     1.000
+      62.5     247.5    24.166    24.166     1.000
+      62.5     252.5    24.428    24.428     1.000
+      62.5     257.5    24.364    24.542     0.865
+      62.5     262.5    24.158    24.428     0.170
+      62.5     267.5    24.068    24.068     1.000
+      62.5     272.5    23.848    23.848     1.000
+      62.5     277.5    23.496    23.496     1.000
+      62.5     282.5    23.018    23.018     1.000
+      62.5     287.5    22.428    22.428     1.000
+      62.5     292.5    21.738    21.738     1.000
+      62.5     297.5    20.960    20.960     1.000
+      62.5     302.5    20.258    20.258     1.000
+      62.5     307.5    19.602    19.602     1.000
+      62.5     312.5    18.894    18.894     1.000
+      62.5     317.5    18.138    18.138     1.000
+      62.5     322.5    17.344    17.344     1.000
+      62.5     327.5    16.516    16.516     1.000
+      62.5     332.5    15.662    15.662     1.000
+      62.5     337.5    14.792    14.792     1.000
+      62.5     342.5    13.906    13.906     1.000
+      62.5     347.5    13.010    13.010     1.000
+      62.5     352.5    12.116    12.116     1.000
+      62.5     357.5    11.222    11.222     1.000
+      67.5       2.5    11.650    11.650     1.000
+      67.5       7.5    10.674    10.674     1.000
+      67.5      12.5     9.716     9.716     1.000
+      67.5      17.5     8.774     8.774     1.000
+      67.5      22.5     7.928     8.408     0.458
+      67.5      27.5     7.678     8.176     0.530
+      67.5      32.5     7.416     7.970     0.588
+      67.5      37.5     7.170     7.800     0.679
+      67.5      42.5     7.006     7.680     0.858
+      67.5      47.5     7.052     7.638     0.891
+      67.5      52.5     7.474     7.736     0.672
+      67.5      57.5     7.052     8.076     0.818
+      67.5      62.5     7.996     8.420     0.354
+      67.5      67.5     8.232     8.564     0.217
+      67.5      72.5     7.112     8.600     0.825
+      67.5      77.5     7.406     8.424     0.688
+      67.5      82.5     7.042     8.550     0.633
+      67.5      87.5     7.306     8.376     0.329
+      67.5      92.5     7.380     8.408     0.241
+      67.5      97.5     7.540     8.368     0.169
+      67.5     102.5     7.596     8.372     0.242
+      67.5     107.5     7.640     8.342     0.302
+      67.5     112.5     7.664     8.340     0.349
+      67.5     117.5     7.700     8.352     0.396
+      67.5     122.5     7.744     8.388     0.475
+      67.5     127.5     7.810     8.452     0.486
+      67.5     132.5     7.904     8.540     0.591
+      67.5     137.5     8.024     8.680     0.655
+      67.5     142.5     8.150     8.856     0.756
+      67.5     147.5     8.352     9.084     0.885
+      67.5     152.5     8.888     9.374     0.905
+      67.5     157.5     9.248     9.740     0.907
+      67.5     162.5    10.090    10.194     0.500
+      67.5     167.5    10.642    10.756     0.667
+      67.5     172.5    11.322    11.440     0.797
+      67.5     177.5    12.152    12.260     0.889
+      67.5     182.5    13.222    13.222     1.000
+      67.5     187.5    14.314    14.314     1.000
+      67.5     192.5    15.512    15.512     1.000
+      67.5     197.5    16.778    16.778     1.000
+      67.5     202.5    18.072    18.072     1.000
+      67.5     207.5    19.360    19.360     1.000
+      67.5     212.5    20.606    20.606     1.000
+      67.5     217.5    21.784    21.784     1.000
+      67.5     222.5    22.876    22.876     1.000
+      67.5     227.5    23.860    23.860     1.000
+      67.5     232.5    24.726    24.726     1.000
+      67.5     237.5    25.458    25.458     1.000
+      67.5     242.5    26.046    26.046     1.000
+      67.5     247.5    26.480    26.480     1.000
+      67.5     252.5    26.742    26.742     1.000
+      67.5     257.5    26.566    26.758     0.563
+      67.5     262.5    26.592    26.592     1.000
+      67.5     267.5    26.458    26.458     1.000
+      67.5     272.5    26.160    26.160     1.000
+      67.5     277.5    25.700    25.700     1.000
+      67.5     282.5    25.094    25.094     1.000
+      67.5     287.5    24.676    24.676     1.000
+      67.5     292.5    24.186    24.186     1.000
+      67.5     297.5    23.604    23.604     1.000
+      67.5     302.5    22.938    22.938     1.000
+      67.5     307.5    22.194    22.194     1.000
+      67.5     312.5    21.388    21.388     1.000
+      67.5     317.5    20.524    20.524     1.000
+      67.5     322.5    19.610    19.610     1.000
+      67.5     327.5    18.660    18.660     1.000
+      67.5     332.5    17.680    17.680     1.000
+      67.5     337.5    16.682    16.682     1.000
+      67.5     342.5    15.670    15.670     1.000
+      67.5     347.5    14.656    14.656     1.000
+      67.5     352.5    13.646    13.646     1.000
+      67.5     357.5    12.642    12.642     1.000
+      72.5       2.5    13.088    13.088     1.000
+      72.5       7.5    11.996    11.996     1.000
+      72.5      12.5    10.930    10.930     1.000
+      72.5      17.5     9.898     9.898     1.000
+      72.5      22.5     8.890     8.890     1.000
+      72.5      27.5     7.912     8.336     0.392
+      72.5      32.5     7.608     8.082     0.422
+      72.5      37.5     7.342     7.858     0.488
+      72.5      42.5     7.098     7.672     0.551
+      72.5      47.5     7.004     7.534     0.766
+      72.5      52.5     7.008     7.470     0.870
+      72.5      57.5     7.104     7.554     0.831
+      72.5      62.5     7.048     7.904     0.806
+      72.5      67.5     7.896     8.314     0.344
+      72.5      72.5     8.170     8.484     0.191
+      72.5      77.5     7.172     8.534     0.815
+      72.5      82.5     7.606     8.510     0.462
+      72.5      87.5     7.176     8.358     0.645
+      72.5      92.5     7.240     8.338     0.346
+      72.5      97.5     7.462     8.310     0.189
+      72.5     102.5     7.570     8.286     0.218
+      72.5     107.5     7.618     8.324     0.252
+      72.5     112.5     7.652     8.324     0.307
+      72.5     117.5     7.686     8.330     0.391
+      72.5     122.5     7.726     8.358     0.440
+      72.5     127.5     7.802     8.414     0.503
+      72.5     132.5     7.888     8.502     0.577
+      72.5     137.5     7.994     8.628     0.637
+      72.5     142.5     8.120     8.800     0.732
+      72.5     147.5     8.308     9.024     0.874
+      72.5     152.5     8.676     9.316     0.931
+      72.5     157.5     9.584     9.690     0.660
+      72.5     162.5    10.058    10.164     0.585
+      72.5     167.5    10.644    10.762     0.610
+      72.5     172.5    11.392    11.512     0.833
+      72.5     177.5    12.330    12.440     0.945
+      72.5     182.5    13.554    13.554     1.000
+      72.5     187.5    14.850    14.850     1.000
+      72.5     192.5    16.288    16.288     1.000
+      72.5     197.5    17.814    17.814     1.000
+      72.5     202.5    19.372    19.372     1.000
+      72.5     207.5    20.912    20.912     1.000
+      72.5     212.5    22.392    22.392     1.000
+      72.5     217.5    23.784    23.784     1.000
+      72.5     222.5    25.060    25.060     1.000
+      72.5     227.5    26.204    26.204     1.000
+      72.5     232.5    27.198    27.198     1.000
+      72.5     237.5    28.030    28.030     1.000
+      72.5     242.5    28.684    28.684     1.000
+      72.5     247.5    29.142    29.142     1.000
+      72.5     252.5    29.332    29.336     0.000
+      72.5     257.5    29.434    29.434     1.000
+      72.5     262.5    29.432    29.432     1.000
+      72.5     267.5    29.232    29.232     1.000
+      72.5     272.5    29.036    29.036     1.000
+      72.5     277.5    28.874    28.874     1.000
+      72.5     282.5    28.572    28.572     1.000
+      72.5     287.5    28.138    28.138     1.000
+      72.5     292.5    27.580    27.580     1.000
+      72.5     297.5    26.908    26.908     1.000
+      72.5     302.5    26.130    26.130     1.000
+      72.5     307.5    25.264    25.264     1.000
+      72.5     312.5    24.316    24.316     1.000
+      72.5     317.5    23.304    23.304     1.000
+      72.5     322.5    22.236    22.236     1.000
+      72.5     327.5    21.124    21.124     1.000
+      72.5     332.5    19.986    19.986     1.000
+      72.5     337.5    18.828    18.828     1.000
+      72.5     342.5    17.660    17.660     1.000
+      72.5     347.5    16.498    16.498     1.000
+      72.5     352.5    15.344    15.344     1.000
+      72.5     357.5    14.204    14.204     1.000
+      77.5       2.5    14.692    14.692     1.000
+      77.5       7.5    13.456    13.456     1.000
+      77.5      12.5    12.264    12.264     1.000
+      77.5      17.5    11.112    11.112     1.000
+      77.5      22.5    10.004    10.004     1.000
+      77.5      27.5     8.936     8.936     1.000
+      77.5      32.5     7.906     8.266     0.372
+      77.5      37.5     7.530     7.994     0.358
+      77.5      42.5     7.264     7.760     0.419
+      77.5      47.5     7.024     7.566     0.517
+      77.5      52.5     7.002     7.428     0.685
+      77.5      57.5     7.090     7.362     0.801
+      77.5      62.5     7.066     7.452     0.808
+      77.5      67.5     7.420     7.846     0.592
+      77.5      72.5     7.892     8.290     0.312
+      77.5      77.5     8.162     8.462     0.160
+      77.5      82.5     7.436     8.504     0.738
+      77.5      87.5     7.752     8.358     0.380
+      77.5      92.5     7.212     8.420     0.349
+      77.5      97.5     7.388     8.424     0.214
+      77.5     102.5     7.550     8.234     0.225
+      77.5     107.5     7.618     8.274     0.256
+      77.5     112.5     7.662     8.332     0.304
+      77.5     117.5     7.696     8.332     0.343
+      77.5     122.5     7.740     8.352     0.425
+      77.5     127.5     7.790     8.394     0.490
+      77.5     132.5     7.858     8.472     0.567
+      77.5     137.5     7.994     8.596     0.618
+      77.5     142.5     8.142     8.758     0.718
+      77.5     147.5     8.292     8.978     0.886
+      77.5     152.5     8.542     9.264     0.928
+      77.5     157.5     9.190     9.638     0.902
+      77.5     162.5    10.018    10.122     0.596
+      77.5     167.5    10.628    10.750     0.656
+      77.5     172.5    11.458    11.560     0.824
+      77.5     177.5    12.582    12.596     0.857
+      77.5     182.5    13.888    13.888     1.000
+      77.5     187.5    15.430    15.430     1.000
+      77.5     192.5    17.168    17.168     1.000
+      77.5     197.5    19.022    19.022     1.000
+      77.5     202.5    20.904    20.904     1.000
+      77.5     207.5    22.750    22.750     1.000
+      77.5     212.5    24.508    24.508     1.000
+      77.5     217.5    26.144    26.144     1.000
+      77.5     222.5    27.634    27.634     1.000
+      77.5     227.5    28.956    28.956     1.000
+      77.5     232.5    30.092    30.092     1.000
+      77.5     237.5    31.026    31.026     1.000
+      77.5     242.5    31.734    31.734     1.000
+      77.5     247.5    32.210    32.210     1.000
+      77.5     252.5    32.628    32.628     1.000
+      77.5     257.5    32.926    32.926     1.000
+      77.5     262.5    33.312    33.312     1.000
+      77.5     267.5    33.502    33.502     1.000
+      77.5     272.5    33.502    33.502     1.000
+      77.5     277.5    33.324    33.324     1.000
+      77.5     282.5    32.966    32.966     1.000
+      77.5     287.5    32.452    32.452     1.000
+      77.5     292.5    31.782    31.782     1.000
+      77.5     297.5    30.974    30.974     1.000
+      77.5     302.5    30.038    30.038     1.000
+      77.5     307.5    28.994    28.994     1.000
+      77.5     312.5    27.856    27.856     1.000
+      77.5     317.5    26.640    26.640     1.000
+      77.5     322.5    25.362    25.362     1.000
+      77.5     327.5    24.042    24.042     1.000
+      77.5     332.5    22.690    22.690     1.000
+      77.5     337.5    21.328    21.328     1.000
+      77.5     342.5    19.962    19.962     1.000
+      77.5     347.5    18.606    18.606     1.000
+      77.5     352.5    17.272    17.272     1.000
+      77.5     357.5    15.964    15.964     1.000
Index: /tags/Mars-V0.9/mfilter/gcplus.txt
===================================================================
--- /tags/Mars-V0.9/mfilter/gcplus.txt	(revision 9772)
+++ /tags/Mars-V0.9/mfilter/gcplus.txt	(revision 9772)
@@ -0,0 +1,1152 @@
+       2.5       2.5    10.784    11.906     0.715
+       2.5       7.5    10.804    11.926     0.720
+       2.5      12.5    10.824    11.946     0.724
+       2.5      17.5    10.842    11.962     0.727
+       2.5      22.5    10.860    11.980     0.732
+       2.5      27.5    10.876    11.994     0.735
+       2.5      32.5    10.890    12.008     0.741
+       2.5      37.5    10.902    12.018     0.744
+       2.5      42.5    10.912    12.028     0.746
+       2.5      47.5    10.920    12.036     0.749
+       2.5      52.5    10.926    12.042     0.758
+       2.5      57.5    10.932    12.046     0.758
+       2.5      62.5    10.932    12.046     0.761
+       2.5      67.5    10.932    12.046     0.763
+       2.5      72.5    10.930    12.044     0.763
+       2.5      77.5    10.926    12.040     0.772
+       2.5      82.5    10.920    12.032     0.764
+       2.5      87.5    10.910    12.024     0.765
+       2.5      92.5    10.898    12.014     0.771
+       2.5      97.5    10.886    12.000     0.774
+       2.5     102.5    10.872    11.986     0.770
+       2.5     107.5    10.856    11.970     0.772
+       2.5     112.5    10.838    11.954     0.763
+       2.5     117.5    10.818    11.936     0.764
+       2.5     122.5    10.798    11.916     0.764
+       2.5     127.5    10.776    11.894     0.758
+       2.5     132.5    10.754    11.872     0.757
+       2.5     137.5    10.732    11.850     0.757
+       2.5     142.5    10.708    11.828     0.754
+       2.5     147.5    10.684    11.804     0.752
+       2.5     152.5    10.660    11.782     0.745
+       2.5     157.5    10.636    11.758     0.743
+       2.5     162.5    10.612    11.734     0.743
+       2.5     167.5    10.588    11.712     0.735
+       2.5     172.5    10.566    11.690     0.730
+       2.5     177.5    10.544    11.668     0.726
+       2.5     182.5    10.522    11.648     0.723
+       2.5     187.5    10.504    11.630     0.718
+       2.5     192.5    10.484    11.612     0.716
+       2.5     197.5    10.468    11.594     0.709
+       2.5     202.5    10.452    11.578     0.707
+       2.5     207.5    10.438    11.566     0.704
+       2.5     212.5    10.424    11.552     0.697
+       2.5     217.5    10.414    11.542     0.695
+       2.5     222.5    10.406    11.534     0.693
+       2.5     227.5    10.398    11.526     0.691
+       2.5     232.5    10.392    11.522     0.687
+       2.5     237.5    10.388    11.520     0.682
+       2.5     242.5    10.388    11.518     0.687
+       2.5     247.5    10.388    11.518     0.681
+       2.5     252.5    10.390    11.522     0.675
+       2.5     257.5    10.396    11.526     0.681
+       2.5     262.5    10.402    11.532     0.673
+       2.5     267.5    10.410    11.542     0.675
+       2.5     272.5    10.420    11.552     0.675
+       2.5     277.5    10.432    11.564     0.675
+       2.5     282.5    10.444    11.576     0.668
+       2.5     287.5    10.460    11.592     0.673
+       2.5     292.5    10.476    11.608     0.678
+       2.5     297.5    10.494    11.626     0.677
+       2.5     302.5    10.512    11.644     0.677
+       2.5     307.5    10.532    11.664     0.678
+       2.5     312.5    10.554    11.684     0.683
+       2.5     317.5    10.576    11.706     0.683
+       2.5     322.5    10.598    11.728     0.685
+       2.5     327.5    10.622    11.750     0.691
+       2.5     332.5    10.646    11.774     0.697
+       2.5     337.5    10.668    11.796     0.697
+       2.5     342.5    10.692    11.820     0.702
+       2.5     347.5    10.716    11.842     0.703
+       2.5     352.5    10.740    11.864     0.705
+       2.5     357.5    10.762    11.886     0.710
+       7.5       2.5    11.054    12.188     0.714
+       7.5       7.5    11.120    12.250     0.724
+       7.5      12.5    11.184    12.310     0.737
+       7.5      17.5    11.244    12.364     0.748
+       7.5      22.5    11.300    12.416     0.758
+       7.5      27.5    11.352    12.464     0.775
+       7.5      32.5    11.398    12.508     0.786
+       7.5      37.5    11.440    12.544     0.803
+       7.5      42.5    11.474    12.576     0.815
+       7.5      47.5    11.504    12.602     0.832
+       7.5      52.5    11.526    12.622     0.839
+       7.5      57.5    11.540    12.636     0.843
+       7.5      62.5    11.548    12.642     0.856
+       7.5      67.5    11.550    12.642     0.864
+       7.5      72.5    11.542    12.636     0.870
+       7.5      77.5    11.528    12.622     0.878
+       7.5      82.5    11.508    12.602     0.878
+       7.5      87.5    11.480    12.574     0.887
+       7.5      92.5    11.444    12.542     0.885
+       7.5      97.5    11.404    12.502     0.885
+       7.5     102.5    11.356    12.458     0.891
+       7.5     107.5    11.304    12.408     0.889
+       7.5     112.5    11.246    12.352     0.882
+       7.5     117.5    11.184    12.294     0.879
+       7.5     122.5    11.118    12.230     0.867
+       7.5     127.5    11.050    12.166     0.864
+       7.5     132.5    10.978    12.096     0.857
+       7.5     137.5    10.906    12.026     0.848
+       7.5     142.5    10.830    11.956     0.837
+       7.5     147.5    10.756    11.884     0.826
+       7.5     152.5    10.682    11.812     0.816
+       7.5     157.5    10.608    11.740     0.804
+       7.5     162.5    10.536    11.670     0.794
+       7.5     167.5    10.466    11.602     0.780
+       7.5     172.5    10.400    11.536     0.764
+       7.5     177.5    10.336    11.474     0.749
+       7.5     182.5    10.274    11.414     0.740
+       7.5     187.5    10.220    11.356     0.729
+       7.5     192.5    10.176    11.304     0.725
+       7.5     197.5    10.124    11.256     0.723
+       7.5     202.5    10.088    11.212     0.703
+       7.5     207.5    10.054    11.174     0.707
+       7.5     212.5    10.026    11.140     0.698
+       7.5     217.5     9.990    11.112     0.693
+       7.5     222.5     9.970    11.088     0.669
+       7.5     227.5     9.942    11.070     0.674
+       7.5     232.5     9.950    11.058     0.666
+       7.5     237.5     9.934    11.050     0.654
+       7.5     242.5     9.922    11.048     0.655
+       7.5     247.5     9.924    11.052     0.651
+       7.5     252.5     9.930    11.062     0.636
+       7.5     257.5     9.938    11.076     0.638
+       7.5     262.5     9.952    11.094     0.625
+       7.5     267.5     9.980    11.118     0.619
+       7.5     272.5    10.000    11.148     0.622
+       7.5     277.5    10.032    11.182     0.603
+       7.5     282.5    10.064    11.220     0.600
+       7.5     287.5    10.104    11.262     0.603
+       7.5     292.5    10.150    11.308     0.603
+       7.5     297.5    10.198    11.360     0.609
+       7.5     302.5    10.252    11.412     0.609
+       7.5     307.5    10.308    11.470     0.613
+       7.5     312.5    10.368    11.528     0.616
+       7.5     317.5    10.430    11.590     0.617
+       7.5     322.5    10.496    11.654     0.623
+       7.5     327.5    10.562    11.720     0.636
+       7.5     332.5    10.632    11.788     0.647
+       7.5     337.5    10.702    11.856     0.659
+       7.5     342.5    10.774    11.924     0.664
+       7.5     347.5    10.844    11.992     0.676
+       7.5     352.5    10.916    12.058     0.685
+       7.5     357.5    10.986    12.124     0.699
+      12.5       2.5    11.334    12.494     0.710
+      12.5       7.5    11.450    12.602     0.733
+      12.5      12.5    11.564    12.704     0.754
+      12.5      17.5    11.672    12.802     0.779
+      12.5      22.5    11.774    12.894     0.802
+      12.5      27.5    11.868    12.980     0.824
+      12.5      32.5    11.952    13.058     0.846
+      12.5      37.5    12.030    13.126     0.867
+      12.5      42.5    12.098    13.186     0.893
+      12.5      47.5    12.152    13.234     0.911
+      12.5      52.5    12.194    13.272     0.928
+      12.5      57.5    12.224    13.298     0.944
+      12.5      62.5    12.266    13.314     0.952
+      12.5      67.5    12.482    13.316     0.945
+      12.5      72.5    12.468    13.306     0.950
+      12.5      77.5    12.440    13.284     0.950
+      12.5      82.5    12.402    13.250     0.953
+      12.5      87.5    12.352    13.202     0.955
+      12.5      92.5    12.292    13.144     0.958
+      12.5      97.5    12.222    13.076     0.953
+      12.5     102.5    12.142    12.998     0.956
+      12.5     107.5    12.054    12.908     0.956
+      12.5     112.5    11.960    12.812     0.955
+      12.5     117.5    11.608    12.708     0.962
+      12.5     122.5    11.500    12.598     0.958
+      12.5     127.5    11.388    12.482     0.949
+      12.5     132.5    11.276    12.362     0.943
+      12.5     137.5    11.136    12.240     0.940
+      12.5     142.5    11.012    12.114     0.931
+      12.5     147.5    10.898    11.990     0.930
+      12.5     152.5    10.788    11.866     0.920
+      12.5     157.5    10.682    11.746     0.915
+      12.5     162.5    10.580    11.626     0.904
+      12.5     167.5    10.486    11.512     0.899
+      12.5     172.5    10.250    11.402     0.887
+      12.5     177.5    10.164    11.298     0.862
+      12.5     182.5    10.084    11.198     0.833
+      12.5     187.5    10.008    11.108     0.807
+      12.5     192.5     9.938    11.022     0.795
+      12.5     197.5     9.874    10.946     0.778
+      12.5     202.5     9.816    10.878     0.759
+      12.5     207.5     9.676    10.818     0.751
+      12.5     212.5     9.632    10.766     0.743
+      12.5     217.5     9.602    10.722     0.718
+      12.5     222.5     9.564    10.688     0.699
+      12.5     227.5     9.550    10.660     0.688
+      12.5     232.5     9.524    10.644     0.686
+      12.5     237.5     9.512    10.634     0.663
+      12.5     242.5     9.498    10.634     0.662
+      12.5     247.5     9.520    10.640     0.630
+      12.5     252.5     9.528    10.656     0.631
+      12.5     257.5     9.540    10.680     0.621
+      12.5     262.5     9.548    10.712     0.612
+      12.5     267.5     9.582    10.750     0.592
+      12.5     272.5     9.632    10.796     0.591
+      12.5     277.5     9.678    10.850     0.578
+      12.5     282.5     9.750    10.910     0.572
+      12.5     287.5     9.796    10.978     0.565
+      12.5     292.5     9.848    11.050     0.559
+      12.5     297.5     9.924    11.130     0.547
+      12.5     302.5     9.998    11.216     0.548
+      12.5     307.5    10.086    11.306     0.549
+      12.5     312.5    10.180    11.400     0.557
+      12.5     317.5    10.278    11.500     0.561
+      12.5     322.5    10.384    11.604     0.575
+      12.5     327.5    10.494    11.710     0.587
+      12.5     332.5    10.608    11.820     0.601
+      12.5     337.5    10.726    11.932     0.622
+      12.5     342.5    10.846    12.046     0.630
+      12.5     347.5    10.968    12.158     0.652
+      12.5     352.5    11.092    12.272     0.671
+      12.5     357.5    11.212    12.384     0.691
+      17.5       2.5    11.616    12.826     0.711
+      17.5       7.5    11.794    12.982     0.744
+      17.5      12.5    11.962    13.134     0.778
+      17.5      17.5    12.130    13.278     0.807
+      17.5      22.5    12.284    13.416     0.839
+      17.5      27.5    12.430    13.544     0.873
+      17.5      32.5    12.562    13.662     0.904
+      17.5      37.5    12.682    13.768     0.936
+      17.5      42.5    12.808    13.860     0.951
+      17.5      47.5    13.088    13.936     0.948
+      17.5      52.5    13.140    13.998     0.953
+      17.5      57.5    13.174    14.042     0.959
+      17.5      62.5    13.192    14.068     0.963
+      17.5      67.5    13.262    14.076     0.968
+      17.5      72.5    13.242    14.064     0.973
+      17.5      77.5    13.206    14.034     0.973
+      17.5      82.5    13.150    13.986     0.978
+      17.5      87.5    13.078    13.918     0.979
+      17.5      92.5    12.990    13.834     0.983
+      17.5      97.5    12.886    13.732     0.983
+      17.5     102.5    12.768    13.616     0.983
+      17.5     107.5    12.638    13.484     0.983
+      17.5     112.5    12.496    13.340     0.981
+      17.5     117.5    12.346    13.184     0.981
+      17.5     122.5    12.188    13.020     0.978
+      17.5     127.5    12.026    12.848     0.973
+      17.5     132.5    11.860    12.672     0.970
+      17.5     137.5    11.694    12.490     0.967
+      17.5     142.5    11.528    12.308     0.962
+      17.5     147.5    11.362    12.128     0.945
+      17.5     152.5    11.202    11.948     0.930
+      17.5     157.5    11.046    11.772     0.917
+      17.5     162.5    10.886    11.604     0.905
+      17.5     167.5    10.654    11.440     0.903
+      17.5     172.5    10.522    11.286     0.908
+      17.5     177.5    10.480    11.140     0.894
+      17.5     182.5    10.064    11.004     0.917
+      17.5     187.5     9.892    10.880     0.897
+      17.5     192.5     9.724    10.766     0.902
+      17.5     197.5     9.638    10.662     0.848
+      17.5     202.5     9.568    10.572     0.827
+      17.5     207.5     9.502    10.492     0.786
+      17.5     212.5     9.444    10.426     0.756
+      17.5     217.5     9.268    10.370     0.757
+      17.5     222.5     9.272    10.328     0.710
+      17.5     227.5     9.252    10.296     0.703
+      17.5     232.5     9.232    10.274     0.676
+      17.5     237.5     9.220    10.266     0.660
+      17.5     242.5     9.194    10.266     0.655
+      17.5     247.5     9.220    10.278     0.628
+      17.5     252.5     9.226    10.302     0.615
+      17.5     257.5     9.188    10.334     0.606
+      17.5     262.5     9.238    10.378     0.581
+      17.5     267.5     9.220    10.430     0.582
+      17.5     272.5     9.308    10.492     0.566
+      17.5     277.5     9.348    10.562     0.544
+      17.5     282.5     9.392    10.642     0.542
+      17.5     287.5     9.458    10.732     0.543
+      17.5     292.5     9.542    10.828     0.535
+      17.5     297.5     9.626    10.934     0.517
+      17.5     302.5     9.734    11.048     0.502
+      17.5     307.5     9.838    11.168     0.490
+      17.5     312.5     9.960    11.296     0.500
+      17.5     317.5    10.092    11.430     0.510
+      17.5     322.5    10.236    11.572     0.527
+      17.5     327.5    10.390    11.718     0.541
+      17.5     332.5    10.550    11.870     0.553
+      17.5     337.5    10.720    12.024     0.577
+      17.5     342.5    10.894    12.184     0.602
+      17.5     347.5    11.074    12.344     0.624
+      17.5     352.5    11.254    12.504     0.653
+      17.5     357.5    11.436    12.666     0.685
+      22.5       2.5    11.890    13.180     0.716
+      22.5       7.5    12.140    13.390     0.757
+      22.5      12.5    12.382    13.596     0.801
+      22.5      17.5    12.614    13.796     0.841
+      22.5      22.5    12.834    13.986     0.884
+      22.5      27.5    13.040    14.164     0.927
+      22.5      32.5    13.252    14.328     0.946
+      22.5      37.5    13.606    14.478     0.945
+      22.5      42.5    13.728    14.610     0.959
+      22.5      47.5    13.828    14.720     0.964
+      22.5      52.5    13.976    14.810     0.974
+      22.5      57.5    14.030    14.876     0.979
+      22.5      62.5    14.058    14.918     0.984
+      22.5      67.5    14.062    14.934     0.989
+      22.5      72.5    14.040    14.924     0.995
+      22.5      77.5    14.886    14.886     1.000
+      22.5      82.5    14.824    14.824     1.000
+      22.5      87.5    14.736    14.736     1.000
+      22.5      92.5    14.622    14.622     1.000
+      22.5      97.5    14.484    14.484     1.000
+      22.5     102.5    14.324    14.324     1.000
+      22.5     107.5    14.144    14.144     1.000
+      22.5     112.5    13.946    13.946     1.000
+      22.5     117.5    13.734    13.734     1.000
+      22.5     122.5    13.508    13.508     1.000
+      22.5     127.5    13.274    13.274     1.000
+      22.5     132.5    12.138    13.032     0.998
+      22.5     137.5    11.914    12.786     0.995
+      22.5     142.5    11.690    12.540     0.991
+      22.5     147.5    11.474    12.296     0.988
+      22.5     152.5    11.262    12.056     0.970
+      22.5     157.5    11.722    11.824     0.804
+      22.5     162.5    11.492    11.600     0.759
+      22.5     167.5    10.662    11.388     0.956
+      22.5     172.5    10.490    11.188     0.934
+      22.5     177.5    10.032    11.000     0.948
+      22.5     182.5    10.184    10.828     0.913
+      22.5     187.5     9.600    10.670     0.929
+      22.5     192.5     9.430    10.530     0.936
+      22.5     197.5     9.334    10.404     0.927
+      22.5     202.5     9.406    10.292     0.878
+      22.5     207.5     9.178    10.198     0.875
+      22.5     212.5     9.092    10.118     0.795
+      22.5     217.5     9.042    10.054     0.769
+      22.5     222.5     9.012    10.004     0.718
+      22.5     227.5     8.980     9.970     0.687
+      22.5     232.5     8.966     9.948     0.668
+      22.5     237.5     8.976     9.940     0.639
+      22.5     242.5     8.936     9.944     0.607
+      22.5     247.5     8.880     9.962     0.614
+      22.5     252.5     8.884     9.992     0.592
+      22.5     257.5     8.950    10.034     0.555
+      22.5     262.5     8.922    10.088     0.566
+      22.5     267.5     8.972    10.152     0.553
+      22.5     272.5     8.970    10.228     0.547
+      22.5     277.5     9.030    10.314     0.531
+      22.5     282.5     9.066    10.412     0.523
+      22.5     287.5     9.158    10.520     0.501
+      22.5     292.5     9.190    10.638     0.500
+      22.5     297.5     9.280    10.766     0.495
+      22.5     302.5     9.390    10.904     0.483
+      22.5     307.5     9.542    11.052     0.461
+      22.5     312.5     9.628    11.210     0.459
+      22.5     317.5     9.780    11.378     0.452
+      22.5     322.5     9.964    11.552     0.467
+      22.5     327.5    10.168    11.738     0.490
+      22.5     332.5    10.390    11.930     0.506
+      22.5     337.5    10.626    12.128     0.547
+      22.5     342.5    10.872    12.332     0.573
+      22.5     347.5    11.124    12.542     0.605
+      22.5     352.5    11.382    12.754     0.643
+      22.5     357.5    11.638    12.966     0.682
+      27.5       2.5    12.132    13.556     0.739
+      27.5       7.5    12.478    13.826     0.782
+      27.5      12.5    12.810    14.094     0.829
+      27.5      17.5    13.124    14.354     0.881
+      27.5      22.5    13.422    14.604     0.927
+      27.5      27.5    13.712    14.842     0.942
+      27.5      32.5    14.156    15.062     0.940
+      27.5      37.5    14.350    15.264     0.958
+      27.5      42.5    14.586    15.442     0.967
+      27.5      47.5    14.726    15.594     0.979
+      27.5      52.5    14.836    15.720     0.986
+      27.5      57.5    14.914    15.814     0.996
+      27.5      62.5    15.876    15.876     1.000
+      27.5      67.5    15.904    15.904     1.000
+      27.5      72.5    15.898    15.898     1.000
+      27.5      77.5    15.856    15.856     1.000
+      27.5      82.5    15.780    15.780     1.000
+      27.5      87.5    15.668    15.668     1.000
+      27.5      92.5    15.522    15.522     1.000
+      27.5      97.5    15.344    15.344     1.000
+      27.5     102.5    15.136    15.136     1.000
+      27.5     107.5    14.902    14.902     1.000
+      27.5     112.5    14.644    14.644     1.000
+      27.5     117.5    14.366    14.366     1.000
+      27.5     122.5    14.070    14.070     1.000
+      27.5     127.5    13.764    13.764     1.000
+      27.5     132.5    13.448    13.448     1.000
+      27.5     137.5    13.130    13.130     1.000
+      27.5     142.5    12.812    12.812     1.000
+      27.5     147.5    12.498    12.498     1.000
+      27.5     152.5    12.192    12.192     1.000
+      27.5     157.5    11.790    11.898     0.852
+      27.5     162.5    11.500    11.616     0.741
+      27.5     167.5    11.242    11.352     0.727
+      27.5     172.5    11.000    11.104     0.712
+      27.5     177.5    10.196    10.876     0.929
+      27.5     182.5    10.022    10.668     0.926
+      27.5     187.5     9.492    10.480     0.945
+      27.5     192.5     9.304    10.314     0.950
+      27.5     197.5     9.194    10.166     0.928
+      27.5     202.5     8.958    10.038     0.926
+      27.5     207.5     9.022     9.930     0.899
+      27.5     212.5     8.958     9.842     0.846
+      27.5     217.5     8.828     9.770     0.788
+      27.5     222.5     8.742     9.718     0.744
+      27.5     227.5     8.738     9.680     0.694
+      27.5     232.5     8.672     9.660     0.690
+      27.5     237.5     8.654     9.654     0.652
+      27.5     242.5     8.712     9.664     0.592
+      27.5     247.5     8.714     9.686     0.582
+      27.5     252.5     8.652     9.724     0.576
+      27.5     257.5     8.662     9.774     0.565
+      27.5     262.5     8.676     9.838     0.547
+      27.5     267.5     8.680     9.912     0.524
+      27.5     272.5     8.702    10.000     0.519
+      27.5     277.5     8.816    10.100     0.475
+      27.5     282.5     8.748    10.212     0.503
+      27.5     287.5     8.808    10.336     0.493
+      27.5     292.5     8.868    10.472     0.484
+      27.5     297.5     9.000    10.620     0.459
+      27.5     302.5     8.858    10.778     0.517
+      27.5     307.5     8.480    10.950     0.621
+      27.5     312.5     9.210    11.134     0.524
+      27.5     317.5     9.282    11.332     0.572
+      27.5     322.5     9.444    11.540     0.599
+      27.5     327.5     9.598    11.760     0.629
+      27.5     332.5     9.766    11.992     0.623
+      27.5     337.5     9.936    12.236     0.608
+      27.5     342.5    10.530    12.488     0.540
+      27.5     347.5    10.990    12.748     0.596
+      27.5     352.5    11.392    13.014     0.651
+      27.5     357.5    11.770    13.284     0.690
+      32.5       2.5    12.386    13.948     0.832
+      32.5       7.5    12.762    14.288     0.857
+      32.5      12.5    13.226    14.626     0.896
+      32.5      17.5    13.688    14.956     0.918
+      32.5      22.5    14.314    15.278     0.919
+      32.5      27.5    14.628    15.584     0.941
+      32.5      32.5    14.992    15.870     0.957
+      32.5      37.5    15.246    16.132     0.968
+      32.5      42.5    15.468    16.368     0.982
+      32.5      47.5    15.656    16.570     0.993
+      32.5      52.5    16.740    16.740     1.000
+      32.5      57.5    16.870    16.870     1.000
+      32.5      62.5    16.958    16.958     1.000
+      32.5      67.5    17.004    17.004     1.000
+      32.5      72.5    17.004    17.004     1.000
+      32.5      77.5    16.960    16.960     1.000
+      32.5      82.5    16.870    16.870     1.000
+      32.5      87.5    16.734    16.734     1.000
+      32.5      92.5    16.552    16.552     1.000
+      32.5      97.5    16.330    16.330     1.000
+      32.5     102.5    16.070    16.070     1.000
+      32.5     107.5    15.774    15.774     1.000
+      32.5     112.5    15.446    15.446     1.000
+      32.5     117.5    15.092    15.092     1.000
+      32.5     122.5    14.718    14.718     1.000
+      32.5     127.5    14.328    14.328     1.000
+      32.5     132.5    13.930    13.930     1.000
+      32.5     137.5    13.528    13.528     1.000
+      32.5     142.5    13.128    13.128     1.000
+      32.5     147.5    12.736    12.736     1.000
+      32.5     152.5    12.356    12.356     1.000
+      32.5     157.5    11.880    11.994     0.895
+      32.5     162.5    11.526    11.652     0.746
+      32.5     167.5    11.216    11.332     0.759
+      32.5     172.5    10.928    11.036     0.722
+      32.5     177.5    10.100    10.766     0.946
+      32.5     182.5     9.906    10.524     0.945
+      32.5     187.5     9.690    10.306     0.932
+      32.5     192.5     9.536    10.116     0.910
+      32.5     197.5     8.874     9.950     0.941
+      32.5     202.5     8.826     9.808     0.923
+      32.5     207.5     8.820     9.690     0.903
+      32.5     212.5     8.746     9.594     0.868
+      32.5     217.5     8.626     9.518     0.798
+      32.5     222.5     8.540     9.462     0.753
+      32.5     227.5     8.546     9.426     0.686
+      32.5     232.5     8.314     9.406     0.718
+      32.5     237.5     8.514     9.406     0.601
+      32.5     242.5     8.268     9.420     0.655
+      32.5     247.5     8.506     9.450     0.566
+      32.5     252.5     8.502     9.494     0.534
+      32.5     257.5     8.438     9.550     0.538
+      32.5     262.5     8.474     9.624     0.511
+      32.5     267.5     8.460     9.708     0.492
+      32.5     272.5     8.410     9.806     0.509
+      32.5     277.5     8.494     9.916     0.466
+      32.5     282.5     8.484    10.040     0.463
+      32.5     287.5     8.400    10.176     0.511
+      32.5     292.5     8.614    10.324     0.526
+      32.5     297.5     8.746    10.488     0.692
+      32.5     302.5     8.704    10.664     0.682
+      32.5     307.5     9.138    10.854     0.749
+      32.5     312.5     9.994    11.062     0.566
+      32.5     317.5    10.134    11.282     0.580
+      32.5     322.5    10.300    11.520     0.584
+      32.5     327.5    10.498    11.776     0.587
+      32.5     332.5    10.760    12.046     0.589
+      32.5     337.5    11.046    12.334     0.616
+      32.5     342.5    11.380    12.634     0.641
+      32.5     347.5    11.740    12.950     0.678
+      32.5     352.5    12.118    13.274     0.708
+      32.5     357.5    11.778    13.608     0.779
+      37.5       2.5    12.924    14.344     0.776
+      37.5       7.5    13.508    14.766     0.819
+      37.5      12.5    14.030    15.186     0.865
+      37.5      17.5    14.512    15.602     0.906
+      37.5      22.5    14.958    16.006     0.927
+      37.5      27.5    15.372    16.394     0.951
+      37.5      32.5    15.830    16.758     0.968
+      37.5      37.5    16.162    17.096     0.983
+      37.5      42.5    17.398    17.398     1.000
+      37.5      47.5    17.664    17.664     1.000
+      37.5      52.5    17.886    17.886     1.000
+      37.5      57.5    18.060    18.060     1.000
+      37.5      62.5    18.184    18.184     1.000
+      37.5      67.5    18.252    18.252     1.000
+      37.5      72.5    18.264    18.264     1.000
+      37.5      77.5    18.220    18.220     1.000
+      37.5      82.5    18.116    18.116     1.000
+      37.5      87.5    17.954    17.954     1.000
+      37.5      92.5    17.736    17.736     1.000
+      37.5      97.5    17.464    17.464     1.000
+      37.5     102.5    17.144    17.144     1.000
+      37.5     107.5    16.776    16.776     1.000
+      37.5     112.5    16.370    16.370     1.000
+      37.5     117.5    15.930    15.930     1.000
+      37.5     122.5    15.464    15.464     1.000
+      37.5     127.5    14.978    14.978     1.000
+      37.5     132.5    14.484    14.484     1.000
+      37.5     137.5    13.986    13.986     1.000
+      37.5     142.5    13.492    13.492     1.000
+      37.5     147.5    13.012    13.012     1.000
+      37.5     152.5    12.550    12.550     1.000
+      37.5     157.5    11.992    12.112     0.967
+      37.5     162.5    11.566    11.704     0.783
+      37.5     167.5    11.200    11.326     0.778
+      37.5     172.5    10.866    10.980     0.754
+      37.5     177.5    10.566    10.668     0.765
+      37.5     182.5    10.232    10.392     0.788
+      37.5     187.5     9.534    10.146     0.938
+      37.5     192.5     8.954     9.934     0.957
+      37.5     197.5     8.762     9.752     0.947
+      37.5     202.5     8.736     9.600     0.933
+      37.5     207.5     8.598     9.472     0.902
+      37.5     212.5     8.588     9.372     0.870
+      37.5     217.5     8.392     9.294     0.809
+      37.5     222.5     8.392     9.238     0.742
+      37.5     227.5     8.150     9.204     0.744
+      37.5     232.5     8.342     9.188     0.629
+      37.5     237.5     8.064     9.192     0.693
+      37.5     242.5     8.284     9.210     0.564
+      37.5     247.5     8.026     9.246     0.633
+      37.5     252.5     8.242     9.298     0.528
+      37.5     257.5     7.944     9.362     0.599
+      37.5     262.5     8.272     9.440     0.462
+      37.5     267.5     8.164     9.534     0.492
+      37.5     272.5     8.002     9.640     0.520
+      37.5     277.5     8.044     9.758     0.510
+      37.5     282.5     8.264     9.888     0.563
+      37.5     287.5     7.760    10.032     0.689
+      37.5     292.5     9.210    10.190     0.512
+      37.5     297.5     9.210    10.360     0.525
+      37.5     302.5     8.210    10.548     0.721
+      37.5     307.5     8.440    10.750     0.721
+      37.5     312.5     9.336    10.972     0.516
+      37.5     317.5     8.436    11.212     0.612
+      37.5     322.5     9.244    11.474     0.713
+      37.5     327.5     9.704    11.758     0.862
+      37.5     332.5    10.022    12.066     0.854
+      37.5     337.5    10.366    12.398     0.758
+      37.5     342.5    10.626    12.752     0.560
+      37.5     347.5    10.712    13.128     0.449
+      37.5     352.5    11.958    13.520     0.666
+      37.5     357.5    11.526    13.928     0.774
+      42.5       2.5    14.410    14.722     0.641
+      42.5       7.5    13.612    15.244     0.805
+      42.5      12.5    14.486    15.766     0.863
+      42.5      17.5    15.154    16.284     0.912
+      42.5      22.5    15.742    16.790     0.939
+      42.5      27.5    16.272    17.276     0.960
+      42.5      32.5    16.750    17.736     0.980
+      42.5      37.5    18.164    18.164     1.000
+      42.5      42.5    18.550    18.550     1.000
+      42.5      47.5    18.890    18.890     1.000
+      42.5      52.5    19.178    19.178     1.000
+      42.5      57.5    19.406    19.406     1.000
+      42.5      62.5    19.574    19.574     1.000
+      42.5      67.5    19.674    19.674     1.000
+      42.5      72.5    19.702    19.702     1.000
+      42.5      77.5    19.660    19.660     1.000
+      42.5      82.5    19.546    19.546     1.000
+      42.5      87.5    19.358    19.358     1.000
+      42.5      92.5    19.098    19.098     1.000
+      42.5      97.5    18.772    18.772     1.000
+      42.5     102.5    18.380    18.380     1.000
+      42.5     107.5    17.934    17.934     1.000
+      42.5     112.5    17.436    17.436     1.000
+      42.5     117.5    16.896    16.896     1.000
+      42.5     122.5    16.322    16.322     1.000
+      42.5     127.5    15.726    15.726     1.000
+      42.5     132.5    15.120    15.120     1.000
+      42.5     137.5    14.510    14.510     1.000
+      42.5     142.5    13.910    13.910     1.000
+      42.5     147.5    13.330    13.330     1.000
+      42.5     152.5    12.774    12.774     1.000
+      42.5     157.5    12.254    12.254     1.000
+      42.5     162.5    11.620    11.772     0.803
+      42.5     167.5    11.194    11.330     0.765
+      42.5     172.5    10.814    10.934     0.783
+      42.5     177.5    10.474    10.580     0.736
+      42.5     182.5    10.166    10.270     0.712
+      42.5     187.5     9.440    10.000     0.943
+      42.5     192.5     9.214     9.770     0.917
+      42.5     197.5     8.800     9.574     0.941
+      42.5     202.5     8.444     9.410     0.917
+      42.5     207.5     8.450     9.278     0.908
+      42.5     212.5     8.408     9.176     0.896
+      42.5     217.5     8.066     9.098     0.866
+      42.5     222.5     8.248     9.044     0.731
+      42.5     227.5     8.032     9.012     0.716
+      42.5     232.5     7.944     9.002     0.703
+      42.5     237.5     7.968     9.008     0.646
+      42.5     242.5     7.976     9.034     0.612
+      42.5     247.5     7.848     9.076     0.601
+      42.5     252.5     7.744     9.132     0.611
+      42.5     257.5     8.100     9.204     0.447
+      42.5     262.5     7.940     9.288     0.485
+      42.5     267.5     7.804     9.388     0.510
+      42.5     272.5     7.722     9.498     0.542
+      42.5     277.5     8.052     9.618     0.642
+      42.5     282.5     8.794     9.752     0.480
+      42.5     287.5     8.668     9.898     0.522
+      42.5     292.5     8.536    10.054     0.576
+      42.5     297.5     8.310    10.224     0.524
+      42.5     302.5     8.890    10.410     0.767
+      42.5     307.5    10.232    10.612     0.347
+      42.5     312.5    10.426    10.834     0.363
+      42.5     317.5    10.662    11.076     0.357
+      42.5     322.5    10.902    11.352     0.369
+      42.5     327.5    11.196    11.658     0.385
+      42.5     332.5    11.538    11.998     0.417
+      42.5     337.5    11.922    12.376     0.401
+      42.5     342.5    12.356    12.790     0.433
+      42.5     347.5    12.828    13.236     0.466
+      42.5     352.5    13.332    13.712     0.516
+      42.5     357.5    13.862    14.208     0.561
+      47.5       2.5    14.608    15.028     0.662
+      47.5       7.5    15.324    15.686     0.729
+      47.5      12.5    16.034    16.344     0.832
+      47.5      17.5    15.450    16.992     0.969
+      47.5      22.5    16.396    17.624     0.963
+      47.5      27.5    17.128    18.232     0.976
+      47.5      32.5    17.758    18.810     0.998
+      47.5      37.5    19.346    19.346     1.000
+      47.5      42.5    19.834    19.834     1.000
+      47.5      47.5    20.268    20.268     1.000
+      47.5      52.5    20.636    20.636     1.000
+      47.5      57.5    20.934    20.934     1.000
+      47.5      62.5    21.156    21.156     1.000
+      47.5      67.5    21.296    21.296     1.000
+      47.5      72.5    21.350    21.350     1.000
+      47.5      77.5    21.314    21.314     1.000
+      47.5      82.5    21.190    21.190     1.000
+      47.5      87.5    20.974    20.974     1.000
+      47.5      92.5    20.670    20.670     1.000
+      47.5      97.5    20.280    20.280     1.000
+      47.5     102.5    19.812    19.812     1.000
+      47.5     107.5    19.272    19.272     1.000
+      47.5     112.5    18.668    18.668     1.000
+      47.5     117.5    18.012    18.012     1.000
+      47.5     122.5    17.314    17.314     1.000
+      47.5     127.5    16.588    16.588     1.000
+      47.5     132.5    15.850    15.850     1.000
+      47.5     137.5    15.112    15.112     1.000
+      47.5     142.5    14.386    14.386     1.000
+      47.5     147.5    13.688    13.688     1.000
+      47.5     152.5    13.028    13.028     1.000
+      47.5     157.5    12.414    12.414     1.000
+      47.5     162.5    11.680    11.852     0.791
+      47.5     167.5    11.196    11.346     0.787
+      47.5     172.5    10.766    10.896     0.800
+      47.5     177.5    10.330    10.500     0.835
+      47.5     182.5    10.008    10.158     0.787
+      47.5     187.5     9.156     9.866     0.946
+      47.5     192.5     8.638     9.618     0.955
+      47.5     197.5     8.538     9.412     0.952
+      47.5     202.5     8.784     9.242     0.882
+      47.5     207.5     8.354     9.108     0.920
+      47.5     212.5     8.188     9.004     0.880
+      47.5     217.5     8.150     8.928     0.789
+      47.5     222.5     7.892     8.878     0.775
+      47.5     227.5     7.920     8.850     0.692
+      47.5     232.5     8.014     8.844     0.600
+      47.5     237.5     7.796     8.856     0.645
+      47.5     242.5     7.840     8.888     0.599
+      47.5     247.5     7.676     8.936     0.598
+      47.5     252.5     7.904     8.998     0.468
+      47.5     257.5     7.820     9.074     0.470
+      47.5     262.5     7.620     9.164     0.500
+      47.5     267.5     7.512     9.264     0.574
+      47.5     272.5     7.690     9.372     0.665
+      47.5     277.5     8.442     9.492     0.448
+      47.5     282.5     7.654     9.622     0.611
+      47.5     287.5     7.864     9.758     0.596
+      47.5     292.5     7.882     9.898     0.855
+      47.5     297.5     9.630    10.048     0.254
+      47.5     302.5     7.694    10.206     0.870
+      47.5     307.5     9.818    10.378     0.332
+      47.5     312.5     9.896    10.560     0.352
+      47.5     317.5     9.958    10.764     0.387
+      47.5     322.5    10.000    11.002     0.431
+      47.5     327.5    10.042    11.286     0.466
+      47.5     332.5    10.222    11.636     0.511
+      47.5     337.5    10.842    12.064     0.509
+      47.5     342.5    11.624    12.568     0.479
+      47.5     347.5    12.398    13.132     0.485
+      47.5     352.5    13.150    13.740     0.549
+      47.5     357.5    13.884    14.376     0.598
+      52.5       2.5    11.658    15.078     0.835
+      52.5       7.5    15.476    15.998     0.801
+      52.5      12.5    16.454    16.866     0.869
+      52.5      17.5    17.696    17.696     1.000
+      52.5      22.5    18.496    18.496     1.000
+      52.5      27.5    19.260    19.260     1.000
+      52.5      32.5    19.984    19.984     1.000
+      52.5      37.5    20.656    20.656     1.000
+      52.5      42.5    21.272    21.272     1.000
+      52.5      47.5    21.818    21.818     1.000
+      52.5      52.5    22.288    22.288     1.000
+      52.5      57.5    22.672    22.672     1.000
+      52.5      62.5    22.964    22.964     1.000
+      52.5      67.5    23.156    23.156     1.000
+      52.5      72.5    23.242    23.242     1.000
+      52.5      77.5    23.220    23.220     1.000
+      52.5      82.5    23.088    23.088     1.000
+      52.5      87.5    22.844    22.844     1.000
+      52.5      92.5    22.490    22.490     1.000
+      52.5      97.5    22.032    22.032     1.000
+      52.5     102.5    21.474    21.474     1.000
+      52.5     107.5    20.826    20.826     1.000
+      52.5     112.5    20.098    20.098     1.000
+      52.5     117.5    19.306    19.306     1.000
+      52.5     122.5    18.462    18.462     1.000
+      52.5     127.5    17.584    17.584     1.000
+      52.5     132.5    16.690    16.690     1.000
+      52.5     137.5    15.798    15.798     1.000
+      52.5     142.5    14.926    14.926     1.000
+      52.5     147.5    14.092    14.092     1.000
+      52.5     152.5    13.310    13.310     1.000
+      52.5     157.5    12.590    12.590     1.000
+      52.5     162.5    11.748    11.942     0.804
+      52.5     167.5    11.200    11.366     0.819
+      52.5     172.5    10.722    10.862     0.800
+      52.5     177.5    10.308    10.426     0.797
+      52.5     182.5     9.944    10.054     0.709
+      52.5     187.5     9.648     9.742     0.702
+      52.5     192.5     8.982     9.480     0.936
+      52.5     197.5     8.432     9.266     0.950
+      52.5     202.5     8.270     9.094     0.944
+      52.5     207.5     8.178     8.958     0.923
+      52.5     212.5     7.794     8.856     0.919
+      52.5     217.5     8.012     8.776     0.793
+      52.5     222.5     8.004     8.738     0.706
+      52.5     227.5     7.714     8.714     0.730
+      52.5     232.5     7.724     8.714     0.675
+      52.5     237.5     7.764     8.734     0.598
+      52.5     242.5     7.646     8.770     0.578
+      52.5     247.5     7.474     8.824     0.601
+      52.5     252.5     7.728     8.890     0.468
+      52.5     257.5     7.570     8.970     0.480
+      52.5     262.5     7.290     9.060     0.567
+      52.5     267.5     7.476     9.158     0.687
+      52.5     272.5     8.154     9.262     0.455
+      52.5     277.5     7.246     9.372     0.654
+      52.5     282.5     8.072     9.480     0.722
+      52.5     287.5     7.542     9.590     0.853
+      52.5     292.5     7.188     9.688     0.864
+      52.5     297.5     9.146     9.770     0.324
+      52.5     302.5     8.968     9.820     0.399
+      52.5     307.5     7.578     9.816     0.765
+      52.5     312.5     7.960     9.702     0.799
+      52.5     317.5     8.168     9.444     0.851
+      52.5     322.5     8.812     9.274     0.797
+      52.5     327.5     8.784     9.286     0.892
+      52.5     332.5     8.948     9.408     0.909
+      52.5     337.5     8.890     9.602     0.958
+      52.5     342.5     9.592     9.864     0.912
+      52.5     347.5     9.926    10.214     0.931
+      52.5     352.5    10.456    10.780     0.975
+      52.5     357.5    11.022    14.032     0.994
+      57.5       2.5    12.270    12.270     1.000
+      57.5       7.5    13.038    15.292     0.256
+      57.5      12.5    16.554    17.150     0.987
+      57.5      17.5    17.926    18.326     0.990
+      57.5      22.5    19.372    19.372     1.000
+      57.5      27.5    20.346    20.346     1.000
+      57.5      32.5    21.258    21.258     1.000
+      57.5      37.5    22.104    22.104     1.000
+      57.5      42.5    22.878    22.878     1.000
+      57.5      47.5    23.568    23.568     1.000
+      57.5      52.5    24.164    24.164     1.000
+      57.5      57.5    24.656    24.656     1.000
+      57.5      62.5    25.036    25.036     1.000
+      57.5      67.5    25.296    25.296     1.000
+      57.5      72.5    25.428    25.428     1.000
+      57.5      77.5    25.426    25.426     1.000
+      57.5      82.5    25.290    25.290     1.000
+      57.5      87.5    25.016    25.016     1.000
+      57.5      92.5    24.608    24.608     1.000
+      57.5      97.5    24.070    24.070     1.000
+      57.5     102.5    23.410    23.410     1.000
+      57.5     107.5    22.638    22.638     1.000
+      57.5     112.5    21.766    21.766     1.000
+      57.5     117.5    20.812    20.812     1.000
+      57.5     122.5    19.794    19.794     1.000
+      57.5     127.5    18.734    18.734     1.000
+      57.5     132.5    17.654    17.654     1.000
+      57.5     137.5    16.580    16.580     1.000
+      57.5     142.5    15.534    15.534     1.000
+      57.5     147.5    14.540    14.540     1.000
+      57.5     152.5    13.618    13.618     1.000
+      57.5     157.5    12.780    12.780     1.000
+      57.5     162.5    11.814    12.036     0.802
+      57.5     167.5    11.202    11.386     0.815
+      57.5     172.5    10.676    10.828     0.842
+      57.5     177.5    10.232    10.354     0.803
+      57.5     182.5     9.858     9.956     0.735
+      57.5     187.5     9.064     9.626     0.950
+      57.5     192.5     8.878     9.356     0.925
+      57.5     197.5     8.326     9.138     0.946
+      57.5     202.5     8.336     8.964     0.930
+      57.5     207.5     8.146     8.830     0.898
+      57.5     212.5     8.092     8.732     0.862
+      57.5     217.5     7.956     8.664     0.771
+      57.5     222.5     7.592     8.622     0.763
+      57.5     227.5     7.680     8.606     0.674
+      57.5     232.5     7.654     8.612     0.624
+      57.5     237.5     7.508     8.638     0.637
+      57.5     242.5     7.514     8.680     0.578
+      57.5     247.5     7.672     8.738     0.448
+      57.5     252.5     7.518     8.808     0.481
+      57.5     257.5     7.424     8.888     0.463
+      57.5     262.5     7.134     8.976     0.687
+      57.5     267.5     7.956     9.066     0.436
+      57.5     272.5     7.130     9.156     0.611
+      57.5     277.5     7.188     9.242     0.812
+      57.5     282.5     8.874     9.306     0.269
+      57.5     287.5     8.784     9.340     0.309
+      57.5     292.5     7.038     9.298     0.784
+      57.5     297.5     8.038     9.112     0.642
+      57.5     302.5     7.624     8.702     0.833
+      57.5     307.5     7.708     8.454     0.922
+      57.5     312.5     7.610     8.426     0.956
+      57.5     317.5     8.076     8.504     0.939
+      57.5     322.5     8.504     8.644     0.857
+      57.5     327.5     8.586     8.828     0.934
+      57.5     332.5     8.528     9.040     0.949
+      57.5     337.5     8.722     9.278     0.939
+      57.5     342.5     9.194     9.536     0.936
+      57.5     347.5     9.950     9.950     1.000
+      57.5     352.5    10.726    10.726     1.000
+      57.5     357.5    11.500    11.500     1.000
+      62.5       2.5    13.980    13.980     1.000
+      62.5       7.5    14.866    14.866     1.000
+      62.5      12.5    15.748    15.748     1.000
+      62.5      17.5    18.546    18.546     1.000
+      62.5      22.5    20.168    20.168     1.000
+      62.5      27.5    21.458    21.458     1.000
+      62.5      32.5    22.624    22.624     1.000
+      62.5      37.5    23.696    23.696     1.000
+      62.5      42.5    24.674    24.674     1.000
+      62.5      47.5    25.544    25.544     1.000
+      62.5      52.5    26.300    26.300     1.000
+      62.5      57.5    26.930    26.930     1.000
+      62.5      62.5    27.422    27.422     1.000
+      62.5      67.5    27.768    27.768     1.000
+      62.5      72.5    27.960    27.960     1.000
+      62.5      77.5    27.992    27.992     1.000
+      62.5      82.5    27.856    27.856     1.000
+      62.5      87.5    27.554    27.554     1.000
+      62.5      92.5    27.086    27.086     1.000
+      62.5      97.5    26.458    26.458     1.000
+      62.5     102.5    25.678    25.678     1.000
+      62.5     107.5    24.758    24.758     1.000
+      62.5     112.5    23.716    23.716     1.000
+      62.5     117.5    22.570    22.570     1.000
+      62.5     122.5    21.346    21.346     1.000
+      62.5     127.5    20.068    20.068     1.000
+      62.5     132.5    18.766    18.766     1.000
+      62.5     137.5    17.472    17.472     1.000
+      62.5     142.5    16.218    16.218     1.000
+      62.5     147.5    15.034    15.034     1.000
+      62.5     152.5    13.948    13.948     1.000
+      62.5     157.5    12.976    12.976     1.000
+      62.5     162.5    11.874    12.126     0.810
+      62.5     167.5    11.196    11.400     0.814
+      62.5     172.5    10.628    10.790     0.827
+      62.5     177.5    10.070    10.280     0.886
+      62.5     182.5     9.700     9.862     0.864
+      62.5     187.5     9.012     9.520     0.933
+      62.5     192.5     8.322     9.246     0.961
+      62.5     197.5     8.258     9.026     0.940
+      62.5     202.5     8.206     8.854     0.917
+      62.5     207.5     7.980     8.724     0.927
+      62.5     212.5     7.920     8.630     0.879
+      62.5     217.5     7.742     8.568     0.804
+      62.5     222.5     7.624     8.534     0.710
+      62.5     227.5     7.500     8.524     0.695
+      62.5     232.5     7.578     8.538     0.615
+      62.5     237.5     7.740     8.568     0.469
+      62.5     242.5     7.664     8.616     0.454
+      62.5     247.5     7.546     8.676     0.435
+      62.5     252.5     7.368     8.748     0.436
+      62.5     257.5     7.432     8.826     0.558
+      62.5     262.5     7.888     8.906     0.420
+      62.5     267.5     7.032     8.980     0.589
+      62.5     272.5     7.300     9.044     0.810
+      62.5     277.5     8.630     9.070     0.291
+      62.5     282.5     7.102     9.034     0.788
+      62.5     287.5     7.122     8.842     0.750
+      62.5     292.5     7.236     8.376     0.837
+      62.5     297.5     7.538     8.064     0.886
+      62.5     302.5     7.798     8.010     0.868
+      62.5     307.5     7.868     8.080     0.868
+      62.5     312.5     7.724     8.218     0.891
+      62.5     317.5     7.928     8.398     0.885
+      62.5     322.5     8.002     8.614     0.925
+      62.5     327.5     8.186     8.852     0.925
+      62.5     332.5     8.762     9.112     0.903
+      62.5     337.5     9.608     9.608     1.000
+      62.5     342.5    10.470    10.470     1.000
+      62.5     347.5    11.340    11.340     1.000
+      62.5     352.5    12.216    12.216     1.000
+      62.5     357.5    13.098    13.098     1.000
+      67.5       2.5    15.848    15.848     1.000
+      67.5       7.5    16.874    16.874     1.000
+      67.5      12.5    17.900    17.900     1.000
+      67.5      17.5    18.928    18.928     1.000
+      67.5      22.5    20.356    20.356     1.000
+      67.5      27.5    22.518    22.518     1.000
+      67.5      32.5    24.056    24.056     1.000
+      67.5      37.5    25.428    25.428     1.000
+      67.5      42.5    26.672    26.672     1.000
+      67.5      47.5    27.780    27.780     1.000
+      67.5      52.5    28.740    28.740     1.000
+      67.5      57.5    29.544    29.544     1.000
+      67.5      62.5    30.182    30.182     1.000
+      67.5      67.5    30.642    30.642     1.000
+      67.5      72.5    30.914    30.914     1.000
+      67.5      77.5    30.990    30.990     1.000
+      67.5      82.5    30.864    30.864     1.000
+      67.5      87.5    30.534    30.534     1.000
+      67.5      92.5    30.000    30.000     1.000
+      67.5      97.5    29.268    29.268     1.000
+      67.5     102.5    28.348    28.348     1.000
+      67.5     107.5    27.256    27.256     1.000
+      67.5     112.5    26.010    26.010     1.000
+      67.5     117.5    24.636    24.636     1.000
+      67.5     122.5    23.162    23.162     1.000
+      67.5     127.5    21.620    21.620     1.000
+      67.5     132.5    20.048    20.048     1.000
+      67.5     137.5    18.488    18.488     1.000
+      67.5     142.5    16.982    16.982     1.000
+      67.5     147.5    15.570    15.570     1.000
+      67.5     152.5    14.292    14.292     1.000
+      67.5     157.5    13.166    13.166     1.000
+      67.5     162.5    11.918    12.206     0.806
+      67.5     167.5    11.176    11.402     0.832
+      67.5     172.5    10.402    10.742     0.924
+      67.5     177.5    10.076    10.206     0.723
+      67.5     182.5     9.544     9.772     0.877
+      67.5     187.5     8.918     9.424     0.945
+      67.5     192.5     8.612     9.146     0.933
+      67.5     197.5     8.534     8.930     0.924
+      67.5     202.5     8.124     8.764     0.919
+      67.5     207.5     8.066     8.640     0.913
+      67.5     212.5     7.904     8.550     0.833
+      67.5     217.5     7.692     8.498     0.767
+      67.5     222.5     7.664     8.472     0.676
+      67.5     227.5     7.582     8.468     0.641
+      67.5     232.5     7.372     8.488     0.638
+      67.5     237.5     7.286     8.524     0.616
+      67.5     242.5     7.270     8.576     0.565
+      67.5     247.5     7.312     8.640     0.474
+      67.5     252.5     7.026     8.708     0.586
+      67.5     257.5     7.884     8.780     0.406
+      67.5     262.5     7.096     8.844     0.586
+      67.5     267.5     7.222     8.888     0.796
+      67.5     272.5     7.038     8.892     0.825
+      67.5     277.5     8.160     8.796     0.327
+      67.5     282.5     7.188     8.458     0.737
+      67.5     287.5     7.296     7.936     0.809
+      67.5     292.5     7.044     7.752     0.938
+      67.5     297.5     7.154     7.768     0.938
+      67.5     302.5     7.142     7.874     0.923
+      67.5     307.5     7.356     8.042     0.927
+      67.5     312.5     7.642     8.244     0.884
+      67.5     317.5     7.866     8.488     0.820
+      67.5     322.5     8.138     8.754     0.792
+      67.5     327.5     9.016     9.042     0.615
+      67.5     332.5     9.940     9.940     1.000
+      67.5     337.5    10.884    10.884     1.000
+      67.5     342.5    11.846    11.846     1.000
+      67.5     347.5    12.826    12.826     1.000
+      67.5     352.5    13.822    13.822     1.000
+      67.5     357.5    14.830    14.830     1.000
+      72.5       2.5    17.936    17.936     1.000
+      72.5       7.5    19.126    19.126     1.000
+      72.5      12.5    20.328    20.328     1.000
+      72.5      17.5    21.532    21.532     1.000
+      72.5      22.5    22.732    22.732     1.000
+      72.5      27.5    23.926    23.926     1.000
+      72.5      32.5    25.496    25.496     1.000
+      72.5      37.5    27.278    27.278     1.000
+      72.5      42.5    28.878    28.878     1.000
+      72.5      47.5    30.300    30.300     1.000
+      72.5      52.5    31.532    31.532     1.000
+      72.5      57.5    32.566    32.566     1.000
+      72.5      62.5    33.392    33.392     1.000
+      72.5      67.5    34.000    34.000     1.000
+      72.5      72.5    34.378    34.378     1.000
+      72.5      77.5    34.520    34.520     1.000
+      72.5      82.5    34.412    34.412     1.000
+      72.5      87.5    34.056    34.056     1.000
+      72.5      92.5    33.448    33.448     1.000
+      72.5      97.5    32.596    32.596     1.000
+      72.5     102.5    31.512    31.512     1.000
+      72.5     107.5    30.214    30.214     1.000
+      72.5     112.5    28.724    28.724     1.000
+      72.5     117.5    27.074    27.074     1.000
+      72.5     122.5    25.296    25.296     1.000
+      72.5     127.5    23.434    23.434     1.000
+      72.5     132.5    21.532    21.532     1.000
+      72.5     137.5    19.644    19.644     1.000
+      72.5     142.5    17.828    17.828     1.000
+      72.5     147.5    16.142    16.142     1.000
+      72.5     152.5    14.634    14.634     1.000
+      72.5     157.5    13.338    13.338     1.000
+      72.5     162.5    11.934    12.260     0.810
+      72.5     167.5    11.138    11.384     0.854
+      72.5     172.5    10.504    10.682     0.888
+      72.5     177.5     9.812    10.124     0.942
+      72.5     182.5     9.504     9.684     0.933
+      72.5     187.5     8.862     9.336     0.937
+      72.5     192.5     8.252     9.062     0.960
+      72.5     197.5     8.164     8.852     0.942
+      72.5     202.5     8.014     8.690     0.926
+      72.5     207.5     7.986     8.578     0.895
+      72.5     212.5     7.844     8.492     0.802
+      72.5     217.5     7.488     8.452     0.786
+      72.5     222.5     7.598     8.428     0.677
+      72.5     227.5     7.424     8.438     0.671
+      72.5     232.5     7.546     8.464     0.542
+      72.5     237.5     7.202     8.506     0.607
+      72.5     242.5     7.452     8.560     0.426
+      72.5     247.5     7.040     8.624     0.513
+      72.5     252.5     7.246     8.688     0.646
+      72.5     257.5     7.016     8.746     0.555
+      72.5     262.5     7.010     8.784     0.733
+      72.5     267.5     8.356     8.770     0.271
+      72.5     272.5     8.020     8.640     0.326
+      72.5     277.5     7.110     8.210     0.729
+      72.5     282.5     7.040     7.696     0.860
+      72.5     287.5     7.002     7.558     0.932
+      72.5     292.5     7.078     7.598     0.969
+      72.5     297.5     7.144     7.726     0.900
+      72.5     302.5     7.274     7.910     0.896
+      72.5     307.5     7.548     8.132     0.805
+      72.5     312.5     7.788     8.394     0.749
+      72.5     317.5     8.242     8.682     0.623
+      72.5     322.5     9.184     9.184     1.000
+      72.5     327.5    10.180    10.180     1.000
+      72.5     332.5    11.206    11.206     1.000
+      72.5     337.5    12.264    12.264     1.000
+      72.5     342.5    13.348    13.348     1.000
+      72.5     347.5    14.458    14.458     1.000
+      72.5     352.5    15.596    15.596     1.000
+      72.5     357.5    16.756    16.756     1.000
+      77.5       2.5    20.322    20.322     1.000
+      77.5       7.5    21.720    21.720     1.000
+      77.5      12.5    23.134    23.134     1.000
+      77.5      17.5    24.556    24.556     1.000
+      77.5      22.5    25.974    25.974     1.000
+      77.5      27.5    27.382    27.382     1.000
+      77.5      32.5    28.768    28.768     1.000
+      77.5      37.5    30.118    30.118     1.000
+      77.5      42.5    31.424    31.424     1.000
+      77.5      47.5    33.128    33.128     1.000
+      77.5      52.5    34.730    34.730     1.000
+      77.5      57.5    36.068    36.068     1.000
+      77.5      62.5    37.142    37.142     1.000
+      77.5      67.5    37.946    37.946     1.000
+      77.5      72.5    38.470    38.470     1.000
+      77.5      77.5    38.700    38.700     1.000
+      77.5      82.5    38.630    38.630     1.000
+      77.5      87.5    38.250    38.250     1.000
+      77.5      92.5    37.562    37.562     1.000
+      77.5      97.5    36.570    36.570     1.000
+      77.5     102.5    35.292    35.292     1.000
+      77.5     107.5    33.744    33.744     1.000
+      77.5     112.5    31.958    31.958     1.000
+      77.5     117.5    29.968    29.968     1.000
+      77.5     122.5    27.820    27.820     1.000
+      77.5     127.5    25.560    25.560     1.000
+      77.5     132.5    23.250    23.250     1.000
+      77.5     137.5    20.958    20.958     1.000
+      77.5     142.5    18.758    18.758     1.000
+      77.5     147.5    16.732    16.732     1.000
+      77.5     152.5    14.956    14.956     1.000
+      77.5     157.5    13.468    13.468     1.000
+      77.5     162.5    11.908    12.274     0.814
+      77.5     167.5    11.072    11.334     0.855
+      77.5     172.5    10.198    10.606     0.990
+      77.5     177.5     9.716    10.038     0.969
+      77.5     182.5     9.334     9.598     0.970
+      77.5     187.5     8.890     9.258     0.951
+      77.5     192.5     8.238     8.994     0.955
+      77.5     197.5     7.816     8.792     0.953
+      77.5     202.5     8.044     8.644     0.910
+      77.5     207.5     7.970     8.538     0.877
+      77.5     212.5     7.526     8.468     0.832
+      77.5     217.5     7.488     8.428     0.747
+      77.5     222.5     7.594     8.420     0.632
+      77.5     227.5     7.494     8.432     0.601
+      77.5     232.5     7.480     8.464     0.530
+      77.5     237.5     7.562     8.510     0.405
+      77.5     242.5     7.404     8.566     0.396
+      77.5     247.5     7.256     8.626     0.562
+      77.5     252.5     7.598     8.680     0.423
+      77.5     257.5     7.016     8.716     0.655
+      77.5     262.5     8.318     8.698     0.221
+      77.5     267.5     7.990     8.566     0.299
+      77.5     272.5     7.016     8.108     0.729
+      77.5     277.5     7.052     7.560     0.831
+      77.5     282.5     7.092     7.424     0.873
+      77.5     287.5     7.044     7.470     0.883
+      77.5     292.5     7.188     7.602     0.889
+      77.5     297.5     7.174     7.796     0.833
+      77.5     302.5     7.496     8.036     0.715
+      77.5     307.5     7.692     8.306     0.619
+      77.5     312.5     8.250     8.614     0.527
+      77.5     317.5     9.276     9.276     1.000
+      77.5     322.5    10.342    10.342     1.000
+      77.5     327.5    11.448    11.448     1.000
+      77.5     332.5    12.596    12.596     1.000
+      77.5     337.5    13.788    13.788     1.000
+      77.5     342.5    15.020    15.020     1.000
+      77.5     347.5    16.294    16.294     1.000
+      77.5     352.5    17.604    17.604     1.000
+      77.5     357.5    18.950    18.950     1.000
Index: /tags/Mars-V0.9/mfit/MTFitLoop.cc
===================================================================
--- /tags/Mars-V0.9/mfit/MTFitLoop.cc	(revision 9772)
+++ /tags/Mars-V0.9/mfit/MTFitLoop.cc	(revision 9772)
@@ -0,0 +1,238 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTFitLoop
+//
+// This class optimized parameters which are calculated in an eventloop.
+// For this it is unimportant whether the loop reads from a file a
+// matrix or from somewhere else...
+//
+// The parameters which are optimized must be stored in a MParContainer
+// which overwrites SetVariables(). Eg. a MDataChain or MF overwrites
+// SetVariables(). In a MF all arguments given as [0], [1] are
+// set by SetVariables (in MDataValue).
+//  eg: In you loop you have a cut like this:
+//      MF filter("MHillas.fWidth<[0]");
+//      filter.SetName("MyParameters");
+//
+//  Now for each time the eventloop is executed
+//  (MEvtLoop::Eventloop(fNumEvents)) the parameters from TMinuit are
+//  passed to MF::SetVariables and changed.
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTFitLoop.h"
+
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TStopwatch.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MParameters.h"
+
+#include "MRead.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTFitLoop);
+
+using namespace std;
+
+//------------------------------------------------------------------------
+//
+// fcn calculates the function to be minimized (using TMinuit::Migrad)
+//
+void MTFitLoop::fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    MTFitLoop *optim = (MTFitLoop*)gMinuit->GetObjectFit();
+
+    TMinuit *minuit = gMinuit;
+    f = optim->Fcn(npar, gin, par, iflag);
+    gMinuit = minuit;
+
+}
+Double_t MTFitLoop::Fcn(Int_t &npar, Double_t *gin, Double_t *par, Int_t iflag)
+{
+    MParList *plist = fEvtLoop->GetParList();
+
+    MParameterD   *eval = (MParameterD*)  plist->FindCreateObj("MParameterD", fFitParameter);
+    MParContainer *pars = (MParContainer*)plist->FindObject(fParametersName);
+
+    MRead *read = (MRead*)plist->FindObject("MTaskList")->FindObject("MRead");
+    if (read)
+        read->Rewind();
+
+    if (fDebug>=1)
+    {
+        Double_t fmin, fedm, errdef;
+        Int_t n1, n2, istat;
+        gMinuit->mnstat(fmin, fedm, errdef, n1, n2, istat);
+        *fLog << inf << underline << "Minimization Status so far:" << endl;
+        *fLog << " Calls:     " << gMinuit->fNfcn << endl;
+        *fLog << " Func min:  " << fmin << endl;
+        *fLog << " Found edm: " << fedm << endl;
+        *fLog << " ErrDef:    " << errdef << endl;
+        *fLog << " Status:    ";
+        switch (istat)
+        {
+        case 0:  *fLog << "n/a" << endl; break;
+        case 1:  *fLog << "approximation only, not accurate" << endl; break;
+        case 2:  *fLog << "full matrix, but forced positive-definite" << endl; break;
+        case 3:  *fLog << "full accurate covariance matrix" << endl; break;
+        default: *fLog << "undefined" << endl; break;
+        }
+    }
+
+    if (fDebug>=0)
+    {
+        *fLog << inf << "Set(" << gMinuit->fMaxpar << "): ";
+        for (Int_t i=0; i<gMinuit->fMaxpar; i++)
+            *fLog << par[i] << " ";
+        *fLog << endl;
+    }
+ 
+    pars->SetVariables(TArrayD(gMinuit->fMaxpar, par));
+
+    if (fDebug<3)
+        gLog.SetNullOutput(kTRUE);
+    fEvtLoop->Eventloop(fNumEvents);
+    if (fDebug<3)
+        gLog.SetNullOutput(kFALSE);
+
+    const Double_t f = eval->GetVal();
+
+    if (fDebug>=0)
+        *fLog << inf << "F=" << f << endl;
+
+    if (fDebug>=1)
+        fEvtLoop->GetTaskList()->PrintStatistics();
+
+    return f;
+}
+
+MTFitLoop::MTFitLoop(Int_t num) : fNum(num), fMaxIterations(1000)
+{
+    fDebug     = -1;
+    fNumEvents = -1;
+}
+
+void MTFitLoop::Optimize(MEvtLoop &loop, TArrayD &pars)
+{
+    *fLog << inf << "Event loop was setup" << endl;
+    MParList *parlist = loop.GetParList();
+    if (!parlist)
+        return;
+
+//    MParContainer *pars = (MParContainer*)parlist->FindObject(fParametersName);
+//    if (!pars)
+//        return;
+
+    fEvtLoop = &loop;
+
+//    MParContainer &parameters = *pars;
+
+    TMinuit *minsave = gMinuit;
+
+    gMinuit = new TMinuit(pars.GetSize());
+    gMinuit->SetPrintLevel(-1);
+    gMinuit->SetMaxIterations(fMaxIterations);
+
+    gMinuit->SetFCN(fcn);
+    gMinuit->SetObjectFit(this);
+
+     // For chisq fits call this // seems to be something like %)
+     //
+     // The default tolerance is 0.1, and the minimization will stop");
+     // when the estimated vertical distance to the minimum (EDM) is");
+     // less than 0.001*[tolerance]*UP (see [SET ERRordef]).");
+     //
+    if (gMinuit->SetErrorDef(1))
+    {
+        *fLog << err << dbginf << "SetErrorDef failed." << endl;
+        return;
+    }
+
+    //
+    // Set starting values and step sizes for parameters
+    //
+    for (Int_t i=0; i<pars.GetSize(); i++)
+    {
+        TString name = "par[";
+        name += i;
+        name += "]";
+        Double_t vinit = pars[i];
+        Double_t step  = fabs(pars[i]/3);
+
+        Double_t limlo = 0; // limlo=limup=0: no limits
+        Double_t limup = 2*vinit;
+
+        Bool_t rc = gMinuit->DefineParameter(i, name, vinit, step, 0, limup);
+        if (!rc)
+            continue;
+
+        *fLog << err << dbginf << "Error in defining parameter #" << i << endl;
+        return;
+    }
+
+    for (int i=0; i<pars.GetSize() && i<fFixedParams.GetSize(); i++)
+        if (fFixedParams[i]!=0)
+            gMinuit->FixParameter(i);
+
+    // Now ready for minimization step:
+
+    TStopwatch clock;
+    clock.Start();
+    const Bool_t rc = gMinuit->Migrad();
+    clock.Stop();
+    clock.Print();
+
+    if (rc)
+    {
+        *fLog << err << dbginf << "Migrad failed." << endl;
+        return;
+    }
+
+    *fLog << inf << "Resulting Chisq: " << gMinuit->fAmin << endl;
+
+    //
+    // Update values of fA, fB:
+    //
+    for (Int_t i=0; i<pars.GetSize(); i++)
+    {
+        Double_t x1, x2;
+        gMinuit->GetParameter(i,x1,x2);
+        pars[i] = x1;
+        cout << i << ": " << pars[i] << endl;
+    }
+
+    //list.SetVariables(pars);
+
+    gMinuit = minsave;
+}
Index: /tags/Mars-V0.9/mfit/MTFitLoop.h
===================================================================
--- /tags/Mars-V0.9/mfit/MTFitLoop.h	(revision 9772)
+++ /tags/Mars-V0.9/mfit/MTFitLoop.h	(revision 9772)
@@ -0,0 +1,50 @@
+#ifndef MARS_MTFitLoop
+#define MARS_MTFitLoop
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+class MEvtLoop;
+
+class MTFitLoop : public MParContainer
+{
+private:
+    Int_t fDebug;     // -1 no output, 0 MTFitLoop output, 1 PrintStatistics output
+    Int_t fNumEvents;
+
+    static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag);
+    virtual Double_t Fcn(Int_t &npar, Double_t *gin, Double_t *par, Int_t iflag);
+
+    MEvtLoop *fEvtLoop;
+
+    TString   fParametersName;
+    TString   fFitParameter;
+
+    TArrayC   fFixedParams;
+
+    Int_t fNum;
+    Int_t fMaxIterations;
+
+public:
+    MTFitLoop(const Int_t num=0);
+
+    void Optimize(MEvtLoop &loop, TArrayD &pars);
+
+    void SetNameParameters(const char *parm) { fParametersName = parm; }
+    void SetFitParameter(const char *parm)   { fFitParameter   = parm; }
+
+    void SetFixedParameters(const TArrayC &c) { fFixedParams = c; }
+    void SetMaxIterations(Int_t maxiter=500) {fMaxIterations = maxiter;} // for debugging
+
+    void SetDebug(Int_t n)     { fDebug = n; }
+    void SetNumEvents(Int_t n) { fNumEvents = n; }
+
+    ClassDef(MTFitLoop, 0) // Class which can optimize a value (chi^2, significance, etc) calculated in an eventloop
+};
+
+#endif
Index: /tags/Mars-V0.9/mflux/MFHadAlpha.cc
===================================================================
--- /tags/Mars-V0.9/mflux/MFHadAlpha.cc	(revision 9772)
+++ /tags/Mars-V0.9/mflux/MFHadAlpha.cc	(revision 9772)
@@ -0,0 +1,149 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez  2/2005 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MFHadAlpha                                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MFHadAlpha.h"
+
+
+#include <fstream>
+#include <TFile.h>
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MHillasSrc.h"
+#include "MHadAlphaCut.h"
+#include "MEnergyEst.h"
+#include "MHadronness.h"
+#include "MPointingPos.h"
+
+ClassImp(MFHadAlpha);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+MFHadAlpha::MFHadAlpha(const char *name, const char *title)
+    : fFilterType(kHadAlphaCut), fFileName("")
+{
+    fName  = name  ? name  : "MFHadAlpha";
+    fTitle = title ? title : "Filter to apply hadroness and alpha cuts for each size and theta bin";
+}
+
+
+// --------------------------------------------------------------------------
+//
+Int_t MFHadAlpha::PreProcess(MParList *pList)
+{
+   
+    fHillas = (MHillas*)pList->FindObject("MHillas");
+    if (!fHillas)
+    {
+        *fLog << dbginf << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    } 
+
+    fPointingPos = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointingPos)
+    {
+        *fLog << dbginf << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHadronness = (MHadronness*)pList->FindObject("MHadronness");
+    if (!fHadronness)
+    {
+        *fLog << dbginf << "MHadronness not found... aborting." << endl;
+        return kFALSE;
+    } 
+
+    fHillasSrc = (MHillasSrc*)pList->FindObject("MHillasSrc");
+    if (!fHillasSrc)
+    {
+        *fLog << dbginf << "MHillasSrc not found... aborting." << endl;
+        return kFALSE;
+    } 
+
+    fEnergyEst = (MEnergyEst*)pList->FindObject("MEnergyEst");
+    if (!fEnergyEst)
+    {
+        *fLog << dbginf << "MEnergyEst not found... aborting." << endl;
+        return kFALSE;
+    } 
+
+   
+    fHadAlphaCut = (MHadAlphaCut*)pList->FindCreateObj("MHadAlphaCut");
+    if (!fHadAlphaCut)
+    {
+	*fLog << dbginf << "MHadAlphaCut not found... aborting." << endl;
+	return kFALSE;
+    }
+ 
+    if(fFileName!="")
+    {
+	TFile f(fFileName);
+	fHadAlphaCut->Read("MHadAlphaCut");
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFHadAlpha::Process()
+{
+    //const Float_t size = fHillas->GetSize();
+    const Float_t energy = fEnergyEst->GetEnergy();
+    const Float_t zd = fPointingPos->GetZd();
+    const Float_t alpha = TMath::Abs(fHillasSrc->GetAlpha());
+    const Float_t had = fHadronness->GetHadronness();
+
+    const Float_t alphacut = fHadAlphaCut->GetAlphaCut(energy,zd);
+    const Float_t hadcut = fHadAlphaCut->GetHadCut(energy,zd);
+    
+    switch(fFilterType)
+    {
+	case MFHadAlpha::kAlphaCut:
+	    fResult = ( alpha <= alphacut );
+	    break;
+	case MFHadAlpha::kHadCut:
+	    fResult = ( had <= hadcut ); 
+	    break;
+	case MFHadAlpha::kHadAlphaCut:
+	    fResult = ( (alpha <= alphacut)  && (had <= hadcut) );
+	    break;
+	default:
+	    fResult = kTRUE;
+    }
+
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mflux/MFHadAlpha.h
===================================================================
--- /tags/Mars-V0.9/mflux/MFHadAlpha.h	(revision 9772)
+++ /tags/Mars-V0.9/mflux/MFHadAlpha.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MFHadAlpha
+#define MARS_MFHadAlpha
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+#ifndef ROOT_TString
+#include "TString.h"
+#endif
+
+class MParList;
+class MHadAlphaCut;
+class MHadronness;
+class MHillas;
+class MHillasSrc;
+class MPointingPos;
+class MEnergyEst;
+
+class MFHadAlpha : public MFilter
+{
+
+ public:
+
+   typedef enum { kHadCut, kAlphaCut, kHadAlphaCut } FilterType_t;
+    FilterType_t fFilterType;
+
+ private:
+   
+    MHadronness*  fHadronness;
+    MHillas*      fHillas; 
+    MHillasSrc*   fHillasSrc;
+    MHadAlphaCut* fHadAlphaCut;
+    MPointingPos* fPointingPos;
+    MEnergyEst*   fEnergyEst;
+
+    TString fFileName;
+
+    Bool_t  fResult; //!
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+
+    MFHadAlpha( const char *name=NULL, const char *title=NULL);
+  
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    void SetInputCutsFile(const char* fname) { fFileName = fname; }
+
+    void SetCutType(FilterType_t type) { fFilterType = type; }
+
+    ClassDef(MFHadAlpha, 1) // A Filter for cuts in fabs(alpha)
+};
+
+#endif
Index: /tags/Mars-V0.9/mflux/MHadAlphaCut.cc
===================================================================
--- /tags/Mars-V0.9/mflux/MHadAlphaCut.cc	(revision 9772)
+++ /tags/Mars-V0.9/mflux/MHadAlphaCut.cc	(revision 9772)
@@ -0,0 +1,139 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez  2/2005 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHadAlphaCut
+//
+//  Container for Hadronness and Alpha cut for each Estimated Energy and theta
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHadAlphaCut.h"
+
+
+#include <TH2F.h>
+#include <TCanvas.h>
+
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHadAlphaCut);
+
+using namespace std;
+
+
+// ------------------------------------------------------------------------
+//
+//
+MHadAlphaCut::MHadAlphaCut(const char* name, const char* title)
+{
+    fName  = name  ? name  : "MHadAlphaCut";
+    fTitle = title ? title : "Container of Hadronness and Alpha cuts";
+    
+
+    fHistHadCut = new TH2F;
+    fHistHadCut->UseCurrentStyle();
+    fHistHadCut->SetNameTitle("HadCut","HadCut");
+    fHistHadCut->SetXTitle("Energy");
+    fHistHadCut->SetYTitle("Theta");
+    fHistHadCut->SetZTitle("Hadronness Cut");
+
+    fHistAlphaCut = new TH2F; 
+    fHistAlphaCut->UseCurrentStyle();
+    fHistAlphaCut->SetNameTitle("AlphaCut","AlphaCut");
+    fHistAlphaCut->SetXTitle("Energy");
+    fHistAlphaCut->SetYTitle("Theta");
+    fHistAlphaCut->SetZTitle("Alpha Cut");
+  
+
+    MBinning binsx;
+    MBinning binsy;
+    
+    binsx.SetEdgesLog(8, 50., 2000);  // Est. Energy binning
+    binsy.SetEdges(2,14,31);          // Theta binning
+
+    MH::SetBinning(fHistHadCut, &binsx, &binsy);
+    MH::SetBinning(fHistAlphaCut, &binsx, &binsy);
+    
+
+    for(int ix=1; ix<=fHistHadCut->GetNbinsX(); ix++)
+	for(int iy=1; iy<=fHistHadCut->GetNbinsY(); iy++)
+	{
+	    fHistAlphaCut->SetBinContent(ix,iy,10);
+	    fHistHadCut->SetBinContent(ix,iy,0.3);
+	}
+}
+
+
+Float_t MHadAlphaCut::GetAlphaCut(Float_t energy, Float_t zd)
+{
+    Int_t bin = fHistAlphaCut->FindBin(energy,zd);
+    return fHistAlphaCut->GetBinContent(bin);
+}
+
+Float_t MHadAlphaCut::GetHadCut(Float_t energy, Float_t zd)
+{ 
+    Int_t bin = fHistHadCut->FindBin(energy,zd);
+    return fHistHadCut->GetBinContent(bin);
+} 
+
+
+//------------------------------------------------------------------------
+//
+//
+void MHadAlphaCut::Print(Option_t *o) const
+{
+
+    // *fLog << " Size bin \t HadCut \t AlphaCut" << endl;
+    for(Int_t ix=1; ix<=fHistHadCut->GetNbinsX(); ix++)
+    {
+	for(Int_t iy=1; iy<=fHistHadCut->GetNbinsY(); iy++)
+	{	
+	    *fLog <<"(" <<ix << ", " << iy << ") = " 
+		  << fHistHadCut->GetBinContent(ix,iy) << " " << 
+		fHistAlphaCut->GetBinContent(ix,iy) << endl;
+	}
+    }
+}
+
+
+// -------------------------------------------------------------------------
+//
+//
+void MHadAlphaCut::Draw(Option_t *o)
+{
+    TCanvas *c1 = new TCanvas;
+    c1->SetLogx();
+    fHistAlphaCut->Draw("lego");
+
+    TCanvas *c2 = new TCanvas;
+    c2->SetLogx();
+    fHistHadCut->Draw("lego");
+}
+
+
+
+
Index: /tags/Mars-V0.9/mflux/MHadAlphaCut.h
===================================================================
--- /tags/Mars-V0.9/mflux/MHadAlphaCut.h	(revision 9772)
+++ /tags/Mars-V0.9/mflux/MHadAlphaCut.h	(revision 9772)
@@ -0,0 +1,35 @@
+#ifndef MARS_MHadAlphaCut
+#define MARS_MHadAlphaCut
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH2F;
+
+class MHadAlphaCut : public MH
+{
+ private:
+
+    TH2F*  fHistHadCut;
+    TH2F*  fHistAlphaCut;
+  
+
+ public:
+    
+    MHadAlphaCut(const char* name=NULL, const char* title=NULL);
+
+    Float_t GetAlphaCut(Float_t energy, Float_t zd);
+    Float_t GetHadCut(Float_t energy, Float_t zd);
+    
+    void Print(Option_t *o="") const;
+    void Draw(Option_t *o="");
+    
+    TH2F* GetHistHadCut() const   { return fHistHadCut; }
+    TH2F* GetHistAlphaCut() const { return fHistAlphaCut; }
+
+
+    ClassDef(MHadAlphaCut, 1)	// Container for Hadronness and Alpha cut for each estimated energy and theta bin
+};
+
+#endif
Index: /tags/Mars-V0.9/mgeom/GeomIncl.h
===================================================================
--- /tags/Mars-V0.9/mgeom/GeomIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/GeomIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mgeom/GeomLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mgeom/GeomLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/GeomLinkDef.h	(revision 9772)
@@ -0,0 +1,23 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MGeomPix+;
+#pragma link C++ class MGeomCam+;
+#pragma link C++ class MGeomPMT+;
+#pragma link C++ class MGeomMirror+;
+#pragma link C++ class MGeomCorsikaCT+;
+
+#pragma link C++ class MGeomCamCT1+;
+#pragma link C++ class MGeomCamCT1Daniel+;
+
+#pragma link C++ class MGeomCamMagic+;
+#pragma link C++ class MGeomCamMagicHG+;
+#pragma link C++ class MGeomCamMagic919+;
+
+#pragma link C++ class MGeomCamECO1000+;
+#pragma link C++ class MGeomCamECO1000HG+;
+
+#endif
Index: /tags/Mars-V0.9/mgeom/MGeomCam.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCam.cc	(revision 9772)
@@ -0,0 +1,405 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz     12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!              Harald Kornmayer 01/2001
+!              Markus Gaug      03/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCam
+//
+// This is the base class of different camera geometries. It creates
+// a pixel object for a given number of pixels and defines the
+// interface of how to acccess the geometry information.
+//
+// We use a TObjArray for possible future usage (it is much more flexible
+// than a TClonesArray so that it can store more types of pixels (eg
+// fake pixels which are not really existing)
+//
+// Version 1:
+// ----------
+//  - first implementation
+//
+// Version 2:
+// ----------
+//  - added fPixRatio
+//  - added fPixRatioSqrt
+//
+// Version 3:
+// ----------
+//  - added fNumAreas
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MGeomCam.h"
+
+#include <TClass.h>     // IsA()->New()
+#include <TArrayI.h>    // TArrayI
+#include <TVector2.h>   // TVector2
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MGeomCam::MGeomCam()
+    : fNumPixels(0), fCamDist(0), fConvMm2Deg(0), /*fPixels(1000),*/ fMaxRadius(1), fMinRadius(1)
+{
+    fName  = "MGeomCam";
+    fTitle = "Storage container for a camera geometry";
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes a Camera Geometry with npix pixels. All pixels
+// are deleted when the corresponding array is deleted.
+//
+MGeomCam::MGeomCam(UInt_t npix, Float_t dist, const char *name, const char *title)
+    : fNumPixels(npix), fCamDist(dist), fConvMm2Deg(kRad2Deg/(dist*1000)), 
+      fPixels(npix), fMaxRadius(1), fMinRadius(1), fPixRatio(npix), fPixRatioSqrt(npix)
+{
+    fName  = name  ? name  : "MGeomCam";
+    fTitle = title ? title : "Storage container for a camera geometry";
+
+    //
+    // make sure that the destructor delete all contained objects
+    //
+    fPixels.SetOwner();
+
+    for (UInt_t i=0; i<npix; i++)
+        fPixels[i] = new MGeomPix;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns a reference of the i-th entry (the pixel with the software idx i)
+// The access is unchecked (for speed reasons!) accesing non existing
+// entries may crash the program!
+//
+MGeomPix &MGeomCam::operator[](Int_t i)
+{
+    return *static_cast<MGeomPix*>(fPixels.UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns a reference of the i-th entry (the pixel with the software idx i)
+// The access is unchecked (for speed reasons!) accesing non existing
+// entries may crash the program!
+//
+MGeomPix &MGeomCam::operator[](Int_t i) const
+{
+    return *static_cast<MGeomPix*>(fPixels.UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate and fill the arrays storing the ratio of the area of a pixel
+// i to the pixel 0 and its square root.
+// The precalculation is done for speed reasons. Having an event the
+// ratio would be calculated at least once for each pixel which is
+// an enormous amount of numerical calculations, which are time
+// consuming and which can be avoided doing the precalculation.
+//
+void MGeomCam::CalcPixRatio()
+{
+    const Double_t a0 = (*this)[0].GetA();
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        fPixRatio[i] = a0/(*this)[i].GetA();
+        fPixRatioSqrt[i] = TMath::Sqrt(fPixRatio[i]);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the kIsOuterRing flag for all pixels which have a outermost pixel
+//  as Next Neighbor and don't have the kIsOutermostRing flag itself.
+//
+void MGeomCam::InitOuterRing()
+{
+    fPixels.ForEach(MGeomPix, CheckOuterRing)(*this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the highest sector index+1 of all pixels, please make sure
+// the the sector numbers are continous.
+//
+void MGeomCam::CalcNumSectors()
+{
+    fNumSectors = 0;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const Int_t s = (*this)[i].GetSector();
+
+        if (s>fNumSectors)
+            fNumSectors = s;
+    }
+
+    fNumSectors++;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the highest area index+1 of all pixels, please make sure
+// the the area indices are continous.
+//
+void MGeomCam::CalcNumAreas()
+{
+    fNumAreas = 0;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const Int_t s = (*this)[i].GetAidx();
+
+        if (s>fNumAreas)
+            fNumAreas = s;
+    }
+
+    fNumAreas++;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the maximum radius of the camera. This is ment for GUI layout.
+//
+void MGeomCam::CalcMaxRadius()
+{
+    fMaxRadius.Set(fNumAreas+1);
+    fMinRadius.Set(fNumAreas+1);
+
+    for (Int_t i=0; i<fNumAreas+1; i++)
+    {
+        fMaxRadius[i] = 0.;
+        fMinRadius[i] = FLT_MAX;
+    }
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGeomPix &pix = (*this)[i];
+
+        const UInt_t  s = pix.GetAidx();
+        const Float_t x = pix.GetX();
+        const Float_t y = pix.GetY();
+        const Float_t d = pix.GetD();
+
+        const Float_t r = TMath::Hypot(x, y);
+
+        const Float_t maxr = r + d;
+        const Float_t minr = r>d ? r-d : 0;
+
+        if (maxr>fMaxRadius[s+1])
+            fMaxRadius[s+1] = maxr;
+
+        if (minr<fMinRadius[s+1])
+            fMinRadius[s+1] = minr;
+
+        if (minr<fMinRadius[0])
+            fMinRadius[0] = minr;
+
+        if (maxr>fMaxRadius[0])
+            fMaxRadius[0] = maxr;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Have to call the radii of the subcameras starting to count from 1
+//
+Float_t MGeomCam::GetMaxRadius(const Int_t i) const
+{
+    return i<-1 || i>fNumAreas ? -1 : fMaxRadius[i+1];
+}
+
+// --------------------------------------------------------------------------
+//
+// Have to call the radii of the subcameras starting to count from 1
+//
+Float_t MGeomCam::GetMinRadius(const Int_t i) const
+{
+    return i<-1 || i>fNumAreas ? -1 : fMinRadius[i+1];
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  returns the ratio of the area of the pixel with index 0 to the pixel
+//  with the specified index i. 0 Is returned if the index argument is
+//  out of range.
+//
+Float_t MGeomCam::GetPixRatio(UInt_t i) const
+{
+    // Former: (*this)[0].GetA()/(*this)[i].GetA();
+    // The const_cast is necessary to support older root version
+    return i<fNumPixels ? const_cast<TArrayF&>(fPixRatio)[i] : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  returns the square root of the ratio of the area of the pixel with
+//  index 0 to the pixel with the specified index i. 0 Is returned if
+//  the index argument is out of range.
+//
+Float_t MGeomCam::GetPixRatioSqrt(UInt_t i) const
+{
+    // The const_cast is necessary to support older root version
+    return i<fNumPixels ? const_cast<TArrayF&>(fPixRatioSqrt)[i] : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints the Geometry information of all pixels in the camera
+//
+void MGeomCam::Print(Option_t *) const
+{
+    //
+    //   Print Information about the Geometry of the camera
+    //
+    *fLog << all << " Number of Pixels (" << GetTitle() << "): " << fNumPixels << endl;
+    *fLog << " Number of Sectors: " << GetNumSectors() << "  Area-Indices: " << GetNumAreas() << endl;
+    *fLog << " Min.Radius: " << GetMinRadius() << "  Max.Radius: " << GetMaxRadius() << endl;
+
+    fPixels.Print();
+} 
+
+// --------------------------------------------------------------------------
+//
+//  Create a clone of this container. This is very easy, because we
+//  simply have to create a new object of the same type.
+//
+TObject *MGeomCam::Clone(const char *newname) const
+{
+    if (IsA()==MGeomCam::Class())
+    {
+        MGeomCam *cam = new MGeomCam(fNumPixels, fCamDist);
+        for (UInt_t i=0; i<fNumPixels; i++)
+        {
+            //if (fPixels.UncheckedAt(i))
+                (*this)[i].Copy((*cam)[i]);
+        }
+        cam->InitGeometry();
+        return cam;
+    }
+
+    return (TObject*)IsA()->New();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the pixel index corresponding to the coordinates given in x, y.
+//  The coordinates are given in pixel units (millimeters)
+//  If no pixel exists return -1;
+//
+Int_t MGeomCam::GetPixelIdxXY(Float_t x, Float_t y) const
+{
+    for (unsigned int i=0; i<fNumPixels; i++)
+        if ((*this)[i].IsInside(x, y))
+            return i;
+
+    return -1;
+}
+
+Int_t MGeomCam::GetPixelIdx(const TVector2 &v) const
+{
+    return GetPixelIdxXY(v.X(), v.Y());
+}
+
+Int_t MGeomCam::GetPixelIdxDeg(const TVector2 &v) const
+{
+    return GetPixelIdxXYdeg(v.X(), v.Y());
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all indices to arr of all neighbors around pix in a radius r.
+// The center pixel is also returned.
+//
+void MGeomCam::GetNeighbors(TArrayI &arr, const MGeomPix &pix, Float_t r) const
+{
+    arr.Set(GetNumPixels());
+
+    Int_t n = 0;
+
+    for (unsigned int i=0; i<GetNumPixels(); i++)
+    {
+        if (r>TMath::Hypot(pix.GetX()-(*this)[i].GetX(), pix.GetY()-(*this)[i].GetY()))
+            arr[n++] = i;
+    }
+
+    arr.Set(n);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all indices to arr of all neighbors around idx in a radius r.
+// The center pixel is also returned.
+//
+void MGeomCam::GetNeighbors(TArrayI &arr, UInt_t idx, Float_t r) const
+{
+    if (idx>=GetNumPixels())
+    {
+        arr.Set(0);
+        return;
+    }
+
+
+    const MGeomPix &pix = (*this)[idx];
+    GetNeighbors(arr, pix, r);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all pixels to list of all neighbors around pix in a radius r.
+// The center pixel is also returned.
+//
+void MGeomCam::GetNeighbors(TList &arr, const MGeomPix &pix, Float_t r) const
+{
+    for (unsigned int i=0; i<GetNumPixels(); i++)
+    {
+        if (r>TMath::Hypot(pix.GetX()-(*this)[i].GetX(), pix.GetY()-(*this)[i].GetY()))
+            arr.Add(fPixels.UncheckedAt(i));
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all pixels to list of all neighbors around idx in a radius r.
+// The center pixel is also returned.
+//
+void MGeomCam::GetNeighbors(TList &arr, UInt_t idx, Float_t r) const
+{
+    if (idx>=GetNumPixels())
+        return;
+
+    const MGeomPix &pix = (*this)[idx];
+    GetNeighbors(arr, pix, r);
+}
Index: /tags/Mars-V0.9/mgeom/MGeomCam.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCam.h	(revision 9772)
@@ -0,0 +1,97 @@
+#ifndef MARS_MGeomCam
+#define MARS_MGeomCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class TVector2;
+class TArrayI;
+class MGeomPix;
+
+class MGeomCam : public MParContainer
+{
+private:
+    UInt_t    fNumPixels;    // Number of pixels in this camera
+
+    Float_t   fCamDist;      // [m] Average distance of the camera from the mirror
+    Float_t   fConvMm2Deg;   // conversion factor to convert mm in the camera plain into degrees
+
+    TObjArray fPixels;       // Array of singel pixels storing the geometry
+
+    TArrayF   fMaxRadius;    // maximum radius of the part of the camera with the same pixel size (eg. for GUI layout)
+    TArrayF   fMinRadius;    // minimum radius of the part of the camera with the same pixel size (eg. for GUI layout)    
+    TArrayF   fPixRatio;     // Array storing the ratio between size of pixel 0 and pixel idx (for speed reasons)
+    TArrayF   fPixRatioSqrt; // Array storing the square root ratio between size of pixel 0 and pixel idx (for speed reasons)
+
+    Int_t     fNumSectors;   // Number of sectors
+    Int_t     fNumAreas;     // Number of different pixel sizes
+
+protected:
+
+    void CalcMaxRadius();
+    void CalcNumSectors();
+    void CalcNumAreas();
+    void InitOuterRing();
+
+
+public:
+    MGeomCam();
+    MGeomCam(UInt_t npix, Float_t dist, const char *name=NULL, const char *title=NULL);
+
+    virtual TObject *Clone(const char *newname=NULL) const;
+
+    void CalcPixRatio(); 
+    // FIXME, workaround: this function is made public just to allow
+    // the use of some camera files from the 0.7 beta version in which the 
+    // array containing pixel ratios is not initialized.
+    void InitGeometry()
+    {
+        CalcNumSectors();
+        CalcNumAreas();
+        CalcMaxRadius();
+        CalcPixRatio();
+        InitOuterRing();
+    }
+
+    Float_t GetCameraDist() const { return fCamDist; }
+    Float_t GetConvMm2Deg() const { return fConvMm2Deg; }
+
+    UInt_t  GetNumPixels()  const { return fNumPixels; }
+
+    Float_t GetMaxRadius(const Int_t i=-1) const;
+    Float_t GetMinRadius(const Int_t i=-1) const;
+    
+    UInt_t  GetNumSectors()                const  { return fNumSectors; }
+    UInt_t  GetNumAreas()                  const  { return fNumAreas; }
+    Float_t GetPixRatio(UInt_t i)          const;
+    Float_t GetPixRatioSqrt(UInt_t i)      const;
+
+    MGeomPix &operator[](Int_t i);
+    MGeomPix &operator[](Int_t i) const;
+
+    Int_t GetPixelIdx(const TVector2 &v) const;
+    Int_t GetPixelIdxDeg(const TVector2 &v) const;
+    Int_t GetPixelIdxXY(Float_t x, Float_t y) const;
+    Int_t GetPixelIdxXYdeg(Float_t x, Float_t y) const
+    {
+        return GetPixelIdxXY(x/fConvMm2Deg, y/fConvMm2Deg);
+    }
+
+    void GetNeighbors(TArrayI &arr, UInt_t idx,          Float_t r) const;
+    void GetNeighbors(TList &arr,   UInt_t idx,          Float_t r) const;
+    void GetNeighbors(TArrayI &arr, const MGeomPix &pix, Float_t r) const;
+    void GetNeighbors(TList &arr,   const MGeomPix &pix, Float_t r) const;
+
+    virtual void Print(Option_t *opt=NULL)   const;
+
+    ClassDef(MGeomCam, 4)  // Geometry base class for the camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mgeom/MGeomCamCT1.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamCT1.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamCT1.cc	(revision 9772)
@@ -0,0 +1,265 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamCT1
+//
+// This class stores the geometrz information of the CT1 camera.
+// The next neighbor information comes from a table, the geometry layout
+// is calculated (for Algorithm see CreateCam
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamCT1.h"
+
+#include <math.h>     // floor
+
+/*
+ #include "MLog.h"
+ #include "MLogManip.h"
+ */
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamCT1);
+
+// --------------------------------------------------------------------------
+//
+//  CT1 camera has 127 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamCT1::MGeomCamCT1(const char *name)
+    : MGeomCam(127, 4.88, name, "Geometry information of CT1 camera")
+{
+    CreateCam();
+    CreateNN();
+    InitGeometry();
+} 
+
+// --------------------------------------------------------------------------
+//
+//  Create Next Neighbors: Fill the NN Info into the pixel objects.
+//
+void MGeomCamCT1::CreateNN()
+{ 
+    const Short_t nn[127][6] = {       // Neighbors of #
+      {  1,   2,   3,   4,   5,   6},  // 0
+      {  0,   2,   6,   7,   8,  18},
+      {  0,   1,   3,   8,   9,  10},
+      {  0,   2,   4,  10,  11,  12},
+      {  0,   3,   5,  12,  13,  14},
+      {  0,   4,   6,  14,  15,  16},
+      {  0,   1,   5,  16,  17,  18},
+      {  1,   8,  18,  19,  20,  36},
+      {  1,   2,   7,   9,  20,  21},
+      {  2,   8,  10,  21,  22,  23},
+      {  2,   3,   9,  11,  23,  24},  // 10
+      {  3,  10,  12,  24,  25,  26},
+      {  3,   4,  11,  13,  26,  27},
+      {  4,  12,  14,  27,  28,  29},
+      {  4,   5,  13,  15,  29,  30},
+      {  5,  14,  16,  30,  31,  32},
+      {  5,   6,  15,  17,  32,  33},
+      {  6,  16,  18,  33,  34,  35},
+      {  1,   6,   7,  17,  35,  36},
+      {  7,  20,  36,  37,  38,  60},
+      {  7,   8,  19,  21,  38,  39},  // 20
+      {  8,   9,  20,  22,  39,  40},
+      {  9,  21,  23,  40,  41,  42},
+      {  9,  10,  22,  24,  42,  43},
+      { 10,  11,  23,  25,  43,  44},
+      { 11,  24,  26,  44,  45,  46},
+      { 11,  12,  25,  27,  46,  47},
+      { 12,  13,  26,  28,  47,  48},
+      { 13,  27,  29,  48,  49,  50},
+      { 13,  14,  28,  30,  50,  51},
+      { 14,  15,  29,  31,  51,  52},  // 30
+      { 15,  30,  32,  52,  53,  54},
+      { 15,  16,  31,  33,  54,  55},
+      { 16,  17,  32,  34,  55,  56},
+      { 17,  33,  35,  56,  57,  58},
+      { 17,  18,  34,  36,  58,  59},
+      {  7,  18,  19,  35,  59,  60},
+      { 19,  38,  60,  61,  62,  90},
+      { 19,  20,  37,  39,  62,  63},
+      { 20,  21,  38,  40,  63,  64},
+      { 21,  22,  39,  41,  64,  65},  // 40
+      { 22,  40,  42,  65,  66,  67},
+      { 22,  23,  41,  43,  67,  68},
+      { 23,  24,  42,  44,  68,  69},
+      { 24,  25,  43,  45,  69,  70},
+      { 25,  44,  46,  70,  71,  72},
+      { 25,  26,  45,  47,  72,  73},
+      { 26,  27,  46,  48,  73,  74},
+      { 27,  28,  47,  49,  74,  75},
+      { 28,  48,  50,  75,  76,  77},
+      { 28,  29,  49,  51,  77,  78},  // 50
+      { 29,  30,  50,  52,  78,  79},
+      { 30,  31,  51,  53,  79,  80},
+      { 31,  52,  54,  80,  81,  82},
+      { 31,  32,  53,  55,  82,  83},
+      { 32,  33,  54,  56,  83,  84},
+      { 33,  34,  55,  57,  84,  85},
+      { 34,  56,  58,  85,  86,  87},
+      { 34,  35,  57,  59,  87,  88},
+      { 35,  36,  58,  60,  88,  89},
+      { 19,  36,  37,  59,  89,  90},  // 60
+      { 37,  62,  90,  91,  92, 126},
+      { 37,  38,  61,  63,  92,  93},
+      { 38,  39,  62,  64,  93,  94},
+      { 39,  40,  63,  65,  94,  95},
+      { 40,  41,  64,  66,  95,  96},
+      { 41,  65,  67,  96,  97,  98},
+      { 41,  42,  66,  68,  98,  99},
+      { 42,  43,  67,  69,  99, 100},
+      { 43,  44,  68,  70, 100, 101},
+      { 44,  45,  69,  71, 101, 102},  // 70
+      { 45,  70,  72, 102, 103, 104},
+      { 45,  46,  71,  73, 104, 105},
+      { 46,  47,  72,  74, 105, 106},
+      { 47,  48,  73,  75, 106, 107},
+      { 48,  49,  74,  76, 107, 108},
+      { 49,  75,  77, 108, 109, 110},
+      { 49,  50,  76,  78, 110, 111},
+      { 50,  51,  77,  79, 111, 112},
+      { 51,  52,  78,  80, 112, 113},
+      { 52,  53,  79,  81, 113, 114},  // 80
+      { 53,  80,  82, 114, 115, 116},
+      { 53,  54,  81,  83, 116, 117},
+      { 54,  55,  82,  84, 117, 118},
+      { 55,  56,  83,  85, 118, 119},
+      { 56,  57,  84,  86, 119, 120},
+      { 57,  85,  87, 120, 121, 122},
+      { 57,  58,  86,  88, 122, 123},
+      { 58,  59,  87,  89, 123, 124},
+      { 59,  60,  88,  90, 124, 125},
+      { 37,  60,  61,  89, 125, 126},  // 90
+      { 61,  92, 126,  -1,  -1,  -1},
+      { 61,  62,  91,  93,  -1,  -1},
+      { 62,  63,  92,  94,  -1,  -1},
+      { 63,  64,  93,  95,  -1,  -1},
+      { 64,  65,  94,  96,  -1,  -1},
+      { 65,  66,  95,  97,  -1,  -1},
+      { 66,  96,  98,  -1,  -1,  -1},
+      { 66,  67,  97,  99,  -1,  -1},
+      { 67,  68,  98, 100,  -1,  -1},
+      { 68,  69,  99, 101,  -1,  -1},  // 100
+      { 69,  70, 100, 102,  -1,  -1},
+      { 70,  71, 101, 103,  -1,  -1},
+      { 71, 102, 104,  -1,  -1,  -1},
+      { 71,  72, 103, 105,  -1,  -1},
+      { 72,  73, 104, 106,  -1,  -1},
+      { 73,  74, 105, 107,  -1,  -1},
+      { 74,  75, 106, 108,  -1,  -1},
+      { 75,  76, 107, 109,  -1,  -1},
+      { 76, 108, 110,  -1,  -1,  -1},
+      { 76,  77, 109, 111,  -1,  -1},  // 110
+      { 77,  78, 110, 112,  -1,  -1},
+      { 78,  79, 111, 113,  -1,  -1},
+      { 79,  80, 112, 114,  -1,  -1},
+      { 80,  81, 113, 115,  -1,  -1},
+      { 81, 114, 116,  -1,  -1,  -1},
+      { 81,  82, 115, 117,  -1,  -1},
+      { 82,  83, 116, 118,  -1,  -1},
+      { 83,  84, 117, 119,  -1,  -1},
+      { 84,  85, 118, 120,  -1,  -1},
+      { 85,  86, 119, 121,  -1,  -1},  // 120
+      { 86, 120, 122,  -1,  -1,  -1},
+      { 86,  87, 121, 123,  -1,  -1},
+      { 87,  88, 122, 124,  -1,  -1},
+      { 88,  89, 123, 125,  -1,  -1},
+      { 89,  90, 124, 126,  -1,  -1},
+      { 61,  90,  91, 125,  -1,  -1}   // 126
+  };
+
+  for (Int_t i=0; i<127; i++)
+      (*this)[i].SetNeighbors(nn[i][0], nn[i][1], nn[i][2],
+                              nn[i][3], nn[i][4], nn[i][5]);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the geometry information of CT1 and fill this information
+//  into the pixel objects.
+//
+void MGeomCamCT1::CreateCam()
+{
+    //
+    // fill the geometry class with the coordinates of the CT1 camera
+    //
+    //*fLog << inf << " Create CT1 geometry " << endl;
+
+    //
+    // this algorithm is from Martin Kestel originally
+    // it was punt into a root/C++ context by Harald Kornmayer and Thomas Bretz
+   
+    const Float_t diameter = 21;    // units are mm
+    const Float_t kS32  = sqrt(3)/2;
+
+    //
+    //  add the first pixel to the list
+    //
+    Int_t pixnum = 0;
+
+    (*this)[pixnum++].Set(0, 0, diameter);
+
+    for (Int_t ring=1; ring<7; ring++)
+    {
+        //
+        // calc. coords for this ring counting from the
+        // starting number to the ending number
+        //
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring-i*0.5)*diameter,
+                                  i*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring*0.5-i)*diameter,
+                                  ring*kS32 * diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set(-(ring+i)*0.5*diameter,
+                                  (ring-i)*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((0.5*i-ring)*diameter,
+                                  -i*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((i-ring*0.5)*diameter,
+                                  -ring*kS32 * diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring+i)*0.5*diameter,
+                                  (-ring+i)*kS32*diameter,
+                                  diameter);
+    }
+}
+
Index: /tags/Mars-V0.9/mgeom/MGeomCamCT1.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamCT1.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamCT1.h	(revision 9772)
@@ -0,0 +1,23 @@
+#ifndef MARS_MGeomCamCT1
+#define MARS_MGeomCamCT1
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamCT1 : public MGeomCam
+{
+private:
+
+    void CreateCam();
+    void CreateNN();
+
+public:
+
+    MGeomCamCT1(const char *name=NULL);
+
+    ClassDef(MGeomCamCT1, 1)		// Geometry class for the CT1 camera
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgeom/MGeomCamCT1Daniel.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamCT1Daniel.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamCT1Daniel.cc	(revision 9772)
@@ -0,0 +1,269 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!   Author(s): Wolfgang Wittek 10/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamCT1Daniel
+//
+// This class stores the geometry information of the CT1 camera.
+// The next neighbor information comes from a table, the geometry layout
+// is calculated (for Algorithm see CreateCam
+//
+//
+// The only difference to MGeomCamCT1 is the second argument of MGeomCam
+// (which is the distance camera-reflector)
+//        it is        dist = 4.8129 m    (instead of 4.88  m)
+//
+// together with the pixel diameter of d = 21 mm this gives      
+// d/dist = 0.0043633 = 0.25 deg    (instead of 0.0043033 = 0.2466 deg)
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamCT1Daniel.h"
+
+#include <math.h>     // floor
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamCT1Daniel);
+
+// --------------------------------------------------------------------------
+//
+//  CT1 camera has 127 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamCT1Daniel::MGeomCamCT1Daniel(const char *name)
+    : MGeomCam(127, 4.8129, name, "Geometry information of CT1 camera")
+{
+    CreateCam();
+    CreateNN();
+    InitGeometry();
+} 
+
+// --------------------------------------------------------------------------
+//
+//  Create Next Neighbors: Fill the NN Info into the pixel objects.
+//
+void MGeomCamCT1Daniel::CreateNN()
+{ 
+    const Short_t nn[127][6] = {       // Neighbors of #
+      {  1,   2,   3,   4,   5,   6},  // 0
+      {  0,   2,   6,   7,   8,  18},
+      {  0,   1,   3,   8,   9,  10},
+      {  0,   2,   4,  10,  11,  12},
+      {  0,   3,   5,  12,  13,  14},
+      {  0,   4,   6,  14,  15,  16},
+      {  0,   1,   5,  16,  17,  18},
+      {  1,   8,  18,  19,  20,  36},
+      {  1,   2,   7,   9,  20,  21},
+      {  2,   8,  10,  21,  22,  23},
+      {  2,   3,   9,  11,  23,  24},  // 10
+      {  3,  10,  12,  24,  25,  26},
+      {  3,   4,  11,  13,  26,  27},
+      {  4,  12,  14,  27,  28,  29},
+      {  4,   5,  13,  15,  29,  30},
+      {  5,  14,  16,  30,  31,  32},
+      {  5,   6,  15,  17,  32,  33},
+      {  6,  16,  18,  33,  34,  35},
+      {  1,   6,   7,  17,  35,  36},
+      {  7,  20,  36,  37,  38,  60},
+      {  7,   8,  19,  21,  38,  39},  // 20
+      {  8,   9,  20,  22,  39,  40},
+      {  9,  21,  23,  40,  41,  42},
+      {  9,  10,  22,  24,  42,  43},
+      { 10,  11,  23,  25,  43,  44},
+      { 11,  24,  26,  44,  45,  46},
+      { 11,  12,  25,  27,  46,  47},
+      { 12,  13,  26,  28,  47,  48},
+      { 13,  27,  29,  48,  49,  50},
+      { 13,  14,  28,  30,  50,  51},
+      { 14,  15,  29,  31,  51,  52},  // 30
+      { 15,  30,  32,  52,  53,  54},
+      { 15,  16,  31,  33,  54,  55},
+      { 16,  17,  32,  34,  55,  56},
+      { 17,  33,  35,  56,  57,  58},
+      { 17,  18,  34,  36,  58,  59},
+      {  7,  18,  19,  35,  59,  60},
+      { 19,  38,  60,  61,  62,  90},
+      { 19,  20,  37,  39,  62,  63},
+      { 20,  21,  38,  40,  63,  64},
+      { 21,  22,  39,  41,  64,  65},  // 40
+      { 22,  40,  42,  65,  66,  67},
+      { 22,  23,  41,  43,  67,  68},
+      { 23,  24,  42,  44,  68,  69},
+      { 24,  25,  43,  45,  69,  70},
+      { 25,  44,  46,  70,  71,  72},
+      { 25,  26,  45,  47,  72,  73},
+      { 26,  27,  46,  48,  73,  74},
+      { 27,  28,  47,  49,  74,  75},
+      { 28,  48,  50,  75,  76,  77},
+      { 28,  29,  49,  51,  77,  78},  // 50
+      { 29,  30,  50,  52,  78,  79},
+      { 30,  31,  51,  53,  79,  80},
+      { 31,  52,  54,  80,  81,  82},
+      { 31,  32,  53,  55,  82,  83},
+      { 32,  33,  54,  56,  83,  84},
+      { 33,  34,  55,  57,  84,  85},
+      { 34,  56,  58,  85,  86,  87},
+      { 34,  35,  57,  59,  87,  88},
+      { 35,  36,  58,  60,  88,  89},
+      { 19,  36,  37,  59,  89,  90},  // 60
+      { 37,  62,  90,  91,  92, 126},
+      { 37,  38,  61,  63,  92,  93},
+      { 38,  39,  62,  64,  93,  94},
+      { 39,  40,  63,  65,  94,  95},
+      { 40,  41,  64,  66,  95,  96},
+      { 41,  65,  67,  96,  97,  98},
+      { 41,  42,  66,  68,  98,  99},
+      { 42,  43,  67,  69,  99, 100},
+      { 43,  44,  68,  70, 100, 101},
+      { 44,  45,  69,  71, 101, 102},  // 70
+      { 45,  70,  72, 102, 103, 104},
+      { 45,  46,  71,  73, 104, 105},
+      { 46,  47,  72,  74, 105, 106},
+      { 47,  48,  73,  75, 106, 107},
+      { 48,  49,  74,  76, 107, 108},
+      { 49,  75,  77, 108, 109, 110},
+      { 49,  50,  76,  78, 110, 111},
+      { 50,  51,  77,  79, 111, 112},
+      { 51,  52,  78,  80, 112, 113},
+      { 52,  53,  79,  81, 113, 114},  // 80
+      { 53,  80,  82, 114, 115, 116},
+      { 53,  54,  81,  83, 116, 117},
+      { 54,  55,  82,  84, 117, 118},
+      { 55,  56,  83,  85, 118, 119},
+      { 56,  57,  84,  86, 119, 120},
+      { 57,  85,  87, 120, 121, 122},
+      { 57,  58,  86,  88, 122, 123},
+      { 58,  59,  87,  89, 123, 124},
+      { 59,  60,  88,  90, 124, 125},
+      { 37,  60,  61,  89, 125, 126},  // 90
+      { 61,  92, 126,  -1,  -1,  -1},
+      { 61,  62,  91,  93,  -1,  -1},
+      { 62,  63,  92,  94,  -1,  -1},
+      { 63,  64,  93,  95,  -1,  -1},
+      { 64,  65,  94,  96,  -1,  -1},
+      { 65,  66,  95,  97,  -1,  -1},
+      { 66,  96,  98,  -1,  -1,  -1},
+      { 66,  67,  97,  99,  -1,  -1},
+      { 67,  68,  98, 100,  -1,  -1},
+      { 68,  69,  99, 101,  -1,  -1},  // 100
+      { 69,  70, 100, 102,  -1,  -1},
+      { 70,  71, 101, 103,  -1,  -1},
+      { 71, 102, 104,  -1,  -1,  -1},
+      { 71,  72, 103, 105,  -1,  -1},
+      { 72,  73, 104, 106,  -1,  -1},
+      { 73,  74, 105, 107,  -1,  -1},
+      { 74,  75, 106, 108,  -1,  -1},
+      { 75,  76, 107, 109,  -1,  -1},
+      { 76, 108, 110,  -1,  -1,  -1},
+      { 76,  77, 109, 111,  -1,  -1},  // 110
+      { 77,  78, 110, 112,  -1,  -1},
+      { 78,  79, 111, 113,  -1,  -1},
+      { 79,  80, 112, 114,  -1,  -1},
+      { 80,  81, 113, 115,  -1,  -1},
+      { 81, 114, 116,  -1,  -1,  -1},
+      { 81,  82, 115, 117,  -1,  -1},
+      { 82,  83, 116, 118,  -1,  -1},
+      { 83,  84, 117, 119,  -1,  -1},
+      { 84,  85, 118, 120,  -1,  -1},
+      { 85,  86, 119, 121,  -1,  -1},  // 120
+      { 86, 120, 122,  -1,  -1,  -1},
+      { 86,  87, 121, 123,  -1,  -1},
+      { 87,  88, 122, 124,  -1,  -1},
+      { 88,  89, 123, 125,  -1,  -1},
+      { 89,  90, 124, 126,  -1,  -1},
+      { 61,  90,  91, 125,  -1,  -1}   // 126
+  };
+
+  for (Int_t i=0; i<127; i++)
+      (*this)[i].SetNeighbors(nn[i][0], nn[i][1], nn[i][2],
+                              nn[i][3], nn[i][4], nn[i][5]);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the geometry information of CT1 and fill this information
+//  into the pixel objects.
+//
+void MGeomCamCT1Daniel::CreateCam()
+{
+    //
+    // fill the geometry class with the coordinates of the CT1 camera
+    //
+    //*fLog << inf << " Create CT1 geometry " << endl;
+
+    //
+    // this algorithm is from Martin Kestel originally
+    // it was punt into a root/C++ context by Harald Kornmayer and Thomas Bretz
+   
+    const Float_t diameter = 21;    // units are mm
+    const Float_t kS32  = sqrt(3)/2;
+
+    //
+    //  add the first pixel to the list
+    //
+    Int_t pixnum = 0;
+
+    (*this)[pixnum++].Set(0, 0, diameter);
+
+    for (Int_t ring=1; ring<7; ring++)
+    {
+        //
+        // calc. coords for this ring counting from the
+        // starting number to the ending number
+        //
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring-i*0.5)*diameter,
+                                  i*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring*0.5-i)*diameter,
+                                  ring*kS32 * diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set(-(ring+i)*0.5*diameter,
+                                  (ring-i)*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((0.5*i-ring)*diameter,
+                                  -i*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((i-ring*0.5)*diameter,
+                                  -ring*kS32 * diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring+i)*0.5*diameter,
+                                  (-ring+i)*kS32*diameter,
+                                  diameter);
+    }
+}
+
Index: /tags/Mars-V0.9/mgeom/MGeomCamCT1Daniel.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamCT1Daniel.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamCT1Daniel.h	(revision 9772)
@@ -0,0 +1,23 @@
+#ifndef MARS_MGeomCamCT1Daniel
+#define MARS_MGeomCamCT1Daniel
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamCT1Daniel : public MGeomCam
+{
+private:
+
+    void CreateCam();
+    void CreateNN();
+
+public:
+
+    MGeomCamCT1Daniel(const char *name=NULL);
+
+    ClassDef(MGeomCamCT1Daniel, 1)  // Geometry class for the CT1 camera (daniel's version)
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgeom/MGeomCamECO1000.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamECO1000.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamECO1000.cc	(revision 9772)
@@ -0,0 +1,895 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch, 4/2003 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamECO1000
+//
+// This class stores the geometry information of the ECO1000 camera.
+// All information are copied from tables, see source code.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamECO1000.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamECO1000);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Magic camera has 577 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamECO1000::MGeomCamECO1000(const char *name)
+    : MGeomCam(577, 34.5, name, "Geometry information of Magic Camera")
+{
+    CreateCam();
+    CreateNN();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information from a table into the pixel objects.
+//
+void MGeomCamECO1000::CreateCam()
+{
+    //
+    //   fill the geometry class with the coordinates of the MAGIC camera
+    //
+
+    //
+    //   here define the hardwire things of the ECO 1000 telescope
+    //
+    const Float_t xtemp[577] = {
+      0, 60, 30, -30, -60, -30, 30, 120, // 0
+      90, 60, 0, -60, -90, -120, -90, -60, // 8
+      0, 60, 90, 180, 150, 120, 90, 30, // 16
+      -30, -90, -120, -150, -180, -150, -120, -90, // 24
+      -30, 30, 90, 120, 150, 240, 210, 180, // 32
+      150, 120, 60, 0, -60, -120, -150, -180, // 40
+      -210, -240, -210, -180, -150, -120, -60, 0, // 48
+      60, 120, 150, 180, 210, 300, 270, 240, // 56
+      210, 180, 150, 90, 30, -30, -90, -150, // 64
+      -180, -210, -240, -270, -300, -270, -240, -210, // 72
+      -180, -150, -90, -30, 30, 90, 150, 180, // 80
+      210, 240, 270, 360, 330, 300, 270, 240, // 88
+      210, 180, 120, 60, 0, -60, -120, -180, // 96
+      -210, -240, -270, -300, -330, -360, -330, -300, // 104
+      -270, -240, -210, -180, -120, -60, 0, 60, // 112
+      120, 180, 210, 240, 270, 300, 330, 420, // 120
+      390, 360, 330, 300, 270, 240, 210, 150, // 128
+      90, 30, -30, -90, -150, -210, -240, -270, // 136
+      -300, -330, -360, -390, -420, -390, -360, -330, // 144
+      -300, -270, -240, -210, -150, -90, -30, 30, // 152
+      90, 150, 210, 240, 270, 300, 330, 360, // 160
+      390, 480, 450, 420, 390, 360, 330, 300, // 168
+      270, 240, 180, 120, 60, 0, -60, -120, // 176
+      -180, -240, -270, -300, -330, -360, -390, -420, // 184
+      -450, -480, -450, -420, -390, -360, -330, -300, // 192
+      -270, -240, -180, -120, -60, 0, 60, 120, // 200
+      180, 240, 270, 300, 330, 360, 390, 420, // 208
+      450, 540, 510, 480, 450, 420, 390, 360, // 216
+      330, 300, 270, 210, 150, 90, 30, -30, // 224
+      -90, -150, -210, -270, -300, -330, -360, -390, // 232
+      -420, -450, -480, -510, -540, -510, -480, -450, // 240
+      -420, -390, -360, -330, -300, -270, -210, -150, // 248
+      -90, -30, 30, 90, 150, 210, 270, 300, // 256
+      330, 360, 390, 420, 450, 480, 510, 600, // 264
+      570, 540, 510, 480, 450, 420, 390, 360, // 272
+      330, 300, 240, 180, 120, 60, 0, -60, // 280
+      -120, -180, -240, -300, -330, -360, -390, -420, // 288
+      -450, -480, -510, -540, -570, -600, -570, -540, // 296
+      -510, -480, -450, -420, -390, -360, -330, -300, // 304
+      -240, -180, -120, -60, 0, 60, 120, 180, // 312
+      240, 300, 330, 360, 390, 420, 450, 480, // 320
+      510, 540, 570, 660, 630, 600, 570, 540, // 328
+      510, 480, 450, 420, 390, 360, 330, 270, // 336
+      210, 150, 90, 30, -30, -90, -150, -210, // 344
+      -270, -330, -360, -390, -420, -450, -480, -510, // 352
+      -540, -570, -600, -630, -660, -630, -600, -570, // 360
+      -540, -510, -480, -450, -420, -390, -360, -330, // 368
+      -270, -210, -150, -90, -30, 30, 90, 150, // 376
+      210, 270, 330, 360, 390, 420, 450, 480, // 384
+      510, 540, 570, 600, 630, 720, 660, 600, // 392
+      540, 480, 420, 300, 180, 60, -60, -180, // 400
+      -300, -420, -480, -540, -600, -660, -720, -720, // 408
+      -660, -600, -540, -480, -420, -300, -180, -60, // 416
+      60, 180, 300, 420, 480, 540, 600, 660, // 424
+      720, 840, 780, 720, 660, 600, 540, 480, // 432
+      360, 240, 120, 0, -120, -240, -360, -480, // 440
+      -540, -600, -660, -720, -780, -840, -840, -780, // 448
+      -720, -660, -600, -540, -480, -360, -240, -120, // 456
+      0, 120, 240, 360, 480, 540, 600, 660, // 464
+      720, 780, 840, 960, 900, 840, 780, 720, // 472
+      660, 600, 540, 420, 300, 180, 60, -60, // 480
+      -180, -300, -420, -540, -600, -660, -720, -780, // 488
+      -840, -900, -960, -960, -900, -840, -780, -720, // 496
+      -660, -600, -540, -420, -300, -180, -60, 60, // 504
+      180, 300, 420, 540, 600, 660, 720, 780, // 512
+      840, 900, 960, 1080, 1020, 960, 900, 840, // 520
+      780, 720, 660, 600, 480, 360, 240, 120, // 528
+      0, -120, -240, -360, -480, -600, -660, -720, // 536
+      -780, -840, -900, -960, -1020, -1080, -1080, -1020, // 544
+      -960, -900, -840, -780, -720, -660, -600, -480, // 552
+      -360, -240, -120, 0, 120, 240, 360, 480, // 560
+      600, 660, 720, 780, 840, 900, 960, 1020, // 568
+      1080                        //576
+    };
+ 
+    const Float_t ytemp[577] = {
+      0, 0, 51.962, 51.962, 0, -51.962, -51.962, 0, // 0
+      51.962, 103.922, 103.922, 103.922, 51.962, 0, -51.962, -103.922, // 8
+      -103.922, -103.922, -51.962, 0, 51.962, 103.922, 155.884, 155.884, // 16
+      155.884, 155.884, 103.922, 51.962, 0, -51.962, -103.922, -155.884, // 24
+      -155.884, -155.884, -155.884, -103.922, -51.962, 0, 51.962, 103.922, // 32
+      155.884, 207.846, 207.846, 207.846, 207.846, 207.846, 155.884, 103.922, // 40
+      51.962, 0, -51.962, -103.922, -155.884, -207.846, -207.846, -207.846, // 48
+      -207.846, -207.846, -155.884, -103.922, -51.962, 0, 51.962, 103.922, // 56
+      155.884, 207.846, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, // 64
+      207.846, 155.884, 103.922, 51.962, 0, -51.962, -103.922, -155.884, // 72
+      -207.846, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -207.846, // 80
+      -155.884, -103.922, -51.962, 0, 51.962, 103.922, 155.884, 207.846, // 88
+      259.808, 311.77, 311.77, 311.77, 311.77, 311.77, 311.77, 311.77, // 96
+      259.808, 207.846, 155.884, 103.922, 51.962, 0, -51.962, -103.922, // 104
+      -155.884, -207.846, -259.808, -311.77, -311.77, -311.77, -311.77, -311.77, // 112
+      -311.77, -311.77, -259.808, -207.846, -155.884, -103.922, -51.962, 0, // 120
+      51.962, 103.922, 155.884, 207.846, 259.808, 311.77, 363.73, 363.73, // 128
+      363.73, 363.73, 363.73, 363.73, 363.73, 363.73, 311.77, 259.808, // 136
+      207.846, 155.884, 103.922, 51.962, 0, -51.962, -103.922, -155.884, // 144
+      -207.846, -259.808, -311.77, -363.73, -363.73, -363.73, -363.73, -363.73, // 152
+      -363.73, -363.73, -363.73, -311.77, -259.808, -207.846, -155.884, -103.922, // 160
+      -51.962, 0, 51.962, 103.922, 155.884, 207.846, 259.808, 311.77, // 168
+      363.73, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, // 176
+      415.692, 415.692, 363.73, 311.77, 259.808, 207.846, 155.884, 103.922, // 184
+      51.962, 0, -51.962, -103.922, -155.884, -207.846, -259.808, -311.77, // 192
+      -363.73, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, // 200
+      -415.692, -415.692, -363.73, -311.77, -259.808, -207.846, -155.884, -103.922, // 208
+      -51.962, 0, 51.962, 103.922, 155.884, 207.846, 259.808, 311.77, // 216
+      363.73, 415.692, 467.654, 467.654, 467.654, 467.654, 467.654, 467.654, // 224
+      467.654, 467.654, 467.654, 467.654, 415.692, 363.73, 311.77, 259.808, // 232
+      207.846, 155.884, 103.922, 51.962, 0, -51.962, -103.922, -155.884, // 240
+      -207.846, -259.808, -311.77, -363.73, -415.692, -467.654, -467.654, -467.654, // 248
+      -467.654, -467.654, -467.654, -467.654, -467.654, -467.654, -467.654, -415.692, // 256
+      -363.73, -311.77, -259.808, -207.846, -155.884, -103.922, -51.962, 0, // 264
+      51.962, 103.922, 155.884, 207.846, 259.808, 311.77, 363.73, 415.692, // 272
+      467.654, 519.616, 519.616, 519.616, 519.616, 519.616, 519.616, 519.616, // 280
+      519.616, 519.616, 519.616, 519.616, 467.654, 415.692, 363.73, 311.77, // 288
+      259.808, 207.846, 155.884, 103.922, 51.962, 0, -51.962, -103.922, // 296
+      -155.884, -207.846, -259.808, -311.77, -363.73, -415.692, -467.654, -519.616, // 304
+      -519.616, -519.616, -519.616, -519.616, -519.616, -519.616, -519.616, -519.616, // 312
+      -519.616, -519.616, -467.654, -415.692, -363.73, -311.77, -259.808, -207.846, // 320
+      -155.884, -103.922, -51.962, 0, 51.962, 103.922, 155.884, 207.846, // 328
+      259.808, 311.77, 363.73, 415.692, 467.654, 519.616, 571.576, 571.576, // 336
+      571.576, 571.576, 571.576, 571.576, 571.576, 571.576, 571.576, 571.576, // 344
+      571.576, 571.576, 519.616, 467.654, 415.692, 363.73, 311.77, 259.808, // 352
+      207.846, 155.884, 103.922, 51.962, 0, -51.962, -103.922, -155.884, // 360
+      -207.846, -259.808, -311.77, -363.73, -415.692, -467.654, -519.616, -571.576, // 368
+      -571.576, -571.576, -571.576, -571.576, -571.576, -571.576, -571.576, -571.576, // 376
+      -571.576, -571.576, -571.576, -519.616, -467.654, -415.692, -363.73, -311.77, // 384
+      -259.808, -207.846, -155.884, -103.922, -51.962, 69.282, 173.206, 277.128, // 392
+      381.052, 484.974, 588.898, 658.18, 658.18, 658.18, 658.18, 658.18, // 400
+      658.18, 588.898, 484.974, 381.052, 277.128, 173.206, 69.282, -69.282, // 408
+      -173.206, -277.128, -381.052, -484.974, -588.898, -658.18, -658.18, -658.18, // 416
+      -658.18, -658.18, -658.18, -588.898, -484.974, -381.052, -277.128, -173.206, // 424
+      -69.282, 69.282, 173.206, 277.128, 381.052, 484.974, 588.898, 692.82, // 432
+      762.102, 762.102, 762.102, 762.102, 762.102, 762.102, 762.102, 692.82, // 440
+      588.898, 484.974, 381.052, 277.128, 173.206, 69.282, -69.282, -173.206, // 448
+      -277.128, -381.052, -484.974, -588.898, -692.82, -762.102, -762.102, -762.102, // 456
+      -762.102, -762.102, -762.102, -762.102, -692.82, -588.898, -484.974, -381.052, // 464
+      -277.128, -173.206, -69.282, 69.282, 173.206, 277.128, 381.052, 484.974, // 472
+      588.898, 692.82, 796.744, 866.026, 866.026, 866.026, 866.026, 866.026, // 480
+      866.026, 866.026, 866.026, 796.744, 692.82, 588.898, 484.974, 381.052, // 488
+      277.128, 173.206, 69.282, -69.282, -173.206, -277.128, -381.052, -484.974, // 496
+      -588.898, -692.82, -796.744, -866.026, -866.026, -866.026, -866.026, -866.026, // 504
+      -866.026, -866.026, -866.026, -796.744, -692.82, -588.898, -484.974, -381.052, // 512
+      -277.128, -173.206, -69.282, 69.282, 173.206, 277.128, 381.052, 484.974, // 520
+      588.898, 692.82, 796.744, 900.666, 969.948, 969.948, 969.948, 969.948, // 528
+      969.948, 969.948, 969.948, 969.948, 969.948, 900.666, 796.744, 692.82, // 536
+      588.898, 484.974, 381.052, 277.128, 173.206, 69.282, -69.282, -173.206, // 544
+      -277.128, -381.052, -484.974, -588.898, -692.82, -796.744, -900.666, -969.948, // 552
+      -969.948, -969.948, -969.948, -969.948, -969.948, -969.948, -969.948, -969.948, // 560
+      -900.666, -796.744, -692.82, -588.898, -484.974, -381.052, -277.128, -173.206, // 568
+      -69.282                        //576
+};
+
+    const Float_t rtemp[577] = {
+      60, 60, 60, 60, 60, 60, 60, 60, // 0
+      60, 60, 60, 60, 60, 60, 60, 60, // 8
+      60, 60, 60, 60, 60, 60, 60, 60, // 16
+      60, 60, 60, 60, 60, 60, 60, 60, // 24
+      60, 60, 60, 60, 60, 60, 60, 60, // 32
+      60, 60, 60, 60, 60, 60, 60, 60, // 40
+      60, 60, 60, 60, 60, 60, 60, 60, // 48
+      60, 60, 60, 60, 60, 60, 60, 60, // 56
+      60, 60, 60, 60, 60, 60, 60, 60, // 64
+      60, 60, 60, 60, 60, 60, 60, 60, // 72
+      60, 60, 60, 60, 60, 60, 60, 60, // 80
+      60, 60, 60, 60, 60, 60, 60, 60, // 88
+      60, 60, 60, 60, 60, 60, 60, 60, // 96
+      60, 60, 60, 60, 60, 60, 60, 60, // 104
+      60, 60, 60, 60, 60, 60, 60, 60, // 112
+      60, 60, 60, 60, 60, 60, 60, 60, // 120
+      60, 60, 60, 60, 60, 60, 60, 60, // 128
+      60, 60, 60, 60, 60, 60, 60, 60, // 136
+      60, 60, 60, 60, 60, 60, 60, 60, // 144
+      60, 60, 60, 60, 60, 60, 60, 60, // 152
+      60, 60, 60, 60, 60, 60, 60, 60, // 160
+      60, 60, 60, 60, 60, 60, 60, 60, // 168
+      60, 60, 60, 60, 60, 60, 60, 60, // 176
+      60, 60, 60, 60, 60, 60, 60, 60, // 184
+      60, 60, 60, 60, 60, 60, 60, 60, // 192
+      60, 60, 60, 60, 60, 60, 60, 60, // 200
+      60, 60, 60, 60, 60, 60, 60, 60, // 208
+      60, 60, 60, 60, 60, 60, 60, 60, // 216
+      60, 60, 60, 60, 60, 60, 60, 60, // 224
+      60, 60, 60, 60, 60, 60, 60, 60, // 232
+      60, 60, 60, 60, 60, 60, 60, 60, // 240
+      60, 60, 60, 60, 60, 60, 60, 60, // 248
+      60, 60, 60, 60, 60, 60, 60, 60, // 256
+      60, 60, 60, 60, 60, 60, 60, 60, // 264
+      60, 60, 60, 60, 60, 60, 60, 60, // 272
+      60, 60, 60, 60, 60, 60, 60, 60, // 280
+      60, 60, 60, 60, 60, 60, 60, 60, // 288
+      60, 60, 60, 60, 60, 60, 60, 60, // 296
+      60, 60, 60, 60, 60, 60, 60, 60, // 304
+      60, 60, 60, 60, 60, 60, 60, 60, // 312
+      60, 60, 60, 60, 60, 60, 60, 60, // 320
+      60, 60, 60, 60, 60, 60, 60, 60, // 328
+      60, 60, 60, 60, 60, 60, 60, 60, // 336
+      60, 60, 60, 60, 60, 60, 60, 60, // 344
+      60, 60, 60, 60, 60, 60, 60, 60, // 352
+      60, 60, 60, 60, 60, 60, 60, 60, // 360
+      60, 60, 60, 60, 60, 60, 60, 60, // 368
+      60, 60, 60, 60, 60, 60, 60, 60, // 376
+      60, 60, 60, 60, 60, 60, 60, 60, // 384
+      60, 60, 60, 60, 60, 120, 120, 120, // 392
+      120, 120, 120, 120, 120, 120, 120, 120, // 400
+      120, 120, 120, 120, 120, 120, 120, 120, // 408
+      120, 120, 120, 120, 120, 120, 120, 120, // 416
+      120, 120, 120, 120, 120, 120, 120, 120, // 424
+      120, 120, 120, 120, 120, 120, 120, 120, // 432
+      120, 120, 120, 120, 120, 120, 120, 120, // 440
+      120, 120, 120, 120, 120, 120, 120, 120, // 448
+      120, 120, 120, 120, 120, 120, 120, 120, // 456
+      120, 120, 120, 120, 120, 120, 120, 120, // 464
+      120, 120, 120, 120, 120, 120, 120, 120, // 472
+      120, 120, 120, 120, 120, 120, 120, 120, // 480
+      120, 120, 120, 120, 120, 120, 120, 120, // 488
+      120, 120, 120, 120, 120, 120, 120, 120, // 496
+      120, 120, 120, 120, 120, 120, 120, 120, // 504
+      120, 120, 120, 120, 120, 120, 120, 120, // 512
+      120, 120, 120, 120, 120, 120, 120, 120, // 520
+      120, 120, 120, 120, 120, 120, 120, 120, // 528
+      120, 120, 120, 120, 120, 120, 120, 120, // 536
+      120, 120, 120, 120, 120, 120, 120, 120, // 544
+      120, 120, 120, 120, 120, 120, 120, 120, // 552
+      120, 120, 120, 120, 120, 120, 120, 120, // 560
+      120, 120, 120, 120, 120, 120, 120, 120, // 568
+      120                        //576
+};
+
+    //
+    //   fill the pixels list with this data
+    //
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+        (*this)[i].Set(xtemp[i], ytemp[i], rtemp[i]) ;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the next neighbor information from a table into the pixel
+//  objects.
+//
+void MGeomCamECO1000::CreateNN()
+{
+    const Short_t nn[577][6] = {         // Neighbors of #
+        {   1,   2,   3,   4,   5,   6}, // 0
+        {   0,   2,   6,   7,   8,  18},
+        {   0,   1,   3,   8,   9,  10},
+        {   0,   2,   4,  10,  11,  12},
+        {   0,   3,   5,  12,  13,  14},
+        {   0,   4,   6,  14,  15,  16},
+        {   0,   1,   5,  16,  17,  18},
+        {   1,   8,  18,  19,  20,  36},
+        {   1,   2,   7,   9,  20,  21},
+        {   2,   8,  10,  21,  22,  23},
+        {   2,   3,   9,  11,  23,  24},
+        {   3,  10,  12,  24,  25,  26},
+        {   3,   4,  11,  13,  26,  27},
+        {   4,  12,  14,  27,  28,  29},
+        {   4,   5,  13,  15,  29,  30},
+        {   5,  14,  16,  30,  31,  32},
+        {   5,   6,  15,  17,  32,  33},
+        {   6,  16,  18,  33,  34,  35},
+        {   1,   6,   7,  17,  35,  36},
+        {   7,  20,  36,  37,  38,  60},
+        {   7,   8,  19,  21,  38,  39}, // 20
+        {   8,   9,  20,  22,  39,  40},
+        {   9,  21,  23,  40,  41,  42},
+        {   9,  10,  22,  24,  42,  43},
+        {  10,  11,  23,  25,  43,  44},
+        {  11,  24,  26,  44,  45,  46},
+        {  11,  12,  25,  27,  46,  47},
+        {  12,  13,  26,  28,  47,  48},
+        {  13,  27,  29,  48,  49,  50},
+        {  13,  14,  28,  30,  50,  51},
+        {  14,  15,  29,  31,  51,  52},
+        {  15,  30,  32,  52,  53,  54},
+        {  15,  16,  31,  33,  54,  55},
+        {  16,  17,  32,  34,  55,  56},
+        {  17,  33,  35,  56,  57,  58},
+        {  17,  18,  34,  36,  58,  59},
+        {   7,  18,  19,  35,  59,  60},
+        {  19,  38,  60,  61,  62,  90},
+        {  19,  20,  37,  39,  62,  63},
+        {  20,  21,  38,  40,  63,  64},
+        {  21,  22,  39,  41,  64,  65}, // 40
+        {  22,  40,  42,  65,  66,  67},
+        {  22,  23,  41,  43,  67,  68},
+        {  23,  24,  42,  44,  68,  69},
+        {  24,  25,  43,  45,  69,  70},
+        {  25,  44,  46,  70,  71,  72},
+        {  25,  26,  45,  47,  72,  73},
+        {  26,  27,  46,  48,  73,  74},
+        {  27,  28,  47,  49,  74,  75},
+        {  28,  48,  50,  75,  76,  77},
+        {  28,  29,  49,  51,  77,  78},
+        {  29,  30,  50,  52,  78,  79},
+        {  30,  31,  51,  53,  79,  80},
+        {  31,  52,  54,  80,  81,  82},
+        {  31,  32,  53,  55,  82,  83},
+        {  32,  33,  54,  56,  83,  84},
+        {  33,  34,  55,  57,  84,  85},
+        {  34,  56,  58,  85,  86,  87},
+        {  34,  35,  57,  59,  87,  88},
+        {  35,  36,  58,  60,  88,  89},
+        {  19,  36,  37,  59,  89,  90}, // 60
+        {  37,  62,  90,  91,  92, 126},
+        {  37,  38,  61,  63,  92,  93},
+        {  38,  39,  62,  64,  93,  94},
+        {  39,  40,  63,  65,  94,  95},
+        {  40,  41,  64,  66,  95,  96},
+        {  41,  65,  67,  96,  97,  98},
+        {  41,  42,  66,  68,  98,  99},
+        {  42,  43,  67,  69,  99, 100},
+        {  43,  44,  68,  70, 100, 101},
+        {  44,  45,  69,  71, 101, 102},
+        {  45,  70,  72, 102, 103, 104},
+        {  45,  46,  71,  73, 104, 105},
+        {  46,  47,  72,  74, 105, 106},
+        {  47,  48,  73,  75, 106, 107},
+        {  48,  49,  74,  76, 107, 108},
+        {  49,  75,  77, 108, 109, 110},
+        {  49,  50,  76,  78, 110, 111},
+        {  50,  51,  77,  79, 111, 112},
+        {  51,  52,  78,  80, 112, 113},
+        {  52,  53,  79,  81, 113, 114}, // 80
+        {  53,  80,  82, 114, 115, 116},
+        {  53,  54,  81,  83, 116, 117},
+        {  54,  55,  82,  84, 117, 118},
+        {  55,  56,  83,  85, 118, 119},
+        {  56,  57,  84,  86, 119, 120},
+        {  57,  85,  87, 120, 121, 122},
+        {  57,  58,  86,  88, 122, 123},
+        {  58,  59,  87,  89, 123, 124},
+        {  59,  60,  88,  90, 124, 125},
+        {  37,  60,  61,  89, 125, 126},
+        {  61,  92, 126, 127, 128, 168},
+        {  61,  62,  91,  93, 128, 129},
+        {  62,  63,  92,  94, 129, 130},
+        {  63,  64,  93,  95, 130, 131},
+        {  64,  65,  94,  96, 131, 132},
+        {  65,  66,  95,  97, 132, 133},
+        {  66,  96,  98, 133, 134, 135},
+        {  66,  67,  97,  99, 135, 136},
+        {  67,  68,  98, 100, 136, 137},
+        {  68,  69,  99, 101, 137, 138}, // 100
+        {  69,  70, 100, 102, 138, 139},
+        {  70,  71, 101, 103, 139, 140},
+        {  71, 102, 104, 140, 141, 142},
+        {  71,  72, 103, 105, 142, 143},
+        {  72,  73, 104, 106, 143, 144},
+        {  73,  74, 105, 107, 144, 145},
+        {  74,  75, 106, 108, 145, 146},
+        {  75,  76, 107, 109, 146, 147},
+        {  76, 108, 110, 147, 148, 149},
+        {  76,  77, 109, 111, 149, 150},
+        {  77,  78, 110, 112, 150, 151},
+        {  78,  79, 111, 113, 151, 152},
+        {  79,  80, 112, 114, 152, 153},
+        {  80,  81, 113, 115, 153, 154},
+        {  81, 114, 116, 154, 155, 156},
+        {  81,  82, 115, 117, 156, 157},
+        {  82,  83, 116, 118, 157, 158},
+        {  83,  84, 117, 119, 158, 159},
+        {  84,  85, 118, 120, 159, 160},
+        {  85,  86, 119, 121, 160, 161}, // 120
+        {  86, 120, 122, 161, 162, 163},
+        {  86,  87, 121, 123, 163, 164},
+        {  87,  88, 122, 124, 164, 165},
+        {  88,  89, 123, 125, 165, 166},
+        {  89,  90, 124, 126, 166, 167},
+        {  61,  90,  91, 125, 167, 168},
+        {  91, 128, 168, 169, 170, 216},
+        {  91,  92, 127, 129, 170, 171},
+        {  92,  93, 128, 130, 171, 172},
+        {  93,  94, 129, 131, 172, 173},
+        {  94,  95, 130, 132, 173, 174},
+        {  95,  96, 131, 133, 174, 175},
+        {  96,  97, 132, 134, 175, 176},
+        {  97, 133, 135, 176, 177, 178},
+        {  97,  98, 134, 136, 178, 179},
+        {  98,  99, 135, 137, 179, 180},
+        {  99, 100, 136, 138, 180, 181},
+        { 100, 101, 137, 139, 181, 182},
+        { 101, 102, 138, 140, 182, 183},
+        { 102, 103, 139, 141, 183, 184}, // 140
+        { 103, 140, 142, 184, 185, 186},
+        { 103, 104, 141, 143, 186, 187},
+        { 104, 105, 142, 144, 187, 188},
+        { 105, 106, 143, 145, 188, 189},
+        { 106, 107, 144, 146, 189, 190},
+        { 107, 108, 145, 147, 190, 191},
+        { 108, 109, 146, 148, 191, 192},
+        { 109, 147, 149, 192, 193, 194},
+        { 109, 110, 148, 150, 194, 195},
+        { 110, 111, 149, 151, 195, 196},
+        { 111, 112, 150, 152, 196, 197},
+        { 112, 113, 151, 153, 197, 198},
+        { 113, 114, 152, 154, 198, 199},
+        { 114, 115, 153, 155, 199, 200},
+        { 115, 154, 156, 200, 201, 202},
+        { 115, 116, 155, 157, 202, 203},
+        { 116, 117, 156, 158, 203, 204},
+        { 117, 118, 157, 159, 204, 205},
+        { 118, 119, 158, 160, 205, 206},
+        { 119, 120, 159, 161, 206, 207}, // 160
+        { 120, 121, 160, 162, 207, 208},
+        { 121, 161, 163, 208, 209, 210},
+        { 121, 122, 162, 164, 210, 211},
+        { 122, 123, 163, 165, 211, 212},
+        { 123, 124, 164, 166, 212, 213},
+        { 124, 125, 165, 167, 213, 214},
+        { 125, 126, 166, 168, 214, 215},
+        {  91, 126, 127, 167, 215, 216},
+        { 127, 170, 216, 217, 218, 270},
+        { 127, 128, 169, 171, 218, 219},
+        { 128, 129, 170, 172, 219, 220},
+        { 129, 130, 171, 173, 220, 221},
+        { 130, 131, 172, 174, 221, 222},
+        { 131, 132, 173, 175, 222, 223},
+        { 132, 133, 174, 176, 223, 224},
+        { 133, 134, 175, 177, 224, 225},
+        { 134, 176, 178, 225, 226, 227},
+        { 134, 135, 177, 179, 227, 228},
+        { 135, 136, 178, 180, 228, 229},
+        { 136, 137, 179, 181, 229, 230}, // 180
+        { 137, 138, 180, 182, 230, 231},
+        { 138, 139, 181, 183, 231, 232},
+        { 139, 140, 182, 184, 232, 233},
+        { 140, 141, 183, 185, 233, 234},
+        { 141, 184, 186, 234, 235, 236},
+        { 141, 142, 185, 187, 236, 237},
+        { 142, 143, 186, 188, 237, 238},
+        { 143, 144, 187, 189, 238, 239},
+        { 144, 145, 188, 190, 239, 240},
+        { 145, 146, 189, 191, 240, 241},
+        { 146, 147, 190, 192, 241, 242},
+        { 147, 148, 191, 193, 242, 243},
+        { 148, 192, 194, 243, 244, 245},
+        { 148, 149, 193, 195, 245, 246},
+        { 149, 150, 194, 196, 246, 247},
+        { 150, 151, 195, 197, 247, 248},
+        { 151, 152, 196, 198, 248, 249},
+        { 152, 153, 197, 199, 249, 250},
+        { 153, 154, 198, 200, 250, 251},
+        { 154, 155, 199, 201, 251, 252}, // 200
+        { 155, 200, 202, 252, 253, 254},
+        { 155, 156, 201, 203, 254, 255},
+        { 156, 157, 202, 204, 255, 256},
+        { 157, 158, 203, 205, 256, 257},
+        { 158, 159, 204, 206, 257, 258},
+        { 159, 160, 205, 207, 258, 259},
+        { 160, 161, 206, 208, 259, 260},
+        { 161, 162, 207, 209, 260, 261},
+        { 162, 208, 210, 261, 262, 263},
+        { 162, 163, 209, 211, 263, 264},
+        { 163, 164, 210, 212, 264, 265},
+        { 164, 165, 211, 213, 265, 266},
+        { 165, 166, 212, 214, 266, 267},
+        { 166, 167, 213, 215, 267, 268},
+        { 167, 168, 214, 216, 268, 269},
+        { 127, 168, 169, 215, 269, 270},
+        { 169, 218, 270, 271, 272, 330},
+        { 169, 170, 217, 219, 272, 273},
+        { 170, 171, 218, 220, 273, 274},
+        { 171, 172, 219, 221, 274, 275}, // 220
+        { 172, 173, 220, 222, 275, 276},
+        { 173, 174, 221, 223, 276, 277},
+        { 174, 175, 222, 224, 277, 278},
+        { 175, 176, 223, 225, 278, 279},
+        { 176, 177, 224, 226, 279, 280},
+        { 177, 225, 227, 280, 281, 282},
+        { 177, 178, 226, 228, 282, 283},
+        { 178, 179, 227, 229, 283, 284},
+        { 179, 180, 228, 230, 284, 285},
+        { 180, 181, 229, 231, 285, 286},
+        { 181, 182, 230, 232, 286, 287},
+        { 182, 183, 231, 233, 287, 288},
+        { 183, 184, 232, 234, 288, 289},
+        { 184, 185, 233, 235, 289, 290},
+        { 185, 234, 236, 290, 291, 292},
+        { 185, 186, 235, 237, 292, 293},
+        { 186, 187, 236, 238, 293, 294},
+        { 187, 188, 237, 239, 294, 295},
+        { 188, 189, 238, 240, 295, 296},
+        { 189, 190, 239, 241, 296, 297}, // 240
+        { 190, 191, 240, 242, 297, 298},
+        { 191, 192, 241, 243, 298, 299},
+        { 192, 193, 242, 244, 299, 300},
+        { 193, 243, 245, 300, 301, 302},
+        { 193, 194, 244, 246, 302, 303},
+        { 194, 195, 245, 247, 303, 304},
+        { 195, 196, 246, 248, 304, 305},
+        { 196, 197, 247, 249, 305, 306},
+        { 197, 198, 248, 250, 306, 307},
+        { 198, 199, 249, 251, 307, 308},
+        { 199, 200, 250, 252, 308, 309},
+        { 200, 201, 251, 253, 309, 310},
+        { 201, 252, 254, 310, 311, 312},
+        { 201, 202, 253, 255, 312, 313},
+        { 202, 203, 254, 256, 313, 314},
+        { 203, 204, 255, 257, 314, 315},
+        { 204, 205, 256, 258, 315, 316},
+        { 205, 206, 257, 259, 316, 317},
+        { 206, 207, 258, 260, 317, 318},
+        { 207, 208, 259, 261, 318, 319}, // 260
+        { 208, 209, 260, 262, 319, 320},
+        { 209, 261, 263, 320, 321, 322},
+        { 209, 210, 262, 264, 322, 323},
+        { 210, 211, 263, 265, 323, 324},
+        { 211, 212, 264, 266, 324, 325},
+        { 212, 213, 265, 267, 325, 326},
+        { 213, 214, 266, 268, 326, 327},
+        { 214, 215, 267, 269, 327, 328},
+        { 215, 216, 268, 270, 328, 329},
+        { 169, 216, 217, 269, 329, 330},
+        { 217, 272, 330, 331, 332, 396},
+        { 217, 218, 271, 273, 332, 333},
+        { 218, 219, 272, 274, 333, 334},
+        { 219, 220, 273, 275, 334, 335},
+        { 220, 221, 274, 276, 335, 336},
+        { 221, 222, 275, 277, 336, 337},
+        { 222, 223, 276, 278, 337, 338},
+        { 223, 224, 277, 279, 338, 339},
+        { 224, 225, 278, 280, 339, 340},
+        { 225, 226, 279, 281, 340, 341}, // 280
+        { 226, 280, 282, 341, 342, 343},
+        { 226, 227, 281, 283, 343, 344},
+        { 227, 228, 282, 284, 344, 345},
+        { 228, 229, 283, 285, 345, 346},
+        { 229, 230, 284, 286, 346, 347},
+        { 230, 231, 285, 287, 347, 348},
+        { 231, 232, 286, 288, 348, 349},
+        { 232, 233, 287, 289, 349, 350},
+        { 233, 234, 288, 290, 350, 351},
+        { 234, 235, 289, 291, 351, 352},
+        { 235, 290, 292, 352, 353, 354},
+        { 235, 236, 291, 293, 354, 355},
+        { 236, 237, 292, 294, 355, 356},
+        { 237, 238, 293, 295, 356, 357},
+        { 238, 239, 294, 296, 357, 358},
+        { 239, 240, 295, 297, 358, 359},
+        { 240, 241, 296, 298, 359, 360},
+        { 241, 242, 297, 299, 360, 361},
+        { 242, 243, 298, 300, 361, 362},
+        { 243, 244, 299, 301, 362, 363}, // 300
+        { 244, 300, 302, 363, 364, 365},
+        { 244, 245, 301, 303, 365, 366},
+        { 245, 246, 302, 304, 366, 367},
+        { 246, 247, 303, 305, 367, 368},
+        { 247, 248, 304, 306, 368, 369},
+        { 248, 249, 305, 307, 369, 370},
+        { 249, 250, 306, 308, 370, 371},
+        { 250, 251, 307, 309, 371, 372},
+        { 251, 252, 308, 310, 372, 373},
+        { 252, 253, 309, 311, 373, 374},
+        { 253, 310, 312, 374, 375, 376},
+        { 253, 254, 311, 313, 376, 377},
+        { 254, 255, 312, 314, 377, 378},
+        { 255, 256, 313, 315, 378, 379},
+        { 256, 257, 314, 316, 379, 380},
+        { 257, 258, 315, 317, 380, 381},
+        { 258, 259, 316, 318, 381, 382},
+        { 259, 260, 317, 319, 382, 383},
+        { 260, 261, 318, 320, 383, 384},
+        { 261, 262, 319, 321, 384, 385}, // 320
+        { 262, 320, 322, 385, 386, 387},
+        { 262, 263, 321, 323, 387, 388},
+        { 263, 264, 322, 324, 388, 389},
+        { 264, 265, 323, 325, 389, 390},
+        { 265, 266, 324, 326, 390, 391},
+        { 266, 267, 325, 327, 391, 392},
+        { 267, 268, 326, 328, 392, 393},
+        { 268, 269, 327, 329, 393, 394},
+        { 269, 270, 328, 330, 394, 395},
+        { 217, 270, 271, 329, 395, 396},
+        { 271, 332, 396, 397, 432,  -1},
+        { 271, 272, 331, 333, 397,  -1},
+        { 272, 273, 332, 334, 398,  -1},
+        { 273, 274, 333, 335, 398,  -1},
+        { 274, 275, 334, 336, 399,  -1},
+        { 275, 276, 335, 337, 399,  -1},
+        { 276, 277, 336, 338, 400,  -1},
+        { 277, 278, 337, 339, 400,  -1},
+        { 278, 279, 338, 340, 401,  -1},
+        { 279, 280, 339, 341, 401,  -1}, // 340
+        { 280, 281, 340, 342, 402,  -1},
+        { 281, 341, 343, 402, 403,  -1},
+        { 281, 282, 342, 344, 403,  -1},
+        { 282, 283, 343, 345, 404,  -1},
+        { 283, 284, 344, 346, 404,  -1},
+        { 284, 285, 345, 347, 405,  -1},
+        { 285, 286, 346, 348, 405,  -1},
+        { 286, 287, 347, 349, 406,  -1},
+        { 287, 288, 348, 350, 406,  -1},
+        { 288, 289, 349, 351, 407,  -1},
+        { 289, 290, 350, 352, 407,  -1},
+        { 290, 291, 351, 353, 408,  -1},
+        { 291, 352, 354, 408, 409,  -1},
+        { 291, 292, 353, 355, 409,  -1},
+        { 292, 293, 354, 356, 410,  -1},
+        { 293, 294, 355, 357, 410,  -1},
+        { 294, 295, 356, 358, 411,  -1},
+        { 295, 296, 357, 359, 411,  -1},
+        { 296, 297, 358, 360, 412,  -1},
+        { 297, 298, 359, 361, 412,  -1}, // 360
+        { 298, 299, 360, 362, 413,  -1},
+        { 299, 300, 361, 363, 413,  -1},
+        { 300, 301, 362, 364, 414,  -1},
+        { 301, 363, 365, 414, 415,  -1},
+        { 301, 302, 364, 366, 415,  -1},
+        { 302, 303, 365, 367, 416,  -1},
+        { 303, 304, 366, 368, 416,  -1},
+        { 304, 305, 367, 369, 417,  -1},
+        { 305, 306, 368, 370, 417,  -1},
+        { 306, 307, 369, 371, 418,  -1},
+        { 307, 308, 370, 372, 418,  -1},
+        { 308, 309, 371, 373, 419,  -1},
+        { 309, 310, 372, 374, 419,  -1},
+        { 310, 311, 373, 375, 420,  -1},
+        { 311, 374, 376, 420, 421,  -1},
+        { 311, 312, 375, 377, 421,  -1},
+        { 312, 313, 376, 378, 422,  -1},
+        { 313, 314, 377, 379, 422,  -1},
+        { 314, 315, 378, 380, 423,  -1},
+        { 315, 316, 379, 381, 423,  -1}, // 380
+        { 316, 317, 380, 382, 424,  -1},
+        { 317, 318, 381, 383, 424,  -1},
+        { 318, 319, 382, 384, 425,  -1},
+        { 319, 320, 383, 385, 425,  -1},
+        { 320, 321, 384, 386, 426,  -1},
+        { 321, 385, 387, 426, 427,  -1},
+        { 321, 322, 386, 388, 427,  -1},
+        { 322, 323, 387, 389, 428,  -1},
+        { 323, 324, 388, 390, 428,  -1},
+        { 324, 325, 389, 391, 429,  -1},
+        { 325, 326, 390, 392, 429,  -1},
+        { 326, 327, 391, 393, 430,  -1},
+        { 327, 328, 392, 394, 430,  -1},
+        { 328, 329, 393, 395, 431,  -1},
+        { 329, 330, 394, 396, 431,  -1},
+        { 271, 330, 331, 395, 432,  -1},
+        { 331, 332, 398, 432, 433, 434},
+        { 333, 334, 397, 399, 434, 435},
+        { 335, 336, 398, 400, 435, 436},
+        { 337, 338, 399, 401, 436, 437}, // 400
+        { 339, 340, 400, 402, 437, 438},
+        { 341, 342, 401, 403, 438, 439},
+        { 342, 343, 402, 404, 440, 441},
+        { 344, 345, 403, 405, 441, 442},
+        { 346, 347, 404, 406, 442, 443},
+        { 348, 349, 405, 407, 443, 444},
+        { 350, 351, 406, 408, 444, 445},
+        { 352, 353, 407, 409, 445, 446},
+        { 353, 354, 408, 410, 447, 448},
+        { 355, 356, 409, 411, 448, 449},
+        { 357, 358, 410, 412, 449, 450},
+        { 359, 360, 411, 413, 450, 451},
+        { 361, 362, 412, 414, 451, 452},
+        { 363, 364, 413, 415, 452, 453},
+        { 364, 365, 414, 416, 454, 455},
+        { 366, 367, 415, 417, 455, 456},
+        { 368, 369, 416, 418, 456, 457},
+        { 370, 371, 417, 419, 457, 458},
+        { 372, 373, 418, 420, 458, 459},
+        { 374, 375, 419, 421, 459, 460}, // 420
+        { 375, 376, 420, 422, 461, 462},
+        { 377, 378, 421, 423, 462, 463},
+        { 379, 380, 422, 424, 463, 464},
+        { 381, 382, 423, 425, 464, 465},
+        { 383, 384, 424, 426, 465, 466},
+        { 385, 386, 425, 427, 466, 467},
+        { 386, 387, 426, 428, 468, 469},
+        { 388, 389, 427, 429, 469, 470},
+        { 390, 391, 428, 430, 470, 471},
+        { 392, 393, 429, 431, 471, 472},
+        { 394, 395, 430, 432, 472, 473},
+        { 331, 396, 397, 431, 473, 474},
+        { 397, 434, 474, 475, 476,  -1},
+        { 397, 398, 433, 435, 476, 477},
+        { 398, 399, 434, 436, 477, 478},
+        { 399, 400, 435, 437, 478, 479},
+        { 400, 401, 436, 438, 479, 480},
+        { 401, 402, 437, 439, 480, 481},
+        { 402, 438, 440, 481, 482,  -1},
+        { 403, 439, 441, 483, 484,  -1}, // 440
+        { 403, 404, 440, 442, 484, 485},
+        { 404, 405, 441, 443, 485, 486},
+        { 405, 406, 442, 444, 486, 487},
+        { 406, 407, 443, 445, 487, 488},
+        { 407, 408, 444, 446, 488, 489},
+        { 408, 445, 447, 489, 490,  -1},
+        { 409, 446, 448, 491, 492,  -1},
+        { 409, 410, 447, 449, 492, 493},
+        { 410, 411, 448, 450, 493, 494},
+        { 411, 412, 449, 451, 494, 495},
+        { 412, 413, 450, 452, 495, 496},
+        { 413, 414, 451, 453, 496, 497},
+        { 414, 452, 454, 497, 498,  -1},
+        { 415, 453, 455, 499, 500,  -1},
+        { 415, 416, 454, 456, 500, 501},
+        { 416, 417, 455, 457, 501, 502},
+        { 417, 418, 456, 458, 502, 503},
+        { 418, 419, 457, 459, 503, 504},
+        { 419, 420, 458, 460, 504, 505},
+        { 420, 459, 461, 505, 506,  -1}, // 460
+        { 421, 460, 462, 507, 508,  -1},
+        { 421, 422, 461, 463, 508, 509},
+        { 422, 423, 462, 464, 509, 510},
+        { 423, 424, 463, 465, 510, 511},
+        { 424, 425, 464, 466, 511, 512},
+        { 425, 426, 465, 467, 512, 513},
+        { 426, 466, 468, 513, 514,  -1},
+        { 427, 467, 469, 515, 516,  -1},
+        { 427, 428, 468, 470, 516, 517},
+        { 428, 429, 469, 471, 517, 518},
+        { 429, 430, 470, 472, 518, 519},
+        { 430, 431, 471, 473, 519, 520},
+        { 431, 432, 472, 474, 520, 521},
+        { 432, 433, 473, 521, 522,  -1},
+        { 433, 476, 522, 523, 524,  -1},
+        { 433, 434, 475, 477, 524, 525},
+        { 434, 435, 476, 478, 525, 526},
+        { 435, 436, 477, 479, 526, 527},
+        { 436, 437, 478, 480, 527, 528},
+        { 437, 438, 479, 481, 528, 529}, // 480
+        { 438, 439, 480, 482, 529, 530},
+        { 439, 481, 483, 530, 531,  -1},
+        { 440, 482, 484, 532, 533,  -1},
+        { 440, 441, 483, 485, 533, 534},
+        { 441, 442, 484, 486, 534, 535},
+        { 442, 443, 485, 487, 535, 536},
+        { 443, 444, 486, 488, 536, 537},
+        { 444, 445, 487, 489, 537, 538},
+        { 445, 446, 488, 490, 538, 539},
+        { 446, 489, 491, 539, 540,  -1},
+        { 447, 490, 492, 541, 542,  -1},
+        { 447, 448, 491, 493, 542, 543},
+        { 448, 449, 492, 494, 543, 544},
+        { 449, 450, 493, 495, 544, 545},
+        { 450, 451, 494, 496, 545, 546},
+        { 451, 452, 495, 497, 546, 547},
+        { 452, 453, 496, 498, 547, 548},
+        { 453, 497, 499, 548, 549,  -1},
+        { 454, 498, 500, 550, 551,  -1},
+        { 454, 455, 499, 501, 551, 552}, // 500
+        { 455, 456, 500, 502, 552, 553},
+        { 456, 457, 501, 503, 553, 554},
+        { 457, 458, 502, 504, 554, 555},
+        { 458, 459, 503, 505, 555, 556},
+        { 459, 460, 504, 506, 556, 557},
+        { 460, 505, 507, 557, 558,  -1},
+        { 461, 506, 508, 559, 560,  -1},
+        { 461, 462, 507, 509, 560, 561},
+        { 462, 463, 508, 510, 561, 562},
+        { 463, 464, 509, 511, 562, 563},
+        { 464, 465, 510, 512, 563, 564},
+        { 465, 466, 511, 513, 564, 565},
+        { 466, 467, 512, 514, 565, 566},
+        { 467, 513, 515, 566, 567,  -1},
+        { 468, 514, 516, 568, 569,  -1},
+        { 468, 469, 515, 517, 569, 570},
+        { 469, 470, 516, 518, 570, 571},
+        { 470, 471, 517, 519, 571, 572},
+        { 471, 472, 518, 520, 572, 573},
+        { 472, 473, 519, 521, 573, 574}, // 520
+        { 473, 474, 520, 522, 574, 575},
+        { 474, 475, 521, 575, 576,  -1},
+        { 475, 524, 576,  -1,  -1,  -1},
+        { 475, 476, 523, 525,  -1,  -1},
+        { 476, 477, 524, 526,  -1,  -1},
+        { 477, 478, 525, 527,  -1,  -1},
+        { 478, 479, 526, 528,  -1,  -1},
+        { 479, 480, 527, 529,  -1,  -1},
+        { 480, 481, 528, 530,  -1,  -1},
+        { 481, 482, 529, 531,  -1,  -1},
+        { 482, 530, 532,  -1,  -1,  -1},
+        { 483, 531, 533,  -1,  -1,  -1},
+        { 483, 484, 532, 534,  -1,  -1},
+        { 484, 485, 533, 535,  -1,  -1},
+        { 485, 486, 534, 536,  -1,  -1},
+        { 486, 487, 535, 537,  -1,  -1},
+        { 487, 488, 536, 538,  -1,  -1},
+        { 488, 489, 537, 539,  -1,  -1},
+        { 489, 490, 538, 540,  -1,  -1},
+        { 490, 539, 541,  -1,  -1,  -1}, // 540
+        { 491, 540, 542,  -1,  -1,  -1},
+        { 491, 492, 541, 543,  -1,  -1},
+        { 492, 493, 542, 544,  -1,  -1},
+        { 493, 494, 543, 545,  -1,  -1},
+        { 494, 495, 544, 546,  -1,  -1},
+        { 495, 496, 545, 547,  -1,  -1},
+        { 496, 497, 546, 548,  -1,  -1},
+        { 497, 498, 547, 549,  -1,  -1},
+        { 498, 548, 550,  -1,  -1,  -1},
+        { 499, 549, 551,  -1,  -1,  -1},
+        { 499, 500, 550, 552,  -1,  -1},
+        { 500, 501, 551, 553,  -1,  -1},
+        { 501, 502, 552, 554,  -1,  -1},
+        { 502, 503, 553, 555,  -1,  -1},
+        { 503, 504, 554, 556,  -1,  -1},
+        { 504, 505, 555, 557,  -1,  -1},
+        { 505, 506, 556, 558,  -1,  -1},
+        { 506, 557, 559,  -1,  -1,  -1},
+        { 507, 558, 560,  -1,  -1,  -1},
+        { 507, 508, 559, 561,  -1,  -1}, // 560
+        { 508, 509, 560, 562,  -1,  -1},
+        { 509, 510, 561, 563,  -1,  -1},
+        { 510, 511, 562, 564,  -1,  -1},
+        { 511, 512, 563, 565,  -1,  -1},
+        { 512, 513, 564, 566,  -1,  -1},
+        { 513, 514, 565, 567,  -1,  -1},
+        { 514, 566, 568,  -1,  -1,  -1},
+        { 515, 567, 569,  -1,  -1,  -1},
+        { 515, 516, 568, 570,  -1,  -1},
+        { 516, 517, 569, 571,  -1,  -1}, // 570
+        { 517, 518, 570, 572,  -1,  -1},
+        { 518, 519, 571, 573,  -1,  -1},
+        { 519, 520, 572, 574,  -1,  -1},
+        { 520, 521, 573, 575,  -1,  -1},
+        { 521, 522, 574, 576,  -1,  -1},
+        { 522, 523, 575,  -1,  -1,  -1}  // 576
+    };
+
+  for (Int_t i=0; i<577; i++)
+      (*this)[i].SetNeighbors(nn[i][0], nn[i][1], nn[i][2],
+                              nn[i][3], nn[i][4], nn[i][5]);
+}
Index: /tags/Mars-V0.9/mgeom/MGeomCamECO1000.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamECO1000.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamECO1000.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MGeomCamECO1000
+#define MARS_MGeomCamECO1000
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamECO1000 : public MGeomCam
+{
+private:
+    void CreateCam();
+    void CreateNN();
+
+public:
+    MGeomCamECO1000(const char *name=NULL);
+
+    ClassDef(MGeomCamECO1000, 1) // Geometry class for the ECO1000 camera
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgeom/MGeomCamECO1000HG.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamECO1000HG.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamECO1000HG.cc	(revision 9772)
@@ -0,0 +1,3408 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamECO1000HG
+//
+// This class stores the geometry information of the Magic camera.
+// All information are copied from tables, see source code.
+//
+////////////////////////////////////////////////////////////////////////////
+
+#include "MGeomCamECO1000HG.h"
+
+#include "TCanvas.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamECO1000HG);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Magic camera has 577 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamECO1000HG::MGeomCamECO1000HG(const char *name)
+    : MGeomCam(2401, 34.5, name, "Geometry information of ECO1000 HG Camera")
+{
+    CreateCam();
+    CreateNN();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information from a table into the pixel objects.
+//
+void MGeomCamECO1000HG::CreateCam()
+{
+    //
+    //   here define the hardwire things of the ECO 1000 telescope
+    //
+
+
+    //
+    //   fill the pixels list with this data
+    //
+const float xtemp[2401] = {
+  0, 30, 15, -15, -30, -15, 15, 60, // 0
+  45, 30, 0, -30, -45, -60, -45, -30, // 8
+  0, 30, 45, 90, 75, 60, 45, 15, // 16
+  -15, -45, -60, -75, -90, -75, -60, -45, // 24
+  -15, 15, 45, 60, 75, 120, 105, 90, // 32
+  75, 60, 30, 0, -30, -60, -75, -90, // 40
+  -105, -120, -105, -90, -75, -60, -30, 0, // 48
+  30, 60, 75, 90, 105, 150, 135, 120, // 56
+  105, 90, 75, 45, 15, -15, -45, -75, // 64
+  -90, -105, -120, -135, -150, -135, -120, -105, // 72
+  -90, -75, -45, -15, 15, 45, 75, 90, // 80
+  105, 120, 135, 180, 165, 150, 135, 120, // 88
+  105, 90, 60, 30, 0, -30, -60, -90, // 96
+  -105, -120, -135, -150, -165, -180, -165, -150, // 104
+  -135, -120, -105, -90, -60, -30, 0, 30, // 112
+  60, 90, 105, 120, 135, 150, 165, 210, // 120
+  195, 180, 165, 150, 135, 120, 105, 75, // 128
+  45, 15, -15, -45, -75, -105, -120, -135, // 136
+  -150, -165, -180, -195, -210, -195, -180, -165, // 144
+  -150, -135, -120, -105, -75, -45, -15, 15, // 152
+  45, 75, 105, 120, 135, 150, 165, 180, // 160
+  195, 240, 225, 210, 195, 180, 165, 150, // 168
+  135, 120, 90, 60, 30, 0, -30, -60, // 176
+  -90, -120, -135, -150, -165, -180, -195, -210, // 184
+  -225, -240, -225, -210, -195, -180, -165, -150, // 192
+  -135, -120, -90, -60, -30, 0, 30, 60, // 200
+  90, 120, 135, 150, 165, 180, 195, 210, // 208
+  225, 270, 255, 240, 225, 210, 195, 180, // 216
+  165, 150, 135, 105, 75, 45, 15, -15, // 224
+  -45, -75, -105, -135, -150, -165, -180, -195, // 232
+  -210, -225, -240, -255, -270, -255, -240, -225, // 240
+  -210, -195, -180, -165, -150, -135, -105, -75, // 248
+  -45, -15, 15, 45, 75, 105, 135, 150, // 256
+  165, 180, 195, 210, 225, 240, 255, 300, // 264
+  285, 270, 255, 240, 225, 210, 195, 180, // 272
+  165, 150, 120, 90, 60, 30, 0, -30, // 280
+  -60, -90, -120, -150, -165, -180, -195, -210, // 288
+  -225, -240, -255, -270, -285, -300, -285, -270, // 296
+  -255, -240, -225, -210, -195, -180, -165, -150, // 304
+  -120, -90, -60, -30, 0, 30, 60, 90, // 312
+  120, 150, 165, 180, 195, 210, 225, 240, // 320
+  255, 270, 285, 330, 315, 300, 285, 270, // 328
+  255, 240, 225, 210, 195, 180, 165, 135, // 336
+  105, 75, 45, 15, -15, -45, -75, -105, // 344
+  -135, -165, -180, -195, -210, -225, -240, -255, // 352
+  -270, -285, -300, -315, -330, -315, -300, -285, // 360
+  -270, -255, -240, -225, -210, -195, -180, -165, // 368
+  -135, -105, -75, -45, -15, 15, 45, 75, // 376
+  105, 135, 165, 180, 195, 210, 225, 240, // 384
+  255, 270, 285, 300, 315, 360, 345, 330, // 392
+  315, 300, 285, 270, 255, 240, 225, 210, // 400
+  195, 180, 150, 120, 90, 60, 30, 0, // 408
+  -30, -60, -90, -120, -150, -180, -195, -210, // 416
+  -225, -240, -255, -270, -285, -300, -315, -330, // 424
+  -345, -360, -345, -330, -315, -300, -285, -270, // 432
+  -255, -240, -225, -210, -195, -180, -150, -120, // 440
+  -90, -60, -30, 0, 30, 60, 90, 120, // 448
+  150, 180, 195, 210, 225, 240, 255, 270, // 456
+  285, 300, 315, 330, 345, 390, 375, 360, // 464
+  345, 330, 315, 300, 285, 270, 255, 240, // 472
+  225, 210, 195, 165, 135, 105, 75, 45, // 480
+  15, -15, -45, -75, -105, -135, -165, -195, // 488
+  -210, -225, -240, -255, -270, -285, -300, -315, // 496
+  -330, -345, -360, -375, -390, -375, -360, -345, // 504
+  -330, -315, -300, -285, -270, -255, -240, -225, // 512
+  -210, -195, -165, -135, -105, -75, -45, -15, // 520
+  15, 45, 75, 105, 135, 165, 195, 210, // 528
+  225, 240, 255, 270, 285, 300, 315, 330, // 536
+  345, 360, 375, 420, 405, 390, 375, 360, // 544
+  345, 330, 315, 300, 285, 270, 255, 240, // 552
+  225, 210, 180, 150, 120, 90, 60, 30, // 560
+  0, -30, -60, -90, -120, -150, -180, -210, // 568
+  -225, -240, -255, -270, -285, -300, -315, -330, // 576
+  -345, -360, -375, -390, -405, -420, -405, -390, // 584
+  -375, -360, -345, -330, -315, -300, -285, -270, // 592
+  -255, -240, -225, -210, -180, -150, -120, -90, // 600
+  -60, -30, 0, 30, 60, 90, 120, 150, // 608
+  180, 210, 225, 240, 255, 270, 285, 300, // 616
+  315, 330, 345, 360, 375, 390, 405, 450, // 624
+  435, 420, 405, 390, 375, 360, 345, 330, // 632
+  315, 300, 285, 270, 255, 240, 225, 195, // 640
+  165, 135, 105, 75, 45, 15, -15, -45, // 648
+  -75, -105, -135, -165, -195, -225, -240, -255, // 656
+  -270, -285, -300, -315, -330, -345, -360, -375, // 664
+  -390, -405, -420, -435, -450, -435, -420, -405, // 672
+  -390, -375, -360, -345, -330, -315, -300, -285, // 680
+  -270, -255, -240, -225, -195, -165, -135, -105, // 688
+  -75, -45, -15, 15, 45, 75, 105, 135, // 696
+  165, 195, 225, 240, 255, 270, 285, 300, // 704
+  315, 330, 345, 360, 375, 390, 405, 420, // 712
+  435, 480, 465, 450, 435, 420, 405, 390, // 720
+  375, 360, 345, 330, 315, 300, 285, 270, // 728
+  255, 240, 210, 180, 150, 120, 90, 60, // 736
+  30, 0, -30, -60, -90, -120, -150, -180, // 744
+  -210, -240, -255, -270, -285, -300, -315, -330, // 752
+  -345, -360, -375, -390, -405, -420, -435, -450, // 760
+  -465, -480, -465, -450, -435, -420, -405, -390, // 768
+  -375, -360, -345, -330, -315, -300, -285, -270, // 776
+  -255, -240, -210, -180, -150, -120, -90, -60, // 784
+  -30, 0, 30, 60, 90, 120, 150, 180, // 792
+  210, 240, 255, 270, 285, 300, 315, 330, // 800
+  345, 360, 375, 390, 405, 420, 435, 450, // 808
+  465, 510, 495, 480, 465, 450, 435, 420, // 816
+  405, 390, 375, 360, 345, 330, 315, 300, // 824
+  285, 270, 255, 225, 195, 165, 135, 105, // 832
+  75, 45, 15, -15, -45, -75, -105, -135, // 840
+  -165, -195, -225, -255, -270, -285, -300, -315, // 848
+  -330, -345, -360, -375, -390, -405, -420, -435, // 856
+  -450, -465, -480, -495, -510, -495, -480, -465, // 864
+  -450, -435, -420, -405, -390, -375, -360, -345, // 872
+  -330, -315, -300, -285, -270, -255, -225, -195, // 880
+  -165, -135, -105, -75, -45, -15, 15, 45, // 888
+  75, 105, 135, 165, 195, 225, 255, 270, // 896
+  285, 300, 315, 330, 345, 360, 375, 390, // 904
+  405, 420, 435, 450, 465, 480, 495, 540, // 912
+  525, 510, 495, 480, 465, 450, 435, 420, // 920
+  405, 390, 375, 360, 345, 330, 315, 300, // 928
+  285, 270, 240, 210, 180, 150, 120, 90, // 936
+  60, 30, 0, -30, -60, -90, -120, -150, // 944
+  -180, -210, -240, -270, -285, -300, -315, -330, // 952
+  -345, -360, -375, -390, -405, -420, -435, -450, // 960
+  -465, -480, -495, -510, -525, -540, -525, -510, // 968
+  -495, -480, -465, -450, -435, -420, -405, -390, // 976
+  -375, -360, -345, -330, -315, -300, -285, -270, // 984
+  -240, -210, -180, -150, -120, -90, -60, -30, // 992
+  0, 30, 60, 90, 120, 150, 180, 210, // 1000
+  240, 270, 285, 300, 315, 330, 345, 360, // 1008
+  375, 390, 405, 420, 435, 450, 465, 480, // 1016
+  495, 510, 525, 570, 555, 540, 525, 510, // 1024
+  495, 480, 465, 450, 435, 420, 405, 390, // 1032
+  375, 360, 345, 330, 315, 300, 285, 255, // 1040
+  225, 195, 165, 135, 105, 75, 45, 15, // 1048
+  -15, -45, -75, -105, -135, -165, -195, -225, // 1056
+  -255, -285, -300, -315, -330, -345, -360, -375, // 1064
+  -390, -405, -420, -435, -450, -465, -480, -495, // 1072
+  -510, -525, -540, -555, -570, -555, -540, -525, // 1080
+  -510, -495, -480, -465, -450, -435, -420, -405, // 1088
+  -390, -375, -360, -345, -330, -315, -300, -285, // 1096
+  -255, -225, -195, -165, -135, -105, -75, -45, // 1104
+  -15, 15, 45, 75, 105, 135, 165, 195, // 1112
+  225, 255, 285, 300, 315, 330, 345, 360, // 1120
+  375, 390, 405, 420, 435, 450, 465, 480, // 1128
+  495, 510, 525, 540, 555, 600, 585, 570, // 1136
+  555, 540, 525, 510, 495, 480, 465, 450, // 1144
+  435, 420, 405, 390, 375, 360, 345, 330, // 1152
+  315, 300, 270, 240, 210, 180, 150, 120, // 1160
+  90, 60, 30, 0, -30, -60, -90, -120, // 1168
+  -150, -180, -210, -240, -270, -300, -315, -330, // 1176
+  -345, -360, -375, -390, -405, -420, -435, -450, // 1184
+  -465, -480, -495, -510, -525, -540, -555, -570, // 1192
+  -585, -600, -585, -570, -555, -540, -525, -510, // 1200
+  -495, -480, -465, -450, -435, -420, -405, -390, // 1208
+  -375, -360, -345, -330, -315, -300, -270, -240, // 1216
+  -210, -180, -150, -120, -90, -60, -30, 0, // 1224
+  30, 60, 90, 120, 150, 180, 210, 240, // 1232
+  270, 300, 315, 330, 345, 360, 375, 390, // 1240
+  405, 420, 435, 450, 465, 480, 495, 510, // 1248
+  525, 540, 555, 570, 585, 630, 615, 600, // 1256
+  585, 570, 555, 540, 525, 510, 495, 480, // 1264
+  465, 450, 435, 420, 405, 390, 375, 360, // 1272
+  345, 330, 315, 285, 255, 225, 195, 165, // 1280
+  135, 105, 75, 45, 15, -15, -45, -75, // 1288
+  -105, -135, -165, -195, -225, -255, -285, -315, // 1296
+  -330, -345, -360, -375, -390, -405, -420, -435, // 1304
+  -450, -465, -480, -495, -510, -525, -540, -555, // 1312
+  -570, -585, -600, -615, -630, -615, -600, -585, // 1320
+  -570, -555, -540, -525, -510, -495, -480, -465, // 1328
+  -450, -435, -420, -405, -390, -375, -360, -345, // 1336
+  -330, -315, -285, -255, -225, -195, -165, -135, // 1344
+  -105, -75, -45, -15, 15, 45, 75, 105, // 1352
+  135, 165, 195, 225, 255, 285, 315, 330, // 1360
+  345, 360, 375, 390, 405, 420, 435, 450, // 1368
+  465, 480, 495, 510, 525, 540, 555, 570, // 1376
+  585, 600, 615, 660, 645, 630, 615, 600, // 1384
+  585, 570, 555, 540, 525, 510, 495, 480, // 1392
+  465, 450, 435, 420, 405, 390, 375, 360, // 1400
+  345, 330, 300, 270, 240, 210, 180, 150, // 1408
+  120, 90, 60, 30, 0, -30, -60, -90, // 1416
+  -120, -150, -180, -210, -240, -270, -300, -330, // 1424
+  -345, -360, -375, -390, -405, -420, -435, -450, // 1432
+  -465, -480, -495, -510, -525, -540, -555, -570, // 1440
+  -585, -600, -615, -630, -645, -660, -645, -630, // 1448
+  -615, -600, -585, -570, -555, -540, -525, -510, // 1456
+  -495, -480, -465, -450, -435, -420, -405, -390, // 1464
+  -375, -360, -345, -330, -300, -270, -240, -210, // 1472
+  -180, -150, -120, -90, -60, -30, 0, 30, // 1480
+  60, 90, 120, 150, 180, 210, 240, 270, // 1488
+  300, 330, 345, 360, 375, 390, 405, 420, // 1496
+  435, 450, 465, 480, 495, 510, 525, 540, // 1504
+  555, 570, 585, 600, 615, 630, 645, 690, // 1512
+  675, 660, 645, 630, 615, 600, 585, 570, // 1520
+  555, 540, 525, 510, 495, 480, 465, 450, // 1528
+  435, 420, 405, 390, 375, 360, 345, 315, // 1536
+  285, 255, 225, 195, 165, 135, 105, 75, // 1544
+  45, 15, -15, -45, -75, -105, -135, -165, // 1552
+  -195, -225, -255, -285, -315, -345, -360, -375, // 1560
+  -390, -405, -420, -435, -450, -465, -480, -495, // 1568
+  -510, -525, -540, -555, -570, -585, -600, -615, // 1576
+  -630, -645, -660, -675, -690, -675, -660, -645, // 1584
+  -630, -615, -600, -585, -570, -555, -540, -525, // 1592
+  -510, -495, -480, -465, -450, -435, -420, -405, // 1600
+  -390, -375, -360, -345, -315, -285, -255, -225, // 1608
+  -195, -165, -135, -105, -75, -45, -15, 15, // 1616
+  45, 75, 105, 135, 165, 195, 225, 255, // 1624
+  285, 315, 345, 360, 375, 390, 405, 420, // 1632
+  435, 450, 465, 480, 495, 510, 525, 540, // 1640
+  555, 570, 585, 600, 615, 630, 645, 660, // 1648
+  675, 720, 690, 660, 630, 600, 570, 540, // 1656
+  510, 480, 450, 420, 390, 330, 270, 210, // 1664
+  150, 90, 30, -30, -90, -150, -210, -270, // 1672
+  -330, -390, -420, -450, -480, -510, -540, -570, // 1680
+  -600, -630, -660, -690, -720, -720, -690, -660, // 1688
+  -630, -600, -570, -540, -510, -480, -450, -420, // 1696
+  -390, -330, -270, -210, -150, -90, -30, 30, // 1704
+  90, 150, 210, 270, 330, 390, 420, 450, // 1712
+  480, 510, 540, 570, 600, 630, 660, 690, // 1720
+  720, 780, 750, 720, 690, 660, 630, 600, // 1728
+  570, 540, 510, 480, 450, 420, 360, 300, // 1736
+  240, 180, 120, 60, 0, -60, -120, -180, // 1744
+  -240, -300, -360, -420, -450, -480, -510, -540, // 1752
+  -570, -600, -630, -660, -690, -720, -750, -780, // 1760
+  -780, -750, -720, -690, -660, -630, -600, -570, // 1768
+  -540, -510, -480, -450, -420, -360, -300, -240, // 1776
+  -180, -120, -60, 0, 60, 120, 180, 240, // 1784
+  300, 360, 420, 450, 480, 510, 540, 570, // 1792
+  600, 630, 660, 690, 720, 750, 780, 840, // 1800
+  810, 780, 750, 720, 690, 660, 630, 600, // 1808
+  570, 540, 510, 480, 450, 390, 330, 270, // 1816
+  210, 150, 90, 30, -30, -90, -150, -210, // 1824
+  -270, -330, -390, -450, -480, -510, -540, -570, // 1832
+  -600, -630, -660, -690, -720, -750, -780, -810, // 1840
+  -840, -840, -810, -780, -750, -720, -690, -660, // 1848
+  -630, -600, -570, -540, -510, -480, -450, -390, // 1856
+  -330, -270, -210, -150, -90, -30, 30, 90, // 1864
+  150, 210, 270, 330, 390, 450, 480, 510, // 1872
+  540, 570, 600, 630, 660, 690, 720, 750, // 1880
+  780, 810, 840, 900, 870, 840, 810, 780, // 1888
+  750, 720, 690, 660, 630, 600, 570, 540, // 1896
+  510, 480, 420, 360, 300, 240, 180, 120, // 1904
+  60, 0, -60, -120, -180, -240, -300, -360, // 1912
+  -420, -480, -510, -540, -570, -600, -630, -660, // 1920
+  -690, -720, -750, -780, -810, -840, -870, -900, // 1928
+  -900, -870, -840, -810, -780, -750, -720, -690, // 1936
+  -660, -630, -600, -570, -540, -510, -480, -420, // 1944
+  -360, -300, -240, -180, -120, -60, 0, 60, // 1952
+  120, 180, 240, 300, 360, 420, 480, 510, // 1960
+  540, 570, 600, 630, 660, 690, 720, 750, // 1968
+  780, 810, 840, 870, 900, 960, 930, 900, // 1976
+  870, 840, 810, 780, 750, 720, 690, 660, // 1984
+  630, 600, 570, 540, 510, 450, 390, 330, // 1992
+  270, 210, 150, 90, 30, -30, -90, -150, // 2000
+  -210, -270, -330, -390, -450, -510, -540, -570, // 2008
+  -600, -630, -660, -690, -720, -750, -780, -810, // 2016
+  -840, -870, -900, -930, -960, -960, -930, -900, // 2024
+  -870, -840, -810, -780, -750, -720, -690, -660, // 2032
+  -630, -600, -570, -540, -510, -450, -390, -330, // 2040
+  -270, -210, -150, -90, -30, 30, 90, 150, // 2048
+  210, 270, 330, 390, 450, 510, 540, 570, // 2056
+  600, 630, 660, 690, 720, 750, 780, 810, // 2064
+  840, 870, 900, 930, 960, 1020, 990, 960, // 2072
+  930, 900, 870, 840, 810, 780, 750, 720, // 2080
+  690, 660, 630, 600, 570, 540, 480, 420, // 2088
+  360, 300, 240, 180, 120, 60, 0, -60, // 2096
+  -120, -180, -240, -300, -360, -420, -480, -540, // 2104
+  -570, -600, -630, -660, -690, -720, -750, -780, // 2112
+  -810, -840, -870, -900, -930, -960, -990, -1020, // 2120
+  -1020, -990, -960, -930, -900, -870, -840, -810, // 2128
+  -780, -750, -720, -690, -660, -630, -600, -570, // 2136
+  -540, -480, -420, -360, -300, -240, -180, -120, // 2144
+  -60, 0, 60, 120, 180, 240, 300, 360, // 2152
+  420, 480, 540, 570, 600, 630, 660, 690, // 2160
+  720, 750, 780, 810, 840, 870, 900, 930, // 2168
+  960, 990, 1020, 1080, 1050, 1020, 990, 960, // 2176
+  930, 900, 870, 840, 810, 780, 750, 720, // 2184
+  690, 660, 630, 600, 570, 510, 450, 390, // 2192
+  330, 270, 210, 150, 90, 30, -30, -90, // 2200
+  -150, -210, -270, -330, -390, -450, -510, -570, // 2208
+  -600, -630, -660, -690, -720, -750, -780, -810, // 2216
+  -840, -870, -900, -930, -960, -990, -1020, -1050, // 2224
+  -1080, -1080, -1050, -1020, -990, -960, -930, -900, // 2232
+  -870, -840, -810, -780, -750, -720, -690, -660, // 2240
+  -630, -600, -570, -510, -450, -390, -330, -270, // 2248
+  -210, -150, -90, -30, 30, 90, 150, 210, // 2256
+  270, 330, 390, 450, 510, 570, 600, 630, // 2264
+  660, 690, 720, 750, 780, 810, 840, 870, // 2272
+  900, 930, 960, 990, 1020, 1050, 1080, 1140, // 2280
+  1110, 1080, 1050, 1020, 990, 960, 930, 900, // 2288
+  870, 840, 810, 780, 750, 720, 690, 660, // 2296
+  630, 600, 540, 480, 420, 360, 300, 240, // 2304
+  180, 120, 60, 0, -60, -120, -180, -240, // 2312
+  -300, -360, -420, -480, -540, -600, -630, -660, // 2320
+  -690, -720, -750, -780, -810, -840, -870, -900, // 2328
+  -930, -960, -990, -1020, -1050, -1080, -1110, -1140, // 2336
+  -1140, -1110, -1080, -1050, -1020, -990, -960, -930, // 2344
+  -900, -870, -840, -810, -780, -750, -720, -690, // 2352
+  -660, -630, -600, -540, -480, -420, -360, -300, // 2360
+  -240, -180, -120, -60, 0, 60, 120, 180, // 2368
+  240, 300, 360, 420, 480, 540, 600, 630, // 2376
+  660, 690, 720, 750, 780, 810, 840, 870, // 2384
+  900, 930, 960, 990, 1020, 1050, 1080, 1110, // 2392
+  1140                        //2400
+};
+
+const float ytemp[2401] = {
+  0, 0, 25.9808, 25.9808, -0, -25.9808, -25.9808, 0, // 0
+  25.9808, 51.9615, 51.9615, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 8
+  -51.9615, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 77.9423, // 16
+  77.9423, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 24
+  -77.9423, -77.9423, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 32
+  77.9423, 103.923, 103.923, 103.923, 103.923, 103.923, 77.9423, 51.9615, // 40
+  25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -103.923, -103.923, // 48
+  -103.923, -103.923, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 56
+  77.9423, 103.923, 129.904, 129.904, 129.904, 129.904, 129.904, 129.904, // 64
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 72
+  -103.923, -129.904, -129.904, -129.904, -129.904, -129.904, -129.904, -103.923, // 80
+  -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, // 88
+  129.904, 155.885, 155.885, 155.885, 155.885, 155.885, 155.885, 155.885, // 96
+  129.904, 103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 104
+  -77.9423, -103.923, -129.904, -155.885, -155.885, -155.885, -155.885, -155.885, // 112
+  -155.885, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, // 120
+  25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, 181.865, 181.865, // 128
+  181.865, 181.865, 181.865, 181.865, 181.865, 181.865, 155.885, 129.904, // 136
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 144
+  -103.923, -129.904, -155.885, -181.865, -181.865, -181.865, -181.865, -181.865, // 152
+  -181.865, -181.865, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 160
+  -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, // 168
+  181.865, 207.846, 207.846, 207.846, 207.846, 207.846, 207.846, 207.846, // 176
+  207.846, 207.846, 181.865, 155.885, 129.904, 103.923, 77.9423, 51.9615, // 184
+  25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -129.904, -155.885, // 192
+  -181.865, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, // 200
+  -207.846, -207.846, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 208
+  -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, // 216
+  181.865, 207.846, 233.827, 233.827, 233.827, 233.827, 233.827, 233.827, // 224
+  233.827, 233.827, 233.827, 233.827, 207.846, 181.865, 155.885, 129.904, // 232
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 240
+  -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -233.827, -233.827, // 248
+  -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -207.846, // 256
+  -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, // 264
+  25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, // 272
+  233.827, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, // 280
+  259.808, 259.808, 259.808, 259.808, 233.827, 207.846, 181.865, 155.885, // 288
+  129.904, 103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 296
+  -77.9423, -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, // 304
+  -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, // 312
+  -259.808, -259.808, -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, // 320
+  -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, // 328
+  129.904, 155.885, 181.865, 207.846, 233.827, 259.808, 285.788, 285.788, // 336
+  285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, // 344
+  285.788, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 352
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 360
+  -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 368
+  -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, // 376
+  -285.788, -285.788, -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, // 384
+  -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 392
+  77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, 233.827, 259.808, // 400
+  285.788, 311.769, 311.769, 311.769, 311.769, 311.769, 311.769, 311.769, // 408
+  311.769, 311.769, 311.769, 311.769, 311.769, 311.769, 285.788, 259.808, // 416
+  233.827, 207.846, 181.865, 155.885, 129.904, 103.923, 77.9423, 51.9615, // 424
+  25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -129.904, -155.885, // 432
+  -181.865, -207.846, -233.827, -259.808, -285.788, -311.769, -311.769, -311.769, // 440
+  -311.769, -311.769, -311.769, -311.769, -311.769, -311.769, -311.769, -311.769, // 448
+  -311.769, -311.769, -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, // 456
+  -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 464
+  77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, 233.827, 259.808, // 472
+  285.788, 311.769, 337.75, 337.75, 337.75, 337.75, 337.75, 337.75, // 480
+  337.75, 337.75, 337.75, 337.75, 337.75, 337.75, 337.75, 337.75, // 488
+  311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 496
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 504
+  -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 512
+  -311.769, -337.75, -337.75, -337.75, -337.75, -337.75, -337.75, -337.75, // 520
+  -337.75, -337.75, -337.75, -337.75, -337.75, -337.75, -337.75, -311.769, // 528
+  -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, // 536
+  -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, // 544
+  129.904, 155.885, 181.865, 207.846, 233.827, 259.808, 285.788, 311.769, // 552
+  337.75, 363.731, 363.731, 363.731, 363.731, 363.731, 363.731, 363.731, // 560
+  363.731, 363.731, 363.731, 363.731, 363.731, 363.731, 363.731, 363.731, // 568
+  337.75, 311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, // 576
+  129.904, 103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 584
+  -77.9423, -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, // 592
+  -285.788, -311.769, -337.75, -363.731, -363.731, -363.731, -363.731, -363.731, // 600
+  -363.731, -363.731, -363.731, -363.731, -363.731, -363.731, -363.731, -363.731, // 608
+  -363.731, -363.731, -337.75, -311.769, -285.788, -259.808, -233.827, -207.846, // 616
+  -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, // 624
+  25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, // 632
+  233.827, 259.808, 285.788, 311.769, 337.75, 363.731, 389.711, 389.711, // 640
+  389.711, 389.711, 389.711, 389.711, 389.711, 389.711, 389.711, 389.711, // 648
+  389.711, 389.711, 389.711, 389.711, 389.711, 389.711, 363.731, 337.75, // 656
+  311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 664
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 672
+  -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 680
+  -311.769, -337.75, -363.731, -389.711, -389.711, -389.711, -389.711, -389.711, // 688
+  -389.711, -389.711, -389.711, -389.711, -389.711, -389.711, -389.711, -389.711, // 696
+  -389.711, -389.711, -389.711, -363.731, -337.75, -311.769, -285.788, -259.808, // 704
+  -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 712
+  -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, // 720
+  181.865, 207.846, 233.827, 259.808, 285.788, 311.769, 337.75, 363.731, // 728
+  389.711, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, // 736
+  415.692, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, // 744
+  415.692, 415.692, 389.711, 363.731, 337.75, 311.769, 285.788, 259.808, // 752
+  233.827, 207.846, 181.865, 155.885, 129.904, 103.923, 77.9423, 51.9615, // 760
+  25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -129.904, -155.885, // 768
+  -181.865, -207.846, -233.827, -259.808, -285.788, -311.769, -337.75, -363.731, // 776
+  -389.711, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, // 784
+  -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, // 792
+  -415.692, -415.692, -389.711, -363.731, -337.75, -311.769, -285.788, -259.808, // 800
+  -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 808
+  -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, // 816
+  181.865, 207.846, 233.827, 259.808, 285.788, 311.769, 337.75, 363.731, // 824
+  389.711, 415.692, 441.673, 441.673, 441.673, 441.673, 441.673, 441.673, // 832
+  441.673, 441.673, 441.673, 441.673, 441.673, 441.673, 441.673, 441.673, // 840
+  441.673, 441.673, 441.673, 441.673, 415.692, 389.711, 363.731, 337.75, // 848
+  311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 856
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 864
+  -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 872
+  -311.769, -337.75, -363.731, -389.711, -415.692, -441.673, -441.673, -441.673, // 880
+  -441.673, -441.673, -441.673, -441.673, -441.673, -441.673, -441.673, -441.673, // 888
+  -441.673, -441.673, -441.673, -441.673, -441.673, -441.673, -441.673, -415.692, // 896
+  -389.711, -363.731, -337.75, -311.769, -285.788, -259.808, -233.827, -207.846, // 904
+  -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, // 912
+  25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, // 920
+  233.827, 259.808, 285.788, 311.769, 337.75, 363.731, 389.711, 415.692, // 928
+  441.673, 467.654, 467.654, 467.654, 467.654, 467.654, 467.654, 467.654, // 936
+  467.654, 467.654, 467.654, 467.654, 467.654, 467.654, 467.654, 467.654, // 944
+  467.654, 467.654, 467.654, 467.654, 441.673, 415.692, 389.711, 363.731, // 952
+  337.75, 311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, // 960
+  129.904, 103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 968
+  -77.9423, -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, // 976
+  -285.788, -311.769, -337.75, -363.731, -389.711, -415.692, -441.673, -467.654, // 984
+  -467.654, -467.654, -467.654, -467.654, -467.654, -467.654, -467.654, -467.654, // 992
+  -467.654, -467.654, -467.654, -467.654, -467.654, -467.654, -467.654, -467.654, // 1000
+  -467.654, -467.654, -441.673, -415.692, -389.711, -363.731, -337.75, -311.769, // 1008
+  -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, // 1016
+  -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, // 1024
+  129.904, 155.885, 181.865, 207.846, 233.827, 259.808, 285.788, 311.769, // 1032
+  337.75, 363.731, 389.711, 415.692, 441.673, 467.654, 493.634, 493.634, // 1040
+  493.634, 493.634, 493.634, 493.634, 493.634, 493.634, 493.634, 493.634, // 1048
+  493.634, 493.634, 493.634, 493.634, 493.634, 493.634, 493.634, 493.634, // 1056
+  493.634, 493.634, 467.654, 441.673, 415.692, 389.711, 363.731, 337.75, // 1064
+  311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 1072
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 1080
+  -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 1088
+  -311.769, -337.75, -363.731, -389.711, -415.692, -441.673, -467.654, -493.634, // 1096
+  -493.634, -493.634, -493.634, -493.634, -493.634, -493.634, -493.634, -493.634, // 1104
+  -493.634, -493.634, -493.634, -493.634, -493.634, -493.634, -493.634, -493.634, // 1112
+  -493.634, -493.634, -493.634, -467.654, -441.673, -415.692, -389.711, -363.731, // 1120
+  -337.75, -311.769, -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, // 1128
+  -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 1136
+  77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, 233.827, 259.808, // 1144
+  285.788, 311.769, 337.75, 363.731, 389.711, 415.692, 441.673, 467.654, // 1152
+  493.634, 519.615, 519.615, 519.615, 519.615, 519.615, 519.615, 519.615, // 1160
+  519.615, 519.615, 519.615, 519.615, 519.615, 519.615, 519.615, 519.615, // 1168
+  519.615, 519.615, 519.615, 519.615, 519.615, 519.615, 493.634, 467.654, // 1176
+  441.673, 415.692, 389.711, 363.731, 337.75, 311.769, 285.788, 259.808, // 1184
+  233.827, 207.846, 181.865, 155.885, 129.904, 103.923, 77.9423, 51.9615, // 1192
+  25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -129.904, -155.885, // 1200
+  -181.865, -207.846, -233.827, -259.808, -285.788, -311.769, -337.75, -363.731, // 1208
+  -389.711, -415.692, -441.673, -467.654, -493.634, -519.615, -519.615, -519.615, // 1216
+  -519.615, -519.615, -519.615, -519.615, -519.615, -519.615, -519.615, -519.615, // 1224
+  -519.615, -519.615, -519.615, -519.615, -519.615, -519.615, -519.615, -519.615, // 1232
+  -519.615, -519.615, -493.634, -467.654, -441.673, -415.692, -389.711, -363.731, // 1240
+  -337.75, -311.769, -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, // 1248
+  -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 1256
+  77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, 233.827, 259.808, // 1264
+  285.788, 311.769, 337.75, 363.731, 389.711, 415.692, 441.673, 467.654, // 1272
+  493.634, 519.615, 545.596, 545.596, 545.596, 545.596, 545.596, 545.596, // 1280
+  545.596, 545.596, 545.596, 545.596, 545.596, 545.596, 545.596, 545.596, // 1288
+  545.596, 545.596, 545.596, 545.596, 545.596, 545.596, 545.596, 545.596, // 1296
+  519.615, 493.634, 467.654, 441.673, 415.692, 389.711, 363.731, 337.75, // 1304
+  311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 1312
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 1320
+  -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 1328
+  -311.769, -337.75, -363.731, -389.711, -415.692, -441.673, -467.654, -493.634, // 1336
+  -519.615, -545.596, -545.596, -545.596, -545.596, -545.596, -545.596, -545.596, // 1344
+  -545.596, -545.596, -545.596, -545.596, -545.596, -545.596, -545.596, -545.596, // 1352
+  -545.596, -545.596, -545.596, -545.596, -545.596, -545.596, -545.596, -519.615, // 1360
+  -493.634, -467.654, -441.673, -415.692, -389.711, -363.731, -337.75, -311.769, // 1368
+  -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, // 1376
+  -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, // 1384
+  129.904, 155.885, 181.865, 207.846, 233.827, 259.808, 285.788, 311.769, // 1392
+  337.75, 363.731, 389.711, 415.692, 441.673, 467.654, 493.634, 519.615, // 1400
+  545.596, 571.577, 571.577, 571.577, 571.577, 571.577, 571.577, 571.577, // 1408
+  571.577, 571.577, 571.577, 571.577, 571.577, 571.577, 571.577, 571.577, // 1416
+  571.577, 571.577, 571.577, 571.577, 571.577, 571.577, 571.577, 571.577, // 1424
+  545.596, 519.615, 493.634, 467.654, 441.673, 415.692, 389.711, 363.731, // 1432
+  337.75, 311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, // 1440
+  129.904, 103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 1448
+  -77.9423, -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, // 1456
+  -285.788, -311.769, -337.75, -363.731, -389.711, -415.692, -441.673, -467.654, // 1464
+  -493.634, -519.615, -545.596, -571.577, -571.577, -571.577, -571.577, -571.577, // 1472
+  -571.577, -571.577, -571.577, -571.577, -571.577, -571.577, -571.577, -571.577, // 1480
+  -571.577, -571.577, -571.577, -571.577, -571.577, -571.577, -571.577, -571.577, // 1488
+  -571.577, -571.577, -545.596, -519.615, -493.634, -467.654, -441.673, -415.692, // 1496
+  -389.711, -363.731, -337.75, -311.769, -285.788, -259.808, -233.827, -207.846, // 1504
+  -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, // 1512
+  25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, // 1520
+  233.827, 259.808, 285.788, 311.769, 337.75, 363.731, 389.711, 415.692, // 1528
+  441.673, 467.654, 493.634, 519.615, 545.596, 571.577, 597.558, 597.558, // 1536
+  597.558, 597.558, 597.558, 597.558, 597.558, 597.558, 597.558, 597.558, // 1544
+  597.558, 597.558, 597.558, 597.558, 597.558, 597.558, 597.558, 597.558, // 1552
+  597.558, 597.558, 597.558, 597.558, 597.558, 597.558, 571.577, 545.596, // 1560
+  519.615, 493.634, 467.654, 441.673, 415.692, 389.711, 363.731, 337.75, // 1568
+  311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 1576
+  103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 1584
+  -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 1592
+  -311.769, -337.75, -363.731, -389.711, -415.692, -441.673, -467.654, -493.634, // 1600
+  -519.615, -545.596, -571.577, -597.558, -597.558, -597.558, -597.558, -597.558, // 1608
+  -597.558, -597.558, -597.558, -597.558, -597.558, -597.558, -597.558, -597.558, // 1616
+  -597.558, -597.558, -597.558, -597.558, -597.558, -597.558, -597.558, -597.558, // 1624
+  -597.558, -597.558, -597.558, -571.577, -545.596, -519.615, -493.634, -467.654, // 1632
+  -441.673, -415.692, -389.711, -363.731, -337.75, -311.769, -285.788, -259.808, // 1640
+  -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 1648
+  -25.9808, 34.641, 86.6025, 138.564, 190.526, 242.487, 294.449, 346.41, // 1656
+  398.372, 450.333, 502.295, 554.256, 606.218, 640.859, 640.859, 640.859, // 1664
+  640.859, 640.859, 640.859, 640.859, 640.859, 640.859, 640.859, 640.859, // 1672
+  640.859, 606.218, 554.256, 502.295, 450.333, 398.372, 346.41, 294.449, // 1680
+  242.487, 190.526, 138.564, 86.6025, 34.641, -34.641, -86.6025, -138.564, // 1688
+  -190.526, -242.487, -294.449, -346.41, -398.372, -450.333, -502.295, -554.256, // 1696
+  -606.218, -640.859, -640.859, -640.859, -640.859, -640.859, -640.859, -640.859, // 1704
+  -640.859, -640.859, -640.859, -640.859, -640.859, -606.218, -554.256, -502.295, // 1712
+  -450.333, -398.372, -346.41, -294.449, -242.487, -190.526, -138.564, -86.6025, // 1720
+  -34.641, 34.641, 86.6025, 138.564, 190.526, 242.487, 294.449, 346.41, // 1728
+  398.372, 450.333, 502.295, 554.256, 606.218, 658.179, 692.82, 692.82, // 1736
+  692.82, 692.82, 692.82, 692.82, 692.82, 692.82, 692.82, 692.82, // 1744
+  692.82, 692.82, 692.82, 658.179, 606.218, 554.256, 502.295, 450.333, // 1752
+  398.372, 346.41, 294.449, 242.487, 190.526, 138.564, 86.6025, 34.641, // 1760
+  -34.641, -86.6025, -138.564, -190.526, -242.487, -294.449, -346.41, -398.372, // 1768
+  -450.333, -502.295, -554.256, -606.218, -658.179, -692.82, -692.82, -692.82, // 1776
+  -692.82, -692.82, -692.82, -692.82, -692.82, -692.82, -692.82, -692.82, // 1784
+  -692.82, -692.82, -658.179, -606.218, -554.256, -502.295, -450.333, -398.372, // 1792
+  -346.41, -294.449, -242.487, -190.526, -138.564, -86.6025, -34.641, 34.641, // 1800
+  86.6025, 138.564, 190.526, 242.487, 294.449, 346.41, 398.372, 450.333, // 1808
+  502.295, 554.256, 606.218, 658.179, 710.141, 744.782, 744.782, 744.782, // 1816
+  744.782, 744.782, 744.782, 744.782, 744.782, 744.782, 744.782, 744.782, // 1824
+  744.782, 744.782, 744.782, 710.141, 658.179, 606.218, 554.256, 502.295, // 1832
+  450.333, 398.372, 346.41, 294.449, 242.487, 190.526, 138.564, 86.6025, // 1840
+  34.641, -34.641, -86.6025, -138.564, -190.526, -242.487, -294.449, -346.41, // 1848
+  -398.372, -450.333, -502.295, -554.256, -606.218, -658.179, -710.141, -744.782, // 1856
+  -744.782, -744.782, -744.782, -744.782, -744.782, -744.782, -744.782, -744.782, // 1864
+  -744.782, -744.782, -744.782, -744.782, -744.782, -710.141, -658.179, -606.218, // 1872
+  -554.256, -502.295, -450.333, -398.372, -346.41, -294.449, -242.487, -190.526, // 1880
+  -138.564, -86.6025, -34.641, 34.641, 86.6025, 138.564, 190.526, 242.487, // 1888
+  294.449, 346.41, 398.372, 450.333, 502.295, 554.256, 606.218, 658.179, // 1896
+  710.141, 762.102, 796.743, 796.743, 796.743, 796.743, 796.743, 796.743, // 1904
+  796.743, 796.743, 796.743, 796.743, 796.743, 796.743, 796.743, 796.743, // 1912
+  796.743, 762.102, 710.141, 658.179, 606.218, 554.256, 502.295, 450.333, // 1920
+  398.372, 346.41, 294.449, 242.487, 190.526, 138.564, 86.6025, 34.641, // 1928
+  -34.641, -86.6025, -138.564, -190.526, -242.487, -294.449, -346.41, -398.372, // 1936
+  -450.333, -502.295, -554.256, -606.218, -658.179, -710.141, -762.102, -796.743, // 1944
+  -796.743, -796.743, -796.743, -796.743, -796.743, -796.743, -796.743, -796.743, // 1952
+  -796.743, -796.743, -796.743, -796.743, -796.743, -796.743, -762.102, -710.141, // 1960
+  -658.179, -606.218, -554.256, -502.295, -450.333, -398.372, -346.41, -294.449, // 1968
+  -242.487, -190.526, -138.564, -86.6025, -34.641, 34.641, 86.6025, 138.564, // 1976
+  190.526, 242.487, 294.449, 346.41, 398.372, 450.333, 502.295, 554.256, // 1984
+  606.218, 658.179, 710.141, 762.102, 814.064, 848.705, 848.705, 848.705, // 1992
+  848.705, 848.705, 848.705, 848.705, 848.705, 848.705, 848.705, 848.705, // 2000
+  848.705, 848.705, 848.705, 848.705, 848.705, 814.064, 762.102, 710.141, // 2008
+  658.179, 606.218, 554.256, 502.295, 450.333, 398.372, 346.41, 294.449, // 2016
+  242.487, 190.526, 138.564, 86.6025, 34.641, -34.641, -86.6025, -138.564, // 2024
+  -190.526, -242.487, -294.449, -346.41, -398.372, -450.333, -502.295, -554.256, // 2032
+  -606.218, -658.179, -710.141, -762.102, -814.064, -848.705, -848.705, -848.705, // 2040
+  -848.705, -848.705, -848.705, -848.705, -848.705, -848.705, -848.705, -848.705, // 2048
+  -848.705, -848.705, -848.705, -848.705, -848.705, -814.064, -762.102, -710.141, // 2056
+  -658.179, -606.218, -554.256, -502.295, -450.333, -398.372, -346.41, -294.449, // 2064
+  -242.487, -190.526, -138.564, -86.6025, -34.641, 34.641, 86.6025, 138.564, // 2072
+  190.526, 242.487, 294.449, 346.41, 398.372, 450.333, 502.295, 554.256, // 2080
+  606.218, 658.179, 710.141, 762.102, 814.064, 866.025, 900.666, 900.666, // 2088
+  900.666, 900.666, 900.666, 900.666, 900.666, 900.666, 900.666, 900.666, // 2096
+  900.666, 900.666, 900.666, 900.666, 900.666, 900.666, 900.666, 866.025, // 2104
+  814.064, 762.102, 710.141, 658.179, 606.218, 554.256, 502.295, 450.333, // 2112
+  398.372, 346.41, 294.449, 242.487, 190.526, 138.564, 86.6025, 34.641, // 2120
+  -34.641, -86.6025, -138.564, -190.526, -242.487, -294.449, -346.41, -398.372, // 2128
+  -450.333, -502.295, -554.256, -606.218, -658.179, -710.141, -762.102, -814.064, // 2136
+  -866.025, -900.666, -900.666, -900.666, -900.666, -900.666, -900.666, -900.666, // 2144
+  -900.666, -900.666, -900.666, -900.666, -900.666, -900.666, -900.666, -900.666, // 2152
+  -900.666, -900.666, -866.025, -814.064, -762.102, -710.141, -658.179, -606.218, // 2160
+  -554.256, -502.295, -450.333, -398.372, -346.41, -294.449, -242.487, -190.526, // 2168
+  -138.564, -86.6025, -34.641, 34.641, 86.6025, 138.564, 190.526, 242.487, // 2176
+  294.449, 346.41, 398.372, 450.333, 502.295, 554.256, 606.218, 658.179, // 2184
+  710.141, 762.102, 814.064, 866.025, 917.987, 952.628, 952.628, 952.628, // 2192
+  952.628, 952.628, 952.628, 952.628, 952.628, 952.628, 952.628, 952.628, // 2200
+  952.628, 952.628, 952.628, 952.628, 952.628, 952.628, 952.628, 917.987, // 2208
+  866.025, 814.064, 762.102, 710.141, 658.179, 606.218, 554.256, 502.295, // 2216
+  450.333, 398.372, 346.41, 294.449, 242.487, 190.526, 138.564, 86.6025, // 2224
+  34.641, -34.641, -86.6025, -138.564, -190.526, -242.487, -294.449, -346.41, // 2232
+  -398.372, -450.333, -502.295, -554.256, -606.218, -658.179, -710.141, -762.102, // 2240
+  -814.064, -866.025, -917.987, -952.628, -952.628, -952.628, -952.628, -952.628, // 2248
+  -952.628, -952.628, -952.628, -952.628, -952.628, -952.628, -952.628, -952.628, // 2256
+  -952.628, -952.628, -952.628, -952.628, -952.628, -917.987, -866.025, -814.064, // 2264
+  -762.102, -710.141, -658.179, -606.218, -554.256, -502.295, -450.333, -398.372, // 2272
+  -346.41, -294.449, -242.487, -190.526, -138.564, -86.6025, -34.641, 34.641, // 2280
+  86.6025, 138.564, 190.526, 242.487, 294.449, 346.41, 398.372, 450.333, // 2288
+  502.295, 554.256, 606.218, 658.179, 710.141, 762.102, 814.064, 866.025, // 2296
+  917.987, 969.948, 1004.59, 1004.59, 1004.59, 1004.59, 1004.59, 1004.59, // 2304
+  1004.59, 1004.59, 1004.59, 1004.59, 1004.59, 1004.59, 1004.59, 1004.59, // 2312
+  1004.59, 1004.59, 1004.59, 1004.59, 1004.59, 969.948, 917.987, 866.025, // 2320
+  814.064, 762.102, 710.141, 658.179, 606.218, 554.256, 502.295, 450.333, // 2328
+  398.372, 346.41, 294.449, 242.487, 190.526, 138.564, 86.6025, 34.641, // 2336
+  -34.641, -86.6025, -138.564, -190.526, -242.487, -294.449, -346.41, -398.372, // 2344
+  -450.333, -502.295, -554.256, -606.218, -658.179, -710.141, -762.102, -814.064, // 2352
+  -866.025, -917.987, -969.948, -1004.59, -1004.59, -1004.59, -1004.59, -1004.59, // 2360
+  -1004.59, -1004.59, -1004.59, -1004.59, -1004.59, -1004.59, -1004.59, -1004.59, // 2368
+  -1004.59, -1004.59, -1004.59, -1004.59, -1004.59, -1004.59, -969.948, -917.987, // 2376
+  -866.025, -814.064, -762.102, -710.141, -658.179, -606.218, -554.256, -502.295, // 2384
+  -450.333, -398.372, -346.41, -294.449, -242.487, -190.526, -138.564, -86.6025, // 2392
+  -34.641                        //2400
+};
+
+
+
+ const float rtemp[2401] = {
+   30, 30, 30, 30, 30, 30, 30, 30, // 0
+   30, 30, 30, 30, 30, 30, 30, 30, // 8
+   30, 30, 30, 30, 30, 30, 30, 30, // 16
+   30, 30, 30, 30, 30, 30, 30, 30, // 24
+   30, 30, 30, 30, 30, 30, 30, 30, // 32
+   30, 30, 30, 30, 30, 30, 30, 30, // 40
+   30, 30, 30, 30, 30, 30, 30, 30, // 48
+   30, 30, 30, 30, 30, 30, 30, 30, // 56
+   30, 30, 30, 30, 30, 30, 30, 30, // 64
+   30, 30, 30, 30, 30, 30, 30, 30, // 72
+   30, 30, 30, 30, 30, 30, 30, 30, // 80
+   30, 30, 30, 30, 30, 30, 30, 30, // 88
+   30, 30, 30, 30, 30, 30, 30, 30, // 96
+   30, 30, 30, 30, 30, 30, 30, 30, // 104
+   30, 30, 30, 30, 30, 30, 30, 30, // 112
+   30, 30, 30, 30, 30, 30, 30, 30, // 120
+   30, 30, 30, 30, 30, 30, 30, 30, // 128
+   30, 30, 30, 30, 30, 30, 30, 30, // 136
+   30, 30, 30, 30, 30, 30, 30, 30, // 144
+   30, 30, 30, 30, 30, 30, 30, 30, // 152
+   30, 30, 30, 30, 30, 30, 30, 30, // 160
+   30, 30, 30, 30, 30, 30, 30, 30, // 168
+   30, 30, 30, 30, 30, 30, 30, 30, // 176
+   30, 30, 30, 30, 30, 30, 30, 30, // 184
+   30, 30, 30, 30, 30, 30, 30, 30, // 192
+   30, 30, 30, 30, 30, 30, 30, 30, // 200
+   30, 30, 30, 30, 30, 30, 30, 30, // 208
+   30, 30, 30, 30, 30, 30, 30, 30, // 216
+   30, 30, 30, 30, 30, 30, 30, 30, // 224
+   30, 30, 30, 30, 30, 30, 30, 30, // 232
+   30, 30, 30, 30, 30, 30, 30, 30, // 240
+   30, 30, 30, 30, 30, 30, 30, 30, // 248
+   30, 30, 30, 30, 30, 30, 30, 30, // 256
+   30, 30, 30, 30, 30, 30, 30, 30, // 264
+   30, 30, 30, 30, 30, 30, 30, 30, // 272
+   30, 30, 30, 30, 30, 30, 30, 30, // 280
+   30, 30, 30, 30, 30, 30, 30, 30, // 288
+   30, 30, 30, 30, 30, 30, 30, 30, // 296
+   30, 30, 30, 30, 30, 30, 30, 30, // 304
+   30, 30, 30, 30, 30, 30, 30, 30, // 312
+   30, 30, 30, 30, 30, 30, 30, 30, // 320
+   30, 30, 30, 30, 30, 30, 30, 30, // 328
+   30, 30, 30, 30, 30, 30, 30, 30, // 336
+   30, 30, 30, 30, 30, 30, 30, 30, // 344
+   30, 30, 30, 30, 30, 30, 30, 30, // 352
+   30, 30, 30, 30, 30, 30, 30, 30, // 360
+   30, 30, 30, 30, 30, 30, 30, 30, // 368
+   30, 30, 30, 30, 30, 30, 30, 30, // 376
+   30, 30, 30, 30, 30, 30, 30, 30, // 384
+   30, 30, 30, 30, 30, 30, 30, 30, // 392
+   30, 30, 30, 30, 30, 30, 30, 30, // 400
+   30, 30, 30, 30, 30, 30, 30, 30, // 408
+   30, 30, 30, 30, 30, 30, 30, 30, // 416
+   30, 30, 30, 30, 30, 30, 30, 30, // 424
+   30, 30, 30, 30, 30, 30, 30, 30, // 432
+   30, 30, 30, 30, 30, 30, 30, 30, // 440
+   30, 30, 30, 30, 30, 30, 30, 30, // 448
+   30, 30, 30, 30, 30, 30, 30, 30, // 456
+   30, 30, 30, 30, 30, 30, 30, 30, // 464
+   30, 30, 30, 30, 30, 30, 30, 30, // 472
+   30, 30, 30, 30, 30, 30, 30, 30, // 480
+   30, 30, 30, 30, 30, 30, 30, 30, // 488
+   30, 30, 30, 30, 30, 30, 30, 30, // 496
+   30, 30, 30, 30, 30, 30, 30, 30, // 504
+   30, 30, 30, 30, 30, 30, 30, 30, // 512
+   30, 30, 30, 30, 30, 30, 30, 30, // 520
+   30, 30, 30, 30, 30, 30, 30, 30, // 528
+   30, 30, 30, 30, 30, 30, 30, 30, // 536
+   30, 30, 30, 30, 30, 30, 30, 30, // 544
+   30, 30, 30, 30, 30, 30, 30, 30, // 552
+   30, 30, 30, 30, 30, 30, 30, 30, // 560
+   30, 30, 30, 30, 30, 30, 30, 30, // 568
+   30, 30, 30, 30, 30, 30, 30, 30, // 576
+   30, 30, 30, 30, 30, 30, 30, 30, // 584
+   30, 30, 30, 30, 30, 30, 30, 30, // 592
+   30, 30, 30, 30, 30, 30, 30, 30, // 600
+   30, 30, 30, 30, 30, 30, 30, 30, // 608
+   30, 30, 30, 30, 30, 30, 30, 30, // 616
+   30, 30, 30, 30, 30, 30, 30, 30, // 624
+   30, 30, 30, 30, 30, 30, 30, 30, // 632
+   30, 30, 30, 30, 30, 30, 30, 30, // 640
+   30, 30, 30, 30, 30, 30, 30, 30, // 648
+   30, 30, 30, 30, 30, 30, 30, 30, // 656
+   30, 30, 30, 30, 30, 30, 30, 30, // 664
+   30, 30, 30, 30, 30, 30, 30, 30, // 672
+   30, 30, 30, 30, 30, 30, 30, 30, // 680
+   30, 30, 30, 30, 30, 30, 30, 30, // 688
+   30, 30, 30, 30, 30, 30, 30, 30, // 696
+   30, 30, 30, 30, 30, 30, 30, 30, // 704
+   30, 30, 30, 30, 30, 30, 30, 30, // 712
+   30, 30, 30, 30, 30, 30, 30, 30, // 720
+   30, 30, 30, 30, 30, 30, 30, 30, // 728
+   30, 30, 30, 30, 30, 30, 30, 30, // 736
+   30, 30, 30, 30, 30, 30, 30, 30, // 744
+   30, 30, 30, 30, 30, 30, 30, 30, // 752
+   30, 30, 30, 30, 30, 30, 30, 30, // 760
+   30, 30, 30, 30, 30, 30, 30, 30, // 768
+   30, 30, 30, 30, 30, 30, 30, 30, // 776
+   30, 30, 30, 30, 30, 30, 30, 30, // 784
+   30, 30, 30, 30, 30, 30, 30, 30, // 792
+   30, 30, 30, 30, 30, 30, 30, 30, // 800
+   30, 30, 30, 30, 30, 30, 30, 30, // 808
+   30, 30, 30, 30, 30, 30, 30, 30, // 816
+   30, 30, 30, 30, 30, 30, 30, 30, // 824
+   30, 30, 30, 30, 30, 30, 30, 30, // 832
+   30, 30, 30, 30, 30, 30, 30, 30, // 840
+   30, 30, 30, 30, 30, 30, 30, 30, // 848
+   30, 30, 30, 30, 30, 30, 30, 30, // 856
+   30, 30, 30, 30, 30, 30, 30, 30, // 864
+   30, 30, 30, 30, 30, 30, 30, 30, // 872
+   30, 30, 30, 30, 30, 30, 30, 30, // 880
+   30, 30, 30, 30, 30, 30, 30, 30, // 888
+   30, 30, 30, 30, 30, 30, 30, 30, // 896
+   30, 30, 30, 30, 30, 30, 30, 30, // 904
+   30, 30, 30, 30, 30, 30, 30, 30, // 912
+   30, 30, 30, 30, 30, 30, 30, 30, // 920
+   30, 30, 30, 30, 30, 30, 30, 30, // 928
+   30, 30, 30, 30, 30, 30, 30, 30, // 936
+   30, 30, 30, 30, 30, 30, 30, 30, // 944
+   30, 30, 30, 30, 30, 30, 30, 30, // 952
+   30, 30, 30, 30, 30, 30, 30, 30, // 960
+   30, 30, 30, 30, 30, 30, 30, 30, // 968
+   30, 30, 30, 30, 30, 30, 30, 30, // 976
+   30, 30, 30, 30, 30, 30, 30, 30, // 984
+   30, 30, 30, 30, 30, 30, 30, 30, // 992
+   30, 30, 30, 30, 30, 30, 30, 30, // 1000
+   30, 30, 30, 30, 30, 30, 30, 30, // 1008
+   30, 30, 30, 30, 30, 30, 30, 30, // 1016
+   30, 30, 30, 30, 30, 30, 30, 30, // 1024
+   30, 30, 30, 30, 30, 30, 30, 30, // 1032
+   30, 30, 30, 30, 30, 30, 30, 30, // 1040
+   30, 30, 30, 30, 30, 30, 30, 30, // 1048
+   30, 30, 30, 30, 30, 30, 30, 30, // 1056
+   30, 30, 30, 30, 30, 30, 30, 30, // 1064
+   30, 30, 30, 30, 30, 30, 30, 30, // 1072
+   30, 30, 30, 30, 30, 30, 30, 30, // 1080
+   30, 30, 30, 30, 30, 30, 30, 30, // 1088
+   30, 30, 30, 30, 30, 30, 30, 30, // 1096
+   30, 30, 30, 30, 30, 30, 30, 30, // 1104
+   30, 30, 30, 30, 30, 30, 30, 30, // 1112
+   30, 30, 30, 30, 30, 30, 30, 30, // 1120
+   30, 30, 30, 30, 30, 30, 30, 30, // 1128
+   30, 30, 30, 30, 30, 30, 30, 30, // 1136
+   30, 30, 30, 30, 30, 30, 30, 30, // 1144
+   30, 30, 30, 30, 30, 30, 30, 30, // 1152
+   30, 30, 30, 30, 30, 30, 30, 30, // 1160
+   30, 30, 30, 30, 30, 30, 30, 30, // 1168
+   30, 30, 30, 30, 30, 30, 30, 30, // 1176
+   30, 30, 30, 30, 30, 30, 30, 30, // 1184
+   30, 30, 30, 30, 30, 30, 30, 30, // 1192
+   30, 30, 30, 30, 30, 30, 30, 30, // 1200
+   30, 30, 30, 30, 30, 30, 30, 30, // 1208
+   30, 30, 30, 30, 30, 30, 30, 30, // 1216
+   30, 30, 30, 30, 30, 30, 30, 30, // 1224
+   30, 30, 30, 30, 30, 30, 30, 30, // 1232
+   30, 30, 30, 30, 30, 30, 30, 30, // 1240
+   30, 30, 30, 30, 30, 30, 30, 30, // 1248
+   30, 30, 30, 30, 30, 30, 30, 30, // 1256
+   30, 30, 30, 30, 30, 30, 30, 30, // 1264
+   30, 30, 30, 30, 30, 30, 30, 30, // 1272
+   30, 30, 30, 30, 30, 30, 30, 30, // 1280
+   30, 30, 30, 30, 30, 30, 30, 30, // 1288
+   30, 30, 30, 30, 30, 30, 30, 30, // 1296
+   30, 30, 30, 30, 30, 30, 30, 30, // 1304
+   30, 30, 30, 30, 30, 30, 30, 30, // 1312
+   30, 30, 30, 30, 30, 30, 30, 30, // 1320
+   30, 30, 30, 30, 30, 30, 30, 30, // 1328
+   30, 30, 30, 30, 30, 30, 30, 30, // 1336
+   30, 30, 30, 30, 30, 30, 30, 30, // 1344
+   30, 30, 30, 30, 30, 30, 30, 30, // 1352
+   30, 30, 30, 30, 30, 30, 30, 30, // 1360
+   30, 30, 30, 30, 30, 30, 30, 30, // 1368
+   30, 30, 30, 30, 30, 30, 30, 30, // 1376
+   30, 30, 30, 30, 30, 30, 30, 30, // 1384
+   30, 30, 30, 30, 30, 30, 30, 30, // 1392
+   30, 30, 30, 30, 30, 30, 30, 30, // 1400
+   30, 30, 30, 30, 30, 30, 30, 30, // 1408
+   30, 30, 30, 30, 30, 30, 30, 30, // 1416
+   30, 30, 30, 30, 30, 30, 30, 30, // 1424
+   30, 30, 30, 30, 30, 30, 30, 30, // 1432
+   30, 30, 30, 30, 30, 30, 30, 30, // 1440
+   30, 30, 30, 30, 30, 30, 30, 30, // 1448
+   30, 30, 30, 30, 30, 30, 30, 30, // 1456
+   30, 30, 30, 30, 30, 30, 30, 30, // 1464
+   30, 30, 30, 30, 30, 30, 30, 30, // 1472
+   30, 30, 30, 30, 30, 30, 30, 30, // 1480
+   30, 30, 30, 30, 30, 30, 30, 30, // 1488
+   30, 30, 30, 30, 30, 30, 30, 30, // 1496
+   30, 30, 30, 30, 30, 30, 30, 30, // 1504
+   30, 30, 30, 30, 30, 30, 30, 30, // 1512
+   30, 30, 30, 30, 30, 30, 30, 30, // 1520
+   30, 30, 30, 30, 30, 30, 30, 30, // 1528
+   30, 30, 30, 30, 30, 30, 30, 30, // 1536
+   30, 30, 30, 30, 30, 30, 30, 30, // 1544
+   30, 30, 30, 30, 30, 30, 30, 30, // 1552
+   30, 30, 30, 30, 30, 30, 30, 30, // 1560
+   30, 30, 30, 30, 30, 30, 30, 30, // 1568
+   30, 30, 30, 30, 30, 30, 30, 30, // 1576
+   30, 30, 30, 30, 30, 30, 30, 30, // 1584
+   30, 30, 30, 30, 30, 30, 30, 30, // 1592
+   30, 30, 30, 30, 30, 30, 30, 30, // 1600
+   30, 30, 30, 30, 30, 30, 30, 30, // 1608
+   30, 30, 30, 30, 30, 30, 30, 30, // 1616
+   30, 30, 30, 30, 30, 30, 30, 30, // 1624
+   30, 30, 30, 30, 30, 30, 30, 30, // 1632
+   30, 30, 30, 30, 30, 30, 30, 30, // 1640
+   30, 30, 30, 30, 30, 30, 30, 30, // 1648
+   30, 60, 60, 60, 60, 60, 60, 60, // 1656
+   60, 60, 60, 60, 60, 60, 60, 60, // 1664
+   60, 60, 60, 60, 60, 60, 60, 60, // 1672
+   60, 60, 60, 60, 60, 60, 60, 60, // 1680
+   60, 60, 60, 60, 60, 60, 60, 60, // 1688
+   60, 60, 60, 60, 60, 60, 60, 60, // 1696
+   60, 60, 60, 60, 60, 60, 60, 60, // 1704
+   60, 60, 60, 60, 60, 60, 60, 60, // 1712
+   60, 60, 60, 60, 60, 60, 60, 60, // 1720
+   60, 60, 60, 60, 60, 60, 60, 60, // 1728
+   60, 60, 60, 60, 60, 60, 60, 60, // 1736
+   60, 60, 60, 60, 60, 60, 60, 60, // 1744
+   60, 60, 60, 60, 60, 60, 60, 60, // 1752
+   60, 60, 60, 60, 60, 60, 60, 60, // 1760
+   60, 60, 60, 60, 60, 60, 60, 60, // 1768
+   60, 60, 60, 60, 60, 60, 60, 60, // 1776
+   60, 60, 60, 60, 60, 60, 60, 60, // 1784
+   60, 60, 60, 60, 60, 60, 60, 60, // 1792
+   60, 60, 60, 60, 60, 60, 60, 60, // 1800
+   60, 60, 60, 60, 60, 60, 60, 60, // 1808
+   60, 60, 60, 60, 60, 60, 60, 60, // 1816
+   60, 60, 60, 60, 60, 60, 60, 60, // 1824
+   60, 60, 60, 60, 60, 60, 60, 60, // 1832
+   60, 60, 60, 60, 60, 60, 60, 60, // 1840
+   60, 60, 60, 60, 60, 60, 60, 60, // 1848
+   60, 60, 60, 60, 60, 60, 60, 60, // 1856
+   60, 60, 60, 60, 60, 60, 60, 60, // 1864
+   60, 60, 60, 60, 60, 60, 60, 60, // 1872
+   60, 60, 60, 60, 60, 60, 60, 60, // 1880
+   60, 60, 60, 60, 60, 60, 60, 60, // 1888
+   60, 60, 60, 60, 60, 60, 60, 60, // 1896
+   60, 60, 60, 60, 60, 60, 60, 60, // 1904
+   60, 60, 60, 60, 60, 60, 60, 60, // 1912
+   60, 60, 60, 60, 60, 60, 60, 60, // 1920
+   60, 60, 60, 60, 60, 60, 60, 60, // 1928
+   60, 60, 60, 60, 60, 60, 60, 60, // 1936
+   60, 60, 60, 60, 60, 60, 60, 60, // 1944
+   60, 60, 60, 60, 60, 60, 60, 60, // 1952
+   60, 60, 60, 60, 60, 60, 60, 60, // 1960
+   60, 60, 60, 60, 60, 60, 60, 60, // 1968
+   60, 60, 60, 60, 60, 60, 60, 60, // 1976
+   60, 60, 60, 60, 60, 60, 60, 60, // 1984
+   60, 60, 60, 60, 60, 60, 60, 60, // 1992
+   60, 60, 60, 60, 60, 60, 60, 60, // 2000
+   60, 60, 60, 60, 60, 60, 60, 60, // 2008
+   60, 60, 60, 60, 60, 60, 60, 60, // 2016
+   60, 60, 60, 60, 60, 60, 60, 60, // 2024
+   60, 60, 60, 60, 60, 60, 60, 60, // 2032
+   60, 60, 60, 60, 60, 60, 60, 60, // 2040
+   60, 60, 60, 60, 60, 60, 60, 60, // 2048
+   60, 60, 60, 60, 60, 60, 60, 60, // 2056
+   60, 60, 60, 60, 60, 60, 60, 60, // 2064
+   60, 60, 60, 60, 60, 60, 60, 60, // 2072
+   60, 60, 60, 60, 60, 60, 60, 60, // 2080
+   60, 60, 60, 60, 60, 60, 60, 60, // 2088
+   60, 60, 60, 60, 60, 60, 60, 60, // 2096
+   60, 60, 60, 60, 60, 60, 60, 60, // 2104
+   60, 60, 60, 60, 60, 60, 60, 60, // 2112
+   60, 60, 60, 60, 60, 60, 60, 60, // 2120
+   60, 60, 60, 60, 60, 60, 60, 60, // 2128
+   60, 60, 60, 60, 60, 60, 60, 60, // 2136
+   60, 60, 60, 60, 60, 60, 60, 60, // 2144
+   60, 60, 60, 60, 60, 60, 60, 60, // 2152
+   60, 60, 60, 60, 60, 60, 60, 60, // 2160
+   60, 60, 60, 60, 60, 60, 60, 60, // 2168
+   60, 60, 60, 60, 60, 60, 60, 60, // 2176
+   60, 60, 60, 60, 60, 60, 60, 60, // 2184
+   60, 60, 60, 60, 60, 60, 60, 60, // 2192
+   60, 60, 60, 60, 60, 60, 60, 60, // 2200
+   60, 60, 60, 60, 60, 60, 60, 60, // 2208
+   60, 60, 60, 60, 60, 60, 60, 60, // 2216
+   60, 60, 60, 60, 60, 60, 60, 60, // 2224
+   60, 60, 60, 60, 60, 60, 60, 60, // 2232
+   60, 60, 60, 60, 60, 60, 60, 60, // 2240
+   60, 60, 60, 60, 60, 60, 60, 60, // 2248
+   60, 60, 60, 60, 60, 60, 60, 60, // 2256
+   60, 60, 60, 60, 60, 60, 60, 60, // 2264
+   60, 60, 60, 60, 60, 60, 60, 60, // 2272
+   60, 60, 60, 60, 60, 60, 60, 60, // 2280
+   60, 60, 60, 60, 60, 60, 60, 60, // 2288
+   60, 60, 60, 60, 60, 60, 60, 60, // 2296
+   60, 60, 60, 60, 60, 60, 60, 60, // 2304
+   60, 60, 60, 60, 60, 60, 60, 60, // 2312
+   60, 60, 60, 60, 60, 60, 60, 60, // 2320
+   60, 60, 60, 60, 60, 60, 60, 60, // 2328
+   60, 60, 60, 60, 60, 60, 60, 60, // 2336
+   60, 60, 60, 60, 60, 60, 60, 60, // 2344
+   60, 60, 60, 60, 60, 60, 60, 60, // 2352
+   60, 60, 60, 60, 60, 60, 60, 60, // 2360
+   60, 60, 60, 60, 60, 60, 60, 60, // 2368
+   60, 60, 60, 60, 60, 60, 60, 60, // 2376
+   60, 60, 60, 60, 60, 60, 60, 60, // 2384
+   60, 60, 60, 60, 60, 60, 60, 60, // 2392
+   60                        //2400
+ };
+
+
+ for (UInt_t i=0; i<GetNumPixels(); i++)
+   (*this)[i].Set(xtemp[i], ytemp[i], rtemp[i]) ;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the next neighbor information from a table into the pixel
+//  objects.
+//
+void MGeomCamECO1000HG::CreateNN()
+{
+  const Short_t nn[2401][6] = {       // Neighbours of  #
+    {  1,  2,  3,  4,  5,  6}, // 0
+    {  0,  2,  6,  7,  8,  18},
+    {  0,  1,  3,  8,  9,  10},
+    {  0,  2,  4,  10,  11,  12},
+    {  0,  3,  5,  12,  13,  14},
+    {  0,  4,  6,  14,  15,  16},
+    {  0,  1,  5,  16,  17,  18},
+    {  1,  8,  18,  19,  20,  36},
+    {  1,  2,  7,  9,  20,  21},
+    {  2,  8,  10,  21,  22,  23},
+    {  2,  3,  9,  11,  23,  24},
+    {  3,  10,  12,  24,  25,  26},
+    {  3,  4,  11,  13,  26,  27},
+    {  4,  12,  14,  27,  28,  29},
+    {  4,  5,  13,  15,  29,  30},
+    {  5,  14,  16,  30,  31,  32},
+    {  5,  6,  15,  17,  32,  33},
+    {  6,  16,  18,  33,  34,  35},
+    {  1,  6,  7,  17,  35,  36},
+    {  7,  20,  36,  37,  38,  60},
+    {  7,  8,  19,  21,  38,  39}, // 20
+    {  8,  9,  20,  22,  39,  40},
+    {  9,  21,  23,  40,  41,  42},
+    {  9,  10,  22,  24,  42,  43},
+    {  10,  11,  23,  25,  43,  44},
+    {  11,  24,  26,  44,  45,  46},
+    {  11,  12,  25,  27,  46,  47},
+    {  12,  13,  26,  28,  47,  48},
+    {  13,  27,  29,  48,  49,  50},
+    {  13,  14,  28,  30,  50,  51},
+    {  14,  15,  29,  31,  51,  52},
+    {  15,  30,  32,  52,  53,  54},
+    {  15,  16,  31,  33,  54,  55},
+    {  16,  17,  32,  34,  55,  56},
+    {  17,  33,  35,  56,  57,  58},
+    {  17,  18,  34,  36,  58,  59},
+    {  7,  18,  19,  35,  59,  60},
+    {  19,  38,  60,  61,  62,  90},
+    {  19,  20,  37,  39,  62,  63},
+    {  20,  21,  38,  40,  63,  64},
+    {  21,  22,  39,  41,  64,  65}, // 40
+    {  22,  40,  42,  65,  66,  67},
+    {  22,  23,  41,  43,  67,  68},
+    {  23,  24,  42,  44,  68,  69},
+    {  24,  25,  43,  45,  69,  70},
+    {  25,  44,  46,  70,  71,  72},
+    {  25,  26,  45,  47,  72,  73},
+    {  26,  27,  46,  48,  73,  74},
+    {  27,  28,  47,  49,  74,  75},
+    {  28,  48,  50,  75,  76,  77},
+    {  28,  29,  49,  51,  77,  78},
+    {  29,  30,  50,  52,  78,  79},
+    {  30,  31,  51,  53,  79,  80},
+    {  31,  52,  54,  80,  81,  82},
+    {  31,  32,  53,  55,  82,  83},
+    {  32,  33,  54,  56,  83,  84},
+    {  33,  34,  55,  57,  84,  85},
+    {  34,  56,  58,  85,  86,  87},
+    {  34,  35,  57,  59,  87,  88},
+    {  35,  36,  58,  60,  88,  89},
+    {  19,  36,  37,  59,  89,  90}, // 60
+    {  37,  62,  90,  91,  92,  126},
+    {  37,  38,  61,  63,  92,  93},
+    {  38,  39,  62,  64,  93,  94},
+    {  39,  40,  63,  65,  94,  95},
+    {  40,  41,  64,  66,  95,  96},
+    {  41,  65,  67,  96,  97,  98},
+    {  41,  42,  66,  68,  98,  99},
+    {  42,  43,  67,  69,  99,  100},
+    {  43,  44,  68,  70,  100,  101},
+    {  44,  45,  69,  71,  101,  102},
+    {  45,  70,  72,  102,  103,  104},
+    {  45,  46,  71,  73,  104,  105},
+    {  46,  47,  72,  74,  105,  106},
+    {  47,  48,  73,  75,  106,  107},
+    {  48,  49,  74,  76,  107,  108},
+    {  49,  75,  77,  108,  109,  110},
+    {  49,  50,  76,  78,  110,  111},
+    {  50,  51,  77,  79,  111,  112},
+    {  51,  52,  78,  80,  112,  113},
+    {  52,  53,  79,  81,  113,  114}, // 80
+    {  53,  80,  82,  114,  115,  116},
+    {  53,  54,  81,  83,  116,  117},
+    {  54,  55,  82,  84,  117,  118},
+    {  55,  56,  83,  85,  118,  119},
+    {  56,  57,  84,  86,  119,  120},
+    {  57,  85,  87,  120,  121,  122},
+    {  57,  58,  86,  88,  122,  123},
+    {  58,  59,  87,  89,  123,  124},
+    {  59,  60,  88,  90,  124,  125},
+    {  37,  60,  61,  89,  125,  126},
+    {  61,  92,  126,  127,  128,  168},
+    {  61,  62,  91,  93,  128,  129},
+    {  62,  63,  92,  94,  129,  130},
+    {  63,  64,  93,  95,  130,  131},
+    {  64,  65,  94,  96,  131,  132},
+    {  65,  66,  95,  97,  132,  133},
+    {  66,  96,  98,  133,  134,  135},
+    {  66,  67,  97,  99,  135,  136},
+    {  67,  68,  98,  100,  136,  137},
+    {  68,  69,  99,  101,  137,  138}, // 100
+    {  69,  70,  100,  102,  138,  139},
+    {  70,  71,  101,  103,  139,  140},
+    {  71,  102,  104,  140,  141,  142},
+    {  71,  72,  103,  105,  142,  143},
+    {  72,  73,  104,  106,  143,  144},
+    {  73,  74,  105,  107,  144,  145},
+    {  74,  75,  106,  108,  145,  146},
+    {  75,  76,  107,  109,  146,  147},
+    {  76,  108,  110,  147,  148,  149},
+    {  76,  77,  109,  111,  149,  150},
+    {  77,  78,  110,  112,  150,  151},
+    {  78,  79,  111,  113,  151,  152},
+    {  79,  80,  112,  114,  152,  153},
+    {  80,  81,  113,  115,  153,  154},
+    {  81,  114,  116,  154,  155,  156},
+    {  81,  82,  115,  117,  156,  157},
+    {  82,  83,  116,  118,  157,  158},
+    {  83,  84,  117,  119,  158,  159},
+    {  84,  85,  118,  120,  159,  160},
+    {  85,  86,  119,  121,  160,  161}, // 120
+    {  86,  120,  122,  161,  162,  163},
+    {  86,  87,  121,  123,  163,  164},
+    {  87,  88,  122,  124,  164,  165},
+    {  88,  89,  123,  125,  165,  166},
+    {  89,  90,  124,  126,  166,  167},
+    {  61,  90,  91,  125,  167,  168},
+    {  91,  128,  168,  169,  170,  216},
+    {  91,  92,  127,  129,  170,  171},
+    {  92,  93,  128,  130,  171,  172},
+    {  93,  94,  129,  131,  172,  173},
+    {  94,  95,  130,  132,  173,  174},
+    {  95,  96,  131,  133,  174,  175},
+    {  96,  97,  132,  134,  175,  176},
+    {  97,  133,  135,  176,  177,  178},
+    {  97,  98,  134,  136,  178,  179},
+    {  98,  99,  135,  137,  179,  180},
+    {  99,  100,  136,  138,  180,  181},
+    {  100,  101,  137,  139,  181,  182},
+    {  101,  102,  138,  140,  182,  183},
+    {  102,  103,  139,  141,  183,  184}, // 140
+    {  103,  140,  142,  184,  185,  186},
+    {  103,  104,  141,  143,  186,  187},
+    {  104,  105,  142,  144,  187,  188},
+    {  105,  106,  143,  145,  188,  189},
+    {  106,  107,  144,  146,  189,  190},
+    {  107,  108,  145,  147,  190,  191},
+    {  108,  109,  146,  148,  191,  192},
+    {  109,  147,  149,  192,  193,  194},
+    {  109,  110,  148,  150,  194,  195},
+    {  110,  111,  149,  151,  195,  196},
+    {  111,  112,  150,  152,  196,  197},
+    {  112,  113,  151,  153,  197,  198},
+    {  113,  114,  152,  154,  198,  199},
+    {  114,  115,  153,  155,  199,  200},
+    {  115,  154,  156,  200,  201,  202},
+    {  115,  116,  155,  157,  202,  203},
+    {  116,  117,  156,  158,  203,  204},
+    {  117,  118,  157,  159,  204,  205},
+    {  118,  119,  158,  160,  205,  206},
+    {  119,  120,  159,  161,  206,  207}, // 160
+    {  120,  121,  160,  162,  207,  208},
+    {  121,  161,  163,  208,  209,  210},
+    {  121,  122,  162,  164,  210,  211},
+    {  122,  123,  163,  165,  211,  212},
+    {  123,  124,  164,  166,  212,  213},
+    {  124,  125,  165,  167,  213,  214},
+    {  125,  126,  166,  168,  214,  215},
+    {  91,  126,  127,  167,  215,  216},
+    {  127,  170,  216,  217,  218,  270},
+    {  127,  128,  169,  171,  218,  219},
+    {  128,  129,  170,  172,  219,  220},
+    {  129,  130,  171,  173,  220,  221},
+    {  130,  131,  172,  174,  221,  222},
+    {  131,  132,  173,  175,  222,  223},
+    {  132,  133,  174,  176,  223,  224},
+    {  133,  134,  175,  177,  224,  225},
+    {  134,  176,  178,  225,  226,  227},
+    {  134,  135,  177,  179,  227,  228},
+    {  135,  136,  178,  180,  228,  229},
+    {  136,  137,  179,  181,  229,  230}, // 180
+    {  137,  138,  180,  182,  230,  231},
+    {  138,  139,  181,  183,  231,  232},
+    {  139,  140,  182,  184,  232,  233},
+    {  140,  141,  183,  185,  233,  234},
+    {  141,  184,  186,  234,  235,  236},
+    {  141,  142,  185,  187,  236,  237},
+    {  142,  143,  186,  188,  237,  238},
+    {  143,  144,  187,  189,  238,  239},
+    {  144,  145,  188,  190,  239,  240},
+    {  145,  146,  189,  191,  240,  241},
+    {  146,  147,  190,  192,  241,  242},
+    {  147,  148,  191,  193,  242,  243},
+    {  148,  192,  194,  243,  244,  245},
+    {  148,  149,  193,  195,  245,  246},
+    {  149,  150,  194,  196,  246,  247},
+    {  150,  151,  195,  197,  247,  248},
+    {  151,  152,  196,  198,  248,  249},
+    {  152,  153,  197,  199,  249,  250},
+    {  153,  154,  198,  200,  250,  251},
+    {  154,  155,  199,  201,  251,  252}, // 200
+    {  155,  200,  202,  252,  253,  254},
+    {  155,  156,  201,  203,  254,  255},
+    {  156,  157,  202,  204,  255,  256},
+    {  157,  158,  203,  205,  256,  257},
+    {  158,  159,  204,  206,  257,  258},
+    {  159,  160,  205,  207,  258,  259},
+    {  160,  161,  206,  208,  259,  260},
+    {  161,  162,  207,  209,  260,  261},
+    {  162,  208,  210,  261,  262,  263},
+    {  162,  163,  209,  211,  263,  264},
+    {  163,  164,  210,  212,  264,  265},
+    {  164,  165,  211,  213,  265,  266},
+    {  165,  166,  212,  214,  266,  267},
+    {  166,  167,  213,  215,  267,  268},
+    {  167,  168,  214,  216,  268,  269},
+    {  127,  168,  169,  215,  269,  270},
+    {  169,  218,  270,  271,  272,  330},
+    {  169,  170,  217,  219,  272,  273},
+    {  170,  171,  218,  220,  273,  274},
+    {  171,  172,  219,  221,  274,  275}, // 220
+    {  172,  173,  220,  222,  275,  276},
+    {  173,  174,  221,  223,  276,  277},
+    {  174,  175,  222,  224,  277,  278},
+    {  175,  176,  223,  225,  278,  279},
+    {  176,  177,  224,  226,  279,  280},
+    {  177,  225,  227,  280,  281,  282},
+    {  177,  178,  226,  228,  282,  283},
+    {  178,  179,  227,  229,  283,  284},
+    {  179,  180,  228,  230,  284,  285},
+    {  180,  181,  229,  231,  285,  286},
+    {  181,  182,  230,  232,  286,  287},
+    {  182,  183,  231,  233,  287,  288},
+    {  183,  184,  232,  234,  288,  289},
+    {  184,  185,  233,  235,  289,  290},
+    {  185,  234,  236,  290,  291,  292},
+    {  185,  186,  235,  237,  292,  293},
+    {  186,  187,  236,  238,  293,  294},
+    {  187,  188,  237,  239,  294,  295},
+    {  188,  189,  238,  240,  295,  296},
+    {  189,  190,  239,  241,  296,  297}, // 240
+    {  190,  191,  240,  242,  297,  298},
+    {  191,  192,  241,  243,  298,  299},
+    {  192,  193,  242,  244,  299,  300},
+    {  193,  243,  245,  300,  301,  302},
+    {  193,  194,  244,  246,  302,  303},
+    {  194,  195,  245,  247,  303,  304},
+    {  195,  196,  246,  248,  304,  305},
+    {  196,  197,  247,  249,  305,  306},
+    {  197,  198,  248,  250,  306,  307},
+    {  198,  199,  249,  251,  307,  308},
+    {  199,  200,  250,  252,  308,  309},
+    {  200,  201,  251,  253,  309,  310},
+    {  201,  252,  254,  310,  311,  312},
+    {  201,  202,  253,  255,  312,  313},
+    {  202,  203,  254,  256,  313,  314},
+    {  203,  204,  255,  257,  314,  315},
+    {  204,  205,  256,  258,  315,  316},
+    {  205,  206,  257,  259,  316,  317},
+    {  206,  207,  258,  260,  317,  318},
+    {  207,  208,  259,  261,  318,  319}, // 260
+    {  208,  209,  260,  262,  319,  320},
+    {  209,  261,  263,  320,  321,  322},
+    {  209,  210,  262,  264,  322,  323},
+    {  210,  211,  263,  265,  323,  324},
+    {  211,  212,  264,  266,  324,  325},
+    {  212,  213,  265,  267,  325,  326},
+    {  213,  214,  266,  268,  326,  327},
+    {  214,  215,  267,  269,  327,  328},
+    {  215,  216,  268,  270,  328,  329},
+    {  169,  216,  217,  269,  329,  330},
+    {  217,  272,  330,  331,  332,  396},
+    {  217,  218,  271,  273,  332,  333},
+    {  218,  219,  272,  274,  333,  334},
+    {  219,  220,  273,  275,  334,  335},
+    {  220,  221,  274,  276,  335,  336},
+    {  221,  222,  275,  277,  336,  337},
+    {  222,  223,  276,  278,  337,  338},
+    {  223,  224,  277,  279,  338,  339},
+    {  224,  225,  278,  280,  339,  340},
+    {  225,  226,  279,  281,  340,  341}, // 280
+    {  226,  280,  282,  341,  342,  343},
+    {  226,  227,  281,  283,  343,  344},
+    {  227,  228,  282,  284,  344,  345},
+    {  228,  229,  283,  285,  345,  346},
+    {  229,  230,  284,  286,  346,  347},
+    {  230,  231,  285,  287,  347,  348},
+    {  231,  232,  286,  288,  348,  349},
+    {  232,  233,  287,  289,  349,  350},
+    {  233,  234,  288,  290,  350,  351},
+    {  234,  235,  289,  291,  351,  352},
+    {  235,  290,  292,  352,  353,  354},
+    {  235,  236,  291,  293,  354,  355},
+    {  236,  237,  292,  294,  355,  356},
+    {  237,  238,  293,  295,  356,  357},
+    {  238,  239,  294,  296,  357,  358},
+    {  239,  240,  295,  297,  358,  359},
+    {  240,  241,  296,  298,  359,  360},
+    {  241,  242,  297,  299,  360,  361},
+    {  242,  243,  298,  300,  361,  362},
+    {  243,  244,  299,  301,  362,  363}, // 300
+    {  244,  300,  302,  363,  364,  365},
+    {  244,  245,  301,  303,  365,  366},
+    {  245,  246,  302,  304,  366,  367},
+    {  246,  247,  303,  305,  367,  368},
+    {  247,  248,  304,  306,  368,  369},
+    {  248,  249,  305,  307,  369,  370},
+    {  249,  250,  306,  308,  370,  371},
+    {  250,  251,  307,  309,  371,  372},
+    {  251,  252,  308,  310,  372,  373},
+    {  252,  253,  309,  311,  373,  374},
+    {  253,  310,  312,  374,  375,  376},
+    {  253,  254,  311,  313,  376,  377},
+    {  254,  255,  312,  314,  377,  378},
+    {  255,  256,  313,  315,  378,  379},
+    {  256,  257,  314,  316,  379,  380},
+    {  257,  258,  315,  317,  380,  381},
+    {  258,  259,  316,  318,  381,  382},
+    {  259,  260,  317,  319,  382,  383},
+    {  260,  261,  318,  320,  383,  384},
+    {  261,  262,  319,  321,  384,  385}, // 320
+    {  262,  320,  322,  385,  386,  387},
+    {  262,  263,  321,  323,  387,  388},
+    {  263,  264,  322,  324,  388,  389},
+    {  264,  265,  323,  325,  389,  390},
+    {  265,  266,  324,  326,  390,  391},
+    {  266,  267,  325,  327,  391,  392},
+    {  267,  268,  326,  328,  392,  393},
+    {  268,  269,  327,  329,  393,  394},
+    {  269,  270,  328,  330,  394,  395},
+    {  217,  270,  271,  329,  395,  396},
+    {  271,  332,  396,  397,  398,  468},
+    {  271,  272,  331,  333,  398,  399},
+    {  272,  273,  332,  334,  399,  400},
+    {  273,  274,  333,  335,  400,  401},
+    {  274,  275,  334,  336,  401,  402},
+    {  275,  276,  335,  337,  402,  403},
+    {  276,  277,  336,  338,  403,  404},
+    {  277,  278,  337,  339,  404,  405},
+    {  278,  279,  338,  340,  405,  406},
+    {  279,  280,  339,  341,  406,  407}, // 340
+    {  280,  281,  340,  342,  407,  408},
+    {  281,  341,  343,  408,  409,  410},
+    {  281,  282,  342,  344,  410,  411},
+    {  282,  283,  343,  345,  411,  412},
+    {  283,  284,  344,  346,  412,  413},
+    {  284,  285,  345,  347,  413,  414},
+    {  285,  286,  346,  348,  414,  415},
+    {  286,  287,  347,  349,  415,  416},
+    {  287,  288,  348,  350,  416,  417},
+    {  288,  289,  349,  351,  417,  418},
+    {  289,  290,  350,  352,  418,  419},
+    {  290,  291,  351,  353,  419,  420},
+    {  291,  352,  354,  420,  421,  422},
+    {  291,  292,  353,  355,  422,  423},
+    {  292,  293,  354,  356,  423,  424},
+    {  293,  294,  355,  357,  424,  425},
+    {  294,  295,  356,  358,  425,  426},
+    {  295,  296,  357,  359,  426,  427},
+    {  296,  297,  358,  360,  427,  428},
+    {  297,  298,  359,  361,  428,  429}, // 360
+    {  298,  299,  360,  362,  429,  430},
+    {  299,  300,  361,  363,  430,  431},
+    {  300,  301,  362,  364,  431,  432},
+    {  301,  363,  365,  432,  433,  434},
+    {  301,  302,  364,  366,  434,  435},
+    {  302,  303,  365,  367,  435,  436},
+    {  303,  304,  366,  368,  436,  437},
+    {  304,  305,  367,  369,  437,  438},
+    {  305,  306,  368,  370,  438,  439},
+    {  306,  307,  369,  371,  439,  440},
+    {  307,  308,  370,  372,  440,  441},
+    {  308,  309,  371,  373,  441,  442},
+    {  309,  310,  372,  374,  442,  443},
+    {  310,  311,  373,  375,  443,  444},
+    {  311,  374,  376,  444,  445,  446},
+    {  311,  312,  375,  377,  446,  447},
+    {  312,  313,  376,  378,  447,  448},
+    {  313,  314,  377,  379,  448,  449},
+    {  314,  315,  378,  380,  449,  450},
+    {  315,  316,  379,  381,  450,  451}, // 380
+    {  316,  317,  380,  382,  451,  452},
+    {  317,  318,  381,  383,  452,  453},
+    {  318,  319,  382,  384,  453,  454},
+    {  319,  320,  383,  385,  454,  455},
+    {  320,  321,  384,  386,  455,  456},
+    {  321,  385,  387,  456,  457,  458},
+    {  321,  322,  386,  388,  458,  459},
+    {  322,  323,  387,  389,  459,  460},
+    {  323,  324,  388,  390,  460,  461},
+    {  324,  325,  389,  391,  461,  462},
+    {  325,  326,  390,  392,  462,  463},
+    {  326,  327,  391,  393,  463,  464},
+    {  327,  328,  392,  394,  464,  465},
+    {  328,  329,  393,  395,  465,  466},
+    {  329,  330,  394,  396,  466,  467},
+    {  271,  330,  331,  395,  467,  468},
+    {  331,  398,  468,  469,  470,  546},
+    {  331,  332,  397,  399,  470,  471},
+    {  332,  333,  398,  400,  471,  472},
+    {  333,  334,  399,  401,  472,  473}, // 400
+    {  334,  335,  400,  402,  473,  474},
+    {  335,  336,  401,  403,  474,  475},
+    {  336,  337,  402,  404,  475,  476},
+    {  337,  338,  403,  405,  476,  477},
+    {  338,  339,  404,  406,  477,  478},
+    {  339,  340,  405,  407,  478,  479},
+    {  340,  341,  406,  408,  479,  480},
+    {  341,  342,  407,  409,  480,  481},
+    {  342,  408,  410,  481,  482,  483},
+    {  342,  343,  409,  411,  483,  484},
+    {  343,  344,  410,  412,  484,  485},
+    {  344,  345,  411,  413,  485,  486},
+    {  345,  346,  412,  414,  486,  487},
+    {  346,  347,  413,  415,  487,  488},
+    {  347,  348,  414,  416,  488,  489},
+    {  348,  349,  415,  417,  489,  490},
+    {  349,  350,  416,  418,  490,  491},
+    {  350,  351,  417,  419,  491,  492},
+    {  351,  352,  418,  420,  492,  493},
+    {  352,  353,  419,  421,  493,  494}, // 420
+    {  353,  420,  422,  494,  495,  496},
+    {  353,  354,  421,  423,  496,  497},
+    {  354,  355,  422,  424,  497,  498},
+    {  355,  356,  423,  425,  498,  499},
+    {  356,  357,  424,  426,  499,  500},
+    {  357,  358,  425,  427,  500,  501},
+    {  358,  359,  426,  428,  501,  502},
+    {  359,  360,  427,  429,  502,  503},
+    {  360,  361,  428,  430,  503,  504},
+    {  361,  362,  429,  431,  504,  505},
+    {  362,  363,  430,  432,  505,  506},
+    {  363,  364,  431,  433,  506,  507},
+    {  364,  432,  434,  507,  508,  509},
+    {  364,  365,  433,  435,  509,  510},
+    {  365,  366,  434,  436,  510,  511},
+    {  366,  367,  435,  437,  511,  512},
+    {  367,  368,  436,  438,  512,  513},
+    {  368,  369,  437,  439,  513,  514},
+    {  369,  370,  438,  440,  514,  515},
+    {  370,  371,  439,  441,  515,  516}, // 440
+    {  371,  372,  440,  442,  516,  517},
+    {  372,  373,  441,  443,  517,  518},
+    {  373,  374,  442,  444,  518,  519},
+    {  374,  375,  443,  445,  519,  520},
+    {  375,  444,  446,  520,  521,  522},
+    {  375,  376,  445,  447,  522,  523},
+    {  376,  377,  446,  448,  523,  524},
+    {  377,  378,  447,  449,  524,  525},
+    {  378,  379,  448,  450,  525,  526},
+    {  379,  380,  449,  451,  526,  527},
+    {  380,  381,  450,  452,  527,  528},
+    {  381,  382,  451,  453,  528,  529},
+    {  382,  383,  452,  454,  529,  530},
+    {  383,  384,  453,  455,  530,  531},
+    {  384,  385,  454,  456,  531,  532},
+    {  385,  386,  455,  457,  532,  533},
+    {  386,  456,  458,  533,  534,  535},
+    {  386,  387,  457,  459,  535,  536},
+    {  387,  388,  458,  460,  536,  537},
+    {  388,  389,  459,  461,  537,  538}, // 460
+    {  389,  390,  460,  462,  538,  539},
+    {  390,  391,  461,  463,  539,  540},
+    {  391,  392,  462,  464,  540,  541},
+    {  392,  393,  463,  465,  541,  542},
+    {  393,  394,  464,  466,  542,  543},
+    {  394,  395,  465,  467,  543,  544},
+    {  395,  396,  466,  468,  544,  545},
+    {  331,  396,  397,  467,  545,  546},
+    {  397,  470,  546,  547,  548,  630},
+    {  397,  398,  469,  471,  548,  549},
+    {  398,  399,  470,  472,  549,  550},
+    {  399,  400,  471,  473,  550,  551},
+    {  400,  401,  472,  474,  551,  552},
+    {  401,  402,  473,  475,  552,  553},
+    {  402,  403,  474,  476,  553,  554},
+    {  403,  404,  475,  477,  554,  555},
+    {  404,  405,  476,  478,  555,  556},
+    {  405,  406,  477,  479,  556,  557},
+    {  406,  407,  478,  480,  557,  558},
+    {  407,  408,  479,  481,  558,  559}, // 480
+    {  408,  409,  480,  482,  559,  560},
+    {  409,  481,  483,  560,  561,  562},
+    {  409,  410,  482,  484,  562,  563},
+    {  410,  411,  483,  485,  563,  564},
+    {  411,  412,  484,  486,  564,  565},
+    {  412,  413,  485,  487,  565,  566},
+    {  413,  414,  486,  488,  566,  567},
+    {  414,  415,  487,  489,  567,  568},
+    {  415,  416,  488,  490,  568,  569},
+    {  416,  417,  489,  491,  569,  570},
+    {  417,  418,  490,  492,  570,  571},
+    {  418,  419,  491,  493,  571,  572},
+    {  419,  420,  492,  494,  572,  573},
+    {  420,  421,  493,  495,  573,  574},
+    {  421,  494,  496,  574,  575,  576},
+    {  421,  422,  495,  497,  576,  577},
+    {  422,  423,  496,  498,  577,  578},
+    {  423,  424,  497,  499,  578,  579},
+    {  424,  425,  498,  500,  579,  580},
+    {  425,  426,  499,  501,  580,  581}, // 500
+    {  426,  427,  500,  502,  581,  582},
+    {  427,  428,  501,  503,  582,  583},
+    {  428,  429,  502,  504,  583,  584},
+    {  429,  430,  503,  505,  584,  585},
+    {  430,  431,  504,  506,  585,  586},
+    {  431,  432,  505,  507,  586,  587},
+    {  432,  433,  506,  508,  587,  588},
+    {  433,  507,  509,  588,  589,  590},
+    {  433,  434,  508,  510,  590,  591},
+    {  434,  435,  509,  511,  591,  592},
+    {  435,  436,  510,  512,  592,  593},
+    {  436,  437,  511,  513,  593,  594},
+    {  437,  438,  512,  514,  594,  595},
+    {  438,  439,  513,  515,  595,  596},
+    {  439,  440,  514,  516,  596,  597},
+    {  440,  441,  515,  517,  597,  598},
+    {  441,  442,  516,  518,  598,  599},
+    {  442,  443,  517,  519,  599,  600},
+    {  443,  444,  518,  520,  600,  601},
+    {  444,  445,  519,  521,  601,  602}, // 520
+    {  445,  520,  522,  602,  603,  604},
+    {  445,  446,  521,  523,  604,  605},
+    {  446,  447,  522,  524,  605,  606},
+    {  447,  448,  523,  525,  606,  607},
+    {  448,  449,  524,  526,  607,  608},
+    {  449,  450,  525,  527,  608,  609},
+    {  450,  451,  526,  528,  609,  610},
+    {  451,  452,  527,  529,  610,  611},
+    {  452,  453,  528,  530,  611,  612},
+    {  453,  454,  529,  531,  612,  613},
+    {  454,  455,  530,  532,  613,  614},
+    {  455,  456,  531,  533,  614,  615},
+    {  456,  457,  532,  534,  615,  616},
+    {  457,  533,  535,  616,  617,  618},
+    {  457,  458,  534,  536,  618,  619},
+    {  458,  459,  535,  537,  619,  620},
+    {  459,  460,  536,  538,  620,  621},
+    {  460,  461,  537,  539,  621,  622},
+    {  461,  462,  538,  540,  622,  623},
+    {  462,  463,  539,  541,  623,  624}, // 540
+    {  463,  464,  540,  542,  624,  625},
+    {  464,  465,  541,  543,  625,  626},
+    {  465,  466,  542,  544,  626,  627},
+    {  466,  467,  543,  545,  627,  628},
+    {  467,  468,  544,  546,  628,  629},
+    {  397,  468,  469,  545,  629,  630},
+    {  469,  548,  630,  631,  632,  720},
+    {  469,  470,  547,  549,  632,  633},
+    {  470,  471,  548,  550,  633,  634},
+    {  471,  472,  549,  551,  634,  635},
+    {  472,  473,  550,  552,  635,  636},
+    {  473,  474,  551,  553,  636,  637},
+    {  474,  475,  552,  554,  637,  638},
+    {  475,  476,  553,  555,  638,  639},
+    {  476,  477,  554,  556,  639,  640},
+    {  477,  478,  555,  557,  640,  641},
+    {  478,  479,  556,  558,  641,  642},
+    {  479,  480,  557,  559,  642,  643},
+    {  480,  481,  558,  560,  643,  644},
+    {  481,  482,  559,  561,  644,  645}, // 560
+    {  482,  560,  562,  645,  646,  647},
+    {  482,  483,  561,  563,  647,  648},
+    {  483,  484,  562,  564,  648,  649},
+    {  484,  485,  563,  565,  649,  650},
+    {  485,  486,  564,  566,  650,  651},
+    {  486,  487,  565,  567,  651,  652},
+    {  487,  488,  566,  568,  652,  653},
+    {  488,  489,  567,  569,  653,  654},
+    {  489,  490,  568,  570,  654,  655},
+    {  490,  491,  569,  571,  655,  656},
+    {  491,  492,  570,  572,  656,  657},
+    {  492,  493,  571,  573,  657,  658},
+    {  493,  494,  572,  574,  658,  659},
+    {  494,  495,  573,  575,  659,  660},
+    {  495,  574,  576,  660,  661,  662},
+    {  495,  496,  575,  577,  662,  663},
+    {  496,  497,  576,  578,  663,  664},
+    {  497,  498,  577,  579,  664,  665},
+    {  498,  499,  578,  580,  665,  666},
+    {  499,  500,  579,  581,  666,  667}, // 580
+    {  500,  501,  580,  582,  667,  668},
+    {  501,  502,  581,  583,  668,  669},
+    {  502,  503,  582,  584,  669,  670},
+    {  503,  504,  583,  585,  670,  671},
+    {  504,  505,  584,  586,  671,  672},
+    {  505,  506,  585,  587,  672,  673},
+    {  506,  507,  586,  588,  673,  674},
+    {  507,  508,  587,  589,  674,  675},
+    {  508,  588,  590,  675,  676,  677},
+    {  508,  509,  589,  591,  677,  678},
+    {  509,  510,  590,  592,  678,  679},
+    {  510,  511,  591,  593,  679,  680},
+    {  511,  512,  592,  594,  680,  681},
+    {  512,  513,  593,  595,  681,  682},
+    {  513,  514,  594,  596,  682,  683},
+    {  514,  515,  595,  597,  683,  684},
+    {  515,  516,  596,  598,  684,  685},
+    {  516,  517,  597,  599,  685,  686},
+    {  517,  518,  598,  600,  686,  687},
+    {  518,  519,  599,  601,  687,  688}, // 600
+    {  519,  520,  600,  602,  688,  689},
+    {  520,  521,  601,  603,  689,  690},
+    {  521,  602,  604,  690,  691,  692},
+    {  521,  522,  603,  605,  692,  693},
+    {  522,  523,  604,  606,  693,  694},
+    {  523,  524,  605,  607,  694,  695},
+    {  524,  525,  606,  608,  695,  696},
+    {  525,  526,  607,  609,  696,  697},
+    {  526,  527,  608,  610,  697,  698},
+    {  527,  528,  609,  611,  698,  699},
+    {  528,  529,  610,  612,  699,  700},
+    {  529,  530,  611,  613,  700,  701},
+    {  530,  531,  612,  614,  701,  702},
+    {  531,  532,  613,  615,  702,  703},
+    {  532,  533,  614,  616,  703,  704},
+    {  533,  534,  615,  617,  704,  705},
+    {  534,  616,  618,  705,  706,  707},
+    {  534,  535,  617,  619,  707,  708},
+    {  535,  536,  618,  620,  708,  709},
+    {  536,  537,  619,  621,  709,  710}, // 620
+    {  537,  538,  620,  622,  710,  711},
+    {  538,  539,  621,  623,  711,  712},
+    {  539,  540,  622,  624,  712,  713},
+    {  540,  541,  623,  625,  713,  714},
+    {  541,  542,  624,  626,  714,  715},
+    {  542,  543,  625,  627,  715,  716},
+    {  543,  544,  626,  628,  716,  717},
+    {  544,  545,  627,  629,  717,  718},
+    {  545,  546,  628,  630,  718,  719},
+    {  469,  546,  547,  629,  719,  720},
+    {  547,  632,  720,  721,  722,  816},
+    {  547,  548,  631,  633,  722,  723},
+    {  548,  549,  632,  634,  723,  724},
+    {  549,  550,  633,  635,  724,  725},
+    {  550,  551,  634,  636,  725,  726},
+    {  551,  552,  635,  637,  726,  727},
+    {  552,  553,  636,  638,  727,  728},
+    {  553,  554,  637,  639,  728,  729},
+    {  554,  555,  638,  640,  729,  730},
+    {  555,  556,  639,  641,  730,  731}, // 640
+    {  556,  557,  640,  642,  731,  732},
+    {  557,  558,  641,  643,  732,  733},
+    {  558,  559,  642,  644,  733,  734},
+    {  559,  560,  643,  645,  734,  735},
+    {  560,  561,  644,  646,  735,  736},
+    {  561,  645,  647,  736,  737,  738},
+    {  561,  562,  646,  648,  738,  739},
+    {  562,  563,  647,  649,  739,  740},
+    {  563,  564,  648,  650,  740,  741},
+    {  564,  565,  649,  651,  741,  742},
+    {  565,  566,  650,  652,  742,  743},
+    {  566,  567,  651,  653,  743,  744},
+    {  567,  568,  652,  654,  744,  745},
+    {  568,  569,  653,  655,  745,  746},
+    {  569,  570,  654,  656,  746,  747},
+    {  570,  571,  655,  657,  747,  748},
+    {  571,  572,  656,  658,  748,  749},
+    {  572,  573,  657,  659,  749,  750},
+    {  573,  574,  658,  660,  750,  751},
+    {  574,  575,  659,  661,  751,  752}, // 660
+    {  575,  660,  662,  752,  753,  754},
+    {  575,  576,  661,  663,  754,  755},
+    {  576,  577,  662,  664,  755,  756},
+    {  577,  578,  663,  665,  756,  757},
+    {  578,  579,  664,  666,  757,  758},
+    {  579,  580,  665,  667,  758,  759},
+    {  580,  581,  666,  668,  759,  760},
+    {  581,  582,  667,  669,  760,  761},
+    {  582,  583,  668,  670,  761,  762},
+    {  583,  584,  669,  671,  762,  763},
+    {  584,  585,  670,  672,  763,  764},
+    {  585,  586,  671,  673,  764,  765},
+    {  586,  587,  672,  674,  765,  766},
+    {  587,  588,  673,  675,  766,  767},
+    {  588,  589,  674,  676,  767,  768},
+    {  589,  675,  677,  768,  769,  770},
+    {  589,  590,  676,  678,  770,  771},
+    {  590,  591,  677,  679,  771,  772},
+    {  591,  592,  678,  680,  772,  773},
+    {  592,  593,  679,  681,  773,  774}, // 680
+    {  593,  594,  680,  682,  774,  775},
+    {  594,  595,  681,  683,  775,  776},
+    {  595,  596,  682,  684,  776,  777},
+    {  596,  597,  683,  685,  777,  778},
+    {  597,  598,  684,  686,  778,  779},
+    {  598,  599,  685,  687,  779,  780},
+    {  599,  600,  686,  688,  780,  781},
+    {  600,  601,  687,  689,  781,  782},
+    {  601,  602,  688,  690,  782,  783},
+    {  602,  603,  689,  691,  783,  784},
+    {  603,  690,  692,  784,  785,  786},
+    {  603,  604,  691,  693,  786,  787},
+    {  604,  605,  692,  694,  787,  788},
+    {  605,  606,  693,  695,  788,  789},
+    {  606,  607,  694,  696,  789,  790},
+    {  607,  608,  695,  697,  790,  791},
+    {  608,  609,  696,  698,  791,  792},
+    {  609,  610,  697,  699,  792,  793},
+    {  610,  611,  698,  700,  793,  794},
+    {  611,  612,  699,  701,  794,  795}, // 700
+    {  612,  613,  700,  702,  795,  796},
+    {  613,  614,  701,  703,  796,  797},
+    {  614,  615,  702,  704,  797,  798},
+    {  615,  616,  703,  705,  798,  799},
+    {  616,  617,  704,  706,  799,  800},
+    {  617,  705,  707,  800,  801,  802},
+    {  617,  618,  706,  708,  802,  803},
+    {  618,  619,  707,  709,  803,  804},
+    {  619,  620,  708,  710,  804,  805},
+    {  620,  621,  709,  711,  805,  806},
+    {  621,  622,  710,  712,  806,  807},
+    {  622,  623,  711,  713,  807,  808},
+    {  623,  624,  712,  714,  808,  809},
+    {  624,  625,  713,  715,  809,  810},
+    {  625,  626,  714,  716,  810,  811},
+    {  626,  627,  715,  717,  811,  812},
+    {  627,  628,  716,  718,  812,  813},
+    {  628,  629,  717,  719,  813,  814},
+    {  629,  630,  718,  720,  814,  815},
+    {  547,  630,  631,  719,  815,  816}, // 720
+    {  631,  722,  816,  817,  818,  918},
+    {  631,  632,  721,  723,  818,  819},
+    {  632,  633,  722,  724,  819,  820},
+    {  633,  634,  723,  725,  820,  821},
+    {  634,  635,  724,  726,  821,  822},
+    {  635,  636,  725,  727,  822,  823},
+    {  636,  637,  726,  728,  823,  824},
+    {  637,  638,  727,  729,  824,  825},
+    {  638,  639,  728,  730,  825,  826},
+    {  639,  640,  729,  731,  826,  827},
+    {  640,  641,  730,  732,  827,  828},
+    {  641,  642,  731,  733,  828,  829},
+    {  642,  643,  732,  734,  829,  830},
+    {  643,  644,  733,  735,  830,  831},
+    {  644,  645,  734,  736,  831,  832},
+    {  645,  646,  735,  737,  832,  833},
+    {  646,  736,  738,  833,  834,  835},
+    {  646,  647,  737,  739,  835,  836},
+    {  647,  648,  738,  740,  836,  837},
+    {  648,  649,  739,  741,  837,  838}, // 740
+    {  649,  650,  740,  742,  838,  839},
+    {  650,  651,  741,  743,  839,  840},
+    {  651,  652,  742,  744,  840,  841},
+    {  652,  653,  743,  745,  841,  842},
+    {  653,  654,  744,  746,  842,  843},
+    {  654,  655,  745,  747,  843,  844},
+    {  655,  656,  746,  748,  844,  845},
+    {  656,  657,  747,  749,  845,  846},
+    {  657,  658,  748,  750,  846,  847},
+    {  658,  659,  749,  751,  847,  848},
+    {  659,  660,  750,  752,  848,  849},
+    {  660,  661,  751,  753,  849,  850},
+    {  661,  752,  754,  850,  851,  852},
+    {  661,  662,  753,  755,  852,  853},
+    {  662,  663,  754,  756,  853,  854},
+    {  663,  664,  755,  757,  854,  855},
+    {  664,  665,  756,  758,  855,  856},
+    {  665,  666,  757,  759,  856,  857},
+    {  666,  667,  758,  760,  857,  858},
+    {  667,  668,  759,  761,  858,  859}, // 760
+    {  668,  669,  760,  762,  859,  860},
+    {  669,  670,  761,  763,  860,  861},
+    {  670,  671,  762,  764,  861,  862},
+    {  671,  672,  763,  765,  862,  863},
+    {  672,  673,  764,  766,  863,  864},
+    {  673,  674,  765,  767,  864,  865},
+    {  674,  675,  766,  768,  865,  866},
+    {  675,  676,  767,  769,  866,  867},
+    {  676,  768,  770,  867,  868,  869},
+    {  676,  677,  769,  771,  869,  870},
+    {  677,  678,  770,  772,  870,  871},
+    {  678,  679,  771,  773,  871,  872},
+    {  679,  680,  772,  774,  872,  873},
+    {  680,  681,  773,  775,  873,  874},
+    {  681,  682,  774,  776,  874,  875},
+    {  682,  683,  775,  777,  875,  876},
+    {  683,  684,  776,  778,  876,  877},
+    {  684,  685,  777,  779,  877,  878},
+    {  685,  686,  778,  780,  878,  879},
+    {  686,  687,  779,  781,  879,  880}, // 780
+    {  687,  688,  780,  782,  880,  881},
+    {  688,  689,  781,  783,  881,  882},
+    {  689,  690,  782,  784,  882,  883},
+    {  690,  691,  783,  785,  883,  884},
+    {  691,  784,  786,  884,  885,  886},
+    {  691,  692,  785,  787,  886,  887},
+    {  692,  693,  786,  788,  887,  888},
+    {  693,  694,  787,  789,  888,  889},
+    {  694,  695,  788,  790,  889,  890},
+    {  695,  696,  789,  791,  890,  891},
+    {  696,  697,  790,  792,  891,  892},
+    {  697,  698,  791,  793,  892,  893},
+    {  698,  699,  792,  794,  893,  894},
+    {  699,  700,  793,  795,  894,  895},
+    {  700,  701,  794,  796,  895,  896},
+    {  701,  702,  795,  797,  896,  897},
+    {  702,  703,  796,  798,  897,  898},
+    {  703,  704,  797,  799,  898,  899},
+    {  704,  705,  798,  800,  899,  900},
+    {  705,  706,  799,  801,  900,  901}, // 800
+    {  706,  800,  802,  901,  902,  903},
+    {  706,  707,  801,  803,  903,  904},
+    {  707,  708,  802,  804,  904,  905},
+    {  708,  709,  803,  805,  905,  906},
+    {  709,  710,  804,  806,  906,  907},
+    {  710,  711,  805,  807,  907,  908},
+    {  711,  712,  806,  808,  908,  909},
+    {  712,  713,  807,  809,  909,  910},
+    {  713,  714,  808,  810,  910,  911},
+    {  714,  715,  809,  811,  911,  912},
+    {  715,  716,  810,  812,  912,  913},
+    {  716,  717,  811,  813,  913,  914},
+    {  717,  718,  812,  814,  914,  915},
+    {  718,  719,  813,  815,  915,  916},
+    {  719,  720,  814,  816,  916,  917},
+    {  631,  720,  721,  815,  917,  918},
+    {  721,  818,  918,  919,  920,  1026},
+    {  721,  722,  817,  819,  920,  921},
+    {  722,  723,  818,  820,  921,  922},
+    {  723,  724,  819,  821,  922,  923}, // 820
+    {  724,  725,  820,  822,  923,  924},
+    {  725,  726,  821,  823,  924,  925},
+    {  726,  727,  822,  824,  925,  926},
+    {  727,  728,  823,  825,  926,  927},
+    {  728,  729,  824,  826,  927,  928},
+    {  729,  730,  825,  827,  928,  929},
+    {  730,  731,  826,  828,  929,  930},
+    {  731,  732,  827,  829,  930,  931},
+    {  732,  733,  828,  830,  931,  932},
+    {  733,  734,  829,  831,  932,  933},
+    {  734,  735,  830,  832,  933,  934},
+    {  735,  736,  831,  833,  934,  935},
+    {  736,  737,  832,  834,  935,  936},
+    {  737,  833,  835,  936,  937,  938},
+    {  737,  738,  834,  836,  938,  939},
+    {  738,  739,  835,  837,  939,  940},
+    {  739,  740,  836,  838,  940,  941},
+    {  740,  741,  837,  839,  941,  942},
+    {  741,  742,  838,  840,  942,  943},
+    {  742,  743,  839,  841,  943,  944}, // 840
+    {  743,  744,  840,  842,  944,  945},
+    {  744,  745,  841,  843,  945,  946},
+    {  745,  746,  842,  844,  946,  947},
+    {  746,  747,  843,  845,  947,  948},
+    {  747,  748,  844,  846,  948,  949},
+    {  748,  749,  845,  847,  949,  950},
+    {  749,  750,  846,  848,  950,  951},
+    {  750,  751,  847,  849,  951,  952},
+    {  751,  752,  848,  850,  952,  953},
+    {  752,  753,  849,  851,  953,  954},
+    {  753,  850,  852,  954,  955,  956},
+    {  753,  754,  851,  853,  956,  957},
+    {  754,  755,  852,  854,  957,  958},
+    {  755,  756,  853,  855,  958,  959},
+    {  756,  757,  854,  856,  959,  960},
+    {  757,  758,  855,  857,  960,  961},
+    {  758,  759,  856,  858,  961,  962},
+    {  759,  760,  857,  859,  962,  963},
+    {  760,  761,  858,  860,  963,  964},
+    {  761,  762,  859,  861,  964,  965}, // 860
+    {  762,  763,  860,  862,  965,  966},
+    {  763,  764,  861,  863,  966,  967},
+    {  764,  765,  862,  864,  967,  968},
+    {  765,  766,  863,  865,  968,  969},
+    {  766,  767,  864,  866,  969,  970},
+    {  767,  768,  865,  867,  970,  971},
+    {  768,  769,  866,  868,  971,  972},
+    {  769,  867,  869,  972,  973,  974},
+    {  769,  770,  868,  870,  974,  975},
+    {  770,  771,  869,  871,  975,  976},
+    {  771,  772,  870,  872,  976,  977},
+    {  772,  773,  871,  873,  977,  978},
+    {  773,  774,  872,  874,  978,  979},
+    {  774,  775,  873,  875,  979,  980},
+    {  775,  776,  874,  876,  980,  981},
+    {  776,  777,  875,  877,  981,  982},
+    {  777,  778,  876,  878,  982,  983},
+    {  778,  779,  877,  879,  983,  984},
+    {  779,  780,  878,  880,  984,  985},
+    {  780,  781,  879,  881,  985,  986}, // 880
+    {  781,  782,  880,  882,  986,  987},
+    {  782,  783,  881,  883,  987,  988},
+    {  783,  784,  882,  884,  988,  989},
+    {  784,  785,  883,  885,  989,  990},
+    {  785,  884,  886,  990,  991,  992},
+    {  785,  786,  885,  887,  992,  993},
+    {  786,  787,  886,  888,  993,  994},
+    {  787,  788,  887,  889,  994,  995},
+    {  788,  789,  888,  890,  995,  996},
+    {  789,  790,  889,  891,  996,  997},
+    {  790,  791,  890,  892,  997,  998},
+    {  791,  792,  891,  893,  998,  999},
+    {  792,  793,  892,  894,  999,  1000},
+    {  793,  794,  893,  895,  1000,  1001},
+    {  794,  795,  894,  896,  1001,  1002},
+    {  795,  796,  895,  897,  1002,  1003},
+    {  796,  797,  896,  898,  1003,  1004},
+    {  797,  798,  897,  899,  1004,  1005},
+    {  798,  799,  898,  900,  1005,  1006},
+    {  799,  800,  899,  901,  1006,  1007}, // 900
+    {  800,  801,  900,  902,  1007,  1008},
+    {  801,  901,  903,  1008,  1009,  1010},
+    {  801,  802,  902,  904,  1010,  1011},
+    {  802,  803,  903,  905,  1011,  1012},
+    {  803,  804,  904,  906,  1012,  1013},
+    {  804,  805,  905,  907,  1013,  1014},
+    {  805,  806,  906,  908,  1014,  1015},
+    {  806,  807,  907,  909,  1015,  1016},
+    {  807,  808,  908,  910,  1016,  1017},
+    {  808,  809,  909,  911,  1017,  1018},
+    {  809,  810,  910,  912,  1018,  1019},
+    {  810,  811,  911,  913,  1019,  1020},
+    {  811,  812,  912,  914,  1020,  1021},
+    {  812,  813,  913,  915,  1021,  1022},
+    {  813,  814,  914,  916,  1022,  1023},
+    {  814,  815,  915,  917,  1023,  1024},
+    {  815,  816,  916,  918,  1024,  1025},
+    {  721,  816,  817,  917,  1025,  1026},
+    {  817,  920,  1026,  1027,  1028,  1140},
+    {  817,  818,  919,  921,  1028,  1029}, // 920
+    {  818,  819,  920,  922,  1029,  1030},
+    {  819,  820,  921,  923,  1030,  1031},
+    {  820,  821,  922,  924,  1031,  1032},
+    {  821,  822,  923,  925,  1032,  1033},
+    {  822,  823,  924,  926,  1033,  1034},
+    {  823,  824,  925,  927,  1034,  1035},
+    {  824,  825,  926,  928,  1035,  1036},
+    {  825,  826,  927,  929,  1036,  1037},
+    {  826,  827,  928,  930,  1037,  1038},
+    {  827,  828,  929,  931,  1038,  1039},
+    {  828,  829,  930,  932,  1039,  1040},
+    {  829,  830,  931,  933,  1040,  1041},
+    {  830,  831,  932,  934,  1041,  1042},
+    {  831,  832,  933,  935,  1042,  1043},
+    {  832,  833,  934,  936,  1043,  1044},
+    {  833,  834,  935,  937,  1044,  1045},
+    {  834,  936,  938,  1045,  1046,  1047},
+    {  834,  835,  937,  939,  1047,  1048},
+    {  835,  836,  938,  940,  1048,  1049},
+    {  836,  837,  939,  941,  1049,  1050}, // 940
+    {  837,  838,  940,  942,  1050,  1051},
+    {  838,  839,  941,  943,  1051,  1052},
+    {  839,  840,  942,  944,  1052,  1053},
+    {  840,  841,  943,  945,  1053,  1054},
+    {  841,  842,  944,  946,  1054,  1055},
+    {  842,  843,  945,  947,  1055,  1056},
+    {  843,  844,  946,  948,  1056,  1057},
+    {  844,  845,  947,  949,  1057,  1058},
+    {  845,  846,  948,  950,  1058,  1059},
+    {  846,  847,  949,  951,  1059,  1060},
+    {  847,  848,  950,  952,  1060,  1061},
+    {  848,  849,  951,  953,  1061,  1062},
+    {  849,  850,  952,  954,  1062,  1063},
+    {  850,  851,  953,  955,  1063,  1064},
+    {  851,  954,  956,  1064,  1065,  1066},
+    {  851,  852,  955,  957,  1066,  1067},
+    {  852,  853,  956,  958,  1067,  1068},
+    {  853,  854,  957,  959,  1068,  1069},
+    {  854,  855,  958,  960,  1069,  1070},
+    {  855,  856,  959,  961,  1070,  1071}, // 960
+    {  856,  857,  960,  962,  1071,  1072},
+    {  857,  858,  961,  963,  1072,  1073},
+    {  858,  859,  962,  964,  1073,  1074},
+    {  859,  860,  963,  965,  1074,  1075},
+    {  860,  861,  964,  966,  1075,  1076},
+    {  861,  862,  965,  967,  1076,  1077},
+    {  862,  863,  966,  968,  1077,  1078},
+    {  863,  864,  967,  969,  1078,  1079},
+    {  864,  865,  968,  970,  1079,  1080},
+    {  865,  866,  969,  971,  1080,  1081},
+    {  866,  867,  970,  972,  1081,  1082},
+    {  867,  868,  971,  973,  1082,  1083},
+    {  868,  972,  974,  1083,  1084,  1085},
+    {  868,  869,  973,  975,  1085,  1086},
+    {  869,  870,  974,  976,  1086,  1087},
+    {  870,  871,  975,  977,  1087,  1088},
+    {  871,  872,  976,  978,  1088,  1089},
+    {  872,  873,  977,  979,  1089,  1090},
+    {  873,  874,  978,  980,  1090,  1091},
+    {  874,  875,  979,  981,  1091,  1092}, // 980
+    {  875,  876,  980,  982,  1092,  1093},
+    {  876,  877,  981,  983,  1093,  1094},
+    {  877,  878,  982,  984,  1094,  1095},
+    {  878,  879,  983,  985,  1095,  1096},
+    {  879,  880,  984,  986,  1096,  1097},
+    {  880,  881,  985,  987,  1097,  1098},
+    {  881,  882,  986,  988,  1098,  1099},
+    {  882,  883,  987,  989,  1099,  1100},
+    {  883,  884,  988,  990,  1100,  1101},
+    {  884,  885,  989,  991,  1101,  1102},
+    {  885,  990,  992,  1102,  1103,  1104},
+    {  885,  886,  991,  993,  1104,  1105},
+    {  886,  887,  992,  994,  1105,  1106},
+    {  887,  888,  993,  995,  1106,  1107},
+    {  888,  889,  994,  996,  1107,  1108},
+    {  889,  890,  995,  997,  1108,  1109},
+    {  890,  891,  996,  998,  1109,  1110},
+    {  891,  892,  997,  999,  1110,  1111},
+    {  892,  893,  998,  1000,  1111,  1112},
+    {  893,  894,  999,  1001,  1112,  1113}, // 1000
+    {  894,  895,  1000,  1002,  1113,  1114},
+    {  895,  896,  1001,  1003,  1114,  1115},
+    {  896,  897,  1002,  1004,  1115,  1116},
+    {  897,  898,  1003,  1005,  1116,  1117},
+    {  898,  899,  1004,  1006,  1117,  1118},
+    {  899,  900,  1005,  1007,  1118,  1119},
+    {  900,  901,  1006,  1008,  1119,  1120},
+    {  901,  902,  1007,  1009,  1120,  1121},
+    {  902,  1008,  1010,  1121,  1122,  1123},
+    {  902,  903,  1009,  1011,  1123,  1124},
+    {  903,  904,  1010,  1012,  1124,  1125},
+    {  904,  905,  1011,  1013,  1125,  1126},
+    {  905,  906,  1012,  1014,  1126,  1127},
+    {  906,  907,  1013,  1015,  1127,  1128},
+    {  907,  908,  1014,  1016,  1128,  1129},
+    {  908,  909,  1015,  1017,  1129,  1130},
+    {  909,  910,  1016,  1018,  1130,  1131},
+    {  910,  911,  1017,  1019,  1131,  1132},
+    {  911,  912,  1018,  1020,  1132,  1133},
+    {  912,  913,  1019,  1021,  1133,  1134}, // 1020
+    {  913,  914,  1020,  1022,  1134,  1135},
+    {  914,  915,  1021,  1023,  1135,  1136},
+    {  915,  916,  1022,  1024,  1136,  1137},
+    {  916,  917,  1023,  1025,  1137,  1138},
+    {  917,  918,  1024,  1026,  1138,  1139},
+    {  817,  918,  919,  1025,  1139,  1140},
+    {  919,  1028,  1140,  1141,  1142,  1260},
+    {  919,  920,  1027,  1029,  1142,  1143},
+    {  920,  921,  1028,  1030,  1143,  1144},
+    {  921,  922,  1029,  1031,  1144,  1145},
+    {  922,  923,  1030,  1032,  1145,  1146},
+    {  923,  924,  1031,  1033,  1146,  1147},
+    {  924,  925,  1032,  1034,  1147,  1148},
+    {  925,  926,  1033,  1035,  1148,  1149},
+    {  926,  927,  1034,  1036,  1149,  1150},
+    {  927,  928,  1035,  1037,  1150,  1151},
+    {  928,  929,  1036,  1038,  1151,  1152},
+    {  929,  930,  1037,  1039,  1152,  1153},
+    {  930,  931,  1038,  1040,  1153,  1154},
+    {  931,  932,  1039,  1041,  1154,  1155}, // 1040
+    {  932,  933,  1040,  1042,  1155,  1156},
+    {  933,  934,  1041,  1043,  1156,  1157},
+    {  934,  935,  1042,  1044,  1157,  1158},
+    {  935,  936,  1043,  1045,  1158,  1159},
+    {  936,  937,  1044,  1046,  1159,  1160},
+    {  937,  1045,  1047,  1160,  1161,  1162},
+    {  937,  938,  1046,  1048,  1162,  1163},
+    {  938,  939,  1047,  1049,  1163,  1164},
+    {  939,  940,  1048,  1050,  1164,  1165},
+    {  940,  941,  1049,  1051,  1165,  1166},
+    {  941,  942,  1050,  1052,  1166,  1167},
+    {  942,  943,  1051,  1053,  1167,  1168},
+    {  943,  944,  1052,  1054,  1168,  1169},
+    {  944,  945,  1053,  1055,  1169,  1170},
+    {  945,  946,  1054,  1056,  1170,  1171},
+    {  946,  947,  1055,  1057,  1171,  1172},
+    {  947,  948,  1056,  1058,  1172,  1173},
+    {  948,  949,  1057,  1059,  1173,  1174},
+    {  949,  950,  1058,  1060,  1174,  1175},
+    {  950,  951,  1059,  1061,  1175,  1176}, // 1060
+    {  951,  952,  1060,  1062,  1176,  1177},
+    {  952,  953,  1061,  1063,  1177,  1178},
+    {  953,  954,  1062,  1064,  1178,  1179},
+    {  954,  955,  1063,  1065,  1179,  1180},
+    {  955,  1064,  1066,  1180,  1181,  1182},
+    {  955,  956,  1065,  1067,  1182,  1183},
+    {  956,  957,  1066,  1068,  1183,  1184},
+    {  957,  958,  1067,  1069,  1184,  1185},
+    {  958,  959,  1068,  1070,  1185,  1186},
+    {  959,  960,  1069,  1071,  1186,  1187},
+    {  960,  961,  1070,  1072,  1187,  1188},
+    {  961,  962,  1071,  1073,  1188,  1189},
+    {  962,  963,  1072,  1074,  1189,  1190},
+    {  963,  964,  1073,  1075,  1190,  1191},
+    {  964,  965,  1074,  1076,  1191,  1192},
+    {  965,  966,  1075,  1077,  1192,  1193},
+    {  966,  967,  1076,  1078,  1193,  1194},
+    {  967,  968,  1077,  1079,  1194,  1195},
+    {  968,  969,  1078,  1080,  1195,  1196},
+    {  969,  970,  1079,  1081,  1196,  1197}, // 1080
+    {  970,  971,  1080,  1082,  1197,  1198},
+    {  971,  972,  1081,  1083,  1198,  1199},
+    {  972,  973,  1082,  1084,  1199,  1200},
+    {  973,  1083,  1085,  1200,  1201,  1202},
+    {  973,  974,  1084,  1086,  1202,  1203},
+    {  974,  975,  1085,  1087,  1203,  1204},
+    {  975,  976,  1086,  1088,  1204,  1205},
+    {  976,  977,  1087,  1089,  1205,  1206},
+    {  977,  978,  1088,  1090,  1206,  1207},
+    {  978,  979,  1089,  1091,  1207,  1208},
+    {  979,  980,  1090,  1092,  1208,  1209},
+    {  980,  981,  1091,  1093,  1209,  1210},
+    {  981,  982,  1092,  1094,  1210,  1211},
+    {  982,  983,  1093,  1095,  1211,  1212},
+    {  983,  984,  1094,  1096,  1212,  1213},
+    {  984,  985,  1095,  1097,  1213,  1214},
+    {  985,  986,  1096,  1098,  1214,  1215},
+    {  986,  987,  1097,  1099,  1215,  1216},
+    {  987,  988,  1098,  1100,  1216,  1217},
+    {  988,  989,  1099,  1101,  1217,  1218}, // 1100
+    {  989,  990,  1100,  1102,  1218,  1219},
+    {  990,  991,  1101,  1103,  1219,  1220},
+    {  991,  1102,  1104,  1220,  1221,  1222},
+    {  991,  992,  1103,  1105,  1222,  1223},
+    {  992,  993,  1104,  1106,  1223,  1224},
+    {  993,  994,  1105,  1107,  1224,  1225},
+    {  994,  995,  1106,  1108,  1225,  1226},
+    {  995,  996,  1107,  1109,  1226,  1227},
+    {  996,  997,  1108,  1110,  1227,  1228},
+    {  997,  998,  1109,  1111,  1228,  1229},
+    {  998,  999,  1110,  1112,  1229,  1230},
+    {  999,  1000,  1111,  1113,  1230,  1231},
+    {  1000,  1001,  1112,  1114,  1231,  1232},
+    {  1001,  1002,  1113,  1115,  1232,  1233},
+    {  1002,  1003,  1114,  1116,  1233,  1234},
+    {  1003,  1004,  1115,  1117,  1234,  1235},
+    {  1004,  1005,  1116,  1118,  1235,  1236},
+    {  1005,  1006,  1117,  1119,  1236,  1237},
+    {  1006,  1007,  1118,  1120,  1237,  1238},
+    {  1007,  1008,  1119,  1121,  1238,  1239}, // 1120
+    {  1008,  1009,  1120,  1122,  1239,  1240},
+    {  1009,  1121,  1123,  1240,  1241,  1242},
+    {  1009,  1010,  1122,  1124,  1242,  1243},
+    {  1010,  1011,  1123,  1125,  1243,  1244},
+    {  1011,  1012,  1124,  1126,  1244,  1245},
+    {  1012,  1013,  1125,  1127,  1245,  1246},
+    {  1013,  1014,  1126,  1128,  1246,  1247},
+    {  1014,  1015,  1127,  1129,  1247,  1248},
+    {  1015,  1016,  1128,  1130,  1248,  1249},
+    {  1016,  1017,  1129,  1131,  1249,  1250},
+    {  1017,  1018,  1130,  1132,  1250,  1251},
+    {  1018,  1019,  1131,  1133,  1251,  1252},
+    {  1019,  1020,  1132,  1134,  1252,  1253},
+    {  1020,  1021,  1133,  1135,  1253,  1254},
+    {  1021,  1022,  1134,  1136,  1254,  1255},
+    {  1022,  1023,  1135,  1137,  1255,  1256},
+    {  1023,  1024,  1136,  1138,  1256,  1257},
+    {  1024,  1025,  1137,  1139,  1257,  1258},
+    {  1025,  1026,  1138,  1140,  1258,  1259},
+    {  919,  1026,  1027,  1139,  1259,  1260}, // 1140
+    {  1027,  1142,  1260,  1261,  1262,  1386},
+    {  1027,  1028,  1141,  1143,  1262,  1263},
+    {  1028,  1029,  1142,  1144,  1263,  1264},
+    {  1029,  1030,  1143,  1145,  1264,  1265},
+    {  1030,  1031,  1144,  1146,  1265,  1266},
+    {  1031,  1032,  1145,  1147,  1266,  1267},
+    {  1032,  1033,  1146,  1148,  1267,  1268},
+    {  1033,  1034,  1147,  1149,  1268,  1269},
+    {  1034,  1035,  1148,  1150,  1269,  1270},
+    {  1035,  1036,  1149,  1151,  1270,  1271},
+    {  1036,  1037,  1150,  1152,  1271,  1272},
+    {  1037,  1038,  1151,  1153,  1272,  1273},
+    {  1038,  1039,  1152,  1154,  1273,  1274},
+    {  1039,  1040,  1153,  1155,  1274,  1275},
+    {  1040,  1041,  1154,  1156,  1275,  1276},
+    {  1041,  1042,  1155,  1157,  1276,  1277},
+    {  1042,  1043,  1156,  1158,  1277,  1278},
+    {  1043,  1044,  1157,  1159,  1278,  1279},
+    {  1044,  1045,  1158,  1160,  1279,  1280},
+    {  1045,  1046,  1159,  1161,  1280,  1281}, // 1160
+    {  1046,  1160,  1162,  1281,  1282,  1283},
+    {  1046,  1047,  1161,  1163,  1283,  1284},
+    {  1047,  1048,  1162,  1164,  1284,  1285},
+    {  1048,  1049,  1163,  1165,  1285,  1286},
+    {  1049,  1050,  1164,  1166,  1286,  1287},
+    {  1050,  1051,  1165,  1167,  1287,  1288},
+    {  1051,  1052,  1166,  1168,  1288,  1289},
+    {  1052,  1053,  1167,  1169,  1289,  1290},
+    {  1053,  1054,  1168,  1170,  1290,  1291},
+    {  1054,  1055,  1169,  1171,  1291,  1292},
+    {  1055,  1056,  1170,  1172,  1292,  1293},
+    {  1056,  1057,  1171,  1173,  1293,  1294},
+    {  1057,  1058,  1172,  1174,  1294,  1295},
+    {  1058,  1059,  1173,  1175,  1295,  1296},
+    {  1059,  1060,  1174,  1176,  1296,  1297},
+    {  1060,  1061,  1175,  1177,  1297,  1298},
+    {  1061,  1062,  1176,  1178,  1298,  1299},
+    {  1062,  1063,  1177,  1179,  1299,  1300},
+    {  1063,  1064,  1178,  1180,  1300,  1301},
+    {  1064,  1065,  1179,  1181,  1301,  1302}, // 1180
+    {  1065,  1180,  1182,  1302,  1303,  1304},
+    {  1065,  1066,  1181,  1183,  1304,  1305},
+    {  1066,  1067,  1182,  1184,  1305,  1306},
+    {  1067,  1068,  1183,  1185,  1306,  1307},
+    {  1068,  1069,  1184,  1186,  1307,  1308},
+    {  1069,  1070,  1185,  1187,  1308,  1309},
+    {  1070,  1071,  1186,  1188,  1309,  1310},
+    {  1071,  1072,  1187,  1189,  1310,  1311},
+    {  1072,  1073,  1188,  1190,  1311,  1312},
+    {  1073,  1074,  1189,  1191,  1312,  1313},
+    {  1074,  1075,  1190,  1192,  1313,  1314},
+    {  1075,  1076,  1191,  1193,  1314,  1315},
+    {  1076,  1077,  1192,  1194,  1315,  1316},
+    {  1077,  1078,  1193,  1195,  1316,  1317},
+    {  1078,  1079,  1194,  1196,  1317,  1318},
+    {  1079,  1080,  1195,  1197,  1318,  1319},
+    {  1080,  1081,  1196,  1198,  1319,  1320},
+    {  1081,  1082,  1197,  1199,  1320,  1321},
+    {  1082,  1083,  1198,  1200,  1321,  1322},
+    {  1083,  1084,  1199,  1201,  1322,  1323}, // 1200
+    {  1084,  1200,  1202,  1323,  1324,  1325},
+    {  1084,  1085,  1201,  1203,  1325,  1326},
+    {  1085,  1086,  1202,  1204,  1326,  1327},
+    {  1086,  1087,  1203,  1205,  1327,  1328},
+    {  1087,  1088,  1204,  1206,  1328,  1329},
+    {  1088,  1089,  1205,  1207,  1329,  1330},
+    {  1089,  1090,  1206,  1208,  1330,  1331},
+    {  1090,  1091,  1207,  1209,  1331,  1332},
+    {  1091,  1092,  1208,  1210,  1332,  1333},
+    {  1092,  1093,  1209,  1211,  1333,  1334},
+    {  1093,  1094,  1210,  1212,  1334,  1335},
+    {  1094,  1095,  1211,  1213,  1335,  1336},
+    {  1095,  1096,  1212,  1214,  1336,  1337},
+    {  1096,  1097,  1213,  1215,  1337,  1338},
+    {  1097,  1098,  1214,  1216,  1338,  1339},
+    {  1098,  1099,  1215,  1217,  1339,  1340},
+    {  1099,  1100,  1216,  1218,  1340,  1341},
+    {  1100,  1101,  1217,  1219,  1341,  1342},
+    {  1101,  1102,  1218,  1220,  1342,  1343},
+    {  1102,  1103,  1219,  1221,  1343,  1344}, // 1220
+    {  1103,  1220,  1222,  1344,  1345,  1346},
+    {  1103,  1104,  1221,  1223,  1346,  1347},
+    {  1104,  1105,  1222,  1224,  1347,  1348},
+    {  1105,  1106,  1223,  1225,  1348,  1349},
+    {  1106,  1107,  1224,  1226,  1349,  1350},
+    {  1107,  1108,  1225,  1227,  1350,  1351},
+    {  1108,  1109,  1226,  1228,  1351,  1352},
+    {  1109,  1110,  1227,  1229,  1352,  1353},
+    {  1110,  1111,  1228,  1230,  1353,  1354},
+    {  1111,  1112,  1229,  1231,  1354,  1355},
+    {  1112,  1113,  1230,  1232,  1355,  1356},
+    {  1113,  1114,  1231,  1233,  1356,  1357},
+    {  1114,  1115,  1232,  1234,  1357,  1358},
+    {  1115,  1116,  1233,  1235,  1358,  1359},
+    {  1116,  1117,  1234,  1236,  1359,  1360},
+    {  1117,  1118,  1235,  1237,  1360,  1361},
+    {  1118,  1119,  1236,  1238,  1361,  1362},
+    {  1119,  1120,  1237,  1239,  1362,  1363},
+    {  1120,  1121,  1238,  1240,  1363,  1364},
+    {  1121,  1122,  1239,  1241,  1364,  1365}, // 1240
+    {  1122,  1240,  1242,  1365,  1366,  1367},
+    {  1122,  1123,  1241,  1243,  1367,  1368},
+    {  1123,  1124,  1242,  1244,  1368,  1369},
+    {  1124,  1125,  1243,  1245,  1369,  1370},
+    {  1125,  1126,  1244,  1246,  1370,  1371},
+    {  1126,  1127,  1245,  1247,  1371,  1372},
+    {  1127,  1128,  1246,  1248,  1372,  1373},
+    {  1128,  1129,  1247,  1249,  1373,  1374},
+    {  1129,  1130,  1248,  1250,  1374,  1375},
+    {  1130,  1131,  1249,  1251,  1375,  1376},
+    {  1131,  1132,  1250,  1252,  1376,  1377},
+    {  1132,  1133,  1251,  1253,  1377,  1378},
+    {  1133,  1134,  1252,  1254,  1378,  1379},
+    {  1134,  1135,  1253,  1255,  1379,  1380},
+    {  1135,  1136,  1254,  1256,  1380,  1381},
+    {  1136,  1137,  1255,  1257,  1381,  1382},
+    {  1137,  1138,  1256,  1258,  1382,  1383},
+    {  1138,  1139,  1257,  1259,  1383,  1384},
+    {  1139,  1140,  1258,  1260,  1384,  1385},
+    {  1027,  1140,  1141,  1259,  1385,  1386}, // 1260
+    {  1141,  1262,  1386,  1387,  1388,  1518},
+    {  1141,  1142,  1261,  1263,  1388,  1389},
+    {  1142,  1143,  1262,  1264,  1389,  1390},
+    {  1143,  1144,  1263,  1265,  1390,  1391},
+    {  1144,  1145,  1264,  1266,  1391,  1392},
+    {  1145,  1146,  1265,  1267,  1392,  1393},
+    {  1146,  1147,  1266,  1268,  1393,  1394},
+    {  1147,  1148,  1267,  1269,  1394,  1395},
+    {  1148,  1149,  1268,  1270,  1395,  1396},
+    {  1149,  1150,  1269,  1271,  1396,  1397},
+    {  1150,  1151,  1270,  1272,  1397,  1398},
+    {  1151,  1152,  1271,  1273,  1398,  1399},
+    {  1152,  1153,  1272,  1274,  1399,  1400},
+    {  1153,  1154,  1273,  1275,  1400,  1401},
+    {  1154,  1155,  1274,  1276,  1401,  1402},
+    {  1155,  1156,  1275,  1277,  1402,  1403},
+    {  1156,  1157,  1276,  1278,  1403,  1404},
+    {  1157,  1158,  1277,  1279,  1404,  1405},
+    {  1158,  1159,  1278,  1280,  1405,  1406},
+    {  1159,  1160,  1279,  1281,  1406,  1407}, // 1280
+    {  1160,  1161,  1280,  1282,  1407,  1408},
+    {  1161,  1281,  1283,  1408,  1409,  1410},
+    {  1161,  1162,  1282,  1284,  1410,  1411},
+    {  1162,  1163,  1283,  1285,  1411,  1412},
+    {  1163,  1164,  1284,  1286,  1412,  1413},
+    {  1164,  1165,  1285,  1287,  1413,  1414},
+    {  1165,  1166,  1286,  1288,  1414,  1415},
+    {  1166,  1167,  1287,  1289,  1415,  1416},
+    {  1167,  1168,  1288,  1290,  1416,  1417},
+    {  1168,  1169,  1289,  1291,  1417,  1418},
+    {  1169,  1170,  1290,  1292,  1418,  1419},
+    {  1170,  1171,  1291,  1293,  1419,  1420},
+    {  1171,  1172,  1292,  1294,  1420,  1421},
+    {  1172,  1173,  1293,  1295,  1421,  1422},
+    {  1173,  1174,  1294,  1296,  1422,  1423},
+    {  1174,  1175,  1295,  1297,  1423,  1424},
+    {  1175,  1176,  1296,  1298,  1424,  1425},
+    {  1176,  1177,  1297,  1299,  1425,  1426},
+    {  1177,  1178,  1298,  1300,  1426,  1427},
+    {  1178,  1179,  1299,  1301,  1427,  1428}, // 1300
+    {  1179,  1180,  1300,  1302,  1428,  1429},
+    {  1180,  1181,  1301,  1303,  1429,  1430},
+    {  1181,  1302,  1304,  1430,  1431,  1432},
+    {  1181,  1182,  1303,  1305,  1432,  1433},
+    {  1182,  1183,  1304,  1306,  1433,  1434},
+    {  1183,  1184,  1305,  1307,  1434,  1435},
+    {  1184,  1185,  1306,  1308,  1435,  1436},
+    {  1185,  1186,  1307,  1309,  1436,  1437},
+    {  1186,  1187,  1308,  1310,  1437,  1438},
+    {  1187,  1188,  1309,  1311,  1438,  1439},
+    {  1188,  1189,  1310,  1312,  1439,  1440},
+    {  1189,  1190,  1311,  1313,  1440,  1441},
+    {  1190,  1191,  1312,  1314,  1441,  1442},
+    {  1191,  1192,  1313,  1315,  1442,  1443},
+    {  1192,  1193,  1314,  1316,  1443,  1444},
+    {  1193,  1194,  1315,  1317,  1444,  1445},
+    {  1194,  1195,  1316,  1318,  1445,  1446},
+    {  1195,  1196,  1317,  1319,  1446,  1447},
+    {  1196,  1197,  1318,  1320,  1447,  1448},
+    {  1197,  1198,  1319,  1321,  1448,  1449}, // 1320
+    {  1198,  1199,  1320,  1322,  1449,  1450},
+    {  1199,  1200,  1321,  1323,  1450,  1451},
+    {  1200,  1201,  1322,  1324,  1451,  1452},
+    {  1201,  1323,  1325,  1452,  1453,  1454},
+    {  1201,  1202,  1324,  1326,  1454,  1455},
+    {  1202,  1203,  1325,  1327,  1455,  1456},
+    {  1203,  1204,  1326,  1328,  1456,  1457},
+    {  1204,  1205,  1327,  1329,  1457,  1458},
+    {  1205,  1206,  1328,  1330,  1458,  1459},
+    {  1206,  1207,  1329,  1331,  1459,  1460},
+    {  1207,  1208,  1330,  1332,  1460,  1461},
+    {  1208,  1209,  1331,  1333,  1461,  1462},
+    {  1209,  1210,  1332,  1334,  1462,  1463},
+    {  1210,  1211,  1333,  1335,  1463,  1464},
+    {  1211,  1212,  1334,  1336,  1464,  1465},
+    {  1212,  1213,  1335,  1337,  1465,  1466},
+    {  1213,  1214,  1336,  1338,  1466,  1467},
+    {  1214,  1215,  1337,  1339,  1467,  1468},
+    {  1215,  1216,  1338,  1340,  1468,  1469},
+    {  1216,  1217,  1339,  1341,  1469,  1470}, // 1340
+    {  1217,  1218,  1340,  1342,  1470,  1471},
+    {  1218,  1219,  1341,  1343,  1471,  1472},
+    {  1219,  1220,  1342,  1344,  1472,  1473},
+    {  1220,  1221,  1343,  1345,  1473,  1474},
+    {  1221,  1344,  1346,  1474,  1475,  1476},
+    {  1221,  1222,  1345,  1347,  1476,  1477},
+    {  1222,  1223,  1346,  1348,  1477,  1478},
+    {  1223,  1224,  1347,  1349,  1478,  1479},
+    {  1224,  1225,  1348,  1350,  1479,  1480},
+    {  1225,  1226,  1349,  1351,  1480,  1481},
+    {  1226,  1227,  1350,  1352,  1481,  1482},
+    {  1227,  1228,  1351,  1353,  1482,  1483},
+    {  1228,  1229,  1352,  1354,  1483,  1484},
+    {  1229,  1230,  1353,  1355,  1484,  1485},
+    {  1230,  1231,  1354,  1356,  1485,  1486},
+    {  1231,  1232,  1355,  1357,  1486,  1487},
+    {  1232,  1233,  1356,  1358,  1487,  1488},
+    {  1233,  1234,  1357,  1359,  1488,  1489},
+    {  1234,  1235,  1358,  1360,  1489,  1490},
+    {  1235,  1236,  1359,  1361,  1490,  1491}, // 1360
+    {  1236,  1237,  1360,  1362,  1491,  1492},
+    {  1237,  1238,  1361,  1363,  1492,  1493},
+    {  1238,  1239,  1362,  1364,  1493,  1494},
+    {  1239,  1240,  1363,  1365,  1494,  1495},
+    {  1240,  1241,  1364,  1366,  1495,  1496},
+    {  1241,  1365,  1367,  1496,  1497,  1498},
+    {  1241,  1242,  1366,  1368,  1498,  1499},
+    {  1242,  1243,  1367,  1369,  1499,  1500},
+    {  1243,  1244,  1368,  1370,  1500,  1501},
+    {  1244,  1245,  1369,  1371,  1501,  1502},
+    {  1245,  1246,  1370,  1372,  1502,  1503},
+    {  1246,  1247,  1371,  1373,  1503,  1504},
+    {  1247,  1248,  1372,  1374,  1504,  1505},
+    {  1248,  1249,  1373,  1375,  1505,  1506},
+    {  1249,  1250,  1374,  1376,  1506,  1507},
+    {  1250,  1251,  1375,  1377,  1507,  1508},
+    {  1251,  1252,  1376,  1378,  1508,  1509},
+    {  1252,  1253,  1377,  1379,  1509,  1510},
+    {  1253,  1254,  1378,  1380,  1510,  1511},
+    {  1254,  1255,  1379,  1381,  1511,  1512}, // 1380
+    {  1255,  1256,  1380,  1382,  1512,  1513},
+    {  1256,  1257,  1381,  1383,  1513,  1514},
+    {  1257,  1258,  1382,  1384,  1514,  1515},
+    {  1258,  1259,  1383,  1385,  1515,  1516},
+    {  1259,  1260,  1384,  1386,  1516,  1517},
+    {  1141,  1260,  1261,  1385,  1517,  1518},
+    {  1261,  1388,  1518,  1519,  1520,  1656},
+    {  1261,  1262,  1387,  1389,  1520,  1521},
+    {  1262,  1263,  1388,  1390,  1521,  1522},
+    {  1263,  1264,  1389,  1391,  1522,  1523},
+    {  1264,  1265,  1390,  1392,  1523,  1524},
+    {  1265,  1266,  1391,  1393,  1524,  1525},
+    {  1266,  1267,  1392,  1394,  1525,  1526},
+    {  1267,  1268,  1393,  1395,  1526,  1527},
+    {  1268,  1269,  1394,  1396,  1527,  1528},
+    {  1269,  1270,  1395,  1397,  1528,  1529},
+    {  1270,  1271,  1396,  1398,  1529,  1530},
+    {  1271,  1272,  1397,  1399,  1530,  1531},
+    {  1272,  1273,  1398,  1400,  1531,  1532},
+    {  1273,  1274,  1399,  1401,  1532,  1533}, // 1400
+    {  1274,  1275,  1400,  1402,  1533,  1534},
+    {  1275,  1276,  1401,  1403,  1534,  1535},
+    {  1276,  1277,  1402,  1404,  1535,  1536},
+    {  1277,  1278,  1403,  1405,  1536,  1537},
+    {  1278,  1279,  1404,  1406,  1537,  1538},
+    {  1279,  1280,  1405,  1407,  1538,  1539},
+    {  1280,  1281,  1406,  1408,  1539,  1540},
+    {  1281,  1282,  1407,  1409,  1540,  1541},
+    {  1282,  1408,  1410,  1541,  1542,  1543},
+    {  1282,  1283,  1409,  1411,  1543,  1544},
+    {  1283,  1284,  1410,  1412,  1544,  1545},
+    {  1284,  1285,  1411,  1413,  1545,  1546},
+    {  1285,  1286,  1412,  1414,  1546,  1547},
+    {  1286,  1287,  1413,  1415,  1547,  1548},
+    {  1287,  1288,  1414,  1416,  1548,  1549},
+    {  1288,  1289,  1415,  1417,  1549,  1550},
+    {  1289,  1290,  1416,  1418,  1550,  1551},
+    {  1290,  1291,  1417,  1419,  1551,  1552},
+    {  1291,  1292,  1418,  1420,  1552,  1553},
+    {  1292,  1293,  1419,  1421,  1553,  1554}, // 1420
+    {  1293,  1294,  1420,  1422,  1554,  1555},
+    {  1294,  1295,  1421,  1423,  1555,  1556},
+    {  1295,  1296,  1422,  1424,  1556,  1557},
+    {  1296,  1297,  1423,  1425,  1557,  1558},
+    {  1297,  1298,  1424,  1426,  1558,  1559},
+    {  1298,  1299,  1425,  1427,  1559,  1560},
+    {  1299,  1300,  1426,  1428,  1560,  1561},
+    {  1300,  1301,  1427,  1429,  1561,  1562},
+    {  1301,  1302,  1428,  1430,  1562,  1563},
+    {  1302,  1303,  1429,  1431,  1563,  1564},
+    {  1303,  1430,  1432,  1564,  1565,  1566},
+    {  1303,  1304,  1431,  1433,  1566,  1567},
+    {  1304,  1305,  1432,  1434,  1567,  1568},
+    {  1305,  1306,  1433,  1435,  1568,  1569},
+    {  1306,  1307,  1434,  1436,  1569,  1570},
+    {  1307,  1308,  1435,  1437,  1570,  1571},
+    {  1308,  1309,  1436,  1438,  1571,  1572},
+    {  1309,  1310,  1437,  1439,  1572,  1573},
+    {  1310,  1311,  1438,  1440,  1573,  1574},
+    {  1311,  1312,  1439,  1441,  1574,  1575}, // 1440
+    {  1312,  1313,  1440,  1442,  1575,  1576},
+    {  1313,  1314,  1441,  1443,  1576,  1577},
+    {  1314,  1315,  1442,  1444,  1577,  1578},
+    {  1315,  1316,  1443,  1445,  1578,  1579},
+    {  1316,  1317,  1444,  1446,  1579,  1580},
+    {  1317,  1318,  1445,  1447,  1580,  1581},
+    {  1318,  1319,  1446,  1448,  1581,  1582},
+    {  1319,  1320,  1447,  1449,  1582,  1583},
+    {  1320,  1321,  1448,  1450,  1583,  1584},
+    {  1321,  1322,  1449,  1451,  1584,  1585},
+    {  1322,  1323,  1450,  1452,  1585,  1586},
+    {  1323,  1324,  1451,  1453,  1586,  1587},
+    {  1324,  1452,  1454,  1587,  1588,  1589},
+    {  1324,  1325,  1453,  1455,  1589,  1590},
+    {  1325,  1326,  1454,  1456,  1590,  1591},
+    {  1326,  1327,  1455,  1457,  1591,  1592},
+    {  1327,  1328,  1456,  1458,  1592,  1593},
+    {  1328,  1329,  1457,  1459,  1593,  1594},
+    {  1329,  1330,  1458,  1460,  1594,  1595},
+    {  1330,  1331,  1459,  1461,  1595,  1596}, // 1460
+    {  1331,  1332,  1460,  1462,  1596,  1597},
+    {  1332,  1333,  1461,  1463,  1597,  1598},
+    {  1333,  1334,  1462,  1464,  1598,  1599},
+    {  1334,  1335,  1463,  1465,  1599,  1600},
+    {  1335,  1336,  1464,  1466,  1600,  1601},
+    {  1336,  1337,  1465,  1467,  1601,  1602},
+    {  1337,  1338,  1466,  1468,  1602,  1603},
+    {  1338,  1339,  1467,  1469,  1603,  1604},
+    {  1339,  1340,  1468,  1470,  1604,  1605},
+    {  1340,  1341,  1469,  1471,  1605,  1606},
+    {  1341,  1342,  1470,  1472,  1606,  1607},
+    {  1342,  1343,  1471,  1473,  1607,  1608},
+    {  1343,  1344,  1472,  1474,  1608,  1609},
+    {  1344,  1345,  1473,  1475,  1609,  1610},
+    {  1345,  1474,  1476,  1610,  1611,  1612},
+    {  1345,  1346,  1475,  1477,  1612,  1613},
+    {  1346,  1347,  1476,  1478,  1613,  1614},
+    {  1347,  1348,  1477,  1479,  1614,  1615},
+    {  1348,  1349,  1478,  1480,  1615,  1616},
+    {  1349,  1350,  1479,  1481,  1616,  1617}, // 1480
+    {  1350,  1351,  1480,  1482,  1617,  1618},
+    {  1351,  1352,  1481,  1483,  1618,  1619},
+    {  1352,  1353,  1482,  1484,  1619,  1620},
+    {  1353,  1354,  1483,  1485,  1620,  1621},
+    {  1354,  1355,  1484,  1486,  1621,  1622},
+    {  1355,  1356,  1485,  1487,  1622,  1623},
+    {  1356,  1357,  1486,  1488,  1623,  1624},
+    {  1357,  1358,  1487,  1489,  1624,  1625},
+    {  1358,  1359,  1488,  1490,  1625,  1626},
+    {  1359,  1360,  1489,  1491,  1626,  1627},
+    {  1360,  1361,  1490,  1492,  1627,  1628},
+    {  1361,  1362,  1491,  1493,  1628,  1629},
+    {  1362,  1363,  1492,  1494,  1629,  1630},
+    {  1363,  1364,  1493,  1495,  1630,  1631},
+    {  1364,  1365,  1494,  1496,  1631,  1632},
+    {  1365,  1366,  1495,  1497,  1632,  1633},
+    {  1366,  1496,  1498,  1633,  1634,  1635},
+    {  1366,  1367,  1497,  1499,  1635,  1636},
+    {  1367,  1368,  1498,  1500,  1636,  1637},
+    {  1368,  1369,  1499,  1501,  1637,  1638}, // 1500
+    {  1369,  1370,  1500,  1502,  1638,  1639},
+    {  1370,  1371,  1501,  1503,  1639,  1640},
+    {  1371,  1372,  1502,  1504,  1640,  1641},
+    {  1372,  1373,  1503,  1505,  1641,  1642},
+    {  1373,  1374,  1504,  1506,  1642,  1643},
+    {  1374,  1375,  1505,  1507,  1643,  1644},
+    {  1375,  1376,  1506,  1508,  1644,  1645},
+    {  1376,  1377,  1507,  1509,  1645,  1646},
+    {  1377,  1378,  1508,  1510,  1646,  1647},
+    {  1378,  1379,  1509,  1511,  1647,  1648},
+    {  1379,  1380,  1510,  1512,  1648,  1649},
+    {  1380,  1381,  1511,  1513,  1649,  1650},
+    {  1381,  1382,  1512,  1514,  1650,  1651},
+    {  1382,  1383,  1513,  1515,  1651,  1652},
+    {  1383,  1384,  1514,  1516,  1652,  1653},
+    {  1384,  1385,  1515,  1517,  1653,  1654},
+    {  1385,  1386,  1516,  1518,  1654,  1655},
+    {  1261,  1386,  1387,  1517,  1655,  1656},
+    {  1387,  1520,  1656,  -1,  -1,  -1},
+    {  1387,  1388,  1519,  1521,  1657,  -1}, // 1520
+    {  1388,  1389,  1520,  1522,  -1,  -1},
+    {  1389,  1390,  1521,  1523,  1658,  -1},
+    {  1390,  1391,  1522,  1524,  -1,  -1},
+    {  1391,  1392,  1523,  1525,  1659,  -1},
+    {  1392,  1393,  1524,  1526,  -1,  -1},
+    {  1393,  1394,  1525,  1527,  1660,  -1},
+    {  1394,  1395,  1526,  1528,  -1,  -1},
+    {  1395,  1396,  1527,  1529,  1661,  -1},
+    {  1396,  1397,  1528,  1530,  -1,  -1},
+    {  1397,  1398,  1529,  1531,  1662,  -1},
+    {  1398,  1399,  1530,  1532,  -1,  -1},
+    {  1399,  1400,  1531,  1533,  1663,  -1},
+    {  1400,  1401,  1532,  1534,  -1,  -1},
+    {  1401,  1402,  1533,  1535,  1664,  -1},
+    {  1402,  1403,  1534,  1536,  -1,  -1},
+    {  1403,  1404,  1535,  1537,  1665,  -1},
+    {  1404,  1405,  1536,  1538,  -1,  -1},
+    {  1405,  1406,  1537,  1539,  1666,  -1},
+    {  1406,  1407,  1538,  1540,  -1,  -1},
+    {  1407,  1408,  1539,  1541,  1667,  -1}, // 1540
+    {  1408,  1409,  1540,  1542,  -1,  -1},
+    {  1409,  1541,  1543,  1668,  -1,  -1},
+    {  1409,  1410,  1542,  1544,  -1,  -1},
+    {  1410,  1411,  1543,  1545,  -1,  -1},
+    {  1411,  1412,  1544,  1546,  -1,  -1},
+    {  1412,  1413,  1545,  1547,  -1,  -1},
+    {  1413,  1414,  1546,  1548,  -1,  -1},
+    {  1414,  1415,  1547,  1549,  -1,  -1},
+    {  1415,  1416,  1548,  1550,  -1,  -1},
+    {  1416,  1417,  1549,  1551,  -1,  -1},
+    {  1417,  1418,  1550,  1552,  -1,  -1},
+    {  1418,  1419,  1551,  1553,  -1,  -1},
+    {  1419,  1420,  1552,  1554,  -1,  -1},
+    {  1420,  1421,  1553,  1555,  -1,  -1},
+    {  1421,  1422,  1554,  1556,  -1,  -1},
+    {  1422,  1423,  1555,  1557,  -1,  -1},
+    {  1423,  1424,  1556,  1558,  -1,  -1},
+    {  1424,  1425,  1557,  1559,  -1,  -1},
+    {  1425,  1426,  1558,  1560,  -1,  -1},
+    {  1426,  1427,  1559,  1561,  -1,  -1}, // 1560
+    {  1427,  1428,  1560,  1562,  -1,  -1},
+    {  1428,  1429,  1561,  1563,  -1,  -1},
+    {  1429,  1430,  1562,  1564,  -1,  -1},
+    {  1430,  1431,  1563,  1565,  -1,  -1},
+    {  1431,  1564,  1566,  -1,  -1,  -1},
+    {  1431,  1432,  1565,  1567,  -1,  -1},
+    {  1432,  1433,  1566,  1568,  -1,  -1},
+    {  1433,  1434,  1567,  1569,  -1,  -1},
+    {  1434,  1435,  1568,  1570,  -1,  -1},
+    {  1435,  1436,  1569,  1571,  -1,  -1},
+    {  1436,  1437,  1570,  1572,  -1,  -1},
+    {  1437,  1438,  1571,  1573,  -1,  -1},
+    {  1438,  1439,  1572,  1574,  -1,  -1},
+    {  1439,  1440,  1573,  1575,  -1,  -1},
+    {  1440,  1441,  1574,  1576,  -1,  -1},
+    {  1441,  1442,  1575,  1577,  -1,  -1},
+    {  1442,  1443,  1576,  1578,  -1,  -1},
+    {  1443,  1444,  1577,  1579,  -1,  -1},
+    {  1444,  1445,  1578,  1580,  -1,  -1},
+    {  1445,  1446,  1579,  1581,  -1,  -1}, // 1580
+    {  1446,  1447,  1580,  1582,  -1,  -1},
+    {  1447,  1448,  1581,  1583,  -1,  -1},
+    {  1448,  1449,  1582,  1584,  -1,  -1},
+    {  1449,  1450,  1583,  1585,  -1,  -1},
+    {  1450,  1451,  1584,  1586,  -1,  -1},
+    {  1451,  1452,  1585,  1587,  -1,  -1},
+    {  1452,  1453,  1586,  1588,  -1,  -1},
+    {  1453,  1587,  1589,  -1,  -1,  -1},
+    {  1453,  1454,  1588,  1590,  -1,  -1},
+    {  1454,  1455,  1589,  1591,  -1,  -1},
+    {  1455,  1456,  1590,  1592,  -1,  -1},
+    {  1456,  1457,  1591,  1593,  -1,  -1},
+    {  1457,  1458,  1592,  1594,  -1,  -1},
+    {  1458,  1459,  1593,  1595,  -1,  -1},
+    {  1459,  1460,  1594,  1596,  -1,  -1},
+    {  1460,  1461,  1595,  1597,  -1,  -1},
+    {  1461,  1462,  1596,  1598,  -1,  -1},
+    {  1462,  1463,  1597,  1599,  -1,  -1},
+    {  1463,  1464,  1598,  1600,  -1,  -1},
+    {  1464,  1465,  1599,  1601,  -1,  -1}, // 1600
+    {  1465,  1466,  1600,  1602,  -1,  -1},
+    {  1466,  1467,  1601,  1603,  -1,  -1},
+    {  1467,  1468,  1602,  1604,  -1,  -1},
+    {  1468,  1469,  1603,  1605,  -1,  -1},
+    {  1469,  1470,  1604,  1606,  -1,  -1},
+    {  1470,  1471,  1605,  1607,  -1,  -1},
+    {  1471,  1472,  1606,  1608,  -1,  -1},
+    {  1472,  1473,  1607,  1609,  -1,  -1},
+    {  1473,  1474,  1608,  1610,  -1,  -1},
+    {  1474,  1475,  1609,  1611,  -1,  -1},
+    {  1475,  1610,  1612,  -1,  -1,  -1},
+    {  1475,  1476,  1611,  1613,  -1,  -1},
+    {  1476,  1477,  1612,  1614,  -1,  -1},
+    {  1477,  1478,  1613,  1615,  -1,  -1},
+    {  1478,  1479,  1614,  1616,  -1,  -1},
+    {  1479,  1480,  1615,  1617,  -1,  -1},
+    {  1480,  1481,  1616,  1618,  -1,  -1},
+    {  1481,  1482,  1617,  1619,  -1,  -1},
+    {  1482,  1483,  1618,  1620,  -1,  -1},
+    {  1483,  1484,  1619,  1621,  -1,  -1}, // 1620
+    {  1484,  1485,  1620,  1622,  -1,  -1},
+    {  1485,  1486,  1621,  1623,  -1,  -1},
+    {  1486,  1487,  1622,  1624,  -1,  -1},
+    {  1487,  1488,  1623,  1625,  -1,  -1},
+    {  1488,  1489,  1624,  1626,  -1,  -1},
+    {  1489,  1490,  1625,  1627,  -1,  -1},
+    {  1490,  1491,  1626,  1628,  -1,  -1},
+    {  1491,  1492,  1627,  1629,  -1,  -1},
+    {  1492,  1493,  1628,  1630,  -1,  -1},
+    {  1493,  1494,  1629,  1631,  -1,  -1},
+    {  1494,  1495,  1630,  1632,  -1,  -1},
+    {  1495,  1496,  1631,  1633,  -1,  -1},
+    {  1496,  1497,  1632,  1634,  -1,  -1},
+    {  1497,  1633,  1635,  1717,  -1,  -1},
+    {  1497,  1498,  1634,  1636,  -1,  -1},
+    {  1498,  1499,  1635,  1637,  1718,  -1},
+    {  1499,  1500,  1636,  1638,  -1,  -1},
+    {  1500,  1501,  1637,  1639,  1719,  -1},
+    {  1501,  1502,  1638,  1640,  -1,  -1},
+    {  1502,  1503,  1639,  1641,  1720,  -1}, // 1640
+    {  1503,  1504,  1640,  1642,  -1,  -1},
+    {  1504,  1505,  1641,  1643,  1721,  -1},
+    {  1505,  1506,  1642,  1644,  -1,  -1},
+    {  1506,  1507,  1643,  1645,  1722,  -1},
+    {  1507,  1508,  1644,  1646,  -1,  -1},
+    {  1508,  1509,  1645,  1647,  1723,  -1},
+    {  1509,  1510,  1646,  1648,  -1,  -1},
+    {  1510,  1511,  1647,  1649,  1724,  -1},
+    {  1511,  1512,  1648,  1650,  -1,  -1},
+    {  1512,  1513,  1649,  1651,  1725,  -1},
+    {  1513,  1514,  1650,  1652,  -1,  -1},
+    {  1514,  1515,  1651,  1653,  1726,  -1},
+    {  1515,  1516,  1652,  1654,  -1,  -1},
+    {  1516,  1517,  1653,  1655,  1727,  -1},
+    {  1517,  1518,  1654,  1656,  -1,  -1},
+    {  1387,  1518,  1519,  1655,  1728,  -1},
+    {  1658,  1729,  1730,  -1,  -1,  -1},
+    {  1657,  1659,  1730,  1731,  -1,  -1},
+    {  1658,  1660,  1731,  1732,  -1,  -1},
+    {  1659,  1661,  1732,  1733,  -1,  -1}, // 1660
+    {  1660,  1662,  1733,  1734,  -1,  -1},
+    {  1661,  1663,  1734,  1735,  -1,  -1},
+    {  1662,  1664,  1735,  1736,  -1,  -1},
+    {  1663,  1665,  1736,  1737,  -1,  -1},
+    {  1664,  1666,  1737,  1738,  -1,  -1},
+    {  1665,  1667,  1738,  1739,  -1,  -1},
+    {  1666,  1668,  1739,  1740,  -1,  -1},
+    {  1667,  1740,  1741,  -1,  -1,  -1},
+    {  1670,  1742,  1743,  -1,  -1,  -1},
+    {  1669,  1671,  1743,  1744,  -1,  -1},
+    {  1670,  1672,  1744,  1745,  -1,  -1},
+    {  1671,  1673,  1745,  1746,  -1,  -1},
+    {  1672,  1674,  1746,  1747,  -1,  -1},
+    {  1673,  1675,  1747,  1748,  -1,  -1},
+    {  1674,  1676,  1748,  1749,  -1,  -1},
+    {  1675,  1677,  1749,  1750,  -1,  -1},
+    {  1676,  1678,  1750,  1751,  -1,  -1},
+    {  1677,  1679,  1751,  1752,  -1,  -1},
+    {  1678,  1680,  1752,  1753,  -1,  -1},
+    {  1679,  1753,  1754,  -1,  -1,  -1}, // 1680
+    {  1682,  1755,  1756,  -1,  -1,  -1},
+    {  1681,  1683,  1756,  1757,  -1,  -1},
+    {  1682,  1684,  1757,  1758,  -1,  -1},
+    {  1683,  1685,  1758,  1759,  -1,  -1},
+    {  1684,  1686,  1759,  1760,  -1,  -1},
+    {  1685,  1687,  1760,  1761,  -1,  -1},
+    {  1686,  1688,  1761,  1762,  -1,  -1},
+    {  1687,  1689,  1762,  1763,  -1,  -1},
+    {  1688,  1690,  1763,  1764,  -1,  -1},
+    {  1689,  1691,  1764,  1765,  -1,  -1},
+    {  1690,  1692,  1765,  1766,  -1,  -1},
+    {  1691,  1766,  1767,  -1,  -1,  -1},
+    {  1694,  1768,  1769,  -1,  -1,  -1},
+    {  1693,  1695,  1769,  1770,  -1,  -1},
+    {  1694,  1696,  1770,  1771,  -1,  -1},
+    {  1695,  1697,  1771,  1772,  -1,  -1},
+    {  1696,  1698,  1772,  1773,  -1,  -1},
+    {  1697,  1699,  1773,  1774,  -1,  -1},
+    {  1698,  1700,  1774,  1775,  -1,  -1},
+    {  1699,  1701,  1775,  1776,  -1,  -1}, // 1700
+    {  1700,  1702,  1776,  1777,  -1,  -1},
+    {  1701,  1703,  1777,  1778,  -1,  -1},
+    {  1702,  1704,  1778,  1779,  -1,  -1},
+    {  1703,  1779,  1780,  -1,  -1,  -1},
+    {  1706,  1781,  1782,  -1,  -1,  -1},
+    {  1705,  1707,  1782,  1783,  -1,  -1},
+    {  1706,  1708,  1783,  1784,  -1,  -1},
+    {  1707,  1709,  1784,  1785,  -1,  -1},
+    {  1708,  1710,  1785,  1786,  -1,  -1},
+    {  1709,  1711,  1786,  1787,  -1,  -1},
+    {  1710,  1712,  1787,  1788,  -1,  -1},
+    {  1711,  1713,  1788,  1789,  -1,  -1},
+    {  1712,  1714,  1789,  1790,  -1,  -1},
+    {  1713,  1715,  1790,  1791,  -1,  -1},
+    {  1714,  1716,  1791,  1792,  -1,  -1},
+    {  1715,  1792,  1793,  -1,  -1,  -1},
+    {  1718,  1794,  1795,  -1,  -1,  -1},
+    {  1717,  1719,  1795,  1796,  -1,  -1},
+    {  1718,  1720,  1796,  1797,  -1,  -1},
+    {  1719,  1721,  1797,  1798,  -1,  -1}, // 1720
+    {  1720,  1722,  1798,  1799,  -1,  -1},
+    {  1721,  1723,  1799,  1800,  -1,  -1},
+    {  1722,  1724,  1800,  1801,  -1,  -1},
+    {  1723,  1725,  1801,  1802,  -1,  -1},
+    {  1724,  1726,  1802,  1803,  -1,  -1},
+    {  1725,  1727,  1803,  1804,  -1,  -1},
+    {  1726,  1728,  1804,  1805,  -1,  -1},
+    {  1727,  1805,  1806,  -1,  -1,  -1},
+    {  1657,  1730,  1807,  1808,  -1,  -1},
+    {  1657,  1658,  1729,  1731,  1808,  1809},
+    {  1658,  1659,  1730,  1732,  1809,  1810},
+    {  1659,  1660,  1731,  1733,  1810,  1811},
+    {  1660,  1661,  1732,  1734,  1811,  1812},
+    {  1661,  1662,  1733,  1735,  1812,  1813},
+    {  1662,  1663,  1734,  1736,  1813,  1814},
+    {  1663,  1664,  1735,  1737,  1814,  1815},
+    {  1664,  1665,  1736,  1738,  1815,  1816},
+    {  1665,  1666,  1737,  1739,  1816,  1817},
+    {  1666,  1667,  1738,  1740,  1817,  1818},
+    {  1667,  1668,  1739,  1741,  1818,  1819}, // 1740
+    {  1668,  1740,  1819,  1820,  -1,  -1},
+    {  1669,  1743,  1821,  1822,  -1,  -1},
+    {  1669,  1670,  1742,  1744,  1822,  1823},
+    {  1670,  1671,  1743,  1745,  1823,  1824},
+    {  1671,  1672,  1744,  1746,  1824,  1825},
+    {  1672,  1673,  1745,  1747,  1825,  1826},
+    {  1673,  1674,  1746,  1748,  1826,  1827},
+    {  1674,  1675,  1747,  1749,  1827,  1828},
+    {  1675,  1676,  1748,  1750,  1828,  1829},
+    {  1676,  1677,  1749,  1751,  1829,  1830},
+    {  1677,  1678,  1750,  1752,  1830,  1831},
+    {  1678,  1679,  1751,  1753,  1831,  1832},
+    {  1679,  1680,  1752,  1754,  1832,  1833},
+    {  1680,  1753,  1833,  1834,  -1,  -1},
+    {  1681,  1756,  1835,  1836,  -1,  -1},
+    {  1681,  1682,  1755,  1757,  1836,  1837},
+    {  1682,  1683,  1756,  1758,  1837,  1838},
+    {  1683,  1684,  1757,  1759,  1838,  1839},
+    {  1684,  1685,  1758,  1760,  1839,  1840},
+    {  1685,  1686,  1759,  1761,  1840,  1841}, // 1760
+    {  1686,  1687,  1760,  1762,  1841,  1842},
+    {  1687,  1688,  1761,  1763,  1842,  1843},
+    {  1688,  1689,  1762,  1764,  1843,  1844},
+    {  1689,  1690,  1763,  1765,  1844,  1845},
+    {  1690,  1691,  1764,  1766,  1845,  1846},
+    {  1691,  1692,  1765,  1767,  1846,  1847},
+    {  1692,  1766,  1847,  1848,  -1,  -1},
+    {  1693,  1769,  1849,  1850,  -1,  -1},
+    {  1693,  1694,  1768,  1770,  1850,  1851},
+    {  1694,  1695,  1769,  1771,  1851,  1852},
+    {  1695,  1696,  1770,  1772,  1852,  1853},
+    {  1696,  1697,  1771,  1773,  1853,  1854},
+    {  1697,  1698,  1772,  1774,  1854,  1855},
+    {  1698,  1699,  1773,  1775,  1855,  1856},
+    {  1699,  1700,  1774,  1776,  1856,  1857},
+    {  1700,  1701,  1775,  1777,  1857,  1858},
+    {  1701,  1702,  1776,  1778,  1858,  1859},
+    {  1702,  1703,  1777,  1779,  1859,  1860},
+    {  1703,  1704,  1778,  1780,  1860,  1861},
+    {  1704,  1779,  1861,  1862,  -1,  -1}, // 1780
+    {  1705,  1782,  1863,  1864,  -1,  -1},
+    {  1705,  1706,  1781,  1783,  1864,  1865},
+    {  1706,  1707,  1782,  1784,  1865,  1866},
+    {  1707,  1708,  1783,  1785,  1866,  1867},
+    {  1708,  1709,  1784,  1786,  1867,  1868},
+    {  1709,  1710,  1785,  1787,  1868,  1869},
+    {  1710,  1711,  1786,  1788,  1869,  1870},
+    {  1711,  1712,  1787,  1789,  1870,  1871},
+    {  1712,  1713,  1788,  1790,  1871,  1872},
+    {  1713,  1714,  1789,  1791,  1872,  1873},
+    {  1714,  1715,  1790,  1792,  1873,  1874},
+    {  1715,  1716,  1791,  1793,  1874,  1875},
+    {  1716,  1792,  1875,  1876,  -1,  -1},
+    {  1717,  1795,  1877,  1878,  -1,  -1},
+    {  1717,  1718,  1794,  1796,  1878,  1879},
+    {  1718,  1719,  1795,  1797,  1879,  1880},
+    {  1719,  1720,  1796,  1798,  1880,  1881},
+    {  1720,  1721,  1797,  1799,  1881,  1882},
+    {  1721,  1722,  1798,  1800,  1882,  1883},
+    {  1722,  1723,  1799,  1801,  1883,  1884}, // 1800
+    {  1723,  1724,  1800,  1802,  1884,  1885},
+    {  1724,  1725,  1801,  1803,  1885,  1886},
+    {  1725,  1726,  1802,  1804,  1886,  1887},
+    {  1726,  1727,  1803,  1805,  1887,  1888},
+    {  1727,  1728,  1804,  1806,  1888,  1889},
+    {  1728,  1805,  1889,  1890,  -1,  -1},
+    {  1729,  1808,  1891,  1892,  -1,  -1},
+    {  1729,  1730,  1807,  1809,  1892,  1893},
+    {  1730,  1731,  1808,  1810,  1893,  1894},
+    {  1731,  1732,  1809,  1811,  1894,  1895},
+    {  1732,  1733,  1810,  1812,  1895,  1896},
+    {  1733,  1734,  1811,  1813,  1896,  1897},
+    {  1734,  1735,  1812,  1814,  1897,  1898},
+    {  1735,  1736,  1813,  1815,  1898,  1899},
+    {  1736,  1737,  1814,  1816,  1899,  1900},
+    {  1737,  1738,  1815,  1817,  1900,  1901},
+    {  1738,  1739,  1816,  1818,  1901,  1902},
+    {  1739,  1740,  1817,  1819,  1902,  1903},
+    {  1740,  1741,  1818,  1820,  1903,  1904},
+    {  1741,  1819,  1904,  1905,  -1,  -1}, // 1820
+    {  1742,  1822,  1906,  1907,  -1,  -1},
+    {  1742,  1743,  1821,  1823,  1907,  1908},
+    {  1743,  1744,  1822,  1824,  1908,  1909},
+    {  1744,  1745,  1823,  1825,  1909,  1910},
+    {  1745,  1746,  1824,  1826,  1910,  1911},
+    {  1746,  1747,  1825,  1827,  1911,  1912},
+    {  1747,  1748,  1826,  1828,  1912,  1913},
+    {  1748,  1749,  1827,  1829,  1913,  1914},
+    {  1749,  1750,  1828,  1830,  1914,  1915},
+    {  1750,  1751,  1829,  1831,  1915,  1916},
+    {  1751,  1752,  1830,  1832,  1916,  1917},
+    {  1752,  1753,  1831,  1833,  1917,  1918},
+    {  1753,  1754,  1832,  1834,  1918,  1919},
+    {  1754,  1833,  1919,  1920,  -1,  -1},
+    {  1755,  1836,  1921,  1922,  -1,  -1},
+    {  1755,  1756,  1835,  1837,  1922,  1923},
+    {  1756,  1757,  1836,  1838,  1923,  1924},
+    {  1757,  1758,  1837,  1839,  1924,  1925},
+    {  1758,  1759,  1838,  1840,  1925,  1926},
+    {  1759,  1760,  1839,  1841,  1926,  1927}, // 1840
+    {  1760,  1761,  1840,  1842,  1927,  1928},
+    {  1761,  1762,  1841,  1843,  1928,  1929},
+    {  1762,  1763,  1842,  1844,  1929,  1930},
+    {  1763,  1764,  1843,  1845,  1930,  1931},
+    {  1764,  1765,  1844,  1846,  1931,  1932},
+    {  1765,  1766,  1845,  1847,  1932,  1933},
+    {  1766,  1767,  1846,  1848,  1933,  1934},
+    {  1767,  1847,  1934,  1935,  -1,  -1},
+    {  1768,  1850,  1936,  1937,  -1,  -1},
+    {  1768,  1769,  1849,  1851,  1937,  1938},
+    {  1769,  1770,  1850,  1852,  1938,  1939},
+    {  1770,  1771,  1851,  1853,  1939,  1940},
+    {  1771,  1772,  1852,  1854,  1940,  1941},
+    {  1772,  1773,  1853,  1855,  1941,  1942},
+    {  1773,  1774,  1854,  1856,  1942,  1943},
+    {  1774,  1775,  1855,  1857,  1943,  1944},
+    {  1775,  1776,  1856,  1858,  1944,  1945},
+    {  1776,  1777,  1857,  1859,  1945,  1946},
+    {  1777,  1778,  1858,  1860,  1946,  1947},
+    {  1778,  1779,  1859,  1861,  1947,  1948}, // 1860
+    {  1779,  1780,  1860,  1862,  1948,  1949},
+    {  1780,  1861,  1949,  1950,  -1,  -1},
+    {  1781,  1864,  1951,  1952,  -1,  -1},
+    {  1781,  1782,  1863,  1865,  1952,  1953},
+    {  1782,  1783,  1864,  1866,  1953,  1954},
+    {  1783,  1784,  1865,  1867,  1954,  1955},
+    {  1784,  1785,  1866,  1868,  1955,  1956},
+    {  1785,  1786,  1867,  1869,  1956,  1957},
+    {  1786,  1787,  1868,  1870,  1957,  1958},
+    {  1787,  1788,  1869,  1871,  1958,  1959},
+    {  1788,  1789,  1870,  1872,  1959,  1960},
+    {  1789,  1790,  1871,  1873,  1960,  1961},
+    {  1790,  1791,  1872,  1874,  1961,  1962},
+    {  1791,  1792,  1873,  1875,  1962,  1963},
+    {  1792,  1793,  1874,  1876,  1963,  1964},
+    {  1793,  1875,  1964,  1965,  -1,  -1},
+    {  1794,  1878,  1966,  1967,  -1,  -1},
+    {  1794,  1795,  1877,  1879,  1967,  1968},
+    {  1795,  1796,  1878,  1880,  1968,  1969},
+    {  1796,  1797,  1879,  1881,  1969,  1970}, // 1880
+    {  1797,  1798,  1880,  1882,  1970,  1971},
+    {  1798,  1799,  1881,  1883,  1971,  1972},
+    {  1799,  1800,  1882,  1884,  1972,  1973},
+    {  1800,  1801,  1883,  1885,  1973,  1974},
+    {  1801,  1802,  1884,  1886,  1974,  1975},
+    {  1802,  1803,  1885,  1887,  1975,  1976},
+    {  1803,  1804,  1886,  1888,  1976,  1977},
+    {  1804,  1805,  1887,  1889,  1977,  1978},
+    {  1805,  1806,  1888,  1890,  1978,  1979},
+    {  1806,  1889,  1979,  1980,  -1,  -1},
+    {  1807,  1892,  1981,  1982,  -1,  -1},
+    {  1807,  1808,  1891,  1893,  1982,  1983},
+    {  1808,  1809,  1892,  1894,  1983,  1984},
+    {  1809,  1810,  1893,  1895,  1984,  1985},
+    {  1810,  1811,  1894,  1896,  1985,  1986},
+    {  1811,  1812,  1895,  1897,  1986,  1987},
+    {  1812,  1813,  1896,  1898,  1987,  1988},
+    {  1813,  1814,  1897,  1899,  1988,  1989},
+    {  1814,  1815,  1898,  1900,  1989,  1990},
+    {  1815,  1816,  1899,  1901,  1990,  1991}, // 1900
+    {  1816,  1817,  1900,  1902,  1991,  1992},
+    {  1817,  1818,  1901,  1903,  1992,  1993},
+    {  1818,  1819,  1902,  1904,  1993,  1994},
+    {  1819,  1820,  1903,  1905,  1994,  1995},
+    {  1820,  1904,  1995,  1996,  -1,  -1},
+    {  1821,  1907,  1997,  1998,  -1,  -1},
+    {  1821,  1822,  1906,  1908,  1998,  1999},
+    {  1822,  1823,  1907,  1909,  1999,  2000},
+    {  1823,  1824,  1908,  1910,  2000,  2001},
+    {  1824,  1825,  1909,  1911,  2001,  2002},
+    {  1825,  1826,  1910,  1912,  2002,  2003},
+    {  1826,  1827,  1911,  1913,  2003,  2004},
+    {  1827,  1828,  1912,  1914,  2004,  2005},
+    {  1828,  1829,  1913,  1915,  2005,  2006},
+    {  1829,  1830,  1914,  1916,  2006,  2007},
+    {  1830,  1831,  1915,  1917,  2007,  2008},
+    {  1831,  1832,  1916,  1918,  2008,  2009},
+    {  1832,  1833,  1917,  1919,  2009,  2010},
+    {  1833,  1834,  1918,  1920,  2010,  2011},
+    {  1834,  1919,  2011,  2012,  -1,  -1}, // 1920
+    {  1835,  1922,  2013,  2014,  -1,  -1},
+    {  1835,  1836,  1921,  1923,  2014,  2015},
+    {  1836,  1837,  1922,  1924,  2015,  2016},
+    {  1837,  1838,  1923,  1925,  2016,  2017},
+    {  1838,  1839,  1924,  1926,  2017,  2018},
+    {  1839,  1840,  1925,  1927,  2018,  2019},
+    {  1840,  1841,  1926,  1928,  2019,  2020},
+    {  1841,  1842,  1927,  1929,  2020,  2021},
+    {  1842,  1843,  1928,  1930,  2021,  2022},
+    {  1843,  1844,  1929,  1931,  2022,  2023},
+    {  1844,  1845,  1930,  1932,  2023,  2024},
+    {  1845,  1846,  1931,  1933,  2024,  2025},
+    {  1846,  1847,  1932,  1934,  2025,  2026},
+    {  1847,  1848,  1933,  1935,  2026,  2027},
+    {  1848,  1934,  2027,  2028,  -1,  -1},
+    {  1849,  1937,  2029,  2030,  -1,  -1},
+    {  1849,  1850,  1936,  1938,  2030,  2031},
+    {  1850,  1851,  1937,  1939,  2031,  2032},
+    {  1851,  1852,  1938,  1940,  2032,  2033},
+    {  1852,  1853,  1939,  1941,  2033,  2034}, // 1940
+    {  1853,  1854,  1940,  1942,  2034,  2035},
+    {  1854,  1855,  1941,  1943,  2035,  2036},
+    {  1855,  1856,  1942,  1944,  2036,  2037},
+    {  1856,  1857,  1943,  1945,  2037,  2038},
+    {  1857,  1858,  1944,  1946,  2038,  2039},
+    {  1858,  1859,  1945,  1947,  2039,  2040},
+    {  1859,  1860,  1946,  1948,  2040,  2041},
+    {  1860,  1861,  1947,  1949,  2041,  2042},
+    {  1861,  1862,  1948,  1950,  2042,  2043},
+    {  1862,  1949,  2043,  2044,  -1,  -1},
+    {  1863,  1952,  2045,  2046,  -1,  -1},
+    {  1863,  1864,  1951,  1953,  2046,  2047},
+    {  1864,  1865,  1952,  1954,  2047,  2048},
+    {  1865,  1866,  1953,  1955,  2048,  2049},
+    {  1866,  1867,  1954,  1956,  2049,  2050},
+    {  1867,  1868,  1955,  1957,  2050,  2051},
+    {  1868,  1869,  1956,  1958,  2051,  2052},
+    {  1869,  1870,  1957,  1959,  2052,  2053},
+    {  1870,  1871,  1958,  1960,  2053,  2054},
+    {  1871,  1872,  1959,  1961,  2054,  2055}, // 1960
+    {  1872,  1873,  1960,  1962,  2055,  2056},
+    {  1873,  1874,  1961,  1963,  2056,  2057},
+    {  1874,  1875,  1962,  1964,  2057,  2058},
+    {  1875,  1876,  1963,  1965,  2058,  2059},
+    {  1876,  1964,  2059,  2060,  -1,  -1},
+    {  1877,  1967,  2061,  2062,  -1,  -1},
+    {  1877,  1878,  1966,  1968,  2062,  2063},
+    {  1878,  1879,  1967,  1969,  2063,  2064},
+    {  1879,  1880,  1968,  1970,  2064,  2065},
+    {  1880,  1881,  1969,  1971,  2065,  2066},
+    {  1881,  1882,  1970,  1972,  2066,  2067},
+    {  1882,  1883,  1971,  1973,  2067,  2068},
+    {  1883,  1884,  1972,  1974,  2068,  2069},
+    {  1884,  1885,  1973,  1975,  2069,  2070},
+    {  1885,  1886,  1974,  1976,  2070,  2071},
+    {  1886,  1887,  1975,  1977,  2071,  2072},
+    {  1887,  1888,  1976,  1978,  2072,  2073},
+    {  1888,  1889,  1977,  1979,  2073,  2074},
+    {  1889,  1890,  1978,  1980,  2074,  2075},
+    {  1890,  1979,  2075,  2076,  -1,  -1}, // 1980
+    {  1891,  1982,  2077,  2078,  -1,  -1},
+    {  1891,  1892,  1981,  1983,  2078,  2079},
+    {  1892,  1893,  1982,  1984,  2079,  2080},
+    {  1893,  1894,  1983,  1985,  2080,  2081},
+    {  1894,  1895,  1984,  1986,  2081,  2082},
+    {  1895,  1896,  1985,  1987,  2082,  2083},
+    {  1896,  1897,  1986,  1988,  2083,  2084},
+    {  1897,  1898,  1987,  1989,  2084,  2085},
+    {  1898,  1899,  1988,  1990,  2085,  2086},
+    {  1899,  1900,  1989,  1991,  2086,  2087},
+    {  1900,  1901,  1990,  1992,  2087,  2088},
+    {  1901,  1902,  1991,  1993,  2088,  2089},
+    {  1902,  1903,  1992,  1994,  2089,  2090},
+    {  1903,  1904,  1993,  1995,  2090,  2091},
+    {  1904,  1905,  1994,  1996,  2091,  2092},
+    {  1905,  1995,  2092,  2093,  -1,  -1},
+    {  1906,  1998,  2094,  2095,  -1,  -1},
+    {  1906,  1907,  1997,  1999,  2095,  2096},
+    {  1907,  1908,  1998,  2000,  2096,  2097},
+    {  1908,  1909,  1999,  2001,  2097,  2098}, // 2000
+    {  1909,  1910,  2000,  2002,  2098,  2099},
+    {  1910,  1911,  2001,  2003,  2099,  2100},
+    {  1911,  1912,  2002,  2004,  2100,  2101},
+    {  1912,  1913,  2003,  2005,  2101,  2102},
+    {  1913,  1914,  2004,  2006,  2102,  2103},
+    {  1914,  1915,  2005,  2007,  2103,  2104},
+    {  1915,  1916,  2006,  2008,  2104,  2105},
+    {  1916,  1917,  2007,  2009,  2105,  2106},
+    {  1917,  1918,  2008,  2010,  2106,  2107},
+    {  1918,  1919,  2009,  2011,  2107,  2108},
+    {  1919,  1920,  2010,  2012,  2108,  2109},
+    {  1920,  2011,  2109,  2110,  -1,  -1},
+    {  1921,  2014,  2111,  2112,  -1,  -1},
+    {  1921,  1922,  2013,  2015,  2112,  2113},
+    {  1922,  1923,  2014,  2016,  2113,  2114},
+    {  1923,  1924,  2015,  2017,  2114,  2115},
+    {  1924,  1925,  2016,  2018,  2115,  2116},
+    {  1925,  1926,  2017,  2019,  2116,  2117},
+    {  1926,  1927,  2018,  2020,  2117,  2118},
+    {  1927,  1928,  2019,  2021,  2118,  2119}, // 2020
+    {  1928,  1929,  2020,  2022,  2119,  2120},
+    {  1929,  1930,  2021,  2023,  2120,  2121},
+    {  1930,  1931,  2022,  2024,  2121,  2122},
+    {  1931,  1932,  2023,  2025,  2122,  2123},
+    {  1932,  1933,  2024,  2026,  2123,  2124},
+    {  1933,  1934,  2025,  2027,  2124,  2125},
+    {  1934,  1935,  2026,  2028,  2125,  2126},
+    {  1935,  2027,  2126,  2127,  -1,  -1},
+    {  1936,  2030,  2128,  2129,  -1,  -1},
+    {  1936,  1937,  2029,  2031,  2129,  2130},
+    {  1937,  1938,  2030,  2032,  2130,  2131},
+    {  1938,  1939,  2031,  2033,  2131,  2132},
+    {  1939,  1940,  2032,  2034,  2132,  2133},
+    {  1940,  1941,  2033,  2035,  2133,  2134},
+    {  1941,  1942,  2034,  2036,  2134,  2135},
+    {  1942,  1943,  2035,  2037,  2135,  2136},
+    {  1943,  1944,  2036,  2038,  2136,  2137},
+    {  1944,  1945,  2037,  2039,  2137,  2138},
+    {  1945,  1946,  2038,  2040,  2138,  2139},
+    {  1946,  1947,  2039,  2041,  2139,  2140}, // 2040
+    {  1947,  1948,  2040,  2042,  2140,  2141},
+    {  1948,  1949,  2041,  2043,  2141,  2142},
+    {  1949,  1950,  2042,  2044,  2142,  2143},
+    {  1950,  2043,  2143,  2144,  -1,  -1},
+    {  1951,  2046,  2145,  2146,  -1,  -1},
+    {  1951,  1952,  2045,  2047,  2146,  2147},
+    {  1952,  1953,  2046,  2048,  2147,  2148},
+    {  1953,  1954,  2047,  2049,  2148,  2149},
+    {  1954,  1955,  2048,  2050,  2149,  2150},
+    {  1955,  1956,  2049,  2051,  2150,  2151},
+    {  1956,  1957,  2050,  2052,  2151,  2152},
+    {  1957,  1958,  2051,  2053,  2152,  2153},
+    {  1958,  1959,  2052,  2054,  2153,  2154},
+    {  1959,  1960,  2053,  2055,  2154,  2155},
+    {  1960,  1961,  2054,  2056,  2155,  2156},
+    {  1961,  1962,  2055,  2057,  2156,  2157},
+    {  1962,  1963,  2056,  2058,  2157,  2158},
+    {  1963,  1964,  2057,  2059,  2158,  2159},
+    {  1964,  1965,  2058,  2060,  2159,  2160},
+    {  1965,  2059,  2160,  2161,  -1,  -1}, // 2060
+    {  1966,  2062,  2162,  2163,  -1,  -1},
+    {  1966,  1967,  2061,  2063,  2163,  2164},
+    {  1967,  1968,  2062,  2064,  2164,  2165},
+    {  1968,  1969,  2063,  2065,  2165,  2166},
+    {  1969,  1970,  2064,  2066,  2166,  2167},
+    {  1970,  1971,  2065,  2067,  2167,  2168},
+    {  1971,  1972,  2066,  2068,  2168,  2169},
+    {  1972,  1973,  2067,  2069,  2169,  2170},
+    {  1973,  1974,  2068,  2070,  2170,  2171},
+    {  1974,  1975,  2069,  2071,  2171,  2172},
+    {  1975,  1976,  2070,  2072,  2172,  2173},
+    {  1976,  1977,  2071,  2073,  2173,  2174},
+    {  1977,  1978,  2072,  2074,  2174,  2175},
+    {  1978,  1979,  2073,  2075,  2175,  2176},
+    {  1979,  1980,  2074,  2076,  2176,  2177},
+    {  1980,  2075,  2177,  2178,  -1,  -1},
+    {  1981,  2078,  2179,  2180,  -1,  -1},
+    {  1981,  1982,  2077,  2079,  2180,  2181},
+    {  1982,  1983,  2078,  2080,  2181,  2182},
+    {  1983,  1984,  2079,  2081,  2182,  2183}, // 2080
+    {  1984,  1985,  2080,  2082,  2183,  2184},
+    {  1985,  1986,  2081,  2083,  2184,  2185},
+    {  1986,  1987,  2082,  2084,  2185,  2186},
+    {  1987,  1988,  2083,  2085,  2186,  2187},
+    {  1988,  1989,  2084,  2086,  2187,  2188},
+    {  1989,  1990,  2085,  2087,  2188,  2189},
+    {  1990,  1991,  2086,  2088,  2189,  2190},
+    {  1991,  1992,  2087,  2089,  2190,  2191},
+    {  1992,  1993,  2088,  2090,  2191,  2192},
+    {  1993,  1994,  2089,  2091,  2192,  2193},
+    {  1994,  1995,  2090,  2092,  2193,  2194},
+    {  1995,  1996,  2091,  2093,  2194,  2195},
+    {  1996,  2092,  2195,  2196,  -1,  -1},
+    {  1997,  2095,  2197,  2198,  -1,  -1},
+    {  1997,  1998,  2094,  2096,  2198,  2199},
+    {  1998,  1999,  2095,  2097,  2199,  2200},
+    {  1999,  2000,  2096,  2098,  2200,  2201},
+    {  2000,  2001,  2097,  2099,  2201,  2202},
+    {  2001,  2002,  2098,  2100,  2202,  2203},
+    {  2002,  2003,  2099,  2101,  2203,  2204}, // 2100
+    {  2003,  2004,  2100,  2102,  2204,  2205},
+    {  2004,  2005,  2101,  2103,  2205,  2206},
+    {  2005,  2006,  2102,  2104,  2206,  2207},
+    {  2006,  2007,  2103,  2105,  2207,  2208},
+    {  2007,  2008,  2104,  2106,  2208,  2209},
+    {  2008,  2009,  2105,  2107,  2209,  2210},
+    {  2009,  2010,  2106,  2108,  2210,  2211},
+    {  2010,  2011,  2107,  2109,  2211,  2212},
+    {  2011,  2012,  2108,  2110,  2212,  2213},
+    {  2012,  2109,  2213,  2214,  -1,  -1},
+    {  2013,  2112,  2215,  2216,  -1,  -1},
+    {  2013,  2014,  2111,  2113,  2216,  2217},
+    {  2014,  2015,  2112,  2114,  2217,  2218},
+    {  2015,  2016,  2113,  2115,  2218,  2219},
+    {  2016,  2017,  2114,  2116,  2219,  2220},
+    {  2017,  2018,  2115,  2117,  2220,  2221},
+    {  2018,  2019,  2116,  2118,  2221,  2222},
+    {  2019,  2020,  2117,  2119,  2222,  2223},
+    {  2020,  2021,  2118,  2120,  2223,  2224},
+    {  2021,  2022,  2119,  2121,  2224,  2225}, // 2120
+    {  2022,  2023,  2120,  2122,  2225,  2226},
+    {  2023,  2024,  2121,  2123,  2226,  2227},
+    {  2024,  2025,  2122,  2124,  2227,  2228},
+    {  2025,  2026,  2123,  2125,  2228,  2229},
+    {  2026,  2027,  2124,  2126,  2229,  2230},
+    {  2027,  2028,  2125,  2127,  2230,  2231},
+    {  2028,  2126,  2231,  2232,  -1,  -1},
+    {  2029,  2129,  2233,  2234,  -1,  -1},
+    {  2029,  2030,  2128,  2130,  2234,  2235},
+    {  2030,  2031,  2129,  2131,  2235,  2236},
+    {  2031,  2032,  2130,  2132,  2236,  2237},
+    {  2032,  2033,  2131,  2133,  2237,  2238},
+    {  2033,  2034,  2132,  2134,  2238,  2239},
+    {  2034,  2035,  2133,  2135,  2239,  2240},
+    {  2035,  2036,  2134,  2136,  2240,  2241},
+    {  2036,  2037,  2135,  2137,  2241,  2242},
+    {  2037,  2038,  2136,  2138,  2242,  2243},
+    {  2038,  2039,  2137,  2139,  2243,  2244},
+    {  2039,  2040,  2138,  2140,  2244,  2245},
+    {  2040,  2041,  2139,  2141,  2245,  2246}, // 2140
+    {  2041,  2042,  2140,  2142,  2246,  2247},
+    {  2042,  2043,  2141,  2143,  2247,  2248},
+    {  2043,  2044,  2142,  2144,  2248,  2249},
+    {  2044,  2143,  2249,  2250,  -1,  -1},
+    {  2045,  2146,  2251,  2252,  -1,  -1},
+    {  2045,  2046,  2145,  2147,  2252,  2253},
+    {  2046,  2047,  2146,  2148,  2253,  2254},
+    {  2047,  2048,  2147,  2149,  2254,  2255},
+    {  2048,  2049,  2148,  2150,  2255,  2256},
+    {  2049,  2050,  2149,  2151,  2256,  2257},
+    {  2050,  2051,  2150,  2152,  2257,  2258},
+    {  2051,  2052,  2151,  2153,  2258,  2259},
+    {  2052,  2053,  2152,  2154,  2259,  2260},
+    {  2053,  2054,  2153,  2155,  2260,  2261},
+    {  2054,  2055,  2154,  2156,  2261,  2262},
+    {  2055,  2056,  2155,  2157,  2262,  2263},
+    {  2056,  2057,  2156,  2158,  2263,  2264},
+    {  2057,  2058,  2157,  2159,  2264,  2265},
+    {  2058,  2059,  2158,  2160,  2265,  2266},
+    {  2059,  2060,  2159,  2161,  2266,  2267}, // 2160
+    {  2060,  2160,  2267,  2268,  -1,  -1},
+    {  2061,  2163,  2269,  2270,  -1,  -1},
+    {  2061,  2062,  2162,  2164,  2270,  2271},
+    {  2062,  2063,  2163,  2165,  2271,  2272},
+    {  2063,  2064,  2164,  2166,  2272,  2273},
+    {  2064,  2065,  2165,  2167,  2273,  2274},
+    {  2065,  2066,  2166,  2168,  2274,  2275},
+    {  2066,  2067,  2167,  2169,  2275,  2276},
+    {  2067,  2068,  2168,  2170,  2276,  2277},
+    {  2068,  2069,  2169,  2171,  2277,  2278},
+    {  2069,  2070,  2170,  2172,  2278,  2279},
+    {  2070,  2071,  2171,  2173,  2279,  2280},
+    {  2071,  2072,  2172,  2174,  2280,  2281},
+    {  2072,  2073,  2173,  2175,  2281,  2282},
+    {  2073,  2074,  2174,  2176,  2282,  2283},
+    {  2074,  2075,  2175,  2177,  2283,  2284},
+    {  2075,  2076,  2176,  2178,  2284,  2285},
+    {  2076,  2177,  2285,  2286,  -1,  -1},
+    {  2077,  2180,  2287,  2288,  -1,  -1},
+    {  2077,  2078,  2179,  2181,  2288,  2289}, // 2180
+    {  2078,  2079,  2180,  2182,  2289,  2290},
+    {  2079,  2080,  2181,  2183,  2290,  2291},
+    {  2080,  2081,  2182,  2184,  2291,  2292},
+    {  2081,  2082,  2183,  2185,  2292,  2293},
+    {  2082,  2083,  2184,  2186,  2293,  2294},
+    {  2083,  2084,  2185,  2187,  2294,  2295},
+    {  2084,  2085,  2186,  2188,  2295,  2296},
+    {  2085,  2086,  2187,  2189,  2296,  2297},
+    {  2086,  2087,  2188,  2190,  2297,  2298},
+    {  2087,  2088,  2189,  2191,  2298,  2299},
+    {  2088,  2089,  2190,  2192,  2299,  2300},
+    {  2089,  2090,  2191,  2193,  2300,  2301},
+    {  2090,  2091,  2192,  2194,  2301,  2302},
+    {  2091,  2092,  2193,  2195,  2302,  2303},
+    {  2092,  2093,  2194,  2196,  2303,  2304},
+    {  2093,  2195,  2304,  2305,  -1,  -1},
+    {  2094,  2198,  2306,  2307,  -1,  -1},
+    {  2094,  2095,  2197,  2199,  2307,  2308},
+    {  2095,  2096,  2198,  2200,  2308,  2309},
+    {  2096,  2097,  2199,  2201,  2309,  2310}, // 2200
+    {  2097,  2098,  2200,  2202,  2310,  2311},
+    {  2098,  2099,  2201,  2203,  2311,  2312},
+    {  2099,  2100,  2202,  2204,  2312,  2313},
+    {  2100,  2101,  2203,  2205,  2313,  2314},
+    {  2101,  2102,  2204,  2206,  2314,  2315},
+    {  2102,  2103,  2205,  2207,  2315,  2316},
+    {  2103,  2104,  2206,  2208,  2316,  2317},
+    {  2104,  2105,  2207,  2209,  2317,  2318},
+    {  2105,  2106,  2208,  2210,  2318,  2319},
+    {  2106,  2107,  2209,  2211,  2319,  2320},
+    {  2107,  2108,  2210,  2212,  2320,  2321},
+    {  2108,  2109,  2211,  2213,  2321,  2322},
+    {  2109,  2110,  2212,  2214,  2322,  2323},
+    {  2110,  2213,  2323,  2324,  -1,  -1},
+    {  2111,  2216,  2325,  2326,  -1,  -1},
+    {  2111,  2112,  2215,  2217,  2326,  2327},
+    {  2112,  2113,  2216,  2218,  2327,  2328},
+    {  2113,  2114,  2217,  2219,  2328,  2329},
+    {  2114,  2115,  2218,  2220,  2329,  2330},
+    {  2115,  2116,  2219,  2221,  2330,  2331}, // 2220
+    {  2116,  2117,  2220,  2222,  2331,  2332},
+    {  2117,  2118,  2221,  2223,  2332,  2333},
+    {  2118,  2119,  2222,  2224,  2333,  2334},
+    {  2119,  2120,  2223,  2225,  2334,  2335},
+    {  2120,  2121,  2224,  2226,  2335,  2336},
+    {  2121,  2122,  2225,  2227,  2336,  2337},
+    {  2122,  2123,  2226,  2228,  2337,  2338},
+    {  2123,  2124,  2227,  2229,  2338,  2339},
+    {  2124,  2125,  2228,  2230,  2339,  2340},
+    {  2125,  2126,  2229,  2231,  2340,  2341},
+    {  2126,  2127,  2230,  2232,  2341,  2342},
+    {  2127,  2231,  2342,  2343,  -1,  -1},
+    {  2128,  2234,  2344,  2345,  -1,  -1},
+    {  2128,  2129,  2233,  2235,  2345,  2346},
+    {  2129,  2130,  2234,  2236,  2346,  2347},
+    {  2130,  2131,  2235,  2237,  2347,  2348},
+    {  2131,  2132,  2236,  2238,  2348,  2349},
+    {  2132,  2133,  2237,  2239,  2349,  2350},
+    {  2133,  2134,  2238,  2240,  2350,  2351},
+    {  2134,  2135,  2239,  2241,  2351,  2352}, // 2240
+    {  2135,  2136,  2240,  2242,  2352,  2353},
+    {  2136,  2137,  2241,  2243,  2353,  2354},
+    {  2137,  2138,  2242,  2244,  2354,  2355},
+    {  2138,  2139,  2243,  2245,  2355,  2356},
+    {  2139,  2140,  2244,  2246,  2356,  2357},
+    {  2140,  2141,  2245,  2247,  2357,  2358},
+    {  2141,  2142,  2246,  2248,  2358,  2359},
+    {  2142,  2143,  2247,  2249,  2359,  2360},
+    {  2143,  2144,  2248,  2250,  2360,  2361},
+    {  2144,  2249,  2361,  2362,  -1,  -1},
+    {  2145,  2252,  2363,  2364,  -1,  -1},
+    {  2145,  2146,  2251,  2253,  2364,  2365},
+    {  2146,  2147,  2252,  2254,  2365,  2366},
+    {  2147,  2148,  2253,  2255,  2366,  2367},
+    {  2148,  2149,  2254,  2256,  2367,  2368},
+    {  2149,  2150,  2255,  2257,  2368,  2369},
+    {  2150,  2151,  2256,  2258,  2369,  2370},
+    {  2151,  2152,  2257,  2259,  2370,  2371},
+    {  2152,  2153,  2258,  2260,  2371,  2372},
+    {  2153,  2154,  2259,  2261,  2372,  2373}, // 2260
+    {  2154,  2155,  2260,  2262,  2373,  2374},
+    {  2155,  2156,  2261,  2263,  2374,  2375},
+    {  2156,  2157,  2262,  2264,  2375,  2376},
+    {  2157,  2158,  2263,  2265,  2376,  2377},
+    {  2158,  2159,  2264,  2266,  2377,  2378},
+    {  2159,  2160,  2265,  2267,  2378,  2379},
+    {  2160,  2161,  2266,  2268,  2379,  2380},
+    {  2161,  2267,  2380,  2381,  -1,  -1},
+    {  2162,  2270,  2382,  2383,  -1,  -1},
+    {  2162,  2163,  2269,  2271,  2383,  2384},
+    {  2163,  2164,  2270,  2272,  2384,  2385},
+    {  2164,  2165,  2271,  2273,  2385,  2386},
+    {  2165,  2166,  2272,  2274,  2386,  2387},
+    {  2166,  2167,  2273,  2275,  2387,  2388},
+    {  2167,  2168,  2274,  2276,  2388,  2389},
+    {  2168,  2169,  2275,  2277,  2389,  2390},
+    {  2169,  2170,  2276,  2278,  2390,  2391},
+    {  2170,  2171,  2277,  2279,  2391,  2392},
+    {  2171,  2172,  2278,  2280,  2392,  2393},
+    {  2172,  2173,  2279,  2281,  2393,  2394}, // 2280
+    {  2173,  2174,  2280,  2282,  2394,  2395},
+    {  2174,  2175,  2281,  2283,  2395,  2396},
+    {  2175,  2176,  2282,  2284,  2396,  2397},
+    {  2176,  2177,  2283,  2285,  2397,  2398},
+    {  2177,  2178,  2284,  2286,  2398,  2399},
+    {  2178,  2285,  2399,  2400,  -1,  -1},
+    {  2179,  2288,  -1,  -1,  -1,  -1},
+    {  2179,  2180,  2287,  2289,  -1,  -1},
+    {  2180,  2181,  2288,  2290,  -1,  -1},
+    {  2181,  2182,  2289,  2291,  -1,  -1},
+    {  2182,  2183,  2290,  2292,  -1,  -1},
+    {  2183,  2184,  2291,  2293,  -1,  -1},
+    {  2184,  2185,  2292,  2294,  -1,  -1},
+    {  2185,  2186,  2293,  2295,  -1,  -1},
+    {  2186,  2187,  2294,  2296,  -1,  -1},
+    {  2187,  2188,  2295,  2297,  -1,  -1},
+    {  2188,  2189,  2296,  2298,  -1,  -1},
+    {  2189,  2190,  2297,  2299,  -1,  -1},
+    {  2190,  2191,  2298,  2300,  -1,  -1},
+    {  2191,  2192,  2299,  2301,  -1,  -1}, // 2300
+    {  2192,  2193,  2300,  2302,  -1,  -1},
+    {  2193,  2194,  2301,  2303,  -1,  -1},
+    {  2194,  2195,  2302,  2304,  -1,  -1},
+    {  2195,  2196,  2303,  2305,  -1,  -1},
+    {  2196,  2304,  -1,  -1,  -1,  -1},
+    {  2197,  2307,  -1,  -1,  -1,  -1},
+    {  2197,  2198,  2306,  2308,  -1,  -1},
+    {  2198,  2199,  2307,  2309,  -1,  -1},
+    {  2199,  2200,  2308,  2310,  -1,  -1},
+    {  2200,  2201,  2309,  2311,  -1,  -1},
+    {  2201,  2202,  2310,  2312,  -1,  -1},
+    {  2202,  2203,  2311,  2313,  -1,  -1},
+    {  2203,  2204,  2312,  2314,  -1,  -1},
+    {  2204,  2205,  2313,  2315,  -1,  -1},
+    {  2205,  2206,  2314,  2316,  -1,  -1},
+    {  2206,  2207,  2315,  2317,  -1,  -1},
+    {  2207,  2208,  2316,  2318,  -1,  -1},
+    {  2208,  2209,  2317,  2319,  -1,  -1},
+    {  2209,  2210,  2318,  2320,  -1,  -1},
+    {  2210,  2211,  2319,  2321,  -1,  -1}, // 2320
+    {  2211,  2212,  2320,  2322,  -1,  -1},
+    {  2212,  2213,  2321,  2323,  -1,  -1},
+    {  2213,  2214,  2322,  2324,  -1,  -1},
+    {  2214,  2323,  -1,  -1,  -1,  -1},
+    {  2215,  2326,  -1,  -1,  -1,  -1},
+    {  2215,  2216,  2325,  2327,  -1,  -1},
+    {  2216,  2217,  2326,  2328,  -1,  -1},
+    {  2217,  2218,  2327,  2329,  -1,  -1},
+    {  2218,  2219,  2328,  2330,  -1,  -1},
+    {  2219,  2220,  2329,  2331,  -1,  -1},
+    {  2220,  2221,  2330,  2332,  -1,  -1},
+    {  2221,  2222,  2331,  2333,  -1,  -1},
+    {  2222,  2223,  2332,  2334,  -1,  -1},
+    {  2223,  2224,  2333,  2335,  -1,  -1},
+    {  2224,  2225,  2334,  2336,  -1,  -1},
+    {  2225,  2226,  2335,  2337,  -1,  -1},
+    {  2226,  2227,  2336,  2338,  -1,  -1},
+    {  2227,  2228,  2337,  2339,  -1,  -1},
+    {  2228,  2229,  2338,  2340,  -1,  -1},
+    {  2229,  2230,  2339,  2341,  -1,  -1}, // 2340
+    {  2230,  2231,  2340,  2342,  -1,  -1},
+    {  2231,  2232,  2341,  2343,  -1,  -1},
+    {  2232,  2342,  -1,  -1,  -1,  -1},
+    {  2233,  2345,  -1,  -1,  -1,  -1},
+    {  2233,  2234,  2344,  2346,  -1,  -1},
+    {  2234,  2235,  2345,  2347,  -1,  -1},
+    {  2235,  2236,  2346,  2348,  -1,  -1},
+    {  2236,  2237,  2347,  2349,  -1,  -1},
+    {  2237,  2238,  2348,  2350,  -1,  -1},
+    {  2238,  2239,  2349,  2351,  -1,  -1},
+    {  2239,  2240,  2350,  2352,  -1,  -1},
+    {  2240,  2241,  2351,  2353,  -1,  -1},
+    {  2241,  2242,  2352,  2354,  -1,  -1},
+    {  2242,  2243,  2353,  2355,  -1,  -1},
+    {  2243,  2244,  2354,  2356,  -1,  -1},
+    {  2244,  2245,  2355,  2357,  -1,  -1},
+    {  2245,  2246,  2356,  2358,  -1,  -1},
+    {  2246,  2247,  2357,  2359,  -1,  -1},
+    {  2247,  2248,  2358,  2360,  -1,  -1},
+    {  2248,  2249,  2359,  2361,  -1,  -1}, // 2360
+    {  2249,  2250,  2360,  2362,  -1,  -1},
+    {  2250,  2361,  -1,  -1,  -1,  -1},
+    {  2251,  2364,  -1,  -1,  -1,  -1},
+    {  2251,  2252,  2363,  2365,  -1,  -1},
+    {  2252,  2253,  2364,  2366,  -1,  -1},
+    {  2253,  2254,  2365,  2367,  -1,  -1},
+    {  2254,  2255,  2366,  2368,  -1,  -1},
+    {  2255,  2256,  2367,  2369,  -1,  -1},
+    {  2256,  2257,  2368,  2370,  -1,  -1},
+    {  2257,  2258,  2369,  2371,  -1,  -1},
+    {  2258,  2259,  2370,  2372,  -1,  -1},
+    {  2259,  2260,  2371,  2373,  -1,  -1},
+    {  2260,  2261,  2372,  2374,  -1,  -1},
+    {  2261,  2262,  2373,  2375,  -1,  -1},
+    {  2262,  2263,  2374,  2376,  -1,  -1},
+    {  2263,  2264,  2375,  2377,  -1,  -1},
+    {  2264,  2265,  2376,  2378,  -1,  -1},
+    {  2265,  2266,  2377,  2379,  -1,  -1},
+    {  2266,  2267,  2378,  2380,  -1,  -1},
+    {  2267,  2268,  2379,  2381,  -1,  -1}, // 2380
+    {  2268,  2380,  -1,  -1,  -1,  -1},
+    {  2269,  2383,  -1,  -1,  -1,  -1},
+    {  2269,  2270,  2382,  2384,  -1,  -1},
+    {  2270,  2271,  2383,  2385,  -1,  -1},
+    {  2271,  2272,  2384,  2386,  -1,  -1},
+    {  2272,  2273,  2385,  2387,  -1,  -1},
+    {  2273,  2274,  2386,  2388,  -1,  -1},
+    {  2274,  2275,  2387,  2389,  -1,  -1},
+    {  2275,  2276,  2388,  2390,  -1,  -1},
+    {  2276,  2277,  2389,  2391,  -1,  -1},
+    {  2277,  2278,  2390,  2392,  -1,  -1},
+    {  2278,  2279,  2391,  2393,  -1,  -1},
+    {  2279,  2280,  2392,  2394,  -1,  -1},
+    {  2280,  2281,  2393,  2395,  -1,  -1},
+    {  2281,  2282,  2394,  2396,  -1,  -1},
+    {  2282,  2283,  2395,  2397,  -1,  -1},
+    {  2283,  2284,  2396,  2398,  -1,  -1},
+    {  2284,  2285,  2397,  2399,  -1,  -1},
+    {  2285,  2286,  2398,  2400,  -1,  -1},
+    {  2286,  2399,  -1,  -1,  -1,  -1} // 2400
+  };
+
+  for (Int_t i=0; i<2401; i++)
+      (*this)[i].SetNeighbors(nn[i][0], nn[i][1], nn[i][2],
+                              nn[i][3], nn[i][4], nn[i][5]);
+}
Index: /tags/Mars-V0.9/mgeom/MGeomCamECO1000HG.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamECO1000HG.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamECO1000HG.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MGeomCamECO1000HG
+#define MARS_MGeomCamECO1000HG
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamECO1000HG : public MGeomCam
+{
+private:
+    void CreateCam();
+    void CreateNN();
+
+public:
+    MGeomCamECO1000HG(const char *name=NULL);
+
+    ClassDef(MGeomCamECO1000HG, 1)		// Geometry class for the Magic camera
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgeom/MGeomCamMagic.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamMagic.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamMagic.cc	(revision 9772)
@@ -0,0 +1,925 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagic
+//
+// This class stores the geometry information of the Magic camera.
+// All information are copied from tables, see source code.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagic.h"
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamMagic);
+
+// --------------------------------------------------------------------------
+//
+//  Magic camera has 577 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamMagic::MGeomCamMagic(const char *name)
+    : MGeomCam(577, 17, name, "Geometry information of Magic Camera")
+{
+    CreateCam();
+    CreateNN();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information from a table into the pixel objects.
+//
+void MGeomCamMagic::CreateCam()
+{
+    //
+    //   fill the geometry class with the coordinates of the MAGIC camera
+    //
+    //*fLog << inf << " Creating Magic geometry " << endl ;
+
+    //
+    //   here define the hardwire things of the magic telescope
+    //
+    const Float_t xtemp[577] = {
+        +000.000,   30.000,   15.000,  -15.000,  -30.000,  -15.000,   15.000,   60.000,  //   0
+        +045.000,   30.000,    0.000,  -30.000,  -45.000,  -60.000,  -45.000,  -30.000,  //   8
+        +000.000,   30.000,   45.000,   90.000,   75.000,   60.000,   45.000,   15.000,  //  16
+        -015.000,  -45.000,  -60.000,  -75.000,  -90.000,  -75.000,  -60.000,  -45.000,  //  24
+        -015.000,   15.000,   45.000,   60.000,   75.000,  120.000,  105.000,   90.000,  //  32
+        +075.000,   60.000,   30.000,    0.000,  -30.000,  -60.000,  -75.000,  -90.000,  //  40
+        -105.000, -120.000, -105.000,  -90.000,  -75.000,  -60.000,  -30.000,    0.000,  //  48
+        +030.000,   60.000,   75.000,   90.000,  105.000,  150.000,  135.000,  120.000,  //  56
+        +105.000,   90.000,   75.000,   45.000,   15.000,  -15.000,  -45.000,  -75.000,  //  64
+        -090.000, -105.000, -120.000, -135.000, -150.000, -135.000, -120.000, -105.000,  //  72
+        -090.000,  -75.000,  -45.000,  -15.000,   15.000,   45.000,   75.000,   90.000,  //  80
+        +105.000,  120.000,  135.000,  180.000,  165.000,  150.000,  135.000,  120.000,  //  88
+        +105.000,   90.000,   60.000,   30.000,    0.000,  -30.000,  -60.000,  -90.000,  //  96
+        -105.000, -120.000, -135.000, -150.000, -165.000, -180.000, -165.000, -150.000,  // 104
+        -135.000, -120.000, -105.000,  -90.000,  -60.000,  -30.000,    0.000,   30.000,  // 112
+        +060.000,   90.000,  105.000,  120.000,  135.000,  150.000,  165.000,  210.000,  // 120
+        +195.000,  180.000,  165.000,  150.000,  135.000,  120.000,  105.000,   75.000,  // 128
+        +045.000,   15.000,  -15.000,  -45.000,  -75.000, -105.000, -120.000, -135.000,  // 136
+        -150.000, -165.000, -180.000, -195.000, -210.000, -195.000, -180.000, -165.000,  // 144
+        -150.000, -135.000, -120.000, -105.000,  -75.000,  -45.000,  -15.000,   15.000,  // 152
+        +045.000,   75.000,  105.000,  120.000,  135.000,  150.000,  165.000,  180.000,  // 160
+        +195.000,  240.000,  225.000,  210.000,  195.000,  180.000,  165.000,  150.000,  // 168
+        +135.000,  120.000,   90.000,   60.000,   30.000,    0.000,  -30.000,  -60.000,  // 176
+        -090.000, -120.000, -135.000, -150.000, -165.000, -180.000, -195.000, -210.000,  // 184
+        -225.000, -240.000, -225.000, -210.000, -195.000, -180.000, -165.000, -150.000,  // 192
+        -135.000, -120.000,  -90.000,  -60.000,  -30.000,    0.000,   30.000,   60.000,  // 200
+        +090.000,  120.000,  135.000,  150.000,  165.000,  180.000,  195.000,  210.000,  // 208
+        +225.000,  270.000,  255.000,  240.000,  225.000,  210.000,  195.000,  180.000,  // 216
+        +165.000,  150.000,  135.000,  105.000,   75.000,   45.000,   15.000,  -15.000,  // 224
+        -045.000,  -75.000, -105.000, -135.000, -150.000, -165.000, -180.000, -195.000,  // 232
+        -210.000, -225.000, -240.000, -255.000, -270.000, -255.000, -240.000, -225.000,  // 240
+        -210.000, -195.000, -180.000, -165.000, -150.000, -135.000, -105.000,  -75.000,  // 248
+        -045.000,  -15.000,   15.000,   45.000,   75.000,  105.000,  135.000,  150.000,  // 256
+        +165.000,  180.000,  195.000,  210.000,  225.000,  240.000,  255.000,  300.000,  // 264
+        +285.000,  270.000,  255.000,  240.000,  225.000,  210.000,  195.000,  180.000,  // 272
+        +165.000,  150.000,  120.000,   90.000,   60.000,   30.000,    0.000,  -30.000,  // 280
+        -060.000,  -90.000, -120.000, -150.000, -165.000, -180.000, -195.000, -210.000,  // 288
+        -225.000, -240.000, -255.000, -270.000, -285.000, -300.000, -285.000, -270.000,  // 296
+        -255.000, -240.000, -225.000, -210.000, -195.000, -180.000, -165.000, -150.000,  // 304
+        -120.000,  -90.000,  -60.000,  -30.000,    0.000,   30.000,   60.000,   90.000,  // 312
+        +120.000,  150.000,  165.000,  180.000,  195.000,  210.000,  225.000,  240.000,  // 320
+        +255.000,  270.000,  285.000,  330.000,  315.000,  300.000,  285.000,  270.000,  // 328
+        +255.000,  240.000,  225.000,  210.000,  195.000,  180.000,  165.000,  135.000,  // 336
+        +105.000,   75.000,   45.000,   15.000,  -15.000,  -45.000,  -75.000, -105.000,  // 344
+        -135.000, -165.000, -180.000, -195.000, -210.000, -225.000, -240.000, -255.000,  // 352
+        -270.000, -285.000, -300.000, -315.000, -330.000, -315.000, -300.000, -285.000,  // 360
+        -270.000, -255.000, -240.000, -225.000, -210.000, -195.000, -180.000, -165.000,  // 368
+        -135.000, -105.000,  -75.000,  -45.000,  -15.000,   15.000,   45.000,   75.000,  // 376
+        +105.000,  135.000,  165.000,  180.000,  195.000,  210.000,  225.000,  240.000,  // 384
+        +255.000,  270.000,  285.000,  300.000,  315.000,  360.000,  330.000,  300.000,  // 392
+        +270.000,  240.000,  210.000,  150.000,   90.000,   30.000,  -30.000,  -90.000,  // 400
+        -150.000, -210.000, -240.000, -270.000, -300.000, -330.000, -360.000, -360.000,  // 408
+        -330.000, -300.000, -270.000, -240.000, -210.000, -150.000,  -90.000,  -30.000,  // 416
+        +030.000,   90.000,  150.000,  210.000,  240.000,  270.000,  300.000,  330.000,  // 424
+        +360.000,  420.000,  390.000,  360.000,  330.000,  300.000,  270.000,  240.000,  // 432
+        +180.000,  120.000,   60.000,    0.000,  -60.000, -120.000, -180.000, -240.000,  // 440
+        -270.000, -300.000, -330.000, -360.000, -390.000, -420.000, -420.000, -390.000,  // 448
+        -360.000, -330.000, -300.000, -270.000, -240.000, -180.000, -120.000,  -60.000,  // 456
+        +000.000,   60.000,  120.000,  180.000,  240.000,  270.000,  300.000,  330.000,  // 464
+        +360.000,  390.000,  420.000,  480.000,  450.000,  420.000,  390.000,  360.000,  // 472
+        +330.000,  300.000,  270.000,  210.000,  150.000,   90.000,   30.000,  -30.000,  // 480
+        -090.000, -150.000, -210.000, -270.000, -300.000, -330.000, -360.000, -390.000,  // 488
+        -420.000, -450.000, -480.000, -480.000, -450.000, -420.000, -390.000, -360.000,  // 496
+        -330.000, -300.000, -270.000, -210.000, -150.000,  -90.000,  -30.000,   30.000,  // 504
+        +090.000,  150.000,  210.000,  270.000,  300.000,  330.000,  360.000,  390.000,  // 512
+        +420.000,  450.000,  480.000,  540.000,  510.000,  480.000,  450.000,  420.000,  // 520
+        +390.000,  360.000,  330.000,  300.000,  240.000,  180.000,  120.000,   60.000,  // 528
+        +000.000,  -60.000, -120.000, -180.000, -240.000, -300.000, -330.000, -360.000,  // 536
+        -390.000, -420.000, -450.000, -480.000, -510.000, -540.000, -540.000, -510.000,  // 544
+        -480.000, -450.000, -420.000, -390.000, -360.000, -330.000, -300.000, -240.000,  // 552
+        -180.000, -120.000,  -60.000,    0.000,   60.000,  120.000,  180.000,  240.000,  // 560
+        +300.000,  330.000,  360.000,  390.000,  420.000,  450.000,  480.000,  510.000,  // 568
+        +540.000                                                                         // 576
+    };
+
+    const Float_t ytemp[577] = {
+        +000.000,    0.000,   25.981,   25.981,    0.000,  -25.981,  -25.981,    0.000,  //   0
+        +025.981,   51.961,   51.961,   51.961,   25.981,    0.000,  -25.981,  -51.961,  //   8
+        -051.961,  -51.961,  -25.981,    0.000,   25.981,   51.961,   77.942,   77.942,  //  16
+        +077.942,   77.942,   51.961,   25.981,    0.000,  -25.981,  -51.961,  -77.942,  //  24
+        -077.942,  -77.942,  -77.942,  -51.961,  -25.981,    0.000,   25.981,   51.961,  //  32
+        +077.942,  103.923,  103.923,  103.923,  103.923,  103.923,   77.942,   51.961,  //  40
+        +025.981,    0.000,  -25.981,  -51.961,  -77.942, -103.923, -103.923, -103.923,  //  48
+        -103.923, -103.923,  -77.942,  -51.961,  -25.981,    0.000,   25.981,   51.961,  //  56
+        +077.942,  103.923,  129.904,  129.904,  129.904,  129.904,  129.904,  129.904,  //  64
+        +103.923,   77.942,   51.961,   25.981,    0.000,  -25.981,  -51.961,  -77.942,  //  72
+        -103.923, -129.904, -129.904, -129.904, -129.904, -129.904, -129.904, -103.923,  //  80
+        -077.942,  -51.961,  -25.981,    0.000,   25.981,   51.961,   77.942,  103.923,  //  88
+        +129.904,  155.885,  155.885,  155.885,  155.885,  155.885,  155.885,  155.885,  //  96
+        +129.904,  103.923,   77.942,   51.961,   25.981,    0.000,  -25.981,  -51.961,  // 104
+        -077.942, -103.923, -129.904, -155.885, -155.885, -155.885, -155.885, -155.885,  // 112
+        -155.885, -155.885, -129.904, -103.923,  -77.942,  -51.961,  -25.981,    0.000,  // 120
+        +025.981,   51.961,   77.942,  103.923,  129.904,  155.885,  181.865,  181.865,  // 128
+        +181.865,  181.865,  181.865,  181.865,  181.865,  181.865,  155.885,  129.904,  // 136
+        +103.923,   77.942,   51.961,   25.981,    0.000,  -25.981,  -51.961,  -77.942,  // 144
+        -103.923, -129.904, -155.885, -181.865, -181.865, -181.865, -181.865, -181.865,  // 152
+        -181.865, -181.865, -181.865, -155.885, -129.904, -103.923,  -77.942,  -51.961,  // 160
+        -025.981,    0.000,   25.981,   51.961,   77.942,  103.923,  129.904,  155.885,  // 168
+        +181.865,  207.846,  207.846,  207.846,  207.846,  207.846,  207.846,  207.846,  // 176
+        +207.846,  207.846,  181.865,  155.885,  129.904,  103.923,   77.942,   51.961,  // 184
+        +025.981,    0.000,  -25.981,  -51.961,  -77.942, -103.923, -129.904, -155.885,  // 192
+        -181.865, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846,  // 200
+        -207.846, -207.846, -181.865, -155.885, -129.904, -103.923,  -77.942,  -51.961,  // 208
+        -025.981,    0.000,   25.981,   51.961,   77.942,  103.923,  129.904,  155.885,  // 216
+        +181.865,  207.846,  233.827,  233.827,  233.827,  233.827,  233.827,  233.827,  // 224
+        +233.827,  233.827,  233.827,  233.827,  207.846,  181.865,  155.885,  129.904,  // 232
+        +103.923,   77.942,   51.961,   25.981,    0.000,  -25.981,  -51.961,  -77.942,  // 240
+        -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -233.827, -233.827,  // 248
+        -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -207.846,  // 256
+        -181.865, -155.885, -129.904, -103.923,  -77.942,  -51.961,  -25.981,    0.000,  // 264
+        +025.981,   51.961,   77.942,  103.923,  129.904,  155.885,  181.865,  207.846,  // 272
+        +233.827,  259.808,  259.808,  259.808,  259.808,  259.808,  259.808,  259.808,  // 280
+        +259.808,  259.808,  259.808,  259.808,  233.827,  207.846,  181.865,  155.885,  // 288
+        +129.904,  103.923,   77.942,   51.961,   25.981,    0.000,  -25.981,  -51.961,  // 296
+        -077.942, -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808,  // 304
+        -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808,  // 312
+        -259.808, -259.808, -233.827, -207.846, -181.865, -155.885, -129.904, -103.923,  // 320
+        -077.942,  -51.961,  -25.981,    0.000,   25.981,   51.961,   77.942,  103.923,  // 328
+        +129.904,  155.885,  181.865,  207.846,  233.827,  259.808,  285.788,  285.788,  // 336
+        +285.788,  285.788,  285.788,  285.788,  285.788,  285.788,  285.788,  285.788,  // 344
+        +285.788,  285.788,  259.808,  233.827,  207.846,  181.865,  155.885,  129.904,  // 352
+        +103.923,   77.942,   51.961,   25.981,    0.000,  -25.981,  -51.961,  -77.942,  // 360
+        -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788,  // 368
+        -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788,  // 376
+        -285.788, -285.788, -285.788, -259.808, -233.827, -207.846, -181.865, -155.885,  // 384
+        -129.904, -103.923,  -77.942,  -51.961,  -25.981,   34.641,   86.603,  138.564,  // 392
+        +190.526,  242.487,  294.449,  329.090,  329.090,  329.090,  329.090,  329.090,  // 400
+        +329.090,  294.449,  242.487,  190.526,  138.564,   86.603,   34.641,  -34.641,  // 408
+        -086.603, -138.564, -190.526, -242.487, -294.449, -329.090, -329.090, -329.090,  // 416
+        -329.090, -329.090, -329.090, -294.449, -242.487, -190.526, -138.564,  -86.603,  // 424
+        -034.641,   34.641,   86.603,  138.564,  190.526,  242.487,  294.449,  346.410,  // 432
+        +381.051,  381.051,  381.051,  381.051,  381.051,  381.051,  381.051,  346.410,  // 440
+        +294.449,  242.487,  190.526,  138.564,   86.603,   34.641,  -34.641,  -86.603,  // 448
+        -138.564, -190.526, -242.487, -294.449, -346.410, -381.051, -381.051, -381.051,  // 456
+        -381.051, -381.051, -381.051, -381.051, -346.410, -294.449, -242.487, -190.526,  // 464
+        -138.564,  -86.603,  -34.641,   34.641,   86.603,  138.564,  190.526,  242.487,  // 472
+        +294.449,  346.410,  398.372,  433.013,  433.013,  433.013,  433.013,  433.013,  // 480
+        +433.013,  433.013,  433.013,  398.372,  346.410,  294.449,  242.487,  190.526,  // 488
+        +138.564,   86.603,   34.641,  -34.641,  -86.603, -138.564, -190.526, -242.487,  // 496
+        -294.449, -346.410, -398.372, -433.013, -433.013, -433.013, -433.013, -433.013,  // 504
+        -433.013, -433.013, -433.013, -398.372, -346.410, -294.449, -242.487, -190.526,  // 512
+        -138.564,  -86.603,  -34.641,   34.641,   86.603,  138.564,  190.526,  242.487,  // 520
+        +294.449,  346.410,  398.372,  450.333,  484.974,  484.974,  484.974,  484.974,  // 528
+        +484.974,  484.974,  484.974,  484.974,  484.974,  450.333,  398.372,  346.410,  // 536
+        +294.449,  242.487,  190.526,  138.564,   86.603,   34.641,  -34.641,  -86.603,  // 544
+        -138.564, -190.526, -242.487, -294.449, -346.410, -398.372, -450.333, -484.974,  // 552
+        -484.974, -484.974, -484.974, -484.974, -484.974, -484.974, -484.974, -484.974,  // 560
+        -450.333, -398.372, -346.410, -294.449, -242.487, -190.526, -138.564,  -86.603,  // 568
+        -034.641                                                                         // 576
+    };
+/*
+    const Float_t dtemp[577] = {
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //   0
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //   8
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  16
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  24
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  32
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  40
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  48
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  56
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  64
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  72
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  80
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  88
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  //  96
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 104
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 112
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 120
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 128
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 136
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 144
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 152
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 160
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 168
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 176
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 184
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 192
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 200
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 208
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 216
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 224
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 232
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 240
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 248
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 256
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 264
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 272
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 280
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 288
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 296
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 304
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 312
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 320
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 328
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 336
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 344
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 352
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 360
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 368
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 376
+        30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00, 30.00,  // 384
+        30.00, 30.00, 30.00, 30.00, 30.00, 60.00, 60.00, 60.00,  // 392
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 400
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 408
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 416
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 424
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 432
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 440
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 448
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 456
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 464
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 472
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 480
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 488
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 496
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 504
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 512
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 520
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 528
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 536
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 544
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 552
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 560
+        60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00, 60.00,  // 568
+        60.00  };                                                // 576
+*/
+    const Byte_t sector[577] = {
+        0, 1, 2, 3, 4, 5, 6, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+        1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 1,
+        1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5,
+        6, 6, 6, 6, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
+        4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 1, 1, 1, 1,
+        1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4,
+        4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1,
+        1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4,
+        4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 1, 1,
+        1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
+        3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
+        6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
+        2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4,
+        4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6,
+        6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
+        2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4,
+        4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6,
+        6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
+        3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5,
+        5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1,
+        1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4,
+        4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1,
+        1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4,
+        4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
+        1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3,
+        3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5,
+        5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+        2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4,
+        4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6,
+        6, 6, 6, 6, 6, 6, 6 };
+
+    //
+    //   fill the pixels list with this data
+    //
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+        (*this)[i].Set(xtemp[i], ytemp[i], i>396?60:30, sector[i], i>396?1:0);
+    // (*this)[i].Set(xtemp[i], ytemp[i], i>396?60:30, i>396?sector[i]+6:sector[i]);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the next neighbor information from a table into the pixel
+//  objects.
+//
+void MGeomCamMagic::CreateNN()
+{
+    const Short_t nn[577][6] = {         // Neighbors of #
+        {   1,   2,   3,   4,   5,   6}, // 0
+        {   0,   2,   6,   7,   8,  18},
+        {   0,   1,   3,   8,   9,  10},
+        {   0,   2,   4,  10,  11,  12},
+        {   0,   3,   5,  12,  13,  14},
+        {   0,   4,   6,  14,  15,  16},
+        {   0,   1,   5,  16,  17,  18},
+        {   1,   8,  18,  19,  20,  36},
+        {   1,   2,   7,   9,  20,  21},
+        {   2,   8,  10,  21,  22,  23},
+        {   2,   3,   9,  11,  23,  24},
+        {   3,  10,  12,  24,  25,  26},
+        {   3,   4,  11,  13,  26,  27},
+        {   4,  12,  14,  27,  28,  29},
+        {   4,   5,  13,  15,  29,  30},
+        {   5,  14,  16,  30,  31,  32},
+        {   5,   6,  15,  17,  32,  33},
+        {   6,  16,  18,  33,  34,  35},
+        {   1,   6,   7,  17,  35,  36},
+        {   7,  20,  36,  37,  38,  60},
+        {   7,   8,  19,  21,  38,  39}, // 20
+        {   8,   9,  20,  22,  39,  40},
+        {   9,  21,  23,  40,  41,  42},
+        {   9,  10,  22,  24,  42,  43},
+        {  10,  11,  23,  25,  43,  44},
+        {  11,  24,  26,  44,  45,  46},
+        {  11,  12,  25,  27,  46,  47},
+        {  12,  13,  26,  28,  47,  48},
+        {  13,  27,  29,  48,  49,  50},
+        {  13,  14,  28,  30,  50,  51},
+        {  14,  15,  29,  31,  51,  52},
+        {  15,  30,  32,  52,  53,  54},
+        {  15,  16,  31,  33,  54,  55},
+        {  16,  17,  32,  34,  55,  56},
+        {  17,  33,  35,  56,  57,  58},
+        {  17,  18,  34,  36,  58,  59},
+        {   7,  18,  19,  35,  59,  60},
+        {  19,  38,  60,  61,  62,  90},
+        {  19,  20,  37,  39,  62,  63},
+        {  20,  21,  38,  40,  63,  64},
+        {  21,  22,  39,  41,  64,  65}, // 40
+        {  22,  40,  42,  65,  66,  67},
+        {  22,  23,  41,  43,  67,  68},
+        {  23,  24,  42,  44,  68,  69},
+        {  24,  25,  43,  45,  69,  70},
+        {  25,  44,  46,  70,  71,  72},
+        {  25,  26,  45,  47,  72,  73},
+        {  26,  27,  46,  48,  73,  74},
+        {  27,  28,  47,  49,  74,  75},
+        {  28,  48,  50,  75,  76,  77},
+        {  28,  29,  49,  51,  77,  78},
+        {  29,  30,  50,  52,  78,  79},
+        {  30,  31,  51,  53,  79,  80},
+        {  31,  52,  54,  80,  81,  82},
+        {  31,  32,  53,  55,  82,  83},
+        {  32,  33,  54,  56,  83,  84},
+        {  33,  34,  55,  57,  84,  85},
+        {  34,  56,  58,  85,  86,  87},
+        {  34,  35,  57,  59,  87,  88},
+        {  35,  36,  58,  60,  88,  89},
+        {  19,  36,  37,  59,  89,  90}, // 60
+        {  37,  62,  90,  91,  92, 126},
+        {  37,  38,  61,  63,  92,  93},
+        {  38,  39,  62,  64,  93,  94},
+        {  39,  40,  63,  65,  94,  95},
+        {  40,  41,  64,  66,  95,  96},
+        {  41,  65,  67,  96,  97,  98},
+        {  41,  42,  66,  68,  98,  99},
+        {  42,  43,  67,  69,  99, 100},
+        {  43,  44,  68,  70, 100, 101},
+        {  44,  45,  69,  71, 101, 102},
+        {  45,  70,  72, 102, 103, 104},
+        {  45,  46,  71,  73, 104, 105},
+        {  46,  47,  72,  74, 105, 106},
+        {  47,  48,  73,  75, 106, 107},
+        {  48,  49,  74,  76, 107, 108},
+        {  49,  75,  77, 108, 109, 110},
+        {  49,  50,  76,  78, 110, 111},
+        {  50,  51,  77,  79, 111, 112},
+        {  51,  52,  78,  80, 112, 113},
+        {  52,  53,  79,  81, 113, 114}, // 80
+        {  53,  80,  82, 114, 115, 116},
+        {  53,  54,  81,  83, 116, 117},
+        {  54,  55,  82,  84, 117, 118},
+        {  55,  56,  83,  85, 118, 119},
+        {  56,  57,  84,  86, 119, 120},
+        {  57,  85,  87, 120, 121, 122},
+        {  57,  58,  86,  88, 122, 123},
+        {  58,  59,  87,  89, 123, 124},
+        {  59,  60,  88,  90, 124, 125},
+        {  37,  60,  61,  89, 125, 126},
+        {  61,  92, 126, 127, 128, 168},
+        {  61,  62,  91,  93, 128, 129},
+        {  62,  63,  92,  94, 129, 130},
+        {  63,  64,  93,  95, 130, 131},
+        {  64,  65,  94,  96, 131, 132},
+        {  65,  66,  95,  97, 132, 133},
+        {  66,  96,  98, 133, 134, 135},
+        {  66,  67,  97,  99, 135, 136},
+        {  67,  68,  98, 100, 136, 137},
+        {  68,  69,  99, 101, 137, 138}, // 100
+        {  69,  70, 100, 102, 138, 139},
+        {  70,  71, 101, 103, 139, 140},
+        {  71, 102, 104, 140, 141, 142},
+        {  71,  72, 103, 105, 142, 143},
+        {  72,  73, 104, 106, 143, 144},
+        {  73,  74, 105, 107, 144, 145},
+        {  74,  75, 106, 108, 145, 146},
+        {  75,  76, 107, 109, 146, 147},
+        {  76, 108, 110, 147, 148, 149},
+        {  76,  77, 109, 111, 149, 150},
+        {  77,  78, 110, 112, 150, 151},
+        {  78,  79, 111, 113, 151, 152},
+        {  79,  80, 112, 114, 152, 153},
+        {  80,  81, 113, 115, 153, 154},
+        {  81, 114, 116, 154, 155, 156},
+        {  81,  82, 115, 117, 156, 157},
+        {  82,  83, 116, 118, 157, 158},
+        {  83,  84, 117, 119, 158, 159},
+        {  84,  85, 118, 120, 159, 160},
+        {  85,  86, 119, 121, 160, 161}, // 120
+        {  86, 120, 122, 161, 162, 163},
+        {  86,  87, 121, 123, 163, 164},
+        {  87,  88, 122, 124, 164, 165},
+        {  88,  89, 123, 125, 165, 166},
+        {  89,  90, 124, 126, 166, 167},
+        {  61,  90,  91, 125, 167, 168},
+        {  91, 128, 168, 169, 170, 216},
+        {  91,  92, 127, 129, 170, 171},
+        {  92,  93, 128, 130, 171, 172},
+        {  93,  94, 129, 131, 172, 173},
+        {  94,  95, 130, 132, 173, 174},
+        {  95,  96, 131, 133, 174, 175},
+        {  96,  97, 132, 134, 175, 176},
+        {  97, 133, 135, 176, 177, 178},
+        {  97,  98, 134, 136, 178, 179},
+        {  98,  99, 135, 137, 179, 180},
+        {  99, 100, 136, 138, 180, 181},
+        { 100, 101, 137, 139, 181, 182},
+        { 101, 102, 138, 140, 182, 183},
+        { 102, 103, 139, 141, 183, 184}, // 140
+        { 103, 140, 142, 184, 185, 186},
+        { 103, 104, 141, 143, 186, 187},
+        { 104, 105, 142, 144, 187, 188},
+        { 105, 106, 143, 145, 188, 189},
+        { 106, 107, 144, 146, 189, 190},
+        { 107, 108, 145, 147, 190, 191},
+        { 108, 109, 146, 148, 191, 192},
+        { 109, 147, 149, 192, 193, 194},
+        { 109, 110, 148, 150, 194, 195},
+        { 110, 111, 149, 151, 195, 196},
+        { 111, 112, 150, 152, 196, 197},
+        { 112, 113, 151, 153, 197, 198},
+        { 113, 114, 152, 154, 198, 199},
+        { 114, 115, 153, 155, 199, 200},
+        { 115, 154, 156, 200, 201, 202},
+        { 115, 116, 155, 157, 202, 203},
+        { 116, 117, 156, 158, 203, 204},
+        { 117, 118, 157, 159, 204, 205},
+        { 118, 119, 158, 160, 205, 206},
+        { 119, 120, 159, 161, 206, 207}, // 160
+        { 120, 121, 160, 162, 207, 208},
+        { 121, 161, 163, 208, 209, 210},
+        { 121, 122, 162, 164, 210, 211},
+        { 122, 123, 163, 165, 211, 212},
+        { 123, 124, 164, 166, 212, 213},
+        { 124, 125, 165, 167, 213, 214},
+        { 125, 126, 166, 168, 214, 215},
+        {  91, 126, 127, 167, 215, 216},
+        { 127, 170, 216, 217, 218, 270},
+        { 127, 128, 169, 171, 218, 219},
+        { 128, 129, 170, 172, 219, 220},
+        { 129, 130, 171, 173, 220, 221},
+        { 130, 131, 172, 174, 221, 222},
+        { 131, 132, 173, 175, 222, 223},
+        { 132, 133, 174, 176, 223, 224},
+        { 133, 134, 175, 177, 224, 225},
+        { 134, 176, 178, 225, 226, 227},
+        { 134, 135, 177, 179, 227, 228},
+        { 135, 136, 178, 180, 228, 229},
+        { 136, 137, 179, 181, 229, 230}, // 180
+        { 137, 138, 180, 182, 230, 231},
+        { 138, 139, 181, 183, 231, 232},
+        { 139, 140, 182, 184, 232, 233},
+        { 140, 141, 183, 185, 233, 234},
+        { 141, 184, 186, 234, 235, 236},
+        { 141, 142, 185, 187, 236, 237},
+        { 142, 143, 186, 188, 237, 238},
+        { 143, 144, 187, 189, 238, 239},
+        { 144, 145, 188, 190, 239, 240},
+        { 145, 146, 189, 191, 240, 241},
+        { 146, 147, 190, 192, 241, 242},
+        { 147, 148, 191, 193, 242, 243},
+        { 148, 192, 194, 243, 244, 245},
+        { 148, 149, 193, 195, 245, 246},
+        { 149, 150, 194, 196, 246, 247},
+        { 150, 151, 195, 197, 247, 248},
+        { 151, 152, 196, 198, 248, 249},
+        { 152, 153, 197, 199, 249, 250},
+        { 153, 154, 198, 200, 250, 251},
+        { 154, 155, 199, 201, 251, 252}, // 200
+        { 155, 200, 202, 252, 253, 254},
+        { 155, 156, 201, 203, 254, 255},
+        { 156, 157, 202, 204, 255, 256},
+        { 157, 158, 203, 205, 256, 257},
+        { 158, 159, 204, 206, 257, 258},
+        { 159, 160, 205, 207, 258, 259},
+        { 160, 161, 206, 208, 259, 260},
+        { 161, 162, 207, 209, 260, 261},
+        { 162, 208, 210, 261, 262, 263},
+        { 162, 163, 209, 211, 263, 264},
+        { 163, 164, 210, 212, 264, 265},
+        { 164, 165, 211, 213, 265, 266},
+        { 165, 166, 212, 214, 266, 267},
+        { 166, 167, 213, 215, 267, 268},
+        { 167, 168, 214, 216, 268, 269},
+        { 127, 168, 169, 215, 269, 270},
+        { 169, 218, 270, 271, 272, 330},
+        { 169, 170, 217, 219, 272, 273},
+        { 170, 171, 218, 220, 273, 274},
+        { 171, 172, 219, 221, 274, 275}, // 220
+        { 172, 173, 220, 222, 275, 276},
+        { 173, 174, 221, 223, 276, 277},
+        { 174, 175, 222, 224, 277, 278},
+        { 175, 176, 223, 225, 278, 279},
+        { 176, 177, 224, 226, 279, 280},
+        { 177, 225, 227, 280, 281, 282},
+        { 177, 178, 226, 228, 282, 283},
+        { 178, 179, 227, 229, 283, 284},
+        { 179, 180, 228, 230, 284, 285},
+        { 180, 181, 229, 231, 285, 286},
+        { 181, 182, 230, 232, 286, 287},
+        { 182, 183, 231, 233, 287, 288},
+        { 183, 184, 232, 234, 288, 289},
+        { 184, 185, 233, 235, 289, 290},
+        { 185, 234, 236, 290, 291, 292},
+        { 185, 186, 235, 237, 292, 293},
+        { 186, 187, 236, 238, 293, 294},
+        { 187, 188, 237, 239, 294, 295},
+        { 188, 189, 238, 240, 295, 296},
+        { 189, 190, 239, 241, 296, 297}, // 240
+        { 190, 191, 240, 242, 297, 298},
+        { 191, 192, 241, 243, 298, 299},
+        { 192, 193, 242, 244, 299, 300},
+        { 193, 243, 245, 300, 301, 302},
+        { 193, 194, 244, 246, 302, 303},
+        { 194, 195, 245, 247, 303, 304},
+        { 195, 196, 246, 248, 304, 305},
+        { 196, 197, 247, 249, 305, 306},
+        { 197, 198, 248, 250, 306, 307},
+        { 198, 199, 249, 251, 307, 308},
+        { 199, 200, 250, 252, 308, 309},
+        { 200, 201, 251, 253, 309, 310},
+        { 201, 252, 254, 310, 311, 312},
+        { 201, 202, 253, 255, 312, 313},
+        { 202, 203, 254, 256, 313, 314},
+        { 203, 204, 255, 257, 314, 315},
+        { 204, 205, 256, 258, 315, 316},
+        { 205, 206, 257, 259, 316, 317},
+        { 206, 207, 258, 260, 317, 318},
+        { 207, 208, 259, 261, 318, 319}, // 260
+        { 208, 209, 260, 262, 319, 320},
+        { 209, 261, 263, 320, 321, 322},
+        { 209, 210, 262, 264, 322, 323},
+        { 210, 211, 263, 265, 323, 324},
+        { 211, 212, 264, 266, 324, 325},
+        { 212, 213, 265, 267, 325, 326},
+        { 213, 214, 266, 268, 326, 327},
+        { 214, 215, 267, 269, 327, 328},
+        { 215, 216, 268, 270, 328, 329},
+        { 169, 216, 217, 269, 329, 330},
+        { 217, 272, 330, 331, 332, 396},
+        { 217, 218, 271, 273, 332, 333},
+        { 218, 219, 272, 274, 333, 334},
+        { 219, 220, 273, 275, 334, 335},
+        { 220, 221, 274, 276, 335, 336},
+        { 221, 222, 275, 277, 336, 337},
+        { 222, 223, 276, 278, 337, 338},
+        { 223, 224, 277, 279, 338, 339},
+        { 224, 225, 278, 280, 339, 340},
+        { 225, 226, 279, 281, 340, 341}, // 280
+        { 226, 280, 282, 341, 342, 343},
+        { 226, 227, 281, 283, 343, 344},
+        { 227, 228, 282, 284, 344, 345},
+        { 228, 229, 283, 285, 345, 346},
+        { 229, 230, 284, 286, 346, 347},
+        { 230, 231, 285, 287, 347, 348},
+        { 231, 232, 286, 288, 348, 349},
+        { 232, 233, 287, 289, 349, 350},
+        { 233, 234, 288, 290, 350, 351},
+        { 234, 235, 289, 291, 351, 352},
+        { 235, 290, 292, 352, 353, 354},
+        { 235, 236, 291, 293, 354, 355},
+        { 236, 237, 292, 294, 355, 356},
+        { 237, 238, 293, 295, 356, 357},
+        { 238, 239, 294, 296, 357, 358},
+        { 239, 240, 295, 297, 358, 359},
+        { 240, 241, 296, 298, 359, 360},
+        { 241, 242, 297, 299, 360, 361},
+        { 242, 243, 298, 300, 361, 362},
+        { 243, 244, 299, 301, 362, 363}, // 300
+        { 244, 300, 302, 363, 364, 365},
+        { 244, 245, 301, 303, 365, 366},
+        { 245, 246, 302, 304, 366, 367},
+        { 246, 247, 303, 305, 367, 368},
+        { 247, 248, 304, 306, 368, 369},
+        { 248, 249, 305, 307, 369, 370},
+        { 249, 250, 306, 308, 370, 371},
+        { 250, 251, 307, 309, 371, 372},
+        { 251, 252, 308, 310, 372, 373},
+        { 252, 253, 309, 311, 373, 374},
+        { 253, 310, 312, 374, 375, 376},
+        { 253, 254, 311, 313, 376, 377},
+        { 254, 255, 312, 314, 377, 378},
+        { 255, 256, 313, 315, 378, 379},
+        { 256, 257, 314, 316, 379, 380},
+        { 257, 258, 315, 317, 380, 381},
+        { 258, 259, 316, 318, 381, 382},
+        { 259, 260, 317, 319, 382, 383},
+        { 260, 261, 318, 320, 383, 384},
+        { 261, 262, 319, 321, 384, 385}, // 320
+        { 262, 320, 322, 385, 386, 387},
+        { 262, 263, 321, 323, 387, 388},
+        { 263, 264, 322, 324, 388, 389},
+        { 264, 265, 323, 325, 389, 390},
+        { 265, 266, 324, 326, 390, 391},
+        { 266, 267, 325, 327, 391, 392},
+        { 267, 268, 326, 328, 392, 393},
+        { 268, 269, 327, 329, 393, 394},
+        { 269, 270, 328, 330, 394, 395},
+        { 217, 270, 271, 329, 395, 396},
+        { 271, 332, 396, 397, 432,  -1},
+        { 271, 272, 331, 333, 397,  -1},
+        { 272, 273, 332, 334, 398,  -1},
+        { 273, 274, 333, 335, 398,  -1},
+        { 274, 275, 334, 336, 399,  -1},
+        { 275, 276, 335, 337, 399,  -1},
+        { 276, 277, 336, 338, 400,  -1},
+        { 277, 278, 337, 339, 400,  -1},
+        { 278, 279, 338, 340, 401,  -1},
+        { 279, 280, 339, 341, 401,  -1}, // 340
+        { 280, 281, 340, 342, 402,  -1},
+        { 281, 341, 343, 402, 403,  -1},
+        { 281, 282, 342, 344, 403,  -1},
+        { 282, 283, 343, 345, 404,  -1},
+        { 283, 284, 344, 346, 404,  -1},
+        { 284, 285, 345, 347, 405,  -1},
+        { 285, 286, 346, 348, 405,  -1},
+        { 286, 287, 347, 349, 406,  -1},
+        { 287, 288, 348, 350, 406,  -1},
+        { 288, 289, 349, 351, 407,  -1},
+        { 289, 290, 350, 352, 407,  -1},
+        { 290, 291, 351, 353, 408,  -1},
+        { 291, 352, 354, 408, 409,  -1},
+        { 291, 292, 353, 355, 409,  -1},
+        { 292, 293, 354, 356, 410,  -1},
+        { 293, 294, 355, 357, 410,  -1},
+        { 294, 295, 356, 358, 411,  -1},
+        { 295, 296, 357, 359, 411,  -1},
+        { 296, 297, 358, 360, 412,  -1},
+        { 297, 298, 359, 361, 412,  -1}, // 360
+        { 298, 299, 360, 362, 413,  -1},
+        { 299, 300, 361, 363, 413,  -1},
+        { 300, 301, 362, 364, 414,  -1},
+        { 301, 363, 365, 414, 415,  -1},
+        { 301, 302, 364, 366, 415,  -1},
+        { 302, 303, 365, 367, 416,  -1},
+        { 303, 304, 366, 368, 416,  -1},
+        { 304, 305, 367, 369, 417,  -1},
+        { 305, 306, 368, 370, 417,  -1},
+        { 306, 307, 369, 371, 418,  -1},
+        { 307, 308, 370, 372, 418,  -1},
+        { 308, 309, 371, 373, 419,  -1},
+        { 309, 310, 372, 374, 419,  -1},
+        { 310, 311, 373, 375, 420,  -1},
+        { 311, 374, 376, 420, 421,  -1},
+        { 311, 312, 375, 377, 421,  -1},
+        { 312, 313, 376, 378, 422,  -1},
+        { 313, 314, 377, 379, 422,  -1},
+        { 314, 315, 378, 380, 423,  -1},
+        { 315, 316, 379, 381, 423,  -1}, // 380
+        { 316, 317, 380, 382, 424,  -1},
+        { 317, 318, 381, 383, 424,  -1},
+        { 318, 319, 382, 384, 425,  -1},
+        { 319, 320, 383, 385, 425,  -1},
+        { 320, 321, 384, 386, 426,  -1},
+        { 321, 385, 387, 426, 427,  -1},
+        { 321, 322, 386, 388, 427,  -1},
+        { 322, 323, 387, 389, 428,  -1},
+        { 323, 324, 388, 390, 428,  -1},
+        { 324, 325, 389, 391, 429,  -1},
+        { 325, 326, 390, 392, 429,  -1},
+        { 326, 327, 391, 393, 430,  -1},
+        { 327, 328, 392, 394, 430,  -1},
+        { 328, 329, 393, 395, 431,  -1},
+        { 329, 330, 394, 396, 431,  -1},
+        { 271, 330, 331, 395, 432,  -1},
+        { 331, 332, 398, 432, 433, 434},
+        { 333, 334, 397, 399, 434, 435},
+        { 335, 336, 398, 400, 435, 436},
+        { 337, 338, 399, 401, 436, 437}, // 400
+        { 339, 340, 400, 402, 437, 438},
+        { 341, 342, 401, 403, 438, 439},
+        { 342, 343, 402, 404, 440, 441},
+        { 344, 345, 403, 405, 441, 442},
+        { 346, 347, 404, 406, 442, 443},
+        { 348, 349, 405, 407, 443, 444},
+        { 350, 351, 406, 408, 444, 445},
+        { 352, 353, 407, 409, 445, 446},
+        { 353, 354, 408, 410, 447, 448},
+        { 355, 356, 409, 411, 448, 449},
+        { 357, 358, 410, 412, 449, 450},
+        { 359, 360, 411, 413, 450, 451},
+        { 361, 362, 412, 414, 451, 452},
+        { 363, 364, 413, 415, 452, 453},
+        { 364, 365, 414, 416, 454, 455},
+        { 366, 367, 415, 417, 455, 456},
+        { 368, 369, 416, 418, 456, 457},
+        { 370, 371, 417, 419, 457, 458},
+        { 372, 373, 418, 420, 458, 459},
+        { 374, 375, 419, 421, 459, 460}, // 420
+        { 375, 376, 420, 422, 461, 462},
+        { 377, 378, 421, 423, 462, 463},
+        { 379, 380, 422, 424, 463, 464},
+        { 381, 382, 423, 425, 464, 465},
+        { 383, 384, 424, 426, 465, 466},
+        { 385, 386, 425, 427, 466, 467},
+        { 386, 387, 426, 428, 468, 469},
+        { 388, 389, 427, 429, 469, 470},
+        { 390, 391, 428, 430, 470, 471},
+        { 392, 393, 429, 431, 471, 472},
+        { 394, 395, 430, 432, 472, 473},
+        { 331, 396, 397, 431, 473, 474},
+        { 397, 434, 474, 475, 476,  -1},
+        { 397, 398, 433, 435, 476, 477},
+        { 398, 399, 434, 436, 477, 478},
+        { 399, 400, 435, 437, 478, 479},
+        { 400, 401, 436, 438, 479, 480},
+        { 401, 402, 437, 439, 480, 481},
+        { 402, 438, 440, 481, 482,  -1},
+        { 403, 439, 441, 483, 484,  -1}, // 440
+        { 403, 404, 440, 442, 484, 485},
+        { 404, 405, 441, 443, 485, 486},
+        { 405, 406, 442, 444, 486, 487},
+        { 406, 407, 443, 445, 487, 488},
+        { 407, 408, 444, 446, 488, 489},
+        { 408, 445, 447, 489, 490,  -1},
+        { 409, 446, 448, 491, 492,  -1},
+        { 409, 410, 447, 449, 492, 493},
+        { 410, 411, 448, 450, 493, 494},
+        { 411, 412, 449, 451, 494, 495},
+        { 412, 413, 450, 452, 495, 496},
+        { 413, 414, 451, 453, 496, 497},
+        { 414, 452, 454, 497, 498,  -1},
+        { 415, 453, 455, 499, 500,  -1},
+        { 415, 416, 454, 456, 500, 501},
+        { 416, 417, 455, 457, 501, 502},
+        { 417, 418, 456, 458, 502, 503},
+        { 418, 419, 457, 459, 503, 504},
+        { 419, 420, 458, 460, 504, 505},
+        { 420, 459, 461, 505, 506,  -1}, // 460
+        { 421, 460, 462, 507, 508,  -1},
+        { 421, 422, 461, 463, 508, 509},
+        { 422, 423, 462, 464, 509, 510},
+        { 423, 424, 463, 465, 510, 511},
+        { 424, 425, 464, 466, 511, 512},
+        { 425, 426, 465, 467, 512, 513},
+        { 426, 466, 468, 513, 514,  -1},
+        { 427, 467, 469, 515, 516,  -1},
+        { 427, 428, 468, 470, 516, 517},
+        { 428, 429, 469, 471, 517, 518},
+        { 429, 430, 470, 472, 518, 519},
+        { 430, 431, 471, 473, 519, 520},
+        { 431, 432, 472, 474, 520, 521},
+        { 432, 433, 473, 521, 522,  -1},
+        { 433, 476, 522, 523, 524,  -1},
+        { 433, 434, 475, 477, 524, 525},
+        { 434, 435, 476, 478, 525, 526},
+        { 435, 436, 477, 479, 526, 527},
+        { 436, 437, 478, 480, 527, 528},
+        { 437, 438, 479, 481, 528, 529}, // 480
+        { 438, 439, 480, 482, 529, 530},
+        { 439, 481, 483, 530, 531,  -1},
+        { 440, 482, 484, 532, 533,  -1},
+        { 440, 441, 483, 485, 533, 534},
+        { 441, 442, 484, 486, 534, 535},
+        { 442, 443, 485, 487, 535, 536},
+        { 443, 444, 486, 488, 536, 537},
+        { 444, 445, 487, 489, 537, 538},
+        { 445, 446, 488, 490, 538, 539},
+        { 446, 489, 491, 539, 540,  -1},
+        { 447, 490, 492, 541, 542,  -1},
+        { 447, 448, 491, 493, 542, 543},
+        { 448, 449, 492, 494, 543, 544},
+        { 449, 450, 493, 495, 544, 545},
+        { 450, 451, 494, 496, 545, 546},
+        { 451, 452, 495, 497, 546, 547},
+        { 452, 453, 496, 498, 547, 548},
+        { 453, 497, 499, 548, 549,  -1},
+        { 454, 498, 500, 550, 551,  -1},
+        { 454, 455, 499, 501, 551, 552}, // 500
+        { 455, 456, 500, 502, 552, 553},
+        { 456, 457, 501, 503, 553, 554},
+        { 457, 458, 502, 504, 554, 555},
+        { 458, 459, 503, 505, 555, 556},
+        { 459, 460, 504, 506, 556, 557},
+        { 460, 505, 507, 557, 558,  -1},
+        { 461, 506, 508, 559, 560,  -1},
+        { 461, 462, 507, 509, 560, 561},
+        { 462, 463, 508, 510, 561, 562},
+        { 463, 464, 509, 511, 562, 563},
+        { 464, 465, 510, 512, 563, 564},
+        { 465, 466, 511, 513, 564, 565},
+        { 466, 467, 512, 514, 565, 566},
+        { 467, 513, 515, 566, 567,  -1},
+        { 468, 514, 516, 568, 569,  -1},
+        { 468, 469, 515, 517, 569, 570},
+        { 469, 470, 516, 518, 570, 571},
+        { 470, 471, 517, 519, 571, 572},
+        { 471, 472, 518, 520, 572, 573},
+        { 472, 473, 519, 521, 573, 574}, // 520
+        { 473, 474, 520, 522, 574, 575},
+        { 474, 475, 521, 575, 576,  -1},
+        { 475, 524, 576,  -1,  -1,  -1},
+        { 475, 476, 523, 525,  -1,  -1},
+        { 476, 477, 524, 526,  -1,  -1},
+        { 477, 478, 525, 527,  -1,  -1},
+        { 478, 479, 526, 528,  -1,  -1},
+        { 479, 480, 527, 529,  -1,  -1},
+        { 480, 481, 528, 530,  -1,  -1},
+        { 481, 482, 529, 531,  -1,  -1},
+        { 482, 530, 532,  -1,  -1,  -1},
+        { 483, 531, 533,  -1,  -1,  -1},
+        { 483, 484, 532, 534,  -1,  -1},
+        { 484, 485, 533, 535,  -1,  -1},
+        { 485, 486, 534, 536,  -1,  -1},
+        { 486, 487, 535, 537,  -1,  -1},
+        { 487, 488, 536, 538,  -1,  -1},
+        { 488, 489, 537, 539,  -1,  -1},
+        { 489, 490, 538, 540,  -1,  -1},
+        { 490, 539, 541,  -1,  -1,  -1}, // 540
+        { 491, 540, 542,  -1,  -1,  -1},
+        { 491, 492, 541, 543,  -1,  -1},
+        { 492, 493, 542, 544,  -1,  -1},
+        { 493, 494, 543, 545,  -1,  -1},
+        { 494, 495, 544, 546,  -1,  -1},
+        { 495, 496, 545, 547,  -1,  -1},
+        { 496, 497, 546, 548,  -1,  -1},
+        { 497, 498, 547, 549,  -1,  -1},
+        { 498, 548, 550,  -1,  -1,  -1},
+        { 499, 549, 551,  -1,  -1,  -1},
+        { 499, 500, 550, 552,  -1,  -1},
+        { 500, 501, 551, 553,  -1,  -1},
+        { 501, 502, 552, 554,  -1,  -1},
+        { 502, 503, 553, 555,  -1,  -1},
+        { 503, 504, 554, 556,  -1,  -1},
+        { 504, 505, 555, 557,  -1,  -1},
+        { 505, 506, 556, 558,  -1,  -1},
+        { 506, 557, 559,  -1,  -1,  -1},
+        { 507, 558, 560,  -1,  -1,  -1},
+        { 507, 508, 559, 561,  -1,  -1}, // 560
+        { 508, 509, 560, 562,  -1,  -1},
+        { 509, 510, 561, 563,  -1,  -1},
+        { 510, 511, 562, 564,  -1,  -1},
+        { 511, 512, 563, 565,  -1,  -1},
+        { 512, 513, 564, 566,  -1,  -1},
+        { 513, 514, 565, 567,  -1,  -1},
+        { 514, 566, 568,  -1,  -1,  -1},
+        { 515, 567, 569,  -1,  -1,  -1},
+        { 515, 516, 568, 570,  -1,  -1},
+        { 516, 517, 569, 571,  -1,  -1}, // 570
+        { 517, 518, 570, 572,  -1,  -1},
+        { 518, 519, 571, 573,  -1,  -1},
+        { 519, 520, 572, 574,  -1,  -1},
+        { 520, 521, 573, 575,  -1,  -1},
+        { 521, 522, 574, 576,  -1,  -1},
+        { 522, 523, 575,  -1,  -1,  -1}  // 576
+    };
+
+    for (Int_t i=0; i<577; i++)
+        (*this)[i].SetNeighbors(nn[i][0], nn[i][1], nn[i][2],
+                                nn[i][3], nn[i][4], nn[i][5]);
+}
Index: /tags/Mars-V0.9/mgeom/MGeomCamMagic.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamMagic.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamMagic.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MGeomCamMagic
+#define MARS_MGeomCamMagic
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamMagic : public MGeomCam
+{
+private:
+    void CreateCam();
+    void CreateNN();
+
+public:
+    MGeomCamMagic(const char *name=NULL);
+
+    ClassDef(MGeomCamMagic, 1)		// Geometry class for the Magic camera
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgeom/MGeomCamMagic919.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamMagic919.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamMagic919.cc	(revision 9772)
@@ -0,0 +1,1363 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 07/2003 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagic919
+//
+// This class stores the geometry information of Magic camera,
+// which only has small pixels.
+// All information are copied from tables, see source code.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagic919.h"
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamMagic919);
+
+// --------------------------------------------------------------------------
+//
+//  This Magic camera has 919 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamMagic919::MGeomCamMagic919(const char *name)
+    : MGeomCam(919, 17, name, 
+	       "Geometry information of Magic Camera with only small pixels")
+{
+    CreateCam();
+    CreateNN();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information from a table into the pixel objects.
+//
+void MGeomCamMagic919::CreateCam()
+{
+    //
+    //   fill the geometry class with the coordinates of the MAGIC camera
+    //
+    //*fLog << inf << " Creating Magic geometry " << endl ;
+
+    //
+    //   here define the hardwire things of the magic telescope
+    //
+
+  const float xtemp[919] = {
+	0, 30, 15, -15, -30, -15, 15, 60, // 0
+	45, 30, 0, -30, -45, -60, -45, -30, // 8
+	0, 30, 45, 90, 75, 60, 45, 15, // 16
+	-15, -45, -60, -75, -90, -75, -60, -45, // 24
+	-15, 15, 45, 60, 75, 120, 105, 90, // 32
+	75, 60, 30, 0, -30, -60, -75, -90, // 40
+	-105, -120, -105, -90, -75, -60, -30, 0, // 48
+	30, 60, 75, 90, 105, 150, 135, 120, // 56
+	105, 90, 75, 45, 15, -15, -45, -75, // 64
+	-90, -105, -120, -135, -150, -135, -120, -105, // 72
+	-90, -75, -45, -15, 15, 45, 75, 90, // 80
+	105, 120, 135, 180, 165, 150, 135, 120, // 88
+	105, 90, 60, 30, 0, -30, -60, -90, // 96
+	-105, -120, -135, -150, -165, -180, -165, -150, // 104
+	-135, -120, -105, -90, -60, -30, 0, 30, // 112
+	60, 90, 105, 120, 135, 150, 165, 210, // 120
+	195, 180, 165, 150, 135, 120, 105, 75, // 128
+	45, 15, -15, -45, -75, -105, -120, -135, // 136
+	-150, -165, -180, -195, -210, -195, -180, -165, // 144
+	-150, -135, -120, -105, -75, -45, -15, 15, // 152
+	45, 75, 105, 120, 135, 150, 165, 180, // 160
+	195, 240, 225, 210, 195, 180, 165, 150, // 168
+	135, 120, 90, 60, 30, 0, -30, -60, // 176
+	-90, -120, -135, -150, -165, -180, -195, -210, // 184
+	-225, -240, -225, -210, -195, -180, -165, -150, // 192
+	-135, -120, -90, -60, -30, 0, 30, 60, // 200
+	90, 120, 135, 150, 165, 180, 195, 210, // 208
+	225, 270, 255, 240, 225, 210, 195, 180, // 216
+	165, 150, 135, 105, 75, 45, 15, -15, // 224
+	-45, -75, -105, -135, -150, -165, -180, -195, // 232
+	-210, -225, -240, -255, -270, -255, -240, -225, // 240
+	-210, -195, -180, -165, -150, -135, -105, -75, // 248
+	-45, -15, 15, 45, 75, 105, 135, 150, // 256
+	165, 180, 195, 210, 225, 240, 255, 300, // 264
+	285, 270, 255, 240, 225, 210, 195, 180, // 272
+	165, 150, 120, 90, 60, 30, 0, -30, // 280
+	-60, -90, -120, -150, -165, -180, -195, -210, // 288
+	-225, -240, -255, -270, -285, -300, -285, -270, // 296
+	-255, -240, -225, -210, -195, -180, -165, -150, // 304
+	-120, -90, -60, -30, 0, 30, 60, 90, // 312
+	120, 150, 165, 180, 195, 210, 225, 240, // 320
+	255, 270, 285, 330, 315, 300, 285, 270, // 328
+	255, 240, 225, 210, 195, 180, 165, 135, // 336
+	105, 75, 45, 15, -15, -45, -75, -105, // 344
+	-135, -165, -180, -195, -210, -225, -240, -255, // 352
+	-270, -285, -300, -315, -330, -315, -300, -285, // 360
+	-270, -255, -240, -225, -210, -195, -180, -165, // 368
+	-135, -105, -75, -45, -15, 15, 45, 75, // 376
+	105, 135, 165, 180, 195, 210, 225, 240, // 384
+	255, 270, 285, 300, 315, 360, 345, 330, // 392
+	315, 300, 285, 270, 255, 240, 225, 210, // 400
+	195, 180, 150, 120, 90, 60, 30, 0, // 408
+	-30, -60, -90, -120, -150, -180, -195, -210, // 416
+	-225, -240, -255, -270, -285, -300, -315, -330, // 424
+	-345, -360, -345, -330, -315, -300, -285, -270, // 432
+	-255, -240, -225, -210, -195, -180, -150, -120, // 440
+	-90, -60, -30, 0, 30, 60, 90, 120, // 448
+	150, 180, 195, 210, 225, 240, 255, 270, // 456
+	285, 300, 315, 330, 345, 390, 375, 360, // 464
+	345, 330, 315, 300, 285, 270, 255, 240, // 472
+	225, 210, 195, 165, 135, 105, 75, 45, // 480
+	15, -15, -45, -75, -105, -135, -165, -195, // 488
+	-210, -225, -240, -255, -270, -285, -300, -315, // 496
+	-330, -345, -360, -375, -390, -375, -360, -345, // 504
+	-330, -315, -300, -285, -270, -255, -240, -225, // 512
+	-210, -195, -165, -135, -105, -75, -45, -15, // 520
+	15, 45, 75, 105, 135, 165, 195, 210, // 528
+	225, 240, 255, 270, 285, 300, 315, 330, // 536
+	345, 360, 375, 420, 405, 390, 375, 360, // 544
+	345, 330, 315, 300, 285, 270, 255, 240, // 552
+	225, 210, 180, 150, 120, 90, 60, 30, // 560
+	0, -30, -60, -90, -120, -150, -180, -210, // 568
+	-225, -240, -255, -270, -285, -300, -315, -330, // 576
+	-345, -360, -375, -390, -405, -420, -405, -390, // 584
+	-375, -360, -345, -330, -315, -300, -285, -270, // 592
+	-255, -240, -225, -210, -180, -150, -120, -90, // 600
+	-60, -30, 0, 30, 60, 90, 120, 150, // 608
+	180, 210, 225, 240, 255, 270, 285, 300, // 616
+	315, 330, 345, 360, 375, 390, 405, 450, // 624
+	435, 420, 405, 390, 375, 360, 345, 330, // 632
+	315, 300, 285, 270, 255, 240, 225, 195, // 640
+	165, 135, 105, 75, 45, 15, -15, -45, // 648
+	-75, -105, -135, -165, -195, -225, -240, -255, // 656
+	-270, -285, -300, -315, -330, -345, -360, -375, // 664
+	-390, -405, -420, -435, -450, -435, -420, -405, // 672
+	-390, -375, -360, -345, -330, -315, -300, -285, // 680
+	-270, -255, -240, -225, -195, -165, -135, -105, // 688
+	-75, -45, -15, 15, 45, 75, 105, 135, // 696
+	165, 195, 225, 240, 255, 270, 285, 300, // 704
+	315, 330, 345, 360, 375, 390, 405, 420, // 712
+	435, 480, 465, 450, 435, 420, 405, 390, // 720
+	375, 360, 345, 330, 315, 300, 285, 270, // 728
+	255, 240, 210, 180, 150, 120, 90, 60, // 736
+	30, 0, -30, -60, -90, -120, -150, -180, // 744
+	-210, -240, -255, -270, -285, -300, -315, -330, // 752
+	-345, -360, -375, -390, -405, -420, -435, -450, // 760
+	-465, -480, -465, -450, -435, -420, -405, -390, // 768
+	-375, -360, -345, -330, -315, -300, -285, -270, // 776
+	-255, -240, -210, -180, -150, -120, -90, -60, // 784
+	-30, 0, 30, 60, 90, 120, 150, 180, // 792
+	210, 240, 255, 270, 285, 300, 315, 330, // 800
+	345, 360, 375, 390, 405, 420, 435, 450, // 808
+	465, 510, 495, 480, 465, 450, 435, 420, // 816
+	405, 390, 375, 360, 345, 330, 315, 300, // 824
+	285, 270, 255, 225, 195, 165, 135, 105, // 832
+	75, 45, 15, -15, -45, -75, -105, -135, // 840
+	-165, -195, -225, -255, -270, -285, -300, -315, // 848
+	-330, -345, -360, -375, -390, -405, -420, -435, // 856
+	-450, -465, -480, -495, -510, -495, -480, -465, // 864
+	-450, -435, -420, -405, -390, -375, -360, -345, // 872
+	-330, -315, -300, -285, -270, -255, -225, -195, // 880
+	-165, -135, -105, -75, -45, -15, 15, 45, // 888
+	75, 105, 135, 165, 195, 225, 255, 270, // 896
+	285, 300, 315, 330, 345, 360, 375, 390, // 904
+	405, 420, 435, 450, 465, 480, 495//919
+  };
+
+  const float ytemp[919] = {
+	0, 0, 25.9808, 25.9808, -0, -25.9808, -25.9808, 0, // 0
+	25.9808, 51.9615, 51.9615, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 8
+	-51.9615, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 77.9423, // 16
+	77.9423, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 24
+	-77.9423, -77.9423, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 32
+	77.9423, 103.923, 103.923, 103.923, 103.923, 103.923, 77.9423, 51.9615, // 40
+	25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -103.923, -103.923, // 48
+	-103.923, -103.923, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 56
+	77.9423, 103.923, 129.904, 129.904, 129.904, 129.904, 129.904, 129.904, // 64
+	103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 72
+	-103.923, -129.904, -129.904, -129.904, -129.904, -129.904, -129.904, -103.923, // 80
+	-77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, // 88
+	129.904, 155.885, 155.885, 155.885, 155.885, 155.885, 155.885, 155.885, // 96
+	129.904, 103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 104
+	-77.9423, -103.923, -129.904, -155.885, -155.885, -155.885, -155.885, -155.885, // 112
+	-155.885, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, // 120
+	25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, 181.865, 181.865, // 128
+	181.865, 181.865, 181.865, 181.865, 181.865, 181.865, 155.885, 129.904, // 136
+	103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 144
+	-103.923, -129.904, -155.885, -181.865, -181.865, -181.865, -181.865, -181.865, // 152
+	-181.865, -181.865, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 160
+	-25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, // 168
+	181.865, 207.846, 207.846, 207.846, 207.846, 207.846, 207.846, 207.846, // 176
+	207.846, 207.846, 181.865, 155.885, 129.904, 103.923, 77.9423, 51.9615, // 184
+	25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -129.904, -155.885, // 192
+	-181.865, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, // 200
+	-207.846, -207.846, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 208
+	-25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, // 216
+	181.865, 207.846, 233.827, 233.827, 233.827, 233.827, 233.827, 233.827, // 224
+	233.827, 233.827, 233.827, 233.827, 207.846, 181.865, 155.885, 129.904, // 232
+	103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 240
+	-103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -233.827, -233.827, // 248
+	-233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -207.846, // 256
+	-181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, // 264
+	25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, // 272
+	233.827, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, // 280
+	259.808, 259.808, 259.808, 259.808, 233.827, 207.846, 181.865, 155.885, // 288
+	129.904, 103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 296
+	-77.9423, -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, // 304
+	-259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, // 312
+	-259.808, -259.808, -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, // 320
+	-77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, // 328
+	129.904, 155.885, 181.865, 207.846, 233.827, 259.808, 285.788, 285.788, // 336
+	285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, // 344
+	285.788, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 352
+	103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 360
+	-103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 368
+	-285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, // 376
+	-285.788, -285.788, -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, // 384
+	-129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 392
+	77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, 233.827, 259.808, // 400
+	285.788, 311.769, 311.769, 311.769, 311.769, 311.769, 311.769, 311.769, // 408
+	311.769, 311.769, 311.769, 311.769, 311.769, 311.769, 285.788, 259.808, // 416
+	233.827, 207.846, 181.865, 155.885, 129.904, 103.923, 77.9423, 51.9615, // 424
+	25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -129.904, -155.885, // 432
+	-181.865, -207.846, -233.827, -259.808, -285.788, -311.769, -311.769, -311.769, // 440
+	-311.769, -311.769, -311.769, -311.769, -311.769, -311.769, -311.769, -311.769, // 448
+	-311.769, -311.769, -285.788, -259.808, -233.827, -207.846, -181.865, -155.885, // 456
+	-129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, // 464
+	77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, 233.827, 259.808, // 472
+	285.788, 311.769, 337.75, 337.75, 337.75, 337.75, 337.75, 337.75, // 480
+	337.75, 337.75, 337.75, 337.75, 337.75, 337.75, 337.75, 337.75, // 488
+	311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 496
+	103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 504
+	-103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 512
+	-311.769, -337.75, -337.75, -337.75, -337.75, -337.75, -337.75, -337.75, // 520
+	-337.75, -337.75, -337.75, -337.75, -337.75, -337.75, -337.75, -311.769, // 528
+	-285.788, -259.808, -233.827, -207.846, -181.865, -155.885, -129.904, -103.923, // 536
+	-77.9423, -51.9615, -25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, // 544
+	129.904, 155.885, 181.865, 207.846, 233.827, 259.808, 285.788, 311.769, // 552
+	337.75, 363.731, 363.731, 363.731, 363.731, 363.731, 363.731, 363.731, // 560
+	363.731, 363.731, 363.731, 363.731, 363.731, 363.731, 363.731, 363.731, // 568
+	337.75, 311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, // 576
+	129.904, 103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, // 584
+	-77.9423, -103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, // 592
+	-285.788, -311.769, -337.75, -363.731, -363.731, -363.731, -363.731, -363.731, // 600
+	-363.731, -363.731, -363.731, -363.731, -363.731, -363.731, -363.731, -363.731, // 608
+	-363.731, -363.731, -337.75, -311.769, -285.788, -259.808, -233.827, -207.846, // 616
+	-181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808, 0, // 624
+	25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, 181.865, 207.846, // 632
+	233.827, 259.808, 285.788, 311.769, 337.75, 363.731, 389.711, 389.711, // 640
+	389.711, 389.711, 389.711, 389.711, 389.711, 389.711, 389.711, 389.711, // 648
+	389.711, 389.711, 389.711, 389.711, 389.711, 389.711, 363.731, 337.75, // 656
+	311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 664
+	103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 672
+	-103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 680
+	-311.769, -337.75, -363.731, -389.711, -389.711, -389.711, -389.711, -389.711, // 688
+	-389.711, -389.711, -389.711, -389.711, -389.711, -389.711, -389.711, -389.711, // 696
+	-389.711, -389.711, -389.711, -363.731, -337.75, -311.769, -285.788, -259.808, // 704
+	-233.827, -207.846, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 712
+	-25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, // 720
+	181.865, 207.846, 233.827, 259.808, 285.788, 311.769, 337.75, 363.731, // 728
+	389.711, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, // 736
+	415.692, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, 415.692, // 744
+	415.692, 415.692, 389.711, 363.731, 337.75, 311.769, 285.788, 259.808, // 752
+	233.827, 207.846, 181.865, 155.885, 129.904, 103.923, 77.9423, 51.9615, // 760
+	25.9808, -0, -25.9808, -51.9615, -77.9423, -103.923, -129.904, -155.885, // 768
+	-181.865, -207.846, -233.827, -259.808, -285.788, -311.769, -337.75, -363.731, // 776
+	-389.711, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, // 784
+	-415.692, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, -415.692, // 792
+	-415.692, -415.692, -389.711, -363.731, -337.75, -311.769, -285.788, -259.808, // 800
+	-233.827, -207.846, -181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, // 808
+	-25.9808, 0, 25.9808, 51.9615, 77.9423, 103.923, 129.904, 155.885, // 816
+	181.865, 207.846, 233.827, 259.808, 285.788, 311.769, 337.75, 363.731, // 824
+	389.711, 415.692, 441.673, 441.673, 441.673, 441.673, 441.673, 441.673, // 832
+	441.673, 441.673, 441.673, 441.673, 441.673, 441.673, 441.673, 441.673, // 840
+	441.673, 441.673, 441.673, 441.673, 415.692, 389.711, 363.731, 337.75, // 848
+	311.769, 285.788, 259.808, 233.827, 207.846, 181.865, 155.885, 129.904, // 856
+	103.923, 77.9423, 51.9615, 25.9808, -0, -25.9808, -51.9615, -77.9423, // 864
+	-103.923, -129.904, -155.885, -181.865, -207.846, -233.827, -259.808, -285.788, // 872
+	-311.769, -337.75, -363.731, -389.711, -415.692, -441.673, -441.673, -441.673, // 880
+	-441.673, -441.673, -441.673, -441.673, -441.673, -441.673, -441.673, -441.673, // 888
+	-441.673, -441.673, -441.673, -441.673, -441.673, -441.673, -441.673, -415.692, // 896
+	-389.711, -363.731, -337.75, -311.769, -285.788, -259.808, -233.827, -207.846, // 904
+	-181.865, -155.885, -129.904, -103.923, -77.9423, -51.9615, -25.9808 //919
+  };
+
+  const float rtemp[919] = {
+	30, 30, 30, 30, 30, 30, 30, 30, // 0
+	30, 30, 30, 30, 30, 30, 30, 30, // 8
+	30, 30, 30, 30, 30, 30, 30, 30, // 16
+	30, 30, 30, 30, 30, 30, 30, 30, // 24
+	30, 30, 30, 30, 30, 30, 30, 30, // 32
+	30, 30, 30, 30, 30, 30, 30, 30, // 40
+	30, 30, 30, 30, 30, 30, 30, 30, // 48
+	30, 30, 30, 30, 30, 30, 30, 30, // 56
+	30, 30, 30, 30, 30, 30, 30, 30, // 64
+	30, 30, 30, 30, 30, 30, 30, 30, // 72
+	30, 30, 30, 30, 30, 30, 30, 30, // 80
+	30, 30, 30, 30, 30, 30, 30, 30, // 88
+	30, 30, 30, 30, 30, 30, 30, 30, // 96
+	30, 30, 30, 30, 30, 30, 30, 30, // 104
+	30, 30, 30, 30, 30, 30, 30, 30, // 112
+	30, 30, 30, 30, 30, 30, 30, 30, // 120
+	30, 30, 30, 30, 30, 30, 30, 30, // 128
+	30, 30, 30, 30, 30, 30, 30, 30, // 136
+	30, 30, 30, 30, 30, 30, 30, 30, // 144
+	30, 30, 30, 30, 30, 30, 30, 30, // 152
+	30, 30, 30, 30, 30, 30, 30, 30, // 160
+	30, 30, 30, 30, 30, 30, 30, 30, // 168
+	30, 30, 30, 30, 30, 30, 30, 30, // 176
+	30, 30, 30, 30, 30, 30, 30, 30, // 184
+	30, 30, 30, 30, 30, 30, 30, 30, // 192
+	30, 30, 30, 30, 30, 30, 30, 30, // 200
+	30, 30, 30, 30, 30, 30, 30, 30, // 208
+	30, 30, 30, 30, 30, 30, 30, 30, // 216
+	30, 30, 30, 30, 30, 30, 30, 30, // 224
+	30, 30, 30, 30, 30, 30, 30, 30, // 232
+	30, 30, 30, 30, 30, 30, 30, 30, // 240
+	30, 30, 30, 30, 30, 30, 30, 30, // 248
+	30, 30, 30, 30, 30, 30, 30, 30, // 256
+	30, 30, 30, 30, 30, 30, 30, 30, // 264
+	30, 30, 30, 30, 30, 30, 30, 30, // 272
+	30, 30, 30, 30, 30, 30, 30, 30, // 280
+	30, 30, 30, 30, 30, 30, 30, 30, // 288
+	30, 30, 30, 30, 30, 30, 30, 30, // 296
+	30, 30, 30, 30, 30, 30, 30, 30, // 304
+	30, 30, 30, 30, 30, 30, 30, 30, // 312
+	30, 30, 30, 30, 30, 30, 30, 30, // 320
+	30, 30, 30, 30, 30, 30, 30, 30, // 328
+	30, 30, 30, 30, 30, 30, 30, 30, // 336
+	30, 30, 30, 30, 30, 30, 30, 30, // 344
+	30, 30, 30, 30, 30, 30, 30, 30, // 352
+	30, 30, 30, 30, 30, 30, 30, 30, // 360
+	30, 30, 30, 30, 30, 30, 30, 30, // 368
+	30, 30, 30, 30, 30, 30, 30, 30, // 376
+	30, 30, 30, 30, 30, 30, 30, 30, // 384
+	30, 30, 30, 30, 30, 30, 30, 30, // 392
+	30, 30, 30, 30, 30, 30, 30, 30, // 400
+	30, 30, 30, 30, 30, 30, 30, 30, // 408
+	30, 30, 30, 30, 30, 30, 30, 30, // 416
+	30, 30, 30, 30, 30, 30, 30, 30, // 424
+	30, 30, 30, 30, 30, 30, 30, 30, // 432
+	30, 30, 30, 30, 30, 30, 30, 30, // 440
+	30, 30, 30, 30, 30, 30, 30, 30, // 448
+	30, 30, 30, 30, 30, 30, 30, 30, // 456
+	30, 30, 30, 30, 30, 30, 30, 30, // 464
+	30, 30, 30, 30, 30, 30, 30, 30, // 472
+	30, 30, 30, 30, 30, 30, 30, 30, // 480
+	30, 30, 30, 30, 30, 30, 30, 30, // 488
+	30, 30, 30, 30, 30, 30, 30, 30, // 496
+	30, 30, 30, 30, 30, 30, 30, 30, // 504
+	30, 30, 30, 30, 30, 30, 30, 30, // 512
+	30, 30, 30, 30, 30, 30, 30, 30, // 520
+	30, 30, 30, 30, 30, 30, 30, 30, // 528
+	30, 30, 30, 30, 30, 30, 30, 30, // 536
+	30, 30, 30, 30, 30, 30, 30, 30, // 544
+	30, 30, 30, 30, 30, 30, 30, 30, // 552
+	30, 30, 30, 30, 30, 30, 30, 30, // 560
+	30, 30, 30, 30, 30, 30, 30, 30, // 568
+	30, 30, 30, 30, 30, 30, 30, 30, // 576
+	30, 30, 30, 30, 30, 30, 30, 30, // 584
+	30, 30, 30, 30, 30, 30, 30, 30, // 592
+	30, 30, 30, 30, 30, 30, 30, 30, // 600
+	30, 30, 30, 30, 30, 30, 30, 30, // 608
+	30, 30, 30, 30, 30, 30, 30, 30, // 616
+	30, 30, 30, 30, 30, 30, 30, 30, // 624
+	30, 30, 30, 30, 30, 30, 30, 30, // 632
+	30, 30, 30, 30, 30, 30, 30, 30, // 640
+	30, 30, 30, 30, 30, 30, 30, 30, // 648
+	30, 30, 30, 30, 30, 30, 30, 30, // 656
+	30, 30, 30, 30, 30, 30, 30, 30, // 664
+	30, 30, 30, 30, 30, 30, 30, 30, // 672
+	30, 30, 30, 30, 30, 30, 30, 30, // 680
+	30, 30, 30, 30, 30, 30, 30, 30, // 688
+	30, 30, 30, 30, 30, 30, 30, 30, // 696
+	30, 30, 30, 30, 30, 30, 30, 30, // 704
+	30, 30, 30, 30, 30, 30, 30, 30, // 712
+	30, 30, 30, 30, 30, 30, 30, 30, // 720
+	30, 30, 30, 30, 30, 30, 30, 30, // 728
+	30, 30, 30, 30, 30, 30, 30, 30, // 736
+	30, 30, 30, 30, 30, 30, 30, 30, // 744
+	30, 30, 30, 30, 30, 30, 30, 30, // 752
+	30, 30, 30, 30, 30, 30, 30, 30, // 760
+	30, 30, 30, 30, 30, 30, 30, 30, // 768
+	30, 30, 30, 30, 30, 30, 30, 30, // 776
+	30, 30, 30, 30, 30, 30, 30, 30, // 784
+	30, 30, 30, 30, 30, 30, 30, 30, // 792
+	30, 30, 30, 30, 30, 30, 30, 30, // 800
+	30, 30, 30, 30, 30, 30, 30, 30, // 808
+	30, 30, 30, 30, 30, 30, 30, 30, // 816
+	30, 30, 30, 30, 30, 30, 30, 30, // 824
+	30, 30, 30, 30, 30, 30, 30, 30, // 832
+	30, 30, 30, 30, 30, 30, 30, 30, // 840
+	30, 30, 30, 30, 30, 30, 30, 30, // 848
+	30, 30, 30, 30, 30, 30, 30, 30, // 856
+	30, 30, 30, 30, 30, 30, 30, 30, // 864
+	30, 30, 30, 30, 30, 30, 30, 30, // 872
+	30, 30, 30, 30, 30, 30, 30, 30, // 880
+	30, 30, 30, 30, 30, 30, 30, 30, // 888
+	30, 30, 30, 30, 30, 30, 30, 30, // 896
+	30, 30, 30, 30, 30, 30, 30, 30, // 904
+	30, 30, 30, 30, 30, 30, 30//919
+};
+
+    //
+    //   fill the pixels list with this data
+    //
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+        (*this)[i].Set(xtemp[i], ytemp[i], rtemp[i]) ;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the next neighbor information from a table into the pixel
+//  objects.
+//
+void MGeomCamMagic919::CreateNN()
+{
+  const Short_t nn[919][6] = {       // Neighbours of  #
+	{  1,	2,	3,	4,	5,	6},// 0
+	{  0,	2,	6,	7,	8,	18},
+	{  0,	1,	3,	8,	9,	10},
+	{  0,	2,	4,	10,	11,	12},
+	{  0,	3,	5,	12,	13,	14},
+	{  0,	4,	6,	14,	15,	16},
+	{  0,	1,	5,	16,	17,	18},
+	{  1,	8,	18,	19,	20,	36},
+	{  1,	2,	7,	9,	20,	21},
+	{  2,	8,	10,	21,	22,	23},
+	{  2,	3,	9,	11,	23,	24},
+	{  3,	10,	12,	24,	25,	26},
+	{  3,	4,	11,	13,	26,	27},
+	{  4,	12,	14,	27,	28,	29},
+	{  4,	5,	13,	15,	29,	30},
+	{  5,	14,	16,	30,	31,	32},
+	{  5,	6,	15,	17,	32,	33},
+	{  6,	16,	18,	33,	34,	35},
+	{  1,	6,	7,	17,	35,	36},
+	{  7,	20,	36,	37,	38,	60},
+	{  7,	8,	19,	21,	38,	39},// 20
+	{  8,	9,	20,	22,	39,	40},
+	{  9,	21,	23,	40,	41,	42},
+	{  9,	10,	22,	24,	42,	43},
+	{  10,	11,	23,	25,	43,	44},
+	{  11,	24,	26,	44,	45,	46},
+	{  11,	12,	25,	27,	46,	47},
+	{  12,	13,	26,	28,	47,	48},
+	{  13,	27,	29,	48,	49,	50},
+	{  13,	14,	28,	30,	50,	51},
+	{  14,	15,	29,	31,	51,	52},
+	{  15,	30,	32,	52,	53,	54},
+	{  15,	16,	31,	33,	54,	55},
+	{  16,	17,	32,	34,	55,	56},
+	{  17,	33,	35,	56,	57,	58},
+	{  17,	18,	34,	36,	58,	59},
+	{  7,	18,	19,	35,	59,	60},
+	{  19,	38,	60,	61,	62,	90},
+	{  19,	20,	37,	39,	62,	63},
+	{  20,	21,	38,	40,	63,	64},
+	{  21,	22,	39,	41,	64,	65},// 40
+	{  22,	40,	42,	65,	66,	67},
+	{  22,	23,	41,	43,	67,	68},
+	{  23,	24,	42,	44,	68,	69},
+	{  24,	25,	43,	45,	69,	70},
+	{  25,	44,	46,	70,	71,	72},
+	{  25,	26,	45,	47,	72,	73},
+	{  26,	27,	46,	48,	73,	74},
+	{  27,	28,	47,	49,	74,	75},
+	{  28,	48,	50,	75,	76,	77},
+	{  28,	29,	49,	51,	77,	78},
+	{  29,	30,	50,	52,	78,	79},
+	{  30,	31,	51,	53,	79,	80},
+	{  31,	52,	54,	80,	81,	82},
+	{  31,	32,	53,	55,	82,	83},
+	{  32,	33,	54,	56,	83,	84},
+	{  33,	34,	55,	57,	84,	85},
+	{  34,	56,	58,	85,	86,	87},
+	{  34,	35,	57,	59,	87,	88},
+	{  35,	36,	58,	60,	88,	89},
+	{  19,	36,	37,	59,	89,	90},// 60
+	{  37,	62,	90,	91,	92,	126},
+	{  37,	38,	61,	63,	92,	93},
+	{  38,	39,	62,	64,	93,	94},
+	{  39,	40,	63,	65,	94,	95},
+	{  40,	41,	64,	66,	95,	96},
+	{  41,	65,	67,	96,	97,	98},
+	{  41,	42,	66,	68,	98,	99},
+	{  42,	43,	67,	69,	99,	100},
+	{  43,	44,	68,	70,	100,	101},
+	{  44,	45,	69,	71,	101,	102},
+	{  45,	70,	72,	102,	103,	104},
+	{  45,	46,	71,	73,	104,	105},
+	{  46,	47,	72,	74,	105,	106},
+	{  47,	48,	73,	75,	106,	107},
+	{  48,	49,	74,	76,	107,	108},
+	{  49,	75,	77,	108,	109,	110},
+	{  49,	50,	76,	78,	110,	111},
+	{  50,	51,	77,	79,	111,	112},
+	{  51,	52,	78,	80,	112,	113},
+	{  52,	53,	79,	81,	113,	114},// 80
+	{  53,	80,	82,	114,	115,	116},
+	{  53,	54,	81,	83,	116,	117},
+	{  54,	55,	82,	84,	117,	118},
+	{  55,	56,	83,	85,	118,	119},
+	{  56,	57,	84,	86,	119,	120},
+	{  57,	85,	87,	120,	121,	122},
+	{  57,	58,	86,	88,	122,	123},
+	{  58,	59,	87,	89,	123,	124},
+	{  59,	60,	88,	90,	124,	125},
+	{  37,	60,	61,	89,	125,	126},
+	{  61,	92,	126,	127,	128,	168},
+	{  61,	62,	91,	93,	128,	129},
+	{  62,	63,	92,	94,	129,	130},
+	{  63,	64,	93,	95,	130,	131},
+	{  64,	65,	94,	96,	131,	132},
+	{  65,	66,	95,	97,	132,	133},
+	{  66,	96,	98,	133,	134,	135},
+	{  66,	67,	97,	99,	135,	136},
+	{  67,	68,	98,	100,	136,	137},
+	{  68,	69,	99,	101,	137,	138},// 100
+	{  69,	70,	100,	102,	138,	139},
+	{  70,	71,	101,	103,	139,	140},
+	{  71,	102,	104,	140,	141,	142},
+	{  71,	72,	103,	105,	142,	143},
+	{  72,	73,	104,	106,	143,	144},
+	{  73,	74,	105,	107,	144,	145},
+	{  74,	75,	106,	108,	145,	146},
+	{  75,	76,	107,	109,	146,	147},
+	{  76,	108,	110,	147,	148,	149},
+	{  76,	77,	109,	111,	149,	150},
+	{  77,	78,	110,	112,	150,	151},
+	{  78,	79,	111,	113,	151,	152},
+	{  79,	80,	112,	114,	152,	153},
+	{  80,	81,	113,	115,	153,	154},
+	{  81,	114,	116,	154,	155,	156},
+	{  81,	82,	115,	117,	156,	157},
+	{  82,	83,	116,	118,	157,	158},
+	{  83,	84,	117,	119,	158,	159},
+	{  84,	85,	118,	120,	159,	160},
+	{  85,	86,	119,	121,	160,	161},// 120
+	{  86,	120,	122,	161,	162,	163},
+	{  86,	87,	121,	123,	163,	164},
+	{  87,	88,	122,	124,	164,	165},
+	{  88,	89,	123,	125,	165,	166},
+	{  89,	90,	124,	126,	166,	167},
+	{  61,	90,	91,	125,	167,	168},
+	{  91,	128,	168,	169,	170,	216},
+	{  91,	92,	127,	129,	170,	171},
+	{  92,	93,	128,	130,	171,	172},
+	{  93,	94,	129,	131,	172,	173},
+	{  94,	95,	130,	132,	173,	174},
+	{  95,	96,	131,	133,	174,	175},
+	{  96,	97,	132,	134,	175,	176},
+	{  97,	133,	135,	176,	177,	178},
+	{  97,	98,	134,	136,	178,	179},
+	{  98,	99,	135,	137,	179,	180},
+	{  99,	100,	136,	138,	180,	181},
+	{  100,	101,	137,	139,	181,	182},
+	{  101,	102,	138,	140,	182,	183},
+	{  102,	103,	139,	141,	183,	184},// 140
+	{  103,	140,	142,	184,	185,	186},
+	{  103,	104,	141,	143,	186,	187},
+	{  104,	105,	142,	144,	187,	188},
+	{  105,	106,	143,	145,	188,	189},
+	{  106,	107,	144,	146,	189,	190},
+	{  107,	108,	145,	147,	190,	191},
+	{  108,	109,	146,	148,	191,	192},
+	{  109,	147,	149,	192,	193,	194},
+	{  109,	110,	148,	150,	194,	195},
+	{  110,	111,	149,	151,	195,	196},
+	{  111,	112,	150,	152,	196,	197},
+	{  112,	113,	151,	153,	197,	198},
+	{  113,	114,	152,	154,	198,	199},
+	{  114,	115,	153,	155,	199,	200},
+	{  115,	154,	156,	200,	201,	202},
+	{  115,	116,	155,	157,	202,	203},
+	{  116,	117,	156,	158,	203,	204},
+	{  117,	118,	157,	159,	204,	205},
+	{  118,	119,	158,	160,	205,	206},
+	{  119,	120,	159,	161,	206,	207},// 160
+	{  120,	121,	160,	162,	207,	208},
+	{  121,	161,	163,	208,	209,	210},
+	{  121,	122,	162,	164,	210,	211},
+	{  122,	123,	163,	165,	211,	212},
+	{  123,	124,	164,	166,	212,	213},
+	{  124,	125,	165,	167,	213,	214},
+	{  125,	126,	166,	168,	214,	215},
+	{  91,	126,	127,	167,	215,	216},
+	{  127,	170,	216,	217,	218,	270},
+	{  127,	128,	169,	171,	218,	219},
+	{  128,	129,	170,	172,	219,	220},
+	{  129,	130,	171,	173,	220,	221},
+	{  130,	131,	172,	174,	221,	222},
+	{  131,	132,	173,	175,	222,	223},
+	{  132,	133,	174,	176,	223,	224},
+	{  133,	134,	175,	177,	224,	225},
+	{  134,	176,	178,	225,	226,	227},
+	{  134,	135,	177,	179,	227,	228},
+	{  135,	136,	178,	180,	228,	229},
+	{  136,	137,	179,	181,	229,	230},// 180
+	{  137,	138,	180,	182,	230,	231},
+	{  138,	139,	181,	183,	231,	232},
+	{  139,	140,	182,	184,	232,	233},
+	{  140,	141,	183,	185,	233,	234},
+	{  141,	184,	186,	234,	235,	236},
+	{  141,	142,	185,	187,	236,	237},
+	{  142,	143,	186,	188,	237,	238},
+	{  143,	144,	187,	189,	238,	239},
+	{  144,	145,	188,	190,	239,	240},
+	{  145,	146,	189,	191,	240,	241},
+	{  146,	147,	190,	192,	241,	242},
+	{  147,	148,	191,	193,	242,	243},
+	{  148,	192,	194,	243,	244,	245},
+	{  148,	149,	193,	195,	245,	246},
+	{  149,	150,	194,	196,	246,	247},
+	{  150,	151,	195,	197,	247,	248},
+	{  151,	152,	196,	198,	248,	249},
+	{  152,	153,	197,	199,	249,	250},
+	{  153,	154,	198,	200,	250,	251},
+	{  154,	155,	199,	201,	251,	252},// 200
+	{  155,	200,	202,	252,	253,	254},
+	{  155,	156,	201,	203,	254,	255},
+	{  156,	157,	202,	204,	255,	256},
+	{  157,	158,	203,	205,	256,	257},
+	{  158,	159,	204,	206,	257,	258},
+	{  159,	160,	205,	207,	258,	259},
+	{  160,	161,	206,	208,	259,	260},
+	{  161,	162,	207,	209,	260,	261},
+	{  162,	208,	210,	261,	262,	263},
+	{  162,	163,	209,	211,	263,	264},
+	{  163,	164,	210,	212,	264,	265},
+	{  164,	165,	211,	213,	265,	266},
+	{  165,	166,	212,	214,	266,	267},
+	{  166,	167,	213,	215,	267,	268},
+	{  167,	168,	214,	216,	268,	269},
+	{  127,	168,	169,	215,	269,	270},
+	{  169,	218,	270,	271,	272,	330},
+	{  169,	170,	217,	219,	272,	273},
+	{  170,	171,	218,	220,	273,	274},
+	{  171,	172,	219,	221,	274,	275},// 220
+	{  172,	173,	220,	222,	275,	276},
+	{  173,	174,	221,	223,	276,	277},
+	{  174,	175,	222,	224,	277,	278},
+	{  175,	176,	223,	225,	278,	279},
+	{  176,	177,	224,	226,	279,	280},
+	{  177,	225,	227,	280,	281,	282},
+	{  177,	178,	226,	228,	282,	283},
+	{  178,	179,	227,	229,	283,	284},
+	{  179,	180,	228,	230,	284,	285},
+	{  180,	181,	229,	231,	285,	286},
+	{  181,	182,	230,	232,	286,	287},
+	{  182,	183,	231,	233,	287,	288},
+	{  183,	184,	232,	234,	288,	289},
+	{  184,	185,	233,	235,	289,	290},
+	{  185,	234,	236,	290,	291,	292},
+	{  185,	186,	235,	237,	292,	293},
+	{  186,	187,	236,	238,	293,	294},
+	{  187,	188,	237,	239,	294,	295},
+	{  188,	189,	238,	240,	295,	296},
+	{  189,	190,	239,	241,	296,	297},// 240
+	{  190,	191,	240,	242,	297,	298},
+	{  191,	192,	241,	243,	298,	299},
+	{  192,	193,	242,	244,	299,	300},
+	{  193,	243,	245,	300,	301,	302},
+	{  193,	194,	244,	246,	302,	303},
+	{  194,	195,	245,	247,	303,	304},
+	{  195,	196,	246,	248,	304,	305},
+	{  196,	197,	247,	249,	305,	306},
+	{  197,	198,	248,	250,	306,	307},
+	{  198,	199,	249,	251,	307,	308},
+	{  199,	200,	250,	252,	308,	309},
+	{  200,	201,	251,	253,	309,	310},
+	{  201,	252,	254,	310,	311,	312},
+	{  201,	202,	253,	255,	312,	313},
+	{  202,	203,	254,	256,	313,	314},
+	{  203,	204,	255,	257,	314,	315},
+	{  204,	205,	256,	258,	315,	316},
+	{  205,	206,	257,	259,	316,	317},
+	{  206,	207,	258,	260,	317,	318},
+	{  207,	208,	259,	261,	318,	319},// 260
+	{  208,	209,	260,	262,	319,	320},
+	{  209,	261,	263,	320,	321,	322},
+	{  209,	210,	262,	264,	322,	323},
+	{  210,	211,	263,	265,	323,	324},
+	{  211,	212,	264,	266,	324,	325},
+	{  212,	213,	265,	267,	325,	326},
+	{  213,	214,	266,	268,	326,	327},
+	{  214,	215,	267,	269,	327,	328},
+	{  215,	216,	268,	270,	328,	329},
+	{  169,	216,	217,	269,	329,	330},
+	{  217,	272,	330,	331,	332,	396},
+	{  217,	218,	271,	273,	332,	333},
+	{  218,	219,	272,	274,	333,	334},
+	{  219,	220,	273,	275,	334,	335},
+	{  220,	221,	274,	276,	335,	336},
+	{  221,	222,	275,	277,	336,	337},
+	{  222,	223,	276,	278,	337,	338},
+	{  223,	224,	277,	279,	338,	339},
+	{  224,	225,	278,	280,	339,	340},
+	{  225,	226,	279,	281,	340,	341},// 280
+	{  226,	280,	282,	341,	342,	343},
+	{  226,	227,	281,	283,	343,	344},
+	{  227,	228,	282,	284,	344,	345},
+	{  228,	229,	283,	285,	345,	346},
+	{  229,	230,	284,	286,	346,	347},
+	{  230,	231,	285,	287,	347,	348},
+	{  231,	232,	286,	288,	348,	349},
+	{  232,	233,	287,	289,	349,	350},
+	{  233,	234,	288,	290,	350,	351},
+	{  234,	235,	289,	291,	351,	352},
+	{  235,	290,	292,	352,	353,	354},
+	{  235,	236,	291,	293,	354,	355},
+	{  236,	237,	292,	294,	355,	356},
+	{  237,	238,	293,	295,	356,	357},
+	{  238,	239,	294,	296,	357,	358},
+	{  239,	240,	295,	297,	358,	359},
+	{  240,	241,	296,	298,	359,	360},
+	{  241,	242,	297,	299,	360,	361},
+	{  242,	243,	298,	300,	361,	362},
+	{  243,	244,	299,	301,	362,	363},// 300
+	{  244,	300,	302,	363,	364,	365},
+	{  244,	245,	301,	303,	365,	366},
+	{  245,	246,	302,	304,	366,	367},
+	{  246,	247,	303,	305,	367,	368},
+	{  247,	248,	304,	306,	368,	369},
+	{  248,	249,	305,	307,	369,	370},
+	{  249,	250,	306,	308,	370,	371},
+	{  250,	251,	307,	309,	371,	372},
+	{  251,	252,	308,	310,	372,	373},
+	{  252,	253,	309,	311,	373,	374},
+	{  253,	310,	312,	374,	375,	376},
+	{  253,	254,	311,	313,	376,	377},
+	{  254,	255,	312,	314,	377,	378},
+	{  255,	256,	313,	315,	378,	379},
+	{  256,	257,	314,	316,	379,	380},
+	{  257,	258,	315,	317,	380,	381},
+	{  258,	259,	316,	318,	381,	382},
+	{  259,	260,	317,	319,	382,	383},
+	{  260,	261,	318,	320,	383,	384},
+	{  261,	262,	319,	321,	384,	385},// 320
+	{  262,	320,	322,	385,	386,	387},
+	{  262,	263,	321,	323,	387,	388},
+	{  263,	264,	322,	324,	388,	389},
+	{  264,	265,	323,	325,	389,	390},
+	{  265,	266,	324,	326,	390,	391},
+	{  266,	267,	325,	327,	391,	392},
+	{  267,	268,	326,	328,	392,	393},
+	{  268,	269,	327,	329,	393,	394},
+	{  269,	270,	328,	330,	394,	395},
+	{  217,	270,	271,	329,	395,	396},
+	{  271,	332,	396,	397,	398,	468},
+	{  271,	272,	331,	333,	398,	399},
+	{  272,	273,	332,	334,	399,	400},
+	{  273,	274,	333,	335,	400,	401},
+	{  274,	275,	334,	336,	401,	402},
+	{  275,	276,	335,	337,	402,	403},
+	{  276,	277,	336,	338,	403,	404},
+	{  277,	278,	337,	339,	404,	405},
+	{  278,	279,	338,	340,	405,	406},
+	{  279,	280,	339,	341,	406,	407},// 340
+	{  280,	281,	340,	342,	407,	408},
+	{  281,	341,	343,	408,	409,	410},
+	{  281,	282,	342,	344,	410,	411},
+	{  282,	283,	343,	345,	411,	412},
+	{  283,	284,	344,	346,	412,	413},
+	{  284,	285,	345,	347,	413,	414},
+	{  285,	286,	346,	348,	414,	415},
+	{  286,	287,	347,	349,	415,	416},
+	{  287,	288,	348,	350,	416,	417},
+	{  288,	289,	349,	351,	417,	418},
+	{  289,	290,	350,	352,	418,	419},
+	{  290,	291,	351,	353,	419,	420},
+	{  291,	352,	354,	420,	421,	422},
+	{  291,	292,	353,	355,	422,	423},
+	{  292,	293,	354,	356,	423,	424},
+	{  293,	294,	355,	357,	424,	425},
+	{  294,	295,	356,	358,	425,	426},
+	{  295,	296,	357,	359,	426,	427},
+	{  296,	297,	358,	360,	427,	428},
+	{  297,	298,	359,	361,	428,	429},// 360
+	{  298,	299,	360,	362,	429,	430},
+	{  299,	300,	361,	363,	430,	431},
+	{  300,	301,	362,	364,	431,	432},
+	{  301,	363,	365,	432,	433,	434},
+	{  301,	302,	364,	366,	434,	435},
+	{  302,	303,	365,	367,	435,	436},
+	{  303,	304,	366,	368,	436,	437},
+	{  304,	305,	367,	369,	437,	438},
+	{  305,	306,	368,	370,	438,	439},
+	{  306,	307,	369,	371,	439,	440},
+	{  307,	308,	370,	372,	440,	441},
+	{  308,	309,	371,	373,	441,	442},
+	{  309,	310,	372,	374,	442,	443},
+	{  310,	311,	373,	375,	443,	444},
+	{  311,	374,	376,	444,	445,	446},
+	{  311,	312,	375,	377,	446,	447},
+	{  312,	313,	376,	378,	447,	448},
+	{  313,	314,	377,	379,	448,	449},
+	{  314,	315,	378,	380,	449,	450},
+	{  315,	316,	379,	381,	450,	451},// 380
+	{  316,	317,	380,	382,	451,	452},
+	{  317,	318,	381,	383,	452,	453},
+	{  318,	319,	382,	384,	453,	454},
+	{  319,	320,	383,	385,	454,	455},
+	{  320,	321,	384,	386,	455,	456},
+	{  321,	385,	387,	456,	457,	458},
+	{  321,	322,	386,	388,	458,	459},
+	{  322,	323,	387,	389,	459,	460},
+	{  323,	324,	388,	390,	460,	461},
+	{  324,	325,	389,	391,	461,	462},
+	{  325,	326,	390,	392,	462,	463},
+	{  326,	327,	391,	393,	463,	464},
+	{  327,	328,	392,	394,	464,	465},
+	{  328,	329,	393,	395,	465,	466},
+	{  329,	330,	394,	396,	466,	467},
+	{  271,	330,	331,	395,	467,	468},
+	{  331,	398,	468,	469,	470,	546},
+	{  331,	332,	397,	399,	470,	471},
+	{  332,	333,	398,	400,	471,	472},
+	{  333,	334,	399,	401,	472,	473},// 400
+	{  334,	335,	400,	402,	473,	474},
+	{  335,	336,	401,	403,	474,	475},
+	{  336,	337,	402,	404,	475,	476},
+	{  337,	338,	403,	405,	476,	477},
+	{  338,	339,	404,	406,	477,	478},
+	{  339,	340,	405,	407,	478,	479},
+	{  340,	341,	406,	408,	479,	480},
+	{  341,	342,	407,	409,	480,	481},
+	{  342,	408,	410,	481,	482,	483},
+	{  342,	343,	409,	411,	483,	484},
+	{  343,	344,	410,	412,	484,	485},
+	{  344,	345,	411,	413,	485,	486},
+	{  345,	346,	412,	414,	486,	487},
+	{  346,	347,	413,	415,	487,	488},
+	{  347,	348,	414,	416,	488,	489},
+	{  348,	349,	415,	417,	489,	490},
+	{  349,	350,	416,	418,	490,	491},
+	{  350,	351,	417,	419,	491,	492},
+	{  351,	352,	418,	420,	492,	493},
+	{  352,	353,	419,	421,	493,	494},// 420
+	{  353,	420,	422,	494,	495,	496},
+	{  353,	354,	421,	423,	496,	497},
+	{  354,	355,	422,	424,	497,	498},
+	{  355,	356,	423,	425,	498,	499},
+	{  356,	357,	424,	426,	499,	500},
+	{  357,	358,	425,	427,	500,	501},
+	{  358,	359,	426,	428,	501,	502},
+	{  359,	360,	427,	429,	502,	503},
+	{  360,	361,	428,	430,	503,	504},
+	{  361,	362,	429,	431,	504,	505},
+	{  362,	363,	430,	432,	505,	506},
+	{  363,	364,	431,	433,	506,	507},
+	{  364,	432,	434,	507,	508,	509},
+	{  364,	365,	433,	435,	509,	510},
+	{  365,	366,	434,	436,	510,	511},
+	{  366,	367,	435,	437,	511,	512},
+	{  367,	368,	436,	438,	512,	513},
+	{  368,	369,	437,	439,	513,	514},
+	{  369,	370,	438,	440,	514,	515},
+	{  370,	371,	439,	441,	515,	516},// 440
+	{  371,	372,	440,	442,	516,	517},
+	{  372,	373,	441,	443,	517,	518},
+	{  373,	374,	442,	444,	518,	519},
+	{  374,	375,	443,	445,	519,	520},
+	{  375,	444,	446,	520,	521,	522},
+	{  375,	376,	445,	447,	522,	523},
+	{  376,	377,	446,	448,	523,	524},
+	{  377,	378,	447,	449,	524,	525},
+	{  378,	379,	448,	450,	525,	526},
+	{  379,	380,	449,	451,	526,	527},
+	{  380,	381,	450,	452,	527,	528},
+	{  381,	382,	451,	453,	528,	529},
+	{  382,	383,	452,	454,	529,	530},
+	{  383,	384,	453,	455,	530,	531},
+	{  384,	385,	454,	456,	531,	532},
+	{  385,	386,	455,	457,	532,	533},
+	{  386,	456,	458,	533,	534,	535},
+	{  386,	387,	457,	459,	535,	536},
+	{  387,	388,	458,	460,	536,	537},
+	{  388,	389,	459,	461,	537,	538},// 460
+	{  389,	390,	460,	462,	538,	539},
+	{  390,	391,	461,	463,	539,	540},
+	{  391,	392,	462,	464,	540,	541},
+	{  392,	393,	463,	465,	541,	542},
+	{  393,	394,	464,	466,	542,	543},
+	{  394,	395,	465,	467,	543,	544},
+	{  395,	396,	466,	468,	544,	545},
+	{  331,	396,	397,	467,	545,	546},
+	{  397,	470,	546,	547,	548,	630},
+	{  397,	398,	469,	471,	548,	549},
+	{  398,	399,	470,	472,	549,	550},
+	{  399,	400,	471,	473,	550,	551},
+	{  400,	401,	472,	474,	551,	552},
+	{  401,	402,	473,	475,	552,	553},
+	{  402,	403,	474,	476,	553,	554},
+	{  403,	404,	475,	477,	554,	555},
+	{  404,	405,	476,	478,	555,	556},
+	{  405,	406,	477,	479,	556,	557},
+	{  406,	407,	478,	480,	557,	558},
+	{  407,	408,	479,	481,	558,	559},// 480
+	{  408,	409,	480,	482,	559,	560},
+	{  409,	481,	483,	560,	561,	562},
+	{  409,	410,	482,	484,	562,	563},
+	{  410,	411,	483,	485,	563,	564},
+	{  411,	412,	484,	486,	564,	565},
+	{  412,	413,	485,	487,	565,	566},
+	{  413,	414,	486,	488,	566,	567},
+	{  414,	415,	487,	489,	567,	568},
+	{  415,	416,	488,	490,	568,	569},
+	{  416,	417,	489,	491,	569,	570},
+	{  417,	418,	490,	492,	570,	571},
+	{  418,	419,	491,	493,	571,	572},
+	{  419,	420,	492,	494,	572,	573},
+	{  420,	421,	493,	495,	573,	574},
+	{  421,	494,	496,	574,	575,	576},
+	{  421,	422,	495,	497,	576,	577},
+	{  422,	423,	496,	498,	577,	578},
+	{  423,	424,	497,	499,	578,	579},
+	{  424,	425,	498,	500,	579,	580},
+	{  425,	426,	499,	501,	580,	581},// 500
+	{  426,	427,	500,	502,	581,	582},
+	{  427,	428,	501,	503,	582,	583},
+	{  428,	429,	502,	504,	583,	584},
+	{  429,	430,	503,	505,	584,	585},
+	{  430,	431,	504,	506,	585,	586},
+	{  431,	432,	505,	507,	586,	587},
+	{  432,	433,	506,	508,	587,	588},
+	{  433,	507,	509,	588,	589,	590},
+	{  433,	434,	508,	510,	590,	591},
+	{  434,	435,	509,	511,	591,	592},
+	{  435,	436,	510,	512,	592,	593},
+	{  436,	437,	511,	513,	593,	594},
+	{  437,	438,	512,	514,	594,	595},
+	{  438,	439,	513,	515,	595,	596},
+	{  439,	440,	514,	516,	596,	597},
+	{  440,	441,	515,	517,	597,	598},
+	{  441,	442,	516,	518,	598,	599},
+	{  442,	443,	517,	519,	599,	600},
+	{  443,	444,	518,	520,	600,	601},
+	{  444,	445,	519,	521,	601,	602},// 520
+	{  445,	520,	522,	602,	603,	604},
+	{  445,	446,	521,	523,	604,	605},
+	{  446,	447,	522,	524,	605,	606},
+	{  447,	448,	523,	525,	606,	607},
+	{  448,	449,	524,	526,	607,	608},
+	{  449,	450,	525,	527,	608,	609},
+	{  450,	451,	526,	528,	609,	610},
+	{  451,	452,	527,	529,	610,	611},
+	{  452,	453,	528,	530,	611,	612},
+	{  453,	454,	529,	531,	612,	613},
+	{  454,	455,	530,	532,	613,	614},
+	{  455,	456,	531,	533,	614,	615},
+	{  456,	457,	532,	534,	615,	616},
+	{  457,	533,	535,	616,	617,	618},
+	{  457,	458,	534,	536,	618,	619},
+	{  458,	459,	535,	537,	619,	620},
+	{  459,	460,	536,	538,	620,	621},
+	{  460,	461,	537,	539,	621,	622},
+	{  461,	462,	538,	540,	622,	623},
+	{  462,	463,	539,	541,	623,	624},// 540
+	{  463,	464,	540,	542,	624,	625},
+	{  464,	465,	541,	543,	625,	626},
+	{  465,	466,	542,	544,	626,	627},
+	{  466,	467,	543,	545,	627,	628},
+	{  467,	468,	544,	546,	628,	629},
+	{  397,	468,	469,	545,	629,	630},
+	{  469,	548,	630,	631,	632,	720},
+	{  469,	470,	547,	549,	632,	633},
+	{  470,	471,	548,	550,	633,	634},
+	{  471,	472,	549,	551,	634,	635},
+	{  472,	473,	550,	552,	635,	636},
+	{  473,	474,	551,	553,	636,	637},
+	{  474,	475,	552,	554,	637,	638},
+	{  475,	476,	553,	555,	638,	639},
+	{  476,	477,	554,	556,	639,	640},
+	{  477,	478,	555,	557,	640,	641},
+	{  478,	479,	556,	558,	641,	642},
+	{  479,	480,	557,	559,	642,	643},
+	{  480,	481,	558,	560,	643,	644},
+	{  481,	482,	559,	561,	644,	645},// 560
+	{  482,	560,	562,	645,	646,	647},
+	{  482,	483,	561,	563,	647,	648},
+	{  483,	484,	562,	564,	648,	649},
+	{  484,	485,	563,	565,	649,	650},
+	{  485,	486,	564,	566,	650,	651},
+	{  486,	487,	565,	567,	651,	652},
+	{  487,	488,	566,	568,	652,	653},
+	{  488,	489,	567,	569,	653,	654},
+	{  489,	490,	568,	570,	654,	655},
+	{  490,	491,	569,	571,	655,	656},
+	{  491,	492,	570,	572,	656,	657},
+	{  492,	493,	571,	573,	657,	658},
+	{  493,	494,	572,	574,	658,	659},
+	{  494,	495,	573,	575,	659,	660},
+	{  495,	574,	576,	660,	661,	662},
+	{  495,	496,	575,	577,	662,	663},
+	{  496,	497,	576,	578,	663,	664},
+	{  497,	498,	577,	579,	664,	665},
+	{  498,	499,	578,	580,	665,	666},
+	{  499,	500,	579,	581,	666,	667},// 580
+	{  500,	501,	580,	582,	667,	668},
+	{  501,	502,	581,	583,	668,	669},
+	{  502,	503,	582,	584,	669,	670},
+	{  503,	504,	583,	585,	670,	671},
+	{  504,	505,	584,	586,	671,	672},
+	{  505,	506,	585,	587,	672,	673},
+	{  506,	507,	586,	588,	673,	674},
+	{  507,	508,	587,	589,	674,	675},
+	{  508,	588,	590,	675,	676,	677},
+	{  508,	509,	589,	591,	677,	678},
+	{  509,	510,	590,	592,	678,	679},
+	{  510,	511,	591,	593,	679,	680},
+	{  511,	512,	592,	594,	680,	681},
+	{  512,	513,	593,	595,	681,	682},
+	{  513,	514,	594,	596,	682,	683},
+	{  514,	515,	595,	597,	683,	684},
+	{  515,	516,	596,	598,	684,	685},
+	{  516,	517,	597,	599,	685,	686},
+	{  517,	518,	598,	600,	686,	687},
+	{  518,	519,	599,	601,	687,	688},// 600
+	{  519,	520,	600,	602,	688,	689},
+	{  520,	521,	601,	603,	689,	690},
+	{  521,	602,	604,	690,	691,	692},
+	{  521,	522,	603,	605,	692,	693},
+	{  522,	523,	604,	606,	693,	694},
+	{  523,	524,	605,	607,	694,	695},
+	{  524,	525,	606,	608,	695,	696},
+	{  525,	526,	607,	609,	696,	697},
+	{  526,	527,	608,	610,	697,	698},
+	{  527,	528,	609,	611,	698,	699},
+	{  528,	529,	610,	612,	699,	700},
+	{  529,	530,	611,	613,	700,	701},
+	{  530,	531,	612,	614,	701,	702},
+	{  531,	532,	613,	615,	702,	703},
+	{  532,	533,	614,	616,	703,	704},
+	{  533,	534,	615,	617,	704,	705},
+	{  534,	616,	618,	705,	706,	707},
+	{  534,	535,	617,	619,	707,	708},
+	{  535,	536,	618,	620,	708,	709},
+	{  536,	537,	619,	621,	709,	710},// 620
+	{  537,	538,	620,	622,	710,	711},
+	{  538,	539,	621,	623,	711,	712},
+	{  539,	540,	622,	624,	712,	713},
+	{  540,	541,	623,	625,	713,	714},
+	{  541,	542,	624,	626,	714,	715},
+	{  542,	543,	625,	627,	715,	716},
+	{  543,	544,	626,	628,	716,	717},
+	{  544,	545,	627,	629,	717,	718},
+	{  545,	546,	628,	630,	718,	719},
+	{  469,	546,	547,	629,	719,	720},
+	{  547,	632,	720,	721,	722,	816},
+	{  547,	548,	631,	633,	722,	723},
+	{  548,	549,	632,	634,	723,	724},
+	{  549,	550,	633,	635,	724,	725},
+	{  550,	551,	634,	636,	725,	726},
+	{  551,	552,	635,	637,	726,	727},
+	{  552,	553,	636,	638,	727,	728},
+	{  553,	554,	637,	639,	728,	729},
+	{  554,	555,	638,	640,	729,	730},
+	{  555,	556,	639,	641,	730,	731},// 640
+	{  556,	557,	640,	642,	731,	732},
+	{  557,	558,	641,	643,	732,	733},
+	{  558,	559,	642,	644,	733,	734},
+	{  559,	560,	643,	645,	734,	735},
+	{  560,	561,	644,	646,	735,	736},
+	{  561,	645,	647,	736,	737,	738},
+	{  561,	562,	646,	648,	738,	739},
+	{  562,	563,	647,	649,	739,	740},
+	{  563,	564,	648,	650,	740,	741},
+	{  564,	565,	649,	651,	741,	742},
+	{  565,	566,	650,	652,	742,	743},
+	{  566,	567,	651,	653,	743,	744},
+	{  567,	568,	652,	654,	744,	745},
+	{  568,	569,	653,	655,	745,	746},
+	{  569,	570,	654,	656,	746,	747},
+	{  570,	571,	655,	657,	747,	748},
+	{  571,	572,	656,	658,	748,	749},
+	{  572,	573,	657,	659,	749,	750},
+	{  573,	574,	658,	660,	750,	751},
+	{  574,	575,	659,	661,	751,	752},// 660
+	{  575,	660,	662,	752,	753,	754},
+	{  575,	576,	661,	663,	754,	755},
+	{  576,	577,	662,	664,	755,	756},
+	{  577,	578,	663,	665,	756,	757},
+	{  578,	579,	664,	666,	757,	758},
+	{  579,	580,	665,	667,	758,	759},
+	{  580,	581,	666,	668,	759,	760},
+	{  581,	582,	667,	669,	760,	761},
+	{  582,	583,	668,	670,	761,	762},
+	{  583,	584,	669,	671,	762,	763},
+	{  584,	585,	670,	672,	763,	764},
+	{  585,	586,	671,	673,	764,	765},
+	{  586,	587,	672,	674,	765,	766},
+	{  587,	588,	673,	675,	766,	767},
+	{  588,	589,	674,	676,	767,	768},
+	{  589,	675,	677,	768,	769,	770},
+	{  589,	590,	676,	678,	770,	771},
+	{  590,	591,	677,	679,	771,	772},
+	{  591,	592,	678,	680,	772,	773},
+	{  592,	593,	679,	681,	773,	774},// 680
+	{  593,	594,	680,	682,	774,	775},
+	{  594,	595,	681,	683,	775,	776},
+	{  595,	596,	682,	684,	776,	777},
+	{  596,	597,	683,	685,	777,	778},
+	{  597,	598,	684,	686,	778,	779},
+	{  598,	599,	685,	687,	779,	780},
+	{  599,	600,	686,	688,	780,	781},
+	{  600,	601,	687,	689,	781,	782},
+	{  601,	602,	688,	690,	782,	783},
+	{  602,	603,	689,	691,	783,	784},
+	{  603,	690,	692,	784,	785,	786},
+	{  603,	604,	691,	693,	786,	787},
+	{  604,	605,	692,	694,	787,	788},
+	{  605,	606,	693,	695,	788,	789},
+	{  606,	607,	694,	696,	789,	790},
+	{  607,	608,	695,	697,	790,	791},
+	{  608,	609,	696,	698,	791,	792},
+	{  609,	610,	697,	699,	792,	793},
+	{  610,	611,	698,	700,	793,	794},
+	{  611,	612,	699,	701,	794,	795},// 700
+	{  612,	613,	700,	702,	795,	796},
+	{  613,	614,	701,	703,	796,	797},
+	{  614,	615,	702,	704,	797,	798},
+	{  615,	616,	703,	705,	798,	799},
+	{  616,	617,	704,	706,	799,	800},
+	{  617,	705,	707,	800,	801,	802},
+	{  617,	618,	706,	708,	802,	803},
+	{  618,	619,	707,	709,	803,	804},
+	{  619,	620,	708,	710,	804,	805},
+	{  620,	621,	709,	711,	805,	806},
+	{  621,	622,	710,	712,	806,	807},
+	{  622,	623,	711,	713,	807,	808},
+	{  623,	624,	712,	714,	808,	809},
+	{  624,	625,	713,	715,	809,	810},
+	{  625,	626,	714,	716,	810,	811},
+	{  626,	627,	715,	717,	811,	812},
+	{  627,	628,	716,	718,	812,	813},
+	{  628,	629,	717,	719,	813,	814},
+	{  629,	630,	718,	720,	814,	815},
+	{  547,	630,	631,	719,	815,	816},// 720
+	{  631,	722,	816,	817,	818,	918},
+	{  631,	632,	721,	723,	818,	819},
+	{  632,	633,	722,	724,	819,	820},
+	{  633,	634,	723,	725,	820,	821},
+	{  634,	635,	724,	726,	821,	822},
+	{  635,	636,	725,	727,	822,	823},
+	{  636,	637,	726,	728,	823,	824},
+	{  637,	638,	727,	729,	824,	825},
+	{  638,	639,	728,	730,	825,	826},
+	{  639,	640,	729,	731,	826,	827},
+	{  640,	641,	730,	732,	827,	828},
+	{  641,	642,	731,	733,	828,	829},
+	{  642,	643,	732,	734,	829,	830},
+	{  643,	644,	733,	735,	830,	831},
+	{  644,	645,	734,	736,	831,	832},
+	{  645,	646,	735,	737,	832,	833},
+	{  646,	736,	738,	833,	834,	835},
+	{  646,	647,	737,	739,	835,	836},
+	{  647,	648,	738,	740,	836,	837},
+	{  648,	649,	739,	741,	837,	838},// 740
+	{  649,	650,	740,	742,	838,	839},
+	{  650,	651,	741,	743,	839,	840},
+	{  651,	652,	742,	744,	840,	841},
+	{  652,	653,	743,	745,	841,	842},
+	{  653,	654,	744,	746,	842,	843},
+	{  654,	655,	745,	747,	843,	844},
+	{  655,	656,	746,	748,	844,	845},
+	{  656,	657,	747,	749,	845,	846},
+	{  657,	658,	748,	750,	846,	847},
+	{  658,	659,	749,	751,	847,	848},
+	{  659,	660,	750,	752,	848,	849},
+	{  660,	661,	751,	753,	849,	850},
+	{  661,	752,	754,	850,	851,	852},
+	{  661,	662,	753,	755,	852,	853},
+	{  662,	663,	754,	756,	853,	854},
+	{  663,	664,	755,	757,	854,	855},
+	{  664,	665,	756,	758,	855,	856},
+	{  665,	666,	757,	759,	856,	857},
+	{  666,	667,	758,	760,	857,	858},
+	{  667,	668,	759,	761,	858,	859},// 760
+	{  668,	669,	760,	762,	859,	860},
+	{  669,	670,	761,	763,	860,	861},
+	{  670,	671,	762,	764,	861,	862},
+	{  671,	672,	763,	765,	862,	863},
+	{  672,	673,	764,	766,	863,	864},
+	{  673,	674,	765,	767,	864,	865},
+	{  674,	675,	766,	768,	865,	866},
+	{  675,	676,	767,	769,	866,	867},
+	{  676,	768,	770,	867,	868,	869},
+	{  676,	677,	769,	771,	869,	870},
+	{  677,	678,	770,	772,	870,	871},
+	{  678,	679,	771,	773,	871,	872},
+	{  679,	680,	772,	774,	872,	873},
+	{  680,	681,	773,	775,	873,	874},
+	{  681,	682,	774,	776,	874,	875},
+	{  682,	683,	775,	777,	875,	876},
+	{  683,	684,	776,	778,	876,	877},
+	{  684,	685,	777,	779,	877,	878},
+	{  685,	686,	778,	780,	878,	879},
+	{  686,	687,	779,	781,	879,	880},// 780
+	{  687,	688,	780,	782,	880,	881},
+	{  688,	689,	781,	783,	881,	882},
+	{  689,	690,	782,	784,	882,	883},
+	{  690,	691,	783,	785,	883,	884},
+	{  691,	784,	786,	884,	885,	886},
+	{  691,	692,	785,	787,	886,	887},
+	{  692,	693,	786,	788,	887,	888},
+	{  693,	694,	787,	789,	888,	889},
+	{  694,	695,	788,	790,	889,	890},
+	{  695,	696,	789,	791,	890,	891},
+	{  696,	697,	790,	792,	891,	892},
+	{  697,	698,	791,	793,	892,	893},
+	{  698,	699,	792,	794,	893,	894},
+	{  699,	700,	793,	795,	894,	895},
+	{  700,	701,	794,	796,	895,	896},
+	{  701,	702,	795,	797,	896,	897},
+	{  702,	703,	796,	798,	897,	898},
+	{  703,	704,	797,	799,	898,	899},
+	{  704,	705,	798,	800,	899,	900},
+	{  705,	706,	799,	801,	900,	901},// 800
+	{  706,	800,	802,	901,	902,	903},
+	{  706,	707,	801,	803,	903,	904},
+	{  707,	708,	802,	804,	904,	905},
+	{  708,	709,	803,	805,	905,	906},
+	{  709,	710,	804,	806,	906,	907},
+	{  710,	711,	805,	807,	907,	908},
+	{  711,	712,	806,	808,	908,	909},
+	{  712,	713,	807,	809,	909,	910},
+	{  713,	714,	808,	810,	910,	911},
+	{  714,	715,	809,	811,	911,	912},
+	{  715,	716,	810,	812,	912,	913},
+	{  716,	717,	811,	813,	913,	914},
+	{  717,	718,	812,	814,	914,	915},
+	{  718,	719,	813,	815,	915,	916},
+	{  719,	720,	814,	816,	916,	917},
+	{  631,	720,	721,	815,	917,	918},
+	{  721,	818,	918,	-1,	-1,	-1},
+	{  721,	722,	817,	819,	-1,	-1},
+	{  722,	723,	818,	820,	-1,	-1},
+	{  723,	724,	819,	821,	-1,	-1},// 820
+	{  724,	725,	820,	822,	-1,	-1},
+	{  725,	726,	821,	823,	-1,	-1},
+	{  726,	727,	822,	824,	-1,	-1},
+	{  727,	728,	823,	825,	-1,	-1},
+	{  728,	729,	824,	826,	-1,	-1},
+	{  729,	730,	825,	827,	-1,	-1},
+	{  730,	731,	826,	828,	-1,	-1},
+	{  731,	732,	827,	829,	-1,	-1},
+	{  732,	733,	828,	830,	-1,	-1},
+	{  733,	734,	829,	831,	-1,	-1},
+	{  734,	735,	830,	832,	-1,	-1},
+	{  735,	736,	831,	833,	-1,	-1},
+	{  736,	737,	832,	834,	-1,	-1},
+	{  737,	833,	835,	-1,	-1,	-1},
+	{  737,	738,	834,	836,	-1,	-1},
+	{  738,	739,	835,	837,	-1,	-1},
+	{  739,	740,	836,	838,	-1,	-1},
+	{  740,	741,	837,	839,	-1,	-1},
+	{  741,	742,	838,	840,	-1,	-1},
+	{  742,	743,	839,	841,	-1,	-1},// 840
+	{  743,	744,	840,	842,	-1,	-1},
+	{  744,	745,	841,	843,	-1,	-1},
+	{  745,	746,	842,	844,	-1,	-1},
+	{  746,	747,	843,	845,	-1,	-1},
+	{  747,	748,	844,	846,	-1,	-1},
+	{  748,	749,	845,	847,	-1,	-1},
+	{  749,	750,	846,	848,	-1,	-1},
+	{  750,	751,	847,	849,	-1,	-1},
+	{  751,	752,	848,	850,	-1,	-1},
+	{  752,	753,	849,	851,	-1,	-1},
+	{  753,	850,	852,	-1,	-1,	-1},
+	{  753,	754,	851,	853,	-1,	-1},
+	{  754,	755,	852,	854,	-1,	-1},
+	{  755,	756,	853,	855,	-1,	-1},
+	{  756,	757,	854,	856,	-1,	-1},
+	{  757,	758,	855,	857,	-1,	-1},
+	{  758,	759,	856,	858,	-1,	-1},
+	{  759,	760,	857,	859,	-1,	-1},
+	{  760,	761,	858,	860,	-1,	-1},
+	{  761,	762,	859,	861,	-1,	-1},// 860
+	{  762,	763,	860,	862,	-1,	-1},
+	{  763,	764,	861,	863,	-1,	-1},
+	{  764,	765,	862,	864,	-1,	-1},
+	{  765,	766,	863,	865,	-1,	-1},
+	{  766,	767,	864,	866,	-1,	-1},
+	{  767,	768,	865,	867,	-1,	-1},
+	{  768,	769,	866,	868,	-1,	-1},
+	{  769,	867,	869,	-1,	-1,	-1},
+	{  769,	770,	868,	870,	-1,	-1},
+	{  770,	771,	869,	871,	-1,	-1},
+	{  771,	772,	870,	872,	-1,	-1},
+	{  772,	773,	871,	873,	-1,	-1},
+	{  773,	774,	872,	874,	-1,	-1},
+	{  774,	775,	873,	875,	-1,	-1},
+	{  775,	776,	874,	876,	-1,	-1},
+	{  776,	777,	875,	877,	-1,	-1},
+	{  777,	778,	876,	878,	-1,	-1},
+	{  778,	779,	877,	879,	-1,	-1},
+	{  779,	780,	878,	880,	-1,	-1},
+	{  780,	781,	879,	881,	-1,	-1},// 880
+	{  781,	782,	880,	882,	-1,	-1},
+	{  782,	783,	881,	883,	-1,	-1},
+	{  783,	784,	882,	884,	-1,	-1},
+	{  784,	785,	883,	885,	-1,	-1},
+	{  785,	884,	886,	-1,	-1,	-1},
+	{  785,	786,	885,	887,	-1,	-1},
+	{  786,	787,	886,	888,	-1,	-1},
+	{  787,	788,	887,	889,	-1,	-1},
+	{  788,	789,	888,	890,	-1,	-1},
+	{  789,	790,	889,	891,	-1,	-1},
+	{  790,	791,	890,	892,	-1,	-1},
+	{  791,	792,	891,	893,	-1,	-1},
+	{  792,	793,	892,	894,	-1,	-1},
+	{  793,	794,	893,	895,	-1,	-1},
+	{  794,	795,	894,	896,	-1,	-1},
+	{  795,	796,	895,	897,	-1,	-1},
+	{  796,	797,	896,	898,	-1,	-1},
+	{  797,	798,	897,	899,	-1,	-1},
+	{  798,	799,	898,	900,	-1,	-1},
+	{  799,	800,	899,	901,	-1,	-1},// 900
+	{  800,	801,	900,	902,	-1,	-1},
+	{  801,	901,	903,	-1,	-1,	-1},
+	{  801,	802,	902,	904,	-1,	-1},
+	{  802,	803,	903,	905,	-1,	-1},
+	{  803,	804,	904,	906,	-1,	-1},
+	{  804,	805,	905,	907,	-1,	-1},
+	{  805,	806,	906,	908,	-1,	-1},
+	{  806,	807,	907,	909,	-1,	-1},
+	{  807,	808,	908,	910,	-1,	-1},
+	{  808,	809,	909,	911,	-1,	-1},
+	{  809,	810,	910,	912,	-1,	-1},
+	{  810,	811,	911,	913,	-1,	-1},
+	{  811,	812,	912,	914,	-1,	-1},
+	{  812,	813,	913,	915,	-1,	-1},
+	{  813,	814,	914,	916,	-1,	-1},
+	{  814,	815,	915,	917,	-1,	-1},
+	{  815,	816,	916,	918,	-1,	-1},
+	{  721,	816,	817,	917,	-1,	-1}
+  };
+
+  for (UInt_t i=0; i<GetNumPixels(); i++)
+      (*this)[i].SetNeighbors(nn[i][0], nn[i][1], nn[i][2],
+                              nn[i][3], nn[i][4], nn[i][5]);
+}
Index: /tags/Mars-V0.9/mgeom/MGeomCamMagic919.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamMagic919.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamMagic919.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MGeomCamMagic919
+#define MARS_MGeomCamMagic919
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamMagic919 : public MGeomCam
+{
+private:
+    void CreateCam();
+    void CreateNN();
+
+public:
+    MGeomCamMagic919(const char *name=NULL);
+
+    ClassDef(MGeomCamMagic919, 1)		// Geometry class for Magic camera with only small pixels
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgeom/MGeomCamMagicHG.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamMagicHG.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamMagicHG.cc	(revision 9772)
@@ -0,0 +1,3397 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagicHG
+//
+// This class stores the geometry information of the hipotethic Magic camera
+// with high granularity
+// All information are copied from tables, see source code.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagicHG.h"
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamMagicHG);
+
+// --------------------------------------------------------------------------
+//
+//  Magic high Granularity camera could have 2401 pixels. For geometry and Next Neighbor 
+//  info see CreateCam and CreateNN
+//
+MGeomCamMagicHG::MGeomCamMagicHG(const char *name)
+    : MGeomCam(2401, 17, name, "Geometry information of high Granularity Magic Camera")
+{
+    CreateCam();
+    CreateNN();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information from a table into the pixel objects.
+//
+void MGeomCamMagicHG::CreateCam()
+{
+
+    //
+    //   here define the hardwire things of the magic telescope
+    //
+  const float xtemp[2401] = {
+    0, 15, 7.5, -7.5, -15, -7.5, 7.5, 30, // 0
+    22.5, 15, 0, -15, -22.5, -30, -22.5, -15, // 8
+    0, 15, 22.5, 45, 37.5, 30, 22.5, 7.5, // 16
+    -7.5, -22.5, -30, -37.5, -45, -37.5, -30, -22.5, // 24
+    -7.5, 7.5, 22.5, 30, 37.5, 60, 52.5, 45, // 32
+    37.5, 30, 15, 0, -15, -30, -37.5, -45, // 40
+    -52.5, -60, -52.5, -45, -37.5, -30, -15, 0, // 48
+    15, 30, 37.5, 45, 52.5, 75, 67.5, 60, // 56
+    52.5, 45, 37.5, 22.5, 7.5, -7.5, -22.5, -37.5, // 64
+    -45, -52.5, -60, -67.5, -75, -67.5, -60, -52.5, // 72
+    -45, -37.5, -22.5, -7.5, 7.5, 22.5, 37.5, 45, // 80
+    52.5, 60, 67.5, 90, 82.5, 75, 67.5, 60, // 88
+    52.5, 45, 30, 15, 0, -15, -30, -45, // 96
+    -52.5, -60, -67.5, -75, -82.5, -90, -82.5, -75, // 104
+    -67.5, -60, -52.5, -45, -30, -15, 0, 15, // 112
+    30, 45, 52.5, 60, 67.5, 75, 82.5, 105, // 120
+    97.5, 90, 82.5, 75, 67.5, 60, 52.5, 37.5, // 128
+    22.5, 7.5, -7.5, -22.5, -37.5, -52.5, -60, -67.5, // 136
+    -75, -82.5, -90, -97.5, -105, -97.5, -90, -82.5, // 144
+    -75, -67.5, -60, -52.5, -37.5, -22.5, -7.5, 7.5, // 152
+    22.5, 37.5, 52.5, 60, 67.5, 75, 82.5, 90, // 160
+    97.5, 120, 112.5, 105, 97.5, 90, 82.5, 75, // 168
+    67.5, 60, 45, 30, 15, 0, -15, -30, // 176
+    -45, -60, -67.5, -75, -82.5, -90, -97.5, -105, // 184
+    -112.5, -120, -112.5, -105, -97.5, -90, -82.5, -75, // 192
+    -67.5, -60, -45, -30, -15, 0, 15, 30, // 200
+    45, 60, 67.5, 75, 82.5, 90, 97.5, 105, // 208
+    112.5, 135, 127.5, 120, 112.5, 105, 97.5, 90, // 216
+    82.5, 75, 67.5, 52.5, 37.5, 22.5, 7.5, -7.5, // 224
+    -22.5, -37.5, -52.5, -67.5, -75, -82.5, -90, -97.5, // 232
+    -105, -112.5, -120, -127.5, -135, -127.5, -120, -112.5, // 240
+    -105, -97.5, -90, -82.5, -75, -67.5, -52.5, -37.5, // 248
+    -22.5, -7.5, 7.5, 22.5, 37.5, 52.5, 67.5, 75, // 256
+    82.5, 90, 97.5, 105, 112.5, 120, 127.5, 150, // 264
+    142.5, 135, 127.5, 120, 112.5, 105, 97.5, 90, // 272
+    82.5, 75, 60, 45, 30, 15, 0, -15, // 280
+    -30, -45, -60, -75, -82.5, -90, -97.5, -105, // 288
+    -112.5, -120, -127.5, -135, -142.5, -150, -142.5, -135, // 296
+    -127.5, -120, -112.5, -105, -97.5, -90, -82.5, -75, // 304
+    -60, -45, -30, -15, 0, 15, 30, 45, // 312
+    60, 75, 82.5, 90, 97.5, 105, 112.5, 120, // 320
+    127.5, 135, 142.5, 165, 157.5, 150, 142.5, 135, // 328
+    127.5, 120, 112.5, 105, 97.5, 90, 82.5, 67.5, // 336
+    52.5, 37.5, 22.5, 7.5, -7.5, -22.5, -37.5, -52.5, // 344
+    -67.5, -82.5, -90, -97.5, -105, -112.5, -120, -127.5, // 352
+    -135, -142.5, -150, -157.5, -165, -157.5, -150, -142.5, // 360
+    -135, -127.5, -120, -112.5, -105, -97.5, -90, -82.5, // 368
+    -67.5, -52.5, -37.5, -22.5, -7.5, 7.5, 22.5, 37.5, // 376
+    52.5, 67.5, 82.5, 90, 97.5, 105, 112.5, 120, // 384
+    127.5, 135, 142.5, 150, 157.5, 180, 172.5, 165, // 392
+    157.5, 150, 142.5, 135, 127.5, 120, 112.5, 105, // 400
+    97.5, 90, 75, 60, 45, 30, 15, 0, // 408
+    -15, -30, -45, -60, -75, -90, -97.5, -105, // 416
+    -112.5, -120, -127.5, -135, -142.5, -150, -157.5, -165, // 424
+    -172.5, -180, -172.5, -165, -157.5, -150, -142.5, -135, // 432
+    -127.5, -120, -112.5, -105, -97.5, -90, -75, -60, // 440
+    -45, -30, -15, 0, 15, 30, 45, 60, // 448
+    75, 90, 97.5, 105, 112.5, 120, 127.5, 135, // 456
+    142.5, 150, 157.5, 165, 172.5, 195, 187.5, 180, // 464
+    172.5, 165, 157.5, 150, 142.5, 135, 127.5, 120, // 472
+    112.5, 105, 97.5, 82.5, 67.5, 52.5, 37.5, 22.5, // 480
+    7.5, -7.5, -22.5, -37.5, -52.5, -67.5, -82.5, -97.5, // 488
+    -105, -112.5, -120, -127.5, -135, -142.5, -150, -157.5, // 496
+    -165, -172.5, -180, -187.5, -195, -187.5, -180, -172.5, // 504
+    -165, -157.5, -150, -142.5, -135, -127.5, -120, -112.5, // 512
+    -105, -97.5, -82.5, -67.5, -52.5, -37.5, -22.5, -7.5, // 520
+    7.5, 22.5, 37.5, 52.5, 67.5, 82.5, 97.5, 105, // 528
+    112.5, 120, 127.5, 135, 142.5, 150, 157.5, 165, // 536
+    172.5, 180, 187.5, 210, 202.5, 195, 187.5, 180, // 544
+    172.5, 165, 157.5, 150, 142.5, 135, 127.5, 120, // 552
+    112.5, 105, 90, 75, 60, 45, 30, 15, // 560
+    0, -15, -30, -45, -60, -75, -90, -105, // 568
+    -112.5, -120, -127.5, -135, -142.5, -150, -157.5, -165, // 576
+    -172.5, -180, -187.5, -195, -202.5, -210, -202.5, -195, // 584
+    -187.5, -180, -172.5, -165, -157.5, -150, -142.5, -135, // 592
+    -127.5, -120, -112.5, -105, -90, -75, -60, -45, // 600
+    -30, -15, 0, 15, 30, 45, 60, 75, // 608
+    90, 105, 112.5, 120, 127.5, 135, 142.5, 150, // 616
+    157.5, 165, 172.5, 180, 187.5, 195, 202.5, 225, // 624
+    217.5, 210, 202.5, 195, 187.5, 180, 172.5, 165, // 632
+    157.5, 150, 142.5, 135, 127.5, 120, 112.5, 97.5, // 640
+    82.5, 67.5, 52.5, 37.5, 22.5, 7.5, -7.5, -22.5, // 648
+    -37.5, -52.5, -67.5, -82.5, -97.5, -112.5, -120, -127.5, // 656
+    -135, -142.5, -150, -157.5, -165, -172.5, -180, -187.5, // 664
+    -195, -202.5, -210, -217.5, -225, -217.5, -210, -202.5, // 672
+    -195, -187.5, -180, -172.5, -165, -157.5, -150, -142.5, // 680
+    -135, -127.5, -120, -112.5, -97.5, -82.5, -67.5, -52.5, // 688
+    -37.5, -22.5, -7.5, 7.5, 22.5, 37.5, 52.5, 67.5, // 696
+    82.5, 97.5, 112.5, 120, 127.5, 135, 142.5, 150, // 704
+    157.5, 165, 172.5, 180, 187.5, 195, 202.5, 210, // 712
+    217.5, 240, 232.5, 225, 217.5, 210, 202.5, 195, // 720
+    187.5, 180, 172.5, 165, 157.5, 150, 142.5, 135, // 728
+    127.5, 120, 105, 90, 75, 60, 45, 30, // 736
+    15, 0, -15, -30, -45, -60, -75, -90, // 744
+    -105, -120, -127.5, -135, -142.5, -150, -157.5, -165, // 752
+    -172.5, -180, -187.5, -195, -202.5, -210, -217.5, -225, // 760
+    -232.5, -240, -232.5, -225, -217.5, -210, -202.5, -195, // 768
+    -187.5, -180, -172.5, -165, -157.5, -150, -142.5, -135, // 776
+    -127.5, -120, -105, -90, -75, -60, -45, -30, // 784
+    -15, 0, 15, 30, 45, 60, 75, 90, // 792
+    105, 120, 127.5, 135, 142.5, 150, 157.5, 165, // 800
+    172.5, 180, 187.5, 195, 202.5, 210, 217.5, 225, // 808
+    232.5, 255, 247.5, 240, 232.5, 225, 217.5, 210, // 816
+    202.5, 195, 187.5, 180, 172.5, 165, 157.5, 150, // 824
+    142.5, 135, 127.5, 112.5, 97.5, 82.5, 67.5, 52.5, // 832
+    37.5, 22.5, 7.5, -7.5, -22.5, -37.5, -52.5, -67.5, // 840
+    -82.5, -97.5, -112.5, -127.5, -135, -142.5, -150, -157.5, // 848
+    -165, -172.5, -180, -187.5, -195, -202.5, -210, -217.5, // 856
+    -225, -232.5, -240, -247.5, -255, -247.5, -240, -232.5, // 864
+    -225, -217.5, -210, -202.5, -195, -187.5, -180, -172.5, // 872
+    -165, -157.5, -150, -142.5, -135, -127.5, -112.5, -97.5, // 880
+    -82.5, -67.5, -52.5, -37.5, -22.5, -7.5, 7.5, 22.5, // 888
+    37.5, 52.5, 67.5, 82.5, 97.5, 112.5, 127.5, 135, // 896
+    142.5, 150, 157.5, 165, 172.5, 180, 187.5, 195, // 904
+    202.5, 210, 217.5, 225, 232.5, 240, 247.5, 270, // 912
+    262.5, 255, 247.5, 240, 232.5, 225, 217.5, 210, // 920
+    202.5, 195, 187.5, 180, 172.5, 165, 157.5, 150, // 928
+    142.5, 135, 120, 105, 90, 75, 60, 45, // 936
+    30, 15, 0, -15, -30, -45, -60, -75, // 944
+    -90, -105, -120, -135, -142.5, -150, -157.5, -165, // 952
+    -172.5, -180, -187.5, -195, -202.5, -210, -217.5, -225, // 960
+    -232.5, -240, -247.5, -255, -262.5, -270, -262.5, -255, // 968
+    -247.5, -240, -232.5, -225, -217.5, -210, -202.5, -195, // 976
+    -187.5, -180, -172.5, -165, -157.5, -150, -142.5, -135, // 984
+    -120, -105, -90, -75, -60, -45, -30, -15, // 992
+    0, 15, 30, 45, 60, 75, 90, 105, // 1000
+    120, 135, 142.5, 150, 157.5, 165, 172.5, 180, // 1008
+    187.5, 195, 202.5, 210, 217.5, 225, 232.5, 240, // 1016
+    247.5, 255, 262.5, 285, 277.5, 270, 262.5, 255, // 1024
+    247.5, 240, 232.5, 225, 217.5, 210, 202.5, 195, // 1032
+    187.5, 180, 172.5, 165, 157.5, 150, 142.5, 127.5, // 1040
+    112.5, 97.5, 82.5, 67.5, 52.5, 37.5, 22.5, 7.5, // 1048
+    -7.5, -22.5, -37.5, -52.5, -67.5, -82.5, -97.5, -112.5, // 1056
+    -127.5, -142.5, -150, -157.5, -165, -172.5, -180, -187.5, // 1064
+    -195, -202.5, -210, -217.5, -225, -232.5, -240, -247.5, // 1072
+    -255, -262.5, -270, -277.5, -285, -277.5, -270, -262.5, // 1080
+    -255, -247.5, -240, -232.5, -225, -217.5, -210, -202.5, // 1088
+    -195, -187.5, -180, -172.5, -165, -157.5, -150, -142.5, // 1096
+    -127.5, -112.5, -97.5, -82.5, -67.5, -52.5, -37.5, -22.5, // 1104
+    -7.5, 7.5, 22.5, 37.5, 52.5, 67.5, 82.5, 97.5, // 1112
+    112.5, 127.5, 142.5, 150, 157.5, 165, 172.5, 180, // 1120
+    187.5, 195, 202.5, 210, 217.5, 225, 232.5, 240, // 1128
+    247.5, 255, 262.5, 270, 277.5, 300, 292.5, 285, // 1136
+    277.5, 270, 262.5, 255, 247.5, 240, 232.5, 225, // 1144
+    217.5, 210, 202.5, 195, 187.5, 180, 172.5, 165, // 1152
+    157.5, 150, 135, 120, 105, 90, 75, 60, // 1160
+    45, 30, 15, 0, -15, -30, -45, -60, // 1168
+    -75, -90, -105, -120, -135, -150, -157.5, -165, // 1176
+    -172.5, -180, -187.5, -195, -202.5, -210, -217.5, -225, // 1184
+    -232.5, -240, -247.5, -255, -262.5, -270, -277.5, -285, // 1192
+    -292.5, -300, -292.5, -285, -277.5, -270, -262.5, -255, // 1200
+    -247.5, -240, -232.5, -225, -217.5, -210, -202.5, -195, // 1208
+    -187.5, -180, -172.5, -165, -157.5, -150, -135, -120, // 1216
+    -105, -90, -75, -60, -45, -30, -15, 0, // 1224
+    15, 30, 45, 60, 75, 90, 105, 120, // 1232
+    135, 150, 157.5, 165, 172.5, 180, 187.5, 195, // 1240
+    202.5, 210, 217.5, 225, 232.5, 240, 247.5, 255, // 1248
+    262.5, 270, 277.5, 285, 292.5, 315, 307.5, 300, // 1256
+    292.5, 285, 277.5, 270, 262.5, 255, 247.5, 240, // 1264
+    232.5, 225, 217.5, 210, 202.5, 195, 187.5, 180, // 1272
+    172.5, 165, 157.5, 142.5, 127.5, 112.5, 97.5, 82.5, // 1280
+    67.5, 52.5, 37.5, 22.5, 7.5, -7.5, -22.5, -37.5, // 1288
+    -52.5, -67.5, -82.5, -97.5, -112.5, -127.5, -142.5, -157.5, // 1296
+    -165, -172.5, -180, -187.5, -195, -202.5, -210, -217.5, // 1304
+    -225, -232.5, -240, -247.5, -255, -262.5, -270, -277.5, // 1312
+    -285, -292.5, -300, -307.5, -315, -307.5, -300, -292.5, // 1320
+    -285, -277.5, -270, -262.5, -255, -247.5, -240, -232.5, // 1328
+    -225, -217.5, -210, -202.5, -195, -187.5, -180, -172.5, // 1336
+    -165, -157.5, -142.5, -127.5, -112.5, -97.5, -82.5, -67.5, // 1344
+    -52.5, -37.5, -22.5, -7.5, 7.5, 22.5, 37.5, 52.5, // 1352
+    67.5, 82.5, 97.5, 112.5, 127.5, 142.5, 157.5, 165, // 1360
+    172.5, 180, 187.5, 195, 202.5, 210, 217.5, 225, // 1368
+    232.5, 240, 247.5, 255, 262.5, 270, 277.5, 285, // 1376
+    292.5, 300, 307.5, 330, 322.5, 315, 307.5, 300, // 1384
+    292.5, 285, 277.5, 270, 262.5, 255, 247.5, 240, // 1392
+    232.5, 225, 217.5, 210, 202.5, 195, 187.5, 180, // 1400
+    172.5, 165, 150, 135, 120, 105, 90, 75, // 1408
+    60, 45, 30, 15, 0, -15, -30, -45, // 1416
+    -60, -75, -90, -105, -120, -135, -150, -165, // 1424
+    -172.5, -180, -187.5, -195, -202.5, -210, -217.5, -225, // 1432
+    -232.5, -240, -247.5, -255, -262.5, -270, -277.5, -285, // 1440
+    -292.5, -300, -307.5, -315, -322.5, -330, -322.5, -315, // 1448
+    -307.5, -300, -292.5, -285, -277.5, -270, -262.5, -255, // 1456
+    -247.5, -240, -232.5, -225, -217.5, -210, -202.5, -195, // 1464
+    -187.5, -180, -172.5, -165, -150, -135, -120, -105, // 1472
+    -90, -75, -60, -45, -30, -15, 0, 15, // 1480
+    30, 45, 60, 75, 90, 105, 120, 135, // 1488
+    150, 165, 172.5, 180, 187.5, 195, 202.5, 210, // 1496
+    217.5, 225, 232.5, 240, 247.5, 255, 262.5, 270, // 1504
+    277.5, 285, 292.5, 300, 307.5, 315, 322.5, 345, // 1512
+    337.5, 330, 322.5, 315, 307.5, 300, 292.5, 285, // 1520
+    277.5, 270, 262.5, 255, 247.5, 240, 232.5, 225, // 1528
+    217.5, 210, 202.5, 195, 187.5, 180, 172.5, 157.5, // 1536
+    142.5, 127.5, 112.5, 97.5, 82.5, 67.5, 52.5, 37.5, // 1544
+    22.5, 7.5, -7.5, -22.5, -37.5, -52.5, -67.5, -82.5, // 1552
+    -97.5, -112.5, -127.5, -142.5, -157.5, -172.5, -180, -187.5, // 1560
+    -195, -202.5, -210, -217.5, -225, -232.5, -240, -247.5, // 1568
+    -255, -262.5, -270, -277.5, -285, -292.5, -300, -307.5, // 1576
+    -315, -322.5, -330, -337.5, -345, -337.5, -330, -322.5, // 1584
+    -315, -307.5, -300, -292.5, -285, -277.5, -270, -262.5, // 1592
+    -255, -247.5, -240, -232.5, -225, -217.5, -210, -202.5, // 1600
+    -195, -187.5, -180, -172.5, -157.5, -142.5, -127.5, -112.5, // 1608
+    -97.5, -82.5, -67.5, -52.5, -37.5, -22.5, -7.5, 7.5, // 1616
+    22.5, 37.5, 52.5, 67.5, 82.5, 97.5, 112.5, 127.5, // 1624
+    142.5, 157.5, 172.5, 180, 187.5, 195, 202.5, 210, // 1632
+    217.5, 225, 232.5, 240, 247.5, 255, 262.5, 270, // 1640
+    277.5, 285, 292.5, 300, 307.5, 315, 322.5, 330, // 1648
+    337.5, 360, 345, 330, 315, 300, 285, 270, // 1656
+    255, 240, 225, 210, 195, 165, 135, 105, // 1664
+    75, 45, 15, -15, -45, -75, -105, -135, // 1672
+    -165, -195, -210, -225, -240, -255, -270, -285, // 1680
+    -300, -315, -330, -345, -360, -360, -345, -330, // 1688
+    -315, -300, -285, -270, -255, -240, -225, -210, // 1696
+    -195, -165, -135, -105, -75, -45, -15, 15, // 1704
+    45, 75, 105, 135, 165, 195, 210, 225, // 1712
+    240, 255, 270, 285, 300, 315, 330, 345, // 1720
+    360, 390, 375, 360, 345, 330, 315, 300, // 1728
+    285, 270, 255, 240, 225, 210, 180, 150, // 1736
+    120, 90, 60, 30, 0, -30, -60, -90, // 1744
+    -120, -150, -180, -210, -225, -240, -255, -270, // 1752
+    -285, -300, -315, -330, -345, -360, -375, -390, // 1760
+    -390, -375, -360, -345, -330, -315, -300, -285, // 1768
+    -270, -255, -240, -225, -210, -180, -150, -120, // 1776
+    -90, -60, -30, 0, 30, 60, 90, 120, // 1784
+    150, 180, 210, 225, 240, 255, 270, 285, // 1792
+    300, 315, 330, 345, 360, 375, 390, 420, // 1800
+    405, 390, 375, 360, 345, 330, 315, 300, // 1808
+    285, 270, 255, 240, 225, 195, 165, 135, // 1816
+    105, 75, 45, 15, -15, -45, -75, -105, // 1824
+    -135, -165, -195, -225, -240, -255, -270, -285, // 1832
+    -300, -315, -330, -345, -360, -375, -390, -405, // 1840
+    -420, -420, -405, -390, -375, -360, -345, -330, // 1848
+    -315, -300, -285, -270, -255, -240, -225, -195, // 1856
+    -165, -135, -105, -75, -45, -15, 15, 45, // 1864
+    75, 105, 135, 165, 195, 225, 240, 255, // 1872
+    270, 285, 300, 315, 330, 345, 360, 375, // 1880
+    390, 405, 420, 450, 435, 420, 405, 390, // 1888
+    375, 360, 345, 330, 315, 300, 285, 270, // 1896
+    255, 240, 210, 180, 150, 120, 90, 60, // 1904
+    30, 0, -30, -60, -90, -120, -150, -180, // 1912
+    -210, -240, -255, -270, -285, -300, -315, -330, // 1920
+    -345, -360, -375, -390, -405, -420, -435, -450, // 1928
+    -450, -435, -420, -405, -390, -375, -360, -345, // 1936
+    -330, -315, -300, -285, -270, -255, -240, -210, // 1944
+    -180, -150, -120, -90, -60, -30, 0, 30, // 1952
+    60, 90, 120, 150, 180, 210, 240, 255, // 1960
+    270, 285, 300, 315, 330, 345, 360, 375, // 1968
+    390, 405, 420, 435, 450, 480, 465, 450, // 1976
+    435, 420, 405, 390, 375, 360, 345, 330, // 1984
+    315, 300, 285, 270, 255, 225, 195, 165, // 1992
+    135, 105, 75, 45, 15, -15, -45, -75, // 2000
+    -105, -135, -165, -195, -225, -255, -270, -285, // 2008
+    -300, -315, -330, -345, -360, -375, -390, -405, // 2016
+    -420, -435, -450, -465, -480, -480, -465, -450, // 2024
+    -435, -420, -405, -390, -375, -360, -345, -330, // 2032
+    -315, -300, -285, -270, -255, -225, -195, -165, // 2040
+    -135, -105, -75, -45, -15, 15, 45, 75, // 2048
+    105, 135, 165, 195, 225, 255, 270, 285, // 2056
+    300, 315, 330, 345, 360, 375, 390, 405, // 2064
+    420, 435, 450, 465, 480, 510, 495, 480, // 2072
+    465, 450, 435, 420, 405, 390, 375, 360, // 2080
+    345, 330, 315, 300, 285, 270, 240, 210, // 2088
+    180, 150, 120, 90, 60, 30, 0, -30, // 2096
+    -60, -90, -120, -150, -180, -210, -240, -270, // 2104
+    -285, -300, -315, -330, -345, -360, -375, -390, // 2112
+    -405, -420, -435, -450, -465, -480, -495, -510, // 2120
+    -510, -495, -480, -465, -450, -435, -420, -405, // 2128
+    -390, -375, -360, -345, -330, -315, -300, -285, // 2136
+    -270, -240, -210, -180, -150, -120, -90, -60, // 2144
+    -30, 0, 30, 60, 90, 120, 150, 180, // 2152
+    210, 240, 270, 285, 300, 315, 330, 345, // 2160
+    360, 375, 390, 405, 420, 435, 450, 465, // 2168
+    480, 495, 510, 540, 525, 510, 495, 480, // 2176
+    465, 450, 435, 420, 405, 390, 375, 360, // 2184
+    345, 330, 315, 300, 285, 255, 225, 195, // 2192
+    165, 135, 105, 75, 45, 15, -15, -45, // 2200
+    -75, -105, -135, -165, -195, -225, -255, -285, // 2208
+    -300, -315, -330, -345, -360, -375, -390, -405, // 2216
+    -420, -435, -450, -465, -480, -495, -510, -525, // 2224
+    -540, -540, -525, -510, -495, -480, -465, -450, // 2232
+    -435, -420, -405, -390, -375, -360, -345, -330, // 2240
+    -315, -300, -285, -255, -225, -195, -165, -135, // 2248
+    -105, -75, -45, -15, 15, 45, 75, 105, // 2256
+    135, 165, 195, 225, 255, 285, 300, 315, // 2264
+    330, 345, 360, 375, 390, 405, 420, 435, // 2272
+    450, 465, 480, 495, 510, 525, 540, 570, // 2280
+    555, 540, 525, 510, 495, 480, 465, 450, // 2288
+    435, 420, 405, 390, 375, 360, 345, 330, // 2296
+    315, 300, 270, 240, 210, 180, 150, 120, // 2304
+    90, 60, 30, 0, -30, -60, -90, -120, // 2312
+    -150, -180, -210, -240, -270, -300, -315, -330, // 2320
+    -345, -360, -375, -390, -405, -420, -435, -450, // 2328
+    -465, -480, -495, -510, -525, -540, -555, -570, // 2336
+    -570, -555, -540, -525, -510, -495, -480, -465, // 2344
+    -450, -435, -420, -405, -390, -375, -360, -345, // 2352
+    -330, -315, -300, -270, -240, -210, -180, -150, // 2360
+    -120, -90, -60, -30, 0, 30, 60, 90, // 2368
+    120, 150, 180, 210, 240, 270, 300, 315, // 2376
+    330, 345, 360, 375, 390, 405, 420, 435, // 2384
+    450, 465, 480, 495, 510, 525, 540, 555, // 2392
+    570                        //2400
+  };
+
+  const float ytemp[2401] = {
+    0, 0, 12.9904, 12.9904, -0, -12.9904, -12.9904, 0, // 0
+    12.9904, 25.9808, 25.9808, 25.9808, 12.9904, -0, -12.9904, -25.9808, // 8
+    -25.9808, -25.9808, -12.9904, 0, 12.9904, 25.9808, 38.9711, 38.9711, // 16
+    38.9711, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 24
+    -38.9711, -38.9711, -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, // 32
+    38.9711, 51.9615, 51.9615, 51.9615, 51.9615, 51.9615, 38.9711, 25.9808, // 40
+    12.9904, -0, -12.9904, -25.9808, -38.9711, -51.9615, -51.9615, -51.9615, // 48
+    -51.9615, -51.9615, -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, // 56
+    38.9711, 51.9615, 64.9519, 64.9519, 64.9519, 64.9519, 64.9519, 64.9519, // 64
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 72
+    -51.9615, -64.9519, -64.9519, -64.9519, -64.9519, -64.9519, -64.9519, -51.9615, // 80
+    -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, // 88
+    64.9519, 77.9423, 77.9423, 77.9423, 77.9423, 77.9423, 77.9423, 77.9423, // 96
+    64.9519, 51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, // 104
+    -38.9711, -51.9615, -64.9519, -77.9423, -77.9423, -77.9423, -77.9423, -77.9423, // 112
+    -77.9423, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, // 120
+    12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 90.9327, // 128
+    90.9327, 90.9327, 90.9327, 90.9327, 90.9327, 90.9327, 77.9423, 64.9519, // 136
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 144
+    -51.9615, -64.9519, -77.9423, -90.9327, -90.9327, -90.9327, -90.9327, -90.9327, // 152
+    -90.9327, -90.9327, -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, // 160
+    -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, // 168
+    90.9327, 103.923, 103.923, 103.923, 103.923, 103.923, 103.923, 103.923, // 176
+    103.923, 103.923, 90.9327, 77.9423, 64.9519, 51.9615, 38.9711, 25.9808, // 184
+    12.9904, -0, -12.9904, -25.9808, -38.9711, -51.9615, -64.9519, -77.9423, // 192
+    -90.9327, -103.923, -103.923, -103.923, -103.923, -103.923, -103.923, -103.923, // 200
+    -103.923, -103.923, -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, // 208
+    -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, // 216
+    90.9327, 103.923, 116.913, 116.913, 116.913, 116.913, 116.913, 116.913, // 224
+    116.913, 116.913, 116.913, 116.913, 103.923, 90.9327, 77.9423, 64.9519, // 232
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 240
+    -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -116.913, -116.913, // 248
+    -116.913, -116.913, -116.913, -116.913, -116.913, -116.913, -116.913, -103.923, // 256
+    -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, // 264
+    12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 103.923, // 272
+    116.913, 129.904, 129.904, 129.904, 129.904, 129.904, 129.904, 129.904, // 280
+    129.904, 129.904, 129.904, 129.904, 116.913, 103.923, 90.9327, 77.9423, // 288
+    64.9519, 51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, // 296
+    -38.9711, -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, // 304
+    -129.904, -129.904, -129.904, -129.904, -129.904, -129.904, -129.904, -129.904, // 312
+    -129.904, -129.904, -116.913, -103.923, -90.9327, -77.9423, -64.9519, -51.9615, // 320
+    -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, // 328
+    64.9519, 77.9423, 90.9327, 103.923, 116.913, 129.904, 142.894, 142.894, // 336
+    142.894, 142.894, 142.894, 142.894, 142.894, 142.894, 142.894, 142.894, // 344
+    142.894, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, 64.9519, // 352
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 360
+    -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, -142.894, // 368
+    -142.894, -142.894, -142.894, -142.894, -142.894, -142.894, -142.894, -142.894, // 376
+    -142.894, -142.894, -142.894, -129.904, -116.913, -103.923, -90.9327, -77.9423, // 384
+    -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, // 392
+    38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 103.923, 116.913, 129.904, // 400
+    142.894, 155.885, 155.885, 155.885, 155.885, 155.885, 155.885, 155.885, // 408
+    155.885, 155.885, 155.885, 155.885, 155.885, 155.885, 142.894, 129.904, // 416
+    116.913, 103.923, 90.9327, 77.9423, 64.9519, 51.9615, 38.9711, 25.9808, // 424
+    12.9904, -0, -12.9904, -25.9808, -38.9711, -51.9615, -64.9519, -77.9423, // 432
+    -90.9327, -103.923, -116.913, -129.904, -142.894, -155.885, -155.885, -155.885, // 440
+    -155.885, -155.885, -155.885, -155.885, -155.885, -155.885, -155.885, -155.885, // 448
+    -155.885, -155.885, -142.894, -129.904, -116.913, -103.923, -90.9327, -77.9423, // 456
+    -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, // 464
+    38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 103.923, 116.913, 129.904, // 472
+    142.894, 155.885, 168.875, 168.875, 168.875, 168.875, 168.875, 168.875, // 480
+    168.875, 168.875, 168.875, 168.875, 168.875, 168.875, 168.875, 168.875, // 488
+    155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, 64.9519, // 496
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 504
+    -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, -142.894, // 512
+    -155.885, -168.875, -168.875, -168.875, -168.875, -168.875, -168.875, -168.875, // 520
+    -168.875, -168.875, -168.875, -168.875, -168.875, -168.875, -168.875, -155.885, // 528
+    -142.894, -129.904, -116.913, -103.923, -90.9327, -77.9423, -64.9519, -51.9615, // 536
+    -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, // 544
+    64.9519, 77.9423, 90.9327, 103.923, 116.913, 129.904, 142.894, 155.885, // 552
+    168.875, 181.865, 181.865, 181.865, 181.865, 181.865, 181.865, 181.865, // 560
+    181.865, 181.865, 181.865, 181.865, 181.865, 181.865, 181.865, 181.865, // 568
+    168.875, 155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, // 576
+    64.9519, 51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, // 584
+    -38.9711, -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, // 592
+    -142.894, -155.885, -168.875, -181.865, -181.865, -181.865, -181.865, -181.865, // 600
+    -181.865, -181.865, -181.865, -181.865, -181.865, -181.865, -181.865, -181.865, // 608
+    -181.865, -181.865, -168.875, -155.885, -142.894, -129.904, -116.913, -103.923, // 616
+    -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, // 624
+    12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 103.923, // 632
+    116.913, 129.904, 142.894, 155.885, 168.875, 181.865, 194.856, 194.856, // 640
+    194.856, 194.856, 194.856, 194.856, 194.856, 194.856, 194.856, 194.856, // 648
+    194.856, 194.856, 194.856, 194.856, 194.856, 194.856, 181.865, 168.875, // 656
+    155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, 64.9519, // 664
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 672
+    -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, -142.894, // 680
+    -155.885, -168.875, -181.865, -194.856, -194.856, -194.856, -194.856, -194.856, // 688
+    -194.856, -194.856, -194.856, -194.856, -194.856, -194.856, -194.856, -194.856, // 696
+    -194.856, -194.856, -194.856, -181.865, -168.875, -155.885, -142.894, -129.904, // 704
+    -116.913, -103.923, -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, // 712
+    -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, // 720
+    90.9327, 103.923, 116.913, 129.904, 142.894, 155.885, 168.875, 181.865, // 728
+    194.856, 207.846, 207.846, 207.846, 207.846, 207.846, 207.846, 207.846, // 736
+    207.846, 207.846, 207.846, 207.846, 207.846, 207.846, 207.846, 207.846, // 744
+    207.846, 207.846, 194.856, 181.865, 168.875, 155.885, 142.894, 129.904, // 752
+    116.913, 103.923, 90.9327, 77.9423, 64.9519, 51.9615, 38.9711, 25.9808, // 760
+    12.9904, -0, -12.9904, -25.9808, -38.9711, -51.9615, -64.9519, -77.9423, // 768
+    -90.9327, -103.923, -116.913, -129.904, -142.894, -155.885, -168.875, -181.865, // 776
+    -194.856, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, // 784
+    -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, -207.846, // 792
+    -207.846, -207.846, -194.856, -181.865, -168.875, -155.885, -142.894, -129.904, // 800
+    -116.913, -103.923, -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, // 808
+    -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, // 816
+    90.9327, 103.923, 116.913, 129.904, 142.894, 155.885, 168.875, 181.865, // 824
+    194.856, 207.846, 220.836, 220.836, 220.836, 220.836, 220.836, 220.836, // 832
+    220.836, 220.836, 220.836, 220.836, 220.836, 220.836, 220.836, 220.836, // 840
+    220.836, 220.836, 220.836, 220.836, 207.846, 194.856, 181.865, 168.875, // 848
+    155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, 64.9519, // 856
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 864
+    -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, -142.894, // 872
+    -155.885, -168.875, -181.865, -194.856, -207.846, -220.836, -220.836, -220.836, // 880
+    -220.836, -220.836, -220.836, -220.836, -220.836, -220.836, -220.836, -220.836, // 888
+    -220.836, -220.836, -220.836, -220.836, -220.836, -220.836, -220.836, -207.846, // 896
+    -194.856, -181.865, -168.875, -155.885, -142.894, -129.904, -116.913, -103.923, // 904
+    -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, // 912
+    12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 103.923, // 920
+    116.913, 129.904, 142.894, 155.885, 168.875, 181.865, 194.856, 207.846, // 928
+    220.836, 233.827, 233.827, 233.827, 233.827, 233.827, 233.827, 233.827, // 936
+    233.827, 233.827, 233.827, 233.827, 233.827, 233.827, 233.827, 233.827, // 944
+    233.827, 233.827, 233.827, 233.827, 220.836, 207.846, 194.856, 181.865, // 952
+    168.875, 155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, // 960
+    64.9519, 51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, // 968
+    -38.9711, -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, // 976
+    -142.894, -155.885, -168.875, -181.865, -194.856, -207.846, -220.836, -233.827, // 984
+    -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, // 992
+    -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, -233.827, // 1000
+    -233.827, -233.827, -220.836, -207.846, -194.856, -181.865, -168.875, -155.885, // 1008
+    -142.894, -129.904, -116.913, -103.923, -90.9327, -77.9423, -64.9519, -51.9615, // 1016
+    -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, // 1024
+    64.9519, 77.9423, 90.9327, 103.923, 116.913, 129.904, 142.894, 155.885, // 1032
+    168.875, 181.865, 194.856, 207.846, 220.836, 233.827, 246.817, 246.817, // 1040
+    246.817, 246.817, 246.817, 246.817, 246.817, 246.817, 246.817, 246.817, // 1048
+    246.817, 246.817, 246.817, 246.817, 246.817, 246.817, 246.817, 246.817, // 1056
+    246.817, 246.817, 233.827, 220.836, 207.846, 194.856, 181.865, 168.875, // 1064
+    155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, 64.9519, // 1072
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 1080
+    -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, -142.894, // 1088
+    -155.885, -168.875, -181.865, -194.856, -207.846, -220.836, -233.827, -246.817, // 1096
+    -246.817, -246.817, -246.817, -246.817, -246.817, -246.817, -246.817, -246.817, // 1104
+    -246.817, -246.817, -246.817, -246.817, -246.817, -246.817, -246.817, -246.817, // 1112
+    -246.817, -246.817, -246.817, -233.827, -220.836, -207.846, -194.856, -181.865, // 1120
+    -168.875, -155.885, -142.894, -129.904, -116.913, -103.923, -90.9327, -77.9423, // 1128
+    -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, // 1136
+    38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 103.923, 116.913, 129.904, // 1144
+    142.894, 155.885, 168.875, 181.865, 194.856, 207.846, 220.836, 233.827, // 1152
+    246.817, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, // 1160
+    259.808, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, 259.808, // 1168
+    259.808, 259.808, 259.808, 259.808, 259.808, 259.808, 246.817, 233.827, // 1176
+    220.836, 207.846, 194.856, 181.865, 168.875, 155.885, 142.894, 129.904, // 1184
+    116.913, 103.923, 90.9327, 77.9423, 64.9519, 51.9615, 38.9711, 25.9808, // 1192
+    12.9904, -0, -12.9904, -25.9808, -38.9711, -51.9615, -64.9519, -77.9423, // 1200
+    -90.9327, -103.923, -116.913, -129.904, -142.894, -155.885, -168.875, -181.865, // 1208
+    -194.856, -207.846, -220.836, -233.827, -246.817, -259.808, -259.808, -259.808, // 1216
+    -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, // 1224
+    -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, -259.808, // 1232
+    -259.808, -259.808, -246.817, -233.827, -220.836, -207.846, -194.856, -181.865, // 1240
+    -168.875, -155.885, -142.894, -129.904, -116.913, -103.923, -90.9327, -77.9423, // 1248
+    -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, // 1256
+    38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 103.923, 116.913, 129.904, // 1264
+    142.894, 155.885, 168.875, 181.865, 194.856, 207.846, 220.836, 233.827, // 1272
+    246.817, 259.808, 272.798, 272.798, 272.798, 272.798, 272.798, 272.798, // 1280
+    272.798, 272.798, 272.798, 272.798, 272.798, 272.798, 272.798, 272.798, // 1288
+    272.798, 272.798, 272.798, 272.798, 272.798, 272.798, 272.798, 272.798, // 1296
+    259.808, 246.817, 233.827, 220.836, 207.846, 194.856, 181.865, 168.875, // 1304
+    155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, 64.9519, // 1312
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 1320
+    -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, -142.894, // 1328
+    -155.885, -168.875, -181.865, -194.856, -207.846, -220.836, -233.827, -246.817, // 1336
+    -259.808, -272.798, -272.798, -272.798, -272.798, -272.798, -272.798, -272.798, // 1344
+    -272.798, -272.798, -272.798, -272.798, -272.798, -272.798, -272.798, -272.798, // 1352
+    -272.798, -272.798, -272.798, -272.798, -272.798, -272.798, -272.798, -259.808, // 1360
+    -246.817, -233.827, -220.836, -207.846, -194.856, -181.865, -168.875, -155.885, // 1368
+    -142.894, -129.904, -116.913, -103.923, -90.9327, -77.9423, -64.9519, -51.9615, // 1376
+    -38.9711, -25.9808, -12.9904, 0, 12.9904, 25.9808, 38.9711, 51.9615, // 1384
+    64.9519, 77.9423, 90.9327, 103.923, 116.913, 129.904, 142.894, 155.885, // 1392
+    168.875, 181.865, 194.856, 207.846, 220.836, 233.827, 246.817, 259.808, // 1400
+    272.798, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, // 1408
+    285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, // 1416
+    285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, 285.788, // 1424
+    272.798, 259.808, 246.817, 233.827, 220.836, 207.846, 194.856, 181.865, // 1432
+    168.875, 155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, // 1440
+    64.9519, 51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, // 1448
+    -38.9711, -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, // 1456
+    -142.894, -155.885, -168.875, -181.865, -194.856, -207.846, -220.836, -233.827, // 1464
+    -246.817, -259.808, -272.798, -285.788, -285.788, -285.788, -285.788, -285.788, // 1472
+    -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, // 1480
+    -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, -285.788, // 1488
+    -285.788, -285.788, -272.798, -259.808, -246.817, -233.827, -220.836, -207.846, // 1496
+    -194.856, -181.865, -168.875, -155.885, -142.894, -129.904, -116.913, -103.923, // 1504
+    -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, -12.9904, 0, // 1512
+    12.9904, 25.9808, 38.9711, 51.9615, 64.9519, 77.9423, 90.9327, 103.923, // 1520
+    116.913, 129.904, 142.894, 155.885, 168.875, 181.865, 194.856, 207.846, // 1528
+    220.836, 233.827, 246.817, 259.808, 272.798, 285.788, 298.779, 298.779, // 1536
+    298.779, 298.779, 298.779, 298.779, 298.779, 298.779, 298.779, 298.779, // 1544
+    298.779, 298.779, 298.779, 298.779, 298.779, 298.779, 298.779, 298.779, // 1552
+    298.779, 298.779, 298.779, 298.779, 298.779, 298.779, 285.788, 272.798, // 1560
+    259.808, 246.817, 233.827, 220.836, 207.846, 194.856, 181.865, 168.875, // 1568
+    155.885, 142.894, 129.904, 116.913, 103.923, 90.9327, 77.9423, 64.9519, // 1576
+    51.9615, 38.9711, 25.9808, 12.9904, -0, -12.9904, -25.9808, -38.9711, // 1584
+    -51.9615, -64.9519, -77.9423, -90.9327, -103.923, -116.913, -129.904, -142.894, // 1592
+    -155.885, -168.875, -181.865, -194.856, -207.846, -220.836, -233.827, -246.817, // 1600
+    -259.808, -272.798, -285.788, -298.779, -298.779, -298.779, -298.779, -298.779, // 1608
+    -298.779, -298.779, -298.779, -298.779, -298.779, -298.779, -298.779, -298.779, // 1616
+    -298.779, -298.779, -298.779, -298.779, -298.779, -298.779, -298.779, -298.779, // 1624
+    -298.779, -298.779, -298.779, -285.788, -272.798, -259.808, -246.817, -233.827, // 1632
+    -220.836, -207.846, -194.856, -181.865, -168.875, -155.885, -142.894, -129.904, // 1640
+    -116.913, -103.923, -90.9327, -77.9423, -64.9519, -51.9615, -38.9711, -25.9808, // 1648
+    -12.9904, 17.3205, 43.3013, 69.282, 95.2628, 121.244, 147.224, 173.205, // 1656
+    199.186, 225.167, 251.147, 277.128, 303.109, 320.429, 320.429, 320.429, // 1664
+    320.429, 320.429, 320.429, 320.429, 320.429, 320.429, 320.429, 320.429, // 1672
+    320.429, 303.109, 277.128, 251.147, 225.167, 199.186, 173.205, 147.224, // 1680
+    121.244, 95.2628, 69.282, 43.3013, 17.3205, -17.3205, -43.3013, -69.282, // 1688
+    -95.2628, -121.244, -147.224, -173.205, -199.186, -225.167, -251.147, -277.128, // 1696
+    -303.109, -320.429, -320.429, -320.429, -320.429, -320.429, -320.429, -320.429, // 1704
+    -320.429, -320.429, -320.429, -320.429, -320.429, -303.109, -277.128, -251.147, // 1712
+    -225.167, -199.186, -173.205, -147.224, -121.244, -95.2628, -69.282, -43.3013, // 1720
+    -17.3205, 17.3205, 43.3013, 69.282, 95.2628, 121.244, 147.224, 173.205, // 1728
+    199.186, 225.167, 251.147, 277.128, 303.109, 329.09, 346.41, 346.41, // 1736
+    346.41, 346.41, 346.41, 346.41, 346.41, 346.41, 346.41, 346.41, // 1744
+    346.41, 346.41, 346.41, 329.09, 303.109, 277.128, 251.147, 225.167, // 1752
+    199.186, 173.205, 147.224, 121.244, 95.2628, 69.282, 43.3013, 17.3205, // 1760
+    -17.3205, -43.3013, -69.282, -95.2628, -121.244, -147.224, -173.205, -199.186, // 1768
+    -225.167, -251.147, -277.128, -303.109, -329.09, -346.41, -346.41, -346.41, // 1776
+    -346.41, -346.41, -346.41, -346.41, -346.41, -346.41, -346.41, -346.41, // 1784
+    -346.41, -346.41, -329.09, -303.109, -277.128, -251.147, -225.167, -199.186, // 1792
+    -173.205, -147.224, -121.244, -95.2628, -69.282, -43.3013, -17.3205, 17.3205, // 1800
+    43.3013, 69.282, 95.2628, 121.244, 147.224, 173.205, 199.186, 225.167, // 1808
+    251.147, 277.128, 303.109, 329.09, 355.07, 372.391, 372.391, 372.391, // 1816
+    372.391, 372.391, 372.391, 372.391, 372.391, 372.391, 372.391, 372.391, // 1824
+    372.391, 372.391, 372.391, 355.07, 329.09, 303.109, 277.128, 251.147, // 1832
+    225.167, 199.186, 173.205, 147.224, 121.244, 95.2628, 69.282, 43.3013, // 1840
+    17.3205, -17.3205, -43.3013, -69.282, -95.2628, -121.244, -147.224, -173.205, // 1848
+    -199.186, -225.167, -251.147, -277.128, -303.109, -329.09, -355.07, -372.391, // 1856
+    -372.391, -372.391, -372.391, -372.391, -372.391, -372.391, -372.391, -372.391, // 1864
+    -372.391, -372.391, -372.391, -372.391, -372.391, -355.07, -329.09, -303.109, // 1872
+    -277.128, -251.147, -225.167, -199.186, -173.205, -147.224, -121.244, -95.2628, // 1880
+    -69.282, -43.3013, -17.3205, 17.3205, 43.3013, 69.282, 95.2628, 121.244, // 1888
+    147.224, 173.205, 199.186, 225.167, 251.147, 277.128, 303.109, 329.09, // 1896
+    355.07, 381.051, 398.372, 398.372, 398.372, 398.372, 398.372, 398.372, // 1904
+    398.372, 398.372, 398.372, 398.372, 398.372, 398.372, 398.372, 398.372, // 1912
+    398.372, 381.051, 355.07, 329.09, 303.109, 277.128, 251.147, 225.167, // 1920
+    199.186, 173.205, 147.224, 121.244, 95.2628, 69.282, 43.3013, 17.3205, // 1928
+    -17.3205, -43.3013, -69.282, -95.2628, -121.244, -147.224, -173.205, -199.186, // 1936
+    -225.167, -251.147, -277.128, -303.109, -329.09, -355.07, -381.051, -398.372, // 1944
+    -398.372, -398.372, -398.372, -398.372, -398.372, -398.372, -398.372, -398.372, // 1952
+    -398.372, -398.372, -398.372, -398.372, -398.372, -398.372, -381.051, -355.07, // 1960
+    -329.09, -303.109, -277.128, -251.147, -225.167, -199.186, -173.205, -147.224, // 1968
+    -121.244, -95.2628, -69.282, -43.3013, -17.3205, 17.3205, 43.3013, 69.282, // 1976
+    95.2628, 121.244, 147.224, 173.205, 199.186, 225.167, 251.147, 277.128, // 1984
+    303.109, 329.09, 355.07, 381.051, 407.032, 424.352, 424.352, 424.352, // 1992
+    424.352, 424.352, 424.352, 424.352, 424.352, 424.352, 424.352, 424.352, // 2000
+    424.352, 424.352, 424.352, 424.352, 424.352, 407.032, 381.051, 355.07, // 2008
+    329.09, 303.109, 277.128, 251.147, 225.167, 199.186, 173.205, 147.224, // 2016
+    121.244, 95.2628, 69.282, 43.3013, 17.3205, -17.3205, -43.3013, -69.282, // 2024
+    -95.2628, -121.244, -147.224, -173.205, -199.186, -225.167, -251.147, -277.128, // 2032
+    -303.109, -329.09, -355.07, -381.051, -407.032, -424.352, -424.352, -424.352, // 2040
+    -424.352, -424.352, -424.352, -424.352, -424.352, -424.352, -424.352, -424.352, // 2048
+    -424.352, -424.352, -424.352, -424.352, -424.352, -407.032, -381.051, -355.07, // 2056
+    -329.09, -303.109, -277.128, -251.147, -225.167, -199.186, -173.205, -147.224, // 2064
+    -121.244, -95.2628, -69.282, -43.3013, -17.3205, 17.3205, 43.3013, 69.282, // 2072
+    95.2628, 121.244, 147.224, 173.205, 199.186, 225.167, 251.147, 277.128, // 2080
+    303.109, 329.09, 355.07, 381.051, 407.032, 433.013, 450.333, 450.333, // 2088
+    450.333, 450.333, 450.333, 450.333, 450.333, 450.333, 450.333, 450.333, // 2096
+    450.333, 450.333, 450.333, 450.333, 450.333, 450.333, 450.333, 433.013, // 2104
+    407.032, 381.051, 355.07, 329.09, 303.109, 277.128, 251.147, 225.167, // 2112
+    199.186, 173.205, 147.224, 121.244, 95.2628, 69.282, 43.3013, 17.3205, // 2120
+    -17.3205, -43.3013, -69.282, -95.2628, -121.244, -147.224, -173.205, -199.186, // 2128
+    -225.167, -251.147, -277.128, -303.109, -329.09, -355.07, -381.051, -407.032, // 2136
+    -433.013, -450.333, -450.333, -450.333, -450.333, -450.333, -450.333, -450.333, // 2144
+    -450.333, -450.333, -450.333, -450.333, -450.333, -450.333, -450.333, -450.333, // 2152
+    -450.333, -450.333, -433.013, -407.032, -381.051, -355.07, -329.09, -303.109, // 2160
+    -277.128, -251.147, -225.167, -199.186, -173.205, -147.224, -121.244, -95.2628, // 2168
+    -69.282, -43.3013, -17.3205, 17.3205, 43.3013, 69.282, 95.2628, 121.244, // 2176
+    147.224, 173.205, 199.186, 225.167, 251.147, 277.128, 303.109, 329.09, // 2184
+    355.07, 381.051, 407.032, 433.013, 458.993, 476.314, 476.314, 476.314, // 2192
+    476.314, 476.314, 476.314, 476.314, 476.314, 476.314, 476.314, 476.314, // 2200
+    476.314, 476.314, 476.314, 476.314, 476.314, 476.314, 476.314, 458.993, // 2208
+    433.013, 407.032, 381.051, 355.07, 329.09, 303.109, 277.128, 251.147, // 2216
+    225.167, 199.186, 173.205, 147.224, 121.244, 95.2628, 69.282, 43.3013, // 2224
+    17.3205, -17.3205, -43.3013, -69.282, -95.2628, -121.244, -147.224, -173.205, // 2232
+    -199.186, -225.167, -251.147, -277.128, -303.109, -329.09, -355.07, -381.051, // 2240
+    -407.032, -433.013, -458.993, -476.314, -476.314, -476.314, -476.314, -476.314, // 2248
+    -476.314, -476.314, -476.314, -476.314, -476.314, -476.314, -476.314, -476.314, // 2256
+    -476.314, -476.314, -476.314, -476.314, -476.314, -458.993, -433.013, -407.032, // 2264
+    -381.051, -355.07, -329.09, -303.109, -277.128, -251.147, -225.167, -199.186, // 2272
+    -173.205, -147.224, -121.244, -95.2628, -69.282, -43.3013, -17.3205, 17.3205, // 2280
+    43.3013, 69.282, 95.2628, 121.244, 147.224, 173.205, 199.186, 225.167, // 2288
+    251.147, 277.128, 303.109, 329.09, 355.07, 381.051, 407.032, 433.013, // 2296
+    458.993, 484.974, 502.295, 502.295, 502.295, 502.295, 502.295, 502.295, // 2304
+    502.295, 502.295, 502.295, 502.295, 502.295, 502.295, 502.295, 502.295, // 2312
+    502.295, 502.295, 502.295, 502.295, 502.295, 484.974, 458.993, 433.013, // 2320
+    407.032, 381.051, 355.07, 329.09, 303.109, 277.128, 251.147, 225.167, // 2328
+    199.186, 173.205, 147.224, 121.244, 95.2628, 69.282, 43.3013, 17.3205, // 2336
+    -17.3205, -43.3013, -69.282, -95.2628, -121.244, -147.224, -173.205, -199.186, // 2344
+    -225.167, -251.147, -277.128, -303.109, -329.09, -355.07, -381.051, -407.032, // 2352
+    -433.013, -458.993, -484.974, -502.295, -502.295, -502.295, -502.295, -502.295, // 2360
+    -502.295, -502.295, -502.295, -502.295, -502.295, -502.295, -502.295, -502.295, // 2368
+    -502.295, -502.295, -502.295, -502.295, -502.295, -502.295, -484.974, -458.993, // 2376
+    -433.013, -407.032, -381.051, -355.07, -329.09, -303.109, -277.128, -251.147, // 2384
+    -225.167, -199.186, -173.205, -147.224, -121.244, -95.2628, -69.282, -43.3013, // 2392
+    -17.3205                        //2400
+  };
+
+  const float dtemp[2401] = {
+    15, 15, 15, 15, 15, 15, 15, 15, // 0
+    15, 15, 15, 15, 15, 15, 15, 15, // 8
+    15, 15, 15, 15, 15, 15, 15, 15, // 16
+    15, 15, 15, 15, 15, 15, 15, 15, // 24
+    15, 15, 15, 15, 15, 15, 15, 15, // 32
+    15, 15, 15, 15, 15, 15, 15, 15, // 40
+    15, 15, 15, 15, 15, 15, 15, 15, // 48
+    15, 15, 15, 15, 15, 15, 15, 15, // 56
+    15, 15, 15, 15, 15, 15, 15, 15, // 64
+    15, 15, 15, 15, 15, 15, 15, 15, // 72
+    15, 15, 15, 15, 15, 15, 15, 15, // 80
+    15, 15, 15, 15, 15, 15, 15, 15, // 88
+    15, 15, 15, 15, 15, 15, 15, 15, // 96
+    15, 15, 15, 15, 15, 15, 15, 15, // 104
+    15, 15, 15, 15, 15, 15, 15, 15, // 112
+    15, 15, 15, 15, 15, 15, 15, 15, // 120
+    15, 15, 15, 15, 15, 15, 15, 15, // 128
+    15, 15, 15, 15, 15, 15, 15, 15, // 136
+    15, 15, 15, 15, 15, 15, 15, 15, // 144
+    15, 15, 15, 15, 15, 15, 15, 15, // 152
+    15, 15, 15, 15, 15, 15, 15, 15, // 160
+    15, 15, 15, 15, 15, 15, 15, 15, // 168
+    15, 15, 15, 15, 15, 15, 15, 15, // 176
+    15, 15, 15, 15, 15, 15, 15, 15, // 184
+    15, 15, 15, 15, 15, 15, 15, 15, // 192
+    15, 15, 15, 15, 15, 15, 15, 15, // 200
+    15, 15, 15, 15, 15, 15, 15, 15, // 208
+    15, 15, 15, 15, 15, 15, 15, 15, // 216
+    15, 15, 15, 15, 15, 15, 15, 15, // 224
+    15, 15, 15, 15, 15, 15, 15, 15, // 232
+    15, 15, 15, 15, 15, 15, 15, 15, // 240
+    15, 15, 15, 15, 15, 15, 15, 15, // 248
+    15, 15, 15, 15, 15, 15, 15, 15, // 256
+    15, 15, 15, 15, 15, 15, 15, 15, // 264
+    15, 15, 15, 15, 15, 15, 15, 15, // 272
+    15, 15, 15, 15, 15, 15, 15, 15, // 280
+    15, 15, 15, 15, 15, 15, 15, 15, // 288
+    15, 15, 15, 15, 15, 15, 15, 15, // 296
+    15, 15, 15, 15, 15, 15, 15, 15, // 304
+    15, 15, 15, 15, 15, 15, 15, 15, // 312
+    15, 15, 15, 15, 15, 15, 15, 15, // 320
+    15, 15, 15, 15, 15, 15, 15, 15, // 328
+    15, 15, 15, 15, 15, 15, 15, 15, // 336
+    15, 15, 15, 15, 15, 15, 15, 15, // 344
+    15, 15, 15, 15, 15, 15, 15, 15, // 352
+    15, 15, 15, 15, 15, 15, 15, 15, // 360
+    15, 15, 15, 15, 15, 15, 15, 15, // 368
+    15, 15, 15, 15, 15, 15, 15, 15, // 376
+    15, 15, 15, 15, 15, 15, 15, 15, // 384
+    15, 15, 15, 15, 15, 15, 15, 15, // 392
+    15, 15, 15, 15, 15, 15, 15, 15, // 400
+    15, 15, 15, 15, 15, 15, 15, 15, // 408
+    15, 15, 15, 15, 15, 15, 15, 15, // 416
+    15, 15, 15, 15, 15, 15, 15, 15, // 424
+    15, 15, 15, 15, 15, 15, 15, 15, // 432
+    15, 15, 15, 15, 15, 15, 15, 15, // 440
+    15, 15, 15, 15, 15, 15, 15, 15, // 448
+    15, 15, 15, 15, 15, 15, 15, 15, // 456
+    15, 15, 15, 15, 15, 15, 15, 15, // 464
+    15, 15, 15, 15, 15, 15, 15, 15, // 472
+    15, 15, 15, 15, 15, 15, 15, 15, // 480
+    15, 15, 15, 15, 15, 15, 15, 15, // 488
+    15, 15, 15, 15, 15, 15, 15, 15, // 496
+    15, 15, 15, 15, 15, 15, 15, 15, // 504
+    15, 15, 15, 15, 15, 15, 15, 15, // 512
+    15, 15, 15, 15, 15, 15, 15, 15, // 520
+    15, 15, 15, 15, 15, 15, 15, 15, // 528
+    15, 15, 15, 15, 15, 15, 15, 15, // 536
+    15, 15, 15, 15, 15, 15, 15, 15, // 544
+    15, 15, 15, 15, 15, 15, 15, 15, // 552
+    15, 15, 15, 15, 15, 15, 15, 15, // 560
+    15, 15, 15, 15, 15, 15, 15, 15, // 568
+    15, 15, 15, 15, 15, 15, 15, 15, // 576
+    15, 15, 15, 15, 15, 15, 15, 15, // 584
+    15, 15, 15, 15, 15, 15, 15, 15, // 592
+    15, 15, 15, 15, 15, 15, 15, 15, // 600
+    15, 15, 15, 15, 15, 15, 15, 15, // 608
+    15, 15, 15, 15, 15, 15, 15, 15, // 616
+    15, 15, 15, 15, 15, 15, 15, 15, // 624
+    15, 15, 15, 15, 15, 15, 15, 15, // 632
+    15, 15, 15, 15, 15, 15, 15, 15, // 640
+    15, 15, 15, 15, 15, 15, 15, 15, // 648
+    15, 15, 15, 15, 15, 15, 15, 15, // 656
+    15, 15, 15, 15, 15, 15, 15, 15, // 664
+    15, 15, 15, 15, 15, 15, 15, 15, // 672
+    15, 15, 15, 15, 15, 15, 15, 15, // 680
+    15, 15, 15, 15, 15, 15, 15, 15, // 688
+    15, 15, 15, 15, 15, 15, 15, 15, // 696
+    15, 15, 15, 15, 15, 15, 15, 15, // 704
+    15, 15, 15, 15, 15, 15, 15, 15, // 712
+    15, 15, 15, 15, 15, 15, 15, 15, // 720
+    15, 15, 15, 15, 15, 15, 15, 15, // 728
+    15, 15, 15, 15, 15, 15, 15, 15, // 736
+    15, 15, 15, 15, 15, 15, 15, 15, // 744
+    15, 15, 15, 15, 15, 15, 15, 15, // 752
+    15, 15, 15, 15, 15, 15, 15, 15, // 760
+    15, 15, 15, 15, 15, 15, 15, 15, // 768
+    15, 15, 15, 15, 15, 15, 15, 15, // 776
+    15, 15, 15, 15, 15, 15, 15, 15, // 784
+    15, 15, 15, 15, 15, 15, 15, 15, // 792
+    15, 15, 15, 15, 15, 15, 15, 15, // 800
+    15, 15, 15, 15, 15, 15, 15, 15, // 808
+    15, 15, 15, 15, 15, 15, 15, 15, // 816
+    15, 15, 15, 15, 15, 15, 15, 15, // 824
+    15, 15, 15, 15, 15, 15, 15, 15, // 832
+    15, 15, 15, 15, 15, 15, 15, 15, // 840
+    15, 15, 15, 15, 15, 15, 15, 15, // 848
+    15, 15, 15, 15, 15, 15, 15, 15, // 856
+    15, 15, 15, 15, 15, 15, 15, 15, // 864
+    15, 15, 15, 15, 15, 15, 15, 15, // 872
+    15, 15, 15, 15, 15, 15, 15, 15, // 880
+    15, 15, 15, 15, 15, 15, 15, 15, // 888
+    15, 15, 15, 15, 15, 15, 15, 15, // 896
+    15, 15, 15, 15, 15, 15, 15, 15, // 904
+    15, 15, 15, 15, 15, 15, 15, 15, // 912
+    15, 15, 15, 15, 15, 15, 15, 15, // 920
+    15, 15, 15, 15, 15, 15, 15, 15, // 928
+    15, 15, 15, 15, 15, 15, 15, 15, // 936
+    15, 15, 15, 15, 15, 15, 15, 15, // 944
+    15, 15, 15, 15, 15, 15, 15, 15, // 952
+    15, 15, 15, 15, 15, 15, 15, 15, // 960
+    15, 15, 15, 15, 15, 15, 15, 15, // 968
+    15, 15, 15, 15, 15, 15, 15, 15, // 976
+    15, 15, 15, 15, 15, 15, 15, 15, // 984
+    15, 15, 15, 15, 15, 15, 15, 15, // 992
+    15, 15, 15, 15, 15, 15, 15, 15, // 1000
+    15, 15, 15, 15, 15, 15, 15, 15, // 1008
+    15, 15, 15, 15, 15, 15, 15, 15, // 1016
+    15, 15, 15, 15, 15, 15, 15, 15, // 1024
+    15, 15, 15, 15, 15, 15, 15, 15, // 1032
+    15, 15, 15, 15, 15, 15, 15, 15, // 1040
+    15, 15, 15, 15, 15, 15, 15, 15, // 1048
+    15, 15, 15, 15, 15, 15, 15, 15, // 1056
+    15, 15, 15, 15, 15, 15, 15, 15, // 1064
+    15, 15, 15, 15, 15, 15, 15, 15, // 1072
+    15, 15, 15, 15, 15, 15, 15, 15, // 1080
+    15, 15, 15, 15, 15, 15, 15, 15, // 1088
+    15, 15, 15, 15, 15, 15, 15, 15, // 1096
+    15, 15, 15, 15, 15, 15, 15, 15, // 1104
+    15, 15, 15, 15, 15, 15, 15, 15, // 1112
+    15, 15, 15, 15, 15, 15, 15, 15, // 1120
+    15, 15, 15, 15, 15, 15, 15, 15, // 1128
+    15, 15, 15, 15, 15, 15, 15, 15, // 1136
+    15, 15, 15, 15, 15, 15, 15, 15, // 1144
+    15, 15, 15, 15, 15, 15, 15, 15, // 1152
+    15, 15, 15, 15, 15, 15, 15, 15, // 1160
+    15, 15, 15, 15, 15, 15, 15, 15, // 1168
+    15, 15, 15, 15, 15, 15, 15, 15, // 1176
+    15, 15, 15, 15, 15, 15, 15, 15, // 1184
+    15, 15, 15, 15, 15, 15, 15, 15, // 1192
+    15, 15, 15, 15, 15, 15, 15, 15, // 1200
+    15, 15, 15, 15, 15, 15, 15, 15, // 1208
+    15, 15, 15, 15, 15, 15, 15, 15, // 1216
+    15, 15, 15, 15, 15, 15, 15, 15, // 1224
+    15, 15, 15, 15, 15, 15, 15, 15, // 1232
+    15, 15, 15, 15, 15, 15, 15, 15, // 1240
+    15, 15, 15, 15, 15, 15, 15, 15, // 1248
+    15, 15, 15, 15, 15, 15, 15, 15, // 1256
+    15, 15, 15, 15, 15, 15, 15, 15, // 1264
+    15, 15, 15, 15, 15, 15, 15, 15, // 1272
+    15, 15, 15, 15, 15, 15, 15, 15, // 1280
+    15, 15, 15, 15, 15, 15, 15, 15, // 1288
+    15, 15, 15, 15, 15, 15, 15, 15, // 1296
+    15, 15, 15, 15, 15, 15, 15, 15, // 1304
+    15, 15, 15, 15, 15, 15, 15, 15, // 1312
+    15, 15, 15, 15, 15, 15, 15, 15, // 1320
+    15, 15, 15, 15, 15, 15, 15, 15, // 1328
+    15, 15, 15, 15, 15, 15, 15, 15, // 1336
+    15, 15, 15, 15, 15, 15, 15, 15, // 1344
+    15, 15, 15, 15, 15, 15, 15, 15, // 1352
+    15, 15, 15, 15, 15, 15, 15, 15, // 1360
+    15, 15, 15, 15, 15, 15, 15, 15, // 1368
+    15, 15, 15, 15, 15, 15, 15, 15, // 1376
+    15, 15, 15, 15, 15, 15, 15, 15, // 1384
+    15, 15, 15, 15, 15, 15, 15, 15, // 1392
+    15, 15, 15, 15, 15, 15, 15, 15, // 1400
+    15, 15, 15, 15, 15, 15, 15, 15, // 1408
+    15, 15, 15, 15, 15, 15, 15, 15, // 1416
+    15, 15, 15, 15, 15, 15, 15, 15, // 1424
+    15, 15, 15, 15, 15, 15, 15, 15, // 1432
+    15, 15, 15, 15, 15, 15, 15, 15, // 1440
+    15, 15, 15, 15, 15, 15, 15, 15, // 1448
+    15, 15, 15, 15, 15, 15, 15, 15, // 1456
+    15, 15, 15, 15, 15, 15, 15, 15, // 1464
+    15, 15, 15, 15, 15, 15, 15, 15, // 1472
+    15, 15, 15, 15, 15, 15, 15, 15, // 1480
+    15, 15, 15, 15, 15, 15, 15, 15, // 1488
+    15, 15, 15, 15, 15, 15, 15, 15, // 1496
+    15, 15, 15, 15, 15, 15, 15, 15, // 1504
+    15, 15, 15, 15, 15, 15, 15, 15, // 1512
+    15, 15, 15, 15, 15, 15, 15, 15, // 1520
+    15, 15, 15, 15, 15, 15, 15, 15, // 1528
+    15, 15, 15, 15, 15, 15, 15, 15, // 1536
+    15, 15, 15, 15, 15, 15, 15, 15, // 1544
+    15, 15, 15, 15, 15, 15, 15, 15, // 1552
+    15, 15, 15, 15, 15, 15, 15, 15, // 1560
+    15, 15, 15, 15, 15, 15, 15, 15, // 1568
+    15, 15, 15, 15, 15, 15, 15, 15, // 1576
+    15, 15, 15, 15, 15, 15, 15, 15, // 1584
+    15, 15, 15, 15, 15, 15, 15, 15, // 1592
+    15, 15, 15, 15, 15, 15, 15, 15, // 1600
+    15, 15, 15, 15, 15, 15, 15, 15, // 1608
+    15, 15, 15, 15, 15, 15, 15, 15, // 1616
+    15, 15, 15, 15, 15, 15, 15, 15, // 1624
+    15, 15, 15, 15, 15, 15, 15, 15, // 1632
+    15, 15, 15, 15, 15, 15, 15, 15, // 1640
+    15, 15, 15, 15, 15, 15, 15, 15, // 1648
+    15, 30, 30, 30, 30, 30, 30, 30, // 1656
+    30, 30, 30, 30, 30, 30, 30, 30, // 1664
+    30, 30, 30, 30, 30, 30, 30, 30, // 1672
+    30, 30, 30, 30, 30, 30, 30, 30, // 1680
+    30, 30, 30, 30, 30, 30, 30, 30, // 1688
+    30, 30, 30, 30, 30, 30, 30, 30, // 1696
+    30, 30, 30, 30, 30, 30, 30, 30, // 1704
+    30, 30, 30, 30, 30, 30, 30, 30, // 1712
+    30, 30, 30, 30, 30, 30, 30, 30, // 1720
+    30, 30, 30, 30, 30, 30, 30, 30, // 1728
+    30, 30, 30, 30, 30, 30, 30, 30, // 1736
+    30, 30, 30, 30, 30, 30, 30, 30, // 1744
+    30, 30, 30, 30, 30, 30, 30, 30, // 1752
+    30, 30, 30, 30, 30, 30, 30, 30, // 1760
+    30, 30, 30, 30, 30, 30, 30, 30, // 1768
+    30, 30, 30, 30, 30, 30, 30, 30, // 1776
+    30, 30, 30, 30, 30, 30, 30, 30, // 1784
+    30, 30, 30, 30, 30, 30, 30, 30, // 1792
+    30, 30, 30, 30, 30, 30, 30, 30, // 1800
+    30, 30, 30, 30, 30, 30, 30, 30, // 1808
+    30, 30, 30, 30, 30, 30, 30, 30, // 1816
+    30, 30, 30, 30, 30, 30, 30, 30, // 1824
+    30, 30, 30, 30, 30, 30, 30, 30, // 1832
+    30, 30, 30, 30, 30, 30, 30, 30, // 1840
+    30, 30, 30, 30, 30, 30, 30, 30, // 1848
+    30, 30, 30, 30, 30, 30, 30, 30, // 1856
+    30, 30, 30, 30, 30, 30, 30, 30, // 1864
+    30, 30, 30, 30, 30, 30, 30, 30, // 1872
+    30, 30, 30, 30, 30, 30, 30, 30, // 1880
+    30, 30, 30, 30, 30, 30, 30, 30, // 1888
+    30, 30, 30, 30, 30, 30, 30, 30, // 1896
+    30, 30, 30, 30, 30, 30, 30, 30, // 1904
+    30, 30, 30, 30, 30, 30, 30, 30, // 1912
+    30, 30, 30, 30, 30, 30, 30, 30, // 1920
+    30, 30, 30, 30, 30, 30, 30, 30, // 1928
+    30, 30, 30, 30, 30, 30, 30, 30, // 1936
+    30, 30, 30, 30, 30, 30, 30, 30, // 1944
+    30, 30, 30, 30, 30, 30, 30, 30, // 1952
+    30, 30, 30, 30, 30, 30, 30, 30, // 1960
+    30, 30, 30, 30, 30, 30, 30, 30, // 1968
+    30, 30, 30, 30, 30, 30, 30, 30, // 1976
+    30, 30, 30, 30, 30, 30, 30, 30, // 1984
+    30, 30, 30, 30, 30, 30, 30, 30, // 1992
+    30, 30, 30, 30, 30, 30, 30, 30, // 2000
+    30, 30, 30, 30, 30, 30, 30, 30, // 2008
+    30, 30, 30, 30, 30, 30, 30, 30, // 2016
+    30, 30, 30, 30, 30, 30, 30, 30, // 2024
+    30, 30, 30, 30, 30, 30, 30, 30, // 2032
+    30, 30, 30, 30, 30, 30, 30, 30, // 2040
+    30, 30, 30, 30, 30, 30, 30, 30, // 2048
+    30, 30, 30, 30, 30, 30, 30, 30, // 2056
+    30, 30, 30, 30, 30, 30, 30, 30, // 2064
+    30, 30, 30, 30, 30, 30, 30, 30, // 2072
+    30, 30, 30, 30, 30, 30, 30, 30, // 2080
+    30, 30, 30, 30, 30, 30, 30, 30, // 2088
+    30, 30, 30, 30, 30, 30, 30, 30, // 2096
+    30, 30, 30, 30, 30, 30, 30, 30, // 2104
+    30, 30, 30, 30, 30, 30, 30, 30, // 2112
+    30, 30, 30, 30, 30, 30, 30, 30, // 2120
+    30, 30, 30, 30, 30, 30, 30, 30, // 2128
+    30, 30, 30, 30, 30, 30, 30, 30, // 2136
+    30, 30, 30, 30, 30, 30, 30, 30, // 2144
+    30, 30, 30, 30, 30, 30, 30, 30, // 2152
+    30, 30, 30, 30, 30, 30, 30, 30, // 2160
+    30, 30, 30, 30, 30, 30, 30, 30, // 2168
+    30, 30, 30, 30, 30, 30, 30, 30, // 2176
+    30, 30, 30, 30, 30, 30, 30, 30, // 2184
+    30, 30, 30, 30, 30, 30, 30, 30, // 2192
+    30, 30, 30, 30, 30, 30, 30, 30, // 2200
+    30, 30, 30, 30, 30, 30, 30, 30, // 2208
+    30, 30, 30, 30, 30, 30, 30, 30, // 2216
+    30, 30, 30, 30, 30, 30, 30, 30, // 2224
+    30, 30, 30, 30, 30, 30, 30, 30, // 2232
+    30, 30, 30, 30, 30, 30, 30, 30, // 2240
+    30, 30, 30, 30, 30, 30, 30, 30, // 2248
+    30, 30, 30, 30, 30, 30, 30, 30, // 2256
+    30, 30, 30, 30, 30, 30, 30, 30, // 2264
+    30, 30, 30, 30, 30, 30, 30, 30, // 2272
+    30, 30, 30, 30, 30, 30, 30, 30, // 2280
+    30, 30, 30, 30, 30, 30, 30, 30, // 2288
+    30, 30, 30, 30, 30, 30, 30, 30, // 2296
+    30, 30, 30, 30, 30, 30, 30, 30, // 2304
+    30, 30, 30, 30, 30, 30, 30, 30, // 2312
+    30, 30, 30, 30, 30, 30, 30, 30, // 2320
+    30, 30, 30, 30, 30, 30, 30, 30, // 2328
+    30, 30, 30, 30, 30, 30, 30, 30, // 2336
+    30, 30, 30, 30, 30, 30, 30, 30, // 2344
+    30, 30, 30, 30, 30, 30, 30, 30, // 2352
+    30, 30, 30, 30, 30, 30, 30, 30, // 2360
+    30, 30, 30, 30, 30, 30, 30, 30, // 2368
+    30, 30, 30, 30, 30, 30, 30, 30, // 2376
+    30, 30, 30, 30, 30, 30, 30, 30, // 2384
+    30, 30, 30, 30, 30, 30, 30, 30, // 2392
+    30                        //2400
+  };
+  
+    //
+    //   fill the pixels list with this data
+    //
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+        (*this)[i].Set(xtemp[i], ytemp[i], dtemp[i]);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the next neighbor information from a table into the pixel
+//  objects.
+//
+void MGeomCamMagicHG::CreateNN()
+{
+  const Short_t nn[2401][6] = {       // Neighbours of  #
+    {  1,  2,  3,  4,  5,  6}, // 0
+    {  0,  2,  6,  7,  8,  18},
+    {  0,  1,  3,  8,  9,  10},
+    {  0,  2,  4,  10,  11,  12},
+    {  0,  3,  5,  12,  13,  14},
+    {  0,  4,  6,  14,  15,  16},
+    {  0,  1,  5,  16,  17,  18},
+    {  1,  8,  18,  19,  20,  36},
+    {  1,  2,  7,  9,  20,  21},
+    {  2,  8,  10,  21,  22,  23},
+    {  2,  3,  9,  11,  23,  24},
+    {  3,  10,  12,  24,  25,  26},
+    {  3,  4,  11,  13,  26,  27},
+    {  4,  12,  14,  27,  28,  29},
+    {  4,  5,  13,  15,  29,  30},
+    {  5,  14,  16,  30,  31,  32},
+    {  5,  6,  15,  17,  32,  33},
+    {  6,  16,  18,  33,  34,  35},
+    {  1,  6,  7,  17,  35,  36},
+    {  7,  20,  36,  37,  38,  60},
+    {  7,  8,  19,  21,  38,  39}, // 20
+    {  8,  9,  20,  22,  39,  40},
+    {  9,  21,  23,  40,  41,  42},
+    {  9,  10,  22,  24,  42,  43},
+    {  10,  11,  23,  25,  43,  44},
+    {  11,  24,  26,  44,  45,  46},
+    {  11,  12,  25,  27,  46,  47},
+    {  12,  13,  26,  28,  47,  48},
+    {  13,  27,  29,  48,  49,  50},
+    {  13,  14,  28,  30,  50,  51},
+    {  14,  15,  29,  31,  51,  52},
+    {  15,  30,  32,  52,  53,  54},
+    {  15,  16,  31,  33,  54,  55},
+    {  16,  17,  32,  34,  55,  56},
+    {  17,  33,  35,  56,  57,  58},
+    {  17,  18,  34,  36,  58,  59},
+    {  7,  18,  19,  35,  59,  60},
+    {  19,  38,  60,  61,  62,  90},
+    {  19,  20,  37,  39,  62,  63},
+    {  20,  21,  38,  40,  63,  64},
+    {  21,  22,  39,  41,  64,  65}, // 40
+    {  22,  40,  42,  65,  66,  67},
+    {  22,  23,  41,  43,  67,  68},
+    {  23,  24,  42,  44,  68,  69},
+    {  24,  25,  43,  45,  69,  70},
+    {  25,  44,  46,  70,  71,  72},
+    {  25,  26,  45,  47,  72,  73},
+    {  26,  27,  46,  48,  73,  74},
+    {  27,  28,  47,  49,  74,  75},
+    {  28,  48,  50,  75,  76,  77},
+    {  28,  29,  49,  51,  77,  78},
+    {  29,  30,  50,  52,  78,  79},
+    {  30,  31,  51,  53,  79,  80},
+    {  31,  52,  54,  80,  81,  82},
+    {  31,  32,  53,  55,  82,  83},
+    {  32,  33,  54,  56,  83,  84},
+    {  33,  34,  55,  57,  84,  85},
+    {  34,  56,  58,  85,  86,  87},
+    {  34,  35,  57,  59,  87,  88},
+    {  35,  36,  58,  60,  88,  89},
+    {  19,  36,  37,  59,  89,  90}, // 60
+    {  37,  62,  90,  91,  92,  126},
+    {  37,  38,  61,  63,  92,  93},
+    {  38,  39,  62,  64,  93,  94},
+    {  39,  40,  63,  65,  94,  95},
+    {  40,  41,  64,  66,  95,  96},
+    {  41,  65,  67,  96,  97,  98},
+    {  41,  42,  66,  68,  98,  99},
+    {  42,  43,  67,  69,  99,  100},
+    {  43,  44,  68,  70,  100,  101},
+    {  44,  45,  69,  71,  101,  102},
+    {  45,  70,  72,  102,  103,  104},
+    {  45,  46,  71,  73,  104,  105},
+    {  46,  47,  72,  74,  105,  106},
+    {  47,  48,  73,  75,  106,  107},
+    {  48,  49,  74,  76,  107,  108},
+    {  49,  75,  77,  108,  109,  110},
+    {  49,  50,  76,  78,  110,  111},
+    {  50,  51,  77,  79,  111,  112},
+    {  51,  52,  78,  80,  112,  113},
+    {  52,  53,  79,  81,  113,  114}, // 80
+    {  53,  80,  82,  114,  115,  116},
+    {  53,  54,  81,  83,  116,  117},
+    {  54,  55,  82,  84,  117,  118},
+    {  55,  56,  83,  85,  118,  119},
+    {  56,  57,  84,  86,  119,  120},
+    {  57,  85,  87,  120,  121,  122},
+    {  57,  58,  86,  88,  122,  123},
+    {  58,  59,  87,  89,  123,  124},
+    {  59,  60,  88,  90,  124,  125},
+    {  37,  60,  61,  89,  125,  126},
+    {  61,  92,  126,  127,  128,  168},
+    {  61,  62,  91,  93,  128,  129},
+    {  62,  63,  92,  94,  129,  130},
+    {  63,  64,  93,  95,  130,  131},
+    {  64,  65,  94,  96,  131,  132},
+    {  65,  66,  95,  97,  132,  133},
+    {  66,  96,  98,  133,  134,  135},
+    {  66,  67,  97,  99,  135,  136},
+    {  67,  68,  98,  100,  136,  137},
+    {  68,  69,  99,  101,  137,  138}, // 100
+    {  69,  70,  100,  102,  138,  139},
+    {  70,  71,  101,  103,  139,  140},
+    {  71,  102,  104,  140,  141,  142},
+    {  71,  72,  103,  105,  142,  143},
+    {  72,  73,  104,  106,  143,  144},
+    {  73,  74,  105,  107,  144,  145},
+    {  74,  75,  106,  108,  145,  146},
+    {  75,  76,  107,  109,  146,  147},
+    {  76,  108,  110,  147,  148,  149},
+    {  76,  77,  109,  111,  149,  150},
+    {  77,  78,  110,  112,  150,  151},
+    {  78,  79,  111,  113,  151,  152},
+    {  79,  80,  112,  114,  152,  153},
+    {  80,  81,  113,  115,  153,  154},
+    {  81,  114,  116,  154,  155,  156},
+    {  81,  82,  115,  117,  156,  157},
+    {  82,  83,  116,  118,  157,  158},
+    {  83,  84,  117,  119,  158,  159},
+    {  84,  85,  118,  120,  159,  160},
+    {  85,  86,  119,  121,  160,  161}, // 120
+    {  86,  120,  122,  161,  162,  163},
+    {  86,  87,  121,  123,  163,  164},
+    {  87,  88,  122,  124,  164,  165},
+    {  88,  89,  123,  125,  165,  166},
+    {  89,  90,  124,  126,  166,  167},
+    {  61,  90,  91,  125,  167,  168},
+    {  91,  128,  168,  169,  170,  216},
+    {  91,  92,  127,  129,  170,  171},
+    {  92,  93,  128,  130,  171,  172},
+    {  93,  94,  129,  131,  172,  173},
+    {  94,  95,  130,  132,  173,  174},
+    {  95,  96,  131,  133,  174,  175},
+    {  96,  97,  132,  134,  175,  176},
+    {  97,  133,  135,  176,  177,  178},
+    {  97,  98,  134,  136,  178,  179},
+    {  98,  99,  135,  137,  179,  180},
+    {  99,  100,  136,  138,  180,  181},
+    {  100,  101,  137,  139,  181,  182},
+    {  101,  102,  138,  140,  182,  183},
+    {  102,  103,  139,  141,  183,  184}, // 140
+    {  103,  140,  142,  184,  185,  186},
+    {  103,  104,  141,  143,  186,  187},
+    {  104,  105,  142,  144,  187,  188},
+    {  105,  106,  143,  145,  188,  189},
+    {  106,  107,  144,  146,  189,  190},
+    {  107,  108,  145,  147,  190,  191},
+    {  108,  109,  146,  148,  191,  192},
+    {  109,  147,  149,  192,  193,  194},
+    {  109,  110,  148,  150,  194,  195},
+    {  110,  111,  149,  151,  195,  196},
+    {  111,  112,  150,  152,  196,  197},
+    {  112,  113,  151,  153,  197,  198},
+    {  113,  114,  152,  154,  198,  199},
+    {  114,  115,  153,  155,  199,  200},
+    {  115,  154,  156,  200,  201,  202},
+    {  115,  116,  155,  157,  202,  203},
+    {  116,  117,  156,  158,  203,  204},
+    {  117,  118,  157,  159,  204,  205},
+    {  118,  119,  158,  160,  205,  206},
+    {  119,  120,  159,  161,  206,  207}, // 160
+    {  120,  121,  160,  162,  207,  208},
+    {  121,  161,  163,  208,  209,  210},
+    {  121,  122,  162,  164,  210,  211},
+    {  122,  123,  163,  165,  211,  212},
+    {  123,  124,  164,  166,  212,  213},
+    {  124,  125,  165,  167,  213,  214},
+    {  125,  126,  166,  168,  214,  215},
+    {  91,  126,  127,  167,  215,  216},
+    {  127,  170,  216,  217,  218,  270},
+    {  127,  128,  169,  171,  218,  219},
+    {  128,  129,  170,  172,  219,  220},
+    {  129,  130,  171,  173,  220,  221},
+    {  130,  131,  172,  174,  221,  222},
+    {  131,  132,  173,  175,  222,  223},
+    {  132,  133,  174,  176,  223,  224},
+    {  133,  134,  175,  177,  224,  225},
+    {  134,  176,  178,  225,  226,  227},
+    {  134,  135,  177,  179,  227,  228},
+    {  135,  136,  178,  180,  228,  229},
+    {  136,  137,  179,  181,  229,  230}, // 180
+    {  137,  138,  180,  182,  230,  231},
+    {  138,  139,  181,  183,  231,  232},
+    {  139,  140,  182,  184,  232,  233},
+    {  140,  141,  183,  185,  233,  234},
+    {  141,  184,  186,  234,  235,  236},
+    {  141,  142,  185,  187,  236,  237},
+    {  142,  143,  186,  188,  237,  238},
+    {  143,  144,  187,  189,  238,  239},
+    {  144,  145,  188,  190,  239,  240},
+    {  145,  146,  189,  191,  240,  241},
+    {  146,  147,  190,  192,  241,  242},
+    {  147,  148,  191,  193,  242,  243},
+    {  148,  192,  194,  243,  244,  245},
+    {  148,  149,  193,  195,  245,  246},
+    {  149,  150,  194,  196,  246,  247},
+    {  150,  151,  195,  197,  247,  248},
+    {  151,  152,  196,  198,  248,  249},
+    {  152,  153,  197,  199,  249,  250},
+    {  153,  154,  198,  200,  250,  251},
+    {  154,  155,  199,  201,  251,  252}, // 200
+    {  155,  200,  202,  252,  253,  254},
+    {  155,  156,  201,  203,  254,  255},
+    {  156,  157,  202,  204,  255,  256},
+    {  157,  158,  203,  205,  256,  257},
+    {  158,  159,  204,  206,  257,  258},
+    {  159,  160,  205,  207,  258,  259},
+    {  160,  161,  206,  208,  259,  260},
+    {  161,  162,  207,  209,  260,  261},
+    {  162,  208,  210,  261,  262,  263},
+    {  162,  163,  209,  211,  263,  264},
+    {  163,  164,  210,  212,  264,  265},
+    {  164,  165,  211,  213,  265,  266},
+    {  165,  166,  212,  214,  266,  267},
+    {  166,  167,  213,  215,  267,  268},
+    {  167,  168,  214,  216,  268,  269},
+    {  127,  168,  169,  215,  269,  270},
+    {  169,  218,  270,  271,  272,  330},
+    {  169,  170,  217,  219,  272,  273},
+    {  170,  171,  218,  220,  273,  274},
+    {  171,  172,  219,  221,  274,  275}, // 220
+    {  172,  173,  220,  222,  275,  276},
+    {  173,  174,  221,  223,  276,  277},
+    {  174,  175,  222,  224,  277,  278},
+    {  175,  176,  223,  225,  278,  279},
+    {  176,  177,  224,  226,  279,  280},
+    {  177,  225,  227,  280,  281,  282},
+    {  177,  178,  226,  228,  282,  283},
+    {  178,  179,  227,  229,  283,  284},
+    {  179,  180,  228,  230,  284,  285},
+    {  180,  181,  229,  231,  285,  286},
+    {  181,  182,  230,  232,  286,  287},
+    {  182,  183,  231,  233,  287,  288},
+    {  183,  184,  232,  234,  288,  289},
+    {  184,  185,  233,  235,  289,  290},
+    {  185,  234,  236,  290,  291,  292},
+    {  185,  186,  235,  237,  292,  293},
+    {  186,  187,  236,  238,  293,  294},
+    {  187,  188,  237,  239,  294,  295},
+    {  188,  189,  238,  240,  295,  296},
+    {  189,  190,  239,  241,  296,  297}, // 240
+    {  190,  191,  240,  242,  297,  298},
+    {  191,  192,  241,  243,  298,  299},
+    {  192,  193,  242,  244,  299,  300},
+    {  193,  243,  245,  300,  301,  302},
+    {  193,  194,  244,  246,  302,  303},
+    {  194,  195,  245,  247,  303,  304},
+    {  195,  196,  246,  248,  304,  305},
+    {  196,  197,  247,  249,  305,  306},
+    {  197,  198,  248,  250,  306,  307},
+    {  198,  199,  249,  251,  307,  308},
+    {  199,  200,  250,  252,  308,  309},
+    {  200,  201,  251,  253,  309,  310},
+    {  201,  252,  254,  310,  311,  312},
+    {  201,  202,  253,  255,  312,  313},
+    {  202,  203,  254,  256,  313,  314},
+    {  203,  204,  255,  257,  314,  315},
+    {  204,  205,  256,  258,  315,  316},
+    {  205,  206,  257,  259,  316,  317},
+    {  206,  207,  258,  260,  317,  318},
+    {  207,  208,  259,  261,  318,  319}, // 260
+    {  208,  209,  260,  262,  319,  320},
+    {  209,  261,  263,  320,  321,  322},
+    {  209,  210,  262,  264,  322,  323},
+    {  210,  211,  263,  265,  323,  324},
+    {  211,  212,  264,  266,  324,  325},
+    {  212,  213,  265,  267,  325,  326},
+    {  213,  214,  266,  268,  326,  327},
+    {  214,  215,  267,  269,  327,  328},
+    {  215,  216,  268,  270,  328,  329},
+    {  169,  216,  217,  269,  329,  330},
+    {  217,  272,  330,  331,  332,  396},
+    {  217,  218,  271,  273,  332,  333},
+    {  218,  219,  272,  274,  333,  334},
+    {  219,  220,  273,  275,  334,  335},
+    {  220,  221,  274,  276,  335,  336},
+    {  221,  222,  275,  277,  336,  337},
+    {  222,  223,  276,  278,  337,  338},
+    {  223,  224,  277,  279,  338,  339},
+    {  224,  225,  278,  280,  339,  340},
+    {  225,  226,  279,  281,  340,  341}, // 280
+    {  226,  280,  282,  341,  342,  343},
+    {  226,  227,  281,  283,  343,  344},
+    {  227,  228,  282,  284,  344,  345},
+    {  228,  229,  283,  285,  345,  346},
+    {  229,  230,  284,  286,  346,  347},
+    {  230,  231,  285,  287,  347,  348},
+    {  231,  232,  286,  288,  348,  349},
+    {  232,  233,  287,  289,  349,  350},
+    {  233,  234,  288,  290,  350,  351},
+    {  234,  235,  289,  291,  351,  352},
+    {  235,  290,  292,  352,  353,  354},
+    {  235,  236,  291,  293,  354,  355},
+    {  236,  237,  292,  294,  355,  356},
+    {  237,  238,  293,  295,  356,  357},
+    {  238,  239,  294,  296,  357,  358},
+    {  239,  240,  295,  297,  358,  359},
+    {  240,  241,  296,  298,  359,  360},
+    {  241,  242,  297,  299,  360,  361},
+    {  242,  243,  298,  300,  361,  362},
+    {  243,  244,  299,  301,  362,  363}, // 300
+    {  244,  300,  302,  363,  364,  365},
+    {  244,  245,  301,  303,  365,  366},
+    {  245,  246,  302,  304,  366,  367},
+    {  246,  247,  303,  305,  367,  368},
+    {  247,  248,  304,  306,  368,  369},
+    {  248,  249,  305,  307,  369,  370},
+    {  249,  250,  306,  308,  370,  371},
+    {  250,  251,  307,  309,  371,  372},
+    {  251,  252,  308,  310,  372,  373},
+    {  252,  253,  309,  311,  373,  374},
+    {  253,  310,  312,  374,  375,  376},
+    {  253,  254,  311,  313,  376,  377},
+    {  254,  255,  312,  314,  377,  378},
+    {  255,  256,  313,  315,  378,  379},
+    {  256,  257,  314,  316,  379,  380},
+    {  257,  258,  315,  317,  380,  381},
+    {  258,  259,  316,  318,  381,  382},
+    {  259,  260,  317,  319,  382,  383},
+    {  260,  261,  318,  320,  383,  384},
+    {  261,  262,  319,  321,  384,  385}, // 320
+    {  262,  320,  322,  385,  386,  387},
+    {  262,  263,  321,  323,  387,  388},
+    {  263,  264,  322,  324,  388,  389},
+    {  264,  265,  323,  325,  389,  390},
+    {  265,  266,  324,  326,  390,  391},
+    {  266,  267,  325,  327,  391,  392},
+    {  267,  268,  326,  328,  392,  393},
+    {  268,  269,  327,  329,  393,  394},
+    {  269,  270,  328,  330,  394,  395},
+    {  217,  270,  271,  329,  395,  396},
+    {  271,  332,  396,  397,  398,  468},
+    {  271,  272,  331,  333,  398,  399},
+    {  272,  273,  332,  334,  399,  400},
+    {  273,  274,  333,  335,  400,  401},
+    {  274,  275,  334,  336,  401,  402},
+    {  275,  276,  335,  337,  402,  403},
+    {  276,  277,  336,  338,  403,  404},
+    {  277,  278,  337,  339,  404,  405},
+    {  278,  279,  338,  340,  405,  406},
+    {  279,  280,  339,  341,  406,  407}, // 340
+    {  280,  281,  340,  342,  407,  408},
+    {  281,  341,  343,  408,  409,  410},
+    {  281,  282,  342,  344,  410,  411},
+    {  282,  283,  343,  345,  411,  412},
+    {  283,  284,  344,  346,  412,  413},
+    {  284,  285,  345,  347,  413,  414},
+    {  285,  286,  346,  348,  414,  415},
+    {  286,  287,  347,  349,  415,  416},
+    {  287,  288,  348,  350,  416,  417},
+    {  288,  289,  349,  351,  417,  418},
+    {  289,  290,  350,  352,  418,  419},
+    {  290,  291,  351,  353,  419,  420},
+    {  291,  352,  354,  420,  421,  422},
+    {  291,  292,  353,  355,  422,  423},
+    {  292,  293,  354,  356,  423,  424},
+    {  293,  294,  355,  357,  424,  425},
+    {  294,  295,  356,  358,  425,  426},
+    {  295,  296,  357,  359,  426,  427},
+    {  296,  297,  358,  360,  427,  428},
+    {  297,  298,  359,  361,  428,  429}, // 360
+    {  298,  299,  360,  362,  429,  430},
+    {  299,  300,  361,  363,  430,  431},
+    {  300,  301,  362,  364,  431,  432},
+    {  301,  363,  365,  432,  433,  434},
+    {  301,  302,  364,  366,  434,  435},
+    {  302,  303,  365,  367,  435,  436},
+    {  303,  304,  366,  368,  436,  437},
+    {  304,  305,  367,  369,  437,  438},
+    {  305,  306,  368,  370,  438,  439},
+    {  306,  307,  369,  371,  439,  440},
+    {  307,  308,  370,  372,  440,  441},
+    {  308,  309,  371,  373,  441,  442},
+    {  309,  310,  372,  374,  442,  443},
+    {  310,  311,  373,  375,  443,  444},
+    {  311,  374,  376,  444,  445,  446},
+    {  311,  312,  375,  377,  446,  447},
+    {  312,  313,  376,  378,  447,  448},
+    {  313,  314,  377,  379,  448,  449},
+    {  314,  315,  378,  380,  449,  450},
+    {  315,  316,  379,  381,  450,  451}, // 380
+    {  316,  317,  380,  382,  451,  452},
+    {  317,  318,  381,  383,  452,  453},
+    {  318,  319,  382,  384,  453,  454},
+    {  319,  320,  383,  385,  454,  455},
+    {  320,  321,  384,  386,  455,  456},
+    {  321,  385,  387,  456,  457,  458},
+    {  321,  322,  386,  388,  458,  459},
+    {  322,  323,  387,  389,  459,  460},
+    {  323,  324,  388,  390,  460,  461},
+    {  324,  325,  389,  391,  461,  462},
+    {  325,  326,  390,  392,  462,  463},
+    {  326,  327,  391,  393,  463,  464},
+    {  327,  328,  392,  394,  464,  465},
+    {  328,  329,  393,  395,  465,  466},
+    {  329,  330,  394,  396,  466,  467},
+    {  271,  330,  331,  395,  467,  468},
+    {  331,  398,  468,  469,  470,  546},
+    {  331,  332,  397,  399,  470,  471},
+    {  332,  333,  398,  400,  471,  472},
+    {  333,  334,  399,  401,  472,  473}, // 400
+    {  334,  335,  400,  402,  473,  474},
+    {  335,  336,  401,  403,  474,  475},
+    {  336,  337,  402,  404,  475,  476},
+    {  337,  338,  403,  405,  476,  477},
+    {  338,  339,  404,  406,  477,  478},
+    {  339,  340,  405,  407,  478,  479},
+    {  340,  341,  406,  408,  479,  480},
+    {  341,  342,  407,  409,  480,  481},
+    {  342,  408,  410,  481,  482,  483},
+    {  342,  343,  409,  411,  483,  484},
+    {  343,  344,  410,  412,  484,  485},
+    {  344,  345,  411,  413,  485,  486},
+    {  345,  346,  412,  414,  486,  487},
+    {  346,  347,  413,  415,  487,  488},
+    {  347,  348,  414,  416,  488,  489},
+    {  348,  349,  415,  417,  489,  490},
+    {  349,  350,  416,  418,  490,  491},
+    {  350,  351,  417,  419,  491,  492},
+    {  351,  352,  418,  420,  492,  493},
+    {  352,  353,  419,  421,  493,  494}, // 420
+    {  353,  420,  422,  494,  495,  496},
+    {  353,  354,  421,  423,  496,  497},
+    {  354,  355,  422,  424,  497,  498},
+    {  355,  356,  423,  425,  498,  499},
+    {  356,  357,  424,  426,  499,  500},
+    {  357,  358,  425,  427,  500,  501},
+    {  358,  359,  426,  428,  501,  502},
+    {  359,  360,  427,  429,  502,  503},
+    {  360,  361,  428,  430,  503,  504},
+    {  361,  362,  429,  431,  504,  505},
+    {  362,  363,  430,  432,  505,  506},
+    {  363,  364,  431,  433,  506,  507},
+    {  364,  432,  434,  507,  508,  509},
+    {  364,  365,  433,  435,  509,  510},
+    {  365,  366,  434,  436,  510,  511},
+    {  366,  367,  435,  437,  511,  512},
+    {  367,  368,  436,  438,  512,  513},
+    {  368,  369,  437,  439,  513,  514},
+    {  369,  370,  438,  440,  514,  515},
+    {  370,  371,  439,  441,  515,  516}, // 440
+    {  371,  372,  440,  442,  516,  517},
+    {  372,  373,  441,  443,  517,  518},
+    {  373,  374,  442,  444,  518,  519},
+    {  374,  375,  443,  445,  519,  520},
+    {  375,  444,  446,  520,  521,  522},
+    {  375,  376,  445,  447,  522,  523},
+    {  376,  377,  446,  448,  523,  524},
+    {  377,  378,  447,  449,  524,  525},
+    {  378,  379,  448,  450,  525,  526},
+    {  379,  380,  449,  451,  526,  527},
+    {  380,  381,  450,  452,  527,  528},
+    {  381,  382,  451,  453,  528,  529},
+    {  382,  383,  452,  454,  529,  530},
+    {  383,  384,  453,  455,  530,  531},
+    {  384,  385,  454,  456,  531,  532},
+    {  385,  386,  455,  457,  532,  533},
+    {  386,  456,  458,  533,  534,  535},
+    {  386,  387,  457,  459,  535,  536},
+    {  387,  388,  458,  460,  536,  537},
+    {  388,  389,  459,  461,  537,  538}, // 460
+    {  389,  390,  460,  462,  538,  539},
+    {  390,  391,  461,  463,  539,  540},
+    {  391,  392,  462,  464,  540,  541},
+    {  392,  393,  463,  465,  541,  542},
+    {  393,  394,  464,  466,  542,  543},
+    {  394,  395,  465,  467,  543,  544},
+    {  395,  396,  466,  468,  544,  545},
+    {  331,  396,  397,  467,  545,  546},
+    {  397,  470,  546,  547,  548,  630},
+    {  397,  398,  469,  471,  548,  549},
+    {  398,  399,  470,  472,  549,  550},
+    {  399,  400,  471,  473,  550,  551},
+    {  400,  401,  472,  474,  551,  552},
+    {  401,  402,  473,  475,  552,  553},
+    {  402,  403,  474,  476,  553,  554},
+    {  403,  404,  475,  477,  554,  555},
+    {  404,  405,  476,  478,  555,  556},
+    {  405,  406,  477,  479,  556,  557},
+    {  406,  407,  478,  480,  557,  558},
+    {  407,  408,  479,  481,  558,  559}, // 480
+    {  408,  409,  480,  482,  559,  560},
+    {  409,  481,  483,  560,  561,  562},
+    {  409,  410,  482,  484,  562,  563},
+    {  410,  411,  483,  485,  563,  564},
+    {  411,  412,  484,  486,  564,  565},
+    {  412,  413,  485,  487,  565,  566},
+    {  413,  414,  486,  488,  566,  567},
+    {  414,  415,  487,  489,  567,  568},
+    {  415,  416,  488,  490,  568,  569},
+    {  416,  417,  489,  491,  569,  570},
+    {  417,  418,  490,  492,  570,  571},
+    {  418,  419,  491,  493,  571,  572},
+    {  419,  420,  492,  494,  572,  573},
+    {  420,  421,  493,  495,  573,  574},
+    {  421,  494,  496,  574,  575,  576},
+    {  421,  422,  495,  497,  576,  577},
+    {  422,  423,  496,  498,  577,  578},
+    {  423,  424,  497,  499,  578,  579},
+    {  424,  425,  498,  500,  579,  580},
+    {  425,  426,  499,  501,  580,  581}, // 500
+    {  426,  427,  500,  502,  581,  582},
+    {  427,  428,  501,  503,  582,  583},
+    {  428,  429,  502,  504,  583,  584},
+    {  429,  430,  503,  505,  584,  585},
+    {  430,  431,  504,  506,  585,  586},
+    {  431,  432,  505,  507,  586,  587},
+    {  432,  433,  506,  508,  587,  588},
+    {  433,  507,  509,  588,  589,  590},
+    {  433,  434,  508,  510,  590,  591},
+    {  434,  435,  509,  511,  591,  592},
+    {  435,  436,  510,  512,  592,  593},
+    {  436,  437,  511,  513,  593,  594},
+    {  437,  438,  512,  514,  594,  595},
+    {  438,  439,  513,  515,  595,  596},
+    {  439,  440,  514,  516,  596,  597},
+    {  440,  441,  515,  517,  597,  598},
+    {  441,  442,  516,  518,  598,  599},
+    {  442,  443,  517,  519,  599,  600},
+    {  443,  444,  518,  520,  600,  601},
+    {  444,  445,  519,  521,  601,  602}, // 520
+    {  445,  520,  522,  602,  603,  604},
+    {  445,  446,  521,  523,  604,  605},
+    {  446,  447,  522,  524,  605,  606},
+    {  447,  448,  523,  525,  606,  607},
+    {  448,  449,  524,  526,  607,  608},
+    {  449,  450,  525,  527,  608,  609},
+    {  450,  451,  526,  528,  609,  610},
+    {  451,  452,  527,  529,  610,  611},
+    {  452,  453,  528,  530,  611,  612},
+    {  453,  454,  529,  531,  612,  613},
+    {  454,  455,  530,  532,  613,  614},
+    {  455,  456,  531,  533,  614,  615},
+    {  456,  457,  532,  534,  615,  616},
+    {  457,  533,  535,  616,  617,  618},
+    {  457,  458,  534,  536,  618,  619},
+    {  458,  459,  535,  537,  619,  620},
+    {  459,  460,  536,  538,  620,  621},
+    {  460,  461,  537,  539,  621,  622},
+    {  461,  462,  538,  540,  622,  623},
+    {  462,  463,  539,  541,  623,  624}, // 540
+    {  463,  464,  540,  542,  624,  625},
+    {  464,  465,  541,  543,  625,  626},
+    {  465,  466,  542,  544,  626,  627},
+    {  466,  467,  543,  545,  627,  628},
+    {  467,  468,  544,  546,  628,  629},
+    {  397,  468,  469,  545,  629,  630},
+    {  469,  548,  630,  631,  632,  720},
+    {  469,  470,  547,  549,  632,  633},
+    {  470,  471,  548,  550,  633,  634},
+    {  471,  472,  549,  551,  634,  635},
+    {  472,  473,  550,  552,  635,  636},
+    {  473,  474,  551,  553,  636,  637},
+    {  474,  475,  552,  554,  637,  638},
+    {  475,  476,  553,  555,  638,  639},
+    {  476,  477,  554,  556,  639,  640},
+    {  477,  478,  555,  557,  640,  641},
+    {  478,  479,  556,  558,  641,  642},
+    {  479,  480,  557,  559,  642,  643},
+    {  480,  481,  558,  560,  643,  644},
+    {  481,  482,  559,  561,  644,  645}, // 560
+    {  482,  560,  562,  645,  646,  647},
+    {  482,  483,  561,  563,  647,  648},
+    {  483,  484,  562,  564,  648,  649},
+    {  484,  485,  563,  565,  649,  650},
+    {  485,  486,  564,  566,  650,  651},
+    {  486,  487,  565,  567,  651,  652},
+    {  487,  488,  566,  568,  652,  653},
+    {  488,  489,  567,  569,  653,  654},
+    {  489,  490,  568,  570,  654,  655},
+    {  490,  491,  569,  571,  655,  656},
+    {  491,  492,  570,  572,  656,  657},
+    {  492,  493,  571,  573,  657,  658},
+    {  493,  494,  572,  574,  658,  659},
+    {  494,  495,  573,  575,  659,  660},
+    {  495,  574,  576,  660,  661,  662},
+    {  495,  496,  575,  577,  662,  663},
+    {  496,  497,  576,  578,  663,  664},
+    {  497,  498,  577,  579,  664,  665},
+    {  498,  499,  578,  580,  665,  666},
+    {  499,  500,  579,  581,  666,  667}, // 580
+    {  500,  501,  580,  582,  667,  668},
+    {  501,  502,  581,  583,  668,  669},
+    {  502,  503,  582,  584,  669,  670},
+    {  503,  504,  583,  585,  670,  671},
+    {  504,  505,  584,  586,  671,  672},
+    {  505,  506,  585,  587,  672,  673},
+    {  506,  507,  586,  588,  673,  674},
+    {  507,  508,  587,  589,  674,  675},
+    {  508,  588,  590,  675,  676,  677},
+    {  508,  509,  589,  591,  677,  678},
+    {  509,  510,  590,  592,  678,  679},
+    {  510,  511,  591,  593,  679,  680},
+    {  511,  512,  592,  594,  680,  681},
+    {  512,  513,  593,  595,  681,  682},
+    {  513,  514,  594,  596,  682,  683},
+    {  514,  515,  595,  597,  683,  684},
+    {  515,  516,  596,  598,  684,  685},
+    {  516,  517,  597,  599,  685,  686},
+    {  517,  518,  598,  600,  686,  687},
+    {  518,  519,  599,  601,  687,  688}, // 600
+    {  519,  520,  600,  602,  688,  689},
+    {  520,  521,  601,  603,  689,  690},
+    {  521,  602,  604,  690,  691,  692},
+    {  521,  522,  603,  605,  692,  693},
+    {  522,  523,  604,  606,  693,  694},
+    {  523,  524,  605,  607,  694,  695},
+    {  524,  525,  606,  608,  695,  696},
+    {  525,  526,  607,  609,  696,  697},
+    {  526,  527,  608,  610,  697,  698},
+    {  527,  528,  609,  611,  698,  699},
+    {  528,  529,  610,  612,  699,  700},
+    {  529,  530,  611,  613,  700,  701},
+    {  530,  531,  612,  614,  701,  702},
+    {  531,  532,  613,  615,  702,  703},
+    {  532,  533,  614,  616,  703,  704},
+    {  533,  534,  615,  617,  704,  705},
+    {  534,  616,  618,  705,  706,  707},
+    {  534,  535,  617,  619,  707,  708},
+    {  535,  536,  618,  620,  708,  709},
+    {  536,  537,  619,  621,  709,  710}, // 620
+    {  537,  538,  620,  622,  710,  711},
+    {  538,  539,  621,  623,  711,  712},
+    {  539,  540,  622,  624,  712,  713},
+    {  540,  541,  623,  625,  713,  714},
+    {  541,  542,  624,  626,  714,  715},
+    {  542,  543,  625,  627,  715,  716},
+    {  543,  544,  626,  628,  716,  717},
+    {  544,  545,  627,  629,  717,  718},
+    {  545,  546,  628,  630,  718,  719},
+    {  469,  546,  547,  629,  719,  720},
+    {  547,  632,  720,  721,  722,  816},
+    {  547,  548,  631,  633,  722,  723},
+    {  548,  549,  632,  634,  723,  724},
+    {  549,  550,  633,  635,  724,  725},
+    {  550,  551,  634,  636,  725,  726},
+    {  551,  552,  635,  637,  726,  727},
+    {  552,  553,  636,  638,  727,  728},
+    {  553,  554,  637,  639,  728,  729},
+    {  554,  555,  638,  640,  729,  730},
+    {  555,  556,  639,  641,  730,  731}, // 640
+    {  556,  557,  640,  642,  731,  732},
+    {  557,  558,  641,  643,  732,  733},
+    {  558,  559,  642,  644,  733,  734},
+    {  559,  560,  643,  645,  734,  735},
+    {  560,  561,  644,  646,  735,  736},
+    {  561,  645,  647,  736,  737,  738},
+    {  561,  562,  646,  648,  738,  739},
+    {  562,  563,  647,  649,  739,  740},
+    {  563,  564,  648,  650,  740,  741},
+    {  564,  565,  649,  651,  741,  742},
+    {  565,  566,  650,  652,  742,  743},
+    {  566,  567,  651,  653,  743,  744},
+    {  567,  568,  652,  654,  744,  745},
+    {  568,  569,  653,  655,  745,  746},
+    {  569,  570,  654,  656,  746,  747},
+    {  570,  571,  655,  657,  747,  748},
+    {  571,  572,  656,  658,  748,  749},
+    {  572,  573,  657,  659,  749,  750},
+    {  573,  574,  658,  660,  750,  751},
+    {  574,  575,  659,  661,  751,  752}, // 660
+    {  575,  660,  662,  752,  753,  754},
+    {  575,  576,  661,  663,  754,  755},
+    {  576,  577,  662,  664,  755,  756},
+    {  577,  578,  663,  665,  756,  757},
+    {  578,  579,  664,  666,  757,  758},
+    {  579,  580,  665,  667,  758,  759},
+    {  580,  581,  666,  668,  759,  760},
+    {  581,  582,  667,  669,  760,  761},
+    {  582,  583,  668,  670,  761,  762},
+    {  583,  584,  669,  671,  762,  763},
+    {  584,  585,  670,  672,  763,  764},
+    {  585,  586,  671,  673,  764,  765},
+    {  586,  587,  672,  674,  765,  766},
+    {  587,  588,  673,  675,  766,  767},
+    {  588,  589,  674,  676,  767,  768},
+    {  589,  675,  677,  768,  769,  770},
+    {  589,  590,  676,  678,  770,  771},
+    {  590,  591,  677,  679,  771,  772},
+    {  591,  592,  678,  680,  772,  773},
+    {  592,  593,  679,  681,  773,  774}, // 680
+    {  593,  594,  680,  682,  774,  775},
+    {  594,  595,  681,  683,  775,  776},
+    {  595,  596,  682,  684,  776,  777},
+    {  596,  597,  683,  685,  777,  778},
+    {  597,  598,  684,  686,  778,  779},
+    {  598,  599,  685,  687,  779,  780},
+    {  599,  600,  686,  688,  780,  781},
+    {  600,  601,  687,  689,  781,  782},
+    {  601,  602,  688,  690,  782,  783},
+    {  602,  603,  689,  691,  783,  784},
+    {  603,  690,  692,  784,  785,  786},
+    {  603,  604,  691,  693,  786,  787},
+    {  604,  605,  692,  694,  787,  788},
+    {  605,  606,  693,  695,  788,  789},
+    {  606,  607,  694,  696,  789,  790},
+    {  607,  608,  695,  697,  790,  791},
+    {  608,  609,  696,  698,  791,  792},
+    {  609,  610,  697,  699,  792,  793},
+    {  610,  611,  698,  700,  793,  794},
+    {  611,  612,  699,  701,  794,  795}, // 700
+    {  612,  613,  700,  702,  795,  796},
+    {  613,  614,  701,  703,  796,  797},
+    {  614,  615,  702,  704,  797,  798},
+    {  615,  616,  703,  705,  798,  799},
+    {  616,  617,  704,  706,  799,  800},
+    {  617,  705,  707,  800,  801,  802},
+    {  617,  618,  706,  708,  802,  803},
+    {  618,  619,  707,  709,  803,  804},
+    {  619,  620,  708,  710,  804,  805},
+    {  620,  621,  709,  711,  805,  806},
+    {  621,  622,  710,  712,  806,  807},
+    {  622,  623,  711,  713,  807,  808},
+    {  623,  624,  712,  714,  808,  809},
+    {  624,  625,  713,  715,  809,  810},
+    {  625,  626,  714,  716,  810,  811},
+    {  626,  627,  715,  717,  811,  812},
+    {  627,  628,  716,  718,  812,  813},
+    {  628,  629,  717,  719,  813,  814},
+    {  629,  630,  718,  720,  814,  815},
+    {  547,  630,  631,  719,  815,  816}, // 720
+    {  631,  722,  816,  817,  818,  918},
+    {  631,  632,  721,  723,  818,  819},
+    {  632,  633,  722,  724,  819,  820},
+    {  633,  634,  723,  725,  820,  821},
+    {  634,  635,  724,  726,  821,  822},
+    {  635,  636,  725,  727,  822,  823},
+    {  636,  637,  726,  728,  823,  824},
+    {  637,  638,  727,  729,  824,  825},
+    {  638,  639,  728,  730,  825,  826},
+    {  639,  640,  729,  731,  826,  827},
+    {  640,  641,  730,  732,  827,  828},
+    {  641,  642,  731,  733,  828,  829},
+    {  642,  643,  732,  734,  829,  830},
+    {  643,  644,  733,  735,  830,  831},
+    {  644,  645,  734,  736,  831,  832},
+    {  645,  646,  735,  737,  832,  833},
+    {  646,  736,  738,  833,  834,  835},
+    {  646,  647,  737,  739,  835,  836},
+    {  647,  648,  738,  740,  836,  837},
+    {  648,  649,  739,  741,  837,  838}, // 740
+    {  649,  650,  740,  742,  838,  839},
+    {  650,  651,  741,  743,  839,  840},
+    {  651,  652,  742,  744,  840,  841},
+    {  652,  653,  743,  745,  841,  842},
+    {  653,  654,  744,  746,  842,  843},
+    {  654,  655,  745,  747,  843,  844},
+    {  655,  656,  746,  748,  844,  845},
+    {  656,  657,  747,  749,  845,  846},
+    {  657,  658,  748,  750,  846,  847},
+    {  658,  659,  749,  751,  847,  848},
+    {  659,  660,  750,  752,  848,  849},
+    {  660,  661,  751,  753,  849,  850},
+    {  661,  752,  754,  850,  851,  852},
+    {  661,  662,  753,  755,  852,  853},
+    {  662,  663,  754,  756,  853,  854},
+    {  663,  664,  755,  757,  854,  855},
+    {  664,  665,  756,  758,  855,  856},
+    {  665,  666,  757,  759,  856,  857},
+    {  666,  667,  758,  760,  857,  858},
+    {  667,  668,  759,  761,  858,  859}, // 760
+    {  668,  669,  760,  762,  859,  860},
+    {  669,  670,  761,  763,  860,  861},
+    {  670,  671,  762,  764,  861,  862},
+    {  671,  672,  763,  765,  862,  863},
+    {  672,  673,  764,  766,  863,  864},
+    {  673,  674,  765,  767,  864,  865},
+    {  674,  675,  766,  768,  865,  866},
+    {  675,  676,  767,  769,  866,  867},
+    {  676,  768,  770,  867,  868,  869},
+    {  676,  677,  769,  771,  869,  870},
+    {  677,  678,  770,  772,  870,  871},
+    {  678,  679,  771,  773,  871,  872},
+    {  679,  680,  772,  774,  872,  873},
+    {  680,  681,  773,  775,  873,  874},
+    {  681,  682,  774,  776,  874,  875},
+    {  682,  683,  775,  777,  875,  876},
+    {  683,  684,  776,  778,  876,  877},
+    {  684,  685,  777,  779,  877,  878},
+    {  685,  686,  778,  780,  878,  879},
+    {  686,  687,  779,  781,  879,  880}, // 780
+    {  687,  688,  780,  782,  880,  881},
+    {  688,  689,  781,  783,  881,  882},
+    {  689,  690,  782,  784,  882,  883},
+    {  690,  691,  783,  785,  883,  884},
+    {  691,  784,  786,  884,  885,  886},
+    {  691,  692,  785,  787,  886,  887},
+    {  692,  693,  786,  788,  887,  888},
+    {  693,  694,  787,  789,  888,  889},
+    {  694,  695,  788,  790,  889,  890},
+    {  695,  696,  789,  791,  890,  891},
+    {  696,  697,  790,  792,  891,  892},
+    {  697,  698,  791,  793,  892,  893},
+    {  698,  699,  792,  794,  893,  894},
+    {  699,  700,  793,  795,  894,  895},
+    {  700,  701,  794,  796,  895,  896},
+    {  701,  702,  795,  797,  896,  897},
+    {  702,  703,  796,  798,  897,  898},
+    {  703,  704,  797,  799,  898,  899},
+    {  704,  705,  798,  800,  899,  900},
+    {  705,  706,  799,  801,  900,  901}, // 800
+    {  706,  800,  802,  901,  902,  903},
+    {  706,  707,  801,  803,  903,  904},
+    {  707,  708,  802,  804,  904,  905},
+    {  708,  709,  803,  805,  905,  906},
+    {  709,  710,  804,  806,  906,  907},
+    {  710,  711,  805,  807,  907,  908},
+    {  711,  712,  806,  808,  908,  909},
+    {  712,  713,  807,  809,  909,  910},
+    {  713,  714,  808,  810,  910,  911},
+    {  714,  715,  809,  811,  911,  912},
+    {  715,  716,  810,  812,  912,  913},
+    {  716,  717,  811,  813,  913,  914},
+    {  717,  718,  812,  814,  914,  915},
+    {  718,  719,  813,  815,  915,  916},
+    {  719,  720,  814,  816,  916,  917},
+    {  631,  720,  721,  815,  917,  918},
+    {  721,  818,  918,  919,  920,  1026},
+    {  721,  722,  817,  819,  920,  921},
+    {  722,  723,  818,  820,  921,  922},
+    {  723,  724,  819,  821,  922,  923}, // 820
+    {  724,  725,  820,  822,  923,  924},
+    {  725,  726,  821,  823,  924,  925},
+    {  726,  727,  822,  824,  925,  926},
+    {  727,  728,  823,  825,  926,  927},
+    {  728,  729,  824,  826,  927,  928},
+    {  729,  730,  825,  827,  928,  929},
+    {  730,  731,  826,  828,  929,  930},
+    {  731,  732,  827,  829,  930,  931},
+    {  732,  733,  828,  830,  931,  932},
+    {  733,  734,  829,  831,  932,  933},
+    {  734,  735,  830,  832,  933,  934},
+    {  735,  736,  831,  833,  934,  935},
+    {  736,  737,  832,  834,  935,  936},
+    {  737,  833,  835,  936,  937,  938},
+    {  737,  738,  834,  836,  938,  939},
+    {  738,  739,  835,  837,  939,  940},
+    {  739,  740,  836,  838,  940,  941},
+    {  740,  741,  837,  839,  941,  942},
+    {  741,  742,  838,  840,  942,  943},
+    {  742,  743,  839,  841,  943,  944}, // 840
+    {  743,  744,  840,  842,  944,  945},
+    {  744,  745,  841,  843,  945,  946},
+    {  745,  746,  842,  844,  946,  947},
+    {  746,  747,  843,  845,  947,  948},
+    {  747,  748,  844,  846,  948,  949},
+    {  748,  749,  845,  847,  949,  950},
+    {  749,  750,  846,  848,  950,  951},
+    {  750,  751,  847,  849,  951,  952},
+    {  751,  752,  848,  850,  952,  953},
+    {  752,  753,  849,  851,  953,  954},
+    {  753,  850,  852,  954,  955,  956},
+    {  753,  754,  851,  853,  956,  957},
+    {  754,  755,  852,  854,  957,  958},
+    {  755,  756,  853,  855,  958,  959},
+    {  756,  757,  854,  856,  959,  960},
+    {  757,  758,  855,  857,  960,  961},
+    {  758,  759,  856,  858,  961,  962},
+    {  759,  760,  857,  859,  962,  963},
+    {  760,  761,  858,  860,  963,  964},
+    {  761,  762,  859,  861,  964,  965}, // 860
+    {  762,  763,  860,  862,  965,  966},
+    {  763,  764,  861,  863,  966,  967},
+    {  764,  765,  862,  864,  967,  968},
+    {  765,  766,  863,  865,  968,  969},
+    {  766,  767,  864,  866,  969,  970},
+    {  767,  768,  865,  867,  970,  971},
+    {  768,  769,  866,  868,  971,  972},
+    {  769,  867,  869,  972,  973,  974},
+    {  769,  770,  868,  870,  974,  975},
+    {  770,  771,  869,  871,  975,  976},
+    {  771,  772,  870,  872,  976,  977},
+    {  772,  773,  871,  873,  977,  978},
+    {  773,  774,  872,  874,  978,  979},
+    {  774,  775,  873,  875,  979,  980},
+    {  775,  776,  874,  876,  980,  981},
+    {  776,  777,  875,  877,  981,  982},
+    {  777,  778,  876,  878,  982,  983},
+    {  778,  779,  877,  879,  983,  984},
+    {  779,  780,  878,  880,  984,  985},
+    {  780,  781,  879,  881,  985,  986}, // 880
+    {  781,  782,  880,  882,  986,  987},
+    {  782,  783,  881,  883,  987,  988},
+    {  783,  784,  882,  884,  988,  989},
+    {  784,  785,  883,  885,  989,  990},
+    {  785,  884,  886,  990,  991,  992},
+    {  785,  786,  885,  887,  992,  993},
+    {  786,  787,  886,  888,  993,  994},
+    {  787,  788,  887,  889,  994,  995},
+    {  788,  789,  888,  890,  995,  996},
+    {  789,  790,  889,  891,  996,  997},
+    {  790,  791,  890,  892,  997,  998},
+    {  791,  792,  891,  893,  998,  999},
+    {  792,  793,  892,  894,  999,  1000},
+    {  793,  794,  893,  895,  1000,  1001},
+    {  794,  795,  894,  896,  1001,  1002},
+    {  795,  796,  895,  897,  1002,  1003},
+    {  796,  797,  896,  898,  1003,  1004},
+    {  797,  798,  897,  899,  1004,  1005},
+    {  798,  799,  898,  900,  1005,  1006},
+    {  799,  800,  899,  901,  1006,  1007}, // 900
+    {  800,  801,  900,  902,  1007,  1008},
+    {  801,  901,  903,  1008,  1009,  1010},
+    {  801,  802,  902,  904,  1010,  1011},
+    {  802,  803,  903,  905,  1011,  1012},
+    {  803,  804,  904,  906,  1012,  1013},
+    {  804,  805,  905,  907,  1013,  1014},
+    {  805,  806,  906,  908,  1014,  1015},
+    {  806,  807,  907,  909,  1015,  1016},
+    {  807,  808,  908,  910,  1016,  1017},
+    {  808,  809,  909,  911,  1017,  1018},
+    {  809,  810,  910,  912,  1018,  1019},
+    {  810,  811,  911,  913,  1019,  1020},
+    {  811,  812,  912,  914,  1020,  1021},
+    {  812,  813,  913,  915,  1021,  1022},
+    {  813,  814,  914,  916,  1022,  1023},
+    {  814,  815,  915,  917,  1023,  1024},
+    {  815,  816,  916,  918,  1024,  1025},
+    {  721,  816,  817,  917,  1025,  1026},
+    {  817,  920,  1026,  1027,  1028,  1140},
+    {  817,  818,  919,  921,  1028,  1029}, // 920
+    {  818,  819,  920,  922,  1029,  1030},
+    {  819,  820,  921,  923,  1030,  1031},
+    {  820,  821,  922,  924,  1031,  1032},
+    {  821,  822,  923,  925,  1032,  1033},
+    {  822,  823,  924,  926,  1033,  1034},
+    {  823,  824,  925,  927,  1034,  1035},
+    {  824,  825,  926,  928,  1035,  1036},
+    {  825,  826,  927,  929,  1036,  1037},
+    {  826,  827,  928,  930,  1037,  1038},
+    {  827,  828,  929,  931,  1038,  1039},
+    {  828,  829,  930,  932,  1039,  1040},
+    {  829,  830,  931,  933,  1040,  1041},
+    {  830,  831,  932,  934,  1041,  1042},
+    {  831,  832,  933,  935,  1042,  1043},
+    {  832,  833,  934,  936,  1043,  1044},
+    {  833,  834,  935,  937,  1044,  1045},
+    {  834,  936,  938,  1045,  1046,  1047},
+    {  834,  835,  937,  939,  1047,  1048},
+    {  835,  836,  938,  940,  1048,  1049},
+    {  836,  837,  939,  941,  1049,  1050}, // 940
+    {  837,  838,  940,  942,  1050,  1051},
+    {  838,  839,  941,  943,  1051,  1052},
+    {  839,  840,  942,  944,  1052,  1053},
+    {  840,  841,  943,  945,  1053,  1054},
+    {  841,  842,  944,  946,  1054,  1055},
+    {  842,  843,  945,  947,  1055,  1056},
+    {  843,  844,  946,  948,  1056,  1057},
+    {  844,  845,  947,  949,  1057,  1058},
+    {  845,  846,  948,  950,  1058,  1059},
+    {  846,  847,  949,  951,  1059,  1060},
+    {  847,  848,  950,  952,  1060,  1061},
+    {  848,  849,  951,  953,  1061,  1062},
+    {  849,  850,  952,  954,  1062,  1063},
+    {  850,  851,  953,  955,  1063,  1064},
+    {  851,  954,  956,  1064,  1065,  1066},
+    {  851,  852,  955,  957,  1066,  1067},
+    {  852,  853,  956,  958,  1067,  1068},
+    {  853,  854,  957,  959,  1068,  1069},
+    {  854,  855,  958,  960,  1069,  1070},
+    {  855,  856,  959,  961,  1070,  1071}, // 960
+    {  856,  857,  960,  962,  1071,  1072},
+    {  857,  858,  961,  963,  1072,  1073},
+    {  858,  859,  962,  964,  1073,  1074},
+    {  859,  860,  963,  965,  1074,  1075},
+    {  860,  861,  964,  966,  1075,  1076},
+    {  861,  862,  965,  967,  1076,  1077},
+    {  862,  863,  966,  968,  1077,  1078},
+    {  863,  864,  967,  969,  1078,  1079},
+    {  864,  865,  968,  970,  1079,  1080},
+    {  865,  866,  969,  971,  1080,  1081},
+    {  866,  867,  970,  972,  1081,  1082},
+    {  867,  868,  971,  973,  1082,  1083},
+    {  868,  972,  974,  1083,  1084,  1085},
+    {  868,  869,  973,  975,  1085,  1086},
+    {  869,  870,  974,  976,  1086,  1087},
+    {  870,  871,  975,  977,  1087,  1088},
+    {  871,  872,  976,  978,  1088,  1089},
+    {  872,  873,  977,  979,  1089,  1090},
+    {  873,  874,  978,  980,  1090,  1091},
+    {  874,  875,  979,  981,  1091,  1092}, // 980
+    {  875,  876,  980,  982,  1092,  1093},
+    {  876,  877,  981,  983,  1093,  1094},
+    {  877,  878,  982,  984,  1094,  1095},
+    {  878,  879,  983,  985,  1095,  1096},
+    {  879,  880,  984,  986,  1096,  1097},
+    {  880,  881,  985,  987,  1097,  1098},
+    {  881,  882,  986,  988,  1098,  1099},
+    {  882,  883,  987,  989,  1099,  1100},
+    {  883,  884,  988,  990,  1100,  1101},
+    {  884,  885,  989,  991,  1101,  1102},
+    {  885,  990,  992,  1102,  1103,  1104},
+    {  885,  886,  991,  993,  1104,  1105},
+    {  886,  887,  992,  994,  1105,  1106},
+    {  887,  888,  993,  995,  1106,  1107},
+    {  888,  889,  994,  996,  1107,  1108},
+    {  889,  890,  995,  997,  1108,  1109},
+    {  890,  891,  996,  998,  1109,  1110},
+    {  891,  892,  997,  999,  1110,  1111},
+    {  892,  893,  998,  1000,  1111,  1112},
+    {  893,  894,  999,  1001,  1112,  1113}, // 1000
+    {  894,  895,  1000,  1002,  1113,  1114},
+    {  895,  896,  1001,  1003,  1114,  1115},
+    {  896,  897,  1002,  1004,  1115,  1116},
+    {  897,  898,  1003,  1005,  1116,  1117},
+    {  898,  899,  1004,  1006,  1117,  1118},
+    {  899,  900,  1005,  1007,  1118,  1119},
+    {  900,  901,  1006,  1008,  1119,  1120},
+    {  901,  902,  1007,  1009,  1120,  1121},
+    {  902,  1008,  1010,  1121,  1122,  1123},
+    {  902,  903,  1009,  1011,  1123,  1124},
+    {  903,  904,  1010,  1012,  1124,  1125},
+    {  904,  905,  1011,  1013,  1125,  1126},
+    {  905,  906,  1012,  1014,  1126,  1127},
+    {  906,  907,  1013,  1015,  1127,  1128},
+    {  907,  908,  1014,  1016,  1128,  1129},
+    {  908,  909,  1015,  1017,  1129,  1130},
+    {  909,  910,  1016,  1018,  1130,  1131},
+    {  910,  911,  1017,  1019,  1131,  1132},
+    {  911,  912,  1018,  1020,  1132,  1133},
+    {  912,  913,  1019,  1021,  1133,  1134}, // 1020
+    {  913,  914,  1020,  1022,  1134,  1135},
+    {  914,  915,  1021,  1023,  1135,  1136},
+    {  915,  916,  1022,  1024,  1136,  1137},
+    {  916,  917,  1023,  1025,  1137,  1138},
+    {  917,  918,  1024,  1026,  1138,  1139},
+    {  817,  918,  919,  1025,  1139,  1140},
+    {  919,  1028,  1140,  1141,  1142,  1260},
+    {  919,  920,  1027,  1029,  1142,  1143},
+    {  920,  921,  1028,  1030,  1143,  1144},
+    {  921,  922,  1029,  1031,  1144,  1145},
+    {  922,  923,  1030,  1032,  1145,  1146},
+    {  923,  924,  1031,  1033,  1146,  1147},
+    {  924,  925,  1032,  1034,  1147,  1148},
+    {  925,  926,  1033,  1035,  1148,  1149},
+    {  926,  927,  1034,  1036,  1149,  1150},
+    {  927,  928,  1035,  1037,  1150,  1151},
+    {  928,  929,  1036,  1038,  1151,  1152},
+    {  929,  930,  1037,  1039,  1152,  1153},
+    {  930,  931,  1038,  1040,  1153,  1154},
+    {  931,  932,  1039,  1041,  1154,  1155}, // 1040
+    {  932,  933,  1040,  1042,  1155,  1156},
+    {  933,  934,  1041,  1043,  1156,  1157},
+    {  934,  935,  1042,  1044,  1157,  1158},
+    {  935,  936,  1043,  1045,  1158,  1159},
+    {  936,  937,  1044,  1046,  1159,  1160},
+    {  937,  1045,  1047,  1160,  1161,  1162},
+    {  937,  938,  1046,  1048,  1162,  1163},
+    {  938,  939,  1047,  1049,  1163,  1164},
+    {  939,  940,  1048,  1050,  1164,  1165},
+    {  940,  941,  1049,  1051,  1165,  1166},
+    {  941,  942,  1050,  1052,  1166,  1167},
+    {  942,  943,  1051,  1053,  1167,  1168},
+    {  943,  944,  1052,  1054,  1168,  1169},
+    {  944,  945,  1053,  1055,  1169,  1170},
+    {  945,  946,  1054,  1056,  1170,  1171},
+    {  946,  947,  1055,  1057,  1171,  1172},
+    {  947,  948,  1056,  1058,  1172,  1173},
+    {  948,  949,  1057,  1059,  1173,  1174},
+    {  949,  950,  1058,  1060,  1174,  1175},
+    {  950,  951,  1059,  1061,  1175,  1176}, // 1060
+    {  951,  952,  1060,  1062,  1176,  1177},
+    {  952,  953,  1061,  1063,  1177,  1178},
+    {  953,  954,  1062,  1064,  1178,  1179},
+    {  954,  955,  1063,  1065,  1179,  1180},
+    {  955,  1064,  1066,  1180,  1181,  1182},
+    {  955,  956,  1065,  1067,  1182,  1183},
+    {  956,  957,  1066,  1068,  1183,  1184},
+    {  957,  958,  1067,  1069,  1184,  1185},
+    {  958,  959,  1068,  1070,  1185,  1186},
+    {  959,  960,  1069,  1071,  1186,  1187},
+    {  960,  961,  1070,  1072,  1187,  1188},
+    {  961,  962,  1071,  1073,  1188,  1189},
+    {  962,  963,  1072,  1074,  1189,  1190},
+    {  963,  964,  1073,  1075,  1190,  1191},
+    {  964,  965,  1074,  1076,  1191,  1192},
+    {  965,  966,  1075,  1077,  1192,  1193},
+    {  966,  967,  1076,  1078,  1193,  1194},
+    {  967,  968,  1077,  1079,  1194,  1195},
+    {  968,  969,  1078,  1080,  1195,  1196},
+    {  969,  970,  1079,  1081,  1196,  1197}, // 1080
+    {  970,  971,  1080,  1082,  1197,  1198},
+    {  971,  972,  1081,  1083,  1198,  1199},
+    {  972,  973,  1082,  1084,  1199,  1200},
+    {  973,  1083,  1085,  1200,  1201,  1202},
+    {  973,  974,  1084,  1086,  1202,  1203},
+    {  974,  975,  1085,  1087,  1203,  1204},
+    {  975,  976,  1086,  1088,  1204,  1205},
+    {  976,  977,  1087,  1089,  1205,  1206},
+    {  977,  978,  1088,  1090,  1206,  1207},
+    {  978,  979,  1089,  1091,  1207,  1208},
+    {  979,  980,  1090,  1092,  1208,  1209},
+    {  980,  981,  1091,  1093,  1209,  1210},
+    {  981,  982,  1092,  1094,  1210,  1211},
+    {  982,  983,  1093,  1095,  1211,  1212},
+    {  983,  984,  1094,  1096,  1212,  1213},
+    {  984,  985,  1095,  1097,  1213,  1214},
+    {  985,  986,  1096,  1098,  1214,  1215},
+    {  986,  987,  1097,  1099,  1215,  1216},
+    {  987,  988,  1098,  1100,  1216,  1217},
+    {  988,  989,  1099,  1101,  1217,  1218}, // 1100
+    {  989,  990,  1100,  1102,  1218,  1219},
+    {  990,  991,  1101,  1103,  1219,  1220},
+    {  991,  1102,  1104,  1220,  1221,  1222},
+    {  991,  992,  1103,  1105,  1222,  1223},
+    {  992,  993,  1104,  1106,  1223,  1224},
+    {  993,  994,  1105,  1107,  1224,  1225},
+    {  994,  995,  1106,  1108,  1225,  1226},
+    {  995,  996,  1107,  1109,  1226,  1227},
+    {  996,  997,  1108,  1110,  1227,  1228},
+    {  997,  998,  1109,  1111,  1228,  1229},
+    {  998,  999,  1110,  1112,  1229,  1230},
+    {  999,  1000,  1111,  1113,  1230,  1231},
+    {  1000,  1001,  1112,  1114,  1231,  1232},
+    {  1001,  1002,  1113,  1115,  1232,  1233},
+    {  1002,  1003,  1114,  1116,  1233,  1234},
+    {  1003,  1004,  1115,  1117,  1234,  1235},
+    {  1004,  1005,  1116,  1118,  1235,  1236},
+    {  1005,  1006,  1117,  1119,  1236,  1237},
+    {  1006,  1007,  1118,  1120,  1237,  1238},
+    {  1007,  1008,  1119,  1121,  1238,  1239}, // 1120
+    {  1008,  1009,  1120,  1122,  1239,  1240},
+    {  1009,  1121,  1123,  1240,  1241,  1242},
+    {  1009,  1010,  1122,  1124,  1242,  1243},
+    {  1010,  1011,  1123,  1125,  1243,  1244},
+    {  1011,  1012,  1124,  1126,  1244,  1245},
+    {  1012,  1013,  1125,  1127,  1245,  1246},
+    {  1013,  1014,  1126,  1128,  1246,  1247},
+    {  1014,  1015,  1127,  1129,  1247,  1248},
+    {  1015,  1016,  1128,  1130,  1248,  1249},
+    {  1016,  1017,  1129,  1131,  1249,  1250},
+    {  1017,  1018,  1130,  1132,  1250,  1251},
+    {  1018,  1019,  1131,  1133,  1251,  1252},
+    {  1019,  1020,  1132,  1134,  1252,  1253},
+    {  1020,  1021,  1133,  1135,  1253,  1254},
+    {  1021,  1022,  1134,  1136,  1254,  1255},
+    {  1022,  1023,  1135,  1137,  1255,  1256},
+    {  1023,  1024,  1136,  1138,  1256,  1257},
+    {  1024,  1025,  1137,  1139,  1257,  1258},
+    {  1025,  1026,  1138,  1140,  1258,  1259},
+    {  919,  1026,  1027,  1139,  1259,  1260}, // 1140
+    {  1027,  1142,  1260,  1261,  1262,  1386},
+    {  1027,  1028,  1141,  1143,  1262,  1263},
+    {  1028,  1029,  1142,  1144,  1263,  1264},
+    {  1029,  1030,  1143,  1145,  1264,  1265},
+    {  1030,  1031,  1144,  1146,  1265,  1266},
+    {  1031,  1032,  1145,  1147,  1266,  1267},
+    {  1032,  1033,  1146,  1148,  1267,  1268},
+    {  1033,  1034,  1147,  1149,  1268,  1269},
+    {  1034,  1035,  1148,  1150,  1269,  1270},
+    {  1035,  1036,  1149,  1151,  1270,  1271},
+    {  1036,  1037,  1150,  1152,  1271,  1272},
+    {  1037,  1038,  1151,  1153,  1272,  1273},
+    {  1038,  1039,  1152,  1154,  1273,  1274},
+    {  1039,  1040,  1153,  1155,  1274,  1275},
+    {  1040,  1041,  1154,  1156,  1275,  1276},
+    {  1041,  1042,  1155,  1157,  1276,  1277},
+    {  1042,  1043,  1156,  1158,  1277,  1278},
+    {  1043,  1044,  1157,  1159,  1278,  1279},
+    {  1044,  1045,  1158,  1160,  1279,  1280},
+    {  1045,  1046,  1159,  1161,  1280,  1281}, // 1160
+    {  1046,  1160,  1162,  1281,  1282,  1283},
+    {  1046,  1047,  1161,  1163,  1283,  1284},
+    {  1047,  1048,  1162,  1164,  1284,  1285},
+    {  1048,  1049,  1163,  1165,  1285,  1286},
+    {  1049,  1050,  1164,  1166,  1286,  1287},
+    {  1050,  1051,  1165,  1167,  1287,  1288},
+    {  1051,  1052,  1166,  1168,  1288,  1289},
+    {  1052,  1053,  1167,  1169,  1289,  1290},
+    {  1053,  1054,  1168,  1170,  1290,  1291},
+    {  1054,  1055,  1169,  1171,  1291,  1292},
+    {  1055,  1056,  1170,  1172,  1292,  1293},
+    {  1056,  1057,  1171,  1173,  1293,  1294},
+    {  1057,  1058,  1172,  1174,  1294,  1295},
+    {  1058,  1059,  1173,  1175,  1295,  1296},
+    {  1059,  1060,  1174,  1176,  1296,  1297},
+    {  1060,  1061,  1175,  1177,  1297,  1298},
+    {  1061,  1062,  1176,  1178,  1298,  1299},
+    {  1062,  1063,  1177,  1179,  1299,  1300},
+    {  1063,  1064,  1178,  1180,  1300,  1301},
+    {  1064,  1065,  1179,  1181,  1301,  1302}, // 1180
+    {  1065,  1180,  1182,  1302,  1303,  1304},
+    {  1065,  1066,  1181,  1183,  1304,  1305},
+    {  1066,  1067,  1182,  1184,  1305,  1306},
+    {  1067,  1068,  1183,  1185,  1306,  1307},
+    {  1068,  1069,  1184,  1186,  1307,  1308},
+    {  1069,  1070,  1185,  1187,  1308,  1309},
+    {  1070,  1071,  1186,  1188,  1309,  1310},
+    {  1071,  1072,  1187,  1189,  1310,  1311},
+    {  1072,  1073,  1188,  1190,  1311,  1312},
+    {  1073,  1074,  1189,  1191,  1312,  1313},
+    {  1074,  1075,  1190,  1192,  1313,  1314},
+    {  1075,  1076,  1191,  1193,  1314,  1315},
+    {  1076,  1077,  1192,  1194,  1315,  1316},
+    {  1077,  1078,  1193,  1195,  1316,  1317},
+    {  1078,  1079,  1194,  1196,  1317,  1318},
+    {  1079,  1080,  1195,  1197,  1318,  1319},
+    {  1080,  1081,  1196,  1198,  1319,  1320},
+    {  1081,  1082,  1197,  1199,  1320,  1321},
+    {  1082,  1083,  1198,  1200,  1321,  1322},
+    {  1083,  1084,  1199,  1201,  1322,  1323}, // 1200
+    {  1084,  1200,  1202,  1323,  1324,  1325},
+    {  1084,  1085,  1201,  1203,  1325,  1326},
+    {  1085,  1086,  1202,  1204,  1326,  1327},
+    {  1086,  1087,  1203,  1205,  1327,  1328},
+    {  1087,  1088,  1204,  1206,  1328,  1329},
+    {  1088,  1089,  1205,  1207,  1329,  1330},
+    {  1089,  1090,  1206,  1208,  1330,  1331},
+    {  1090,  1091,  1207,  1209,  1331,  1332},
+    {  1091,  1092,  1208,  1210,  1332,  1333},
+    {  1092,  1093,  1209,  1211,  1333,  1334},
+    {  1093,  1094,  1210,  1212,  1334,  1335},
+    {  1094,  1095,  1211,  1213,  1335,  1336},
+    {  1095,  1096,  1212,  1214,  1336,  1337},
+    {  1096,  1097,  1213,  1215,  1337,  1338},
+    {  1097,  1098,  1214,  1216,  1338,  1339},
+    {  1098,  1099,  1215,  1217,  1339,  1340},
+    {  1099,  1100,  1216,  1218,  1340,  1341},
+    {  1100,  1101,  1217,  1219,  1341,  1342},
+    {  1101,  1102,  1218,  1220,  1342,  1343},
+    {  1102,  1103,  1219,  1221,  1343,  1344}, // 1220
+    {  1103,  1220,  1222,  1344,  1345,  1346},
+    {  1103,  1104,  1221,  1223,  1346,  1347},
+    {  1104,  1105,  1222,  1224,  1347,  1348},
+    {  1105,  1106,  1223,  1225,  1348,  1349},
+    {  1106,  1107,  1224,  1226,  1349,  1350},
+    {  1107,  1108,  1225,  1227,  1350,  1351},
+    {  1108,  1109,  1226,  1228,  1351,  1352},
+    {  1109,  1110,  1227,  1229,  1352,  1353},
+    {  1110,  1111,  1228,  1230,  1353,  1354},
+    {  1111,  1112,  1229,  1231,  1354,  1355},
+    {  1112,  1113,  1230,  1232,  1355,  1356},
+    {  1113,  1114,  1231,  1233,  1356,  1357},
+    {  1114,  1115,  1232,  1234,  1357,  1358},
+    {  1115,  1116,  1233,  1235,  1358,  1359},
+    {  1116,  1117,  1234,  1236,  1359,  1360},
+    {  1117,  1118,  1235,  1237,  1360,  1361},
+    {  1118,  1119,  1236,  1238,  1361,  1362},
+    {  1119,  1120,  1237,  1239,  1362,  1363},
+    {  1120,  1121,  1238,  1240,  1363,  1364},
+    {  1121,  1122,  1239,  1241,  1364,  1365}, // 1240
+    {  1122,  1240,  1242,  1365,  1366,  1367},
+    {  1122,  1123,  1241,  1243,  1367,  1368},
+    {  1123,  1124,  1242,  1244,  1368,  1369},
+    {  1124,  1125,  1243,  1245,  1369,  1370},
+    {  1125,  1126,  1244,  1246,  1370,  1371},
+    {  1126,  1127,  1245,  1247,  1371,  1372},
+    {  1127,  1128,  1246,  1248,  1372,  1373},
+    {  1128,  1129,  1247,  1249,  1373,  1374},
+    {  1129,  1130,  1248,  1250,  1374,  1375},
+    {  1130,  1131,  1249,  1251,  1375,  1376},
+    {  1131,  1132,  1250,  1252,  1376,  1377},
+    {  1132,  1133,  1251,  1253,  1377,  1378},
+    {  1133,  1134,  1252,  1254,  1378,  1379},
+    {  1134,  1135,  1253,  1255,  1379,  1380},
+    {  1135,  1136,  1254,  1256,  1380,  1381},
+    {  1136,  1137,  1255,  1257,  1381,  1382},
+    {  1137,  1138,  1256,  1258,  1382,  1383},
+    {  1138,  1139,  1257,  1259,  1383,  1384},
+    {  1139,  1140,  1258,  1260,  1384,  1385},
+    {  1027,  1140,  1141,  1259,  1385,  1386}, // 1260
+    {  1141,  1262,  1386,  1387,  1388,  1518},
+    {  1141,  1142,  1261,  1263,  1388,  1389},
+    {  1142,  1143,  1262,  1264,  1389,  1390},
+    {  1143,  1144,  1263,  1265,  1390,  1391},
+    {  1144,  1145,  1264,  1266,  1391,  1392},
+    {  1145,  1146,  1265,  1267,  1392,  1393},
+    {  1146,  1147,  1266,  1268,  1393,  1394},
+    {  1147,  1148,  1267,  1269,  1394,  1395},
+    {  1148,  1149,  1268,  1270,  1395,  1396},
+    {  1149,  1150,  1269,  1271,  1396,  1397},
+    {  1150,  1151,  1270,  1272,  1397,  1398},
+    {  1151,  1152,  1271,  1273,  1398,  1399},
+    {  1152,  1153,  1272,  1274,  1399,  1400},
+    {  1153,  1154,  1273,  1275,  1400,  1401},
+    {  1154,  1155,  1274,  1276,  1401,  1402},
+    {  1155,  1156,  1275,  1277,  1402,  1403},
+    {  1156,  1157,  1276,  1278,  1403,  1404},
+    {  1157,  1158,  1277,  1279,  1404,  1405},
+    {  1158,  1159,  1278,  1280,  1405,  1406},
+    {  1159,  1160,  1279,  1281,  1406,  1407}, // 1280
+    {  1160,  1161,  1280,  1282,  1407,  1408},
+    {  1161,  1281,  1283,  1408,  1409,  1410},
+    {  1161,  1162,  1282,  1284,  1410,  1411},
+    {  1162,  1163,  1283,  1285,  1411,  1412},
+    {  1163,  1164,  1284,  1286,  1412,  1413},
+    {  1164,  1165,  1285,  1287,  1413,  1414},
+    {  1165,  1166,  1286,  1288,  1414,  1415},
+    {  1166,  1167,  1287,  1289,  1415,  1416},
+    {  1167,  1168,  1288,  1290,  1416,  1417},
+    {  1168,  1169,  1289,  1291,  1417,  1418},
+    {  1169,  1170,  1290,  1292,  1418,  1419},
+    {  1170,  1171,  1291,  1293,  1419,  1420},
+    {  1171,  1172,  1292,  1294,  1420,  1421},
+    {  1172,  1173,  1293,  1295,  1421,  1422},
+    {  1173,  1174,  1294,  1296,  1422,  1423},
+    {  1174,  1175,  1295,  1297,  1423,  1424},
+    {  1175,  1176,  1296,  1298,  1424,  1425},
+    {  1176,  1177,  1297,  1299,  1425,  1426},
+    {  1177,  1178,  1298,  1300,  1426,  1427},
+    {  1178,  1179,  1299,  1301,  1427,  1428}, // 1300
+    {  1179,  1180,  1300,  1302,  1428,  1429},
+    {  1180,  1181,  1301,  1303,  1429,  1430},
+    {  1181,  1302,  1304,  1430,  1431,  1432},
+    {  1181,  1182,  1303,  1305,  1432,  1433},
+    {  1182,  1183,  1304,  1306,  1433,  1434},
+    {  1183,  1184,  1305,  1307,  1434,  1435},
+    {  1184,  1185,  1306,  1308,  1435,  1436},
+    {  1185,  1186,  1307,  1309,  1436,  1437},
+    {  1186,  1187,  1308,  1310,  1437,  1438},
+    {  1187,  1188,  1309,  1311,  1438,  1439},
+    {  1188,  1189,  1310,  1312,  1439,  1440},
+    {  1189,  1190,  1311,  1313,  1440,  1441},
+    {  1190,  1191,  1312,  1314,  1441,  1442},
+    {  1191,  1192,  1313,  1315,  1442,  1443},
+    {  1192,  1193,  1314,  1316,  1443,  1444},
+    {  1193,  1194,  1315,  1317,  1444,  1445},
+    {  1194,  1195,  1316,  1318,  1445,  1446},
+    {  1195,  1196,  1317,  1319,  1446,  1447},
+    {  1196,  1197,  1318,  1320,  1447,  1448},
+    {  1197,  1198,  1319,  1321,  1448,  1449}, // 1320
+    {  1198,  1199,  1320,  1322,  1449,  1450},
+    {  1199,  1200,  1321,  1323,  1450,  1451},
+    {  1200,  1201,  1322,  1324,  1451,  1452},
+    {  1201,  1323,  1325,  1452,  1453,  1454},
+    {  1201,  1202,  1324,  1326,  1454,  1455},
+    {  1202,  1203,  1325,  1327,  1455,  1456},
+    {  1203,  1204,  1326,  1328,  1456,  1457},
+    {  1204,  1205,  1327,  1329,  1457,  1458},
+    {  1205,  1206,  1328,  1330,  1458,  1459},
+    {  1206,  1207,  1329,  1331,  1459,  1460},
+    {  1207,  1208,  1330,  1332,  1460,  1461},
+    {  1208,  1209,  1331,  1333,  1461,  1462},
+    {  1209,  1210,  1332,  1334,  1462,  1463},
+    {  1210,  1211,  1333,  1335,  1463,  1464},
+    {  1211,  1212,  1334,  1336,  1464,  1465},
+    {  1212,  1213,  1335,  1337,  1465,  1466},
+    {  1213,  1214,  1336,  1338,  1466,  1467},
+    {  1214,  1215,  1337,  1339,  1467,  1468},
+    {  1215,  1216,  1338,  1340,  1468,  1469},
+    {  1216,  1217,  1339,  1341,  1469,  1470}, // 1340
+    {  1217,  1218,  1340,  1342,  1470,  1471},
+    {  1218,  1219,  1341,  1343,  1471,  1472},
+    {  1219,  1220,  1342,  1344,  1472,  1473},
+    {  1220,  1221,  1343,  1345,  1473,  1474},
+    {  1221,  1344,  1346,  1474,  1475,  1476},
+    {  1221,  1222,  1345,  1347,  1476,  1477},
+    {  1222,  1223,  1346,  1348,  1477,  1478},
+    {  1223,  1224,  1347,  1349,  1478,  1479},
+    {  1224,  1225,  1348,  1350,  1479,  1480},
+    {  1225,  1226,  1349,  1351,  1480,  1481},
+    {  1226,  1227,  1350,  1352,  1481,  1482},
+    {  1227,  1228,  1351,  1353,  1482,  1483},
+    {  1228,  1229,  1352,  1354,  1483,  1484},
+    {  1229,  1230,  1353,  1355,  1484,  1485},
+    {  1230,  1231,  1354,  1356,  1485,  1486},
+    {  1231,  1232,  1355,  1357,  1486,  1487},
+    {  1232,  1233,  1356,  1358,  1487,  1488},
+    {  1233,  1234,  1357,  1359,  1488,  1489},
+    {  1234,  1235,  1358,  1360,  1489,  1490},
+    {  1235,  1236,  1359,  1361,  1490,  1491}, // 1360
+    {  1236,  1237,  1360,  1362,  1491,  1492},
+    {  1237,  1238,  1361,  1363,  1492,  1493},
+    {  1238,  1239,  1362,  1364,  1493,  1494},
+    {  1239,  1240,  1363,  1365,  1494,  1495},
+    {  1240,  1241,  1364,  1366,  1495,  1496},
+    {  1241,  1365,  1367,  1496,  1497,  1498},
+    {  1241,  1242,  1366,  1368,  1498,  1499},
+    {  1242,  1243,  1367,  1369,  1499,  1500},
+    {  1243,  1244,  1368,  1370,  1500,  1501},
+    {  1244,  1245,  1369,  1371,  1501,  1502},
+    {  1245,  1246,  1370,  1372,  1502,  1503},
+    {  1246,  1247,  1371,  1373,  1503,  1504},
+    {  1247,  1248,  1372,  1374,  1504,  1505},
+    {  1248,  1249,  1373,  1375,  1505,  1506},
+    {  1249,  1250,  1374,  1376,  1506,  1507},
+    {  1250,  1251,  1375,  1377,  1507,  1508},
+    {  1251,  1252,  1376,  1378,  1508,  1509},
+    {  1252,  1253,  1377,  1379,  1509,  1510},
+    {  1253,  1254,  1378,  1380,  1510,  1511},
+    {  1254,  1255,  1379,  1381,  1511,  1512}, // 1380
+    {  1255,  1256,  1380,  1382,  1512,  1513},
+    {  1256,  1257,  1381,  1383,  1513,  1514},
+    {  1257,  1258,  1382,  1384,  1514,  1515},
+    {  1258,  1259,  1383,  1385,  1515,  1516},
+    {  1259,  1260,  1384,  1386,  1516,  1517},
+    {  1141,  1260,  1261,  1385,  1517,  1518},
+    {  1261,  1388,  1518,  1519,  1520,  1656},
+    {  1261,  1262,  1387,  1389,  1520,  1521},
+    {  1262,  1263,  1388,  1390,  1521,  1522},
+    {  1263,  1264,  1389,  1391,  1522,  1523},
+    {  1264,  1265,  1390,  1392,  1523,  1524},
+    {  1265,  1266,  1391,  1393,  1524,  1525},
+    {  1266,  1267,  1392,  1394,  1525,  1526},
+    {  1267,  1268,  1393,  1395,  1526,  1527},
+    {  1268,  1269,  1394,  1396,  1527,  1528},
+    {  1269,  1270,  1395,  1397,  1528,  1529},
+    {  1270,  1271,  1396,  1398,  1529,  1530},
+    {  1271,  1272,  1397,  1399,  1530,  1531},
+    {  1272,  1273,  1398,  1400,  1531,  1532},
+    {  1273,  1274,  1399,  1401,  1532,  1533}, // 1400
+    {  1274,  1275,  1400,  1402,  1533,  1534},
+    {  1275,  1276,  1401,  1403,  1534,  1535},
+    {  1276,  1277,  1402,  1404,  1535,  1536},
+    {  1277,  1278,  1403,  1405,  1536,  1537},
+    {  1278,  1279,  1404,  1406,  1537,  1538},
+    {  1279,  1280,  1405,  1407,  1538,  1539},
+    {  1280,  1281,  1406,  1408,  1539,  1540},
+    {  1281,  1282,  1407,  1409,  1540,  1541},
+    {  1282,  1408,  1410,  1541,  1542,  1543},
+    {  1282,  1283,  1409,  1411,  1543,  1544},
+    {  1283,  1284,  1410,  1412,  1544,  1545},
+    {  1284,  1285,  1411,  1413,  1545,  1546},
+    {  1285,  1286,  1412,  1414,  1546,  1547},
+    {  1286,  1287,  1413,  1415,  1547,  1548},
+    {  1287,  1288,  1414,  1416,  1548,  1549},
+    {  1288,  1289,  1415,  1417,  1549,  1550},
+    {  1289,  1290,  1416,  1418,  1550,  1551},
+    {  1290,  1291,  1417,  1419,  1551,  1552},
+    {  1291,  1292,  1418,  1420,  1552,  1553},
+    {  1292,  1293,  1419,  1421,  1553,  1554}, // 1420
+    {  1293,  1294,  1420,  1422,  1554,  1555},
+    {  1294,  1295,  1421,  1423,  1555,  1556},
+    {  1295,  1296,  1422,  1424,  1556,  1557},
+    {  1296,  1297,  1423,  1425,  1557,  1558},
+    {  1297,  1298,  1424,  1426,  1558,  1559},
+    {  1298,  1299,  1425,  1427,  1559,  1560},
+    {  1299,  1300,  1426,  1428,  1560,  1561},
+    {  1300,  1301,  1427,  1429,  1561,  1562},
+    {  1301,  1302,  1428,  1430,  1562,  1563},
+    {  1302,  1303,  1429,  1431,  1563,  1564},
+    {  1303,  1430,  1432,  1564,  1565,  1566},
+    {  1303,  1304,  1431,  1433,  1566,  1567},
+    {  1304,  1305,  1432,  1434,  1567,  1568},
+    {  1305,  1306,  1433,  1435,  1568,  1569},
+    {  1306,  1307,  1434,  1436,  1569,  1570},
+    {  1307,  1308,  1435,  1437,  1570,  1571},
+    {  1308,  1309,  1436,  1438,  1571,  1572},
+    {  1309,  1310,  1437,  1439,  1572,  1573},
+    {  1310,  1311,  1438,  1440,  1573,  1574},
+    {  1311,  1312,  1439,  1441,  1574,  1575}, // 1440
+    {  1312,  1313,  1440,  1442,  1575,  1576},
+    {  1313,  1314,  1441,  1443,  1576,  1577},
+    {  1314,  1315,  1442,  1444,  1577,  1578},
+    {  1315,  1316,  1443,  1445,  1578,  1579},
+    {  1316,  1317,  1444,  1446,  1579,  1580},
+    {  1317,  1318,  1445,  1447,  1580,  1581},
+    {  1318,  1319,  1446,  1448,  1581,  1582},
+    {  1319,  1320,  1447,  1449,  1582,  1583},
+    {  1320,  1321,  1448,  1450,  1583,  1584},
+    {  1321,  1322,  1449,  1451,  1584,  1585},
+    {  1322,  1323,  1450,  1452,  1585,  1586},
+    {  1323,  1324,  1451,  1453,  1586,  1587},
+    {  1324,  1452,  1454,  1587,  1588,  1589},
+    {  1324,  1325,  1453,  1455,  1589,  1590},
+    {  1325,  1326,  1454,  1456,  1590,  1591},
+    {  1326,  1327,  1455,  1457,  1591,  1592},
+    {  1327,  1328,  1456,  1458,  1592,  1593},
+    {  1328,  1329,  1457,  1459,  1593,  1594},
+    {  1329,  1330,  1458,  1460,  1594,  1595},
+    {  1330,  1331,  1459,  1461,  1595,  1596}, // 1460
+    {  1331,  1332,  1460,  1462,  1596,  1597},
+    {  1332,  1333,  1461,  1463,  1597,  1598},
+    {  1333,  1334,  1462,  1464,  1598,  1599},
+    {  1334,  1335,  1463,  1465,  1599,  1600},
+    {  1335,  1336,  1464,  1466,  1600,  1601},
+    {  1336,  1337,  1465,  1467,  1601,  1602},
+    {  1337,  1338,  1466,  1468,  1602,  1603},
+    {  1338,  1339,  1467,  1469,  1603,  1604},
+    {  1339,  1340,  1468,  1470,  1604,  1605},
+    {  1340,  1341,  1469,  1471,  1605,  1606},
+    {  1341,  1342,  1470,  1472,  1606,  1607},
+    {  1342,  1343,  1471,  1473,  1607,  1608},
+    {  1343,  1344,  1472,  1474,  1608,  1609},
+    {  1344,  1345,  1473,  1475,  1609,  1610},
+    {  1345,  1474,  1476,  1610,  1611,  1612},
+    {  1345,  1346,  1475,  1477,  1612,  1613},
+    {  1346,  1347,  1476,  1478,  1613,  1614},
+    {  1347,  1348,  1477,  1479,  1614,  1615},
+    {  1348,  1349,  1478,  1480,  1615,  1616},
+    {  1349,  1350,  1479,  1481,  1616,  1617}, // 1480
+    {  1350,  1351,  1480,  1482,  1617,  1618},
+    {  1351,  1352,  1481,  1483,  1618,  1619},
+    {  1352,  1353,  1482,  1484,  1619,  1620},
+    {  1353,  1354,  1483,  1485,  1620,  1621},
+    {  1354,  1355,  1484,  1486,  1621,  1622},
+    {  1355,  1356,  1485,  1487,  1622,  1623},
+    {  1356,  1357,  1486,  1488,  1623,  1624},
+    {  1357,  1358,  1487,  1489,  1624,  1625},
+    {  1358,  1359,  1488,  1490,  1625,  1626},
+    {  1359,  1360,  1489,  1491,  1626,  1627},
+    {  1360,  1361,  1490,  1492,  1627,  1628},
+    {  1361,  1362,  1491,  1493,  1628,  1629},
+    {  1362,  1363,  1492,  1494,  1629,  1630},
+    {  1363,  1364,  1493,  1495,  1630,  1631},
+    {  1364,  1365,  1494,  1496,  1631,  1632},
+    {  1365,  1366,  1495,  1497,  1632,  1633},
+    {  1366,  1496,  1498,  1633,  1634,  1635},
+    {  1366,  1367,  1497,  1499,  1635,  1636},
+    {  1367,  1368,  1498,  1500,  1636,  1637},
+    {  1368,  1369,  1499,  1501,  1637,  1638}, // 1500
+    {  1369,  1370,  1500,  1502,  1638,  1639},
+    {  1370,  1371,  1501,  1503,  1639,  1640},
+    {  1371,  1372,  1502,  1504,  1640,  1641},
+    {  1372,  1373,  1503,  1505,  1641,  1642},
+    {  1373,  1374,  1504,  1506,  1642,  1643},
+    {  1374,  1375,  1505,  1507,  1643,  1644},
+    {  1375,  1376,  1506,  1508,  1644,  1645},
+    {  1376,  1377,  1507,  1509,  1645,  1646},
+    {  1377,  1378,  1508,  1510,  1646,  1647},
+    {  1378,  1379,  1509,  1511,  1647,  1648},
+    {  1379,  1380,  1510,  1512,  1648,  1649},
+    {  1380,  1381,  1511,  1513,  1649,  1650},
+    {  1381,  1382,  1512,  1514,  1650,  1651},
+    {  1382,  1383,  1513,  1515,  1651,  1652},
+    {  1383,  1384,  1514,  1516,  1652,  1653},
+    {  1384,  1385,  1515,  1517,  1653,  1654},
+    {  1385,  1386,  1516,  1518,  1654,  1655},
+    {  1261,  1386,  1387,  1517,  1655,  1656},
+    {  1387,  1520,  1656,  -1,  -1,  -1},
+    {  1387,  1388,  1519,  1521,  1657,  -1}, // 1520
+    {  1388,  1389,  1520,  1522,  -1,  -1},
+    {  1389,  1390,  1521,  1523,  1658,  -1},
+    {  1390,  1391,  1522,  1524,  -1,  -1},
+    {  1391,  1392,  1523,  1525,  1659,  -1},
+    {  1392,  1393,  1524,  1526,  -1,  -1},
+    {  1393,  1394,  1525,  1527,  1660,  -1},
+    {  1394,  1395,  1526,  1528,  -1,  -1},
+    {  1395,  1396,  1527,  1529,  1661,  -1},
+    {  1396,  1397,  1528,  1530,  -1,  -1},
+    {  1397,  1398,  1529,  1531,  1662,  -1},
+    {  1398,  1399,  1530,  1532,  -1,  -1},
+    {  1399,  1400,  1531,  1533,  1663,  -1},
+    {  1400,  1401,  1532,  1534,  -1,  -1},
+    {  1401,  1402,  1533,  1535,  1664,  -1},
+    {  1402,  1403,  1534,  1536,  -1,  -1},
+    {  1403,  1404,  1535,  1537,  1665,  -1},
+    {  1404,  1405,  1536,  1538,  -1,  -1},
+    {  1405,  1406,  1537,  1539,  1666,  -1},
+    {  1406,  1407,  1538,  1540,  -1,  -1},
+    {  1407,  1408,  1539,  1541,  1667,  -1}, // 1540
+    {  1408,  1409,  1540,  1542,  -1,  -1},
+    {  1409,  1541,  1543,  1668,  -1,  -1},
+    {  1409,  1410,  1542,  1544,  -1,  -1},
+    {  1410,  1411,  1543,  1545,  -1,  -1},
+    {  1411,  1412,  1544,  1546,  -1,  -1},
+    {  1412,  1413,  1545,  1547,  -1,  -1},
+    {  1413,  1414,  1546,  1548,  -1,  -1},
+    {  1414,  1415,  1547,  1549,  -1,  -1},
+    {  1415,  1416,  1548,  1550,  -1,  -1},
+    {  1416,  1417,  1549,  1551,  -1,  -1},
+    {  1417,  1418,  1550,  1552,  -1,  -1},
+    {  1418,  1419,  1551,  1553,  -1,  -1},
+    {  1419,  1420,  1552,  1554,  -1,  -1},
+    {  1420,  1421,  1553,  1555,  -1,  -1},
+    {  1421,  1422,  1554,  1556,  -1,  -1},
+    {  1422,  1423,  1555,  1557,  -1,  -1},
+    {  1423,  1424,  1556,  1558,  -1,  -1},
+    {  1424,  1425,  1557,  1559,  -1,  -1},
+    {  1425,  1426,  1558,  1560,  -1,  -1},
+    {  1426,  1427,  1559,  1561,  -1,  -1}, // 1560
+    {  1427,  1428,  1560,  1562,  -1,  -1},
+    {  1428,  1429,  1561,  1563,  -1,  -1},
+    {  1429,  1430,  1562,  1564,  -1,  -1},
+    {  1430,  1431,  1563,  1565,  -1,  -1},
+    {  1431,  1564,  1566,  -1,  -1,  -1},
+    {  1431,  1432,  1565,  1567,  -1,  -1},
+    {  1432,  1433,  1566,  1568,  -1,  -1},
+    {  1433,  1434,  1567,  1569,  -1,  -1},
+    {  1434,  1435,  1568,  1570,  -1,  -1},
+    {  1435,  1436,  1569,  1571,  -1,  -1},
+    {  1436,  1437,  1570,  1572,  -1,  -1},
+    {  1437,  1438,  1571,  1573,  -1,  -1},
+    {  1438,  1439,  1572,  1574,  -1,  -1},
+    {  1439,  1440,  1573,  1575,  -1,  -1},
+    {  1440,  1441,  1574,  1576,  -1,  -1},
+    {  1441,  1442,  1575,  1577,  -1,  -1},
+    {  1442,  1443,  1576,  1578,  -1,  -1},
+    {  1443,  1444,  1577,  1579,  -1,  -1},
+    {  1444,  1445,  1578,  1580,  -1,  -1},
+    {  1445,  1446,  1579,  1581,  -1,  -1}, // 1580
+    {  1446,  1447,  1580,  1582,  -1,  -1},
+    {  1447,  1448,  1581,  1583,  -1,  -1},
+    {  1448,  1449,  1582,  1584,  -1,  -1},
+    {  1449,  1450,  1583,  1585,  -1,  -1},
+    {  1450,  1451,  1584,  1586,  -1,  -1},
+    {  1451,  1452,  1585,  1587,  -1,  -1},
+    {  1452,  1453,  1586,  1588,  -1,  -1},
+    {  1453,  1587,  1589,  -1,  -1,  -1},
+    {  1453,  1454,  1588,  1590,  -1,  -1},
+    {  1454,  1455,  1589,  1591,  -1,  -1},
+    {  1455,  1456,  1590,  1592,  -1,  -1},
+    {  1456,  1457,  1591,  1593,  -1,  -1},
+    {  1457,  1458,  1592,  1594,  -1,  -1},
+    {  1458,  1459,  1593,  1595,  -1,  -1},
+    {  1459,  1460,  1594,  1596,  -1,  -1},
+    {  1460,  1461,  1595,  1597,  -1,  -1},
+    {  1461,  1462,  1596,  1598,  -1,  -1},
+    {  1462,  1463,  1597,  1599,  -1,  -1},
+    {  1463,  1464,  1598,  1600,  -1,  -1},
+    {  1464,  1465,  1599,  1601,  -1,  -1}, // 1600
+    {  1465,  1466,  1600,  1602,  -1,  -1},
+    {  1466,  1467,  1601,  1603,  -1,  -1},
+    {  1467,  1468,  1602,  1604,  -1,  -1},
+    {  1468,  1469,  1603,  1605,  -1,  -1},
+    {  1469,  1470,  1604,  1606,  -1,  -1},
+    {  1470,  1471,  1605,  1607,  -1,  -1},
+    {  1471,  1472,  1606,  1608,  -1,  -1},
+    {  1472,  1473,  1607,  1609,  -1,  -1},
+    {  1473,  1474,  1608,  1610,  -1,  -1},
+    {  1474,  1475,  1609,  1611,  -1,  -1},
+    {  1475,  1610,  1612,  -1,  -1,  -1},
+    {  1475,  1476,  1611,  1613,  -1,  -1},
+    {  1476,  1477,  1612,  1614,  -1,  -1},
+    {  1477,  1478,  1613,  1615,  -1,  -1},
+    {  1478,  1479,  1614,  1616,  -1,  -1},
+    {  1479,  1480,  1615,  1617,  -1,  -1},
+    {  1480,  1481,  1616,  1618,  -1,  -1},
+    {  1481,  1482,  1617,  1619,  -1,  -1},
+    {  1482,  1483,  1618,  1620,  -1,  -1},
+    {  1483,  1484,  1619,  1621,  -1,  -1}, // 1620
+    {  1484,  1485,  1620,  1622,  -1,  -1},
+    {  1485,  1486,  1621,  1623,  -1,  -1},
+    {  1486,  1487,  1622,  1624,  -1,  -1},
+    {  1487,  1488,  1623,  1625,  -1,  -1},
+    {  1488,  1489,  1624,  1626,  -1,  -1},
+    {  1489,  1490,  1625,  1627,  -1,  -1},
+    {  1490,  1491,  1626,  1628,  -1,  -1},
+    {  1491,  1492,  1627,  1629,  -1,  -1},
+    {  1492,  1493,  1628,  1630,  -1,  -1},
+    {  1493,  1494,  1629,  1631,  -1,  -1},
+    {  1494,  1495,  1630,  1632,  -1,  -1},
+    {  1495,  1496,  1631,  1633,  -1,  -1},
+    {  1496,  1497,  1632,  1634,  -1,  -1},
+    {  1497,  1633,  1635,  1717,  -1,  -1},
+    {  1497,  1498,  1634,  1636,  -1,  -1},
+    {  1498,  1499,  1635,  1637,  1718,  -1},
+    {  1499,  1500,  1636,  1638,  -1,  -1},
+    {  1500,  1501,  1637,  1639,  1719,  -1},
+    {  1501,  1502,  1638,  1640,  -1,  -1},
+    {  1502,  1503,  1639,  1641,  1720,  -1}, // 1640
+    {  1503,  1504,  1640,  1642,  -1,  -1},
+    {  1504,  1505,  1641,  1643,  1721,  -1},
+    {  1505,  1506,  1642,  1644,  -1,  -1},
+    {  1506,  1507,  1643,  1645,  1722,  -1},
+    {  1507,  1508,  1644,  1646,  -1,  -1},
+    {  1508,  1509,  1645,  1647,  1723,  -1},
+    {  1509,  1510,  1646,  1648,  -1,  -1},
+    {  1510,  1511,  1647,  1649,  1724,  -1},
+    {  1511,  1512,  1648,  1650,  -1,  -1},
+    {  1512,  1513,  1649,  1651,  1725,  -1},
+    {  1513,  1514,  1650,  1652,  -1,  -1},
+    {  1514,  1515,  1651,  1653,  1726,  -1},
+    {  1515,  1516,  1652,  1654,  -1,  -1},
+    {  1516,  1517,  1653,  1655,  1727,  -1},
+    {  1517,  1518,  1654,  1656,  -1,  -1},
+    {  1387,  1518,  1519,  1655,  1728,  -1},
+    {  1658,  1729,  1730,  -1,  -1,  -1},
+    {  1657,  1659,  1730,  1731,  -1,  -1},
+    {  1658,  1660,  1731,  1732,  -1,  -1},
+    {  1659,  1661,  1732,  1733,  -1,  -1}, // 1660
+    {  1660,  1662,  1733,  1734,  -1,  -1},
+    {  1661,  1663,  1734,  1735,  -1,  -1},
+    {  1662,  1664,  1735,  1736,  -1,  -1},
+    {  1663,  1665,  1736,  1737,  -1,  -1},
+    {  1664,  1666,  1737,  1738,  -1,  -1},
+    {  1665,  1667,  1738,  1739,  -1,  -1},
+    {  1666,  1668,  1739,  1740,  -1,  -1},
+    {  1667,  1740,  1741,  -1,  -1,  -1},
+    {  1670,  1742,  1743,  -1,  -1,  -1},
+    {  1669,  1671,  1743,  1744,  -1,  -1},
+    {  1670,  1672,  1744,  1745,  -1,  -1},
+    {  1671,  1673,  1745,  1746,  -1,  -1},
+    {  1672,  1674,  1746,  1747,  -1,  -1},
+    {  1673,  1675,  1747,  1748,  -1,  -1},
+    {  1674,  1676,  1748,  1749,  -1,  -1},
+    {  1675,  1677,  1749,  1750,  -1,  -1},
+    {  1676,  1678,  1750,  1751,  -1,  -1},
+    {  1677,  1679,  1751,  1752,  -1,  -1},
+    {  1678,  1680,  1752,  1753,  -1,  -1},
+    {  1679,  1753,  1754,  -1,  -1,  -1}, // 1680
+    {  1682,  1755,  1756,  -1,  -1,  -1},
+    {  1681,  1683,  1756,  1757,  -1,  -1},
+    {  1682,  1684,  1757,  1758,  -1,  -1},
+    {  1683,  1685,  1758,  1759,  -1,  -1},
+    {  1684,  1686,  1759,  1760,  -1,  -1},
+    {  1685,  1687,  1760,  1761,  -1,  -1},
+    {  1686,  1688,  1761,  1762,  -1,  -1},
+    {  1687,  1689,  1762,  1763,  -1,  -1},
+    {  1688,  1690,  1763,  1764,  -1,  -1},
+    {  1689,  1691,  1764,  1765,  -1,  -1},
+    {  1690,  1692,  1765,  1766,  -1,  -1},
+    {  1691,  1766,  1767,  -1,  -1,  -1},
+    {  1694,  1768,  1769,  -1,  -1,  -1},
+    {  1693,  1695,  1769,  1770,  -1,  -1},
+    {  1694,  1696,  1770,  1771,  -1,  -1},
+    {  1695,  1697,  1771,  1772,  -1,  -1},
+    {  1696,  1698,  1772,  1773,  -1,  -1},
+    {  1697,  1699,  1773,  1774,  -1,  -1},
+    {  1698,  1700,  1774,  1775,  -1,  -1},
+    {  1699,  1701,  1775,  1776,  -1,  -1}, // 1700
+    {  1700,  1702,  1776,  1777,  -1,  -1},
+    {  1701,  1703,  1777,  1778,  -1,  -1},
+    {  1702,  1704,  1778,  1779,  -1,  -1},
+    {  1703,  1779,  1780,  -1,  -1,  -1},
+    {  1706,  1781,  1782,  -1,  -1,  -1},
+    {  1705,  1707,  1782,  1783,  -1,  -1},
+    {  1706,  1708,  1783,  1784,  -1,  -1},
+    {  1707,  1709,  1784,  1785,  -1,  -1},
+    {  1708,  1710,  1785,  1786,  -1,  -1},
+    {  1709,  1711,  1786,  1787,  -1,  -1},
+    {  1710,  1712,  1787,  1788,  -1,  -1},
+    {  1711,  1713,  1788,  1789,  -1,  -1},
+    {  1712,  1714,  1789,  1790,  -1,  -1},
+    {  1713,  1715,  1790,  1791,  -1,  -1},
+    {  1714,  1716,  1791,  1792,  -1,  -1},
+    {  1715,  1792,  1793,  -1,  -1,  -1},
+    {  1718,  1794,  1795,  -1,  -1,  -1},
+    {  1717,  1719,  1795,  1796,  -1,  -1},
+    {  1718,  1720,  1796,  1797,  -1,  -1},
+    {  1719,  1721,  1797,  1798,  -1,  -1}, // 1720
+    {  1720,  1722,  1798,  1799,  -1,  -1},
+    {  1721,  1723,  1799,  1800,  -1,  -1},
+    {  1722,  1724,  1800,  1801,  -1,  -1},
+    {  1723,  1725,  1801,  1802,  -1,  -1},
+    {  1724,  1726,  1802,  1803,  -1,  -1},
+    {  1725,  1727,  1803,  1804,  -1,  -1},
+    {  1726,  1728,  1804,  1805,  -1,  -1},
+    {  1727,  1805,  1806,  -1,  -1,  -1},
+    {  1657,  1730,  1807,  1808,  -1,  -1},
+    {  1657,  1658,  1729,  1731,  1808,  1809},
+    {  1658,  1659,  1730,  1732,  1809,  1810},
+    {  1659,  1660,  1731,  1733,  1810,  1811},
+    {  1660,  1661,  1732,  1734,  1811,  1812},
+    {  1661,  1662,  1733,  1735,  1812,  1813},
+    {  1662,  1663,  1734,  1736,  1813,  1814},
+    {  1663,  1664,  1735,  1737,  1814,  1815},
+    {  1664,  1665,  1736,  1738,  1815,  1816},
+    {  1665,  1666,  1737,  1739,  1816,  1817},
+    {  1666,  1667,  1738,  1740,  1817,  1818},
+    {  1667,  1668,  1739,  1741,  1818,  1819}, // 1740
+    {  1668,  1740,  1819,  1820,  -1,  -1},
+    {  1669,  1743,  1821,  1822,  -1,  -1},
+    {  1669,  1670,  1742,  1744,  1822,  1823},
+    {  1670,  1671,  1743,  1745,  1823,  1824},
+    {  1671,  1672,  1744,  1746,  1824,  1825},
+    {  1672,  1673,  1745,  1747,  1825,  1826},
+    {  1673,  1674,  1746,  1748,  1826,  1827},
+    {  1674,  1675,  1747,  1749,  1827,  1828},
+    {  1675,  1676,  1748,  1750,  1828,  1829},
+    {  1676,  1677,  1749,  1751,  1829,  1830},
+    {  1677,  1678,  1750,  1752,  1830,  1831},
+    {  1678,  1679,  1751,  1753,  1831,  1832},
+    {  1679,  1680,  1752,  1754,  1832,  1833},
+    {  1680,  1753,  1833,  1834,  -1,  -1},
+    {  1681,  1756,  1835,  1836,  -1,  -1},
+    {  1681,  1682,  1755,  1757,  1836,  1837},
+    {  1682,  1683,  1756,  1758,  1837,  1838},
+    {  1683,  1684,  1757,  1759,  1838,  1839},
+    {  1684,  1685,  1758,  1760,  1839,  1840},
+    {  1685,  1686,  1759,  1761,  1840,  1841}, // 1760
+    {  1686,  1687,  1760,  1762,  1841,  1842},
+    {  1687,  1688,  1761,  1763,  1842,  1843},
+    {  1688,  1689,  1762,  1764,  1843,  1844},
+    {  1689,  1690,  1763,  1765,  1844,  1845},
+    {  1690,  1691,  1764,  1766,  1845,  1846},
+    {  1691,  1692,  1765,  1767,  1846,  1847},
+    {  1692,  1766,  1847,  1848,  -1,  -1},
+    {  1693,  1769,  1849,  1850,  -1,  -1},
+    {  1693,  1694,  1768,  1770,  1850,  1851},
+    {  1694,  1695,  1769,  1771,  1851,  1852},
+    {  1695,  1696,  1770,  1772,  1852,  1853},
+    {  1696,  1697,  1771,  1773,  1853,  1854},
+    {  1697,  1698,  1772,  1774,  1854,  1855},
+    {  1698,  1699,  1773,  1775,  1855,  1856},
+    {  1699,  1700,  1774,  1776,  1856,  1857},
+    {  1700,  1701,  1775,  1777,  1857,  1858},
+    {  1701,  1702,  1776,  1778,  1858,  1859},
+    {  1702,  1703,  1777,  1779,  1859,  1860},
+    {  1703,  1704,  1778,  1780,  1860,  1861},
+    {  1704,  1779,  1861,  1862,  -1,  -1}, // 1780
+    {  1705,  1782,  1863,  1864,  -1,  -1},
+    {  1705,  1706,  1781,  1783,  1864,  1865},
+    {  1706,  1707,  1782,  1784,  1865,  1866},
+    {  1707,  1708,  1783,  1785,  1866,  1867},
+    {  1708,  1709,  1784,  1786,  1867,  1868},
+    {  1709,  1710,  1785,  1787,  1868,  1869},
+    {  1710,  1711,  1786,  1788,  1869,  1870},
+    {  1711,  1712,  1787,  1789,  1870,  1871},
+    {  1712,  1713,  1788,  1790,  1871,  1872},
+    {  1713,  1714,  1789,  1791,  1872,  1873},
+    {  1714,  1715,  1790,  1792,  1873,  1874},
+    {  1715,  1716,  1791,  1793,  1874,  1875},
+    {  1716,  1792,  1875,  1876,  -1,  -1},
+    {  1717,  1795,  1877,  1878,  -1,  -1},
+    {  1717,  1718,  1794,  1796,  1878,  1879},
+    {  1718,  1719,  1795,  1797,  1879,  1880},
+    {  1719,  1720,  1796,  1798,  1880,  1881},
+    {  1720,  1721,  1797,  1799,  1881,  1882},
+    {  1721,  1722,  1798,  1800,  1882,  1883},
+    {  1722,  1723,  1799,  1801,  1883,  1884}, // 1800
+    {  1723,  1724,  1800,  1802,  1884,  1885},
+    {  1724,  1725,  1801,  1803,  1885,  1886},
+    {  1725,  1726,  1802,  1804,  1886,  1887},
+    {  1726,  1727,  1803,  1805,  1887,  1888},
+    {  1727,  1728,  1804,  1806,  1888,  1889},
+    {  1728,  1805,  1889,  1890,  -1,  -1},
+    {  1729,  1808,  1891,  1892,  -1,  -1},
+    {  1729,  1730,  1807,  1809,  1892,  1893},
+    {  1730,  1731,  1808,  1810,  1893,  1894},
+    {  1731,  1732,  1809,  1811,  1894,  1895},
+    {  1732,  1733,  1810,  1812,  1895,  1896},
+    {  1733,  1734,  1811,  1813,  1896,  1897},
+    {  1734,  1735,  1812,  1814,  1897,  1898},
+    {  1735,  1736,  1813,  1815,  1898,  1899},
+    {  1736,  1737,  1814,  1816,  1899,  1900},
+    {  1737,  1738,  1815,  1817,  1900,  1901},
+    {  1738,  1739,  1816,  1818,  1901,  1902},
+    {  1739,  1740,  1817,  1819,  1902,  1903},
+    {  1740,  1741,  1818,  1820,  1903,  1904},
+    {  1741,  1819,  1904,  1905,  -1,  -1}, // 1820
+    {  1742,  1822,  1906,  1907,  -1,  -1},
+    {  1742,  1743,  1821,  1823,  1907,  1908},
+    {  1743,  1744,  1822,  1824,  1908,  1909},
+    {  1744,  1745,  1823,  1825,  1909,  1910},
+    {  1745,  1746,  1824,  1826,  1910,  1911},
+    {  1746,  1747,  1825,  1827,  1911,  1912},
+    {  1747,  1748,  1826,  1828,  1912,  1913},
+    {  1748,  1749,  1827,  1829,  1913,  1914},
+    {  1749,  1750,  1828,  1830,  1914,  1915},
+    {  1750,  1751,  1829,  1831,  1915,  1916},
+    {  1751,  1752,  1830,  1832,  1916,  1917},
+    {  1752,  1753,  1831,  1833,  1917,  1918},
+    {  1753,  1754,  1832,  1834,  1918,  1919},
+    {  1754,  1833,  1919,  1920,  -1,  -1},
+    {  1755,  1836,  1921,  1922,  -1,  -1},
+    {  1755,  1756,  1835,  1837,  1922,  1923},
+    {  1756,  1757,  1836,  1838,  1923,  1924},
+    {  1757,  1758,  1837,  1839,  1924,  1925},
+    {  1758,  1759,  1838,  1840,  1925,  1926},
+    {  1759,  1760,  1839,  1841,  1926,  1927}, // 1840
+    {  1760,  1761,  1840,  1842,  1927,  1928},
+    {  1761,  1762,  1841,  1843,  1928,  1929},
+    {  1762,  1763,  1842,  1844,  1929,  1930},
+    {  1763,  1764,  1843,  1845,  1930,  1931},
+    {  1764,  1765,  1844,  1846,  1931,  1932},
+    {  1765,  1766,  1845,  1847,  1932,  1933},
+    {  1766,  1767,  1846,  1848,  1933,  1934},
+    {  1767,  1847,  1934,  1935,  -1,  -1},
+    {  1768,  1850,  1936,  1937,  -1,  -1},
+    {  1768,  1769,  1849,  1851,  1937,  1938},
+    {  1769,  1770,  1850,  1852,  1938,  1939},
+    {  1770,  1771,  1851,  1853,  1939,  1940},
+    {  1771,  1772,  1852,  1854,  1940,  1941},
+    {  1772,  1773,  1853,  1855,  1941,  1942},
+    {  1773,  1774,  1854,  1856,  1942,  1943},
+    {  1774,  1775,  1855,  1857,  1943,  1944},
+    {  1775,  1776,  1856,  1858,  1944,  1945},
+    {  1776,  1777,  1857,  1859,  1945,  1946},
+    {  1777,  1778,  1858,  1860,  1946,  1947},
+    {  1778,  1779,  1859,  1861,  1947,  1948}, // 1860
+    {  1779,  1780,  1860,  1862,  1948,  1949},
+    {  1780,  1861,  1949,  1950,  -1,  -1},
+    {  1781,  1864,  1951,  1952,  -1,  -1},
+    {  1781,  1782,  1863,  1865,  1952,  1953},
+    {  1782,  1783,  1864,  1866,  1953,  1954},
+    {  1783,  1784,  1865,  1867,  1954,  1955},
+    {  1784,  1785,  1866,  1868,  1955,  1956},
+    {  1785,  1786,  1867,  1869,  1956,  1957},
+    {  1786,  1787,  1868,  1870,  1957,  1958},
+    {  1787,  1788,  1869,  1871,  1958,  1959},
+    {  1788,  1789,  1870,  1872,  1959,  1960},
+    {  1789,  1790,  1871,  1873,  1960,  1961},
+    {  1790,  1791,  1872,  1874,  1961,  1962},
+    {  1791,  1792,  1873,  1875,  1962,  1963},
+    {  1792,  1793,  1874,  1876,  1963,  1964},
+    {  1793,  1875,  1964,  1965,  -1,  -1},
+    {  1794,  1878,  1966,  1967,  -1,  -1},
+    {  1794,  1795,  1877,  1879,  1967,  1968},
+    {  1795,  1796,  1878,  1880,  1968,  1969},
+    {  1796,  1797,  1879,  1881,  1969,  1970}, // 1880
+    {  1797,  1798,  1880,  1882,  1970,  1971},
+    {  1798,  1799,  1881,  1883,  1971,  1972},
+    {  1799,  1800,  1882,  1884,  1972,  1973},
+    {  1800,  1801,  1883,  1885,  1973,  1974},
+    {  1801,  1802,  1884,  1886,  1974,  1975},
+    {  1802,  1803,  1885,  1887,  1975,  1976},
+    {  1803,  1804,  1886,  1888,  1976,  1977},
+    {  1804,  1805,  1887,  1889,  1977,  1978},
+    {  1805,  1806,  1888,  1890,  1978,  1979},
+    {  1806,  1889,  1979,  1980,  -1,  -1},
+    {  1807,  1892,  1981,  1982,  -1,  -1},
+    {  1807,  1808,  1891,  1893,  1982,  1983},
+    {  1808,  1809,  1892,  1894,  1983,  1984},
+    {  1809,  1810,  1893,  1895,  1984,  1985},
+    {  1810,  1811,  1894,  1896,  1985,  1986},
+    {  1811,  1812,  1895,  1897,  1986,  1987},
+    {  1812,  1813,  1896,  1898,  1987,  1988},
+    {  1813,  1814,  1897,  1899,  1988,  1989},
+    {  1814,  1815,  1898,  1900,  1989,  1990},
+    {  1815,  1816,  1899,  1901,  1990,  1991}, // 1900
+    {  1816,  1817,  1900,  1902,  1991,  1992},
+    {  1817,  1818,  1901,  1903,  1992,  1993},
+    {  1818,  1819,  1902,  1904,  1993,  1994},
+    {  1819,  1820,  1903,  1905,  1994,  1995},
+    {  1820,  1904,  1995,  1996,  -1,  -1},
+    {  1821,  1907,  1997,  1998,  -1,  -1},
+    {  1821,  1822,  1906,  1908,  1998,  1999},
+    {  1822,  1823,  1907,  1909,  1999,  2000},
+    {  1823,  1824,  1908,  1910,  2000,  2001},
+    {  1824,  1825,  1909,  1911,  2001,  2002},
+    {  1825,  1826,  1910,  1912,  2002,  2003},
+    {  1826,  1827,  1911,  1913,  2003,  2004},
+    {  1827,  1828,  1912,  1914,  2004,  2005},
+    {  1828,  1829,  1913,  1915,  2005,  2006},
+    {  1829,  1830,  1914,  1916,  2006,  2007},
+    {  1830,  1831,  1915,  1917,  2007,  2008},
+    {  1831,  1832,  1916,  1918,  2008,  2009},
+    {  1832,  1833,  1917,  1919,  2009,  2010},
+    {  1833,  1834,  1918,  1920,  2010,  2011},
+    {  1834,  1919,  2011,  2012,  -1,  -1}, // 1920
+    {  1835,  1922,  2013,  2014,  -1,  -1},
+    {  1835,  1836,  1921,  1923,  2014,  2015},
+    {  1836,  1837,  1922,  1924,  2015,  2016},
+    {  1837,  1838,  1923,  1925,  2016,  2017},
+    {  1838,  1839,  1924,  1926,  2017,  2018},
+    {  1839,  1840,  1925,  1927,  2018,  2019},
+    {  1840,  1841,  1926,  1928,  2019,  2020},
+    {  1841,  1842,  1927,  1929,  2020,  2021},
+    {  1842,  1843,  1928,  1930,  2021,  2022},
+    {  1843,  1844,  1929,  1931,  2022,  2023},
+    {  1844,  1845,  1930,  1932,  2023,  2024},
+    {  1845,  1846,  1931,  1933,  2024,  2025},
+    {  1846,  1847,  1932,  1934,  2025,  2026},
+    {  1847,  1848,  1933,  1935,  2026,  2027},
+    {  1848,  1934,  2027,  2028,  -1,  -1},
+    {  1849,  1937,  2029,  2030,  -1,  -1},
+    {  1849,  1850,  1936,  1938,  2030,  2031},
+    {  1850,  1851,  1937,  1939,  2031,  2032},
+    {  1851,  1852,  1938,  1940,  2032,  2033},
+    {  1852,  1853,  1939,  1941,  2033,  2034}, // 1940
+    {  1853,  1854,  1940,  1942,  2034,  2035},
+    {  1854,  1855,  1941,  1943,  2035,  2036},
+    {  1855,  1856,  1942,  1944,  2036,  2037},
+    {  1856,  1857,  1943,  1945,  2037,  2038},
+    {  1857,  1858,  1944,  1946,  2038,  2039},
+    {  1858,  1859,  1945,  1947,  2039,  2040},
+    {  1859,  1860,  1946,  1948,  2040,  2041},
+    {  1860,  1861,  1947,  1949,  2041,  2042},
+    {  1861,  1862,  1948,  1950,  2042,  2043},
+    {  1862,  1949,  2043,  2044,  -1,  -1},
+    {  1863,  1952,  2045,  2046,  -1,  -1},
+    {  1863,  1864,  1951,  1953,  2046,  2047},
+    {  1864,  1865,  1952,  1954,  2047,  2048},
+    {  1865,  1866,  1953,  1955,  2048,  2049},
+    {  1866,  1867,  1954,  1956,  2049,  2050},
+    {  1867,  1868,  1955,  1957,  2050,  2051},
+    {  1868,  1869,  1956,  1958,  2051,  2052},
+    {  1869,  1870,  1957,  1959,  2052,  2053},
+    {  1870,  1871,  1958,  1960,  2053,  2054},
+    {  1871,  1872,  1959,  1961,  2054,  2055}, // 1960
+    {  1872,  1873,  1960,  1962,  2055,  2056},
+    {  1873,  1874,  1961,  1963,  2056,  2057},
+    {  1874,  1875,  1962,  1964,  2057,  2058},
+    {  1875,  1876,  1963,  1965,  2058,  2059},
+    {  1876,  1964,  2059,  2060,  -1,  -1},
+    {  1877,  1967,  2061,  2062,  -1,  -1},
+    {  1877,  1878,  1966,  1968,  2062,  2063},
+    {  1878,  1879,  1967,  1969,  2063,  2064},
+    {  1879,  1880,  1968,  1970,  2064,  2065},
+    {  1880,  1881,  1969,  1971,  2065,  2066},
+    {  1881,  1882,  1970,  1972,  2066,  2067},
+    {  1882,  1883,  1971,  1973,  2067,  2068},
+    {  1883,  1884,  1972,  1974,  2068,  2069},
+    {  1884,  1885,  1973,  1975,  2069,  2070},
+    {  1885,  1886,  1974,  1976,  2070,  2071},
+    {  1886,  1887,  1975,  1977,  2071,  2072},
+    {  1887,  1888,  1976,  1978,  2072,  2073},
+    {  1888,  1889,  1977,  1979,  2073,  2074},
+    {  1889,  1890,  1978,  1980,  2074,  2075},
+    {  1890,  1979,  2075,  2076,  -1,  -1}, // 1980
+    {  1891,  1982,  2077,  2078,  -1,  -1},
+    {  1891,  1892,  1981,  1983,  2078,  2079},
+    {  1892,  1893,  1982,  1984,  2079,  2080},
+    {  1893,  1894,  1983,  1985,  2080,  2081},
+    {  1894,  1895,  1984,  1986,  2081,  2082},
+    {  1895,  1896,  1985,  1987,  2082,  2083},
+    {  1896,  1897,  1986,  1988,  2083,  2084},
+    {  1897,  1898,  1987,  1989,  2084,  2085},
+    {  1898,  1899,  1988,  1990,  2085,  2086},
+    {  1899,  1900,  1989,  1991,  2086,  2087},
+    {  1900,  1901,  1990,  1992,  2087,  2088},
+    {  1901,  1902,  1991,  1993,  2088,  2089},
+    {  1902,  1903,  1992,  1994,  2089,  2090},
+    {  1903,  1904,  1993,  1995,  2090,  2091},
+    {  1904,  1905,  1994,  1996,  2091,  2092},
+    {  1905,  1995,  2092,  2093,  -1,  -1},
+    {  1906,  1998,  2094,  2095,  -1,  -1},
+    {  1906,  1907,  1997,  1999,  2095,  2096},
+    {  1907,  1908,  1998,  2000,  2096,  2097},
+    {  1908,  1909,  1999,  2001,  2097,  2098}, // 2000
+    {  1909,  1910,  2000,  2002,  2098,  2099},
+    {  1910,  1911,  2001,  2003,  2099,  2100},
+    {  1911,  1912,  2002,  2004,  2100,  2101},
+    {  1912,  1913,  2003,  2005,  2101,  2102},
+    {  1913,  1914,  2004,  2006,  2102,  2103},
+    {  1914,  1915,  2005,  2007,  2103,  2104},
+    {  1915,  1916,  2006,  2008,  2104,  2105},
+    {  1916,  1917,  2007,  2009,  2105,  2106},
+    {  1917,  1918,  2008,  2010,  2106,  2107},
+    {  1918,  1919,  2009,  2011,  2107,  2108},
+    {  1919,  1920,  2010,  2012,  2108,  2109},
+    {  1920,  2011,  2109,  2110,  -1,  -1},
+    {  1921,  2014,  2111,  2112,  -1,  -1},
+    {  1921,  1922,  2013,  2015,  2112,  2113},
+    {  1922,  1923,  2014,  2016,  2113,  2114},
+    {  1923,  1924,  2015,  2017,  2114,  2115},
+    {  1924,  1925,  2016,  2018,  2115,  2116},
+    {  1925,  1926,  2017,  2019,  2116,  2117},
+    {  1926,  1927,  2018,  2020,  2117,  2118},
+    {  1927,  1928,  2019,  2021,  2118,  2119}, // 2020
+    {  1928,  1929,  2020,  2022,  2119,  2120},
+    {  1929,  1930,  2021,  2023,  2120,  2121},
+    {  1930,  1931,  2022,  2024,  2121,  2122},
+    {  1931,  1932,  2023,  2025,  2122,  2123},
+    {  1932,  1933,  2024,  2026,  2123,  2124},
+    {  1933,  1934,  2025,  2027,  2124,  2125},
+    {  1934,  1935,  2026,  2028,  2125,  2126},
+    {  1935,  2027,  2126,  2127,  -1,  -1},
+    {  1936,  2030,  2128,  2129,  -1,  -1},
+    {  1936,  1937,  2029,  2031,  2129,  2130},
+    {  1937,  1938,  2030,  2032,  2130,  2131},
+    {  1938,  1939,  2031,  2033,  2131,  2132},
+    {  1939,  1940,  2032,  2034,  2132,  2133},
+    {  1940,  1941,  2033,  2035,  2133,  2134},
+    {  1941,  1942,  2034,  2036,  2134,  2135},
+    {  1942,  1943,  2035,  2037,  2135,  2136},
+    {  1943,  1944,  2036,  2038,  2136,  2137},
+    {  1944,  1945,  2037,  2039,  2137,  2138},
+    {  1945,  1946,  2038,  2040,  2138,  2139},
+    {  1946,  1947,  2039,  2041,  2139,  2140}, // 2040
+    {  1947,  1948,  2040,  2042,  2140,  2141},
+    {  1948,  1949,  2041,  2043,  2141,  2142},
+    {  1949,  1950,  2042,  2044,  2142,  2143},
+    {  1950,  2043,  2143,  2144,  -1,  -1},
+    {  1951,  2046,  2145,  2146,  -1,  -1},
+    {  1951,  1952,  2045,  2047,  2146,  2147},
+    {  1952,  1953,  2046,  2048,  2147,  2148},
+    {  1953,  1954,  2047,  2049,  2148,  2149},
+    {  1954,  1955,  2048,  2050,  2149,  2150},
+    {  1955,  1956,  2049,  2051,  2150,  2151},
+    {  1956,  1957,  2050,  2052,  2151,  2152},
+    {  1957,  1958,  2051,  2053,  2152,  2153},
+    {  1958,  1959,  2052,  2054,  2153,  2154},
+    {  1959,  1960,  2053,  2055,  2154,  2155},
+    {  1960,  1961,  2054,  2056,  2155,  2156},
+    {  1961,  1962,  2055,  2057,  2156,  2157},
+    {  1962,  1963,  2056,  2058,  2157,  2158},
+    {  1963,  1964,  2057,  2059,  2158,  2159},
+    {  1964,  1965,  2058,  2060,  2159,  2160},
+    {  1965,  2059,  2160,  2161,  -1,  -1}, // 2060
+    {  1966,  2062,  2162,  2163,  -1,  -1},
+    {  1966,  1967,  2061,  2063,  2163,  2164},
+    {  1967,  1968,  2062,  2064,  2164,  2165},
+    {  1968,  1969,  2063,  2065,  2165,  2166},
+    {  1969,  1970,  2064,  2066,  2166,  2167},
+    {  1970,  1971,  2065,  2067,  2167,  2168},
+    {  1971,  1972,  2066,  2068,  2168,  2169},
+    {  1972,  1973,  2067,  2069,  2169,  2170},
+    {  1973,  1974,  2068,  2070,  2170,  2171},
+    {  1974,  1975,  2069,  2071,  2171,  2172},
+    {  1975,  1976,  2070,  2072,  2172,  2173},
+    {  1976,  1977,  2071,  2073,  2173,  2174},
+    {  1977,  1978,  2072,  2074,  2174,  2175},
+    {  1978,  1979,  2073,  2075,  2175,  2176},
+    {  1979,  1980,  2074,  2076,  2176,  2177},
+    {  1980,  2075,  2177,  2178,  -1,  -1},
+    {  1981,  2078,  2179,  2180,  -1,  -1},
+    {  1981,  1982,  2077,  2079,  2180,  2181},
+    {  1982,  1983,  2078,  2080,  2181,  2182},
+    {  1983,  1984,  2079,  2081,  2182,  2183}, // 2080
+    {  1984,  1985,  2080,  2082,  2183,  2184},
+    {  1985,  1986,  2081,  2083,  2184,  2185},
+    {  1986,  1987,  2082,  2084,  2185,  2186},
+    {  1987,  1988,  2083,  2085,  2186,  2187},
+    {  1988,  1989,  2084,  2086,  2187,  2188},
+    {  1989,  1990,  2085,  2087,  2188,  2189},
+    {  1990,  1991,  2086,  2088,  2189,  2190},
+    {  1991,  1992,  2087,  2089,  2190,  2191},
+    {  1992,  1993,  2088,  2090,  2191,  2192},
+    {  1993,  1994,  2089,  2091,  2192,  2193},
+    {  1994,  1995,  2090,  2092,  2193,  2194},
+    {  1995,  1996,  2091,  2093,  2194,  2195},
+    {  1996,  2092,  2195,  2196,  -1,  -1},
+    {  1997,  2095,  2197,  2198,  -1,  -1},
+    {  1997,  1998,  2094,  2096,  2198,  2199},
+    {  1998,  1999,  2095,  2097,  2199,  2200},
+    {  1999,  2000,  2096,  2098,  2200,  2201},
+    {  2000,  2001,  2097,  2099,  2201,  2202},
+    {  2001,  2002,  2098,  2100,  2202,  2203},
+    {  2002,  2003,  2099,  2101,  2203,  2204}, // 2100
+    {  2003,  2004,  2100,  2102,  2204,  2205},
+    {  2004,  2005,  2101,  2103,  2205,  2206},
+    {  2005,  2006,  2102,  2104,  2206,  2207},
+    {  2006,  2007,  2103,  2105,  2207,  2208},
+    {  2007,  2008,  2104,  2106,  2208,  2209},
+    {  2008,  2009,  2105,  2107,  2209,  2210},
+    {  2009,  2010,  2106,  2108,  2210,  2211},
+    {  2010,  2011,  2107,  2109,  2211,  2212},
+    {  2011,  2012,  2108,  2110,  2212,  2213},
+    {  2012,  2109,  2213,  2214,  -1,  -1},
+    {  2013,  2112,  2215,  2216,  -1,  -1},
+    {  2013,  2014,  2111,  2113,  2216,  2217},
+    {  2014,  2015,  2112,  2114,  2217,  2218},
+    {  2015,  2016,  2113,  2115,  2218,  2219},
+    {  2016,  2017,  2114,  2116,  2219,  2220},
+    {  2017,  2018,  2115,  2117,  2220,  2221},
+    {  2018,  2019,  2116,  2118,  2221,  2222},
+    {  2019,  2020,  2117,  2119,  2222,  2223},
+    {  2020,  2021,  2118,  2120,  2223,  2224},
+    {  2021,  2022,  2119,  2121,  2224,  2225}, // 2120
+    {  2022,  2023,  2120,  2122,  2225,  2226},
+    {  2023,  2024,  2121,  2123,  2226,  2227},
+    {  2024,  2025,  2122,  2124,  2227,  2228},
+    {  2025,  2026,  2123,  2125,  2228,  2229},
+    {  2026,  2027,  2124,  2126,  2229,  2230},
+    {  2027,  2028,  2125,  2127,  2230,  2231},
+    {  2028,  2126,  2231,  2232,  -1,  -1},
+    {  2029,  2129,  2233,  2234,  -1,  -1},
+    {  2029,  2030,  2128,  2130,  2234,  2235},
+    {  2030,  2031,  2129,  2131,  2235,  2236},
+    {  2031,  2032,  2130,  2132,  2236,  2237},
+    {  2032,  2033,  2131,  2133,  2237,  2238},
+    {  2033,  2034,  2132,  2134,  2238,  2239},
+    {  2034,  2035,  2133,  2135,  2239,  2240},
+    {  2035,  2036,  2134,  2136,  2240,  2241},
+    {  2036,  2037,  2135,  2137,  2241,  2242},
+    {  2037,  2038,  2136,  2138,  2242,  2243},
+    {  2038,  2039,  2137,  2139,  2243,  2244},
+    {  2039,  2040,  2138,  2140,  2244,  2245},
+    {  2040,  2041,  2139,  2141,  2245,  2246}, // 2140
+    {  2041,  2042,  2140,  2142,  2246,  2247},
+    {  2042,  2043,  2141,  2143,  2247,  2248},
+    {  2043,  2044,  2142,  2144,  2248,  2249},
+    {  2044,  2143,  2249,  2250,  -1,  -1},
+    {  2045,  2146,  2251,  2252,  -1,  -1},
+    {  2045,  2046,  2145,  2147,  2252,  2253},
+    {  2046,  2047,  2146,  2148,  2253,  2254},
+    {  2047,  2048,  2147,  2149,  2254,  2255},
+    {  2048,  2049,  2148,  2150,  2255,  2256},
+    {  2049,  2050,  2149,  2151,  2256,  2257},
+    {  2050,  2051,  2150,  2152,  2257,  2258},
+    {  2051,  2052,  2151,  2153,  2258,  2259},
+    {  2052,  2053,  2152,  2154,  2259,  2260},
+    {  2053,  2054,  2153,  2155,  2260,  2261},
+    {  2054,  2055,  2154,  2156,  2261,  2262},
+    {  2055,  2056,  2155,  2157,  2262,  2263},
+    {  2056,  2057,  2156,  2158,  2263,  2264},
+    {  2057,  2058,  2157,  2159,  2264,  2265},
+    {  2058,  2059,  2158,  2160,  2265,  2266},
+    {  2059,  2060,  2159,  2161,  2266,  2267}, // 2160
+    {  2060,  2160,  2267,  2268,  -1,  -1},
+    {  2061,  2163,  2269,  2270,  -1,  -1},
+    {  2061,  2062,  2162,  2164,  2270,  2271},
+    {  2062,  2063,  2163,  2165,  2271,  2272},
+    {  2063,  2064,  2164,  2166,  2272,  2273},
+    {  2064,  2065,  2165,  2167,  2273,  2274},
+    {  2065,  2066,  2166,  2168,  2274,  2275},
+    {  2066,  2067,  2167,  2169,  2275,  2276},
+    {  2067,  2068,  2168,  2170,  2276,  2277},
+    {  2068,  2069,  2169,  2171,  2277,  2278},
+    {  2069,  2070,  2170,  2172,  2278,  2279},
+    {  2070,  2071,  2171,  2173,  2279,  2280},
+    {  2071,  2072,  2172,  2174,  2280,  2281},
+    {  2072,  2073,  2173,  2175,  2281,  2282},
+    {  2073,  2074,  2174,  2176,  2282,  2283},
+    {  2074,  2075,  2175,  2177,  2283,  2284},
+    {  2075,  2076,  2176,  2178,  2284,  2285},
+    {  2076,  2177,  2285,  2286,  -1,  -1},
+    {  2077,  2180,  2287,  2288,  -1,  -1},
+    {  2077,  2078,  2179,  2181,  2288,  2289}, // 2180
+    {  2078,  2079,  2180,  2182,  2289,  2290},
+    {  2079,  2080,  2181,  2183,  2290,  2291},
+    {  2080,  2081,  2182,  2184,  2291,  2292},
+    {  2081,  2082,  2183,  2185,  2292,  2293},
+    {  2082,  2083,  2184,  2186,  2293,  2294},
+    {  2083,  2084,  2185,  2187,  2294,  2295},
+    {  2084,  2085,  2186,  2188,  2295,  2296},
+    {  2085,  2086,  2187,  2189,  2296,  2297},
+    {  2086,  2087,  2188,  2190,  2297,  2298},
+    {  2087,  2088,  2189,  2191,  2298,  2299},
+    {  2088,  2089,  2190,  2192,  2299,  2300},
+    {  2089,  2090,  2191,  2193,  2300,  2301},
+    {  2090,  2091,  2192,  2194,  2301,  2302},
+    {  2091,  2092,  2193,  2195,  2302,  2303},
+    {  2092,  2093,  2194,  2196,  2303,  2304},
+    {  2093,  2195,  2304,  2305,  -1,  -1},
+    {  2094,  2198,  2306,  2307,  -1,  -1},
+    {  2094,  2095,  2197,  2199,  2307,  2308},
+    {  2095,  2096,  2198,  2200,  2308,  2309},
+    {  2096,  2097,  2199,  2201,  2309,  2310}, // 2200
+    {  2097,  2098,  2200,  2202,  2310,  2311},
+    {  2098,  2099,  2201,  2203,  2311,  2312},
+    {  2099,  2100,  2202,  2204,  2312,  2313},
+    {  2100,  2101,  2203,  2205,  2313,  2314},
+    {  2101,  2102,  2204,  2206,  2314,  2315},
+    {  2102,  2103,  2205,  2207,  2315,  2316},
+    {  2103,  2104,  2206,  2208,  2316,  2317},
+    {  2104,  2105,  2207,  2209,  2317,  2318},
+    {  2105,  2106,  2208,  2210,  2318,  2319},
+    {  2106,  2107,  2209,  2211,  2319,  2320},
+    {  2107,  2108,  2210,  2212,  2320,  2321},
+    {  2108,  2109,  2211,  2213,  2321,  2322},
+    {  2109,  2110,  2212,  2214,  2322,  2323},
+    {  2110,  2213,  2323,  2324,  -1,  -1},
+    {  2111,  2216,  2325,  2326,  -1,  -1},
+    {  2111,  2112,  2215,  2217,  2326,  2327},
+    {  2112,  2113,  2216,  2218,  2327,  2328},
+    {  2113,  2114,  2217,  2219,  2328,  2329},
+    {  2114,  2115,  2218,  2220,  2329,  2330},
+    {  2115,  2116,  2219,  2221,  2330,  2331}, // 2220
+    {  2116,  2117,  2220,  2222,  2331,  2332},
+    {  2117,  2118,  2221,  2223,  2332,  2333},
+    {  2118,  2119,  2222,  2224,  2333,  2334},
+    {  2119,  2120,  2223,  2225,  2334,  2335},
+    {  2120,  2121,  2224,  2226,  2335,  2336},
+    {  2121,  2122,  2225,  2227,  2336,  2337},
+    {  2122,  2123,  2226,  2228,  2337,  2338},
+    {  2123,  2124,  2227,  2229,  2338,  2339},
+    {  2124,  2125,  2228,  2230,  2339,  2340},
+    {  2125,  2126,  2229,  2231,  2340,  2341},
+    {  2126,  2127,  2230,  2232,  2341,  2342},
+    {  2127,  2231,  2342,  2343,  -1,  -1},
+    {  2128,  2234,  2344,  2345,  -1,  -1},
+    {  2128,  2129,  2233,  2235,  2345,  2346},
+    {  2129,  2130,  2234,  2236,  2346,  2347},
+    {  2130,  2131,  2235,  2237,  2347,  2348},
+    {  2131,  2132,  2236,  2238,  2348,  2349},
+    {  2132,  2133,  2237,  2239,  2349,  2350},
+    {  2133,  2134,  2238,  2240,  2350,  2351},
+    {  2134,  2135,  2239,  2241,  2351,  2352}, // 2240
+    {  2135,  2136,  2240,  2242,  2352,  2353},
+    {  2136,  2137,  2241,  2243,  2353,  2354},
+    {  2137,  2138,  2242,  2244,  2354,  2355},
+    {  2138,  2139,  2243,  2245,  2355,  2356},
+    {  2139,  2140,  2244,  2246,  2356,  2357},
+    {  2140,  2141,  2245,  2247,  2357,  2358},
+    {  2141,  2142,  2246,  2248,  2358,  2359},
+    {  2142,  2143,  2247,  2249,  2359,  2360},
+    {  2143,  2144,  2248,  2250,  2360,  2361},
+    {  2144,  2249,  2361,  2362,  -1,  -1},
+    {  2145,  2252,  2363,  2364,  -1,  -1},
+    {  2145,  2146,  2251,  2253,  2364,  2365},
+    {  2146,  2147,  2252,  2254,  2365,  2366},
+    {  2147,  2148,  2253,  2255,  2366,  2367},
+    {  2148,  2149,  2254,  2256,  2367,  2368},
+    {  2149,  2150,  2255,  2257,  2368,  2369},
+    {  2150,  2151,  2256,  2258,  2369,  2370},
+    {  2151,  2152,  2257,  2259,  2370,  2371},
+    {  2152,  2153,  2258,  2260,  2371,  2372},
+    {  2153,  2154,  2259,  2261,  2372,  2373}, // 2260
+    {  2154,  2155,  2260,  2262,  2373,  2374},
+    {  2155,  2156,  2261,  2263,  2374,  2375},
+    {  2156,  2157,  2262,  2264,  2375,  2376},
+    {  2157,  2158,  2263,  2265,  2376,  2377},
+    {  2158,  2159,  2264,  2266,  2377,  2378},
+    {  2159,  2160,  2265,  2267,  2378,  2379},
+    {  2160,  2161,  2266,  2268,  2379,  2380},
+    {  2161,  2267,  2380,  2381,  -1,  -1},
+    {  2162,  2270,  2382,  2383,  -1,  -1},
+    {  2162,  2163,  2269,  2271,  2383,  2384},
+    {  2163,  2164,  2270,  2272,  2384,  2385},
+    {  2164,  2165,  2271,  2273,  2385,  2386},
+    {  2165,  2166,  2272,  2274,  2386,  2387},
+    {  2166,  2167,  2273,  2275,  2387,  2388},
+    {  2167,  2168,  2274,  2276,  2388,  2389},
+    {  2168,  2169,  2275,  2277,  2389,  2390},
+    {  2169,  2170,  2276,  2278,  2390,  2391},
+    {  2170,  2171,  2277,  2279,  2391,  2392},
+    {  2171,  2172,  2278,  2280,  2392,  2393},
+    {  2172,  2173,  2279,  2281,  2393,  2394}, // 2280
+    {  2173,  2174,  2280,  2282,  2394,  2395},
+    {  2174,  2175,  2281,  2283,  2395,  2396},
+    {  2175,  2176,  2282,  2284,  2396,  2397},
+    {  2176,  2177,  2283,  2285,  2397,  2398},
+    {  2177,  2178,  2284,  2286,  2398,  2399},
+    {  2178,  2285,  2399,  2400,  -1,  -1},
+    {  2179,  2288,  -1,  -1,  -1,  -1},
+    {  2179,  2180,  2287,  2289,  -1,  -1},
+    {  2180,  2181,  2288,  2290,  -1,  -1},
+    {  2181,  2182,  2289,  2291,  -1,  -1},
+    {  2182,  2183,  2290,  2292,  -1,  -1},
+    {  2183,  2184,  2291,  2293,  -1,  -1},
+    {  2184,  2185,  2292,  2294,  -1,  -1},
+    {  2185,  2186,  2293,  2295,  -1,  -1},
+    {  2186,  2187,  2294,  2296,  -1,  -1},
+    {  2187,  2188,  2295,  2297,  -1,  -1},
+    {  2188,  2189,  2296,  2298,  -1,  -1},
+    {  2189,  2190,  2297,  2299,  -1,  -1},
+    {  2190,  2191,  2298,  2300,  -1,  -1},
+    {  2191,  2192,  2299,  2301,  -1,  -1}, // 2300
+    {  2192,  2193,  2300,  2302,  -1,  -1},
+    {  2193,  2194,  2301,  2303,  -1,  -1},
+    {  2194,  2195,  2302,  2304,  -1,  -1},
+    {  2195,  2196,  2303,  2305,  -1,  -1},
+    {  2196,  2304,  -1,  -1,  -1,  -1},
+    {  2197,  2307,  -1,  -1,  -1,  -1},
+    {  2197,  2198,  2306,  2308,  -1,  -1},
+    {  2198,  2199,  2307,  2309,  -1,  -1},
+    {  2199,  2200,  2308,  2310,  -1,  -1},
+    {  2200,  2201,  2309,  2311,  -1,  -1},
+    {  2201,  2202,  2310,  2312,  -1,  -1},
+    {  2202,  2203,  2311,  2313,  -1,  -1},
+    {  2203,  2204,  2312,  2314,  -1,  -1},
+    {  2204,  2205,  2313,  2315,  -1,  -1},
+    {  2205,  2206,  2314,  2316,  -1,  -1},
+    {  2206,  2207,  2315,  2317,  -1,  -1},
+    {  2207,  2208,  2316,  2318,  -1,  -1},
+    {  2208,  2209,  2317,  2319,  -1,  -1},
+    {  2209,  2210,  2318,  2320,  -1,  -1},
+    {  2210,  2211,  2319,  2321,  -1,  -1}, // 2320
+    {  2211,  2212,  2320,  2322,  -1,  -1},
+    {  2212,  2213,  2321,  2323,  -1,  -1},
+    {  2213,  2214,  2322,  2324,  -1,  -1},
+    {  2214,  2323,  -1,  -1,  -1,  -1},
+    {  2215,  2326,  -1,  -1,  -1,  -1},
+    {  2215,  2216,  2325,  2327,  -1,  -1},
+    {  2216,  2217,  2326,  2328,  -1,  -1},
+    {  2217,  2218,  2327,  2329,  -1,  -1},
+    {  2218,  2219,  2328,  2330,  -1,  -1},
+    {  2219,  2220,  2329,  2331,  -1,  -1},
+    {  2220,  2221,  2330,  2332,  -1,  -1},
+    {  2221,  2222,  2331,  2333,  -1,  -1},
+    {  2222,  2223,  2332,  2334,  -1,  -1},
+    {  2223,  2224,  2333,  2335,  -1,  -1},
+    {  2224,  2225,  2334,  2336,  -1,  -1},
+    {  2225,  2226,  2335,  2337,  -1,  -1},
+    {  2226,  2227,  2336,  2338,  -1,  -1},
+    {  2227,  2228,  2337,  2339,  -1,  -1},
+    {  2228,  2229,  2338,  2340,  -1,  -1},
+    {  2229,  2230,  2339,  2341,  -1,  -1}, // 2340
+    {  2230,  2231,  2340,  2342,  -1,  -1},
+    {  2231,  2232,  2341,  2343,  -1,  -1},
+    {  2232,  2342,  -1,  -1,  -1,  -1},
+    {  2233,  2345,  -1,  -1,  -1,  -1},
+    {  2233,  2234,  2344,  2346,  -1,  -1},
+    {  2234,  2235,  2345,  2347,  -1,  -1},
+    {  2235,  2236,  2346,  2348,  -1,  -1},
+    {  2236,  2237,  2347,  2349,  -1,  -1},
+    {  2237,  2238,  2348,  2350,  -1,  -1},
+    {  2238,  2239,  2349,  2351,  -1,  -1},
+    {  2239,  2240,  2350,  2352,  -1,  -1},
+    {  2240,  2241,  2351,  2353,  -1,  -1},
+    {  2241,  2242,  2352,  2354,  -1,  -1},
+    {  2242,  2243,  2353,  2355,  -1,  -1},
+    {  2243,  2244,  2354,  2356,  -1,  -1},
+    {  2244,  2245,  2355,  2357,  -1,  -1},
+    {  2245,  2246,  2356,  2358,  -1,  -1},
+    {  2246,  2247,  2357,  2359,  -1,  -1},
+    {  2247,  2248,  2358,  2360,  -1,  -1},
+    {  2248,  2249,  2359,  2361,  -1,  -1}, // 2360
+    {  2249,  2250,  2360,  2362,  -1,  -1},
+    {  2250,  2361,  -1,  -1,  -1,  -1},
+    {  2251,  2364,  -1,  -1,  -1,  -1},
+    {  2251,  2252,  2363,  2365,  -1,  -1},
+    {  2252,  2253,  2364,  2366,  -1,  -1},
+    {  2253,  2254,  2365,  2367,  -1,  -1},
+    {  2254,  2255,  2366,  2368,  -1,  -1},
+    {  2255,  2256,  2367,  2369,  -1,  -1},
+    {  2256,  2257,  2368,  2370,  -1,  -1},
+    {  2257,  2258,  2369,  2371,  -1,  -1},
+    {  2258,  2259,  2370,  2372,  -1,  -1},
+    {  2259,  2260,  2371,  2373,  -1,  -1},
+    {  2260,  2261,  2372,  2374,  -1,  -1},
+    {  2261,  2262,  2373,  2375,  -1,  -1},
+    {  2262,  2263,  2374,  2376,  -1,  -1},
+    {  2263,  2264,  2375,  2377,  -1,  -1},
+    {  2264,  2265,  2376,  2378,  -1,  -1},
+    {  2265,  2266,  2377,  2379,  -1,  -1},
+    {  2266,  2267,  2378,  2380,  -1,  -1},
+    {  2267,  2268,  2379,  2381,  -1,  -1}, // 2380
+    {  2268,  2380,  -1,  -1,  -1,  -1},
+    {  2269,  2383,  -1,  -1,  -1,  -1},
+    {  2269,  2270,  2382,  2384,  -1,  -1},
+    {  2270,  2271,  2383,  2385,  -1,  -1},
+    {  2271,  2272,  2384,  2386,  -1,  -1},
+    {  2272,  2273,  2385,  2387,  -1,  -1},
+    {  2273,  2274,  2386,  2388,  -1,  -1},
+    {  2274,  2275,  2387,  2389,  -1,  -1},
+    {  2275,  2276,  2388,  2390,  -1,  -1},
+    {  2276,  2277,  2389,  2391,  -1,  -1},
+    {  2277,  2278,  2390,  2392,  -1,  -1},
+    {  2278,  2279,  2391,  2393,  -1,  -1},
+    {  2279,  2280,  2392,  2394,  -1,  -1},
+    {  2280,  2281,  2393,  2395,  -1,  -1},
+    {  2281,  2282,  2394,  2396,  -1,  -1},
+    {  2282,  2283,  2395,  2397,  -1,  -1},
+    {  2283,  2284,  2396,  2398,  -1,  -1},
+    {  2284,  2285,  2397,  2399,  -1,  -1},
+    {  2285,  2286,  2398,  2400,  -1,  -1},
+    {  2286,  2399,  -1,  -1,  -1,  -1} // 2400
+};
+
+    for (Int_t i=0; i<2401; i++)
+        (*this)[i].SetNeighbors(nn[i][0], nn[i][1], nn[i][2],
+                                nn[i][3], nn[i][4], nn[i][5]);
+}
Index: /tags/Mars-V0.9/mgeom/MGeomCamMagicHG.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCamMagicHG.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCamMagicHG.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MGeomCamMagicHG
+#define MARS_MGeomCamMagicHG
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamMagicHG : public MGeomCam
+{
+private:
+    void CreateCam();
+    void CreateNN();
+
+public:
+    MGeomCamMagicHG(const char *name=NULL);
+
+    ClassDef(MGeomCamMagicHG, 1)		// Geometry class for a high granularity Magic camera
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgeom/MGeomCorsikaCT.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCorsikaCT.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCorsikaCT.cc	(revision 9772)
@@ -0,0 +1,76 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 11/2002 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCorsikaCT
+//
+// This is the base class of the PMT characteristics. 
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCorsikaCT.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MGeomCorsikaCT);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes a Telescope geometry.
+//
+MGeomCorsikaCT::MGeomCorsikaCT(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MGeomCorsikaCT";
+    fTitle = title ? title : "Storage container for CT Telescope characteristics";
+}
+
+// --------------------------------------------------------------------------
+//
+// It fills the member variable of this class
+//
+void MGeomCorsikaCT::Fill(Float_t ctx, Float_t cty, Float_t ctz,
+			  Float_t cttheta, Float_t ctphi,
+			  Float_t ctdiam, Float_t ctfocal){
+  
+  fCTx=ctx;
+  fCTy=cty;
+  fCTz=ctz;
+  fCTtheta=cttheta;
+  fCTphi=ctphi;
+  fCTdiam=ctdiam;
+  fCTfocal=ctfocal;
+}
+// --------------------------------------------------------------------------
+//
+// Print the geometry information of one pixel.
+//
+void MGeomCorsikaCT::Print(Option_t *opt) const
+{ 
+    //   information about a telescope
+  *fLog << all << "x = " << fCTx << ", y = " << fCTy << ", z = " 
+	<< fCTz << " cm " << endl;
+}
Index: /tags/Mars-V0.9/mgeom/MGeomCorsikaCT.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomCorsikaCT.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomCorsikaCT.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MGeomCorsikaCT
+#define MARS_MGeomCorsikaCT
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGeomCorsikaCT : public MParContainer
+{
+private:
+
+    Float_t fCTx;  // X position of the CT center
+    Float_t fCTy;  // Y position of the CT center
+    Float_t fCTz;  // Z above high position of the CT center
+    Float_t fCTtheta; // 
+    Float_t fCTphi;   //
+    Float_t fCTdiam;  // Diameter where the Cph are stored at MMCs level
+    Float_t fCTfocal; // Focal of the CT
+
+public:
+
+    MGeomCorsikaCT(const char *name=NULL, const char *title=NULL);
+
+    void Print(Option_t *opt=NULL) const;
+
+    void Fill(Float_t ctx, Float_t cty, Float_t ctz,
+	      Float_t cttheta, Float_t ctphi,
+	      Float_t ctdiam, Float_t ctfocal);
+
+    Float_t GetCTx() { return fCTx; }
+    Float_t GetCTy() { return fCTy; }
+    Float_t GetCTz() { return fCTz; }
+
+    ClassDef(MGeomCorsikaCT, 1)  // class containing information about CTelescope
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mgeom/MGeomMirror.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomMirror.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomMirror.cc	(revision 9772)
@@ -0,0 +1,156 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 11/2002 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomMirror
+//
+// This is the base class of the Mirror geometry. 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MGeomMirror.h"
+
+#include <TRotation.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MGeomMirror);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes a Mirror geometry with 0 values, except for fMirrorID.
+//
+MGeomMirror::MGeomMirror(Int_t mir, const char *name, const char *title)
+    : fReflector(0)
+{
+    fName  = name  ? name  : "MGeomMirror";
+    fTitle = title ? title : "Storage container for  a mirror geometry";
+
+    fMirrorId=mir;   // the Mirror Id
+
+    fFocalDist=0.;   //  focal distance of that mirror [cm]
+    fSX=0.;          // curvilinear coordinate of mirror's center in X[cm]
+    fSY=0.;          // curvilinear coordinate of mirror's center in X[cm]
+    fX=0.;           // x coordinate of the center of the mirror [cm]
+    fY=0.;           // y coordinate of the center of the mirror [cm]
+    fZ=0.;           // z coordinate of the center of the mirror [cm]
+    fThetaN=0.;      // polar theta angle of the direction 
+                     //  where the mirror points to
+    fPhiN=0.;        // polar phi angle of the direction
+                     // where the mirror points to
+    fXN=0.;          // xn coordinate of the normal vector
+                     // in the center
+    fYN=0.;          // yn coordinate of the normal vector
+                     // in the center
+    fZN=0.;          // zn coordinate of the normal vector
+                     // in the center
+                     // Note: fXN^2*fYN^2*fZN^2 = 1
+    fDeviationX=0.;  // deviation in x [cm]
+    fDeviationY=0.;  // deviation in y [cm]
+                     // of the spot of a single mirror on the camera plane
+
+}
+
+// --------------------------------------------------------------------------
+//
+// DESCRIPTION MISSING: Please contact Oscar
+//
+void MGeomMirror::SetMirrorContent(Int_t mir, Float_t focal, Float_t curv_x,
+                                   Float_t curv_y, Float_t lin_x, Float_t lin_y,
+				   Float_t lin_z, Float_t theta, Float_t phi,
+				   Float_t x_n, Float_t y_n, Float_t z_n){
+    fMirrorId=mir;   // the Mirror Id
+
+    fFocalDist=focal;   //  focal distance of that mirror [cm]
+    fSX=curv_x;          // curvilinear coordinate of mirror's center in X[cm]
+    fSY=curv_y;          // curvilinear coordinate of mirror's center in X[cm]
+    fX=lin_x;           // x coordinate of the center of the mirror [cm]
+    fY=lin_y;           // y coordinate of the center of the mirror [cm]
+    fZ=lin_z;           // z coordinate of the center of the mirror [cm]
+    fThetaN=theta;      // polar theta angle of the direction 
+                     //  where the mirror points to
+    fPhiN=phi;        // polar phi angle of the direction
+                     // where the mirror points to
+    fXN=x_n;          // xn coordinate of the normal vector
+                     // in the center
+    fYN=y_n;          // yn coordinate of the normal vector
+                     // in the center
+    fZN=z_n;          // zn coordinate of the normal vector
+                     // in the center
+                     // Note: fXN^2*fYN^2*fZN^2 = 1
+}
+
+void MGeomMirror::SetMirrorDeviations(Float_t dev_x, Float_t dev_y)
+{
+    fDeviationX=dev_x;  // deviation in x [cm]
+    fDeviationY=dev_y;  // deviation in y [cm]
+                     // of the spot of a single mirror on the camera plane
+}
+
+// --------------------------------------------------------------------------
+//
+// Setting function to store the mirror reflectivity (ref) at different
+// wavelength (wav).
+//
+void MGeomMirror::SetReflectivity(const TArrayF &wav, const TArrayF &ref)
+{
+    if (fWavelength.GetSize()!=wav.GetSize() ||
+        fReflectivity.GetSize()!=ref.GetSize())
+    {
+        *fLog << err << dbginf << " fWavelength or fQE do not have ";
+        *fLog << "size of setting arrays" << endl;
+        return;
+    }
+
+    fWavelength = wav;
+    fReflectivity = ref;
+}
+
+TVector3 MGeomMirror::GetReflection(const TVector3 &star, Double_t dist)
+{
+    if (!fReflector)
+    {
+        fReflector = new TRotation; // unit matrix
+        fReflector->Rotate(TMath::Pi(), GetMirrorNorm());
+    }
+
+    // Reflect star on the mirror (done by a rotation
+    // around the normal vector of the mirror center
+    TVector3 light(star);
+    light *= *fReflector;
+
+    if (dist<0)
+        return light;
+
+    // calculate distance to the camera (stretch vector such, that
+    // its Z component is the distance between the camera and
+    // the mirror
+    const TVector3 &pos = GetMirrorCenter();
+    const Double_t d = (dist - pos.Z()) / light.Z();
+
+    return light*d + pos;
+}
Index: /tags/Mars-V0.9/mgeom/MGeomMirror.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomMirror.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomMirror.h	(revision 9772)
@@ -0,0 +1,67 @@
+#ifndef MARS_MGeomMirror
+#define MARS_MGeomMirror
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class TRotation;
+class MGeomMirror : public MParContainer
+{
+private:
+    Int_t   fMirrorId;     // the Mirror Id
+
+    Float_t fFocalDist;    // [cm] focal distance of that mirror
+    Float_t fSX;           // [cm] curvilinear coordinate of mirror's center in X
+    Float_t fSY;           // [cm] curvilinear coordinate of mirror's center in Y
+    Float_t fX;            // [cm] x coordinate of the center of the mirror
+    Float_t fY;            // [cm] y coordinate of the center of the mirror
+    Float_t fZ;            // [cm] z coordinate of the center of the mirror
+    Float_t fThetaN;       // polar theta angle of the direction where the mirror points to
+    Float_t fPhiN;         // polar phi angle of the direction where the mirror points to
+    Float_t fXN;           // xn coordinate of the normal vector in the center
+    Float_t fYN;           // yn coordinate of the normal vector in the center
+    Float_t fZN;           // zn coordinate of the normal vector in the center
+                           // Note: fXN^2*fYN^2*fZN^2 = 1
+    Float_t fDeviationX;   // [cm] deviation in x of the spot of a single mirror on the camera plane
+    Float_t fDeviationY;   // [cm] deviation in y of the spot of a single mirror on the camera plane
+
+    TArrayF fWavelength;   // List of wavelength
+    TArrayF fReflectivity; // Mirror reflectivity
+
+    TRotation *fReflector; //! Store this for acceleration
+
+public:
+    MGeomMirror(Int_t mir=-1, const char *name=NULL, const char *title=NULL);
+
+    Int_t GetMirrorId() const         { return fMirrorId;   }
+
+    void  SetMirrorContent(Int_t mir, Float_t focal, Float_t curv_x,
+                           Float_t curv_y, Float_t lin_x, Float_t lin_y,
+                           Float_t lin_z, Float_t theta, Float_t phi,
+                           Float_t x_n, Float_t y_n, Float_t z_n);
+    void  SetMirrorDeviations(Float_t dev_x, Float_t dev_y);
+
+    void  SetReflectivity(const TArrayF &wav, const TArrayF &ref);
+
+    void  SetArraySize(Int_t dim) { fWavelength.Set(dim); fReflectivity.Set(dim); }
+
+    TVector3 GetMirrorCenter() const { return TVector3(fX/100, fY/100, fZ/100); }
+    TVector3 GetMirrorNorm()   const { return TVector3(fXN, fYN, fZN); }
+
+    TVector3 GetReflection(const TVector3 &star, Double_t dist=-1);
+
+    ClassDef(MGeomMirror, 2)  // geometry class describing one mirror
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mgeom/MGeomPMT.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomPMT.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomPMT.cc	(revision 9772)
@@ -0,0 +1,70 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 11/2002 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomPMT
+//
+// This is the base class of the PMT characteristics. 
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomPMT.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MGeomPMT);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes a Mirror geometry with 0 values, except for fMirrorID.
+//
+MGeomPMT::MGeomPMT(Int_t pmt, const char *name, const char *title)
+    : fPMTId(pmt), fWavelength(0), fQE(0)
+{
+    fName  = name  ? name  : "MGeomPMT";
+    fTitle = title ? title : "Storage container for  a PMT characteristics";
+}
+
+// --------------------------------------------------------------------------
+//
+// DESCRIPTION MISSING Please contact Oscar
+//
+void MGeomPMT::SetPMTContent(Int_t pmt, const TArrayF &wav, const TArrayF &qe)
+{
+    if (fWavelength.GetSize()!=wav.GetSize() ||
+        fQE.GetSize()!=qe.GetSize())
+    {
+        *fLog << err << dbginf << " fWavelength or fQE do not have ";
+        *fLog << "size of setting arrays" << endl;
+        return;
+    }
+
+    fPMTId = pmt;
+
+    fWavelength = wav;
+    fQE = qe;
+}
Index: /tags/Mars-V0.9/mgeom/MGeomPMT.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomPMT.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomPMT.h	(revision 9772)
@@ -0,0 +1,34 @@
+#ifndef MARS_MGeomPMT
+#define MARS_MGeomPMT
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGeomPMT : public MParContainer
+{
+private:
+    Int_t   fPMTId;        // the PMT Id
+
+    TArrayF fWavelength;  // List of wavelength
+    TArrayF fQE;          // QE values
+
+public:
+
+    MGeomPMT(Int_t pmt=-1,const char *name=NULL, const char *title=NULL);
+
+    Int_t   GetPMTId() const         { return fPMTId;   }
+
+    void    SetArraySize(Int_t dim) { fWavelength.Set(dim); fQE.Set(dim); }
+
+    void    SetPMTContent(Int_t pmt, const TArrayF &wav, const TArrayF &qe);
+
+    ClassDef(MGeomPMT, 1)  // class containing information about PMTs
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mgeom/MGeomPix.cc
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomPix.cc	(revision 9772)
@@ -0,0 +1,172 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MGeomPix
+//
+// This container stores the geometry (position) information of
+// a single pixel together with the information about next neighbors.
+//
+// The BIT(22) and BIT(23) is used to flag the pixels in the outer
+// and outermost ring. Please don't use this bits in conjuction with
+// MGeomPix.
+//
+//
+// Version 1:
+// ----------
+//  - first implementation
+//
+// Version 2:
+// ----------
+//  - added fA
+//
+// Version 3:
+// ----------
+//  - added fAidx
+//
+//
+// FIXME: According to an agreement we have to change the name 'Id' to 'idx'
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomPix.h"
+
+#include <math.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MGeomPix);
+
+using namespace std;
+
+const Float_t MGeomPix::gsTan30 = tan(30/kRad2Deg);
+const Float_t MGeomPix::gsTan60 = tan(60/kRad2Deg);
+
+// --------------------------------------------------------------------------
+//
+// Initializes one pixel
+//
+MGeomPix::MGeomPix(Float_t x, Float_t y, Float_t r, UInt_t s, UInt_t a)
+{
+    //  default constructor
+    Set(x, y, r, s, a);
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes Next Neighbors.
+//
+// WARNING: This function is public, but it is not meant for user access.
+// It should only be used from geometry classes (like MGeomCam)
+//
+void MGeomPix::SetNeighbors(Short_t i0, Short_t i1, Short_t i2,
+                            Short_t i3, Short_t i4, Short_t i5)
+{
+    fNeighbors[0] = i0;
+    fNeighbors[1] = i1;
+    fNeighbors[2] = i2;
+    fNeighbors[3] = i3;
+    fNeighbors[4] = i4;
+    fNeighbors[5] = i5;
+
+    int i;
+    for (i=0; i<6; i++)
+        if (fNeighbors[i]<0)
+            break;
+
+    fNumNeighbors = i;
+
+    if (fNumNeighbors<5)
+        SetBit(kIsInOutermostRing);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the kIsOuterRing flag if this pixel has a outermost pixel
+//  as Next Neighbor and don't have the kIsOutermostRing flag itself.
+//
+void MGeomPix::CheckOuterRing(const MGeomCam &cam)
+{
+    if (IsInOutermostRing())
+        return;
+
+    for (int i=0; i<fNumNeighbors; i++)
+        if (cam[fNeighbors[i]].IsInOutermostRing())
+        {
+            SetBit(kIsInOuterRing);
+            return;
+        }
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the geometry information of one pixel.
+//
+void MGeomPix::Print(Option_t *opt) const
+{ 
+    //   information about a pixel
+    *fLog << all << "MPixGeom:  x= " << fX << "mm  y= " << fY << "mm ";
+    *fLog << "d= " << fD << "mm  A= " << fA << "mm²" << endl;
+}
+
+// ------------------------------------------------------------------------
+//
+// compute the distance of a point (px,py) to the Hexagon center in
+// MGeomPix coordinates. Return kTRUE if inside.
+//
+Bool_t MGeomPix::IsInside(Float_t px, Float_t py) const
+{
+    //
+    //  compute the distance of the Point to the center of the Hexagon
+    //
+    const Double_t dx = px-fX;
+
+    //
+    // Now check if point is outside of hexagon; just check x coordinate
+    // in three coordinate systems: the default one, in which two sides of
+    // the hexagon are paralel to the y axis (see camera displays) and two 
+    // more, rotated with respect to that one by +- 60 degrees.
+    //
+    if (TMath::Abs(dx)*2>fD)
+        return kFALSE;
+
+    const Double_t dy = py-fY;
+
+    const static Double_t cos60 = TMath::Cos(60/kRad2Deg);
+    const static Double_t sin60 = TMath::Sin(60/kRad2Deg);
+
+    const Double_t dx2 = dx*cos60 + dy*sin60;
+    if  (TMath::Abs(dx2)*2>fD)
+        return kFALSE;
+
+    const Double_t dx3 = dx*cos60 - dy*sin60;
+    if (TMath::Abs(dx3)*2>fD)
+        return kFALSE;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mgeom/MGeomPix.h
===================================================================
--- /tags/Mars-V0.9/mgeom/MGeomPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/MGeomPix.h	(revision 9772)
@@ -0,0 +1,90 @@
+#ifndef MARS_MGeomPix
+#define MARS_MGeomPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGeomCam;
+
+class MGeomPix : public MParContainer
+{ 
+private:
+    static const Float_t gsTan60; // tan(60/kRad2Deg);
+    static const Float_t gsTan30; // tan(30/kRad2Deg);
+
+    enum {
+        kIsInOutermostRing = BIT(22),
+        kIsInOuterRing     = BIT(23),
+        kUserBits          = 0x1fc000 // 14-21 are allowed
+    };
+
+    Float_t fX;            // [mm]   the x coordinate of the center
+    Float_t fY;            // [mm]   the y coordinate of the center
+    Float_t fD;            // [mm]   the d coordinate of the pixel (dist between two parallel sides)
+    Float_t fA;            // [mm^2] Area of the pixel
+
+    Byte_t  fNumNeighbors; // number of valid neighbors
+    Short_t fNeighbors[6]; // the IDs of the pixel next to it (we are assuming an hexagonal geometry)
+
+    UInt_t fSector;        // Number of sector the pixels corresponds to
+    UInt_t fAidx;          // Area index of the pixel
+
+public:
+    MGeomPix(Float_t x=0, Float_t y=0, Float_t d=0, UInt_t s=0, UInt_t aidx=0);
+
+    void Copy(TObject &obj) const
+    {
+        MGeomPix &pix = (MGeomPix&)obj;
+        pix.fX = fX;
+        pix.fY = fY;
+        pix.fD = fD;
+        pix.fA = fA;
+        pix.fNumNeighbors = fNumNeighbors;
+        pix.fSector = fSector;
+        pix.fAidx = fAidx;
+        for (int i=0; i<6; i++)
+            pix.fNeighbors[i] = fNeighbors[i];
+    }
+
+    void Print(Option_t *opt=NULL) const;
+
+    void Set(Float_t x, Float_t y, Float_t d, UInt_t s=0, UInt_t aidx=0) { fX=x; fY=y; fD=d; fA=d*d*gsTan60/2; fSector=s; fAidx=aidx; }
+
+    void SetNeighbors(Short_t i0=-1, Short_t i1=-1, Short_t i2=-1,
+                      Short_t i3=-1, Short_t i4=-1, Short_t i5=-1);
+
+    void CheckOuterRing(const MGeomCam &cam);
+
+    Float_t GetX() const  { return fX; }
+    Float_t GetY() const  { return fY; }
+    Float_t GetD() const  { return fD; }
+    Float_t GetL() const  { return fD*gsTan30; } // Length of one of the parallel sides
+    UInt_t  GetSector() const { return fSector; }
+
+    Float_t GetA() const    { return fA; /*fD*fD*gsTan60/2;*/ }
+    Int_t   GetAidx() const { return fAidx; }
+
+    Byte_t  GetNumNeighbors() const { return fNumNeighbors; }
+    Short_t GetNeighbor(Byte_t i) const { return fNeighbors[i]; }
+
+    Bool_t IsInOutermostRing() const { return TestBit(kIsInOutermostRing); }
+    Bool_t IsInOuterRing() const     { return TestBit(kIsInOuterRing); }
+
+    Bool_t IsInside(Float_t px, Float_t py) const;
+
+    /*
+     //
+     // These function are for future usage. They are not virtual in
+     // root by now.
+     //
+     void SetBit(UInt_t f, Bool_t set) { set ? TObject::SetBit(f) : TObject::ResetBit(f); }
+     void SetBit(UInt_t f)    { TObject::SetBit(f & kUserBits); }
+     void ResetBit(UInt_t f)  { TObject::ResetBit(f & kUserBits); }
+     void InvertBit(UInt_t f) { TObject InvertBit(f & kUserBits); }
+     */
+
+    ClassDef(MGeomPix, 3) // Geometry class describing the geometry of one pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/mgeom/Makefile
===================================================================
--- /tags/Mars-V0.9/mgeom/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mgeom/Makefile	(revision 9772)
@@ -0,0 +1,42 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Geom
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../MBase
+
+SRCFILES = MGeomPix.cc \
+           MGeomCam.cc \
+           MGeomCamCT1.cc \
+           MGeomCamCT1Daniel.cc \
+           MGeomCamMagic.cc \
+           MGeomCamMagicHG.cc \
+           MGeomCamMagic919.cc \
+           MGeomCamECO1000.cc \
+           MGeomCamECO1000HG.cc \
+           MGeomCorsikaCT.cc \
+	   MGeomMirror.cc \
+	   MGeomPMT.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mgui/GuiIncl.h
===================================================================
--- /tags/Mars-V0.9/mgui/GuiIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mgui/GuiIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mgui/GuiLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mgui/GuiLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mgui/GuiLinkDef.h	(revision 9772)
@@ -0,0 +1,10 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHexagon+;
+#pragma link C++ class MCamEvent+;
+
+#endif
Index: /tags/Mars-V0.9/mgui/MAitoff.cc
===================================================================
--- /tags/Mars-V0.9/mgui/MAitoff.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgui/MAitoff.cc	(revision 9772)
@@ -0,0 +1,86 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 7/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MAitoff
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAitoff.h"
+
+#include <TMath.h>
+#include <TMarker.h>
+#include <TVirtualPad.h>
+
+#include "MH.h"
+
+ClassImp(MAitoff);
+
+using namespace std;
+
+void MAitoff::Transform(Double_t lon, Double_t lat, Double_t &x, Double_t &y)
+{
+    Double_t b = lon;
+    Double_t sa = lat;
+
+    Double_t alpha2 = sa/kRad2Deg /2.;
+    Double_t delta = b/kRad2Deg;
+
+    Double_t r2 = sqrt(2.);
+    Double_t f = 2.*r2/TMath::Pi();
+    Double_t cdec = cos(delta);
+    Double_t denom = sqrt(1.+cdec*cos(alpha2));
+    x = cdec*sin(alpha2)*2.*r2/denom;
+    y = sin(delta);
+
+    x /= f/kRad2Deg;
+    y /= f/kRad2Deg;
+}
+
+void MAitoff::Draw(Option_t *)
+{
+    if (!gPad)
+        MH::MakeDefCanvas();
+
+    gPad->Range(-200, -80, 200, 80);
+
+    TMarker m;
+    Double_t x, y;
+
+    for (int i=-180; i<180; i+=3) { Transform( 60, i, x, y); m.DrawMarker(x, y); }
+    for (int i=-180; i<180; i+=3) { Transform( 30, i, x, y); m.DrawMarker(x, y); }
+    for (int i=-180; i<180; i+=3) { Transform(  0, i, x, y); m.DrawMarker(x, y); }
+    for (int i=-180; i<180; i+=3) { Transform(-30, i, x, y); m.DrawMarker(x, y); }
+    for (int i=-180; i<180; i+=3) { Transform(-60, i, x, y); m.DrawMarker(x, y); }
+
+    for (int i=-90; i<90; i++) { Transform(i, -180, x, y); m.DrawMarker(x, y); }
+    for (int i=-90; i<90; i++) { Transform(i, -135, x, y); m.DrawMarker(x, y); }
+    for (int i=-90; i<90; i++) { Transform(i,  -90, x, y); m.DrawMarker(x, y); }
+    for (int i=-90; i<90; i++) { Transform(i,  -45, x, y); m.DrawMarker(x, y); }
+    for (int i=-90; i<90; i++) { Transform(i,    0, x, y); m.DrawMarker(x, y); }
+    for (int i=-90; i<90; i++) { Transform(i,   45, x, y); m.DrawMarker(x, y); }
+    for (int i=-90; i<90; i++) { Transform(i,   90, x, y); m.DrawMarker(x, y); }
+    for (int i=-90; i<90; i++) { Transform(i,  135, x, y); m.DrawMarker(x, y); }
+    for (int i=-90; i<90; i++) { Transform(i,  180, x, y); m.DrawMarker(x, y); }
+}
Index: /tags/Mars-V0.9/mgui/MAitoff.h
===================================================================
--- /tags/Mars-V0.9/mgui/MAitoff.h	(revision 9772)
+++ /tags/Mars-V0.9/mgui/MAitoff.h	(revision 9772)
@@ -0,0 +1,31 @@
+#ifndef MARS_MAitoff
+#define MARS_MAitoff
+
+//////////////////////////////////////////////////////////////
+//
+//   MAitoff
+//
+//   A Hexagon for the MAGIC event display
+//
+//////////////////////////////////////////////////////////////
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TPad
+#include <TPad.h>
+#endif 
+
+class MAitoff
+{
+public:
+    static void Transform(Double_t lon, Double_t lat, Double_t &x, Double_t &y);
+
+    void Draw(Option_t *o="");
+
+    ClassDef(MAitoff, 1)    // A hexagon for MAGIC
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgui/MCamEvent.cc
===================================================================
--- /tags/Mars-V0.9/mgui/MCamEvent.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgui/MCamEvent.cc	(revision 9772)
@@ -0,0 +1,56 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MCamEvent
+//
+// A base class describing an event in the camera.
+//
+// If GetPixelContent returns kFALSE, it must not touch 'val'.
+//
+// You can derive a class in addition to TObject from MCamEvent, too.
+//
+// MCamEvent MUST be after TObject:
+//  ALLOWED:   class MyClass : public TObject, public MCamEvent
+//  FORBIDDEN: class MyClass : public MCamEvent, public TObject
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCamEvent.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MCamEvent);
+
+// --------------------------------------------------------------------------
+//
+// You can overwrite this function if you want the container to be
+// initialized by MGeomApply with the geometry. If it is not overloaded
+// it calls InitSize with the corresponding pixel number. If this information
+// is enough for you it is enough to overload InitSize.
+//
+void MCamEvent::Init(const MGeomCam &geom)
+{
+    InitSize(geom.GetNumPixels());
+}
Index: /tags/Mars-V0.9/mgui/MCamEvent.h
===================================================================
--- /tags/Mars-V0.9/mgui/MCamEvent.h	(revision 9772)
+++ /tags/Mars-V0.9/mgui/MCamEvent.h	(revision 9772)
@@ -0,0 +1,23 @@
+#ifndef MARS_MCamEvent
+#define MARS_MCamEvent
+
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+
+class MGeomCam;
+
+class MCamEvent
+{
+public:
+    virtual Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const = 0;
+    virtual void   DrawPixelContent(Int_t num) const = 0;
+
+    virtual void   Init(const MGeomCam &geom);
+    virtual void   InitSize(const UInt_t i) { } // Used by MGeomApply see Init()
+
+    ClassDef(MCamEvent, 0) // A camera event
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgui/MHexagon.cc
===================================================================
--- /tags/Mars-V0.9/mgui/MHexagon.cc	(revision 9772)
+++ /tags/Mars-V0.9/mgui/MHexagon.cc	(revision 9772)
@@ -0,0 +1,348 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// MHexagon                                                                 //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHexagon.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TVirtualPad.h>  // gPad
+
+#include "MGeomPix.h"     // GetX
+
+ClassImp(MHexagon);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+//   default constructor for MHexagon
+//
+MHexagon::MHexagon()
+{
+}
+
+// ------------------------------------------------------------------------
+//
+//    normal constructor for MHexagon
+//
+MHexagon::MHexagon(Float_t x, Float_t y, Float_t d)
+: TAttLine(1, 1, 1), TAttFill(0, 1001), fX(x), fY(y), fD(d)
+{
+}
+
+// ------------------------------------------------------------------------
+//
+//    normal constructor for MHexagon
+//
+MHexagon::MHexagon(const MGeomPix &pix)
+: TAttLine(1, 1, 1), TAttFill(0, 1001)
+{
+    fX = pix.GetX();
+    fY = pix.GetY();
+    fD = pix.GetD();
+}
+
+// ------------------------------------------------------------------------
+//
+//    copy constructor for MHexagon
+//
+MHexagon::MHexagon(const MHexagon &hexagon) : TObject(hexagon), TAttLine(hexagon), TAttFill(hexagon)
+{
+    fX = hexagon.fX;
+    fY = hexagon.fY;
+    fD = hexagon.fD;
+} 
+
+// ------------------------------------------------------------------------
+//
+//     copy this hexagon to hexagon
+//
+void MHexagon::Copy(TObject &obj)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+const
+#endif
+{
+    MHexagon &hex = (MHexagon&) obj;
+
+    TObject::Copy(obj);
+    TAttLine::Copy(hex);
+    TAttFill::Copy(hex);
+
+    hex.fX = fX;
+    hex.fY = fY;
+    hex.fD = fD;
+}
+
+// ------------------------------------------------------------------------
+//
+// compute the distance of a point (px,py) to the Hexagon
+// this functions needed for graphical primitives, that
+// means without this function you are not able to interact
+// with the graphical primitive with the mouse!!!
+//
+// All calcutations are running in pixel coordinates
+//
+Int_t MHexagon::DistancetoPrimitive(Int_t px, Int_t py, Float_t conv)
+{
+    //
+    //  compute the distance of the Point to the center of the Hexagon
+    //
+    const Int_t pxhex = gPad->XtoAbsPixel(fX*conv);
+    const Int_t pyhex = gPad->YtoAbsPixel(fY*conv);
+
+    const Double_t x = TMath::Abs(px-pxhex);
+    const Double_t y = TMath::Abs(py-pyhex);
+
+    const Double_t disthex = TMath::Sqrt(x*x + y*y);
+
+    if (disthex==0)
+        return 0;
+
+    const Double_t cosa = x / disthex;
+    const Double_t sina = y / disthex;
+
+    //
+    // comput the distance of hexagon center to pixel border
+    //
+    const Double_t dx = fD/2 * cosa;
+    const Double_t dy = fD/2 * sina;
+
+    const Int_t pxborder = gPad->XtoAbsPixel((fX + dx)*conv);
+    const Int_t pyborder = gPad->YtoAbsPixel((fY + dy)*conv);
+
+    const Double_t bx = pxhex-pxborder;
+    const Double_t by = pyhex-pyborder;
+
+    const Double_t distborder = TMath::Sqrt(bx*bx + by*by);
+
+    //
+    //  compute the distance from the border of Pixel
+    //  here in the first implementation is just circle inside
+    //
+    return distborder < disthex ? (int)((disthex-distborder)/conv+1) : 0;
+}
+
+// ------------------------------------------------------------------------
+//
+// compute the distance of a point (px,py) to the Hexagon center in world
+// coordinates. Return -1 if inside.
+//
+Float_t MHexagon::DistanceToPrimitive(Float_t px, Float_t py)
+{
+    //
+    //  compute the distance of the Point to the center of the Hexagon
+    //
+    const Double_t dx = px-fX;
+    const Double_t dy = py-fY;
+    const Double_t disthex = TMath::Sqrt(dx*dx + dy*dy);
+
+    //
+    // Now check if point is outside of hexagon; just check x coordinate
+    // in three coordinate systems: the default one, in which two sides of
+    // the hexagon are paralel to the y axis (see camera displays) and two 
+    // more, rotated with respect to that one by +- 60 degrees.
+    //
+
+    if (TMath::Abs(dx) > fD/2.)
+      return disthex;
+
+    const static Double_t cos60 = TMath::Cos(60/kRad2Deg);
+    const static Double_t sin60 = TMath::Sin(60/kRad2Deg);
+
+    const Double_t dx2 = dx*cos60 + dy*sin60;
+
+    if  (TMath::Abs(dx2) > fD/2.)
+      return disthex;
+
+    const Double_t dx3 = dx*cos60 - dy*sin60;
+
+    if  (TMath::Abs(dx3) > fD/2.)
+      return disthex;
+
+    return -1;
+}
+
+/*
+Float_t MHexagon::DistanceToPrimitive(Float_t px, Float_t py)
+{
+    //
+    //  compute the distance of the Point to the center of the Hexagon
+    //
+    const Double_t dx = px-fX;
+    const Double_t dy = py-fY;
+
+    const Double_t disthex = TMath::Sqrt(dx*dx + dy*dy);
+
+    //
+    //  compute the distance from the border of Pixel
+    //  here in the first implementation is just circle outside
+    //
+    return fD*0.5772 < disthex ? disthex-fD*0.5772 : -1;
+    //
+    // FIXME: this approximate method results in some photons being 
+    // assigned to two or even three different pixels.
+    //
+}
+*/
+
+// ------------------------------------------------------------------------
+//
+//  Draw this ellipse with new coordinate
+//
+void MHexagon::DrawHexagon(Float_t x, Float_t y, Float_t d)
+{ 
+    MHexagon *newhexagon = new MHexagon(x, y, d);
+
+    TAttLine::Copy(*newhexagon);
+    TAttFill::Copy(*newhexagon);
+
+    newhexagon->SetBit(kCanDelete);
+    newhexagon->AppendPad();
+}
+
+/*
+// ------------------------------------------------------------------------
+//
+//  This is the first test of implementing a clickable interface
+//  for one pixel
+//
+void MHexagon::ExecuteEvent(Int_t event, Int_t px, Int_t py)
+{
+    switch (event)
+    {
+    case kButton1Down:
+        cout << endl << "kButton1Down" << endl;
+        SetFillColor(2);
+        gPad->Modified();
+        break;
+
+    case kButton1Double:
+        SetFillColor(0);
+        gPad->Modified();
+        break;
+        //  case kMouseEnter:
+        //     printf ("\n Mouse inside object \n" ) ;
+        //     break;
+    }
+}
+*/
+
+// ------------------------------------------------------------------------
+//
+//  list this hexagon with its attributes
+//
+void MHexagon::ls(const Option_t *) const
+{
+    TROOT::IndentLevel();
+    Print();
+}
+
+// ------------------------------------------------------------------------
+//
+//  paint this hexagon with its attribute
+//
+void MHexagon::Paint(Option_t *)
+{
+    PaintHexagon(fX, fY, fD);
+}
+
+// ------------------------------------------------------------------------
+//
+//  draw this hexagon with the coordinates
+//
+void MHexagon::PaintHexagon(Float_t inX, Float_t inY, Float_t inD)
+{ 
+    const Int_t np = 6;
+
+    const Float_t dx[np+1] = { .5   , 0.    , -.5   , -.5   , 0.    ,  .5   , .5    };
+    const Float_t dy[np+1] = { .2886,  .5772,  .2886, -.2886, -.5772, -.2886, .2886 };
+
+    //
+    //  calculate the positions of the pixel corners
+    //
+    Float_t x[np+1], y[np+1];
+    for (Int_t i=0; i<np+1; i++)
+    {
+        x[i] = inX + dx[i]*inD;
+        y[i] = inY + dy[i]*inD;
+    }
+
+    TAttLine::Modify();    // Change line attributes only if neccessary
+    TAttFill::Modify();    // Change fill attributes only if neccessary
+
+    //
+    //   paint the pixel
+    //
+    if (GetFillColor())
+        gPad->PaintFillArea(np, x, y);
+
+    if (GetLineStyle())
+        gPad->PaintPolyLine(np+1, x, y);
+}
+
+// ------------------------------------------------------------------------
+//
+//  print/dump this hexagon with its attributes
+//
+void MHexagon::Print(Option_t *) const
+{
+    cout << "MHexagon: ";
+    cout << "x=" << fX << "mm y=" << fY << "mm r=" << fD << "mm" << endl;
+
+    cout << " Line:";
+    cout << " Color=" << GetLineColor() << ",";
+    cout << " Style=" << GetLineStyle() << ",";
+    cout << " Width=" << GetLineWidth() << endl;
+    cout << " Fill:";
+    cout << " Color=" << GetFillColor() << ",";
+    cout << " Style=" << GetFillStyle() << endl;
+}
+
+// ------------------------------------------------------------------------
+//
+// Save primitive as a C++ statement(s) on output stream out
+//
+void MHexagon::SavePrimitive(ofstream &out, Option_t *)
+{
+    if (gROOT->ClassSaved(Class()))
+       out << "   ";
+    else
+       out << "   MHexagon *";
+
+    out << "hexagon = new MHexagon(" << fX << "," << fY << "," << fD << ");" << endl;
+
+    SaveFillAttributes(out, "hexagon");
+    SaveLineAttributes(out, "hexagon");
+
+    out << "   hexagon->Draw();" << endl;
+}
+
Index: /tags/Mars-V0.9/mgui/MHexagon.h
===================================================================
--- /tags/Mars-V0.9/mgui/MHexagon.h	(revision 9772)
+++ /tags/Mars-V0.9/mgui/MHexagon.h	(revision 9772)
@@ -0,0 +1,75 @@
+#ifndef MARS_MHexagon
+#define MARS_MHexagon
+
+//////////////////////////////////////////////////////////////
+//
+//   MHexagon
+//
+//   A Hexagon for the MAGIC event display
+//
+//////////////////////////////////////////////////////////////
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif 
+
+#ifndef ROOT_TAttLine
+#include <TAttLine.h>
+#endif 
+
+#ifndef ROOT_TAttFill
+#include <TAttFill.h>
+#endif 
+
+class MGeomPix;
+
+class MHexagon : public TObject, public TAttLine, public TAttFill
+{
+protected:
+
+    Float_t fX;  // X coordinate  of center
+    Float_t fY;  // Y coordinate  of center
+    Float_t fD;  // diameter D or better distance between opposite sides
+
+public:
+
+    MHexagon();
+    MHexagon(Float_t x, Float_t y, Float_t d);
+    MHexagon(const MGeomPix &pix);
+    MHexagon(const MHexagon &hexagon);
+
+    virtual void  Copy(TObject &hexagon)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+const
+#endif
+        ;
+
+    Int_t DistancetoPrimitive(Int_t px, Int_t py, Float_t conv);
+    virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)
+    {
+        return DistancetoPrimitive(px, py, 1);
+    }
+    virtual Float_t DistanceToPrimitive(Float_t px, Float_t py);
+    virtual void  DrawHexagon(Float_t x, Float_t y, Float_t d);
+
+    //virtual void  ExecuteEvent(Int_t event, Int_t px, Int_t py);
+
+    virtual void  ls(const Option_t *Option="") const;
+    virtual void  Paint(Option_t *Option="");
+    virtual void  PaintHexagon(Float_t x, Float_t y, Float_t d);
+    virtual void  Print(Option_t *Option="") const; // *MENU*
+    virtual void  SavePrimitive(ofstream &out, Option_t *);
+
+    Float_t GetX() const { return fX; }
+    Float_t GetY() const { return fY; }
+    Float_t GetD() const { return fD; }
+
+    ClassDef(MHexagon, 1)    // A hexagon for MAGIC
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mgui/Makefile
===================================================================
--- /tags/Mars-V0.9/mgui/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mgui/Makefile	(revision 9772)
@@ -0,0 +1,32 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Gui
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgeom
+
+SRCFILES = MHexagon.cc \
+	   MCamEvent.cc
+           
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mhbase/HBaseIncl.h
===================================================================
--- /tags/Mars-V0.9/mhbase/HBaseIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/HBaseIncl.h	(revision 9772)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mhbase/HBaseLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mhbase/HBaseLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/HBaseLinkDef.h	(revision 9772)
@@ -0,0 +1,17 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MFillH+;
+
+#pragma link C++ class MH+;
+#pragma link C++ class MH3+;
+#pragma link C++ class MHArray+;
+#pragma link C++ class MHMatrix+;
+
+#pragma link C++ class MBinning+;
+#pragma link C++ class MWeight+;
+
+#endif
Index: /tags/Mars-V0.9/mhbase/MBinning.cc
===================================================================
--- /tags/Mars-V0.9/mhbase/MBinning.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MBinning.cc	(revision 9772)
@@ -0,0 +1,553 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 01/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MBinning
+//
+// This is a MParCOntainer storing a binning for a histogram. Doing this
+// you are able to distribute a single binning to several histograms
+// in your parameter list.
+//
+// In some classes the title of the container is used to set the
+// axis-title of the corresponding axis in your histogram.
+//
+// For all the features supported see the function descriptions in
+//  MBinning and MH
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MBinning.h"
+
+#include <ctype.h>      // tolower
+#include <fstream>
+
+#include <TH1.h>        // InheritsFrom
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MH.h"
+
+ClassImp(MBinning);
+
+using namespace std;
+
+const TString MBinning::gsDefName  = "MBinning";
+const TString MBinning::gsDefTitle = "Container describing the binning of an axis";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title only. Typically you won't
+// need to change this.
+//
+MBinning::MBinning(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetEdges(10, 0, 1);
+    fType = kIsDefault;
+}
+
+// --------------------------------------------------------------------------
+//
+// Instantiate MBinning with nbins number of bins between lo (lower edge)
+// and hi (upper edge), name name and title title.
+//
+MBinning::MBinning(Int_t nbins, Axis_t lo, Axis_t hi, const char *name, const char *opt, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetEdges(nbins, lo, hi, opt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Search in the parameter list for the binning with name "name". If found,
+// set the edges and title accordingly. Default is name of object.
+// return kTRUE if object found, kFALSE otherwise.
+//
+Bool_t MBinning::SetEdges(const MParList &list, const char *name)
+{
+    MBinning *bins = (MBinning*)list.FindObject(name ? name : fName.Data(), "MBinning");
+    if (!bins)
+        return kFALSE;
+
+    SetEdges(*bins);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the edges stored in MBinning from the TAxis axe
+//
+void MBinning::SetEdges(const TAxis &axe)
+{
+    const TArrayD &arr = *axe.GetXbins();
+    if (arr.GetSize()>0)
+    {
+        SetEdges(arr);
+        return;
+    }
+
+    SetEdges(axe.GetNbins(), axe.GetXmin(), axe.GetXmax());
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new upper edge to the edges stored in MBinning. The new upper
+// edge must be greater than the current greatest. Using this you can
+// enhance a histogram bin-by-bin, eg:
+//   TH1F h("", "", 2, 0, 1);
+//   MBinning b;
+//   b.SetEdges(h);
+//   b.AddEdge(2);
+//   b.Apply(h);
+//   b.AddEdge(3);
+//   b.Apply(h);
+//   [...]
+//
+void MBinning::AddEdge(Axis_t up)
+{
+    const Int_t n = fEdges.GetSize();
+
+    if (up<=fEdges[n-1])
+    {
+        *fLog << warn << dbginf << "WARNING - New upper edge not greater than old upper edge... ignored." << endl;
+        return;
+    }
+
+    fEdges.Set(n+1);
+    fEdges[n] = up;
+
+    fType = kIsUserArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// Removes the first edge
+//
+void MBinning::RemoveFirstEdge()
+{
+    const Int_t n = fEdges.GetSize();
+    for (int i=0; i<n-1; i++)
+        fEdges[i] = fEdges[i+1];
+    fEdges.Set(n-1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Removes the last edge
+//
+void MBinning::RemoveLastEdge()
+{
+    fEdges.Set(fEdges.GetSize()-1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the edges in MBinning from a histogram-axis. Which axis is
+// specified by axis ('x', 'y', 'z')
+//
+void MBinning::SetEdges(const TH1 &h, const Char_t axis)
+{
+    switch (tolower(axis))
+    {
+    case 'x':
+        SetEdges(*h.GetXaxis());
+        return;
+    case 'y':
+        SetEdges(*h.GetYaxis());
+        return;
+    case 'z':
+        SetEdges(*h.GetZaxis());
+        return;
+    default:
+        *fLog << warn << "MBinning::SetEdges: Axis '" << axis << "' unknown... using x." << endl;
+        SetEdges(*h.GetXaxis());
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the number of bins <nbins> (not the number of edges), the
+// lowest <lo> and highest <up> Edge (of your histogram)
+//
+void MBinning::SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up)
+{
+    const Double_t binsize = nbins<=0 ? 0 : (up-lo)/nbins;
+    fEdges.Set(nbins+1);
+    for (int i=0; i<=nbins; i++)
+        fEdges[i] = binsize*i + lo;
+
+    fType = kIsLinear;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set edged from text. With the following structure:
+//
+//     n lo hi [type [title]]
+//
+//  n:  number of bins
+//  lo: lowest edge
+//  hi: highest edge
+//  type: "lin" <default>, "log", "cos" (without quotationmarks)
+//  title: Whatever the title might be
+//
+// For example:
+//   SetEdgesRaw("12 0 1 lin This is the title");
+//
+Bool_t MBinning::SetEdgesRaw(const char *txt)
+{
+    Int_t   nbins  = 0;
+    Float_t loedge = 0;
+    Float_t upedge = 0;
+    Int_t   len    = 0;
+    if (3!=sscanf(txt, " %d %f %f %n", &nbins, &loedge, &upedge, &len))
+    {
+        *fLog << warn << GetDescriptor() << "::SetEdges: Not enough arguments... ignored." << endl;
+        return kFALSE;
+    }
+
+    if (loedge>=upedge)
+    {
+        *fLog << warn << GetDescriptor() << "::SetEdges: Lowest edge >= highest edge... ignored." << endl;
+        return kFALSE;
+    }
+
+    TString str(txt);
+    str.Remove(0, len);
+    str = str.Strip(TString::kBoth);
+
+    TString typ;
+    Ssiz_t pos = str.First(' ');
+    if (pos>=0)
+    {
+        typ = str(0, pos);
+        if (typ!=(TString)"lin" && typ!=(TString)"log" && typ!=(TString)"cos")
+        {
+            *fLog << warn << GetDescriptor() << "::SetEdges: Type " << typ << " unknown... ignored." << endl;
+            return kFALSE;
+        }
+    }
+
+    SetEdges(nbins, loedge, upedge, typ.Data());
+
+    str = str.Strip(TString::kBoth);
+
+    if (!str.IsNull())
+        fTitle = str;
+
+    return kTRUE;
+}
+/*
+// --------------------------------------------------------------------------
+//
+// Set edged from text. With the following structure:
+//
+//     n= lo= hi= type= title="my title"
+//
+//  n:  number of bins
+//  lo: lowest edge
+//  hi: highest edge
+//  type: "lin" <default>, "log", "cos" (without quotationmarks)
+//  title: Whatever the title might be
+//
+// For example:
+//   SetEdgesRaw("12 0 1 lin This is the title");
+//
+Bool_t MBinning::SetEdgesRaw(const char *txt)
+{
+    Int_t   nbins  = 0;
+    Float_t loedge = 0;
+    Float_t upedge = 0;
+    Int_t   len    = 0;
+    if (3!=sscanf(txt, " %d %f %f %n", &nbins, &loedge, &upedge, &len))
+    {
+        *fLog << warn << GetDescriptor() << "::SetEdges: Not enough arguments... ignored." << endl;
+        return kFALSE;
+    }
+
+    if (loedge>=upedge)
+    {
+        *fLog << warn << GetDescriptor() << "::SetEdges: Lowest edge >= highest edge... ignored." << endl;
+        return kFALSE;
+    }
+
+    TString str(txt);
+    str.Remove(0, len);
+    str = str.Strip(TString::kBoth);
+
+    TString typ;
+    Ssiz_t pos = str.First(' ');
+    if (pos>=0)
+    {
+        typ = str(0, pos);
+        if (typ!=(TString)"lin" && typ!=(TString)"log" && typ!=(TString)"cos")
+        {
+            *fLog << warn << GetDescriptor() << "::SetEdges: Type " << typ << " unknown... ignored." << endl;
+            return kFALSE;
+        }
+    }
+
+    SetEdges(nbins, loedge, upedge, typ.Data());
+
+    str = str.Strip(TString::kBoth);
+
+    if (!str.IsNull())
+        fTitle = str;
+
+    return kTRUE;
+}
+*/
+// --------------------------------------------------------------------------
+//
+// Calls SetEdgesLog if opt contains "log"
+// Calls SetEdgesCos if opt contains "cos"
+// Calls SetEdges in all other cases
+//
+void MBinning::SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up, const char *opt)
+{
+    const TString o(opt);
+    if (o.Contains("log", TString::kIgnoreCase))
+    {
+        SetEdgesLog(nbins, lo, up);
+        return;
+    }
+    if (o.Contains("cos", TString::kIgnoreCase))
+    {
+        SetEdgesCos(nbins, lo, up);
+        return;
+    }
+    SetEdges(nbins, lo, up);
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the number of bins <nbins> (not the number of edges), the
+// lowest <lo> and highest <up> Edge (of your histogram)
+//
+void MBinning::SetEdgesLog(const Int_t nbins, const Axis_t lo, Axis_t up)
+{
+    // if (lo==0) ...
+
+    const Double_t binsize = log10(up/lo)/nbins;
+    fEdges.Set(nbins+1);
+    for (int i=0; i<=nbins; i++)
+        fEdges[i] = pow(10, binsize*i) * lo;
+
+    fType = kIsLogarithmic;
+}
+
+// --------------------------------------------------------------------------
+//
+// Specify the number of bins <nbins> (not the number of edges), the
+// lowest [deg] <lo> and highest [deg] <up> Edge (of your histogram)
+//
+void MBinning::SetEdgesCos(const Int_t nbins, const Axis_t lo, Axis_t up)
+{
+    // if (lo==0) ...
+    const Axis_t ld = lo/kRad2Deg;
+    const Axis_t ud = up/kRad2Deg;
+
+    const Double_t binsize = (cos(ld)-cos(ud))/nbins;
+    fEdges.Set(nbins+1);
+    for (int i=0; i<=nbins; i++)
+        fEdges[i] = acos(cos(ld)-binsize*i)*kRad2Deg;
+
+    fType = kIsCosinic;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply this binning to the given histogram.
+// (By definition this works only for 1D-histograms. For 2D- and 3D-
+//  histograms use MH::SetBinning directly)
+//
+void MBinning::Apply(TH1 &h) const
+{
+    if (h.InheritsFrom("TH2") || h.InheritsFrom("TH3"))
+    {
+        *fLog << warn << "MBinning::Apply: '" << h.GetName() << "' is not a basic TH1 object... no binning applied." << endl;
+        return;
+    }
+
+    MH::SetBinning(&h, this);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print binning.
+//
+void MBinning::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ": nbins=" << GetNumBins() << " [";
+    *fLog << GetEdgeLo() << ", " << GetEdgeHi() << "] ";
+    switch (fType)
+    {
+    case kIsDefault:     *fLog << "deafult"; break;
+    case kIsLinear:      *fLog << "linear"; break;
+    case kIsLogarithmic: *fLog << "logarithmic"; break;
+    case kIsCosinic:     *fLog << "consinic"; break;
+    case kIsUserArray:   *fLog << "user-array"; break;
+    }
+    *fLog << ">";
+
+    if (fTitle!=gsDefTitle)
+        *fLog << " title=" << fTitle;
+
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MBinning::StreamPrimitive(ofstream &out) const
+{
+    out << "   MBinning " << GetUniqueName();
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl;
+
+    if (IsDefault())
+        return;
+
+    if (IsLinear() || IsLogarithmic() || IsCosinic())
+    {
+        out << "   " << GetUniqueName() << ".SetEdges";
+        if (IsLogarithmic())
+            out << "Log";
+        if (IsCosinic())
+            out << "Cos";
+        out << "(" << GetNumBins() << ", " << GetEdgeLo() << ", " << GetEdgeHi() << ");" << endl;
+        return;
+    }
+
+    out << "   {" << endl;
+    out << "      TArrayD dummy;" << endl;
+    for (int i=0; i<GetNumEdges(); i++)
+        out << "      dummy[" << i << "]=" << GetEdges()[i] << ";" << endl;
+    out << "      " << GetUniqueName() << ".SetEdges(dummy);" << endl;
+    out << "   }" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Allows reading a binning from resource files. The structure is as follows
+//
+Int_t MBinning::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    UInt_t  nbins  = GetNumBins();
+    Float_t edgelo = GetEdgeLo();
+    Float_t edgehi = GetEdgeHi();
+    TString type;
+    if (IsEnvDefined(env, prefix, "NumBins", print))
+    {
+        nbins = GetEnvValue(env, prefix, "NumBins", GetNumBins());
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "EdgeLo", print))
+    {
+        edgelo = GetEnvValue(env, prefix, "EdgeLo", GetEdgeLo());
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "EdgeHi", print))
+    {
+        edgehi = GetEnvValue(env, prefix, "EdgeHi", GetEdgeHi());
+        rc = kTRUE;
+    }
+    if (rc==kTRUE && (type==kIsUserArray || type==kIsDefault))
+        type = kIsLinear;
+
+    if (IsEnvDefined(env, prefix, "Type", print))
+    {
+        type = GetEnvValue(env, prefix, "Type", "lin");
+        if (type!=(TString)"lin" && type!=(TString)"log" && type!=(TString)"cos")
+        {
+            *fLog << warn << GetDescriptor() << "::ReadEnv - WARNING: Type is not lin, log nor cos... assuming lin." << endl;
+            type = "lin";
+        }
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Edges", print))
+    {
+        if (rc==kTRUE)
+            *fLog << warn << GetDescriptor() << "::ReadEnv - WARNING: 'Edges' found... ignoring any 'NumBins', 'EdgeLo' and 'EdgeHi'" << endl;
+
+        const TString type = GetEnvValue(env, prefix, "Edges", "");
+        //type = kIsUserArray;
+        /* MISSING */
+        rc = kTRUE;
+        *fLog << err << " SORRY USER ARRAY NOT YET IMPLEMENTED" << endl;
+        return kERROR;
+    }
+
+    const Bool_t raw = IsEnvDefined(env, prefix, "Raw", print);
+    //const Bool_t fullbins    = IsEnvDefined(env, prefix, "Binning", print);
+    if (!raw && /*!fullbins &&*/ rc==kTRUE)
+        SetEdges(nbins, edgelo, edgehi, type.Data());
+
+    if (rc==kTRUE)
+        *fLog << warn << GetDescriptor() << "::ReadEnv - WARNING: 'Binning' found... ignoring any 'NumBins', 'EdgeLo', 'EdgeHi' and 'Edges'" << endl;
+
+    if (IsEnvDefined(env, prefix, "Title", print))
+    {
+        fTitle = GetEnvValue(env, prefix, "Title", gsDefTitle.Data());
+        rc = kTRUE;
+    }
+
+    if (raw)
+    {
+        const TString txt = GetEnvValue(env, prefix, "Raw", "");
+        if (!SetEdgesRaw(txt.Data()))
+            return kERROR;
+    }
+/*
+    if (fullbins)
+    {
+        TString txt = GetEnvValue(env, prefix, "Binning", "");
+        SetEdgesRaw(txt.Data());
+    }
+   */
+
+    return rc;
+}
Index: /tags/Mars-V0.9/mhbase/MBinning.h
===================================================================
--- /tags/Mars-V0.9/mhbase/MBinning.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MBinning.h	(revision 9772)
@@ -0,0 +1,115 @@
+#ifndef MARS_MBinning
+#define MARS_MBinning
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TH1;
+class TAxis;
+
+class MParList;
+
+class MBinning : public MParContainer
+{
+public:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+private:
+
+    TArrayD fEdges;
+
+    Byte_t  fType;
+
+    void StreamPrimitive(ofstream &out) const;
+
+    enum {
+        kIsDefault,
+        kIsLinear,
+        kIsLogarithmic,
+        kIsCosinic,
+        kIsUserArray
+    };
+
+public:
+    MBinning(const char *name=NULL, const char *title=NULL);
+    MBinning(Int_t nbins, Axis_t lo, Axis_t hi, const char *name=0, const char *opt="", const char *title=NULL);
+    MBinning(const MBinning &bins) { SetEdges(bins); }
+
+    void Copy(TObject &named) const
+    {
+        MBinning &bins = (MBinning&)named;
+        bins.SetEdges(*this);
+    }
+
+    void SetEdges(const TArrayD &arr)
+    {
+        fEdges = arr;
+        fType  = kIsUserArray;
+    }
+
+    Bool_t SetEdges(const MParList &list, const char *name=0);
+    Bool_t SetEdgesRaw(const char *txt);
+    //Bool_t SetEdges(const char *txt);
+    void SetEdges(const TAxis &axe);
+    void SetEdges(const MBinning &bins) { SetEdges(bins.fEdges); fType = bins.fType; fTitle = bins.fTitle; }
+    void SetEdges(const TH1 &h, const Char_t axis='x');
+    void SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up);
+    void SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up, const char *opt);
+    void SetEdgesLog(const Int_t nbins, const Axis_t lo, Axis_t up);
+    void SetEdgesCos(const Int_t nbins, const Axis_t lo, Axis_t up);
+
+    Int_t FindLoEdge(Double_t val) const
+    {
+        if (val<GetEdgeLo() || val>=GetEdgeHi())
+            return -1;
+
+	for (int i=1; i<fEdges.GetSize(); i++)
+        {
+            if (fEdges[i] >= val)
+                return i-1;
+        }
+        return -1;
+    }
+    Int_t FindHiEdge(Double_t val) const
+    {
+        const Int_t i = FindLoEdge(val);
+        return i<0 ? -1 : i+1;
+    }
+
+    Double_t GetEdgeLo() const { return fEdges[0]; }
+    Double_t GetEdgeHi() const { return fEdges[fEdges.GetSize()-1]; }
+
+    Int_t GetNumEdges() const  { return fEdges.GetSize(); }
+    Int_t GetNumBins() const   { return fEdges.GetSize()-1; }
+
+    Double_t *GetEdges() const { return (Double_t*)fEdges.GetArray(); }
+    const TArrayD &GetEdgesD() const { return fEdges; }
+
+    void AddEdge(Axis_t up);
+    void RemoveFirstEdge();
+    void RemoveLastEdge();
+
+    Bool_t IsLinear() const      { return fType==kIsLinear; }
+    Bool_t IsLogarithmic() const { return fType==kIsLogarithmic; }
+    Bool_t IsCosinic() const     { return fType==kIsCosinic; }
+    Bool_t IsDefault() const     { return fType==kIsDefault; }
+    Bool_t IsUserArray() const   { return fType==kIsUserArray; }
+
+    Bool_t HasTitle() const      { return gsDefTitle!=fTitle; }
+
+    void Apply(TH1 &) const;
+
+    void Print(Option_t *o="") const;
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MBinning, 1) //Container to store the binning of a histogram
+};
+
+#endif
Index: /tags/Mars-V0.9/mhbase/MFillH.cc
===================================================================
--- /tags/Mars-V0.9/mhbase/MFillH.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MFillH.cc	(revision 9772)
@@ -0,0 +1,642 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MFillH
+//
+//  This is a common interface (task) to fill mars histograms. Every mars
+//  histogram which is derived from MH can be filled with this task.
+//
+//  There are two options to use:
+//
+//  1) You specifiy the parameter container with which data the
+//     histogram container should be filled, and the histogram container
+//     which has to be filled. This can be done by either specifing the
+//     name of the objects in the parameter list or by specifiing a pointer
+//     to the object. (s. Constructor)
+//
+//  2) You specify the name and/or type of the histogram to become filled.
+//     Any other action imust be taken by the histogram class.
+//
+//  PreProcess: In the preprocessing of this task we setup all pointers
+//              to instances which are needed and call FillSetup of the
+//              histogram class with the parameter list as an argument.
+//
+//  Process: The process function calls the Fill member function of the
+//           histogram class instance (inheriting from MH) with either
+//           a NULL pointer or a pointer to the corresponding container
+//           as an argument.
+//
+// To use a weight for each event filled in a histogram call
+// SetWeight(). You can eithe use the name of a MWeight container stored
+// in the parameter list or a pointer to it as an argument.
+//
+//
+//  WARNING:
+//   Because MFillH is a generalized task to fill histograms it doesn't
+//   know about which branches from a file are necessary to fill the
+//   histograms. If you are reading data from a file which is directly
+//   filled into a histogram via MFillH, please call either
+//   MReadTree::DisableAutoScheme() or enable the necessary branches by
+//   yourself, using MReadTree::EnableBranch()
+//
+//   Checkout the Warning in MTaskList.
+//
+//  Version 2:
+//  ----------
+//   - added fNumExcutions
+//
+//
+//  Input Containers:
+//   A parameter container
+//
+//  Output Containers:
+//   A histogram container
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MFillH.h"
+
+#include <fstream>
+
+#include <TClass.h>
+#include <TCanvas.h>
+
+#include "MDataChain.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MH.h"
+#include "MHArray.h"
+
+#include "MWeight.h"
+
+#include "MParList.h"
+#include "MStatusDisplay.h"
+
+ClassImp(MFillH);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initializes name and title of the object. It is called by all
+// constructors.
+//
+void MFillH::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFillH";
+    fTitle = title ? title : "Task to fill Mars histograms";
+
+    fH            = NULL;
+    fParContainer = NULL;
+
+    fIndex  = NULL;
+    fCanvas = NULL;
+
+    fWeight     = NULL;
+    fWeightName = "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. This is to support some root-stuff.
+// Never try to use it yourself!
+//
+MFillH::MFillH()
+{
+    Init(NULL, NULL);
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor.
+//
+// 1) - par is the name of the parameter container which should be filled into
+//      the histogram
+//    - hist is the name of the histogram container (which must have been
+//      derived from MH)
+//
+//    In this case MH::Fill is called with a pointer to the corresponding
+//    histogram instance.
+//
+// 2) - hist is the name and/or type of the histogram.
+//      1) The name and type is identical, eg: "MHHillas"
+//      2) They are not identical, eg: "MyHistogram [MHHillas]"
+//         This searches for a class instance of MHHillas with the name
+//         "MyHistogram". If it doesn't exist one is created.
+//
+//    In this case PreProcess calls MH::SetupFill with a pointer to the
+//    parameter list and MH::Fill is called with a NULL-pointer.
+//
+MFillH::MFillH(const char *hist, const char *par, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fHName = hist;
+    fParContainerName = par;
+
+    AddToBranchList(Form("%s.*", (const char*)ExtractName(hist)));
+    if (par)
+        AddToBranchList(Form("%s.*", (const char*)ExtractName(par)));
+
+    if (title)
+        return;
+
+    fTitle = Form("Fill %s", fHName.Data());
+    if (fParContainerName.IsNull())
+        return;
+
+    fTitle += Form(" from %s", fParContainerName.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor.
+//
+// 1) - par is a pointer to the instance of your parameter container from which
+//      the data should be used to fill the histogram.
+//    - hist is the name of the histogram container (which must have been
+//      derived from MH)
+//
+//    In this case MH::Fill is called with a pointer to the corresponding
+//    histogram instance.
+//
+// 2) - hist is the name and/or type of the histogram.
+//      1) The name and type is identical, eg: "MHHillas"
+//      2) They are not identical, eg: "MyHistogram [MHHillas]"
+//         This searches for a class instance of MHHillas with the name
+//         "MyHistogram". If it doesn't exist one is created. Everything
+//         which is between the first '[' and the last ']' in the string
+//         is used as the histogram type.
+//
+//    In this case PreProcess calls MH::SetupFill with a pointer to the
+//    parameter list and MH::Fill is called with a NULL-pointer.
+//
+//
+MFillH::MFillH(const char *hist, MParContainer *par, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fHName = hist;
+    fParContainer = par;
+    fParContainerName = par->GetName();
+
+    AddToBranchList(Form("%s.*", (const char*)ExtractName(hist)));
+    AddToBranchList(Form("%s.*", par->GetName()));
+
+    if (!title)
+        fTitle = Form("Fill %s from %s", fName.Data(), par->GetDescriptor().Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor.
+//
+// - par is a pointer to the instance of your parameter container from which
+//   the data should be used to fill the histogram.
+// - hist is a pointer to the instance of your histogram container (which must
+//   have been derived from MH) into which the data should flow
+//
+MFillH::MFillH(MH *hist, const char *par, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fH = hist;
+    fHName = hist->GetName();
+    fParContainerName = par;
+
+    AddToBranchList(fH->GetDataMember());
+    if (par)
+        AddToBranchList(Form("%s.*", (const char*)ExtractName(par)));
+
+    if (title)
+        return;
+
+    fTitle = Form("Fill %s", hist->GetDescriptor().Data());
+    if (!par)
+        return;
+
+    fTitle += Form(" from %s", fParContainerName.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor.
+//
+// - par is a pointer to the instance of your parameter container from which
+//   the data should be used to fill the histogram.
+// - hist is the name of the histogram container (which must have been
+//   derived from MH)
+//
+MFillH::MFillH(MH *hist, MParContainer *par, const char *name, const char *title)
+{
+    Init(name, title);
+
+    fH = hist;
+    fHName = hist->GetName();
+    fParContainer = par;
+    fParContainerName = par->GetName();
+
+    AddToBranchList(fH->GetDataMember());
+    AddToBranchList(Form("%s.*", par->GetName()));
+
+    if (!title)
+        fTitle = Form("Fill %s from %s", hist->GetDescriptor().Data(), par->GetDescriptor().Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete fData if existing and kCanDelete is set.
+//
+MFillH::~MFillH()
+{
+    if (fIndex)
+        if (fIndex->TestBit(kCanDelete))
+            delete fIndex;
+}
+
+// --------------------------------------------------------------------------
+//
+// If the histogram to be filles is a MHArray you can specify a 'rule'
+// This rule is used to create an MDataChain. The return value of the chain
+// is casted to int. Each int acts as a key. For each (new) key a new
+// histogram is created in the array. (eg for the rule
+// "MRawEvtHeader::fRunNumber" you would get one histogram per run-number)
+//
+void MFillH::SetRuleForIdx(const TString rule)
+{
+    fIndex = new MDataChain(rule);
+    fIndex->SetBit(kCanDelete);
+}
+
+// --------------------------------------------------------------------------
+//
+// If the histogram to be filles is a MHArray you can specify a MData-object
+// The return value of the object is casted to int. Each int acts as a key.
+// For each (new) key a new histogram is created in the array. (eg for
+// MDataMember("MRawEvtHeader::fRunNumber") you would get one histogram per
+// run-number)
+//
+void MFillH::SetRuleForIdx(MData *data)
+{
+    fIndex = data;
+}
+
+// --------------------------------------------------------------------------
+//
+// Extracts the name of the histogram from the MFillH argument
+//
+TString MFillH::ExtractName(const char *name) const
+{
+    TString type = name;
+
+    const Ssiz_t first = type.First('[');
+    const Ssiz_t last  = type.First(']');
+
+    if (!first || !last || first>=last)
+        return type;
+
+    return type.Remove(first).Strip(TString::kBoth);
+}
+
+// --------------------------------------------------------------------------
+//
+// Extracts the class-name of the histogram from the MFillH argument
+//
+TString MFillH::ExtractClass(const char *name) const
+{
+    TString type = name;
+
+    const Ssiz_t first = type.First('[');
+    const Ssiz_t last  = type.First(']');
+
+    if (!first || !last || first>=last)
+        return type;
+
+    const Ssiz_t length = last-first-1;
+
+    TString strip = fHName(first+1, length);
+    return strip.Strip(TString::kBoth);
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this to set a draw option used when drawing automatically to the
+// status display.
+//
+void MFillH::SetDrawOption(Option_t *option)
+{
+    fDrawOption = option;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new tab in a status display with the name of the MH class,
+// if fDisplay is set and the MH-class overwrites the Draw function
+//
+// If the draw-option contains 'same' (case insensitive) a tab with the
+// same name as the one which would be created is searched and the
+// MH is drawn to this canvas. If it is not found a new tab is created.
+//
+Bool_t MFillH::DrawToDisplay()
+{
+    fCanvas = NULL;
+
+    if (!fDisplay)
+        return kTRUE;
+
+    if (!fH->OverwritesDraw())
+        return kTRUE;
+
+    if (TestBit(kDoNotDisplay))
+        return kTRUE;
+
+    const TString tabname = fNameTab.IsNull() ? fH->GetName() : fNameTab.Data();
+
+    fCanvas = 0;
+    if (fDrawOption.Contains("same", TString::kIgnoreCase))
+    {
+        fCanvas = fDisplay->GetCanvas(tabname);
+        if (!fCanvas)
+            *fLog << warn << "WARNING - 'same' option given, but no tab with name '" << tabname << "' found." << endl;
+    }
+
+    if (!fCanvas)
+        fCanvas = &fDisplay->AddTab(tabname);
+
+    fCanvas->cd();
+    fH->Draw(fDrawOption);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks the parameter list for the existance of the parameter container. If
+// the name of it was given in the constructor. It checks also for the
+// existance of the histogram container in the parameter list if a name was
+// given. If it is not available it tried to create a histogram container
+// with the same type as the given object name.
+//
+Int_t MFillH::PreProcess(MParList *pList)
+{
+    if (fIndex)
+    {
+        if (!fIndex->PreProcess(pList))
+        {
+            *fLog << all << "PreProcessing of Index rule failed... aborting." << endl;
+            return kFALSE;
+        }
+
+        if (!fIndex->IsValid())
+        {
+            *fLog << all << "Given Index rule invalid... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    //
+    // If the user defined the use of a weight: search for it.
+    //
+    if (!fWeight && !fWeightName.IsNull())
+    {
+        fWeight = (MWeight*)pList->FindObject(fWeightName, "MWeight");
+
+	if (!fWeight)
+        {
+            *fLog << err << fWeightName << " [MWeight] not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    //
+    // Try to get the histogram container with name fHName from list
+    // or create one with this name
+    //
+    if (!fH)
+    {
+        const TString cls  = ExtractClass(fHName);
+        const TString name = ExtractName(fHName);
+
+        TObject *obj=NULL;
+        if (cls==name)
+            obj = pList->FindObject(fHName);
+
+        if (!obj)
+        {
+            /*
+            if (cls==name)
+            *fLog << inf << "Object '" << fHName << "' not found in parlist... creating." << endl;
+            */
+            obj = pList->FindCreateObj(cls, name);
+        }
+
+        if (!obj)
+            return kFALSE;
+
+        //
+        // We were successfull getting it. Check whether it really inherits
+        // from MH, FindCreateObj does only check for inheritance from
+        // 'type'.
+        //
+        TClass *tcls = fIndex ? MHArray::Class() : MH::Class();
+        if (!obj->InheritsFrom(tcls))
+        {
+            *fLog << err << obj->GetName() << " doesn't inherit ";
+            *fLog << "from " << tcls->GetName() << " - cannot be used for MFillH...";
+            *fLog << "aborting." << endl;
+            return kFALSE;
+        }
+
+        fH = (MH*)obj;
+    }
+
+    //
+    // Now we have the histogram container available. Try to Setup Fill.
+    //
+    fH->SetSerialNumber(GetSerialNumber());
+    fH->SetNumExecutions(0);
+    if (!fH->SetupFill(pList))
+    {
+        *fLog << (TestBit(kCanSkip) ? warn : err);
+        *fLog << (TestBit(kCanSkip) ? "WARNING" : "ERROR");
+        *fLog << " - Calling SetupFill for " << fH->GetDescriptor() << "...";
+        *fLog << (TestBit(kCanSkip) ? "skipped." : "aborting.") << endl;
+
+        return TestBit(kCanSkip) ? kSKIP : kFALSE;
+    }
+
+    //
+    // If also a parameter container is already set we are done.
+    //
+    if (fParContainer)
+        return DrawToDisplay();
+
+    //
+    // This case means, that the MH sets up its container to be filled
+    // by itself. Check there if it has something to be filled with!
+    //
+    if (fParContainerName.IsNull())
+    {
+        fParContainer = NULL;
+        return DrawToDisplay();
+    }
+
+    fParContainer = (MParContainer*)pList->FindObject(fParContainerName);
+    if (fParContainer)
+        return DrawToDisplay();
+
+    if (TestBit(kCanSkip))
+    {
+        *fLog << warn << fParContainerName << " [MParContainer] not found... skipped." << endl;
+        return kSKIP;
+    }
+
+    *fLog << err << fParContainerName << " [MParContainer] not found... aborting." << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call the ReInit function of the contained Histogram
+//
+Bool_t MFillH::ReInit(MParList *pList)
+{
+    return fH->ReInit(pList);
+} 
+
+// --------------------------------------------------------------------------
+//
+// Fills the data from the parameter conatiner into the histogram container
+//
+Int_t MFillH::Process()
+{
+    if (fIndex)
+        ((MHArray*)fH)->SetIndexByKey(fIndex->GetValue());
+    /*
+     const Int_t key = (Int_t)fIndex->GetValue();
+     const Int_t idx = fMapIdx->Add(key);
+     ((MHArray*)fH)->SetIndex(idx);
+     */
+
+    TVirtualPad *save = gPad;
+    if (fCanvas)
+        fCanvas->cd();
+
+    const Bool_t rc = fH->Fill(fParContainer, fWeight?fWeight->GetWeight():1);
+    fH->SetNumExecutions(GetNumExecutions()+1);
+
+    if (save && fCanvas)
+        save->cd();
+
+    return rc;
+} 
+
+// --------------------------------------------------------------------------
+//
+// Set the ReadyToSave flag of the histogram container, because now all data
+// has been filled into the histogram.
+//
+Int_t MFillH::PostProcess()
+{
+    //
+    // Now all data is in the histogram. Maybe some final action is
+    // necessary.
+    //
+    if (!fH->Finalize())
+    {
+        *fLog << err << "ERROR - Calling Finalize for ";
+        *fLog << fH->GetDescriptor() << "... aborting." << endl;
+        return kFALSE;
+    }
+
+    fH->SetReadyToSave();
+
+    //
+    // Check whether fDisplay has previously been used (fCanvas),
+    // fDisplay is still open and the corresponding Canvas/Tab is
+    // still existing.
+    //
+    if (fDisplay && fDisplay->HasCanvas(fCanvas))
+    {
+        const TString opt(Form("nonew %s", fDrawOption.Data()));
+        fCanvas->cd();
+        fH->DrawClone(opt);
+        fCanvas->Modified();
+        fCanvas->Update();
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MFillH::StreamPrimitive(ofstream &out) const
+{
+    if (fH)
+        fH->SavePrimitive(out);
+
+    if (fParContainer)
+        fParContainer->SavePrimitive(out);
+
+    if (fWeight)
+        fWeight->SavePrimitive(out);
+
+    out << "   MFillH " << GetUniqueName() << "(";
+
+    if (fH)
+        out << "&" << fH->GetUniqueName();
+    else
+        out << "\"" << fHName << "\"";
+
+    if (fParContainer)
+        out << ", &" << fParContainer->GetUniqueName();
+    else
+        if (!fParContainerName.IsNull())
+            out << ", \"" << fParContainerName << "\"";
+
+    out << ");" << endl;
+
+    if (fWeight || !fWeightName.IsNull())
+    {
+        out << "   " << GetUniqueName() << ".SetWeight(";
+        if (fWeight)
+            out << "&" << fWeight->GetUniqueName() << ");" << endl;
+        else
+            if (!fWeightName.IsNull())
+                out << "\"" << fWeightName << "\");" << endl;
+    }
+
+    if (fIndex)
+    {
+        out << "   " << GetUniqueName() << ".SetRuleForIdx(\"";
+        out << fIndex->GetRule() << "\");" << endl;
+    }
+}
Index: /tags/Mars-V0.9/mhbase/MFillH.h
===================================================================
--- /tags/Mars-V0.9/mhbase/MFillH.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MFillH.h	(revision 9772)
@@ -0,0 +1,81 @@
+#ifndef MARS_MFillH
+#define MARS_MFillH
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MH;
+class MMap;
+class MData;
+class MWeight;
+class MParList;
+
+class TCanvas;
+
+class MFillH : public MTask
+{
+public:
+    enum {
+        kDoNotDisplay = BIT(17),
+        kCanSkip      = BIT(18)
+    };
+
+private:
+    MParContainer *fParContainer; // Pointer to the data container storing
+    TString fParContainerName;    // Name to a data container
+
+    MH* fH;                       // Pointer to the MH container to get filled
+    TString fHName;               // Name to a MH container to get filled
+    TString fNameTab;
+
+    MWeight *fWeight;             // Pointer to the container storing a weight
+    TString fWeightName;          // Name of a container storing a weight
+
+    MData *fIndex;                // MData object describing the 'key' to an automatic index for an MHArray
+    MMap  *fMapIdx;               //! Map to map key-index-pair for an MHArray (MMap see MFillH.cc)
+
+    TCanvas *fCanvas;             //! Canvas used to update a MStatusDisplay at the end of a loop
+
+    TString fDrawOption;          // Draw option for status display
+
+    TString ExtractName(const char *name) const;
+    TString ExtractClass(const char *name) const;
+
+    void Init(const char *name, const char *title);
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Bool_t DrawToDisplay();
+
+public:
+    MFillH();
+    MFillH(const char *hist, const char *par=NULL, const char *name=NULL, const char *title=NULL);
+    MFillH(const char *hist, MParContainer *par,   const char *name=NULL, const char *title=NULL);
+    MFillH(MH *hist,         const char *par=NULL, const char *name=NULL, const char *title=NULL);
+    MFillH(MH *hist,         MParContainer *par,   const char *name=NULL, const char *title=NULL);
+    ~MFillH();
+
+    void SetNameTab(const char *n="") { fNameTab = n; }
+
+    void SetRuleForIdx(const TString rule);
+    void SetRuleForIdx(MData *rule);
+
+    void SetWeight(MWeight *w)       { fWeight = w; }
+    void SetWeight(const char *name) { fWeightName = name; }
+
+    void      SetDrawOption(Option_t *option="");
+    Option_t *GetDrawOption() const { return fDrawOption; }
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+    TCanvas *GetCanvas() { return fCanvas; }
+
+    ClassDef(MFillH, 2) // Task to fill a histogram with data from a parameter container
+};
+    
+#endif
+
Index: /tags/Mars-V0.9/mhbase/MH.cc
===================================================================
--- /tags/Mars-V0.9/mhbase/MH.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MH.cc	(revision 9772)
@@ -0,0 +1,1301 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MH                                                                      //
+//                                                                          //
+//  This is a base tasks for mars histograms. It defines a common interface //
+//  for filling the histograms with events (MH::Fill) which is used by a    //
+//  common 'filler' And a SetupFill member function which may be used       //
+//  by MFillH. The idea is:                                                 //
+//   1) If your Histogram can become filled by one single container         //
+//      (like MHHillas) you overload MH::Fill and it gets called with       //
+//      a pointer to the container with which it should be filled.          //
+//                                                                          //
+//   2) You histogram needs several containers to get filled. Than you      //
+//      have to overload MH::SetupFill and get the necessary objects from   //
+//      the parameter list. Use this objects in Fill to fill your           //
+//      histogram.                                                          //
+//                                                                          //
+//  If you want to create your own histogram class the new class must be    //
+//  derived from MH (instead of the base MParContainer) and you must        //
+//  the fill function of MH. This is the function which is called to fill   //
+//  the histogram(s) by the data of a corresponding parameter container.    //
+//                                                                          //
+//  Remark: the static member function (eg MakeDefCanvas) can be called     //
+//          from everywhere using: MH::MakeDefCanvas(...)                   //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MH.h"
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TStyle.h>       // TStyle::GetScreenFactor
+#include <TGaxis.h>
+#include <TCanvas.h>
+#include <TLegend.h>
+#include <TPaveStats.h>
+#include <TBaseClass.h>
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+#include <THLimitsFinder.h>
+#endif
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MParContainer.h"
+
+#include "MBinning.h"
+
+#include "MArrayD.h"
+#include "MArrayF.h"
+
+ClassImp(MH);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title only. Typically you won't
+// need to change this.
+//
+MH::MH(const char *name, const char *title)
+    : fSerialNumber(0), fNumExecutions(0)
+
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MH";
+    fTitle = title ? title : "Base class for Mars histograms";
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to use the automatic filling of your derived class you
+// must overload this function. If it is not overloaded you cannot use
+// FillH with this class. The argument is a pointer to a container
+// in your paremeter list which is specified in the MFillH constructor.
+// If you are not going to use it you should at least add
+//   Bool_t MH::Fill(const MParContainer *) { return kTRUE; }
+// to your class definition.
+//
+Bool_t MH::Fill(const MParContainer *par, const Stat_t w)
+{
+    *fLog << warn << GetDescriptor() << ": Fill not overloaded! Can't be used!" << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This virtual function is ment as a generalized interface to retrieve
+// a pointer to a root histogram from the MH-derived class.
+//
+TH1 *MH::GetHistByName(const TString name)
+{
+    *fLog << warn << GetDescriptor() << ": GetHistByName not overloaded! Can't be used!" << endl;
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a function which should replace the creation of default
+// canvases like root does. Because this is inconvinient in some aspects.
+// need to change this.
+// You can specify a name for the default canvas and a title. Also
+// width and height can be given.
+// MakeDefCanvas looks for a canvas with the given name. If now name is
+// given the DefCanvasName of root is used. If no such canvas is existing
+// it is created and returned. If such a canvas already exists a new canvas
+// with a name plus anumber is created (the number is calculated by the
+// number of all existing canvases plus one)
+//
+// Normally the canvas size is scaled with gStyle->GetScreenFactor() so
+// that on all screens it looks like the same part of the screen.
+// To suppress this scaling use usescreenfactor=kFALSE. In this case
+// you specify directly the size of the embedded pad.
+//
+TCanvas *MH::MakeDefCanvas(TString name, const char *title,
+                           UInt_t w, UInt_t h, Bool_t usescreenfactor)
+{
+    const TList *list = (TList*)gROOT->GetListOfCanvases();
+
+    if (name.IsNull())
+        name = gROOT->GetDefCanvasName();
+
+    if (list->FindObject(name))
+        name += Form(" <%d>", list->GetSize()+1);
+
+    if (!usescreenfactor)
+    {
+        const Float_t cx = gStyle->GetScreenFactor();
+        w += 4;
+        h += 28;
+        w = (int)(w/cx+1);
+        h = (int)(h/cx+1);
+    }
+
+    return new TCanvas(name, title, w, h);
+}
+
+// --------------------------------------------------------------------------
+//
+// This function works like MakeDefCanvas(name, title, w, h) but name
+// and title are retrieved from the given TObject.
+//
+// Normally the canvas size is scaled with gStyle->GetScreenFactor() so
+// that on all screens it looks like the same part of the screen.
+// To suppress this scaling use usescreenfactor=kFALSE. In this case
+// you specify directly the size of the embedded pad.
+//
+TCanvas *MH::MakeDefCanvas(const TObject *obj,
+                           UInt_t w, UInt_t h, Bool_t usescreenfactor)
+{
+    if (!usescreenfactor)
+    {
+        const Float_t cx = gStyle->GetScreenFactor();
+        w += 4;
+        h += 28;
+        h = (int)(h/cx+1);
+        w = (int)(w/cx+1);
+    }
+
+    return MakeDefCanvas(obj->GetName(), obj->GetTitle(), w, h);
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies a given binning to a 1D-histogram
+//
+void MH::SetBinning(TH1 *h, const MBinning *binsx)
+{
+    //
+    // Another strange behaviour: TAxis::Set deletes the axis title!
+    //
+    TAxis &x = *h->GetXaxis();
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,03)
+    TString xtitle = x.GetTitle();
+#endif
+
+    // All this is reset by TAxis::Set
+    const TAttAxis att(x);
+    const Bool_t   tm(x.GetTimeDisplay());
+    const TString  tf(x.GetTimeFormat());
+
+    //
+    // This is a necessary workaround if one wants to set
+    // non-equidistant bins after the initialization
+    // TH1D::fNcells must be set correctly.
+    //
+    h->SetBins(binsx->GetNumBins(), 0, 1);
+
+    //
+    // Set the binning of the current histogram to the binning
+    // in one of the two given histograms
+    //
+    x.Set(binsx->GetNumBins(), binsx->GetEdges());
+
+    // All this is reset by TAxis::Set
+    att.Copy(x);
+    x.SetTimeDisplay(tm);
+    x.SetTimeFormat(tf);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,03)
+    x.SetTitle(xtitle);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies given binnings to the two axis of a 2D-histogram
+//
+void MH::SetBinning(TH2 *h, const MBinning *binsx, const MBinning *binsy)
+{
+    TAxis &x = *h->GetXaxis();
+    TAxis &y = *h->GetYaxis();
+
+    //
+    // Another strange behaviour: TAxis::Set deletes the axis title!
+    //
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,03)
+    TString xtitle = x.GetTitle();
+    TString ytitle = y.GetTitle();
+#endif
+
+    // All this is reset by TAxis::Set
+    const TAttAxis attx(x);
+    const TAttAxis atty(y);
+    const Bool_t   tmx(x.GetTimeDisplay());
+    const Bool_t   tmy(y.GetTimeDisplay());
+    const TString  tfx(x.GetTimeFormat());
+    const TString  tfy(y.GetTimeFormat());
+
+    //
+    // This is a necessary workaround if one wants to set
+    // non-equidistant bins after the initialization
+    // TH1D::fNcells must be set correctly.
+    //
+    h->SetBins(binsx->GetNumBins(), 0, 1,
+               binsy->GetNumBins(), 0, 1);
+
+    //
+    // Set the binning of the current histogram to the binning
+    // in one of the two given histograms
+    //
+    x.Set(binsx->GetNumBins(), binsx->GetEdges());
+    y.Set(binsy->GetNumBins(), binsy->GetEdges());
+
+    // All this is reset by TAxis::Set
+    attx.Copy(x);
+    atty.Copy(y);
+    x.SetTimeDisplay(tmx);
+    y.SetTimeDisplay(tmy);
+    x.SetTimeFormat(tfx);
+    y.SetTimeFormat(tfy);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,03)
+    x.SetTitle(xtitle);
+    y.SetTitle(ytitle);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies given binnings to the three axis of a 3D-histogram
+//
+void MH::SetBinning(TH3 *h, const MBinning *binsx, const MBinning *binsy, const MBinning *binsz)
+{
+    //
+    // Another strange behaviour: TAxis::Set deletes the axis title!
+    //
+    TAxis &x = *h->GetXaxis();
+    TAxis &y = *h->GetYaxis();
+    TAxis &z = *h->GetZaxis();
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,03)
+    TString xtitle = x.GetTitle();
+    TString ytitle = y.GetTitle();
+    TString ztitle = z.GetTitle();
+#endif
+
+    // All this is reset by TAxis::Set
+    const TAttAxis attx(x);
+    const TAttAxis atty(y);
+    const TAttAxis attz(z);
+    const Bool_t   tmx(x.GetTimeDisplay());
+    const Bool_t   tmy(y.GetTimeDisplay());
+    const Bool_t   tmz(z.GetTimeDisplay());
+    const TString  tfx(x.GetTimeFormat());
+    const TString  tfy(y.GetTimeFormat());
+    const TString  tfz(z.GetTimeFormat());
+
+    //
+    // This is a necessary workaround if one wants to set
+    // non-equidistant bins after the initialization
+    // TH1D::fNcells must be set correctly.
+    //
+    h->SetBins(binsx->GetNumBins(), 0, 1,
+               binsy->GetNumBins(), 0, 1,
+               binsz->GetNumBins(), 0, 1);
+
+    //
+    // Set the binning of the current histogram to the binning
+    // in one of the two given histograms
+    //
+    x.Set(binsx->GetNumBins(), binsx->GetEdges());
+    y.Set(binsy->GetNumBins(), binsy->GetEdges());
+    z.Set(binsz->GetNumBins(), binsz->GetEdges());
+
+    // All this is reset by TAxis::Set
+    attx.Copy(x);
+    atty.Copy(y);
+    attz.Copy(z);
+    x.SetTimeDisplay(tmx);
+    y.SetTimeDisplay(tmy);
+    z.SetTimeDisplay(tmz);
+    x.SetTimeFormat(tfx);
+    y.SetTimeFormat(tfy);
+    z.SetTimeFormat(tfz);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,03,03)
+    x.SetTitle(xtitle);
+    y.SetTitle(ytitle);
+    z.SetTitle(ztitle);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies given binning (the n+1 edges)  to the axis of a 1D-histogram
+//
+void MH::SetBinning(TH1 *h, const TArrayD &binsx)
+{
+    MBinning bx;
+    bx.SetEdges(binsx);
+    SetBinning(h, &bx);
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies given binning (the n+1 edges) to the two axis of a
+// 2D-histogram
+//
+void MH::SetBinning(TH2 *h, const TArrayD &binsx, const TArrayD &binsy)
+{
+    MBinning bx;
+    MBinning by;
+    bx.SetEdges(binsx);
+    by.SetEdges(binsy);
+    SetBinning(h, &bx, &by);
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies given binning (the n+1 edges) to the three axis of a
+// 3D-histogram
+//
+void MH::SetBinning(TH3 *h, const TArrayD &binsx, const TArrayD &binsy, const TArrayD &binsz)
+{
+    MBinning bx;
+    MBinning by;
+    MBinning bz;
+    bx.SetEdges(binsx);
+    by.SetEdges(binsy);
+    bz.SetEdges(binsz);
+    SetBinning(h, &bx, &by, &bz);
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies the binning of a TAxis (eg from a root histogram) to the axis
+// of a 1D-histogram
+//
+void MH::SetBinning(TH1 *h, const TAxis *binsx)
+{
+    const Int_t nx = binsx->GetNbins();
+
+    TArrayD bx(nx+1);
+    for (int i=0; i<nx; i++) bx[i] = binsx->GetBinLowEdge(i+1);
+    bx[nx] = binsx->GetXmax();
+
+    SetBinning(h, bx);
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies the binnings of the TAxis' (eg from a root histogram) to the
+// two axis' of a 2D-histogram
+//
+void MH::SetBinning(TH2 *h, const TAxis *binsx, const TAxis *binsy)
+{
+    const Int_t nx = binsx->GetNbins();
+    const Int_t ny = binsy->GetNbins();
+
+    TArrayD bx(nx+1);
+    TArrayD by(ny+1);
+    for (int i=0; i<nx; i++) bx[i] = binsx->GetBinLowEdge(i+1);
+    for (int i=0; i<ny; i++) by[i] = binsy->GetBinLowEdge(i+1);
+    bx[nx] = binsx->GetXmax();
+    by[ny] = binsy->GetXmax();
+
+    SetBinning(h, bx, by);
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies the binnings of the TAxis' (eg from a root histogram) to the
+// three axis' of a 3D-histogram
+//
+void MH::SetBinning(TH3 *h, const TAxis *binsx, const TAxis *binsy, const TAxis *binsz)
+{
+    const Int_t nx = binsx->GetNbins();
+    const Int_t ny = binsy->GetNbins();
+    const Int_t nz = binsz->GetNbins();
+
+    TArrayD bx(nx+1);
+    TArrayD by(ny+1);
+    TArrayD bz(nz+1);
+    for (int i=0; i<nx; i++) bx[i] = binsx->GetBinLowEdge(i+1);
+    for (int i=0; i<ny; i++) by[i] = binsy->GetBinLowEdge(i+1);
+    for (int i=0; i<nz; i++) bz[i] = binsz->GetBinLowEdge(i+1);
+    bx[nx] = binsx->GetXmax();
+    by[ny] = binsy->GetXmax();
+    bz[nz] = binsz->GetXmax();
+
+    SetBinning(h, bx, by, bz);
+}
+
+// --------------------------------------------------------------------------
+//
+// Applies the binnings of one root-histogram x to another one h
+// Both histograms must be of the same type: TH1, TH2 or TH3
+//
+void MH::SetBinning(TH1 *h, const TH1 *x)
+{
+    if (h->InheritsFrom(TH3::Class()) && x->InheritsFrom(TH3::Class()))
+    {
+        SetBinning((TH3*)h, ((TH1*)x)->GetXaxis(), ((TH1*)x)->GetYaxis(), ((TH1*)x)->GetZaxis());
+        return;
+    }
+    if (h->InheritsFrom(TH3::Class()) || x->InheritsFrom(TH3::Class()))
+        return;
+    if (h->InheritsFrom(TH2::Class()) && x->InheritsFrom(TH2::Class()))
+    {
+        SetBinning((TH2*)h, ((TH1*)x)->GetXaxis(), ((TH1*)x)->GetYaxis());
+        return;
+    }
+    if (h->InheritsFrom(TH2::Class()) || x->InheritsFrom(TH2::Class()))
+        return;
+    if (h->InheritsFrom(TH1::Class()) && x->InheritsFrom(TH1::Class()))
+    {
+        SetBinning(h, ((TH1*)x)->GetXaxis());
+        return;
+    }
+}
+
+void MH::RemoveFirstBin(TH1 &h)
+{
+    if (h.InheritsFrom(TH2::Class()) || h.InheritsFrom(TH3::Class()))
+        return;
+
+    const Bool_t haserr = h.GetSumw2N()>0;
+
+    const Int_t n0 = h.GetNbinsX();
+    if (n0<2)
+        return;
+
+    TArrayD val(n0-1);
+    TArrayD err(haserr ? n0-1 : 0);
+    for (int i=1; i<n0; i++)
+    {
+        val[i-1] = h.GetBinContent(i+1);
+        if (haserr)
+            err[i-1] = h.GetBinError(i+1);
+    }
+
+    MBinning bins;
+    bins.SetEdges(h, 'x');
+    bins.RemoveFirstEdge();
+    bins.Apply(h);
+
+    h.Reset();
+
+    for (int i=1; i<n0; i++)
+    {
+        h.SetBinContent(i, val[i-1]);
+        if (haserr)
+            h.SetBinError(i, err[i-1]);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Multiplies all entries in a TArrayD by a float f
+//
+void MH::ScaleArray(TArrayD &bins, Double_t f)
+{
+    for (int i=0; i<bins.GetSize(); i++)
+        bins[i] *= f;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scales the binning of a TAxis by a float f
+//
+TArrayD MH::ScaleAxis(TAxis &axe, Double_t f)
+{
+    TArrayD arr(axe.GetNbins()+1);
+
+    for (int i=1; i<=axe.GetNbins()+1; i++)
+        arr[i-1] = axe.GetBinLowEdge(i);
+
+    ScaleArray(arr, f);
+
+    return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scales the binning of one, two or three axis of a histogram by a float f
+//
+void MH::ScaleAxis(TH1 *h, Double_t fx, Double_t fy, Double_t fz)
+{
+    if (h->InheritsFrom(TH3::Class()))
+    {
+        SetBinning((TH3*)h,
+                   ScaleAxis(*h->GetXaxis(), fx),
+                   ScaleAxis(*h->GetYaxis(), fy),
+                   ScaleAxis(*h->GetZaxis(), fz));
+        return;
+    }
+
+    if (h->InheritsFrom(TH2::Class()))
+    {
+        SetBinning((TH2*)h,
+                   ScaleAxis(*h->GetXaxis(), fx),
+                   ScaleAxis(*h->GetYaxis(), fy));
+        return;
+    }
+
+    if (h->InheritsFrom(TH1::Class()))
+        SetBinning(h, ScaleAxis(*h->GetXaxis(), fx));
+}
+
+// --------------------------------------------------------------------------
+//
+// Tries to find a MBinning container with the name "Binning"+name
+// in the given parameter list. If it was found it is applied to the
+// given histogram. This is only valid for 1D-histograms
+//
+Bool_t MH::ApplyBinning(const MParList &plist, TString name, TH1 *h)
+{
+    if (h->InheritsFrom(TH2::Class()) || h->InheritsFrom(TH3::Class()))
+    {
+        gLog << warn << "MH::ApplyBinning: '" << h->GetName() << "' is not a basic TH1 object... no binning applied." << endl;
+        return kFALSE;
+    }
+
+    const MBinning *bins = (MBinning*)plist.FindObject("Binning"+name);
+    if (!bins)
+    {
+        gLog << inf << "Object 'Binning" << name << "' [MBinning] not found... no binning applied." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(h, bins);
+    return kTRUE;
+}
+
+void MH::FindGoodLimits(Int_t nbins, Int_t &newbins, Double_t &xmin, Double_t &xmax, Bool_t isInteger)
+{
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+    THLimitsFinder::OptimizeLimits(nbins, newbins, xmin, xmax, isInteger);
+#else
+//*-*-*-*-*-*-*-*-*Find reasonable bin values*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
+//*-*              ==========================
+
+    Double_t dx = 0.1*(xmax-xmin);
+    Double_t umin = xmin - dx;
+    Double_t umax = xmax + dx;
+
+    if (umin < 0 && xmin >= 0)
+        umin = 0;
+
+    if (umax > 0 && xmax <= 0)
+        umax = 0;
+
+    Double_t binlow  =0;
+    Double_t binhigh =0;
+    Double_t binwidth=0;
+
+    TGaxis::Optimize(umin, umax, nbins, binlow, binhigh, nbins, binwidth, "");
+
+    if (binwidth <= 0 || binwidth > 1.e+39)
+    {
+        xmin = -1;
+        xmax = 1;
+    }
+    else
+    {
+        xmin = binlow;
+        xmax = binhigh;
+    }
+
+    if (isInteger)
+    {
+        Int_t ixmin = (Int_t)xmin;
+        Int_t ixmax = (Int_t)xmax;
+        Double_t dxmin = (Double_t)ixmin;
+        Double_t dxmax = (Double_t)ixmax;
+
+        xmin = xmin<0 && xmin!=dxmin ? dxmin - 1 : dxmin;
+        xmax = xmax>0 && xmax!=dxmax ? dxmax + 1 : dxmax;
+
+        if (xmin>=xmax)
+            xmax = xmin+1;
+
+        Int_t bw = 1 + (Int_t)((xmax-xmin)/nbins);
+
+        nbins = (Int_t)((xmax-xmin)/bw);
+
+        if (xmin+nbins*bw < xmax)
+        {
+            nbins++;
+            xmax = xmin +nbins*bw;
+        }
+    }
+
+    newbins = nbins;
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+//  Returns the lowest entry in a histogram which is greater than gt (eg >0)
+//
+Double_t MH::GetMinimumGT(const TH1 &h, Double_t gt)
+{
+    Double_t min = FLT_MAX;
+
+    const TAxis &axex = *((TH1&)h).GetXaxis();
+    const TAxis &axey = *((TH1&)h).GetYaxis();
+    const TAxis &axez = *((TH1&)h).GetZaxis();
+
+    for (int iz=1; iz<=axez.GetNbins(); iz++)
+        for (int iy=1; iy<=axey.GetNbins(); iy++)
+            for (int ix=1; ix<=axex.GetNbins(); ix++)
+            {
+                const Double_t v = h.GetBinContent(h.GetBin(ix, iy, iz));
+                if (gt<v && v<min)
+                    min = v;
+            }
+    return min;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Returns the bin center in a logarithmic scale. If the given bin
+//  number is <1 it is set to 1. If it is =GetNbins() it is set to
+//  GetNbins()
+//
+Double_t MH::GetBinCenterLog(const TAxis &axe, Int_t nbin)
+{
+    if (nbin>axe.GetNbins())
+        nbin = axe.GetNbins();
+
+    if (nbin<1)
+        nbin = 1;
+
+    const Double_t lo = axe.GetBinLowEdge(nbin);
+    const Double_t hi = axe.GetBinUpEdge(nbin);
+
+    const Double_t val = log10(lo) + log10(hi);
+
+    return pow(10, val/2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draws a copy of the two given histograms. Uses title as the pad title.
+// Also layout the two statistic boxes and a legend.
+//
+void MH::DrawSameCopy(const TH1 &hist1, const TH1 &hist2, const TString title)
+{
+    //
+    // Draw first histogram
+    //
+    TH1 *h1 = ((TH1&)hist1).DrawCopy();
+    gPad->SetBorderMode(0);
+    gPad->Update();
+
+    // FIXME: Also align max/min with set Maximum/Minimum
+    const Double_t maxbin1 = hist1.GetBinContent(hist1.GetMaximumBin());
+    const Double_t maxbin2 = hist2.GetBinContent(hist2.GetMaximumBin());
+    const Double_t minbin1 = hist1.GetBinContent(hist1.GetMinimumBin());
+    const Double_t minbin2 = hist2.GetBinContent(hist2.GetMinimumBin());
+
+    const Double_t max = TMath::Max(maxbin1, maxbin2);
+    const Double_t min = TMath::Min(minbin1, minbin2);
+
+    h1->SetMaximum(max>0?max*1.05:max*0.95);
+    h1->SetMinimum(max>0?min*0.95:min*1.05);
+
+    TPaveText *t = (TPaveText*)gPad->FindObject("title");
+    if (t)
+    {
+        t->SetName((TString)"MHTitle");     // rename object
+        t->Clear();                         // clear old lines
+        t->AddText((TString)" "+title+" "); // add the new title
+        t->SetBit(kCanDelete);              // make sure object is deleted
+
+        //
+        // FIXME: This is a stupid workaround to hide the redrawn
+        // (see THistPainter::PaintTitle) title
+        //
+        gPad->Modified();  // indicates a change
+        gPad->Update();    // recreates the original title
+        t->Pop();          // bring our title on top
+    }
+
+    //
+    // Rename first statistics box
+    //
+    TPaveStats *s1 = (TPaveStats*)gPad->FindObject("stats");
+    if (!s1)
+        s1 = (TPaveStats*)hist1.GetListOfFunctions()->FindObject("stats");
+    else
+        s1->SetName((TString)"Stat"+hist1.GetTitle());
+
+    if (s1 && s1->GetX2NDC()>0.95)
+    {
+        const Double_t x1 = s1->GetX1NDC()-0.01;
+        s1->SetX1NDC(x1-(s1->GetX2NDC()-s1->GetX1NDC()));
+        s1->SetX2NDC(x1);
+    }
+
+    //
+    // Draw second histogram
+    //
+    TH1 *h2 = ((TH1&)hist2).DrawCopy("sames");
+    gPad->Update();
+
+    //
+    // Draw Legend
+    //
+    TPaveStats *s2 = (TPaveStats*)gPad->FindObject("stats");
+    if (!s2)
+        s2 = (TPaveStats*)hist2.GetListOfFunctions()->FindObject("stats");
+
+    if (s2)
+    {
+        TLegend &l = *new TLegend(s2->GetX1NDC(),
+                                  s2->GetY1NDC()-0.015-(s2->GetY2NDC()-s2->GetY1NDC())/2,
+                                  s2->GetX2NDC(),
+                                  s2->GetY1NDC()-0.01
+                                 );
+        l.AddEntry(h1, h1->GetTitle());
+        l.AddEntry(h2, h2->GetTitle());
+        l.SetTextSize(s2->GetTextSize());
+        l.SetTextFont(s2->GetTextFont());
+        l.SetBorderSize(s2->GetBorderSize());
+        l.SetBit(kCanDelete);
+        l.Draw();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draws the two given histograms. Uses title as the pad title.
+// Also layout the two statistic boxes and a legend.
+//
+void MH::DrawSame(TH1 &hist1, TH1 &hist2, const TString title, Bool_t same)
+{
+    //
+    // Draw first histogram
+    //
+    hist1.Draw(same?"same":"");
+    gPad->SetBorderMode(0);
+    gPad->Update();
+
+    if (hist1.GetEntries()>0 && hist2.GetEntries()>0)
+    {
+        const Double_t maxbin1 = hist1.GetBinContent(hist1.GetMaximumBin());
+        const Double_t maxbin2 = hist2.GetBinContent(hist2.GetMaximumBin());
+        const Double_t minbin1 = hist1.GetBinContent(hist1.GetMinimumBin());
+        const Double_t minbin2 = hist2.GetBinContent(hist2.GetMinimumBin());
+
+        const Double_t max = TMath::Max(maxbin1, maxbin2);
+        const Double_t min = TMath::Min(minbin1, minbin2);
+
+        if (max!=min)
+        {
+            hist1.SetMaximum(max>0?max*1.05:max*0.95);
+            hist1.SetMinimum(max>0?min*0.95:min*1.05);
+        }
+    }
+
+    TPaveText *t = (TPaveText*)gPad->FindObject("title");
+    if (t)
+    {
+        t->SetName((TString)"MHTitle");     // rename object
+        t->Clear();                         // clear old lines
+        t->AddText((TString)" "+title+" "); // add the new title
+        t->SetBit(kCanDelete);              // make sure object is deleted
+
+        //
+        // FIXME: This is a stupid workaround to hide the redrawn
+        // (see THistPainter::PaintTitle) title
+        //
+        gPad->Modified();  // indicates a change
+        gPad->Update();    // recreates the original title
+        t->Pop();          // bring our title on top
+    }
+
+    //
+    // Rename first statistics box
+    //
+    // Where to get the TPaveStats depends on the root version
+    TPaveStats *s1 = (TPaveStats*)gPad->FindObject("stats");
+    if (!s1)
+        s1 = (TPaveStats*)hist1.GetListOfFunctions()->FindObject("stats");
+    else
+        s1->SetName((TString)"Stat"+hist1.GetTitle());
+
+    if (s1 && s1->GetX2NDC()>0.95)
+    {
+        const Double_t x1 = s1->GetX1NDC()-0.01;
+        s1->SetX1NDC(x1-(s1->GetX2NDC()-s1->GetX1NDC()));
+        s1->SetX2NDC(x1);
+    }
+
+    //
+    // Draw second histogram
+    //
+    hist2.Draw("sames");
+    gPad->Update();
+
+    //
+    // Draw Legend
+    //
+    // Where to get the TPaveStats depends on the root version
+    TPaveStats *s2 = (TPaveStats*)gPad->FindObject("stats");
+    if (!s2)
+        s2 = (TPaveStats*)hist2.GetListOfFunctions()->FindObject("stats");
+
+    if (s2)
+    {
+        TLegend &l = *new TLegend(s2->GetX1NDC(),
+                                  s2->GetY1NDC()-0.015-(s2->GetY2NDC()-s2->GetY1NDC())/2,
+                                  s2->GetX2NDC(),
+                                  s2->GetY1NDC()-0.01
+                                 );
+        l.AddEntry(&hist1, hist1.GetTitle());
+        l.AddEntry(&hist2, hist2.GetTitle());
+        l.SetTextSize(s2->GetTextSize());
+        l.SetTextFont(s2->GetTextFont());
+        l.SetBorderSize(s2->GetBorderSize());
+        l.SetBit(kCanDelete);
+        l.Draw();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// If the opt string contains 'nonew' or gPad is not given NULL is returned.
+// Otherwise the present gPad is returned.
+//
+TVirtualPad *MH::GetNewPad(TString &opt)
+{
+    opt.ToLower();
+
+    if (!opt.Contains("nonew"))
+        return NULL;
+
+    opt.ReplaceAll("nonew", "");
+
+    return gPad;
+}
+
+// --------------------------------------------------------------------------
+//
+// Encapsulate the TObject::Clone such, that a cloned TH1 (or derived)
+// object is not added to the current directory, when cloned.
+//
+TObject *MH::Clone(const char *name) const
+{
+    const Bool_t store = TH1::AddDirectoryStatus();
+
+    TH1::AddDirectory(kFALSE);
+    TObject *o = MParContainer::Clone(name);
+    TH1::AddDirectory(store);
+
+    return o;
+}
+
+// --------------------------------------------------------------------------
+//
+// If the opt string contains 'nonew' or gPad is not given a new canvas
+// with size w/h is created. Otherwise the object is cloned and drawn
+// to the present pad. The kCanDelete bit is set for the clone.
+//
+TObject *MH::DrawClone(Option_t *opt, Int_t w, Int_t h) const
+{
+    TString option(opt);
+
+    TVirtualPad *p = GetNewPad(option);
+    if (!p)
+        p = MakeDefCanvas(this, w, h);
+    else
+        if (!option.Contains("same", TString::kIgnoreCase))
+            p->Clear();
+
+    gROOT->SetSelectedPad(NULL);
+
+    TObject *o = MParContainer::DrawClone(option);
+    o->SetBit(kCanDelete);
+    return o;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether a class inheriting from MH overwrites the Draw function
+//
+Bool_t MH::OverwritesDraw(TClass *cls) const
+{
+    if (!cls)
+        cls = IsA();
+
+    //
+    // Check whether we reached the base class MTask
+    //
+    if (TString(cls->GetName())=="MH")
+        return kFALSE;
+
+    //
+    // Check whether the class cls overwrites Draw
+    //
+    if (cls->GetMethodAny("Draw"))
+        return kTRUE;
+
+    //
+    // If the class itself doesn't overload it check all it's base classes
+    //
+    TBaseClass *base=NULL;
+    TIter NextBase(cls->GetListOfBases());
+    while ((base=(TBaseClass*)NextBase()))
+    {
+        if (OverwritesDraw(base->GetClassPointer()))
+            return kTRUE;
+    }
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the bins containing only zeros at the edges.
+//
+//  A new number of bins can be defined with nbins != 0
+//        In the case of nbins == 0, no rebinning will take place
+//
+//  Returns the new (real) number of bins
+//
+Int_t MH::StripZeros(TH1 *h, Int_t nbins)
+{
+    TAxis &axe = *h->GetXaxis();
+
+    const Int_t min1   = axe.GetFirst();
+    const Int_t max1   = axe.GetLast();
+    const Int_t range1 = max1-min1;
+
+    //
+    // Check for useless zeros
+    //
+    if (range1 == 0)
+        return 0;
+
+    Int_t min2 = 0;
+    for (int i=min1; i<=max1; i++)
+        if (h->GetBinContent(i) != 0)
+        {
+            min2 = i;
+            break;
+        }
+
+    //
+    // If the histogram consists of zeros only
+    //
+    if (min2 == max1)
+        return 0;
+
+    Int_t max2 = 0;
+    for (int i=max1; i>=min2; i--)
+        if (h->GetBinContent(i) != 0)
+        {
+            max2 = i;
+            break;
+        }
+
+    //
+    // Appying TAxis->SetRange before ReBin does not work ...
+    // But this workaround helps quite fine
+    //
+    Axis_t min = h->GetBinLowEdge(min2);
+    Axis_t max = h->GetBinLowEdge(max2)+h->GetBinWidth(max2);
+
+    Int_t nbins2 = max2-min2;
+    //
+    // Check for rebinning
+    //
+    if (nbins > 0)
+      {
+        const Int_t ngroup = (Int_t)(nbins2*h->GetNbinsX()/nbins/(max1-min1));
+        if (ngroup > 1)
+          {
+            h->Rebin(ngroup);
+            nbins2 /= ngroup;
+          }
+      }
+    
+    Int_t newbins = 0;
+    FindGoodLimits(nbins2, newbins, min, max, kFALSE);
+    axe.SetRangeUser(min,max);
+    return axe.GetLast()-axe.GetFirst();
+}
+
+void MH::ProjectionX(TH1D &dest, const TH2 &src, Int_t firstybin, Int_t lastybin)
+{
+    //*-*-*-*-*Project a 2-D histogram into a 1-D histogram along X*-*-*-*-*-*-*
+    //*-*      ====================================================
+    //
+    //   The projection dest is always of the type TH1D.
+    //   The projection is made from the channels along the Y axis
+    //   ranging from firstybin to lastybin included.
+    //   By default, bins 1 to ny are included
+    //   When all bins are included, the number of entries in the projection
+    //   is set to the number of entries of the 2-D histogram, otherwise
+    //   the number of entries is incremented by 1 for all non empty cells.
+    //
+    //   if Sumw2() was called for dest, the errors are computed.
+    //
+    TAxis &axex = *((TH2&)src).GetXaxis();
+    TAxis &axey = *((TH2&)src).GetYaxis();
+
+    const Int_t nx = axex.GetNbins();
+    const Int_t ny = axey.GetNbins();
+    if (firstybin < 0)
+        firstybin = 1;
+    if (lastybin > ny)
+        lastybin = ny;
+
+    dest.Reset();
+    SetBinning(&dest, &axex);
+
+    // Create the projection histogram
+    const Bool_t computeErrors = dest.GetSumw2N() ? 1 : 0;
+
+    // Fill the projected histogram
+    for (Int_t binx=0; binx<=nx+1; binx++)
+    {
+        Double_t err2 = 0;
+        for (Int_t biny=firstybin; biny<=lastybin; biny++)
+        {
+            const Double_t cont = src.GetCellContent(binx,biny);
+            const Double_t err1 = src.GetCellError(binx,biny);
+            err2 += err1*err1;
+            if (cont)
+                dest.Fill(axex.GetBinCenter(binx), cont);
+        }
+        if (computeErrors)
+            dest.SetBinError(binx, TMath::Sqrt(err2));
+    }
+    if (firstybin <=1 && lastybin >= ny)
+        dest.SetEntries(src.GetEntries());
+}
+
+void MH::ProjectionY(TH1D &dest, const TH2 &src, Int_t firstxbin, Int_t lastxbin)
+{
+    //*-*-*-*-*Project a 2-D histogram into a 1-D histogram along X*-*-*-*-*-*-*
+    //*-*      ====================================================
+    //
+    //   The projection dest is always of the type TH1D.
+    //   The projection is made from the channels along the Y axis
+    //   ranging from firstybin to lastybin included.
+    //   By default, bins 1 to ny are included
+    //   When all bins are included, the number of entries in the projection
+    //   is set to the number of entries of the 2-D histogram, otherwise
+    //   the number of entries is incremented by 1 for all non empty cells.
+    //
+    //   if Sumw2() was called for dest, the errors are computed.
+    //
+    TAxis &axex = *((TH2&)src).GetXaxis();
+    TAxis &axey = *((TH2&)src).GetYaxis();
+
+    const Int_t nx = axex.GetNbins();
+    const Int_t ny = axey.GetNbins();
+    if (firstxbin < 0)
+        firstxbin = 1;
+    if (lastxbin > nx)
+        lastxbin = nx;
+
+    dest.Reset();
+    SetBinning(&dest, &axey);
+
+    // Create the projection histogram
+    const Bool_t computeErrors = dest.GetSumw2N() ? 1 : 0;
+
+    // Fill the projected histogram
+    for (Int_t biny=0; biny<=ny+1; biny++)
+    {
+        Double_t err2 = 0;
+        for (Int_t binx=firstxbin; binx<=lastxbin; binx++)
+        {
+            const Double_t cont = src.GetCellContent(binx,biny);
+            const Double_t err1 = src.GetCellError(binx,biny);
+            err2 += err1*err1;
+            if (cont)
+                dest.Fill(axey.GetBinCenter(biny), cont);
+        }
+        if (computeErrors)
+            dest.SetBinError(biny, TMath::Sqrt(err2));
+    }
+    if (firstxbin <=1 && lastxbin >= nx)
+        dest.SetEntries(src.GetEntries());
+}
+
+// --------------------------------------------------------------------------
+//
+// In contradiction to TPad::FindObject this function searches recursively
+// in a pad for an object. gPad is the default.
+//
+TObject *MH::FindObjectInPad(const char *name, TVirtualPad *pad)
+{
+    if (!pad)
+        pad = gPad;
+
+    if (!pad)
+        return NULL;
+
+    TObject *o;
+
+    TIter Next(pad->GetListOfPrimitives());
+    while ((o=Next()))
+    {
+        if (!strcmp(o->GetName(), name))
+            return o;
+
+        if (o->InheritsFrom("TPad"))
+            if ((o = FindObjectInPad(name, (TVirtualPad*)o)))
+                return o;
+    }
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// M.Gaug added this withouz Documentation
+//
+TH1I* MH::ProjectArray(const TArrayF &array, Int_t nbins, 
+                       const char* name, const char* title)
+{
+    const Int_t size = array.GetSize();
+
+    TH1I *h1=0;
+
+    //check if histogram with identical name exist
+    TObject *h1obj = gROOT->FindObject(name);
+    if (h1obj && h1obj->InheritsFrom("TH1I"))
+    {
+        h1 = (TH1I*)h1obj;
+        h1->Reset();
+    }
+
+    Double_t min = size>0 ? array[0] : 0;
+    Double_t max = size>0 ? array[0] : 1;
+
+    // first loop over array to find the min and max
+    for (Int_t i=1; i<size;i++)
+    {
+        max = TMath::Max((Double_t)array[i], max);
+        min = TMath::Min((Double_t)array[i], min);
+    }
+
+    Int_t newbins = 0;
+    FindGoodLimits(nbins, newbins, min, max, kFALSE);
+
+    if (!h1)
+    {
+        h1 = new TH1I(name, title, nbins, min, max);
+        h1->SetXTitle("");
+        h1->SetYTitle("Counts");
+        h1->SetDirectory(NULL);
+    }
+
+    // Second loop to fill the histogram
+    for (Int_t i=0;i<size;i++)
+        h1->Fill(array[i]);
+
+    return h1;
+}
+
+// --------------------------------------------------------------------------
+//
+// M.Gaug added this withouz Documentation
+//
+TH1I* MH::ProjectArray(const TArrayD &array, Int_t nbins, const char* name, const char* title)
+{
+    const Int_t size = array.GetSize();
+
+    Double_t min = size>0 ? array[0] : 0;
+    Double_t max = size>0 ? array[0] : 1;
+
+    TH1I *h1=0;
+
+    //check if histogram with identical name exist
+    TObject *h1obj = gROOT->FindObject(name);
+    if (h1obj && h1obj->InheritsFrom("TH1I"))
+    {
+        h1 = (TH1I*)h1obj;
+        h1->Reset();
+    }
+
+    // first loop over array to find the min and max
+    for (Int_t i=1; i<size;i++)
+    {
+        max = TMath::Max(array[i], max);
+        min = TMath::Min(array[i], min);
+    }
+
+    Int_t newbins = 0;
+    FindGoodLimits(nbins, newbins, min, max, kFALSE);
+
+    if (!h1)
+    {
+      h1 = new TH1I(name, title, newbins, min, max);
+      h1->SetXTitle("");
+      h1->SetYTitle("Counts");
+      h1->SetDirectory(NULL);
+    }
+    
+    // Second loop to fill the histogram
+    for (Int_t i=0;i<size;i++)
+        h1->Fill(array[i]);
+
+    return h1;
+}
+
+// --------------------------------------------------------------------------
+//
+// M.Gaug added this withouz Documentation
+//
+TH1I* MH::ProjectArray(const MArrayF &array, Int_t nbins, 
+                       const char* name, const char* title)
+{
+    return ProjectArray(TArrayF(array.GetSize(),array.GetArray()), nbins, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+// M.Gaug added this withouz Documentation
+//
+TH1I* MH::ProjectArray(const MArrayD &array, Int_t nbins, const char* name, const char* title)
+{
+    return ProjectArray(TArrayD(array.GetSize(),array.GetArray()), nbins, name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+// See MTask::PrintSkipped
+//
+void MH::PrintSkipped(UInt_t n, const char *str)
+{
+    *fLog << " " << setw(7) << n << " (";
+    *fLog << Form("%5.1f", 100.*n/GetNumExecutions());
+    *fLog << "%) Evts skipped: " << str << endl;
+}
Index: /tags/Mars-V0.9/mhbase/MH.h
===================================================================
--- /tags/Mars-V0.9/mhbase/MH.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MH.h	(revision 9772)
@@ -0,0 +1,121 @@
+#ifndef MARS_MH
+#define MARS_MH
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TH1;
+class TH1I;
+class TH1D;
+class TH2;
+class TH3;
+class TAxis;
+class TArrayF;
+class TArrayD;
+class MArrayF;
+class MArrayD;
+class TCanvas;
+
+class MBinning;
+class MParList;
+
+class MH : public MParContainer
+{
+private:
+    Byte_t fSerialNumber;   // Serial number (eg of telecope)
+    UInt_t fNumExecutions;  // Number of calls to Fill function
+
+public:
+    MH(const char *name=NULL, const char *title=NULL);
+
+    virtual void SetSerialNumber(Byte_t num) { fSerialNumber = num; }
+    Byte_t  GetSerialNumber() const { return fSerialNumber; }
+    TString AddSerialNumber(const char *str) const { TString s(str); if (fSerialNumber==0) return s; s += ";"; s += fSerialNumber; return s; }
+    TString AddSerialNumber(const TString &str) const { return AddSerialNumber((const char*)str); }
+
+    UInt_t GetNumExecutions() const { return fNumExecutions; }
+    void SetNumExecutions(UInt_t n) { fNumExecutions=n; }
+
+    void PrintSkipped(UInt_t n, const char *str);
+
+    Bool_t OverwritesDraw(TClass *cls=NULL) const;
+
+    virtual Bool_t SetupFill(const MParList *pList) { return kTRUE; }
+    virtual Bool_t ReInit(MParList *pList) { return kTRUE; }
+    virtual Bool_t Fill(const MParContainer *par, const Stat_t weight=1);
+    virtual Bool_t Finalize() { return kTRUE; }
+
+    virtual TString GetDataMember() const { return ""; }
+
+    virtual TH1 *GetHistByName(const TString name);
+
+    static TCanvas *MakeDefCanvas(TString name="", const char *title="",
+                                  UInt_t w=625, UInt_t h=440,
+                                  Bool_t usescreenfactor=kTRUE);
+    static TCanvas *MakeDefCanvas(const TObject *obj,
+                                  UInt_t w=625, UInt_t h=440,
+                                  Bool_t usescreenfactor=kFALSE);
+
+    // FIXME: * --> & !!!
+
+    static void SetBinning(TH1 *h, const MBinning *binsx);
+    static void SetBinning(TH2 *h, const MBinning *binsx, const MBinning *binsy);
+    static void SetBinning(TH3 *h, const MBinning *binsx, const MBinning *binsy, const MBinning *binsz);
+
+    static void SetBinning(TH1 *h, const TArrayD &binsx);
+    static void SetBinning(TH2 *h, const TArrayD &binsx, const TArrayD &binsy);
+    static void SetBinning(TH3 *h, const TArrayD &binsx, const TArrayD &binsy, const TArrayD &binsz);
+
+    static void SetBinning(TH1 *h, const TAxis *binsx);
+    static void SetBinning(TH2 *h, const TAxis *binsx, const TAxis *binsy);
+    static void SetBinning(TH3 *h, const TAxis *binsx, const TAxis *binsy, const TAxis *binsz);
+
+    static void SetBinning(TH1 *h, const TH1 *x);
+
+    static void RemoveFirstBin(TH1 &h);
+
+    static Bool_t ApplyBinning(const MParList &plist, TString name, TH1 *h);
+
+    static void    ScaleArray(TArrayD &bins, Double_t f);
+    static TArrayD ScaleAxis(TAxis &axe, Double_t f);
+    static void    ScaleAxis(TH1 *bins, Double_t fx=1, Double_t fy=1, Double_t fz=1);
+
+    static Double_t GetBinCenterLog(const TAxis &axe, Int_t nbin);
+
+    static void DrawSameCopy(const TH1 &hist1, const TH1 &hist2, const TString title);
+    static void DrawSame(TH1 &hist1, TH1 &hist2, const TString title, Bool_t same=kFALSE);
+
+    TObject *Clone(const char *name="") const;
+
+    TObject *DrawClone(Option_t *opt, Int_t w, Int_t h) const;
+    TObject *DrawClone(Option_t *opt="") const
+    {
+        return MH::DrawClone(opt, 625, 440);
+    }
+
+    static TVirtualPad *GetNewPad(TString &opt);
+
+    static void FindGoodLimits(Int_t nbins, Int_t &newbins, Double_t &xmin, Double_t &xmax, Bool_t isInteger);
+    static Double_t GetMinimumGT(const TH1 &h, Double_t gt=0);
+    static Int_t StripZeros(TH1 *h, Int_t nbins);
+
+    static TH1I* ProjectArray(const TArrayF &array, Int_t nbins=30,
+                              const char* name="ProjectArray", const char* title="Projected Array");
+    static TH1I* ProjectArray(const TArrayD &array, Int_t nbins=30,
+                              const char* name="ProjectArray", const char* title="Projected Array");
+    static TH1I* ProjectArray(const MArrayF &array, Int_t nbins=30,
+                              const char* name="ProjectArray", const char* title="Projected Array");
+    static TH1I* ProjectArray(const MArrayD &array, Int_t nbins=30,
+                              const char* name="ProjectArray", const char* title="Projected Array");
+    
+    static void ProjectionX(TH1D &dest, const TH2 &src, Int_t firstybin=-1, Int_t lastybin=9999);
+    static void ProjectionY(TH1D &dest, const TH2 &src, Int_t firstxbin=-1, Int_t lastxbin=9999);
+
+    static TObject *FindObjectInPad(const char *name, TVirtualPad *pad=NULL);
+
+    ClassDef(MH, 2) //A base class for Mars histograms
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhbase/MH3.cc
===================================================================
--- /tags/Mars-V0.9/mhbase/MH3.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MH3.cc	(revision 9772)
@@ -0,0 +1,770 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MH3
+//
+// With this histogram you can fill a histogram with up to three
+// variables from Mars parameter containers in an eventloop.
+//
+// In the constructor you can give up to three variables which should be
+// filled in the histogram. Dependend on the number of given variables
+// (data members) a TH1F, TH2F or TH3F is created.
+// Specify the data mamber like the following:
+//   "MHillas.fLength"
+// Where MHillas is the name of the parameter container in the parameter
+// list and fLength is the name of the data member which should be filled
+// in the histogram. Assuming that your MHillas container has a different
+// name (MyHillas) the name to give would be:
+//   "MyHillas.fLength"
+//
+// The axis binning is retrieved from the parameter list, too. Create a
+// MBinning with the name "Binning" plus the name of your MH3 container
+// plus the axis name ("X", "Y" or "Z") and add it to the parameter list.
+//
+// If you want to use a different unit for histogramming use SetScaleX,
+// SetScaleY and SetScaleZ.
+//
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given the rule for this axis is used.
+// 2) If the MBinning used for this axis has a non-default Title
+//    (MBinning::HasTitle) this title is used for the corresponding axis
+// 3) If the MH3 has a non-default title (MH3::SetTitle called)
+//    this title is set as the histogram title. It can be used to overwrite
+//    the axis titles. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyHist;x[mm];y[cm];Counts");
+//
+// For example:
+//   MH3 myhist("MHillas.fLength");
+//   myhist.SetName("MyHist");
+//   myhist.SetScaleX(geomcam.GetConvMm2Deg()); //convert length to degree
+//   MBinning bins("BinningMyHistX");
+//   bins.SetEdges(10, 0, 150);
+//   plist.AddToList(&myhist);
+//   plist.AddToList(&bins);
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MH3.h"
+
+#include <ctype.h>   // tolower
+#include <fstream>
+
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include <TH2.h>
+#include <TH3.h>
+#include <TProfile.h>
+#include <TProfile2D.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MDataChain.h"
+
+ClassImp(MH3);
+
+using namespace std;
+
+const TString MH3::gsDefName  = "MH3";
+const TString MH3::gsDefTitle = "Container for a n-D Mars Histogram";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MH3::MH3(const unsigned int dim)
+    : fDimension(dim>3?3:dim), fHist(NULL)
+{  
+    switch (fDimension)
+    {
+    case 1:
+        fHist = new TH1F;
+        fHist->SetYTitle("Counts");
+        break;
+    case 2:
+        fHist = new TH2F;
+        fHist->SetZTitle("Counts");
+        break;
+    case 3:
+        fHist = new TH3F;
+        break;
+    }
+
+    fData[0] = NULL;
+    fData[1] = NULL;
+    fData[2] = NULL;
+
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    if (fHist)
+    {
+        fHist->SetDirectory(NULL);
+        fHist->UseCurrentStyle();
+    }
+
+    fScale[0] = 1;
+    fScale[1] = 1;
+    fScale[2] = 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates an TH1F. memberx is filled into the X-bins. For a more detailed
+// description see the class description above.
+//
+MH3::MH3(const char *memberx)
+    : fDimension(1)
+{
+    fHist = new TH1F;
+
+    fData[0] = new MDataChain(memberx);
+    fData[1] = NULL;
+    fData[2] = NULL;
+
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    fHist->UseCurrentStyle();
+    fHist->SetDirectory(NULL);
+    fHist->SetYTitle("Counts");
+
+    fScale[0] = 1;
+    fScale[1] = 1;
+    fScale[2] = 1;
+}
+
+MH3::MH3(const TH1 &h1) : fDimension(1)
+{
+    if (h1.InheritsFrom(TH3::Class()))
+        fDimension = 3;
+    if (h1.InheritsFrom(TH2::Class()))
+        fDimension = 2;
+
+    fData[0] = NULL;
+    fData[1] = NULL;
+    fData[2] = NULL;
+
+    switch (fDimension)
+    {
+    case 3:
+        fData[2] = new MDataChain(h1.GetZaxis()->GetTitle());
+    case 2:
+        fData[1] = new MDataChain(h1.GetYaxis()->GetTitle());
+    case 1:
+        fData[0] = new MDataChain(h1.GetXaxis()->GetTitle());
+    }
+
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    fHist = (TH1*)h1.Clone();
+    fHist->SetDirectory(NULL);
+
+    fScale[0] = 1;
+    fScale[1] = 1;
+    fScale[2] = 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates an TH2F. memberx is filled into the X-bins. membery is filled
+// into the Y-bins. For a more detailed description see the class
+// description above.
+//
+MH3::MH3(const char *memberx, const char *membery)
+    : fDimension(2)
+{
+    fHist = new TH2F;
+
+    fData[0] = new MDataChain(memberx);
+    fData[1] = new MDataChain(membery);
+    fData[2] = NULL;
+
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    fHist->UseCurrentStyle();
+    fHist->SetDirectory(NULL);
+    fHist->SetZTitle("Counts");
+
+    fScale[0] = 1;
+    fScale[1] = 1;
+    fScale[2] = 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates an TH3F. memberx is filled into the X-bins. membery is filled
+// into the Y-bins. membery is filled into the Z-bins. For a more detailed
+// description see the class description above.
+//
+MH3::MH3(const char *memberx, const char *membery, const char *memberz)
+    : fDimension(3)
+{
+    fHist = new TH3F;
+
+    fData[0] = new MDataChain(memberx);
+    fData[1] = new MDataChain(membery);
+    fData[2] = new MDataChain(memberz);
+
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    fHist->UseCurrentStyle();
+    fHist->SetDirectory(NULL);
+
+    fScale[0] = 1;
+    fScale[1] = 1;
+    fScale[2] = 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the histogram
+//
+MH3::~MH3()
+{
+    delete fHist;
+
+    for (int i=0; i<3; i++)
+        if (fData[i])
+            delete fData[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data members used by the data chain to be used in
+// MTask::AddBranchToList
+//
+TString MH3::GetDataMember() const
+{
+    TString str=fData[0]->GetDataMember();
+    if (fData[1])
+    {
+        str += ";";
+        str += fData[1]->GetDataMember();
+    }
+    if (fData[2])
+    {
+        str += ";";
+        str += fData[2]->GetDataMember();
+    }
+    return str;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning are found in the parameter list
+// For a more detailed description see class description above.
+//
+Bool_t MH3::SetupFill(const MParList *plist)
+{
+    // reset histogram (necessary if the same eventloop is run more than once) 
+    fHist->Reset();
+
+    TString bname("Binning");
+    bname += fName;
+
+    MBinning *binsx = NULL;
+    MBinning *binsy = NULL;
+    MBinning *binsz = NULL;
+
+    switch (fDimension)
+    {
+    case 3:
+        binsz = (MBinning*)plist->FindObject(bname+"Z", "MBinning");
+        if (!binsz)
+        {
+            *fLog << err << dbginf << "MBinning '" << bname << "X' not found... aborting." << endl;
+            return kFALSE;
+        }
+        if (fData[2] && !fData[2]->PreProcess(plist))
+            return kFALSE;
+        if (fData[2])
+            fHist->SetZTitle(fData[2]->GetTitle());
+        if (binsz->HasTitle())
+            fHist->SetZTitle(binsz->GetTitle());
+        if (binsz->IsLogarithmic())
+            fHist->SetBit(kIsLogz);
+    case 2:
+        binsy = (MBinning*)plist->FindObject(bname+"Y", "MBinning");
+        if (!binsy)
+        {
+            *fLog << err << dbginf << "MBinning '" << bname << "Y' not found... aborting." << endl;
+            return kFALSE;
+        }
+        if (fData[1] && !fData[1]->PreProcess(plist))
+            return kFALSE;
+        if (fData[1])
+            fHist->SetYTitle(fData[1]->GetTitle());
+        if (binsy->HasTitle())
+            fHist->SetYTitle(binsy->GetTitle());
+        if (binsy->IsLogarithmic())
+            fHist->SetBit(kIsLogy);
+    case 1:
+        binsx = (MBinning*)plist->FindObject(bname+"X", "MBinning");
+        if (!binsx)
+        {
+            if (fDimension==1)
+                binsx = (MBinning*)plist->FindObject(bname, "MBinning");
+
+            if (!binsx)
+            {
+                *fLog << err << dbginf << "Neither MBinning '" << bname << "X' nor '" << bname << "' found... aborting." << endl;
+                return kFALSE;
+            }
+        }
+        if (fData[0] && !fData[0]->PreProcess(plist))
+            return kFALSE;
+        if (fData[0]!=NULL)
+            fHist->SetXTitle(fData[0]->GetTitle());
+        if (binsx->HasTitle())
+            fHist->SetXTitle(binsx->GetTitle());
+        if (binsx->IsLogarithmic())
+            fHist->SetBit(kIsLogx);
+    }
+
+    TString title("Histogram for ");
+    title += fName;
+    title += Form(" (%dD)", fDimension);
+
+    fHist->SetName(fName);
+    fHist->SetTitle(fTitle==gsDefTitle ? title : fTitle);
+    fHist->SetDirectory(0);
+
+    switch (fDimension)
+    {
+    case 1:
+        SetBinning(fHist, binsx);
+        return kTRUE;
+    case 2:
+        SetBinning((TH2*)fHist, binsx, binsy);
+        return kTRUE;
+    case 3:
+        SetBinning((TH3*)fHist, binsx, binsy, binsz);
+        return kTRUE;
+    }
+
+    *fLog << err << "ERROR - MH3 has " << fDimension << " dimensions!" << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the histogram ant the MH3 container
+//
+void MH3::SetName(const char *name)
+{
+    if (fHist)
+    {
+        if (gPad)
+        {
+            const TString pfx(Form("%sProfX", fHist->GetName()));
+            const TString pfy(Form("%sProfY", fHist->GetName()));
+
+            TProfile *p = 0;
+            if ((p=dynamic_cast<TProfile*>(gPad->FindObject(pfx))))
+                p->SetName(Form("%sProfX", name));
+            if ((p=dynamic_cast<TProfile*>(gPad->FindObject(pfy))))
+                p->SetName(Form("%sProfY", name));
+        }
+
+        fHist->SetName(name);
+        fHist->SetDirectory(0);
+
+    }
+    MParContainer::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the histogram ant the MH3 container
+//
+void MH3::SetTitle(const char *title)
+{
+    if (fHist)
+        fHist->SetTitle(title);
+    MParContainer::SetTitle(title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills the one, two or three data members into our histogram
+//
+Bool_t MH3::Fill(const MParContainer *par, const Stat_t w)
+{
+    Double_t x=0;
+    Double_t y=0;
+    Double_t z=0;
+
+    switch (fDimension)
+    {
+    case 3:
+        z = fData[2]->GetValue()*fScale[2];
+    case 2:
+        y = fData[1]->GetValue()*fScale[1];
+    case 1:
+        x = fData[0]->GetValue()*fScale[0];
+    }
+
+    switch (fDimension)
+    {
+    case 3:
+        ((TH3*)fHist)->Fill(x, y, z, w);
+        return kTRUE;
+    case 2:
+        ((TH2*)fHist)->Fill(x, y, w);
+        return kTRUE;
+    case 1:
+        fHist->Fill(x, w);
+        return kTRUE;
+    }
+
+    return kFALSE;
+}
+/*
+// --------------------------------------------------------------------------
+//
+// Set the palette you wanna use:
+//  - you could set the root "Pretty Palette Violet->Red" by
+//    gStyle->SetPalette(1, 0), but in some cases this may look
+//    confusing
+//  - The maximum colors root allowes us to set by ourself
+//    is 50 (idx: 51-100). This colors are set to a grayscaled
+//    palette
+//  - the number of contours must be two less than the number
+//    of palette entries
+//
+void MHStarMap::PrepareDrawing() const
+{
+    const Int_t numg = 32; // number of gray scaled colors
+    const Int_t numw = 32; // number of white
+
+    Int_t palette[numg+numw];
+
+    //
+    // The first half of the colors are white.
+    // This is some kind of optical background supression
+    //
+    gROOT->GetColor(51)->SetRGB(1, 1, 1);
+
+    Int_t i;
+    for (i=0; i<numw; i++)
+        palette[i] = 51;
+
+    //
+    // now the (gray) scaled part is coming
+    //
+    for (;i<numw+numg; i++)
+    {
+        const Float_t gray = 1.0-(float)(i-numw)/(numg-1.0);
+
+        gROOT->GetColor(52+i)->SetRGB(gray, gray, gray);
+        palette[i] = 52+i;
+    }
+
+    //
+    // Set the palette and the number of contour levels
+    //
+    gStyle->SetPalette(numg+numw, palette);
+    fStarMap->SetContour(numg+numw-2);
+}
+*/
+// --------------------------------------------------------------------------
+//
+// Setup a inversed deep blue sea palette for the fCenter histogram.
+//
+void MH3::SetColors() const
+{
+    // FIXME: This must be redone each time the canvas is repainted....
+    gStyle->SetPalette(51, NULL);
+    Int_t c[50];
+    for (int i=0; i<50; i++)
+        c[49-i] = gStyle->GetColorPalette(i);
+    gStyle->SetPalette(50, c);
+}
+
+void MH3::Paint(Option_t *o)
+{
+    TProfile *p=0;
+
+    const TString pfx(Form("%sProfX", fHist->GetName()));
+    if ((p=dynamic_cast<TProfile*>(gPad->FindObject(pfx))))
+    {
+        Int_t col = p->GetLineColor();
+        p = ((TH2*)fHist)->ProfileX(pfx, -1, 9999, "s");
+        p->SetLineColor(col);
+    }
+
+    const TString pfy(Form("%sProfY", fHist->GetName()));
+    if ((p=dynamic_cast<TProfile*>(gPad->FindObject(pfy))))
+    {
+        Int_t col = p->GetLineColor();
+        p = ((TH2*)fHist)->ProfileY(pfy, -1, 9999, "s");
+        p->SetLineColor(col);
+    }
+
+    if (fHist->TestBit(kIsLogx) && fHist->GetEntries()>0) gPad->SetLogx();
+    if (fHist->TestBit(kIsLogy) && fHist->GetEntries()>0) gPad->SetLogy();
+    if (fHist->TestBit(kIsLogz) && fHist->GetEntries()>0) gPad->SetLogz();
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the histogram into it.
+//
+// Possible options are:
+//   PROFX: Draw a x-profile into the histogram (for 2D histograms only)
+//   PROFY: Draw a y-profile into the histogram (for 2D histograms only)
+//   ONLY:  Draw the profile histogram only (for 2D histograms only)
+//   BLUE:  Draw the profile in blue color instead of the histograms line color
+//
+// If the kIsLog?-Bit is set the axis is displayed lkogarithmically.
+// eg this is set when applying a logarithmic MBinning
+//
+// Be careful: The histogram belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MH3::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(fHist);
+    pad->SetBorderMode(0);
+
+    fHist->SetFillStyle(4000);
+
+    TString str(opt);
+    str = str.Strip(TString::kBoth);
+
+    const Bool_t only  = str.Contains("ONLY",  TString::kIgnoreCase) && fDimension==2;
+    const Bool_t same  = str.Contains("SAME",  TString::kIgnoreCase) && fDimension==2;
+    const Bool_t blue  = str.Contains("BLUE",  TString::kIgnoreCase) && fDimension==2;
+    const Bool_t profx = str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2;
+    const Bool_t profy = str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2;
+
+    str.ReplaceAll("only",  "");
+    str.ReplaceAll("blue",  "");
+    str.ReplaceAll("profx", "");
+    str.ReplaceAll("profy", "");
+
+    // FIXME: We may have to remove all our own options from str!
+    if (!only)
+        fHist->Draw(str);
+
+    AppendPad();
+
+    TProfile *p=0;
+    if (profx)
+    {
+        const TString pfx(Form("%sProfX", fHist->GetName()));
+
+        if (same && (p=dynamic_cast<TProfile*>(gPad->FindObject(pfx))))
+            *fLog << warn << "TProfile " << pfx << " already in pad." << endl;
+
+        p = ((TH2*)fHist)->ProfileX(pfx, -1, 9999, "s");
+        p->UseCurrentStyle();
+        p->SetLineColor(blue ? kBlue : fHist->GetLineColor());
+        p->SetBit(kCanDelete);
+        p->SetDirectory(NULL);
+        p->SetXTitle(fHist->GetXaxis()->GetTitle());
+        p->SetYTitle(fHist->GetYaxis()->GetTitle());
+        p->Draw(only&&!same?"":"same");
+    }
+    if (profy)
+    {
+        const TString pfy(Form("%sProfY", fHist->GetName()));
+
+        if (same && (p=dynamic_cast<TProfile*>(gPad->FindObject(pfy))))
+            *fLog << warn << "TProfile " << pfy << " already in pad." << endl;
+
+        p = ((TH2*)fHist)->ProfileY(pfy, -1, 9999, "s");
+        p->UseCurrentStyle();
+        p->SetLineColor(blue ? kBlue : fHist->GetLineColor());
+        p->SetBit(kCanDelete);
+        p->SetDirectory(NULL);
+        p->SetYTitle(fHist->GetXaxis()->GetTitle());
+        p->SetXTitle(fHist->GetYaxis()->GetTitle());
+        p->Draw(only&&!same?"":"same");
+    }
+
+    //AppendPad("log");
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MH3::StreamPrimitive(ofstream &out) const
+{
+    TString name = GetUniqueName();
+
+    out << "   MH3 " << name << "(\"";
+    out << fData[0]->GetRule() << "\"";
+    if (fDimension>1)
+        out << ", \"" << fData[1]->GetRule() << "\"";
+    if (fDimension>2)
+        out << ", \"" << fData[2]->GetRule() << "\"";
+
+    out << ");" << endl;
+
+    if (fName!=gsDefName)
+        out << "   " << name << ".SetName(\"" << fName << "\");" << endl;
+
+    if (fTitle!=gsDefTitle)
+        out << "   " << name << ".SetTitle(\"" << fTitle << "\");" << endl;
+
+    switch (fDimension)
+    {
+    case 3:
+        if (fScale[2]!=1)
+            out << "   " << name << ".SetScaleZ(" << fScale[2] << ");" << endl;
+    case 2:
+        if (fScale[1]!=1)
+            out << "   " << name << ".SetScaleY(" << fScale[1] << ");" << endl;
+    case 1:
+        if (fScale[0]!=1)
+            out << "   " << name << ".SetScaleX(" << fScale[0] << ");" << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Used to rebuild a MH3 object of the same type (data members,
+// dimension, ...)
+//
+MParContainer *MH3::New() const
+{
+    MH3 *h = NULL;
+
+    if (fData[0] == NULL)
+        h=new MH3(fDimension);
+    else
+        switch (fDimension)
+        {
+        case 1:
+            h=new MH3(fData[0]->GetRule());
+            break;
+        case 2:
+            h=new MH3(fData[0]->GetRule(), fData[1]->GetRule());
+            break;
+        case 3:
+            h=new MH3(fData[0]->GetRule(), fData[1]->GetRule(), fData[2]->GetRule());
+            break;
+        }
+    switch (fDimension)
+    {
+    case 3:
+        h->SetScaleZ(fScale[2]);
+    case 2:
+        h->SetScaleY(fScale[1]);
+    case 1:
+        h->SetScaleX(fScale[0]);
+    }
+    return h;
+}
+
+TString MH3::GetRule(const Char_t axis) const
+{
+    switch (tolower(axis))
+    {
+    case 'x':
+        return fData[0] ? fData[0]->GetRule() : TString("");
+    case 'y':
+        return fData[1] ? fData[1]->GetRule() : TString("");
+    case 'z':
+        return fData[2] ? fData[2]->GetRule() : TString("");
+    default:
+        return "<n/a>";
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the total number of bins in a histogram (excluding under- and
+// overflow bins)
+//
+Int_t MH3::GetNbins() const
+{
+    Int_t num = 1;
+
+    switch (fDimension)
+    {
+    case 3:
+        num *= fHist->GetNbinsZ()+2;
+    case 2:
+        num *= fHist->GetNbinsY()+2;
+    case 1:
+        num *= fHist->GetNbinsX()+2;
+    }
+
+    return num;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the total number of bins in a histogram (excluding under- and
+// overflow bins) Return -1 if bin is underflow or overflow
+//
+Int_t MH3::FindFixBin(Double_t x, Double_t y, Double_t z) const
+{
+    const TAxis &axex = *fHist->GetXaxis();
+    const TAxis &axey = *fHist->GetYaxis();
+    const TAxis &axez = *fHist->GetZaxis();
+
+    Int_t binz = 0;
+    Int_t biny = 0;
+    Int_t binx = 0;
+
+    switch (fDimension)
+    {
+    case 3:
+        binz = axez.FindFixBin(z);
+        if (binz>axez.GetLast() || binz<axez.GetFirst())
+            return -1;
+    case 2:
+        biny = axey.FindFixBin(y);
+        if (biny>axey.GetLast() || biny<axey.GetFirst())
+            return -1;
+    case 1:
+        binx = axex.FindFixBin(x);
+        if (binx<axex.GetFirst() || binx>axex.GetLast())
+            return -1;
+    }
+
+    const Int_t nx = fHist->GetNbinsX()+2;
+    const Int_t ny = fHist->GetNbinsY()+2;
+
+    return binx + nx*(biny +ny*binz);
+}
Index: /tags/Mars-V0.9/mhbase/MH3.h
===================================================================
--- /tags/Mars-V0.9/mhbase/MH3.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MH3.h	(revision 9772)
@@ -0,0 +1,85 @@
+#ifndef MARS_MH3
+#define MARS_MH3
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1;
+class TMethodCall;
+class MDataChain;
+
+class MH3 : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+protected:
+    // Could be const but root < 3.02/06 doesn't like this...
+    Int_t       fDimension;      // Number of dimensions of histogram
+    TH1        *fHist;           // Histogram to fill
+    MDataChain *fData[3];        // Object from which the data is filled
+    Double_t    fScale[3];       // Scale for the three axis (eg unit)
+
+    // TString     fNameProfX;      //! This should make sure, that gROOT doen't confuse the profile with something else
+    // TString     fNameProfY;      //! This should make sure, that gROOT doen't confuse the profile with something else
+
+    void StreamPrimitive(ofstream &out) const;
+
+    enum {
+        kIsLogx = BIT(17),
+        kIsLogy = BIT(18),
+        kIsLogz = BIT(19)
+    };
+
+//    Int_t DistancetoPrimitive(Int_t px, Int_t py);
+//    void  ExecuteEvent(Int_t event, Int_t px, Int_t py);
+
+public:
+    MH3(const unsigned int dim=0);
+    MH3(const TH1 &h1);
+    MH3(const char *memberx);
+    MH3(const char *memberx, const char *membery);
+    MH3(const char *memberx, const char *membery, const char *memberz);
+    ~MH3();
+
+    void SetScaleX(Double_t scale) { fScale[0] = scale; }
+    void SetScaleY(Double_t scale) { fScale[1] = scale; }
+    void SetScaleZ(Double_t scale) { fScale[2] = scale; }
+
+    void SetLogx(Bool_t b=kTRUE) { b ? fHist->SetBit(kIsLogx) : fHist->ResetBit(kIsLogx); }
+    void SetLogy(Bool_t b=kTRUE) { b ? fHist->SetBit(kIsLogy) : fHist->ResetBit(kIsLogy); }
+    void SetLogz(Bool_t b=kTRUE) { b ? fHist->SetBit(kIsLogz) : fHist->ResetBit(kIsLogz); }
+
+    Int_t GetDimension() const { return fDimension; }
+    Int_t GetNbins() const;
+    Int_t FindFixBin(Double_t x, Double_t y=0, Double_t z=0) const;
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TString GetDataMember() const;
+    TString GetRule(const Char_t axis='x') const;
+
+    TH1 &GetHist() { return *fHist; }
+    const TH1 &GetHist() const { return *fHist; }
+
+    TH1 *GetHistByName(const TString name="") { return fHist; }
+
+    void SetColors() const;
+    void Draw(Option_t *opt=NULL);
+    void Paint(Option_t *opt="");
+
+    MParContainer *New() const;
+
+    ClassDef(MH3, 1) // Generalized 1/2/3D-histogram for Mars variables
+};
+
+#endif
Index: /tags/Mars-V0.9/mhbase/MHArray.cc
===================================================================
--- /tags/Mars-V0.9/mhbase/MHArray.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MHArray.cc	(revision 9772)
@@ -0,0 +1,772 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHArray
+//
+//  is a sequential collection of mars histograms. If the given index to
+//  call the Fill function of the histogram excceeds the size of the
+//  array by 1 a new entry is created.
+//
+//  With Set/Inc/DecIndex you may specify the actual index of the histogram
+//  wich should be filles by Fill.
+//
+//  Use GetH to get the current histogram, the []-operator get the histogram
+//  by its index.
+//
+//  To access the histograms by a key instead of an index use SetIndexByKey
+//  instead of Set/Inc/DecIndex. It will take the integerpart of the
+//  floating point value (2 in case of 2.9). For each new key a new
+//  index in the Mapping Table is created. So that you can access your
+//  histograms by the key (eg in case of the Angle Theta=23.2deg use
+//  SetIndexByKey(23.2)
+//
+//  If the index is equal to the number of histograms in the array a call
+//  to the Fill-member-function will create a new histogram.
+//
+//  In the constructor istempl leads to two different behaviours of the
+//  MHArray:
+//
+//  - istempl=kTRUE tells MHArray to use the first histogram retrieved from
+//    the Parameterlist by hname to be used as a template. New histograms
+//    are not created using the root dictionary, but the New-member function
+//    (see MParConatiner)
+//  - In the case istempl=kFALSE new histograms are created using the root
+//    dictionary while hname is the class name. For the creation their
+//    default constructor is used.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHArray.h"
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TStyle.h>
+#include <TGaxis.h>
+#include <TCanvas.h>
+#include <TLegend.h>
+#include <TPaveStats.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MParContainer.h"
+
+#include "MBinning.h"
+
+ClassImp(MHArray);
+
+using namespace std;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MMap
+//
+// This class maps a key-value to a given value. In its simple versions it
+// maps a key to an index.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include <TArrayI.h>
+
+class MMap
+{
+private:
+    TArrayI fKeys;
+    TArrayI fValues;
+
+    Int_t K(Int_t i) const { return ((TArrayI)fKeys)[i]; }
+    Int_t V(Int_t i) const { return ((TArrayI)fValues)[i]; }
+
+public:
+    // --------------------------------------------------------------------------
+    //
+    // Return the size of the table
+    //
+    Int_t GetSize() const
+    {
+        return fKeys.GetSize();
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    // Get the value which corresponds to the given key-value
+    //
+    Int_t GetValue(Int_t key) const
+    {
+        const Int_t n = fKeys.GetSize();
+        for (int i=0; i<n; i++)
+        {
+            if (K(i)==key)
+                return V(i);
+        }
+        return -1;
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    // Get the key which corresponds to the given index
+    //
+    Int_t GetKey(Int_t value) const
+    {
+        const Int_t n = fKeys.GetSize();
+        for (int i=0; i<n; i++)
+        {
+            if (V(i)==value)
+                return K(i);
+        }
+        return -1;
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    // Adds a new pair key-value. While the key is the key to the value.
+    // if the key already exists the pair is ignored.
+    //
+    void Add(Int_t key, Int_t value)
+    {
+        if (GetValue(key)>=0)
+            return;
+
+        const Int_t n = fKeys.GetSize();
+
+        fKeys.Set(n+1);
+        fValues.Set(n+1);
+
+        fKeys[n] = key;
+        fValues[n] = value;
+    }
+
+    // --------------------------------------------------------------------------
+    //
+    // Adds a new pair key-value. While the key is the key to the value.
+    // In this case the value is an automatically sequential created index.
+    // if the key already exists the pair is ignored.
+    //
+    Int_t Add(Int_t key)
+    {
+        const Int_t k = GetValue(key);
+        if (k>=0)
+            return k;
+
+        const Int_t n = fKeys.GetSize();
+
+        fKeys.Set(n+1);
+        fValues.Set(n+1);
+
+        fKeys[n] = key;
+        fValues[n] = n;
+
+        return n;
+    }
+};
+
+void MHArray::Init(const char *name)
+{
+    fName  = name  ? name  : "MHArray";
+
+    fMapIdx = new MMap;
+
+    fArray = new TList;
+    fArray->SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Can replace a constructor. Use the default constructor and afterwards
+// the Set function of your need.
+//
+void MHArray::Set(const TString hname, Bool_t istempl)
+{
+    if (fTemplate || fClass || fTemplateName!="<dummy>")
+    {
+        *fLog << warn << "WARNING - MHArray already setup... Set ignored." << endl;
+        return;
+    }
+
+    if (istempl)
+    {
+        fTemplateName = hname;
+        return;
+    }
+
+    //
+    // try to get class from root environment
+    //
+    fClass = gROOT->GetClass(hname);
+    if (!fClass)
+    {
+        //
+        // if class is not existing in the root environment
+        //
+        *fLog << err << dbginf << "Class '" << hname << "' not existing in dictionary." << endl;
+    }
+
+    //
+    // check for ineritance from MH
+    //
+    if (!fClass->InheritsFrom(MH::Class()))
+    {
+        //
+        // if class doesn't inherit from MH --> error
+        //
+        *fLog << err << dbginf << "Class '" << hname << "' doesn't inherit from MH." << endl;
+        fClass = NULL;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Can replace a constructor. Use the default constructor and afterwards
+// the Set function of your need.
+//
+void MHArray::Set(const MH *hist)
+{
+    fIdx=0;
+    fClass=NULL;
+    fTemplate=hist;
+    fTemplateName="<dummy>";
+}
+
+
+// --------------------------------------------------------------------------
+//
+// hname is the name of the histogram class which is in the array.
+//
+// istempl=kTRUE tells MHArray to use the first histogram retrieved from the
+// ParameterList by hname to be used as a template. New histograms are not
+// created using the root dictionary, but the New-member function (see
+// MParConatiner)
+// In the case istempl=kFALSE new histograms are created using the root
+// dictionary while hname is the class name. For the creation their
+// default constructor is used.
+//
+MHArray::MHArray(const TString hname, Bool_t istempl, const char *name, const char *title)
+    : fIdx(0), fClass(NULL), fTemplate(NULL)
+{
+    //
+    //   set the name and title of this object
+    //
+    Init(name);
+    fTitle = title ? TString(title) : (TString("Base class for Mars histogram arrays:") + hname);
+
+    Set(hname, istempl);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Use MHArray::Set to setup the MHArray afterwards
+//
+MHArray::MHArray(const char *name, const char *title)
+    : fIdx(0), fClass(NULL), fTemplate(NULL), fTemplateName("<dummy>")
+{
+    //
+    //   set the name and title of this object
+    //
+    Init(name);
+    fTitle = title ? title : "A Mars histogram array";
+}
+
+// --------------------------------------------------------------------------
+//
+// hname is the name of the histogram class which is in the array.
+//
+// istempl=kTRUE tells MHArray to use the first histogram retrieved from the
+// ParameterList by hname to be used as a template. New histograms are not
+// created using the root dictionary, but the New-member function (see
+// MParConatiner)
+// In the case istempl=kFALSE new histograms are created using the root
+// dictionary while hname is the class name. For the creation their
+// default constructor is used.
+//
+MHArray::MHArray(const MH *hist, const char *name, const char *title)
+    : fIdx(0), fClass(NULL), fTemplate(hist), fTemplateName("<dummy>")
+{
+    //
+    //   set the name and title of this object
+    //
+    Init(name);
+    fTitle = title ? TString(title) : (TString("Base class for Mars histogram arrays:") + hist->GetName());
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor: Deleteing the array and all histograms which are part of the
+// array.
+//
+MHArray::~MHArray()
+{
+    fArray->Delete();
+    delete fArray;
+    delete fMapIdx;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Use this to access the histograms by a key. If you use values like
+//   (in this order) 2.5, 7.2, 2.5, 9.3, 9.3, 3.3, 2.2, 1.1
+//  it will be mapped to the following indices internally:
+//                    0    1    0    2    2    3    4    5
+//
+//  WARNING: Make sure that you don't create new histograms by setting
+//           a new index (SetIndex or IncIndex) which is equal the size
+//           of the array and create new histogram by CreateH. In this
+//           case you will confuse the mapping completely.
+//
+void MHArray::SetIndexByKey(Double_t key)
+{
+    fIdx = fMapIdx->Add((Int_t)key);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Use this function to access a histogram by its index in the array.
+//  Becarefull the index isn't checked!
+//
+MH &MHArray::operator[](Int_t i)
+{
+    return *(MH*)fArray->At(i);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Use this function to access a histogram by its index in the array.
+//  Becarefull the index isn't checked!
+//
+MH *MHArray::At(Int_t i)
+{
+    return (MH*)fArray->At(i);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Use this function to access the histogram corresponding to the
+//  currently set index (by Set/Inc/DecIndex or SetIndexByKey)
+//  Becarefull the index set isn't checked!
+//
+MH *MHArray::GetH()
+{
+    return (MH*)fArray->At(fIdx);
+}
+
+// --------------------------------------------------------------------------
+//
+// Tries to create a new histogram, adds it as last entry to the array
+// and tries to call SetupFill for it. In case of success the last entry
+// in the array is the new histogram and kTRUE is returned. Otherwise
+// kFALSE is returned.
+//
+Bool_t MHArray::CreateH()
+{
+    TString cname = fClass ? fClass->GetName() : fTemplate->IsA()->GetName();
+
+    MH *hist = NULL;
+    if (fTemplate)
+    {
+        //
+        // create the parameter container as a clone of the existing
+        // template histogram.
+        //
+        hist = (MH*)fTemplate->New();
+    }
+    else
+    {
+        //
+        // create the parameter container of the the given class type
+        //
+        hist = (MH*)fClass->New();
+    }
+    if (!hist)
+    {
+        *fLog << err << dbginf << "Cannot create new instance of class '";
+        *fLog << cname << "' (Maybe no def. constructor)" << endl;
+        return kFALSE;
+    }
+
+    //
+    // Set the name of the container
+    //
+    if (!fTemplate)
+    {
+        TString name = TString(hist->GetName())+";";
+        name += fIdx;
+
+        hist->SetName(name);
+    }
+
+    //
+    // Try to setup filling for the histogram
+    //
+    if (!hist->SetupFill(fParList))
+    {
+        *fLog << err << dbginf << "SetupFill for new histogram of type '";
+        *fLog << cname << "' with Index #" << fIdx << " failed." << endl;
+        delete hist;
+        return kFALSE;
+    }
+
+    fArray->AddLast(hist);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns kFALSE if the class couldn't be found in the root dictionary or
+// if it doesn't inherit from MH.
+// The parameter list is remembert to be used for SetupFill in case a new
+// histogram is created.
+// The index is reset to 0
+//
+Bool_t MHArray::SetupFill(const MParList *pList)
+{
+    fParList = pList;
+    fIdx = 0;
+
+    if (fTemplate)
+        return kTRUE;
+
+    if (!fTemplateName.IsNull())
+    {
+        fTemplate = (MH*)pList->FindObject(fTemplateName, "MH");
+        return fTemplate ? kTRUE : kFALSE;
+    }
+
+    return fClass ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call Fill for the present histogram index. If the index is out of
+// bounds the event is skipped. If the index is the number of current
+// histograms in the array a new histogram is created and if creation was
+// successfull filled.
+//
+Bool_t MHArray::Fill(const MParContainer *par, const Stat_t w)
+{
+    const Int_t n = fArray->GetSize();
+
+    if (fIdx<0 || fIdx>n)
+    {
+        *fLog << warn << "Histogram Index #" << fIdx << " out of bounds (>";
+        *fLog << n << ")... skipped." << endl;
+        return kCONTINUE;
+    }
+
+    if (fIdx==n)
+        if (!CreateH())
+            return kFALSE;
+
+    return GetH()->Fill(par, w);
+}
+
+Bool_t MHArray::AddHistogram()
+{
+    fIdx=fArray->GetSize();
+
+    return CreateH();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls Finalize for all histograms in the list. If at least one Finalize
+// fails kFALSE is returned.
+//
+Bool_t MHArray::Finalize()
+{
+    Bool_t rc = kTRUE;
+
+    TIter Next(fArray);
+    MH *hist = NULL;
+
+    while ((hist=(MH*)Next()))
+        if (!hist->Finalize())
+            rc = kFALSE;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the number of entries in the array
+//
+void MHArray::Print(Option_t *option) const
+{
+    *fLog << all << GetDescriptor() << " contains " << fArray->GetSize();
+    *fLog << " histograms." << endl;
+
+    if (fMapIdx->GetSize()<=0)
+        return;
+
+    *fLog << " idx\t     key" << endl;
+    for (int i=0; i<fMapIdx->GetSize(); i++)
+        *fLog << "  " << i << "\t<-->  " << fMapIdx->GetKey(i) << endl;
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Adds the given object to the given legend (if != NULL). The Legend
+// entry name is created from the key...
+//
+void MHArray::AddLegendEntry(TLegend *leg, TObject *obj, Int_t idx) const
+{
+    if (!leg)
+        return;
+
+    TString name = " ";
+    name += fMapIdx->GetKey(idx);
+    leg->AddEntry(obj, name, "lpf"); // l=line, p=polymarker, f=fill
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The option is the name of the histogram, used to get a histogram from
+// the MH entries by calling their GetHist function.
+//
+void MHArray::Draw(Option_t *opt)
+{
+    if (!gPad)
+        MH::MakeDefCanvas(this);
+
+    const Int_t sstyle = gStyle->GetOptStat();
+    gStyle->SetOptStat(0);
+
+    //
+    // if the keymapping is used create a legend to identify the histograms
+    //
+    TLegend *leg = NULL;
+    if (fMapIdx->GetSize()>0)
+    {
+        leg = new TLegend(0.85, 0.80, 0.99, 0.99);
+        leg->SetBit(kCanDelete);
+    }
+
+    TIter Next(fArray);
+    MH *hist = (MH*)Next();
+
+    Int_t idx=0;
+    Double_t max=0;
+    Double_t min=0;
+
+    TH1 *h1=NULL;
+
+    //
+    // If the array has at least one entry:
+    //  - find the starting boundaries
+    //  - draw it and set its line color
+    //
+    if (hist)
+    {
+        if ((h1 = hist->GetHistByName(opt)))
+        {
+            h1->Draw();
+            h1->SetLineColor(idx+2);
+            max = h1->GetMaximum();
+            min = h1->GetMinimum();
+
+            AddLegendEntry(leg, h1, idx);
+        }
+    }
+
+    //
+    // For all following histograms:
+    //  - update the boundaries
+    //  - draw it and set its line color
+    //
+    while ((hist=(MH*)Next()))
+    {
+        TH1 *h=NULL;
+
+        if (!(h = hist->GetHistByName(opt)))
+            continue;
+
+        h->Draw("same");
+        h->SetLineColor(idx+2);
+        if (max<h->GetMaximum())
+            max = h->GetMaximum();
+        if (min>h->GetMinimum())
+            min = h->GetMinimum();
+
+        AddLegendEntry(leg, h, idx++);
+    }
+
+    //
+    // Now update the drawing region so that everything is displayed
+    //
+    if (h1)
+    {
+        h1->SetMinimum(min>0 ? min*0.95 : min*1.05);
+        h1->SetMaximum(max>0 ? max*1.05 : max*0.95);
+    }
+
+    if (leg)
+        leg->Draw();
+
+    gPad->Modified();
+    gPad->Update();
+
+    gStyle->SetOptStat(sstyle);
+}
+
+// --------------------------------------------------------------------------
+//
+// The option is the name of the histogram, used to get a histogram from
+// the MH entries by calling their GetHistByName function.
+// If the option also contains 'nonew' no new canvas is created.
+// The option "Scale=1" scales the area of all histogram to 1
+// The option "Scale=max" scales the maximum of all histogram to 1
+//
+TObject *MHArray::DrawClone(Option_t *opt) const
+{
+    TString o(opt);
+
+    TCanvas *c = NULL;
+
+    Int_t scale1   = o.Index("scale=1",   TString::kIgnoreCase);
+    Int_t scalemax = o.Index("scale=max", TString::kIgnoreCase);
+    Int_t nonew    = o.Index("nonew",     TString::kIgnoreCase);
+
+    if (o.BeginsWith("scale=1", TString::kIgnoreCase))
+        scale1 = 0;
+    if (o.BeginsWith("scale=max", TString::kIgnoreCase))
+        scalemax = 0;
+    if (o.BeginsWith("nonew", TString::kIgnoreCase))
+        nonew = 0;
+
+    if (nonew>=0)
+    {
+        c = MH::MakeDefCanvas(this);
+
+        //
+        // This is necessary to get the expected bahviour of DrawClone
+        //
+        gROOT->SetSelectedPad(NULL);
+
+        o.Remove(nonew, 5);
+    }
+    if (scale1>=0)
+        o.Remove(scale1, 7);
+    if (scalemax>=0)
+        o.Remove(scalemax, 9);
+
+    const Int_t sstyle = gStyle->GetOptStat();
+    gStyle->SetOptStat(0);
+
+    //
+    // if the keymapping is used create a legend to identify the histograms
+    //
+    TLegend *leg = NULL;
+    if (fMapIdx->GetSize()>0)
+    {
+        leg = new TLegend(0.85, 0.80, 0.99, 0.99);
+        leg->SetBit(kCanDelete);
+    }
+
+    TIter Next(fArray);
+    MH *hist = (MH*)Next();
+
+    Int_t idx=0;
+    Double_t max=0;
+    Double_t min=0;
+
+    TH1 *h1=NULL;
+
+     //
+    // If the array has at least one entry:
+    //  - find the starting boundaries
+    //  - draw it and set its line color
+    //
+    if (hist)
+    {
+        if ((h1 = hist->GetHistByName(o)))
+        {
+            h1 = (TH1*)h1->DrawCopy();
+
+            if (scale1>=0)
+                h1->Scale(1./h1->Integral());
+            if (scalemax>=0)
+                h1->Scale(1./h1->GetMaximum());
+
+            h1->SetMarkerColor(idx);
+            h1->SetLineColor(idx+2);
+            h1->SetFillStyle(4000);
+            max = h1->GetMaximum();
+            min = h1->GetMinimum();
+
+            AddLegendEntry(leg, h1, idx++);
+        }
+    }
+
+    //
+    // For all following histograms:
+    //  - update the boundaries
+    //  - draw it and set its line color
+    //
+    while ((hist=(MH*)Next()))
+    {
+        TH1 *h=NULL;
+
+        if (!(h = hist->GetHistByName(o)))
+            continue;
+
+        h = (TH1*)h->DrawCopy("same");
+
+        if (scale1>=0)
+            h->Scale(1./h->Integral());
+        if (scalemax>=0)
+            h->Scale(1./h->GetMaximum());
+
+        h->SetMarkerColor(idx);
+        h->SetLineColor(idx+2);
+        h->SetFillStyle(4000); // transperent (why is this necessary?)
+        if (max<h->GetMaximum())
+            max = h->GetMaximum();
+        if (min>h->GetMinimum())
+            min = h->GetMinimum();
+
+        AddLegendEntry(leg, h, idx++);
+    }
+
+    //
+    // Now update the drawing region so that everything is displayed
+    //
+    if (h1)
+    {
+        h1->SetMinimum(min>0 ? min*0.95 : min*1.05);
+        h1->SetMaximum(max>0 ? max*1.05 : max*0.95);
+    }
+
+    if (leg)
+        leg->Draw();
+
+    gPad->Modified();
+    gPad->Update();
+
+    gStyle->SetOptStat(sstyle);
+
+    return c;
+}
Index: /tags/Mars-V0.9/mhbase/MHArray.h
===================================================================
--- /tags/Mars-V0.9/mhbase/MHArray.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MHArray.h	(revision 9772)
@@ -0,0 +1,71 @@
+#ifndef MARS_MHArray
+#define MARS_MHArray
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TList;
+class TLegend;
+
+class MMap;
+
+class MHArray : public MH
+{
+private:
+    Int_t  fIdx;              // current index for the fill function
+    TList *fArray;            //-> Array storing the histograms
+
+    const MParList *fParList; //! pointer to parameter list used for SetupFill when a new Hist is created
+    TClass *fClass;           // pointer to class entry in root dictionary
+
+    const MH *fTemplate;      //-> pointer to a template histogram
+    TString fTemplateName;    // name of the template class
+
+    MMap *fMapIdx;            //! Table to map keys to array indices
+
+    Bool_t CreateH();
+    void   AddLegendEntry(TLegend *leg, TObject *obj, Int_t idx) const;
+
+    enum { kUseTemplate=BIT(14) };
+
+    void Init(const char *name);
+
+public:
+    MHArray(const char *name=NULL, const char *title=NULL);
+    MHArray(const TString hname, Bool_t istempl=kFALSE, const char *name=NULL, const char *title=NULL);
+    MHArray(const MH *hist, const char *name=NULL, const char *title=NULL);
+    ~MHArray();
+
+    void Set(const TString hname, Bool_t istempl=kFALSE);
+    void Set(const MH *hist);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    Bool_t AddHistogram();
+
+    MH &operator[](Int_t i);
+    MH *At(Int_t i);
+
+    MH *GetH();
+
+    void SetIndexByKey(Double_t key);
+
+    void SetIndex(Int_t i) { fIdx=i; }
+    void IncIndex() { fIdx++; }
+    void DecIndex() { fIdx--; }
+
+    Int_t GetIndex() const { return fIdx; }
+
+    void Print(Option_t *option="") const;
+
+    void Draw(Option_t *opt="");
+    TObject *DrawClone(Option_t *opt="") const;
+
+    ClassDef(MHArray, 0) //A histogram class for an array of Mars histograms
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhbase/MHMatrix.cc
===================================================================
--- /tags/Mars-V0.9/mhbase/MHMatrix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MHMatrix.cc	(revision 9772)
@@ -0,0 +1,1263 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz   2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Rudy Boeck     2003 <mailto:
+!              Wolfgang Wittek2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHMatrix
+//
+// This is a histogram container which holds a matrix with one column per
+// data variable. The data variable can be a complex rule (MDataChain).
+// Each event for wich Fill is called (by MFillH) is added as a new
+// row to the matrix.
+//
+// For example:
+//   MHMatrix m;
+//   m.AddColumn("MHillas.fSize");
+//   m.AddColumn("MMcEvt.fImpact/100");
+//   m.AddColumn("HillasSource.fDist*MGeomCam.fConvMm2Deg");
+//   MFillH fillm(&m);
+//   taskliost.AddToList(&fillm);
+//   [...]
+//   m.Print();
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHMatrix.h"
+
+#include <fstream>
+
+#include <TList.h>
+#include <TArrayF.h>
+#include <TArrayD.h>
+#include <TArrayI.h>
+#include <TVector.h>
+
+#include <TH1.h>
+#include <TCanvas.h>
+#include <TRandom3.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MFillH.h"
+#include "MEvtLoop.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MProgressBar.h"
+
+#include "MData.h"
+#include "MDataArray.h"
+#include "MFilter.h"
+
+ClassImp(MHMatrix);
+
+using namespace std;
+
+const TString MHMatrix::gsDefName  = "MHMatrix";
+const TString MHMatrix::gsDefTitle = "Multidimensional Matrix";
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor
+//
+MHMatrix::MHMatrix(const char *name, const char *title)
+    : fNumRows(0), fData(NULL)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor
+//
+MHMatrix::MHMatrix(const TMatrix &m, const char *name, const char *title)
+    : fNumRows(m.GetNrows()), fM(m), fData(NULL)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Constructor. Initializes the columns of the matrix with the entries
+//  from a MDataArray
+//
+MHMatrix::MHMatrix(MDataArray *mat, const char *name, const char *title)
+    : fNumRows(0), fData(mat)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. Does not deleted a user given MDataArray, except IsOwner
+//  was called.
+//
+MHMatrix::~MHMatrix()
+{
+    if (TestBit(kIsOwner) && fData)
+        delete fData;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MHMatrix::SetNumRow(Int_t row) 
+{
+    if (row>=fM.GetNrows() || row<0) return kFALSE;
+    fRow = row;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new column to the matrix. This can only be done before the first
+// event (row) was filled into the matrix. For the syntax of the rule
+// see MDataChain.
+// Returns the index of the new column, -1 in case of failure.
+// (0, 1, 2, ... for the 1st, 2nd, 3rd, ...)
+//
+Int_t MHMatrix::AddColumn(const char *rule)
+{
+    if (fM.IsValid())
+    {
+        *fLog << warn << "Warning - matrix is already in use. Can't add a new column... skipped." << endl;
+        return -1;
+    }
+
+    if (TestBit(kIsLocked))
+    {
+        *fLog << warn << "Warning - matrix is locked. Can't add new column... skipped." << endl;
+        return -1;
+    }
+
+    if (!fData)
+    {
+        fData = new MDataArray;
+        SetBit(kIsOwner);
+    }
+
+    const Int_t idx = fData->FindRule(rule);
+    if (idx>=0)
+        return idx;
+
+    fData->AddEntry(rule);
+    return fData->GetNumEntries()-1;
+}
+
+// --------------------------------------------------------------------------
+//
+void MHMatrix::AddColumns(MDataArray *matrix)
+{
+    if (fM.IsValid())
+    {
+        *fLog << warn << "Warning - matrix is already in use. Can't add new columns... skipped." << endl;
+        return;
+    }
+
+    if (TestBit(kIsLocked))
+    {
+        *fLog << warn << "Warning - matrix is locked. Can't add new columns... skipped." << endl;
+        return;
+    }
+
+    if (fData)
+        *fLog << warn << "Warning - columns already added... replacing." << endl;
+
+    if (fData && TestBit(kIsOwner))
+    {
+        delete fData;
+        ResetBit(kIsOwner);
+    }
+
+    fData = matrix;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks whether at least one column is available and PreProcesses all
+// data chains.
+//
+Bool_t MHMatrix::SetupFill(const MParList *plist)
+{
+    if (!fData)
+    {
+        *fLog << err << "Error - No Columns initialized... aborting." << endl;
+        return kFALSE;
+    }
+
+    return fData->PreProcess(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// If the matrix has not enough rows double the number of available rows.
+//
+void MHMatrix::AddRow()
+{
+    fNumRows++;
+
+    if (fM.GetNrows() > fNumRows)
+        return;
+
+    if (!fM.IsValid())
+    {
+        fM.ResizeTo(1, fData->GetNumEntries());
+        return;
+    }
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
+    TMatrix m(fM);
+#endif
+    fM.ResizeTo(fM.GetNrows()*2, fData->GetNumEntries());
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
+    TVector vold(fM.GetNcols());
+    for (int x=0; x<m.GetNrows(); x++)
+        TMatrixRow(fM, x) = vold = TMatrixRow(m, x);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the values correspoding to the columns to the new row
+//
+Bool_t MHMatrix::Fill(const MParContainer *par, const Stat_t w)
+{
+    AddRow();
+
+    for (int col=0; col<fData->GetNumEntries(); col++)
+        fM(fNumRows-1, col) = (*fData)(col);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Resize the matrix to a number of rows which corresponds to the number of
+// rows which have really been filled with values.
+//
+Bool_t MHMatrix::Finalize()
+{
+    //
+    // It's not a fatal error so we don't need to stop PostProcessing...
+    //
+    if (fData->GetNumEntries()==0 || fNumRows<1)
+        return kTRUE;
+
+    if (fNumRows != fM.GetNrows())
+    {
+        TMatrix m(fM);
+        CopyCrop(fM, m, fNumRows);
+    }
+
+    return kTRUE;
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Draw clone of histogram. So that the object can be deleted
+// and the histogram is still visible in the canvas.
+// The cloned object are deleted together with the canvas if the canvas is
+// destroyed. If you want to handle destroying the canvas you can get a
+// pointer to it from this function
+//
+TObject *MHMatrix::DrawClone(Option_t *opt) const
+{
+    TCanvas &c = *MH::MakeDefCanvas(fHist);
+
+    //
+    // This is necessary to get the expected bahviour of DrawClone
+    //
+    gROOT->SetSelectedPad(NULL);
+
+    fHist->DrawCopy(opt);
+
+    TString str(opt);
+    if (str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileX();
+        p->Draw("same");
+        p->SetBit(kCanDelete);
+    }
+    if (str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileY();
+        p->Draw("same");
+        p->SetBit(kCanDelete);
+    }
+
+    c.Modified();
+    c.Update();
+
+    return &c;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the histogram into it.
+// Be careful: The histogram belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHMatrix::Draw(Option_t *opt)
+{
+    if (!gPad)
+        MH::MakeDefCanvas(fHist);
+
+    fHist->Draw(opt);
+
+    TString str(opt);
+    if (str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileX();
+        p->Draw("same");
+        p->SetBit(kCanDelete);
+    }
+    if (str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileY();
+        p->Draw("same");
+        p->SetBit(kCanDelete);
+    }
+
+    gPad->Modified();
+    gPad->Update();
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Prints the meaning of the columns and the contents of the matrix.
+// Becareful, this can take a long time for matrices with many rows.
+// Use the option 'size' to print the size of the matrix.
+// Use the option 'cols' to print the culumns
+// Use the option 'data' to print the contents
+//
+void MHMatrix::Print(Option_t *o) const
+{
+    TString str(o);
+
+    *fLog << all << flush;
+
+    if (str.Contains("size", TString::kIgnoreCase))
+    {
+        *fLog << GetDescriptor() << ": NumColumns=" << fM.GetNcols();
+        *fLog << " NumRows=" << fM.GetNrows() << endl;
+    }
+
+    if (!fData && str.Contains("cols", TString::kIgnoreCase))
+        *fLog << "Sorry, no column information available." << endl;
+
+    if (fData && str.Contains("cols", TString::kIgnoreCase))
+    {
+        fData->SetName(fName);
+        fData->Print();
+    }
+
+    if (str.Contains("data", TString::kIgnoreCase))
+        fM.Print();
+}
+
+// --------------------------------------------------------------------------
+//
+const TMatrix *MHMatrix::InvertPosDef()
+{
+    TMatrix m(fM);
+
+    const Int_t rows = m.GetNrows();
+    const Int_t cols = m.GetNcols();
+
+    for (int x=0; x<cols; x++)
+    {
+        Double_t avg = 0;
+        for (int y=0; y<rows; y++)
+            avg += fM(y, x);
+
+        avg /= rows;
+
+        TMatrixColumn(m, x) += -avg;
+    }
+
+    TMatrix *m2 = new TMatrix(m, TMatrix::kTransposeMult, m);
+
+    Double_t det;
+    m2->Invert(&det);
+    if (det==0)
+    {
+        *fLog << err << "ERROR - MHMatrix::InvertPosDef failed (Matrix is singular)." << endl;
+        delete m2;
+        return NULL;
+    }
+
+    // m2->Print();
+
+    return m2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculated the distance of vector evt from the reference sample
+// represented by the covariance metrix m.
+//  - If n<0 the kernel method is applied and
+//    -log(sum(epx(-d/h))/n) is returned.
+//  - For n>0 the n nearest neighbors are summed and
+//    sqrt(sum(d)/n) is returned.
+//  - if n==0 all distances are summed
+//
+Double_t MHMatrix::CalcDist(const TMatrix &m, const TVector &evt, Int_t num) const
+{
+    if (num==0) // may later be used for another method
+    {
+        TVector d = evt;
+        d *= m;
+        return TMath::Sqrt(d*evt);
+    }
+
+    const Int_t rows = fM.GetNrows();
+    const Int_t cols = fM.GetNcols();
+
+    TArrayD dists(rows);
+
+    //
+    // Calculate:  v^T * M * v
+    //
+    for (int i=0; i<rows; i++)
+    {
+        TVector col(cols);
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        col = TMatrixRow(fM, i);
+#else
+        col = TMatrixFRow_const(fM, i);
+#endif
+        TVector d = evt;
+        d -= col;
+
+        TVector d2 = d;
+        d2 *= m;
+
+        dists[i] = d2*d; // square of distance
+
+        //
+        // This corrects for numerical uncertanties in cases of very
+        // small distances...
+        //
+        if (dists[i]<0)
+            dists[i]=0;
+    }
+
+    TArrayI idx(rows);
+    TMath::Sort(dists.GetSize(), dists.GetArray(), idx.GetArray(), kFALSE);
+
+    Int_t from = 0;
+    Int_t to   = TMath::Abs(num)<rows ? TMath::Abs(num) : rows;
+    //
+    // This is a zero-suppression for the case a test- and trainings
+    // sample is identical. This would result in an unwanted leading
+    // zero in the array. To suppress also numerical uncertanties of
+    // zero we cut at 1e-5. Due to Rudy this should be enough. If
+    // you encounter problems we can also use (eg) 1e-25
+    //
+    if (dists[idx[0]]<1e-5)
+    {
+        from++;
+        to ++;
+        if (to>rows)
+            to = rows;
+    }
+
+    if (num<0)
+    {
+        //
+        // Kernel function sum (window size h set according to literature)
+        //
+        const Double_t h    = TMath::Power(rows, -1./(cols+4));
+        const Double_t hwin = h*h*2;
+
+        Double_t res = 0;
+        for (int i=from; i<to; i++)
+            res += TMath::Exp(-dists[idx[i]]/hwin);
+
+        return -TMath::Log(res/(to-from));
+    }
+    else
+    {
+        //
+        // Nearest Neighbor sum
+        //
+        Double_t res = 0;
+        for (int i=from; i<to; i++)
+            res += dists[idx[i]];
+
+        return TMath::Sqrt(res/(to-from));
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls calc dist. In the case of the first call the covariance matrix
+// fM2 is calculated.
+//  - If n<0 it is divided by (nrows-1)/h while h is the kernel factor.
+//
+Double_t MHMatrix::CalcDist(const TVector &evt, Int_t num)
+{
+    if (!fM2.IsValid())
+    {
+        if (!fM.IsValid())
+        {
+            *fLog << err << "MHMatrix::CalcDist - ERROR: fM not valid." << endl;
+            return -1;
+        }
+
+        const TMatrix *m = InvertPosDef();
+        if (!m)
+            return -1;
+
+        fM2.ResizeTo(*m);
+        fM2 = *m;
+        fM2 *= fM.GetNrows()-1;
+        delete m;
+    }
+
+    return CalcDist(fM2, evt, num);
+}
+
+// --------------------------------------------------------------------------
+//
+void MHMatrix::Reassign()
+{
+    TMatrix m = fM;
+    fM.ResizeTo(1,1);
+    fM.ResizeTo(m);
+    fM = m;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MHMatrix::StreamPrimitive(ofstream &out) const
+{
+    Bool_t data = fData && !TestBit(kIsOwner);
+
+    if (data)
+    {
+        fData->SavePrimitive(out);
+        out << endl;
+    }
+
+    out << "   MHMatrix " << GetUniqueName();
+
+    if (data || fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(";
+        if (data)
+            out << "&" << fData->GetUniqueName();
+        if (fName!=gsDefName || fTitle!=gsDefTitle)
+        {
+            if (data)
+                out << ", ";
+            out << "\"" << fName << "\"";
+            if (fTitle!=gsDefTitle)
+                out << ", \"" << fTitle << "\"";
+        }
+    }
+    out << ");" << endl;
+
+    if (fData && TestBit(kIsOwner))
+        for (int i=0; i<fData->GetNumEntries(); i++)
+            out << "   " << GetUniqueName() << ".AddColumn(\"" << (*fData)[i].GetRule() << "\");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+const TArrayI MHMatrix::GetIndexOfSortedColumn(Int_t ncol, Bool_t desc) const
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TMatrixColumn col(fM, ncol);
+#else
+    TMatrixFColumn_const col(fM, ncol);
+#endif
+
+    const Int_t n = fM.GetNrows();
+
+    TArrayF array(n);
+
+    for (int i=0; i<n; i++)
+        array[i] = col(i);
+
+    TArrayI idx(n);
+    TMath::Sort(n, array.GetArray(), idx.GetArray(), desc);
+
+    return idx;
+}
+
+// --------------------------------------------------------------------------
+//
+void MHMatrix::SortMatrixByColumn(Int_t ncol, Bool_t desc)
+{
+    TArrayI idx = GetIndexOfSortedColumn(ncol, desc);
+
+    const Int_t n = fM.GetNrows();
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(fM.GetNcols());
+#endif
+
+    TMatrix m(n, fM.GetNcols());
+    for (int i=0; i<n; i++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(m, i) = vold = TMatrixRow(fM, idx[i]);
+#else
+        TMatrixFRow(m, i) = TMatrixFRow_const(fM, idx[i]);
+#endif
+    fM = m;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MHMatrix::Fill(MParList *plist, MTask *read, MFilter *filter)
+{
+    //
+    // Read data into Matrix
+    //
+    const Bool_t is = plist->IsOwner();
+    plist->SetOwner(kFALSE);
+
+    MTaskList tlist;
+    plist->Replace(&tlist);
+
+    MFillH fillh(this);
+
+    tlist.AddToList(read);
+
+    if (filter)
+    {
+        tlist.AddToList(filter);
+        fillh.SetFilter(filter);
+    }
+
+    tlist.AddToList(&fillh);
+
+    //MProgressBar bar;
+    MEvtLoop evtloop("MHMatrix::Fill-EvtLoop");
+    evtloop.SetParList(plist);
+    //evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+        return kFALSE;
+
+    tlist.PrintStatistics();
+
+    plist->Remove(&tlist);
+    plist->SetOwner(is);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a comma seperated list of all data members used in the matrix.
+// This is mainly used in MTask::AddToBranchList
+//
+TString MHMatrix::GetDataMember() const
+{
+    return fData ? fData->GetDataMember() : TString("");
+}
+
+// --------------------------------------------------------------------------
+//
+//
+void MHMatrix::ReduceNumberOfRows(UInt_t numrows, const TString opt)
+{
+    UInt_t rows = fM.GetNrows();
+
+    if (rows==numrows)
+    {
+        *fLog << warn << "Matrix has already the correct number of rows..." << endl;
+        return;
+    }
+
+    Float_t ratio = (Float_t)numrows/fM.GetNrows();
+
+    if (ratio>=1)
+    {
+        *fLog << warn << "Matrix cannot be enlarged..." << endl;
+        return;
+    }
+
+    Double_t sum = 0;
+
+    UInt_t oldrow = 0;
+    UInt_t newrow = 0;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(fM.GetNcols());
+#endif
+    while (oldrow<rows)
+    {
+        sum += ratio;
+
+        if (newrow<=(unsigned int)sum)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+            TMatrixRow(fM, newrow++) = vold = TMatrixRow(fM, oldrow);
+#else
+            TMatrixFRow(fM, newrow++) = TMatrixFRow_const(fM, oldrow);
+#endif
+
+        oldrow++;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+//  Used in DefRefMatrix to display the result graphically
+//
+void MHMatrix::DrawDefRefInfo(const TH1 &hth, const TH1 &hthd, const TH1 &thsh, Int_t refcolumn)
+{
+    //
+    // Fill a histogram with the distribution after raduction
+    //
+    TH1F hta;
+    hta.SetDirectory(NULL);
+    hta.SetName("hta");
+    hta.SetTitle("Distribution after reduction");
+    SetBinning(&hta, &hth);
+
+    for (Int_t i=0; i<fM.GetNrows(); i++)
+        hta.Fill(fM(i, refcolumn));
+
+    TCanvas *th1 = MakeDefCanvas(this);
+    th1->Divide(2,2);
+
+    th1->cd(1);
+    ((TH1&)hth).DrawCopy();   // real histogram before
+
+    th1->cd(2);
+    ((TH1&)hta).DrawCopy();   // histogram after
+
+    th1->cd(3);
+    ((TH1&)hthd).DrawCopy();  // correction factors
+
+    th1->cd(4);
+    ((TH1&)thsh).DrawCopy();  // target
+}
+
+// ------------------------------------------------------------------------
+//
+//  Resizes th etarget matrix to rows*source.GetNcol() and copies
+//  the data from the first (n)rows or the source into the target matrix.
+//
+void MHMatrix::CopyCrop(TMatrix &target, const TMatrix &source, Int_t rows)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector v(source.GetNcols());
+#endif
+    target.ResizeTo(rows, source.GetNcols());
+    for (Int_t ir=0; ir<rows; ir++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(target, ir) = v = TMatrixRow(source, ir);
+#else
+        TMatrixFRow(target, ir) = TMatrixFRow_const(source, ir);
+#endif
+}
+
+// ------------------------------------------------------------------------
+//
+// Define the reference matrix
+//   refcolumn  number of the column (starting at 0) containing the variable,
+//              for which a target distribution may be given;
+//   thsh       histogram containing the target distribution of the variable
+//   nmaxevts   the number of events the reference matrix should have after 
+//              the renormalization
+//   rest       a TMatrix conatining the resulting (not choosen)
+//              columns of the primary matrix. Maybe NULL if you
+//              are not interested in this
+//
+Bool_t MHMatrix::DefRefMatrix(const UInt_t refcolumn, const TH1F &thsh,
+                              Int_t nmaxevts, TMatrix *rest)
+{
+    if (!fM.IsValid())
+    {
+        *fLog << err << dbginf << "Matrix not initialized" << endl;
+        return kFALSE;
+    }
+
+    if (thsh.GetMinimum()<0)
+    {
+        *fLog << err << dbginf << "Renormalization not possible: ";
+        *fLog << "Target Distribution has values < 0" << endl;
+        return kFALSE;
+    }
+
+
+    if (nmaxevts>fM.GetNrows())
+    {
+        *fLog << warn << dbginf << "No.requested (" << nmaxevts;
+        *fLog << ") > available events (" << fM.GetNrows() << ")... ";
+        *fLog << "setting equal." << endl;
+        nmaxevts = fM.GetNrows();
+    }
+
+
+    if (nmaxevts<0)
+    {
+        *fLog << err << dbginf << "Number of requested events < 0" << endl;
+        return kFALSE;
+    }
+
+    if (nmaxevts==0)
+        nmaxevts = fM.GetNrows();
+
+    //
+    // refcol is the column number starting at 0; it is >= 0
+    //
+    // number of the column (count from 0) containing
+    // the variable for which the target distribution is given
+    //
+
+    //
+    // Calculate normalization factors
+    //
+    //const int    nbins   = thsh.GetNbinsX();
+    //const double frombin = thsh.GetBinLowEdge(1);
+    //const double tobin   = thsh.GetBinLowEdge(nbins+1);
+    //const double dbin    = thsh.GetBinWidth(1);
+
+    const Int_t  nrows   = fM.GetNrows();
+    const Int_t  ncols   = fM.GetNcols();
+
+    //
+    // set up the real histogram (distribution before)
+    //
+    //TH1F hth("th", "Distribution before reduction", nbins, frombin, tobin);
+    TH1F hth;
+    hth.SetNameTitle("th", "Distribution before reduction");
+    SetBinning(&hth, &thsh);
+    hth.SetDirectory(NULL);
+    for (Int_t j=0; j<nrows; j++)
+        hth.Fill(fM(j, refcolumn));
+
+    //TH1F hthd("thd", "Correction factors", nbins, frombin, tobin);
+    TH1F hthd;
+    hthd.SetNameTitle("thd", "Correction factors");
+    SetBinning(&hthd, &thsh);
+    hthd.SetDirectory(NULL);
+    hthd.Divide((TH1F*)&thsh, &hth, 1, 1);
+
+    if (hthd.GetMaximum() <= 0)
+    {
+        *fLog << err << dbginf << "Maximum correction factor <= 0... abort." << endl;
+        return kFALSE;
+    }
+
+    //
+    // ===== obtain correction factors (normalization factors)
+    //
+    hthd.Scale(1/hthd.GetMaximum());
+
+    //
+    // get random access
+    //
+    TArrayI ind(nrows);
+    GetRandomArrayI(ind);
+
+    //
+    // define  new matrix
+    //
+    Int_t evtcount1 = -1;
+    Int_t evtcount2 =  0;
+
+    TMatrix mnewtmp(nrows, ncols);
+    TMatrix mrest(nrows, ncols);
+
+    TArrayF cumulweight(nrows); // keep track for each bin how many events
+
+    //
+    // Project values in reference column into [0,1]
+    //
+    TVector v(fM.GetNrows());
+    v = TMatrixColumn(fM, refcolumn);
+    //v += -frombin;
+    //v *= 1/dbin;
+
+    //
+    // select events (distribution after renormalization)
+    //
+    Int_t ir;
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(fM.GetNcols());
+#endif
+    for (ir=0; ir<nrows; ir++)
+    {
+        // const Int_t indref = (Int_t)v(ind[ir]);
+        const Int_t indref = hthd.FindBin(v(ind[ir])) - 1;
+        cumulweight[indref] += hthd.GetBinContent(indref+1);
+        if (cumulweight[indref]<=0.5)
+        {
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+            TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+#else
+            TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+            continue;
+        }
+
+        cumulweight[indref] -= 1.;
+        if (++evtcount1 >=  nmaxevts)
+            break;
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(mnewtmp, evtcount1) = vold = TMatrixRow(fM, ind[ir]);
+#else
+        TMatrixFRow(mnewtmp, evtcount1) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+    }
+
+    for (/*empty*/; ir<nrows; ir++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+#else
+        TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+
+    //
+    // reduce size
+    //
+    // matrix fM having the requested distribution
+    // and the requested number of rows;
+    // this is the matrix to be used in the g/h separation
+    //
+    CopyCrop(fM, mnewtmp, evtcount1);
+    fNumRows = evtcount1;
+
+    if (evtcount1 < nmaxevts)
+        *fLog << warn << "Reference sample contains less events (" << evtcount1 << ") than requested (" << nmaxevts << ")" << endl;
+
+    if (TestBit(kEnableGraphicalOutput))
+        DrawDefRefInfo(hth, hthd, thsh, refcolumn);
+
+    if (rest)
+        CopyCrop(*rest, mrest, evtcount2);
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns a array containing randomly sorted indices
+//
+void MHMatrix::GetRandomArrayI(TArrayI &ind) const
+{
+    const Int_t rows = ind.GetSize();
+
+    TArrayF ranx(rows);
+
+    TRandom3 rnd(0);
+    for (Int_t i=0; i<rows; i++)
+        ranx[i] = rnd.Rndm(i);
+
+    TMath::Sort(rows, ranx.GetArray(), ind.GetArray(), kTRUE);
+}
+
+// ------------------------------------------------------------------------
+//
+// Define the reference matrix
+//   nmaxevts   maximum number of events in the reference matrix
+//   rest       a TMatrix conatining the resulting (not choosen)
+//              columns of the primary matrix. Maybe NULL if you
+//              are not interested in this
+//
+//              the target distribution will be set
+//              equal to the real distribution; the events in the reference
+//              matrix will then be simply a random selection of the events 
+//              in the original matrix.
+//
+Bool_t MHMatrix::DefRefMatrix(Int_t nmaxevts, TMatrix *rest)
+{
+    if (!fM.IsValid())
+    {
+        *fLog << err << dbginf << "Matrix not initialized" << endl;
+        return kFALSE;
+    }
+
+    if (nmaxevts>fM.GetNrows())
+    {
+      *fLog << dbginf << "No.of requested events (" << nmaxevts 
+            << ") exceeds no.of available events (" << fM.GetNrows() 
+            << ")" << endl;
+        *fLog << dbginf 
+              << "        set no.of requested events = no.of available events" 
+              << endl;
+        nmaxevts = fM.GetNrows();
+    }
+
+    if (nmaxevts<0)
+    {
+        *fLog << err << dbginf << "Number of requested events < 0" << endl;
+        return kFALSE;
+    }
+
+    if (nmaxevts==0)
+        nmaxevts = fM.GetNrows();
+
+    const Int_t nrows = fM.GetNrows();
+    const Int_t ncols = fM.GetNcols();
+
+    //
+    // get random access
+    //
+    TArrayI ind(nrows);
+    GetRandomArrayI(ind);
+
+    //
+    // define  new matrix
+    //
+    Int_t evtcount1 = 0;
+    Int_t evtcount2 = 0;
+
+    TMatrix mnewtmp(nrows, ncols);
+    TMatrix mrest(nrows, ncols);
+
+    //
+    // select events (distribution after renormalization)
+    //
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(fM.GetNcols());
+#endif
+    for (Int_t ir=0; ir<nmaxevts; ir++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(mnewtmp, evtcount1++) = vold = TMatrixRow(fM, ind[ir]);
+#else
+        TMatrixFRow(mnewtmp, evtcount1++) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+
+    for (Int_t ir=nmaxevts; ir<nrows; ir++)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+#else
+        TMatrixFRow(mrest, evtcount2++) = TMatrixFRow_const(fM, ind[ir]);
+#endif
+
+    //
+    // reduce size
+    //
+    // matrix fM having the requested distribution
+    // and the requested number of rows;
+    // this is the matrix to be used in the g/h separation
+    //
+    CopyCrop(fM, mnewtmp, evtcount1);
+    fNumRows = evtcount1;
+
+    if (evtcount1 < nmaxevts)
+        *fLog << warn << "The reference sample contains less events (" << evtcount1 << ") than requested (" << nmaxevts << ")" << endl;
+
+    if (!rest)
+        return kTRUE;
+
+    CopyCrop(*rest, mrest, evtcount2);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// overload TOject member function read 
+// in order to reset the name of the object read
+//
+Int_t MHMatrix::Read(const char *name)
+{
+    Int_t ret = TObject::Read(name);
+    SetName(name);
+
+    return ret;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv:
+//   Column0, Column1, Column2, ..., Column10, ..., Column100, ...
+//
+// Searching stops if the first key isn't found in the TEnv. Empty
+// columns are not allowed
+//
+// eg.
+//     MHMatrix.Column0: cos(MMcEvt.fTelescopeTheta)
+//     MHMatrix.Column1: MHillasSrc.fAlpha
+//
+Int_t MHMatrix::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (fM.IsValid())
+    {
+        *fLog << err << "ERROR - matrix is already in use. Can't add a new column from TEnv... skipped." << endl;
+        return kERROR;
+    }
+
+    if (TestBit(kIsLocked))
+    {
+        *fLog << err << "ERROR - matrix is locked. Can't add new column from TEnv... skipped." << endl;
+        return kERROR;
+    }
+
+    //
+    // Search (beginning with 0) all keys
+    //
+    int i=0;
+    while (1)
+    {
+        TString idx = "Column";
+        idx += i;
+
+        // Output if print set to kTRUE
+        if (!IsEnvDefined(env, prefix, idx, print))
+            break;
+
+        // Try to get the file name
+        TString name = GetEnvValue(env, prefix, idx, "");
+        if (name.IsNull())
+        {
+            *fLog << warn << prefix+"."+idx << " empty." << endl;
+            continue;
+        }
+
+        if (i==0)
+            if (fData)
+            {
+                *fLog << inf << "Removing all existing columns in " << GetDescriptor() << endl;
+                fData->Delete();
+            }
+            else
+            {
+                fData = new MDataArray;
+                SetBit(kIsOwner);
+            }
+
+        fData->AddEntry(name);
+        i++;
+    }
+
+    return i!=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// ShuffleEvents. Shuffles the order of the matrix rows.
+// 
+//
+void MHMatrix::ShuffleRows(UInt_t seed)
+{
+    TRandom rnd(seed);
+
+    TVector v(fM.GetNcols());
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector tmp(fM.GetNcols());
+#endif
+    for (Int_t irow = 0; irow<fNumRows; irow++)
+    {
+        const Int_t jrow = rnd.Integer(fNumRows);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+        v = TMatrixRow(fM, irow);
+        TMatrixRow(fM, irow) = tmp = TMatrixRow(fM, jrow);
+        TMatrixRow(fM, jrow) = v;
+#else
+        v = TMatrixFRow_const(fM, irow);
+        TMatrixFRow(fM, irow) = TMatrixFRow_const(fM, jrow);
+        TMatrixFRow(fM, jrow) = v;
+#endif
+    }
+
+    *fLog << warn << GetDescriptor() << ": Attention! Matrix rows have been shuffled." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reduces the number of rows to the given number num by cutting out the
+// last rows.
+//
+void MHMatrix::ReduceRows(UInt_t num)
+{
+    if ((Int_t)num>=fM.GetNrows())
+    {
+        *fLog << warn << GetDescriptor() << ": Warning - " << num << " >= rows=" << fM.GetNrows() << endl;
+        return;
+    }
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
+    const TMatrix m(fM);
+#endif
+    fM.ResizeTo(num, fM.GetNcols());
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,07)
+    TVector tmp(fM.GetNcols());
+    for (UInt_t irow=0; irow<num; irow++)
+        TMatrixRow(fM, irow) = tmp = TMatrixRow(m, irow);
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// Remove rows which contains numbers not fullfilling TMath::Finite
+//
+Bool_t MHMatrix::RemoveInvalidRows()
+{
+    TMatrix m(fM);
+
+    const Int_t ncol=fM.GetNcols();
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    TVector vold(ncol);
+#endif
+
+    int irow=0;
+
+    for (int i=0; i<m.GetNrows(); i++)
+    {
+        const TMatrixRow &row = TMatrixRow(m, i);
+
+        // finite (-> math.h) checks for NaN as well as inf
+        int jcol;
+        for (jcol=0; jcol<ncol; jcol++)
+            if (!TMath::Finite(row(jcol)))
+                break;
+
+        if (jcol==ncol)
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+            TMatrixRow(fM, irow++) = vold = row;
+#else
+            TMatrixFRow(fM, irow++) = row;
+#endif
+        else
+            *fLog << warn << "Warning - MHMatrix::RemoveInvalidRows: row #" << i<< " removed." << endl;
+    }
+
+    // Do not use ResizeTo (in older root versions this doesn't save the contents
+    ReduceRows(irow);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mhbase/MHMatrix.h
===================================================================
--- /tags/Mars-V0.9/mhbase/MHMatrix.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MHMatrix.h	(revision 9772)
@@ -0,0 +1,123 @@
+#ifndef MARS_MHMatrix
+#define MARS_MHMatrix
+
+#ifdef MARS_MLogManip
+#error Please make ensure that MLogManip.h are included _after_ MHMatrix.h
+#endif
+
+#ifndef ROOT_TMatrix
+#include <TMatrix.h>
+#endif
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TArrayI;
+class TArrayF;
+class TVector;
+class TH1F;
+
+class MTask;
+class MParList;
+class MDataArray;
+class MFilter;
+
+class MHMatrix : public MH
+{
+private:
+    static const TString gsDefName;  //! Default Name
+    static const TString gsDefTitle; //! Default Title
+
+    Int_t   fNumRows;   //! Number of rows filled into the matrix (this is NOT the number of rows of the matrix!)
+    Int_t   fRow;       //! Present row
+    TMatrix fM;         // Matrix to be filled
+
+    TMatrix fM2;        //! Covariance Matrix
+
+    MDataArray *fData;  // List of data members (columns)
+
+
+    enum {
+        kIsOwner  = BIT(14),
+        kIsLocked = BIT(17)
+    };
+
+    void AddRow();
+
+    Bool_t SetupFill(const MParList *pList);
+
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    void DrawDefRefInfo(const TH1 &hth, const TH1 &hthd, const TH1 &thsh, Int_t refcolumn);
+    void GetRandomArrayI(TArrayI &ind) const;
+
+    void StreamPrimitive(ofstream &out) const;
+
+public:
+    MHMatrix(const char *name=NULL, const char *title=NULL);
+    MHMatrix(MDataArray *mat, const char *name=NULL, const char *title=NULL);
+    MHMatrix(const TMatrix &m, const char *name=NULL, const char *title=NULL);
+    ~MHMatrix();
+
+    static void CopyCrop(TMatrix &target, const TMatrix &source, Int_t rows);
+
+    void Lock()   { SetBit(kIsLocked); }
+    void Unlock() { ResetBit(kIsLocked); }
+
+    Int_t AddColumn(const char *name);
+    void AddColumns(MDataArray *mat);
+
+    MDataArray *GetColumns() { return fData; }
+
+    const TMatrix &GetM() const { return fM; }
+
+    Bool_t IsValid() const { return fM.IsValid(); }
+    Int_t  GetNumRows() const { return fM.GetNrows(); }
+
+    //void Draw(Option_t *opt=NULL);
+    //TObject *DrawClone(Option_t *opt=NULL) const;
+
+    void Print(Option_t *) const;
+
+    const TMatrix *InvertPosDef();
+
+    Double_t CalcDist(const TMatrix &m, const TVector &v, Int_t num = 25) const;
+    Double_t CalcDist(const TVector &v, Int_t num = 25);
+
+    void SetOwner(Bool_t b=kTRUE) { b ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+
+    void Reassign();
+
+    const TArrayI GetIndexOfSortedColumn(Int_t ncol=0, Bool_t desc=kTRUE) const;
+    void SortMatrixByColumn(Int_t ncol=0, Bool_t desc=kTRUE);
+
+    Bool_t SetNumRow(Int_t row); 
+ 
+    Int_t GetNumRow() const { return fRow; };
+    Double_t operator[](Int_t col) { return fM(fRow, col); }
+
+    Bool_t Fill(MParList *plist, MTask *read, MFilter *filter=NULL);
+
+    TString GetDataMember() const;
+
+    void ReduceNumberOfRows(UInt_t numrows, const TString opt);
+    Bool_t RemoveInvalidRows();
+
+    Int_t Read(const char *name);
+
+    Bool_t DefRefMatrix(const UInt_t refcolumn, const TH1F &thsh,
+                        Int_t nmaxevts=0, TMatrix *mrest=NULL);
+    Bool_t DefRefMatrix(Int_t nmaxevts=0, TMatrix *mrest=NULL);
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    void ShuffleRows(UInt_t seed);
+    void ReduceRows(UInt_t num);
+
+    ClassDef(MHMatrix, 1) // Multidimensional Matrix (TMatrix) to store events
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mhbase/MWeight.cc
===================================================================
--- /tags/Mars-V0.9/mhbase/MWeight.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MWeight.cc	(revision 9772)
@@ -0,0 +1,35 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MWeight
+//
+//   Storage container for a weight to fill histograms
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MWeight.h"
+
+ClassImp(MWeight);
+
Index: /tags/Mars-V0.9/mhbase/MWeight.h
===================================================================
--- /tags/Mars-V0.9/mhbase/MWeight.h	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/MWeight.h	(revision 9772)
@@ -0,0 +1,32 @@
+#ifndef MARS_MWeight
+#define MARS_MWeight
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MWeight                                                                //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MWeight : public MParContainer
+{
+private:
+    Double_t fWeight;
+
+public:
+    MWeight(const char *name=NULL, const char *title=NULL) : fWeight(1)
+    {
+        fName  = name  ? name  : "MWeight";
+        fTitle = title ? title : "A weight for filling histograms";
+    }
+
+    void SetWeight(Double_t weight) { fWeight = weight; }
+    Double_t GetWeight() const { return fWeight; }
+
+    ClassDef(MWeight, 1) // A weight for filling histograms
+};
+
+#endif
Index: /tags/Mars-V0.9/mhbase/Makefile
===================================================================
--- /tags/Mars-V0.9/mhbase/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mhbase/Makefile	(revision 9772)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HBase
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mdata
+
+SRCFILES = MFillH.cc \
+           MBinning.cc \
+           MWeight.cc \
+           MH.cc \
+           MH3.cc \
+           MHArray.cc \
+           MHMatrix.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mhcalib/HCalibIncl.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/HCalibIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/HCalibIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mhcalib/HCalibLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/HCalibLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/HCalibLinkDef.h	(revision 9772)
@@ -0,0 +1,24 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHCalibrationCam+;
+#pragma link C++ class MHCalibrationPix+;
+#pragma link C++ class MHCalibrationChargeCam+;
+#pragma link C++ class MHCalibrationChargePix+;
+#pragma link C++ class MHCalibrationChargeBlindCam+;
+#pragma link C++ class MHCalibrationChargeBlindPix+;
+#pragma link C++ class MHCalibrationChargePINDiode+;
+#pragma link C++ class MHCalibrationRelTimeCam+;
+#pragma link C++ class MHCalibrationTestCam+;
+#pragma link C++ class MHCalibrationHiLoCam+;
+#pragma link C++ class MHCalibrationPulseTimeCam+;
+#pragma link C++ class MHPedestalCam+;
+#pragma link C++ class MHPedestalPix+;
+#pragma link C++ class MHCalibrationTestTimeCam+;
+
+#pragma link C++ class MHGausEvents+;
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationCam.cc	(revision 9772)
@@ -0,0 +1,1498 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHCalibrationCam                                               
+//
+// Base class for camera calibration classes. Incorporates the TOrdCollection's:
+// - fHiGainArray (for calibrated High Gains per pixel)
+// - fLoGainArray (for calibrated Low Gains per pixel) 
+// - fAverageHiGainAreas (for averaged High Gains events per camera area index)
+// - fAverageLoGainAreas (for averaged High Gains events per camera area index)
+// - fAverageHiGainSectors (for averaged High Gains events per camera sector )
+// - fAverageLoGainSectors (for averaged High Gains events per camera sector )
+// These TOrdCollection's are called by their default constructors, thus no objects 
+// are created, until the derived class does so. 
+//
+// The corresponding operators: [],() and the operators GetAverageHiGainArea(), 
+// GetAverageLoGainArea(), GetAverageHiGainSector() and GetAverageLoGainSector() 
+// have to be cast to the corresponding class. It is assumed that all classes 
+// dealing with calibration pixels derive from MHCalibrationPix.
+//
+// The following flag can be set:
+// - SetAverageing() for calculating the event-by-event averages.
+// - SetDebug()      for debug output.
+// - SetLoGain()     for the case that low-gain slices are available, but 
+//                       MRawRunHeader::GetNumLoGainSlices() gives still 0.
+// - SetCheckSize()  for testing the sizes of the f*Arrays in ReInit() if they 
+//                       are coinciding with the equiv. sizes in MGeomCam
+//
+// The flag kLoGain steers if the low-gain signal is treated at all or not.
+// The flag kAverageing steers if the event-by-event averages are treated at all.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationCam.h"
+#include "MHCalibrationPix.h"
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TText.h>
+#include <TPaveText.h>
+#include <TOrdCollection.h>
+#include <TROOT.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCalibrationIntensityCam.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationPix.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+
+ClassImp(MHCalibrationCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationCam::fgPulserFrequency  = 500;
+const Float_t MHCalibrationCam::fgProbLimit        = 0.0001;
+const Float_t MHCalibrationCam::fgOverflowLimit    = 0.005;
+const TString MHCalibrationCam::gsHistName   = "Hist";
+const TString MHCalibrationCam::gsHistTitle  = "";
+const TString MHCalibrationCam::gsHistXTitle = "";
+const TString MHCalibrationCam::gsHistYTitle = "Nr. events";
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// Initializes and sets owner of:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+// Initializes:
+// - fPulserFrequency to fgPulserFrequency
+// - fProbLimit       to fgProbLimit
+// - fOverflowLimit   to fgOverflowLimit
+//
+// - SetAveregeing  (kTRUE);
+// - SetDebug       (kFALSE);
+// - SetLoGain      (kTRUE);
+//-  SetOscillations(kTRUE);
+//-  SetSizeCheck   (kTRUE);
+//-  SetInterlaced  (kFALSE);
+//
+MHCalibrationCam::MHCalibrationCam(const char *name, const char *title)
+    :  fHistName(gsHistName),fHistTitle(gsHistTitle),
+       fHistXTitle(gsHistXTitle),fHistYTitle(gsHistYTitle), 
+       fColor(MCalibrationCam::kNONE), fIntensBad(NULL),
+       fBadPixels(NULL), fIntensCam(NULL), fCam(NULL), fGeom(NULL), 
+       fRunHeader(NULL)
+{
+
+    fHiGainArray = new TOrdCollection;
+    fHiGainArray->SetOwner();
+
+    fLoGainArray = new TOrdCollection;
+    fLoGainArray->SetOwner();
+
+    fAverageHiGainAreas = new TOrdCollection;
+    fAverageHiGainAreas->SetOwner();
+
+    fAverageLoGainAreas = new TOrdCollection;
+    fAverageLoGainAreas->SetOwner();
+
+    fAverageHiGainSectors = new TOrdCollection;
+    fAverageHiGainSectors->SetOwner();
+
+    fAverageLoGainSectors = new TOrdCollection;
+    fAverageLoGainSectors->SetOwner();
+
+    SetPulserFrequency();
+    SetProbLimit();
+    SetOverflowLimit();
+
+    SetAverageing  (kTRUE);
+    SetDebug       (kFALSE);
+    SetLoGain      (kTRUE);
+    SetOscillations(kTRUE);
+    SetSizeCheck   (kTRUE);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the TOrdCollection of:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+MHCalibrationCam::~MHCalibrationCam()
+{
+
+  delete fHiGainArray;
+  delete fLoGainArray;
+
+  delete fAverageHiGainAreas;
+  delete fAverageLoGainAreas;
+
+  delete fAverageHiGainSectors;
+  delete fAverageLoGainSectors;
+  /*
+
+  Remove ( fHiGainArray );
+  Remove ( fLoGainArray );
+
+  Remove ( fAverageHiGainAreas );
+  Remove ( fAverageLoGainAreas );
+
+  Remove ( fAverageHiGainSectors );
+  Remove ( fAverageLoGainSectors );
+  */
+
+}
+
+void MHCalibrationCam::Remove(TOrdCollection *col)
+{
+
+  if (!col)
+    return;
+
+  TOrdCollectionIter Next(col);
+  
+  Int_t count = 0;
+
+  while (MHCalibrationPix *obj = (MHCalibrationPix*)Next())
+    {
+      *fLog << ++count << " " << obj << flush;
+      if (obj && obj->IsOnHeap())
+        {
+          obj->Draw();
+          delete obj;
+        }
+    }
+  
+  delete col;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns size of fHiGainArray
+//
+const Int_t MHCalibrationCam::GetSize() const
+{
+  return fHiGainArray->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel (pixel number)
+//
+MHCalibrationPix &MHCalibrationCam::operator[](UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fHiGainArray->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel (pixel number)
+//
+const MHCalibrationPix &MHCalibrationCam::operator[](UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fHiGainArray->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel (pixel number)
+//
+MHCalibrationPix  &MHCalibrationCam::operator()(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fLoGainArray->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel (pixel number)
+//
+const MHCalibrationPix  &MHCalibrationCam::operator()(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fLoGainArray->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageHiGainAreas
+// independently if the MHCalibrationPix is filled with values or not.
+//
+const Int_t MHCalibrationCam::GetAverageAreas() const
+{
+  return fAverageHiGainAreas->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area (area number)
+//
+MHCalibrationPix  &MHCalibrationCam::GetAverageHiGainArea(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fAverageHiGainAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area (area number)
+//
+const MHCalibrationPix  &MHCalibrationCam::GetAverageHiGainArea(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix *>(fAverageHiGainAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel Area (area number)
+//
+MHCalibrationPix  &MHCalibrationCam::GetAverageLoGainArea(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fAverageLoGainAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel Area (area number)
+//
+const MHCalibrationPix  &MHCalibrationCam::GetAverageLoGainArea(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fAverageLoGainAreas->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TOrdCollection fAverageHiGainSectors
+// independently if the MHCalibrationPix is filled with values or not.
+//
+const Int_t MHCalibrationCam::GetAverageSectors() const
+{
+  return fAverageHiGainSectors->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector (sector number)
+//
+MHCalibrationPix  &MHCalibrationCam::GetAverageHiGainSector(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fAverageHiGainSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector (sector number)
+//
+const MHCalibrationPix  &MHCalibrationCam::GetAverageHiGainSector(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fAverageHiGainSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain Sector (sector number)
+//
+MHCalibrationPix  &MHCalibrationCam::GetAverageLoGainSector(UInt_t i)
+{
+  return *static_cast<MHCalibrationPix*>(fAverageLoGainSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain Sector (sector number)
+//
+const MHCalibrationPix  &MHCalibrationCam::GetAverageLoGainSector(UInt_t i) const
+{
+  return *static_cast<MHCalibrationPix*>(fAverageLoGainSectors->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls ResetHistTitles()
+//
+// Calls Reset() for each entry in:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+void MHCalibrationCam::ResetHists()
+{
+  
+  ResetHistTitles();
+
+  if (fHiGainArray)
+    { fHiGainArray->ForEach(MHCalibrationPix,Reset)();  }
+
+  if (IsAverageing())
+    {
+      if (fAverageHiGainAreas)
+        { fAverageHiGainAreas->ForEach(MHCalibrationPix,Reset)();  }
+      if (fAverageHiGainSectors)
+        { fAverageHiGainSectors->ForEach(MHCalibrationPix,Reset)();  }
+    }
+  
+  if (!IsLoGain())
+    return;
+
+  if (fLoGainArray)
+    { fLoGainArray->ForEach(MHCalibrationPix,Reset)();  }
+  if (IsAverageing())
+    {
+      if (fAverageLoGainAreas)
+        { fAverageLoGainAreas->ForEach(MHCalibrationPix,Reset)();  }
+      if (fAverageLoGainSectors)
+        { fAverageLoGainSectors->ForEach(MHCalibrationPix,Reset)();  }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Resets the histogram titles for each entry in:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+void MHCalibrationCam::ResetHistTitles()
+{
+  
+  TH1F *h;
+
+  if (fHiGainArray)
+    for (Int_t i=0;i<fHiGainArray->GetSize(); i++)
+      {
+        MHCalibrationPix &pix = (*this)[i];        
+        h = pix.GetHGausHist();
+        h->SetName (Form("%s%s%s%04d","H",fHistName.Data(),"HiGainPix",i));
+        h->SetTitle(Form("%s%s%04d%s",fHistTitle.Data()," High Gain Pixel ",i," Runs: "));  
+        h->SetXTitle(fHistXTitle.Data());
+        h->SetYTitle(fHistYTitle.Data());
+      }
+  
+  if (IsAverageing())
+    {
+      if (fAverageHiGainAreas)
+        for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+          {
+            MHCalibrationPix &pix = GetAverageHiGainArea(j);        
+            h = pix.GetHGausHist();
+            h->SetName (Form("%s%s%s%d","H",fHistName.Data(),"HiGainArea",j));
+            h->SetXTitle(fHistXTitle.Data());
+            h->SetYTitle(fHistYTitle.Data());
+            if (fGeom->InheritsFrom("MGeomCamMagic"))
+              h->SetTitle(Form("%s%s%s%s",fHistTitle.Data()," averaged on event-by-event basis ",
+                               j==0 ? "Inner Pixels " : "Outer Pixels ","High Gain Runs: "));
+            else
+              h->SetTitle(Form("%s%s%d%s",fHistTitle.Data(),
+                               " averaged on event-by-event basis High Gain Area Idx ",j," Runs: "));
+          }
+      
+      if (fAverageHiGainSectors)
+        for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+          {
+            MHCalibrationPix &pix = GetAverageHiGainSector(j);        
+            h = pix.GetHGausHist();
+            h->SetName (Form("%s%s%s%02d","H",fHistName.Data(),"HiGainSector",j));
+            h->SetTitle(Form("%s%s%02d%s",fHistTitle.Data(),
+                             " averaged on event-by-event basis High Gain Sector ",j," Runs: "));
+            h->SetXTitle(fHistXTitle.Data());
+            h->SetYTitle(fHistYTitle.Data());
+          }
+    }
+  
+  if (!IsLoGain())
+    return;
+  
+  if (fLoGainArray)
+    for (Int_t i=0;i<fLoGainArray->GetSize(); i++)
+      {
+        MHCalibrationPix &pix = (*this)(i);        
+        h = pix.GetHGausHist();
+        h->SetName (Form("%s%s%s%04d","H",fHistName.Data(),"LoGainPix",i));
+        h->SetTitle(Form("%s%s%04d%s",fHistTitle.Data()," Low Gain Pixel ",i," Runs: "));  
+        h->SetXTitle(fHistXTitle.Data());
+        h->SetYTitle(fHistYTitle.Data());
+      }
+  
+  if (IsAverageing())
+    {
+      if (fAverageLoGainAreas)
+        for (Int_t j=0; j<fAverageLoGainAreas->GetSize(); j++)
+          {
+            MHCalibrationPix &pix = GetAverageLoGainArea(j);        
+            h = pix.GetHGausHist();
+            h->SetName (Form("%s%s%s%d","H",fHistName.Data(),"LoGainArea",j));
+            h->SetXTitle(fHistXTitle.Data());
+            h->SetYTitle(fHistYTitle.Data());
+            if (fGeom->InheritsFrom("MGeomCamMagic"))
+              h->SetTitle(Form("%s%s%s%s",fHistTitle.Data()," averaged on event-by-event basis ",
+                               j==0 ? "Inner Pixels " : "Outer Pixels ","Low Gain Runs: "));
+            else
+              h->SetTitle(Form("%s%s%d%s",fHistTitle.Data(),
+                               " averaged on event-by-event basis Low Gain Area Idx ",j," Runs: "));
+          }
+      
+      if (fAverageLoGainSectors)
+        for (Int_t j=0; j<fAverageLoGainSectors->GetSize(); j++)
+          {
+            MHCalibrationPix &pix = GetAverageLoGainSector(j);        
+            h = pix.GetHGausHist();
+            h->SetName (Form("%s%s%s%02d","H",fHistName.Data(),"LoGainSector",j));
+            h->SetTitle(Form("%s%s%02d%s",fHistTitle.Data(),
+                             " averaged on event-by-event basis Low Gain Sector ",j," Runs: "));
+            h->SetXTitle(fHistXTitle.Data());
+            h->SetYTitle(fHistYTitle.Data());
+          }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MGeomCam
+//
+// Calls SetupHists(const MParList *pList)
+//
+// Calls Delete-Function of:
+// - MHCalibrationCam::fHiGainArray, MHCalibrationCam::fLoGainArray
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+//
+Bool_t MHCalibrationCam::SetupFill(const MParList *pList)
+{
+  
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+  {
+      *fLog << err << GetDescriptor() 
+            << ": MGeomCam not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!fRunHeader)
+  {
+    *fLog << warn << GetDescriptor() 
+          << ": MRawRunHeader not found... will not store run numbers." << endl;
+  }
+
+  return SetupHists(pList);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Searches MRawEvtHeader to find the correct pulser colour
+//
+// Gets or creates the pointers to:
+// - MBadPixelsIntensityCam
+// - MBadPixelsCam
+//
+// Searches pointer to:
+// - MArrivalTimeCam
+//
+// Initializes, if empty to MArrivalTimeCam::GetSize() for:
+// - MHCalibrationCam::fHiGainArray, MHCalibrationCam::fLoGainArray
+//
+// Initializes, if empty to MGeomCam::GetNumAreas() for:
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+//
+// Initializes, if empty to MGeomCam::GetNumSectors() for:
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+// 
+// Initializes TArray's to MGeomCam::GetNumAreas and MGeomCam::GetNumSectors, respectively
+// Fills with number of valid pixels (if !MBadPixelsPix::IsBad()):
+// - MHCalibrationCam::fAverageAreaNum[area index]
+// - MHCalibrationCam::fAverageSectorNum[area index]
+//
+// Calls InitializeHists() for every entry in:
+// - MHCalibrationCam::fHiGainArray
+// - MHCalibrationCam::fAverageHiGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors
+//
+// Sets Titles and Names for the Histograms 
+// - MHCalibrationCam::fAverageHiGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors
+// 
+// Retrieves the run numbers from MRawRunHeader and stores them in fRunNumbers
+//
+Bool_t MHCalibrationCam::ReInit(MParList *pList)
+{
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  fIntensBad = (MBadPixelsIntensityCam*)pList->FindObject(AddSerialNumber("MBadPixelsIntensityCam"));
+  if (fIntensBad)
+    *fLog << inf << "Found MBadPixelsIntensityCam ... " << endl;
+  else
+    {
+      fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+      if (!fBadPixels)
+        {
+          
+          fBadPixels = (MBadPixelsCam*)pList->FindCreateObj(AddSerialNumber("MBadPixelsCam"));
+          if (!fBadPixels)
+              return kFALSE;
+
+          fBadPixels->InitSize(npixels);
+        }
+    }
+  
+  if (IsAverageing())
+    {
+      //
+      // The function TArrayF::Set() already sets all entries to 0.
+      //
+      fAverageAreaNum.        Set(nareas);
+      fAverageAreaSat.        Set(nareas);           
+      fAverageAreaSigma.      Set(nareas);      
+      fAverageAreaSigmaVar.   Set(nareas);   
+      fAverageAreaRelSigma.   Set(nareas);   
+      fAverageAreaRelSigmaVar.Set(nareas);
+      fAverageSectorNum.      Set(nsectors);
+      
+      for (Int_t aidx=0; aidx<nareas; aidx++)
+        fAverageAreaNum[aidx] = 0;
+      
+      for (Int_t sector=0; sector<nsectors; sector++)
+        fAverageSectorNum[sector] = 0;
+  
+      for (Int_t i=0; i<npixels; i++)
+        {
+          
+          MBadPixelsPix &bad = fIntensBad ? (*fIntensBad)[i] : (*fBadPixels)[i];
+          if (bad.IsBad())
+            continue;
+          
+          fAverageAreaNum  [(*fGeom)[i].GetAidx()  ]++;
+          fAverageSectorNum[(*fGeom)[i].GetSector()]++;
+        }
+    }
+
+  //
+  // Because ReInit has been called, a new run number is added
+  //
+  fRunNumbers.Set(fRunNumbers.GetSize()+1);
+
+  if (fRunHeader)
+    {
+      fRunNumbers[fRunNumbers.GetSize()-1] = fRunHeader->GetRunNumber();
+      if (IsLoGain())
+        SetLoGain(fRunHeader->GetNumSamplesLoGain());
+    }
+
+  if (!ReInitHists(pList))
+    return kFALSE;
+
+  ResetHistTitles();
+
+  if (!fRunHeader)
+    return kTRUE;
+  
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      TH1F *h = (*this)[i].GetHGausHist();
+      h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+    }
+
+  if (IsLoGain())
+    for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+      {
+        TH1F *h = (*this)(i).GetHGausHist();
+        h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+      }
+  
+  if (!IsAverageing())
+    return kTRUE;
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+      TH1F *h = GetAverageHiGainArea(j).GetHGausHist();
+      h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+    }
+  
+  if (IsLoGain())
+    for (Int_t j=0; j<nareas; j++)
+      {
+        TH1F *h = GetAverageLoGainArea(j).GetHGausHist();
+        h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+      }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      TH1F *h = GetAverageHiGainSector(j).GetHGausHist();
+      h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+    }
+  
+  if (IsLoGain())
+    for (Int_t j=0; j<nsectors; j++)
+      {
+        TH1F *h = GetAverageLoGainSector(j).GetHGausHist();
+        h->SetTitle( Form("%s%08d ", h->GetTitle(),fRunNumbers[fRunNumbers.GetSize()-1]));
+      }
+  
+  return kTRUE;
+}
+
+//--------------------------------------------------------------------------------------
+//
+// Initializes the High Gain Arrays:
+// 
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationPix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set X-axis and Y-axis titles with fHistXTitle and fHistYTitle
+//   * Call InitHists
+//
+void MHCalibrationCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationPix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                 Form("%s High Gain Pixel %4d",fHistTitle.Data(),i)),i);
+        
+        MHCalibrationPix &pix = (*this)[i];          
+        pix.SetNbins(fNbins);
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+        pix.SetProbLimit(fProbLimit);
+        
+        MBadPixelsPix &bad = fIntensBad ? (*fIntensBad)[i] : (*fBadPixels)[i];
+        InitHists(pix,bad,i);
+
+	if (fCam)
+	  (*fCam)[i].SetPixId(i);
+      }
+  }
+
+  if (!IsAverageing())
+    return;
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHCalibrationPix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                        Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationPix &pix = GetAverageHiGainArea(j);
+        
+        pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+
+        if (fGeom && fGeom->InheritsFrom("MGeomCamMagic"))
+          {
+            pix.InitBins();
+            pix.SetEventFrequency(fPulserFrequency);
+          }
+        else
+          InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadArea(j) : fCam->GetAverageBadArea(j),j);
+      }
+  }
+
+  if (fAverageHiGainSectors->GetSize()==0)
+    {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+          fAverageHiGainSectors->AddAt(new MHCalibrationPix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                            Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+          MHCalibrationPix &pix = GetAverageHiGainSector(j);
+
+          pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nsectors));
+          pix.SetFirst(fFirst);
+          pix.SetLast (fLast);
+          
+          InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadSector(j) : fCam->GetAverageBadSector(j),j);
+      }
+  }
+}
+
+//--------------------------------------------------------------------------------------
+//
+// Return, if IsLoGain() is kFALSE 
+//
+// Initializes the Low Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationPix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set X-axis and Y-axis titles with fHistXTitle and fHistYTitle
+//   * Call InitHists
+//
+void MHCalibrationCam::InitLoGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+
+  if (!IsLoGain())
+    return;
+
+  if (fLoGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fLoGainArray->AddAt(new MHCalibrationPix(Form("%sLoGainPix%04d",fHistName.Data(),i),
+                                                 Form("%s Low Gain Pixel%04d",fHistTitle.Data(),i)),i);
+        
+        MHCalibrationPix &pix = (*this)(i);          
+        pix.SetNbins(fNbins);
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+        pix.SetProbLimit(fProbLimit);
+        
+        MBadPixelsPix &bad = fIntensBad ? (*fIntensBad)[i] : (*fBadPixels)[i];
+        InitHists(pix,bad,i);
+      }
+  }
+
+  if (!IsAverageing())
+    return;
+
+  if (fAverageLoGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageLoGainAreas->AddAt(new MHCalibrationPix(Form("%sLoGainArea%d",fHistName.Data(),j),
+                                                        Form("%s Low Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationPix &pix = GetAverageLoGainArea(j);
+        
+        pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+        
+        if (fGeom && fGeom->InheritsFrom("MGeomCamMagic"))
+          {
+            pix.InitBins();
+            pix.SetEventFrequency(fPulserFrequency);
+          }
+        else
+          InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadArea(j) : fCam->GetAverageBadArea(j),j);
+      }
+  }
+
+  if (fAverageLoGainSectors->GetSize()==0)
+    {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+          fAverageLoGainSectors->AddAt(new MHCalibrationPix(Form("%sLoGainSector%02d",fHistName.Data(),j),
+                                                            Form("%s Low Gain Sector %02d",fHistTitle.Data(),j)),j);
+          MHCalibrationPix &pix = GetAverageLoGainSector(j);
+
+          pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nsectors));
+          pix.SetFirst(fFirst);
+          pix.SetLast (fLast);
+          
+          InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadSector(j) : fCam->GetAverageBadSector(j),j);
+      }
+  }
+}
+
+//--------------------------------------------------------------------------------
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Return kFALSE, if sizes of the TOrdCollections do not match npixels, nareas or nsectors
+// 
+// Call FillHists()
+//
+Bool_t MHCalibrationCam::Fill(const MParContainer *par, const Stat_t w)
+{
+
+  if (!IsSizeCheck())
+    return FillHists(par,w);
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  
+  //
+  // Hi-Gain OrdCollections
+  //
+  if (fHiGainArray->GetSize() != npixels)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of pixels... abort." << endl;
+      return kFALSE;
+    }
+  
+  if (IsLoGain())
+    {
+      if (fLoGainArray->GetSize() != npixels)
+        {
+          *fLog << err << "ERROR - Size mismatch in number of pixels... abort." << endl;
+          return kFALSE;
+        }
+    }
+  
+  if (!IsAverageing())
+    return FillHists(par,w);
+
+  if (fAverageHiGainAreas->GetSize() != nareas)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of areas ... abort." << endl;
+      return kFALSE;
+    }
+  
+  if (fAverageHiGainSectors->GetSize() != nsectors)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of sectors ... abort." << endl;
+      return kFALSE;
+    }
+  
+  if (IsLoGain())
+    {
+      
+      if (fAverageLoGainAreas->GetSize() != nareas)
+        {
+          *fLog << err << "ERROR - Size mismatch in number of areas ... abort." << endl;
+          return kFALSE;
+        }
+      
+      if (fAverageLoGainSectors->GetSize() != nsectors)
+        {
+          *fLog << err << "ERROR - Size mismatch in number of sectors ... abort." << endl;
+          return kFALSE;
+        }
+    }
+  
+  return FillHists(par, w);
+}
+
+// --------------------------------------------------------------------------
+//
+// 0) Ask if fHiGainArray and fLoGainArray have been initialized, 
+//    otherwise return kFALSE.
+// 1) FinalizeHists()
+// 2) FinalizeBadPixels()
+// 3) CalcAverageSigma()
+//
+Bool_t MHCalibrationCam::Finalize()
+{
+
+  if (GetNumExecutions() < 2)
+    return kTRUE;
+
+  if (fHiGainArray->GetSize() == 0 && fLoGainArray->GetSize() == 0)
+    {
+      *fLog << err << GetDescriptor() 
+            << ": ERROR: Both (HiGain and LoGain) histogram arrays have not been initialized... abort." << endl;
+      return kFALSE;
+    }
+  
+  for (Int_t i=0; i<fAverageHiGainAreas->GetSize(); i++)
+    {
+      TH1F *h = GetAverageHiGainArea(i).GetHGausHist();
+      switch (fColor)
+        {
+        case MCalibrationCam::kNONE: 
+          break;
+        case MCalibrationCam::kBLUE: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"BLUE "));
+          break;
+        case MCalibrationCam::kGREEN: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"GREEN "));
+          break;
+        case MCalibrationCam::kUV: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"UV "));
+          break;
+        case MCalibrationCam::kCT1: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"CT1-Pulser "));
+          break;
+        }
+    }
+
+  for (Int_t i=0; i<fAverageLoGainAreas->GetSize(); i++)
+    {
+      TH1F *h = GetAverageLoGainArea(i).GetHGausHist();
+      switch (fColor)
+        {
+        case MCalibrationCam::kNONE: 
+          break;
+        case MCalibrationCam::kBLUE: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"BLUE "));
+          break;
+        case MCalibrationCam::kGREEN: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"GREEN "));
+          break;
+        case MCalibrationCam::kUV: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"UV "));
+          break;
+        case MCalibrationCam::kCT1: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"CT1-Pulser "));
+          break;
+        }
+    }
+  
+  if (!FinalizeHists())
+    return kFALSE;
+
+
+  FinalizeBadPixels();
+  CalcAverageSigma();
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------
+//
+// If MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableRun):
+// - calls MHCalibrationPix::SetExcluded()
+//
+// Calls:
+// - MHGausEvents::InitBins()
+// - MHCalibrationPix::ChangeHistId(i)
+// - MHCalibrationPix::SetEventFrequency(fPulserFrequency)
+// 
+void MHCalibrationCam::InitHists(MHCalibrationPix &hist, MBadPixelsPix &bad, const Int_t i)
+{
+
+  if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+    hist.SetExcluded();
+
+  hist.InitBins();
+  hist.SetEventFrequency(fPulserFrequency);
+}
+
+// -------------------------------------------------------------
+//
+// - Searches for the CalibrationIntensity*Cam corresponding to 'name'. 
+// - In case, it does not exist in the parameter list, it searches
+//   for the corresponding MCalibration*Cam.
+// - Initializes the MCalibration*Cam, if not yet done.
+// 
+Bool_t MHCalibrationCam::InitCams( MParList *plist, const TString name )
+{
+
+  TString intensname = "MCalibrationIntensity";
+  intensname += name;
+  intensname += "Cam";
+
+  TString ordname    = "MCalibration";
+  ordname    += name;
+  ordname    += "Cam";
+
+  fIntensCam = (MCalibrationIntensityCam*)plist->FindObject(AddSerialNumber(intensname));
+  if (fIntensCam)
+    *fLog << inf << "Found " << intensname << "... " << endl;
+  else
+    {
+      fCam = (MCalibrationCam*)plist->FindObject(AddSerialNumber(ordname));
+      if (!fCam)
+        {
+          fCam = (MCalibrationCam*)plist->FindCreateObj(AddSerialNumber(ordname));
+          if (!fCam)
+              return kFALSE;
+
+          fCam->Init(*fGeom);
+        }
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls FitHiGainHists for every entry in:
+// - fHiGainArray
+// - fAverageHiGainAreas
+// - fAverageHiGainSectors
+// 
+void MHCalibrationCam::FitHiGainArrays(MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                                       MBadPixelsPix::UncalibratedType_t fittyp, 
+                                       MBadPixelsPix::UncalibratedType_t osctyp)
+{
+  
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)[i];
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      MCalibrationPix &pix    = calcam[i];
+      MBadPixelsPix   &bad    = badcam[i];
+      
+      FitHiGainHists(hist,pix,bad,fittyp,osctyp);
+    }
+
+  if (!IsAverageing())
+    return;
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageHiGainArea(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageArea(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadArea(j);        
+
+      FitHiGainHists(hist,pix,bad,fittyp,osctyp);
+  }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      MHCalibrationPix &hist = GetAverageHiGainSector(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageSector(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadSector(j);        
+
+      FitHiGainHists(hist,pix,bad,fittyp,osctyp);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls FitLoGainHists for every entry in:
+// - fLoGainArray
+// - fAverageLoGainAreas
+// - fAverageLoGainSectors
+// 
+void MHCalibrationCam::FitLoGainArrays(MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                                            MBadPixelsPix::UncalibratedType_t fittyp, 
+                                            MBadPixelsPix::UncalibratedType_t osctyp)
+{
+  
+  if (!IsLoGain())
+    return;
+
+  for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)(i);
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      MCalibrationPix &pix    = calcam[i];
+      MBadPixelsPix   &bad    = badcam[i];
+      
+      FitLoGainHists(hist,pix,bad,fittyp,osctyp);
+      
+    }
+
+  if (!IsAverageing())
+    return;
+  
+  for (Int_t j=0; j<fAverageLoGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageLoGainArea(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageArea(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadArea(j);        
+      
+      FitLoGainHists(hist,pix,bad,fittyp,osctyp);
+  }
+  
+  for (Int_t j=0; j<fAverageLoGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageLoGainSector(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageSector(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadSector(j);        
+      
+      FitLoGainHists(hist,pix,bad,fittyp,osctyp);
+    }
+}
+
+//------------------------------------------------------------
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels
+//
+void MHCalibrationCam::CalcAverageSigma()
+{
+
+  if (!fCam)
+    return;
+  
+  if (!IsAverageing())
+    return;
+  
+  for (UInt_t j=0; j<fGeom->GetNumAreas(); j++)
+    {
+  
+      MCalibrationPix &pix    = fCam->GetAverageArea(j);
+
+      const Float_t numsqr    = TMath::Sqrt((Float_t)fAverageAreaNum[j]);
+      fAverageAreaSigma[j]    = pix.GetSigma    () * numsqr;
+      fAverageAreaSigmaVar[j] = pix.GetSigmaErr () * pix.GetSigmaErr() * numsqr;
+
+      pix.SetSigma   (fAverageAreaSigma[j]);
+      pix.SetSigmaVar(fAverageAreaSigmaVar[j]);
+
+      fAverageAreaRelSigma   [j]  = fAverageAreaSigma[j]    / pix.GetMean();
+      fAverageAreaRelSigmaVar[j]  = fAverageAreaSigmaVar[j] / (fAverageAreaSigma[j]*fAverageAreaSigma[j]);
+      fAverageAreaRelSigmaVar[j] += pix.GetMeanRelVar();
+      fAverageAreaRelSigmaVar[j] *= fAverageAreaRelSigma[j];
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// Returns if the histogram is empty and sets the following flag:
+// - MBadPixelsPix::SetUnsuitable(MBadPixelsPix::kUnsuitableRun)
+//
+// Fits the histograms with a Gaussian, in case of failure 
+// calls MHCalibrationPix::RepeatFit(), in case of repeated failure 
+// calls MHCalibrationPix::BypassFit() and sets the following flags:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::UncalibratedType_t fittyp )
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun   )
+// 
+// Creates the fourier spectrum and tests MHGausEvents::IsFourierSpectrumOK(). 
+// In case no, sets the following flags:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::UncalibratedType_t osctyp )
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun     )
+//
+// Retrieves the results and store them in MCalibrationPix
+//
+void MHCalibrationCam::FitHiGainHists(MHCalibrationPix &hist, 
+                                      MCalibrationPix &pix, 
+                                      MBadPixelsPix &bad, 
+                                      MBadPixelsPix::UncalibratedType_t fittyp,
+                                      MBadPixelsPix::UncalibratedType_t osctyp)
+{
+
+  if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+    {
+      *fLog << warn << GetDescriptor()
+	    << ": Only overflow or underflow in hi-gain pixel: " << pix.GetPixId() << endl;
+      return;
+    }  
+  //
+  // 2) Fit the Hi Gain histograms with a Gaussian
+  //
+  if (!hist.FitGaus())
+    //
+    // 3) In case of failure set the bit Fitted to false and take histogram means and RMS
+    //
+    if (!hist.RepeatFit())
+      {
+        hist.BypassFit();
+        bad.SetUncalibrated( fittyp );
+      }
+ 
+  //
+  // 4) Check for oscillations
+  // 
+  if (IsOscillations())
+    {
+      hist.CreateFourierSpectrum();
+  
+      if (!hist.IsFourierSpectrumOK())
+        bad.SetUncalibrated( osctyp );
+    }
+  
+  //
+  // 5) Retrieve the results and store them in this class
+  //
+  pix.SetHiGainMean       ( hist.GetMean()      );
+  pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+  pix.SetHiGainRms        ( hist.GetHistRms()   );
+  pix.SetHiGainSigma      ( hist.GetSigma()     );
+  pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+  pix.SetHiGainProb       ( hist.GetProb()      );
+  pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+  pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << GetDescriptor() << ": ID " << GetName() 
+            << " HiGainSaturation: "   << pix.IsHiGainSaturation() 
+            << " HiGainMean: "         << hist.GetMean    ()
+            << " HiGainMeanErr: "      << hist.GetMeanErr ()
+            << " HiGainMeanSigma: "    << hist.GetSigma   ()
+            << " HiGainMeanSigmaErr: " << hist.GetSigmaErr()
+            << " HiGainMeanProb: "     << hist.GetProb    ()
+            << " HiGainNumBlackout: "  << hist.GetBlackout()
+            << " HiGainNumPickup  : "  << hist.GetPickup  ()
+            << endl;
+    }
+
+}
+
+
+// ---------------------------------------------------------------------------
+//
+// Returns if the histogram is empty and sets the following flag:
+// - MBadPixelsPix::SetUnsuitable(MBadPixelsPix::kUnsuitableRun)
+//
+// Fits the histograms with a Gaussian, in case of failure 
+// calls MHCalibrationPix::RepeatFit(), in case of repeated failure 
+// calls MHCalibrationPix::BypassFit() and sets the following flags:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::UncalibratedType_t fittyp )
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun   )
+// 
+// Creates the fourier spectrum and tests MHGausEvents::IsFourierSpectrumOK(). 
+// In case no, sets the following flags:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::UncalibratedType_t osctyp )
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun     )
+//
+// Retrieves the results and store them in MCalibrationPix
+//
+void MHCalibrationCam::FitLoGainHists(MHCalibrationPix &hist, 
+                                      MCalibrationPix &pix, 
+                                      MBadPixelsPix &bad, 
+                                      MBadPixelsPix::UncalibratedType_t fittyp,
+                                      MBadPixelsPix::UncalibratedType_t osctyp)
+{
+
+  if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+    {
+      *fLog << warn << GetDescriptor()
+	    << ": Only overflow or underflow in lo-gain pixel: " << pix.GetPixId() << endl;
+      return;
+    }  
+  //
+  // 2) Fit the Hi Gain histograms with a Gaussian
+  //
+  if (!hist.FitGaus())
+    //
+    // 3) In case of failure set the bit Fitted to false and take histogram means and RMS
+    //
+    if (!hist.RepeatFit())
+      {
+        hist.BypassFit();
+        if (pix.IsHiGainSaturation())
+          bad.SetUncalibrated( fittyp );
+      }
+  
+  //
+  // 4) Check for oscillations
+  // 
+  if (IsOscillations())
+    {
+      hist.CreateFourierSpectrum();
+      
+      if (!hist.IsFourierSpectrumOK())
+        bad.SetUncalibrated( osctyp );
+    }
+  
+  //
+  // 5) Retrieve the results and store them in this class
+  //
+  pix.SetLoGainMean       ( hist.GetMean()      );
+  pix.SetLoGainMeanVar    ( hist.GetMeanErr()  * hist.GetMeanErr()   );
+  pix.SetLoGainRms        ( hist.GetHistRms()   );
+  pix.SetLoGainSigma      ( hist.GetSigma()     );
+  pix.SetLoGainSigmaVar   ( hist.GetSigmaErr() * hist.GetSigmaErr()  );
+  pix.SetLoGainProb       ( hist.GetProb()      );
+  pix.SetLoGainNumBlackout( hist.GetBlackout()  );
+  pix.SetLoGainNumPickup  ( hist.GetPickup()    );
+  
+  if (IsDebug())
+    {
+      *fLog << dbginf << GetDescriptor() << "ID: " << hist.GetName() 
+            << " HiGainSaturation: "   << pix.IsHiGainSaturation() 
+            << " LoGainMean: "         << hist.GetMean    ()
+            << " LoGainMeanErr: "      << hist.GetMeanErr ()
+            << " LoGainMeanSigma: "    << hist.GetSigma   ()
+            << " LoGainMeanSigmaErr: " << hist.GetSigmaErr()
+            << " LoGainMeanProb: "     << hist.GetProb    ()
+            << " LoGainNumBlackout: "  << hist.GetBlackout()
+            << " LoGainNumPickup  : "  << hist.GetPickup  ()
+            << endl;
+    }
+
+}
+
+
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationCam::Draw(const Option_t *opt)
+{
+
+  if (!IsAverageing())
+    return;
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  pad->Divide(IsLoGain() ? 2 : 1,nareas);
+
+  for (Int_t i=0; i<nareas;i++) 
+    {
+
+      pad->cd(IsLoGain() ? 2*(i+1)-1 : i+1);
+      GetAverageHiGainArea(i).Draw(opt);
+
+      if (!fAverageAreaSat[i])
+        DrawAverageSigma(fAverageAreaSat[i], i,
+                         fAverageAreaSigma[i],    fAverageAreaSigmaVar[i],
+                         fAverageAreaRelSigma[i], fAverageAreaRelSigmaVar[i]);
+
+      if (IsLoGain())
+        {
+          pad->cd(2*(i+1));
+          GetAverageLoGainArea(i).Draw(opt);
+        }
+      
+      if (fAverageAreaSat[i])
+        DrawAverageSigma(fAverageAreaSat[i], i,
+                         fAverageAreaSigma[i], fAverageAreaSigmaVar[i],
+                         fAverageAreaRelSigma[i], fAverageAreaRelSigmaVar[i]);
+    }
+      
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays a TPaveText with the re-normalized sigmas of the average area
+//
+void MHCalibrationCam::DrawAverageSigma(Bool_t sat, Bool_t inner,
+                                              Float_t sigma, Float_t sigmavar,
+                                              Float_t relsigma, Float_t relsigmavar) const 
+{
+  
+  if (sigma != 0 && sigmavar >= 0 && relsigmavar >= 0.)
+    {
+      
+      TPad *newpad = new TPad("newpad","transparent",0,0,1,1);
+      newpad->SetFillStyle(4000);
+      newpad->Draw();
+      newpad->cd();
+      
+      TPaveText *text = new TPaveText(sat? 0.1 : 0.35,0.7,sat ? 0.4 : 0.7,1.0);
+      text->SetTextSize(0.05);
+      const TString line1 = Form("%s%s%s",inner ? "Outer" : "Inner",
+                                 " Pixels ", sat ? "Low Gain" : "High Gain");
+      TText *txt1 = text->AddText(line1.Data());
+      const TString line2 = Form("#sigma per pix: %2.2f #pm %2.2f",sigma,TMath::Sqrt(sigmavar));
+      TText *txt2 = text->AddText(line2.Data());
+      const TString line3 = Form("Rel. #sigma per pix: %2.2f #pm %2.2f",relsigma,TMath::Sqrt(relsigmavar));
+      TText *txt3 = text->AddText(line3.Data());
+      text->Draw("");
+      
+      text->SetBit(kCanDelete);
+      txt1->SetBit(kCanDelete);
+      txt2->SetBit(kCanDelete);
+      txt3->SetBit(kCanDelete);
+      newpad->SetBit(kCanDelete);
+    }
+}
+
+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;
+    }
+  if (IsEnvDefined(env, prefix, "LoGain", print))
+    {
+      SetDebug(GetEnvValue(env, prefix, "LoGain", IsLoGain()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "Oscillations", print))
+    {
+      SetOscillations(GetEnvValue(env, prefix, "Oscillations", IsOscillations()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "SizeCheck", print))
+    {
+      SetSizeCheck(GetEnvValue(env, prefix, "SizeCheck", IsSizeCheck()));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "Averageing", print))
+    {
+      SetAverageing(GetEnvValue(env, prefix, "Averageing", IsAverageing()));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "Nbins", print))
+    {
+      SetNbins(GetEnvValue(env, prefix, "Nbins", fNbins));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "First", print))
+    {
+      SetFirst(GetEnvValue(env, prefix, "First", fFirst));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "Last", print))
+    {
+      SetLast(GetEnvValue(env, prefix, "Last", fLast));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "ProbLimit", print))
+    {
+      SetProbLimit(GetEnvValue(env, prefix, "ProbLimit", fProbLimit));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "OverflowLimit", print))
+    {
+      SetOverflowLimit(GetEnvValue(env, prefix, "OverflowLimit", fOverflowLimit));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "PulserFrequency", print))
+    {
+      SetPulserFrequency(GetEnvValue(env, prefix, "PulserFrequency", fPulserFrequency));
+      rc = kTRUE;
+    }
+  
+  return rc;
+}
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationCam.h	(revision 9772)
@@ -0,0 +1,228 @@
+#ifndef MARS_MHCalibrationCam
+#define MARS_MHCalibrationCam
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class TText;
+class TOrdCollection;
+
+class MHCalibrationPix;
+class MGeomCam;
+class MRawRunHeader;
+class MCalibrationIntensityCam;
+class MCalibrationCam;
+class MCalibrationPix;
+class MBadPixelsIntensityCam;
+class MBadPixelsCam;
+class MBadPixelsPix;
+
+class MHCalibrationCam : public MH, public MCamEvent
+{
+  
+private:
+
+  static const Int_t   fgPulserFrequency;  //! The default for fPulserFrequency (now set to: 500)
+  static const Float_t fgProbLimit;        //! The default for fProbLimit (now set to: 0.0001)  
+  static const Float_t fgOverflowLimit;    //! The default for fOverflowLimit (now at: 0.005)
+  
+  static const TString gsHistName;         //! Default Histogram names
+  static const TString gsHistTitle;        //! Default Histogram titles
+  static const TString gsHistXTitle;       //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;       //! Default Histogram y-axis titles
+  
+protected:
+
+  Int_t   fNbins;                         // Number of bins        
+  Axis_t  fFirst;                         // Lower histogram limit 
+  Axis_t  fLast;                          // Upper histogram limit 
+ 
+  Float_t fProbLimit;                     // Limit for acceptance of probability of Gauss-Fit
+  Float_t fOverflowLimit;                 // Part of maximum allowed overflow events
+  
+  TString fHistName;                      //! Histogram names
+  TString fHistTitle;                     //! Histogram titles
+  TString fHistXTitle;                    //! Histogram x-axis titles
+  TString fHistYTitle;                    //! Histogram y-axis titles
+  
+  Float_t fNumHiGainSaturationLimit;      // Rel. amount sat. higain FADC slices until pixel is called saturated 
+  Float_t fNumLoGainSaturationLimit;      // Rel. amount sat. logain FADC slices until pixel is called saturated
+  
+  MArrayI fRunNumbers;                    // Numbers of runs used
+
+  MArrayF fAverageAreaRelSigma;           // Re-normalized relative sigmas in average pixels per area
+  MArrayF fAverageAreaRelSigmaVar;        // Variance Re-normalized relative sigmas in average pixels per area 
+  MArrayI fAverageAreaSat;                // Number of saturated slices in average pixels per area
+  MArrayF fAverageAreaSigma;              // Re-normalized sigmas in average pixels per area
+  MArrayF fAverageAreaSigmaVar;           // Variance Re-normalized sigmas in average pixels per area
+  MArrayI fAverageAreaNum;                // Number of pixels in average pixels per area
+  MArrayI fAverageSectorNum;              // Number of pixels in average pixels per sector
+
+  TOrdCollection *fAverageHiGainAreas;    // Array of calibration pixels, one per pixel area
+  TOrdCollection *fAverageHiGainSectors;  // Array of calibration pixels, one per camera sector
+  TOrdCollection *fAverageLoGainAreas;    // Array of calibration pixels, one per pixel area
+  TOrdCollection *fAverageLoGainSectors;  // Array of calibration pixels, one per camera sector
+
+  MCalibrationCam::PulserColor_t fColor;  // Colour of the pulsed LEDs
+
+  MBadPixelsIntensityCam *fIntensBad;     //! Bad Pixels intensity calibration storage container  
+  MBadPixelsCam    *fBadPixels;           //! Bad Pixels storage container
+  MCalibrationIntensityCam *fIntensCam;   //! Intensity Calibration Cam with the results
+  MCalibrationCam  *fCam;                 //! Calibration Cam with the results
+  MGeomCam         *fGeom;                //! Camera geometry
+  MRawRunHeader    *fRunHeader;           //! Run Header
+  
+  TOrdCollection *fHiGainArray;           // Array of calibration pixels, one per pixel
+  TOrdCollection *fLoGainArray;           // Array of calibration pixels, one per pixel
+
+  Int_t  fPulserFrequency;                // Light pulser frequency
+
+  enum { kDebug, kLoGain, kAverageing,
+         kOscillations, kSizeCheck };     // Possible global flags
+   
+  Byte_t  fFlags;                         // Bit-field to hold the global flags
+  
+  virtual Bool_t SetupHists ( const MParList *pList ) { return kTRUE; }
+  virtual Bool_t ReInitHists(       MParList *pList ) { return kTRUE; }
+  virtual Bool_t FillHists  ( const MParContainer *par, const Stat_t w=1) { return kTRUE; }
+  virtual Bool_t FinalizeHists()                      { return kTRUE;  }
+  
+  virtual void   FinalizeBadPixels() { }
+  
+  virtual void   CalcAverageSigma();
+  
+  virtual void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+  virtual void   InitLoGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+  
+  virtual void   ResetHistTitles();
+  
+  void DrawAverageSigma( Bool_t sat, Bool_t inner,
+                         Float_t sigma, Float_t sigmaerr,
+                         Float_t relsigma, Float_t relsigmaerr) const; 
+  
+  void FitHiGainArrays ( MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                         MBadPixelsPix::UncalibratedType_t fittyp,
+                         MBadPixelsPix::UncalibratedType_t osctyp);
+  
+  void FitHiGainHists  ( MHCalibrationPix &hist, 
+                         MCalibrationPix &pix, 
+                         MBadPixelsPix &bad, 
+                         MBadPixelsPix::UncalibratedType_t fittyp,
+                         MBadPixelsPix::UncalibratedType_t osctyp);
+  
+  void FitLoGainArrays ( MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                         MBadPixelsPix::UncalibratedType_t fittyp,
+                         MBadPixelsPix::UncalibratedType_t osctyp);
+  
+  void FitLoGainHists  ( MHCalibrationPix &hist, 
+                         MCalibrationPix &pix, 
+                         MBadPixelsPix &bad, 
+                         MBadPixelsPix::UncalibratedType_t fittyp,
+                         MBadPixelsPix::UncalibratedType_t osctyp);
+
+  void   InitHists     ( MHCalibrationPix &hist, MBadPixelsPix &bad, const Int_t i);
+  Bool_t InitCams      ( MParList *plist, const TString name );
+  
+  Bool_t IsAverageing  () const  { return TESTBIT(fFlags,kAverageing);   }
+  Bool_t IsDebug       () const  { return TESTBIT(fFlags,kDebug);        }  
+  Bool_t IsLoGain      () const  { return TESTBIT(fFlags,kLoGain);       }
+  Bool_t IsOscillations() const  { return TESTBIT(fFlags,kOscillations); }
+  Bool_t IsSizeCheck   () const  { return TESTBIT(fFlags,kSizeCheck);    }
+
+  void   Remove  ( TOrdCollection *col );
+  
+  Int_t  ReadEnv ( const TEnv &env, TString prefix, Bool_t print );
+
+public:
+
+  MHCalibrationCam(const char *name=NULL, const char *title=NULL);
+  virtual ~MHCalibrationCam();
+
+  Bool_t SetupFill(const MParList *pList);
+  Bool_t ReInit   (      MParList *pList);
+  Bool_t Fill     (const MParContainer *par, const Stat_t w=1);
+  Bool_t Finalize ( );
+
+  virtual void ResetHists();
+
+  // Draw
+  void   Draw(const Option_t *opt);       // *MENU*
+
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const { return kTRUE; }
+  void   DrawPixelContent( Int_t num )  const  {}
+
+  const Int_t              GetAverageAreas       ()          const;	 
+        MHCalibrationPix  &GetAverageHiGainArea  (UInt_t i);
+  const MHCalibrationPix  &GetAverageHiGainArea  (UInt_t i)  const;
+        MHCalibrationPix  &GetAverageLoGainArea  (UInt_t i);
+  const MHCalibrationPix  &GetAverageLoGainArea  (UInt_t i)  const;
+        MHCalibrationPix  &GetAverageHiGainSector(UInt_t i);
+  const MHCalibrationPix  &GetAverageHiGainSector(UInt_t i)  const;
+        MHCalibrationPix  &GetAverageLoGainSector(UInt_t i);
+  const MHCalibrationPix  &GetAverageLoGainSector(UInt_t i)  const;
+  const Int_t              GetAverageSectors     ()          const;
+  const MCalibrationCam::PulserColor_t GetColor   ()     const  { return fColor;                    }
+  const Float_t        GetNumHiGainSaturationLimit()     const  { return fNumHiGainSaturationLimit; }
+  const Float_t        GetNumLoGainSaturationLimit()     const  { return fNumLoGainSaturationLimit; }
+  const MArrayI       &GetRunNumbers         ()          const { return fRunNumbers;            }
+  const Int_t          GetSize               ()          const;
+
+        MHCalibrationPix  &operator[]            (UInt_t i);
+  const MHCalibrationPix  &operator[]            (UInt_t i)  const;
+        MHCalibrationPix  &operator()            (UInt_t i);
+  const MHCalibrationPix  &operator()            (UInt_t i)  const;
+ 
+  void SetColor                   ( const MCalibrationCam::PulserColor_t color) { fColor = color; }
+  void SetAverageing              ( const Bool_t b=kTRUE ) { b 
+								? SETBIT(fFlags,kAverageing) 
+								: CLRBIT(fFlags,kAverageing); }
+  void SetDebug                   ( const Bool_t b=kTRUE ) { b 
+								? SETBIT(fFlags,kDebug) 
+								: CLRBIT(fFlags,kDebug); }
+  void SetLoGain                  ( const Bool_t b=kTRUE ) { b 
+								? SETBIT(fFlags,kLoGain) 
+								: CLRBIT(fFlags,kLoGain); }
+  void SetOscillations            ( const Bool_t b=kTRUE ) { b 
+								? SETBIT(fFlags,kOscillations) 
+								: CLRBIT(fFlags,kOscillations); }
+  void SetSizeCheck               ( const Bool_t b=kTRUE ) { b 
+								? SETBIT(fFlags,kSizeCheck) 
+								: CLRBIT(fFlags,kSizeCheck); }
+  void SetHistName  ( const char *name )  { fHistName  = name;  }
+  void SetHistTitle ( const char *name )  { fHistTitle = name;  }
+  void SetHistXTitle( const char *name )  { fHistXTitle = name; }
+  void SetHistYTitle( const char *name )  { fHistYTitle = name; }
+   
+  void SetNbins                   ( const Int_t  i )       { fNbins   = i; }
+  void SetFirst                   ( const Axis_t f )       { fFirst   = f; }
+  void SetLast                    ( const Axis_t f )       { fLast    = f; }
+
+  void SetProbLimit               ( const Float_t f=fgProbLimit) { fProbLimit = f; }    
+
+  void SetNumLoGainSaturationLimit( const Float_t lim )    { fNumLoGainSaturationLimit  = lim; }
+  void SetNumHiGainSaturationLimit( const Float_t lim )    { fNumHiGainSaturationLimit  = lim; }
+  void SetOverflowLimit        ( const Float_t f=fgOverflowLimit ) { fOverflowLimit = f; }
+  void SetPulserFrequency      ( const Int_t   i=fgPulserFrequency )   { fPulserFrequency  = i; }
+  
+  ClassDef(MHCalibrationCam, 4)	// Base Histogram class for Calibration Camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindCam.cc	(revision 9772)
@@ -0,0 +1,527 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHCalibrationChargeBlindCam                                               
+//
+// Histogram class for blind pixels in the camera. Incorporates the TObjArray's:
+// - fBlindPixelsArray (for calibrated High Gains per pixel)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargeBlindCam.h"
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TOrdCollection.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalBlindPixel.h"
+
+#include "MCalibrationBlindPix.h"
+#include "MCalibrationIntensityBlindCam.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+
+ClassImp(MHCalibrationChargeBlindCam);
+
+using namespace std;
+const Int_t     MHCalibrationChargeBlindCam::fgNbins    =  128;
+const Axis_t    MHCalibrationChargeBlindCam::fgFirst    = -0.5;
+const Axis_t    MHCalibrationChargeBlindCam::fgLast     =  511.5;
+const Axis_t    MHCalibrationChargeBlindCam::fgSPheCut  =  20.;
+const TString   MHCalibrationChargeBlindCam::gsHistName   = "ChargeBlind";
+const TString   MHCalibrationChargeBlindCam::gsHistTitle  = "Signals Blind";
+const TString   MHCalibrationChargeBlindCam::gsHistXTitle = "Signal [FADC counts]";
+const TString   MHCalibrationChargeBlindCam::gsHistYTitle = "Nr. events";
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// - fFitFunc to kEPoisson4
+// - fNbins   to fgNbins
+// - fFirst   to fgFirst
+// - fLast    to fgLast 
+// - fSPheCut to fgSPheCut
+// 
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - SetAverageing  (kFALSE);
+// - SetLoGain      (kFALSE);
+// - SetOscillations(kFALSE);
+// - SetSizeCheck   (kFALSE);
+//
+MHCalibrationChargeBlindCam::MHCalibrationChargeBlindCam(const char *name, const char *title)
+    : fRawEvt(NULL)
+{
+
+  fName  = name  ? name  : "MHCalibrationChargeBlindCam";
+  fTitle = title ? title : "Class to fille the blind pixel histograms";
+
+  SetSPheCut();
+
+  SetNbins(fgNbins);
+  SetFirst(fgFirst);
+  SetLast (fgLast );
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetAverageing  (kFALSE);
+  SetLoGain      (kFALSE);
+  SetOscillations(kFALSE);
+  SetSizeCheck   (kFALSE);
+
+  SetFitFunc(MHCalibrationChargeBlindPix::kEPoisson4);
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MRawEvtData
+//
+Bool_t MHCalibrationChargeBlindCam::SetupHists(const MParList *pList)
+{
+
+  fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+  if (!fRawEvt)
+  {
+      *fLog << err << dbginf << "MRawEvtData not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MExtractedSignalBlindPixel
+// - MCalibrationChargeCam or MCalibrationIntensityBlindCam
+//
+// Initializes the number of used FADC slices from MExtractedSignalCam 
+// into MCalibrationChargeCam and test for changes in that variable
+//
+// Retrieve:
+// - fRunHeader->GetNumSamplesHiGain();
+//
+// Initializes the High Gain Arrays:
+//
+// - Expand fHiGainArrays to nblindpixels
+// 
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationPix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Call InitHists
+//
+Bool_t MHCalibrationChargeBlindCam::ReInitHists(MParList *pList)
+{
+
+  if (!InitCams(pList,"Blind"))
+    return kFALSE;
+
+  MExtractedSignalBlindPixel *signal = 
+    (MExtractedSignalBlindPixel*)pList->FindObject(AddSerialNumber("MExtractedSignalBlindPixel"));
+  if (!signal)
+  {
+      *fLog << err << "MExtractedSignalBlindPixel not found... abort." << endl;
+      return kFALSE;
+  }
+
+  const Int_t nblindpixels = signal->GetNumBlindPixels();
+  const Int_t samples      = signal->GetNumFADCSamples();
+  const Int_t integ        = signal->IsExtractionType( MExtractBlindPixel::kIntegral );
+  
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<nblindpixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationChargeBlindPix(Form("%s%s%d",fHistName.Data(),"Pix",i),
+                                                  Form("%s%s%d",fHistTitle.Data()," Pixel ",i)),i);
+
+        MHCalibrationChargeBlindPix &pix = (MHCalibrationChargeBlindPix&)(*this)[i];
+
+        pix.SetNbins        ( fNbins );
+        pix.SetFirst        ( fFirst );
+        pix.SetLast         ( integ ? ((fLast+0.5)*samples)-0.5 : fLast    );
+        pix.SetSinglePheCut ( integ ? fSPheCut * samples        : fSPheCut );
+        pix.SetFitFunc      ( integ ? MHCalibrationChargeBlindPix::kEPoisson5 : fFitFunc );
+
+        pix.InitBins();
+
+      }
+  }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Resets the histogram titles for each entry in:
+// - fHiGainArray
+//
+void MHCalibrationChargeBlindCam::ResetHistTitles()
+{
+  
+  TH1F *h;
+
+  if (fHiGainArray)
+    for (Int_t i=0;i<fHiGainArray->GetSize(); i++)
+      {
+        MHCalibrationPix &pix = (*this)[i];        
+        h = pix.GetHGausHist();
+        h->SetName (Form("%s%s%s%d","H",fHistName.Data(),"Pix",i));
+        h->SetTitle(Form("%s%s%d%s",fHistTitle.Data()," Pixel ",i," Runs: "));  
+        h->SetXTitle(fHistXTitle.Data());
+        h->SetYTitle(fHistYTitle.Data());
+      }
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalBlindPixel:
+// - number of blind pixels
+//
+// Retrieves from MExtractedSignalBlindPixel:
+// - number of FADC samples
+// - extracted signal 
+// - blind Pixel ID
+//
+// Resizes (if necessary):
+// - fASinglePheFADCSlices to sum of HiGain and LoGain samples
+// - fAPedestalFADCSlices to sum of HiGain and LoGain samples
+//
+// Fills the following histograms:
+// - MHGausEvents::FillHistAndArray(signal)
+//
+// Creates MRawEvtPixelIter, jumps to blind pixel ID, 
+// fills the vectors fASinglePheFADCSlices and fAPedestalFADCSlices 
+// with the full FADC slices, depending on the size of the signal w.r.t. fSinglePheCut
+//
+Bool_t MHCalibrationChargeBlindCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MExtractedSignalBlindPixel *signal = (MExtractedSignalBlindPixel*)par;
+  if (!signal)
+    {
+      *fLog << err << "No argument in MExtractedSignalBlindCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const Int_t nblindpixels  = signal->GetNumBlindPixels();
+  
+  if (GetSize() != nblindpixels)
+    {
+      gLog << err << "ERROR - Size mismatch... abort." << endl;
+      return kFALSE;
+    }
+
+  Float_t slices = (Float_t)signal->GetNumFADCSamples();
+  
+  if (slices == 0.)
+    {
+      *fLog << err << dbginf
+	    << "Number of used signal slices in MExtractedSignalBlindPix "
+	    << "is zero  ... abort." 
+            << endl;
+      return kFALSE;
+    }
+  
+  for (Int_t i=0; i<nblindpixels; i++)
+    {
+
+      //
+      // Signal extraction and histogram filling
+      // If filter has been applied, sig has been set to -1.
+      //
+      const Float_t sig = signal->GetExtractedSignal(i);
+      
+      if (sig < -0.5)
+        continue;
+
+      MHCalibrationChargeBlindPix &hist = (MHCalibrationChargeBlindPix&)(*this)[i];
+
+      hist.FillHist(sig);
+      //
+      // In order to study the single-phe posistion, we extract the slices
+      //
+      const Int_t blindpixIdx = signal->GetBlindPixelIdx(i);
+      
+      MRawEvtPixelIter pixel(fRawEvt);
+      pixel.Jump(blindpixIdx);
+      
+      if (sig > fSPheCut)
+        hist.FillSinglePheFADCSlices(pixel);
+      else
+        hist.FillPedestalFADCSlices(pixel);
+
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For all TObjArray's (including the averaged ones), the following steps are performed: 
+//
+// 1) Returns if the pixel is excluded.
+// 2) Tests saturation. In case yes, set the flag: MCalibrationPix::SetHiGainSaturation()
+//    or the flag: MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturated )
+// 3) Store the absolute arrival times in the MCalibrationChargePix's. If flag 
+//    MCalibrationPix::IsHiGainSaturation() is set, the Low-Gain arrival times are stored, 
+//    otherwise the Hi-Gain ones.
+// 4) Calls to MHCalibrationCam::FitHiGainArrays() and MCalibrationCam::FitLoGainArrays() 
+//    with the flags:
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating )
+//
+Bool_t MHCalibrationChargeBlindCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  MCalibrationCam *blindcam = fIntensCam ? fIntensCam->GetCam() : fCam;
+      
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      MHCalibrationChargeBlindPix &hist = (MHCalibrationChargeBlindPix&)(*this)[i];
+      
+      TH1F *h = hist.GetHGausHist();
+
+      switch (fColor)
+        {
+        case MCalibrationCam::kNONE: 
+          break;
+        case MCalibrationCam::kBLUE: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"BLUE "));
+          break;
+        case MCalibrationCam::kGREEN: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"GREEN "));
+          break;
+        case MCalibrationCam::kUV: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"UV "));
+          break;
+        case MCalibrationCam::kCT1: 
+          h->SetTitle( Form("%s%s", h->GetTitle(),"CT1-Pulser "));
+          break;
+        }
+      
+      Stat_t overflow = h->GetBinContent(h->GetNbinsX()+1);
+      if (overflow > 0.1)
+        {
+          *fLog << warn << GetDescriptor()
+                << ": Histogram Overflow occurred " << overflow 
+                << " times in blind pixel: " << i << endl;
+        }
+
+      overflow = h->GetBinContent(0);
+      if (overflow > 0.1)
+        {
+          *fLog << warn << GetDescriptor()
+                << ": Histogram Underflow occurred " << overflow
+                << " times in blind pixel: " << i << endl;
+        }
+
+      MCalibrationBlindPix  &pix = (MCalibrationBlindPix&)(*blindcam)[i];
+
+      FitBlindPixel(hist,pix);
+    }
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns kFALSE, if empty
+//
+// - Creates the fourier spectrum and sets bit MHGausEvents::IsFourierSpectrumOK()
+// - Retrieves the pedestals from MExtractedSignalBlindPixel
+// - Normalizes fASinglePheFADCSlices and fAPedestalFADCSlices
+// - Executes FitPedestal()
+// - Executes FitSinglePhe()
+// - Retrieves fit results and stores them in MCalibrationBlindPix
+// 
+void MHCalibrationChargeBlindCam::FitBlindPixel(MHCalibrationChargeBlindPix &hist, MCalibrationBlindPix &pix)
+{
+
+  if (hist.IsEmpty())
+  {
+    *fLog << err << GetDescriptor() << " ID: " << hist.GetName()
+	  << " My histogram has not been filled !! " << endl;
+      return;
+  }
+
+  hist.FinalizeSinglePheSpectrum();
+  
+  hist.FitPedestal();
+
+  pix.SetValid(kTRUE);
+
+  if (hist.FitSinglePhe())
+    pix.SetSinglePheFitOK();
+  else
+    pix.SetValid(hist.IsPedestalFitOK());
+
+  pix.SetLambda      ( hist.GetLambda   () );
+  pix.SetLambdaVar   ( hist.GetLambdaErr()*hist.GetLambdaErr() );
+  pix.SetMu0         ( hist.GetMu0      () );
+  pix.SetMu0Err      ( hist.GetMu0Err   () );
+  pix.SetMu1         ( hist.GetMu1      () );
+  pix.SetMu1Err      ( hist.GetMu1Err   () );
+  pix.SetSigma0      ( hist.GetSigma0   () );
+  pix.SetSigma0Err   ( hist.GetSigma0Err() );
+  pix.SetSigma1      ( hist.GetSigma1   () );
+  pix.SetSigma1Err   ( hist.GetSigma1Err() );
+  pix.SetProb        ( hist.GetProb     () );
+
+  pix.SetLambdaCheck    ( hist.GetLambdaCheck()    );
+  pix.SetLambdaCheckErr ( hist.GetLambdaCheckErr() );
+}
+
+// --------------------------------------------------------------------------
+//
+// This Clone-function has to be different from the MHCalibrationCam 
+// Clone function since it does not store and display the averaged values 
+// (in fAverageAreas), but the blind pixels stored in fHiGainArray. 
+//
+// Creates new MHCalibrationChargeBlindCam and
+// Clones MHCalibrationChargeBlindPix's individually
+//
+#if 0
+TObject *MHCalibrationChargeBlindCam::Clone(const char *name) const
+{
+
+  MHCalibrationChargeBlindCam *cam = new MHCalibrationChargeBlindCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+  cam->fFitFunc                = fFitFunc;
+
+  const Int_t nhi = fHiGainArray->GetSize();
+  
+  for (int i=0; i<nhi; i++)
+    cam->fHiGainArray->AddAt((*this)[i].Clone(),i);
+
+  return cam;
+}
+#endif
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationChargeBlindCam::Draw(Option_t *opt)
+{
+
+  const Int_t size = fHiGainArray->GetSize();
+
+  if (size == 0)
+    return;
+  
+  TString option(opt);
+  option.ToLower();
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  switch (size)
+    {
+    case 1: 
+      break;
+    case 2:
+      pad->Divide(2,1);
+      break;
+    case 3:
+    case 4:
+      pad->Divide(2,2);
+      break;
+    default:
+      pad->Divide(size/2+1,size/2+1);
+      break;
+    }
+
+  for (Int_t i=0; i<size;i++) 
+    {
+      pad->cd(i+1);
+      (*this)[i].Draw(option);
+    }
+
+  pad->Modified();
+  pad->Update();
+
+}
+
+Int_t MHCalibrationChargeBlindCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (MHCalibrationCam::ReadEnv(env,prefix,print))
+    rc = kTRUE;
+  
+  if (IsEnvDefined(env, prefix, "SPheCut", print))
+    {
+      SetSPheCut(GetEnvValue(env, prefix, "SPheCut", fSPheCut));
+      rc = kTRUE;
+    }
+  
+  // FIXME: GetEnvValue does not work with enums yet
+  /*
+  if (IsEnvDefined(env, prefix, "FitFunc", print))
+    {
+      SetFitFunc((Int_t)GetEnvValue(env, prefix, "FitFunc", fFitFunc));
+      rc = kTRUE;
+  }
+  */
+  return rc;
+}
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindCam.h	(revision 9772)
@@ -0,0 +1,69 @@
+
+#ifndef MARS_MHCalibrationChargeBlindCam
+#define MARS_MHCalibrationChargeBlindCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MHCalibrationChargeBlindPix
+#include "MHCalibrationChargeBlindPix.h"
+#endif
+
+class MRawEvtData;
+class MCalibrationBlindPix;
+class MHCalibrationChargeBlindPix;
+class MHCalibrationChargeBlindCam : public MHCalibrationCam
+{
+private:
+
+  static const Int_t   fgNbins;        //! Default for fNBins new style blind pixel (now set to:  128   )
+  static const Axis_t  fgFirst;        //! Default for fFirst new style blind pixel (now set to: - 0.5 )
+  static const Axis_t  fgLast;         //! Default for fLast  new style blind pixel (now set to: 511.5 )
+
+  static const Axis_t  fgSPheCut;      //! Default for fSinglePheCut new style blind pixel (now set to: 20)
+  
+  static const TString gsHistName;     //! Default Histogram names
+  static const TString gsHistTitle;    //! Default Histogram titles
+  static const TString gsHistXTitle;   //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;   //! Default Histogram y-axis titles
+
+  Axis_t fSPheCut;                    // Signal value upon which event considered as single-phe
+  
+  MRawEvtData *fRawEvt;               //!  Raw event data
+
+  MHCalibrationChargeBlindPix::FitFunc_t fFitFunc; // The actual fit function type
+  
+  Bool_t SetupHists   (const MParList *pList );
+  Bool_t ReInitHists  (      MParList *pList );
+  Bool_t FillHists    (const MParContainer *par, const Stat_t w=1 );
+  Bool_t FinalizeHists();
+
+  void   ResetHistTitles();
+  void   FitBlindPixel( MHCalibrationChargeBlindPix &hist, MCalibrationBlindPix &pix);
+
+  Int_t ReadEnv        ( const TEnv &env, TString prefix, Bool_t print);  
+  
+public:
+
+  MHCalibrationChargeBlindCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeBlindCam() {}
+  
+  // Draw
+  void  Draw(Option_t *opt="");
+  void  SetFitFunc( const MHCalibrationChargeBlindPix::FitFunc_t func )  { fFitFunc = func;  }
+  void  SetSPheCut( const Axis_t    a   =fgSPheCut )  { fSPheCut = a;     }    
+  
+  ClassDef(MHCalibrationChargeBlindCam, 1)	// Histogram class for Blind Pixel Calibration
+};
+
+#endif
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindPix.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindPix.cc	(revision 9772)
@@ -0,0 +1,974 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationChargeBlindPix
+//
+//  Histogram class for the charge calibration of the Blind Pixel.
+//  Stores and fits the charges and stores the averaged assumed pedestal and 
+//  single-phe FADC slice entries. Charges are taken from MExtractedSignalBlindPix.
+//  Performs the Single Photo-electron fit to extract the Poisson mean and its errors.
+//
+//  Different fits can be chosen with the function SetFitFunc().
+//
+//  The fit result is accepted under the condition that:
+//  1) the Probability is greater than fProbLimit (default 0.001 == 99.7%)
+//  2) at least fNumSinglePheLimit events are found in the single Photo-electron peak
+//
+//  The single FADC slice entries are averaged and stored in fASinglePheFADCSlices, if 
+//  their sum exceeds fSinglePheCut, otherwise in fAPedestalFADCSlices.
+//
+//  Used numbers are the following:
+//
+//  Electronic conversion factor:
+//   Assume, we have N_e electrons at the anode, 
+//   thus a charge of N_e*e (e = electron charge) Coulomb.
+//
+//   This charge is AC coupled and runs into a R_pre = 50 Ohm resistency. 
+//   The corresponding current is amplified by a gain factor G_pre = 400 
+//   (the precision of this value still has to be checked !!!) and again AC coupled to 
+//   the output. 
+//   The corresponding signal goes through the whole transmission and 
+//   amplification chain and is digitized in the FADCs. 
+//   The conversion Signal Area to FADC counts (Conv_trans) has been measured 
+//   by David and Oscar to be approx. 3.9 pVs^-1
+//
+//   Thus: Conversion FADC counts to Number of Electrons at Anode: 
+//         FADC counts = (1/Conv_tran) * G_pre * R_pre *  e * N_e = 8 * 10^-4 N_e. 
+//
+//   Also: FADC counts = 8*10^-4 * GAIN * N_phe
+//
+//   In the blind pixel, there is an additional pre-amplifier with an amplification of 
+//   about 10. Therefore, we have for the blind pixel:
+//
+//
+//   FADC counts (Blind Pixel) = 8*10^-3 * GAIN * N_phe
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargeBlindPix.h"
+
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TPaveText.h>
+#include <TPaveStats.h>
+#include <TGraph.h>
+
+#include <TVector.h>
+#include <TF1.h>
+#include <TH1.h>
+#include <TH2D.h>
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MHCalibrationChargeBlindPix);
+
+using namespace std;
+
+const Double_t MHCalibrationChargeBlindPix::gkElectronicAmp      = 0.008;
+const Double_t MHCalibrationChargeBlindPix::gkElectronicAmpErr   = 0.002;
+const Float_t  MHCalibrationChargeBlindPix::gkSignalInitializer  = -9999.;
+const Float_t  MHCalibrationChargeBlindPix::fgNumSinglePheLimit  =  50.;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNumSinglePheLimit (fgNumSinglePheLimit)
+// - the default number of bins after stripping (30)
+//
+// Initializes:
+// - all pointers to NULL
+// - fASinglePheFADCSlices(0);
+// - fAPedestalFADCSlices(0);
+//
+// Calls:
+// - Clear()
+//
+MHCalibrationChargeBlindPix::MHCalibrationChargeBlindPix(const char *name, const char *title)
+    :  fSinglePheFit(NULL), 
+       fFitLegend(NULL),
+       fHSinglePheFADCSlices(NULL), fHPedestalFADCSlices(NULL)
+{
+
+    fName  = name  ? name  : "MHCalibrationChargeBlindPix";
+    fTitle = title ? title : "Statistics of the FADC sums of Blind Pixel calibration events";
+
+    fASinglePheFADCSlices.ResizeTo(1);
+    fAPedestalFADCSlices.ResizeTo(1);
+
+    SetNumSinglePheLimit();
+    SetProbLimit(0.001);
+    SetBinsAfterStripping(0);
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Destructor. 
+//
+// Deletes (if Pointer is not NULL):
+// 
+// - fFitLegend 
+// - fHSinglePheFADCSlices
+// - fHPedestalFADCSlices    
+// - fSinglePheFit
+// 
+MHCalibrationChargeBlindPix::~MHCalibrationChargeBlindPix()
+{
+
+  //
+  // The next two lines are important for the case that 
+  // the class has been stored to a file and is read again. 
+  // In this case, the next two lines prevent a segm. violation
+  // in the destructor
+  //
+  gROOT->GetListOfFunctions()->Remove(fSinglePheFit);
+
+  if (fSinglePheFit)
+      delete fSinglePheFit;
+  
+  if (fFitLegend)
+    delete fFitLegend;
+
+  if (fHSinglePheFADCSlices)
+    delete fHSinglePheFADCSlices;
+
+  if (fHPedestalFADCSlices)
+    delete fHPedestalFADCSlices;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - all variables to 0., except the fit result variables to gkSignalInitializer
+// - all flags to kFALSE
+// - all pointers to NULL
+// - the default fit function (kEPoisson5)
+//
+// Deletes: 
+// - all pointers unequal NULL
+//
+// Calls:
+// - MHCalibrationChargePix::Clear()
+//
+void MHCalibrationChargeBlindPix::Clear(Option_t *o)
+{
+
+  fLambda    = gkSignalInitializer;
+  fMu0       = gkSignalInitializer;
+  fMu1       = gkSignalInitializer;
+  fSigma0    = gkSignalInitializer;
+  fSigma1    = gkSignalInitializer;
+  fLambdaErr = gkSignalInitializer;
+  fMu0Err    = gkSignalInitializer;
+  fMu1Err    = gkSignalInitializer;
+  fSigma0Err = gkSignalInitializer;
+  fSigma1Err = gkSignalInitializer;
+
+  fLambdaCheck    = gkSignalInitializer;
+  fLambdaCheckErr = gkSignalInitializer;
+  
+  fFitFunc = kEPoisson5;
+
+  fNumSinglePhes    = 0;
+  fNumPedestals     = 0;
+
+  fChisquare        = 0.;
+  fNDF              = 0 ;
+  fProb             = 0.;
+
+  SetSinglePheFitOK ( kFALSE );
+  SetPedestalFitOK  ( kFALSE );
+
+  if (fFitLegend)
+  {
+    delete fFitLegend;
+    fFitLegend = NULL;
+  }
+
+  if (fSinglePheFit)
+  {
+    delete fSinglePheFit;
+    fSinglePheFit = NULL;
+  }
+
+  if (fHSinglePheFADCSlices)
+  {
+    delete fHSinglePheFADCSlices;
+    fHSinglePheFADCSlices = NULL;
+  }
+
+  if (fHPedestalFADCSlices)
+  {
+    delete fHPedestalFADCSlices;
+    fHPedestalFADCSlices = NULL;
+  }
+
+  MHCalibrationPix::Clear();
+  return;
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Our own clone function is necessary since root 3.01/06 or Mars 0.4
+// I don't know the reason. 
+//
+// Creates new MHCalibrationCam
+//
+TObject *MHCalibrationChargeBlindPix::Clone(const char *) const
+{
+
+    MHCalibrationChargeBlindPix *pix = new MHCalibrationChargeBlindPix();
+    this->Copy(*pix);
+
+    this->fHGausHist.Copy(pix->fHGausHist);
+    this->fSinglePheFit->Copy(*(pix->fSinglePheFit));
+    this->fHSinglePheFADCSlices->Copy(*(pix->fHSinglePheFADCSlices));
+    this->fHPedestalFADCSlices->Copy(*(pix->fHPedestalFADCSlices));
+    
+
+    return pix;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Set bit kSinglePheFitOK from outside
+//
+void MHCalibrationChargeBlindPix::SetSinglePheFitOK (const Bool_t b ) 
+{
+    b ? SETBIT(fFlags,kSinglePheFitOK) : CLRBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set bit kPedestalFitOK from outside
+//
+void MHCalibrationChargeBlindPix::SetPedestalFitOK(const Bool_t b)
+{
+    b ? SETBIT(fFlags,kPedestalFitOK) : CLRBIT(fFlags,kPedestalFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Ask for status of bit kSinglePheFitOK 
+//
+const Bool_t  MHCalibrationChargeBlindPix::IsSinglePheFitOK()     const 
+{
+    return TESTBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Ask for status of bit kPedestalFitOK 
+//
+const Bool_t  MHCalibrationChargeBlindPix::IsPedestalFitOK()  const
+{
+    return TESTBIT(fFlags,kPedestalFitOK);
+}
+  
+// --------------------------------------------------------------------------
+//
+// Normalizes fASinglePheFADCSlices and fAPedestalFADCSlices
+// 
+void MHCalibrationChargeBlindPix::FinalizeSinglePheSpectrum() 
+{
+  
+  if (fNumSinglePhes > 1)
+      for (Int_t i=0;i<fASinglePheFADCSlices.GetNrows();i++)
+	  fASinglePheFADCSlices[i] = fASinglePheFADCSlices[i]/fNumSinglePhes;
+  if (fNumPedestals > 1)
+      for (Int_t i=0;i<fAPedestalFADCSlices.GetNrows();i++)
+        fAPedestalFADCSlices[i]  = fAPedestalFADCSlices[i]/fNumPedestals;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks again for the size and fills fASinglePheFADCSlices with the FADC slice entries
+// 
+void MHCalibrationChargeBlindPix::FillSinglePheFADCSlices(const MRawEvtPixelIter &iter)
+{
+
+  const Int_t n = iter.GetNumHiGainSamples() + iter.GetNumLoGainSamples();
+
+  if (fASinglePheFADCSlices.GetNrows() < n)
+      fASinglePheFADCSlices.ResizeTo(n);
+  
+  Int_t i=0;
+  
+  Byte_t *start = iter.GetHiGainSamples();
+  Byte_t *end   = start + iter.GetNumHiGainSamples();
+
+  for (Byte_t *ptr = start; ptr < end; ptr++, i++)
+      fASinglePheFADCSlices(i) = fASinglePheFADCSlices(i) + (Float_t)*ptr;
+
+  start = iter.GetLoGainSamples();
+  end   = start + iter.GetNumLoGainSamples();
+
+  for (Byte_t *ptr = start; ptr < end; ptr++, i++)
+      fASinglePheFADCSlices(i) = fASinglePheFADCSlices(i) + (Float_t)*ptr;
+
+  fNumSinglePhes++;
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks again for the size and fills fAPedestalFADCSlices with the FADC slice entries
+// 
+void MHCalibrationChargeBlindPix::FillPedestalFADCSlices(const MRawEvtPixelIter &iter)
+{
+
+  const Int_t n = iter.GetNumHiGainSamples() + iter.GetNumLoGainSamples();
+
+  if (fAPedestalFADCSlices.GetNrows() < n)
+      fAPedestalFADCSlices.ResizeTo(n);
+
+  Int_t i = 0;
+  Byte_t *start = iter.GetHiGainSamples();
+  Byte_t *end   = start + iter.GetNumHiGainSamples();
+
+  for (Byte_t *ptr = start; ptr < end; ptr++, i++)
+      fAPedestalFADCSlices(i) = fAPedestalFADCSlices(i)+ (Float_t)*ptr;
+
+  start = iter.GetLoGainSamples();
+  end   = start + iter.GetNumLoGainSamples();
+
+  for (Byte_t *ptr = start; ptr < end; ptr++, i++)
+      fAPedestalFADCSlices(i) = fAPedestalFADCSlices(i)+ (Float_t)*ptr;
+
+  fNumPedestals++;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Task to simulate single phe spectrum with the given parameters
+// 
+Bool_t MHCalibrationChargeBlindPix::SimulateSinglePhe(Double_t lambda, Double_t mu0, Double_t mu1, Double_t sigma0, Double_t sigma1) 
+{
+
+  gRandom->SetSeed();
+
+  if (fHGausHist.GetIntegral() != 0)
+    {
+      *fLog << err << "Histogram " << fHGausHist.GetTitle() << " is already filled. " << endl;
+      *fLog << err << "Create new class MHCalibrationBlindPixel for simulation! " << endl;
+      return kFALSE;
+    }
+
+  if (!InitFit())
+    return kFALSE;
+
+  for (Int_t i=0;i<10000; i++) 
+    fHGausHist.Fill(fSinglePheFit->GetRandom());
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// - Get the ranges from the stripped histogram
+// - choose reasonable start values for the fit
+// - initialize the fit function depending on fFitFunc
+// - initialize parameter names and limits depending on fFitFunc
+//
+Bool_t MHCalibrationChargeBlindPix::InitFit()
+{
+  
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetFirst());
+  Axis_t rmax = fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetLast()); 
+
+  if (rmin < 0.)
+      rmin = 0.;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  // otherwise the fit goes gaga because of high number of dimensions ...
+  //
+  const Stat_t   entries      = fHGausHist.Integral("width");
+  const Double_t lambda_guess = 0.5;
+  //const Double_t maximum_bin  = fHGausHist.GetBinCenter(fHGausHist.GetMaximumBin());
+  const Double_t norm         = entries/TMath::Sqrt(TMath::TwoPi());
+
+  //
+  // Initialize the fit function
+  //
+  switch (fFitFunc)
+    {
+    case kEPoisson4:
+      fSinglePheFit = new TF1("SinglePheFit",&fPoissonKto4,rmin,rmax,6);
+      rmin += 6.5;
+      break;
+    case kEPoisson5:
+      fSinglePheFit = new TF1("SinglePheFit",&fPoissonKto5,rmin,rmax,6);
+      rmin = 0.;
+      break;
+    case kEPoisson6:
+      fSinglePheFit = new TF1("SinglePheFit",&fPoissonKto6,rmin,rmax,6);
+      break;
+    case kEPolya:
+      fSinglePheFit = new TF1("SinglePheFit",&fPolya,rmin,rmax,8);
+      break;
+    case kEMichele:
+      fSinglePheFit = new TF1("SinglePheFit",&fFitFuncMichele,rmin,rmax,9);
+      break;
+    default:
+      *fLog << warn << "WARNING: Could not find Fit Function for Blind Pixel " << endl;
+      return kFALSE;
+      break;
+    }
+
+  if (!fSinglePheFit) 
+  {
+      *fLog << warn << dbginf << "WARNING: Could not create fit function for Single Phe fit" << endl;
+      return kFALSE;
+  }
+
+  //
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  // 
+  gROOT->GetListOfFunctions()->Remove(fSinglePheFit);
+  
+  const Double_t mu_0_guess = 13.5;
+  const Double_t si_0_guess = 2.5;
+  const Double_t mu_1_guess = 30.;
+  const Double_t si_1_guess = si_0_guess + si_0_guess;
+  // Michele
+  const Double_t lambda_1cat_guess = 1.00;
+  const Double_t lambda_1dyn_guess = lambda_1cat_guess/10.;
+  const Double_t mu_1cat_guess = 50.;
+  const Double_t mu_1dyn_guess = 17.;
+  const Double_t si_1cat_guess = si_0_guess + si_0_guess;
+  const Double_t si_1dyn_guess = si_0_guess + si_0_guess/2.;
+  // Polya
+  const Double_t excessPoisson_guess = 0.5;
+  const Double_t delta1_guess     = 8.;
+  const Double_t delta2_guess     = 5.;
+  const Double_t electronicAmp_guess  = gkElectronicAmp;
+  const Double_t electronicAmp_limit  = gkElectronicAmpErr;
+
+  //
+  // Initialize boundaries and start parameters
+  //
+  switch (fFitFunc)
+    {
+      
+    case kEPoisson4:
+	fSinglePheFit->SetParNames(  "#lambda",   "#mu_{0}",    "#mu_{1}", "#sigma_{0}",  "#sigma_{1}","Area");
+        fSinglePheFit->SetParameters(lambda_guess,mu_0_guess,mu_1_guess,si_0_guess,si_1_guess,norm);
+	fSinglePheFit->SetParLimits(0,0.,2.);
+        fSinglePheFit->SetParLimits(1,10.,17.);
+	fSinglePheFit->SetParLimits(2,17.,50.);
+        fSinglePheFit->SetParLimits(3,1.,5.);
+	fSinglePheFit->SetParLimits(4,5.,30.);
+	fSinglePheFit->SetParLimits(5,norm-(0.5*norm),norm+(0.7*norm));
+	break;
+    case kEPoisson5:
+    case kEPoisson6:
+      fSinglePheFit->SetParNames("#lambda","#mu_{0}","#mu_{1}","#sigma_{0}","#sigma_{1}","Area");
+      fSinglePheFit->SetParameters(lambda_guess,mu_0_guess,800.,si_0_guess,500.,norm);
+      fSinglePheFit->SetParLimits(0,0.,2.);
+      fSinglePheFit->SetParLimits(1,0.,100.);
+      fSinglePheFit->SetParLimits(2,300.,1500.);
+      fSinglePheFit->SetParLimits(3,30.,250.);
+      fSinglePheFit->SetParLimits(4,100.,1000.);
+      fSinglePheFit->SetParLimits(5,norm/1.5,norm*1.5);
+      break;
+
+    case kEPolya:
+        fSinglePheFit->SetParameters(lambda_guess, excessPoisson_guess,
+                                     delta1_guess,delta2_guess,
+                                     electronicAmp_guess,
+                                     10.,
+                                     norm, 
+                                     0.);
+      fSinglePheFit->SetParNames("#lambda","b_{tot}",
+                                 "#delta_{1}","#delta_{2}",
+                                 "amp_{e}","#sigma_{0}",
+                                 "Area", "#mu_{0}");
+      fSinglePheFit->SetParLimits(0,0.,1.);
+      fSinglePheFit->SetParLimits(1,0.,1.); 
+      fSinglePheFit->SetParLimits(2,6.,12.);    
+      fSinglePheFit->SetParLimits(3,3.,8.);    
+      fSinglePheFit->SetParLimits(4,electronicAmp_guess-electronicAmp_limit,
+                                    electronicAmp_guess+electronicAmp_limit);    
+      fSinglePheFit->SetParLimits(5,0.,40.);
+      fSinglePheFit->SetParLimits(6,norm-0.1,norm+0.1);
+      fSinglePheFit->SetParLimits(7,-10.,10.);
+      break;
+    case kEMichele:
+      fSinglePheFit->SetParNames("#lambda_{cat}","#lambda_{dyn}",
+                                 "#mu_{0}","#mu_{1cat}","#mu_{1dyn}",
+                                 "#sigma_{0}","#sigma_{1cat}","#sigma_{1dyn}",
+                                 "Area");
+      fSinglePheFit->SetParameters(lambda_1cat_guess, lambda_1dyn_guess, 
+                                   mu_0_guess, mu_1cat_guess,mu_1dyn_guess,
+                                   si_0_guess, si_1cat_guess,si_1dyn_guess,
+                                   norm);
+      fSinglePheFit->SetParLimits(0,0.01,2.0);
+      fSinglePheFit->SetParLimits(1,0.,0.5); 
+      fSinglePheFit->SetParLimits(2,10.,16.);    
+      fSinglePheFit->SetParLimits(3,25.,50.);    
+      fSinglePheFit->SetParLimits(4,16.,18.5);    
+      fSinglePheFit->SetParLimits(5,1.,5.);    
+      fSinglePheFit->SetParLimits(6,10.,50.);    
+      fSinglePheFit->SetParLimits(7,5.,10.);    
+      fSinglePheFit->SetParLimits(8,norm/2.,norm*2.5);
+      break;
+
+    default:
+      *fLog << warn << "WARNING: Could not find Fit Function for Blind Pixel " << endl;
+      return kFALSE;
+      break;
+    }
+
+  fSinglePheFit->SetRange(rmin,rmax);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// - Retrieve the parameters depending on fFitFunc
+// - Retrieve probability, Chisquare and NDF
+//
+void MHCalibrationChargeBlindPix::ExitFit()
+{
+  
+
+  //
+  // Finalize
+  //
+  switch (fFitFunc)
+    {
+      
+    case kEPoisson4:
+    case kEPoisson5:
+    case kEPoisson6:
+    case kEPoisson7:
+      fLambda = fSinglePheFit->GetParameter(0);
+      fMu0    = fSinglePheFit->GetParameter(1);
+      fMu1    = fSinglePheFit->GetParameter(2);
+      fSigma0 = fSinglePheFit->GetParameter(3);
+      fSigma1 = fSinglePheFit->GetParameter(4);
+      
+      fLambdaErr = fSinglePheFit->GetParError(0);
+      fMu0Err    = fSinglePheFit->GetParError(1);
+      fMu1Err    = fSinglePheFit->GetParError(2);
+      fSigma0Err = fSinglePheFit->GetParError(3);
+      fSigma1Err = fSinglePheFit->GetParError(4);
+      break;
+    case kEPolya:
+      fLambda =  fSinglePheFit->GetParameter(0);
+      fMu0    =  fSinglePheFit->GetParameter(7);
+      fMu1    = 0.;
+      fSigma0 =  fSinglePheFit->GetParameter(5);
+      fSigma1 = 0.;
+
+      fLambdaErr = fSinglePheFit->GetParError(0);
+      fMu0Err    = fSinglePheFit->GetParError(7);
+      fMu1Err    = 0.;
+      fSigma0Err = fSinglePheFit->GetParError(5);
+      fSigma1Err = 0.;
+    case kEMichele:
+      fLambda =  fSinglePheFit->GetParameter(0);
+      fMu0    =  fSinglePheFit->GetParameter(2);
+      fMu1    =  fSinglePheFit->GetParameter(3);
+      fSigma0 =  fSinglePheFit->GetParameter(5);
+      fSigma1 =  fSinglePheFit->GetParameter(6);
+
+      fLambdaErr = fSinglePheFit->GetParError(0);
+      fMu0Err    = fSinglePheFit->GetParError(2);
+      fMu1Err    = fSinglePheFit->GetParError(3);
+      fSigma0Err = fSinglePheFit->GetParError(5);
+      fSigma1Err = fSinglePheFit->GetParError(6);
+      break;
+    default:
+      break;
+    }
+
+  fProb      = fSinglePheFit->GetProb();
+  fChisquare = fSinglePheFit->GetChisquare();
+  fNDF       = fSinglePheFit->GetNDF();
+
+  *fLog << all << "Results of the Blind Pixel Fit: "              << endl;
+  *fLog << all << "Chisquare:   " << fChisquare                   << endl;
+  *fLog << all << "DoF:         " << fNDF                         << endl;
+  *fLog << all << "Probability: " << fProb                        << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// - Executes InitFit()
+// - Fits the fHGausHist with fSinglePheFit
+// - Executes ExitFit()
+//
+// The fit result is accepted under condition:
+// 1) The results are not nan's
+// 2) The NDF is not smaller than fNDFLimit (5)
+// 3) The Probability is greater than fProbLimit (default 0.001 == 99.9%)
+// 4) at least fNumSinglePheLimit events are in the single Photo-electron peak
+//
+Bool_t MHCalibrationChargeBlindPix::FitSinglePhe(Option_t *opt) 
+{
+
+  if (!InitFit())
+      return kFALSE;
+
+  fHGausHist.Fit(fSinglePheFit,opt);
+
+  ExitFit();
+
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (5)
+  // 3) The Probability is greater than fProbLimit (default 0.001 == 99.9%)
+  // 4) at least fNumSinglePheLimit events are in the single Photo-electron peak
+  //
+  if (   TMath::IsNaN(fLambda) 
+      || TMath::IsNaN(fLambdaErr)
+      || TMath::IsNaN(fProb)    
+      || TMath::IsNaN(fMu0)
+      || TMath::IsNaN(fMu0Err) 
+      || TMath::IsNaN(fMu1)
+      || TMath::IsNaN(fMu1Err) 
+      || TMath::IsNaN(fSigma0)
+      || TMath::IsNaN(fSigma0Err) 
+      || TMath::IsNaN(fSigma1)
+      || TMath::IsNaN(fSigma1Err) 
+      || fNDF  < fNDFLimit
+      || fProb < fProbLimit )
+    return kFALSE;
+
+  const Stat_t   entries      = fHGausHist.Integral("width");
+  const Float_t  numSinglePhe = TMath::Exp(-1.0*fLambda)*fLambda*entries;
+  
+  if (numSinglePhe < fNumSinglePheLimit) 
+    {
+      *fLog << warn << "WARNING - Statistics is too low: Only " << numSinglePhe
+            << " in the Single Photo-Electron peak " << endl;
+      return kFALSE;
+    } 
+  else
+    *fLog << all << numSinglePhe << " in Single Photo-Electron peak " << endl;
+  
+  SetSinglePheFitOK();
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// - Retrieves limits for the fit
+// - Fits the fHGausHist with Gauss 
+// - Retrieves the results to fLambdaCheck and fLambdaCheckErr
+// - Sets a flag IsPedestalFitOK()
+//
+void MHCalibrationChargeBlindPix::FitPedestal  (Option_t *opt)
+{
+
+  // Perform the cross-check fitting only the pedestal:
+  const Axis_t rmin    = 0.;
+  //  const Axis_t rmax    = fHGausHist.GetBinCenter(fHGausHist.GetMaximumBin());
+  const Axis_t rmax = fSinglePheCut;
+
+  FitGaus(opt, rmin, rmax);
+
+  const Stat_t   entries = fHGausHist.Integral("width");
+  const Double_t pedarea = fFGausFit->Integral(0.,fSinglePheCut);
+
+  fLambdaCheck     = TMath::Log(entries/pedarea);
+  // estimate the error by the error of the obtained area from the Gauss-function:
+  fLambdaCheckErr  = fFGausFit->GetParError(0)/fFGausFit->GetParameter(0);
+  
+  SetPedestalFitOK(IsGausFitOK());
+  return;
+}
+
+ 
+// -------------------------------------------------------------------------
+//
+// Draw a legend with the fit results
+//
+void MHCalibrationChargeBlindPix::DrawLegend(Option_t *opt)
+{
+
+  TString option(opt);
+
+  if (!fFitLegend)
+  {
+      fFitLegend = new TPaveText(0.05,0.05,0.95,0.95);
+      fFitLegend->SetLabel(Form("%s%s", "Results of the single PhE Fit (",
+				(fFitFunc ==  kEPoisson4) ? "Poisson(k=4))" : 
+				(fFitFunc ==  kEPoisson5) ? "Poisson(k=5))" : 
+				(fFitFunc ==  kEPoisson6) ? "Poisson(k=6))" :
+				(fFitFunc ==  kEPolya   ) ? "Polya(k=4))"   : 
+				(fFitFunc ==  kEMichele ) ?  "Michele)"     
+                                                                                       : " none )" ));
+      fFitLegend->SetTextSize(0.05);
+  }
+  else
+      fFitLegend->Clear();
+
+  const TString line1 = 
+      Form("Mean: #lambda = %2.2f #pm %2.2f",fLambda,fLambdaErr);
+  TText *t1 = fFitLegend->AddText(line1.Data());
+  t1->SetBit(kCanDelete);
+      
+  const TString line6 =
+      Form("Mean #lambda_{check} = %2.2f #pm %2.2f",fLambdaCheck,fLambdaCheckErr);
+  TText *t2 = fFitLegend->AddText(line6.Data());
+  t2->SetBit(kCanDelete);
+
+  if (option.Contains("datacheck"))
+    {
+      if (fLambda + 3.*fLambdaErr < fLambdaCheck - 3.*fLambdaCheckErr 
+          || 
+          fLambda - 3.*fLambdaErr > fLambdaCheck + 3.*fLambdaCheckErr )
+        {
+          TText *t = fFitLegend->AddText("#lambda and #lambda_{check} more than 3#sigma apart!");
+          t->SetBit(kCanDelete);
+        }
+    }
+  else
+    {
+
+      const TString line2 = 
+        Form("Pedestal: #mu_{0} = %2.2f #pm %2.2f",fMu0,fMu0Err);
+      TText *t3 = fFitLegend->AddText(line2.Data());
+      t3->SetBit(kCanDelete);
+      
+      const TString line3 =
+        Form("Width Pedestal: #sigma_{0} = %2.2f #pm %2.2f",fSigma0,fSigma0Err);
+      TText *t4 = fFitLegend->AddText(line3.Data());
+      t4->SetBit(kCanDelete);
+      
+      const TString line4 =
+        Form("1^{st} Phe-peak: #mu_{1} = %2.2f #pm %2.2f",fMu1,fMu1Err);
+      TText *t5 = fFitLegend->AddText(line4.Data());
+      t5->SetBit(kCanDelete);
+      
+      const TString line5 =
+        Form("Width 1^{st} Phe-peak: #sigma_{1} = %2.2f #pm %2.2f",fSigma1,fSigma1Err);
+      TText *t6 = fFitLegend->AddText(line5.Data());
+      t6->SetBit(kCanDelete);
+    }
+  
+  const TString line7 =
+    Form("#chi^{2} / N_{dof}: %4.2f / %3i",fChisquare,fNDF);
+  TText *t7 = fFitLegend->AddText(line7.Data());
+  t7->SetBit(kCanDelete);
+  
+  const TString line8 =
+      Form("Probability: %6.4f ",fProb);
+  TText *t8 = fFitLegend->AddText(line8.Data());
+  t8->SetBit(kCanDelete);
+  
+  if (IsSinglePheFitOK())
+  {
+      TText *t = fFitLegend->AddText("Result of the Fit: OK");
+      t->SetBit(kCanDelete);
+  }
+  else
+  {
+      TText *t = fFitLegend->AddText("Result of the Fit: NOT OK");
+      t->SetBit(kCanDelete);
+  }
+
+  fFitLegend->SetFillColor(IsSinglePheFitOK() ? 80 : 2);
+  fFitLegend->Draw();
+  
+  return;
+}
+
+
+// -------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+// The following options can be chosen:
+//
+// "": displays the fHGausHist, the fits, the legend and fASinglePheFADCSlices and fAPedestalFADCSlices
+// "all": executes additionally MHGausEvents::Draw(), with option "fourierevents"
+// "datacheck" display the fHGausHist, the fits and the legend
+//
+void MHCalibrationChargeBlindPix::Draw(Option_t *opt) 
+{
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win = 1;
+
+  TVirtualPad *oldpad = gPad ? gPad : MH::MakeDefCanvas(this,900, 600);
+  TVirtualPad *pad    = NULL;
+
+  if (option.Contains("all"))
+  {
+      option.ReplaceAll("all","");
+      oldpad->Divide(2,1);
+      win = 2;
+      oldpad->cd(1);
+      TVirtualPad *newpad = gPad;
+      pad = newpad;
+      pad->Divide(2,2);
+      pad->cd(1);
+  }
+  else if (option.Contains("datacheck"))
+    {
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+      fHGausHist.SetStats(0);
+    }
+  else
+  {
+      pad = oldpad;
+      pad->Divide(2,2);
+      pad->cd(1);
+  }
+
+  if (!IsEmpty() && !IsOnlyOverflow() && !IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  gPad->SetTicks();
+
+  fHGausHist.Draw(); 
+  if (fFGausFit )
+  {
+      fFGausFit->SetLineColor(kBlue);
+      fFGausFit->Draw("same");
+      if (!option.Contains("datacheck"))
+        {
+          TLine *line = new TLine(fSinglePheCut, 0., fSinglePheCut, 10.);
+          line->SetBit(kCanDelete);
+          line->SetLineColor(kBlue);
+          line->SetLineWidth(3);
+          line->DrawLine(fSinglePheCut, 0., fSinglePheCut, 2.);
+        }
+  }
+  
+  if (fSinglePheFit)
+  {    
+    fSinglePheFit->SetFillStyle(0);
+    fSinglePheFit->SetLineWidth(3);
+    fSinglePheFit->SetLineColor(IsSinglePheFitOK() ? kGreen : kRed);          
+    fSinglePheFit->Draw("same");
+  }
+
+  pad->cd(2);
+  DrawLegend(option.Data());
+
+  if (option.Contains("datacheck"))
+    return;
+
+  pad->cd(3);
+
+  if (fASinglePheFADCSlices.GetNrows()!=1)
+    {
+      if (fHSinglePheFADCSlices)
+        delete fHSinglePheFADCSlices;
+
+      fHSinglePheFADCSlices = new TH1F(fASinglePheFADCSlices);
+      fHSinglePheFADCSlices->SetName("SinglePheFADCSlices");
+      fHSinglePheFADCSlices->SetTitle(Form("%s%4.1f","Assumed Single Phe FADC Slices, Sum > ",fSinglePheCut));
+      fHSinglePheFADCSlices->SetXTitle("FADC slice number");
+      fHSinglePheFADCSlices->SetYTitle("FADC counts");
+      const Int_t nbins = fHSinglePheFADCSlices->GetNbinsX();
+      TH2D *nulls = new TH2D("Nulls",fHSinglePheFADCSlices->GetTitle(),nbins,0.,
+                            fHSinglePheFADCSlices->GetXaxis()->GetBinCenter(nbins),
+                            100,0.,50.);
+      nulls->SetDirectory(NULL);
+      nulls->SetBit(kCanDelete);
+      nulls->GetXaxis()->SetTitle(fHSinglePheFADCSlices->GetXaxis()->GetTitle());
+      nulls->GetYaxis()->SetTitle(fHSinglePheFADCSlices->GetYaxis()->GetTitle());  
+      nulls->GetXaxis()->CenterTitle();
+      nulls->GetYaxis()->CenterTitle();
+      nulls->SetStats(0);
+      nulls->Draw();
+      fHSinglePheFADCSlices->Draw("same");
+    }
+  
+  pad->cd(4);
+  if (fAPedestalFADCSlices.GetNrows()!=1)
+    {
+
+      if (fHPedestalFADCSlices)
+        delete fHPedestalFADCSlices;
+      
+      fHPedestalFADCSlices = new TH1F(fAPedestalFADCSlices);
+      fHPedestalFADCSlices->SetName("PedestalFADCSlices");
+      fHPedestalFADCSlices->SetTitle(Form("%s%4.1f","Pedestal FADC Slices, Sum < ",fSinglePheCut));
+      fHPedestalFADCSlices->SetXTitle("FADC slice number");
+      fHPedestalFADCSlices->SetYTitle("FADC counts");
+      const Int_t nbins = fHPedestalFADCSlices->GetNbinsX();
+      TH2D *nullp = new TH2D("Nullp",fHPedestalFADCSlices->GetTitle(),nbins,0.,
+                            fHPedestalFADCSlices->GetXaxis()->GetBinCenter(nbins),
+                            100,0.,50.);
+      nullp->SetDirectory(NULL);
+      nullp->SetBit(kCanDelete);
+      nullp->GetXaxis()->SetTitle(fHPedestalFADCSlices->GetXaxis()->GetTitle());
+      nullp->GetYaxis()->SetTitle(fHPedestalFADCSlices->GetYaxis()->GetTitle());  
+      nullp->GetXaxis()->CenterTitle();
+      nullp->GetYaxis()->CenterTitle();
+      nullp->SetStats(0);
+      nullp->Draw();
+      fHPedestalFADCSlices->Draw("same");
+    }
+  
+  if (win < 2)
+  return;
+
+  oldpad->cd(2);
+  MHCalibrationPix::Draw("fourierevents");
+}
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindPix.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargeBlindPix.h	(revision 9772)
@@ -0,0 +1,495 @@
+#ifndef MARS_MHCalibrationChargeBlindPix
+#define MARS_MHCalibrationChargeBlindPix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+#ifndef ROOT_TF1
+#include <TF1.h>
+#endif
+
+#ifndef ROOT_TVector
+#include <TVector.h>
+#endif
+
+class TH1F;
+class TPaveText;
+class TText;
+class MExtractedSignalBlindPixel;
+class MRawEvtPixelIter;
+
+class MHCalibrationChargeBlindPix : public MHCalibrationPix
+{
+private:
+
+  static const Float_t  fgNumSinglePheLimit; //! Default for fNumSinglePheLimit (now set to: 50)
+  static const Float_t  gkSignalInitializer; //! Signal initializer (-9999.)
+  
+  static const Double_t gkElectronicAmp;     // Electronic Amplification after the PMT (in FADC counts/N_e)
+  static const Double_t gkElectronicAmpErr;  // Error of the electronic amplification
+
+  Float_t fSinglePheCut;                     // Value of summed FADC slices upon which event considered as single-phe
+  Float_t fNumSinglePheLimit;                // Minimum number of single-phe events 
+
+  TVector fASinglePheFADCSlices;             //! Averaged FADC slice entries supposed single-phe events
+  TVector fAPedestalFADCSlices;              //! Averaged FADC slice entries supposed pedestal   events
+ 
+  TF1 *fSinglePheFit;                        // Single Phe Fit (Gaussians convoluted with Poisson) 
+
+  UInt_t  fNumSinglePhes;                    // Number of entries in fASinglePheFADCSlices 
+  UInt_t  fNumPedestals;                     // Number of entries in fAPedestalFADCSlices  
+
+  Double_t  fLambda;                         // Poisson mean from Single-phe fit 
+  Double_t  fLambdaCheck;                    // Poisson mean from Pedestal fit alone
+  Double_t  fMu0;                            // Mean of the pedestal
+  Double_t  fMu1;                            // Mean of single-phe peak
+  Double_t  fSigma0;                         // Sigma of the pedestal
+  Double_t  fSigma1;                         // Sigma of single-phe peak
+  Double_t  fLambdaErr;                      // Error of Poisson mean from Single-phe fit 
+  Double_t  fLambdaCheckErr;                 // Error of Poisson mean from Pedestal fit alone 
+  Double_t  fMu0Err;                         // Error of  Mean of the pedestal    
+  Double_t  fMu1Err;                         // Error of  Mean of single-phe peak 
+  Double_t  fSigma0Err;                      // Error of  Sigma of the pedestal   
+  Double_t  fSigma1Err;                      // Error of  Sigma of single-phe peak
+  Double_t  fChisquare;                      // Chisquare of single-phe fit 
+  Int_t     fNDF;                            // Ndof of single-phe fit 
+  Double_t  fProb;                           // Probability of singleo-phe fit
+				     
+  Byte_t    fFlags;                          // Bit-field for the flags
+  enum { kSinglePheFitOK, kPedestalFitOK };  // Possible bits to be set
+
+public:
+
+  enum FitFunc_t { kEPoisson4, kEPoisson5,
+                   kEPoisson6, kEPoisson7,
+                   kEPolya, kEMichele };    // Possible fit functions types 
+
+private:  
+
+  FitFunc_t fFitFunc;
+  
+  TPaveText *fFitLegend;                     //! Some legend to display the fit results
+  TH1F      *fHSinglePheFADCSlices;          // A histogram created and deleted only in Draw()
+  TH1F      *fHPedestalFADCSlices;           // A histogram created and deleted only in Draw()
+
+  // Fit
+  Bool_t InitFit();
+  void   ExitFit();  
+  
+  void DrawLegend(Option_t *opt="");
+  
+public:
+
+  MHCalibrationChargeBlindPix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeBlindPix();
+
+  void Clear(Option_t *o="");  
+  void Reset() {}
+  
+  // Getters
+  const Double_t GetLambda        ()  const { return fLambda;         }
+  const Double_t GetLambdaCheck   ()  const { return fLambdaCheck;    }
+  const Double_t GetMu0           ()  const { return fMu0;            }
+  const Double_t GetMu1           ()  const { return fMu1;            }
+  const Double_t GetSigma0        ()  const { return fSigma0;         }
+  const Double_t GetSigma1        ()  const { return fSigma1;         }
+  const Double_t GetLambdaErr     ()  const { return fLambdaErr;      }
+  const Double_t GetLambdaCheckErr()  const { return fLambdaCheckErr; }
+  const Double_t GetMu0Err        ()  const { return fMu0Err;         }
+  const Double_t GetMu1Err        ()  const { return fMu1Err;         }
+  const Double_t GetSigma0Err     ()  const { return fSigma0Err;      }
+  const Double_t GetSigma1Err     ()  const { return fSigma1Err;      }
+  const Float_t  GetSinglePheCut  ()  const { return fSinglePheCut;   }
+ 
+  TVector &GetASinglePheFADCSlices()             { return fASinglePheFADCSlices;  }
+  const TVector &GetASinglePheFADCSlices() const { return fASinglePheFADCSlices;  }
+
+  TVector &GetAPedestalFADCSlices()              { return fAPedestalFADCSlices;  }  
+  const TVector &GetAPedestalFADCSlices()  const { return fAPedestalFADCSlices;  }  
+
+  const Bool_t  IsSinglePheFitOK()         const;
+  const Bool_t  IsPedestalFitOK()          const;
+  
+  // Setters
+  void SetFitFunc        ( const FitFunc_t func )                   { fFitFunc = func;  }
+  void SetSinglePheCut      ( const Float_t cut = 0.               )    { fSinglePheCut      = cut;  }
+  void SetNumSinglePheLimit ( const Float_t lim =fgNumSinglePheLimit )    { fNumSinglePheLimit = lim;  }
+
+  void SetSinglePheFitOK    ( const Bool_t b=kTRUE);
+  void SetPedestalFitOK     ( const Bool_t b=kTRUE);
+  
+  // Fill histos
+  void  FillSinglePheFADCSlices(const MRawEvtPixelIter &iter);
+  void  FillPedestalFADCSlices( const MRawEvtPixelIter &iter);
+  void  FinalizeSinglePheSpectrum();
+  
+  // Draws
+  void Draw(Option_t *opt="");
+
+  // Fits
+  Bool_t FitSinglePhe (Option_t *opt="RL0+Q");
+  void   FitPedestal  (Option_t *opt="RL0+Q");
+
+  // Simulation
+  Bool_t SimulateSinglePhe(const Double_t lambda,
+                           const Double_t mu0,    const Double_t mu1,
+                           const Double_t sigma0, const Double_t sigma1);
+  
+private:
+
+  inline static Double_t fFitFuncMichele(Double_t *x, Double_t *par)
+    {
+      
+      Double_t lambda1cat = par[0];  
+      Double_t lambda1dyn = par[1];
+      Double_t mu0        = par[2];
+      Double_t mu1cat     = par[3];
+      Double_t mu1dyn     = par[4];
+      Double_t sigma0     = par[5];
+      Double_t sigma1cat  = par[6];
+      Double_t sigma1dyn  = par[7];
+      
+      Double_t sumcat = 0.;
+      Double_t sumdyn = 0.;
+      Double_t arg    = 0.;
+      
+      if (lambda1cat < lambda1dyn)
+        return FLT_MAX;
+
+      if (mu1cat    < mu0)
+        return FLT_MAX;
+
+      if (mu1dyn    < mu0)
+        return FLT_MAX;
+
+      if (mu1cat < mu1dyn)
+        return FLT_MAX;
+
+      if (sigma0 < 0.0001)
+        return FLT_MAX;
+      
+      if (sigma1cat < sigma0)
+        return FLT_MAX;
+
+      if (sigma1dyn < sigma0)
+        return FLT_MAX;
+
+      Double_t mu2cat = (2.*mu1cat)-mu0;  
+      Double_t mu2dyn = (2.*mu1dyn)-mu0;  
+      Double_t mu3cat = (3.*mu1cat)-(2.*mu0);
+      Double_t mu3dyn = (3.*mu1dyn)-(2.*mu0);
+      
+      Double_t sigma2cat = TMath::Sqrt((2.*sigma1cat*sigma1cat) - (sigma0*sigma0));  
+      Double_t sigma2dyn = TMath::Sqrt((2.*sigma1dyn*sigma1dyn) - (sigma0*sigma0));  
+      Double_t sigma3cat = TMath::Sqrt((3.*sigma1cat*sigma1cat) - (2.*sigma0*sigma0));
+      Double_t sigma3dyn = TMath::Sqrt((3.*sigma1dyn*sigma1dyn) - (2.*sigma0*sigma0));
+      
+      Double_t lambda2cat = lambda1cat*lambda1cat;
+      Double_t lambda2dyn = lambda1dyn*lambda1dyn;
+      Double_t lambda3cat = lambda2cat*lambda1cat;
+      Double_t lambda3dyn = lambda2dyn*lambda1dyn;
+
+     // k=0:
+      arg = (x[0] - mu0)/sigma0;
+      sumcat = TMath::Exp(-0.5*arg*arg)/sigma0;
+      sumdyn = sumcat;
+
+      // k=1cat:
+      arg = (x[0] - mu1cat)/sigma1cat;
+      sumcat += lambda1cat*TMath::Exp(-0.5*arg*arg)/sigma1cat;
+      // k=1dyn:
+      arg = (x[0] - mu1dyn)/sigma1dyn;
+      sumdyn += lambda1dyn*TMath::Exp(-0.5*arg*arg)/sigma1dyn;
+      
+      // k=2cat:
+      arg = (x[0] - mu2cat)/sigma2cat;
+      sumcat += 0.5*lambda2cat*TMath::Exp(-0.5*arg*arg)/sigma2cat;
+      // k=2dyn:
+      arg = (x[0] - mu2dyn)/sigma2dyn;
+      sumdyn += 0.5*lambda2dyn*TMath::Exp(-0.5*arg*arg)/sigma2dyn;
+  
+     
+      // k=3cat:
+      arg = (x[0] - mu3cat)/sigma3cat;
+      sumcat += 0.1666666667*lambda3cat*TMath::Exp(-0.5*arg*arg)/sigma3cat;
+      // k=3dyn:
+      arg = (x[0] - mu3dyn)/sigma3dyn;
+      sumdyn += 0.1666666667*lambda3dyn*TMath::Exp(-0.5*arg*arg)/sigma3dyn;  
+    
+      sumcat = TMath::Exp(-1.*lambda1cat)*sumcat;
+      sumdyn = TMath::Exp(-1.*lambda1dyn)*sumdyn;
+      
+      return par[8]*(sumcat+sumdyn)/2.;
+
+    }
+    
+  inline static Double_t fPoissonKto4(Double_t *x, Double_t *par)
+    {
+
+      Double_t lambda = par[0];  
+      
+      Double_t sum = 0.;
+      Double_t arg = 0.;
+      
+      Double_t mu0 = par[1];
+      Double_t mu1 = par[2];
+      
+      if (mu1 < mu0)
+        return FLT_MAX;
+
+      Double_t sigma0 = par[3];
+      Double_t sigma1 = par[4];
+
+      if (sigma0 < 0.0001)
+        return FLT_MAX;
+      
+      if (sigma1 < sigma0)
+        return FLT_MAX;
+      
+      Double_t mu2 = (2.*mu1)-mu0;  
+      Double_t mu3 = (3.*mu1)-(2.*mu0);
+      Double_t mu4 = (4.*mu1)-(3.*mu0);
+      
+      Double_t sigma2 = TMath::Sqrt((2.*sigma1*sigma1) - (sigma0*sigma0));  
+      Double_t sigma3 = TMath::Sqrt((3.*sigma1*sigma1) - (2.*sigma0*sigma0));
+      Double_t sigma4 = TMath::Sqrt((4.*sigma1*sigma1) - (3.*sigma0*sigma0));
+      
+      Double_t lambda2 = lambda*lambda;
+      Double_t lambda3 = lambda2*lambda;
+      Double_t lambda4 = lambda3*lambda;
+      
+      // k=0:
+      arg = (x[0] - mu0)/sigma0;
+      sum = TMath::Exp(-0.5*arg*arg)/sigma0;
+      
+      // k=1:
+      arg = (x[0] - mu1)/sigma1;
+      sum += lambda*TMath::Exp(-0.5*arg*arg)/sigma1;
+      
+      // k=2:
+      arg = (x[0] - mu2)/sigma2;
+      sum += 0.5*lambda2*TMath::Exp(-0.5*arg*arg)/sigma2;
+      
+      // k=3:
+      arg = (x[0] - mu3)/sigma3;
+      sum += 0.1666666667*lambda3*TMath::Exp(-0.5*arg*arg)/sigma3;
+      
+      // k=4:
+      arg = (x[0] - mu4)/sigma4;
+      sum += 0.041666666666667*lambda4*TMath::Exp(-0.5*arg*arg)/sigma4;
+      
+      return TMath::Exp(-1.*lambda)*par[5]*sum;
+      
+    } 
+
+  
+  inline static Double_t fPoissonKto5(Double_t *x, Double_t *par)
+    {
+      
+      Double_t lambda = par[0];  
+      
+      Double_t sum = 0.;
+      Double_t arg = 0.;
+      
+      Double_t mu0 = par[1];
+      Double_t mu1 = par[2];
+      
+      if (mu1 < mu0)
+        return FLT_MAX;
+      
+      Double_t sigma0 = par[3];
+      Double_t sigma1 = par[4];
+      
+      if (sigma0 < 0.0001)
+        return FLT_MAX;
+      
+      if (sigma1 < sigma0)
+        return FLT_MAX;
+      
+      
+      Double_t mu2 = (2.*mu1)-mu0;  
+      Double_t mu3 = (3.*mu1)-(2.*mu0);
+      Double_t mu4 = (4.*mu1)-(3.*mu0);
+      Double_t mu5 = (5.*mu1)-(4.*mu0);
+      
+      Double_t sigma2 = TMath::Sqrt((2.*sigma1*sigma1) - (sigma0*sigma0));  
+      Double_t sigma3 = TMath::Sqrt((3.*sigma1*sigma1) - (2.*sigma0*sigma0));
+      Double_t sigma4 = TMath::Sqrt((4.*sigma1*sigma1) - (3.*sigma0*sigma0));
+      Double_t sigma5 = TMath::Sqrt((5.*sigma1*sigma1) - (4.*sigma0*sigma0));
+      
+      Double_t lambda2 = lambda*lambda;
+      Double_t lambda3 = lambda2*lambda;
+      Double_t lambda4 = lambda3*lambda;
+      Double_t lambda5 = lambda4*lambda;
+      
+      // k=0:
+      arg = (x[0] - mu0)/sigma0;
+      sum = TMath::Exp(-0.5*arg*arg)/sigma0;
+      
+      // k=1:
+      arg = (x[0] - mu1)/sigma1;
+      sum += lambda*TMath::Exp(-0.5*arg*arg)/sigma1;
+      
+      // k=2:
+      arg = (x[0] - mu2)/sigma2;
+      sum += 0.5*lambda2*TMath::Exp(-0.5*arg*arg)/sigma2;
+      
+      // k=3:
+      arg = (x[0] - mu3)/sigma3;
+      sum += 0.1666666667*lambda3*TMath::Exp(-0.5*arg*arg)/sigma3;
+      
+      // k=4:
+      arg = (x[0] - mu4)/sigma4;
+      sum += 0.041666666666667*lambda4*TMath::Exp(-0.5*arg*arg)/sigma4;
+      
+      // k=5:
+      arg = (x[0] - mu5)/sigma5;
+      sum += 0.008333333333333*lambda5*TMath::Exp(-0.5*arg*arg)/sigma5;
+      
+      return TMath::Exp(-1.*lambda)*par[5]*sum;
+      
+    }
+  
+  
+  inline static Double_t fPoissonKto6(Double_t *x, Double_t *par)
+    {
+      
+      Double_t lambda = par[0];  
+      
+      Double_t sum = 0.;
+      Double_t arg = 0.;
+      
+      Double_t mu0 = par[1];
+      Double_t mu1 = par[2];
+      
+      if (mu1 < mu0)
+        return FLT_MAX;
+      
+      Double_t sigma0 = par[3];
+      Double_t sigma1 = par[4];
+      
+      if (sigma0 < 0.0001)
+        return FLT_MAX;
+      
+      if (sigma1 < sigma0)
+        return FLT_MAX;
+      
+      
+      Double_t mu2 = (2.*mu1)-mu0;  
+      Double_t mu3 = (3.*mu1)-(2.*mu0);
+      Double_t mu4 = (4.*mu1)-(3.*mu0);
+      Double_t mu5 = (5.*mu1)-(4.*mu0);
+      Double_t mu6 = (6.*mu1)-(5.*mu0);
+      
+      Double_t sigma2 = TMath::Sqrt((2.*sigma1*sigma1) - (sigma0*sigma0));  
+      Double_t sigma3 = TMath::Sqrt((3.*sigma1*sigma1) - (2.*sigma0*sigma0));
+      Double_t sigma4 = TMath::Sqrt((4.*sigma1*sigma1) - (3.*sigma0*sigma0));
+      Double_t sigma5 = TMath::Sqrt((5.*sigma1*sigma1) - (4.*sigma0*sigma0));
+      Double_t sigma6 = TMath::Sqrt((6.*sigma1*sigma1) - (5.*sigma0*sigma0));
+      
+      Double_t lambda2 = lambda*lambda;
+      Double_t lambda3 = lambda2*lambda;
+      Double_t lambda4 = lambda3*lambda;
+      Double_t lambda5 = lambda4*lambda;
+      Double_t lambda6 = lambda5*lambda;
+      
+      // k=0:
+      arg = (x[0] - mu0)/sigma0;
+      sum = TMath::Exp(-0.5*arg*arg)/sigma0;
+      
+      // k=1:
+      arg = (x[0] - mu1)/sigma1;
+      sum += lambda*TMath::Exp(-0.5*arg*arg)/sigma1;
+      
+      // k=2:
+      arg = (x[0] - mu2)/sigma2;
+      sum += 0.5*lambda2*TMath::Exp(-0.5*arg*arg)/sigma2;
+      
+      // k=3:
+      arg = (x[0] - mu3)/sigma3;
+      sum += 0.1666666667*lambda3*TMath::Exp(-0.5*arg*arg)/sigma3;
+      
+      // k=4:
+      arg = (x[0] - mu4)/sigma4;
+      sum += 0.041666666666667*lambda4*TMath::Exp(-0.5*arg*arg)/sigma4;
+      
+      // k=5:
+      arg = (x[0] - mu5)/sigma5;
+      sum += 0.008333333333333*lambda5*TMath::Exp(-0.5*arg*arg)/sigma5;
+      
+      // k=6:
+      arg = (x[0] - mu6)/sigma6;
+      sum += 0.001388888888889*lambda6*TMath::Exp(-0.5*arg*arg)/sigma6;
+      
+      return TMath::Exp(-1.*lambda)*par[5]*sum;
+      
+    }
+
+  inline static Double_t fPolya(Double_t *x, Double_t *par)
+    {
+
+      const Double_t QEcat = 0.247;            // mean quantum efficiency
+      const Double_t sqrt2 = 1.4142135623731;
+      const Double_t sqrt3 = 1.7320508075689;
+      const Double_t sqrt4 = 2.;
+      
+      const Double_t lambda = par[0];           // mean number of photons
+      
+      const Double_t excessPoisson = par[1];    // non-Poissonic noise contribution
+      const Double_t delta1 = par[2];           // amplification first dynode
+      const Double_t delta2 = par[3];           // amplification subsequent dynodes
+      
+      const Double_t electronicAmpl = par[4];   // electronic amplification and conversion to FADC charges
+
+      const Double_t pmtAmpl = delta1*delta2*delta2*delta2*delta2*delta2;  // total PMT gain
+      const Double_t A = 1. + excessPoisson - QEcat                        
+        + 1./delta1 
+                + 1./delta1/delta2
+        + 1./delta1/delta2/delta2;                                  // variance contributions from PMT and QE
+      
+      const Double_t totAmpl = QEcat*pmtAmpl*electronicAmpl;        // Total gain and conversion
+      
+      const Double_t mu0 = par[7];                                      // pedestal
+      const Double_t mu1 = totAmpl;                                 // single phe position
+      const Double_t mu2 = 2*totAmpl;                               // double phe position
+      const Double_t mu3 = 3*totAmpl;                               // triple phe position
+      const Double_t mu4 = 4*totAmpl;                               // quadruple phe position
+      
+      const Double_t sigma0 = par[5];
+      const Double_t sigma1 = electronicAmpl*pmtAmpl*TMath::Sqrt(QEcat*A);
+      const Double_t sigma2 = sqrt2*sigma1;
+      const Double_t sigma3 = sqrt3*sigma1;
+      const Double_t sigma4 = sqrt4*sigma1;
+      
+      const Double_t lambda2 = lambda*lambda;
+      const Double_t lambda3 = lambda2*lambda;
+      const Double_t lambda4 = lambda3*lambda;
+      
+      //-- calculate the area----
+      Double_t arg = (x[0] - mu0)/sigma0;
+      Double_t sum = TMath::Exp(-0.5*arg*arg)/sigma0;
+      
+     // k=1:
+      arg = (x[0] - mu1)/sigma1;
+      sum += lambda*TMath::Exp(-0.5*arg*arg)/sigma1;
+      
+      // k=2:
+      arg = (x[0] - mu2)/sigma2;
+      sum += 0.5*lambda2*TMath::Exp(-0.5*arg*arg)/sigma2;
+      
+      // k=3:
+      arg = (x[0] - mu3)/sigma3;
+      sum += 0.1666666667*lambda3*TMath::Exp(-0.5*arg*arg)/sigma3;
+      
+      // k=4:
+      arg = (x[0] - mu4)/sigma4;
+      sum += 0.041666666666667*lambda4*TMath::Exp(-0.5*arg*arg)/sigma4;      
+      
+      return TMath::Exp(-1.*lambda)*par[6]*sum;
+    }
+  
+  ClassDef(MHCalibrationChargeBlindPix, 1)  // Histogram class for Charge Blind Pixel Calibration
+};
+
+#endif  /* MARS_MHCalibrationChargeBlindPix */
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargeCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargeCam.cc	(revision 9772)
@@ -0,0 +1,1423 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHCalibrationChargeCam                                               
+//
+// Fills the extracted signals of MExtractedSignalCam into the MHCalibrationPix-classes 
+// MHCalibrationChargeHiGainPix and MHCalibrationChargeLoGainPix for every:
+//
+// - Pixel, stored in the TOrdCollection's MHCalibrationCam::fHiGainArray and 
+//   MHCalibrationCam::fLoGainArray
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TOrdCollection's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageLoGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TOrdCollection's MHCalibrationCam::fAverageHiGainSectors and 
+//   MHCalibrationCam::fAverageLoGainSectors
+// 
+// Every signal is taken from MExtractedSignalCam and filled into a histogram and 
+// an array, in order to perform a Fourier analysis (see MHGausEvents). 
+// The signals are moreover averaged on an event-by-event basis and written into 
+// the corresponding average pixels.
+//
+// Additionally, the (FADC slice) position of the maximum is stored in an Absolute 
+// Arrival Time histogram. This histogram serves for a rough cross-check if the 
+// signal does not lie at or outside the edges of the extraction window. 
+//
+// The Charge histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted ) or  
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted ) and 
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun   ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// Unless more than fNumHiGainSaturationLimit (default: 1%) of the overall FADC 
+// slices show saturation, the following flag is set:
+// - MCalibrationChargePix::SetHiGainSaturation();
+// In that case, the calibration constants are derived from the low-gain results.
+//
+// If more than fNumLoGainSaturationLimit (default: 1%) of the overall 
+// low-gain FADC slices saturate, the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturation ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    )
+// 
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum and investigates if the projected fourier components follow an exponential 
+// distribution. In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating ) or
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun     )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MCalibrationChargeCam:
+//
+// - MCalibrationPix::SetHiGainSaturation() 
+// - MCalibrationPix::SetHiGainMean()
+// - MCalibrationPix::SetHiGainMeanErr()
+// - MCalibrationPix::SetHiGainSigma()
+// - MCalibrationPix::SetHiGainSigmaErr()
+// - MCalibrationPix::SetHiGainProb()
+// - MCalibrationPix::SetHiGainNumPickup()
+//
+// - MCalibrationPix::SetLoGainMean()
+// - MCalibrationPix::SetLoGainMeanErr()
+// - MCalibrationPix::SetLoGainSigma()
+// - MCalibrationPix::SetLoGainSigmaErr()
+// - MCalibrationPix::SetLoGainProb()
+// - MCalibrationPix::SetLoGainNumPickup()
+//
+// - MCalibrationChargePix::SetAbsTimeMean()
+// - MCalibrationChargePix::SetAbsTimeRms()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MHCalibrationChargePix.h"
+#include "MHCalibrationPix.h"
+
+#include "MCalibrationIntensityCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MRawEvtData.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MArrayI.h"
+#include "MArrayD.h"
+
+#include <TOrdCollection.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TF1.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TGraph.h>
+#include <TEnv.h>
+
+ClassImp(MHCalibrationChargeCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationChargeCam::fgChargeHiGainNbins =  500;
+const Axis_t  MHCalibrationChargeCam::fgChargeHiGainFirst = -100.125;
+const Axis_t  MHCalibrationChargeCam::fgChargeHiGainLast  =  1899.875;
+const Int_t   MHCalibrationChargeCam::fgChargeLoGainNbins =  500;
+const Axis_t  MHCalibrationChargeCam::fgChargeLoGainFirst = -100.25;
+const Axis_t  MHCalibrationChargeCam::fgChargeLoGainLast  =  899.75;
+const Float_t MHCalibrationChargeCam::fgProbLimit         = 0.00000001;
+const TString MHCalibrationChargeCam::gsHistName          = "Charge";
+const TString MHCalibrationChargeCam::gsHistTitle         = "Signals";
+const TString MHCalibrationChargeCam::gsHistXTitle        = "Signal [FADC counts]";
+const TString MHCalibrationChargeCam::gsHistYTitle        = "Nr. events";
+const TString MHCalibrationChargeCam::gsAbsHistName       = "AbsTime";
+const TString MHCalibrationChargeCam::gsAbsHistTitle      = "Abs. Arr. Times";
+const TString MHCalibrationChargeCam::gsAbsHistXTitle     = "Time [FADC slices]";
+const TString MHCalibrationChargeCam::gsAbsHistYTitle     = "Nr. events";
+const Float_t MHCalibrationChargeCam::fgNumHiGainSaturationLimit = 0.05;
+const Float_t MHCalibrationChargeCam::fgNumLoGainSaturationLimit = 0.005;
+const Float_t MHCalibrationChargeCam::fgTimeLowerLimit           = 1.;
+const Float_t MHCalibrationChargeCam::fgTimeUpperLimit           = 3.;
+const TString MHCalibrationChargeCam::fgReferenceFile = "mjobs/calibrationref.rc";
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// Initializes:
+// - fNumHiGainSaturationLimit to fgNumHiGainSaturationLimit
+// - fNumLoGainSaturationLimit to fgNumLoGainSaturationLimit
+// - fTimeLowerLimit           to fgTimeLowerLimit 
+// - fTimeUpperLimit           to fgTimeUpperLimit 
+//
+// - fNbins to fgChargeHiGainNbins
+// - fFirst to fgChargeHiGainFirst
+// - fLast  to fgChargeHiGainLast 
+//
+// - fLoGainNbins to fgChargeLoGainNbins
+// - fLoGainFirst to fgChargeLoGainFirst
+// - fLoGainLast  to fgChargeLoGainLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - fAbsHistName   to gsAbsHistName  
+// - fAbsHistTitle  to gsAbsHistTitle 
+// - fAbsHistXTitle to gsAbsHistXTitle
+// - fAbsHistYTitle to gsAbsHistYTitle
+//
+MHCalibrationChargeCam::MHCalibrationChargeCam(const char *name, const char *title)
+    : fRawEvt(NULL)
+{
+
+  fName  = name  ? name  : "MHCalibrationChargeCam";
+  fTitle = title ? title : "Class to fill the calibration histograms ";
+  
+  SetNumHiGainSaturationLimit(fgNumHiGainSaturationLimit);
+  SetNumLoGainSaturationLimit(fgNumLoGainSaturationLimit);
+
+  SetTimeLowerLimit();
+  SetTimeUpperLimit();
+
+  SetNbins(fgChargeHiGainNbins);
+  SetFirst(fgChargeHiGainFirst);
+  SetLast (fgChargeHiGainLast );
+
+  SetProbLimit(fgProbLimit);
+
+  SetLoGainNbins(fgChargeLoGainNbins);
+  SetLoGainFirst(fgChargeLoGainFirst);
+  SetLoGainLast (fgChargeLoGainLast );
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetAbsHistName  (gsAbsHistName  .Data());
+  SetAbsHistTitle (gsAbsHistTitle .Data());
+  SetAbsHistXTitle(gsAbsHistXTitle.Data());
+  SetAbsHistYTitle(gsAbsHistYTitle.Data());
+
+  SetReferenceFile();
+
+  fInnerRefCharge = 278.;
+  fOuterRefCharge = 282.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationChargeCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHCalibrationChargeCam *cam = MParList::FindObject("MHCalibrationChargeCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHCalibrationChargeCam::Clone(const char *) const
+{
+
+  MHCalibrationChargeCam *cam = new MHCalibrationChargeCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fColor                  = fColor;
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+  cam->fLoGainNbins            = fLoGainNbins;
+  cam->fLoGainFirst            = fLoGainFirst;
+  cam->fLoGainLast             = fLoGainLast;
+  cam->fReferenceFile          = fReferenceFile;
+
+  //
+  // Copy the MArrays
+  //
+  cam->fAverageAreaRelSigma    = fAverageAreaRelSigma;
+  cam->fAverageAreaRelSigmaVar = fAverageAreaRelSigmaVar;
+  cam->fAverageAreaSat         = fAverageAreaSat;
+  cam->fAverageAreaSigma       = fAverageAreaSigma;
+  cam->fAverageAreaSigmaVar    = fAverageAreaSigmaVar;
+  cam->fAverageAreaNum         = fAverageAreaNum;
+  cam->fAverageSectorNum       = fAverageSectorNum;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  if (IsLoGain())
+    {
+      
+      const Int_t navlo = fAverageLoGainAreas->GetSize();
+      for (int i=0; i<navlo; i++)
+        cam->fAverageLoGainAreas->AddAt(GetAverageLoGainArea(i).Clone(),i);
+
+    }
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MRawEvtData
+//
+Bool_t MHCalibrationChargeCam::SetupHists(const MParList *pList)
+{
+
+  fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+  if (!fRawEvt)
+  {
+      *fLog << err << dbginf << "MRawEvtData not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MExtractedSignalCam
+// - MCalibrationChargeCam or MCalibrationIntensityChargeCam
+// - MBadPixelsCam
+//
+// Initializes the number of used FADC slices from MExtractedSignalCam 
+// into MCalibrationChargeCam and test for changes in that variable
+//
+// Calls:
+// - InitHiGainArrays()
+// - InitLoGainArrays()
+// 
+// Sets:
+// - fSumhiarea   to nareas 
+// - fSumloarea   to nareas 
+// - fTimehiarea  to nareas 
+// - fTimeloarea  to nareas
+// - fSumhisector to nsectors 
+// - fSumlosector to nsectors 
+// - fTimehisector to nsectors 
+// - fTimelosector to nsectors
+// - fSathiarea   to nareas 
+// - fSatloarea   to nareas
+// - fSathisector to nsectors 
+// - fSatlosector to nsectors
+//
+Bool_t MHCalibrationChargeCam::ReInitHists(MParList *pList)
+{
+
+  MExtractedSignalCam *signal = 
+    (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+  if (!signal)
+  {
+      *fLog << err << "MExtractedSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  if (!InitCams(pList,"Charge"))
+    return kFALSE;
+
+  fFirstHiGain = signal->GetFirstUsedSliceHiGain();
+  fLastHiGain  = signal->GetLastUsedSliceHiGain();
+  fFirstLoGain = signal->GetFirstUsedSliceLoGain();
+  fLastLoGain  = signal->GetLastUsedSliceLoGain();
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  //
+  // In case of the intense blue, double the range
+  //
+  if (fGeom->InheritsFrom("MGeomCamMagic"))
+    if ( fColor == MCalibrationCam::kBLUE)
+      SetLoGainLast(2.*fLoGainLast - fLoGainFirst);
+  
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  fSumhiarea  .Set(nareas); 
+  fSumloarea  .Set(nareas); 
+  fTimehiarea .Set(nareas); 
+  fTimeloarea .Set(nareas);
+  fSumhisector.Set(nsectors); 
+  fSumlosector.Set(nsectors); 
+  fTimehisector.Set(nsectors); 
+  fTimelosector.Set(nsectors);
+
+  fSathiarea  .Set(nareas); 
+  fSatloarea  .Set(nareas);
+  fSathisector.Set(nsectors); 
+  fSatlosector.Set(nsectors);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieve:
+// - fRunHeader->GetNumSamplesHiGain();
+//
+// Initializes the High Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationChargePix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Binning of Abs Times histogram from  fAbsNbins, fAbsFirst and fAbsLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set Abs Times Histgram names and titles from fAbsHistName and fAbsHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Set X-axis and Y-axis titles of Abs Times Histogram from fAbsHistXTitle and fAbsHistYTitle
+//   * Call InitHists
+//
+//
+void MHCalibrationChargeCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+  
+  MBadPixelsCam *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  TH1F *h;
+
+  const Int_t higainsamples = fRunHeader->GetNumSamplesHiGain();
+
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationChargePix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                       Form("%s High Gain Pixel%04d",fHistTitle.Data(),i)),i);
+
+        MHCalibrationChargePix &pix = (MHCalibrationChargePix&)(*this)[i];
+
+        pix.SetNbins(fNbins);
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+
+        pix.SetProbLimit(fProbLimit);
+
+        pix.SetAbsTimeNbins(higainsamples);
+        pix.SetAbsTimeFirst(-0.5);
+        pix.SetAbsTimeLast(higainsamples-0.5);
+
+        InitHists(pix,(*badcam)[i],i);
+
+        h = pix.GetHAbsTime();
+
+        h->SetName (Form("H%sHiGainPix%04d",fAbsHistName.Data(),i));
+        h->SetTitle(Form("%s High Gain Pixel %04d",fAbsHistTitle.Data(),i));
+        h->SetXTitle(fAbsHistXTitle.Data());
+        h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHCalibrationChargePix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                  Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationChargePix &pix = (MHCalibrationChargePix&)GetAverageHiGainArea(j);
+        
+        pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+        
+        pix.SetAbsTimeNbins(higainsamples);
+        pix.SetAbsTimeFirst(-0.5);
+        pix.SetAbsTimeLast(higainsamples-0.5);
+
+        InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadArea(j) : fCam->GetAverageBadArea(j),j);
+
+        h =  pix.GetHAbsTime();
+        
+        h->SetName (Form("H%sHiGainArea%d",fAbsHistName.Data(),j));
+        h->SetTitle(Form("%s%s%d",fAbsHistTitle.Data(),
+                         " averaged on event-by-event basis High Gain Area Idx ",j));
+        h->SetXTitle(fAbsHistXTitle.Data());
+        h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+  
+  if (fAverageHiGainSectors->GetSize()==0)
+  {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+	  fAverageHiGainSectors->AddAt(new MHCalibrationChargePix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                      Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+
+          MHCalibrationChargePix &pix = (MHCalibrationChargePix&)GetAverageHiGainSector(j);
+
+          pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+          pix.SetFirst(fFirst);
+          pix.SetLast (fLast);
+
+          pix.SetAbsTimeNbins(higainsamples);
+          pix.SetAbsTimeFirst(-0.5);
+          pix.SetAbsTimeLast(higainsamples-0.5);
+          
+          InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadSector(j) : fCam->GetAverageBadSector(j),j);
+
+          h =  pix.GetHAbsTime();
+          
+          h->SetName (Form("H%sHiGainSector%02d",fAbsHistName.Data(),j));
+          h->SetTitle(Form("%s%s%02d",fAbsHistTitle.Data(),
+                           " averaged on event-by-event basis High Gain Area Sector ",j));
+          h->SetXTitle(fAbsHistXTitle.Data());
+          h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+}
+
+//--------------------------------------------------------------------------------------
+//
+// Return, if IsLoGain() is kFALSE 
+//
+// Retrieve:
+// - fRunHeader->GetNumSamplesHiGain();
+//
+// Initializes the Low Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationChargePix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Binning of Abs Times histogram from  fAbsNbins, fAbsFirst and fAbsLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set Abs Times Histgram names and titles from fAbsHistName and fAbsHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Set X-axis and Y-axis titles of Abs Times Histogram from fAbsHistXTitle and fAbsHistYTitle
+//   * Call InitHists
+//
+void MHCalibrationChargeCam::InitLoGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+
+  if (!IsLoGain())
+    return;
+
+
+  MBadPixelsCam *badcam    = fIntensBad 
+    ? (MBadPixelsCam*)        fIntensBad->GetCam()  : fBadPixels;
+
+  const Int_t logainsamples = fRunHeader->GetNumSamplesLoGain();
+
+  TH1F *h;
+
+  if (fLoGainArray->GetSize()==0 )
+    {
+      for (Int_t i=0; i<npixels; i++)
+        {
+          fLoGainArray->AddAt(new MHCalibrationChargePix(Form("%sLoGainPix%04d",fHistName.Data(),i),
+                                       Form("%s Low Gain Pixel %04d",fHistTitle.Data(),i)),i);
+
+          MHCalibrationChargePix &pix = (MHCalibrationChargePix&)(*this)(i);
+
+          pix.SetNbins(fLoGainNbins);
+          pix.SetFirst(fLoGainFirst);
+          pix.SetLast (fLoGainLast);
+          
+          pix.SetProbLimit(fProbLimit);
+
+          pix.SetAbsTimeNbins(logainsamples);
+          pix.SetAbsTimeFirst(-0.5);
+          pix.SetAbsTimeLast(logainsamples-0.5);
+          
+          InitHists(pix,(*badcam)[i],i);
+
+          h = pix.GetHAbsTime();
+          
+          h->SetName (Form("H%sLoGainPix%04d",fAbsHistName.Data(),i));
+          h->SetTitle(Form("%s Low Gain Pixel %04d",fAbsHistTitle.Data(),i));
+          h->SetXTitle(fAbsHistXTitle.Data());
+          h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+
+  if (fAverageLoGainAreas->GetSize()==0)
+    {
+      for (Int_t j=0; j<nareas; j++)
+        {
+	  fAverageLoGainAreas->AddAt(new MHCalibrationChargePix(Form("%sLoGainArea%d",fHistName.Data(),j),
+                                       Form("%s Low Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+          MHCalibrationChargePix &pix = (MHCalibrationChargePix&)GetAverageLoGainArea(j);
+          
+          pix.SetNbins(fLoGainNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+          pix.SetFirst(fLoGainFirst);
+          pix.SetLast (fLoGainLast);
+          
+          pix.SetAbsTimeNbins(logainsamples);
+          pix.SetAbsTimeFirst(-0.5);
+          pix.SetAbsTimeLast(logainsamples-0.5);
+          
+          InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadArea(j) : fCam->GetAverageBadArea(j),j);
+
+          h =  pix.GetHAbsTime();
+          
+          h->SetName (Form("H%sLoGainArea%02d",fAbsHistName.Data(),j));
+          h->SetTitle(Form("%s%s%02d",fAbsHistTitle.Data(),
+                           " averaged on event-by-event basis Low Gain Area Idx ",j));
+          h->SetXTitle(fAbsHistXTitle.Data());
+          h->SetYTitle(fAbsHistYTitle.Data());
+        }
+    }
+  
+
+  if (fAverageLoGainSectors->GetSize()==0 && IsLoGain())
+  {
+    for (Int_t j=0; j<nsectors; j++)
+      {
+        fAverageLoGainSectors->AddAt(new MHCalibrationChargePix(Form("%sLoGainSector%02d",fHistName.Data(),j),
+                                                        Form("%s Low Gain Sector %02d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationChargePix &pix = (MHCalibrationChargePix&)GetAverageLoGainSector(j);
+        
+        pix.SetNbins(fLoGainNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+        pix.SetFirst(fLoGainFirst);
+        pix.SetLast (fLoGainLast);
+        
+        pix.SetAbsTimeNbins(logainsamples);
+        pix.SetAbsTimeFirst(-0.5);
+        pix.SetAbsTimeLast(logainsamples-0.5);
+        
+        InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadSector(j) : fCam->GetAverageBadSector(j),j);
+
+        h =  pix.GetHAbsTime();
+        
+        h->SetName (Form("H%sLoGainSector%02d",fAbsHistName.Data(),j));
+        h->SetTitle(Form("%s%s%02d",fAbsHistTitle.Data(),
+                           " averaged on event-by-event basis Low Gain Area Sector ",j));
+        h->SetXTitle(fAbsHistXTitle.Data());
+        h->SetYTitle(fAbsHistYTitle.Data());
+      }
+  }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalCam:
+// - first used LoGain FADC slice
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// For all TOrdCollection's (including the averaged ones), the following steps are performed: 
+//
+// 1) Fill Charges histograms (MHGausEvents::FillHistAndArray()) with:
+// - MExtractedSignalPix::GetExtractedSignalHiGain();
+// - MExtractedSignalPix::GetExtractedSignalLoGain();
+//
+// 2) Set number of saturated slices (MHCalibrationChargePix::AddSaturated()) with:
+// - MExtractedSignalPix::GetNumHiGainSaturated();
+// - MExtractedSignalPix::GetNumLoGainSaturated();
+//
+// 3) Fill AbsTime histograms (MHCalibrationChargePix::FillAbsTime()) with:
+// - MRawEvtPixelIter::GetIdxMaxHiGainSample();       
+// - MRawEvtPixelIter::GetIdxMaxLoGainSample(first slice);
+//
+Bool_t MHCalibrationChargeCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)par;
+  if (!signal)
+    {
+      *fLog << err << "No argument in MExtractedSignalCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+  const UInt_t lofirst  = signal->GetFirstUsedSliceLoGain();
+
+  fSumhiarea  .Reset(); 
+  fSumloarea  .Reset(); 
+  fTimehiarea .Reset(); 
+  fTimeloarea .Reset();
+  fSumhisector.Reset(); 
+  fSumlosector.Reset(); 
+  fTimehisector.Reset(); 
+  fTimelosector.Reset();
+
+  fSathiarea  .Reset(); 
+  fSatloarea  .Reset();
+  fSathisector.Reset(); 
+  fSatlosector.Reset();
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[i];
+
+      if (histhi.IsExcluded())
+	continue;
+
+      const MExtractedSignalPix &pix = (*signal)[i];
+      
+      const Float_t sumhi = pix.GetExtractedSignalHiGain();
+      const Int_t   sathi = (Int_t)pix.GetNumHiGainSaturated();
+
+      if (IsOscillations())
+        histhi.FillHistAndArray(sumhi);
+      else
+        histhi.FillHist(sumhi);
+        
+      histhi.AddSaturated(sathi); 
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      fSumhiarea[aidx]  += sumhi;
+      fSathiarea[aidx]  += sathi;
+
+      fSumhisector[sector]  += sumhi;
+      fSathisector[sector]  += sathi;
+
+      if (IsLoGain())
+        {
+          MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(i);
+          const Float_t sumlo  = pix.GetExtractedSignalLoGain();
+          const Int_t   satlo = (Int_t)pix.GetNumLoGainSaturated();
+          
+          if (IsOscillations())
+            histlo.FillHistAndArray(sumlo);
+          else
+            histlo.FillHist(sumlo);
+          
+          histlo.AddSaturated(satlo); 
+          
+          fSumloarea[aidx]  += sumlo;
+          fSatloarea[aidx]  += satlo;
+          fSumlosector[sector]  += sumlo;
+          fSatlosector[sector]  += satlo;
+        }
+      
+    }
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  while (pixel.Next())
+    {
+      
+      const UInt_t pixid = pixel.GetPixelId();
+
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[pixid];
+
+      if (histhi.IsExcluded())
+         continue;
+      
+      const Float_t timehi = (Float_t)pixel.GetIdxMaxHiGainSample();
+
+      histhi.FillAbsTime(timehi);
+
+      const Int_t aidx   = (*fGeom)[pixid].GetAidx();
+      const Int_t sector = (*fGeom)[pixid].GetSector();
+
+      fTimehiarea  [aidx]   += timehi;
+      fTimehisector[sector] += timehi;
+
+      if (IsLoGain())
+        {
+          MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(pixid);
+
+          const Float_t timelo = (Float_t)pixel.GetIdxMaxLoGainSample(lofirst);
+          histlo.FillAbsTime(timelo);
+
+          fTimeloarea[aidx] += timelo;
+          fTimelosector[sector] += timelo;
+        }
+    }
+  
+  for (UInt_t j=0; j<nareas; j++)
+    {
+
+      const Int_t npix = fAverageAreaNum[j];
+
+      if (npix == 0)
+        continue;
+
+      MHCalibrationChargePix &hipix = (MHCalibrationChargePix&)GetAverageHiGainArea(j);
+      
+
+      if (IsOscillations())
+        hipix.FillHistAndArray(fSumhiarea [j]/npix);
+      else
+        hipix.FillHist(fSumhiarea[j]/npix);
+      
+      hipix.AddSaturated    ((Float_t)fSathiarea [j]/npix > 0.5 ? 1 : 0); 
+      hipix.FillAbsTime     (fTimehiarea[j]/npix);
+
+      if (IsLoGain())
+        {
+          MHCalibrationChargePix &lopix = (MHCalibrationChargePix&)GetAverageLoGainArea(j);
+          if (IsOscillations())
+            lopix.FillHistAndArray(fSumloarea [j]/npix);
+          else
+            lopix.FillHist(fSumloarea [j]/npix);
+          lopix.AddSaturated    ((Float_t)fSatloarea [j]/npix > 0.5 ? 1 : 0); 
+          lopix.FillAbsTime     (fTimeloarea[j]/npix);
+        }
+    }
+
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+
+      const Int_t npix = fAverageSectorNum[j];
+
+      if (npix == 0)
+        continue;
+
+      MHCalibrationChargePix &hipix = (MHCalibrationChargePix&)GetAverageHiGainSector(j);
+
+      if (IsOscillations())      
+        hipix.FillHistAndArray(fSumhisector [j]/npix);
+      else
+        hipix.FillHist(fSumhisector [j]/npix);
+
+      hipix.AddSaturated    ((Float_t)fSathisector[j]/npix > 0.5 ? 1 : 0); 
+      hipix.FillAbsTime     (fTimehisector[j]/npix);
+
+      if (IsLoGain())
+        {
+          MHCalibrationChargePix &lopix = (MHCalibrationChargePix&)GetAverageLoGainSector(j);
+
+          if (IsOscillations())      
+            lopix.FillHistAndArray(fSumlosector [j]/npix);
+          else
+            lopix.FillHist(fSumlosector [j]/npix);
+            
+          lopix.AddSaturated    ((Float_t)fSatlosector[j]/npix > 0.5 ? 1 : 0); 
+          lopix.FillAbsTime     (fTimelosector[j]/npix);
+        }
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For all TOrdCollection's (including the averaged ones), the following steps are performed: 
+//
+// 1) Returns if the pixel is excluded.
+// 2) Tests saturation. In case yes, set the flag: MCalibrationPix::SetHiGainSaturation()
+//    or the flag: MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturated )
+// 3) Store the absolute arrival times in the MCalibrationChargePix's. If flag 
+//    MCalibrationPix::IsHiGainSaturation() is set, the Low-Gain arrival times are stored, 
+//    otherwise the Hi-Gain ones.
+// 4) Calls to MHCalibrationCam::FitHiGainArrays() and MCalibrationCam::FitLoGainArrays() 
+//    with the flags:
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating )
+//
+Bool_t MHCalibrationChargeCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  TH1F *h = NULL;
+
+  MCalibrationCam *chargecam = fIntensCam ? fIntensCam->GetCam() : fCam;
+  MBadPixelsCam   *badcam    = fIntensBad ? fIntensBad->GetCam() : fBadPixels;
+
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[i];
+      
+      if (histhi.IsExcluded())
+	continue;
+
+      MCalibrationChargePix  &pix = (MCalibrationChargePix&)(*chargecam)[i] ;
+
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          if (IsOscillations())
+            histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      MBadPixelsPix &bad = (*badcam)[i];
+
+      h = histhi.GetHGausHist();
+
+      Stat_t overflow = h->GetBinContent(h->GetNbinsX()+1);
+      if (overflow > fOverflowLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          *fLog << warn
+                << "HiGain Hist-overflow " << overflow
+                << " times in: " << histhi.GetName() << " (w/o saturation!) " << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kHiGainOverFlow ); 
+        }
+
+      overflow = h->GetBinContent(0);
+      if (overflow >  fOverflowLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          *fLog << warn
+                << "HiGain Hist-underflow " << overflow
+                << " times in pix: " << histhi.GetName() << " (w/o saturation!) " << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kHiGainOverFlow ); 
+        }
+      
+      FinalizeAbsTimes(histhi, pix, bad, fFirstHiGain, fLastHiGain);
+    }
+
+  if (IsLoGain())
+    for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+      {
+        
+        MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(i);
+        MBadPixelsPix          &bad    = (*badcam)[i];
+        
+        if (histlo.IsExcluded())
+	  continue;
+
+        if (histlo.GetSaturated() > fNumLoGainSaturationLimit*histlo.GetHGausHist()->GetEntries())
+          {
+            *fLog << warn << "Saturated Lo Gain histogram in pixel: " << i << endl;
+            bad.SetUncalibrated( MBadPixelsPix::kLoGainSaturation ); 
+            if (IsOscillations())
+              histlo.CreateFourierSpectrum();
+            continue;
+          }
+        
+        h = histlo.GetHGausHist();
+
+        Stat_t overflow = h->GetBinContent(h->GetNbinsX()+1);
+        if (overflow >  fOverflowLimit*histlo.GetHGausHist()->GetEntries())
+          {
+              *fLog << warn
+                  << "LoGain Hist-overflow " << overflow
+                  << " times in: " << histlo.GetName() << " (w/o saturation!) " << endl;
+            bad.SetUncalibrated( MBadPixelsPix::kLoGainOverFlow ); 
+          }
+
+        overflow = h->GetBinContent(0);
+        if (overflow > fOverflowLimit*histlo.GetHGausHist()->GetEntries())
+          {
+            *fLog << warn
+                  << "LoGain Hist-underflow " << overflow
+                  << " times in: " << histlo.GetName() << " (w/o saturation!) " << endl;
+            bad.SetUncalibrated( MBadPixelsPix::kLoGainOverFlow ); 
+          }
+        
+        MCalibrationChargePix  &pix    = (MCalibrationChargePix&)(*chargecam)[i] ;
+        
+        if (pix.IsHiGainSaturation())
+          FinalizeAbsTimes(histlo, pix, bad, fFirstLoGain, fLastLoGain);
+      }
+
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)GetAverageHiGainArea(j);      
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)chargecam->GetAverageArea(j);
+
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          if (IsOscillations())
+            histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      MBadPixelsPix &bad = chargecam->GetAverageBadArea(j);
+      FinalizeAbsTimes(histhi, pix, bad, fFirstHiGain, fLastHiGain);
+   }
+
+  if (IsLoGain())
+    for (Int_t j=0; j<fAverageLoGainAreas->GetSize(); j++)
+      {
+        
+        MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)GetAverageLoGainArea(j);      
+
+        if (histlo.GetSaturated() > fNumLoGainSaturationLimit*histlo.GetHGausHist()->GetEntries())
+          {
+            *fLog << warn << "Saturated Lo Gain histogram in area idx: " << j << endl;
+            histlo.CreateFourierSpectrum();
+            continue;
+          }
+        
+        MCalibrationChargePix  &pix    = (MCalibrationChargePix&)chargecam->GetAverageArea(j);
+
+        if (pix.IsHiGainSaturation())
+          {
+            MBadPixelsPix &bad = chargecam->GetAverageBadArea(j);
+            FinalizeAbsTimes(histlo, pix, bad, fFirstLoGain, fLastLoGain);
+          }
+        
+      }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)GetAverageHiGainSector(j);      
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)chargecam->GetAverageSector(j);
+
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          if (IsOscillations())
+            histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      MBadPixelsPix &bad = chargecam->GetAverageBadSector(j);
+      FinalizeAbsTimes(histhi, pix, bad, fFirstHiGain, fLastHiGain);
+    }
+  
+  if (IsLoGain())
+    for (Int_t j=0; j<fAverageLoGainSectors->GetSize(); j++)
+      {
+        
+        MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)GetAverageLoGainSector(j);      
+        MBadPixelsPix          &bad    = chargecam->GetAverageBadSector(j);
+        
+        if (histlo.GetSaturated() > fNumLoGainSaturationLimit*histlo.GetHGausHist()->GetEntries())
+          {
+            *fLog << warn << "Saturated Lo Gain histogram in sector: " << j << endl;
+            bad.SetUncalibrated( MBadPixelsPix::kLoGainSaturation ); 
+            if (IsOscillations())
+              histlo.CreateFourierSpectrum();
+            continue;
+          }
+        
+        MCalibrationChargePix  &pix    = (MCalibrationChargePix&)chargecam->GetAverageSector(j);
+
+        if (pix.IsHiGainSaturation())
+          FinalizeAbsTimes(histlo, pix, bad, fFirstLoGain, fLastLoGain);
+      }
+  
+  //
+  // Perform the fitting for the High Gain (done in MHCalibrationCam)
+  //
+  FitHiGainArrays(*chargecam, *badcam, 
+                  MBadPixelsPix::kHiGainNotFitted,
+                  MBadPixelsPix::kHiGainOscillating);
+  
+  //
+  // Perform the fitting for the Low Gain (done in MHCalibrationCam)
+  //
+  if (IsLoGain())
+    FitLoGainArrays(*chargecam, *badcam, 
+                    MBadPixelsPix::kLoGainNotFitted,
+                    MBadPixelsPix::kLoGainOscillating);
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------------
+//
+// Fill the absolute time results into MCalibrationChargePix
+//
+// Check absolute time validity:
+// - Mean arrival time is at least fTimeLowerLimit slices from the lower edge 
+// - Mean arrival time is at least fUpperLimit     slices from the upper edge
+//
+void MHCalibrationChargeCam::FinalizeAbsTimes(MHCalibrationChargePix &hist, MCalibrationChargePix &pix, MBadPixelsPix &bad, 
+                                              Byte_t first, Byte_t last)
+{
+  
+  const Float_t mean = hist.GetAbsTimeMean();
+  const Float_t rms  = hist.GetAbsTimeRms();
+
+  pix.SetAbsTimeMean ( mean );
+  pix.SetAbsTimeRms  ( rms  );
+  
+  const Float_t lowerlimit = (Float_t)first + fTimeLowerLimit;
+  const Float_t upperlimit = (Float_t)last  - fTimeUpperLimit;  
+
+  if ( mean < lowerlimit)
+    {
+      *fLog << warn
+            << Form("Mean ArrivalTime: %3.1f < %2.1f slices from lower edge: %2i in pixel %s",
+                    mean,fTimeLowerLimit,(Int_t)first,hist.GetName()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kMeanTimeInFirstBin );
+    }
+  
+  if ( mean  > upperlimit )
+    {
+      *fLog << warn
+            << Form("Mean ArrivalTime: %3.1f > %2.1f slices from upper edge: %2i in pixel %s",
+                    mean,fTimeUpperLimit,(Int_t)last,hist.GetName()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kMeanTimeInLast2Bins );
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets all pixels to MBadPixelsPix::kUnsuitableRun, if following flags are set:
+// - MBadPixelsPix::kLoGainSaturation
+//
+// Sets all pixels to MBadPixelsPix::kUnreliableRun, if following flags are set:
+// - if MBadPixelsPix::kHiGainNotFitted   and !MCalibrationPix::IsHiGainSaturation()
+// - if MBadPixelsPix::kHiGainOscillating and !MCalibrationPix::IsHiGainSaturation()
+// - if MBadPixelsPix::kLoGainNotFitted   and  MCalibrationPix::IsLoGainSaturation()
+// - if MBadPixelsPix::kLoGainOscillating and  MCalibrationPix::IsLoGainSaturation()
+//
+void MHCalibrationChargeCam::FinalizeBadPixels()
+{
+
+  MBadPixelsCam   *badcam    = fIntensBad ? fIntensBad->GetCam() : fBadPixels;
+  MCalibrationCam *chargecam = fIntensCam ? fIntensCam->GetCam() : fCam;
+      
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      
+      MBadPixelsPix    &bad    = (*badcam)[i];
+      MCalibrationPix  &pix    = (*chargecam)[i];
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kHiGainNotFitted ))
+        if (!pix.IsHiGainSaturation())
+          bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+ 
+      if (bad.IsUncalibrated( MBadPixelsPix::kLoGainNotFitted ))
+        if (pix.IsHiGainSaturation())
+          bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kLoGainSaturation ))
+          bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+
+      if (IsOscillations())
+        {
+          if (bad.IsUncalibrated( MBadPixelsPix::kHiGainOscillating ))
+            bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+          
+          if (bad.IsUncalibrated( MBadPixelsPix::kLoGainOscillating ))
+            if (pix.IsHiGainSaturation())
+              bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+        }
+    }
+
+
+      
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationChargeCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationChargeCam::Draw(const Option_t *opt)
+{
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TString option(opt);
+  option.ToLower();
+
+  if (!option.Contains("datacheck"))
+    {
+      MHCalibrationCam::Draw(opt);
+      return;
+    }
+
+  // 
+  // From here on , the datacheck - Draw
+  //
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+  pad->Divide(1,nareas);
+
+  //
+  // Loop over inner and outer pixels
+  //  
+  for (Int_t i=0; i<nareas;i++) 
+     {
+       
+       pad->cd(i+1);
+       
+       MHCalibrationChargePix &hipix = (MHCalibrationChargePix&)GetAverageHiGainArea(i);
+       //
+       // Ask for Hi-Gain saturation
+       //
+       if (hipix.GetSaturated() > fNumHiGainSaturationLimit*hipix.GetHGausHist()->GetEntries() && IsLoGain())
+         {
+           MHCalibrationChargePix &lopix = (MHCalibrationChargePix&)GetAverageLoGainArea(i);
+           DrawDataCheckPixel(lopix,i ? fOuterRefCharge : fInnerRefCharge);
+         }
+       else
+         DrawDataCheckPixel(hipix,i ? fOuterRefCharge : fInnerRefCharge);
+
+    }      
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Draw the average pixel for the datacheck:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationChargeCam::DrawDataCheckPixel(MHCalibrationChargePix &pix, const Float_t refline)
+{
+  
+  TVirtualPad *newpad = gPad;
+  newpad->Divide(1,2);
+  newpad->cd(1);
+  
+  gPad->SetTicks();
+  if (!pix.IsEmpty() && !pix.IsOnlyOverflow() && !pix.IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  TH1F *hist = pix.GetHGausHist();
+
+  TH1F *null = new TH1F("Null",hist->GetTitle(),100,
+                        pix.GetFirst() > 0. ? pix.GetFirst() : 0.,
+                        pix.GetLast() > pix.GetFirst()
+                        ? ( pix.GetLast() > 450. 
+                            ? ( fColor == MCalibrationCam::kBLUE ? 800. : 450. )
+                            : pix.GetLast() )
+                        : pix.GetFirst()*2.);
+
+  null->SetMaximum(1.1*hist->GetMaximum());
+  null->SetDirectory(NULL);
+  null->SetBit(kCanDelete);
+  null->SetStats(kFALSE);
+  //
+  // set the labels bigger
+  //
+  TAxis *xaxe = null->GetXaxis();
+  TAxis *yaxe = null->GetYaxis();
+  xaxe->CenterTitle();
+  yaxe->CenterTitle();    
+  xaxe->SetTitleSize(0.07);
+  yaxe->SetTitleSize(0.07);    
+  xaxe->SetTitleOffset(0.7);
+  yaxe->SetTitleOffset(0.55);    
+  xaxe->SetLabelSize(0.06);
+  yaxe->SetLabelSize(0.06);    
+  xaxe->SetTitle(hist->GetXaxis()->GetTitle());
+  yaxe->SetTitle(hist->GetYaxis()->GetTitle());  
+
+  null->Draw();
+  hist->Draw("same");
+
+  gStyle->SetOptFit();
+
+  TF1 *fit = pix.GetFGausFit();
+
+  if (fit)
+  {
+    switch ( fColor )
+      {
+      case MCalibrationCam::kGREEN:
+        fit->SetLineColor(kGreen);
+        break;
+      case MCalibrationCam::kBLUE:
+        fit->SetLineColor(kBlue);
+        break;
+      case MCalibrationCam::kUV:  
+        fit->SetLineColor(106);
+        break;
+      case MCalibrationCam::kCT1: 
+        fit->SetLineColor(006);
+        break;
+      default:
+        fit->SetLineColor(kRed);
+      }
+    fit->Draw("same");
+  }
+
+  DisplayRefLines(null,refline);
+
+  newpad->cd(2);
+  gPad->SetTicks();
+
+  TH1F *null2 = new TH1F("Null2",hist->GetTitle(),100,0.,pix.GetEvents()->GetSize()/pix.GetEventFrequency());
+
+  null2->SetMinimum(pix.GetMean()-10.*pix.GetSigma());
+  null2->SetMaximum(pix.GetMean()+10.*pix.GetSigma());
+  null2->SetDirectory(NULL);
+  null2->SetBit(kCanDelete);
+  null2->SetStats(kFALSE);
+  //
+  // set the labels bigger
+  //
+  TAxis *xaxe2 = null2->GetXaxis();
+  TAxis *yaxe2 = null2->GetYaxis();
+  xaxe2->CenterTitle();
+  yaxe2->CenterTitle();    
+  xaxe2->SetTitleSize(0.07);
+  yaxe2->SetTitleSize(0.07);    
+  xaxe2->SetTitleOffset(0.7);
+  yaxe2->SetTitleOffset(0.55);    
+  xaxe2->SetLabelSize(0.06);
+  yaxe2->SetLabelSize(0.06);    
+
+  pix.CreateGraphEvents();
+  TGraph *gr = pix.GetGraphEvents();
+
+  xaxe2->SetTitle(gr->GetXaxis()->GetTitle());
+  yaxe2->SetTitle(gr->GetYaxis()->GetTitle());  
+
+  null2->Draw();
+
+  pix.DrawEvents("same");
+
+  //  newpad->cd(3);
+  //  pix.DrawPowerSpectrum(*newpad,4);
+
+  return;
+  
+}
+
+
+void  MHCalibrationChargeCam::DisplayRefLines(const TH1F *hist, const Float_t refline) const
+{
+
+  TGraph *uv10    = new TGraph(2);
+  uv10->SetPoint(0,refline,0.);
+  uv10->SetPoint(1,refline,hist->GetMaximum());
+  uv10->SetBit(kCanDelete);
+  uv10->SetLineColor(106);
+  uv10->SetLineStyle(2);
+  uv10->SetLineWidth(3);
+  uv10->Draw("L");
+
+  TLegend *leg = new TLegend(0.8,0.55,0.99,0.99);
+  leg->SetBit(kCanDelete);
+  leg->AddEntry(uv10,"10 Leds UV","l");
+
+  leg->Draw();
+}
+
+Int_t MHCalibrationChargeCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (MHCalibrationCam::ReadEnv(env,prefix,print))
+    rc = kTRUE;
+   
+  if (IsEnvDefined(env, prefix, "HiGainNbins", print))
+    {
+      SetNbins(GetEnvValue(env, prefix, "HiGainNbins", fNbins));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "HiGainFirst", print))
+    {
+      SetFirst(GetEnvValue(env, prefix, "HiGainFirst", fFirst));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "HiGainLast", print))
+    {
+      SetLast(GetEnvValue(env, prefix, "HiGainLast", fLast));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "LoGainNbins", print))
+    {
+      SetLoGainNbins(GetEnvValue(env, prefix, "LoGainNbins", fLoGainNbins));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "LoGainFirst", print))
+    {
+      SetLoGainFirst(GetEnvValue(env, prefix, "LoGainFirst", fLoGainFirst));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "LoGainLast", print))
+    {
+      SetLoGainLast(GetEnvValue(env, prefix, "LoGainLast", fLoGainLast));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "TimeLowerLimit", print))
+    {
+      SetTimeLowerLimit(GetEnvValue(env, prefix, "TimeLowerLimit", fTimeLowerLimit));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "TimeUpperLimit", print))
+    {
+      SetTimeUpperLimit(GetEnvValue(env, prefix, "TimeUpperLimit", fTimeUpperLimit));
+      rc = kTRUE;
+    }
+   
+  if (IsEnvDefined(env, prefix, "ReferenceFile", print))
+    {
+      SetReferenceFile(GetEnvValue(env,prefix,"ReferenceFile",fReferenceFile.Data()));
+      rc = kTRUE;
+    }
+
+  TEnv refenv(fReferenceFile);
+
+  fInnerRefCharge = refenv.GetValue("InnerRefCharge",fInnerRefCharge);
+  fOuterRefCharge = refenv.GetValue("OuterRefCharge",fOuterRefCharge);
+
+  return rc;
+}
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargeCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargeCam.h	(revision 9772)
@@ -0,0 +1,137 @@
+#ifndef MARS_MHCalibrationChargeCam
+#define MARS_MHCalibrationChargeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TH1F;
+class MRawEvtData;
+class MExtractedSignalCam;
+class MCalibrationChargePix;
+class MHCalibrationChargePix;
+
+class MHCalibrationChargeCam : public MHCalibrationCam
+{
+private:
+
+  static const Int_t   fgChargeHiGainNbins;          //! Nr. bins of HiGain Histograms  (now set to:  550  )
+  static const Axis_t  fgChargeHiGainFirst;          //! First Bin of HiGain Histograms (now set to: -100.5)
+  static const Axis_t  fgChargeHiGainLast;           //! Last Bin of HiGain Histograms  (now set to:  999.5)
+  static const Int_t   fgChargeLoGainNbins;          //! First Bin of LoGain Histograms (now set to:  325  )
+  static const Axis_t  fgChargeLoGainFirst;          //! First Bin of LoGain Histograms (now set to: -150.5)
+  static const Axis_t  fgChargeLoGainLast;           //! Last Bin of LoGain Histograms  (now set to:  499.5)
+  static const Float_t fgProbLimit;                  //! The default for fProbLimit    (now set to: 0.00001)
+  
+  static const TString fgReferenceFile;              //! default for fReferenceFile ("mjobs/calibrationref.rc")
+
+  static const TString gsHistName;                   //! Default Histogram names
+  static const TString gsHistTitle;                  //! Default Histogram titles
+  static const TString gsHistXTitle;                 //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;                 //! Default Histogram y-axis titles
+  
+  static const TString gsAbsHistName;                //! Default Histogram names abs.times
+  static const TString gsAbsHistTitle;               //! Default Histogram titles abs.times
+  static const TString gsAbsHistXTitle;              //! Default Histogram x-axis titles abs.times
+  static const TString gsAbsHistYTitle;              //! Default Histogram y-axis titles abs.times
+  
+  static const Float_t fgNumHiGainSaturationLimit;   //! The default for fNumHiGainSaturationLimit (now at: 0.01)
+  static const Float_t fgNumLoGainSaturationLimit;   //! The default for fNumLoGainSaturationLimit (now at: 0.005)
+
+  static const Float_t fgTimeLowerLimit;             //! Default for fTimeLowerLimit    (now set to: 1.) 
+  static const Float_t fgTimeUpperLimit;             //! Default for fTimeUpperLimit    (now set to: 2.)
+  
+  Int_t   fLoGainNbins;                              // Number of LoGain bins        
+  Axis_t  fLoGainFirst;                              // Lower histogram limit low gain
+  Axis_t  fLoGainLast;                               // Upper histogram limit low gain  
+
+  TString fAbsHistName;                              // Histogram names abs.times
+  TString fAbsHistTitle;                             // Histogram titles abs. times
+  TString fAbsHistXTitle;                            // Histogram x-axis titles abs. times
+  TString fAbsHistYTitle;                            // Histogram y-axis titles abs. times
+  
+  TString fReferenceFile;                            // File name containing the reference values
+
+  Float_t fInnerRefCharge;                           // The reference mean arrival time inner pixels
+  Float_t fOuterRefCharge;                           // The reference mean arrival time outer pixels
+
+  MArrayD fSumhiarea  ;                              //!
+  MArrayD fSumloarea  ;                              //!
+  MArrayD fTimehiarea ;                              //!
+  MArrayD fTimeloarea ;                              //!
+  MArrayD fSumhisector;                              //!
+  MArrayD fSumlosector;                              //!
+  MArrayD fTimehisector;                             //!
+  MArrayD fTimelosector;                             //!
+
+  MArrayI fSathiarea  ;                              //!
+  MArrayI fSatloarea  ;                              //!
+  MArrayI fSathisector;                              //!
+  MArrayI fSatlosector;                              //!
+
+  Float_t fTimeLowerLimit;                           // Limit dist. to first signal slice (in units of FADC slices) 
+  Float_t fTimeUpperLimit;                           // Limit dist. to last signal slice  (in units of FADC slices) 
+  Byte_t  fFirstHiGain;                              // First used slice High Gain 
+  Byte_t  fLastHiGain;                               // Last used slice High Gain
+  Byte_t  fFirstLoGain;                              // First used slice Low Gain
+  Byte_t  fLastLoGain;                               // Last used slice Low Gain
+  
+  MRawEvtData         *fRawEvt;                      //!  Raw event data 
+
+  Bool_t SetupHists(const MParList *pList);
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+
+  void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+  void   InitLoGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+
+  void   FinalizeAbsTimes (MHCalibrationChargePix &hist, MCalibrationChargePix &pix, MBadPixelsPix &bad,
+                           Byte_t first, Byte_t last);  
+  Bool_t FinalizeHists();
+  void   FinalizeBadPixels();
+
+  void   DrawDataCheckPixel(MHCalibrationChargePix &pix, const Float_t refline);
+  void   DisplayRefLines   ( const TH1F *hist,           const Float_t refline) const;
+
+  Int_t ReadEnv        ( const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MHCalibrationChargeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeCam() {}
+  
+  // Clone
+  TObject *Clone(const char *name="") const;
+
+  // Draw
+  void   Draw(const Option_t *opt);
+
+  void SetAbsHistName   ( const char *name )  { fAbsHistName   = name; }
+  void SetAbsHistTitle  ( const char *name )  { fAbsHistTitle  = name; }
+  void SetAbsHistXTitle ( const char *name )  { fAbsHistXTitle = name; }
+  void SetAbsHistYTitle ( const char *name )  { fAbsHistYTitle = name; }
+   
+  void SetLoGainNbins   ( const Int_t  i )    { fLoGainNbins   = i; }
+  void SetLoGainFirst   ( const Axis_t f )    { fLoGainFirst   = f; }
+  void SetLoGainLast    ( const Axis_t f )    { fLoGainLast    = f; }  
+
+  void SetReferenceFile ( const TString ref=fgReferenceFile ) { fReferenceFile  = ref; }
+
+  void SetTimeLowerLimit( const Float_t f=fgTimeLowerLimit )  { fTimeLowerLimit = f; }
+  void SetTimeUpperLimit( const Float_t f=fgTimeUpperLimit )  { fTimeUpperLimit = f; }
+  
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const { return kTRUE; }
+  void   DrawPixelContent( Int_t num )  const;    
+
+  ClassDef(MHCalibrationChargeCam, 1)	// Histogram class for Charge Camera Calibration 
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargePINDiode.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargePINDiode.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargePINDiode.cc	(revision 9772)
@@ -0,0 +1,424 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationChargePINDiode
+//
+//  Histogram class for the charge calibration of the PIN Diode. 
+//  Stores and fits the charges, the RMS of the charges  and stores the 
+//  location of the maximum FADC slice. Charges are taken from MExtractedSignalPINDiode.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargePINDiode.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MExtractedSignalPINDiode.h"
+#include "MCalibrationChargePINDiode.h"
+
+ClassImp(MHCalibrationChargePINDiode);
+
+using namespace std;
+
+const Axis_t  MHCalibrationChargePINDiode::fgAbsTimeFirst    = -0.5;
+const Axis_t  MHCalibrationChargePINDiode::fgAbsTimeLast     = 29.5;
+const Int_t   MHCalibrationChargePINDiode::fgAbsTimeNbins    = 30;
+const Axis_t  MHCalibrationChargePINDiode::fgChargeFirst     = -0.5;
+const Axis_t  MHCalibrationChargePINDiode::fgChargeLast      = 1999.5;
+const Int_t   MHCalibrationChargePINDiode::fgChargeNbins     = 2000;
+const Int_t   MHCalibrationChargePINDiode::fgRmsChargeNbins  = 200;
+const Axis_t  MHCalibrationChargePINDiode::fgRmsChargeFirst  = 0.;
+const Axis_t  MHCalibrationChargePINDiode::fgRmsChargeLast   = 200.;  
+const Float_t MHCalibrationChargePINDiode::fgTimeLowerLimit  = 3.;
+const Float_t MHCalibrationChargePINDiode::fgTimeUpperLimit  = 4.;
+const TString MHCalibrationChargePINDiode::gsHistName          = "Charge";
+const TString MHCalibrationChargePINDiode::gsHistTitle         = "Signals";
+const TString MHCalibrationChargePINDiode::gsHistXTitle        = "Signal [FADC counts]";
+const TString MHCalibrationChargePINDiode::gsHistYTitle        = "Nr. events";
+const TString MHCalibrationChargePINDiode::gsAbsHistName       = "AbsTime";
+const TString MHCalibrationChargePINDiode::gsAbsHistTitle      = "Abs. Arr. Times";
+const TString MHCalibrationChargePINDiode::gsAbsHistXTitle     = "Time [FADC slices]";
+const TString MHCalibrationChargePINDiode::gsAbsHistYTitle     = "Nr. events";
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fAbsTimeFirst        (fgAbsTimeFirst)
+// - the default number for fAbsTimeLast         (fgAbsTimeLast)
+// - the default number for fAbsTimeNbins        (fgAbsTimeNbins)
+// - the default number for MHGausEvents::fNbins (fgChargeNbins)
+// - the default number for MHGausEvents::fFirst (fgChargeFirst)
+// - the default number for MHGausEvents::fLast  (fgChargeLast)
+// - the default number for fRmsChargeNbins      (fgRmsChargeNbins)
+// - the default number for fRmsChargeFirst      (fgRmsChargeFirst)
+// - the default number for fRmsChargeLast       (fgRmsChargeLast)
+// - the default number for fTimeLowerLimit      (fgTimeLowerLimit)
+// - the default number for fTimeUpperLimit      (fgTimeUpperLimit)
+//
+// - the default name of the  fHGausHist      ("HCalibrationChargePINDiode")
+// - the default title of the fHGausHist      ("Distribution of Summed FADC slices PIN Diode")
+// - the default x-axis title for fHGausHist  ("Sum FADC Slices")
+// - the default y-axis title for fHGausHist  ("Nr. of events")
+// - the default name of the  fHAbsTime       ("HAbsTimePINDiode")
+// - the default title of the fHAbsTime       ("Distribution of Absolute Arrival Times PIN Diode")
+// - the default x-axis title for fHAbsTime   ("Absolute Arrival Time [FADC slice nr]")
+// - the default y-axis title for fHAbsTime   ("Nr. of events")
+// - the default name of the  fHRmsCharge     ("HRmsChargePINDiode")
+// - the default title of the fHRmsCharge     ("Distribution of Variances of summed FADC slices PIN Diode")
+// - the default x-axis title for fHRmsCharge ("RMS (sum) [FADC slices]")
+// - the default y-axis title for fHRmsCharge ("Nr. of events")
+// - the default directory of the fHRmsCharge (NULL)
+// - the current style for fHRmsCharge (NULL)
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - fAbsHistName   to gsAbsHistName  
+// - fAbsHistTitle  to gsAbsHistTitle 
+// - fAbsHistXTitle to gsAbsHistXTitle
+// - fAbsHistYTitle to gsAbsHistYTitle
+//
+// Initializes:
+// - fHRmsCharge()
+// - all pointers to NULL
+//
+// Calls:
+// - Clear()
+//
+MHCalibrationChargePINDiode::MHCalibrationChargePINDiode(const char *name, const char *title)
+    : fPINDiode(NULL), fSigPIN(NULL), fHRmsCharge()
+{
+
+  fName  = name  ? name  : "MHCalibrationChargePINDiode";
+  fTitle = title ? title : "Fill the FADC sums of the PINDiode events and perform the fits";
+  
+  SetAbsTimeFirst();
+  SetAbsTimeLast();
+  SetAbsTimeNbins();
+
+  SetNbins( fgChargeNbins );
+  SetFirst( fgChargeFirst );
+  SetLast ( fgChargeLast  );
+  
+  SetRmsChargeNbins();
+  SetRmsChargeFirst();
+  SetRmsChargeLast();
+  
+  SetTimeLowerLimit();
+  SetTimeUpperLimit();
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetAbsHistName  (gsAbsHistName  .Data());
+  SetAbsHistTitle (gsAbsHistTitle .Data());
+  SetAbsHistXTitle(gsAbsHistXTitle.Data());
+  SetAbsHistYTitle(gsAbsHistYTitle.Data());
+
+  fHRmsCharge.SetName("HRmsChargePINDiode");
+  fHRmsCharge.SetTitle("Distribution of Variances of summed FADC slices PIN Diode");  
+  fHRmsCharge.SetXTitle("RMS (sum) [FADC slices]");
+  fHRmsCharge.SetYTitle("Nr. of events");
+  fHRmsCharge.UseCurrentStyle();
+  fHRmsCharge.SetDirectory(NULL); 
+
+  Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes Binning of the following histograms:
+// - fHGausHist.SetBins(fNbins,fFirst,fLast);
+// - fHAbsTime.SetBins(fAbsTimeNbins,fAbsTimeFirst,fAbsTimeLast);
+// - fHRmsCharge.SetBins(fRmsChargeNbins,fRmsChargeFirst,fRmsChargeLast);
+//
+Bool_t MHCalibrationChargePINDiode::SetupFill(const MParList *pList) 
+{
+
+  TH1F *h = GetHGausHist();
+
+  h->SetName (fHistName.Data());
+  h->SetTitle(fHistTitle.Data());  
+  h->SetXTitle(fHistXTitle.Data());
+  h->SetYTitle(fHistYTitle.Data());
+  
+  h = GetHAbsTime();
+
+  h->SetName (fAbsHistName.Data());
+  h->SetTitle(fAbsHistTitle.Data());
+  h->SetXTitle(fAbsHistXTitle.Data());
+  h->SetYTitle(fAbsHistYTitle.Data());
+  
+  MHCalibrationPix::InitBins();
+
+  fHAbsTime.  SetBins(fAbsTimeNbins,  fAbsTimeFirst,  fAbsTimeLast);
+  fHRmsCharge.SetBins(fRmsChargeNbins,fRmsChargeFirst,fRmsChargeLast);
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MExtractedSignalPINDiode
+// - MCalibrationChargePINDiode
+//
+Bool_t MHCalibrationChargePINDiode::ReInit(MParList *pList)
+{
+  
+  fSigPIN = (MExtractedSignalPINDiode*)pList->FindCreateObj("MExtractedSignalPINDiode");
+  if (!fSigPIN)
+      return kFALSE;
+
+  fPINDiode = (MCalibrationChargePINDiode*)pList->FindCreateObj("MCalibrationChargePINDiode");
+  if (!fPINDiode)
+      return kFALSE;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalPINDiode:
+// - Number of used FADC samples via MExtractedSignalPINDiode::GetNumFADCSamples()
+// - Extracted signal via            MExtractedSignalPINDiode::GetExtractedSignal()
+// - Signal Rms                      MExtractedSignalPINDiode::GetExtractedRms()
+// - Arrival Time                    MExtractedSignalPINDiode::GetExtractedTime()
+//
+// Fills the following histograms:
+// - MHGausEvents::FillHistAndArray(signal)
+// - MHCalibrationChargePix::FillAbsTime(time);
+// - FillRmsCharge(rms);
+//
+Bool_t MHCalibrationChargePINDiode::Fill(const MParContainer *par, const Stat_t w)
+{
+
+  MExtractedSignalPINDiode *extractor = (MExtractedSignalPINDiode*)par;
+  
+  if (!extractor)
+    {
+      *fLog << err << "No argument in MExtractedSignalPINDiode::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  Float_t slices = (Float_t)extractor->GetNumFADCSamples();
+  
+  if (slices == 0.)
+    {
+      *fLog << err << "Number of used signal slices in MExtractedSignalPINDiode is zero  ... abort." 
+            << endl;
+      return kFALSE;
+    }
+  
+  const Float_t signal = (float)extractor->GetExtractedSignal();
+  const Float_t time   = extractor->GetExtractedTime();
+  const Float_t rms    = extractor->GetExtractedRms();
+
+  FillHistAndArray(signal);
+  FillAbsTime(time);
+  FillRmsCharge(rms);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns kTRUE, if empty
+//
+// Performs the following fits:
+// - MHGausEvents::FitGaus()
+// - FitRmsCharge()
+//
+// Creates the fourier spectrum (MHGausEvents::CreateFourierSpectrum() 
+// and sets bit MCalibrationChargePINDiode::SetOscillating( MHGausEvents::IsFourierSpectrumOK() )
+// Retrieves the results of the following fits and stores them in MCalibrationChargePINDiode:
+// - Mean Charge and Error 
+// - Sigma Charge and Error
+// - Fit Probability
+// - Abs Time Mean
+// - Abs Time Rms
+// - Rms Charge Mean and Error
+// - Rms Charge Sigma and Error
+// 
+// Performs one consistency check on the arrival time: 
+// The check returns kFALSE if:
+//
+// -The mean arrival time is in fTimeLowerLimit slices from the lower edge 
+//  and fUpperLimit slices from the upper edge
+//
+Bool_t MHCalibrationChargePINDiode::Finalize() 
+{
+  
+  if (IsGausFitOK() || IsEmpty())
+    return kTRUE;
+    
+  FitGaus();
+  FitRmsCharge();
+
+  CreateFourierSpectrum();
+  fPINDiode->SetOscillating  ( !IsFourierSpectrumOK() );
+
+  fPINDiode->SetMean     (  fMean     );
+  fPINDiode->SetMeanVar  (  fMeanErr  * fMeanErr );
+  fPINDiode->SetSigma    (  fSigma    );
+  fPINDiode->SetSigmaVar (  fSigmaErr * fMeanErr );
+  fPINDiode->SetProb     (  fProb     );
+
+  fPINDiode->SetAbsTimeMean(    GetAbsTimeMean() );
+  fPINDiode->SetAbsTimeRms(     GetAbsTimeRms()  );
+
+  fPINDiode->SetRmsChargeMean(     GetRmsChargeMean()        );
+  fPINDiode->SetRmsChargeMeanErr(  GetRmsChargeMeanErr()     );
+  fPINDiode->SetRmsChargeSigma(    GetRmsChargeSigma()       );
+  fPINDiode->SetRmsChargeSigmaErr( GetRmsChargeSigmaErr()    );
+
+  fPINDiode->SetValid(kTRUE);
+
+  const Byte_t  loweredge  = fSigPIN->GetFirstUsedSlice();
+  const Byte_t  upperedge  = fSigPIN->GetLastUsedSlice();
+  const Float_t lowerlimit = (Float_t)loweredge + fTimeLowerLimit;
+  const Float_t upperlimit = (Float_t)upperedge + fTimeUpperLimit;  
+
+  if (GetAbsTimeMean() < lowerlimit)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%3.1f%s%2.1f%s",": Mean ArrivalTime: ",GetAbsTimeMean()," smaller than ",
+                    lowerlimit," FADC slices from lower edge in PIN Diode") << endl;
+      *fLog << warn << GetDescriptor() << ": No PIN Diode calibration!! " << endl;
+      fPINDiode->SetValid(kFALSE);
+    }
+  
+  if ( GetAbsTimeMean() > upperlimit )
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%3.1f%s%2.1f%s",": Mean ArrivalTime: ",GetAbsTimeMean()," bigger than ",
+                    upperlimit," FADC slices from upper edge in PIN Diode") << endl;
+      *fLog << warn << GetDescriptor() << ": No PIN Diode calibration!! " << endl;
+      fPINDiode->SetValid(kFALSE);
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills fHRmsCharge with q
+// Returns kFALSE, if overflow or underflow occurred, else kTRUE
+//
+Bool_t MHCalibrationChargePINDiode::FillRmsCharge(const Float_t q)
+{
+  return fHRmsCharge.Fill(q) > -1;
+}
+
+// -----------------------------------------------------------
+//
+// Fits -- not yet implemented
+//
+Bool_t MHCalibrationChargePINDiode::FitRmsCharge(Option_t *option)
+{
+  return 1;
+}
+
+
+// -------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+// The following options can be chosen:
+//
+// "": displays the fHGausHist with fits and fHRmsCharge
+// "all": executes additionally MHCalibrationPix::Draw(), with option "fourierevents"
+//
+void MHCalibrationChargePINDiode::Draw(const Option_t *opt)
+{
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win = 1;
+
+  TVirtualPad *oldpad = gPad ? gPad : MH::MakeDefCanvas(this,900, 600);
+  TVirtualPad *pad    = NULL;
+
+  oldpad->SetBorderMode(0);
+    
+  if (option.Contains("all"))
+  {
+      option.ReplaceAll("all","");
+      oldpad->Divide(2,1);
+      win = 2;
+      oldpad->cd(1);
+      TVirtualPad *newpad = gPad;
+      pad = newpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+  else
+  {
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+
+  if (IsEmpty())
+    return;
+
+  if (!IsOnlyOverflow() && !IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  gPad->SetTicks();
+
+  fHGausHist.Draw(opt); 
+  if (fFGausFit)
+  {
+      fFGausFit->SetLineColor(IsGausFitOK() ? kGreen : kRed);
+      fFGausFit->Draw("same");
+  }
+
+  pad->cd(2);
+  fHRmsCharge.Draw(opt);
+
+  oldpad->cd(2);
+  MHCalibrationPix::Draw("fourierevents");
+}
+
+
+
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargePINDiode.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargePINDiode.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargePINDiode.h	(revision 9772)
@@ -0,0 +1,114 @@
+#ifndef MARS_MHCalibrationChargePINDiode
+#define MARS_MHCalibrationChargePINDiode
+
+
+#ifndef MARS_MHCalibrationChargePix
+#include "MHCalibrationChargePix.h"
+#endif
+
+class TH1F;
+class MExtractedSignalPINDiode;
+class MCalibrationChargePINDiode;
+class MHCalibrationChargePINDiode : public MHCalibrationChargePix
+{
+private:
+
+  static const Axis_t  fgAbsTimeFirst;    //! Default for fAbsTimeFirst    (now set to: -0.5  )
+  static const Axis_t  fgAbsTimeLast;     //! Default for fAbsTimeLast     (now set to: 29.5  )
+  static const Int_t   fgAbsTimeNbins;    //! Default for fAbsTimeNBins    (now set to: 30    )
+  static const Int_t   fgChargeNbins;     //! Default for fNBins           (now set to: 200   )
+  static const Axis_t  fgChargeFirst;     //! Default for fFirst           (now set to: -0.5  )
+  static const Axis_t  fgChargeLast;      //! Default for fLast            (now set to: 199.5 )
+  static const Int_t   fgRmsChargeNbins;  //! Default for fRmsChargeNBins  (now set to: 100   )
+  static const Axis_t  fgRmsChargeFirst;  //! Default for fRmsChargeFirst  (now set to: 0.    )
+  static const Axis_t  fgRmsChargeLast;   //! Default for fRmsChargeLast   (now set to: 100.  )
+  static const Float_t fgTimeLowerLimit;  //! Default for fTimeLowerLimit    (now set to: 1.) 
+  static const Float_t fgTimeUpperLimit;  //! Default for fTimeUpperLimit    (now set to: 2.)
+
+  static const TString gsHistName;        //! Default Histogram names
+  static const TString gsHistTitle;       //! Default Histogram titles
+  static const TString gsHistXTitle;      //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;      //! Default Histogram y-axis titles
+  
+  static const TString gsAbsHistName;     //! Default Histogram names abs.times
+  static const TString gsAbsHistTitle;    //! Default Histogram titles abs.times
+  static const TString gsAbsHistXTitle;   //! Default Histogram x-axis titles abs.times
+  static const TString gsAbsHistYTitle;   //! Default Histogram y-axis titles abs.times
+  
+  TString fHistName;                      // Histogram names
+  TString fHistTitle;                     // Histogram titles
+  TString fHistXTitle;                    // Histogram x-axis titles
+  TString fHistYTitle;                    // Histogram y-axis titles
+  
+  TString fAbsHistName;                   // Histogram names abs.times
+  TString fAbsHistTitle;                  // Histogram titles abs. times
+  TString fAbsHistXTitle;                 // Histogram x-axis titles abs. times
+  TString fAbsHistYTitle;                 // Histogram y-axis titles abs. times
+  
+  MCalibrationChargePINDiode *fPINDiode;  //! Storage container of the results
+  MExtractedSignalPINDiode   *fSigPIN;    //! Storage container of extracted signal
+
+  TH1F fHRmsCharge;                       //  Histogram containing Variance of summed FADC slices
+
+  Axis_t  fRmsChargeFirst;                //  Lower bound bin used for the fHRmsCharge
+  Axis_t  fRmsChargeLast;                 //  Upper bound bin used for the fHRmsCharge
+  Int_t   fRmsChargeNbins;                //  Number of  bins used for the fHRmsCharge
+  Float_t fRmsChargeMean;                 //  Mean of the Gauss fit               
+  Float_t fRmsChargeMeanErr;              //  Error of the mean of the Gauss fit 
+  Float_t fRmsChargeSigma;                //  Sigma of the Gauss fit             
+  Float_t fRmsChargeSigmaErr;             //  Error of the sigma of the Gauss fit
+  Float_t fTimeLowerLimit;                //  Limit dist. to first signal slice (units: FADC slices) 
+  Float_t fTimeUpperLimit;                //  Limit dist. to last signal slice  (units: FADC slices) 
+  
+public:
+
+  MHCalibrationChargePINDiode(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargePINDiode(){}
+
+  Bool_t SetupFill(const MParList *pList);
+  Bool_t ReInit   (      MParList *pList);
+  Bool_t Fill     (const MParContainer *par, const Stat_t w=1);
+  Bool_t Finalize ();
+  
+  // Draw
+  void Draw(Option_t *opt="");
+  
+  // Getters
+        TH1F *GetHRmsCharge()                  { return &fHRmsCharge;       }
+  const TH1F *GetHRmsCharge()            const { return &fHRmsCharge;       }
+  Float_t     GetRmsChargeMean()         const { return fRmsChargeMean;     }
+  Float_t     GetRmsChargeMeanErr()      const { return fRmsChargeMeanErr;  }
+  Float_t     GetRmsChargeSigma()        const { return fRmsChargeSigma;    }
+  Float_t     GetRmsChargeSigmaErr()     const { return fRmsChargeSigmaErr; }
+
+  // Fill histos
+  Bool_t FillRmsCharge(const Float_t q);
+
+  // Fits
+  Bool_t FitRmsCharge(Option_t *option="RQ0");
+
+  // Setters
+  void SetAbsTimeNbins   ( const Int_t   bins =fgAbsTimeNbins   ) { fAbsTimeNbins   = bins;  }
+  void SetAbsTimeFirst   ( const Axis_t  first=fgAbsTimeFirst   ) { fAbsTimeFirst   = first; }
+  void SetAbsTimeLast    ( const Axis_t  last =fgAbsTimeLast    ) { fAbsTimeLast    = last;  }
+  void SetRmsChargeNbins ( const Int_t   bins =fgRmsChargeNbins ) { fRmsChargeNbins = bins;  }
+  void SetRmsChargeFirst ( const Axis_t  first=fgRmsChargeFirst ) { fRmsChargeFirst = first; }
+  void SetRmsChargeLast  ( const Axis_t  last =fgRmsChargeLast  ) { fRmsChargeLast  = last;  }
+  void SetTimeLowerLimit ( const Float_t f=fgTimeLowerLimit     ) { fTimeLowerLimit = f;     }
+  void SetTimeUpperLimit ( const Float_t f=fgTimeUpperLimit     ) { fTimeUpperLimit = f;     }
+
+  void SetAbsHistName  ( const char *name )  { fAbsHistName  = name;  }
+  void SetAbsHistTitle ( const char *name )  { fAbsHistTitle = name;  }
+  void SetAbsHistXTitle( const char *name )  { fAbsHistXTitle = name; }
+  void SetAbsHistYTitle( const char *name )  { fAbsHistYTitle = name; }
+   
+  void SetHistName  ( const char *name )  { fHistName  = name;  }
+  void SetHistTitle ( const char *name )  { fHistTitle = name;  }
+  void SetHistXTitle( const char *name )  { fHistXTitle = name; }
+  void SetHistYTitle( const char *name )  { fHistYTitle = name; }
+   
+  ClassDef(MHCalibrationChargePINDiode, 1)  // Histogram class for Charge PIN Diode Calibration 
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargePix.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargePix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargePix.cc	(revision 9772)
@@ -0,0 +1,255 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationChargePix
+//
+//  Histogram class for the charge calibration. 
+//  Stores and fits the charges and stores the location of the maximum FADC 
+//  slice. Charges are taken from MExtractedSignalPix.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargePix.h"
+
+#include <TH1.h>
+#include <TF1.h>
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TGraph.h>
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCalibrationChargePix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default x-axis title for fHAbsTime ("Absolute Arrival Time [FADC slice nr]")
+// - the default y-axis title for fHAbsTime ("Nr. of events"); 
+// - the default directory of the fHAbsTime (NULL)
+// - the current style for fHAbsTime
+//
+// Initializes:
+// - fHAbsTime()
+//
+// Calls:
+// - Clear();
+//
+MHCalibrationChargePix::MHCalibrationChargePix(const char *name, const char *title)
+    : fHAbsTime(), 
+      fAbsTimeNbins(1), fAbsTimeFirst(0.), fAbsTimeLast(1.)
+{ 
+  
+  fName  = name  ? name  : "MHCalibrationChargePix";
+  fTitle = title ? title : "Statistics of the FADC sums of calibration events";
+
+  fHAbsTime.UseCurrentStyle();
+  fHAbsTime.SetDirectory(NULL); 
+
+  Clear();
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - fHGausHist.SetBins(fNbins,fFirst,fLast);
+// - fHAbsTime.SetBins(fAbsTimeNbins,fAbsTimeFirst,fAbsTimeLast);
+//
+void MHCalibrationChargePix::InitBins()
+{
+  MHGausEvents::InitBins();
+  fHAbsTime.SetBins(fAbsTimeNbins,fAbsTimeFirst,fAbsTimeLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// Empty function to overload MHGausEvents::Reset()
+//
+void MHCalibrationChargePix::Reset()
+{
+  MHGausEvents::Reset();
+  fHAbsTime.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// returns fHGausHist.Integral("width")
+//
+const Float_t MHCalibrationChargePix::GetIntegral() const 
+{ 
+   return fHGausHist.Integral("width");  
+}
+
+// --------------------------------------------------------------------------
+//
+// returns fHAbsTime.GetMean()
+//
+const Float_t MHCalibrationChargePix::GetAbsTimeMean() const 
+{
+  return fHAbsTime.GetMean();
+}
+
+// --------------------------------------------------------------------------
+//
+// returns fHAbsTime.GetRMS()
+//
+const Float_t MHCalibrationChargePix::GetAbsTimeRms()  const 
+{
+  return fHAbsTime.GetRMS();
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills fHAbsTime with t
+// Returns kFALSE, if overflow or underflow occurred, else kTRUE
+//
+Bool_t MHCalibrationChargePix::FillAbsTime(Float_t t)
+{
+  return fHAbsTime.Fill(t) > -1;
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// The following options can be chosen:
+//
+// "": displays the fHGausHist and the fHAbsTime
+// "all": executes additionally MHCalibrationPix::Draw(), with options
+//
+// The following picture shows a typical outcome of call to Draw("all"): 
+// One the left side:
+// - The distribution of the values with the Gauss fit are shown (points connected 
+//   with each other). The line is green, thus the Gauss fit has a probability higher 
+//   than 0.5%.
+// - The distribution of the positions of the maximum (abs. arrival times) 
+//   is displayed. Most of the events have an arrival time of slice 7 (==hardware:8)
+//
+// On the right side:
+// - The first plot shows the distribution of the values with the Gauss fit
+//   with error bars
+// - The second plot shows the TGraph with the events vs. time
+// - The third plot shows the fourier transform and a peak at 100 Hz.
+// - The fourth plot shows the projection of the fourier components and an exponential 
+//   fit, with the result that the observed deviation is not statistical, but signficant with a 
+//   probability smaller than 0.5%. 
+//
+//Begin_Html
+/*
+<img src="images/MHCalibrationChargePixDraw.gif">
+*/
+//End_Html
+//
+void MHCalibrationChargePix::Draw(const Option_t *opt)
+{
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win = 1;
+  
+  TVirtualPad *oldpad = gPad ? gPad : MH::MakeDefCanvas(this,600, 600);
+  TVirtualPad *pad    = NULL;
+
+  if (option.Contains("all"))
+  {
+      option.ReplaceAll("all","");
+      oldpad->Divide(2,1);
+      win = 2;
+      oldpad->cd(1);
+      TVirtualPad *newpad = gPad;
+      pad = newpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+  else if (option.Contains("datacheck"))
+    {
+      MHCalibrationPix::Draw("events");
+      return;
+    }
+  else 
+  {
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+  /*
+  else
+    {
+      option.ReplaceAll("time","");
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+    }
+  */
+  if (!IsEmpty() && !IsOnlyOverflow() && !IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  gPad->SetTicks();
+
+  fHGausHist.GetXaxis()->SetLabelSize(0.06);
+  fHGausHist.GetYaxis()->SetLabelSize(0.07);
+  fHGausHist.GetXaxis()->SetLabelOffset(0.01);
+  fHGausHist.GetYaxis()->SetLabelOffset(0.01);
+  fHGausHist.GetXaxis()->SetTitleSize(0.065);
+  fHGausHist.GetYaxis()->SetTitleSize(0.07);
+  fHGausHist.GetXaxis()->SetTitleOffset(0.6);
+  fHGausHist.GetYaxis()->SetTitleOffset(0.6);
+  fHGausHist.Draw(); 
+  if (fFGausFit)
+  {
+      fFGausFit->SetLineColor(IsGausFitOK() ? kGreen : kRed);
+      fFGausFit->Draw("same");
+  }
+
+  pad->cd(2);
+  gPad->SetTicks();
+
+  fHAbsTime.GetXaxis()->SetLabelSize(0.06);
+  fHAbsTime.GetYaxis()->SetLabelSize(0.07);
+  fHAbsTime.GetXaxis()->SetLabelOffset(0.01);
+  fHAbsTime.GetYaxis()->SetLabelOffset(0.01);
+  fHAbsTime.GetXaxis()->SetTitleSize(0.065);
+  fHAbsTime.GetYaxis()->SetTitleSize(0.07);
+  fHAbsTime.GetXaxis()->SetTitleOffset(0.6);
+  fHAbsTime.GetYaxis()->SetTitleOffset(0.6);
+  fHAbsTime.Draw();
+
+  if (win < 2)
+      return;
+
+  oldpad->cd(2);
+  MHCalibrationPix::Draw("fourierevents");
+
+}
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationChargePix.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationChargePix.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationChargePix.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MHCalibrationChargePix
+#define MARS_MHCalibrationChargePix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+class MHCalibrationChargePix : public MHCalibrationPix
+{
+
+protected:
+
+  TH1F     fHAbsTime;      // Histogram containing the absolute arrival times 
+                          
+  Int_t    fAbsTimeNbins;  // Number of  bins used for the fHAbsTime 
+  Axis_t   fAbsTimeFirst;  // Lower bound bin used for the fHAbsTime
+  Axis_t   fAbsTimeLast;   // Upper bound bin used for the fHAbsTime
+
+public:
+
+  MHCalibrationChargePix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargePix() {}
+
+  void Reset();  
+  void InitBins();
+  
+  // Setters 
+  virtual void SetAbsTimeNbins(const Int_t  bins )  { fAbsTimeNbins = bins;  }
+  virtual void SetAbsTimeFirst(const Axis_t first)  { fAbsTimeFirst = first; }
+  virtual void SetAbsTimeLast( const Axis_t last )   { fAbsTimeLast  = last;  }
+
+  // Getters
+  TH1F *GetHAbsTime()                         { return &fHAbsTime;  }
+  const TH1F *GetHAbsTime()             const { return &fHAbsTime;  }
+
+  const Float_t  GetAbsTimeMean(  )     const;
+  const Float_t  GetAbsTimeRms()        const;
+  const Float_t  GetIntegral()          const;
+
+  // Fill histos
+  Bool_t FillAbsTime(const Float_t t);
+
+  // Draws
+  virtual void Draw(Option_t *opt="");
+
+  ClassDef(MHCalibrationChargePix, 1)     // Base Histogram class for Charge Pixel Calibration
+};
+
+#endif /* MARS_MHCalibrationChargePix */
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationHiLoCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationHiLoCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationHiLoCam.cc	(revision 9772)
@@ -0,0 +1,675 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!              
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                        
+// MHCalibrationHiLoCam                                                
+//                                                                        
+// Fills the extracted high-gain low-gain charge ratios of MArrivalTimeCam into 
+// the MHCalibrationPix-classes MHCalibrationPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray  
+//   or MHCalibrationCam::fHiGainArray, respectively, depending if 
+//   MArrivalTimePix::IsLoGainUsed() is set.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors 
+//   and MHCalibrationCam::fAverageHiGainSectors 
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiLoNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the 
+// projected fourier components follow an exponential distribution. 
+// In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiLoOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun      )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MCalibrationHiLoCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//                                                                         
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationHiLoCam.h"
+#include "MHCalibrationPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationHiLoCam.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include <TOrdCollection.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TF1.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TGraph.h>
+
+ClassImp(MHCalibrationHiLoCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationHiLoCam::fgNbins    = 175;
+const Axis_t  MHCalibrationHiLoCam::fgFirst    = -5.1;
+const Axis_t  MHCalibrationHiLoCam::fgLast     = 29.9;
+const Float_t MHCalibrationHiLoCam::fgProbLimit = 0.;
+const TString MHCalibrationHiLoCam::gsHistName  = "HiLo";
+const TString MHCalibrationHiLoCam::gsHistTitle = "HiGain vs. LoGain";
+const TString MHCalibrationHiLoCam::gsHistXTitle = "Amplification Ratio [1]";
+const TString MHCalibrationHiLoCam::gsHistYTitle = "Nr. events";
+// --------------------------------------------------------------------------
+//
+// Default Constructor.
+//
+// Sets: 
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - fLowerLimt  to fgLowerLim
+// - fUpperLimt  to fgUpperLim
+//
+MHCalibrationHiLoCam::MHCalibrationHiLoCam(const char *name, const char *title) 
+  : fArrTimes(NULL)
+{
+
+  fName  = name  ? name  : "MHCalibrationHiLoCam";
+  fTitle = title ? title : "Histogram class for the high-gain vs. low-gain amplification ratio calibration";
+
+  SetNbins(fgNbins);
+  SetFirst(fgFirst);
+  SetLast (fgLast );
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationHiLoCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHCalibrationHiLoCam *cam = MParList::FindObject("MHCalibrationHiLoCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHCalibrationHiLoCam::Clone(const char *) const
+{
+
+  MHCalibrationHiLoCam *cam = new MHCalibrationHiLoCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fColor                  = fColor;
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+
+  //
+  // Copy the MArrays
+  //
+  cam->fAverageAreaRelSigma    = fAverageAreaRelSigma;
+  cam->fAverageAreaRelSigmaVar = fAverageAreaRelSigmaVar;
+  cam->fAverageAreaSat         = fAverageAreaSat;
+  cam->fAverageAreaSigma       = fAverageAreaSigma;
+  cam->fAverageAreaSigmaVar    = fAverageAreaSigmaVar;
+  cam->fAverageAreaNum         = fAverageAreaNum;
+  cam->fAverageSectorNum       = fAverageSectorNum;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+  const Int_t navlo   =  fAverageLoGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  for (int i=0; i<navlo; i++)
+    cam->fAverageLoGainAreas->AddAt(GetAverageLoGainArea(i).Clone(),i);
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MCalibrationHiLoCam
+//
+// Searches pointer to:
+// - MExtractedSignalCam
+// - MArrivalTimeCam
+//
+// Calls:
+// - MHCalibrationCam::InitHiGainArrays()
+// - MHCalibrationCam::InitLoGainArrays()
+// 
+// Sets:
+// - fSumarea   to nareas
+// - fSumsector to nareas
+// - fNumarea   to nareas
+// - fNumsector to nareas
+//
+Bool_t MHCalibrationHiLoCam::ReInitHists(MParList *pList)
+{
+
+  fCam = (MCalibrationCam*)pList->FindObject(AddSerialNumber("MCalibrationHiLoCam"));
+  if (!fCam)
+    {
+      fCam = (MCalibrationCam*)pList->FindCreateObj(AddSerialNumber("MCalibrationHiLoCam"));
+      if (!fCam)
+	  return kFALSE;
+      fCam->Init(*fGeom);
+    }
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!signal)
+  {
+      *fLog << err << "MExtractedSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  fArrTimes = (MArrivalTimeCam*)pList->FindObject("MArrivalTimeCam");
+  if (!fArrTimes)
+  {
+      *fLog << warn << "MArrivalTimeCam not found... cannot calibrated arrival times between "
+	    <<"high and low-gain" << endl;
+      SetLoGain(kFALSE);
+  }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  fSumareahi  .Set(nareas); 
+  fSumsectorhi.Set(nsectors); 
+  fNumareahi  .Set(nareas); 
+  fNumsectorhi.Set(nsectors); 
+  if (IsLoGain())
+    {
+      fSumarealo  .Set(nareas); 
+      fSumsectorlo.Set(nsectors); 
+      fNumarealo  .Set(nareas); 
+      fNumsectorlo.Set(nsectors); 
+    }
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MExtractedSignalCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills histograms (MHGausEvents::FillHistAndArray()) with:
+// - MExtractedSignalPix::GetExtractedSignalHiGain(pixid) / MExtractedSignalPix::GetExtractedSignalLoGain;
+//   if the high-gain signal does not show high-gain saturation, but the low-gain
+//   has been extracted.
+// - MArrivalTimePix::GetArrivalTimeHiGain(pixid) / MArrivalTimePix::GetArrivalTimeLoGain;
+//   if the high-gain signal does not show high-gain saturation, but the low-gain
+//   has been extracted.
+//
+Bool_t MHCalibrationHiLoCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)par;
+  if (!signal)
+    {
+      gLog << err << "No argument in MExtractedSignal::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  fSumareahi  .Reset();
+  fSumsectorhi.Reset(); 
+  fNumareahi  .Reset(); 
+  fNumsectorhi.Reset(); 
+  fSumarealo  .Reset();
+  fSumsectorlo.Reset(); 
+  fNumarealo  .Reset(); 
+  fNumsectorlo.Reset(); 
+
+  for (Int_t i=0; i<npixels; i++)
+    {
+      const MExtractedSignalPix &pix = (*signal)[i];
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      const Float_t siglo = pix.GetExtractedSignalLoGain();
+
+      //
+      // Skip all pixels with:
+      // - Saturated high-gain
+      // - Not extracted low-gain 
+      //   (see MExtractTimeAndCharge::fLoGainSwitch for setting the criteria)
+      //
+      if (siglo < 0.5 || pix.GetNumHiGainSaturated() > 0)
+	continue;
+
+      const Float_t sighi = pix.GetExtractedSignalHiGain();
+      const Float_t ratio = sighi / siglo;
+      
+      MHCalibrationPix &histhi = (*this)[i];
+
+      histhi.FillHistAndArray(ratio);
+      fSumareahi  [aidx]   += ratio;
+      fNumareahi  [aidx]   ++;
+      fSumsectorhi[sector] += ratio;
+      fNumsectorhi[sector] ++;
+
+      if (IsLoGain())
+	{
+	  const MArrivalTimePix &tix = (*fArrTimes)[i];
+	  MHCalibrationPix &histlo = (*this)(i);	  
+
+	  const Float_t diff = tix.GetArrivalTimeLoGain() - tix.GetArrivalTimeHiGain();
+
+	  histlo.FillHistAndArray(diff);
+	  fSumarealo  [aidx]   += diff;
+	  fNumarealo  [aidx]   ++;
+	  fSumsectorlo[sector] += diff;
+	  fNumsectorlo[sector] ++;
+	}
+    }
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(fNumareahi[j] == 0 ? 0. : fSumareahi[j]/fNumareahi[j]);
+
+      if (IsLoGain())
+	{
+	  MHCalibrationPix &histlo = GetAverageLoGainArea(j);
+	  histlo.FillHistAndArray(fNumarealo[j] == 0 ? 0. : fSumarealo[j]/fNumarealo[j]);
+	}
+    }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &hist = GetAverageHiGainSector(j);
+      hist.FillHistAndArray(fNumsectorhi[j] == 0 ? 0. : fSumsectorhi[j]/fNumsectorhi[j]);
+
+      if (IsLoGain())
+	{
+	  MHCalibrationPix &histlo = GetAverageLoGainSector(j);
+	  histlo.FillHistAndArray(fNumsectorlo[j] == 0 ? 0. : fSumsectorlo[j]/fNumsectorlo[j]);
+	}
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with flags:
+//   MBadPixelsPix::kHiLoNotFitted and MBadPixelsPix::kHiLoOscillating
+// - MHCalibrationCam::FitLoGainArrays() with flags:
+//   MBadPixelsPix::kHiLoNotFitted and MBadPixelsPix::kHiLoOscillating
+// 
+Bool_t MHCalibrationHiLoCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  MCalibrationCam *hilocam = fCam;
+  MBadPixelsCam   *badcam  = fIntensBad ? fIntensBad->GetCam() : fBadPixels;
+
+  const Int_t nareas   = fAverageHiGainAreas->GetSize();
+  const Int_t nsectors = fAverageHiGainSectors->GetSize();
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)[i];
+
+      if (hist.IsExcluded())
+        continue;
+      
+      CheckOverflow(hist);
+    }
+
+  for (Int_t j=0; j<nareas; j++)
+    {
+      
+      MHCalibrationPix    &hist = GetAverageHiGainArea(j);      
+      //
+      // Check histogram overflow
+      // 
+      CheckOverflow(hist);
+   }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageHiGainSector(j);      
+      //
+      // Check histogram overflow
+      // 
+      CheckOverflow(hist);
+    }
+
+  FitHiGainArrays(*hilocam,*badcam,
+                  MBadPixelsPix::kHiLoNotFitted,
+                  MBadPixelsPix::kHiLoOscillating);
+  
+  if (!IsLoGain())
+    return kTRUE;
+
+  for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)(i);
+
+      if (hist.IsExcluded())
+        continue;
+      
+      CheckOverflow(hist);
+    }
+
+  for (Int_t j=0; j<nareas; j++)
+    {
+      
+      MHCalibrationPix    &hist = GetAverageLoGainArea(j);      
+      CheckOverflow(hist);
+   }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageLoGainSector(j);      
+      CheckOverflow(hist);
+    }
+
+  FitLoGainArrays(*hilocam,*badcam,
+                  MBadPixelsPix::kHiLoNotFitted,
+                  MBadPixelsPix::kHiLoOscillating);
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets all pixels to MBadPixelsPix::kUnreliableRun, if following flags are set:
+// - MBadPixelsPix::kHiLoNotFitted
+// - MBadPixelsPix::kHiLoOscillating
+//
+void MHCalibrationHiLoCam::FinalizeBadPixels()
+{
+
+  MBadPixelsCam *badcam = fIntensBad ? fIntensBad->GetCam() : fBadPixels;
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      MBadPixelsPix          &bad    = (*badcam)[i];
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kHiLoNotFitted ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kHiLoOscillating))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+      
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Mean High-Gain Low-Gain Charge Ratio in FADC slices  (MHGausEvents::GetMean()
+// 1: Error Mean High-Gain Low-Gain Charge Ratio in FADC slices   (MHGausEvents::GetMeanErr()
+// 2: Sigma fitted High-Gain Low-Gain Charge Ratio in FADC slices (MHGausEvents::GetSigma()
+// 3: Error Sigma High-Gain Low-Gain Charge Ratio in FADC slices  (MHGausEvents::GetSigmaErr()
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit              (calls: MHGausEvents::GetProb())
+//
+// Localized defects:
+// ==================
+//
+// 5: Gaus fit not OK                               (calls: MHGausEvents::IsGausFitOK())
+// 6: Fourier spectrum not OK                       (calls: MHGausEvents::IsFourierSpectrumOK())
+//
+Bool_t MHCalibrationHiLoCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  const MHCalibrationPix &pixhi = (*this)[idx];
+  const MHCalibrationPix &pixlo = (*this)(idx);
+
+  switch (type)
+    {
+    case 0:
+      val = pixhi.GetMean();
+      break;
+    case 1:
+      val = pixhi.GetMeanErr();
+      break;
+    case 2:
+      val = pixhi.GetSigma();
+      break;
+    case 3:
+      val = pixhi.GetSigmaErr();
+      break;
+    case 4:
+      val = pixhi.GetProb();
+      break;
+    case 5:
+      if (!pixhi.IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!pixhi.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    case 7:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetMean();
+      break;
+    case 8:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetMeanErr();
+      break;
+    case 9:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetSigma();
+      break;
+    case 10:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetSigmaErr();
+      break;
+    case 11:
+      if (!IsLoGain())
+	break;
+      val = pixlo.GetProb();
+      break;
+    case 12:
+      if (!IsLoGain())
+	break;
+      if (!pixlo.IsGausFitOK())
+        val = 1.;
+      break;
+    case 13:
+      if (!IsLoGain())
+	break;
+      if (!pixlo.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationHiLoCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
+
+void MHCalibrationHiLoCam::CheckOverflow( MHCalibrationPix &pix )
+{
+
+  if (pix.IsExcluded())
+    return;
+
+  TH1F *hist = pix.GetHGausHist();
+  
+  Stat_t overflow = hist->GetBinContent(hist->GetNbinsX()+1);
+  if (overflow > fOverflowLimit*hist->GetEntries())
+    {
+      *fLog << warn << "Hist-overflow " << overflow
+            << " times in " << pix.GetName() << endl;
+    }
+  
+  overflow = hist->GetBinContent(0);
+  if (overflow > fOverflowLimit*hist->GetEntries())
+    {
+      *fLog << warn << "Hist-underflow " << overflow
+            << " times in " << pix.GetName()  << endl;
+    }
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both amplification ratio as time difference
+//
+void MHCalibrationHiLoCam::Draw(const Option_t *opt)
+{
+
+  if (!IsAverageing())
+    return;
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  pad->Divide(IsLoGain() ? 2 : 1,nareas);
+
+  for (Int_t i=0; i<nareas;i++) 
+    {
+
+      pad->cd(IsLoGain() ? 2*(i+1)-1 : i+1);
+
+      GetAverageHiGainArea(i).Draw(opt);
+
+      if (IsLoGain())
+        {
+          pad->cd(2*(i+1));
+
+          TH1F *hist = GetAverageLoGainArea(i).GetHGausHist();
+          hist->SetXTitle("Extracted Time Difference [FADC sl.]");
+          GetAverageLoGainArea(i).Draw(opt);
+        }
+    }
+}
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationHiLoCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationHiLoCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationHiLoCam.h	(revision 9772)
@@ -0,0 +1,70 @@
+#ifndef MARS_MHCalibrationHiLoCam
+#define MARS_MHCalibrationHiLoCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TH1F;
+
+class MGeomCam;
+class MArrivalTimeCam;
+class MHCalibrationHiLoCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Int_t   fgNbins;                      //! Default number of bins        (now set to: 900   )
+  static const Axis_t  fgFirst;                      //! Default lower histogram limit (now set to: -13.5 )
+  static const Axis_t  fgLast;                       //! Default upper histogram limit (now set to:  13.5 )
+  static const Float_t fgProbLimit;                  //! The default for fProbLimit    (now set to: 0.0)  
+  
+  static const TString gsHistName;                   //! Default Histogram names
+  static const TString gsHistTitle;                  //! Default Histogram titles
+  static const TString gsHistXTitle;                 //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;                 //! Default Histogram y-axis titles
+
+  MArrayD fSumareahi  ;                               //
+  MArrayD fSumsectorhi;                               //
+  MArrayI fNumareahi  ;                               //
+  MArrayI fNumsectorhi;                               //
+  MArrayD fSumarealo  ;                               //
+  MArrayD fSumsectorlo;                               //
+  MArrayI fNumarealo  ;                               //
+  MArrayI fNumsectorlo;                               //
+
+  MArrivalTimeCam *fArrTimes;                         //! Pointer to arrival times
+
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  void   FinalizeBadPixels();
+
+  void   CheckOverflow( MHCalibrationPix &pix);
+  
+public:
+
+  MHCalibrationHiLoCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationHiLoCam() {}
+
+  // Clone
+  TObject *Clone(const char *name="") const;
+
+  // Draw
+  void   Draw(const Option_t *opt);       // *MENU*
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  ClassDef(MHCalibrationHiLoCam, 1)	// Histogram class for High Gain vs. Low Gain Calibration
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationPix.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationPix.cc	(revision 9772)
@@ -0,0 +1,239 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationPix
+//
+//  A base class for events which are believed to follow a Gaussian distribution 
+//  with time, e.g. calibration events, observables containing white noise, ...
+//
+//  MHCalibrationPix derives from MHGausEvents, thus all features of 
+//  MHGausEvents can be used by a class deriving from MHCalibrationPix
+//
+//  As an additional feature to MHGausEvents, this class offers to skip the fitting 
+//  to set mean, sigma and its errors directly from the histograms with the function 
+//  BypassFit()
+//
+//  See also: MHGausEvents
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationPix.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TGraph.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCalibrationPix);
+
+using namespace std;
+
+const Float_t  MHCalibrationPix::fgBlackoutLimit        = 5.;
+const Float_t  MHCalibrationPix::fgPickupLimit          = 5.;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+// Sets: 
+// - the default number for fPickupLimit           (fgPickupLimit)
+// - the default number for fBlackoutLimit         (fgBlackoutLimit)
+//
+// Initializes:
+// - all variables to 0.
+//
+MHCalibrationPix::MHCalibrationPix(const char *name, const char *title)
+{ 
+
+  fName  = name  ? name  : "MHCalibrationPix";
+  fTitle = title ? title : "Calibration histogram events";
+
+  Clear();
+  
+  SetBlackoutLimit();
+  SetPickupLimit();
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Clear(), can be overloaded.
+//
+// Sets:
+// - all other pointers to NULL
+// - all variables to 0., except fPixId to -1 
+// - all flags to kFALSE
+// 
+// - all pointers
+//
+void MHCalibrationPix::Clear(Option_t *o)
+{
+
+  MHGausEvents::Clear();
+  fSaturated         = 0;
+}
+
+void MHCalibrationPix::Reset()
+{
+  
+  MHGausEvents::Reset();
+  fSaturated = 0;
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Bypasses the Gauss fit by taking mean and RMS from the histogram
+//
+// Errors are determined in the following way:
+// MeanErr  = RMS / Sqrt(entries)
+// SigmaErr = RMS / (2.*Sqrt(entries) )
+//
+void MHCalibrationPix::BypassFit()
+{
+
+  const Stat_t entries = fHGausHist.GetEntries();
+  
+  if (entries <= 0.)
+    {
+      *fLog << warn << GetDescriptor() 
+            << ": Cannot bypass fit. Number of entries smaller or equal 0 in pixel: " << GetName() << endl;
+      return;
+    }
+  
+  fMean     = fHGausHist.GetMean();
+  fMeanErr  = fHGausHist.GetRMS() / TMath::Sqrt(entries);
+  fSigma    = fHGausHist.GetRMS() ;
+  fSigmaErr = fHGausHist.GetRMS() / TMath::Sqrt(entries) / 2.;
+}
+
+// -------------------------------------------------------------------------------
+//
+// Return the number of "blackout" events, which are events with values higher 
+// than fBlackoutLimit sigmas from the mean
+//
+//
+const Double_t MHCalibrationPix::GetBlackout() const 
+{
+  
+  if ((fMean == 0.) && (fSigma == 0.))
+    return -1.;
+
+  const Int_t first = fHGausHist.GetXaxis()->GetFirst();
+  const Int_t last  = fHGausHist.GetXaxis()->FindBin(fMean-fBlackoutLimit*fSigma);
+
+  if (first >= last)
+    return 0.;
+  
+  return fHGausHist.Integral(first, last);
+}
+
+
+// -------------------------------------------------------------------------------
+//
+// Return the number of "pickup" events, which are events with values higher 
+// than fPickupLimit sigmas from the mean
+//
+//
+const Double_t MHCalibrationPix::GetPickup() const 
+{
+  
+  if ((fMean == 0.) && (fSigma == 0.))
+    return -1.;
+
+  const Int_t first = fHGausHist.GetXaxis()->FindBin(fMean+fPickupLimit*fSigma);
+  const Int_t last  = fHGausHist.GetXaxis()->GetLast();
+
+  if (first >= last)
+    return 0.;
+  
+  return fHGausHist.Integral(first, last);
+}
+
+// -----------------------------------------------------------------------------
+//
+// If flag IsGausFitOK() is set (histogram already successfully fitted), 
+// returns kTRUE
+// 
+// If both fMean and fSigma are still zero, call FitGaus() 
+// 
+// Repeats the Gauss fit in a smaller range, defined by: 
+// 
+// min = GetMean() - fBlackoutLimit * GetSigma();
+// max = GetMean() + fPickupLimit   * GetSigma();
+//
+// The fit results are retrieved and stored in class-own variables.  
+//
+// A flag IsGausFitOK() is set according to whether the fit probability 
+// is smaller or bigger than fProbLimit, whether the NDF is bigger than 
+// fNDFLimit and whether results are NaNs.
+//
+Bool_t MHCalibrationPix::RepeatFit(const Option_t *option)
+{
+
+  if (IsGausFitOK())
+    return kTRUE;
+
+  if ((fMean == 0.) && (fSigma == 0.))
+    return FitGaus();
+
+  //
+  // Get new fitting ranges
+  //
+  Axis_t rmin = fMean - fBlackoutLimit * fSigma;
+  Axis_t rmax = fMean + fPickupLimit   * fSigma;
+
+  Axis_t hmin = fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetFirst());
+  Axis_t hmax = fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetLast()) ;
+
+  fFGausFit->SetRange(hmin < rmin ? rmin : hmin , hmax > rmax ? rmax : hmax);
+
+  fHGausHist.Fit(fFGausFit,option);
+
+  fMean     = fFGausFit->GetParameter(1);
+  fSigma    = fFGausFit->GetParameter(2);
+  fMeanErr  = fFGausFit->GetParError(1) ; 
+  fSigmaErr = fFGausFit->GetParError(2) ; 
+  fProb     = fFGausFit->GetProb()      ;      
+
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (default: fgNDFLimit)
+  // 3) The Probability is greater than fProbLimit (default: fgProbLimit)
+  //
+  if (   TMath::IsNaN ( fMean     ) 
+      || TMath::IsNaN ( fMeanErr  )
+      || TMath::IsNaN ( fProb     )    
+      || TMath::IsNaN ( fSigma    )
+      || TMath::IsNaN ( fSigmaErr ) 
+      || fFGausFit->GetNDF() < fNDFLimit 
+      || fProb < fProbLimit )
+    return kFALSE;
+  
+  SetGausFitOK(kTRUE);
+  return kTRUE;
+
+}
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationPix.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationPix.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MHCalibrationPix
+#define MARS_MHCalibrationPix
+
+#ifndef MARS_MHGausEvents
+#include "MHGausEvents.h"
+#endif
+
+class MHCalibrationPix : public MHGausEvents
+{
+private:
+
+  const static Float_t  fgBlackoutLimit; //! Default for fBlackoutLimit (now set to: 5. )
+  const static Float_t  fgPickupLimit;   //! Default for fPickupLimit   (now set to: 5. )
+  
+protected:
+
+  Float_t  fBlackoutLimit;               // Lower nr sigmas from mean until event is considered blackout
+  Int_t    fSaturated;                   // Number of events classified as saturated
+  Float_t  fPickupLimit;                 // Upper nr sigmas from mean until event is considered pickup
+
+public:
+
+  MHCalibrationPix(const char* name=NULL, const char* title=NULL);
+
+  void  Clear(Option_t *o="");
+  void  Reset();
+  
+  // Getters
+  const Double_t GetBlackout       () const;  
+  const Double_t GetPickup         () const;
+  const Float_t  GetSaturated      () const { return fSaturated;      }
+
+  // Fits
+  Bool_t RepeatFit(const Option_t *option="RQ0"); // Repeat fit within limits defined by fPickupLimit
+  void   BypassFit();                             // Take mean and RMS from the histogram
+  
+  // Setters
+  void  AddSaturated        ( const Int_t    i                   ) { fSaturated     += i;   }
+  void  SetBlackoutLimit    ( const Float_t  lim=fgBlackoutLimit ) { fBlackoutLimit  = lim; }
+  void  SetPickupLimit      ( const Float_t  lim=fgPickupLimit   ) { fPickupLimit    = lim; }
+
+  ClassDef(MHCalibrationPix, 1) // Base class for calibration events 
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationPulseTimeCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationPulseTimeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationPulseTimeCam.cc	(revision 9772)
@@ -0,0 +1,726 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHCalibrationPulseTimeCam                                               
+//
+// Fills the extracted signals of MExtractedSignalCam into the MHCalibrationPix-classes 
+// MHCalibrationPulseTimeHiGainPix and MHCalibrationPulseTimeLoGainPix for every:
+//
+// - Pixel, stored in the TOrdCollection's MHCalibrationCam::fHiGainArray and 
+//   MHCalibrationCam::fLoGainArray
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TOrdCollection's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageLoGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TOrdCollection's MHCalibrationCam::fAverageHiGainSectors and 
+//   MHCalibrationCam::fAverageLoGainSectors
+// 
+// Every signal is taken from MExtractedSignalCam and filled into a histogram and 
+// an array, in order to perform a Fourier analysis (see MHGausEvents). 
+// The signals are moreover averaged on an event-by-event basis and written into 
+// the corresponding average pixels.
+//
+// Additionally, the (FADC slice) position of the maximum is stored in an Absolute 
+// Arrival Time histogram. This histogram serves for a rough cross-check if the 
+// signal does not lie at or outside the edges of the extraction window. 
+//
+// The PulseTime histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted ) or  
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted ) and 
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun   ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// Unless more than fNumHiGainSaturationLimit (default: 1%) of the overall FADC 
+// slices show saturation, the following flag is set:
+// - MCalibrationPulseTimePix::SetHiGainSaturation();
+// In that case, the calibration constants are derived from the low-gain results.
+//
+// If more than fNumLoGainSaturationLimit (default: 1%) of the overall 
+// low-gain FADC slices saturate, the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturation ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    )
+// 
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum and investigates if the projected fourier components follow an exponential 
+// distribution. In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating ) or
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun     )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MCalibrationPulseTimeCam:
+//
+// - MCalibrationPix::SetHiGainSaturation() 
+// - MCalibrationPix::SetHiGainMean()
+// - MCalibrationPix::SetHiGainMeanErr()
+// - MCalibrationPix::SetHiGainSigma()
+// - MCalibrationPix::SetHiGainSigmaErr()
+// - MCalibrationPix::SetHiGainProb()
+// - MCalibrationPix::SetHiGainNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationPulseTimeCam.h"
+#include "MHCalibrationCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MHCalibrationPix.h"
+
+#include "MCalibrationIntensityCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MRawEvtData.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MArrayI.h"
+#include "MArrayD.h"
+
+#include <TOrdCollection.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TF1.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TGraph.h>
+#include <TEnv.h>
+
+ClassImp(MHCalibrationPulseTimeCam);
+
+using namespace std;
+
+const Byte_t  MHCalibrationPulseTimeCam::fgSaturationLimit   = 254;
+const Byte_t  MHCalibrationPulseTimeCam::fgLowerSignalLimit  = 100;
+const Int_t   MHCalibrationPulseTimeCam::fgNumPixelsRequired = 2;
+const Int_t   MHCalibrationPulseTimeCam::fgHiGainNbins =  40;
+const Axis_t  MHCalibrationPulseTimeCam::fgHiGainFirst =  -0.5;
+const Axis_t  MHCalibrationPulseTimeCam::fgHiGainLast  =  19.5;
+const Float_t MHCalibrationPulseTimeCam::fgProbLimit   = 0.001;
+const TString MHCalibrationPulseTimeCam::gsHistName    = "PulseTime";
+const TString MHCalibrationPulseTimeCam::gsHistTitle   = "Extracted Times";
+const TString MHCalibrationPulseTimeCam::gsHistXTitle  = "Time [FADC slices]";
+const TString MHCalibrationPulseTimeCam::gsHistYTitle  = "Nr. events";
+const TString MHCalibrationPulseTimeCam::fgReferenceFile = "mjobs/signalref.rc";
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// - fNbins to fgHiGainNbins
+// - fFirst to fgHiGainFirst
+// - fLast  to fgHiGainLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+// - fSaturationLimit to fgSaturationLimit
+// - fLowerSignalLimit to fgLowerSignalLimit
+// - fNumPixelsRequired to fgNumPixelsRequired
+//
+MHCalibrationPulseTimeCam::MHCalibrationPulseTimeCam(const char *name, const char *title)
+    : fBadPixels(NULL)
+{
+
+  fName  = name  ? name  : "MHCalibrationPulseTimeCam";
+  fTitle = title ? title : "Class to fill the extracted pulse times for cosmics ";
+  
+  SetNbins(fgHiGainNbins);
+  SetFirst(fgHiGainFirst);
+  SetLast (fgHiGainLast );
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetReferenceFile();
+  SetLoGain(kFALSE);
+  SetOscillations(kFALSE);
+
+  SetSaturationLimit();
+  SetLowerSignalLimit();
+  SetNumPixelsRequired();
+
+  fInnerRefTime = 5.;
+  fOuterRefTime = 5.;
+}
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationPulseTimeCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHCalibrationPulseTimeCam *cam = MParList::FindObject("MHCalibrationPulseTimeCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHCalibrationPulseTimeCam::Clone(const char *) const
+{
+
+  MHCalibrationPulseTimeCam *cam = new MHCalibrationPulseTimeCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fColor                  = fColor;
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+  cam->fReferenceFile          = fReferenceFile;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MRawEvtData
+//
+Bool_t MHCalibrationPulseTimeCam::SetupHists(const MParList *pList)
+{
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBadPixels)
+  {
+      *fLog << warn << GetDescriptor() << "MBadPixelsCam not found... " << endl;
+  }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MExtractedSignalCam
+// - MCalibrationPulseTimeCam or MCalibrationIntensityPulseTimeCam
+// - MBadPixelsCam
+//
+// Initializes the number of used FADC slices from MExtractedSignalCam 
+// into MCalibrationPulseTimeCam and test for changes in that variable
+//
+// Calls:
+// - InitHiGainArrays()
+// 
+// Sets:
+// - fSumhiarea   to nareas 
+// - fSumloarea   to nareas 
+// - fSumhisector to nsectors 
+// - fSumlosector to nsectors 
+//
+Bool_t MHCalibrationPulseTimeCam::ReInitHists(MParList *pList)
+{
+
+  MExtractedSignalCam *signal = 
+    (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+  if (!signal)
+  {
+      *fLog << err << "MExtractedSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  if (!InitCams(pList,"PulseTime"))
+    return kFALSE;
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+
+  fSumhiarea  .Set(nareas); 
+  fSumhisector.Set(nsectors); 
+
+  return kTRUE;
+}
+
+void MHCalibrationPulseTimeCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+  
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHCalibrationPix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                 Form("%s High Gain Pixel %4d",fHistTitle.Data(),i)),i);
+        
+        MHCalibrationPix &pix = (*this)[i];          
+        pix.SetNbins(fNbins*2);
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+        
+        MBadPixelsPix &bad = fIntensBad ? (*fIntensBad)[i] : (*fBadPixels)[i];
+        InitHists(pix,bad,i);
+
+	if (fCam)
+	  (*fCam)[i].SetPixId(i);
+      }
+  }
+
+  if (!IsAverageing())
+    return;
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHCalibrationPix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                        Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+        MHCalibrationPix &pix = GetAverageHiGainArea(j);
+        
+        pix.SetNbins(fNbins*2);
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+
+        InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadArea(j) : fCam->GetAverageBadArea(j),j);
+      }
+  }
+
+  if (fAverageHiGainSectors->GetSize()==0)
+    {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+          fAverageHiGainSectors->AddAt(new MHCalibrationPix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                            Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+          MHCalibrationPix &pix = GetAverageHiGainSector(j);
+
+          pix.SetNbins(fNbins);
+          pix.SetFirst(fFirst);
+          pix.SetLast (fLast);
+          
+          InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadSector(j) : fCam->GetAverageBadSector(j),j);
+      }
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalCam:
+// - first used LoGain FADC slice
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// For all TOrdCollection's (including the averaged ones), the following steps are performed: 
+//
+// 1) Fill PulseTimes histograms (MHGausEvents::FillHistAndArray()) with:
+// - MExtractedSignalPix::GetExtractedSignalHiGain();
+// - MExtractedSignalPix::GetExtractedSignalLoGain();
+//
+Bool_t MHCalibrationPulseTimeCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MRawEvtData *data = (MRawEvtData*)par;
+  if (!data)
+    {
+      *fLog << err << "No argument in MHCalibrationPulseTimeCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  fSumhiarea  .Reset(); 
+  fSumhisector.Reset(); 
+  fAverageAreaNum.Reset();
+  fAverageSectorNum.Reset();
+
+  MRawEvtPixelIter pixel(data);
+  while (pixel.Next())
+    {
+      
+      const Int_t i = pixel.GetPixelId();
+
+      if (fBadPixels)
+        {
+          MBadPixelsPix &bad = (*fBadPixels)[i];
+          if (bad.IsUnsuitable())
+            continue;
+        }
+
+      Byte_t *start = pixel.GetHiGainSamples();
+      Byte_t *end   = start + pixel.GetNumHiGainSamples();
+      Byte_t *p     = start;
+      Byte_t max    = 0;
+      Int_t  maxpos = 0;
+
+      while (p < end)
+	{
+	  if ((*p > max) && (*p < fSaturationLimit))
+	    {
+              max = *p;
+              maxpos = p-start-1;
+	    }
+	  p++;
+	}
+
+      start   = pixel.GetLoGainSamples();
+      end     = start + pixel.GetNumLoGainSamples();
+      p       = start;
+
+      while (p < end)
+	{
+	  if ((*p > max) && (*p < fSaturationLimit))
+	    {
+	      max = *p;
+	      maxpos = p-start+pixel.GetNumHiGainSamples() - 1;
+	    }
+	  p++;
+	}
+
+      //      *fLog << (Int_t)max << "  " << (Int_t)maxpos << endl;
+
+      if (max < fLowerSignalLimit)
+	continue;
+
+      const Float_t time = (Float_t)maxpos;
+
+      (*this)[i].FillHist(time);
+        
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      fSumhiarea[aidx]      += time;
+      fSumhisector[sector]  += time;
+      
+      fAverageAreaNum[aidx]++;
+      fAverageSectorNum[sector]++;
+    }
+  
+  for (UInt_t j=0; j<nareas; j++)
+    {
+
+      const Int_t npix = fAverageAreaNum[j];
+
+      if (npix > fNumPixelsRequired)
+        GetAverageHiGainArea(j).FillHist(fSumhiarea[j]/npix);
+    }
+
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+
+      const Int_t npix = fAverageSectorNum[j];
+
+      if (npix > 0)
+        GetAverageHiGainSector(j).FillHist(fSumhisector [j]/npix);
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For all TOrdCollection's (including the averaged ones), the following steps are performed: 
+//
+// 1) Returns if the pixel is excluded.
+// 2) Tests saturation. In case yes, set the flag: MCalibrationPix::SetHiGainSaturation()
+//    or the flag: MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainSaturated )
+// 3) Store the absolute arrival times in the MCalibrationPulseTimePix's. If flag 
+//    MCalibrationPix::IsHiGainSaturation() is set, the Low-Gain arrival times are stored, 
+//    otherwise the Hi-Gain ones.
+// 4) Calls to MHCalibrationCam::FitHiGainArrays() and MCalibrationCam::FitLoGainArrays() 
+//    with the flags:
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainNotFitted )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating )
+//    - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kLoGainOscillating )
+//
+Bool_t MHCalibrationPulseTimeCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  MCalibrationCam *calcam  = fIntensCam ? fIntensCam->GetCam() : fCam;
+  //
+  // Perform the fitting for the High Gain (done in MHCalibrationCam)
+  // 
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)[i];
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      MCalibrationPix &pix    = (*calcam)[i];
+      CalcHists(hist,pix);
+    }
+
+  if (!IsAverageing())
+    return kTRUE;
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageHiGainArea(j);      
+      MCalibrationPix  &pix  = calcam->GetAverageArea(j);
+      CalcHists(hist,pix);
+  }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      MHCalibrationPix &hist = GetAverageHiGainSector(j);      
+      MCalibrationPix  &pix  = calcam->GetAverageSector(j);
+      CalcHists(hist,pix);
+    }
+  
+  return kTRUE;
+}
+
+void MHCalibrationPulseTimeCam::CalcHists(MHCalibrationPix &hist, MCalibrationPix &pix)
+{
+
+
+  if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+    {
+      *fLog << warn << GetDescriptor()
+	    << ": Only overflow or underflow in hi-gain pixel: " << hist.GetName() << endl;
+      return;
+    }  
+
+  hist.BypassFit();
+
+  pix.SetHiGainMean       ( hist.GetMean()      );
+  pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+  pix.SetHiGainRms        ( hist.GetHistRms()   );
+  pix.SetHiGainSigma      ( hist.GetSigma()     );
+  pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+
+  if (IsDebug())
+    {
+      *fLog << dbginf << GetDescriptor() << ": ID " << GetName() 
+            << " Mean: "         << hist.GetMean    ()
+            << " MeanErr: "      << hist.GetMeanErr ()
+            << " MeanSigma: "    << hist.GetSigma   ()
+            << " MeanSigmaErr: " << hist.GetSigmaErr()
+            << " Prob: "         << hist.GetProb    ()
+            << endl;
+    }
+  return;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationPulseTimeCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationPulseTimeCam::Draw(const Option_t *opt)
+{
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TString option(opt);
+  option.ToLower();
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+  pad->Divide(1,nareas);
+
+  //
+  // Loop over inner and outer pixels
+  //  
+  for (Int_t i=0; i<nareas;i++) 
+     {
+       
+       pad->cd(i+1);
+       
+       MHCalibrationPix &hipix = GetAverageHiGainArea(i);
+       DrawDataCheckPixel(hipix,i ? fOuterRefTime : fInnerRefTime);
+    }      
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Draw the average pixel for the datacheck:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationPulseTimeCam::DrawDataCheckPixel(MHCalibrationPix &pix, const Float_t refline)
+{
+  
+  gPad->SetTicks();
+
+  TH1F *hist = pix.GetHGausHist();
+
+  TH1F *null = new TH1F("Null",hist->GetTitle(),100,
+                        pix.GetFirst() > 0. ? pix.GetFirst() : 0.,
+                        pix.GetLast() > pix.GetFirst()
+                        ? pix.GetLast() : pix.GetFirst()*2.);
+
+  null->SetMaximum(1.1*hist->GetMaximum());
+  null->SetDirectory(NULL);
+  null->SetBit(kCanDelete);
+  null->SetStats(kFALSE);
+  //
+  // set the labels bigger
+  //
+  TAxis *xaxe = null->GetXaxis();
+  TAxis *yaxe = null->GetYaxis();
+  xaxe->CenterTitle();
+  yaxe->CenterTitle();    
+  xaxe->SetTitleSize(0.06);
+  yaxe->SetTitleSize(0.076);    
+  xaxe->SetTitleOffset(0.6);
+  yaxe->SetTitleOffset(0.65);    
+  xaxe->SetLabelSize(0.06);
+  yaxe->SetLabelSize(0.06);    
+  xaxe->SetTitle(hist->GetXaxis()->GetTitle());
+  yaxe->SetTitle(hist->GetYaxis()->GetTitle());  
+
+  null->Draw();
+  hist->Draw("same");
+
+  DisplayRefLines(null,refline);
+
+  return;
+  
+}
+
+void  MHCalibrationPulseTimeCam::DisplayRefLines(const TH1F *hist, const Float_t refline) const
+{
+
+  TGraph *gr    = new TGraph(2);
+  gr->SetPoint(0,refline,0.);
+  gr->SetPoint(1,refline,hist->GetMaximum());
+  gr->SetBit(kCanDelete);
+  gr->SetLineColor(106);
+  gr->SetLineStyle(2);
+  gr->SetLineWidth(3);
+  gr->Draw("L");
+
+  TLegend *leg = new TLegend(0.8,0.35,0.99,0.65);
+  leg->SetBit(kCanDelete);
+  leg->AddEntry(gr,"Reference","l");
+
+  leg->Draw();
+}
+
+Int_t MHCalibrationPulseTimeCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (MHCalibrationCam::ReadEnv(env,prefix,print))
+    rc = kTRUE;
+   
+  if (IsEnvDefined(env, prefix, "SaturationLimit", print))
+    {
+      SetSaturationLimit(GetEnvValue(env, prefix, "SaturationLimit", fSaturationLimit));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "LowerSignalLimit", print))
+    {
+      SetLowerSignalLimit(GetEnvValue(env,prefix,"LowerSignalLimit",fLowerSignalLimit));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "NumPixelsRequired", print))
+    {
+      SetNumPixelsRequired(GetEnvValue(env,prefix,"NumPixelsRequired",fNumPixelsRequired));
+      rc = kTRUE;
+    }
+
+  if (IsEnvDefined(env, prefix, "ReferenceFile", print))
+    {
+      SetReferenceFile(GetEnvValue(env,prefix,"ReferenceFile",fReferenceFile.Data()));
+      rc = kTRUE;
+    }
+
+  TEnv refenv(fReferenceFile);
+
+  fInnerRefTime = refenv.GetValue("InnerRefTime",fInnerRefTime);
+  fOuterRefTime = refenv.GetValue("OuterRefTime",fOuterRefTime);
+
+  return rc;
+}
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationPulseTimeCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationPulseTimeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationPulseTimeCam.h	(revision 9772)
@@ -0,0 +1,89 @@
+#ifndef MARS_MHCalibrationPulseTimeCam
+#define MARS_MHCalibrationPulseTimeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TH1F;
+class MRawEvtData;
+class MHCalibrationChargePix;
+class MHCalibrationPulseTimeCam : public MHCalibrationCam
+{
+private:
+
+  static const Byte_t  fgSaturationLimit;      //! Default for fSaturationLimit (now set to: 245)
+  static const Byte_t  fgLowerSignalLimit;     //! Default for fLowerSignalLimit
+  static const Int_t   fgNumPixelsRequired;    //! Default for fNumPixelsRequired
+
+  static const Int_t   fgHiGainNbins;          //! Nr. bins of HiGain Histograms  (now set to:  550  )
+  static const Axis_t  fgHiGainFirst;          //! First Bin of HiGain Histograms (now set to: -100.5)
+  static const Axis_t  fgHiGainLast;           //! Last Bin of HiGain Histograms  (now set to:  999.5)
+  static const Float_t fgProbLimit;            //! The default for fProbLimit    (now set to: 0.00001)
+
+  static const TString fgReferenceFile;        //! default for fReferenceFile ("mjobs/calibrationref.rc")
+
+  static const TString gsHistName;             //! Default Histogram names
+  static const TString gsHistTitle;            //! Default Histogram titles
+  static const TString gsHistXTitle;           //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;           //! Default Histogram y-axis titles
+  
+  Byte_t  fSaturationLimit;                    // Highest FADC slice value until being declared saturated
+  Byte_t  fLowerSignalLimit;                   // Lower signal limit for pulse time extraction
+  Int_t   fNumPixelsRequired;                  // Minimum Number of pixels required for averageing
+  
+  TString fReferenceFile;                      // File name containing the reference values
+
+  Float_t fInnerRefTime;                       // The reference mean arrival time inner pixels
+  Float_t fOuterRefTime;                       // The reference mean arrival time outer pixels
+
+  MArrayF fSumhiarea  ;                        //!
+  MArrayF fSumhisector;                        //!
+
+  MBadPixelsCam *fBadPixels;                   //!  Bad Pixels
+  
+  void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+
+  Bool_t SetupHists(const MParList *pList);
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+
+  Bool_t FinalizeHists();
+
+  void   DrawDataCheckPixel(MHCalibrationPix &pix, const Float_t refline);
+  void   DisplayRefLines   ( const TH1F *hist,           const Float_t refline) const;
+  void   CalcHists         (MHCalibrationPix &hist, MCalibrationPix &pix);
+
+  Int_t ReadEnv        ( const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MHCalibrationPulseTimeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationPulseTimeCam() {}
+  
+  // Clone
+  TObject *Clone(const char *name="") const;
+
+  // Draw
+  void   Draw(const Option_t *opt);
+
+  void SetReferenceFile    ( const TString ref=fgReferenceFile     ) { fReferenceFile     = ref; }
+  void SetSaturationLimit  ( const Byte_t  lim=fgSaturationLimit   ) { fSaturationLimit   = lim; }
+  void SetLowerSignalLimit ( const Byte_t  lim=fgLowerSignalLimit  ) { fLowerSignalLimit  = lim; }
+  void SetNumPixelsRequired( const Byte_t  lim=fgNumPixelsRequired ) { fNumPixelsRequired = lim; }
+  
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const { return kTRUE; }
+  void   DrawPixelContent( Int_t num )  const;    
+
+  ClassDef(MHCalibrationPulseTimeCam, 1)	// Histogram class for Pulse Time Checks
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationRelTimeCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationRelTimeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationRelTimeCam.cc	(revision 9772)
@@ -0,0 +1,838 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!              
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                        
+// MHCalibrationRelTimeCam                                                
+//                                                                        
+// Fills the extracted relative arrival times of MArrivalTimeCam into 
+// the MHCalibrationPix-classes MHCalibrationPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray  
+//   or MHCalibrationCam::fHiGainArray, respectively, depending if 
+//   MArrivalTimePix::IsLoGainUsed() is set.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors 
+//   and MHCalibrationCam::fAverageHiGainSectors 
+//
+// Every relative time is calculated as the difference between the individual 
+// pixel arrival time and the one of pixel 1 (hardware number: 2). 
+// The relative times are filled into a histogram and an array, in order to perform 
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an 
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kRelTimeNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the 
+// projected fourier components follow an exponential distribution. 
+// In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kRelTimeOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun      )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MCalibrationRelTimeCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//                                                                         
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationRelTimeCam.h"
+#include "MHCalibrationPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationIntensityRelTimeCam.h"
+
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimePix.h"
+#include "MCalibrationPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include <TOrdCollection.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TF1.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TGraph.h>
+#include <TEnv.h>
+
+ClassImp(MHCalibrationRelTimeCam);
+
+using namespace std;
+
+const Float_t MHCalibrationRelTimeCam::fgNumHiGainSaturationLimit = 0.25;
+const UInt_t  MHCalibrationRelTimeCam::fgReferencePixel = 1;
+const Int_t   MHCalibrationRelTimeCam::fgNbins      = 300;
+const Axis_t  MHCalibrationRelTimeCam::fgFirst      = -4.975;
+const Axis_t  MHCalibrationRelTimeCam::fgLast       = 10.025;
+const Float_t MHCalibrationRelTimeCam::fgProbLimit  = 0.0;
+const TString MHCalibrationRelTimeCam::gsHistName   = "RelTime";
+const TString MHCalibrationRelTimeCam::gsHistTitle  = "Arr. Times";
+const TString MHCalibrationRelTimeCam::gsHistXTitle = "Arr. Time [FADC slices]";
+const TString MHCalibrationRelTimeCam::gsHistYTitle = "Nr. events";
+const TString MHCalibrationRelTimeCam::fgReferenceFile = "mjobs/calibrationref.rc";
+// --------------------------------------------------------------------------
+//
+// Default Constructor.
+//
+// Sets: 
+// - fReferencePixel to fgReferencePixel
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+MHCalibrationRelTimeCam::MHCalibrationRelTimeCam(const char *name, const char *title) 
+{
+
+  fName  = name  ? name  : "MHCalibrationRelTimeCam";
+  fTitle = title ? title : "Histogram class for the relative time calibration of the camera";
+
+  SetNumHiGainSaturationLimit(fgNumHiGainSaturationLimit);
+
+  SetReferencePixel();
+
+  SetNbins(fgNbins);
+  SetFirst(fgFirst);
+  SetLast (fgLast );
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetReferenceFile();
+
+  fInnerRefTime  = 2.95;   
+  fOuterRefTime  = 3.6;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationRelTimeCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHCalibrationRelTimeCam *cam = MParList::FindObject("MHCalibrationRelTimeCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHCalibrationRelTimeCam::Clone(const char *) const
+{
+
+  MHCalibrationRelTimeCam *cam = new MHCalibrationRelTimeCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fColor                  = fColor;
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+
+  cam->fReferenceFile          = fReferenceFile;
+  cam->fInnerRefTime           = fInnerRefTime;
+  cam->fOuterRefTime           = fOuterRefTime;
+
+  //
+  // Copy the MArrays
+  //
+  cam->fAverageAreaRelSigma    = fAverageAreaRelSigma;
+  cam->fAverageAreaRelSigmaVar = fAverageAreaRelSigmaVar;
+  cam->fAverageAreaSat         = fAverageAreaSat;
+  cam->fAverageAreaSigma       = fAverageAreaSigma;
+  cam->fAverageAreaSigmaVar    = fAverageAreaSigmaVar;
+  cam->fAverageAreaNum         = fAverageAreaNum;
+  cam->fAverageSectorNum       = fAverageSectorNum;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  if (IsLoGain())
+    {
+      
+      const Int_t navlo = fAverageLoGainAreas->GetSize();
+      for (int i=0; i<navlo; i++)
+        cam->fAverageLoGainAreas->AddAt(GetAverageLoGainArea(i).Clone(),i);
+
+    }
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MCalibrationRelTimeCam
+//
+// Searches pointer to:
+// - MArrivalTimeCam
+//
+// Calls:
+// - MHCalibrationCam::InitHiGainArrays()
+// - MHCalibrationCam::InitLoGainArrays()
+// 
+// Sets:
+// - fSumareahi   to nareas
+// - fSumarealo   to nareas
+// - fSumsectorhi to nareas
+// - fSumsectorlo to nareas
+// - fNumareahi   to nareas
+// - fNumarealo   to nareas
+// - fNumsectorhi to nareas
+// - fNumsectorlo to nareas
+//
+Bool_t MHCalibrationRelTimeCam::ReInitHists(MParList *pList)
+{
+
+  if (!InitCams(pList,"RelTime"))
+    return kFALSE;
+
+  MArrivalTimeCam *signal = (MArrivalTimeCam*)pList->FindObject("MArrivalTimeCam");
+  if (!signal)
+  {
+      *fLog << err << "MArrivalTimeCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  fSumareahi  .Set(nareas); 
+  fSumarealo  .Set(nareas);
+  fSumsectorhi.Set(nsectors); 
+  fSumsectorlo.Set(nsectors);
+  fNumareahi  .Set(nareas); 
+  fNumarealo  .Set(nareas);
+  fNumsectorhi.Set(nsectors); 
+  fNumsectorlo.Set(nsectors);
+
+  return kTRUE;
+}
+
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MArrivalTimeCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain or LoGain histograms (MHGausEvents::FillHistAndArray()), respectively
+// depending on MArrivalTimePix::IsLoGainUsed(), with:
+// - MArrivalTimePix::GetArrivalTime(pixid) - MArrivalTimePix::GetArrivalTime(1);
+//   (i.e. the time difference between pixel i and pixel 1 (hardware number: 2) )
+//
+Bool_t MHCalibrationRelTimeCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MArrivalTimeCam *arrtime = (MArrivalTimeCam*)par;
+  if (!arrtime)
+    {
+      gLog << err << "No argument in MArrivalTime::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  fSumareahi  .Reset();
+  fSumarealo  .Reset();
+  fSumsectorhi.Reset(); 
+  fSumsectorlo.Reset();
+  fNumareahi  .Reset(); 
+  fNumarealo  .Reset();
+  fNumsectorhi.Reset(); 
+  fNumsectorlo.Reset();
+
+  const MArrivalTimePix &refpix = (*arrtime)[fReferencePixel];
+  const Float_t reftime = refpix.IsLoGainUsed() 
+     ? refpix.GetArrivalTimeLoGain() : refpix.GetArrivalTimeHiGain();
+
+  for (Int_t i=0; i<npixels; i++)
+    {
+
+      MHCalibrationPix &histhi = (*this)[i];
+
+      if (histhi.IsExcluded())
+	continue;
+
+      const MArrivalTimePix &pix = (*arrtime)[i];
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      if (pix.IsLoGainUsed() && IsLoGain())
+        { 
+          const Float_t time = pix.GetArrivalTimeLoGain();
+          histhi.AddSaturated(1); 
+
+          MHCalibrationPix &histlo = (*this)(i);
+          histlo.FillHistAndArray(time-reftime);
+
+          fSumarealo  [aidx]   += time;
+          fNumarealo  [aidx]   ++;
+          fSumsectorlo[sector] += time;
+          fNumsectorlo[sector] ++;
+        }
+      else
+        {
+          const Float_t time = pix.GetArrivalTimeHiGain();
+
+          histhi.FillHistAndArray(time-reftime) ;
+          fSumareahi  [aidx]   += time;
+          fNumareahi  [aidx]   ++;
+          fSumsectorhi[sector] += time;
+          fNumsectorhi[sector] ++;
+        }
+    }
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(fNumareahi[j] == 0 ? 0. : fSumareahi[j]/fNumareahi[j]);
+
+      if (IsLoGain())
+        {
+          MHCalibrationPix &histlo = GetAverageLoGainArea(j);
+          histlo.FillHistAndArray(fNumarealo[j] == 0 ? 0. : fSumarealo[j]/fNumarealo[j]);
+        }
+    }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(fNumsectorhi[j] == 0 ? 0. : fSumsectorhi[j]/fNumsectorhi[j]);
+
+      if (IsLoGain())
+        {
+          MHCalibrationPix &histlo = GetAverageLoGainSector(j);
+          histlo.FillHistAndArray(fNumsectorlo[j] == 0 ? 0. : fSumsectorlo[j]/fNumsectorlo[j]);
+        }
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with flags:
+//   MBadPixelsPix::kRelTimeNotFitted and MBadPixelsPix::kRelTimeOscillating
+// - MHCalibrationCam::FitLoGainArrays() with flags:
+//   MBadPixelsPix::kRelTimeNotFitted and MBadPixelsPix::kRelTimeOscillating
+// 
+Bool_t MHCalibrationRelTimeCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  MCalibrationCam *relcam = fIntensCam ? fIntensCam->GetCam() : fCam;
+  MBadPixelsCam   *badcam = fIntensBad ? fIntensBad->GetCam() : fBadPixels;
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  const Int_t nsectors = fAverageHiGainSectors->GetSize();
+
+  TArrayI satarea(nareas);
+  TArrayI satsect(nsectors);
+  fNumareahi  .Reset(); 
+  fNumsectorhi.Reset(); 
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &histhi = (*this)[i];
+
+      if (histhi.IsExcluded())
+        continue;
+      
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*relcam)[i] ;
+
+      fNumareahi[aidx]++;
+      fNumsectorhi[sector]++;
+      //
+      // Check saturation
+      // 
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          histhi.SetExcluded();
+          satarea[aidx]++;
+          satsect[sector]++;
+        }
+      else
+        if (IsLoGain())
+          (*this)(i).SetExcluded();
+
+      //
+      // Check histogram overflow
+      // 
+      CheckOverflow(histhi);
+      if (IsLoGain())
+        CheckOverflow((*this)(i));
+
+    }
+
+  for (Int_t j=0; j<nareas; j++)
+    {
+      
+      MHCalibrationPix     &histhi = GetAverageHiGainArea(j);      
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)relcam->GetAverageArea(j);
+
+      if (satarea[j] > 0.5*fNumareahi[j])
+        {
+          pix.SetHiGainSaturation();
+          histhi.SetExcluded();
+        }
+      else
+        if (IsLoGain())
+          GetAverageLoGainArea(j).SetExcluded();
+
+      //
+      // Check histogram overflow
+      // 
+      CheckOverflow(histhi);
+      if (IsLoGain())
+        CheckOverflow(GetAverageLoGainArea(j));
+   }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);      
+      MCalibrationRelTimePix  &pix = (MCalibrationRelTimePix&)relcam->GetAverageSector(j) ;
+
+      if (satsect[j] > 0.5*fNumsectorhi[j])
+        {
+          pix.SetHiGainSaturation();
+          histhi.SetExcluded();
+        }
+      else
+        if (IsLoGain())        
+          GetAverageLoGainSector(j).SetExcluded();
+
+      //
+      // Check histogram overflow
+      // 
+      CheckOverflow(histhi);
+      if (IsLoGain())
+        CheckOverflow(GetAverageLoGainSector(j));
+    }
+
+  FitHiGainArrays(*relcam,*badcam,
+                  MBadPixelsPix::kRelTimeNotFitted,
+                  MBadPixelsPix::kRelTimeOscillating);
+  
+  if (IsLoGain())        
+    FitLoGainArrays(*relcam,*badcam,
+                    MBadPixelsPix::kRelTimeNotFitted,
+                    MBadPixelsPix::kRelTimeOscillating);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets all pixels to MBadPixelsPix::kUnreliableRun, if following flags are set:
+// - MBadPixelsPix::kRelTimeNotFitted
+// - MBadPixelsPix::kRelTimeOscillating
+//
+void MHCalibrationRelTimeCam::FinalizeBadPixels()
+{
+
+  MBadPixelsCam *badcam = fIntensBad ? fIntensBad->GetCam() : fBadPixels;
+
+  for (Int_t i=0; i<badcam->GetSize(); i++)
+    {
+      MBadPixelsPix          &bad    = (*badcam)[i];
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kRelTimeNotFitted ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kRelTimeOscillating))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+      
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Mean Relative Arrival Time in FADC slices  (MHGausEvents::GetMean()
+// 1: Error Mean Relative Arrival Time in FADC slices   (MHGausEvents::GetMeanErr()
+// 2: Sigma fitted Relative Arrival Time in FADC slices (MHGausEvents::GetSigma()
+// 3: Error Sigma Relative Arrival Time in FADC slices  (MHGausEvents::GetSigmaErr()
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit              (calls: MHGausEvents::GetProb())
+//
+// Localized defects:
+// ==================
+//
+// 5: Gaus fit not OK                               (calls: MHGausEvents::IsGausFitOK())
+// 6: Fourier spectrum not OK                       (calls: MHGausEvents::IsFourierSpectrumOK())
+//
+Bool_t MHCalibrationRelTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  const MHCalibrationPix &pix = (*this)[idx];
+
+  switch (type)
+    {
+    case 0:
+      val = pix.GetMean();
+      break;
+    case 1:
+      val = pix.GetMeanErr();
+      break;
+    case 2:
+      val = pix.GetSigma();
+      break;
+    case 3:
+      val = pix.GetSigmaErr();
+      break;
+    case 4:
+      val = pix.GetProb();
+      break;
+    case 5:
+      if (!pix.IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!pix.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationRelTimeCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationRelTimeCam::Draw(const Option_t *opt)
+{
+
+  const Int_t nareas = fAverageHiGainAreas->GetSize();
+  if (nareas == 0)
+    return;
+
+  TString option(opt);
+  option.ToLower();
+
+  if (!option.Contains("datacheck"))
+    {
+      MHCalibrationCam::Draw(opt);
+      return;
+    }
+
+  // 
+  // From here on , the datacheck - Draw
+  //
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+  pad->Divide(1,nareas);
+
+  //
+  // Loop over inner and outer pixels
+  //  
+  for (Int_t i=0; i<nareas;i++) 
+     {
+       
+       pad->cd(i+1);
+       
+       MHCalibrationPix &hipix = GetAverageHiGainArea(i);
+       //
+       // Ask for Hi-Gain saturation
+       //
+       if (hipix.IsExcluded() && IsLoGain())
+        {
+           MHCalibrationPix &lopix = GetAverageLoGainArea(i);
+           DrawDataCheckPixel(lopix,i ? fOuterRefTime+1.5 : fInnerRefTime+1.5);
+         }
+       else
+         DrawDataCheckPixel(hipix,i ? fOuterRefTime : fInnerRefTime);
+    }      
+}
+
+void MHCalibrationRelTimeCam::CheckOverflow( MHCalibrationPix &pix )
+{
+
+  if (pix.IsExcluded())
+    return;
+
+  TH1F *hist = pix.GetHGausHist();
+  
+  Stat_t overflow = hist->GetBinContent(hist->GetNbinsX()+1);
+  if (overflow > fOverflowLimit*hist->GetEntries())
+    {
+      *fLog << warn << "HiGain Hist-overflow " << overflow
+            << " times in " << pix.GetName() << " (w/o saturation!) " << endl;
+    }
+  
+  overflow = hist->GetBinContent(0);
+  if (overflow > fOverflowLimit*hist->GetEntries())
+    {
+      *fLog << warn << "HiGain Hist-underflow " << overflow
+            << " times in " << pix.GetName() << " (w/o saturation!) " << endl;
+    }
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Draw the average pixel for the datacheck:
+//
+// Displays the averaged areas, both High Gain and Low Gain 
+//
+// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
+//
+void MHCalibrationRelTimeCam::DrawDataCheckPixel(MHCalibrationPix &pix, const Float_t refline)
+{
+  
+  TVirtualPad *newpad = gPad;
+  newpad->Divide(1,2);
+  newpad->cd(1);
+  
+  gPad->SetTicks();
+  if (!pix.IsEmpty() && !pix.IsOnlyOverflow() && !pix.IsOnlyUnderflow())
+    gPad->SetLogy();
+
+  TH1F *hist = pix.GetHGausHist();
+  
+  TH1F *null = new TH1F("Null",hist->GetTitle(),100,0.,pix.GetLast());
+
+  null->SetMaximum(1.1*hist->GetMaximum());
+  null->SetDirectory(NULL);
+  null->SetBit(kCanDelete);
+  null->SetStats(kFALSE);
+  //
+  // set the labels bigger
+  //
+  TAxis *xaxe = null->GetXaxis();
+  TAxis *yaxe = null->GetYaxis();
+  xaxe->CenterTitle();
+  yaxe->CenterTitle();    
+  xaxe->SetTitleSize(0.07);
+  yaxe->SetTitleSize(0.07);    
+  xaxe->SetTitleOffset(0.65);
+  yaxe->SetTitleOffset(0.55);    
+  xaxe->SetLabelSize(0.06);
+  yaxe->SetLabelSize(0.06);    
+  xaxe->SetTitle(hist->GetXaxis()->GetTitle());
+  yaxe->SetTitle(hist->GetYaxis()->GetTitle());  
+
+  null->Draw();
+  hist->Draw("same");
+
+  gStyle->SetOptFit();
+
+  TF1 *fit = pix.GetFGausFit();
+
+  if (fit)
+  {
+    switch ( fColor )
+      {
+      case MCalibrationCam::kGREEN:
+        fit->SetLineColor(kGreen);
+        break;
+      case MCalibrationCam::kBLUE:
+        fit->SetLineColor(kBlue);
+        break;
+      case MCalibrationCam::kUV:  
+        fit->SetLineColor(106);
+        break;
+      case MCalibrationCam::kCT1: 
+        fit->SetLineColor(006);
+        break;
+      default:
+        fit->SetLineColor(kRed);
+      }
+    fit->Draw("same");
+  }
+
+  DisplayRefLines(null,refline);
+
+  newpad->cd(2);
+  gPad->SetTicks();
+
+  TH1F *null2 = new TH1F("Null2",hist->GetTitle(),100,0.,pix.GetEvents()->GetSize()/pix.GetEventFrequency());
+
+  null2->SetMinimum(pix.GetMean()-10.*pix.GetSigma());
+  null2->SetMaximum(pix.GetMean()+10.*pix.GetSigma());
+  null2->SetDirectory(NULL);
+  null2->SetBit(kCanDelete);
+  null2->SetStats(kFALSE);
+  //
+  // set the labels bigger
+  //
+  TAxis *xaxe2 = null2->GetXaxis();
+  TAxis *yaxe2 = null2->GetYaxis();
+  xaxe2->CenterTitle();
+  yaxe2->CenterTitle();    
+  xaxe2->SetTitleSize(0.07);
+  yaxe2->SetTitleSize(0.07);    
+  xaxe2->SetTitleOffset(0.65);
+  yaxe2->SetTitleOffset(0.55);    
+  xaxe2->SetLabelSize(0.06);
+  yaxe2->SetLabelSize(0.06);    
+  
+  pix.CreateGraphEvents();
+  TGraph *gr = pix.GetGraphEvents();
+
+  xaxe2->SetTitle(gr->GetXaxis()->GetTitle());
+  yaxe2->SetTitle(gr->GetYaxis()->GetTitle());  
+
+  null2->Draw();
+
+  pix.DrawEvents("same");
+
+  return;
+}
+
+void  MHCalibrationRelTimeCam::DisplayRefLines(const TH1F *hist, const Float_t refline) const
+{
+
+  TGraph *gr = new TGraph(2);
+  gr->SetPoint(0,refline,0.);
+  gr->SetPoint(1,refline,hist->GetMaximum());
+  gr->SetBit(kCanDelete);
+  gr->SetLineColor(kGreen);
+  gr->SetLineStyle(2);
+  gr->SetLineWidth(3);
+  gr->Draw("L");
+
+  TLegend *leg = new TLegend(0.75,0.7,0.99,0.99);
+  leg->SetBit(kCanDelete);
+  leg->AddEntry(gr,"Trigger Calibration","l");
+  leg->Draw();
+}
+
+Int_t MHCalibrationRelTimeCam::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (IsEnvDefined(env, prefix, "ReferenceFile", print))
+    {
+      SetReferenceFile(GetEnvValue(env,prefix,"ReferenceFile",fReferenceFile.Data()));
+      rc = kTRUE;
+    }
+
+  TEnv refenv(fReferenceFile);
+
+  fInnerRefTime = refenv.GetValue("InnerRefTime",fInnerRefTime);
+  fOuterRefTime = refenv.GetValue("OuterRefTime",fOuterRefTime);
+
+  return MHCalibrationCam::ReadEnv(env,prefix,print) ? kTRUE : rc;
+
+}
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationRelTimeCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationRelTimeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationRelTimeCam.h	(revision 9772)
@@ -0,0 +1,86 @@
+#ifndef MARS_MHCalibrationRelTimeCam
+#define MARS_MHCalibrationRelTimeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class TH1F;
+class MGeomCam;
+class MHCalibrationRelTimeCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Float_t fgNumHiGainSaturationLimit;   //! The default for fNumHiGainSaturationLimit (now at: 0.25)
+  static const UInt_t  fgReferencePixel;             //! Default for fReferencePixel   (now set to: 1)
+  static const Int_t   fgNbins;                      //! Default number of bins        (now set to: 900   )
+  static const Axis_t  fgFirst;                      //! Default lower histogram limit (now set to: -13.5 )
+  static const Axis_t  fgLast;                       //! Default upper histogram limit (now set to:  13.5 )
+  static const Float_t fgProbLimit;                  //! The default for fProbLimit    (now set to: 0.0)  
+  
+  static const TString gsHistName;                   //! Default Histogram names
+  static const TString gsHistTitle;                  //! Default Histogram titles
+  static const TString gsHistXTitle;                 //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;                 //! Default Histogram y-axis titles
+  
+  static const TString fgReferenceFile;              //! default for fReferenceFile ("mjobs/calibrationref.rc")
+
+  UInt_t  fReferencePixel;                           // The reference pixel for rel. times
+  Float_t fInnerRefTime;                             // The reference mean arrival time inner pixels
+  Float_t fOuterRefTime;                             // The reference mean arrival time outer pixels
+
+  TString  fReferenceFile;                           // File name containing the reference values
+
+  MArrayD fSumareahi  ;                              //
+  MArrayD fSumarealo  ;                              //
+  MArrayD fSumsectorhi;                              //
+  MArrayD fSumsectorlo;                              //
+  MArrayI fNumareahi  ;                              //
+  MArrayI fNumarealo  ;                              //
+  MArrayI fNumsectorhi;                              //
+  MArrayI fNumsectorlo;                              //
+
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  void   FinalizeBadPixels();
+
+  void   CheckOverflow( MHCalibrationPix &pix);
+  void   DrawDataCheckPixel(MHCalibrationPix &pix, const Float_t refline);
+  void   DisplayRefLines( const TH1F *hist, const Float_t refline) const;
+
+  Int_t  ReadEnv ( const TEnv &env, TString prefix, Bool_t print );
+  
+public:
+
+  MHCalibrationRelTimeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationRelTimeCam() {}
+
+  UInt_t GetReferencePixel() const { return fReferencePixel; }
+
+  // Clone
+  TObject *Clone(const char *name="") const;
+
+  // Setters
+  void  SetReferencePixel( const UInt_t i=fgReferencePixel   ) { fReferencePixel = i;   }
+  void  SetReferenceFile ( const TString ref=fgReferenceFile ) { fReferenceFile  = ref; }
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  // Draw
+  void Draw(const Option_t *opt);
+
+  ClassDef(MHCalibrationRelTimeCam, 1)	// Histogram class for Relative Time Camera Calibration
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationTestCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationTestCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationTestCam.cc	(revision 9772)
@@ -0,0 +1,473 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!              
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                        
+// MHCalibrationTestCam                                                
+//                                                                        
+// Fills the calibrated signal from an MSignalCam into 
+// MHCalibrationPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray  
+//   or MHCalibrationCam::fHiGainArray, respectively.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors 
+//   and MHCalibrationCam::fAverageHiGainSectors 
+//
+// The signals are filled into a histogram and an array, in order to perform 
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an 
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the 
+// projected fourier components follow an exponential distribution. 
+// In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun      )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into an MCalibrationCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//                                                                         
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationTestCam.h"
+
+#include "MHCalibrationPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationCam.h"
+#include "MCalibrationPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MHCalibrationTestCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationTestCam::fgNbins    = 1000;
+const Axis_t  MHCalibrationTestCam::fgFirst    = -1.;
+const Axis_t  MHCalibrationTestCam::fgLast     = 1999.;
+const Float_t MHCalibrationTestCam::fgProbLimit  = 0.00000001;
+const TString MHCalibrationTestCam::gsHistName   = "Test";
+const TString MHCalibrationTestCam::gsHistTitle  = "Calibrated Calibration Signals";  
+const TString MHCalibrationTestCam::gsHistXTitle = "Nr. Photons";
+const TString MHCalibrationTestCam::gsHistYTitle = "Nr. events";
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+MHCalibrationTestCam::MHCalibrationTestCam(const char *name, const char *title) 
+{
+
+  fName  = name  ? name  : "MHCalibrationTestCam";
+  fTitle = title ? title : "Histogram class for testing the calibration";
+  
+  SetNbins(fgNbins);
+  SetFirst(fgFirst);
+  SetLast (fgLast );
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetLoGain(kFALSE);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches pointer to:
+// - MSignalCam
+//
+// Calls:
+// - MHCalibrationCam::InitHiGainArrays()
+// 
+// Sets: 
+// - SetLoGain(kFALSE);
+// - fMeanMeanPhotPerArea to nareas
+// - fRmsMeanPhotPerArea  to nareas
+// - fMeanSigmaPhotPerArea to nareas
+// - fRmsSigmaPhotPerArea  to nareas
+//
+Bool_t MHCalibrationTestCam::ReInitHists(MParList *pList)
+{
+
+  if (!InitCams(pList,"Test"))
+    return kFALSE;
+
+
+  MSignalCam *signal = (MSignalCam*)pList->FindObject("MSignalCam");
+  if (!signal)
+  {
+      *fLog << err << "MSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  fMeanMeanPhotPerArea.Set(nareas);   
+  fRmsMeanPhotPerArea .Set(nareas); 
+  fMeanSigmaPhotPerArea.Set(nareas);  
+  fRmsSigmaPhotPerArea.Set(nareas);
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MSignalCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain histograms (MHGausEvents::FillHistAndArray())
+// with:
+// - MSignalPix::GetNumPhotons(pixid);
+//
+Bool_t MHCalibrationTestCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MSignalCam *calibration = (MSignalCam*)par;
+  if (!calibration)
+    {
+      gLog << err << "No argument in MHCalibrationTestCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  TArrayF sumareahi  (nareas); 
+  TArrayF sumsectorhi(nsectors);
+  TArrayI numareahi  (nareas); 
+  TArrayI numsectorhi(nsectors);
+  
+  for (Int_t i=0; i<npixels; i++)
+    {
+
+      MHCalibrationPix &histhi = (*this)[i];
+
+      const MSignalPix *pix = calibration->GetPixById(i);
+      if (!pix)
+        continue;
+
+      const Float_t   signal = pix->GetNumPhotons();
+
+      if (signal < 0.0001)
+        continue;
+      
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      histhi.FillHistAndArray(signal) ;
+
+      sumareahi  [aidx]   += signal;
+      numareahi  [aidx]   ++;
+      sumsectorhi[sector] += signal;
+      numsectorhi[sector] ++;
+    }
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+    }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with flags:
+//   MBadPixelsPix::kTestNotFitted and MBadPixelsPix::kTestOscillating
+// 
+Bool_t MHCalibrationTestCam::FinalizeHists()
+{
+
+  *fLog << endl;
+
+  TArrayI numaidx;
+  numaidx.Set(fGeom->GetNumAreas());
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)[i];
+      
+      if (hist.IsEmpty())
+        continue;
+
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          hist.BypassFit();
+      
+      hist.CreateFourierSpectrum();
+      
+      const Float_t area = (*fGeom)[i].GetA();
+      const Int_t   aidx = (*fGeom)[i].GetAidx();
+
+      fMeanMeanPhotPerArea[aidx]  += hist.GetMean() / area;
+      fRmsMeanPhotPerArea [aidx]  += hist.GetMean() / area * hist.GetMean()  / area;
+      fMeanSigmaPhotPerArea[aidx] += hist.GetSigma()/ area;
+      fRmsSigmaPhotPerArea [aidx] += hist.GetSigma()/ area * hist.GetSigma() / area;
+      numaidx[aidx]++;
+    }
+
+
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix     &hist = GetAverageHiGainArea(j);      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          hist.BypassFit();
+      
+      hist.CreateFourierSpectrum();
+      
+      fRmsMeanPhotPerArea [j]  -= fMeanMeanPhotPerArea [j]*fMeanMeanPhotPerArea [j]/numaidx[j];
+      fRmsSigmaPhotPerArea[j]  -= fMeanSigmaPhotPerArea[j]*fMeanSigmaPhotPerArea[j]/numaidx[j];
+
+      fMeanMeanPhotPerArea [j]  /=  numaidx[j];
+      fMeanSigmaPhotPerArea[j]  /=  numaidx[j];
+      fRmsMeanPhotPerArea  [j]  /=  numaidx[j]-1.;
+      fRmsSigmaPhotPerArea [j]  /=  numaidx[j]-1.; 
+
+      if (fRmsMeanPhotPerArea  [j] > 0.)
+        fRmsMeanPhotPerArea  [j]  =  TMath::Sqrt(fRmsMeanPhotPerArea  [j]);
+      if (fRmsSigmaPhotPerArea [j] > 0.)
+        fRmsSigmaPhotPerArea [j]  =  TMath::Sqrt(fRmsSigmaPhotPerArea [j]);
+  }
+
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationPix     &hist = GetAverageHiGainSector(j);      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          hist.BypassFit();
+
+      hist.CreateFourierSpectrum();
+    }
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Mean Test Calibration (MHGausEvents::GetMean())
+// 1: Error Mean Test Calibration  (MHGausEvents::GetMeanErr())
+// 2: Sigma fitted Test Calibration (MHGausEvents::GetSigma())
+// 3: Error Sigma Test Calibration (MHGausEvents::GetSigmaErr())
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit              (calls: MHGausEvents::GetProb())
+//
+// Localized defects:
+// ==================
+//
+// 5: Gaus fit not OK                               (calls: MHGausEvents::IsGausFitOK())
+// 6: Fourier spectrum not OK                       (calls: MHGausEvents::IsFourierSpectrumOK())
+//
+// Converted values:
+// =================
+//
+// 7:  Fitted Mean Test Calibration   (MHGausEvents::GetMean())     by MGeomPix::GetA()
+// 8:  Fitted Mean Error Calibration  (MHGausEvents::GetMeanErr())  by MGeomPix::GetA()
+// 9:  Fitted Sigma Test Calibration  (MHGausEvents::GetSigma())    by MGeomPix::GetA()
+// 10: Fitted Sigma Error Calibration (MHGausEvents::GetSigmaErr()) by MGeomPix::GetA()
+//
+Bool_t MHCalibrationTestCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  const MHCalibrationPix &pix = (*this)[idx];
+
+  if (pix.IsEmpty())
+    return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      val = pix.GetMean();
+      break;
+    case 1:
+      val = pix.GetMeanErr();
+      break;
+    case 2:
+      val = pix.GetSigma();
+      break;
+    case 3:
+      val = pix.GetSigmaErr();
+      break;
+    case 4:
+      val = pix.GetProb();
+      break;
+    case 5:
+      if (!pix.IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!pix.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    case 7:
+      val = pix.GetMean()/cam[idx].GetA();
+      break;
+    case 8:
+      val = pix.GetMeanErr()/cam[idx].GetA();
+      break;
+    case 9:
+      val = pix.GetSigma()/cam[idx].GetA();
+      break;
+    case 10:
+      val = pix.GetSigmaErr()/cam[idx].GetA();
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationTestCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
+
+
+//------------------------------------------------------------
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels
+//
+void MHCalibrationTestCam::CalcAverageSigma()
+{
+  
+  for (UInt_t j=0; j<fGeom->GetNumAreas(); j++)
+    {
+  
+      MHCalibrationPix &hist    = GetAverageHiGainArea(j);
+
+      const Float_t numsqr    = TMath::Sqrt((Float_t)fAverageAreaNum[j]);
+      fAverageAreaSigma[j]    = hist.GetSigma    () * numsqr;
+      fAverageAreaSigmaVar[j] = hist.GetSigmaErr () * hist.GetSigmaErr() * numsqr;
+
+      fAverageAreaRelSigma   [j]  = fAverageAreaSigma[j]    / hist.GetMean();
+      fAverageAreaRelSigmaVar[j]  = fAverageAreaSigmaVar[j] / (fAverageAreaSigma[j]*fAverageAreaSigma[j]);
+      fAverageAreaRelSigmaVar[j] += hist.GetMeanErr()*hist.GetMeanErr()/hist.GetMean()/hist.GetMean();
+      fAverageAreaRelSigmaVar[j] *= fAverageAreaRelSigma[j];
+    }
+}
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationTestCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationTestCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationTestCam.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MHCalibrationTestCam
+#define MARS_MHCalibrationTestCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include <MArrayF.h>
+#endif
+#ifndef MARS_MArrayI
+#include <MArrayI.h>
+#endif
+
+class MHCalibrationTestCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Int_t   fgNbins;        //! Default for fNBins  (now set to: 2000  )
+  static const Axis_t  fgFirst;        //! Default for fFirst  (now set to: -0.5  )
+  static const Axis_t  fgLast;         //! Default for fLast   (now set to: 1999.5)
+  static const Float_t fgProbLimit;    //! The default for fProbLimit (now set to: 0.0000001)  
+  
+  static const TString gsHistName;     //! Default Histogram names
+  static const TString gsHistTitle;    //! Default Histogram titles
+  static const TString gsHistXTitle;   //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;   //! Default Histogram y-axis titles
+  
+  MArrayF fMeanMeanPhotPerArea;
+  MArrayF fRmsMeanPhotPerArea   ;
+  MArrayF fMeanSigmaPhotPerArea;
+  MArrayF fRmsSigmaPhotPerArea   ;
+
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+
+public:
+
+  MHCalibrationTestCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationTestCam() {}
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  const Float_t  GetMeanMeanPhotPerArea  ( const Int_t aidx ) const { return fMeanMeanPhotPerArea  [aidx]; }
+  const Float_t  GetMeanSigmaPhotPerArea ( const Int_t aidx ) const { return fMeanSigmaPhotPerArea [aidx]; }
+  const Float_t  GetRmsMeanPhotPerArea   ( const Int_t aidx ) const { return fRmsMeanPhotPerArea   [aidx]; }
+  const Float_t  GetRmsSigmaPhotPerArea  ( const Int_t aidx ) const { return fRmsSigmaPhotPerArea  [aidx]; }
+
+  void CalcAverageSigma();
+  
+  ClassDef(MHCalibrationTestCam, 1)	// Histogram class for Relative Time Camera Calibration
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationTestPix.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationTestPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationTestPix.cc	(revision 9772)
@@ -0,0 +1,98 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationTestPix
+//
+//  Histogram class for the charge calibration. 
+//  Stores and fits the charges and stores the location of the maximum FADC 
+//  slice. Tests are taken from MExtractedSignalPix.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationTestPix.h"
+
+#include <TH1.h>
+#include <TF1.h>
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TGraph.h>
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCalibrationTestPix);
+
+using namespace std;
+
+const Int_t   MHCalibrationTestPix::fgChargeNbins     = 4000;
+const Axis_t  MHCalibrationTestPix::fgChargeFirst     = -0.5;
+const Axis_t  MHCalibrationTestPix::fgChargeLast      = 39999.5;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNbins        (fgChargeNbins)
+// - the default number for fFirst        (fgChargeFirst)
+// - the default number for fLast         (fgChargeLast)
+//
+// - the default name of the  fHGausHist ("HCalibrationTest")
+// - the default title of the fHGausHist ("Distribution of calibrated FADC slices Pixel ")
+// - the default x-axis title for fHGausHist ("Sum FADC Slices")
+// - the default y-axis title for fHGausHist ("Nr. of events")
+//
+// Calls:
+// - Clear();
+//
+MHCalibrationTestPix::MHCalibrationTestPix(const char *name, const char *title)
+{ 
+  
+  fName  = name  ? name  : "MHCalibrationTestPix";
+  fTitle = title ? title : "Statistics of the calibrated FADC sums of calibration events";
+
+  SetNbins ( fgChargeNbins );
+  SetFirst ( fgChargeFirst );
+  SetLast  ( fgChargeLast  );
+
+  fHGausHist.SetName("HCalibrationTest");
+  fHGausHist.SetTitle("Distribution of calibrated Photons Pixel ");  
+  fHGausHist.SetXTitle("Nr. Photons");
+  fHGausHist.SetYTitle("Nr. of events");
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// returns fHGausHist.Integral("width")
+//
+const Float_t MHCalibrationTestPix::GetIntegral() const 
+{ 
+   return fHGausHist.Integral("width");  
+}
+
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationTestPix.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationTestPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationTestPix.h	(revision 9772)
@@ -0,0 +1,27 @@
+#ifndef MARS_MHCalibrationTestPix
+#define MARS_MHCalibrationTestPix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+class MHCalibrationTestPix : public MHCalibrationPix
+{
+
+private:
+
+  static const Int_t   fgChargeNbins;        // Default for fNBins          (now set to: 2000  )
+  static const Axis_t  fgChargeFirst;        // Default for fFirst          (now set to: -0.5  )
+  static const Axis_t  fgChargeLast;         // Default for fLast           (now set to: 1999.5)
+
+public:
+
+  MHCalibrationTestPix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationTestPix() {}
+
+  const Float_t  GetIntegral()          const;
+  
+  ClassDef(MHCalibrationTestPix, 1)     // Base Histogram class for Test Pixel Calibration
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationTestTimeCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationTestTimeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationTestTimeCam.cc	(revision 9772)
@@ -0,0 +1,421 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!              
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                                        
+// MHCalibrationTestTimeCam                                                
+//                                                                        
+// Fills the calibrated signal from an MArrivalTime into 
+// MHCalibrationTestTimePix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray  
+//   or MHCalibrationCam::fHiGainArray, respectively.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors 
+//   and MHCalibrationCam::fAverageHiGainSectors 
+//
+// The signals are filled into a histogram and an array, in order to perform 
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an 
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors 
+// and the fit probability are extracted. If none of these values are NaN's and 
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%), 
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean 
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHCalibrationPix::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    ) 
+// 
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup) 
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier 
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the 
+// projected fourier components follow an exponential distribution. 
+// In case that the probability of the exponential fit is less than 
+// MHGausEvents::fProbLimit (default: 0.5%), the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kHiGainOscillating ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun      )
+// 
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into an MCalibrationCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels in order to be able to compare it to the average of 
+// sigmas in the camera.
+//                                                                         
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationTestTimeCam.h"
+
+#include "MHCalibrationPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationCam.h"
+#include "MCalibrationPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MHCalibrationTestTimeCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationTestTimeCam::fgNbins      = 300;
+const Axis_t  MHCalibrationTestTimeCam::fgFirst      = -0.025;
+const Axis_t  MHCalibrationTestTimeCam::fgLast       = 14.975;
+const Float_t MHCalibrationTestTimeCam::fgProbLimit  = 0.00000001;
+const TString MHCalibrationTestTimeCam::gsHistName   = "TestTime";
+const TString MHCalibrationTestTimeCam::gsHistTitle  = "Calibrated Calibration Arrival Times";  
+const TString MHCalibrationTestTimeCam::gsHistXTitle = "Arrival Time [FADC slices]";
+const TString MHCalibrationTestTimeCam::gsHistYTitle = "Nr. events";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+MHCalibrationTestTimeCam::MHCalibrationTestTimeCam(const char *name, const char *title) 
+{
+
+  fName  = name  ? name  : "MHCalibrationTestTimeCam";
+  fTitle = title ? title : "Histogram class for testing the calibration of arrival times";
+
+  SetNbins(fgNbins);
+  SetFirst(fgFirst);
+  SetLast (fgLast );
+
+  SetProbLimit(fgProbLimit);
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetLoGain(kFALSE);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches pointer to:
+// - MArrivalTime
+//
+// Calls:
+// - MHCalibrationCam::InitHiGainArrays()
+// 
+// Sets: 
+// - SetLoGain(kFALSE);
+//
+Bool_t MHCalibrationTestTimeCam::ReInitHists(MParList *pList)
+{
+
+  if (!InitCams(pList,""))
+    return kFALSE;
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  InitHiGainArrays(npixels,nareas,nsectors);
+  InitLoGainArrays(npixels,nareas,nsectors);
+
+  return kTRUE;
+}
+
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MArrivalTime:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain histograms (MHGausEvents::FillHistAndArray())
+// with:
+// - MArrivalTime::GetArrivalTime(pixid) - MArrivalTime::GetArrivalTime(1);
+//   (i.e. the time difference between pixel i and pixel 1 (hardware number: 2) )
+//
+Bool_t MHCalibrationTestTimeCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MSignalCam *calibration = (MSignalCam*)par;
+  if (!calibration)
+    {
+      gLog << err << "No argument in MHCalibrationRelTimeCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+
+  TArrayF sumareahi  (nareas); 
+  TArrayF sumsectorhi(nsectors);
+  TArrayI numareahi  (nareas); 
+  TArrayI numsectorhi(nsectors);
+
+  for (Int_t i=0; i<npixels; i++)
+    {
+
+      MHCalibrationPix &histhi = (*this)[i];
+
+      if (histhi.IsExcluded())
+	continue;
+
+      const Float_t  time = (*calibration)[i].GetArrivalTime();
+      const Int_t  aidx   = (*fGeom)[i].GetAidx();
+      const Int_t  sector = (*fGeom)[i].GetSector();
+
+      histhi.FillHistAndArray(time) ;
+      sumareahi  [aidx]   += time;
+      numareahi  [aidx]   ++;
+      sumsectorhi[sector] += time;
+      numsectorhi[sector] ++;
+    }
+  
+  for (Int_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+
+    }
+  
+  for (Int_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+Bool_t MHCalibrationTestTimeCam::FinalizeHists()
+{
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationPix &hist = (*this)[i];
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          {
+            hist.BypassFit();
+          }
+      
+      hist.CreateFourierSpectrum();
+      
+    }
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix     &hist = GetAverageHiGainArea(j);      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          {
+            hist.BypassFit();
+          }
+      
+      hist.CreateFourierSpectrum();
+      
+
+  }
+
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationPix     &hist = GetAverageHiGainSector(j);      
+      if (hist.IsEmpty())
+        continue;
+      
+      if (!hist.FitGaus())
+        if (!hist.RepeatFit())
+          {
+            hist.BypassFit();
+          }
+      hist.CreateFourierSpectrum();
+      
+
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+void MHCalibrationTestTimeCam::FinalizeBadPixels()
+{
+
+}
+
+// --------------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Mean Time Calibration (MHGausEvents::GetMean())
+// 1: Error Mean Time Calibration  (MHGausEvents::GetMeanErr())
+// 2: Sigma fitted Time Calibration (MHGausEvents::GetSigma())
+// 3: Error Sigma Time Calibration (MHGausEvents::GetSigmaErr())
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit              (calls: MHGausEvents::GetProb())
+//
+// Localized defects:
+// ==================
+//
+// 5: Gaus fit not OK                               (calls: MHGausEvents::IsGausFitOK())
+// 6: Fourier spectrum not OK                       (calls: MHGausEvents::IsFourierSpectrumOK())
+//
+Bool_t MHCalibrationTestTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  const MHCalibrationPix &pix = (*this)[idx];
+
+  if (pix.IsExcluded())
+    return kFALSE;
+
+  switch (type)
+    {
+    case 0:
+      val = pix.GetMean();
+      break;
+    case 1:
+      val = pix.GetMeanErr();
+      break;
+    case 2:
+      val = pix.GetSigma();
+      break;
+    case 3:
+      val = pix.GetSigmaErr();
+      break;
+    case 4:
+      val = pix.GetProb();
+      break;
+    case 5:
+      if (!pix.IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!pix.IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationPix::DrawClone() for pixel idx
+//
+void MHCalibrationTestTimeCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
+
+
+//------------------------------------------------------------
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of 
+// the number involved pixels
+//
+void MHCalibrationTestTimeCam::CalcAverageSigma()
+{
+  
+  for (UInt_t j=0; j<fGeom->GetNumAreas(); j++)
+    {
+  
+      MHCalibrationPix &hist    = GetAverageHiGainArea(j);
+
+      const Float_t numsqr    = TMath::Sqrt((Float_t)fAverageAreaNum[j]);
+      fAverageAreaSigma[j]    = hist.GetSigma    () * numsqr;
+      fAverageAreaSigmaVar[j] = hist.GetSigmaErr () * hist.GetSigmaErr() * numsqr;
+
+      fAverageAreaRelSigma   [j]  = fAverageAreaSigma[j]    / hist.GetMean();
+      fAverageAreaRelSigmaVar[j]  = fAverageAreaSigmaVar[j] / (fAverageAreaSigma[j]*fAverageAreaSigma[j]);
+      fAverageAreaRelSigmaVar[j] += hist.GetMeanErr()*hist.GetMeanErr()/hist.GetMean()/hist.GetMean();
+      fAverageAreaRelSigmaVar[j] *= fAverageAreaRelSigma[j];
+    }
+}
Index: /tags/Mars-V0.9/mhcalib/MHCalibrationTestTimeCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHCalibrationTestTimeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHCalibrationTestTimeCam.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHCalibrationTestTimeCam
+#define MARS_MHCalibrationTestTimeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+class MHCalibrationTestTimeCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Int_t   fgNbins;        //! Default for fNBins  (now set to: 600  )
+  static const Axis_t  fgFirst;        //! Default for fFirst  (now set to: -0.5 )
+  static const Axis_t  fgLast;         //! Default for fLast   (now set to: 29.5 )
+  static const Float_t fgProbLimit;    //! Default for fProbLimit (now set to: 0.000001)  
+  
+  static const TString gsHistName;     //! Default Histogram names
+  static const TString gsHistTitle;    //! Default Histogram titles
+  static const TString gsHistXTitle;   //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;   //! Default Histogram y-axis titles
+  
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  void    FinalizeBadPixels();
+  
+public:
+
+  MHCalibrationTestTimeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationTestTimeCam() {}
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  void CalcAverageSigma();
+  
+  ClassDef(MHCalibrationTestTimeCam, 0)	// Histogram class for Relative Time Camera Calibration
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhcalib/MHGausEvents.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHGausEvents.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHGausEvents.cc	(revision 9772)
@@ -0,0 +1,988 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHGausEvents
+//
+//  A base class for events which are believed to follow a Gaussian distribution 
+//  with time, e.g. calibration events, observables containing white noise, ...
+//
+//  MHGausEvents derives from MH, thus all features of MH can be used by a class 
+//  deriving from MHGausEvents, especially the filling functions. 
+//
+//  The central objects are: 
+//
+//  1) The TH1F fHGausHist: 
+//     ====================
+//   
+//     It is created with a default name and title and resides in directory NULL.
+//     - Any class deriving from MHGausEvents needs to apply a binning to fHGausHist
+//       (e.g. by setting the variables fNbins, fFirst, fLast and calling the function 
+//       InitBins() or by directly calling fHGausHist.SetBins(..) )
+//     - The histogram is filled with the functions FillHist() or FillHistAndArray(). 
+//     - The histogram can be fitted with the function FitGaus(). This involves stripping 
+//       of all zeros at the lower and upper end of the histogram and re-binning to 
+//       a new number of bins, specified in the variable fBinsAfterStripping.      
+//     - The fit result's probability is compared to a reference probability fProbLimit
+//       The NDF is compared to fNDFLimit and a check is made whether results are NaNs. 
+//       Accordingly, a flag IsGausFitOK() is set.
+//     - One can repeat the fit within a given amount of sigmas from the previous mean 
+//       (specified by the variables fPickupLimit and fBlackoutLimit) with the function RepeatFit()
+// 
+//  2) The TArrayF fEvents:
+//     ==========================
+// 
+//     It is created with 0 entries and not expanded unless FillArray() or FillHistAndArray()
+//     are called.
+//     - A first call to FillArray() or FillHistAndArray() initializes fEvents by default 
+//       to 512 entries. 
+//     - Any later call to FillArray() or FillHistAndArray() fills up the array. 
+//       Reaching the limit, the array is expanded by a factor 2.
+//     - The array can be fourier-transformed into the array fPowerSpectrum. 
+//       Note that any FFT accepts only number of events which are a power of 2. 
+//       Thus, fEvents is cut to the next power of 2 smaller than its actual number of entries. 
+//       Be aware that you might lose information at the end of your analysis. 
+//     - Calling the function CreateFourierSpectrum() creates the array fPowerSpectrum 
+//       and its projection fHPowerProbability which in turn is fit to an exponential. 
+//     - The fit result's probability is compared to a referenc probability fProbLimit 
+//       and accordingly the flag IsExpFitOK() is set.
+//     - The flag IsFourierSpectrumOK() is set accordingly to IsExpFitOK(). 
+//       Later, a closer check will be installed. 
+//     - You can display all arrays by calls to: CreateGraphEvents() and 
+//       CreateGraphPowerSpectrum() and successive calls to the corresponding Getters.
+//
+// To see an example, have a look at: Draw()
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHGausEvents.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TGraph.h>
+#include <TPad.h>
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TRandom.h>
+
+#include "MFFT.h"
+#include "MArrayF.h"
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHGausEvents);
+
+using namespace std;
+
+const Int_t    MHGausEvents::fgNDFLimit             = 2;
+const Float_t  MHGausEvents::fgProbLimit            = 0.001;
+const Int_t    MHGausEvents::fgPowerProbabilityBins = 30;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+// Sets: 
+// - the default Probability Bins for fPowerProbabilityBins (fgPowerProbabilityBins)
+// - the default Probability Limit for fProbLimit  (fgProbLimit)
+// - the default NDF Limit for fNDFLimit           (fgNDFLimit)
+// - the default number of bins after stripping for fBinsAfterStipping (fgBinsAfterStipping)
+// - the default name of the fHGausHist            ("HGausHist")
+// - the default title of the fHGausHist           ("Histogram of Events with Gaussian Distribution")
+// - the default directory of the fHGausHist       (NULL)
+// - the default for fNbins (100)
+// - the default for fFirst (0.)
+// - the default for fLast  (100.)
+//
+// Initializes:
+// - fEvents to 0 entries
+// - fHGausHist()
+// - all other pointers to NULL
+// - all variables to 0.
+// - all flags to kFALSE
+//
+MHGausEvents::MHGausEvents(const char *name, const char *title)
+    : fEventFrequency(0), fFlags(0),
+      fHPowerProbability(NULL), 
+      fPowerSpectrum(NULL),
+      fFGausFit(NULL), fFExpFit(NULL),
+      fFirst(0.), 
+      fGraphEvents(NULL), fGraphPowerSpectrum(NULL),
+      fLast(100.), fNbins(100)
+{ 
+
+  fName  = name  ? name  : "MHGausEvents";
+  fTitle = title ? title : "Events with expected Gaussian distributions";
+
+  Clear();
+  
+  SetBinsAfterStripping();
+  SetNDFLimit();
+  SetPowerProbabilityBins();
+  SetProbLimit();
+
+  fHGausHist.SetName("HGausHist");
+  fHGausHist.SetTitle("Histogram of Events with Gaussian Distribution");
+  // important, other ROOT will not draw the axes:
+  fHGausHist.UseCurrentStyle();
+  fHGausHist.SetDirectory(NULL);
+  TAxis *yaxe = fHGausHist.GetYaxis();
+  yaxe->CenterTitle();
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Default Destructor. 
+//
+// Deletes (if Pointer is not NULL):
+// 
+// - fHPowerProbability
+// - fPowerSpectrum     
+// - fGraphEvents
+// - fGraphPowerSpectrum
+// 
+// - fFGausFit 
+// - fFExpFit
+//
+MHGausEvents::~MHGausEvents()
+{
+
+  //
+  // The next two lines are important for the case that 
+  // the class has been stored to a file and is read again. 
+  // In this case, the next two lines prevent a segm. violation
+  // in the destructor
+  //
+  gROOT->GetListOfFunctions()->Remove(fFGausFit);
+  gROOT->GetListOfFunctions()->Remove(fFExpFit);
+  
+  // delete fits
+  if (fFGausFit)
+      delete fFGausFit; 
+  
+  if (fFExpFit)
+      delete fFExpFit;
+
+  // delete histograms
+  if (fHPowerProbability)
+    delete fHPowerProbability;
+
+  // delete arrays
+  if (fPowerSpectrum)  
+    delete fPowerSpectrum;     
+
+  // delete graphs
+  if (fGraphEvents)
+    delete fGraphEvents;
+
+  if (fGraphPowerSpectrum)
+    delete fGraphPowerSpectrum;
+}
+      
+// --------------------------------------------------------------------------
+//
+// Default Clear(), can be overloaded.
+//
+// Sets:
+// - all other pointers to NULL
+// - all variables to 0. and keep fEventFrequency
+// - all flags to kFALSE
+// 
+// Deletes (if not NULL):
+// - all pointers
+//
+void MHGausEvents::Clear(Option_t *o)
+{
+
+  SetGausFitOK        ( kFALSE );
+  SetExpFitOK         ( kFALSE );
+  SetFourierSpectrumOK( kFALSE );
+  SetExcluded         ( kFALSE );
+
+  fMean              = 0.;
+  fSigma             = 0.;
+  fMeanErr           = 0.;
+  fSigmaErr          = 0.;
+  fProb              = 0.;
+
+  fCurrentSize       = 0;
+
+  if (fHPowerProbability)
+    {
+      delete fHPowerProbability;
+      fHPowerProbability = NULL;
+    }
+
+  // delete fits
+  if (fFGausFit)
+    {
+      delete fFGausFit; 
+      fFGausFit = NULL;
+    }
+  
+  if (fFExpFit)
+    {
+      delete fFExpFit;
+      fFExpFit = NULL;
+    }
+  
+  // delete arrays
+  if (fPowerSpectrum)  
+    {
+      delete fPowerSpectrum;     
+      fPowerSpectrum = NULL;
+    }
+
+  // delete graphs
+  if (fGraphEvents)
+    {
+      delete fGraphEvents;
+      fGraphEvents = NULL;
+    }
+
+  if (fGraphPowerSpectrum)
+    {
+      delete fGraphPowerSpectrum;
+      fGraphPowerSpectrum = NULL;
+    }
+}
+
+
+
+// -----------------------------------------------------------------------------
+// 
+// Create the x-axis for the event graph
+//
+Float_t *MHGausEvents::CreateEventXaxis(Int_t n)
+{
+
+  Float_t *xaxis = new Float_t[n];  
+
+  if (fEventFrequency)
+    for (Int_t i=0;i<n;i++)
+      xaxis[i] = (Float_t)i/fEventFrequency;
+  else
+    for (Int_t i=0;i<n;i++)
+      xaxis[i] = (Float_t)i;
+  
+  return xaxis;
+                 
+}
+
+
+// -------------------------------------------------------------------
+//
+// Create the fourier spectrum using the class MFFT.
+// The result is projected into a histogram and fitted by an exponential
+//
+void MHGausEvents::CreateFourierSpectrum()
+{
+
+  if (fFExpFit)
+    return;
+
+  if (fEvents.GetSize() < 8)
+    {
+      *fLog << warn << "Cannot create Fourier spectrum in: " << fName 
+            << ". Number of events smaller than 8 " << endl;
+      return;
+    }
+  
+  //
+  // The number of entries HAS to be a potence of 2, 
+  // so we can only cut out from the last potence of 2 to the rest. 
+  // Another possibility would be to fill everything with 
+  // zeros, but that gives a low frequency peak, which we would 
+  // have to cut out later again. 
+  //
+  // So, we have to live with the possibility that at the end 
+  // of the calibration run, something has happened without noticing 
+  // it...
+  //
+  
+  // This cuts only the non-used zero's, but MFFT will later cut the rest
+  fEvents.StripZeros();
+
+  if (fEvents.GetSize() < 8)
+    {
+      /*
+      *fLog << warn << "Cannot create Fourier spectrum. " << endl;
+      *fLog << warn << "Number of events (after stripping of zeros) is smaller than 8 " 
+            << "in pixel: " << fPixId << endl;
+      */
+      return;
+    }
+
+  MFFT fourier;
+
+  fPowerSpectrum     = fourier.PowerSpectrumDensity(&fEvents);
+  fHPowerProbability = ProjectArray(*fPowerSpectrum, fPowerProbabilityBins,
+                                    Form("%s%s","PowerProb",GetName()),
+                                    "Probability of Power occurrance");
+  fHPowerProbability->SetXTitle("P(f)");
+  fHPowerProbability->SetYTitle("Counts");
+  fHPowerProbability->GetYaxis()->CenterTitle();
+  fHPowerProbability->SetDirectory(NULL);
+  fHPowerProbability->SetBit(kCanDelete);  
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Double_t xmax = fHPowerProbability->GetXaxis()->GetXmax();
+
+  fFExpFit = new TF1("FExpFit","exp([0]-[1]*x)",0.,xmax);
+
+  const Double_t slope_guess  = (TMath::Log(fHPowerProbability->GetEntries())+1.)/xmax;
+  const Double_t offset_guess = slope_guess*xmax;
+
+  // 
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  //
+  gROOT->GetListOfFunctions()->Remove(fFExpFit);
+  fFExpFit->SetParameters(offset_guess, slope_guess);
+  fFExpFit->SetParNames("Offset","Slope");
+  fFExpFit->SetParLimits(0,offset_guess/2.,2.*offset_guess);
+  fFExpFit->SetParLimits(1,slope_guess/1.5,1.5*slope_guess);
+  fFExpFit->SetRange(0.,xmax);
+
+  fHPowerProbability->Fit(fFExpFit,"RQL0");
+  
+  if (GetExpProb() > fProbLimit)
+    SetExpFitOK(kTRUE);
+  
+  //
+  // For the moment, this is the only check, later we can add more...
+  //
+  SetFourierSpectrumOK(IsExpFitOK());
+
+  return;
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Create a graph to display the array fEvents
+// If the variable fEventFrequency is set, the x-axis is transformed into real time.
+//
+void MHGausEvents::CreateGraphEvents()
+{
+
+  fEvents.StripZeros();
+
+  const Int_t n = fEvents.GetSize();
+
+  if (n==0)
+    return;
+
+  fGraphEvents = new TGraph(n,CreateEventXaxis(n),fEvents.GetArray());  
+  fGraphEvents->SetTitle("Evolution of Events with time");
+  fGraphEvents->GetXaxis()->SetTitle((fEventFrequency) ? "Time [s]" : "Event Nr.");
+  fGraphEvents->GetYaxis()->SetTitle(fHGausHist.GetXaxis()->GetTitle());
+  fGraphEvents->GetYaxis()->CenterTitle();
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Create a graph to display the array fPowerSpectrum
+// If the variable fEventFrequency is set, the x-axis is transformed into real frequency.
+//
+void MHGausEvents::CreateGraphPowerSpectrum()
+{
+
+  fPowerSpectrum->StripZeros();
+
+  const Int_t n = fPowerSpectrum->GetSize();
+
+  fGraphPowerSpectrum = new TGraph(n,CreatePSDXaxis(n),fPowerSpectrum->GetArray());  
+  fGraphPowerSpectrum->SetTitle("Power Spectrum Density");
+  fGraphPowerSpectrum->GetXaxis()->SetTitle((fEventFrequency) ? "Frequency [Hz]" : "Frequency");
+  fGraphPowerSpectrum->GetYaxis()->SetTitle("P(f)");
+  fGraphPowerSpectrum->GetYaxis()->CenterTitle();
+
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// Create the x-axis for the event graph
+//
+Float_t *MHGausEvents::CreatePSDXaxis(Int_t n)
+{
+
+  Float_t *xaxis = new Float_t[n];
+
+  if (fEventFrequency)
+    for (Int_t i=0;i<n;i++)
+      xaxis[i] = 0.5*(Float_t)i*fEventFrequency/n;
+  else
+    for (Int_t i=0;i<n;i++)
+    xaxis[i] = 0.5*(Float_t)i/n;
+  
+  return xaxis;
+                 
+}
+  
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+// The following options can be chosen:
+//
+// "EVENTS": displays a TGraph of the array fEvents
+// "FOURIER": display a TGraph of the fourier transform of fEvents 
+//            displays the projection of the fourier transform with the fit
+//
+// The following picture shows a typical outcome of call to Draw("fourierevents"): 
+// - The first plot shows the distribution of the values with the Gauss fit
+//   (which did not succeed, in this case, for obvious reasons)
+// - The second plot shows the TGraph with the events vs. time
+// - The third plot shows the fourier transform and a small peak at about 85 Hz.
+// - The fourth plot shows the projection of the fourier components and an exponential 
+//   fit, with the result that the observed deviation is still statistical with a 
+//   probability of 0.5%. 
+//
+//Begin_Html
+/*
+<img src="images/MHGausEventsDraw.gif">
+*/
+//End_Html
+//
+void MHGausEvents::Draw(const Option_t *opt)
+{
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this,600, 600);
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win = 1;
+  Int_t nofit = 0;
+
+  if (option.Contains("events"))
+    {
+      option.ReplaceAll("events","");      
+      win += 1;
+    }
+  if (option.Contains("fourier"))
+    {
+      option.ReplaceAll("fourier","");      
+      win += 2;
+    }
+  
+  if (IsEmpty())
+    win--;
+
+  if (option.Contains("nofit"))
+    {
+      option.ReplaceAll("nofit","");
+      nofit++;
+    }
+  
+  pad->SetBorderMode(0);
+  if (win > 1)
+    pad->Divide(1,win);
+
+  Int_t cwin = 1;
+
+  gPad->SetTicks();
+
+  if (!IsEmpty())
+    {
+      pad->cd(cwin++);
+
+      if (!IsOnlyOverflow() && !IsOnlyUnderflow())
+        gPad->SetLogy();
+
+      fHGausHist.Draw(option);
+
+      if (!nofit)
+        if (fFGausFit)
+          {
+            fFGausFit->SetLineColor(IsGausFitOK() ? kGreen : kRed);
+            fFGausFit->Draw("same");
+          }
+    }
+  
+  if (option.Contains("events"))
+    {
+      pad->cd(cwin++);
+      DrawEvents();
+    }
+  if (option.Contains("fourier"))      
+    {
+      pad->cd(cwin++);
+      DrawPowerSpectrum();
+      pad->cd(cwin);
+      DrawPowerProjection();
+    }
+}
+
+// -----------------------------------------------------------------------------
+// 
+// DrawEvents:
+//
+// Will draw the graph with the option "A", unless the option:
+// "SAME" has been chosen 
+//
+void MHGausEvents::DrawEvents(Option_t *opt)
+{
+  
+  if (!fGraphEvents)
+    CreateGraphEvents();
+
+  if (!fGraphEvents)
+    return;
+
+  fGraphEvents->SetBit(kCanDelete);
+  fGraphEvents->SetTitle("Events with time");
+
+  TString option(opt);
+  option.ToLower();
+
+  if (option.Contains("same"))
+    {
+      option.ReplaceAll("same","");      
+      fGraphEvents->Draw(option+"L");
+    }
+  else
+    fGraphEvents->Draw(option+"AL");  
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// DrawPowerSpectrum
+//
+// Will draw the fourier spectrum of the events sequence with the option "A", unless the option:
+// "SAME" has been chosen 
+//
+void MHGausEvents::DrawPowerSpectrum(Option_t *option)
+{
+
+  TString opt(option);
+  
+  if (!fPowerSpectrum)
+    CreateFourierSpectrum();
+
+  if (fPowerSpectrum)
+    {
+      if (!fGraphPowerSpectrum)
+        CreateGraphPowerSpectrum();
+
+      if (!fGraphPowerSpectrum)
+        return;
+      
+      if (opt.Contains("same"))
+        {
+          opt.ReplaceAll("same","");      
+          fGraphPowerSpectrum->Draw(opt+"L");
+        }
+      else
+        {
+          fGraphPowerSpectrum->Draw(opt+"AL");  
+          fGraphPowerSpectrum->SetBit(kCanDelete);
+        }
+    }
+}
+
+// -----------------------------------------------------------------------------
+// 
+// DrawPowerProjection
+//
+// Will draw the projection of the fourier spectrum onto the power probability axis
+// with the possible options of TH1D
+//
+void MHGausEvents::DrawPowerProjection(Option_t *option)
+{
+  
+  TString opt(option);
+
+  if (!fHPowerProbability)
+    CreateFourierSpectrum();
+
+  if (fHPowerProbability && fHPowerProbability->GetEntries() > 0)
+    {
+      gPad->SetLogy();
+      fHPowerProbability->Draw(opt.Data());
+      if (fFExpFit)
+        {
+          fFExpFit->SetLineColor(IsExpFitOK() ? kGreen : kRed);
+          fFExpFit->Draw("same");
+        }
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill fEvents with f
+// If size of fEvents is 0, initializes it to 512
+// If size of fEvents is smaller than fCurrentSize, double the size
+// Increase fCurrentSize by 1
+//
+void MHGausEvents::FillArray(const Float_t f)
+{
+
+  if (fEvents.GetSize() == 0)
+    fEvents.Set(512);
+
+  if (fCurrentSize >= fEvents.GetSize())
+    fEvents.Set(fEvents.GetSize()*2);
+  
+  fEvents.AddAt(f,fCurrentSize++);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fills fHGausHist with f
+// Returns kFALSE, if overflow or underflow occurred, else kTRUE
+//
+Bool_t MHGausEvents::FillHist(const Float_t f)
+{
+  return fHGausHist.Fill(f) > -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Executes:
+// - FillArray()
+// - FillHist()
+//
+Bool_t MHGausEvents::FillHistAndArray(const Float_t f)
+{
+
+  FillArray(f);
+  return FillHist(f);
+}
+
+// -------------------------------------------------------------------
+//
+// Fit fGausHist with a Gaussian after stripping zeros from both ends 
+// and rebinned to the number of bins specified in fBinsAfterStripping
+//
+// The fit results are retrieved and stored in class-own variables.  
+//
+// A flag IsGausFitOK() is set according to whether the fit probability 
+// is smaller or bigger than fProbLimit, whether the NDF is bigger than 
+// fNDFLimit and whether results are NaNs.
+//
+Bool_t MHGausEvents::FitGaus(Option_t *option, const Double_t xmin, const Double_t xmax)
+{
+
+  if (IsGausFitOK())
+    return kTRUE;
+
+  //
+  // First, strip the zeros from the edges which contain only zeros and rebin 
+  // to fBinsAfterStripping bins. If fBinsAfterStripping is 0, reduce bins only by 
+  // a factor 10.
+  //
+  // (ATTENTION: The Chisquare method is more sensitive, 
+  // the _less_ bins, you have!)
+  //
+  StripZeros(&fHGausHist,
+             fBinsAfterStripping ? fBinsAfterStripping 
+             : (fNbins > 1000 ? fNbins/10 : 0));
+  
+  TAxis *axe = fHGausHist.GetXaxis();
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetFirst()) : xmin;
+  Axis_t rmax = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetLast())  : xmax;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Stat_t   entries     = fHGausHist.Integral(axe->FindBin(rmin),axe->FindBin(rmax),"width");
+  const Double_t mu_guess    = fHGausHist.GetBinCenter(fHGausHist.GetMaximumBin());
+  const Double_t sigma_guess = fHGausHist.GetRMS();
+  const Double_t area_guess  = entries/TMath::Sqrt(TMath::TwoPi())/sigma_guess;
+
+  fFGausFit = new TF1("GausFit","gaus",rmin,rmax);
+
+  if (!fFGausFit) 
+    {
+    *fLog << warn << dbginf << "WARNING: Could not create fit function for Gauss fit " 
+          << "in: " << fName << endl;
+    return kFALSE;
+    }
+  
+  // 
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  //
+  gROOT->GetListOfFunctions()->Remove(fFGausFit);
+
+  fFGausFit->SetParameters(area_guess,mu_guess,sigma_guess);
+  fFGausFit->SetParNames("Area","#mu","#sigma");
+  fFGausFit->SetParLimits(0,0.,area_guess*25.);
+  fFGausFit->SetParLimits(1,rmin,rmax);
+  fFGausFit->SetParLimits(2,0.,rmax-rmin);
+  fFGausFit->SetRange(rmin,rmax);
+
+  fHGausHist.Fit(fFGausFit,option);
+
+  fMean     = fFGausFit->GetParameter(1);
+  fSigma    = fFGausFit->GetParameter(2);
+  fMeanErr  = fFGausFit->GetParError(1);
+  fSigmaErr = fFGausFit->GetParError(2);
+  fProb     = fFGausFit->GetProb();
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (default: fgNDFLimit)
+  // 3) The Probability is greater than fProbLimit (default: fgProbLimit)
+  //
+  if (   TMath::IsNaN(fMean) 
+      || TMath::IsNaN(fMeanErr)
+      || TMath::IsNaN(fProb)    
+      || TMath::IsNaN(fSigma)
+      || TMath::IsNaN(fSigmaErr) 
+      || fFGausFit->GetNDF() < fNDFLimit 
+      || fProb < fProbLimit )
+    return kFALSE;
+  
+  SetGausFitOK(kTRUE);
+  return kTRUE;
+}
+
+
+const Double_t MHGausEvents::GetChiSquare()  const 
+{
+  return ( fFGausFit ? fFGausFit->GetChisquare() : 0.);
+}
+
+
+const Double_t MHGausEvents::GetExpChiSquare()  const 
+{
+  return ( fFExpFit ? fFExpFit->GetChisquare() : 0.);
+}
+
+
+const Int_t MHGausEvents::GetExpNdf()  const 
+{
+  return ( fFExpFit ? fFExpFit->GetNDF() : 0);
+}
+
+
+const Double_t MHGausEvents::GetExpProb()  const 
+{
+  return ( fFExpFit ? fFExpFit->GetProb() : 0.);
+}
+
+
+const Int_t MHGausEvents::GetNdf() const 
+{
+  return ( fFGausFit ? fFGausFit->GetNDF() : 0);
+}
+
+const Double_t MHGausEvents::GetOffset()  const 
+{
+  return ( fFExpFit ? fFExpFit->GetParameter(0) : 0.);
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// If fFExpFit exists, returns fit parameter 1 (Slope of Exponential fit), 
+// otherwise 0.
+//
+const Double_t MHGausEvents::GetSlope()  const 
+{
+  return ( fFExpFit ? fFExpFit->GetParameter(1) : 0.);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default InitBins, can be overloaded.
+//
+// Executes:
+// - fHGausHist.SetBins(fNbins,fFirst,fLast)
+//
+void MHGausEvents::InitBins()
+{
+  //  const TAttAxis att(fHGausHist.GetXaxis());
+  fHGausHist.SetBins(fNbins,fFirst,fLast);
+  //  att.Copy(fHGausHist.GetXaxis());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return kFALSE if number of entries is 0 
+//
+const Bool_t MHGausEvents::IsEmpty() const
+{
+  return !(fHGausHist.GetEntries());
+}
+
+// --------------------------------------------------------------------------
+//
+// Return kTRUE  if number of entries is bin content of fNbins+1
+//
+const Bool_t MHGausEvents::IsOnlyOverflow() const
+{
+  return fHGausHist.GetEntries() == fHGausHist.GetBinContent(fNbins+1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Return kTRUE  if number of entries is bin content of 0
+//
+const Bool_t MHGausEvents::IsOnlyUnderflow() const
+{
+  return fHGausHist.GetEntries() == fHGausHist.GetBinContent(0);
+}
+
+
+const Bool_t MHGausEvents::IsExcluded() const
+{
+  return TESTBIT(fFlags,kExcluded);
+}
+
+
+const Bool_t MHGausEvents::IsExpFitOK() const 
+{
+  return TESTBIT(fFlags,kExpFitOK);
+}
+
+const Bool_t MHGausEvents::IsFourierSpectrumOK() const 
+{
+  return TESTBIT(fFlags,kFourierSpectrumOK);
+}
+
+
+const Bool_t MHGausEvents::IsGausFitOK() const 
+{
+  return TESTBIT(fFlags,kGausFitOK);
+}
+
+
+// -----------------------------------------------------------------------------------
+// 
+// A default print
+//
+void MHGausEvents::Print(const Option_t *o) const 
+{
+  
+  *fLog << all                                                        << endl;
+  *fLog << all << "Results of the Gauss Fit in: " << fName            << endl;
+  *fLog << all << "Mean: "             << GetMean()                   << endl;
+  *fLog << all << "Sigma: "            << GetSigma()                  << endl;
+  *fLog << all << "Chisquare: "        << GetChiSquare()              << endl;
+  *fLog << all << "DoF: "              << GetNdf()                    << endl;
+  *fLog << all << "Probability: "      << GetProb()                   << endl;
+  *fLog << all                                                        << endl;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default Reset(), can be overloaded.
+//
+// Executes:
+// - Clear()
+// - fHGausHist.Reset()
+// - fEvents.Set(0)
+// - InitBins()
+//
+void MHGausEvents::Reset()
+{
+
+  Clear();
+  fHGausHist.Reset();
+  fEvents.Set(0);
+  InitBins();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set Excluded bit from outside
+//
+void MHGausEvents::SetExcluded(const Bool_t b)
+{
+    b ? SETBIT(fFlags,kExcluded) : CLRBIT(fFlags,kExcluded);
+}
+
+
+// -------------------------------------------------------------------
+//
+// The flag setters are to be used ONLY for Monte-Carlo!!
+//
+void  MHGausEvents::SetExpFitOK(const Bool_t b)
+{
+  
+  b ? SETBIT(fFlags,kExpFitOK) : CLRBIT(fFlags,kExpFitOK);  
+}
+
+// -------------------------------------------------------------------
+//
+// The flag setters are to be used ONLY for Monte-Carlo!!
+//
+void  MHGausEvents::SetFourierSpectrumOK(const Bool_t b)
+{
+
+  b ? SETBIT(fFlags,kFourierSpectrumOK) : CLRBIT(fFlags,kFourierSpectrumOK);    
+}
+
+
+// -------------------------------------------------------------------
+//
+// The flag setters are to be used ONLY for Monte-Carlo!!
+//
+void  MHGausEvents::SetGausFitOK(const Bool_t b)
+{
+  b ? SETBIT(fFlags,kGausFitOK) : CLRBIT(fFlags,kGausFitOK);
+
+}
+
+// ----------------------------------------------------------------------------
+//
+// Simulates Gaussian events and fills them  into the histogram and the array
+// In order to do a fourier analysis, call CreateFourierSpectrum()
+//
+void  MHGausEvents::SimulateGausEvents(const Float_t mean, const Float_t sigma, const Int_t nevts)
+{
+
+  if (!IsEmpty())
+    *fLog << warn << "The histogram is already filled, will superimpose simulated events on it..." << endl;
+  
+  for (Int_t i=0;i<nevts;i++) {
+    const Double_t ran = gRandom->Gaus(mean,sigma);
+    FillHistAndArray(ran);
+  }
+  
+}
Index: /tags/Mars-V0.9/mhcalib/MHGausEvents.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHGausEvents.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHGausEvents.h	(revision 9772)
@@ -0,0 +1,171 @@
+#ifndef MARS_MHGausEvents
+#define MARS_MHGausEvents
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class TVirtualPad;
+class TGraph;
+class MArrayF;
+class TH1F;
+class TH1I;
+class TF1;
+class MHGausEvents : public MH
+{
+private:
+
+  const static Int_t    fgNDFLimit;             //! Default for fNDFLimit             (now set to: 2)
+  const static Float_t  fgProbLimit;            //! Default for fProbLimit            (now set to: 0.001)
+  const static Int_t    fgPowerProbabilityBins; //! Default for fPowerProbabilityBins (now set to: 20)
+
+  Float_t *CreateEventXaxis(Int_t n);  // Create an x-axis for the Event TGraphs
+  Float_t *CreatePSDXaxis(Int_t n);    // Create an x-axis for the PSD TGraphs
+  
+protected:
+
+  Float_t  fEventFrequency;            // Event frequency in Hertz (to be set)
+
+  Int_t    fBinsAfterStripping;        // Bins for the Gauss Histogram after stripping off the zeros at both ends
+  UInt_t   fCurrentSize;               // Current size of the array fEvents
+  Byte_t   fFlags;                     // Bit field for the fit result bits
+  Int_t    fPowerProbabilityBins;      // Bins for the projected power spectrum
+  
+  TH1I    *fHPowerProbability;         //! Fourier transform of fEvents projected on y-axis
+  MArrayF *fPowerSpectrum;             //! Fourier transform of fEvents
+
+  enum  { kGausFitOK,
+          kExpFitOK,
+          kFourierSpectrumOK,
+          kExcluded };                 // Bits for information about fit results 
+  
+  MArrayF  fEvents;                    // Array which holds the entries of GausHist
+  TF1     *fFGausFit;                  // Gauss fit for fHGausHist
+  TF1     *fFExpFit;                   // Exponential fit for FHPowerProbability
+  Axis_t   fFirst;                     // Lower histogram edge  for fHGausHist (used by InitBins()) 
+  TGraph  *fGraphEvents;               //! TGraph to display the event array 
+  TGraph  *fGraphPowerSpectrum;        //! TGraph to display the power spectrum array 
+  TH1F     fHGausHist;                 // Histogram to hold the Gaussian distribution
+  Axis_t   fLast;                      // Upper histogram edge  for fHGausHist (used by InitBins()) 
+  Double_t fMean;                      // Mean of the Gauss fit
+  Double_t fMeanErr;                   // Error of the mean of the Gauss fit
+  Int_t    fNbins;                     // Number histogram bins for fHGausHist (used by InitBins())
+  Int_t    fNDFLimit;                  // NDF limit for judgement if fit is OK
+  Double_t fSigma;                     // Sigma of the Gauss fit
+  Double_t fSigmaErr;                  // Error of the sigma of the Gauss fit
+  Double_t fProb;                      // Probability of the Gauss fit 
+  Float_t  fProbLimit;                 // Probability limit for judgement if fit is OK 
+
+  // Setters
+  void  SetBinsAfterStripping   ( const Int_t nbins=0   )                    { fBinsAfterStripping  =nbins; }
+  void  SetPowerProbabilityBins ( const Int_t nbins=fgPowerProbabilityBins ) { fPowerProbabilityBins=nbins; }
+
+public:
+
+  MHGausEvents(const char* name=NULL, const char* title=NULL);
+  ~MHGausEvents();
+
+  void Clear(Option_t *o="");
+  void Reset();  
+
+  void CreateFourierSpectrum();         
+  void CreateGraphEvents();             
+  void CreateGraphPowerSpectrum(); 
+
+  // Draws
+  void Draw(Option_t *option="");                  // *MENU*
+  void DrawEvents(Option_t *option="");              // *MENU*
+  void DrawPowerSpectrum(Option_t *option="");         // *MENU*
+  void DrawPowerProjection(Option_t *option="");       // *MENU*
+
+  // Fill
+  void   FillArray       ( const Float_t f ); 
+  Bool_t FillHist        ( const Float_t f ); 
+  Bool_t FillHistAndArray( const Float_t f ); 
+  
+  // Fits
+  Bool_t FitGaus(  Option_t *option="RQ0",         
+                   const Double_t xmin=0., 
+	           const Double_t xmax=0.);           // *MENU*
+  
+  // Inits
+  virtual void InitBins();
+  
+  // Getters
+  const Double_t GetChiSquare()          const;
+  const Double_t GetExpChiSquare()       const;
+  const Int_t    GetExpNdf()             const;
+  const Double_t GetExpProb()            const;
+        MArrayF *GetEvents()                   { return &fEvents;            }  
+  const MArrayF *GetEvents()             const { return &fEvents;            }
+  const Float_t  GetEventFrequency () const { return fEventFrequency; }
+  TF1     *GetFExpFit()                  { return fFExpFit;            }
+  const TF1     *GetFExpFit()            const { return fFExpFit;            } 
+        TF1     *GetFGausFit()                 { return fFGausFit;           }
+  const TF1     *GetFGausFit()           const { return fFGausFit;           } 
+        TGraph  *GetGraphEvents()              { return fGraphEvents;        }
+  const Double_t GetFirst()              const { return fFirst;              }
+  const Double_t GetLast ()              const { return fLast ;              }  
+  const TGraph  *GetGraphEvents()        const { return fGraphEvents;        }
+        TGraph  *GetGraphPowerSpectrum()       { return fGraphPowerSpectrum; }
+  const TGraph  *GetGraphPowerSpectrum() const { return fGraphPowerSpectrum; }
+        TH1F    *GetHGausHist()                { return &fHGausHist;         }
+  const TH1F    *GetHGausHist()          const { return &fHGausHist;         } 
+        TH1I    *GetHPowerProbability()        { return fHPowerProbability;  }
+  const TH1I    *GetHPowerProbability()  const { return fHPowerProbability;  } 
+  const Double_t GetHistRms()            const { return fHGausHist.GetRMS(); }
+  const Double_t GetMean()               const { return fMean;               }
+  const Double_t GetMeanErr()            const { return fMeanErr;            }
+  const Int_t    GetNdf()                const;
+  const Int_t    GetNbins()               const { return fNbins;            }
+  const Double_t GetOffset()             const;
+        MArrayF *GetPowerSpectrum()            { return fPowerSpectrum;      }  
+  const MArrayF *GetPowerSpectrum()      const { return fPowerSpectrum;      }
+  const Double_t GetProb()               const { return fProb;               }
+  const Double_t GetSigma()              const { return fSigma;              }
+  const Double_t GetSigmaErr()           const { return fSigmaErr;           }
+  const Double_t GetSlope()              const;
+
+  const Bool_t IsExcluded()              const;
+  const Bool_t IsExpFitOK()              const; 
+  const Bool_t IsEmpty()                 const;
+  const Bool_t IsFourierSpectrumOK()     const;
+  const Bool_t IsGausFitOK()             const; 
+  const Bool_t IsOnlyOverflow()          const;
+  const Bool_t IsOnlyUnderflow()         const;  
+
+  // Prints
+  void Print(const Option_t *o="") const;       // *MENU*
+  
+  // Setters
+  void  SetEventFrequency   ( const Float_t  f                   ) { fEventFrequency = f;   }
+  void  SetExcluded         ( const Bool_t   b=kTRUE             );  
+  void  SetExpFitOK         ( const Bool_t   b=kTRUE             );
+  void  SetFourierSpectrumOK( const Bool_t   b=kTRUE             );
+  void  SetGausFitOK        ( const Bool_t   b=kTRUE             );
+  void  SetLast             ( const Double_t d                   ) { fLast           = d;   }
+  void  SetFirst            ( const Double_t d                   ) { fFirst          = d;   }
+  void  SetMean             ( const Double_t d                   ) { fMean           = d;   }
+  void  SetMeanErr          ( const Double_t d                   ) { fMeanErr        = d;   }
+  void  SetNbins            ( const Int_t    i                   ) { fNbins          = i;   }  
+  void  SetNDFLimit         ( const Int_t    lim=fgNDFLimit      ) { fNDFLimit       = lim; }  
+  void  SetProb             ( const Double_t d                   ) { fProb           = d;   }
+  void  SetProbLimit        ( const Float_t  lim=fgProbLimit     ) { fProbLimit      = lim; }
+  void  SetSigma            ( const Double_t d                   ) { fSigma          = d;   }
+  void  SetSigmaErr         ( const Double_t d                   ) { fSigmaErr       = d;   }
+
+  // Simulates
+  void  SimulateGausEvents(const Float_t mean, const Float_t sigma, const Int_t nevts=4096);     // *MENU*
+
+  ClassDef(MHGausEvents, 3) // Base class for events with Gaussian distributed values
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/MHPedestalCam.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHPedestalCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHPedestalCam.cc	(revision 9772)
@@ -0,0 +1,856 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPedestalCam
+//
+// Fills the extracted pedestals of MExtractedSignalCam into
+// the MHCalibrationPix-classes MHPedestalPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray
+//   or MHCalibrationCam::fHiGainArray, respectively
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors
+//   and MHCalibrationCam::fAverageHiGainSectors
+//
+// Every pedestal is directly taken from MExtractedSignalCam, filled by the
+// appropriate extractor.
+//
+// The pedestals are filled into a histogram and an array, in order to perform
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors
+// and the fit probability are extracted. If none of these values are NaN's and
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%),
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are
+// taken directly (see MHCalibrationPix::BypassFit()).
+//
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup)
+//
+// The number of summed FADC slices is taken to re-normalize
+// the result to a pedestal per pixel with the formulas (see MHPedestalPix::Renorm()):
+// - Mean Pedestal        / slice = Mean Pedestal        / Number slices
+// - Mean Pedestal Error  / slice = Mean Pedestal Error  / Number slices
+// - Sigma Pedestal       / slice = Sigma Pedestal       / Sqrt (Number slices)
+// - Sigma Pedestal Error / slice = Sigma Pedestal Error / Sqrt (Number slices)
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the
+// projected fourier components follow an exponential distribution.
+//
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MPedestalCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of
+// the number involved pixels in order to be able to compare it to the average of
+// sigmas in the camera.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPedestalCam.h"
+#include "MHPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCalibrationIntensityCam.h"
+#include "MCalibrationPix.h"
+
+#include "MBadPixelsIntensityCam.h"
+#include "MBadPixelsCam.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationPedCam.h"
+
+#include <TH1F.h>
+#include <TOrdCollection.h>
+
+ClassImp(MHPedestalCam);
+
+using namespace std;
+
+const Int_t   MHPedestalCam::fgNbins      =  50;
+const Axis_t  MHPedestalCam::fgFirst      = -57.5;
+const Axis_t  MHPedestalCam::fgLast       = 192.5;
+const TString MHPedestalCam::gsHistName   = "Pedestal";
+const TString MHPedestalCam::gsHistTitle  = "Pedestal";
+const TString MHPedestalCam::gsHistXTitle = "Charge [FADC slices]";
+const TString MHPedestalCam::gsHistYTitle = "Nr. events";
+const TString MHPedestalCam::fgNamePedestalCam = "MPedestalCam";
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes:
+// - fExtractHiGainSlices to 0.
+// - the event frequency to 1200 Hz.
+// - the fRenormflag to kFALSE
+//
+// - fNbins to fgNbins
+// - fFirst to fgFirst
+// - fLast  to fgLast 
+//
+// - fHistName   to gsHistName  
+// - fHistTitle  to gsHistTitle 
+// - fHistXTitle to gsHistXTitle
+// - fHistYTitle to gsHistYTitle
+//
+MHPedestalCam::MHPedestalCam(const char *name, const char *title) 
+    : fNamePedestalCamOut(fgNamePedestalCam), fNumEvents(0), 
+      fExtractHiGainSlices(0.), fPedestalsOut(NULL)
+{
+
+  fName  = name  ? name  : "MHPedestalCam";
+  fTitle = title ? title : "Class to fill the pedestal histograms";
+  
+  SetPulserFrequency(1200);
+  SetRenorm(kFALSE);
+  SetLoGain(kFALSE);
+
+  SetNbins(fgNbins);
+  SetFirst(fgFirst);
+  SetLast (fgLast );
+
+  SetHistName  (gsHistName  .Data());
+  SetHistTitle (gsHistTitle .Data());
+  SetHistXTitle(gsHistXTitle.Data());
+  SetHistYTitle(gsHistYTitle.Data());
+
+  SetFitStart();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHCalibrationCam::ResetHists()
+//
+// Resets:
+// - fSum
+// - fSumSquare
+// - fAreaSum
+// - fAreaSumSquare
+// - fAreaNum
+// - fSectorSum
+// - fSectorSumSquare
+// - fSectorNum
+//
+void MHPedestalCam::ResetHists()
+{
+  
+  MHCalibrationCam::ResetHists();
+  
+  fNumEvents = 0;
+  
+  // If the size is yet set, set the size
+  if (fSum.GetSize()>0)
+    {
+      // Reset contents of arrays.
+      fSum.Reset();
+      fSumSquare.Reset();
+      
+      fAreaSum. Reset();
+      fAreaSumSquare.Reset();
+      fAreaNum.Reset();
+      
+      fSectorSum. Reset();
+      fSectorSumSquare.Reset();
+      fSectorNum.Reset();
+    }
+}
+// --------------------------------------------------------------------------
+//
+// Creates new MHCalibrationChargeCam only with the averaged areas:
+// the rest has to be retrieved directly, e.g. via: 
+//     MHPedestalCam *cam = MParList::FindObject("MHPedestalCam");
+//  -  cam->GetAverageSector(5).DrawClone();
+//  -  (*cam)[100].DrawClone()
+//
+TObject *MHPedestalCam::Clone(const char *) const
+{
+
+  MHPedestalCam *cam = new MHPedestalCam();
+
+  //
+  // Copy the data members
+  //
+  cam->fRunNumbers             = fRunNumbers;
+  cam->fPulserFrequency        = fPulserFrequency;
+  cam->fFlags                  = fFlags;
+  cam->fNbins                  = fNbins;
+  cam->fFirst                  = fFirst;
+  cam->fLast                   = fLast;
+
+  if (!IsAverageing())
+    return cam;
+
+  const Int_t navhi   =  fAverageHiGainAreas->GetSize();
+
+  for (int i=0; i<navhi; i++)
+    cam->fAverageHiGainAreas->AddAt(GetAverageHiGainArea(i).Clone(),i);
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// Searches pointer to:
+// - MPedestalCam
+// - MExtractedSignalCam
+//
+// Searches or creates:
+// - MCalibrationPedCam
+//
+// Retrieves from MExtractedSignalCam:
+// - number of used High Gain FADC slices (MExtractedSignalCam::GetNumUsedHiGainFADCSlices())
+//
+// Initializes, if empty to MGeomCam::GetNumPixels():
+// - MHCalibrationCam::fHiGainArray
+//
+// Initializes, if empty to MGeomCam::GetNumAreas() for:
+// - MHCalibrationCam::fAverageHiGainAreas
+//
+// Initializes, if empty to MGeomCam::GetNumSectors() for:
+// - MHCalibrationCam::fAverageHiGainSectors
+// 
+// Calls MHCalibrationCam::InitPedHists() for every entry in:
+// - MHCalibrationCam::fHiGainArray
+// - MHCalibrationCam::fAverageHiGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors
+//
+// Sets Titles and Names for the Histograms 
+// - MHCalibrationCam::fAverageHiGainAreas
+// 
+Bool_t MHPedestalCam::ReInitHists(MParList *pList)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!signal && fRenorm)
+    {
+      *fLog << err << "Cannot find MExtractedSignalCam, but re-normalization switched on..."
+            << " Cannot find number of used slices ...abort." << endl;
+      return kFALSE;
+    }
+  
+
+  if (!fPedestalsOut)
+    fPedestalsOut = (MPedestalCam*)pList->FindObject(AddSerialNumber(fNamePedestalCamOut),"MPedestalCam");
+
+  if (!fPedestalsOut)
+    {
+      *fLog << err << "Cannot find nor create outgoing MPedestalCam ..." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  fCam = (MCalibrationCam*)pList->FindObject("MCalibrationPedCam");
+  if (!fCam)
+  {
+      fCam = (MCalibrationCam*)pList->FindCreateObj(AddSerialNumber("MCalibrationPedCam"));
+      if (!fCam)
+          return kFALSE;
+
+      fCam->Init(*fGeom);
+  }
+  
+  InitHiGainArrays(npixels,nareas,nsectors);
+
+  if (fSum.GetSize()==0)
+    {
+      fSum.       Set(npixels);
+      fSumSquare.      Set(npixels);
+      fAreaSum.   Set(nareas);
+      fAreaSumSquare.  Set(nareas);
+      fAreaNum.  Set(nareas);
+      fSectorSum. Set(nsectors);
+      fSectorSumSquare.Set(nsectors);
+      fSectorNum.Set(nsectors);
+    }
+
+  fNumEvents = 0;
+
+  if (!signal)
+    return kTRUE;
+  
+  
+  Float_t sliceshi = signal->GetNumUsedHiGainFADCSlices();
+  
+  if (sliceshi == 0.)
+    {
+      *fLog << err << "Number of used signal slices in MExtractedSignalCam is zero  ... abort." 
+            << endl;
+      return kFALSE;
+    }
+  
+  if (fExtractHiGainSlices != 0. && sliceshi != fExtractHiGainSlices )
+    {
+      *fLog << err << "Number of used High Gain signal slices changed in MExtractedSignalCam  ... abort." 
+            << endl;
+      return kFALSE;
+    }
+  
+  fExtractHiGainSlices = sliceshi;
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() 
+        << ": Number of found High Gain signal slices: " << fExtractHiGainSlices << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes the High Gain Arrays:
+//
+// - For every entry in the expanded arrays: 
+//   * Initialize an MHCalibrationChargePix
+//   * Set Binning from  fNbins, fFirst and fLast
+//   * Set Binning of Abs Times histogram from  fAbsNbins, fAbsFirst and fAbsLast
+//   * Set Histgram names and titles from fHistName and fHistTitle
+//   * Set Abs Times Histgram names and titles from fAbsHistName and fAbsHistTitle
+//   * Set X-axis and Y-axis titles from fHistXTitle and fHistYTitle
+//   * Set X-axis and Y-axis titles of Abs Times Histogram from fAbsHistXTitle and fAbsHistYTitle
+//   * Call InitHists
+//
+//
+void MHPedestalCam::InitHiGainArrays(const Int_t npixels, const Int_t nareas, const Int_t nsectors)
+{
+  
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHPedestalPix(Form("%sHiGainPix%04d",fHistName.Data(),i),
+                                                       Form("%s High Gain Pixel%04d",fHistTitle.Data(),i)),i);
+
+        MHPedestalPix &pix = (MHPedestalPix&)(*this)[i];
+
+        pix.SetNbins(fNbins);
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+
+        pix.SetProbLimit(fProbLimit);
+
+        MBadPixelsPix &bad = fIntensBad ? (*fIntensBad)[i] : (*fBadPixels)[i];
+        InitHists(pix,bad,i);
+      }
+  }
+
+  if (!IsAverageing())
+    return;
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHPedestalPix(Form("%sHiGainArea%d",fHistName.Data(),j),
+                                                  Form("%s High Gain Area Idx %d",fHistTitle.Data(),j)),j);
+        
+        MHPedestalPix &pix = (MHPedestalPix&)GetAverageHiGainArea(j);
+        
+        pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+        pix.SetFirst(fFirst);
+        pix.SetLast (fLast);
+        
+        InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadArea(j) : fCam->GetAverageBadArea(j),j);
+
+      }
+  }
+  
+  if (fAverageHiGainSectors->GetSize()==0)
+  {
+      for (Int_t j=0; j<nsectors; j++)
+        {
+	  fAverageHiGainSectors->AddAt(new MHPedestalPix(Form("%sHiGainSector%02d",fHistName.Data(),j),
+                                                      Form("%s High Gain Sector %02d",fHistTitle.Data(),j)),j);
+
+          MHPedestalPix &pix = (MHPedestalPix&)GetAverageHiGainSector(j);
+
+          pix.SetNbins(fNbins*(Int_t)TMath::Sqrt((Float_t)npixels/nareas));
+          pix.SetFirst(fFirst);
+          pix.SetLast (fLast);
+
+          InitHists(pix,fIntensCam ? fIntensCam->GetAverageBadSector(j) : fCam->GetAverageBadSector(j),j);
+
+      }
+  }
+}
+
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MExtractedSignalCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain histograms (MHGausEvents::FillHistAndArray()), respectively
+// with the signals MExtractedSignalCam::GetExtractedSignalHiGain().
+//
+Bool_t MHPedestalCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MPedestalCam *pedestal = (MPedestalCam*)par;
+  if (!pedestal)
+    {
+      *fLog << err << "No argument in MHPedestalCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  MArrayF sumareahi(nareas);
+  MArrayF sumsectorhi(nsectors);
+  MArrayI numareahi(nareas);
+  MArrayI numsectorhi(nsectors);
+
+  for (UInt_t i=0; i<npixels; i++)
+  {
+
+      MHCalibrationPix &histhi = (*this)[i];
+
+      if (histhi.IsExcluded())
+          continue;
+
+      const MPedestalPix &ped = (*pedestal)[i];
+
+      const Float_t pedes = ped.GetPedestal();
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      histhi.FillHistAndArray(pedes) ;
+
+      fSum[i]            += pedes;
+      fAreaSum[aidx]     += pedes;
+      fSectorSum[sector] += pedes;      
+
+      const Float_t sqrsum  = pedes*pedes;
+      fSumSquare[i]            += sqrsum;
+      fAreaSumSquare[aidx]     += sqrsum;
+      fSectorSumSquare[sector] += sqrsum;      
+
+      sumareahi  [aidx]   += pedes;
+      numareahi  [aidx]   ++;
+      sumsectorhi[sector] += pedes;
+      numsectorhi[sector] ++;
+
+    }
+  
+  for (UInt_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+    }
+  
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+    }
+  
+  fNumEvents++;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with Bad Pixels flags 0
+// 
+Bool_t MHPedestalCam::FinalizeHists()
+{
+  
+  if (fNumEvents <= 1)
+    {
+      *fLog << err << GetDescriptor()
+            << ": Number of processed events smaller or equal to 1" << endl;
+      return kFALSE;
+    }
+  
+  FitHists();
+
+  if (fRenorm)
+    RenormResults();
+
+  return kTRUE;
+  
+}
+
+void MHPedestalCam::FitHists()
+{
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHPedestalPix &hist = (MHPedestalPix&)(*this)[i];
+      MCalibrationPix &pix   = (*fCam)[i];
+      
+      //
+      // 1) Store calculated means and variances in the low-gain slices
+      //
+      pix.SetLoGainMean    ( fSum[i] / fNumEvents  );
+      const Double_t diff = fSumSquare[i] - fSum[i]*fSum[i]/fNumEvents;
+      pix.SetLoGainSigma   ( diff > 0. ? TMath::Sqrt( diff / (fNumEvents-1) ) : 0.);
+      pix.SetLoGainMeanVar ( pix.GetLoGainSigma() * pix.GetLoGainSigma() / fNumEvents  );
+      pix.SetLoGainSigmaVar( pix.GetLoGainMeanVar() / 4. );
+
+      if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+        continue;
+      
+      //
+      // 2) Fit the Hi Gain histograms with a Gaussian
+      //
+      //      if (i%100)
+      //        hist.FitTripleGaus();
+      //      else
+      TH1F *gaush = hist.GetHGausHist();
+      hist.FitGaus("RQ0",fFitStart,gaush->GetBinCenter(gaush->GetXaxis()->GetLast()));
+      //
+      // 4) Check for oscillations
+      // 
+      if (IsOscillations())
+        hist.CreateFourierSpectrum();
+      //
+      // 5) Retrieve the results and store them in this class
+      //
+      pix.SetHiGainMean       ( hist.GetMean()      );
+      pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+      pix.SetHiGainRms        ( hist.GetHistRms()   );
+      pix.SetHiGainSigma      ( hist.GetSigma()     );
+      pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+      pix.SetHiGainProb       ( hist.GetProb()      );
+      pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+      pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+    }
+
+  if (!IsAverageing())
+    return;
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationPix &hist = GetAverageHiGainArea(j);      
+      MCalibrationPix  &pix  = fCam->GetAverageArea(j);
+
+      if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+        continue;
+      
+      //
+      // 2) Fit the Hi Gain histograms with a Gaussian
+      //
+      TH1F *gaush = hist.GetHGausHist();
+      hist.FitGaus("RQ0",fFitStart,gaush->GetBinCenter(gaush->GetXaxis()->GetLast()));
+      //
+      // 4) Check for oscillations
+      // 
+      if (IsOscillations())
+        hist.CreateFourierSpectrum();
+      //
+      // 5) Retrieve the results and store them in this class
+      //
+      pix.SetHiGainMean       ( hist.GetMean()      );
+      pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+      pix.SetHiGainRms        ( hist.GetHistRms()   );
+      pix.SetHiGainSigma      ( hist.GetSigma()     );
+      pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+      pix.SetHiGainProb       ( hist.GetProb()      );
+      pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+      pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+      //
+      // 6) Store calculated means and variances in the low-gain slices
+      //
+      const ULong_t aevts = fNumEvents * fAreaNum[j];
+      if (aevts <= 1)
+        continue;
+
+      pix.SetLoGainMean ( fAreaSum[j] / aevts  );
+      const Double_t diff = fAreaSumSquare[j] - fAreaSum[j]*fAreaSum[j]/aevts ;
+      pix.SetLoGainSigma( diff > 0. ? TMath::Sqrt( diff / (aevts-1) ) : 0.);
+    }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      MHCalibrationPix &hist = GetAverageHiGainSector(j);      
+      MCalibrationPix  &pix  = fCam->GetAverageSector(j);
+
+      if (hist.IsEmpty() || hist.IsOnlyOverflow() || hist.IsOnlyUnderflow())
+        continue;
+      
+      //
+      // 2) Fit the Hi Gain histograms with a Gaussian
+      //
+      TH1F *gaush = hist.GetHGausHist();
+      hist.FitGaus("RQ0",fFitStart,gaush->GetBinCenter(gaush->GetXaxis()->GetLast()));
+      //
+      // 4) Check for oscillations
+      // 
+      if (IsOscillations())
+        hist.CreateFourierSpectrum();
+      //
+      // 5) Retrieve the results and store them in this class
+      //
+      pix.SetHiGainMean       ( hist.GetMean()      );
+      pix.SetHiGainMeanVar    ( hist.GetMeanErr() * hist.GetMeanErr()   );
+      pix.SetHiGainRms        ( hist.GetHistRms()   );
+      pix.SetHiGainSigma      ( hist.GetSigma()     );
+      pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+      pix.SetHiGainProb       ( hist.GetProb()      );
+      pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+      pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+      //
+      // 6) Store calculated means and variances in the low-gain slices
+      //
+      const ULong_t sevts = fNumEvents * fSectorNum[j];
+      if (sevts <= 1)
+        continue;
+
+      pix.SetLoGainMean ( fSectorSum[j] / sevts  );
+      const Double_t diff = fSectorSumSquare[j] - fSectorSum[j]*fSectorSum[j]/sevts ;
+      pix.SetLoGainSigma( diff > 0. ? TMath::Sqrt( diff / (sevts-1) ) : 0.);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Renormalizes the pedestal fit results by the following formulae:
+//
+// - Mean Pedestal        / slice -> Mean Pedestal        / Number slices
+// - Mean Pedestal Error  / slice -> Mean Pedestal Error  / Number slices
+// - Sigma Pedestal       / slice -> Sigma Pedestal       / Sqrt (Number slices)
+// - Sigma Pedestal Error / slice -> Sigma Pedestal Error / Sqrt (Number slices)
+// 
+void MHPedestalCam::RenormResults()
+{
+
+  //
+  // One never knows...
+  //
+  if (fExtractHiGainSlices <= 0)
+    return;
+
+  const Float_t sqslices = TMath::Sqrt(fExtractHiGainSlices);
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MCalibrationPix &pix = (*fCam)[i];
+      MPedestalPix    &ped = (*fPedestalsOut)[i];
+      pix.SetHiGainMean     ( pix.GetHiGainMean()     / fExtractHiGainSlices  );
+      pix.SetLoGainMean     ( pix.GetLoGainMean()     / fExtractHiGainSlices  );
+
+      ped.SetPedestal(pix.GetHiGainMean());
+      //
+      // Mean error goes with PedestalRMS/Sqrt(entries) -> scale with sqrt(slices)
+      // 
+      pix.SetHiGainMeanVar  ( pix.GetHiGainMeanVar()  / fExtractHiGainSlices );
+      pix.SetLoGainMeanVar  ( pix.GetHiGainMeanVar()  / fExtractHiGainSlices );
+
+      //
+      // Sigma goes like PedestalRMS -> scale with sqrt(slices)    
+      //
+      pix.SetHiGainSigma    ( pix.GetHiGainSigma()    / sqslices  );
+      pix.SetLoGainSigma    ( pix.GetLoGainSigma()    / sqslices  );
+
+      ped.SetPedestalRms(pix.GetHiGainSigma());
+      //
+      // Sigma error goes like PedestalRMS/2.(entries) -> scale with sqrt(slices)
+      //
+      pix.SetHiGainSigmaVar ( pix.GetHiGainSigmaVar() / fExtractHiGainSlices );
+      pix.SetLoGainSigmaVar ( pix.GetLoGainSigmaVar() / fExtractHiGainSlices );
+    }
+
+  if (!IsAverageing())
+    return;
+  
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MCalibrationPix  &pix  = fCam->GetAverageArea(j);
+      pix.SetHiGainMean     ( pix.GetHiGainMean()     / fExtractHiGainSlices  );
+      pix.SetLoGainMean     ( pix.GetLoGainMean()     / fExtractHiGainSlices  );
+      pix.SetHiGainMeanVar  ( pix.GetHiGainMeanVar()  / fExtractHiGainSlices  );
+      pix.SetHiGainSigma    ( pix.GetHiGainSigma()    / sqslices  );
+      pix.SetLoGainSigma    ( pix.GetLoGainSigma()    / sqslices  );
+      pix.SetHiGainSigmaVar ( pix.GetHiGainSigmaVar() / fExtractHiGainSlices  );
+  }
+  
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      MCalibrationPix  &pix  = fCam->GetAverageSector(j);
+      pix.SetHiGainMean     ( pix.GetHiGainMean()     / fExtractHiGainSlices  );
+      pix.SetLoGainMean     ( pix.GetLoGainMean()     / fExtractHiGainSlices  );
+      pix.SetHiGainMeanVar  ( pix.GetHiGainMeanVar()  / fExtractHiGainSlices  );
+      pix.SetHiGainSigma    ( pix.GetHiGainSigma()    / sqslices  );
+      pix.SetLoGainSigma    ( pix.GetLoGainSigma()    / sqslices  );
+      pix.SetHiGainSigmaVar ( pix.GetHiGainSigmaVar() / fExtractHiGainSlices  );
+    }
+
+}
+
+
+// ------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Charge
+// 1: Error of fitted Charge
+// 2: Sigma of fitted Charge
+// 3: Error of Sigma of fitted Charge
+//
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Charge distribution
+// 5: Relative differenc of calculated pedestal (per slice) and fitted (per slice)
+// 6: Error of the Relative differenc of calculated pedestal (per slice) and fitted (per slice)
+// 7: Relative difference of the error of the mean pedestal (per slice) - calculated and fitted
+// 8: Relative differenc of calculated pedestal RMS (per slice) and fitted sigma (per slice)
+// 9: Error of Relative differenc of calculated pedestal RMS (per slice) and fitted sigma (per slice)
+// 10: Relative difference of the error of the pedestal RMS (per slice) - calculated and fitted
+//
+// Localized defects:
+// ==================
+//
+// 11: Gaus fit not OK
+// 12: Fourier spectrum not OK
+//
+Bool_t MHPedestalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  if ((*this)[idx].IsExcluded())
+    return kFALSE;
+
+  const Float_t ped      = (*fPedestalsOut)[idx].GetPedestal();
+  const Float_t rms      = (*fPedestalsOut)[idx].GetPedestalRms();
+
+  const Float_t entsqr    =  TMath::Sqrt((Float_t)fPedestalsOut->GetTotalEntries());
+
+  const Float_t pederr   = rms/entsqr;
+  const Float_t rmserr   = rms/entsqr/2.;
+
+  const Float_t mean     = (*this)[idx].GetMean();
+  const Float_t meanerr  = (*this)[idx].GetMeanErr();
+  const Float_t sigma    = (*this)[idx].GetSigma() ;
+  const Float_t sigmaerr = (*this)[idx].GetSigmaErr();
+
+  switch (type)
+    {
+    case 0:
+      val = mean;
+      break;
+    case 1:
+      val = meanerr;
+      break;
+    case 2:
+      val = sigma;
+      break;
+    case 3:
+      val = sigmaerr;
+      break;
+    case 4:
+      val = (*this)[idx].GetProb();
+      break;
+    case 5:
+      val = 2.*(mean-ped)/(ped+mean);
+      break;
+    case 6:
+      val = TMath::Sqrt((pederr*pederr + meanerr*meanerr) * (ped*ped + mean*mean))
+            *2./(ped+mean)/(ped+mean);
+      break;
+    case 7:
+      val = 2.*(meanerr-pederr)/(pederr + meanerr);
+      break;
+    case 8:
+      val = 2.*(sigma-rms)/(sigma+rms);
+      break;
+    case 9:
+      val = TMath::Sqrt((rmserr*rmserr + sigmaerr*sigmaerr) * (rms*rms + sigma*sigma))
+            *2./(rms+sigma)/(rms+sigma);
+      break;
+    case 10:
+      val = 2.*(sigmaerr - rmserr)/(sigmaerr + rmserr);
+      break;
+    case 11:
+      if (!(*this)[idx].IsGausFitOK())
+        val = 1.;
+      break;
+    case 12:
+      if (!(*this)[idx].IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHGausEvents::DrawClone() for pixel idx
+//
+void MHPedestalCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
Index: /tags/Mars-V0.9/mhcalib/MHPedestalCam.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHPedestalCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHPedestalCam.h	(revision 9772)
@@ -0,0 +1,82 @@
+#ifndef MARS_MHPedestalCam
+#define MARS_MHPedestalCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class MGeomCam;
+class MPedestalCam;
+class MHPedestalCam : public MHCalibrationCam
+{
+
+private:
+
+  static const Int_t   fgNbins;           //! Default number of bins        (now set to: 100  )
+  static const Axis_t  fgFirst;           //! Default lower histogram limit (now set to: -50. )
+  static const Axis_t  fgLast;            //! Default upper histogram limit (now set to:  50. )
+                                           
+  static const TString gsHistName;        //! Default Histogram names
+  static const TString gsHistTitle;       //! Default Histogram titles
+  static const TString gsHistXTitle;      //! Default Histogram x-axis titles
+  static const TString gsHistYTitle;      //! Default Histogram y-axis titles
+
+  static const TString fgNamePedestalCam; //! "MPedestalCam"
+  
+  TString fNamePedestalCamOut;            // Name of the 'MPedestalCam' container with results
+
+  ULong_t fNumEvents;                     // Number of processed events
+  
+  Float_t fExtractHiGainSlices;           // Number of FADC slices used for high gain signal extraction
+  Float_t fExtractLoGainSlices;           // Number of FADC slices used for low  gain signal extraction
+
+  MPedestalCam *fPedestalsOut;            //! Pedestal Cam with results
+   
+  Bool_t  fRenorm;                        // Flag if the results will be re-normalized
+
+  Axis_t  fFitStart;                      // Charge value to start the fitting procedure
+  
+  MArrayD fSum;                           //! sum of values  
+  MArrayD fSumSquare;                     //! sum of squared values
+  MArrayD fAreaSum;                       //! averaged sum of values per area idx
+  MArrayD fAreaSumSquare;                 //! averaged sum of squared values per area idx
+  MArrayI fAreaNum;                       //! number of valid pixel with area idx
+  MArrayI fSectorNum;                     //! number of valid pixel with sector idx
+  MArrayD fSectorSum;                     //! averaged sum of values per sector
+  MArrayD fSectorSumSquare;               //! averaged sum of squared values per sector
+  
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  
+  void   InitHiGainArrays( const Int_t npix, const Int_t nareas, const Int_t nsectors );
+  
+  void RenormResults();
+  void FitHists();
+
+public:
+
+  MHPedestalCam(const char *name=NULL, const char *title=NULL);
+
+ // Clone
+  TObject *Clone(const char *name="") const;
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  void ResetHists();
+
+  void SetFitStart          ( const Axis_t a=-0.5  ) { fFitStart = a;  }
+  void SetNamePedestalCamOut( const char *name     ) { fNamePedestalCamOut = name; }
+  void SetPedestalsOut      ( MPedestalCam *cam    ) { fPedestalsOut = cam; }
+  void SetRenorm            ( const Bool_t b=kTRUE ) { fRenorm = b; }
+  
+  ClassDef(MHPedestalCam, 1)	// Histogram class for Charge Camera Pedestals 
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhcalib/MHPedestalPix.cc
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHPedestalPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHPedestalPix.cc	(revision 9772)
@@ -0,0 +1,236 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 02/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHPedestalPix
+//
+//  A base class for events which are believed to follow a Gaussian distribution 
+//  with time, e.g. calibration events, observables containing white noise, ...
+//
+//  MHPedestalPix derives from MHGausEvents, thus all features of 
+//  MHGausEvents can be used by a class deriving from MHPedestalPix
+//
+//  As an additional feature to MHGausEvents, this class offers to skip the fitting 
+//  to set mean, sigma and its errors directly from the histograms with the function 
+//  BypassFit()
+//
+//  See also: MHGausEvents
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHPedestalPix.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TGraph.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHPedestalPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+MHPedestalPix::MHPedestalPix(const char *name, const char *title)
+{ 
+
+  fName  = name  ? name  : "MHPedestalPix";
+  fTitle = title ? title : "Pedestal histogram events";
+
+}
+
+// -------------------------------------------------------------------------------
+//
+// Fits the histogram to a double Gauss.
+//
+//
+Bool_t MHPedestalPix::FitDoubleGaus(const Double_t xmin, const Double_t xmax, Option_t *option)
+{
+
+  if (IsGausFitOK())
+    return kTRUE;
+
+  StripZeros(&fHGausHist,0);
+  
+  TAxis *axe = fHGausHist.GetXaxis();
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetFirst()) : xmin;
+  Axis_t rmax = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetLast())  : xmax;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Stat_t   entries     = fHGausHist.Integral(axe->FindBin(rmin),axe->FindBin(rmax),"width");
+  const Double_t sigma_guess = fHGausHist.GetRMS();
+  const Double_t area_guess  = entries/TMath::Sqrt(TMath::TwoPi())/sigma_guess;
+
+  fFGausFit = new TF1("GausFit","gaus(0)+gaus(3)",rmin,rmax);
+
+  if (!fFGausFit) 
+    {
+    *fLog << warn << dbginf << "WARNING: Could not create fit function for Gauss fit " 
+          << "in: " << fName << endl;
+    return kFALSE;
+    }
+  
+  // 
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  //
+  gROOT->GetListOfFunctions()->Remove(fFGausFit);
+
+  fFGausFit->SetParameters(area_guess/2.,0.,sigma_guess/2.,area_guess/2.,25.,sigma_guess/2.);
+  fFGausFit->SetParNames("Area_{0}","#mu_{0}","#sigma_{0}","Area_{1}","#mu_{1}","#sigma_{1}");
+  fFGausFit->SetParLimits(0,0.,area_guess*5.);
+  fFGausFit->SetParLimits(1,rmin,0.);
+  fFGausFit->SetParLimits(2,0.,rmax-rmin);
+  fFGausFit->SetParLimits(3,0.,area_guess*10.);
+  fFGausFit->SetParLimits(4,0.,rmax/2.);
+  fFGausFit->SetParLimits(5,0.,rmax-rmin);
+  fFGausFit->SetRange(rmin,rmax);
+
+  fHGausHist.Fit(fFGausFit,option);
+
+  SetMean     (fFGausFit->GetParameter(4)-fFGausFit->GetParameter(1));
+  SetSigma    (TMath::Sqrt(fFGausFit->GetParameter(5)*fFGausFit->GetParameter(5)
+                           +fFGausFit->GetParameter(2)*fFGausFit->GetParameter(2)));
+  SetMeanErr  (TMath::Sqrt(fFGausFit->GetParError(4)*fFGausFit->GetParError(4)
+                           +fFGausFit->GetParError(1)*fFGausFit->GetParError(1)));
+  SetSigmaErr (TMath::Sqrt(fFGausFit->GetParError(5)*fFGausFit->GetParError(5)
+                           +fFGausFit->GetParError(2)*fFGausFit->GetParError(2)));
+  SetProb     (fFGausFit->GetProb());
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (default: fgNDFLimit)
+  // 3) The Probability is greater than fProbLimit (default: fgProbLimit)
+  //
+  if (   TMath::IsNaN(GetMean()) 
+      || TMath::IsNaN(GetMeanErr())
+      || TMath::IsNaN(GetProb())    
+      || TMath::IsNaN(GetSigma())
+      || TMath::IsNaN(GetSigmaErr()) 
+      || fProb < fProbLimit )
+    return kFALSE;
+  
+  SetGausFitOK(kTRUE);
+  return kTRUE;
+}
+
+  
+// -------------------------------------------------------------------------------
+//
+// Fits the histogram to a triple Gauss.
+//
+Bool_t MHPedestalPix::FitTripleGaus(const Double_t xmin, const Double_t xmax, Option_t *option)
+{
+
+  if (IsGausFitOK())
+    return kTRUE;
+
+  StripZeros(&fHGausHist,0);
+  
+  TAxis *axe = fHGausHist.GetXaxis();
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetFirst()) : xmin;
+  Axis_t rmax = ((xmin==0.) && (xmax==0.)) ? fHGausHist.GetBinCenter(axe->GetLast())  : xmax;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Stat_t   entries     = fHGausHist.Integral(axe->FindBin(rmin),axe->FindBin(rmax),"width");
+  const Double_t sigma_guess = fHGausHist.GetRMS();
+  const Double_t area_guess  = entries/TMath::Sqrt(TMath::TwoPi())/sigma_guess;
+
+  fFGausFit = new TF1("GausFit","gaus(0)+gaus(3)+gaus(6)",rmin,rmax);
+
+  if (!fFGausFit) 
+    {
+    *fLog << warn << dbginf << "WARNING: Could not create fit function for Gauss fit " 
+          << "in: " << fName << endl;
+    return kFALSE;
+    }
+  
+  // 
+  // For the fits, we have to take special care since ROOT 
+  // has stored the function pointer in a global list which 
+  // lead to removing the object twice. We have to take out 
+  // the following functions of the global list of functions 
+  // as well:
+  //
+  gROOT->GetListOfFunctions()->Remove(fFGausFit);
+
+  fFGausFit->SetParameters(10.,-4.0,1.5,70.,1.5,6.,5.,7.,7.);
+  fFGausFit->SetParNames("Area_{0}","#mu_{0}","#sigma_{0}","Area_{1}","#mu_{1}","#sigma_{1}","Area_{2}","#mu_{2}","#sigma_{2}");
+  fFGausFit->SetParLimits(0,0.,area_guess*2.5);
+  fFGausFit->SetParLimits(1,-9.0,-2.2);
+  fFGausFit->SetParLimits(2,-1.0,15.);
+  fFGausFit->SetParLimits(3,0.,area_guess*10.);
+  fFGausFit->SetParLimits(4,-4.5,2.);
+  fFGausFit->SetParLimits(5,0.,(rmax-rmin)/3.);
+  fFGausFit->SetParLimits(6,0.,area_guess*5.);
+  fFGausFit->SetParLimits(7,6.,20.);
+  fFGausFit->SetParLimits(8,5.,40.);
+  fFGausFit->SetRange(rmin,rmax);
+
+  fHGausHist.Fit(fFGausFit,option);
+
+  SetMean     (fFGausFit->GetParameter(4)-fFGausFit->GetParameter(1));
+  SetSigma    (TMath::Sqrt(fFGausFit->GetParameter(5)*fFGausFit->GetParameter(5)
+                           +fFGausFit->GetParameter(2)*fFGausFit->GetParameter(2)));
+  SetMeanErr  (TMath::Sqrt(fFGausFit->GetParError(4)*fFGausFit->GetParError(4)
+                           +fFGausFit->GetParError(1)*fFGausFit->GetParError(1)));
+  SetSigmaErr (TMath::Sqrt(fFGausFit->GetParError(5)*fFGausFit->GetParError(5)
+                           +fFGausFit->GetParError(2)*fFGausFit->GetParError(2)));
+  SetProb     (fFGausFit->GetProb());
+  //
+  // The fit result is accepted under condition:
+  // 1) The results are not nan's
+  // 2) The NDF is not smaller than fNDFLimit (default: fgNDFLimit)
+  // 3) The Probability is greater than fProbLimit (default: fgProbLimit)
+  //
+  if (   TMath::IsNaN(GetMean()) 
+      || TMath::IsNaN(GetMeanErr())
+      || TMath::IsNaN(GetProb())    
+      || TMath::IsNaN(GetSigma())
+      || TMath::IsNaN(GetSigmaErr()) 
+      || fProb < fProbLimit )
+    return kFALSE;
+  
+  SetGausFitOK(kTRUE);
+  return kTRUE;
+}
+
+  
Index: /tags/Mars-V0.9/mhcalib/MHPedestalPix.h
===================================================================
--- /tags/Mars-V0.9/mhcalib/MHPedestalPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/MHPedestalPix.h	(revision 9772)
@@ -0,0 +1,25 @@
+#ifndef MARS_MHPedestalPix
+#define MARS_MHPedestalPix
+
+#ifndef MARS_MHCalibrationPix
+#include "MHCalibrationPix.h"
+#endif
+
+class MHPedestalPix : public MHCalibrationPix
+{
+public:
+
+  MHPedestalPix(const char* name=NULL, const char* title=NULL);
+
+    // Fits
+  Bool_t FitDoubleGaus(  const Double_t xmin=0., 
+                         const Double_t xmax=0.,
+                         Option_t *option="RQ0");   
+  Bool_t FitTripleGaus(  const Double_t xmin=0., 
+                         const Double_t xmax=0.,
+                         Option_t *option="RQ0");   
+
+  ClassDef(MHPedestalPix, 1) // Base class for histogrammed pedestal events 
+};
+
+#endif
Index: /tags/Mars-V0.9/mhcalib/Makefile
===================================================================
--- /tags/Mars-V0.9/mhcalib/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mhcalib/Makefile	(revision 9772)
@@ -0,0 +1,56 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HCalib
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase  -I../mgui -I../mgeom -I../mhbase -I../mcalib \
+           -I../manalysis -I../mraw -I../mtools -I../mmc -I../mhist  \
+           -I../mimage -I../msignal -I../mbadpixels -I../mpedestal 
+
+# mhbase:    MBinning MH 
+# mgui:      MCamEvent (McalibrationCam)
+# mgeom:     MGeomCam (McalibrationCam - necessary?)
+# mcalib:    MCalibration*Cam
+# manalysis: MExtractedSignal, MCerPhotEvt (move to mcalib?)
+# mraw:      MRawRunHeader, MRawEvtHeader, MRawEvtPixelIter (3xMCalibrationCalc)
+# mmc:       MMcFadcHeader, MMcEvt
+# mimage     MHillas
+
+SRCFILES = MHCalibrationCam.cc \
+           MHCalibrationPix.cc \
+           MHCalibrationChargeCam.cc \
+           MHCalibrationChargePix.cc \
+           MHCalibrationChargeBlindCam.cc \
+           MHCalibrationChargeBlindPix.cc \
+           MHCalibrationChargePINDiode.cc \
+           MHCalibrationRelTimeCam.cc \
+           MHCalibrationHiLoCam.cc \
+           MHCalibrationTestCam.cc \
+           MHCalibrationPulseTimeCam.cc \
+           MHPedestalCam.cc \
+           MHPedestalPix.cc \
+           MHCalibrationTestTimeCam.cc \
+	   MHGausEvents.cc 
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mhflux/FluxIncl.h
===================================================================
--- /tags/Mars-V0.9/mhflux/FluxIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/FluxIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mhflux/FluxLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mhflux/FluxLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/FluxLinkDef.h	(revision 9772)
@@ -0,0 +1,14 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MAlphaFitter+;
+
+#pragma link C++ class MHAlpha+;
+#pragma link C++ class MHEnergyEst+;
+#pragma link C++ class MHFalseSource+;
+#pragma link C++ class MHEffectiveOnTime+;
+
+#endif
Index: /tags/Mars-V0.9/mhflux/MAlphaFitter.cc
===================================================================
--- /tags/Mars-V0.9/mhflux/MAlphaFitter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MAlphaFitter.cc	(revision 9772)
@@ -0,0 +1,588 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MAlphaFitter
+//
+// Create a single Alpha-Plot. The alpha-plot is fitted online. You can
+// check the result when it is filles in the MStatusDisplay
+// For more information see MHFalseSource::FitSignificance
+//
+// For convinience (fit) the output significance is stored in a
+// container in the parlisrt
+//
+// PRELIMINARY!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAlphaFitter.h"
+
+#include <TF1.h>
+#include <TH1.h>
+#include <TH3.h>
+
+#include <TRandom.h>
+
+#include <TLatex.h>
+
+#include "MMath.h"
+
+#include "MLogManip.h"
+
+ClassImp(MAlphaFitter);
+
+using namespace std;
+
+void MAlphaFitter::Clear(Option_t *o)
+{
+    fSignificance=0;
+    fEventsExcess=0;
+    fEventsSignal=0;
+    fEventsBackground=0;
+
+    fChiSqSignal=0;
+    fChiSqBg=0;
+    fIntegralMax=0;
+    fScaleFactor=1;
+
+    fCoefficients.Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a preliminary implementation of a alpha-fit procedure for
+// all possible source positions. It will be moved into its own
+// more powerfull class soon.
+//
+// The fit function is "gaus(0)+pol2(3)" which is equivalent to:
+//   [0]*exp(-0.5*((x-[1])/[2])^2) + [3] + [4]*x + [5]*x^2
+// or
+//   A*exp(-0.5*((x-mu)/sigma)^2) + a + b*x + c*x^2
+//
+// Parameter [1] is fixed to 0 while the alpha peak should be
+// symmetric around alpha=0.
+//
+// Parameter [4] is fixed to 0 because the first derivative at
+// alpha=0 should be 0, too.
+//
+// In a first step the background is fitted between bgmin and bgmax,
+// while the parameters [0]=0 and [2]=1 are fixed.
+//
+// In a second step the signal region (alpha<sigmax) is fittet using
+// the whole function with parameters [1], [3], [4] and [5] fixed.
+//
+// The number of excess and background events are calculated as
+//   s = int(hist,    0, 1.25*sigint)
+//   b = int(pol2(3), 0, 1.25*sigint)
+//
+// The Significance is calculated using the Significance() member
+// function.
+//
+Bool_t MAlphaFitter::Fit(TH1D &h, Bool_t paint)
+{
+    Clear();
+    if (h.GetEntries()==0)
+        return kFALSE;
+
+    Double_t sigmax=fSigMax;
+    Double_t bgmin =fBgMin;
+    Double_t bgmax =fBgMax;
+
+    //*fLog << inf << "Fit: " << sigmax << " " << fSigInt << "  " << bgmin << " " << bgmax << endl;
+
+    //TF1 fFunc("", Form("gaus(0) + pol%d(3)", fPolynomOrder), 0, 90);
+
+    //fFunc->SetParameters(fCoefficients.GetArray());
+
+    fFunc->FixParameter(1, 0);
+    fFunc->FixParameter(4, 0);
+    fFunc->SetParLimits(2, 0, 90);
+    fFunc->SetParLimits(3, -1, 1);
+
+    const Double_t alpha0 = h.GetBinContent(1);
+    const Double_t alphaw = h.GetXaxis()->GetBinWidth(1);
+
+    // Check for the regios which is not filled...
+    if (alpha0==0)
+        return kFALSE; //*fLog << warn << "Histogram empty." << endl;
+
+    // First fit a polynom in the off region
+    fFunc->FixParameter(0, 0);
+    fFunc->FixParameter(2, 1);
+    fFunc->ReleaseParameter(3);
+
+    for (int i=5; i<fFunc->GetNpar(); i++)
+        fFunc->ReleaseParameter(i);
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+    //           E  Perform better Errors estimation using Minos technique
+    h.Fit(fFunc, "NQI", "", bgmin, bgmax);
+
+    fChiSqBg = fFunc->GetChisquare()/fFunc->GetNDF();
+
+    // ------------------------------------
+    if (paint)
+    {
+        fFunc->SetRange(0, 90);
+        fFunc->SetLineColor(kRed);
+        fFunc->SetLineWidth(2);
+        fFunc->Paint("same");
+    }
+    // ------------------------------------
+
+    fFunc->ReleaseParameter(0);
+    //func.ReleaseParameter(1);
+    fFunc->ReleaseParameter(2);
+    fFunc->FixParameter(3, fFunc->GetParameter(3));
+    for (int i=5; i<fFunc->GetNpar(); i++)
+        fFunc->FixParameter(i, fFunc->GetParameter(i));
+
+    // Do not allow signals smaller than the background
+    const Double_t A  = alpha0-fFunc->GetParameter(3);
+    const Double_t dA = TMath::Abs(A);
+    fFunc->SetParLimits(0, -dA*4, dA*4);
+    fFunc->SetParLimits(2, 0, 90);
+
+    // Now fit a gaus in the on region on top of the polynom
+    fFunc->SetParameter(0, A);
+    fFunc->SetParameter(2, sigmax*0.75);
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+    //           E  Perform better Errors estimation using Minos technique
+    h.Fit(fFunc, "NQI", "", 0, sigmax);
+
+    fChiSqSignal = fFunc->GetChisquare()/fFunc->GetNDF();
+    fCoefficients.Set(fFunc->GetNpar(), fFunc->GetParameters());
+
+    //const Bool_t ok = NDF>0 && chi2<2.5*NDF;
+
+    // ------------------------------------
+    if (paint)
+    {
+        fFunc->SetLineColor(kGreen);
+        fFunc->SetLineWidth(2);
+        fFunc->Paint("same");
+    }
+    // ------------------------------------
+
+     //const Double_t s = fFunc->Integral(0, fSigInt)/alphaw;
+     fFunc->SetParameter(0, 0);
+     fFunc->SetParameter(2, 1);
+     //const Double_t b = fFunc->Integral(0, fSigInt)/alphaw;
+     //fSignificance = MMath::SignificanceLiMaSigned(s, b);
+
+    const Int_t bin = h.GetXaxis()->FindFixBin(fSigInt*0.999);
+
+    fIntegralMax      = h.GetBinLowEdge(bin+1);
+    fEventsBackground = fFunc->Integral(0, fIntegralMax)/alphaw;
+    fEventsSignal     = h.Integral(0, bin);
+    fEventsExcess     = fEventsSignal-fEventsBackground;
+    fSignificance     = MMath::SignificanceLiMaSigned(fEventsSignal, fEventsBackground);
+
+    if (fEventsExcess<0)
+        fEventsExcess=0;
+
+    return kTRUE;
+}
+
+Bool_t MAlphaFitter::Fit(const TH1D &hon, const TH1D &hof, Double_t alpha, Bool_t paint)
+{
+    TH1D h(hon);
+    h.Add(&hof, -1); // substracts also number of entries!
+    h.SetEntries(hon.GetEntries());
+
+    MAlphaFitter fit(*this);
+    fit.SetPolynomOrder(1);
+
+    if (alpha<=0 || !fit.Fit(h, paint))
+        return kFALSE;
+
+    fChiSqSignal  = fit.GetChiSqSignal();
+    fChiSqBg      = fit.GetChiSqBg();
+    fCoefficients = fit.GetCoefficients();
+
+    const Int_t bin = hon.GetXaxis()->FindFixBin(fSigInt*0.999);
+
+    fIntegralMax      = hon.GetBinLowEdge(bin+1);
+    fEventsBackground = hof.Integral(0, bin);
+    fEventsSignal     = hon.Integral(0, bin);
+    fEventsExcess     = fEventsSignal-fEventsBackground;
+    fScaleFactor      = alpha;
+    fSignificance     = MMath::SignificanceLiMaSigned(fEventsSignal, fEventsBackground/alpha, alpha);
+
+    if (fEventsExcess<0)
+        fEventsExcess=0;
+/*
+    TF1 func("", "gaus(0)+pol0(3)", 0., 90.);
+
+    const Double_t A  = fEventsSignal/bin;
+    const Double_t dA = TMath::Abs(A);
+    func.SetParLimits(0, -dA*4, dA*4);
+    func.SetParLimits(2, 0, 90);
+    func.SetParLimits(3, -dA, dA);
+
+    func.SetParameter(0, A);
+    func.FixParameter(1, 0);
+    func.SetParameter(2, fSigMax*0.75);
+    func.SetParameter(3, 0);
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+    //           E  Perform better Errors estimation using Minos technique
+    TH1D h(hon);
+    h.Add(&hof, -1);
+    h.Fit(&func, "NQI", "", 0, 90);
+
+    fChiSqSignal = func.GetChisquare()/func.GetNDF();
+
+    const Int_t bin1 = h.GetXaxis()->FindFixBin(func.GetParameter(2)*2);
+
+    fChiSqBg = 0;
+    for (int i=bin1; i<=h.GetNbinsX(); i++)
+    {
+        const Float_t val = h.GetBinContent(i);
+        fChiSqBg = val*val;
+    }
+    if (fChiSqBg>0)
+        fChiSqBg /= h.GetNbinsX()+1-bin1;
+
+    fCoefficients.Set(func.GetNpar(), func.GetParameters());
+
+    // ------------------------------------
+    if (paint)
+    {
+        func.SetLineColor(kBlue);
+        func.SetLineWidth(2);
+        func.Paint("same");
+    }
+    // ------------------------------------
+  */
+    return kTRUE;
+}
+
+void MAlphaFitter::PaintResult(Float_t x, Float_t y, Float_t size) const
+{
+    TLatex text(x, y, Form("\\sigma_{Li/Ma}=%.1f  \\omega=%.1f\\circ  E=%d  (\\alpha<%.1f\\circ)  (\\chi_{b}^{2}/ndf=%.1f  \\chi_{s}^{2}/ndf=%.1f  c_{0}=%.1f)",
+                           fSignificance, GetGausSigma(),
+                           (int)fEventsExcess, fIntegralMax,
+                           fChiSqBg, fChiSqSignal, fCoefficients[3]));
+
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(size);
+    text.Paint();
+}
+
+void MAlphaFitter::Copy(TObject &o) const
+{
+    MAlphaFitter &f = static_cast<MAlphaFitter&>(o);
+
+    f.fSigInt       = fSigInt;
+    f.fSigMax       = fSigMax;
+    f.fBgMin        = fBgMin;
+    f.fBgMax        = fBgMax;
+    f.fScaleMin     = fScaleMin;
+    f.fScaleMax     = fScaleMax;
+    f.fPolynomOrder = fPolynomOrder;
+    f.fScaleMode    = fScaleMode;
+    f.fScaleUser    = fScaleUser;
+    f.fStrategy     = fStrategy;
+    f.fCoefficients.Set(fCoefficients.GetSize());
+    f.fCoefficients.Reset();
+
+    TF1 *fcn = f.fFunc;
+    f.fFunc = new TF1(*fFunc);
+    gROOT->GetListOfFunctions()->Remove(f.fFunc);
+    f.fFunc->SetName("Dummy");
+    delete fcn;
+}
+
+void MAlphaFitter::Print(Option_t *o) const
+{
+    *fLog << inf << GetDescriptor() << ": Fitting..." << endl;
+    *fLog << " ...background from " << fBgMin << " to " << fBgMax << endl;
+    *fLog << " ...signal to " << fSigMax << " (integrate into bin at " << fSigInt << ")" << endl;
+    *fLog << " ...polynom order " << fPolynomOrder << endl;
+    *fLog << " ...scale mode: ";
+    switch (fScaleMode)
+    {
+    case kNone:        *fLog << "none.";         break;
+    case kEntries:     *fLog << "entries.";      break;
+    case kIntegral:    *fLog << "integral.";     break;
+    case kOffRegion:   *fLog << "off region.";   break;
+    case kLeastSquare: *fLog << "least square."; break;
+    case kUserScale:   *fLog << "user def (" << fScaleUser << ")"; break;
+    }
+    *fLog << endl;
+
+    if (TString(o).Contains("result"))
+    {
+        *fLog << "Result:" << endl;
+        *fLog << " - Significance           " << fSignificance << endl;
+        *fLog << " - Excess Events          " << fEventsExcess << endl;
+        *fLog << " - Signal Events          " << fEventsSignal << endl;
+        *fLog << " - Background Events      " << fEventsBackground << endl;
+        *fLog << " - Chi^2/ndf (Signal)     " << fChiSqSignal << endl;
+        *fLog << " - Chi^2/ndf (Background) " << fChiSqBg << endl;
+        *fLog << " - Signal integrated      " << fIntegralMax << "°" << endl;
+    }
+}
+
+Bool_t MAlphaFitter::FitEnergy(const TH3D &hon, UInt_t bin, Bool_t paint)
+{
+    const TString name(Form("TempAlphaEnergy%06d", gRandom->Integer(1000000)));
+    TH1D *h = hon.ProjectionZ(name, -1, 9999, bin, bin, "E");
+    h->SetDirectory(0);
+
+    const Bool_t rc = Fit(*h, paint);
+    delete h;
+    return rc;
+}
+
+Bool_t MAlphaFitter::FitTheta(const TH3D &hon, UInt_t bin, Bool_t paint)
+{
+    const TString name(Form("TempAlphaTheta%06d", gRandom->Integer(1000000)));
+    TH1D *h = hon.ProjectionZ(name, bin, bin, -1, 9999, "E");
+    h->SetDirectory(0);
+
+    const Bool_t rc = Fit(*h, paint);
+    delete h;
+    return rc;
+}
+
+Bool_t MAlphaFitter::FitAlpha(const TH3D &hon, Bool_t paint)
+{
+    const TString name(Form("TempAlpha%06d", gRandom->Integer(1000000)));
+    TH1D *h = hon.ProjectionZ(name, -1, 9999, -1, 9999, "E");
+    h->SetDirectory(0);
+
+    const Bool_t rc = Fit(*h, paint);
+    delete h;
+    return rc;
+}
+
+Bool_t MAlphaFitter::FitEnergy(const TH3D &hon, const TH3D &hof, UInt_t bin, Bool_t paint)
+{
+    const TString name1(Form("TempAlpha%06d_on",  gRandom->Integer(1000000)));
+    const TString name0(Form("TempAlpha%06d_off", gRandom->Integer(1000000)));
+
+    TH1D *h1 = hon.ProjectionZ(name1, -1, 9999, bin, bin, "E");
+    TH1D *h0 = hof.ProjectionZ(name0, -1, 9999, bin, bin, "E");
+    h1->SetDirectory(0);
+    h0->SetDirectory(0);
+
+    const Bool_t rc = ScaleAndFit(*h1, h0, paint);
+
+    delete h0;
+    delete h1;
+
+    return rc;
+}
+
+Bool_t MAlphaFitter::FitTheta(const TH3D &hon, const TH3D &hof, UInt_t bin, Bool_t paint)
+{
+    const TString name1(Form("TempAlpha%06d_on",  gRandom->Integer(1000000)));
+    const TString name0(Form("TempAlpha%06d_off", gRandom->Integer(1000000)));
+
+    TH1D *h1 = hon.ProjectionZ(name1, bin, bin, -1, 9999, "E");
+    TH1D *h0 = hof.ProjectionZ(name0, bin, bin, -1, 9999, "E");
+    h1->SetDirectory(0);
+    h0->SetDirectory(0);
+
+    const Bool_t rc = ScaleAndFit(*h1, h0, paint);
+
+    delete h0;
+    delete h1;
+
+    return rc;
+}
+
+Bool_t MAlphaFitter::FitAlpha(const TH3D &hon, const TH3D &hof, Bool_t paint)
+{
+    const TString name1(Form("TempAlpha%06d_on",  gRandom->Integer(1000000)));
+    const TString name0(Form("TempAlpha%06d_off", gRandom->Integer(1000000)));
+
+    TH1D *h1 = hon.ProjectionZ(name1, -1, 9999, -1, 9999, "E");
+    TH1D *h0 = hof.ProjectionZ(name0, -1, 9999, -1, 9999, "E");
+    h1->SetDirectory(0);
+    h0->SetDirectory(0);
+
+    const Bool_t rc = ScaleAndFit(*h1, h0, paint);
+
+    delete h0;
+    delete h1;
+
+    return rc;
+}
+
+Double_t MAlphaFitter::Scale(TH1D &of, const TH1D &on) const
+{
+    Float_t scaleon = 1;
+    Float_t scaleof = 1;
+    switch (fScaleMode)
+    {
+    case kNone:
+        return 1;
+
+    case kEntries:
+        scaleon = on.GetEntries();
+        scaleof = of.GetEntries();
+        break;
+
+    case kIntegral:
+        scaleon = on.Integral();
+        scaleof = of.Integral();
+        break;
+
+    case kOffRegion:
+        {
+            const Int_t min = on.GetXaxis()->FindFixBin(fScaleMin);
+            const Int_t max = on.GetXaxis()->FindFixBin(fScaleMax);
+            scaleon = on.Integral(min, max);
+            scaleof = of.Integral(min, max);
+        }
+        break;
+
+    case kUserScale:
+        scaleon = fScaleUser;
+        break;
+
+        // This is just to make some compiler happy
+    default:
+        return 1;
+    }
+
+    if (scaleof!=0)
+    {
+        of.Scale(scaleon/scaleof);
+        return scaleon/scaleof;
+    }
+    else
+    {
+        of.Reset();
+        return 0;
+    }
+}
+
+Double_t MAlphaFitter::GetMinimizationValue() const
+{
+    switch (fStrategy)
+    {
+    case kSignificance:
+        return -GetSignificance();
+    case kSignificanceChi2:
+        return -GetSignificance()/GetChiSqSignal();
+    }
+    return 0;
+}
+
+Int_t MAlphaFitter::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    //void SetScaleUser(Float_t scale)       { fScaleUser = scale; fScaleMode=kUserScale; }
+    //void SetScaleMode(ScaleMode_t mode)    { fScaleMode    = mode; }
+
+    if (IsEnvDefined(env, prefix, "SignalIntegralMax", print))
+    {
+        SetSignalIntegralMax(GetEnvValue(env, prefix, "SignalIntegralMax", fSigInt));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "SignalFitMax", print))
+    {
+        SetSignalIntegralMax(GetEnvValue(env, prefix, "SignalFitMax", fSigMax));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "BackgroundFitMax", print))
+    {
+        SetBackgroundFitMax(GetEnvValue(env, prefix, "BackgroundFitMax", fBgMax));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "BackgroundFitMin", print))
+    {
+        SetBackgroundFitMin(GetEnvValue(env, prefix, "BackgroundFitMin", fBgMin));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "ScaleMin", print))
+    {
+        SetScaleMin(GetEnvValue(env, prefix, "ScaleMin", fScaleMin));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "ScaleMax", print))
+    {
+        SetScaleMax(GetEnvValue(env, prefix, "ScaleMax", fScaleMax));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "PolynomOrder", print))
+    {
+        SetPolynomOrder(GetEnvValue(env, prefix, "PolynomOrder", fPolynomOrder));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "MinimizationStrategy", print))
+    {
+        TString txt = GetEnvValue(env, prefix, "MinimizationStrategy", "");
+        txt = txt.Strip(TString::kBoth);
+        txt.ToLower();
+        if (txt==(TString)"significance")
+            fStrategy = kSignificance;
+        if (txt==(TString)"significancechi2")
+            fStrategy = kSignificanceChi2;
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "ScaleMode", print))
+    {
+        TString txt = GetEnvValue(env, prefix, "ScaleMode", "");
+        txt = txt.Strip(TString::kBoth);
+        txt.ToLower();
+        if (txt==(TString)"none")
+            fScaleMode = kNone;
+        if (txt==(TString)"entries")
+            fScaleMode = kEntries;
+        if (txt==(TString)"integral")
+            fScaleMode = kIntegral;
+        if (txt==(TString)"offregion")
+            fScaleMode = kOffRegion;
+        if (txt==(TString)"leastsquare")
+            fScaleMode = kLeastSquare;
+        if (txt==(TString)"userscale")
+            fScaleMode = kUserScale;
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "Scale", print))
+    {
+        fScaleUser = GetEnvValue(env, prefix, "Scale", fScaleUser);
+        rc = kTRUE;
+    }
+
+    return rc;
+}
Index: /tags/Mars-V0.9/mhflux/MAlphaFitter.h
===================================================================
--- /tags/Mars-V0.9/mhflux/MAlphaFitter.h	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MAlphaFitter.h	(revision 9772)
@@ -0,0 +1,170 @@
+#ifndef MARS_MAlphaFitter
+#define MARS_MAlphaFitter
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TF1
+#include <TF1.h>
+#endif
+
+class TH1D;
+class TH3D;
+
+class MAlphaFitter : public MParContainer
+{
+public:
+    enum ScaleMode_t {
+        kNone,
+        kEntries,
+        kIntegral,
+        kOffRegion,
+        kLeastSquare,
+        kUserScale
+    };
+    enum Strategy_t {
+        kSignificance,
+        kSignificanceChi2
+    };
+private:
+    Float_t fSigInt;
+    Float_t fSigMax;
+    Float_t fBgMin;
+    Float_t fBgMax;
+    Float_t fScaleMin;
+    Float_t fScaleMax;
+    Int_t   fPolynomOrder;
+
+    Double_t fSignificance;
+    Double_t fEventsExcess;
+    Double_t fEventsSignal;
+    Double_t fEventsBackground; // fScaleFactor already applied
+
+    Double_t fChiSqSignal;
+    Double_t fChiSqBg;
+    Double_t fIntegralMax;
+    Double_t fScaleFactor;  // Scale factor for off-data
+
+    TArrayD fCoefficients;
+
+    TF1 *fFunc;
+
+    ScaleMode_t fScaleMode;
+    Double_t fScaleUser;
+
+    Strategy_t fStrategy;
+
+public:
+    // Implementing the function yourself is only about 5% faster
+    MAlphaFitter(const char *name=0, const char *title=0) : fSigInt(15), fSigMax(75), fBgMin(45), fBgMax(85), fScaleMin(40), fScaleMax(80), fPolynomOrder(2), fCoefficients(3+fPolynomOrder+1), fFunc(new TF1("", Form("gaus(0) + pol%d(3)", fPolynomOrder), 0, 90)), fScaleMode(kOffRegion), fScaleUser(1), fStrategy(kSignificance)
+    {
+        fName  = name  ? name  : "MAlphaFitter";
+        fTitle = title ? title : "Fit alpha";
+
+        gROOT->GetListOfFunctions()->Remove(fFunc);
+        fFunc->SetName("Dummy");
+
+        Clear();
+    }
+
+    MAlphaFitter(const MAlphaFitter &f) : fFunc(0)
+    {
+        f.Copy(*this);
+    }
+    ~MAlphaFitter()
+    {
+        delete fFunc;
+    }
+
+    void Clear(Option_t *o="");
+    void Print(Option_t *o="") const;
+    void Copy(TObject &o) const;
+    /*
+    TObject *Clone(const char *name) const
+    {
+        return new MAlphaFitter(*this);
+    }
+    */
+
+    void SetScaleUser(Float_t scale)       { fScaleUser = scale; fScaleMode=kUserScale; }
+    void SetScaleMode(ScaleMode_t mode)    { fScaleMode    = mode; }
+    void SetMinimizationStrategy(Strategy_t mode) { fStrategy = mode; }
+    void SetSignalIntegralMax(Float_t s)   { fSigInt       = s; }
+    void SetSignalFitMax(Float_t s)        { fSigMax       = s; }
+    void SetBackgroundFitMin(Float_t s)    { fBgMin        = s; }
+    void SetBackgroundFitMax(Float_t s)    { fBgMax        = s; }
+    void SetScaleMin(Float_t s)            { fScaleMin     = s; }
+    void SetScaleMax(Float_t s)            { fScaleMax     = s; }
+    void SetPolynomOrder(Int_t s)          { if (s==fPolynomOrder) return; fPolynomOrder = s; delete fFunc; fFunc=new TF1 ("", Form("gaus(0) + pol%d(3)", s));
+        gROOT->GetListOfFunctions()->Remove(fFunc);
+        fFunc->SetName("Dummy");
+        fCoefficients.Set(3+s+1); fCoefficients.Reset(); }
+
+    Double_t GetEventsExcess() const       { return fEventsExcess; }
+    Double_t GetEventsSignal() const       { return fEventsSignal; }
+    Double_t GetEventsBackground() const   { return fEventsBackground; }
+
+    Double_t GetSignificance() const       { return fSignificance; }
+    Double_t GetChiSqSignal() const        { return fChiSqSignal; }
+    Double_t GetChiSqBg() const            { return fChiSqBg; }
+    Double_t GetScaleFactor() const        { return fScaleFactor; }
+    Double_t GetMinimizationValue() const;
+
+    Double_t GetGausSigma() const          { return fCoefficients[2]; }
+    Double_t GetGausMu() const             { return fCoefficients[1]; }
+    Double_t GetGausA() const              { return fCoefficients[0]; }
+    Double_t GetCoefficient(Int_t i) const { return fCoefficients[i]; }
+    const TArrayD &GetCoefficients() const { return fCoefficients; }
+
+    void PaintResult(Float_t x=0.04, Float_t y=0.94, Float_t size=0.035) const;
+
+    Bool_t Fit(TH1D &h, Bool_t paint=kFALSE);
+    Bool_t Fit(const TH1D &on, const TH1D &off, Double_t alpha, Bool_t paint=kFALSE);
+    Bool_t Fit(TH1D &on, TH1D *off, Double_t alpha, Bool_t paint=kFALSE)
+    {
+        return off ? Fit(on, *off, alpha, paint) : Fit(on, paint);
+    }
+    Bool_t Fit(TH1D &on, TH1D *off, Bool_t paint=kFALSE)
+    {
+        return off ? Fit(on, *off, 1, paint) : Fit(on, paint);
+    }
+    Bool_t ScaleAndFit(TH1D &on, TH1D *off, Bool_t paint=kFALSE)
+    {
+        const Double_t alpha = off ? Scale(*off, on) : 1;
+        return off ? Fit(on, *off, alpha, paint) : Fit(on, paint);
+    }
+
+    Bool_t FitAlpha(const TH3D &h, Bool_t paint=kFALSE);
+    Bool_t FitEnergy(const TH3D &h, UInt_t bin, Bool_t paint=kFALSE);
+    Bool_t FitTheta(const TH3D &h,  UInt_t bin, Bool_t paint=kFALSE);
+
+    Bool_t FitAlpha(const TH3D &on, const TH3D &off, Bool_t paint=kFALSE);
+    Bool_t FitEnergy(const TH3D &on, const TH3D &off, UInt_t bin, Bool_t paint=kFALSE);
+    Bool_t FitTheta(const TH3D &on, const TH3D &off, UInt_t bin, Bool_t paint=kFALSE);
+
+    Bool_t FitAlpha(const TH3D &on, const TH3D *off, Bool_t paint=kFALSE)
+    {
+        return off ? FitAlpha(on, *off, paint) : FitAlpha(on, paint);
+    }
+    Bool_t FitEnergy(const TH3D &on, const TH3D *off, UInt_t bin, Bool_t paint=kFALSE)
+    {
+        return off ? FitEnergy(on, *off, bin, paint) : FitEnergy(on, bin, paint);
+    }
+    Bool_t FitTheta(const TH3D &on, const TH3D *off, UInt_t bin, Bool_t paint=kFALSE)
+    {
+        return off ? FitTheta(on, *off, bin, paint) : FitTheta(on, bin, paint);
+    }
+
+    Double_t Scale(TH1D &off, const TH1D &on) const;
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MAlphaFitter, 1)
+};
+
+#endif
Index: /tags/Mars-V0.9/mhflux/MHAlpha.cc
===================================================================
--- /tags/Mars-V0.9/mhflux/MHAlpha.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MHAlpha.cc	(revision 9772)
@@ -0,0 +1,918 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHAlpha
+//
+// Create a single Alpha-Plot. The alpha-plot is fitted online. You can
+// check the result when it is filles in the MStatusDisplay
+// For more information see MHFalseSource::FitSignificance
+//
+// For convinience (fit) the output significance is stored in a
+// container in the parlisrt
+//
+// PRELIMINARY!
+//
+//
+// ToDo:
+// =====
+//
+//   - Replace time-binning by histogram (which is enhanced bin-wise)
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHAlpha.h"
+
+#include <TF1.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+#include <TPaveStats.h>
+#include <TStopwatch.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHillasSrc.h"
+#include "MEnergyEst.h"
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MAstroSky2Local.h"
+#include "MStatusDisplay.h"
+#include "MParameters.h"
+#include "MHMatrix.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHAlpha);
+ClassImp(MAlphaFitter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHAlpha::MHAlpha(const char *name, const char *title)
+    : fOffData(0), fResult(0), /*fExcess(0),*/ fEnergy(0), fHillas(0),
+    fPointPos(0), fTimeEffOn(0), fTime(0),
+    fSkipHistTime(kFALSE), fSkipHistTheta(kFALSE), fSkipHistEnergy(kFALSE),
+    fNumTimeBins(10), fMatrix(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHAlpha";
+    fTitle = title ? title : "Alpha plot";
+
+    fHAlpha.SetName("Alpha");
+    fHAlpha.SetTitle("Alpha");
+    fHAlpha.SetXTitle("\\Theta [deg]");
+    fHAlpha.SetYTitle("E_{est} [GeV]");
+    fHAlpha.SetZTitle("|\\alpha| [\\circ]");
+    fHAlpha.SetDirectory(NULL);
+    fHAlpha.UseCurrentStyle();
+
+    // Main histogram
+    fHAlphaTime.SetName("Alpha");
+    fHAlphaTime.SetXTitle("|\\alpha| [\\circ]");
+    fHAlphaTime.SetYTitle("Counts");
+    fHAlphaTime.UseCurrentStyle();
+    fHAlphaTime.SetDirectory(NULL);
+
+
+    //fHEnergy.SetName("Energy");
+    //fHEnergy.SetTitle(" N_{exc} vs. E_{est} ");
+    //fHEnergy.SetXTitle("E_{est} [GeV]");
+    fHEnergy.SetYTitle("N_{exc}");
+    fHEnergy.SetDirectory(NULL);
+    fHEnergy.UseCurrentStyle();
+
+    fHTheta.SetName("Theta");
+    fHTheta.SetTitle(" N_{exc} vs. \\Theta ");
+    fHTheta.SetXTitle("\\Theta [\\circ]");
+    fHTheta.SetYTitle("N_{exc}");
+    fHTheta.SetDirectory(NULL);
+    fHTheta.UseCurrentStyle();
+
+    // effective on time versus time
+    fHTime.SetName("Time");
+    fHTime.SetTitle(" N_{exc} vs. Time ");
+    fHTime.SetXTitle("Time");
+    fHTime.SetYTitle("N_{exc} [s]");
+    fHTime.UseCurrentStyle();
+    fHTime.SetDirectory(NULL);
+    fHTime.GetYaxis()->SetTitleOffset(1.2);
+    fHTime.GetXaxis()->SetLabelSize(0.033);
+    fHTime.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTime.GetXaxis()->SetTimeDisplay(1);
+    fHTime.Sumw2();
+
+    MBinning binsa, binse, binst;
+    binsa.SetEdges(18, 0, 90);
+    binse.SetEdgesLog(25, 10, 100000);
+    binst.SetEdgesCos(50, 0, 60);
+    binse.Apply(fHEnergy);
+    binst.Apply(fHTheta);
+    binsa.Apply(fHAlphaTime);
+
+    MH::SetBinning(&fHAlpha, &binst, &binse, &binsa);
+}
+
+void MHAlpha::FitEnergySpec(Bool_t paint)
+{
+    /*
+    TF1 f("Spectrum", "pow(x, [0])*exp(-x/[1])*[2]*x");//
+    f.SetParameter(0,  -2.1);
+    f.SetParameter(1,  1400); // 50
+    f.SetParameter(2,  fHEnergy.Integral()); // 50
+    f.SetLineWidth(2);
+
+    fHEnergy.Fit(&f,  "0QI", "", 100, 2400); // Integral? 90, 2800
+
+    const Double_t chi2 = f.GetChisquare();
+    const Int_t    NDF  = f.GetNDF();
+
+    // was fit successful ?
+    const Bool_t ok = NDF>0 && chi2<2.5*NDF;
+    f.SetLineColor(ok ? kGreen : kRed);
+
+    if (paint)
+    {
+        f.Paint("same");
+
+        if (ok)
+        {
+        TString s;
+        s += Form("\\alpha=%.1f ",   f.GetParameter(0));
+        s += Form("E_{c}=%.1f TeV ", f.GetParameter(1)/1000);
+        s += Form("N=%.1e",          f.GetParameter(2));
+
+        TLatex text(0.25, 0.94, s.Data());
+        text.SetBit(TLatex::kTextNDC);
+        text.SetTextSize(0.04);
+        text.Paint();
+        }
+    }*/
+}
+
+void MHAlpha::FitEnergyBins(Bool_t paint)
+{
+    // Do not store the 'final' result in fFit
+    MAlphaFitter fit(fFit);
+
+    const Int_t n = fHAlpha.GetNbinsY();
+
+    fHEnergy.SetEntries(0);
+
+    for (int i=1; i<=n; i++)
+    {
+        if (fit.FitEnergy(fHAlpha, fOffData, i))
+        {
+            fHEnergy.SetBinContent(i, fit.GetEventsExcess());
+            fHEnergy.SetBinError(i, fit.GetEventsExcess()*0.2);
+        }
+    }
+}
+
+void MHAlpha::FitThetaBins(Bool_t paint)
+{
+    // Do not store the 'final' result in fFit
+    MAlphaFitter fit(fFit);
+
+    const Int_t n = fHAlpha.GetNbinsX();
+
+    fHTheta.SetEntries(0);
+
+    for (int i=1; i<=n; i++)
+    {
+        if (fit.FitTheta(fHAlpha, fOffData, i))
+        {
+            fHTheta.SetBinContent(i, fit.GetEventsExcess());
+            fHTheta.SetBinError(i, fit.GetEventsExcess()*0.2);
+        }
+    }
+}
+
+Bool_t MHAlpha::SetupFill(const MParList *pl)
+{
+    fHAlpha.Reset();
+    fHEnergy.Reset();
+    fHTheta.Reset();
+    fHTime.Reset();
+
+    if (fName!=(TString)"MHAlphaOff" && fOffData==NULL)
+    {
+        MHAlpha *hoff = (MHAlpha*)pl->FindObject("MHAlphaOff", "MHAlpha");
+        if (!hoff)
+            *fLog << inf << "No MHAlphaOff [MHAlpha] found... using current data only!" << endl;
+        else
+        {
+            *fLog << inf << "MHAlphaOff [MHAlpha] found... using on-off mode!" << endl;
+            SetOffData(*hoff);
+        }
+    }
+
+    fHillas = 0;
+    /*
+    if (fSizeMin>=0 || fSizeMax>=0)
+    {
+        fHillas = (MHillas*)pl->FindObject("MHillas");
+        if (!fHillas)
+        {
+            *fLog << warn << "Size cut set, but MHillas not found... abort." << endl;
+            return kFALSE;
+        }
+    }
+    */
+    fEnergy = (MEnergyEst*)pl->FindObject("MEnergyEst");
+    if (!fEnergy)
+    { /*
+        if (fEnergyMin>=0 || fEnergyMax>=0)
+        {
+            *fLog << warn << "Energy cut set, but MEnergyEst not found... abort." << endl;
+            return kFALSE;
+        } */
+
+        *fLog << warn << "MEnergyEst not found... " << flush;
+
+        if (!fHillas)
+            fHillas = (MHillas*)pl->FindObject("MHillas");
+        if (fHillas)
+            *fLog << "using SIZE instead!" << endl;
+        else
+            *fLog << "ignored." << endl;
+
+        fHEnergy.SetName("Size");
+        fHEnergy.SetTitle(" N_{exc} vs. Size ");
+        fHEnergy.SetXTitle("Size [\\gamma]");
+    }
+    else
+    {
+        fHEnergy.SetName("Energy");
+        fHEnergy.SetTitle(" N_{exc} vs. E_{est} ");
+        fHEnergy.SetXTitle("E_{est} [GeV]");
+    }
+
+    fPointPos = (MPointingPos*)pl->FindObject("MPointingPos");
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... ignored." << endl;
+
+    fTimeEffOn = (MTime*)pl->FindObject("MTimeEffectiveOnTime", "MTime");
+    if (!fTimeEffOn)
+        *fLog << warn << "MTimeEffectiveOnTime [MTime] not found... ignored." << endl;
+    else
+        *fTimeEffOn = MTime(); // FIXME: How to do it different?
+
+    fTime = (MTime*)pl->FindObject("MTime");
+    if (!fTime)
+        *fLog << warn << "MTime not found... ignored." << endl;
+
+    fResult = (MParameterD*)const_cast<MParList*>(pl)->FindCreateObj("MParameterD", "MinimizationValue");
+    if (!fResult)
+        return kFALSE;
+
+    //fExcess = (MParameterD*)const_cast<MParList*>(pl)->FindCreateObj("MParameterD", "MExcess");
+    //if (!fExcess)
+    //    return kFALSE;
+
+    fLastTime = MTime();
+    fNumRebin = fNumTimeBins;
+
+    MBinning binst, binse, binsa;
+    binst.SetEdges(fOffData ? *fOffData : fHAlpha, 'x');
+    binse.SetEdges(fOffData ? *fOffData : fHAlpha, 'y');
+    binsa.SetEdges(fOffData ? *fOffData : fHAlpha, 'z');
+
+    if (!fOffData)
+    {
+        if (!fPointPos)
+            binst.SetEdges(1, 0, 60);
+        else
+            binst.SetEdges(*pl, "BinningTheta");
+
+        if (!fEnergy && !fHillas)
+            binse.SetEdges(1, 10, 100000);
+        else
+            binse.SetEdges(*pl, "BinningEnergyEst");
+
+        binsa.SetEdges(*pl, "BinningAlpha");
+    }
+
+    binse.Apply(fHEnergy);
+    binst.Apply(fHTheta);
+    binsa.Apply(fHAlphaTime);
+    MH::SetBinning(&fHAlpha, &binst, &binse, &binsa);
+
+    MAlphaFitter *fit = (MAlphaFitter*)pl->FindObject("MAlphaFitter");
+    if (!fit)
+        *fLog << warn << "MAlphaFitter not found... ignored." << endl;
+    else
+        fit->Copy(fFit);
+
+    fFit.Print();
+
+    return kTRUE;
+}
+
+void MHAlpha::InitAlphaTime(const MTime &t)
+{
+    //
+    // If this is the first call we have to initialize the time-histogram
+    //
+    MBinning bins;
+    bins.SetEdges(1, t.GetAxisTime()-60, t.GetAxisTime());
+    bins.Apply(fHTime);
+
+    fLastTime=t;
+}
+
+void MHAlpha::UpdateAlphaTime(Bool_t final)
+{
+    if (!fTimeEffOn)
+        return;
+
+    if (!final)
+    {
+        if (fLastTime==MTime() && *fTimeEffOn!=MTime())
+        {
+            InitAlphaTime(*fTimeEffOn);
+            return;
+        }
+
+        if (fLastTime!=*fTimeEffOn)
+        {
+            fLastTime=*fTimeEffOn;
+            fNumRebin--;
+        }
+
+        if (fNumRebin>0)
+            return;
+    }
+
+    // Check new 'last time'
+    MTime *time = final ? fTime : fTimeEffOn;
+
+    if (time->GetAxisTime()<=fHTime.GetXaxis()->GetXmax())
+    {
+        *fLog << warn << "WARNING - New time-stamp " << *time << " lower" << endl;
+        *fLog << "than upper edge of histogram... skipped." << endl;
+        *fLog << "This should not happen. Maybe you started you eventloop with" << endl;
+        *fLog << "an already initialized time stamp MTimeEffectiveOnTime?" << endl;
+        fNumRebin++;
+        return;
+    }
+
+    // Fit time histogram
+    MAlphaFitter fit(fFit);
+
+    TH1D *h = fOffData ? fOffData->ProjectionZ("ProjTimeTemp", -1, 9999, -1, 9999, "E") : 0;
+    const Bool_t rc = fit.ScaleAndFit(fHAlphaTime, h);
+    if (h)
+        delete h;
+
+    if (!rc)
+        return;
+
+    // Reset Histogram
+    fHAlphaTime.Reset();
+    fHAlphaTime.SetEntries(0);
+
+    // Get number of bins
+    const Int_t n = fHTime.GetNbinsX();
+
+    //
+    // Prepare Histogram
+    //
+    if (final)
+        time->Plus1ns();
+
+    // Enhance binning
+    MBinning bins;
+    bins.SetEdges(fHTime, 'x');
+    bins.AddEdge(time->GetAxisTime());
+    bins.Apply(fHTime);
+
+    //
+    // Fill histogram
+    //
+    fHTime.SetBinContent(n+1, fit.GetEventsExcess());
+    fHTime.SetBinError(n+1, fit.GetEventsExcess()*0.1);
+
+    *fLog << all << *fTimeEffOn << ": " << fit.GetEventsExcess() << endl;
+
+    fNumRebin = fNumTimeBins;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Bool_t MHAlpha::Fill(const MParContainer *par, const Stat_t w)
+{
+    Double_t alpha, energy, theta;
+    Double_t size=-1;
+
+    if (fMatrix)
+    {
+        alpha  = (*fMatrix)[fMap[0]];
+        energy = fMap[1]<0 ? -1 : (*fMatrix)[fMap[1]];
+        size   = fMap[2]<0 ? -1 : (*fMatrix)[fMap[2]];
+        //<0 ? 1000 : (*fMatrix)[fMap[1]];
+        theta  = 0;
+
+        if (energy<0)
+            energy=size;
+        if (size<0)
+            size=energy;
+
+        if (energy<0 && size<0)
+            energy = size = 1000;
+    }
+    else
+    {
+        const MHillasSrc *hil = dynamic_cast<const MHillasSrc*>(par);
+        if (!par)
+        {
+            *fLog << err << dbginf << "MHillasSrc not found... abort." << endl;
+            return kFALSE;
+        }
+
+        alpha  = hil->GetAlpha();
+        if (fHillas)
+            size = fHillas->GetSize();
+        energy = fEnergy   ? fEnergy->GetEnergy() : (fHillas?fHillas->GetSize():1000);
+        theta  = fPointPos ? fPointPos->GetZd()   : 0;
+    }
+
+    // enhance histogram if necessary
+    UpdateAlphaTime();
+
+    // Fill histograms
+    fHAlpha.Fill(theta, energy, TMath::Abs(alpha), w);
+
+    // Check cuts
+    /*
+    if ( (fEnergyMin>=0 && energy<fEnergyMin) ||
+         (fEnergyMax>=0 && energy>fEnergyMax) ||
+         (fSizeMin>=0   && size  <fSizeMin)   ||
+         (fSizeMax>=0   && size  >fSizeMin) )
+         return kTRUE;
+         */
+
+    if (!fSkipHistTime)
+        fHAlphaTime.Fill(TMath::Abs(alpha), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Paint the integral and the error on top of the histogram
+//
+void MHAlpha::PaintText(Double_t val, Double_t error) const
+{
+    TLatex text(0.45, 0.94, Form("N_{exc} = %.1f \\pm %.1f", val, error));
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+    text.Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the projections
+//
+void MHAlpha::Paint(Option_t *opt)
+{
+    // Note: Any object cannot be added to a pad twice!
+    //       The object is searched by gROOT->FindObject only in
+    //       gPad itself!
+    TVirtualPad *padsave = gPad;
+
+    TH1D *h0=0;
+
+    TString o(opt);
+    if (o==(TString)"proj")
+    {
+        TPaveStats *st=0;
+        for (int x=0; x<4; x++)
+        {
+            TVirtualPad *p=padsave->GetPad(x+1);
+            if (!p || !(st = (TPaveStats*)p->GetPrimitive("stats")))
+                continue;
+
+            if (st->GetOptStat()==11)
+                continue;
+
+            const Double_t y1 = st->GetY1NDC();
+            const Double_t y2 = st->GetY2NDC();
+            const Double_t x1 = st->GetX1NDC();
+            const Double_t x2 = st->GetX2NDC();
+
+            st->SetY1NDC((y2-y1)/3+y1);
+            st->SetX1NDC((x2-x1)/3+x1);
+            st->SetOptStat(11);
+        }
+
+        padsave->cd(1);
+        TH1D *hon = fHAlpha.ProjectionZ("ProjAlpha");
+        if (fOffData)
+        {
+            TH1D *hoff = fOffData->ProjectionZ("ProjAlphaOff");
+            const Double_t alpha = fFit.Scale(*hoff, *hon);
+
+            hon->SetMaximum();
+            hon->SetMaximum(TMath::Max(hon->GetMaximum(), hoff->GetMaximum())*1.05);
+
+            // BE CARFEULL: This is a really weird workaround!
+            hoff->SetMaximum(alpha);
+
+            if ((h0=(TH1D*)gPad->FindObject("ProjAlphaOnOff")))
+            {
+                h0->Reset();
+                h0->Add(hoff, hon, -1);
+                const Float_t min = h0->GetMinimum()*1.05;
+                hon->SetMinimum(min<0 ? min : 0);
+            }
+        }
+        FitEnergyBins();
+        FitThetaBins();
+    }
+
+    if (o==(TString)"alpha")
+        if ((h0 = (TH1D*)gPad->FindObject("ProjAlpha")))
+        {
+            // Check whether we are dealing with on-off analysis
+            TH1D *hoff = (TH1D*)gPad->FindObject("ProjAlphaOff");
+
+            // BE CARFEULL: This is a really weird workaround!
+            const Double_t scale = !hoff || hoff->GetMaximum()<0 ? 1 : hoff->GetMaximum();
+
+            // Do not store the 'final' result in fFit
+            MAlphaFitter fit(fFit);
+            fit.Fit(*h0, hoff, scale, kTRUE);
+            fit.PaintResult();
+        }
+
+    if (o==(TString)"time")
+        PaintText(fHTime.Integral(), 0);
+
+    if (o==(TString)"theta")
+    {
+        TH1 *h = (TH1*)gPad->FindObject("Alpha_x");
+        if (h)
+        {
+            TH1D *h2 = (TH1D*)fHAlpha.Project3D("dum_x");
+            h2->SetDirectory(0);
+            h2->Scale(fHTheta.Integral()/h2->Integral());
+            h->Reset();
+            h->Add(h2);
+            delete h2;
+        }
+        PaintText(fHTheta.Integral(), 0);
+    }
+
+    if (o==(TString)"energy")
+    {
+        TH1 *h = (TH1*)gPad->FindObject("Alpha_y");
+        if (h)
+        {
+            TH1D *h2 = (TH1D*)fHAlpha.Project3D("dum_y");
+            h2->SetDirectory(0);
+            h2->Scale(fHEnergy.Integral()/h2->Integral());
+            h->Reset();
+            h->Add(h2);
+            delete h2;
+        }
+
+        if (fHEnergy.GetMaximum()>1)
+        {
+            gPad->SetLogx();
+            gPad->SetLogy();
+        }
+        FitEnergySpec(kTRUE);
+    }
+
+    gPad = padsave;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHAlpha::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+    // Do the projection before painting the histograms into
+    // the individual pads
+    AppendPad("proj");
+
+    pad->SetBorderMode(0);
+    pad->Divide(2,2);
+
+    TH1D *h=0;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+
+    h = fHAlpha.ProjectionZ("ProjAlpha", -1, 9999, -1, 9999, "E");
+    h->SetBit(TH1::kNoTitle);
+    h->SetStats(kTRUE);
+    h->SetXTitle("\\alpha [\\circ]");
+    h->SetYTitle("Counts");
+    h->SetDirectory(NULL);
+    h->SetMarkerStyle(kFullDotMedium);
+    h->SetBit(kCanDelete);
+    h->Draw("");
+
+    if (fOffData)
+    {
+        h->SetMarkerColor(kGreen);
+
+        h = fOffData->ProjectionZ("ProjAlphaOff", -1, 9999, -1, 9999, "E");
+        h->SetBit(TH1::kNoTitle);
+        h->SetXTitle("\\alpha [\\circ]");
+        h->SetYTitle("Counts");
+        h->SetDirectory(NULL);
+        h->SetMarkerStyle(kFullDotMedium);
+        h->SetBit(kCanDelete);
+        h->SetMarkerColor(kRed);
+        h->Draw("same");
+
+        h = (TH1D*)h->Clone("ProjAlphaOnOff");
+        h->SetBit(TH1::kNoTitle);
+        h->SetXTitle("\\alpha [\\circ]");
+        h->SetYTitle("Counts");
+        h->SetDirectory(NULL);
+        h->SetMarkerStyle(kFullDotMedium);
+        h->SetBit(kCanDelete);
+        h->SetMarkerColor(kBlue);
+        h->Draw("same");
+
+        TLine lin;
+        lin.SetLineStyle(kDashed);
+        lin.DrawLine(0, 0, 90, 0);
+    }
+
+    // After the Alpha-projection has been drawn. Fit the histogram
+    // and paint the result into this pad
+    AppendPad("alpha");
+
+    if (fHEnergy.GetNbinsX()>1)
+    {
+        pad->cd(2);
+        gPad->SetBorderMode(0);
+        fHEnergy.Draw();
+
+        AppendPad("energy");
+
+        h = (TH1D*)fHAlpha.Project3D("y");
+        h->SetBit(TH1::kNoTitle|TH1::kNoStats);
+        h->SetXTitle("E [GeV]");
+        h->SetYTitle("Counts");
+        h->SetDirectory(NULL);
+        h->SetMarkerStyle(kFullDotMedium);
+        h->SetBit(kCanDelete);
+        h->SetMarkerColor(kCyan);
+        h->SetLineColor(kCyan);
+        h->Draw("Psame");
+    }
+    else
+        delete pad->GetPad(2);
+
+    if (fTimeEffOn && fTime || fHTime.GetNbinsX()>1)
+    {
+        pad->cd(3);
+        gPad->SetBorderMode(0);
+        fHTime.Draw();
+        AppendPad("time");
+    }
+    else
+        delete pad->GetPad(3);
+
+    if (fHTheta.GetNbinsX()>1)
+    {
+        pad->cd(4);
+        gPad->SetBorderMode(0);
+        fHTheta.Draw();
+
+        AppendPad("theta");
+
+        h = (TH1D*)fHAlpha.Project3D("x");
+        h->SetBit(TH1::kNoTitle|TH1::kNoStats);
+        h->SetXTitle("\\theta [\\circ]");
+        h->SetYTitle("Counts");
+        h->SetDirectory(NULL);
+        h->SetMarkerStyle(kFullDotMedium);
+        h->SetBit(kCanDelete);
+        h->SetMarkerColor(kCyan);
+        h->SetLineColor(kCyan);
+        h->Draw("Psame");
+    }
+    else
+        delete pad->GetPad(4);
+}
+
+void MHAlpha::DrawAll()
+{
+    // FIXME: Do in Paint if special option given!
+    TCanvas *c = new TCanvas;
+    Int_t n = fHAlpha.GetNbinsY();
+    Int_t nc = (Int_t)(TMath::Sqrt((Float_t)n-1)+1);
+    c->Divide(nc, nc, 0, 0);
+
+    // Do not store the 'final' result in fFit
+    MAlphaFitter fit(fFit);
+
+    for (int i=1; i<=fHAlpha.GetNbinsY(); i++)
+    {
+        c->cd(i);
+
+        TH1D *hon = fHAlpha.ProjectionZ("ProjAlpha", -1, 9999, i, i, "E");
+        hon->SetBit(TH1::kNoTitle);
+        hon->SetStats(kTRUE);
+        hon->SetXTitle("\\alpha [\\circ]");
+        hon->SetYTitle("Counts");
+        hon->SetDirectory(NULL);
+        hon->SetMarkerStyle(kFullDotMedium);
+        hon->SetBit(kCanDelete);
+        hon->Draw("");
+
+        TH1D *hof = 0;
+        Double_t alpha = 1;
+
+        if (fOffData)
+        {
+            hon->SetMarkerColor(kGreen);
+
+            hof = fOffData->ProjectionZ("ProjAlphaOff", -1, 9999, i, i, "E");
+            hof->SetBit(TH1::kNoTitle|TH1::kNoStats);
+            hof->SetXTitle("\\alpha [\\circ]");
+            hof->SetYTitle("Counts");
+            hof->SetDirectory(NULL);
+            hof->SetMarkerStyle(kFullDotMedium);
+            hof->SetBit(kCanDelete);
+            hof->SetMarkerColor(kRed);
+            hof->Draw("same");
+
+            alpha = fit.Scale(*hof, *hon);
+
+            hon->SetMaximum();
+            hon->SetMaximum(TMath::Max(hon->GetMaximum(), hof->GetMaximum())*1.05);
+
+            TH1D *diff = new TH1D(*hon);
+            diff->Add(hof, -1);
+            diff->SetBit(TH1::kNoTitle);
+            diff->SetXTitle("\\alpha [\\circ]");
+            diff->SetYTitle("Counts");
+            diff->SetDirectory(NULL);
+            diff->SetMarkerStyle(kFullDotMedium);
+            diff->SetBit(kCanDelete);
+            diff->SetMarkerColor(kBlue);
+            diff->Draw("same");
+
+            TLine lin;
+            lin.SetLineStyle(kDashed);
+            lin.DrawLine(0, 0, 90, 0);
+
+            const Float_t min = diff->GetMinimum()*1.05;
+            hon->SetMinimum(min<0 ? min : 0);
+        }
+
+        if (hof ? fit.Fit(*hon, *hof, alpha) : fit.Fit(*hon))
+            *fLog << dbg << "Bin " << i << ": sigma=" << fit.GetSignificance() << " omega=" << fit.GetGausSigma() << " events=" << fit.GetEventsExcess() << endl;
+        /*
+        if (fit.FitEnergy(fHAlpha, fOffData, i, kTRUE))
+        {
+            fHEnergy.SetBinContent(i, fit.GetEventsExcess());
+            fHEnergy.SetBinError(i, fit.GetEventsExcess()*0.2);
+        }*/
+    }
+
+}
+
+
+Bool_t MHAlpha::Finalize()
+{
+    //TH1D *h = fHAlpha.ProjectionZ("AlphaExc_px", -1, 9999, -1, 9999, "E");
+    //h->SetDirectory(0);
+    //Bool_t rc = fFit.Fit(*h);
+    //delete h;
+
+    if (!fFit.FitAlpha(fHAlpha, fOffData))
+    {
+        *fLog << warn << "MAlphaFitter - Fit failed..." << endl;
+        return kTRUE;
+    }
+
+    // Store the final result in fFit
+    fFit.Print("result");
+
+    fResult->SetVal(fFit.GetMinimizationValue());
+
+    if (!fSkipHistEnergy)
+    {
+        *fLog << inf << "Processing energy bins..." << endl;
+        FitEnergyBins();
+    }
+    if (!fSkipHistTheta)
+    {
+        *fLog << inf << "Processing theta bins..." << endl;
+        FitThetaBins();
+    }
+    if (!fSkipHistTime)
+    {
+        *fLog << inf << "Processing time bins..." << endl;
+        UpdateAlphaTime(kTRUE);
+        MH::RemoveFirstBin(fHTime);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of
+// MMcEvt. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MHHadronness::Fill
+// will take the values from the matrix instead of the containers.
+//
+// It takes fSkipHist* into account!
+//
+void MHAlpha::InitMapping(MHMatrix *mat, Int_t type)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MHillasSrc.fAlpha");
+    fMap[1] = -1;
+    fMap[2] = -1;
+    fMap[3] = -1;
+    fMap[4] = -1;
+
+    if (!fSkipHistEnergy)
+        if (type==0)
+        {
+            fMap[1] = fMatrix->AddColumn("MEnergyEst.fEnergy");
+            fMap[2] = -1;
+        }
+        else
+        {
+            fMap[1] = -1;
+            fMap[2] = fMatrix->AddColumn("MHillas.fSize");
+        }
+
+    if (!fSkipHistTheta)
+        fMap[3] = fMatrix->AddColumn("MPointingPos.fZd");
+
+   // if (!fSkipHistTime)
+   //     fMap[4] = fMatrix->AddColumn("MTime.GetAxisTime");
+}
+
+void MHAlpha::StopMapping()
+{
+    fMatrix = NULL; 
+}
+
+Int_t MHAlpha::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "NumTimeBins", print))
+    {
+        SetNumTimeBins(GetEnvValue(env, prefix, "NumTimeBins", fNumTimeBins));
+        rc = kTRUE;
+    }
+    return rc;
+}
Index: /tags/Mars-V0.9/mhflux/MHAlpha.h
===================================================================
--- /tags/Mars-V0.9/mhflux/MHAlpha.h	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MHAlpha.h	(revision 9772)
@@ -0,0 +1,178 @@
+#ifndef MARS_MHAlpha
+#define MARS_MHAlpha
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+#ifndef MARS_MAlphaFitter
+#include "MAlphaFitter.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+class MParList;
+class MParameterD;
+class MEnergyEst;
+class MHillas;
+class MHMatrix;
+class MPointingPos;
+
+/*
+class MAlphaFitter : public MParContainer
+{
+private:
+    Float_t fSigInt;
+    Float_t fSigMax;
+    Float_t fBgMin;
+    Float_t fBgMax;
+    Int_t   fPolynom;
+
+    Double_t fSignificance;
+    Double_t fExcessEvents;
+    Double_t fChiSqSignal;
+    Double_t fChiSqBg;
+    Double_t fSigmaGaus;
+    Double_t fIntegralMax;
+
+public:
+    MAlphaFitter() : fSigInt(10), fSigMax(75), fBgMin(45), fBgMax(85), fPolynom(2)
+    {
+    }
+
+    MAlphaFitter(const MAlphaFitter &f)
+    {
+        f.Copy(*this);
+    }
+
+    void Copy(TObject &o) const
+    {
+        MAlphaFitter &f = static_cast<MAlphaFitter&>(o);
+
+        f.fSigInt  = fSigInt;
+        f.fSigMax  = fSigMax;
+        f.fBgMin   = fBgMin;
+        f.fBgMax   = fBgMax;
+        f.fPolynom = fPolynom;
+    }
+
+    void SetSignalIntegralMax(Float_t s) { fSigInt = s; }
+    void SetSignalFitMax(Float_t s)      { fSigMax = s; }
+    void SetBackgroundFitMin(Float_t s)  { fBgMin = s; }
+    void SetBackgroundFitMax(Float_t s)  { fBgMax = s; }
+    void SetNumPolynom(Int_t s)          { fPolynom = s; }
+
+    Double_t GetExcessEvents() const { return fExcessEvents; }
+    Double_t GetSignificance() const { return fSignificance; }
+    Double_t GetChiSqSignal() const  { return fChiSqSignal; }
+    Double_t GetChiSqBg() const      { return fChiSqBg; }
+    Double_t GetSigmaGaus() const    { return fSigmaGaus; }
+
+    void PaintResult(Float_t x=0.04, Float_t y=0.94, Float_t size=0.035) const;
+
+    Bool_t Fit(TH1D &h, Bool_t paint=kFALSE);
+    ClassDef(MAlphaFitter, 1)
+};
+*/
+
+class MHAlpha : public MH
+{
+private:
+    const TH3D *fOffData;
+
+    MAlphaFitter fFit;          // SEEMS THAT STREAMER HAS SOME PROBLEMS... MAYBE IF FUNC IS USED AT THE SAME TIME FOR FITS (PAINT)
+
+    TH3D fHAlpha;               // Alpha vs. theta and energy
+    TH1D fHEnergy;              // excess events vs energy
+    TH1D fHTheta;               // excess events vs theta
+    TH1D fHTime;                // excess events vs time;
+    TH1D fHAlphaTime;           //! temporary histogram to get alpha vs. time
+
+    MParameterD  *fResult;      //!
+    MEnergyEst   *fEnergy;      //!
+    MHillas      *fHillas;      //!
+    MPointingPos *fPointPos;    //!
+
+    MTime   *fTimeEffOn;        //! Time to steer filling of fHTime
+    MTime   *fTime;             //! Event-Time to finalize fHTime
+    MTime    fLastTime;         //! Last fTimeEffOn
+
+    Bool_t fSkipHistTime;
+    Bool_t fSkipHistTheta;
+    Bool_t fSkipHistEnergy;
+
+    UShort_t fNumTimeBins;      // Number of time bins to fill together
+    UShort_t fNumRebin;         //!
+
+    //const TString fNameProjAlpha;  //! This should make sure, that gROOT doen't confuse the projection with something else
+
+    MHMatrix *fMatrix;          //!
+    Int_t fMap[5];              //!
+
+    void FitEnergySpec(Bool_t paint=kFALSE);
+    void FitEnergyBins(Bool_t paint=kFALSE);
+    void FitThetaBins(Bool_t paint=kFALSE);
+
+    void UpdateAlphaTime(Bool_t final=kFALSE);
+    void InitAlphaTime(const MTime &t);
+    void FinalAlphaTime(MBinning &bins);
+
+    void PaintText(Double_t val, Double_t error) const;
+
+    Int_t DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+public:
+    MHAlpha(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pl);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    const TH3D &GetHist() const { return fHAlpha; }
+    const MAlphaFitter &GetAlphaFitter() const { return fFit; }
+
+    void SetOffData(const MHAlpha &h)
+    {
+        fOffData = &h.fHAlpha;
+    }
+    void SetNumTimeBins(UShort_t n) { fNumTimeBins = n; }
+/*
+    void SetSizeCuts(Float_t min, Float_t max)   { fSizeMin=min; fSizeMax=max; }
+    void SetSizeMin(Float_t min)                 { fSizeMin=min; }
+    void SetSizeMax(Float_t max)                 { fSizeMax=max; }
+    void SetEnergyCuts(Float_t min, Float_t max) { fEnergyMin=min; fEnergyMax=max; }
+    void SetEnergyMin(Float_t min)               { fEnergyMin=min; }
+    void SetEnergyMax(Float_t max)               { fEnergyMax=max; }
+
+    void SetCuts(const MHAlpha &h) {
+        fSizeMin = h.fSizeMin; fEnergyMin = h.fEnergyMin;
+        fSizeMax = h.fSizeMax; fEnergyMax = h.fEnergyMax;
+    }
+    */
+
+    void SkipHistTime(Bool_t b=kTRUE)   { fSkipHistTime=b; }
+    void SkipHistTheta(Bool_t b=kTRUE)  { fSkipHistTheta=b; }
+    void SkipHistEnergy(Bool_t b=kTRUE) { fSkipHistEnergy=b; }
+
+    void DrawAll(); //*MENU*
+
+    void InitMapping(MHMatrix *mat, Int_t type=0);
+    void StopMapping();
+
+    // TObject
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *option="");
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    ClassDef(MHAlpha, 1) // Alpha-Plot which is fitted online
+};
+
+#endif
Index: /tags/Mars-V0.9/mhflux/MHEffectiveOnTime.cc
===================================================================
--- /tags/Mars-V0.9/mhflux/MHEffectiveOnTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MHEffectiveOnTime.cc	(revision 9772)
@@ -0,0 +1,828 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek, 1/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHEffectiveOnTime
+//
+//  Filling this you will get the effective on-time versus theta and
+//  observation time.
+//
+//  From this histogram the effective on-time is determined by a fit.
+//  The result of the fit (see Fit()) and the fit-parameters (like chi^2)
+//  are stored in corresponding histograms
+//
+//  To determin the efective on time a poisson fit is done. For more details
+//  please have a look into the source code of FitH() it should be simple
+//  to understand. In this function a Delta-T distribution is fitted, while
+//  Delta-T is the time between two consecutive events.
+//
+//  The fit is done for projections of a 2D histogram in Theta and Delta T.
+//  So you get the effective on time versus theta.
+//
+//  To get the effective on-time versus time a histogram is filled with
+//  the Delta-T distribution of a number of events set by SetNumEvents().
+//  The default is 12000 (roughly 1min at 200Hz)
+//
+//  For each "time-bin" the histogram is fitted and the resulting effective
+//  on-time is stored in the fHTimeEffOn histogram. Each entry in this
+//  histogram is the effective observation time between the upper and
+//  lower edges of the bins.
+//
+//  In addition the calculated effective on time is stored in a
+//  "MEffectiveOnTime [MParameterDerr]" and the corresponding time-stamp
+//  (the upper edge of the bin) "MTimeEffectiveOnTime [MTime]"
+//
+//  The class takes two binnings from the Parameter list; if these binnings
+//  are not available the defaultbinning is used:
+//      MBinning("BinningDeltaT"); // Units of seconds
+//      MBinning("BinningTheta");  // Units of degrees
+//
+//
+//  Usage:
+//  ------
+//    MFillH fill("MHEffectiveOnTime", "MTime");
+//    tlist.AddToList(&fill);
+//
+//
+//  Input Container:
+//    MPointingPos
+//
+//  Output Container:
+//    MEffectiveOnTime [MParameterDerr]
+//    MTimeEffectiveOnTime [MTime]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHEffectiveOnTime.h"
+
+#include <TF1.h>
+#include <TMinuit.h>
+#include <TRandom.h>
+
+#include <TLatex.h>
+#include <TGaxis.h>
+#include <TCanvas.h>
+#include <TPaveStats.h>
+
+#include "MTime.h"
+#include "MParameters.h"
+#include "MPointingPos.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHEffectiveOnTime);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It initializes all histograms.
+//
+MHEffectiveOnTime::MHEffectiveOnTime(const char *name, const char *title)
+    : fPointPos(0), fTime(0), fParam(0), fIsFinalized(kFALSE), 
+    fNumEvents(200*60)/*, fNameProjDeltaT(Form("DeltaT_%p", this)),
+    fNameProjTheta(Form("Theta_%p", this))*/
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHEffectiveOnTime";
+    fTitle = title ? title : "Histogram to determin effective On-Time vs Time and Zenith Angle";
+
+    // Main histogram
+    fH2DeltaT.SetName("DeltaT");
+    fH2DeltaT.SetXTitle("\\Delta t [s]");
+    fH2DeltaT.SetYTitle("\\Theta [\\circ]");
+    fH2DeltaT.SetZTitle("Count");
+    fH2DeltaT.UseCurrentStyle();
+    fH2DeltaT.SetDirectory(NULL);
+
+    // Main histogram
+    fH1DeltaT.SetName("DeltaT");
+    fH1DeltaT.SetXTitle("\\Delta t [s]");
+    fH1DeltaT.SetYTitle("Counts");
+    fH1DeltaT.UseCurrentStyle();
+    fH1DeltaT.SetDirectory(NULL);
+
+    // effective on time versus theta
+    fHThetaEffOn.SetName("EffOnTheta");
+    fHThetaEffOn.SetTitle("Effective On Time T_{eff}");
+    fHThetaEffOn.SetXTitle("\\Theta [\\circ]");
+    fHThetaEffOn.SetYTitle("T_{eff} [s]");
+    fHThetaEffOn.UseCurrentStyle();
+    fHThetaEffOn.SetDirectory(NULL);
+    fHThetaEffOn.GetYaxis()->SetTitleOffset(1.2);
+    fHThetaEffOn.GetYaxis()->SetTitleColor(kBlue);
+    fHThetaEffOn.SetLineColor(kBlue);
+    //fHEffOn.Sumw2();
+
+    // effective on time versus time
+    fHTimeEffOn.SetName("EffOnTime");
+    fHTimeEffOn.SetTitle("Effective On Time T_{eff}");
+    fHTimeEffOn.SetXTitle("Time");
+    fHTimeEffOn.SetYTitle("T_{eff} [s]");
+    fHTimeEffOn.UseCurrentStyle();
+    fHTimeEffOn.SetDirectory(NULL);
+    fHTimeEffOn.GetYaxis()->SetTitleOffset(1.2);
+    fHTimeEffOn.GetXaxis()->SetLabelSize(0.033);
+    fHTimeEffOn.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTimeEffOn.GetXaxis()->SetTimeDisplay(1);
+    fHTimeEffOn.GetYaxis()->SetTitleColor(kBlue);
+    fHTimeEffOn.SetLineColor(kBlue);
+
+    // chi2 probability
+    fHThetaProb.SetName("ProbTheta");
+    fHThetaProb.SetTitle("\\chi^{2} Probability of Fit");
+    fHThetaProb.SetXTitle("\\Theta [\\circ]");
+    fHThetaProb.SetYTitle("p [%]");
+    fHThetaProb.UseCurrentStyle();
+    fHThetaProb.SetDirectory(NULL);
+    fHThetaProb.GetYaxis()->SetTitleOffset(1.2);
+    fHThetaProb.SetMaximum(101);
+    fHThetaProb.GetYaxis()->SetTitleColor(kBlue);
+    fHThetaProb.SetLineColor(kBlue);
+
+    // chi2 probability
+    fHTimeProb.SetName("ProbTime");
+    fHTimeProb.SetTitle("\\chi^{2} Probability of Fit");
+    fHTimeProb.SetXTitle("Time");
+    fHTimeProb.SetYTitle("p [%]");
+    fHTimeProb.UseCurrentStyle();
+    fHTimeProb.SetDirectory(NULL);
+    fHTimeProb.GetYaxis()->SetTitleOffset(1.2);
+    fHTimeProb.GetXaxis()->SetLabelSize(0.033);
+    fHTimeProb.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTimeProb.GetXaxis()->SetTimeDisplay(1);
+    fHTimeProb.SetMaximum(101);
+    fHTimeProb.GetYaxis()->SetTitleColor(kBlue);
+    fHTimeProb.SetLineColor(kBlue);
+
+    // lambda versus theta
+    fHThetaLambda.SetName("LambdaTheta");
+    fHThetaLambda.SetTitle("Slope (Rate) vs Theta");
+    fHThetaLambda.SetXTitle("\\Theta [\\circ]");
+    fHThetaLambda.SetYTitle("\\lambda [s^{-1}]");
+    fHThetaLambda.UseCurrentStyle();
+    fHThetaLambda.SetDirectory(NULL);
+    fHThetaLambda.SetLineColor(kGreen);
+
+    // lambda versus time
+    fHTimeLambda.SetName("LambdaTime");
+    fHTimeLambda.SetTitle("Slope (Rate) vs Time");
+    fHTimeLambda.SetXTitle("\\Time [\\circ]");
+    fHTimeLambda.SetYTitle("\\lambda [s^{-1}]");
+    fHTimeLambda.UseCurrentStyle();
+    fHTimeLambda.SetDirectory(NULL);
+    fHTimeLambda.GetYaxis()->SetTitleOffset(1.2);
+    fHTimeLambda.GetXaxis()->SetLabelSize(0.033);
+    fHTimeLambda.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTimeLambda.GetXaxis()->SetTimeDisplay(1);
+    fHTimeLambda.SetLineColor(kGreen);
+
+    // NDoF versus theta
+    fHThetaNDF.SetName("NDofTheta");
+    fHThetaNDF.SetTitle("Number of Degrees of freedom vs Theta");
+    fHThetaNDF.SetXTitle("\\Theta [\\circ]");
+    fHThetaNDF.SetYTitle("NDoF [#]");
+    fHThetaNDF.UseCurrentStyle();
+    fHThetaNDF.SetDirectory(NULL);
+    fHThetaNDF.SetLineColor(kGreen);
+
+    // NDoF versus time
+    /*
+    fHTimeNDF.SetName("NDofTime");
+    fHTimeNDF.SetTitle("Number of Degrees of freedom vs Time");
+    fHTimeNDF.SetXTitle("Time");
+    fHTimeNDF.SetYTitle("NDoF [#]");
+    fHTimeNDF.UseCurrentStyle();
+    fHTimeNDF.SetDirectory(NULL);
+    fHTimeNDF.GetYaxis()->SetTitleOffset(1.2);
+    fHTimeNDF.GetXaxis()->SetLabelSize(0.033);
+    fHTimeNDF.GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+    fHTimeNDF.GetXaxis()->SetTimeDisplay(1);
+    fHTimeNDF.SetLineColor(kBlue);
+    */
+    // setup binning
+    MBinning btheta("BinningTheta");
+    btheta.SetEdgesCos(100, 0, 60);
+
+    MBinning btime("BinningDeltaT");
+    btime.SetEdges(50, 0, 0.1);
+
+    MH::SetBinning(&fH2DeltaT, &btime, &btheta);
+
+    btime.Apply(fH1DeltaT);
+
+    btheta.Apply(fHThetaEffOn);
+    btheta.Apply(fHThetaLambda);
+    btheta.Apply(fHThetaNDF);
+    btheta.Apply(fHThetaProb);
+    //btheta.Apply(fHChi2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHEffectiveOnTime::SetupFill(const MParList *plist)
+{
+   fPointPos = (MPointingPos*)plist->FindObject("MPointingPos");
+   if (!fPointPos)
+   {
+       *fLog << err << dbginf << "MPointingPos not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   // FIXME: Remove const-qualifier from base-class!
+   fTime = (MTime*)const_cast<MParList*>(plist)->FindCreateObj("MTime", "MTimeEffectiveOnTime");
+   if (!fTime)
+       return kFALSE;
+   fParam = (MParameterDerr*)const_cast<MParList*>(plist)->FindCreateObj("MParameterDerr", "MEffectiveOnTime");
+   if (!fParam)
+       return kFALSE;
+
+   const MBinning* binsdtime = (MBinning*)plist->FindObject("BinningDeltaT");
+   const MBinning* binstheta = (MBinning*)plist->FindObject("BinningTheta");
+   if (binsdtime)
+       binsdtime->Apply(fH1DeltaT);
+   if (binstheta)
+   {
+       binstheta->Apply(fHThetaEffOn);
+       binstheta->Apply(fHThetaLambda);
+       binstheta->Apply(fHThetaNDF);
+       binstheta->Apply(fHThetaProb);
+       //binstheta->Apply(fHChi2);
+   }
+   if (binstheta && binsdtime)
+       SetBinning(&fH2DeltaT, binsdtime, binstheta);
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fit a single Delta-T distribution. See source code for more details
+//
+Bool_t MHEffectiveOnTime::FitH(TH1D *h, Double_t *res, Bool_t paint) const
+{
+    const Double_t Nm = h->Integral();
+
+    // FIXME: Do fit only if contents of bin has changed
+    if (Nm<=0)
+        return kFALSE;
+
+    // determine range (yq[0], yq[1]) of time differences
+    // where fit should be performed;
+    // require a fraction >=xq[0] of all entries to lie below yq[0]
+    //     and a fraction <=xq[1] of all entries to lie below yq[1];
+    // within the range (yq[0], yq[1]) there must be no empty bin;
+    // choose pedestrian approach as long as GetQuantiles is not available
+    Double_t xq[2] = { 0.6, 0.99 };
+    Double_t yq[2];
+    h->GetQuantiles(2, yq, xq);
+
+    // Nmdel = Nm * binwidth,  with Nm = number of observed events
+    const Double_t Nmdel = h->Integral("width");
+
+    //
+    // Setup Poisson function for the fit:
+    // lambda [Hz], N0 = ideal no of evts, del = bin width of dt
+    //
+    // parameter 0 = lambda
+    // parameter 1 = N0*del
+    //
+    TF1 func("Poisson", " [1]*[2] * [0] * exp(-[0] *x)");
+    //func.SetParNames("lambda", "N0", "del");
+
+    func.SetParameter(0, 200);       // Hz
+    func.SetParameter(1, Nm);
+    func.FixParameter(2, Nmdel/Nm);
+
+    // options : N  do not store the function, do not draw
+    //           I  use integral of function in bin rather than value at bin center
+    //           R  use the range specified in the function range
+    //           Q  quiet mode
+    h->Fit(&func, "NIQE", "", yq[0], yq[1]);
+
+    const Double_t chi2 = func.GetChisquare();
+    const Int_t    NDF  = func.GetNDF();
+
+    // was fit successful ?
+    const Bool_t ok = NDF>0 && chi2<3*NDF;
+
+    if (paint)
+    {
+        func.SetLineWidth(2);
+        func.SetLineColor(ok ? kGreen : kRed);
+        func.Paint("same");
+    }
+
+    const Double_t lambda = func.GetParameter(0);
+    //const Double_t N0     = func.GetParameter(1);
+    const Double_t prob   = func.GetProb();
+
+    /*
+     *fLog << all << "Nm/lambda=" << Nm/lambda << "  chi2/NDF=";
+     *fLog << (NDF ? chi2/NDF : 0.0) << "  lambda=";
+     *fLog << lambda << "  N0=" << N0 << endl;
+     */
+
+    Double_t emat[2][2];
+    gMinuit->mnemat((Double_t*)emat, 2);
+
+    const Double_t dldl  = emat[0][0];
+    //const Double_t dN0dN0 = emat[1][1];
+
+    const Double_t teff  = Nm/lambda;
+    const Double_t dteff = teff * TMath::Sqrt(dldl/(lambda*lambda) + 1.0/Nm);
+    const Double_t dl    = TMath::Sqrt(dldl);
+
+    //const Double_t kappa  = Nm/N0;
+    //const Double_t Rdead  = 1.0 - kappa;
+    //const Double_t dRdead = kappa * TMath::Sqrt(dN0dN0/(N0*N0) + 1.0/Nm);
+
+    // the effective on time is Nm/lambda
+    res[0] = teff;
+    res[1] = dteff;
+
+    // plot chi2-probability of fit
+    res[2] = prob*100;
+
+    // lambda of fit
+    res[3] = lambda;
+    res[4] = dl;
+
+    // NDoF of fit
+    res[5] = NDF;
+
+    // Chi2
+    res[6] = chi2;
+
+    // Rdead (from fit) is the fraction from real time lost by the dead time
+    //fHRdead.SetBinContent(i, Rdead);
+    //fHRdead.SetBinError  (i,dRdead);
+
+    return ok;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fit a all bins of the distribution in theta. Store the result in the
+// Theta-Histograms
+//
+void MHEffectiveOnTime::FitThetaBins()
+{
+    fHThetaEffOn.Reset();
+    fHThetaProb.Reset();
+    fHThetaLambda.Reset();
+    fHThetaNDF.Reset();
+
+    const TString name = Form("CalcTheta%d", (UInt_t)gRandom->Uniform(999999999));
+
+    // nbins = number of Theta bins
+    const Int_t nbins = fH2DeltaT.GetNbinsY();
+
+    TH1D *h=0;
+    for (int i=1; i<=nbins; i++)
+    {
+        //        TH1D &h = *hist->ProjectionX("Calc-theta", i, i);
+        h = fH2DeltaT.ProjectionX(name, i, i, "E");
+
+        Double_t res[7];
+        if (!FitH(h, res))
+            continue;
+
+        // the effective on time is Nm/lambda
+        fHThetaEffOn.SetBinContent(i, res[0]);
+        fHThetaEffOn.SetBinError  (i, res[1]);
+
+        // plot chi2-probability of fit
+        fHThetaProb.SetBinContent(i, res[2]);
+
+        // plot chi2/NDF of fit
+        //fHChi2.SetBinContent(i, res[3]);
+
+        // lambda of fit
+        fHThetaLambda.SetBinContent(i, res[3]);
+        fHThetaLambda.SetBinError  (i, res[4]);
+
+        // NDoF of fit
+        fHThetaNDF.SetBinContent(i, res[5]);
+
+        // Rdead (from fit) is the fraction from real time lost by the dead time
+        //fHRdead.SetBinContent(i, Rdead);
+        //fHRdead.SetBinError  (i,dRdead);
+    }
+
+    // Histogram is reused via gROOT->FindObject()
+    // Need to be deleted only once
+    if (h)
+        delete h;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fit the single-time-bin histogram. Store the result in the
+// Time-Histograms
+//
+void MHEffectiveOnTime::FitTimeBin()
+{
+    //
+    // Fit histogram
+    //
+    Double_t res[7];
+    if (!FitH(&fH1DeltaT, res))
+        return;
+
+    // Reset Histogram
+    fH1DeltaT.Reset();
+
+    //
+    // Prepare Histogram
+    //
+
+    // Get number of bins
+    const Int_t n = fHTimeEffOn.GetNbinsX();
+
+    // Enhance binning
+    MBinning bins;
+    bins.SetEdges(fHTimeEffOn, 'x');
+    bins.AddEdge(fLastTime.GetAxisTime());
+    bins.Apply(fHTimeEffOn);
+    bins.Apply(fHTimeProb);
+    bins.Apply(fHTimeLambda);
+    //bins.Apply(fHTimeNDF);
+
+    //
+    // Fill histogram
+    //
+    fHTimeEffOn.SetBinContent(n, res[0]);
+    fHTimeEffOn.SetBinError(n, res[1]);
+
+    fHTimeProb.SetBinContent(n, res[2]);
+
+    fHTimeLambda.SetBinContent(n, res[3]);
+    fHTimeLambda.SetBinError(n, res[4]);
+
+    //fHTimeNDF.SetBinContent(n, res[5]);
+
+    //
+    // Now prepare output
+    //
+    fParam->SetVal(res[0], res[1]);
+    fParam->SetReadyToSave();
+
+    *fTime = fLastTime;
+
+    // Include the current event
+    fTime->Plus1ns();
+
+    *fLog << fLastTime << ":  Val=" << res[0] << "  Err=" << res[1] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill the histogram
+//
+Bool_t MHEffectiveOnTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MTime *time = dynamic_cast<const MTime*>(par);
+    if (!time)
+    {
+        *fLog << err << "ERROR - MHEffectiveOnTime::Fill without argument or container doesn't inherit from MTime... abort." << endl;
+        return kFALSE;
+    }
+
+    //
+    // If this is the first call we have to initialize the time-histogram
+    //
+    if (fLastTime==MTime())
+    {
+        MBinning bins;
+        bins.SetEdges(1, time->GetAxisTime()-fNumEvents/200, time->GetAxisTime());
+        bins.Apply(fHTimeEffOn);
+        bins.Apply(fHTimeProb);
+        bins.Apply(fHTimeLambda);
+        //bins.Apply(fHTimeNDF);
+
+        fParam->SetVal(0, 0);
+        fParam->SetReadyToSave();
+
+        *fTime = *time;
+
+        // Make this 1ns before the first event!
+        fTime->Minus1ns();
+    }
+
+    //
+    // Fill time difference into the histograms
+    //
+    const Double_t dt = *time-fLastTime;
+    fLastTime = *time;
+
+    fH2DeltaT.Fill(dt, fPointPos->GetZd(), w);
+    fH1DeltaT.Fill(dt, w);
+
+    //
+    // If we reached the event number limit for the time-bins fit the
+    // histogram - if it fails try again when 1.6% more events available
+    //
+    const Int_t n = (Int_t)fH1DeltaT.GetEntries();
+    if (n>=fNumEvents && n%(fNumEvents/60)==0)
+        FitTimeBin();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fit the theta projections of the 2D histogram and the 1D Delta-T
+// distribution
+//
+Bool_t MHEffectiveOnTime::Finalize()
+{
+    FitThetaBins();
+    FitTimeBin();
+    MH::RemoveFirstBin(fHTimeEffOn);
+    MH::RemoveFirstBin(fHTimeProb);
+    MH::RemoveFirstBin(fHTimeLambda);
+    //MH::RemoveFirstBin(fHTimeNDF);
+
+    fIsFinalized = kTRUE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Paint the integral and the error on top of the histogram
+//
+void MHEffectiveOnTime::PaintText(Double_t val, Double_t error) const
+{
+    TLatex text(0.45, 0.94, Form("T_{eff} = %.1fs \\pm %.1fs", val, error));
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+    text.Paint();
+}
+
+void MHEffectiveOnTime::PaintText(Double_t *res) const
+{
+    TLatex text(0.27, 0.94, Form("T_{eff}=%.1fs\\pm%.1fs  \\lambda=%.1f\\pm%.1fHz  p=%.1f%%  \\chi^{2}/%d=%.1f",
+                                 res[0], res[1], res[3], res[4], res[2], (int)res[5], res[6]/res[5]));
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+    text.Paint();
+}
+
+void MHEffectiveOnTime::PaintProb(TH1 &h) const
+{
+    Double_t sum = 0;
+    Int_t    n = 0;
+    for (int i=0; i<h.GetNbinsX(); i++)
+        if (h.GetBinContent(i+1)>0)
+        {
+            sum += h.GetBinContent(i+1);
+            n++;
+        }
+
+    if (n==0)
+        return;
+
+    TLatex text(0.47, 0.94, Form("\\bar{p} = %.1f%%", sum/n));
+    text.SetBit(TLatex::kTextNDC);
+    text.SetTextSize(0.04);
+    text.Paint();
+}
+
+void MHEffectiveOnTime::UpdateRightAxis(TH1 &h)
+{
+    const Double_t max = h.GetMaximum()*1.1;
+    if (max==0)
+        return;
+
+    h.SetNormFactor(h.Integral()*gPad->GetUymax()/max);
+
+    TGaxis *axis = (TGaxis*)gPad->FindObject("RightAxis");
+    if (!axis)
+        return;
+
+    axis->SetX1(gPad->GetUxmax());
+    axis->SetX2(gPad->GetUxmax());
+    axis->SetY1(gPad->GetUymin());
+    axis->SetY2(gPad->GetUymax());
+    axis->SetWmax(max);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prepare painting the histograms
+//
+void MHEffectiveOnTime::Paint(Option_t *opt)
+{
+    *fLog << all << "Paint: '" << opt << "'" << endl;
+
+    TH1D *h=0;
+    TPaveStats *st=0;
+
+    TString o(opt);
+    if (o==(TString)"fit")
+    {
+        TVirtualPad *pad = gPad;
+
+        for (int x=0; x<2; x++)
+            for (int y=0; y<3; y++)
+            {
+                TVirtualPad *p=gPad->GetPad(x+1)->GetPad(y+1);
+                if (!(st = (TPaveStats*)p->GetPrimitive("stats")))
+                    continue;
+
+                if (st->GetOptStat()==11)
+                    continue;
+
+                const Double_t y1 = st->GetY1NDC();
+                const Double_t y2 = st->GetY2NDC();
+                const Double_t x1 = st->GetX1NDC();
+                const Double_t x2 = st->GetX2NDC();
+
+                st->SetY1NDC((y2-y1)/3+y1);
+                st->SetX1NDC((x2-x1)/3+x1);
+                st->SetOptStat(11);
+            }
+
+        pad->GetPad(1)->cd(1);
+        if ((h = (TH1D*)gPad->FindObject("ProjDeltaT"/*fNameProjDeltaT*/)))
+        {
+            h = fH2DeltaT.ProjectionX("ProjDeltaT"/*fNameProjDeltaT*/, -1, 9999, "E");
+            if (h->GetEntries()>0)
+                gPad->SetLogy();
+        }
+
+        pad->GetPad(2)->cd(1);
+        if ((h = (TH1D*)gPad->FindObject("ProjTheta"/*fNameProjTheta*/)))
+            fH2DeltaT.ProjectionY("ProjTheta"/*fNameProjTheta*/, -1, 9999, "E");
+
+        if (!fIsFinalized)
+            FitThetaBins();
+        return;
+    }
+    if (o==(TString)"paint")
+    {
+        if ((h = (TH1D*)gPad->FindObject("ProjDeltaT"/*fNameProjDeltaT*/)))
+        {
+            Double_t res[7];
+            FitH(h, res, kTRUE);
+            PaintText(res);
+        }
+        return;
+    }
+
+    if (o==(TString)"timendf")
+    {
+        //    UpdateRightAxis(fHTimeNDF);
+        // FIXME: first bin?
+        PaintProb(fHTimeProb);
+    }
+
+    if (o==(TString)"thetandf")
+    {
+        UpdateRightAxis(fHThetaNDF);
+        // FIXME: first bin?
+        PaintProb(fHThetaProb);
+    }
+
+    h=0;
+    if (o==(TString)"theta")
+    {
+        h = &fHThetaEffOn;
+        UpdateRightAxis(fHThetaLambda);
+    }
+    if (o==(TString)"time")
+    {
+        h = &fHTimeEffOn;
+        UpdateRightAxis(fHTimeLambda);
+    }
+
+    if (!h)
+        return;
+
+    Double_t error = 0;
+    for (int i=0; i<h->GetXaxis()->GetNbins(); i++)
+        error += h->GetBinError(i);
+
+    PaintText(h->Integral(), error);
+}
+
+void MHEffectiveOnTime::DrawRightAxis(const char *title)
+{
+    TGaxis *axis = new TGaxis(gPad->GetUxmax(), gPad->GetUymin(),
+                              gPad->GetUxmax(), gPad->GetUymax(),
+                              0, 1, 510, "+L");
+    axis->SetName("RightAxis");
+    axis->SetTitle(title);
+    axis->SetTitleOffset(0.9);
+    axis->SetTextColor(kGreen);
+    axis->CenterTitle();
+    axis->SetBit(kCanDelete);
+    axis->Draw();
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHEffectiveOnTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("fit");
+
+    pad->Divide(2, 1, 0, 0);
+
+    TH1 *h;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1, 3, 0, 0);
+    pad->GetPad(1)->cd(1);
+    gPad->SetBorderMode(0);
+    h = fH2DeltaT.ProjectionX("ProjDeltaT"/*fNameProjDeltaT*/, -1, 9999, "E");
+    h->SetTitle("Distribution of \\Delta t [s]");
+    h->SetXTitle("\\Delta t [s]");
+    h->SetYTitle("Counts");
+    h->SetDirectory(NULL);
+    h->SetMarkerStyle(kFullDotMedium);
+    h->SetBit(kCanDelete);
+    h->Draw();
+    AppendPad("paint");
+
+    pad->GetPad(1)->cd(2);
+    gPad->SetBorderMode(0);
+    fHTimeProb.Draw();
+    AppendPad("timendf");
+    //fHTimeNDF.Draw("same");
+    //DrawRightAxis("NDF");
+
+    pad->GetPad(1)->cd(3);
+    gPad->SetBorderMode(0);
+    fHTimeEffOn.Draw();
+    AppendPad("time");
+    fHTimeLambda.Draw("same");
+    DrawRightAxis("\\lambda [s^{-1}]");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1, 3, 0, 0);
+
+    pad->GetPad(2)->cd(1);
+    gPad->SetBorderMode(0);
+    h = fH2DeltaT.ProjectionY("ProjTheta"/*fNameProjTheta*/, -1, 9999, "E");
+    h->SetTitle("Distribution of  \\Theta [\\circ]");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("Counts");
+    h->SetDirectory(NULL);
+    h->SetMarkerStyle(kFullDotMedium);
+    h->SetBit(kCanDelete);
+    h->GetYaxis()->SetTitleOffset(1.1);
+    h->Draw();
+
+    pad->GetPad(2)->cd(2);
+    gPad->SetBorderMode(0);
+    fHThetaProb.Draw();
+    AppendPad("thetandf");
+    fHThetaNDF.Draw("same");
+    DrawRightAxis("NDF");
+
+    pad->GetPad(2)->cd(3);
+    gPad->SetBorderMode(0);
+    fHThetaEffOn.Draw();
+    AppendPad("theta");
+    fHThetaLambda.Draw("same");
+    DrawRightAxis("\\lambda [s^{-1}]");
+}
Index: /tags/Mars-V0.9/mhflux/MHEffectiveOnTime.h
===================================================================
--- /tags/Mars-V0.9/mhflux/MHEffectiveOnTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MHEffectiveOnTime.h	(revision 9772)
@@ -0,0 +1,84 @@
+#ifndef MARS_MHEffectiveOnTime
+#define MARS_MHEffectiveOnTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+#ifndef ROOT_TF1
+#include <TF1.h>
+#endif
+
+class MTime;
+class MPointingPos;
+class MParameterDerr;
+
+class MParList;
+
+class MHEffectiveOnTime : public MH
+{
+private:
+    MPointingPos   *fPointPos; //! Container to get the zenith angle from
+    MTime           fLastTime; //! Time-Stamp of last event
+
+    MTime          *fTime;     //! Time-Stamp of "effective on-time" event
+    MParameterDerr *fParam;    //! Output container for effective on-time
+
+    TH2D fH2DeltaT;      // Counts vs Delta T and Theta
+    TH1D fH1DeltaT;      //! Counts vs Delta T (for a time interval)
+
+    TH1D fHThetaEffOn;   // Effective On time versus Theta
+    TH1D fHThetaProb;    // Chisq prob fit of Effective On time versus Theta
+    TH1D fHThetaNDF;     // NDF vs Theta
+    TH1D fHThetaLambda;  // Slope (rate) vs Theta
+
+    TH1D fHTimeEffOn;    // Effective On time versus Time
+    TH1D fHTimeProb;     // Chisq prob fit of Effective On time versus Time
+    //TH1D fHTimeNDF;      // NDF vs Time
+    TH1D fHTimeLambda;   // Slope (rate) vs Time
+
+    Bool_t fIsFinalized; // Flag telling you whether fHThetaEffOn is the final result
+
+    Int_t fNumEvents;    // Number of events to be used for a bin in time
+
+    //const TString fNameProjDeltaT; //! This should make sure, that gROOT doen't confuse the projection with something else
+    //const TString fNameProjTheta;  //! This should make sure, that gROOT doen't confuse the projection with something else
+
+    Bool_t FitH(TH1D *h, Double_t *res, Bool_t paint=kFALSE) const;
+    void FitThetaBins();
+    void FitTimeBin();
+    void PaintProb(TH1 &h) const;
+    void PaintText(Double_t val, Double_t error) const;
+    void PaintText(Double_t *res) const;
+    void DrawRightAxis(const char *title);
+    void UpdateRightAxis(TH1 &h);
+    void PrintStatistics();
+
+public:
+    MHEffectiveOnTime(const char *name=NULL, const char *title=NULL);
+
+    void SetNumEvents(Int_t i) { fNumEvents=i; }
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    const TH1D &GetHEffOnTheta() const { return fHThetaEffOn; }
+    const TH1D &GetHEffOnTime() const { return fHTimeEffOn; }
+
+    void Draw(Option_t *option="");
+    void Paint(Option_t *opt="");
+
+    ClassDef(MHEffectiveOnTime, 1) // Histogram to determin effective On-Time vs Time and Zenith Angle
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhflux/MHEnergyEst.cc
===================================================================
--- /tags/Mars-V0.9/mhflux/MHEnergyEst.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MHEnergyEst.cc	(revision 9772)
@@ -0,0 +1,454 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 4/2002 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Abelardo Moralejo 5/2003 <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz 1/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHEnergyEst
+//
+//  calculates the migration matrix E-est vs. E-true
+//  for different bins in Theta
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHEnergyEst.h"
+
+#include <TLine.h>
+#include <TCanvas.h> 
+#include <TProfile.h>
+
+#include "MString.h"
+
+#include "MMcEvt.hxx"
+
+#include "MEnergyEst.h"
+#include "MBinning.h"
+#include "MParList.h"
+#include "MParameters.h"
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHEnergyEst);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram.
+//
+MHEnergyEst::MHEnergyEst(const char *name, const char *title)
+    : fMcEvt(0), fEnergy(0), fResult(0), fMatrix(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHEnergyEst";
+    fTitle = title ? title : "3-D histogram   E-true E-est Theta";
+
+    fHEnergy.SetDirectory(NULL);
+    fHEnergy.SetName("EnergyEst");
+    fHEnergy.SetTitle("Histogram in E_{est}, E_{mc} and \\Theta");
+    fHEnergy.SetXTitle("E_{est} [GeV]");
+    fHEnergy.SetYTitle("E_{mc} [GeV]");
+    fHEnergy.SetZTitle("\\Theta [\\circ]");
+
+    fHResolution.SetDirectory(NULL);
+    fHResolution.SetName("EnergyRes");
+    fHResolution.SetTitle("Histogram in \\frac{\\Delta E}{E_{mc}} vs E_{est} and E_{mc}");
+    fHResolution.SetXTitle("E_{est} [GeV]");
+    fHResolution.SetYTitle("E_{mc} [GeV]");
+    fHResolution.SetZTitle("\\frac{E_{est} - E_{mc}}{E_{mc}}");
+
+    fHImpact.SetDirectory(NULL);
+    fHImpact.SetName("Impact");
+    fHImpact.SetTitle("\\frac{\\Delta E}{E} vs Impact parameter");
+    fHImpact.SetXTitle("Impact parameter [m]");
+    fHImpact.SetYTitle("\\frac{E_{est} - E_{mc}}{E_{mc}}");
+
+    fHEnergy.Sumw2();
+    fHImpact.Sumw2();
+    fHResolution.Sumw2();
+
+    MBinning binsi, binse, binst, binsr;
+    binse.SetEdgesLog(25, 10, 10000);
+    binst.SetEdgesCos(50, 0, 60);
+    binsi.SetEdges(10, 0, 400);
+    binsr.SetEdges(10, 0, 1);
+
+    SetBinning(&fHEnergy,     &binse, &binse, &binst);
+    SetBinning(&fHImpact,     &binsi, &binsr);
+    SetBinning(&fHResolution, &binse, &binse, &binsr);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histograms
+//
+Bool_t MHEnergyEst::SetupFill(const MParList *plist)
+{
+    if (!fMatrix)
+    {
+        fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+        if (!fMcEvt)
+        {
+            *fLog << err << "MMcEvt not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fEnergy = (MEnergyEst*)plist->FindObject("MEnergyEst");
+    if (!fEnergy)
+    {
+        *fLog << err << "MEnergyEst not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fResult = (MParameterD*)const_cast<MParList*>(plist)->FindCreateObj("MParameterD", "MinimizationValue");
+    if (!fResult)
+        return kFALSE;
+
+    MBinning binst, binse, binsi, binsr;
+    binse.SetEdges(fHEnergy, 'x');
+    binst.SetEdges(fHEnergy, 'z');
+    binsi.SetEdges(fHImpact, 'x');
+    binsr.SetEdges(fHImpact, 'y');
+
+    binst.SetEdges(*plist, "BinningTheta");
+    binse.SetEdges(*plist, "BinningEnergyEst");
+    binsi.SetEdges(*plist, "BinningImpact");
+    binsr.SetEdges(*plist, "BinningEnergyRes");
+
+    SetBinning(&fHEnergy,     &binse, &binse, &binst);
+    SetBinning(&fHImpact,     &binsi, &binsr);
+    SetBinning(&fHResolution, &binse, &binse, &binsr);
+
+    fChisq = 0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+//
+Bool_t MHEnergyEst::Fill(const MParContainer *par, const Stat_t w)
+{
+    const Double_t eest  = fEnergy->GetEnergy();
+    const Double_t etru  = fMatrix ? GetVal(0) : fMcEvt->GetEnergy();
+    const Double_t theta = fMatrix ? GetVal(2) : fMcEvt->GetTelescopeTheta()*TMath::RadToDeg();
+    const Double_t imp   = fMatrix ? GetVal(1) : fMcEvt->GetImpact()/100;
+    const Double_t res   = (eest-etru)/etru;
+
+    fHEnergy.Fill(eest, etru, theta, w);
+    fHResolution.Fill(eest, etru, res, w);
+    fHImpact.Fill(imp, res, w);
+
+    fChisq += res*res;
+
+    return kTRUE;
+}
+
+Bool_t MHEnergyEst::Finalize()
+{
+    fChisq /= GetNumExecutions();
+
+    fResult->SetVal(fChisq);
+
+    *fLog << all << "Mean Energy Resoltuion: " << Form("%.1f%%", TMath::Sqrt(fChisq)*100) << endl;
+
+    return kTRUE;
+}
+
+void MHEnergyEst::Paint(Option_t *opt)
+{
+    TVirtualPad *pad = gPad;
+
+    pad->cd(1);
+
+    TH1D *hx=0;
+    TH1D *hy=0;
+
+    if (pad->GetPad(1))
+    {
+        pad->GetPad(1)->cd(1);
+
+        if ((hx=(TH1D*)gPad->FindObject("EnergyEst_ex")))
+        {
+            TH1D *h2 = (TH1D*)fHEnergy.Project3D("dum_ex");
+            hx->Reset();
+            hx->Add(h2);
+            delete h2;
+        }
+
+        if ((hy=(TH1D*)gPad->FindObject("EnergyEst_ey")))
+        {
+            TH1D *h2 = (TH1D*)fHEnergy.Project3D("dum_ey");
+            hy->Reset();
+            hy->Add(h2);
+            delete h2;
+        }
+
+        if (hx && hy)
+        {
+            hy->SetMaximum();
+            hy->SetMaximum(TMath::Max(hx->GetMaximum(), hy->GetMaximum())*1.2);
+            if (hy->GetMaximum()>0)
+                gPad->SetLogy();
+        }
+
+        if (pad->GetPad(1)->GetPad(2))
+        {
+            pad->GetPad(1)->GetPad(2)->cd(1);
+            /*h =*/ fHImpact.ProjectionX("Impact", -1, 9999, "e");
+
+            pad->GetPad(1)->GetPad(2)->cd(2);
+            if ((hx=(TH1D*)gPad->FindObject("EnergyEst_z")))
+            {
+                TH1D *h2 = (TH1D*)fHEnergy.Project3D("dum_z");
+                hx->Reset();
+                hx->Add(h2);
+                delete h2;
+            }
+        }
+    }
+
+    if (pad->GetPad(2))
+    {
+        pad->GetPad(2)->cd(1);
+        UpdatePlot(fHEnergy, "yx", kTRUE);
+
+        TLine *l = (TLine*)gPad->FindObject("TLine");
+        if (l)
+        {
+            const Float_t min = TMath::Max(fHEnergy.GetXaxis()->GetXmin(), fHEnergy.GetYaxis()->GetXmin());
+            const Float_t max = TMath::Min(fHEnergy.GetXaxis()->GetXmax(), fHEnergy.GetYaxis()->GetXmax());
+
+            l->SetX1(min);
+            l->SetX2(max);
+            l->SetY1(min);
+            l->SetY2(max);
+        }
+
+        pad->GetPad(2)->cd(2);
+        UpdatePlot(fHResolution, "zy");
+
+        pad->GetPad(2)->cd(3);
+        UpdatePlot(fHResolution, "zx");
+    }
+}
+
+void MHEnergyEst::UpdatePlot(TH3 &h, const char *how, Bool_t logy)
+{
+    TH2D *hyx=0;
+    if (!(hyx=(TH2D*)gPad->FindObject(MString::Form("%s_%s", h.GetName(), how))))
+        return;
+
+    TH2D *h2 = (TH2D*)h.Project3D(MString::Form("dum_%s", how));
+    hyx->Reset();
+    hyx->Add(h2);
+    delete h2;
+
+    TH1D *hx = 0;
+    if ((hx=(TH1D*)gPad->FindObject("Prof")))
+    {
+        hx = hyx->ProfileX("Prof", -1, 9999, "s");
+
+        if (logy && hx->GetMaximum()>0)
+            gPad->SetLogy();
+    }
+}
+
+TH1 *MHEnergyEst::MakePlot(TH3 &h, const char *how)
+{
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+
+    gROOT->GetListOfCleanups()->Add(gPad); // WHY?
+
+    TH2D *h2 = (TH2D*)h.Project3D(how);
+    TH1D *h1 = h2->ProfileX("Prof", -1, 9999, "s");
+
+    h1->SetDirectory(NULL);
+    //h1->SetBit(kCanDelete);
+    h1->SetLineWidth(2);
+    h1->SetLineColor(kRed); // PROBLEM!
+    h1->SetStats(kFALSE);
+
+    h2->SetDirectory(NULL);
+    h2->SetBit(kCanDelete);
+    h2->SetFillColor(kBlue);
+
+    h1->Draw("E3");
+    h2->Draw("boxsame");
+    h1->Draw("Chistsame");
+
+    return h1;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHEnergyEst::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+
+    // Do the projection before painting the histograms into
+    // the individual pads
+    AppendPad("");
+
+    pad->SetBorderMode(0);
+    pad->Divide(2, 1, 0, 0);
+
+    TH1 *h;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+
+    gPad->Divide(1, 2, 0, 0);
+
+    TVirtualPad *pad2 = gPad;
+
+    pad2->cd(1);
+    gPad->SetBorderMode(0);
+
+    gPad->SetLogx();
+    h = (TH1D*)fHEnergy.Project3D("ey");
+    h->SetBit(TH1::kNoStats);
+    h->SetTitle("Energy disribution: Monte Carlo E_{mc} (black), Estimated E_{est} (green)");
+    h->SetXTitle("E [GeV]"); // E_mc
+    h->SetYTitle("Counts");
+    h->SetBit(kCanDelete);
+    h->SetDirectory(NULL);
+    h->SetMarkerStyle(kFullDotMedium);
+    h->Draw();
+
+    h = (TH1D*)fHEnergy.Project3D("ex");
+    h->SetBit(TH1::kNoTitle|TH1::kNoStats);
+    h->SetXTitle("E [GeV]"); // E_est
+    h->SetYTitle("Counts");
+    h->SetBit(kCanDelete);
+    h->SetDirectory(NULL);
+    h->SetMarkerStyle(kFullDotMedium);
+    h->SetLineColor(kGreen);
+    h->SetMarkerColor(kGreen);
+    h->Draw("same");
+
+    // FIXME: LEGEND
+
+    pad2->cd(2);
+    gPad->SetBorderMode(0);
+
+    TVirtualPad *pad3 = gPad;
+    pad3->Divide(2, 1, 0, 0);
+    pad3->cd(1);
+    gPad->SetBorderMode(0);
+    h = fHImpact.ProjectionX("Impact", -1, 9999, "e");
+    h->SetBit(TH1::kNoStats);
+    h->SetTitle("Distribution of Impact");
+    h->SetDirectory(NULL);
+    h->SetXTitle("Impact [m]");
+    h->SetBit(kCanDelete);
+    h->Draw();
+
+    pad3->cd(2);
+    gPad->SetBorderMode(0);
+    h = fHEnergy.Project3D("ez");
+    h->SetTitle("Distribution of Theta");
+    h->SetBit(TH1::kNoStats);
+    h->SetDirectory(NULL);
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetBit(kCanDelete);
+    h->Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+
+    gPad->Divide(1, 3, 0, 0);
+    pad2 = gPad;
+
+    pad2->cd(1);
+    h = MakePlot(fHEnergy, "yx");
+    h->SetXTitle("E_{mc} [GeV]");
+    h->SetYTitle("E_{est} [GeV]");
+    h->SetTitle("Estimated energy E_{est} vs Monte Carlo energy E_{mc}");
+
+    TLine line;
+    line.DrawLine(0,0,1,1);
+
+    pad2->cd(2);
+    h = MakePlot(fHResolution, "zy");
+    h->SetXTitle("E_{mc} [GeV]");
+    h->SetYTitle("\\frac{E_{est} - E_{mc}}{E_{mc}}");
+    h->SetTitle("Energy resolution \\Delta E / E vs Monte Carlo energy E_{mc}");
+    h->SetMinimum(0);
+    h->SetMaximum(1);
+
+    pad2->cd(3);
+    h = MakePlot(fHResolution, "zx");
+    h->SetXTitle("E_{est} [GeV]");
+    h->SetYTitle("\\frac{E_{est} - E_{mc}}{E_{mc}}");
+    h->SetTitle("Energy Resolution \\Delta E / E vs estimated Energy E_{est}");
+    h->SetMinimum(0);
+    h->SetMaximum(1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MHEnergyEst::GetVal(Int_t i) const
+{
+    return (*fMatrix)[fMap[i]];
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam2::Process
+// will take the values from the matrix instead of the containers.
+//
+void MHEnergyEst::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MMcEvt.fEnergy");
+    fMap[1] = fMatrix->AddColumn("MMcEvt.fImpact/100");
+    fMap[2] = fMatrix->AddColumn("MMcEvt.fTelescopeTheta*kRad2Deg");
+}
+
+void MHEnergyEst::StopMapping()
+{
+    fMatrix = NULL; 
+}
+
Index: /tags/Mars-V0.9/mhflux/MHEnergyEst.h
===================================================================
--- /tags/Mars-V0.9/mhflux/MHEnergyEst.h	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MHEnergyEst.h	(revision 9772)
@@ -0,0 +1,60 @@
+#ifndef MARS_MHEnergyEst
+#define MARS_MHEnergyEst
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+class MEnergyEst;
+class MParList;
+class MParameterD;
+class MHMatrix;
+
+class MHEnergyEst : public MH
+{
+private:
+    MMcEvt      *fMcEvt;  //!
+    MEnergyEst  *fEnergy; //!
+    MParameterD *fResult; //!
+
+    Int_t     fMap[100]; // FIXME!
+    MHMatrix    *fMatrix; //!
+
+    TH3D fHEnergy;
+    TH3D fHResolution;
+    TH2D fHImpact;
+
+    Double_t fChisq;
+
+    TH1 *MakePlot(TH3 &h, const char *how);
+    void UpdatePlot(TH3 &h, const char *how, Bool_t logy=kFALSE);
+
+    Double_t GetVal(Int_t i) const;
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+public:
+    MHEnergyEst(const char *name=NULL, const char *title=NULL);
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping();
+
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *option="");
+
+    ClassDef(MHEnergyEst, 1) //
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mhflux/MHFalseSource.cc
===================================================================
--- /tags/Mars-V0.9/mhflux/MHFalseSource.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MHFalseSource.cc	(revision 9772)
@@ -0,0 +1,1235 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHFalseSource
+//
+// Create a false source plot. For the Binning in x,y the object MBinning
+// "BinningFalseSource" is taken from the paremeter list.
+//
+// The binning in alpha is currently fixed as 18bins from 0 to 90deg.
+//
+// If MTime, MObservatory and MPointingPos is available in the paremeter
+// list each image is derotated.
+//
+// MHFalseSource fills a 3D histogram with alpha distribution for
+// each (derotated) x and y position.
+//
+// Only a radius of 1.2deg around the camera center is taken into account.
+//
+// The displayed histogram is the projection of alpha<fAlphaCut into
+// the x,y plain and the projection of alpha>90-fAlphaCut
+//
+// By using the context menu (find it in a small region between the single
+// pads) you can change the AlphaCut 'online'
+//
+// Each Z-Projection (Alpha-histogram) is scaled such, that the number
+// of entries fits the maximum number of entries in all Z-Projections.
+// This should correct for the different acceptance in the center
+// and at the vorder of the camera. This, however, produces more noise
+// at the border.
+//
+// Here is a slightly simplified version of the algorithm:
+// ------------------------------------------------------
+//    MHillas hil; // Taken as second argument in MFillH
+//
+//    MSrcPosCam src;
+//    MHillasSrc hsrc;
+//    hsrc.SetSrcPos(&src);
+//
+//    for (int ix=0; ix<nx; ix++)
+//        for (int iy=0; iy<ny; iy++)
+//        {
+//            TVector2 v(cx[ix], cy[iy]); //cx center of x-bin ix
+//            if (rho!=0)                 //cy center of y-bin iy
+//                v=v.Rotate(rho);         //image rotation angle
+//
+//            src.SetXY(v);               //source position in the camera
+//
+//            if (!hsrc.Calc(hil))        //calc source dependant hillas
+//                return;
+//
+//            //fill absolute alpha into histogram
+//            const Double_t alpha = hsrc.GetAlpha();
+//            fHist.Fill(cx[ix], cy[iy], TMath::Abs(alpha), w);
+//        }
+//    }
+//
+// Use MHFalse Source like this:
+// -----------------------------
+//    MFillH fill("MHFalseSource", "MHillas");
+// or
+//    MHFalseSource hist;
+//    hist.SetAlphaCut(12.5);  // The default value
+//    hist.SetBgmean(55);      // The default value
+//    MFillH fill(&hist, "MHillas");
+//
+// To be implemented:
+// ------------------
+//  - a switch to use alpha or |alpha|
+//  - taking the binning for alpha from the parlist (binning is
+//    currently fixed)
+//  - a possibility to change the fit-function (eg using a different TF1)
+//  - a possibility to change the fit algorithm (eg which paremeters
+//    are fixed at which time)
+//  - use a different varaible than alpha
+//  - a possiblity to change the algorithm which is used to calculate
+//    alpha (or another parameter) is missing (this could be done using
+//    a tasklist somewhere...)
+//  - a more clever (and faster) algorithm to fill the histogram, eg by
+//    calculating alpha once and fill the two coils around the mean
+//  - more drawing options...
+//  - Move Significance() to a more 'general' place and implement
+//    also different algorithms like (Li/Ma)
+//  - implement fit for best alpha distribution -- online (Paint)
+//  - currently a constant pointing position is assumed in Fill()
+//  - the center of rotation need not to be the camera center
+//  - ERRORS on each alpha bin to estimate the chi^2 correctly!
+//    (sqrt(N)/binwidth) needed for WOlfgangs proposed caluclation
+//    of alpha(Li/Ma)
+//  - use the g/h-separation filters from the tasklists ("Cut1") as filters
+//    two
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHFalseSource.h"
+
+#include <TF1.h>
+#include <TF2.h>
+#include <TH2.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TRandom.h>
+#include <TPaveText.h>
+#include <TStopwatch.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHillasSrc.h"
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MAstroCatalog.h"
+#include "MAstroSky2Local.h"
+#include "MStatusDisplay.h"
+
+#include "MMath.h"
+#include "MAlphaFitter.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHFalseSource);
+
+using namespace std;
+
+//class MHillasExt;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHFalseSource::MHFalseSource(const char *name, const char *title)
+    : fTime(0), fPointPos(0), fObservatory(0), fMm2Deg(-1), fAlphaCut(12.5),
+    fBgMean(55), fMinDist(-1), fMaxDist(-1), fMinDW(-1), fMaxDW(-1),
+    fHistOff(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHFalseSource";
+    fTitle = title ? title : "3D-plot of Alpha vs x, y";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetName("Alpha");
+    fHist.SetTitle("3D-plot of Alpha vs x, y");
+    fHist.SetXTitle("x [\\circ]");
+    fHist.SetYTitle("y [\\circ]");
+    fHist.SetZTitle("\\alpha [\\circ]");
+}
+
+void MHFalseSource::MakeSymmetric(TH1 *h)
+{
+    h->SetMinimum();
+    h->SetMaximum();
+
+    const Float_t min = TMath::Abs(h->GetMinimum());
+    const Float_t max = TMath::Abs(h->GetMaximum());
+
+    const Float_t absmax = TMath::Max(min, max)*1.002;
+
+    h->SetMaximum( absmax);
+    h->SetMinimum(-absmax);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the alpha cut (|alpha|<fAlphaCut) which is use to estimate the
+// number of excess events
+//
+void MHFalseSource::SetAlphaCut(Float_t alpha)
+{
+    if (alpha<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    fAlphaCut = TMath::Abs(alpha);
+
+    Modified();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set mean alpha around which the off sample is determined
+// (fBgMean-fAlphaCut/2<|fAlpha|<fBgMean+fAlphaCut/2) which is use
+// to estimate the number of off events
+//
+void MHFalseSource::SetBgMean(Float_t alpha)
+{
+    if (alpha<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    fBgMean = TMath::Abs(alpha);
+
+    Modified();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings (takes BinningFalseSource) and prepare filling of the
+// histogram.
+//
+// Also search for MTime, MObservatory and MPointingPos
+//
+//MHillasExt *ext=0;
+Bool_t MHFalseSource::SetupFill(const MParList *plist)
+{
+    const MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+    /*
+    ext = (MHillasExt*)plist->FindObject("MHillasExt");
+    if (!ext)
+    {
+        *fLog << err << "MHillasExt not found... aborting." << endl;
+        return kFALSE;
+    }
+    */
+    fMm2Deg = geom->GetConvMm2Deg();
+
+    if (fName!=(TString)"MHFalseSourceOff" && fHistOff==NULL)
+    {
+        MHFalseSource *hoff = (MHFalseSource*)plist->FindObject("MHFalseSourceOff", "MHFalseSource");
+        if (!hoff)
+            *fLog << inf << "No MHFalseSourceOff [MHFalseSource] found... using current data only!" << endl;
+        else
+        {
+            *fLog << inf << "MHFalseSource [MHFalseSource] found... using on-off mode!" << endl;
+            SetOffData(*hoff);
+        }
+    }
+
+    if (fHistOff)
+        MH::SetBinning(&fHist, fHistOff);
+    else
+    {
+        MBinning binsa(18, 0, 90);
+        binsa.SetEdges(*plist, "BinningAlpha");
+
+        const MBinning *bins = (MBinning*)plist->FindObject("BinningFalseSource");
+        if (!bins || bins->IsDefault())
+        {
+            const Float_t r = (geom ? geom->GetMaxRadius()/3 : 200)*fMm2Deg;
+
+            MBinning b;
+            b.SetEdges(20, -r, r);
+            SetBinning(&fHist, &b, &b, &binsa);
+        }
+        else
+            SetBinning(&fHist, bins, bins, &binsa);
+    }
+
+    fPointPos = (MPointingPos*)plist->FindObject(AddSerialNumber("MPointingPos"));
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... no derotation." << endl;
+
+    fTime = (MTime*)plist->FindObject(AddSerialNumber("MTime"));
+    if (!fTime)
+        *fLog << warn << "MTime not found... no derotation." << endl;
+
+    fSrcPos = (MSrcPosCam*)plist->FindObject(AddSerialNumber("MSrcPosCam"));
+    if (!fSrcPos)
+        *fLog << warn << "MSrcPosCam not found... no translation." << endl;
+
+    fObservatory = (MObservatory*)plist->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+        *fLog << warn << "MObservatory not found... no derotation." << endl;
+
+    // FIXME: Because the pointing position could change we must check
+    // for the current pointing position and add a offset in the
+    // Fill function!
+    fRa  = fPointPos ? fPointPos->GetRa()  :  0;
+    fDec = fPointPos ? fPointPos->GetDec() : 90;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Bool_t MHFalseSource::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MHillas *hil = dynamic_cast<const MHillas*>(par);
+    if (!hil)
+    {
+        *fLog << err << "MHFalseSource::Fill: No container specified!" << endl;
+        return kFALSE;
+    }
+
+    // Get max radius...
+    const Double_t maxr = 0.98*TMath::Abs(fHist.GetBinCenter(1));
+
+    // Get camera rotation angle
+    Double_t rho = 0;
+    if (fTime && fObservatory && fPointPos)
+        rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+    //if (fPointPos)
+    //    rho = fPointPos->RotationAngle(*fObservatory);
+
+    // Create necessary containers for calculation
+    MSrcPosCam src;
+    MHillasSrc hsrc;
+    hsrc.SetSrcPos(&src);
+
+    // Get number of bins and bin-centers
+    const Int_t nx = fHist.GetNbinsX();
+    const Int_t ny = fHist.GetNbinsY();
+    Axis_t cx[nx];
+    Axis_t cy[ny];
+    fHist.GetXaxis()->GetCenter(cx);
+    fHist.GetYaxis()->GetCenter(cy);
+
+    for (int ix=0; ix<nx; ix++)
+    {
+        for (int iy=0; iy<ny; iy++)
+        {
+            // check distance... to get a circle plot
+            if (TMath::Hypot(cx[ix], cy[iy])>maxr)
+                continue;
+
+            // rotate center of bin
+            // precalculation of sin/cos doesn't accelerate
+            TVector2 v(cx[ix], cy[iy]);
+            if (rho!=0)
+                v=v.Rotate(rho);
+
+            // convert degrees to millimeters
+            v *= 1./fMm2Deg;
+
+            if (fSrcPos)
+                v += fSrcPos->GetXY();
+
+            src.SetXY(v);
+
+            // Source dependant hillas parameters
+            if (hsrc.Calc(*hil/*, ext*/)>0)
+            {
+                *fLog << warn << "Calculation of MHillasSrc failed for x=" << cx[ix] << " y=" << cy[iy] << endl;
+                return kFALSE;
+            }
+
+            // FIXME: This should be replaced by an external MFilter
+            //        and/or MTaskList
+            // Source dependant distance cut
+            if (fMinDist>0 && hsrc.GetDist()*fMm2Deg<fMinDist)
+                continue;
+            if (fMaxDist>0 && hsrc.GetDist()*fMm2Deg>fMaxDist)
+                continue;
+
+            if (fMaxDW>0 && hsrc.GetDist()>fMaxDW*hil->GetWidth())
+                continue;
+            if (fMinDW<0 && hsrc.GetDist()<fMinDW*hil->GetWidth())
+                continue;
+
+            // Fill histogram
+            const Double_t alpha = hsrc.GetAlpha();
+            fHist.Fill(cx[ix], cy[iy], TMath::Abs(alpha), w);
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Create projection for off data, taking sum of bin contents of
+// range (fBgMean-fAlphaCut/2, fBgMean+fAlphaCut) Making sure to take
+// the same number of bins than for on-data
+//
+void MHFalseSource::ProjectOff(const TH3D &src, TH2D *h2, TH2D *all)
+{
+    TAxis &axe = *src.GetZaxis();
+
+    // Find range to cut (left edge and width)
+    const Int_t f = axe.FindBin(fBgMean-fAlphaCut/2);
+    const Int_t l = axe.FindBin(fAlphaCut)+f-1;
+
+    axe.SetRange(f, l);
+    const Float_t cut1 = axe.GetBinLowEdge(f);
+    const Float_t cut2 = axe.GetBinUpEdge(l);
+    h2->SetTitle(Form("Distribution of %.1f\\circ<|\\alpha|<%.1f\\circ in x,y", cut1, cut2));
+
+    // Get projection for range
+    TH2D *p = (TH2D*)src.Project3D("yx_off");
+
+    // Reset range
+    axe.SetRange(0,9999);
+
+    // Move contents from projection to h2
+    h2->Reset();
+    h2->Add(p, all->GetMaximum());
+    h2->Divide(all);
+
+    // Delete p
+    delete p;
+
+    // Set Minimum as minimum value Greater Than 0
+    h2->SetMinimum(GetMinimumGT(*h2));
+}
+
+// --------------------------------------------------------------------------
+//
+// Create projection for on data, taking sum of bin contents of
+// range (0, fAlphaCut)
+//
+void MHFalseSource::ProjectOn(const TH3D &src, TH2D *h3, TH2D *all)
+{
+    TAxis &axe = *src.GetZaxis();
+
+    // Find range to cut
+    axe.SetRangeUser(0, fAlphaCut);
+    const Float_t cut = axe.GetBinUpEdge(axe.GetLast());
+    h3->SetTitle(Form("Distribution of |\\alpha|<%.1f\\circ in x,y", cut));
+
+    // Get projection for range
+    TH2D *p = (TH2D*)src.Project3D("yx_on");
+
+    // Reset range
+    axe.SetRange(0,9999);
+
+    // Move contents from projection to h3
+    h3->Reset();
+    h3->Add(p, all->GetMaximum());
+    h3->Divide(all);
+
+    // Delete p
+    delete p;
+
+    // Set Minimum as minimum value Greater Than 0
+    h3->SetMinimum(GetMinimumGT(*h3));
+}
+
+// --------------------------------------------------------------------------
+//
+// Create projection for all data, taking sum of bin contents of
+// range (0, 90) - corresponding to the number of entries in this slice.
+//
+void MHFalseSource::ProjectAll(TH2D *h3)
+{
+    h3->SetTitle("Number of entries");
+
+    // Get projection for range
+    TH2D *p = (TH2D*)fHist.Project3D(Form("yx_%d", gRandom->Uniform(999999)));
+    p->SetDirectory(0);
+
+    // Move contents from projection to h3
+    h3->Reset();
+    h3->Add(p);
+    delete p;
+
+    // Set Minimum as minimum value Greater Than 0
+    h3->SetMinimum(GetMinimumGT(*h3));
+}
+
+void MHFalseSource::ProjectOnOff(TH2D *h2, TH2D *h0)
+{
+    ProjectOn(*fHistOff, h2, h0);
+
+    TH2D h;
+    MH::SetBinning(&h, h2);
+
+    // Divide by number of entries in off region (of off-data)
+    ProjectOff(*fHistOff, &h, h0);
+    h2->Divide(&h);
+
+    // Multiply by number of entries in off region (of on-data)
+    ProjectOff(fHist, &h, h0);
+    h2->Multiply(&h);
+
+    // Recalculate Minimum
+    h2->SetMinimum(GetMinimumGT(*h2));
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the projections and paint them
+//
+void MHFalseSource::Paint(Option_t *opt)
+{
+    // Set pretty color palette
+    gStyle->SetPalette(1, 0);
+
+    TVirtualPad *padsave = gPad;
+
+    TH1D* h1;
+    TH2D* h0;
+    TH2D* h2;
+    TH2D* h3;
+    TH2D* h4;
+    TH2D* h5;
+
+    /*
+     fHistProjAll  = Form("All_%p",  this);
+     fHistProjOn   = Form("On_%p",   this);
+     fHistProjOff  = Form("Off_%p",  this);
+     fHistProjDiff = Form("Diff_%p", this);
+     fHistProjAll  = Form("All_%p",  this);
+     */
+
+    // Update projection of all-events
+    padsave->GetPad(2)->cd(3);
+    if ((h0 = (TH2D*)gPad->FindObject("Alpha_yx_all")))
+        ProjectAll(h0);
+
+    // Update projection of on-events
+    padsave->GetPad(1)->cd(1);
+    if ((h3 = (TH2D*)gPad->FindObject("Alpha_yx_on")))
+        ProjectOn(fHist, h3, h0);
+
+    // Update projection of off-events
+    padsave->GetPad(1)->cd(3);
+    if ((h2 = (TH2D*)gPad->FindObject("Alpha_yx_off")))
+    {
+        if (!fHistOff)
+            ProjectOff(fHist, h2, h0);
+        else
+            ProjectOnOff(h2, h0);
+    }
+
+    padsave->GetPad(2)->cd(2);
+    if ((h5 = (TH2D*)gPad->FindObject("Alpha_yx_diff")))
+    {
+        h5->Add(h2, h3, -1);
+        MakeSymmetric(h5);
+    }
+
+    // Update projection of significance
+    padsave->GetPad(1)->cd(2);
+    if (h2 && h3 && (h4 = (TH2D*)gPad->FindObject("Alpha_yx_sig")))
+    {
+        const Int_t nx = h4->GetXaxis()->GetNbins();
+        const Int_t ny = h4->GetYaxis()->GetNbins();
+        //const Int_t nr = nx*nx + ny*ny;
+
+        Int_t maxx=nx/2;
+        Int_t maxy=ny/2;
+
+        Int_t max = h4->GetBin(nx, ny);
+
+        for (int ix=1; ix<=nx; ix++)
+            for (int iy=1; iy<=ny; iy++)
+            {
+                const Int_t n = h4->GetBin(ix, iy);
+
+                const Double_t s = h3->GetBinContent(n);
+                const Double_t b = h2->GetBinContent(n);
+
+                const Double_t sig = MMath::SignificanceLiMaSigned(s, b);
+
+                h4->SetBinContent(n, sig);
+
+                if (sig>h4->GetBinContent(max) && sig>0/* && (ix-nx/2)*(ix-nx/2)+(iy-ny/2)*(iy-ny/2)<nr*nr/9*/)
+                {
+                    max = n;
+                    maxx=ix;
+                    maxy=iy;
+                }
+            }
+
+        MakeSymmetric(h4);
+
+        // Update projection of 'the best alpha-plot'
+        padsave->GetPad(2)->cd(1);
+        if ((h1 = (TH1D*)gPad->FindObject("Alpha_z")) && max>0)
+        {
+            const Double_t x = h4->GetXaxis()->GetBinCenter(maxx);
+            const Double_t y = h4->GetYaxis()->GetBinCenter(maxy);
+            const Double_t s = h4->GetBinContent(max);
+
+            // This is because a 3D histogram x and y are vice versa
+            // Than for their projections
+            TH1 *h = fHist.ProjectionZ("Alpha_z", maxx, maxx, maxy, maxy);
+            h->SetTitle(Form("Distribution of \\alpha for x=%.2f y=%.2f (S_{max}=%.1f\\sigma)", x, y, s));
+
+            TH1D *h0=0;
+            if ((h0 = (TH1D*)gPad->FindObject("AlphaOff_z")))
+            {
+                fHistOff->ProjectionZ("AlphaOff_z", maxx, maxx, maxy, maxy);
+
+                const Int_t f = h0->GetXaxis()->FindFixBin(fBgMean-1.5*fAlphaCut);
+                const Int_t l = h0->GetXaxis()->FindFixBin(fAlphaCut*3)+f-1;
+                h0->Scale(h1->Integral(f, l)/h0->Integral(f, l));
+                //h0->Scale(h1->GetEntries()/h0->GetEntries());
+
+            }
+        }
+    }
+
+    gPad = padsave;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the MAstroCatalog corresponding to fRa, fDec. The limiting magnitude
+// is set to 9, while the fov is equal to the current fov of the false
+// source plot.
+//
+TObject *MHFalseSource::GetCatalog()
+{
+    const Double_t maxr = 0.98*TMath::Abs(fHist.GetBinCenter(1));
+
+    // Create catalog...
+    MAstroCatalog *stars = new MAstroCatalog;
+    stars->SetLimMag(9);
+    stars->SetGuiActive(kFALSE);
+    stars->SetRadiusFOV(maxr);
+    stars->SetRaDec(fRa*TMath::DegToRad()*15, fDec*TMath::DegToRad());
+    stars->ReadBSC("bsc5.dat");
+
+    stars->SetBit(kCanDelete);
+    return stars;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHFalseSource::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(1, 2, 0, 0.03);
+
+//    TObject *catalog = GetCatalog();
+
+    // Initialize upper part
+    pad->cd(1);
+    // Make sure that the catalog is deleted only once
+    // Normally this is not done by root, because it is not necessary...
+    // but in this case it is necessary, because the catalog is
+    // deleted by the first pad and the second one tries to do the same!
+//    gROOT->GetListOfCleanups()->Add(gPad);
+    gPad->SetBorderMode(0);
+    gPad->Divide(3, 1);
+
+    // PAD #1
+    pad->GetPad(1)->cd(1);
+    gPad->SetBorderMode(0);
+    fHist.GetZaxis()->SetRangeUser(0,fAlphaCut);
+    TH1 *h3 = fHist.Project3D("yx_on");
+    fHist.GetZaxis()->SetRange(0,9999);
+    h3->SetDirectory(NULL);
+    h3->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h3->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h3->Draw("colz");
+    h3->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+
+    // PAD #2
+    pad->GetPad(1)->cd(2);
+    gPad->SetBorderMode(0);
+    fHist.GetZaxis()->SetRange(0,0);
+    TH1 *h4 = fHist.Project3D("yx_sig"); // Do this to get the correct binning....
+    fHist.GetZaxis()->SetRange(0,9999);
+    h4->SetTitle("Significance");
+    h4->SetDirectory(NULL);
+    h4->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h4->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h4->Draw("colz");
+    h4->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+
+    // PAD #3
+    pad->GetPad(1)->cd(3);
+    gPad->SetBorderMode(0);
+    TH1 *h2 = 0;
+    if (fHistOff)
+    {
+        fHistOff->GetZaxis()->SetRangeUser(0,fAlphaCut);
+        h2 = fHistOff->Project3D("yx_off");
+        fHistOff->GetZaxis()->SetRange(0,9999);
+    }
+    else
+    {
+        fHist.GetZaxis()->SetRangeUser(fBgMean-fAlphaCut/2, fBgMean+fAlphaCut/2);
+        h2 = fHist.Project3D("yx_off");
+        fHist.GetZaxis()->SetRange(0,9999);
+    }
+    h2->SetDirectory(NULL);
+    h2->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h2->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h2->Draw("colz");
+    h2->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+
+    // Initialize lower part
+    pad->cd(2);
+    // Make sure that the catalog is deleted only once
+//    gROOT->GetListOfCleanups()->Add(gPad);
+    gPad->SetBorderMode(0);
+    gPad->Divide(3, 1);
+
+    // PAD #4
+    pad->GetPad(2)->cd(1);
+    gPad->SetBorderMode(0);
+    TH1 *h1 = fHist.ProjectionZ("Alpha_z");
+    h1->SetDirectory(NULL);
+    h1->SetTitle("Distribution of \\alpha");
+    h1->SetXTitle(fHist.GetZaxis()->GetTitle());
+    h1->SetYTitle("Counts");
+    h1->Draw();
+    h1->SetBit(kCanDelete);
+    if (fHistOff)
+    {
+        h1->SetLineColor(kGreen);
+
+        h1 = fHistOff->ProjectionZ("AlphaOff_z");
+        h1->SetDirectory(NULL);
+        h1->SetTitle("Distribution of \\alpha");
+        h1->SetXTitle(fHistOff->GetZaxis()->GetTitle());
+        h1->SetYTitle("Counts");
+        h1->Draw("same");
+        h1->SetBit(kCanDelete);
+        h1->SetLineColor(kRed);
+    }
+
+    // PAD #5
+    pad->GetPad(2)->cd(2);
+    gPad->SetBorderMode(0);
+    TH1 *h5 = (TH1*)h3->Clone("Alpha_yx_diff");
+    h5->Add(h2, -1);
+    h5->SetTitle("Difference of on- and off-distribution");
+    h5->SetDirectory(NULL);
+    h5->Draw("colz");
+    h5->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+
+    // PAD #6
+    pad->GetPad(2)->cd(3);
+    gPad->SetBorderMode(0);
+    TH1 *h0 = fHist.Project3D("yx_all");
+    h0->SetDirectory(NULL);
+    h0->SetXTitle(fHist.GetXaxis()->GetTitle());
+    h0->SetYTitle(fHist.GetYaxis()->GetTitle());
+    h0->Draw("colz");
+    h0->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+}
+
+// --------------------------------------------------------------------------
+//
+// Everything which is in the main pad belongs to this class!
+//
+Int_t MHFalseSource::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set all sub-pads to Modified()
+//
+void MHFalseSource::Modified()
+{
+    if (!gPad)
+        return;
+
+    TVirtualPad *padsave = gPad;
+    padsave->Modified();
+    padsave->GetPad(1)->cd(1);
+    gPad->Modified();
+    padsave->GetPad(1)->cd(3);
+    gPad->Modified();
+    padsave->GetPad(2)->cd(1);
+    gPad->Modified();
+    padsave->GetPad(2)->cd(2);
+    gPad->Modified();
+    padsave->GetPad(2)->cd(3);
+    gPad->Modified();
+    gPad->cd();
+}
+
+// --------------------------------------------------------------------------
+//
+// The following resources are available:
+//
+//    MHFalseSource.DistMin: 0.5
+//    MHFalseSource.DistMax: 1.4
+//    MHFalseSource.DWMin:   0.1
+//    MHFalseSource.DWMax:   0.3
+//
+Int_t MHFalseSource::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "DistMin", print))
+    {
+        rc = kTRUE;
+        SetMinDist(GetEnvValue(env, prefix, "DistMin", fMinDist));
+    }
+    if (IsEnvDefined(env, prefix, "DistMax", print))
+    {
+        rc = kTRUE;
+        SetMaxDist(GetEnvValue(env, prefix, "DistMax", fMaxDist));
+    }
+
+    if (IsEnvDefined(env, prefix, "DWMin", print))
+    {
+        rc = kTRUE;
+        SetMinDW(GetEnvValue(env, prefix, "DWMin", fMinDist));
+    }
+    if (IsEnvDefined(env, prefix, "DWMax", print))
+    {
+        rc = kTRUE;
+        SetMaxDW(GetEnvValue(env, prefix, "DWMax", fMaxDist));
+    }
+
+    return rc;
+}
+
+Double_t FcnGauss2d(Double_t *x, Double_t *par)
+{
+    TVector2 v = TVector2(x[0], x[1]).Rotate(par[5]*TMath::DegToRad());
+
+    const Double_t g0 = TMath::Gaus(v.X(), par[1], par[2]);
+    const Double_t g1 = TMath::Gaus(v.Y(), par[3], par[4]);
+
+    //Gaus(Double_t x, Double_t mean=0, Double_t sigma=1, Bool_t norm=kFALSE);
+    return par[0]*g0*g1;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a preliminary implementation of a alpha-fit procedure for
+// all possible source positions. It will be moved into its own
+// more powerfull class soon.
+//
+// The fit function is "gaus(0)+pol2(3)" which is equivalent to:
+//   [0]*exp(-0.5*((x-[1])/[2])^2) + [3] + [4]*x + [5]*x^2
+// or
+//   A*exp(-0.5*((x-mu)/sigma)^2) + a + b*x + c*x^2
+//
+// Parameter [1] is fixed to 0 while the alpha peak should be
+// symmetric around alpha=0.
+//
+// Parameter [4] is fixed to 0 because the first derivative at
+// alpha=0 should be 0, too.
+//
+// In a first step the background is fitted between bgmin and bgmax,
+// while the parameters [0]=0 and [2]=1 are fixed.
+//
+// In a second step the signal region (alpha<sigmax) is fittet using
+// the whole function with parameters [1], [3], [4] and [5] fixed.
+//
+// The number of excess and background events are calculated as
+//   s = int(0, sigint, gaus(0)+pol2(3))
+//   b = int(0, sigint,         pol2(3))
+//
+// The Significance is calculated using the Significance() member
+// function.
+//
+void MHFalseSource::FitSignificance(Float_t sigint, Float_t sigmax, Float_t bgmin, Float_t bgmax, Byte_t polynom)
+{
+//    TObject *catalog = GetCatalog();
+
+    TH1D h0a("A",          "", 50,   0, 4000);
+    TH1D h4a("chisq1",     "", 50,   0,   35);
+    //TH1D h5a("prob1",      "", 50,   0,  1.1);
+    TH1D h6("signifcance", "", 50, -20,   20);
+
+    TH1D h1("mu",    "Parameter \\mu",    50,   -1,    1);
+    TH1D h2("sigma", "Parameter \\sigma", 50,    0,   90);
+    TH1D h3("b",     "Parameter b",       50, -0.1,  0.1);
+
+    TH1D h0b("a",         "Parameter a (red), A (blue)", 50, 0, 4000);
+    TH1D h4b("\\chi^{2}", "\\chi^{2} (red, green) / significance (black)", 50, 0, 35);
+    //TH1D h5b("prob",      "Fit probability: Bg(red), F(blue)", 50, 0, 1.1);
+
+    h0a.SetLineColor(kBlue);
+    h4a.SetLineColor(kBlue);
+    //h5a.SetLineColor(kBlue);
+    h0b.SetLineColor(kRed);
+    h4b.SetLineColor(kRed);
+    //h5b.SetLineColor(kRed);
+
+    TH1 *hist  = fHist.Project3D("yx_fit");
+    hist->SetDirectory(0);
+    TH1 *hists = fHist.Project3D("yx_fit");
+    hists->SetDirectory(0);
+    TH1 *histb = fHist.Project3D("yx_fit");
+    histb->SetDirectory(0);
+    hist->Reset();
+    hists->Reset();
+    histb->Reset();
+    hist->SetNameTitle("Significance",
+                       Form("Fit Region: Signal<%.1f\\circ, %.1f\\circ<Bg<%.1f\\circ",
+                            sigmax, bgmin, bgmax));
+    hists->SetName("Excess");
+    histb->SetName("Background");
+    hist->SetXTitle(fHist.GetXaxis()->GetTitle());
+    hists->SetXTitle(fHist.GetXaxis()->GetTitle());
+    histb->SetXTitle(fHist.GetXaxis()->GetTitle());
+    hist->SetYTitle(fHist.GetYaxis()->GetTitle());
+    hists->SetYTitle(fHist.GetYaxis()->GetTitle());
+    histb->SetYTitle(fHist.GetYaxis()->GetTitle());
+
+    const Double_t w = fHist.GetZaxis()->GetBinWidth(1);
+
+    TArrayD maxpar;
+
+    /*  func.SetParName(0, "A");
+     *  func.SetParName(1, "mu");
+     *  func.SetParName(2, "sigma");
+    */
+
+    const Int_t nx = hist->GetXaxis()->GetNbins();
+    const Int_t ny = hist->GetYaxis()->GetNbins();
+    //const Int_t nr = nx*nx+ny*ny;
+
+    Double_t maxalpha0=0;
+    Double_t maxs=3;
+
+    Int_t maxx=0;
+    Int_t maxy=0;
+
+    TStopwatch clk;
+    clk.Start();
+
+    *fLog << inf;
+    *fLog << "Signal fit:     alpha < " << sigmax << endl;
+    *fLog << "Integration:    alpha < " << sigint << endl;
+    *fLog << "Background fit: " << bgmin << " < alpha < " << bgmax << endl;
+    *fLog << "Polynom order:  " << (int)polynom << endl;
+    *fLog << "Fitting False Source Plot..." << flush;
+
+    TH1 *h0 = fHist.Project3D("yx_entries");
+    Float_t entries = h0->GetMaximum();
+    delete h0;
+
+    MAlphaFitter fit;
+    fit.SetSignalIntegralMax(sigint);
+    fit.SetSignalFitMax(sigmax);
+    fit.SetBackgroundFitMin(bgmin);
+    fit.SetBackgroundFitMax(bgmax);
+    fit.SetPolynomOrder(polynom);
+
+    TH1D *h=0, *hoff=0;
+    Double_t scale = 1;
+    for (int ix=1; ix<=nx; ix++)
+        for (int iy=1; iy<=ny; iy++)
+        {
+            // This is because a 3D histogram x and y are vice versa
+            // Than for their projections
+            h = fHist.ProjectionZ("AlphaFit", ix, ix, iy, iy);
+
+            if (h->GetEntries()==0)
+                continue;
+
+            // This is a quick hack to correct for the lower acceptance at
+            // the edge of the camera
+            h->Scale(entries/h->GetEntries());
+
+            if (fHistOff)
+            {
+                hoff = fHistOff->ProjectionZ("AlphaFitOff", ix, ix, iy, iy);
+                // This is a quick hack to correct for the lower acceptance at
+                // the edge of the camera
+                hoff->Scale(entries/h->GetEntries());
+                scale = fit.Scale(*hoff, *h);
+            }
+
+            if (!fit.Fit(*h, hoff, scale))
+                continue;
+
+            const Double_t alpha0 = h->GetBinContent(1);
+            if (alpha0>maxalpha0)
+                maxalpha0=alpha0;
+ 
+            // Fill results into some histograms
+            h0a.Fill(fit.GetGausA());        // gaus-A
+            h0b.Fill(fit.GetCoefficient(3)); // 3
+            h1.Fill(fit.GetGausMu());        // mu
+            h2.Fill(fit.GetGausSigma());     // sigma-gaus
+            if (polynom>1 && !fHistOff)
+                h3.Fill(fit.GetCoefficient(5));
+            h4b.Fill(fit.GetChiSqSignal());
+
+            const Double_t sig = fit.GetSignificance();
+            const Double_t b   = fit.GetEventsBackground();
+            const Double_t s   = fit.GetEventsSignal();
+
+            const Int_t n = hist->GetBin(ix, iy);
+            hists->SetBinContent(n, s-b);
+            histb->SetBinContent(n, b);
+
+            hist->SetBinContent(n, sig);
+            if (sig!=0)
+                h6.Fill(sig);
+
+            if (sig>maxs)
+            {
+                maxs = sig;
+                maxx = ix;
+                maxy = iy;
+                maxpar = fit.GetCoefficients();
+            }
+        }
+
+    *fLog << "Done." << endl;
+
+    h0a.GetXaxis()->SetRangeUser(0, maxalpha0*1.5);
+    h0b.GetXaxis()->SetRangeUser(0, maxalpha0*1.5);
+
+    hists->SetTitle(Form("Excess events for \\alpha<%.0f\\circ (N_{max}=%d)", sigint, (int)hists->GetMaximum()));
+    histb->SetTitle(Form("Background events for \\alpha<%.0f\\circ", sigint));
+
+    //hists->SetMinimum(GetMinimumGT(*hists));
+    histb->SetMinimum(GetMinimumGT(*histb));
+
+    MakeSymmetric(hists);
+    MakeSymmetric(hist);
+
+    clk.Stop();
+    clk.Print("m");
+
+    TCanvas *c=new TCanvas;
+
+    gStyle->SetPalette(1, 0);
+
+    c->Divide(3,2, 0, 0);
+    c->cd(1);
+    gPad->SetBorderMode(0);
+    hists->Draw("colz");
+    hists->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    hist->Draw("colz");
+    hist->SetBit(kCanDelete);
+
+
+    const Double_t maxr = 0.9*TMath::Abs(fHist.GetBinCenter(1));
+    TF2 f2d("Gaus-2D", FcnGauss2d, -maxr, maxr, -maxr, maxr, 6);
+    f2d.SetLineWidth(1);
+    f2d.SetParName(0, "Max   sigma");
+    f2d.SetParName(1, "Mean_1  deg");
+    f2d.SetParName(2, "Sigma_1 deg");
+    f2d.SetParName(3, "Mean_2  deg");
+    f2d.SetParName(4, "Sigma_2 deg");
+    f2d.SetParName(5, "Phi     deg");
+    f2d.SetParLimits(1, -maxr/2, maxr/2); // mu_1
+    f2d.SetParLimits(3, -maxr/2, maxr/2); // mu_2
+    f2d.SetParLimits(2, 0, maxr);         // sigma_1
+    f2d.SetParLimits(4, 0, maxr);         // sigma_2
+    f2d.SetParLimits(5, 0, 45);           // phi
+    f2d.SetParameter(0, maxs);            // A
+    f2d.SetParameter(1, hist->GetXaxis()->GetBinCenter(maxx)); // mu_1
+    f2d.SetParameter(2, 0.1);             // sigma_1
+    f2d.SetParameter(3, hist->GetYaxis()->GetBinCenter(maxy)); // mu_2
+    f2d.SetParameter(4, 0.1);             // sigma_2
+    f2d.FixParameter(5, 0);               // phi
+    hist->Fit(&f2d, "NI0R");
+    f2d.DrawCopy("cont2same");
+
+
+//    catalog->Draw("mirror same *");
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    histb->Draw("colz");
+    histb->SetBit(kCanDelete);
+//    catalog->Draw("mirror same *");
+    c->cd(4);
+    gPad->Divide(1,3, 0, 0);
+    TVirtualPad *p=gPad;
+    p->SetBorderMode(0);
+    p->cd(1);
+    gPad->SetBorderMode(0);
+    h0b.DrawCopy();
+    h0a.DrawCopy("same");
+    p->cd(2);
+    gPad->SetBorderMode(0);
+    h3.DrawCopy();
+    p->cd(3);
+    gPad->SetBorderMode(0);
+    h2.DrawCopy();
+    c->cd(6);
+    gPad->Divide(1,2, 0, 0);
+    TVirtualPad *q=gPad;
+    q->SetBorderMode(0);
+    q->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetBorderMode(0);
+    h4b.DrawCopy();
+    h4a.DrawCopy("same");
+    h6.DrawCopy("same");
+    q->cd(2);
+    gPad->SetBorderMode(0);
+    //h5b.DrawCopy();
+    //h5a.DrawCopy("same");
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    if (maxx>0 && maxy>0)
+    {
+        const char *title = Form(" \\alpha for x=%.2f y=%.2f (S_{max}=%.1f\\sigma) ",
+                                 hist->GetXaxis()->GetBinCenter(maxx),
+                                 hist->GetYaxis()->GetBinCenter(maxy), maxs);
+
+        h = fHist.ProjectionZ("AlphaFit", maxx, maxx, maxy, maxy);
+        h->Scale(entries/h->GetEntries());
+
+        h->SetDirectory(NULL);
+        h->SetNameTitle("Result \\alpha", title);
+        h->SetBit(kCanDelete);
+        h->SetXTitle("\\alpha [\\circ]");
+        h->SetYTitle("Counts");
+        h->Draw();
+
+        if (fHistOff)
+        {
+            h->SetLineColor(kGreen);
+
+            TH1D *hof=fHistOff->ProjectionZ("AlphaFitOff", maxx, maxx, maxy, maxy);
+            hof->Scale(entries/hof->GetEntries());
+
+            fit.Scale(*(TH1D*)hof, *(TH1D*)h);
+
+            hof->SetLineColor(kRed);
+            hof->SetDirectory(NULL);
+            hof->SetNameTitle("Result \\alpha", title);
+            hof->SetBit(kCanDelete);
+            hof->SetXTitle("\\alpha [\\circ]");
+            hof->SetYTitle("Counts");
+            hof->Draw("same");
+
+            TH1D *diff = (TH1D*)h->Clone("AlphaFitOnOff");
+            diff->Add(hof, -1);
+            diff->SetLineColor(kBlue);
+            diff->SetNameTitle("Result On-Off \\alpha", title);
+            diff->SetBit(kCanDelete);
+            diff->SetXTitle("\\alpha [\\circ]");
+            diff->SetYTitle("Counts");
+            diff->Draw("same");
+
+            h->SetMinimum(diff->GetMinimum()<0 ? diff->GetMinimum()*1.2 : 0);
+
+            TLine l;
+            l.DrawLine(0, 0, 90, 0);
+        }
+
+        TF1 f1("f1", Form("gaus(0) + pol%d(3)", fHistOff ? 0 : polynom), 0, 90);
+        TF1 f2("f2", Form("gaus(0) + pol%d(3)", fHistOff ? 0 : polynom), 0, 90);
+        f1.SetParameters(maxpar.GetArray());
+        f2.SetParameters(maxpar.GetArray());
+        f2.FixParameter(0, 0);
+        f2.FixParameter(1, 0);
+        f2.FixParameter(2, 1);
+        f1.SetLineColor(kGreen);
+        f2.SetLineColor(kRed);
+
+        f2.DrawCopy("same");
+        f1.DrawCopy("same");
+
+        TPaveText *leg = new TPaveText(0.35, 0.10, 0.90, 0.35, "brNDC");
+        leg->SetBorderSize(1);
+        leg->SetTextSize(0.04);
+        leg->AddText(0.5, 0.82, Form("A * exp(-(\\frac{x-\\mu}{\\sigma})^{2}/2) + pol%d", polynom))->SetTextAlign(22);
+        //leg->AddText(0.5, 0.82, "A * exp(-(\\frac{x-\\mu}{\\sigma})^{2}/2) + b*x^{2} + a")->SetTextAlign(22);
+        leg->AddLine(0, 0.65, 0, 0.65);
+        leg->AddText(0.06, 0.54, Form("A=%.2f", maxpar[0]))->SetTextAlign(11);
+        leg->AddText(0.06, 0.34, Form("\\sigma=%.2f", maxpar[2]))->SetTextAlign(11);
+        leg->AddText(0.06, 0.14, Form("\\mu=%.2f (fix)", maxpar[1]))->SetTextAlign(11);
+        leg->AddText(0.60, 0.54, Form("a=%.2f", maxpar[3]))->SetTextAlign(11);
+        leg->AddText(0.60, 0.34, Form("b=%.2f (fix)", maxpar[4]))->SetTextAlign(11);
+        if (polynom>1)
+            leg->AddText(0.60, 0.14, Form("c=%.2f", !fHistOff?maxpar[5]:0))->SetTextAlign(11);
+        leg->SetBit(kCanDelete);
+        leg->Draw();
+
+        q->cd(2);
+
+        TGraph *g = new TGraph;
+        g->SetPoint(0, 0, 0);
+
+        Int_t max=0;
+        Float_t maxsig=0;
+        for (int i=1; i<89; i++)
+        {
+            const Double_t s = f1.Integral(0, (float)i)/w;
+            const Double_t b = f2.Integral(0, (float)i)/w;
+
+            const Double_t sig = MMath::SignificanceLiMaSigned(s, b);
+
+            g->SetPoint(g->GetN(), i, sig);
+
+            if (sig>maxsig)
+            {
+                max = i;
+                maxsig = sig;
+            }
+        }
+
+        g->SetNameTitle("SigVs\\alpha", "Significance vs \\alpha");
+        g->GetHistogram()->SetXTitle("\\alpha_{0} [\\circ]");
+        g->GetHistogram()->SetYTitle("Significance");
+        g->SetBit(kCanDelete);
+        g->Draw("AP");
+
+        leg = new TPaveText(0.35, 0.10, 0.90, 0.25, "brNDC");
+        leg->SetBorderSize(1);
+        leg->SetTextSize(0.1);
+        leg->AddText(Form("S_{max}=%.1f\\sigma at \\alpha_{max}=%d\\circ", maxsig, max));
+        leg->SetBit(kCanDelete);
+        leg->Draw();
+    }
+}
Index: /tags/Mars-V0.9/mhflux/MHFalseSource.h
===================================================================
--- /tags/Mars-V0.9/mhflux/MHFalseSource.h	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/MHFalseSource.h	(revision 9772)
@@ -0,0 +1,103 @@
+#ifndef MARS_MHFalseSource
+#define MARS_MHFalseSource
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+class TH2D;
+
+class MParList;
+class MTime;
+class MSrcPosCam;
+class MPointingPos;
+class MObservatory;
+
+class MHFalseSource : public MH
+{
+private:
+    MTime         *fTime;        //! container to take the event time from
+    MPointingPos  *fPointPos;    //! container to take pointing position from
+    MSrcPosCam    *fSrcPos;      //! container for sopurce position in camera
+    MObservatory  *fObservatory; //! conteiner to take observatory location from
+
+    Float_t fMm2Deg;             // conversion factor for display in degrees
+
+    Float_t fAlphaCut;           // Alpha cut
+    Float_t fBgMean;             // Background mean
+
+    Float_t fMinDist;            // Min dist
+    Float_t fMaxDist;            // Max dist
+
+    Float_t fMinDW;              // Minimum distance in percent of dist
+    Float_t fMaxDW;              // Maximum distance in percent of dist
+
+    TH3D    fHist;               // Alpha vs. x and y
+
+    const TH3D *fHistOff;
+
+    Double_t fRa;
+    Double_t fDec;
+
+    Int_t DistancetoPrimitive(Int_t px, Int_t py);
+    void Modified();
+
+    void ProjectAll(TH2D *h);
+    void ProjectOff(const TH3D &src, TH2D *h, TH2D *all);
+    void ProjectOn(const TH3D &src, TH2D *h, TH2D *all);
+    void ProjectOnOff(TH2D *h, TH2D *all);
+
+    TObject *GetCatalog();
+
+    void MakeSymmetric(TH1 *h);
+
+public:
+    MHFalseSource(const char *name=NULL, const char *title=NULL);
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void FitSignificance(Float_t sigint=10, Float_t sigmax=75, Float_t bgmin=45, Float_t bgmax=85, Byte_t polynom=2); //*MENU*
+    void FitSignificanceStd() { FitSignificance(); } //*MENU*
+
+    void SetMinDist(Float_t dist) { fMinDist = dist; } // Absolute minimum distance
+    void SetMaxDist(Float_t dist) { fMaxDist = dist; } // Absolute maximum distance
+    void SetMinDW(Float_t ratio)  { fMinDW = ratio; }  // Minimum ratio between length/dist
+    void SetMaxDW(Float_t ratio)  { fMaxDW = ratio; }  // Maximum ratio between length/dist
+
+    void SetAlphaCut(Float_t alpha); //*MENU*
+    void SetAlphaPlus5()  { SetAlphaCut(fAlphaCut+5); } //*MENU*
+    void SetAlphaMinus5() { SetAlphaCut(fAlphaCut-5); } //*MENU*
+
+    void SetBgMean(Float_t alpha); //*MENU*
+    void SetBgMeanPlus5()  { SetBgMean(fBgMean+5); } //*MENU*
+    void SetBgMeanMinus5() { SetBgMean(fBgMean-5); } //*MENU*
+
+    void SetOffData(const MHFalseSource &fs) {
+        fHistOff  = &fs.fHist;
+        fMinDist  =  fs.fMinDist;
+        fMaxDist  =  fs.fMaxDist;
+        fMaxDW    =  fs.fMaxDW;
+        fMinDW    =  fs.fMinDW;
+        fAlphaCut =  fs.fAlphaCut;
+        fBgMean   =  fs.fBgMean;
+    }
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+
+    // MH
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    // TObject
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *option="");
+
+    ClassDef(MHFalseSource, 1) //3D-histogram in alpha, x and y
+};
+
+#endif
Index: /tags/Mars-V0.9/mhflux/Makefile
===================================================================
--- /tags/Mars-V0.9/mhflux/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mhflux/Makefile	(revision 9772)
@@ -0,0 +1,38 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Flux
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mraw -I../manalysis      \
+	   -I../mgui -I../mgeom -I../mdata -I../mfilter -I../mimage \
+           -I../mmain -I../mmc -I../mreflector -I../mpointing       \
+           -I../mastro -I../mpedestal -I../msignal -I../mbadpixels
+
+SRCFILES = MAlphaFitter.cc \
+	   MHAlpha.cc \
+           MHEnergyEst.cc \
+	   MHEffectiveOnTime.cc \
+           MHFalseSource.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mhft/HftIncl.h
===================================================================
--- /tags/Mars-V0.9/mhft/HftIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mhft/HftIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mhft/HftLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mhft/HftLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mhft/HftLinkDef.h	(revision 9772)
@@ -0,0 +1,14 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHexagonalFT+;
+#pragma link C++ class MHexagonalFTCalc+;
+#pragma link C++ class MHexagonFreqSpace+;
+
+#pragma link C++ class MGeomCamMagicXT+;
+#pragma link C++ class MGeomCamMagicEnhance+;
+
+#endif
Index: /tags/Mars-V0.9/mhft/MGeomCamMagicEnhance.cc
===================================================================
--- /tags/Mars-V0.9/mhft/MGeomCamMagicEnhance.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MGeomCamMagicEnhance.cc	(revision 9772)
@@ -0,0 +1,175 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 12/2004  <mailto:>
+!   Author(s): Thomas Bretz, 12/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagicEnhance
+//
+// This task takes MSignalCam assuming that it is related to the Magic
+// camera geometry. By deviding and interpolation it resamples MSignalCam
+// such, that afterwards it is related to a geometry MGeomCamMagicXT
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagicEnhance.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MArrayD.h"
+
+ClassImp(MGeomCamMagicEnhance);
+
+using namespace std;
+
+const char *MGeomCamMagicEnhance::fgNameSignalCamIn  = "MSignalCam";
+const char *MGeomCamMagicEnhance::fgNameSignalCamOut = "MSignalCam";
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor - empty
+//
+MGeomCamMagicEnhance::MGeomCamMagicEnhance(const char *name, const char *title)
+    : fNameSignalCamIn(fgNameSignalCamIn), fNameSignalCamOut(fgNameSignalCamOut),
+    fEvtIn(0), fEvtOut(0)
+{
+    fName  = name  ? name  : "MGeomCamMagicEnhance";
+    fTitle = title ? title : "Task to convert MSignalCam from MGeomCamMagic to MGeomCamMagicXT";
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Search for MSignalCam input and output container.
+//
+Int_t MGeomCamMagicEnhance::PreProcess(MParList *plist)
+{
+    fEvtIn = (MSignalCam*)plist->FindObject(fNameSignalCamIn, "MSignalCam");
+    if (!fEvtIn)
+    {
+        *fLog << err << fNameSignalCamIn << " [MSignalCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fEvtOut = (MSignalCam*)plist->FindCreateObj("MSignalCam", fNameSignalCamOut);
+    if (!fEvtOut)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Convert MCerPhotEvent into a new MArrayD depending on the new geometry
+//
+MArrayD MGeomCamMagicEnhance::Convert() const
+{
+    Double_t dEvt[577];
+    for (int i = 0; i<577; ++i)
+        dEvt[i] = fEvtIn->GetPixById(i)->GetNumPhotons();
+
+    MArrayD dEvent(1141);
+    memcpy(dEvent.GetArray(), dEvt, 577*sizeof(Double_t));
+
+    int k = 397; // alter Pixelindex
+    int m = 397; // neuer Index nach einem Durchlauf
+
+    double* pEvent = dEvent.GetArray() + 397;
+
+    for( int i = 0 ; i < 4 ; ++i )
+    {
+        for( int j = 0; j < 6; ++j )
+            for( int h = 0; h < 6 + i; ++h )
+            {
+                if( !j && !h )
+                    *(pEvent++) = 0.25*0.5*( dEvt[ m ] + dEvt[ m + (6 + i)*6 - 1 ] );
+
+                *(pEvent++) = 0.25*dEvt[ k ];
+
+                if(!(j == 5 && h == 5 + i)){
+                    if( i && h != 5 + i){
+                        *(pEvent++) = 0.25*1/3.*( dEvt[ k ] + dEvt[ k + 1 ] + dEvt[ k - (5 + i)*6 - j ] );
+                    }else
+                        *(pEvent++) = 0.25*0.5*( dEvt[ k ] + dEvt[ k + 1 ] );
+                }
+                k++;
+            }
+
+        k = m;
+
+        for( int j = 0; j < 6; ++j )
+            for( int h = 0; h < 6 + i; ++h )
+            {
+                if( !h && !j ){
+                    if( i != 3)
+                        *(pEvent++) = 0.25*0.25*( dEvt[ m ] + dEvt[ m + (6 + i)*6 - 1 ] + dEvt[ m + (6 + i)*6 ] + dEvt[ m + 12*i + 77 /*m + (6 + i)*6 + (6 + i + 1)*6 - 1*/ ] );
+                    else
+                        *(pEvent++) = 0.25*0.5*( dEvt[ m ] + dEvt[ m + (6 + i)*6 - 1 ] );
+                }
+
+                if( !h && j ){
+                    if( i != 3 ){
+                        *(pEvent++) = 0.25*0.25*( dEvt[ k - 1 ] + dEvt[ k ] + dEvt[ k + (6 + i)*6 + j - 1 ] + dEvt[ k + (6 + i)*6 + j ] );
+                    }else
+                        *(pEvent++) = 0.25*0.5*( dEvt[ k - 1 ] + dEvt[ k ] );
+                }
+
+                *(pEvent++) = 0.25*dEvt[ k ];
+                *(pEvent++) = 0.25*dEvt[ k ];
+
+                k++;
+
+            }
+
+        m += (6 + i)*6;
+    }
+
+    return dEvent;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Call Convert and copy result into output MSignalCam
+//
+Int_t MGeomCamMagicEnhance::Process()
+{
+    // Convert old stylish magic camera into new enhanced version
+    const MArrayD res(Convert());
+
+    // Copy result into output MSignalCam
+    fEvtOut->InitSize(res.GetSize());
+
+    for (UInt_t i=0; i<res.GetSize(); i++)
+        fEvtOut->AddPixel(i, res[i], 0);
+
+    //fEvtOut->FixSize();
+    fEvtOut->SetReadyToSave();
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mhft/MGeomCamMagicEnhance.h
===================================================================
--- /tags/Mars-V0.9/mhft/MGeomCamMagicEnhance.h	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MGeomCamMagicEnhance.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MGeomCamMagicEnhance
+#define MARS_MGeomCamMagicEnhance
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MArrayD;
+class MSignalCam;
+
+class MGeomCamMagicEnhance : public MTask
+{
+private:
+    static const char *fgNameSignalCamIn;
+    static const char *fgNameSignalCamOut;
+
+    TString fNameSignalCamIn;
+    TString fNameSignalCamOut;
+
+    MSignalCam *fEvtIn;
+    MSignalCam *fEvtOut;
+
+    MArrayD Convert() const;
+
+    Int_t PreProcess(MParList *p);
+    Int_t Process();
+
+    void CleanFreqSpace(MArrayD &re, MArrayD &im);
+
+public:
+    MGeomCamMagicEnhance(const char *name=0, const char *title=0);
+
+    void SetNameSignalCamIn(const char *n) { fNameSignalCamIn = n; }
+    void SetNameSignalCamOut(const char *n) { fNameSignalCamOut = n; }
+
+    ClassDef(MGeomCamMagicEnhance, 0) //Task to convert MSignalCam from MGeomCamMagic to MGeomCamMagicXT
+};
+    
+#endif
Index: /tags/Mars-V0.9/mhft/MGeomCamMagicXT.cc
===================================================================
--- /tags/Mars-V0.9/mhft/MGeomCamMagicXT.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MGeomCamMagicXT.cc	(revision 9772)
@@ -0,0 +1,182 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 12/2004  <mailto:>
+!   Author(s): Thomas Bretz, 12/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGeomCamMagicXT
+//
+// This class stores the geometry information of the 'extended' Magic
+// camera. The extended geometry has also small pixels in the outer region.
+// To convert MCerPhotEvt from MGeomCamMagic to MGeomCamMagicXT use
+// MGeomCamMagicExtend.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGeomCamMagicXT.h"
+
+#include "MGeomPix.h"
+
+ClassImp(MGeomCamMagicXT);
+
+// --------------------------------------------------------------------------
+//
+//  Magic camera has 577 pixels. For geometry and Next Neighbor info see
+//  CreateCam and CreateNN
+//
+MGeomCamMagicXT::MGeomCamMagicXT(const char *name)
+    : MGeomCam(1141, 17, name, "Geometry information of Magic Camera")
+{
+    CreateCam();
+    CreateNN();
+    InitGeometry();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the geometry information from a table into the pixel objects.
+//
+void MGeomCamMagicXT::CreateCam()
+{
+    //
+    // fill the geometry class with the coordinates of the CT1 camera
+    //
+    //*fLog << inf << " Create CT1 geometry " << endl;
+
+    //
+    // this algorithm is from Martin Kestel originally
+    // it was punt into a root/C++ context by Harald Kornmayer and Thomas Bretz
+   
+    const Float_t diameter = 30;    // units are mm
+    const Float_t kS32  = sqrt(3)/2;
+
+    //
+    //  add the first pixel to the list
+    //
+    Int_t pixnum = 0;
+
+    (*this)[pixnum++].Set(0, 0, diameter);
+
+    for (Int_t ring=1; ring<20; ring++)
+    {
+        //
+        // calc. coords for this ring counting from the
+        // starting number to the ending number
+        //
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring-i*0.5)*diameter,
+                                  i*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring*0.5-i)*diameter,
+                                  ring*kS32 * diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set(-(ring+i)*0.5*diameter,
+                                  (ring-i)*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((0.5*i-ring)*diameter,
+                                  -i*kS32*diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((i-ring*0.5)*diameter,
+                                  -ring*kS32 * diameter,
+                                  diameter);
+
+        for (int i=0; i<ring; i++)
+            (*this)[pixnum++].Set((ring+i)*0.5*diameter,
+                                  (-ring+i)*kS32*diameter,
+                                  diameter);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  This fills the next neighbor information from a table into the pixel
+//  objects.
+//
+void MGeomCamMagicXT::CreateNN()
+{
+    Int_t pos = 0;
+
+    const Short_t nn[7][6] = {         // Neighbors of #
+        {   1,   2,   3,   4,   5,   6}, // 0
+        {   0,   2,   6,   7,   8,  18},
+        {   0,   1,   3,   8,   9,  10},
+        {   0,   2,   4,  10,  11,  12},
+        {   0,   3,   5,  12,  13,  14},
+        {   0,   4,   6,  14,  15,  16},
+        {   0,   1,   5,  16,  17,  18}
+    };
+
+    for (Int_t i=0; i<7; i++)
+        (*this)[pos++].SetNeighbors(nn[i][0], nn[i][1], nn[i][2],
+                                    nn[i][3], nn[i][4], nn[i][5]);
+
+    for (Int_t ring=2; ring<20; ring++)
+    {
+        for (Int_t s=0; s<6; s++)
+        {
+            for (int i=pos; i<ring+pos; i++)
+            {
+                Int_t n[6], idx[6];
+
+                n[0] = i==pos&&s==0 ? i+6*ring : i-1;                // vor
+                n[1] = i==ring+pos-1&&s==5 ? i-12*(ring-1)-5 : i+1;  // danach
+                n[2] = i==pos ? i+6*ring-1+s   : i-6*(ring-1)-s;     // ring- groesser
+                n[3] = i==pos ? i-6*(ring-1)-s : i-6*(ring-1)-1-s;   // ring- kleiner
+                n[4] = i==pos&&s==0 ? i+12*ring+5 : i+6*ring+s;      // ring+ kleiner
+                n[5] = i+6*ring+1+s;                                 // ring+ groesser
+
+                if (n[0]>1140)
+                    n[0] = -1;
+                if (n[1]>1140)
+                    n[1] = -1;
+                if (n[2]>1140)
+                    n[2] = -1;
+                if (n[3]>1140)
+                    n[3] = -1;
+                if (n[4]>1140)
+                    n[4] = -1;
+                if (n[5]>1140)
+                    n[5] = -1;
+
+                TMath::Sort(6, n, idx);
+
+                (*this)[i].SetNeighbors(n[idx[0]],
+                                        n[idx[1]],
+                                        n[idx[2]],
+                                        n[idx[3]],
+                                        n[idx[4]],
+                                        n[idx[5]]);
+            }
+
+            pos += ring;
+        }
+    }
+}
Index: /tags/Mars-V0.9/mhft/MGeomCamMagicXT.h
===================================================================
--- /tags/Mars-V0.9/mhft/MGeomCamMagicXT.h	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MGeomCamMagicXT.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MGeomCamMagicXT
+#define MARS_MGeomCamMagicXT
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+class MGeomCamMagicXT : public MGeomCam
+{
+private:
+    void CreateCam();
+    void CreateNN();
+
+public:
+    MGeomCamMagicXT(const char *name=NULL);
+
+    ClassDef(MGeomCamMagicXT, 1) // Geometry class for the 'extended' Magic camera
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhft/MHexagonFFT.cc
===================================================================
--- /tags/Mars-V0.9/mhft/MHexagonFFT.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MHexagonFFT.cc	(revision 9772)
@@ -0,0 +1,578 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 11/2004  <mailto:>
+!   Author(s): Thomas Bretz, 11/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHexagonFFT.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHexagonFFT);
+
+using namespace std;
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor
+//  Initializes random number generator and default variables
+//
+MHexagonFFT::MHexagonFFT()
+{
+}
+
+/*
+void MHexagonFFT::Prepare(Int_t num, Float_t scale)
+{
+    //Int_t    num   = 34;
+    //Double_t scale = dist_y/dist_x;
+
+    Int_t    cnt   = 108*num*num;
+
+    psire.Set(num*num);
+    psiim.Set(num*num);
+
+//    for(int j=0; j<num; j++)
+//    {
+//        for(int n=0; n<num; n++)
+//        {
+//            if (arr_k_m_id[j][n]<0)
+//                continue;
+//
+//            Double_t sumre=0;
+//            Double_t sumim=0;
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m<34-k; m++)
+                {
+                    //Int_t new_ID=arr_k_m_id[k][m];
+                    //if (new_ID<0)
+                    //    continue;
+
+                    Double_t dx = 0.5*(m-k)/num;
+                    Double_t dy = 0.5*(m+k)/num*scale;
+
+                    dx *= TMath::TwoPi()/3;
+                    dy *= TMath::TwoPi()/fgSqrt3;
+
+                    const Double_t cos1 = cos(dy*(j+n));
+                    const Double_t cos2 = cos(dy*j);
+                    const Double_t cos3 = cos(dy*n);
+
+                    //Alternatie nach Paper:
+                    psire[m*num+k] = 0.5*(
+                        +cos1*cos(dx*(j-n))
+                        +cos2*cos(dx*(j+2*n))
+                        +cos3*cos(dx*(2*j+n)));
+
+                    psiim[m*num+k] = 0.5*(
+                        +cos1*sin(dx*(j-n))
+                        +cos2*sin(dx*(j+2*n))
+                        -cos3*sin(dx*(2*j+n)));
+
+
+//                    psi_im *= i_inv;
+//
+//                    Double_t factor = (i_inv==1?1.:P_j_n(k,m));
+//
+//                    sumre += factor * (inre[new_ID]*psi_re - inim[new_ID]*psi_im);
+//                    sumim += factor * (inre[new_ID]*psi_im + inim[new_ID]*psi_re);
+}
+            }
+
+//            Double_t factor = (i_inv==1?1.:P_j_n(j,n)/cnt);
+//
+//            outre[arr_k_m_id[j][n]] = factor * sumre;
+//            outim[arr_k_m_id[j][n]] = factor * sumim;
+//        }
+//    }
+}
+*/
+
+void MHexagonFFT::Prepare(Float_t scale, Int_t num)
+{
+    static const Double_t fgSqrt3 = TMath::Sqrt(3.);
+
+    fNum = num;
+
+    MArrayD fCosX(num*num*num*3);
+    MArrayD fCosY(num*num*num*3);
+    MArrayD fSin(num*num*num*3);
+
+    for(int j=0; j<3*num; j++)
+    {
+        for(int k=0; k<num; k++)
+        {
+            for(int m=0; m<num-k; m++)
+            {
+                Double_t dx = 0.5*(m-k)/num;
+                Double_t dy = 0.5*(m+k)/num*scale;
+
+                dx *= TMath::TwoPi()/3;
+                dy *= TMath::TwoPi()/fgSqrt3;
+
+                const Int_t idx = (m*num + k)*3*num;
+
+                fCosX[idx+j] = TMath::Cos(dx*j);
+                fCosY[idx+j] = TMath::Cos(dy*j);
+                fSin [idx+j] = TMath::Sin(dx*j);
+            }
+        }
+    }
+
+    //fPsiRe.Set(num*num*num*num);
+    //fPsiIm.Set(num*num*num*num);
+    fPsi.Set(num*num*num*num*2);
+
+    Int_t lim = num*(num+1)/2;
+
+    fM.Set(lim);
+    fK.Set(lim);
+    fP.Set(lim);
+    fIdx.Set(lim);
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            int idx0 = num-n-1;
+            int idx1 = idx0*(idx0+1)/2 + j;
+
+            fM[idx1]=n;
+            fK[idx1]=j;
+
+            fP[idx1]=P(j,n);
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m<num-k; m++)
+                {
+                    const Int_t idx = (m*num + k)*3*num;
+
+                    const Float_t cos1 = fCosY[idx+j+n];
+                    const Float_t cos2 = fCosY[idx+j];
+                    const Float_t cos3 = fCosY[idx+n];
+
+                    int idx2 = num-m-1;
+                    int idx3 = idx2*(idx2+1)/2 + k;
+                    const Int_t id1 = idx1*lim + idx3;
+
+                    //fPsiRe[id1]
+                    Double_t fPsiRe
+                        = 2*(
+                          +cos1*fCosX[idx+TMath::Abs(j-n)]
+                          +cos2*fCosX[idx+j+2*n]
+                          +cos3*fCosX[idx+2*j+n]);
+
+                    //fPsiIm[id1] = 2*(
+                    Double_t fPsiIm = 2*(
+                          +cos1*fSin[idx+TMath::Abs(j-n)]*TMath::Sign(1, j-n)
+                          +cos2*fSin[idx+j+2*n]
+                          -cos3*fSin[idx+2*j+n]);
+
+                    fPsi[id1*2]   = fPsiRe;//fPsiRe[id1];
+                    fPsi[id1*2+1] = fPsiIm;//fPsiIm[id1];
+                }
+            }
+
+        }
+    }
+
+    for (int idx1=0; idx1<lim; idx1++)
+    {
+        int n = fM[idx1];
+        int j = fK[idx1];
+
+        int idx0;
+        for (idx0=0; idx0<lim; idx0++)
+            if (fM[idx0]==j && fK[idx0]==n)
+                break;
+
+        fIdx[idx1]=idx0;
+    }
+
+}
+/*
+void MHexagonFFT::DGT4(const MArrayD &inre,
+                       const MArrayD &inim,
+                       MArrayD &outre,
+                       MArrayD &outim,
+                       Float_t scale,
+                       Bool_t fwd)
+{
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*num*num;
+    Int_t lim = num*(num+1)/2;
+
+    Float_t *endp = fP.GetArray()+lim;
+
+    for (int idx1=0; idx1<lim; idx1++)
+    {
+        if (fK[idx1]>fM[idx1] && fwd)
+            continue;
+
+        Double_t sumre=0;
+        Double_t sumim=0;
+
+        Float_t  *psi = fPsi.GetArray() + idx1*lim*2;
+        Float_t  *p   = fP.GetArray();
+        Double_t *im  = inim.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        while (p<endp)
+        {
+            const Float_t factor1 = (fwd?*p:1.);
+
+            const Float_t psire = *psi++;
+            const Float_t psiim = *psi++;
+
+            sumre     += factor1 * (*re * psire - *im * psiim);
+            if (fwd)
+                sumim += factor1 * (*re * psiim + *im * psire);
+
+            im++;
+            re++;
+            p++;
+        }
+
+        const Double_t factor2 = fwd?fP[idx1]/cnt:1.;
+
+        outre[idx1] =  factor2 * sumre;
+        outim[idx1] = -factor2 * sumim;
+    }
+
+    if (!fwd)
+        return;
+
+    for (int idx1=0; idx1<lim; idx1++)
+    {
+        if (fK[idx1]<fM[idx1])
+            continue;
+
+        outre[idx1] =  outre[fIdx[idx1]];
+        outim[idx1] = -outim[fIdx[idx1]];
+    }
+    }*/
+
+void MHexagonFFT::TransformFastFWD(const MArrayD &inre,
+                                   MArrayD &outre,
+                                   MArrayD &outim) const
+{
+    const UInt_t num = fP.GetSize();
+
+    if (inre.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonFFT prepared for different size." << endl;
+        return;
+    }
+
+    outre.Set(num);
+    outim.Set(num);
+
+    const Int_t cnt = 108*fNum*fNum;
+
+    const Float_t *endp = fP.GetArray()+num;
+
+    for (UInt_t idx1=0; idx1<num; idx1++)
+    {
+        if (fK[idx1]>fM[idx1])
+            continue;
+
+        Double_t sumre=0;
+        Double_t sumim=0;
+
+        Float_t  *psi = fPsi.GetArray() + idx1*num*2;
+        Float_t  *p   = fP.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        // 1st access to psi: const Float_t psire = *psi++;
+        // 2nd access to psi: const Float_t psiim = *psi++;
+        // sumre += f * *psire;
+        // sumim += f * *psiim;
+        while (p<endp)
+        {
+            const Double_t f = *p++ * *re++;
+
+            sumre += f * *psi++;
+            sumim += f * *psi++;
+        }
+
+        const Double_t factor2 = fP[idx1]/cnt;
+
+        outre[fIdx[idx1]] =   outre[idx1] =  factor2 * sumre;
+        outim[fIdx[idx1]] = -(outim[idx1] = -factor2 * sumim);
+
+        /*
+         outre[idx1] =  factor2 * sumre;
+         outim[idx1] = -factor2 * sumim;
+
+         outre[fIdx[idx1]] =  outre[idx1];
+         outim[fIdx[idx1]] = -outim[idx1];
+         */
+    }
+    /*
+     for (UInt_t idx1=0; idx1<num; idx1++)
+     {
+        if (fK[idx1]<fM[idx1])
+           continue;
+
+        outre[idx1] =  outre[fIdx[idx1]];
+        outim[idx1] = -outim[fIdx[idx1]];
+     }
+     */
+}
+
+void MHexagonFFT::TransformFastBWD(const MArrayD &inre,
+                                   const MArrayD &inim,
+                                   MArrayD &outre) const
+{
+    const UInt_t num = fP.GetSize();
+
+    if (inre.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonFFT prepared for different size." << endl;
+        return;
+    }
+    if (inim.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonFFT prepared for different size." << endl;
+        return;
+    }
+    outre.Set(num);
+
+
+    const Double_t *endre = inre.GetArray()+num;
+
+    for (UInt_t idx1=0; idx1<num; idx1++)
+    {
+        Float_t  *psi = fPsi.GetArray() + idx1*num*2;
+        Double_t *im  = inim.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        Double_t sumre=0;
+        while (re<endre)
+        {
+            const Float_t psire = *psi++;
+            const Float_t psiim = *psi++;
+
+            sumre += *re++ * psire - *im++ * psiim;
+        }
+
+        outre[idx1] = sumre;
+    }
+}
+/*
+void MHexagonFFT::DGT3(const MArrayD &inre,
+                       const MArrayD &inim,
+                       MArrayD &outre,
+                       MArrayD &outim,
+                       Float_t scale,
+                       Bool_t fwd)
+{
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*num*num;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            if (j-n>0 && fwd)
+                continue;
+
+            Double_t sumre=0;
+            Double_t sumim=0;
+
+            Int_t lim = num*(num+1)/2;
+            for (int idx0=0; idx0<lim; idx0++)
+
+//            for(int k=0; k<num; k++)
+            {
+                int m = fM[idx0];
+                int k = fK[idx0];
+            //                for(int m=0; m<num-k; m++)
+
+                {
+                    const Int_t id = k*num + m;
+                    const Int_t id1 = (((id*num)+n)*num+j)*2;
+
+                    //Alternatie nach Paper:
+                    const Float_t psire = fPsi[id1];   //fPsiRe[(id*num+n)*num+j];
+                    const Float_t psiim = fPsi[id1+1]; //fPsiIm[(id*num+n)*num+j]*inv;
+
+                    const Float_t factor1 = fwd==1?P(k,m):1.;
+
+                    sumre += factor1 * (inre[id]*psire - inim[id]*psiim);
+                    if (fwd)
+                        sumim += factor1 * (inre[id]*psiim + inim[id]*psire);
+                }
+            }
+
+            const Double_t factor2 = fwd==1?P(j,n)/cnt:1.;
+
+            outre[j*num+n] =  factor2 * sumre;
+            outim[j*num+n] = -factor2 * sumim;
+
+            if (!fwd)
+                continue;
+
+            outre[n*num+j] =  factor2 * sumre;
+            outim[n*num+j] =  factor2 * sumim;
+        }
+    }
+}
+
+void MHexagonFFT::DGT2(const MArrayD &inre,
+                       const MArrayD &inim,
+                       MArrayD &outre,
+                       MArrayD &outim,
+                       Float_t scale,
+                       Bool_t fwd)
+{
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*num*num;
+    Int_t inv = fwd?-1:1;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            if (j-n>0 && fwd)
+                continue;
+
+            Double_t sumre=0;
+            Double_t sumim=0;
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m<num-k; m++)
+                {
+                    const Int_t idx = (m*num + k)*3*num;
+
+                    const Float_t cos1 = fCosY[idx+j+n];
+                    const Float_t cos2 = fCosY[idx+j];
+                    const Float_t cos3 = fCosY[idx+n];
+
+                    //Alternatie nach Paper:
+                    const Float_t psire = 2*(
+                          +cos1*fCosX[idx+TMath::Abs(j-n)]
+                          +cos2*fCosX[idx+j+2*n]
+                          +cos3*fCosX[idx+2*j+n]);
+
+                    const Float_t psiim = 2*inv*(
+                          +cos1*fSin[idx+TMath::Abs(j-n)]*TMath::Sign(1, j-n)
+                          +cos2*fSin[idx+j+2*n]
+                          -cos3*fSin[idx+2*j+n]);
+
+                    const Float_t factor = (fwd==1?P(k,m):1.);
+
+                    sumre += factor * (inre[k*num+m]*psire - inim[k*num+m]*psiim);
+                    sumim += factor * (inre[k*num+m]*psiim + inim[k*num+m]*psire);
+                }
+            }
+
+            const Double_t factor = (fwd==1?P(j,n)/cnt:1.);
+
+            outre[j*num+n] = factor * sumre;
+            outim[j*num+n] = factor * sumim;
+
+            if (fwd)
+            {
+                outre[n*num+j] =  factor * sumre;
+                outim[n*num+j] = -factor * sumim;
+            }
+        }
+    }
+}
+*/
+void MHexagonFFT::TransformSlow(const MArrayD &inre, const MArrayD &inim,
+                                MArrayD &outre,      MArrayD &outim,
+                                Float_t scale,       Bool_t fwd)
+{
+    static const Double_t fgSqrt3 = TMath::Sqrt(3.);
+
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*num*num;
+    Int_t inv = fwd?-1:1;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            if (j-n>0 && fwd)
+                continue;
+
+            Double_t sumre=0;
+            Double_t sumim=0;
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m<num-k; m++)
+                {
+                    Double_t dx = 0.5*(m-k)/num;
+                    Double_t dy = 0.5*(m+k)/num*scale;
+
+                    dx *= TMath::TwoPi()/3;
+                    dy *= TMath::TwoPi()/fgSqrt3;
+
+                    const Double_t cos1 = TMath::Cos(dy*(j+n));
+                    const Double_t cos2 = TMath::Cos(dy*j);
+                    const Double_t cos3 = TMath::Cos(dy*n);
+
+                    //Alternatie nach Paper:
+                    const Double_t psire = 2*(
+                        +cos1*TMath::Cos(dx*(j-n))
+                        +cos2*TMath::Cos(dx*(j+2*n))
+                        +cos3*TMath::Cos(dx*(2*j+n)));
+
+                    const Double_t psiim = 2*inv*(
+                        +cos1*TMath::Sin(dx*(j-n))
+                        +cos2*TMath::Sin(dx*(j+2*n))
+                        -cos3*TMath::Sin(dx*(2*j+n)));
+
+                    const Double_t factor = (fwd==1?P(k,m):1.);
+
+                    sumre += factor * (inre[k*num+m]*psire - inim[k*num+m]*psiim);
+                    sumim += factor * (inre[k*num+m]*psiim + inim[k*num+m]*psire);
+                }
+            }
+
+            const Double_t factor = (fwd==1?P(j,n)/cnt:1.);
+
+            outre[j*num+n] = factor * sumre;
+            outim[j*num+n] = factor * sumim;
+
+            if (fwd)
+            {
+                outre[n*num+j] =  factor * sumre;
+                outim[n*num+j] = -factor * sumim;
+            }
+        }
+    }
+}
Index: /tags/Mars-V0.9/mhft/MHexagonFFT.h
===================================================================
--- /tags/Mars-V0.9/mhft/MHexagonFFT.h	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MHexagonFFT.h	(revision 9772)
@@ -0,0 +1,78 @@
+#ifndef MARS_MHexagonFFT
+#define MARS_MHexagonFFT
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_MArrayF
+#include "MArrayF.h"
+#endif
+#ifndef ROOT_MArrayI
+#include "MArrayI.h"
+#endif
+
+class MHexagonFFT : public TObject
+{
+private:
+    static float P(int j, int n)
+    {
+        const Int_t a = (j+n)%34 ? 0 : 1;
+        const Int_t b = j%34     ? 0 : 1;
+        const Int_t c = n%34     ? 0 : 1;
+
+        return 6./((1+a)*(1+b+c));
+    }
+
+    Int_t fNum;
+
+    MArrayF fPsi;
+
+    MArrayI fM;
+    MArrayI fK;
+
+    MArrayF fP;
+
+    MArrayI fIdx;
+
+public:
+    MHexagonFFT();
+    MHexagonFFT(Float_t scale, Int_t num)
+    {
+        Prepare(scale, num);
+    }
+
+    void Prepare(Float_t scale, Int_t num);
+
+    void TransformFastFWD(const MArrayD &inre, MArrayD &outre, MArrayD &outim) const;
+    void TransformFastBWD(const MArrayD &inre, const MArrayD &inim, MArrayD &outre) const;
+
+    void TransformSlow(const MArrayD &inre,
+                       const MArrayD &inim,
+                       MArrayD &outre,
+                       MArrayD &outim,
+                       Float_t scale,
+                       Bool_t fwd=kTRUE);
+    /*
+    void DGT2(const MArrayD &inre,
+             const MArrayD &inim,
+             MArrayD &outre,
+             MArrayD &outim,
+             Float_t scale,
+             Bool_t fwd=kTRUE);
+    void DGT3(const MArrayD &inre,
+             const MArrayD &inim,
+             MArrayD &outre,
+             MArrayD &outim,
+             Float_t scale,
+             Bool_t fwd=kTRUE);
+    void DGT4(const MArrayD &inre,
+             const MArrayD &inim,
+             MArrayD &outre,
+             MArrayD &outim,
+             Float_t scale,
+             Bool_t fwd=kTRUE);
+    */
+    ClassDef(MHexagonFFT,0)
+};
+    
+#endif
Index: /tags/Mars-V0.9/mhft/MHexagonFreqSpace.cc
===================================================================
--- /tags/Mars-V0.9/mhft/MHexagonFreqSpace.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MHexagonFreqSpace.cc	(revision 9772)
@@ -0,0 +1,172 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 08/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHexagonFreqSpace
+//
+// This is a generalized class storing camera data. It stores real and
+// imaginary part of the triangular frequency space of the MHexagonalFT.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHexagonFreqSpace.h"
+
+#include "MMath.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+
+ClassImp(MHexagonFreqSpace);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MCerPhotPix object for each pixel in the event
+//
+MHexagonFreqSpace::MHexagonFreqSpace(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHexagonFreqSpace";
+    fTitle = title ? title : "Storage container for fourier space camera";
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// This is not yet implemented like it should.
+//
+
+void MHexagonFreqSpace::Draw(Option_t* option) 
+{
+    //
+    //   FIXME!!! Here the Draw function of the CamDisplay
+    //   should be called to add the CamDisplay to the Pad.
+    //   The drawing should be done in MCamDisplay::Paint
+    //
+
+    //    MGeomCam *geom = fType ? new MGeomCamMagic : new MGeomCamCT1;
+    //    MCamDisplay *disp = new MCamDisplay(geom);
+    //    delete geom;
+    //    disp->DrawPhotNum(this);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Returns the contents of the pixel.
+//  type 0: sqrt(re^2+im^2)
+//  type 1: re
+//  type 2: im
+//
+Bool_t MHexagonFreqSpace::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx<0 || (UInt_t)idx>=fDataRe.GetSize())
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+        val = TMath::Hypot(fDataRe[idx], fDataIm[idx]);
+        break;
+    case 1:
+        val = fDataRe[idx];
+        break;
+    case 2:
+        val = fDataIm[idx];
+        break;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set real and imaginary part from MArrayD re and im. The size of both
+// arrays must be identical.
+//
+void MHexagonFreqSpace::Set(const MArrayD &re, const MArrayD &im)
+{
+    if (re.GetSize()!=im.GetSize())
+        return;
+/*
+    fDataRe.Set(re.GetSize());
+    fDataIm.Set(re.GetSize());
+    for(unsigned int j=0; j<re.GetSize(); j++)
+    {
+        fDataRe[j]=re[j];
+        fDataIm[j]=im[j];
+    }
+  */
+    fDataRe = re;
+    fDataIm = im;
+}
+
+void MHexagonFreqSpace::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MHexagonFreqSpace::DrawPixelContent - not available." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Create a new geometry based on the size num. which is the number
+// of pixels in the triangle.
+//
+// It is YOUR responsibility to make sure that the allocated MGeomCam is
+// deleted elsewhere!
+//
+// WARNING:
+// ========
+// * Currently there are some basic problems with MGeomCam -- so please don't
+// wonder if you encounter strange behaviour, especially using this
+// kind of MGeomCam as a data member in MHCamera which is itself a data
+// member of some other class.
+// This maybe fixed soon by intoducing a MGeomCamTriangle.
+// * The created geometry does not contain ANY valid neighbor information yet.
+//
+MGeomCam *MHexagonFreqSpace::NewGeomCam(UShort_t num)
+{
+    static const Double_t fgTan30 = TMath::Tan(30*TMath::DegToRad())*3;
+
+    MGeomCam *cam = new MGeomCam(num, 1);
+
+    num = (int)((1.+sqrt(1.+8.*num))/2.)-1;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n<num-j; n++)
+        {
+            int idx1 = (j+n)*(j+n+1)/2 + j;
+
+            (*cam)[idx1].Set(n-j, (n+j-num/2)*fgTan30, 2);
+            (*cam)[idx1].SetNeighbors(-1, -1, -1, -1, -1, -1);
+        }
+    }
+    cam->InitGeometry();
+    return cam;
+}
Index: /tags/Mars-V0.9/mhft/MHexagonFreqSpace.h
===================================================================
--- /tags/Mars-V0.9/mhft/MHexagonFreqSpace.h	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MHexagonFreqSpace.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MHexagonFreqSpace
+#define MARS_MHexagonFreqSpace
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef ROOT_MArrayD
+#include "MArrayD.h"
+#endif
+
+class MGeomCam;
+
+class MHexagonFreqSpace : public MParContainer, public MCamEvent
+{
+private:
+    MArrayD fDataRe;  //
+    MArrayD fDataIm;  //
+
+public:
+    MHexagonFreqSpace(const char *name=NULL, const char *title=NULL);
+    ~MHexagonFreqSpace() { }
+
+    void Set(const MArrayD &re, const MArrayD &im);
+
+    Double_t GetAbs(UInt_t idx) const { return TMath::Hypot(fDataRe[idx], fDataIm[idx]); }
+
+    static MGeomCam *NewGeomCam(UShort_t num);
+    MGeomCam *NewGeomCam() const { return NewGeomCam(fDataRe.GetSize()); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MHexagonFreqSpace, 1) // Generalized storage class for camera data in hexagonal frequency space (triangle)
+};
+
+#endif
Index: /tags/Mars-V0.9/mhft/MHexagonalFT.cc
===================================================================
--- /tags/Mars-V0.9/mhft/MHexagonalFT.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MHexagonalFT.cc	(revision 9772)
@@ -0,0 +1,465 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 11/2004  <mailto:>
+!   Author(s): Thomas Bretz, 11/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHexagonalFT
+//
+// This is a class representating a (fast) fourier transformation explicitly
+// for hexagonal geometries as described in astro-ph/0409388.
+//
+//
+// WARNING:
+// ========
+// Be carefull using the fast transformation (Prepare())! The precalculation
+// consumes a lot of memory. fPsi has the size of 2*n^4 (while n is the
+// number of rows in fourier space). For the enhanced MAGIC camery fPsi has
+// the size 27691682*sizeof(float) = 105.6MB (Std MAGIC: ~12MB)
+//
+// The runtime is more or less determined by the speed of accessing a
+// huge amount of memory (see above) sequentially.
+//
+//
+// Coordinate systems:
+// ===================
+//
+//  original hexagonal structure     enhanced hexagonal structure
+//  ----------------------------     ----------------------------
+//
+//                            structure
+//                            ---------
+//
+//                h h h                  f f h h h f f
+//               h h h h                  f h h h h f
+//              h h h h h       ----->     h h h h h
+//               h h h h                    h h h h
+//                h h h                      h h h
+//                                            f f
+//                                             f
+//
+//                            numbering
+//                            ---------
+//                d c b                  m n o p q r s
+//               e 4 3 a                  g h i j k l
+//              f 5 1 2 9       ----->     b c d e f
+//               g 6 7 8                    7 8 9 a
+//                h i j                      4 5 6
+//                                            2 3
+//                                             1
+//
+// In reality the fourier space looks like because of symmetries:
+//
+//            real part                 imaginary part
+//            ---------                 --------------
+//          m n o p o n m          m   n   o   0  -o  -n  -m
+//           g h i i h g             g   h   i  -i  -h  -g
+//            b c d c b                b   c   0  -c  -b
+//             7 8 8 7                   7   8  -8  -7
+//              4 5 4                      4   0  -4
+//               2 2                         2  -2
+//                1                            0
+//
+//         column: GetK()                  row: GetM()
+//         --------------                  -----------
+//          6 5 4 3 2 1 0                 0 1 2 3 4 5 6
+//           5 4 3 2 1 0                   0 1 2 3 4 5
+//            4 3 2 1 0                     0 1 2 3 4
+//             3 2 1 0                       0 1 2 3
+//              2 1 0                         0 1 2
+//               1 0                           0 1
+//                0                             0
+//
+//       row: GetRow() (m+k)        column: GetCol() (m-k)
+//       -------------------        ----------------------
+//          6 6 6 6 6 6 6         -6  -4  -2   0   2   4   6
+//           5 5 5 5 5 5            -5  -3  -1   1   3   5
+//            4 4 4 4 4               -4  -2   0   2   4
+//             3 3 3 3                  -3  -1   1   3
+//              2 2 2                     -2   0   2
+//               1 1                        -1   1
+//                0                            0
+//
+//
+// The coordinates of the pixels in the triangle are:
+//
+//    Double_t dx; // Distance of too pixels in x
+//    Double_t dy; // Distance of to pixel rows in y
+//    Int_t idx;   // Index of pixel in triangle (see above)
+//
+//    const Float_t x = dx*GetCol(idx);
+//    const Float_t y = dy*Int_t(GetRow(idx)-2*GetNumRows()/3);
+//
+// You can use MGeomCam::GetPixelIdxXY(x, y) to get the corresponding index
+// in space space.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHexagonalFT.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayD.h"
+
+ClassImp(MHexagonalFT);
+
+using namespace std;
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor - empty
+//
+MHexagonalFT::MHexagonalFT()
+{
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor - num is the number of lines the fourier space has.
+//  It calls Prepare to fill the arrays with the necessary coefficients.
+//
+//  Here are some simple rules to calculate parameters in a hexagonal space:
+//
+// Number of Rings (r) ---> Number of Pixels (p)
+// p = 3*r*(r-1)+1
+//
+// Number of Pixels (p) ---> Number of Rings (r)
+// p = (sqrt(9+12*(p-1))+3)/6
+//
+// Number of pixels at one border == number of rings (r)
+// Row of border                  == number of rings (r)
+//
+// Number of rows to get a triangle: 3r-2
+//
+MHexagonalFT::MHexagonalFT(Int_t num)
+{
+    Prepare(num);
+}
+
+// ---------------------------------------------------------------------------
+//
+// Calculate the contents of: fM, fK, fP, fIdx and fPsi.
+//
+// While fPsi are the fourier coefficients, fM and fK are the hexagonal x and
+// y coordinates of the pixel corresponding to the index i which is the
+// common index of all arrays. fP is P(i,j) for all pixels.
+//
+// fIdx is also filled and used for reverse mapping. Due to the geometry
+// the right and left side of the fourier space triangle has identical
+// values. fIdx 'maps' the indices from the right to the left side.
+//
+void MHexagonalFT::Prepare(Int_t num)
+{
+    fNumRows = num;
+
+    fPsi.Set(num*num*num*num*2);
+
+    Int_t lim = num*(num+1)/2;
+
+    fM.Set(lim);
+    fK.Set(lim);
+    fP.Set(lim);
+    fIdx.Set(lim);
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n+j<num; n++)
+        {
+            int idx1 = (j+n)*(j+n+1)/2 + j;
+
+            fM[idx1]=n;
+            fK[idx1]=j;
+
+            fP[idx1]=P(j,n);
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m+k<num; m++)
+                {
+                    const Double_t dx = TMath::Pi()*(m-k)/(num-1)/3;
+                    const Double_t dy = TMath::Pi()*(m+k)/(num-1);
+
+                    const Double_t cos1 = TMath::Cos(dy*(j+n));
+                    const Double_t cos2 = TMath::Cos(dy*j);
+                    const Double_t cos3 = TMath::Cos(dy*n);
+
+                    const Double_t psire = 2*(
+                        +cos1*TMath::Cos(dx*(j-n))
+                        +cos2*TMath::Cos(dx*(j+2*n))
+                        +cos3*TMath::Cos(dx*(2*j+n)));
+
+                    const Double_t psiim = 2*(
+                        +cos1*TMath::Sin(dx*(j-n))
+                        +cos2*TMath::Sin(dx*(j+2*n))
+                        -cos3*TMath::Sin(dx*(2*j+n)));
+
+                    const Int_t idx3 = (k+m)*(k+m+1)/2 + k;
+                    const Int_t id1  = idx1*lim + idx3;
+
+                    fPsi[id1*2]   = psire;
+                    fPsi[id1*2+1] = psiim;
+                }
+            }
+        }
+    }
+
+    for (int idx1=0; idx1<lim; idx1++)
+    {
+        int n = fM[idx1];
+        int j = fK[idx1];
+
+        int idx0;
+        for (idx0=0; idx0<lim; idx0++)
+            if (fM[idx0]==j && fK[idx0]==n)
+                break;
+
+        fIdx[idx1]=idx0;
+    }
+
+}
+
+// ---------------------------------------------------------------------------
+//
+// Do a fast forward tranformation. Because all coefficients are
+// precalculated, the tranformation is reduced to a simple pointer based
+// loop over the coeffiecients multiplied with the corresponding input
+// values.
+//
+// Parameters:
+//  inre: array storing the real part of the input (eg. pixel contents)
+// outre: array storing the real part of the output
+// outim: array storing the imaginary part of the output
+//
+// inre must be of the size of the fourier space triangle. The pixel
+// contents must have been mapped into this new space with the proper
+// pixel indices. The size of outre and outim is set accordingly.
+//
+// After initialization (Prepare()) you can get the size of the arrays with
+// GetNumKnots()
+//
+// For the definition of the coordinate system see class description
+//
+void MHexagonalFT::TransformFastFWD(const MArrayD &inre, MArrayD &outre,
+                                    MArrayD &outim) const
+{
+    const UInt_t num = fP.GetSize();
+
+    if (inre.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonalFT prepared for different size." << endl;
+        return;
+    }
+
+    outre.Set(num);
+    outim.Set(num);
+
+    const Int_t cnt = 108*(fNumRows-1)*(fNumRows-1);
+
+    const Float_t *endp = fP.GetArray()+num;
+
+    for (UInt_t idx1=0; idx1<num; idx1++)
+    {
+        if (fK[idx1]>fM[idx1])
+            continue;
+
+        Double_t sumre=0;
+        Double_t sumim=0;
+
+        Float_t  *psi = fPsi.GetArray() + idx1*num*2;
+        Float_t  *p   = fP.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        // 1st access to psi: const Float_t psire = *psi++;
+        // 2nd access to psi: const Float_t psiim = *psi++;
+        // sumre += f * *psire;
+        // sumim += f * *psiim;
+        while (p<endp)
+        {
+            const Double_t f = *p++ * *re++;
+
+            sumre += f * *psi++;
+            sumim += f * *psi++;
+        }
+
+        const Double_t factor2 = fP[idx1]/cnt;
+
+        outre[fIdx[idx1]] =  (outre[idx1] =  factor2 * sumre);
+        outim[fIdx[idx1]] = -(outim[idx1] = -factor2 * sumim);
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// Do a fast backward tranformation. Because all coefficients are
+// precalculated, the tranformation is reduced to a simple pointer based
+// loop over the coeffiecients multiplied with the corresponding input
+// values.
+//
+// Parameters:
+//  inre: outre of TransformFastBwd
+//  inim: outim of TransformFastBwd
+// outre: backward tranformed real part of the resulting
+//
+// inre and inim must be of the size of the fourier space triangle. The
+// pixel contents must have been mapped into this new space with the proper
+// pixel indices. The size of outre is set accordingly.
+//
+// After initialization (Prepare()) you can get the size of the arrays with
+// GetNumKnots()
+//
+// For the definition of the coordinate system see class description
+//
+void MHexagonalFT::TransformFastBWD(const MArrayD &inre, const MArrayD &inim,
+                                    MArrayD &outre) const
+{
+    const UInt_t num = fP.GetSize();
+
+    // Sanity check: check size of arrays
+    if (inre.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonalFT prepared for different size." << endl;
+        return;
+    }
+    if (inim.GetSize()!=num)
+    {
+        cout << "ERROR - MHexagonalFT prepared for different size." << endl;
+        return;
+    }
+    outre.Set(num);
+
+    const Double_t *endre = inre.GetArray()+num;
+
+    for (UInt_t idx1=0; idx1<num; idx1++)
+    {
+        Float_t  *psi = fPsi.GetArray() + idx1*num*2;
+        Double_t *im  = inim.GetArray();
+        Double_t *re  = inre.GetArray();
+
+        Double_t sumre=0;
+        while (re<endre)
+        {
+            const Float_t psire = *psi++;
+            const Float_t psiim = *psi++;
+
+            sumre += *re++ * psire - *im++ * psiim;
+        }
+
+        outre[idx1] = sumre;
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// This is a slow (direct) version of the tranformation. It is identical
+// for forward and backward tranformation.
+//
+// The whole calculation is done straight forward without any precalculation.
+//
+// Parameters:
+//  inre:  real part of input
+//  inim:  imaginary part of input
+//  outre: real part of output
+//  outim: imaginary part of output
+//  fwd:   kTRUE for forward, kFALSE for backward transformations
+//
+// After initialization (Prepare()) you can get the size of the arrays with
+// GetNumKnots()
+//
+// For the definition of the coordinate system see class description
+//
+// It is currently not tested!
+//
+void MHexagonalFT::TransformSlow(const MArrayD &inre, const MArrayD &inim,
+                                 MArrayD &outre,      MArrayD &outim,
+                                 Bool_t fwd)
+{
+    static const Double_t fgSqrt3 = TMath::Sqrt(3.);
+    static const Double_t fgTan30 = TMath::Tan(30*TMath::DegToRad())*3;
+
+    Int_t num = (Int_t)TMath::Sqrt((Float_t)inim.GetSize());
+    Int_t cnt = 108*(num-1)*(num-1);
+    Int_t inv = fwd?-1:1;
+
+    // FIXME: For p(j,n)
+    fNumRows = num;
+
+    for(int j=0; j<num; j++)
+    {
+        for(int n=0; n+j<num; n++)
+        {
+            if (j-n>0 && fwd)
+                continue;
+
+            Double_t sumre=0;
+            Double_t sumim=0;
+
+            for(int k=0; k<num; k++)
+            {
+                for(int m=0; m+k<num; m++)
+                {
+                    Double_t dx = 0.5*(m-k)/num;
+                    Double_t dy = 0.5*(m+k)/num*fgTan30;
+
+                    dx *= TMath::TwoPi()/3;
+                    dy *= TMath::TwoPi()/fgSqrt3;
+
+                    const Double_t cos1 = TMath::Cos(dy*(j+n));
+                    const Double_t cos2 = TMath::Cos(dy*j);
+                    const Double_t cos3 = TMath::Cos(dy*n);
+
+                    //Alternatie nach Paper:
+                    const Double_t psire = 2*(
+                        +cos1*TMath::Cos(dx*(j-n))
+                        +cos2*TMath::Cos(dx*(j+2*n))
+                        +cos3*TMath::Cos(dx*(2*j+n)));
+
+                    const Double_t psiim = 2*inv*(
+                        +cos1*TMath::Sin(dx*(j-n))
+                        +cos2*TMath::Sin(dx*(j+2*n))
+                        -cos3*TMath::Sin(dx*(2*j+n)));
+
+                    const Double_t factor = (fwd==1?P(k,m):1.);
+
+                    sumre += factor * (inre[k*num+m]*psire - inim[k*num+m]*psiim);
+                    sumim += factor * (inre[k*num+m]*psiim + inim[k*num+m]*psire);
+                }
+            }
+
+            const Double_t factor = (fwd==1?P(j,n)/cnt:1.);
+
+            outre[j*num+n] = factor * sumre;
+            outim[j*num+n] = factor * sumim;
+
+            if (fwd)
+            {
+                outre[n*num+j] =  factor * sumre;
+                outim[n*num+j] = -factor * sumim;
+            }
+        }
+    }
+}
+
+
Index: /tags/Mars-V0.9/mhft/MHexagonalFT.h
===================================================================
--- /tags/Mars-V0.9/mhft/MHexagonalFT.h	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MHexagonalFT.h	(revision 9772)
@@ -0,0 +1,69 @@
+#ifndef MARS_MHexagonalFT
+#define MARS_MHexagonalFT
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_MArrayF
+#include "MArrayF.h"
+#endif
+#ifndef ROOT_MArrayI
+#include "MArrayI.h"
+#endif
+
+class MArrayD;
+class MGeomCam;
+
+class MHexagonalFT : public TObject
+{
+private:
+    
+    int Delta(int i) const
+    {
+        return i==0 || i==(Int_t)fNumRows-1 ? 1 : 0;
+    } // Delta(i) = kronecker(i%(fNumRows-1), 0)
+    float P(int j, int n) const
+    {
+        const Int_t a = Delta(j+n);
+        const Int_t b = Delta(j);
+        const Int_t c = Delta(n);
+
+        return 6./((1+a)*(1+b+c));
+    } // Definition of P(i,j) see paper
+
+    UInt_t fNumRows;
+
+    MArrayF fPsi;
+
+    MArrayI fM;
+    MArrayI fK;
+
+    MArrayF fP;
+
+    MArrayI fIdx;
+
+public:
+    MHexagonalFT();
+    MHexagonalFT(Int_t num);
+
+    void Prepare(Int_t num);
+
+    void TransformFastFWD(const MArrayD &inre, MArrayD &outre, MArrayD &outim) const;
+    void TransformFastBWD(const MArrayD &inre, const MArrayD &inim, MArrayD &outre) const;
+
+    void TransformSlow(const MArrayD &inre, const MArrayD &inim,
+                       MArrayD &outre, MArrayD &outim, Bool_t fwd=kTRUE);
+
+    UInt_t GetNumKnots() const { return fP.GetSize(); } // Return number of knots in triangle
+    UInt_t GetNumRows() const  { return fNumRows; }     // return number of rows in triangle
+
+    UInt_t M(UShort_t i) const { return fM[i]; } // return m-axis-index of absolute index i
+    UInt_t K(UShort_t i) const { return fK[i]; } // return k-axis-index of absolute index i
+
+    Int_t GetRow(UShort_t i) const { return fM[i]+fK[i]; } // return row-index of absolute index i
+    Int_t GetCol(UShort_t i) const { return fM[i]-fK[i]; } // return col-index of absolute index i
+
+    ClassDef(MHexagonalFT,0) // general hexagonal fourier transformation
+};
+    
+#endif
Index: /tags/Mars-V0.9/mhft/MHexagonalFTCalc.cc
===================================================================
--- /tags/Mars-V0.9/mhft/MHexagonalFTCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MHexagonalFTCalc.cc	(revision 9772)
@@ -0,0 +1,321 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Christoph Kolodziejski, 11/2004  <mailto:>
+!   Author(s): Thomas Bretz, 11/2004  <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHexagonalFTCalc
+//
+// Task to perform forward transformation, cuts in fourier space and
+// backward tranformation.
+//
+// If you don't want to copy the rsult back to any MSignalCam call
+// SetNameSignalCamOut()
+//
+// Currently - this will change in the future! - there are two output
+// containers:
+//  - MHexagonalFreqSpace1
+//      real      part: input values in triangle space
+//      imaginary part: output values in triangle space
+//
+//  - MHexagonalFreqSpace2
+//      real      part: real part of frequency space
+//      imaginary part: imaginary part of frequency space
+//
+// To be done:
+// Flags to perform forward/backward trafo only to be able to cut outside!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHexagonalFTCalc.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+#include "MHexagonFreqSpace.h"
+
+#include "MArrayD.h"
+
+ClassImp(MHexagonalFTCalc);
+
+using namespace std;
+
+const char *MHexagonalFTCalc::fgNameGeomCam       = "MGeomCam";
+const char *MHexagonalFTCalc::fgNameSignalCamIn  = "MSignalCam";
+const char *MHexagonalFTCalc::fgNameSignalCamOut = "MSignalCam";
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor - empty. Initialize
+//   fMaxAmplitude   = 0.08
+//   fMaxRowFraction = 0.75
+//
+MHexagonalFTCalc::MHexagonalFTCalc(const char *name, const char *title)
+    : fNameGeomCam(fgNameGeomCam),
+    fNameSignalCamIn(fgNameSignalCamIn), fNameSignalCamOut(fgNameSignalCamOut),
+    fEvtIn(0), fEvtOut(0), 
+    fMaxAmplitude(0.08), fMaxRowFraction(0.75), fSkipBwdTrafo(kFALSE)
+{
+    fName  = name  ? name  : "MHexagonalFTCalc";
+    fTitle = title ? title : "Task to calculate Hexagonal Fourier Transformation";
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Search for all necessary containers.
+//
+// Do a forward transformation for a flat camera, eg:
+//
+//    0 0 1 0 0
+//     0 1 1 0
+//      1 1 1
+//       1 1
+//        1
+//
+// The result (fOffset) is treated as a offset in the fourier space comming
+// from the fact that the camera doesn't extend the whole triangle.
+//
+// Before cutting in the fourier space it is substracted. After cutting it
+// is added again. Scaling is done by the constant-frequency-pixel (index 0)
+//
+// Create the LookUpTable which tells you which fourier space (triangle)
+// pixel index corresponds to which camera pixel index.
+//
+Int_t MHexagonalFTCalc::PreProcess(MParList *plist)
+{
+    fEvtIn = (MSignalCam*)plist->FindObject(fNameSignalCamIn, "MSignalCam");
+    if (!fEvtIn)
+    {
+        *fLog << err << fNameSignalCamIn << " [MSignalCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fEvtOut=0;
+    if (!fNameSignalCamOut.IsNull())
+    {
+        fEvtOut = (MSignalCam*)plist->FindCreateObj(fNameSignalCamOut, "MSignalCam");
+        if (!fEvtOut)
+            return kFALSE;
+    }
+
+    fFreq1 = (MHexagonFreqSpace*)plist->FindCreateObj("MHexagonFreqSpace","MHexagonFreqSpace1");
+    if (!fFreq1)
+        return kFALSE;
+    fFreq2 = (MHexagonFreqSpace*)plist->FindCreateObj("MHexagonFreqSpace","MHexagonFreqSpace2");
+    if (!fFreq2)
+        return kFALSE;
+
+    MGeomCam *geom = (MGeomCam*)plist->FindObject(fNameGeomCam, "MGeomCam");
+    if (!geom)
+    {
+        *fLog << err << fNameGeomCam << " [MGeomCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    // Number of Rings (r) ---> Number of Pixels (p)
+    // p = 3*r*(r-1)+1
+
+    // Number of Pixels (p) ---> Number of Rings (r)
+    // p = (sqrt(9+12*(p-1))+3)/6
+
+    // Number of pixels at one border == number of rings (r)
+    // Row of border                  == number of rings (r)
+
+    // Number of rows to get a triangle: 3r-2
+
+    // One additional line on all three sides, number of rows: 3r-2+3 = 3r+1
+    Int_t num = 0;
+    for (UInt_t i=0; i<geom->GetNumPixels(); i++)
+        if ((*geom)[i].GetAidx()==0)
+            num++;
+
+    cout << "Number of pixels with Area Idx==0: " << num << endl;
+
+    const Int_t numrows = (Int_t)((sqrt(9.+12.*(num-1))+3)/2+1); //61;//34;
+    fHFT.Prepare(numrows);
+
+    cout << "Number of rows: " << numrows << endl;
+
+    const Int_t lim = fHFT.GetNumKnots();
+
+    fOffset.Set(lim);
+    fOffset.Reset();
+
+    //fMap.Set(lim);
+    //for (int i=0; i<lim; i++)
+    //    fMap[i]=-1;
+
+    const Double_t dx = (*geom)[2].GetX(); // -(*geom)[0].GetX()
+    const Double_t dy = (*geom)[2].GetY(); // -(*geom)[0].GetY()
+
+    for (int i=0; i<lim; i++)
+    {
+        const Float_t x = dx*fHFT.GetCol(i);
+        const Float_t y = dy*Int_t(fHFT.GetRow(i)-2*fHFT.GetNumRows()/3);
+
+        const Int_t idx = geom->GetPixelIdxXY(x, y);
+        if (idx<0)
+            continue;
+
+        if ((*geom)[idx].GetAidx()==0)
+        {
+            //fMap[idx]  = i;
+            fOffset[i] = 1;
+        }
+    }
+
+    fFreq1->Set(MArrayD(lim), MArrayD(lim));
+    fFreq2->Set(MArrayD(lim), MArrayD(lim));
+
+    // Calculate fourier tranformation of a constant field for all
+    // 'valid' pixels
+    MArrayD freqre;
+    MArrayD freqim;
+    fHFT.TransformFastFWD(fOffset, freqre, freqim);
+    fOffset = freqre;
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Do cuts in frequence space (fOffset already sustracted), eg:
+// fMaxRowFraction = 0.5
+// fMaxAmplitude   = 0.3
+//
+//    0.1  0.2    0.1   0.3   0.4            0    0      0     0     0
+//       0.4   0.3   0.2   0.1                  0     0     0     0
+//          0.6   0.4   0.8      ----->           0.6    0    0.8
+//             0.4   0.9                              0    0.9
+//                 0                                     0
+//
+// The result (fOffset) is treated as a offset in the fourier space comming
+// from the fact that the camera doesn't extend the whole triangle.
+//
+// Before cutting in the fourier space it is substracted. After cutting it
+// is added again. Scaling is done by the constant-frequency-pixel (index 0)
+//
+void MHexagonalFTCalc::CleanFreqSpace(MArrayD &outre, MArrayD &outim)
+{
+    // Do cut in frequency space
+    for (unsigned int i=0; i<outre.GetSize(); i++)
+    {
+        if (fHFT.GetRow(i)>(Int_t)fHFT.GetNumRows()*fMaxRowFraction)
+            outre[i]=outim[i]=0;
+        if (TMath::Hypot(outre[i], outim[i])<fMaxAmplitude)
+            outre[i]=outim[i]=0;
+    }
+}
+
+// ---------------------------------------------------------------------------
+//
+// - Copy input MSignalCam using the pixel mapping into an array
+// - Do forward transformation
+// - substract fourier offset
+// - perform cuts in fourier space
+// - add fourier offset
+// - do backward tranformation
+// - copy result back into output MSignalCam
+//
+Int_t MHexagonalFTCalc::Process()
+{
+    const Int_t lim = fHFT.GetNumKnots();
+
+    MArrayD re(lim);
+
+    //    MSignalPix *pix=0;
+    //    MSignalCamIter Next(fEvtIn, kFALSE);
+    //    while ((pix = (MSignalPix*)Next()))
+    // Copy data from MSignalCam into array
+    const UInt_t npix = fEvtIn->GetNumPixels();
+    for (UInt_t idx=0; idx<npix; idx++)
+    {
+        //const Int_t idx = pix->GetPixId();
+        //if (fMap[idx]>=0)
+        re[idx] = (*fEvtIn)[idx].GetNumPhotons();
+    }
+
+    MArrayD freqre, freqim;
+
+    // Do forward transformation
+    fHFT.TransformFastFWD(re, freqre, freqim);
+
+    // Substract the 'structure of the hexagon'
+    Double_t scale = TMath::Abs(freqre[0]/fOffset[0]);
+    for (int i=0; i<lim; i++)
+        freqre[i] -= scale*fOffset[i];
+
+    // Put result in output container
+    fFreq2->Set(freqre, freqim);
+
+    // ----------------------------------------------------
+    // Do we need a backward transformation?
+    // ----------------------------------------------------
+    if (fSkipBwdTrafo)
+        return kTRUE;
+
+    // Clean image in frequency space
+    CleanFreqSpace(freqre, freqim);
+
+    // Add the 'structure of the hexagon'
+    for (int i=0; i<lim; i++)
+        freqre[i] += scale*fOffset[i];
+
+
+    MArrayD out;
+
+    // Do backward transformation
+    fHFT.TransformFastBWD(freqre, freqim, out);
+
+    // Write output into Mars container
+    fFreq1->Set(re, out);
+
+    // ----------------------------------------------------
+    // Do we have to copy the result back into MSignalCam?
+    // ----------------------------------------------------
+    if (!fEvtOut)
+        return kTRUE;
+
+    fEvtOut->InitSize(lim); // necessary?
+    for (int i=0; i<lim; i++)
+    {
+        //const Int_t map = fMap[i];
+        //if (map>=0)
+        fEvtOut->AddPixel(i, out[i]);
+    }
+    //fEvtOut->FixSize();
+    fEvtOut->SetReadyToSave();
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mhft/MHexagonalFTCalc.h
===================================================================
--- /tags/Mars-V0.9/mhft/MHexagonalFTCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mhft/MHexagonalFTCalc.h	(revision 9772)
@@ -0,0 +1,67 @@
+#ifndef MARS_MHexagonalFTCalc
+#define MARS_MHexagonalFTCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef MARS_MHexagonalFT
+#include "MHexagonalFT.h"
+#endif
+#ifndef MARS_MArrayD
+#include "MArrayD.h"
+#endif
+
+class MArrayD;
+class MSignalCam;
+class MHexagonFreqSpace;
+
+class MHexagonalFTCalc : public MTask
+{
+private:
+    static const char *fgNameGeomCam;       // Default name of used geometry
+    static const char *fgNameSignalCamIn;  // Default name of used input MSignalCam
+    static const char *fgNameSignalCamOut; // Default name of used output MSignalCam
+
+    TString fNameGeomCam;       // name of used geometry
+    TString fNameSignalCamIn;  // name of used input MSignalCam
+    TString fNameSignalCamOut; // name of used output MSignalCam
+
+    MSignalCam       *fEvtIn;  // input MSignalCam
+    MSignalCam       *fEvtOut; // output MSignalCam
+
+    MHexagonFreqSpace *fFreq1;  //!
+    MHexagonFreqSpace *fFreq2;  //!
+
+    Float_t fMaxAmplitude;      // Maximum amplitude to cut
+    Float_t fMaxRowFraction;    // Maximum fraction of rows (frequency space) to remove
+
+    Bool_t fSkipBwdTrafo;       // flag whether backward trafo should be done
+
+    MHexagonalFT       fHFT;    // Fourier transformation
+
+    MArrayI fMap;    //! Pixel mapping between space space and frequency space
+    MArrayD fOffset; //! Fourier transformation of a constant 1 for all 'valid' pixels
+
+    Int_t PreProcess(MParList *p);
+    Int_t Process();
+
+    void CleanFreqSpace(MArrayD &re, MArrayD &im);
+
+public:
+    MHexagonalFTCalc(const char *name=0, const char *title=0);
+
+    void SetSkipBwdTrafo(Bool_t b=kTRUE) { fSkipBwdTrafo=b; } // Don't do a backward transoformation
+
+    const MHexagonalFT &GetHFT() const { return fHFT; }       // return the MHexagonalFT object used
+
+    void SetNameGeomCam(const char *n) { fNameGeomCam = n; }       // name of camera geometry used 
+    void SetNameSignalCamIn(const char *n)     { fNameSignalCamIn = n; }  // name of input MSignalCam used
+    void SetNameSignalCamOut(const char *n="") { fNameSignalCamOut = n; } // name of ouput MSignalCam used
+
+    void SetMaxAmplitude(Float_t max) { fMaxAmplitude=max; } // amplitude to cut at
+    void SetMaxRowFraction(Float_t max) { fMaxRowFraction=max; } // row (frequency) to cut at
+
+    ClassDef(MHexagonalFTCalc,0)//Task to calculate Hexagonal Fourier Transformation
+};
+    
+#endif
Index: /tags/Mars-V0.9/mhft/Makefile
===================================================================
--- /tags/Mars-V0.9/mhft/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mhft/Makefile	(revision 9772)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Hft
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../msignal
+
+#manalysis: MChisqEval (MParameters)
+
+SRCFILES = MHexagonalFT.cc \
+           MHexagonalFTCalc.cc \
+   	   MHexagonFreqSpace.cc \
+           MGeomCamMagicXT.cc \
+           MGeomCamMagicEnhance.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mhist/HistIncl.h
===================================================================
--- /tags/Mars-V0.9/mhist/HistIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/HistIncl.h	(revision 9772)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mhist/HistLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mhist/HistLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/HistLinkDef.h	(revision 9772)
@@ -0,0 +1,23 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHFadcCam+;
+#pragma link C++ class MHFadcPix+;
+
+#pragma link C++ class MHEvent+;
+#pragma link C++ class MHCamEvent+;
+#pragma link C++ class MHTriggerLvl0+;
+
+#pragma link C++ class MHStarMap+;
+
+#pragma link C++ class MHCompProb+;
+#pragma link C++ class MHHadronness+;    
+
+#pragma link C++ class MHCamera+;
+
+#pragma link C++ class MHCamEventRot+;
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHAlphaEnergyTheta.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHAlphaEnergyTheta.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHAlphaEnergyTheta.cc	(revision 9772)
@@ -0,0 +1,173 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    1/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek 1/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHAlphaEnergyTheta                                                      //
+//                                                                          //
+//  3D-histogram in alpha, E-est and Theta                                  //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHAlphaEnergyTheta.h"
+
+#include <TCanvas.h>
+
+#include <math.h>
+
+#include "MMcEvt.hxx"
+#include "MHillasSrc.h"
+#include "MEnergyEst.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHAlphaEnergyTheta);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram. 
+//
+MHAlphaEnergyTheta::MHAlphaEnergyTheta(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHAlphaEnergyTheta";
+    fTitle = title ? title : "3-D histogram in alpha, energy and theta";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetTitle("3D-plot of alpha, E_{est}, Theta");
+    fHist.SetXTitle("\\alpha [\\circ]");
+    fHist.SetYTitle("E_{est} [GeV]");
+    fHist.SetZTitle("\\Theta [\\circ]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings and prepare filling of the histogram
+// 
+Bool_t MHAlphaEnergyTheta::SetupFill(const MParList *plist)
+{
+   fEnergy = (MEnergyEst*)plist->FindObject("MEnergyEst");
+   if (!fEnergy)
+   {
+       *fLog << err << dbginf << "MEnergyEst not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+   if (!fMcEvt)
+   {
+       *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   MBinning* binsenergy = (MBinning*)plist->FindObject("BinningE");
+   MBinning* binsalphaflux  = (MBinning*)plist->FindObject("BinningAlphaFlux");
+   MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta");
+   if (!binsenergy || !binsalphaflux || !binstheta)
+   {
+       *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+       return kFALSE;      
+   }
+
+   SetBinning(&fHist, binsalphaflux, binsenergy, binstheta);
+
+   fHist.Sumw2(); 
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+// 
+Bool_t MHAlphaEnergyTheta::Fill(const MParContainer *par, const Stat_t w)
+{
+    MHillasSrc &hil = *(MHillasSrc*)par;
+
+    fHist.Fill(hil.GetAlpha(), fEnergy->GetEnergy(),
+               fMcEvt->GetTelescopeTheta()*kRad2Deg, w);
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+// 
+void MHAlphaEnergyTheta::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2,2);
+
+    TH1 *h;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    h = fHist.Project3D("expro");
+    h->SetTitle("Distribution of \\alpha [\\circ]");
+    h->SetXTitle("\\alpha [\\circ]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    h = fHist.Project3D("eypro");
+    h->SetTitle("Distribution of E-est [GeV]");
+    h->SetXTitle("E_{est} [GeV]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = fHist.Project3D("ezpro");
+    h->SetTitle("Distribution of \\Theta [\\circ]");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fHist.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+}
Index: /tags/Mars-V0.9/mhist/MHAlphaEnergyTheta.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHAlphaEnergyTheta.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHAlphaEnergyTheta.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHAlphaEnergyTheta
+#define MARS_MHAlphaEnergyTheta
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+class MMcEvt;
+class MHillasSrc;
+class MEnergyEst;
+class MParList;
+
+class MHAlphaEnergyTheta : public MH
+{
+private:
+    MMcEvt     *fMcEvt;  //!
+    MHillasSrc *fHillas; //!
+    MEnergyEst *fEnergy; //!
+
+    TH3D fHist;
+
+public:
+    MHAlphaEnergyTheta(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TH3D *GetHist()       { return &fHist; }
+    const TH3D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHAlphaEnergyTheta, 0) //3D-histogram in alpha, Energy and theta
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHAlphaEnergyTime.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHAlphaEnergyTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHAlphaEnergyTime.cc	(revision 9772)
@@ -0,0 +1,279 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    1/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek 1/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHAlphaEnergyTime                                                       //
+//                                                                          //
+//  3D-histogram in alpha, E-est and time                                   //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHAlphaEnergyTime.h"
+
+#include <TCanvas.h>
+
+#include <math.h>
+
+#include "MHillasSrc.h"
+#include "MEnergyEst.h"
+#include "MTime.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHAlphaEnergyTime);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram. 
+//
+MHAlphaEnergyTime::MHAlphaEnergyTime(const char *name, const char *title) 
+  : fHist()
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHAlphaEnergyTime";
+    fTitle = title ? title : "3-D histogram in alpha, energy and time";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetTitle("3D-plot of alpha, E-est, time");
+    fHist.SetXTitle("\\alpha [\\circ]");
+    fHist.SetYTitle("E-est [GeV]            ");
+    fHist.SetZTitle("time [s]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings and prepare filling of the histogram
+// 
+Bool_t MHAlphaEnergyTime::SetupFill(const MParList *plist)
+{
+   fEnergy = (MEnergyEst*)plist->FindObject("MEnergyEst");
+   if (!fEnergy)
+   {
+       *fLog << err << dbginf << "MHAlphaEnergyTime : MEnergyEst not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   fTime = (MTime*)plist->FindObject("MTime");
+   if (!fTime)
+   {
+       *fLog << err << dbginf << "MHAlphaEnergyTime : MTime not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   MBinning* binsenergy = (MBinning*)plist->FindObject("BinningE");
+   MBinning* binsalphaflux  = (MBinning*)plist->FindObject("BinningAlphaFlux");
+   MBinning* binstime   = (MBinning*)plist->FindObject("BinningTime");
+   if (!binsenergy || !binsalphaflux || !binstime)
+   {
+       *fLog << err << dbginf << "MHAlphaEnergyTime : At least one MBinning not found... aborting." << endl;
+       return kFALSE;      
+   }
+
+   SetBinning(&fHist, binsalphaflux, binsenergy, binstime);
+
+   fHist.Sumw2();
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+// 
+Bool_t MHAlphaEnergyTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    MHillasSrc &hil = *(MHillasSrc*)par;
+
+    fHist.Fill(fabs(hil.GetAlpha()), fEnergy->GetEnergy(), *fTime, w);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+// 
+void MHAlphaEnergyTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(2,2);
+
+    TH1 *h;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    h = fHist.Project3D("ex");
+    h->SetTitle("Distribution of \\alpha [\\circ]");
+    h->SetXTitle("\\alpha [\\circ]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    h = fHist.Project3D("ey");
+    h->SetTitle("Distribution of E-est [GeV]");
+    h->SetXTitle("E-est [GeV]            ");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = fHist.Project3D("ez");
+    h->SetTitle("Distribution of time [s]");
+    h->SetXTitle("time [s]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fHist.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Integrate fHist     (Alpha,E-est,Time) over the Time to get
+//           fAlphaEest(Alpha,E-est)
+// 
+TH2D *MHAlphaEnergyTime::IntegrateTime(const char *title, Bool_t draw)
+{
+    Int_t nzbins = fHist.GetNbinsZ();
+    TAxis &axez  = *fHist.GetZaxis();
+    axez.SetRange(1,nzbins);
+
+    TH2D &fAlphaEest = *(TH2D *)fHist.Project3D("exy");
+
+    fAlphaEest.SetTitle(title);
+    fAlphaEest.SetXTitle("E-est [GeV]            ");
+    fAlphaEest.SetYTitle("\\alpha  [  \\circ]");
+
+    if (draw == kTRUE)
+    {
+      TCanvas &c = *MakeDefCanvas(title, title);
+
+      gROOT->SetSelectedPad(NULL);
+
+      fAlphaEest.DrawCopy();
+      gPad->SetLogx();
+
+      c.Modified();
+      c.Update();
+    }
+
+    return &fAlphaEest;
+}
+
+// --------------------------------------------------------------------------
+//
+// Integrate fHist     (Alpha,E-est,Time) over E-est to get
+//           fAlphaTime(Alpha,Time)
+// 
+TH2D *MHAlphaEnergyTime::IntegrateEest(const char *title, Bool_t draw)
+{
+    Int_t nybins = fHist.GetNbinsY();
+    TAxis &axey  = *fHist.GetYaxis();
+    axey.SetRange(1,nybins);
+
+    TH2D &fAlphaTime = *(TH2D *)fHist.Project3D("exz");
+
+    fAlphaTime.SetTitle(title);
+    fAlphaTime.SetXTitle("Time [s]");
+    fAlphaTime.SetYTitle("\\alpha  [  \\circ]");
+
+    if (draw == kTRUE)
+    {
+      TCanvas &c = *MakeDefCanvas(title, title);
+
+      gROOT->SetSelectedPad(NULL);
+
+      fAlphaTime.DrawCopy();
+
+      c.Modified();
+      c.Update();
+    }
+
+    return &fAlphaTime;
+}
+
+// --------------------------------------------------------------------------
+//
+// Integrate fHist (Alpha,E-est,Time) over Eest and Time to get
+//           fAlpha(Alpha)
+// 
+TH1D *MHAlphaEnergyTime::IntegrateEestTime(const char *title, Bool_t draw)
+{
+    Int_t nybins = fHist.GetNbinsY();
+    TAxis &axey  = *fHist.GetYaxis();
+    axey.SetRange(1,nybins);
+
+    Int_t nzbins = fHist.GetNbinsZ();
+    TAxis &axez  = *fHist.GetZaxis();
+    axez.SetRange(1,nzbins);
+
+    TH1D &fAlpha = *(TH1D *)fHist.Project3D("ex");
+
+    fAlpha.SetTitle(title);
+    fAlpha.SetXTitle("\\alpha  [  \\circ]");
+    fAlpha.SetYTitle("Counts");
+
+    if (draw == kTRUE)
+    {
+      TCanvas &c = *MakeDefCanvas(title, title);
+
+      gROOT->SetSelectedPad(NULL);
+
+      fAlpha.DrawCopy();
+
+      c.Modified();
+      c.Update();
+    }
+
+    return &fAlpha;
+}
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHAlphaEnergyTime.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHAlphaEnergyTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHAlphaEnergyTime.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MHAlphaEnergyTime
+#define MARS_MHAlphaEnergyTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include "TH3.h"
+#endif
+
+#ifndef ROOT_TH2
+#include "TH2.h"
+#endif
+
+class MHillasSrc;
+class MEnergyEst;
+class MTime;
+class TH2D;
+class MParList;
+
+class MHAlphaEnergyTime : public MH
+{
+private:
+    MHillasSrc *fHillas; //!
+    MEnergyEst *fEnergy; //!
+    MTime      *fTime;   //!
+
+    TH3D    fHist;
+
+public:
+    MHAlphaEnergyTime(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TH3D *GetHist()       { return &fHist; }
+    const TH3D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t *option="");
+
+    TH2D *IntegrateTime    (const char *title, Bool_t Draw);
+    TH2D *IntegrateEest    (const char *title, Bool_t Draw);
+    TH1D *IntegrateEestTime(const char *title, Bool_t Draw);
+   
+    ClassDef(MHAlphaEnergyTime, 0) //3D-histogram in alpha, Energy and time
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHCT1Supercuts.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHCT1Supercuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCT1Supercuts.cc	(revision 9772)
@@ -0,0 +1,225 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHCT1Supercuts
+//
+// This class contains histograms for the supercuts
+//
+// the histograms are filled during the optimization of the supercuts
+//
+///////////////////////////////////////////////////////////////////////
+#include "MHCT1Supercuts.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MParList.h"
+#include "MHFindSignificance.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCT1Supercuts);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Alpha, and Dist
+//
+MHCT1Supercuts::MHCT1Supercuts(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHCT1Supercuts";
+    fTitle = title ? title : "Container for histograms for the supercuts";
+
+
+    fDegree = new TH1F("Degree", "Degree of polynomial",   5, -0.5,  4.5);
+    fProb   = new TH1F("Prob",   "chi2 probability",      40,    0,  1.0);
+    fNdf    = new TH1F("NDF",    "NDF of polynomial fit", 60, -0.5, 59.5);
+    fGamma  = new TH1F("gamma",  "gamma",                 40,  0.0,  8.0);
+    fNexNon = new TH1F("NexNon", "Nex / Non",             50,  0.0,  1.0);
+    fSigLiMa= new TH1F("Significance", "significance of gamma signal",   
+                                                          60,  0.0, 120.0);
+    fSigtoBackg= new TH2F("SigtoBackg", "Significance vs signal/backg ratio",
+                          50,  0.0,  10.0, 60, 0.0, 120.0);
+    fSigDegree = new TH2F("SigDegree", "Significance vs Degree of polynomial",
+                           5, -0.5,   4.5, 60, 0.0, 120.0);
+    fSigNbins  = new TH2F("SigNbins", "Significance vs number of bins",
+                           40, -0.5, 79.5, 60, 0.0, 120.0);
+
+    fDegree->SetDirectory(NULL);
+    fProb->SetDirectory(NULL);
+    fNdf->SetDirectory(NULL);
+    fGamma->SetDirectory(NULL);
+    fNexNon->SetDirectory(NULL);
+    fSigLiMa->SetDirectory(NULL);
+    fSigtoBackg->SetDirectory(NULL);
+    fSigDegree->SetDirectory(NULL);
+    fSigNbins->SetDirectory(NULL);
+
+    fDegree->SetXTitle("order of polynomial");
+    fProb->SetXTitle("chi2 probability of polynomial fit");
+    fNdf->SetXTitle("NDF of polynomial fit");
+    fGamma->SetXTitle("gamma");
+    fNexNon->SetXTitle("Nex / Non");
+    fSigLiMa->SetXTitle("significance");
+
+    fSigtoBackg->SetXTitle("signa./background ratio");
+    fSigtoBackg->SetYTitle("significance");
+
+    fSigDegree->SetXTitle("order of polynomial");
+    fSigDegree->SetYTitle("significance");
+
+    fSigNbins->SetXTitle("number of bins");
+    fSigNbins->SetYTitle("significance");
+
+    fDegree->SetYTitle("Counts");
+    fProb->SetYTitle("Counts");
+    fNdf->SetYTitle("Counts");
+    fGamma->SetYTitle("Counts");
+    fNexNon->SetYTitle("Counts");
+    fSigLiMa->SetYTitle("Counts");
+
+    fSigtoBackg->SetZTitle("Counts");
+    fSigDegree->SetZTitle("Counts");
+    fSigNbins->SetZTitle("Counts");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms
+//
+MHCT1Supercuts::~MHCT1Supercuts()
+{
+    delete fDegree;
+    delete fProb;
+    delete fNdf;
+    delete fGamma;
+    delete fNexNon;
+    delete fSigLiMa;
+
+    delete fSigtoBackg;
+    delete fSigDegree;
+    delete fSigNbins;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms from the 'MHFindSignificance' container
+//
+Bool_t MHCT1Supercuts::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MHCT1Supercuts::Fill: Pointer (!=NULL) expected." << endl;
+        return kFALSE;
+    }
+
+    MHFindSignificance &h = *(MHFindSignificance*)par;
+
+    fDegree    ->Fill(h.GetDegree( ), w);
+    fProb      ->Fill(h.GetProb(),    w);
+    fNdf       ->Fill(h.GetNdf(),     w);
+    fGamma     ->Fill(h.GetGamma(),   w);
+
+    Double_t ratio = h.GetNon()>0.0 ? h.GetNex()/h.GetNon() : 0.0;
+    fNexNon    ->Fill(ratio,          w);
+
+    fSigLiMa   ->Fill(h.GetSigLiMa(), w);
+
+    Double_t sigtobackg = h.GetNbg()!=0.0 ? h.GetNex() / h.GetNbg() : 0.0;
+    fSigtoBackg->Fill(sigtobackg,    h.GetSigLiMa(), w);
+
+    fSigDegree ->Fill(h.GetDegree(), h.GetSigLiMa(), w);
+    fSigNbins  ->Fill(h.GetMbins(),  h.GetSigLiMa(), w);
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the two histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHCT1Supercuts::Draw(Option_t *)
+{
+  //TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+  //pad->SetBorderMode(0);
+  //AppendPad("");
+
+    TCanvas *pad = new TCanvas("Supercuts", "Supercut plots", 900, 900);
+    gROOT->SetSelectedPad(NULL);
+
+    pad->Divide(3, 3);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fDegree->Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fProb->Draw();
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fNdf->Draw();
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fGamma->Draw();
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    fNexNon->Draw();
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    fSigLiMa->Draw();
+
+    pad->cd(7);
+    gPad->SetBorderMode(0);
+    fSigtoBackg->Draw();
+
+    pad->cd(8);
+    gPad->SetBorderMode(0);
+    fSigDegree->Draw();
+
+    pad->cd(9);
+    gPad->SetBorderMode(0);
+    fSigNbins->Draw();
+
+    pad->Modified();
+    pad->Update();
+}
Index: /tags/Mars-V0.9/mhist/MHCT1Supercuts.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHCT1Supercuts.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCT1Supercuts.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHCT1Supercuts
+#define MARS_MHCT1Supercuts
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1F;
+class TH2F;
+
+class MHCT1Supercuts : public MH
+{
+private:
+    TH1F *fDegree;     // order of polynomial for background fit
+    TH1F *fProb;       // chi2 probability of polynomial fit
+    TH1F *fNdf;        // NDF of polynomial fit
+    TH1F *fGamma;      // Nbg = gamma * Noff
+    TH1F *fNexNon;     // no.of excess events / no.of events in signal region 
+    TH1F *fSigLiMa;    // significance of gamma signal
+
+    TH2F *fSigtoBackg; // significance vs signal to background ratio (Nex/Nbg)
+    TH2F *fSigDegree;  // significance vs order of polynomial
+    TH2F *fSigNbins;   // significance vs number of bins
+
+
+public:
+    MHCT1Supercuts(const char *name=NULL, const char *title=NULL);
+    ~MHCT1Supercuts();
+
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    void Draw(Option_t *opt=NULL);
+
+    ClassDef(MHCT1Supercuts, 1) // Container which holds histograms for the supercuts
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHCamEvent.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHCamEvent.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCamEvent.cc	(revision 9772)
@@ -0,0 +1,315 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHCamEvent
+//
+// A histogram to store the sum of camera events. This can be photons,
+// currents or enything else derived from MCamEvent
+//
+// Setup
+// =====
+//
+// To count how often a certain pixel is above or below a threshold do:
+//    MHCamEvent::SetThreshold(5.5);  // Default=LowerBound
+//    MHCamEvent::SetThreshold(5.5, MHCamEvent::kIsUpperBound);
+//
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given 'a.u.' is used.
+// 2) If the title of MHCamEvent is different from the default,
+//    it is used as histogram title. You can use this to set the
+//    axis title, too. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyHist;;y[cm];Counts");
+//    Make sure to set an empty x-axis title.
+//
+// For example:
+//   MHCamEvent myhist("Titele;;y [cm]");
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCamEvent.h"
+
+#include <TCanvas.h>
+#include <TPaveStats.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MHCamEvent);
+
+using namespace std;
+
+const TString MHCamEvent::gsDefName  = "MHCamEvent";
+const TString MHCamEvent::gsDefTitle = "Average of MCamEvents";
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task
+//
+void MHCamEvent::Init(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fNameGeom = "MGeomCam";
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task. Set fType to 0
+//
+MHCamEvent::MHCamEvent(const char *name, const char *title)
+    : fSum(NULL), fEvt(NULL), fType(0), fThreshold(0), fUseThreshold(0)
+{
+    Init(name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task. Set fType to type
+//
+MHCamEvent::MHCamEvent(Int_t type, const char *name, const char *title)
+    : fSum(NULL), fEvt(NULL), fType(type), fThreshold(0), fUseThreshold(0)
+{
+    Init(name, title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHCamEvent::~MHCamEvent()
+{
+    if (fSum)
+        delete fSum;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MCamEvent) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+//
+Bool_t MHCamEvent::SetupFill(const MParList *plist)
+{
+    fEvt = (MCamEvent*)plist->FindObject(fNameEvt, "MCamEvent");
+    if (!fEvt)
+    {
+        if (!fNameEvt.IsNull())
+        {
+            *fLog << err << GetDescriptor() << ": No " << fNameEvt <<" [MCamEvent] available..." << endl;
+            return kFALSE;
+        }
+        *fLog << inf << GetDescriptor() << ": Assuming to get MCamEvent from Fill()..." << endl;
+    }
+
+    MGeomCam *cam = (MGeomCam*)plist->FindObject(fNameGeom, "MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << fNameGeom << " [MGeomCam] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    // Delete a possible old histogram from a previous loop
+    if (fSum)
+        delete (fSum);
+
+    // combine name
+    const TString name = fNameEvt.IsNull() ? fName : fNameEvt;
+
+    // create and setup MHCamera
+    fSum = new MHCamera(*cam, name+";avg");
+    if (fTitle!=gsDefTitle)
+        fSum->SetTitle(fTitle);
+    if (!fTitle.Contains(";"))
+        fSum->SetYTitle("a.u.");
+    fSum->SetBit(MHCamera::kProfile);
+
+    fSum->SetXTitle("Pixel Idx");
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCamEvent-Container.
+//
+Bool_t MHCamEvent::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MCamEvent *evt = par ? dynamic_cast<const MCamEvent*>(par) : fEvt;
+    if (!evt)
+    {
+        *fLog << err << dbginf << "Got no MCamEvent as argument of Fill()..." << endl;
+        return kFALSE;
+    }
+    if (fUseThreshold)
+        fSum->CntCamContent(*evt, fThreshold, fType, fUseThreshold>0);
+    else
+        fSum->AddCamContent(*evt, fType);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Take the mean of the sum histogram and print all pixel indices
+// which are above sum+s*rms
+//
+void MHCamEvent::PrintOutliers(Float_t s) const
+{
+    const Double_t mean = fSum->GetMean();
+    const Double_t rms  = fSum->GetRMS();
+
+    *fLog << all << underline << GetDescriptor() << ": Mean=" << mean << ", Rms=" << rms << endl;
+
+    for (UInt_t i=0; i<fSum->GetNumPixels(); i++)
+    {
+        if (!fSum->IsUsed(i))
+            continue;
+
+        if ((*fSum)[i+1]>mean+s*rms)
+            *fLog << "Contents of Pixel-Index #" << i << ": " << (*fSum)[i+1] << " > " << s << "*rms" << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fSum for "sum" and fRms for "rms"
+//
+TH1 *MHCamEvent::GetHistByName(const TString name)
+{
+    return fSum;
+}
+
+void MHCamEvent::Paint(Option_t *)
+{
+    TVirtualPad *pad = gPad;
+
+    pad->cd(2);
+    if (gPad->FindObject(Form("%s;proj", fName.Data())))
+    {
+        TH1 *h=fSum->Projection(Form("%s;proj", fName.Data()));
+        if (h->GetMaximum()>0)
+            gPad->SetLogy();
+    }
+
+    pad->cd(5);
+    if (gPad->FindObject(Form("%s;rad", fName.Data())))
+        fSum->RadialProfile(Form("%s;rad", fName.Data()));
+
+    pad->cd(6);
+    if (gPad->FindObject(Form("%s;az", fName.Data())))
+        fSum->AzimuthProfile(Form("%s;az", fName.Data()));
+
+    pad->cd(4);
+    gPad->cd(1);
+    MHCamera *cam = (MHCamera*)gPad->FindObject(Form("%s;err", fName.Data()));
+    if (cam)
+        cam->SetCamContent(*fSum, 1);
+}
+
+void MHCamEvent::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    const Int_t col = pad->GetFillColor();
+    pad->SetBorderMode(0);
+
+    AppendPad();
+
+    TString name = Form("%s_1", pad->GetName());
+    TPad *p = new TPad(name,name,0.005, 0.5, 0.66, 0.995,col,0,0);
+    p->SetNumber(1);
+    p->Draw();
+    p->cd();
+    fSum->Draw("EPhist");
+
+    pad->cd();
+    name = Form("%s_2", pad->GetName());
+    p = new TPad(name,name,0.66, 0.5, 0.995, 0.995,col,0,0);
+    p->SetNumber(2);
+    p->Draw();
+    p->cd();
+    TH1 *h = fSum->Projection(Form("%s;proj", fName.Data()), 50);
+    h->SetTitle("Projection");
+    h->SetBit(kCanDelete);
+    h->Draw();
+
+    pad->cd();
+    name = Form("%s_3", pad->GetName());
+    p = new TPad(name,name,0.005, 0.005, 3./8, 0.5,col,0,0);
+    p->SetNumber(3);
+    p->Draw();
+    p->cd();
+    fSum->Draw();
+
+    pad->cd();
+    name = Form("%s_4", pad->GetName());
+    p = new TPad(name,name,3./8, 0.005, 6./8-0.005, 0.5,col,0,0);
+    p->SetNumber(4);
+    p->Draw();
+    p->cd();
+
+    MHCamera *cam = new MHCamera(*fSum->GetGeometry());
+    cam->SetName(Form("%s;err", fName.Data()));
+    cam->SetTitle("Sqrt(Variance)");
+    cam->SetYTitle(fSum->GetYaxis()->GetTitle());
+    cam->SetCamContent(*fSum, 1);
+    cam->SetBit(kCanDelete);
+    cam->Draw();
+
+    pad->cd();
+    name = Form("%s_5", pad->GetName());
+    p = new TPad(name,name,6./8,0.25,0.995,0.5,col,0,0);
+    p->SetNumber(5);
+    p->Draw();
+    p->cd();
+    h = (TH1*)fSum->RadialProfile(Form("%s;rad", fName.Data()), 20);
+    h->SetTitle("Radial Profile");
+    h->SetBit(kCanDelete|TH1::kNoStats);
+    h->Draw();
+
+    pad->cd();
+    name = Form("%s_6", pad->GetName());
+    p = new TPad(name,name,6./8,0.005,0.995,0.25,col,0,0);
+    p->SetNumber(6);
+    p->Draw();
+    p->cd();
+    h = (TH1*)fSum->AzimuthProfile(Form("%s;az", fName.Data()), 30);
+    h->SetTitle("Azimuth Profile");
+    h->SetBit(kCanDelete|TH1::kNoStats);
+    h->Draw();
+}
+
Index: /tags/Mars-V0.9/mhist/MHCamEvent.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHCamEvent.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCamEvent.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MHCamEvent
+#define MARS_MHCamEvent
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MHCamera;
+class MCamEvent;
+
+class MHCamEvent : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+protected:
+    MHCamera  *fSum;       // storing the sum
+    MCamEvent *fEvt;       //! the current event
+
+    TString fNameEvt;      // Name of MCamEvent to fill into histogram
+    TString fNameGeom;     // Name of geometry container
+
+    Int_t fType;           // Type to used for calling GetPixelContent
+
+    Float_t fThreshold;    // Count pixel above/below this threshold
+    Char_t fUseThreshold;  // Use a threshold? Which direction has it?
+
+    void Init(const char *name, const char *title);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+public:
+    enum { kIsLowerBound=1, kIsUpperBound=-1, kNoBound=0 };
+
+    MHCamEvent(const char *name=NULL, const char *title=NULL);
+    MHCamEvent(Int_t type, const char *name=NULL, const char *title=NULL);
+    ~MHCamEvent();
+
+    void SetNameEvt(const TString name)  { fNameEvt = name; }
+    void SetNameGeom(const TString name) { fNameGeom = name; }
+    void SetType(Int_t type) { fType = type; }
+
+    TH1 *GetHistByName(const TString name="");
+
+    void Paint(Option_t *o="");
+    void Draw(Option_t *o="");
+
+    void PrintOutliers(Float_t s) const;
+
+    void SetThreshold(Float_t f, Char_t direction=kIsLowerBound) { fThreshold = f; fUseThreshold=direction; }
+
+    ClassDef(MHCamEvent, 1) // Histogram to sum camera events
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHCamEventRot.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHCamEventRot.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCamEventRot.cc	(revision 9772)
@@ -0,0 +1,278 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHCamEventRot
+//
+// Derotate MCamEvent before filling a 2D histogram.
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given 'a.u.' or 'counts'is used.
+// 2) If the corresponding MBinning has no default title. This title
+//    is used for the z-axis
+// 3) If the title of MHCamEvent is different from the default,
+//    it is used as histogram title. You can use this to set the
+//    axis title, too. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyHist;;;z[photons]");
+//    The x- and y-axis title is ignored.
+//
+// For example:
+//   MHCamEventRot myhist("Title;;;z[photons]");
+//
+//
+// To be done: * Set the sky position of the center of the display and
+//               correct if the pointing position of the telescope is
+//               different.
+//             * Make it quadratic like MHCamera
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCamEventRot.h"
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TPaveText.h>
+#include <TStopwatch.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHillasSrc.h"
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MAstroCatalog.h"
+#include "MAstroSky2Local.h"
+#include "MStatusDisplay.h"
+#include "MMath.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+#include "MCamEvent.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHCamEventRot);
+
+using namespace std;
+
+const TString MHCamEventRot::gsDefName  = "MHCamEventRot";
+const TString MHCamEventRot::gsDefTitle = "Plot showing derotated MCamEvent data";
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHCamEventRot::MHCamEventRot(const char *name, const char *title)
+    : fTime(0), fPointPos(0), fObservatory(0), fType(0), fNameTime("MTime"),
+    fThreshold(0), fUseThreshold(kNoBound)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetName("Derot");
+    fHist.SetTitle("2D-plot of MCamEvents (derotated)");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings (takes BinningCamEvent) and prepare filling of the
+// histogram.
+//
+// Also search for MTime, MObservatory and MPointingPos
+// 
+Bool_t MHCamEventRot::SetupFill(const MParList *plist)
+{
+    fGeom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningCamEvent");
+    if (!bins)
+    {
+        const Float_t r = fGeom->GetMaxRadius()*fGeom->GetConvMm2Deg();
+
+        MBinning b;
+        b.SetEdges(41, -r, r);
+        SetBinning(&fHist, &b, &b);
+    }
+    else
+        SetBinning(&fHist, bins, bins);
+
+    fPointPos = (MPointingPos*)plist->FindObject(AddSerialNumber("MPointingPos"));
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... no derotation." << endl;
+
+    fTime = (MTime*)plist->FindObject(AddSerialNumber(fNameTime));
+    if (!fTime)
+        *fLog << warn << "MTime not found... no derotation." << endl;
+
+    fObservatory = (MObservatory*)plist->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+        *fLog << warn << "MObservatory not found... no derotation." << endl;
+
+    // FIXME: Because the pointing position could change we must check
+    // for the current pointing position and add a offset in the
+    // Fill function!
+    if (fPointPos)
+    {
+        fRa  = fPointPos->GetRa();
+        fDec = fPointPos->GetDec();
+    }
+
+    if (bins && bins->HasTitle())
+        fHist.SetZTitle(bins->GetTitle());
+    else
+        if (fTitle!=gsDefTitle)
+        {
+            fHist.SetTitle(fTitle);
+            fHist.SetXTitle("x [\\circ]");
+            fHist.SetYTitle("y [\\circ]");
+        }
+        else
+            if (!fTitle.Contains(";"))
+                fHist.SetZTitle(fUseThreshold==kNoBound?"a.u.":"Counts");
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Bool_t MHCamEventRot::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MCamEvent *evt = dynamic_cast<const MCamEvent*>(par);
+    if (!evt)
+    {
+        *fLog << err << "MHCamEventRot::Fill: No container specified!" << endl;
+        return kFALSE;
+    }
+
+    // Get max radius...
+    // const Double_t maxr = fGeom->GetMaxRadius()*fGeom->GetConvMm2Deg();
+
+    // Get camera rotation angle
+    Double_t rho = 0;
+    if (fTime && fObservatory && fPointPos)
+        rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+    //if (fPointPos)
+    //    rho = fPointPos->RotationAngle(*fObservatory);
+
+    // Get number of bins and bin-centers
+    const Int_t nx = fHist.GetNbinsX();
+    const Int_t ny = fHist.GetNbinsY();
+    Axis_t cx[nx];
+    Axis_t cy[ny];
+    fHist.GetXaxis()->GetCenter(cx);
+    fHist.GetYaxis()->GetCenter(cy);
+
+    for (int ix=0; ix<nx; ix++)
+    {
+        for (int iy=0; iy<ny; iy++)
+        {
+            // check distance... to get a circle plot
+            //if (TMath::Hypot(cx[ix], cy[iy])>maxr)
+            //    continue;
+
+            // rotate center of bin
+            TVector2 v(cx[ix], cy[iy]);
+            if (rho!=0)
+                v=v.Rotate(rho);
+
+            // FIXME: slow! Create Lookup table instead!
+            const Int_t idx = fGeom->GetPixelIdxDeg(v);
+
+            Double_t val;
+            if (idx<0 || !evt->GetPixelContent(val, idx, *fGeom, fType))
+                continue;
+
+            // Fill histogram
+            if (fUseThreshold!=kNoBound)
+            {
+                if (val>fThreshold && fUseThreshold==kIsLowerBound ||
+                    val<fThreshold && fUseThreshold==kIsUpperBound)
+                    fHist.Fill(cx[ix], cy[iy]);
+            }
+            else
+                fHist.Fill(cx[ix], cy[iy], val);
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the MAstroCatalog corresponding to fRa, fDec. The limiting magnitude
+// is set to 9, while the fov is equal to the current fov of the false
+// source plot.
+//
+TObject *MHCamEventRot::GetCatalog()
+{
+    const Double_t maxr = 0.98*TMath::Abs(fHist.GetBinCenter(1));
+
+    // Create catalog...
+    MAstroCatalog stars;
+    stars.SetLimMag(9);
+    stars.SetGuiActive(kFALSE);
+    stars.SetRadiusFOV(maxr);
+    stars.SetRaDec(fRa*TMath::DegToRad()*15, fDec*TMath::DegToRad());
+    stars.ReadBSC("bsc5.dat");
+
+    TObject *o = (MAstroCatalog*)stars.Clone();
+    o->SetBit(kCanDelete);
+
+    return o;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHCamEventRot::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    // draw the 2D histogram Sigmabar versus Theta
+    fHist.Draw(opt);
+    TObject *catalog = GetCatalog();
+    catalog->Draw("mirror same");
+}
Index: /tags/Mars-V0.9/mhist/MHCamEventRot.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHCamEventRot.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCamEventRot.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MHCamEventRot
+#define MARS_MHCamEventRot
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class TH2D;
+
+class MGeomCam;
+class MParList;
+class MTime;
+class MPointingPos;
+class MObservatory;
+
+class MHCamEventRot : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    MGeomCam      *fGeom;        //! container storing the camera geometry
+    MTime         *fTime;        //! container to take the event time from
+    MPointingPos  *fPointPos;    //! container to take pointing position from
+    MObservatory  *fObservatory; //! conteiner to take observatory location from
+
+    TH2D    fHist;               // Alpha vs. x and y
+
+    Int_t fType;                 // Type to used for calling GetPixelContent
+
+    Double_t fRa;
+    Double_t fDec;
+
+    TString fNameTime;
+
+    Float_t fThreshold;          // Count pixel above/below this threshold
+    Char_t fUseThreshold;        // Use a threshold? Which direction has it?
+
+    TObject *GetCatalog();
+
+public:
+    enum { kIsLowerBound=1, kIsUpperBound=-1, kNoBound=0 };
+
+    MHCamEventRot(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void SetNameTime(const char *name) { fNameTime=name; }
+
+    void Draw(Option_t *option="");
+
+    void SetThreshold(Float_t f, Char_t direction=kIsLowerBound) { fThreshold = f; fUseThreshold=direction; }
+
+    ClassDef(MHCamEventRot, 1) //2D-histogram in MCamEvent data (derotated)
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHCamera.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHCamera.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCamera.cc	(revision 9772)
@@ -0,0 +1,2196 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 05/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer, 1/2001
+!   Author(s): Markus Gaug, 03/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHCamera
+//
+// Camera Display, based on a TH1D. Pleas be carefull using the
+// underlaying TH1D.
+//
+// To change the scale to a logarithmic scale SetLogy() of the Pad.
+//
+// You can correct for the abberation. Assuming that the distance
+// between the mean position of the light distribution and the position
+// of a perfect reflection on a perfect mirror in the distance r on
+// the camera plane is dr it is  d = a*dr  while a is the abberation
+// constant (for the MAGIC mirror it is roughly 0.0713). You can
+// set this constant by calling SetAbberation(a) which results in a
+// 'corrected' display (all outer pixels are shifted towards the center
+// of the camera to correct for this abberation)
+//
+// Be carefull: Entries in this context means Entries/bin or Events
+//
+// FIXME? Maybe MHCamera can take the fLog object from MGeomCam?
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHCamera.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TBox.h>
+#include <TArrow.h>
+#include <TLatex.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TArrayF.h>
+#include <TRandom.h>
+#include <TPaveText.h>
+#include <TPaveStats.h>
+#include <TClonesArray.h>
+#include <THistPainter.h>
+#include <THLimitsFinder.h>
+#include <TProfile.h>
+#include <TH1.h>
+#include <TF1.h>
+#include <TCanvas.h>
+#include <TLegend.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MH.h"
+#include "MBinning.h"
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCamEvent.h"
+
+#include "MArrayD.h"
+
+#define kItemsLegend 48 // see SetPalette(1,0)
+
+ClassImp(MHCamera);
+
+using namespace std;
+
+void MHCamera::Init()
+{
+    UseCurrentStyle();
+
+    SetDirectory(NULL);
+
+    SetLineColor(kGreen);
+    SetMarkerStyle(kFullDotMedium);
+    SetXTitle("Pixel Index");
+
+    fNotify  = new TList;
+    fNotify->SetBit(kMustCleanup);
+    gROOT->GetListOfCleanups()->Add(fNotify);
+
+    TVirtualPad *save = gPad;
+    gPad = 0;
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,01,06)
+    SetPalette(1, 0);
+#else
+    SetInvDeepBlueSeaPalette();
+#endif
+    gPad = save;
+}
+
+// ------------------------------------------------------------------------
+//
+//  Default Constructor. To be used by the root system ONLY.
+//
+MHCamera::MHCamera() : TH1D(), fGeomCam(NULL), fColors(kItemsLegend), fAbberation(0)
+{
+    Init();
+}
+
+// ------------------------------------------------------------------------
+//
+//  Constructor. Makes a clone of MGeomCam. Removed the TH1D from the
+// current directory. Calls Sumw2(). Set the histogram line color
+// (for error bars) to Green and the marker style to kFullDotMedium.
+//
+MHCamera::MHCamera(const MGeomCam &geom, const char *name, const char *title)
+: fGeomCam(NULL), fColors(kItemsLegend), fAbberation(0)
+{
+    //fGeomCam = (MGeomCam*)geom.Clone();
+    SetGeometry(geom, name, title);
+    Init();
+
+    //
+    // root 3.02
+    //  * base/inc/TObject.h:
+    //    register BIT(8) as kNoContextMenu. If an object has this bit set it will
+    //    not get an automatic context menu when clicked with the right mouse button.
+}
+
+void MHCamera::SetGeometry(const MGeomCam &geom, const char *name, const char *title)
+{
+    SetNameTitle(name, title);
+
+    TAxis &x = *GetXaxis();
+
+    SetBins(geom.GetNumPixels(), 0, 1);
+    x.Set(geom.GetNumPixels(), -0.5, geom.GetNumPixels()-0.5);
+
+    //SetBins(geom.GetNumPixels(), -0.5, geom.GetNumPixels()-0.5);
+    //Rebuild();
+
+    Sumw2(); // necessary?
+
+    if (fGeomCam)
+        delete fGeomCam;
+    fGeomCam = (MGeomCam*)geom.Clone();
+
+    fUsed.Set(geom.GetNumPixels());
+    for (Int_t i=0; i<fNcells-2; i++)
+        ResetUsed(i);
+
+    fBinEntries.Set(geom.GetNumPixels()+2);
+    fBinEntries.Reset();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes the cloned fGeomCam and the notification list.
+//
+MHCamera::~MHCamera()
+{
+    if (fGeomCam)
+      delete fGeomCam;
+    if (fNotify)
+      delete fNotify;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return kTRUE for sector<0. Otherwise return kTRUE only if the specified
+// sector idx matches the sector of the pixel with index idx.
+//
+Bool_t MHCamera::MatchSector(Int_t idx, const TArrayI &sector, const TArrayI &aidx) const
+{
+    const MGeomPix &pix = (*fGeomCam)[idx];
+    return FindVal(sector, pix.GetSector()) && FindVal(aidx, pix.GetAidx());
+}
+
+// ------------------------------------------------------------------------
+//
+// Taken from TH1D::Fill(). Uses the argument directly as bin index.
+// Doesn't increment the number of entries.
+//
+//   -*-*-*-*-*-*-*-*Increment bin with abscissa X by 1*-*-*-*-*-*-*-*-*-*-*
+//                   ==================================
+//
+//    if x is less than the low-edge of the first bin, the Underflow bin is incremented
+//    if x is greater than the upper edge of last bin, the Overflow bin is incremented
+//
+//    If the storage of the sum of squares of weights has been triggered,
+//    via the function Sumw2, then the sum of the squares of weights is incremented
+//    by 1 in the bin corresponding to x.
+//
+//   -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
+Int_t MHCamera::Fill(Axis_t x)
+{
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,05,00)
+   if (fBuffer) return BufferFill(x,1);
+#endif
+   const Int_t bin = (Int_t)x+1;
+   AddBinContent(bin);
+   fBinEntries[bin]++;
+   if (fSumw2.fN)
+       fSumw2.fArray[bin]++;
+
+   if (bin<=0 || bin>fNcells-2)
+       return -1;
+
+   fTsumw++;
+   fTsumw2++;
+   fTsumwx  += x;
+   fTsumwx2 += x*x;
+   return bin;
+}
+
+// ------------------------------------------------------------------------
+//
+// Taken from TH1D::Fill(). Uses the argument directly as bin index.
+// Doesn't increment the number of entries.
+//
+//   -*-*-*-*-*-*Increment bin with abscissa X with a weight w*-*-*-*-*-*-*-*
+//               =============================================
+//
+//    if x is less than the low-edge of the first bin, the Underflow bin is incremented
+//    if x is greater than the upper edge of last bin, the Overflow bin is incremented
+//
+//    If the storage of the sum of squares of weights has been triggered,
+//    via the function Sumw2, then the sum of the squares of weights is incremented
+//    by w^2 in the bin corresponding to x.
+//
+//   -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
+Int_t MHCamera::Fill(Axis_t x, Stat_t w)
+{
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,05,00)
+   if (fBuffer) return BufferFill(x,w);
+#endif
+   const Int_t bin = (Int_t)x+1;
+   AddBinContent(bin, w);
+   fBinEntries[bin]++;
+   if (fSumw2.fN)
+       fSumw2.fArray[bin] += w*w;
+
+   if (bin<=0 || bin>fNcells-2)
+       return -1;
+
+   const Stat_t z = (w > 0 ? w : -w);
+   fTsumw   += z;
+   fTsumw2  += z*z;
+   fTsumwx  += z*x;
+   fTsumwx2 += z*x*x;
+   return bin;
+}
+
+// ------------------------------------------------------------------------
+//
+// Use x and y in millimeters
+//
+Int_t MHCamera::Fill(Axis_t x, Axis_t y, Stat_t w)
+{
+    if (fNcells<=1 || IsFreezed())
+        return -1;
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        MHexagon hex((*fGeomCam)[idx]);
+        if (hex.DistanceToPrimitive(x, y)>0)
+            continue;
+
+        SetUsed(idx);
+        return Fill(idx, w);
+    }
+    return -1;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this if you want to change the display status (displayed or not)
+// for all pixels. val==0 means that the pixel is not displayed.
+//
+void MHCamera::SetUsed(const TArrayC &arr)
+{
+    if (fNcells-2 != arr.GetSize())
+    {
+        gLog << warn << "WARNING - MHCamera::SetUsed: array size mismatch... ignored." << endl;
+        return;
+    }
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+        arr[idx] ? SetUsed(idx) : ResetUsed(idx);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the mean value of all entries which are used if all=kFALSE and
+// of all entries if all=kTRUE if sector<0. If sector>=0 only
+// entries with match the given sector are taken into account.
+//
+Stat_t MHCamera::GetMeanSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all) const
+{
+    if (fNcells<=1)
+        return 0;
+
+    Int_t n=0;
+
+    Stat_t mean = 0;
+    for (int i=0; i<fNcells-2; i++)
+    {
+        if ((all || IsUsed(i)) && MatchSector(i, sector, aidx))
+        {
+            if (TestBit(kProfile) && fBinEntries[i+1]==0)
+                continue;
+
+            mean += TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+            n++;
+        }
+    }
+
+    return n==0 ? 0 : mean/n;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the sqrt variance of all entries which are used if all=kFALSE and
+// of all entries if all=kTRUE if sector<0. If sector>=0 only
+// entries with match the given sector are taken into account.
+//
+Stat_t MHCamera::GetRmsSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all) const
+{
+    if (fNcells<=1)
+        return -1;
+
+    Int_t n=0;
+
+    Stat_t sum = 0;
+    Stat_t sq  = 0;
+    for (int i=0; i<fNcells-2; i++)
+    {
+        if ((all || IsUsed(i)) && MatchSector(i, sector, aidx))
+        {
+            if (TestBit(kProfile) && fBinEntries[i+1]==0)
+                continue;
+
+            const Double_t val = TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+
+            sum += val;
+            sq  += val*val;
+            n++;
+        }
+    }
+
+    if (n==0)
+        return 0;
+
+    sum /= n;
+    sq  /= n;
+
+    return TMath::Sqrt(sq-sum*sum);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the minimum contents of all pixels (if all is set, otherwise
+// only of all 'used' pixels), fMinimum if fMinimum set. If sector>=0
+// only pixels with matching sector number are taken into account.
+//
+Double_t MHCamera::GetMinimumSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all) const
+{
+    if (fMinimum != -1111)
+        return fMinimum;
+
+    if (fNcells<=1)
+        return 0;
+
+    Double_t minimum=FLT_MAX;
+
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        if (TestBit(kProfile) && fBinEntries[i+1]==0)
+            continue;
+
+        const Double_t val = TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+        if (MatchSector(i, sector, aidx) && (all || IsUsed(i)) && val<minimum)
+            minimum = val;
+    }
+
+    return minimum;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the maximum contents of all pixels (if all is set, otherwise
+// only of all 'used' pixels), fMaximum if fMaximum set. If sector>=0
+// only pixels with matching sector number are taken into account.
+//
+Double_t MHCamera::GetMaximumSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all) const
+{
+    if (fMaximum!=-1111)
+        return fMaximum;
+
+    if (fNcells<=1)
+        return 1;
+
+    Double_t maximum=-FLT_MAX;
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        if (TestBit(kProfile) && fBinEntries[i+1]==0)
+            continue;
+
+        const Double_t val = TestBit(kProfile) ? fArray[i+1]/fBinEntries[i+1] : fArray[i+1];
+        if (MatchSector(i, sector, aidx) && (all || IsUsed(i)) && val>maximum)
+            maximum = val;
+    }
+
+    return maximum;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to draw the camera layout into your canvas.
+// Setup a drawing canvas. Add this object and all child objects
+// (hexagons, etc) to the current pad. If no pad exists a new one is
+// created. (To access the 'real' pad containing the camera you have
+// to do a cd(1) in the current layer.
+//
+// To draw a camera into its own pad do something like:
+//
+//   MGeomCamMagic m;
+//   MHCamera *d=new MHCamera(m);
+//
+//   TCanvas *c = new TCanvas;
+//   c->Divide(2,1);
+//   c->cd(1);
+//
+//   d->FillRandom();
+//   d->Draw();
+//   d->SetBit(kCanDelete);
+//
+// There are several drawing options:
+//   'hist'        Draw as a standard TH1 histogram (value vs. pixel index)
+//   'box'         Draw hexagons which size is in respect to its contents
+//   'nocol'       Leave the 'boxed' hexagons empty
+//   'pixelindex'  Display the pixel index in each pixel
+//   'sectorindex' Display the sector index in each pixel
+//   'content'     Display the relative content aligned to GetMaximum() and
+//                 GeMinimum() ((val-min)/(max-min))
+//   'proj'        Display the y-projection of the histogram
+//   'same'        Draw trandparent pixels on top of an existing pad. This
+//                 makes it possible to draw the camera image on top of an
+//                 existing TH2, but also allows for distorted camera images
+//
+void MHCamera::Draw(Option_t *option)
+{
+    const Bool_t hassame = TString(option).Contains("same", TString::kIgnoreCase) && gPad;
+
+    // root 3.02:
+    // gPad->SetFixedAspectRatio()
+    const Color_t col = gPad ? gPad->GetFillColor() : 16;
+    TVirtualPad  *pad = gPad ? gPad : MH::MakeDefCanvas("CamDisplay", "Mars Camera Display", 656, 600);
+
+    if (!hassame)
+    {
+        pad->SetBorderMode(0);
+        pad->SetFillColor(col);
+
+        //
+        // Create an own pad for the MHCamera-Object which can be
+        // resized in paint to keep the correct aspect ratio
+        //
+        // The margin != 0 is a workaround for a problem in root 4.02/00
+        pad->Divide(1, 1, 1e-10, 1e-10, col);
+        pad->cd(1);
+        gPad->SetBorderMode(0);
+    }
+
+    AppendPad(option);
+    //fGeomCam->AppendPad();
+
+    //
+    // Do not change gPad. The user should not see, that Draw
+    // changes gPad...
+    //
+    if (!hassame)
+        pad->cd();
+}
+
+// ------------------------------------------------------------------------
+//
+// This is TObject::DrawClone but completely ignores
+// gROOT->GetSelectedPad(). tbretz had trouble with this in the past.
+// If this makes trouble please write a bug report.
+//
+TObject *MHCamera::DrawClone(Option_t *option) const 
+{
+   // Draw a clone of this object in the current pad
+
+   //TVirtualPad *pad = gROOT->GetSelectedPad();
+   TVirtualPad *padsav = gPad;
+   //if (pad) pad->cd();
+
+   TObject *newobj = Clone();
+
+   if (!newobj)
+       return 0;
+
+   /*
+   if (pad) {
+      if (strlen(option)) pad->GetListOfPrimitives()->Add(newobj,option);
+      else                pad->GetListOfPrimitives()->Add(newobj,GetDrawOption());
+      pad->Modified(kTRUE);
+      pad->Update();
+      if (padsav) padsav->cd();
+      return newobj;
+   }
+   */
+
+   TString opt(option);
+   opt.ToLower();
+
+   newobj->Draw(opt.IsNull() ? GetDrawOption() : option);
+
+   if (padsav)
+       padsav->cd();
+
+   return newobj;
+}
+
+// ------------------------------------------------------------------------
+//
+// Creates a TH1D which contains the projection of the contents of the
+// MHCamera onto the y-axis. The maximum and minimum are calculated
+// such that a slighly wider range than (GetMinimum(), GetMaximum()) is
+// displayed using THLimitsFinder::OptimizeLimits.
+//
+// If no name is given the newly allocated histogram is removed from
+// the current directory calling SetDirectory(0) in any other case
+// the newly created histogram is removed from the current directory
+// and added to gROOT such the gROOT->FindObject can find the histogram.
+//
+// If the standard name "_py" is given "_py" is appended to the name
+// of the MHCamera and the corresponding histogram is searched using
+// gROOT->FindObject and updated with the present projection.
+//
+// It is the responsibility of the user to make sure, that the newly
+// created histogram is freed correctly.
+//
+// Currently the new histogram is restrictred to 50 bins.
+// Maybe a optimal number can be calulated from the number of
+// bins on the x-axis of the MHCamera?
+//
+// The code was taken mainly from TH2::ProjectX such the interface
+// is more or less the same than to TH2-projections.
+//
+// If sector>=0 only entries with matching sector index are taken
+// into account.
+//
+TH1D *MHCamera::ProjectionS(const TArrayI &sector, const TArrayI &aidx, const char *name, const Int_t nbins) const
+{
+
+    // Create the projection histogram
+    TString pname(name);
+    if (name=="_py")
+    {
+        pname.Prepend(GetName());
+        if (sector.GetSize()>0)
+        {
+            pname += ";";
+            for (int i=0; i<sector.GetSize(); i++)
+                pname += sector[i];
+        }
+        if (aidx.GetSize()>0)
+        {
+            pname += ";";
+            for (int i=0; i<aidx.GetSize(); i++)
+                pname += aidx[i];
+        }
+    }
+
+    TH1D *h1=0;
+
+    //check if histogram with identical name exist
+    TObject *h1obj = gROOT->FindObject(pname);
+    if (h1obj && h1obj->InheritsFrom("TH1D")) {
+        h1 = (TH1D*)h1obj;
+        h1->Reset();
+    }
+
+    if (!h1)
+    {
+        h1 = new TH1D;
+        h1->UseCurrentStyle();
+        h1->SetName(pname);
+        h1->SetTitle(GetTitle());
+        h1->SetDirectory(0);
+        h1->SetXTitle(GetYaxis()->GetTitle());
+        h1->SetYTitle("Counts");
+        //h1->Sumw2();
+    }
+
+    Double_t min = GetMinimumSectors(sector, aidx);
+    Double_t max = GetMaximumSectors(sector, aidx);
+
+    if (min==max && max>0)
+        min=0;
+    if (min==max && min<0)
+        max=0;
+
+    Int_t newbins=0;
+    THLimitsFinder::OptimizeLimits(nbins, newbins, min, max, kFALSE);
+
+    MBinning bins(nbins, min, max);
+    bins.Apply(*h1);
+
+    // Fill the projected histogram
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+        if (IsUsed(idx) && MatchSector(idx, sector, aidx))
+            h1->Fill(GetBinContent(idx+1));
+
+    return h1;
+}
+
+// ------------------------------------------------------------------------
+//
+// Creates a TH1D which contains the projection of the contents of the
+// MHCamera onto the radius from the camera center. 
+// The maximum and minimum are calculated
+// such that a slighly wider range than (GetMinimum(), GetMaximum()) is
+// displayed using THLimitsFinder::OptimizeLimits.
+//
+// If no name is given the newly allocated histogram is removed from
+// the current directory calling SetDirectory(0) in any other case
+// the newly created histogram is removed from the current directory
+// and added to gROOT such the gROOT->FindObject can find the histogram.
+//
+// If the standard name "_rad" is given "_rad" is appended to the name
+// of the MHCamera and the corresponding histogram is searched using
+// gROOT->FindObject and updated with the present projection.
+//
+// It is the responsibility of the user to make sure, that the newly
+// created histogram is freed correctly.
+//
+// Currently the new histogram is restrictred to 50 bins.
+// Maybe a optimal number can be calulated from the number of
+// bins on the x-axis of the MHCamera?
+//
+// The code was taken mainly from TH2::ProjectX such the interface
+// is more or less the same than to TH2-projections.
+//
+// If sector>=0 only entries with matching sector index are taken
+// into account.
+//
+TProfile *MHCamera::RadialProfileS(const TArrayI &sector, const TArrayI &aidx, const char *name, const Int_t nbins) const
+{
+    // Create the projection histogram
+    TString pname(name);
+    if (name=="_rad")
+    {
+        pname.Prepend(GetName());
+        if (sector.GetSize()>0)
+        {
+            pname += ";";
+            for (int i=0; i<sector.GetSize(); i++)
+                pname += sector[i];
+        }
+        if (aidx.GetSize()>0)
+        {
+            pname += ";";
+            for (int i=0; i<aidx.GetSize(); i++)
+                pname += aidx[i];
+        }
+    }
+
+    TProfile *h1=0;
+
+    //check if histogram with identical name exist
+    TObject *h1obj = gROOT->FindObject(pname);
+    if (h1obj && h1obj->InheritsFrom("TProfile")) {
+        h1 = (TProfile*)h1obj;
+        h1->Reset();
+    }
+
+    if (!h1)
+    {
+        h1 = new TProfile;
+        h1->UseCurrentStyle();
+        h1->SetName(pname);
+        h1->SetTitle(GetTitle());
+        h1->SetDirectory(0);
+        h1->SetXTitle("Radius from camera center [mm]");
+        h1->SetYTitle(GetYaxis()->GetTitle());
+    }
+
+    Double_t min = 0.;
+    Double_t max = fGeomCam->GetMaxRadius();
+
+    Int_t newbins=0;
+
+    THLimitsFinder::OptimizeLimits(nbins, newbins, min, max, kFALSE);
+
+    MBinning bins(nbins, min, max);
+    bins.Apply(*h1);
+  
+    // Fill the projected histogram
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+        if (IsUsed(idx) && MatchSector(idx, sector, aidx))
+            h1->Fill(TMath::Hypot((*fGeomCam)[idx].GetX(),(*fGeomCam)[idx].GetY()),
+                     GetBinContent(idx+1));
+    return h1;
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Creates a TH1D which contains the projection of the contents of the
+// MHCamera onto the azimuth angle in the camera. 
+//
+// If no name is given the newly allocated histogram is removed from
+// the current directory calling SetDirectory(0) in any other case
+// the newly created histogram is removed from the current directory
+// and added to gROOT such the gROOT->FindObject can find the histogram.
+//
+// If the standard name "_azi" is given "_azi" is appended to the name
+// of the MHCamera and the corresponding histogram is searched using
+// gROOT->FindObject and updated with the present projection.
+//
+// It is the responsibility of the user to make sure, that the newly
+// created histogram is freed correctly.
+//
+// Currently the new histogram is restrictred to 60 bins.
+// Maybe a optimal number can be calulated from the number of
+// bins on the x-axis of the MHCamera?
+//
+// The code was taken mainly from TH2::ProjectX such the interface
+// is more or less the same than to TH2-projections.
+//
+TProfile *MHCamera::AzimuthProfileA(const TArrayI &aidx, const char *name, const Int_t nbins) const
+{
+    // Create the projection histogram
+    TString pname(name);
+    if (name=="_azi")
+    {
+        pname.Prepend(GetName());
+        if (aidx.GetSize()>0)
+        {
+            pname += ";";
+            for (int i=0; i<aidx.GetSize(); i++)
+                pname += aidx[i];
+        }
+    }
+
+    TProfile *h1=0;
+
+    //check if histogram with identical name exist
+    TObject *h1obj = gROOT->FindObject(pname);
+    if (h1obj && h1obj->InheritsFrom("TProfile")) {
+        h1 = (TProfile*)h1obj;
+        h1->Reset();
+    }
+
+    if (!h1)
+    {
+
+        h1 = new TProfile;
+        h1->UseCurrentStyle();
+        h1->SetName(pname);
+        h1->SetTitle(GetTitle());
+        h1->SetDirectory(0);
+        h1->SetXTitle("Azimuth in camera [deg]");
+        h1->SetYTitle(GetYaxis()->GetTitle());
+    }
+
+    Double_t min = 0;
+    Double_t max = 360;
+
+    Int_t newbins=0;
+    THLimitsFinder::OptimizeLimits(nbins, newbins, min, max, kFALSE);
+
+    MBinning bins(nbins, min, max);
+    bins.Apply(*h1);
+
+    // Fill the projected histogram
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        if (IsUsed(idx) && MatchSector(idx, TArrayI(), aidx))
+            h1->Fill(TMath::ATan2((*fGeomCam)[idx].GetY(),(*fGeomCam)[idx].GetX())*TMath::RadToDeg()+180,
+                     GetPixContent(idx));
+
+    }
+
+    return h1;
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Resizes the current pad so that the camera is displayed in its
+// correct aspect ratio
+//
+void MHCamera::SetRange()
+{
+    const Float_t range = fGeomCam->GetMaxRadius()*1.05;
+
+    //
+    // Maintain aspect ratio
+    //
+    const float ratio = TestBit(kNoLegend) ? 1 : 1.15;
+
+    //
+    // Calculate width and height of the current pad in pixels
+    //
+    Float_t w = gPad->GetWw();
+    Float_t h = gPad->GetWh()*ratio;
+
+    //
+    // This prevents the pad from resizing itself wrongly
+    //
+    if (gPad->GetMother() != gPad)
+    {
+        w *= gPad->GetMother()->GetAbsWNDC();
+        h *= gPad->GetMother()->GetAbsHNDC();
+    }
+
+    //
+    // Set Range (coordinate system) of pad
+    //
+    gPad->Range(-range, -range, (2*ratio-1)*range, range);
+
+    //
+    // Resize Pad to given ratio
+    //
+    if (h<w)
+        gPad->SetPad((1.-h/w)/2, 0, (h/w+1.)/2, 1);
+    else
+        gPad->SetPad(0, (1.-w/h)/2, 1, (w/h+1.)/2);
+}
+
+// ------------------------------------------------------------------------
+//
+// Updates the pixel colors and paints the pixels
+//
+void MHCamera::Update(Bool_t islog, Bool_t isbox, Bool_t iscol, Bool_t issame)
+{
+    Double_t min = GetMinimum(kFALSE);
+    Double_t max = GetMaximum(kFALSE);
+    if (min==FLT_MAX)
+    {
+        min = 0;
+        max = 1;
+    }
+
+    if (min==max)
+        max += 1;
+
+    if (!issame)
+        UpdateLegend(min, max, islog);
+
+    // Try to estimate the units of the current display. This is only
+    // necessary for 'same' option and allows distorted images of the camera!
+    const Float_t maxr = (1-fGeomCam->GetConvMm2Deg())*fGeomCam->GetMaxRadius()/2;
+    const Float_t conv = !issame ||
+        gPad->GetX1()<-maxr || gPad->GetY1()<-maxr ||
+        gPad->GetX2()> maxr || gPad->GetY2()>maxr ? 1 : fGeomCam->GetConvMm2Deg();
+
+    MHexagon hex;
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        hex.SetFillStyle(issame ? 0 : 1001);
+
+        if (!issame)
+        {
+            const Bool_t isnan = TMath::IsNaN(fArray[i+1]);
+            if (!IsUsed(i) || !iscol || isnan)
+            {
+                hex.SetFillColor(10);
+
+                if (isnan)
+                    gLog << warn << "MHCamera::Update: " << GetName() << " <" << GetTitle() << "> - Pixel Index #" << i << " contents is NaN (Not a Number)..." << endl;
+            }
+            else
+                hex.SetFillColor(GetColor(GetBinContent(i+1), min, max, islog));
+        }
+
+        const MGeomPix &pix = (*fGeomCam)[i];
+
+        Float_t x = pix.GetX()*conv/(fAbberation+1);
+        Float_t y = pix.GetY()*conv/(fAbberation+1);
+        Float_t d = pix.GetD()*conv;
+
+        if (!isbox)
+            hex.PaintHexagon(x, y, d);
+        else
+            if (IsUsed(i) && !TMath::IsNaN(fArray[i+1]))
+            {
+                Float_t size = d*(GetBinContent(i+1)-min)/(max-min);
+                if (size>d)
+                    size=d;
+                hex.PaintHexagon(x, y, size);
+            }
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Print minimum and maximum
+//
+void MHCamera::Print(Option_t *) const
+{
+    gLog << all << "Minimum: " << GetMinimum();
+    if (fMinimum==-1111)
+        gLog << " <autoscaled>";
+    gLog << endl;
+    gLog << "Maximum: " << GetMaximum();
+    if (fMaximum==-1111)
+        gLog << " <autoscaled>";
+    gLog << endl;
+}
+
+// ------------------------------------------------------------------------
+//
+// Paint the y-axis title
+//
+void MHCamera::PaintAxisTitle()
+{
+    const Float_t range = fGeomCam->GetMaxRadius()*1.05;
+    const Float_t w = (1 + 1.5/sqrt((float)(fNcells-2)))*range;
+
+    TLatex *ptitle = new TLatex(w, -.90*range, GetYaxis()->GetTitle());
+
+    ptitle->SetTextSize(0.05);
+    ptitle->SetTextAlign(21);
+
+    // box with the histogram title
+    ptitle->SetTextColor(gStyle->GetTitleTextColor());
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,05,01)
+    ptitle->SetTextFont(gStyle->GetTitleFont(""));
+#endif
+    ptitle->Paint();
+}
+
+// ------------------------------------------------------------------------
+//
+// Paints the camera.
+//
+void MHCamera::Paint(Option_t *o)
+{
+    if (fNcells<=1)
+        return;
+
+    TString opt(o);
+    opt.ToLower();
+
+    if (opt.Contains("hist"))
+    {
+        opt.ReplaceAll("hist", "");
+        TH1D::Paint(opt);
+        return;
+    }
+
+    if (opt.Contains("proj"))
+    {
+      opt.ReplaceAll("proj", "");
+      Projection(GetName())->Paint(opt);
+      return;
+    }
+
+    const Bool_t hassame = opt.Contains("same");
+    const Bool_t hasbox  = opt.Contains("box");
+    const Bool_t hascol  = hasbox ? !opt.Contains("nocol") : kTRUE;
+
+    if (!hassame)
+    {
+        gPad->Clear();
+
+        // Maintain aspect ratio
+        SetRange();
+
+        if (GetPainter())
+        {
+            // Paint statistics
+            if (!TestBit(TH1::kNoStats))
+                fPainter->PaintStat(gStyle->GetOptStat(), NULL);
+
+            // Paint primitives (pixels, color legend, photons, ...)
+            if (fPainter->InheritsFrom(THistPainter::Class()))
+            {
+                static_cast<THistPainter*>(fPainter)->MakeChopt("");
+                static_cast<THistPainter*>(fPainter)->PaintTitle();
+            }
+        }
+    }
+
+    // Update Contents of the pixels and paint legend
+    Update(gPad->GetLogy(), hasbox, hascol, hassame);
+
+    if (!hassame)
+        PaintAxisTitle();
+
+    if (opt.Contains("pixelindex"))
+        PaintIndices(0);
+    if (opt.Contains("sectorindex"))
+        PaintIndices(1);
+    if (opt.Contains("content"))
+        PaintIndices(2);
+}
+
+// ------------------------------------------------------------------------
+//
+// With this function you can change the color palette. For more
+// information see TStyle::SetPalette. Only palettes with 50 colors
+// are allowed.
+// In addition you can use SetPalette(52, 0) to create an inverse
+// deep blue sea palette
+//
+void MHCamera::SetPalette(Int_t ncolors, Int_t *colors)
+{
+    //
+    // If not enough colors are specified skip this.
+    //
+    if (ncolors>1 && ncolors<50)
+    {
+        gLog << err << "MHCamera::SetPalette: Only default palettes with 50 colors are allowed... ignored." << endl;
+        return;
+    }
+
+    //
+    // If ncolors==52 create a reversed deep blue sea palette
+    //
+    if (ncolors==52)
+    {
+        gStyle->SetPalette(51, NULL);
+        TArrayI c(kItemsLegend);
+        for (int i=0; i<kItemsLegend; i++)
+            c[kItemsLegend-i-1] = gStyle->GetColorPalette(i);
+        gStyle->SetPalette(kItemsLegend, c.GetArray());
+    }
+    else
+        gStyle->SetPalette(ncolors, colors);
+
+    fColors.Set(kItemsLegend);
+    for (int i=0; i<kItemsLegend; i++)
+        fColors[i] = gStyle->GetColorPalette(i);
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Changes the palette of the displayed camera histogram.
+//
+// Change to the right pad first - otherwise GetDrawOption() might fail.
+//
+void MHCamera::SetPrettyPalette()
+{
+    if (!TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+        SetPalette(1, 0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Changes the palette of the displayed camera histogram.
+//
+// Change to the right pad first - otherwise GetDrawOption() might fail.
+//
+void MHCamera::SetDeepBlueSeaPalette()
+{
+    if (!TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+        SetPalette(51, 0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Changes the palette of the displayed camera histogram.
+//
+// Change to the right pad first - otherwise GetDrawOption() might fail.
+//
+void MHCamera::SetInvDeepBlueSeaPalette()
+{
+    if (!TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+        SetPalette(52, 0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Paint indices (as text) inside the pixels. Depending of the type-
+// argument we paint:
+//  0: pixel number
+//  1: sector number
+//  2: content
+//
+void MHCamera::PaintIndices(Int_t type)
+{
+    if (fNcells<=1)
+        return;
+
+    const Double_t min = GetMinimum();
+    const Double_t max = GetMaximum();
+
+    if (type==2 && max==min)
+        return;
+
+    TText txt;
+    txt.SetTextFont(122);
+    txt.SetTextAlign(22);   // centered/centered
+
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        const MGeomPix &h = (*fGeomCam)[i];
+
+        TString num;
+        switch (type)
+        {
+        case 0: num += i; break;
+        case 1: num += h.GetSector(); break;
+        case 2: num += (Int_t)((fArray[i+1]-min)/(max-min)); break;
+        }
+
+        // FIXME: Should depend on the color of the pixel...
+        //(GetColor(GetBinContent(i+1), min, max, 0));
+        txt.SetTextColor(kRed);
+        txt.SetTextSize(0.3*h.GetD()/fGeomCam->GetMaxRadius()/1.05);
+        txt.PaintText(h.GetX(), h.GetY(), num);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+//
+void MHCamera::AddCamContent(const MCamEvent &event, Int_t type)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val=0;
+        if (event.GetPixelContent(val, idx, *fGeomCam, type)/* && !IsUsed(idx)*/)
+        {
+            SetUsed(idx);
+            Fill(idx, val); // FIXME: Slow!
+        }
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+//
+void MHCamera::SetCamError(const MCamEvent &evt, Int_t type)
+{
+
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val=0;
+        if (evt.GetPixelContent(val, idx, *fGeomCam, type)/* && !IsUsed(idx)*/)
+            SetUsed(idx);
+
+        SetBinError(idx+1, val); // FIXME: Slow!
+    }
+}
+
+Stat_t MHCamera::GetBinContent(Int_t bin) const
+{
+    if (fBuffer) ((TProfile*)this)->BufferEmpty();
+    if (bin < 0) bin = 0;
+    if (bin >= fNcells) bin = fNcells-1;
+    if (!fArray) return 0;
+
+    if (!TestBit(kProfile))
+        return Stat_t (fArray[bin]);
+
+    if (fBinEntries.fArray[bin] == 0) return 0;
+    return fArray[bin]/fBinEntries.fArray[bin];
+}
+
+Stat_t MHCamera::GetBinError(Int_t bin) const
+{
+    if (!TestBit(kProfile))
+        return TH1D::GetBinError(bin);
+
+    const UInt_t n = (UInt_t)fBinEntries[bin];
+
+    if (n==0)
+        return 0;
+
+    const Double_t sqr = fSumw2.fArray[bin] / n;
+    const Double_t val = fArray[bin]        / n;
+
+    return sqr>val*val ? TMath::Sqrt(sqr - val*val) / n : 0;
+
+    /*
+    Double_t rc = 0;
+    if (TestBit(kSqrtVariance) && GetEntries()>0) // error on the mean
+    {
+        const Double_t error = fSumw2.fArray[bin]/GetEntries();
+        const Double_t val   = fArray[bin]/GetEntries();
+        rc = val*val>error ? 0 : TMath::Sqrt(error - val*val);
+    }
+    else
+        rc = TH1D::GetBinError(bin);
+
+    return Profile(rc);*/
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MHCamera on top of the present contents.
+// Type:
+//  0) bin content
+//  1) errors
+//  2) rel. errors
+//
+void MHCamera::AddCamContent(const MHCamera &d, Int_t type)
+{
+    if (fNcells!=d.fNcells || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+        if (d.IsUsed(idx))
+            SetUsed(idx);
+
+    switch (type)
+    {
+    case 1:
+        for (Int_t idx=0; idx<fNcells-2; idx++)
+            Fill(idx, d.GetBinError(idx+1));
+        break;
+    case 2:
+        for (Int_t idx=0; idx<fNcells-2; idx++)
+            if (d.GetBinContent(idx+1)!=0)
+                Fill(idx, TMath::Abs(d.GetBinError(idx+1)/d.GetBinContent(idx+1)));
+        break;
+    default:
+        for (Int_t idx=0; idx<fNcells-2; idx++)
+            Fill(idx, d.GetBinContent(idx+1));
+        break;
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a TArrayD on top of the present contents.
+//
+void MHCamera::AddCamContent(const TArrayD &event, const TArrayC *used)
+{
+    if (event.GetSize()!=fNcells-2 || IsFreezed())
+        return;
+
+    if (used && used->GetSize()!=fNcells-2)
+        return;
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Fill(idx, event[idx]); // FIXME: Slow!
+
+        if (!used || (*used)[idx])
+            SetUsed(idx);
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MArrayD on top of the present contents.
+//
+void MHCamera::AddCamContent(const MArrayD &event, const TArrayC *used)
+{
+    if (event.GetSize()!=(UInt_t)(fNcells-2) || IsFreezed())
+        return;
+
+    if (used && used->GetSize()!=fNcells-2)
+        return;
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Fill(idx, event[idx]); // FIXME: Slow!
+
+        if (!used || (*used)[idx])
+            SetUsed(idx);
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+// 1 is added to each pixel if the contents of MCamEvent>threshold (in case isabove is set to kTRUE == default)
+// 1 is added to each pixel if the contents of MCamEvent<threshold (in case isabove is set to kFALSE)
+//
+// in unused pixel is not counted if it didn't fullfill the condition.
+//
+void MHCamera::CntCamContent(const MCamEvent &event, Double_t threshold, Int_t type, Bool_t isabove)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val=threshold;
+        const Bool_t rc = event.GetPixelContent(val, idx, *fGeomCam, type);
+        if (rc)
+            SetUsed(idx);
+
+        const Bool_t cond =
+            ( isabove && val>threshold) ||
+            (!isabove && val<threshold);
+
+        Fill(idx, rc && cond ? 1 : 0);
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+// - the contents of the pixels in event are added to each pixel
+//   if the pixel of thresevt<threshold (in case isabove is set
+//   to kTRUE == default)
+// - the contents of the pixels in event are  added to each pixel
+//   if the pixel of thresevt<threshold (in case isabove is set
+//   to kFALSE)
+//
+// in unused pixel is not counted if it didn't fullfill the condition.
+//
+void MHCamera::CntCamContent(const MCamEvent &event, Int_t type1, const MCamEvent &thresevt, Int_t type2, Double_t threshold, Bool_t isabove)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t th=0;
+        if (!thresevt.GetPixelContent(th, idx, *fGeomCam, type2))
+            continue;
+
+        if ((isabove && th>threshold) || (!isabove && th<threshold))
+            continue;
+
+        Double_t val=th;
+        if (event.GetPixelContent(val, idx, *fGeomCam, type1))
+        {
+            SetUsed(idx);
+            Fill(idx, val);
+        }
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a MCamEvent on top of the present contents.
+// 1 is added to each pixel if the contents of MCamEvent>threshold (in case isabove is set to kTRUE == default)
+// 1 is added to each pixel if the contents of MCamEvent<threshold (in case isabove is set to kFALSE)
+//
+// in unused pixel is not counted if it didn't fullfill the condition.
+//
+void MHCamera::CntCamContent(const MCamEvent &event, TArrayD threshold, Int_t type, Bool_t isabove)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val=threshold[idx];
+        if (event.GetPixelContent(val, idx, *fGeomCam, type)/* && !IsUsed(idx)*/)
+        {
+            SetUsed(idx);
+
+            if (val>threshold[idx] && isabove)
+                Fill(idx);
+            if (val<threshold[idx] && !isabove)
+                Fill(idx);
+        }
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to add a TArrayD on top of the present contents.
+// 1 is added to each pixel if the contents of MCamEvent>threshold
+//
+void MHCamera::CntCamContent(const TArrayD &event, Double_t threshold, Bool_t ispos)
+{
+    if (event.GetSize()!=fNcells-2 || IsFreezed())
+        return;
+
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        if (event[idx]>threshold)
+            Fill(idx);
+
+        if (!ispos || fArray[idx+1]>0)
+            SetUsed(idx);
+    }
+    fEntries++;
+}
+
+// ------------------------------------------------------------------------
+//
+// Fill the pixels with random contents.
+//
+void MHCamera::FillRandom()
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    Reset();
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Fill(idx, gRandom->Uniform()*fGeomCam->GetPixRatio(idx));
+        SetUsed(idx);
+    }
+    fEntries=1;
+}
+
+
+// ------------------------------------------------------------------------
+//
+// The array must be in increasing order, eg: 2.5, 3.7, 4.9
+// The values in each bin are replaced by the interval in which the value
+// fits. In the example we have four intervals
+// (<2.5, 2.5-3.7, 3.7-4.9, >4.9). Maximum and minimum are set
+// accordingly.
+//
+void MHCamera::SetLevels(const TArrayF &arr)
+{
+    if (fNcells<=1)
+        return;
+
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        if (!IsUsed(i))
+            continue;
+
+        Int_t j = arr.GetSize();
+        while (j && fArray[i+1]<arr[j-1])
+            j--;
+
+        fArray[i+1] = j;
+    }
+    SetMaximum(arr.GetSize());
+    SetMinimum(0);
+}
+
+// ------------------------------------------------------------------------
+//
+// Reset the all pixel colors to a default value
+//
+void MHCamera::Reset(Option_t *opt)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    TH1::Reset(opt);
+
+    for (Int_t i=0; i<fNcells-2; i++)
+    {
+        fArray[i+1]=0;
+        ResetUsed(i);
+    }
+    fArray[0]         = 0;
+    fArray[fNcells-1] = 0;
+} 
+
+// ------------------------------------------------------------------------
+//
+//  Here we calculate the color index for the current value.
+//  The color index is defined with the class TStyle and the
+//  Color palette inside. We use the command gStyle->SetPalette(1,0)
+//  for the display. So we have to convert the value "wert" into
+//  a color index that fits the color palette.
+//  The range of the color palette is defined by the values fMinPhe
+//  and fMaxRange. Between this values we have 50 color index, starting
+//  with 0 up to 49.
+//
+Int_t MHCamera::GetColor(Float_t val, Float_t min, Float_t max, Bool_t islog)
+{
+    if (TMath::IsNaN(val)) // FIXME: gLog!
+        return 10;
+
+    //
+    //   first treat the over- and under-flows
+    //
+    const Int_t maxcolidx = kItemsLegend-1;
+
+    if (val >= max)
+        return fColors[maxcolidx];
+
+    if (val <= min)
+        return fColors[0];
+
+    //
+    // calculate the color index
+    //
+    Float_t ratio;
+    if (islog && min>0)
+        ratio = log10(val/min) / log10(max/min);
+    else
+        ratio = (val-min) / (max-min);
+
+    const Int_t colidx = (Int_t)(ratio*maxcolidx + .5);
+    return fColors[colidx];
+}
+
+TPaveStats *MHCamera::GetStatisticBox()
+{
+    TObject *obj = 0;
+
+    TIter Next(fFunctions);
+    while ((obj = Next()))
+        if (obj->InheritsFrom(TPaveStats::Class()))
+            return static_cast<TPaveStats*>(obj);
+
+    return NULL;
+}
+
+// ------------------------------------------------------------------------
+//
+//  Change the text on the legend according to the range of the Display
+//
+void MHCamera::UpdateLegend(Float_t min, Float_t max, Bool_t islog)
+{
+    const Float_t range = fGeomCam->GetMaxRadius()*1.05;
+
+    TArrow arr;
+    arr.PaintArrow(-range*.9, -range*.9, -range*.6, -range*.9, 0.025);
+    arr.PaintArrow(-range*.9, -range*.9, -range*.9, -range*.6, 0.025);
+
+    TString text;
+    text += (int)(range*.3);
+    text += "mm";
+
+    TText newtxt2;
+    newtxt2.SetTextSize(0.04);
+    newtxt2.PaintText(-range*.85, -range*.85, text);
+
+    text = "";
+    text += Form("%.2f", (float)((int)(range*.3*fGeomCam->GetConvMm2Deg()*10))/10);
+    text += "\\circ";
+    text = text.Strip(TString::kLeading);
+
+    TLatex latex;
+    latex.PaintLatex(-range*.85, -range*.75, 0, 0.04, text);
+
+    if (TestBit(kNoLegend))
+        return;
+
+    TPaveStats *stats = GetStatisticBox();
+
+    const Float_t hndc   = 0.92 - (stats ? stats->GetY1NDC() : 1);
+    const Float_t H      = (0.75-hndc)*range;
+    const Float_t offset = hndc*range;
+
+    const Float_t h = 2./kItemsLegend;
+    const Float_t w = range/sqrt((float)(fNcells-2));
+
+    TBox newbox;
+    TText newtxt;
+    newtxt.SetTextSize(0.03);
+    newtxt.SetTextAlign(12);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    newtxt.SetBit(/*kNoContextMenu|*/kCannotPick);
+    newbox.SetBit(/*kNoContextMenu|*/kCannotPick);
+#endif
+
+    const Float_t step   = (islog && min>0 ? log10(max/min) : max-min) / kItemsLegend;
+    const Int_t   firsts = step*3 < 1e-8 ? 8 : (Int_t)floor(log10(step*3));
+    const TString opt    = Form("%%.%if", firsts>0 ? 0 : TMath::Abs(firsts));
+
+    for (Int_t i=0; i<kItemsLegend+1; i+=3)
+    {
+        Float_t val;
+        if (islog && min>0)
+            val = pow(10, step*i) * min;
+        else
+            val = min + step*i;
+
+        //const bool dispexp = max-min>1.5 && fabs(val)>0.1 && fabs(val)<1e6;
+        newtxt.PaintText(range+1.5*w, H*(i*h-1)-offset, Form(opt, val));
+    }
+
+    for (Int_t i=0; i<kItemsLegend; i++)
+    {
+        newbox.SetFillColor(fColors[i]);
+        newbox.PaintBox(range, H*(i*h-1)-offset, range+w, H*((i+1)*h-1)-offset);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Save primitive as a C++ statement(s) on output stream out
+//
+void MHCamera::SavePrimitive(ofstream &out, Option_t *opt)
+{
+    gLog << err << "MHCamera::SavePrimitive: Must be rewritten!" << endl;
+    /*
+    if (!gROOT->ClassSaved(TCanvas::Class()))
+        fDrawingPad->SavePrimitive(out, opt);
+
+    out << "   " << fDrawingPad->GetName() << "->SetWindowSize(";
+    out << fDrawingPad->GetWw() << "," << fDrawingPad->GetWh() << ");" << endl;
+    */
+}
+
+// ------------------------------------------------------------------------
+//
+// compute the distance of a point (px,py) to the Camera
+// this functions needed for graphical primitives, that
+// means without this function you are not able to interact
+// with the graphical primitive with the mouse!!!
+//
+// All calcutations are done in pixel coordinates
+//
+Int_t MHCamera::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    if (fNcells<=1)
+        return 999999;
+
+    TPaveStats *box = (TPaveStats*)gPad->GetPrimitive("stats");
+    if (box)
+    {
+        const Double_t w = box->GetY2NDC()-box->GetY1NDC();
+        box->SetX1NDC(gStyle->GetStatX()-gStyle->GetStatW());
+        box->SetY1NDC(gStyle->GetStatY()-w);
+        box->SetX2NDC(gStyle->GetStatX());
+        box->SetY2NDC(gStyle->GetStatY());
+    }
+
+    if (TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+        return TH1D::DistancetoPrimitive(px, py);
+
+    const Bool_t issame = TString(GetDrawOption()).Contains("same", TString::kIgnoreCase);
+
+    const Float_t maxr = (1-fGeomCam->GetConvMm2Deg())*fGeomCam->GetMaxRadius()/2;
+    const Float_t conv = !issame ||
+        gPad->GetX1()<-maxr || gPad->GetY1()<-maxr ||
+        gPad->GetX2()> maxr || gPad->GetY2()>maxr ? 1 : fGeomCam->GetConvMm2Deg();
+
+    if (GetPixelIndex(px, py, conv)>=0)
+        return 0;
+
+    if (!box)
+        return 999999;
+
+    const Int_t dist = box->DistancetoPrimitive(px, py);
+    if (dist > TPad::GetMaxPickDistance())
+        return 999999;
+
+    gPad->SetSelected(box);
+    return dist;
+}
+
+// ------------------------------------------------------------------------
+//
+//
+Int_t MHCamera::GetPixelIndex(Int_t px, Int_t py, Float_t conv) const
+{
+    if (fNcells<=1)
+        return -1;
+
+    Int_t i;
+    for (i=0; i<fNcells-2; i++)
+    {
+        MHexagon hex((*fGeomCam)[i]);
+        if (hex.DistancetoPrimitive(px, py, conv)>0)
+            continue;
+
+        return i;
+    }
+    return -1;
+}
+
+// ------------------------------------------------------------------------
+//
+// Returns string containing info about the object at position (px,py).
+// Returned string will be re-used (lock in MT environment).
+//
+char *MHCamera::GetObjectInfo(Int_t px, Int_t py) const
+{
+    if (TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+        return TH1D::GetObjectInfo(px, py);
+
+    static char info[128];
+
+    const Int_t idx=GetPixelIndex(px, py);
+
+    if (idx<0)
+        return TObject::GetObjectInfo(px, py);
+
+    sprintf(info, "Software Pixel Idx: %d (Hardware Id=%d) c=%.1f <%s>",
+            idx, idx+1, GetBinContent(idx+1), IsUsed(idx)?"on":"off");
+    return info;
+}
+
+// ------------------------------------------------------------------------
+//
+// Add a MCamEvent which should be displayed when the user clicks on a
+// pixel.
+// Warning: The object MUST inherit from TObject AND MCamEvent
+//
+void MHCamera::AddNotify(TObject *obj)
+{
+    // Make sure, that the object derives from MCamEvent!
+    MCamEvent *evt = dynamic_cast<MCamEvent*>(obj);
+    if (!evt)
+    {
+        gLog << err << "ERROR: MHCamera::AddNotify - TObject doesn't inherit from MCamEvent... ignored." << endl;
+        return;
+    }
+
+    // Make sure, that it is deleted from the list too, if the obj is deleted
+    obj->SetBit(kMustCleanup);
+
+    // Add object to list
+    fNotify->Add(obj);
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a mouse event on the camera
+//
+void MHCamera::ExecuteEvent(Int_t event, Int_t px, Int_t py)
+{
+    if (TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+    {
+        TH1D::ExecuteEvent(event, px, py);
+        return;
+    }
+    //if (event==kMouseMotion && fStatusBar)
+    //    fStatusBar->SetText(GetObjectInfo(px, py), 0);
+    if (event!=kButton1Down)
+        return;
+
+    const Int_t idx = GetPixelIndex(px, py);
+    if (idx<0)
+        return;
+
+    gLog << all << GetTitle() << " <" << GetName() << ">" << dec << endl;
+    gLog << "Software Pixel Idx: " << idx << endl;
+    gLog << "Hardware Pixel Id:  " << idx+1 << endl;
+    gLog << "Contents:           " << GetBinContent(idx+1);
+    if (GetBinError(idx+1)>0)
+        gLog << " +/- " << GetBinError(idx+1);
+    gLog << "  <" << (IsUsed(idx)?"on":"off") << ">  n=" << fBinEntries[idx+1] << endl;
+
+    if (fNotify && fNotify->GetSize()>0)
+    {
+        // FIXME: Is there a simpler and more convinient way?
+
+        // The name which is created here depends on the instance of
+        // MHCamera and on the pad on which it is drawn --> The name
+        // is unique. For ExecuteEvent gPad is always correctly set.
+        const TString name = Form("%p;%p;PixelContent", this, gPad);
+
+        TCanvas *old = (TCanvas*)gROOT->GetListOfCanvases()->FindObject(name);
+        if (old)
+            old->cd();
+        else
+            new TCanvas(name);
+
+        /*
+         TIter Next(gPad->GetListOfPrimitives());
+         TObject *o;
+         while (o=Next()) cout << o << ": " << o->GetName() << " " << o->IsA()->GetName() << endl;
+         */
+
+        // FIXME: Make sure, that the old histograms are really deleted.
+        //        Are they already deleted?
+
+        // The dynamic_cast is necessary here: We cannot use ForEach
+        TIter Next(fNotify);
+        MCamEvent *evt;
+        while ((evt=dynamic_cast<MCamEvent*>(Next())))
+            evt->DrawPixelContent(idx);
+
+        gPad->Modified();
+        gPad->Update();
+    }
+}
+
+UInt_t MHCamera::GetNumPixels() const
+{
+    return fGeomCam->GetNumPixels();
+}
+
+TH1 *MHCamera::DrawCopy() const
+{
+    gPad=NULL;
+    return TH1D::DrawCopy(fName+";cpy");
+} 
+
+// --------------------------------------------------------------------------
+//
+// Draw a projection of MHCamera onto the y-axis values. Depending on the 
+// variable fit, the following fits are performed:
+//
+// 0: No fit, simply draw the projection
+// 1: Single Gauss (for distributions flat-fielded over the whole camera)
+// 2: Double Gauss (for distributions different for inner and outer pixels)
+// 3: Triple Gauss (for distributions with inner, outer pixels and outliers)
+// 4: flat         (for the probability distributions)
+// (1-4:) Moreover, sectors 6,1 and 2 of the camera and sectors 3,4 and 5 are 
+//        drawn separately, for inner and outer pixels.
+// 5: Fit Inner and Outer pixels separately by a single Gaussian 
+//                 (only for MAGIC cameras)
+// 6: Fit Inner and Outer pixels separately by a single Gaussian and display 
+//                 additionally the two camera halfs separately (for MAGIC camera)
+// 7: Single Gauss with TLegend to show the meaning of the colours
+//
+void MHCamera::DrawProjection(Int_t fit) const
+{
+    TArrayI inner(1);
+    inner[0] = 0;
+
+    TArrayI outer(1);
+    outer[0] = 1;
+
+    if (fit==5 || fit==6)
+    {
+        if (GetGeomCam().InheritsFrom("MGeomCamMagic"))
+        {
+            TArrayI s0(6);
+            s0[0] = 6;
+            s0[1] = 1;
+            s0[2] = 2;
+            s0[3] = 3;
+            s0[4] = 4;
+            s0[5] = 5;
+
+            TArrayI s1(3);
+            s1[0] = 6;
+            s1[1] = 1;
+            s1[2] = 2;
+
+            TArrayI s2(3);
+            s2[0] = 3;
+            s2[1] = 4;
+            s2[2] = 5;
+
+            gPad->Clear();
+            TVirtualPad *pad = gPad;
+            pad->Divide(2,1);
+
+            TH1D *inout[2];
+            inout[0] = ProjectionS(s0, inner, "Inner");
+            inout[1] = ProjectionS(s0, outer, "Outer");
+
+            inout[0]->SetDirectory(NULL);
+            inout[1]->SetDirectory(NULL);
+
+            for (int i=0; i<2; i++)
+            {
+                pad->cd(i+1);
+                gPad->SetBorderMode(0);
+
+                inout[i]->SetLineColor(kRed+i);
+                inout[i]->SetBit(kCanDelete);
+                inout[i]->Draw();
+                inout[i]->Fit("gaus","Q");
+
+                if (fit == 6)
+                {
+                    TH1D *half[2];
+                    half[0] = ProjectionS(s1, i==0 ? inner : outer , "Sector 6-1-2");
+                    half[1] = ProjectionS(s2, i==0 ? inner : outer , "Sector 3-4-5");
+
+                    for (int j=0; j<2; j++)
+                    {
+                        half[j]->SetLineColor(kRed+i+2*j+1);
+                        half[j]->SetDirectory(NULL);
+                        half[j]->SetBit(kCanDelete);
+                        half[j]->Draw("same");
+                    }
+                }
+
+            }
+        }
+        return;
+    }
+
+    TH1D *obj2 = (TH1D*)Projection(GetName());
+    obj2->SetDirectory(0);
+    obj2->Draw();
+    obj2->SetBit(kCanDelete);
+
+    if (fit == 0)
+        return;
+
+    if (GetGeomCam().InheritsFrom("MGeomCamMagic"))
+    {
+        TArrayI s0(3);
+        s0[0] = 6;
+        s0[1] = 1;
+        s0[2] = 2;
+
+        TArrayI s1(3);
+        s1[0] = 3;
+        s1[1] = 4;
+        s1[2] = 5;
+
+        TH1D *halfInOut[4];
+
+        // Just to get the right (maximum) binning
+        halfInOut[0] = ProjectionS(s0, inner, "Sector 6-1-2 Inner");
+        halfInOut[1] = ProjectionS(s1, inner, "Sector 3-4-5 Inner");
+        halfInOut[2] = ProjectionS(s0, outer, "Sector 6-1-2 Outer");
+        halfInOut[3] = ProjectionS(s1, outer, "Sector 3-4-5 Outer");
+
+        TLegend *leg = new TLegend(0.05,0.65,0.35,0.9);
+
+        for (int i=0; i<4; i++)
+        {
+            halfInOut[i]->SetLineColor(kRed+i);
+            halfInOut[i]->SetDirectory(0);
+            halfInOut[i]->SetBit(kCanDelete);
+            halfInOut[i]->Draw("same");
+            leg->AddEntry(halfInOut[i],halfInOut[i]->GetTitle(),"l");
+        }
+
+        if (fit==7)
+            leg->Draw();
+      
+        gPad->Modified();
+        gPad->Update();
+    }
+
+    const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+    const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+    const Double_t integ = obj2->Integral("width")/2.5;
+    const Double_t mean  = obj2->GetMean();
+    const Double_t rms   = obj2->GetRMS();
+    const Double_t width = max-min;
+
+    const TString dgausformula = "([0]-[3])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])"
+        "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
+
+    const TString tgausformula = "([0]-[3]-[6])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])"
+        "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])"
+        "+[6]/[8]*exp(-0.5*(x-[7])*(x-[7])/[8]/[8])";
+
+    TF1 *f=0;
+    switch (fit)
+    {
+    case 1:
+        f = new TF1("sgaus", "gaus(0)", min, max);
+        f->SetLineColor(kYellow);
+        f->SetBit(kCanDelete);
+        f->SetParNames("Area", "#mu", "#sigma");
+        f->SetParameters(integ/rms, mean, rms);
+        f->SetParLimits(0, 0,   integ);
+        f->SetParLimits(1, min, max);
+        f->SetParLimits(2, 0,   width/1.5);
+
+        obj2->Fit(f, "QLR");
+        break;
+
+    case 2:
+        f = new TF1("dgaus",dgausformula.Data(),min,max);
+        f->SetLineColor(kYellow);
+        f->SetBit(kCanDelete);
+        f->SetParNames("A_{tot}", "#mu1", "#sigma1", "A2", "#mu2", "#sigma2");
+        f->SetParameters(integ,(min+mean)/2.,width/4.,
+                         integ/width/2.,(max+mean)/2.,width/4.);
+        // The left-sided Gauss
+        f->SetParLimits(0,integ-1.5      , integ+1.5);
+        f->SetParLimits(1,min+(width/10.), mean);
+        f->SetParLimits(2,0              , width/2.);
+        // The right-sided Gauss
+        f->SetParLimits(3,0   , integ);
+        f->SetParLimits(4,mean, max-(width/10.));
+        f->SetParLimits(5,0   , width/2.);
+        obj2->Fit(f,"QLRM");
+        break;
+
+    case 3:
+        f = new TF1("tgaus",tgausformula.Data(),min,max);
+        f->SetLineColor(kYellow);
+        f->SetBit(kCanDelete);
+        f->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}",
+                       "A_{2}","#mu_{2}","#sigma_{2}",
+                       "A_{3}","#mu_{3}","#sigma_{3}");
+        f->SetParameters(integ,(min+mean)/2,width/4.,
+                         integ/width/3.,(max+mean)/2.,width/4.,
+                         integ/width/3.,mean,width/2.);
+        // The left-sided Gauss
+        f->SetParLimits(0,integ-1.5,integ+1.5);
+        f->SetParLimits(1,min+(width/10.),mean);
+        f->SetParLimits(2,width/15.,width/2.);
+        // The right-sided Gauss
+        f->SetParLimits(3,0.,integ);
+        f->SetParLimits(4,mean,max-(width/10.));
+        f->SetParLimits(5,width/15.,width/2.);
+        // The Gauss describing the outliers
+        f->SetParLimits(6,0.,integ);
+        f->SetParLimits(7,min,max);
+        f->SetParLimits(8,width/4.,width/1.5);
+        obj2->Fit(f,"QLRM");
+        break;
+
+    case 4:
+        obj2->Fit("pol0", "Q");
+        obj2->GetFunction("pol0")->SetLineColor(kYellow);
+        break;
+
+    case 9:
+        break;
+
+    default:
+        obj2->Fit("gaus", "Q");
+        obj2->GetFunction("gaus")->SetLineColor(kYellow);
+        break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a projection of MHCamera vs. the radius from the central pixel. 
+//
+// The inner and outer pixels are drawn separately, both fitted by a polynomial
+// of grade 1.
+//
+void MHCamera::DrawRadialProfile() const
+{
+    TProfile *obj2 = (TProfile*)RadialProfile(GetName());
+    obj2->SetDirectory(0);
+    obj2->Draw();
+    obj2->SetBit(kCanDelete);
+
+    if (GetGeomCam().InheritsFrom("MGeomCamMagic"))
+    {
+        TArrayI s0(6);
+        s0[0] = 1;
+        s0[1] = 2;
+        s0[2] = 3;
+        s0[3] = 4;
+        s0[4] = 5;
+        s0[5] = 6;
+
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TProfile *half[2];
+        half[0] = RadialProfileS(s0, inner,Form("%sInner",GetName()));
+        half[1] = RadialProfileS(s0, outer,Form("%sOuter",GetName()));
+
+        for (Int_t i=0; i<2; i++)
+        {
+            Double_t min = GetGeomCam().GetMinRadius(i);
+            Double_t max = GetGeomCam().GetMaxRadius(i);
+
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->Draw("same");
+            half[i]->Fit("pol1","Q","",min,max);
+            half[i]->GetFunction("pol1")->SetLineColor(kRed+i);
+            half[i]->GetFunction("pol1")->SetLineWidth(1);
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a projection of MHCamera vs. the azimuth angle inside the camera.
+//
+// The inner and outer pixels are drawn separately. 
+// The general azimuth profile is fitted by a straight line
+//
+void MHCamera::DrawAzimuthProfile() const
+{
+    TProfile *obj2 = (TProfile*)AzimuthProfile(GetName());
+    obj2->SetDirectory(0);
+    obj2->Draw();
+    obj2->SetBit(kCanDelete);
+    obj2->Fit("pol0","Q","");
+    obj2->GetFunction("pol0")->SetLineWidth(1);
+
+    if (GetGeomCam().InheritsFrom("MGeomCamMagic"))
+    {
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TProfile *half[2];
+        half[0] = AzimuthProfileA(inner,Form("%sInner",GetName()));
+        half[1] = AzimuthProfileA(outer,Form("%sOuter",GetName()));
+
+        for (Int_t i=0; i<2; i++)
+        {
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->SetMarkerSize(0.5);
+            half[i]->Draw("same");
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the MHCamera into the MStatusDisplay: 
+// 
+// 1) Draw it as histogram (MHCamera::DrawCopy("hist")
+// 2) Draw it as a camera, with MHCamera::SetPrettyPalette() set. 
+// 3) If "rad" is not zero, draw its values vs. the radius from the camera center. 
+//    (DrawRadialProfile())
+// 4) Depending on the variable "fit", draw the values projection on the y-axis
+//    (DrawProjection()):
+//    0: don't draw
+//    1: Draw fit to Single Gauss (for distributions flat-fielded over the whole camera)
+//    2: Draw and fit to Double Gauss (for distributions different for inner and outer pixels)
+//    3: Draw and fit to Triple Gauss (for distributions with inner, outer pixels and outliers)
+//    4: Draw and fit to Polynomial grade 0: (for the probability distributions)
+//    >4: Draw and don;t fit.
+//
+void MHCamera::CamDraw(TCanvas &c, const Int_t x, const Int_t y, 
+                       const Int_t fit, const Int_t rad, const Int_t azi,
+                       TObject *notify)
+{
+    c.cd(x);
+    gPad->SetBorderMode(0);
+    gPad->SetTicks();
+    MHCamera *obj1=(MHCamera*)DrawCopy("hist");
+    obj1->SetDirectory(NULL);
+
+    if (notify)
+        obj1->AddNotify(notify);
+
+    c.cd(x+y);
+    gPad->SetBorderMode(0);
+    obj1->SetPrettyPalette();
+    obj1->Draw();
+
+    Int_t cnt = 2;
+
+    if (rad)
+    {
+        c.cd(x+2*y);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+        DrawRadialProfile();
+        cnt++;
+    }
+
+    if (azi)
+    {
+        c.cd(x+cnt*y);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+        DrawAzimuthProfile();
+        cnt++;
+    }
+
+    if (!fit)
+        return;
+
+    c.cd(x + cnt*y);
+    gPad->SetBorderMode(0);
+    gPad->SetTicks();
+    DrawProjection(fit);
+}
Index: /tags/Mars-V0.9/mhist/MHCamera.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHCamera.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCamera.h	(revision 9772)
@@ -0,0 +1,448 @@
+#ifndef MARS_MHCamera
+#define MARS_MHCamera
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef ROOT_MArrayD
+#include <MArrayD.h>
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+#ifndef ROOT_TCanvas
+#include <TCanvas.h>
+#endif
+
+class TPaveStats;
+class TProfile;
+
+class MGeomCam;
+class MCamEvent;
+class MRflEvtData;
+class MCerPhotEvt;
+class MImgCleanStd;
+
+class MHCamera : public TH1D
+{
+public:
+    enum {
+        kProfile            = BIT(18), // FIXME: When changing change max/min!
+        kFreezed            = BIT(19),
+        kNoLegend           = BIT(20)/*,
+        kSqrtVariance       = BIT(21),
+        kSinglePixelProfile = BIT(22)*/
+    };
+private:
+    MGeomCam      *fGeomCam;     // pointer to camera geometry (y-axis)
+    TArrayC        fUsed;        // array containing flags
+    TArrayI        fBinEntries;  // number of entries per bin
+
+    TArrayI        fColors;      //! Color conversion table
+    TList         *fNotify;      //!
+
+//#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,03)
+    Bool_t         fFreezed;     //! Just a dummy!!!! ([Set,Is]Freezed)
+//#endif
+
+    Float_t fAbberation;
+
+    void Init();
+/*
+    Stat_t Profile(Stat_t val) const
+    {
+        if (!TestBit(kProfile))
+            return val;
+
+        const Stat_t n = TH1D::GetEntries();
+        return n>0 ? val/n : val;
+    }
+  */
+    Int_t GetColor(Float_t val, Float_t min, Float_t max, Bool_t islog);
+
+    void  PaintIndices(Int_t type);
+    void  Update(Bool_t islog, Bool_t isbox, Bool_t iscol, Bool_t issame);
+    void  UpdateLegend(Float_t min, Float_t max, Bool_t islog);
+    void  SetRange();
+
+    TPaveStats *GetStatisticBox();
+
+    Int_t GetPixelIndex(Int_t px, Int_t py, Float_t conv=1) const;
+
+    void PaintAxisTitle();
+
+    enum {
+        kIsUsed = BIT(1)
+    };
+
+    void   ResetUsed(Int_t idx)    { CLRBIT(fUsed[idx], kIsUsed); }
+
+    Bool_t FindVal(const TArrayI &arr, Int_t val) const
+    {
+        const Int_t n = arr.GetSize();
+        if (n==0)
+            return kTRUE;
+
+        const Int_t *p = arr.GetArray();
+        const Int_t *end = p+n;
+        while (p<end)
+            if (val==*p++)
+                return kTRUE;
+
+        return kFALSE;
+    }
+    Bool_t MatchSector(Int_t idx, const TArrayI &sector, const TArrayI &aidx) const;
+
+    // This is a trick to remove TH1 entries from the context menu
+    TH1 *Rebin(Int_t ngroup=2, const char*newname="") { return this; }
+    void DrawPanel() {}
+
+    Int_t Fill(Axis_t x);
+    Int_t Fill(const char *name, Stat_t w) { return -1; }
+    void  FillN(Int_t ntimes, const Axis_t *x, const Double_t *w, Int_t stride=1) {}
+    void  FillN(Int_t, const Axis_t *, const Axis_t *, const Double_t *, Int_t) {}
+
+public:
+    MHCamera();
+    MHCamera(const MGeomCam &geom, const char *name="", const char *title="");
+    ~MHCamera();
+
+    void SetGeometry(const MGeomCam &geom, const char *name="", const char *title="");
+    const MGeomCam* GetGeometry() const { return fGeomCam; }
+
+    Bool_t IsUsed(Int_t idx) const { return TESTBIT(const_cast<TArrayC&>(fUsed)[idx], kIsUsed); }
+    void   SetUsed(Int_t idx)      { SETBIT(fUsed[idx], kIsUsed); }
+    void   SetAllUsed()            { fUsed.Reset(BIT(kIsUsed)); }
+
+    Int_t Fill(Axis_t x, Axis_t y, Stat_t w);
+    Int_t Fill(Axis_t x, Stat_t w);
+
+    //void     AddPixContent(Int_t idx) const { AddBinContent(idx+1); }
+    //void     AddPixContent(Int_t idx, Stat_t w) const { AddBinContent(idx+1, w); }
+
+    // This is a trick to remove TH1 entries from the context menu
+    /*
+     void Add(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1) { TH1::Add(h1, h2, c1, c2); }
+     void Add(TF1 *h1, Double_t c1=1) { TH1::Add(h1, c1); }
+     void Add(const TH1 *h1, Double_t c1=1) { TH1::Add(h1, c1); }
+     void Divide(TF1 *f1, Double_t c1=1) { TH1::Divide(f1, c1); }
+     void Divide(const TH1 *h1) { TH1::Divide(h1); }
+     void Divide(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option="") { TH1::Divide(h1, h2, c1, c2, option); }
+     void Multiply(TF1 *h1, Double_t c1=1) { TH1::Multiply(h1, c1); }
+     void Multiply(const TH1 *h1) { TH1::Multiply(h1); }
+     void Multiply(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option="") { TH1::Multiply(h1, h2, c1, c2, option); }
+     */
+
+    void FitPanel() { TH1::FitPanel(); }
+
+    virtual Double_t GetPixContent(Int_t idx) const { return GetBinContent(idx+1); }
+    virtual void     AddCamContent(const MCamEvent &evt, Int_t type=0);
+    virtual void     AddCamContent(const MHCamera &evt, Int_t type=0);
+    virtual void     AddCamContent(const TArrayD &arr, const TArrayC *used=NULL);
+    virtual void     AddCamContent(const MArrayD &arr, const TArrayC *used=NULL);
+    virtual void     SetCamContent(const MCamEvent &evt, Int_t type=0) { Reset(); AddCamContent(evt, type); }
+    virtual void     SetCamContent(const MHCamera &d, Int_t type=0) { Reset(); AddCamContent(d, type); fEntries=d.fEntries; }
+    virtual void     SetCamContent(const TArrayD &evt, const TArrayC *used=NULL) { Reset(); AddCamContent(evt, used); }
+    virtual void     SetCamContent(const MArrayD &evt, const TArrayC *used=NULL) { Reset(); AddCamContent(evt, used); }
+
+    virtual void     SetCamError(const MCamEvent &evt, Int_t type=0);
+    virtual void     SetUsed(const TArrayC &arr);
+
+    virtual void     CntCamContent(const MCamEvent &evt, Double_t threshold, Int_t type=0, Bool_t isabove=kTRUE);
+    virtual void     CntCamContent(const MCamEvent &evt, TArrayD threshold, Int_t type=0, Bool_t isabove=kTRUE);
+    virtual void     CntCamContent(const TArrayD &evt, Double_t threshold, Bool_t ispos=kTRUE);
+    virtual void     CntCamContent(const MCamEvent &event, Int_t type1, const MCamEvent &thresevt, Int_t type2, Double_t threshold, Bool_t isabove);
+
+    Stat_t   GetBinContent(Int_t bin) const;
+    Stat_t   GetBinContent(Int_t binx, Int_t biny) const { return GetBinContent(binx); }
+    Stat_t   GetBinContent(Int_t binx, Int_t biny, Int_t binz) const { return GetBinContent(binx); }
+    Stat_t   GetBinError(Int_t bin) const;
+    Stat_t   GetBinError(Int_t binx, Int_t biny) const { return GetBinError(binx); }
+    Stat_t   GetBinError(Int_t binx, Int_t biny, Int_t binz) const { return GetBinError(binx); }
+
+    Double_t GetMinimum(Bool_t all) const { return GetMinimumSectors(TArrayI(), TArrayI(), all); }
+    Double_t GetMaximum(Bool_t all) const { return GetMaximumSectors(TArrayI(), TArrayI(), all); }
+
+    Double_t GetMinimum(Double_t gt) const { return GetMinimumSectors(TArrayI(), TArrayI(), kFALSE); } // FIXME: To be done: Minimum greater than
+    Double_t GetMaximum(Double_t lt) const { return GetMaximumSectors(TArrayI(), TArrayI(), kFALSE); } // FIXME: To be done: Maximum lower than
+
+    Double_t GetMinimum() const { return GetMinimum(0.0); } // FIXME: To be done: Minimum greater than
+    Double_t GetMaximum() const { return GetMaximum(0.0); } // FIXME: To be done: Maximum lower than
+
+    Double_t GetMinimumSector(Int_t sector, Int_t aidx, Bool_t all=kFALSE) const
+    {
+        return GetMinimumSectors(TArrayI(1, &sector), TArrayI(1, &aidx), all);
+    }
+    Double_t GetMaximumSector(Int_t sector, Int_t aidx, Bool_t all=kFALSE) const
+    {
+        return GetMaximumSectors(TArrayI(1, &sector), TArrayI(1, &aidx), all);
+    }
+    Double_t GetMinimumSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all=kFALSE) const;
+    Double_t GetMaximumSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all=kFALSE) const;
+
+    void     SetLevels(const TArrayF &arr);
+
+    void     FillRandom(const char *fname, Int_t ntimes=5000) { TH1::FillRandom(fname, ntimes); }
+    void     FillRandom(TH1 *h, Int_t ntimes=5000) { TH1::FillRandom(h, ntimes); }
+    void     FillRandom();
+
+    void     PrintInfo() const { Print(""); } // *MENU*
+    void     Reset(Option_t *);
+    void     Reset() { Reset(""); } // *MENU*
+    TH1     *DrawCopy() const/* { gPad=NULL; return TH1D::DrawCopy(); }*/; // *MENU*
+    TH1     *DrawCopy(Option_t *o) const { return TH1D::DrawCopy(o); }
+
+    void     Print(Option_t *) const;
+    void     Paint(Option_t *option="");
+    void     Draw(Option_t *option="");
+    TObject *DrawClone(Option_t *option="") const;
+    void     DrawProjection (Int_t fit=0) const;
+    void     DrawRadialProfile()           const;
+    void     DrawAzimuthProfile()          const;
+
+    void     SavePrimitive(ofstream &out, Option_t *);
+    Int_t    DistancetoPrimitive(Int_t px, Int_t py);
+    char    *GetObjectInfo(Int_t px, Int_t py) const;
+    void     ExecuteEvent(Int_t event, Int_t px, Int_t py);
+
+    void     SetPalette(Int_t ncolors, Int_t *colors);
+
+    void     SetPrettyPalette(); // *MENU*
+    void     SetDeepBlueSeaPalette(); // *MENU*
+    void     SetInvDeepBlueSeaPalette(); // *MENU*
+
+    void     SetAutoScale() { fMinimum = fMaximum = -1111; } // *MENU*
+    void     DisplayAsHistogram() { SetDrawOption("histEP"); } // *MENU*
+    void     DisplayAsCamera() { SetDrawOption(""); } // *MENU*
+
+    void     SetFreezed(Bool_t f=kTRUE) { f ? SetBit(kFreezed) : ResetBit(kFreezed); } // *TOGGLE* *GETTER=IsFreezed
+    Bool_t   IsFreezed() const { return TestBit(kFreezed); }
+    //void  SetOptStat(Int_t os=-1) { fOptStat = os; } // *MENU*
+
+    void     SetAbberation(Float_t f=0.0713) { fAbberation=f; } // *MENU*
+
+    void     AddNotify(TObject *event);
+
+    Stat_t   GetMean(Bool_t all) const { return GetMeanSectors(TArrayI(), TArrayI(), all); }
+    Stat_t   GetRMS(Bool_t all)  const { return GetRmsSectors(TArrayI(), TArrayI(), all); }
+
+    Stat_t   GetMean(Int_t=0) const { return GetMeanSectors(TArrayI(), TArrayI(), kFALSE); }
+    Stat_t   GetRMS(Int_t=0)  const { return GetRmsSectors(TArrayI(), TArrayI(), kFALSE); }
+
+    Stat_t   GetMeanSector(Int_t sector, Int_t aidx, Bool_t all=kFALSE) const
+    {
+        return GetMeanSectors(TArrayI(1, &sector), TArrayI(1, &aidx), all);
+    }
+    Stat_t   GetRmsSector(Int_t sector, Int_t aidx, Bool_t all=kFALSE) const
+    {
+        return GetRmsSectors(TArrayI(1, &sector), TArrayI(1, &aidx), all);
+    }
+
+    Stat_t   GetMeanSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all=kFALSE) const;
+    Stat_t   GetRmsSectors(const TArrayI &sector, const TArrayI &aidx, Bool_t all=kFALSE) const;
+
+    UInt_t   GetNumPixels() const;
+
+    TH1D    *Projection(const char *name="_py", const Int_t nbins=50) const
+      {
+        return ProjectionS(TArrayI(), TArrayI(), name,nbins);
+      }
+    TH1D    *ProjectionS(Int_t sector, Int_t aidx, const char *name="_py", const Int_t nbins=50) const
+    {
+        return ProjectionS(TArrayI(1, &sector), TArrayI(1, &aidx), name, nbins);
+    }
+    TH1D    *ProjectionS(const TArrayI &sector, const TArrayI &aidx, const char *name="_py", const Int_t nbins=50) const;
+
+    TProfile *RadialProfile(const char *name="_rad", Int_t nbins=25) const { return  RadialProfileS(TArrayI(), TArrayI(), name, nbins);}
+    TProfile *RadialProfileS(Int_t sector, Int_t aidx, const char *name="_rad", const Int_t nbins=25) const
+    {
+        return RadialProfileS(TArrayI(1, &sector), TArrayI(1, &aidx), name, nbins);
+    }
+    TProfile *RadialProfileS(const TArrayI &sector, const TArrayI &aidx, const char *name="_rad", const Int_t nbins=25) const;
+
+    TProfile *AzimuthProfile(const char *name="_azi", Int_t nbins=25) const { return  AzimuthProfileA(TArrayI(), name, nbins);  }
+    TProfile *AzimuthProfile(Int_t aidx, const char *name="_rad", const Int_t nbins=25) const
+      {
+        return AzimuthProfileA(TArrayI(1, &aidx), name, nbins);
+      }
+    TProfile *AzimuthProfileA(const TArrayI &aidx, const char *name="_rad", const Int_t nbins=25) const;
+    
+    void CamDraw(TCanvas &c, const Int_t x, const Int_t y, 
+                 const Int_t fit, const Int_t rad=0, const Int_t azi=0,
+                 TObject *notify=NULL);             
+    
+    const MGeomCam &GetGeomCam() const { return *fGeomCam; }
+
+    ClassDef(MHCamera, 1) // Displays the magic camera
+};
+
+#endif
+
+/* ------------ OK ---------------
+ virtual void     Browse(TBrowser *b);
+ virtual void     FillRandom(const char *fname, Int_t ntimes=5000);
+ virtual void     FillRandom(TH1 *h, Int_t ntimes=5000);
+
+ virtual Int_t    GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum=0);
+ virtual Axis_t   GetRandom();
+ virtual void     GetStats(Stat_t *stats) const;
+ virtual Stat_t   GetSumOfWeights() const;
+ virtual Int_t    GetSumw2N() const {return fSumw2.fN;}
+ virtual Stat_t   GetRMS(Int_t axis=1) const;
+
+ virtual Int_t    GetNbinsX() const {return fXaxis.GetNbins();}
+ virtual Int_t    GetNbinsY() const {return fYaxis.GetNbins();}
+ virtual Int_t    GetNbinsZ() const {return fZaxis.GetNbins();}
+
+ // ------------- to check -------------------
+
+ virtual Double_t ComputeIntegral();
+ virtual Int_t    DistancetoPrimitive(Int_t px, Int_t py);
+ virtual void     Draw(Option_t *option="");
+ virtual TH1     *DrawCopy(Option_t *option="") const;
+ virtual TH1     *DrawNormalized(Option_t *option="", Double_t norm=1) const;
+ virtual Int_t    BufferEmpty(Bool_t deleteBuffer=kFALSE);
+ virtual void     Eval(TF1 *f1, Option_t *option="");
+ virtual void     ExecuteEvent(Int_t event, Int_t px, Int_t py);
+ virtual void     FillN(Int_t ntimes, const Axis_t *x, const Double_t *w, Int_t stride=1);
+ virtual void     FillN(Int_t, const Axis_t *, const Axis_t *, const Double_t *, Int_t) {;}
+ virtual Int_t    FindBin(Axis_t x, Axis_t y=0, Axis_t z=0);
+ virtual TObject *FindObject(const char *name) const;
+ virtual TObject *FindObject(const TObject *obj) const;
+ virtual Int_t    Fit(const char *formula ,Option_t *option="" ,Option_t *goption="", Axis_t xmin=0, Axis_t xmax=0); // *MENU*
+ virtual Int_t    Fit(TF1 *f1 ,Option_t *option="" ,Option_t *goption="", Axis_t xmin=0, Axis_t xmax=0);
+ virtual void     FitPanel(); // *MENU*
+ TH1             *GetAsymmetry(TH1* h2, Double_t c2=1, Double_t dc2=0);
+ Int_t            GetBufferLength() const {return (Int_t)fBuffer[0];}
+ Int_t            GetBufferSize  () const {return fBufferSize;}
+ const   Double_t *GetBuffer() const {return fBuffer;}
+ static  Int_t    GetDefaultBufferSize();
+ virtual Double_t *GetIntegral() {return fIntegral;}
+
+ TList           *GetListOfFunctions() const { return fFunctions; }
+
+ virtual Int_t    GetNdivisions(Option_t *axis="X") const;
+ virtual Color_t  GetAxisColor(Option_t *axis="X") const;
+ virtual Color_t  GetLabelColor(Option_t *axis="X") const;
+ virtual Style_t  GetLabelFont(Option_t *axis="X") const;
+ virtual Float_t  GetLabelOffset(Option_t *axis="X") const;
+ virtual Float_t  GetLabelSize(Option_t *axis="X") const;
+ virtual Float_t  GetTitleOffset(Option_t *axis="X") const;
+ virtual Float_t  GetTitleSize(Option_t *axis="X") const;
+ virtual Float_t  GetTickLength(Option_t *axis="X") const;
+ virtual Float_t  GetBarOffset() const {return Float_t(0.001*Float_t(fBarOffset));}
+ virtual Float_t  GetBarWidth() const  {return Float_t(0.001*Float_t(fBarWidth));}
+ virtual Int_t    GetContour(Double_t *levels=0);
+ virtual Double_t GetContourLevel(Int_t level) const;
+ virtual Double_t GetContourLevelPad(Int_t level) const;
+
+ virtual void     GetCenter(Axis_t *center) const {fXaxis.GetCenter(center);}
+ TDirectory      *GetDirectory() const {return fDirectory;}
+ virtual Stat_t   GetEntries() const;
+ virtual TF1     *GetFunction(const char *name) const;
+ virtual Int_t    GetDimension() const { return fDimension; }
+ virtual void     GetLowEdge(Axis_t *edge) const {fXaxis.GetLowEdge(edge);}
+ virtual Double_t GetMaximum() const;
+ virtual Int_t    GetMaximumBin() const;
+ virtual Int_t    GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const;
+ virtual Double_t GetMaximumStored() const {return fMaximum;}
+ virtual Double_t GetMinimum() const;
+ virtual Int_t    GetMinimumBin() const;
+ virtual Int_t    GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const;
+ virtual Double_t GetMinimumStored() const {return fMinimum;}
+ virtual Stat_t   GetMean(Int_t axis=1) const;
+ virtual Double_t GetNormFactor() const {return fNormFactor;}
+ virtual char    *GetObjectInfo(Int_t px, Int_t py) const;
+ Option_t        *GetOption() const {return fOption.Data();}
+
+ TVirtualHistPainter *GetPainter();
+
+ TAxis   *GetXaxis() const;
+ TAxis   *GetYaxis() const;
+ TAxis   *GetZaxis() const;
+ virtual Stat_t   Integral(Option_t *option="") const;
+ virtual Stat_t   Integral(Int_t binx1, Int_t binx2, Option_t *option="") const;
+ virtual Stat_t   Integral(Int_t, Int_t, Int_t, Int_t, Option_t * ="") const {return 0;}
+ virtual Stat_t   Integral(Int_t, Int_t, Int_t, Int_t, Int_t, Int_t, Option_t * ="" ) const {return 0;}
+ virtual Double_t KolmogorovTest(TH1 *h2, Option_t *option="") const;
+ virtual void     LabelsDeflate(Option_t *axis="X");
+ virtual void     LabelsInflate(Option_t *axis="X");
+ virtual void     LabelsOption(Option_t *option="h", Option_t *axis="X");
+ virtual Int_t    Merge(TCollection *list);
+ virtual void     Multiply(TF1 *h1, Double_t c1=1);
+ virtual void     Multiply(const TH1 *h1);
+ virtual void     Multiply(const TH1 *h1, const TH1 *h2, Double_t c1=1, Double_t c2=1, Option_t *option=""); // *MENU*
+ virtual void     Paint(Option_t *option="");
+ virtual void     Print(Option_t *option="") const;
+ virtual void     PutStats(Stat_t *stats);
+ virtual TH1     *Rebin(Int_t ngroup=2, const char*newname="");  // *MENU*
+ virtual void     RebinAxis(Axis_t x, Option_t *axis="X");
+ virtual void     Rebuild(Option_t *option="");
+ virtual void     RecursiveRemove(TObject *obj);
+ virtual void     Reset(Option_t *option="");
+ virtual void     SavePrimitive(ofstream &out, Option_t *option);
+ virtual void     Scale(Double_t c1=1);
+ virtual void     SetAxisColor(Color_t color=1, Option_t *axis="X");
+ virtual void     SetAxisRange(Axis_t xmin, Axis_t xmax, Option_t *axis="X");
+ virtual void     SetBarOffset(Float_t offset=0.25) {fBarOffset = Short_t(1000*offset);}
+ virtual void     SetBarWidth(Float_t width=0.5) {fBarWidth = Short_t(1000*width);}
+ virtual void     SetBinContent(Int_t bin, Stat_t content);
+ virtual void     SetBinContent(Int_t binx, Int_t biny, Stat_t content);
+ virtual void     SetBinContent(Int_t binx, Int_t biny, Int_t binz, Stat_t content);
+ virtual void     SetBinError(Int_t bin, Stat_t error);
+ virtual void     SetBinError(Int_t binx, Int_t biny, Stat_t error);
+ virtual void     SetBinError(Int_t binx, Int_t biny, Int_t binz, Stat_t error);
+ virtual void     SetBins(Int_t nx, Axis_t xmin, Axis_t xmax);
+ virtual void     SetBins(Int_t nx, Axis_t xmin, Axis_t xmax, Int_t ny, Axis_t ymin, Axis_t ymax);
+ virtual void     SetBins(Int_t nx, Axis_t xmin, Axis_t xmax, Int_t ny, Axis_t ymin, Axis_t ymax,
+ Int_t nz, Axis_t zmin, Axis_t zmax);
+ virtual void     SetBinsLength(Int_t = -1) { } //refefined in derived classes
+ virtual void     SetBuffer(Int_t buffersize, Option_t *option="");
+ virtual void     SetCellContent(Int_t binx, Int_t biny, Stat_t content);
+ virtual void     SetCellError(Int_t binx, Int_t biny, Stat_t content);
+ virtual void     SetContent(const Stat_t *content);
+ virtual void     SetContour(Int_t nlevels, const Double_t *levels=0);
+ virtual void     SetContourLevel(Int_t level, Double_t value);
+ static  void     SetDefaultBufferSize(Int_t buffersize=1000);
+ virtual void     SetDirectory(TDirectory *dir);
+ virtual void     SetEntries(Stat_t n) {fEntries = n;};
+ virtual void     SetError(const Stat_t *error);
+ virtual void     SetLabelColor(Color_t color=1, Option_t *axis="X");
+ virtual void     SetLabelFont(Style_t font=62, Option_t *axis="X");
+ virtual void     SetLabelOffset(Float_t offset=0.005, Option_t *axis="X");
+ virtual void     SetLabelSize(Float_t size=0.02, Option_t *axis="X");
+
+ virtual void     SetMaximum(Double_t maximum=-1111); // *MENU*
+ virtual void     SetMinimum(Double_t minimum=-1111); // *MENU*
+ virtual void     SetName(const char *name); // *MENU*
+ virtual void     SetNameTitle(const char *name, const char *title);
+ virtual void     SetNdivisions(Int_t n=510, Option_t *axis="X");
+ virtual void     SetNormFactor(Double_t factor=1) {fNormFactor = factor;}
+ virtual void     SetStats(Bool_t stats=kTRUE);
+ virtual void     SetOption(Option_t *option=" ") {fOption = option;}
+ virtual void     SetTickLength(Float_t length=0.02, Option_t *axis="X");
+ virtual void     SetTitleOffset(Float_t offset=1, Option_t *axis="X");
+ virtual void     SetTitleSize(Float_t size=0.02, Option_t *axis="X");
+ virtual void     SetTitle(const char *title);
+ virtual void     SetXTitle(const char *title) {fXaxis.SetTitle(title);}
+ virtual void     SetYTitle(const char *title) {fYaxis.SetTitle(title);}
+ virtual void     SetZTitle(const char *title) {fZaxis.SetTitle(title);}
+ virtual void     Smooth(Int_t ntimes=1); // *MENU*
+ static  void     SmoothArray(Int_t NN, Double_t *XX, Int_t ntimes=1);
+ static Double_t  SmoothMedian(Int_t n, Double_t *a);
+ virtual void     Sumw2();
+ void             UseCurrentStyle();
+
+ ClassDef(TH1,4)  //1-Dim histogram base class
+};
+
+*/
Index: /tags/Mars-V0.9/mhist/MHCerPhotEvt.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHCerPhotEvt.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCerPhotEvt.cc	(revision 9772)
@@ -0,0 +1,161 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHCerPhotEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCerPhotEvt.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+#include "MCamDisplay.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MHCerPhotEvt);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task.
+// Resets the sum histogram
+//
+MHCerPhotEvt::MHCerPhotEvt(const char *name, const char *title)
+    : fSum(NULL), fEvt(NULL)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHCerPhotEvt";
+    fTitle = title ? title : "Average of MCerPhotEvts";
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHCerPhotEvt::~MHCerPhotEvt()
+{
+    if (fSum)
+        delete fSum;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MCerPhotEvt) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+//
+Bool_t MHCerPhotEvt::SetupFill(const MParList *plist)
+{
+    fEvt = (MCamEvent*)plist->FindObject(fNameEvt, "MCamEvent");
+    if (!fEvt)
+        *fLog << warn << GetDescriptor() << ": No MCerPhotEvt available..." << endl;
+
+    MGeomCam *cam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!cam)
+        *fLog << warn << GetDescriptor() << ": No MGeomCam found." << endl;
+
+    if (fSum)
+        delete (fSum);
+    fSum = new MCamDisplay(*cam, fNameEvt+";avg", fNameEvt+" Avarage");
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCerPhotEvt-Container.
+//
+Bool_t MHCerPhotEvt::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MCamEvent *evt = par ? dynamic_cast<const MCamEvent*>(par) : fEvt;
+    if (!evt)
+    {
+        *fLog << err << dbginf << "No MCerPhotEvt found..." << endl;
+        return kFALSE;
+    }
+    fSum->AddCamContent(*evt);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scale the sum container with the number of entries
+//
+Bool_t MHCerPhotEvt::Finalize()
+{
+    if (fSum->GetEntries()>0)
+        fSum->Scale(1./fSum->GetEntries());
+    return kTRUE;
+}
+/*
+// --------------------------------------------------------------------------
+//
+// Draw the present 'fill status'
+//
+void MHCerPhotEvt::Draw(Option_t *)
+{
+    if (!fSum)
+    {
+        *fLog << warn << "WARNING - Cannot draw " << GetDescriptor() << ": No Camera Geometry available." << endl;
+        return;
+    }
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this, 750, 600);
+    pad->SetBorderMode(0);
+    //pad->Divide(1,1);
+    //gPad->SetBorderMode(0);
+
+    AppendPad("");
+}
+
+// --------------------------------------------------------------------------
+//
+// If a camera display is not yet assigned, assign a new one.
+//
+void MHCerPhotEvt::Paint(Option_t *option)
+{
+    if (!fSum)
+        return;
+
+    fSum->Paint();
+}
+*/
+
+TH1 *MHCerPhotEvt::GetHistByName(const TString name)
+{
+    return fSum;
+}
Index: /tags/Mars-V0.9/mhist/MHCerPhotEvt.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHCerPhotEvt.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCerPhotEvt.h	(revision 9772)
@@ -0,0 +1,34 @@
+#ifndef MARS_MHCerPhotEvt
+#define MARS_MHCerPhotEvt
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MCamDisplay;
+class MCamEvent;
+
+class MHCerPhotEvt : public MH
+{
+private:
+    MCamDisplay *fSum;      // storing the sum
+    MCamEvent   *fEvt;      //! the current event
+
+    TString fNameEvt;
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+public:
+    MHCerPhotEvt(const char *name=NULL, const char *title=NULL);
+    ~MHCerPhotEvt();
+
+    void SetNameEvt(const TString name) { fNameEvt = name; }
+
+    TH1 *GetHistByName(const TString name="");
+
+    ClassDef(MHCerPhotEvt, 1) // Histogram to sum camera events
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHCompProb.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHCompProb.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCompProb.cc	(revision 9772)
@@ -0,0 +1,243 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz, 5/2002 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHCompProb
+//
+// This class contains different histograms of the Hillas parameters
+//   and composite probabilities based on them.
+//
+///////////////////////////////////////////////////////////////////////
+
+#include "MHCompProb.h"
+
+#include <TH2.h>
+#include <TPad.h>
+#include <TText.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TProfile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MDataChain.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MHCompProb);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms
+//
+MHCompProb::MHCompProb(Int_t nbins, const char *name, const char *title)
+    : fNumLoop(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHCompProb";
+    fTitle = title ? title : "Gamma/Hadron Separation Quality Histograms";
+
+    fData    = new TList;
+    fRules   = new TList;
+    fHists   = new TList;
+    fHistVar = new TList;
+
+    fData->SetOwner();
+    fRules->SetOwner();
+    fHists->SetOwner();
+    fHistVar->SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms
+//
+MHCompProb::~MHCompProb()
+{
+    delete fData;
+    delete fRules;
+    delete fHists;
+    delete fHistVar;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+//
+void MHCompProb::Add(const char *rule, Int_t n, Float_t min, Float_t max)
+{
+    MDataChain &chain = *new MDataChain(rule);
+    fData->Add(&chain);
+
+    TNamed &name = *new TNamed(rule, "");
+    fRules->Add(&name);
+
+    TH1D &hist = *new TH1D(Form("Hist_%s", rule), rule, n, min, max);
+    hist.SetXTitle(rule);
+    hist.SetYTitle("Counts");
+    hist.SetDirectory(NULL);
+    fHists->Add(&hist);
+
+    TH1D &varhist = *new TH1D;
+    varhist.SetName(Form("Var_%s", rule));
+    varhist.SetTitle(rule);
+    varhist.SetXTitle(rule);
+    varhist.SetYTitle("Counts");
+    varhist.SetDirectory(NULL);
+    fHistVar->Add(&varhist);
+}
+
+// --------------------------------------------------------------------------
+//
+//
+//
+Bool_t MHCompProb::SetupFill(const MParList *plist)
+{
+    if (fData->GetSize()==0)
+    {
+        *fLog << err << "No data members spcified for usage... aborting." << endl;
+        return kFALSE;
+    }
+
+    TIter Next(fData);
+    MData *data=NULL;
+    while ((data=(MData*)Next()))
+        if (!data->PreProcess(plist))
+            return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+//
+void MHCompProb::Fill(TList &list)
+{
+    MData *data = NULL;
+
+    TIter NextD(fData);
+    TIter NextH(&list);
+
+    while ((data=(MData*)NextD()))
+    {
+        TH1D *hist = (TH1D*)NextH();
+        hist->Fill(data->GetValue());
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//
+//
+Bool_t MHCompProb::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MMcEvt &mcevt = *(MMcEvt*)par;
+
+    switch (fNumLoop)
+    {
+    case 0:  // First loop : fill the fixed-bin histograms with gammas.
+        if (mcevt.GetPartId() == MMcEvt::kGAMMA)
+            Fill(*fHists);
+        return kTRUE;
+
+    case 1:   //  Second Loop: fill the variable-bin histograms with protons.
+        if (mcevt.GetPartId() != MMcEvt::kGAMMA)
+            Fill(*fHistVar);
+        return kTRUE;
+    default:
+        *fLog << err << "Error - Invalid Loop Number... aborting." << endl;
+        return kFALSE;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//
+//
+Bool_t MHCompProb::Finalize()
+{
+    switch (fNumLoop++)
+    {
+    case 0:
+        *fLog << inf << "Finished filling fixed bin size histograms with gamma-data." << endl;
+        SetBinningHistVar();
+        fHists->Delete();
+        return kTRUE;
+    case 1:
+        *fLog << inf << "Finished filling variable bin size histogram with proton data." << endl;
+        return kTRUE;
+    default:
+        *fLog << err << "Error - Invalid Loop Number... aborting." << endl;
+        return kFALSE;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//
+//
+void MHCompProb::SetBinningHistVar()
+{
+    Int_t nedges = 51; // Number of bins in variable-bin histograms.
+
+    TIter NextH(fHists);
+    TIter NextV(fHistVar);
+    TH1D *hist = NULL;
+    while ((hist=(TH1D*)NextH()))
+    {
+        Int_t n = hist->GetNbinsX();
+
+        TArrayD edges(nedges);
+
+        edges[0]        = hist->GetBinLowEdge(1);
+        edges[nedges-1] = hist->GetBinLowEdge(n+1);
+
+        Float_t newwidth = hist->Integral(1, n)/nedges;
+
+        Int_t jbin = 1;
+        for (Int_t j=1; j<n && jbin<nedges-1; j++)
+        {
+            if (hist->Integral(1, j) <= jbin*newwidth)
+                continue;
+
+            edges[jbin++] = hist->GetBinLowEdge(j+1);
+        }
+
+        MBinning bins;
+        bins.SetEdges(edges);
+
+        SetBinning((TH1D*)NextV(), &bins);
+    }
+}
+
Index: /tags/Mars-V0.9/mhist/MHCompProb.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHCompProb.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCompProb.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifndef MARS_MHCompProb
+#define MARS_MHCompProb
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MParList;
+
+class MHCompProb : public MH
+{
+private:
+    Int_t fNumLoop;   //! Counter of the loop (two eventloops needed)
+
+    TList *fRules;    // Rules describing the used data sets
+
+    TList *fData;     //! MDataChain objects
+    TList *fHists;    //! fixed bin size histograms
+    TList *fHistVar;  // variable bin size histograms
+
+    void Fill(TList &list);
+    void SetBinningHistVar();
+
+public:
+    MHCompProb(Int_t nbins, const char *name=NULL, const char *title=NULL);
+    ~MHCompProb();
+
+    void Add(const char *rule, Int_t n, Float_t min, Float_t max);
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    const TList *GetRules() const   { return fRules; }
+    TList *GetHistVar() const { return fHistVar; }
+
+    ClassDef(MHCompProb, 1) // Histogram to be used for the calculation of the composite probabilities
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHCurrents.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHCurrents.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCurrents.cc	(revision 9772)
@@ -0,0 +1,246 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHCurrents
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCurrents.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MCurrents.h"
+#include "MCamDisplay.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MHCurrents);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Reset all pixels to 0 and reset fEntries to 0.
+//
+void MHCurrents::Clear(const Option_t *)
+{
+    const Int_t n = fCam ? fCam->GetNumPixels() : 577;
+
+    // FIXME: Implement a clear function with setmem
+    fSum.Set(n); // also clears memory
+    fRms.Set(n);
+/*    for (int i=0; i<577; i++)
+    {
+        fSum[i] = 0;
+        fRms[i] = 0;
+    }*/
+
+    fEntries = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task.
+// Resets the sum histogram
+//
+MHCurrents::MHCurrents(const char *name, const char *title)
+    : /*fSum(577), fRms(577), */fCam(NULL), fEvt(NULL), fDispl(NULL)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHCurrents";
+    fTitle = title ? title : "Average of MCurrents";
+
+    Clear();
+
+    fHist.SetName("currents;avg");
+    fHist.SetTitle("Avg.Currents [nA]");
+    fHist.SetXTitle("Pixel Index");
+    fHist.SetYTitle("A [nA]");
+    fHist.SetDirectory(NULL);
+    fHist.SetLineColor(kGreen);
+    fHist.SetMarkerStyle(kFullDotMedium);
+    fHist.SetMarkerSize(0.3);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHCurrents::~MHCurrents()
+{
+    if (fDispl)
+        delete fDispl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MCerPhotEvt) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+//
+Bool_t MHCurrents::SetupFill(const MParList *plist)
+{
+    fEvt = (MCurrents*)plist->FindObject("MCurrents");
+    if (!fEvt)
+        *fLog << warn << GetDescriptor() << ": No MCerPhotEvt available..." << endl;
+
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    /*
+    if (!fCam)
+        *fLog << warn << GetDescriptor() << ": No MGeomCam found... assuming Magic geometry!" << endl;
+    */
+    if (!fCam)
+    {
+        *fLog << err << GetDescriptor() << ": No MGeomCam found... aborting." << endl;
+        return kFALSE;
+    }
+
+    Clear();
+
+    const Int_t n = fSum.GetSize();
+
+    MBinning bins;
+    bins.SetEdges(n, -0.5, n-0.5);
+    bins.Apply(fHist);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCerPhotEvt-Container.
+//
+Bool_t MHCurrents::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MCurrents *evt = par ? (MCurrents*)par : fEvt;
+    if (!evt)
+    {
+        *fLog << err << dbginf << "No MCurrents found..." << endl;
+        return kFALSE;
+    }
+
+    const Int_t n = fSum.GetSize();
+    for (UInt_t idx=0; idx<n; idx++)
+    {
+        Float_t val;
+        if (!evt->GetPixelContent(val, idx))
+            continue;
+
+        fSum[idx] += val;
+        fRms[idx] += val*val;
+
+    }
+
+    fEntries++;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scale the sum container with the number of entries
+//
+Bool_t MHCurrents::Finalize()
+{
+    if (fEntries<2)
+    {
+        *fLog << warn << "WARNING - " << GetDescriptor() << " doesn't contain enough entries." << endl;
+        return kTRUE;
+    }
+
+    const Int_t n = fSum.GetSize();
+    for (UInt_t i=0; i<n; i++)
+    {
+        // calc sdev^2 for pixel index i
+        // var^2 = (sum[xi^2] - sum[xi]^2/n) / (n-1);
+        fRms[i] -= fSum[i]*fSum[i]/fEntries;
+        fRms[i] /= fEntries-1;
+
+        if (fRms[i]<0)
+        {
+            *fLog << warn << "WARNING - fRms[" << i <<"]= " << fRms[i] << " -> was set to 0 " << endl;
+            fRms[i]=0;
+        }
+
+        else
+            fRms[i]  = TMath::Sqrt(fRms[i]);
+
+        // calc mean value for pixel index i
+        fSum[i] /= fEntries;
+
+        fHist.SetBinContent(i+1, fSum[i]);
+        fHist.SetBinError(  i+1, fRms[i]);
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the present 'fill status'
+//
+void MHCurrents::Draw(Option_t *o)
+{
+    if (!fCam)
+    {
+        *fLog << warn << "WARNING - Cannot draw " << GetDescriptor() << ": No Camera Geometry available." << endl;
+        return;
+    }
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this, 750, 600);
+    pad->SetBorderMode(0);
+
+    SetDrawOption(o);
+    AppendPad("");
+}
+
+// --------------------------------------------------------------------------
+//
+// If a camera display is not yet assigned, assign a new one.
+//
+void MHCurrents::Paint(Option_t *option)
+{
+    if (!fCam)
+    {
+        *fLog << warn << "WARNING - Cannot paint " << GetDescriptor() << ": No Camera Geometry available." << endl;
+        return;
+    }
+
+    if (!fDispl)
+        fDispl = new MCamDisplay(fCam);
+
+    TString opt(GetDrawOption());
+
+    fDispl->Fill(opt.Contains("rms", TString::kIgnoreCase) ? fRms : fSum);
+    fDispl->Paint();
+}
Index: /tags/Mars-V0.9/mhist/MHCurrents.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHCurrents.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHCurrents.h	(revision 9772)
@@ -0,0 +1,55 @@
+#ifndef MARS_MHCurrents
+#define MARS_MHCurrents
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MCurrents;
+class MGeomCam;
+class MCamDisplay;
+
+class MHCurrents : public MH
+{
+private:
+    TArrayF      fSum;      // storing the sum
+    TArrayF      fRms;      // storing the rms
+    Int_t        fEntries;  // number of entries in the histogram
+    MGeomCam    *fCam;      // the present geometry
+    MCurrents   *fEvt;      //! the current event
+    MCamDisplay *fDispl;    //! the camera display
+
+    TH1F         fHist;
+
+public:
+    MHCurrents(const char *name=NULL, const char *title=NULL);
+    ~MHCurrents();
+
+    void Clear(const Option_t *o="");
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    TH1 *GetHistByName(const TString name) { return NULL; }
+
+    const TArrayF &GetSum() const { return fSum; }
+    const TArrayF &GetRms() const { return fRms; }
+
+    const TH1F    &GetHist() const { return fHist; }
+
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *option="");
+
+    ClassDef(MHCurrents, 1) // Histogram to sum camera events
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHEnergyTheta.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHEnergyTheta.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHEnergyTheta.cc	(revision 9772)
@@ -0,0 +1,133 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  1/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHEnergyTheta                                                           //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHEnergyTheta.h"
+
+#include <TCanvas.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+
+#include "MParList.h"
+
+ClassImp(MHEnergyTheta);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Creates the three necessary histograms:
+//   - selected showers (input)
+//   - all showers (input)
+//   - collection area (result)
+//
+MHEnergyTheta::MHEnergyTheta(const char *name, const char *title)
+{ 
+    //   initialize the histogram for the distribution r vs E
+    //
+    //   we set the energy range from 1 Gev to 10000 GeV (in log 5 orders
+    //   of magnitude) and for each order we take 10 subdivision --> 50 xbins
+    //
+    //   we set the radius range from 0 m to 500 m with 10 m bin --> 50 ybins
+
+  
+    fName  = name  ? name  : "MHEnergyTheta";
+    fTitle = title ? title : "Data to Calculate Collection Area";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("\\Theta [\\circ]");
+    fHist.SetZTitle("N");
+}
+
+Bool_t MHEnergyTheta::SetupFill(const MParList *plist)
+{
+    MBinning* binsenergy = (MBinning*)plist->FindObject("BinningE");
+    MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta");
+    if (!binsenergy || !binstheta)
+    {
+        *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(&fHist, binsenergy, binstheta);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains all showers
+//
+Bool_t MHEnergyTheta::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MMcEvt &mcevt = *(MMcEvt*)par;
+
+    fHist.Fill(mcevt.GetEnergy(), mcevt.GetTheta(), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram with all showers
+//
+void MHEnergyTheta::Draw(Option_t* option)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+    pad->SetLogy();
+
+    fHist.Draw(option);
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency (collection area) and set the 'ReadyToSave'
+//  flag
+//
+void MHEnergyTheta::Divide(const TH2D *h1, const TH2D *h2)
+{
+    // Description!
+
+    fHist.Sumw2();
+    fHist.Divide((TH2D*)h1, (TH2D*)h2);
+
+    SetReadyToSave();
+}
Index: /tags/Mars-V0.9/mhist/MHEnergyTheta.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHEnergyTheta.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHEnergyTheta.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHEnergyTheta
+#define MARS_MHEnergyTheta
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MTime;
+class MParList;
+
+class MHEnergyTheta : public MH
+{
+private:
+    TH2D fHist; //! 
+
+public:
+    MHEnergyTheta(const char *name=NULL, const char *title=NULL);
+
+    Bool_t Fill(const MParContainer *cont, const Stat_t w=1);
+
+    void Draw(Option_t *option="");
+
+    Bool_t SetupFill(const MParList *plist);
+
+    const TH2D *GetHist() { return &fHist; }
+    const TH2D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Divide(const TH2D *h1, const TH2D *h2);
+    void Divide(const MHEnergyTheta *h1, const MHEnergyTheta *h2)
+    {
+        Divide(h1->GetHist(), h2->GetHist());
+    }
+
+    ClassDef(MHEnergyTheta, 1)  // Histogram: Energy vs. Theta
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHEnergyTime.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHEnergyTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHEnergyTime.cc	(revision 9772)
@@ -0,0 +1,142 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  1/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHEnergyTime                                                            //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHEnergyTime.h" 
+
+#include <TCanvas.h>
+
+#include "MMcEvt.hxx"
+#include "MTime.h"
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MHEnergyTime);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Creates the three necessary histograms:
+//   - selected showers (input)
+//   - all showers (input)
+//   - collection area (result)
+//
+MHEnergyTime::MHEnergyTime(const char *name, const char *title)
+{ 
+    //   initialize the histogram for the distribution r vs E
+    //
+    //   we set the energy range from 1 Gev to 10000 GeV (in log 5 orders
+    //   of magnitude) and for each order we take 10 subdivision --> 50 xbins
+    //
+    //   we set the radius range from 0 m to 500 m with 10 m bin --> 50 ybins
+
+    fName  = name  ? name  : "MHEnergyTime";
+    fTitle = title ? title : "Data to Calculate Collection Area";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("t [s]");
+    fHist.SetZTitle("N");
+}
+
+Bool_t MHEnergyTime::SetupFill(const MParList *plist)
+{
+    fTime = (MTime*)plist->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << dbginf << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MBinning* binsenergy = (MBinning*)plist->FindObject("BinningE");
+    const MBinning* binstime   = (MBinning*)plist->FindObject("BinningTime");
+    if (!binsenergy || !binstime)
+    {
+        *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(&fHist, binsenergy, binstime);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains all showers
+//
+Bool_t MHEnergyTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MMcEvt &mcevt = *(MMcEvt*)par;
+
+    fHist.Fill(mcevt.GetEnergy(), *fTime, w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram with all showers
+//
+void MHEnergyTime::Draw(Option_t* option)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->SetLogy();
+    fHist.DrawCopy(option);
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency (collection area) and set the 'ReadyToSave'
+//  flag
+//
+void MHEnergyTime::Divide(const TH2D *h1, const TH2D *h2)
+{
+    // Description!
+
+    fHist.Sumw2();
+    fHist.Divide((TH2D*)h1, (TH2D*)h2);
+
+    SetReadyToSave();
+}
Index: /tags/Mars-V0.9/mhist/MHEnergyTime.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHEnergyTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHEnergyTime.h	(revision 9772)
@@ -0,0 +1,43 @@
+#ifndef MARS_MHEnergyTime
+#define MARS_MHEnergyTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH2
+#include "TH2.h"
+#endif
+
+class MTime;
+class MParList;
+
+class MHEnergyTime : public MH
+{
+private:
+    MTime *fTime;
+    TH2D fHist; //! 
+
+public:
+    MHEnergyTime(const char *name=NULL, const char *title=NULL);
+
+    Bool_t Fill(const MParContainer *cont,  const Stat_t w=1);
+
+    void Draw(Option_t *option="");
+
+    Bool_t SetupFill(const MParList *plist);
+
+    const TH2D *GetHist() { return &fHist; }
+    const TH2D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Divide(const TH2D *h1, const TH2D *h2);
+    void Divide(const MHEnergyTime *h1, const MHEnergyTime *h2)
+    {
+        Divide(h1->GetHist(), h2->GetHist());
+    }
+
+    ClassDef(MHEnergyTime, 1)  // Histogram: Energy vs. Time
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHEvent.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHEvent.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHEvent.cc	(revision 9772)
@@ -0,0 +1,370 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          
+//  MHEvent
+//                                                                          
+//  Display a single event in a canvas with as many informations as
+//  possible, such as event number, run number, ...
+//
+//  WARNING: This class is not yet ready!
+//
+//  Input Containers:
+//   MGeomCam
+//   [MTaskList]
+//   [MImgCleanStd]
+//   [MRawEvtData]
+//   [MRawRunHeader]
+//   [MRawEvtHeader]
+//
+//  Output Containers:
+//   -/-
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHEvent.h"
+
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+
+#include "MHCamera.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MParList.h"
+#include "MSignalCam.h"
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"
+#include "MImgCleanStd.h"
+
+ClassImp(MHEvent);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MHEvent::MHEvent(EventType_t type) : fHist(NULL), fType(type)
+{
+    fName = "MHEvent";
+    fTitle = "Single Event display task";
+
+    fClone = new MRawEvtData("MHEventData");
+}
+
+// --------------------------------------------------------------------------
+//
+MHEvent::~MHEvent()
+{
+    if (fHist)
+        delete fHist;
+
+    delete fClone;
+}
+
+Bool_t MHEvent::SetupFill(const MParList *plist)
+{
+    MTaskList *tlist = (MTaskList*)plist->FindObject("MTaskList");
+
+    fImgCleanStd = tlist ? (MImgCleanStd*)tlist->FindObject("MImgCleanStd") : NULL;
+    fMcEvt       = (MMcEvt*)plist->FindObject("MMcEvt");
+
+    fRawEvtData = (MRawEvtData*)plist->FindObject("MRawEvtData");
+    if (!fRawEvtData)
+        *fLog << warn << "MRawEvtData not found..." << endl;
+
+    fRawRunHeader = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!fRawRunHeader)
+        *fLog << warn << dbginf << "MRawRunHeader not found..." << endl;
+
+    fRawEvtHeader = (MRawEvtHeader*)plist->FindObject("MRawEvtHeader");
+    if (!fRawEvtHeader)
+        *fLog << warn << dbginf << "MRawEvtHeader not found..." << endl;
+
+    MGeomCam *cam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << GetDescriptor() << ": No MGeomCam found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fHist)
+        delete (fHist);
+
+    fHist = new MHCamera(*cam);
+    fHist->AddNotify(fClone);
+
+    switch (fType)
+    {
+    case kEvtSignalRaw:
+        fHist->SetName("Signal (raw)");
+        fHist->SetYTitle("S [au]");
+        break;
+    case kEvtSignalDensity:
+        fHist->SetName("Signal density");
+        fHist->SetYTitle("S [au]");
+        break;
+    case kEvtPedestal:
+        fHist->SetName("Pedestal");
+        fHist->SetYTitle("P [au]");
+        break;
+    case kEvtPedestalRMS:
+        fHist->SetName("Pedestal RMS");
+        fHist->SetYTitle("\\sigma_{P} [au]");
+        break;
+    case kEvtPedPhot:
+        fHist->SetName("Pedestal");
+        fHist->SetYTitle("P [\\gamma]");
+        break;
+    case kEvtPedPhotRMS:
+        fHist->SetName("Pedestal RMS");
+        fHist->SetYTitle("\\sigma_{P} [\\gamma]");
+        break;
+    case kEvtCleaningLevels:
+        if (!fImgCleanStd)
+        {
+            *fLog << err << "MImgCleanStd not found... aborting." << endl;
+            return kFALSE;
+        }
+        fHist->SetName("CleanLevels");
+        fHist->SetYTitle("L");
+        break;
+    case kEvtCleaningData:
+        fHist->SetName("CleanData");
+        fHist->SetYTitle("L");
+        break;
+     case kEvtIdxMax:
+        fHist->SetName("Max Slice Idx");
+        fHist->SetYTitle("t [slice id]");
+	fHist->SetPrettyPalette();
+        break;
+     case kEvtArrTime:
+        fHist->SetName("Arrival Time");
+        fHist->SetYTitle("t [slice id]");
+	fHist->SetPrettyPalette();
+        break;
+     case kEvtTrigPix:
+        fHist->SetName("Triggered pix");
+        fHist->SetYTitle("ON/OFF");
+        fHist->SetPrettyPalette();
+        break;
+     case kEvtIslandIndex:
+        fHist->SetName("Island Index");
+        fHist->SetYTitle("Index");
+	fHist->SetPrettyPalette();
+        break;
+    }
+
+    return kTRUE;
+}
+
+Bool_t MHEvent::Fill(const MParContainer *par, const Stat_t weight)
+{
+    if (fHist->IsFreezed())
+        return kTRUE;
+
+    if (!par)
+        return kFALSE;
+
+    const MCamEvent *event = dynamic_cast<const MCamEvent*>(par);
+    if (!event)
+    {
+        *fLog << err << par->GetDescriptor() << " doesn't inherit from MCamEvent... abort." << endl;
+        return kFALSE;
+    }
+
+    if (fRawEvtData)
+        fRawEvtData->Copy(*fClone);
+
+    switch (fType)
+    {
+    case kEvtSignalRaw:   // Get Content without pixel-size scaling
+        fHist->SetCamContent(*event, 3);
+        break;
+    case kEvtSignalDensity:
+        fHist->SetCamContent(*event, 0);
+        break;
+    case kEvtPedestal:
+        fHist->SetCamContent(*event, 0);
+        break;
+    case kEvtPedestalRMS:
+        fHist->SetCamContent(*event, 2);
+        break;
+    case kEvtPedPhot:
+        fHist->SetCamContent(*event, 4);
+        break;
+    case kEvtPedPhotRMS:
+        fHist->SetCamContent(*event, 5);
+        break;
+    case kEvtCleaningLevels:
+        {
+            TArrayF lvl(2);
+            lvl[0] = fImgCleanStd->GetCleanLvl2();
+            lvl[1] = fImgCleanStd->GetCleanLvl1();
+            fHist->SetCamContent(*event, 0);
+            fHist->SetLevels(lvl);
+        }
+        break;
+    case kEvtCleaningData:
+        fHist->SetCamContent(*event, 0);
+        break;
+    case kEvtIdxMax:
+        fHist->SetCamContent(*event, 5);
+        break;
+    case kEvtArrTime:
+        fHist->SetCamContent(*event, 6);
+        break; 
+    case kEvtTrigPix:
+        fHist->SetCamContent(*event, 0);
+        break; 
+    case kEvtIslandIndex:
+        fHist->SetCamContent(*event, 5);
+        break; 
+    }
+
+    TString s;
+    if (fRawEvtHeader)
+    {
+        s += "Event #";
+        s += fRawEvtHeader->GetDAQEvtNumber();
+    }
+    if (fRawEvtHeader && fRawRunHeader)
+        s += " of ";
+
+    if (fRawRunHeader)
+    {
+        s += "Run #";
+        s += fRawRunHeader->GetRunNumber();
+    }
+
+    if (fMcEvt)
+    {
+        TString txt("#splitline{");
+
+        txt += fMcEvt->GetParticleName();
+        txt += " ";
+
+        s.Insert(0, txt);
+
+        s += "}{  E=";
+
+        s+= fMcEvt->GetEnergyStr();
+
+        s += " r=";
+        s += (int)(fMcEvt->GetImpact()/100+.5);
+        s += "m Zd=";
+        s += (int)(fMcEvt->GetTheta()*180/TMath::Pi()+.5);
+        s += "\\circ ";
+        if (fMcEvt->GetPhotElfromShower()>=10000)
+            s += Form("%dk", (Int_t)(fMcEvt->GetPhotElfromShower()/1000.+.5));
+        else
+            if (fMcEvt->GetPhotElfromShower()>=1000)
+                s += Form("%.1fk", fMcEvt->GetPhotElfromShower()/1000.);
+            else
+                s += fMcEvt->GetPhotElfromShower();
+        s += "PhEl}";
+    }
+
+    gPad=NULL;
+    fHist->SetTitle(s);
+
+    return kTRUE;
+}
+
+void MHEvent::Paint(Option_t *)
+{
+    TVirtualPad *pad = gPad;
+
+    pad->GetPad(2)->cd(1);
+    if (gPad->FindObject(Form("Proj_%p", this)))
+    {
+        TH1 *h=fHist->Projection(Form("Proj_%p", this));
+        if (h->GetMaximum()>0)
+            gPad->SetLogy();
+    }
+
+    pad->GetPad(2)->cd(2);
+    if (gPad->FindObject(Form("ProfR_%p", this)))
+        fHist->RadialProfile(Form("ProfR_%p", this));
+
+    pad->GetPad(2)->cd(3);
+    if (gPad->FindObject(Form("ProfA_%p", this)))
+        fHist->AzimuthProfile(Form("ProfA_%p", this));
+}
+
+void MHEvent::Draw(Option_t *)
+{
+    if (!fHist)
+    {
+        *fLog << warn << "MHEvent::Draw - fHist==NULL not initialized." << endl;
+        return;
+    }
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad();
+
+    pad->Divide(2,1);
+
+    pad->cd(1);
+    gPad->SetPad(0.01, 0.01, 0.75, 0.99);
+    gPad->SetBorderMode(0);
+    fHist->Draw();
+
+    pad->cd(2);
+    gPad->SetPad(0.75, 0.01, 0.99, 0.99);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,3);
+
+    pad = gPad;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+
+    TH1 *h = fHist->Projection(Form("Proj_%p", this), 50);
+    h->SetTitle("Projection");
+    h->SetBit(kCanDelete);
+    h->Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+
+    h = (TH1*)fHist->RadialProfile(Form("ProfR_%p", this), 20);
+    h->SetTitle("Radial Profile");
+    h->SetBit(kCanDelete|TH1::kNoStats);
+    h->Draw();
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = (TH1*)fHist->AzimuthProfile(Form("ProfA_%p", this), 30);
+    h->SetTitle("Azimuth Profile");
+    h->SetBit(kCanDelete|TH1::kNoStats);
+    h->Draw();
+}
Index: /tags/Mars-V0.9/mhist/MHEvent.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHEvent.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHEvent.h	(revision 9772)
@@ -0,0 +1,62 @@
+#ifndef MARS_MHEvent
+#define MARS_MHEvent
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MHCamera;
+class MRawEvtData;
+class MRawRunHeader;
+class MRawEvtHeader;
+
+class MMcEvt;
+class MMcTrig;
+class MSignalCam;
+class MImgCleanStd;
+
+class MHEvent : public MH
+{
+public:
+    enum EventType_t {
+        kEvtSignalRaw, kEvtSignalDensity,
+        kEvtPedestal, kEvtPedestalRMS,
+        kEvtPedPhot, kEvtPedPhotRMS,
+        kEvtCleaningLevels, kEvtCleaningData,
+        kEvtIdxMax, kEvtArrTime, kEvtTrigPix, kEvtIslandIndex
+    };
+
+private:
+    MRawEvtData   *fRawEvtData;    //!
+    MRawRunHeader *fRawRunHeader;  //!
+    MRawEvtHeader *fRawEvtHeader;  //!
+
+    MMcEvt        *fMcEvt;         //!
+    MMcTrig       *fMcTrig;        //!
+    MSignalCam    *fCerPhotEvt;    //!
+    MImgCleanStd  *fImgCleanStd;   //!
+
+    MRawEvtData   *fClone;         //->
+
+    MHCamera *fHist;
+
+    EventType_t fType;
+
+    TH1 *GetHistByName(const TString name) { return (TH1*)fHist; }
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t weight=1);
+
+public:
+    MHEvent(EventType_t type=kEvtSignalRaw);
+    ~MHEvent();
+
+    MHCamera *GetHist() { return fHist; }
+
+    void Draw(Option_t *o="");
+    void Paint(Option_t *o="");
+ 
+    ClassDef(MHEvent, 1)
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHFadcCam.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHFadcCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHFadcCam.cc	(revision 9772)
@@ -0,0 +1,194 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHFadcCam
+//
+// This class contains a list of MHFadcPix.
+//
+///////////////////////////////////////////////////////////////////////
+
+#include "MHFadcCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MGeomCam.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MHFadcCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  default constructor
+//  creates an a list of histograms for all pixels and both gain channels
+//
+MHFadcCam::MHFadcCam(/*const Int_t n,*/ MHFadcPix::Type_t t, const char *name, const char *title)
+    : fNumHiGains(-1), fNumLoGains(-1), fType(t)
+{
+    //
+    // set the name and title of this object
+    //
+    fName  = name  ? name  : "MHFadcCam";
+    fTitle = title ? title : "Container for ADC spectra histograms";
+
+    //
+    // loop over all Pixels and create two histograms
+    // one for the Low and one for the High gain
+    // connect all the histogram with the container fHist
+    //
+    fArray = new TObjArray;
+    fArray->SetOwner();
+
+    //    for (Int_t i=0; i<n; i++)
+    //        (*fArray)[i] = new MHFadcPix(i, fType);
+}
+
+// --------------------------------------------------------------------------
+MHFadcCam::~MHFadcCam()
+{
+    delete fArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// Our own clone function is necessary since root 3.01/06 or Mars 0.4
+// I don't know the reason
+//
+TObject *MHFadcCam::Clone(const char *) const
+{
+    const Int_t n = fArray->GetSize();
+
+    //
+    // FIXME, this might be done faster and more elegant, by direct copy.
+    //
+    MHFadcCam *cam = new MHFadcCam(fType);
+
+    cam->fArray->Expand(n);
+
+    for (int i=0; i<n; i++)
+    {
+        delete (*cam->fArray)[i];
+        (*cam->fArray)[i] = (MHFadcPix*)(*fArray)[i]->Clone();
+    }
+    return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// To setup the object we get the number of pixels from a MGeomCam object
+// in the Parameter list.
+//
+Bool_t MHFadcCam::SetupFill(const MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    const Int_t n = cam->GetNumPixels();
+
+    fArray->Delete();
+    fArray->Expand(n);
+
+    for (Int_t i=0; i<n; i++)
+        (*fArray)[i] = new MHFadcPix(i, fType);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+Bool_t MHFadcCam::Fill(const MParContainer *par, const Stat_t w)
+{
+    return Fill((MRawEvtData*)par);
+}
+
+Bool_t MHFadcCam::Fill(const MRawEvtData *par)
+{
+    const Int_t n = fArray->GetSize();
+
+    if (fType==MHFadcPix::kSlices)
+    {
+        const Int_t nhi = par->GetNumHiGainSamples();
+
+        //
+        // skip MC events without FADC information stored
+        //
+        if (nhi==0)
+            return kTRUE;
+
+        const Int_t nlo = par->GetNumLoGainSamples();
+
+        //
+        // First call with nhi!=0
+        //
+        if (fNumHiGains<0)
+            for (int i=0; i<n; i++)
+                (*this)[i].Init(nhi, nlo);
+        else
+        {
+            if (fNumLoGains!=nlo)
+            {
+                *fLog << err << dbginf << "ERROR - Number of lo-gain samples changed from " << fNumLoGains << " to " << nlo << endl;
+                return kFALSE;
+            }
+            if (fNumHiGains!=nhi)
+            {
+                *fLog << err << dbginf << "ERROR - Number of hi-gain samples changed from " << fNumHiGains << " to " << nhi << endl;
+                return kFALSE;
+            }
+        }
+
+        fNumHiGains = nhi;
+        fNumLoGains = nlo;
+    }
+
+    for (int i=0; i<n; i++)
+        if (!(*this)[i].Fill(*par))
+            return kFALSE;
+
+    return kTRUE;
+}
+
+void MHFadcCam::ResetHistograms()
+{
+    const Int_t n = fArray->GetSize();
+    for (Int_t i=0; i<n; i++)
+        ResetEntry(i);
+}
+
+void MHFadcCam::ResetEntry(Int_t i)
+{
+    GetHistHi(i)->Reset();
+    GetHistLo(i)->Reset();
+}
Index: /tags/Mars-V0.9/mhist/MHFadcCam.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHFadcCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHFadcCam.h	(revision 9772)
@@ -0,0 +1,75 @@
+#ifndef MARS_MHFadcCam
+#define MARS_MHFadcCam
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef MARS_MHFadcPix
+#include "MHFadcPix.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MRawEvtData;
+
+class MHFadcCam : public MH
+{
+private:
+    TObjArray *fArray;	//-> List of Lo/Hi gain Histograms
+
+    //    void FillHi(UInt_t ipix, Byte_t data) { (*this)[ipix]->FillHi(data); }
+    //    void FillLo(UInt_t ipix, Byte_t data) { (*this)[ipix]->FillLo(data); }
+
+    Int_t fNumHiGains; //!
+    Int_t fNumLoGains; //!
+
+    MHFadcPix::Type_t fType; //!
+
+public:
+    MHFadcCam(/*const Int_t n=577,*/ MHFadcPix::Type_t t=MHFadcPix::kValue, const char *name=NULL, const char *title=NULL);
+    ~MHFadcCam();
+
+    MHFadcPix &operator[](UInt_t i) { return *(MHFadcPix*)(fArray->At(i)); }
+    const MHFadcPix &operator[](UInt_t i) const { return *(MHFadcPix*)(fArray->At(i)); }
+
+    TH1F *GetHistHi(UInt_t i)  { return (*this)[i].GetHistHi(); }
+    TH1F *GetHistLo(UInt_t i)  { return (*this)[i].GetHistLo(); }
+
+    const TH1F *GetHistHi(UInt_t i) const { return (*this)[i].GetHistHi(); }
+    const TH1F *GetHistLo(UInt_t i) const { return (*this)[i].GetHistLo(); }
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Fill(const MRawEvtData *par);
+
+    void ResetHistograms();
+    void ResetEntry(Int_t i);
+
+    //
+    // FIXME! This should be replaced by a Draw(Option_t)-function
+    //
+    void DrawHi(UInt_t i)      { GetHistHi(i)->Draw(); }
+    void DrawLo(UInt_t i)      { GetHistLo(i)->Draw(); }
+
+    Bool_t HasLo(UInt_t i) const { return GetHistLo(i)->GetEntries()>0; }
+    Bool_t HasHi(UInt_t i) const { return GetHistHi(i)->GetEntries()>0; }
+
+    Bool_t Exists(UInt_t i) const { return HasLo(i) && HasHi(i); }
+
+    void DrawPix(UInt_t i)     { (*this)[i].Draw(); }
+
+    Int_t GetEntries() const   { return fArray->GetEntries(); }
+
+    TObject *Clone(const char *opt="") const;
+
+    ClassDef(MHFadcCam, 1) // A list of histograms storing the Fadc spektrum of one pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhist/MHFadcPix.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHFadcPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHFadcPix.cc	(revision 9772)
@@ -0,0 +1,171 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHFadcPix
+//
+// This container stores a histogram to display an Fadc Spektrum.
+// The spektrum of all the values measured by the Fadcs.
+//
+///////////////////////////////////////////////////////////////////////
+#include "MHFadcPix.h"
+
+#include <TPad.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MHFadcPix);
+
+// --------------------------------------------------------------------------
+//
+// Creates the histograms for lo and hi gain of one pixel
+//
+MHFadcPix::MHFadcPix(Int_t pixid, Type_t t)
+    : fPixId(pixid), fType(t)
+{
+    fHistHi.SetName(pixid>=0 ? Form("HiGain%03d", pixid) : "HiGain");
+    fHistHi.SetTitle(pixid>=0 ? Form("Hi Gain Pixel #%d", pixid) : "Hi Gain Samples");
+    fHistHi.SetDirectory(NULL);
+    fHistHi.UseCurrentStyle();
+
+    fHistLo.SetName(pixid>=0 ? Form("LoGain%03d", pixid) : "LoGain");
+    fHistLo.SetTitle(pixid>=0 ? Form("Lo Gain Pixel #%d", pixid) : "Lo Gain Samples");
+    fHistLo.SetDirectory(NULL);
+    fHistLo.UseCurrentStyle();
+
+    if (fType==kValue)
+    {
+        fHistHi.SetXTitle("Signal/FADC Units");
+        fHistLo.SetXTitle("Signal/FADC Units");
+        fHistHi.SetYTitle("Count");
+        fHistLo.SetYTitle("Count");
+
+        MBinning bins;
+        bins.SetEdges(255, -.5, 255.5);
+
+        bins.Apply(fHistHi);
+        bins.Apply(fHistLo);
+    }
+    else
+    {
+        fHistHi.SetXTitle("Time/FADC Slices");
+        fHistLo.SetXTitle("Time/FADC Slices");
+        fHistLo.SetYTitle("Sum Signal/FADC Units");
+        fHistHi.SetYTitle("Sum Signal/FADC Units");
+    }
+}
+
+void MHFadcPix::Init(Byte_t nhi, Byte_t nlo)
+{
+    MBinning bins;
+
+    bins.SetEdges(nhi, -.5, -.5+nhi);
+    bins.Apply(fHistHi);
+
+    bins.SetEdges(nlo, -.5, -.5+nlo);
+    bins.Apply(fHistLo);
+}
+
+Bool_t MHFadcPix::Fill(const MRawEvtData &evt)
+{
+    MRawEvtPixelIter pixel((MRawEvtData*)&evt);
+
+    if (!pixel.Jump(fPixId))
+        return kTRUE;
+
+    const Int_t nhisamples = evt.GetNumHiGainSamples();
+
+    if (fType==kValue)
+        for (Int_t i=0; i<nhisamples; i++)
+            fHistHi.Fill(pixel.GetHiGainSamples()[i]);
+    else
+        for (Int_t i=0; i<nhisamples; i++)
+            fHistHi.Fill(i, pixel.GetHiGainSamples()[i]);
+
+    if (!pixel.HasLoGain())
+        return kTRUE;
+
+    const Int_t nlosamples = evt.GetNumLoGainSamples();
+
+    if (fType==kValue)
+        for (Int_t i=0; i<nlosamples; i++)
+            fHistLo.Fill(pixel.GetLoGainSamples()[i]);
+    else
+        for (Int_t i=0; i<nlosamples; i++)
+            fHistLo.Fill(i, pixel.GetLoGainSamples()[i]);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+void MHFadcPix::DrawHi()
+{
+    fHistHi.Draw();
+}
+
+// --------------------------------------------------------------------------
+void MHFadcPix::DrawLo()
+{
+    fHistLo.Draw();
+}
+
+// --------------------------------------------------------------------------
+//
+// We need our own clone function to get rid of the histogram in any
+// directory
+//
+TObject *MHFadcPix::Clone(const char *) const
+{
+    MHFadcPix &pix = *(MHFadcPix*)TObject::Clone();
+
+    pix.fHistHi.SetDirectory(NULL);
+    pix.fHistLo.SetDirectory(NULL);
+
+    return &pix;
+}
+
+// --------------------------------------------------------------------------
+void MHFadcPix::Draw(Option_t *)
+{
+    if (!gPad)
+    {
+        const char *name = StrDup(fPixId ? Form("Pixel #%d", fPixId) : "Pixel");
+        MH::MakeDefCanvas(name, fPixId ? Form("%s FADC Samples", name) : "FADC Samples");
+        delete [] name;
+    }
+
+    gPad->Divide(1, 2);
+
+    gPad->cd(1);
+    fHistHi.Draw();
+
+    gPad->cd(2);
+    fHistLo.Draw();
+}
Index: /tags/Mars-V0.9/mhist/MHFadcPix.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHFadcPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHFadcPix.h	(revision 9772)
@@ -0,0 +1,50 @@
+#ifndef MARS_MHFadcPix
+#define MARS_MHFadcPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MRawEvtData;
+
+class MHFadcPix : public MParContainer
+{
+public:
+    enum Type_t { kSlices, kValue };
+
+private:
+    TH1F fHistHi;
+    TH1F fHistLo;
+
+    UInt_t fPixId;
+
+    Type_t fType;
+
+public:
+    MHFadcPix(Int_t pixid=-1, Type_t t=kValue);
+
+    TH1F *GetHistHi() { return &fHistHi; }
+    TH1F *GetHistLo() { return &fHistLo; }
+
+    const TH1F *GetHistHi() const { return &fHistHi; }
+    const TH1F *GetHistLo() const { return &fHistLo; }
+
+    void Init(Byte_t nhi, Byte_t nlo);
+    Bool_t Fill(const MRawEvtData &evt);
+
+    void DrawHi();
+    void DrawLo();
+
+    TObject *Clone(const char *) const;
+
+    void Draw(Option_t *opt=NULL);
+
+    ClassDef(MHFadcPix, 1) // Conatiner to hold two histograms container spektrums for the lo-/hi gain of one pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhist/MHFindSignificance.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHFindSignificance.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHFindSignificance.cc	(revision 9772)
@@ -0,0 +1,2052 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek,  July 2003      <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHFindSignificance
+//
+// determines the significance of a gamma signal in an |alpha| plot
+// 
+//
+// Input : TH1 histogram of |alpha| : with 0 < |alpha| < 90 degrees
+//         alphamin, alphamax :     defining the background region
+//         alphasig           :     defining the signal region for which
+//                                  the significance is calculated
+//         degree : the degree of the polynomial to be fitted to the background
+//                  ( a0 + a1*x + a2*x**2 + a3*x**3 + ...) 
+//
+// Output : 
+//
+//   - polynomial which describes the background in the background region
+//   - the number of events in the signal region (Non)
+//     the number of background events in the signal region (Nbg)
+//   - the number of excess events in the signal region (Nex = Non - Nbg)
+//   - thew effective number of background events (Noff), and gamma :
+//     Nbg = gamma * Noff
+//   - the significance of the gamma signal according to Li & Ma               
+//
+//
+// call member function 'FindSigma' 
+//      to fit the background and to determine the significance  
+//
+// call the member function 'SigmaVsAlpha'
+//      to determine the significance as a function of alphasig
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHFindSignificance.h"
+
+#include <fstream>
+#include <math.h>
+
+#include <TArrayD.h>
+#include <TArrayI.h>
+#include <TH1.h>
+#include <TF1.h>
+#include <TCanvas.h>
+#include <TFitter.h>
+#include <TMinuit.h>
+#include <TPaveText.h>
+#include <TStyle.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMinuitInterface.h"
+
+
+ClassImp(MHFindSignificance);
+
+using namespace std;
+
+const TString MHFindSignificance::gsDefName  = "MHFindSignificance";
+const TString MHFindSignificance::gsDefTitle = "Find Significance in alpha plot";
+
+
+
+// --------------------------------------------------------------------------
+//
+// fcnpoly
+//
+// calculates the chi2 for the fit of the polynomial function 'poly' 
+// to the histogram 'fhist'
+//
+// it is called by CallMinuit() (which is called in FitPolynomial()) 
+//
+// bins of fhist with huge errors are ignored in the calculation of the chi2
+// (the huge errors were set in 'FitPolynomial()')
+//
+
+static void fcnpoly(Int_t &npar, Double_t *gin, Double_t &f, 
+                    Double_t *par, Int_t iflag)
+{
+    TH1 *fhist = (TH1*)gMinuit->GetObjectFit();
+    TF1 *fpoly = fhist->GetFunction("Poly");    
+
+
+    //-------------------------------------------
+
+    Double_t chi2 = 0.0;
+
+    Int_t nbins = fhist->GetNbinsX();
+    Int_t mbins = 0;
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      Double_t content = fhist->GetBinContent(i);
+      Double_t error   = fhist->GetBinError(i);
+      Double_t center  = fhist->GetBinCenter(i);
+
+      //-----------------------------
+      // ignore unwanted points
+      if (error > 1.e19)
+        continue;
+
+      if (content <= 0.0)
+      {
+        gLog << "fcnpoly : bin with zero content; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      if (error <= 0.0)
+      {
+        gLog << "fcnpoly : bin with zero error; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      //-----------------------------
+      mbins++;
+
+      Double_t fu;
+      fu = fpoly->EvalPar(&center, par);
+
+      // the fitted function must not be negative
+      if (fu <= 0.0)
+      {
+        chi2 = 1.e10;
+        break;
+      }
+
+      Double_t temp = (content - fu) / error;
+      chi2 += temp*temp;
+    }
+
+    //-------------------------------------------
+
+    f = chi2;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+// --------------------------------------------------------------------------
+//
+// fcnpolygauss
+//
+// calculates the chi2 for the fit of the (polynomial+Gauss) function 
+// 'PolyGauss' to the histogram 'fhist'
+//
+// it is called by CallMinuit() (which is called in FitGaussPoly()) 
+//
+// bins of fhist with huge errors are ignored in the calculation of the chi2
+// (the huge errors were set in 'FitGaussPoly()')
+//
+
+static void fcnpolygauss(Int_t &npar, Double_t *gin, Double_t &f, 
+                         Double_t *par, Int_t iflag)
+{
+    TH1 *fhist = (TH1*)gMinuit->GetObjectFit();
+    TF1 *fpolygauss = fhist->GetFunction("PolyGauss");    
+
+
+    //-------------------------------------------
+
+    Double_t chi2 = 0.0;
+
+    Int_t nbins = fhist->GetNbinsX();
+    Int_t mbins = 0;
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      Double_t content = fhist->GetBinContent(i);
+      Double_t error   = fhist->GetBinError(i);
+      Double_t center  = fhist->GetBinCenter(i);
+
+      //-----------------------------
+      // ignore unwanted points
+      if (error > 1.e19)
+        continue;
+
+      if (content <= 0.0)
+      {
+        gLog << "fcnpolygauss : bin with zero content; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      if (error <= 0.0)
+      {
+        gLog << "fcnpolygauss : bin with zero error; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      //-----------------------------
+      mbins++;
+
+      Double_t fu;
+      fu = fpolygauss->EvalPar(&center, par);
+
+      // the fitted function must not be negative
+      if (fu <= 0.0)
+      {
+        chi2 = 1.e10;
+        break;
+      }
+
+      Double_t temp = (content - fu) / error;
+      chi2 += temp*temp;
+    }
+
+    //-------------------------------------------
+
+    f = chi2;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Constructor
+//
+MHFindSignificance::MHFindSignificance(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fSigVsAlpha = NULL;
+
+    fPoly   = NULL;
+    fGPoly  = NULL;
+    fGBackg = NULL;
+
+    fHist     = NULL;
+    fHistOrig = NULL;
+
+    // allow rebinning of the alpha plot
+    fRebin = kTRUE;
+
+    // allow reducing the degree of the polynomial
+    fReduceDegree = kTRUE;
+
+    fCanvas = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. 
+//
+// =====>  it is not clear why one obtains sometimes a segmentation violation
+//         when the destructor is active     <=======================
+//
+// therefore the 'return'statement
+//
+
+MHFindSignificance::~MHFindSignificance()
+{
+  return;
+
+  *fLog << "destructor of MHFindSignificance is called" << endl;
+ 
+    //delete fHist;
+
+    delete fSigVsAlpha;
+    delete fPoly;
+    delete fGPoly;
+    delete fGBackg;
+    //delete fCanvas;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set flag fRebin 
+//
+//  if flag is kTRUE rebinning of the alpha plot is allowed
+//
+//
+void MHFindSignificance::SetRebin(Bool_t b)
+{
+  fRebin = b;
+
+  *fLog << "MHFindSignificance::SetRebin; flag fRebin set to " 
+        << (b? "kTRUE" : "kFALSE") << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set flag fReduceDegree 
+//
+//  if flag is kTRUE reducing of the degree of the polynomial is allowed
+//
+//
+void MHFindSignificance::SetReduceDegree(Bool_t b)
+{
+  fReduceDegree = b;
+
+  *fLog << "MHFindSignificance::SetReduceDegree; flag fReduceDegree set to " 
+        << (b? "kTRUE" : "kFALSE") << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  FindSigma
+//
+//  calls FitPolynomial     to fit the background in the background region
+//  calls DetExcess         to determine the number of excess events
+//                          using an extrapolation of the polynomial
+//                          into the signal region
+//  calls SigmaLiMa         to determine the significance of the gamma signal
+//                          in the range |alpha| < alphasig
+//  calls FitGaussPoly      to fit a (polynomial+Gauss) function in the
+//                          whole |alpha| region
+//
+//
+Bool_t MHFindSignificance::FindSigma(TH1 *fhist,  Double_t alphamin,
+       Double_t alphamax, Int_t degree, Double_t alphasig, 
+       Bool_t drawpoly,   Bool_t fitgauss, Bool_t print)
+{
+  //*fLog << "MHFindSignificance::FindSigma;" << endl;
+
+  fHistOrig = fhist;
+
+  fHist = (TH1*)fHistOrig->Clone();
+  fHist->SetName(fhist->GetName());
+  if ( !fHist )
+  {
+    *fLog << "MHFindSignificance::FindSigma; Clone of histogram could not be generated" 
+          << endl;
+    return kFALSE;
+  }
+  
+  fHist->Sumw2();
+  //fHist->SetNameTitle("Alpha", "alpha plot");
+  fHist->SetXTitle("|alpha|  [\\circ]");
+  fHist->SetYTitle("Counts");
+  fHist->UseCurrentStyle();
+
+  fAlphamin = alphamin;
+  fAlphamax = alphamax;
+  fAlphammm = (alphamin+alphamax)/2.0;
+  fDegree   = degree;
+  fAlphasig = alphasig;
+
+  fDraw     = drawpoly;
+  fFitGauss = fitgauss;
+
+
+  //--------------------------------------------
+  // fit a polynomial in the background region
+
+  //*fLog << "MHFindSignificance::FindSigma;  calling FitPolynomial()" << endl;
+  if ( !FitPolynomial() )
+  {
+    *fLog << "MHFindSignificance::FindSigma; FitPolynomial failed"
+	  << endl;  
+    return kFALSE;
+  }
+
+
+  //--------------------------------------------
+  // calculate the number of excess events in the signal region
+
+  //*fLog << "MHFindSignificance::FindSigma;  calling DetExcess()" << endl;
+  if ( !DetExcess() )
+  {
+    *fLog << "MHFindSignificance::FindSigma; DetExcess failed"
+	  << endl;  
+    return kFALSE;
+  }
+
+
+  //--------------------------------------------
+  // calculate the significance of the excess
+
+  //*fLog << "MHFindSignificance::FindSigma;  calling SigmaLiMa()" << endl;
+  Double_t siglima = 0.0;
+  if ( !SigmaLiMa(fNon, fNoff, fGamma, &siglima) )
+  {
+    *fLog << "MHFindSignificance::FindSigma; SigmaLiMa failed"
+	  << endl;  
+    return kFALSE;
+  }
+  fSigLiMa = siglima;
+
+  //--------------------------------------------
+  // calculate the error of the number of excess events
+
+  fdNex = fNex / fSigLiMa;
+
+
+  //--------------------------------------------
+
+  //*fLog << "MHFindSignificance::FindSigma;  calling PrintPoly()" << endl;
+  if (print)
+    PrintPoly();
+
+
+  //--------------------------------------------
+  // fit a (polynomial + Gauss) function
+
+  if (fFitGauss)
+  {
+    //--------------------------------------------------
+    // delete objects from this fit
+    // in order to have independent starting conditions for the next fit
+
+      delete gMinuit;
+      gMinuit = NULL;
+    //--------------------------------------------------
+
+      //*fLog << "MHFindSignificance::FindSigma;  calling FitGaussPoly()" 
+      //      << endl;
+    if ( !FitGaussPoly() )
+    {
+      *fLog << "MHFindSignificance::FindSigma; FitGaussPoly failed"  
+      	    << endl;  
+      return kFALSE;
+    }
+
+    if (print)
+    {
+      //*fLog << "MHFindSignificance::FindSigma;  calling PrintPolyGauss()" 
+      //      << endl;
+      PrintPolyGauss();
+    }
+  }
+
+  //--------------------------------------------------
+  // draw the histogram if requested
+
+  if (fDraw)
+  {
+    //*fLog << "MHFindSignificance::FindSigma;  calling DrawFit()" << endl;
+    if ( !DrawFit() )
+    {
+      *fLog << "MHFindSignificance::FindSigma; DrawFit failed"  
+      	    << endl;  
+      return kFALSE;
+    }
+  }
+
+
+  //--------------------------------------------------
+  // delete objects from this fit
+  // in order to have independent starting conditions for the next fit
+
+    delete gMinuit;
+    gMinuit = NULL;
+  //--------------------------------------------------
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  SigmaVsAlpha  (like FindSigma. However, alphasig is scanned and
+//                 the significance is plotted versus alphasig)
+//
+//  calls FitPolynomial     to fit the background in the background region
+//
+//  scan alphasig; for a given alphasig :
+//       calls DetExcess    to determine the number of excess events
+//       calls SigmaLiMa    to determine the significance of the gamma signal
+//                          in the range fAlphalow < |alpha| < alphasig
+//
+
+Bool_t MHFindSignificance::SigmaVsAlpha(TH1 *fhist,  Double_t alphamin,
+                    Double_t alphamax, Int_t degree, Bool_t print)
+{
+  //*fLog << "MHFindSignificance::SigmaVsAlpha;" << endl;
+
+  fHistOrig = fhist;
+
+  fHist = (TH1*)fHistOrig->Clone();
+  fHist->SetName(fhist->GetName());
+  fHist->Sumw2();
+  //fHist->SetNameTitle("alpha", "alpha plot");
+  fHist->SetXTitle("|alpha|  [\\circ]");
+  fHist->SetYTitle("Counts");
+  fHist->UseCurrentStyle();
+
+  fAlphamin = alphamin;
+  fAlphamax = alphamax;
+  fAlphammm = (alphamin+alphamax)/2.0;
+  fDegree   = degree;
+
+
+  //--------------------------------------------
+  // fit a polynomial in the background region
+
+  //*fLog << "MHFindSignificance::SigmaVsAlpha  calling FitPolynomial()" 
+  //      << endl;
+  if ( !FitPolynomial() )  
+    {
+      *fLog << "MHFindSignificance::SigmaVsAlpha;  FitPolynomial() failed" 
+            << endl;
+      return kFALSE;
+    }
+
+
+  //--------------------------------------------
+  // loop over different signal regions
+
+  Int_t    nsteps    =  15;
+
+  fSigVsAlpha = new TH1D("SigVsAlpha","Sigma vs Alpha", nsteps, 0.0, alphamin);
+  fSigVsAlpha->SetXTitle("upper edge of signal region in |alpha|  [\\circ]");
+  fSigVsAlpha->SetYTitle("Significance of gamma signal");
+
+  for (Int_t i=1; i<=nsteps; i++)
+  {
+    fAlphasig = fSigVsAlpha->GetBinCenter(i);
+
+    if ( !DetExcess() )
+    {
+      *fLog << "MHFindSignificance::SigmaVsAlpha;  DetExcess() failed" << endl;
+      continue;
+    }
+
+    Double_t siglima = 0.0;
+    if ( !SigmaLiMa(fNon, fNoff, fGamma, &siglima) )
+    {
+      *fLog << "MHFindSignificance::SigmaVsAlpha;  SigmaLiMa() failed" << endl;
+      continue;
+    }
+
+    fdNex = fNex / siglima;
+    fSigVsAlpha->SetBinContent(i, siglima);
+
+    if (print)
+      PrintPoly();
+  }
+
+  //--------------------------------------------
+  // plot significance versus alphasig
+ 
+  TCanvas *ccc = new TCanvas("SigVsAlpha", "Sigma vs Alpha", 600, 600);
+ 
+  gROOT->SetSelectedPad(NULL);
+  gStyle->SetPadLeftMargin(0.05);
+
+  ccc->cd();
+  fSigVsAlpha->DrawCopy();
+
+  ccc->Modified();
+  ccc->Update();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  FitPolynomial
+//
+//  - create a clone 'fHist' of the |alpha| distribution 'fHistOrig'
+//  - fit a polynomial of degree 'fDegree' to the alpha distribution 
+//    'fHist' in the region alphamin < |alpha| < alphamax
+//
+//  in pathological cases the histogram is rebinned before fitting
+//     (this is done only if fRebin is kTRUE)
+//
+//  if the highest coefficient of the polynomial is compatible with zero
+//     the fit is repeated with a polynomial of lower degree
+//     (this is done only if fReduceDegree is kTRUE)
+//
+//
+Bool_t MHFindSignificance::FitPolynomial()
+{
+  //--------------------------------------------------
+  // check the histogram :
+  //       - calculate initial values of the parameters
+  //       - check for bins with zero entries
+  //       - set minimum errors
+  //       - save the original errors
+  //       - set errors huge outside the fit range
+  //         (in 'fcnpoly' points with huge errors will be ignored)
+
+
+  Double_t dummy = 1.e20;
+
+  Double_t mean;
+  Double_t rms;
+  Double_t nclose;
+  Double_t nfar;
+  Double_t a2init = 0.0;
+  TArrayD  saveError;
+
+  Int_t nbins;
+  Int_t nrebin = 1;
+
+  //----------------   start while loop for rebinning   -----------------
+  while(1)
+  {
+
+  fNzero   = 0;
+  fMbins   = 0;
+  fMlow    = 0;
+  fNbgtot  = 0.0;
+
+  fAlphami =  10000.0;
+  fAlphamm =  10000.0;
+  fAlphama = -10000.0;
+
+  mean   = 0.0;
+  rms    = 0.0;
+  nclose = 0.0;
+  nfar   = 0.0;
+
+  nbins = fHist->GetNbinsX();
+  saveError.Set(nbins);
+
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    saveError[i-1] = fHist->GetBinError(i);
+
+    // bin should be completely contained in the fit range
+    // (fAlphamin, fAlphamax)
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+
+    if ( xlo >= fAlphamin-fEps  &&  xlo <= fAlphamax+fEps  &&
+	 xup >= fAlphamin-fEps  &&  xup <= fAlphamax+fEps     )
+    {
+      fMbins++;
+
+      if ( xlo < fAlphami )
+        fAlphami = xlo;
+
+      if ( xup > fAlphama )
+        fAlphama = xup;
+
+      Double_t content = fHist->GetBinContent(i);
+      fNbgtot += content;
+
+      mean += content;
+      rms  += content*content;
+
+      // count events in low-alpha and high-alpha region
+      if ( xlo >= fAlphammm-fEps  &&  xup >= fAlphammm-fEps)
+      {
+        nfar   += content;
+        if ( xlo < fAlphamm )
+          fAlphamm = xlo;
+        if ( xup < fAlphamm )
+          fAlphamm = xup; 
+      }
+      else
+      {
+        nclose += content;
+        if ( xlo > fAlphamm )
+          fAlphamm = xlo;
+        if ( xup > fAlphamm )
+          fAlphamm = xup; 
+      }
+
+      // count bins with zero entry
+      if (content <= 0.0)
+        fNzero++;
+     
+      // set minimum error
+      if (content < 9.0)
+      {
+        fMlow += 1;
+        fHist->SetBinError(i, 3.0);
+      }
+
+      //*fLog << "Take : i, content, error = " << i << ",  " 
+      //      << fHist->GetBinContent(i) << ",  "
+      //      << fHist->GetBinError(i)   << endl;
+
+      continue;
+    }    
+    // bin is not completely contained in the fit range : set error huge
+
+    fHist->SetBinError(i, dummy);
+
+    //*fLog << "Omit : i, content, error = " << i << ",  " 
+    //      << fHist->GetBinContent(i) << ",  " << fHist->GetBinError(i) 
+    //      << endl;
+
+  }
+
+  // mean of entries/bin in the fit range
+  if (fMbins > 0)
+  {
+    mean /= ((Double_t) fMbins);
+    rms  /= ((Double_t) fMbins);
+  }
+
+  rms = sqrt( rms - mean*mean );
+
+  // if there are no events in the background region
+  //    there is no reason for rebinning
+  //    and this is the condition for assuming a constant background (= 0)
+  if (mean <= 0.0)
+    break;
+
+  Double_t helpmi = fAlphami*fAlphami*fAlphami;
+  Double_t helpmm = fAlphamm*fAlphamm*fAlphamm;
+  Double_t helpma = fAlphama*fAlphama*fAlphama;
+  Double_t help   =   (helpma-helpmm) * (fAlphamm-fAlphami)    
+	            - (helpmm-helpmi) * (fAlphama-fAlphamm);
+  if (help != 0.0)
+    a2init =  ( (fAlphamm-fAlphami)*nfar - (fAlphama-fAlphamm)*nclose )
+                * 1.5 * fHist->GetBinWidth(1) / help;
+  else
+    a2init = 0.0;
+
+
+  //--------------------------------------------
+  // rebin the histogram
+  //   - if a bin has no entries 
+  //   - or if there are too many bins with too few entries
+  //   - or if the new bin width would exceed half the size of the 
+  //     signal region
+
+  if ( !fRebin  ||
+       ( fNzero <= 0 && (Double_t)fMlow<0.05*(Double_t)fMbins )  || 
+       (Double_t)(nrebin+1)/(Double_t)nrebin * fHist->GetBinWidth(1) 
+                                                           > fAlphasig/2.0 )
+  {
+    //*fLog << "before break" << endl;
+    break;
+  }
+
+  nrebin += 1;
+  TString histname = fHist->GetName();
+  delete fHist;
+  fHist = NULL;
+
+  *fLog << "MHFindSignificance::FitPolynomial; rebin the |alpha| plot, grouping "
+        << nrebin << " bins together" << endl;
+
+  // TH1::Rebin doesn't work properly
+  //fHist = fHistOrig->Rebin(nrebin, "Rebinned");
+  // use private routine RebinHistogram()
+  fHist = new TH1F;
+  fHist->Sumw2();
+  fHist->SetNameTitle(histname, histname);
+  fHist->UseCurrentStyle();
+
+  // do rebinning such that x0 remains a lower bin edge
+  Double_t x0 = 0.0;
+  if ( !RebinHistogram(x0, nrebin) )
+  {
+    *fLog << "MHFindSignificance::FitPolynomial; RebinHistgram() failed" 
+          << endl;
+    return kFALSE;
+  }
+
+  fHist->SetXTitle("|alpha|  [\\circ]");
+  fHist->SetYTitle("Counts");
+
+  }
+  //----------------   end of while loop for rebinning   -----------------
+
+
+  // if there are still too many bins with too few entries don't fit
+  // and assume a constant background
+
+  fConstantBackg = kFALSE;
+  if ( fNzero > 0  ||  (Double_t)fMlow>0.05*(Double_t)fMbins ) 
+  {
+    *fLog << "MHFindSignificance::FitPolynomial; polynomial fit not possible,  fNzero, fMlow, fMbins = "
+          << fNzero << ",  " << fMlow << ",  " << fMbins << endl;
+    *fLog << "                    assume a constant background" << endl;
+
+    fConstantBackg = kTRUE;
+    fDegree        = 0;
+
+    TString funcname = "Poly";
+    Double_t xmin =   0.0;
+    Double_t xmax =  90.0;
+
+    TString formula = "[0]";
+
+    fPoly = new TF1(funcname, formula, xmin, xmax);
+    TList *funclist = fHist->GetListOfFunctions();
+    funclist->Add(fPoly);
+
+    //--------------------
+    Int_t nparfree = 1;
+    fChisq         = 0.0; 
+    fNdf           = fMbins - nparfree;
+    fProb          = 0.0;
+    fIstat         = 0;
+
+    fValues.Set(1);
+    fErrors.Set(1);
+
+    Double_t val, err;
+    val = mean;
+    err = sqrt( mean / (Double_t)fMbins );
+
+    fPoly->SetParameter(0, val);
+    fPoly->SetParError (0, err);
+
+    fValues[0] = val;
+    fErrors[0] = err; 
+
+    fEma[0][0]  = err*err;
+    fCorr[0][0] = 1.0;
+    //--------------------
+
+    //--------------------------------------------------
+    // reset the errors of the points in the histogram
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      fHist->SetBinError(i, saveError[i-1]);
+    }
+
+
+    return kTRUE;
+  }
+
+
+  //===========   start loop for reducing the degree   ==================
+  //              of the polynomial
+  while (1)
+  {
+      //--------------------------------------------------
+      // prepare fit of a polynomial :   (a0 + a1*x + a2*x**2 + a3*x**3 + ...)
+
+      TString funcname = "Poly";
+      Double_t xmin =   0.0;
+      Double_t xmax =  90.0;
+
+      TString formula = "[0]";
+      TString bra1     = "+[";
+      TString bra2     =    "]";
+      TString xpower   = "*x";
+      TString newpower = "*x";
+      for (Int_t i=1; i<=fDegree; i++)
+      {
+          formula += bra1;
+          formula += i;
+          formula += bra2;
+          formula += xpower;
+
+          xpower += newpower;
+      }
+
+      //*fLog << "FitPolynomial : formula = " << formula << endl;
+
+      fPoly = new TF1(funcname, formula, xmin, xmax);
+      TList *funclist = fHist->GetListOfFunctions();
+      funclist->Add(fPoly);
+
+      //------------------------
+      // attention : the dimensions must agree with those in CallMinuit()
+      const UInt_t npar = fDegree+1;
+
+      TString parname[npar];
+      TArrayD vinit(npar);
+      TArrayD  step(npar);
+      TArrayD limlo(npar);
+      TArrayD limup(npar);
+      TArrayI   fix(npar);
+
+      vinit[0] =   mean;
+      vinit[2] = a2init;
+
+      for (UInt_t j=0; j<npar; j++)
+      {
+          parname[j]  = "p";
+          parname[j] += j+1;
+
+          step[j] = vinit[j] != 0.0 ? TMath::Abs(vinit[j]) / 10.0 : 0.000001;
+      }
+
+      // limit the first coefficient of the polynomial to positive values
+      // because the background must not be negative
+      limup[0] = fHist->GetEntries();
+
+      // use the subsequernt loop if you want to apply the
+      // constraint : uneven derivatives (at alpha=0) = zero
+      for (UInt_t j=1; j<npar; j+=2)
+      {
+          vinit[j] = 0;
+          step[j]  = 0;
+          fix[j]   = 1;
+      }
+
+      //*fLog << "FitPolynomial : before CallMinuit()" << endl;
+
+      MMinuitInterface inter;
+      const Bool_t rc = inter.CallMinuit(fcnpoly, parname, vinit, step,
+                                         limlo, limup, fix, fHist, "Migrad",
+                                         kFALSE);
+
+      //*fLog << "FitPolynomial : after CallMinuit()" << endl;
+
+      if (rc != 0)
+      {
+          //  *fLog << "MHFindSignificance::FitPolynomial; polynomial fit failed"
+          //        << endl;
+          //  return kFALSE;
+      }
+
+
+      //-------------------
+      // get status of minimization
+      Double_t fmin   = 0;
+      Double_t fedm   = 0;
+      Double_t errdef = 0;
+      Int_t    npari  = 0;
+      Int_t    nparx  = 0;
+
+      if (gMinuit)
+          gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, fIstat);
+
+      *fLog << "MHFindSignificance::FitPolynomial; fmin, fedm, errdef, npari, nparx, fIstat = "
+            << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+            << ",  " << nparx << ",  " << fIstat << endl;
+
+
+      //-------------------
+      // store the results
+
+      Int_t nparfree = gMinuit!=NULL ? gMinuit->GetNumFreePars() : 0;
+      fChisq         = fmin;
+      fNdf           = fMbins - nparfree;
+      fProb          = TMath::Prob(fChisq, fNdf);
+
+
+      // get fitted parameter values and errors
+      fValues.Set(npar);
+      fErrors.Set(npar);
+
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          Double_t val, err;
+          if (gMinuit)
+              gMinuit->GetParameter(j, val, err);
+
+          fPoly->SetParameter(j, val);
+          fPoly->SetParError(j, err);
+
+          fValues[j] = val;
+          fErrors[j] = err;
+      }
+
+
+      //--------------------------------------------------
+      // if the highest coefficient (j0) of the polynomial
+      // is consistent with zero reduce the degree of the polynomial
+
+      Int_t j0 = 0;
+      for (Int_t j=fDegree; j>1; j--)
+      {
+          // ignore fixed parameters
+          if (fErrors[j] == 0)
+              continue;
+
+          // this is the highest coefficient
+          j0 = j;
+          break;
+      }
+
+      if (!fReduceDegree || j0==0 || TMath::Abs(fValues[j0]) > fErrors[j0])
+          break;
+
+      // reduce the degree of the polynomial
+      *fLog << "MHFindSignificance::FitPolynomial; reduce the degree of the polynomial from "
+          << fDegree << " to " << (j0-2) << endl;
+      fDegree = j0 - 2;
+
+      funclist->Remove(fPoly);
+      //if (fPoly)
+      delete fPoly;
+      fPoly = NULL;
+
+      // delete the Minuit object in order to have independent starting
+      // conditions for the next minimization
+      //if (gMinuit)
+      delete gMinuit;
+      gMinuit = NULL;
+  }
+  //===========   end of loop for reducing the degree   ==================
+  //              of the polynomial
+
+
+  //--------------------------------------------------
+  // get the error matrix of the fitted parameters
+
+
+  if (fIstat >= 1)
+  {
+      // error matrix was calculated
+      if (gMinuit)
+          gMinuit->mnemat(&fEmat[0][0], fNdim);
+
+      // copy covariance matrix into a matrix which includes also the fixed
+      // parameters
+      TString  name;
+      Double_t bnd1, bnd2, val, err;
+      Int_t    jvarbl;
+      Int_t    kvarbl;
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          if (gMinuit)
+              gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+          for (Int_t k=0; k<=fDegree; k++)
+          {
+              if (gMinuit)
+                  gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+              fEma[j][k] = jvarbl==0 || kvarbl==0 ? 0 : fEmat[jvarbl-1][kvarbl-1];
+          }
+      }
+  }
+  else
+  {
+      // error matrix was not calculated, construct it
+      *fLog << "MHFindSignificance::FitPolynomial; error matrix not defined"
+          << endl;
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          for (Int_t k=0; k<=fDegree; k++)
+              fEma[j][k] = 0;
+
+          fEma[j][j] = fErrors[j]*fErrors[j];
+      }
+  }
+
+
+  //--------------------------------------------------
+  // calculate correlation matrix
+  for (Int_t j=0; j<=fDegree; j++)
+      for (Int_t k=0; k<=fDegree; k++)
+      {
+          const Double_t sq = fEma[j][j]*fEma[k][k];
+          fCorr[j][k] = sq==0 ? 0 : fEma[j][k] / TMath::Sqrt(fEma[j][j]*fEma[k][k]);
+      }
+
+
+  //--------------------------------------------------
+  // reset the errors of the points in the histogram
+  for (Int_t i=1; i<=nbins; i++)
+      fHist->SetBinError(i, saveError[i-1]);
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ReBinHistogram
+//
+// rebin the histogram 'fHistOrig' by grouping 'nrebin' bins together 
+// put the result into the histogram 'fHist'
+// the rebinning is made such that 'x0' remains a lower bound of a bin
+//
+
+Bool_t MHFindSignificance::RebinHistogram(Double_t x0, Int_t nrebin)
+{
+  //-----------------------------------------
+  // search bin i0 which has x0 as lower edge
+
+  Int_t i0 = -1;
+  Int_t nbold = fHistOrig->GetNbinsX();
+  for (Int_t i=1; i<=nbold; i++)
+  {
+      if (TMath::Abs(fHistOrig->GetBinLowEdge(i) - x0) < 1.e-4 )
+      {
+          i0 = i;
+          break;
+      }
+  }
+
+  if (i0 == -1)
+  {
+    i0 = 1;
+    *fLog << "MHFindsignificance::Rebin; no bin found with " << x0
+          << " as lower edge,  start rebinning with bin 1" << endl;
+  }
+
+  Int_t istart = i0 - nrebin * ( (i0-1)/nrebin );
+
+  //-----------------------------------------
+  // get new bin edges
+
+  const Int_t    nbnew = (nbold-istart+1) / nrebin;
+  const Double_t xmin  = fHistOrig->GetBinLowEdge(istart);
+  const Double_t xmax  = xmin + (Double_t)nbnew * nrebin * fHistOrig->GetBinWidth(1);
+  fHist->SetBins(nbnew, xmin, xmax);
+
+  *fLog << "MHFindSignificance::ReBin; x0, i0, nbold, nbnew, xmin, xmax = "
+        << x0 << ",  " << i0 << ",  " << nbold << ",  " << nbnew << ",  "
+        << xmin << ",  " << xmax << endl;
+
+  //-----------------------------------------
+  // get new bin entries
+
+  for (Int_t i=1; i<=nbnew; i++)
+  {
+      Int_t j = nrebin*(i-1) + istart;
+
+      Double_t content = 0;
+      Double_t error2  = 0;
+      for (Int_t k=0; k<nrebin; k++)
+      {
+          content += fHistOrig->GetBinContent(j+k);
+          error2  += fHistOrig->GetBinError(j+k) * fHistOrig->GetBinError(j+k);
+      }
+      fHist->SetBinContent(i, content);
+      fHist->SetBinError  (i, sqrt(error2));
+  }
+  fHist->SetEntries( fHistOrig->GetEntries() );
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  FitGaussPoly
+//
+//  fits a (Gauss + polynomial function) to the alpha distribution 'fhist' 
+//
+//
+Bool_t MHFindSignificance::FitGaussPoly()
+{
+  *fLog << "Entry FitGaussPoly" << endl;
+
+  //--------------------------------------------------
+  // check the histogram :
+  //       - calculate initial values of the parameters
+  //       - check for bins with zero entries
+  //       - set minimum errors
+  //       - save the original errors
+  //       - set errors huge outside the fit range
+  //         (in 'fcnpoly' points with huge errors will be ignored)
+
+
+  Double_t dummy = 1.e20;
+
+  fGNzero   = 0;
+  fGMbins   = 0;
+
+  //------------------------------------------
+  // if a constant background has been assumed (due to low statistics)
+  // fit only in the signal region
+  if ( !fConstantBackg )
+  {
+    fAlphalow = 0.0;
+    fAlphahig = fAlphamax;
+  }
+  else
+  {
+    fAlphalow = 0.0;
+    fAlphahig = 2.0*fAlphasig>25.0 ? 25.0 : 2.0*fAlphasig;
+  }
+  //------------------------------------------
+
+
+  fAlphalo =  10000.0;
+  fAlphahi = -10000.0;
+
+
+  Int_t nbins = fHist->GetNbinsX();
+  TArrayD saveError(nbins);
+
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    saveError[i-1] = fHist->GetBinError(i);
+
+    // bin should be completely contained in the fit range
+    // (fAlphalow, fAlphahig)
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+
+    if ( xlo >= fAlphalow-fEps  &&  xlo <= fAlphahig+fEps  &&
+	 xup >= fAlphalow-fEps  &&  xup <= fAlphahig+fEps     )
+    {
+      fGMbins++;
+
+      if ( xlo < fAlphalo )
+        fAlphalo = xlo;
+
+      if ( xup > fAlphahi )
+        fAlphahi = xup;
+
+      Double_t content = fHist->GetBinContent(i);
+
+
+      // count bins with zero entry
+      if (content <= 0.0)
+        fGNzero++;
+     
+      // set minimum error
+      if (content < 9.0)
+        fHist->SetBinError(i, 3.0);
+
+      //*fLog << "Take : i, content, error = " << i << ",  " 
+      //      << fHist->GetBinContent(i) << ",  "
+      //      << fHist->GetBinError(i)   << endl;
+
+      continue;
+    }    
+    // bin is not completely contained in the fit range : set error huge
+
+    fHist->SetBinError(i, dummy);
+
+    //*fLog << "Omit : i, content, error = " << i << ",  " 
+    //      << fHist->GetBinContent(i) << ",  " << fHist->GetBinError(i) 
+    //      << endl;
+
+  }
+
+
+  // if a bin has no entries don't fit
+  if (fGNzero > 0)
+  {
+    *fLog << "MHFindSignificance::FitGaussPoly; out of " << fGMbins 
+          << " bins there are " << fGNzero
+          << " bins with zero entry" << endl;
+
+    fGPoly = NULL;
+    return kFALSE;
+  }
+
+
+  //--------------------------------------------------
+  // prepare fit of a (polynomial+Gauss) :   
+  // (a0 + a1*x + a2*x**2 + a3*x**3 + ...) + A*exp( -0.5*((x-x0)/sigma)**2 )
+
+  TString funcname = "PolyGauss";
+  Double_t xmin =   0.0;
+  Double_t xmax =  90.0;
+
+  TString xpower   = "*x";
+  TString newpower = "*x";
+
+  TString formulaBackg = "[0]";
+  for (Int_t i=1; i<=fDegree; i++)
+      formulaBackg += Form("+[%d]*x^%d", i, i);
+
+  const TString formulaGauss = 
+        Form("[%d]/[%d]*exp(-0.5*((x-[%d])/[%d])^2)",
+             fDegree+1, fDegree+3, fDegree+2, fDegree+3);
+
+  TString formula = formulaBackg;
+  formula += "+";
+  formula += formulaGauss;
+
+  *fLog << "FitGaussPoly : formulaBackg = " << formulaBackg << endl;
+  *fLog << "FitGaussPoly : formulaGauss = " << formulaGauss << endl;
+  *fLog << "FitGaussPoly : formula = " << formula << endl;
+
+  fGPoly = new TF1(funcname, formula, xmin, xmax);
+  TList *funclist = fHist->GetListOfFunctions();
+  funclist->Add(fGPoly);
+
+  fGBackg = new TF1("Backg", formulaBackg, xmin, xmax);
+  funclist->Add(fGBackg);
+
+  //------------------------
+  // attention : the dimensions must agree with those in CallMinuit()
+  Int_t npar = fDegree+1 + 3;
+
+  TString parname[npar];
+  TArrayD vinit(npar);
+  TArrayD  step(npar); 
+  TArrayD limlo(npar); 
+  TArrayD limup(npar); 
+  TArrayI   fix(npar);
+
+
+  // take as initial values for the polynomial 
+  // the result from the polynomial fit
+  for (Int_t j=0; j<=fDegree; j++)
+    vinit[j] = fPoly->GetParameter(j);
+
+  Double_t sigma = 8;
+  vinit[fDegree+1] = 2.0 * fNex * fHist->GetBinWidth(1) / TMath::Sqrt(TMath::Pi()*2);
+  vinit[fDegree+2] = 0;
+  vinit[fDegree+3] = sigma;
+
+  *fLog << "FitGaussPoly : starting value for Gauss-amplitude = " 
+        << vinit[fDegree+1] << endl;
+
+  for (Int_t j=0; j<npar; j++)
+  {
+      parname[j]  = "p";
+      parname[j] += j+1;
+
+      step[j] = vinit[j]!=0 ? TMath::Abs(vinit[j]) / 10.0 : 0.000001;
+  }
+
+  // limit the first coefficient of the polynomial to positive values
+  // because the background must not be negative
+  limup[0] = fHist->GetEntries()*10;
+
+  // limit the sigma of the Gauss function
+  limup[fDegree+3] = 20;
+
+
+  // use the subsequernt loop if you want to apply the
+  // constraint : uneven derivatives (at alpha=0) = zero
+  for (Int_t j=1; j<=fDegree; j+=2)
+  {
+      vinit[j] = 0;
+      step[j]  = 0;
+      fix[j]   = 1;
+  }
+
+  // fix position of Gauss function
+  vinit[fDegree+2] = 0;
+  step[fDegree+2]  = 0;
+  fix[fDegree+2]   = 1;
+   
+  // if a constant background has been assumed (due to low statistics)
+  // fix the background
+  if (fConstantBackg)
+  {
+      step[0] = 0;
+      fix[0]  = 1;
+  }
+
+  MMinuitInterface inter;
+  const Bool_t rc = inter.CallMinuit(fcnpolygauss, parname, vinit, step,
+                                     limlo, limup, fix, fHist, "Migrad",
+                                     kFALSE);
+
+  if (rc != 0)
+  {
+  //  *fLog << "MHFindSignificance::FitGaussPoly; (polynomial+Gauss) fit failed"
+  //        << endl;
+  //  return kFALSE;
+  }
+
+
+  //-------------------
+  // get status of the minimization
+  Double_t fmin;
+  Double_t fedm;
+  Double_t errdef;
+  Int_t    npari;
+  Int_t    nparx;
+
+  if (gMinuit)
+    gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, fGIstat);
+
+  *fLog << "MHFindSignificance::FitGaussPoly; fmin, fedm, errdef, npari, nparx, fGIstat = "
+        << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+        << ",  " << nparx << ",  " << fGIstat << endl;
+
+
+  //-------------------
+  // store the results
+
+  Int_t nparfree  = gMinuit!=NULL ? gMinuit->GetNumFreePars() : 0;
+  fGChisq         = fmin; 
+  fGNdf           = fGMbins - nparfree;
+  fGProb          = TMath::Prob(fGChisq, fGNdf);
+
+
+  // get fitted parameter values and errors
+  fGValues.Set(npar);
+  fGErrors.Set(npar);
+
+  for (Int_t j=0; j<npar; j++)
+  {
+    Double_t val, err;
+    if (gMinuit)
+      gMinuit->GetParameter(j, val, err);
+
+    fGPoly->SetParameter(j, val);
+    fGPoly->SetParError(j, err);
+
+    fGValues[j] = val;
+    fGErrors[j] = err; 
+
+    if (j <=fDegree)
+    {
+      fGBackg->SetParameter(j, val);
+      fGBackg->SetParError(j, err);
+    }
+  }
+
+  fSigmaGauss  = fGValues[fDegree+3];
+  fdSigmaGauss = fGErrors[fDegree+3];
+  // fitted total number of excess events 
+  fNexGauss = fGValues[fDegree+1] * TMath::Sqrt(TMath::Pi()*2) /
+                                         (fHist->GetBinWidth(1)*2 );
+  fdNexGauss = fNexGauss * fGErrors[fDegree+1]/fGValues[fDegree+1];
+
+  //--------------------------------------------------
+  // get the error matrix of the fitted parameters
+
+
+  if (fGIstat >= 1)
+  {
+    // error matrix was calculated
+    if (gMinuit)
+      gMinuit->mnemat(&fGEmat[0][0], fGNdim);
+
+    // copy covariance matrix into a matrix which includes also the fixed
+    // parameters
+    TString  name;
+    Double_t bnd1, bnd2, val, err;
+    Int_t    jvarbl;
+    Int_t    kvarbl;
+    for (Int_t j=0; j<npar; j++)
+    {
+        if (gMinuit)
+            gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+        for (Int_t k=0; k<npar; k++)
+        {
+            if (gMinuit)
+                gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+            fGEma[j][k] = jvarbl==0 || kvarbl==0 ? 0 : fGEmat[jvarbl-1][kvarbl-1];
+        }
+    }
+  }
+  else
+  {
+    // error matrix was not calculated, construct it
+    *fLog << "MHFindSignificance::FitPolynomial; error matrix not defined" 
+          << endl;
+    for (Int_t j=0; j<npar; j++)
+    {
+        for (Int_t k=0; k<npar; k++)
+            fGEma[j][k] = 0;
+
+        fGEma[j][j] = fGErrors[j]*fGErrors[j];
+    }
+  }
+
+
+  //--------------------------------------------------
+  // calculate correlation matrix
+  for (Int_t j=0; j<npar; j++)
+  {
+    for (Int_t k=0; k<npar; k++)
+    {
+        const Double_t sq = fGEma[j][j]*fGEma[k][k];
+        fGCorr[j][k] = sq==0 ? 0 : fGEma[j][k] / sqrt( fGEma[j][j]*fGEma[k][k] );
+    }
+  }
+
+
+  //--------------------------------------------------
+  // reset the errors of the points in the histogram
+  for (Int_t i=1; i<=nbins; i++)
+    fHist->SetBinError(i, saveError[i-1]);
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  DetExcess
+//
+//  using the result of the polynomial fit (fValues), DetExcess determines
+//
+//  - the total number of events in the signal region (fNon)
+//  - the number of backgound events in the signal region (fNbg)
+//  - the number of excess events (fNex)
+//  - the effective number of background events (fNoff), and fGamma :
+//    fNbg = fGamma * fNoff;  fdNbg = fGamma * sqrt(fNoff);
+//
+//  It assumed that the polynomial is defined as
+//               a0 + a1*x + a2*x**2 + a3*x**3 + ..
+//
+//  and that the alpha distribution has the range 0 < alpha < 90 degrees
+//
+
+Bool_t MHFindSignificance::DetExcess()
+{
+  //*fLog << "MHFindSignificance::DetExcess;" << endl;
+
+  //--------------------------------------------
+  // calculate the total number of events (fNon) in the signal region
+
+  fNon  = 0.0;
+  fdNon = 0.0;
+
+  Double_t alphaup = -1000.0; 
+  Double_t binwidth = fHist->GetBinWidth(1);
+
+  Int_t nbins = fHist->GetNbinsX();
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+ 
+    // bin must be completely contained in the signal region
+    if ( xlo <= (fAlphasig+fEps)  &&  xup <= (fAlphasig+fEps)    )
+    {
+      Double_t width = fabs(xup-xlo);
+      if (fabs(width-binwidth) > fEps)
+      {
+        *fLog << "MHFindSignificance::DetExcess; alpha plot has variable binning, which is not allowed" 
+          << endl;
+        return kFALSE;
+      }
+
+      if (xup > alphaup)
+        alphaup = xup;
+
+      fNon  += fHist->GetBinContent(i);
+      fdNon += fHist->GetBinError(i) * fHist->GetBinError(i);
+    }
+  }
+  fdNon = sqrt(fdNon);
+
+  // the actual signal range is :
+  if (alphaup == -1000.0)
+    return kFALSE;
+
+  fAlphasi = alphaup;
+
+  //*fLog << "fAlphasi, fNon, fdNon, binwidth, fDegree = " << fAlphasi << ",  "
+  //      << fNon << ",  " << fdNon << ",  " << binwidth << ",  "
+  //      << fDegree << endl;
+
+  //--------------------------------------------
+  // calculate the number of background events (fNbg) in the signal region
+  // and its error (fdNbg) 
+
+  Double_t fac = 1.0/binwidth;
+
+  fNbg         = 0.0;
+  Double_t altothejplus1 = fAlphasi;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    fNbg += fValues[j] * altothejplus1 / ((Double_t)(j+1));
+    altothejplus1 *= fAlphasi;
+  }
+  fNbg *= fac;
+
+  // derivative of Nbg 
+  Double_t facj;
+  Double_t fack;
+
+  Double_t sum = 0.0;
+  altothejplus1 = fAlphasi;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    facj = altothejplus1 / ((Double_t)(j+1));
+
+    Double_t altothekplus1 = fAlphasi;    
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      fack = altothekplus1 / ((Double_t)(k+1));
+
+      sum   += facj * fack * fEma[j][k];
+      altothekplus1 *= fAlphasi;
+    }
+    altothejplus1 *= fAlphasi;
+  }
+  sum  *= fac*fac;
+
+  if (sum < 0.0)
+  {
+    *fLog << "MHFindsignificance::DetExcess; error squared is negative" 
+          << endl;
+    return kFALSE;
+  }
+
+  fdNbg = sqrt(sum);
+
+
+  //--------------------------------------------
+  // AS A CHECK :
+  // calculate the number of background events (fNbgtotFitted) in the 
+  // background region, and its error (fdNbgtotFitted) 
+  // expect fdnbg to be approximately equal to sqrt(fNbgtotFitted)
+
+  Double_t fNmi = 0.0;
+  altothejplus1 = fAlphami;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    fNmi += fValues[j] * altothejplus1 / ((Double_t)(j+1));
+    altothejplus1 *= fAlphami;
+  }
+  fNmi *= fac;
+
+  Double_t fNma = 0.0;
+  altothejplus1 = fAlphama;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    fNma += fValues[j] * altothejplus1 / ((Double_t)(j+1));
+    altothejplus1 *= fAlphama;
+  }
+  fNma *= fac;
+
+  fNbgtotFitted  = fNma - fNmi;
+
+  //----------------------
+
+  sum = 0.0;
+  Double_t altothejma = fAlphama;
+  Double_t altothejmi = fAlphami;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    facj = (altothejma-altothejmi) / ((Double_t)(j+1));
+
+    Double_t altothekma = fAlphama;    
+    Double_t altothekmi = fAlphami;    
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      fack = (altothekma-altothekmi) / ((Double_t)(k+1));
+
+      sum   += facj * fack * fEma[j][k];
+      altothekma *= fAlphama;
+      altothekmi *= fAlphami;
+    }
+    altothejma *= fAlphama;
+    altothejmi *= fAlphami;
+  }
+  sum  *= fac*fac;
+
+  fdNbgtotFitted = sqrt(sum);
+  if ( fabs(fdNbgtotFitted - sqrt(fNbgtotFitted)) > 0.2 * sqrt(fNbgtotFitted) )
+  {
+    *fLog << "MHFindSignificance::DetExcess; error of calculated number of background events (in the background region) does not agree with the expectation :"
+          << endl;
+    *fLog << "                    fNbgtotFitted, fdNbgtotFitted = " 
+          << fNbgtotFitted << ",  " << fdNbgtotFitted
+          << ",  expected : " << sqrt(fNbgtotFitted) << endl;         
+  } 
+
+
+  //--------------------------------------------
+  // calculate the number of excess events in the signal region
+
+  fNex = fNon - fNbg;
+
+  //--------------------------------------------
+  // calculate the effective number of background events (fNoff) , and fGamma :
+  // fNbg = fGamma * fNoff;   dfNbg = fGamma * sqrt(fNoff);
+
+  if (fNbg < 0.0)
+  {
+    *fLog << "MHFindSignificamce::DetExcess; number of background events is negative,  fNbg, fdNbg = "
+          << fNbg  << ",  " << fdNbg << endl;
+
+    fGamma = 1.0;
+    fNoff  = 0.0;
+    return kFALSE;
+  }
+
+  if (fNbg > 0.0)
+  {
+    fGamma = fdNbg*fdNbg / fNbg;
+    fNoff  =  fNbg*fNbg  / (fdNbg*fdNbg);
+  }
+  else
+  {
+    fGamma = 1.0;
+    fNoff  = 0.0;
+  }
+
+  //*fLog << "Exit DetExcess()" << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  SigmaLiMa
+//
+//  calculates the significance according to Li & Ma
+//  ApJ 272 (1983) 317
+//
+Bool_t MHFindSignificance::SigmaLiMa(Double_t non,   Double_t noff, 
+                                     Double_t gamma, Double_t *siglima)
+{
+  if (gamma <= 0.0  ||  non <= 0.0  ||  noff <= 0.0)
+  {
+    *siglima = 0.0;
+    return kFALSE;
+  }
+
+  Double_t help1 = non  * log( (1.0+gamma)*non  / (gamma*(non+noff)) );
+  Double_t help2 = noff * log( (1.0+gamma)*noff / (       non+noff ) );
+  *siglima = sqrt( 2.0 * (help1+help2) );
+
+  Double_t nex = non - gamma*noff;
+  if (nex < 0.0)
+    *siglima = - *siglima;
+
+  //*fLog << "MHFindSignificance::SigmaLiMa; non, noff, gamma, *siglima = "
+  //      << non << ",  " << noff << ",  " << gamma << ",  " << *siglima << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MHFindSignificance::DrawFit(const Option_t *opt)
+{
+    if (fHist == NULL)
+      *fLog << "MHFindSignificance::DrawFit; fHist = NULL" << endl;
+
+
+    //TCanvas *fCanvas = new TCanvas("Alpha", "Alpha plot", 600, 600);
+//      fCanvas = new TCanvas(fHist->GetName(), "Alpha plot", 600, 600);
+
+    TVirtualPad *c = gPad ? gPad : MakeDefCanvas(this);
+
+    //gStyle->SetOptFit(1011);
+
+    gROOT->SetSelectedPad(NULL);    
+    gStyle->SetPadLeftMargin(0.1);
+
+//      fCanvas->cd();
+    c->cd();
+
+
+    if (fHist)
+    {
+      fHist->DrawCopy();
+    }
+
+    TF1 *fpoly = fHist->GetFunction("Poly");    
+    if (fpoly == NULL)
+      *fLog << "MHFindSignificance::DrawFit; fpoly = NULL" << endl;
+
+    if (fpoly)
+    {
+      // 2, 1 is red and solid
+      fpoly->SetLineColor(2);
+      fpoly->SetLineStyle(1);
+      fpoly->SetLineWidth(2);
+      fpoly->DrawCopy("same");
+    }
+
+    if (fFitGauss)
+    {
+      TF1 *fpolygauss = fHist->GetFunction("PolyGauss");    
+      if (fpolygauss == NULL)
+        *fLog << "MHFindSignificance::DrawFit; fpolygauss = NULL" << endl;
+
+      if (fpolygauss)
+      {
+        // 4, 1 is blue and solid
+        fpolygauss->SetLineColor(4);
+        fpolygauss->SetLineStyle(1);
+        fpolygauss->SetLineWidth(4);
+        fpolygauss->DrawCopy("same");
+      }
+
+      TF1 *fbackg = fHist->GetFunction("Backg");    
+      if (fbackg == NULL)
+        *fLog << "MHFindSignificance::DrawFit; fbackg = NULL" << endl;
+
+      if (fbackg)
+      {
+        // 6, 4 is pink and dotted
+        fbackg->SetLineColor(4);
+        fbackg->SetLineStyle(4);
+        fbackg->SetLineWidth(4);
+        fbackg->DrawCopy("same");
+      }
+    }
+
+
+    //-------------------------------
+    // print results onto the figure
+    TPaveText *pt = new TPaveText(0.30, 0.35, 0.70, 0.90, "NDC");
+    char tx[100];
+
+    sprintf(tx, "Results of polynomial fit (order %2d) :", fDegree);
+    TText *t1 = pt->AddText(tx);
+    t1->SetTextSize(0.03);
+    t1->SetTextColor(2);
+
+    sprintf(tx, "   (%6.2f< |alpha| <%6.2f [\\circ])", fAlphami, fAlphama);
+    pt->AddText(tx);
+
+    sprintf(tx, "   chi2 = %8.2f,  Ndof = %4d,  Prob = %6.2f", 
+            fChisq, fNdf, fProb);
+    pt->AddText(tx);
+
+    sprintf(tx, "   Nbgtot(fit) = %8.1f #pm %8.1f", 
+            fNbgtotFitted, fdNbgtotFitted);
+    pt->AddText(tx);
+
+    sprintf(tx, "   Nbgtot(meas) = %8.1f", fNbgtot);
+    pt->AddText(tx);
+
+
+    //sprintf(tx, "     ");
+    //pt->AddText(tx);
+
+    //--------------
+    sprintf(tx, "Results for |alpha|< %6.2f [\\circ] :", fAlphasi);
+    TText *t6 = pt->AddText(tx);
+    t6->SetTextSize(0.03);
+    t6->SetTextColor(8);
+
+    sprintf(tx, "   Non = %8.1f #pm %8.1f", fNon, fdNon);
+    pt->AddText(tx);
+
+    sprintf(tx, "   Nex = %8.1f #pm %8.1f", fNex, fdNex);
+    pt->AddText(tx);
+
+    sprintf(tx, "   Nbg = %8.1f #pm %8.1f,    gamma = %6.1f", 
+            fNbg, fdNbg, fGamma);
+    pt->AddText(tx);
+
+    Double_t ratio = fNbg>0.0 ? fNex/fNbg : 0.0;
+    sprintf(tx, "   Significance = %6.2f,    Nex/Nbg = %6.2f", 
+            fSigLiMa, ratio);
+    pt->AddText(tx);
+
+    //sprintf(tx, "     ");
+    //pt->AddText(tx);
+
+    //--------------
+    if (fFitGauss)
+    {
+      sprintf(tx, "Results of (polynomial+Gauss) fit  :");
+      TText *t7 = pt->AddText(tx);
+      t7->SetTextSize(0.03);
+      t7->SetTextColor(4);
+
+      sprintf(tx, "   chi2 = %8.2f,  Ndof = %4d,  Prob = %6.2f", 
+              fGChisq, fGNdf, fGProb);
+      pt->AddText(tx);
+
+      sprintf(tx, "   Sigma of Gauss = %8.1f #pm %8.1f  [\\circ]", 
+              fSigmaGauss, fdSigmaGauss);
+      pt->AddText(tx);
+
+      sprintf(tx, "   total no.of excess events = %8.1f #pm %8.1f", 
+              fNexGauss, fdNexGauss);
+      pt->AddText(tx);
+    }
+    //--------------
+
+    pt->SetFillStyle(0);
+    pt->SetBorderSize(0);
+    pt->SetTextAlign(12);
+
+    pt->Draw();
+
+//      fCanvas->Modified();
+//      fCanvas->Update();
+    c->Modified();
+    c->Update();
+
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Print the results of the polynomial fit to the alpha distribution
+// 
+//
+void MHFindSignificance::PrintPoly(Option_t *o) 
+{
+  *fLog << "---------------------------" << endl;
+  *fLog << "MHFindSignificance::PrintPoly :" << endl; 
+
+  *fLog << "fAlphami, fAlphama, fDegree, fAlphasi = "
+        << fAlphami << ",  " << fAlphama << ",  " << fDegree << ",  " 
+        << fAlphasi << endl;
+
+  *fLog << "fMbins, fNzero, fIstat = " << fMbins << ",  "
+        << fNzero << ",  " << fIstat << endl;
+
+  *fLog << "fChisq, fNdf, fProb = " << fChisq << ",  " 
+        << fNdf << ",  " << fProb << endl; 
+
+  *fLog << "fNon, fNbg, fdNbg, fNbgtot, fNbgtotFitted, fdNbgtotFitted = "
+        << fNon << ",  " << fNbg << ",  " << fdNbg << ",  " << fNbgtot 
+        << ",  " << fNbgtotFitted << ",  " << fdNbgtotFitted << endl;
+
+  Double_t sigtoback = fNbg>0.0 ? fNex/fNbg : 0.0;
+  *fLog << "fNex, fdNex, fGamma, fNoff, fSigLiMa, sigtoback = "
+        << fNex << ",  " << fdNex << ",  " << fGamma << ",  " << fNoff 
+        << ",  " << fSigLiMa << ",  " << sigtoback << endl;
+
+  //------------------------------------
+  // get errors
+
+  /*
+  Double_t eplus; 
+  Double_t eminus; 
+  Double_t eparab; 
+  Double_t gcc;
+  Double_t errdiag;
+
+
+  if ( !fConstantBackg )
+  {
+    *fLog << "parameter value     error     eplus     eminus    eparab   errdiag   gcc"
+          << endl; 
+
+    for (Int_t j=0; j<=fDegree; j++)
+    {
+      if (gMinuit)
+        gMinuit->mnerrs(j, eplus, eminus, eparab, gcc);
+      errdiag = sqrt(fEma[j][j]);
+      *fLog << j << "  " << fValues[j] << "  "   << fErrors[j] << "  "
+            << eplus     << "  "       << eminus << "  " << eparab     << "  " 
+            <<  errdiag  << "  "       << gcc    << endl;
+    }
+  }  
+  else
+  {
+    *fLog << "parameter value     error     errdiag "
+          << endl; 
+
+    for (Int_t j=0; j<=fDegree; j++)
+    {
+      errdiag = sqrt(fEma[j][j]);
+      *fLog << j << "  " << fValues[j] << "  "   << fErrors[j] << "  "
+            <<  errdiag  << endl;
+    }
+  }  
+  */
+
+  //----------------------------------------
+  /*
+  *fLog << "Covariance matrix :" << endl;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      *fLog << fEma[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "Correlation matrix :" << endl;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      *fLog << fCorr[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+  */
+
+  *fLog << "---------------------------" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the results of the (polynomial+Gauss) fit to the alpha distribution
+// 
+//
+void MHFindSignificance::PrintPolyGauss(Option_t *o) 
+{
+  *fLog << "---------------------------" << endl;
+  *fLog << "MHFindSignificance::PrintPolyGauss :" << endl; 
+
+  *fLog << "fAlphalo, fAlphahi = "
+        << fAlphalo << ",  " << fAlphahi << endl;
+
+  *fLog << "fGMbins, fGNzero, fGIstat = " << fGMbins << ",  "
+        << fGNzero << ",  " << fGIstat << endl;
+
+  *fLog << "fGChisq, fGNdf, fGProb = " << fGChisq << ",  " 
+        << fGNdf << ",  " << fGProb << endl; 
+
+
+  //------------------------------------
+  // get errors
+
+  Double_t eplus; 
+  Double_t eminus; 
+  Double_t eparab; 
+  Double_t gcc;
+  Double_t errdiag;
+
+  *fLog << "parameter value     error     eplus     eminus    eparab   errdiag   gcc"
+        << endl; 
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    if (gMinuit)
+      gMinuit->mnerrs(j, eplus, eminus, eparab, gcc);
+    errdiag = sqrt(fGEma[j][j]);
+    *fLog << j << "  " << fGValues[j] << "  "   << fGErrors[j] << "  "
+          << eplus     << "  "       << eminus << "  " << eparab     << "  " 
+          <<  errdiag  << "  "       << gcc    << endl;
+  }
+
+  
+  *fLog << "Covariance matrix :" << endl;
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=(fDegree+3); k++)
+    {
+      *fLog << fGEma[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "Correlation matrix :" << endl;
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=(fDegree+3); k++)
+    {
+      *fLog << fGCorr[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "---------------------------" << endl;
+}
+
+//============================================================================
+
Index: /tags/Mars-V0.9/mhist/MHFindSignificance.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHFindSignificance.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHFindSignificance.h	(revision 9772)
@@ -0,0 +1,211 @@
+#ifndef MARS_MHFindSignificance
+#define MARS_MHFindSignificance
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TF1;
+class TH1;
+class TCanvas;
+
+class MHFindSignificance : public MH
+{
+private:
+
+    TH1  *fHistOrig;  // original plot of |alpha| (0.0 to 90.0 degrees)
+    TH1  *fHist;      // copy of fHistOrig or rebinned histogram
+
+    TH1D    *fSigVsAlpha;
+
+    Double_t fAlphamin;  // requested lower limit of fit range
+    Double_t fAlphammm;  // center of fit range
+    Double_t fAlphamax;  // requested lower limit of fit range
+
+    Double_t fAlphami;  // actual lower limit of fit range 
+    Double_t fAlphamm;  // actual center of fit range 
+    Double_t fAlphama;  // actual upper limit of fit range
+
+    Double_t fAlphasig; // requested signal range
+    Double_t fAlphasi;  // actual signal range
+
+    Double_t fAlphalow; // requested lower edge of signal range
+    Double_t fAlphalo;  // actual lower edge of signal range
+
+    Double_t fAlphahig; // requested upper edge of background range
+    Double_t fAlphahi;  // actual upper edge of background range
+ 
+    // number of events in signal region
+    Double_t fNon;     // total number of events in signal region
+    Double_t fNbg;     // number of background events in signal region
+    Double_t fNex;     // number of excess events in signal region
+
+    Double_t fdNon;
+    Double_t fdNbg;
+    Double_t fdNex;
+
+    // number of events in background region
+    Double_t fNbgtot;  // total number of events in background region
+    Double_t fNbgtotFitted;  // fitted total no. of events in background region
+    Double_t fdNbgtotFitted; // fitted error of this number
+
+    // effective number of background events
+    Double_t fNoff;
+    Double_t fGamma;   // Nbg = Non - gamma * Noff
+
+    Double_t fSigLiMa; // significance of gamma signal according to Li & Ma
+
+    const static Double_t fEps = 1.e-4;  // tolerance for floating point comparisons
+
+    Bool_t fDraw;          // if true : draw plots
+    Bool_t fFitGauss;      // if true : do the (polynomial+Gauss fit)
+    Bool_t fRebin;         // if true : allow rebinning of the alpha plot    
+    Bool_t fReduceDegree;  // if true : allow reducing of the order of the polynomial
+
+    Bool_t fConstantBackg; // if set true if background fit is not possible
+                           // due to low statistics
+
+    TCanvas  *fCanvas;
+
+    Double_t fNexGauss;    // total number of excess events 
+                           // (from fitted Gauss function)
+    Double_t fdNexGauss;   // error of the total number of excess events
+ 
+    Double_t fSigmaGauss;  // sigma of fitted Gauss function
+    Double_t fdSigmaGauss; // error of this sigma
+
+    //--------------------
+    TF1      *fPoly;   // polynomial function
+    Int_t    fFitBad;  // if != 0 fit failed
+    Int_t    fDegree;  // degree of polynomial to be fitted to the background
+    Int_t    fNdf;     // number of degrees of freedom of polynomial fit
+    Double_t fChisq;   // chi squared of polynomial fit
+    Double_t fProb;    // chi squared probability ofg polynomial fit 
+
+    TArrayD fValues;
+    TArrayD fErrors;
+
+    const static Int_t    fNdim = 6;
+    Double_t fEmat[fNdim][fNdim];
+    Double_t fEma [fNdim][fNdim];
+    Double_t fCorr[fNdim][fNdim];
+
+    Int_t  fMbins;     // number of bins in the fit range
+    Int_t  fMlow;      // number of bins in the fit range with too few entries
+    Int_t  fNzero;     // number of bins in the fit range with zero entry
+    Int_t  fIstat;
+
+    //--------------------
+
+    //--------------------
+    TF1      *fGPoly;   // (Gauss+polynomial) function
+    TF1      *fGBackg;  // polynomial part of (Gauss+polynomial) function
+    Int_t    fGFitBad;  // if != 0 fit failed
+    Int_t    fGDegree;  // degree of polynomial to be fitted to the background
+    Int_t    fGNdf;     // number of degrees of freedom of polynomial fit
+    Double_t fGChisq;   // chi squared of polynomial fit
+    Double_t fGProb;    // chi squared probability ofg polynomial fit 
+
+    TArrayD fGValues;
+    TArrayD fGErrors;
+
+    const static Int_t    fGNdim = 9;
+    Double_t fGEmat[fGNdim][fGNdim];
+    Double_t fGEma[fGNdim][fGNdim];
+    Double_t fGCorr[fGNdim][fGNdim];
+
+    Int_t  fGMbins;     // number of bins in the fit range
+    Int_t  fGNzero;     // numnber of bins in the fit range with zero entry
+    Int_t  fGIstat;
+
+    //--------------------
+
+    static const TString gsDefName;  //! Default Name
+    static const TString gsDefTitle; //! Default Title
+
+    Bool_t DetExcess(); 
+    Bool_t FitPolynomial();
+    Bool_t FitGaussPoly();
+    Bool_t RebinHistogram(Double_t x0, Int_t nrebin);
+
+public:
+    MHFindSignificance(const char *name=NULL, const char *title=NULL);
+    ~MHFindSignificance();
+
+    Bool_t FindSigma(TH1 *fhist,  Double_t alphamin, Double_t alphamax, 
+                     Int_t degree, Double_t alphasig, 
+                     Bool_t drawpoly, Bool_t fitgauss, Bool_t print);
+
+    Bool_t SigmaLiMa(Double_t non, Double_t noff, Double_t gamma,
+                     Double_t *siglima);
+
+    Bool_t SigmaVsAlpha(TH1 *fhist,   Double_t alphamin, Double_t alphamax, 
+                        Int_t degree, Bool_t print);
+
+    Double_t GetSignificance()   { return fSigLiMa; }
+
+    Bool_t DrawFit(Option_t *opt=NULL);
+
+    Int_t    GetDegree()     const { return fDegree;  }
+    Double_t GetProb()       const { return fProb;    }
+    Int_t    GetNdf()        const { return fNdf;     }
+    Double_t GetGamma()      const { return fGamma;   }
+    Double_t GetNon()        const { return fNon;     }
+    Double_t GetNex()        const { return fNex;     }
+    Double_t GetNbg()        const { return fNbg;     }
+    Double_t GetSigLiMa()    const { return fSigLiMa; }
+    Int_t    GetMbins()      const { return fMbins;   }
+    Double_t GetAlphasi()    const { return fAlphasi; }
+
+    TH1* GetHist() const { return fHist;}
+    Double_t GetdNon() const { return fNon;}
+    Double_t GetdNbg() const {return fNbg; } 
+    Double_t GetdNex()        const { return fdNex;     }
+    Double_t GetNoff() const {return fNoff;}
+    Double_t GetChisq() const {return fChisq;}
+    Double_t GetNbgtotFitted() const {return fNbgtotFitted;}
+    Double_t GetdNbgtotFitted() const {return fNbgtotFitted;}
+    Double_t GetNbgtot() const {return fNbgtot;}
+    Double_t GetSigmaGauss() const {return fSigmaGauss;}
+    Double_t GetdSigmaGauss() const {return fdSigmaGauss;}
+    Double_t GetNexGauss() const {return fNexGauss;}
+    Double_t GetdNexGauss() const {return fdNexGauss;}
+    TF1*    GetGBackg()     const { return fGBackg;  }
+    TF1*    GetGPoly()      const { return fGPoly;   }
+    TF1*    GetPoly()       const { return fPoly;    }
+
+
+    void SetRebin(Bool_t b=kTRUE);
+    void SetReduceDegree(Bool_t b=kTRUE);
+
+    void PrintPoly(Option_t *opt=NULL);
+    void PrintPolyGauss(Option_t *opt=NULL);
+
+    ClassDef(MHFindSignificance, 1) // Determine significance from alpha plot
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHFlux.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHFlux.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHFlux.cc	(revision 9772)
@@ -0,0 +1,586 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 5/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHFlux                                                                 //
+//                                                                          //
+//  calculates absolute photon fluxes                                       //
+//             from the distributions of the estimated energy               //
+//                      for the different bins in some variable 'Var'       //
+//                      (Var = Theta or time)                               //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHFlux.h"
+
+#include <TStyle.h>
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TProfile.h>
+
+#include <TCanvas.h>
+
+#include "MTime.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHThetabarTheta.h"
+#include "MHEffOnTime.h"
+#include "MHGamma.h"
+
+ClassImp(MHFlux);
+
+using namespace std;
+
+MHFlux::MHFlux(const MHGamma &hist, const TString varname, const TString unit)
+    : fHOrig(), fHUnfold(), fHFlux()
+{
+    const TH2D &h2d = *hist.GetProject();
+
+    if (varname.IsNull() || unit.IsNull())
+        *fLog << warn << dbginf << "varname or unit not defined" << endl;
+
+    fVarname = varname;
+    fUnit    = unit;
+
+    // char txt[100];
+
+    // original distribution of E-est for different bins 
+    //                       of the variable (Theta or time)
+    // sprintf(txt, "gammas vs. E-est and %s",varname);
+
+    ((TH2D&)h2d).Copy(fHOrig);
+
+    fHOrig.SetName("E_est");
+    fHOrig.SetTitle(TString("No.of gammas vs. E-est and ")+fVarname);
+
+    fHOrig.SetDirectory(NULL);
+    fHOrig.SetXTitle("E_{est} [GeV]");
+    fHOrig.SetYTitle(fVarname+fUnit);
+    //fHOrig.Sumw2();
+
+    SetBinning((TH2*)&fHOrig, (TH2*)&h2d);
+
+    fHOrig.Copy(fHUnfold);
+
+    // unfolded distribution of E-unfold for different bins 
+    //                       of the variable (Theta or time)
+    // sprintf(txt, "gammas vs. E-unfold and %s",varname);
+    fHUnfold.SetName("E-unfolded");
+    fHUnfold.SetTitle(TString("No.of gammas vs. E-unfold and ")+fVarname);
+
+    fHUnfold.SetDirectory(NULL);
+    fHUnfold.SetXTitle("E_{unfold} [GeV]");
+    fHUnfold.SetYTitle(fVarname+fUnit);
+    //fHUnfold.Sumw2();
+    
+    SetBinning((TH2*)&fHUnfold, (TH2*)&fHOrig);
+
+
+    // absolute photon flux vs. E-unfold
+    //          for different bins of the variable (Theta or time)
+    //
+    // sprintf(txt, "gamma flux [1/(s m2 GeV) vs. E-unfold and %s",varname);
+    fHFlux.SetName("photon flux");
+    fHFlux.SetTitle(TString("Gamma flux [1/(s m^2 GeV) vs. E-unfold and ")+fVarname);
+
+    fHFlux.SetDirectory(NULL);
+    fHFlux.SetXTitle("E_{unfold} [GeV]");
+    fHFlux.SetYTitle(fVarname+fUnit);
+    fHFlux.Sumw2();
+
+    SetBinning((TH2*)&fHFlux, (TH2*)&fHUnfold);
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets the variable name (Theta or time)
+//                      and the units for the variable
+// 
+MHFlux::MHFlux(const TH2D &h2d, const TString varname, const TString unit)
+    : fHOrig(), fHUnfold(), fHFlux()
+{
+    if (varname.IsNull() || unit.IsNull())
+        *fLog << warn << dbginf << "varname or unit not defined" << endl;
+
+    fVarname = varname;
+    fUnit    = unit;
+
+    // char txt[100];
+
+    // original distribution of E-est for different bins 
+    //                       of the variable (Theta or time)
+    // sprintf(txt, "gammas vs. E-est and %s",varname);
+
+    ((TH2D&)h2d).Copy(fHOrig);
+
+    fHOrig.SetName("E_est");
+    fHOrig.SetTitle(TString("No.of gammas vs. E-est and ")+fVarname);
+
+    fHOrig.SetDirectory(NULL);
+    fHOrig.SetXTitle("E_{est} [GeV]");
+    fHOrig.SetYTitle(fVarname+fUnit);
+    //fHOrig.Sumw2();
+
+    // copy fHOrig into fHUnfold in case no unfolding is done
+    fHOrig.Copy(fHUnfold);
+
+    SetBinning((TH2*)&fHOrig, (TH2*)&h2d);
+
+
+    // unfolded distribution of E-unfold for different bins 
+    //                       of the variable (Theta or time)
+    // sprintf(txt, "gammas vs. E-unfold and %s",varname);
+    fHUnfold.SetName("E-unfolded");
+    fHUnfold.SetTitle(TString("No.of gammas vs. E-unfold and ")+fVarname);
+
+    fHUnfold.SetDirectory(NULL);
+    fHUnfold.SetXTitle("E_{unfold} [GeV]");
+    fHUnfold.SetYTitle(fVarname+fUnit);
+    //fHUnfold.Sumw2();
+    
+    SetBinning((TH2*)&fHUnfold, (TH2*)&fHOrig);
+
+
+    // absolute photon flux vs. E-unfold
+    //          for different bins of the variable (Theta or time)
+    //
+    // sprintf(txt, "gamma flux [1/(s m2 GeV) vs. E-unfold and %s",varname);
+    fHFlux.SetName("photon flux");
+    fHFlux.SetTitle(TString("Gamma flux [1/(s m^{2} GeV)] vs. E-unfold and ")+fVarname);
+
+    fHFlux.SetDirectory(NULL);
+    fHFlux.SetXTitle("E_{unfold} [GeV]");
+    fHFlux.SetYTitle(fVarname+fUnit);
+    fHFlux.Sumw2();
+
+    SetBinning((TH2*)&fHFlux, (TH2*)&fHUnfold);
+}
+
+// -------------------------------------------------------------------------
+//
+// Unfold the distribution in E-est
+//
+void MHFlux::Unfold()
+{
+}
+
+void MHFlux::CalcFlux(const MHEffOnTime &teff, const MHThetabarTheta &thetabar,
+                      const TH2D *aeff)
+{
+    CalcFlux(teff.GetHist(), thetabar.GetHist(), aeff);
+}
+
+Double_t MHFlux::ParabInterpolLog(const TAxis &axe, Int_t j,
+                                  Double_t y[], Double_t Ebar) const
+{
+    const double t1 = log10(axe.GetBinLowEdge(j-1)) + log10(axe.GetBinUpEdge(j-1));
+    const double t2 = log10(axe.GetBinLowEdge(j))   + log10(axe.GetBinUpEdge(j));
+    const double t3 = log10(axe.GetBinLowEdge(j+1)) + log10(axe.GetBinUpEdge(j+1));
+
+    const Double_t lebar = log10(Ebar);
+
+    return Parab(t1/2, t2/2, t3/2, y[j-2], y[j-1], y[j], lebar);
+}
+
+// --------------------------------------------------------------------
+//
+//  determine bins for interpolation (k3 is the middle one) in bar.
+//  k0 denotes the bin from which the error is copied
+//
+void MHFlux::FindBins(const TAxis &axe, const Double_t bar, Int_t &k3, Int_t &k0) const
+{
+    const Int_t n = axe.GetNbins();
+
+    k3 = axe.FindFixBin(bar);
+    k0 = k3;
+
+    if (k3<2)
+    {
+        k3 = 2;
+        if (bar<axe.GetBinLowEdge(2))
+            k0 = 1;
+    }
+
+    if (k3>n-1)
+    {
+        k3 = n-1;
+        if (bar>axe.GetBinLowEdge(n))
+            k0 = n;
+    }
+
+    if (bar>=axe.GetBinLowEdge(1) && bar<=axe.GetBinUpEdge(n))
+        return;
+
+    *fLog << dbginf << "extrapolation: bar = " << bar;
+    *fLog << ", min =" << axe.GetBinLowEdge(1);
+    *fLog << ", max =" << axe.GetBinUpEdge(n) << endl;
+}
+
+Double_t MHFlux::ParabInterpolCos(const TAxis &axe, const TH2D *aeff, Int_t j, Int_t k3, Double_t val) const
+{
+    const double t1 = cos( axe.GetBinCenter (k3-1) );
+    const double t2 = cos( axe.GetBinCenter (k3)   );
+    const double t3 = cos( axe.GetBinCenter (k3+1) );
+
+    const double a1 = aeff->GetBinContent(j, k3-1);
+    const double a2 = aeff->GetBinContent(j, k3);
+    const double a3 = aeff->GetBinContent(j, k3+1);
+
+    return Parab(t1, t2, t3, a1, a2, a3, val);
+}
+
+// -------------------------------------------------------------------------
+//
+// Calculate photon flux by dividing the distribution in Eunf (fHUnfold) by
+//                       the width of the energy interval     (deltaE)
+//                       the effective ontime                 (*teff)
+//                       and the effective collection area    (*aeff)
+//
+void MHFlux::CalcFlux(const TH1D *teff, const TProfile *thetabar,
+                      const TH2D *aeff)
+{
+    //
+    // Note that fHUnfold  has bins in Eunf and Var
+    //           *teff     has bins in Var  (the same bins in Var as fHUnfold)
+    //           *thetabar has bins in Var  (the same bins in Var as fHUnfold)
+    //           *aeff     has bins in Etru and Theta
+    //                     (where in general the binning in Etru is different
+    //                      from the binning in Eunf)
+    // The variable Var may be 'time' or 'Theta'
+
+    const TAxis &axex = *((TH2*)aeff)->GetXaxis();
+    const TAxis &axey = *((TH2*)aeff)->GetYaxis();
+
+    if (axex.GetNbins()<3)
+    {
+        *fLog << err << "ERROR - Number of Energy bins <3 not implemented!" << endl;
+        return;
+    }
+
+    if (axey.GetNbins()<3)
+        *fLog << warn << "WARNING - Less than 3 theta-bins not supported very well!" << endl;
+
+    //
+    // calculate effective collection area
+    //    for the Eunf and Var bins of the histogram fHUnfold
+    //    from the histogram *aeff, which has bins in Etru and Theta
+    // the result is the histogram fHAeff
+    //
+    TH2D fHAeff;
+    SetBinning((TH2*)&fHAeff, (TH2*)&fHUnfold);
+    fHAeff.Sumw2();
+
+    //
+    // ------ start loops ------
+    //
+    const Int_t nEtru = aeff->GetNbinsX();
+
+    Double_t *aeffbar  = new Double_t[nEtru];
+    Double_t *daeffbar = new Double_t[nEtru];
+
+    const Int_t nVar = fHFlux.GetNbinsY();
+    for (int n=1; n<=nVar; n++)
+    {
+        const Double_t tbar = thetabar->GetBinContent(n);
+        const Double_t costbar = cos(tbar/kRad2Deg);
+
+        // determine bins for interpolation (k3, k0)
+        Int_t kv, ke;
+        FindBins(axey, tbar, kv, ke);
+
+        //
+        // calculate effective collection area at Theta = Thetabar
+        // by quadratic interpolation in cos(Theta);
+        // do this for each bin of Etru
+        //
+        for (int j=1; j<=nEtru; j++)
+        {
+            if (axey.GetNbins()<3)
+            {
+                // FIXME: Other interpolation?
+                aeffbar[j-1]  = aeff->GetBinContent(j, n);
+                daeffbar[j-1] = aeff->GetBinError(j, n);
+            }
+            else
+            {
+                aeffbar[j-1]  = ParabInterpolCos(axey, aeff, j, kv, costbar);
+                daeffbar[j-1] = aeff->GetBinError(j, ke);
+            }
+        }
+
+        //
+        // calculate effective collection area at (E = Ebar, Theta = Thetabar)
+        // by quadratic interpolation in log10(Etru)
+        // do this for each bin of Eunf
+        //
+        CalcEffCol(axex, fHAeff, n, aeffbar, daeffbar);
+    }
+
+    delete aeffbar;
+    delete daeffbar;
+
+    //
+    // now calculate the absolute gamma flux
+    //
+    CalcAbsGammaFlux(*teff, fHAeff);
+}
+
+// --------------------------------------------------------------------
+//
+//  calculate effective collection area at (E = Ebar, Theta = Thetabar)
+//  by quadratic interpolation in log10(Etru)
+//  do this for each bin of Eunf
+//
+void MHFlux::CalcEffCol(const TAxis &axex, TH2D &fHAeff, Int_t n, Double_t aeffbar[], Double_t daeffbar[])
+{
+    const Int_t nEunf = fHFlux.GetNbinsX();
+
+    const TAxis &unfx = *fHUnfold.GetXaxis();
+
+    for (int m=1; m<=nEunf; m++)
+    {
+        const Double_t Ebar = GetBinCenterLog(unfx, m);
+
+        Int_t j0, j3;
+        FindBins(axex, Ebar, j3, j0);
+
+        const Double_t v = ParabInterpolLog(axex, j3, aeffbar, Ebar);
+
+        fHAeff.SetBinContent(m,n, v);
+        fHAeff.SetBinError(m,n, daeffbar[j0-1]);
+    }
+}
+
+// --------------------------------------------------------------------
+//
+//  calculate the absolute gamma flux
+//
+void MHFlux::CalcAbsGammaFlux(const TH1D &teff, const TH2D &fHAeff)
+{
+    const Int_t nEunf = fHFlux.GetNbinsX();
+    const Int_t nVar  = fHFlux.GetNbinsY();
+
+    for (int m=1; m<=nEunf; m++)
+    {
+        const Double_t DeltaE = fHFlux.GetXaxis()->GetBinWidth(m);
+
+        for (int n=1; n<=nVar; n++)
+        {
+            const Double_t Ngam  = fHUnfold.GetBinContent(m,n);
+            const Double_t Aeff  = fHAeff.GetBinContent(m,n);
+            const Double_t Effon = teff.GetBinContent(n);
+
+            const Double_t c1 = fHUnfold.GetBinError(m,n)/Ngam;
+            const Double_t c2 = teff.GetBinError(n)      /Effon;
+            const Double_t c3 = fHAeff.GetBinError(m,n)  /Aeff;
+
+            const Double_t cont  = Ngam / (DeltaE * Effon * Aeff);
+            const Double_t dcont = sqrt(c1*c1 + c2*c2 + c3*c3);
+
+            //
+            // Out of Range
+            //
+            const Bool_t oor = Ngam<=0 || DeltaE<=0 || Effon<=0 || Aeff<=0;
+
+            if (oor)
+                *fLog << warn << "MHFlux::CalcAbsGammaFlux(" << m << "," << n << ") ";
+
+            if (Ngam<=0)
+                *fLog << " Ngam=0";
+            if (DeltaE<=0)
+                *fLog << " DeltaE=0";
+            if (Effon<=0)
+                *fLog << " Effon=0";
+            if (Aeff<=0)
+                *fLog << " Aeff=0";
+
+            if (oor)
+                *fLog << endl;
+
+            fHFlux.SetBinContent(m,n, oor ? 1e-20 : cont);
+            fHFlux.SetBinError(m,n,   oor ? 1e-20 : dcont*cont);
+        }
+    }
+}
+
+// --------------------------------------------------------------------
+//
+// draw the differential photon flux vs. E-unf
+// for the individual bins of the variable Var
+//
+void MHFlux::DrawFluxProjectionX(Option_t *opt) const
+{
+    const Int_t nVar = fHFlux.GetNbinsY();
+
+    for (int n=1; n<=nVar; n++)
+    {
+        TString strg0("Flux-");
+
+        TH1D &h = *((TH2D)fHFlux).ProjectionX(strg0+fVarname, n, n, "E");
+
+        TString strg1 = "Photon flux vs. E_{unfold} for ";
+        TString strg2 = fVarname+"-bin #";
+        strg2 += n;
+
+        new TCanvas(strg2, strg1+strg2);
+        gPad->SetLogx();
+        gPad->SetLogy();
+
+        TString name = fVarname+"bin_";
+        name += n;
+
+        h.SetName(name);
+        h.SetTitle(strg1+strg2);
+        h.SetXTitle("E_{unfold} [GeV]");
+        h.SetYTitle("photons / (s m^{2} GeV)");
+        h.GetXaxis()->SetLabelOffset(-0.025);
+        h.GetXaxis()->SetTitleOffset(1.1);
+        h.GetXaxis()->SetNdivisions(1);
+        h.GetYaxis()->SetTitleOffset(1.25);
+        h.DrawCopy();
+     }
+}
+
+void MHFlux::DrawOrigProjectionX(Option_t *opt) const
+{
+    const Int_t nVar = fHOrig.GetNbinsY();
+
+    for (int n=1; n<=nVar; n++)
+    {
+        TString strg0 = "Orig-";
+        strg0 += fVarname;
+        strg0 += "_";
+        strg0 += n;
+
+        TH1D &h = *((TH2D)fHOrig).ProjectionX(strg0, n, n, "E");
+
+        TString strg1("No.of photons vs. E-est for ");
+        strg1 += fVarname+"-bin ";
+        strg1 += n;
+
+        new TCanvas(strg0, strg1);
+
+        gPad->SetLogx();
+        gPad->SetLogy();
+
+        h.SetName(strg0);
+        h.SetTitle(strg1);
+        h.SetXTitle("E_{est} [GeV]");
+        h.GetXaxis()->SetLabelOffset(-0.025);
+        h.GetXaxis()->SetTitleOffset(1.1);
+        h.GetXaxis()->SetNdivisions(1);
+        h.SetYTitle("No.of photons");
+        h.DrawCopy();
+    }
+}
+
+// -------------------------------------------------------------------------
+//
+//  Draw the histograms
+//
+void MHFlux::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fHOrig.Draw(opt);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fHUnfold.Draw(opt);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fHFlux.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+}
+
+Double_t MHFlux::Parab(Double_t x1, Double_t x2, Double_t x3,
+                       Double_t y1, Double_t y2, Double_t y3,
+                       Double_t val)
+{
+    Double_t c0, c1, c2;
+    Parab(x1, x2, x3, y1, y2, y3, &c0, &c1, &c2);
+    return c0 + c1*val + c2*val*val;
+}
+
+// -------------------------------------------------------------------------
+//
+// Quadratic interpolation
+//
+// *** calculate the parameters of a parabula 
+//                      y = a + b*x + c*x**2 = F(x)
+//     such that       yi = F(xi)       for (i=1,3)
+//
+Bool_t MHFlux::Parab(Double_t x1, Double_t x2, Double_t x3,
+                     Double_t y1, Double_t y2, Double_t y3,
+                     Double_t *a, Double_t *b, Double_t *c)
+{
+    const double det =
+        + x2*x3*x3 + x1*x2*x2 + x3*x1*x1
+        - x2*x1*x1 - x3*x2*x2 - x1*x3*x3;
+
+    if (det==0)
+    {
+        *a = 0;
+        *b = 0;
+        *c = 0;
+        return kFALSE;
+    }
+
+    const double det1 = 1.0/det;
+
+    const double ai11 = x2*x3*x3 - x3*x2*x2;
+    const double ai12 = x3*x1*x1 - x1*x3*x3;
+    const double ai13 = x1*x2*x2 - x2*x1*x1;
+
+    const double ai21 = x2*x2 - x3*x3;
+    const double ai22 = x3*x3 - x1*x1;
+    const double ai23 = x1*x1 - x2*x2;
+
+    const double ai31 = x3 - x2;
+    const double ai32 = x1 - x3;
+    const double ai33 = x2 - x1;
+
+    *a = (ai11*y1 + ai12*y2 + ai13*y3) * det1;
+    *b = (ai21*y1 + ai22*y2 + ai23*y3) * det1;
+    *c = (ai31*y1 + ai32*y2 + ai33*y3) * det1;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mhist/MHFlux.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHFlux.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHFlux.h	(revision 9772)
@@ -0,0 +1,92 @@
+#ifndef MARS_MHFlux
+#define MARS_MHFlux
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class TH2D;
+
+class MHGamma;
+class MHEffOnTime;
+class MHThetabarTheta;
+
+// base class MH is used because it defines "MakeDefCanvas"
+// if base class MH is used one has to define the member function Fill
+//                          because in MH Fill is set to zero
+class MHFlux : public MH 
+{
+private:
+
+    TString fVarname;
+    TString fUnit;
+
+    TH2D fHOrig;       // original distribution of E-est 
+    TH2D fHUnfold;     // unfolded distribution of E-unfold
+    TH2D fHFlux;       // absolute differential photon flux versus E-unfold
+    // all these plots for different bins of the variable (Theta or time)
+
+    void CalcEffCol(const TAxis &axex, TH2D &aeff, Int_t n, Double_t aeffbar[], Double_t daeffbar[]);
+    Double_t ParabInterpolCos(const TAxis &axe, const TH2D *aeff, Int_t j, Int_t k3, Double_t val) const;
+    void FindBins(const TAxis &axe, const Double_t bar, Int_t &k3, Int_t &k0) const;
+    void CalcAbsGammaFlux(const TH1D &teff, const TH2D &fHAeff);
+    Double_t ParabInterpolLog(const TAxis &axe, Int_t j,
+                              Double_t y[], Double_t Ebar) const;
+
+public:
+    MHFlux(const TH2D &h2d, const TString varname, const TString unit);
+    MHFlux(const MHGamma &h2d, const TString varname, const TString unit);
+
+    void Unfold();
+    void CalcFlux(const TH1D *teff, const TProfile *thetabar,
+                  const TH2D *aeff);
+
+    void CalcFlux(const MHEffOnTime &teff,
+                  const MHThetabarTheta &thetabar,
+                  const TH2D *aeff);
+
+    void Draw(Option_t *option="");
+
+    void DrawFluxProjectionX(Option_t *opt="") const;
+    void DrawOrigProjectionX(Option_t *opt="") const;
+
+    const TH2D *GetHOrig()       { return &fHOrig; }
+    const TH2D *GetHUnfold()     { return &fHUnfold; }
+    const TH2D *GetHFlux()       { return &fHFlux; }
+
+    static Bool_t Parab(double x1, double x2, double x3,
+                        double y1, double y2, double y3,
+                        double *a, double *b, double *c);
+
+    static Double_t Parab(double x1, double x2, double x3,
+                          double y1, double y2, double y3,
+                          double val);
+
+    ClassDef(MHFlux, 0) //2D-plots (original, unfolded, flux)
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHGamma.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHGamma.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHGamma.cc	(revision 9772)
@@ -0,0 +1,286 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and time saving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 6/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHGamma                                                                 //
+//                                                                          //
+//  manipulation of alpha distributions                                     //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHGamma.h"
+
+#include <TCanvas.h>
+#include <TPad.h>
+
+#include <math.h>
+
+#include <TH2.h>
+#include <TH3.h>
+
+#include "MHAlphaEnergyTheta.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHGamma);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+MHGamma::MHGamma(const TString &name, const TString &title)
+    : fHist(NULL), fProject(NULL)
+{
+    fName  = name.IsNull()  ? (TString)"MHGamma" : name;
+    fTitle = title.IsNull() ? (TString)"3D-histogram of Alpha, E_est, Theta (Gamma sample)" : title;
+}
+
+TH3D *MHGamma::Subtract(const MHAlphaEnergyTheta &h1, const MHAlphaEnergyTheta &h2)
+{
+    return Subtract(h1.GetHist(), h2.GetHist());
+}
+
+TObject *MHGamma::DrawClone(Option_t *opt) const
+{
+    DrawClone1();
+    DrawClone2();
+
+    return NULL;
+}
+
+void MHGamma::DrawClone1() const
+{
+    if (!fHist)
+        return;
+
+    //
+    // ------------- Part 1 ---------------------
+    //
+    TString titlex = fHist->GetXaxis()->GetTitle();
+    TString titley = fHist->GetYaxis()->GetTitle();
+    TString titlez = fHist->GetYaxis()->GetTitle();
+
+    TString canvtitle = "3D-plot "; //of ";
+    /*
+     canvtitle += titlex;
+     canvtitle += ", ";
+     canvtitle += titley;
+     canvtitle += ", ";
+     canvtitle += titlez+" ";
+     */
+    canvtitle += "for 'gamma' sample";
+
+    TCanvas &c = *MakeDefCanvas("Alpha", canvtitle);
+
+    c.Divide(2, 2);
+
+    gROOT->SetSelectedPad(NULL);
+
+    TH1 *h;
+
+    c.cd(1);
+    h = ((TH3D*)(fHist))->Project3D(fName+"_ex");
+
+    TString title= "Source-Antisource: ";
+    h->SetTitle(title + titlex);
+    h->SetXTitle(titlex);
+    h->SetYTitle("Counts");
+
+    h->Draw();
+    h->SetBit(kCanDelete);
+
+    c.cd(2);
+    h = ((TH3D*)(fHist))->Project3D(fName+"_ey");
+
+    h->SetTitle(title + titley);
+    h->SetXTitle(titley);
+    h->SetYTitle("Counts");
+
+    h->Draw();
+    h->SetBit(kCanDelete);
+    gPad->SetLogx();
+
+    c.cd(3);
+    h = ((TH3D*)(fHist))->Project3D(fName+"_ez");
+
+    h->SetTitle(title + titlez);
+    h->SetXTitle(titlez);
+    h->SetYTitle("Counts");
+
+    h->Draw();
+    h->SetBit(kCanDelete);
+
+    c.cd(4);
+    ((TH3D*)fHist)->DrawCopy();
+
+    c.Modified();
+    c.Update();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculate the histogram as the difference of two histograms :
+//          fHist(gamma) = h1(source) - h2(antisource)
+// 
+TH3D *MHGamma::Subtract(const TH3D *h1, const TH3D *h2)
+{
+    if (fHist)
+        delete fHist;
+
+    fHist = new TH3D;
+    fHist->SetName(fName);
+    fHist->SetTitle(fTitle);
+    fHist->SetDirectory(NULL);
+
+    SetBinning((TH1*)fHist, (TH1*)h1);
+
+    fHist->SetXTitle((((TH1*)h1)->GetXaxis())->GetTitle());
+    fHist->SetYTitle((((TH1*)h1)->GetYaxis())->GetTitle());
+    fHist->SetZTitle((((TH1*)h1)->GetZaxis())->GetTitle());
+
+    fHist->Add((TH1*)h1, (TH1*)h2, 1, -1); // ROOT: FIXME!
+
+    return fHist;
+}
+
+// --------------------------------------------------------------------------
+//
+// Integrate fHist(gamma) in the alpha range (lo, up)
+// 
+TH2D *MHGamma::GetAlphaProjection(Axis_t lo, Axis_t up)
+{
+    if (up < lo)
+    {
+        *fLog << err << fName << "MHGamma : Alpha projection not possible: lo=" << lo << " up=" << up << endl;
+        return NULL;
+    }
+
+    TAxis &axe = *fHist->GetXaxis();
+
+    Int_t ilo = axe.FindFixBin(lo);
+    Int_t iup = axe.FindFixBin(up);
+
+    const Double_t epslo1 = lo-axe.GetBinLowEdge(ilo);
+    const Double_t epslo2 = axe.GetBinUpEdge(ilo)-lo;
+
+    const Double_t epsup1 = up-axe.GetBinLowEdge(iup);
+    const Double_t epsup2 = axe.GetBinUpEdge(iup)-up;
+
+    const Double_t epslo = epslo1<epslo2 ? epslo1 : epslo2;
+    const Double_t epsup = epsup1<epsup2 ? epsup1 : epsup2;
+
+    if (epslo1>epslo2)
+        ilo++;
+
+    if (epsup1<epsup2)
+        iup--;
+
+    if (epslo>0.01*axe.GetBinWidth(ilo) || epsup>0.01*axe.GetBinWidth(iup))
+    {
+        *fLog << err << fName << "MHGamma : binning is not adequate for the requested projection:" << endl;
+        *fLog << "Please specify a lower or upper limit which is not more than 1% away from a bin edge" << endl;
+        *fLog << " epslo = " << epslo << endl;
+        *fLog << " epsup = " << epsup << endl;
+        *fLog << " dwl   = " << axe.GetBinWidth(ilo) << endl;
+        *fLog << " dwu   = " << axe.GetBinWidth(iup) << endl;
+        return NULL;
+    }
+
+    axe.SetRange(ilo, iup);
+
+    fLo = lo;
+    fHi = up;
+
+    if (fProject)
+        delete fProject;
+    fProject = (TH2D*)fHist->Project3D(fName+"_ezy");
+
+    const TString title = "2D-plot of ";
+    const TString titley = fHist->GetYaxis()->GetTitle();
+    const TString titlez = fHist->GetZaxis()->GetTitle();
+
+    fProject->SetTitle(title + titley + " vs. " + titlez);
+    fProject->SetXTitle(titley);
+    fProject->SetYTitle(titlez);
+
+    return fProject;
+}
+
+void MHGamma::DrawClone2() const
+{
+    if (!fProject)
+        return;
+
+    const TString titley = fHist->GetYaxis()->GetTitle();
+    const TString titlez = fHist->GetZaxis()->GetTitle();
+
+    TString canvtitle = "No.of Gammas ";//vs. ";
+    /*
+     canvtitle += titley;
+     canvtitle += " and ";
+     canvtitle += titlez;
+     */
+    canvtitle += Form("(%.1f < alpha < %.1f deg)", fLo, fHi);
+
+    TCanvas &c = *MakeDefCanvas("Gamma", canvtitle);
+
+    c.Divide(2, 2);
+
+    gROOT->SetSelectedPad(NULL);
+
+    TH1 *h;
+
+    c.cd(1);
+    h = fProject->ProjectionX(fName+"_xpro", -1, 9999, "E");
+    TString title = "No.of gammas: ";
+    h->SetTitle(title+titley);
+    h->SetXTitle(titley);
+    h->SetYTitle("Counts");
+
+    h->Draw();
+    h->SetBit(kCanDelete);
+    gPad->SetLogx();
+
+    c.cd(2);
+    h = fProject->ProjectionY(fName+"_ypro", -1, 9999, "E");
+    h->SetTitle(title+titlez);
+    h->SetXTitle(titlez);
+    h->SetYTitle("Counts");
+
+    h->Draw();
+    h->SetBit(kCanDelete);
+
+    c.cd(3);
+
+    fProject->DrawCopy();
+    gPad->SetLogx();
+
+    c.Modified();
+    c.Update();
+}
Index: /tags/Mars-V0.9/mhist/MHGamma.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHGamma.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHGamma.h	(revision 9772)
@@ -0,0 +1,46 @@
+#ifndef MARS_MHGamma
+#define MARS_MHGamma
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH2D;
+class TH3D;
+
+class MHAlphaEnergyTheta;
+
+class MHGamma : public MH 
+{
+private:
+    TH3D *fHist;    //!
+    TH2D *fProject; //!
+
+    Axis_t fLo; //!
+    Axis_t fHi; //!
+
+public:
+    MHGamma(const TString &name="", const TString &title="");
+
+    TH3D *Subtract(const TH3D *h1, const TH3D *h2);
+
+    TH3D *Subtract(const MHAlphaEnergyTheta &h1, const MHAlphaEnergyTheta &h2);
+
+    TH2D *GetAlphaProjection(Axis_t lo, Axis_t up);
+
+    TObject *DrawClone(Option_t *opt="") const;
+    void DrawClone1() const;
+    void DrawClone2() const;
+
+    const TH2D *GetProject() const { return fProject; }
+
+    ClassDef(MHGamma, 0) // manipulation of alpha distributions
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHHadronness.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHHadronness.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHHadronness.cc	(revision 9772)
@@ -0,0 +1,576 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHHadronness
+//
+// This is histogram is a way to evaluate the quality of a gamma/hadron
+// seperation method. It is filled from a MHadronness container, which
+// stores a hadroness for the current event. The Value must be in the
+// range [0,1]. To fill the histograms correctly the information
+// whether it is a gamma or hadron (not a gamma) must be available from
+// a MMcEvt container.
+//
+// In the constructor you can change the number of used bns for the
+// evaluation.
+//
+// The meaning of the histograms (Draw, DrawClone) are the following:
+//  * Upper Left Corner:
+//    - black: histogram of all hadronesses for gammas
+//    - red:   histogram of all hadronesses for non gammas
+//  * Upper Right Corner:
+//    - black: acceptance of gammas (Ag) vs. the hadroness
+//    - red:   acceptance of non gammas (Ah) vs. the hadroness
+//  * Bottom Left Corner:
+//    Naive quality factor: Ag/sqrt(Ah)
+//  * Bottom Right Corner:
+//    - black: Acceptance Gammas vs. Acceptance Hadrons
+//    - blue cross: minimum of distance to (0, 1)
+//
+// As a default MHHadronness searches for the container "MHadronness".
+// This can be overwritten by a different pointer specified in the
+// Fill function (No type check is done!) Use a different name in
+// MFillH.
+//
+// If you are using filtercuts which gives you only two discrete values
+// of the hadronness (0.25 and 0.75) you may want to use MHHadronness(2).
+// If you request Q05() from such a MHHadronness instance you will get
+// Acc_g/sqrt(Acc_h)
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHHadronness.h"
+
+#include <TPad.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MHMatrix.h"
+#include "MHadronness.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MHHadronness);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms, nbins is the number of bins used for the evaluation.
+// The default is 100 bins.
+//
+MHHadronness::MHHadronness(Int_t nbins, const char *name, const char *title)
+    : fMatrix(NULL)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHHadronness";
+    fTitle = title ? title : "Gamma/Hadron Separation Quality Histograms";
+
+    fGraph = new TGraph;
+    fGraph->SetTitle("Acceptance Gammas vs. Hadrons");
+    fGraph->SetMarkerStyle(kFullDotSmall);
+
+    fGhness = new TH1D("Ghness", "Acceptance vs. Hadronness (Gammas)",  nbins, 0, 1.0001);
+    fPhness = new TH1D("Phness", "Acceptance vs. Hadronness (Hadrons)", nbins, 0, 1.0001);
+    fGhness->SetXTitle("Hadronness");
+    fPhness->SetXTitle("Hadronness");
+    fGhness->SetYTitle("Acceptance");
+    fPhness->SetYTitle("Acceptance");
+    fPhness->SetLineColor(kRed);
+    fGhness->SetDirectory(NULL);
+    fPhness->SetDirectory(NULL);
+    
+    fIntGhness = new TH1D("AccGammas",  "Integral Acceptance vs. Hadronness (Gammas)", nbins, 0, 1);
+    fIntPhness = new TH1D("AccHadrons", "Integral Acceptance vs. Hadronness (Hadrons)", nbins, 0, 1);
+    fIntGhness->SetXTitle("Hadronness");
+    fIntPhness->SetXTitle("Hadronness");
+    fIntGhness->SetYTitle("Acceptance");
+    fIntPhness->SetYTitle("Acceptance");
+    fIntGhness->SetMaximum(1.1);
+    fIntPhness->SetMaximum(1.1);
+    fIntGhness->SetDirectory(NULL);
+    fIntPhness->SetDirectory(NULL);
+    fIntPhness->SetLineColor(kRed);
+    fIntGhness->SetBit(TH1::kNoStats);
+    fIntPhness->SetBit(TH1::kNoStats);
+
+    fQfac = new TGraph;
+    fQfac->SetTitle(" Naive Quality factor ");
+    fQfac->SetMarkerStyle(kFullDotSmall);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms.
+//
+MHHadronness::~MHHadronness()
+{
+    delete fGhness;
+    delete fIntGhness;
+    delete fPhness;
+    delete fIntPhness;
+    delete fQfac;
+    delete fGraph;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup Filling of the histograms. It needs:
+//  MMcEvt and MHadronness
+//
+Bool_t MHHadronness::SetupFill(const MParList *plist)
+{
+    if (!fMatrix)
+    {
+        fMcEvt = (MMcEvt*)plist->FindObject(AddSerialNumber("MMcEvt"));
+        if (!fMcEvt)
+        {
+            *fLog << err << dbginf << AddSerialNumber("MMcEvt");
+            *fLog << " not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fHadronness = (MHadronness*)plist->FindObject("MHadronness");
+
+    fGhness->Reset();
+    fPhness->Reset();
+
+    /*
+     MBinning* bins = (MBinning*)plist->FindObject("BinningHadronness");
+     if (!bins)
+     {
+     *fLog << err << dbginf << "BinningHadronness [MBinning] not found... aborting." << endl;
+     return kFALSE;
+     }
+
+     SetBinning(&fHist, binsalpha, binsenergy, binstheta);
+
+     fHist.Sumw2();
+     */
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the Hadronness from a MHadronness container into the corresponding
+// histogram dependant on the particle id.
+//
+// Every particle Id different than kGAMMA is considered a hadron.
+//
+// If you call Fill with a pointer (eg. from MFillH) this container is
+// used as a hadronness (Warning: No type check is done!) otherwise
+// the default is used ("MHadronness")
+//
+// Sometimes a distance is calculated as NaN (not a number). Such events
+// are skipped at the moment.
+//
+Bool_t MHHadronness::Fill(const MParContainer *par, const Stat_t w)
+{
+    // Preliminary Workaround: FIXME!
+    if (!par && !fHadronness)
+    {
+        *fLog << err << "MHHadronness::Fill: No MHadronness container specified!" << endl;
+        return kFALSE;
+    }
+
+    const MHadronness &had = par ? *(MHadronness*)par : *fHadronness;
+
+    const Double_t h = had.GetHadronness();
+
+    if (TMath::IsNaN(h))
+        return kCONTINUE;
+
+    const Int_t particleid = fMatrix ? (Int_t)(*fMatrix)[fMap] : fMcEvt->GetPartId();
+
+    if (particleid==MMcEvt::kGAMMA)
+        fGhness->Fill(h, w);
+    else
+        fPhness->Fill(h, w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the quality factor at gamma acceptance 0.5.
+//
+// If the histogram containes only two bins we return the
+// naive quality: ag/sqrt(ah)
+// with ag the acceptance of gammas and ah the acceptance of hadrons.
+//
+// You can use this (nbins=2) in case of some kind of filter cuts giving
+// only a result: gamma yes/no (means discrete values of hadronness 0.25
+// or 0.75)
+//
+// FIXME: In the later case weights cannot be used!
+//
+Float_t MHHadronness::GetQ05() const
+{
+    if (fGhness->GetNbinsX()==2)
+    {
+        // acceptance of all gamma-like gammas  (h<0.5)
+        const Double_t ig = fGhness->GetBinContent(1);
+
+        // acceptance of all gamma-like hadrons (h<0.5)
+        const Double_t ip = fPhness->GetBinContent(1);
+
+        if (ip==0)
+            return 0; // FIXME!
+
+        // naive quality factor
+        const Double_t q = ig / sqrt(ip);
+
+        *fLog << all << ip << "/" << ig << ": " << q << endl;
+
+        return q;
+    }
+
+    const Int_t n = fQfac->GetN();
+
+    Double_t val1x=0;
+    Double_t val2x=1;
+
+    Double_t val1y=0;
+    Double_t val2y=0;
+
+    for (Int_t i=1; i<=n; i++)
+    {
+        Double_t x, y;
+
+        fQfac->GetPoint(i, x, y);
+
+        if (x<0.5 && x>val1x)
+        {
+            val1x = x;
+            val1y = y;
+        }
+
+        if (x>0.5 && x<val2x)
+        {
+            val2x = x;
+            val2y = y;
+        }
+    }
+
+    //*fLog << dbg << val1x << "/" << val1y << "  " << val2x << "/" << val2y << endl;
+
+    return val2x-val1x == 0 ? 0 : val1y - (val2y-val1y)/(val2x-val1x) * (val1x-0.5);
+}
+
+// --------------------------------------------------------------------------
+//
+// Finalize the histograms:
+//  - integrate the hadroness histograms --> acceptance
+//  - fill the Minimum Distance histogram (formular see class description)
+//  - fill the Quality histogram (formular see class description)
+//
+void MHHadronness::CalcGraph(Double_t sumg, Double_t sump)
+{
+    Int_t n = fGhness->GetNbinsX();
+
+    fGraph->Set(n);
+    fQfac->Set(n);
+
+    // Calculate acceptances
+    Float_t max=0;
+
+    for (Int_t i=1; i<=n; i++)
+    {
+        const Stat_t ip = fPhness->Integral(1, i)/sump;
+        const Stat_t ig = fGhness->Integral(1, i)/sumg;
+
+        fIntPhness->SetBinContent(i, ip);
+        fIntGhness->SetBinContent(i, ig);
+
+        fGraph->SetPoint(i, ip, ig);
+
+        if (ip<=0)
+            continue;
+
+        const Double_t val = ig/sqrt(ip);
+        fQfac->SetPoint(i, ig, val);
+
+        if (val>max)
+            max = val;
+    }
+
+    fQfac->SetMaximum(max*1.05);
+}
+
+Bool_t MHHadronness::Finalize()
+{
+    const Stat_t sumg = fGhness->Integral();
+    const Stat_t sump = fPhness->Integral();
+
+    *fLog << inf << "Sum Hadronness: gammas=" << sumg << " hadrons=" << sump << endl;
+
+    // Normalize photon distribution
+    if (sumg>0)
+        fGhness->Scale(1./sumg);
+    else
+        *fLog << warn << "Cannot calculate hadronness for 'gammas'." << endl;
+
+    // Normalize hadron distribution
+    if (sump>0)
+        fPhness->Scale(1./sump);
+    else
+        *fLog << warn << "Cannot calculate hadronness for 'hadrons'." << endl;
+
+    CalcGraph(1, 1);
+
+    return kTRUE;
+}
+
+void MHHadronness::Paint(Option_t *opt)
+{
+    Stat_t sumg = fGhness->Integral();
+    Stat_t sump = fPhness->Integral();
+
+    // Normalize photon distribution
+    if (sumg<=0)
+        sumg=1;
+
+    // Normalize hadron distribution
+    if (sump<=0)
+        sump=1;
+
+    CalcGraph(sumg, sump);
+}
+
+// --------------------------------------------------------------------------
+//
+// Search the corresponding points for the given hadron acceptance (acchad)
+// and interpolate the tow points (linear)
+//
+Double_t MHHadronness::GetGammaAcceptance(Double_t acchad) const
+{
+    const Int_t n = fGraph->GetN();
+    const Double_t *x = fGraph->GetX();
+    const Double_t *y = fGraph->GetY();
+
+    Int_t i = 0;
+    while (i<n && x[i]<acchad)
+        i++;
+
+    if (i==0 || i==n)
+        return 0;
+
+    if (i==n-1)
+        i--;
+
+    const Double_t x1 = x[i-1];
+    const Double_t y1 = y[i-1];
+
+    const Double_t x2 = x[i];
+    const Double_t y2 = y[i];
+
+    return (y2-y1)/(x2-x1) * (acchad-x2) + y2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search the corresponding points for the given gamma acceptance (accgam)
+// and interpolate the tow points (linear)
+//
+Double_t MHHadronness::GetHadronAcceptance(Double_t accgam) const
+{
+    const Int_t n = fGraph->GetN();
+    const Double_t *x = fGraph->GetX();
+    const Double_t *y = fGraph->GetY();
+
+    Int_t i = 0;
+    while (i<n && y[i]<accgam)
+        i++;
+
+    if (i==0 || i==n)
+        return 0;
+
+    if (i==n-1)
+        i--;
+
+    const Double_t x1 = y[i-1];
+    const Double_t y1 = x[i-1];
+
+    const Double_t x2 = y[i];
+    const Double_t y2 = x[i];
+
+    return (y2-y1)/(x2-x1) * (accgam-x2) + y2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search the hadronness corresponding to a given hadron acceptance.
+//
+Double_t MHHadronness::GetHadronness(Double_t acchad) const
+{
+    for (int i=1; i<fIntPhness->GetNbinsX()+1; i++)
+        if (fIntPhness->GetBinContent(i)>acchad)
+            return fIntPhness->GetBinLowEdge(i);
+
+    return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the corresponding Gammas Acceptance for a hadron acceptance of
+// 10%, 20%, 30%, 40% and 50%. Also the minimum distance to the optimum
+// acceptance and the corresponding acceptances and hadroness value is
+// printed, together with the maximum Q-factor.
+//
+void MHHadronness::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << underline << GetDescriptor() << endl;
+
+    if (fGraph->GetN()==0)
+    {
+        *fLog << " <No Entries>" << endl;
+        return;
+    }
+
+    *fLog << "Used " << fGhness->GetEntries() << " Gammas and " << fPhness->GetEntries() << " Hadrons." << endl;
+    *fLog << "acc(hadron) acc(gamma) acc(g)/acc(h)  h" << endl <<endl;
+
+    *fLog << "    0.005    " << Form("%6.3f", GetGammaAcceptance(0.005)) << "      " << Form("%6.3f", GetGammaAcceptance(0.005)/0.005) << "      " << GetHadronness(0.005) << endl;
+    *fLog << "    0.02     " << Form("%6.3f", GetGammaAcceptance(0.02))  << "      " << Form("%6.3f", GetGammaAcceptance(0.02)/0.02)   << "      " << GetHadronness(0.02) << endl;
+    *fLog << "    0.05     " << Form("%6.3f", GetGammaAcceptance(0.05))  << "      " << Form("%6.3f", GetGammaAcceptance(0.05)/0.05)   << "      " << GetHadronness(0.05) << endl;
+    *fLog << "    0.1      " << Form("%6.3f", GetGammaAcceptance(0.1 ))  << "      " << Form("%6.3f", GetGammaAcceptance(0.1)/0.1)     << "      " << GetHadronness(0.1) << endl;
+    *fLog << "    0.2      " << Form("%6.3f", GetGammaAcceptance(0.2 ))  << "      " << Form("%6.3f", GetGammaAcceptance(0.2)/0.2)     << "      " << GetHadronness(0.2) << endl;
+    *fLog << "    0.3      " << Form("%6.3f", GetGammaAcceptance(0.3 ))  << "      " << Form("%6.3f", GetGammaAcceptance(0.3)/0.3)     << "      " << GetHadronness(0.3) << endl;
+    *fLog << Form("%6.3f", GetHadronAcceptance(0.1)) << "        0.1  " << endl;
+    *fLog << Form("%6.3f", GetHadronAcceptance(0.2)) << "        0.2  " << endl;
+    *fLog << Form("%6.3f", GetHadronAcceptance(0.3)) << "        0.3  " << endl;
+    *fLog << Form("%6.3f", GetHadronAcceptance(0.4)) << "        0.4  " << endl;
+    *fLog << Form("%6.3f", GetHadronAcceptance(0.5)) << "        0.5  " << endl;
+    *fLog << Form("%6.3f", GetHadronAcceptance(0.6)) << "        0.6  " << endl;
+    *fLog << Form("%6.3f", GetHadronAcceptance(0.7)) << "        0.7  " << endl;
+    *fLog << Form("%6.3f", GetHadronAcceptance(0.8)) << "        0.8  " << endl;
+    *fLog << endl;
+
+    *fLog << "Q-Factor @ Acc Gammas=0.5: Q(0.5)=" << Form("%.1f", GetQ05()) << endl;
+    *fLog << "  Acc Hadrons = " << Form("%5.1f", GetHadronAcceptance(0.5)*100) << "%" << endl;
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw all histograms. (For the Meaning see class description)
+//
+void MHHadronness::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas("Hadronness", fTitle);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2, 2);
+
+    TH1 *h;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    //gStyle->SetOptStat(10);
+    MH::DrawSame(*fGhness, *fPhness, "Hadronness"); // Displ both stat boxes
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fIntGhness->Draw();
+    fIntPhness->Draw("same");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fQfac->Draw("A*");
+    gPad->Modified();
+    gPad->Update();
+    if ((h=fQfac->GetHistogram()))
+    {
+        h->GetXaxis()->SetRangeUser(0, 1);
+        h->SetXTitle("Acceptance Gammas");
+        h->SetYTitle("Quality");
+        fQfac->Draw("P");
+        gPad->Modified();
+        gPad->Update();
+    }
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    fGraph->Draw("AC");
+    gPad->Modified();
+    gPad->Update();
+    if ((h=fGraph->GetHistogram()))
+    {
+        h->GetXaxis()->SetRangeUser(0, 1);
+        h->SetXTitle("Acceptance Hadrons");
+        h->SetYTitle("Acceptance Gammas");
+        fGraph->SetMaximum(1);
+        fGraph->Draw("P");
+        gPad->Modified();
+        gPad->Update();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of
+// MMcEvt. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MHHadronness::Fill
+// will take the values from the matrix instead of the containers.
+//
+void MHHadronness::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    TString str = AddSerialNumber("MMcEvt");
+    str += ".fPartId";
+
+    fMap = fMatrix->AddColumn(str);
+}
+
+void MHHadronness::StopMapping()
+{
+    fMatrix = NULL; 
+}
Index: /tags/Mars-V0.9/mhist/MHHadronness.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHHadronness.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHHadronness.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MHHadronness
+#define MARS_MHHadronness
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TGraph;
+class MParList;
+class MMcEvt;
+class MHadronness;
+class MHMatrix;
+
+class MHHadronness : public MH
+{
+private:
+    const MMcEvt *fMcEvt;           //!
+    const MHadronness *fHadronness; //!
+    MHMatrix *fMatrix;        //!
+    Int_t fMap;                     //!
+
+    TH1D* fPhness;    //-> Hadrons Hadronness
+    TH1D* fGhness;    //-> Gammas  Hadronness
+    TH1D* fIntPhness; //-> Hadrons Acceptance
+    TH1D* fIntGhness; //-> Gammas  Acceptance
+
+    TGraph *fQfac;    //-> Quality factor
+    TGraph *fGraph;   //-> gamma acceptance vs. hadron acceptance
+
+    void Paint(Option_t *opt="");
+    void CalcGraph(Double_t sumg, Double_t sump);
+
+public:
+    MHHadronness(Int_t nbins=100, const char *name=NULL, const char *title=NULL);
+    ~MHHadronness();
+
+    Double_t GetGammaAcceptance(Double_t acchad) const;
+    Double_t GetHadronAcceptance(Double_t accgam) const;
+    Double_t GetHadronness(Double_t acchad) const;
+
+    TH1D *Getghness() const  { return fGhness; }
+    TH1D *Getphness() const  { return fPhness; }
+    TH1D *Getighness() const { return fIntGhness; }
+    TH1D *Getiphness() const { return fIntPhness; }
+    //TH2D *GetHist() const    { return fHist; }
+
+    Float_t GetQ05() const;
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping();
+
+    void Print(Option_t *option="") const;
+
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHHadronness, 1) // Gamma/Hadron Separation Quality Histograms
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHOnSubtraction.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHOnSubtraction.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHOnSubtraction.cc	(revision 9772)
@@ -0,0 +1,1767 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner 9/2002 <mailto:rw@rwagner.de>
+!   Author(s): Robert Wagner 3/2003 <mailto:rw@rwagner.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHOnSubtraction                                                         //
+//                                                                          //
+//                                                                          //
+//  extracts the gamma signal from a pure ON-signal given in an             //
+//  ALPHA-Energy-Theta histogram. The class will take this histogram from   //
+//  the parameter list and will provide result histograms in the            //
+//  parameter list.                                                         //
+//                                                                          //
+//  This class still is work in progress.                                   //
+//                                                                          //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+// This part of MARS is code still evolving. Please do not change the code 
+// without prior feedback by the author.
+
+#include "MHOnSubtraction.h"
+
+#include <TPaveText.h>
+#include <TPaveLabel.h>
+#include <TF1.h>
+#include <TLegend.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+#include <TGraph.h>
+
+#include "MBinning.h"
+#include "MParList.h"
+#include "MHArray.h"
+#include "MH3.h"
+
+#include "MHAlphaEnergyTheta.h"
+#include "MHAlphaEnergyTime.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHOnSubtraction);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor.
+//
+MHOnSubtraction::MHOnSubtraction(const char *name, const char *title) : fMaxSignif(0),	fMaxRedChiSq(0), fSlope(20.0)
+{ 
+  fName  = name  ? name  : "MHOnSubtraction";
+  fTitle = title ? title : "Extracts Gamma signal from pure ON data";
+  fHistogramType = "Theta";
+  fChiSquareHisto=0;
+  fSignificanceHisto=0;
+  fSummedAlphaPlots=0;
+  fThetaBin=0;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Destructor.
+//
+MHOnSubtraction::~MHOnSubtraction()
+{ 
+  if (fChiSquareHisto) delete fChiSquareHisto;
+  if (fSignificanceHisto) delete fSignificanceHisto;
+  if (fSummedAlphaPlots) delete fSummedAlphaPlots;
+}
+
+// -----------------------------------------------------------------------
+//
+// Calculate Significance according to Li and Ma, ApJ 272 (1983) 317, eq
+// (17). n_{On}, n_{Off} and the ratio of On-times for On and Off 
+// measurements have to be provided.
+//
+// This function underestimates the true significance for it does not take
+// into account errors on the event numbers. A more accurate variation wil
+// be provided soon
+//
+Double_t MHOnSubtraction::CalcSignificance(Double_t nOn, Double_t nOff, Double_t theta)
+{ 
+  if (nOn<=0)
+    *fLog << warn << "Got " << nOn << " total events, " << flush;
+  if (nOff<=0)
+    *fLog << warn << "Got " << nOff << " background events, " << flush;
+  if (nOn<=0 || nOff<=0.0) {
+    *fLog << warn << "returning significance of 0.0" << endl;
+    return 0.0;
+  }
+  return sqrt(2*(nOn*log((1+theta)*nOn/(theta*(nOn+nOff)))
+		 +nOff*log((1+theta)*(nOff/(nOn+nOff)))));
+}
+
+// -----------------------------------------------------------------------
+//
+// This function takes a first look at a given ALPHA distribution
+// and determines if a fit is applicable.
+//
+// Fits a given TH1 containing an ALPHA distribution with a combined
+// gaussian plus polynomial of third grade and returns the fitted 
+// function. By signalRegionFactor the width of the region in which
+// signal extraction is to be performed can be specified in units of
+// sigma of the gaussian which is fitted to the distribution (default: 
+// 3.5). Accordingly, FitHistogram returns the range in which it suggests 
+// signal extraction (lowerBin < ALPHA < upperBin). An estimated 
+// significance of the signal is also provided. draw specifies whether
+// FitHistogram should draw the distribution.
+//
+Bool_t MHOnSubtraction::FitHistogram(TH1 &alphaHisto, Double_t &sigLiMa,
+			       Double_t &lowerBin, Double_t &upperBin,
+			       Float_t signalRegionFactor, const Bool_t draw,
+			       TString funcName)
+{
+  if (alphaHisto.GetEntries() == 0) {
+    *fLog << warn << "Histogram contains no entries. Returning. " << endl;
+    lowerBin=0;
+    upperBin=0;
+    sigLiMa=0;    
+    if (draw) {
+      TPaveLabel* lab = new TPaveLabel(0.1,0.2,0.9,0.8,"(no events)");
+      lab->SetFillStyle(0);
+      lab->SetBorderSize(0);
+      lab->Draw();  
+    }
+    return kFALSE;
+  }
+  
+  //cosmetics
+  alphaHisto.GetXaxis()->SetTitle("ALPHA");
+  alphaHisto.GetYaxis()->SetTitle("events");
+
+  Double_t outerEvents = 0.0;
+  Double_t innerEvents = 0.0;
+  Int_t outerBins = 0;
+  Int_t innerBins = 0;
+  Int_t outerBinsZero = 0;
+  Int_t innerBinsZero = 0;
+
+  for (Int_t alphaBin = 1; alphaBin < alphaHisto.GetNbinsX(); alphaBin++) {
+    if ((alphaHisto.GetBinLowEdge(alphaBin) >= -35.)&& //inner Region
+  	(alphaHisto.GetBinLowEdge(alphaBin+1) <= 35.0)) {
+      innerEvents+=alphaHisto.GetBinContent(alphaBin);
+      innerBins++;
+      if (alphaHisto.GetBinContent(alphaBin)==0.0)
+  	innerBinsZero++;     
+    } else {
+      if ((alphaHisto.GetBinLowEdge(alphaBin) >= -89.5)&& //outer Region
+	  (alphaHisto.GetBinLowEdge(alphaBin+1) <=89.5)) {
+	outerEvents+=alphaHisto.GetBinContent(alphaBin);
+	outerBins++;
+	if (alphaHisto.GetBinContent(alphaBin)==0.0)
+	  outerBinsZero++;     
+      }
+    }
+  }
+
+   *fLog << dbg << "Plot contains " << 
+     outerEvents << " outer ev (" << outerEvents/outerBins << "/bin), " <<
+     innerEvents << " inner ev (" << innerEvents/innerBins << "/bin) " << endl;
+
+  if ((outerBinsZero!=0) || (innerBinsZero != 0))
+    *fLog << warn << "There are ";
+  if (outerBinsZero != 0)
+    *fLog << dbg << outerBinsZero << " empty outer bins ";
+  if (innerBinsZero != 0)
+    *fLog << dbg <<innerBinsZero << " empty inner bins ";
+  if ((outerBinsZero!=0) || (innerBinsZero != 0))
+    *fLog << endl;
+
+  if (outerEvents == 0.0) {
+     *fLog << warn << "No events in OFF region. Assuming background = 0" 
+	   << endl;
+     TF1 *po = new TF1("pol0"+funcName,"pol0(0)",-89.5,89.5);
+     po->SetLineWidth(2);
+     po->SetLineColor(2);
+     po->SetParNames("c");
+     po->SetParameter(0,0.0);
+     alphaHisto.GetListOfFunctions()->Add(po);
+     alphaHisto.SetLineColor(97);
+     if (draw) {
+       alphaHisto.DrawCopy(); //rwagner
+       po->Draw("SAME");
+     }
+     sigLiMa = 0;
+     lowerBin = 1;
+     upperBin = alphaHisto.GetNbinsX()-1;
+     signalRegionFactor = 0;
+    
+     return kFALSE; //No gaus fit applied
+  }
+
+  if (outerEvents/outerBins < 2.5) {
+    *fLog << warn << "Only " << /*setprecision(2) <<*/ outerEvents/outerBins 
+	  << " events/bin in OFF region: "
+	  << "Assuming this as background." << endl;
+   
+     TF1 *po = new TF1("pol0"+funcName,"pol0(0)",-89.5,89.5);
+     po->SetLineWidth(2);
+     po->SetLineColor(94);
+     po->SetParNames("c");
+     po->SetParameter(0,outerEvents/outerBins);
+     alphaHisto.GetListOfFunctions()->Add(po);    
+     if (draw) {
+       alphaHisto.DrawCopy(); //rwagner
+       po->Draw("SAME");
+     }
+    
+     Int_t centerBin = alphaHisto.GetXaxis()->FindBin((Double_t)0.0);
+     Int_t maxBin    = centerBin > alphaHisto.GetNbinsX() - centerBin ? 
+       alphaHisto.GetNbinsX()- centerBin : centerBin;
+     
+     Int_t lowerSignalEdge = centerBin;
+     for (Int_t i=3; i < maxBin; i++) {
+       if ((Double_t)alphaHisto.GetBinContent(centerBin-i) 
+	   < outerEvents/outerBins) {
+	 lowerSignalEdge = centerBin-i+1;
+	 break;
+       }
+     }
+     if (centerBin<lowerSignalEdge) lowerSignalEdge=centerBin;
+
+     Int_t upperSignalEdge = centerBin;
+     for (Int_t i=3; i < maxBin; i++) {
+       if ((Double_t)alphaHisto.GetBinContent(centerBin+i) 
+	   <= outerEvents/outerBins) {
+	 upperSignalEdge=centerBin+i-1;
+	 break;
+       } 
+     }
+     if (centerBin>upperSignalEdge) upperSignalEdge=centerBin;
+
+     Double_t nOnInt = 0;
+     for (Int_t i=1; i < alphaHisto.GetNbinsX(); i++)
+       nOnInt += alphaHisto.GetBinContent(i) - outerEvents/outerBins;
+     
+     Double_t nOffInt = (upperSignalEdge - lowerSignalEdge + 1) 
+       * (outerEvents/outerBins);
+     
+     sigLiMa = CalcSignificance(nOnInt, nOffInt, 1);
+
+     if (sigLiMa < 3) 
+       alphaHisto.SetLineColor(2);   
+
+   
+     *fLog << inf << "Estimated significance is " << sigLiMa 
+	   << " sigma " << endl;   
+     *fLog << inf << "Signal region is " 
+	   << lowerBin << " < ALPHA < " << upperBin 
+	   << " (Most likely you wanna ignore this)" << endl;
+
+     return kFALSE; //No gaus fit applied    
+  }
+  
+  //fit combined gaus+pol3 to data
+  TF1 *gp = new TF1("gauspol3"+funcName,"gaus(0)+pol3(3)",-89.5,89.5);
+  gp->SetLineWidth(2);
+  gp->SetLineColor(2);
+  gp->SetParNames("Excess","A","sigma","a","b","c","d");
+  gp->SetParLimits(0, 200,2000); 
+  gp->SetParLimits(1, -4.,4.); 
+  gp->SetParLimits(2, 2.,20.);
+  // gp->SetParameter(6,  0.0000); // include for slope(0)=0 constrain
+  TString gpDrawOptions = draw ? "RIQ" : "RIQ0";
+  gpDrawOptions = "RIQ0"; // rwagner
+  alphaHisto.Fit("gauspol3"+funcName,gpDrawOptions);
+  alphaHisto.DrawCopy(); //rwagner
+  alphaHisto.SetDirectory(NULL); //rwagner
+  
+  Double_t gausMean  = gp->GetParameter(1);
+  Double_t gausSigma = gp->GetParameter(2);
+
+//   TF1 *p3 = new TF1("p3"+funcName,"pol3(0)",-signalRegionFactor*gausSigma+gausMean,
+// 		    signalRegionFactor*gausSigma+gausMean);
+  TF1 *p3 = new TF1("p3"+funcName,"pol3(0)",-100,
+		    100);
+  p3->SetParameters(gp->GetParameter(3),gp->GetParameter(4),
+		    gp->GetParameter(5),gp->GetParameter(6));
+  // p3->SetLineStyle(2);
+  p3->SetLineColor(4);
+  p3->SetLineWidth(1);
+  if (draw) p3->Draw("SAME");   
+   
+  TF1 *ga = new TF1("ga"+funcName,"gaus(0)",-40,40);
+  ga->SetParameters(gp->GetParameter(0),gp->GetParameter(1),gp->GetParameter(2));
+  ga->SetLineColor(93);
+  ga->SetLineWidth(2);
+  //  if (draw) ga->Draw("SAME");
+
+  // identify the signal region: signalRegionFactor*gausSigma
+  // this allows us to
+  // (1) determine n_{ON}, n_{OFF}
+  Double_t scalingFactor = 
+    (alphaHisto.GetXaxis()->GetBinLowEdge(alphaHisto.GetNbinsX()+1)
+     - alphaHisto.GetXaxis()->GetBinLowEdge(1)) / alphaHisto.GetNbinsX();
+  
+  Double_t nOnInt  = (gp->Integral(-signalRegionFactor*gausSigma+gausMean, 
+				 signalRegionFactor*gausSigma+gausMean) / scalingFactor);
+  Double_t nOffInt = (p3->Integral(-signalRegionFactor*gausSigma+gausMean, 
+				 signalRegionFactor*gausSigma+gausMean) / scalingFactor);
+
+  // (2) determine the signal region from fit in degrees
+  // we do it a bit more complicated: assuming that the binning in all 
+  // histograms is the same, we want to be sure that summing up is always
+  // done over the same bins.
+
+  lowerBin = alphaHisto.GetXaxis()->FindBin(-signalRegionFactor*gausSigma+gausMean);
+  upperBin = alphaHisto.GetXaxis()->FindBin( signalRegionFactor*gausSigma+gausMean);
+
+  lowerBin = alphaHisto.GetBinLowEdge((Int_t)lowerBin);
+  upperBin = alphaHisto.GetBinLowEdge((Int_t)upperBin)+alphaHisto.GetBinWidth((Int_t)upperBin);
+  
+  sigLiMa = CalcSignificance(nOnInt, nOffInt, 1);
+//   if (sigLiMa < 3)
+//     alphaHisto.SetLineColor(2);   
+
+
+  *fLog << inf << "Fit estimates significance to be " 
+	<< sigLiMa << " sigma " << endl; 
+
+  *fLog << inf << "Fit yields signal region to be " 
+	<< lowerBin << " < ALPHA < " << upperBin
+	<< " (Chisquare/dof=" << gp->GetChisquare()/gp->GetNDF() 
+	<< ", prob="  <<  gp->GetProb() << ")" << endl;
+
+  return kTRUE; //returning gaus fit
+}
+
+
+
+
+
+// -----------------------------------------------------------------------
+//
+// Does the actual extraction of the gamma signal. For performance 
+// reasons, fits already done by MHOnSubtraction::FitHistogram are used 
+// and not redone.
+// From it, a polynomial function for the background is evaluated and the
+// gamma signal is extracted in the region given by lowerBin < ALPHA < 
+// upperBin.
+// Significance of the signal is also provided. draw specifies whether
+// FitHistogram should draw the distribution.
+//
+Bool_t MHOnSubtraction::ExtractSignal(TH1 &alphaHisto, Double_t &sigLiMa,
+   Double_t &lowerBin, Double_t &upperBin,
+   Double_t &gammaSignal, Double_t &errorGammaSignal,
+   Double_t &off, Double_t &errorOff,
+   Float_t signalRegionFactor, const Bool_t draw, TString funcName,
+   TPad *drawPad, Int_t drawBase)
+{
+  TF1 *gausPol = alphaHisto.GetFunction("gauspol3"+funcName);
+  TF1 *pol = alphaHisto.GetFunction("pol0"+funcName);
+  
+  if (!gausPol && !pol) {
+    *fLog << err << "Fatal: ALPHA histogram has no gauspol or pol "  
+	  << " fit attached to it." << endl;
+    TPaveLabel* lab = new TPaveLabel(0.1,0.2,0.9,0.8,"(no fit)");
+    lab->SetFillStyle(3000);
+    lab->SetBorderSize(0);
+    lab->DrawClone();  
+    lab->SetBit(kCanDelete);
+    return kFALSE;
+  } 
+
+  TF1* po;
+  po = NULL;
+
+  if (gausPol) {
+    Double_t gausMean  = gausPol->GetParameter(1);
+    Double_t gausSigma = gausPol->GetParameter(2);
+    po = new TF1("po"+funcName,"pol3(0)",
+		  -signalRegionFactor*gausSigma+gausMean,
+		  signalRegionFactor*gausSigma+gausMean);
+    po->SetParameters(gausPol->GetParameter(3),gausPol->GetParameter(4),
+		      gausPol->GetParameter(5),gausPol->GetParameter(6));
+
+    TF1 *ga = new TF1("ga"+funcName,"gaus(0)",-40,40);
+    ga->SetParameters(gausPol->GetParameter(0),gausPol->GetParameter(1),
+		      gausPol->GetParameter(2));
+    
+    if (draw) {
+      alphaHisto.Draw();
+      gausPol->Draw("SAME"); //Maybe not even necessary?
+      
+      po->SetLineColor(4);
+      po->SetLineWidth(2);
+      po->Draw("SAME");   
+      
+      ga->SetLineColor(93);
+      ga->SetLineWidth(2);    
+      ga->Draw("SAME");   
+      
+      char legendTitle[80];
+      sprintf(legendTitle, "Signal region: %2.1f < #alpha < %2.1f", 
+	      lowerBin, upperBin);
+      
+      TLegend *legend = new TLegend(0.13, 0.52, 0.47, 0.72, legendTitle);
+      
+      legend->SetBorderSize(0);
+      legend->SetFillColor(10);
+      legend->SetFillStyle(0);
+      legend->AddEntry(gausPol, "combined N_{on}","l");
+      legend->AddEntry(po,"polynomial N_{bg} Signal region","l");
+      legend->AddEntry(ga, "putative gaussian N_{S}","l");
+      legend->Draw();
+    }
+  } // gausPol
+
+
+  if (pol) {
+    po = pol;
+    
+    if (draw) {
+      alphaHisto.Draw();
+      
+      po->SetLineColor(6);
+      po->SetLineWidth(2);
+      po->Draw("SAME");   
+            
+      char legendTitle[80];
+      sprintf(legendTitle, "Signal region: %2.1f < #alpha < %2.1f", 
+	      lowerBin, upperBin);
+      
+      TLegend *legend = new TLegend(0.13, 0.52, 0.47, 0.72, legendTitle);
+      
+      legend->SetBorderSize(0);
+      legend->SetFillColor(10);
+      legend->SetFillStyle(0);
+      legend->AddEntry(po,"polynomial N_{bg} Signal region","l");
+      legend->Draw();
+    }
+  } // pol
+    
+  Double_t nOn = 0;
+  Double_t eNOn = 0;
+
+  Int_t binNumberLow = alphaHisto.GetXaxis()->FindBin(lowerBin);
+  Int_t binNumberHigh = alphaHisto.GetXaxis()->FindBin(upperBin);
+  
+  for (Int_t bin=binNumberLow; bin<binNumberHigh+1; bin++) {
+    nOn += alphaHisto.GetBinContent(bin);
+    eNOn += alphaHisto.GetBinError(bin) * alphaHisto.GetBinError(bin);
+  } //for bin
+  eNOn = sqrt(eNOn);
+     
+  // Evaluate background
+  
+  Double_t nOff = 0;
+  Double_t eNOff = 0;
+  for (Int_t bin=binNumberLow; bin<binNumberHigh+1; bin++) {
+    Double_t x = .5*(alphaHisto.GetBinLowEdge(bin)+alphaHisto.GetBinLowEdge(bin+1));
+    Double_t offEvts = po->Eval(x);
+    //cout << bin << ": " << offEvts << endl;
+    nOff += offEvts;
+  } //for bin
+  eNOff = sqrt(fabs(nOff));
+  
+  if (nOn==0)   // there should not be a negative number of signal events
+    nOff=0;
+  
+  if (nOff<0) { // there should not be a negative number of off events
+    nOff=0;
+    eNOff=0;
+  }
+    
+  *fLog << inf << "nEvts = " << nOn << "+-" << eNOn << ", ";
+
+  off = nOff;              errorOff = eNOff;
+  gammaSignal = nOn-nOff;  errorGammaSignal = sqrt(eNOn*eNOn + eNOff*eNOff); 
+
+  *fLog << inf << "nBack = " << nOff << "+-" << eNOff << ", ";
+  *fLog << inf << "nSig = " << gammaSignal << "+-" << errorGammaSignal << endl;
+
+  sigLiMa = CalcSignificance(nOn, nOff, 1);  
+  //  Double_t sigFit=(ga->GetParameter(1))/(ga->GetParError(1)); //Mean / sigMean
+  
+  *fLog << inf << "Significance: "<<sigLiMa<<" sigma "<<endl;
+
+  if (draw) { 
+    TPaveText *pt = new TPaveText(0.11,.74,.57,.88,"NDC ");
+    char tx[60];
+    sprintf(tx, "Excess: %2.2f #pm %2.2f", nOn-nOff, sqrt(eNOn*eNOn + eNOff*eNOff));
+    pt->AddText(tx);
+    sprintf(tx, "Off:    %2.2f #pm %2.2f", nOff, eNOff);
+    pt->AddText(tx);
+    sprintf(tx, "Significance: %2.2f   #sigma", sigLiMa);
+    pt->AddText(tx);
+    pt->SetFillStyle(0);
+    pt->SetBorderSize(0);
+    pt->SetTextAlign(12);
+    pt->Draw("");
+  }  
+  if (draw||drawPad) {
+
+    // Plot significance vs alpha_cut
+    
+    Int_t centerBin = alphaHisto.GetXaxis()->FindBin((Double_t)0.0);
+    Int_t maxBin    = centerBin > alphaHisto.GetNbinsX()- centerBin ? 
+      alphaHisto.GetNbinsX()- centerBin : centerBin;
+         
+    const Int_t totalBins = centerBin;
+    Float_t alpha[totalBins];
+    Float_t signi[totalBins];
+    Float_t maxSigni = 0;
+    
+    for (Int_t i=0; i < maxBin; i++) {
+      Double_t nOn = 0;  Double_t eNOn = 0;
+      Double_t nOff = 0; Double_t eNOff = 0;
+      for (Int_t bin=centerBin-i; bin<centerBin+i+1; bin++) {
+	nOn += alphaHisto.GetBinContent(bin);
+	eNOn += alphaHisto.GetBinError(bin) * alphaHisto.GetBinError(bin);
+	Double_t x = .5*(alphaHisto.GetBinLowEdge(bin)+alphaHisto.GetBinLowEdge(bin+1));
+	Double_t offEvts = po->Eval(x);
+	nOff += offEvts;
+      } //for bin
+      eNOn = sqrt(eNOn);
+      eNOff = sqrt(nOff);  
+      alpha[i] = 
+	(alphaHisto.GetXaxis()->GetBinLowEdge(centerBin+i+1)-
+	 alphaHisto.GetXaxis()->GetBinLowEdge(centerBin-i))/2;
+      signi[i] = CalcSignificance(nOn, nOff, 1);  
+      maxSigni = maxSigni > signi[i] ? maxSigni : signi[i];
+    }
+
+    if (!drawPad) {
+      TCanvas *c3 = new TCanvas("c3"+funcName, "Significance vs ALPHA cut", 800,600);
+      c3->cd();
+    }
+
+    if (drawPad) 
+      drawPad->cd(drawBase-1);
+    
+    TGraph* gr = new TGraph(totalBins-2,alpha,signi);
+    TString drawOpt = "L";
+    
+    if (draw || (drawPad && fSigniPlotIndex == 0))
+      drawOpt += "A";
+    
+    gr->Draw(drawOpt);
+    if (drawPad && fSigniPlotIndex == 0) {
+      gr->GetXaxis()->SetTitle("|#alpha_{max}|");
+      gr->GetYaxis()->SetTitle("Significance");
+    }
+    gr->SetMarkerStyle(2);
+    gr->SetMarkerSize(1);
+    gr->SetMarkerColor(4+fSigniPlotIndex);
+    gr->SetLineColor(4+fSigniPlotIndex);
+    gr->SetLineWidth(1);
+    gr->SetTitle("Significance vs ALPHA integration range");
+    gr->Draw("L");
+
+    fSigniPlotIndex++;      
+    
+  } //draw
+
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// Extraction of Gamma signal is performed on a MHAlphaEnergyTheta or 
+// MHAlphaEnergyTime object expected in the ParList.
+//
+Bool_t MHOnSubtraction::Calc(MParList *parlist, const Bool_t Draw)
+{
+  //Find source histograms
+  fHistogramType = "Theta";
+  MHAlphaEnergyTheta* mhisttheta = (MHAlphaEnergyTheta*)parlist->FindObject("MHAlphaEnergyTheta"); 
+  if (mhisttheta) return Calc((TH3D*)mhisttheta->GetHist(), parlist, Draw);
+
+  fHistogramType = "Time";
+  MHAlphaEnergyTime* mhisttime = (MHAlphaEnergyTime*)parlist->FindObject("MHAlphaEnergyTime");  
+  if (mhisttime) return Calc((TH3D*)mhisttime->GetHist(), parlist, Draw);
+
+  *fLog << err << "No MHAlphaEnergyTheta type object found in the parameter list. Aborting." << endl;
+  return kFALSE; 
+}
+
+// -----------------------------------------------------------------------
+//
+// Extraction of Gamma signal is performed on a TH3D histogram in
+// ALPHA, Energy and Theta.
+//
+Bool_t MHOnSubtraction::CalcAET(TH3D *aetHisto, MParList *parlist, const Bool_t Draw)
+{
+  // Analyze aetHisto
+  // -------------------------------------
+  Int_t alphaBins =  aetHisto->GetNbinsX();  // # of alpha bins 
+  Int_t energyBins = aetHisto->GetNbinsY();  
+  Int_t thetaBins =  aetHisto->GetNbinsZ();  
+  
+  // We output an array of histograms to the parlist.
+  // Create a template for such a histogram, needed by MHArray
+  // -------------------------------------
+  MBinning *binsfft = new MBinning("BinningMH3X");
+  binsfft->SetEdgesLog(energyBins,aetHisto->GetYaxis()->GetBinLowEdge(1),
+		aetHisto->GetYaxis()->GetBinLowEdge(energyBins+1));
+  parlist->AddToList(binsfft);  
+  MH3 *energyHistogram = new MH3(1); // The template histogram in energy
+                                     // for a given theta value
+  energyHistogram->SetName("MHOnSubtractionEnergyHistogramTemplate");
+  parlist->AddToList(energyHistogram);
+
+  fThetaHistoArray = new MHArray("MHOnSubtractionEnergyHistogramTemplate", kTRUE, 
+				 "MHOnSubtractionGammaSignalArray", 
+				 "Array of histograms in energy bins");
+  fThetaHistoArray->SetupFill(parlist);
+  parlist->AddToList(fThetaHistoArray);
+  
+  // Canvases---direct debug output for the time being
+  // -------------------------------------
+  TCanvas *c3 = new TCanvas("c3", "Plots by MHOnSubtraction::ExtractSignal", 800,600);
+  cout << thetaBins << " x " << energyBins << endl;
+  c3->Divide(thetaBins,energyBins);
+
+  TCanvas *c4a = new TCanvas("c4a", "Energy distributions for different ZA", 800,600);
+  
+  TH1D* histalphaon[energyBins*thetaBins]; // ALPHA histograms
+
+  fChiSquareHisto = new TH1D("fChiSquareHisto", "#chi^{2}/d.o.f. of fits", 50, 0, 5);
+  fSignificanceHisto = new TH1D("fSignificanceHisto", "Significances", 41, -0.5, 40.5);
+  fSummedAlphaPlots = new TH1D("fSummedAlphaPlots", "Cumulative Alpha", 
+			       alphaBins,aetHisto->GetXaxis()->GetBinLowEdge(1),
+			       aetHisto->GetXaxis()->GetBinLowEdge(alphaBins+1));
+  
+  // -------------------------------------
+
+  fThetaLegend = new TLegend(0.83, 0.07, 0.98, 0.42, "Energy Distributions");  
+  fThetaLegend->SetBorderSize(1);
+  
+  Double_t overallSigLiMa = 0;
+
+  for (Int_t thetaBin = 1; thetaBin < thetaBins+1; thetaBin++) {
+    
+    char hname[80];  
+    sprintf(hname, "Energy distribution for %s bin %d", fHistogramType.Data(), 
+	    thetaBin);
+    *fLog << all << "Calculating " << hname << endl;
+
+    Double_t minLowerBin = -10; // minimum integration range
+    Double_t maxUpperBin =  10; // minimum integration range
+    Double_t maxAlpha =  70; // maximum integration range
+
+    Double_t sumSigLiMa = 0;
+    
+    // This loop just fixes the integration range
+    // And alerts when no significant excess is found.
+
+    for (Int_t energyBin = 1; energyBin < energyBins+1; energyBin++) {
+
+      sprintf(hname, "histalphaon%d", (thetaBin-1)*(energyBins)+energyBin);
+      histalphaon[(thetaBin-1)*(energyBins)+energyBin] = 
+	new TH1D(hname, "ALPHA histogram",
+		 alphaBins,aetHisto->GetXaxis()->GetBinLowEdge(1),
+		 aetHisto->GetXaxis()->GetBinLowEdge(alphaBins+1));
+      histalphaon[(thetaBin-1)*(energyBins)+energyBin]->Sumw2();    
+      histalphaon[(thetaBin-1)*(energyBins)+energyBin]->SetTitle(hname);
+     
+      sprintf(hname,"ALPHA distribution for E bin %d, theta bin %d",
+	      energyBin, thetaBin);
+      *fLog << inf << hname << endl;
+
+      // now we fill one histogram for one particular set
+      // of Energy and Theta...
+      
+      if (aetHisto->InheritsFrom("TH3D")||aetHisto->InheritsFrom("TH2D")) {
+	aetHisto->GetYaxis()->SetRange(energyBin,energyBin); // E
+	if (aetHisto->InheritsFrom("TH3D"))
+	  aetHisto->GetZaxis()->SetRange(thetaBin,thetaBin); // theta
+	histalphaon[(thetaBin-1)*(energyBins)+energyBin] = (TH1D*)aetHisto->Project3D("xe");
+      } else {
+	histalphaon[(thetaBin-1)*(energyBins)+energyBin] = (TH1D*)aetHisto;
+      }
+
+      *fLog << inf << "This histogram has " 
+	    << histalphaon[(thetaBin-1)*(energyBins)+energyBin]->GetEntries()
+	    << " entries" << endl;
+
+      sprintf(hname, "histalphaon%d", (thetaBin-1)*(energyBins)+energyBin);
+      histalphaon[(thetaBin-1)*(energyBins)+energyBin]->SetName(hname);
+      
+      // Test: Find signal region and significance in histogram
+      Double_t lowerBin, upperBin, sSigLiMa;
+      FitHistogram(*histalphaon[(thetaBin-1)*(energyBins)+energyBin],
+		   sSigLiMa, lowerBin, upperBin, (Float_t)3.5, kFALSE);
+
+      Double_t redChiSq = histalphaon[(thetaBin-1)*(energyBins)+energyBin]->GetFunction("gauspol3")->GetChisquare()/histalphaon[(thetaBin-1)*(energyBins)+energyBin]->GetFunction("gauspol3")->GetNDF();
+
+      fChiSquareHisto->Fill(redChiSq);
+      fMaxRedChiSq = redChiSq > fMaxRedChiSq ? redChiSq : fMaxRedChiSq;
+
+      // histalphaon[(thetaBin-1)*(energyBins)+energyBin]->GetFunction("gauspol3")->GetProb() <<endl;
+
+      fSummedAlphaPlots->Add(histalphaon[(thetaBin-1)*(energyBins)+energyBin], 1);
+      
+      if (sSigLiMa < 3)
+	*fLog << inf << "No significant excess for this bin (sigma="<< sSigLiMa <<")!"<<endl;
+      sumSigLiMa+=sSigLiMa;
+   
+      // Evaluate integration range
+
+      lowerBin = (lowerBin < -maxAlpha) ? -maxAlpha : lowerBin;
+      minLowerBin = (lowerBin < minLowerBin) ? lowerBin : minLowerBin;
+
+      upperBin = (upperBin > maxAlpha) ? maxAlpha : upperBin;
+      maxUpperBin = (upperBin > maxUpperBin) ? upperBin : maxUpperBin;
+
+    } //energyBin
+    
+    *fLog << inf << "Integration range for this " << fHistogramType 
+	  << " value will be " << minLowerBin << " < ALPHA < "
+	  << maxUpperBin << endl;
+    
+    *fLog << inf << "Summed estd. significance for this " << fHistogramType 
+	  << " value is " << sumSigLiMa << endl;
+
+    // Create Histogram in Energy for this Theta value
+    cout << "STARTIGN REAL CALC1 "<< endl;
+    fThetaHistoArray->AddHistogram();
+    cout << "STARTIGN REAL CALC1a "<< endl;
+    fThetaHistoArray->SetIndex(thetaBin-1);
+    
+    MH3 &mThetaHisto = *(MH3*)(fThetaHistoArray->GetH());
+    mThetaHisto.Print();
+   
+    TH1D &thetaHisto = (TH1D&)(mThetaHisto.GetHist());
+    sprintf(hname,"Energy distribution for theta bin %d", thetaBin);
+    thetaHisto.SetTitle(hname);
+    thetaHisto.SetEntries(0);
+      
+    // we have a rough idea of what is going on in the ALPHA plot...
+    // So now we can indeed extract the signal.
+         
+//     cout << "STARTIGN REAL CALC "<< endl;
+
+    sumSigLiMa = 0;
+    for (Int_t energyBin = 1; energyBin < energyBins+1; energyBin++) {
+
+      sprintf(hname,"ALPHA distribution for E bin %d, theta bin %d",
+	      energyBin, thetaBin);
+      *fLog << inf << hname << endl;
+  
+      Double_t gammaSignal, errorGammaSignal, off, errorOff, sigLiMa;
+
+      c3->cd((thetaBin-1)*(energyBins)+energyBin);
+  
+      ExtractSignal(*histalphaon[(thetaBin-1)*(energyBins)+energyBin],
+		    sigLiMa, minLowerBin, maxUpperBin, 
+		    gammaSignal, errorGammaSignal, 
+		    off, errorOff, (Float_t)3, kTRUE);
+      
+      fSignificanceHisto->Fill(sigLiMa);
+      fMaxSignif = sigLiMa > fMaxSignif ? sigLiMa : fMaxSignif;
+
+      thetaHisto.SetBinContent(energyBin, gammaSignal*TMath::Exp(7-energyBin));
+      thetaHisto.SetBinError(energyBin, errorGammaSignal);
+      thetaHisto.SetEntries(thetaHisto.GetEntries()+gammaSignal);
+     
+      sumSigLiMa += sigLiMa;
+      
+    }//energyBin
+
+    *fLog << inf << "Summed significance for this " << fHistogramType 
+	  << " value is " << sumSigLiMa << endl;
+
+    //fit exponential function to data
+    TF1* e = new TF1("expF","expo",0,5);
+    e->SetLineWidth(3);
+    e->SetLineColor(thetaBin);
+    // e->SetParLimits(1, -0.5,3); //limits on slope
+    
+     if (fSlope!=20.0) {
+       e->SetParameter(1, fSlope);
+       *fLog << inf << "Fixing slope to " << e->GetParameter(1) << endl;
+     }
+
+    TString eDrawOptions = Draw ? "RIQ" : "RIQ0";
+    cout << "doing the fit" << endl;
+    thetaHisto.Fit("expF");
+    
+    Double_t expoSlope = e->GetParameter(1);
+    
+    *fLog << inf << "Determined slope for energy distribution is " 
+	  << expoSlope << endl;
+
+    Double_t integralEvts =
+      e->Integral(aetHisto->GetYaxis()->GetBinLowEdge(1), 
+		  aetHisto->GetYaxis()->GetBinLowEdge(energyBins+1));
+    
+    *fLog << inf << "Integral in E range [" <<
+      aetHisto->GetYaxis()->GetBinLowEdge(1) << ";" <<
+      aetHisto->GetYaxis()->GetBinLowEdge(energyBins+1) << "] is " << 
+      integralEvts << endl;
+      
+    // Plot Energy histogram
+  
+    c4a->cd(0);
+    thetaHisto.SetLineColor(thetaBin);
+    if (thetaBin==1) {      
+      thetaHisto.Draw();
+    } else {
+      thetaHisto.Draw("SAME");
+    }
+
+    sprintf(hname,"Theta bin %d",thetaBin);
+    fThetaLegend->AddEntry(&thetaHisto, hname, "l");
+
+    overallSigLiMa += sumSigLiMa;
+
+  } //thetaBin
+
+  fThetaLegend->Draw();
+
+  Double_t sigLiMa, lowerBin, upperBin;    
+  FitHistogram(*fSummedAlphaPlots, sigLiMa, lowerBin, upperBin);
+  fSummedAlphaPlots->SetTitle("Cumulative ALPHA distribution");
+
+  *fLog << inf << "Summed overall significance is " << overallSigLiMa << endl;
+
+  *fLog << inf << "Setting range for Significance histo " << fMaxSignif << endl;
+  // fSignificanceHisto->GetXaxis()->SetRange(0,fMaxSignif+1);
+
+  // *fLog << inf << "Setting range for chisq histo " << fMaxRedChiSq << endl;
+  // fChiSquareHisto->GetXaxis()->SetRange(0,fMaxRedChiSq+5);
+  
+  return kTRUE;
+}
+
+
+
+
+
+
+
+
+// -----------------------------------------------------------------------
+//
+// Extraction of Gamma signal is performed on a TH3D histogram in
+// ALPHA, Energy and Theta. Output to parameter list: TH2 histograms
+// in energy and Theta.
+//
+Bool_t MHOnSubtraction::Calc(TH3 *aetHisto, MParList *parlist, const Bool_t Draw)
+{
+  // Analyze aetHisto
+  // -------------------------------------
+  Int_t energyBins = aetHisto->GetNbinsY();  
+  Int_t thetaBins =  aetHisto->GetNbinsZ();  
+
+  *fLog << "Total events:     " << aetHisto->GetEntries() << endl;
+  *fLog << "Total energy bins: " << energyBins << endl;
+  *fLog << "Total theta bins:  " << thetaBins << endl;
+  
+  // We output results in an array of histograms to the parameter list.
+  // Create a template for such a histogram, needed by MH3
+  // -------------------------------------
+  MBinning *binsmh3x = new MBinning("BinningMH3X");
+  // dummy binning, real one follows some lines down
+  binsmh3x->SetEdgesLog(energyBins,aetHisto->GetYaxis()->GetBinLowEdge(1),
+			aetHisto->GetYaxis()->GetBinLowEdge(energyBins+1));
+  parlist->AddToList(binsmh3x);  
+
+  MBinning *binsmh3y = new MBinning("BinningMH3Y");
+  // dummy binning, real one follows some lines down
+  binsmh3y->SetEdges(thetaBins,aetHisto->GetZaxis()->GetBinLowEdge(1),
+		     aetHisto->GetZaxis()->GetBinLowEdge(thetaBins+1));
+  parlist->AddToList(binsmh3y);  
+  
+  MH3 *signalHisto = new MH3(2); // Signal(E,t)
+  signalHisto->SetupFill(parlist);
+  parlist->AddToList(signalHisto);
+  signalHisto->SetName("MHOnSubtractionSignal");
+  signalHisto->SetTitle("Gamma Events");
+
+  MH3 *offHisto = new MH3(2); // Off(E,t)
+  offHisto->SetupFill(parlist);
+  parlist->AddToList(offHisto);
+  offHisto->SetName("MHOnSubtractionOff");
+  offHisto->SetTitle("Background Events");
+
+  MH3 *signifHisto = new MH3(2); // Significance(E,t)
+  signifHisto->SetupFill(parlist);
+  parlist->AddToList(signifHisto);
+  signifHisto->SetName("MHOnSubtractionSignif");
+  signifHisto->SetTitle("Significance");
+
+//   if (!fChiSquareHisto) 
+//     fChiSquareHisto = new TH1D("fChiSquareHisto", "#chi^{2}/d.o.f. of fits", 50, 0, 5);
+//   if (!fSignificanceHisto) 
+//     fSignificanceHisto = new TH1D("fSignificanceHisto", "Significances", 40.5, -0.5, 41);
+//   if (!fSummedAlphaPlots)
+//     fSummedAlphaPlots = new TH1D("fSummedAlphaPlots", "Cumulative Alpha", 
+// 				 alphaBins,aetHisto->GetXaxis()->GetBinLowEdge(1),
+// 				 aetHisto->GetXaxis()->GetBinLowEdge(alphaBins+1));
+  
+  TCanvas *c4 = new TCanvas("c4", "MHOnSubtraction Detailed Result Plots", 800,600);
+  c4->Divide(energyBins+3,thetaBins,0,0,0);
+  
+  TH2D& signalTH2DHist = (TH2D&)signalHisto->GetHist();
+  TH2D& offTH2DHist =    (TH2D&)offHisto->GetHist();
+  TH2D& signifTH2DHist = (TH2D&)signifHisto->GetHist();
+  
+  signalTH2DHist.Reset();
+  signalTH2DHist.SetTitle("Gamma Signal");
+  signalTH2DHist.SetXTitle("E [GeV]");
+  signalTH2DHist.SetYTitle("theta [deg]");
+  signalHisto->SetBinning(&signalTH2DHist, aetHisto->GetYaxis(), aetHisto->GetZaxis());
+  signalTH2DHist.Sumw2();
+  
+  offTH2DHist.Reset();
+  offTH2DHist.SetTitle("Off Signal");
+  offTH2DHist.SetXTitle("E [GeV]");
+  offTH2DHist.SetYTitle("theta [deg]");
+  offHisto->SetBinning(&offTH2DHist, aetHisto->GetYaxis(), aetHisto->GetZaxis());
+  offTH2DHist.Sumw2();  
+
+  signifTH2DHist.Reset();
+  signifTH2DHist.SetTitle("Significance");
+  signifTH2DHist.SetXTitle("E [GeV]");
+  signifTH2DHist.SetYTitle("theta [deg]");
+  signifHisto->SetBinning(&signifTH2DHist, aetHisto->GetYaxis(), aetHisto->GetZaxis());
+  signifTH2DHist.Sumw2();
+ 
+  for (Int_t thetaBin = 1; thetaBin < thetaBins+1; thetaBin++) {  
+
+    *fLog << dbg << "--------------------------------------" << endl;
+    *fLog << dbg << "Processing ALPHA plots for theta bin " << thetaBin << endl;           
+    *fLog << dbg << "--------------------------------------" << endl;
+    aetHisto->GetZaxis()->SetRange(thetaBin, thetaBin);
+    TH2F* aeHisto = (TH2F*)aetHisto->Project3D("yxe");
+    aeHisto->SetDirectory(NULL);
+    char hname[80];
+    sprintf(hname, "%2.1f < #theta < %2.1f", 
+	    aetHisto->GetZaxis()->GetBinLowEdge(thetaBin),
+	    aetHisto->GetZaxis()->GetBinLowEdge(thetaBin+1));
+    *fLog << inf << "There are " << aeHisto->GetEntries() 
+ 	  << " entries in " << hname << endl;
+    aeHisto->SetTitle(hname);
+    sprintf(hname, "MHOnSubtractionThetaBin%d", thetaBin);
+    aeHisto->SetName(hname);
+
+    c4->cd((energyBins+3)*(thetaBin-1)+1);
+    aeHisto->SetMarkerColor(3);
+    aeHisto->DrawCopy();
+
+    c4->Update();
+
+    // We hand over a nonstandard parameter list, which
+    // contails lower-dimensional result histograms 
+    // signalHisto, offHisto and signifHisto
+
+//     cout << fLog->GetDebugLevel() << endl;
+    fLog->SetDebugLevel(1);
+
+    MParList *parlistth2 = new MParList();
+    //    parlistth2->SetNullOutput();
+    parlistth2->AddToList(binsmh3x);  
+
+    MH3* signalHisto2 = new MH3(1); // Signal(E)
+    signalHisto2->SetupFill(parlistth2);
+    parlistth2->AddToList(signalHisto2);
+    signalHisto2->SetName("MHOnSubtractionSignal");
+    signalHisto2->SetTitle("Gamma Events");
+
+    MH3* offHisto2 = new MH3(1); // Off(E)
+    offHisto2->SetupFill(parlistth2);
+    parlistth2->AddToList(offHisto2);
+    offHisto2->SetName("MHOnSubtractionOff");
+    offHisto2->SetTitle("Background Events");
+
+    MH3* signifHisto2 = new MH3(1); // Significance(E)
+    signifHisto2->SetupFill(parlistth2);
+    parlistth2->AddToList(signifHisto2);
+    signifHisto2->SetName("MHOnSubtractionSignif");
+    signifHisto2->SetTitle("Significance");
+
+    fLog->SetDebugLevel(-1);
+
+    TH1D& signalTH1DHist = (TH1D&)signalHisto2->GetHist();
+    TH1D& offTH1DHist =    (TH1D&)offHisto2->GetHist();
+    TH1D& signifTH1DHist = (TH1D&)signifHisto2->GetHist();
+
+    signalTH1DHist.Sumw2();
+    offTH1DHist.Sumw2();
+    signifTH1DHist.Sumw2();
+
+    TH2Calc(aeHisto, parlistth2, kFALSE, c4,   
+	    (energyBins+3)*(thetaBin-1)+4);
+
+
+    for (Int_t energyBin = 1; energyBin < energyBins+1; energyBin++) {  
+    
+   //    cout << "filling " << thetaBin << " " << energyBin << ": " 
+// 		      << signalTH1DHist.GetBinContent(energyBin) << "+-" 
+// 	   << signalTH1DHist.GetBinError(energyBin)  <<  " " 
+// 		      << offTH1DHist.GetBinContent(energyBin) << "+-" 
+// 		      << offTH1DHist.GetBinError(energyBin) << endl;
+        
+      if (signalTH1DHist.GetBinContent(energyBin)>=0.0) {
+	signalTH2DHist.SetBinContent(energyBin, thetaBin,
+				     signalTH1DHist.GetBinContent(energyBin));
+	signalTH2DHist.SetBinError(energyBin, thetaBin,
+				   signalTH1DHist.GetBinError(energyBin));
+      }
+      
+      if (offTH1DHist.GetBinContent(energyBin)>=0.0) {
+	offTH2DHist.SetBinContent(energyBin, thetaBin, 
+				  offTH1DHist.GetBinContent(energyBin));
+	offTH2DHist.SetBinError(energyBin, thetaBin,
+				offTH1DHist.GetBinError(energyBin));
+      }
+      
+      signifTH2DHist.SetBinContent(energyBin, thetaBin,
+ 				   signifTH1DHist.GetBinContent(energyBin));
+      signifTH2DHist.SetBinError(energyBin, thetaBin,
+ 				 signifTH1DHist.GetBinError(energyBin));           
+    } //energyBin
+
+  
+    c4->cd((energyBins+3)*(thetaBin-1)+2);
+    sprintf(hname,"c4_%d",(energyBins+3)*(thetaBin-1)+2);     
+    TPad* tp = (TPad*)(gROOT->FindObject(hname));
+    tp->SetLogx();     
+    signalTH1DHist.SetLineColor(2);
+    signalTH1DHist.DrawCopy();     
+    offTH1DHist.SetLineColor(4);
+    offTH1DHist.DrawCopy("SAME");          
+    c4->Update();
+           
+    signalTH2DHist.SetEntries(signalTH2DHist.GetEntries()+signalTH1DHist.GetEntries());
+    offTH2DHist.SetEntries(offTH2DHist.GetEntries()+offTH1DHist.GetEntries());
+    signifTH2DHist.SetEntries(signifTH2DHist.GetEntries()+signifTH1DHist.GetEntries());
+    
+    delete signifHisto2;
+    delete offHisto2;
+    delete signalHisto2;
+    delete parlistth2;
+  
+  }
+
+
+  c4->Update();
+
+  return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+/*
+
+// -----------------------------------------------------------------------
+//
+// Extraction of Gamma signal is performed on a TH3D histogram in
+// ALPHA, Energy and Theta. Output to parameter list: TH2 histograms
+// in energy and Theta.
+//
+Bool_t MHOnSubtraction::CalcLightCurve(TH3 *aetHisto, MParList *parlist, const Bool_t draw)
+{
+  // Analyze aetHisto
+  // -------------------------------------
+  Int_t alphaBins = aetHisto->GetNbinsX(); 
+  Int_t energyBins = aetHisto->GetNbinsY();  
+  Int_t timeBins =  aetHisto->GetNbinsZ();  
+
+  *fLog << "Total events:      " << aetHisto->GetEntries() << endl;
+  *fLog << "Total energy bins: " << energyBins << endl;
+  *fLog << "Total time bins:   " << timeBins << endl;
+
+  // We output results in an array of histograms to the parameter list.
+  // Create a template for such a histogram, needed by MH3
+  // -------------------------------------
+  MBinning *binsmh3x = new MBinning("BinningMH3X");
+  // dummy binning, real one follows some lines down
+  binsmh3x->SetEdges(timeBins,aetHisto->GetZaxis()->GetBinLowEdge(1),
+		     aetHisto->GetZaxis()->GetBinLowEdge(timeBins+1));
+  parlist->AddToList(binsmh3x); 
+  
+  MH3 *signalHisto = new MH3(1); // Signal(t)
+  signalHisto->SetupFill(parlist);
+  parlist->AddToList(signalHisto);
+  signalHisto->SetName("MHOnSubtractionSignal");
+  signalHisto->SetTitle("Gamma Events");
+
+  MH3 *offHisto = new MH3(1); // Off(t)
+  offHisto->SetupFill(parlist);
+  parlist->AddToList(offHisto);
+  offHisto->SetName("MHOnSubtractionOff");
+  offHisto->SetTitle("Background Events");
+
+  MH3 *signifHisto = new MH3(1); // Significance(t)
+  signifHisto->SetupFill(parlist);
+  parlist->AddToList(signifHisto);
+  signifHisto->SetName("MHOnSubtractionSignif");
+  signifHisto->SetTitle("Significance");
+
+  TH1D& signalTH1DHist = (TH1D&)signalHisto->GetHist();
+  TH1D& offTH1DHist =    (TH1D&)offHisto->GetHist();
+  TH1D& signifTH1DHist = (TH1D&)signifHisto->GetHist();
+  
+  signalTH1DHist.Reset();
+  signalTH1DHist.SetTitle("Gamma Signal");
+  signalTH1DHist.SetXTitle("Time [MJD]");
+  signalTH1DHist.SetYTitle("Events");
+  signalHisto->SetBinning(&signalTH1DHist, aetHisto->GetZaxis());
+  signalTH1DHist.Sumw2();
+  
+  offTH1DHist.Reset();
+  offTH1DHist.SetTitle("Background Signal");
+  offTH1DHist.SetXTitle("Time [MJD]");
+  offTH1DHist.SetYTitle("Events");
+  offHisto->SetBinning(&offTH1DHist,  aetHisto->GetZaxis());
+  offTH1DHist.Sumw2();  
+
+  signifTH1DHist.Reset();
+  signifTH1DHist.SetTitle("Significance");
+  signifTH1DHist.SetXTitle("Time [MJD]");
+  signifTH1DHist.SetYTitle("Significance #sigma");
+  signifHisto->SetBinning(&signifTH1DHist, aetHisto->GetZaxis());
+  signifTH1DHist.Sumw2();
+ 
+  //The following histogram is an additional histogram needed for
+  //the light curve
+
+  TCanvas *c4 = new TCanvas("c4", "MHOnSubtraction Detailed Result Plots", 800,600);
+  c4->Divide(8,7,0,0,0);
+
+ 
+
+  // The following loop fixes a common integration region for each
+  // energy bin and alerts when no significant excess is found.
+  
+  Double_t minLowerBin = -10; // minimum integration range
+  Double_t maxUpperBin =  10; // minimum integration range
+  Double_t maxAlpha =  70; // maximum integration range
+  Double_t sumSigLiMa = 0;
+
+  TH1F* alphaHisto[timeBins];
+
+  for (Int_t timeBin = 1; timeBin < timeBins+1; timeBin++) {  
+
+    *fLog << dbg << "--------------------------------------" << endl;
+    *fLog << dbg << "Processing ALPHA plots for time bin " << timeBin << endl;           
+    *fLog << dbg << "--------------------------------------" << endl;
+   
+    aetHisto->GetZaxis()->SetRange(timeBin, timeBin);
+
+    char hname[80];
+    sprintf(hname, "MHOnSubtractionTimeBin%d", timeBin);    
+    alphaHisto[timeBin-1] =
+      new TH1F(hname, "ALPHA histogram",
+	       alphaBins,aetHisto->GetXaxis()->GetBinLowEdge(1),
+	       aetHisto->GetXaxis()->GetBinLowEdge(alphaBins+1));
+    alphaHisto[timeBin-1]->SetDirectory(NULL);
+    alphaHisto[timeBin-1]->Sumw2();
+    alphaHisto[timeBin-1] = (TH1F*)aetHisto->Project3D("xe");
+    alphaHisto[timeBin-1]->SetName(hname);
+    alphaHisto[timeBin-1]->SetDirectory(NULL);
+
+    sprintf(hname, "%6.0f < t < %6.0f", 
+	    aetHisto->GetZaxis()->GetBinLowEdge(timeBin),
+	    aetHisto->GetZaxis()->GetBinLowEdge(timeBin+1));
+    *fLog << inf << "There are " << alphaHisto[timeBin-1]->GetEntries() 
+ 	  << " entries in " << hname << endl;
+    alphaHisto[timeBin-1]->SetTitle(hname);
+      
+    // Find signal region and significance in histogram
+    Double_t lowerBin, upperBin, sSigLiMa;
+    char funcName[20];
+    sprintf(funcName, "%2d", timeBin);
+
+    Bool_t drawFit = kTRUE;
+
+    c4->cd(timeBin);
+//     alphaHisto[timeBin-1]->SetMarkerColor(3);
+    alphaHisto[timeBin-1]->DrawCopy();
+
+    c4->Update();
+
+    fSigniPlotColor = 0;
+ ;
+    Bool_t fit = FitHistogram(*alphaHisto[timeBin-1], sSigLiMa, 
+			      lowerBin, upperBin, (Float_t)3.0, drawFit, 
+			      funcName);
+
+    if (fit) { 
+      if (sSigLiMa < 3)
+	*fLog << warn << "No significant excess for this bin (sigma="<< sSigLiMa <<")!"<<endl;
+      sumSigLiMa+=sSigLiMa;
+   
+      // Evaluate integration range
+      lowerBin = (lowerBin < -maxAlpha) ? -maxAlpha : lowerBin;
+      minLowerBin = (lowerBin < minLowerBin) ? lowerBin : minLowerBin;    
+      upperBin = (upperBin > maxAlpha) ? maxAlpha : upperBin;
+      maxUpperBin = (upperBin > maxUpperBin) ? upperBin : maxUpperBin;
+    }
+
+
+    
+
+
+
+  } //timeBin
+  
+  *fLog << inf << "=> Integration range will be " << minLowerBin << " < ALPHA < "
+	<< maxUpperBin << "," << endl;    
+  *fLog << inf << "   Summed estimated significance is " << sumSigLiMa << endl;
+      
+  // we have an idea of what is going on in the ALPHA plot...
+  // So now we can indeed extract the signal.
+         
+  sumSigLiMa = 0;
+  for (Int_t timeBin = 1; timeBin < timeBins+1; timeBin++) {
+    *fLog << inf << "Processing ALPHA distribution for time bin " << timeBin << endl;
+    if (alphaHisto[timeBin-1]->GetEntries() == 0) {
+       *fLog << warn << "No attempt to extract a signal from 0 events." << endl;       
+       if (draw) {
+	 TPaveLabel* lab = new TPaveLabel(0.2,0.4,0.8,0.6,"-(nothing to extract)-");
+	 lab->SetBorderSize(0);
+	 lab->Draw();  
+       }
+    } else {
+      char funcName[20];
+      sprintf(funcName, "%2d", timeBin);
+      
+      Double_t gammaSignal, errorGammaSignal, off, errorOff, sigLiMa;    
+
+      Bool_t drawFit = kFALSE;     
+
+      ExtractSignal(*alphaHisto[timeBin-1],
+		    sigLiMa, minLowerBin, maxUpperBin, 
+		    gammaSignal, errorGammaSignal, off, errorOff, (Float_t)3, drawFit,
+		    funcName, NULL, 1);
+
+      sumSigLiMa += sigLiMa;      
+
+      fMaxSignif = sigLiMa > fMaxSignif ? sigLiMa : fMaxSignif;
+
+      // Fill Signal 
+      TH1D &h = (TH1D&)(signalHisto->GetHist());
+      h.SetBinContent(timeBin, gammaSignal);
+      h.SetBinError(timeBin, errorGammaSignal);
+      h.SetEntries(h.GetEntries()+gammaSignal);
+      
+      // Fill Off Events
+      TH1D &ho = (TH1D&)(offHisto->GetHist());
+      ho.SetBinContent(timeBin, off);
+      ho.SetBinError(timeBin, errorOff);
+      ho.SetEntries(ho.GetEntries()+off);
+      
+      // Fill Significance
+      TH1D &hg = (TH1D&)(signifHisto->GetHist());
+      hg.SetBinContent(timeBin, sigLiMa);
+      hg.SetEntries(hg.GetEntries()+sigLiMa);           
+    }
+    
+  }//timeBin
+
+  *fLog << inf << "Summed significance is " << sumSigLiMa << endl;
+
+
+  if (draw) {
+    Double_t sigLiMa, lowerBin, upperBin;    
+    FitHistogram(*fSummedAlphaPlots, sigLiMa, lowerBin, upperBin);
+    fSummedAlphaPlots->SetTitle("Cumulative ALPHA distribution");
+
+    *fLog << inf << "Setting range for Significance histo " << fMaxSignif << endl;
+    // fSignificanceHisto->GetXaxis()->SetRange(0,fMaxSignif+1);
+    
+    // *fLog << inf << "Setting range for chisq histo " << fMaxRedChiSq << endl;
+    // fChiSquareHisto->GetXaxis()->SetRange(0,fMaxRedChiSq+5);
+    
+    fChiSquareHisto->DrawClone();
+    fSignificanceHisto->DrawClone();
+    fSummedAlphaPlots->DrawClone();
+  }
+  
+  return kTRUE;
+}
+
+
+
+
+
+*/
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+// -----------------------------------------------------------------------
+//
+// Extraction of Gamma signal is performed on a TH2 histogram in
+// ALPHA and Energy. Output to parameter list is TH1 histogram in
+// energy
+//
+Bool_t MHOnSubtraction::TH2Calc(TH2 *aeHisto, MParList *parlist, const Bool_t draw, TPad *drawPad, Int_t drawBase)
+{
+
+  fSigniPlotColor = 0;
+
+  // Analyze aeHisto
+  // -------------------------------------
+  const Int_t alphaBins =  aeHisto->GetNbinsX();  // # of alpha bins 
+  const Int_t energyBins = aeHisto->GetNbinsY();  
+
+  // Check availability of result histograms
+  // -------------------------------------
+
+  MH3* signalHisto = (MH3*)parlist->FindObject("MHOnSubtractionSignal","MH3");
+  MH3* offHisto =    (MH3*)parlist->FindObject("MHOnSubtractionOff","MH3");
+  MH3* signifHisto = (MH3*)parlist->FindObject("MHOnSubtractionSignif","MH3");
+
+  if (signalHisto && offHisto && signifHisto) {  
+//     *fLog << dbg << "Result histograms are present in parameter list " <<
+//       "and will be used further." << endl;
+  } else {
+
+    *fLog << warn << "Result histograms are not present in parameter " <<
+      "list and thus are going to be created now." << endl;
+
+    MBinning *binsmh3x = new MBinning("BinningMH3X");
+    binsmh3x->SetEdgesLog(energyBins,aeHisto->GetYaxis()->GetBinLowEdge(1),
+		       aeHisto->GetYaxis()->GetBinLowEdge(energyBins+1));
+    parlist->AddToList(binsmh3x);  
+  
+    signalHisto = new MH3(1); // Signal(E)
+    signalHisto->SetName("MHOnSubtractionSignal");
+    signalHisto->SetTitle("Extracted Signal");
+    parlist->AddToList(signalHisto);
+    signalHisto->SetBinning(&((TH1D&)signalHisto->GetHist()), 
+			    aeHisto->GetYaxis());
+
+    offHisto = new MH3(1); // Off(E)
+    offHisto->SetName("MHOnSubtractionOff");
+    offHisto->SetTitle("Off Signal");
+    parlist->AddToList(offHisto);
+    offHisto->SetBinning(&((TH1D&)offHisto->GetHist()), 
+			    aeHisto->GetYaxis());
+    
+    signifHisto = new MH3(1); // Significance(E)
+    signifHisto->SetName("MHOnSubtractionSignif");
+    signifHisto->SetTitle("Significance");
+    parlist->AddToList(signifHisto);
+    signifHisto->SetBinning(&((TH1D&)signifHisto->GetHist()), 
+			    aeHisto->GetYaxis());
+
+  }
+  if (fChiSquareHisto==0x0)
+    fChiSquareHisto = new TH1D("fChiSquareHisto", "#chi^{2}/d.o.f. of fits", 50, 0, 5);
+  if (fSignificanceHisto==0x0)
+    fSignificanceHisto = new TH1D("fSignificanceHisto", "Significances", 41, -0.5, 40.5);
+  if (fSummedAlphaPlots==0x0)
+    fSummedAlphaPlots = new TH1D("fSummedAlphaPlots", "Cumulative Alpha", 
+				 alphaBins,aeHisto->GetXaxis()->GetBinLowEdge(1),
+				 aeHisto->GetXaxis()->GetBinLowEdge(alphaBins+1));  
+         
+  // The following loop fixes a common integration region for each
+  // energy bin and alerts when no significant excess is found.
+  
+  Double_t minLowerBin = -10; // minimum integration range
+  Double_t maxUpperBin =  10; // minimum integration range
+  Double_t maxAlpha =  70; // maximum integration range
+  Double_t sumSigLiMa = 0;
+
+  TH1F* alphaHisto[energyBins];
+
+  fSigniPlotIndex = 0; // cf. ExtractSignal
+ 
+  for (Int_t energyBin = 1; energyBin < energyBins+1; energyBin++) {
+    *fLog << inf << "Preprocessing ALPHA distribution for E bin " << energyBin << endl;
+    char hname[80];
+    sprintf(hname, "MHOnSubtractionAlpha%d", energyBin);    
+    alphaHisto[energyBin-1] =
+      new TH1F(hname, "ALPHA histogram",
+	       alphaBins,aeHisto->GetXaxis()->GetBinLowEdge(1),
+	       aeHisto->GetXaxis()->GetBinLowEdge(alphaBins+1));
+    alphaHisto[energyBin-1]->SetDirectory(NULL);
+    alphaHisto[energyBin-1]->Sumw2();
+    alphaHisto[energyBin-1] = (TH1F*)aeHisto->ProjectionX("xe", energyBin, energyBin);
+    alphaHisto[energyBin-1]->SetName(hname);
+    alphaHisto[energyBin-1]->SetDirectory(NULL);
+
+    sprintf(hname, "%2.1f < E < %2.1f", 
+	    aeHisto->GetYaxis()->GetBinLowEdge(energyBin),
+	    aeHisto->GetYaxis()->GetBinLowEdge(energyBin+1));
+    alphaHisto[energyBin-1]->SetTitle(hname);
+    //    alphaHisto[energyBin-1]->DrawCopy();
+    alphaHisto[energyBin-1]->SetDirectory(NULL);
+      
+    // Find signal region and significance in histogram
+    Double_t lowerBin, upperBin, sSigLiMa;
+    char funcName[20];
+    sprintf(funcName, "%2d", energyBin);
+
+    Bool_t drawFit = kFALSE;
+
+    if (drawPad) {
+      drawPad->cd(drawBase+energyBin-1);
+      drawFit = kTRUE;
+    }
+
+    Bool_t fit = FitHistogram(*alphaHisto[energyBin-1], sSigLiMa, 
+			      lowerBin, upperBin, (Float_t)3.0, drawFit, 
+			      funcName);
+
+    if (fit) { 
+      Double_t redChiSq = alphaHisto[energyBin-1]->GetFunction("gauspol3"+(TString)funcName)->GetChisquare()/
+	alphaHisto[energyBin-1]->GetFunction("gauspol3"+(TString)funcName)->GetNDF();
+      fChiSquareHisto->Fill(redChiSq);
+      fMaxRedChiSq = redChiSq > fMaxRedChiSq ? redChiSq : fMaxRedChiSq;
+      fSummedAlphaPlots->Add(alphaHisto[energyBin-1], 1);
+      if (sSigLiMa < 3)
+	*fLog << warn << "No significant excess for this bin (sigma="<< sSigLiMa <<")!"<<endl;
+      sumSigLiMa+=sSigLiMa;
+   
+      // Evaluate integration range
+      lowerBin = (lowerBin < -maxAlpha) ? -maxAlpha : lowerBin;
+      minLowerBin = (lowerBin < minLowerBin) ? lowerBin : minLowerBin;    
+      upperBin = (upperBin > maxAlpha) ? maxAlpha : upperBin;
+      maxUpperBin = (upperBin > maxUpperBin) ? upperBin : maxUpperBin;
+    } else {
+      fChiSquareHisto->Fill(0);
+    }
+
+//     debugOut->Update();
+
+  } //energyBin
+  
+  *fLog << inf << "=> Integration range for this theta bin will be " << minLowerBin << " < ALPHA < "
+	<< maxUpperBin << "," << endl;    
+  *fLog << inf << "   Summed estimated significance is " << sumSigLiMa << endl;
+      
+  // we have an idea of what is going on in the ALPHA plot...
+  // So now we can indeed extract the signal.
+         
+  sumSigLiMa = 0;
+  for (Int_t energyBin = 1; energyBin < energyBins+1; energyBin++) {
+    *fLog << inf << "Processing ALPHA distribution for E bin " << energyBin << endl;
+    if (alphaHisto[energyBin-1]->GetEntries() == 0) {
+       *fLog << warn << "No attempt to extract a signal from 0 events." << endl;       
+       if (draw) {
+	 TPaveLabel* lab = new TPaveLabel(0.2,0.4,0.8,0.6,"-(nothing to extract)-");
+	 lab->SetBorderSize(0);
+	 lab->Draw();  
+       }
+    } else {
+      char funcName[20];
+      sprintf(funcName, "%2d", energyBin);
+      
+      Double_t gammaSignal, errorGammaSignal, off, errorOff, sigLiMa;    
+
+      Bool_t drawFit = kFALSE;
+      
+//       if (drawPad) {
+// 	cout << "Going to use pad " <<drawBase+energyBin-1 << endl;
+// 	drawPad->cd(drawBase+energyBin-1);
+// 	drawFit = kTRUE;
+//       }
+
+
+      ExtractSignal(*alphaHisto[energyBin-1],
+		    sigLiMa, minLowerBin, maxUpperBin, 
+		    gammaSignal, errorGammaSignal, off, errorOff, (Float_t)3, drawFit,
+		    funcName, drawPad, drawBase);
+
+      sumSigLiMa += sigLiMa;      
+      fSignificanceHisto->Fill(sigLiMa);
+      fMaxSignif = sigLiMa > fMaxSignif ? sigLiMa : fMaxSignif;
+
+      // Fill Signal 
+      TH1D &h = (TH1D&)(signalHisto->GetHist());
+      h.SetBinContent(energyBin, gammaSignal);
+      h.SetBinError(energyBin, errorGammaSignal);
+      h.SetEntries(h.GetEntries()+gammaSignal);
+      
+      // Fill Off Events
+      TH1D &ho = (TH1D&)(offHisto->GetHist());
+      ho.SetBinContent(energyBin, off);
+      ho.SetBinError(energyBin, errorOff);
+      ho.SetEntries(ho.GetEntries()+off);
+      
+      // Fill Significance
+      TH1D &hg = (TH1D&)(signifHisto->GetHist());
+      hg.SetBinContent(energyBin, sigLiMa);
+      hg.SetEntries(hg.GetEntries()+sigLiMa);           
+    }
+    
+  }//energyBin
+
+  *fLog << inf << "Summed significance is " << sumSigLiMa << endl;
+
+
+  if (draw) {
+    Double_t sigLiMa, lowerBin, upperBin;    
+    FitHistogram(*fSummedAlphaPlots, sigLiMa, lowerBin, upperBin);
+    fSummedAlphaPlots->SetTitle("Cumulative ALPHA distribution");
+
+    *fLog << inf << "Setting range for Significance histo " << fMaxSignif << endl;
+    // fSignificanceHisto->GetXaxis()->SetRange(0,fMaxSignif+1);
+    
+    // *fLog << inf << "Setting range for chisq histo " << fMaxRedChiSq << endl;
+    // fChiSquareHisto->GetXaxis()->SetRange(0,fMaxRedChiSq+5);
+    
+    fChiSquareHisto->DrawClone();
+    fSignificanceHisto->DrawClone();
+    fSummedAlphaPlots->DrawClone();
+  }
+  
+  return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+// -----------------------------------------------------------------------
+//
+// Extraction of Gamma signal is performed on a TH1 histogram in ALPHA
+// 
+//
+Bool_t MHOnSubtraction::Calc(TH1 *aHisto, MParList *parlist, 
+			     const Bool_t draw, Float_t signalRegion)
+{ 
+  // Find signal region and estimate significance
+  Double_t lowerBin, upperBin, sigLiMa;
+  FitHistogram(*aHisto,	sigLiMa, lowerBin, upperBin, (Float_t)3.5, kFALSE);
+
+  //if (sigLiMa < 3)
+  //  *fLog << err << "No significant excess (sigma=" << sigLiMa <<")!"<<endl;
+
+  if (signalRegion!=0) {
+    lowerBin = -signalRegion;
+    upperBin =  signalRegion;
+  }
+       
+  Double_t gammaSignal, errorGammaSignal, off, errorOff;
+
+  ExtractSignal(*aHisto, sigLiMa, lowerBin, upperBin, 
+		gammaSignal, errorGammaSignal, off, errorOff, 
+		(Float_t)3.0, draw);
+
+  fSignificance = sigLiMa;
+  
+  *fLog << inf << "Signal is " 
+	<< gammaSignal << "+-" << errorGammaSignal << endl
+	<< inf << "Significance is " << sigLiMa << endl;
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Draw a copy of the histogram
+//
+TObject *MHOnSubtraction::DrawClone(Option_t *opt) const
+{  
+    TCanvas &c = *MakeDefCanvas("OnSubtraction", "Results from OnSubtraction");
+    c.Divide(2,2);
+
+    gROOT->SetSelectedPad(NULL);
+    gStyle->SetOptStat(0);
+
+    c.cd(1);
+    fSummedAlphaPlots->DrawCopy(opt);
+
+    c.cd(2);
+    fSignificanceHisto->DrawCopy(opt);
+
+    c.cd(3);  
+    TString drawopt="";
+    for (fThetaHistoArray->SetIndex(0); 
+ 	 MH3* h=(MH3*)(fThetaHistoArray->GetH()); 
+ 	 fThetaHistoArray->IncIndex())
+      {
+	// Get the current histogram
+	TH1D& hist = (TH1D&)h->GetHist();
+	fSummedAlphaPlots->SetTitle("Energy distributions for different theta bins");
+	hist.Draw(drawopt);
+	drawopt="SAME";
+      }
+    fThetaLegend->Draw();
+    
+    c.cd(4);
+    fChiSquareHisto->DrawCopy(opt);
+    
+    c.Modified();
+    c.Update();
+
+    return &c;
+}
+
+// -------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHOnSubtraction::Draw(Option_t *opt) 
+{ 
+    if (!gPad)
+      MakeDefCanvas("OnSubtraction", "Results from OnSubtraction");
+
+    gPad->Divide(2,3);
+
+// Ok, at some point this will be implemented
+
+    gPad->Modified();
+    gPad->Update();
+}
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHOnSubtraction.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHOnSubtraction.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHOnSubtraction.h	(revision 9772)
@@ -0,0 +1,75 @@
+#ifndef MARS_MHOnSubtraction
+#define MARS_MHOnSubtraction
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TH3D;
+class TPad;
+class TGraph;
+class TLegend;
+class TPaveLabel;
+
+class MHArray;
+
+class MHOnSubtraction : public MH
+{
+private:
+  TString fHistogramType;
+  TH1D*   fChiSquareHisto;
+  TH1D*   fSignificanceHisto;
+  TH1D*   fSummedAlphaPlots;
+  MHArray *fThetaHistoArray;
+  TLegend *fThetaLegend;
+  Double_t fMaxSignif;
+  Double_t fMaxRedChiSq;
+  Double_t fSlope;             // slope for exponential fit
+  Int_t fThetaBin;
+  Int_t fSigniPlotIndex;
+  Int_t fSigniPlotColor;
+
+  Double_t fSignificance;
+
+  Bool_t CalcAET(TH3D *histon, MParList *parlist, const Bool_t Draw);
+
+  Bool_t FitHistogram(TH1 &alphaHisto, Double_t &sigLiMa,
+		      Double_t &lowerBin, Double_t &upperBin,
+		      Float_t signalRegionFactor = 3, const Bool_t draw = kFALSE,
+		      TString funcName = "");
+
+  Bool_t ExtractSignal(TH1 &alphaHisto, Double_t &sigLiMa,
+		       Double_t &lowerBin, Double_t &upperBin,
+		       Double_t &gammaSignal, Double_t &errorGammaSignal,
+		       Double_t &off, Double_t &errorOff,
+ 		       Float_t signalRegionFactor = 3, const Bool_t draw = kFALSE,
+ 		       TString funcName = "", TPad *drawPad = 0, Int_t drawBase = 0);
+
+
+
+public:
+  MHOnSubtraction(const char *name=NULL, const char *title=NULL);
+  ~MHOnSubtraction();
+
+  Double_t CalcSignificance(Double_t nOn, Double_t nOff, Double_t theta);
+  Double_t GetSignificance()  { return fSignificance; };
+
+  void SetExpoSlope(Double_t slope) { fSlope = slope; }
+  
+  Bool_t Calc(MParList *parlist, const Bool_t Draw);
+
+  Bool_t Calc(TH3 *histon, MParList *parlist, const Bool_t Draw);
+  Bool_t TH2Calc(TH2 *aeHisto, MParList *parlist, const Bool_t Draw, 
+		 TPad *drawPad = 0, Int_t drawBase = 0);
+  Bool_t Calc(TH1 *histon, MParList *parlist, const Bool_t Draw,
+	      Float_t signalRegion = 0);
+
+  void Draw(Option_t *option="");
+  TObject *DrawClone(Option_t *option="") const;
+
+  ClassDef(MHOnSubtraction, 1) //Extracts gamma signals from pure ON-data
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhist/MHSigmaPixel.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHSigmaPixel.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHSigmaPixel.cc	(revision 9772)
@@ -0,0 +1,138 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner 10/2002 <mailto:magicsoft@rwagner.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHSigmaPixel                                                            //
+//                                                                          //
+//  2D-Histogram pedestal sigma vs pixel number                             //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHSigmaPixel.h"
+
+#include <TCanvas.h>
+
+#include <math.h>
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+#include "MSigmabar.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHSigmaPixel);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram. 
+//
+MHSigmaPixel::MHSigmaPixel(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHSigmaPixel";
+    fTitle = title ? title : "2-D histogram in sigma and pixel";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetTitle("Sigma vs pixel #");
+    fHist.SetXTitle("pixel #");
+    fHist.SetYTitle("\\sigma");
+    fHist.SetZTitle("N");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings and prepare filling of the histogram. The binning for the
+// pixel axis is derived automagically from the MPedestalCam container
+// expected to be found in the MParList *plist.
+// 
+Bool_t MHSigmaPixel::SetupFill(const MParList *plist)
+{
+  fPedestalCam = (MPedestalCam*)plist->FindObject("MPedestalCam");
+  if (!fPedestalCam)
+    {
+      *fLog << err << "MPedestalCam not found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  MBinning* binssigma = (MBinning*)plist->FindObject("BinningSigma");
+  if (!binssigma)
+    {
+      *fLog << err << "BinningSigma [MBinning] not found... aborting." << endl;
+      return kFALSE;      
+    }
+
+  const Int_t n = fPedestalCam->GetSize();
+
+  MBinning binspixel;
+  binspixel.SetEdges(n, -0.5, -0.5+n);
+
+  SetBinning(&fHist, &binspixel, binssigma);
+
+  fHist.Sumw2();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+// 
+Bool_t MHSigmaPixel::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MPedestalCam &ped = *(MPedestalCam*)par;
+    for (Int_t i=0;i<(ped.GetSize());i++)
+    {
+        const MPedestalPix pix = ped[i];
+        fHist.Fill(i, pix.GetPedestalRms());
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+// 
+void MHSigmaPixel::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    fHist.Draw(opt);
+
+    gPad->Modified();
+    gPad->Update();
+}
+
Index: /tags/Mars-V0.9/mhist/MHSigmaPixel.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHSigmaPixel.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHSigmaPixel.h	(revision 9772)
@@ -0,0 +1,46 @@
+#ifndef MARS_MHSigmaPixel
+#define MARS_MHSigmaPixel
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class TH2D;
+
+class MMcEvt;
+class MParList;
+class MPedestalCam;
+
+class MHSigmaPixel : public MH
+{
+private:
+    MPedestalCam *fPedestalCam; //!
+
+    TH2D fHist;
+
+public:
+    MHSigmaPixel(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TH2D *GetHist()       { return &fHist; }
+    const TH2D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHSigmaPixel, 1) //2D-histogram in Sigma and Pixel number
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHSigmaTheta.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHSigmaTheta.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHSigmaTheta.cc	(revision 9772)
@@ -0,0 +1,512 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 1/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz 4/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHSigmaTheta                                                            //
+//                                                                          //
+//  calculates - the 2D-histogram   sigmabar vs. Theta (Inner), and         //
+//             - the 2D-histogram   sigmabar vs. Theta (Outer)              //
+//             - the 3D-histogram   sigma, pixel no., Theta                 //
+//             - the 3D-histogram   (sigma^2-sigmabar^2), pixel no., Theta  //
+//             - the 2D-histogram   Theta    vs. Phi                        //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHSigmaTheta.h"
+
+#include <TCanvas.h>
+
+#include "MTime.h"
+#include "MPointingPos.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MBadPixelsCam.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHSigmaTheta);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Constructor. 
+//
+MHSigmaTheta::MHSigmaTheta(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHSigmaTheta";
+    fTitle = title ? title : "2D histogram sigmabar vs. Theta";
+
+    fThetaPhi = new TH2D;
+    fThetaPhi->SetDirectory(NULL);
+    fThetaPhi->UseCurrentStyle();
+    fThetaPhi->SetName("2D-ThetaPhi");
+    fThetaPhi->SetTitle("2D: \\Theta vs. \\Phi");
+    fThetaPhi->SetXTitle("\\phi [\\circ]");
+    fThetaPhi->SetYTitle("\\Theta [\\circ]");
+    fThetaPhi->SetTitleOffset(1.2,"Y");
+
+    fSigmaTheta = new TH2D;
+    fSigmaTheta->SetDirectory(NULL);
+    fSigmaTheta->UseCurrentStyle();
+    fSigmaTheta->SetName("2D-ThetaSigmabar(Inner)");
+    fSigmaTheta->SetTitle("2D: \\bar{\\sigma}, \\Theta");
+    fSigmaTheta->SetXTitle("\\Theta [\\circ]");
+    fSigmaTheta->SetYTitle("Sigmabar(Inner)");
+    fSigmaTheta->SetTitleOffset(1.2,"Y");
+
+    fSigmaThetaOuter = new TH2D;
+    fSigmaThetaOuter->SetDirectory(NULL);
+    fSigmaThetaOuter->UseCurrentStyle();
+    fSigmaThetaOuter->SetName("2D-ThetaSigmabar(Outer)");
+    fSigmaThetaOuter->SetTitle("2D: \\bar{\\sigma}, \\Theta");
+    fSigmaThetaOuter->SetXTitle("\\Theta [\\circ]");
+    fSigmaThetaOuter->SetYTitle("Sigmabar(Outer)");
+    fSigmaThetaOuter->SetTitleOffset(1.2,"Y");
+
+    fSigmaPixTheta = new TH3D;
+    fSigmaPixTheta->SetDirectory(NULL);
+    fSigmaPixTheta->UseCurrentStyle();
+    fSigmaPixTheta->SetName("3D-ThetaPixSigma");
+    fSigmaPixTheta->SetTitle("3D: \\Theta, Pixel Id, \\sigma");
+    fSigmaPixTheta->SetXTitle("\\Theta [\\circ]");
+    fSigmaPixTheta->SetYTitle("Pixel Id");
+    fSigmaPixTheta->SetZTitle("Sigma");
+
+    fDiffPixTheta = new TH3D;
+    fDiffPixTheta->SetDirectory(NULL);
+    fDiffPixTheta->UseCurrentStyle();
+    fDiffPixTheta->SetName("3D-ThetaPixDiff");
+    //fDiffPixTheta->SetTitle("3D: \\Theta, Pixel Id, {\\sigma}^{2}-\\bar{\\sigma}^{2}");
+    fDiffPixTheta->SetTitle("3D: \\Theta, Pixel Id, (Sigma2-Sigmabar2)/Area");
+    fDiffPixTheta->SetXTitle("\\Theta [\\circ]");
+    fDiffPixTheta->SetYTitle("Pixel Id");
+    fDiffPixTheta->SetZTitle("(Sigma2 - Sigmabar2)/Area");
+
+    // Define default binning
+    fBinsPhi = new MBinning;
+    fBinsPhi->SetEdges( 20, 0.0, 360.0);
+
+    Double_t fThetaLo =  0.0;
+    Double_t fThetaHi = 90.0;
+    fBinsTheta = new MBinning;
+    fBinsTheta->SetEdgesCos( 10,  fThetaLo, fThetaHi);   // theta
+    //fBinsTheta->SetEdges( 1, fThetaLo, fThetaHi);   // theta
+
+    fBinsSigma = new MBinning;
+    fBinsSigma->SetEdges(   100,     0.0, 120.0);   // sigma 
+
+    fBinsSigmabarIn  = new MBinning;
+    fBinsSigmabarOut = new MBinning;;
+    fBinsSigmabarIn->SetEdges( 100,     0.0,  25.0);   // sigmabar (inner)
+    fBinsSigmabarOut->SetEdges(100,     0.0,  60.0);   // sigmabar (outer)
+
+    fBinsPix = new MBinning;
+    fBinsPix->SetEdges(578, -0.5, 577.5);
+
+    fBinsDiff = new MBinning;
+    fBinsDiff->SetEdges(   100,  -500.0, 1500.0);   // (sigma2-sigmabar2)/area
+
+    SetBinning(fThetaPhi,        fBinsPhi,   fBinsTheta);
+    SetBinning(fSigmaTheta,      fBinsTheta, fBinsSigmabarIn);
+    SetBinning(fSigmaThetaOuter, fBinsTheta, fBinsSigmabarOut);
+    SetBinning(fSigmaPixTheta,   fBinsTheta, fBinsPix, fBinsSigma);
+    SetBinning(fDiffPixTheta,    fBinsTheta, fBinsPix, fBinsDiff);
+
+    //--------------------------------------------
+    fNamePedPhotCam = "MPedPhotCamFromData";
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MHSigmaTheta::~MHSigmaTheta()
+{
+  delete fThetaPhi;
+  delete fSigmaTheta;
+  delete fSigmaThetaOuter;
+  delete fSigmaPixTheta;
+  delete fDiffPixTheta;
+
+  delete fBinsPhi;
+  delete fBinsTheta;
+  delete fBinsSigma;
+  delete fBinsSigmabarIn;
+  delete fBinsSigmabarOut;
+  delete fBinsPix;
+  delete fBinsDiff;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHSigmaTheta::SetupFill(const MParList *plist)
+{
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointPos = (MPointingPos*)plist->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed = (MPedPhotCam*)plist->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+    if (!fPed)
+    {
+        *fLog << err << AddSerialNumber(fNamePedPhotCam) 
+              << "[MPedPhotCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+    fPed->InitSize(fCam->GetNumPixels()); 
+
+    
+    fBad = (MBadPixelsCam*)plist->FindObject("MBadPixelsCam");
+    if (!fBad)
+    {  
+       *fLog << err << "MBadPixelsCam not found... continue. " << endl; 
+    }
+
+
+    fEvt = (MCerPhotEvt*)plist->FindObject("MCerPhotEvt");
+    if (!fEvt)
+    {
+        *fLog << err << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    //---------------------------------------------------------------
+    *fLog << inf << "Name of MPedPhotCam container : " 
+          << fNamePedPhotCam << endl;
+
+
+    //---------------------------------------------------------------
+
+    // Get Phi Binning
+    MBinning* binsphi  = (MBinning*)plist->FindObject("BinningPhi", "MBinning");
+    if (!binsphi)
+    {
+        *fLog << warn << "Object 'BinningPhi' [MBinning] not found... use default binning." << endl;
+        binsphi = fBinsPhi;
+    }
+
+    // Get Theta Binning
+    MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta", "MBinning");
+    if (!binstheta)
+    {
+        *fLog << warn << "Object 'BinningTheta' [MBinning] not found... use default binning." << endl;
+        binstheta = fBinsTheta;
+    }
+
+    // Get Sigma binning
+    MBinning* binssig = (MBinning*)plist->FindObject("BinningSigma", "MBinning");
+    if (!binssig)
+    {
+        *fLog << warn << "Object 'BinningSigma' [MBinning] not found... use default binning." << endl;
+        binssig = fBinsSigma;
+    }
+
+    // Get SigmabarIn binning
+    MBinning* binssigmain = (MBinning*)plist->FindObject("BinningSigmabarIn", "MBinning");
+    if (!binssigmain)
+    {
+        *fLog << warn << "Object 'BinningSigmabarIn' [MBinning] not found... use default binning." << endl;
+        binssigmain = fBinsSigmabarIn;
+    }
+
+    // Get SigmabarOut binning
+    MBinning* binssigmaout = (MBinning*)plist->FindObject("BinningSigmabarOut", "MBinning");
+    if (!binssigmaout)
+    {
+        *fLog << warn << "Object 'BinningSigmabarOut' [MBinning] not found... use default binning." << endl;
+        binssigmaout = fBinsSigmabarOut;
+    }
+
+    // Get binning for (sigma^2-sigmabar^2)
+    MBinning* binsdiff  = (MBinning*)plist->FindObject("BinningDiffsigma2", "MBinning");
+    if (!binsdiff)
+    {
+        *fLog << warn << "Object 'BinningDiffsigma2' [MBinning] not found... use default binning." << endl;
+        binsdiff = fBinsDiff;
+    }
+
+
+    //---------------------------------------------------------------
+
+    // Get binning for pixel number
+    const UInt_t npix1 = fPed->GetSize()+1;
+    //*fLog << "MHSigmaTheata::SetupFill(); npix1 = " << npix1 << endl;
+    MBinning binspix("BinningPixel");
+    binspix.SetEdges(npix1, -0.5, npix1-0.5);
+
+    // Set binnings in histograms
+    SetBinning(fThetaPhi,        binsphi,   binstheta);
+    SetBinning(fSigmaTheta,      binstheta, binssigmain);
+    SetBinning(fSigmaThetaOuter, binstheta, binssigmaout);
+    SetBinning(fSigmaPixTheta,   binstheta, &binspix, binssig);
+    SetBinning(fDiffPixTheta,    binstheta, &binspix, binsdiff);
+
+    *fLog << "MHSigmaTheta::SetupFill(); binnings were set" << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill the histograms
+//
+//  ignore pixels if they are unused or blind
+//
+Bool_t MHSigmaTheta::Fill(const MParContainer *par, const Stat_t w)
+{
+    Double_t theta = fPointPos->GetZd();
+    Double_t phi   = fPointPos->GetAz();
+
+    fPed->ReCalc(*fCam, fBad);
+
+    Double_t mysig      = (fPed->GetArea(0)).GetRms();
+    Double_t mysigouter = (fPed->GetArea(1)).GetRms();
+
+    //*fLog << "theta, mysig, mysigouter = " << theta << ",  " << mysig 
+    //      << ",  " << mysigouter << endl;
+
+    fThetaPhi->Fill(phi, theta);
+    fSigmaTheta->Fill(theta, mysig);
+    fSigmaThetaOuter->Fill(theta, mysigouter);
+
+    MCerPhotPix *cerpix = 0;
+    TIter Next(*fEvt);
+    while ( (cerpix=(MCerPhotPix*)Next()) )
+    {
+        const Int_t id = cerpix->GetPixId();
+
+        if (!cerpix->IsPixelUsed())
+	{
+          //*fLog << all << "MHSigmaTheta::Fill; unused pixel found, id = "
+          //      << id << endl;
+          continue;
+	}
+
+        const MPedPhotPix &pix = (*fPed)[id];
+
+        // ratio is the area of pixel 0 
+        //          divided by the area of the current pixel
+        const Double_t ratio = fCam->GetPixRatio(id);
+        const Double_t sigma = pix.GetRms();
+
+        fSigmaPixTheta->Fill(theta, (Double_t)id, sigma);
+
+	Double_t diff;
+        const Byte_t aidx = (*fCam)[id].GetAidx();
+        if (aidx == 0)
+	{
+          // inner pixel
+          diff = (sigma*sigma - mysig*mysig) * ratio;
+	}
+        else
+	{
+          // outer pixel
+          diff = (sigma*sigma - mysigouter*mysigouter) * ratio;
+	}
+
+        fDiffPixTheta->Fill(theta, (Double_t)id, diff);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the projections and (if possible) set log scales before painting
+//
+void MHSigmaTheta::Paint(Option_t *opt)
+{
+    TVirtualPad *padsave = gPad;
+
+    TH1D* h;
+
+    padsave->cd(1);
+    if ((h = (TH1D*)gPad->FindObject("ProjX-Theta")))
+    {
+        ProjectionX(*h, *fSigmaTheta);
+        if (h->GetEntries()!=0)
+            gPad->SetLogy();
+    }
+
+    padsave->cd(4);
+    if ((h = (TH1D*)gPad->FindObject("ProjY-sigma")))
+        ProjectionY(*h, *fSigmaTheta);
+
+    gPad = padsave;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHSigmaTheta::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+    AppendPad("");
+
+    pad->Divide(3, 3);
+
+    // draw the 2D histogram Sigmabar versus Theta
+    TH1 *h;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    h = fSigmaTheta->ProjectionX("ProjX-Theta", -1, 9999, "E");
+    h->SetDirectory(NULL);
+    h->UseCurrentStyle();
+    h->SetTitle("Distribution of \\Theta");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("No.of events");
+    h->SetTitleOffset(1.2,"Y");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    h = fDiffPixTheta->Project3D("zx");
+    h->SetDirectory(NULL);
+    h->UseCurrentStyle();
+    //h->SetTitle("\\sigma_{ped}^{2}-\\bar{\\sigma}_{ped}^{2} vs. \\Theta (all pixels)");
+    h->SetTitle("(Sigma2-Sigmabar2)/Area  vs. \\Theta (all pixels)");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("(Sigma2 - Sigmabar2) / Area");
+    h->SetTitleOffset(1.2,"Y");
+    h->Draw("box");
+    h->SetBit(kCanDelete);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = fSigmaPixTheta->Project3D("zx");
+    h->SetDirectory(NULL);
+    h->UseCurrentStyle();
+    h->SetTitle("\\sigma_{ped} vs. \\Theta (all pixels)");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("Sigma");
+    h->SetTitleOffset(1.2,"Y");
+    h->Draw("box");
+    h->SetBit(kCanDelete);
+
+    //pad->cd(7);
+    //gPad->SetBorderMode(0);
+    //h = fSigmaTheta->ProjectionY("ProjY-sigma", -1, 9999, "E");
+    //h->SetDirectory(NULL);
+    //h->UseCurrentStyle();
+    //h->SetTitle("Distribution of \\bar{\\sigma}_{ped}");
+    //h->SetXTitle("\\bar{\\sigma}_{ped}");
+    //h->SetYTitle("No.of events");
+    //h->SetTitleOffset(1.2,"Y");
+    //h->Draw(opt);
+    //h->SetBit(kCanDelete);
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    h = fDiffPixTheta->Project3D("zy");
+    h->SetDirectory(NULL);
+    h->UseCurrentStyle();
+    //h->SetTitle("\\sigma_{ped}^{2}-\\bar{\\sigma}_{ped}^{2} vs. pixel Id (all  \\Theta)");
+    h->SetTitle("(Sigma2-Sigmabar2)/Area  vs. pixel Id (all  \\Theta)");
+    h->SetXTitle("Pixel Id");
+    h->SetYTitle("(Sigma2 - sigmabar2) / Area");
+    h->SetTitleOffset(1.2,"Y");
+    h->Draw("box");
+    h->SetBit(kCanDelete);
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    h = fSigmaPixTheta->Project3D("zy");
+    h->SetDirectory(NULL);
+    h->UseCurrentStyle();
+    h->SetTitle("\\sigma_{ped} vs. pixel Id (all  \\Theta)");
+    h->SetXTitle("Pixel Id");
+    h->SetYTitle("Sigma");
+    h->SetTitleOffset(1.2,"Y");
+    h->Draw("box");
+    h->SetBit(kCanDelete);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fSigmaTheta->Draw();
+
+    pad->cd(7);
+    gPad->SetBorderMode(0);
+    fSigmaThetaOuter->Draw();
+
+    pad->cd(8);
+    gPad->SetBorderMode(0);
+    fThetaPhi->Draw();
+
+    pad->cd(9);
+    gPad->SetBorderMode(0);
+    h = fThetaPhi->ProjectionX("ProjX-Phi", -1, 9999, "E");
+    h->SetDirectory(NULL);
+    h->UseCurrentStyle();
+    h->SetTitle("Distribution of \\Phi");
+    h->SetXTitle("\\phi [\\circ]");
+    h->SetYTitle("No. of events");
+    h->SetTitleOffset(1.2,"Y");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHSigmaTheta.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHSigmaTheta.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHSigmaTheta.h	(revision 9772)
@@ -0,0 +1,89 @@
+#ifndef MARS_MHSigmaTheta
+#define MARS_MHSigmaTheta
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+
+class MParList;
+class MGeomCam;
+class MCerPhotEvt;
+class MPointingPos;
+class MPedPhotCam;
+class MBadPixelsCam;
+
+
+class MHSigmaTheta : public MH
+{
+private:
+    const MGeomCam *fCam;        //!
+    MPedPhotCam    *fPed;        //!
+    MCerPhotEvt    *fEvt;        //!
+    MPointingPos   *fPointPos;   //!
+    MBadPixelsCam  *fBad;        //!
+
+    TString  fNamePedPhotCam; //! name of the 'MPedPhotCam' container
+
+                           // sigmabar is the average pedestal sigma  
+    TH2D *fSigmaTheta;      // 2D-distribution sigmabar versus Theta (Inner) 
+    TH2D *fSigmaThetaOuter; // 2D-distribution sigmabar versus Theta (Outer) 
+
+    TH3D *fSigmaPixTheta; // 3D-distr.:Theta, pixel, pedestal sigma
+    TH3D *fDiffPixTheta;  // 3D-distr.:Theta, pixel, sigma^2-sigmabar^2
+
+    TH2D *fThetaPhi;      // 2D-distribution Theta versus Phi 
+
+    MBinning *fBinsPhi;            //!
+    MBinning *fBinsTheta;          //!
+    MBinning *fBinsSigma;          //!
+    MBinning *fBinsSigmabarIn;     //!
+    MBinning *fBinsSigmabarOut;    //!
+    MBinning *fBinsPix;            //!
+    MBinning *fBinsDiff;           //!
+
+    void Paint(Option_t *opt="");
+
+public:
+    MHSigmaTheta(const char *name=NULL, const char *title=NULL);
+    ~MHSigmaTheta();
+
+    void SetNamePedPhotCam(const char *name)  { fNamePedPhotCam = name; }
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TH2D *GetThetaPhi() { return fThetaPhi; }
+    const TH2D *GetThetaPhi() const { return fThetaPhi; }
+
+    const TH2D *GetSigmaTheta() { return fSigmaTheta; }
+    const TH2D *GetSigmaTheta() const { return fSigmaTheta; }
+
+    const TH2D *GetSigmaThetaOuter() { return fSigmaThetaOuter; }
+    const TH2D *GetSigmaThetaOuter() const { return fSigmaThetaOuter; }
+
+    const TH3D *GetSigmaPixTheta() { return fSigmaPixTheta; }
+    const TH3D *GetSigmaPixTheta() const { return fSigmaPixTheta; }
+
+    const TH3D *GetDiffPixTheta() { return fDiffPixTheta; }
+    const TH3D *GetDiffPixTheta() const { return fDiffPixTheta; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHSigmaTheta, 1) //2D-histogram  sigmabar vs. Theta
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHSigmabarTheta.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHSigmabarTheta.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHSigmabarTheta.cc	(revision 9772)
@@ -0,0 +1,137 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner 10/2002 <mailto:magicsoft@rwagner.de>
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHSigmabarTheta                                                         //
+//                                                                          //
+//  2D-Histogram in Sigmabar and Theta                                      //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHSigmabarTheta.h"
+
+#include <TCanvas.h>
+
+#include <math.h>
+
+#include "MMcEvt.hxx"
+#include "MSigmabar.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHSigmabarTheta);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram. 
+//
+MHSigmabarTheta::MHSigmabarTheta(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHSigmabarTheta";
+    fTitle = title ? title : "3-D histogram in sigmabar and theta";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetTitle("3D-plot of sigmabar and theta");
+    fHist.SetXTitle("\\theta [\\circ]");
+    fHist.SetYTitle("\\bar{\\sigma}");
+    fHist.SetZTitle("N");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings and prepare filling of the histogram
+// 
+Bool_t MHSigmabarTheta::SetupFill(const MParList *plist)
+{
+   fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+   if (!fMcEvt)
+   {
+       *fLog << err << "MMcEvt not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   fSigmabar = (MSigmabar*)plist->FindObject("MSigmabar");
+   if (!fSigmabar)
+   {
+       *fLog << err << "MSigmabar not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta");
+   if (!binstheta)
+   {
+       *fLog << err << "BinningTheta [MBinning] not found... aborting." << endl;
+       return kFALSE;      
+   }
+   MBinning* binssigmabar = (MBinning*)plist->FindObject("BinningSigmabar");
+   if (!binssigmabar)
+   {
+       *fLog << err << "BinningSigmabar [MBinning] not found... aborting." << endl;
+       return kFALSE;      
+   }
+
+   SetBinning(&fHist, binstheta, binssigmabar);
+
+   fHist.Sumw2(); 
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+// 
+Bool_t MHSigmabarTheta::Fill(const MParContainer *par, const Stat_t w)
+{
+    fHist.Fill(fMcEvt->GetTheta()*kRad2Deg, fSigmabar->GetSigmabar(), w);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+// 
+void MHSigmabarTheta::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    fHist.Draw(opt);
+    
+    pad->Modified();
+    pad->Update();
+}
+
Index: /tags/Mars-V0.9/mhist/MHSigmabarTheta.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHSigmabarTheta.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHSigmabarTheta.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MHSigmabarTheta
+#define MARS_MHSigmabarTheta
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+class MSigmabar;
+class TH2D;
+class MParList;
+
+
+class MHSigmabarTheta : public MH
+{
+private:
+    MMcEvt    *fMcEvt;        //!
+    MSigmabar *fSigmabar;     //!
+
+    TH2D fHist;
+
+public:
+    MHSigmabarTheta(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TH2D *GetHist()       { return &fHist; }
+    const TH2D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHSigmabarTheta, 1) //3D-histogram in alpha, Energy and theta
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHStarMap.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHStarMap.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHStarMap.cc	(revision 9772)
@@ -0,0 +1,420 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek 02/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHStarMap
+//
+// This class contains a 2-dimensional histogram. It should show some
+// kind of star map. The algorith which calculates the star map
+// from the Hillas parameters (Fill) can be enhanced.
+//
+// For a given a shower, a series of points along its main axis are filled 
+// into the 2-dim histogram (x, y) of the camera plane.
+//
+// Before filling a point (x, y) into the histogram it is
+//        - shifted by (xSrc, ySrc)   (the expected source position)
+//        - and rotated in order to compensate the rotation of the
+//          sky image in the camera
+//
+// To be done:
+//  - simplification of the algorithm, by doing all translation before
+//    calculation of the line
+//  - the center of rotation need not to be the camera center
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHStarMap.h"
+
+#include <TH2.h>
+#include <TStyle.h>   // gStyle
+#include <TColor.h>   // SetRGB
+#include <TCanvas.h>  // TCanvas
+#include <TVector2.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MAstro.h"
+#include "MGeomCam.h"
+#include "MHillas.h"
+#include "MBinning.h"
+#include "MSrcPosCam.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+
+ClassImp(MHStarMap);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Create the star map histogram
+//
+MHStarMap::MHStarMap(const char *name, const char *title)
+    : fMm2Deg(-1), fUseMmScale(kTRUE)
+{
+    //
+    //  default constructor
+    //  creates an a list of histograms for all pixels and both gain channels
+    //
+
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHStarMap" ;
+    fTitle = title ? title : "Container for a Star Map" ;
+
+    //
+    //   loop over all Pixels and create two histograms
+    //   one for the Low and one for the High gain
+    //   connect all the histogram with the container fHist
+    //
+    fStarMap = new TH2F("StarMap", " 2D Hillas Star Map ",
+                        150, -300, 300,
+                        150, -300, 300);
+
+    fStarMap->SetDirectory(NULL);
+
+    fStarMap->SetXTitle("x [mm]");
+    fStarMap->SetYTitle("y [mm]");
+    fStarMap->SetZTitle("Counts");
+}
+
+// --------------------------------------------------------------------------
+//
+// delete the histogram instance
+//
+MHStarMap::~MHStarMap()
+{
+    delete fStarMap;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning (with the names 'BinningCamera')
+// are found in the parameter list
+// Use this function if you want to set the conversion factor which
+// is used to convert the mm-scale in the camera plain into the deg-scale
+// used for histogram presentations. The conversion factor is part of
+// the camera geometry. Please create a corresponding MGeomCam container.
+//
+Bool_t MHStarMap::SetupFill(const MParList *plist)
+{
+    const MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (geom)
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+        fUseMmScale = kFALSE;
+
+        fStarMap->SetXTitle("x [\\circ]");
+        fStarMap->SetYTitle("y [\\circ]");
+    }
+
+    fPointPos = (MPointingPos*)plist->FindObject("MPointingPos");
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... no derotation." << endl;
+
+    fSrcPos = (MSrcPosCam*)plist->FindObject(AddSerialNumber("MSrcPosCam"));
+    if (!fSrcPos)
+        *fLog << warn << "MSrcPosCam not found...  no source translation." << endl;
+
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningStarMap");
+    if (!bins)
+    {
+        float r = geom ? geom->GetMaxRadius() : 600;
+        r *= 5./6;
+        if (!fUseMmScale)
+            r *= fMm2Deg;
+
+        MBinning b;
+        b.SetEdges(100, -r, r);
+        SetBinning(fStarMap, &b, &b);
+    }
+    else
+        SetBinning(fStarMap, bins, bins);
+
+    if (!geom)
+    {
+        *fLog << warn << "No Camera Geometry available. Using mm-scale for histograms." << endl;
+        return kTRUE;
+    }
+
+    *fLog << warn << "WARNING - Using MHStarMap doesn't take care of the Source Position!" << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the observatory location "MObservatory" from parameter list
+// 
+Bool_t MHStarMap::ReInit(MParList *pList)
+{
+    fObservatory = (MObservatory*)pList->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+        *fLog << err << "MObservatory not found... no derotation." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the four histograms with data from a MHillas-Container.
+// Be careful: Only call this with an object of type MHillas
+//
+Bool_t MHStarMap::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MHillas &h = *(MHillas*)par;
+
+    const Float_t delta = h.GetDelta();
+
+    const Float_t m    = TMath::Tan(delta);
+
+    const Float_t cosd = 1.0/TMath::Sqrt(m*m+1);
+    const Float_t sind = TMath::Sqrt(1-cosd*cosd);
+
+    Float_t t = h.GetMeanY() - m*h.GetMeanX();
+
+    TVector2 src;
+    if (fSrcPos)
+        src = fSrcPos->GetXY();
+
+    if (!fUseMmScale)
+    {
+        t   *= fMm2Deg;
+        src *= fMm2Deg;
+    }
+
+    // get step size ds along the main axis of the ellipse
+    const TAxis &axex = *fStarMap->GetXaxis();
+    const Float_t xmin = axex.GetXmin();
+    const Float_t xmax = axex.GetXmax();
+
+    // FIXME: Fixed number?
+    const Float_t ds = (xmax-xmin) / 200.0;
+
+    // Fill points along the main axis of the shower into the histogram;
+    // before filling 
+    //   - perform a translation by (xSource, ySource)
+    //   - and perform a rotation to compensate the rotation of the
+    //     sky image in the camera
+    const Double_t rho = fPointPos && fObservatory ?
+        fPointPos->RotationAngle(*fObservatory) : 0;
+
+    if (m>-1 && m<1)
+    {
+        const Float_t dx = ds * cosd;
+
+        for (float x=xmin+dx/2; x<(xmax-xmin)+dx; x+=dx)
+        {
+            TVector2 v(x, m*x+t);
+            v -= src;
+            v=v.Rotate(-rho);
+
+            fStarMap->Fill(v.X(), v.Y(), w);
+        }
+    }
+    else
+    {
+        const TAxis &axey = *fStarMap->GetYaxis();
+        const Float_t ymin = axey.GetXmin();
+        const Float_t ymax = axey.GetXmax();
+
+        const float dy = ds * sind;
+
+        for (float y=ymin+dy/2; y<(ymax-ymin)+dy; y+=dy)
+        {
+            TVector2 v((y-t)/m, y);
+            v -= src;
+            v=v.Rotate(-rho);
+
+            fStarMap->Fill(v.X(), v.Y(), w);
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this function to setup your own conversion factor between degrees
+// and millimeters. The conversion factor should be the one calculated in
+// MGeomCam. Use this function with Caution: You could create wrong values
+// by setting up your own scale factor.
+//
+void MHStarMap::SetMm2Deg(Float_t mmdeg)
+{
+    if (mmdeg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Conversion factor < 0 - nonsense. Ignored." << endl;
+        return;
+    }
+
+    if (fMm2Deg>=0)
+        *fLog << warn << dbginf << "Warning - Conversion factor already set. Overwriting" << endl;
+
+    fMm2Deg = mmdeg;
+}
+
+// --------------------------------------------------------------------------
+//
+// With this function you can convert the histogram ('on the fly') between
+// degrees and millimeters.
+//
+void MHStarMap::SetMmScale(Bool_t mmscale)
+{
+    if (fUseMmScale == mmscale)
+        return;
+
+    if (fMm2Deg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Sorry, no conversion factor for conversion available." << endl;
+        return;
+    }
+
+    if (fUseMmScale)
+    {
+        fStarMap->SetXTitle("x [mm]");
+        fStarMap->SetYTitle("y [mm]");
+
+        fStarMap->Scale(1./fMm2Deg);
+    }
+    else
+    {
+        fStarMap->SetXTitle("x [\\circ]");
+        fStarMap->SetYTitle("y [\\circ]");
+
+        fStarMap->Scale(1./fMm2Deg);
+    }
+
+    fUseMmScale = mmscale;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the palette you wanna use:
+//  - you could set the root "Pretty Palette Violet->Red" by
+//    gStyle->SetPalette(1, 0), but in some cases this may look
+//    confusing
+//  - The maximum colors root allowes us to set by ourself
+//    is 50 (idx: 51-100). This colors are set to a grayscaled
+//    palette
+//  - the number of contours must be two less than the number
+//    of palette entries
+//
+void MHStarMap::PrepareDrawing() const
+{
+    const Int_t numg = 32; // number of gray scaled colors
+    const Int_t numw = 32; // number of white
+
+    Int_t palette[numg+numw];
+
+    //
+    // The first half of the colors are white.
+    // This is some kind of optical background supression
+    //
+    gROOT->GetColor(51)->SetRGB(1, 1, 1);
+
+    Int_t i;
+    for (i=0; i<numw; i++)
+        palette[i] = 51;
+
+    //
+    // now the (gray) scaled part is coming
+    //
+    for (;i<numw+numg; i++)
+    {
+        const Float_t gray = 1.0-(float)(i-numw)/(numg-1.0);
+
+        gROOT->GetColor(52+i)->SetRGB(gray, gray, gray);
+        palette[i] = 52+i;
+    }
+
+    //
+    // Set the palette and the number of contour levels
+    //
+    gStyle->SetPalette(numg+numw, palette);
+    fStarMap->SetContour(numg+numw-2);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw clones of the  histograms, so that the object can be deleted
+// and the histogram is still visible in the canvas.
+// The cloned object is deleted together with the canvas if the canvas is
+// destroyed. If you want to handle destroying the canvas you can get a
+// pointer to it from this function
+//
+TObject *MHStarMap::DrawClone(Option_t *opt) const
+{
+    return MH::DrawClone(opt, 500, 500);
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draw the histogram into it.
+// Be careful: The histogram belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHStarMap::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this, 500, 500);
+    pad->SetBorderMode(0);
+
+    pad->Divide(1,1);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+
+    AppendPad("");
+}
+
+void MHStarMap::Paint(Option_t *opt)
+{
+    //
+    // Maintain aspect ratio
+    //
+    const float w = gPad->GetWw();
+    const float h = gPad->GetWh();
+
+    if (h<w)
+        gPad->SetPad((1.-h/w)/2, 0, (h/w+1)/2, 1);
+    else
+        gPad->SetPad(0, (1.-w/h)/2, 1, (w/h+1)/2);
+
+    //
+    // Maintain colors
+    //
+    PrepareDrawing();
+
+    //
+    // Paint Histogram
+    //
+    fStarMap->Paint("colz");
+}
Index: /tags/Mars-V0.9/mhist/MHStarMap.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHStarMap.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHStarMap.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MHStarMap
+#define MARS_MHStarMap
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH2F;
+class MHillas;
+class MSrcPosCam;
+class MObservatory;
+class MPointingPos;
+
+class MHStarMap : public MH
+{
+private:
+    MSrcPosCam   *fSrcPos;      //!
+    MPointingPos *fPointPos;    //!
+    MObservatory *fObservatory; //!
+
+    TH2F *fStarMap;      //->
+
+    Float_t fMm2Deg;
+
+    Bool_t fUseMmScale;
+
+    Float_t fCosLat;  //!
+    Float_t fSinLat;  //!
+
+    void PrepareDrawing() const;
+
+    void Paint(Option_t *opt="");
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    Bool_t ReInit(MParList *pList);
+    void GetRotationAngle(Double_t &sin, Double_t &cos);
+
+public:
+    MHStarMap(const char *name=NULL, const char *title=NULL);
+    ~MHStarMap();
+
+    void SetMmScale(Bool_t mmscale=kTRUE);
+    void SetMm2Deg(Float_t mmdeg);
+
+    TH1 *GetHistByName(const TString name) { return (TH1*)fStarMap; }
+
+    TH2F *GetHist() { return fStarMap; }
+
+    void Draw(Option_t *opt=NULL);
+    TObject *DrawClone(Option_t *opt=NULL) const;
+
+    ClassDef(MHStarMap, 1) // Container to hold the Starmap
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHSupercuts.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHSupercuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHSupercuts.cc	(revision 9772)
@@ -0,0 +1,225 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHSupercuts
+//
+// This class contains histograms for the supercuts
+//
+// the histograms are filled during the optimization of the supercuts
+//
+///////////////////////////////////////////////////////////////////////
+#include "MHSupercuts.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MParList.h"
+#include "MHFindSignificance.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHSupercuts);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Alpha, and Dist
+//
+MHSupercuts::MHSupercuts(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHSupercuts";
+    fTitle = title ? title : "Container for histograms for the supercuts";
+
+
+    fDegree = new TH1F("Degree", "Degree of polynomial",   5, -0.5,  4.5);
+    fProb   = new TH1F("Prob",   "chi2 probability",      40,    0,  1.0);
+    fNdf    = new TH1F("NDF",    "NDF of polynomial fit", 60, -0.5, 59.5);
+    fGamma  = new TH1F("gamma",  "gamma",                 40,  0.0,  8.0);
+    fNexNon = new TH1F("NexNon", "Nex / Non",             50,  0.0,  1.0);
+    fSigLiMa= new TH1F("Significance", "significance of gamma signal",   
+                                                          60,  0.0, 120.0);
+    fSigtoBackg= new TH2F("SigtoBackg", "Significance vs signal/backg ratio",
+                          50,  0.0,  10.0, 60, 0.0, 120.0);
+    fSigDegree = new TH2F("SigDegree", "Significance vs Degree of polynomial",
+                           5, -0.5,   4.5, 60, 0.0, 120.0);
+    fSigNbins  = new TH2F("SigNbins", "Significance vs number of bins",
+                           40, -0.5, 79.5, 60, 0.0, 120.0);
+
+    fDegree->SetDirectory(NULL);
+    fProb->SetDirectory(NULL);
+    fNdf->SetDirectory(NULL);
+    fGamma->SetDirectory(NULL);
+    fNexNon->SetDirectory(NULL);
+    fSigLiMa->SetDirectory(NULL);
+    fSigtoBackg->SetDirectory(NULL);
+    fSigDegree->SetDirectory(NULL);
+    fSigNbins->SetDirectory(NULL);
+
+    fDegree->SetXTitle("order of polynomial");
+    fProb->SetXTitle("chi2 probability of polynomial fit");
+    fNdf->SetXTitle("NDF of polynomial fit");
+    fGamma->SetXTitle("gamma");
+    fNexNon->SetXTitle("Nex / Non");
+    fSigLiMa->SetXTitle("significance");
+
+    fSigtoBackg->SetXTitle("signa./background ratio");
+    fSigtoBackg->SetYTitle("significance");
+
+    fSigDegree->SetXTitle("order of polynomial");
+    fSigDegree->SetYTitle("significance");
+
+    fSigNbins->SetXTitle("number of bins");
+    fSigNbins->SetYTitle("significance");
+
+    fDegree->SetYTitle("Counts");
+    fProb->SetYTitle("Counts");
+    fNdf->SetYTitle("Counts");
+    fGamma->SetYTitle("Counts");
+    fNexNon->SetYTitle("Counts");
+    fSigLiMa->SetYTitle("Counts");
+
+    fSigtoBackg->SetZTitle("Counts");
+    fSigDegree->SetZTitle("Counts");
+    fSigNbins->SetZTitle("Counts");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms
+//
+MHSupercuts::~MHSupercuts()
+{
+    delete fDegree;
+    delete fProb;
+    delete fNdf;
+    delete fGamma;
+    delete fNexNon;
+    delete fSigLiMa;
+
+    delete fSigtoBackg;
+    delete fSigDegree;
+    delete fSigNbins;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms from the 'MHFindSignificance' container
+//
+Bool_t MHSupercuts::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MHSupercuts::Fill: Pointer (!=NULL) expected." << endl;
+        return kFALSE;
+    }
+
+    MHFindSignificance &h = *(MHFindSignificance*)par;
+
+    fDegree    ->Fill(h.GetDegree( ), w);
+    fProb      ->Fill(h.GetProb(),    w);
+    fNdf       ->Fill(h.GetNdf(),     w);
+    fGamma     ->Fill(h.GetGamma(),   w);
+
+    Double_t ratio = h.GetNon()>0.0 ? h.GetNex()/h.GetNon() : 0.0;
+    fNexNon    ->Fill(ratio,          w);
+
+    fSigLiMa   ->Fill(h.GetSigLiMa(), w);
+
+    Double_t sigtobackg = h.GetNbg()!=0.0 ? h.GetNex() / h.GetNbg() : 0.0;
+    fSigtoBackg->Fill(sigtobackg,    h.GetSigLiMa(), w);
+
+    fSigDegree ->Fill(h.GetDegree(), h.GetSigLiMa(), w);
+    fSigNbins  ->Fill(h.GetMbins(),  h.GetSigLiMa(), w);
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the two histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHSupercuts::Draw(Option_t *)
+{
+  //TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+  //pad->SetBorderMode(0);
+  //AppendPad("");
+
+    TCanvas *pad = new TCanvas("Supercuts", "Supercut plots", 900, 900);
+    gROOT->SetSelectedPad(NULL);
+
+    pad->Divide(3, 3);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fDegree->Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fProb->Draw();
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fNdf->Draw();
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fGamma->Draw();
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    fNexNon->Draw();
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    fSigLiMa->Draw();
+
+    pad->cd(7);
+    gPad->SetBorderMode(0);
+    fSigtoBackg->Draw();
+
+    pad->cd(8);
+    gPad->SetBorderMode(0);
+    fSigDegree->Draw();
+
+    pad->cd(9);
+    gPad->SetBorderMode(0);
+    fSigNbins->Draw();
+
+    pad->Modified();
+    pad->Update();
+}
Index: /tags/Mars-V0.9/mhist/MHSupercuts.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHSupercuts.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHSupercuts.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHSupercuts
+#define MARS_MHSupercuts
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1F;
+class TH2F;
+
+class MHSupercuts : public MH
+{
+private:
+    TH1F *fDegree;     // order of polynomial for background fit
+    TH1F *fProb;       // chi2 probability of polynomial fit
+    TH1F *fNdf;        // NDF of polynomial fit
+    TH1F *fGamma;      // Nbg = gamma * Noff
+    TH1F *fNexNon;     // no.of excess events / no.of events in signal region 
+    TH1F *fSigLiMa;    // significance of gamma signal
+
+    TH2F *fSigtoBackg; // significance vs signal to background ratio (Nex/Nbg)
+    TH2F *fSigDegree;  // significance vs order of polynomial
+    TH2F *fSigNbins;   // significance vs number of bins
+
+
+public:
+    MHSupercuts(const char *name=NULL, const char *title=NULL);
+    ~MHSupercuts();
+
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    void Draw(Option_t *opt=NULL);
+
+    ClassDef(MHSupercuts, 1) // Container which holds histograms for the supercuts
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHThetabarTheta.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHThetabarTheta.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHThetabarTheta.cc	(revision 9772)
@@ -0,0 +1,121 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 1/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHThetabarTheta                                                         //
+//                                                                          //
+//  calculates the average Theta for different bins in Theta                //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHThetabarTheta.h"
+
+#include <TCanvas.h>
+
+#include "MMcEvt.hxx"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHThetabarTheta);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram.
+//
+MHThetabarTheta::MHThetabarTheta(const char *name, const char *title)
+    : fHist()
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHThetabarTheta";
+    fTitle = title ? title : "1-D profile histogram Thetabar vs. Theta";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("\\Theta [\\circ]");
+    fHist.SetYTitle("\\bar{\\Theta} [ \\circ]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHThetabarTheta::SetupFill(const MParList *plist)
+{
+    fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MBinning* binstheta = (MBinning*)plist->FindObject("BinningTheta");
+    if (!binstheta )
+    {
+        *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(&fHist, binstheta);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHThetabarTheta::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    fHist.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+//
+Bool_t MHThetabarTheta::Fill(const MParContainer *par, const Stat_t w)
+{
+    const Double_t theta = fMcEvt->GetTelescopeTheta()*kRad2Deg;
+
+    fHist.Fill(theta, theta, w);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mhist/MHThetabarTheta.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHThetabarTheta.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHThetabarTheta.h	(revision 9772)
@@ -0,0 +1,52 @@
+#ifndef MARS_MHThetabarTheta
+#define MARS_MHThetabarTheta
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TProfile
+#include <TProfile.h>
+#endif
+
+class MTime;
+class MMcEvt;
+
+class MParList;
+
+class MHThetabarTheta : public MH
+{
+private:
+    MTime   *fTime;   //!
+    MMcEvt  *fMcEvt;  //!
+
+    TProfile fHist;
+
+public:
+    MHThetabarTheta(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TProfile *GetHist() { return &fHist; }
+    const TProfile *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHThetabarTheta, 0) //Profile histogram Thetabar vs. time
+
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mhist/MHThetabarTime.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHThetabarTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHThetabarTime.cc	(revision 9772)
@@ -0,0 +1,127 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 3/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHThetabarTime                                                          //
+//                                                                          //
+//  calculates the average Theta for different bins in time                 //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHThetabarTime.h"
+
+#include <TCanvas.h>
+
+#include "MTime.h"
+#include "MMcEvt.hxx"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHThetabarTime);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram.
+//
+MHThetabarTime::MHThetabarTime(const char *name, const char *title)
+    : fHist()
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHThetabarTime";
+    fTitle = title ? title : "1-D profile histogram Thetabar vs. time";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("t [s]");
+    fHist.SetYTitle("\\bar{\\Theta} [ \\circ]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHThetabarTime::SetupFill(const MParList *plist)
+{
+    fTime = (MTime*)plist->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << dbginf << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+       *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+       return kFALSE;
+    }
+
+    const MBinning* binstime  = (MBinning*)plist->FindObject("BinningTime");
+    if (!binstime )
+    {
+        *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(&fHist, binstime);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHThetabarTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    fHist.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+//
+Bool_t MHThetabarTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    fHist.Fill(*fTime, fMcEvt->GetTheta()*kRad2Deg, w);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mhist/MHThetabarTime.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHThetabarTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHThetabarTime.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MHThetabarTime
+#define MARS_MHThetabarTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TProfile
+#include "TProfile.h"
+#endif
+#ifndef ROOT_TH2
+#include "TH2.h"
+#endif
+
+class MTime;
+class MMcEvt;
+
+class MParList;
+
+class MHThetabarTime : public MH
+{
+private:
+    MTime  *fTime;   //!
+    MMcEvt *fMcEvt;
+
+    TProfile   fHist;
+
+public:
+    MHThetabarTime(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TProfile *GetHist() { return &fHist; }
+    const TProfile *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHThetabarTime, 0) //Profile histogram Thetabar vs. time
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHTrigLvl0.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHTrigLvl0.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHTrigLvl0.cc	(revision 9772)
@@ -0,0 +1,234 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo 06/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHTrigLvl0
+//
+// This is intended to be a sort of "level 0 trigger display". What it really
+// does is to store the number of events of a data file in which each pixel 
+// has gone above a given threshold (fPixelThreshold) which is chosen when
+// calling the constructor. Displaying a camera view with these values can
+// help identify noisy pixels. See the macro pixfixrate.C to see an example
+// of its use. Many things are to be fixed. Only inner pixels are shown now
+// (which are anyhow those involved in the trigger), and the camera geometry
+// (number of pixels, and how many inner ones) is not yet read from the input 
+// file. 
+// The "pedestal" we are using is just the signal in the first ADC slice 
+// (seems reasonable from the inspection of the available test data files).
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHTrigLvl0.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+#include "MCamDisplay.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MHTrigLvl0);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Reset all pixels to 0 and reset fEntries to 0.
+//
+void MHTrigLvl0::Clear()
+{
+    fSum.Reset();
+    for (int i=0; i<577; i++)
+    {
+        fSum.AddPixel(i, 0, 0);
+        fSum[i].SetPixelUnused();
+    }
+    fSum.FixSize();
+    fEntries = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task.
+// Resets the sum histogram
+//
+MHTrigLvl0::MHTrigLvl0(const Float_t pixelthreshold, 
+		       const char *name, const char *title)
+    : fCam(NULL), fRawEvt(NULL), fDispl(NULL)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHTrigLvl0";
+    fTitle = title ? title : "Number of hits above per pixel";
+    fPixelThreshold = pixelthreshold;
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHTrigLvl0::~MHTrigLvl0()
+{
+    if (fDispl)
+        delete fDispl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MRawEvtData) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+//
+Bool_t MHTrigLvl0::SetupFill(const MParList *plist)
+{
+    fRawEvt = (MRawEvtData*)plist->FindObject("MRawEvtData");
+    if (!fRawEvt)
+    {
+        *fLog << dbginf << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fCam)
+        *fLog << warn << GetDescriptor() << ": No MGeomCam found." << endl;
+
+    Clear();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCerPhotEvt-Container.
+//
+Bool_t MHTrigLvl0::Fill(const MParContainer *par, const Stat_t w)
+{
+    MRawEvtData *rawevt = par ? (MRawEvtData*) par : fRawEvt;
+    if (!rawevt)
+    {
+        *fLog << err << dbginf << "No MRawEvtData found..." << endl;
+        return kFALSE;
+    }
+
+    MRawEvtPixelIter pixel(rawevt);
+
+    while(pixel.Next())
+    {
+      const UInt_t pixid = pixel.GetPixelId();
+
+      // FIXME: number of inner pixels should be read from file
+      if (pixid > 396)
+	break;
+      if (pixid == 0)
+	continue;
+
+      fSum[pixid].SetPixelUsed();
+
+      //
+      // FIXME: we now use as "pedestal" the value of the first ADC slice!
+      //
+      Float_t baseline = rawevt->GetNumHiGainSamples() *
+	pixel.GetHiGainSamples()[0];
+
+      Float_t pixel_signal = pixel.GetSumHiGainSamples() - baseline;
+
+      Float_t pixel_is_on = ( pixel_signal > fPixelThreshold)? 1. : 0.;
+
+      fSum[pixid].AddNumPhotons(pixel_is_on);
+    }
+
+    fEntries++;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set to Unused outer pixels.
+//
+Bool_t MHTrigLvl0::Finalize()
+{
+  //
+  // Show only pixels in the inner region of the camera:
+  // (otherwise, problem with the too different ranges) 
+  //
+  for (Int_t i=0; i<577; i++)
+    // FIXME: read number of total and inner pixels from file
+    {
+      if (i > 396)
+	fSum[i].SetPixelUnused();
+    }
+
+  //  fSum.Scale(fEntries); Now disabled, scale was not readable otherwise.
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the present 'fill status'
+//
+void MHTrigLvl0::Draw(Option_t *)
+{
+    if (!fCam)
+    {
+        *fLog << warn << "WARNING - Cannot draw " << GetDescriptor() << ": No Camera Geometry available." << endl;
+        return;
+    }
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this, 750, 600);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+}
+
+// --------------------------------------------------------------------------
+//
+// If a camera display is not yet assigned, assign a new one.
+//
+void MHTrigLvl0::Paint(Option_t *option)
+{
+    if (!fCam)
+    {
+        *fLog << warn << "WARNING - Cannot paint " << GetDescriptor() << ": No Camera Geometry available." << endl;
+        return;
+    }
+
+    if (!fDispl)
+        fDispl = new MCamDisplay(fCam);
+
+    fDispl->Fill(fSum);
+    fDispl->Paint();
+}
Index: /tags/Mars-V0.9/mhist/MHTrigLvl0.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHTrigLvl0.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHTrigLvl0.h	(revision 9772)
@@ -0,0 +1,46 @@
+#ifndef MARS_MHTrigLvl0
+#define MARS_MHTrigLvl0
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MCerPhotEvt
+#include "MCerPhotEvt.h"
+#endif
+
+class TH1D;
+class MCamDisplay;
+class MRawEvtData;
+
+class MHTrigLvl0 : public MH
+{
+private:
+    MCerPhotEvt  fSum;            // storing the sum of triggers
+    Int_t        fEntries;        // number of entries in the histogram
+    MGeomCam    *fCam;            // the present geometry
+    MRawEvtData *fRawEvt;         //! ADC info of the current event
+    MCamDisplay *fDispl;          //! the camera display
+    Float_t      fPixelThreshold; // Threshold (ADC counts a.p.) to consider
+                                  // a pixel as "fired".
+
+public:
+    MHTrigLvl0(const Float_t pixelthreshold = 0, 
+	       const char *name=NULL, const char *title=NULL);
+    ~MHTrigLvl0();
+
+    void Clear();
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    const MCerPhotEvt &GetSum() const { return fSum; }
+
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *option="");
+
+    ClassDef(MHTrigLvl0, 1) // Histogram to sum level 0 triggers in all pixels
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/MHTriggerLvl0.cc
===================================================================
--- /tags/Mars-V0.9/mhist/MHTriggerLvl0.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHTriggerLvl0.cc	(revision 9772)
@@ -0,0 +1,193 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 06/2003 <mailto:moralejo@pd.infn.it>
+!   Author(s): Thomas Bretz, 06/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHTriggerLvl0
+//
+// This is intended to be a sort of "level 0 trigger display". What it
+// really does is to store the number of events of a data file in which
+// each pixel has gone above a given threshold (fPixelThreshold) which
+// is chosen when calling the constructor. Displaying a camera view with
+// these values can help identify noisy pixels. See the macro pixfixrate.C
+// to see an example of its use.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHTriggerLvl0.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MHTriggerLvl0);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task.
+// Resets the sum histogram
+//
+MHTriggerLvl0::MHTriggerLvl0(Double_t t, const char *name, const char *title)
+    : fSum(NULL), fEvt(NULL), fType(0), fThreshold(t)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHTriggerLvl0";
+    fTitle = title ? title : "Number of hits above threshold per pixel";
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHTriggerLvl0::~MHTriggerLvl0()
+{
+    if (fSum)
+        delete fSum;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MRawEvtData) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+//
+Bool_t MHTriggerLvl0::SetupFill(const MParList *plist)
+{
+    fEvt = (MCamEvent*)plist->FindObject(fNameEvt, "MCamEvent");
+    if (!fEvt)
+    {
+        if (!fNameEvt.IsNull())
+        {
+            *fLog << err << GetDescriptor() << ": No " << fNameEvt <<" [MCamEvent] available..." << endl;
+            return kFALSE;
+        }
+        *fLog << warn << GetDescriptor() << ": No MCamEvent available..." << endl;
+    }
+
+    MGeomCam *cam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << GetDescriptor() << ": No MGeomCam found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fSum)
+        delete (fSum);
+
+    const TString name = fNameEvt.IsNull() ? fName : fNameEvt;
+
+    fSum = new MHCamera(*cam, name+";avg", fTitle);
+    fSum->SetBit(MHCamera::kProfile);
+    fSum->SetYTitle("% [1]");
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCamEvent-Container.
+//
+Bool_t MHTriggerLvl0::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MCamEvent *evt = par ? dynamic_cast<const MCamEvent*>(par) : fEvt;
+    if (!evt)
+    {
+        *fLog << err << dbginf << "Got no MCamEvent as argument of Fill()..." << endl;
+        return kFALSE;
+    }
+
+    fSum->CntCamContent(*evt, fThreshold, fType);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scale by the number of events
+//
+Bool_t MHTriggerLvl0::Finalize()
+{
+    //    if (fSum->GetEntries()>0)
+    //        fSum->Scale(100);
+    return kTRUE;
+}
+
+void MHTriggerLvl0::PrintOutliers(Float_t s) const
+{
+    const Double_t mean = fSum->GetMean();
+    const Double_t rms  = fSum->GetRMS();
+
+    *fLog << all << underline << GetDescriptor() << ": Mean=" << mean << ", Rms=" << rms << endl;
+
+    for (unsigned int i=0; i<fSum->GetNumPixels(); i++)
+    {
+        if (!fSum->IsUsed(i))
+            continue;
+
+        if ((*fSum)[i+1]>mean+s*rms)
+            *fLog << "Contents of Pixel-Index #" << i << ": " << (*fSum)[i+1] << " > " << s << "*rms" << endl;
+        // if ((*fSum)[i+1]==0)
+        //     *fLog << "Contents of Pixel-Index #" << i << ": " << (*fSum)[i+1] << " == 0" << endl;
+        // if ((*fSum)[i+1]<fSum->GetMean()-s*fSum->GetRMS())
+        //     *fLog << "Contents of Pixel-Index #" << i << ": " << (*fSum)[i+1] << " < " << s << "*rms" << endl;
+    }
+}
+
+TH1 *MHTriggerLvl0::GetHistByName(const TString name)
+{
+    return fSum;
+}
+
+void MHTriggerLvl0::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(1,2);
+
+    pad->cd(1);
+    /*
+     gPad->SetBorderMode(0);
+     gPad->Divide(1,1);
+     gPad->cd(1);
+     gPad->SetBorderMode(0);
+     */
+    fSum->Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fSum->Draw("EPhist");
+}
Index: /tags/Mars-V0.9/mhist/MHTriggerLvl0.h
===================================================================
--- /tags/Mars-V0.9/mhist/MHTriggerLvl0.h	(revision 9772)
+++ /tags/Mars-V0.9/mhist/MHTriggerLvl0.h	(revision 9772)
@@ -0,0 +1,43 @@
+#ifndef MARS_MHTriggerLvl0
+#define MARS_MHTriggerLvl0
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MHCamera;
+class MCamEvent;
+
+class MHTriggerLvl0 : public MH
+{
+private:
+    MHCamera  *fSum;  // storing the sum
+    MCamEvent *fEvt;  //! the current event
+
+    TString fNameEvt;
+
+    Int_t fType;
+    Double_t fThreshold;
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+public:
+    MHTriggerLvl0(Double_t t=0, const char *name=NULL, const char *title=NULL);
+    ~MHTriggerLvl0();
+
+    void SetNameEvt(const TString name) { fNameEvt = name; }
+    void SetType(Int_t type) { fType = type; }
+    void SetThreshold(Double_t t) { fThreshold = t; }
+
+    TH1 *GetHistByName(const TString name="");
+
+    void Draw(Option_t * ="");
+
+    void PrintOutliers(Float_t s) const;
+
+    ClassDef(MHTriggerLvl0, 1) // Histogram to count how often a pixel is above threshold
+};
+
+#endif
Index: /tags/Mars-V0.9/mhist/Makefile
===================================================================
--- /tags/Mars-V0.9/mhist/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mhist/Makefile	(revision 9772)
@@ -0,0 +1,44 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Hist
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mraw -I../manalysis      \
+	   -I../mgui -I../mgeom -I../mdata -I../mfilter -I../mimage \
+           -I../mmain -I../mmc -I../mreflector -I../mpointing       \
+           -I../mastro -I../mpedestal -I../msignal -I../mbadpixels  \
+	   -I../mcalib
+
+SRCFILES = MHEvent.cc \
+	   MHCamEvent.cc \
+           MHCamEventRot.cc \
+           MHFadcPix.cc \
+           MHFadcCam.cc \
+           MHStarMap.cc \
+           MHCompProb.cc \
+           MHHadronness.cc \
+	   MHTriggerLvl0.cc \
+           MHCamera.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mhistmc/HistMcIncl.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/HistMcIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/HistMcIncl.h	(revision 9772)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mhistmc/HistMcLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/HistMcLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/HistMcLinkDef.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHMcRate+;
+#pragma link C++ class MHMcDifRate+;
+#pragma link C++ class MHMcIntRate+;
+#pragma link C++ class MHMcEfficiency+;
+#pragma link C++ class MHMcEfficiencyImpact+;
+#pragma link C++ class MHMcEfficiencyEnergy+;
+#pragma link C++ class MHMcEnergy+;
+#pragma link C++ class MHMcEnergyImpact+;
+#pragma link C++ class MHMcCollectionArea+;
+#pragma link C++ class MHMcEnergyMigration+;
+#pragma link C++ class MHMcCT1CollectionArea+;
+#pragma link C++ class MHMcTriggerLvl2+;
+#pragma link C++ class MHMcUnfoldCoeff+;
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcCT1CollectionArea.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcCT1CollectionArea.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcCT1CollectionArea.cc	(revision 9772)
@@ -0,0 +1,575 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): A. Moralejo 3/2003  <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHMcCT1CollectionArea                                                   //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHMcCT1CollectionArea.h" 
+
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MMcEvt.hxx"
+#include "MH.h"
+#include "MBinning.h"
+#include "MParList.h"
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHMcCT1CollectionArea);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Creates the three necessary histograms:
+//   - selected showers (input)
+//   - all showers (input)
+//   - collection area (result)
+//
+MHMcCT1CollectionArea::MHMcCT1CollectionArea(const char *name, const char *title) :
+    fEaxis(kLog10)
+{ 
+  //
+  //   nbins, minEnergy, maxEnergy defaults:
+  //   we set the energy range from 100 Gev to 30000 GeV (in log, 3.5 orders
+  //   of magnitude) and for each order we take 10 subdivisions --> 35 xbins
+  //   we set the theta range from 12.5 to 48 deg, with 6 bins (the latter
+  //   choice has been done to make the bin centers as close as possible to 
+  //   the actual zenith angles in the CT1 MC sample).
+  //
+
+  fName  = name  ? name  : "MHMcCT1CollectionArea";
+  fTitle = title ? title : "Collection Area vs. log10 Energy";
+
+  fHistAll = new TH2D;
+  fHistSel = new TH2D;
+  fHistCol = new TH2D;
+
+  fHistCol->SetName(fName);
+  fHistAll->SetName("AllEvents");
+  fHistSel->SetName("SelectedEvents");
+
+  fHistCol->SetTitle(fTitle);
+  fHistAll->SetTitle("All showers - Theta vs log10 Energy distribution");
+  fHistSel->SetTitle("Selected showers - Theta vs log10 Energy distribution");
+
+  fHistAll->SetDirectory(NULL);
+  fHistSel->SetDirectory(NULL);
+  fHistCol->SetDirectory(NULL);
+
+  fHistAll->SetXTitle("log10(E [GeV])");
+  fHistAll->SetYTitle("\\Theta [\\circ]");
+  fHistAll->SetZTitle("Counts");
+
+  fHistSel->SetXTitle("log10(E [GeV])");
+  fHistSel->SetYTitle("\\Theta [\\circ]");
+  fHistSel->SetZTitle("Counts");
+
+  fHistCol->SetXTitle("log10(E [GeV])");
+  fHistCol->SetYTitle("theta [deg]");
+  fHistCol->SetZTitle("A [m^{2}]");
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the three histograms
+//
+MHMcCT1CollectionArea::~MHMcCT1CollectionArea()
+{
+  delete fHistAll;
+  delete fHistSel;
+  delete fHistCol;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histograms
+//
+Bool_t MHMcCT1CollectionArea::SetupFill(const MParList *plist)
+{
+    const MBinning* binsenergy = (MBinning*)plist->FindObject("BinningE");
+    const MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta");
+
+    if (!binsenergy || !binstheta)
+    {
+        *fLog << err << dbginf << "At least one MBinning not found... aborting.";
+        *fLog << endl;
+        return kFALSE;
+    }
+
+    SetBinning(fHistAll, binsenergy, binstheta);
+    SetBinning(fHistSel, binsenergy, binstheta);
+    SetBinning(fHistCol, binsenergy, binstheta);
+
+    fHistAll->Sumw2();
+    fHistSel->Sumw2();
+    fHistCol->Sumw2();
+
+    if (fEaxis == kLinear)
+    {
+        fTitle = "Collection Area vs. Energy";
+        fHistCol->SetTitle(fTitle);
+        fHistAll->SetTitle("All showers - Theta vs Energy distribution");
+        fHistSel->SetTitle("Selected showers - Theta vs Energy distribution");
+        fHistCol->SetXTitle("E [GeV]");
+        fHistAll->SetXTitle("E [GeV]");
+        fHistSel->SetXTitle("E [GeV]");
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains the selected showers
+//
+Bool_t MHMcCT1CollectionArea::Fill(const MParContainer *par, const Stat_t w)
+{ 
+  MMcEvt &mcevt = *(MMcEvt*)par;
+
+  const Double_t E = fEaxis==kLinear ? mcevt.GetEnergy() : log10(mcevt.GetEnergy());
+
+  fHistSel->Fill(E, kRad2Deg*mcevt.GetTelescopeTheta(), w);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram with all showers
+//
+void MHMcCT1CollectionArea::DrawAll(Option_t* option)
+{
+  if (!gPad)
+    MH::MakeDefCanvas(fHistAll);
+
+  fHistAll->Draw(option);
+
+  gPad->Modified();
+  gPad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram with the selected showers only.
+//
+void MHMcCT1CollectionArea::DrawSel(Option_t* option)
+{
+  if (!gPad)
+    MH::MakeDefCanvas(fHistSel);
+
+  fHistSel->Draw(option);
+
+  gPad->Modified();
+  gPad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the histogram into it.
+// Be careful: The histogram belongs to this object and won't get deleted
+// together with the canvas.
+//
+TObject *MHMcCT1CollectionArea::DrawClone(Option_t* option) const
+{
+  TCanvas &c = *MakeDefCanvas("CollArea", "Collection area plots", 600, 600);
+  c.Divide(2,2);
+
+  //
+  // This is necessary to get the expected behaviour of DrawClone
+  //
+  gROOT->SetSelectedPad(NULL);
+
+  c.cd(1);
+  if (fEaxis == kLinear)
+    gPad->SetLogx();
+  fHistCol->SetDirectory(NULL);
+  fHistCol->DrawCopy(option);
+
+  c.cd(2);
+  if (fEaxis == kLinear)
+    gPad->SetLogx();
+  fHistSel->SetDirectory(NULL);
+  fHistSel->DrawCopy(option);
+
+  c.cd(3);
+  if (fEaxis == kLinear)
+    gPad->SetLogx();
+  fHistAll->SetDirectory(NULL);
+  fHistAll->DrawCopy(option);
+
+
+  c.Modified();
+  c.Update();
+
+  return &c;
+}
+
+void MHMcCT1CollectionArea::Draw(Option_t* option)
+{
+  if (!gPad)
+    MH::MakeDefCanvas(fHistCol);
+
+  fHistCol->Draw(option);
+
+  gPad->Modified();
+  gPad->Update();
+}
+
+//
+//  Calculate the Efficiency (collection area) for the CT1 MC sample
+//  and set the 'ReadyToSave' flag
+//
+void MHMcCT1CollectionArea::CalcEfficiency()
+{
+  //
+  // Here we estimate the total number of showers in each energy bin
+  // from the known the energy range and spectral index of the generated 
+  // showers. This procedure is intended for the CT1 MC files. The total 
+  // number of generated events, collection area, spectral index etc will be 
+  // set here by hand, so make sure that the MC sample you are using is the 
+  // right one (check all these quantities in your files and compare with
+  // what is written below. In some theta bins, there are two different 
+  // productions, with different energy limits but with the same spectral 
+  // slope. We account for this when calculating the original number of 
+  // events in each energy bin.
+  //
+  // The theta angle with which the MC data (from D. Kranich) were produced 
+  // is not exactly the center of the theta bins we are using (the bin limits 
+  // should be 0.0, 17.5, 23.5, 29.5, 35.5, 42., 50.). The theta variable in 
+  // the MC root file has nevertheless been changed (W.Wittek) to correspond 
+  // to the centers of these bins. Only in the first bin is the difference big:
+  // the data were produced at theta = 15 degrees, whreas the bin center is at
+  // 8.75 degrees. Howeverm at such low z.a. the shower characteristics change 
+  // very slowly with theta.
+  //
+  //
+  //
+  // Only for the binning taken from D. Kranich :
+  //
+
+  for (Int_t thetabin = 1; thetabin <= fHistAll->GetNbinsY(); thetabin++)
+    {
+      // This theta is not exactly the one of the MC events, just about 
+      // the same (bins have been selected so):
+
+      Float_t theta = fHistAll->GetYaxis()->GetBinCenter(thetabin);
+      Float_t thetalo = fHistAll->GetYaxis()->GetBinLowEdge(thetabin);
+      Float_t thetahi = fHistAll->GetYaxis()->GetBinLowEdge(thetabin+1);
+
+      Float_t emin[4];       // Minimum energy in MC sample
+      Float_t emax[4];       // Maximum energy in MC sample
+      Float_t index[4];      // Spectral index
+      Float_t numevts[4];    // Number of events
+      Float_t multfactor[4]; // Factor by which the original number of events in an MC 
+                             // sample has been multiplied to account for the differences
+                             // in the generation areas of the various samples.
+      Float_t rmax;          // Maximum impact parameter range (on ground up to 45 degrees, 
+                             // on a plane perpendicular to Shower axis for 55 and 65 deg).
+
+      memset(emin,    0, 4*sizeof(Float_t));
+      memset(emax,    0, 4*sizeof(Float_t));
+      memset(index,   0, 4*sizeof(Float_t));
+      memset(numevts, 0, 4*sizeof(Float_t));
+      rmax = 0.;
+
+      multfactor[0] = 1.;
+      multfactor[1] = 1.;
+      multfactor[2] = 1.;
+      multfactor[3] = 1.;
+
+      //
+      // rmin and rmax are the minimum and maximum values of the impact 
+      // parameter of the shower on the ground (horizontal plane).
+      //
+
+      Int_t num_MC_samples = 0;
+
+      //if (theta > 8 && theta < 9)   // 8.75 deg
+      if (  thetalo<8.75  && 8.75<thetahi)   // 8.75 deg
+	{
+	  emin[0] = 300.;
+	  emax[0] = 400.;  // Energies in GeV.
+	  index[0] = 1.5;
+	  numevts[0] = 4000.;
+
+	  emin[1] = 400.;
+	  emax[1] = 30000.;
+	  index[1] = 1.5;
+	  numevts[1] = 25740.;
+
+	  rmax = 250.;     //meters
+	  num_MC_samples = 2;
+	}
+      //else if (theta > 20 && theta < 21)  // 20.5 deg 
+      else if (  thetalo<20.5  && 20.5<thetahi)   // 20.5 deg
+	{
+	  emin[0] = 300.;
+	  emax[0] = 400.;  // Energies in GeV.
+	  index[0] = 1.5;
+	  numevts[0] = 6611.;
+
+	  emin[1] = 400.;
+	  emax[1] = 30000.;
+	  index[1] = 1.5;
+	  numevts[1] = 24448.;
+
+	  rmax = 263.;
+	  num_MC_samples = 2;
+	}
+      //else if (theta > 26 && theta < 27)  // 26.5 degrees
+      else if (  thetalo<26.5  && 26.5<thetahi)   // 26.5 deg
+	{
+	  emin[0] = 300.;
+	  emax[0] = 400.;  // Energies in GeV.
+	  index[0] = 1.5;
+	  numevts[0] = 4000.;
+
+	  emin[1] = 400.;
+	  emax[1] = 30000.;
+	  index[1] = 1.5;
+	  numevts[1] = 26316.;
+
+	  rmax = 290.;     //meters
+	  num_MC_samples = 2;
+	}
+      //else if (theta > 32 && theta < 33)  // 32.5 degrees
+      else if (  thetalo<32.5  && 32.5<thetahi)   // 32.5 deg
+	{
+	  emin[0] = 300.;
+	  emax[0] = 30000.;  // Energies in GeV.
+	  index[0] = 1.5;
+	  numevts[0] = 33646.;
+
+	  rmax = 350.;     //meters
+	  num_MC_samples = 1;
+	}
+      //else if (theta > 38 && theta < 39)  // 38.75 degrees
+      else if (  thetalo<38.75  && 38.75<thetahi)   // 38.75 deg
+	{
+	  emin[0] = 300.;
+	  emax[0] = 30000.;  // Energies in GeV.
+	  index[0] = 1.5;
+	  numevts[0] = 38415.;
+
+	  rmax = 380.;     //meters
+	  num_MC_samples = 1;
+	}
+      //else if (theta > 45 && theta < 47)  // 46 degrees
+      else if (  thetalo<46  && 46<thetahi)   // 46 deg
+	{
+	  emin[0] = 300.;
+	  emax[0] = 50000.;  // Energies in GeV.
+	  index[0] = 1.5;
+	  numevts[0] = 30197.;
+
+	  rmax = 565.;     //meters
+	  num_MC_samples = 1;
+	}
+      //else if (theta > 54 && theta < 56)  // 55 degrees
+      else if (  thetalo<55  && 55<thetahi)   // 55 deg
+	{
+	  //
+	  // The value of numevts in the first sample (below) has been
+	  // changed to simplify calculations. We have multiplied it
+	  // times 1.2808997 to convert it to the number it would be if 
+	  // the generation area was equal to that of the other samples 
+	  // at 55 degrees (pi*600**2 m2). This has to be taken into account 
+	  // in the error in the number of events.
+	  //
+
+	  emin[0] = 500.;
+	  emax[0] = 50000.;  // Energies in GeV.
+	  index[0] = 1.5;
+	  numevts[0] = 3298.;
+	  multfactor[0] = 1.2808997;
+
+	  emin[1] = 1500.;
+	  emax[1] = 50000.;  // Energies in GeV.
+	  index[1] = 1.5;
+	  numevts[1] = 22229.;
+
+	  emin[2] = 1500.;
+	  emax[2] = 50000.;  // Energies in GeV.
+	  index[2] = 1.7;
+	  numevts[2] = 7553.;
+
+	  rmax = 600;     //meters
+	  num_MC_samples = 3;
+	}
+
+      //else if (theta > 64 && theta < 66)  // 65 degrees
+      else if (  thetalo<65  && 65<thetahi)   // 65 deg
+	{
+	  emin[0] = 2000.;
+	  emax[0] = 50000.;  // Energies in GeV.
+	  index[0] = 1.5;
+	  numevts[0] = 16310.;
+
+	  emin[1] = 2000.;
+	  emax[1] = 50000.;  // Energies in GeV.
+	  index[1] = 1.7;
+	  numevts[1] = 3000.;
+
+	  //
+	  // The value of numevts in the next two samples (below) has been
+	  // changed to simplify calculations. We have converted them to the
+	  // number it would be if the generation area was equal to that of 
+	  // the first two samples at 65 degrees (pi*800**2 m2) (four times 
+	  // as many, since the original maximum impact parameter was 400
+	  // instead of 800. This is taken into account in the error too.
+	  //
+
+	  emin[2] = 5000.;
+	  emax[2] = 50000.;  // Energies in GeV.
+	  index[2] = 1.5;
+	  numevts[2] = 56584.;
+	  multfactor[2] = 4;
+
+	  emin[3] = 5000.;
+	  emax[3] = 50000.;  // Energies in GeV.
+	  index[3] = 1.7;
+	  numevts[3] = 11464;
+	  multfactor[3] = 4;
+
+	  rmax = 800;     // meters
+	  num_MC_samples = 4;
+	}
+
+
+      for (Int_t i=1; i <= fHistAll->GetNbinsX(); i++)
+	{
+	  Float_t e1;
+	  Float_t e2;
+
+	  if (fEaxis == kLog10)
+	    {
+	      e1 = pow(10.,fHistAll->GetXaxis()->GetBinLowEdge(i));
+	      e2 = pow(10.,fHistAll->GetXaxis()->GetBinLowEdge(i+1));
+	    }
+	  else
+	    {
+	      e1 = fHistAll->GetXaxis()->GetBinLowEdge(i);
+	      e2 = fHistAll->GetXaxis()->GetBinLowEdge(i+1);
+	    }
+
+	  Float_t events = 0.;
+	  Float_t errevents = 0.;
+
+	  for (Int_t sample = 0; sample < num_MC_samples; sample++)
+	    {
+	      Float_t expo = 1.-index[sample];
+	      Float_t k = numevts[sample] / (pow(emax[sample],expo) - pow(emin[sample],expo));
+
+	      if (e2 < emin[sample] || e1 > emax[sample])
+		continue;
+
+	      if (emin[sample] > e1) 
+		e1 = emin[sample];
+
+	      if (emax[sample] < e2) 
+		e2 = emax[sample];
+
+	      events += k * (pow(e2, expo) - pow(e1, expo));
+	      errevents += multfactor[sample] * events;
+	    }
+
+	  errevents= sqrt(errevents);
+
+	  fHistAll->SetBinContent(i, thetabin, events);
+	  fHistAll->SetBinError(i, thetabin, errevents);
+	}
+
+      // -----------------------------------------------------------
+
+      const Float_t dr = TMath::Pi() * rmax * rmax;
+
+      for (Int_t ix = 1; ix <= fHistAll->GetNbinsX(); ix++)
+	{
+	  const Float_t Na = fHistAll->GetBinContent(ix,thetabin);
+
+	  if (Na <= 0)
+	    {
+	      //
+	      // If energy is large, this case means that no or very few events
+	      // were generated at this energy bin. In this case we assign it 
+	      // the effective area of the bin below it in energy. If energy is
+	      // below 1E4, it means that no events triggered -> eff area = 0
+	      //
+	      // NOW DISABLED: because collection area after analysis does not
+	      // saturate at high E!
+	      //
+
+	      /*
+	      if (fHistSel->GetXaxis()->GetBinLowEdge(ix) > 4.)
+		{
+		  fHistCol->SetBinContent(ix, thetabin, fHistCol->GetBinContent(ix-1, thetabin));
+		  fHistCol->SetBinError(ix, thetabin, fHistCol->GetBinError(ix-1, thetabin));
+		}
+	      */
+	      continue;
+	    }
+
+	  const Float_t Ns = fHistSel->GetBinContent(ix,thetabin);
+
+	  // Since Na is an estimate of the total number of showers generated
+	  // in the energy bin, it may happen that Ns (triggered showers) is
+	  // larger than Na. In that case, the bin is skipped:
+
+	  if (Na < Ns)
+	    continue;
+
+	  const Double_t eff = Ns/Na;
+	  const Double_t efferr = sqrt((1.-eff)*Ns)/Na;
+
+	  //
+	  // Now we get the total area, perpendicular to the observation direction
+	  // in which the events were generated (correct for cos theta):
+	  //
+
+	  Float_t area = dr;
+
+	  if (theta < 50)
+	    area *= cos(theta*TMath::Pi()/180.);
+
+	  // Above 50 degrees MC was generated with Corsika 6.xx, and the cores
+	  // were distributed on a circle perpendicular to the observation direction, 
+	  // and not on ground, hence the correction for cos(theta) is not necessary.
+	  //
+
+
+	  fHistCol->SetBinContent(ix, thetabin, eff*area);
+	  fHistCol->SetBinError(ix, thetabin, efferr*area);
+
+	}
+    }
+
+  SetReadyToSave();
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcCT1CollectionArea.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcCT1CollectionArea.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcCT1CollectionArea.h	(revision 9772)
@@ -0,0 +1,53 @@
+#ifndef MARS_MHMcCT1CollectionArea
+#define MARS_MHMcCT1CollectionArea
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH2D;
+
+class MHMcCT1CollectionArea : public MH
+{
+public:
+    enum FillType_t {
+        kLog10,
+        kLinear
+    };
+
+private:
+    TH2D *fHistAll; //  all simulated showers
+    TH2D *fHistSel; //  the selected showers
+    TH2D *fHistCol; //  the collection area
+
+    FillType_t fEaxis;
+
+public:
+    MHMcCT1CollectionArea(const char *name=NULL, const char *title=NULL);
+    ~MHMcCT1CollectionArea();
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    void DrawAll(Option_t *option="");
+    void DrawSel(Option_t *option="");
+
+    void SetEaxis(FillType_t x) { fEaxis = x; }
+
+    const TH2D *GetHist() const { return fHistCol; }
+    const TH2D *GetHAll() const { return fHistAll; }
+    const TH2D *GetHSel() const { return fHistSel; }
+
+    void Draw(Option_t *option="");
+    TObject *DrawClone(Option_t *option="") const;
+
+    void CalcEfficiency();
+
+    ClassDef(MHMcCT1CollectionArea, 1)  // Data Container to calculate Collection Area
+};
+
+#endif
+
+
+
+
Index: /tags/Mars-V0.9/mhistmc/MHMcCollectionArea.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcCollectionArea.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcCollectionArea.cc	(revision 9772)
@@ -0,0 +1,392 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+   !   Author(s): Harald Kornmayer 1/2001
+   !   Author(s): Abelardo Moralejo 2/2005 <mailto:moralejo@pd.infn.it>
+   !
+   !   Copyright: MAGIC Software Development, 2000-2005
+   !
+   !
+   \* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHMcCollectionArea                                                      //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHMcCollectionArea.h" 
+
+#include <TH2.h>
+#include <TH3.h>
+#include <TCanvas.h>
+#include <THStack.h>
+#include <TLegend.h>
+#include <TArrayD.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MHMcCollectionArea);
+
+using namespace std;
+
+////////////////////////////////////////////////////////////////////////////////
+//
+//  Constructor. Creates the three necessary histograms:
+//   - selected showers (input)
+//   - all showers (input)
+//   - collection area (result)
+//
+MHMcCollectionArea::MHMcCollectionArea(const char *name, const char *title):
+  fImpactBins(50), fImpactMax(500.), fMinEvents(10)
+{ 
+  fName  = name  ? name  : "MHMcCollectionArea";
+  fTitle = title ? title : "Collection Area vs. Theta vs. Energy";
+
+  //
+  //   Initialize the histogram for the distribution 
+  //   Theta vs impact parameter vs E (z, y, x)
+  //
+  //   As default we set the energy range from 2 Gev to 20000 GeV (in log 4 
+  //   orders of magnitude) and for each order we take 25 subdivisions --> 
+  //   100 xbins. We set the radius range from 0 m to 500 m with 10 m bin --> 
+  //   50 ybins. We make bins equally spaced in cos(theta)
+  //
+  //   The coarse binning (of fHistColCoarse) is not set by default, the
+  //   PreProcess of mmc/MMcCollectionAreaCalc will do it with the binnings
+  //   found in the parameter list.
+  //
+
+  MBinning binsx;
+  MBinning binsy;
+  MBinning binsz;
+
+  Int_t nbins = 32;
+  TArrayD edges(nbins+1);
+    
+  edges[0] = 0;
+    
+  for(int i = 0; i < nbins; i++)
+    {
+      Double_t x = 1 - i*0.01;  // x = cos(theta) 
+      edges[i+1] = acos(x-0.005)*kRad2Deg;
+    }
+
+  binsx.SetEdgesLog(100, 2., 20000);               // Energy [GeV]
+  binsy.SetEdges   (fImpactBins, 0, fImpactMax);   // Impact parameter [m]
+  binsz.SetEdges   (edges);                        // Theta [deg]
+
+  fHistAll = new TH3D();
+  fHistSel = new TH3D();
+  fHistCol = new TH2D();
+  fHistColCoarse = new TH2D();
+ 
+  MH::SetBinning(fHistAll, &binsx, &binsy, &binsz);
+  MH::SetBinning(fHistSel, &binsx, &binsy, &binsz);
+
+  fHistColCoarse->SetName("CollectionArea");
+  fHistCol->SetName("CollAreaFineBins");
+  fHistAll->SetName("AllEvents");
+  fHistSel->SetName("SelectedEvents");
+
+  fHistAll->Sumw2();
+  fHistSel->Sumw2();
+
+  fHistColCoarse->SetTitle(fTitle);
+  fHistCol->SetTitle(fTitle);
+  fHistAll->SetTitle("All showers - Theta vs Radius vs Energy");
+  fHistSel->SetTitle("Selected showers - Theta vs Radius vs Energy");
+
+  fHistAll->SetDirectory(NULL);
+  fHistSel->SetDirectory(NULL);
+  fHistCol->SetDirectory(NULL);
+  fHistColCoarse->SetDirectory(NULL);
+
+  fHistAll->UseCurrentStyle();
+  fHistSel->UseCurrentStyle();
+  fHistCol->UseCurrentStyle();
+  fHistColCoarse->UseCurrentStyle();
+
+  fHistAll->SetXTitle("E [GeV]");
+  fHistAll->SetYTitle("r [m]"); 
+  fHistAll->SetZTitle("\\theta [\\circ]");
+
+  fHistSel->SetXTitle("E [GeV]");
+  fHistSel->SetYTitle("r [m]");
+  fHistSel->SetZTitle("\\theta [\\circ]");
+
+  fHistCol->SetXTitle("E [GeV]");
+  fHistCol->SetYTitle("\\theta [\\circ]");
+  fHistCol->SetZTitle("A [m^{2}]");
+
+  fHistColCoarse->SetXTitle("E [GeV]");
+  fHistColCoarse->SetYTitle("\\theta [\\circ]");
+  fHistColCoarse->SetZTitle("A [m^{2}]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the three histograms
+//
+MHMcCollectionArea::~MHMcCollectionArea()
+{
+  delete fHistAll;
+  delete fHistSel;
+  delete fHistCol;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the (fine) binnings of histograms fHistAll, fHistSel used in the 
+// calculations. We do not need to change impact parameter binning.
+//
+void MHMcCollectionArea::SetBinnings(const MBinning &binsEnergy, 
+				     const MBinning &binsTheta)
+{
+  MBinning binsImpact;
+  binsImpact.SetEdges(fImpactBins, 0., fImpactMax);
+
+  MH::SetBinning(fHistAll, &binsEnergy, &binsImpact, &binsTheta);
+  MH::SetBinning(fHistSel, &binsEnergy, &binsImpact, &binsTheta);
+
+  fHistAll->Sumw2();
+  fHistSel->Sumw2();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings of the histogram fHistColCoarse, the effective areas
+// in the coarse bins used in the analysis.
+//
+//
+void MHMcCollectionArea::SetCoarseBinnings(const MBinning &binsEnergy, 
+					   const MBinning &binsTheta)
+{
+  MH::SetBinning(fHistColCoarse, &binsEnergy, &binsTheta);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains all showers
+//
+void MHMcCollectionArea::FillAll(Double_t energy, Double_t radius, Double_t theta)
+{
+  fHistAll->Fill(energy, radius, theta);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains the selected showers
+//
+void MHMcCollectionArea::FillSel(Double_t energy, Double_t radius, Double_t theta)
+{
+  fHistSel->Fill(energy, radius, theta);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw
+//
+void MHMcCollectionArea::Draw(Option_t* option)
+{
+  //
+  // Lego plot
+  //
+  TCanvas *c1 = new TCanvas();  
+  c1->SetLogx();
+  c1->SetLogz();
+  c1->SetGridx();
+  c1->SetGridy();
+
+  fHistCol->Draw("lego2");
+    
+  //
+  // Averagye Aeff
+  //
+  TCanvas *c2 = new TCanvas();
+  c2->SetLogx();
+  c2->SetLogy();
+  c2->SetGridx();
+  c2->SetGridy();
+
+  TH1D* harea = fHistCol->ProjectionX();
+  harea->Draw("e1");
+  
+  //
+  // Plot the Aeff for the different theta
+  //
+  TCanvas *c3 = new TCanvas();
+  c3->SetLogx();
+  c3->SetLogy();
+  c3->SetGridx();
+  c3->SetGridy();
+
+  TLegend * leg = new TLegend(0.73,0.65,0.89,0.89);
+   
+  TAxis* yaxis = fHistCol->GetYaxis();
+  const Int_t nbiny = fHistCol->GetYaxis()->GetNbins();
+    
+  THStack* hs = new THStack("aa","aa");
+
+  hs->Add(harea,"e1");
+  leg->AddEntry(harea,"All","l");
+
+  for(Int_t iy=1; iy<=nbiny; iy++)
+    {
+
+      TH1D* h1=  fHistCol->ProjectionX(Form("%d",iy),iy,iy);
+
+      if(h1->GetEntries()==0)
+	continue;
+
+      cout <<h1->GetEntries() << endl;
+
+      leg->AddEntry(h1,Form("\\theta = %.0f",yaxis->GetBinCenter(iy)),"l");
+      h1->SetLineColor(iy);
+      hs->Add(h1,"e1");
+    }
+  hs->SetMinimum(1);
+  
+  hs->Draw("nostack");
+  leg->Draw();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the collection area and set the 'ReadyToSave' flag
+// We first calculate the area in fine energy bins, and then do a
+// weighted mean to obtain the area in coarse bins. The weights in
+// the coarse bins are intended to account for the effect of the 
+// energy spectrum in the effective area itself. The weights 
+// are taken from the tentative differential spectrum dN_gam/dE given 
+// through the function "spectrum". If no such function is supplied, 
+// then no weights are applied (and hence the spectrum will be as a 
+// flat spectrum in dN_gam/dE). Of course we have a "generated" MC
+// spectrum, but within each fine bin the differences in spectrum 
+// should not change the result (if bins are fine enough). With no 
+// supplied tentative spectrum, each fine bin is weighted equally in
+// calculating the area in the coarse bin, and so it is like having a 
+// flat spectrum.
+//
+// You can run this Calc procedure on an already existing 
+// MHMcCollectionArea object, as long as it is filled.
+//
+void MHMcCollectionArea::Calc(TF1 *spectrum)
+{
+  // Search last impact parameter bin containing events
+  // FIXME: this should be done independently for each theta angle.
+  //
+  TH1D &himpact = *(TH1D*)fHistAll->Project3D("y");
+
+  Int_t impbin;
+  for (impbin = himpact.GetNbinsX(); impbin > 0; impbin--)
+    if (himpact.GetBinContent(impbin)>0)
+      break;
+
+  Float_t max_radius = himpact.GetBinLowEdge(impbin);
+
+  Float_t total_area = TMath::Pi()*max_radius*max_radius;
+
+  for (Int_t ix = 1; ix <= fHistAll->GetNbinsX(); ix++)
+    for (Int_t iz = 1; iz <= fHistAll->GetNbinsZ(); iz++)
+      {
+	fHistAll->SetBinContent(ix, impbin, iz, 0.);
+	fHistSel->SetBinContent(ix, impbin, iz, 0.);
+	fHistAll->SetBinError(ix, impbin, iz, 0.);
+	fHistSel->SetBinError(ix, impbin, iz, 0.);
+      }
+
+  TH2D &histsel = *(TH2D*)fHistSel->Project3D("zx,e");
+  TH2D &histall = *(TH2D*)fHistAll->Project3D("zx,e"); 
+  // "e" option means that errors are computed!
+
+
+  TAxis &xaxis = *histsel.GetXaxis();
+  TAxis &yaxis = *histsel.GetYaxis();
+  MH::SetBinning(fHistCol, &xaxis, &yaxis);
+
+  cout << "Total considered MC area = pi * " << max_radius 
+       << "^2 square meters" << endl;
+
+  fHistCol->Sumw2();
+  fHistCol->Divide(&histsel, &histall, total_area, 1., "b");
+
+  //
+  // Now get the effective area in the selected coarse bins. Weight
+  // the values in the small bins according the supplied tentative
+  // spectrum, if it has been supplied as argument of Calc.
+  //
+
+  for (Int_t ibin = 1; ibin <= fHistColCoarse->GetNbinsX(); ibin++)
+    for (Int_t jbin = 1; jbin <= fHistColCoarse->GetNbinsY(); jbin++)
+      {
+	Float_t maxenergy = fHistColCoarse->GetXaxis()->GetBinUpEdge(ibin);
+	Float_t minenergy = fHistColCoarse->GetXaxis()->GetBinLowEdge(ibin);
+
+	Float_t maxtheta = fHistColCoarse->GetYaxis()->GetBinUpEdge(jbin);
+	Float_t mintheta = fHistColCoarse->GetYaxis()->GetBinLowEdge(jbin);
+
+	// Fine bins ranges covered by the coarse bin ibin, jbin:
+	Int_t ibin2max = fHistCol->GetXaxis()->FindBin(maxenergy);
+	Int_t ibin2min = fHistCol->GetXaxis()->FindBin(minenergy);
+
+	Int_t jbin2max = fHistCol->GetYaxis()->FindBin(maxtheta);
+	Int_t jbin2min = fHistCol->GetYaxis()->FindBin(mintheta);
+
+	Float_t area = 0.;
+	Float_t errarea = 0.;
+	Float_t norm = 0;
+
+	for (Int_t ibin2 = ibin2min; ibin2 <= ibin2max; ibin2++)
+	  {
+  	    Float_t weight = spectrum? spectrum->
+  	      Eval(fHistCol->GetXaxis()->GetBinCenter(ibin2)) : 1.;
+
+	    for (Int_t jbin2 = jbin2min; jbin2 <= jbin2max; jbin2++)
+	      {
+		// Skip bins with too few produced MC events
+		if (histall.GetBinContent(ibin2,jbin2) < fMinEvents)
+		  continue;
+
+		area += weight * fHistCol->GetBinContent(ibin2,jbin2);
+		norm += weight;
+		errarea += pow(weight * fHistCol->
+			       GetBinError(ibin2,jbin2), 2.);
+	      }
+	  }
+	if (norm > 0.)
+	  {
+	    area /= norm;
+	    errarea = sqrt(errarea)/norm;
+	  }
+
+	fHistColCoarse->SetBinContent(ibin, jbin, area);
+	fHistColCoarse->SetBinError(ibin, jbin, errarea);
+      }
+
+  SetReadyToSave();
+}
+     
+
Index: /tags/Mars-V0.9/mhistmc/MHMcCollectionArea.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcCollectionArea.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcCollectionArea.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MHMcCollectionArea
+#define MARS_MHMcCollectionArea
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#include "MBinning.h"
+#include "TF1.h"
+
+class TH1D;
+class TH2D;
+class TH3D;
+
+//
+// Version 2:
+//
+// Now all histograms are saved with the object. Added members
+// fImpactMax, fImpactBins, fMinEvents
+//
+
+class MHMcCollectionArea : public MH
+{
+private:
+  TH3D *fHistAll;        // all simulated showers
+  TH3D *fHistSel;        // the selected showers
+  TH2D *fHistCol;        // the collection area in fine bins
+  TH2D *fHistColCoarse;  // the coll. area in coarse bins 
+
+  Int_t   fImpactBins;   // number of bins in i.p. for histograms
+  Float_t fImpactMax;    // [m] Maximum impact parameter for histograms
+
+  Int_t   fMinEvents;    
+  // minimum number of events in each of the "fine bins" of fHistAll 
+  // so that the bin is used in the averaging for the coarse bins. 
+
+  void Calc(TH3D &hsel, TH3D &hall);
+
+public:
+  MHMcCollectionArea(const char *name=NULL, const char *title=NULL);
+  ~MHMcCollectionArea();
+
+  void FillAll(Double_t energy, Double_t radius, Double_t theta);
+  void FillSel(Double_t energy, Double_t radius, Double_t theta);
+
+  const TH2D *GetHist()       const { return fHistCol; }
+  const TH2D *GetHistCoarse() const { return fHistColCoarse; }
+  const TH3D *GetHistAll()    const { return fHistAll; }
+  const TH3D *GetHistSel()    const { return fHistSel; }
+
+  void SetBinnings(const MBinning &binsEnergy, const MBinning &binsTheta);
+  void SetCoarseBinnings(const MBinning &binsEnergy, const MBinning &binsTheta);
+
+  void Draw(Option_t *option="");
+
+  void Calc(TF1 *spectrum);
+
+  ClassDef(MHMcCollectionArea, 2)  // Data Container to store Collection Area
+    };
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcDifRate.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcDifRate.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcDifRate.cc	(revision 9772)
@@ -0,0 +1,158 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 05/2001 <mailto:jlopez@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHMcDifRate
+//
+// This class holds the information (histogram and fit function)
+// about the energy threshold for a particular trigger condition.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHMcDifRate.h" 
+
+#include <math.h>
+
+#include <TCanvas.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MHMcCollectionArea.h"
+
+ClassImp(MHMcDifRate);
+
+// -------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MHMcDifRate::MHMcDifRate(const char *name, const char *title)
+    : fHist()
+{
+    fName  = name  ? name  : "MHMcDifRate";
+    fTitle = title ? title : "Differential Trigger Rate";
+
+    //  - we initialize the histogram
+    //  - we have to give diferent names for the diferent histograms because
+    //    root don't allow us to have diferent histograms with the same name
+
+    fHist.SetName(fName);
+    fHist.SetTitle(fTitle);
+
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("dR/dE [Hz/GeV]");
+}
+
+void MHMcDifRate::SetName(const char *name)
+{
+    fName = name;
+    fHist.SetName(name);
+    fHist.SetDirectory(NULL);
+}
+
+void MHMcDifRate::SetTitle(const char *title)
+{
+    fTitle = title;
+    fHist.SetTitle(title);
+}
+
+// ------------------------------------------------------------------------
+// 
+// Drawing function. It creates its own canvas.
+//
+void MHMcDifRate::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->SetLogx();
+
+    fHist.Draw(option);
+
+    pad->Modified();
+    pad->Update();
+}
+/*
+void MHMcDifRate::Calc(const TH2D &hsel, const TH2D &hall)
+{
+    //
+    // Set the binning from the two axis of one of the two histograms
+    //
+    MH::SetBinning(&fHist, ((TH2D&)hsel).GetXaxis(), ((TH2D&)hsel).GetYaxis());
+
+    //
+    // This is necessary to initialize thze error calculation correctly
+    // (Nothing important: The histogram set the size of its internal
+    // array storing the errors to the correct size)
+    //
+    fHist.Sumw2();
+
+    //
+    // Calculate the efficiency by dividing the number of selected
+    // (eg. triggered) showers by the number of all showers per bin.
+    // Both histograms are weighted with weight 1, and for the error
+    // calculation we assume a binomial error calculation.
+    //
+    fHist.Divide((TH2D*)&hsel, (TH2D*)&hall, 1, 1, "B");
+
+    SetReadyToSave();
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the DifRate and set the 'ReadyToSave' flag.
+//  The DifRate is calculated as the number of selected showers
+//  (eg. triggered ones) divided by the number of all showers.
+//  For error calculation Binomial errors are computed.
+//
+void MHMcDifRate::Calc(const MHMcCollectionArea &cola, const TF1 &spect)
+{
+    /*const*/ TH1D &hcol = (TH1D&)*cola.GetHist();
+
+    fHist.Reset();
+
+    //
+    // Set the binning from the two axis of one of the two histograms
+    //
+    MH::SetBinning(&fHist, hcol.GetXaxis());
+
+    //
+    // This is necessary to initialize thze error calculation correctly
+    // (Nothing important: The histogram set the size of its internal
+    // array storing the errors to the correct size)
+    //
+    fHist.Sumw2();
+
+    fHist.Add(&hcol);
+    fHist.Multiply((TF1*)&spect);
+
+    SetReadyToSave();
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcDifRate.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcDifRate.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcDifRate.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHMcDifRate
+#define MARS_MHMcDifRate
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class TF1;
+class MMcEvt;
+class MHMcCollectionArea;
+
+class MHMcDifRate : public MParContainer
+{
+private:
+
+    TH1D fHist;           // histogram with the logarith of the energy
+
+    // const MMcEvt *fMcEvt;  //! container to fill histogram from
+
+public:
+    MHMcDifRate(const char *name=NULL, const char *title=NULL);
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    const TH1D *GetHist()       { return &fHist; }
+    const TH1D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t* option = "");
+
+//    void Calc(const TH2D &hsel, const TH2D &hall);
+    void Calc(const MHMcCollectionArea &cola, const TF1 &spect);
+
+    ClassDef(MHMcDifRate, 1)  // Histogram container for differential trigger rate
+};
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcEfficiency.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEfficiency.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEfficiency.cc	(revision 9772)
@@ -0,0 +1,148 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 05/2001 <mailto:jlopez@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHMcEfficiency
+//
+// This class holds the information (histogram and fit function)
+// about the energy threshold for a particular trigger condition.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHMcEfficiency.h" 
+
+#include <math.h>
+
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MHMcEnergyImpact.h"
+
+ClassImp(MHMcEfficiency);
+
+// -------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MHMcEfficiency::MHMcEfficiency(const char *name, const char *title)
+    : fHist()
+{
+    fName  = name  ? name  : "MHMcEfficiency";
+    fTitle = title ? title : "Trigger Efficieny (Energy-Impact parameter plane)";
+
+    //  - we initialize the histogram
+    //  - we have to give diferent names for the diferent histograms because
+    //    root don't allow us to have diferent histograms with the same name
+
+    fHist.SetName(fName);
+    fHist.SetTitle(fTitle);
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("r [m]");
+    fHist.SetZTitle("Trig. Eff. [1]");
+
+
+    MBinning binsx;
+    binsx.SetEdgesLog(10, 1, 100000); // [GeV]
+
+    MBinning binsy;
+    binsy.SetEdges(9, 0, 450);       // [m]
+    MH::SetBinning(&fHist, &binsx, &binsy);
+}
+
+void MHMcEfficiency::SetName(const char *name)
+{
+    fName = name;
+    fHist.SetName(name);
+    fHist.SetDirectory(NULL);
+}
+
+void MHMcEfficiency::SetTitle(const char *title)
+{
+    fTitle = title;
+    fHist.SetTitle(title);
+}
+
+// ------------------------------------------------------------------------
+// 
+// Drawing function. It creates its own canvas.
+//
+void MHMcEfficiency::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->SetLogx();
+
+    fHist.Draw(option);
+
+    pad->Modified();
+    pad->Update();
+}
+
+void MHMcEfficiency::Calc(const TH2D &hsel, const TH2D &hall)
+{
+    //
+    // Set the binning from the two axis of one of the two histograms
+    //
+    MH::SetBinning(&fHist, ((TH2D&)hsel).GetXaxis(), ((TH2D&)hsel).GetYaxis());
+
+    //
+    // This is necessary to initialize thze error calculation correctly
+    // (Nothing important: The histogram set the size of its internal
+    // array storing the errors to the correct size)
+    //
+    fHist.Sumw2();
+
+    //
+    // Calculate the efficiency by dividing the number of selected
+    // (eg. triggered) showers by the number of all showers per bin.
+    // Both histograms are weighted with weight 1, and for the error
+    // calculation we assume a binomial error calculation.
+    //
+    fHist.Divide((TH2D*)&hsel, (TH2D*)&hall, 1, 1, "B");
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency and set the 'ReadyToSave' flag.
+//  The Efficiency is calculated as the number of selected showers
+//  (eg. triggered ones) divided by the number of all showers.
+//  For error calculation Binomial errors are computed.
+//
+void MHMcEfficiency::Calc(const MHMcEnergyImpact &mcsel, const MHMcEnergyImpact &mcall)
+{
+    Calc(*mcsel.GetHist(), *mcall.GetHist());
+
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcEfficiency.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEfficiency.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEfficiency.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MHMcEfficiency
+#define MARS_MHMcEfficiency
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+class MHMcEnergyImpact;
+
+class MHMcEfficiency : public MParContainer
+{
+private:
+
+    TH2D fHist;           // histogram with the logarith of the energy
+
+    // const MMcEvt *fMcEvt;  //! container to fill histogram from
+
+public:
+    MHMcEfficiency(const char *name=NULL, const char *title=NULL);
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    const TH2D *GetHist()       { return &fHist; }
+    const TH2D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t* option = "");
+
+    void Calc(const TH2D &hsel, const TH2D &hall);
+    void Calc(const MHMcEnergyImpact &mcsel, const MHMcEnergyImpact &mcall);
+
+    ClassDef(MHMcEfficiency, 1)  // Histogram container for 2D trigger efficiency
+};
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcEfficiencyEnergy.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEfficiencyEnergy.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEfficiencyEnergy.cc	(revision 9772)
@@ -0,0 +1,146 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 05/2001 <mailto:jlopez@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHMcEfficiencyEnergy
+//
+// This class holds the information (histogram and fit function)
+// about the energy threshold for a particular trigger condition.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHMcEfficiencyEnergy.h" 
+
+#include <math.h>
+
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MHMcEnergyImpact.h"
+
+ClassImp(MHMcEfficiencyEnergy);
+
+// -------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MHMcEfficiencyEnergy::MHMcEfficiencyEnergy(const char *name, const char *title)
+    : fHist()
+{
+    fName  = name  ? name  : "MHMcEfficiencyEnergy";
+    fTitle = title ? title : "Trigger Efficieny vs. Energy";
+
+    //  - we initialize the histogram
+    //  - we have to give diferent names for the diferent histograms because
+    //    root don't allow us to have diferent histograms with the same name
+
+    fHist.SetName(fName);
+    fHist.SetTitle(fTitle);
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("Trig. Eff. [1]");
+
+    MBinning binse;
+    binse.SetEdgesLog(10, 1, 100000); // [GeV]
+    MH::SetBinning(&fHist, &binse);
+}
+
+void MHMcEfficiencyEnergy::SetName(const char *name)
+{
+    fName = name;
+    fHist.SetName(name);
+    fHist.SetDirectory(NULL);
+}
+
+void MHMcEfficiencyEnergy::SetTitle(const char *title)
+{
+    fTitle = title;
+    fHist.SetTitle(title);
+}
+
+// ------------------------------------------------------------------------
+// 
+// Drawing function. It creates its own canvas.
+//
+void MHMcEfficiencyEnergy::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->SetLogx();
+
+    fHist.Draw(option);
+
+    pad->Modified();
+    pad->Update();
+}
+
+void MHMcEfficiencyEnergy::Calc(const TH2D &hsel, const TH2D &hall)
+{
+    //
+    // Set the binning from the two axis of one of the two histograms
+    //
+    MH::SetBinning(&fHist, ((TH2D&)hsel).GetXaxis());
+
+    //
+    // This is necessary to initialize thze error calculation correctly
+    // (Nothing important: The histogram set the size of its internal
+    // array storing the errors to the correct size)
+    //
+    fHist.Sumw2();
+
+    //
+    // Calculate the efficiency by dividing the number of selected
+    // (eg. triggered) showers by the number of all showers per bin.
+    // Both histograms are weighted with weight 1, and for the error
+    // calculation we assume a binomial error calculation.
+    //
+    TH1D &tsel = *((TH2D&)hsel).ProjectionX();
+    TH1D &tall = *((TH2D&)hall).ProjectionX();
+    fHist.Divide(&tsel, &tall, 1, 1);
+    delete &tsel;
+    delete &tall;
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the EfficiencyEnergy and set the 'ReadyToSave' flag.
+//  The EfficiencyEnergy is calculated as the number of selected showers
+//  (eg. triggered ones) divided by the number of all showers.
+//  For error calculation Binomial errors are computed.
+//
+void MHMcEfficiencyEnergy::Calc(const MHMcEnergyImpact &mcsel, const MHMcEnergyImpact &mcall)
+{
+    Calc(*mcsel.GetHist(), *mcall.GetHist());
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcEfficiencyEnergy.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEfficiencyEnergy.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEfficiencyEnergy.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MHMcEfficiencyEnergy
+#define MARS_MHMcEfficiencyEnergy
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+class MHMcEnergyImpact;
+
+class MHMcEfficiencyEnergy : public MParContainer
+{
+private:
+
+    TH1D fHist;           // histogram with the logarith of the energy
+
+    // const MMcEvt *fMcEvt;  //! container to fill histogram from
+
+public:
+    MHMcEfficiencyEnergy(const char *name=NULL, const char *title=NULL);
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    const TH1D *GetHist()       { return &fHist; }
+    const TH1D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t* option = "");
+
+    void Calc(const TH2D &hsel, const TH2D &hall);
+    void Calc(const MHMcEnergyImpact &mcsel, const MHMcEnergyImpact &mcall);
+
+    ClassDef(MHMcEfficiencyEnergy, 1)  // Histogram container for 1D trigger efficiency in energy
+};
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcEfficiencyImpact.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEfficiencyImpact.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEfficiencyImpact.cc	(revision 9772)
@@ -0,0 +1,146 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 05/2001 <mailto:jlopez@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHMcEfficiencyImpact
+//
+// This class holds the information (histogram and fit function)
+// about the energy threshold for a particular trigger condition.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHMcEfficiencyImpact.h" 
+
+#include <math.h>
+
+#include <TCanvas.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MHMcEnergyImpact.h"
+
+ClassImp(MHMcEfficiencyImpact);
+
+// -------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MHMcEfficiencyImpact::MHMcEfficiencyImpact(const char *name, const char *title)
+    : fHist()
+{
+    fName  = name  ? name  : "MHMcEfficiencyImpact";
+    fTitle = title ? title : "Trigger Efficieny vs. Impact";
+
+    //  - we initialize the histogram
+    //  - we have to give diferent names for the diferent histograms because
+    //    root don't allow us to have diferent histograms with the same name
+
+    fHist.SetName(fName);
+    fHist.SetTitle(fTitle);
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("r [m]");
+    fHist.SetYTitle("Trig. Eff. [1]");
+
+
+    MBinning binsr;
+    binsr.SetEdges(9, 0, 450);       // [m]
+    MH::SetBinning(&fHist, &binsr);
+}
+
+void MHMcEfficiencyImpact::SetName(const char *name)
+{
+    fName = name;
+    fHist.SetName(name);
+    fHist.SetDirectory(NULL);
+}
+
+void MHMcEfficiencyImpact::SetTitle(const char *title)
+{
+    fTitle = title;
+    fHist.SetTitle(title);
+}
+
+// ------------------------------------------------------------------------
+// 
+// Drawing function. It creates its own canvas.
+//
+void MHMcEfficiencyImpact::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->SetLogx();
+
+    fHist.Draw(option);
+
+    pad->Modified();
+    pad->Update();
+}
+
+void MHMcEfficiencyImpact::Calc(const TH2D &hsel, const TH2D &hall)
+{
+    //
+    // Set the binning from the two axis of one of the two histograms
+    //
+    MH::SetBinning(&fHist, ((TH2D&)hsel).GetYaxis());
+
+    //
+    // This is necessary to initialize thze error calculation correctly
+    // (Nothing important: The histogram set the size of its internal
+    // array storing the errors to the correct size)
+    //
+    fHist.Sumw2();
+
+    //
+    // Calculate the efficiency by dividing the number of selected
+    // (eg. triggered) showers by the number of all showers per bin.
+    // Both histograms are weighted with weight 1, and for the error
+    // calculation we assume a binomial error calculation.
+    //
+    TH1D &tsel = *((TH2D&)hsel).ProjectionY();
+    TH1D &tall = *((TH2D&)hall).ProjectionY();
+    fHist.Divide(&tsel, &tall, 1, 1);
+    delete &tsel;
+    delete &tall;
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the EfficiencyImpact and set the 'ReadyToSave' flag.
+//  The EfficiencyImpact is calculated as the number of selected showers
+//  (eg. triggered ones) divided by the number of all showers.
+//  For error calculation Binomial errors are computed.
+//
+void MHMcEfficiencyImpact::Calc(const MHMcEnergyImpact &mcsel, const MHMcEnergyImpact &mcall)
+{
+    Calc(*mcsel.GetHist(), *mcall.GetHist());
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcEfficiencyImpact.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEfficiencyImpact.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEfficiencyImpact.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MHMcEfficiencyImpact
+#define MARS_MHMcEfficiencyImpact
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+class MHMcEnergyImpact;
+
+class MHMcEfficiencyImpact : public MParContainer
+{
+private:
+
+    TH1D fHist;           // histogram with the logarith of the energy
+
+    // const MMcEvt *fMcEvt;  //! container to fill histogram from
+
+public:
+    MHMcEfficiencyImpact(const char *name=NULL, const char *title=NULL);
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    const TH1D *GetHist()       { return &fHist; }
+    const TH1D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t* option = "");
+
+    void Calc(const TH2D &hsel, const TH2D &hall);
+    void Calc(const MHMcEnergyImpact &mcsel, const MHMcEnergyImpact &mcall);
+
+    ClassDef(MHMcEfficiencyImpact, 1) // Histogram container for 1D trigger efficiency in impact
+};
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcEnergy.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEnergy.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEnergy.cc	(revision 9772)
@@ -0,0 +1,250 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 05/2001 <mailto:jlopez@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHMcEnergy
+//
+// This class holds the information (histogram and fit function)
+// about the energy threshold for a particular trigger condition.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHMcEnergy.h" 
+
+#include <stdlib.h>
+#include <iostream>
+
+#include <TH1.h> 
+#include <TF1.h> 
+#include <TCanvas.h>
+#include <TPaveLabel.h> 
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHMcEnergy);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MHMcEnergy::MHMcEnergy(const char *name, const char *title)
+{ 
+    fTitle = title ? title : "Container for an energy distribution histogram";
+
+    //  - we initialize the histogram
+    //  - we have to give diferent names for the diferent histograms because
+    //    root don't allow us to have diferent histograms with the same name
+
+    fHist = new TH1F("", "", 20, 0.5, 4.5);
+
+    fHist->SetDirectory(NULL);
+    fHist->SetXTitle("log(E/GeV)");
+    fHist->SetYTitle("dN/dE");
+
+    SetName(name ? name : "MHMcEnergy");
+}
+
+// -------------------------------------------------------------------------
+//
+//  This doesn't only set the name. It tries to get the number from the
+//  name and creates also name and title of the histogram.
+//
+//  This is necessary for example if a list of such MHMcEnergy histograms
+//  is created (s. MParList::CreateObjList)
+//
+void MHMcEnergy::SetName(const char *name)
+{
+    TString cname(name);
+    const char *semicolon = strrchr(cname, ';');
+
+    UInt_t idx = semicolon ? atoi(semicolon+1) : 0;
+
+    fName = cname;
+
+    char text[256];
+    if (idx>0)
+        sprintf(text, "Energy Distribution for trigger condition #%i", idx);
+    else
+        sprintf(text, "Energy Distribution");
+
+    char aux[256];
+    strcpy(aux, "Threshold");
+
+    if (idx>0)
+        sprintf(aux+strlen(aux), " #%i", idx);
+
+    fHist->SetName(aux);
+    fHist->SetTitle(text);
+}
+
+//-------------------------------------------------------------------------
+//
+//  Defualt Destructor
+//
+MHMcEnergy::~MHMcEnergy()
+{
+    delete fHist;
+}
+
+//--------------------------------------------------------------------------
+//
+//  Fill the histogram with the log10 of the energy for triggered events.
+//
+void MHMcEnergy::Fill(Float_t log10E, Float_t w)
+{
+    fHist->Fill(log10E, w);
+}
+
+// -------------------------------------------------------------------------
+//
+// Fitting function
+//
+void MHMcEnergy::Fit(Axis_t xxmin, Axis_t xxmax)
+{
+    //
+    // 0: don't draw the function (it is drawn together with the histogram)
+    // Q: quiet mode
+    //
+    fHist->Fit("gaus", "Q0", "", xxmin, xxmax);
+
+    TF1 *result = fHist->GetFunction("gaus");
+
+    fThreshold    = CalcThreshold(result);
+    fThresholdErr = CalcThresholdErr(result);
+    fGaussPeak    = CalcGaussPeak(result);
+    fGaussSigma   = CalcGaussSigma(result);
+}
+
+// ------------------------------------------------------------------------
+// 
+//  Helper function for Draw() and DrawClone() which adds some useful
+//  information to the plot.
+//
+void MHMcEnergy::DrawLegend() const
+{
+    char text[256];
+
+    const Float_t min = fHist->GetMinimum();
+    const Float_t max = fHist->GetMaximum();
+    const Float_t sum = min+max;
+
+    sprintf(text, "Energy Threshold = %4.1f +- %4.1f GeV",
+            fThreshold, fThresholdErr);
+
+    TPaveLabel* label = new TPaveLabel(2.2, 0.75*sum, 4.4, 0.90*sum, text);
+    label->SetFillColor(10);
+    label->SetTextSize(0.3);
+    label->SetBit(kCanDelete);
+    label->Draw();
+}
+
+// ------------------------------------------------------------------------
+// 
+// Drawing function. It creates its own canvas.
+//
+void MHMcEnergy::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    fHist->Draw(option);
+
+    DrawLegend();
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the number of bins in the histogran.
+//
+void MHMcEnergy::SetNumBins(Int_t nbins)
+{
+    fHist->SetBins(nbins, 0.5, 4.5);
+}
+// --------------------------------------------------------------------------
+//
+// Write the threshold and its error in the standard output
+//
+void MHMcEnergy::Print(Option_t*) const
+{
+    *fLog << all << "Threshold: " << fThreshold << " +- " << fThresholdErr << endl;
+}
+
+// -------------------------------------------------------------------------
+//
+//  Return the threshold
+//
+Float_t MHMcEnergy::CalcThreshold(TF1 *gauss)
+{
+    const Float_t p1 = gauss->GetParameter(1);
+
+    return pow(10, p1);
+}
+
+// -------------------------------------------------------------------------
+//
+// Return the error of the threshold.
+//
+Float_t MHMcEnergy::CalcThresholdErr(TF1 *gauss)
+{
+    const Float_t lg10  = log(10.);
+    const Float_t p1    = gauss->GetParameter(1);
+    const Float_t p1err = gauss->GetParError(1);
+
+    // The error has into accuont the error in the fit
+    return pow(10, p1) * p1err * lg10;
+}
+
+// -------------------------------------------------------------------------
+//
+// Return the peak of the fitted gaussan function.
+//
+Float_t MHMcEnergy::CalcGaussPeak(TF1 *gauss)
+{
+    return gauss->GetParameter(1);
+}
+
+// -------------------------------------------------------------------------
+//
+// Return the sigma of the fitted gaussan function.
+//
+Float_t MHMcEnergy::CalcGaussSigma(TF1 *gauss)
+{
+    return gauss->GetParameter(2);
+}
+
+TH1 *MHMcEnergy::GetHistByName(const TString name)
+{
+    return fHist;
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcEnergy.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEnergy.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEnergy.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MHMcEnergy
+#define MARS_MHMcEnergy
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TH1;
+class TH1F;
+class TF1;
+
+class MHMcEnergy : public MParContainer
+{
+private:
+
+    TH1F *fHist;  // histogram with the logarith of the energy
+
+    Float_t fThreshold;
+    Float_t fThresholdErr;
+    Float_t fGaussPeak;
+    Float_t fGaussSigma;
+
+    Float_t CalcThreshold(TF1 *gauss);
+    Float_t CalcThresholdErr(TF1 *gauss);
+
+    Float_t CalcGaussPeak(TF1 *gauss);
+    Float_t CalcGaussSigma(TF1 *gauss);
+
+    void DrawLegend() const;
+
+public:
+
+    MHMcEnergy(const char *name=NULL, const char *title=NULL);
+    ~MHMcEnergy();
+
+    void SetName(const char *name);
+
+    Float_t GetThreshold() const { return fThreshold; }
+    Float_t GetThresholdErr() const { return fThresholdErr; }
+
+    Float_t GetGaussPeak() const { return fGaussPeak; }
+    Float_t GetGaussSigma() const { return fGaussSigma; };
+
+    void Fill(Float_t log10E, Float_t w);
+    void Fit(Axis_t xxmin, Axis_t xxmax);
+    void SetNumBins(Int_t nbins = 100);
+
+    TH1 *GetHistByName(const TString name);
+
+    void Draw(Option_t* option = "");
+
+    void Print(Option_t* option = NULL) const;
+
+    ClassDef(MHMcEnergy, 1)  // Histogram container for montecarlo energy threshold
+};
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcEnergyImpact.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEnergyImpact.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEnergyImpact.cc	(revision 9772)
@@ -0,0 +1,141 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 05/2001 <mailto:jlopez@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHMcEnergyImpact
+//
+// This class holds the information (histogram and fit function)
+// about the energy threshold for a particular trigger condition.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHMcEnergyImpact.h" 
+
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MParList.h"
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MHMcEnergyImpact);
+
+// -------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MHMcEnergyImpact::MHMcEnergyImpact(const char *name, const char *title)
+    : fHist()
+{
+    fName  = name  ? name  : "MHMcEnergyImpact";
+    fTitle = title ? title : "Impact (radius) vs Energy distribution";
+
+    //  - we initialize the histogram
+    //  - we have to give diferent names for the diferent histograms because
+    //    root don't allow us to have diferent histograms with the same name
+
+    fHist.SetName(fName);
+    fHist.SetTitle(fTitle);
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("r [m]");
+    fHist.SetZTitle("N");
+
+    MBinning binsx;
+    binsx.SetEdgesLog(10, 1, 100000); // [GeV]
+
+    MBinning binsy;
+    binsy.SetEdges(9, 0, 450);       // [m]
+
+    SetBinning(&fHist, &binsx, &binsy);
+
+}
+
+void MHMcEnergyImpact::SetName(const char *name)
+{
+    fName = name;
+    fHist.SetName(name);
+    fHist.SetDirectory(NULL);
+}
+
+void MHMcEnergyImpact::SetTitle(const char *title)
+{
+    fTitle = title;
+    fHist.SetName(title);
+}
+
+Bool_t MHMcEnergyImpact::SetupFill(const MParList *pList)
+{
+    const MBinning *binsx = (MBinning*)pList->FindObject("BinningEnergy", "MBinning");
+    const MBinning *binsy = (MBinning*)pList->FindObject("BinningImpact", "MBinning");
+
+    if (!binsx || !binsy)
+        return kTRUE;
+
+    SetBinning(&fHist, binsx, binsy);
+
+    return kTRUE;
+}
+
+//--------------------------------------------------------------------------
+//
+//  Fill the histogram with the log10 of the energy for triggered events.
+//
+Bool_t MHMcEnergyImpact::Fill(const MParContainer *cont, const Stat_t w)
+{
+    const MMcEvt &mcevt = *(MMcEvt*)cont;
+
+    const Float_t energy = mcevt.GetEnergy();
+    const Float_t impact = mcevt.GetImpact()/100.;
+
+    fHist.Fill(energy, impact, w);
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+// 
+// Drawing function. It creates its own canvas.
+//
+void MHMcEnergyImpact::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->SetLogx();
+
+    fHist.Draw(option);
+
+    pad->Modified();
+    pad->Update();
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcEnergyImpact.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEnergyImpact.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEnergyImpact.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MHMcEnergyImpact
+#define MARS_MHMcEnergyImpact
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+
+class MHMcEnergyImpact : public MH
+{
+private:
+    TH2D fHist; // histogram with the logarith of the energy
+
+public:
+    MHMcEnergyImpact(const char *name=NULL, const char *title=NULL);
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *pcont=NULL, const Stat_t w=1);
+
+    const TH2D *GetHist()       { return &fHist; }
+    const TH2D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t* option = "");
+
+    ClassDef(MHMcEnergyImpact, 1)  // Histogram container for 2D histogram in Energy and Impact
+};
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcEnergyMigration.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEnergyMigration.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEnergyMigration.cc	(revision 9772)
@@ -0,0 +1,311 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 4/2002 <mailto:wittek@mppmu.mpg.de>
+!              Abelardo Moralejo 5/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHMcEnergyMigration                                                     //
+//                                                                          //
+//  calculates the migration matrix E-est vs. E-true                        //
+//  for different bins in Theta                                             //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHMcEnergyMigration.h"
+
+#include <TCanvas.h>
+
+#include "MMcEvt.hxx"
+
+#include "MEnergyEst.h"
+#include "MBinning.h"
+#include "MHillasSrc.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include <TProfile.h>
+
+ClassImp(MHMcEnergyMigration);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram.
+//
+MHMcEnergyMigration::MHMcEnergyMigration(const char *name, const char *title)
+  : fHist(), fHist2(), fHistImp()
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHMcEnergyMigration";
+    fTitle = title ? title : "3-D histogram   E-true E-est Theta";
+
+    fHist.SetDirectory(NULL);
+    fHist.SetTitle("3D-plot  E_{EST}  E_{TRUE}  \\Theta");
+    fHist.SetXTitle("E_{EST} [GeV]");
+    fHist.SetYTitle("E_{TRUE} [GeV]");
+    fHist.SetZTitle("\\Theta [\\circ]");
+
+    fHist2.SetDirectory(NULL);
+    fHist2.SetTitle("3D-plot \\Delta E / E  vs E_{EST} E_{TRUE}");
+    fHist2.SetXTitle("E_{EST} [GeV]");
+    fHist2.SetYTitle("E_{TRUE} [GeV]");
+    fHist2.SetZTitle("\\frac{E_{EST} - E_{TRUE}}{E_{TRUE}}");
+
+    fHistImp.SetDirectory(NULL);
+    fHistImp.SetTitle("\\Delta E / E  vs Impact parameter");
+    fHistImp.SetXTitle("Impact parameter (m)");
+    fHistImp.SetYTitle("\\frac{E_{EST} - E_{TRUE}}{E_{TRUE}}");
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histograms
+//
+Bool_t MHMcEnergyMigration::SetupFill(const MParList *plist)
+{
+    fEnergy = (MEnergyEst*)plist->FindObject("MEnergyEst");
+    if (!fEnergy)
+    {
+        *fLog << err << dbginf << "MEnergyEst not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MBinning* binsenergy = (MBinning*)plist->FindObject("BinningE");
+    const MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta");
+    if (!binsenergy || !binstheta)
+    {
+        *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(&fHist, binsenergy, binsenergy, binstheta);
+    fHist.Sumw2();
+
+    const MBinning* binsde = (MBinning*)plist->FindObject("BinningDE");
+    const MBinning* binsimpact = (MBinning*)plist->FindObject("BinningImpact");
+    SetBinning(&fHistImp, binsimpact, binsde);
+
+    fHistImp.Sumw2();
+
+    SetBinning(&fHist2, binsenergy, binsenergy, binsde);
+    fHist2.Sumw2();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHMcEnergyMigration::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2,2);
+    
+    TH1 *h;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    h = fHist.Project3D("ey_pro");
+    h->SetTitle("Distribution of E_{TRUE}");
+    h->SetXTitle("E_{TRUE} [GeV]");
+    h->SetBit(kCanDelete);
+    h->Draw(opt);
+    h->SetDirectory(NULL);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    h = fHist.Project3D("ex_pro");
+    h->SetTitle("Distribution of E_{EST}");
+    h->SetXTitle("E_{est} [GeV]");
+    h->SetBit(kCanDelete);
+    h->Draw(opt);
+    Double_t minEest = h->GetXaxis()->GetXmin();
+    h->SetDirectory(NULL);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = fHist.Project3D("z_pro");
+    h->SetTitle("Distribution of \\Theta");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetBit(kCanDelete);
+    h->SetLineWidth(2);
+    h->Draw(opt);
+    h->SetDirectory(NULL);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    TH1D* hpx;
+    hpx = fHistImp.ProjectionX("_px", 1, fHistImp.GetNbinsY(),"e");
+    hpx->SetTitle("Distribution of Impact parameter");
+    hpx->SetXTitle("Impact parameter (m)");
+    hpx->SetBit(kCanDelete);
+    hpx->Draw(opt);
+    hpx->SetDirectory(NULL);
+    fHistImp.SetDirectory(NULL);
+
+    pad->Modified();
+    pad->Update();
+
+    TVirtualPad *pad2 = MakeDefCanvas((TString)GetName()+"2");
+    pad2->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad2->Divide(2,2);
+    
+    TH2D *h2;
+
+    pad2->cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    h2 = (TH2D*) fHist.Project3D("yx");
+
+    TProfile* h2pfx;
+    h2pfx = h2->ProfileX("_pfx", 1, h2->GetNbinsY(),"S");
+    h2pfx->SetXTitle("E_{TRUE} (GeV)");
+    h2pfx->SetYTitle("E_{EST} (GeV)");
+    h2pfx->SetTitle("E_{EST} vs E_{TRUE}");
+    h2pfx->SetBit(kCanDelete);
+    h2pfx->SetFillColor(41);
+    h2pfx->SetFillStyle(1001);
+    h2pfx->SetMinimum(minEest);
+    h2pfx->SetStats(kFALSE);
+    h2pfx->DrawCopy("E3");
+
+    h2->SetBit(kCanDelete);
+    h2->SetFillColor(1);
+    h2->Draw("box,same");
+    h2->SetDirectory(NULL);
+
+    h2pfx->SetLineColor(2);
+    h2pfx->SetLineWidth(2);
+    h2pfx->SetFillColor(0);
+    h2pfx->DrawCopy("C,hist,same");
+    h2pfx->SetDirectory(NULL);
+
+    pad2->cd(2);
+
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLeftMargin(0.15);
+    h2 = (TH2D*) fHist2.Project3D("zy");
+    h2->SetBit(kCanDelete);
+    h2pfx = h2->ProfileX("_pfx", 1, h2->GetNbinsY(),"S");
+    h2pfx->SetTitle("\\Delta E / E vs E_{TRUE}");
+    h2pfx->SetXTitle("E_{TRUE} (GeV)");
+    h2pfx->SetYTitle("\\frac{E_{EST} - E_{TRUE}}{E_{TRUE}}");
+    h2pfx->SetBit(kCanDelete);
+    h2pfx->SetFillColor(41);
+    h2pfx->SetFillStyle(1001);
+    h2pfx->GetYaxis()->SetTitleOffset(1.4);
+    h2pfx->SetStats(kFALSE);
+    h2pfx->DrawCopy("E3");
+    h2->SetFillColor(1);
+    h2->Draw("same,box");
+    h2->SetDirectory(NULL);
+    h2pfx->SetLineColor(2);
+    h2pfx->SetLineWidth(2);
+    h2pfx->SetFillColor(0);
+    h2pfx->DrawCopy("C,hist,same");
+    h2pfx->SetDirectory(NULL);
+    
+    pad2->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLeftMargin(0.15);
+    h2 = (TH2D*) fHist2.Project3D("zx");
+    h2->SetBit(kCanDelete);
+    h2pfx = h2->ProfileX("_pfx", 1, h2->GetNbinsY(),"S");
+    h2pfx->SetTitle("\\Delta E / E vs E_{EST}");
+    h2pfx->SetXTitle("E_{EST} (GeV)");
+    h2pfx->SetYTitle("\\frac{E_{EST} - E_{TRUE}}{E_{TRUE}}");
+    h2pfx->SetBit(kCanDelete);
+    h2pfx->SetFillColor(41);
+    h2pfx->SetFillStyle(1001);
+    h2pfx->GetYaxis()->SetTitleOffset(1.4);
+    h2pfx->SetStats(kFALSE);
+    h2pfx->SetMinimum(-1.);
+    h2pfx->SetMaximum(1.);
+    h2pfx->DrawCopy("E3");
+    
+    h2->SetFillColor(1);
+    h2->Draw("same,box");
+    h2->SetDirectory(NULL);
+    h2pfx->SetLineColor(2);
+    h2pfx->SetLineWidth(2);
+    h2pfx->SetFillColor(0);
+    h2pfx->DrawCopy("L,histo,same");
+    h2pfx->SetDirectory(NULL);
+    
+    pad2->cd(4);
+    gPad->SetBorderMode(0);
+    h = fHist2.ProjectionZ("_pz",1,fHist2.GetNbinsX(),1,fHist2.GetNbinsY(),"e");
+    h->SetBit(kCanDelete);
+    h->Draw();
+    h->SetDirectory(NULL);
+
+    pad2->Modified();
+    pad2->Update();
+
+    fHist.SetDirectory(NULL);
+    fHist2.SetDirectory(NULL);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+//
+Bool_t MHMcEnergyMigration::Fill(const MParContainer *par, const Stat_t w)
+{
+    // get E-true from fMcEvt and E-est from fEnergy
+
+    fHist.Fill(fEnergy->GetEnergy(), fMcEvt->GetEnergy(), fMcEvt->GetTelescopeTheta()*kRad2Deg, w);
+
+    fHist2.Fill(fEnergy->GetEnergy(), fMcEvt->GetEnergy(), (fEnergy->GetEnergy()-fMcEvt->GetEnergy())/fMcEvt->GetEnergy(), w);
+
+    fHistImp.Fill(fMcEvt->GetImpact()/100., (fEnergy->GetEnergy()-fMcEvt->GetEnergy())/fMcEvt->GetEnergy(), w);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcEnergyMigration.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcEnergyMigration.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcEnergyMigration.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MHMcEnergyMigration
+#define MARS_MHMcEnergyMigration
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH3.h>
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MMcEvt;
+class MEnergyEst;
+class MParList;
+
+class MHMcEnergyMigration : public MH
+{
+private:
+    MMcEvt      *fMcEvt; //!
+    MEnergyEst  *fEnergy; //!
+
+    TH3D        fHist;
+    TH3D        fHist2;
+    TH2D        fHistImp;
+
+public:
+    MHMcEnergyMigration(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    const TH3D *GetHist() { return &fHist; }
+    const TH3D *GetHist() const { return &fHist; }
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    const TH3D *GetHist2() { return &fHist2; }
+    const TH2D *GetHistImp() { return &fHistImp; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHMcEnergyMigration, 1) //3D-histogram   E-true E-est Theta
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcIntRate.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcIntRate.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcIntRate.cc	(revision 9772)
@@ -0,0 +1,132 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 05/2001 <mailto:jlopez@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHMcIntRate
+//
+// This class holds the information (histogram and fit function)
+// about the energy threshold for a particular trigger condition.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHMcIntRate.h" 
+
+#include <math.h>
+
+#include <TCanvas.h>
+
+#include "MH.h"
+#include "MBinning.h"
+
+#include "MHMcDifRate.h"
+
+ClassImp(MHMcIntRate);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MHMcIntRate::MHMcIntRate(const char *name, const char *title)
+    : fHist()
+{
+    fName  = name  ? name  : "MHMcIntRate";
+    fTitle = title ? title : "Integral Trigger Rate";
+
+    //  - we initialize the histogram
+    //  - we have to give diferent names for the diferent histograms because
+    //    root don't allow us to have diferent histograms with the same name
+
+    fHist.SetName(fName);
+    fHist.SetTitle(fTitle);
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("Rate [Hz]");
+}
+
+void MHMcIntRate::SetName(const char *name)
+{
+    fName = name;
+    fHist.SetName(name);
+    fHist.SetDirectory(NULL);
+}
+
+void MHMcIntRate::SetTitle(const char *title)
+{
+    fTitle = title;
+    fHist.SetTitle(title);
+}
+
+// ------------------------------------------------------------------------
+// 
+// Drawing function. It creates its own canvas.
+//
+void MHMcIntRate::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->SetLogx();
+
+    fHist.Draw(option);
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the IntRate and set the 'ReadyToSave' flag.
+//  The IntRate is calculated as the number of selected showers
+//  (eg. triggered ones) divided by the number of all showers.
+//  For error calculation Binomial errors are computed.
+//
+void MHMcIntRate::Calc(const MHMcDifRate &rate)
+{
+    /*const*/ TH1D  &hist = (TH1D&)*rate.GetHist();
+    const TAxis &axis = *hist.GetXaxis();
+
+    //
+    // Set the binning from the two axis of one of the two histograms
+    //
+    MH::SetBinning(&fHist, &axis);
+
+    const Int_t nbinsx = axis.GetNbins();
+
+    for (Int_t i=1; i<=nbinsx; i++)
+    {
+        fHist.SetBinContent(i, hist.Integral(i, nbinsx, "width"));
+        fHist.SetBinError(i, hist.GetBinError(i)*axis.GetBinWidth(i));
+    }
+
+    fHist.SetEntries(hist.GetEntries());
+
+    SetReadyToSave();
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcIntRate.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcIntRate.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcIntRate.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MHMcIntRate
+#define MARS_MHMcIntRate
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MHMcDifRate;
+
+class MHMcIntRate : public MParContainer
+{
+private:
+
+    TH1D fHist;           // histogram with the logarith of the energy
+
+    // const MMcEvt *fMcEvt;  //! container to fill histogram from
+
+public:
+    MHMcIntRate(const char *name=NULL, const char *title=NULL);
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    const TH1D *GetHist()       { return &fHist; }
+    const TH1D *GetHist() const { return &fHist; }
+
+    TH1 *GetHistByName(const TString name) { return &fHist; }
+
+    void Draw(Option_t* option = "");
+
+    void Calc(const MHMcDifRate &rate);
+
+    ClassDef(MHMcIntRate, 1)  // Histogram container for integral event rate
+};
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcRate.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcRate.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcRate.cc	(revision 9772)
@@ -0,0 +1,258 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!   Author(s): Abelardo Moralejo 2/2003
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   Explanations on the rate calculation can be found in
+//   chapter 7 of the following diploma thesis:
+//   http://www.pd.infn.it/magic/tesi2.ps.gz (in Italian)
+//
+////////////////////////////////////////////////////////////////////////////
+
+#include "MHMcRate.h" 
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHMcRate);
+
+using namespace std;
+
+void MHMcRate::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcTriggerRate";
+    fTitle = title ? title : "Task to calc the collection area ";
+
+    fPartId=0;               // Type of particle
+
+    fEnergyMax=0.0;          // Maximum Energy (TeV)
+    fEnergyMin=1000000.0;    // Minimum Energy (TeV)
+
+    fSolidAngle = -1.;       // Solid angle within which incident directions
+                             // are distributed
+    fThetaMax=0.0;           // Maximum theta angle of run
+    fThetaMin=370.0;         // Minimum theta angle of run
+    fPhiMax=0.0;             // Maximum phi angle of run
+    fPhiMin=370.0;           // Minimum phi angle of run
+
+    fImpactMax=0.0;          // Maximum impact parameter
+    fImpactMin=100000.0;     // Minimum impact parameter
+
+    fBackTrig=-1.0;          // Number of triggers from background
+    fBackSim=-1.0;           // Number of simulated showers for the background
+
+    fTriggerRate= -1.0;      // Trigger rate in Hz
+    fTriggerRateError= -1.0; // Estimated error for the trigger rate in Hz
+
+    fMultiplicity = -1;      // Multiplicity of the trigger condition
+    fMeanThreshold = -1.;    // Discr. threshold of the trigger condition
+    fTriggerCondNum = 0;     // Trigger condition number within camera file
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  default constructor
+//  fills all member data with initial values
+//
+MHMcRate::MHMcRate(const char *name, const char *title)
+{
+    Init(name, title);
+
+    fSpecIndex=0.0;         // dn/dE = k * e^{- fSpecIndex}
+    fFlux0=-1.0;            // dn/dE = fFlux0 * E^{-a}
+
+    fShowerRate= -1.0;      // Showers rate in Hz
+    fShowerRateError=0.0;   // Estimated error of shower rate in Hz
+}
+
+// --------------------------------------------------------------------------
+//
+//  overloaded constructor I
+//  fills all member data with initial values and sets the rate of
+//  incident showers to ShowRate
+//
+MHMcRate::MHMcRate(Float_t showrate,
+                   const char *name, const char *title)
+{
+    Init(name, title);
+
+    fSpecIndex=0.0;                  // dn/dE = k * e^{- fSpecIndex}
+    fFlux0=-1.0;                     // dn/dE = fFlux0 * E^{-a}
+
+    fShowerRate= showrate;           // Showers rate in Hz
+    fShowerRateError=sqrt(showrate); // Estimated error of shower rate in Hz
+}
+
+// --------------------------------------------------------------------------
+//
+//  overloaded constructor I
+//  fills all member data with initial values and sets the
+//  spectral index and the initial flux to SpecIndex and Flux0
+//
+MHMcRate::MHMcRate(Float_t specindex, Float_t flux0,
+                   const char *name, const char *title)
+{
+    Init(name, title);
+
+    fSpecIndex=specindex;   // dn/dE = k * e^{- fSpecIndex}
+    fFlux0=flux0;           // dn/dE = fFlux0 * E^{-a}
+
+    fShowerRate= -1.0;
+    fShowerRateError=0.0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  set the particle that produces the showers in the athmosphere
+//
+void MHMcRate:: SetParticle(UShort_t part)
+{
+    fPartId=part;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the information about trigger due only to the Night Sky Background:
+//
+void MHMcRate::SetBackground (Float_t showers, Float_t triggers)
+{
+    fBackTrig=showers;      // Number of triggers from background
+    fBackSim=triggers;      // Number of simulated showers for the background
+}
+
+// --------------------------------------------------------------------------
+//
+//  set the parameters to compute the incident rate 
+//
+void MHMcRate:: SetFlux(Float_t flux0, Float_t specindx)
+{
+    fFlux0=flux0;
+    fSpecIndex=specindx;
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  set the incident rate 
+//
+void MHMcRate:: SetIncidentRate(Float_t showerrate)
+{
+    fShowerRate=showerrate;
+}
+
+// --------------------------------------------------------------------------
+//
+//  update the limits for energy, theta, phi and impact parameter
+//
+void MHMcRate::UpdateBoundaries(Float_t energy, Float_t theta,
+                                Float_t phi, Float_t impact)
+{ 
+    // It updates the limit values
+
+    if (fThetaMax<theta) fThetaMax=theta;
+    if (fThetaMin>theta) fThetaMin=theta;
+
+    if (fPhiMax<phi) fPhiMax=phi;
+    if (fPhiMin>phi) fPhiMin=phi;
+
+    if (fImpactMax<impact) fImpactMax=impact;
+    if (fImpactMin>impact) fImpactMin=impact;
+
+    if (fEnergyMax<energy) fEnergyMax=energy;
+    if (fEnergyMin>energy) fEnergyMin=energy;
+} 
+
+// --------------------------------------------------------------------------
+//
+//  compute the trigger rate and set the ReadyToSave bit
+//
+void MHMcRate::CalcRate(Float_t trig, Float_t anal, Float_t simu) 
+{ 
+    // It computes the trigger rate
+
+    // First one computes the rate of incident showers.
+    const Double_t specidx = 1.0-fSpecIndex;
+
+    const Double_t epowmax = pow((double)fEnergyMax, specidx);
+    const Double_t epowmin = pow((double)fEnergyMin, specidx);
+
+    if (fShowerRate <= 0)
+      fShowerRate = fFlux0/specidx*(epowmax-epowmin);
+
+    if (fSolidAngle < 0.)
+      fSolidAngle = (fPhiMax-fPhiMin)*(cos(fThetaMin)-cos(fThetaMax));
+
+    if (fPartId!=1)
+      fShowerRate *= fSolidAngle;
+
+    fShowerRate *= TMath::Pi()*(fImpactMax/100.0*fImpactMax/100.0 - 
+				fImpactMin/100.0*fImpactMin/100.0);
+
+    fShowerRateError = sqrt(fShowerRate);
+
+    // The simulated trigger time in the camera program is 160 ns:
+    // 9/10/2002, AM: Fixed error below in calculation of "anal2"
+    // ( added factor fShowerRate/simu )
+
+    const Double_t anal2 = 1.0-fShowerRate*(anal/simu)*160.0e-9;
+    const Double_t back2 = fBackSim*160.0e-9;
+
+    // Then the trigger rate and its error is evaluated
+    if(fBackTrig<0){
+        fTriggerRateError = sqrt((trig*fShowerRate*fShowerRate/(simu*simu)) +
+                                 (anal2*anal2*1/(fBackSim*back2*back2)));
+        fBackTrig=0;
+    }
+    else
+        fTriggerRateError = sqrt((trig*fShowerRate*fShowerRate/(simu*simu)) +
+                                 (anal2*anal2*fBackTrig/(back2*back2)));
+
+    fTriggerRate = trig*fShowerRate/simu + anal2*fBackTrig/back2;
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+//  print the trigger rate
+//
+void MHMcRate::Print(Option_t *) const
+{
+    *fLog << all << "Incident rate " << fShowerRate << " Hz " << endl;
+    *fLog << "Multiplicity: " << fMultiplicity << ",  Discr. threshold: " << fMeanThreshold << endl;
+    *fLog << "Trigger Rate " << fTriggerRate << " +- " << fTriggerRateError << " Hz" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  draw the trigger rate
+//
+void MHMcRate::Draw(Option_t *)
+{
+    *fLog << all << dbginf << " - MHMcRate::Draw: To be iplemented" << endl;
+}
+
Index: /tags/Mars-V0.9/mhistmc/MHMcRate.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcRate.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcRate.h	(revision 9772)
@@ -0,0 +1,99 @@
+#ifndef MARS_MHMcRate
+#define MARS_MHMcRate
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHMcRate : public MParContainer
+{
+
+private:
+    UShort_t fPartId;           // Type of particle
+
+    Float_t fEnergyMax;         // Maximum Energy [TeV]
+    Float_t fEnergyMin;         // Minimum Energy [TeV]
+
+    Float_t fThetaMax;          // Maximum theta angle of run [?]
+    Float_t fThetaMin;          // Minimum theta angle of run [?]
+    Float_t fPhiMax;            // Maximum phi angle of run [?]
+    Float_t fPhiMin;            // Minimum phi angle of run [?]
+
+    Float_t fSolidAngle;        // Solid angle within which incident directions are distributed [sr]
+
+    Float_t fImpactMax;         //[cm] Maximum impact parameter [cm]
+    Float_t fImpactMin;         //[cm] Minimum impact parameter [cm]
+
+    Float_t fBackTrig;          // Number of triggers from background
+    Float_t fBackSim;           // Number of simulated showers for the background
+
+    Float_t fSpecIndex;         // dn/dE = k * e^{- fSpecIndex}
+    Float_t fFlux0;             // dn/dE = fFlux0 * E^{-a}
+
+    Float_t fShowerRate;        // Showers rate in Hz
+    Float_t fShowerRateError;   // Estimated error of shower rate in Hz
+
+    Float_t fTriggerRate;       // Trigger rate in Hz
+    Float_t fTriggerRateError;  // Estimated error for the trigger rate in Hz
+
+    Float_t fMeanThreshold;     // Mean discriminator threshold of trigger pixels [mV]
+
+    Short_t fMultiplicity;      // L1 trigger multiplicity.
+
+    Short_t fTriggerCondNum;    // Trigger condition number, for the case of running over camra files containing several.
+
+    void Init(const char *name, const char *title);
+
+public:
+
+    MHMcRate(const char *name=NULL, const char *title=NULL);
+    MHMcRate(Float_t showrate,
+             const char *name=NULL, const char *title=NULL);
+    MHMcRate(Float_t specindex, Float_t flux0,
+             const char *name=NULL, const char *title=NULL);
+
+    void SetParticle(UShort_t part);
+    void SetBackground(Float_t showers, Float_t triggers);
+    void SetFlux(Float_t flux0, Float_t specindx);
+    void SetIncidentRate(Float_t showerrate);
+
+    void SetImpactMax(Float_t Impact) {fImpactMax=Impact;}
+    void SetImpactMin(Float_t Impact) {fImpactMin=Impact;}
+
+    void SetThetaMax(Float_t Theta) {fThetaMax=Theta;}
+    void SetThetaMin(Float_t Theta) {fThetaMin=Theta;}
+    void SetPhiMax(Float_t Phi) {fPhiMax=Phi;}
+    void SetPhiMin(Float_t Phi) {fPhiMin=Phi;}
+
+    void SetSolidAngle(Float_t Solid) {fSolidAngle=Solid;}
+    void SetEnergyMax(Float_t Energy) {fEnergyMax=Energy;}
+    void SetEnergyMin(Float_t Energy) {fEnergyMin=Energy;}
+
+    void SetMultiplicity(Short_t nMul) {fMultiplicity = nMul;}
+    void SetMeanThreshold(Float_t thresh) {fMeanThreshold = thresh;}
+
+    void SetTriggerCondNum(Short_t num) {fTriggerCondNum = num;}
+
+    void UpdateBoundaries(Float_t energy, Float_t theta, Float_t phi, Float_t impact);
+
+    Float_t GetTriggerRate() {return fTriggerRate;}
+    Float_t GetTriggerRateError() {return fTriggerRateError;}
+
+    Short_t GetMultiplicity() {return fMultiplicity;}
+    Float_t GetMeanThreshold() {return fMeanThreshold;}
+    Short_t GetTriggerCondNum() {return fTriggerCondNum;}
+
+
+    void CalcRate(Float_t trig, Float_t anal, Float_t simu);
+
+    void Print(Option_t *o=NULL) const;
+
+    void Draw(Option_t *o=NULL);
+
+    ClassDef(MHMcRate, 1)  // Data Container to calculate trigger rate
+};
+
+#endif 
+
+
+
Index: /tags/Mars-V0.9/mhistmc/MHMcTriggerLvl2.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcTriggerLvl2.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcTriggerLvl2.cc	(revision 9772)
@@ -0,0 +1,422 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante, 2003 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHMcTriggerLvl2
+//
+// This class contains histograms for the Trigger Level2 image parameters
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MHMcTriggerLvl2.h"
+
+#include <TMath.h>
+
+#include <TH2.h>
+#include <TH1.h>
+#include <TF1.h>
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TPaveLabel.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcTriggerLvl2.h"
+
+using namespace std;
+
+/* Use this insteadif you want to have some value which is the same for all
+ your instances of MHMcTriggerLvl2, if not define the values in the constructor
+ and remove the 'static'
+ */
+
+Int_t MHMcTriggerLvl2::fColorLps = 1;
+Int_t MHMcTriggerLvl2::fColorCps = 1;
+Int_t MHMcTriggerLvl2::fColorSbc = 1;
+Int_t MHMcTriggerLvl2::fColorPs = 1;
+Int_t MHMcTriggerLvl2::fColorPsE = 1;
+Int_t MHMcTriggerLvl2::fColorCPsE = 1;
+Int_t MHMcTriggerLvl2::fColorLPsE = 1;
+Int_t MHMcTriggerLvl2::fColorSBCE = 1;
+
+
+ClassImp(MHMcTriggerLvl2);
+
+// --------------------------------------------------------------------------
+//
+// Setup three histograms for fLutPseudoSize, fPseudoSize, fSizeBiggerCell
+//
+MHMcTriggerLvl2::MHMcTriggerLvl2(const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHMcTriggerLvl2";
+    fTitle = title ? title : "Trigger L2 image parameters";
+
+    fHistLutPseudoSize = new TH1F("fHistLutPseudoSize",  "Lut Pseudo Size",                13,   0, 13);
+    fHistPseudoSize = new TH1F("fHistPseudoSize",   "Pseudo Size",    397,   0, 397);
+    fHistCellPseudoSize = new TH1F("fHistCellPseudoSize",   "Cell Pseudo Size",    37,   0, 37);
+    fHistSizeBiggerCell = new TH1F("fHistSizeBiggerCell",   "Size in Bigger Cell",            37,   0, 37);
+
+    fHistLutPseudoSizeNorm = new TH1F("fHistLutPseudoSizeNorm",  "Normalized Lut Pseudo Size",                13,   0, 13);
+    fHistPseudoSizeNorm = new TH1F("fHistPseudoSizeNorm",   "Normalized Pseudo Size",    397,   0, 397);
+    fHistSizeBiggerCellNorm = new TH1F("fHistSizeBiggerCellNorm",   "Normalized Size in Bigger Cell",            37,   0, 37);
+    fHistCellPseudoSizeNorm = new TH1F("fHistCellPseudoSizeNorm",   "Normalized Cell Pseudo Size",    37,   0, 37);
+
+    fHistLutPseudoSize->SetDirectory(NULL);
+    fHistLutPseudoSizeNorm->SetDirectory(NULL);
+    fHistPseudoSize->SetDirectory(NULL);
+    fHistPseudoSizeNorm->SetDirectory(NULL);
+    fHistSizeBiggerCell->SetDirectory(NULL);
+    fHistSizeBiggerCellNorm->SetDirectory(NULL);
+    fHistCellPseudoSize->SetDirectory(NULL);
+    fHistCellPseudoSizeNorm->SetDirectory(NULL);
+
+    fHistLutPseudoSize->SetXTitle("Number of Pixels");
+    fHistLutPseudoSizeNorm->SetXTitle("Number of Pixels");
+    fHistPseudoSize->SetXTitle("Number of Pixels");
+    fHistPseudoSizeNorm->SetXTitle("Number of Pixels");
+    fHistSizeBiggerCell->SetXTitle("Number of Pixels");
+    fHistSizeBiggerCellNorm->SetXTitle("Number of Pixels");
+    fHistCellPseudoSize->SetXTitle("Number of Pixels");
+    fHistCellPseudoSizeNorm->SetXTitle("Number of Pixels");
+
+    fHistLutPseudoSize->SetYTitle("Counts");
+    fHistLutPseudoSizeNorm->SetYTitle("Counts/Total Counts");
+    fHistPseudoSize->SetYTitle("Counts");
+    fHistPseudoSizeNorm->SetYTitle("Counts/Total Counts");
+    fHistSizeBiggerCell->SetYTitle("Counts");
+    fHistSizeBiggerCellNorm->SetYTitle("Counts/Total Counts");
+    fHistCellPseudoSize->SetYTitle("Counts");
+    fHistCellPseudoSizeNorm->SetYTitle("Counts/Total Counts");
+
+    fHistPseudoSizeEnergy = new TH2D("fHistPseudoSizeEnergy","Ps Size vs Energy", 40, 1, 5, 397, 0,397);
+    fHistCellPseudoSizeEnergy = new TH2D("fHistCellPseudoSizeEnergy","CPS Size vs Energy", 40, 1, 5, 397, 0,397);
+    fHistLutPseudoSizeEnergy = new TH2D("fHistLutPseudoSizeEnergy","Ps Size vs Energy", 40, 1, 5, 397, 0,397);
+    fHistSizeBiggerCellEnergy = new TH2D("fHistSizeBiggerCellEnergy","Ps Size vs Energy", 40, 1, 5, 397, 0,397);
+ 
+    fHistPseudoSizeEnergy->SetName("fHistPseudoSizeEnergy");
+    fHistPseudoSizeEnergy->SetTitle("PseudoSize vs. Energy");
+    fHistPseudoSizeEnergy->SetXTitle("Log(E[GeV])");
+    fHistPseudoSizeEnergy->SetYTitle("PseudoSize");
+
+    fHistCellPseudoSizeEnergy->SetName("fHistCellPseudoSizeEnergy");
+    fHistCellPseudoSizeEnergy->SetTitle("CellPseudoSize vs. Energy");
+    fHistCellPseudoSizeEnergy->SetXTitle("Log(E[GeV])");
+    fHistCellPseudoSizeEnergy->SetYTitle("CellPseudoSize");
+
+    fHistLutPseudoSizeEnergy->SetName("fHistLutPseudoSizeEnergy");
+    fHistLutPseudoSizeEnergy->SetTitle("LutPseudoSize vs. Energy");
+    fHistLutPseudoSizeEnergy->SetXTitle("Log(E[GeV])");
+    fHistLutPseudoSizeEnergy->SetYTitle("LutPseudoSize");
+
+    fHistSizeBiggerCellEnergy->SetName("fHistSizeBiggerCellEnergy");
+    fHistSizeBiggerCellEnergy->SetTitle("Size Bigger Cell vs. Energy");
+    fHistSizeBiggerCellEnergy->SetXTitle("Log(E[GeV])");
+    fHistSizeBiggerCellEnergy->SetYTitle("Size Bigger Cell");
+
+		
+
+		
+    fFNorm = new TF1("FNorm", "1", -1, 397);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms
+//
+MHMcTriggerLvl2::~MHMcTriggerLvl2()
+{
+    delete fHistLutPseudoSize;
+    delete fHistPseudoSize;
+    delete fHistCellPseudoSize;
+    delete fHistSizeBiggerCell;
+    delete fHistLutPseudoSizeNorm;
+    delete fHistPseudoSizeNorm;
+    delete fHistCellPseudoSizeNorm;
+    delete fHistSizeBiggerCellNorm;
+    delete fHistPseudoSizeEnergy;
+    delete fHistCellPseudoSizeEnergy;
+    delete fHistLutPseudoSizeEnergy;
+    delete fHistSizeBiggerCellEnergy;
+    delete fFNorm;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MMcTriggerLvl2-Container.
+// Be careful: Only call this with an object of type MMcTriggerLvl2
+//
+Bool_t MHMcTriggerLvl2::Fill(const MParContainer *par, const Stat_t w)
+{
+  const MMcTriggerLvl2 &h = *(MMcTriggerLvl2 *)par;
+ 
+  fHistLutPseudoSize->Fill(h.GetLutPseudoSize());
+  fHistPseudoSize->Fill(h.GetPseudoSize());
+  fHistCellPseudoSize->Fill(h.GetCellPseudoSize());
+  fHistSizeBiggerCell->Fill(h.GetSizeBiggerCell());
+  fHistPseudoSizeEnergy->Fill(TMath::Log10(h.GetEnergy()), h.GetPseudoSize());
+  fHistCellPseudoSizeEnergy->Fill(TMath::Log10(h.GetEnergy()), h.GetCellPseudoSize());
+  fHistLutPseudoSizeEnergy->Fill(TMath::Log10(h.GetEnergy()), h.GetLutPseudoSize());
+  fHistSizeBiggerCellEnergy->Fill(TMath::Log10(h.GetEnergy()), h.GetSizeBiggerCell());
+
+  return kTRUE;
+}
+
+
+
+
+// --------------------------------------------------------------------------
+//
+// This is the private function member which draw a clone of a histogram. 
+// This method is called by the DrawClone method.
+//
+TObject *MHMcTriggerLvl2::DrawHist(TH1 &hist, TH1 &histNorm, const TString &canvasname, Int_t &col) const
+{
+    col++;
+
+    TCanvas *c = (TCanvas*)gROOT->FindObject(canvasname);
+
+    Bool_t same = kTRUE;
+    if (!c)
+    {
+        c = MakeDefCanvas(canvasname,canvasname, 800, 610);
+        c->Divide(2,1);
+        same = kFALSE;
+    }
+
+    c->cd(1);
+    hist.SetLineColor(col);
+    hist.DrawCopy(same?"same":"");
+
+    c->cd(2);
+    histNorm.SetLineColor(col);
+    histNorm.DrawCopy(same?"same":"");
+
+    return c;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// This is the private function member which draw a clone of a 2D-histogram. 
+// This method is called by the DrawClone method.
+//
+TObject *MHMcTriggerLvl2::Draw2DHist(TH1 &hist, const TString &canvasname, Int_t &col) const
+{
+    col++;
+
+    TCanvas *c = (TCanvas*)gROOT->FindObject(canvasname);
+
+    Bool_t same = kTRUE;
+    if (!c)
+    {
+        c = MakeDefCanvas(canvasname,canvasname, 800, 600);
+        same = kFALSE;
+    }
+
+    hist.SetLineColor(col);
+    hist.DrawCopy(same?"same":"");
+
+    return c;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Draw a clone of a data member histogram. So that the object can be deleted
+// and the histogram is still visible in the canvas.
+// The cloned object are deleted together with the canvas if the canvas is
+// destroyed. If you want to handle dostroying the canvas you can get a
+// pointer to it from this function
+// Possible options are:
+//      "lps" for the fLutPseudoSize histogram;
+//      "sbc" for the fSizeBiggerCell histogram;
+//      "ps" for the fPseudoSize histogram;
+//      "lut-energy" for the fLutPseudoSize vs. energy 2D histogram
+//      "size-energy" for the fPseudoSize vs. energy 2D histogram
+//      "big-energy" for the fSizeBiggerCell vs. energy 2D histogram
+//      
+//      default: "ps"
+//
+TObject *MHMcTriggerLvl2::DrawClone(Option_t *opt) const
+{
+    TString str(opt);
+
+    if (str.IsNull())
+        str = "ps";
+
+    if (!str.Contains("lps", TString::kIgnoreCase) &&
+	!str.Contains("cps", TString::kIgnoreCase) &&
+        !str.Contains("sbc", TString::kIgnoreCase) &&
+        !str.Contains("ps",  TString::kIgnoreCase) &&
+        !str.Contains("lut-energy",  TString::kIgnoreCase) &&
+	!str.Contains("size-energy",  TString::kIgnoreCase) &&
+	!str.Contains("cellsize-energy",  TString::kIgnoreCase) &&
+	!str.Contains("big-energy",  TString::kIgnoreCase))
+    {
+        *fLog << "ARGH!@! Possible options are \"lps\", \"cps\", \"sbc\", \"ps\", \"lut-energy\", \"size-energy\", \"cellsize-energy\", \"big-energy\" or NULL!" <<endl;
+        return NULL;
+    }
+
+    if (str.Contains("lps",TString::kIgnoreCase)){
+      TH1 *hist=NormalizeHist(*fHistLutPseudoSizeNorm, fHistLutPseudoSize);
+      return DrawHist(*fHistLutPseudoSize, *hist, "CanvasLPS", fColorLps);
+    }
+
+    if (str.Contains("cps",TString::kIgnoreCase)){
+      TH1 *hist=NormalizeHist(*fHistCellPseudoSizeNorm, fHistCellPseudoSize);
+      return DrawHist(*fHistCellPseudoSize, *hist, "CanvasCPS", fColorCps);
+    }
+
+    if (str.Contains("sbc",TString::kIgnoreCase)){
+      TH1 *hist=NormalizeHist(*fHistSizeBiggerCellNorm, fHistSizeBiggerCell);
+      return DrawHist(*fHistSizeBiggerCell, *hist, "CanvasSBC", fColorSbc);
+    }
+
+    if (str.Contains("ps",TString::kIgnoreCase)){
+      TH1 *hist=NormalizeHist(*fHistPseudoSizeNorm, fHistPseudoSize);
+      return DrawHist(*fHistPseudoSize, *hist, "CanvasPS", fColorPs);
+    }
+
+    if (str.Contains("size-energy",TString::kIgnoreCase))
+      return Draw2DHist(*fHistPseudoSizeEnergy, "CanvasPSE", fColorPsE);
+
+    if (str.Contains("cellsize-energy",TString::kIgnoreCase))
+      return Draw2DHist(*fHistCellPseudoSizeEnergy, "CanvasCPSE", fColorCPsE);
+
+    if (str.Contains("lut-energy",TString::kIgnoreCase))
+      return Draw2DHist(*fHistLutPseudoSizeEnergy, "CanvasLPSE", fColorLPsE);
+
+    if (str.Contains("big-energy",TString::kIgnoreCase))
+      return Draw2DHist(*fHistSizeBiggerCellEnergy, "CanvasSBCE", fColorSBCE);
+    
+
+    return NULL;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the three histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHMcTriggerLvl2::Draw(Option_t *)
+{
+  MakeDefCanvas("c","L2T Parameters", 720, 810);
+  
+  TPad* pad1 = new TPad("pad1","Pad with fLutPseudoSize", 0.003, 0.7, 0.4, 0.997);
+  TPad* pad2 = new TPad("pad2","Pad with fSizeBiggerCell", 0.403, 0.7, 0.997, 0.997);
+  TPad* pad3 = new TPad("pad3","Pad with fPseudoSize", 0.003, 0.003, 0.997, 0.697);
+  pad1->Draw();
+  pad2->Draw();
+  pad3->Draw();
+  
+  pad1->cd();
+  fHistLutPseudoSize->Draw();
+  
+  pad2->cd();
+  fHistSizeBiggerCell->Draw();
+  
+  pad3->cd();
+  fHistPseudoSize->Draw();
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Return the histogram by its name. This method returns a (TObject *)
+//  so remember to cast the returned object if you want to work with it.
+//
+TH1 *MHMcTriggerLvl2::GetHistByName(const TString name)
+{
+  
+    if (name.Contains("fHistLutPseudoSizeEnergy", TString::kIgnoreCase))
+	return fHistLutPseudoSizeEnergy;
+    if (name.Contains("fHistSizeBiggerCellEnergy", TString::kIgnoreCase))
+        return fHistSizeBiggerCellEnergy;
+    if (name.Contains("fHistPseudoSizeEnergy", TString::kIgnoreCase))
+        return fHistPseudoSizeEnergy;
+    if (name.Contains("fHistCellPseudoSizeEnergy", TString::kIgnoreCase))
+        return fHistCellPseudoSizeEnergy;
+
+    if (name.Contains("fHistLutPseudoSizeNorm", TString::kIgnoreCase))
+      return fHistLutPseudoSizeNorm;
+    if (name.Contains("fHistSizeBiggerCellNorm", TString::kIgnoreCase))
+        return fHistSizeBiggerCellNorm;
+    if (name.Contains("fHistPseudoSizeNorm", TString::kIgnoreCase))
+        return fHistPseudoSizeNorm;
+    if (name.Contains("fHistCellPseudoSizeNorm", TString::kIgnoreCase))
+        return fHistCellPseudoSizeNorm;
+	    
+    if (name.Contains("fHistLutPseudoSize", TString::kIgnoreCase))
+      return fHistLutPseudoSize;
+    if (name.Contains("fHistSizeBiggerCell", TString::kIgnoreCase))
+        return fHistSizeBiggerCell;
+    if (name.Contains("fHistPseudoSize", TString::kIgnoreCase))
+        return fHistPseudoSize;
+    if (name.Contains("fHistCellPseudoSize", TString::kIgnoreCase))
+        return fHistCellPseudoSize;
+
+    
+    return NULL;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Normalize the histogram on its integral, i.e.  normalize the
+// values of the histogram on the statistics. This method creates
+// a copy (histNorm) of the histogram to normalize (hist) and normalize
+// the copy (histNorm) on its integral. It returns histNorm.
+//
+TH1 *MHMcTriggerLvl2::NormalizeHist(TH1 &histNorm, TH1 *hist) const
+{
+  if (&histNorm == hist){
+    *fLog << "ARGH!@! You cannot pass the same histogram into each argument!" << endl;
+    return NULL;
+  }
+
+  if ((hist == NULL) || (hist->Integral() == (Stat_t)0)){
+    *fLog << "ARGH!@! You are trying to normalize the histogram to 0!" << endl;
+    return NULL;
+  }
+  
+  histNorm.Reset("ICE");
+  histNorm.Add(hist, 1);
+  histNorm.Divide(fFNorm, (Double_t)(hist->Integral()));
+
+  return &histNorm;
+}
Index: /tags/Mars-V0.9/mhistmc/MHMcTriggerLvl2.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcTriggerLvl2.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcTriggerLvl2.h	(revision 9772)
@@ -0,0 +1,74 @@
+#ifndef MARS_MHMcTriggerLvl2
+#define MARS_MHMcTriggerLvl2
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH2D;
+class TH1F;
+class TF1;
+class MMcTriggerLvl2;
+
+class MHMcTriggerLvl2 : public MH
+{
+private:
+
+    TH1F *fHistLutPseudoSize;        // Histogram of fLutPseudoSize
+    TH1F *fHistLutPseudoSizeNorm;    // Histogram of fLutPseudoSize normalized on integral of distribution
+    TH1F *fHistPseudoSize;           // Histogram of fPseudoSize
+    TH1F *fHistPseudoSizeNorm;       // Histogram of fPseudoSize normalized on integral of distribution
+    TH1F *fHistCellPseudoSize;           // Histogram of fCellPseudoSize
+    TH1F *fHistCellPseudoSizeNorm;       // Histogram of fCellPseudoSize normalized on integral of distribution
+    TH1F *fHistSizeBiggerCell;       // Histogram of fSizeBiggerCell
+    TH1F *fHistSizeBiggerCellNorm;   // Histogram of fSizeBiggerCell normalized on integral of distribution
+    TH2D *fHistPseudoSizeEnergy;     // 2D-Histogram of fPseudoSize vs. Energy
+    TH2D *fHistLutPseudoSizeEnergy;  // 2D-Histogram of fLutPseudoSize vs. Energy
+    TH2D *fHistCellPseudoSizeEnergy;  // 2D-Histogram of fCellPseudoSize vs. Energy
+    TH2D *fHistSizeBiggerCellEnergy; // 2D-Histogram of fSizeBiggerCell vs. Energy
+    TF1* fFNorm;                     // Function used to normalize histograms
+
+    static Int_t fColorLps;
+    static Int_t fColorSbc;
+    static Int_t fColorPs;
+    static Int_t fColorCps;
+    static Int_t fColorPsE;
+    static Int_t fColorLPsE;
+    static Int_t fColorCPsE;
+    static Int_t fColorSBCE;
+    
+
+    TObject *DrawHist(TH1 &hist, TH1 &histNorm, const TString &canvasname, Int_t &colore) const;
+    TObject *Draw2DHist(TH1 &hist, const TString &canvasname, Int_t &col) const;
+    
+public:
+    MHMcTriggerLvl2(const char *name=NULL, const char *title=NULL);
+    ~MHMcTriggerLvl2();
+
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name);
+
+    TH1F *GetHistLutPseudoSize() const { return fHistLutPseudoSize; }
+    TH1F *GetHistLutPseudoSizeNorm() const { return fHistLutPseudoSizeNorm; }
+    TH1F *GetHistPseudoSize()  const { return fHistPseudoSize; }
+    TH1F *GetHistPseudoSizeNorm()  const { return fHistPseudoSizeNorm; }
+    TH1F *GetHistCellPseudoSize()  const { return fHistCellPseudoSize; }
+    TH1F *GetHistCellPseudoSizeNorm()  const { return fHistCellPseudoSizeNorm; }
+    TH1F *GetHistSizeBiggerCell()  const { return fHistSizeBiggerCell; }
+    TH1F *GetHistSizeBiggerCellNorm()  const { return fHistSizeBiggerCellNorm; }
+    TH2D *GetHistLutPseudoSizeEnergy() const { return fHistLutPseudoSizeEnergy; }
+    TH2D *GetHistPseudoSizeEnergy() const { return fHistPseudoSizeEnergy; }
+    TH2D *GetHistSizeBiggerCellEnergy() const { return fHistSizeBiggerCellEnergy; }
+    
+
+    void Draw(Option_t *opt=NULL);
+    TObject *DrawClone(Option_t *opt=NULL) const;
+
+    TH1 *NormalizeHist(TH1 &histNorm, TH1 *hist) const;
+
+    ClassDef(MHMcTriggerLvl2, 1) // Container which holds histograms for the Trigger Level2 image parameters
+};
+
+
+#endif
Index: /tags/Mars-V0.9/mhistmc/MHMcUnfoldCoeff.cc
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcUnfoldCoeff.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcUnfoldCoeff.cc	(revision 9772)
@@ -0,0 +1,352 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     02/2005 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHMcUnfoldCoeff
+// Container that stores the coefficients to convert from estimated to real
+// (unfolded) energy. 
+// It is filled by MMcUnfoldCoeffCalc
+// Events are weighted from any initial spectrum to a tentative spectrum
+// that must be set through MMcUnfoldCoeffCalc::SetSpectrum method.
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <math.h>
+
+#include "TH1D.h"
+#include "TH2D.h"
+#include "TF1.h"
+#include "TCanvas.h"
+#include "TArrayD.h"
+
+#include "MHMcUnfoldCoeff.h"
+
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHMcUnfoldCoeff);
+
+using namespace std;
+
+
+// -------------------------------------------------------------------------
+//
+// Constructor: Define and configure the different histograms to be filled
+//
+MHMcUnfoldCoeff::MHMcUnfoldCoeff(const char *name, const char *title) :
+  fNsubbins(20), fEmin(1.), fEmax(100000.), fNumMin(10), fFineBinning(NULL)
+{
+  fName  = name  ? name  : "MHMcUnfoldCoeff";
+  fTitle = title ? title : "Unfolding Coefficients vs. Theta vs. Energy";
+
+  // define histos
+  fHistAll    = new TH1D(); 
+  fHistWeight = new TH1D(); 
+  fHistMcE    = new TH2D();
+  fHistEstE   = new TH2D();
+  fHistCoeff  = new TH2D();
+
+  // set histo names
+  fHistAll->SetName("AllEvents");
+  fHistWeight->SetName("Weights");
+  fHistMcE->SetName("MCEnergy");
+  fHistEstE->SetName("EstimatedEnergy");
+  fHistCoeff->SetName("UnfoldCoeff");
+
+  // set histo titles
+  fHistAll->SetTitle("MC energy for all generated events");
+  fHistWeight->SetTitle("Weights");
+  fHistMcE->SetTitle("MC energy for survivors");
+  fHistEstE->SetTitle("Estimate energy for survivors");
+  fHistCoeff->SetTitle(fTitle);
+
+  // histos directory
+  fHistAll->SetDirectory(NULL);
+  fHistWeight->SetDirectory(NULL);
+  fHistMcE->SetDirectory(NULL);
+  fHistEstE->SetDirectory(NULL);
+  fHistCoeff->SetDirectory(NULL);
+
+  // histos style
+  fHistAll->UseCurrentStyle();
+  fHistWeight->UseCurrentStyle();
+  fHistMcE->UseCurrentStyle();
+  fHistEstE->UseCurrentStyle();
+  fHistCoeff->UseCurrentStyle();
+
+  // labels
+  fHistAll->SetXTitle("E [GeV]");
+  fHistWeight->SetXTitle("E [GeV]");
+  fHistMcE->SetXTitle("E_{MC} [GeV]");
+  fHistEstE->SetXTitle("E_{est} [GeV]");
+  fHistCoeff->SetXTitle("E_{est} [GeV]");
+
+  fHistWeight->SetYTitle("weight");
+  fHistMcE->SetYTitle("\\theta [\\circ]");
+  fHistEstE->SetYTitle("\\theta [\\circ]");
+  fHistCoeff->SetYTitle("\\theta [\\circ]");
+
+  fHistMcE->SetZTitle("weighted entries");
+  fHistEstE->SetZTitle("weighted entries");
+  fHistCoeff->SetZTitle("Coefficient");
+}
+
+// -------------------------------------------------------------------------
+//
+// Destructor: Delete all the histograms
+//
+MHMcUnfoldCoeff::~MHMcUnfoldCoeff()
+{
+  delete fHistAll;
+  delete fHistWeight;
+  delete fHistMcE;
+  delete fHistEstE;
+  delete fHistCoeff;
+
+  if(fFineBinning) 
+    delete fFineBinning;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the histograms binning. The coarse binning has to be provided
+// from outside (in the parameter list) whereas the fine binning for
+// energy is computed from the former.
+// The subbinning is set logarithmicaly (linearly) for a logarithmic
+// (linear) coarse binning. 
+// It is extended down to fEmin and up to fEmax
+// The number of subbins per coarse bins may be changed using
+// SetNsubbins() method
+// The maximum and minimum energies of the fine binning histograms
+// may be changed with the SetEmin() and SetEmax() methods
+//
+void MHMcUnfoldCoeff::SetCoarseBinnings(const MBinning &binsEnergy, 
+					const MBinning &binsTheta)
+{
+  // set histo binning (for coarse bin histos)
+  MH::SetBinning(fHistMcE,&binsEnergy,&binsTheta);
+  MH::SetBinning(fHistEstE,&binsEnergy,&binsTheta);
+  MH::SetBinning(fHistCoeff,&binsEnergy,&binsTheta);
+
+  // good errors
+  fHistMcE->Sumw2();
+  fHistEstE->Sumw2();
+
+  // define fine binning from coarse one
+  const Int_t nbins = binsEnergy.GetNumBins();
+  const TArrayD edges = binsEnergy.GetEdgesD();
+  const Bool_t isLinear = binsEnergy.IsLinear();
+
+  // compute bins needed to extend down to fEmin and up to fEmax
+  Double_t dedown, deup;
+  Int_t binsdown,binsup;
+  MBinning dbin;
+  MBinning ubin;
+  if(isLinear)
+    {
+      dedown   = (edges[1]-edges[0])/fNsubbins;
+      deup     = (edges[nbins]-edges[nbins-1])/fNsubbins;      
+      binsdown = (fEmin<edges[0])     ? Int_t((edges[0]-fEmin)/dedown) : 0;
+      binsup   = (fEmax>edges[nbins]) ? Int_t((fEmax-edges[nbins])/deup) : 0;
+      if(binsdown) dbin.SetEdges(binsdown,fEmin,edges[0]);
+      if(binsup)   ubin.SetEdges(binsup,edges[nbins],fEmax);
+    }
+  else
+    {
+      dedown   = (TMath::Log10(edges[1])-TMath::Log10(edges[0]))/fNsubbins;
+      deup     = (TMath::Log10(edges[nbins])-TMath::Log10(edges[nbins-1]))/fNsubbins;
+      binsdown = (fEmin<edges[0])    ? Int_t((TMath::Log10(edges[0])-TMath::Log10(fEmin))/dedown) : 0;
+      binsup   = (fEmax>edges[nbins])? Int_t((TMath::Log10(fEmax)-TMath::Log10(edges[nbins]))/deup) : 0;
+      if(binsdown) dbin.SetEdgesLog(binsdown,fEmin,edges[0]);
+      if(binsup)   ubin.SetEdgesLog(binsup,edges[nbins],fEmax);
+    }
+  
+  // fill the subins' edges
+  TArrayD fineedges(binsdown+nbins*fNsubbins+binsup+1);
+
+  for(Int_t i=0;i<binsdown;i++)
+    fineedges[i] = dbin.GetEdgesD().At(i);
+
+  for(Int_t i=0;i<nbins;i++)
+    {
+      MBinning coarb;
+      if(isLinear)
+	coarb.SetEdges(fNsubbins,edges[i],edges[i+1]);
+      else
+	coarb.SetEdgesLog(fNsubbins,edges[i],edges[i+1]);
+      
+      for(Int_t j=0;j<fNsubbins;j++)
+	fineedges[binsdown+i*fNsubbins+j] = coarb.GetEdgesD().At(j);
+    }  
+
+  for(Int_t i=0;i<binsup;i++)
+    fineedges[binsdown+nbins*fNsubbins+i] = ubin.GetEdgesD().At(i);
+  
+  fineedges[binsdown+nbins*fNsubbins+binsup] = binsup ? ubin.GetEdgesD().At(binsup): edges[nbins];
+
+  // define fine binning object
+  fFineBinning = new MBinning;
+  fFineBinning->SetEdges(fineedges);
+
+  // apply fine binning to histograms that need it
+  fFineBinning->Apply(*fHistAll);
+  fFineBinning->Apply(*fHistWeight);  
+}
+
+// -------------------------------------------------------------------------
+//
+// Compute the weights for a particular tentative spectrum.
+// For each energy (fine) bin we compute it as the value of the input function
+// divided by the number of entries in the actual energy histogram.
+// First and last bin are not filled since they could be biased
+//
+void MHMcUnfoldCoeff::ComputeWeights(TF1* spectrum)
+{  
+  Bool_t first=kTRUE;
+  Int_t  lastb=0;
+  for(Int_t i=0;i<fHistAll->GetNbinsX();i++)
+    {
+      const Float_t denom = fHistAll->GetBinContent(i+1); // number of events in initial spectrum
+      const Float_t ew    = fHistAll->GetBinCenter(i+1);  // energy associated to the bin
+      const Float_t numer = spectrum->Eval(ew);           // number of events for the required spectrum
+
+      if(denom>fNumMin)
+	{
+	  // do not fill it if it is the first one
+	  if(first)
+	    {
+	      fHistWeight->SetBinContent(i+1,-1);
+	      first=kFALSE;
+	    }
+	  else
+	    {
+	      fHistWeight->SetBinContent(i+1,numer/denom);	
+	      lastb=i+1;
+	    }
+	}
+      else
+	fHistWeight->SetBinContent(i+1,-1);
+    }
+
+  //remove last filled bin
+  if(lastb)
+    fHistWeight->SetBinContent(lastb,-1);
+}
+
+// --------------------------------------------------------------
+//
+// Compute the coefficients used for the (iterative) unfolding
+// The coefficients are the ratio between the contents of the
+// mc energy and estimate energy histograms (filled with weighted
+// events
+// Errors are computed as if estimated and MC energy histos where
+// uncorrelated
+//
+void MHMcUnfoldCoeff::ComputeCoefficients()
+{ 
+  for(Int_t j=0;j<fHistEstE->GetNbinsY();j++)
+    for(Int_t i=0;i<fHistEstE->GetNbinsX();i++)
+      {
+	const Float_t num = fHistMcE->GetBinContent(i+1,j+1);	
+	const Float_t den = fHistEstE->GetBinContent(i+1,j+1);
+		
+	if(den>0)
+	  {	    
+	    const Float_t cf  = num/den;
+	    fHistCoeff->SetBinContent(i+1,j+1,cf);
+
+	    if(num>0)
+	      {
+		const Float_t ernum = fHistMcE->GetBinError(i+1,j+1);
+		const Float_t erden = fHistEstE->GetBinError(i+1,j+1);
+		const Float_t ercf  = cf*(TMath::Sqrt(ernum/num*ernum/num+erden/den*erden/den));
+		fHistCoeff->SetBinError(i+1,j+1,ercf);
+	      }
+	    else
+	      fHistCoeff->SetBinError(i+1,j+1,0);		  
+	  }
+	else
+	  {
+	    *fLog << warn << "MHMcUnfoldCoeff::ComputeCoefficients Warning: energy bin " << i << ", thetabin " << j << " has no survivors, setting coefficient to 0" << endl;
+	    fHistCoeff->SetBinContent(i+1,j+1,0.);
+	    fHistCoeff->SetBinError(i+1,j+1,0.);
+	  }
+      }
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains all showers
+//
+void MHMcUnfoldCoeff::FillAll(Double_t energy)
+{
+  fHistAll->Fill(energy);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histograms which contain survivors
+// each event is introduced with a weight depending on its (MC) energy
+//
+void MHMcUnfoldCoeff::FillSel(Double_t mcenergy,Double_t estenergy,Double_t theta)
+{
+  // bin of the corresponding weight
+  const Int_t wbin = fFineBinning->FindHiEdge(mcenergy);
+
+  if(wbin>0)
+    {
+      // weight
+      const Double_t weight = fHistWeight->GetBinContent(wbin);
+      
+      if(weight>0)
+	{
+	  fHistMcE->Fill(mcenergy,theta,weight);
+	  fHistEstE->Fill(estenergy,theta,weight);
+	}
+      //      else
+	//	*fLog << warn << "MHMcUnfoldCoeff::FillSel Warning: event with energy " << mcenergy << " has no computed weight (lack of MC statistics), skipping" << endl;
+    }
+  // the event has an energy out of the considered range
+  else
+    *fLog << warn << "MHMcUnfoldCoeff::FillSel Warning: event with energy " << mcenergy << " has energy out of bounds, skipping" << endl;   
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw
+//
+void MHMcUnfoldCoeff::Draw(Option_t* option)
+{
+  TCanvas *c1 = new TCanvas();  
+  c1->SetLogx();
+  c1->SetLogy();
+  c1->SetGridx();
+  c1->SetGridy();
+
+  fHistCoeff->Draw("");
+}
+
Index: /tags/Mars-V0.9/mhistmc/MHMcUnfoldCoeff.h
===================================================================
--- /tags/Mars-V0.9/mhistmc/MHMcUnfoldCoeff.h	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/MHMcUnfoldCoeff.h	(revision 9772)
@@ -0,0 +1,59 @@
+#ifndef MARS_MHMcUnfoldCoeff
+#define MARS_MHMcUnfoldCoeff
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TF1;
+class TH1D;
+class TH2D;
+class MBinning;
+
+class MHMcUnfoldCoeff : public MH
+{
+ private:
+
+  TH1D* fHistAll;    // histogram of all events (fine bins)
+  TH1D* fHistWeight; // histogram of weights    (fine bins)
+
+  TH2D* fHistMcE;    // histogram of MC energy for survivors (coarse bins)
+  TH2D* fHistEstE;   // histogram of estimated energy for survivors (coarse bins)
+  TH2D* fHistCoeff;  // histogram of coefficients for iterative unfolding
+
+  Int_t fNsubbins;   // number of subbins per coarse bin
+  Double_t fEmin;    // [GeV] absolute minimum energy where weights are computed
+  Double_t fEmax;    // [GeV] absolute maximum energy where weights are computed
+  Int_t fNumMin;     // minimum number of events in a fine bin required to compute the weight
+
+  MBinning* fFineBinning; // fine binning (used for weights)
+  
+ public:
+
+  MHMcUnfoldCoeff(const char *name=NULL, const char *title=NULL);
+
+  virtual ~MHMcUnfoldCoeff();
+
+  void FillAll(Double_t energy);
+  void FillSel(Double_t mcenergy,Double_t estenergy,Double_t theta);
+  void Draw(Option_t* option="");
+  void ComputeWeights(TF1* spectrum);
+  void ComputeCoefficients();
+
+  void SetCoarseBinnings(const MBinning& binsEnergy,const MBinning& binsTheta);
+  void SetNsubbins(Int_t n)   {fNsubbins=n;}
+  void SetEmax(Double_t emax) {fEmax=emax;}
+  void SetEmin(Double_t emin) {fEmin=emin;}
+  void SetNumMin(Int_t n)     {fNumMin=n;}
+    
+  const TH1D* GetHistAll()    const {return fHistAll;}
+  const TH1D* GetHistWeight() const {return fHistWeight;}
+  const TH2D* GetHistMcE()    const {return fHistMcE;}
+  const TH2D* GetHistEstE()   const {return fHistEstE;}
+  const TH2D* GetHistCoeff()  const {return fHistCoeff;}
+
+  ClassDef(MHMcUnfoldCoeff, 1) // Data Container to store Unfolding Coefficients
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mhistmc/Makefile
===================================================================
--- /tags/Mars-V0.9/mhistmc/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mhistmc/Makefile	(revision 9772)
@@ -0,0 +1,44 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HistMc
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mhist -I../mmc -I../manalysis \
+    	   -I../mimage -I../mgeom -I../mgui
+
+SRCFILES = MHMcEnergy.cc \
+           MHMcEfficiency.cc \
+           MHMcEfficiencyImpact.cc \
+           MHMcEfficiencyEnergy.cc \
+           MHMcEnergyImpact.cc \
+	   MHMcRate.cc \
+	   MHMcCollectionArea.cc \
+           MHMcIntRate.cc \
+           MHMcDifRate.cc \
+           MHMcEnergyMigration.cc \
+	   MHMcCT1CollectionArea.cc \
+	   MHMcTriggerLvl2.cc \
+	   MHMcUnfoldCoeff.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mhvstime/HVsTimeIncl.h
===================================================================
--- /tags/Mars-V0.9/mhvstime/HVsTimeIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/HVsTimeIncl.h	(revision 9772)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mhvstime/HVsTimeLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mhvstime/HVsTimeLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/HVsTimeLinkDef.h	(revision 9772)
@@ -0,0 +1,11 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MHVsTime+;
+#pragma link C++ class MHPixVsTime+;
+#pragma link C++ class MHSectorVsTime+;
+
+#endif
Index: /tags/Mars-V0.9/mhvstime/MHPixVsTime.cc
===================================================================
--- /tags/Mars-V0.9/mhvstime/MHPixVsTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/MHPixVsTime.cc	(revision 9772)
@@ -0,0 +1,253 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPixVsTime
+//
+// Display the pixel content versus time or event number
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given the rule for the y-axis is used.
+// 2) If the MH3 has a non-default title (MH3::SetTitle called)
+//    this title is set as the histogram title. It can be used to overwrite
+//    the axis titles. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyGraph;;Counts");
+//    The title for the x-axis is ignored and set automatically (MAKE SURE
+//    YOU HAVE TWO SEMICOLON!)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPixVsTime.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+
+#include "MGeomCam.h"
+
+#include "MRawEvtHeader.h"
+#include "MTime.h"
+
+ClassImp(MHPixVsTime);
+
+using namespace std;
+
+const TString MHPixVsTime::gsDefName  = "MHPixVsTime";
+const TString MHPixVsTime::gsDefTitle = "Graph of pixel content vs. time";
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task.
+//
+MHPixVsTime::MHPixVsTime(Int_t idx, const char *name, const char *title)
+    : fIndex(idx), fEvt(NULL), fType(0), fTypeErr(-1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    TString t("Pixel Index #");
+    t += idx;
+    t += " vs Time";
+
+    fGraph = new TGraphErrors;
+    fGraph->SetName("MCamEvent");
+    fGraph->SetTitle(t);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHPixVsTime::~MHPixVsTime()
+{
+    if (fGraph)
+        delete fGraph;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the TGraph and the MHPixVsTime container
+//
+void MHPixVsTime::SetName(const char *name)
+{
+    fGraph->SetName(name);
+    MParContainer::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the TGraph and the MHPixVsTime container
+//
+void MHPixVsTime::SetTitle(const char *title)
+{
+    fGraph->SetTitle(title);
+    MParContainer::SetTitle(title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MPixVsTime) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+//
+Bool_t MHPixVsTime::SetupFill(const MParList *plist)
+{
+    fEvt = (MCamEvent*)plist->FindObject(fNameEvt, "MCamEvent");
+    if (!fEvt)
+    {
+        if (!fNameEvt.IsNull())
+        {
+            *fLog << err << GetDescriptor() << ": No " << fNameEvt <<" [MCamEvent] available..." << endl;
+            return kFALSE;
+        }
+        *fLog << warn << GetDescriptor() << ": No MCamEvent available..." << endl;
+    }
+
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fNameTime.IsNull())
+    {
+        fTime = (MTime*)plist->FindObject(fNameTime, "MTime");
+        if (!fTime)
+        {
+            *fLog << err << fNameTime << " [MTime] not found... abort." << endl;
+            return kFALSE;
+        }
+    }
+    else
+    {
+        fHeader = (MRawEvtHeader*)plist->FindObject("MRawEvtHeader");
+        if (!fHeader)
+            *fLog << warn << "MRawEvtHeader not found... using counter." << endl;
+    }
+
+    if (fTitle!=gsDefTitle)
+        fGraph->SetTitle(fTitle);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MPixVsTime-Container.
+//
+Bool_t MHPixVsTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MCamEvent *evt = par ? dynamic_cast<const MCamEvent*>(par) : fEvt;
+    if (!evt)
+    {
+        *fLog << err << dbginf << "No MCamEvent found..." << endl;
+        return kFALSE;
+    }
+
+    Double_t val = 0;
+    Double_t rms = 0;
+    evt->GetPixelContent(val, fIndex, *fCam, fType);
+    if (TMath::IsNaN(val))
+        return kCONTINUE;
+
+    Double_t t = 0;
+    if (!fNameTime.IsNull())
+        t = fTime->GetAxisTime();
+    else
+        t = fHeader ? fHeader->GetDAQEvtNumber() : fGraph->GetN();
+
+    fGraph->SetPoint(fGraph->GetN(), t, val);
+
+    if (fTypeErr>=0)
+    {
+        evt->GetPixelContent(rms, fIndex, *fCam, fType);
+        if (TMath::IsNaN(rms))
+            return kCONTINUE;
+    }
+
+    fGraph->SetPointError(fGraph->GetN()-1, 0, rms);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return histogram of TGraph
+//
+TH1 *MHPixVsTime::GetHistByName(const TString name)
+{
+    return fGraph->GetHistogram();
+}
+
+void MHPixVsTime::Draw(Option_t *opt)
+{
+
+    if (fGraph->GetN()==0)
+        return;
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString str(opt);
+
+    TH1 *h = fGraph->GetHistogram();
+
+    h->SetXTitle("Time");
+    if (!fNameTime.IsNull())
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+        axe->SetTimeDisplay(1);
+        axe->SetLabelSize(0.033);
+    }
+
+
+    if (!str.Contains("A"))
+        str += "A";
+    if (!str.Contains("P"))
+        str += "P";
+
+    if (str.Contains("same", TString::kIgnoreCase))
+    {
+        str.ReplaceAll("same", "");
+        str.ReplaceAll("A", "");
+    }
+
+    fGraph->Draw(str);
+
+    pad->Modified();
+    pad->Update();
+}
Index: /tags/Mars-V0.9/mhvstime/MHPixVsTime.h
===================================================================
--- /tags/Mars-V0.9/mhvstime/MHPixVsTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/MHPixVsTime.h	(revision 9772)
@@ -0,0 +1,65 @@
+#ifndef MARS_MHPixVsTime
+#define MARS_MHPixVsTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TGraphErrors
+#include <TGraphErrors.h>
+#endif
+
+class MHCamera;
+class MCamEvent;
+class MGeomCam;
+
+class MRawEvtHeader;
+class MTime;
+
+class MHPixVsTime : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    TGraphErrors *fGraph;
+    Int_t fIndex;
+
+    MCamEvent *fEvt; //! the current event
+    MGeomCam  *fCam; //! the camera geometry
+
+    MRawEvtHeader *fHeader; //!
+    MTime         *fTime;   //!
+
+    TString fNameEvt;
+    TString fNameTime;
+
+    Int_t fType;
+    Int_t fTypeErr;
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+public:
+    MHPixVsTime(Int_t idx=0, const char *name=NULL, const char *title=NULL);
+    ~MHPixVsTime();
+
+    void SetNameEvt(const TString name) { fNameEvt = name; }
+    void SetNameTime(const TString name) { fNameTime = name; }
+    void SetType(Int_t type, Int_t e=-1) { fType = type; fTypeErr=e; }
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    TH1 *GetHistByName(const TString name="");
+    TGraph *GetGraph() { return fGraph; }
+
+    void Draw(Option_t *o=NULL);
+
+    ClassDef(MHPixVsTime, 1) // Histogram to sum camera events
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/mhvstime/MHSectorVsTime.cc
===================================================================
--- /tags/Mars-V0.9/mhvstime/MHSectorVsTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/MHSectorVsTime.cc	(revision 9772)
@@ -0,0 +1,277 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHSectorVsTime
+//
+// Display the mean and its variance vs time of the whole camera or a
+// single sector
+//
+// 1) If no other title is given the rule for the y-axis is used.
+// 2) If the MH3 has a non-default title (MH3::SetTitle called)
+//    this title is set as the histogram title. It can be used to overwrite
+//    the axis titles. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyGraph;;Counts");
+//    The title for the x-axis is ignored and set automatically (MAKE SURE
+//    YOU HAVE TWO SEMICOLON!)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHSectorVsTime.h"
+
+#include <TCanvas.h>
+#include <TGraphErrors.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+
+#include "MGeomCam.h"
+
+#include "MRawEvtHeader.h"
+#include "MTime.h"
+
+ClassImp(MHSectorVsTime);
+
+using namespace std;
+
+const TString MHSectorVsTime::gsDefName  = "MSectorHVsTime";
+const TString MHSectorVsTime::gsDefTitle = "Graph of sector mean vs. time";
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task. If fErrType>=0 the variance is
+// taken into account.
+//
+MHSectorVsTime::MHSectorVsTime(const char *name, const char *title)
+    : fGraph(0), fEvt(NULL), fType(0), fTypeErr(-1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the fGraph
+//
+MHSectorVsTime::~MHSectorVsTime()
+{
+    if (fGraph)
+        delete fGraph;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the TGraph and the MHVsTime container
+//
+void MHSectorVsTime::SetName(const char *name)
+{
+    fGraph->SetName(name);
+    MParContainer::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the TGraph and the MHVsTime container
+//
+void MHSectorVsTime::SetTitle(const char *title)
+{
+    fGraph->SetTitle(title);
+    MParContainer::SetTitle(title);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the event (MPixVsTime) the histogram might be filled with. If
+// it is not given, it is assumed, that it is filled with the argument
+// of the Fill function.
+// Looks for the camera geometry MGeomCam and resets the sum histogram.
+// Create and/or initialize fGraph
+//
+Bool_t MHSectorVsTime::SetupFill(const MParList *plist)
+{
+    fEvt = dynamic_cast<MCamEvent*>(plist->FindObject(fNameEvt, "MCamEvent"));
+    if (!fEvt)
+    {
+        if (!fNameEvt.IsNull())
+        {
+            *fLog << err << GetDescriptor() << ": No " << fNameEvt <<" [MCamEvent] available..." << endl;
+            return kFALSE;
+        }
+        *fLog << warn << GetDescriptor() << ": No MCamEvent available..." << endl;
+    }
+
+    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHCamera.SetGeometry(*fCam);
+
+    if (!fNameTime.IsNull())
+    {
+        fTime = (MTime*)plist->FindObject(fNameTime, "MTime");
+        if (!fTime)
+        {
+            *fLog << err << fNameTime << " [MTime] not found... abort." << endl;
+            return kFALSE;
+        }
+    }
+    else
+    {
+        fHeader = (MRawEvtHeader*)plist->FindObject("MRawEvtHeader");
+        if (!fHeader)
+            *fLog << warn << "MRawEvtHeader not found... using counter." << endl;
+    }
+
+    if (fGraph)
+        delete fGraph;
+
+    fGraph = fTypeErr<0 ? new TGraph : new TGraphErrors;
+    fGraph->SetName(fEvt ? dynamic_cast<TObject*>(fEvt)->GetName() : "MCamEvent");
+    fGraph->SetTitle(fTitle==gsDefTitle?"Camera":fTitle.Data());
+
+    fMin =  FLT_MAX;
+    fMax = -FLT_MAX;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MCamEvent
+//
+Bool_t MHSectorVsTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MCamEvent *evt = par ? dynamic_cast<const MCamEvent*>(par) : fEvt;
+    if (!evt)
+    {
+        *fLog << err << dbginf << "No MCamEvent found..." << endl;
+        return kFALSE;
+    }
+
+    Double_t t = 0;
+    if (!fNameTime.IsNull())
+        t = fTime->GetAxisTime();
+    else
+        t = fHeader ? fHeader->GetDAQEvtNumber() : fGraph->GetN();
+
+
+    fHCamera.SetCamContent(*evt, fType);
+
+    const Double_t val0 = fHCamera.GetMeanSectors(fSectors, fAreaIndex);
+
+    if (TMath::IsNaN(val0)/* || TMath::IsNaN(rms0)*/)
+        return kCONTINUE;
+
+    fGraph->SetPoint(fGraph->GetN(), t, val0);
+
+    if (fTypeErr>=0)
+    {
+        const Double_t rms0 = fHCamera.GetRmsSectors(fSectors, fAreaIndex);
+        if (TMath::IsNaN(rms0))
+            return kCONTINUE;
+        ((TGraphErrors*)fGraph)->SetPointError(fGraph->GetN()-1, 0, rms0);
+    }
+
+    fMin = TMath::Min(fMin, val0);
+    fMax = TMath::Max(fMax, val0);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set Minimum and Maximum;
+//
+Bool_t MHSectorVsTime::Finalize()
+{
+    const Double_t add = (fMax-fMin)*0.15;
+
+    fGraph->SetMinimum(fMin-add);
+    fGraph->SetMaximum(fMax+add);
+
+    *fLog << dbg << "Min=" << fMin << " " << fMin-add << endl;
+    *fLog << dbg << "Max=" << fMax << " " << fMax+add << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return fHistogram from TGraph
+//
+TH1 *MHSectorVsTime::GetHistByName(const TString name)
+{
+    return fGraph->GetHistogram();
+}
+
+void MHSectorVsTime::Draw(Option_t *opt)
+{
+    if (!fGraph)
+        return;
+
+    if (fGraph->GetN()==0)
+        return;
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString str(opt);
+
+    if (!str.Contains("A"))
+        str += "A";
+    if (!str.Contains("L"))
+        str += "L";
+
+    if (str.Contains("same", TString::kIgnoreCase))
+    {
+        str.ReplaceAll("same", "");
+        str.ReplaceAll("A", "");
+    }
+
+    TH1 *h = fGraph->GetHistogram();
+
+    h->SetXTitle("Time");
+
+    if (!fNameTime.IsNull())
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+        axe->SetTimeDisplay(1);
+        axe->SetLabelSize(0.025);
+    }
+
+    fGraph->Draw(str);
+}
Index: /tags/Mars-V0.9/mhvstime/MHSectorVsTime.h
===================================================================
--- /tags/Mars-V0.9/mhvstime/MHSectorVsTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/MHSectorVsTime.h	(revision 9772)
@@ -0,0 +1,77 @@
+#ifndef MARS_MHSectorVsTime
+#define MARS_MHSectorVsTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+class MHCamera;
+class MCamEvent;
+class MGeomCam;
+
+class MRawEvtHeader;
+class MTime;
+class TGraph;
+
+class MHSectorVsTime : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+private:
+    TGraph *fGraph;
+
+    MCamEvent *fEvt;        //! the current event
+    MGeomCam  *fCam;        //! the camera geometry
+
+    MRawEvtHeader *fHeader; //!
+    MTime         *fTime;   //!
+
+    MHCamera fHCamera;      //!
+
+    Double_t fMin;          //!
+    Double_t fMax;          //!
+
+    TString fNameEvt;
+    TString fNameTime;
+
+    Int_t fType;
+    Int_t fTypeErr;
+
+    TArrayI fSectors;
+    TArrayI fAreaIndex;
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+public:
+    MHSectorVsTime(const char *name=NULL, const char *title=NULL);
+    ~MHSectorVsTime();
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    void SetNameEvt(const TString name)  { fNameEvt = name; }
+    void SetNameTime(const TString name) { fNameTime = name; }
+    void SetType(Int_t type, Int_t e=-1) { fType = type; fTypeErr=e; }
+    void SetSectors(const TArrayI &s)    { fSectors=s; }
+    void SetAreaIndex(const TArrayI &a)  { fAreaIndex=a; }
+
+    TH1 *GetHistByName(const TString name="");
+    //TGraph *GetGraph() { return fGraph; }
+
+    void Draw(Option_t *o=NULL);
+
+    ClassDef(MHSectorVsTime, 1) // Histogram to sum camera events
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/mhvstime/MHVsTime.cc
===================================================================
--- /tags/Mars-V0.9/mhvstime/MHVsTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/MHVsTime.cc	(revision 9772)
@@ -0,0 +1,358 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHVsTime
+//
+// Use this class if you want to display any rule vs time (or event number)
+//
+// Axis titles
+// ===========
+//
+// 1) If no other title is given the rule for the y-axis is used.
+// 2) If the MH3 has a non-default title (MH3::SetTitle called)
+//    this title is set as the histogram title. It can be used to overwrite
+//    the axis titles. For more information see TH1::SetTitle, eg.
+//       SetTitle("MyGraph;;Counts");
+//    The title for the x-axis is ignored and set automatically (MAKE SURE
+//    YOU HAVE TWO SEMICOLON!)
+//
+// eg.
+//       MHVsTime hist("MHillas.fAlpha");
+//       MHVsTime hist("MPointintPos.GetAbsErr");
+//       MHVsTime hist("MPointintPos.GetAbsErr*kRad2Deg");
+//
+// To set a maximum number of data-points (eg. to display the last 20min
+// only) call SetMaxPts(200)
+//
+// SetMaxPts(-1) disables this feature.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHVsTime.h"
+
+#include <ctype.h>   // tolower
+#include <fstream>
+
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include <TGraphErrors.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MParList.h"
+#include "MDataChain.h"
+#include "MRawEvtHeader.h"
+
+ClassImp(MHVsTime);
+
+using namespace std;
+
+const TString MHVsTime::gsDefName  = "MHVsTime";
+const TString MHVsTime::gsDefTitle = "Container for a graph vs time/evtnumber";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. For more informations about a valid rule
+// see MDataChain.
+//
+MHVsTime::MHVsTime(const char *rule, const char *error)
+    : fGraph(NULL), fData(NULL), fError(NULL), fScale(1), fMaxPts(-1),
+    fNumEvents(1), fUseEventNumber(0)
+{
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    if (!rule)
+        return;
+
+    fData = new MDataChain(rule);
+
+    if (error)
+        fError = new MDataChain(error);
+
+    fGraph = error ? new TGraphErrors : new TGraph;
+    fGraph->SetPoint(0, 0, 0); // Dummy point!
+    fGraph->SetEditable();     // Used as flag: First point? yes/no
+    fGraph->SetMarkerStyle(kFullDotMedium);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the histogram
+//
+MHVsTime::~MHVsTime()
+{
+    if (fGraph)
+        delete fGraph;
+
+    if (fData)
+        delete fData;
+
+    if (fError)
+        delete fError;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data members used by the data chain to be used in
+// MTask::AddBranchToList
+//
+TString MHVsTime::GetDataMember() const
+{
+    return fData ? fData->GetDataMember() : (TString)"";
+}
+
+// --------------------------------------------------------------------------
+//
+// PreProcess the MDataChain. Create a new TGraph. Delete an old one if
+// already allocated.
+//
+Bool_t MHVsTime::SetupFill(const MParList *plist)
+{
+    if (!fGraph || !fData)
+    {
+        *fLog << err << "ERROR - MHVsTime cannot be used with its default constructor!" << endl;
+        return kFALSE;
+    }
+
+    if (!fData->PreProcess(plist))
+        return kFALSE;
+
+    if (fError && !fError->PreProcess(plist))
+        return kFALSE;
+
+    fGraph->Set(1);
+    fGraph->SetPoint(0, 0, 0); // Dummy point!
+    fGraph->SetEditable();     // Used as flag: First point? yes/no
+
+
+    TString title(fData ? GetRule() : (TString)"Graph");
+    title += " vs ";
+    title += fUseEventNumber ? "Event Number" : "Time";
+
+    fGraph->SetNameTitle(fName, fTitle==gsDefTitle?title:fTitle);
+
+    fMean = 0;
+    fN    = 0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the TGraph and the MHVsTime container
+//
+void MHVsTime::SetName(const char *name)
+{
+    fGraph->SetName(name);
+    MH::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the TGraph and the MHVsTime container
+//
+void MHVsTime::SetTitle(const char *title)
+{
+    fGraph->SetTitle(title);
+    MH::SetTitle(title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the next data point. If the graph exceeds fMaxPts remove the first
+//
+Bool_t MHVsTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    Double_t t = 0;
+    if (fUseEventNumber)
+    {
+        const MRawEvtHeader *h = dynamic_cast<const MRawEvtHeader*>(par);
+        t = h ? h->GetDAQEvtNumber() : fGraph->GetN();
+    }
+    else
+    {
+        const MTime *tm = dynamic_cast<const MTime*>(par);
+        if (!tm)
+        {
+            *fLog << err << dbginf << "No MTime found..." << endl;
+            return kFALSE;
+        }
+        // If the time is not valid skip this entry
+	if (!*tm)
+            return kTRUE;
+
+        // Do not fill events with equal time
+        if (*tm==fLast || *tm==MTime())
+            return kTRUE;
+
+        fLast = *tm;
+
+        t = tm->GetAxisTime();
+    }
+
+    const Double_t v = fData->GetValue();
+    const Double_t e = fError ? fError->GetValue() : 0;
+
+    //*fLog << all << "ADD " << v << " " << e << endl;
+
+    fMean    += v;
+    fMeanErr += e;
+    fN++;
+
+    if (fN==fNumEvents)
+    {
+        if (fMaxPts>0 && fGraph->GetN()>fMaxPts || fGraph->IsEditable())
+        {
+            fGraph->RemovePoint(0);
+            fGraph->SetEditable(kFALSE);
+        }
+
+        fGraph->SetPoint(fGraph->GetN(), t, fMean/fN*fScale);
+
+        if (fError)
+            static_cast<TGraphErrors*>(fGraph)->SetPointError(fGraph->GetN()-1, 0, fMeanErr/fN*fScale);
+
+        fMean = 0;
+        fMeanErr = 0;
+        fN = 0;
+    }
+
+    return kTRUE;
+}
+
+void MHVsTime::Paint(Option_t *opt)
+{
+    /*
+     *fLog << all << fGraph << " " << gPad->GetName() << " ----> Paint " << opt << endl;
+     TListIter Next(gPad->GetListOfPrimitives()); TObject *obj;
+     while ((obj=Next())) *fLog << obj << " " << obj->GetName() << " " << obj->ClassName() << " " << Next.GetOption() << endl;
+     */
+
+    if (!fGraph)
+        return;
+
+//    *fLog << all << fGraph->GetN() << " " << opt << endl;
+
+    if (fGraph->GetN()==0)
+        return;
+
+    TString str(opt);
+    if (!str.Contains("A"))
+        str += "A";
+    if (!str.Contains("P"))
+        str += "P";
+    if (str.Contains("same", TString::kIgnoreCase))
+    {
+        str.ReplaceAll("same", "");
+        str.ReplaceAll("A", "");
+    }
+
+    // SetPoint deletes the histogram!
+    if (fUseEventNumber)
+        fGraph->GetHistogram()->SetXTitle("Event Number");
+    else
+    {
+        fGraph->GetHistogram()->SetXTitle("Time");
+        fGraph->GetHistogram()->GetXaxis()->SetLabelSize(0.033);
+        fGraph->GetHistogram()->GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00 GMT");
+        fGraph->GetHistogram()->GetXaxis()->SetTimeDisplay(1);
+    }
+
+    if (TestBit(kIsLogy))
+        gPad->SetLogy();
+
+    // This is a workaround if the TGraph has only one point.
+    // Otherwise MStatusDisplay::Update hangs.
+    gPad->GetListOfPrimitives()->Remove(fGraph);
+    fGraph->Draw(fGraph->GetN()<2 ? "A" : str.Data());
+    //gPad->GetListOfPrimitives()->Add(fGraph, fGraph->GetN()<2 ? "A" : opt);
+    //    AppendPad(str);
+    //    fGraph->Draw(str);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// This displays the TGraph like you expect it to be (eg. time on the axis)
+// It should also make sure, that the displayed time always is UTC and
+// not local time...
+//
+void MHVsTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(fGraph);
+    pad->SetBorderMode(0);
+    AppendPad(opt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Used to rebuild a MHVsTime object of the same type (data members,
+// dimension, ...)
+//
+MParContainer *MHVsTime::New() const
+{
+    MHVsTime *h=new MHVsTime(fData ? (const char*)GetRule() : NULL);
+    h->SetScale(fScale);
+    if (fUseEventNumber)
+        h->SetUseEventNumber();
+    h->SetMaxPts(fMaxPts);
+    return h;
+}
+
+TString MHVsTime::GetRule() const
+{
+    return fData ? fData->GetRule() : (TString)"";
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the total number of bins in a histogram (excluding under- and
+// overflow bins)
+//
+Int_t MHVsTime::GetNbins() const
+{
+    return fGraph->GetN();
+}
+/*
+TH1 *MHVsTime::GetHist()
+{
+    return fGraph ? fGraph->GetHistogram() : 0;
+}
+
+const TH1 *MHVsTime::GetHist() const
+{
+    return fGraph ? fGraph->GetHistogram() : 0;
+}
+
+TH1 *MHVsTime::GetHistByName(const TString name)
+{
+    return GetHist();
+}
+*/
Index: /tags/Mars-V0.9/mhvstime/MHVsTime.h
===================================================================
--- /tags/Mars-V0.9/mhvstime/MHVsTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/MHVsTime.h	(revision 9772)
@@ -0,0 +1,82 @@
+#ifndef MARS_MHVsTime
+#define MARS_MHVsTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class TGraph;
+class MDataChain;
+
+class MHVsTime : public MH
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+protected:
+    // Could be const but root < 3.02/06 doesn't like this...
+    TGraph     *fGraph;     // Histogram to fill
+    MDataChain *fData;      // Object from which the data is filled
+    MDataChain *fError;     // Object from which the error is filled
+    Double_t    fScale;     // Scale for axis (eg unit)
+    Int_t       fMaxPts;    // Maximum number of data points
+
+    Int_t       fNumEvents; // Number of events to average
+
+    Double_t    fMean;      //! Mean value
+    Double_t    fMeanErr;   //! Mean error
+    Int_t       fN;         //! Number of entries in fMean
+    MTime       fLast;      //! For checks
+
+    enum {
+        kIsLogy = BIT(18)
+    };
+
+    Bool_t fUseEventNumber;
+
+public:
+    MHVsTime(const char *rule=NULL, const char *ruleerr=NULL);
+    ~MHVsTime();
+
+    void SetScale(Double_t scale) { fScale = scale; }
+
+    Int_t GetNbins() const;
+
+    void SetName(const char *name);
+    void SetTitle(const char *title);
+
+    void SetLogy(Bool_t b=kTRUE) { b ? SetBit(kIsLogy) : ResetBit(kIsLogy); }
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TString GetDataMember() const;
+    TString GetRule() const;
+
+    /*
+     const TH1 *GetHist() const;
+     TH1 *GetHist();
+     TH1 *GetHistByName(const TString name="");
+     */
+    const TGraph *GetGraph() const { return fGraph; }
+    TGraph *GetGraph() { return fGraph; }
+
+    void SetUseEventNumber(Bool_t use = kTRUE) { fUseEventNumber = use; }
+    void SetNumEvents(Int_t n) { fNumEvents=n; }
+
+    void Draw(Option_t *opt=NULL);
+    void Paint(Option_t *opt=NULL);
+
+    MParContainer *New() const;
+
+    void SetMaxPts(Int_t n) { fMaxPts=n; }
+
+    ClassDef(MHVsTime, 1) // Generalized 1/2/3D-histogram for Mars variables
+};
+
+#endif
Index: /tags/Mars-V0.9/mhvstime/Makefile
===================================================================
--- /tags/Mars-V0.9/mhvstime/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mhvstime/Makefile	(revision 9772)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HVsTime
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mgeom -I../mhist \
+	   -I../mgui -I../mraw -I../mdata -I../mcalib
+# mhist (MHCamera)
+# mgui  (MCamEvent)
+# mraw  (MRawEvtHeader)
+
+SRCFILES = MHVsTime.cc \
+           MHPixVsTime.cc \
+           MHSectorVsTime.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mimage/ImageIncl.h
===================================================================
--- /tags/Mars-V0.9/mimage/ImageIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/ImageIncl.h	(revision 9772)
@@ -0,0 +1,5 @@
+#ifndef __CINT__
+
+#include <TVector2.h>
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mimage/ImageLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mimage/ImageLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/ImageLinkDef.h	(revision 9772)
@@ -0,0 +1,29 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MImgCleanStd+;
+#pragma link C++ class MCameraSmooth+;
+
+#pragma link C++ class MHillas+;
+#pragma link C++ class MHillasSrc+;
+#pragma link C++ class MHillasExt+;
+#pragma link C++ class MHillasCalc+;
+
+#pragma link C++ class MImagePar+;
+#pragma link C++ class MNewImagePar+;
+#pragma link C++ class MNewImagePar2+;
+#pragma link C++ class MConcentration+;
+
+#pragma link C++ class MHHillas+;
+#pragma link C++ class MHHillasSrc+;
+#pragma link C++ class MHHillasExt+;
+#pragma link C++ class MHImagePar+;
+#pragma link C++ class MHNewImagePar+;
+#pragma link C++ class MHNewImagePar2+;
+#pragma link C++ class MStereoPar+;
+#pragma link C++ class MStereoCalc+;
+
+#endif
Index: /tags/Mars-V0.9/mimage/MCameraSmooth.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MCameraSmooth.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MCameraSmooth.cc	(revision 9772)
@@ -0,0 +1,144 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 08/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MCameraSmooth                                                          //
+//                                                                         //
+//  This task fills each pixel in the camera with the average of the       //
+//  number of cerenkov photons from its surrounding pixels. This can       //
+//  be done using the central pixel or ignoring the central pixel.         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraSmooth.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+ClassImp(MCameraSmooth);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. You can specify the numer of loops how often a
+// smoothing should be done. The default is 1.
+//
+MCameraSmooth::MCameraSmooth(Byte_t n, const char *name, const char *title)
+    : fCounts(n), fUseCentralPixel(kTRUE)
+{
+    fName  = name  ? name  : "MCameraSmooth";
+    fTitle = title ? title : "Task to smooth the camera";
+}
+
+// --------------------------------------------------------------------------
+//
+//  - get the MSignalCam from the parlist (abort if missing)
+//  - get MGeomCam from the parameter list
+//
+Int_t MCameraSmooth::PreProcess (MParList *pList)
+{
+    fEvt = (MSignalCam*)pList->FindObject("MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << dbginf << "MSignalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << warn << dbginf << "No camera geometry available... aborting." << endl;
+
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the smoothing
+//
+Int_t MCameraSmooth::Process()
+{
+    const UShort_t entries = fEvt->GetNumPixels();
+
+    //
+    // remove the pixels in fPixelsID if they are set to be used,
+    // (set them to 'unused' state)
+    //
+
+    Double_t *photons = new Double_t[entries];
+    Double_t *errors  = new Double_t[entries];
+
+    for (int n=0; n<fCounts; n++)
+    {
+        for (UShort_t i=0; i<entries; i++)
+        {
+            MSignalPix &pix = (*fEvt)[i];
+
+            //const Int_t id = pix.GetPixId();
+
+            const MGeomPix &gpix = (*fGeomCam)[i];
+
+            const Int_t n = gpix.GetNumNeighbors();
+
+            Int_t num  = fUseCentralPixel ? 1 : 0;
+            photons[i] = fUseCentralPixel ? pix.GetNumPhotons() : 0;
+            errors[i]  = fUseCentralPixel ? pix.GetErrorPhot()  : 0;
+
+            for (int j=0; j<n; j++)
+            {
+                const UShort_t nid = gpix.GetNeighbor(j);
+
+                const MSignalPix *evtpix = fEvt->GetPixById(nid);
+                if (evtpix)
+                {
+                    photons[i] += evtpix->GetNumPhotons();
+                    errors[i]  += evtpix->GetErrorPhot();
+                }
+                num++;
+            }
+
+            photons[i] /= num;
+            errors[i]  /= num;
+        }
+
+        for (UShort_t i=0; i<entries; i++)
+            (*fEvt)[i].Set(photons[i], errors[i]);
+    }
+
+    delete photons;
+    delete errors;
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mimage/MCameraSmooth.h
===================================================================
--- /tags/Mars-V0.9/mimage/MCameraSmooth.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MCameraSmooth.h	(revision 9772)
@@ -0,0 +1,36 @@
+#ifndef MARS_MCameraSmooth
+#define MARS_MCameraSmooth
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class MGeomCam;
+class MSignalCam;
+
+class MCameraSmooth : public MTask
+{
+private:
+    MSignalCam *fEvt;     //! Pointer to data to smooth
+    MGeomCam   *fGeomCam; //! Camera geometry
+
+    Byte_t fCounts;           // number of smoothing loops
+    Bool_t fUseCentralPixel;  // use also the central pixel
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MCameraSmooth(Byte_t cnt=1, const char *name=NULL, const char *title=NULL);
+
+    void SetUseCentralPixel(Bool_t b=kTRUE) { fUseCentralPixel=kTRUE; }
+
+    ClassDef(MCameraSmooth, 0) // task to smooth the camera contants
+}; 
+
+#endif
+
Index: /tags/Mars-V0.9/mimage/MConcentration.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MConcentration.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MConcentration.cc	(revision 9772)
@@ -0,0 +1,157 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@atsro.uni-wuerzburg.de>
+!   Author(s): Rudolf Bock     10/2001 <mailto:Rudolf.Bock@cern.ch>
+!   Author(s): Wolfgang Wittek  6/2002 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Oscar Blanch     3/2004 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MConcentration
+//
+// Storage Container for Concentration parameters
+//
+//
+// Version 1:
+// ----------
+// fConc[i]    [ratio] Number of photons in the i+1 more populated pixels
+//                     over the event size (till i=7).
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MConcentration.h"
+
+
+#include <TArrayF.h>
+#include <TArrayI.h>
+
+#include "MHillas.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MConcentration);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MConcentration::MConcentration(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MConcentration";
+    fTitle = title ? title : "Storage container for concentrations";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes the values with defaults. For the default values see the
+// source code.
+//
+void MConcentration::Reset()
+{
+    for (int i=0; i<9; i++)
+        fConc[i] = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the Concetration Parameters to *fLog
+//
+void MConcentration::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Concentrations (" << GetName() << ")" << endl;
+    for(int i=0;i<9;i++)
+      *fLog << "Conc" << i+1 <<" = "<< fConc[i] << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the Concentrations from a Cherenkov photon event
+// assuming Cher.photons/pixel, their standard hillas parameters 
+// and  pixel coordinates are given.
+// In case you don't call Calc from within an eventloop make sure, that
+// you call the Reset member function before.
+//
+// Returns:
+//    Nothing.
+//
+Int_t MConcentration::Calc(const MGeomCam &geom, const MSignalCam &evt, const MHillas &hillas)
+{
+    Float_t maxpix[9] = {0,0,0,0,0,0,0,0,0};             // [#phot]
+
+   const UInt_t npix = evt.GetNumPixels();
+   for (UInt_t i=0; i<npix; i++)
+   {
+       const MSignalPix &pix = evt[i];
+       if (!pix.IsPixelUsed())
+           continue;
+
+        const Double_t nphot = pix.GetNumPhotons()* geom.GetPixRatio(i);
+
+	// Get number of photons in the 8 most populated pixels	
+        if (maxpix[0]<=nphot)
+        {
+            for(int i=0;i<8;i++)
+                maxpix[8-i]=maxpix[7-i];
+            maxpix[0]=nphot;
+            continue;
+        }
+
+	// Check if the latest value is 'somewhere in between'
+        for (int i=0; i<8; i++)
+        {
+            if (nphot>=maxpix[7-i])
+                continue;
+
+            for(int j=0;j<i-1;j++)
+                maxpix[7-j]=maxpix[6-j];                 // [#phot]
+
+            maxpix[8-i]=nphot;
+            break;
+        }
+    }
+
+    // Compute concentrations from the 8 pixels with higher signal
+    fConc[0]=maxpix[0];
+
+    // No calculate the integral of the n highest pixels
+    for(int i=1; i<8; i++)
+        fConc[i] = fConc[i-1]+maxpix[i];
+
+    for(int i=0; i<8; i++)
+        fConc[i] /= hillas.GetSize();                    // [ratio]
+
+    SetReadyToSave();
+
+    return 0;
+}
Index: /tags/Mars-V0.9/mimage/MConcentration.h
===================================================================
--- /tags/Mars-V0.9/mimage/MConcentration.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MConcentration.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MConcentration
+#define MARS_MConcentration
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MConcentration : public MParContainer
+{
+private:
+    Float_t fConc[9];       // [ratio] Num photons in i+1 pixels over size of event 
+
+public:
+    MConcentration(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Int_t Calc(const MGeomCam &geom, const MSignalCam &pix, const MHillas &hil);
+
+    void Print(Option_t *opt=NULL) const;
+
+    Float_t GetConc1() const { return fConc[0]; }
+    Float_t GetConc2() const { return fConc[1]; }
+    Float_t GetConc3() const { return fConc[2]; }
+    Float_t GetConc4() const { return fConc[3]; }
+    Float_t GetConc5() const { return fConc[4]; }
+    Float_t GetConc6() const { return fConc[5]; }
+    Float_t GetConc7() const { return fConc[6]; }
+    Float_t GetConc8() const { return fConc[7]; }
+    Float_t GetConc9() const { return fConc[8]; }
+
+    ClassDef(MConcentration, 1) // Storage Container for Concentration Parameter
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MHHillas.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHHillas.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHHillas.cc	(revision 9772)
@@ -0,0 +1,376 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek  2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHHillas
+//
+// This class contains histograms for the source independent image parameters
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHHillas.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MGeomCam.h"
+#include "MBinning.h"
+
+#include "MHCamera.h"
+
+ClassImp(MHHillas);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Width, Length
+//
+MHHillas::MHHillas(const char *name, const char *title)
+    : fGeomCam(0), fMm2Deg(1), fUseMmScale(kTRUE)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHHillas";
+    fTitle = title ? title : "Source independent image parameters";
+
+    fLength  = new TH1F("Length", "Length of Ellipse",               100,   0, 296.7);
+    fWidth   = new TH1F("Width",  "Width of Ellipse",                100,   0, 296.7);
+    fDistC   = new TH1F("DistC",  "Distance from center of camera",  100,   0, 445);
+    fDelta   = new TH1F("Delta",  "Angle (Main axis - x-axis)",      101, -90,  90);
+
+    fLength->SetLineColor(kBlue);
+
+    fLength->SetDirectory(NULL);
+    fWidth->SetDirectory(NULL);
+    fDistC->SetDirectory(NULL);
+    fDelta->SetDirectory(NULL);
+
+    fLength->SetXTitle("Length [mm]");
+    fWidth->SetXTitle("Width [mm]");
+    fDistC->SetXTitle("Distance [mm]");
+    fDelta->SetXTitle("Delta [\\circ]");
+
+    fLength->SetYTitle("Counts");
+    fWidth->SetYTitle("Counts");
+    fDistC->SetYTitle("Counts");
+    fDelta->SetYTitle("Counts");
+
+    MBinning bins;
+    bins.SetEdgesLog(50, 1, 1e7);
+
+    fSize  = new TH1F;
+    fSize->SetName("Size");
+    fSize->SetTitle("Number of Photons");
+    fSize->SetDirectory(NULL);
+    fSize->SetXTitle("Size");
+    fSize->SetYTitle("Counts");
+    fSize->GetXaxis()->SetTitleOffset(1.2);
+    fSize->GetXaxis()->SetLabelOffset(-0.015);
+    fSize->SetFillStyle(4000);
+    fSize->UseCurrentStyle();
+
+    bins.Apply(*fSize);
+
+    fCenter = new TH2F("Center", "Center of Ellipse", 51, -445, 445, 51, -445, 445);
+    fCenter->SetDirectory(NULL);
+    fCenter->SetXTitle("x [mm]");
+    fCenter->SetYTitle("y [mm]");
+    fCenter->SetZTitle("Counts");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms
+//
+MHHillas::~MHHillas()
+{
+    delete fLength;
+    delete fWidth;
+
+    delete fDistC;
+    delete fDelta;
+
+    delete fSize;
+    delete fCenter;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning (with the names 'BinningWidth' and 'BinningLength')
+// are found in the parameter list
+// Use this function if you want to set the conversion factor which
+// is used to convert the mm-scale in the camera plain into the deg-scale
+// used for histogram presentations. The conversion factor is part of
+// the camera geometry. Please create a corresponding MGeomCam container.
+//
+Bool_t MHHillas::SetupFill(const MParList *plist)
+{
+    fGeomCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeomCam)
+        *fLog << warn << GetDescriptor() << ": No Camera Geometry available. Using mm-scale for histograms." << endl;
+    else
+    {
+        fMm2Deg = fGeomCam->GetConvMm2Deg();
+        SetMmScale(kFALSE);
+    }
+
+    ApplyBinning(*plist, "Width",  fWidth);
+    ApplyBinning(*plist, "Length", fLength);
+    ApplyBinning(*plist, "Dist",   fDistC);
+    ApplyBinning(*plist, "Delta",  fDelta);
+    ApplyBinning(*plist, "Size",   fSize);
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningCamera");
+    if (!bins)
+    {
+        float r = fGeomCam ? fGeomCam->GetMaxRadius() : 600;
+        r *= 0.9;
+        if (!fUseMmScale)
+            r *= fMm2Deg;
+
+        MBinning b;
+        b.SetEdges(61, -r, r);
+        SetBinning(fCenter, &b, &b);
+    }
+    else
+        SetBinning(fCenter, bins, bins);
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this function to setup your own conversion factor between degrees
+// and millimeters. The conversion factor should be the one calculated in
+// MGeomCam. Use this function with Caution: You could create wrong values
+// by setting up your own scale factor.
+//
+void MHHillas::SetMm2Deg(Float_t mmdeg)
+{
+    if (mmdeg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Conversion factor < 0 - nonsense. Ignored." << endl;
+        return;
+    }
+
+    if (fMm2Deg>=0)
+        *fLog << warn << dbginf << "Warning - Conversion factor already set. Overwriting" << endl;
+
+    fMm2Deg = mmdeg;
+}
+
+// --------------------------------------------------------------------------
+//
+// With this function you can convert the histogram ('on the fly') between
+// degrees and millimeters.
+//
+void MHHillas::SetMmScale(Bool_t mmscale)
+{
+    if (fUseMmScale == mmscale)
+        return;
+
+    if (fMm2Deg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Sorry, no conversion factor for conversion available." << endl;
+        return;
+    }
+
+    const Double_t scale = mmscale ? 1./fMm2Deg : fMm2Deg;
+    MH::ScaleAxis(fLength, scale);
+    MH::ScaleAxis(fWidth,  scale);
+    MH::ScaleAxis(fDistC,  scale);
+    MH::ScaleAxis(fCenter, scale, scale);
+
+    if (mmscale)
+    {
+        fLength->SetXTitle("Length [mm]");
+        fWidth->SetXTitle("Width [mm]");
+        fDistC->SetXTitle("Distance [mm]");
+        fCenter->SetXTitle("x [mm]");
+        fCenter->SetYTitle("y [mm]");
+    }
+    else
+    {
+        fLength->SetXTitle("Length [\\circ]");
+        fWidth->SetXTitle("Width [\\circ]");
+        fDistC->SetXTitle("Distance [\\circ]");
+        fCenter->SetXTitle("x [\\circ]");
+        fCenter->SetYTitle("y [\\circ]");
+    }
+
+    fUseMmScale = mmscale;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MHillas-Container.
+// Be careful: Only call this with an object of type MHillas
+//
+Bool_t MHHillas::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MHHillas::Fill: Pointer (!=NULL) expected." << endl;
+        return kFALSE;
+    }
+
+    const MHillas &h = *(MHillas*)par;
+
+    const Double_t d = sqrt(h.GetMeanX()*h.GetMeanX() + h.GetMeanY()*h.GetMeanY());
+    const Double_t scale = fUseMmScale ? 1 : fMm2Deg;
+
+    fLength->Fill(scale*h.GetLength(), w);
+    fWidth ->Fill(scale*h.GetWidth(), w);
+    fDistC ->Fill(scale*d, w);
+    fCenter->Fill(scale*h.GetMeanX(), scale*h.GetMeanY(), w);
+    fDelta ->Fill(kRad2Deg*h.GetDelta(), w);
+    fSize  ->Fill(h.GetSize(), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup a inversed deep blue sea palette for the fCenter histogram.
+//
+void MHHillas::SetColors() const
+{
+    gStyle->SetPalette(51, NULL);
+    Int_t c[50];
+    for (int i=0; i<50; i++)
+        c[49-i] = gStyle->GetColorPalette(i);
+    gStyle->SetPalette(50, c);
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the four histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHHillas::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString opt(o);
+    opt.ToLower();
+
+    // FIXME: If same-option given make two independant y-axis!
+    const Bool_t same = opt.Contains("same");
+
+    if (!same)
+        pad->Divide(2,3);
+    else
+    {
+        fDistC->SetLineColor(kGreen);
+        fSize->SetLineColor(kGreen);
+        fDelta->SetLineColor(kGreen);
+
+        fWidth->SetLineColor(kMagenta);
+        fLength->SetLineColor(kCyan);
+    }
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    MH::DrawSame(*fWidth, *fLength, "Width'n'Length", same);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fDistC->Draw(same?"same":"");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    fSize->Draw(same?"same":"");
+
+    if (!same)
+    {
+        pad->cd(4);
+        gPad->SetBorderMode(0);
+        gPad->SetPad(0.51, 0.01, 0.99, 0.65);
+        SetColors();
+        fCenter->Draw("colz");
+        if (fGeomCam)
+        {
+            MHCamera *cam = new MHCamera(*fGeomCam);
+            cam->Draw("same");
+            cam->SetBit(kCanDelete);
+        }
+    }
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    fDelta->Draw(same?"same":"");
+
+    pad->cd(6);
+    if (gPad && !same)
+        delete gPad;
+
+    pad->Modified();
+    pad->Update();
+}
+
+TH1 *MHHillas::GetHistByName(const TString name)
+{
+    if (name.Contains("Width", TString::kIgnoreCase))
+        return fWidth;
+    if (name.Contains("Length", TString::kIgnoreCase))
+        return fLength;
+    if (name.Contains("Size", TString::kIgnoreCase))
+        return fSize;
+    if (name.Contains("Delta", TString::kIgnoreCase))
+        return fDelta;
+    if (name.Contains("DistC", TString::kIgnoreCase))
+        return fDistC;
+    if (name.Contains("Center", TString::kIgnoreCase))
+        return fCenter;
+
+    return NULL;
+}
+
+void MHHillas::Paint(Option_t *opt)
+{
+    SetColors();
+    MH::Paint();
+}
Index: /tags/Mars-V0.9/mimage/MHHillas.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHHillas.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHHillas.h	(revision 9772)
@@ -0,0 +1,63 @@
+#ifndef MARS_MHHillas
+#define MARS_MHHillas
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1F;
+class TH2F;
+class MHillas;
+class MGeomCam;
+
+class MHHillas : public MH
+{
+private:
+
+    TH1F *fLength;  //-> Length
+    TH1F *fWidth;   //-> Width
+
+    TH1F *fDistC;   //-> Distance to Camera Center
+    TH1F *fDelta;   //-> Angle between Length axis and x-axis
+
+    TH1F *fSize;    //-> Sum of used pixels
+    TH2F *fCenter;  //-> Center
+
+    void SetColors() const;
+
+    MGeomCam *fGeomCam; //! Camera geometry for plots (for the moment this is a feature for a loop only!)
+
+    Float_t fMm2Deg;
+    Bool_t  fUseMmScale;
+
+    void Paint(Option_t *opt="");
+
+public:
+    MHHillas(const char *name=NULL, const char *title=NULL);
+    ~MHHillas();
+
+    void SetMmScale(Bool_t mmscale=kTRUE);
+    virtual void SetMm2Deg(Float_t mmdeg);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name);
+
+    TH1F *GetHistLength() { return fLength; }
+    TH1F *GetHistWidth()  { return fWidth; }
+
+    TH1F *GetHistDistC()  { return fDistC; }
+    TH1F *GetHistDelta()  { return fDelta; }
+
+    TH1F *GetHistSize()   { return fSize; }
+    TH2F *GetHistCenter() { return fCenter; }
+
+    void Draw(Option_t *opt=NULL);
+
+    //Int_t DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+    ClassDef(MHHillas, 1) // Container which holds histograms for the source independent image parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MHHillasExt.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHHillasExt.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHHillasExt.cc	(revision 9772)
@@ -0,0 +1,282 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHHillasExt
+//
+// This class contains histograms for every Hillas parameter
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHHillasExt.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TLegend.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+
+#include "MParList.h"
+
+#include "MBinning.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+
+ClassImp(MHHillasExt);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Width, Length
+//
+MHHillasExt::MHHillasExt(const char *name, const char *title)
+    : fMm2Deg(1), fUseMmScale(kTRUE), fHilName("MHillasExt")
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHHillasExt";
+    fTitle = title ? title : "Container for extended Hillas histograms";
+
+    //
+    // loop over all Pixels and create two histograms
+    // one for the Low and one for the High gain
+    // connect all the histogram with the container fHist
+    //
+    fHAsym.SetDirectory(NULL);
+    fHM3Long.SetDirectory(NULL);
+    fHM3Trans.SetDirectory(NULL);
+    fHMaxDist.SetDirectory(NULL);
+
+    fHAsym.UseCurrentStyle();
+    fHM3Long.UseCurrentStyle();
+    fHM3Trans.UseCurrentStyle();
+    fHMaxDist.UseCurrentStyle();
+
+    fHAsym.SetName("Asymmetry");
+    fHM3Long.SetName("3rd Mom Long");
+    fHM3Trans.SetName("3rd Mom Trans");
+    fHMaxDist.SetName("Max Dist");
+
+    fHAsym.SetTitle("Asymmetry");
+    fHM3Long.SetTitle("3^{rd} Moment Longitudinal");
+    fHM3Trans.SetTitle("3^{rd} Moment Transverse");
+    fHMaxDist.SetTitle("Distance of max distant pixel");
+
+    fHAsym.SetXTitle("Asym [mm]");
+    fHM3Long.SetXTitle("3^{rd} M_{l} [mm]");
+    fHM3Trans.SetXTitle("3^{rd} M_{t} [mm]");
+    fHMaxDist.SetXTitle("D_{max} [mm]");
+
+    fHAsym.SetYTitle("Counts");
+    fHM3Long.SetYTitle("Counts");
+    fHM3Trans.SetYTitle("Counts");
+    fHMaxDist.SetYTitle("Counts");
+
+    fHAsym.SetFillStyle(4000);
+    fHM3Long.SetFillStyle(4000);
+    fHM3Trans.SetFillStyle(4000);
+    fHMaxDist.SetFillStyle(4000);
+
+    fHM3Trans.SetLineColor(kBlue);
+
+    MBinning bins;
+
+    bins.SetEdges(51, -326, 326);
+    bins.Apply(fHM3Long);
+    bins.Apply(fHM3Trans);
+
+    bins.SetEdges(51, -593, 593);
+    bins.Apply(fHAsym);
+
+    bins.SetEdges(100, 0, 593);
+    bins.Apply(fHMaxDist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning (with the names 'BinningWidth' and 'BinningLength')
+// are found in the parameter list
+// Use this function if you want to set the conversion factor which
+// is used to convert the mm-scale in the camera plain into the deg-scale
+// used for histogram presentations. The conversion factor is part of
+// the camera geometry. Please create a corresponding MGeomCam container.
+//
+Bool_t MHHillasExt::SetupFill(const MParList *plist)
+{
+    fHillasExt = (MHillasExt*)plist->FindObject(fHilName, "MHillasExt");
+    if (!fHillasExt)
+    {
+        *fLog << err << fHilName << "[MHillasExt] not found in parameter list... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << GetDescriptor() << ": No Camera Geometry available. Using mm-scale for histograms." << endl;
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+        SetMmScale(kFALSE);
+    }
+
+    ApplyBinning(*plist, "Asym",    &fHAsym);
+    ApplyBinning(*plist, "M3Long",  &fHM3Long);
+    ApplyBinning(*plist, "M3Trans", &fHM3Trans);
+    ApplyBinning(*plist, "MaxDist", &fHMaxDist);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the four histograms with data from a MHillas-Container.
+// Be careful: Only call this with an object of type MHillas
+//
+Bool_t MHHillasExt::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MHillasSrc *src = (MHillasSrc*)par;
+
+    const Double_t scale = TMath::Sign(fUseMmScale?1:fMm2Deg, (src ? src->GetCosDeltaAlpha() : 1));
+
+    fHAsym.Fill(scale*fHillasExt->GetAsym(), w);
+    fHM3Long.Fill(scale*fHillasExt->GetM3Long(), w);
+    fHM3Trans.Fill(scale*fHillasExt->GetM3Trans(), w);
+    fHMaxDist.Fill(TMath::Abs(scale*fHillasExt->GetMaxDist()), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// With this function you can convert the histogram ('on the fly') between
+// degrees and millimeters.
+//
+void MHHillasExt::SetMmScale(Bool_t mmscale)
+{
+    if (fUseMmScale == mmscale)
+        return;
+
+    if (fMm2Deg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Sorry, no conversion factor for conversion available." << endl;
+        return;
+    }
+
+    const Double_t scale = mmscale ? 1./fMm2Deg : fMm2Deg;
+    MH::ScaleAxis(&fHAsym,    scale);
+    MH::ScaleAxis(&fHM3Long,  scale);
+    MH::ScaleAxis(&fHM3Trans, scale);
+    MH::ScaleAxis(&fHMaxDist, scale);
+
+    if (mmscale)
+    {
+        fHAsym.SetXTitle("Asym [mm]");
+        fHM3Long.SetXTitle("3^{rd} M_{l} [mm]");
+        fHM3Trans.SetXTitle("3^{rd} M_{t} [mm]");
+        fHMaxDist.SetXTitle("D_{max} [mm]");
+    }
+    else
+    {
+        fHAsym.SetXTitle("Asym [\\circ]");
+        fHM3Long.SetXTitle("3^{rd} M_{l} [\\circ]");
+        fHM3Trans.SetXTitle("3^{rd} M_{t} [\\circ]");
+        fHMaxDist.SetXTitle("D_{max} [\\circ]");
+    }
+
+    fUseMmScale = mmscale;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this function to setup your own conversion factor between degrees
+// and millimeters. The conversion factor should be the one calculated in
+// MGeomCam. Use this function with Caution: You could create wrong values
+// by setting up your own scale factor.
+//
+void MHHillasExt::SetMm2Deg(Float_t mmdeg)
+{
+    if (mmdeg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Conversion factor < 0 - nonsense. Ignored." << endl;
+        return;
+    }
+
+    if (fMm2Deg>=0)
+        *fLog << warn << dbginf << "Warning - Conversion factor already set. Overwriting" << endl;
+
+    fMm2Deg = mmdeg;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the four histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHHillasExt::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2, 2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    MH::DrawSame(fHM3Long, fHM3Trans, "3^{rd} Moments");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fHAsym.Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fHMaxDist.Draw();
+
+    delete pad->GetPad(4);
+}
+
+TH1 *MHHillasExt::GetHistByName(const TString name)
+{
+    if (name.Contains("Asym", TString::kIgnoreCase))
+        return &fHAsym;
+    if (name.Contains("M3Long", TString::kIgnoreCase))
+        return &fHM3Long;
+    if (name.Contains("M3Trans", TString::kIgnoreCase))
+        return &fHM3Trans;
+    if (name.Contains("MaxDist", TString::kIgnoreCase))
+        return &fHMaxDist;
+
+    return NULL;
+}
Index: /tags/Mars-V0.9/mimage/MHHillasExt.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHHillasExt.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHHillasExt.h	(revision 9772)
@@ -0,0 +1,46 @@
+#ifndef MARS_MHHillasExt
+#define MARS_MHHillasExt
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MHillasExt;
+
+class MHHillasExt : public MH
+{
+private:
+    MHillasExt *fHillasExt; //! Pointer to the MHillasExt container
+
+    TH1F fHAsym;    // [mm]    fDist minus dist: center of ellipse, highest pixel
+    TH1F fHM3Long;  // [mm]    3rd moment (e-weighted) along major axis
+    TH1F fHM3Trans; // [mm]    3rd moment (e-weighted) along minor axis
+    TH1F fHMaxDist; // [mm]    Distance between shower center maximum distant pixel
+
+    Float_t fMm2Deg;
+    Bool_t  fUseMmScale;
+
+    TString fHilName;
+
+public:
+    MHHillasExt(const char *name=NULL, const char *title=NULL);
+
+    void SetHillasName(const char *name) { fHilName = name; }
+
+    void SetMmScale(Bool_t mmscale=kTRUE);
+    virtual void SetMm2Deg(Float_t mmdeg);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name);
+
+    void Draw(Option_t *opt=NULL);
+
+    ClassDef(MHHillasExt, 1) // Container which holds histograms for the extended hillas parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MHHillasSrc.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHHillasSrc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHHillasSrc.cc	(revision 9772)
@@ -0,0 +1,274 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHHillasSrc
+//
+// This class contains histograms for every Hillas parameter
+//
+///////////////////////////////////////////////////////////////////////
+#include "MHHillasSrc.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MHillasSrc.h"
+
+ClassImp(MHHillasSrc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Alpha, and Dist
+//
+MHHillasSrc::MHHillasSrc(const char *name, const char *title)
+    : fUseMmScale(kTRUE)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHHillasSrc";
+    fTitle = title ? title : "Container for Hillas histograms";
+
+    //
+    // loop over all Pixels and create two histograms
+    // one for the Low and one for the High gain
+    // connect all the histogram with the container fHist
+    //
+    fAlpha    = new TH1F("Alpha",    "Alpha of Ellipse",                 90,   -90,  90);
+    fDist     = new TH1F("Dist",     "Dist of Ellipse",                 100,     0, 445);
+    fCosDA    = new TH1F("CosDA",    "cos(Delta,Alpha) of Ellipse",     101,    -1,   1);
+    fDCA      = new TH1F("DCA",      "Distance of closest aproach",     101,  -500, 500);
+    fDCADelta = new TH1F("DCADelta", "Angle between shower and x-axis",  80,     0, 360);
+
+    fAlpha->SetDirectory(NULL);
+    fDist->SetDirectory(NULL);
+    fCosDA->SetDirectory(NULL);
+    fDCA->SetDirectory(NULL);
+    fDCADelta->SetDirectory(NULL);
+
+    fAlpha->SetXTitle("\\alpha [\\circ]");
+    fDist->SetXTitle("Dist [mm]");
+    fCosDA->SetXTitle("cos(\\delta,\\alpha)");
+    fDCA->SetXTitle("DCA [\\circ]");
+    fDCADelta->SetXTitle("DCADelta [0, 2\\pi]");
+
+    fAlpha->SetYTitle("Counts");
+    fDist->SetYTitle("Counts");
+    fCosDA->SetYTitle("Counts");
+    fDCA->SetYTitle("Counts");
+    fDCADelta->SetYTitle("Counts");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the four histograms
+//
+MHHillasSrc::~MHHillasSrc()
+{
+    delete fAlpha;
+    delete fDist;
+    delete fCosDA;
+    delete fDCA;
+    delete fDCADelta;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning (with the names 'BinningAlpha' and 'BinningDist')
+// are found in the parameter list
+// Use this function if you want to set the conversion factor which
+// is used to convert the mm-scale in the camera plain into the deg-scale
+// used for histogram presentations. The conversion factor is part of
+// the camera geometry. Please create a corresponding MGeomCam container.
+//
+Bool_t MHHillasSrc::SetupFill(const MParList *plist)
+{
+    const MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << dbginf << "No Camera Geometry available. Using mm-scale for histograms." << endl;
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+        SetMmScale(kFALSE);
+    }
+
+    ApplyBinning(*plist, "Alpha",    fAlpha);
+    ApplyBinning(*plist, "Dist",     fDist);
+    ApplyBinning(*plist, "DCA",      fDCA);
+    ApplyBinning(*plist, "DCADelta", fDCADelta);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the four histograms with data from a MHillas-Container.
+// Be careful: Only call this with an object of type MHillas
+//
+Bool_t MHHillasSrc::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MHHillasSrc::Fill: Pointer (!=NULL) expected." << endl;
+        return kFALSE;
+    }
+
+    const MHillasSrc &h = *(MHillasSrc*)par;
+
+    fAlpha->Fill(h.GetAlpha(), w);
+    fDist ->Fill(fUseMmScale ? h.GetDist() : fMm2Deg*h.GetDist(), w);
+    fCosDA->Fill(h.GetCosDeltaAlpha(), w);
+    fDCA  ->Fill(fUseMmScale ? h.GetDCA() : fMm2Deg*h.GetDCA(), w);
+    fDCADelta ->Fill(h.GetDCADelta(), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this function to setup your own conversion factor between degrees
+// and millimeters. The conversion factor should be the one calculated in
+// MGeomCam. Use this function with Caution: You could create wrong values
+// by setting up your own scale factor.
+//
+void MHHillasSrc::SetMm2Deg(Float_t mmdeg)
+{
+    if (mmdeg<=0)
+    {
+        *fLog << warn << dbginf << "Warning - Conversion factor <= 0 - nonsense. Ignored." << endl;
+        return;
+    }
+
+    if (fMm2Deg>0)
+        *fLog << warn << dbginf << "Warning - Conversion factor already set. Overwriting" << endl;
+
+    fMm2Deg = mmdeg;
+}
+
+// --------------------------------------------------------------------------
+//
+// With this function you can convert the histogram ('on the fly') between
+// degrees and millimeters.
+//
+void MHHillasSrc::SetMmScale(Bool_t mmscale)
+{
+    if (fUseMmScale == mmscale)
+        return;
+
+    if (fMm2Deg<0)
+    {
+        *fLog << warn << GetDescriptor() << ": Warning - Sorry, no conversion factor for conversion available." << endl;
+        return;
+    }
+
+    const Double_t scale = mmscale ? 1./fMm2Deg : fMm2Deg;
+    MH::ScaleAxis(fDist, scale);
+    MH::ScaleAxis(fDCA,  scale);
+
+    fDist->SetXTitle(mmscale ? "Dist [mm]" : "Dist [\\circ]");
+    fDCA ->SetXTitle(mmscale ? "DCA [mm]"  : "DCA [\\circ]");
+
+    fUseMmScale = mmscale;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the two histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHHillasSrc::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    // FIXME: Display Source position
+
+    pad->Divide(2, 2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fAlpha->Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fDist->Draw();
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fDCA->Draw();
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+
+    TVirtualPad *p = gPad;
+    p->Divide(1,2);
+    p->cd(1);
+    gPad->SetBorderMode(0);
+    fCosDA->Draw();
+
+    p->cd(2);
+    gPad->SetBorderMode(0);
+    fDCADelta->Draw();
+}
+
+void MHHillasSrc::Paint(Option_t *opt)
+{
+    if (fCosDA->GetEntries()==0)
+        return;
+
+    TVirtualPad *savepad = gPad;
+    savepad->cd(4);
+    gPad->SetLogy();
+    gPad = savepad;
+}
+
+TH1 *MHHillasSrc::GetHistByName(const TString name)
+{
+    if (name.Contains("Alpha", TString::kIgnoreCase))
+        return fAlpha;
+    if (name.Contains("Dist", TString::kIgnoreCase))
+        return fDist;
+    if (name.Contains("CosDA", TString::kIgnoreCase))
+        return fCosDA;
+
+    return NULL;
+}
Index: /tags/Mars-V0.9/mimage/MHHillasSrc.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHHillasSrc.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHHillasSrc.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MHHillasSrc
+#define MARS_MHHillasSrc
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1F;
+class MHillas;
+
+class MHHillasSrc : public MH
+{
+private:
+    TH1F *fAlpha;     //->
+    TH1F *fDist;      //->
+    TH1F *fCosDA;     //->
+
+    TH1F *fDCA;       //->
+    TH1F *fDCADelta;  //->
+
+    Float_t fMm2Deg;
+    Bool_t  fUseMmScale;
+
+public:
+    MHHillasSrc(const char *name=NULL, const char *title=NULL);
+    ~MHHillasSrc();
+
+    void SetMmScale(Bool_t mmscale=kTRUE);
+    void SetMm2Deg(Float_t mmdeg);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name);
+
+    TH1F *GetHistAlpha()         { return fAlpha; }
+    TH1F *GetHistDist()          { return fDist; }
+    TH1F *GetHistCosDeltaAlpha() { return fCosDA; }
+    TH1F *GetHistDCA()           { return fDCA; }
+    TH1F *GetHistDCADelta()      { return fDCADelta; }
+
+    void Draw(Option_t *opt=NULL);
+    void Paint(Option_t *opt);
+
+
+    ClassDef(MHHillasSrc, 1) // Container which holds histograms for the source dependant parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MHImagePar.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHImagePar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHImagePar.cc	(revision 9772)
@@ -0,0 +1,277 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 03/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHImagePar
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHImagePar.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MImagePar.h"
+
+ClassImp(MHImagePar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHImagePar::MHImagePar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHImagePar";
+    fTitle = title ? title : "Histograms of image parameters";
+
+    fHistSatHi.SetName("SatHi");
+    fHistSatHi.SetTitle("Number of pixels with saturating hi-gains");
+    fHistSatHi.SetXTitle("Pixels");
+    fHistSatHi.SetYTitle("Counts");
+    fHistSatHi.SetDirectory(NULL);
+    fHistSatHi.UseCurrentStyle();
+    fHistSatHi.SetLineColor(kBlue);
+    fHistSatHi.SetFillStyle(4000);
+
+    fHistSatLo.SetName("SatLo");
+    fHistSatLo.SetTitle("Number of pixels with saturating lo-gains");
+    fHistSatLo.SetXTitle("Pixels");
+    fHistSatLo.SetYTitle("Counts");
+    fHistSatLo.SetDirectory(NULL);
+    fHistSatLo.UseCurrentStyle();
+    fHistSatLo.SetFillStyle(4000);
+
+    fHistIslands.SetName("Islands");
+    fHistIslands.SetTitle("Number of Islands");
+    fHistIslands.SetXTitle("N");
+    fHistIslands.SetYTitle("Counts");
+    fHistIslands.SetDirectory(NULL);
+    fHistIslands.UseCurrentStyle();
+    //fHistIslands.SetLineColor(kBlue);
+    fHistIslands.SetFillStyle(4000);
+
+    fHistSizeSubIslands.SetName("SizeSub");
+    fHistSizeSubIslands.SetTitle("Size of Sub Islands");
+    fHistSizeSubIslands.SetXTitle("S [phe]");
+    fHistSizeSubIslands.SetYTitle("Counts");
+    fHistSizeSubIslands.SetDirectory(NULL);
+    fHistSizeSubIslands.UseCurrentStyle();
+    fHistSizeSubIslands.SetLineColor(kBlue);
+    fHistSizeSubIslands.SetFillStyle(4000);
+
+    fHistSizeMainIsland.SetName("SizeMain");
+    fHistSizeMainIsland.SetTitle("Size of Main Island");
+    fHistSizeMainIsland.SetXTitle("S [phe]");
+    fHistSizeMainIsland.SetYTitle("Counts");
+    fHistSizeMainIsland.SetDirectory(NULL);
+    fHistSizeMainIsland.UseCurrentStyle();
+    fHistSizeMainIsland.SetFillStyle(4000);
+
+    fHistNumSP.SetName("NumSP");
+    fHistNumSP.SetTitle("Number of single core pixels");
+    fHistNumSP.SetXTitle("N");
+    fHistNumSP.SetYTitle("Counts");
+    fHistNumSP.SetDirectory(NULL);
+    fHistNumSP.UseCurrentStyle();
+    //fHistNumSP.SetLineColor(kBlue);
+    fHistNumSP.SetFillStyle(4000);
+
+    fHistSizeSP.SetName("SizeSP");
+    fHistSizeSP.SetTitle("Size of single core pixels");
+    fHistSizeSP.SetXTitle("S [phe]");
+    fHistSizeSP.SetYTitle("Counts");
+    fHistSizeSP.SetDirectory(NULL);
+    fHistSizeSP.UseCurrentStyle();
+    //fHistSizeSP.SetLineColor(kBlue);
+    fHistSizeSP.SetFillStyle(4000);
+
+
+    MBinning bins;
+
+    bins.SetEdges(60, -0.5, 59.5);
+    bins.Apply(fHistSatLo);
+    bins.Apply(fHistSatHi);
+    bins.Apply(fHistNumSP);
+
+    bins.SetEdgesLog(50, 1, 1e7);
+    bins.Apply(fHistSizeSubIslands);
+    bins.Apply(fHistSizeMainIsland);
+    bins.Apply(fHistSizeSP);
+
+    bins.SetEdges(15, 0.5, 15.5);
+    bins.Apply(fHistIslands);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHImagePar::SetupFill(const MParList *plist)
+{
+    ApplyBinning(*plist, "Pixels",  &fHistSatLo);
+    ApplyBinning(*plist, "Pixels",  &fHistSatHi);
+    ApplyBinning(*plist, "Pixels",  &fHistNumSP);
+
+    ApplyBinning(*plist, "Islands", &fHistIslands);
+
+    ApplyBinning(*plist, "Size",    &fHistSizeSubIslands);
+    ApplyBinning(*plist, "Size",    &fHistSizeMainIsland);
+    ApplyBinning(*plist, "Size",    &fHistSizeSP);
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MNewImagePar container.
+//
+Bool_t MHImagePar::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MImagePar::Fill: Pointer (!=NULL) expected." << endl;
+        return kFALSE;
+    }
+
+    const MImagePar &h = *(MImagePar*)par;
+
+    fHistSatHi.Fill(h.GetNumSatPixelsHG(),    w);
+    fHistSatLo.Fill(h.GetNumSatPixelsLG(),    w);
+    fHistNumSP.Fill(h.GetNumSinglePixels(),   w);
+    fHistSizeSP.Fill(h.GetSizeSinglePixels(), w);
+    fHistSizeSubIslands.Fill(h.GetSizeSubIslands(), w);
+    fHistSizeMainIsland.Fill(h.GetSizeMainIsland(), w);
+    fHistIslands.Fill(h.GetNumIslands(),      w);
+
+    return kTRUE;
+}
+
+void MHImagePar::Paint(Option_t *o)
+{
+     if (fHistSatHi.GetMaximum()>0 && gPad->GetPad(1))
+         gPad->GetPad(1)->SetLogy();
+     if (fHistIslands.GetMaximum()>0 && gPad->GetPad(3))
+         gPad->GetPad(3)->SetLogy();
+
+     TVirtualPad *pad = gPad->GetPad(2);
+     if (pad)
+     {
+         if (fHistNumSP.GetMaximum()>0 && pad->GetPad(1))
+             pad->GetPad(1)->SetLogy();
+         if (fHistSizeSP.GetMaximum()>0 && pad->GetPad(2))
+         {
+             pad->GetPad(2)->SetLogx();
+             pad->GetPad(2)->SetLogy();
+         }
+     }
+     if (fHistSizeMainIsland.GetMaximum()>0 && gPad->GetPad(4))
+     {
+         gPad->GetPad(4)->SetLogx();
+         gPad->GetPad(4)->SetLogy();
+     }
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the two histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHImagePar::Draw(Option_t *o)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString opt(o);
+    opt.ToLower();
+
+    // FIXME: If same-option given make two independant y-axis!
+    const Bool_t same = opt.Contains("same");
+
+    if (!same)
+        pad->Divide(2,2);
+    else
+        fHistIslands.SetLineColor(kGreen);
+
+    if (!same)
+    {
+        pad->cd(1);
+        gPad->SetBorderMode(0);
+        MH::DrawSame(fHistSatHi, fHistSatLo, "Saturating Pixels");
+        fHistSatHi.SetMinimum();    // switch off to allow log-scale
+        fHistSatLo.SetMinimum();    // switch off to allow log-scale
+        fHistSatLo.SetMaximum(0.1); // dummy value to allow log-scale
+
+        pad->cd(4);
+        gPad->SetBorderMode(0);
+        MH::DrawSame(fHistSizeMainIsland, fHistSizeSubIslands, "Sizes...");
+        fHistSizeMainIsland.SetMinimum();    // switch off to allow log-scale
+        fHistSizeSubIslands.SetMinimum();    // switch off to allow log-scale
+        fHistSizeSubIslands.SetMaximum(0.1); // dummy value to allow log-scale
+    }
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    pad->GetPad(2)->Divide(1,2,1e-10,1e-10);
+    pad->GetPad(2)->cd(1);
+    gPad->SetBorderMode(0);
+    fHistNumSP.Draw(same?"same":"");
+    pad->GetPad(2)->cd(2);
+    gPad->SetBorderMode(0);
+    fHistSizeSP.Draw(same?"same":"");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fHistIslands.Draw(same?"same":"");
+}
+
+TH1 *MHImagePar::GetHistByName(const TString name)
+{
+    if (name.Contains("SatHi", TString::kIgnoreCase))
+        return &fHistSatHi;
+    if (name.Contains("SatLo", TString::kIgnoreCase))
+        return &fHistSatLo;
+    if (name.Contains("Islands", TString::kIgnoreCase))
+        return &fHistIslands;
+
+    return NULL;
+}
Index: /tags/Mars-V0.9/mimage/MHImagePar.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHImagePar.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHImagePar.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MHImagePar
+#define MARS_MHImagePar
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MHillas;
+
+class MHImagePar : public MH
+{
+private:
+    TH1F fHistSatHi;          // Number of pixels with sat hi-gain
+    TH1F fHistSatLo;          // Number of pixels with sat lo-gain
+
+    TH1F fHistIslands;        // Number of islands per event
+    TH1F fHistSizeSubIslands; // Size of sub islands
+    TH1F fHistSizeMainIsland; // Size of main island
+
+    TH1F fHistNumSP;          // Number of single core pixels
+    TH1F fHistSizeSP;         // size of single core pixels
+
+    Short_t fNumSatPixelsHG; // number of pixels with saturating hi-gains
+    Short_t fNumSatPixelsLG; // number of pixels with saturating lo-gains
+
+public:
+    MHImagePar(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name);
+
+    TH1F &GetHistSatHi()   { return fHistSatHi; }
+    TH1F &GetHistSatLo()   { return fHistSatLo; }
+
+    TH1F &GetHistIslands() { return fHistIslands; }
+
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHImagePar, 1) // Histograms of image parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MHNewImagePar.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHNewImagePar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHNewImagePar.cc	(revision 9772)
@@ -0,0 +1,348 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 03/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 04/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHNewImagePar
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHNewImagePar.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MNewImagePar.h"
+
+ClassImp(MHNewImagePar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHNewImagePar::MHNewImagePar(const char *name, const char *title)
+    : fMm2Deg(1), fUseMmScale(kTRUE)
+{
+    fName  = name  ? name  : "MHNewImagePar";
+    fTitle = title ? title : "Histograms of new image parameters";
+
+    fHistLeakage1.SetName("Leakage1");
+    fHistLeakage1.SetTitle("Leakage_{1}");
+    fHistLeakage1.SetXTitle("Leakage");
+    fHistLeakage1.SetYTitle("Counts");
+    fHistLeakage1.SetDirectory(NULL);
+    fHistLeakage1.UseCurrentStyle();
+    fHistLeakage1.SetFillStyle(4000);
+
+    fHistLeakage2.SetName("Leakage2");
+    fHistLeakage2.SetTitle("Leakage_{2}");
+    fHistLeakage2.SetXTitle("Leakage");
+    fHistLeakage2.SetYTitle("Counts");
+    fHistLeakage2.SetDirectory(NULL);
+    fHistLeakage2.UseCurrentStyle();
+    fHistLeakage2.SetLineColor(kBlue);
+    fHistLeakage2.SetFillStyle(4000);
+ 
+    fHistUsedPix.SetName("UsedPix");
+    fHistUsedPix.SetTitle("Number of used pixels");
+    fHistUsedPix.SetXTitle("Number of Pixels");
+    fHistUsedPix.SetYTitle("Counts");
+    fHistUsedPix.SetDirectory(NULL);
+    fHistUsedPix.UseCurrentStyle();
+    fHistUsedPix.SetLineColor(kBlue);
+    fHistUsedPix.SetFillStyle(4000);
+
+    fHistCorePix.SetName("CorePix");
+    fHistCorePix.SetTitle("Number of core pixels");
+    fHistCorePix.SetXTitle("Number of Pixels");
+    fHistCorePix.SetYTitle("Counts");
+    fHistCorePix.SetDirectory(NULL);
+    fHistCorePix.UseCurrentStyle();
+    fHistCorePix.SetLineColor(kBlack);
+    fHistCorePix.SetFillStyle(4000);
+
+    fHistUsedArea.SetName("UsedArea");
+    fHistUsedArea.SetTitle("Area of used pixels");
+    fHistUsedArea.SetXTitle("Area [m^2]");
+    fHistUsedArea.SetYTitle("Counts");
+    fHistUsedArea.SetDirectory(NULL);
+    fHistUsedArea.UseCurrentStyle();
+    fHistUsedArea.SetLineColor(kBlue);
+    fHistUsedArea.SetFillStyle(4000);
+
+    fHistCoreArea.SetName("CoreArea");
+    fHistCoreArea.SetTitle("Area of core pixels");
+    fHistCoreArea.SetXTitle("Area [m^2]");
+    fHistCoreArea.SetYTitle("Counts");
+    fHistCoreArea.SetDirectory(NULL);
+    fHistCoreArea.UseCurrentStyle();
+    fHistCoreArea.SetLineColor(kBlack);
+    fHistCoreArea.SetFillStyle(4000);
+
+    fHistConc.SetDirectory(NULL);
+    fHistConc1.SetDirectory(NULL);
+    fHistConc.SetName("Conc2");
+    fHistConc1.SetName("Conc1");
+    fHistConc.SetTitle("Ratio: Conc");
+    fHistConc1.SetTitle("Ratio: Conc1");
+    fHistConc.SetXTitle("Ratio");
+    fHistConc1.SetXTitle("Ratio");
+    fHistConc.SetYTitle("Counts");
+    fHistConc1.SetYTitle("Counts");
+    fHistConc1.UseCurrentStyle();
+    fHistConc.UseCurrentStyle();
+    fHistConc.SetFillStyle(4000);
+    fHistConc1.SetFillStyle(4000);
+    fHistConc1.SetLineColor(kBlue);
+
+
+    MBinning bins;
+
+    bins.SetEdges(100, 0, 1);
+    bins.Apply(fHistLeakage1);
+    bins.Apply(fHistLeakage2);
+    bins.Apply(fHistConc);
+    bins.Apply(fHistConc1);
+
+    bins.SetEdges(75, 0.5, 150.5);
+    bins.Apply(fHistUsedPix);
+    bins.Apply(fHistCorePix);
+
+    //bins.SetEdges(75, 0, 0.249);
+    //bins.Apply(fHistUsedArea);
+    //bins.Apply(fHistCoreArea);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHNewImagePar::SetupFill(const MParList *plist)
+{
+    MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << GetDescriptor() << ": No Camera Geometry available. Using mm-scale for histograms." << endl;
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+        SetMmScale(kFALSE);
+    }
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningArea");
+    if (!bins)
+    {
+        float r = geom ? 1.5 : 0.133;
+
+        MBinning b;
+        b.SetEdges(50, 0, r);
+        b.Apply(fHistUsedArea);
+        b.Apply(fHistCoreArea);
+    }
+    else
+    {
+        bins->Apply(fHistUsedArea);
+        bins->Apply(fHistCoreArea);
+    }
+
+    ApplyBinning(*plist, "Leakage", &fHistLeakage1);
+    ApplyBinning(*plist, "Leakage", &fHistLeakage2);
+
+    ApplyBinning(*plist, "Pixels",  &fHistUsedPix);
+    ApplyBinning(*plist, "Pixels",  &fHistCorePix);
+
+    //ApplyBinning(*plist, "Area",    &fHistUsedArea);
+    //ApplyBinning(*plist, "Area",    &fHistCoreArea);
+
+    ApplyBinning(*plist, "Conc",    &fHistConc);
+    ApplyBinning(*plist, "Conc1",   &fHistConc1);
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MNewImagePar container.
+//
+Bool_t MHNewImagePar::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+    {
+        *fLog << err << "MHNewImagePar::Fill: Pointer (!=NULL) expected." << endl;
+        return kFALSE;
+    }
+
+    const Double_t scale = fUseMmScale ? 1e-6 : fMm2Deg*fMm2Deg;
+
+    const MNewImagePar &h = *(MNewImagePar*)par;
+
+    fHistLeakage1.Fill(h.GetLeakage1(), w);
+    fHistLeakage2.Fill(h.GetLeakage2(), w);
+
+    fHistUsedPix.Fill(h.GetNumUsedPixels(), w);
+    fHistCorePix.Fill(h.GetNumCorePixels(), w);
+
+    fHistUsedArea.Fill(h.GetUsedArea()*scale, w);
+    fHistCoreArea.Fill(h.GetCoreArea()*scale, w);
+
+    fHistConc.Fill(h.GetConc(), w);
+    fHistConc1.Fill(h.GetConc1(), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// With this function you can convert the histogram ('on the fly') between
+// degrees and millimeters.
+//
+void MHNewImagePar::SetMmScale(Bool_t mmscale)
+{
+    if (fUseMmScale == mmscale)
+        return;
+
+    if (fMm2Deg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Sorry, no conversion factor for conversion available." << endl;
+        return;
+    }
+
+    const Double_t scale = mmscale ? 1./(fMm2Deg*fMm2Deg) : (fMm2Deg*fMm2Deg);
+    MH::ScaleAxis(&fHistUsedArea,  scale);
+    MH::ScaleAxis(&fHistCoreArea,  scale);
+
+    if (mmscale)
+    {
+        fHistUsedArea.SetXTitle("A [m^{2}]");
+        fHistCoreArea.SetXTitle("A [m^{2}]");
+    }
+    else
+    {
+        fHistUsedArea.SetXTitle("A [deg^{2}]");
+        fHistCoreArea.SetXTitle("A [deg^{2}]");
+    }
+
+    fUseMmScale = mmscale;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this function to setup your own conversion factor between degrees
+// and millimeters. The conversion factor should be the one calculated in
+// MGeomCam. Use this function with Caution: You could create wrong values
+// by setting up your own scale factor.
+//
+void MHNewImagePar::SetMm2Deg(Float_t mmdeg)
+{
+    if (mmdeg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Conversion factor < 0 - nonsense. Ignored." << endl;
+        return;
+    }
+
+    if (fMm2Deg>=0)
+        *fLog << warn << dbginf << "Warning - Conversion factor already set. Overwriting" << endl;
+
+    fMm2Deg = mmdeg;
+}
+
+void MHNewImagePar::Paint(Option_t *o)
+{
+    if (TString(o)==(TString)"log" && fHistLeakage1.GetMaximum()>0)
+        gPad->SetLogy();
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the two histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHNewImagePar::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    TAxis &x = *fHistLeakage1.GetXaxis();
+    x.SetRangeUser(0.0, x.GetXmax());
+    MH::DrawSame(fHistLeakage1, fHistLeakage2, "Leakage1 and Leakage2");
+    fHistLeakage1.SetMinimum();
+    fHistLeakage2.SetMinimum();
+    fHistLeakage2.SetMaximum(0.1);   // dummy value to allow log-scale
+    AppendPad("log");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    MH::DrawSame(fHistCorePix, fHistUsedPix, "Number of core/used Pixels");
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    MH::DrawSame(fHistConc1, fHistConc, "Concentrations");
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    MH::DrawSame(fHistCoreArea, fHistUsedArea, "Area of core/used Pixels");
+}
+
+TH1 *MHNewImagePar::GetHistByName(const TString name)
+{
+    if (name.Contains("Leakage1", TString::kIgnoreCase))
+        return &fHistLeakage1;
+    if (name.Contains("Leakage2", TString::kIgnoreCase))
+        return &fHistLeakage2;
+    if (name.Contains("Conc", TString::kIgnoreCase))
+        return &fHistConc;
+    if (name.Contains("Conc1", TString::kIgnoreCase))
+        return &fHistConc1;
+    if (name.Contains("UsedPix", TString::kIgnoreCase))
+        return &fHistUsedPix;
+    if (name.Contains("CorePix", TString::kIgnoreCase))
+        return &fHistCorePix;
+    if (name.Contains("UsedArea", TString::kIgnoreCase))
+        return &fHistUsedArea;
+    if (name.Contains("CoreArea", TString::kIgnoreCase))
+        return &fHistCoreArea;
+
+    return NULL;
+}
Index: /tags/Mars-V0.9/mimage/MHNewImagePar.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHNewImagePar.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHNewImagePar.h	(revision 9772)
@@ -0,0 +1,62 @@
+#ifndef MARS_MHNewImagePar
+#define MARS_MHNewImagePar
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MHillas;
+
+class MHNewImagePar : public MH
+{
+private:
+    TH1F fHistLeakage1;  //
+    TH1F fHistLeakage2;  //
+
+    TH1F fHistUsedPix;   // Number of used pixels
+    TH1F fHistCorePix;   // Number of core pixels
+
+    TH1F fHistUsedArea;  // Area of used pixels
+    TH1F fHistCoreArea;  // Area of core pixels
+
+    TH1F fHistConc;      // [ratio] concentration ratio: sum of the two highest pixels / fSize
+    TH1F fHistConc1;     // [ratio] concentration ratio: sum of the highest pixel / fSize
+
+    Float_t fMm2Deg;
+    Bool_t  fUseMmScale;
+
+public:
+    MHNewImagePar(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH1 *GetHistByName(const TString name);
+
+    TH1F &GetHistLeakage1()  { return fHistLeakage1; }
+    TH1F &GetHistLeakage2()  { return fHistLeakage2; }
+
+    TH1F &GetHistUsedPix()   { return fHistUsedPix; }
+    TH1F &GetHistCorePix()   { return fHistCorePix; }
+
+    TH1F &GetHistUsedArea()  { return fHistUsedArea; }
+    TH1F &GetHistCoreArea()  { return fHistCoreArea; }
+
+    TH1F &GetHistConc()      { return fHistConc; }
+    TH1F &GetHistConc1()     { return fHistConc1; }
+
+    void SetMmScale(Bool_t mmscale=kTRUE);
+    virtual void SetMm2Deg(Float_t mmdeg);
+
+    void Draw(Option_t *opt="");
+    void Paint(Option_t *opt="");
+
+    ClassDef(MHNewImagePar, 1) // Histograms of new image parameters
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mimage/MHNewImagePar2.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHNewImagePar2.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHNewImagePar2.cc	(revision 9772)
@@ -0,0 +1,207 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 03/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHNewImagePar2
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHNewImagePar2.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TPad.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MNewImagePar2.h"
+
+ClassImp(MHNewImagePar2);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms 
+//
+MHNewImagePar2::MHNewImagePar2(const char *name, const char *title)
+    : fMm2Deg(1), fUseMmScale(kTRUE)
+{
+    fName  = name  ? name  : "MHNewImagePar2";
+    fTitle = title ? title : "Histograms of new image parameters 2";
+
+    fHistBorder1.SetName("Border1");
+    fHistBorder1.SetTitle("Border Line of border pixels (pixel border)");
+    fHistBorder1.SetXTitle("Border");
+    fHistBorder1.SetYTitle("Counts");
+    fHistBorder1.SetDirectory(NULL);
+    fHistBorder1.UseCurrentStyle();
+    fHistBorder1.SetFillStyle(4000);
+
+    fHistBorder2.SetName("Border2");
+    fHistBorder2.SetTitle("Border Line of border pixels (pixel center)");
+    fHistBorder2.SetXTitle("Border");
+    fHistBorder2.SetYTitle("Counts");
+    fHistBorder2.SetDirectory(NULL);
+    fHistBorder2.UseCurrentStyle();
+    fHistBorder2.SetLineColor(kBlue);
+    fHistBorder2.SetFillStyle(4000);
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms automatically if the correct
+// instances of MBinning
+//
+Bool_t MHNewImagePar2::SetupFill(const MParList *plist)
+{
+    MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << GetDescriptor() << ": No Camera Geometry available. Using mm-scale for histograms." << endl;
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+        SetMmScale(kFALSE);
+    }
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningBorder");
+    if (!bins)
+    {
+        const float r = geom ? 10 : 2967;
+
+        MBinning b;
+        b.SetEdges(87, 0, r);
+        b.Apply(fHistBorder1);
+        b.Apply(fHistBorder2);
+    }
+    else
+    {
+        bins->Apply(fHistBorder1);
+        bins->Apply(fHistBorder2);
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms with data from a MNewImagePar2 container.
+//
+Bool_t MHNewImagePar2::Fill(const MParContainer *par, const Stat_t w)
+{
+    const MNewImagePar2 *h = dynamic_cast<const MNewImagePar2*>(par);
+    if (!h)
+    {
+        *fLog << err << "MHNewImagePar2::Fill: Pointer (!=NULL) expected." << endl;
+        return kFALSE;
+    }
+
+    const Double_t scale = fUseMmScale ? 1 : fMm2Deg;
+
+    fHistBorder1.Fill(h->GetBorderLinePixel() *scale, w);
+    fHistBorder2.Fill(h->GetBorderLineCenter()*scale, w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// With this function you can convert the histogram ('on the fly') between
+// degrees and millimeters.
+//
+void MHNewImagePar2::SetMmScale(Bool_t mmscale)
+{
+    if (fUseMmScale == mmscale)
+        return;
+
+    if (fMm2Deg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Sorry, no conversion factor for conversion available." << endl;
+        return;
+    }
+
+    const Double_t scale = mmscale ? 1./fMm2Deg : fMm2Deg;
+    MH::ScaleAxis(&fHistBorder1,  scale);
+    MH::ScaleAxis(&fHistBorder2,  scale);
+
+    if (mmscale)
+    {
+        fHistBorder1.SetXTitle("L [mm]");
+        fHistBorder2.SetXTitle("L [mm]");
+    }
+    else
+    {
+        fHistBorder1.SetXTitle("L [\\circ]");
+        fHistBorder2.SetXTitle("L [\\circ]");
+    }
+
+    fUseMmScale = mmscale;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this function to setup your own conversion factor between degrees
+// and millimeters. The conversion factor should be the one calculated in
+// MGeomCam. Use this function with Caution: You could create wrong values
+// by setting up your own scale factor.
+//
+void MHNewImagePar2::SetMm2Deg(Float_t mmdeg)
+{
+    if (mmdeg<0)
+    {
+        *fLog << warn << dbginf << "Warning - Conversion factor < 0 - nonsense. Ignored." << endl;
+        return;
+    }
+
+    if (fMm2Deg>=0)
+        *fLog << warn << dbginf << "Warning - Conversion factor already set. Overwriting" << endl;
+
+    fMm2Deg = mmdeg;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the two histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHNewImagePar2::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    gPad->SetBorderMode(0);
+    MH::DrawSame(fHistBorder1, fHistBorder2, "Border Line");
+}
Index: /tags/Mars-V0.9/mimage/MHNewImagePar2.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHNewImagePar2.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHNewImagePar2.h	(revision 9772)
@@ -0,0 +1,38 @@
+#ifndef MARS_MHNewImagePar2
+#define MARS_MHNewImagePar2
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MHillas;
+
+class MHNewImagePar2 : public MH
+{
+private:
+    TH1F fHistBorder1;  //
+    TH1F fHistBorder2;  //
+
+    Float_t fMm2Deg;
+    Bool_t  fUseMmScale;
+
+public:
+    MHNewImagePar2(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    void SetMmScale(Bool_t mmscale=kTRUE);
+    virtual void SetMm2Deg(Float_t mmdeg);
+
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHNewImagePar2, 1) // Histograms of new image parameters
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mimage/MHillas.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHillas.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillas.cc	(revision 9772)
@@ -0,0 +1,409 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!   Author(s): Rudolf Bock     10/2001 <mailto:Rudolf.Bock@cern.ch>
+!   Author(s): Wolfgang Wittek  6/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHillas
+//
+// Storage Container for image parameters
+//
+//    basic image parameters
+//
+// Version 1:
+// ----------
+// fLength   [mm]       major axis of ellipse
+// fWidth    [mm]       minor axis
+// fDelta    [rad]      angle of major axis with x-axis
+//                      by definition the major axis is pointing into
+//                      the hemisphere x>0, thus -pi/2 < delta < pi/2
+// fSize     [#CerPhot] total sum of pixels
+// fMeanX    [mm]       x of center of ellipse
+// fMeanY    [mm]       y of center of ellipse
+//
+// Version 2:
+// ----------
+// fNumCorePixels  number of pixels called core
+// fNumUsedPixels  number of pixels which survived the cleaning
+//
+// Version 3:
+// ----------
+// fNumCorePixels  moved to MNewImagePar
+// fNumUsedPixels  moved to MNewImagePar
+// fCosDelta       added
+// fSinDelte       added
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHillas.h"
+
+#include <TArrayF.h>
+
+#include <TLine.h>
+#include <TEllipse.h>
+#include <TVector2.h>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHillas);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillas::MHillas(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHillas";
+    fTitle = title ? title : "Storage container for image parameters of one event";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// Initializes the values with defaults. For the default values see the
+// source code.
+//
+void MHillas::Reset()
+{
+    fLength = -1;
+    fWidth  = -1;
+    fDelta  =  0;
+
+    fSize   = -1;
+    fMeanX  =  0;
+    fMeanY  =  0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  return the mean position as TVector2(meanx, meany)
+//
+TVector2 MHillas::GetMean() const
+{
+    return TVector2(fMeanX, fMeanY);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Analytical estimation of length of border line:
+//    U = pi*(a+b - sqrt(a*b))
+//
+//  GetBorderLine() [mm]
+//
+Double_t MHillas::GetBorderLine() const
+{
+    const Double_t a = fWidth+fLength;
+    const Double_t s = fWidth*fLength;
+
+    return TMath::Pi()*(1.5*a - TMath::Sqrt(s));
+}
+
+// --------------------------------------------------------------------------
+//
+//  Analytical estimation of length of border line:
+//    A = pi*a*b
+//
+//  GetArea() [mm^2]
+//
+Double_t MHillas::GetArea() const
+{
+    return TMath::Pi()*fWidth*fLength;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the hillas Parameters to *fLog
+//
+void MHillas::Print(Option_t *) const
+{
+    Double_t atg = atan2(fMeanY, fMeanX)*kRad2Deg;
+
+    if (atg<0)
+        atg += 180;
+
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Length         [mm]  = " << fLength << endl;
+    *fLog << " - Width          [mm]  = " << fWidth  << endl;
+    *fLog << " - Delta          [deg] = " << fDelta*kRad2Deg << endl;
+    *fLog << " - Size           [1]   = " << fSize   << " #CherPhot"   << endl;
+    *fLog << " - Meanx          [mm]  = " << fMeanX  << endl;
+    *fLog << " - Meany          [mm]  = " << fMeanY  << endl;
+    *fLog << " - atg(y/x)       [deg] = " << atg     << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the hillas Parameters to *fLog, depending on the geometry in
+// units of deg
+//
+void MHillas::Print(const MGeomCam &geom) const
+{
+    Double_t atg = atan2(fMeanY, fMeanX)*kRad2Deg;
+
+    if (atg<0)
+        atg += 180;
+
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Length         [deg] = " << fLength*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Width          [deg] = " << fWidth *geom.GetConvMm2Deg() << endl;
+    *fLog << " - Delta          [deg] = " << fDelta*kRad2Deg << endl;
+    *fLog << " - Size           [1]   = " << fSize   << " #CherPhot"   << endl;
+    *fLog << " - Meanx          [deg] = " << fMeanX *geom.GetConvMm2Deg() << endl;
+    *fLog << " - Meany          [deg] = " << fMeanY *geom.GetConvMm2Deg() << endl;
+    *fLog << " - atg(y/x)       [deg] = " << atg     << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MHillas::Paint(Option_t *opt)
+{
+    static const Float_t sOffsetW=40.0;
+    static const Float_t sOffsetL=266.0;
+
+    if (fLength<0 || fWidth<0)
+        return;
+
+    const Float_t l = fLength+sOffsetL;
+    const Float_t w = fWidth +sOffsetW;
+
+    TLine line;
+    line.SetLineWidth(1);
+    line.SetLineColor(kRed);
+
+    // Length line
+    line.PaintLine(-l*fCosDelta+fMeanX, -l*fSinDelta+fMeanY,
+                   +l*fCosDelta+fMeanX, +l*fSinDelta+fMeanY);
+
+
+    // Width line
+    line.PaintLine(+w*fSinDelta+fMeanX, -w*fCosDelta+fMeanY,
+                   -w*fSinDelta+fMeanX, +w*fCosDelta+fMeanY);
+
+    TEllipse e(fMeanX, fMeanY, fLength, fWidth, 0, 360, fDelta*kRad2Deg+180);
+    e.SetLineWidth(2);
+    e.SetLineColor(kGreen);
+    e.Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the image parameters from a Cherenkov photon event
+// assuming Cher.photons/pixel and pixel coordinates are given
+// In case you don't call Calc from within an eventloop make sure, that
+// you call the Reset member function before.
+// Returns:
+//   0  no error
+//   1  number of pixels in event == 0 (special MC events)
+//   2  size==0
+//   3  number of used pixel < 3
+//   4  CorrXY == 0
+//
+Int_t MHillas::Calc(const MGeomCam &geom, const MSignalCam &evt, Int_t island)
+{
+    const UInt_t numpix  = evt.GetNumPixels();
+
+    //
+    // sanity check 1 (special MC events)
+    //
+    if (numpix==0)
+        return 1;
+
+    //
+    // calculate mean value of pixel coordinates and fSize
+    // -----------------------------------------------------
+    //
+    // Because this are only simple sums of roughly 600 values
+    // with an accuracy less than three digits there should not
+    // be any need to use double precision (Double_t) for the
+    // calculation of fMeanX, fMeanY and fSize.
+    //
+    fMeanX = 0;
+    fMeanY = 0;
+    fSize  = 0;
+
+    UInt_t numused = 0;
+/*
+    MSignalPix *pix = 0;
+
+    TIter Next(evt);
+    while ((pix=(MSignalPix*)Next()))*/
+    for (UInt_t i=0; i<numpix; i++)
+    {
+        MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        const MGeomPix &gpix = geom[i/*pix->GetPixId()*/];
+
+        const Float_t nphot = pix.GetNumPhotons();
+
+        fSize  += nphot;		             // [counter]
+        fMeanX += nphot * gpix.GetX();               // [mm]
+        fMeanY += nphot * gpix.GetY();               // [mm]
+
+        numused++;
+    }
+
+    //
+    // sanity check 2
+    //
+    if (fSize==0)
+        return 2;
+
+    fMeanX /= fSize;                                 // [mm]
+    fMeanY /= fSize;                                 // [mm]
+
+    //
+    // sanity check 3
+    //
+    if (numused<3)
+        return 3;
+
+    //
+    // calculate 2nd moments
+    // ---------------------
+    //
+    // To make sure that the more complicated sum is evaluated as
+    // accurate as possible (because it is needed for more
+    // complicated calculations (see below) we calculate it using
+    // double prcision.
+    //
+    Double_t corrxx=0;                               // [m^2]
+    Double_t corrxy=0;                               // [m^2]
+    Double_t corryy=0;                               // [m^2]
+
+    //Next.Reset();
+    //while ((pix=(MSignalPix*)Next()))
+    //{
+    for (UInt_t i=0; i<numpix; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        const MGeomPix &gpix = geom[i/*pix->GetPixId()*/];
+
+        const Float_t dx = gpix.GetX() - fMeanX;     // [mm]
+        const Float_t dy = gpix.GetY() - fMeanY;     // [mm]
+
+        const Float_t nphot = pix.GetNumPhotons();   // [#phot]
+
+        corrxx += nphot * dx*dx;                     // [mm^2]
+        corrxy += nphot * dx*dy;                     // [mm^2]
+        corryy += nphot * dy*dy;                     // [mm^2]
+    }
+
+    //
+    // If corrxy=0 (which should happen not very often, because fSize>0)
+    // we cannot calculate Length and Width.
+    // In reallity it is almost impossible to have a distribution of
+    // cerenkov photons in the used pixels which is exactly symmetric
+    // along one of the axis.
+    // It seems to be less than 0.1% of all events.
+    //
+    if (corrxy==0)
+        return 4;
+
+    //
+    // calculate the basic Hillas parameters: orientation and size of axes
+    // -------------------------------------------------------------------
+    //
+    // fDelta is the angle between the major axis of the ellipse and
+    //  the x axis. It is independent of the position of the ellipse
+    //  in the camera it has values between -pi/2 and pi/2 degrees
+    //
+    // Rem: I tested replacing sqrt() by hypot() but they exactly
+    //      consume the same amount of time
+    //
+    const Double_t d0    = corryy - corrxx;
+    const Double_t d1    = corrxy*2;
+    const Double_t d2    = d0 + TMath::Sqrt(d0*d0 + d1*d1);
+    const Double_t tand  = d2 / d1;
+    const Double_t tand2 = tand*tand;
+
+    fDelta = TMath::ATan(tand);
+
+    const Double_t s2 = tand2+1;
+    const Double_t s  = TMath::Sqrt(s2);
+
+    fCosDelta =  1.0/s;   // need these in derived classes
+    fSinDelta = tand/s;   // like MHillasExt
+
+    const Double_t axis1 = (tand2*corryy + d2 + corrxx)/s2/fSize;
+    const Double_t axis2 = (tand2*corrxx - d2 + corryy)/s2/fSize;
+
+    //
+    // fLength^2 is the second moment along the major axis of the ellipse
+    // fWidth^2  is the second moment along the minor axis of the ellipse
+    //
+    // From the algorithm we get: fWidth <= fLength is always true
+    //
+    // very small numbers can get negative by rounding
+    //
+    fLength = axis1<0 ? 0 : TMath::Sqrt(axis1);  // [mm]
+    fWidth  = axis2<0 ? 0 : TMath::Sqrt(axis2);  // [mm]
+
+    SetReadyToSave();
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function is ment for special usage, please never try to set
+// values via this function
+//
+void MHillas::Set(const TArrayF &arr)
+{
+    if (arr.GetSize() != 6)
+        return;
+
+    fLength = arr.At(0);  // [mm]        major axis of ellipse
+    fWidth  = arr.At(1);  // [mm]        minor axis of ellipse
+    fDelta  = arr.At(2);  // [rad]       angle of major axis with x-axis
+    fSize   = arr.At(3);  // [#CerPhot]  sum of content of all pixels (number of Cherenkov photons)
+    fMeanX  = arr.At(4);  // [mm]        x-coordinate of center of ellipse
+    fMeanY  = arr.At(5);  // [mm]        y-coordinate of center of ellipse
+}
Index: /tags/Mars-V0.9/mimage/MHillas.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHillas.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillas.h	(revision 9772)
@@ -0,0 +1,60 @@
+#ifndef MARS_MHillas
+#define MARS_MHillas
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TArrayF;
+class TVector2;
+
+class MGeomCam;
+class MSignalCam;
+
+class MHillas : public MParContainer
+{
+private:
+    // for description see MHillas.cc
+    Float_t fLength;        // [mm]        major axis of ellipse
+    Float_t fWidth;         // [mm]        minor axis of ellipse
+    Float_t fDelta;         // [rad]       angle of major axis with x-axis
+    Float_t fSize;          // [#CerPhot]  sum of content of all pixels (number of Cherenkov photons)
+    Float_t fMeanX;         // [mm]        x-coordinate of center of ellipse
+    Float_t fMeanY;         // [mm]        y-coordinate of center of ellipse
+
+    Float_t fSinDelta;      // [1] sin of Delta (to be used in derived classes)
+    Float_t fCosDelta;      // [1] cos of Delta (to be used in derived classes)
+
+public:
+    MHillas(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Int_t Calc(const MGeomCam &geom, const MSignalCam &pix, Int_t island=-1);
+
+    void Print(const MGeomCam &geom) const;
+    void Print(Option_t *opt=NULL) const;
+    void Paint(Option_t *opt=NULL);
+
+    Float_t  GetLength() const { return fLength; }
+    Float_t  GetWidth() const  { return fWidth; }
+    Float_t  GetDelta() const  { return fDelta; }
+    Float_t  GetSize() const   { return fSize; }
+    Float_t  GetMeanX() const  { return fMeanX; }
+    Float_t  GetMeanY() const  { return fMeanY; }
+    Double_t GetDist0() const  { return TMath::Hypot(fMeanX, fMeanY); } // return distance to center
+
+    TVector2 GetMean() const;
+
+    Double_t GetBorderLine() const;
+    Double_t GetArea() const;
+
+    Float_t GetCosDelta() const { return fCosDelta; }
+    Float_t GetSinDelta() const { return fSinDelta; }
+
+    void Set(const TArrayF &arr);
+
+    ClassDef(MHillas, 3) // Storage Container for Hillas Parameter
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MHillasCalc.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHillasCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillasCalc.cc	(revision 9772)
@@ -0,0 +1,470 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer, 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHillasCalc
+//  ===========
+//
+//  This is a task to calculate the Hillas parameters from each event
+//
+//
+//   Flags
+//  --------
+//
+//  By default all flags are set:
+//
+//  To switch of the calculation you may use:
+//   - Disable(MHillasCalc::kCalcHillas)
+//   - Disable(MHillasCalc::kCalcHillasExt)
+//   - Disable(MHillasCalc::kCalcNewImagePar)
+//   - Disable(MHillasCalc::kCalcImagePar)
+//   - Disable(MHillasCalc::kCalcImagePar2)
+//   - Disable(MHillasCalc::kCalcSrcPosCam)
+//   - Disable(MHillasCalc::kCalcConc)
+//
+//  If the calculation of MHillas is switched off a container MHillas
+//  in the parameter list is nevertheless necessary for the calculation
+//  of some other containers, see below.
+//
+//  If kCalcHillasSrc is set and no corresponding MSrcPosCam is found
+//  in the parameter list an empty container (X=0, Y=0) is created.
+//
+//
+//   Container names
+//  -----------------
+//
+//  The names of the containers to be used can be set with:
+//   - SetNameHillas("NewName")
+//   - SetNameHillasExt("NewName")
+//   - SetNameNewImgPar("NewName")
+//   - SetNameImagePar("NewName")
+//   - SetNameImagePar2("NewName")
+//   - SetNameSrcPosCam("NewName")
+//   - SetNameConc("NewName")
+//   - SetNameHillasSrc("NewName")
+//
+//
+//   Islands
+//  ---------
+//
+//  You can change the islands for which the caluclations are done by:
+//   - SetNumIsland()
+//  The default is to use all used pixels (-1)
+//
+//  fIdxIslands effects the calculations:
+//   - kCalcHillas
+//   - kCalcHillasExt
+//   - kCalcNewImgPar
+//   - kCalcNewImgPar2
+//
+//
+//   Example
+//  ---------
+//
+//   MHillasCalc calc0; // calculate all image parameters except source dep.
+//   MHillasCalc calc1; // calculate source dependant image parameters for 'Source'
+//   MHillasCalc calc2; // calculate source dependant image parameters for 'AntiSource'
+//   MHillasCalc calc3; // calculate hillas parameters only for biggest island
+//   MHillasCalc calc4; // calculate hillas parameter for 2nd biggest island
+//   // setup names of input-/output-containers
+//   calc1.SetNameSrcPosCam("Source");
+//   calc2.SetNameSrcPosCam("AntiSource");
+//   calc1.SetNameHillasSrc("MHillasSource");
+//   calc2.SetNameHillasSrc("MHillasAntiSource");
+//   calc3.SetNameHillas("MHillas0");
+//   calc4.SetNameHillas("MHillas1");
+//   // setup calculations to be done
+//   calc0.Disable(MHillasCalc::kCalcHillasSrc);
+//   calc1.SetFlags(MHillasCalc::kCalcHillasSrc);
+//   calc2.SetFlags(MHillasCalc::kCalcHillasSrc);
+//   calc3.SetFlags(MHillasCalc::kCalcHillas);
+//   calc4.SetFlags(MHillasCalc::kCalcHillas);
+//   // choode index of island
+//   calc3.SetNumIsland(0);
+//   calc4.SetNumIsland(1);
+//
+//   // setup tasklist
+//   MTaskList list;
+//   list.Add(&calc0);
+//   list.Add(&calc1);
+//   list.Add(&calc2);
+//   list.Add(&calc3);
+//   list.Add(&calc4);
+//
+//
+//   Input/Output Containers
+//  -------------------------
+//
+//    1) MGeomCam          5) MHillas         8) MImagePar
+//    2) MSignalCam        6) MHillasSrc      9) MNewImagePar
+//    3) MSrcPosCam        7) MHillasExt     10) MNewImagePar2
+//    4) fIdxIslands      11) MConcentration
+//
+//     Flag           | Input Container | Output
+//   -----------------+-----------------+--------
+//    kCalcHillas     |  1  2     4     |    5
+//    kCalcHillasSrc  |        3  4  5  |    6
+//    kCalcHillasExt  |  1  2     4  5  |    7
+//    kCalcImagePar   |     2           |    8
+//    kCalcNewImgPar  |  1  2     4  5  |    9
+//    kCalcNewImgPar2 |  1  2     4     |   10
+//    kCalcConc       |  1  2        5  |   11
+//   -----------------+-----------------+--------
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHillasCalc.h"
+
+#include <fstream> // StreamPrimitive
+
+#include "MParList.h"
+
+#include "MSignalCam.h"
+
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MImagePar.h"
+#include "MNewImagePar.h"
+#include "MNewImagePar2.h"
+#include "MConcentration.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHillasCalc);
+
+using namespace std;
+
+const TString MHillasCalc::gsDefName         = "MHillasCalc";
+const TString MHillasCalc::gsDefTitle        = "Calculate Hillas and other image parameters";
+
+const TString MHillasCalc::gsNameHillas      = "MHillas";        // default name of the 'MHillas' container
+const TString MHillasCalc::gsNameHillasExt   = "MHillasExt";     // default name of the 'MHillasExt' container
+const TString MHillasCalc::gsNameNewImagePar = "MNewImagePar";   // default name of the 'MNewImagePar' container
+const TString MHillasCalc::gsNameNewImagePar2= "MNewImagePar2";  // default name of the 'MNewImagePar2' container
+const TString MHillasCalc::gsNameConc        = "MConcentration"; // default name of the 'MConcentration' container
+const TString MHillasCalc::gsNameImagePar    = "MImagePar";      // default name of the 'MImagePar' container
+const TString MHillasCalc::gsNameHillasSrc   = "MHillasSrc";     // default name of the 'MHillasSrc' container
+const TString MHillasCalc::gsNameSrcPosCam   = "MSrcPosCam";     // default name of the 'MSrcPosCam' container
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillasCalc::MHillasCalc(const char *name, const char *title)
+        : fNameHillas(gsNameHillas),       fNameHillasExt(gsNameHillasExt),
+          fNameHillasSrc(gsNameHillasSrc), fNameSrcPosCam(gsNameSrcPosCam),
+          fNameConc(gsNameConc),           fNameImagePar(gsNameImagePar),
+          fNameNewImagePar(gsNameNewImagePar),
+          fNameNewImagePar2(gsNameNewImagePar2),
+          fErrors(7), fFlags(0xff), fIdxIsland(-1)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for in-/output containers, see class description
+//
+Int_t MHillasCalc::PreProcess(MParList *pList)
+{
+
+    if (TestFlags(~kCalcHillasSrc))
+    {
+        fCerPhotEvt = (MSignalCam*)pList->FindObject(AddSerialNumber("MSignalCam"));
+        if (!fCerPhotEvt)
+        {
+            *fLog << err << "MSignalCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    if (TestFlags(kCalcHillas|kCalcHillasExt|kCalcNewImagePar|kCalcNewImagePar2|kCalcConc))
+    {
+        fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+        if (!fGeomCam)
+        {
+            *fLog << err << "MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    // depend on whether MHillas is an in- or output container
+    if (TestFlag(kCalcHillas))
+    {
+        fHillas = (MHillas*)pList->FindCreateObj("MHillas", AddSerialNumber(fNameHillas));
+        if (!fHillas)
+            return kFALSE;
+    }
+
+    if (TestFlags(kCalcHillasExt|kCalcNewImagePar|kCalcConc|kCalcHillasSrc))
+    {
+        fHillas = (MHillas*)pList->FindObject(AddSerialNumber(fNameHillas), "MHillas");
+        if (!fHillas)
+        {
+            *fLog << err << fNameHillas << " [MHillas] not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    // if enabled
+    if (TestFlag(kCalcHillasExt))
+    {
+        fHillasExt = (MHillasExt*)pList->FindCreateObj("MHillasExt", AddSerialNumber(fNameHillasExt));
+        if (!fHillasExt)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcHillasSrc))
+    {
+        const MSrcPosCam *src = (MSrcPosCam*)pList->FindObject(AddSerialNumber(fNameSrcPosCam), "MSrcPosCam");
+        if (!src)
+        {
+            *fLog << warn << AddSerialNumber(fNameSrcPosCam) << " [MSrcPosCam] not found... creating default container." << endl;
+            src = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam", AddSerialNumber(fNameSrcPosCam));
+        }
+        if (!src)
+            return kFALSE;
+
+        fHillasSrc = (MHillasSrc*)pList->FindCreateObj("MHillasSrc", AddSerialNumber(fNameHillasSrc));
+        if (!fHillasSrc)
+            return kFALSE;
+
+        fHillasSrc->SetSrcPos(src);
+    }
+
+    // if enabled
+    if (TestFlag(kCalcNewImagePar))
+    {
+        fNewImgPar = (MNewImagePar*)pList->FindCreateObj("MNewImagePar", AddSerialNumber(fNameNewImagePar));
+        if (!fNewImgPar)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcNewImagePar2))
+    {
+        fNewImgPar2 = (MNewImagePar2*)pList->FindCreateObj("MNewImagePar2", AddSerialNumber(fNameNewImagePar2));
+        if (!fNewImgPar2)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcImagePar))
+    {
+        fImagePar = (MImagePar*)pList->FindCreateObj("MImagePar", AddSerialNumber(fNameImagePar));
+        if (!fImagePar)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcConc))
+    {
+        fConc = (MConcentration*)pList->FindCreateObj("MConcentration", fNameConc);
+        if (!fConc)
+            return kFALSE;
+    }
+
+    fErrors.Reset();
+
+    Print();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want do complex descisions inside the calculations
+// we must move the calculation code inside this function
+//
+// If the calculation wasn't sucessfull skip this event
+//
+Int_t MHillasCalc::Process()
+{
+    if (TestFlag(kCalcHillas))
+    {
+        const Int_t rc = fHillas->Calc(*fGeomCam, *fCerPhotEvt, fIdxIsland);
+        if (rc<0 || rc>4)
+        {
+            *fLog << err << dbginf << "MHillas::Calc returned unknown error code!" << endl;
+            return kFALSE;
+        }
+        if (rc>0)
+        {
+            fErrors[rc]++;
+            return kCONTINUE;
+        }
+    }
+
+    if (TestFlag(kCalcHillasSrc))
+    {
+        const Int_t rc = fHillasSrc->Calc(*fHillas);
+        if (rc<0 || rc>2)
+        {
+            *fLog << err << dbginf << "MHillasSrc::Calc returned unknown error code!" << endl;
+            return kFALSE;
+        }
+        if (rc>0)
+        {
+            fErrors[rc+4]++;
+            return kCONTINUE;
+        }
+    }
+    fErrors[0]++;
+
+    if (TestFlag(kCalcHillasExt))
+        fHillasExt->Calc(*fGeomCam, *fCerPhotEvt, *fHillas, fIdxIsland);
+
+    if (TestFlag(kCalcImagePar))
+        fImagePar->Calc(*fCerPhotEvt);
+
+    if (TestFlag(kCalcNewImagePar))
+        fNewImgPar->Calc(*fGeomCam, *fCerPhotEvt, *fHillas, fIdxIsland);
+
+    if (TestFlag(kCalcNewImagePar2))
+        fNewImgPar2->Calc(*fGeomCam, *fCerPhotEvt, fIdxIsland);
+
+    if (TestFlag(kCalcConc))
+        fConc->Calc(*fGeomCam, *fCerPhotEvt, *fHillas);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the hillas calculation. The percentage
+//  is calculated with respect to the number of executions of this task.
+//
+Int_t MHillasCalc::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    if (!TestFlag(kCalcHillas) && !TestFlag(kCalcHillasSrc))
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    if (TestFlag(kCalcHillas))
+    {
+        PrintSkipped(fErrors[1], "0-Pixel Event (before cleaning, MC event?)");
+        PrintSkipped(fErrors[2], "Calculated Size == 0 (after cleaning)");
+        PrintSkipped(fErrors[3], "Number of used pixels < 3");
+        PrintSkipped(fErrors[4], "CorrXY==0");
+    }
+    if (TestFlag(kCalcHillasSrc))
+    {
+        PrintSkipped(fErrors[5], "Dist==0");
+        PrintSkipped(fErrors[6], "Arg2==0");
+    }
+    *fLog << " " << (int)fErrors[0] << " (" << Form("%5.1f", 100.*fErrors[0]/GetNumExecutions()) << "%) Evts survived Hillas calculation!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print 'Dataflow'
+//
+void MHillasCalc::Print(Option_t *o) const
+{
+    *fLog << inf << GetDescriptor() << " calculating:" << endl;
+    if (TestFlag(kCalcHillas))
+        *fLog << " - " << fNameHillas << " from MGeomCam, MSignalCam and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcHillasSrc))
+        *fLog << " - " << fNameHillasSrc << " from " << fNameSrcPosCam << ", " << fNameHillas << " and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcHillasExt))
+        *fLog << " - " << fNameHillasExt << " from MGeomCam, MSignalCam, " << fNameHillas << " and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcImagePar))
+        *fLog << " - " << fNameImagePar << " from MSignalCam" << endl;
+    if (TestFlag(kCalcNewImagePar))
+        *fLog << " - " << fNameNewImagePar << " from MGeomCam, MSignalCam, " << fNameHillas << " and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcNewImagePar2))
+        *fLog << " - " << fNameNewImagePar2 << " from MGeomCam, MSignalCam, " << fNameHillas << " and fIdxIsland=" << fIdxIsland << endl;
+    if (TestFlag(kCalcConc))
+        *fLog << " - " << fNameConc << " from MGeomCam, MSignalCam and " << fNameHillas << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MHillasCalc::StreamPrimitive(ofstream &out) const
+{
+    out << "   MHillasCalc " << GetUniqueName() << "(";
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+    if (TestFlags(kCalcHillasExt|kCalcNewImagePar|kCalcConc|kCalcHillasSrc))
+    {
+        if (fNameHillas!=gsNameHillas)
+            out << "   " << GetUniqueName() << ".SetNameHillas(\"" << fNameHillas << "\");" << endl;
+    }
+    if (TestFlag(kCalcHillasSrc) && fNameHillasSrc!=gsNameHillasSrc)
+    {
+        out << "   " << GetUniqueName() << ".SetNameHillasSrc(\"" << fNameHillasSrc << "\");" << endl;
+        out << "   " << GetUniqueName() << ".SetNameSrcPosCam(\"" << fNameSrcPosCam << "\");" << endl;
+    }
+    if (TestFlag(kCalcHillasExt) && fNameHillasExt!=gsNameHillasExt)
+        out << "   " << GetUniqueName() << ".SetNameHillasExt(\"" << fNameHillasExt << "\");" << endl;
+    if (TestFlag(kCalcConc) && fNameConc!=gsNameConc)
+        out << "   " << GetUniqueName() << ".SetNameConc(\"" << fNameConc << "\");" << endl;
+    if (TestFlag(kCalcImagePar) && fNameImagePar!=gsNameImagePar)
+        out << "   " << GetUniqueName() << ".SetNameImagePar(\"" << fNameImagePar << "\");" << endl;
+    if (TestFlag(kCalcNewImagePar) && fNameNewImagePar!=gsNameNewImagePar)
+        out << "   " << GetUniqueName() << ".SetNameNewImagePar(\"" << fNameNewImagePar << "\");" << endl;
+    if (TestFlag(kCalcNewImagePar2) && fNameNewImagePar2!=gsNameNewImagePar2)
+        out << "   " << GetUniqueName() << ".SetNameNewImagePar2(\"" << fNameNewImagePar2 << "\");" << endl;
+
+    if (!TestFlag(kCalcHillas))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcHillas);" << endl;
+    if (!TestFlag(kCalcHillasExt))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcHillasExt);" << endl;
+    if (!TestFlag(kCalcHillasSrc))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcHillasSrc);" << endl;
+    if (!TestFlag(kCalcNewImagePar))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcNewImagePar);" << endl;
+    if (!TestFlag(kCalcNewImagePar2))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcNewImagePar2);" << endl;
+    if (!TestFlag(kCalcConc))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcConc);" << endl;
+    if (!TestFlag(kCalcImagePar))
+        out << "   " << GetUniqueName() << ".Disable(MHilllasCalc::kCalcImagePar);" << endl;
+
+    if (fIdxIsland>=0)
+        out << "   " << GetUniqueName() << ".SetNumIsland(" << fIdxIsland << ");" << endl;
+}
+
Index: /tags/Mars-V0.9/mimage/MHillasCalc.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHillasCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillasCalc.h	(revision 9772)
@@ -0,0 +1,119 @@
+#ifndef MARS_MHillasCalc
+#define MARS_MHillasCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MHillasCalkc                                                            //
+//                                                                         //
+// Task to calculate Hillas Parameters                                     //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MGeomCam;
+class MSignalCam;
+class MHillas;
+class MHillasExt;
+class MHillasSrc;
+class MImagePar;
+class MNewImagePar;
+class MNewImagePar2;
+class MConcentration;
+class MSrcPosCam;
+
+class MHillasCalc : public MTask
+{
+    static const TString gsDefName;         // default name
+    static const TString gsDefTitle;        // default title
+
+    static const TString gsNameHillas;      // default name of the 'MHillas' container
+    static const TString gsNameHillasExt;   // default name of the 'MHillasExt' container
+    static const TString gsNameNewImagePar; // default name of the 'MNewImagePar' container
+    static const TString gsNameNewImagePar2; // default name of the 'MNewImagePar' container
+    static const TString gsNameConc;        // default name of the 'MConcentration' container
+    static const TString gsNameImagePar;    // default name of the 'MImagePar' container
+    static const TString gsNameHillasSrc;   // default name of the 'MHillasSrc' container
+    static const TString gsNameSrcPosCam;   // default name of the 'MSrcPosCam' container
+
+    const MGeomCam      *fGeomCam;          //! Camera Geometry used to calculate Hillas
+    const MSignalCam    *fCerPhotEvt;       //! Cerenkov Photon Event used for calculation
+
+    MHillas             *fHillas;           //! output container to store result
+    MHillasExt          *fHillasExt;        //! output container to store result
+    MHillasSrc          *fHillasSrc;        //! output container to store result
+    MImagePar           *fImagePar;         //! output container to store result
+    MNewImagePar        *fNewImgPar;        //! output container to store result
+    MNewImagePar2       *fNewImgPar2;       //! output container to store result
+    MConcentration      *fConc;             //! output container to store result
+
+    TString              fNameHillas;       // name of the 'MHillas' container
+    TString              fNameHillasExt;    // name of the 'MHillasExt' container
+    TString              fNameHillasSrc;    // name of the 'MHillasSrc' container
+    TString              fNameSrcPosCam;    // name of the 'MSrcPosCam' container
+    TString              fNameConc;         // name of the 'MConcentration' container
+    TString              fNameImagePar;     // name of the 'MImagePar' container
+    TString              fNameNewImagePar;  // name of the 'MNewImagePar' container
+    TString              fNameNewImagePar2; // name of the 'MNewImagePar' container
+
+    TArrayL              fErrors;           //! Error counter. Do we have to change to Double?
+
+    Int_t                fFlags;            // Flags defining the behaviour of MHillasCalc
+    Short_t              fIdxIsland;        // Number of island to use for calculation
+
+    // MParContainer
+    void StreamPrimitive(ofstream &out) const;
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    // Constructor
+    MHillasCalc(const char *name=NULL, const char *title=NULL);
+
+    // Flags
+    enum CalcCont_t {
+        kCalcHillas       = BIT(0),
+        kCalcHillasExt    = BIT(1),
+        kCalcHillasSrc    = BIT(2),
+        kCalcNewImagePar  = BIT(3),
+        kCalcNewImagePar2 = BIT(4),
+        kCalcConc         = BIT(5),
+        kCalcImagePar     = BIT(6)
+    };
+
+    // Setup flags
+    void SetFlags(Int_t f) { fFlags  =  f; }
+    void Enable(Int_t f)   { fFlags |=  f; }
+    void Disable(Int_t f)  { fFlags &= ~f; }
+
+    Bool_t TestFlag(CalcCont_t i) const { return fFlags&i; }
+    Bool_t TestFlags(Int_t i) const     { return fFlags&i; }
+
+    // Setup container names
+    void SetNameHillas(const char *name)      { fNameHillas      = name; }
+    void SetNameHillasExt(const char *name)   { fNameHillasExt   = name; }
+    void SetNameHillasSrc(const char *name)   { fNameHillasSrc   = name; }
+    void SetNameNewImagePar(const char *name) { fNameNewImagePar = name; }
+    void SetNameNewImagePar2(const char *name){ fNameNewImagePar2 = name; }
+    void SetNameConc(const char *name)        { fNameConc        = name; }
+    void SetNameImagePar(const char *name)    { fNameImagePar    = name; }
+    void SetNameSrcPosCam(const char *name)   { fNameSrcPosCam   = name; }
+
+    // Setup island number
+    void SetIdxIsland(Short_t idx) { fIdxIsland = idx; }
+
+    // TObject
+    void Print(Option_t *o="") const;
+
+    ClassDef(MHillasCalc, 0) // Task to calculate Hillas and other image parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MHillasExt.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHillasExt.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillasExt.cc	(revision 9772)
@@ -0,0 +1,239 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Rudolf Bock     10/2001 <mailto:Rudolf.Bock@cern.ch>
+!   Author(s): Wolfgang Wittek 06/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHillasExt
+//
+// Storage Container for extended image parameters
+//
+//    extended image parameters
+//
+//
+// Version 1:
+// ----------
+// fConc     ratio of sum of two highest pixels over fSize
+// fConc1    ratio of highest pixel over fSize
+// fAsym     distance from highest pixel to center, projected onto major axis
+// fM3Long   third moment along major axis
+// fM3Trans  third moment along minor axis
+//
+// Version 2:
+// ----------
+// fConc     removed
+// fConc1    removed
+//
+// Version 3:
+// ----------
+// fMaxDist  added. Distance between center and most distant used pixel
+//
+//
+// WARNING: Before you can use fAsym, fM3Long and fM3Trans you must
+//          multiply by the sign of MHillasSrc::fCosDeltaAlpha
+//
+////////////////////////////////////////////////////////////////////////////
+/*
+ // fAsymna   d/(d na) of ( sum(x*q^na)/sum(q^na), sum(y*q^na)/sum(q^na) )
+ //           projected onto the major axis
+ // fAsym0    (F-B)/(F+B) along the major axis
+ */
+#include "MHillasExt.h"
+
+#include <TArrayF.h>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+
+ClassImp(MHillasExt);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillasExt::MHillasExt(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHillasExt";
+    fTitle = title ? title : "Storage container for extended parameter set of one event";
+
+    Reset();
+}
+
+// -------------------------------------------------------------------------
+//
+void MHillasExt::Reset()
+{
+    fAsym    =  0;
+    fM3Long  =  0;
+    fM3Trans =  0;
+
+    fMaxDist =  0;
+}
+
+// -------------------------------------------------------------------------
+//
+// calculation of additional parameters based on the camera geometry
+// and the cerenkov photon event
+//
+Int_t MHillasExt::Calc(const MGeomCam &geom, const MSignalCam &evt, const MHillas &hil, Int_t island)
+{
+    //
+    //   calculate the additional image parameters
+    // --------------------------------------------
+    //
+    //  loop to get third moments along ellipse axes and two max pixels
+    //
+    //  For the moments double precision is used to make sure, that
+    //  the complex matrix multiplication and sum is evaluated correctly.
+    //
+    Double_t m3x = 0;
+    Double_t m3y = 0;
+
+    Int_t maxpixid  = 0;
+    Float_t maxpix  = 0;
+    Float_t maxdist = 0;
+
+    //    MSignalPix *pix = 0;
+    //    TIter Next(evt);
+    //    while ((pix=(MSignalPix*)Next()))
+
+    const UInt_t npix = evt.GetNumPixels();
+    for (UInt_t i=0; i<npix; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        //const Int_t pixid = pix->GetPixId();
+
+        const MGeomPix &gpix = geom[i/*pixid*/];
+        const Double_t dx = gpix.GetX() - hil.GetMeanX();      // [mm]
+        const Double_t dy = gpix.GetY() - hil.GetMeanY();      // [mm]
+
+        Double_t nphot = pix.GetNumPhotons();                  // [1]
+
+        const Double_t dzx =  hil.GetCosDelta()*dx + hil.GetSinDelta()*dy; // [mm]
+        const Double_t dzy = -hil.GetSinDelta()*dx + hil.GetCosDelta()*dy; // [mm]
+
+        const Double_t dist = dx*dx+dy*dy;
+        if (TMath::Abs(dist)>TMath::Abs(maxdist))
+            maxdist = dzx<0 ? -dist : dist;                    // [mm^2]
+
+        m3x += nphot * dzx*dzx*dzx;                            // [mm^3]
+        m3y += nphot * dzy*dzy*dzy;                            // [mm^3]
+
+        //
+        // Now we are working on absolute values of nphot, which
+        // must take pixel size into account
+        //
+        nphot *= geom.GetPixRatio(i/*pixid*/);
+
+        if (nphot>maxpix)
+        {
+            maxpix   = nphot;                                  // [1]
+            maxpixid = i;//pixid;
+            continue;                                          // [1]
+        }
+    }
+
+    const MGeomPix &maxp = geom[maxpixid];
+
+    fAsym = (hil.GetMeanX()-maxp.GetX())*hil.GetCosDelta() +
+            (hil.GetMeanY()-maxp.GetY())*hil.GetSinDelta();            // [mm]
+
+    //
+    // Third moments along axes get normalized
+    //
+    m3x /= hil.GetSize();
+    m3y /= hil.GetSize();
+
+    fM3Long  = m3x<0 ? -pow(-m3x, 1./3) : pow(m3x, 1./3);      // [mm]
+    fM3Trans = m3y<0 ? -pow(-m3y, 1./3) : pow(m3y, 1./3);      // [mm]
+
+    const Double_t md = TMath::Sqrt(TMath::Abs(maxdist));
+    fMaxDist = maxdist<0 ? -md : md;                           // [mm]
+
+    SetReadyToSave();
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function is ment for special usage, please never try to set
+// values via this function
+//
+void MHillasExt::Set(const TArrayF &arr)
+{
+    if (arr.GetSize() != 4)
+        return;
+
+    fAsym    = arr.At(0);
+    fM3Long  = arr.At(1);
+    fM3Trans = arr.At(2);
+    fMaxDist = arr.At(3);
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MHillasExt to *fLog.
+//
+void MHillasExt::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Asymmetry            = " << fAsym    << endl;
+    *fLog << " - 3.Moment Long  [mm]  = " << fM3Long  << endl;
+    *fLog << " - 3.Moment Trans [mm]  = " << fM3Trans << endl;
+    *fLog << " - Max.Dist       [mm]  = " << fMaxDist << endl;
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MHillasExt to *fLog, depending on the geometry in
+// units of deg.
+//
+void MHillasExt::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Asymmetry            = " << fAsym   *geom.GetConvMm2Deg() << endl;
+    *fLog << " - 3.Moment Long  [deg] = " << fM3Long *geom.GetConvMm2Deg() << endl;
+    *fLog << " - 3.Moment Trans [deg] = " << fM3Trans*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Max.Dist       [deg] = " << fMaxDist*geom.GetConvMm2Deg() << endl;
+}
Index: /tags/Mars-V0.9/mimage/MHillasExt.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHillasExt.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillasExt.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MHillasExt
+#define MARS_MHillasExt
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TArrayF;
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MHillasExt : public MParContainer
+{
+private:
+    // for description see MExtHillas.cc
+    Float_t fAsym;    // [mm] fDist minus dist: center of ellipse, highest pixel
+    Float_t fM3Long;  // [mm] 3rd moment (e-weighted) along major axis
+    Float_t fM3Trans; // [mm] 3rd moment (e-weighted) along minor axis
+
+    Float_t fMaxDist; // Distance between center and most distant used pixel
+
+public:
+    MHillasExt(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Float_t GetAsym() const    { return fAsym; }
+    Float_t GetM3Long() const  { return fM3Long; }
+    Float_t GetM3Trans() const { return fM3Trans; }
+
+    Float_t GetMaxDist() const { return fMaxDist; }
+
+    Int_t Calc(const MGeomCam &geom, const MSignalCam &pix,
+               const MHillas &hil, Int_t island=-1);
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+
+    void Set(const TArrayF &arr);
+
+    ClassDef(MHillasExt, 3) // Storage Container for extended Hillas Parameter
+};
+#endif
Index: /tags/Mars-V0.9/mimage/MHillasSrc.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHillasSrc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillasSrc.cc	(revision 9772)
@@ -0,0 +1,258 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!   Author(s): Rudolf Bock     10/2001 <mailto:Rudolf.Bock@cern.ch>
+!   Author(s): Wolfgang Wittek 06/2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHillasSrc
+//
+// Storage Container for image parameters
+//
+//    source-dependent image parameters
+//
+//
+// Version 1:
+// ----------
+//  fAlpha          angle between major axis and line source-to-center
+//  fDist           distance from source to center of ellipse
+//
+//
+// Version 2:
+// ----------
+//  fHeadTail       added
+//
+//
+// Version 3:
+// ----------
+//  fCosDeltaAlpha  cosine of angle between d and a, where
+//                   - d is the vector from the source position to the
+//                     center of the ellipse
+//                   - a is a vector along the main axis of the ellipse,
+//                     defined with positive x-component
+//
+//
+// Version 4:
+// ----------
+// fHeadTail        removed
+//
+//
+// Version 5:
+// ----------
+//  - added Float_t fDCA;      // [mm]   Distance to closest approach 'DCA'
+//  - added Float_t fDCADelta; // [deg]  Angle of the shower axis with respect
+//                                       to the x-axis [0,2pi]
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHillasSrc.h"
+
+#include <TArrayF.h>
+
+#include <TLine.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+
+ClassImp(MHillasSrc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillasSrc::MHillasSrc(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHillasSrc";
+    fTitle = title ? title : "Parameters depending in source position";
+}
+
+void MHillasSrc::Reset()
+{
+    fDist          = -1;
+    fAlpha         =  0;
+    fCosDeltaAlpha =  0;
+
+    fDCA           = -1;
+    fDCADelta      =  0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of source-dependent parameters
+//  In case you don't call Calc from within an eventloop make sure, that
+//  you call the Reset member function before.
+//
+Int_t MHillasSrc::Calc(const MHillas &hillas)
+{
+     const Double_t mx = hillas.GetMeanX();     // [mm]
+     const Double_t my = hillas.GetMeanY();     // [mm]
+
+     const Double_t sx = mx - fSrcPos->GetX();   // [mm]
+     const Double_t sy = my - fSrcPos->GetY();   // [mm]
+
+     const Double_t sd = hillas.GetSinDelta();  // [1]
+     const Double_t cd = hillas.GetCosDelta();  // [1]
+
+     //
+     // Distance from source position to center of ellipse.
+     // If the distance is 0 distance, Alpha is not specified.
+     // The calculation has failed and returnes kFALSE.
+     //
+     const Double_t dist = TMath::Sqrt(sx*sx + sy*sy);  // [mm]
+     if (dist==0)
+         return 1;
+
+     //
+     // Calculate Alpha and Cosda = cos(d,a)
+     // The sign of Cosda will be used for quantities containing
+     // a head-tail information
+     //
+     // *OLD* const Double_t arg = (sy-tand*sx) / (dist*sqrt(tand*tand+1));
+     // *OLD* fAlpha = asin(arg)*kRad2Deg;
+     //
+     const Double_t arg2 = cd*sx + sd*sy;          // [mm]
+     if (arg2==0)
+         return 2;
+
+     const Double_t arg1 = cd*sy - sd*sx;          // [mm]
+
+     //
+     // Due to numerical uncertanties in the calculation of the
+     // square root (dist) and arg1 it can happen (in less than 1e-5 cases)
+     // that the absolute value of arg exceeds 1. Because this uncertainty
+     // results in an Delta Alpha which is still less than 1e-3 we don't care
+     // about this uncertainty in general and simply set values which exceed
+     // to 1 saving its sign.
+     //
+     const Double_t arg = arg1/dist;
+     fAlpha = TMath::Abs(arg)>1 ? TMath::Sign(90., arg) : TMath::ASin(arg)*TMath::RadToDeg(); // [deg]
+
+     fCosDeltaAlpha = arg2/dist;                 // [1]
+     fDist          = dist;                      // [mm]
+
+     // ----- Calculation of Distance to closest approach 'DCA' -----
+
+     // Components of DCA vector
+     const Double_t fpd1 = sx - arg2*cd;         // [mm]
+     const Double_t fpd2 = sy - arg2*sd;         // [mm]
+
+     // Determine the correct sign of the DCA (cross product of DCA vector and the
+     // vector going from the intersection point of the DCA vector with the shower axis
+     // to the COG)
+     const Double_t sign = arg2*cd*fpd2 - arg2*sd*fpd1;
+     fDCA  = TMath::Sign(TMath::Sqrt(fpd1*fpd1 + fpd2*fpd2), sign); // [mm]
+
+     // Calculate angle of the shower axis with respect to the x-axis
+     fDCADelta = TMath::ACos((sx-fpd1)/TMath::Abs(arg2))*TMath::RadToDeg(); // [deg]
+
+     // Enlarge the interval of fDdca to [0, 2pi]
+     if (sy < fpd2)
+         fDCADelta = 360 - fDCADelta;
+
+     SetReadyToSave();
+
+     return 0;
+}
+
+void MHillasSrc::Paint(Option_t *opt)
+{
+    const Float_t x = fSrcPos ? fSrcPos->GetX() : 0;
+    const Float_t y = fSrcPos ? fSrcPos->GetY() : 0;
+
+    TMarker m;
+    m.SetMarkerColor(kYellow);
+    m.SetMarkerStyle(kStar);
+    m.PaintMarker(x, y);
+/*
+    m.SetMarkerColor(kMagenta);
+    m.PaintMarker(fDist*cos((fDCADelta-fAlpha)*TMath::DegToRad()),
+                  fDist*sin((fDCADelta-fAlpha)*TMath::DegToRad()));
+
+    TLine line;
+    line.SetLineWidth(1);
+    line.SetLineColor(108);
+
+    line.PaintLine(-radius, y, radius, y);
+    line.PaintLine(x, -radius, x, radius);
+  
+    // COG line
+    TLine line(x, y, meanX, meanY);
+    line.SetLineWidth(1);
+    line.SetLineColor(2);
+    line.Paint();*/
+}
+
+// --------------------------------------------------------------------------
+//
+// Print contents of MHillasSrc to *fLog
+//
+void MHillasSrc::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Dist           [mm]  = " << fDist << endl;
+    *fLog << " - Alpha          [deg] = " << fAlpha << endl;
+    *fLog << " - CosDeltaAlpha        = " << fCosDeltaAlpha << endl;
+    *fLog << " - DCA            [mm]  = " << fDCA << endl;
+    *fLog << " - DCA delta      [deg] = " << fDCADelta << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print contents of MHillasSrc to *fLog depending on the geometry in
+// units of deg.
+//
+void MHillasSrc::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Dist           [deg] = " << fDist*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Alpha          [deg] = " << fAlpha << endl;
+    *fLog << " - CosDeltaAlpha        = " << fCosDeltaAlpha << endl;
+    *fLog << " - DCA            [deg] = " << fDCA*geom.GetConvMm2Deg() << endl;
+    *fLog << " - DCA delta      [deg] = " << fDCADelta << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function is ment for special usage, please never try to set
+// values via this function
+//
+void MHillasSrc::Set(const TArrayF &arr)
+{
+    if (arr.GetSize() != 5)
+        return;
+
+    fAlpha = arr.At(0);         // [deg]  angle of major axis with vector to src
+    fDist  = arr.At(1);         // [mm]   distance between src and center of ellipse
+    fCosDeltaAlpha = arr.At(2); // [1]    cosine of angle between d and a
+    fDCA = arr.At(3);           // [mm]
+    fDCADelta = arr.At(4);      // [mm]
+}
Index: /tags/Mars-V0.9/mimage/MHillasSrc.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHillasSrc.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillasSrc.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MHillasSrc
+#define MARS_MHillasSrc
+
+#ifndef MARS_MHillas
+#include "MHillas.h"
+#endif
+
+class MSrcPosCam;
+
+class MHillasSrc : public MParContainer
+{
+private:
+    const MSrcPosCam *fSrcPos; //! Source position in the camere
+
+    Float_t fAlpha;         // [deg]  angle of major axis with vector to src
+    Float_t fDist;          // [mm]   distance between src and center of ellipse
+    Float_t fCosDeltaAlpha; // [1]    cosine of angle between d and a
+
+    Float_t fDCA;           // [mm]   Distance to closest approach 'DCA'
+    Float_t fDCADelta;      // [deg]  Angle of the shower axis with respect to the x-axis
+
+public:
+    MHillasSrc(const char *name=NULL, const char *title=NULL);
+
+    void SetSrcPos(const MSrcPosCam *pos) { fSrcPos = pos; }
+    const MSrcPosCam *GetSrcPos() const   { return fSrcPos; }
+
+    void Reset();
+
+    Float_t GetAlpha()         const { return fAlpha; }
+    Float_t GetDist()          const { return fDist; }
+    Float_t GetCosDeltaAlpha() const { return fCosDeltaAlpha; }
+    Float_t GetDCA()           const { return fDCA; }
+    Float_t GetDCADelta()      const { return fDCADelta; }
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+    void Paint(Option_t *opt=NULL);
+
+    virtual Int_t Calc(const MHillas &hillas);
+
+    void Set(const TArrayF &arr);
+
+    ClassDef(MHillasSrc, 5) // Container to hold source position dependant parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MHillasSrcCalc.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MHillasSrcCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillasSrcCalc.cc	(revision 9772)
@@ -0,0 +1,183 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Rudolf Bock     10/2001 <mailto:Rudolf.Bock@cern.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MHillasSrcCalc
+//
+// Task to calculate the source dependant part of the hillas parameters
+//
+// THE USE OF THIS TASK IS DEPRICATED. PLEASE USE MHillasCalc INSTEAD!!!
+//
+//
+//  Input Containers:
+//   MHillas
+//   [MSrcPosCam]
+//
+//  Output Containers:
+//   MHillasSrc
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHillasSrcCalc.h"
+
+#include <fstream>
+
+#include "MParList.h"
+
+#include "MSrcPosCam.h"
+#include "MHillasSrc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHillasSrcCalc);
+
+using namespace std;
+
+static const TString gsDefName  = "MHillasSrcCalc";
+static const TString gsDefTitle = "Calculate position dependant image parameters";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. The first argument is the name of a container
+// containing the source position in the camera plain (MScrPosCam).
+// The default is "MSrcPosCam". hil is the name of a container
+// of type MHillasSrc (or derived) in which the parameters are stored
+// The default is "MHillasSrc"
+//
+MHillasSrcCalc::MHillasSrcCalc(const char *src, const char *hil,
+                               const char *name, const char *title)
+    : fHillas(NULL), fSrcPos(NULL), fHillasSrc(NULL)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fSrcName     = src;
+    fHillasName  = hil;
+    fHillasInput = "MHillas";
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MHillasSrcCalc::PreProcess(MParList *pList)
+{
+    fHillas = (MHillas*)pList->FindObject(AddSerialNumber(fHillasInput), "MHillas");
+    if (!fHillas)
+    {
+        *fLog << err << dbginf << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSrcPos = (MSrcPosCam*)pList->FindObject(AddSerialNumber(fSrcName), "MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << warn << AddSerialNumber(fSrcName) << " [MSrcPosCam] not found... creating default container." << endl;
+        fSrcPos = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam", AddSerialNumber(fSrcName));
+        if (!fSrcPos)
+            return kFALSE;
+    }
+
+    fHillasSrc = (MHillasSrc*)pList->FindCreateObj("MHillasSrc", AddSerialNumber(fHillasName));
+    if (!fHillasSrc)
+        return kFALSE;
+
+    fHillasSrc->SetSrcPos(fSrcPos);
+
+    fErrors = 0;
+
+    return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MHillasSrcCalc::Process()
+{
+    if (fHillasSrc->Calc(*fHillas)>0)
+    {
+        fErrors++;
+        return kCONTINUE;
+
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the hillas calculation. The percentage
+//  is calculated with respect to the number of executions of this task.
+//
+Int_t MHillasSrcCalc::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << fErrors << " (" << (int)(fErrors*100/GetNumExecutions()) << "%) Evts skipped due to: Calc>0" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MHillasSrcCalc::StreamPrimitive(ofstream &out) const
+{
+    if (fHillas && !fHillas->IsSavedAsPrimitive())
+        fHillas->StreamPrimitive(out);
+
+    if (fSrcPos && !fSrcPos->IsSavedAsPrimitive())
+        fSrcPos->StreamPrimitive(out);
+
+    if (fHillasSrc && !fHillasSrc->IsSavedAsPrimitive())
+        fHillasSrc->StreamPrimitive(out);
+
+    out << "   MHillasSrcCalc " << GetUniqueName() << "(";
+
+    if (fSrcPos)
+        out << "&" << fSrcPos->GetUniqueName();
+    else
+        out << "\"" << fSrcName << "\"";
+
+    out << ", ";
+
+    if (fHillasSrc)
+        out << "&" << fHillasSrc->GetUniqueName();
+    else
+        out << "\"" << fHillasName << "\"";
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+}
Index: /tags/Mars-V0.9/mimage/MHillasSrcCalc.h
===================================================================
--- /tags/Mars-V0.9/mimage/MHillasSrcCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MHillasSrcCalc.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MHillasSrcCalc
+#define MARS_MHillasSrcCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MHillas;
+class MHillasSrc;
+class MSrcPosCam;
+
+class MHillasSrcCalc : public MTask
+{
+private:
+    const MHillas    *fHillas;     //! Pointer to the source independant hillas parameters
+    const MSrcPosCam *fSrcPos;     //! Pointer to the source position
+          MHillasSrc *fHillasSrc;  //! Pointer to the output container for the source dependant parameters
+
+    TString     fSrcName;
+    TString     fHillasName;
+    TString     fHillasInput;
+
+    Int_t       fErrors;
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MHillasSrcCalc(const char *src="MSrcPosCam", const char *hil="MHillasSrc",
+                   const char *name=NULL, const char *title=NULL);
+
+    void SetInput(TString hilname) { fHillasInput = hilname; }
+
+    ClassDef(MHillasSrcCalc, 1) // task to calculate the source position depandant hillas parameters
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mimage/MImagePar.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MImagePar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MImagePar.cc	(revision 9772)
@@ -0,0 +1,116 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MImagePar
+//
+// Storage Container for new image parameters
+//
+//  Class Version 2:
+//  ----------------
+//    - added Short_t fNumSinglePixels;
+//    - added Float_t fSizeSinglePixels;
+//    - added Float_t fSizeSubIslands;
+//
+//  Class Version 1:
+//  ----------------
+//    Short_t fNumIslands;           // number of islands found
+//
+//    Short_t fNumHGSaturatedPixels; // number of pixels with saturating hi-gains
+//    Short_t fNumSaturatedPixels;   // number of pixels with saturating lo-gains
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImagePar.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MSignalCam.h"
+
+ClassImp(MImagePar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MImagePar::MImagePar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MImagePar";
+    fTitle = title ? title : "New image parameters";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+void MImagePar::Reset()
+{
+    fNumIslands       = -1;
+    fNumSinglePixels  = -1;
+
+    fNumSatPixelsHG   = -1;
+    fNumSatPixelsLG   = -1;
+
+    fSizeSinglePixels = -1;
+    fSizeSubIslands   = -1;
+    fSizeMainIsland   = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of new image parameters
+//
+void MImagePar::Calc(const MSignalCam &evt)
+{
+    // Get number of saturating pixels
+    fNumSatPixelsHG   = evt.GetNumPixelsSaturatedHiGain();
+    fNumSatPixelsLG   = evt.GetNumPixelsSaturatedLoGain();
+
+    // Get number of islands
+    fNumIslands       = evt.GetNumIslands();
+    fNumSinglePixels  = evt.GetNumSinglePixels();
+    fSizeSinglePixels = evt.GetSizeSinglePixels();
+    fSizeSubIslands   = evt.GetSizeSubIslands();
+    fSizeMainIsland   = evt.GetSizeMainIsland();
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+void MImagePar::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Num Islands      [#] = " << fNumIslands       << " Islands" << endl;
+    *fLog << " - Sat.Pixels (HG)  [#] = " << fNumSatPixelsHG   << " Pixels" << endl;
+    *fLog << " - Sat.Pixels (LG)  [#] = " << fNumSatPixelsLG   << " Pixels" << endl;
+    *fLog << " - Num rmvd CorePix [#] = " << fNumSinglePixels  << " Pixels" << endl;
+    *fLog << " - Sz  rmvd CorePix [#] = " << fSizeSinglePixels << " CerPhot" << endl;
+    *fLog << " - Size Sub Islands [#] = " << fSizeSubIslands   << " CerPhot" << endl;
+    *fLog << " - Size Main Island [#] = " << fSizeMainIsland   << " CerPhot" << endl;
+}
Index: /tags/Mars-V0.9/mimage/MImagePar.h
===================================================================
--- /tags/Mars-V0.9/mimage/MImagePar.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MImagePar.h	(revision 9772)
@@ -0,0 +1,46 @@
+#ifndef MARS_MImagePar
+#define MARS_MImagePar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MImagePar : public MParContainer
+{
+private:
+    Short_t fNumIslands;     // Number of islands found
+    Short_t fNumSinglePixels;
+
+    Float_t fSizeSinglePixels;
+    Float_t fSizeSubIslands;
+    Float_t fSizeMainIsland;
+
+    Short_t fNumSatPixelsHG; // number of pixels with saturating hi-gains
+    Short_t fNumSatPixelsLG; // number of pixels with saturating lo-gains
+
+public:
+    MImagePar(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Short_t GetNumIslands() const { return fNumIslands; }
+
+    Short_t GetNumSatPixelsHG() const { return fNumSatPixelsHG; }
+    Short_t GetNumSatPixelsLG() const { return fNumSatPixelsLG; }
+    Short_t GetNumSinglePixels() const { return fNumSinglePixels; }
+    Float_t GetSizeSinglePixels() const { return fSizeSinglePixels; }
+    Float_t GetSizeSubIslands() const { return fSizeSubIslands; }
+    Float_t GetSizeMainIsland() const { return fSizeMainIsland; }
+
+    void Print(Option_t *opt=NULL) const;
+
+    void Calc(const MSignalCam &evt);
+
+    ClassDef(MImagePar, 2) // Container to hold (geometry and island independant) image parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MImgCleanStd.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MImgCleanStd.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MImgCleanStd.cc	(revision 9772)
@@ -0,0 +1,874 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer, 1/2001
+!   Author(s): Nadia Tonello, 4/2003 <mailto:tonello@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MImgCleanStd
+//
+// The Image Cleaning task selects the pixels you use for the Hillas
+// parameters calculation.
+//
+// There are two methods to make the selection: the standard one, as done
+// in the analysis of CT1 data, and the democratic one, as suggested by
+// W.Wittek. The number of photo-electrons of a pixel is compared with the
+// pedestal RMS of the pixel itself (standard method) or with the average
+// RMS of the inner pixels (democratic method).
+// In both cases, the possibility to have a camera with pixels of
+// different area is taken into account.
+// The too noisy pixels can be recognized and eventally switched off
+// (Unmap: set blind pixels to UNUSED) separately, using the
+// MBlindPixelCalc Class. In the MBlindPixelCalc class there is also the
+// function to replace the value of the noisy pixels with the interpolation
+// of the content of the neighbors (SetUseInterpolation).
+//
+// Example:
+// ...
+// MBlindPixelCalc blind;
+// blind.SetUseInterpolation();
+// blind.SetUseBlindPixels();
+//
+// MImgCleanStd clean;
+// ...
+// tlist.AddToList(&blind);
+// tlist.AddToList(&clean);
+//
+// Look at the MBlindPixelCalc Class for more details.
+//
+// Starting point: default values ----------------------------------------
+//
+// When an event is read, before the image cleaning, all the pixels that
+// are in MSignalCam are set as USED and NOT CORE. All the pixels belong
+// to RING number 1 (like USED pixels).
+// Look at MSignalPix.h to see how these informations of the pixel are
+// stored.
+// The default  cleaning METHOD is the STANDARD one and the number of the
+// rings around the CORE pixel it analyzes is 1. Look at the Constructor
+// of the class in MImgCleanStd.cc to see (or change) the default values.
+//
+// Example: To modify this setting, use the member functions
+// SetMethod(MImgCleanStd::kDemocratic) and SetCleanRings(UShort_t n).
+//
+// MImgCleanStd:CleanStep1 -----------------------------------------------
+//
+// The first step of cleaning defines the CORE pixels. The CORE pixels are
+// the ones which contain the informations about the core of the electro-
+// magnetic shower.
+// The ratio  (A_0/A_i) is calculated from fCam->GetPixRatio(i). A_0 is
+// the area of the central pixel of the camera, A_i is the area of the
+// examined pixel. In this way, if we have a MAGIC-like camera, with the
+// outer pixels bigger than the inner ones, the level of cleaning in the
+// two different regions is weighted.
+// This avoids problems of deformations of the shower images.
+// The signal S_i and the pedestal RMS Prms_i of the pixel are called from
+// the object MSignalPix.
+// If (default method = kStandard)
+//Begin_Html
+//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/MImgCleanStd-f1.png">
+//End_Html
+// the pixel is set as CORE pixel. L_1 (n=1) is called "first level of
+// cleaning" (default: fCleanLvl1 = 3).
+// All the other pixels are set as UNUSED and belong to RING 0.
+// After this point, only the CORE pixels are set as USED, with RING
+// number 1.
+//
+// MImgCleanStd:CleanStep2 ----------------------------------------------
+//
+// The second step of cleaning looks at the isolated CORE pixels and sets
+// them to UNUSED. An isolated pixel is a pixel without CORE neighbors.
+// At the end of this point, we have set as USED only CORE pixels with at
+// least one CORE neighbor.
+//
+// MImgCleanStd:CleanStep3  ----------------------------------------------
+//
+// The third step of cleaning looks at all the pixels (USED or UNUSED) that
+// surround the USED pixels.
+// If the content of the analyzed pixel survives at the second level of
+// cleaning, i.e. if
+//Begin_Html
+//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/MImgCleanStd-f1.png">
+//End_Html
+// the pixel is set as USED. L_2 (n=2) is called "second level of cleaning"
+// (default:fCleanLvl2 = 2.5).
+//
+// When the number of RINGS to analyze is 1 (default value), only the
+// pixels that have a neighbor CORE pixel are analyzed.
+//
+// There is the option to decide the number of times you want to repeat
+// this procedure (number of RINGS analyzed around the core pixels = n).
+// Every time the level of cleaning is the same (fCleanLvl2) and the pixel
+// will belong to ring r+1, 1 < r < n+1. This is described in
+// MImgCleanStd:CleanStep4 .
+//
+// Dictionary and member functions ---------------------------------------
+//
+// Here there is the detailed description of the member functions and of
+// the terms commonly used in the class.
+//
+//
+// STANDARD CLEANING:
+// =================
+// This is the method used for the CT1 data analysis. It is the default
+// method of the class.
+// The number of photo-electrons of a pixel (S_i) is compared to the
+// pedestal RMS of the pixel itself (Prms_i). To have the comparison to
+// the same photon density for all the pixels, taking into account they
+// can have different areas, we have to keep in mind that the number of
+// photons that hit each pixel, goes linearly with the area of the pixel.
+// The fluctuations of the LONS are proportional to sqrt(A_i), so when we
+// compare S_i with Prms_i, only a factor  sqrt(A_0/A_i) is missing to
+// have the same (N.photons/Area) threshold for all the pixels.
+//
+//              !!WARNING: if noise independent from the
+//         pixel size (example: electronic noise) is introduced,
+//         then the noise fluctuations are no longer proportional
+//         to sqrt(A_i), and then the cut value (for a camera with
+//         pixels of different sizes) resulting from the above
+//         procedure  would not be proportional to pixel size as we 
+//         intend. In that case, democratic cleaning is preferred.
+//
+// If
+//Begin_Html
+//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/MImgCleanStd-f1.png">
+//End_Html
+// the pixel survives the cleaning and it is set as CORE (when L_n is the
+// first level of cleaning, fCleanLvl1) or USED (when L_n is the second
+// level of cleaning, fCleanLvl2).
+//
+// Example:
+//
+// MImgCleanStd clean;
+// //creates a default Cleaning object, with default setting
+// ...
+// tlist.AddToList(&clean);
+// // add the image cleaning to the main task list
+//
+//
+// DEMOCRATIC CLEANING:
+// ===================
+// You use this cleaning method when you want to compare the number of
+// photo-electons of each pixel with the average pedestal RMS of the
+// inner pixels (for the MAGIC camera they are the smaller ones):
+//Begin_Html
+//&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/MImgCleanStd-f2.png">
+//End_Html
+// In this case, the simple ratio (A_0/A_i) is used to weight the level of
+// cleaning, because both the inner and the outer pixels (that in MAGIC
+// have a different area) are compared to the same pedestal RMS, coming
+// from the inner pixels.
+//
+// Make sure that you used a class calculating the MPedPhotCam which also
+// updated the contents of the mean values (Recalc) correctly.
+//
+//
+// PROBABILITY CLEANING
+// ====================
+// This method takes signal height (over signal noise) and arrival time
+// into account. Instead of comparing signal/Noise with cleaning level
+// one and two, we calculate
+//  - P_ped: The probability that a signal is a pedestal (using
+//           the signal height and the pedestal) For this probability the
+//           same algorithm like in kScaled is used (which is a standard
+//           cleaning which scales the noise with the mean noise of pixels
+//           with the same size)
+//  - P_sig: The probability that the signal corresponds to the pixel
+//           with the highest signal. For this probability we use the
+//           arrival time only.
+//
+// The cleaning now is done in levels of Probability (eg. 0.2, 0.05)
+// The meaning of the cleaning levels is essentially the same (the same cleaning
+// algorithm is used) but the cleaning is not done in levels of signal/noise
+// but in level of this probability.
+//
+// This probability is calculated as (1-P_ped)*P_sig
+//
+// Example:
+//
+// MImgCleanStd clean(0.2, 0.05);
+// clean.SetMethod(MImgCleanStd::kProbability);
+//
+//
+// ABSOLUTE CLEANING
+// =================
+// This method takes signal height (photons) times area ratio
+// ad the cleaning levels.
+//
+// The cleaning now is done in these levels (eg. 16, 20)
+// The meaning of the cleaning levels is essentially the same (the same cleaning
+// algorithm is used) but the cleaning is not done in different 'units'
+//
+// Example:
+//
+// MImgCleanStd clean(20, 16);
+// clean.SetMethod(MImgCleanStd::kAbsolulte);
+//
+//
+// Member Function:  SetMethod()
+// ============================
+// When you call the MImgCleanStd task, the default method is kStandard.
+//
+// If you want to switch to the kDemocratic method you have to
+// call this member function.
+//
+// Example:
+//
+// MImgCleanStd clean;
+// //creates a default Cleaning object, with default setting
+//
+// clean.SetMethod(MImgCleanStd::kDemocratic);
+// //now the method of cleaning is changed to Democratic
+//
+//
+// FIRST AND SECOND CLEANING LEVEL
+// ===============================
+// When you call the MImgCleanStd task, the default cleaning levels are
+// fCleanLvl1 = 3, fCleanLvl2 = 2.5. You can change them easily when you
+// create the MImgCleanStd object.
+//
+// Example:
+//
+// MImgCleanStd clean(Float_t lvl1,Float_t lvl2);
+// //creates a default cleaning object, but the cleaning levels are now
+// //lvl1 and lvl2.
+//
+// RING NUMBER
+// ===========
+// The standard cleaning procedure is such that it looks for the
+// informations of the boundary part of the shower only on the first
+// neighbors of the CORE pixels.
+// There is the possibility now to look not only at the firs neighbors
+// (first ring),but also further away, around the CORE pixels. All the new
+// pixels you can find with this method, are tested with the second level
+// of cleaning and have to have at least an USED neighbor.
+//
+// They will be also set as USED and will be taken into account during the
+// calculation of the image parameters.
+// The only way to distinguish them from the other USED pixels, is the
+// Ring number, that is bigger than 1.
+//
+// Example: You can decide how many rings you want to analyze using:
+//
+// MImgCleanStd clean;
+// //creates a default cleaning object (default number of rings =1)
+// clean.SetCleanRings(UShort_t r);
+// //now it looks r times around the CORE pixels to find new pixels with
+// //signal.
+//
+//
+//  Input Containers:
+//   MGeomCam
+//   MPedPhotCam
+//   MSignalCam
+//
+//  Output Containers:
+//   MSignalCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImgCleanStd.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include <TEnv.h>
+
+#include <TGFrame.h>      // TGFrame
+#include <TGLabel.h>      // TGLabel
+#include <TGTextEntry.h>  // TGTextEntry
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCameraData.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MGGroupFrame.h" // MGGroupFrame
+
+ClassImp(MImgCleanStd);
+
+using namespace std;
+
+enum {
+    kImgCleanLvl1,
+    kImgCleanLvl2
+};
+
+static const TString gsDefName  = "MImgCleanStd";
+static const TString gsDefTitle = "Task to perform image cleaning";
+
+const TString MImgCleanStd::gsNamePedPhotCam="MPedPhotCam"; // default name of the 'MPedPhotCam' container
+const TString MImgCleanStd::gsNameSignalCam ="MSignalCam"; // default name of the 'MSignalCam' container
+const TString MImgCleanStd::gsNameGeomCam   ="MGeomCam";    // default name of the 'MGeomCam' container
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Here you can specify the cleaning method and levels. 
+// If you don't specify them the 'common standard' values 3.0 and 2.5 (sigma
+// above mean) are used.
+// Here you can also specify how many rings around the core pixels you want 
+// to analyze (with the fixed lvl2). The default value for "rings" is 1.
+//
+MImgCleanStd::MImgCleanStd(const Float_t lvl1, const Float_t lvl2,
+                           const char *name, const char *title)
+    : fCleaningMethod(kStandard), fCleanLvl1(lvl1),
+    fCleanLvl2(lvl2), fCleanRings(1), fKeepSinglePixels(kFALSE),
+    fNamePedPhotCam(gsNamePedPhotCam), fNameGeomCam(gsNameGeomCam),
+    fNameSignalCam(gsNameSignalCam)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// The first step of cleaning defines the CORE pixels. All the other pixels
+// are set as UNUSED and belong to RING 0.
+// After this point, only the CORE pixels are set as USED, with RING
+// number 1.
+//
+//  NT 28/04/2003: now the option to use the standard method or the
+//  democratic method is implemented:
+//
+//  kStandard:   This method looks for all pixels with an entry (photons)
+//               that is three times bigger than the noise of the pixel
+//               (default: 3 sigma, clean level 1)
+//
+//  kDemocratic: this method looks for all pixels with an entry (photons)
+//               that is n times bigger than the noise of the mean of the
+//               inner pixels (default: 3 sigmabar, clean level 1)
+//
+//
+void MImgCleanStd::CleanStep1()
+{
+    const TArrayD &data = fData->GetData();
+
+    //
+    // check the number of all pixels against the noise level and
+    // set them to 'unused' state if necessary
+    //
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        if (data[idx]>fCleanLvl1)
+            continue;
+
+        MSignalPix &pix = (*fEvt)[idx];
+        if (!pix.IsPixelUnmapped())
+            pix.SetPixelUnused();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if the survived pixel have a neighbor, that also
+//  survived. Set all single pixels Unused if !fKeepSinglePixels. Now we
+//  declare all pixels that survived previous CleanSteps as CorePixels.
+//  Return number of single pixels, and there cumulative size in size.
+//
+Short_t MImgCleanStd::CleanStep2(Float_t &size)
+{
+    Short_t n=0;
+    size = 0;
+
+    const UInt_t npixevt = fEvt->GetNumPixels();
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+        if (!pix.IsPixelUsed())
+            continue;
+ 
+        // check for 'used' neighbors of this pixel
+        const MGeomPix &gpix  = (*fCam)[idx];
+        const Int_t     nnmax = gpix.GetNumNeighbors();
+
+        Bool_t hasNeighbor = kFALSE;
+
+	//loop on the neighbors to check if they are used
+        for (Int_t j=0; j<nnmax; j++)
+        {
+            const Int_t idx2 = gpix.GetNeighbor(j);
+
+	    // when you find an used neighbor, break the loop
+            if (fEvt->IsPixelUsed(idx2))
+            {
+                hasNeighbor = kTRUE;
+                break;
+            }
+        }
+
+        if (hasNeighbor == kFALSE)
+        {
+            if (!fKeepSinglePixels)
+                pix.SetPixelUnused();
+            size += pix.GetNumPhotons();
+            n++;
+        }
+    }
+
+    for (UInt_t idx=0; idx<npixevt; idx++)
+    {
+        MSignalPix &pix = (*fEvt)[idx];
+	if (pix.IsPixelUsed())
+            pix.SetPixelCore();
+    }
+
+    return n;
+} 
+
+void MImgCleanStd::CleanStep3b(Int_t idx)
+{
+    MSignalPix &pix = (*fEvt)[idx];
+
+    //
+    // check if the pixel's next neighbor is a core pixel.
+    // if it is a core pixel set pixel state to: used.
+    //
+    MGeomPix   &gpix  = (*fCam)[idx];
+    const Int_t nnmax = gpix.GetNumNeighbors();
+
+    for (Int_t j=0; j<nnmax; j++)
+    {
+        const Int_t idx2 = gpix.GetNeighbor(j);
+
+	if (!fEvt->IsPixelCore(idx2))
+            continue;
+
+        pix.SetPixelUsed();
+       	break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//   NT: Add option "rings": default value = 1. 
+//   Look n (n>1) times for the boundary pixels around the used pixels.
+//   If a pixel has more than 2.5 (clean level 2.5) sigma,
+//   it is declared as used.
+//
+//   If a value<2 for fCleanRings is used, no CleanStep4 is done.
+//
+void MImgCleanStd::CleanStep4(UShort_t r, Int_t idx/*MSignalPix &pix*/)
+{
+    MSignalPix &pix = (*fEvt)[idx];
+
+    //
+    // Skip events that have already a defined status;
+    //
+    if (pix.GetRing() != 0)
+        return;
+
+    //
+    // check if the pixel's next neighbor is a used pixel.
+    // if it is a used pixel set pixel state to: used,
+    // and tell to which ring it belongs to.
+    //
+    MGeomPix  &gpix  = (*fCam)[idx];
+
+    const Int_t nnmax = gpix.GetNumNeighbors();
+
+    for (Int_t j=0; j<nnmax; j++)
+    {
+        const Int_t idx2 = gpix.GetNeighbor(j);
+
+        MSignalPix *npix = fEvt->GetPixById(idx2);
+        if (!npix || !npix->IsPixelUsed() || npix->GetRing()>r-1 ) 
+            continue;
+
+        pix.SetRing(r);
+        break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Look for the boundary pixels around the core pixels
+//  if a pixel has more than 2.5 (clean level 2.5) sigma, and
+//  a core neigbor, it is declared as used.
+//
+void MImgCleanStd::CleanStep3()
+{
+    const TArrayD &data = fData->GetData();
+
+    for (UShort_t r=1; r<fCleanRings+1; r++)
+    {
+        // Loop over all pixels
+        const UInt_t npixevt = fEvt->GetNumPixels();
+        for (UInt_t idx=0; idx<npixevt; idx++)
+        {
+            MSignalPix &pix = (*fEvt)[idx];
+
+            //
+	    // if pixel is a core pixel or unmapped, go to the next pixel
+            //
+            if (pix.IsPixelCore() || pix.IsPixelUnmapped())
+                continue;
+
+            if (data[idx] <= fCleanLvl2)
+                continue;
+
+            if (r==1)
+                CleanStep3b(idx);
+            else
+                CleanStep4(r, idx);
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if MEvtHeader exists in the Parameter list already.
+//  if not create one and add them to the list
+//
+Int_t MImgCleanStd::PreProcess (MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber(fNameGeomCam), "MGeomCam");
+    if (!fCam)
+    {
+        *fLog << err << fNameGeomCam << " [MGeomCam] not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MSignalCam*)pList->FindObject(AddSerialNumber(fNameSignalCam), "MSignalCam");
+    if (!fEvt)
+    {
+        *fLog << err << fNameSignalCam << " [MSignalCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed = (MPedPhotCam*)pList->FindObject(AddSerialNumber(fNamePedPhotCam), "MPedPhotCam");
+    if (!fPed)
+    {
+        *fLog << err << fNamePedPhotCam << " [MPedPhotCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fData = (MCameraData*)pList->FindCreateObj(AddSerialNumber("MCameraData"));
+    if (!fData)
+        return kFALSE;
+
+    Print();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cleans the image.
+//
+Int_t MImgCleanStd::Process()
+{
+    switch (fCleaningMethod)
+    {
+    case kStandard:
+        fData->CalcCleaningLevel(*fEvt, *fPed, *fCam);
+        break;
+    case kScaled:
+        fData->CalcCleaningLevel2(*fEvt, *fPed, *fCam);
+        break;
+    case kDemocratic:
+        fData->CalcCleaningLevelDemocratic(*fEvt, *fPed, *fCam);
+        break;
+    case kProbability:
+        fData->CalcCleaningProbability(*fEvt, *fPed, *fCam);
+        break;
+    case kAbsolute:
+        fData->CalcCleaningAbsolute(*fEvt, *fCam);
+        break;
+    default:
+        break;
+    }
+
+#ifdef DEBUG
+    *fLog << all << "CleanStep 1" << endl;
+#endif
+    CleanStep1();
+
+
+#ifdef DEBUG
+    *fLog << all << "CleanStep 2" << endl;
+#endif
+    Float_t size;
+    const Short_t n = CleanStep2(size);
+    fEvt->SetSinglePixels(n, size);
+
+    // For speed reasons skip the rest of the cleaning if no
+    // action will be taken!
+    if (fCleanLvl1>fCleanLvl2)
+    {
+#ifdef DEBUG
+        *fLog << all << "CleanStep 3" << endl;
+#endif
+        CleanStep3();
+    }
+
+#ifdef DEBUG
+    *fLog << all << "Calc Islands" << endl;
+#endif
+    // Takes roughly 10% of the time
+    fEvt->CalcIslands(*fCam);
+
+#ifdef DEBUG
+    *fLog << all << "Done." << endl;
+#endif
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print descriptor and cleaning levels.
+//
+void MImgCleanStd::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << " using ";
+    switch (fCleaningMethod)
+    {
+    case kDemocratic:
+        *fLog << "democratic";
+        break;
+    case kStandard:
+        *fLog << "standard";
+        break;
+    case kScaled:
+        *fLog << "scaled";
+        break;
+    case kProbability:
+        *fLog << "probability";
+        break;
+    case kAbsolute:
+        *fLog << "absolute";
+        break;
+    }
+    *fLog << " cleaning" << endl;
+    *fLog << "initialized with level " << fCleanLvl1 << " and " << fCleanLvl2;
+    *fLog << " (CleanRings=" << fCleanRings << ")" << endl;
+
+    *fLog << "Name of MPedPhotCam container used: ";
+    *fLog << (fPed?((MParContainer*)fPed)->GetName():(const char*)fNamePedPhotCam) << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Create two text entry fields, one for each cleaning level and a
+//  describing text line.
+//
+void MImgCleanStd::CreateGuiElements(MGGroupFrame *f)
+{
+    //
+    // Create a frame for line 3 and 4 to be able
+    // to align entry field and label in one line
+    //
+    TGHorizontalFrame *f1 = new TGHorizontalFrame(f, 0, 0);
+    TGHorizontalFrame *f2 = new TGHorizontalFrame(f, 0, 0);
+    
+    /*
+     * --> use with root >=3.02 <--
+     *
+     
+     TGNumberEntry *fNumEntry1 = new TGNumberEntry(frame, 3.0, 2, M_NENT_LVL1, kNESRealOne, kNEANonNegative);
+     TGNumberEntry *fNumEntry2 = new TGNumberEntry(frame, 2.5, 2, M_NENT_LVL1, kNESRealOne, kNEANonNegative);
+  
+    */
+    TGTextEntry *entry1 = new TGTextEntry(f1, "****", kImgCleanLvl1);
+    TGTextEntry *entry2 = new TGTextEntry(f2, "****", kImgCleanLvl2);
+    
+    // --- doesn't work like expected (until root 3.02?) --- fNumEntry1->SetAlignment(kTextRight);
+    // --- doesn't work like expected (until root 3.02?) --- fNumEntry2->SetAlignment(kTextRight);
+    
+    entry1->SetText("3.0");
+    entry2->SetText("2.5");
+    
+    entry1->Associate(f);
+    entry2->Associate(f);
+    
+    TGLabel *l1 = new TGLabel(f1, "Cleaning Level 1");
+    TGLabel *l2 = new TGLabel(f2, "Cleaning Level 2");
+    
+    l1->SetTextJustify(kTextLeft);
+    l2->SetTextJustify(kTextLeft);
+    
+    //
+    // Align the text of the label centered, left in the row
+    // with a left padding of 10
+    //
+    TGLayoutHints *laylabel = new TGLayoutHints(kLHintsCenterY|kLHintsLeft, 10);
+    TGLayoutHints *layframe = new TGLayoutHints(kLHintsCenterY|kLHintsLeft,  5, 0, 10);
+    
+    //
+    // Add one entry field and the corresponding label to each line
+    //
+    f1->AddFrame(entry1);
+    f2->AddFrame(entry2);
+    
+    f1->AddFrame(l1, laylabel);
+    f2->AddFrame(l2, laylabel);
+    
+    f->AddFrame(f1, layframe);
+    f->AddFrame(f2, layframe);
+    
+    f->AddToList(entry1);
+    f->AddToList(entry2);
+    f->AddToList(l1);
+    f->AddToList(l2);
+    f->AddToList(laylabel);
+    f->AddToList(layframe);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Process the GUI Events comming from the two text entry fields.
+//
+Bool_t MImgCleanStd::ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2)
+{
+    if (msg!=kC_TEXTENTRY || submsg!=kTE_ENTER)
+        return kTRUE;
+
+    TGTextEntry *txt = (TGTextEntry*)FindWidget(param1);
+
+    if (!txt)
+        return kTRUE;
+
+    Float_t lvl = atof(txt->GetText());
+
+    switch (param1)
+    {
+    case kImgCleanLvl1:
+        fCleanLvl1 = lvl;
+        *fLog << "Cleaning level 1 set to " << lvl << endl;
+        return kTRUE;
+
+    case kImgCleanLvl2:
+        fCleanLvl2 = lvl;
+        *fLog << "Cleaning level 2 set to " << lvl << endl;
+        return kTRUE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MImgCleanStd::StreamPrimitive(ofstream &out) const
+{
+    out << "   MImgCleanStd " << GetUniqueName() << "(";
+    out << fCleanLvl1 << ", " << fCleanLvl2;
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+    if (fCleaningMethod!=kStandard)
+    {
+        out << "   " << GetUniqueName() << ".SetMethod(MImgCleanStd::k";
+        switch (fCleaningMethod)
+        {
+        case kScaled:      out << "Scaled";      break;
+        case kDemocratic:  out << "Democratic";  break;
+        case kProbability: out << "Probability"; break;
+        case kAbsolute:    out << "Absolute";    break;
+        default:
+            break;
+        }
+        out << ");" << endl;
+    }
+    if (fCleanRings!=1)
+        out << "   " << GetUniqueName() << ".SetCleanRings(" << fCleanRings << ");" << endl;
+
+    if (gsNamePedPhotCam!=fNamePedPhotCam)
+        out << "   " << GetUniqueName() << ".SetNamePedPhotCam(\"" << fNamePedPhotCam << "\");" << endl;
+    if (gsNameGeomCam!=fNameGeomCam)
+        out << "   " << GetUniqueName() << ".SetNameGeomCam(\"" << fNameGeomCam << "\");" << endl;
+    if (gsNameSignalCam!=fNameSignalCam)
+        out << "   " << GetUniqueName() << ".SetNameSignalCam(\"" << fNameSignalCam << "\");" << endl;
+    if (fKeepSinglePixels)
+        out << "   " << GetUniqueName() << ".SetKeepSinglePixels();" << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MImgCleanStd.CleanLevel1: 3.0
+//   MImgCleanStd.CleanLevel2: 2.5
+//   MImgCleanStd.CleanMethod: Standard, Scaled, Democratic, Probability, Absolute
+//   MImgCleanStd.CleanRings:  1
+//   MImgCleanStd.KeepSinglePixels: yes, no
+//
+Int_t MImgCleanStd::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "CleanRings", print))
+    {
+        rc = kTRUE;
+        SetCleanRings(GetEnvValue(env, prefix, "CleanRings", fCleanRings));
+    }
+    if (IsEnvDefined(env, prefix, "CleanLevel1", print))
+    {
+        rc = kTRUE;
+        fCleanLvl1 = GetEnvValue(env, prefix, "CleanLevel1", fCleanLvl1);
+    }
+    if (IsEnvDefined(env, prefix, "CleanLevel2", print))
+    {
+        rc = kTRUE;
+        fCleanLvl2 = GetEnvValue(env, prefix, "CleanLevel2", fCleanLvl2);
+    }
+    if (IsEnvDefined(env, prefix, "KeepSinglePixels", print))
+    {
+        rc = kTRUE;
+        fKeepSinglePixels = GetEnvValue(env, prefix, "KeepSinglePixels", fKeepSinglePixels);
+    }
+
+    if (IsEnvDefined(env, prefix, "CleanMethod", print))
+    {
+        rc = kTRUE;
+        TString s = GetEnvValue(env, prefix, "CleanMethod", "");
+        s.ToLower();
+        if (s.BeginsWith("standard"))
+            SetMethod(kStandard);
+        if (s.BeginsWith("scaled"))
+            SetMethod(kScaled);
+        if (s.BeginsWith("democratic"))
+            SetMethod(kDemocratic);
+        if (s.BeginsWith("probability"))
+            SetMethod(kProbability);
+        if (s.BeginsWith("absolute"))
+            SetMethod(kAbsolute);
+    }
+
+    return rc;
+}
Index: /tags/Mars-V0.9/mimage/MImgCleanStd.h
===================================================================
--- /tags/Mars-V0.9/mimage/MImgCleanStd.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MImgCleanStd.h	(revision 9772)
@@ -0,0 +1,87 @@
+#ifndef MARS_MImgCleanStd
+#define MARS_MImgCleanStd
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+class MGeomCam;
+class MSigmabar;
+class MSignalCam;
+class MPedPhotCam;
+class MArrivalTime;
+class MCameraData;
+
+class MGGroupFrame;
+
+class MImgCleanStd : public MGTask
+{
+public:
+    typedef enum {
+        kStandard,
+        kScaled,
+        kDemocratic,
+        kProbability,
+        kAbsolute
+    } CleaningMethod_t;
+
+private:
+    static const TString gsNamePedPhotCam; // default name of the 'MPedPhotCam' container
+    static const TString gsNameGeomCam;    // default name of the 'MGeomCam' container
+    static const TString gsNameSignalCam;  // default name of the 'MSignalCam' container
+
+    const MGeomCam     *fCam;  //!
+          MSignalCam  *fEvt;  //!
+          MPedPhotCam  *fPed;  //!
+          MCameraData  *fData; //!
+
+    CleaningMethod_t fCleaningMethod;
+
+    Float_t  fCleanLvl1;
+    Float_t  fCleanLvl2;
+
+    UShort_t fCleanRings;
+    Bool_t   fKeepSinglePixels;
+
+    TString  fNamePedPhotCam; // name of the 'MPedPhotCam' container
+    TString  fNameGeomCam;    // name of the 'MGeomCam' container
+    TString  fNameSignalCam;  // name of the 'MSignalCam' container
+
+    // MImgCleanStd
+    void    CleanStep1();
+    Short_t CleanStep2(Float_t &size);
+    void    CleanStep3();
+    void    CleanStep3b(Int_t idx);
+    void    CleanStep4(UShort_t r, Int_t idx);
+
+    // MGTask, MTask, MParContainer
+    void    CreateGuiElements(MGGroupFrame *f);
+    void    StreamPrimitive(ofstream &out) const;
+    Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MImgCleanStd(const Float_t lvl1=3.0, const Float_t lvl2=2.5,
+                 const char *name=NULL, const char *title=NULL);
+    void Print(Option_t *o="") const;
+
+    Float_t  GetCleanLvl1() const { return fCleanLvl1; }
+    Float_t  GetCleanLvl2() const { return fCleanLvl2; }
+    UShort_t GetCleanRings() const { return fCleanRings;}
+
+    void SetCleanRings(UShort_t r) { if(r==0) r=1; fCleanRings=r; }
+    void SetMethod(CleaningMethod_t m) { fCleaningMethod = m; }
+    void SetKeepSinglePixels(Bool_t b=kTRUE) { fKeepSinglePixels=b; }
+
+    Bool_t ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2);
+
+    void SetNamePedPhotCam(const char *name)  { fNamePedPhotCam = name; }
+    void SetNameSignalCam(const char *name)   { fNameSignalCam = name; }
+    void SetNameGeomCam(const char *name)     { fNameGeomCam = name; }
+
+    ClassDef(MImgCleanStd, 3)    // task doing the image cleaning
+}; 
+
+#endif
Index: /tags/Mars-V0.9/mimage/MImgCleanTGB.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MImgCleanTGB.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MImgCleanTGB.cc	(revision 9772)
@@ -0,0 +1,456 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer, 1/2001
+!   Author(s): Nadia Tonello, 4/2003 <mailto:tonello@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MImgCleanTGB
+//
+//
+//  Input Containers:
+//   MGeomCam, MCerPhotEvt, MSigmabar
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImgCleanTGB.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include <TGFrame.h>      // TGFrame
+#include <TGLabel.h>      // TGLabel
+#include <TArrayC.h>      // TArrayC
+#include <TGTextEntry.h>  // TGTextEntry
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MSigmabar.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+#include "MGGroupFrame.h" // MGGroupFrame
+
+ClassImp(MImgCleanTGB);
+
+using namespace std;
+
+enum {
+    kImgCleanLvl1,
+    kImgCleanLvl2
+};
+
+static const TString gsDefName  = "MImgCleanTGB";
+static const TString gsDefTitle = "Task to perform image cleaning";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Here you can specify the cleaning method and levels. 
+// If you don't specify them the 'common standard' values 3.0 and 2.5 (sigma
+// above mean) are used.
+// Here you can also specify how many rings around the core pixels you want 
+// to analyze (with the fixed lvl2). The default value for "rings" is 1.
+//
+MImgCleanTGB::MImgCleanTGB(const Float_t lvl1, const Float_t lvl2,
+                               const char *name, const char *title)
+    : fSgb(NULL), fCleaningMethod(kStandard), fCleanLvl1(lvl1),
+    fCleanLvl2(lvl2), fCleanRings(1)
+
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    Print();
+}
+
+
+Int_t MImgCleanTGB::CleanStep3b(MCerPhotPix &pix)
+{
+    const Int_t id = pix.GetPixId();
+
+    //
+    // check if the pixel's next neighbor is a core pixel.
+    // if it is a core pixel set pixel state to: used.
+    //
+    MGeomPix   &gpix  = (*fCam)[id];
+    const Int_t nnmax = gpix.GetNumNeighbors();
+
+    Int_t rc = 0;
+
+    for (Int_t j=0; j<nnmax; j++)
+    {
+        const Int_t id2 = gpix.GetNeighbor(j);
+
+	if (fEvt->GetPixById(id2) && fEvt->IsPixelUsed(id2))
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Look for the boundary pixels around the core pixels
+//   if a pixel has more than 2.5 (clean level 2.5) sigma, and
+//   a core neigbor, it is declared as used.
+//
+void MImgCleanTGB::CleanStep3(Int_t num1, Int_t num2)
+{
+    const Int_t entries = fEvt->GetNumPixels();
+
+    Int_t *u = new Int_t[entries];
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        //
+        // get pixel as entry il from list
+        //
+        MCerPhotPix &pix = (*fEvt)[i];
+        u[i] = CleanStep3b(pix);
+    }
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        MCerPhotPix &pix = (*fEvt)[i];
+        if (u[i]<num1)
+            pix.SetPixelUnused();
+        if (u[i]>num2)
+            pix.SetPixelUsed();
+    }
+
+    delete u;
+}
+
+void MImgCleanTGB::CleanStep3(Byte_t *nb, Int_t num1, Int_t num2)
+{
+    const Int_t entries = fEvt->GetNumPixels();
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        MCerPhotPix &pix = (*fEvt)[i];
+
+        const Int_t idx = pix.GetPixId();
+
+        if (nb[idx]<num1 && pix.IsPixelUsed())
+        {
+            const MGeomPix &gpix = (*fCam)[idx];
+            const Int_t nnmax = gpix.GetNumNeighbors();
+            for (Int_t j=0; j<nnmax; j++)
+                nb[gpix.GetNeighbor(j)]--;
+
+            pix.SetPixelUnused();
+        }
+    }
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        MCerPhotPix &pix = (*fEvt)[i];
+
+        const Int_t idx = pix.GetPixId();
+        if (nb[idx]>num2 && !pix.IsPixelUsed())
+        {
+            const MGeomPix &gpix = (*fCam)[idx];
+            const Int_t nnmax = gpix.GetNumNeighbors();
+            for (Int_t j=0; j<nnmax; j++)
+                nb[gpix.GetNeighbor(j)]++;
+
+            pix.SetPixelUsed();
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if MEvtHeader exists in the Parameter list already.
+//  if not create one and add them to the list
+//
+Int_t MImgCleanTGB::PreProcess (MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fCam)
+    {
+        *fLog << dbginf << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+    if (!fEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fCleaningMethod == kDemocratic)
+    {
+        fSgb = (MSigmabar*)pList->FindObject("MSigmabar");
+        if (!fSgb)
+        {
+            *fLog << dbginf << "MSigmabar not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+    else
+    {
+        fPed = (MPedPhotCam*)pList->FindObject("MPedPhotCam");
+        if (!fPed)
+        {
+            *fLog << dbginf << "MPedPhotCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cleans the image.
+//
+Int_t MImgCleanTGB::Process()
+{
+    const Int_t entries = fEvt->GetNumPixels();
+
+    Double_t sum = 0;
+    Double_t sq  = 0;
+    Double_t w   = 0;
+    Double_t w2  = 0;
+    for (Int_t i=0; i<entries; i++)
+    {
+        //
+        // get pixel as entry il from list
+        //
+        MCerPhotPix &pix = (*fEvt)[i];
+
+        const Int_t    idx        = pix.GetPixId();
+        const Double_t entry      = pix.GetNumPhotons();
+        const Double_t factor     = fCam->GetPixRatio(idx);
+        const Double_t factorsqrt = fCam->GetPixRatioSqrt(idx);
+        const Float_t  noise      = (*fPed)[idx].GetRms();
+
+        if (entry * factorsqrt <= fCleanLvl2 * noise)
+        {
+            sum += entry*factor;
+            sq  += entry*entry*factor*factor;
+            w   += factor;
+            w2  += factor*factor;
+        }
+    }
+
+    Double_t mean = sum/w;
+    Double_t sdev = sqrt(sq/w2 - mean*mean);
+
+    TArrayC n(fCam->GetNumPixels());
+    Byte_t *nb = (Byte_t*)n.GetArray();
+    //Byte_t *nb = new Byte_t[1000];
+    //memset(nb, 0, 577);
+
+    for (Int_t i=0; i<entries; i++)
+    {
+        //
+        // get pixel as entry il from list
+        //
+        MCerPhotPix &pix = (*fEvt)[i];
+        const Int_t idx = pix.GetPixId();
+
+        const Double_t entry  = pix.GetNumPhotons();
+        const Double_t factor = fCam->GetPixRatio(idx);
+
+        if (entry*factor > fCleanLvl1*sdev)
+        {
+            pix.SetPixelUsed();
+
+            const MGeomPix &gpix = (*fCam)[idx];
+            const Int_t nnmax = gpix.GetNumNeighbors();
+            for (Int_t j=0; j<nnmax; j++)
+                nb[gpix.GetNeighbor(j)]++;
+        }
+        else
+            pix.SetPixelUnused();
+    }
+
+    CleanStep3(nb, 2, 3);
+    //CleanStep3(nb, 2, 3);
+    //CleanStep3(nb, 2, 3);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print descriptor and cleaning levels.
+//
+void MImgCleanTGB::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << " using ";
+    switch (fCleaningMethod)
+    {
+    case kDemocratic:
+        *fLog << "democratic";
+        break;
+    case kStandard:
+        *fLog << "standard";
+        break;
+    }
+    *fLog << " cleaning initialized with noise level " << fCleanLvl1 << " and " << fCleanLvl2;
+    *fLog << " (CleanRings=" << fCleanRings << ")" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Create two text entry fields, one for each cleaning level and a
+//  describing text line.
+//
+void MImgCleanTGB::CreateGuiElements(MGGroupFrame *f)
+{
+  //
+  // Create a frame for line 3 and 4 to be able
+  // to align entry field and label in one line
+  //
+  TGHorizontalFrame *f1 = new TGHorizontalFrame(f, 0, 0);
+  TGHorizontalFrame *f2 = new TGHorizontalFrame(f, 0, 0);
+  
+  /*
+   * --> use with root >=3.02 <--
+   *
+   
+   TGNumberEntry *fNumEntry1 = new TGNumberEntry(frame, 3.0, 2, M_NENT_LVL1, kNESRealOne, kNEANonNegative);
+   TGNumberEntry *fNumEntry2 = new TGNumberEntry(frame, 2.5, 2, M_NENT_LVL1, kNESRealOne, kNEANonNegative);
+
+  */
+  TGTextEntry *entry1 = new TGTextEntry(f1, "****", kImgCleanLvl1);
+  TGTextEntry *entry2 = new TGTextEntry(f2, "****", kImgCleanLvl2);
+  
+  // --- doesn't work like expected (until root 3.02?) --- fNumEntry1->SetAlignment(kTextRight);
+  // --- doesn't work like expected (until root 3.02?) --- fNumEntry2->SetAlignment(kTextRight);
+  
+  entry1->SetText("3.0");
+  entry2->SetText("2.5");
+  
+  entry1->Associate(f);
+  entry2->Associate(f);
+  
+  TGLabel *l1 = new TGLabel(f1, "Cleaning Level 1");
+  TGLabel *l2 = new TGLabel(f2, "Cleaning Level 2");
+  
+  l1->SetTextJustify(kTextLeft);
+  l2->SetTextJustify(kTextLeft);
+  
+  //
+  // Align the text of the label centered, left in the row
+  // with a left padding of 10
+  //
+  TGLayoutHints *laylabel = new TGLayoutHints(kLHintsCenterY|kLHintsLeft, 10);
+  TGLayoutHints *layframe = new TGLayoutHints(kLHintsCenterY|kLHintsLeft,  5, 0, 10);
+  
+  //
+  // Add one entry field and the corresponding label to each line
+  //
+  f1->AddFrame(entry1);
+  f2->AddFrame(entry2);
+  
+  f1->AddFrame(l1, laylabel);
+  f2->AddFrame(l2, laylabel);
+  
+  f->AddFrame(f1, layframe);
+  f->AddFrame(f2, layframe);
+  
+  f->AddToList(entry1);
+  f->AddToList(entry2);
+  f->AddToList(l1);
+  f->AddToList(l2);
+  f->AddToList(laylabel);
+  f->AddToList(layframe);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Process the GUI Events comming from the two text entry fields.
+//
+Bool_t MImgCleanTGB::ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2)
+{
+    if (msg!=kC_TEXTENTRY || submsg!=kTE_ENTER)
+        return kTRUE;
+
+    TGTextEntry *txt = (TGTextEntry*)FindWidget(param1);
+
+    if (!txt)
+        return kTRUE;
+
+    Float_t lvl = atof(txt->GetText());
+
+    switch (param1)
+    {
+    case kImgCleanLvl1:
+        fCleanLvl1 = lvl;
+        *fLog << "Cleaning level 1 set to " << lvl << " sigma." << endl;
+        return kTRUE;
+
+    case kImgCleanLvl2:
+        fCleanLvl2 = lvl;
+        *fLog << "Cleaning level 2 set to " << lvl << " sigma." << endl;
+        return kTRUE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MImgCleanTGB::StreamPrimitive(ofstream &out) const
+{
+    out << "   MImgCleanTGB " << GetUniqueName() << "(";
+    out << fCleanLvl1 << ", " << fCleanLvl2;
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << endl;
+
+    if (fCleaningMethod!=kDemocratic)
+        return;
+
+    out << "   " << GetUniqueName() << ".SetMethod(MImgCleanTGB::kDemocratic);" << endl;
+
+    if (fCleanRings==1)
+        return;
+
+    out << "   " << GetUniqueName() << ".SetCleanRings(" << fCleanRings << ");" << endl;
+}
Index: /tags/Mars-V0.9/mimage/MImgCleanTGB.h
===================================================================
--- /tags/Mars-V0.9/mimage/MImgCleanTGB.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MImgCleanTGB.h	(revision 9772)
@@ -0,0 +1,66 @@
+#ifndef MARS_MImgCleanTGB
+#define MARS_MImgCleanTGB
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+class MGeomCam;
+class MSigmabar;
+class MCerPhotPix;
+class MCerPhotEvt;
+class MPedPhotCam;
+
+class MGGroupFrame;
+
+class MImgCleanTGB : public MGTask
+{
+public:
+    typedef enum {
+        kStandard,
+        kDemocratic
+    } CleaningMethod_t;
+
+private:
+    const MGeomCam    *fCam;  //!
+          MCerPhotEvt *fEvt;  //!
+          MSigmabar   *fSgb;  //!
+          MPedPhotCam *fPed;  //!
+
+    CleaningMethod_t fCleaningMethod;
+
+    Float_t fCleanLvl1;
+    Float_t fCleanLvl2;
+
+    UShort_t fCleanRings;
+
+    Float_t fInnerNoise;      //!
+
+    void CreateGuiElements(MGGroupFrame *f);
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t CleanStep3b(MCerPhotPix &pix);
+    void  CleanStep3(Int_t num1, Int_t num2);
+    void  CleanStep3(Byte_t *nb, Int_t num1, Int_t num2);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MImgCleanTGB(const Float_t lvl1=3.0, const Float_t lvl2=2.5,
+              const char *name=NULL, const char *title=NULL);
+    void Print(Option_t *o="") const;
+
+    Float_t  GetCleanLvl1() const { return fCleanLvl1; }
+    Float_t  GetCleanLvl2() const { return fCleanLvl2; }
+    UShort_t GetCleanRings() const { return fCleanRings;}
+
+    void SetCleanRings(UShort_t r) { if(r==0) r=1; fCleanRings=r; }
+    void SetMethod(CleaningMethod_t m) { fCleaningMethod = m; }
+
+    Bool_t ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2);
+
+    ClassDef(MImgCleanTGB, 2)    // task doing the image cleaning
+}; 
+
+#endif
Index: /tags/Mars-V0.9/mimage/MNewImagePar.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MNewImagePar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MNewImagePar.cc	(revision 9772)
@@ -0,0 +1,263 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 03/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz            <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MNewImagePar
+//
+// Storage Container for new image parameters
+//
+//    Float_t fLeakage1;             // (photons in most outer ring of pixels) over fSize
+//    Float_t fLeakage2;             // (photons in the 2 outer rings of pixels) over fSize
+//    Float_t fInnerLeakage1;        // (photons in most outer rings of inner pixels) over fInnerSize
+//    Float_t fInnerLeakage2;        // (photons in the 2 outer rings of inner pixels) over fInnerSize
+//    Float_t fInnerSize;            //
+//
+//    Float_t fConc;                 // [ratio] concentration ratio: sum of the two highest pixels / fSize
+//    Float_t fConc1;                // [ratio] concentration ratio: sum of the highest pixel / fSize
+//
+//    Float_t fUsedArea;             // Area of pixels which survived the image cleaning
+//    Float_t fCoreArea;             // Area of core pixels
+//    Short_t fNumUsedPixels;        // Number of pixels which survived the image cleaning
+//    Short_t fNumCorePixels;        // number of core pixels
+//    Short_t fNumHGSaturatedPixels; // number of pixels with saturating hi-gains
+//    Short_t fNumSaturatedPixels;   // number of pixels with saturating lo-gains
+//
+// Version 2:
+// ----------
+//  - added fNumSaturatedPixels
+// 
+// Version 3:
+// ----------
+//  - added fNumHGSaturatedPixels
+//  - added fInnerLeakage1
+//  - added fInnerLeakage2
+//  - added fInnerSize
+//  - added fUsedArea
+//  - added fCoreArea
+//
+// Version 4:
+// ----------
+//  - moved cleaning/island independant parameters to MImagePar:
+//    + removed fNumHGSaturatedPixels
+//    + removed fNumSaturatedPixels
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MNewImagePar.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+ClassImp(MNewImagePar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MNewImagePar::MNewImagePar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MNewImagePar";
+    fTitle = title ? title : "New image parameters";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+void MNewImagePar::Reset()
+{
+    fLeakage1 = -1;
+    fLeakage2 = -1;
+
+    fInnerLeakage1 = -1;
+    fInnerLeakage2 = -1;
+    fInnerSize = -1;
+
+    fConc  = -1;
+    fConc1 = -1;
+
+    fNumUsedPixels = -1;
+    fNumCorePixels = -1;
+
+    fUsedArea = -1;
+    fCoreArea = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of new image parameters
+//
+void MNewImagePar::Calc(const MGeomCam &geom, const MSignalCam &evt,
+                        const MHillas &hillas, Int_t island)
+{
+    fNumUsedPixels = 0;
+    fNumCorePixels = 0;
+
+    fUsedArea = 0;
+    fCoreArea = 0;
+
+    fInnerSize = 0;
+
+    Double_t edgepix1 = 0;
+    Double_t edgepix2 = 0;
+
+    Double_t edgepixin1 = 0;
+    Double_t edgepixin2 = 0;
+
+    Float_t maxpix1 = 0;                                 // [#phot]
+    Float_t maxpix2 = 0;                                 // [#phot]
+
+    /*
+    MSignalPix *pix = 0;
+    TIter Next(evt);
+    while ((pix=(MSignalPix*)Next()))
+    */
+    UInt_t npix = evt.GetNumPixels();
+    for (UInt_t i=0; i<npix; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        // Check for requested islands
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        // Get geometry of pixel
+        //const Int_t pixid = pix->GetPixId();
+        const MGeomPix &gpix = geom[i/*pixid*/];
+
+        // count used and core pixels
+        if (pix.IsPixelCore())
+        {
+            fNumCorePixels++;
+            fCoreArea += gpix.GetA();
+        }
+
+        // count used pixels
+        fNumUsedPixels++;
+        fUsedArea += gpix.GetA();
+
+        Double_t nphot = pix.GetNumPhotons();
+
+        //
+        // count photons in outer rings of camera
+        //
+        if (gpix.IsInOutermostRing())
+           edgepix1 += nphot;
+        if (gpix.IsInOuterRing())
+           edgepix2 += nphot;
+
+        //
+        // Now we are working on absolute values of nphot, which
+        // must take pixel size into account
+        //
+        nphot *= geom.GetPixRatio(i/*pixid*/);
+
+	// count inner pixels: To dependent on MAGIC Camera --> FIXME
+
+        if (i<397){
+            fInnerSize += nphot;
+            if(i>270){
+                edgepixin2 += nphot;
+                if(i>330)
+                    edgepixin1 += nphot;
+            }
+        }
+
+	// Compute Concentration 1-2
+        if (nphot>maxpix1)
+        {
+            maxpix2  = maxpix1;
+            maxpix1  = nphot;                            // [1]
+            continue;                                    // [1]
+        }
+
+        if (nphot>maxpix2)
+            maxpix2 = nphot;                             // [1]
+    }
+    
+    fInnerLeakage1 = edgepixin1 / fInnerSize;
+    fInnerLeakage2 = edgepixin2 / fInnerSize;
+    fLeakage1 = edgepix1 / hillas.GetSize();
+    fLeakage2 = edgepix2 / hillas.GetSize();
+
+    fConc  = (maxpix1+maxpix2)/hillas.GetSize();         // [ratio]
+    fConc1 = maxpix1/hillas.GetSize();                   // [ratio]
+
+    SetReadyToSave();
+} 
+
+// --------------------------------------------------------------------------
+//
+void MNewImagePar::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Leakage1       [1]   = " << fLeakage1             << endl;
+    *fLog << " - Leakage2       [1]   = " << fLeakage2             << endl;
+    *fLog << " - InnerLeakage1  [1]   = " << fInnerLeakage1        << endl;
+    *fLog << " - InnerLeakage2  [1]   = " << fInnerLeakage2        << endl;
+    *fLog << " - InnerSize      [#]   = " << fInnerSize            << " CerPhot" << endl;
+    *fLog << " - Conc           [1]   = " << fConc                 << " (ratio)" << endl;
+    *fLog << " - Conc1          [1]   = " << fConc1                << " (ratio)" << endl;
+    *fLog << " - Used Pixels    [#]   = " << fNumUsedPixels        << " Pixels" << endl;
+    *fLog << " - Core Pixels    [#]   = " << fNumCorePixels        << " Pixels" << endl;
+    *fLog << " - Used Area     [mm^2] = " << fUsedArea             << endl;
+    *fLog << " - Core Area     [mm^2] = " << fCoreArea             << endl;
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MNewImagePar to *fLog, depending on the geometry in
+// units of deg.
+//
+void MNewImagePar::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Leakage1       [1]   = " << fLeakage1             << endl;
+    *fLog << " - Leakage2       [1]   = " << fLeakage2             << endl;
+    *fLog << " - InnerLeakage1  [1]   = " << fInnerLeakage1        << endl;
+    *fLog << " - InnerLeakage2  [1]   = " << fInnerLeakage2        << endl;
+    *fLog << " - InnerSize      [#]   = " << fInnerSize            << " CerPhot" << endl;
+    *fLog << " - Conc           [1]   = " << fConc                 << " (ratio)" << endl;
+    *fLog << " - Conc1          [1]   = " << fConc1                << " (ratio)" << endl;
+    *fLog << " - Used Pixels    [#]   = " << fNumUsedPixels        << " Pixels" << endl;
+    *fLog << " - Core Pixels    [#]   = " << fNumCorePixels        << " Pixels" << endl;
+    *fLog << " - Used Area    [deg^2] = " << fUsedArea*geom.GetConvMm2Deg()*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Core Area    [deg^2] = " << fCoreArea*geom.GetConvMm2Deg()*geom.GetConvMm2Deg() << endl;
+}
Index: /tags/Mars-V0.9/mimage/MNewImagePar.h
===================================================================
--- /tags/Mars-V0.9/mimage/MNewImagePar.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MNewImagePar.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MNewImagePar
+#define MARS_MNewImagePar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MSignalCam;
+
+class MNewImagePar : public MParContainer
+{
+private:
+    // FIXME: MOVE ALL PARAMETRS WHICH DOES'T DEPEND ON THE IMAGE
+    //        CLEANING TO A NEW CLASS!
+    Float_t fLeakage1;             // (photons in most outer ring of pixels) over fSize
+    Float_t fLeakage2;             // (photons in the 2 outer rings of pixels) over fSize
+    Float_t fInnerLeakage1;        // (photons in most outer rings of inner pixels) over fInnerSize
+    Float_t fInnerLeakage2;        // (photons in the 2 outer rings of inner pixels) over fInnerSize
+    Float_t fInnerSize;            //
+
+    Float_t fConc;                 // [ratio] concentration ratio: sum of the two highest pixels / fSize
+    Float_t fConc1;                // [ratio] concentration ratio: sum of the highest pixel / fSize
+
+    Float_t fUsedArea;             // Area of pixels which survived the image cleaning
+    Float_t fCoreArea;             // Area of core pixels
+    Short_t fNumUsedPixels;        // Number of pixels which survived the image cleaning
+    Short_t fNumCorePixels;        // number of core pixels
+
+public:
+    MNewImagePar(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Float_t GetLeakage1() const { return fLeakage1; }
+    Float_t GetLeakage2() const { return fLeakage2; }
+
+    Float_t GetInnerLeakage1() const { return fInnerLeakage1; }
+    Float_t GetInnerLeakage2() const { return fInnerLeakage2; }
+    Float_t GetInnerSize()     const { return fInnerSize; }
+
+    Float_t GetConc() const  { return fConc;  }
+    Float_t GetConc1() const { return fConc1; }
+
+    Short_t GetNumUsedPixels() const { return fNumUsedPixels; }
+    Short_t GetNumCorePixels() const { return fNumCorePixels; }
+
+    Float_t GetUsedArea() const { return fUsedArea; }
+    Float_t GetCoreArea() const { return fCoreArea; }
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+
+    void Calc(const MGeomCam &geom, const MSignalCam &evt,
+              const MHillas &hillas, Int_t island=-1);
+
+    ClassDef(MNewImagePar, 4) // Container to hold new image parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MNewImagePar2.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MNewImagePar2.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MNewImagePar2.cc	(revision 9772)
@@ -0,0 +1,157 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 03/2005, <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MNewImagePar2
+//
+// Storage Container for new image parameters
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MNewImagePar2.h"
+
+#include <TArrayI.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MSignalCam.h"
+#include "MSignalPix.h"
+
+ClassImp(MNewImagePar2);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MNewImagePar2::MNewImagePar2(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MNewImagePar2";
+    fTitle = title ? title : "New image parameters 2";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+void MNewImagePar2::Reset()
+{
+    fBorderLinePixel  = 0;
+    fBorderLineCenter = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of new image parameters
+//
+void MNewImagePar2::Calc(const MGeomCam &geom, const MSignalCam &evt, Int_t island)
+{
+    TArrayI idx(evt.GetNumPixels());
+    idx.Reset(-1);
+    Int_t cnt=0;
+
+    Int_t n = evt.GetNumPixels();
+    for (int i=0; i<n; i++)
+    {
+        const MSignalPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (island>=0 && pix.GetIdxIsland()!=island)
+            continue;
+
+        Int_t used=0;
+
+        const MGeomPix &gpix = geom[i];
+        const Int_t nn = gpix.GetNumNeighbors();
+        for (int j=0; j<nn; j++)
+        {
+            const Int_t k = gpix.GetNeighbor(j);
+            if (evt[k].IsPixelUsed())
+                used++;
+        }
+
+        if (used<nn)
+        {
+            idx[cnt++] = i;
+            evt[i].SetBit(BIT(14));
+        }
+        else
+            evt[i].ResetBit(BIT(14));
+
+        fBorderLinePixel += (nn-used)*gpix.GetL();
+    }
+
+    for (Int_t n=0; idx[n]>=0; n++)
+    {
+        const Int_t l = idx[n];
+
+        const MGeomPix &gpix = geom[l];
+
+        const Int_t nn = gpix.GetNumNeighbors();
+        for (int j=0; j<nn; j++)
+        {
+            const Int_t k = gpix.GetNeighbor(j);
+            if (k<l)
+                continue;
+
+            if (!evt[k].IsPixelUsed())
+                continue;
+
+            if (!evt[k].TestBit(BIT(14)))
+                continue;
+
+            fBorderLineCenter += TMath::Hypot(gpix.GetX()-geom[k].GetX(),
+                                              gpix.GetY()-geom[k].GetY());
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+void MNewImagePar2::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - Border L.Pixel  [mm] = " << fBorderLinePixel  << endl;
+    *fLog << " - Border L.Center [mm] = " << fBorderLineCenter << endl;
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MNewImagePar to *fLog, depending on the geometry in
+// units of deg.
+//
+void MNewImagePar2::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << endl;
+    *fLog << " - BorderL.Pixel  [deg] = " << fBorderLinePixel*geom.GetConvMm2Deg()  << endl;
+    *fLog << " - BorderL.Center [deg] = " << fBorderLineCenter*geom.GetConvMm2Deg() << endl;
+}
Index: /tags/Mars-V0.9/mimage/MNewImagePar2.h
===================================================================
--- /tags/Mars-V0.9/mimage/MNewImagePar2.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MNewImagePar2.h	(revision 9772)
@@ -0,0 +1,33 @@
+#ifndef MARS_MNewImagePar2
+#define MARS_MNewImagePar2
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGeomCam;
+class MSignalCam;
+
+class MNewImagePar2 : public MParContainer
+{
+private:
+    Float_t fBorderLinePixel;   //
+    Float_t fBorderLineCenter;  //
+
+public:
+    MNewImagePar2(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Float_t GetBorderLinePixel() const  { return fBorderLinePixel; }
+    Float_t GetBorderLineCenter() const { return fBorderLineCenter; }
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+
+    void Calc(const MGeomCam &geom, const MSignalCam &evt, Int_t island=-1);
+
+    ClassDef(MNewImagePar2, 1) // Container to hold new image parameters 2
+};
+
+#endif
Index: /tags/Mars-V0.9/mimage/MNewImageParCalc.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MNewImageParCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MNewImageParCalc.cc	(revision 9772)
@@ -0,0 +1,146 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek     03/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MNewImageParCalc
+//
+// Task to calculate the source dependant part of the hillas parameters
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MNewImageParCalc.h"
+
+#include <fstream.h>
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MCerPhotEvt.h"
+#include "MNewImagePar.h"
+#include "MNewImagePar.h"
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MNewImageParCalc);
+
+static const TString gsDefName  = "MNewImageParCalc";
+static const TString gsDefTitle = "Calculate new image parameters";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. The first argument is the name of a container
+// containing the source position in the camera plain (MScrPosCam).
+// The default is "MSrcPosCam". newpar is the name of a container
+// of type MNewImagePar, in which the parameters are stored.
+// The default is "MNewImagePar"
+//
+//
+MNewImageParCalc::MNewImageParCalc(const char *src, const char *newpar,
+                                   const char *name, const char *title)
+    : fHillas(NULL), fSrcPos(NULL), fNewImagePar(NULL)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fSrcName     = src;
+    fNewParName  = newpar;
+    fHillasInput = "MHillas";
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MNewImageParCalc::PreProcess(MParList *pList)
+{
+    fHillas = (MHillas*)pList->FindObject(fHillasInput, "MHillas");
+    if (!fHillas)
+    {
+        *fLog << err << dbginf << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSrcPos = (MSrcPosCam*)pList->FindObject(fSrcName, "MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << dbginf << fSrcName << " [MSrcPosCam] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+    if (!fCerPhotEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << dbginf << "MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewImagePar = (MNewImagePar*)pList->FindCreateObj("MNewImagePar", fNewParName);
+    if (!fNewImagePar)
+        return kFALSE;
+
+    //fErrors = 0;
+
+    return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MNewImageParCalc::Process()
+{
+
+    /*if (!*/fNewImagePar->Calc(*fGeomCam, *fCerPhotEvt, *fHillas);/*)
+    {
+        fErrors++;
+        return kCONTINUE;
+
+    }*/
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the hillas calculation. The percentage
+//  is calculated with respect to the number of executions of this task.
+//
+/*
+Bool_t MNewImageParCalc::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << fErrors << " (" << (int)(fErrors*100/GetNumExecutions()) << "%) Evts skipped due to: calculation failed" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+*/
Index: /tags/Mars-V0.9/mimage/MNewImageParCalc.h
===================================================================
--- /tags/Mars-V0.9/mimage/MNewImageParCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MNewImageParCalc.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MNewImageParCalc
+#define MARS_MNewImageParCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MHillas;
+class MNewImagePar;
+class MSrcPosCam;
+class MGeomCam;
+class MCerPhotEvt;
+
+class MNewImageParCalc : public MTask
+{
+private:
+    MGeomCam    *fGeomCam;
+    MCerPhotEvt *fCerPhotEvt;
+
+    MHillas      *fHillas;       //! Pointer to the source independent hillas parameters
+    MSrcPosCam   *fSrcPos;       //! Pointer to the source position
+    MNewImagePar *fNewImagePar;  //! Pointer to the output container for the new image parameters
+
+    TString fSrcName;
+    TString fNewParName;
+    TString fHillasInput;
+
+    //Int_t       fErrors;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    //Bool_t PostProcess();
+
+public:
+    MNewImageParCalc(const char *src="MSrcPosCam", const char *newpar="MNewImagePar",
+                     const char *name=NULL,        const char *title=NULL);
+
+    void SetInput(TString hilname) { fHillasInput = hilname; }
+
+    ClassDef(MNewImageParCalc, 0) // task to calculate new image parameters
+};
+
+#endif
+
+
+
+
Index: /tags/Mars-V0.9/mimage/MStereoCalc.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MStereoCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MStereoCalc.cc	(revision 9772)
@@ -0,0 +1,162 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 11/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MStereoCalc
+//
+//  This is a task to calculate some shower parameters from the images of
+//  two telescopes in stereo mode. 
+//
+//  Input Containers:
+//   MGeomCam
+//   MHillas
+//   MMcEvt
+//
+//  Output Containers:
+//   MStereoPar
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MStereoCalc.h"
+
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MMcEvt.hxx"
+#include "MStereoPar.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MStereoCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MStereoCalc::MStereoCalc(const char *name, const char *title)
+    : fStereoParName("MStereoPar")
+{
+    fName  = name  ? name  : "MStereoCalc";
+    fTitle = title ? title : "Calculate shower parameters in stereo mode";
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for MMcEvt and MHillas containers.
+// Try to find the Geometry conatiner.
+// Try to find (and maybe create) the container MStereoPar.
+//
+Int_t MStereoCalc::PreProcess(MParList *pList)
+{
+    // necessary
+
+    fmcevt1 = (MMcEvt*)pList->FindObject(AddSerialNumber("MMcEvt",fCT1id));
+    if (!fmcevt1)
+    {
+        *fLog << err << AddSerialNumber("MMcEvt",fCT1id) << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // necessary
+    fmcevt2 = (MMcEvt*)pList->FindObject(AddSerialNumber("MMcEvt",fCT2id));
+    if (!fmcevt2)
+    {
+      *fLog << err << AddSerialNumber("MMcEvt",fCT2id) << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // necessary
+    TString geomname = "MGeomCam;";
+    geomname += fCT1id;
+    fGeomCam1 = (MGeomCam*)pList->FindObject(geomname);
+    if (!fGeomCam1)
+    {
+        *fLog << err << geomname << " (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    // necessary
+    geomname = "MGeomCam;";
+    geomname += fCT2id;
+    fGeomCam2 = (MGeomCam*)pList->FindObject(geomname);
+    if (!fGeomCam2)
+    {
+        *fLog << err << geomname << " (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    // necessary
+    TString hillasname = "MHillas;";
+    hillasname += fCT1id;
+    fHillas1 = (MHillas*)pList->FindObject(hillasname);
+    if (!fHillas1)
+    {
+        *fLog << err << hillasname << " missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    // necessary
+    hillasname = "MHillas;";
+    hillasname += fCT2id;
+    fHillas2 = (MHillas*)pList->FindObject(hillasname);
+    if (!fHillas2)
+    {
+        *fLog << err << hillasname << " missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    fStereoPar = (MStereoPar*)pList->FindCreateObj("MStereoPar");
+    if (!fStereoPar)
+    {
+	*fLog << err << "Could not create MStereoPar... aborting" << endl;
+	return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call the Calc procedure of the MStereoPar object, where the 
+// calculations combining the data from the two telescopes are performed.
+//
+Int_t MStereoCalc::Process()
+{
+    fStereoPar->Calc(*fHillas1, *fmcevt1, *fGeomCam1, fCT1x, fCT1y, *fHillas2, *fmcevt2, *fGeomCam2, fCT2x, fCT2y);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Does nothing at the moment.
+//
+Int_t MStereoCalc::PostProcess()
+{
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mimage/MStereoCalc.h
===================================================================
--- /tags/Mars-V0.9/mimage/MStereoCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MStereoCalc.h	(revision 9772)
@@ -0,0 +1,65 @@
+#ifndef MARS_MStereoCalc
+#define MARS_MStereoCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MStereoCalc                                                             //
+//                                                                         //
+// Task to calculate some shower parameters in stereo mode                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MGeomCam;
+class MHillas;
+class MMcEvt;
+class MStereoPar;
+
+class MStereoCalc : public MTask
+{
+    const MGeomCam    *fGeomCam1;    //! Camera Geometry CT1
+    const MHillas     *fHillas1;     //! input
+    const MMcEvt      *fmcevt1;      //! input
+
+    const MGeomCam    *fGeomCam2;    //! Camera Geometry CT2
+    const MHillas     *fHillas2;     //! input
+    const MMcEvt      *fmcevt2;      //! input
+
+    Int_t fCT1id;   //! 
+    Int_t fCT2id;   //! Identifiers of the two analyzed telescopes.
+
+    Float_t fCT1x;   //!
+    Float_t fCT1y;   //! Position of first telescope
+    Float_t fCT2x;   //!
+    Float_t fCT2y;   //! Position of second telescope
+
+    MStereoPar   *fStereoPar;     //! output container to store result
+    TString       fStereoParName; // name of the 'MStereoPar' container
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+
+public:
+
+    MStereoCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetNameStereoPar(const char *name) { fStereoParName = name; }
+
+    void SetCTids(Int_t i, Int_t j) { fCT1id = i; fCT2id = j; }
+    void SetCT1coor(Float_t x, Float_t y) { fCT1x = x; fCT1y = y; } // in m
+    void SetCT2coor(Float_t x, Float_t y) { fCT2x = x; fCT2y = y; } // in m
+
+    ClassDef(MStereoCalc, 0) // Task to calculate some shower parameters in stereo mode
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mimage/MStereoPar.cc
===================================================================
--- /tags/Mars-V0.9/mimage/MStereoPar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MStereoPar.cc	(revision 9772)
@@ -0,0 +1,309 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! * 
+!
+!
+!   Author(s): Abelardo Moralejo 11/2003 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MStereoPar
+//
+// Storage Container for shower parameters estimated using the information
+// from two telescopes (presently for MC studies)
+//
+// 
+/////////////////////////////////////////////////////////////////////////////
+#include "MStereoPar.h"
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+#include "MMcEvt.hxx"
+#include "MGeomCam.h"
+
+
+ClassImp(MStereoPar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MStereoPar::MStereoPar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MStereoPar";
+    fTitle = title ? title : "Stereo image parameters";
+
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+void MStereoPar::Reset()
+{
+    fCoreX = 0.;
+    fCoreY = 0.;
+    fSourceX = 0.;
+    fSourceY = 0.;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of shower parameters
+//
+void MStereoPar::Calc(const MHillas &hillas1, const MMcEvt &mcevt1, const MGeomCam &mgeom1, const Float_t ct1_x, const Float_t ct1_y, const MHillas &hillas2, const MMcEvt &mcevt2, const MGeomCam &mgeom2, const Float_t ct2_x, const Float_t ct2_y)
+{
+    //
+    // Get the direction corresponding to the c.o.g. of the image on 
+    // the camera
+    //
+
+    Float_t ct1_cosx_a;
+    Float_t ct1_cosy_a;
+    Float_t ct1_cosz_a; // Direction from ct1 to the shower c.o.g.
+
+    Camera2direction(1e3*mgeom1.GetCameraDist(), mcevt1.GetTelescopePhi(), mcevt1.GetTelescopeTheta(), hillas1.GetMeanX(), hillas1.GetMeanY(), &ct1_cosx_a, &ct1_cosy_a, &ct1_cosz_a);
+
+    //
+    // Now we get another (arbitrary) point along the image long axis,
+    // fMeanX + cosdelta, fMeanY + sindelta, and calculate the direction 
+    // to which it corresponds.
+    //
+    
+    Float_t ct1_cosx_b;
+    Float_t ct1_cosy_b;
+    Float_t ct1_cosz_b;
+
+    Camera2direction(1e3*mgeom1.GetCameraDist(), mcevt1.GetTelescopePhi(), mcevt1.GetTelescopeTheta(), hillas1.GetMeanX()+hillas1.GetCosDelta(), hillas1.GetMeanY()+hillas1.GetSinDelta(), &ct1_cosx_b, &ct1_cosy_b, &ct1_cosz_b);
+
+    //
+    // The vectorial product of the latter two vectors is a vector 
+    // perpendicular to the plane which contains the shower axis and 
+    // passes through the telescope center (center of reflector). 
+    // The vectorial product of that vector and (0,0,1) is a vector on
+    // the horizontal plane pointing from the telescope center to the 
+    // shower core position on the z=0 plane (ground).
+    //
+
+    Float_t ct1_coreVersorX = ct1_cosz_a*ct1_cosx_b - ct1_cosx_a*ct1_cosz_b;
+    Float_t ct1_coreVersorY = ct1_cosz_a*ct1_cosy_b - ct1_cosy_a*ct1_cosz_b;
+
+    //
+    // Now we calculate again the versor, now assuming that the source 
+    // direction is paralel to the telescope axis (camera position 0,0)  
+    // This increases the precision of the core determination if the showers
+    // actually come from that direction (like for gammas from a point source)
+
+    Camera2direction(1e3*mgeom1.GetCameraDist(), mcevt1.GetTelescopePhi(), mcevt1.GetTelescopeTheta(), 0., 0., &ct1_cosx_b, &ct1_cosy_b, &ct1_cosz_b);
+
+    Float_t ct1_coreVersorX_best = ct1_cosz_a*ct1_cosx_b - ct1_cosx_a*ct1_cosz_b;
+    Float_t ct1_coreVersorY_best = ct1_cosz_a*ct1_cosy_b - ct1_cosy_a*ct1_cosz_b;
+    
+    //
+    // Now the second telescope
+    //
+
+    Float_t ct2_cosx_a;
+    Float_t ct2_cosy_a;
+    Float_t ct2_cosz_a; // Direction from ct2 to the shower c.o.g.
+
+
+    Camera2direction(1e3*mgeom2.GetCameraDist(), mcevt2.GetTelescopePhi(), mcevt2.GetTelescopeTheta(), hillas2.GetMeanX(), hillas2.GetMeanY(), &ct2_cosx_a, &ct2_cosy_a, &ct2_cosz_a);
+
+    Float_t ct2_cosx_b;
+    Float_t ct2_cosy_b;
+    Float_t ct2_cosz_b;
+
+    Camera2direction(1e3*mgeom2.GetCameraDist(), mcevt2.GetTelescopePhi(), mcevt2.GetTelescopeTheta(), hillas2.GetMeanX()+hillas2.GetCosDelta(), hillas2.GetMeanY()+hillas2.GetSinDelta(), &ct2_cosx_b, &ct2_cosy_b, &ct2_cosz_b);
+
+
+    Float_t ct2_coreVersorX = ct2_cosz_a*ct2_cosx_b - ct2_cosx_a*ct2_cosz_b;
+    Float_t ct2_coreVersorY = ct2_cosz_a*ct2_cosy_b - ct2_cosy_a*ct2_cosz_b;
+
+
+    Camera2direction(1e3*mgeom2.GetCameraDist(), mcevt2.GetTelescopePhi(), mcevt2.GetTelescopeTheta(), 0., 0., &ct2_cosx_b, &ct2_cosy_b, &ct2_cosz_b);
+
+    Float_t ct2_coreVersorX_best = ct2_cosz_a*ct2_cosx_b - ct2_cosx_a*ct2_cosz_b;
+    Float_t ct2_coreVersorY_best = ct2_cosz_a*ct2_cosy_b - ct2_cosy_a*ct2_cosz_b;
+    
+    //
+    // Estimate core position:
+    //
+    Float_t t = ct1_x - ct2_x - ct2_coreVersorX/ct2_coreVersorY*(ct1_y-ct2_y);
+    t /= (ct2_coreVersorX/ct2_coreVersorY*ct1_coreVersorY - ct1_coreVersorX);
+
+    fCoreX = ct1_x + t * ct1_coreVersorX;
+    fCoreY = ct1_y + t * ct1_coreVersorY;
+
+    // fCoreX, fCoreY, fCoreX2, fCoreY2 will have the same units 
+    // as ct1_x, ct1_y, ct2_x, ct2_y
+
+
+    //
+    // Now the estimated core position assuming the source is located in 
+    // the center of the camera:
+    //
+    t = ct1_x - ct2_x - ct2_coreVersorX_best / 
+	ct2_coreVersorY_best*(ct1_y-ct2_y);
+    t /= (ct2_coreVersorX_best/ct2_coreVersorY_best*ct1_coreVersorY_best - 
+	  ct1_coreVersorX_best);
+
+    fCoreX2 = ct1_x + t * ct1_coreVersorX_best;
+    fCoreY2 = ct1_y + t * ct1_coreVersorY_best;
+
+    //
+    // Be careful, the coordinates in MMcEvt.fCoreX,fCoreY are actually 
+    // those of the vector going *from the shower core to the telescope*.
+    // Ours are those of the vector which goes from telescope 1 to the 
+    // core estimated core.
+    //
+
+    /////////////////////////////////////////////////////////////////////
+    //
+    // Now estimate the source location on the camera by intersecting 
+    // major axis of the ellipses. This assumes both telescopes are 
+    // pointing paralel! We introduce the camera scale to account for
+    // the use of telescopes with different focal distances. 
+    //
+
+    Float_t scale1 = mgeom1.GetConvMm2Deg();
+    Float_t scale2 = mgeom2.GetConvMm2Deg();
+
+    t = scale2*hillas2.GetMeanY() - scale1*hillas1.GetMeanY() +
+	(scale1*hillas1.GetMeanX() - scale2*hillas2.GetMeanX()) * 
+	hillas2.GetSinDelta() / hillas2.GetCosDelta();
+
+    t /= (hillas1.GetSinDelta() - 
+	  hillas2.GetSinDelta()/hillas2.GetCosDelta()*hillas1.GetCosDelta());
+
+    fSourceX = scale1*hillas1.GetMeanX() + t * hillas1.GetCosDelta();
+    fSourceY = scale1*hillas1.GetMeanY() + t * hillas1.GetSinDelta();
+
+    //
+    // Squared angular distance from reconstructed source position to 
+    // camera center.
+    //
+    fTheta2 = fSourceX*fSourceX+fSourceY*fSourceY;
+
+    //
+    // Get the direction corresponding to the intersection of axes
+    //
+
+    Float_t source_direction[3];
+
+    Camera2direction(1e3*mgeom1.GetCameraDist(), mcevt1.GetTelescopePhi(), mcevt1.GetTelescopeTheta(), fSourceX/scale1, fSourceY/scale1, &(source_direction[0]), &(source_direction[1]), &(source_direction[2]));
+
+
+    //
+    // Calculate impact parameters
+    //
+
+    Float_t scalar = (fCoreX-ct1_x)*source_direction[0] +
+	(fCoreY-ct1_y)*source_direction[1];
+    fCT1Impact = sqrt( (fCoreX-ct1_x)*(fCoreX-ct1_x) +
+		       (fCoreY-ct1_y)*(fCoreY-ct1_y) -
+		       scalar * scalar );
+
+    scalar = (fCoreX-ct2_x)*source_direction[0] +
+	(fCoreY-ct2_y)*source_direction[1];
+    fCT2Impact = sqrt( (fCoreX-ct2_x)*(fCoreX-ct2_x) +
+		       (fCoreY-ct2_y)*(fCoreY-ct2_y) -
+		       scalar * scalar );
+
+    //
+    // Now calculate i.p. assuming source is point-like and placed in
+    // the center of the camera.
+    //
+    scalar = (fCoreX2-ct1_x)*(-sin(mcevt1.GetTelescopeTheta())*
+			     cos(mcevt1.GetTelescopePhi()))  +
+      (fCoreY2-ct1_y)*(-sin(mcevt1.GetTelescopeTheta())*
+		      sin(mcevt1.GetTelescopePhi()));
+
+    fCT1Impact2 = sqrt( (fCoreX2-ct1_x)*(fCoreX2-ct1_x) +
+		       (fCoreY2-ct1_y)*(fCoreY2-ct1_y) -
+		       scalar * scalar );
+
+    scalar = (fCoreX2-ct2_x)*(-sin(mcevt2.GetTelescopeTheta())*
+			     cos(mcevt2.GetTelescopePhi()))  +
+      (fCoreY2-ct2_y)*(-sin(mcevt2.GetTelescopeTheta())*
+		      sin(mcevt2.GetTelescopePhi()));
+
+    fCT2Impact2 = sqrt( (fCoreX2-ct2_x)*(fCoreX2-ct2_x) +
+		       (fCoreY2-ct2_y)*(fCoreY2-ct2_y) -
+		       scalar * scalar );
+
+ 
+    SetReadyToSave();
+} 
+
+// --------------------------------------------------------------------------
+//
+// Transformation of coordinates, from a point on the camera x, y , to
+// the director cosines of the corresponding direction, in the system of 
+// coordinates in which X-axis is North, Y-axis is west, and Z-axis 
+// points to the zenith. The transformation has been taken from TDAS 01-05,
+// although the final system of coordinates is not the same defined there,
+// but the one defined in Corsika (for convenience). 
+//
+// rc is the distance from the reflector center to the camera. CTphi and 
+// CTtheta indicate the telescope orientation. The angle CTphi is the 
+// azimuth of the vector going along the telescope axis from the camera 
+// towards the reflector, measured from the North direction anticlockwise 
+// ( being West: phi=pi/2, South: phi=pi, East: phi=3pi/2 )
+//
+// rc and x,y must be given in the same units!
+//
+  
+
+void MStereoPar::Camera2direction(Float_t rc, Float_t CTphi, Float_t CTtheta, Float_t x, Float_t y, Float_t* cosx, Float_t* cosy, Float_t* cosz)
+{
+    //
+    // We convert phi to the convention defined in TDAS 01-05
+    //
+    Float_t sinphi = sin(2*TMath::Pi()-CTphi);
+    Float_t cosphi = cos(CTphi);
+    Float_t costheta = cos(CTtheta);
+    Float_t sintheta = sin(CTtheta);
+
+    Float_t xc = x/rc;
+    Float_t yc = y/rc;
+
+    Float_t norm = 1/sqrt(1+xc*xc+yc*yc);
+
+    Float_t xref = xc * norm;
+    Float_t yref = yc * norm;
+    Float_t zref = -1 * norm;
+
+    *cosx =  xref * sinphi + yref * costheta*cosphi - zref * sintheta*cosphi;
+    *cosy = -xref * cosphi + yref * costheta*sinphi - zref * sintheta*sinphi;
+    *cosz =                  yref * sintheta        + zref * costheta; 
+
+    //  Now change from system A of TDAS 01-05 to Corsika system:
+
+    *cosy *= -1;
+    *cosz *= -1; 
+
+}
Index: /tags/Mars-V0.9/mimage/MStereoPar.h
===================================================================
--- /tags/Mars-V0.9/mimage/MStereoPar.h	(revision 9772)
+++ /tags/Mars-V0.9/mimage/MStereoPar.h	(revision 9772)
@@ -0,0 +1,92 @@
+#ifndef MARS_MStereoPar
+#define MARS_MStereoPar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MMcEvt;
+
+class MStereoPar : public MParContainer
+{
+private:
+
+    Float_t fCoreX;
+    Float_t fCoreY;   // Estimated core position on ground
+
+    Float_t fCoreX2;  // Estimated core position on ground assuming 
+    Float_t fCoreY2;  // that the source direction is paralel to the 
+                      // telescope axis.
+
+    Float_t fSourceX; // Estimated source position on the camera
+    Float_t fSourceY; // Units are degrees! 
+
+    Float_t fTheta2;  // deg^2; Squared angular distance of estimated
+                      // source position to cameracenter.
+
+    Float_t fCT1Impact; // Estimated shower impact parameter from CT1
+    Float_t fCT2Impact; // Estimated shower impact parameter from CT2
+
+    Float_t fCT1Impact2; // Estimated shower impact parameter from CT1
+                         // assuming that the source direction is paralel 
+                         // to the telescope axis.
+
+    Float_t fCT2Impact2; // Estimated shower impact parameter from CT2
+                         // assuming that the source direction is paralel 
+                         // to the telescope axis.
+
+
+    void Camera2direction(Float_t rc, Float_t CTphi, Float_t CTtheta, Float_t x, Float_t y, Float_t* cosx, Float_t* cosy, Float_t* cosz);
+
+
+public:
+    MStereoPar(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Float_t GetCoreX() const { return fCoreX; }
+    Float_t GetCoreY() const { return fCoreY; }
+    Float_t GetSourceX() const { return fSourceX; }
+    Float_t GetSourceY() const { return fSourceY; }
+    Float_t GetTheta2() const { return fTheta2; }
+    Float_t GetCT1Impact() const { return fCT1Impact; }
+    Float_t GetCT2Impact() const { return fCT2Impact; }
+    Float_t GetCT1Impact2() const { return fCT1Impact2; }
+    Float_t GetCT2Impact2() const { return fCT2Impact2; }
+
+
+    void Calc(const MHillas &hillas1, const MMcEvt &mcevt1, const MGeomCam &mgeom1, const Float_t ct1_x, const Float_t ct1_y, const MHillas &hillas2, const MMcEvt &mcevt2, const MGeomCam &mgeom2, const Float_t ct2_x, const Float_t ct2_y);
+
+    ClassDef(MStereoPar, 1) // Container to hold new image parameters
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mimage/Makefile
===================================================================
--- /tags/Mars-V0.9/mimage/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mimage/Makefile	(revision 9772)
@@ -0,0 +1,53 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Image
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mgeom -I../msignal \
+	   -I../mgui -I../mmc -I../mpointing -I../mpedestal \
+           -I../mhist -I../manalysis
+
+# mhist: MHHillas (MHCamera)
+
+
+SRCFILES = MImgCleanStd.cc \
+           MCameraSmooth.cc \
+           MHillas.cc \
+           MHillasSrc.cc \
+           MHillasExt.cc \
+           MHillasCalc.cc \
+           MImagePar.cc \
+	   MNewImagePar.cc \
+	   MNewImagePar2.cc \
+	   MConcentration.cc \
+           MHHillas.cc \
+           MHHillasSrc.cc \
+           MHHillasExt.cc \
+           MHImagePar.cc \
+	   MHNewImagePar.cc \
+	   MHNewImagePar2.cc \
+	   MStereoPar.cc \
+	   MStereoCalc.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mjobs/JobsIncl.h
===================================================================
--- /tags/Mars-V0.9/mjobs/JobsIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/JobsIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mjobs/JobsLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mjobs/JobsLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/JobsLinkDef.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MJob+;
+#pragma link C++ class MJCalib+;
+#pragma link C++ class MSequence+;
+#pragma link C++ class MDataSet+;
+
+#pragma link C++ class MJCut+;
+#pragma link C++ class MJStar+;
+#pragma link C++ class MJPedestal+;
+#pragma link C++ class MJOptimize+;
+#pragma link C++ class MJCalibration+;
+#pragma link C++ class MJCalibrateSignal+;
+#pragma link C++ class MJExtractSignal+;
+#pragma link C++ class MJCalibTest+;
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MDataSet.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MDataSet.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MDataSet.cc	(revision 9772)
@@ -0,0 +1,372 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MDataSet
+//
+//  This class describes a collection of sequences.
+//
+//  Such an input file looks like:
+//
+//     crab.seq:
+//     ---------
+//       AnalysisNumber: 1
+//
+//       SequencesOn: 35222
+//       SequencesOff: 36817
+//
+//       Sequence00035222.File: sequences/sequence035222.txt
+//       Sequence00036817.File: sequences/sequence036817.txt
+//
+//       Sequence00035222.Dir: /data2/wuerzburg/Crab-Analyse/images/035222
+//       Sequence00036817.Dir: /data2/wuerzburg/Crab-Analyse/images/036817
+//
+// The analysis number is an artifical number used to name the output
+// files automatically if the names are not overwritten in the corresponding
+// programs.
+//
+// The sequence number are used to concatenate the filenames of the
+// sequences using the file structure used in the datacenter.
+//
+// If you have different file names you can overwrite the default file names
+// using Sequence%08d.File (make sure you have 8 digits!)
+//
+// In standard coditions (datacenter file system) paths are concatenated
+// by using the information in the sequence files (date, etc). You can
+// overwrite the directories in which the sequence-files (eg I-files) are
+// stored using Sequence%08d.Dir (make sure you have 8 digits!)
+//
+// Resource file entries are case sensitive!
+//
+// MISSING (27/01/04): The default name and paths cannot be used yet, because
+//                     they have to be defined soon.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataSet.h"
+
+#include <stdlib.h>
+#include <fstream>
+
+#include <TEnv.h>
+#include <TRegexp.h>
+#include <TSystem.h> // TSystem::ExpandPath
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRead.h"
+#include "MAstro.h"
+#include "MDirIter.h"
+#include "MSequence.h"
+#include "MPointingPos.h"
+
+ClassImp(MDataSet);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Copy the run numbers from the TString runs into the TArrayI data
+//
+void MDataSet::Split(TString &runs, TArrayI &data) const
+{
+    const TRegexp regexp("[0-9]+");
+
+    data.Set(0);
+    runs = runs.Strip(TString::kTrailing);
+
+    while (!runs.IsNull())
+    {
+        TString num = runs(regexp);
+
+        const Int_t n = data.GetSize();
+        data.Set(n+1);
+        data[n] = atoi(num.Data());
+
+        runs.Remove(0, runs.First(num)+num.Length());
+    }
+}
+
+void MDataSet::ResolveSequences(TEnv &env, const TArrayI &num, TList &list) const
+{
+    for (int i=0; i<num.GetSize(); i++)
+    {
+        TString name = env.GetValue(Form("Sequence%08d.File", num[i]), "");
+        TString dir  = env.GetValue(Form("Sequence%08d.Dir",  num[i]), "");
+
+        gSystem->ExpandPathName(name);
+        gSystem->ExpandPathName(dir);
+
+        if (name.IsNull())
+        {
+            // Replace with correct default name
+            name = Form("/data2/wuerzburg/sequences/sequence%08d.txt", num[i]);
+        }
+        /*
+        if (dir.IsNull())
+        {
+            // Replace with default dir
+        }
+        */
+
+        if (gSystem->AccessPathName(name, kFileExists))
+            gLog << warn << "WARNING - Sequence file '" << name << "' doesn't exist." << endl;
+
+        if (gSystem->AccessPathName(dir, kFileExists))
+            gLog << warn << "WARNING - Directory '" << dir << "' doesn't exist." << endl;
+
+        list.Add(new TNamed(name, dir));
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the file fname as setup file for the sequence.
+//
+MDataSet::MDataSet(const char *fname)
+{
+    fName  = fname;
+
+    const char *expname = gSystem->ExpandPathName(fname);
+
+    fTitle = Form("Sequences contained in file %s", expname);
+
+    TEnv env(expname);
+    delete [] expname;
+
+    TString str;
+
+    fNumAnalysis = env.GetValue("AnalysisNumber",  -1);
+
+    str = env.GetValue("SequencesOn", "");
+    Split(str, fNumSequencesOn);
+    str = env.GetValue("SequencesOff", "");
+    Split(str, fNumSequencesOff);
+
+    ResolveSequences(env, fNumSequencesOn,  fSequencesOn);
+    ResolveSequences(env, fNumSequencesOff, fSequencesOff);
+
+
+    fNameSource = env.GetValue("SourceName", "");
+    fCatalog    = env.GetValue("Catalog",    "~/Software/data/magic_favorites.edb");
+
+    //Print();
+    /*
+     GetFileNames(env, fSequencesOn);
+     GetFileNames(env, fSequencesOff);
+     */
+}
+
+// --------------------------------------------------------------------------
+//
+// Return '+' if both can be accessed, '-' otherwise.
+//
+void MDataSet::PrintFile(const TObject &obj)
+{
+    const Bool_t access = !gSystem->AccessPathName(obj.GetName(), kFileExists) && !gSystem->AccessPathName(obj.GetTitle(), kFileExists) ? '+' : '-';
+    gLog << " " << (access?"+":"-") << " " << obj.GetName() << " <" << obj.GetTitle() << ">" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the sequence
+//
+void MDataSet::Print(Option_t *o) const
+{
+    gLog << all;
+    if (!IsValid())
+    {
+        gLog << "Sequence: " << fName << " <invalid>" << endl;
+        return;
+    }
+    gLog << "Analysis Number: " << fNumAnalysis << endl;
+    gLog << "Sequences On:   ";
+    for (int i=0; i<fNumSequencesOn.GetSize(); i++)
+        gLog << " " << fNumSequencesOn[i];
+    gLog << endl;
+    gLog << "Sequences Off:  ";
+    for (int i=0; i<fNumSequencesOff.GetSize(); i++)
+        gLog << " " << fNumSequencesOff[i];
+    gLog << endl;
+
+    gLog << "SourceName: " << fNameSource << endl;
+    gLog << "Catalog:    " << fCatalog << endl;
+
+    if (!TString(o).Contains("files", TString::kIgnoreCase))
+        return;
+
+    TObject *obj=0;
+
+    gLog << endl;
+    gLog << "On-Data Files:" << endl;
+    TIter NextOn(&fSequencesOn);
+    while ((obj=NextOn()))
+        PrintFile(*obj);
+
+    gLog << endl;
+    gLog << "Off-Data Files:" << endl;
+    TIter NextOff(&fSequencesOff);
+    while ((obj=NextOff()))
+        PrintFile(*obj);
+}
+
+Bool_t MDataSet::AddSequencesToList(const TList &list, MRead &read, char *id, Bool_t raw)
+{
+    MDirIter files;
+
+    TIter Next(const_cast<TList*>(&list));
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        MSequence seq(o->GetName());
+        if (!seq.IsValid())
+        {
+            gLog << warn << "WARNING - Sequence " << o->GetName() << " invalid!" << endl;
+            return kFALSE;
+        }
+
+        const TString dir(o->GetTitle());
+        seq.SetupDatRuns(files, dir.IsNull() ? 0 : dir.Data(), id, raw);
+    }
+
+    if (gLog.GetDebugLevel()>4)
+    {
+        gLog << dbg << "Files which are searched:" << endl;
+        files.Print();
+    }
+
+    return read.AddFiles(files)>0;
+}
+
+Bool_t MDataSet::AddFiles(MRead &read, char *id, Bool_t raw) const
+{
+    const Bool_t rc1 = AddFilesOff(read, id, raw);
+    const Bool_t rc2 = AddFilesOn(read, id, raw);
+    return rc1 && rc2;
+}
+
+Bool_t MDataSet::AddFilesOn(MRead &read, char *id, Bool_t raw) const
+{
+    return AddSequencesToList(fSequencesOn, read, id, raw);
+}
+
+Bool_t MDataSet::AddFilesOff(MRead &read, char *id, Bool_t raw) const
+{
+    return AddSequencesToList(fSequencesOff, read, id, raw);
+}
+
+Bool_t MDataSet::GetSourcePos(MPointingPos &pos) const
+{
+    if (!HasSource())
+        return kFALSE;
+
+    TString catalog(fCatalog);
+    gSystem->ExpandPathName(catalog);
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open file " << catalog << ": ";
+        gLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    TString ra,dec,epoch;
+
+    Int_t n = 0;
+    while (1)
+    {
+        TString line;
+        line.ReadLine(fin);
+        if (!fin)
+            break;
+
+        n++;
+        line = line.Strip(TString::kBoth);
+
+        if (!line.BeginsWith(fNameSource))
+            continue;
+
+        // CrabNebula,f|L|K0,5:34:32.0,22:0:52,-1.0,2000
+
+        for (int i=0; i<6; i++)
+        {
+            const Ssiz_t p = line.First(',');
+            if (p<0 && i<5)
+            {
+                gLog << err << "Not enough arguments in line #" << n << endl;
+                return kFALSE;
+            }
+
+            switch (i)
+            {
+            case 0:
+            case 1:
+            case 4:
+                break;
+            case 2:
+                ra = line(0, p);
+                break;
+            case 3:
+                dec = line(0, p);
+                break;
+            case 5:
+                epoch = line;
+                break;
+            }
+            line.Remove(0, p+1);
+        }
+
+        if (line.First(',')>=0)
+        {
+            gLog << err << "Too much arguments in line #" << n << endl;
+            return kFALSE;
+        }
+        break;
+    }
+
+    if (epoch!=(TString)"2000")
+    {
+        gLog << err << "Epoch not 2000... not supported." << endl;
+        return kFALSE;
+    }
+
+    Double_t r,d;
+    if (!MAstro::Coordinate2Angle(ra, r))
+    {
+        gLog << err << "ERROR - Interpreting right ascension: " << ra << endl;
+        return kFALSE;
+    }
+    if (!MAstro::Coordinate2Angle(dec, d))
+    {
+        gLog << err << "ERROR - Interpreting declination: " << dec << endl;
+        return kFALSE;
+    }
+
+    pos.SetSkyPosition(r, d);
+    pos.SetTitle(fNameSource);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mjobs/MDataSet.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MDataSet.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MDataSet.h	(revision 9772)
@@ -0,0 +1,66 @@
+#ifndef MARS_MDataSet
+#define MARS_MDataSet
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MRead;
+class MPointingPos;
+
+class MDataSet : public MParContainer
+{
+private:
+    UInt_t fNumAnalysis;      // Analysis number (artificial)
+
+    TArrayI fNumSequencesOn;  // number of on-sequences
+    TArrayI fNumSequencesOff; // number of off-sequences
+
+    TList fSequencesOn;       // list of names and paths of on-sequences
+    TList fSequencesOff;      // list of names and paths of off-sequences
+
+
+    TString  fNameSource;     // Name of source from catalog
+    TString  fCatalog;        // edb catalog (magic_favourites.edb)
+
+
+    void Split(TString &runs, TArrayI &data) const;
+    void ResolveSequences(TEnv &env, const TArrayI &num, TList &list) const;
+    static void PrintFile(const TObject &obj);
+
+public:
+    MDataSet() : fNumAnalysis((UInt_t)-1) { }
+    MDataSet(const char *fname);
+
+    // Getter
+    Bool_t IsValid() const { return fNumAnalysis!=(UInt_t)-1; }
+
+    UInt_t GetNumSequencesOn() const  { return fNumSequencesOn.GetSize(); }
+    UInt_t GetNumSequencesOff() const { return fNumSequencesOff.GetSize(); }
+
+    Bool_t HasOffSequences() const { return GetNumSequencesOff()>0; }
+
+    UInt_t GetNumAnalysis() const { return fNumAnalysis; }
+    void   SetNumAnalysis(UInt_t num) { fNumAnalysis=num; }
+
+    Bool_t HasSource() const { return !fNameSource.IsNull(); }
+    Bool_t GetSourcePos(MPointingPos &pos) const;
+
+    // Setter
+    static Bool_t AddSequencesToList(const TList &list, MRead &read, char *id="I", Bool_t raw=kFALSE);
+
+    Bool_t AddFiles(MRead &read,    char *id="I", Bool_t raw=kFALSE) const;
+    Bool_t AddFilesOn(MRead &read,  char *id="I", Bool_t raw=kFALSE) const;
+    Bool_t AddFilesOff(MRead &read, char *id="I", Bool_t raw=kFALSE) const;
+
+    // TObject
+    void Print(Option_t *o="") const;
+
+    ClassDef(MDataSet, 0)
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJCalib.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCalib.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCalib.cc	(revision 9772)
@@ -0,0 +1,103 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 2/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalib
+//
+// A base class for the calibration jobs
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalib.h"
+
+ClassImp(MJCalib);
+
+using namespace std;
+
+const Int_t MJCalib::fgCheckedPixId = 100;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fDataFlag      to kIsUseRootData
+// - fRuns          to NULL
+// - fCheckedPixId  to fgCheckedPixId
+// - fPixelCheck    to kFALSE
+// - fPulsePosCheck to kFALSE
+//
+MJCalib::MJCalib() : fDataFlag(kIsUseRootData), fStorage(0), 
+                     fIsPixelCheck(kFALSE), fIsPulsePosCheck(kFALSE),
+                     fIsHiLoCalibration(kFALSE),
+                     fRuns(NULL)
+{
+  SetCheckedPixId();
+}
+
+Bool_t MJCalib::CheckEnvLocal()
+{
+    if (HasEnv("PixelCheck"))
+        SetPixelCheck(GetEnv("PixelCheck", fIsPixelCheck));
+
+    if (HasEnv("PulsePosCheck"))
+        SetPulsePosCheck(GetEnv("PulsePosCheck", fIsPulsePosCheck));
+
+    if (HasEnv("CheckedPixId"))
+        SetCheckedPixId(GetEnv("CheckedPixId",fCheckedPixId));
+
+    if (HasEnv("HiLoCalibration"))    
+      SetHiLoCalibration(GetEnv("HiLoCalibration", fIsHiLoCalibration));
+
+    if (HasEnv("StorageType"))
+      {
+        TString type = GetEnv("StorageType", "");
+        type = type.Strip(TString::kBoth);
+        type.ToLower();
+
+        if (type == (TString)"hists")
+          SetHistsStorage();
+        
+        if (type == (TString)"no" || type == (TString)"nostorage")
+          SetNoStorage();
+      }
+
+    if (!HasEnv("DataType"))
+        return kTRUE;
+
+    TString dat = GetEnv("DataType", "");
+    dat = dat.Strip(TString::kBoth);
+    dat.ToLower();
+
+    if (dat == (TString)"raw")
+        SetUseRawData();
+
+    if (dat == (TString)"mc" || dat == (TString)"montecarlo")
+        SetUseMC();
+
+    if (dat == (TString)"root")
+        SetUseRootData();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mjobs/MJCalib.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCalib.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCalib.h	(revision 9772)
@@ -0,0 +1,78 @@
+#ifndef MARS_MJCalib
+#define MARS_MJCalib
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MRunIter;
+
+class MJCalib : public MJob
+{
+public:
+    enum DataType_t
+    {
+        kIsUseRootData,
+        kIsUseRawData,
+        kIsUseMC
+    };
+
+private:
+
+    static const Int_t fgCheckedPixId;  //! Default for fCheckedPixId
+
+    Byte_t fDataFlag;                   // Bit-field to store the data type
+
+    enum  Storage_t                     // Possible devices for calibration
+      {
+        kNoStorage,
+        kHistsStorage
+      };                                // Possible flags for the storage of results
+    
+    Byte_t fStorage;                    // Bit-field for chosen storage type
+
+protected:
+
+    Bool_t fIsPixelCheck;               // Check a test pixel?
+    Int_t  fCheckedPixId;               // ID of checked pixel
+
+    Bool_t fIsPulsePosCheck;            // Check pulse position?
+    Bool_t fIsHiLoCalibration;          // Choose to calibrate the high-gain vs. low-gains
+    
+    MRunIter *fRuns;                    // Data files, only used for test applications, default is sequence files!
+
+    Bool_t CheckEnvLocal();
+    Byte_t GetDataFlag() { return fDataFlag; }
+
+    Bool_t IsNoStorage    () const { return TESTBIT(fStorage,kNoStorage);    }
+    Bool_t IsHistsStorage () const { return TESTBIT(fStorage,kHistsStorage); }
+    
+public:
+
+    MJCalib();
+
+    void SetInput(MRunIter *iter) { fRuns = iter; }
+
+    Bool_t IsUseRawData()  const { return fDataFlag==kIsUseRawData;  }
+    Bool_t IsUseRootData() const { return fDataFlag==kIsUseRootData; }
+    Bool_t IsUseMC()       const { return fDataFlag==kIsUseMC;       }
+
+    void SetUseRawData () { fDataFlag=kIsUseRawData;  }
+    void SetUseRootData() { fDataFlag=kIsUseRootData; }
+    void SetUseMC      () { fDataFlag=kIsUseMC;       }
+
+    void SetDataType(DataType_t type) { fDataFlag=type; }
+  
+    void SetCheckedPixId ( const Int_t  i=fgCheckedPixId ) { fCheckedPixId  = i; }
+
+    void SetNoStorage    ( const Bool_t b=kTRUE ) { b ? SETBIT(fStorage,kNoStorage)    : CLRBIT(fStorage,kNoStorage); }
+    void SetHistsStorage ( const Bool_t b=kTRUE ) { b ? SETBIT(fStorage,kHistsStorage) : CLRBIT(fStorage,kHistsStorage); }
+
+    void SetHiLoCalibration( const Bool_t b=kTRUE )  { fIsHiLoCalibration = b; }
+    void SetPixelCheck     ( const Bool_t b=kTRUE )  { fIsPixelCheck        = b; }
+    void SetPulsePosCheck  ( const Bool_t b=kTRUE )  { fIsPulsePosCheck     = b; }
+  
+    ClassDef(MJCalib, 0) // Base class for calibration jobs
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJCalibTest.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCalibTest.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCalibTest.cc	(revision 9772)
@@ -0,0 +1,590 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalibTest
+//
+// If the flag SetDataCheckDisplay() is set, only the most important distributions
+//  are displayed. 
+// Otherwise, (default: SetNormalDisplay()), a good selection of plots is given
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalibTest.h"
+
+#include <TFile.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRunIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MTaskEnv.h"
+#include "MEvtLoop.h"
+
+#include "MHCamera.h"
+
+#include "MSignalCam.h"
+#include "MPedestalCam.h"
+#include "MPedPhotCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsTreat.h"
+#include "MBadPixelsCalc.h"
+#include "MBadPixelsMerge.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationTestCam.h"
+#include "MCalibrationTestCalc.h"
+#include "MHCamEvent.h"
+#include "MHCalibrationTestCam.h"
+#include "MHCalibrationTestTimeCam.h"
+#include "MHCalibrationPix.h"
+
+#include "MReadMarsFile.h"
+#include "MRawFileRead.h"
+#include "MGeomApply.h"
+#include "MGeomCam.h"
+#include "MExtractTimeAndChargeSlidingWindow.h"
+#include "MExtractor.h"
+#include "MExtractTime.h"
+#include "MExtractTimeFastSpline.h"
+#include "MFCosmics.h"
+#include "MContinue.h"
+#include "MFillH.h"
+#include "MCalibrateData.h"
+#include "MCalibrateRelTimes.h"
+
+#include "MTriggerPattern.h"
+#include "MTriggerPatternDecode.h"
+#include "MFTriggerPattern.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MJCalibTest);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fUseCosmicsFilter to kTRUE, fRuns to 0, fExtractor to NULL, fTimeExtractor to NULL
+// fDisplay to kNormalDisplay
+//
+MJCalibTest::MJCalibTest(const char *name, const char *title) 
+    : fUseCosmicsFilter(kTRUE), fExtractor(NULL), fTimeExtractor(NULL),
+      fDisplayType(kNormalDisplay), fGeometry("MGeomCamMagic")
+{
+    fName  = name  ? name  : "MJCalibTest";
+    fTitle = title ? title : "Tool to extract, calibrate and test signals from a file";
+}
+
+
+void MJCalibTest::DisplayResult(MParList &plist)
+{
+  if (!fDisplay)
+    return;
+  
+  //
+  // Get container from list
+  //
+  MGeomCam  &geomcam = *(MGeomCam*) plist.FindObject("MGeomCam");
+  MHCalibrationTestCam &testcam = *(MHCalibrationTestCam*)plist.FindObject("MHCalibrationTestCam");
+  
+  // Create histograms to display
+  MHCamera disp1 (geomcam, "Test;PhotoElectrons",    "Mean equiv. phes");
+  MHCamera disp2 (geomcam, "Test;SigmaPhes",         "Sigma equiv.phes");
+  MHCamera disp3 (geomcam, "Test;PhesPerArea",       "Equiv. Phes per Area");
+  MHCamera disp4 (geomcam, "Test;SigmaPhotPerArea",  "Sigma equiv. Phes per Area");
+  MHCamera disp5 (geomcam, "Test;Phot",              "Calibrated Phes from Fit");
+  MHCamera disp6 (geomcam, "Test;PhotPerArea",       "Calibrated Phes per Area from Fit");
+  MHCamera disp7 (geomcam, "Test;NotInterpolate",    "Not interpolated pixels");
+  MHCamera disp8 (geomcam, "Test;DeviatingPhots",    "Deviating Number Phes");
+  MHCamera disp9 (geomcam, "Test;Arr.Times",         "Mean of calibrated Arr.Times");
+  MHCamera disp10(geomcam, "Test;SigmaArr.Times",    "Sigma of calibrated Arr.Times");
+
+  // Fitted charge means and sigmas
+  disp1.SetCamContent(testcam,  0);
+  disp1.SetCamError(  testcam,  1);
+  disp2.SetCamContent(testcam,  2);
+  disp2.SetCamError(  testcam,  3);
+  disp3.SetCamContent(testcam,  7);
+  disp3.SetCamError(  testcam,  8);
+  disp4.SetCamContent(testcam,  9);
+  disp4.SetCamError(  testcam,  10);
+
+  disp5.SetCamContent(fTestCam,  0);
+  disp5.SetCamError(  fTestCam,  1);
+  disp6.SetCamContent(fTestCam,  2);
+  disp6.SetCamError(  fTestCam,  3);
+  disp7.SetCamError(  fTestCam,  4);
+
+  disp8.SetCamError(  fBadPixels, 22);
+
+  disp9.SetCamContent(fTestTimeCam,  0);
+  disp9.SetCamError(  fTestTimeCam,  1);
+  disp10.SetCamContent(fTestTimeCam,  2);
+  disp10.SetCamError(  fTestTimeCam,  3);
+
+
+  disp1.SetYTitle("Phes");
+  disp2.SetYTitle("\\sigma_{phe}");
+  disp3.SetYTitle("Phes per area [mm^{-2}]");
+  disp4.SetYTitle("\\sigma_{phe} per area [mm^{-2}]");
+
+  disp5.SetYTitle("Phes");
+  disp6.SetYTitle("Phes per area [mm^{-2}]");
+  disp7.SetYTitle("[1]");
+  disp8.SetYTitle("[1]");
+  
+  disp9.SetYTitle("Mean Arr.Times [FADC units]");
+  disp10.SetYTitle("\\sigma_{t} [FADC units]");
+  
+  TCanvas &c = fDisplay->AddTab("TestPhes");
+  c.Divide(4,4);
+  
+  disp1.CamDraw(c, 1, 4, 2, 1);
+  disp2.CamDraw(c, 2, 4, 2, 1);        
+  disp3.CamDraw(c, 3, 4, 1, 1);        
+  disp4.CamDraw(c, 4, 4, 2, 1);        
+  
+  /*
+
+  TCanvas &c2 = fDisplay->AddTab("TestResult");
+  c2.Divide(2,4);
+
+  disp5.CamDraw(c2, 1, 2, 2, 1);
+  disp6.CamDraw(c2, 2, 2, 2, 1);        
+
+  */
+
+  TCanvas &c3 = fDisplay->AddTab("TestDefects");
+  c3.Divide(2,2);
+
+  disp7.CamDraw(c3, 1, 2, 0);
+  disp8.CamDraw(c3, 2, 2, 0);        
+
+  //
+  // Display times
+  // 
+  TCanvas &c4 = fDisplay->AddTab("TestTimes");
+  c4.Divide(2,4);
+
+  disp9.CamDraw(c4, 1, 2,  5, 1);
+  disp10.CamDraw(c4, 2, 2,  5, 1);        
+
+  return;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieve the output file written by WriteResult()
+// 
+const char* MJCalibTest::GetOutputFile() const
+{
+    const TString name(GetOutputFileName());
+    if (name.IsNull())
+        return "";
+
+    return Form("%s/%s", fPathOut.Data(), name.Data());
+}
+
+
+const char* MJCalibTest::GetOutputFileName() const
+{
+
+  if (fSequence.IsValid())
+    return Form("calib%08d.root", fSequence.GetSequence());
+  
+  if (!fRuns)
+    return "";
+  
+  return Form("%s-F1.root", (const char*)fRuns->GetRunsAsFileName());
+  
+}
+
+Bool_t MJCalibTest::ReadCalibration(TObjArray &l, MBadPixelsCam &cam, MExtractor* &ext1, MExtractor* &ext2, TString &geom) const
+{
+
+  const TString fname = GetOutputFile();
+  
+  *fLog << inf << "Reading from file: " << fname << endl;
+
+  TFile file(fname, "READ");
+  if (!file.IsOpen())
+    {
+      *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+      return kFALSE;
+    }
+  
+  TObject *o = file.Get("ExtractSignal");
+  if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+      *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
+      return kFALSE;
+    }
+  ext1 = o ? (MExtractor*)o->Clone() : NULL;
+  
+  o = file.Get("ExtractTime");
+  if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+      *fLog << err << dbginf << "ERROR - ExtractTime read from " << fname << " doesn't inherit from MExtractor!" << endl;
+      return kFALSE;
+    }
+  ext2 = o ? (MExtractor*)o->Clone() : NULL;
+  if (!ext1 && !ext2)
+    {
+      *fLog << err << dbginf << "ERROR - Neither ExtractSignal nor ExrtractTime found in " << fname << "!" << endl;
+      return kFALSE;
+    }
+  
+  o = file.Get("MGeomCam");
+  if (o && !o->InheritsFrom(MGeomCam::Class()))
+    {
+      *fLog << err << dbginf << "ERROR - MGeomCam read from " << fname << " doesn't inherit from MGeomCam!" << endl;
+      return kFALSE;
+    }
+  geom = o ? o->ClassName() : "";
+  
+  TObjArray cont(l);
+  cont.Add(&cam);
+  return ReadContainer(cont);
+}
+
+Bool_t MJCalibTest::ProcessFile(MPedestalCam &pedcam)
+{
+  
+  if (!fSequence.IsValid())
+    {
+      if (!fRuns)
+        {
+            *fLog << err << "ERROR - Sequence invalid and no runs chosen!" << endl;
+            return kFALSE;
+	}
+      
+      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 << "Calibrate data from ";
+      *fLog << "Runs " << fRuns->GetRunsAsString() << endl;
+      *fLog << endl;
+    }
+  
+  CheckEnv();
+  
+  *fLog << inf;
+  fLog->Separator(GetDescriptor());
+  
+  *fLog << "Calibrate Calibration data from ";
+  if (fSequence.IsValid())
+    *fLog << "Sequence #" << fSequence.GetSequence() << endl;
+  else
+    *fLog << "Runs " << fRuns->GetRunsAsString() << endl;
+  *fLog << endl;
+  
+  MDirIter iter;
+
+  if (fSequence.IsValid())
+    {
+      const Int_t n0 = fSequence.SetupCalRuns(iter, fPathData, "C", IsUseRawData());
+      const Int_t n1 = fSequence.GetNumCalRuns();
+      if (n0==0)
+        {
+          *fLog << err << "ERROR - No input files of sequence found!" << endl;
+          return kFALSE;
+        }
+      if (n0!=n1)
+        {
+          *fLog << err << "ERROR - Number of files found (" << n0 << ") doesn't match number of files in sequence (" << n1 << ")" << endl;
+            if (fLog->GetDebugLevel()>4)
+            {
+                *fLog << dbg << "Files which are searched:" << endl;
+                iter.Print();
+            }
+          return kFALSE;
+        }
+    }
+  
+  MCalibrationChargeCam      calcam;
+  MCalibrationQECam          qecam;
+  MCalibrationRelTimeCam     tmcam;
+  MBadPixelsCam              badpix;
+  
+  TObjArray calibcont;
+  calibcont.Add(&calcam);
+  calibcont.Add(&qecam);
+  calibcont.Add(&tmcam);
+    
+  MExtractor *extractor1=0;
+  MExtractor *extractor2=0;
+  TString geom;
+
+  if (!ReadCalibration(calibcont, badpix, extractor1, extractor2, geom))
+    {
+      *fLog << err << "Could not read calibration constants " << endl;
+      return kFALSE;
+    }
+  
+  *fLog << all;
+  if (extractor1)
+    {
+      *fLog << underline << "Signal Extractor found in calibration file" << endl;
+      extractor1->Print();
+      *fLog << endl;
+    }
+  else
+    *fLog << inf << "No Signal Extractor: ExtractSignal in file." << endl;
+  
+  if (extractor2)
+    {
+      *fLog << underline << "Time Extractor found in calibration file" << endl;
+      extractor2->Print();
+      *fLog << endl;
+    }
+  else
+    *fLog << inf << "No Time Extractor: ExtractTime in file." << endl;
+  
+  if (!geom.IsNull())
+    *fLog << inf << "Camera geometry found in file: " << geom << endl;
+  else
+    *fLog << inf << "No Camera geometry found using default <MGeomCamMagic>" << endl;
+
+  if (fExtractor)
+    extractor1 = fExtractor;
+  if (fTimeExtractor)
+    extractor2 = fTimeExtractor;
+
+  // Setup Lists
+  MParList plist;
+  plist.AddToList(this); // take care of fDisplay!
+  plist.AddToList(&fTestCam);
+  plist.AddToList(&fTestTimeCam);
+  plist.AddToList(&badpix);
+  plist.AddToList(&pedcam);
+  plist.AddToList(&calcam);
+  plist.AddToList(&qecam);
+  plist.AddToList(&tmcam);
+
+  MSignalCam           cerphot;
+  MPedPhotCam          pedphot;
+  MHCalibrationTestCam testcam;
+
+  plist.AddToList(&cerphot);
+  plist.AddToList(&pedphot);
+  plist.AddToList(&testcam);
+
+  pedcam.SetName("MPedestalFundamental");
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  // Setup Task-lists
+  MRawFileRead rawread(NULL);
+  MReadMarsFile read("Events");
+  read.DisableAutoScheme();
+
+  if (IsUseRawData())
+    rawread.AddFiles(fSequence.IsValid() ? iter : *fRuns);
+  else
+    static_cast<MRead&>(read).AddFiles(fSequence.IsValid() ? iter : *fRuns);
+
+  // Check for interleaved events
+  MTriggerPatternDecode decode;
+  MFTriggerPattern      fcalib;
+  fcalib.DenyCalibration();
+  MContinue conttp(&fcalib, "ContTrigPattern");
+
+  MGeomApply            apply; // Only necessary to craete geometry
+  if (!geom.IsNull())
+    apply.SetGeometry(geom);  
+  MBadPixelsMerge       merge(&badpix);
+
+  MExtractTimeAndChargeSlidingWindow extrsw;
+  MExtractTimeFastSpline             extime;
+  extime.SetPedestals(&pedcam);
+
+  MTaskEnv taskenv1("ExtractSignal");
+  MTaskEnv taskenv2("ExtractTime");
+
+  if (extractor1)
+    { 
+      extractor1->SetPedestals(&pedcam);
+      taskenv1.SetDefault(extractor1);
+    }
+
+  if (extractor2)
+    {
+      fTimeExtractor->SetPedestals(&pedcam);
+      taskenv2.SetDefault(fTimeExtractor);
+    }
+  else if (!(extractor1->InheritsFrom("MExtractTimeAndCharge")))
+    {
+      extrsw.SetPedestals(&pedcam);
+      extrsw.SetWindowSize(8,8);
+      taskenv2.SetDefault(&extrsw);
+      *fLog << warn << GetDescriptor() 
+            << ": No extractor has been chosen, take default MExtractTimeAndChargeSlidingWindow " << endl;
+    }
+
+
+  MCalibrateData        photcalc;
+  photcalc.AddPedestal("Fundamental");
+  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);
+  photcalc.SetPedestalFlag(MCalibrateData::kEvent);
+  photcalc.SetSignalType(MCalibrateData::kPhe);
+
+  MCalibrateRelTimes    caltimes;
+  MBadPixelsCalc        badcalc;
+  MBadPixelsTreat       badtreat;
+  badtreat.SetProcessTimes(kFALSE);
+
+  badcalc.SetNamePedPhotCam("MPedPhotFundamental");
+  badtreat.SetUseInterpolation();
+  badtreat.AddNamePedPhotCam("MPedPhotFundamental");
+
+  MCalibrationTestCalc  testcalc;
+
+  if (!fSequence.IsValid())
+    {
+      testcalc.SetOutputPath(fPathOut);
+      testcalc.SetOutputFile(Form("%s-TestCalibStat.txt",(const char*)fRuns->GetRunsAsFileName()));
+    }
+  
+  MHCamEvent evt0(0,"Signal", "Un-Calibrated Signal;;S [FADC cnts]" );
+  MHCamEvent evt1(0,"CalSig", "Cal. and Interp. Sig. by Pixel Size Ratio;;S [phe]");
+  MHCamEvent evt2(6,"Times" , "Arrival Time;;T [slice]");
+
+  MFillH fill0(&evt0, "MExtractedSignalCam", "FillUncalibrated");
+  MFillH fill1(&evt1, "MSignalCam", "FillCalibrated");
+  MFillH fill2(&evt2, "MSignalCam", "FillTimes");
+  
+  MFillH fillcam("MHCalibrationTestCam",     "MSignalCam" ,"FillTest");
+  MFillH filltme("MHCalibrationTestTimeCam", "MSignalCam", "FillTestTime");
+  fillcam.SetBit(MFillH::kDoNotDisplay);
+  filltme.SetBit(MFillH::kDoNotDisplay);
+
+  MFCosmics cosmics;
+  cosmics.SetNamePedestalCam("MPedestalFundamental");
+  MContinue contcos(&cosmics,"ContCosmics");
+  
+  tlist.AddToList(&read);
+  tlist.AddToList(&decode);
+  tlist.AddToList(&apply);
+  tlist.AddToList(&merge);
+  //  tlist.AddToList(&conttp);
+  tlist.AddToList(&taskenv1);
+  if (!extractor1->InheritsFrom("MExtractTimeAndCharge"))
+    tlist.AddToList(&taskenv2);
+
+  tlist.AddToList(&contcos);
+  tlist.AddToList(&fill0);
+  tlist.AddToList(&photcalc);
+  tlist.AddToList(&caltimes);
+  tlist.AddToList(&badcalc);
+  tlist.AddToList(&badtreat);
+  tlist.AddToList(&fill1);
+  tlist.AddToList(&fill2);
+  tlist.AddToList(&fillcam);
+  tlist.AddToList(&filltme);
+  tlist.AddToList(&testcalc);
+  
+  // 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();
+  
+  if (fIsPixelCheck)
+    {
+      MHCalibrationTestCam *hcam = (MHCalibrationTestCam*)plist.FindObject("MHCalibrationTestCam");
+      MHCalibrationPix &pix1 = (*hcam)[fCheckedPixId];
+      pix1.DrawClone("");
+      
+      MHCalibrationTestTimeCam *hccam = (MHCalibrationTestTimeCam*)plist.FindObject("MHCalibrationTestTimeCam");
+      MHCalibrationPix &pix11 = (*hccam)[fCheckedPixId];
+      pix11.DrawClone("");
+    }
+
+  DisplayResult(plist);
+
+  if (!WriteResult())
+    return kFALSE;
+
+  *fLog << inf << GetDescriptor() << ": Done." << endl;
+  
+  return kTRUE;
+}
+
+Bool_t MJCalibTest::WriteResult()
+{
+    
+    if (fPathOut.IsNull())
+        return kTRUE;
+    
+    const TString oname(GetOutputFile());
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+    
+    TFile file(oname, "UPDATE");
+    
+    if (fDisplay && fDisplay->Write()<=0)
+    {
+        *fLog << err << "Unable to write MStatusDisplay to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fTestCam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MCalibrationTestCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fTestTimeCam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MCalibrationTestCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+
+}
+
Index: /tags/Mars-V0.9/mjobs/MJCalibTest.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCalibTest.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCalibTest.h	(revision 9772)
@@ -0,0 +1,81 @@
+#ifndef MARS_MJCalibTest
+#define MARS_MJCalibTest
+
+#ifndef MARS_MJCalib
+#include "MJCalib.h"
+#endif
+#ifndef MARS_MCalibrationTestCam
+#include "MCalibrationTestCam.h"
+#endif
+#ifndef MARS_MHCalibrationTestTimeCam
+#include "MHCalibrationTestTimeCam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+class MParList;
+class MPedestalCam;
+class MCalibrationRelTimeCam;
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MExtractor;
+class MExtractTime;
+
+class MJCalibTest : public MJCalib
+{
+private:
+
+  Bool_t  fUseCosmicsFilter;
+
+  MExtractor   *fExtractor;                  // Signal extractor
+  MExtractTime *fTimeExtractor;              // Arrival time extractor  
+  
+  MBadPixelsCam            fBadPixels;
+  MCalibrationTestCam      fTestCam;
+  MHCalibrationTestTimeCam fTestTimeCam;
+
+  enum  Display_t                                      // Possible Display types
+    {
+      kDataCheckDisplay,
+      kNormalDisplay
+    };
+  
+  Display_t fDisplayType;                              // Chosen Display type
+
+  TString fGeometry;
+  
+  void   DisplayResult(MParList &plist);
+
+  Bool_t WriteResult();
+  
+  Bool_t ReadCalibration(TObjArray &o, MBadPixelsCam &bpix,
+                         MExtractor* &ext1, MExtractor* &ext2, TString &geom) const;
+
+  const char* GetOutputFileName() const;
+
+public:
+
+  MJCalibTest(const char *name=NULL, const char *title=NULL);
+  
+  const char* GetOutputFile() const;
+  
+  MCalibrationTestCam      &GetTestCam()      { return fTestCam; }
+  MHCalibrationTestTimeCam &GetTestTimeCam()  { return fTestTimeCam; }  
+  const MBadPixelsCam &GetBadPixels()  const { return fBadPixels; }
+  
+  void SetExtractor(MExtractor* ext)              { fExtractor = ext; }
+  void SetTimeExtractor(MExtractTime* ext)         { fTimeExtractor = ext; }
+  void SetBadPixels(const MBadPixelsCam &bad) { bad.Copy(fBadPixels); }
+  void SetUseCosmicsFilter( const Bool_t b )    { fUseCosmicsFilter = b;  }
+
+  // Displays
+  void SetDataCheckDisplay() { fDisplayType = kDataCheckDisplay; }
+  void SetNormalDisplay()    { fDisplayType = kNormalDisplay;    }
+  
+  Bool_t ProcessFile(MPedestalCam &pedcam);
+  
+  ClassDef(MJCalibTest, 0) // Tool to calibrate and test the calibration run itself
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJCalibrateSignal.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCalibrateSignal.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCalibrateSignal.cc	(revision 9772)
@@ -0,0 +1,921 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalibrateSignal
+//
+// This class is reading the output written by callisto. It calibrates
+// signal and time.
+//
+// The signal and time extractors are read from the callisto-output. In
+// pricipal you could overwrite these default using the resource file,
+// but this is NOT recommended!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalibrateSignal.h"
+
+#include <TEnv.h>
+#include <TFile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+#include "MRunIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+
+#include "MGeomCam.h"
+#include "MHCamEvent.h"
+//#include "MHCamEventTH.h"
+#include "MPedestalCam.h"
+#include "MBadPixelsCam.h"
+#include "MArrivalTimeCam.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationHiLoCam.h"
+#include "MCalibrationPulseTimeCam.h"
+#include "MCalibrationPatternDecode.h"
+
+#include "MCalibrationChargeCalc.h"
+#include "MCalibrationRelTimeCalc.h"
+
+#include "MCalibrationIntensityChargeCam.h"
+#include "MCalibrationIntensityBlindCam.h"
+#include "MCalibrationIntensityRelTimeCam.h"
+#include "MCalibrationIntensityQECam.h"
+#include "MBadPixelsIntensityCam.h"
+
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationChargeBlindCam.h"
+#include "MHCalibrationChargePINDiode.h"
+#include "MHCalibrationRelTimeCam.h"
+#include "MHCalibrationPulseTimeCam.h"
+#include "MHCalibrationHiLoCam.h"
+#include "MHCamera.h"
+
+#include "MCalibCalcFromPast.h"
+
+#include "MReadReports.h"
+#include "MReadMarsFile.h"
+#include "MRawFileRead.h"
+#include "MContinue.h"
+#include "MTriggerPatternDecode.h"
+#include "MFTriggerPattern.h"
+#include "MGeomApply.h"
+//#include "MMcPedestalCopy.h"
+#include "MPointingPosCalc.h"
+#include "MPointingPosInterpolate.h"
+#include "MPedCalcFromLoGain.h"
+#include "MExtractor.h"
+#include "MExtractTimeAndCharge.h"
+#include "MExtractPINDiode.h"
+#include "MExtractBlindPixel.h"
+#include "MFCosmics.h"
+#include "MTaskEnv.h"
+#include "MCalibrateData.h"
+#include "MCalibrateRelTimes.h"
+#include "MBadPixelsMerge.h"
+#include "MBadPixelsCalc.h"
+#include "MBadPixelsTreat.h"
+#include "MFillH.h"
+#include "MWriteRootFile.h"
+
+ClassImp(MJCalibrateSignal);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fIsInterlaced to kTRUE
+// - fIsRelTimesUpdate to kFALSE
+// - fIsHiLoCalibration to kFALSE
+// - fPulsePosCheck to kTRUE
+//
+MJCalibrateSignal::MJCalibrateSignal(const char *name, const char *title)
+    : fExtractor(0), fIsInterlaced(kTRUE), fIsRelTimesUpdate(kFALSE)
+{
+    fName  = name  ? name  : "MJCalibrateSignal";
+    fTitle = title ? title : "Tool to calibrate data";
+
+    SetPulsePosCheck();
+    //fCruns = NULL;
+}
+
+MJCalibrateSignal::~MJCalibrateSignal()
+{
+    if (fExtractor)
+        delete fExtractor;
+}
+
+void MJCalibrateSignal::SetExtractor(const MExtractor *ext)
+{
+    if (fExtractor)
+        delete fExtractor;
+
+    fExtractor = ext ? (MExtractor*)ext->Clone() : NULL;
+}
+
+const char* MJCalibrateSignal::GetInputFile() const
+{
+    const TString name(GetInputFileName());
+    if (name.IsNull())
+        return "";
+
+    return Form("%s/%s", fPathIn.Data(), name.Data());
+}
+
+const char* MJCalibrateSignal::GetInputFileName() const
+{
+
+  if (fSequence.IsValid())
+    return Form("calib%08d.root", fSequence.GetSequence());
+  
+  //  if (!fCruns)
+    return "";
+  
+  //  return Form("%s-F1.root", (const char*)fCruns->GetRunsAsFileName());
+}
+
+Bool_t MJCalibrateSignal::WriteResult(TObjArray &cont)
+{
+  if (IsNoStorage())
+    return kTRUE;
+
+  const TString name(Form("signal%08d.root", fSequence.GetSequence()));
+  return WriteContainer(cont, name);
+}
+
+Bool_t MJCalibrateSignal::ReadCalibration(TObjArray &l, MBadPixelsCam &cam, MExtractor* &ext1, MExtractor* &ext2, TString &geom) const
+{
+
+    const TString fname = GetInputFile();
+
+    *fLog << inf << "Reading from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+        return kFALSE;
+    }
+
+    if (!ext1)
+    {
+        TObject *o = file.Get("ExtractSignal");
+        if (o && !o->InheritsFrom(MExtractor::Class()))
+        {
+            *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
+            return kFALSE;
+        }
+        ext1 = o ? (MExtractor*)o->Clone() : NULL;
+    }
+
+    TObject *o = file.Get("ExtractTime");
+    if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - ExtractTime read from " << fname << " doesn't inherit from MExtractor!" << endl;
+        return kFALSE;
+    }
+    ext2 = o ? (MExtractor*)o->Clone() : NULL;
+    if (!ext1 && !ext2)
+    {
+        *fLog << err << dbginf << "ERROR - Neither ExtractSignal nor ExrtractTime found in " << fname << "!" << endl;
+        return kFALSE;
+    }
+
+    o = file.Get("MGeomCam");
+    if (o && !o->InheritsFrom(MGeomCam::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - MGeomCam read from " << fname << " doesn't inherit from MGeomCam!" << endl;
+        return kFALSE;
+    }
+    geom = o ? o->ClassName() : "";
+
+    TObjArray cont(l);
+    cont.Add(&cam);
+    return ReadContainer(cont);
+}
+/*
+Bool_t MJCalibrateSignal::ReadExtractorCosmics(MExtractor* &ext1) const
+{
+
+  const TString fname = Form("pedy%08d.root",fSequence.GetSequence());
+
+  *fLog << inf << "Reading from file: " << fname << endl;
+
+  TFile file(fname, "READ");
+  if (!file.IsOpen())
+    {
+      *fLog << warn << "Could not find or open file " << fname << endl;
+      return kFALSE;
+    }
+
+  TObject *o = file.Get("ExtractSignal");
+  if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+      *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
+      return kFALSE;
+    }
+  if (o)
+    {
+      delete ext1;
+      ext1 = (MExtractor*)o->Clone();
+    }
+  else
+    *fLog << warn << "No signal extractor found in " << fname << endl;
+
+  file.Close();
+  return kTRUE;
+}
+*/
+// --------------------------------------------------------------------------
+//
+// MJCalibration allows to setup several option by a resource file:
+//   MJCalibrateSignal.RawData: yes,no
+//
+// For more details see the class description and the corresponding Getters
+//
+Bool_t MJCalibrateSignal::CheckEnvLocal()
+{
+    SetInterlaced(GetEnv("Interlaced", fIsInterlaced));
+    SetRelTimesUpdate(GetEnv("RelTimesUpdate", fIsRelTimesUpdate));
+
+    return MJCalib::CheckEnvLocal();
+}
+
+Bool_t MJCalibrateSignal::ProcessFile(MPedestalCam &pedcamab, MPedestalCam &pedcambias, 
+				      MPedestalCam &pedcamextr)
+{
+    if (!fSequence.IsValid())
+    {
+        if (!fRuns)
+        {
+	  *fLog << err << "ERROR - Sequence invalid and no runs chosen!" << endl;
+	  return kFALSE;
+	}
+
+        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 << "Calibrate data from ";
+	*fLog << "Runs " << fRuns->GetRunsAsString() << endl;
+	*fLog << endl;
+    }
+
+    //if (!CheckEnv())
+    //    return kFALSE;
+
+    CheckEnv();
+
+    // --------------------------------------------------------------------------------
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate calibrated data from runs ";
+    *fLog << fSequence.GetName() << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+
+    MDirIter iter;
+    if (fSequence.IsValid())
+      {
+        const Int_t n0 = fSequence.SetupDatRuns(iter, fPathData, "D", IsUseRawData());
+        const Int_t n1 = fSequence.GetNumDatRuns();
+        if (n0==0)
+          {
+            *fLog << err << "ERROR - No input files of sequence found!" << endl;
+            return kFALSE;
+          }
+        if (n0!=n1)
+          {
+            *fLog << err << "ERROR - Number of files found (" << n0 << ") doesn't match number of files in sequence (" << n1 << ")" << endl;
+            if (fLog->GetDebugLevel()>4)
+            {
+                *fLog << dbg << "Files which are searched:" << endl;
+                iter.Print();
+            }
+            return kFALSE;
+          }
+      }
+    
+    // Read File
+    MCalibrationIntensityChargeCam      ichcam;
+    MCalibrationIntensityQECam          iqecam;
+    MCalibrationIntensityBlindCam       iblcam;
+    MCalibrationIntensityRelTimeCam     itmcam;
+    MBadPixelsIntensityCam              ibdcam;
+
+    MHCalibrationChargeCam      hchacam;
+    MHCalibrationChargeBlindCam hbndcam;
+    MHCalibrationChargePINDiode hpndiod;
+    MHCalibrationRelTimeCam     hrelcam;
+
+    MCalibrationChargeCam      calcam;
+    MCalibrationQECam          qecam;
+    MCalibrationBlindCam       bndcam;
+    MCalibrationChargePINDiode pind;
+    MCalibrationRelTimeCam     tmcam;
+    MCalibrationHiLoCam        hilcam;
+    MCalibrationPulseTimeCam   pulcam;
+
+    MBadPixelsCam              badpix;
+
+    TObjArray interlacedcont;
+    if (fIsInterlaced)
+    {
+        interlacedcont.Add(&ichcam);
+        interlacedcont.Add(&iqecam);
+        interlacedcont.Add(&iblcam);
+        interlacedcont.Add(&itmcam);
+        interlacedcont.Add(&ibdcam);
+        interlacedcont.Add(&hchacam);
+        interlacedcont.Add(&hbndcam);
+        interlacedcont.Add(&hpndiod);
+        if (fIsRelTimesUpdate)
+	  interlacedcont.Add(&hrelcam);
+    }
+
+    MExtractor *extractor1=fExtractor;
+    MExtractor *extractor2=0;
+    MExtractor *extractor3=0;
+    TString geom;
+
+    TObjArray calibcont;
+    calibcont.Add(&calcam);
+    calibcont.Add(&qecam);
+    calibcont.Add(&bndcam);
+    calibcont.Add(&pind);
+    calibcont.Add(&tmcam);
+
+    if (!ReadCalibration(calibcont, badpix, extractor1, extractor2, geom))
+        return kFALSE;
+
+    *fLog << all;
+    if (!geom.IsNull())
+        *fLog << inf << "Camera geometry found in file: " << geom << endl;
+    else
+        *fLog << inf << "No Camera geometry found using default <MGeomCamMagic>" << endl;
+
+    if (extractor1)
+    {
+      *fLog << underline << "Signal Extractor found in calibration file" << endl;
+      extractor1->Print();
+      *fLog << endl;
+      extractor3 = (MExtractor*)extractor1->Clone();
+    }
+    else
+      *fLog << inf << "No Signal Extractor: ExtractSignal in file." << endl;
+
+    if (extractor2)
+    {
+        *fLog << underline << "Time Extractor found in calibration file" << endl;
+        extractor2->Print();
+        *fLog << endl;
+    }
+    else
+        *fLog << inf << "No Time Extractor: ExtractTime in file." << endl;
+
+    // This is necessary for the case in which it is not in the files
+    MBadPixelsCam badcam;
+
+    // Setup Parlist
+    MParList plist;
+    plist.AddToList(this); // take care of fDisplay!
+    plist.AddToList(&badcam);
+    plist.AddToList(&hilcam);
+    plist.AddToList(&calibcont);       // Using AddToList(TObjArray *)
+    plist.AddToList(&interlacedcont);  // Using AddToList(TObjArray *)
+    plist.AddToList(&pulcam);
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadReports readreal;
+    readreal.AddTree("Events", "MTime.", kTRUE);
+    readreal.AddTree("Trigger");
+    readreal.AddTree("Camera");
+    readreal.AddTree("Drive");
+    readreal.AddTree("CC");
+    readreal.AddTree("Currents");
+
+    MReadMarsFile readmc("Events");
+    readmc.DisableAutoScheme();
+
+    MRawFileRead rawread(NULL);
+
+    MRead *read = 0;
+    switch (GetDataFlag())
+    {
+    case kIsUseRawData:  read = &rawread;  break;
+    case kIsUseMC:       read = &readmc;   break;
+    case kIsUseRootData: read = &readreal; break;
+    }
+    read->AddFiles(fSequence.IsValid() ? iter : *fRuns);
+
+    const TString fname(Form("%s{s/_D_/_Y_}{s/.raw$/.root}", fPathOut.Data()));
+
+    
+    // Skips empty MC events (Not necessary, but faster!)
+    MContinue contmc("MRawEvtData.GetNumPixels<0.5", "ContEmptyMC");
+
+    MPointingPosInterpolate pextr;
+    pextr.AddFiles(&iter);
+    
+    MGeomApply             apply; // Only necessary to create geometry
+    if (!geom.IsNull())
+        apply.SetGeometry(geom);
+    MBadPixelsMerge        merge(&badpix);
+
+    // Make sure that pedcamab has the correct name
+    pedcamab.SetName("MPedestalFundamental");
+    pedcamextr.SetName("MPedestalFromExtractorRndm");
+    pedcambias.SetName("MPedestalFromExtractor");
+    plist.AddToList(&pedcamextr);
+    plist.AddToList(&pedcambias);
+    plist.AddToList(&pedcamab);
+
+    MArrivalTimeCam timecam;
+    plist.AddToList(&timecam);
+
+    // Check for interleaved events
+    MCalibrationPatternDecode caldec;
+    MTriggerPatternDecode     decode;
+
+    MFTriggerPattern ftp;
+    //    ftp.RequireCalibration();
+    ftp.DenyCalibration();
+    ftp.DenyPedestal();
+    //    ftp.DenyPinDiode();
+    ftp.SetInverted();
+    MContinue conttp(&ftp, "ContTrigPattern");
+    // --> tlist2
+
+    // Do signal and pedestal calculation
+    MPedCalcFromLoGain     pedlo1("MPedCalcFundamental");
+    pedlo1.SetPedestalUpdate(kTRUE);
+    pedlo1.SetNamePedestalCamOut("MPedestalFundamental");
+
+    MPedCalcFromLoGain     pedlo2("MPedCalcWithExtractorRndm");
+    pedlo2.SetPedestalUpdate(kTRUE);
+    pedlo2.SetRandomCalculation(kTRUE);
+    pedlo2.SetNamePedestalCamIn("MPedestalFundamental");
+    pedlo2.SetNamePedestalCamOut("MPedestalFromExtractorRndm");
+
+    MPedCalcFromLoGain     pedlo3("MPedCalcWithExtractor");
+    pedlo3.SetPedestalUpdate(kTRUE);
+    pedlo3.SetRandomCalculation(kFALSE);
+    pedlo3.SetNamePedestalCamIn("MPedestalFundamental");
+    pedlo3.SetNamePedestalCamOut("MPedestalFromExtractor");
+
+    if (extractor1)
+    {
+        extractor1->SetPedestals(&pedcamab);
+
+        if (extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        {
+            pedlo2.SetExtractor((MExtractTimeAndCharge*)extractor1);
+            pedlo3.SetExtractor((MExtractTimeAndCharge*)extractor1);
+            const Int_t win = ((MExtractTimeAndCharge*)extractor1)->GetWindowSizeHiGain();
+            pedlo1.SetExtractWindow(15, win);
+            pedlo2.SetExtractWindow(15, win/*obsolete*/);
+            pedlo3.SetExtractWindow(15, win/*obsolete*/);
+        }
+        else
+        {
+            // FIXME: How to get the fixed value 15 automatically?
+            const Int_t f = (Int_t)(15.5+extractor1->GetHiGainFirst());
+            const Int_t n = (Int_t)(15.5+extractor1->GetNumHiGainSamples());
+            pedlo1.SetExtractWindow(f, n);
+            pedlo2.SetExtractWindow(f, n);
+            pedlo3.SetExtractWindow(f, n);
+        }
+    }
+    if (extractor2)
+      extractor2->SetPedestals(&pedcamab);
+
+    if (extractor3)
+      extractor3->SetPedestals(&pedcamab);
+
+    MFCosmics fcosmics;
+    fcosmics.SetNamePedestalCam("MPedestalFundamental");
+    MContinue contcos(&fcosmics, "ContTrigEvts");
+    contcos.SetInverted();
+
+    //MMcPedestalCopy pcopy;
+    MTaskEnv taskenv1("ExtractSignal");
+    MTaskEnv taskenv2("ExtractTime");
+    MTaskEnv taskenv3("ExtractInterlaced");
+    taskenv1.SetDefault(extractor1);
+    taskenv2.SetDefault(extractor2);
+    taskenv3.SetDefault(extractor3);
+
+    // 
+    // This is new calibration to photo-electrons, hard-coded
+    // as decided at the Wuerzburg software meeting 26.01.05
+    //
+    MCalibrateData calib;
+    calib.SetSignalType(MCalibrateData::kPhe);
+    calib.AddPedestal("Fundamental");
+    calib.AddPedestal("FromExtractor");
+    calib.AddPedestal("FromExtractorRndm");
+    calib.SetPedestalFlag(MCalibrateData::kEvent);
+    //----------------------------------------------------------
+
+    MExtractPINDiode        pinext;
+    MExtractBlindPixel      bldext;
+
+    MFTriggerPattern        fcalib("CalibFilter");
+    fcalib.RequireCalibration();
+
+    MCalibrationChargeCalc  chcalc;
+    MCalibrationRelTimeCalc recalc;
+    MCalibCalcFromPast      pacalc;
+    chcalc.SetOutputFile("");
+    recalc.SetOutputFile("");
+
+    pinext.SetPedestals(&pedcamab);
+    bldext.SetPedestals(&pedcamab);
+    chcalc.SetPedestals(&pedcamextr);
+
+    pacalc.SetChargeCalc(&chcalc);
+    if (fIsRelTimesUpdate)
+      pacalc.SetRelTimeCalc(&recalc);
+    pacalc.SetCalibrate(&calib);
+
+    //
+    // Intensity Calibration histogramming
+    //
+    MFillH filpin("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode",   "FillPINDiode");
+    MFillH filbnd("MHCalibrationChargeBlindCam", "MExtractedSignalBlindPixel", "FillBlindCam");
+    MFillH filcam("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillChargeCam");
+    MFillH filtme("MHCalibrationRelTimeCam",     "MArrivalTimeCam",            "FillRelTime");
+    MFillH filhil("MHCalibrationHiLoCam",        "MExtractedSignalCam",        "FillHiLoRatio");
+    MFillH filpul("MHCalibrationPulseTimeCam",   "MRawEvtData",                "FillPulseTime");
+
+    filpin.SetBit(MFillH::kDoNotDisplay);
+    filbnd.SetBit(MFillH::kDoNotDisplay);
+    filcam.SetBit(MFillH::kDoNotDisplay);
+    filtme.SetBit(MFillH::kDoNotDisplay);
+    filhil.SetBit(MFillH::kDoNotDisplay);
+    filpul.SetBit(MFillH::kDoNotDisplay);
+
+    MCalibrateRelTimes caltm;
+    MBadPixelsCalc     bpcal;
+    MBadPixelsTreat    treat;
+
+    bpcal.SetNamePedPhotCam("MPedPhotFromExtractor");
+    treat.AddNamePedPhotCam("MPedPhotFundamental");
+    treat.AddNamePedPhotCam("MPedPhotFromExtractor");
+    treat.AddNamePedPhotCam("MPedPhotFromExtractorRndm");
+    if (!extractor2 && !extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        treat.SetProcessTimes(kFALSE);
+
+    MHCamEvent evt0(0, "PedFLG",     "Fundamental Pedestal from Lo Gain;;P [cnts/sl]");
+    MHCamEvent evt1(2, "PedRmsFLG",  "RMS from Extractor applied to ped.;;\\sigma_{p} [cnts/sl]");
+    MHCamEvent evt2(0, "Extra'd",    "Extracted Signal;;S [cnts/sl]");
+    // MHCamEvent evt3(4, "PedPhot",    "Calibrated Pedestal;;P [phe]");
+    MHCamEvent evt4(5, "PedRMS",     "Calibrated RMS from Extractor applied to ped.;;\\sigma_{p} [phe]");
+    MHCamEvent evt5(0, "Interp'd",   "Interpolated Signal;;S [phe]");
+    MHCamEvent evt6(2, "Unsuitable", "Fraction of unsuitable events per Pixel;;[1]");
+    MHCamEvent evt7(6, "Times",      "Calibrated Arrival Time;;T [fadc sl]");
+    MHCamEvent evt8(0, "Conv",       "Calibration Conv. Factors;;[phe/fadc cnts]");
+    MHCamEvent evt9(7, "PulsePos",  "Pulse Position of cosmics (>15phe);;T"); //Calibration Conv. Factors;;[phe/fadc cnts]
+    /*
+     MHCamEventTH evt9(6, "PulsePos",  "Pulse Position of cosmics"); //Calibration Conv. Factors;;[phe/fadc cnts]
+     evt9.SetNameThreshold("MCerPhotEvt");
+     evt9.SetThreshold(15);
+     */
+/*
+    evt0.EnableSqrtVariance();
+    evt1.EnableSqrtVariance();
+    evt2.EnableSqrtVariance();
+    // evt3.EnableVariance();
+    evt4.EnableSqrtVariance();
+    evt5.EnableSqrtVariance();
+    evt7.EnableSqrtVariance();
+    evt8.EnableSqrtVariance();
+  */
+    MFillH fill0(&evt0, "MPedestalFundamental",    "FillPedFLG");
+    MFillH fill1(&evt1, "MPedestalFromExtractorRndm", "FillPedRmsFLG");
+    MFillH fill2(&evt2, "MExtractedSignalCam",     "FillExtracted");
+    // MFillH fill3(&evt3, "MPedPhotFundamental",  "FillPedPhot");
+    MFillH fill4(&evt4, "MPedPhotFromExtractorRndm", "FillPedRMS");
+    MFillH fill5(&evt5, "MSignalCam",              "FillInterpolated");
+    MFillH fill6(&evt6, "MBadPixelsCam",           "FillUnsuitable");
+    MFillH fill7(&evt7, "MSignalCam",              "FillTimes");
+    MFillH fill8(&evt8, "MCalibConstCam",          "FillConv");
+    MFillH fill9(&evt9, "MSignalCam",              "FillPulse");
+
+    MTaskEnv fillflorian("FinalFantasy");
+    fillflorian.SetDefault();
+
+    // The second rule is for the case reading raw-files!
+    MWriteRootFile write(2, fname, fOverwrite?"RECREATE":"NEW");
+    // Run Header
+    write.AddContainer("MRawRunHeader",             "RunHeaders");
+    write.AddContainer("MBadPixelsCam",             "RunHeaders");
+    write.AddContainer("MGeomCam",                  "RunHeaders");
+    // Monte Carlo Headers
+    write.AddContainer("MMcRunHeader",              "RunHeaders", kFALSE);
+    write.AddContainer("MMcFadcHeader",             "RunHeaders", kFALSE);
+    write.AddContainer("MMcTrigHeader",             "RunHeaders", kFALSE);
+    write.AddContainer("MMcConfigRunHeader",        "RunHeaders", kFALSE);
+    write.AddContainer("MMcCorsikaRunHeader",       "RunHeaders", kFALSE);
+    // Monte Carlo
+    write.AddContainer("MMcEvt",                    "Events",     kFALSE);
+    write.AddContainer("MMcTrig",                   "Events",     kFALSE);
+    // Data tree
+    write.AddContainer("MSignalCam",                "Events");
+    write.AddContainer("MPedPhotFundamental",       "Events");
+    write.AddContainer("MPedPhotFromExtractor",     "Events");
+    write.AddContainer("MPedPhotFromExtractorRndm", "Events");
+    write.AddContainer("MTime",                     "Events",     kFALSE);
+    write.AddContainer("MRawEvtHeader",             "Events");
+    //write.AddContainer("MArrivalTime",              "Events",     kFALSE);
+    write.AddContainer("MPointingPos",              "Events",     kFALSE);
+    // Slow-Control: Current-tree
+    write.AddContainer("MTimeCurrents",             "Currents",   kFALSE);
+    write.AddContainer("MCameraDC",                 "Currents",   kFALSE);
+    write.AddContainer("MReportCurrents",           "Currents",   kFALSE);
+    // Slow-Control: Camera-tree
+    write.AddContainer("MReportCamera",             "Camera",     kFALSE);
+    write.AddContainer("MTimeCamera",               "Camera",     kFALSE);
+    write.AddContainer("MCameraAUX",                "Camera",     kFALSE);
+    write.AddContainer("MCameraCalibration",        "Camera",     kFALSE);
+    write.AddContainer("MCameraCooling",            "Camera",     kFALSE);
+    write.AddContainer("MCameraHV",                 "Camera",     kFALSE);
+    write.AddContainer("MCameraLV",                 "Camera",     kFALSE);
+    write.AddContainer("MCameraLids",               "Camera",     kFALSE);
+    // Slow-Control: Trigger-tree
+    write.AddContainer("MReportTrigger",            "Trigger",    kFALSE);
+    write.AddContainer("MTimeTrigger",              "Trigger",    kFALSE);
+    // Slow-Control: Drive-tree
+    write.AddContainer("MReportDrive",              "Drive",      kFALSE);
+    write.AddContainer("MTimeDrive",                "Drive",      kFALSE);
+    // Slow-Control: Central Control-tree
+    write.AddContainer("MReportCC",                 "CC",         kFALSE);
+    write.AddContainer("MTimeCC",                   "CC",         kFALSE);
+
+    // Write the special MC tree
+    MWriteRootFile writemc(2, fname, fOverwrite?"RECREATE":"NEW");
+    writemc.SetName("WriteMC");
+    writemc.AddContainer("MMcEvtBasic", "OriginalMC");
+
+    // Now setup tasklist for events
+    MTaskList tlist2;
+
+    tlist2.AddToList(&caldec);
+    tlist2.AddToList(&decode);
+    tlist2.AddToList(&apply);
+    tlist2.AddToList(&merge);
+    tlist2.AddToList(&pedlo1);
+    tlist2.AddToList(&pedlo2);
+    tlist2.AddToList(&pedlo3);
+    //-----------------------------------------------------------
+    if (fIsInterlaced)
+    {
+	pinext.SetFilter(&fcalib);
+	bldext.SetFilter(&fcalib);
+	taskenv3.SetFilter(&fcalib);
+	pacalc.SetFilter(&fcalib);
+	filcam.SetFilter(&fcalib);
+	filtme.SetFilter(&fcalib);
+	filbnd.SetFilter(&fcalib);
+	filpin.SetFilter(&fcalib);
+	chcalc.SetFilter(&fcalib);
+	recalc.SetFilter(&fcalib);
+
+        tlist2.AddToList(&fcalib);
+        tlist2.AddToList(&pinext);
+        tlist2.AddToList(&bldext);
+	tlist2.AddToList(&taskenv3);
+        tlist2.AddToList(&pacalc);
+        tlist2.AddToList(&filcam);
+	if (fIsRelTimesUpdate)
+	  tlist2.AddToList(&filtme);
+        tlist2.AddToList(&filbnd);
+        tlist2.AddToList(&filpin);
+        tlist2.AddToList(&chcalc);
+	if (fIsRelTimesUpdate)
+	  tlist2.AddToList(&recalc);
+    }
+
+    tlist2.AddToList(&conttp);
+    if (extractor1)
+      tlist2.AddToList(&taskenv1);
+    if (extractor2)
+      tlist2.AddToList(&taskenv2);
+    tlist2.AddToList(&fill0);
+    tlist2.AddToList(&fill1);
+    tlist2.AddToList(&contcos);
+    if (fIsHiLoCalibration)
+      tlist2.AddToList(&filhil);
+    if (fIsPulsePosCheck)
+      tlist2.AddToList(&filpul);
+    tlist2.AddToList(&fill2);
+    tlist2.AddToList(&calib);
+    if (extractor2 || extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        tlist2.AddToList(&caltm);
+    if (fIsInterlaced)
+      tlist2.AddToList(&fill8);
+    tlist2.AddToList(&bpcal);
+    tlist2.AddToList(&treat);
+    tlist2.AddToList(&fill6);
+    //    tlist2.AddToList(&fill3);
+    tlist2.AddToList(&fill4);
+    tlist2.AddToList(&fill5);
+    if (extractor2 || extractor1->InheritsFrom("MExtractTimeAndCharge"))
+      tlist2.AddToList(&fill7);
+    tlist2.AddToList(&fill9);
+
+    tlist2.AddToList(&fillflorian);
+
+    // Setup List for Drive-tree
+    MPointingPosCalc pcalc;
+
+    // Now setup main tasklist
+    tlist.AddToList(read);
+    if (IsUseMC())
+        tlist.AddToList(&writemc);
+    tlist.AddToList(&contmc);
+
+    if (IsUseRootData())
+      tlist2.AddToList(&pextr);
+    tlist.AddToList(&tlist2, IsUseRootData() ? "Events" : "All");
+
+    if (IsUseMC())
+      tlist.AddToList(&pcalc, "Drive");
+
+    tlist.AddToList(&write);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    // Execute first analysis
+    const Bool_t rc = evtloop.Eventloop(fMaxEvents);
+
+    // Print statistics
+    if (read->GetNumExecutions()>0)
+        tlist.PrintStatistics();
+
+    // make sure owned object are deleted
+    if (extractor1 && extractor1!=fExtractor)
+        delete extractor1;
+    if (extractor2)
+        delete extractor2;
+    if (extractor3)
+        delete extractor3;
+
+    // return if job failed
+    if (!rc)
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    // if everything went ok write and display result
+    DisplayResult(plist);
+
+    if (fIsPixelCheck)
+      {
+        if (fIsPulsePosCheck)
+          {
+            MHCalibrationPulseTimeCam *pcam = (MHCalibrationPulseTimeCam*)plist.FindObject("MHCalibrationPulseTimeCam");
+            MHCalibrationPix &pix1 = (*pcam)[fCheckedPixId];
+            pix1.DrawClone("");
+          }
+        
+	if (fIsHiLoCalibration)
+	  {
+	    MHCalibrationHiLoCam *hcam = (MHCalibrationHiLoCam*)plist.FindObject("MHCalibrationHiLoCam");
+	    MHCalibrationPix &pix2 = (*hcam)[fCheckedPixId];
+	    pix2.DrawClone("");
+	  }
+      }
+
+    interlacedcont.Add(&pulcam);
+
+    if (fIsHiLoCalibration)
+      interlacedcont.Add(&hilcam);
+
+    if (IsHistsStorage())
+      {
+        interlacedcont.Add(plist.FindObject("MHCalibrationHiLoCam"));
+        interlacedcont.Add(plist.FindObject("MHCalibrationPulseTimeCam"));
+      }
+    
+    if (!WriteResult(interlacedcont))
+      return kFALSE;
+
+    // return if job went ok
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
+
+
+void MJCalibrateSignal::DisplayResult(MParList &plist)
+{
+
+    if (!fDisplay)
+        return;
+
+    MGeomCam &geomcam = *(MGeomCam*)plist.FindObject("MGeomCam");
+
+    //
+    // Get container from list
+    //
+    MCalibrationPulseTimeCam *pcam = (MCalibrationPulseTimeCam*)plist.FindObject("MCalibrationPulseTimeCam");
+
+    MHCamera disp11 (geomcam, "PulseTime", "Mean pulse arrival time cosmics");
+    MHCamera disp21 (geomcam, "PulseTimeRMS", "RMS of pulse arrival time cosmics");
+
+    if (pcam)
+      {
+        disp11.SetCamContent(*pcam,  0);
+        disp11.SetCamError(  *pcam,  1);
+        disp21.SetCamContent(*pcam,  2);
+        disp21.SetCamError(  *pcam,  3);
+      }
+    
+    disp11.SetYTitle("T [FADC sl.]");
+    disp21.SetYTitle("T [FADC sl.]");
+
+    if (fIsPulsePosCheck)
+      {
+        TCanvas &c0 = fDisplay->AddTab("PulseTime");
+        c0.Divide(2,3);
+        
+        disp11.CamDraw(c0, 1, 2, 1);
+        disp21.CamDraw(c0, 2, 2, 1);
+      }
+
+    if (!fIsHiLoCalibration)
+      return;
+
+    MCalibrationHiLoCam *hcam      = (MCalibrationHiLoCam*)plist.FindObject("MCalibrationHiLoCam");
+
+    // Create histograms to display
+    MHCamera disp1 (geomcam, "HiLoConv", "Ratio Amplification HiGain vs. LoGain (Charges)");
+    MHCamera disp2 (geomcam, "HiLoDiff", "Arrival Time Diff. HiGain vs. LoGain (Times)");
+
+    disp1.SetCamContent(*hcam,  0);
+    disp1.SetCamError(  *hcam,  1);
+    disp2.SetCamContent(*hcam,  5);
+    disp2.SetCamError(  *hcam,  6);
+
+    disp1.SetYTitle("R [1]");
+    disp2.SetYTitle("\\Delta T [FADC sl.]");
+
+
+    TCanvas &c1 = fDisplay->AddTab("HiLoConv");
+    c1.Divide(2,3);
+    
+    disp1.CamDraw(c1, 1, 2, 1);
+    disp2.CamDraw(c1, 2, 2, 1);
+}
+
Index: /tags/Mars-V0.9/mjobs/MJCalibrateSignal.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCalibrateSignal.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCalibrateSignal.h	(revision 9772)
@@ -0,0 +1,54 @@
+#ifndef MARS_MJCalibrateSignal
+#define MARS_MJCalibrateSignal
+
+#ifndef MARS_MJCalib
+#include "MJCalib.h"
+#endif
+
+class TEnv;
+class TList;
+class MTask;
+class MParList;
+class MGeomCam;
+class MSequence;
+class MExtractor;
+class MPedestalCam;
+class MBadPixelsCam;
+class MRunIter;
+
+class MJCalibrateSignal : public MJCalib
+{
+private:
+    MExtractor *fExtractor;
+
+    Bool_t fIsInterlaced;               // Distinguish interlaced from other calibration
+    Bool_t fIsRelTimesUpdate;           // Choose to update relative times from interlaced
+    
+    Bool_t CheckEnvLocal();
+
+    void   DisplayResult(MParList &plist);
+
+    Bool_t WriteResult(TObjArray &cont);
+    Bool_t ReadCalibration(TObjArray &o, MBadPixelsCam &bpix,
+                           MExtractor* &ext1, MExtractor* &ext2, TString &geom) const;
+    Bool_t ReadExtractorCosmics(MExtractor* &ext1) const;
+
+    const char*  GetInputFileName() const;
+    const char*  GetInputFile() const;
+    
+public:
+
+    MJCalibrateSignal(const char *name=NULL, const char *title=NULL);
+    ~MJCalibrateSignal();
+
+    Bool_t ProcessFile(MPedestalCam &camab, MPedestalCam &cam1, MPedestalCam &cam2);
+
+    void SetInterlaced     ( const Bool_t b=kTRUE )  { fIsInterlaced      = b; }
+    void SetRelTimesUpdate ( const Bool_t b=kTRUE )  { fIsRelTimesUpdate  = b; }
+
+    void SetExtractor(const MExtractor *ext=NULL);
+
+    ClassDef(MJCalibrateSignal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJCalibration.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCalibration.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCalibration.cc	(revision 9772)
@@ -0,0 +1,2298 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Markus Gaug, 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalibration
+//
+//  Do one calibration loop over serious of runs with the same pulser 
+//  colour and the same intensity. The following containers (rectangular) and 
+//  tasks (ellipses) are called to produce an MCalibrationChargeCam and to 
+//  update the MCalibrationQECam: (MCalibrate is not called from this class)
+//
+//Begin_Html
+/*
+<img src="images/CalibClasses.gif">
+*/
+//End_Html
+//
+// Different signal extractors can be set with the command SetExtractor()
+// Only extractors deriving from MExtractor can be set, default is MExtractSlidingWindow
+//
+// Different arrival time extractors can be set with the command SetTimeExtractor()
+// Only extractors deriving from MExtractTime can be set, default is MExtractTimeHighestIntegral
+//
+// At the end of the eventloop, plots and results are displayed, depending on 
+// the flags set (see DisplayResult()) 
+// 
+// If the flag SetFullDisplay() is set, all MHCameras will be displayed. 
+// if the flag SetDataCheckDisplay() is set, only the most important ones are displayed 
+// Otherwise, (default: SetNormalDisplay()), a good selection of plots is given
+//
+// The absolute light calibration devices Blind Pixel and PIN Diode can be switched on
+// and off with the commands:
+//
+// - SetUseBlindPixel(Bool_t )
+// - SetUsePINDiode(Bool_t )
+//
+// See also: MHCalibrationChargePix, MHCalibrationChargeCam, MHGausEvents
+//           MHCalibrationChargeBlindPix, MHCalibrationChargePINDiode
+//           MCalibrationChargePix, MCalibrationChargeCam, MCalibrationChargeCalc
+//           MCalibrationBlindPix, MCalibrationChargePINDiode,
+//           MCalibrationQECam, MBadPixelsPix, MBadPixelsCam
+//
+// If the flag RelTimeCalibration() is set, a calibration of the relative arrival 
+// times is also performed. The following containers (rectangular) and 
+// tasks (ellipses) are called to produce an MCalibrationRelTimeCam used by  
+// MCalibrateTime to correct timing offset between pixels: (MCalibrateTime is not 
+// called from this class)
+//
+//Begin_Html
+/*
+<img src="images/RelTimeClasses.gif">
+*/
+//End_Html
+//
+// Different arrival time extractors can be set directly with the command
+// SetTimeExtractor(MExtractor *)
+//
+// Resource file entries are case sensitive!
+//
+// See also: MHCalibrationRelTimePix, MHCalibrationRelTimeCam, MHGausEvents
+//           MCalibrationRelTimePix, MCalibrationRelTimeCam
+//           MBadPixelsPix, MBadPixelsCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalibration.h"
+
+#include <TFile.h>
+#include <TF1.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TLegend.h>
+#include <TRegexp.h>
+#include <TPaveText.h>
+#include <TPaveStats.h>
+#include <TEnv.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRunIter.h"
+#include "MSequence.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MHCamera.h"
+#include "MGeomCam.h"
+
+#include "MPedestalCam.h"
+#include "MCalibColorSteer.h"
+
+#include "MCalibrationIntensityChargeCam.h"
+#include "MCalibrationIntensityBlindCam.h"
+#include "MCalibrationIntensityRelTimeCam.h"
+#include "MCalibrationIntensityQECam.h"
+
+#include "MCalibrationPatternDecode.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationHiLoCam.h"
+#include "MCalibrationHiLoPix.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationBlindPix.h"
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationBlindCamOneOldStyle.h"
+#include "MCalibrationBlindCamTwoNewStyle.h"
+#include "MCalibrationBlindCamThreeNewStyle.h"
+#include "MCalibrationChargeCalc.h"
+#include "MCalibColorSet.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimeCalc.h"
+
+#include "MHGausEvents.h"
+#include "MHCalibrationCam.h"
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationChargeBlindCam.h"
+#include "MHCalibrationChargePINDiode.h"
+#include "MHCalibrationRelTimeCam.h"
+#include "MHCalibrationPix.h"
+
+#include "MReadMarsFile.h"
+#include "MPedCalcPedRun.h"
+#include "MRawFileRead.h"
+#include "MGeomApply.h"
+#include "MTaskEnv.h"
+#include "MBadPixelsMerge.h"
+#include "MBadPixelsCam.h"
+#include "MExtractTime.h"
+#include "MExtractor.h"
+#include "MExtractPINDiode.h"
+#include "MExtractBlindPixel.h"
+#include "MExtractSlidingWindow.h"
+#include "MExtractTimeHighestIntegral.h"
+#include "MFCosmics.h"
+#include "MContinue.h"
+#include "MFillH.h"
+
+#include "MArrivalTimeCam.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MJCalibration);
+
+using namespace std;
+
+const Int_t MJCalibration::gkIFAEBoxInaugurationRun        = 20113;
+const Int_t MJCalibration::gkSecondBlindPixelInstallation  = 31693;
+const Int_t MJCalibration::gkSpecialPixelsContInstallation = 34057;
+const Int_t MJCalibration::gkThirdBlindPixelInstallation   = 43308;
+const TString MJCalibration::fgReferenceFile = "mjobs/calibrationref.rc";
+const TString MJCalibration::fgHiLoCalibFile = "mjobs/hilocalib_df46.root";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// - Sets fRuns to 0, fExtractor to NULL, fTimeExtractor to NULL, fColor to kNONE, 
+//   fDisplay to kNormalDisplay, kRelTimes to kFALSE, kataCheck to kFALSE, kDebug to kFALSE,
+//   kIntensity to kFALSE
+// - SetUseBlindPixel()
+// - SetUsePINDiode()
+//
+MJCalibration::MJCalibration(const char *name, const char *title) 
+    : fExtractor(NULL), fTimeExtractor(NULL), 
+      fColor(MCalibrationCam::kNONE), fDisplayType(kDataCheckDisplay),
+      fGeometry("MGeomCamMagic")
+{
+
+  fName  = name  ? name  : "MJCalibration";
+  fTitle = title ? title : "Tool to create the calibration constants for one calibration run";
+  
+  SetUseBlindPixel(kFALSE);
+  SetUsePINDiode(kFALSE);
+  
+  SetHiLoCalibration();
+  SetRelTimeCalibration();
+  SetDebug(kFALSE);
+  SetIntensity(kFALSE);
+
+  SetReferenceFile();
+  SetHiLoCalibFile();
+
+  fConvFADC2PheMin           = 0.;
+  fConvFADC2PheMax           = 1.5;
+  fConvFADC2PhotMin          = 0.; 
+  fConvFADC2PhotMax          = 10.; 
+  fQEMin                     = 0.;
+  fQEMax                     = 0.3;
+  fArrivalTimeMin            = 1.;
+  fArrivalTimeMax            = 10.;
+  fTimeOffsetMin             = -3.;
+  fTimeOffsetMax             =  3.;
+  fTimeResolutionMin         =  0.;
+  fTimeResolutionMax         =  1.;
+  
+  fRefConvFADC2PheInner      = 0.14;       
+  fRefConvFADC2PheOuter      = 0.4;       
+  fRefConvFADC2PhotInner     = 0.8; 
+  fRefConvFADC2PhotOuter     = 3.8; 
+  fRefQEInner                = 0.18;            
+  fRefQEOuter                = 0.12;
+  fRefArrivalTimeInner       = 4.5;            
+  fRefArrivalTimeOuter       = 5.0;
+  fRefArrivalTimeRmsInner    = 0.5;            
+  fRefArrivalTimeRmsOuter    = 0.5;
+  fRefTimeOffsetInner        = -0.23;    
+  fRefTimeOffsetOuter        = 0.39;    
+  fRefTimeResolutionInner    = 0.153;
+  fRefTimeResolutionOuter    = 0.128;
+
+}
+
+void MJCalibration::DrawTab(MParList &plist, const char *cont, const char *name, Option_t *opt)
+{
+    TObject *obj = plist.FindObject(cont);
+    if (!obj)
+        return;
+
+    fDisplay->AddTab(name);
+    obj->DrawClone(opt);
+}
+
+// --------------------------------------------------------------------------
+//
+// Display the results in MStatusDisplay: 
+//
+// - Add "Calibration" to the MStatusDisplay title
+// - Retrieve the MGeomCam from MParList
+// - Initialize the following MHCamera's:
+//   1)  MCalibrationPix::GetMean()
+//   2)  MCalibrationPix::Sigma()
+//   3)  MCalibrationChargePix::GetRSigma()
+//   4)  MCalibrationChargePix::GetRSigmaPerCharge()
+//   5)  MCalibrationChargePix::GetPheFFactorMethod()
+//   6)  MCalibrationChargePix::GetMeanConvFADC2Phe()
+//   7)  MCalibrationChargePix::GetMeanFFactorFADC2Phot()
+//   8)  MCalibrationQEPix::GetQECascadesFFactor()
+//   9)  MCalibrationQEPix::GetQECascadesBlindPixel()
+//   10) MCalibrationQEPix::GetQECascadesPINDiode()
+//   11) MCalibrationQEPix::GetQECascadesCombined()
+//   12) MCalibrationQEPix::IsAverageQEFFactorAvailable()
+//   13) MCalibrationQEPix::IsAverageQEBlindPixelAvailable()
+//   14) MCalibrationQEPix::IsAverageQEPINDiodeAvailable()
+//   15) MCalibrationQEPix::IsAverageQECombinedAvailable()
+//   16) MCalibrationChargePix::IsHiGainSaturation()
+//   17) MCalibrationPix::GetHiLoMeansDivided()
+//   18) MCalibrationPix::GetHiLoSigmasDivided()
+//   19) MCalibrationChargePix::GetHiGainPickup()
+//   20) MCalibrationChargePix::GetLoGainPickup()
+//   21) MCalibrationChargePix::GetHiGainBlackout()
+//   22) MCalibrationChargePix::GetLoGainBlackout()
+//   23) MCalibrationPix::IsExcluded()
+//   24) MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnsuitableRun)
+//   25) MBadPixelsPix::IsUnsuitable(MBadPixelsPix::kUnreliableRun)
+//   26) MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kHiGainOscillating)
+//   27) MBadPixelsPix::IsUncalibrated(MBadPixelsPix::kLoGainOscillating)
+//   28) MCalibrationChargePix::GetAbsTimeMean()
+//   29) MCalibrationChargePix::GetAbsTimeRms()
+//
+// If the flag SetFullDisplay() is set, all MHCameras will be displayed. 
+// if the flag SetDataCheckDisplay() is set, only the most important ones are displayed 
+// and otherwise, (default: SetNormalDisplay()), a good selection of plots is given
+//
+void MJCalibration::DisplayResult(MParList &plist)
+{
+    if (!fDisplay)
+        return;
+
+    TString drawoption = "nonew ";
+    if (fDisplayType == kDataCheckDisplay)
+        drawoption += "datacheck";
+    if (fDisplayType == kFullDisplay)
+        drawoption += "all";
+
+    if (IsUsePINDiode())
+        DrawTab(plist, "MHCalibrationChargePINDiode", "PINDiode",  drawoption);
+    if (IsUseBlindPixel())
+        DrawTab(plist, "MHCalibrationChargeBlindCam", "BlindPix",  drawoption);
+    if (IsRelTimes())
+        DrawTab(plist, "MHCalibrationRelTimeCam",     "Time",      drawoption);
+    DrawTab(plist, "MHCalibrationChargeCam",          "Charge",    drawoption);
+
+    //
+    // Update display
+    //
+    TString title = fDisplay->GetTitle();
+    title += "--  Calibration ";
+    title += fSequence.IsValid() ? Form("calib%08d", fSequence.GetSequence()) : (const char*)fRuns->GetRunsAsString();
+    title += "  --";
+    fDisplay->SetTitle(title);
+
+    //
+    // Get container from list
+    //
+    MGeomCam &geomcam = *(MGeomCam*)plist.FindObject("MGeomCam");
+
+    // Create histograms to display
+    MHCamera disp1 (geomcam, "Charge",            "Fitted Mean Signal (Charges)");
+    MHCamera disp2 (geomcam, "SigmaCharge",       "Sigma of Fitted Signal");
+    MHCamera disp3 (geomcam, "RSigma",            "Reduced Sigmas");
+    MHCamera disp4 (geomcam, "RSigmaPerCharge",   "Reduced Sigma per Charge");
+    MHCamera disp5 (geomcam, "NumPhes",           "Number Photo-electrons");
+    MHCamera disp6 (geomcam, "ConvFADC2Phes",     "Conversion Factor to Phes");
+    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 suitable, but 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");
+    MHCamera disp35(geomcam, "TotalConv",         "Conversion Factor to photons");
+    MHCamera disp36(geomcam, "RMSperMean",        "Charge histogram RMS per Mean");
+    
+    MCalibrationChargeCam  *cam    = NULL;
+    MCalibrationQECam      *qecam  = NULL;
+    MCalibrationRelTimeCam *relcam = NULL;
+    MBadPixelsCam          *badcam = NULL;
+
+    if (IsIntensity())
+    {
+        cam    = (MCalibrationChargeCam*) fIntensCalibCam.GetCam();
+        qecam  = (MCalibrationQECam*)     fIntensQECam.GetCam();
+        relcam = (MCalibrationRelTimeCam*)fIntensRelTimeCam.GetCam();
+        badcam = (MBadPixelsCam*)         fIntensBadCam.GetCam();
+    }
+    else
+    {
+        cam    = &fCalibrationCam;
+        qecam  = &fQECam;
+        relcam = &fRelTimeCam;
+        badcam = &fBadPixels;
+    }
+    
+    // Fitted charge means and sigmas
+    disp1.SetCamContent(*cam,  0);
+    disp1.SetCamError(  *cam,  1);
+    disp2.SetCamContent(*cam,  2);
+    disp2.SetCamError(  *cam,  3);
+
+    // Reduced Sigmas and reduced sigmas per charge
+    disp3.SetCamContent(*cam,  5);
+    disp3.SetCamError(  *cam,  6);
+    disp4.SetCamContent(*cam,  7);
+    disp4.SetCamError(  *cam,  8);
+
+    // F-Factor Method
+    disp5.SetCamContent(*cam,  9);
+    disp5.SetCamError(  *cam, 10);
+    disp6.SetCamContent(*cam, 11);
+    disp6.SetCamError(  *cam, 12);
+    disp7.SetCamContent(*cam, 13);
+    disp7.SetCamError(  *cam, 14);
+
+    // Quantum Efficiencies
+    disp8.SetCamContent (*qecam, 0 );
+    disp8.SetCamError   (*qecam, 1 );
+    disp9.SetCamContent (*qecam, 2 );
+    disp9.SetCamError   (*qecam, 3 );
+    disp10.SetCamContent(*qecam, 4 );
+    disp10.SetCamError  (*qecam, 5 );
+    disp11.SetCamContent(*qecam, 6 );
+    disp11.SetCamError  (*qecam, 7 );
+
+    // Valid flags
+    disp12.SetCamContent(*qecam, 8 );
+    disp13.SetCamContent(*qecam, 9 );
+    disp14.SetCamContent(*qecam, 10);
+    disp15.SetCamContent(*qecam, 11);
+
+    // Conversion Hi-Lo
+    disp16.SetCamContent(*cam, 25);
+    disp17.SetCamContent(*cam, 16);
+    disp17.SetCamError  (*cam, 17);
+    disp18.SetCamContent(*cam, 18);
+    disp18.SetCamError  (*cam, 19);
+
+    // Pickup and Blackout
+    disp19.SetCamContent(*cam, 21);
+    disp20.SetCamContent(*cam, 22);
+    disp21.SetCamContent(*cam, 23);
+    disp22.SetCamContent(*cam, 24);
+
+    // Pixels with defects
+    disp23.SetCamContent(*cam, 20);
+    disp24.SetCamContent(*badcam, 6);
+    disp25.SetCamContent(*badcam, 7);
+
+    // Oscillations
+    disp26.SetCamContent(*badcam, 10);
+    disp27.SetCamContent(*badcam, 11);
+
+    // Arrival Times
+    disp28.SetCamContent(*cam, 26);
+    disp28.SetCamError(  *cam, 27);
+    disp29.SetCamContent(*cam, 27);
+
+    // RMS and Mean
+    disp36.SetCamContent(*cam,32);
+
+    disp1.SetYTitle("Q [FADC cnts]");
+    disp2.SetYTitle("\\sigma_{Q} [FADC cnts]");
+
+    disp3.SetYTitle("\\sqrt{\\sigma^{2}_{Q} - RMS^{2}_{Ped}} [FADC cnts]");
+    disp4.SetYTitle("Red.Sigma/<Q> [1]");
+
+    disp5.SetYTitle("Photo-electons [1]");
+    disp6.SetYTitle("Conv.Factor [PhE/FADC cnts]");
+    disp7.SetYTitle("Total F-Factor [1]");
+
+    disp8.SetYTitle("QE [1]");
+    disp9.SetYTitle("QE [1]");
+    disp10.SetYTitle("QE [1]");
+    disp11.SetYTitle("QE [1]");
+
+    disp12.SetYTitle("[1]");
+    disp13.SetYTitle("[1]");
+    disp14.SetYTitle("[1]");
+    disp15.SetYTitle("[1]");
+    disp16.SetYTitle("[1]");
+
+    disp17.SetYTitle("<Q>(High)/<Q>(Low) [1]");
+    disp18.SetYTitle("\\sigma_{Q}(High)/\\sigma_{Q}(Low) [1]");
+
+    disp19.SetYTitle("[1]");
+    disp20.SetYTitle("[1]");
+    disp21.SetYTitle("[1]");
+    disp22.SetYTitle("[1]");
+    //    disp23.SetYTitle("[1]");
+    //    disp24.SetYTitle("[1]");
+    //    disp25.SetYTitle("[1]");
+    disp26.SetYTitle("[1]");
+    disp27.SetYTitle("[1]");
+
+    disp28.SetYTitle("Mean Abs. Time [FADC sl.]");
+    disp29.SetYTitle("RMS Abs. Time [FADC sl.]");
+
+    disp35.SetYTitle("Conv.Factor [Ph/FADC cnts]");
+
+    disp36.SetYTitle("Charge RMS/<Q> [1]");
+
+    for (UInt_t i=0;i<geomcam.GetNumPixels();i++)
+      {
+
+        MCalibrationChargePix &pix = (MCalibrationChargePix&)(*cam)  [i];
+        MCalibrationQEPix     &qe  = (MCalibrationQEPix&)    (*qecam)[i];
+
+        if (!pix.IsFFactorMethodValid())
+          continue;
+
+        const Float_t convphe  = pix.GetMeanConvFADC2Phe();
+        const Float_t quaeff   = qe.GetQECascadesFFactor(0.);
+        
+        disp35.Fill(i,convphe/quaeff);
+        disp35.SetUsed(i);
+      }
+    
+
+    if (IsRelTimes())
+    {
+        disp30.SetCamContent(*relcam,0);
+        disp30.SetCamError(  *relcam,1);
+        disp31.SetCamContent(*relcam,2);
+        disp31.SetCamError(  *relcam,3);
+        disp32.SetCamContent(*relcam,4);
+        disp33.SetCamContent(fBadPixels,20);
+        disp34.SetCamContent(fBadPixels,21);
+    
+        disp30.SetYTitle("Time Offset [FADC units]");
+        disp31.SetYTitle("Timing resolution [FADC units]");
+        disp32.SetYTitle("P_{Time} [1]");
+        disp33.SetYTitle("[1]");
+        disp34.SetYTitle("[1]");
+    }
+
+    if (fDisplayType == kDataCheckDisplay)
+    {
+      
+      TCanvas &c1 = fDisplay->AddTab("FitCharge");
+      c1.Divide(3, 3);
+      
+      //
+      // MEAN CHARGES
+      // 
+      
+      c1.cd(1);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj1=(MHCamera*)disp1.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      // obj1->SetMinimum(fChargeMin);
+      // obj1->SetMaximum(fChargeMax);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj1);
+      obj1->SetStats(kFALSE);
+      //
+      // set reference lines
+      //
+      //        DisplayReferenceLines(obj1,0);
+      
+      c1.cd(4);
+      gPad->SetBorderMode(0);
+      obj1->SetPrettyPalette();
+      obj1->Draw();
+      
+      c1.cd(7);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      TH1D *obj2 = (TH1D*)obj1->Projection(obj1->GetName());
+      obj2->Draw();
+      obj2->SetBit(kCanDelete);
+      obj2->Fit("gaus","Q");
+      TF1 *fun2 = obj2->GetFunction("gaus");
+      fun2->SetLineColor(kYellow);
+      gPad->Modified();
+      gPad->Update();      
+      TPaveStats *st = (TPaveStats*)obj2->GetListOfFunctions()->FindObject("stats");
+      st->SetY1NDC(0.55);
+      st->SetY2NDC(0.89);
+      st->SetX1NDC(0.65);
+      st->SetX2NDC(0.99);
+      gPad->Modified();
+      gPad->Update();      
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist(obj2);
+      obj2->SetStats(1);
+      
+      //
+      // Display the outliers as dead and noisy pixels
+      //
+      DisplayOutliers(obj2,"low-ampl.","high-ampl.");
+      TLatex flattex;
+      flattex.SetTextSize(0.07);
+      const Double_t minl = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+      const Double_t maxl = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+      flattex.DrawLatex(minl+0.015*(maxl-minl),obj2->GetBinContent(obj2->GetMaximumBin())/1.35,
+                        Form("Flatfield precision: %4.2f%%",
+                             fun2->GetParameter(2)/fun2->GetParameter(1)*100.));
+      
+      //
+      // RMS per Charge
+      // 
+      
+      c1.cd(2);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj3=(MHCamera*)disp36.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      //      obj3->SetMinimum(0.);
+      // obj3->SetMaximum(fChargeMax);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj3);
+      obj3->SetStats(kFALSE);
+      //
+      // set reference lines
+      //
+      //        DisplayReferenceLines(obj3,0);
+      
+      c1.cd(5);
+      gPad->SetBorderMode(0);
+      obj3->SetPrettyPalette();
+      obj3->Draw();
+      
+      c1.cd(8);
+      gPad->SetBorderMode(0);
+      if (geomcam.InheritsFrom("MGeomCamMagic"))
+        DisplayDoubleProject(&disp36, "dead", "noisy");
+      
+      //
+      // PHOTO ELECTRONS
+      // 
+      
+      c1.cd(3);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj4=(MHCamera*)disp5.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      // obj3->SetMinimum(fChargeMin);
+      // obj3->SetMaximum(fChargeMax);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj4);
+      obj4->SetStats(kFALSE);
+      //
+      // set reference lines
+      //
+      //        DisplayReferenceLines(obj3,0);
+      
+      c1.cd(6);
+      gPad->SetBorderMode(0);
+      obj4->SetPrettyPalette();
+      obj4->Draw();
+      
+      c1.cd(9);
+      gPad->SetBorderMode(0);
+      if (geomcam.InheritsFrom("MGeomCamMagic"))
+        DisplayDoubleProject(&disp5, "dead", "noisy");
+      
+      //
+      // CONVERSION FACTORS
+      // 
+      TCanvas &c2 = fDisplay->AddTab("Conversion");
+      c2.Divide(3,3);
+      
+      c2.cd(1);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj5=(MHCamera*)disp6.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      obj5->SetMinimum(fConvFADC2PheMin);
+      obj5->SetMaximum(fConvFADC2PheMax);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj5);
+      obj5->SetStats(kFALSE);
+      //
+      // set reference lines
+      //
+      DisplayReferenceLines(obj5,2);
+      
+      c2.cd(4);
+      gPad->SetBorderMode(0);
+      obj5->SetPrettyPalette();
+      obj5->Draw();
+      
+      c2.cd(7);
+      gPad->SetBorderMode(0);
+      if (geomcam.InheritsFrom("MGeomCamMagic"))
+        DisplayDoubleProject(&disp6, "noisy", "dead");
+      
+      //
+      // QUANTUM EFFICIENCY
+      //
+      c2.cd(2);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj6=(MHCamera*)disp8.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      obj6->SetMinimum(fQEMin);
+      obj6->SetMaximum(fQEMax);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj6);
+      obj6->SetStats(kFALSE);
+      //
+      // set reference lines
+      //
+      DisplayReferenceLines(obj6,0);
+      
+      c2.cd(5);
+      gPad->SetBorderMode(0);
+      obj6->SetPrettyPalette();
+      obj6->Draw();
+      
+      c2.cd(8);
+      gPad->SetBorderMode(0);
+      if (geomcam.InheritsFrom("MGeomCamMagic"))
+        DisplayDoubleProject(&disp8, "noisy", "dead");
+      
+      //
+      // CONVERSION FADC TO PHOTONS
+      // 
+      
+      c2.cd(3);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj7=(MHCamera*)disp35.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      obj7->SetMinimum(fConvFADC2PhotMin);
+      obj7->SetMaximum(fConvFADC2PhotMax);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj7);
+      obj7->SetStats(kFALSE);
+      //
+      // set reference lines
+      //
+      DisplayReferenceLines(obj7,1);
+      
+      c2.cd(6);
+      gPad->SetBorderMode(0);
+      obj7->SetPrettyPalette();
+      obj7->Draw();
+      c2.cd(9);
+      gPad->SetBorderMode(0);
+      if (geomcam.InheritsFrom("MGeomCamMagic"))
+        DisplayDoubleProject(&disp35, "noisy", "dead");
+
+      //
+      // ARRIVAL TIMES
+      // 
+      TCanvas &c3 = fDisplay->AddTab("AbsTimes");
+      c3.Divide(2,3);
+      
+      c3.cd(1);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj10=(MHCamera*)disp28.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      obj10->SetMinimum(fArrivalTimeMin);
+      obj10->SetMaximum(fArrivalTimeMax);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj10);
+      obj10->SetStats(kFALSE);
+      //
+      // set reference lines
+      //
+      DisplayReferenceLines(obj10,3);
+      
+      c3.cd(3);
+      gPad->SetBorderMode(0);
+      obj10->SetPrettyPalette();
+      obj10->Draw();
+      
+      c3.cd(5);
+      gPad->SetBorderMode(0);
+      if (geomcam.InheritsFrom("MGeomCamMagic"))
+        DisplayDoubleProject(&disp28, "early", "late");
+
+      //
+      // ARRIVAL TIMES JITTER
+      // 
+      c3.cd(2);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj11=(MHCamera*)disp29.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      //      obj11->SetMinimum(fArrivalTimeMin);
+      //      obj11->SetMaximum(fArrivalTimeMax);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj11);
+      obj11->SetStats(kFALSE);
+      //
+      // set reference lines
+      //
+      DisplayReferenceLines(obj11,4);
+      
+      c3.cd(4);
+      gPad->SetBorderMode(0);
+      obj11->SetPrettyPalette();
+      obj11->Draw();
+      
+      c3.cd(6);
+      gPad->SetBorderMode(0);
+      if (geomcam.InheritsFrom("MGeomCamMagic"))
+        DisplayDoubleProject(&disp29, "", "jittering");
+
+      //
+      // UNSUITABLE PIXELS
+      //
+      TCanvas &c4 = fDisplay->AddTab("Defect");
+      c4.Divide(2,2);
+      
+      c4.cd(1);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj8=(MHCamera*)disp24.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      const Double_t max = 11.;
+      obj8->SetMinimum(0.);
+      obj8->SetMaximum(11.);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj8);
+      obj8->SetStats(kFALSE);
+
+      gStyle->SetPalette(1);
+      const Int_t numcol = gStyle->GetNumberOfColors()-3;
+      
+      TPaveText *pave = new TPaveText(0.0,0.0,0.99,0.99);
+      pave->SetBit(kCanDelete);
+      pave->ConvertNDCtoPad();
+      pave->SetTextSize(0.05);
+      pave->AddText("  ");
+      TText *t1 = pave->AddText(Form("Signal smaller 3 Pedestal RMS:                 %3i pixels",
+                                       CountBadPixels(&disp24,1)));
+      t1->SetTextColor(gStyle->GetColorPalette(Int_t(1./max*numcol + 1.)));
+      t1->SetTextAlign(12);
+      TText *t2 = pave->AddText(Form("%s%3i%s","Signal Rel. error too large:                          ",
+                                       CountBadPixels(&disp24,2)," pixels"));
+      t2->SetTextColor(gStyle->GetColorPalette(Int_t(2./max*numcol + 1.)));
+      t2->SetTextAlign(12);
+      TText *t4 = pave->AddText(Form("Low Gain Saturation:                                   %3i pixels",
+                                       CountBadPixels(&disp24,3)));
+      t4->SetTextColor(gStyle->GetColorPalette(Int_t(3./max*numcol + 1.)));
+      t4->SetTextAlign(12);
+      TText *t5 = pave->AddText(Form("Mean Arr. Time In First Extraction Bin:      %3i pixels",
+                                       CountBadPixels(&disp24,4)));
+      t5->SetTextColor(gStyle->GetColorPalette(Int_t(4./max*numcol + 1.)));
+      t5->SetTextAlign(12);
+      TText *t6 = pave->AddText(Form("Mean Arr. Time In Last 2 Extraction Bins: %3i pixels",
+                                       CountBadPixels(&disp24,5)));
+      t6->SetTextColor(gStyle->GetColorPalette(Int_t(5./max*numcol + 1.)));
+      t6->SetTextAlign(12);
+      TText *t9 = pave->AddText(Form("Deviating Number of Photons:                    %3i pixels",
+                                       CountBadPixels(&disp24,6)));
+      t9->SetTextColor(gStyle->GetColorPalette(Int_t(6./max*numcol + 1.)));
+      t9->SetTextAlign(12);
+      TText *t10= pave->AddText(Form("High-Gain Histogram Overflow:                  %3i pixels",
+                                       CountBadPixels(&disp24,7 )));
+      t10->SetTextColor(gStyle->GetColorPalette(Int_t(7./max*numcol + 1.)));
+      t10->SetTextAlign(12);
+      TText *t11= pave->AddText(Form("Low-Gain Histogram Overflow:                   %3i pixels",
+                                       CountBadPixels(&disp24,8 )));
+      t11->SetTextColor(gStyle->GetColorPalette(Int_t(8./max*numcol + 1.)));
+      t11->SetTextAlign(12);
+      TText *t12= pave->AddText(Form("Previously Excluded:                                    %3i pixels",
+                                       CountBadPixels(&disp24,9)));
+      t12->SetTextColor(gStyle->GetColorPalette(Int_t(9./max*numcol + 1.)));
+      t12->SetTextAlign(12);
+      pave->Draw();
+
+      c4.cd(3);
+      gPad->SetBorderMode(0);
+      obj8->Draw();
+      obj8->SetPrettyPalette();
+
+      //
+      // UNRELIABLE PIXELS
+      // 
+      
+      c4.cd(2);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      MHCamera *obj9=(MHCamera*)disp25.DrawCopy("hist");
+      //
+      // for the datacheck, fix the ranges!!
+      //
+      const Double_t max2 = 8.;
+      obj9->SetMinimum(0.);
+      obj9->SetMaximum(max2);
+      //
+      // Set the datacheck sizes:
+      //
+      FixDataCheckHist((TH1D*)obj9);
+      obj9->SetStats(kFALSE);
+
+      gStyle->SetPalette(1);
+      
+      TPaveText *pave2 = new TPaveText(0.0,0.0,0.99,0.99);
+      pave2->SetBit(kCanDelete);
+      pave2->ConvertNDCtoPad();
+      pave2->SetTextSize(0.05);
+      pave2->AddText("  ");
+      TText *t3 = pave2->AddText(Form("Signal Sigma smaller Pedestal RMS:      %3i pixels",
+                                       CountBadPixels(&disp25,1)));
+      t3->SetTextColor(gStyle->GetColorPalette(Int_t(1./max*numcol + 1.)));
+      t3->SetTextAlign(12);
+
+      TText *t7 = pave2->AddText(Form("Deviating Number of Photo-electrons:     %3i pixels",
+                                       CountBadPixels(&disp25,2)));
+      t7->SetTextColor(gStyle->GetColorPalette(Int_t(2./max*numcol + 1.)));
+      t7->SetTextAlign(12);
+
+      TText *tt1 = pave2->AddText(Form("High Gain Signals could not be fitted:   %3i pixels",
+                                       CountBadPixels(&disp25,3)));
+      tt1->SetTextColor(gStyle->GetColorPalette(Int_t(3./max2*numcol + 1.)));
+      tt1->SetTextAlign(12);
+      TText *tt2 = pave2->AddText(Form("Low  Gain Signals could not be fitted:   %3i pixels",
+                                       CountBadPixels(&disp25,4)));
+      tt2->SetTextColor(gStyle->GetColorPalette(Int_t(4./max2*numcol + 1.)));
+      tt2->SetTextAlign(12);
+      TText *tt3 = pave2->AddText(Form("Relative Arr. Times could not be fitted:  %3i pixels",
+                                       CountBadPixels(&disp25,5)));
+      tt3->SetTextColor(gStyle->GetColorPalette(Int_t(5./max2*numcol + 1.)));
+      tt3->SetTextAlign(12);
+      TText *tt4 = pave2->AddText(Form("High Gain Signals Oscillation:                %3i pixels",
+                                       CountBadPixels(&disp25,6)));
+      tt4->SetTextColor(gStyle->GetColorPalette(Int_t(6./max2*numcol + 1.)));
+      tt4->SetTextAlign(12);
+      TText *tt5 = pave2->AddText(Form("Low  Gain Signals Oscillation:                %3i pixels",
+                                       CountBadPixels(&disp25,7)));
+      tt5->SetTextColor(gStyle->GetColorPalette(Int_t(7./max2*numcol + 1.)));
+      tt5->SetTextAlign(12); 
+      TText *tt6 = pave2->AddText(Form("Relative Arr. Times Oscillation:               %3i pixels",
+                                       CountBadPixels(&disp25,8)));
+      tt6->SetTextColor(gStyle->GetColorPalette(Int_t(8./max2*numcol + 1.)));
+      tt6->SetTextAlign(12);
+      TText *tt8 = pave2->AddText(Form("Deviating global F-Factor:                        %3i pixels",
+                                       CountBadPixels(&disp25,9)));
+      tt8->SetTextColor(gStyle->GetColorPalette(Int_t(9./max2*numcol + 1.)));
+      tt8->SetTextAlign(12);
+      pave2->Draw();
+
+      c4.cd(4);
+      gPad->SetBorderMode(0);
+      obj9->SetPrettyPalette();
+      obj9->Draw();
+
+      if (IsRelTimes())
+        {
+          TCanvas &c5 = fDisplay->AddTab("RelTimes");
+          c5.Divide(2,3);
+          
+          //
+          // MEAN REL. ARR. TIMES
+          //
+          c5.cd(1);
+          gPad->SetBorderMode(0);
+          gPad->SetTicks();
+          MHCamera *obj10=(MHCamera*)disp30.DrawCopy("hist");
+          //
+          // for the datacheck, fix the ranges!!
+          //
+          obj10->SetMinimum(fTimeOffsetMin);
+          obj10->SetMaximum(fTimeOffsetMax);
+          //
+          // Set the datacheck sizes:
+          //
+          FixDataCheckHist((TH1D*)obj10);
+          obj10->SetStats(kFALSE);
+          //
+          // set reference lines
+          //
+          DisplayReferenceLines(obj10,5);
+      
+          c5.cd(3);
+          gPad->SetBorderMode(0);
+          obj10->SetPrettyPalette();
+          obj10->Draw();
+      
+          c5.cd(5);
+          gPad->SetBorderMode(0);
+          if (geomcam.InheritsFrom("MGeomCamMagic"))
+            DisplayDoubleProject(&disp30, "early", "late");
+          
+          //
+          // JITTER Rel. Arr. Times
+          //
+          c5.cd(2);
+          gPad->SetBorderMode(0);
+          gPad->SetTicks();
+          MHCamera *obj11=(MHCamera*)disp31.DrawCopy("hist");
+          //
+          // for the datacheck, fix the ranges!!
+          //
+          obj11->SetMinimum(fTimeResolutionMin);
+          obj11->SetMaximum(fTimeResolutionMax);
+          //
+          // Set the datacheck sizes:
+          //
+          FixDataCheckHist((TH1D*)obj11);
+          obj11->SetStats(kFALSE);
+          //
+          // set reference lines
+          //
+          DisplayReferenceLines(obj11,6);
+          
+          c5.cd(4);
+          gPad->SetBorderMode(0);
+          obj11->SetPrettyPalette();
+          obj11->Draw();
+          
+          c5.cd(6);
+          gPad->SetBorderMode(0);
+          if (geomcam.InheritsFrom("MGeomCamMagic"))
+            DisplayDoubleProject(&disp31, "too stable", "jittering");
+          
+        }
+      return;
+    }
+    
+    if (fDisplayType == kNormalDisplay)
+      {
+        
+        // Charges
+        TCanvas &c11 = fDisplay->AddTab("FitCharge");
+        c11.Divide(2, 4);
+        
+        disp1.CamDraw(c11, 1, 2, 5, 1);
+        disp2.CamDraw(c11, 2, 2, 5, 1);
+        
+        // Reduced Sigmas
+        TCanvas &c12 = fDisplay->AddTab("RedSigma");
+        c12.Divide(2,4);
+        
+        disp3.CamDraw(c12, 1, 2, 5, 1);
+        disp4.CamDraw(c12, 2, 2, 5, 1);
+        
+        //  F-Factor
+        TCanvas &c13 = fDisplay->AddTab("Phe's");
+        c13.Divide(3,4);
+        
+        disp5.CamDraw(c13, 1, 3, 5, 1);
+        disp6.CamDraw(c13, 2, 3, 5, 1);
+        disp7.CamDraw(c13, 3, 3, 5, 1);
+        
+        // QE's
+        TCanvas &c14 = fDisplay->AddTab("QE's");
+        c14.Divide(4,4);
+        
+        disp8.CamDraw(c14, 1, 4, 5, 1);
+        disp9.CamDraw(c14, 2, 4, 5, 1);
+        disp10.CamDraw(c14, 3, 4, 5, 1);
+        disp11.CamDraw(c14, 4, 4, 5, 1);
+        
+        // Defects
+        TCanvas &c15 = fDisplay->AddTab("Defect");
+        //      c15.Divide(5,2);
+        c15.Divide(4,2);
+        
+        /*
+        disp23.CamDraw(c15, 1, 5, 0);
+        disp24.CamDraw(c15, 2, 5, 0);
+        disp25.CamDraw(c15, 3, 5, 0);
+        disp26.CamDraw(c15, 4, 5, 0);
+        disp27.CamDraw(c15, 5, 5, 0);
+        */
+        disp24.CamDraw(c15, 1, 4, 0);
+        disp25.CamDraw(c15, 2, 4, 0);
+        disp26.CamDraw(c15, 3, 4, 0);
+        disp27.CamDraw(c15, 4, 4, 0);
+        
+        // Abs. Times
+        TCanvas &c16 = fDisplay->AddTab("AbsTimes");
+        c16.Divide(2,3);
+        
+        disp28.CamDraw(c16, 1, 2, 5);
+        disp29.CamDraw(c16, 2, 2, 5);
+
+        if (IsRelTimes())
+        {
+            // Rel. Times
+            TCanvas &c17 = fDisplay->AddTab("RelTimes");
+            c17.Divide(2,4);
+
+            disp30.CamDraw(c17, 1, 2, 5, 1);
+            disp31.CamDraw(c17, 2, 2, 5, 1);
+        }
+        
+        return;
+    }
+    
+    if (fDisplayType == kFullDisplay)
+    {
+        MHCalibrationCam *cam = (MHCalibrationCam*)plist.FindObject("MHCalibrationChargeCam");
+
+        for (Int_t sector=1;sector<cam->GetAverageSectors();sector++)
+        {
+            cam->GetAverageHiGainSector(sector).DrawClone("all");
+            cam->GetAverageLoGainSector(sector).DrawClone("all");
+        }
+
+        // Charges
+        TCanvas &c21 = fDisplay->AddTab("FitCharge");
+        c21.Divide(2, 4);
+
+        disp1.CamDraw(c21, 1, 2, 2, 1);
+        disp2.CamDraw(c21, 2, 2, 2, 1);
+
+        // Reduced Sigmas
+        TCanvas &c23 = fDisplay->AddTab("RedSigma");
+        c23.Divide(2,4);
+
+        disp3.CamDraw(c23, 1, 2, 2, 1);
+        disp4.CamDraw(c23, 2, 2, 2, 1);
+
+        //  F-Factor
+        TCanvas &c24 = fDisplay->AddTab("Phe's");
+        c24.Divide(3,5);
+        
+        disp5.CamDraw(c24, 1, 3, 2, 1, 1);
+        disp6.CamDraw(c24, 2, 3, 2, 1, 1);
+        disp7.CamDraw(c24, 3, 3, 2, 1, 1);
+        
+        // QE's
+        TCanvas &c25 = fDisplay->AddTab("QE's");
+        c25.Divide(4,5);
+        
+        disp8.CamDraw(c25, 1, 4, 2, 1, 1);
+        disp9.CamDraw(c25, 2, 4, 2, 1, 1);
+        disp10.CamDraw(c25, 3, 4, 2, 1, 1);
+        disp11.CamDraw(c25, 4, 4, 2, 1, 1);
+        
+        // Validity
+        TCanvas &c26 = fDisplay->AddTab("Valid");
+        c26.Divide(4,2);
+        
+        disp12.CamDraw(c26, 1, 4, 0);
+        disp13.CamDraw(c26, 2, 4, 0);
+        disp14.CamDraw(c26, 3, 4, 0);
+        disp15.CamDraw(c26, 4, 4, 0);
+        
+        // Other info
+        TCanvas &c27 = fDisplay->AddTab("HiLoGain");
+        c27.Divide(3,3);
+        
+        disp16.CamDraw(c27, 1, 3, 0);
+        disp17.CamDraw(c27, 2, 3, 1);
+        disp18.CamDraw(c27, 3, 3, 1);
+        
+        // Pickup
+        TCanvas &c28 = fDisplay->AddTab("Pickup");
+        c28.Divide(4,2);
+        
+        disp19.CamDraw(c28, 1, 4, 0);
+        disp20.CamDraw(c28, 2, 4, 0);
+        disp21.CamDraw(c28, 3, 4, 0);
+        disp22.CamDraw(c28, 4, 4, 0);
+        
+        // Defects
+        TCanvas &c29 = fDisplay->AddTab("Defect");
+        //      c29.Divide(5,2);
+        c29.Divide(4,2);
+        
+        disp24.CamDraw(c29, 1, 4, 0);
+        disp25.CamDraw(c29, 2, 4, 0);
+        disp26.CamDraw(c29, 3, 4, 0);
+        disp27.CamDraw(c29, 4, 4, 0);
+        
+        // Abs. Times
+        TCanvas &c30 = fDisplay->AddTab("AbsTimes");
+        c30.Divide(2,3);
+        
+        disp28.CamDraw(c30, 1, 2, 2);
+        disp29.CamDraw(c30, 2, 2, 1);
+
+        if (IsRelTimes())
+        {
+            // Rel. Times
+            TCanvas &c31 = fDisplay->AddTab("RelTimes");
+            c31.Divide(3,5);
+            
+            disp30.CamDraw(c31, 1, 3, 2, 1, 1);
+            disp31.CamDraw(c31, 2, 3, 2, 1, 1);
+            disp32.CamDraw(c31, 3, 3, 4, 1, 1);
+
+            // Time Defects
+            TCanvas &c32 = fDisplay->AddTab("DefTime");
+            c32.Divide(2,2);
+            
+            disp33.CamDraw(c32, 1, 2, 0);
+            disp34.CamDraw(c32, 2, 2, 0);
+
+            MHCalibrationCam *cam = (MHCalibrationCam*)plist.FindObject("MHCalibrationRelTimeCam");
+            
+            for (Int_t sector=1;sector<cam->GetAverageSectors();sector++)
+            {
+                cam->GetAverageHiGainSector(sector).DrawClone("fourierevents");
+                cam->GetAverageLoGainSector(sector).DrawClone("fourierevents");
+            }
+
+        }
+
+        return;
+    }
+}
+    
+
+void  MJCalibration::DisplayReferenceLines(MHCamera *cam, const Int_t what) const
+{
+
+  const MGeomCam *geom = cam->GetGeometry();
+
+  Double_t x = geom->InheritsFrom("MGeomCamMagic") ? 397 : cam->GetNbinsX() ;
+
+  TLine line;
+  line.SetLineStyle(kDashed);
+  line.SetLineWidth(3);
+  line.SetLineColor(kBlue);
+  
+  TLine *l1 = NULL;
+
+  switch (what)
+    {
+    case 0:
+      l1 = line.DrawLine(0, fRefQEInner, x, fRefQEInner);      
+      break;
+    case  1:
+      l1 = line.DrawLine(0, fRefConvFADC2PhotInner, x, fRefConvFADC2PhotInner);      
+      break;
+    case  2:
+      l1 = line.DrawLine(0, fRefConvFADC2PheInner, x, fRefConvFADC2PheInner );
+      break;
+    case  3:
+      l1 = line.DrawLine(0, fRefArrivalTimeInner, x, fRefArrivalTimeInner );
+      break;
+    case  4:
+      l1 = line.DrawLine(0, fRefArrivalTimeRmsInner, x, fRefArrivalTimeRmsInner );
+      break;
+    case 5:
+      l1 = line.DrawLine(0, fRefTimeOffsetInner, x, fRefTimeOffsetInner );
+      break;
+    case 6:
+      l1 = line.DrawLine(0, fRefTimeResolutionInner, x, fRefTimeResolutionInner );
+      break;
+    default:
+      break;
+    }
+
+  if (geom->InheritsFrom("MGeomCamMagic"))
+    {
+      const Double_t x2 = cam->GetNbinsX();
+
+      switch (what)
+        {
+        case 0:
+          line.DrawLine(x2, fRefQEOuter, 398, fRefQEOuter);      
+          break;
+        case 1:
+          line.DrawLine(x2, fRefConvFADC2PhotOuter, 398, fRefConvFADC2PhotOuter );      
+          break;
+        case 2:
+          line.DrawLine(x2, fRefConvFADC2PheOuter, 398, fRefConvFADC2PheOuter);
+          break;
+        case 3:
+          line.DrawLine(x2, fRefArrivalTimeOuter, 398, fRefArrivalTimeOuter);
+          break;
+        case 4:
+          line.DrawLine(x2, fRefArrivalTimeRmsOuter, 398, fRefArrivalTimeRmsOuter);
+          break;
+        case 5:
+          line.DrawLine(x2, fRefTimeOffsetOuter, 398, fRefTimeOffsetOuter);
+          break;
+        case 6:
+          line.DrawLine(x2, fRefTimeResolutionOuter, 398, fRefTimeResolutionOuter);
+          break;
+	default:
+	  break;
+        }
+    }
+  
+  TLegend *leg = new TLegend(0.6,0.85,0.9 ,0.95);
+  leg->SetBit(kCanDelete);
+  leg->AddEntry(l1, "Reference","l");
+  leg->Draw();
+}
+
+void  MJCalibration::DisplayOutliers(TH1D *hist, const char* whatsmall, const char* whatbig) const
+{
+
+  const Int_t kNotDraw = 1<<9;
+  TF1 *f = hist->GetFunction("gaus");
+  f->ResetBit(kNotDraw);
+
+  const Float_t mean  = f->GetParameter(1);
+  const Float_t lolim = mean - 4.0*f->GetParameter(2);
+  const Float_t uplim = mean + 4.0*f->GetParameter(2);
+  const Stat_t  dead  = hist->Integral(0,hist->FindBin(lolim)-1);
+  const Stat_t  noisy = hist->Integral(hist->FindBin(uplim)+1,hist->GetNbinsX()+1);
+
+  const Double_t max = hist->GetBinContent(hist->GetMaximumBin());                                           
+  
+  const Double_t minl = hist->GetBinCenter(hist->GetXaxis()->GetFirst());
+  const Double_t maxl = hist->GetBinCenter(hist->GetXaxis()->GetLast());
+
+  TLatex deadtex;
+  deadtex.SetTextSize(0.07);
+  deadtex.DrawLatex(minl+0.015*(maxl-minl),max/1.1,
+                    Form("%3i %s pixels",(Int_t)dead,whatsmall));
+
+  TLatex noisytex;
+  noisytex.SetTextSize(0.07);
+  noisytex.DrawLatex(minl+0.015*(maxl-minl),max/1.2,
+                     Form("%3i %s pixels",(Int_t)noisy,whatbig));
+
+}
+
+void MJCalibration::FixDataCheckHist(TH1D *hist) const 
+{
+
+    hist->SetDirectory(NULL);
+
+    //
+    // set the labels bigger
+    //
+    TAxis *xaxe = hist->GetXaxis();
+    TAxis *yaxe = hist->GetYaxis();
+    
+    xaxe->CenterTitle();
+    yaxe->CenterTitle();    
+    xaxe->SetTitleSize(0.06);
+    yaxe->SetTitleSize(0.06);    
+    xaxe->SetTitleOffset(0.8);
+    yaxe->SetTitleOffset(0.85);    
+    xaxe->SetLabelSize(0.05);
+    yaxe->SetLabelSize(0.05);    
+
+}
+
+const Int_t MJCalibration::CountBadPixels ( MHCamera *cam , const Int_t what ) const
+{
+
+  Int_t cnt = 0;
+
+  for (UInt_t pix=0; pix<cam->GetNumPixels();pix++)
+    if ((Int_t)cam->GetPixContent(pix) == what)
+      cnt++;
+
+  return cnt;
+}
+
+// --------------------------------------------------------------------------
+//
+// Retrieve the output file written by WriteResult()
+// 
+const char* MJCalibration::GetOutputFile() const
+{
+    const TString name(GetOutputFileName());
+    if (name.IsNull())
+        return "";
+
+    return Form("%s/%s", fPathOut.Data(), name.Data());
+}
+
+const char* MJCalibration::GetOutputFileName() const
+{
+
+  if (fSequence.IsValid())
+    return Form("calib%08d.root", fSequence.GetSequence());
+  if (!fRuns)
+    return "";
+  
+  return Form("%s-F1.root", (const char*)fRuns->GetRunsAsFileName());
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the following values from resource file:
+//
+//   ConvFADC2PheMin
+//   ConvFADC2PheMax
+//   ConvFADC2PhotMin
+//   ConvFADC2PhotMax
+//
+//   QEMin
+//   QEMax
+//
+//   ArrivalTimeMin
+//   ArrivalTimeMax
+//
+//   TimeOffsetMin
+//   TimeOffsetMax
+//   TimeResolutionMin
+//   TimeResolutionMax
+//
+//   RefConvFADC2PheInner
+//   RefConvFADC2PheOuter
+//   RefConvFADC2PhotInner
+//   RefConvFADC2PhotOuter
+//
+//   RefQEInner
+//   RefQEOuter
+//
+//   RefArrivalTimeInner
+//   RefArrivalTimeOuter
+//   RefArrivalTimeRmsInner
+//   RefArrivalTimeRmsOuter
+//
+//   RefTimeOffsetInner
+//   RefTimeOffsetOuter
+//   RefTimeResolutionInner
+//   RefTimeResolutionOuter
+//
+void MJCalibration::ReadReferenceFile()
+{
+    TEnv refenv(fReferenceFile);
+    
+    fConvFADC2PheMin        = refenv.GetValue("ConvFADC2PheMin",fConvFADC2PheMin);
+    fConvFADC2PheMax        = refenv.GetValue("ConvFADC2PheMax",fConvFADC2PheMax);
+    fConvFADC2PhotMin       = refenv.GetValue("ConvFADC2PhotMin",fConvFADC2PhotMin);
+    fConvFADC2PhotMax       = refenv.GetValue("ConvFADC2PhotMax",fConvFADC2PhotMax);
+    fQEMin                  = refenv.GetValue("QEMin",fQEMin);
+    fQEMax                  = refenv.GetValue("QEMax",fQEMax);
+    fArrivalTimeMin         = refenv.GetValue("ArrivalTimeMin",fArrivalTimeMin);
+    fArrivalTimeMax         = refenv.GetValue("ArrivalTimeMax",fArrivalTimeMax);
+    fTimeOffsetMin          = refenv.GetValue("TimeOffsetMin",fTimeOffsetMin);
+    fTimeOffsetMax          = refenv.GetValue("TimeOffsetMax",fTimeOffsetMax);
+    fTimeResolutionMin      = refenv.GetValue("TimeResolutionMin",fTimeResolutionMin);
+    fTimeResolutionMax      = refenv.GetValue("TimeResolutionMax",fTimeResolutionMax);
+			     		                        
+    fRefConvFADC2PheInner   = refenv.GetValue("RefConvFADC2PheInner",fRefConvFADC2PheInner);
+    fRefConvFADC2PheOuter   = refenv.GetValue("RefConvFADC2PheOuter",fRefConvFADC2PheOuter);
+    fRefConvFADC2PhotInner  = refenv.GetValue("RefConvFADC2PhotInner",fRefConvFADC2PhotInner);
+    fRefConvFADC2PhotOuter  = refenv.GetValue("RefConvFADC2PhotOuter",fRefConvFADC2PhotOuter);
+    fRefQEInner             = refenv.GetValue("RefQEInner",fRefQEInner);
+    fRefQEOuter             = refenv.GetValue("RefQEOuter",fRefQEOuter);
+    fRefArrivalTimeInner    = refenv.GetValue("RefArrivalTimeInner",fRefArrivalTimeInner);
+    fRefArrivalTimeOuter    = refenv.GetValue("RefArrivalTimeOuter",fRefArrivalTimeOuter);
+    fRefArrivalTimeRmsInner = refenv.GetValue("RefArrivalTimeRmsInner",fRefArrivalTimeRmsInner);
+    fRefArrivalTimeRmsOuter = refenv.GetValue("RefArrivalTimeRmsOuter",fRefArrivalTimeRmsOuter);
+    fRefTimeOffsetInner     = refenv.GetValue("RefTimeOffsetInner",fRefTimeOffsetInner);
+    fRefTimeOffsetOuter     = refenv.GetValue("RefTimeOffsetOuter",fRefTimeOffsetOuter);
+    fRefTimeResolutionInner = refenv.GetValue("RefTimeResolutionInner",fRefTimeResolutionInner);
+    fRefTimeResolutionOuter = refenv.GetValue("RefTimeResolutionOuter",fRefTimeResolutionOuter);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the following values from resource file:
+//
+//   MCalibrationHiLoCam
+//
+Bool_t MJCalibration::ReadHiLoCalibFile()
+{
+
+  if (!fIsHiLoCalibration || IsUseMC())
+    return kTRUE;
+
+  TFile file(fHiLoCalibFile,"READ");
+  if (!file.IsOpen())
+  {
+    *fLog << err << "ERROR - Couldn't open hi-lo intercalibration file " << fHiLoCalibFile << " for reading..." << endl;
+    return kFALSE;
+  }
+
+  MCalibrationHiLoCam hilocam;
+  
+  *fLog << all << "Initializing High gain vs. Low gain intercalibration from " << fHiLoCalibFile << endl;
+  *fLog << all << endl;
+
+  if (hilocam.Read()<=0)
+  {
+      *fLog << err << "Unable to read MCalibrationHiLoCam from " << fHiLoCalibFile << endl;
+      return kFALSE;
+  }
+
+  if (hilocam.GetSize() < 1)
+  {
+      *fLog << err << "MCalibationHiLoCam is un-initialized in file " << fHiLoCalibFile << endl;
+      return kFALSE;
+  }
+
+  if (fCalibrationCam.GetSize() < 1)
+    fCalibrationCam.InitSize(hilocam.GetSize());
+  
+  if (fBadPixels.GetSize() < 1)
+    fBadPixels.InitSize(hilocam.GetSize());
+  
+  if (fCalibrationCam.GetSize() != hilocam.GetSize())
+  {
+      *fLog << err << "Size mismatch MCalibationHiLoCam and MCalibrationChargeCam " << endl;
+      return kFALSE;
+  }
+
+  for (Int_t i=0;i<hilocam.GetSize();i++)
+    {
+      const MCalibrationHiLoPix &pix = (MCalibrationHiLoPix&)hilocam[i];
+
+      const Float_t ratio = pix.GetHiLoChargeRatio();
+      const Float_t sigma = pix.GetHiLoChargeRatioSigma();
+
+      if (ratio < 0.)
+        {
+          fBadPixels[i].SetUncalibrated(MBadPixelsPix::kConversionHiLoNotValid);
+          continue;
+        }
+      
+      MCalibrationChargePix &cpix = (MCalibrationChargePix&)fCalibrationCam[i];
+      
+      cpix.SetConversionHiLo(ratio);
+      cpix.SetConversionHiLoErr(sigma);      
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// MJCalibration allows to setup several option by a resource file:
+//   MJCalibration.Display: full, datacheck, normal
+//   MJCalibration.RelTimeCalibration: yes,no
+//   MJCalibration.DataCheck: yes,no
+//   MJCalibration.Debug: yes,no
+//   MJCalibration.Intensity: yes,no
+//   MJCalibration.UseBlindPixel: yes,no
+//   MJCalibration.UsePINDiode: yes,no
+//   MJCalibration.Geometry: MGeomCamMagic, MGeomCamECO1000
+//
+// Name of a file containing reference values (see ReadReferenceFile)
+//   Prefix.ReferenceFile:    filename
+// (see ReadReferenceFile)
+//
+// For more details see the class description and the corresponding Getters
+// 
+Bool_t MJCalibration::CheckEnvLocal()
+{
+
+    TString dis = GetEnv("Display", "");
+    if (dis.BeginsWith("Full", TString::kIgnoreCase))
+        SetFullDisplay();
+    if (dis.BeginsWith("DataCheck", TString::kIgnoreCase))
+        SetDataCheckDisplay();
+    if (dis.BeginsWith("Normal", TString::kIgnoreCase))
+        SetNormalDisplay();
+
+    if (!MJCalib::CheckEnvLocal())
+        return kFALSE;
+    
+    SetRelTimeCalibration(GetEnv("RelTimeCalibration", IsRelTimes()));
+    SetIntensity(GetEnv("IntensityCalibration", IsIntensity()));
+    SetDebug(GetEnv("Debug", IsDebug()));
+
+    SetUseBlindPixel(GetEnv("UseBlindPixel", IsUseBlindPixel()));
+    SetUsePINDiode(GetEnv("UsePINDiode", IsUsePINDiode()));
+    SetGeometry(GetEnv("Geometry", fGeometry));
+
+    fReferenceFile = GetEnv("ReferenceFile",fReferenceFile.Data());
+    ReadReferenceFile();
+
+    fHiLoCalibFile = GetEnv("HiLoCalibFile",fHiLoCalibFile.Data());
+
+    return ReadHiLoCalibFile();
+}
+
+// --------------------------------------------------------------------------
+//
+// Call the ProcessFile(MPedestalCam)
+// 
+Bool_t MJCalibration::Process(MPedestalCam &pedcam)
+{
+    if (!ReadCalibrationCam())
+        return ProcessFile(pedcam);
+
+    return kTRUE;
+}
+
+void MJCalibration::InitBlindPixel(MExtractBlindPixel &blindext,
+                                   MHCalibrationChargeBlindCam &blindcam)
+{
+
+  Int_t run = fSequence.IsValid() ? 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)
+    {
+      MCalibrationBlindCamOneOldStyle blindresults;
+      if (IsIntensity())
+        blindresults.Copy(*fIntensBlindCam.GetCam());
+      else
+        blindresults.Copy(fCalibrationBlindCam);
+
+      blindext.SetExtractionType(MExtractBlindPixel::kIntegral);
+      blindext.SetExtractionType(MExtractBlindPixel::kFilter);
+      blindext.SetRange(10,19,0,6);
+      blindext.SetNSBFilterLimit(70);
+    }
+  else if (run < gkThirdBlindPixelInstallation)
+    {
+
+      MCalibrationBlindCamTwoNewStyle blindresults;
+
+      if (IsIntensity())
+        blindresults.Copy(*fIntensBlindCam.GetCam());
+      else
+        blindresults.Copy(fCalibrationBlindCam);
+
+      blindext.SetNumBlindPixels(blindresults.GetSize());
+      for (Int_t i=0;i<blindresults.GetSize();i++)
+        blindext.SetBlindPixelIdx(blindresults[i].GetPixId(),i);
+
+      blindext.SetExtractionType(MExtractBlindPixel::kAmplitude);
+      blindext.SetExtractionType(MExtractBlindPixel::kFilter);
+      blindext.SetRange(5,8,0,2);
+      blindext.SetNSBFilterLimit(38);
+      
+    }
+  else
+    {
+
+      MCalibrationBlindCamThreeNewStyle blindresults;
+
+      if (IsIntensity())
+        blindresults.Copy(*fIntensBlindCam.GetCam());
+      else
+        blindresults.Copy(fCalibrationBlindCam);
+
+      blindext.SetNumBlindPixels(blindresults.GetSize());
+
+      for (Int_t i=0;i<blindresults.GetSize();i++)
+        blindext.SetBlindPixelIdx(blindresults[i].GetPixId(),i);
+
+      blindext.SetExtractionType(MExtractBlindPixel::kAmplitude);
+      blindext.SetExtractionType(MExtractBlindPixel::kFilter);
+      blindext.SetDataType(MExtractBlindPixel::kRawEvt2);
+      blindext.SetRange(5,8,0,2);
+      blindext.SetNSBFilterLimit(38);
+      
+    }
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Execute the task list and the eventloop:
+//
+// - Check if there are fRuns, otherwise return
+// - Check the colour of the files in fRuns (FindColor()), otherwise return
+// - Check for consistency between run numbers and number of files
+// - Add fRuns to MReadMarsFile
+// - Put into MParList:
+//   1) MPedestalCam          (pedcam)
+//   2) MCalibrationQECam     (fQECam)
+//   3) MCalibrationChargeCam (fCalibrationCam)
+//   4) MCalibrationRelTimeCam (fRelTimeCam)   (only if flag IsRelTimes() is chosen)
+//   5) MBadPixelsCam         (fBadPixels)
+//   6) MCalibrationChargePINDiode
+//   7) MCalibrationBlindPix
+// - Put into the MTaskList:
+//   1)  MReadMarsFile
+//   2)  MBadPixelsMerge
+//   3)  MGeomApply
+//   4)  MExtractor
+//   5)  MExtractPINDiode
+//   6)  MExtractBlindPixel
+//   7)  MExtractTime (only if flag IsRelTimes() is chosen)
+//   8)  MContinue(MFCosmics)
+//   9)  MFillH("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode",   "FillPINDiode")
+//   10) MFillH("MHCalibrationChargeBlindCam", "MExtractedSignalBlindPixel", "FillBlindCam")
+//   11) MFillH("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillChargeCam")
+//   12) MFillH("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillRelTime")
+//   13) MCalibrationChargeCalc
+//   14) MFillH("MHCalibrationRelTimeCam",     "MArrivalTimeCam") (only if flag IsRelTimes() is chosen)
+//   15) MCalibrationRelTimeCalc
+// - Execute MEvtLoop
+// - DisplayResult()
+// - WriteResult()
+//
+Bool_t MJCalibration::ProcessFile(MPedestalCam &pedcam)
+{
+    if (!fSequence.IsValid())
+    {
+        if (!fRuns)
+        {
+            *fLog << err << "No Runs choosen... abort." << endl;
+            return kFALSE;
+        }
+
+        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());
+
+    *fLog << "Calculate MCalibrationCam from ";
+    if (fSequence.IsValid())
+        *fLog << "Sequence #" << fSequence.GetSequence() << endl;
+    else
+        *fLog << "Runs " << fRuns->GetRunsAsString() << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+    
+    if (!CheckEnv())
+      return kFALSE;
+
+    // --------------------------------------------------------------------------------
+
+    // Setup Tasklist
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    plist.AddToList(this); // take care of fDisplay!
+
+    MDirIter iter;
+    if (fSequence.IsValid())
+    {
+        const Int_t n0 = fSequence.SetupCalRuns(iter, fPathData, "C", IsUseRawData());
+        const Int_t n1 = fSequence.GetNumCalRuns();
+        if (n0==0)
+        {
+            *fLog << err << "ERROR - No input files of sequence found!" << endl;
+            return kFALSE;
+        }
+        if (n0!=n1)
+        {
+            *fLog << err << "ERROR - Number of files found (" 
+                  << n0 << ") doesn't match number of files in sequence (" 
+                  << n1 << ")" << endl;
+            if (fLog->GetDebugLevel()>4)
+            {
+                *fLog << dbg << "Files which are searched:" << endl;
+                iter.Print();
+            }
+            return kFALSE;
+        }
+    }
+
+    //
+    // Input containers
+    //
+    pedcam.SetName("MPedestalCam"); // MPedestalFundamental
+    plist.AddToList(&pedcam);
+    plist.AddToList(&fBadPixels);
+        
+    //
+    // Calibration Results containers
+    //
+    if (IsIntensity())
+    {
+        plist.AddToList(&fIntensQECam);
+        plist.AddToList(&fIntensCalibCam);
+        //        plist.AddToList(&fIntensCalibrationPINDiode);
+        plist.AddToList(&fIntensRelTimeCam);
+        plist.AddToList(&fIntensBadCam);
+        if (IsUseBlindPixel())
+            plist.AddToList(&fIntensBlindCam);
+    }
+    else
+    {
+        plist.AddToList(&fQECam);
+        plist.AddToList(&fCalibrationCam);
+        plist.AddToList(&fRelTimeCam);
+        if (IsUseBlindPixel())
+            plist.AddToList(&fCalibrationBlindCam);
+        if (IsUsePINDiode())
+            plist.AddToList(&fCalibrationPINDiode);
+    }
+
+    //
+    // Initialize two histogram containers which could be modified in this class
+    //
+    MHCalibrationRelTimeCam     reltimecam;
+    MHCalibrationChargeCam      chargecam;
+    MHCalibrationChargeBlindCam blindcam;
+    plist.AddToList(&chargecam);
+
+    if (IsUseBlindPixel())
+      plist.AddToList(&blindcam);
+    if (IsRelTimes())
+      plist.AddToList(&reltimecam);
+    //
+    // Data Reading tasks
+    //
+    MReadMarsFile read("Events");
+    MRawFileRead rawread(NULL);
+
+    if (IsUseRawData())
+    {
+        rawread.AddFiles(fSequence.IsValid() ? iter : *fRuns);
+        tlist.AddToList(&rawread);
+    }
+    else
+    {
+        read.DisableAutoScheme();
+        read.AddFiles(fSequence.IsValid() ? iter : *fRuns);
+        tlist.AddToList(&read);
+    }
+
+    //
+    // Other Tasks
+    //
+    MCalibrationPatternDecode decode;
+    MGeomApply               apply;
+    apply.SetGeometry(fGeometry);
+
+    MBadPixelsMerge          merge(&fBadPixels);
+    MExtractPINDiode         pinext;
+    MExtractBlindPixel       blindext;
+
+    if (IsUseBlindPixel())
+        InitBlindPixel(blindext, blindcam);
+
+    MExtractSlidingWindow    extract2;
+    MExtractTimeHighestIntegral timehigh;
+    MCalibrationChargeCalc   calcalc;
+    MCalibrationRelTimeCalc  timecalc;
+    calcalc.SetOutputFile("");
+    timecalc.SetOutputFile("");
+
+    if (!fSequence.IsValid())
+    {
+        calcalc.SetOutputPath(fPathOut);
+        calcalc.SetOutputFile(Form("%s-ChargeCalibStat.txt",(const char*)fRuns->GetRunsAsFileName()));
+        timecalc.SetOutputPath(fPathOut);
+        timecalc.SetOutputFile(Form("%s-ChargeCalibStat.txt",(const char*)fRuns->GetRunsAsFileName()));
+    }
+
+    if (IsDebug())
+    {
+        chargecam.SetDebug();
+        calcalc.SetDebug();
+    }
+
+    //
+    // Calibration histogramming
+    //
+    MFillH fillpin("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode",   "FillPINDiode");
+    MFillH fillbnd("MHCalibrationChargeBlindCam", "MExtractedSignalBlindPixel", "FillBlindCam");
+    MFillH fillcam("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillChargeCam");
+    MFillH filltme("MHCalibrationRelTimeCam",     "MArrivalTimeCam",            "FillRelTime");
+    fillpin.SetBit(MFillH::kDoNotDisplay);
+    fillbnd.SetBit(MFillH::kDoNotDisplay);
+    fillcam.SetBit(MFillH::kDoNotDisplay);
+    filltme.SetBit(MFillH::kDoNotDisplay);
+
+    //
+    // Set default extractors in case, none has been set...
+    //
+    if (!fExtractor)
+      fExtractor = &extract2;
+    if (!fTimeExtractor)
+      fTimeExtractor = &timehigh;
+
+    const Bool_t istimecharge = fExtractor->InheritsFrom("MExtractTimeAndCharge");
+    //
+    // Look if the extractor is a pure charge or also a time extractor
+    //
+    if (istimecharge)
+    {
+        if (fExtractorCam.GetSize() == pedcam.GetSize())
+            calcalc.SetPedestals(&fExtractorCam);
+        else
+        {
+            *fLog << err << GetDescriptor() << "ERROR - ";
+            *fLog << "Used Extractor derives from MExtractTimeAndCharge, " << endl;
+            *fLog << "but MExtractorCam size " << fExtractorCam.GetSize() << " ";
+            *fLog << "mismatch pedcam size " << pedcam.GetSize() << "! " << endl;
+            return kFALSE;
+        }
+    }
+
+    //
+    // Setup more tasks and tasklist
+    //
+    MTaskEnv taskenv("ExtractSignal");
+    taskenv.SetDefault(fExtractor);
+
+    tlist.AddToList(&decode);
+    tlist.AddToList(&merge);
+    tlist.AddToList(&apply);
+
+    MPedCalcPedRun           pedcalc;
+    pedcalc.SetExtractWindow(fExtractor->GetHiGainFirst(),TMath::Nint(fExtractor->GetNumHiGainSamples()));
+
+    if (IsIntensity())
+      tlist.AddToList(&pedcalc);
+
+    MCalibColorSet colorset;
+    tlist.AddToList(&colorset);
+
+    tlist.AddToList(&taskenv);
+    
+    if (IsUsePINDiode())
+      tlist.AddToList(&pinext);
+    if (IsUseBlindPixel())
+      tlist.AddToList(&blindext);
+
+    MTaskEnv taskenv2("ExtractTime");
+    if (!istimecharge)
+    {
+      taskenv2.SetDefault(fTimeExtractor);
+      
+      if (IsRelTimes())
+        tlist.AddToList(&taskenv2);
+    }
+    
+    //
+    // 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);
+
+    if (fColor == MCalibrationCam::kCT1)
+      tlist.AddToList(&cont);
+
+    MCalibColorSteer steer;
+    if (IsIntensity())
+      tlist.AddToList(&steer);
+
+    tlist.AddToList(&fillcam);
+
+    if (IsRelTimes())
+    {
+        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);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    if (!taskenv.GetTask() && !taskenv2.GetTask())
+    {
+        *fLog << err << "ERROR - Neither ExtractSignal nor ExtractTime initialized or both '<dummy>'." << endl;
+        return kFALSE;
+    }
+
+    if (!WriteTasks(taskenv.GetTask(), istimecharge ? 0 : taskenv2.GetTask()))
+        return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop())
+    {
+      DisplayResult(plist);
+      WriteResult(plist);
+      *fLog << err << GetDescriptor() << ": Failed." << endl;
+      return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    // --------------------------------------------------------------------------------
+
+    if (fIsPixelCheck)
+      {
+        MHCalibrationChargeCam *hcam = (MHCalibrationChargeCam*)plist.FindObject("MHCalibrationChargeCam");
+        MHCalibrationChargePix &pix1 = (MHCalibrationChargePix&)(*hcam)[fCheckedPixId];
+        pix1.DrawClone("");
+        
+        MHCalibrationChargePix &pix2 = (MHCalibrationChargePix&)(*hcam)(fCheckedPixId);
+        pix2.DrawClone("");
+        
+        if (IsRelTimes())
+          {
+            MHCalibrationRelTimeCam *hccam = (MHCalibrationRelTimeCam*)plist.FindObject("MHCalibrationRelTimeCam");
+            MHCalibrationPix &pix11 = (*hccam)[fCheckedPixId];
+            pix11.DrawClone("");
+            MHCalibrationPix &pix12 = (*hccam)(fCheckedPixId);
+            pix12.DrawClone("");
+          }
+      }
+    
+    if (!fCalibrationPINDiode.IsValid())
+      SetUsePINDiode(kFALSE);
+    
+    DisplayResult(plist);
+    
+    if (!WriteResult(plist))
+      return kFALSE;
+    
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the following containers from GetOutputFile()
+// - MCalibrationChargeCam
+// - MCalibrationQECam
+// - MBadPixelsCam
+//
+Bool_t MJCalibration::ReadCalibrationCam()
+{
+  
+  if (IsNoStorage())
+    return kFALSE;
+
+  const TString fname = GetOutputFile();
+  
+  if (gSystem->AccessPathName(fname, kFileExists))
+  {
+      *fLog << err << "Input file " << fname << " doesn't exist." << endl;
+      return kFALSE;
+  }
+
+  *fLog << inf << "Reading from file: " << fname << endl;
+
+  TFile file(fname, "READ");
+  if (fCalibrationCam.Read()<=0)
+  {
+      *fLog << err << "Unable to read MCalibrationChargeCam from " << fname << endl;
+      return kFALSE;
+  }
+
+  if (fQECam.Read()<=0)
+  {
+      *fLog << err << "Unable to read MCalibrationQECam from " << fname << endl;
+      return kFALSE;
+  }
+
+
+  if (file.FindKey("MCalibrationRelTimeCam"))
+      if (fRelTimeCam.Read()<=0)
+      {
+          *fLog << err << "Unable to read MCalibrationRelTimeCam from " << fname << endl;
+          return kFALSE;
+      }
+
+  if (file.FindKey("MBadPixelsCam"))
+  {
+      MBadPixelsCam bad;
+      if (bad.Read()<=0)
+      {
+          *fLog << err << "Unable to read MBadPixelsCam from " << fname << endl;
+          return kFALSE;
+      }
+      fBadPixels.Merge(bad);
+  }
+
+  if (fDisplay /*&& !fDisplay->GetCanvas("Pedestals")*/) // FIXME!
+      fDisplay->Read();
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the useage of the Blind Pixel device 
+// 
+void MJCalibration::SetUseBlindPixel(const Bool_t b)
+{
+  b ? SETBIT(fDevices,kUseBlindPixel) : CLRBIT(fDevices,kUseBlindPixel);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the useage of the PIN Diode device 
+// 
+void MJCalibration::SetUsePINDiode(const Bool_t b)
+{
+  b ? SETBIT(fDevices,kUsePINDiode) : CLRBIT(fDevices,kUsePINDiode);
+}
+
+/*
+Bool_t MJCalibration::WriteEventloop(MEvtLoop &evtloop) const
+{
+    if (IsNoStorage())
+        return kTRUE;
+
+  if (fPathOut.IsNull())
+    return kTRUE;
+  
+  const TString oname(GetOutputFile());
+  
+  *fLog << inf << "Writing to file: " << oname << endl;
+  
+  TFile file(oname, fOverwrite?"RECREATE":"NEW", "File created by MJCalibration", 9);
+  if (!file.IsOpen())
+  {
+      *fLog << err << "ERROR - Couldn't open file " << oname << " for writing..." << endl;
+      return kFALSE;
+  }
+
+  if (evtloop.Write(fName)<=0)
+  {
+      *fLog << err << "Unable to write MEvtloop to " << oname << endl;
+      return kFALSE;
+  }
+  
+  return kTRUE;
+}
+*/
+
+Bool_t MJCalibration::WriteTasks(MTask *t1, MTask *t2) const
+{
+    if (IsNoStorage())
+        return kTRUE;
+
+    TObjArray cont;
+    if (t1)
+        cont.Add(t1);
+    if (t2)
+        cont.Add(t2);
+
+    return WriteContainer(cont, GetOutputFileName(), fOverwrite?"RECREATE":"NEW");
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the result into the output file GetOutputFile(), if fOutputPath exists.
+// 
+// The following containers are written:
+// - MStatusDisplay
+// - MCalibrationChargeCam  or MCalibrationIntensityChargeCam 
+// - MCalibrationBlindCam   or MCalibrationIntensityBlindCam
+// - MCalibrationQECam      or MCalibrationIntensityQECam     
+// - MCalibrationChargePINDiode
+// - MBadPixelsCam
+// If the flag kRelTimes is set, then also:
+// - MCalibrationRelTimeCam or MCalibrationIntensityRelTimeCam     
+//
+Bool_t MJCalibration::WriteResult(MParList &plist)
+{
+    if (IsNoStorage())
+        return kTRUE;
+
+    TObjArray cont;
+
+    if (IsIntensity())
+    {
+        cont.Add(&fIntensBadCam);
+        cont.Add(&fIntensCalibCam);
+        cont.Add(&fIntensQECam);
+        cont.Add(&fIntensBlindCam);
+    }
+    else
+    {
+        cont.Add(&fBadPixels);
+        cont.Add(&fCalibrationCam);
+        cont.Add(&fQECam);
+        cont.Add(&fCalibrationBlindCam);
+    }
+    cont.Add(&fCalibrationPINDiode);
+
+    //if (IsRelTimes())
+    cont.Add(IsIntensity() ? (TObject*)&fIntensRelTimeCam : (TObject*)&fRelTimeCam);
+
+    if (fExtractorCam.GetSize() != 0)
+        cont.Add(&fExtractorCam);
+
+    TObject *pedcam = plist.FindObject("MPedestalCam");
+    if (!pedcam)
+        *fLog << warn << " - WARNING - MPedestalCam (fundamental)... not found for writing!" << endl;
+    else
+        cont.Add(pedcam);
+
+    TObject *geom = plist.FindObject("MGeomCam");
+    if (!geom)
+        *fLog << warn << " - WARNING - MGeomCam... not found for writing!" << endl;
+    else
+        cont.Add(geom);
+
+    if (IsHistsStorage())
+    {
+        cont.Add(plist.FindObject("MHCalibrationChargeCam"));
+        cont.Add(plist.FindObject("MHCalibrationChargeBlindCam"));
+        cont.Add(plist.FindObject("MHCalibrationChargePINDiode"));
+        if (IsRelTimes())
+            cont.Add(plist.FindObject("MHCalibrationRelTimeCam"));
+    }
+
+    return WriteContainer(cont, GetOutputFileName(), "UPDATE");
+}
+
+void MJCalibration::DisplayDoubleProject(MHCamera *cam, const char* whatsmall, const char* whatbig) const
+{
+  
+  TArrayI inner(1);
+  inner[0] = 0;
+  
+  TArrayI outer(1);
+  outer[0] = 1;
+          
+  TArrayI s1(3);
+  s1[0] = 6;
+  s1[1] = 1;
+  s1[2] = 2;
+  
+  TArrayI s2(3);
+  s2[0] = 3;
+  s2[1] = 4;
+  s2[2] = 5;
+  
+  TVirtualPad *pad = gPad;
+  pad->Divide(2,1);
+  
+  TH1D *inout[2];
+
+  for (int i=0; i<2; i++)
+    {
+      pad->cd(i+1);
+      gPad->SetBorderMode(0);
+      gPad->SetTicks();
+      
+      inout[i] = cam->ProjectionS(TArrayI(), TArrayI(1,&i), i==0 ? "Inner" : "Outer");
+      FixDataCheckHist(inout[i]);
+      inout[i]->SetTitle(Form("%s %s",cam->GetTitle(),i==0 ? "Inner" : "Outer"));
+      inout[i]->SetDirectory(NULL);
+      inout[i]->SetLineColor(kRed+i);
+      inout[i]->SetBit(kCanDelete);
+      inout[i]->Draw();
+      //
+      // Display the outliers as dead and noisy pixels
+      //
+      if (!inout[i]->Fit("gaus","0Q"))
+        DisplayOutliers(inout[i],whatsmall,whatbig);
+
+      gPad->Modified();
+      gPad->Update();      
+      TPaveStats *st = (TPaveStats*)inout[i]->GetListOfFunctions()->FindObject("stats");
+      st->SetY1NDC(0.6);
+      st->SetY2NDC(0.9);
+      st->SetX1NDC(0.55);
+      st->SetX2NDC(0.99);
+      gPad->Modified();
+      gPad->Update();      
+
+      TLegend *leg2 = new TLegend(0.55,0.4,0.99,0.6);
+      
+      //
+      // Display the two half of the camera separately
+      //
+      TH1D *half[2];
+      half[0] = cam->ProjectionS(s1, TArrayI(1,&i), "Sector 6-1-2");
+      half[1] = cam->ProjectionS(s2, TArrayI(1,&i), "Sector 3-4-5");
+      
+      for (int j=0; j<2; j++)
+        {
+          half[j]->SetLineColor(kRed+i+2*j+1);
+          half[j]->SetDirectory(NULL);
+          half[j]->SetBit(kCanDelete);
+          half[j]->Draw("same");
+          leg2->AddEntry(half[j], half[j]->GetName(), "l");
+        }
+      leg2->Draw();
+    }
+}
Index: /tags/Mars-V0.9/mjobs/MJCalibration.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCalibration.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCalibration.h	(revision 9772)
@@ -0,0 +1,223 @@
+#ifndef MARS_MJCalibration
+#define MARS_MJCalibration
+
+#ifndef MARS_MJCalib
+#include "MJCalib.h"
+#endif
+#ifndef MARS_MCalibrationIntensityChargeCam
+#include "MCalibrationIntensityChargeCam.h"
+#endif
+#ifndef MARS_MCalibrationChargeCam
+#include "MCalibrationChargeCam.h"
+#endif
+#ifndef MARS_MCalibrationIntensityBlindCam
+#include "MCalibrationIntensityBlindCam.h"
+#endif
+#ifndef MARS_MCalibrationBlindCam
+#include "MCalibrationBlindCam.h"
+#endif
+#ifndef MARS_MCalibrationChargePINDiode
+#include "MCalibrationChargePINDiode.h"
+#endif
+#ifndef MARS_MCalibrationIntensityRelTimeCam
+#include "MCalibrationIntensityRelTimeCam.h"
+#endif
+#ifndef MARS_MCalibrationRelTimeCam
+#include "MCalibrationRelTimeCam.h"
+#endif
+#ifndef MARS_MCalibrationIntensityQECam
+#include "MCalibrationIntensityQECam.h"
+#endif
+#ifndef MARS_MCalibrationQECam
+#include "MCalibrationQECam.h"
+#endif
+#ifndef MARS_MBadPixelsIntensityCam
+#include "MBadPixelsIntensityCam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+#ifndef MARS_MPedestalCam
+#include "MPedestalCam.h"
+#endif
+
+class TH1D;
+
+class MTask;
+class MParList;
+class MPedestalCam;
+class MExtractor;
+class MExtractTime;
+class MEvtLoop;
+class MExtractBlindPixel;
+class MHCalibrationChargeBlindCam;
+class MHCamera;
+
+class MJCalibration : public MJCalib
+{
+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 gkSpecialPixelsContInstallation;   //! Run number upon which third blind pixel was installed
+  static const Int_t gkThirdBlindPixelInstallation;     //! Run number upon which third blind pixel was installed  
+
+  static const TString  fgReferenceFile;   //! default for fReferenceFile ("mjobs/calibrationref.rc")
+  static const TString  fgHiLoCalibFile;   //! default for fHiLoCalibFile ("mjobs/hilocalib.root")  
+
+  Double_t fConvFADC2PheMin;               //! Histogram minimum for conversion factor to phes
+  Double_t fConvFADC2PheMax;               //! Histogram maximum for conversion factor to phes
+  Double_t fConvFADC2PhotMin;              //! Histogram minimum for conversion factor to phs
+  Double_t fConvFADC2PhotMax;              //! Histogram maixmum for conversion factor to phs
+  Double_t fQEMin;                         //! Histogram minimum for quantum efficiency
+  Double_t fQEMax;                         //! Histogram maximum for quantum efficiency
+  Double_t fArrivalTimeMin;                //! Histogram minimum for arrival times 
+  Double_t fArrivalTimeMax;                //! Histogram maximum for arrival times
+  Double_t fTimeOffsetMin;                 //! Histogram minimum for time offsets
+  Double_t fTimeOffsetMax;                 //! Histogram maximum for time offsets
+  Double_t fTimeResolutionMin;             //! Histogram minimum for time resolutions
+  Double_t fTimeResolutionMax;             //! Histogram maximum for time resolutions
+  					   
+  Float_t  fRefConvFADC2PheInner;          //! Reference value for the conversion factor to phes - inner
+  Float_t  fRefConvFADC2PheOuter;          //! Reference value for the conversion factor to phes - outer
+  Float_t  fRefConvFADC2PhotInner;         //! Reference value for the conversion factor to phs - inner
+  Float_t  fRefConvFADC2PhotOuter;         //! Reference value for the conversion factor to phs - outer
+  Float_t  fRefQEInner;                    //! Reference value for the quantum eff. cascades - inner
+  Float_t  fRefQEOuter;                    //! Reference value for the quantum eff. cascades - outer
+  Float_t  fRefArrivalTimeInner;           //! Reference value for the arrival time - inner
+  Float_t  fRefArrivalTimeOuter;           //! Reference value for the arrival time - outer
+  Float_t  fRefArrivalTimeRmsInner;        //! Reference value for the arrival time - inner
+  Float_t  fRefArrivalTimeRmsOuter;        //! Reference value for the arrival time - outer
+  Float_t  fRefTimeOffsetInner;            //! Reference value for the time offset - inner
+  Float_t  fRefTimeOffsetOuter;            //! Reference value for the time offset - outer
+  Float_t  fRefTimeResolutionInner;  	   //! Reference value for the time resolution - inner
+  Float_t  fRefTimeResolutionOuter;	   //! Reference value for the time resolution - outer
+					   
+  TString  fReferenceFile;                 // File name containing the reference values
+  TString  fHiLoCalibFile;                 // File name containing the hi-lo calib. constants
+
+  MExtractor     *fExtractor;                           // Signal extractor
+  MExtractTime   *fTimeExtractor;                       // Arrival Time extractor
+  
+  MBadPixelsIntensityCam          fIntensBadCam;        // Bad Pixels cam, can be set from previous runs
+  MBadPixelsCam                   fBadPixels;           // Bad Pixels cam, can be set from previous runs  
+  MCalibrationIntensityChargeCam  fIntensCalibCam;      // Calibration conversion factors FADC2Phe for diff. intens.
+  MCalibrationChargeCam           fCalibrationCam;      // Calibration conversion factors FADC2Phe  
+  MCalibrationIntensityBlindCam   fIntensBlindCam;      // Calibration from Blind Pixel(s)
+  MCalibrationBlindCam            fCalibrationBlindCam; // Calibration from Blind Pixel(s)  
+  MCalibrationChargePINDiode      fCalibrationPINDiode; // Calibration from PIN Diode
+  MCalibrationIntensityQECam      fIntensQECam;         // Quantum efficiency for diff. intensities, 
+  MCalibrationQECam               fQECam;               // Quantum efficiency, can be set from previous runs
+  MCalibrationIntensityRelTimeCam fIntensRelTimeCam;    // Calibration constants rel. times for diff. intensities
+  MCalibrationRelTimeCam          fRelTimeCam;          // Calibration constants rel. times
+  
+  MPedestalCam                    fExtractorCam;        // Pedestal Cam with extractor resolution
+
+  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
+
+  enum { kRelTimes, kDebug, kIntensity };  // Possible flags
+
+  Byte_t fFlags;                                       // Bit-field for the flags
+  
+  TString fGeometry;                                   // Class name geometry
+  
+  Bool_t IsUseBlindPixel() const { return TESTBIT(fDevices,kUseBlindPixel); }
+  Bool_t IsUsePINDiode  () const { return TESTBIT(fDevices,kUsePINDiode);   }
+
+  Bool_t IsRelTimes     () const { return TESTBIT(fFlags,kRelTimes);       }
+  Bool_t IsDebug        () const { return TESTBIT(fFlags,kDebug);          }
+  Bool_t IsIntensity    () const { return TESTBIT(fFlags,kIntensity);      }
+
+  void   DrawTab(MParList &plist, const char *cont, const char *name, Option_t *opt);
+  
+  void   DisplayResult        ( MParList &plist );
+  void   DisplayReferenceLines( MHCamera *cam , const Int_t what                           ) const;
+  void   DisplayOutliers      ( TH1D     *hist, const char* whatsmall, const char* whatbig ) const;
+  void   DisplayDoubleProject ( MHCamera *cam , const char* whatsmall, const char* whatbig ) const;
+  const  Int_t CountBadPixels ( MHCamera *cam , const Int_t what                           ) const;
+  void   FixDataCheckHist     ( TH1D     *hist  ) const;
+  
+  Bool_t WriteResult   (MParList &plist);
+  //Bool_t WriteEventloop( MEvtLoop &evtloop   ) const;
+  Bool_t WriteTasks    ( MTask *t1, MTask *t2) const;
+  Bool_t CheckEnvLocal ();
+  
+  // WORKAROUNDS!!!
+  void   InitBlindPixel(MExtractBlindPixel &blindext,
+                        MHCalibrationChargeBlindCam &blindcam);
+
+  const char* GetOutputFileName() const;
+
+  void ReadReferenceFile();
+  Bool_t ReadHiLoCalibFile();
+  
+public:
+  MJCalibration(const char *name=NULL, const char *title=NULL);
+  
+  const char* GetOutputFile() const;
+  
+  MCalibrationIntensityChargeCam  &GetIntensCalibrationCam() { return fIntensCalibCam;   }
+  MCalibrationIntensityRelTimeCam &GetIntensRelTimeCam()     { return fIntensRelTimeCam; }
+  MCalibrationIntensityQECam      &GetIntensQECam()          { return fIntensQECam;      }
+  MBadPixelsIntensityCam          &GetIntensBadCam()         { return fIntensBadCam;     }  
+
+  MCalibrationChargeCam           &GetCalibrationCam()       { return fCalibrationCam;   }
+  MCalibrationRelTimeCam          &GetRelTimeCam()           { return fRelTimeCam;       }
+  MCalibrationQECam               &GetQECam()                { return fQECam;            }
+  MBadPixelsCam                   &GetBadPixels()            { return fBadPixels;        }
+  
+  // Containers and pointers
+  void SetBadPixels    ( const MBadPixelsCam &bad)                   { bad.Copy(fBadPixels); }
+  void SetColor        ( const MCalibrationCam::PulserColor_t color) { fColor = color;       }
+  void SetExtractor    ( MExtractor* ext)                            { fExtractor = ext;     }
+  void SetExtractorCam ( const MPedestalCam  &ped)                   { ped.Copy(fExtractorCam); fExtractorCam.SetName(ped.GetName()); }
+  void SetQECam        ( const MCalibrationQECam &qe)                { qe.Copy(fQECam);      }
+  void SetTimeExtractor( MExtractTime* ext)                          { fTimeExtractor = ext; }
+    
+  // Displays
+  void SetFullDisplay()      { fDisplayType = kFullDisplay;      }
+  void SetDataCheckDisplay() { fDisplayType = kDataCheckDisplay; }
+  void SetNormalDisplay()    { fDisplayType = kNormalDisplay;    }
+
+  // Camera Geomtry
+  void SetGeometry(const char *geom) { fGeometry = geom; }
+  
+  // Flags
+  void SetRelTimeCalibration( const Bool_t b=kTRUE ) { b ? SETBIT(fFlags,kRelTimes)  : CLRBIT(fFlags,kRelTimes); }
+  void SetDebug             ( const Bool_t b=kTRUE ) { b ? SETBIT(fFlags,kDebug)     : CLRBIT(fFlags,kDebug); }
+  void SetIntensity         ( const Bool_t b=kTRUE ) { b ? SETBIT(fFlags,kIntensity) : CLRBIT(fFlags,kIntensity); }
+  
+  // Devices
+  void SetUseBlindPixel(const Bool_t b=kTRUE);
+  void SetUsePINDiode(const Bool_t b=kTRUE);
+
+  // Files
+  void SetReferenceFile( const TString ref=fgReferenceFile ) { fReferenceFile = ref; }
+  void SetHiLoCalibFile( const TString ref=fgHiLoCalibFile ) { fHiLoCalibFile = ref; }
+
+  // Precessing
+  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
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJCut.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCut.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCut.cc	(revision 9772)
@@ -0,0 +1,521 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCut
+//
+// FIXME: Preparation for wobble mode missing
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCut.h"
+
+#include <TEnv.h>
+#include <TFile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+
+#include "MReadReports.h"
+#include "MPrint.h"
+#include "MContinue.h"
+#include "MEnergyEstimate.h"
+#include "MTaskEnv.h"
+#include "MSrcPosCalc.h"
+#include "MHillasCalc.h"
+#include "MFillH.h"
+#include "MWriteRootFile.h"
+
+#include "../mhflux/MAlphaFitter.h"
+#include "MBinning.h"
+#include "MDataSet.h"
+#include "MParameters.h"
+#include "MPointingPos.h"
+#include "MObservatory.h"
+
+ClassImp(MJCut);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MJCut::MJCut(const char *name, const char *title)
+    : fStoreSummary(kFALSE), fStoreResult(kFALSE), fWriteOnly(kFALSE),
+    fIsWobble(kFALSE), fEstimateEnergy(0), fCalcHadronness(0)
+{
+    fName  = name  ? name  : "MJCut";
+    fTitle = title ? title : "Standard program to perform g/h-seperation cuts";
+}
+
+MJCut::~MJCut()
+{
+    if (fEstimateEnergy)
+        delete fEstimateEnergy;
+    if (fCalcHadronness)
+        delete fCalcHadronness;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the summary file (events after cut0)
+// If you give a name the storage of this file is enabled implicitly.
+// If you give no filename the storage is neither enabled nor disabled,
+// but the storage file name is reset.
+// If no filename is set the default filename is used.
+// You can explicitly enable or disable the storage using EnableStoreOf*()
+// The default argument is no filename.
+//
+void MJCut::SetNameSummaryFile(const char *name)
+{
+    fNameSummary=name;
+    if (!fNameSummary.IsNull())
+        EnableStorageOfSummary();
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the summary file (events after cut3)
+// If you give a name the storage of this file is enabled implicitly.
+// If you give no filename the storage is neither enabled nor disabled,
+// but the storage file name is reset.
+// If no filename is set the default filename is used.
+// You can explicitly enable or disable the storage using EnableStoreOf*()
+// The default argument is no filename.
+//
+void MJCut::SetNameResultFile(const char *name)
+{
+    fNameResult=name;
+    if (!fNameResult.IsNull())
+        EnableStorageOfResult();
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup a task estimating the energy. The given task is cloned.
+//
+void MJCut::SetEnergyEstimator(const MTask *task)
+{
+    if (fEstimateEnergy)
+        delete fEstimateEnergy;
+    fEstimateEnergy = task ? (MTask*)task->Clone() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup a task calculating the hadronness. The given task is cloned.
+//
+void MJCut::SetHadronnessCalculator(const MTask *task)
+{
+    if (fCalcHadronness)
+        delete fCalcHadronness;
+    fCalcHadronness = task ? (MTask*)task->Clone() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// return fOutputPath+"/ganymed%08d.root", num
+//
+TString MJCut::GetOutputFile(UInt_t num) const
+{
+    TString p(fPathOut);
+    p += "/";
+    p += fNameOutput.IsNull() ? Form("ganymed%08d.root", num) : fNameOutput.Data();
+    return p;
+}
+
+/*
+Bool_t MJCut::ReadTasks(const char *fname, MTask* &env1, MTask* &env2) const
+{
+    //    const TString fname = Form("%s/calib%08d.root", fPathIn.Data(), fSequence.GetSequence());
+
+    *fLog << inf << "Reading from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+        return kFALSE;
+    }
+
+    TObject *o = file.Get("EstimateEnergy");
+    if (o && !o->InheritsFrom(MTask::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - EstimateEnergy read from " << fname << " doesn't inherit from MTask!" << endl;
+        return kFALSE;
+    }
+    env1 = o ? (MTask*)o->Clone() : NULL;
+
+    o = file.Get("CalcHadronness");
+    if (o && !o->InheritsFrom(MTask::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - CalcHadronness read from " << fname << " doesn't inherit from MTask!" << endl;
+        return kFALSE;
+    }
+    env2 = o ? (MTask*)o->Clone() : NULL;
+
+    return kTRUE;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Write the tasks in cont to the file corresponding to analysis number num,
+// see GetOutputFile()
+//
+Bool_t MJCut::WriteTasks(UInt_t num, TObjArray &cont) const
+{
+    if (fPathOut.IsNull())
+    {
+        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
+        return kTRUE;
+    }
+
+    const TString oname(GetOutputFile(num));
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TFile file(oname, fOverwrite?"RECREATE":"NEW", "File created by MJCut", 9);
+    if (!file.IsOpen())
+    {
+        *fLog << err << "ERROR - Couldn't open file " << oname << " for writing..." << endl;
+        return kFALSE;
+    }
+
+    return WriteContainer(cont);
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the result plots and other results to the file corresponding to
+// analysis number num, see GetOutputFile()
+//
+Bool_t MJCut::WriteResult(UInt_t num) const
+{
+    TObjArray arr;
+    return WriteContainer(arr, GetOutputFile(num), "UPDATE");
+}
+
+// --------------------------------------------------------------------------
+//
+// MJCut allows to setup several option by a resource file:
+//   MJCut.WriteSummary: yes, no
+//   MJCut.SummaryFile:  filename
+//   MJCut.WriteResult:  yes, no
+//   MJCut.ResultFile:   filename
+//
+Bool_t MJCut::CheckEnvLocal()
+{
+    const TString f0(GetEnv("SummaryFile", ""));
+    const TString f1(GetEnv("ResultFile",  ""));
+    if (!f0.IsNull())
+        SetNameSummaryFile(f0);
+    if (!f1.IsNull())
+        SetNameResultFile(f1);
+
+    EnableStorageOfSummary(GetEnv("SummaryFile", fStoreSummary));
+    EnableStorageOfResult(GetEnv("ResultFile", fStoreResult));
+    EnableWobbleMode(GetEnv("WobbleMode", fIsWobble));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup write to write:
+//     container         tree       optional?
+//  --------------     ----------  -----------
+//   "MHillas"      to  "Events"
+//   "MHillasSrc"   to  "Events"
+//   "MHadronness"  to  "Events"       yes
+//   "MEnergyEst"   to  "Events"       yes
+//   "DataType"     to  "Events"
+//
+void MJCut::SetupWriter(MWriteRootFile &write, const char *name) const
+{
+    write.SetName(name);
+    write.AddContainer("MHillas",     "Events");
+    write.AddContainer("MHillasSrc",  "Events");
+    write.AddContainer("MHadronness", "Events", kFALSE);
+    write.AddContainer("MEnergyEst",  "Events", kFALSE);
+    write.AddContainer("DataType",    "Events");
+
+    // Should not be the default: Either as option, or as
+    // setup from resource file
+    // write.AddContainer("MHillasExt",    "Events");
+    // write.AddContainer("MImagePar",     "Events");
+    // write.AddContainer("MNewImagePar",  "Events");
+}
+
+Bool_t MJCut::ProcessFile(const MDataSet &set)
+{
+    if (!set.IsValid())
+    {
+        *fLog << err << "ERROR - DataSet invalid!" << endl;
+        return kFALSE;
+    }
+
+    CheckEnv();
+
+    // --------------------------------------------------------------------------------
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Perform cuts for data set " << set.GetName() << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+
+    // Setup Parlist
+    MParList plist;
+    plist.AddToList(this); // take care of fDisplay!
+
+    MParameterI par("DataType");
+    plist.AddToList(&par);
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // La Palma Magic1
+    MObservatory obs;
+    plist.AddToList(&obs);
+
+    // Possible source position (eg. Wobble Mode)
+    MPointingPos source("MSourcePos");
+    if (set.GetSourcePos(source))
+    {
+        plist.AddToList(&source);
+        *fLog << inf << "Using Source Position: " << source.GetTitle() << endl;
+    }
+    else
+        *fLog << inf << "No source position applied..." << endl;
+
+    // Initialize default binnings
+    MBinning bins1(18, 0,  90,   "BinningAlpha",     "lin");
+    MBinning bins2(25, 10, 1e6 , "BinningEnergyEst", "log");
+    MBinning bins3(50, 0,  60,   "BinningTheta",     "cos");
+    MBinning bins4("BinningFalseSource");
+    plist.AddToList(&bins1);
+    plist.AddToList(&bins2);
+    plist.AddToList(&bins3);
+    plist.AddToList(&bins4);
+
+    // --------------------------------------------------------------------------------
+
+    // Setup fitter and histograms
+    MAlphaFitter fit;
+    plist.AddToList(&fit);
+    if (fIsWobble)
+        fit.SetScaleMode(MAlphaFitter::kNone);
+
+    MFillH falpha("MHAlphaOff [MHAlpha]", "MHillasSrc", "FillAlpha");
+    MFillH ffs("MHFalseSourceOff [MHFalseSource]", "MHillas", "FillFS");
+
+    // FIXME: If fPathIn read cuts and energy estimator from file!
+    MContinue cont0("", "Cut0");
+    MContinue cont1("", "Cut1");
+    MContinue cont2("", "Cut2");
+    MContinue cont3("", "Cut3");
+    cont0.SetAllowEmpty();
+    cont1.SetAllowEmpty();
+    cont2.SetAllowEmpty();
+    cont3.SetAllowEmpty();
+
+    // ------------- Loop Off Data --------------------
+    MReadReports readoff;
+    readoff.AddTree("Events", "MTime.", kTRUE);
+    readoff.AddTree("Drive");
+    readoff.AddTree("EffectiveOnTime");
+    if (fIsWobble)
+        set.AddFilesOn(readoff);
+    else
+        set.AddFilesOff(readoff);
+
+    const TString path(Form("%s/", fPathOut.Data()));
+    TString fname0(path);
+    TString fname1(path);
+    fname0 += fNameSummary.IsNull() ?  (TString) Form("ganymed%08d-summary.root", set.GetNumAnalysis()) : fNameSummary;
+    fname1 += fNameResult.IsNull()  ?  (TString) Form("ganymed%08d-result.root",  set.GetNumAnalysis()) : fNameResult;
+
+    MWriteRootFile write0(fPathOut.IsNull()?0:fname0.Data(), fOverwrite?"RECREATE":"NEW");
+    MWriteRootFile write1(fPathOut.IsNull()?0:fname1.Data(), fOverwrite?"RECREATE":"NEW");
+    if (CanStoreSummary())
+        SetupWriter(write0, "WriteAfterCut0");
+    if (CanStoreSummary())
+        SetupWriter(write1, "WriteAfterCut3");
+
+
+    MEnergyEstimate est;
+
+    MTaskEnv taskenv1("EstimateEnergy");
+    taskenv1.SetDefault(fEstimateEnergy ? fEstimateEnergy : &est);
+
+    MTaskEnv taskenv2("CalcHadronness");
+    taskenv2.SetDefault(fCalcHadronness);
+
+    MFillH fill1a("MHHillasOffPre  [MHHillas]", "MHillas", "FillHillasPre");
+    MFillH fill2a("MHHillasOffPost [MHHillas]", "MHillas", "FillHillasPost");
+    fill1a.SetNameTab("PreCut");
+    fill2a.SetNameTab("PostCut");
+
+    MPrint print2("MEffectiveOnTime");
+
+    // How to get source position from off- and on-data?
+    MSrcPosCalc scalc;
+    if (fIsWobble)
+        scalc.SetWobbleMode(); /********************/
+    MHillasCalc hcalc;
+    MHillasCalc hcalc2("MHillasCalcAnti");
+    hcalc.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetFlags(MHillasCalc::kCalcHillasSrc);
+    hcalc2.SetNameHillasSrc("MHillasSrcAnti");
+    hcalc2.SetNameSrcPosCam("MSrcPosAnti");
+
+    MTaskList tlist2;
+    tlist2.AddToList(&scalc);
+    tlist2.AddToList(&hcalc);
+    if (fIsWobble)
+        tlist2.AddToList(&hcalc2);
+    tlist2.AddToList(&taskenv1);
+    tlist2.AddToList(&taskenv2);
+    tlist2.AddToList(&cont0);
+    if (CanStoreSummary())
+        tlist2.AddToList(&write0);
+    if (!fWriteOnly)
+        tlist2.AddToList(&fill1a);
+    tlist2.AddToList(&cont1);
+    if (!fWriteOnly)
+        tlist2.AddToList(&ffs);
+    tlist2.AddToList(&cont2);
+    if (!fWriteOnly)
+        tlist2.AddToList(&fill2a);
+    if (!fWriteOnly)
+        tlist2.AddToList(&falpha);
+    tlist2.AddToList(&cont3);
+    if (CanStoreResult())
+        tlist2.AddToList(&write1);
+
+    tlist.AddToList(&readoff);
+    tlist.AddToList(&print2, "EffectiveOnTime");
+    tlist.AddToList(&tlist2, "Events");
+ 
+    par.SetVal(0);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    if (set.HasOffSequences() || fIsWobble)
+    {
+        // Execute first analysis
+        if (!evtloop.Eventloop(fMaxEvents))
+        {
+            *fLog << err << GetDescriptor() << ": Processing of off-sequences failed." << endl;
+            return kFALSE;
+        }
+
+        tlist.PrintStatistics();
+
+        if (!evtloop.GetDisplay())
+        {
+            *fLog << err << GetDescriptor() << ": Execution stopped by user." << endl;
+            return kFALSE;
+        }
+    }
+
+    // ------------- Loop On Data --------------------
+    MReadReports readon;
+    readon.AddTree("Events", "MTime.", kTRUE);
+    readon.AddTree("Drive");
+    readon.AddTree("EffectiveOnTime");
+    set.AddFilesOn(readon);
+
+    if (fIsWobble)
+        scalc.SetWobbleMode(kFALSE); /********************/
+
+    MFillH fill1b("MHHillasOnPre  [MHHillas]", "MHillas", "FillHillasPre");
+    MFillH fill2b("MHHillasOnPost [MHHillas]", "MHillas", "FillHillasPost");
+    fill1b.SetNameTab("PreCut");
+    fill2b.SetNameTab("PostCut");
+    fill1b.SetDrawOption(set.HasOffSequences()||fIsWobble?"same":"");
+    fill2b.SetDrawOption(set.HasOffSequences()||fIsWobble?"same":"");
+
+    MFillH falpha2("MHAlpha", "MHillasSrc", "FillAlpha");
+    MFillH ffs2("MHFalseSource", "MHillas", "FillFS");
+
+    tlist.Replace(&readon);
+    if (!fWriteOnly)
+    {
+        tlist2.Replace(&fill1b);
+        tlist2.Replace(&fill2b);
+        tlist2.Replace(&falpha2);
+        tlist2.Replace(&ffs2);
+    }
+
+    par.SetVal(1);
+
+    TObjArray cont;
+    cont.Add(&cont0);
+    cont.Add(&cont1);
+    cont.Add(&cont2);
+    cont.Add(&cont3);
+    if (taskenv1.GetTask())
+        cont.Add(taskenv1.GetTask());
+    if (taskenv2.GetTask())
+        cont.Add(taskenv2.GetTask());
+
+    if (!WriteTasks(set.GetNumAnalysis(), cont))
+        return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Processing of on-sequences failed." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    // FIXME: Perform fit and plot energy dependant alpha plots
+    // and fit result to new tabs!
+    if (!WriteResult(set.GetNumAnalysis()))
+        return kFALSE;
+
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mjobs/MJCut.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJCut.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJCut.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MJCut
+#define MARS_MJCut
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MTask;
+class MDataSet;
+class MWriteRootFile;
+
+class MJCut : public MJob
+{
+private:
+    Bool_t  fStoreSummary;
+    Bool_t  fStoreResult;
+    Bool_t  fWriteOnly;
+    Bool_t  fIsWobble;
+
+    TString fNameSummary;
+    TString fNameResult;
+    TString fNameOutput;
+
+    MTask *fEstimateEnergy;
+    MTask *fCalcHadronness;
+
+    TString GetOutputFile(UInt_t num) const;
+    Bool_t  CheckEnvLocal();
+    void    SetupWriter(MWriteRootFile &write, const char *name) const;
+    Bool_t  WriteTasks(UInt_t num, TObjArray &cont) const;
+    Bool_t  WriteResult(UInt_t num) const;
+
+    Bool_t  CanStoreSummary() const { return !fPathOut.IsNull() && fStoreSummary; }
+    Bool_t  CanStoreResult() const  { return !fPathOut.IsNull() && fStoreResult;  }
+
+public:
+    MJCut(const char *name=NULL, const char *title=NULL);
+    ~MJCut();
+
+    Bool_t ProcessFile(const MDataSet &set);
+
+    void EnableStorageOfSummary(Bool_t b=kTRUE)  { fStoreSummary = b; } // See SetNameSummary
+    void EnableStorageOfResult(Bool_t b=kTRUE)   { fStoreResult  = b; } // See SetNameResult
+    void EnableWriteOnly(Bool_t b=kTRUE)         { fWriteOnly    = b; }
+    void EnableWobbleMode(Bool_t b=kTRUE)        { fIsWobble     = b; }
+
+    void SetNameSummaryFile(const char *name="");
+    void SetNameResultFile(const char *name="");
+    void SetNameOutFile(const char *name="")      { fNameOutput=name; }
+
+    void SetEnergyEstimator(const MTask *task=0);
+    void SetHadronnessCalculator(const MTask *task=0);
+
+    ClassDef(MJCut, 0) // Standard program to perform g/h-seperation cuts
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJExtractSignal.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJExtractSignal.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJExtractSignal.cc	(revision 9772)
@@ -0,0 +1,538 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJExtractSignal
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJExtractSignal.h"
+
+#include <TFile.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRunIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+#include "MPrint.h"
+
+#include "MHCamera.h"
+
+#include "MPedestalCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationQECam.h"
+#include "MHCamEvent.h"
+
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MBadPixelsMerge.h"
+#include "MExtractSignal.h"
+#include "MFillH.h"
+#include "MCalibrateData.h"
+#include "MPedPhotCalc.h"
+#include "MWriteRootFile.h"
+
+#include "MExtractSlidingWindow.h"
+#include "MExtractor.h"
+#include "MExtractTime.h"
+#include "MExtractTimeFastSpline.h"
+
+#include "MJExtractSignal.h"
+#include "MStatusDisplay.h"
+
+
+ClassImp(MJExtractSignal);
+
+using namespace std;
+
+MJExtractSignal::MJExtractSignal(const char *name, const char *title)
+    : fRuns(0), fExtractor(NULL), fTimeExtractor(NULL)
+{
+    fName  = name  ? name  : "MJExtractSignal";
+    fTitle = title ? title : "Tool to create a pedestal file (MPedestalCam)";
+}
+
+Bool_t MJExtractSignal::WriteResult()
+{
+    if (fOutputPath.IsNull())
+        return kTRUE;
+
+    const TString oname = GetOutputFileP();
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TFile file(oname, "RECREATE");
+
+    if (fDisplay && fDisplay->Write()<=0)
+    {
+        *fLog << err << "Unable to write MStatusDisplay to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fPedPhotCam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MPedPhotCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fBadPixels.Write()<=0)
+    {
+        *fLog << err << "Unable to write MBadPixelsCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+
+}
+
+void MJExtractSignal::SetOutputPath(const char *path)
+{
+    fOutputPath = path;
+    if (fOutputPath.EndsWith("/"))
+        fOutputPath = fOutputPath(0, fOutputPath.Length()-1);
+}
+
+TString MJExtractSignal::GetOutputFileD() const
+{
+    if (!fRuns)
+        return "";
+
+    return Form("%s/%s-F3.root", (const char*)fOutputPath, (const char*)fRuns->GetRunsAsFileName());
+}
+TString MJExtractSignal::GetOutputFileP() const
+{
+    if (!fRuns)
+        return "";
+
+    return Form("%s/%s-F2.root", (const char*)fOutputPath, (const char*)fRuns->GetRunsAsFileName());
+}
+
+Bool_t MJExtractSignal::ProcessD(MPedestalCam &pedcam)
+{
+    const TString fname = GetOutputFileD();
+
+    if (gSystem->AccessPathName(fname, kFileExists))
+        return ProcessFileD(pedcam);
+
+    return kTRUE;
+}
+
+Bool_t MJExtractSignal::ProcessFileD(MPedestalCam &pedcam)
+{
+
+  if (!fRuns)
+    {
+      *fLog << err << "No Runs choosen... abort." << endl;
+      return kFALSE;
+    }
+  if (fRuns->GetNumRuns() != fRuns->GetNumEntries())
+    {
+        *fLog << err << "Number of files found doesn't match number of runs... abort." << endl;
+        return kFALSE;
+    }
+  
+  *fLog << inf;
+  fLog->Separator(GetDescriptor());
+  *fLog << "Calculate MExtractedSignalCam from Runs " << fRuns->GetRunsAsString() << endl;
+  *fLog << endl;
+  
+  // Setup Lists
+  MParList plist;
+  plist.AddToList(&pedcam);
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  // Setup Parameters
+  
+  // Make sure, that at least an empty MBadPixelsCam is available
+  // This is necessary for input which don't contain a MBadPixelsCam
+  MBadPixelsCam badcam;
+  plist.AddToList(&badcam);
+  
+  // Setup Task-lists
+  MReadMarsFile read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(*fRuns);
+  
+  MGeomApply               apply; // Only necessary to craete geometry
+  MBadPixelsMerge          merge(&fBadPixels);
+  MExtractTimeFastSpline   exttime;
+  MExtractSlidingWindow    extcharge; // Only for the cosmics filter
+  
+  MHCamEvent evt("ExtSignal");
+  evt.SetType(0);
+  MFillH fill(&evt, "MExtractedSignalCam");
+  
+  MWriteRootFile write(GetOutputFileD(), "RECREATE", fRuns->GetRunsAsString(), 2);
+  write.AddContainer("MExtractedSignalCam", "Events");
+  write.AddContainer("MArrivalTimeCam",     "Events");
+  write.AddContainer("MTime",               "Events");
+  write.AddContainer("MRawEvtHeader",       "Events");
+  write.AddContainer("MPedestalCam",        "RunHeaders");
+  write.AddContainer("MRawRunHeader",       "RunHeaders");
+  write.AddContainer("MBadPixelsCam",       "RunHeaders");
+  
+  tlist.AddToList(&read);
+  tlist.AddToList(&apply);
+  tlist.AddToList(&merge);
+  
+  if (fTimeExtractor)
+    tlist.AddToList(fTimeExtractor);
+  else
+  {
+      *fLog << warn << GetDescriptor() 
+            << ": No extractor has been chosen, take default MExtractTimeFastSpline " << endl;
+      tlist.AddToList(&exttime);
+  }
+
+  if (fExtractor)
+    tlist.AddToList(fExtractor);
+  else
+  {
+      *fLog << warn << GetDescriptor() 
+            << ": No extractor has been chosen, take default MExtractSlidingWindow " << endl;
+      tlist.AddToList(&extcharge);
+  }
+
+//  MPrint print("MExtractedSignalCam");
+//  tlist.AddToList(&print);
+  
+  if (TestBit(kEnableGraphicalOutput))
+    tlist.AddToList(&fill);
+  tlist.AddToList(&write);
+  
+  // 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();
+  
+  //DisplayResult(plist);
+  
+  //if (!WriteResult())
+  //    return kFALSE;
+  
+  *fLog << inf << GetDescriptor() << ": Done." << endl;
+  
+  return kTRUE;
+}
+
+Bool_t MJExtractSignal::ReadPedPhotCam()
+{
+    const TString fname = GetOutputFileP();
+
+    if (gSystem->AccessPathName(fname, kFileExists))
+    {
+        *fLog << err << "Input file " << fname << " doesn't exist." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Reading from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (fPedPhotCam.Read()<=0)
+    {
+        *fLog << "Unable to read MPedPhotCam from " << fname << endl;
+        return kFALSE;
+    }
+
+    if (file.FindKey("MBadPixelsCam"))
+    {
+        MBadPixelsCam bad;
+        if (bad.Read()<=0)
+        {
+            *fLog << "Unable to read MBadPixelsCam from " << fname << endl;
+            return kFALSE;
+        }
+        fBadPixels.Merge(bad);
+    }
+
+    if (fDisplay /*&& !fDisplay->GetCanvas("Pedestals")*/) // FIXME!
+        fDisplay->Read();
+
+    return kTRUE;
+}
+
+Bool_t MJExtractSignal::ProcessP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam, MCalibrationQECam &qecam)
+{
+    if (!ReadPedPhotCam())
+        return ProcessFileP(pedcam, calcam, qecam);
+
+    return kTRUE;
+}
+
+Bool_t MJExtractSignal::ProcessFileP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam, MCalibrationQECam &qecam)
+{
+    if (!fRuns)
+    {
+        *fLog << err << "No Runs choosen... abort." << endl;
+        return kFALSE;
+    }
+    if (fRuns->GetNumRuns() != fRuns->GetNumEntries())
+    {
+        *fLog << err << "Number of files found doesn't match number of runs... abort." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate MExtractedSignalCam from Runs " << fRuns->GetRunsAsString() << endl;
+    *fLog << endl;
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    static_cast<MRead&>(read).AddFiles(*fRuns);
+
+    // Setup Tasklist
+    MParList plist;
+    plist.AddToList(&pedcam);
+    plist.AddToList(&calcam);
+    plist.AddToList(&qecam);
+    plist.AddToList(&fPedPhotCam);
+    plist.AddToList(&fBadPixels);
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MGeomApply      apply; // Only necessary to craete geometry
+    MBadPixelsMerge merge(&fBadPixels);
+    MExtractSignal  extract;
+    MCalibrateData  calib;
+    MPedPhotCalc    calc;
+
+    MHCamEvent evt1("ExtOffset");
+    MHCamEvent evt2("CalOffset");
+    evt1.SetType(0);
+    evt2.SetType(0);
+    MFillH fill1(&evt1, "MExtractedSignalCam", "FillExtractedSignal");
+    MFillH fill2(&evt2, "MCerPhotEvt",         "FillCerPhotEvt");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&merge);
+    tlist.AddToList(&extract);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill1);
+    tlist.AddToList(&calib);
+    tlist.AddToList(&calc);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill2);
+
+    // 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();
+
+    //DisplayResult(plist);
+
+    if (!WriteResult())
+        return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
+}
+
+/*
+Bool_t MJExtractSignal::ProcessFile(MPedestalCam *pedcam, MCalibrationChargeCam *calcam)
+{
+    if (!fRuns)
+    {
+        *fLog << err << "No Runs choosen... abort." << endl;
+        return kFALSE;
+    }
+    if (fRuns->GetNumRuns() != fRuns->GetNumEntries())
+    {
+        *fLog << err << "Number of files found doesn't match number of runs... abort." << endl;
+        return kFALSE;
+    }
+
+    Int_t type = 0;
+    if (pedcam &&  calcam) type = 2;
+    if (pedcam && !calcam) type = 3;
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculating from Runs " << fRuns->GetRunsAsString() << endl;
+    *fLog << endl;
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    static_cast<MRead&>(read).AddFiles(*fRuns);
+
+    // Setup Tasklist
+    MParList plist;
+    switch (type)
+    {
+    case 2:
+        plist.AddToList(calcam);
+        plist.AddToList(&fPedPhotCam);
+    case 3:
+        plist.AddToList(pedcam);
+    }
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MGeomApply     apply; // Only necessary to craete geometry
+    MExtractSignal extract;
+    MCalibrateData calib;
+    MPedPhotCalc   calc;
+
+
+    MHCamEvent evt1("ExtOffset");
+    MHCamEvent evt2("CalOffset");
+    evt1.SetType(0);
+    evt2.SetType(0);
+    MFillH fill1(&evt1, "MExtractedSignalCam", "FillExtractedSignal");
+    MFillH fill2(&evt2, "MCerPhotEvt",         "FillCerPhotEvt");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&extract);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill1);
+    tlist.AddToList(&calib);
+    tlist.AddToList(&calc);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill2);
+
+
+    MHCamEvent evt("ExtSignal");
+    evt.SetType(0);
+    MFillH fill(&evt, "MExtractedSignalCam");
+
+    MWriteRootFile write(GetOutputFileD(), "RECREATE", fRuns->GetRunsAsString(), 2);
+    write.AddContainer("MExtractedSignalCam", "Events");
+    write.AddContainer("MTime",               "Events");
+    write.AddContainer("MRawRunHeader",       "RunHeaders");
+    write.AddContainer("MPedestalCam",        "RunHeaders");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&extract);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill);
+    tlist.AddToList(&write);
+
+    // 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();
+
+    //DisplayResult(plist);
+
+    //if (!WriteResult())
+    //    return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
+
+
+    // ------------------------------------------------------
+
+    MGeomApply     apply; // Only necessary to craete geometry
+    MExtractSignal extract;
+    MCalibrateData  calib;
+    MPedPhotCalc   calc;
+
+    MHCamEvent evt1("ExtOffset");
+    MHCamEvent evt2("CalOffset");
+    evt1.SetType(0);
+    evt2.SetType(0);
+    MFillH fill1(&evt1, "MExtractedSignalCam", "FillExtractedSignal");
+    MFillH fill2(&evt2, "MCerPhotEvt",         "FillCerPhotEvt");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&extract);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill1);
+    tlist.AddToList(&calib);
+    tlist.AddToList(&calc);
+    if (TestBit(kEnableGraphicalOutput))
+        tlist.AddToList(&fill2);
+
+    // 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();
+
+    //DisplayResult(plist);
+
+    if (!WriteResult())
+        return kFALSE;
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
+    }
+    */
Index: /tags/Mars-V0.9/mjobs/MJExtractSignal.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJExtractSignal.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJExtractSignal.h	(revision 9772)
@@ -0,0 +1,65 @@
+#ifndef MARS_MJExtractSignal
+#define MARS_MJExtractSignal
+
+#ifndef MARS_MPedPhotCam
+#include "MPedPhotCam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+class TCanvas;
+class MHCamera;
+class MCamEvent;
+class MRunIter;
+class MParList;
+class MPedestalCam;
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MExtractor;
+class MExtractTime;
+
+class MJExtractSignal : public MParContainer
+{
+private:
+    TString fOutputPath;
+
+    MRunIter *fRuns;
+    
+    MExtractor   *fExtractor;                  // Signal extractor
+    MExtractTime *fTimeExtractor;              // Arrival time extractor  
+
+    MPedPhotCam   fPedPhotCam;
+    MBadPixelsCam fBadPixels;
+
+    void   DisplayResult(MParList &plist);
+    Bool_t WriteResult();
+
+    Bool_t ReadPedPhotCam();
+
+    Bool_t ProcessFileD(MPedestalCam &pedcam);
+    Bool_t ProcessFileP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam, MCalibrationQECam &qecam);
+
+public:
+    MJExtractSignal(const char *name=NULL, const char *title=NULL);
+
+    void SetInput(MRunIter *iter) { fRuns = iter; }
+    void SetOutputPath(const char *path=".");
+
+    TString GetOutputFileP() const;
+    TString GetOutputFileD() const;
+
+    MPedPhotCam &GetPedPhotCam() { return fPedPhotCam; }
+    const MBadPixelsCam &GetBadPixels()  const { return fBadPixels; }
+
+    void SetExtractor(MExtractor* ext)              { fExtractor = ext; }
+    void SetTimeExtractor(MExtractTime* ext)         { fTimeExtractor = ext; }
+    void SetBadPixels(const MBadPixelsCam &bad) { bad.Copy(fBadPixels); }
+
+    Bool_t ProcessD(MPedestalCam &pedcam);
+    Bool_t ProcessP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam, MCalibrationQECam &qecam);
+
+    ClassDef(MJExtractSignal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJOptimize.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJOptimize.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJOptimize.cc	(revision 9772)
@@ -0,0 +1,1010 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 9/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MJOptimize
+//
+// Class for otimizing the parameters of the supercuts
+//
+// Minimization Control
+// ====================
+//
+//   To choose the minimization algorithm use:
+//         void SetOptimizer(Optimizer_t o);
+//
+//   Allowed options are:
+//        enum Optimizer_t
+//        {
+//            kMigrad,      // Minimize by the method of Migrad
+//            kSimplex,     // Minimize by the method of Simplex
+//            kMinimize,    // Migrad + Simplex (if Migrad fails)
+//            kMinos,       // Minos error determination
+//            kImprove,     // Local minimum search
+//            kSeek,        // Minimize by the method of Monte Carlo
+//            kNone         // Skip optimization
+//        };
+//
+//   For more details on the methods see TMinuit.
+//
+//
+//   You can change the behaviour of the minimization using
+//
+//        void SetNumMaxCalls(UInt_t num=0);
+//        void SetTolerance(Float_t tol=0);
+//
+//   While NumMaxCalls is the first, Tolerance the second arguement.
+//   For more details start root and type
+//
+//        gMinuit->mnhelp("command")
+//
+//   while command can be
+//        * MIGRAD
+//        * SIMPLEX
+//        * MINIMIZE
+//        * MINOS
+//        * IMPROVE
+//        * SEEK
+//
+//   The default (num==0 and tol==0) should always give you the
+//   corresponding defaults used in Minuit.
+//
+//
+// FIXME: Implement changing cut in hadronness...
+// FIXME: Show MHSignificance on MStatusDisplay during filling...
+// FIXME: Choose step-size percentage as static data membewr
+// FIXME: Choose minimization method
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJOptimize.h"
+
+#include <TMinuit.h>
+#include <TVirtualFitter.h>
+
+#include <TStopwatch.h>
+
+#include <TCanvas.h>
+
+#include <TGraph.h>
+#include <TMultiGraph.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MGeomCamCT1.h"
+#include "MFEventSelector.h"
+#include "MReadTree.h"
+#include "MHMatrix.h"
+#include "MEnergyEstimate.h"
+#include "MMatrixLoop.h"
+#include "MChisqEval.h"
+#include "MEvtLoop.h"
+#include "MDataElement.h"
+#include "MDataMember.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParameters.h"
+#include "MFillH.h"
+#include "MF.h"
+#include "MFilterList.h"
+#include "../mfilter/MFSupercuts.h"
+#include "MContinue.h"
+#include "MGeomCamMagic.h"
+#include "../mimage/MHillasSrcCalc.h"
+#include "MHMatrix.h"
+#include "MMatrixLoop.h"
+#include "../mhflux/MHAlpha.h"
+#include "MStatusDisplay.h"
+#include "../mhflux/MHEnergyEst.h"
+#include "MDirIter.h"
+#include "../mjobs/MSequence.h"
+
+using namespace std;
+
+//------------------------------------------------------------------------
+//
+// fcn calculates the function to be minimized (using TMinuit::Migrad)
+//
+void MJOptimize::fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    MJOptimize *optim = (MJOptimize*)gMinuit->GetObjectFit();
+
+    // WORKAROUND --- FOR WHAT?
+    if (gMinuit->fEpsi<1e-2)
+    {
+        *optim->fLog << warn << "WARNING - For unknown reasons: fEspi<1e-100... resetting to 0.01." << endl;
+        gMinuit->fEpsi = 0.01;
+    }
+
+    TMinuit *minuit = gMinuit;
+    f = optim->Fcn(TArrayD(TMath::Min(gMinuit->fMaxpar, optim->fParameters.GetSize()), par), minuit);
+    gMinuit = minuit;
+
+}
+
+Double_t MJOptimize::Fcn(const TArrayD &par, TMinuit *minuit)
+{
+    if (fEvtLoop->GetDisplay()!=fDisplay)
+        return 0;
+    /*
+    switch(iflag)
+    {
+    case 1: // first call
+    case 2: // calc derivative
+        break;
+    case 3:
+        // last call
+        MStatusDisplay *d = new MStatusDisplay;
+        fEvtLoop->SetDisplay(d);
+        break;
+    }
+    */
+    MParList *plist = fEvtLoop->GetParList();
+
+    MParameterD   *eval = (MParameterD*)plist->FindObject("MinimizationValue", "MParameterD");
+    MParContainer *pars = (MParContainer*)plist->FindObject("MParameters", "MParContainer");
+
+    MRead *read = (MRead*)plist->FindObject("MTaskList")->FindObject("MRead");
+    if (read)
+        read->Rewind();
+
+    if (fDebug>=0)
+    {
+        *fLog << inf << "New Set: ";
+        for (Int_t i=0; i<fParameters.GetSize(); i++)
+            *fLog << par[i] << " ";
+        *fLog << endl;
+    }
+ 
+    pars->SetVariables(par);
+    eval->SetVal(0);
+
+    if (fDebug<3)
+        gLog.SetNullOutput(kTRUE);
+
+    TStopwatch clock;
+    clock.Start();
+    fEvtLoop->Eventloop(fNumEvents);
+    clock.Stop();
+
+    if (fDebug<3)
+        gLog.SetNullOutput(kFALSE);
+
+    const Double_t f = eval->GetVal();
+
+    if (fDebug>=0)
+        *fLog << inf << "Result F=" << f << endl;
+
+    if (fDebug>=1 && minuit)
+    {
+        Double_t fmin, fedm, errdef;
+        Int_t n1, n2, istat;
+        minuit->mnstat(fmin, fedm, errdef, n1, n2, istat);
+        *fLog << inf << underline << "Minimization Status so far:" << endl;
+        *fLog << " Calls:      " << minuit->fNfcn << "  (max=" << gMinuit->fMaxIterations << ")" << endl;
+        *fLog << " Parameters: fixed=" << gMinuit->fNpfix << ", free=" << gMinuit->fNpar << endl;
+        *fLog << " Func min:   " << fmin << "  (Epsi=" << gMinuit->fEpsi << ", Apsi=" << gMinuit->fApsi << ")" << endl;
+        *fLog << " Found edm:  " << fedm << endl;
+        *fLog << " ErrDef:     " << errdef << endl;
+        *fLog << " Status:     ";
+
+        switch (istat)
+        {
+        case 0:  *fLog << "n/a" << endl; break;
+        case 1:  *fLog << "approximation only, not accurate" << endl; break;
+        case 2:  *fLog << "full matrix, but forced positive-definite" << endl; break;
+        case 3:  *fLog << "full accurate covariance matrix" << endl; break;
+        default: *fLog << "undefined" << endl; break;
+        }
+    }
+
+    if (fDebug>=1)
+    {
+        clock.Print();
+        fEvtLoop->GetTaskList()->PrintStatistics();
+    }
+
+    return f;
+}
+
+MJOptimize::MJOptimize() : fDebug(-1), fNumEvents(0), fType(kSimplex), fNumMaxCalls(0), fTolerance(0)
+{
+    fRules.SetOwner();
+    fFilter.SetOwner();
+
+    fNamesOn.SetOwner();
+    fNamesOff.SetOwner();
+}
+
+//------------------------------------------------------------------------
+//
+// Add seqeunces from list to reader
+//
+Bool_t MJOptimize::AddSequences(MRead &read, TList &list) const
+{
+    MDirIter files;
+
+    TIter Next(&list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        MSequence seq(o->GetName());
+        if (!seq.IsValid())
+            return kFALSE;
+
+        seq.SetupDatRuns(files, o->GetTitle(), "I");
+    }
+
+    return read.AddFiles(files)>0;
+}
+
+//------------------------------------------------------------------------
+//
+// Add on-sequences:
+//  - fname: sequence file name (with path)
+//  - dir:   directory were image files are stored
+//
+void MJOptimize::AddSequenceOn(const char *fname, const char *dir)
+{
+    fNamesOn.Add(new TNamed(fname, dir));
+}
+
+//------------------------------------------------------------------------
+//
+// Add off-sequences:
+//  - fname: sequence file name (with path)
+//  - dir:   directory were image files are stored
+//
+void MJOptimize::AddSequenceOff(const char *fname, const char *dir)
+{
+    fNamesOff.Add(new TNamed(fname, dir));
+}
+
+//------------------------------------------------------------------------
+//
+// Empty list of on- and off-sequences
+//
+void MJOptimize::ResetSequences()
+{
+    fNamesOn.Delete();
+    fNamesOff.Delete();
+}
+
+//------------------------------------------------------------------------
+//
+// Add a parameter used in your filters (see AddFilter) The parameter
+// index is returned,
+//
+//   Int_t idx = AddParameter("log10(MHillas.fSize)");
+//
+// The indices area starting with 0 always.
+//
+Int_t MJOptimize::AddParameter(const char *rule)
+{
+    fRules.Add(new TNamed(rule, ""));
+    return fRules.GetSize()-1;
+}
+
+//------------------------------------------------------------------------
+//
+// Add a filter which can be applied in the optimization (for deatils
+// see correspodning Run function) You can use the indices you got by
+// AddParameter, eg
+//
+//   AddFilter("M[0] < 3.2");
+//
+// if used in optimization you can do
+//
+//   AddFilter("M[0] < [0]");
+//
+// for more details, see SetParameter and FixParameter
+//
+void MJOptimize::AddFilter(const char *rule)
+{
+    fFilter.Add(new MF(rule));
+}
+
+//------------------------------------------------------------------------
+//
+// Add a cut which is used to fill the matrix, eg "MMcEvt.fOartId<1.5"
+// (The rule is applied, nit inverted: The matrix is filled with
+// the events fullfilling the condition)
+//
+void MJOptimize::AddPreCut(const char *rule)
+{
+    fPreCuts.Add(new MF(rule));
+}
+
+//------------------------------------------------------------------------
+//
+// Set the fParameters Array accoring to par.
+//
+void MJOptimize::SetParameters(const TArrayD &par)
+{
+    fParameters = par;
+}
+
+//------------------------------------------------------------------------
+//
+// Set the number of events processed by the eventloop. (Be carfull,
+// if you are doing on-off analysis and you only process the first
+// 1000 events which are on-events only the optimization may not work)
+//
+void MJOptimize::SetNumEvents(UInt_t n)
+{
+    fNumEvents=n;
+}
+
+//------------------------------------------------------------------------
+//
+// Set a debug level, which tells the optimization how much information
+// is displayed about and in the running eventloop.
+//
+void MJOptimize::SetDebug(UInt_t n)
+{
+    fDebug=n;
+}
+
+//------------------------------------------------------------------------
+//
+// Set a optimization algorithm to be used. For more information see
+// TMinuit.
+//
+// Available Algorithms are:
+//    kMigrad,   // Minimize by the method of Migrad
+//    kSimplex,  // Minimize by the method of Simplex
+//    kSeek      // Minimize by the method of Monte Carlo
+//
+void MJOptimize::SetOptimizer(Optimizer_t o)
+{
+    fType = o;
+}
+
+//------------------------------------------------------------------------
+//
+// If a status didplay is set, search for tab "Optimizer".
+// If not found, create it.
+// In the tab search for TMultiGraph "Parameters".
+// If not found create it.
+// If empty create TGraphs.
+// Check number of graphs vs. number of parameters.
+// return TList with graphs.
+//
+TList *MJOptimize::GetPlots() const
+{
+    if (!fDisplay)
+        return NULL;
+
+    TCanvas *c=fDisplay->GetCanvas("Optimizer");
+    if (!c)
+        c = &fDisplay->AddTab("Optimizer");
+
+    TMultiGraph *mg = dynamic_cast<TMultiGraph*>(c->FindObject("Parameters"));
+    if (!mg)
+        mg = new TMultiGraph("Parameters", "Parameters of optimization");
+
+    TList *l = mg->GetListOfGraphs();
+    if (!l)
+    {
+        const Int_t n = fParameters.GetSize();
+        for (int i=0; i<n+1; i++)
+        {
+            TGraph *g = new TGraph;
+            if (i==n)
+                g->SetLineColor(kBlue);
+            mg->Add(g, "");
+            AddPoint(mg->GetListOfGraphs(), i, i==n?1:fParameters[i]);
+        }
+        mg->SetBit(kCanDelete);
+        mg->Draw("al*");
+
+        l = mg->GetListOfGraphs();
+    }
+
+    return l->GetSize() == fParameters.GetSize()+1 ? l : NULL;
+}
+
+//------------------------------------------------------------------------
+//
+// Add a point with y=val as last point in idx-th Tgraph of list l.
+//
+void MJOptimize::AddPoint(TList *l, Int_t idx, Float_t val) const
+{
+    if (!l)
+        return;
+
+    TGraph *gr = (TGraph*)l->At(idx);
+    gr->SetPoint(gr->GetN(), gr->GetN(), val);
+}
+
+Int_t MJOptimize::Minuit(TMinuit &minuit, const char *cmd) const
+{
+    Int_t err;
+    Double_t tmp[2] = { fNumMaxCalls, fTolerance };
+    minuit.mnexcm(cmd, tmp, 2, err);
+
+    switch (err)
+    {
+    case 0:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm excuted normally." << endl;
+        break;
+    case 1:
+        *fLog << warn << GetDescriptor() << " TMinuit::mnexcm command is blank... ignored." << endl;
+        break;
+    case 2:
+        *fLog << warn << GetDescriptor() << " TMinuit::mnexcm command-line syntax error... ignored." << endl;
+        break;
+    case 3:
+        *fLog << warn << GetDescriptor() << " TMinuit::mnexcm unknown command... ignored." << endl;
+        break;
+    case 4:
+        *fLog << warn << GetDescriptor() << " TMinuit::mnexcm - Abnormal termination (eg Migrad not converged)" << endl;
+        break;
+        /*
+    case 5:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - Parameters requested." << endl;
+        break;
+    case 6:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET INPUT returned." << endl;
+        break;
+    case 7:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET TITLE returned." << endl;
+        break;
+    case 8:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - SET COVAR returned." << endl;
+        break;
+    case 9:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - reserved." << endl;
+        break;
+    case 10:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - END returned." << endl;
+        break;
+    case 11:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - EXIT or STOP returned." << endl;
+        break;
+    case 12:
+        *fLog << inf << GetDescriptor() << " TMinuit::mnexcm - RETURN returned." << endl;
+        break;*/
+    }
+
+    return err;
+}
+
+Bool_t MJOptimize::Optimize(MEvtLoop &evtloop)
+{
+    if (fType==kNone)
+        return kTRUE;
+
+    gMinuit = new TMinuit(fParameters.GetSize());
+    //gMinuit->SetPrintLevel(-1);
+
+    gMinuit->SetFCN(fcn);
+    gMinuit->SetObjectFit(this);
+
+    //
+    // Set starting values and step sizes for parameters
+    //
+    for (Int_t i=0; i<fParameters.GetSize(); i++)
+    {
+        TString name = "par[";
+        name += i;
+        name += "]";
+        Double_t vinit = fParameters[i];
+        Double_t step  = fStep[i];
+
+        Double_t limlo = fLimLo[i];
+        Double_t limup = fLimUp[i];
+
+        Bool_t rc = gMinuit->DefineParameter(i, name, vinit, step, limlo, limup);
+        if (rc)
+        {
+            *fLog << err << dbginf << "Error in defining parameter #" << i << endl;
+            return kFALSE;
+        }
+
+        if (step==0)
+            gMinuit->FixParameter(i);
+    }
+
+    fEvtLoop = &evtloop;
+
+    TList *g=GetPlots();
+
+    // Now ready for minimization step:
+    TStopwatch clock;
+    clock.Start();
+    switch (fType)
+    {
+    case kSimplex:
+        Simplex(*gMinuit);
+        break;
+    case kMigrad:
+        Migrad(*gMinuit);
+        break;
+    case kMinimize:
+        Minimize(*gMinuit);
+        break;
+    case kMinos:
+        Minos(*gMinuit);
+        break;
+    case kImprove:
+        Improve(*gMinuit);
+        break;
+    case kSeek:
+        Seek(*gMinuit);
+        break;
+    case kNone: // Should never happen
+        return kFALSE;
+    }
+    clock.Stop();
+    clock.Print();
+
+    if (evtloop.GetDisplay()!=fDisplay)
+    {
+        *fLog << inf << "Optimization aborted by user." << endl;
+        fDisplay = 0;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Resulting Chisq: " << gMinuit->fAmin << endl;
+
+    //
+    // Update values of fA, fB:
+    //
+    for (Int_t i=0; i<fParameters.GetSize(); i++)
+    {
+        Double_t x1, x2;
+        gMinuit->GetParameter(i,x1,x2);
+        fParameters[i] = x1;
+        cout << i << ": " << fParameters[i] << endl;
+
+        AddPoint(g, i, x1);
+    }
+    AddPoint(g, fParameters.GetSize(), gMinuit->fAmin);
+
+    delete gMinuit;
+
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Optimize allows to use the optimizing by an eventloop based on
+// some requirements.
+//
+// 1) The tasklist to be executed must have the name MTaskList and
+//    be an entry in the parameterlist.
+//
+// 2) The reading task (MReadMarsFile, MMatrixLoop) must have the name
+//    "MRead". If it derives from MRead Rewind() must be implemented,
+//    otherwise it must start reading from scratch each time its
+//    PreProcess is called.
+//
+// 3) The parameters to be optimized must be accessed through (currently)
+//    a single parameter container (MParContainer) called MParameters.
+//    The parameters are set through SetVariables.
+//
+// 4) The result of a single function call for minimization (eg. chisquare)
+//    must be available after the eventloop in a container of type
+//    MParameterD with the name "MinimizationResult".
+//
+// 5) The parameters to start with must have been set using
+//    MJOptimize::SetParameter or MJOptimize::SetParameters and
+//    MJOptimize::FixParameter
+//
+// The behaviour of the optimization can be changed using:
+//  void SetNumEvents(UInt_t n);
+//  void SetDebug(UInt_t n);
+//  void SetOptimizer(Optimizer_t o);
+//
+// After optimization the resulting parameters are set and another eventloop
+// with a MStatusDisplay is set is called. The resulting parameters can be
+// accessed using: GetParameters()
+//
+// To be fixed:
+//  - MStatusDisplay should show status while optimization is running
+//  - write result into MStatusDisplay
+//  - save result
+//
+Bool_t MJOptimize::Optimize(MParList &parlist)
+{
+    // Checks to make sure, that fcn doesn't crash
+    if (!parlist.FindCreateObj("MParameterD", "MinimizationValue"))
+        return kFALSE;
+
+    if (!parlist.FindObject("MParameters", "MParContainer"))
+    {
+        *fLog << err << "MParameters [MParContainer] not found... abort." << endl;
+        return kFALSE;
+    }
+
+    TString txt("Starting ");
+    switch (fType)
+    {
+    case kMigrad:    txt += "Migrad";    break;
+    case kMinimize:  txt += "Minimize";  break;
+    case kMinos:     txt += "Minot";     break;
+    case kImprove:   txt += "Improve";   break;
+    case kSimplex:   txt += "Simplex";   break;
+    case kSeek:      txt += "Seek";      break;
+    case kNone:      txt += "no";        break;
+    }
+    txt += " optimization";
+
+    fLog->Separator(txt);
+
+    // Setup eventloop
+    MEvtLoop evtloop;
+    evtloop.SetParList(&parlist);
+    evtloop.SetDisplay(fDisplay); // set display for evtloop and all childs
+    parlist.SetDisplay(0);        // reset display for all contents of parlist and tasklist
+    evtloop.SetPrivateDisplay();  // prevent display from being cascaded again in PreProcess
+
+    *fLog << inf << "Number of Parameters: " << fParameters.GetSize() << endl;
+
+    if (!Optimize(evtloop))
+        return kFALSE;
+
+    gMinuit = 0;
+
+    fEvtLoop->SetDisplay(fDisplay);
+    return Fcn(fParameters);
+    // Done already in Fcn
+    // list.SetVariables(fParameters);
+}
+
+void MJOptimize::AddRulesToMatrix(MHMatrix &m) const
+{
+    TIter Next1(&fRules);
+    TObject *o1=0;
+    while ((o1=Next1()))
+        m.AddColumn(o1->GetName());
+}
+
+//------------------------------------------------------------------------
+//
+// Fill matrix m by using read. Use rules as a filter if userules.
+//
+Bool_t MJOptimize::FillMatrix(MReadTree &read, MParList &parlist, Bool_t userules)
+{
+    MHMatrix *m = (MHMatrix*)parlist.FindObject("M", "MHMatrix");
+    if (!m)
+    {
+        *fLog << err << "MJOptimize::FillMatrix - ERROR: M [MHMatrix] not found in parlist... abort." << endl;
+        return kFALSE;
+    }
+
+    m->Print("cols");
+
+    //MParList parlist;
+
+    //    MGeomCamMagic cam;
+    //    parlist.AddToList(&cam);
+
+    MTaskList tlist;
+    parlist.Replace(&tlist);
+
+    MFillH fillh(m);
+
+    tlist.AddToList(&read);
+
+    MFilterList list;
+    if (!list.AddToList(fPreCuts))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList for fPreCuts failed!" << endl;
+    if (userules)
+        SetupFilters(list);
+    list.SetName("PreCuts");  // reset Name      set by SetupFilters
+    list.SetInverted(kFALSE); // reset inversion set by SetupFilters
+    fillh.SetFilter(&list);
+    tlist.AddToList(&list);
+
+    tlist.AddToList(&fillh);
+
+    MEvtLoop fillloop;
+    fillloop.SetParList(&parlist);
+    fillloop.SetDisplay(fDisplay);
+    if (!fillloop.Eventloop(fNumEvents))
+    {
+        *fLog << err << "Filling matrix failed..." << endl;
+        return kFALSE;
+    }
+    tlist.PrintStatistics();
+
+    *fLog << inf << "Read events from file '" << read.GetFileName() << "'" << endl;
+
+    if (fillloop.GetDisplay()!=fDisplay)
+    {
+        fDisplay = 0;
+        *fLog << inf << "Optimization aborted by user." << endl;
+        return kFALSE;
+    }
+
+    m->Print("size");
+
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Adds all filters to MFilterList
+//
+void MJOptimize::SetupFilters(MFilterList &list, MFilter *filter) const
+{
+    list.SetName("MParameters");
+    list.SetInverted();
+
+    if (filter)
+    {
+        if (fFilter.GetSize()>0)
+        {
+            *fLog << inf;
+            *fLog << "INFORMATION - You are using an  external filter and internal filters." << endl;
+            *fLog << "              Please make sure that all parameters '[i]' are starting" << endl;
+            *fLog << "              behind the number of parameters of the external filter." << endl;
+        }
+        list.AddToList(filter);
+    }
+
+    if (!list.AddToList(fFilter))
+        *fLog << err << "ERROR - Calling MFilterList::AddToList fFilter failed!" << endl;
+
+    *fLog << inf << "Filter: ";
+    list.Print();
+    *fLog << endl;
+}
+
+//------------------------------------------------------------------------
+//
+Bool_t MJOptimize::Run(const char *fname, MFilter *filter, MAlphaFitter *fit)
+{
+    if (fParameters.GetSize()==0)
+    {
+        *fLog << err << "Sorry, no parameters defined." << endl;
+        return kFALSE;
+    }
+
+    fLog->Separator("Preparing On-only-optimization");
+
+    MParList parlist;
+
+    MGeomCamMagic geom; // For GetConvMm2Deg
+    parlist.AddToList(&geom);
+
+    MHMatrix m("M");
+    AddRulesToMatrix(m);
+    parlist.AddToList(&m);
+
+    MHAlpha hist;
+    hist.SkipHistTime();
+    hist.SkipHistTheta();
+    hist.SkipHistEnergy();
+    hist.InitMapping(&m); 
+
+    if (filter && filter->InheritsFrom(MFSupercuts::Class()))
+        ((MFSupercuts*)filter)->InitMapping(&m);
+
+    MReadTree read("Events");
+    read.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
+    if (fname)
+        read.AddFile(fname);
+    else
+        AddSequences(read, fNamesOn);
+    if (!FillMatrix(read, parlist))
+        return kFALSE;
+
+    MTaskList tasklist;
+    parlist.Replace(&tasklist);
+    if (fit)
+        parlist.AddToList(fit);
+
+    MFilterList list;
+    SetupFilters(list, filter);
+
+    MContinue contin(&list);
+    parlist.AddToList(&list);
+
+    MFillH fill(&hist);
+
+    MMatrixLoop loop(&m);
+
+    tasklist.AddToList(&loop);
+    tasklist.AddToList(&list);
+    tasklist.AddToList(&contin);
+    tasklist.AddToList(&fill);
+
+    if (!Optimize(parlist))
+        return kFALSE;
+
+    TObjArray cont;
+    cont.Add(&contin);
+    return WriteContainer(cont, fNameOut);
+}
+
+//------------------------------------------------------------------------
+//
+// Make sure, that filter->GetDataMember is correctly implemented!!!!
+//
+Bool_t MJOptimize::RunOnOff(const char *fname, MFilter *filter, MAlphaFitter *fit, const char *tree)
+{
+    if (fParameters.GetSize()==0)
+    {
+        *fLog << err << "Sorry, no parameters defined." << endl;
+        return kFALSE;
+    }
+
+    fLog->Separator("Preparing On/Off-optimization");
+
+    MParList parlist;
+
+    MGeomCamMagic geom; // For GetConvMm2Deg
+    parlist.AddToList(&geom);
+
+    MHMatrix m("M");
+    AddRulesToMatrix(m);
+    parlist.AddToList(&m);
+
+    const Int_t idxdatatype = m.AddColumn("DataType.fVal");
+
+    MHAlpha histon, histof("MHAlphaOff");
+    histon.SkipHistTime();
+    histon.SkipHistTheta();
+    //histon.SkipHistEnergy();
+    histof.SkipHistTime();
+    histof.SkipHistTheta();
+    //histof.SkipHistEnergy();
+    // FIXME: MHillasSrc.fAlpha is added twice!
+    histon.InitMapping(&m, 1);
+    histof.InitMapping(&m, 1);
+
+    if (filter && filter->InheritsFrom(MFSupercuts::Class()))
+        ((MFSupercuts*)filter)->InitMapping(&m);
+
+    parlist.AddToList(&histon);
+    parlist.AddToList(&histof);
+
+    if (fname)
+    {
+        MReadTree read(tree);
+        read.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
+        read.AddFile(fname);
+        if (!FillMatrix(read, parlist))
+            return kFALSE;
+    }
+    else
+    {
+        MParameterI par("DataType");
+        parlist.AddToList(&par);
+
+        gLog.Separator("Reading On-Data");
+        par.SetVal(1);
+        MReadTree readon(tree);
+        readon.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
+        AddSequences(readon, fNamesOn);
+        if (!FillMatrix(readon, parlist))
+            return kFALSE;
+
+        gLog.Separator("Reading Off-Data");
+        par.SetVal(0);
+        MReadTree readoff(tree);
+        readoff.DisableAutoScheme(); // AutoScheme doesn't seem to be faster!
+        AddSequences(readoff, fNamesOff);
+        if (!FillMatrix(readoff, parlist))
+            return kFALSE;
+    }
+
+    MTaskList tasklist;
+    parlist.Replace(&tasklist);
+    if (fit)
+        parlist.AddToList(fit);
+
+    MFilterList list;
+    SetupFilters(list, filter);
+
+    MContinue contin(&list);
+    parlist.AddToList(&list);
+
+    MFillH fillon(&histon, "", "FillHistOn");
+    MFillH fillof(&histof, "", "FillHistOff");
+
+    MF f0(Form("M[%d]<0.5", idxdatatype), "FilterOffData");
+    MF f1(Form("M[%d]>0.5", idxdatatype), "FilterOnData");
+
+    fillof.SetFilter(&f0);
+    fillon.SetFilter(&f1);
+
+    MMatrixLoop loop(&m);
+
+    tasklist.AddToList(&loop);
+    tasklist.AddToList(&list);
+    tasklist.AddToList(&contin);
+    tasklist.AddToList(&f0);
+    tasklist.AddToList(&f1);
+    tasklist.AddToList(&fillof);
+    tasklist.AddToList(&fillon);
+
+    if (!Optimize(parlist))
+        return kFALSE;
+
+    TObjArray cont;
+    cont.Add(&contin);
+    return WriteContainer(cont, fNameOut);
+}
+
+//------------------------------------------------------------------------
+//
+// Read all events from file which do match rules and optimize
+// energy estimator.
+//
+Bool_t MJOptimize::RunEnergy(const char *fname, const char *rule)
+{
+    if (fParameters.GetSize()==0)
+    {
+        *fLog << err << "Sorry, no parameters defined." << endl;
+        return kFALSE;
+    }
+
+    fLog->Separator("Preparing Energy optimization");
+
+    MParList parlist;
+
+    MGeomCamMagic geom; // For GetConvMm2Deg
+    parlist.AddToList(&geom);
+
+    MHMatrix m("M");
+    AddRulesToMatrix(m);
+    parlist.AddToList(&m);
+
+    MEnergyEstimate est("MParameters");
+    est.SetRule(rule);
+    parlist.AddToList(&est);
+
+    MHEnergyEst hist;
+    hist.InitMapping(&m); 
+
+    MReadTree read("Events");
+    //read.DisableAutoScheme();
+    if (fname)
+        read.AddFile(fname);
+    else
+        AddSequences(read, fNamesOn);
+    if (!FillMatrix(read, parlist, kTRUE))
+        return kFALSE;
+
+    MTaskList tasklist;
+    parlist.Replace(&tasklist);
+
+    MFillH fill(&hist);
+
+    MMatrixLoop loop(&m);
+
+    tasklist.AddToList(&loop);
+    tasklist.AddToList(&est);
+    tasklist.AddToList(&fill);
+
+    if (!Optimize(parlist))
+        return kFALSE;
+
+    TObjArray cont;
+    cont.Add(&est);
+    return WriteContainer(cont, fNameOut);
+}
Index: /tags/Mars-V0.9/mjobs/MJOptimize.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJOptimize.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJOptimize.h	(revision 9772)
@@ -0,0 +1,191 @@
+#ifndef MARS_MJOptimize
+#define MARS_MJOptimize
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TMinuit;
+
+class MAlphaFitter;
+
+class MEvtLoop;
+class MParList;
+class MFilter;
+class MFilterList;
+class MFitParameters;
+class MFitParametersCalc;
+
+class MHMatrix;
+class MGeomCam;
+class MRead;
+class MReadTree;
+
+class MJOptimize : public MJob
+{
+public:
+    enum Optimizer_t
+    {
+        kMigrad,      // Minimize by the method of Migrad
+        kSimplex,     // Minimize by the method of Simplex
+        kMinimize,    // Migrad + Simplex (if Migrad fails)
+        kMinos,       // Minos error determination
+        kImprove,     // Local minimum search
+        kSeek,        // Minimize by the method of Monte Carlo
+        kNone         // Skip optimization
+    };
+
+private:
+    Int_t fDebug;     // -1 no output, 0 MJOptimize output, 1 PrintStatistics output
+    Int_t fNumEvents;
+
+    TList fRules;
+    TList fFilter;
+    TList fPreCuts;
+
+    TList fNamesOn;
+    TList fNamesOff;
+
+    TString fNameOut;
+
+    void AddPoint(TList *l, Int_t idx, Float_t val) const;
+    TList *GetPlots() const;
+
+    void AddRulesToMatrix(MHMatrix &m) const;
+    void SetupFilters(MFilterList &list, MFilter *filter=0) const;
+    Bool_t FillMatrix(MReadTree &read, MParList &l, Bool_t userules=kFALSE);
+
+    MEvtLoop *fEvtLoop;    //!
+
+    Bool_t AddSequences(MRead &read, TList &list) const;
+
+    // Minuit Interface
+    static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag);
+    Double_t Fcn(const TArrayD &par, TMinuit *minuit=0);
+
+    Int_t Minuit(TMinuit &minuit, const char *cmd) const;
+    Int_t Migrad(TMinuit &minuit) const   { return Minuit(minuit, "MIGRAD"); }
+    Int_t Simplex(TMinuit &minuit) const  { return Minuit(minuit, "SIMPLEX"); }
+    Int_t Minimize(TMinuit &minuit) const { return Minuit(minuit, "MINIMIZE"); }
+    Int_t Seek(TMinuit &minuit) const     { return Minuit(minuit, "SEEK"); }
+    Int_t Improve(TMinuit &minuit) const  { return Minuit(minuit, "IMPROVE"); }
+    Int_t Minos(TMinuit &minuit) const    { return Minuit(minuit, "MINOS"); }
+
+    TArrayD fParameters;   //!
+    TArrayD fLimLo;        //!
+    TArrayD fLimUp;        //!
+    TArrayD fStep;         //!
+
+    Optimizer_t fType;
+    UInt_t  fNumMaxCalls;
+    Float_t fTolerance;
+
+    Bool_t Optimize(MEvtLoop &evtloop);
+
+public:
+    MJOptimize();
+
+    // I/O
+    void AddSequenceOn(const char *fname, const char *dir="");
+    void AddSequenceOff(const char *fname, const char *dir="");
+
+    void ResetSequences();
+
+    // Interface for filter cuts
+    Int_t AddParameter(const char *rule);
+    void AddFilter(const char *rule);
+    void AddPreCut(const char *rule);
+
+    // Steering of optimization
+    void SetNumEvents(UInt_t n);
+    void SetDebug(UInt_t n);
+    void SetNameOut(const char *name="") { fNameOut = name; }
+    void SetOptimizer(Optimizer_t o);
+    void SetNumMaxCalls(UInt_t num=0) { fNumMaxCalls=num; }
+    void SetTolerance(Float_t tol=0)  { fTolerance=tol; }
+
+    // Parameter access
+    void SetParameters(const TArrayD &par);
+    void SetParameter(Int_t idx, Double_t start, Double_t lo=0, Double_t up=0, Double_t step=-1)
+    {
+        if (fParameters.GetSize()<=idx)
+        {
+            fParameters.Set(idx+1);
+            fLimLo.Set(idx+1);
+            fLimUp.Set(idx+1);
+            fStep.Set(idx+1);
+        }
+
+        fParameters[idx] = start;
+        fLimLo[idx] = lo;
+        fLimUp[idx] = up;
+        if (step<=0)
+            fStep[idx] = start==0 ? 0.1 : TMath::Abs(start*0.15);
+        else
+            fStep[idx] = step;
+    }
+    void FixParameter(Int_t idx, Double_t start)
+    {
+        if (fParameters.GetSize()<=idx)
+        {
+            fParameters.Set(idx+1);
+            fLimLo.Set(idx+1);
+            fLimUp.Set(idx+1);
+            fStep.Set(idx+1);
+        }
+
+        fParameters[idx] = start;
+        fLimLo[idx] = 0;
+        fLimUp[idx] = 0;
+        fStep[idx]  = 0;
+    }
+
+    const TArrayD &GetParameters() const { return fParameters; }
+
+    // Generalized optimizing routines
+    Bool_t Optimize(MParList &list);
+
+    // Special optimizing routines
+    Bool_t Run(const char *fname, MFilter *filter, MAlphaFitter *fit=0);
+    Bool_t Run(const char *fname, MAlphaFitter *fit=0)
+    {
+        return Run(fname, 0, fit);
+    }
+
+    Bool_t Run(MFilter *filter, MAlphaFitter *fit=0)
+    {
+        return Run(0, filter, fit);
+    }
+    Bool_t Run(MAlphaFitter *fit=0)
+    {
+        return Run(0, 0, fit);
+    }
+
+    Bool_t RunOnOff(const char *fname, MFilter *filter, MAlphaFitter *fit=0, const char *tree="Events");
+    Bool_t RunOnOff(const char *fname, MAlphaFitter *fit=0, const char *tree="Events")
+    {
+        return RunOnOff(fname, 0, fit, tree);
+    }
+    Bool_t RunEnergy(const char *fname, const char *rule);
+
+    Bool_t RunOnOff(MFilter *filter, MAlphaFitter *fit=0, const char *tree="Events")
+    {
+        return RunOnOff(0, filter, fit, tree);
+    }
+    Bool_t RunOnOff(MAlphaFitter *fit=0, const char *tree="Events")
+    {
+        return RunOnOff(fit, tree);
+    }
+    Bool_t RunEnergy(const char *rule)
+    {
+        return RunEnergy(0, rule);
+    }
+
+    ClassDef(MJOptimize, 0) // Class for optimization of the Supercuts
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJPedestal.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJPedestal.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJPedestal.cc	(revision 9772)
@@ -0,0 +1,1357 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Markus Gaug, 4/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJPedestal
+//
+// Resource file entries are case sensitive!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJPedestal.h"
+
+// C/C++ includes
+#include <fstream>
+
+// root classes
+#include <TF1.h>
+#include <TEnv.h>
+#include <TFile.h>
+#include <TLine.h>
+#include <TLatex.h>
+#include <TString.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+#include <TLegend.h>
+#include <TPad.h>
+#include <TEnv.h>
+#include <TH2F.h>
+
+// mars core
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTaskEnv.h"
+#include "MSequence.h"
+#include "MRunIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+#include "MFEventSelector.h"
+
+// Other basic classes
+#include "MExtractTimeAndCharge.h"
+
+// parameter containers
+#include "MGeomCam.h"
+#include "MHCamera.h"
+#include "MPedestalPix.h"
+
+#include "MCalibrationPedCam.h"
+#include "MCalibrationPix.h"
+#include "MHPedestalPix.h"
+#include "MHCalibrationPulseTimeCam.h"
+#include "MCalibrationPulseTimeCam.h"
+
+// tasks
+#include "MReadMarsFile.h"
+#include "MRawFileRead.h"
+#include "MRawEvtData.h"
+#include "MGeomApply.h"
+#include "MBadPixelsMerge.h"
+#include "MFillH.h"
+#include "MPedCalcPedRun.h"
+#include "MPedCalcFromLoGain.h"
+#include "MFTriggerPattern.h"
+
+ClassImp(MJPedestal);
+
+using namespace std;
+
+const TString  MJPedestal::fgReferenceFile   = "mjobs/pedestalref.rc";
+const TString  MJPedestal::fgBadPixelsFile   = "mjobs/badpixels_0_559.rc";
+const Float_t  MJPedestal::fgExtractWinLeft  = 2.5;
+const Float_t  MJPedestal::fgExtractWinRight = 4.5;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fExtractor to NULL, 
+// - fExtractType to kUsePedRun
+// - fStorage to Normal Storage
+// - fExtractorResolution to kFALSE
+//
+MJPedestal::MJPedestal(const char *name, const char *title) 
+    : fExtractor(NULL), fDisplayType(kDisplayDataCheck),
+      fExtractType(kUsePedRun), fExtractionType(kFundamental), fIsUseHists(kFALSE)
+{
+    fName  = name  ? name  : "MJPedestal";
+    fTitle = title ? title : "Tool to create a pedestal file (MPedestalCam)";
+
+    SetUsePedRun();
+    SetPathIn("");
+    SetReferenceFile();
+    SetBadPixelsFile();
+
+    SetExtractWinLeft();
+    SetExtractWinRight();
+    //
+    // Default references for case that no value references file is there
+    // (should not occur)
+    //
+
+    fPedestalMin                 = 4.;
+    fPedestalMax                 = 16.;
+    fPedRmsMin                   = 0.;
+    fPedRmsMax                   = 20.;
+    fRefPedClosedLids            = 9.635;
+    fRefPedExtraGalactic         = 9.93;
+    fRefPedGalactic              = 10.03;
+    fRefPedRmsClosedLidsInner    = 1.7;
+    fRefPedRmsExtraGalacticInner = 5.6;
+    fRefPedRmsGalacticInner      = 6.92;
+    fRefPedRmsClosedLidsOuter    = 1.7;
+    fRefPedRmsExtraGalacticOuter = 3.35;
+    fRefPedRmsGalacticOuter      = 4.2;
+}
+
+MJPedestal::~MJPedestal()
+{
+    if (fExtractor)
+        delete fExtractor;
+}
+
+const char* MJPedestal::GetOutputFile() const
+{
+    const TString name(GetOutputFileName());
+    if (name.IsNull())
+        return "";
+
+    return Form("%s/%s", fPathOut.Data(), name.Data());
+}
+
+const char* MJPedestal::GetOutputFileName() const
+{
+
+  if (fSequence.IsValid())
+    return Form("pedest%08d.root", fSequence.GetSequence());
+  
+  if (!fRuns)
+    return "";
+  
+  return Form("%s-F0.root", (const char*)fRuns->GetRunsAsFileName());
+}
+
+//---------------------------------------------------------------------------------
+//
+// Try to read an existing MPedestalCam from a previously created output file. 
+// If found, also an MBadPixelsCam and the corresponding display is read.
+//
+// In case of Storage type "kNoStorage" or if the file is not found or the 
+// MPedestalCam cannot be read, return kFALSE, otherwise kTRUE.
+//
+Bool_t MJPedestal::ReadPedestalCam()
+{
+    const TString fname = GetOutputFile();
+
+    const Bool_t fileexist = !gSystem->AccessPathName(fname, kFileExists);
+    if (!fileexist)
+      {
+        *fLog << inf << "Input file " << fname << " not found, will create pedestals" << endl;
+        return kFALSE;
+      }
+
+    *fLog << inf << "Reading pedestals from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (fPedestalCamIn.Read()<=0)
+    {
+        *fLog << err << "Unable to read incoming MPedestalCam from " << fname << endl;
+        return kFALSE;
+    }
+
+    if (fPedestalCamOut.Read()<=0)
+    {
+        *fLog << err << "Unable to read outgoing MPedestalCam from " << fname << endl;
+        return kFALSE;
+    }
+
+    if (file.FindKey("MBadPixelsCam"))
+    {
+        MBadPixelsCam bad;
+        if (bad.Read()<=0)
+        {
+            *fLog << err << "Unable to read MBadPixelsCam from " << fname << endl;
+            return kFALSE;
+        }
+        fBadPixels.Merge(bad);
+    }
+
+    if (fDisplay && !fDisplay->GetCanvas("Pedestals"))
+        fDisplay->Read();
+
+    return kTRUE;
+}
+
+MExtractor *MJPedestal::ReadCalibration() const
+{
+    const TString fname = Form("%s/calib%08d.root",fPathIn.Data(), fSequence.GetSequence());
+
+    *fLog << inf << "Reading extractor from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+        return NULL;
+    }
+
+    TObject *o = file.Get("ExtractSignal");
+    if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
+        return NULL;
+    }
+
+    return o ? (MExtractor*)o->Clone("ExtractSignal") : NULL;
+}
+
+Bool_t MJPedestal::WriteExtractor() const
+{
+
+  const TString name  = Form("pedy%08d.root",fSequence.GetSequence());
+  const TString fname = Form("%s/%s",fPathIn.Data(),name.Data());
+
+  *fLog << inf << "Updating extractor in file: " << fname << endl;
+
+  TFile file(fname, fOverwrite?"RECREATE":"NEW");
+  if (!file.IsOpen())
+    {
+      *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+      *fLog << err << dbginf << "Maybe, file " << fname << " already exists, call callisto with option -f then." << endl;
+      return kFALSE;
+    }
+
+  TObjArray cont;
+  cont.Add(fExtractor);
+
+  return WriteContainer(cont);
+}
+
+//---------------------------------------------------------------------------------
+//
+// Display the results. 
+// If Display type "kDataCheck" was chosen, also the reference lines are displayed.
+//
+void MJPedestal::DisplayResult(MParList &plist)
+{
+    if (!fDisplay)
+        return;
+
+    //
+    // Update display
+    //
+    TString title = fDisplay->GetTitle();
+    title += "--  Pedestal ";
+    if (fSequence.IsValid())
+        title += fSequence.GetName();
+    else
+        if (fRuns)  // FIXME: What to do if an environmentfile was used?
+            title += fRuns->GetRunsAsString();
+    title += "  --";
+    fDisplay->SetTitle(title);
+
+    //
+    // Get container from list
+    //
+    MGeomCam           &geomcam   = *(MGeomCam*)plist.FindObject("MGeomCam");
+    //    MCalibrationPedCam &calpedcam = *(MCalibrationPedCam*)plist.FindObject("MCalibrationPedCam");
+
+    //
+    // Create container to display
+    //
+    MHCamera disp0 (geomcam, "MPedestalCam;ped", "Mean Pedestal");
+    MHCamera disp1 (geomcam, "MPedestalCam;RMS", "Pedestal RMS");
+    MHCamera disp2 (geomcam, "MCalibPedCam;histmean", "Mean Pedestal (Hist.)");
+    MHCamera disp3 (geomcam, "MCalibPedCam;histsigma", "Pedestal RMS (Hist.)");
+    MHCamera disp4 (geomcam, "MCalibPedCam;ped", "Mean Pedestal");
+    MHCamera disp5 (geomcam, "MCalibPedCam;RMS", "Pedestal RMS");
+    MHCamera disp6 (geomcam, "MCalibDiffCam;ped", "Diff. Mean Pedestal (Hist.)");
+    MHCamera disp7 (geomcam, "MCalibDiffCam;RMS", "Diff. Pedestal RMS (Hist.)");
+    MHCamera disp8 (geomcam, "MCalibDiffCam;ped", "Diff. Mean Pedestal");
+    MHCamera disp9 (geomcam, "MCalibDiffCam;AbsRMS", "Diff. Abs. Pedestal RMS");
+    MHCamera disp10(geomcam, "MCalibDiffCam;RelRMS", "Diff. Rel. Pedestal RMS");
+
+    disp0.SetCamContent(fPedestalCamOut, 0);
+    disp0.SetCamError  (fPedestalCamOut, 1);
+
+    disp1.SetCamContent(fPedestalCamOut, 2);
+    disp1.SetCamError  (fPedestalCamOut, 3);
+
+    /*
+    if (fIsUseHists)
+      {
+        disp2.SetCamContent(calpedcam, 0);
+        disp2.SetCamError  (calpedcam, 1);
+
+        disp3.SetCamContent(calpedcam, 2);
+        disp3.SetCamError  (calpedcam, 3);
+
+        disp4.SetCamContent(calpedcam, 5);
+        disp4.SetCamError  (calpedcam, 6);
+
+        disp5.SetCamContent(calpedcam, 7);
+        disp5.SetCamError  (calpedcam, 8);
+
+        for (UInt_t i=0;i<geomcam.GetNumPixels();i++)
+          {
+
+            MPedestalPix    &ped  = fPedestalCamOut[i];
+            MCalibrationPix &hist = calpedcam [i];
+            MBadPixelsPix &bad  = fBadPixels[i];
+
+            if (bad.IsUnsuitable())
+              continue;
+
+            disp6.Fill(i,ped.GetPedestal()-hist.GetHiGainMean());
+            disp6.SetUsed(i);
+
+            disp7.Fill(i,hist.GetHiGainSigma()-ped.GetPedestalRms());
+            if (TMath::Abs(ped.GetPedestalRms()-hist.GetHiGainSigma()) < 4.0)
+              disp7.SetUsed(i);
+
+            disp8.Fill(i,ped.GetPedestal()-hist.GetLoGainMean());
+            disp8.SetUsed(i);
+
+            disp9.Fill(i,hist.GetLoGainSigma()-ped.GetPedestalRms());
+            if (TMath::Abs(hist.GetLoGainSigma() - ped.GetPedestalRms()) < 4.0)
+              disp9.SetUsed(i);
+          }
+      }
+    */
+    
+    if (fExtractionType!=kFundamental/*fExtractorResolution*/)
+      {
+        for (UInt_t i=0;i<geomcam.GetNumPixels();i++)
+          {
+
+            MPedestalPix &pedo  = fPedestalCamOut[i];
+            MPedestalPix &pedi  = fPedestalCamIn[i];
+            MBadPixelsPix &bad  = fBadPixels[i];
+
+            if (bad.IsUnsuitable())
+              continue;
+
+            const Float_t diff = pedo.GetPedestalRms()-pedi.GetPedestalRms();
+            const Float_t sum  = 0.5*(pedo.GetPedestalRms()+pedi.GetPedestalRms());
+
+            disp9.Fill(i,pedo.GetPedestalRms()-pedi.GetPedestalRms());
+            if (pedo.IsValid() && pedi.IsValid())
+              disp9.SetUsed(i);
+
+            disp10.Fill(i,sum == 0. ? 0. : diff/sum);
+            if (pedo.IsValid() && pedi.IsValid() && sum != 0.)
+              disp10.SetUsed(i);
+          }
+      }
+
+    disp0.SetYTitle("P [cts/slice]");
+    disp1.SetYTitle("P_{rms} [cts/slice]");
+    disp2.SetYTitle("Hist. Mean  [cts/slice]");
+    disp3.SetYTitle("Hist. Sigma [cts/slice]");
+    disp4.SetYTitle("Calc. Mean  [cts/slice]");
+    disp5.SetYTitle("Calc. RMS   [cts/slice]");
+    disp6.SetYTitle("Diff. Mean  [cts/slice]");
+    disp7.SetYTitle("Diff. RMS   [cts/slice]");
+    disp8.SetYTitle("Diff. Mean  [cts/slice]");
+    disp9.SetYTitle("Abs.Diff.RMS [cts/slice]");
+    disp10.SetYTitle("Rel.Diff.RMS [1]");
+
+    //
+    // Display data
+    //
+    if (fDisplayType != kDisplayDataCheck &&  fExtractionType==kFundamental/*fExtractorResolution*/)
+      {
+        TCanvas &c3 = fDisplay->AddTab("Pedestals");
+        c3.Divide(2,3);
+        
+        disp0.CamDraw(c3, 1, 2, 1);
+        disp1.CamDraw(c3, 2, 2, 6);
+        return;
+      }
+    
+#if 0
+    if (fIsUseHists)
+      {
+        
+        TCanvas &c3 = fDisplay->AddTab("Extractor Hist.");
+        c3.Divide(2,3);
+
+        disp2.CamDraw(c3, 1, 2, 1);
+        disp3.CamDraw(c3, 2, 2, 5);
+
+        TCanvas &c4 = fDisplay->AddTab("Extractor Calc.");
+        c4.Divide(2,3);
+        
+        disp4.CamDraw(c4, 1, 2, 1);
+        disp5.CamDraw(c4, 2, 2, 5);
+
+        /*
+        TCanvas &c5 = fDisplay->AddTab("Difference Hist.");
+        c5.Divide(2,3);
+        
+        disp6.CamDraw(c5, 1, 2, 1);
+        disp7.CamDraw(c5, 2, 2, 5);
+        */
+
+        TCanvas &c6 = fDisplay->AddTab("Difference Calc.");
+        c6.Divide(2,3);
+        
+        disp8.CamDraw(c6, 1, 2, 1);
+        disp9.CamDraw(c6, 2, 2, 5);
+        return;
+      }
+#endif
+    if (fDisplayType == kDisplayDataCheck)
+      {
+
+        TCanvas &c3 = fDisplay->AddTab(fExtractionType!=kFundamental/*fExtractorResolution*/ ? "PedExtrd" : "Ped");
+        c3.Divide(2,3);
+        
+        c3.cd(1);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+        MHCamera *obj1=(MHCamera*)disp0.DrawCopy("hist");
+        //
+        // for the datacheck, fix the ranges!!
+        //
+        if (fExtractionType==kFundamental/*!fExtractorResolution*/)
+          {
+            obj1->SetMinimum(fPedestalMin);
+            obj1->SetMaximum(fPedestalMax);
+	  }
+	//
+	// Set the datacheck sizes:
+	//
+	FixDataCheckHist((TH1D*)obj1);
+	//
+	// set reference lines
+	//
+	DisplayReferenceLines(obj1,0);
+        //
+        // end reference lines
+        //
+        c3.cd(3);
+        gPad->SetBorderMode(0);
+        obj1->SetPrettyPalette();
+        obj1->Draw();
+        
+        c3.cd(5);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+        TH1D *obj2 = (TH1D*)obj1->Projection(obj1->GetName());
+        obj2->Draw();
+        obj2->SetBit(kCanDelete);
+        obj2->Fit("gaus","Q");
+        obj2->GetFunction("gaus")->SetLineColor(kYellow);
+        //
+        // Set the datacheck sizes:
+        //
+        FixDataCheckHist(obj2);
+        obj2->SetStats(1);
+        
+        c3.cd(2);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+        MHCamera *obj3=(MHCamera*)disp1.DrawCopy("hist");
+        //
+        // for the datacheck, fix the ranges!!
+        //
+        obj3->SetMinimum(fPedRmsMin);
+        obj3->SetMaximum(fPedRmsMax);
+        //
+        // Set the datacheck sizes:
+        //
+        FixDataCheckHist((TH1D*)obj3);
+        //
+        // set reference lines
+        //
+        DisplayReferenceLines(obj3,1);
+        
+        c3.cd(4);
+        gPad->SetBorderMode(0);
+        obj3->SetPrettyPalette();
+        obj3->Draw();
+
+        c3.cd(6);
+        gPad->SetBorderMode(0);
+        
+        if (geomcam.InheritsFrom("MGeomCamMagic"))
+          {
+            TArrayI inner(1);
+            inner[0] = 0;
+
+            TArrayI outer(1);
+            outer[0] = 1;
+            
+            TArrayI s0(6);
+            s0[0] = 6;
+            s0[1] = 1;
+            s0[2] = 2;
+            s0[3] = 3;
+            s0[4] = 4;
+            s0[5] = 5;
+            
+            TArrayI s1(3);
+            s1[0] = 6;
+            s1[1] = 1;
+            s1[2] = 2;
+            
+            TArrayI s2(3);
+            s2[0] = 3;
+            s2[1] = 4;
+            s2[2] = 5;
+            
+            TVirtualPad *pad = gPad;
+            pad->Divide(2,1);
+            
+            TH1D *inout[2];
+            inout[0] = disp1.ProjectionS(s0, inner, "Inner");
+            inout[1] = disp1.ProjectionS(s0, outer, "Outer");
+            FixDataCheckHist(inout[0]);
+            FixDataCheckHist(inout[1]);
+            
+            inout[0]->SetTitle(Form("%s %s",disp1.GetTitle(),"Inner"));
+            inout[1]->SetTitle(Form("%s %s",disp1.GetTitle(),"Outer"));
+            
+            
+            for (int i=0; i<2; i++)
+              {
+                pad->cd(i+1);
+                gPad->SetBorderMode(0);
+                gPad->SetTicks();
+                
+                inout[i]->SetDirectory(NULL);
+                inout[i]->SetLineColor(kRed+i);
+                inout[i]->SetBit(kCanDelete);
+                inout[i]->Draw();
+                inout[i]->Fit("gaus", "Q");
+                
+                TLegend *leg2 = new TLegend(0.6,0.2,0.9,0.55);
+                leg2->SetHeader(inout[i]->GetName());
+                leg2->AddEntry(inout[i], inout[i]->GetName(), "l");
+                
+                //
+                // Display the outliers as dead and noisy pixels
+                //
+                DisplayOutliers(inout[i]);
+                
+                //
+                // Display the two half of the camera separately
+                //
+                TH1D *half[2];
+                half[0] = disp1.ProjectionS(s1, i==0 ? inner : outer , "Sector 6-1-2");
+                half[1] = disp1.ProjectionS(s2, i==0 ? inner : outer , "Sector 3-4-5");
+                
+                for (int j=0; j<2; j++)
+                  {
+                    half[j]->SetLineColor(kRed+i+2*j+1);
+                    half[j]->SetDirectory(NULL);
+                    half[j]->SetBit(kCanDelete);
+                    half[j]->Draw("same");
+                    leg2->AddEntry(half[j], half[j]->GetName(), "l");
+                  }
+                leg2->Draw();
+                delete leg2;
+              }
+            return;
+          }
+      }
+    
+    if (fExtractionType!=kFundamental/*fExtractorResolution*/)
+      {
+            
+          TCanvas &c3 = fDisplay->AddTab(fExtractionType==kWithExtractor?"PedExtrd":"PedRndm");
+          c3.Divide(2,3);
+
+          disp0.CamDraw(c3, 1, 2, 1);
+          disp1.CamDraw(c3, 2, 2, 6);
+
+          TCanvas &c13 = fDisplay->AddTab(fExtractionType==kWithExtractor?"DiffExtrd":"DiffRndm");
+          c13.Divide(2,3);
+
+          disp9.CamDraw(c13, 1, 2, 5);
+          disp10.CamDraw(c13, 2, 2, 5);
+          return;
+      }
+}
+
+
+void  MJPedestal::DisplayReferenceLines(MHCamera *cam, const Int_t what) const
+{
+
+  Double_t x = cam->GetNbinsX();
+  
+  const MGeomCam *geom = cam->GetGeometry();
+
+  if (geom->InheritsFrom("MGeomCamMagic"))
+    x = what ? 397 : cam->GetNbinsX();
+
+  TLine line;
+  line.SetLineStyle(kDashed);
+  line.SetLineWidth(3);
+  line.SetLineColor(kBlue);
+  
+  TLegend *leg = new TLegend(0.6,0.75,0.9,0.99);
+  leg->SetBit(kCanDelete);
+
+  if (fExtractionType==kWithExtractorRndm && !(what))
+    {
+      TLine *l0 = line.DrawLine(0,0.,cam->GetNbinsX(),0.);
+      l0->SetBit(kCanDelete);
+      leg->AddEntry(l0, "Reference","l");
+      leg->Draw();
+      return;
+    }
+
+  line.SetLineColor(kBlue);
+  TLine *l1 = line.DrawLine(0, what ? fRefPedRmsGalacticInner : fRefPedGalactic,
+			    x, what ? fRefPedRmsGalacticInner : fRefPedGalactic);
+  l1->SetBit(kCanDelete);  
+  line.SetLineColor(kYellow);
+  TLine *l2 = line.DrawLine(0, what ? fRefPedRmsExtraGalacticInner : fRefPedExtraGalactic,
+			    x, what ? fRefPedRmsExtraGalacticInner : fRefPedExtraGalactic);
+  l2->SetBit(kCanDelete);  
+  line.SetLineColor(kMagenta);
+  TLine *l3 = line.DrawLine(0, what ? fRefPedRmsClosedLidsInner : fRefPedClosedLids,
+			    x, what ? fRefPedRmsClosedLidsInner : fRefPedClosedLids);
+  l3->SetBit(kCanDelete);
+
+  if (geom->InheritsFrom("MGeomCamMagic"))
+    if (what)
+      {
+        const Double_t x2 = cam->GetNbinsX();
+
+        line.SetLineColor(kBlue);
+        line.DrawLine(398, fRefPedRmsGalacticOuter,
+                      x2,  fRefPedRmsGalacticOuter);
+        
+        line.SetLineColor(kYellow);
+        line.DrawLine(398, fRefPedRmsExtraGalacticOuter,
+                      x2,  fRefPedRmsExtraGalacticOuter);
+        
+        line.SetLineColor(kMagenta);
+        line.DrawLine(398, fRefPedRmsClosedLidsOuter,
+                      x2,  fRefPedRmsClosedLidsOuter);
+      }
+  
+    
+  leg->AddEntry(l1, "Galactic Source","l");
+  leg->AddEntry(l2, "Extra-Galactic Source","l");
+  leg->AddEntry(l3, "Closed Lids","l");
+  leg->Draw();
+}
+
+void  MJPedestal::DisplayOutliers(TH1D *hist) const
+{
+    const Float_t mean  = hist->GetFunction("gaus")->GetParameter(1);
+    const Float_t lolim = mean - 3.5*hist->GetFunction("gaus")->GetParameter(2);
+    const Float_t uplim = mean + 3.5*hist->GetFunction("gaus")->GetParameter(2);
+    const Stat_t  dead  = hist->Integral(0,hist->FindBin(lolim)-1);
+    const Stat_t  noisy = hist->Integral(hist->FindBin(uplim)+1,hist->GetNbinsX()+1);
+
+    TLatex deadtex;
+    deadtex.SetTextSize(0.06);
+    deadtex.DrawLatex(0.1,hist->GetBinContent(hist->GetMaximumBin())/1.1,Form("%3i dead pixels",(Int_t)dead));
+
+    TLatex noisytex;
+    noisytex.SetTextSize(0.06);
+    noisytex.DrawLatex(0.1,hist->GetBinContent(hist->GetMaximumBin())/1.2,Form("%3i noisy pixels",(Int_t)noisy));
+}
+
+void MJPedestal::FixDataCheckHist(TH1D *hist) const 
+{
+    hist->SetDirectory(NULL);
+    hist->SetStats(0);
+
+    //
+    // set the labels bigger
+    //
+    TAxis *xaxe = hist->GetXaxis();
+    TAxis *yaxe = hist->GetYaxis();
+    
+    xaxe->CenterTitle();
+    yaxe->CenterTitle();    
+    xaxe->SetTitleSize(0.06);
+    yaxe->SetTitleSize(0.06);    
+    xaxe->SetTitleOffset(0.8);
+    yaxe->SetTitleOffset(0.5);    
+    xaxe->SetLabelSize(0.05);
+    yaxe->SetLabelSize(0.05);    
+}
+
+/*
+Bool_t MJPedestal::WriteEventloop(MEvtLoop &evtloop) const
+{
+    if (fOutputPath.IsNull())
+        return kTRUE;
+
+    const TString oname(GetOutputFile());
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TFile file(oname, fOverwrite?"RECREATE":"NEW", "File created by MJPedestal", 9);
+    if (!file.IsOpen())
+    {
+        *fLog << err << "ERROR - Couldn't open file " << oname << " for writing..." << endl;
+        return kFALSE;
+    }
+
+    if (evtloop.Write(fName)<=0)
+    {
+        *fLog << err << "Unable to write MEvtloop to " << oname << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+*/
+
+void MJPedestal::SetExtractor(MExtractor* ext)
+{
+    if (ext)
+    {
+        if (fExtractor)
+            delete fExtractor;
+        fExtractor = ext ? (MExtractor*)ext->Clone(ext->GetName()) : NULL;
+    }
+    else
+        fExtractor = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the following values from resource file:
+//
+//   PedestalMin
+//   PedestalMax
+//
+//   PedRmsMin
+//   PedRmsMax
+//
+//   RefPedClosedLids
+//   RefPedExtraGalactic
+//   RefPedGalactic
+//
+//   RefPedRmsClosedLidsInner
+//   RefPedRmsExtraGalacticInner
+//   RefPedRmsGalacticInner
+//   RefPedRmsClosedLidsOuter
+//   RefPedRmsExtraGalacticOuter
+//   RefPedRmsGalacticOuter
+//
+void MJPedestal::ReadReferenceFile()
+{
+    TEnv refenv(fReferenceFile);
+    
+    fPedestalMin                 = refenv.GetValue("PedestalMin",fPedestalMin);
+    fPedestalMax                 = refenv.GetValue("PedestalMax",fPedestalMax);
+    fPedRmsMin                   = refenv.GetValue("PedRmsMin",fPedRmsMin);                   
+    fPedRmsMax                   = refenv.GetValue("PedRmsMax",fPedRmsMax);                   
+    fRefPedClosedLids            = refenv.GetValue("RefPedClosedLids",fRefPedClosedLids);            
+    fRefPedExtraGalactic         = refenv.GetValue("RefPedExtraGalactic",fRefPedExtraGalactic);         
+    fRefPedGalactic              = refenv.GetValue("RefPedGalactic",fRefPedGalactic);              
+    fRefPedRmsClosedLidsInner    = refenv.GetValue("RefPedRmsClosedLidsInner",fRefPedRmsClosedLidsInner);    
+    fRefPedRmsExtraGalacticInner = refenv.GetValue("RefPedRmsExtraGalacticInner",fRefPedRmsExtraGalacticInner); 
+    fRefPedRmsGalacticInner      = refenv.GetValue("RefPedRmsGalacticInner",fRefPedRmsGalacticInner);      
+    fRefPedRmsClosedLidsOuter    = refenv.GetValue("RefPedRmsClosedLidsOuter",fRefPedRmsClosedLidsOuter);    
+    fRefPedRmsExtraGalacticOuter = refenv.GetValue("RefPedRmsExtraGalacticOuter",fRefPedRmsExtraGalacticOuter); 
+    fRefPedRmsGalacticOuter      = refenv.GetValue("RefPedRmsGalacticOuter",fRefPedRmsGalacticOuter);      
+}
+
+// --------------------------------------------------------------------------
+//
+// The following resource options are available:
+//
+// Do a datacheck run (read raw-data and enable display)
+//   Prefix.DataCheck:        Yes, No <default>
+//
+// Setup display type
+//   Prefix.Display:          normal <default>, datacheck, none
+//
+// Use cosmic data instead of pedestal data (DatRuns)
+//   Prefix.UseData:          Yes, No <default>
+//
+// Write an output file with pedestals and status-display
+//   Prefix.DisableOutput:    Yes, No <default>
+//
+// Name of a file containing reference values (see ReadReferenceFile)
+//   Prefix.ReferenceFile:    filename
+// (see ReadReferenceFile)
+//
+Bool_t MJPedestal::CheckEnvLocal()
+{
+    if (HasEnv("Display"))
+    {
+        TString type = GetEnv("Display", "normal");
+        type.ToLower();
+        if (type==(TString)"normal")
+            fDisplayType = kDisplayNormal;
+        if (type==(TString)"datacheck")
+            fDisplayType = kDisplayDataCheck;
+        if (type==(TString)"none")
+            fDisplayType = kDisplayNone;
+    }
+
+
+    SetExtractWinLeft (GetEnv("ExtractWinLeft",  fExtractWinLeft ));
+    SetExtractWinRight(GetEnv("ExtractWinRight", fExtractWinRight));
+
+    if (!MJCalib::CheckEnvLocal())
+        return kFALSE;
+    
+    if (HasEnv("UseData"))
+        fExtractType = GetEnv("UseData",kFALSE) ? kUseData : kUsePedRun;
+
+    if (IsUseMC() && fExtractType==kUseData)
+    {
+        // The reason is, that the standard data files contains empty
+        // (untriggered) events. If we would loop over the default 500
+        // first events of the data file you would calculate the
+        // pedestal from only some single events...
+        *fLog << inf;
+        *fLog << "Sorry, you cannot extract the starting pedestal from the first" << endl;
+        *fLog << "events in your data files... using pedestal file instead.  The" << endl;
+        *fLog << "result should not differ..." << endl;
+        fExtractType = kUsePedRun;
+    }
+
+
+    if (HasEnv("UseHists"))
+      if (GetEnv("UseHists",kFALSE))
+        fIsUseHists = kTRUE;
+    
+    SetNoStorage(GetEnv("DisableOutput", IsNoStorage()));
+
+    MTaskEnv tenv("ExtractSignal");
+    tenv.SetDefault(fExtractor);
+
+    if (tenv.ReadEnv(*GetEnv(), GetEnvPrefix()+".ExtractSignal", GetEnvDebug()>2)==kERROR)
+        return kFALSE;
+
+    if (fExtractor==tenv.GetTask())
+        return kTRUE;
+
+    if (!tenv.GetTask()->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << "ERROR: ExtractSignal from resource file doesn't inherit from MExtractor.... abort." << endl;
+        return kFALSE;
+    }
+
+    SetExtractor((MExtractor*)tenv.GetTask());
+
+    fBadPixelsFile = GetEnv("BadPixelsFile",fBadPixelsFile.Data());
+    fReferenceFile = GetEnv("ReferenceFile",fReferenceFile.Data());
+    ReadReferenceFile();
+
+    return kTRUE;
+}
+
+//---------------------------------------------------------------------------------
+//
+// Try to write the created MPedestalCam in the output file. 
+// If possible, also an MBadPixelsCam and the corresponding display is written.
+//
+// In case of Storage type "kNoStorage" or if any of the containers
+// cannot be written, return kFALSE, otherwise kTRUE.
+//
+Bool_t MJPedestal::WriteResult()
+{
+    if (IsNoStorage())
+        return kTRUE;
+
+    TObjArray cont;
+
+    cont.Add(&fPedestalCamOut);
+    cont.Add(&fBadPixels);
+
+    return WriteContainer(cont, GetOutputFileName(),fOverwrite?"RECREATE":"NEW");
+}
+
+Bool_t MJPedestal::Process()
+{
+    if (!ReadPedestalCam())
+        return ProcessFile();
+
+    return kTRUE;
+}
+
+Bool_t MJPedestal::ProcessFile()
+{
+    if (!fSequence.IsValid())
+    {
+        if (!fRuns)
+        {
+            *fLog << err << "Neither AddRuns nor SetSequence nor SetEnv was called... abort." << endl;
+            return kFALSE;
+        }
+        if (fRuns && 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;
+        }
+    }
+
+    if (!CheckEnv())
+        return kFALSE;
+
+    // --------------------------------------------------------------------------------
+
+    const TString type = IsUseData() ? "data" : "pedestal";
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate MPedestalCam from " << type << "-runs ";
+    if (fSequence.IsValid())
+        *fLog << fSequence.GetName() << endl;
+    else
+        if (fRuns)
+            *fLog << fRuns->GetRunsAsString() << endl;
+        else
+            *fLog << "in Resource File." << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    plist.AddToList(this); // take care of fDisplay!
+
+    MReadMarsFile read("Events");
+    MRawFileRead rawread(NULL);
+
+    MDirIter iter;
+    if (fSequence.IsValid())
+    {
+        const Int_t n0 = IsUseData() 
+          ? fSequence.SetupDatRuns(iter, fPathData, "D", IsUseRawData()) 
+          : fSequence.SetupPedRuns(iter, fPathData, "P", IsUseRawData());
+        const Int_t n1 = IsUseData() 
+          ? fSequence.GetNumDatRuns() 
+          : fSequence.GetNumPedRuns();
+        if (n0==0)
+        {
+            *fLog << err << "ERROR - No " << type << " input files of sequence found in " << (fPathData.IsNull()?"<default>":fPathData.Data()) << endl;
+            return kFALSE;
+        }
+        if (n0!=n1)
+        {
+            *fLog << err << "ERROR - Number of " << type << " files found (" << n0 << ") in " << (fPathData.IsNull()?"<default>":fPathData.Data())  << " doesn't match number of files in sequence (" << n1 << ")" << endl;
+            if (fLog->GetDebugLevel()>4)
+            {
+                *fLog << dbg << "Files which are searched:" << endl;
+                iter.Print();
+            }
+            return kFALSE;
+        }
+    }
+
+    if (IsUseRawData())
+    {
+        if (fRuns || fSequence.IsValid())
+            rawread.AddFiles(fSequence.IsValid() ? iter : *fRuns);
+        tlist.AddToList(&rawread);
+    }
+    else
+    {
+        read.DisableAutoScheme();
+        if (fRuns || fSequence.IsValid())
+          read.AddFiles(fSequence.IsValid() ? iter : *fRuns);
+	tlist.AddToList(&read);
+    }
+
+    // Setup Tasklist
+    plist.AddToList(&fPedestalCamOut);
+    plist.AddToList(&fBadPixels);
+    
+    //
+    // Read bad pixels from outside
+    // 
+    if (!fBadPixelsFile.IsNull())
+      {
+        *fLog << inf << "Excluding: " << fBadPixelsFile << endl;
+        ifstream fin(fBadPixelsFile.Data());
+        fBadPixels.AsciiRead((istream&)fin);
+      }
+
+    MGeomApply geomapl;
+    MBadPixelsMerge merge(&fBadPixels);
+
+    MPedCalcPedRun pedcalc;
+    pedcalc.SetPedestalUpdate(kFALSE);
+
+    MPedCalcFromLoGain pedlogain;
+    pedlogain.SetPedestalUpdate(kFALSE);
+    
+    MHPedestalCam hpedcam;
+    if (fExtractionType != kFundamental)
+      hpedcam.SetRenorm(kTRUE);
+    //    fPedestalHist.SetRenorm(kTRUE);
+    //    fPedestalHist.SetPedestalsOut(&fPedestalCamOut);
+    hpedcam.SetPedestalsOut(&fPedestalCamOut);
+
+    MPedestalCam pedinter;
+    pedinter.SetName("MPedestalCamIntermediate");
+
+    MFillH fillped(&hpedcam, "MPedestalCamIntermediate", "FillPedCam");
+    //    MFillH fillped(&fPedestalHist, "MPedestalCamIntermediate", "FillPedCam");
+    MFillH fillpul("MHCalibrationPulseTimeCam", "MRawEvtData", "FillPulseTime");
+    fillped.SetBit(MFillH::kDoNotDisplay);
+    fillpul.SetBit(MFillH::kDoNotDisplay);
+
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&merge);
+
+    if (!fPathIn.IsNull())
+    {
+        fExtractor = ReadCalibration();
+        if (!fExtractor)
+            return kFALSE;
+
+        *fLog << all;
+        *fLog << underline << "Signal Extractor found in calibration file:" << endl;
+        fExtractor->Print();
+        *fLog << endl;
+    }
+
+    MFTriggerPattern fcalib("CalibFilter");
+    fcalib.RequireCalibration();
+    fcalib.SetInverted();
+
+    if (fIsPulsePosCheck)
+      {
+        fillpul.SetFilter(&fcalib);
+        tlist.AddToList(&fillpul);
+      }
+
+    // ----------------------------------------------------------------------
+    //   Now we make sure, that in all cases the ranges are setup correctly
+    // ----------------------------------------------------------------------
+    MTaskEnv taskenv("ExtractPedestal");
+    switch (fExtractType)
+    {
+    case kUsePedRun:
+        // In case  other than 'fundamental' second argument is obsolete
+        // pedcalc.SetExtractWindow(0,14);  // kUsePedRun (take default from class)
+        taskenv.SetDefault(&pedcalc);
+        tlist.AddToList(&taskenv);
+        break;
+
+    case kUseData:
+        // In case  other than 'fundamental' second argument is obsolete
+        // pedlogain.SetExtractWindow(15,14); // kUseData (take default from class)
+        taskenv.SetDefault(&pedlogain);
+        tlist.AddToList(&taskenv);
+        break;
+    }
+    
+    if (fIsUseHists)
+      {
+        if (fExtractor->InheritsFrom("MExtractTimeAndCharge"))
+          hpedcam.SetFitStart(-10.*((MExtractTimeAndCharge*)fExtractor)->GetWindowSizeHiGain());
+        
+        pedcalc.SetIntermediateStorage();
+        pedlogain.SetIntermediateStorage();
+        plist.AddToList(&pedinter);
+        plist.AddToList(&hpedcam);
+        //        plist.AddToList(&fPedestalHist);
+        tlist.AddToList(&fillped);
+    }
+
+    pedcalc.SetPedestalsIn(&fPedestalCamIn);
+    pedlogain.SetPedestalsIn(&fPedestalCamIn);
+
+    pedcalc.SetPedestalsInter(&pedinter);
+    pedlogain.SetPedestalsInter(&pedinter);
+    pedcalc.SetPedestalsOut(&fPedestalCamOut);
+    pedlogain.SetPedestalsOut(&fPedestalCamOut);
+
+     // kFundamental
+    if (fExtractor)
+    {
+
+      if (fExtractionType!=kFundamental)
+        {
+          pedcalc.SetRandomCalculation(fExtractionType==kWithExtractorRndm);
+          pedlogain.SetRandomCalculation(fExtractionType==kWithExtractorRndm);
+          
+          pedcalc.SetExtractor((MExtractTimeAndCharge*)fExtractor);
+          pedlogain.SetExtractor((MExtractTimeAndCharge*)fExtractor);
+        }
+      
+      if (fExtractor->InheritsFrom("MExtractTimeAndCharge"))
+        {
+
+          const Float_t f = 0.1+fExtractor->GetHiGainFirst();
+          const Int_t win = ((MExtractTimeAndCharge*)fExtractor)->GetWindowSizeHiGain();
+          pedcalc.SetExtractWindow((Int_t)f, win);
+          pedlogain.SetExtractWindow((Int_t)(15+f), win);
+
+        }
+      else
+        {
+          const Float_t f = 0.1+fExtractor->GetHiGainFirst();
+          const Float_t n = 0.1+fExtractor->GetNumHiGainSamples();
+          pedcalc.SetExtractWindow((Int_t)f, (Int_t)n);
+          pedlogain.SetExtractWindow((Int_t)(15+f), (Int_t)n);
+
+          if (fExtractionType!=kFundamental)
+            {
+              *fLog << inf;
+              *fLog << "Signal extractor doesn't inherit from MExtractTimeAndCharge..." << endl;
+              *fLog << " --> falling back to fundamental pedestal extraction." << endl;
+              fExtractionType=kFundamental;
+            }
+        }
+      
+      
+    }
+    else
+    {
+        *fLog << warn << GetDescriptor() << ": WARNING - No extractor has been handed over! " << endl;
+        *fLog << "Taking default window for pedestal extraction. The calculated pedestal  RMS" << endl;
+        *fLog << "will probably not match with future pedestal RMS' from different extraction" << endl;
+        *fLog << "windows." << endl;
+    }
+    
+    /*
+    switch (fExtractType)
+    {
+    case kUseData:
+        *fLog << all << "TYPE: USEDATA " << fExtractor << endl;
+        taskenv.SetDefault(&pedlogain);
+        tlist.AddToList(&taskenv);
+
+        if (!SetupExtractor(plist, pedlogain))
+        {
+            *fLog << all <<  "SETTING TO: " << fExtractor << " " << fExtractor->GetNumHiGainSamples() << endl;
+            fExtractor->Print();
+            pedlogain.SetExtractWindow(15, (Int_t)TMath::Nint(fExtractor->GetNumHiGainSamples()));
+        }
+        break;
+
+    case kUsePedRun:
+        *fLog << all <<  "TYPE: USEPEDRUN " << fExtractor << endl;
+        taskenv.SetDefault(&pedcalc);
+        tlist.AddToList(&taskenv);
+
+        if (!SetupExtractor(plist, pedcalc))
+            pedcalc.SetExtractWindow(fExtractor->GetHiGainFirst(), TMath::Nint(fExtractor->GetNumHiGainSamples()));
+        break;
+
+    case kUseHists:
+        if (!fExtractor)
+        {
+            *fLog << err << GetDescriptor() << " - ERROR: ";
+            *fLog << "Extraction Type is kUseHists, but no extractor was set" << endl;
+            return kFALSE;
+        }
+
+        tlist.AddToList(fExtractor);
+        tlist.AddToList(&fillped);
+        break;
+    } */
+
+    /*
+    if (!fPathIn.IsNull())
+    {
+        delete fExtractor;
+        fExtractor = 0;
+    }
+    */
+
+
+    //
+    // Execute the eventloop
+    //
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    //    if (!WriteEventloop(evtloop))
+    //        return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    if (fIsPixelCheck)
+      {
+        MHPedestalCam *hcam = (MHPedestalCam*)plist.FindObject("MHPedestalCam");
+        if (hcam)
+          {
+            MHPedestalPix &pix1 = (MHPedestalPix&)(*hcam)[fCheckedPixId];
+            pix1.DrawClone("");
+          }
+      }
+    
+    if (fDisplayType!=kDisplayNone)
+        DisplayResult(plist);
+
+    if (!WriteResult())
+        return kFALSE;
+
+    if (fIsPulsePosCheck)
+      {
+        
+        Int_t numhigainsamples = 0;
+        Int_t numlogainsamples = 0;
+        Float_t meanpulsetime  = 0.;
+        Float_t rmspulsetime   = 0.;
+
+        if (IsUseMC())
+          {
+            //
+            // FIXME:
+            // The MC cannot run over the first 2000 pedestal events since almost all
+            // events are empty, therefore a pulse pos. check is not possible, either. 
+            // For the moment, have to fix the problem hardcoded...
+            //
+            //            MMcEvt *evt = (MMcEvt*)plist.FindObject("MMcEvt");
+            //            const Float_t meanpulsetime = evt->GetFadcTimeJitter();
+            meanpulsetime = 4.5;
+            rmspulsetime  = 1.0;
+
+            *fLog << all << "Mean pulse time (MC): " << meanpulsetime << "+-" << rmspulsetime << endl;
+
+            numhigainsamples = 15;
+            numlogainsamples = 15;
+
+          }
+        else
+          {
+            MHCalibrationPulseTimeCam *hcam = (MHCalibrationPulseTimeCam*)plist.FindObject("MHCalibrationPulseTimeCam");
+            if (fIsPixelCheck)
+              {
+                hcam->DrawClone();
+                gPad->SaveAs(Form("%s/PulsePosTest_all.root",fPathOut.Data()));
+                MHCalibrationPix &pix = (*hcam)[fCheckedPixId];
+                pix.DrawClone();
+                gPad->SaveAs(Form("%s/PulsePosTest_Pixel%04d.root",fPathOut.Data(),fCheckedPixId));
+              }
+            
+            MCalibrationPulseTimeCam *cam = (MCalibrationPulseTimeCam*)plist.FindObject("MCalibrationPulseTimeCam");
+            if (!cam)
+              {
+                *fLog << err << "Could not determine mean pulse position, abort... " << endl;
+                return kFALSE;
+              }
+            
+            meanpulsetime = cam->GetAverageArea(0).GetHiGainMean();
+            rmspulsetime  = cam->GetAverageArea(0).GetHiGainRms();
+
+            *fLog << all << "Mean pulse time (cosmics): " << meanpulsetime << "+-" << rmspulsetime << endl;
+
+            MRawEvtData *data = (MRawEvtData*)plist.FindObject("MRawEvtData");
+
+            numhigainsamples = data->GetNumHiGainSamples();
+            numlogainsamples = data->GetNumLoGainSamples();
+          }
+        
+        //
+        // Get the ranges for the new extractor setting
+        //
+        const Int_t newfirst = TMath::Nint(meanpulsetime-fExtractWinLeft);
+        Int_t wshigain = fExtractor->InheritsFrom("MExtractTimeAndCharge") 
+          ?  ((MExtractTimeAndCharge*)fExtractor)->GetWindowSizeHiGain()
+          : 6;
+
+        if (wshigain > 6)
+          wshigain = 6;
+
+        Int_t wslogain = fExtractor->InheritsFrom("MExtractTimeAndCharge") 
+          ? ((MExtractTimeAndCharge*)fExtractor)->GetWindowSizeLoGain()
+          : 6;
+        if (wslogain > 4)
+          wslogain = 4;
+
+        const Int_t newlast  = TMath::Nint(meanpulsetime+fExtractWinRight);
+
+        *fLog << all << underline 
+              << "Try to set new range limits: ("<<newfirst<<","<<newlast<<"+"<<wshigain
+              <<","<<newfirst-1<<","<<newlast<<"+"<<wslogain<<")"<<endl;
+        //
+        // Check the ranges for the new extractor setting
+        //
+        if (newfirst < 0)
+          {
+            *fLog << err << "Pulse is too much to the left, cannot go below 0! " << endl;
+            return kFALSE;
+          }
+        if (newlast+wshigain > numhigainsamples+numlogainsamples-1)
+          {
+            *fLog << err << "Pulse is too much to the right, cannot go beyond limits: " 
+                  << numhigainsamples << "+" << numlogainsamples << "-1" << endl;
+            *fLog << " Cannot extract at all! ... " << endl;
+            return kFALSE;
+          }
+        if (newlast+wslogain > numlogainsamples)
+          {
+            *fLog << err << "Pulse is too much to the right, cannot go beyond logain limits! " << endl;
+            *fLog << endl;
+            *fLog << "Try to use a different extractor (e.g. with a window size of only 4 sl.) or:" << endl;
+            *fLog << "Set the limit to a lower value (callisto.rc: line 329): " << endl;
+            *fLog << "    MJPedestalY2:ExtractWinRight: 4.5           " << endl;
+            *fLog << "(ATTENTION, you will lose late cosmics pulses!)" << endl;
+            *fLog << endl;
+            return kFALSE;
+          }
+        //
+        // Set and store the new ranges 
+        //
+        fExtractor->SetRange(newfirst,newlast+wshigain,
+                             newfirst>0?newfirst-1:newfirst,numlogainsamples-1);
+      }
+    
+
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mjobs/MJPedestal.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJPedestal.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJPedestal.h	(revision 9772)
@@ -0,0 +1,135 @@
+#ifndef MARS_MJPedestal
+#define MARS_MJPedestal
+
+#ifndef MARS_MJCalib
+#include "MJCalib.h"
+#endif
+#ifndef MARS_MPedestalCam
+#include "MPedestalCam.h"
+#endif
+#ifndef MARS_MHPedestalCam
+#include "MHPedestalCam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+class TCanvas;
+class MParList;
+class MHCamera;
+class TH1D;
+class MExtractor;
+class MExtractPedestal;
+class MEvtLoop;
+
+class MJPedestal : public MJCalib
+{
+private:
+
+    static const TString  fgReferenceFile;    //! default for fReferenceFile ("pedestalref.rc")
+    static const TString  fgBadPixelsFile;    //! default for fBadPixelsFile ("badpixels_0_559.rc")
+
+    static const Float_t  fgExtractWinLeft;   //! default for fExtractWinLeft  (now set to: 2.5)
+    static const Float_t  fgExtractWinRight;  //! default for fExtractWinRight (now set to: 6.0)
+
+    Axis_t fPedestalMin;                     //! Minimum Axis value for pedestal datacheck display
+    Axis_t fPedestalMax;                     //! Maximum Axis value for pedestal datacheck display
+    Axis_t fPedRmsMin;                       //! Minimum Axis value for ped. RMS datacheck display
+    Axis_t fPedRmsMax;                       //! Maximum Axis value for ped. RMS datacheck display
+				             
+    Float_t fRefPedClosedLids;               //! Reference line pedestal for closed lids run
+    Float_t fRefPedExtraGalactic;            //! Reference line pedestal for extragalactic source
+    Float_t fRefPedGalactic;                 //! Reference line pedestal for galactic source
+
+    Float_t fRefPedRmsClosedLidsInner;       //! Ref. line ped. RMS for closed lids run - inner pixels
+    Float_t fRefPedRmsExtraGalacticInner;    //! Ref. line ped. RMS for extragalactic source - inner pixels
+    Float_t fRefPedRmsGalacticInner;         //! Ref. line ped. RMS for galactic source - inner pixels
+
+    Float_t fRefPedRmsClosedLidsOuter;       //! Ref. line ped. RMS for closed lids run - outer pixels
+    Float_t fRefPedRmsExtraGalacticOuter;    //! Ref. line ped. RMS for extragalactic source - outer pixels
+    Float_t fRefPedRmsGalacticOuter;         //! Ref. line ped. RMS for galactic source - outer pixels
+
+    Float_t fExtractWinLeft;                 //  Number of FADC slices to extract leftward from mean pulse pos.  
+    Float_t fExtractWinRight;                //  Number of FADC slices to extract rightward from mean pulse pos.
+    
+    TString fReferenceFile;                  // File name containing the reference values
+    TString fBadPixelsFile;                  // File name containing the bad pixels excluded beforehand 
+    
+    MExtractor *fExtractor;                  // Signal extractor, used to find the nr. of used FADC slices
+
+    MPedestalCam  fPedestalCamIn;            // Handed over pedestal results
+    MPedestalCam  fPedestalCamOut;           // Created pedestal results
+    MBadPixelsCam fBadPixels;                // Bad Pixels
+    //    MHPedestalCam fPedestalHist;             // Histogramming pedestal Camera
+
+    enum Display_t { kDisplayNone, kDisplayNormal, kDisplayDataCheck }; // Possible Display types
+    Display_t fDisplayType;                  // Chosen Display type
+
+    enum Extract_t { kUseData, kUsePedRun }; // Possible flags for the extraction of the pedestal
+    Extract_t fExtractType;                  // Chosen extractor type
+
+    enum Extraction { kFundamental, kWithExtractorRndm, kWithExtractor };
+    Int_t fExtractionType;                   // Flag if the extractor is used to calculate the pedestals
+
+    Bool_t fIsUseHists;                      // Switch on histogramming or not
+
+    MExtractor *ReadCalibration() const;
+    Bool_t ReadPedestalCam();
+    Bool_t WriteResult();
+    //Bool_t WriteEventloop(MEvtLoop &evtloop) const;
+
+    void   DisplayResult(MParList &plist);
+    void   DisplayReferenceLines(MHCamera *cam, const Int_t what) const;
+    void   DisplayOutliers(TH1D *hist) const;
+    void   FixDataCheckHist(TH1D *hist) const;
+
+    Bool_t CheckEnvLocal();
+
+    const char*  GetOutputFileName() const;
+
+    void ReadReferenceFile();
+
+    Bool_t WriteExtractor() const;
+    
+public:
+    MJPedestal(const char *name=NULL, const char *title=NULL);
+    ~MJPedestal();
+
+    MPedestalCam &GetPedestalCam()            { return fPedestalCamOut; }
+    const MBadPixelsCam &GetBadPixels() const { return fBadPixels;   }
+
+    const char*  GetOutputFile() const;
+
+    //    const MHPedestalCam &GetPedestalHist() const { return fPedestalHist;  }
+
+    const Bool_t IsUseData() const { return fExtractType == kUseData; }
+
+    Bool_t Process    ();
+    Bool_t ProcessFile();
+
+    void SetBadPixels(const MBadPixelsCam &bad) { bad.Copy(fBadPixels); }
+    void SetPedestals(const MPedestalCam  &ped) { ped.Copy(fPedestalCamIn); }
+    void SetExtractor(MExtractor* ext);
+    void SetUseData()                           { fExtractType = kUseData;   }
+    void SetUseHists( const Bool_t b=kTRUE)     { fIsUseHists = b;  }
+    void SetUsePedRun()                         { fExtractType = kUsePedRun; }
+    void SetDataCheckDisplay()                  { fDisplayType = kDisplayDataCheck; }
+    void SetNormalDisplay()                     { fDisplayType = kDisplayNormal;    }
+    void SetNoDisplay()                         { fDisplayType = kDisplayNone; }
+
+    void SetExtractionFundamental()       { fExtractionType=kFundamental;       /*fPedestalCamOut.SetName("MPedestalFundamental");*/   }
+    void SetExtractionWithExtractorRndm() { fExtractionType=kWithExtractorRndm; /*fPedestalCamOut.SetName("MPedestalExtractorRndm");*/ }
+    void SetExtractionWithExtractor()     { fExtractionType=kWithExtractor;     /*fPedestalCamOut.SetName("MPedestalExtractor");*/     }
+
+    void SetReferenceFile( const TString ref=fgReferenceFile ) { fReferenceFile = ref; }
+    void SetBadPixelsFile( const TString ref=fgBadPixelsFile ) { fBadPixelsFile = ref; }
+
+    void SetExtractWinLeft ( const Float_t f=fgExtractWinLeft  ) { fExtractWinLeft  = f; }
+    void SetExtractWinRight( const Float_t f=fgExtractWinRight ) { fExtractWinRight = f; }    
+
+    MExtractor *GetExtractor() const { return fExtractor; }
+
+    ClassDef(MJPedestal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJStar.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJStar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJStar.cc	(revision 9772)
@@ -0,0 +1,369 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJStar
+//
+// Resource file entries are case sensitive!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJStar.h"
+
+#include <TEnv.h>
+#include <TFile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+
+#include "MH3.h"
+#include "MHVsTime.h"
+#include "MHCamEvent.h"
+#include "MHCamEventRot.h"
+#include "MBinning.h"
+
+#include "MReadReports.h"
+#include "MReadMarsFile.h"
+#include "MFDeltaT.h"
+#include "MFSoftwareTrigger.h"
+#include "MContinue.h"
+#include "MGeomApply.h"
+#include "MEventRateCalc.h"
+#include "MImgCleanStd.h"
+#include "MSrcPosCalc.h"
+#include "MHillasCalc.h"
+#include "MFillH.h"
+#include "MWriteRootFile.h"
+
+#include "MObservatory.h"
+#include "MPointingPosCalc.h"
+
+ClassImp(MJStar);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fRuns to 0, fExtractor to NULL, fDataCheck to kFALSE
+//
+MJStar::MJStar(const char *name, const char *title) 
+{
+    fName  = name  ? name  : "MJStar";
+    fTitle = title ? title : "Standard analysis and reconstruction";
+}
+
+Bool_t MJStar::WriteResult()
+{
+    if (fPathOut.IsNull())
+    {
+        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
+        return kTRUE;
+    }
+
+    const TString oname = Form("%s/star%08d.root", (const char*)fPathOut, fSequence.GetSequence());
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TFile file(oname, "RECREATE");
+
+    *fLog << inf << " - MStatusDisplay..." << flush;
+    if (fDisplay && fDisplay->Write()<=0)
+    {
+        *fLog << err << "Unable to write MStatusDisplay to " << oname << endl;
+        return kFALSE;
+    }
+    *fLog << inf << "ok." << endl;
+
+    return kTRUE;
+}
+
+Bool_t MJStar::ProcessFile(Bool_t ismc)
+{
+    if (!fSequence.IsValid())
+    {
+        *fLog << err << "ERROR - Sequence invalid!" << endl;
+        return kFALSE;
+    }
+
+    //if (!CheckEnv())
+    //    return kFALSE;
+
+    CheckEnv();
+
+    // --------------------------------------------------------------------------------
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate image parameters of sequence ";
+    *fLog << fSequence.GetName() << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+
+    MDirIter iter;
+    const Int_t n0 = fSequence.SetupDatRuns(iter, fPathData, "Y");
+    const Int_t n1 = fSequence.GetNumDatRuns();
+    if (n0==0)
+    {
+        *fLog << err << "ERROR - No input files of sequence found!" << endl;
+        return kFALSE;
+    }
+    if (n0!=n1)
+    {
+        *fLog << err << "ERROR - Number of files found (" << n0 << ") doesn't match number of files in sequence (" << n1 << ")" << endl;
+        if (fLog->GetDebugLevel()>4)
+        {
+            *fLog << dbg << "Files which are searched:" << endl;
+            iter.Print();
+        }
+        return kFALSE;
+    }
+
+    // Setup Parlist
+    MParList plist;
+    plist.AddToList(this); // take care of fDisplay!
+
+    MObservatory obs;
+    plist.AddToList(&obs);
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadReports readreal;
+    readreal.AddTree("Events", "MTime.", kTRUE);
+    readreal.AddTree("Drive");
+    //read.AddTree("Trigger");
+    //read.AddTree("Camera");
+    //read.AddTree("CC");
+    //read.AddTree("Currents");
+    readreal.AddFiles(iter);
+
+    MReadMarsFile readmc("Events");
+    readmc.DisableAutoScheme();
+    readmc.AddFiles(iter);
+
+    // ------------------ Setup general tasks ----------------
+
+    MFDeltaT               fdeltat;
+    MContinue              cont(&fdeltat, "FilterDeltaT", "Filter events with wrong timing");
+    cont.SetInverted();
+
+    MGeomApply             apply; // Only necessary to craete geometry
+    MEventRateCalc         rate;
+    //MEventRateCalc         rate1; // 5min
+    rate.SetNumEvents(1200);
+    //rate1.SetNumEvents(60000);
+    //rate1.SetNameEventRate("MEventRate2");
+    //rate1.SetNameTimeRate("MTimeRate2");
+
+    /*
+    MEventRateCalc         rate10000;
+    rate10000.SetNameEventRate("MEventRate10000");
+    rate10000.SetNumEvents(10000);
+ */
+    //MBadPixelsMerge        merge(&badpix);
+
+    MFSoftwareTrigger swtrig;
+    MContinue contsw(&swtrig, "FilterSwTrigger", "Software trigger");
+    contsw.SetInverted();
+
+
+    MImgCleanStd           clean;
+    clean.SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+
+    MSrcPosCalc            poscalc;
+    MHillasCalc            hcalc;
+    hcalc.Disable(MHillasCalc::kCalcConc);
+
+    // ------------------ Setup histograms and fill tasks ----------------
+    MHCamEvent evt0a(0, "Cleaned", "Signal after Cleaning;;S [\\gamma]");
+    MHCamEvent evt0b(0, "UsedPix", "Fraction of Events in which Pixels are used;;Fraction");
+    evt0b.SetThreshold(0);
+
+    //MHCamEventRot evt0r("UsedRot", "Pixels marked Used (derotated)");
+    //evt0r.SetThreshold(0);
+
+    MH3 h1("MEventRate.fRate");
+    h1.SetName("MHEventRate");
+    h1.SetTitle("Event Rate distribution;R [Hz];Counts");
+    h1.SetLogy();
+/*
+    MH3 h12("MEventRate10000.fRate");
+    h12.SetName("MHEventRate");
+    h12.SetLogy();
+ */
+    MBinning b1("BinningMHEventRate");
+    b1.SetEdges(150, 0, 1500);
+    plist.AddToList(&b1);
+
+    MHVsTime hvs("MEventRate.fRate");
+    hvs.SetTitle("Rate per 500 events;R [Hz];Counts");
+    hvs.SetNumEvents(500);
+
+    //MContinue cont1("MEventRate2.fRate/MEventRate.fRate>1.1");
+    //MContinue cont2("MEventRate.fRate/MEventRate2.fRate>1.1");
+
+    MFillH fillvs(&hvs,           "MTime",        "FillEventRate10s");
+
+    MFillH fill0a(&evt0a,         "MSignalCam",   "FillSignalCam");
+    MFillH fill0b(&evt0b,         "MSignalCam",   "FillCntUsedPixels");
+    //MFillH fill0r(&evt0r,         "MCerPhotEvt",  "FillCntUsedRotated");
+    MFillH fill1("MHHillas",      "MHillas",      "FillHillas");
+    MFillH fill2("MHHillasExt",   "",             "FillHillasExt");
+    MFillH fill3("MHHillasSrc",   "MHillasSrc",   "FillHillasSrc");
+    MFillH fill4("MHImagePar",    "MImagePar",    "FillImagePar");
+    MFillH fill5("MHNewImagePar", "MNewImagePar", "FillNewImagePar");
+    //MFillH fill6("MHImageParTime","MImageParTime","FillImageParTime");
+    //MFillH fill7("MHNewImagePar2","MNewImagePar2","FillNewImagePar2");
+    MFillH fill8(&h1,             "",             "FillEventRate");
+    MFillH fill9("MHEffectiveOnTime", "MTime",    "FillEffOnTime");
+    //MFillH fillb(&h12, "", "FillEvtRate2");
+    //MFillH fill9("MHCerPhot");
+
+    //fill0r.SetDrawOption("colz");
+    fill8.SetNameTab("EvtRate");
+    fill9.SetNameTab("EffOnTime");
+
+    // ------------------ Setup write task ----------------
+
+    MWriteRootFile write(2, Form("%s{s/_Y_/_I_}", fPathOut.Data()), fOverwrite?"RECREATE":"NEW");
+    // Data
+    write.AddContainer("MHillas",       "Events");
+    write.AddContainer("MHillasExt",    "Events");
+    write.AddContainer("MHillasSrc",    "Events");
+    write.AddContainer("MImagePar",     "Events");
+    write.AddContainer("MNewImagePar",  "Events");
+    //write.AddContainer("MNewImagePar2", "Events");
+    //write.AddContainer("MImageParTime", "Events");
+    write.AddContainer("MRawEvtHeader", "Events");
+    write.AddContainer("MPointingPos",  "Events");
+
+    // Run Header
+    write.AddContainer("MRawRunHeader", "RunHeaders");
+    write.AddContainer("MBadPixelsCam", "RunHeaders");
+    write.AddContainer("MGeomCam",      "RunHeaders");
+    write.AddContainer("MObservatory",  "RunHeaders");
+
+    if (ismc)
+    {
+        // Monte Carlo Data
+        write.AddContainer("MMcEvt",               "Events");
+        write.AddContainer("MMcTrig",              "Events");
+        // Monte Carlo Run Headers
+        write.AddContainer("MMcRunHeader",         "RunHeaders");
+        write.AddContainer("MMcTrigHeader",        "RunHeaders");
+        write.AddContainer("MMcFadcHeader",        "RunHeaders");
+        write.AddContainer("MMcConfigRunHeader",   "RunHeaders");
+        write.AddContainer("MMcCorsikaRunHeader",  "RunHeaders");
+        write.AddCopySource("OriginalMC");
+    }
+    else
+    {
+        write.AddContainer("MTime",                "Events");
+        // Drive
+        write.AddContainer("MReportDrive",         "Drive");
+        write.AddContainer("MTimeDrive",           "Drive");
+        // Effective On Time
+        write.AddContainer("MEffectiveOnTime",     "EffectiveOnTime");
+        write.AddContainer("MTimeEffectiveOnTime", "EffectiveOnTime");
+    }
+
+    MTaskList tlist2("Events");
+    tlist2.AddToList(&apply);
+    if (!ismc)
+        tlist2.AddToList(&cont);
+    tlist2.AddToList(&contsw);
+    if (!ismc)
+    {
+        tlist2.AddToList(&rate);
+        //tlist2.AddToList(&rate1);
+        tlist2.AddToList(&fillvs);
+        //tlist2.AddToList(&cont1);
+        //tlist2.AddToList(&cont2);
+        tlist2.AddToList(&fill8);
+        tlist2.AddToList(&fill9);
+    }
+    //tlist2.AddToList(&fillb);
+    tlist2.AddToList(&clean);
+    tlist2.AddToList(&fill0a);
+    tlist2.AddToList(&fill0b);
+    //tlist2.AddToList(&fill0r);
+    tlist2.AddToList(&poscalc);
+    tlist2.AddToList(&hcalc);
+    tlist2.AddToList(&fill1);
+    tlist2.AddToList(&fill2);
+    tlist2.AddToList(&fill3);
+    tlist2.AddToList(&fill4);
+    tlist2.AddToList(&fill5);
+    //tlist2.AddToList(&fill6);
+    //tlist2.AddToList(&fill7);
+    //tlist2.AddToList(&fill9);
+
+    MPointingPosCalc pcalc;
+    //MSrcPosFromModel srcpos;
+
+    MTaskList tlist3("Drive");
+    tlist3.AddToList(&pcalc);
+    //tlist3.AddToList(&srcpos);
+
+    tlist.AddToList(ismc ? (MTask*)&readmc : (MTask*)&readreal);
+    tlist.AddToList(&tlist3, "Drive");
+    tlist.AddToList(&tlist2, "Events");
+    tlist.AddToList(&write);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    if (!WriteResult())
+        return kFALSE;
+
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mjobs/MJStar.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJStar.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJStar.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MJStar
+#define MARS_MJStar
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class MJStar : public MJob
+{
+private:
+    Bool_t WriteResult();
+
+public:
+    MJStar(const char *name=NULL, const char *title=NULL);
+
+    Bool_t ProcessFile(Bool_t ismc=kFALSE);
+
+    ClassDef(MJStar, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MJob.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MJob.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJob.cc	(revision 9772)
@@ -0,0 +1,301 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJob
+//
+// A base class for jobs
+//
+// SetDebugEnv(0) // switch off debugging
+// SetDebugEnv(1) // reserved
+// SetDebugEnv(2) // print untouched resources after evtloop resources setup
+// SetDebugEnv(3) // do 2) and debug setting env completely
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJob.h"
+
+#include "MEnv.h"
+#include <TFile.h>
+#include <TSystem.h>
+#include <TObjArray.h>
+
+#include "MIter.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEvtLoop.h"
+
+ClassImp(MJob);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fDataFlag to 0
+//
+MJob::MJob(const char *name, const char *title) : fEnv(0), fEnvDebug(0), fOverwrite(kFALSE), fMaxEvents(0)
+  
+{
+    fName  = name  ? name  : "MJob";
+    fTitle = title ? title : "Base class for jobs";
+}
+
+void MJob::ClearEnv()
+{
+    if (fEnv && TestBit(kIsOwner))
+        delete fEnv;
+    ResetBit(kIsOwner);
+    fEnv=0;
+}
+
+MJob::~MJob()
+{
+    ClearEnv();
+}
+
+Bool_t MJob::SetEnv(const char *env, const char *prefix)
+{
+    ClearEnv();
+
+    const Bool_t fileexist = !gSystem->AccessPathName(env, kFileExists);
+    if (!fileexist)
+    {
+        *fLog << err << "ERROR - Resource file '" << env << "' not found... no resources applied." << endl;
+        return kFALSE;
+    }
+
+    fEnv = new MEnv(env);
+    SetBit(kIsOwner);
+
+    fEnvPrefix = prefix;
+    if (!prefix)
+        fEnvPrefix = fName.First(' ')>0 ? fName(0, fName.First(' ')) : fName;
+
+    if (fEnvPrefix.EndsWith("."))
+        fEnvPrefix.Remove(fEnvPrefix.Length()-1);
+
+    return kTRUE;
+}
+
+void MJob::SetEnv(MEnv *env, const char *prefix)
+{
+    ClearEnv();
+
+    fEnv = env;
+
+    fEnvPrefix = prefix;
+    if (!prefix)
+        fEnvPrefix = fName.First(' ')>0 ? fName(0, fName.First(' ')) : fName;
+
+    if (fEnvPrefix.EndsWith("."))
+        fEnvPrefix.Remove(fEnvPrefix.Length()-1);
+}
+
+void MJob::FixPath(TString &path) const
+{
+    path.ReplaceAll("\015", "");
+
+    if (path==(TString)"/")
+        return;
+
+    if (path.EndsWith("/"))
+        path.Remove(path.Length()-1);
+}
+
+void MJob::SetPathOut(const char *path)
+{
+    fPathOut = path;
+    FixPath(fPathOut);
+}
+
+void MJob::SetPathIn(const char *path)
+{
+    fPathIn = path;
+    FixPath(fPathIn);
+}
+
+void MJob::SetPathData(const char *path)
+{
+    fPathData = path;
+    FixPath(fPathData);
+}
+
+const TEnv *MJob::GetEnv() const
+{
+    return static_cast<const TEnv *const>(fEnv);
+}
+
+Int_t MJob::GetEnv(const char *name, Int_t dflt) const
+{
+    return GetEnvValue(*fEnv, fEnvPrefix, name, dflt); //    return fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
+}
+
+Double_t MJob::GetEnv(const char *name, Double_t dflt) const
+{
+    return GetEnvValue(*fEnv, fEnvPrefix, name, dflt); //    return fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
+}
+
+const char *MJob::GetEnv(const char *name, const char *dflt) const
+{
+    return GetEnvValue(*fEnv, fEnvPrefix, name, dflt); //fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
+}
+
+Bool_t MJob::HasEnv(const char *name) const
+{
+    return IsEnvDefined(*fEnv, fEnvPrefix, name, fEnvDebug>2);//fEnv->Lookup(Form("%s%s", fEnvPrefix.Data(), name));
+}
+
+Bool_t MJob::CheckEnv()
+{
+    if (!fEnv)
+        return kTRUE;
+
+    TString p;
+    p = GetEnv("PathOut", "");
+    if (!p.IsNull())
+        SetPathOut(p);
+
+    p = GetEnv("PathIn", "");
+    if (!p.IsNull())
+        SetPathIn(p);
+
+    p = GetEnv("PathData", "");
+    if (!p.IsNull())
+        SetPathData(p);
+
+    SetMaxEvents(GetEnv("MaxEvents", fMaxEvents));
+    SetOverwrite(GetEnv("Overwrite", fOverwrite));
+    SetEnvDebug( GetEnv("EnvDebug",  fEnvDebug));
+
+    return CheckEnvLocal();
+}
+
+Bool_t MJob::SetupEnv(MEvtLoop &loop) const
+{
+    if (!fEnv)
+        return kTRUE;
+
+    if (!loop.ReadEnv(*fEnv, fEnvPrefix, fEnvDebug>2))
+        return kFALSE;
+
+    if (fEnvDebug>1)
+        fEnv->PrintUntouched();
+
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Write containers in list to gFile. Returns kFALSE if no gFile or any
+// container couldn't be written. kTRUE otherwise.
+//
+Bool_t MJob::WriteContainer(TCollection &list) const
+{
+    if (!gFile)
+    {
+        *fLog << err << dbginf << "ERROR - No file open (gFile==0)" << endl;
+        return kFALSE;
+    }
+
+    TIter Next(&list);
+    TObject *o=0;
+    while ((o=Next()))
+    {
+        *fLog << inf << " - Writing " << MParContainer::GetDescriptor(*o) << "..." << flush;
+        if (o->Write(o->GetName())<=0)
+        {
+            *fLog << err << dbginf << "ERROR - Writing " << MParContainer::GetDescriptor(*o) << " to file " << gFile->GetName() << endl;
+            return kFALSE;
+        }
+        *fLog << "ok." << endl;
+    }
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Read containers in list into list from gFile
+// Returns kFALSE if no gFile or any container couldn't be read.
+//
+Bool_t MJob::ReadContainer(TCollection &list) const
+{
+    if (!gFile)
+    {
+        *fLog << err << dbginf << "ERROR - No file open (gFile==0)" << endl;
+        return kFALSE;
+    }
+
+    MIter Next(&list);
+    MParContainer *o=0;
+    while ((o=Next()))
+    {
+        *fLog << inf << " - Reading " << o->GetDescriptor() << "..." << flush;
+        if (o->Read(o->GetName())<=0)
+        {
+            *fLog << err << dbginf << "ERROR - Reading " << o->GetDescriptor() << " from file " << gFile->GetName() << endl;
+            return kFALSE;
+        }
+        *fLog << "ok." << endl;
+    }
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Write containers in cont (and - if available) the status display to
+// fPathOut+"/"+name
+//
+Bool_t MJob::WriteContainer(TCollection &cont, const char *name, const char *option, const int compr) const
+{
+    if (fPathOut.IsNull())
+    {
+        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
+        return kTRUE;
+    }
+
+    TString oname(fPathOut);
+    oname += "/";
+    oname += name;
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TString title("File Written by ");
+    title += fName;
+
+    TFile file(oname, option, title, compr);
+    if (!file.IsOpen())
+    {
+        *fLog << err << "ERROR - Couldn't open file " << oname << " for writing..." << endl;
+        return kFALSE;
+    }
+
+    if (fDisplay)
+        cont.Add((TObject*)(fDisplay));
+
+    return WriteContainer(cont);
+}
Index: /tags/Mars-V0.9/mjobs/MJob.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MJob.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MJob.h	(revision 9772)
@@ -0,0 +1,80 @@
+#ifndef MARS_MJob
+#define MARS_MJob
+
+#ifndef MARS_MSequence
+#include "MSequence.h"
+#endif
+
+class MEnv;
+class MEvtLoop;
+
+class MJob : public MParContainer
+{
+private:
+    enum { kIsOwner = BIT(14) };
+
+    void FixPath(TString &path) const;
+    void ClearEnv();
+
+    const MEnv *fEnv;         // Resource file
+    TString     fEnvPrefix;   // Prefix for resources
+    Int_t       fEnvDebug;    // Debug setup of resources
+
+protected:
+    TString   fPathOut;       // Directory to write output file to (eg. calib*.root)
+    TString   fPathIn;        // Directory to read output from (eg. calib*.root)
+    TString   fPathData;      // Directory to read  data files from (2004*.root)
+
+    Bool_t    fOverwrite;     // Allow overwriting output files
+    Int_t     fMaxEvents;     // Maximum number of events
+
+    MSequence fSequence;      // Sequence
+
+    const TEnv *GetEnv() const;
+    const MEnv *GetMEnv() const { return fEnv; }
+    const TString &GetEnvPrefix() const { return fEnvPrefix; }
+    Int_t GetEnvDebug() const { return fEnvDebug; }
+
+    Int_t       GetEnv(const char *name, Int_t dflt) const;
+    Double_t    GetEnv(const char *name, Double_t dflt) const;
+    const char *GetEnv(const char *name, const char *dflt) const;
+    Bool_t      HasEnv(const char *name) const;
+
+    Bool_t SetupEnv(MEvtLoop &loop) const;
+    Bool_t CheckEnv();
+    void PrintUntouchedEnv() const;
+    virtual Bool_t CheckEnvLocal() { return kTRUE; }
+
+    Bool_t WriteContainer(TCollection &list) const;
+    Bool_t ReadContainer(TCollection &list) const;
+    Bool_t WriteContainer(TCollection &cont, const char *name, const char *option="RECREATE", const int compr=2) const;
+
+public:
+    MJob(const char *name=NULL, const char *title=NULL);
+    ~MJob();
+
+    // Setter
+    void   SetPathOut(const char *path=".");
+    void   SetPathIn(const char *path=".");
+    void   SetPathData(const char *path=".");
+
+    void   SetOverwrite(Bool_t b=kTRUE) { fOverwrite=b; }
+    Bool_t SetEnv(const char *env, const char *prefix=0);
+    void   SetEnv(MEnv *env, const char *prefix=0);
+    void   SetEnvDebug(Int_t d=2) { fEnvDebug=d; }
+
+    void   SetMaxEvents(Int_t max) { fMaxEvents = max; }
+    void   SetSequence(const MSequence &seq) { fSequence = seq; }
+
+    // Getter
+    TString GetPathOut() const  { return fPathOut; }
+    TString GetPathIn() const   { return fPathIn; }
+    TString GetPathData() const { return fPathData; }
+
+    // Others
+    MStatusDisplay *GetDisplay() { return fDisplay; }
+
+    ClassDef(MJob, 0) // Bas class for Jobs
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/MSequence.cc
===================================================================
--- /tags/Mars-V0.9/mjobs/MSequence.cc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MSequence.cc	(revision 9772)
@@ -0,0 +1,464 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSequence
+//
+//  This class describes a sequence. For sequences see:
+//    http://magic.astro.uni-wuerzburg.de/mars/db/queryseq.html
+//
+//  A sequence is a collection of runs which should be used together.
+//
+//  Here is an example how a file describing a sequence could look like:
+//
+// ===========================================================================
+//
+//  sequence.txt
+//  ------------
+//
+//   # Sequence number (identifier)
+//   Sequence:     31015
+//   # Observation Period (used to get the path-names)
+//   Period:       18
+//   # Date of sunrise of the observation night
+//   Night:        2004-06-24
+//
+//   # Start time of the sequence (first data run)
+//   Start:        2004-06-24 03:12:42
+//   # Run number of last data run in sequence
+//   LastRun:      31032
+//   # Project name of data-runs of sequence
+//   Project:      3EG2033+41
+//   # Source name of all runs of sequence
+//   Source:       3EG2033+41
+//   # Trigger table of data-runs of sequence
+//   TriggerTable: L1_4NN:L2_DEFAULT
+//   # HV Setting table of data-runs of sequence
+//   HvSettings:   HVSettings_FF36q
+//   # Total number of data-events in sequence
+//   NumEvents:    250914
+//
+//   # List of all runs of this sequence
+//   Runs: 31015 31016 31017 31018 31019 31020 31021 31022 31023 31024 31025 31026 31027 31028 31029 31030 31031 31032
+//
+//   # List of all calibration runs of this sequence
+//   CalRuns: 31015 31016 31017
+//   # List of pedestal runs belonging to the calibration runs of this sequence
+//   PedRuns: 31018
+//   # List of all data runs belonging to this sequence
+//   DatRuns: 31019 31020 31022 31023 31024 31025 31027 31028 31030 31032
+//
+//   # List of run types of all runs
+//   31015: C
+//   31016: C
+//   31017: C
+//   31018: P
+//   31019: D
+//   31020: D
+//   31021: P
+//   31022: D
+//   31023: D
+//   31024: D
+//   31025: D
+//   31026: P
+//   31027: D
+//   31028: D
+//   31029: P
+//   31030: D
+//   31031: P
+//   31032: D
+//
+// ===========================================================================
+//
+//  For special cases you can also setup a sequence directly from a macro,
+//  for example:
+//
+//    MDirIter pediter, datiter, caliter;
+//
+//    MSequence seq;
+//    seq.SetNight("2004-07-06");
+//    seq.AddPedRuns(31751);
+//    seq.AddCalRuns(31752);
+//    seq.AddDatRuns(31753, 31764);
+//    seq.SetupPedRuns(pediter);
+//    seq.SetupCalRuns(caliter);
+//    seq.SetupDatRuns(datiter);
+//
+//  or
+//
+//    MDirIter iter;
+//
+//    MSequence seq;
+//    seq.SetNight("2004-07-06");
+//    seq.AddRuns(31753, 31764);
+//    seq.SetupRuns(iter);
+//    seq.SetupPedRuns(iter, "/mypath", "[DPC]");
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSequence.h"
+
+#include <stdlib.h>
+
+#include <TEnv.h>
+#include <TRegexp.h>
+#include <TSystem.h> // TSystem::ExpandPath
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MAstro.h"
+#include "MString.h"
+#include "MDirIter.h"
+
+ClassImp(MSequence);
+
+using namespace std;
+
+MSequence::~MSequence()
+{
+    /*
+    TExMapIter iter(&fFileNames);
+
+    Long_t key, val;
+
+    while (iter.Next(key, val))
+        delete (TString*)val;
+        */
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Copy the run numbers from the TString runs into the TArrayI data
+//
+void MSequence::Split(TString &runs, TArrayI &data) const
+{
+    const TRegexp regexp("[0-9]+");
+
+    data.Set(0);
+    runs = runs.Strip(TString::kTrailing);
+
+    while (!runs.IsNull())
+    {
+        TString num = runs(regexp);
+
+        const Int_t n = data.GetSize();
+        data.Set(n+1);
+        data[n] = atoi(num.Data());
+
+        runs.Remove(0, runs.First(num)+num.Length());
+    }
+}
+
+const TString MSequence::GetStandardPath(Bool_t raw) const
+{
+    TString d("/magic/data/");
+    d += raw ? "rawfiles/" : "merpp/";
+    return d;
+}
+
+UInt_t MSequence::SetupRuns(MDirIter &iter, const TArrayI &arr, const char *path, char *id, Bool_t raw) const
+{
+    TString d(path);
+
+    // Setup path
+    if (d.IsNull())
+    {
+        d = GetStandardPath(raw);
+        d += fNight.GetStringFmt("%Y/%m/%d");
+    }
+    else
+        gSystem->ExpandPathName(d);
+
+    for (int i=0; i<arr.GetSize(); i++)
+    {
+        // R. DeLosReyes and T. Bretz
+        // Changes to read the DAQ numbering format. Changes takes place
+        // between runs 35487 and 00035488 (2004_08_30)
+        const char *fmt = arr[i]>35487 ? "%08d_%s_*_E" : "%05d_%s_*_E";
+
+        TString n;
+
+        // Create file name
+        n =  fNight.GetStringFmt("%Y%m%d_");
+        n += Form(fmt, arr[i], id);
+        n += raw ? ".raw" : ".root";
+
+        // Add Path/File to TIter
+        iter.AddDirectory(d, n, 0);
+    }
+
+    return iter.GetNumEntries();
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the file fname as setup file for the sequence.
+//
+void MSequence::GetFileNames(TEnv &env, const TArrayI &arr)
+{
+    /*
+    for (int i=0; i<arr.GetSize(); i++)
+    {
+        // Get run number
+        const Int_t num = arr[i];
+
+        // Check if name already set
+        if (fFileNames.GetValue(num))
+            continue;
+
+        TString *str = new TString(env.GetValue(Form("%d", num), ""));
+        fFileNames.Add(num, (Long_t)str);
+        }
+        */
+}
+
+// --------------------------------------------------------------------------
+//
+// Get a file name corresponding to the run-number num, returns 0 if n/a
+//
+const char *MSequence::GetFileName(UInt_t num)
+{
+    return 0;
+    /*
+    TString *str = (TString*)fFileNames.GetValue(num);
+    return str ? str->Data() : 0;*/
+}
+
+MSequence::LightCondition_t MSequence::ReadLightCondition(TEnv &env) const
+{
+    TString str = env.GetValue("LightCondition", "n/a");
+    if (!str.CompareTo("n/a", TString::kIgnoreCase))
+        return kNA;
+    if (!str.CompareTo("NoMoon", TString::kIgnoreCase))
+        return kNoMoon;
+    if (!str.CompareTo("Twilight", TString::kIgnoreCase))
+        return kTwilight;
+    if (!str.CompareTo("Moon", TString::kIgnoreCase))
+        return kMoon;
+
+    gLog << warn << "MSequence: LightCondition-tag not n/a, nomoon, twilight or moon." << endl;
+    return kNA;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the file fname as setup file for the sequence.
+//
+MSequence::MSequence(const char *fname)
+{
+    fName  = fname;
+
+    const char *expname = gSystem->ExpandPathName(fname);
+
+    fTitle = Form("Sequence contained in file %s", expname);
+
+    TEnv env(expname);
+    delete [] expname;
+
+    TString str;
+
+    fSequence  = env.GetValue("Sequence",  -1);
+    fLastRun   = env.GetValue("LastRun",   -1);
+    fNumEvents = env.GetValue("NumEvents", -1);
+    fPeriod    = env.GetValue("Period",    -1);
+
+    fLightCondition = ReadLightCondition(env);
+
+    str = env.GetValue("Start", "");
+    fStart.SetSqlDateTime(str);
+    str = env.GetValue("Night", "");
+    str += " 00:00:00";
+    fNight.SetSqlDateTime(str);
+
+    fProject      = env.GetValue("Project", "");
+    fSource       = env.GetValue("Source", "");
+    fTriggerTable = env.GetValue("TriggerTable", "");
+    fHvSettings   = env.GetValue("HvSettings", "");
+
+    str = env.GetValue("Runs", "");
+    Split(str, fRuns);
+    str = env.GetValue("CalRuns", "");
+    Split(str, fCalRuns);
+    str = env.GetValue("PedRuns", "");
+    Split(str, fPedRuns);
+    str = env.GetValue("DatRuns", "");
+    Split(str, fDatRuns);
+
+    GetFileNames(env, fRuns);
+    GetFileNames(env, fCalRuns);
+    GetFileNames(env, fPedRuns);
+    GetFileNames(env, fDatRuns);
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the sequence
+//
+void MSequence::Print(Option_t *o) const
+{
+    gLog << all;
+    if (!IsValid())
+    {
+        gLog << "Sequence: " << fName << " <invalid>" << endl;
+        return;
+    }
+    gLog << "Sequence:       " << fSequence << endl;
+    gLog << "Period:         " << fPeriod << endl;
+    gLog << "Night:          " << fNight << endl << endl;
+    gLog << "LightCondition: ";
+    switch (fLightCondition)
+    {
+    case kNA:       gLog << "n/a" << endl;      break;
+    case kNoMoon:   gLog << "NoMoon" << endl;   break;
+    case kTwilight: gLog << "Twilight" << endl; break;
+    case kMoon:     gLog << "Moon" << endl;     break;
+    }
+    gLog << "Start:          " << fStart << endl;
+    gLog << "LastRun:        " << fLastRun << endl;
+    gLog << "NumEvents:      " << fNumEvents << endl;
+    gLog << "Project:        " << fProject << endl;
+    gLog << "Source:         " << fSource << endl;
+    gLog << "TriggerTable:   " << fTriggerTable << endl;
+    gLog << "HvSettings:     " << fHvSettings << endl << endl;
+    gLog << "Runs:";
+    for (int i=0; i<fRuns.GetSize(); i++)
+        gLog << " " << fRuns[i];
+    gLog << endl;
+    gLog << "CalRuns:";
+    for (int i=0; i<fCalRuns.GetSize(); i++)
+        gLog << " " << fCalRuns[i];
+    gLog << endl;
+    gLog << "PedRuns:";
+    for (int i=0; i<fPedRuns.GetSize(); i++)
+        gLog << " " << fPedRuns[i];
+    gLog << endl;
+    gLog << "DatRuns:";
+    for (int i=0; i<fDatRuns.GetSize(); i++)
+        gLog << " " << fDatRuns[i];
+    gLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all ped runs from the sequence to MDirIter.
+// If path==0 the standard path of the data-center is assumed.
+// If you have the runs locally use path="."
+// Using raw=kTRUE you get correspodning raw-files setup.
+// Return the number of files added.
+//
+UInt_t MSequence::SetupPedRuns(MDirIter &iter, const char *path, char *id, Bool_t raw) const
+{
+    return SetupRuns(iter, fPedRuns, path, id, raw);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all data runs from the sequence to MDirIter.
+// If path==0 the standard path of the data-center is assumed.
+// If you have the runs locally use path="."
+// Using raw=kTRUE you get correspodning raw-files setup.
+// Return the number of files added.
+//
+UInt_t MSequence::SetupDatRuns(MDirIter &iter, const char *path, char *id, Bool_t raw) const
+{
+    return SetupRuns(iter, fDatRuns, path, id, raw);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all runs from the sequence to MDirIter.
+// If path==0 the standard path of the data-center is assumed.
+// If you have the runs locally use path="."
+// Using raw=kTRUE you get correspodning raw-files setup.
+// Return the number of files added.
+//
+UInt_t MSequence::SetupAllRuns(MDirIter &iter, const char *path, char *id, Bool_t raw) const
+{
+    return SetupRuns(iter, fRuns, path, id, raw);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add all calibration runs from the sequence to MDirIter.
+// If path==0 the standard path of the data-center is assumed.
+// If you have the runs locally use path="."
+// Using raw=kTRUE you get correspodning raw-files setup.
+// Return the number of files added.
+//
+UInt_t MSequence::SetupCalRuns(MDirIter &iter, const char *path, char *id, Bool_t raw) const
+{
+    return SetupRuns(iter, fCalRuns, path, id, raw);
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to add runs manually, use this function.
+//
+UInt_t MSequence::AddRuns(UInt_t first, UInt_t last, TArrayI *runs)
+{
+    if (last<first)
+    {
+        *fLog << warn << "MSequence::AddRuns - WARNING: Last runnumber " << last;
+        *fLog << " smaller than first " << first << "... ignored." << endl;
+        return 0;
+    }
+    if (!IsValid())
+    {
+        *fLog << inf << "Setting Sequence number to #" << first << endl;
+        fSequence = first;
+    }
+
+    const UInt_t nall = fRuns.GetSize();
+    const UInt_t nrun = runs ? runs->GetSize() : 0;
+    const UInt_t add  = last-first+1;
+
+    fRuns.Set(nall+add);
+    if (runs)
+        runs->Set(nrun+add);
+
+    for (UInt_t i=0; i<add; i++)
+    {
+        fRuns[nall+i] = first+i;
+        if (runs)
+            (*runs)[nrun+i]  = first+i;
+    }
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you want to change or set the night manually.
+// The Format is
+//     SetNight("yyyy-mm-dd");
+//
+void MSequence::SetNight(const char *txt)
+{
+    TString night(txt);
+    night += " 00:00:00";
+    fNight.SetSqlDateTime(night);
+
+    fPeriod = MAstro::GetMagicPeriod(fNight.GetMjd());
+}
Index: /tags/Mars-V0.9/mjobs/MSequence.h
===================================================================
--- /tags/Mars-V0.9/mjobs/MSequence.h	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/MSequence.h	(revision 9772)
@@ -0,0 +1,120 @@
+#ifndef MARS_MSequence
+#define MARS_MSequence
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TExMap
+#include <TExMap.h>
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class MDirIter;
+
+class MSequence : public MParContainer
+{
+public:
+    enum LightCondition_t { kNA, kNoMoon, kTwilight, kMoon };
+private:
+    UInt_t fSequence;
+
+    MTime  fStart;
+
+    UInt_t fLastRun;
+    UInt_t fNumEvents;
+
+    UInt_t fPeriod;
+    MTime  fNight;
+
+    LightCondition_t fLightCondition;
+
+    TString fProject;
+    TString fSource;
+    TString fTriggerTable;
+    TString fHvSettings;
+
+    TArrayI fRuns;
+    TArrayI fCalRuns;
+    TArrayI fPedRuns;
+    TArrayI fDatRuns;
+
+    //TExMap fFileNames;
+
+    void Split(TString &runs, TArrayI &data) const;
+    void GetFileNames(TEnv &env, const TArrayI &arr);
+    LightCondition_t ReadLightCondition(TEnv &env) const;
+
+    const char *GetFileName(UInt_t num);
+
+    UInt_t SetupRuns(MDirIter &iter, const TArrayI &arr, const char *path, char *id, Bool_t raw=kFALSE) const;
+    UInt_t AddRuns(UInt_t first, UInt_t last, TArrayI *runs);
+
+public:
+    MSequence() : fSequence((UInt_t)-1), fLastRun((UInt_t)-1),
+        fNumEvents((UInt_t)-1), fPeriod((UInt_t)-1) { }
+    MSequence(const char *fname);
+    MSequence(const MSequence &s) : fSequence(s.fSequence), fStart(s.fStart),
+        fLastRun(s.fLastRun), fNumEvents(s.fNumEvents), fPeriod(s.fPeriod),
+        fNight(s.fNight), fProject(s.fProject), fSource(s.fSource),
+        fTriggerTable(s.fTriggerTable), fHvSettings(s.fHvSettings),
+        fRuns(s.fRuns), fCalRuns(s.fCalRuns), fPedRuns(s.fPedRuns),
+        fDatRuns(s.fDatRuns) { }
+    ~MSequence();
+
+    // TObject
+    void Print(Option_t *o="") const;
+
+    // Genaral interface
+    Bool_t IsValid() const { return fSequence!=(UInt_t)-1; }
+
+    UInt_t SetupPedRuns(MDirIter &iter, const char *path=0, char *id="P", Bool_t raw=kFALSE) const;
+    UInt_t SetupDatRuns(MDirIter &iter, const char *path=0, char *id="D", Bool_t raw=kFALSE) const;
+    UInt_t SetupAllRuns(MDirIter &iter, const char *path=0, char *id="?", Bool_t raw=kFALSE) const;
+    UInt_t SetupCalRuns(MDirIter &iter, const char *path=0, char *id="C", Bool_t raw=kFALSE) const;
+
+    // Getter
+    UInt_t GetNumAllRuns() const { return fRuns.GetSize(); }
+    UInt_t GetNumDatRuns() const { return fDatRuns.GetSize(); }
+    UInt_t GetNumPedRuns() const { return fPedRuns.GetSize(); }
+    UInt_t GetNumCalRuns() const { return fCalRuns.GetSize(); }
+
+    UInt_t GetSequence() const { return fSequence; }
+    UInt_t GetLastRun() const  { return fLastRun; }
+    UInt_t GetPeriod() const   { return fPeriod; }
+    LightCondition_t GetLightCondition() const { return fLightCondition; }
+    Bool_t HasMoon() const { return fLightCondition==kMoon; }
+
+    const UInt_t GetFirstRun() const { return fRuns[0]; }
+    const UInt_t GetFirstCalRun() const { return fCalRuns[0]; }
+    const UInt_t GetLastCalRun() const { return fCalRuns[fCalRuns.GetSize()-1]; }
+    const TArrayI &GetPedRuns() const { return fPedRuns; } 
+    const TArrayI &GetCalRuns() const { return fCalRuns; } 
+    const TArrayI &GetDatRuns() const { return fDatRuns; } 
+
+    const MTime &GetStart() const { return fStart; }
+    const MTime &GetNight() const { return fNight; }
+    const TString &GetSource() const { return fSource; } 
+
+    const TString GetStandardPath(Bool_t raw) const;
+
+    // Setter
+    void SetNight(const char*night);
+
+    UInt_t AddRuns(UInt_t first, UInt_t last)    { return MSequence::AddRuns(first, last, 0); }
+    UInt_t AddCalRuns(UInt_t first, UInt_t last) { return MSequence::AddRuns(first, last, &fCalRuns); }
+    UInt_t AddPedRuns(UInt_t first, UInt_t last) { return MSequence::AddRuns(first, last, &fPedRuns); }
+    UInt_t AddDatRuns(UInt_t first, UInt_t last) { return MSequence::AddRuns(first, last, &fDatRuns); }
+
+    UInt_t AddRuns(UInt_t num)    { return AddRuns(num, num); }
+    UInt_t AddCalRuns(UInt_t num) { return AddCalRuns(num, num); }
+    UInt_t AddPedRuns(UInt_t num) { return AddPedRuns(num, num); }
+    UInt_t AddDatRuns(UInt_t num) { return AddDatRuns(num, num); }
+
+    ClassDef(MSequence, 0)
+};
+
+#endif
Index: /tags/Mars-V0.9/mjobs/Makefile
===================================================================
--- /tags/Mars-V0.9/mjobs/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/Makefile	(revision 9772)
@@ -0,0 +1,47 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Jobs
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../mdata -I../mhbase -I../mhcalib \
+	   -I../mfileio -I../mfilter -I../manalysis -I../mhist -I../mcalib \
+           -I../mbadpixels -I../msignal -I../mraw -I../mpedestal -I../mtools \
+           -I../mimage -I../mpointing -I../mastro -I../mfbase -I../mhvstime \
+           -I../mtrigger
+
+SRCFILES = MSequence.cc \
+           MDataSet.cc \
+           MJob.cc \
+           MJCut.cc \
+           MJCalib.cc \
+	   MJStar.cc \
+	   MJPedestal.cc \
+           MJOptimize.cc \
+           MJCalibration.cc \
+           MJCalibrateSignal.cc \
+           MJExtractSignal.cc \
+           MJCalibTest.cc
+
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mjobs/badpixels_0_559.rc
===================================================================
--- /tags/Mars-V0.9/mjobs/badpixels_0_559.rc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/badpixels_0_559.rc	(revision 9772)
@@ -0,0 +1,1 @@
+0: 0 559
Index: /tags/Mars-V0.9/mjobs/calibrationref.rc
===================================================================
--- /tags/Mars-V0.9/mjobs/calibrationref.rc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/calibrationref.rc	(revision 9772)
@@ -0,0 +1,76 @@
+#
+# Reference lines for the data check, valid from for data
+# before Nov. 04:
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+ConvFADC2PheMin:          0.
+ConvFADC2PheMax:          5.
+ConvFADC2PhotMin:         0.
+ConvFADC2PhotMax:         10.
+#
+# Quantum Efficiencies:
+#
+QEMin:                    0.
+QEMax:                    3.
+#
+# Arrival Times from Max. bin:
+#
+ArrivalTimeMin:           1.
+ArrivalTimeMax:           10.
+#
+# Relative Time Calibration:
+#
+TimeOffsetMin:           -3.
+TimeOffsetMax:            3.
+TimeResolutionMin:        0.
+TimeResolutionMax:        1.
+######################################################################
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+RefConvFADC2PheInner:     0.14
+RefConvFADC2PheOuter:     0.4
+RefConvFADC2PhotInner:    0.8
+RefConvFADC2PhotOuter:    3.8
+#
+# Quantum Efficiencies:
+#
+RefQEInner:               0.18
+RefQEOuter:               0.12
+#
+# Arrival Times from Max. bin:
+#
+RefArrivalTimeInner:      4.5
+RefArrivalTimeOuter:      5.0
+RefArrivalTimeRmsInner:   0.5.
+RefArrivalTimeRmsOuter:   0.5.
+#
+# Relative Time Calibration:
+#
+RefTimeOffsetInner:       -0.23
+RefTimeOffsetOuter:       0.39    
+RefTimeResolutionInner:   0.153
+RefTimeResolutionOuter:   0.128
+#
+# Mean Absolute Time:
+#
+InnerRefTime:             3.4
+OuterRefTime:             4.2
+#
+# Mean Absolute Charge:
+#
+InnerRefCharge:           278.
+OuterRefCharge:           282.
Index: /tags/Mars-V0.9/mjobs/calibrationref_Nov04.rc
===================================================================
--- /tags/Mars-V0.9/mjobs/calibrationref_Nov04.rc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/calibrationref_Nov04.rc	(revision 9772)
@@ -0,0 +1,76 @@
+#
+# Reference lines for the data check, valid from for data
+# from Nov. 04 on
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+ConvFADC2PheMin:          0.
+ConvFADC2PheMax:          4.
+ConvFADC2PhotMin:         0.
+ConvFADC2PhotMax:         8.
+#
+# Quantum Efficiencies:
+#
+QEMin:                    -0.05
+QEMax:                    3.
+#
+# Relative Time Calibration:
+#
+TimeOffsetMin:           -3.
+TimeOffsetMax:            3.
+TimeResolutionMin:        0.
+TimeResolutionMax:        1.
+#
+# Arrival Times from Max. bin:
+#
+ArrivalTimeMin:           1.
+ArrivalTimeMax:           10.
+######################################################################
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Converstion factors:
+#
+RefConvFADC2PheInner:     0.13
+RefConvFADC2PheOuter:     0.33
+RefConvFADC2PhotInner:    0.71.
+RefConvFADC2PhotOuter:    2.8
+#
+# Quantum Efficiencies:
+#
+RefQEInner:               0.18
+RefQEOuter:               0.12
+#
+# Arrival Times from Max. bin:
+#
+RefArrivalTimeInner:      4.4
+RefArrivalTimeOuter:      5.0
+RefArrivalTimeRmsInner:   0.58.
+RefArrivalTimeRmsOuter:   0.57.
+#
+# Relative Time Calibration:
+#
+RefTimeOffsetInner:       -0.23
+RefTimeOffsetOuter:       0.39    
+RefTimeResolutionInner:   0.153
+RefTimeResolutionOuter:   0.128
+#
+# Mean Absolute Time:
+#
+InnerRefCharge:           295.
+OuterRefCharge:           299.
+#
+# Mean Absolute Charge:
+#
+InnerRefTime:             2.95
+OuterRefTime:             3.6
Index: /tags/Mars-V0.9/mjobs/pedestalref.rc
===================================================================
--- /tags/Mars-V0.9/mjobs/pedestalref.rc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/pedestalref.rc	(revision 9772)
@@ -0,0 +1,39 @@
+#
+# Reference lines and histogram limits for the data check in pedestal files
+#
+######################################################################
+######################################################################
+#
+# Histogram Limits:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+PedestalMin:                 4.
+PedestalMax:                 16.
+#
+# Pedestal RMS:
+#
+PedRmsMin:                   0.
+PedRmsMax:                   20.
+######################################################################
+#
+# Reference Lines:
+# 
+######################################################################
+#
+# Mean Pedestals:
+#
+RefPedClosedLids:            9.635
+RefPedExtraGalactic:         9.93
+RefPedGalactic:              10.03
+#
+# Pedestal RMS:
+#
+RefPedRmsClosedLidsInner:    1.7
+RefPedRmsExtraGalacticInner: 5.6
+RefPedRmsGalacticInner:      6.92
+RefPedRmsClosedLidsOuter:    1.7
+RefPedRmsExtraGalacticOuter: 3.35
+RefPedRmsGalacticOuter:      4.2
Index: /tags/Mars-V0.9/mjobs/signalref.rc
===================================================================
--- /tags/Mars-V0.9/mjobs/signalref.rc	(revision 9772)
+++ /tags/Mars-V0.9/mjobs/signalref.rc	(revision 9772)
@@ -0,0 +1,10 @@
+#
+# Reference lines for the data check, valid from for data
+# before Dec. 04:
+#
+######################################################################
+#
+# Mean Absolute Time:
+#
+InnerRefTime:             10.0
+OuterRefTime:             10.0
Index: /tags/Mars-V0.9/mmain/MAnalysis.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MAnalysis.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MAnalysis.cc	(revision 9772)
@@ -0,0 +1,326 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 9/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MAnalysis.h"
+
+#include <iostream>
+
+#include <TGLabel.h>       // TGlabel
+#include <TGButton.h>      // TGTextButton
+#include <TGTextEntry.h>   // TGNumberEntry
+
+#include "MGList.h"
+#include "MImgCleanStd.h"  // MImgCleanStd
+
+ClassImp(MAnalysis);
+
+using namespace std;
+
+enum {
+    kButHillas = 0x100
+};
+
+void MAnalysis::AddButtons()
+{
+    TGTextButton *hillas = new TGTextButton(fTop2, "Calculate Standard Hillas", kButHillas);
+
+    hillas->Associate(this);
+
+    fList->Add(hillas);
+
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsCenterY|kLHintsLeft, 10, 10, 5, 5);
+    fList->Add(laybut);
+
+    fTop2->AddFrame(hillas, laybut);
+}
+
+void MAnalysis::AddSetupTab()
+{
+    //
+    // Create Setup Tab
+    //
+    TGCompositeFrame *frame = CreateNewTab("Setup");
+ /*
+    TGGroupFrame *grp = new TGGroupFrame(frame, "Setup Display");
+    fList->Add(grp);
+
+    //
+    // Align the lines:
+    //  - top, left
+    //  - padding: top=20, bottom=0, left=20, right=0
+    //
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsNormal, 10, 10, 10);
+    fList->Add(laybut);
+
+    //
+    // Create check buttons for the first two lines
+    //
+    fCheckButton1 = new TGCheckButton(grp, "Display Hillas Histograms when finished");  //, M_CHECK_DISPLHIL);
+    fCheckButton2 = new TGCheckButton(grp, "Display Star Map Histogram when finished"); //, M_CHECK_DISPLHIL);
+
+    fList->AddFirst(fCheckButton1);
+    fList->AddFirst(fCheckButton2);
+
+    //
+    // Create first two lines with the checkbuttons
+    //
+    grp->AddFrame(fCheckButton1, laybut);
+    grp->AddFrame(fCheckButton2, laybut);
+ */
+    TGLayoutHints *laygrp = new TGLayoutHints(kLHintsNormal|kLHintsExpandX, 20, 20, 20);
+    fList->Add(laygrp);
+ /*
+    frame->AddFrame(grp, laygrp);
+  */
+
+    /*
+     * Create GUI for image cleaning
+     */
+    fImgClean = new MImgCleanStd;
+    fImgClean->CreateGui(frame, laygrp);
+    fList->Add(fImgClean);
+}
+
+MAnalysis::MAnalysis(/*const TGWindow *main,*/ const TGWindow *p,
+                     const UInt_t w, const UInt_t h)
+: MBrowser(/*main,*/ p, w, h)
+{
+    AddButtons();
+    AddSetupTab();
+
+    MapSubwindows();
+
+    Layout();
+
+    SetWindowName("Analysis Window");
+    SetIconName("Analysis");
+
+    MapWindow();
+}
+
+// ======================================================================
+
+#include "MStatusDisplay.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MGeomCamMagic.h"
+#include "MHHillas.h"
+#include "MHStarMap.h"
+#include "MReadMarsFile.h"
+#include "MMcPedestalCopy.h"     // MMcPedestalCopy
+#include "MMcPedestalNSBAdd.h"   // MMcPedestalNSB
+#include "MCerPhotCalc.h"
+#include "MImgCleanStd.h"
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+#include "MSrcPosCam.h"
+#include "MFillH.h"
+#include "MEvtLoop.h"
+#include "MHillas.h"
+#include "MGeomApply.h"
+
+void MAnalysis::CalculateHillas()
+{
+    //
+    // This is a demonstration program which calculates the Hillas
+    // parameter out of a Magic root file.
+
+    const Bool_t displhillas  = kTRUE;//fCheckButton1->GetState();
+    const Bool_t displstarmap = kTRUE;//fCheckButton2->GetState();
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // The geometry container must be created by yourself to make sure
+    // that you don't choos a wrong geometry by chance
+    //
+    MGeomCamMagic geomcam;
+    plist.AddToList(&geomcam);
+
+    MSrcPosCam source;
+    plist.AddToList(&source);
+    /*
+     MSrcPosCam source("Source");
+     source.SetXY(0, 0);
+     plist.AddToList(&source);
+
+     MSrcPosCam antisrc("AntiSrc");
+     antisrc.SetXY(240, 0);
+     plist.AddToList(&antisrc);
+     */
+
+    //
+    // Now setup the tasks and tasklist:
+    //
+    //  1) read in the data from a magic root file   MReadTree
+    //  2) calculate number of cerenkov photons      MCerPhotCalc
+    //  3) clean the image                           MImgCleanStd
+    //  4) calculate hillas                          MHillasCalc
+    //  5) fill the hillas into the histograms       MFillH
+    //
+
+    //
+    // The first argument is the tree you want to read.
+    //   Events:     Cosmic ray events
+    //   PedEvents:  Pedestal Events
+    //   CalEvents:  Calibration Events
+    //
+    MReadMarsFile read("Events", fInputFile);
+    //read.DisableAutoScheme();
+
+    MGeomApply         apply;
+    MMcPedestalCopy    pcopy;
+    MMcPedestalNSBAdd  pdnsb;
+    MCerPhotCalc       ncalc;
+    //MBlindPixelCalc    blind;
+    MHillasCalc        hcalc;
+    MHillasSrcCalc     csrc1;
+    /*
+     MHillasSrcCalc     csrc1("Source",  "HillasSource");
+     MHillasSrcCalc     csrc2("AntiSrc", "HillasAntiSrc");
+     */
+
+    MFillH hfill("MHHillas",       "MHillas");
+    MFillH hfill2("MHHillasExt",   "MHillasSrc");
+    MFillH hfill2s("MHHillasSrc",  "MHillasSrc");
+    MFillH hfill3("MHNewImagePar", "MNewImagePar");
+    MFillH sfill("MHStarMap",      "MHillas");
+    /*
+     MFillH hfill2s("HistSource  [MHHillasSrc]", "HillasSource");
+     MFillH hfill2a("HistAntiSrc [MHHillasSrc]", "HillasAntiSrc");
+     */
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pdnsb);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(fImgClean);
+    //tlist.AddToList(&blind);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&csrc1);
+    //tlist.AddToList(&csrc2);
+
+    if (displhillas)
+    {
+        tlist.AddToList(&hfill);
+        tlist.AddToList(&hfill2);
+        tlist.AddToList(&hfill2s);
+        tlist.AddToList(&hfill3);
+    }
+
+    if (displstarmap)
+        tlist.AddToList(&sfill);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Add ProgressBar to window
+    //
+    TGProgressBar *bar = NULL;
+    if (displhillas || displstarmap)
+    {
+        MStatusDisplay *d=new MStatusDisplay;
+        evtloop.SetDisplay(d);
+    }
+    else
+    {
+        bar = CreateProgressBar(fTop2);
+        evtloop.SetProgressBar(bar);
+    }
+
+
+    //
+    // Execute your analysis
+    //
+    /*Bool_t rc =*/ evtloop.Eventloop();
+
+    //
+    // Remove progressbar from window
+    //
+    if (bar)
+        DestroyProgressBar(bar);
+
+ /*
+    if (!rc)
+        return;
+
+    //
+    // After the analysis is finished we can display the histograms
+    //
+    if (displhillas)
+    {
+        plist.FindObject("MHHillas")->DrawClone();
+        plist.FindObject("MHHillasExt")->DrawClone();
+        plist.FindObject("MHHillasSrc")->DrawClone();
+        plist.FindObject("MHNewImagePar")->DrawClone();
+    }
+
+    if (displstarmap)
+        plist.FindObject("MHStarMap")->DrawClone();
+
+    cout << endl;
+    cout << "Calculation of Hillas Parameters finished without error!" << endl;
+ */
+}
+
+// ======================================================================
+
+Bool_t MAnalysis::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+{
+    // Process events generated by the buttons in the frame.
+
+    if (GET_MSG(msg)!=kC_COMMAND || GET_SUBMSG(msg)!=kCM_BUTTON)
+        return MBrowser::ProcessMessage(msg, parm1, parm2);
+
+    switch (parm1)
+    {
+    case kButHillas:
+        if (!InputFileSelected())
+        {
+            DisplError("No Input (root) File selected!");
+            return kTRUE;
+        }
+
+        switch (parm1)
+        {
+        case kButHillas:
+            CalculateHillas();
+            return kTRUE;
+        }
+        return kTRUE;
+    }
+
+    return MBrowser::ProcessMessage(msg, parm1, parm2);
+}
Index: /tags/Mars-V0.9/mmain/MAnalysis.h
===================================================================
--- /tags/Mars-V0.9/mmain/MAnalysis.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MAnalysis.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifndef MARS_MAnalysis
+#define MARS_MAnalysis
+
+#ifndef MARS_MBrowser
+#include "MBrowser.h"
+#endif
+
+class TGTextEntry;
+class TGCheckButton;
+
+class MImgCleanStd;
+
+class MAnalysis : public MBrowser
+{
+private:
+    TGCheckButton *fCheckButton1;
+    TGCheckButton *fCheckButton2;
+
+//    TGTextEntry   *fNumEntry1;
+//    TGTextEntry   *fNumEntry2;
+
+    MImgCleanStd  *fImgClean;
+
+    void CalculateHillas();
+
+    void AddButtons();
+    void AddSetupTab();
+
+public:
+    MAnalysis(/*const TGWindow *main=NULL,*/ const TGWindow *p=NULL,
+              const UInt_t w=500, const UInt_t h=500) ;
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+    ClassDef(MAnalysis, 0) // GUI: The 'Analysis' browser.
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MBrowser.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MBrowser.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MBrowser.cc	(revision 9772)
@@ -0,0 +1,604 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+#include "MBrowser.h"
+
+#include <iostream>
+#include <sys/stat.h>       // S_ISDIR
+
+#include <TSystem.h>        // gSystem
+
+#include <TGTab.h>          // TGTab
+#include <TGMenu.h>         // TGPopupMenu
+#include <TG3DLine.h>       // TGHorizontal3DLine
+#include <TGButton.h>       // TGTextButton
+#include <TGMsgBox.h>       // TGMsgBox
+#include <TBrowser.h>       // TBrowser
+#include <TGTextEntry.h>    // TGTextEntry
+#include <TGFSComboBox.h>   // TGFSComboBox, TGFSLboxEntry
+#include <TGProgressBar.h>  // TGHProgressBar
+#include <TGFSContainer.h>  // TGFileContainer
+
+#include "MGList.h"
+
+ClassImp(MBrowser);
+
+using namespace std;
+
+enum {
+    kFileTBrowser,
+    kFileClose,
+    kButDirUp,
+    kButListMode,
+    kButDetailMode,
+    kCBDirectory,
+    kCBFilter,
+    kTEFileName
+};
+
+void MBrowser::CreateMenuBar()
+{
+    //
+    //  crate the menu bar
+    //
+    TGPopupMenu *filemenu = new TGPopupMenu(gClient->GetRoot());
+    filemenu->AddEntry("Open &TBrowser", kFileTBrowser);
+    filemenu->AddSeparator();
+    filemenu->AddEntry("&Close", kFileClose);
+    filemenu->Associate(this);
+    fList->Add(filemenu);
+
+    //
+    //  the button messages are handled by main frame (this)
+    //
+    TGLayoutHints *laymenubar  = new TGLayoutHints(kLHintsTop|kLHintsLeft|kLHintsExpandX, 2, 2, 2, 2);
+    TGLayoutHints *laymenuitem = new TGLayoutHints(kLHintsTop|kLHintsLeft, 0, 4, 0, 0);
+
+    fList->Add(laymenubar);
+    fList->Add(laymenuitem);
+
+    TGMenuBar *menubar = new TGMenuBar(this, 1, 1, kHorizontalFrame);
+    menubar->AddPopup("&File", filemenu, laymenuitem);
+    AddFrame(menubar, laymenubar);
+    fList->Add(menubar);
+}
+
+void MBrowser::CreateUpperFrame(TGCompositeFrame *frametop)
+{
+    TGLayoutHints *lay1 = new TGLayoutHints(kLHintsTop    |kLHintsExpandX, 2, 2, 2, 0);
+    TGLayoutHints *lay2 = new TGLayoutHints(kLHintsCenterY|kLHintsExpandX, 2, 2, 2, 2);
+    TGLayoutHints *lay3 = new TGLayoutHints(kLHintsBottom |kLHintsExpandX, 2, 2, 0, 2);
+    fList->Add(lay1);
+    fList->Add(lay2);
+    fList->Add(lay3);
+
+    //
+    // *********** Create Contents of frame top (upper part) **********
+    //
+    fTop1 = new TGHorizontalFrame(frametop, 500, 50);
+    fTop2 = new TGHorizontalFrame(frametop, 500, 50);
+    fTop3 = new TGHorizontalFrame(frametop, 500, 50);
+
+    // FIXME: If I use TGLayoutHints the Progress Bar doesn't disappear!
+    frametop->AddFrame(fTop1);//, lay1);
+    frametop->AddFrame(fTop2);//, lay2);
+    frametop->AddFrame(fTop3);//, lay3);
+
+    fList->Add(fTop1);
+    fList->Add(fTop2);
+    fList->Add(fTop3);
+}
+
+void MBrowser::CreateDirListMenu(TGCompositeFrame *frame)
+{
+    //
+    // Layout Dir-Listbox and buttons in one row (frame)
+    //
+    //  - layout:
+    //    alignment: top, left
+    //    padding:   5, 5, 5, 5
+    //
+    TGLayoutHints *laydir = new TGLayoutHints(kLHintsExpandX|kLHintsLeft|kLHintsCenterY); //, 5, 5, 5, 5);
+    TGLayoutHints *layout = new TGLayoutHints(kLHintsRight|kLHintsCenterY, 10); //, 5, 5, 5);
+
+    fList->Add(laydir);
+    fList->Add(layout);
+
+    //
+    // Create Dir-Listbox and buttons in first frame
+    //
+    TGFSComboBox *dir = new TGFSComboBox(frame, kCBDirectory);
+    dir->SetHeight(fEntry->GetHeight());
+    dir->Associate(this);
+    fList->Add(dir);
+    frame->AddFrame(dir, laydir);
+
+    const TGPicture *pic0 = fList->GetPicture("magic_t.xpm");
+    if (pic0)
+    {
+        dir->GetListBox()->Resize(100, 150);
+        TGTreeLBEntry *entry = new TGTreeLBEntry(dir->GetListBox()->GetContainer(),
+                                                 new TGString("/data/MAGIC"), pic0, 6000,
+                                                 new TGString("/data/MAGIC"));
+        TGLayoutHints *laylb = new TGLayoutHints(kLHintsLeft|kLHintsTop, 14, 0, 0, 0);
+        dir->AddEntry(entry, laylb);
+        // Not necessary - deleted in ~TGLBContainer: fList->Add(laylb);
+        // fList->Add(laylb);
+    }
+
+    //
+    // Get the three picturs from the system (must be deleted by FreePicture)
+    //
+    const TGPicture *pic1 = fList->GetPicture("tb_list.xpm");
+    if (pic1)
+    {
+        TGPictureButton *list = new TGPictureButton(frame, pic1, kButListMode);
+        list->SetToolTipText("List Mode");
+        list->SetState(kButtonUp);
+        list->AllowStayDown(kTRUE);
+        list->Associate(this);
+        fList->Add(list);
+        frame->AddFrame(list, layout);
+    }
+
+    const TGPicture *pic2 = fList->GetPicture("tb_details.xpm");
+    if (pic2)
+    {
+        TGPictureButton *detail = new TGPictureButton(frame, pic2, kButDetailMode);
+        detail->SetToolTipText("Details Mode");
+        detail->SetState(kButtonEngaged);
+        detail->AllowStayDown(kTRUE);
+        detail->Associate(this);
+        fList->Add(detail);
+        frame->AddFrame(detail, layout);
+    }
+
+    const TGPicture *pic3 = fList->GetPicture("tb_uplevel.xpm");
+    if (pic3)
+    {
+        TGPictureButton *cdup = new TGPictureButton(frame, pic3, kButDirUp);
+        cdup->SetToolTipText("One Level up!");
+        cdup->Associate(this);
+        fList->Add(cdup);
+        frame->AddFrame(cdup, layout);
+    }
+}
+
+void MBrowser::CreateDirListBox(TGCompositeFrame *frame)
+{
+    //
+    // Create file viewer (browser)
+    //
+    fFileView = new TGListView(frame, 540, 380);
+    fList->Add(fFileView);
+
+    TGViewPort *port = fFileView->GetViewPort();
+    port->SetBackgroundColor(fgWhitePixel);
+
+    fFileCont = new TGFileContainer(port, 100, 100, kVerticalFrame, fgWhitePixel);
+    fList->Add(fFileCont);
+
+    fFileView->SetContainer(fFileCont);
+    fFileView->SetViewMode(kLVDetails);
+
+    fFileCont->SetFilter("*.root");
+    fFileCont->Associate(this);
+    fFileCont->Sort(kSortByName);
+
+    TGLayoutHints *layview = new TGLayoutHints(kLHintsTop|kLHintsExpandX|kLHintsExpandY); //, 5, 5, 5, 5);
+    fList->Add(layview);
+
+    frame->AddFrame(fFileView, layview);
+}
+
+void MBrowser::CreateTab1()
+{
+    static const char *filters[] =
+    {
+        "*.root <root-files>",
+        "*      <All Files>",
+        NULL
+    };
+
+    TGCompositeFrame *frame = CreateNewTab("Input File");
+
+    //
+    // Create three frames for the first tab
+    //
+    TGHorizontalFrame *tab1 = new TGHorizontalFrame(frame, 100, 100);
+    TGVerticalFrame   *tab2 = new TGVerticalFrame  (frame, 100, 100);
+
+    TGLayoutHints *laytab1   = new TGLayoutHints(kLHintsNormal|kLHintsExpandX,  10, 10, 10);
+    TGLayoutHints *laytab2   = new TGLayoutHints(kLHintsExpandX|kLHintsExpandY, 10, 10, 10, 10);
+    TGLayoutHints *layfilter = new TGLayoutHints(kLHintsNormal|kLHintsExpandX,  10, 10, 10);
+
+    fEntry = new TGTextEntry(frame, "", kTEFileName);
+    fEntry->Associate(this);
+
+    TGComboBox *filter = new TGComboBox(frame, kCBFilter);
+    filter->SetHeight(fEntry->GetHeight());
+    filter->Associate(this);
+    for (int i=0; filters[i]; i++)
+        filter->AddEntry(filters[i], i);
+    filter->Select(0);
+
+    frame->AddFrame(fEntry, laytab1);
+    frame->AddFrame(tab1,   laytab1);
+    frame->AddFrame(filter, layfilter);
+    frame->AddFrame(tab2,   laytab2);
+
+    CreateDirListMenu(tab1);
+    CreateDirListBox(tab2);
+
+    fList->Add(laytab1);
+    fList->Add(laytab2);
+    fList->Add(tab1);
+    fList->Add(tab2);
+    fList->Add(layfilter);
+    fList->Add(fEntry);
+    fList->Add(filter);
+}
+
+TGCompositeFrame *MBrowser::CreateNewTab(const char *name)
+{
+    return fTabs->AddTab(name);
+}
+
+void MBrowser::CreateLowerFrame(TGCompositeFrame *framelow)
+{
+    //
+    // *********** Create Contents of frame low (downer part) **********
+    //
+
+    //
+    // ----- Create Object holding the Tabs -----
+    //
+    fTabs = new TGTab(framelow, 400, 400);
+    fList->Add(fTabs);
+
+    TGLayoutHints *laytabs = new TGLayoutHints(kLHintsBottom|kLHintsExpandX|kLHintsExpandY, 5, 5, 5, 5);
+    fList->Add(laytabs);
+
+    framelow->AddFrame(fTabs, laytabs);
+
+    //
+    // --- Create the first tab of the tabs ---
+    //
+    CreateTab1();
+}
+
+MBrowser::MBrowser(/*const TGWindow *main,*/ const TGWindow *p,
+                   const UInt_t w, const UInt_t h)
+//: TGTransientFrame(p?p:gClient->GetRoot(),
+//                   main?main:gClient->GetRoot(), w, h)
+: TGMainFrame(p?p:gClient->GetRoot(), w, h)
+{
+    fList = new MGList;
+    fList->SetOwner();
+
+    CreateMenuBar();
+
+    TGLayoutHints *laylinesep  = new TGLayoutHints(kLHintsTop|kLHintsExpandX);
+    fList->Add(laylinesep);
+
+    TGHorizontal3DLine *linesep = new TGHorizontal3DLine(this);
+    fList->Add(linesep);
+    AddFrame(linesep, laylinesep);
+
+    //
+    // ---- Create the top window with a lot of buttons ----
+    //
+    TGLayoutHints *layframetop = new TGLayoutHints(kLHintsExpandX);
+    fList->Add(layframetop);
+
+    TGCompositeFrame *frametop = new TGCompositeFrame(this, 300, 100, kVerticalFrame);
+    fList->Add(frametop);
+    AddFrame(frametop, layframetop);
+
+    linesep = new TGHorizontal3DLine(this);
+    fList->Add(linesep);
+    AddFrame(linesep, laylinesep);
+
+    //
+    // ---- Create the low window with a tabs in it ----
+    //
+    TGLayoutHints *layframelow = new TGLayoutHints(kLHintsExpandX|kLHintsExpandY);
+    fList->Add(layframelow);
+
+    TGCompositeFrame *framelow = new TGCompositeFrame(this, 300, 100, kHorizontalFrame);
+    fList->Add(framelow);
+
+    AddFrame(framelow, layframelow);
+
+    CreateUpperFrame(frametop);
+    CreateLowerFrame(framelow);
+
+    //
+    //   Map the window, set up the layout, etc.
+    //
+    ChangeDir();
+    SetWMSizeHints(400, 350, 1000, 1000, 10, 10); // set the smallest and biggest size of the Main frame
+    Move(rand()%100+50, rand()%100+50);
+}
+
+
+MBrowser::~MBrowser()
+{
+    delete fList;
+} 
+
+TGProgressBar *MBrowser::CreateProgressBar(TGHorizontalFrame *frame)
+{
+    static TGLayoutHints laybar(kLHintsCenterY|kLHintsRight/*|kLHintsExpandX*/,
+                                10, 10);
+
+    TGHProgressBar *bar=new TGHProgressBar(frame);
+
+    bar->SetWidth(150);
+    bar->ShowPosition();
+
+    frame->AddFrame(bar, &laybar);
+
+    Layout();
+    MapSubwindows();
+
+    return bar;
+}
+
+void MBrowser::DestroyProgressBar(TGProgressBar *bar)
+{
+    TGHorizontalFrame *frame = (TGHorizontalFrame*)bar->GetParent();
+
+    frame->RemoveFrame(bar);
+
+    Layout();
+    MapSubwindows();
+
+    delete bar;
+}
+
+void MBrowser::CloseWindow()
+{
+   // Got close message for this MainFrame. Calls parent CloseWindow()
+   // (which destroys the window) and terminate the application.
+   // The close message is generated by the window manager when its close
+   // window menu item is selected.
+
+    delete this;
+}
+
+Bool_t MBrowser::InputFileSelected() 
+{
+    //
+    // Checks if there is a selected input root file
+    //
+    return !fInputFile.IsNull(); //[0]!='\0';
+}
+
+void MBrowser::DisplError(const char *txt)
+{
+    Int_t retval;
+    new TGMsgBox(fClient->GetRoot(), this, "Error!", txt,
+                 kMBIconExclamation, 4, &retval);
+}
+
+void MBrowser::DisplWarning(const char *txt)
+{
+    Int_t retval;
+    new TGMsgBox(fClient->GetRoot(), this, "Warning!", txt,
+                 kMBIconExclamation, 4, &retval);
+}
+
+void MBrowser::DisplInfo(const char *txt)
+{
+    Int_t retval;
+    new TGMsgBox(fClient->GetRoot(), this, "Information!", txt,
+                 kMBIconExclamation, 4, &retval);
+}
+
+void MBrowser::ChangeDir(const char *txt)
+{
+    fFileCont->ChangeDirectory(txt?txt:gSystem->WorkingDirectory());
+
+    const char *dir = fFileCont->GetDirectory();
+
+    TGFSComboBox *cbox = (TGFSComboBox*)fList->FindWidget(kCBDirectory);
+    if (cbox)
+        cbox->Update(dir);
+}
+
+void MBrowser::SetFileName(TString name)
+{
+    if (name[0]!='/')
+    {
+        name.Insert(0, "/");
+        name.Insert(0, fFileCont->GetDirectory());
+    }
+
+    if (gSystem->AccessPathName(name, kFileExists))
+        return;
+
+    if (name.EndsWith(".root", TString::kIgnoreCase))
+        fInputFile = name;
+
+    fEntry->SetText(gSystem->BaseName(name));
+
+    ChangeDir(gSystem->DirName(name));
+}
+
+void MBrowser::SetDir()
+{
+    TGFSComboBox *cbox = (TGFSComboBox*)fList->FindWidget(kCBDirectory);
+    if(!cbox)
+        return;
+
+    const TGTreeLBEntry *entry = (TGTreeLBEntry*)cbox->GetSelectedEntry();
+
+    ChangeDir(entry->GetPath()->GetString());
+}
+
+void MBrowser::SetFilter()
+{
+    //
+    // Try to get widget from list
+    //
+    TGComboBox *filter = (TGComboBox*)fList->FindWidget(kCBFilter);
+    if (!filter)
+        return;
+
+    //
+    // Get the selected text from the list box
+    //
+    const TGTextLBEntry *selected = (TGTextLBEntry*)filter->GetListBox()->GetSelectedEntry();
+
+    //
+    // find filter and remove leading spaces
+    //
+    TString txt = selected->GetText()->GetString();
+    if (txt.First('<') < 0)
+        return;
+
+    //
+    // Set new filter and refresh the file container
+    //
+    txt.Remove(txt.First('<'));
+
+    TString ftxt = txt.Strip();
+    fFileCont->SetFilter(ftxt);
+    fFileCont->DisplayDirectory();
+}
+
+void MBrowser::SetViewMode(const Int_t mode)
+{
+    fFileView->SetViewMode(mode ? kLVList : kLVDetails);
+
+    TGButton *but = (TGButton*)fList->FindWidget(mode);
+    if(!but)
+        return;
+
+    but->SetState(kButtonUp);
+}
+
+// --------------------------------------------------------------------------
+//
+// Process events generated by the gui elements in the frame.
+//
+Bool_t MBrowser::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
+{
+    switch (GET_MSG(msg))
+    {
+    case kC_TEXTENTRY:
+        if (GET_SUBMSG(msg)!=kTE_ENTER)
+            return kTRUE;
+
+        SetFileName(fEntry->GetText());
+        return kTRUE;
+
+    case kC_COMMAND:
+        switch (GET_SUBMSG(msg))
+        {
+        case kCM_MENU:
+            switch (parm1)
+            {
+            case kFileClose:
+                CloseWindow();
+                return kTRUE;
+
+            case kFileTBrowser:
+                new TBrowser();
+                return kTRUE;
+            }
+            return kTRUE;
+
+        case kCM_BUTTON:
+            switch (parm1)
+            {
+            case kButDirUp:
+                //
+                //  goto the parent directory
+                //
+                ChangeDir("..");
+                return kTRUE;
+
+            case kButListMode:
+            case kButDetailMode:
+                SetViewMode(parm1);
+                return kTRUE;
+            }
+            return kTRUE;
+
+        case kCM_COMBOBOX:
+            switch (parm1)
+            {
+            case kCBDirectory:
+                SetDir();
+                return kTRUE;
+            case kCBFilter:
+                SetFilter();
+                return kTRUE;
+            }
+            return kTRUE;
+        }
+        return kTRUE;
+
+    case kC_CONTAINER:
+        switch (GET_SUBMSG(msg))
+        {
+
+            //      case kCT_ITEMCLICK:
+            // 	printf ("itemclick\n");
+            //      break;
+
+        case kCT_ITEMDBLCLICK:
+            //
+            //  process the double click in the file view container
+            //
+            if (parm1 != kButton1 || fFileCont->NumSelected() != 1)
+                return kTRUE;
+
+            //
+            //  one file selected
+            //
+            void *dummy = NULL;
+            const TGFileItem *item = (TGFileItem *)fFileCont->GetNextSelected(&dummy);
+
+            const char *str = item->GetItemName()->GetString();
+
+            //
+            // if the user choose a directory
+            // change to this directory
+            //
+            if (S_ISDIR(item->GetType()))
+            {
+                ChangeDir(str);
+                return kTRUE;
+            }
+
+            SetFileName(str);
+            return kTRUE;
+        }
+    }
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mmain/MBrowser.h
===================================================================
--- /tags/Mars-V0.9/mmain/MBrowser.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MBrowser.h	(revision 9772)
@@ -0,0 +1,80 @@
+#ifndef MARS_MBrowser
+#define MARS_MBrowser
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TGFrame
+#include <TGFrame.h>
+#endif
+
+class MGList;
+class TGTab;
+class TGListView;
+class TGTextEntry;
+class TGFSComboBox;
+class TGProgressBar;
+class TGPictureButton;
+class TGFileContainer;
+
+class MBrowser : public TGMainFrame/*TGTransientFrame*/
+{
+private:
+    TGTab            *fTabs;
+
+    TGTextEntry      *fEntry;
+
+    TGFileContainer  *fFileCont;
+    TGListView       *fFileView;
+
+    void CreateMenuBar();
+    void CreateTab1();
+    void CreateUpperFrame(TGCompositeFrame *frameup);
+    void CreateLowerFrame(TGCompositeFrame *framelow);
+    void CreateDirListMenu(TGCompositeFrame *frame);
+    void CreateDirListBox(TGCompositeFrame *frame);
+
+    void SetFileName(TString name);
+
+    void SetFilter();
+    void SetDir();
+    void SetViewMode(const Int_t mode);
+
+protected:
+    MGList *fList;
+    TString fInputFile;
+
+    TGCompositeFrame *CreateNewTab(const char *name);
+
+    void DisplError(const char *txt);
+    void DisplWarning(const char *txt);
+    void DisplInfo(const char *txt);
+
+    void ChangeDir(const char *txt=NULL);
+
+    TGProgressBar *CreateProgressBar(TGHorizontalFrame *frame);
+    void DestroyProgressBar(TGProgressBar *bar);
+
+    TGHorizontalFrame *fTop1;
+    TGHorizontalFrame *fTop2;
+    TGHorizontalFrame *fTop3;
+
+ public: 
+     MBrowser(/*const TGWindow *main=NULL,*/ const TGWindow *p=NULL,
+              const UInt_t w=500, const UInt_t h=500) ;
+
+     virtual ~MBrowser();
+
+     void   CloseWindow();
+
+     Bool_t InputFileSelected();
+
+     virtual Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+     ClassDef(MBrowser, 0)   // Base class for the Gui-Browsers
+} ; 
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MCameraDisplay.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MCameraDisplay.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MCameraDisplay.cc	(revision 9772)
@@ -0,0 +1,110 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+#include "MCameraDisplay.h"
+
+#include <TGButton.h>  // TGTextButton
+
+#include "MGList.h"
+#include "MEventDisplay.h"
+
+ClassImp(MCameraDisplay);
+
+enum {
+    kButDisplay = 0x100
+};
+
+// --------------------------------------------------------------------------
+//
+//  Create the 'Data Check' GUI Controls (Window) on the screen. To use it
+//  from within the interpreter you can call a Standard Version with
+//  'new MCameraDisplay()'
+//
+MCameraDisplay::MCameraDisplay(/*const TGWindow *main,*/ const TGWindow *p,
+                               const UInt_t w, const UInt_t h)
+: MBrowser(/*main,*/ p, w, h)
+{
+    TGTextButton *disp = new TGTextButton(fTop2, "Display Events", kButDisplay);
+    fList->Add(disp);
+
+    disp->Associate(this);
+
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsTop|kLHintsLeft, 10, 10, 5, 5);
+    fList->Add(laybut);
+
+    fTop2->AddFrame(disp, laybut);
+
+/*
+    const TGPicture *pic2 = fList->GetPicture("marslogo.xpm");
+    if (pic2)
+    {
+        TGPictureButton *mars  = new TGPictureButton(fTop2, pic2, -1);
+        fList->Add(mars);
+        TGLayoutHints *lay2 = new TGLayoutHints(kLHintsRight, 10, 10, 10, 10);
+        fList->Add(lay2);
+        fTop2->AddFrame(mars,  lay2);
+    }
+  */
+    MapSubwindows();
+
+    Layout();
+
+    SetWindowName("Camera Display Window");
+    SetIconName("Camera Dsiplay");
+
+    MapWindow();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Process the GUI control events (here: mainly button clicks)
+//
+Bool_t MCameraDisplay::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+{
+    // Process events generated by the buttons in the frame.
+
+    if (GET_MSG(msg)!=kC_COMMAND || GET_SUBMSG(msg)!=kCM_BUTTON)
+        return MBrowser::ProcessMessage(msg, parm1, parm2);
+
+    switch (parm1)
+    {
+    case kButDisplay:
+        if (!InputFileSelected())
+        {
+            DisplError("No Input (root) File selected!");
+            return kTRUE;
+        }
+
+        switch (parm1)
+        {
+        case kButDisplay:
+            new MEventDisplay(fInputFile);
+            return kTRUE;
+        }
+        return kTRUE;
+    }
+
+    return MBrowser::ProcessMessage(msg, parm1, parm2);
+}
Index: /tags/Mars-V0.9/mmain/MCameraDisplay.h
===================================================================
--- /tags/Mars-V0.9/mmain/MCameraDisplay.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MCameraDisplay.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MCameraDisplay
+#define MARS_MCameraDisplay
+
+#ifndef MARS_MBrowser
+#include "MBrowser.h"
+#endif
+
+class MCameraDisplay : public MBrowser
+{
+public:
+    MCameraDisplay(/*const TGWindow *main=NULL,*/ const TGWindow *p=NULL,
+                   const UInt_t w=500, const UInt_t h=500) ;
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+    ClassDef(MCameraDisplay, 0) // GUI: The 'camera display' browser.
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MDataCheck.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MDataCheck.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MDataCheck.cc	(revision 9772)
@@ -0,0 +1,211 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+#include "MDataCheck.h"
+
+#include <TGButton.h>  // TGTextButton
+
+#include "MGList.h"
+#include "MFillH.h"
+#include "MParList.h"
+#include "MEvtLoop.h"
+#include "MHFadcCam.h"
+#include "MTaskList.h"
+#include "MReadTree.h"
+#include "MGeomApply.h"
+#include "MGDisplayAdc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MDataCheck);
+
+using namespace std;
+
+// ---
+
+enum {
+    kButPedAdc = 0x100,
+    kButEvtAdc = 0x101,
+    kButPedTdc = 0x102,
+    kButEvtTdc = 0x103
+};
+
+// --------------------------------------------------------------------------
+//
+//  Create the 'Data Check' GUI Controls (Window) on the screen. To use it
+//  from within the interpreter you can call a Standard Version with
+//  'new MDataCheck()'
+//
+MDataCheck::MDataCheck(/*const TGWindow *main,*/ const TGWindow *p,
+                       const UInt_t w, const UInt_t h)
+: MBrowser(/*main,*/ p, w, h)
+{
+    //TGTextButton *pedadc = new TGTextButton(fTop1, "ADC Spectra of Pedestals", kButPedAdc);
+    TGTextButton *cradc  = new TGTextButton(fTop1, "ADC Spectra of Cosmics", kButEvtAdc);
+    TGTextButton *evttdc = new TGTextButton(fTop1, "Time Spectra of Cosmics", kButEvtTdc);
+    //TGTextButton *crtdc  = new TGTextButton(fTop3, "Run Spectra of Cosmics",    kButEvtTdc);
+
+    //pedadc->Associate(this);
+    cradc ->Associate(this);
+    evttdc->Associate(this);
+    //crtdc ->Associate(this);
+
+    //fList->Add(pedadc);
+    fList->Add(cradc);
+    fList->Add(evttdc);
+    //fList->Add(crtdc);
+
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsTop|kLHintsLeft, 10, 10, 5, 5);
+    fList->Add(laybut);
+
+    //fTop1->AddFrame(pedadc, laybut);
+    fTop1->AddFrame(cradc,  laybut);
+    fTop1->AddFrame(evttdc,  laybut);
+    //fTop3->AddFrame(pedtdc, laybut);
+    //fTop3->AddFrame(crtdc,  laybut);
+
+    MapSubwindows();
+
+    Layout();
+
+    SetWindowName("DataCheck Window");
+    SetIconName("DataCheck");
+
+    MapWindow();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Create the 'View Adc' GUI Controls (Window) on the screen.
+//  Therefor we have to process all data in a file and fill the corresponding
+//  histograms.
+//
+void MDataCheck::View(const char *inputfile, const char *treeName, MHFadcPix::Type_t t)
+{
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    // connect them in the required way.
+    //
+
+    //
+    //   create the data containers for the raw data
+    //
+    MParList plist;
+
+    //
+    // set up the tasks for this job
+    //
+    MTaskList tasks;
+    plist.AddToList(&tasks);
+
+    MReadTree read(treeName, inputfile);
+    read.DisableAutoScheme();
+
+    MGeomApply geomapl;
+
+    MHFadcCam hist(t);
+    plist.AddToList(&hist);
+
+    MFillH fill(&hist, "MRawEvtData");
+
+    tasks.AddToList(&read);
+    tasks.AddToList(&geomapl);
+    tasks.AddToList(&fill);
+
+    //
+    // set up the loop for the processing
+    //
+    MEvtLoop magic;
+    magic.SetParList(&plist);
+
+    //
+    // Add ProgressBar to window
+    //
+    TGProgressBar *bar = CreateProgressBar(fTop1);
+    magic.SetProgressBar(bar);
+
+    //
+    // Execute your analysis
+    //
+    Bool_t rc = magic.Eventloop();
+
+    //
+    // Remove progressbar from window
+    //
+    DestroyProgressBar(bar);
+
+    if (!rc)
+        return;
+
+    new MGDisplayAdc(&hist);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Process the GUI control events (here: mainly button clicks)
+//
+Bool_t MDataCheck::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+{
+    // Process events generated by the buttons in the frame.
+
+    if (GET_MSG(msg)!=kC_COMMAND || GET_SUBMSG(msg)!=kCM_BUTTON)
+        return MBrowser::ProcessMessage(msg, parm1, parm2);
+
+    switch (parm1)
+    {
+    case kButPedAdc:
+    case kButEvtAdc:
+    case kButPedTdc:
+    case kButEvtTdc:
+        if (!InputFileSelected())
+        {
+            DisplError("No Input (root) File selected!");
+            return kTRUE;
+        }
+
+        switch (parm1)
+        {
+        case kButPedAdc:
+            View(fInputFile, "PedEvents", MHFadcPix::kValue);
+            return kTRUE;
+
+        case kButEvtAdc:
+            View(fInputFile, "Events", MHFadcPix::kValue);
+            return kTRUE;
+
+        case kButPedTdc:
+            View(fInputFile, "PedEvents", MHFadcPix::kSlices);
+            return kTRUE;
+
+        case kButEvtTdc:
+            View(fInputFile, "Events", MHFadcPix::kSlices);
+            return kTRUE;
+        }
+        return kTRUE;
+    }
+
+    return MBrowser::ProcessMessage(msg, parm1, parm2);
+}
Index: /tags/Mars-V0.9/mmain/MDataCheck.h
===================================================================
--- /tags/Mars-V0.9/mmain/MDataCheck.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MDataCheck.h	(revision 9772)
@@ -0,0 +1,28 @@
+#ifndef MARS_MDataCheck
+#define MARS_MDataCheck
+
+#ifndef MARS_MBrowser
+#include "MBrowser.h"
+#endif
+
+#ifndef MARS_MHFadcPix
+#include "MHFadcPix.h"
+#endif
+
+class MDataCheck : public MBrowser
+{
+private:
+    void View(const char *inputfile, const char *treeName, MHFadcPix::Type_t t);
+
+public:
+    MDataCheck(/*const TGWindow *main=NULL,*/ const TGWindow *p=NULL,
+               const UInt_t w=500, const UInt_t h=500) ;
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+    ClassDef(MDataCheck, 0) // GUI: The 'data-check' browser.
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MEventDisplay.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MEventDisplay.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MEventDisplay.cc	(revision 9772)
@@ -0,0 +1,696 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MEventDisplay.h"
+
+//
+// C-lib
+//
+#include <stdlib.h>              // atoi
+
+//
+// root
+//
+#include <TFile.h>               // TFile
+#include <TTree.h>               // TTree
+#include <TList.h>               // TList::Add
+#include <TStyle.h>              // gStyle->SetOptStat
+#include <TCanvas.h>             // TCanvas::cd
+#include <TSystem.h>             // TSystem::BaseName
+
+//
+// root GUI
+//
+#include <TGLabel.h>             // TGLabel
+#include <TGButton.h>            // TGPictureButton
+#include <TG3DLine.h>            // TGHorizontal3DLine
+#include <TGTextEntry.h>         // TGTextEntry
+#include <TGButtonGroup.h>       // TGVButtonGroup
+#include <TRootEmbeddedCanvas.h> // TRootEmbeddedCanvas
+
+//
+// General
+//
+#include "MGList.h"              // MGList
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"            // MParList::AddToList
+#include "MEvtLoop.h"            // MEvtLoop::GetParList
+#include "MTaskList.h"           // MTaskList::AddToList
+
+//
+// Tasks
+//
+#include "MReadMarsFile.h"        // MReadMarsFile
+#include "MGeomApply.h"           // MGeomApply
+#include "MFDataMember.h"         // MFDataMember
+#include "MMcPedestalCopy.h"      // MMcPedestalCopy
+#include "MMcPedestalNSBAdd.h"    // MMcPedestalNSBAdd
+
+#include "MSignalCalc.h"          // MPedestalCalc
+#include "MTaskEnv.h"             // MTaskEnv
+#include "MExtractTimeAndChargeDigitalFilter.h"
+#include "MImgCleanStd.h"         // MImgCleanStd
+#include "MHillasCalc.h"          // MHillasCalc
+#include "MCalibrationRelTimeCalc.h" // MHillasSrcCalc
+#include "MPrint.h"               // 
+#include "MBadPixelsCalc.h"       // MBadPixelsCalc
+#include "MBadPixelsTreat.h"      // MBadPixelsTreat
+#include "MFillH.h"               // MFillH
+#include "MExtractSignal.h"       // MExtractsignal
+#include "MMcCalibrationUpdate.h" // MMcCalibrationUpdate
+#include "MCalibrateData.h"       // MCalibrateData
+#include "MMcTriggerLvl2Calc.h"   // MMcTriggerLvl2Calc
+
+//
+// Container
+//
+#include "MHillas.h"               // MHillas::Print(const MGeomCam&)
+#include "MHillasExt.h"            // MHillasExt::Print(const MGeomCam&)
+#include "MHillasSrc.h"            // MHillasSrc::Print(const MGeomCam&)
+#include "MImagePar.h"             // MImagePar::Print(const MGeomCam&)
+#include "MNewImagePar.h"          // MNewImagePar::Print(const MGeomCam&)
+#include "MHEvent.h"               // MHEvent
+#include "MHCamera.h"              // MHCamera
+#include "MRawEvtData.h"           // MRawEvtData
+#include "MArrivalTimeCam.h"       // MArrivalTimeCam
+#include "MBadPixelsCam.h"         // MBadPixelsCam
+#include "MPedPhotCam.h"           // MPedPhotCam
+#include "MCalibrationChargeCam.h" // MCalibrationChargeCam
+#include "MMcTriggerLvl2.h"        // MMcTriggerLvl2
+
+using namespace std;
+
+ClassImp(MEventDisplay);
+
+// --------------------------------------------------------------------------
+//
+//  Constructor.
+//
+MEventDisplay::MEventDisplay(const char *fname) : MStatusDisplay(), fEvtLoop(0)
+{
+    //
+    // Setup Task list for hillas calculation
+    //
+    SetupTaskList("Events", fname);
+
+    //
+    // Add MEventDisplay GUI elements to the display
+    //
+    AddUserFrame(fname);
+
+    //
+    // Show new part of the window, resize to correct aspect ratio
+    //
+    // FIXME: This should be done by MStatusDisplay automatically
+    Resize(GetWidth(), GetHeight() + fUserFrame->GetDefaultHeight());
+    SetWindowName("Event Display");
+    MapSubwindows();
+
+    //
+    // Readin first event and display it
+    //
+    if (fEvtLoop)
+        ReadFirstEvent();
+
+    SetNoContextMenu(kFALSE);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor: PostProcess eventloop, delete eventloop with all containers
+//
+MEventDisplay::~MEventDisplay()
+{
+    if (fEvtLoop)
+    {
+        fEvtLoop->PostProcess();
+        delete fEvtLoop;
+    }
+}
+
+Int_t MEventDisplay::GetFileType(const char *tree, const char *fname) const
+{
+    TFile f(fname, "READ");
+    TTree *t = (TTree*)f.Get(tree);
+    if (!t)
+        return -1;
+
+    if (t->FindBranch("MSignalCam."))
+        return 1;
+
+    if (t->FindBranch("MRawEvtData."))
+        return 2;
+
+    return -2;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Setup Task and parameter list for hillas calculation,
+//  preprocess tasks and read in first event (process)
+//
+void MEventDisplay::SetupTaskList(const char *tname, const char *fname)
+{
+//    MCalibrationChargeCam *ccam=0;
+//    MPedPhotCam           *pcam=0;
+
+    MBadPixelsCam *badpix = new MBadPixelsCam;
+
+    const Int_t type = GetFileType(tname, fname);
+    switch (type)
+    {
+    case  1: gLog << all << "Calibrated Data File detected..." << endl; break;
+    case  2: gLog << all << "Raw Data File detected..." << endl; break;
+    case -2: gLog << err << "File type unknown... abort." << endl; return;
+    case -1: gLog << err << "Tree " << tname << " not found... abort." << endl; return;
+    }
+
+    //
+    // Setup an empty job, with a reader task only.
+    // All tasks and parameter containers are deleted automatically
+    // (via SetOwner())
+    //
+    MTaskList *tlist = new MTaskList;
+    tlist->SetOwner();
+
+    MReadMarsFile *read = new MReadMarsFile(tname, fname);
+    read->DisableAutoScheme();
+    tlist->AddToList(read);
+
+    MGeomApply *apl = new MGeomApply;
+    tlist->AddToList(apl);
+
+    MParList *plist = new MParList;
+    plist->SetOwner();
+    plist->AddToList(tlist);
+    plist->AddToList(badpix);
+
+    //MArrivalTime *atime = new MArrivalTime;
+    //plist->AddToList(atime);
+
+    MHEvent *evt01 = new MHEvent(MHEvent::kEvtSignalRaw);
+    MHEvent *evt02 = new MHEvent(MHEvent::kEvtSignalRaw);
+    MHEvent *evt03 = new MHEvent(type==1?MHEvent::kEvtPedPhot:MHEvent::kEvtPedestal);
+    MHEvent *evt04 = new MHEvent(type==1?MHEvent::kEvtPedPhotRMS:MHEvent::kEvtPedestalRMS);
+    MHEvent *evt06a= new MHEvent(MHEvent::kEvtCleaningData);
+    MHEvent *evt06b= new MHEvent(MHEvent::kEvtCleaningLevels);
+    MHEvent *evt07 = new MHEvent(MHEvent::kEvtIdxMax);
+    MHEvent *evt08 = new MHEvent(MHEvent::kEvtArrTime);
+    MHEvent *evt09 = new MHEvent(MHEvent::kEvtTrigPix);
+    MHEvent *evt10 = new MHEvent(MHEvent::kEvtIslandIndex);
+
+    evt01->SetName("Signal");
+    evt02->SetName("Cleaned");
+    evt03->SetName("Pedestal");
+    evt04->SetName("PedRMS");
+    evt06a->SetName("CleanData");
+    evt06b->SetName("CleanLevels");
+    evt07->SetName("Max Slice Idx");
+    evt08->SetName("Arrival Time");
+    evt09->SetName("Trigger");
+    evt10->SetName("Islands");
+
+    // This makes sure, that the containers are deleted...
+    plist->AddToList(evt01);
+    plist->AddToList(evt02);
+    plist->AddToList(evt03);
+    plist->AddToList(evt04);
+    plist->AddToList(evt06a);
+    plist->AddToList(evt06b);
+    plist->AddToList(evt07);
+    plist->AddToList(evt08);
+    plist->AddToList(evt09);
+    plist->AddToList(evt10);
+
+    MExtractTimeAndChargeDigitalFilter *digf = new MExtractTimeAndChargeDigitalFilter;
+    digf->ReadWeightsFile("msignal/MC_weights.dat");
+
+    MTaskEnv *taskenv1=new MTaskEnv("ExtractSignal");
+    taskenv1->SetDefault(digf);
+    taskenv1->SetOwner();
+
+    MSignalCalc        *nanal  = new MSignalCalc;
+    MFillH             *fill01 = new MFillH(evt01, "MSignalCam", "MFillH01");
+    MImgCleanStd       *clean  = new MImgCleanStd;
+    MFillH             *fill02 = new MFillH(evt02, "MSignalCam", "MFillH02");
+    MFillH             *fill03 = new MFillH(evt03, type==1?"MPedPhotFundamental":"MPedestalCam",       "MFillH03");
+    MFillH             *fill04 = new MFillH(evt04, type==1?"MPedPhotFromExtractorRndm":"MPedestalCam", "MFillH04");
+    MFillH             *fill06a= new MFillH(evt06a, "MCameraData", "MFillH06a");
+    MFillH             *fill06b= new MFillH(evt06b, "MCameraData", "MFillH06b");
+    MHillasCalc        *hcalc  = new MHillasCalc;
+    MMcTriggerLvl2Calc *trcal  = new MMcTriggerLvl2Calc;
+    MFillH             *fill09 = new MFillH(evt09, "MMcTriggerLvl2", "MFillH09");
+    MFillH             *fill10 = new MFillH(evt10, "MSignalCam",    "MFillH10");
+
+    MBadPixelsCalc     *bcalc  = new MBadPixelsCalc;
+    MBadPixelsTreat    *btreat = new MBadPixelsTreat;
+    btreat->SetProcessTimes(kFALSE);
+    if (type==1)
+    {
+        bcalc->SetNamePedPhotCam("MPedPhotFromExtractor");
+        btreat->AddNamePedPhotCam("MPedPhotFromExtractorRndm");
+        clean->SetNamePedPhotCam("MPedPhotFromExtractorRndm");
+    }
+
+    // If no pedestal or no calibration file is availble
+    if (type==2)
+    {
+        MFilter *f1=new MFDataMember("MRawRunHeader.fRunType", '>', 255.5);
+        f1->SetName("MFMonteCarlo");
+
+        MMcPedestalCopy   *pcopy = new MMcPedestalCopy;
+        MMcPedestalNSBAdd *pdnsb = new MMcPedestalNSBAdd;
+
+        MMcCalibrationUpdate* mcupd = new MMcCalibrationUpdate;
+        mcupd->SetOuterPixelsGainScaling(kFALSE);
+
+        MCalibrateData* calib = new MCalibrateData;
+        calib->SetCalibrationMode(MCalibrateData::kFlatCharge);
+        calib->SetPedestalFlag(MCalibrateData::kEvent);
+
+        //MCalibrationRelTimeCalc *tcalc = new MCalibrationRelTimeCalc;
+
+        // MC
+        mcupd->SetFilter(f1);
+        trcal->SetFilter(f1);
+
+        // TaskList
+        tlist->AddToList(f1);
+        tlist->AddToList(pcopy);
+        tlist->AddToList(pdnsb);
+
+        tlist->AddToList(nanal);    // Calculated MPedPhotCam
+        tlist->AddToList(taskenv1); // Calculates MExtractedSignalCam, MArrivalTimeCam
+        tlist->AddToList(mcupd);
+        tlist->AddToList(calib);    // MExtractedSignalCam --> MSignalCam
+
+        tlist->AddToList(bcalc);    // Produce MBadPixelsCam
+        tlist->AddToList(btreat);   // Treat MBadPixelsCam
+    }
+
+    tlist->AddToList(fill01);
+    tlist->AddToList(clean);
+    tlist->AddToList(fill02);
+    tlist->AddToList(fill03);
+    tlist->AddToList(fill04);
+    tlist->AddToList(fill06a);
+    tlist->AddToList(fill06b);
+    tlist->AddToList(fill10);
+    if (type==2)
+    {
+        MFillH *fill07 = new MFillH(evt07, "MRawEvtData",     "MFillH7");
+        MFillH *fill08 = new MFillH(evt08, "MArrivalTimeCam", "MFillH8");
+        tlist->AddToList(fill07);
+        tlist->AddToList(fill08);
+
+	tlist->AddToList(trcal);
+	tlist->AddToList(fill09);
+    }
+    if (type==1)
+    {
+        MFillH *fill08 = new MFillH(evt08, "MSignalCam", "MFillH8");
+        tlist->AddToList(fill08);
+    }
+    tlist->AddToList(hcalc);
+
+    //
+    // Now distribute Display to all tasks
+    //
+    fEvtLoop = new MEvtLoop(Form("Mars %s", gSystem->BaseName(fname)));
+    fEvtLoop->SetOwner();
+    fEvtLoop->SetParList(plist);
+    fEvtLoop->SetDisplay(this);
+    fEvtLoop->ReadEnv("mars.rc");
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the top part of the frame: This is filename and treename display
+//
+void MEventDisplay::AddTopFramePart1(TGCompositeFrame *frame,
+                                    const char *filename,
+                                    const char *treename)
+{
+    //
+    //  --- the top1 part of the window ---
+    //
+    TGHorizontalFrame *top1 = new TGHorizontalFrame(frame, 1, 1);
+    fList->Add(top1);
+
+    //
+    // create gui elements
+    //
+    TGLabel *file = new TGLabel(top1, new TGString(Form("%s#%s", filename, treename)));
+    fList->Add(file);
+
+    //
+    // layout and add gui elements in/to frame
+    //
+    TGLayoutHints *laystd = new TGLayoutHints(kLHintsCenterX, 5, 5);
+    fList->Add(laystd);
+
+    top1->AddFrame(file,  laystd);
+
+    //
+    //  --- the top1 part of the window ---
+    //
+    TGHorizontalFrame *top2 = new TGHorizontalFrame(frame, 1, 1);
+    fList->Add(top2);
+
+    //
+    // layout and add frames
+    //
+    TGLayoutHints *laytop1 = new TGLayoutHints(kLHintsCenterX, 5, 5, 5);
+    fList->Add(laytop1);
+    frame->AddFrame(top1, laytop1);
+    frame->AddFrame(top2, laytop1);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the second part of the top frame: This are the event number controls
+//
+void MEventDisplay::AddTopFramePart2(TGCompositeFrame *frame)
+{
+    //
+    // --- the top2 part of the window ---
+    //
+    TGHorizontalFrame *top2 = new TGHorizontalFrame(frame, 1, 1);
+    fList->Add(top2);
+
+    //
+    // Create the gui elements
+    //
+    TGTextButton *prevevt = new TGTextButton(top2, " << ", kEvtPrev);
+    prevevt->Associate(this);
+
+    TGLabel *evtnr = new TGLabel(top2, new TGString("Event:"));
+
+    TGTextEntry *entry=new TGTextEntry(top2, new TGTextBuffer(100), kEvtNumber);
+    entry->Resize(60, entry->GetDefaultHeight());
+    entry->Associate(this);
+
+    fNumOfEvts = new TGLabel(top2, "of           .");
+
+    TGTextButton *nextevt = new TGTextButton (top2, " >> ", kEvtNext);
+    nextevt->Associate(this);
+
+    //
+    // Add gui elements to 'atotodel'
+    //
+    fList->Add(prevevt);
+    fList->Add(evtnr);
+    fList->Add(entry);
+    fList->Add(fNumOfEvts);
+    fList->Add(nextevt);
+
+    //
+    // add the gui elements to the frame
+    //
+    TGLayoutHints *laystd = new TGLayoutHints(kLHintsLeft|kLHintsCenterY, 5, 5);
+    fList->Add(laystd);
+
+    top2->AddFrame(prevevt,    laystd);
+    top2->AddFrame(evtnr,      laystd);
+    top2->AddFrame(entry,      laystd);
+    top2->AddFrame(fNumOfEvts, laystd);
+    top2->AddFrame(nextevt,    laystd);
+
+    TGLayoutHints *laystd2 = new TGLayoutHints(kLHintsCenterX, 5, 5, 5, 5);
+    fList->Add(laystd2);
+    frame->AddFrame(top2, laystd2);
+
+    //
+    // Add trailing line...
+    //
+    TGHorizontal3DLine *line = new TGHorizontal3DLine(frame);
+    TGLayoutHints *layline = new TGLayoutHints(kLHintsExpandX);
+    fList->Add(line);
+    fList->Add(layline);
+    frame->AddFrame(line, layline);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the user frame part of the display
+//
+void MEventDisplay::AddUserFrame(const char* filename)
+{
+    fUserFrame->ChangeOptions(kHorizontalFrame);
+
+    TGCompositeFrame *vf1 = new TGVerticalFrame(fUserFrame, 1, 1);
+    TGCompositeFrame *vf2 = new TGVerticalFrame(fUserFrame, 1, 1);
+
+    AddTopFramePart1(vf1, filename, "Events");
+    AddTopFramePart2(vf1);
+
+    // create root embedded canvas and add it to the tab
+    TRootEmbeddedCanvas *ec = new TRootEmbeddedCanvas("Slices", vf2, vf1->GetDefaultHeight()*3/2, vf1->GetDefaultHeight(), 0);
+    vf2->AddFrame(ec);
+    fList->Add(ec);
+
+    // set background and border mode of the canvas
+    fCanvas = ec->GetCanvas();
+    fCanvas->SetBorderMode(0);
+    gROOT->GetListOfCanvases()->Add(fCanvas);
+    //fCanvas->SetBorderSize(1);
+    //fCanvas->SetBit(kNoContextMenu);
+    //fCanvas->SetFillColor(16);
+
+    TGLayoutHints *lay = new TGLayoutHints(kLHintsExpandX);
+    fUserFrame->AddFrame(vf1, lay);
+    fUserFrame->AddFrame(vf2);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Checks if the event number is valid, and if so reads the new event
+//  and updates the display
+//
+void MEventDisplay::ReadinEvent(Int_t dir)
+{
+    MParList    *plist = (MParList*)   fEvtLoop->GetParList();
+    MTaskList   *tlist = (MTaskList*)  fEvtLoop->GetTaskList();
+    MGeomCam    *geom  = (MGeomCam*)   plist->FindObject("MGeomCam");
+    MRawEvtData *raw   = (MRawEvtData*)plist->FindObject("MRawEvtData");
+
+    //
+    // Read first event.
+    //
+    MReadTree *reader = (MReadTree*)fEvtLoop->FindTask("MRead");
+
+    const Int_t num = reader->GetNumEntry();
+
+    do
+    {
+        if (dir<0 && !reader->DecEventNum())
+        {
+            reader->SetEventNum(num);
+            return;
+        }
+        if (dir>0 && !reader->IncEventNum())
+        {
+            reader->SetEventNum(num);
+            return;
+        }
+
+        const Int_t rc = tlist->Process();
+        if (rc==kFALSE || rc==kERROR)
+            return;
+
+        reader->DecEventNum();
+
+    } while (raw && raw->GetNumPixels()<1 && dir!=0);
+
+    //
+    // Cleare the 'FADC canvas'
+    //
+    fCanvas->Clear();
+    fCanvas->Modified();
+    fCanvas->Update();
+
+    //
+    // Print parameters
+    //
+    ((MHillas*)     plist->FindObject("MHillas"))->Print(*geom);
+    ((MHillasExt*)  plist->FindObject("MHillasExt"))->Print(*geom);
+    ((MHillasSrc*)  plist->FindObject("MHillasSrc"))->Print(*geom);
+    plist->FindObject("MImagePar")->Print();
+    ((MNewImagePar*)plist->FindObject("MNewImagePar"))->Print(*geom);
+
+    //
+    // UpdateDisplay
+    //
+    gStyle->SetOptStat(1101);
+    Update();
+
+    TGTextEntry *entry = (TGTextEntry*)fList->FindWidget(kEvtNumber);
+    entry->SetText(Form("%d", reader->GetNumEntry()+1));
+}
+
+// --------------------------------------------------------------------------
+//
+//  Read first event to get display booted
+//
+void MEventDisplay::ReadFirstEvent()
+{
+    const Int_t rc = fEvtLoop->PreProcess();
+    if (rc==kFALSE || rc==kERROR)
+        return;
+
+    UnLock();
+
+    //
+    // Get parlist
+    //
+    MParList *plist = (MParList*)fEvtLoop->GetParList();
+
+    //
+    // Add Geometry tab
+    //
+    AddGeometryTabs();
+
+    //
+    // Now read event...
+    //
+    ReadinEvent();
+
+    MReadTree *reader = (MReadTree*)fEvtLoop->FindTask("MRead");
+    TGString *txt = new TGString(Form("of %d", reader->GetEntries()));
+    fNumOfEvts->SetText(txt);
+
+    //
+    // Draw ellipse on top of all pads
+    //
+    TObject *hillas1 = plist->FindObject("MHillas");
+    TObject *hillas2 = plist->FindObject("MHillasSrc");
+    for (int i=1; i<7;i++)
+    {
+        TCanvas *c = GetCanvas(i);
+        c->GetPad(1)->cd(1);
+        hillas1->Draw();
+        hillas2->Draw();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Adds the geometry tab 
+//
+void MEventDisplay::AddGeometryTabs()
+{
+    MGeomCam *geom = (MGeomCam*)fEvtLoop->GetParList()->FindObject("MGeomCam");
+    if (!geom)
+        return;
+
+    TCanvas &c1=AddTab("Geometry");
+
+    MHCamera *cam = new MHCamera(*geom);
+    cam->SetBit(TH1::kNoStats|MHCamera::kNoLegend|kCanDelete);
+    cam->Draw("pixelindex");
+
+    c1.Modified();
+    c1.Update();
+
+    TCanvas &c2=AddTab("Sectors");
+
+    cam = new MHCamera(*geom);
+    cam->SetBit(TH1::kNoStats|MHCamera::kNoLegend|kCanDelete);
+    cam->Draw("sectorindex");
+
+    c2.Modified();
+    c2.Update();
+}
+
+// --------------------------------------------------------------------------
+//
+//  ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+//
+// Processes information from all GUI items.
+// Selecting an item usually generates an event with 4 parameters.
+// The first two are packed into msg (first and second bytes).
+// The other two are parm1 and parm2.
+//
+Bool_t MEventDisplay::ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2)
+{
+    switch (GET_MSG(msg))
+    {
+    case kC_TEXTENTRY:
+        switch(GET_SUBMSG(msg))
+        {
+        case kTE_ENTER:
+            switch(GET_SUBMSG(msg))
+            {
+            case kTE_ENTER:
+                {
+                    TGTextEntry *entry = (TGTextEntry*)fList->FindWidget(kEvtNumber);
+                    MReadTree *reader  = (MReadTree*)fEvtLoop->FindTask("MRead");
+                    if (reader->SetEventNum(atoi(entry->GetText())-1))
+                        ReadinEvent();
+                }
+                return kTRUE;
+            }
+            return kTRUE;
+        }
+        break;
+
+    case kC_COMMAND:
+        switch (GET_SUBMSG(msg))
+        {
+        case kCM_TAB:
+            {
+                //
+                // Set name for 'FADC canvas'. The name is the anchor for MHCamera.
+                // and clear the canvas
+                TCanvas *c = GetCanvas(mp1);
+                if (!c)
+                    break;
+                MHEvent *o = (MHEvent*)fEvtLoop->GetParList()->FindObject(c->GetName());
+                if (!o)
+                    break;
+                fCanvas->SetName(Form("%p;%p;PixelContent", o->GetHist(), c->GetPad(1)->GetPad(1)));
+            }
+            break;
+
+        case kCM_BUTTON:
+            switch (mp1)
+            {
+            case kEvtPrev:
+                ReadinEvent(-1);
+                return kTRUE;
+
+            case kEvtNext:
+                ReadinEvent(+1);
+                return kTRUE;
+            }
+            return kTRUE;
+        }
+        break;
+    }
+
+    return MStatusDisplay::ProcessMessage(msg, mp1, mp2);
+}
Index: /tags/Mars-V0.9/mmain/MEventDisplay.h
===================================================================
--- /tags/Mars-V0.9/mmain/MEventDisplay.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MEventDisplay.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MEventDisplay
+#define MARS_MEventDisplay
+
+#ifndef MARS_MStatusDisplay
+#include "MStatusDisplay.h"
+#endif
+
+class TGLabel;
+class TGTextEntry;
+class MEvtLoop;
+
+class MParList;
+class MTaskList;
+class MReadTree;
+
+class MEventDisplay : public MStatusDisplay
+{
+private:
+    enum
+    {
+        kEvtPrev = MStatusDisplay::kSearch + 1,
+        kEvtNext,
+        kEvtNumber
+    };
+
+    TGCompositeFrame *fTab1;
+    TGCompositeFrame *fTab2;
+
+    TGLabel  *fNumOfEvts;
+    TCanvas  *fCanvas;
+    MEvtLoop *fEvtLoop;
+
+    void AddTopFramePart1(TGCompositeFrame *frame,
+                          const char *filename, const char *treename);
+    void AddTopFramePart2(TGCompositeFrame *frame);
+    void AddGeometryTabs();
+    void AddUserFrame(const char *filename);
+
+    void UpdateDisplay();
+    void SetupTaskList(const char *tname, const char *fname);
+
+    void ReadFirstEvent();
+    void ReadinEvent(Int_t dir=0);
+
+    Int_t GetFileType(const char *tree, const char *fname) const;
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+public:
+    MEventDisplay(const char *fname);
+    ~MEventDisplay();
+
+    ClassDef(MEventDisplay, 0) // Display for camera images (cerenkov events)
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MGDisplayAdc.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MGDisplayAdc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MGDisplayAdc.cc	(revision 9772)
@@ -0,0 +1,463 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer, 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+#include "MGDisplayAdc.h"
+
+#include <stdlib.h>              // mkstemp
+#include <iostream>              // cout for debugging
+
+#include <TSystem.h>             // gSystem
+#include <TCanvas.h>             // TCanvas.h
+#include <TGSlider.h>            // TGVSlider
+#include <TGButton.h>            // TGTextButton
+#include <TGMsgBox.h>            // TGMsgBox
+#include <TGListBox.h>           // TGListBox
+#include <TGButtonGroup.h>       // TGVButtonGroup
+#include <TRootEmbeddedCanvas.h> // TRootEmbeddedCanvas
+
+#include "MHFadcCam.h"
+
+using namespace std;
+
+ClassImp(MGDisplayAdc);
+
+enum ComIdentDisplayAdc
+{
+    M_BUTTON_SAVE,
+    M_BUTTON_PRINT,
+    M_BUTTON_PRINTALL,
+    M_BUTTON_CLOSE,
+
+    M_BUTTON_PREV,
+    M_BUTTON_NEXT,
+
+    M_LIST_HISTO,
+    M_RADIO_HI,
+    M_RADIO_LO,
+    M_RADIO_LH,
+    M_BUTTON_RESET,
+    M_VSId1
+};
+
+void MGDisplayAdc::AddFrameTop(TGHorizontalFrame *frame)
+{
+    //
+    // left part of top frame
+    //
+    TGVerticalFrame *left = new TGVerticalFrame(frame, 80, 300, kFitWidth);
+    fList->Add(left);
+
+    fHistoList = new TGListBox (left, M_LIST_HISTO);
+    fHistoList->Associate(this);
+    fHistoList->Resize(100, 405);
+
+    fList->Add(fHistoList);
+
+    TGLayoutHints *laylist = new TGLayoutHints(kLHintsNormal, 10, 10, 10, 10);
+    fList->Add(laylist);
+
+    left->AddFrame(fHistoList, laylist);
+
+    //
+    //    middle part of top frame
+    //
+    TGVerticalFrame *mid = new TGVerticalFrame(frame, 80, 20, kFitWidth);
+    fList->Add(mid);
+
+    // ---
+
+    TGTextButton *prev = new TGTextButton(mid, "Prev Histo", M_BUTTON_PREV);
+    TGTextButton *next = new TGTextButton(mid, "Next Histo", M_BUTTON_NEXT);
+    prev->Associate(this);
+    next->Associate(this);
+
+    fList->Add(prev);
+    fList->Add(next);
+
+    // ---
+
+    fSlider = new TGVSlider(mid, 250, kSlider1|kScaleBoth, M_VSId1);
+    fSlider->Associate(this);
+
+    fList->Add(fSlider);
+
+    // ---
+
+    TGVButtonGroup *group = new TGVButtonGroup(mid);
+    fList->Add(group);
+
+    TGRadioButton *radio1 = new TGRadioButton(group, "&High Gain",     M_RADIO_HI);
+    TGRadioButton *radio2 = new TGRadioButton(group, "&Low Gain",      M_RADIO_LO);
+    TGRadioButton *radio3 = new TGRadioButton(group, "H&igh/Low Gain", M_RADIO_LH);
+
+    /* FIXME:
+
+    ~TGRadioButton calls TGRadioButton::TGFrame::GetMainFrame
+    which calles fParent->GetFrame()
+
+    fList->Add(radio1);
+    fList->Add(radio2);
+    fList->Add(radio3);
+    */
+
+    radio3->SetState(kButtonDown);
+
+    radio1->Associate(this);
+    radio2->Associate(this);
+    radio3->Associate(this);
+
+    // ---
+
+    TGLayoutHints *laybut1 = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10,  0, 10);
+    TGLayoutHints *laybut2 = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 10,  5);
+    TGLayoutHints *layslid = new TGLayoutHints(kLHintsCenterX|kLHintsTop);
+
+    fList->Add(laybut1);
+    fList->Add(laybut2);
+    fList->Add(layslid);
+
+    mid->AddFrame(prev,    laybut1);
+    mid->AddFrame(fSlider, layslid);
+    mid->AddFrame(next,    laybut2);
+    mid->AddFrame(group,   laybut2);
+
+    //
+    //    right part of top frame
+    //
+    TGVerticalFrame *right = new TGVerticalFrame(frame, 100, 100, kFitWidth);
+    fList->Add(right);
+
+    TRootEmbeddedCanvas *canvas = new TRootEmbeddedCanvas("fECanv", right, 100, 100);
+    fList->Add(canvas);
+
+    TGLayoutHints *laycanv = new TGLayoutHints(kLHintsCenterX|kLHintsCenterY|kLHintsExpandX|kLHintsExpandY, 10, 10, 10, 10);
+    fList->Add(laycanv);
+
+    right->AddFrame(canvas, laycanv);
+
+
+    TGTextButton *reset = new TGTextButton(right, "Reset histo", M_BUTTON_RESET);
+    reset->Associate(this);
+    fList->Add(reset);
+
+    TGLayoutHints *layreset = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 0, 10);
+    fList->Add(layreset);
+
+    right->AddFrame(reset, layreset);
+
+    // ---
+
+    fCanvas = canvas->GetCanvas();
+
+    //
+    // layout the three subframes
+    //
+    TGLayoutHints *layframe1 = new TGLayoutHints(kLHintsTop, 10, 10, 10, 10);
+    TGLayoutHints *layframe2 = new TGLayoutHints(kLHintsCenterX|kLHintsCenterY|kLHintsExpandX|kLHintsExpandY, 10, 10, 10, 10);
+    fList->Add(layframe1);
+    fList->Add(layframe2);
+
+    frame->AddFrame(left,  layframe1);
+    frame->AddFrame(mid,   layframe1);
+    frame->AddFrame(right, layframe2);
+}
+
+void MGDisplayAdc::AddFrameLow(TGHorizontalFrame *frame)
+{
+    //
+    //   the low frame for the control buttons
+    //
+    TGTextButton *but1 = new TGTextButton(frame, "Save",     M_BUTTON_SAVE);
+    TGTextButton *but2 = new TGTextButton(frame, "Print",    M_BUTTON_PRINT);
+    TGTextButton *but3 = new TGTextButton(frame, "PrintAll", M_BUTTON_PRINTALL);
+    TGTextButton *but4 = new TGTextButton(frame, "Close",    M_BUTTON_CLOSE);
+
+    but1->Associate(this);
+    but2->Associate(this);
+    but3->Associate(this);
+    but4->Associate(this);
+
+    fList->Add(but1);
+    fList->Add(but2);
+    fList->Add(but3);
+    fList->Add(but4);
+
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsNormal, 10, 10, 5, 5);
+    fList->Add(laybut);
+
+    frame->AddFrame(but1, laybut);
+    frame->AddFrame(but2, laybut);
+    frame->AddFrame(but3, laybut);
+    frame->AddFrame(but4, laybut);
+}
+
+MGDisplayAdc::MGDisplayAdc(MHFadcCam *histos,
+                           const TGWindow *p, const TGWindow *main,
+                           UInt_t w, UInt_t h,
+                           UInt_t options)
+: TGTransientFrame(p?p:gClient->GetRoot(), main?main:gClient->GetRoot(), w, h, options),
+  fHistoType(M_RADIO_LH)
+{
+    fHists = (MHFadcCam*)histos->Clone();
+
+    fList = new TList;
+    fList->SetOwner();
+
+    //
+    // Create the to frames
+    //
+    TGHorizontalFrame *frametop = new TGHorizontalFrame(this, 60, 20, kFitWidth);
+    TGHorizontalFrame *framelow = new TGHorizontalFrame(this, 60, 20, kFixedWidth);
+
+    //
+    // Add frames to 'autodel'
+    //
+    fList->Add(frametop);
+    fList->Add(framelow);
+
+    //
+    // Add the gui elements to the two frames
+    //
+    AddFrameTop(frametop);
+    AddFrameLow(framelow);
+
+    //
+    // layout the two frames in this frame
+    //
+    TGLayoutHints *laytop = new TGLayoutHints(kLHintsTop|kLHintsExpandX,    10, 10, 10, 10);
+    TGLayoutHints *laylow = new TGLayoutHints(kLHintsBottom|kLHintsExpandX, 10, 10, 10, 10);
+
+    AddFrame(frametop, laytop);
+    AddFrame(framelow, laylow);
+
+    //
+    // Setup interieur
+    //
+    BuildHistoList();
+
+    //
+    // Here the initial display is set to entry with id 1
+    //
+    fHistoList->Select(1);
+    UpdateHist();
+
+    //
+    // Setup frame
+    //
+    MapSubwindows();
+
+    Layout();
+
+    SetWindowName("ADC Spectra");
+    SetIconName("ADC Spectra");
+
+    MapWindow();
+    SetWMSizeHints(950, 500, 1000, 1000, 1, 1);
+}  
+
+MGDisplayAdc::~MGDisplayAdc()
+{ 
+    delete fList;
+    delete fHists;
+}  
+
+void MGDisplayAdc::CloseWindow()
+{
+    //
+    // The close message is generated by the window manager when its close
+    // window menu item is selected.
+    //
+    delete this;
+}
+
+Bool_t MGDisplayAdc::BuildHistoList()
+{
+    //
+    //   looks in the container of the AdcSpectra and reads in the
+    //   Histogramms in there.
+    //
+    //   In the class MHFadcCam are in fact two lists. One for the high and
+    //   one for the low gain. Here we will use only the high gain list!!!
+    //   With some special options (settings in the gui) we will also be able
+    //   to plot the low gain
+    //
+    const Int_t nhi = fHists->GetEntries();
+
+    Int_t n=1;
+    for (Int_t i=0; i<nhi; i++)
+        if (fHists->HasHi(i))
+            fHistoList->AddEntry(fHists->GetHistHi(i)->GetName(), n++);
+
+    fSlider->SetRange(1, n);
+
+    fHistoList->MapSubwindows();
+    fHistoList->Layout();
+
+    return kTRUE;
+} 
+
+void MGDisplayAdc::UpdateHist()
+{
+    const Int_t selected = fHistoList->GetSelected();
+
+    if (selected<0)
+    {
+        cout << "MGDisplayAdc: No histograms found in list. " << endl;
+        return;
+    }
+
+    fHistoList->Select(selected); // ???
+
+    fCanvas->Clear();
+
+    const Int_t idx = fHistoList->GetSelectedEntry()->EntryId()-1; //selected-1;
+
+    if (!fHists->HasHi(idx))
+        return;
+
+    const Int_t type = fHists->HasLo(idx) ? fHistoType : M_RADIO_HI;
+
+    switch (type)
+    {
+    case M_RADIO_HI:
+    case M_RADIO_LO:
+        fCanvas->Divide(1, 1);
+
+        fCanvas->cd();
+        if (type==M_RADIO_HI)
+            fHists->DrawHi(idx);
+        else
+            fHists->DrawLo(idx);
+        break;
+
+    case M_RADIO_LH:
+        fCanvas->Divide(1, 2);
+
+        fCanvas->cd(1);
+        fHists->DrawHi(idx);
+
+        fCanvas->cd(2);
+        fHists->DrawLo(idx);
+        break;
+    }
+
+    fHistoList->SetTopEntry(selected);
+
+    fCanvas->Modified();
+    fCanvas->Update();
+
+    fSlider->SetPosition(selected);
+}
+
+Bool_t MGDisplayAdc::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+{     
+    //
+    // Process events generated by the buttons in the frame.
+    //
+    switch (GET_MSG(msg))
+    {
+    case kC_COMMAND:
+        switch (GET_SUBMSG(msg))
+        {
+        case kCM_BUTTON:
+            switch (parm1)
+            {
+            case M_BUTTON_SAVE:
+                fCanvas->SaveAs();
+                cout << "Sorry, no well implemented!" << endl;
+                return kTRUE;
+
+            case M_BUTTON_PRINT:
+                {
+                    char *txt = (char*)"canvasXXXXXX";
+                    mkstemp(txt);
+                    TString name = txt;
+                    name += ".ps";
+                    fCanvas->SaveAs(name);
+                    cout << "Calling 'lpr " << name << ".ps'" << endl;
+                    gSystem->Exec(TString("lpr ")+name+".ps");
+                    gSystem->Exec(TString("rm ")+name+".ps");
+                }
+                cout << "Sorry, not well implemented!" << endl;
+                return kTRUE;
+
+            case M_BUTTON_RESET:
+                cout << "Sorry, not yet implemented!" << endl;
+                return kTRUE;
+
+            case M_BUTTON_CLOSE:
+                CloseWindow();
+                return kTRUE;
+
+            case M_BUTTON_PREV:
+            case M_BUTTON_NEXT:
+                {
+                    const Int_t selected = fHistoList->GetSelected();
+
+                    if ((parm1==M_BUTTON_PREV && selected==1) ||
+                        (parm1==M_BUTTON_NEXT && selected==fHistoList->GetNumberOfEntries()))
+                        return kTRUE;
+
+                    fHistoList->Select(parm1==M_BUTTON_PREV ? selected-1 : selected+1);
+                    UpdateHist();
+                }
+                return kTRUE;
+            }
+            return kTRUE;
+
+        case kCM_RADIOBUTTON:
+            switch(parm1)
+            {
+            case M_RADIO_HI:
+            case M_RADIO_LO:
+            case M_RADIO_LH:
+                fHistoType = parm1;
+                UpdateHist();
+                return kTRUE;
+            }
+            return kTRUE;
+        }
+		
+    case kCM_LISTBOX:
+        if (GET_SUBMSG(msg) == M_LIST_HISTO)
+            UpdateHist();
+
+        return kTRUE;
+
+    case kC_VSLIDER:
+        if (GET_SUBMSG(msg)!=kSL_POS || parm1!=M_VSId1)
+            return kTRUE;
+
+        // Check for the slider movement and synchronise with TGListBox
+        if (parm2<1 || parm2>fHistoList->GetNumberOfEntries())
+            return kTRUE;
+
+        fHistoList->Select(parm2);
+        UpdateHist();
+        return kTRUE;
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mmain/MGDisplayAdc.h
===================================================================
--- /tags/Mars-V0.9/mmain/MGDisplayAdc.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MGDisplayAdc.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MGDisplayAdc
+#define MARS_MGDisplayAdc
+
+#ifndef ROOT_TFrame
+#include <TGFrame.h>    // TGTransientFrame
+#endif
+
+class TList;
+class TCanvas;
+
+class MHFadcCam;
+
+class TGVSlider;
+class TGListBox;
+class TGTextButton;
+class TGRadioButton;
+class TRootEmbeddedCanvas;
+
+class MGDisplayAdc : public TGTransientFrame
+{
+private:
+    MHFadcCam *fHists;		// Pointer to Container with the histograms
+
+    TList     *fList;
+    TCanvas   *fCanvas;
+    TGVSlider *fSlider;
+    TGListBox *fHistoList;
+
+    Int_t      fHistoType;
+
+    void AddFrameTop(TGHorizontalFrame *frame);
+    void AddFrameLow(TGHorizontalFrame *frame);
+
+    //
+    // Create a main frame with a number of different buttons.
+    //
+    void   UpdateHist();
+    Bool_t BuildHistoList();
+
+public:
+
+    MGDisplayAdc(MHFadcCam *fHists ,
+                 const TGWindow *p=NULL, const TGWindow *main=NULL,
+                 UInt_t w=800, UInt_t h=500,
+                 UInt_t options = kMainFrame|kVerticalFrame);
+    ~MGDisplayAdc();
+
+    void  CloseWindow();
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+    ClassDef(MGDisplayAdc, 0)
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MMars.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MMars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MMars.cc	(revision 9772)
@@ -0,0 +1,320 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+#include "MMars.h"
+
+#include <iostream>
+
+#include <TApplication.h>  // gROOT->GetApplication()->...
+
+#include <TGTab.h>         // TGTab
+#include <TGMenu.h>        // TGPopupMenu
+#include <TSystem.h>       // gSystem->Exec
+#include <TGMsgBox.h>      // TGMsgBox
+#include <TGButton.h>      // TGPictureButton
+#include <TG3DLine.h>      // TGHorizontal3DLine
+
+#include "MGList.h"
+#include "MAnalysis.h"
+#include "MDataCheck.h"
+#include "MMonteCarlo.h"
+#include "MCameraDisplay.h"
+
+ClassImp(MMars);
+
+using namespace std;
+
+enum {
+    kFileExit,
+    kFileAbout,
+
+    kPicMagic,
+    kPicMars,
+
+    //kButEvtDisplay,
+    kButDataCheck,
+    kButAnalysis,
+    kButMonteCarlo,
+    kButCameraDisplay
+};
+
+void MMars::CreateMenuBar()
+{
+    TGLayoutHints *laymenubar  = new TGLayoutHints(kLHintsTop|kLHintsLeft|kLHintsExpandX, 2, 2, 2, 2);
+    TGLayoutHints *laymenuitem = new TGLayoutHints(kLHintsTop|kLHintsLeft, 0, 4, 0, 0);
+    TGLayoutHints *laylinesep  = new TGLayoutHints(kLHintsTop|kLHintsExpandX);
+
+    fList->Add(laymenubar);
+    fList->Add(laymenuitem);
+    fList->Add(laylinesep);
+
+    TGPopupMenu *filemenu = new TGPopupMenu(gClient->GetRoot());
+    filemenu->AddEntry("E&xit", kFileExit);
+    filemenu->Associate(this);
+
+    TGMenuBar *menubar = new TGMenuBar(this, 1, 1, kHorizontalFrame);
+    menubar->AddPopup("&File", filemenu, laymenuitem);
+    AddFrame(menubar, laymenubar);
+
+    TGHorizontal3DLine *linesep = new TGHorizontal3DLine(this);
+    AddFrame(linesep, laylinesep);
+
+    fList->Add(filemenu);
+    fList->Add(menubar);
+    fList->Add(linesep);
+}
+
+void MMars::CreateTopFrame(TGHorizontalFrame *top)
+{
+    const TGPicture *pic1 = fList->GetPicture("magiclogo.xpm");
+    if (pic1)
+    {
+        TGPictureButton *magic = new TGPictureButton(top, pic1, kPicMagic);
+        fList->Add(magic);
+        magic->Associate(this);
+        TGLayoutHints *lay1 = new TGLayoutHints(kLHintsLeft,  10, 10, 20, 10);
+        fList->Add(lay1);
+        top->AddFrame(magic, lay1);
+    }
+
+    const TGPicture *pic2 = fList->GetPicture("marslogo.xpm");
+    if (pic2)
+    {
+        TGPictureButton *mars  = new TGPictureButton(top, pic2, kPicMars);
+        fList->Add(mars);
+        mars->Associate(this);
+        TGLayoutHints *lay2 = new TGLayoutHints(kLHintsRight, 10, 10, 10, 10);
+        fList->Add(lay2);
+        top->AddFrame(mars,  lay2);
+    }
+}
+
+#include <TGLabel.h>
+
+void MMars::CreateTextButton(TGVerticalFrame *tab,
+                             const char *text, const char *descr,
+                             const UInt_t id) const
+{
+    //
+    // Create the button
+    //
+    TGHorizontalFrame *frame  = new TGHorizontalFrame(tab, 1, 1);
+    TGTextButton      *button = new TGTextButton(frame, text, id);
+    TGLabel           *label  = new TGLabel(frame, descr);
+    TGLayoutHints     *hints1 = new TGLayoutHints(kLHintsLeft|kLHintsCenterY|kLHintsExpandX, 5, 5, 2, 2);
+
+    //
+    // Add button for 'auto-delete'
+    //
+    fList->Add(hints1);
+    fList->Add(button);
+    fList->Add(label);
+    fList->Add(frame);
+
+    //
+    // Send button events (meesages) to this object (s. ProcessMessage)
+    //
+    button->Associate(this);
+
+    //
+    // Add button with corresponding layout to containing frame
+    //
+    tab->AddFrame(frame,    hints1);
+    frame->AddFrame(button, hints1);
+    frame->AddFrame(label,  hints1);
+}
+
+void MMars::CreateBottomFrame(TGHorizontalFrame *low)
+{
+    //
+    // Create Tab Container
+    //
+    TGLayoutHints *laytabs = new TGLayoutHints(kLHintsBottom|kLHintsExpandX|kLHintsExpandY, 5, 5, 5, 5);
+    fList->Add(laytabs);
+
+    TGTab *tabs = new TGTab(low, 1, 1);
+    fList->Add(tabs);
+    low->AddFrame(tabs, laytabs);
+
+    //
+    // Create Tab1
+    //
+    TGCompositeFrame *tf = tabs->AddTab("Control");
+
+    TGLayoutHints   *laytab = new TGLayoutHints(kLHintsCenterY|kLHintsExpandX);
+    TGVerticalFrame *tab    = new TGVerticalFrame(tf, 1, 1);
+    fList->Add(laytab);
+    fList->Add(tab);
+
+//    CreateTextButton(tab, "Event Display",  "Histograms: Pix per Event",
+//                     kButEvtDisplay);
+    CreateTextButton(tab, "Data Check",     "Histograms: Pix per Run",
+                     kButDataCheck);
+    CreateTextButton(tab, "Analysis",       "Calculate image parameters",
+                     kButAnalysis);
+    CreateTextButton(tab, "Monte Carlo",    "Calculate MC stuff",
+                     kButMonteCarlo);
+    CreateTextButton(tab, "Camera Display", "Display Cerenkov Photons",
+                     kButCameraDisplay);
+
+    tf->AddFrame(tab, laytab);
+}
+
+MMars::MMars()
+: TGMainFrame(gClient->GetRoot(), 400, 400, kVerticalFrame)
+{
+    //
+    // Create the deletion list
+    //
+    fList = new MGList;
+    fList->SetOwner();
+
+    //
+    // Create the MenuBar
+    //
+    CreateMenuBar();
+
+    //
+    // create and layout the frame/contents
+    //
+    TGHorizontalFrame *top = new TGHorizontalFrame(this, 1, 1);
+    TGHorizontalFrame *low = new TGHorizontalFrame(this, 1, 1);
+
+    TGHorizontal3DLine *linesep = new TGHorizontal3DLine(this);
+
+    fList->Add(top);
+    fList->Add(low);
+    fList->Add(linesep);
+
+    CreateTopFrame(top);
+    CreateBottomFrame(low);
+
+    TGLayoutHints *layout1 = new TGLayoutHints(kLHintsTop|kLHintsExpandX);
+    TGLayoutHints *layout2 = new TGLayoutHints(kLHintsTop|kLHintsExpandX|kLHintsExpandY);
+    fList->Add(layout1);
+    fList->Add(layout2);
+
+    AddFrame(top,     layout1);
+    AddFrame(linesep, layout1);
+    AddFrame(low,     layout2);
+
+    //
+    //   Map the window, set up the layout, etc.
+    //
+    Move(rand()%100, rand()%100);
+
+    Layout();
+
+    MapSubwindows();
+
+    SetWindowName("MARS Main Window");
+    SetIconName("MARS");
+
+    MapWindow();
+} 
+
+// ======================================================================
+
+MMars::~MMars()
+{
+    delete fList;
+}  
+// ======================================================================
+
+void MMars::CloseWindow()
+{
+   // Got close message for this MainFrame. Calls parent CloseWindow()
+   // (which destroys the window) and terminate the application.
+   // The close message is generated by the window manager when its close
+   // window menu item is selected.
+
+   TGMainFrame::CloseWindow();
+   gROOT->GetApplication()->Terminate(0);
+}
+
+void MMars::DisplWarning(const char *txt)
+{
+    Int_t retval;
+    new TGMsgBox(fClient->GetRoot(), this,
+                 "WARNING!", txt,
+                 kMBIconExclamation, 4, &retval);
+}
+
+Bool_t MMars::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
+{     
+    // Process events generated by the buttons in the frame.
+
+    switch (GET_MSG(msg))
+    {
+    case kC_COMMAND:
+        switch (GET_SUBMSG(msg))
+        {
+        case kCM_BUTTON:
+
+            switch (parm1)
+            {
+/*
+            case kButEvtDisplay:
+                new MEvtDisp();
+                return kTRUE;
+*/
+            case kButDataCheck:
+                new MDataCheck(/*this*/);
+                return kTRUE;
+
+            case kButAnalysis:
+                new MAnalysis(/*this*/);
+                return kTRUE;
+
+            case kButMonteCarlo:
+                new MMonteCarlo(/*this*/);
+                return kTRUE;
+
+            case kButCameraDisplay:
+                new MCameraDisplay(/*this*/);
+                return kTRUE;
+
+            case kPicMagic:
+                cout << "Trying to start 'netscape http://hegra1.mppmu.mpg.de/MAGICWeb/'..." << endl;
+                gSystem->Exec("netscape http://hegra1.mppmu.mpg.de/MAGICWeb/ &");
+                return kTRUE;
+
+            case kPicMars:
+                cout << "Trying to start 'netscape http://magic.astro.uni-wuerzburg.de/mars/'..." << endl;
+                gSystem->Exec("netscape http://magic.astro.uni-wuerzburg.de/mars/ &");
+                return kTRUE;
+            }
+
+	case kCM_MENU:
+            if (parm1!=kFileExit)
+                return kTRUE;
+
+            CloseWindow();
+            return kTRUE;
+	}
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mmain/MMars.h
===================================================================
--- /tags/Mars-V0.9/mmain/MMars.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MMars.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MMars
+#define MARS_MMars
+
+#ifndef MMARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TGFrame
+#include <TGFrame.h>
+#endif
+
+class MGList;
+class TGVerticalFrame;
+class TGLayoutHints;
+
+class MMars : public TGMainFrame
+{
+private:
+
+    MGList *fList;
+
+    void CreateTextButton(TGVerticalFrame *tab, const char *text,
+                          const char *descr, const UInt_t id) const;
+
+    void CreateMenuBar();
+    void CreateTopFrame(TGHorizontalFrame *top);
+    void CreateBottomFrame(TGHorizontalFrame *low);
+
+    void DisplWarning(const char *txt);
+
+public:
+    MMars();
+    ~MMars();
+
+    void CloseWindow();
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+    ClassDef(MMars, 0) // GUI: Mars - the main window
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MMonteCarlo.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MMonteCarlo.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MMonteCarlo.cc	(revision 9772)
@@ -0,0 +1,488 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+#include "MMonteCarlo.h"
+
+#include <stdlib.h>
+#include <iostream>
+
+#include <TGLabel.h>        // TGLabel
+#include <TGButton.h>       // TGTextButton
+#include <TGTextEntry.h>    // TGTextEntry
+#include <TGProgressBar.h>  // TGHProgressBar
+#include <TGButtonGroup.h>  // TGVButtonGroup
+
+#include "MGList.h"
+
+ClassImp(MMonteCarlo);
+
+using namespace std;
+
+enum {
+    kButCollArea  = 0x100,
+    kButTrigRate  = 0x101,
+    kButThreshold = 0x102
+};
+
+void MMonteCarlo::AddButtons()
+{
+    TGTextButton *carea = new TGTextButton(fTop2, "Collection Area", kButCollArea);
+    TGTextButton *trate = new TGTextButton(fTop2, "Trigger Rate",    kButTrigRate);
+    TGTextButton *thold = new TGTextButton(fTop2, "Threshold",       kButThreshold);
+
+    fList->Add(carea);
+    fList->Add(trate);
+    fList->Add(thold);
+
+    carea->Associate(this);
+    trate->Associate(this);
+    thold->Associate(this);
+
+    TGLayoutHints *laybut = new TGLayoutHints(kLHintsNormal, 5, 5, 10, 10);
+    fList->Add(laybut);
+
+    fTop2->AddFrame(carea, laybut);
+    fTop2->AddFrame(trate, laybut);
+    fTop2->AddFrame(thold, laybut);
+}
+
+void MMonteCarlo::AddSetupTab()
+{
+    //
+    // Create Setup Tab
+    //
+    TGCompositeFrame *frame = CreateNewTab("Setup");
+
+    //
+    // Create a button group (it alignes the buttons and make
+    // them automatic radio buttons)
+    // Create three (auto) radio buttons in the button group
+    //
+    TGVButtonGroup *group = new TGVButtonGroup(frame);
+    fList->Add(group);
+
+    fRadioButton1 = new TGRadioButton(group, "Use unnumbered trigger condition olny.");
+    fRadioButton2 = new TGRadioButton(group, "Use only one trigger condition (specify number below).");
+    fRadioButton3 = new TGRadioButton(group, "Use a number of trigger conditions (1..n).");
+
+    fRadioButton1->SetState(kButtonDown);
+
+    /*
+     WARNING:
+     Bacause of some strage and hidden dependencies the
+     GetMainFrame call in the destructor of TGButton may fail if some
+     of the other gui elemts is deleted first.
+     AddFirst adds the buttons at the beginning of the deletion list,
+     this seems to work.
+     */
+    fList->AddFirst(fRadioButton1);
+    fList->AddFirst(fRadioButton2);
+    fList->AddFirst(fRadioButton3);
+
+    //
+    // Add the button group (all buttons) as first line
+    //
+    frame->AddFrame(group);
+
+    //
+    // Create entry fields and labels for line 3 and 4
+    //
+
+    /*
+     * --> use with root >=3.02 <--
+     *
+
+     TGNumberEntry *fNumEntry1 = new TGNumberEntry(frame, 3.0, 2, M_NENT_LVL1, kNESRealOne, kNEANonNegative);
+     TGNumberEntry *fNumEntry2 = new TGNumberEntry(frame, 2.5, 2, M_NENT_LVL1, kNESRealOne, kNEANonNegative);
+
+     */
+
+    //
+    // Align the lines:
+    //  - top, left
+    //  - padding: top=20, bottom=0, left=20, right=0
+    //
+    TGLayoutHints *layline = new TGLayoutHints(kLHintsNormal, 20, 0, 20);
+    fList->Add(layline);
+
+
+    //
+    // Create a frame for line 3 and 4 to be able
+    // to align entry field and label in one line
+    //
+    TGHorizontalFrame *f = new TGHorizontalFrame(frame, 0, 0);
+    fNumEntry = new TGTextEntry(f, "****");
+    fNumEntry->SetText("1");
+    fList->Add(fNumEntry);
+
+    // --- doesn't work like expected --- fNumEntry1->SetAlignment(kTextRight);
+    // --- doesn't work like expected --- fNumEntry2->SetAlignment(kTextRight);
+
+    TGLabel *l = new TGLabel(f, "Trigger Condition Setup.");
+    l->SetTextJustify(kTextLeft);
+    fList->Add(l);
+
+    //
+    // Align the text of the label centered, left in the row
+    // with a left padding of 10
+    //
+    TGLayoutHints *laylabel = new TGLayoutHints(kLHintsCenterY|kLHintsLeft, 10); //, 10); //, 5, 5);
+    fList->Add(laylabel);
+
+    //
+    // Add one entry field and the corresponding label to each line
+    //
+    f->AddFrame(fNumEntry);
+    f->AddFrame(l, laylabel);
+
+    //
+    // Add line 3 and 4 to tab
+    //
+    frame->AddFrame(f, layline);
+}
+
+MMonteCarlo::MMonteCarlo(/*const TGWindow *main,*/ const TGWindow *p,
+                         const UInt_t w, const UInt_t h)
+: MBrowser(/*main,*/ p, w, h)
+{
+    AddButtons();
+    AddSetupTab();
+
+    MapSubwindows();
+
+    Layout();
+
+    SetWindowName("MonteCarlo Main");
+    SetIconName("MonteCarlo");
+
+    MapWindow();
+} 
+
+// ======================================================================
+#include <TObjArray.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MReadMarsFile.h"
+
+#include "MHMcRate.h"
+#include "MHMcEnergy.h"
+
+#include "MMcTriggerRateCalc.h"
+#include "MMcThresholdCalc.h"
+#include "MMcCollectionAreaCalc.h"
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
+#include "../mmc/MMcTrig.hxx" // FIXME: see FIXME below
+#endif
+
+Int_t MMonteCarlo::GetDim() const
+{
+    Int_t dim = atoi(fNumEntry->GetText());
+
+    if (dim<0)
+    {
+        dim=0;
+        fNumEntry->SetText("0");
+    }
+
+    if (fRadioButton1->GetState())
+        dim = 0;
+
+    if (fRadioButton2->GetState())
+        dim = -dim;
+
+    return dim;
+}
+
+void MMonteCarlo::CalculateCollectionArea()
+{
+    //
+    // first we have to create our empty lists
+    //
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
+    //
+    // FIXME: This line is needed that root finds the MMc-classes in the
+    // dictionary when calling the constructor of MReadTree
+    // I don't have any idea why...
+    // Rem: This happens only in this GUI!
+    //
+    MMcTrig trig;
+#endif
+
+    //
+    // Setup out tasks:
+    //  - First we have to read the events
+    //  - Then we can fill the efficiency histograms
+    //
+    MReadMarsFile read("Events", fInputFile);
+    tlist.AddToList(&read);
+
+    MMcCollectionAreaCalc effi;
+    tlist.AddToList(&effi);
+
+    //
+    // set up the loop for the processing
+    //
+    MEvtLoop magic;
+    magic.SetParList(&plist);
+
+    //
+    // Add ProgressBar to window
+    //
+    TGProgressBar *bar = CreateProgressBar(fTop2);
+    magic.SetProgressBar(bar);
+
+    //
+    // Execute your analysis
+    //
+    Bool_t rc = magic.Eventloop();
+
+    //
+    // Remove progressbar from window
+    //
+    DestroyProgressBar(bar);
+
+    if (!rc)
+        return;
+
+    //
+    // Now the histogram we wanted to get out of the data is
+    // filled and can be displayd
+    //
+    plist.FindObject("MHMcCollectionArea")->DrawClone();
+}
+
+void MMonteCarlo::CalculateTriggerRate()
+{
+    //
+    // dim : = 0 -> root file with 1 trigger condition.
+    //       > 0 -> number of trigger condition to be analised 
+    //              in multi conditon file.
+    //       < 0 -> selects the -dim trigger condition.
+    //
+    const Int_t dim = GetDim();
+
+    MParList plist;
+    MTaskList tlist;
+
+    //
+    // Setup the parameter list.
+    //
+    plist.AddToList(&tlist);
+
+    const UInt_t from = dim>0 ?   1 : -dim;
+    const UInt_t to   = dim>0 ? dim : -dim;
+    const Int_t  num  = to-from+1;
+
+    TObjArray hists(MParList::CreateObjList("MHMcRate", from, to));
+    hists.SetOwner();
+
+    //
+    // Check if the list really contains the right number of histograms
+    //
+    if (hists.GetEntriesFast() != num)
+        return;
+
+    //
+    // Set for each MHMcRate object the trigger condition number in the 
+    // camera file (for the case of camera files with several conditions,
+    // produced with the trigger_loop option.
+    //
+    if (dim < 0)
+        ((MHMcRate*)(hists[0]))->SetTriggerCondNum(to);
+    else
+        for (UInt_t i=from; i<=to; i++)
+            ((MHMcRate*)(hists[i-1]))->SetTriggerCondNum(i);
+
+    //
+    // Add the histograms to the parameter list.
+    //
+    plist.AddToList(&hists);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
+    //
+    // FIXME: This line is needed that root finds the MMc-classes in the
+    // dictionary when calling the constructor of MReadTree
+    // I don't have any idea why...
+    // Rem: This happens only in this GUI!
+    //
+    MMcTrig trig;
+#endif
+
+    //
+    // Setup out tasks:
+    //  - First we have to read the events
+    //  - Then we can calculate rates, for what the number of
+    //    triggered showers from a empty reflector file for the
+    //    analised trigger conditions should be set (BgR[])
+    //
+    MReadMarsFile read("Events", fInputFile);
+    tlist.AddToList(&read);
+
+    // We calculate only shower rate (not including NSB-only triggers)
+    Float_t* BgR = new Float_t[num];
+    memset(BgR, 0, num*sizeof(Float_t));
+
+    MMcTriggerRateCalc crate(dim, BgR, 100000);
+    tlist.AddToList(&crate);
+
+    //
+    // set up the loop for the processing
+    //
+    MEvtLoop magic;
+    magic.SetParList(&plist);
+
+    //
+    // Add ProgressBar to window
+    //
+    TGProgressBar *bar = CreateProgressBar(fTop2);
+    magic.SetProgressBar(bar);
+
+    //
+    // Execute your analysis
+    //
+    Bool_t rc = magic.Eventloop();
+
+    //
+    // Remove progressbar from window
+    //
+    DestroyProgressBar(bar);
+
+    delete BgR;
+
+    if (!rc)
+        return;
+
+    hists.Print();
+}
+
+void MMonteCarlo::CalculateThreshold()
+{
+    const Int_t dim = GetDim();
+
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Create numtriggerconditions histograms of type MHMcEnergy
+    // and store the histograms in an TObjArray
+    //
+    const UInt_t from = dim>0 ?   1 : -dim;
+    const UInt_t to   = dim>0 ? dim : -dim;
+    const Int_t  num  = to-from+1;
+
+    TObjArray hists(MParList::CreateObjList("MHMcEnergy", from, to));
+    hists.SetOwner();
+
+    //
+    // Check if the list really contains the right number of histograms
+    //
+    if (hists.GetEntriesFast() != num)
+        return;
+
+    //
+    // Add the histograms to the paramater list.
+    //
+    plist.AddToList(&hists);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,05,05)
+    //
+    // FIXME: This line is needed that root finds the MMc-classes in the
+    // dictionary when calling the constructor of MReadTree
+    // I don't have any idea why...
+    // Rem: This happens only in this GUI!
+    //
+    MMcTrig trig;
+#endif
+
+    //
+    // Setup the task list
+    //
+    MReadTree read("Events", fInputFile);
+
+    MMcThresholdCalc calc(dim);
+    tlist.AddToList(&read);
+    tlist.AddToList(&calc);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Add ProgressBar to window
+    //
+    TGProgressBar *bar = CreateProgressBar(fTop2);
+    evtloop.SetProgressBar(bar);
+
+    //
+    // Execute your analysis
+    //
+    Bool_t rc = evtloop.Eventloop();
+
+    //
+    // Remove progressbar from window
+    //
+    DestroyProgressBar(bar);
+
+    if (!rc)
+        return;
+
+    //
+    // Now you can display the results
+    //
+    hists.ForEach(TObject, DrawClone)();
+}
+
+// ======================================================================
+
+Bool_t MMonteCarlo::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+{
+    if (GET_MSG(msg) == kC_COMMAND && GET_SUBMSG(msg) == kCM_BUTTON)
+        switch (parm1)
+        {
+        case kButCollArea:
+            CalculateCollectionArea();
+            return kTRUE;
+
+        case kButTrigRate:
+            CalculateTriggerRate();
+            return kTRUE;
+
+        case kButThreshold:
+            CalculateThreshold();
+            return kTRUE;
+        }
+
+    return MBrowser::ProcessMessage(msg, parm1, parm2);
+}
Index: /tags/Mars-V0.9/mmain/MMonteCarlo.h
===================================================================
--- /tags/Mars-V0.9/mmain/MMonteCarlo.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MMonteCarlo.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifndef MARS_MMonteCarlo
+#define MARS_MMonteCarlo
+
+#ifndef MARS_MBrowser
+#include "MBrowser.h"
+#endif
+
+class TGTextEntry;
+class TGRadioButton;
+
+class MMonteCarlo : public MBrowser
+{
+private:
+    TGRadioButton *fRadioButton1;
+    TGRadioButton *fRadioButton2;
+    TGRadioButton *fRadioButton3;
+
+    TGTextEntry   *fNumEntry;
+
+    Int_t GetDim() const;
+
+    void CalculateCollectionArea();
+    void CalculateTriggerRate();
+    void CalculateThreshold();
+
+    void AddButtons();
+    void AddSetupTab();
+
+public:
+    MMonteCarlo(/*const TGWindow *main=NULL,*/ const TGWindow *p=NULL,
+                const UInt_t w=500, const UInt_t h=500);
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+    ClassDef(MMonteCarlo, 0) // GUI: The 'monte-carlo' browser
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MOnlineDisplay.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MOnlineDisplay.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MOnlineDisplay.cc	(revision 9772)
@@ -0,0 +1,225 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MOnlineDisplay.h"
+
+//
+// C-lib
+//
+#include <stdlib.h>              // atoi
+
+//
+// root
+//
+#include <TList.h>               // TList::Add
+#include <TStyle.h>              // gStyle->SetOptStat
+#include <TCanvas.h>             // TCanvas::cd
+
+//
+// root GUI
+//
+#include <TGLabel.h>             // TGLabel
+#include <TGButton.h>            // TGPictureButton
+#include <TGSlider.h>            // TGSlider
+#include <TG3DLine.h>            // TGHorizontal3DLine
+#include <TGTextEntry.h>         // TGTextEntry
+#include <TGButtonGroup.h>       // TGVButtonGroup
+#include <TRootEmbeddedCanvas.h> // TRootEmbeddedCanvas
+
+//
+// General
+//
+#include "MGList.h"              // MGList
+
+#include "MParList.h"            // MParList::AddToList
+#include "MEvtLoop.h"            // MEvtLoop::GetParList
+#include "MTaskList.h"           // MTaskList::AddToList
+
+//
+// Tasks
+//
+#include "MReadMarsFile.h"       // MReadMarsFile
+#include "MGeomApply.h"          // MGeomApply
+#include "MFDataMember.h"        // MFDataMember
+#include "MMcPedestalCopy.h"     // MMcPedestalCopy
+#include "MMcPedestalNSBAdd.h"   // MMcPedestalNSBAdd
+#include "MCerPhotCalc.h"        // MCerPhotCalc
+#include "MCerPhotAnal2.h"       // MCerPhotAnal2
+#include "MImgCleanStd.h"        // MImgCleanStd
+#include "MHillasCalc.h"         // MHillasCalc
+#include "MHillasSrcCalc.h"      // MHillasSrcCalc
+#include "MFillH.h"              // MFillH
+#include "MGTask.h"              // MGTask
+
+//
+// Container
+//
+#include "MHEvent.h"             // MHEvent
+#include "MHCamera.h"            // MHCamera
+#include "MRawEvtData.h"         // MRawEvtData
+
+ClassImp(MOnlineDisplay);
+
+// --------------------------------------------------------------------------
+//
+//  Constructor.
+//
+MOnlineDisplay::MOnlineDisplay() : MStatusDisplay(), fTask(0)
+{
+    //
+    // Add MOnlineDisplay GUI elements to the display
+    //
+    AddUserFrame();
+
+    //
+    // Show new part of the window, resize to correct aspect ratio
+    //
+    // FIXME: This should be done by MStatusDisplay automatically
+    Resize(GetWidth(), GetHeight() + fUserFrame->GetDefaultHeight());
+    SetWindowName("Online Display");
+    MapSubwindows();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the top part of the frame: This is filename and treename display
+//
+void MOnlineDisplay::AddTopFramePart1(TGCompositeFrame *vf1)
+{
+    TGLabel *file = new TGLabel(vf1, new TGString("Magic Online Analysis -- MONA"));
+    TGLayoutHints *laystd = new TGLayoutHints(kLHintsCenterX, 5, 5);
+    fList->Add(file);
+    fList->Add(laystd);
+    vf1->AddFrame(file,  laystd);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the second part of the top frame: This are the event number controls
+//
+void MOnlineDisplay::AddTopFramePart2(TGCompositeFrame *vf1)
+{
+    //
+    // --- the top2 part of the window ---
+    //
+    TGHorizontalFrame *top2 = new TGHorizontalFrame(vf1, 1, 1);
+    fList->Add(top2);
+
+    //
+    // Create the gui elements
+    //
+    TGTextButton *freeze = new TGTextButton(top2, " Freeze ", kFreeze);
+    freeze->SetUserData(freeze);
+    freeze->Associate(this);
+    freeze->SetToolTipText("Freeze the current Event");
+
+    fList->Add(freeze);
+
+    //
+    // add the gui elements to the frame
+    //
+    TGLayoutHints *laystd = new TGLayoutHints(kLHintsLeft|kLHintsCenterY, 5, 5);
+    fList->Add(laystd);
+
+    top2->AddFrame(freeze, laystd);
+
+    TGLayoutHints *laystd2 = new TGLayoutHints(kLHintsCenterX, 5, 5, 5, 5);
+    fList->Add(laystd2);
+    vf1->AddFrame(top2, laystd2);
+
+    //
+    // Add trailing line...
+    //
+    TGHorizontal3DLine *line = new TGHorizontal3DLine(vf1);
+    TGLayoutHints *layline = new TGLayoutHints(kLHintsExpandX);
+    fList->Add(line);
+    fList->Add(layline);
+    vf1->AddFrame(line, layline);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Add the user frame part of the display
+//
+void MOnlineDisplay::AddUserFrame()
+{
+    fUserFrame->ChangeOptions(kHorizontalFrame);
+
+    // Slider
+    TGVSlider *slider = new TGVSlider(fUserFrame, 1, kSlider1, kSlider);
+    slider->SetRange(10, 300);
+    slider->SetScale(15);
+    slider->SetPosition(10);
+    slider->Associate(this);
+    //slider->SetToolTipText("Change the update frequency of the event display (1-30s)");
+
+    // frame1/2
+    TGCompositeFrame *vf1 = new TGVerticalFrame(fUserFrame, 1, 1);
+    TGCompositeFrame *vf2 = new TGVerticalFrame(fUserFrame, 1, 1);
+
+    AddTopFramePart1(vf1);
+    AddTopFramePart2(vf1);
+
+    // create root embedded canvas and add it to the tab
+    TRootEmbeddedCanvas *ec = new TRootEmbeddedCanvas("Slices", vf2, vf1->GetDefaultHeight()*3/2, vf1->GetDefaultHeight(), 0);
+    vf2->AddFrame(ec);
+    fList->Add(ec);
+
+    // set background and border mode of the canvas
+    fCanvas = ec->GetCanvas();
+    fCanvas->SetBorderMode(0);
+    gROOT->GetListOfCanvases()->Add(fCanvas);
+    //fCanvas->SetBorderSize(1);
+    //fCanvas->SetBit(kNoContextMenu);
+    //fCanvas->SetFillColor(16);
+
+    // layout
+    TGLayoutHints *lays = new TGLayoutHints(kLHintsExpandY);
+    TGLayoutHints *lay = new TGLayoutHints(kLHintsExpandX);
+    fUserFrame->AddFrame(slider, lays);
+    fUserFrame->AddFrame(vf1, lay);
+    fUserFrame->AddFrame(vf2);
+
+    fList->Add(lay);
+    fList->Add(lays);
+    fList->Add(vf1);
+    fList->Add(vf2);
+    fList->Add(slider);
+}
+
+// --------------------------------------------------------------------------
+//
+//  ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)
+//
+// Processes information from all GUI items.
+// Selecting an item usually generates an event with 4 parameters.
+// The first two are packed into msg (first and second bytes).
+// The other two are parm1 and parm2.
+//
+Bool_t MOnlineDisplay::ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2)
+{
+    if (fTask && fTask->ProcessMessage(GET_MSG(msg), GET_SUBMSG(msg), mp1, mp2))
+        return kTRUE;
+
+    return MStatusDisplay::ProcessMessage(msg, mp1, mp2);
+}
Index: /tags/Mars-V0.9/mmain/MOnlineDisplay.h
===================================================================
--- /tags/Mars-V0.9/mmain/MOnlineDisplay.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MOnlineDisplay.h	(revision 9772)
@@ -0,0 +1,53 @@
+#ifndef MARS_MOnlineDisplay
+#define MARS_MOnlineDisplay
+
+#ifndef MARS_MStatusDisplay
+#include "MStatusDisplay.h"
+#endif
+
+class TGLabel;
+class TGTextEntry;
+class MEvtLoop;
+
+class MParList;
+class MTaskList;
+class MReadTree;
+class MGTask;
+
+class MOnlineDisplay : public MStatusDisplay
+{
+    friend class MOnlineDump;
+public:
+    enum
+    {
+        kSlider = MStatusDisplay::kSearch + 1,
+        kFreeze
+    };
+
+private:
+    TGCompositeFrame *fTab1;
+    TGCompositeFrame *fTab2;
+
+    TCanvas *fCanvas;
+
+    MGTask *fTask;
+
+    void AddTopFramePart1(TGCompositeFrame *frame);
+    void AddTopFramePart2(TGCompositeFrame *frame);
+    void AddUserFrame();
+
+    void UpdateDisplay();
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+public:
+    MOnlineDisplay();
+
+    void SetTask(MGTask *t) { fTask=t; }
+
+    ClassDef(MOnlineDisplay, 0) // Display for camera images (cerenkov events)
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mmain/MOnlineDump.cc
===================================================================
--- /tags/Mars-V0.9/mmain/MOnlineDump.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MOnlineDump.cc	(revision 9772)
@@ -0,0 +1,248 @@
+#include "MOnlineDump.h"
+
+#include <TCanvas.h>
+#include <TSystem.h>
+
+#include <TGButton.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+
+#include "MOnlineDisplay.h"
+
+#include "MFRealTimePeriod.h"
+#include "MHEvent.h"
+#include "MHCamera.h"
+#include "MHCamEvent.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MFillH.h"
+#include "MEventRate.h"
+
+ClassImp(MOnlineDump);
+
+using namespace std;
+
+void MOnlineDump::SetNoContextMenu(TObject *c)
+{
+    if (fDisplay->HasCanvas((TCanvas*)c))
+        c->ResetBit(kNoContextMenu);
+}
+
+void MOnlineDump::DisplayTriggerRate()
+{
+    Bool_t set = kFALSE;
+
+    if (!*fEvtTime)
+    {
+        fEvtTime->Now();
+        set = kTRUE;
+    }
+
+    const UInt_t  evts = fRawEvtHeader->GetDAQEvtNumber() - fEvtNumber;
+    const Double_t sec = *fEvtTime-fTime;
+
+    fEvtNumber = fRawEvtHeader->GetDAQEvtNumber();
+    fTime      = *fEvtTime;
+
+    if (evts>0 && sec>0 && fDisplay)
+        fDisplay->SetStatusLine2(Form("%sTrigger Rate: %.1fHz / Event Rate: %.1fHz",
+                                      (set?"Arb. ":""), evts/sec, fRate->GetRate()));
+
+    if (set)
+        fEvtTime->Reset();
+}
+
+Bool_t MOnlineDump::ProcessMessage(Int_t msg, Int_t submsg, Long_t mp1, Long_t mp2)
+{
+    switch (msg)
+    {
+    case kC_VSLIDER:
+        switch (submsg)
+        {
+        case kSL_POS:
+            if (mp1==MOnlineDisplay::kSlider && GetFilter())
+            {
+                ((MFRealTimePeriod*)GetFilter())->SetTime(mp2*100);
+                *fLog << dbg << "Update Time: " << Form("%.1fs", mp2/10.) << endl;
+            }
+            return kTRUE;
+        }
+        return kFALSE;
+    case kC_COMMAND:
+        switch(submsg)
+        {
+        case kCM_TAB:
+            {
+                //
+                // Set name for 'FADC canvas'. The name is the anchor for MHCamera.
+                // and clear the canvas
+                //
+                if (!fPlist || !fDisplay)
+                    return kTRUE;
+
+                TCanvas *c = fDisplay->GetCanvas(mp1);
+                if (!c)
+                    return kTRUE;
+
+                MHEvent *o = (MHEvent*)fPlist->FindObject(c->GetName());
+                if (o)
+                    ((MOnlineDisplay*)fDisplay)->fCanvas->SetName(Form("%p;%p;PixelContent", o->GetHist(),
+                                                                       c->GetPad(1)));
+            }
+            break;
+
+        case kCM_BUTTON:
+            if (mp1==MOnlineDisplay::kFreeze)
+            {
+                TGButton *but = (TGButton*)mp2;
+                if (!but->IsDown())
+                {
+                    but->AllowStayDown(kTRUE);
+                    fCamEvent->SetFreezed();
+                }
+                else
+                {
+                    but->AllowStayDown(kFALSE);
+                    fCamEvent->SetFreezed(kFALSE);
+                }
+                but->Toggle();
+            }
+            return kTRUE;
+        }
+        return kFALSE;
+    }
+    return kFALSE;
+}
+
+MOnlineDump::~MOnlineDump()
+{
+    if (fDisplay)
+        ((MOnlineDisplay*)fDisplay)->SetTask(0);
+}
+
+Int_t MOnlineDump::PreProcess(MParList *pList)
+{
+    fPlist = pList;
+
+    if (gROOT->IsBatch())
+    {
+        *fLog << err << "We are in batch mode!" << endl;
+        return kFALSE;
+    }
+    if (!fDisplay)
+    {
+        *fLog << err << "fDisplay not set." << endl;
+        return kFALSE;
+    }
+
+    MTaskList *tasks = (MTaskList*)pList->FindObject("MTaskList");
+    if (!tasks)
+    {
+        *fLog << err << "MTaskList not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fFill1 = (MFillH*)tasks->FindObject("MFillCamEvent");
+    if (!fFill1)
+    {
+        *fLog << err << "MFillCamEvent not found... abort." << endl;
+        return kFALSE;
+    }
+    fFill2 = (MFillH*)tasks->FindObject("MFillEvent");
+    if (!fFill2)
+    {
+        *fLog << err << "MFillEvent not found... abort." << endl;
+        return kFALSE;
+    }
+    fFill3 = (MFillH*)tasks->FindObject("MFillTriggerLvl0");
+    if (!fFill3)
+    {
+        *fLog << err << "MFillTriggerLvl0 not found... abort." << endl;
+        return kFALSE;
+    }
+
+    MHCamEvent *idxhi = (MHCamEvent*)pList->FindObject("MaxIdxHi");
+    MHCamEvent *idxlo = (MHCamEvent*)pList->FindObject("MaxIdxLo");
+    if (!idxhi || !idxlo)
+    {
+        *fLog << err << "MaxIdxHi or MaxIdxLo not found... abort." << endl;
+        return kFALSE;
+    }
+
+    idxhi->GetHistByName("sum")->SetMinimum(0);
+    idxlo->GetHistByName("sum")->SetMinimum(0);
+    idxhi->GetHistByName("sum")->SetMaximum(15);
+    idxlo->GetHistByName("sum")->SetMaximum(15);
+
+
+    fRawEvtHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+    if (!fRawEvtHeader)
+    {
+        *fLog << err << "MRawEvtHeader not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fRawRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRawRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fEvtTime = (MTime*)pList->FindObject("MTime");
+    if (!fEvtTime)
+    {
+        *fLog << err << "MTime not found... abort." << endl;
+        return kFALSE;
+    }
+
+    fRate = (MEventRate*)pList->FindObject("MEventRate");
+    if (!fRate)
+    {
+        *fLog << err << "MEventRate not found... abort." << endl;
+        return kFALSE;
+    }
+
+    MHEvent *hevent = (MHEvent*)pList->FindObject("MHEvent");
+    if (!hevent)
+    {
+        *fLog << err << "MHEvent not found... abort." << endl;
+        return kFALSE;
+    }
+    fCamEvent = hevent->GetHist();
+
+    fRunNumber = 0xffffffff;
+    fEvtNumber = 0;
+
+    SetNoContextMenu((TObject*)fFill1->GetCanvas());
+    SetNoContextMenu((TObject*)fFill2->GetCanvas());
+    SetNoContextMenu((TObject*)fFill3->GetCanvas());
+
+    return kTRUE;
+}
+
+Int_t MOnlineDump::Process()
+{
+    DisplayTriggerRate();
+
+    if (fDisplay && fRawRunHeader->GetNumEvents())
+        fDisplay->SetProgressBarPosition((Float_t)fEvtNumber/fRawRunHeader->GetNumEvents());
+
+    return kTRUE;
+}
+
+Int_t MOnlineDump::PostProcess()
+{
+    if (fDisplay)
+    {
+        fDisplay->SetProgressBarPosition(1);
+        //fDisplay->Reset();
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mmain/MOnlineDump.h
===================================================================
--- /tags/Mars-V0.9/mmain/MOnlineDump.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MOnlineDump.h	(revision 9772)
@@ -0,0 +1,53 @@
+#ifndef MARS_MOnlineDump
+#define MARS_MOnlineDump
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+class MFillH;
+class MHCamera;
+class MRawEvtHeader;
+class MRawRunHeader;
+class MTime;
+class MParList;
+class MEventRate;
+
+class MOnlineDump : public MGTask
+{
+private:
+    MFillH *fFill1;
+    MFillH *fFill2;
+    MFillH *fFill3;
+
+    MHCamera *fCamEvent;
+
+    UInt_t fRunNumber;
+    UInt_t fEvtNumber;
+
+    MRawEvtHeader *fRawEvtHeader;
+    MRawRunHeader *fRawRunHeader;
+    MEventRate    *fRate;
+
+    MTime *fEvtTime;
+    Double_t fTime;
+
+    MParList *fPlist;
+
+    void SetNoContextMenu(TObject *c);
+    void DisplayTriggerRate();
+
+    Bool_t ProcessMessage(Int_t msg, Int_t submsg, Long_t mp1, Long_t mp2);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MOnlineDump() : fPlist(NULL) { fName = "MOnlineDump"; }
+    ~MOnlineDump();
+
+    ClassDef(MOnlineDump, 0) // Task to fill a histogram with data from a parameter container
+};
+
+#endif
Index: /tags/Mars-V0.9/mmain/MainIncl.h
===================================================================
--- /tags/Mars-V0.9/mmain/MainIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MainIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mmain/MainLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mmain/MainLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mmain/MainLinkDef.h	(revision 9772)
@@ -0,0 +1,12 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MBrowser+;
+
+#pragma link C++ class MCameraDisplay+;
+#pragma link C++ class MEventDisplay+;
+
+#endif
Index: /tags/Mars-V0.9/mmain/Makefile
===================================================================
--- /tags/Mars-V0.9/mmain/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mmain/Makefile	(revision 9772)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Main
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../manalysis -I../mdatacheck -I../mraw        \
+	   -I../mgui -I../mgeom -I../mhbase -I../mhist -I../mmontecarlo   \
+           -I../mfileio -I../mimage -I../mhistmc -I../mgbase -I../mfbase  \
+           -I../mdata -I../msignal -I../mcalib -I../mbadpixels            \
+           -I../mpointing -I../mpedestal
+
+SRCFILES = MBrowser.cc \
+           MEventDisplay.cc \
+           MCameraDisplay.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mmc/MFadcDefine.h
===================================================================
--- /tags/Mars-V0.9/mmc/MFadcDefine.h	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MFadcDefine.h	(revision 9772)
@@ -0,0 +1,41 @@
+//
+//  --> Sampling frequency of the FADC, in number of slices
+//  per nsec, for the original 300 MHz FADCs of MAGIC. WARNING:
+//  DO NOT CHANGE this number to set a different sampling frequency
+//  of the signals! USE instead the "fadc_GHz" command in the camera
+//  input card (see instructions)
+//
+#define FADC_SLICES_PER_NSEC 0.3
+//
+//
+//  --> The amount of FADC slice written to the raw format.
+#define FADC_SLICES  15
+//
+//  --> Number of bins per FADC slice that we will use for the analog 
+//      signal simulation. In March 2005, raised this value from 5 to 500 
+//      so that we can properly simulate the time jitter of the PMTs (which is
+//      by default 200 ps)
+#define SUBBINS     500 
+//
+//
+// --> Default values of the single photoelectron response going to the FADC,
+//     in the case the gaussian shape is chosen.
+//
+#define MFADC_RESPONSE_FWHM       5.0
+#define MFADC_RESPONSE_INTEGRAL   4.0
+
+//
+// -->  The maximum number of FADC channels
+//      Most likely it will be always equal to CAMERA_PIXELS 
+#define MFADC_CHANNELS  3500
+//
+//  --> Ratio of high to low gain:
+#define HIGH2LOWGAIN 10.
+//
+//
+//  --> The amount of ns before trigger that would be shown from the ADC
+//      history in order to show also the start of the pulse before the
+//      the trigger time.-> JUST FOR DISPLAY purposes! (see MFadc::Scan)
+#define TIME_BEFORE_TRIGGER    10.  
+// 
+//
Index: /tags/Mars-V0.9/mmc/MMcConfigRunHeader.cc
===================================================================
--- /tags/Mars-V0.9/mmc/MMcConfigRunHeader.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcConfigRunHeader.cc	(revision 9772)
@@ -0,0 +1,120 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch  11/2002 (blanch@ifae.es)
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMcConfigRunHeader
+//
+// Root storage container for the MONTE CARLO CONFIGURATION information
+//
+// It saves in a root file all the infromation about values in the configuration
+// files used in the Monte Carlo production: MagicDef (definition of the teslescope),
+// Reflectivity.dat (mirror reflectivities), qe.dat (PMT QEs), axisdev.dat (mirrors 
+// deviations) and lightguides.dat (Effect of the Light Guides).
+//
+//
+// Version 2: 
+// -----------
+// removed obsolete variables which are no longer used by reflector, 
+// nor present in the magic.def file:  fFocalStdev, fPointStdev, fDevAdjust
+//
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MMcConfigRunHeader.h"
+
+#include <fstream>
+#include <iomanip>
+
+#include <TArrayF.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MMcConfigRunHeader);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+//
+MMcConfigRunHeader::MMcConfigRunHeader(const char *name, const char *title)
+    : fNumMirrors(0), fNumPMTs(0), fIncidentTheta(181), fLightCollectionFactor(181), fLightCollectionFactorOuter(181)
+{
+    fName  = name  ? name  : "MMcConfigRunHeader";
+    fTitle = title ? title : "Mc Configuration Information";
+
+    fRadiusMirror=-1;
+    fFocalDist   =-1;
+    fPointSpread =-1;
+    fBlackSpot   =-1;
+    fCameraWidth =-1;
+
+    fMirrors = new TClonesArray("MGeomMirror", 0);
+    fPMTs = new TClonesArray("MGeomPMT", 0);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// DESCRIPTION MISSING Please contact Oscar
+//
+void MMcConfigRunHeader::SetMagicDef(Float_t radius,
+				     Float_t focal,
+				     Float_t point,
+				     Float_t spot,
+				     Float_t camwidth)
+{
+    fRadiusMirror=radius;
+    fFocalDist=focal;
+    fPointSpread=point;
+    fBlackSpot=spot;
+    fCameraWidth=camwidth;
+    
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the values corresponding to the light collection efficiency due to
+// light guides, plexiglas, double crossing, collection of 1st dynode. These
+// are fed to the camera program via de Data/LightCollection.dat file (see
+// camera manual)
+// 
+void  MMcConfigRunHeader::SetLightCollection(const TArrayF &theta, const TArrayF &factor, const TArrayF &factor_outer)
+{
+    if (fIncidentTheta.GetSize()    !=theta.GetSize() ||
+        fLightCollectionFactor.GetSize()!=factor.GetSize() ||
+        fLightCollectionFactorOuter.GetSize()!=factor_outer.GetSize())
+    {
+        *fLog<< err << dbginf << "fIncidentTheta or fLightCollectionFactor";
+        *fLog << "or fLightCollectionFactorOuter" << endl;
+        *fLog << "do not have size of setting arrays" << endl;
+        return;
+    }
+
+    fIncidentTheta = theta;
+    fLightCollectionFactor = factor;
+    fLightCollectionFactorOuter = factor_outer;
+}
Index: /tags/Mars-V0.9/mmc/MMcConfigRunHeader.h
===================================================================
--- /tags/Mars-V0.9/mmc/MMcConfigRunHeader.h	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcConfigRunHeader.h	(revision 9772)
@@ -0,0 +1,139 @@
+#ifndef MARS_MMcConfigRunHeader
+#define MARS_MMcConfigRunHeader
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+#ifndef MARS_MGeomMirror
+#include "MGeomMirror.h"
+#endif
+#ifndef MARS_MGeomPMT
+#include "MGeomPMT.h"
+#endif
+
+class MGeomMirror;
+class MGeomPMT;
+
+//////////////////////////////////////////////////////////////////////////////////
+//
+// class MMcConfigRunHeader
+//
+// Authors: O. Blanch, A. Moralejo 
+//
+// Container to keep some data on the used MC simulation parameters
+// 
+// Version 3: Added member fLightCollectionFactorOuter so that we can store 
+//            the data on the simulatedlight collection efficiency (light
+//            guides + plexiglas +...) as a function of incidence angle for 
+//            outer and inner pixels independently.
+//
+// Version 4: Added member fMirrorFraction, the "active" fraction of the 
+//            mirror dish, to account for reflectivity losses, missing 
+//            mirrors, etc.
+//
+// Version 5: Added member fPmtTimeJitter, the time jitter of the PMTs
+//            (sigma of gaussian) for each photoelectron.
+//
+/////////////////////////////////////////////////////////////////////////////////
+
+class MMcConfigRunHeader : public MParContainer
+{
+private:
+    // Mirror Information
+    UShort_t      fNumMirrors;
+    Float_t       fRadiusMirror;// [cm] Radius of a single mirror
+    TClonesArray *fMirrors;     // FIXME: Change TClonesArray away from a pointer?
+
+    Float_t fMirrorFraction;    // (adimensional, between 0 and 1) Fraction of mirror dish
+                                //  which is really working.
+
+    // Magic Def Parameters
+    Float_t fFocalDist;         // [cm] Focal distance
+    Float_t fPointSpread;       // [cm] Point spread function, sigma in x and y on the camera as simualted in the Reflector
+    Float_t fPointSpreadX;       // [cm] Point spread function, sigma in x on the camera adding gaussian in the Camera
+    Float_t fPointSpreadY;       // [cm] Point spread function, sigma in y on the camera adding gaussian in the Camera
+    Float_t fBlackSpot;         // [cm] Radius of black spot in the mirror center
+    Float_t fCameraWidth;       // [cm] Radius on the camera plain 
+                                // inside which the phe are kept.
+
+    Float_t fMissPointingX;     // [deg] Misspointing in deg added in he Camera 
+    Float_t fMissPointingY;     // [deg] simulation at rho (rotation FoV) = 0. 
+
+    Float_t fPmtTimeJitter;     // [ns] PMT time jitter (sigma of gaussian), per phe-
+
+    // QE Information
+    UInt_t  fNumPMTs;
+    TClonesArray  *fPMTs;
+
+    // Light Collection Information (guides , plexiglas, 1st dynode) 
+
+    TArrayF fIncidentTheta;    // [deg] Angle (0-180 deg) between light 
+                               // direction and camera plane.
+    TArrayF fLightCollectionFactor;//   Inner pixels
+    TArrayF fLightCollectionFactorOuter;//  Outer pixels
+
+public:
+    MMcConfigRunHeader(const char *name=NULL, const char *title=NULL);
+    ~MMcConfigRunHeader() { delete fMirrors; delete fPMTs; }
+
+    void SetMagicDef(Float_t radius, Float_t focal, Float_t point,
+		     Float_t spot, Float_t camwidth);
+    void SetLightCollection(const TArrayF &theta, const TArrayF &factor, 
+			    const TArrayF &factor_outer);
+
+    UInt_t GetNumMirror() const { return fNumMirrors; }
+    void   InitSizeMirror(UInt_t num) { fMirrors->Expand(num); }
+
+    void   SetMirrorFraction(Float_t x) { fMirrorFraction = x; }
+
+    UInt_t GetNumPMTs() const { return fNumPMTs; }
+    void   InitSizePMTs(UInt_t num) { fPMTs->Expand(num); }
+
+    Float_t GetPointSpread() const { return fPointSpread; }
+    void    SetPointSpread(Float_t x) { fPointSpread = x; }
+
+    Float_t GetPointSpreadX() const { return fPointSpreadX; }
+    void    SetPointSpreadX(Float_t x) { fPointSpreadX = x; }
+    Float_t GetPointSpreadY() const { return fPointSpreadY; }
+    void    SetPointSpreadY(Float_t x) { fPointSpreadY = x; }
+
+    Float_t GetMissPointingX() const {return fMissPointingX;}
+    void    SetMissPointingX(Float_t x) {fMissPointingX=x;}
+
+    Float_t GetMissPointingY() const {return fMissPointingY;}
+    void    SetMissPointingY(Float_t x) {fMissPointingY=x;}
+
+    TArrayF GetLightCollectionFactor() const {return fLightCollectionFactor; }
+    TArrayF GetLightCollectionFactorOuter() const 
+      {return fLightCollectionFactorOuter; }
+
+    Float_t GetMirrorFraction() const { return fMirrorFraction; }
+
+    TArrayF GetIncidentTheta() const {return fIncidentTheta;}
+
+    void   AddMirror(Int_t id)
+    {
+        new ((*fMirrors)[fNumMirrors++]) MGeomMirror(id);
+    }
+
+    void   AddPMT(Int_t id)
+    {
+        new ((*fPMTs)[fNumPMTs++]) MGeomPMT(id);
+    }
+
+    MGeomMirror &GetMirror(int i)  { return *(MGeomMirror*)(fMirrors->UncheckedAt(i)); }
+    MGeomMirror &GetMirror(int i) const { return *(MGeomMirror*)(fMirrors->UncheckedAt(i)); }
+
+    TClonesArray *GetMirrors() { return fMirrors; }
+
+    MGeomPMT &GetPMT(int i)  { return *(MGeomPMT*)(fPMTs->UncheckedAt(i)); }
+    MGeomPMT &GetPMT(int i) const { return *(MGeomPMT*)(fPMTs->UncheckedAt(i)); }
+    void    SetPmtTimeJitter(Float_t x) { fPmtTimeJitter = x; }
+    Float_t GetPmtTimeJitter() const { return fPmtTimeJitter; }
+
+    ClassDef(MMcConfigRunHeader, 5)  // class for monte carlo configuration information
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mmc/MMcCorsikaRunHeader.cc
===================================================================
--- /tags/Mars-V0.9/mmc/MMcCorsikaRunHeader.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcCorsikaRunHeader.cc	(revision 9772)
@@ -0,0 +1,211 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch  11/2002 (blanch@ifae.es)
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMcCorsikaRunHeader
+//
+// Root storage container for the CORSIKA run header
+//
+// It saves in a root file all variable that are in the CORSIKA run header, except
+// dummies.
+//
+////////////////////////////////////////////////////////////////////////////
+
+
+#include "MGeomCorsikaCT.h"
+#include "MMcCorsikaRunHeader.h"
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MMcCorsikaRunHeader);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+//
+MMcCorsikaRunHeader::MMcCorsikaRunHeader(const char *name, const char *title,
+					 int NumCT)
+  : fTelescopes(NumCT)
+{
+    fName  = name  ? name  : "MMcCorsikaRunHeader";
+    fTitle = title ? title : "Translation of the CORSIKA header";
+
+    fRunNumber = 0;
+    fDate = 0;
+    fCorsikaVersion = 0;
+    fNumObsLev = 0;
+
+    for (int i=0; i<10; i++)
+        fHeightLev[i]=0;
+
+    fSlopeSpec = 0;
+    fELowLim = 0;
+    fEUppLim = 0;
+    fEGS4flag = 0;
+    fNKGflag = 0;
+    fEcutoffh = 0;
+    fEcutoffm = 0;
+    fEcutoffe = 0;
+    fEcutoffg = 0;
+
+    for(int i=0; i<50; i++)  fC[i] = 0;
+    for(int i=0; i<40; i++)  fCKA[i] = 0;
+    for(int i=0; i<5; i++)  fCETA[i] = 0;
+    for(int i=0; i<11; i++)  fCSTRBA[i] = 0;
+    for(int i=0; i<5; i++)
+    {
+        fAATM[i] = 0;
+        fBATM[i] = 0;
+        fCATM[i] = 0;
+    }
+    for (int i=0;i<4; i++)  fNFL[i] = 0;
+
+    fViewconeAngles[0]=0.0;
+    fViewconeAngles[1]=0.0;
+
+    fWobbleMode=0;
+    fAtmosphericModel=0;
+
+    fNumCT=NumCT;
+
+    fTelescopes.SetOwner();
+
+    for  (int i=0;i<NumCT;i++)
+      {
+	MGeomCorsikaCT* dummy = new  MGeomCorsikaCT();
+	fTelescopes.Add(dummy);
+      }
+
+    SetReadyToSave();
+}
+
+// -------------------------------------------------------------------------
+//
+// Fill Corsika Run Header
+//
+void MMcCorsikaRunHeader::Fill(const Float_t  runnumber,
+                               const Float_t  date,
+			       const Float_t  vers,
+			       const Float_t  numobslev,
+			       const Float_t  height[10],
+			       const Float_t  slope,
+			       const Float_t  elow,
+			       const Float_t  eupp,
+			       const Float_t  egs4,
+			       const Float_t  nkg,
+			       const Float_t  eh,
+			       const Float_t  em,
+			       const Float_t  ee,
+			       const Float_t  eg,
+			       const Float_t  c[50],
+			       const Float_t  cka[40],
+			       const Float_t  ceta[5],
+			       const Float_t  cstrba[11],
+			       const Float_t  aatm[5],
+			       const Float_t  batm[5],
+			       const Float_t  catm[5],
+			       const Float_t  nfl[4],
+			       const Float_t  viewcone[2],
+			       const Float_t  wobble,
+			       const Float_t  atmospher
+			       )
+{
+    fRunNumber = runnumber;
+    fDate = date;
+    fCorsikaVersion = vers;
+    fNumObsLev = numobslev;
+
+    for (int i=0; i<10; i++)
+        fHeightLev[i]=height[i];
+
+    fSlopeSpec = slope;
+    fELowLim = elow;
+    fEUppLim = eupp;
+    fEGS4flag = egs4;
+    fNKGflag = nkg;
+    fEcutoffh = eh;
+    fEcutoffm = em;
+    fEcutoffe = ee;
+    fEcutoffg = eg;
+
+    for (int i=0; i<50; i++)  fC[i] = c[i];
+    for (int i=0; i<40; i++)  fCKA[i] = cka[i];
+    for (int i=0; i<5 ; i++)  fCETA[i] = ceta[i];
+    for (int i=0; i<11; i++)  fCSTRBA[i] = cstrba[i];
+    for (int i=0; i<5; i++)
+    {
+        fAATM[i] = aatm[i];
+        fBATM[i] = batm[i];
+        fCATM[i] = catm[i];
+    }
+    for (int i=0; i<4; i++)  fNFL[i] = nfl[i];
+
+    fViewconeAngles[0]=viewcone[0];
+    fViewconeAngles[1]=viewcone[1];
+
+    fWobbleMode=wobble;
+    fAtmosphericModel=atmospher;
+
+}
+
+// -------------------------------------------------------------------------
+//
+// Fill C Telescope information in Corsika Run Header
+//
+void MMcCorsikaRunHeader::FillCT(Float_t ctx, Float_t cty, Float_t ctz,
+				 Float_t cttheta, Float_t ctphi,
+				 Float_t ctdiam, Float_t ctfocal,
+				 Int_t CTnum){
+
+  static_cast<MGeomCorsikaCT*>(fTelescopes.UncheckedAt(CTnum))
+    ->Fill(ctx, cty, ctz, cttheta, ctphi, ctdiam, ctfocal);
+
+}
+
+// -------------------------------------------------------------------------
+//
+// Returns a reference of the i-th entry (the telescope with the index i)
+//
+MGeomCorsikaCT &MMcCorsikaRunHeader::operator[](Int_t i) const
+{
+    return *static_cast<MGeomCorsikaCT*>(fTelescopes.UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints the information of all telescopes
+//
+void MMcCorsikaRunHeader::Print(Option_t *) const
+{
+    //
+    //   Print Information about the Geometry of the camera
+    //
+  *fLog << all << GetTitle() <<". Number of Telescopes: " << fNumCT << endl;
+
+  fTelescopes.Print();
+} 
Index: /tags/Mars-V0.9/mmc/MMcCorsikaRunHeader.h
===================================================================
--- /tags/Mars-V0.9/mmc/MMcCorsikaRunHeader.h	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcCorsikaRunHeader.h	(revision 9772)
@@ -0,0 +1,115 @@
+#ifndef MARS_MMcCorsikaRunHeader
+#define MARS_MMcCorsikaRunHeader
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MMcCorsikaRunHeader                                               //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MGeomCorsikaCT;
+
+class MMcCorsikaRunHeader : public MParContainer
+{
+private:
+    // Header copied directly from CORSIKA header, skiping dummy values.
+    // The propouse of this container is being able to cmopare with
+    // Corsika run Header
+    // See CORSIKA manual for explanations
+    Float_t fRunNumber;
+    Float_t fDate;
+    Float_t fCorsikaVersion;
+    Float_t fNumObsLev;
+    Float_t fHeightLev[10];
+    Float_t fSlopeSpec;  // Slope of primaries' energy spectrum
+    Float_t fELowLim;
+    Float_t fEUppLim;    // Limits of energy range for generation
+    Float_t fEGS4flag;
+    Float_t fNKGflag;
+    Float_t fEcutoffh;
+    Float_t fEcutoffm;
+    Float_t fEcutoffe;
+    Float_t fEcutoffg;
+
+    // Physical constants and interaction flags (see CORSIKA manual):
+    Float_t fC[50];
+    Float_t fCKA[40];
+    Float_t fCETA[5];
+    Float_t fCSTRBA[11];
+    Float_t fAATM[5];
+    Float_t fBATM[5];
+    Float_t fCATM[5];
+    Float_t fNFL[4];
+
+    // (degrees) Inner and outer angles in Corsika's VIEWCONE option
+    Float_t fViewconeAngles[2]; 
+                                  
+
+    Float_t fWobbleMode;     // Indicates wobble mode with which
+                             //  reflector has been run 
+    Float_t fAtmosphericModel; // Indicates atmospheric model used in
+                               // absorption simulation. 0 = no atmosphere,
+                               // 1 = atm_90percent, 2 = atm_isothermal,
+                               // 3 = atm_corsika.
+    UInt_t fNumCT;
+    TObjArray fTelescopes;
+
+public:
+    MMcCorsikaRunHeader(const char *name=NULL, const char *title=NULL,
+			int NumCT=1);
+
+
+    void Fill(const Float_t  runnumber,
+              const Float_t  date,
+              const Float_t  vers,
+              const Float_t  fNumObsLev,
+              const Float_t  height[10],
+              const Float_t  slope,
+              const Float_t  elow,
+              const Float_t  eupp,
+              const Float_t  egs4,
+              const Float_t  nkg,
+              const Float_t  eh,
+              const Float_t  em,
+              const Float_t  ee,
+              const Float_t  eg,
+              const Float_t  c[50],
+              const Float_t  cka[40],
+              const Float_t  ceta[5],
+              const Float_t  cstrba[11],
+              const Float_t  aatm[5],
+              const Float_t  batm[5],
+              const Float_t  catm[5],
+              const Float_t  nfl[4],
+	      const Float_t  viewcone[2],
+	      const Float_t  wobble,
+	      const Float_t  atmospher
+             );
+
+    Float_t GetELowLim() const { return fELowLim; }
+    Float_t GetEUppLim() const { return fEUppLim; }
+    Float_t GetSlopeSpec() const { return fSlopeSpec; }
+
+    Int_t GetNumCT() const { return fNumCT; }
+
+    void FillCT(Float_t ctx, Float_t cty, Float_t ctz,
+		Float_t cttheta, Float_t ctphi,
+		Float_t ctdiam, Float_t ctfocal,
+		Int_t CTnum);
+
+    MGeomCorsikaCT &operator[](Int_t i) const;
+
+    virtual void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MMcCorsikaRunHeader, 3) // storage container for corsika setup information
+};
+#endif
+
+
+
Index: /tags/Mars-V0.9/mmc/MMcEvt.cxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcEvt.cxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcEvt.cxx	(revision 9772)
@@ -0,0 +1,306 @@
+#include "MMcEvt.hxx"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+//==========
+// MMcEvt
+//    
+// This class handles and contains the MonteCarlo information
+// with which the events have been generated
+// This information exists for each event.
+//
+// Note: All the azimuth Phi angles in this and other MC classes follow
+// the convention in the Corsika program (see Corsika manual). There, phi
+// is the azimuth of the momentum vector of particles, and is measured
+// from the north direction, anticlockwise (i.e, west is phi=90 degrees).
+// When it refers to the telescope orientation, it is the azimuth of a 
+// vector along the telescope axis, going from the camera to the mirror. 
+// So, fTelescopeTheta=90, fTelescopePhi = 0 means the telescope is 
+// pointing horizontally towards South. For an explanation, see also 
+// TDAS 02-11. 
+//
+ClassImp(MMcEvt);
+
+using namespace std;
+
+
+MMcEvt::MMcEvt()
+{
+    //
+    //  default constructor
+    //  set all values to zero
+    fName  = "MMcEvt";
+    fTitle = "Event info from Monte Carlo";
+
+    Clear();
+}
+
+MMcEvt::MMcEvt( UInt_t  fEvtNum,
+		UShort_t usPId,
+		Float_t  fEner,
+		Float_t  fThi0,
+		Float_t  fFirTar,
+		Float_t  fzFirInt,
+		Float_t  fThet, 
+		Float_t  fPhii, 
+		Float_t  fCorD, 
+		Float_t  fCorX, 
+		Float_t  fCorY,
+		Float_t  fImpa,
+		Float_t  fTPhii,
+		Float_t  fTThet,
+		Float_t  fTFirst,
+		Float_t  fTLast,
+		Float_t  fL_Nmax,
+		Float_t  fL_t0,
+		Float_t  fL_tmax,
+		Float_t  fL_a,
+		Float_t  fL_b,
+		Float_t  fL_c,
+		Float_t  fL_chi2,
+		UInt_t   uiPin, 
+		UInt_t   uiPat,  
+		UInt_t   uiPre, 
+		UInt_t   uiPco,  
+		UInt_t   uiPelS,
+		UInt_t   uiPelC,
+		Float_t  elec,
+		Float_t  muon,
+		Float_t  other,
+		Float_t  fadc_jitter) {
+
+    fName  = "MMcEvt";
+    fTitle = "Event info from Monte Carlo";
+  //
+  //  constuctor II 
+  //
+  //  All datamembers are parameters. 
+  //
+  //  Don't use this memberfunction in analysis
+  //  
+
+  fEvtNumber = fEvtNum;
+  fPartId = usPId  ;
+  fEnergy  = fEner  ;
+  fThick0 = fThi0;
+  fFirstTarget = fFirTar;
+  fZFirstInteraction = fzFirInt;
+
+  fTheta   = fThet ;
+  fPhi     = fPhii ;
+
+  fCoreD   = fCorD ;
+  fCoreX   = fCorX ;
+  fCoreY   = fCorY ;
+  fImpact  = fImpa ;
+
+  fTelescopePhi = fTPhii;
+  fTelescopeTheta = fTThet;
+  fTimeFirst = fTFirst;
+  fTimeLast = fTLast;
+  fLongiNmax = fL_Nmax;
+  fLongit0 = fL_t0;
+  fLongitmax = fL_tmax;
+  fLongia = fL_a;
+  fLongib = fL_b;
+  fLongic = fL_c;
+  fLongichi2 = fL_chi2;
+
+
+  fPhotIni      = uiPin ;
+  fPassPhotAtm  = uiPat ;
+  fPassPhotRef  = uiPre ;
+  fPassPhotCone = uiPco ;
+  fPhotElfromShower = uiPelS ;
+  fPhotElinCamera   = uiPelC ;
+
+  fElecCphFraction=elec;
+  fMuonCphFraction=muon;
+  fOtherCphFraction=other;
+
+  fFadcTimeJitter = fadc_jitter;
+}
+
+
+
+MMcEvt::~MMcEvt() {
+  //
+  //  default destructor
+  //
+}
+
+
+
+
+void MMcEvt::Clear(Option_t *opt)
+{
+    //
+    //  reset all values to values as nonsense as possible
+    //
+    fPartId = 0;
+    fEnergy = -1;
+
+    fTheta = 0;
+    fPhi   = 0;
+
+    fCoreD  =  0;
+    fCoreX  =  0;
+    fCoreY  =  0;
+    fImpact = -1;
+
+    fPhotIni          = 0;
+    fPassPhotAtm      = 0;
+    fPassPhotRef      = 0;
+    fPassPhotCone     = 0;
+    fPhotElfromShower = 0;
+    fPhotElinCamera   = 0;
+
+    fElecCphFraction=0;
+    fMuonCphFraction=0;
+    fOtherCphFraction=0;
+}
+
+void MMcEvt::Fill( UInt_t  fEvtNum,
+		   UShort_t usPId, 
+		   Float_t  fEner, 
+		   Float_t  fThi0,
+		   Float_t  fFirTar,
+		   Float_t  fzFirInt,
+		   Float_t  fThet, 
+		   Float_t  fPhii, 
+		   Float_t  fCorD, 
+		   Float_t  fCorX, 
+		   Float_t  fCorY,
+		   Float_t  fImpa, 
+		   Float_t  fTPhii,
+		   Float_t  fTThet,
+		   Float_t  fTFirst,
+		   Float_t  fTLast,
+		   Float_t  fL_Nmax,
+		   Float_t  fL_t0,
+		   Float_t  fL_tmax,
+		   Float_t  fL_a,
+		   Float_t  fL_b,
+		   Float_t  fL_c,
+		   Float_t  fL_chi2,
+		   UInt_t   uiPin, 
+		   UInt_t   uiPat,  
+		   UInt_t   uiPre, 
+		   UInt_t   uiPco,  
+		   UInt_t   uiPelS,  
+		   UInt_t   uiPelC,
+		   Float_t  elec,
+		   Float_t  muon,
+		   Float_t  other,
+		   Float_t  fadc_jitter) {
+  //
+  //  All datamembers are filled with the correspondin parameters. 
+  //
+  //  Don't use this memberfunction in analysis
+  //  
+
+  fEvtNumber = fEvtNum;
+  fPartId = usPId  ;
+  fEnergy = fEner  ;
+  fThick0 = fThi0;
+  fFirstTarget = fFirTar;
+  fZFirstInteraction = fzFirInt;
+
+  fTheta  = fThet ;
+  fPhi    = fPhii ;
+
+  fCoreD  = fCorD ;
+  fCoreX  = fCorX ;
+  fCoreY  = fCorY ;
+  fImpact = fImpa ;
+
+  fTelescopePhi = fTPhii;
+  fTelescopeTheta = fTThet;
+  fTimeFirst = fTFirst;
+  fTimeLast = fTLast;
+  fLongiNmax = fL_Nmax;
+  fLongit0 = fL_t0;
+  fLongitmax = fL_tmax;
+  fLongia = fL_a;
+  fLongib = fL_b;
+  fLongic = fL_c;
+  fLongichi2 = fL_chi2;
+
+  fPhotIni      = uiPin ;
+  fPassPhotAtm  = fPhotIni-uiPat ;
+  fPassPhotRef  = fPassPhotAtm-uiPre ;
+  fPassPhotCone = uiPco ;
+  fPhotElfromShower = uiPelS ;
+  fPhotElinCamera = uiPelC ;
+
+  fElecCphFraction=elec;
+  fMuonCphFraction=muon;
+  fOtherCphFraction=other;
+
+  fFadcTimeJitter = fadc_jitter;
+}
+
+/*
+void MMcEvt::AsciiWrite(ofstream &fout) const
+{
+    fout << fEnergy << " ";
+    fout << fTheta ;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the container.
+//
+//  if you specify an option only the requested data members are printed:
+//  allowed options are:
+//   id, energy, impact
+//
+void MMcEvt::Print(Option_t *opt) const
+{
+    //
+    //  print out the data member on screen
+    //
+    TString str(opt);
+    if (str.IsNull())
+    {
+        *fLog << all << endl;
+        *fLog << "Monte Carlo output:" << endl;
+        *fLog << " Particle Id:    ";
+        switch(fPartId)
+        {
+        case kGAMMA:
+            *fLog << "Gamma" << endl;
+            break;
+        case kPROTON:
+            *fLog << "Proton" << endl;
+            break;
+        case kHELIUM:
+            *fLog << "Helium" << endl;
+            break;
+        }
+        *fLog << " Energy:         " << fEnergy << "GeV" << endl;
+        *fLog << " Impactpar.:     " << fImpact/100 << "m" << endl;
+        *fLog << " Photoelectrons: " << fPhotElfromShower << endl;
+        *fLog << endl;
+        return;
+    }
+    if (str.Contains("id", TString::kIgnoreCase))
+        switch(fPartId)
+        {
+        case kGAMMA:
+            *fLog << "Particle: Gamma" << endl;
+            break;
+        case kPROTON:
+            *fLog << "Particle: Proton" << endl;
+            break;
+        case kHELIUM:
+            *fLog << "Particle: Helium" << endl;
+            break;
+        }
+    if (str.Contains("energy", TString::kIgnoreCase))
+        *fLog << "Energy: " << fEnergy << "GeV" << endl;
+    if (str.Contains("impact", TString::kIgnoreCase))
+        *fLog << "Impact: " << fImpact << "cm" << endl;
+}
Index: /tags/Mars-V0.9/mmc/MMcEvt.hxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcEvt.hxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcEvt.hxx	(revision 9772)
@@ -0,0 +1,245 @@
+#ifndef __MMcEvt__
+#define __MMcEvt__
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+//
+// Version 4: 
+//   Added member fFadcTimeJitter
+//
+
+class MMcEvt : public MParContainer
+{
+public:
+    //
+    //     ParticleId for Monte Carlo simulation
+    //
+    enum ParticleId_t
+    {
+        kGAMMA    =  1,
+        kPOSITRON =  2,
+        kELECTRON =  3,
+        kANTIMUON =  5,
+        kMUON     =  6,
+        kPI0      =  7,
+        kNEUTRON  = 13,
+        kPROTON =   14,
+        kHELIUM =  402,
+        kOXYGEN = 1608,
+        kIRON   = 5626
+    };
+
+private:
+  UInt_t      fEvtNumber;
+  UShort_t     fPartId;             // Type of particle
+  Float_t      fEnergy;             // [GeV] Energy
+  Float_t      fThick0;             // [g/cm2]
+  Float_t      fFirstTarget;        // []
+  Float_t      fZFirstInteraction;  // [cm]
+
+  Float_t fTheta;           // [rad] Theta angle of event 
+  Float_t fPhi;             // [rad] Phi angle of event (see class description)
+
+  Float_t fCoreD;           // [cm] Core d pos
+  Float_t fCoreX;           // [cm] Core x pos
+  Float_t fCoreY;           // [cm] Core y pos
+  Float_t fImpact;          // [cm] impact parameter
+
+  // Up to here, the info from the CORSIKA event header. 
+
+  // Telescope orientation: 
+  Float_t	fTelescopePhi;    // [rad] (see class description)
+  Float_t	fTelescopeTheta;  // [rad]
+
+  // Time of first and last photon:
+  Float_t      fTimeFirst;   // [ns]
+  Float_t      fTimeLast;    // [ns]
+
+  // 6 parameters and chi2 of the NKG fit to the longitudinal 
+  // particle distribution. See CORSIKA manual for explanation,
+  // section 4.42 "Longitudinal shower development": 
+  //
+  Float_t       fLongiNmax;   // [particles]
+  Float_t       fLongit0;     // [g/cm2]
+  Float_t       fLongitmax;   // [g/cm2]
+  Float_t       fLongia;      // [g/cm2]
+  Float_t       fLongib;      // []
+  Float_t       fLongic;      // [cm2/g]
+  Float_t       fLongichi2;
+
+  UInt_t fPhotIni;          // [ph] Initial number of photons
+  UInt_t fPassPhotAtm;      // [ph] Passed atmosphere
+  UInt_t fPassPhotRef;      // [ph] Passed reflector(reflectivity + effective area)
+  UInt_t fPassPhotCone;     // [ph]  Within any valid pixel, before plexiglas
+  UInt_t fPhotElfromShower; // [phe] Passed qe, coming from the shower
+  UInt_t fPhotElinCamera;   // [phe] usPhotElfromShower + mean of phe
+                            // from NSB
+
+  // Now follow the fraction of photons reaching the camera produced by
+  // electrons, muons and other particles respectively:
+
+  Float_t  fElecCphFraction;
+  Float_t  fMuonCphFraction;
+  Float_t  fOtherCphFraction;
+  
+  Float_t  fFadcTimeJitter;
+
+ public:
+  MMcEvt() ;
+  
+  MMcEvt( UInt_t, UShort_t, Float_t, Float_t, Float_t,
+	  Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+	  Float_t, Float_t, Float_t, Float_t, Float_t, Float_t, 
+	  Float_t, Float_t, Float_t, Float_t, Float_t, Float_t, 
+	  UInt_t, UInt_t, UInt_t, UInt_t, UInt_t, UInt_t,
+	  Float_t, Float_t, Float_t, Float_t) ; 
+  
+  ~MMcEvt(); 
+
+  void Clear(Option_t *opt=NULL);
+
+  void Fill( UInt_t, UShort_t, Float_t, Float_t, Float_t, 
+	     Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+	     Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+	     Float_t, Float_t, Float_t, Float_t, Float_t, Float_t,
+	     UInt_t, UInt_t, UInt_t, UInt_t, UInt_t, UInt_t,
+	     Float_t, Float_t, Float_t, Float_t) ; 
+
+  //virtual void AsciiWrite(ofstream &fout) const;
+
+  void Print(Option_t *opt=NULL) const;
+
+  UInt_t GetEvtNumber() const { return fEvtNumber; }  //Get Event Number
+  Short_t GetPartId() const { return fPartId; }       //Get Type of particle
+  Float_t GetEnergy() const { return fEnergy; }        //Get Energy
+
+  Float_t GetTheta() const { return fTheta; }          //Get Theta angle
+  Float_t GetPhi() const { return fPhi ;  }            //Get Phi angle
+
+/*    Float_t GetCoreD() { return fCoreD; }          //Get Core d pos */
+  Float_t GetCoreX() { return fCoreX; }          //Get Core x pos
+  Float_t GetCoreY() { return fCoreY; }          //Get Core y pos
+  Float_t GetImpact() const { return fImpact;}         //Get impact parameter 
+
+  UInt_t GetPhotIni() { return fPhotIni; }           //Get Initial photons
+  UInt_t GetPassPhotAtm() { return fPassPhotAtm;}    //Get Passed atmosphere
+  UInt_t GetPassPhotRef() { return fPassPhotRef; }   //Get Passed reflector
+  UInt_t GetPassPhotCone() { return fPassPhotCone; } //Get Passed glas
+  UInt_t GetPhotElfromShower() { return fPhotElfromShower; }   //Get Passed qe from shower
+  UInt_t GetPhotElinCamera() { return fPhotElinCamera; }   //Get Passed qe total
+  Float_t GetZFirstInteraction() const { return fZFirstInteraction; }
+
+  Float_t GetTelescopePhi() const { return fTelescopePhi; }
+  Float_t GetTelescopeTheta() const { return fTelescopeTheta; }
+  Float_t GetOtherCphFraction() const { return fOtherCphFraction; }
+
+  Float_t GetLongiNmax() const { return fLongiNmax; }
+  Float_t GetLongia()    const { return fLongia; }
+  Float_t GetLongib()    const { return fLongib; }
+  Float_t GetLongic()    const { return fLongic; }
+  Float_t GetLongichi2() const { return fLongichi2; }
+  Float_t GetLongit0()   const { return fLongit0; }
+  Float_t GetLongitmax() const { return fLongitmax; }
+
+  Float_t GetFadcTimeJitter() const { return fFadcTimeJitter; }
+
+  Float_t GetMuonCphFraction() const { return fMuonCphFraction; }
+
+  void SetPartId(Short_t PartId)
+  {fPartId=PartId;}             //Set Type of particle 
+
+  TString GetParticleName() const
+  {
+      switch (fPartId)
+      {
+      case kGAMMA:    return "Gamma";
+      case kPOSITRON: return "Positron";
+      case kELECTRON: return "Electron";
+      case kANTIMUON: return "Anti-Muon";
+      case kMUON:     return "Muon";
+      case kPI0:      return "Pi-0";
+      case kNEUTRON:  return "Neutron";
+      case kPROTON:   return "Proton";
+      case kHELIUM:   return "Helium";
+      case kOXYGEN:   return "Oxygen";
+      case kIRON:     return "Iron";
+      }
+
+      return Form("Id:%d", fPartId);
+  }
+  TString GetParticleSymbol() const
+  {
+      switch (fPartId)
+      {
+      case kGAMMA:    return "\\gamma";
+      case kPOSITRON: return "e^{+}";
+      case kELECTRON: return "e^{-}";
+      case kANTIMUON: return "\\mu^{+}";
+      case kMUON:     return "\\mu^{-}";
+      case kPI0:      return "\\pi^{0}";
+      case kNEUTRON:  return "n";
+      case kPROTON:   return "p";
+      case kHELIUM:   return "He";
+      case kOXYGEN:   return "O";
+      case kIRON:     return "Fe";
+      }
+
+      return Form("Id:%d", fPartId);
+  }
+  TString GetEnergyStr() const
+  {
+      if (fEnergy>1000)
+          return Form("%.1fTeV", fEnergy/1000);
+
+      if (fEnergy>10)
+          return Form("%dGeV", (Int_t)(fEnergy+.5));
+
+      if (fEnergy>1)
+          return Form("%.1fGeV", fEnergy);
+
+      return Form("%dMeV", (Int_t)(fEnergy*1000+.5));
+  }
+
+  void SetEnergy(Float_t Energy)
+  { fEnergy=Energy; }              //Set Energy 
+ 
+  void SetTheta(Float_t Theta) 
+  { fTheta=Theta; }                //Set Theta angle 
+
+  void SetPhi(Float_t Phi) 
+  { fPhi=Phi;  }                   //Set Phi angle 
+ 
+  void SetCoreD(Float_t CoreD) 
+  { fCoreD=CoreD; }                //Set Core d pos
+
+  void SetCoreX(Float_t CoreX)
+  { fCoreX=CoreX; }                //Set Core x pos 
+
+  void SetCoreY(Float_t CoreY ) 
+  { fCoreY=CoreY; }                //Set Core y pos
+
+  void SetImpact(Float_t Impact) 
+  { fImpact=Impact;}               //Set impact parameter
+
+  // DO NOT USE THIS IS A WORKAROUND!
+  void SetTelescopeTheta(Float_t Theta) { fTelescopeTheta=Theta; }
+  void SetTelescopePhi(Float_t Phi)     { fTelescopePhi=Phi; }
+
+  
+/*    void SetPhotIni(Short_t PhotIni)  */
+/*      { fPhotIni=PhotIni; }                 //Set Initial photons */
+/*    void SetPassPhotAtm(Short_t PassPhotAtm)  */
+/*      { fPassPhotAtm=PassPhotAtm;}         //Set Passed atmosphere */
+/*    void SetPassPhotRef(Short_t PassPhotRef)  */
+/*      { fPassPhotRef=PassPhotRef ; }       //Set Passed reflector */
+/*    void SetPassPhotCone(Short_t PhotCon)  */
+/*      { fPassPhotCone=PhotCon; }           //Set Passed glas */
+
+
+  ClassDef(MMcEvt, 4)  //Stores Montecarlo Information of one event (eg. the energy)
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mmc/MMcEvtBasic.cc
===================================================================
--- /tags/Mars-V0.9/mmc/MMcEvtBasic.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcEvtBasic.cc	(revision 9772)
@@ -0,0 +1,180 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 02/2005 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMcEvtBasic
+//
+// This class contains the most basic MonteCarlo information
+// with which an event has been generated
+//
+// Note: The azimuth fTelescopePhi angle in this and other MC classes 
+// follow the convention in the Corsika program (see Corsika manual and
+// TDAS 02-11). There, phi is the azimuth of the momentum vector of 
+// particles, and is measured from the north direction, anticlockwise 
+// (i.e, west is phi=90 degrees). When it refers to the telescope 
+// orientation, it is the azimuth of a vector along the telescope axis, 
+// going from the camera to the mirror. So, fTelescopeTheta=90, 
+// fTelescopePhi = 0 means the telescope is pointing horizontally towards 
+// South. 
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MMcEvtBasic.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MMcEvtBasic);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//  Default constructor set all values to zero
+//
+MMcEvtBasic::MMcEvtBasic()
+{    
+  fName  = "MMcEvtBasic";
+  fTitle = "Basic event info from Monte Carlo";
+
+  Clear();
+}
+
+// --------------------------------------------------------------------------
+//  constuctor II 
+//
+//  All datamembers are parameters. 
+//
+MMcEvtBasic::MMcEvtBasic(MMcEvt::ParticleId_t usPId,
+			 Float_t              fEner,
+			 Float_t              fImpa,
+			 Float_t              fTPhii,
+			 Float_t              fTThet)
+{
+  fName  = "MMcEvtBasic";
+  fTitle = "Basic event info from Monte Carlo";
+
+  fPartId         = usPId;
+  fEnergy         = fEner;
+  fImpact         = fImpa;
+  fTelescopePhi   = fTPhii;
+  fTelescopeTheta = fTThet;
+}
+
+
+// --------------------------------------------------------------------------
+//  default destructor
+//
+MMcEvtBasic::~MMcEvtBasic() {
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Reset all values. We have no "error" value for fPartId, 
+//  we just set kGAMMA
+//
+void MMcEvtBasic::Clear(Option_t *opt)
+{
+  fPartId         = MMcEvt::kGAMMA;
+  fEnergy         = -1.;
+  fImpact         = -1.;
+  fTelescopeTheta = -1.;
+  fTelescopePhi   = -1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill all data members
+//
+void MMcEvtBasic::Fill(MMcEvt::ParticleId_t usPId, 
+		       Float_t  fEner, 
+		       Float_t  fImpa, 
+		       Float_t  fTPhii,
+		       Float_t  fTThet)
+{
+  fPartId = usPId;
+  fEnergy = fEner;
+  fImpact = fImpa;
+  fTelescopePhi = fTPhii;
+  fTelescopeTheta = fTThet;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of the container.
+//
+//  if you specify an option only the requested data members are printed:
+//  allowed options are: id, energy, impact
+//
+void MMcEvtBasic::Print(Option_t *opt) const
+{
+  //
+  //  print out the data member on screen
+  //
+  TString str(opt);
+  if (str.IsNull())
+    {
+      *fLog << all << endl;
+      *fLog << "Monte Carlo output:" << endl;
+      *fLog << " Particle Id:    ";
+      switch(fPartId)
+        {
+        case MMcEvt::kGAMMA:
+	  *fLog << "Gamma" << endl;
+	  break;
+        case MMcEvt::kPROTON:
+	  *fLog << "Proton" << endl;
+	  break;
+        case MMcEvt::kHELIUM:
+	  *fLog << "Helium" << endl;
+	  break;
+	default:
+	  break;
+        }
+      *fLog << " Energy:         " << fEnergy << "GeV" << endl;
+      *fLog << " Impactpar.:     " << fImpact/100 << "m" << endl;
+      *fLog << endl;
+      return;
+    }
+  if (str.Contains("id", TString::kIgnoreCase))
+    switch(fPartId)
+      {
+      case MMcEvt::kGAMMA:
+	*fLog << "Particle: Gamma" << endl;
+	break;
+      case MMcEvt::kPROTON:
+	*fLog << "Particle: Proton" << endl;
+	break;
+      case MMcEvt::kHELIUM:
+	*fLog << "Particle: Helium" << endl;
+	break;
+      default:
+	break;
+      }
+  if (str.Contains("energy", TString::kIgnoreCase))
+    *fLog << "Energy: " << fEnergy << "GeV" << endl;
+  if (str.Contains("impact", TString::kIgnoreCase))
+    *fLog << "Impact: " << fImpact << "cm" << endl;
+}
Index: /tags/Mars-V0.9/mmc/MMcEvtBasic.h
===================================================================
--- /tags/Mars-V0.9/mmc/MMcEvtBasic.h	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcEvtBasic.h	(revision 9772)
@@ -0,0 +1,120 @@
+#ifndef __MMcEvtBasic__
+#define __MMcEvtBasic__
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#include "MMcEvt.hxx"
+
+//
+// Version 1: 
+// New container to keep the very basic informations on the
+// original MC events produced by Corsika
+//
+
+class MMcEvtBasic : public MParContainer
+{
+
+private:
+  MMcEvt::ParticleId_t fPartId;  // Type of particle
+  Float_t              fEnergy;  // [GeV] Energy
+  Float_t              fImpact;  // [cm] impact parameter
+
+  // Telescope orientation (see TDAS 02-11 regarding the 
+  // precise meaning of these angles):
+  Float_t              fTelescopePhi;    // [rad]
+  Float_t              fTelescopeTheta;  // [rad]
+
+  
+ public:
+  MMcEvtBasic();
+  
+  MMcEvtBasic(MMcEvt::ParticleId_t, Float_t, Float_t, Float_t, Float_t);
+  ~MMcEvtBasic(); 
+
+  void Clear(Option_t *opt=NULL);
+
+  void Fill(MMcEvt::ParticleId_t, Float_t, Float_t, Float_t, Float_t);
+
+  void Print(Option_t *opt=NULL) const;
+
+  MMcEvt::ParticleId_t GetPartId() const { return fPartId; }
+  Float_t GetEnergy()  const { return fEnergy; }
+  Float_t GetImpact()  const { return fImpact; }
+  Float_t GetTelescopePhi() const { return fTelescopePhi; }
+  Float_t GetTelescopeTheta() const { return fTelescopeTheta; }
+
+  TString GetParticleName() const
+  {
+      switch (fPartId)
+      {
+      case MMcEvt::kGAMMA:    return "Gamma";
+      case MMcEvt::kPOSITRON: return "Positron";
+      case MMcEvt::kELECTRON: return "Electron";
+      case MMcEvt::kANTIMUON: return "Anti-Muon";
+      case MMcEvt::kMUON:     return "Muon";
+      case MMcEvt::kPI0:      return "Pi-0";
+      case MMcEvt::kNEUTRON:  return "Neutron";
+      case MMcEvt::kPROTON:   return "Proton";
+      case MMcEvt::kHELIUM:   return "Helium";
+      case MMcEvt::kOXYGEN:   return "Oxygen";
+      case MMcEvt::kIRON:     return "Iron";
+      }
+
+      return Form("Id:%d", fPartId);
+  }
+
+  TString GetParticleSymbol() const
+  {
+      switch (fPartId)
+      {
+      case MMcEvt::kGAMMA:    return "\\gamma";
+      case MMcEvt::kPOSITRON: return "e^{+}";
+      case MMcEvt::kELECTRON: return "e^{-}";
+      case MMcEvt::kANTIMUON: return "\\mu^{+}";
+      case MMcEvt::kMUON:     return "\\mu^{-}";
+      case MMcEvt::kPI0:      return "\\pi^{0}";
+      case MMcEvt::kNEUTRON:  return "n";
+      case MMcEvt::kPROTON:   return "p";
+      case MMcEvt::kHELIUM:   return "He";
+      case MMcEvt::kOXYGEN:   return "O";
+      case MMcEvt::kIRON:     return "Fe";
+      }
+
+      return Form("Id:%d", fPartId);
+  }
+
+  TString GetEnergyStr() const
+  {
+      if (fEnergy>1000)
+          return Form("%.1fTeV", fEnergy/1000);
+
+      if (fEnergy>10)
+          return Form("%dGeV", (Int_t)(fEnergy+.5));
+
+      if (fEnergy>1)
+          return Form("%.1fGeV", fEnergy);
+
+      return Form("%dMeV", (Int_t)(fEnergy*1000+.5));
+  }
+
+
+  void SetPartId(MMcEvt::ParticleId_t id)
+    { fPartId = id; }
+
+  void SetEnergy(Float_t Energy)
+  { fEnergy=Energy; }              //Set Energy 
+ 
+  void SetImpact(Float_t Impact) 
+  { fImpact=Impact;}               //Set impact parameter
+
+  void SetTelescopeTheta(Float_t Theta) { fTelescopeTheta=Theta; }
+
+  void SetTelescopePhi  (Float_t Phi)   { fTelescopePhi=Phi; }
+
+  ClassDef(MMcEvtBasic, 1) //Stores Basic Montecarlo Information of one event
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mmc/MMcFadcHeader.cxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcFadcHeader.cxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcFadcHeader.cxx	(revision 9772)
@@ -0,0 +1,71 @@
+#include "MMcFadcHeader.hxx"
+
+#include <iostream>
+
+//==========
+// MMcFadcHeader
+//    
+// This class contains the MonteCarlo information
+// of the FADC simulation for the current run.
+// The information is saved only once, whatever the
+// number of events is
+ 
+
+
+ClassImp(MMcFadcHeader);
+
+using namespace std;
+
+
+MMcFadcHeader::MMcFadcHeader(const char *name, const char *title) {
+  //
+  //  default constructor
+
+  fName  = name  ? name  : "MMcFadcHeader";
+  fTitle = title ? title : "Fadc Header Information from Monte Carlo";
+
+  //  set all values to zero
+
+  Int_t i;
+
+  fFadcShape=0.0; 
+  fAmplFadc=MFADC_RESPONSE_INTEGRAL;
+  fFwhmFadc=MFADC_RESPONSE_FWHM;
+  fAmplFadcOuter=MFADC_RESPONSE_INTEGRAL;
+  fFwhmFadcOuter=MFADC_RESPONSE_FWHM;
+
+  for(i=0;i<MFADC_CHANNELS;i++){
+    fPedesMean[i]= 0.0    ;
+    fPedesSigmaHigh[i]=-1.0    ;
+    fPedesSigmaLow[i]=-1.0    ;
+    fElecNoise[i]=-1.0   ;
+    fDigitalNoise[i]=-1.0   ;
+  }
+}
+
+MMcFadcHeader::~MMcFadcHeader(){
+  //
+  //  default destructor
+  //
+}
+
+
+void MMcFadcHeader::Print(Option_t *Option) const {
+  //
+  //  print out the data member on screen
+  //
+  cout << endl;
+  cout << "Monte Carlo Fadc output:" << endl;
+  cout << " Shape type of the signal: "       << fFadcShape << endl;
+  cout << " FADC integral for sphe [counts*ns]: " << fAmplFadc << endl;
+  cout << " Width of the signal in nsec: "    << fFwhmFadc << endl;
+  cout << " Outer FADC integral for sphe [counts*ns]: " << fAmplFadcOuter
+       << endl;
+  cout << " Width of the signal in nsec for outer: "    << fFwhmFadcOuter 
+       << endl;
+  cout << " Pedestals and ElecNoise in fadc counts: " << endl;
+  for (int i=0;i<MFADC_CHANNELS;i++){
+    cout << " Pixel "<<i<<": "<<fPedesMean[i]<<"  "<<fElecNoise[i]<<endl;
+  }
+  cout << endl ; 
+}
Index: /tags/Mars-V0.9/mmc/MMcFadcHeader.hxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcFadcHeader.hxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcFadcHeader.hxx	(revision 9772)
@@ -0,0 +1,138 @@
+#ifndef __MMcFadcHeader__
+#define __MMcFadcHeader__
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#include "MFadcDefine.h"
+
+//
+// Version 5:
+//   Added member fGainFluctuations
+//
+// Version 6:
+//   Added member fNoiseGainFluctuations
+//
+
+class MMcFadcHeader : public MParContainer{
+ private:
+
+  Float_t  fFadcShape   ;   // a number that indicate the shape type of 
+                            // the signal   
+  Float_t  fFadcShapeOuter; // a number that indicate the shape type of 
+                            // the signal   
+                            // = 0 --> a gaussian  
+                            // = 1 --> from Pulpo set-up  
+ 
+  // NOTE : meaning of fAmplFadc, fAmplFadcOuter changed in camera 0.7, 
+  // 30/03/2004: before it was amplitude of (gaussian) pulse, now is 
+  // integral of pulse (which may be gaussian or not).
+
+  Float_t  fAmplFadc    ;   // the integral of single phe response [counts]
+  Float_t  fFwhmFadc    ;   // the width of the signal in nsec
+  Float_t  fAmplFadcOuter;  // the integral of single phe response [counts], 
+                            // outer pixels
+  Float_t  fFwhmFadcOuter;  // the width of the signal in nsec, outer
+
+  Float_t  fPedesMean[MFADC_CHANNELS]    ;  //  The mean value for the pedestal
+                                            //  of each pixel (channel)
+  Float_t  fPedesSigmaHigh[MFADC_CHANNELS]    ; //  The sigma for the pedestal
+                                                //  of each pixel (channel)
+  Float_t  fPedesSigmaLow[MFADC_CHANNELS]    ;  //  The sigma for the pedestal
+                                                //  of each pixel (channel)
+
+  // In camera 0.7, the meaning of fPedesSigmaHigh, fPedesSigmaLow changed:
+  // before it was the rms of the single FADC slice. Now we calculate the 
+  // RMS of the distribution of the sum of 14 FADC slices. The value we set 
+  // as fPedesSigmaHigh/Low is that RMS divided by sqrt(14). It can be seen
+  // that the fluctuations of the integrated pedestal, when adding n slices 
+  // to obtain the pixel signal, with n>~6, is more or less well 
+  // approximated by sqrt(n)*RMS(sum_14)slices)/sqrt(14).
+
+
+  Float_t  fElecNoise[MFADC_CHANNELS]   ;  //  The rms value in the pedestal 
+                                           //  due to the electronics for
+                                           //  each pixel (channel)
+  Float_t  fDigitalNoise[MFADC_CHANNELS];  //  The rms value in the pedestal 
+                                           //  due to the digital for
+                                           //  each pixel (channel)
+  Float_t fLow2HighGain;    // low gain factor 
+
+  Bool_t  fGainFluctuations;
+  // kTRUE if PMT gain fluctuations were simulated for the signal 
+  // (=> default in camera simulation)
+
+  Bool_t  fNoiseGainFluctuations;
+  // kTRUE if PMT gain fluctuations were simulated for the NSB noise 
+  // (=> default in StarResponse program)
+
+
+ public:
+  MMcFadcHeader(const char *name=NULL, const char *title=NULL);
+
+  ~MMcFadcHeader(); 
+
+  void Print(Option_t *opt=NULL) const;
+  
+  void SetShape(Float_t shape){
+    fFadcShape=shape;
+  }
+
+  void SetShapeOuter(Float_t shape){
+    fFadcShapeOuter=shape;
+  }
+
+  void SetLow2High(Float_t l2h){
+    fLow2HighGain=l2h;
+  }
+
+  void SetAmplitud(Float_t amp, Float_t ampout=0.0){
+    fAmplFadc=amp;
+    fAmplFadcOuter=ampout;
+ }
+
+  void SetFwhm(Float_t fwhm, Float_t fwhmout=0.0){
+    fFwhmFadc=fwhm;
+    fFwhmFadcOuter=fwhmout;
+  }
+
+  void SetPedestal(Float_t *mean, Int_t dim){
+    for (Int_t i=0;i<dim;i++)
+      fPedesMean[i]=mean[i];
+  }
+
+  void SetPedestalSigma(Float_t *sigmalo, Float_t *sigmahi, Int_t dim){
+    for (Int_t i=0;i<dim;i++){
+      fPedesSigmaLow[i]=sigmalo[i];
+      fPedesSigmaHigh[i]=sigmahi[i];
+    }
+  }
+
+  void SetElecNoise(Float_t *sigmae, Float_t *sigmad, Int_t dim){
+    for (Int_t i=0;i<dim;i++){
+      fElecNoise[i]=sigmae[i];
+      fDigitalNoise[i]=sigmad[i];
+    }
+  }
+  
+  void SetGainFluctuations(Bool_t x) { fGainFluctuations = x; }
+  void SetNoiseGainFluctuations(Bool_t x) { fNoiseGainFluctuations = x; }
+
+  Float_t GetPedestal(UInt_t i) const    { return fPedesMean[i]; }
+  Float_t GetPedestalRmsHigh(UInt_t i) const { return fPedesSigmaHigh[i]; }
+  Float_t GetPedestalRmsLow(UInt_t i) const { return fPedesSigmaLow[i]; }
+  Float_t GetElecNoise(UInt_t i) const { return fElecNoise[i]; }
+  Float_t GetDigitalNoise(UInt_t i) const { return fElecNoise[i]; }
+  Float_t GetAmplitud() const { return fAmplFadc; }
+  Float_t GetAmplitudOuter() const { return fAmplFadcOuter; }
+  Float_t GetLow2HighGain() const { return fLow2HighGain; }
+
+  UInt_t GetNumPixel() const { return MFADC_CHANNELS; }
+
+  ClassDef(MMcFadcHeader, 6)  //Stores Montecarlo Information describing the FADC behaviour
+
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mmc/MMcRunHeader.cxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcRunHeader.cxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcRunHeader.cxx	(revision 9772)
@@ -0,0 +1,248 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 (tbretz@uni-sw.gwdg.de)
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMcRunHeader
+//
+// Root storage container for the RUN MONTE CARLO HEADER information
+//
+// This the second version of this output class. Old root files, which have
+// a previous version of this class, are still compatibles and can be used.
+// But of course, you can no try to get infromatino in these old files about
+// the new data members.
+//
+// The following data member have been introduced in this second version 
+// and they do not exist in the previous one:
+//
+//  Float_t fMcRunNumber;      Run Number
+//  UInt_t  fProductionSite;   code to know where the run was generated
+//  Float_t fDateRunMMCs;      Date of the MMCs production
+//  Float_t fDateRunCamera;    Date, when the Camera program is run.
+//  Byte_t  fRawEvt;           RawEvt[Data,Hedaer] stored or not
+//  Byte_t  fElecNoise;        Electronic Noise simulated or not
+//  Byte_t  fStarFieldRotate;  Is the starfield rotation switched on (1) or
+//                             off (0)
+//  Float_t fCWaveLower;       Wavelength limits for the Cerenkov photons
+//  Float_t fCWaveUpper;
+//  UInt_t  fNumObsLev;        Observation levels
+//  Float_t fHeightLev[10];
+//  Float_t fSlopeSpec;        Spectral index
+//
+//  Third version:
+//
+//  Byte_t fOpticLinksNoise;   Flag to state if the optic noise is simualted or not
+//
+//
+// Note: All the azimuth Phi angles in this and other MC classes follow
+// the convention in the Corsika program (see Corsika manual). There, phi
+// is the azimuth of the momentum vector of particles, and is measured
+// from the north direction, anticlockwise (i.e, west is phi=90 degrees).
+//
+////////////////////////////////////////////////////////////////////////////
+
+#include "MMcRunHeader.hxx"
+
+#include <fstream>
+#include <iomanip>
+
+#include "MLog.h"
+
+ClassImp(MMcRunHeader);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+//
+MMcRunHeader::MMcRunHeader(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcRunHeader";
+    fTitle = title ? title : "Raw Run Header Information";
+
+    fMcRunNumber =0;
+    fProductionSite = 0;
+    fDateRunMMCs = 0;
+    fDateRunCamera = 0;
+    fNumTrigCond = 0;
+    fAllEvtsTriggered = 0 ;
+    fMcEvt = 0;
+    fMcTrig = 0;
+    fMcFadc = 0;
+    fRawEvt = 0;
+    fElecNoise = 0;
+    fStarFieldRotate = 0;
+    fNumAnalisedPixels = 0;
+    fNumSimulatedShowers = 0;
+    fNumStoredShowers = 0;
+    fNumEvents = 0;
+
+    fStarFieldRaH = 0;
+    fStarFieldRaM = 0;
+    fStarFieldRaS = 0;
+    fStarFieldDeD = 0;
+    fStarFieldDeM = 0;
+    fStarFieldDeS = 0;
+
+    fNumPheFromDNSB = 0.0;
+    fShowerThetaMax = 0.0;
+    fShowerThetaMin = 0.0;
+    fShowerPhiMax = 0.0;
+    fShowerPhiMin = 0.0;
+
+    fCWaveLower = 0.0;
+    fCWaveUpper = 0.0;
+
+    fNumObsLev = 0;
+    for (int i=0; i<10; i++){
+      fHeightLev[i]=0.0;
+    }
+    fSlopeSpec = 0.0;
+
+    fCorsikaVersion = 0;
+    fReflVersion = 0;
+    fCamVersion = 0;
+    fOpticLinksNoise= 0;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor.
+//
+MMcRunHeader::~MMcRunHeader()
+{
+
+}
+
+// -------------------------------------------------------------------------
+//
+// Fill. Put data in the container
+//
+void MMcRunHeader::Fill(const Float_t  runnumber,
+			const UInt_t   productionsite,
+			const Float_t  daterunMMCs,
+			const Float_t   daterunCamera,
+			const UInt_t   numtrigcond,
+			const Byte_t   allevts,
+			const Byte_t   mcevt,
+			const Byte_t   mctrig,
+			const Byte_t   mcfadc,
+			const Byte_t   rawevt,
+			const Byte_t   elecnoise, 
+			const Int_t    numanalpixels,
+			const UInt_t   numsim,
+			const UInt_t   numsto,
+			const Byte_t   starfieldrotate,
+			const Int_t    sfRaH,
+			const Int_t    sfRaM,
+			const Int_t    sfRaS,
+			const Int_t    sfDeD,
+			const Int_t    sfDeM,
+			const Int_t    sfDeS,
+			const Float_t  numdnsb,
+			const Float_t  shthetamax,
+			const Float_t  shthetamin,
+			const Float_t  shphimax,
+			const Float_t  shphimin,
+			const Float_t  impactmax,
+			const Float_t  cwavelower,
+			const Float_t  cwaveupper,
+			const Float_t  slopespec,
+			const UInt_t   numObslev,
+			const Float_t  heightlev[10],
+			const UInt_t   corsika,
+			const UInt_t   refl,
+			const UInt_t   cam,
+			const Byte_t   opticnoise)
+{
+    fMcRunNumber =runnumber;
+    fProductionSite = productionsite;
+    fDateRunMMCs = daterunMMCs;
+    fDateRunCamera = daterunCamera;
+    fNumTrigCond = numtrigcond;
+    fAllEvtsTriggered = allevts;
+    fMcEvt = mcevt;
+    fMcTrig = mctrig;
+    fMcFadc = mcfadc;
+    fRawEvt = rawevt;
+    fElecNoise = elecnoise;
+    fStarFieldRotate = starfieldrotate;
+    fNumAnalisedPixels = numanalpixels;
+    fNumSimulatedShowers = numsim;
+    fNumStoredShowers = numsto;
+    fNumEvents = numsto;
+
+    fStarFieldRaH = sfRaH;
+    fStarFieldRaM = sfRaM;
+    fStarFieldRaS = sfRaS;
+    fStarFieldDeD = sfDeD;
+    fStarFieldDeM = sfDeM;
+    fStarFieldDeS = sfDeS;
+
+    fNumPheFromDNSB = numdnsb;
+    fShowerThetaMax = shthetamax;
+    fShowerThetaMin = shthetamin;
+    fShowerPhiMax = shphimax;
+    fShowerPhiMin = shphimin;
+
+    fImpactMax=impactmax;
+
+    fCWaveLower = cwavelower;
+    fCWaveUpper = cwaveupper;
+
+    fNumObsLev = numObslev;
+    for (UInt_t i=0; i<numObslev; i++){
+      fHeightLev[i]=heightlev[i];
+    }
+    fSlopeSpec = slopespec;
+
+    fCorsikaVersion = corsika;
+    fReflVersion = refl;
+    fCamVersion = cam;
+    fOpticLinksNoise= opticnoise;
+}
+
+// -------------------------------------------------------------------------
+//
+// GetStarFieldRa. Get RA coordinates of the starfield
+//
+void MMcRunHeader::GetStarFieldRa(Int_t *hour, Int_t *minute, Int_t *second) const
+{
+    *hour   = fStarFieldRaH;
+    *minute = fStarFieldRaM;
+    *second = fStarFieldRaS;
+}
+// -------------------------------------------------------------------------
+//
+// GetStarFieldDec. Get DE coordinates of the starfield
+//
+void MMcRunHeader::GetStarFieldDec(Int_t *degree, Int_t *minute, Int_t *second) const
+{
+    *degree = fStarFieldDeD;
+    *minute = fStarFieldDeM;
+    *second = fStarFieldDeS;
+}
Index: /tags/Mars-V0.9/mmc/MMcRunHeader.hxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcRunHeader.hxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcRunHeader.hxx	(revision 9772)
@@ -0,0 +1,154 @@
+#ifndef MARS_MMcRunHeader
+#define MARS_MMcRunHeader
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MMcRunHeader                                                      //
+//                                                                   //
+// Version 5: removed members fSourceOffsetTheta, fSourceOffsetPhi   //
+//            (were no longer used)                                  //
+//                                                                   //
+// Version 6: removed members fTelesTheta, fTelesPhi                 //
+//            (were no longer used)                                  //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+
+class MMcRunHeader : public MParContainer
+{
+private:
+  UInt_t  fNumTrigCond;     // Number of trigger conditions in this file,
+  // zero means single condition mode
+  
+  //-- 0 means: MMcTrig
+  //-- 1 means: MMcTrig;1
+  //-- 2 means: MMcTrig;1 MMcTrig;2
+  
+  Byte_t  fAllEvtsTriggered;  // boolean that indicates is all images are 
+                              // saved or only the ones that trigger
+
+  Byte_t  fMcEvt;           // McEvt stored or not
+  Byte_t  fMcTrig;          // McTrig stored or not
+  Byte_t  fMcFadc;          // McFadc stored or not
+
+  Int_t   fNumAnalisedPixels;  // Number of analised pixels
+  
+  UInt_t  fNumSimulatedShowers; // Number of showers that were simualted
+  UInt_t  fNumStoredShowers;    // Number of store showers in this run
+  UInt_t  fNumEvents;           // Number of events in this root file
+  
+  //  Coordinates of the Starfield
+  
+  Int_t fStarFieldRaH;
+  Int_t fStarFieldRaM;
+  Int_t fStarFieldRaS;
+  Int_t fStarFieldDeD;
+  Int_t fStarFieldDeM;
+  Int_t fStarFieldDeS;
+
+  Float_t fNumPheFromDNSB;  // Number of phe/ns from diffuse NSB
+  
+  //  Angular range used in the Corsika showers generation (degrees)
+  Float_t fShowerThetaMax; // [deg]
+  Float_t fShowerThetaMin; // [deg]
+  Float_t fShowerPhiMax; // [deg] See note in class description.
+  Float_t fShowerPhiMin; // [deg] See note in class description.
+
+  //  Maximum impact parameter in the input rfl file
+  Float_t fImpactMax; // [cm] 
+
+  UShort_t fCorsikaVersion;
+  UShort_t fReflVersion;
+  UShort_t fCamVersion;
+
+  /* ---- Run Header Informations ---- */
+  Float_t fMcRunNumber;     // Run Number
+  UInt_t  fProductionSite;  // code to know where the run was generated
+  Float_t fDateRunMMCs;     // Date of the MMCs production
+  Float_t fDateRunCamera;   // Date, when the Camera program is run.
+
+  Byte_t  fRawEvt;          // RawEvt[Data,Hedaer] stored or not
+
+  Byte_t  fElecNoise;       // Electronic Noise simulated or not
+  Byte_t  fStarFieldRotate; // Is the starfield rotation 
+                            // switched on (1) or off (0)
+
+  //  Wavelength limits for the Cerenkov photons
+  Float_t fCWaveLower;
+  Float_t fCWaveUpper;
+
+  //  Observation levels  
+  UInt_t    fNumObsLev;
+  Float_t   fHeightLev[10]; 
+
+  //  Spectral index
+  Float_t   fSlopeSpec;
+
+  // Noise from Optic Links
+  Byte_t  fOpticLinksNoise;  // Noise from Optic Links simualted or not.
+
+public:
+  MMcRunHeader(const char *name=NULL, const char *title=NULL);
+  ~MMcRunHeader();
+
+  void Fill(const Float_t  runnumber,
+	    const UInt_t   productionsite,
+	    const Float_t  daterunMMCs,
+	    const Float_t   daterunCamera,
+	    const UInt_t   numtrigcond,
+	    const Byte_t   allevts,
+	    const Byte_t   mcevt,
+	    const Byte_t   mctrig,
+	    const Byte_t   mcfadc,
+	    const Byte_t   rawevt,
+	    const Byte_t   elecnoise, 
+	    const Int_t    numanalpixels,
+	    const UInt_t   numsim,
+	    const UInt_t   numsto,
+	    const Byte_t   starfieldrotate,
+	    const Int_t    sfRaH,
+	    const Int_t    sfRaM,
+	    const Int_t    sfRaS,
+	    const Int_t    sfDeD,
+	    const Int_t    sfDeM,
+	    const Int_t    sfDeS,
+	    const Float_t  numdnsb,
+	    const Float_t  shthetamax,
+	    const Float_t  shthetamin,
+	    const Float_t  shphimax,
+	    const Float_t  shphimin,
+	    const Float_t  impactmax,
+	    const Float_t  cwavelower,
+	    const Float_t  cwaveupper,
+	    const Float_t  slopespec,
+	    const UInt_t   num0bslev,
+	    const Float_t  heightlev[10],
+	    const UInt_t   corsika,
+	    const UInt_t   refl,
+	    const UInt_t   cam,
+	    const Byte_t   opticnoise 
+	    );
+  
+  void     GetStarFieldRa(Int_t *hour, Int_t *minute, Int_t *second) const;
+  void     GetStarFieldDec(Int_t *degree, Int_t *minute, Int_t *second) const;
+
+  Float_t  GetNumPheFromDNSB() const      { return fNumPheFromDNSB; }
+  UShort_t GetCamVersion() const          { return fCamVersion; }
+  UShort_t GetReflVersion() const         { return fReflVersion; }
+  UInt_t   GetNumSimulatedShowers() const { return fNumSimulatedShowers; }
+  UInt_t   GetCorsikaVersion() const      { return fCorsikaVersion; }
+  Bool_t   GetAllEvtsTriggered() const    { return fAllEvtsTriggered ? kTRUE : kFALSE; }
+
+  Float_t  GetShowerThetaMin() const { return fShowerThetaMin; } 
+  Float_t  GetShowerThetaMax() const { return fShowerThetaMax; } 
+
+  Float_t GetImpactMax() const            {return fImpactMax;}
+
+  ClassDef(MMcRunHeader, 6)	// storage container for general run info
+};
+#endif
+
+
Index: /tags/Mars-V0.9/mmc/MMcTrig.cxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcTrig.cxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcTrig.cxx	(revision 9772)
@@ -0,0 +1,141 @@
+#include "MMcTrig.hxx"
+
+#include <iostream>
+
+
+//==========
+// MMcTrig
+//    
+// This class handles and contains the MonteCarlo information
+// with which the events have been generated
+// This information exists for each event.
+//
+// This the second version of this output class. Old root files, which have
+// a previous version of this class, are still compatibles and can be used.
+// But of course, you can no try to get infromatino in these old files about
+// the new data members.
+//
+// The fPixelsFirst array has been increased from 273 (which was the trigger 
+// zone) to 577 (which is the full Camera)
+//
+////////////////////////////////////////////////////////////// 
+
+
+ClassImp(MMcTrig);
+
+using namespace std;
+
+
+MMcTrig::MMcTrig(const char *name, const char *title) {
+  //
+  //  default constructor
+  //  set all values to zero
+
+  
+  fName  = name  ? name  : "MMcTrig";
+  fTitle = title ? title : "Trigger info from Monte Carlo";
+
+    
+  Int_t i,j;
+
+  fNumFirstLevel  = 0 ;
+
+  for(i=0;i<TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME+1;i++){
+    fTimeFirst[i]    = -99.9;
+    for(j=0;j<CAMERA_PIXELS/8+1;j++){
+      fPixelsFirst[j][i]   = 0;
+    }
+  }
+
+  fNumSecondLevel = 0 ; 
+  for(i=0;i<TOTAL_TRIGGER_TIME/LEVEL2_DEAD_TIME+1;i++){
+    fFirstToSecond[i]=0;
+  }
+}
+
+MMcTrig::~MMcTrig() {
+  //
+  //  default destructor
+  //
+}
+
+void MMcTrig::SetTime(Float_t t, Int_t i)
+{
+    if (i>TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME+1  || i<1)
+    {
+        cout << "fNumFirstLevel out of range. Time will be -99" << endl;
+        return;
+    }
+
+    fTimeFirst[i-1]=t;
+}
+
+void MMcTrig::Clear(Option_t *opt) {
+  //
+  //  
+  //  reset all values to zero
+  Int_t i,j;
+
+  fNumFirstLevel  = 0 ;
+  for(i=0;i<TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME+1;i++){
+    fTimeFirst[i]    = -99.9;
+    for(j=0;j<CAMERA_PIXELS/8+1;j++){
+      fPixelsFirst[j][i]   = 0;
+    }
+  }
+
+  fNumSecondLevel = 0 ; 
+  for(i=0;i<TOTAL_TRIGGER_TIME/LEVEL2_DEAD_TIME+1;i++){
+    fFirstToSecond[i]=0;
+  }
+
+  //  cout << "MMcTrig::Clear() " << endl ; 
+}
+
+void MMcTrig::Print(Option_t *option) const
+{
+    //
+    //  print out the data member on screen
+    //
+    cout << "Monte Carlo Trigger output:" << endl;
+    cout << " First Level Trigger in this Event: " << fNumFirstLevel << endl;
+    if (!TString(option).Contains("short"))
+    {
+        cout << " Times of first Level Trigger in this Event: ";
+        for (int i=0; i<fNumFirstLevel; i++)
+            cout << fTimeFirst[i] << " ";
+        cout << endl;
+
+        cout << " Pixels of first  Level Trigger in this Event: ";
+        for (int i=0; i<fNumFirstLevel; i++)
+            for(int j=0; j<CAMERA_PIXELS/8+1; j++)
+                cout << (int)fPixelsFirst[j][i] << " ";
+        cout << endl;
+    }
+
+    cout << " Second Level Trigger in this Event: " << fNumSecondLevel << endl;
+    cout << endl;
+}
+
+Byte_t MMcTrig::IsPixelFired(Int_t npix, Int_t nfirstlevel){
+  //======================================================================
+  //
+  //  It returns >1 if the pixel npix was fired when the nfirstlevel
+  //  first level trigger happened, 0 if not.
+  //
+  
+  const Int_t  body=npix/8;
+  const Byte_t reminder= 1<<(npix%8);
+
+  return reminder&fPixelsFirst[body][nfirstlevel];
+  /*
+  Byte_t ret=0;
+  Byte_t reminder;
+  Int_t body;
+
+  body=npix/8;
+  reminder=(Byte_t)(pow(2,npix%8));
+  ret=reminder&fPixelsFirst[body][nfirstlevel];
+  return(ret);
+  */
+}
Index: /tags/Mars-V0.9/mmc/MMcTrig.hxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcTrig.hxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcTrig.hxx	(revision 9772)
@@ -0,0 +1,67 @@
+#ifndef __MMcTrig__
+#define __MMcTrig__
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#include "MTriggerDefine.h"
+#include "Mdefine.h"
+
+class MMcTrig : public MParContainer {
+ private:
+
+  Short_t fNumFirstLevel  ;    // Number of First Level Trigger in this Event
+  Short_t fNumSecondLevel ;    // Number of Second Level Trigger in this Event
+
+  Float_t fTimeFirst[((Int_t)(TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME))+1];
+                            // Time when it triggers
+  Byte_t fPixelsFirst[((Int_t)(CAMERA_PIXELS/8))+1][((Int_t)(TOTAL_TRIGGER_TIME/LEVEL1_DEAD_TIME))+1];
+                            // Pixel which are above threshold when trigger happens
+  Short_t fFirstToSecond[((Int_t)(TOTAL_TRIGGER_TIME/LEVEL2_DEAD_TIME))+1];
+
+ public:
+  MMcTrig(const char *name=NULL, const char *title=NULL);
+
+  ~MMcTrig(); 
+
+  void Clear(Option_t *opt=NULL);
+  
+  void Print(Option_t *opt=NULL) const;
+
+  void SetFirstLevel  ( Short_t nTr ) {
+    fNumFirstLevel = nTr ; 
+  } 
+  void SetSecondLevel ( Short_t nTr ) {
+    fNumSecondLevel = nTr ; 
+  } 
+
+  void SetTime( Float_t t, Int_t i);
+
+  void SetMapPixels(Byte_t *map,Int_t nfirst){
+    //  
+    //  It sets the map of pixel that are above the trheshold
+    //
+
+    int i;
+
+    for(i=0;i<((Int_t)(CAMERA_PIXELS/8))+1;i++){
+      fPixelsFirst[i][nfirst]=map[i];
+    }
+  }
+
+  Int_t GetFirstLevel() const {
+    return ( fNumFirstLevel );  
+  }
+
+  Int_t GetNumFirstLevel() const {
+    return ( fNumFirstLevel );  
+  }
+
+  Byte_t IsPixelFired(Int_t npix, Int_t nfirstlevel);
+
+  ClassDef(MMcTrig, 3)  //Stores Montecarlo Information (number of 1st, 2nd level triggers)
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mmc/MMcTrigHeader.cxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcTrigHeader.cxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcTrigHeader.cxx	(revision 9772)
@@ -0,0 +1,74 @@
+#include "MMcTrigHeader.hxx"
+
+#include <iostream>
+
+
+//==========
+// MMcTrigHeader
+//    
+// This class contains the MonteCarlo information
+// of the trigger simulation for the current run.
+// The information is saved only once, whatever the
+// number of events is
+//
+// This is the second version of this output class. Old root files, which have
+// a previous version of this class, are still compatibles and can be used.
+// But of course, you can no try to get infromatino in these old files about
+// the new data members.
+//
+// The following data member have been introduced in this second version 
+// and they do not exist in the previous one:
+//
+//   Float_t  fElecNoiseTrig;  The width of the gaussian noise is that times
+//                             the amplitude of the single phe response 
+//                             for the trigger 
+//
+/////////////////////////
+
+ClassImp(MMcTrigHeader);
+
+using namespace std;
+
+
+MMcTrigHeader::MMcTrigHeader() {
+  //
+  //  default constructor
+  //  set all values to zero
+
+  Int_t i;
+
+  fTopology     = -1 ;
+  fMultiplicity = -1 ;
+  for(i=0;i<CAMERA_PIXELS;i++){
+    fThreshold[i] = -1.0;
+  }
+  
+  fTrigPattern[0]=0;
+  fTrigPattern[1]=0;
+
+  fTrigShape=0.0; 
+  fAmplTrig=RESPONSE_AMPLITUDE;
+  fFwhmTrig=RESPONSE_FWHM;
+  fOverlapingTime=TRIGGER_OVERLAPING;
+  fGateLeng=TRIGGER_GATE ;
+}
+
+MMcTrigHeader::~MMcTrigHeader() {
+  //
+  //  default destructor
+  //
+}
+
+
+void MMcTrigHeader::Print(Option_t *opt) const {
+  //
+  //  print out the data member on screen
+  //
+  cout << endl;
+  cout << "Monte Carlo Trigger output:" << endl;
+  cout << " XSTopology Trigger in this run: "   << fTopology << endl;
+  cout << " Multiplicity Trigger in this run: " << fMultiplicity << endl;
+  cout << " Trigger Pattern in this run: ";
+  cout << fTrigPattern[0] << ", " << fTrigPattern[1] << endl;
+  cout << endl; 
+}
Index: /tags/Mars-V0.9/mmc/MMcTrigHeader.hxx
===================================================================
--- /tags/Mars-V0.9/mmc/MMcTrigHeader.hxx	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MMcTrigHeader.hxx	(revision 9772)
@@ -0,0 +1,132 @@
+#ifndef __MMcTrigHeader__
+#define __MMcTrigHeader__
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#include "MTriggerDefine.h"
+#include "Mdefine.h"
+
+//
+// Version 4
+//   Added data members fGainFluctuations and fNoiseGainFluctuations
+//
+
+class MMcTrigHeader : public MParContainer{
+ private:
+
+  Short_t fTopology     ;      // Topology of the trigger
+                                   // 0 = N-1 neighbours of one pixel
+                                   // 1 = N neighbours
+                                   // 2 = N closed pack
+  Short_t fMultiplicity ;      // Pixel multiplicity of trigger configuration
+  Float_t fThreshold[CAMERA_PIXELS] ; // Threshold for trigger
+  UInt_t fTrigPattern[2];     // Used to inddentify with 
+                              // RawEvt::Trigger Pattern identification  
+  Float_t  fTrigShape   ;   // a number that indicate the shape type of 
+                            // the signal   
+                            // = 0 --> a gaussian  
+  Float_t  fAmplTrig    ;   // the amplitude of the trigger in mV
+  Float_t  fFwhmTrig    ;   // the width of the signal in nsec
+  Float_t  fOverlapingTime;// Minimum coincidence time
+  Float_t  fGateLeng;       // the length of the digital signal if analog 
+                            // signal is above threshold
+  Float_t  fElecNoiseTrig;  // The width of the gaussian noise is that times
+                            // the amplitude of the single phe response 
+                            // for the trigger
+
+  Bool_t  fGainFluctuations;
+  // kTRUE if PMT gain fluctuations were simulated for the signal 
+  // (=> default in camera simulation)
+
+  Bool_t  fNoiseGainFluctuations;
+  // kTRUE if PMT gain fluctuations were simulated for the NSB noise 
+  // (=> default in StarResponse program)
+
+
+ public:
+  MMcTrigHeader() ;
+
+  ~MMcTrigHeader(); 
+
+  void Print(Option_t *opt=NULL) const;
+  
+  void SetTopology(Short_t nTop) {
+    fTopology=nTop;
+  }
+
+  void SetMultiplicity(Short_t nMul) {
+    fMultiplicity=nMul;
+  }
+
+  void SetThreshold(Float_t fthr[]){
+    int i;
+    for(i=0;i<CAMERA_PIXELS;i++){
+      fThreshold[i]=fthr[i];
+    }
+  }
+
+  void SetTrigPattern (UInt_t upi, UInt_t loi){
+
+    if (upi==loi==0) {
+      fTrigPattern[0]= (UInt_t) fThreshold[0];
+      fTrigPattern[1]= (UInt_t) (100*fMultiplicity+fTopology);
+    }
+    else {
+      fTrigPattern[0]=upi;
+      fTrigPattern[1]=loi;
+    }
+  }
+
+  void SetShape(Float_t shape){
+    fTrigShape=shape;
+  }
+
+  void SetAmplitud(Float_t amp){
+    fAmplTrig=amp;
+ }
+
+  void SetFwhm(Float_t fwhm){
+    fFwhmTrig=fwhm;
+  }
+
+  void SetOverlap(Float_t overlap){
+    fOverlapingTime=overlap;
+  }
+
+  void SetGate(Float_t gate){
+    fGateLeng=gate;
+  }
+
+  void SetElecNoise( Float_t elecnoise){
+    fElecNoiseTrig = elecnoise;
+  }
+
+  void SetGainFluctuations(Bool_t x) { fGainFluctuations = x; }
+  void SetNoiseGainFluctuations(Bool_t x) { fNoiseGainFluctuations = x; }
+
+  Short_t GetMultiplicity() { return fMultiplicity; }
+
+  Float_t GetMeanThreshold()
+  {
+    int i;
+    Float_t sum = 0., trigpix = 0.;
+    for(i=0;i<CAMERA_PIXELS;i++)
+    {
+      if (fThreshold[i] < 1.e6 && fThreshold[i] > 0.)
+      {
+        sum += fThreshold[i];
+        trigpix += 1.;
+      }
+    }
+
+    return (sum / trigpix);
+  }
+
+
+  ClassDef(MMcTrigHeader, 4)  //Stores Montecarlo Information which describes the used trigger
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mmc/MTriggerDefine.h
===================================================================
--- /tags/Mars-V0.9/mmc/MTriggerDefine.h	(revision 9772)
+++ /tags/Mars-V0.9/mmc/MTriggerDefine.h	(revision 9772)
@@ -0,0 +1,108 @@
+//
+//
+//      In this file are the fundamental definitions for the class MCTrigger
+//
+//
+#define TRIGGER_PIXELS_1      397
+#define TRIGGER_PIXELS_2      397
+#define TRIGGER_PIXELS_3      1657
+#define TRIGGER_PIXELS_5      397
+#define TRIGGER_PIXELS_6      1657
+#define TRIGGER_PIXELS_8      126
+#define TRIGGER_PIXELS_9      126
+//
+//      This is the number of Pixels contributing to the TRIGGER logic
+//      for each of the already implemented geometries.
+//      All Pixels-Id above that value don't do an trigger stuff. 
+//      Actually, not all of them are involved in TRIGGER logic, only the
+//      ones of them that are also in some TRIGGER_CELL 
+//   (MagicSoft/Simulation/Detector/include-MTrigger/TABLE_PIXELS_IN_CELLS)
+//
+#define TOTAL_TRIGGER_TIME    160 
+//
+//      This values defines the total range in that we try to find
+//      a trigger. 
+//
+#define LEVEL1_DEAD_TIME    50
+//
+//      Dead time of the detector after one first level trigger happens.
+//
+#define LEVEL2_DEAD_TIME    300
+//
+//      Dead time of the detector after second level trigger fires
+//
+#define TRIG_SLICES_PER_NSEC         4
+//      
+//      Each nano second is divided into the number of this values slices. 
+//      So you can get the total number of timeslices for one Pixel by 
+//      ( TOTAL_TRIGGER_TIME * SLICES_PER_NSEC ). 
+//      In the current settings this are 1000 slices
+//
+#define TRIGGER_TIME_SLICES     (TOTAL_TRIGGER_TIME*TRIG_SLICES_PER_NSEC) 
+//
+//
+//
+//
+//       ------>>>   SETTINGS for the RESPONSE FUNCTION
+// 
+#define RESPONSE_SLICES_TRIG        40
+//
+//       This is the dimension of the array containing the standard response Signal 
+//       for 1 Photoelectron, as seen at the input of the discriminators (for the 
+//       trigger simulation). Each bin corresponds to 1./TRIG_SLICES_PER_NSEC nanoseconds,
+//       so by default it is 0.25 ns and hence the total range is 10 ns. This should be 
+//       enough for any reasonable single photoelectron response (should be much narrower 
+//       than 10 ns!)
+//
+
+//       The Response function
+//       These values are discussed with Eckart. We start from this point. 
+//
+#define RESPONSE_FWHM          2. 
+
+#define RESPONSE_AMPLITUDE     1. 
+//
+//       This are the Standard values of the response function for
+//       1 photo electron. ( 1 means 1 mV per photoelectron ) 
+//
+//
+//       -------->>> SETTINGS for the DISKRIMINATORS
+//
+//
+#define CHANNEL_THRESHOLD      2.5 
+//
+//       This is the diskriminator threshold for each individual channel
+//       First we set the value to 2 unit of the RESPONSE_AMPLITUDE 
+//
+#define TRIGGER_GATE           3. 
+// 
+//       Here we set the width of the digital signal we get if the signal
+//       passes the diskriminator
+//
+//
+#define TRIGGER_OVERLAPING           0.25 
+// 
+//       Here we set the required overlaping time among pixels
+//       to be in coincidence.
+//
+//
+//      --------->>>> SETTINGS for the TRIGGER logic
+//
+//
+#define TRIGGER_CELLS          19  
+//
+//       Number of trigger cells that cover the trigger zone
+//
+#define TRIGGER_MULTI          4.  
+//
+//       We get a Level Zero Trigger, if we have a least TRIGGER_MULTI
+//       channels with a diskrimiator signal at the same time 
+//
+#define TRIGGER_GEOM           0
+//
+//      This defines the geometry required for a trigger. There exists 
+//      different meaning for this behaviour: 
+//         0 means a pixel with trigger_multi-1 neighbours
+//         1 means trigger_multi neighbours
+//         2 means trigger_multi closed neighbours
+//
Index: /tags/Mars-V0.9/mmc/Makefile
===================================================================
--- /tags/Mars-V0.9/mmc/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mmc/Makefile	(revision 9772)
@@ -0,0 +1,32 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I.  -I../mbase -I../MBase -I../mgeom
+
+CINT     = Mc
+
+SRCFILES = MMcTrigHeader.cxx \
+	   MMcFadcHeader.cxx \
+	   MMcRunHeader.cxx \
+	   MMcEvt.cxx \
+           MMcTrig.cxx \
+	   MMcConfigRunHeader.cc \
+	   MMcCorsikaRunHeader.cc \
+	   MMcEvtBasic.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules 
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mmc/McIncl.h
===================================================================
--- /tags/Mars-V0.9/mmc/McIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mmc/McIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mmc/McLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mmc/McLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mmc/McLinkDef.h	(revision 9772)
@@ -0,0 +1,16 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+ 
+#pragma link C++ class MMcEvt+;
+#pragma link C++ class MMcEvtBasic+;
+#pragma link C++ class MMcTrig+;
+#pragma link C++ class MMcRunHeader+;
+#pragma link C++ class MMcTrigHeader+;
+#pragma link C++ class MMcFadcHeader+;
+#pragma link C++ class MMcConfigRunHeader+;
+#pragma link C++ class MMcCorsikaRunHeader+;
+
+#endif
Index: /tags/Mars-V0.9/mmc/Mdefine.h
===================================================================
--- /tags/Mars-V0.9/mmc/Mdefine.h	(revision 9772)
+++ /tags/Mars-V0.9/mmc/Mdefine.h	(revision 9772)
@@ -0,0 +1,38 @@
+//
+//     Mdefine.h
+//
+//     defines some Values for the MAGIC telecope
+//
+
+//     Number of the Pixels in the Camera
+
+#define     CAMERA_PIXELS         3500
+
+//     Number of the Slices of one Fadc. Be carefull this is the number of 
+//     slices for one gain branch. We sample two times this number. 
+
+//     ParticleId for Monte Carlo simulation
+
+#define  GAMMA 0
+#define  PROTON 14
+#define  HELIUM 402
+#define  OXIGEN 1608
+#define  IRON 5626
+
+
+//---------------------------------------------------------
+// definition of constants
+
+#define TRUE 1
+#define FALSE 0
+
+//camera dimensions and definitions
+#define PIXEL_SIZE  0.00175  // radians
+#define PIXEL_DIST  10.0  //cm
+#define CAMERA_COLOR 13   //Background light grey
+#define DEFAULT_COLOR 1 //black
+//#define TRACK_WALL_COLOR 7   //light blue
+#define PIXEL_LINE_COLOR 15 //dark grey
+#define COLORTABLE_START 18 //Begin of colortable
+#define MAX_PH_EL 500 //upper limit for colortable
+
Index: /tags/Mars-V0.9/mmc/readme.txt
===================================================================
--- /tags/Mars-V0.9/mmc/readme.txt	(revision 9772)
+++ /tags/Mars-V0.9/mmc/readme.txt	(revision 9772)
@@ -0,0 +1,6 @@
+
+ Please be aware of that this subdirectory is used in two CVS modules.
+ 
+ If you change something it can affect the Mars and/or Monte Carlo
+ code!
+ 
Index: /tags/Mars-V0.9/mmontecarlo/MMcCollectionAreaCalc.cc
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcCollectionAreaCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcCollectionAreaCalc.cc	(revision 9772)
@@ -0,0 +1,170 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer  1/2001
+!   Author(s): Abelardo Moralejo 2/2005 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMcCollectionAreaCalc
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MMcCollectionAreaCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcEvtBasic.h"
+
+#include "MMcRunHeader.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+#include "MHMcCollectionArea.h"
+
+ClassImp(MMcCollectionAreaCalc);
+
+using namespace std;
+
+////////////////////////////////////////////////////////////////////////////////
+//
+//  Constructor
+//
+MMcCollectionAreaCalc::MMcCollectionAreaCalc(const char *name, const char *title): 
+  fBinsTheta(0), fBinsEnergy(0), fSpectrum(0)
+{
+    fName  = name  ? name  : "MMcCollectionAreaCalc";
+    fTitle = title ? title : "Task to calculate the collection area";
+} 
+
+////////////////////////////////////////////////////////////////////////////////
+//
+// PreProcess. 
+// Create MHMcCollectionArea object if necessary. 
+// Search in parameter list for MBinning objects with binning in theta and E.
+// These contain the coarse binning to be used in the analysis. Then search 
+// for other necessary input containers: 
+// if MMcEvt is found, it means we are in the loop over the Events tree, 
+// and so we must fill the histogram MHMcCollectionArea::fHistSel (using 
+// MHMcCollectionArea::FillSel). If MMcEvt is not found, it means that we are in 
+// the loop over the "OriginalMC" tree, containing all the original Corsika events 
+// produced, and hence we must fill the histogram  fHistAll through 
+// MHMcCollectionArea::FillAll.
+//
+Int_t MMcCollectionAreaCalc::PreProcess (MParList *pList)
+{
+  fCollArea = (MHMcCollectionArea*)pList->FindCreateObj("MHMcCollectionArea");
+
+  // Look for the binnings of the histograms if they have not been already
+  // found in a previous loop.
+
+  if (!fBinsTheta)
+    {
+      fBinsTheta = (MBinning*) pList->FindObject("binsTheta");
+      if (!fBinsTheta)
+	{
+	  *fLog << err << "Coarse Theta binning not found... Aborting." 
+	    << endl;
+	  return kFALSE;
+	}
+    }
+
+  if (!fBinsEnergy)
+    {
+      fBinsEnergy = (MBinning*) pList->FindObject("binsEnergy");
+      if (!fBinsEnergy)
+	{
+	  *fLog << err << "Coarse Energy binning not found... Aborting." 
+		<< endl;
+	  return kFALSE;
+	}
+    }
+
+  fCollArea->SetCoarseBinnings(*fBinsEnergy, *fBinsTheta);
+
+
+  // Look for the input containers
+
+  fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+  if (fMcEvt)
+    {
+        *fLog << inf << "MMcEvt found... I will fill MHMcCollectionArea.fHistSel..." << endl;
+	return kTRUE;
+    }
+
+  *fLog << inf << "MMcEvt not found... looking for MMcEvtBasic..." << endl;
+
+
+  fMcEvtBasic = (MMcEvtBasic*) pList->FindObject("MMcEvtBasic");
+    
+  if (fMcEvtBasic)
+    {
+      *fLog << inf << "MMcEvtBasic found... I will fill MHMcCollectionArea.fHistAll..." << endl;
+      return kTRUE;
+    }
+
+  *fLog << err << "MMcEvtBasic not found. Aborting..." << endl;
+
+  return kFALSE;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+//
+// Process. Depending on whether fMcEvt or fMcEvtBasic are available, fill 
+// MHMcCollectionArea::fHistAll, else, if fMcEvt is available, fill 
+// MHMcCollectionArea::fHistSel
+//
+Int_t MMcCollectionAreaCalc::Process()
+{
+    Double_t energy = fMcEvt? fMcEvt->GetEnergy() : fMcEvtBasic->GetEnergy();
+    Double_t impact = fMcEvt? fMcEvt->GetImpact()/100. : fMcEvtBasic->GetImpact()/100.; // in m
+    Double_t theta  = fMcEvt? fMcEvt->GetTelescopeTheta()*TMath::RadToDeg() : 
+      fMcEvtBasic->GetTelescopeTheta()*TMath::RadToDeg(); // in deg
+
+    if (fMcEvt)
+      fCollArea->FillSel(energy, impact, theta);
+    else
+      fCollArea->FillAll(energy, impact, theta);
+
+    return kTRUE;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+//
+// Postprocess. If both fHistAll and fHistSel are already filled, calculate
+// effective areas. Else it means we still have to run one more loop.
+//
+Int_t MMcCollectionAreaCalc::PostProcess()
+{
+  if ( ((TH2D*)fCollArea->GetHistAll())->GetEntries() > 0 &&
+       ((TH2D*)fCollArea->GetHistSel())->GetEntries() > 0)
+    {
+      *fLog << inf << "Calculation Collection Area..." << endl;
+      fCollArea->Calc(fSpectrum);
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mmontecarlo/MMcCollectionAreaCalc.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcCollectionAreaCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcCollectionAreaCalc.h	(revision 9772)
@@ -0,0 +1,51 @@
+#ifndef MARS_MMcCollectionAreaCalc
+#define MARS_MMcCollectionAreaCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#include <TH2.h>
+#include <TF1.h>
+
+class MParList;
+class MMcEvt;
+class MMcEvtBasic;
+class MMcTrig;
+class MHMcCollectionArea;
+class MBinning;
+
+class MMcCollectionAreaCalc : public MTask
+{
+private:
+    const MMcEvt       *fMcEvt;
+    const MMcEvtBasic  *fMcEvtBasic;
+    const MMcTrig      *fMcTrig;
+
+    MBinning           *fBinsTheta;
+    MBinning           *fBinsEnergy;
+    // Coarse zenith angle and energy bins used in the analysis
+
+    TF1                *fSpectrum; 
+    // Tentative energy spectrum. This modifies slightly the calculation
+    // of the effective area (see MHMcCollectionArea::Calc)
+
+
+    MHMcCollectionArea *fCollArea;
+
+    TString fObjName;
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MMcCollectionAreaCalc(const char *name = NULL, const char *title = NULL);
+
+    void SetSpectrum(TF1 *f) { fSpectrum = f; }
+
+    ClassDef(MMcCollectionAreaCalc, 0) // Task to calculate the collection area histogram
+};
+
+#endif 
+
Index: /tags/Mars-V0.9/mmontecarlo/MMcEnergyEst.cc
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcEnergyEst.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcEnergyEst.cc	(revision 9772)
@@ -0,0 +1,350 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  1/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek 1/2002 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Abelardo Moralejo 4/2003 <mailto:moralejo@pd.infn.it>
+!   Author(s): Marcos Lopez 5/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMcEnergyEst
+//
+// Class for otimizing the parameters of the energy estimator
+//
+// FIXME: the class must be made more flexible, allowing for different
+// parametrizations to be used. Also a new class is needed, a container
+// for the parameters of the energy estimator.
+// FIXME: the starting values of the parameters are now fixed.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcEnergyEst.h"
+
+#include <math.h>            // fabs on Alpha
+
+#include <TMinuit.h>
+#include <TStopwatch.h>
+#include <TVirtualFitter.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MGeomCamCT1.h"
+#include "MFEventSelector.h"
+#include "MReadTree.h"
+#include "MFCT1SelFinal.h"
+#include "MHMatrix.h"
+#include "MEnergyEstParam.h"
+#include "MMatrixLoop.h"
+#include "MChisqEval.h"
+#include "MEvtLoop.h"
+#include "MDataElement.h"
+#include "MDataMember.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParameters.h"
+
+ClassImp(MMcEnergyEst);
+
+using namespace std;
+
+//------------------------------------------------------------------------
+//
+// fcn calculates the function to be minimized (using TMinuit::Migrad)
+//
+static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    MEvtLoop *evtloop = (MEvtLoop*)gMinuit->GetObjectFit();
+
+    MParList  *plist  = evtloop->GetParList();
+    MTaskList *tlist = (MTaskList*)plist->FindObject("MTaskList");
+ 
+
+    // Pass current minuit parameters to the energy estimation class 
+    MEnergyEstParam *eest = (MEnergyEstParam*)tlist->FindObject("MEnergyEstParam");
+    eest->SetCoeff(TArrayD(eest->GetNumCoeff(), par));
+
+    
+    evtloop->Eventloop();
+
+
+    // Get result of the ChiSquare 
+    MParameterD *eval = (MParameterD*)plist->FindObject("MFitResult", "MParameterD");
+    
+    f = eval->GetVal();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMcEnergyEst::MMcEnergyEst(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcEnergyEst";
+    fTitle = title ? title : "Optimizer of the energy estimator";
+
+    SetHillasName("MHillas");
+    SetHillasSrcName("MHillasSrc");
+
+    //
+    // Set initial values of the parameters (close enough to the final 
+    // ones, taken from previous runs of the procedure). Parameter 
+    // fA[4] is not used in the default energy estimation model (from 
+    // D. Kranich).
+    //
+    fA.Set(5);
+    fB.Set(7);
+
+    fA[0] =  21006.2;
+    fA[1] = -43.2648;
+    fA[2] = -690.403;
+    fA[3] = -0.0428544;
+    fA[4] =  1.;
+    fB[0] = -3391.05;
+    fB[1] =  136.58;
+    fB[2] =  0.253807;
+    fB[3] =  254.363;
+    fB[4] =  61.0386;
+    fB[5] = -0.0190984;
+    fB[6] = -421695;
+}
+
+Bool_t MMcEnergyEst::SetCoeff(TArrayD &coeff)
+{
+  if (coeff.GetSize() != fA.GetSize()+fB.GetSize())
+    {
+      *fLog << err << dbginf << "Wrong number of parameters!" << endl;
+      return(kFALSE);
+    }
+
+  for (Int_t i = 0; i < fA.GetSize(); i++)
+    fA[i] = coeff[i];
+  for (Int_t i = 0; i < fB.GetSize(); i++)
+    fB[i] = coeff[i+fA.GetSize()];
+
+  return(kTRUE);
+
+}
+
+//------------------------------------------------------------------------
+//
+// Optimization (via migrad minimization) of parameters of energy estimation.
+//
+void MMcEnergyEst::FindParams()
+{
+  MParList parlist;
+
+  MFEventSelector selector;
+  selector.SetNumSelectEvts(fNevents);
+  *fLog << inf << "Read events from file '" << fInFile << "'" << endl;    
+
+  MReadTree read("Events");
+  read.AddFile(fInFile);
+  read.DisableAutoScheme();
+  read.SetSelector(&selector);
+
+  *fLog << inf << "Define columns of matrix" << endl;
+  MHMatrix matrix;
+  Int_t colenergy = matrix.AddColumn("MMcEvt.fEnergy");
+  Int_t colimpact = matrix.AddColumn("MMcEvt.fImpact");
+
+  if (colenergy < 0  ||  colimpact < 0)
+  {
+    *fLog << err << dbginf << "colenergy, colimpact = " << colenergy << ",  " 
+	  << colimpact << endl;
+    return;
+  }
+
+  MEnergyEstParam eest(fHillasName);
+  eest.Add(fHillasSrcName);
+  eest.InitMapping(&matrix);
+  
+  *fLog << inf << "--------------------------------------" << endl;
+  *fLog << inf << "Fill events into the matrix" << endl;
+  if ( !matrix.Fill(&parlist, &read, fEventFilter) )
+    return;
+  *fLog << inf << "Matrix was filled with " << matrix.GetNumRows() 
+	<< inf << " events" << endl;  
+
+  //-----------------------------------------------------------------------
+  //
+  // Setup the eventloop which will be executed in the fcn of MINUIT 
+  //
+  *fLog << inf << "--------------------------------------" << endl;
+  *fLog << inf << "Setup event loop to be used in 'fcn'" << endl;
+
+  MTaskList tasklist;
+
+  MMatrixLoop loop(&matrix);
+
+  MChisqEval eval;
+  eval.SetY1(new MDataElement(&matrix, colenergy));
+  eval.SetY2(new MDataMember("MEnergyEst.fEnergy"));
+  eval.SetOwner();
+
+  //
+  // Entries in MParList
+
+  parlist.AddToList(&tasklist);
+
+  //
+  // Entries in MTaskList
+
+  tasklist.AddToList(&loop);
+  tasklist.AddToList(&eest);
+  tasklist.AddToList(&eval);
+
+
+  *fLog << inf << "Event loop was setup" << endl;
+  MEvtLoop evtloop;
+  evtloop.SetParList(&parlist);
+
+  //
+  //----------   Start of minimization part   -------------------- 
+  //
+  // Do the minimization with MINUIT
+  //
+  // Be careful: This is not thread safe
+  //
+  *fLog << inf << "--------------------------------------" << endl;
+  *fLog << inf << "Start minimization for the energy estimator" << endl;
+
+  gMinuit = new TMinuit(12);
+  gMinuit->SetPrintLevel(-1);
+
+  gMinuit->SetFCN(fcn);
+  gMinuit->SetObjectFit(&evtloop);
+
+  // Ready for: gMinuit->mnexcm("SET ERR", arglist, 1, ierflg)
+
+  if (gMinuit->SetErrorDef(1))
+    {
+      *fLog << err << dbginf << "SetErrorDef failed." << endl;
+      return;
+    }
+
+  //
+  // Set starting values and step sizes for parameters
+  //
+  for (Int_t i=0; i<fA.GetSize(); i++)
+    {
+      TString name = "fA[";
+      name += i;
+      name += "]";
+      Double_t vinit = fA[i];
+      Double_t step  = fabs(fA[i]/3);
+
+      Double_t limlo = 0; // limlo=limup=0: no limits
+      Double_t limup = 0; 
+
+      Bool_t rc = gMinuit->DefineParameter(i, name, vinit, step, limlo, limup);
+      if (!rc)
+	continue;
+
+      *fLog << err << dbginf << "Error in defining parameter #" << i << endl;
+      return;
+    }
+
+  for (Int_t i=0; i<fB.GetSize(); i++)
+    {
+      TString name = "fB[";
+      name += i;
+      name += "]";
+      Double_t vinit = fB[i];
+      Double_t step  = fabs(fB[i]/3);
+
+      Double_t limlo = 0; // limlo=limup=0: no limits
+      Double_t limup = 0;
+
+      Bool_t rc = gMinuit->DefineParameter(i+fA.GetSize(), name, vinit, step, limlo, limup);
+      if (!rc)
+	continue;
+
+      *fLog << err << dbginf << "Error in defining parameter #" << i+fA.GetSize() << endl;
+      return;
+    }
+
+  TStopwatch clock;
+  clock.Start();
+
+  // Now ready for minimization step:
+
+  gLog.SetNullOutput(kTRUE);
+  Bool_t rc = gMinuit->Migrad();
+  gLog.SetNullOutput(kFALSE);
+  
+  if (rc)
+    {
+      *fLog << err << dbginf << "Migrad failed." << endl;
+      return;
+    }
+
+  *fLog << inf << endl;
+  clock.Stop();
+  clock.Print();
+  *fLog << inf << endl;
+
+  *fLog << inf << "Resulting Chisq: " << gMinuit->fAmin << endl;
+
+  //
+  // Update values of fA, fB:
+  //
+  for (Int_t i = 0; i < fA.GetSize(); i++)
+    {
+      Double_t x1, x2;
+      gMinuit->GetParameter(i,x1,x2);
+      fA[i] = x1;
+    }
+  for (Int_t i = fA.GetSize(); i < fA.GetSize()+fB.GetSize(); i++)
+    {
+      Double_t x1, x2;
+      gMinuit->GetParameter(i,x1,x2);
+      fB[i-fA.GetSize()] = x1;
+    }
+
+  //    eest.Print();
+  eest.StopMapping();
+  *fLog << inf << "Minimization for the energy estimator finished" << endl;
+
+}
+
+//------------------------------------------------------------------------
+//
+// Print current values of parameters
+//
+void MMcEnergyEst::Print(Option_t *o) const
+{
+  for (Int_t i = 0; i < fA.GetSize(); i++)
+    *fLog << inf << "Parameter " << i << ": " << const_cast<TArrayD&>(fA)[i] << endl;
+
+  for (Int_t i = fA.GetSize(); i < fA.GetSize()+fB.GetSize(); i++)
+    *fLog << inf << "Parameter " << i << ": " << const_cast<TArrayD&>(fB)[i-fA.GetSize()] << endl;
+
+  /*
+    // Print results
+    Double_t amin, edm, errdef;
+    Int_t nvpar, nparx, icstat;
+    gMinuit->mnstat(amin, edm, errdef, nvpar, nparx, icstat);
+    gMinuit->mnprin(3, amin);
+  */
+
+}
Index: /tags/Mars-V0.9/mmontecarlo/MMcEnergyEst.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcEnergyEst.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcEnergyEst.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MMcEnergyEst
+#define MARS_MMcEnergyEst
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#include "MFilter.h"
+
+class MMcEnergyEst : public MParContainer
+{
+private:
+
+  TString fInFile, fOutFile;
+  TString fHillasName;
+  TString fHillasSrcName;
+  Int_t   fNevents;
+
+  MFilter *fEventFilter; //!
+
+  TArrayD fA;
+  TArrayD fB;
+
+public:
+  MMcEnergyEst(const char *name=NULL, const char *title=NULL);
+
+  void SetInFile(const TString &name)         {fInFile = name;}
+  void SetOutFile(const TString &name)        {fOutFile = name;}
+  void SetHillasName(const TString &name)     {fHillasName = name;}
+  void SetHillasSrcName(const TString &name)  {fHillasSrcName = name;}
+  void SetEventFilter(MFilter *filter)        {fEventFilter = filter;}
+  void SetNevents(Int_t n)                    {fNevents = n;}
+
+  TString GetInFile()         const {return fInFile;}
+  TString GetOutFile()        const {return fOutFile;}
+  TString GetHillasName()     const {return fHillasName;}
+  TString GetHillasSrcName()  const {return fHillasSrcName;}
+  Int_t   GetNevents()        const {return fNevents;}
+
+  Int_t   GetNumCoeffA()      const {return fA.GetSize(); }
+  Int_t   GetNumCoeffB()      const {return fB.GetSize(); }
+
+  Double_t GetCoeff(Int_t i) { return i<fA.GetSize()? fA[i] : fB[i-fA.GetSize()]; }
+
+  Bool_t SetCoeff(TArrayD &coeff);
+
+  void FindParams();
+  void Print(Option_t *o="") const;
+
+  ClassDef(MMcEnergyEst, 1) // Class for optimization of Energy estimator
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mmontecarlo/MMcThresholdCalc.cc
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcThresholdCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcThresholdCalc.cc	(revision 9772)
@@ -0,0 +1,185 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 05/2001 <mailto:jlopez@ifae.es>
+!   Author(s): Thomas Bretz 06/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+//  MMcThresholdCalc
+//                                                                         
+//  Input Containers:
+//   MMcEvt, MMcTrig;*
+//
+//  Output Containers:
+//   MHMcEnergies
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MMcThresholdCalc.h"
+
+#include <math.h>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+
+#include "MHMcEnergy.h"
+
+ClassImp(MMcThresholdCalc);
+
+using namespace std;
+
+const Float_t MMcThresholdCalc::fSqrt2 = sqrt(2.);
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor.
+//
+// Specify the number of trigger conditions you want to use.
+// The default is 0.
+//
+// dim < 0: use only condition number dim (eg "MMcTrig;3")
+// dim = 0: use only condition without a number ("MMcTrig")
+// dim > 0: use conditions up to dim (from "MMcTrig;1" to "MMcTrig;dim")
+//
+MMcThresholdCalc::MMcThresholdCalc(const Int_t dim, const char* name,
+                                   const char* title)
+    : fMcTrig(NULL), fEnergy(NULL)
+{
+    fName  = name  ? name  : "MMcThresholdCalc";
+    fTitle = title ? title : "Task to calculate the energy threshold from Monte Carlo";
+
+    fFirst = dim>0 ?   1 : -dim;
+    fLast  = dim>0 ? dim : -dim;
+
+    fNum = fLast-fFirst+1;
+
+    AddToBranchList("MMcEvt.fEnergy");
+    AddToBranchList("MMcTrig", "fNumFirstLevel", fFirst, fLast);
+}
+
+// -------------------------------------------------------------------------
+//
+// Destructor.
+//
+MMcThresholdCalc::~MMcThresholdCalc()
+{
+    if (fMcTrig)
+        delete fMcTrig;
+
+    if (fEnergy)
+        delete fEnergy;
+}
+
+// --------------------------------------------------------------------------
+//
+// connect Monte Carlo data with this task
+//
+Int_t MMcThresholdCalc::PreProcess(MParList* pList)
+{
+    //
+    // This task takes into accout if the root file has one trigger
+    // condition (MMcTrig) or severl of them (MMcTrig;#.)
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    UInt_t num;
+
+    fMcTrig = new TObjArray(pList->FindObjectList("MMcTrig", fFirst, fLast));
+    num = fMcTrig->GetEntriesFast();
+    if (num != fNum)
+    {
+        *fLog << err << dbginf << fNum << " MMcTrig objects requested, ";
+        *fLog << num << " are available... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEnergy = new TObjArray(pList->FindCreateObjList("MHMcEnergy", fFirst, fLast));
+    num = fMcTrig->GetEntriesFast();
+    if (num != fNum)
+    {
+        *fLog << err << dbginf << fNum << " MHMcEnergy objects requested, ";
+        *fLog << num << " are available... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The histograms are filled with log10 of the energy for triggered
+// events and weighted with 1/E because it is needed the dN/dE vs. logE
+// distribution to get the energy threshold.
+//
+Int_t MMcThresholdCalc::Process()
+{
+    const Float_t energy   = fMcEvt->GetEnergy();
+    const Float_t lg10     = log10(energy);
+    const Float_t reciproc = 1./energy;
+
+    for (UInt_t i=0; i<fNum; i++)
+        if (GetTrig(i)->GetFirstLevel()>0)
+            GetHEnergy(i)->Fill(lg10, reciproc);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// fit the energy distribution to get the threshold
+// Some iterations are done to be sure the fit parameters converge.
+//
+Int_t MMcThresholdCalc::PostProcess()
+{
+    for (UInt_t i=0; i<fNum; i++)
+    {
+        MHMcEnergy &hist = *GetHEnergy(i);
+
+        Float_t peak;
+        Float_t sigma;
+
+        hist.Fit(1, 3);
+
+        peak  = hist.GetGaussPeak();
+        sigma = hist.GetGaussSigma();
+        hist.Fit(peak - 2.   *sigma, peak + 2.   *sigma);
+
+        peak  = hist.GetGaussPeak();
+        sigma = hist.GetGaussSigma();
+        hist.Fit(peak - fSqrt2*sigma, peak + fSqrt2*sigma);
+
+        hist.SetReadyToSave();
+    }
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mmontecarlo/MMcThresholdCalc.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcThresholdCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcThresholdCalc.h	(revision 9772)
@@ -0,0 +1,56 @@
+#ifndef MARS_MMcThresholdCalc
+#define MARS_MMcThresholdCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MMcThresholdCalc                                                        //
+//                                                                         //
+// Compute the energy threshold from Monte Carlo data                      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MMcEvt;
+class MMcTrig;
+class MHMcEnergy;
+
+class MMcThresholdCalc : public MTask
+{
+private:
+    UInt_t fFirst;
+    UInt_t fLast;
+
+    UInt_t fNum;
+
+    const MMcEvt  *fMcEvt;       // Container with Monte Carlo information
+
+    TObjArray    *fMcTrig;       // Container with Monte Carlo trigger information
+    TObjArray    *fEnergy;       // Container where we save the energy (threshold)
+
+    const static Float_t fSqrt2; // sqrt(2)
+
+    MMcTrig    *GetTrig   (UInt_t i) { return (MMcTrig*)   (*fMcTrig)[i]; }
+    MHMcEnergy *GetHEnergy(UInt_t i) { return (MHMcEnergy*)(*fEnergy)[i]; }
+
+    Int_t PreProcess(MParList* pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MMcThresholdCalc(const Int_t dim = 0,
+                     const char* name = NULL, const char* title = NULL);
+    ~MMcThresholdCalc();
+
+    ClassDef(MMcThresholdCalc, 0) // Task to compute the energy threshold
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/mmontecarlo/MMcTimeGenerate.cc
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcTimeGenerate.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcTimeGenerate.cc	(revision 9772)
@@ -0,0 +1,90 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+#include "MMcTimeGenerate.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTime.h"
+
+ClassImp(MMcTimeGenerate);
+
+// --------------------------------------------------------------------------
+//
+MMcTimeGenerate::MMcTimeGenerate(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcTimeGenerate";
+    fTitle = title ? title : "Task to generate a random event time";
+
+    const Double_t lambda = 100; // [Hz]
+
+    fFunc = new TF1("Poisson", "[0] * exp(-[0]*x)", 0, 1);
+    fFunc->SetParameter(0, lambda);
+
+    fDeadTime = 0.1/lambda;
+}
+
+MMcTimeGenerate::~MMcTimeGenerate()
+{
+    delete fFunc;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  The PreProcess connects the raw data with this task. It checks if the 
+//  input containers exist, if not a kFalse flag is returned. It also checks
+//  if the output contaniers exist, if not they are created.
+//  This task can read either Montecarlo files with multiple trigger
+//  options, either Montecarlo files with a single trigger option.
+//
+Int_t MMcTimeGenerate::PreProcess (MParList *pList)
+{
+    // connect the raw data with this task
+
+    fTime = (MTime*)pList->FindCreateObj("MTime");
+    if (!fTime)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MMcTimeGenerate::Process()
+{
+    Double_t dt;
+
+    do dt = fFunc->GetRandom();
+    while (dt < fDeadTime);
+
+#warning SetTime not valid anymore!
+//    fTime->SetTime(*fTime+dt/1e4); // [0.1ms]
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mmontecarlo/MMcTimeGenerate.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcTimeGenerate.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcTimeGenerate.h	(revision 9772)
@@ -0,0 +1,33 @@
+#ifndef MARS_MMcTimeGenerate
+#define MARS_MMcTimeGenerate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef ROOT_TF1
+#include "TF1.h"
+#endif
+
+class MParList;
+class MTime;
+
+class MMcTimeGenerate : public MTask
+{
+private:
+    MTime    *fTime;        //!
+    TF1      *fFunc;        //!
+
+    Double_t fDeadTime;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MMcTimeGenerate(const char *name=NULL, const char *title=NULL);
+
+    ~MMcTimeGenerate();
+
+    ClassDef(MMcTimeGenerate, 0) // To generate a random time
+};
+
+#endif 
Index: /tags/Mars-V0.9/mmontecarlo/MMcTriggerRateCalc.cc
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcTriggerRateCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcTriggerRateCalc.cc	(revision 9772)
@@ -0,0 +1,433 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Modified 4/7/2002 Abelardo Moralejo: now the dimension of fTrigger is
+//  set dinamically, to allow an arbitrary large number of trigger
+//  conditions to be processed.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcTriggerRateCalc.h"
+
+#include <math.h>
+
+#include <TCanvas.h>
+#include <TGraphErrors.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+#include "MMcRunHeader.hxx"
+#include "MMcTrigHeader.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+#include "MH.h"
+#include "MHMcRate.h"
+
+ClassImp(MMcTriggerRateCalc);
+
+using namespace std;
+
+void MMcTriggerRateCalc::Init(int dim, float *trigbg, float simbg,
+                              const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcTriggerRateCalc";
+    fTitle = title ? title : "Task to calc the trigger rate ";
+
+    fMcTrig = NULL;
+    fMcRate = NULL;
+
+    fTrigNSB = trigbg;
+    fSimNSB = simbg;
+
+    fPartId = -1; 
+
+    fShowers = 0;
+    fAnalShow = 0;
+
+    fFirst = dim>0 ?   1 : -dim;
+    fLast  = dim>0 ? dim : -dim;
+
+    fNum = fLast-fFirst+1;
+    fTrigger = new float[fNum];
+
+    for (UInt_t i=0;i<fNum;i++)
+      fTrigger[i]=0;
+
+    AddToBranchList("MMcEvt.fPartId");
+    AddToBranchList("MMcEvt.fImpact");
+    AddToBranchList("MMcEvt.fEnergy");
+    AddToBranchList("MMcEvt.fPhi");
+    AddToBranchList("MMcEvt.fTheta");
+    AddToBranchList("MMcEvt.fPhotElfromShower");
+    AddToBranchList("MMcTrig", "fNumFirstLevel", fFirst, fLast);
+
+}
+
+// ReInit: read run header to get some info later:
+
+Bool_t MMcTriggerRateCalc::ReInit(MParList *pList)
+{
+    fMcRunHeader = (MMcRunHeader*) pList->FindObject("MMcRunHeader");
+    if (!fMcRunHeader)
+    {
+        *fLog << err << dbginf << "Error - MMcRunHeader not found... exit." << endl;
+        return kFALSE;
+    }
+
+    fMcCorRunHeader = (MMcCorsikaRunHeader*) pList->FindObject("MMcCorsikaRunHeader");
+    if (!fMcCorRunHeader)
+    {
+        *fLog << err << dbginf << "Error - MMcCorsikaRunHeader not found... exit." << endl;
+        return kFALSE;
+    }
+
+    fShowers += fMcRunHeader->GetNumSimulatedShowers();
+
+    if (fMcRunHeader->GetAllEvtsTriggered())
+      {
+          *fLog << warn;
+          *fLog << "WARNING - the input data file contains only the" << endl;
+          *fLog << "events that triggered. I will assume the standard value" << endl;
+          *fLog << "for maximum impact parameter (400 m)" <<endl;
+
+
+          if (fTrigNSB[0] > 0)
+          {
+              *fLog << warn;
+              *fLog << "WARNING - NSB rate can be overestimated by up to 5%." << endl;
+              *fLog << "For a precise estimate of the total rate including NSB" << endl;
+              *fLog << "accidental triggers I need a file containing all event headers." << endl;
+          }
+          else
+          {
+            *fLog << warn << "WARNING - calculating only shower rate (no NSB accidental triggers)" << endl;
+          }
+      }
+
+    *fLog << endl << warn <<
+      "WARNING: I will assume the standard maximum off axis angle" << endl <<
+      "(5 degrees) for the original showers" << endl;
+
+
+    for (UInt_t i=0; i<fNum; i++)
+      {
+	if (fMcRunHeader->GetAllEvtsTriggered())
+	  {
+	    GetRate(i)->SetImpactMin(0.);
+	    GetRate(i)->SetImpactMax(40000.);   // in cm
+	  }
+	GetRate(i)->SetSolidAngle(2.390941702e-2);  // sr
+
+	//
+	// Set limits of energy range, coverting from GeV to TeV:
+	//
+	GetRate(i)->SetEnergyMin(fMcCorRunHeader->GetELowLim()/1000.);
+	GetRate(i)->SetEnergyMax(fMcCorRunHeader->GetEUppLim()/1000.);
+
+        TString th("MMcTrigHeader");
+	if (GetRate(i)->GetTriggerCondNum() > 0)
+	  {
+	    th += ";";
+	    th += GetRate(i)->GetTriggerCondNum();
+	  }
+
+	MMcTrigHeader* trighead = (MMcTrigHeader*) pList->FindObject(th);
+	GetRate(i)->SetMeanThreshold(trighead->GetMeanThreshold());
+	GetRate(i)->SetMultiplicity(trighead->GetMultiplicity());
+
+      }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  overloaded constructor I
+//
+//      dim:     fDimension
+//      *trigbg: number of NSB triggers for
+//               a given trigger condition.
+//      simbg:   Number of simulated events for the NSB
+//      rate:    rate of incident showers
+//
+MMcTriggerRateCalc::MMcTriggerRateCalc(float rate, int dim,
+                                       float *trigbg, float simbg,
+                                       const char *name, const char *title)
+{
+    Init(dim, trigbg, simbg, name, title);
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  overloaded constructor II
+//
+//      dim:     fDimension
+//      *trigbg: number of NSB triggers for
+//               a given trigger condition.
+//      simbg:   Number of simulated events for the NSB
+//
+MMcTriggerRateCalc::MMcTriggerRateCalc(int dim, float *trigbg,float simbg,
+                                       const char *name, const char *title)
+{
+    Init(dim, trigbg, simbg, name, title);
+}
+
+MMcTriggerRateCalc::~MMcTriggerRateCalc()
+{
+    if (fMcTrig)
+        delete fMcTrig;
+
+    if (fMcRate)
+        delete fMcRate;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  The PreProcess connects the raw data with this task. It checks if the 
+//  input containers exist, if not a kFalse flag is returned. It also checks
+//  if the output contaniers exist, if not they are created.
+//  This task can read either Montecarlo files with multiple trigger
+//  options, either Montecarlo files with a single trigger option.
+//
+Int_t MMcTriggerRateCalc::PreProcess (MParList *pList)
+{
+    // connect the raw data with this task
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    UInt_t num;
+
+    fMcTrig = new TObjArray(pList->FindObjectList("MMcTrig", fFirst, fLast));
+    num = fMcTrig->GetEntriesFast();
+    if (num != fNum)
+    {
+        *fLog << err << dbginf << fNum << " MMcTrig objects requested, ";
+        *fLog << num << " are available... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcRate = new TObjArray(pList->FindObjectList("MHMcRate", fFirst, fLast));
+    num = fMcRate->GetEntriesFast();
+    if (num != fNum)
+    {
+        *fLog << err << dbginf << fNum << " MHMcRate objects requested, ";
+        *fLog << num << " are available... aborting." << endl;
+        return kFALSE;
+    }
+
+    for (UInt_t i=0;i<fNum;i++)
+      {
+        MHMcRate &rate = *GetRate(i);
+
+	if (fTrigNSB)
+	  rate.SetBackground(fTrigNSB[i], fSimNSB);
+	else
+	  rate.SetBackground(0., fSimNSB);
+      }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  The Process-function counts the number of simulated showers, the
+//  number of analised showers and the number of triggers. It also updates
+//  the limits for theta, phi, energy and impact parameter in the
+//  MHMcRate container.
+//
+Int_t MMcTriggerRateCalc::Process()
+{
+    //
+    //  Counting analysed showers (except in the case in which the file 
+    //  contains only events that triggered, since then we do not know
+    //  how many showers were analysed).
+    //
+
+    if ( ! fMcRunHeader->GetAllEvtsTriggered() &&
+	 fMcEvt->GetPhotElfromShower() )
+      fAnalShow++;
+
+    //
+    // Set PartId and check it is the same for all events
+    //
+    if (fPartId < 0)
+      fPartId = fMcEvt->GetPartId();
+    else if (fPartId != fMcEvt->GetPartId())
+      {
+	*fLog << err << dbginf << "Incident particle type seems to change";
+	*fLog << "from " << fPartId << " to " << fMcEvt->GetPartId() << endl;
+	*fLog << "in input data files... aborting." << endl;
+	return kFALSE;
+      }
+
+    //
+    //  Getting angles, energy and impact parameter to set boundaries
+    //
+    const Float_t theta = fMcEvt->GetTheta();
+    const Float_t phi   = fMcEvt->GetPhi();
+    const Float_t param = fMcEvt->GetImpact();
+    const Float_t ener  = fMcEvt->GetEnergy()/1000.0;
+
+    //
+    //  Counting number of triggers
+    //
+    for (UInt_t i=0; i<fNum; i++)
+    {
+	if (GetTrig(i)->GetFirstLevel())
+	    fTrigger[i] ++; 
+
+	if ( ! fMcRunHeader->GetAllEvtsTriggered())
+	  GetRate(i)->UpdateBoundaries(ener, theta, phi, param);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  The PostProcess-function calculates and shows the trigger rate
+//
+Int_t MMcTriggerRateCalc::PostProcess()
+{
+    for (UInt_t i=0; i<fNum; i++)
+    {
+        MHMcRate &rate = *GetRate(i);
+
+        rate.SetParticle(fPartId);
+        switch (fPartId)
+        {
+        case MMcEvt::kPROTON:
+	  if ((Int_t)floor(-100*fMcCorRunHeader->GetSlopeSpec()+0.5) != 275)
+	    {
+                *fLog << err << "Spectrum slope as read from input file (";
+                *fLog << fMcCorRunHeader->GetSlopeSpec() << ") does not match the expected ";
+                *fLog << "one (-2.75) for protons" << endl << "... aborting." << endl;
+                return kFALSE;
+            }
+	  rate.SetFlux(0.1091, 2.75);
+	  break;
+        case MMcEvt::kHELIUM:
+	  if ((Int_t)floor(-100*fMcCorRunHeader->GetSlopeSpec()+0.5) != 262)
+	    {
+                *fLog << err << "Spectrum slope as read from input file (";
+                *fLog << fMcCorRunHeader->GetSlopeSpec() << ") does not match the expected ";
+                *fLog << "one (-2.62) for Helium" << endl << "... aborting." << endl;
+                return kFALSE;
+	    }
+	  rate.SetFlux(0.0660, 2.62);
+	  break;
+        default:
+	  *fLog << err << "Unknown incident flux parameters for ";
+	  *fLog << fPartId<< " particle Id ... aborting." << endl;
+	  return kFALSE;
+	}
+    }
+
+    //
+    // Computing trigger rate
+    //
+    for (UInt_t i=0; i<fNum; i++)
+        GetRate(i)->CalcRate(fTrigger[i], fAnalShow, fShowers);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw rate as a funtion of discriminator threshold.
+//
+void MMcTriggerRateCalc::Draw(Option_t *)
+{
+    /*
+     Commented out, because this is creating a memory leak!
+     The histograms are neither deleted anywhere, nor it is made
+     sure, that the histograms are not overwritten.
+     Also the comment for the function doesn't match the rules.
+     BTW: please replace all arrays by Root lists (TArray*, TList, etc)
+  TCanvas *c = MH::MakeDefCanvas("Rate");
+
+  Float_t xmin = GetRate(0)->GetMeanThreshold()-0.55;
+  Float_t xmax = GetRate(fNum-1)->GetMeanThreshold()+0.55;
+  Int_t  nbins = (Int_t)((xmax-xmin)*10);
+
+  fHist[1] = new TH1F("Rate2","Trigger rate, mult. 2", nbins, xmin, xmax);
+  fHist[2] = new TH1F("Rate3","Trigger rate, mult. 3", nbins, xmin, xmax);
+  fHist[3] = new TH1F("Rate4","Trigger rate, mult. 4", nbins, xmin, xmax);
+  fHist[4] = new TH1F("Rate5","Trigger rate, mult. 5", nbins, xmin, xmax);
+
+  for (UInt_t i=0; i<fNum; i++)
+    {
+      Short_t mult = GetRate(i)->GetMultiplicity();
+
+      fHist[mult-1]->SetBinContent(fHist[mult-1]->FindBin(GetRate(i)->GetMeanThreshold()), GetRate(i)->GetTriggerRate());
+
+      fHist[mult-1]->SetBinError(fHist[mult-1]->FindBin(GetRate(i)->GetMeanThreshold()), GetRate(i)->GetTriggerRateError());
+    }
+
+  for (Int_t i = 1; i <=4; i++)
+    {
+      fHist[i]->SetLineWidth(2);
+      fHist[i]->SetMarkerStyle(20);
+      fHist[i]->SetMarkerSize(.5);
+    }
+
+  c->DrawFrame (xmin, 0.5*GetRate(fNum-1)->GetTriggerRate(), xmax, 1.2*GetRate(0)->GetTriggerRate(), "Trigger rate for multiplicity = 3, 4, 5");
+
+  c->SetLogy();
+  c->SetGridy();
+  c->SetGridx();
+
+  fHist[2]->SetLineColor(1);
+  fHist[2]->SetMarkerColor(1);
+  fHist[2]->SetMinimum(0.5*GetRate(fNum-1)->GetTriggerRate());
+  fHist[2]->GetXaxis()->SetTitle("Discr. threshold (mV)");
+  fHist[2]->GetYaxis()->SetTitle("Trigger rate (Hz)");
+  fHist[2]->GetYaxis()->SetTitleOffset(1.2);
+  fHist[2]->Draw("axis");
+  fHist[2]->Draw("same");
+
+  fHist[3]->SetLineColor(3);
+  fHist[3]->SetMarkerColor(3);
+  fHist[3]->Draw("same");
+
+  fHist[4]->SetLineColor(4);
+  fHist[4]->Draw("same");
+  fHist[4]->SetMarkerColor(4);
+     */
+}
+
Index: /tags/Mars-V0.9/mmontecarlo/MMcTriggerRateCalc.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcTriggerRateCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcTriggerRateCalc.h	(revision 9772)
@@ -0,0 +1,73 @@
+#ifndef MARS_MMcTriggerRateCalc
+#define MARS_MMcTriggerRateCalc
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MMcEvt;
+class MMcRunHeader;
+class MMcCorsikaRunHeader;
+class MMcTrig;
+class MHMcRate;
+class TH1F;
+
+class MMcTriggerRateCalc : public MTask
+{
+private:
+    MMcEvt    *fMcEvt;     //!
+
+    TObjArray *fMcRate;
+    TObjArray *fMcTrig;
+
+    MMcRunHeader *fMcRunHeader; 
+    MMcCorsikaRunHeader *fMcCorRunHeader; 
+
+    UInt_t     fNum;       // decoded dimension
+    UInt_t     fFirst;
+    UInt_t     fLast;
+
+    Float_t   *fTrigNSB;   // Number of triggers due to NSB alone
+    Float_t    fSimNSB;    // Number of simulated NSB-only events
+
+    Float_t   *fTrigger;   // Number of triggered showers
+    Float_t    fShowers;   // Number of simulated showers
+    Float_t    fAnalShow;  // Number of analysed showers
+
+    Int_t      fPartId;    // Incident particle that generates showers
+
+    TH1F      *fHist[5];
+
+    void Init(int dim, float *trigbg,
+              float simbg, const char *name, const char *title);
+
+    MHMcRate *GetRate(UInt_t i) const { return (MHMcRate*)((*fMcRate)[i]); }
+    MMcTrig  *GetTrig(UInt_t i) const { return (MMcTrig*)((*fMcTrig)[i]); }
+
+    Bool_t ReInit(MParList *plist);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MMcTriggerRateCalc(int dim=0, float *trigbg=NULL, float simbg=100000,
+                       const char *name=NULL, const char *title=NULL);
+
+    MMcTriggerRateCalc(float rate, int dim, float *trigbg, float simbg,
+                       const char *name=NULL, const char *title=NULL);
+
+    ~MMcTriggerRateCalc();
+
+    TH1F* GetHist(Int_t i) {return fHist[i];}
+
+    void Draw(const Option_t *o="");
+
+    ClassDef(MMcTriggerRateCalc, 0)	// Task to compute the trigger rate
+};
+
+#endif 
Index: /tags/Mars-V0.9/mmontecarlo/MMcUnfoldCoeffCalc.cc
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcUnfoldCoeffCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcUnfoldCoeffCalc.cc	(revision 9772)
@@ -0,0 +1,206 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico 2/2005 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMcUnfoldCoeffCalc
+//  Task to compute the coefficients for energy unfolding (to be used 
+//  typically in an iterative process).
+//
+//  Input containers:
+//   MMcEvt
+//   MMcEvtBasic
+//   MEnergyEst
+//   binsTheta  [MBinning]
+//   binsEnergy [MBinning]
+//
+//  Output containers:
+//   MHMcUnfoldCoeff
+//
+//  The binning for energy and theta are looked in the parameter list
+//  The tentative spectrum MUST be provided using SetSpectrum, otherwise
+//  it is used for default pow(energy,-1.6) [~Crab at 1 TeV]
+//
+//  This task is supposed to be in a two-looped macro/program: 
+//  In the first one MMcEvtBasic is read in order to compute the 
+//  weights to convert from original to tentative spectrum.
+//  In the second one MMcEvt and MEnergyEst are read and fill the 
+//  MC and estimated energy that are divided in the postprocess to
+//  compute the coefficients
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "TF1.h"
+
+#include "MMcUnfoldCoeffCalc.h"
+#include "MHMcUnfoldCoeff.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcEvtBasic.h"
+#include "MEnergyEst.h"
+
+ClassImp(MMcUnfoldCoeffCalc);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+//  Constructor
+//
+MMcUnfoldCoeffCalc::MMcUnfoldCoeffCalc(const char* name, const char* title) :
+  fSpectrum(NULL)
+{
+  fName  = name  ? name  : "MMcUnfoldCoeffCalc";
+  fTitle = title ? title : "Task to calculate the unfolding coefficients";
+} 
+
+// -------------------------------------------------------------------------
+//
+// PreProcess. 
+// Create MHMcUnfoldCoeff object if necessary. Search for other necessary 
+// containers: if MMcEvt is found, it means we are in the loop over the Events 
+// tree, and so we must fill the histogram MHMcUnfoldCoeff::fHistMcE and 
+// MHMcUnfoldCoeff::fHistEstE (using MHMcUnfoldCoeff::FillSel()). 
+// If MMcEvt is not found, it means that we are in the loop over the 
+// "OriginalMC" tree, containing all the original Corsika events 
+// produced, and hence we must fill the histogram  fHistAll through 
+// MHMcUnfoldCoeff::FillAll()
+//
+Int_t MMcUnfoldCoeffCalc::PreProcess (MParList *pList)
+{
+  fUnfoldCoeff = (MHMcUnfoldCoeff*)pList->FindCreateObj("MHMcUnfoldCoeff");
+  
+  if (!fBinsTheta)
+    {
+      fBinsTheta = (MBinning*) pList->FindObject("binsTheta");
+      if (!fBinsTheta)
+	{
+	  *fLog << err << "Coarse Theta binning not found... Aborting." 
+		<< endl;
+	  return kFALSE;
+	}
+    }
+
+  if (!fBinsEnergy)
+    {
+      fBinsEnergy = (MBinning*) pList->FindObject("binsEnergy");
+      if (!fBinsEnergy)
+	{
+	  *fLog << err << "Coarse Energy binning not found... Aborting." 
+		<< endl;
+	  return kFALSE;
+	}
+    }
+  
+  fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+  if (fMcEvt)
+    {      
+      *fLog << inf << "MMcEvt found... Filling MHMcUnfoldCoeff.fHistSel..." << endl;
+
+      fEnergyEst =  (MEnergyEst*)pList->FindObject("MEnergyEst");
+      if(!fEnergyEst)
+	{
+	  *fLog << err << "MEnergyEst not found... aborting..." << endl;
+	  return kFALSE;
+	}
+
+      return kTRUE;
+    }
+
+  *fLog << inf << "MMcEvt not found... looking for MMcEvtBasic..." << endl;
+
+  fMcEvtBasic = (MMcEvtBasic*) pList->FindObject("MMcEvtBasic");
+    
+  if (fMcEvtBasic)
+    {
+      fUnfoldCoeff->SetCoarseBinnings(*fBinsEnergy,*fBinsTheta);
+
+      *fLog << inf << "MMcEvtBasic found... Filling MHMcUnfoldCoeff.fHistAll..." << endl;
+      return kTRUE;
+    }
+
+  *fLog << err << "MMcEvtBasic not found. Aborting..." << endl;
+
+  return kFALSE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Depending on whether fMcEvt or fMcEvtBasic are available, fill 
+// MHMcUnfoldCoeff::fHistAll, else, if fMcEvt is available, fill 
+// MHMcUnfoldCoeff::fHistMcE and MHMcUnfoldCoeff::fHistEstE
+//
+Int_t MMcUnfoldCoeffCalc::Process()
+{
+  Double_t mcenergy  = fMcEvt ? fMcEvt->GetEnergy() : fMcEvtBasic->GetEnergy();
+  Double_t estenergy = fEnergyEst ? fEnergyEst->GetEnergy() : 0;
+  Double_t theta  = fMcEvt? fMcEvt->GetTelescopeTheta()*TMath::RadToDeg() : 0; // in deg
+  
+  if (fMcEvt)
+    fUnfoldCoeff->FillSel(mcenergy, estenergy, theta);
+  else
+    fUnfoldCoeff->FillAll(mcenergy);
+  
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Postprocess. 
+// If both fHistMcE and fHistEstE are already filled, calculate
+// the coefficients. 
+// Else it means we still have to run one more loop, and then the
+// weights are computed
+//
+Int_t MMcUnfoldCoeffCalc::PostProcess()
+{
+  if(((TH2D*)fUnfoldCoeff->GetHistMcE())->GetEntries() > 0  &&
+     ((TH2D*)fUnfoldCoeff->GetHistEstE())->GetEntries() > 0)
+    {
+      fUnfoldCoeff->ComputeCoefficients();
+      return kTRUE;
+    }
+ 
+  if(((TH1D*)fUnfoldCoeff->GetHistAll())->GetEntries() <= 0)
+    {
+      *fLog << err << "Postprocess reached with no histogram computed. Aborting" << endl;
+      return kFALSE;
+    }
+  
+
+  if(fSpectrum)
+    fUnfoldCoeff->ComputeWeights(fSpectrum);
+  else
+    {
+      // default spectrum in case no other one is provided
+      TF1 spectrum("func","pow(x,-1.6)",2.,20000.);
+      fUnfoldCoeff->ComputeWeights(&spectrum);
+    }
+  
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mmontecarlo/MMcUnfoldCoeffCalc.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcUnfoldCoeffCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcUnfoldCoeffCalc.h	(revision 9772)
@@ -0,0 +1,46 @@
+#ifndef MARS_MMcUnfoldCoeffCalc
+#define MARS_MMcUnfoldCoeffCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#include <TH2.h>
+
+class MParList;
+class MMcEvt;
+class MMcEvtBasic;
+class MEnergyEst;
+class MBinning;
+class MHMcUnfoldCoeff;
+
+class MMcUnfoldCoeffCalc : public MTask
+{
+ private:
+  const MMcEvt*       fMcEvt;
+  const MMcEvtBasic*  fMcEvtBasic;
+  const MEnergyEst*   fEnergyEst;
+
+  MBinning*           fBinsTheta;  // coarse zenith angle binning
+  MBinning*           fBinsEnergy; // coarse energy binning
+  
+  TF1*                fSpectrum;   // Tentative energy spectrum. 
+  
+  MHMcUnfoldCoeff*    fUnfoldCoeff; // container holding coefficients histogram
+  
+  TString fObjName;
+
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  PostProcess();
+  
+ public:
+  MMcUnfoldCoeffCalc(const char *name = NULL, const char *title = NULL);
+
+  void SetSpectrum(TF1 *f) { fSpectrum = f; }
+
+  ClassDef(MMcUnfoldCoeffCalc, 0) // Task to calculate the coefficients for unfolding
+};
+
+#endif 
+
Index: /tags/Mars-V0.9/mmontecarlo/MMcWeightEnergySpecCalc.cc
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcWeightEnergySpecCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcWeightEnergySpecCalc.cc	(revision 9772)
@@ -0,0 +1,361 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez  10/2003 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MMcWeightEnergySlopeCalc
+//               
+//  Change the spectrum of the MC showers simulated with Corsika (a power law)
+//  to a new one, which can be either, again a power law but with a different
+//  spectral index, or a generalizeed spectrum. The new spectrum can be 
+//  pass to this class in different ways:
+//    1. Is the new spectrum will be a power law, just introduce the slope
+//       of this power law.
+//    2. Is the new spectrum will have a general shape, different options are
+//       available:
+//       a) The new spectrum is pass as a TF1 function 
+//       b) The new spectrum is pass as a char*
+//       c) The new spectrum is pass as a "interpreted function", i.e., a 
+//          function defined inside a ROOT macro, which will be invoked by the
+//          ROOT Cint itself. This is the case when we use ROOT macros.
+//       d) The new spectrum is pass as a "real function", i.e., a 
+//          function defined inside normal c++ file.
+//
+//  Method:
+//  ------ 
+//                                 
+//  -Corsika spectrun: dN/dE = A * E^(a)  
+//    with a = fCorsikaSlope, and A = N/integral{E*de} from ELowLim to EUppLim
+//
+//  -New spectrum:     dN/dE = B * g(E)
+//    where B = N/integral{g*dE} from ELowLim to EUppLim, and N=NumEvents 
+//
+//  For converting the spectrum simulated with Corsika to the new one, we apply
+//  a weight to each event, given by:
+//
+//     W(E) = B/A * g(E)/E^(a) 
+//
+//  In the case the new spectrum is simply a power law: dN/dE = B * E^(b), we
+//  have: 
+//
+//     W(E) = B/A * E^(b-a) 
+//
+//  (The factor B/A is used in order both the original and new spectrum have 
+//   the same area (i.e. in order they represent the same number of showers))
+//
+//  Note:
+//  ------
+//   -If the the new spectrum is just a power law (i.e. the user only specify
+//     the slope), the needed calculations (such as the integral of the 
+//     spectrum) are done analytically. But if the new spectrum is given as a 
+//     TF1 object, the calculations is done numerically.
+//
+//  ToDo:
+//  ----- 
+//   -Give to the user also the possibility to specify the integral of the 
+//    spectrum as another TF1 object (or C++ function)
+//
+//
+//  Input Containers:                         
+//   MMcEvt, MMcRunHeader, MMcCorsikaRunHeader
+//                                            
+//  Output Container:                        
+//   MWeight  
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MMcWeightEnergySpecCalc.h"
+
+#include "MParList.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMcEvt.hxx"
+#include "MMcRunHeader.hxx"
+#include "MMcCorsikaRunHeader.h"
+#include "MWeight.h"
+
+#include "TF1.h"
+#include "TGraph.h"
+
+ClassImp(MMcWeightEnergySpecCalc);
+
+using namespace std;
+
+
+
+void MMcWeightEnergySpecCalc::Init(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MMcWeightEnergySpecCalc";
+    fTitle = title ? title : "Task to calculate weights to change the energy spectrum"; 
+    
+    AddToBranchList("MMcEvt.fEnergy");
+
+    fAllEvtsTriggered         =  kFALSE;
+    fTotalNumSimulatedShowers =  0;
+}
+
+
+// ---------------------------------------------------------------------------
+//
+// Constructor. The new spectrum will be just a power law.
+//
+MMcWeightEnergySpecCalc::MMcWeightEnergySpecCalc(Float_t slope, 
+                                                 const char *name, const char *title)
+{
+    fNewSpecIsPowLaw = kTRUE;
+    fNewSlope = slope; 
+
+    fNewSpectrum = NULL; 
+
+    Init(name,title);
+} 
+
+// ---------------------------------------------------------------------------
+//
+// Constructor. The new spectrum will have a general shape, given by the user 
+// as a TF1 function.
+//
+MMcWeightEnergySpecCalc::MMcWeightEnergySpecCalc(const TF1& spectrum, 
+                                                 const char *name, const char *title)
+{
+    fNewSpecIsPowLaw = kFALSE;
+    fNewSpectrum = (TF1*)spectrum.Clone();
+
+    Init(name,title);
+} 
+
+// ---------------------------------------------------------------------------
+//
+// As before, but the function which represent the new spectrum is given as
+// a char* . Starting from it, we build a TF1 function
+//
+MMcWeightEnergySpecCalc::MMcWeightEnergySpecCalc(const char* spectrum, 
+                                                 const char *name, const char *title)
+{
+    fNewSpecIsPowLaw = kFALSE;
+    fNewSpectrum = new TF1("NewSpectrum",spectrum);
+
+    Init(name,title);
+} 
+
+// ---------------------------------------------------------------------------
+//
+// As before, but the new spectrum is given as a intrepreted C++ function. 
+// Starting from it we build a TF1 function.
+// This constructor is called for interpreted functions by CINT, i.e., when
+// the functions are declared inside a ROOT macro.
+//
+// NOTE: you muss do a casting to (void*) of the function that you pass to this
+//       constructor before invoking it in a macro, e.g.
+//
+//       Double_t myfunction(Double_t *x, Double_t *par)
+//         {
+//           ...
+//         }
+//
+//        MMcWeightEnergySpecCalc wcalc((void*)myfunction); 
+//
+//        tasklist.AddToList(&wcalc);
+//
+//        otherwise ROOT will invoke the constructor McWeightEnergySpecCalc(
+//         const char* spectrum, const char *name, const char *title)
+//
+MMcWeightEnergySpecCalc::MMcWeightEnergySpecCalc(void* function, 
+                                                 const char *name, const char *title)
+{
+    fNewSpecIsPowLaw = kFALSE;
+    fNewSpectrum = new TF1("NewSpectrum",function,0,1,1);
+
+    Init(name,title);
+} 
+
+// ---------------------------------------------------------------------------
+//
+// As before, but this is the constructor for real functions, i.e. it is called
+// when invoked with the normal C++ compiler, i.e. not inside a ROOT macro.
+//
+MMcWeightEnergySpecCalc::MMcWeightEnergySpecCalc(Double_t (*function)(Double_t*x, Double_t* par), const Int_t npar,  const char *name, const char *title)
+{
+    fNewSpecIsPowLaw = kFALSE;
+    fNewSpectrum = new TF1("NewSpectrum",function,0,1,1);
+
+    Init(name,title);
+} 
+
+
+
+// ----------------------------------------------------------------------------
+//
+// Destructor. Deletes the cloned fNewSpectrum.
+//
+MMcWeightEnergySpecCalc::~MMcWeightEnergySpecCalc()
+{
+  if (fNewSpectrum)
+    delete fNewSpectrum; 
+}
+
+
+
+// ---------------------------------------------------------------------------
+//
+//
+Int_t MMcWeightEnergySpecCalc::PreProcess (MParList *pList)
+{
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+      {
+	*fLog << err << dbginf << "MMcEvt not found... exit." << endl;
+	return kFALSE;
+      }
+
+    fWeight = (MWeight*)pList->FindCreateObj("MWeight");
+    if (!fWeight)
+      {
+	*fLog << err << dbginf << "MWeight not found... exit." << endl;
+	return kFALSE;
+      }
+    
+    return kTRUE;
+}
+
+
+
+// ----------------------------------------------------------------------------
+//
+// Executed each time a new root file is loaded
+// We will need fCorsikaSlope and fE{Upp,Low}Lim to calculate the weights
+//
+Bool_t MMcWeightEnergySpecCalc::ReInit(MParList *plist)
+{
+    MMcRunHeader *runheader = (MMcRunHeader*)plist->FindObject("MMcRunHeader");
+    if (!runheader)
+    {
+      *fLog << err << dbginf << "Error - MMcRunHeader not found... exit." << endl;
+      return kFALSE;
+    }
+
+    MMcCorsikaRunHeader *corrunheader  = (MMcCorsikaRunHeader*)plist->FindObject("MMcCorsikaRunHeader");
+    if (!corrunheader)
+      {
+	*fLog << err << dbginf << "Error - MMcCorsikaRunHeader not found... exit." << endl;
+	return kFALSE;
+      }
+
+
+    fCorsikaSlope = (Double_t)corrunheader->GetSlopeSpec();
+    fELowLim      = (Double_t)corrunheader->GetELowLim();
+    fEUppLim      = (Double_t)corrunheader->GetEUppLim();
+
+    fTotalNumSimulatedShowers += runheader->GetNumSimulatedShowers();    
+    fAllEvtsTriggered |= runheader->GetAllEvtsTriggered();    
+
+
+
+    *fLog << inf << "Slope of primaries' energy spectrum of Simulated showers: " << fCorsikaSlope << endl;
+    *fLog << inf << "Limits of energy range of Simulated showers: " 
+	  << fELowLim <<" - " << fEUppLim << endl;
+    *fLog << inf << "New Slope for Simulated showers: " << fNewSlope << endl;
+    *fLog << inf << "Total Number of Simulated showers: " 
+	  << fTotalNumSimulatedShowers << endl;    
+    *fLog << inf << "Only triggered events avail: " << (fAllEvtsTriggered?"yes":"no") << endl;
+
+
+
+    //
+    // Sanity checks to be sure that we won't divide by zero later on
+    //
+    if(fCorsikaSlope == -1. || fNewSlope == -1.) 
+      {
+	*fLog << err << "The Slope of the power law must be different of -1... exit" << endl;
+	return kFALSE;
+      }
+
+
+    //
+    // Starting from fCorsikaSlope and fE{Upp,Low}Lim, calculate the integrals
+    // of both, the original Corsika spectrum and the new one.
+    //
+    //
+    // For the Corsika simulated spectrum (just a power law), we have:
+    //
+    fCorSpecInt = ( pow(fEUppLim,1+fCorsikaSlope) - pow(fELowLim,1+fCorsikaSlope) ) / ( 1+fCorsikaSlope );
+ 
+ 
+    //
+    // For the new spectrum:
+    //
+    if (fNewSpecIsPowLaw)     // just the integral of a power law
+      {
+	fNewSpecInt = ( pow(fEUppLim,1+fNewSlope) - pow(fELowLim,1+fNewSlope) )/ ( 1+fNewSlope );
+      }
+    else
+      { 
+	fNewSpectrum->SetRange(fELowLim, fEUppLim);
+
+	// In this case we have to integrate the new spectrum numerically. We 
+	// could do simply fNewSpectrum->Integral(fELowLim,fEUppLim), but ROOT
+	// fails integrating up to fEUppLim for a sharp cutoff spectrum
+	
+	//
+	// Trick to calculate the integral numerically (it works better than 
+	// fNewSpectrum->Integral(fELowLim,fEUppLim) (although not perfectlly)
+	//
+	fNewSpectrum->SetNpx(1000);
+	TGraph gr(fNewSpectrum,"i");
+	Int_t Npx = gr.GetN();
+	Double_t* y = gr.GetY();
+
+	const Double_t integral = y[Npx-1];
+	fNewSpecInt = integral; 
+    }
+
+
+    return kTRUE;
+}
+
+
+
+// ----------------------------------------------------------------------------
+//
+//
+Int_t MMcWeightEnergySpecCalc::Process()
+{
+    const Double_t energy = fMcEvt->GetEnergy();
+
+    const Double_t C = fCorSpecInt / fNewSpecInt;
+    Double_t weight;
+
+
+    if (fNewSpecIsPowLaw)   
+      weight = C * pow(energy,fNewSlope-fCorsikaSlope);
+    else
+      weight = C * fNewSpectrum->Eval(energy) / pow(energy,fCorsikaSlope);
+     
+
+    fWeight->SetWeight( weight );
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mmontecarlo/MMcWeightEnergySpecCalc.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MMcWeightEnergySpecCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MMcWeightEnergySpecCalc.h	(revision 9772)
@@ -0,0 +1,76 @@
+#ifndef MARS_MMcWeightEnergySpecCalc
+#define MARS_MWeigthEnergySlopeCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+
+class MParList;
+class MMcEvt;
+class MWeight;
+class TF1;
+
+
+class MMcWeightEnergySpecCalc : public MTask
+{
+
+ private:
+
+    const MMcEvt *fMcEvt;
+    MWeight  *fWeight;
+
+    TF1*     fNewSpectrum;     // Function with the new spectrum
+
+    Bool_t   fNewSpecIsPowLaw; // Tells whether the new spectrum is introduced 
+                               //as a TF1 object or not
+    Double_t fCorsikaSlope; // Slope of energy spectrum generated with Corsika
+    Double_t fNewSlope;     // Slope of the new spectrum (if it is a power law)
+    Double_t fELowLim;      
+    Double_t fEUppLim;      // Limits of energy range for generation
+    Double_t fCorSpecInt;   // Value of the integrals of the Corsika and new
+    Double_t fNewSpecInt;   //spectrum respectively, between fElow and fUppLim
+
+    UInt_t   fTotalNumSimulatedShowers;
+    Bool_t   fAllEvtsTriggered;
+
+    void   Init(const char *name, const char *title);
+    Bool_t ReInit(MParList *plist); 
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+   
+
+ public:
+
+    MMcWeightEnergySpecCalc(const Float_t slope,
+			    const char *name=NULL, const char *title=NULL);
+
+    MMcWeightEnergySpecCalc(const TF1& spectrum,
+			    const char *name=NULL, const char *title=NULL);
+
+    MMcWeightEnergySpecCalc(const char* spectrum,
+			    const char *name=NULL, const char *title=NULL);
+   
+    MMcWeightEnergySpecCalc(void *function,
+			    const char *name=NULL, const char *title=NULL);
+ 
+    MMcWeightEnergySpecCalc(Double_t (*function)(Double_t* x, Double_t* par),
+	      const Int_t npar, const char *name=NULL, const char *title=NULL);
+    
+
+    ~MMcWeightEnergySpecCalc();
+
+
+    ClassDef(MMcWeightEnergySpecCalc, 0) // Task to convert the spectrum of the MC showers simulated with Corsika to a different one, by using weights
+};
+
+#endif 
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mmontecarlo/Makefile
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/Makefile	(revision 9772)
@@ -0,0 +1,37 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = MonteCarlo
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mmc -I../mhbase -I../mhist -I../mhistmc \
+	   -I../mgeom -I../manalysis -I../mtools -I../mfileio          \
+           -I../mfilter -I../mdata -I../mfbase 
+
+SRCFILES = MMcCollectionAreaCalc.cc \
+	   MMcThresholdCalc.cc \
+	   MMcTriggerRateCalc.cc \
+	   MMcWeightEnergySpecCalc.cc \
+	   MMcUnfoldCoeffCalc.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mmontecarlo/MonteCarloIncl.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MonteCarloIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MonteCarloIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mmontecarlo/MonteCarloLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mmontecarlo/MonteCarloLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mmontecarlo/MonteCarloLinkDef.h	(revision 9772)
@@ -0,0 +1,13 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MMcThresholdCalc+;
+#pragma link C++ class MMcCollectionAreaCalc+;
+#pragma link C++ class MMcTriggerRateCalc+;
+#pragma link C++ class MMcWeightEnergySpecCalc+;
+#pragma link C++ class MMcUnfoldCoeffCalc+;
+
+#endif
Index: /tags/Mars-V0.9/mmuon/MMuonCalibPar.cc
===================================================================
--- /tags/Mars-V0.9/mmuon/MMuonCalibPar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MMuonCalibPar.cc	(revision 9772)
@@ -0,0 +1,141 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Keiichi Mase 10/2004 <mailto:mase@mppmu.mpg.de>
+!              Markus Meyer 10/2004 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMuonCalibPar
+//
+// Storage Container for muon
+//
+//  This class holds some information for a calibraion using muons. Muons 
+// are identified by using the class of the MMuonSearchParCalc. You can fill 
+// these information by using the MMuonCalibParCalc. See also these class
+// manuals.
+//
+//  
+//  Input Containers:
+//   [MGeomCam]
+//   [MCerPhotEvt]
+//   [MMuonSearchPar]
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMuonCalibPar.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+#include "MMuonSearchPar.h"
+#include "MBinning.h"
+
+using namespace std;
+
+ClassImp(MMuonCalibPar);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMuonCalibPar::MMuonCalibPar(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMuonCalibPar";
+    fTitle = title ? title : "Muon calibration parameters";
+
+    fHistPhi   = new TH1F;
+    fHistWidth = new TH1F;
+
+    fHistPhi->SetName("HistPhi");
+    fHistPhi->SetTitle("HistPhi");
+    fHistPhi->SetXTitle("phi [deg.]");
+    fHistPhi->SetYTitle("sum of ADC");
+    fHistPhi->SetDirectory(NULL);
+    fHistPhi->SetFillStyle(4000);
+    fHistPhi->UseCurrentStyle();
+
+    fHistWidth->SetName("HistWidth");
+    fHistWidth->SetTitle("HistWidth");
+    fHistWidth->SetXTitle("distance from the ring center [deg.]");
+    fHistWidth->SetYTitle("sum of ADC");
+    fHistWidth->SetDirectory(NULL);
+    fHistWidth->SetFillStyle(4000);
+    fHistWidth->UseCurrentStyle();
+
+    fMargin = 60.;  // in mm
+    fArcPhiThres  = 100.;
+    fArcWidthThres  = 100.;
+    fArcPhiBinNum = 20;
+    fArcPhiHistStartVal = -180.; // deg.
+    fArcPhiHistEndVal   = 180.;  // deg.
+    fArcWidthBinNum = 28;
+    fArcWidthHistStartVal = 0.3; // deg.
+    fArcWidthHistEndVal   = 1.7; // deg.
+}
+
+// --------------------------------------------------------------------------
+//
+MMuonCalibPar::~MMuonCalibPar()
+{
+  delete fHistPhi;
+  delete fHistWidth;
+}
+
+// --------------------------------------------------------------------------
+//
+void MMuonCalibPar::Reset()
+{
+  fArcLength   = -1.;
+  fArcPhi      =  0.;
+  fArcWidth    = -1.;
+  fChiArcPhi   = -1.;
+  fChiArcWidth = -1.;
+  fMuonSize    =  0.;
+  fEstImpact   = -1.;
+  fUseUnmap    = kFALSE;
+  fPeakPhi     =  0.;
+
+  fHistPhi->Reset();
+  fHistWidth->Reset();
+}
+
+void MMuonCalibPar::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Muon Parameters (" << GetName() << ")"    << endl;
+    *fLog << " - Arc Length    [deg.]  = " << fArcLength     << endl;
+    *fLog << " - Arc Phi       [deg.]  = " << fArcPhi     << endl;
+    *fLog << " - Arc Width     [deg.]  = " << fArcWidth     << endl;
+    *fLog << " - Chi Arc Phi   [x2/ndf]= " << fChiArcPhi  << endl;
+    *fLog << " - Chi Arc Width [x2/ndf]= " << fChiArcWidth  << endl;
+    *fLog << " - Est. I. P.    [m]     = " << fEstImpact  << endl;
+    *fLog << " - Size of muon          = " << fMuonSize   << endl;
+    *fLog << " - Peak Phi      [deg.]  = " << fPeakPhi    << endl;
+    *fLog << " - UseUnmap              = " << fUseUnmap   << endl;
+}
+
+
+
+
Index: /tags/Mars-V0.9/mmuon/MMuonCalibPar.h
===================================================================
--- /tags/Mars-V0.9/mmuon/MMuonCalibPar.h	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MMuonCalibPar.h	(revision 9772)
@@ -0,0 +1,84 @@
+#ifndef MARS_MMuonCalibPar
+#define MARS_MMuonCalibPar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MCerPhotEvt;
+class MMuonSearchPar;
+
+class MMuonCalibPar : public MParContainer
+{
+private:
+  Float_t fArcLength;     // An arc length of a muon along the arc [deg.]
+  Float_t fArcPhi;        // A opening angle of a muon arc [deg.]
+  Float_t fArcWidth;      // A width of a muon [deg.] (1 sigma of gaussian fit)
+  Float_t fChiArcPhi;     // A chisquare value of the cosine fit for arc phi
+  Float_t fChiArcWidth;   // A chisquare value of the cosine fit for arc wid
+  Float_t fMuonSize;      // A SIZE of muon which is defined as a SIZE around the estimated circle
+  Float_t fEstImpact;     // An estimated impact parameter from the photon distribution along the arc image
+  Float_t fMargin;        // margin to evaluate muons [mm]. The defaut value is 60 mm, corresponding to 0.2 deg. This value can be changed by using the function of SetMargin
+  Bool_t  fUseUnmap;      // This is a flag to know the Unmapped pixels are used. Refer to the class of MImgCleanStd
+  Float_t fPeakPhi;       // The angle which indicates the peak position in the estimated circle
+  Float_t fArcPhiThres;   // The threshold value to define arc phi
+  Float_t fArcWidthThres; // The threshold value to define arc width
+
+public:
+  MMuonCalibPar(const char *name=NULL, const char *title=NULL);
+  ~MMuonCalibPar();
+  
+  Int_t   fArcPhiBinNum;         // The bin number for the histogram of arc phi. You may change this value. However, if you change this, YOU ALSO HAVE TO CHANGE THE THRESHOLD VALUE TO GET ARC LENGTH.
+  Int_t   fArcWidthBinNum;       // The bin number for the histogram of arc wid
+  Float_t fArcPhiHistStartVal;   // The starting value for the histogram of arc phi
+  Float_t fArcPhiHistEndVal;     // The end value for the histogram of arc phi
+  Float_t fArcWidthHistStartVal; // The starting value for the histogram of arc width
+  Float_t fArcWidthHistEndVal;   // The end value for the histogram of arc width
+
+  TH1F *fHistPhi;   // Histogram of photon distribution along the arc.
+  TH1F *fHistWidth; // Histogram of radial photon distribution of the arc.
+  
+  void Reset();
+  
+  Float_t GetArcLength()      const { return fArcLength; }
+  Float_t GetArcPhi()         const { return fArcPhi; }
+  Float_t GetArcWidth()       const { return fArcWidth; }
+  Float_t GetChiArcPhi()      const { return fChiArcPhi; }
+  Float_t GetChiArcWidth()    const { return fChiArcWidth; }
+  Float_t GetMargin()         const { return fMargin; }
+  Float_t GetMuonSize()       const { return fMuonSize; }
+  Float_t GetEstImpact()      const { return fEstImpact; }
+  Bool_t  IsUseUnmap()        const { return fUseUnmap; }
+  Float_t GetPeakPhi()        const { return fPeakPhi; }
+  Float_t GetArcPhiThres()    const { return fArcPhiThres; }
+  Float_t GetArcWidthThres()  const { return fArcWidthThres; }
+  Float_t GetArcPhiBinNum()   const { return fArcPhiBinNum; }
+  Float_t GetArcWidthBinNum() const { return fArcWidthBinNum; }
+  TH1F    *GetHistPhi()       { return fHistPhi; }
+  TH1F    *GetHistWidth()     { return fHistWidth; }
+  
+  void    SetArcLength(Float_t len)       { fArcLength = len; }
+  void    SetArcPhi(Float_t phi)          { fArcPhi = phi; }
+  void    SetArcWidth(Float_t wid)        { fArcWidth = wid; }
+  void    SetChiArcPhi(Float_t chi)       { fChiArcPhi = chi; }
+  void    SetChiArcWidth(Float_t chi)     { fChiArcWidth = chi; }
+  void    SetMargin(Float_t margin)       { fMargin = margin; }
+  void    SetMuonSize(Float_t size)       { fMuonSize = size; }
+  void    SetEstImpact(Float_t impact)    { fEstImpact = impact; }
+  void    SetUseUnmap()                   { fUseUnmap = kTRUE; }
+  void    SetPeakPhi(Float_t phi)         { fPeakPhi = phi; }
+  void    SetArcPhiThres(Float_t thres)   { fArcPhiThres = thres; }
+  void    SetArcWidthThres(Float_t thres) { fArcWidthThres = thres; }
+  void    SetArcPhiBinNum(Int_t num)      { fArcPhiBinNum = num; }
+  void    SetArcWidthBinNum(Int_t num)    { fArcWidthBinNum = num; }
+  
+  void    Print(Option_t *opt=NULL) const;
+
+  ClassDef(MMuonCalibPar, 1) // Container to hold muon calibration parameters
+};
+    
+#endif
Index: /tags/Mars-V0.9/mmuon/MMuonCalibParCalc.cc
===================================================================
--- /tags/Mars-V0.9/mmuon/MMuonCalibParCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MMuonCalibParCalc.cc	(revision 9772)
@@ -0,0 +1,593 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Keiichi Mase 10/2004 <mailto:mase@mppmu.mpg.de>
+!              Markus Meyer 10/2004 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MMuonCalibParCalc
+//
+// Task to calculate the muon parameters
+//
+//  This class allows you to get more muon information especially useful for
+// the calibration of our telescope. This class store the information into the
+// container of MMuonCalibPar. 
+//
+//  In order to make this class work, we need the information of the arc
+// center and the radius. Therefore, we need to use the task of 
+// MMuonSearchParCalc.
+//
+//  You can use this class such as the followings;
+//
+//   MTaskList tlist;
+//   MMuonSearchParCalc musearchcalc;
+//   MMuonCalibParCalc mucalibcalc;
+//   tlist.AddToList(&musearchcalc);
+//   tlist.AddToList(&mucalibcalc);.
+//
+//  You may change the allowed region to estimate muon parameters such as 
+// Muon SIZE and ARC LENGTH. The default value is 60 mm (0.2 deg.). If the
+// estimated radius of the arc is 1.0 degree, we take the photons in the 
+// radius range from 0.8 to 1.2 degrees. You can change this value such as
+// the followings;
+//
+//   mucalibcalc.SetMargin(60.);
+//
+//  You can retrieve the histogram (TH1F) using the function of GetHistPhi() 
+// (also GetHistWid()). Therefore, you can draw the histogram such as
+//
+//   MParList  plist;
+//   MMuonCalibPar muparcalib;
+//   plist.AddToList(&muparcalib);.
+//   muparcalib.GetHistPhi().Draw();.
+//
+//  In order to use another information of muons such as the center position 
+// of the estimated circle, the radius of the circle. Use the infomation 
+// stored in MMuonSearchPar. 
+//
+// 
+//  For the faster computation, by default, the calculation of impact
+// parameter is suppressed. If you want to calculate the impact parameter
+// from the muon image, you can use the function of EnableImpactCalc(),
+// namely;
+//
+//   mucalibcalc.EnableImpactCalc();.
+//
+//  In addition, for the faster comutation, pre cuts to select the candidates
+// of muons for the calibration is done. You can set the values using the
+// function of SetPreCuts. This function takes 5 variables. They correspond
+// to the cur for the Arc Radius (low and high), the deviation of the fit
+// (high), the Muon Size (low) and Arc Phi (low). You can set them such as 
+//
+//   mucalibcalc.SetPreCuts(180., 400., 50., 2000., 180.);
+// 
+//  If you want to disable the pre cuts, you can disable it by using the 
+// function of DisablePreCuts(), namely;
+//  
+//   mucalibcalc.DisablePreCuts();.
+//
+// 
+// ### TODO ###
+//  Up to now, in the histogram the error of the signal is estimated from
+// the signal using a rough conversion factor and a F-factor and this values
+// are global for all pixels. This is not the case for the real data. This
+// value should be taken from some containers. In addition, the error of 
+// the pedestal is not taken into accout. The error treatment should be
+// done correctly.
+// 
+//
+//  Input Containers:
+//   [MGeomCam]
+//   [MCerPhotEvt]
+//   [MMuonSearchPar]
+//
+//  Output Containers:
+//   [MMuonCalibPar]
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MMuonCalibParCalc.h"
+
+#include <fstream>
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TMinuit.h>
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MSrcPosCam.h"
+#include "MCerPhotEvt.h"
+#include "MMuonSearchPar.h"
+#include "MMuonCalibPar.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MBinning.h"
+
+using namespace std;
+
+ClassImp(MMuonCalibParCalc);
+
+static const TString gsDefName  = "MMuonCalibParCalc";
+static const TString gsDefTitle = "Calculate new image parameters";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MMuonCalibParCalc::MMuonCalibParCalc(const char *name, const char *title)
+  : fNameCerPhot("MCerPhotEvt")
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fPreCuts[0]     = 180.;
+    fPreCuts[1]     = 400.;
+    fPreCuts[2]     = 50.;
+    fPreCuts[3]     = 2000.;
+    fPreCuts[4]     = 150.;
+
+    fMargin = 60.;
+    fArcPhiThres = 100.;
+    fArcWidthThres = 100.;
+
+    fEnableImpactCalc = kFALSE; // By default the calculation of impact parameter is skipped.
+    fDisablePreCuts =   kFALSE; // By default the pre cuts will be applied.
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MMuonCalibParCalc::PreProcess(MParList *pList)
+{
+  fCerPhotEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber(fNameCerPhot), "MCerPhotEvt");
+  if (!fCerPhotEvt)
+    {
+      *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeomCam)
+    {
+      *fLog << dbginf << "MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fMuonCalibPar = (MMuonCalibPar*)pList->FindCreateObj("MMuonCalibPar", "MMuonCalibPar");
+  if (!fMuonCalibPar)
+    {
+      *fLog << dbginf << "MMuonCalibPar missing in Parameter List... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fMuonSearchPar = (MMuonSearchPar*)pList->FindCreateObj("MMuonSearchPar", "MMuonSearchPar");
+  if (!fMuonSearchPar)
+    {
+      *fLog << dbginf << "MMuonSearchPar missing in Parameter List... aborting." << endl;
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+// 
+//  This function fill the histograms in order to get muon parameters.
+// For the evaluation of the Arc Width, we use only the signals in the inner 
+// part. 
+// 
+void MMuonCalibParCalc::FillHist()
+{
+  Float_t MuonSize = 0.;
+
+  Int_t binnumphi = fMuonCalibPar->fArcPhiBinNum;
+  Int_t binnumwid = fMuonCalibPar->fArcWidthBinNum;
+
+  // preparation for a histgram
+  MBinning binsphi;
+  binsphi.SetEdges(binnumphi, 
+		   fMuonCalibPar->fArcPhiHistStartVal, 
+		   fMuonCalibPar->fArcPhiHistEndVal);
+  binsphi.Apply(*(fMuonCalibPar->fHistPhi));
+
+  MBinning binswid;
+  binswid.SetEdges(binnumwid, 
+		   fMuonCalibPar->fArcWidthHistStartVal, 
+		   fMuonCalibPar->fArcWidthHistEndVal);
+  binswid.Apply(*(fMuonCalibPar->fHistWidth));
+
+  const Int_t entries = (*fCerPhotEvt).GetNumPixels();
+
+  // the position of the center of a muon ring
+  const Float_t cenx = (*fMuonSearchPar).GetCenterX();
+  const Float_t ceny = (*fMuonSearchPar).GetCenterY();
+  
+  for (Int_t i=0; i<entries; i++ )
+    {
+      MCerPhotPix &pix = (*fCerPhotEvt)[i];
+      
+      const MGeomPix &gpix = (*fGeomCam)[pix.GetPixId()];
+      
+      const Float_t dx = gpix.GetX() - cenx;
+      const Float_t dy = gpix.GetY() - ceny;
+      
+     const Float_t dist = TMath::Sqrt(dx*dx+dy*dy);
+      
+      Float_t ang = TMath::ACos(dx/dist);
+      if(dy>0)
+	ang *= -1.0;
+      
+      // if the signal is not near the estimated circle, it is ignored.
+      if(dist < (*fMuonSearchPar).GetRadius() + fMuonCalibPar->GetMargin() 
+	 && dist > (*fMuonSearchPar).GetRadius() - fMuonCalibPar->GetMargin())
+	{
+	  // check whether ummapped pixel is used or not.
+	  // if it is so, ingnore the pixel information since the pixels totally deteriorate the muon information.
+	  if(pix.IsPixelUnmapped())
+	    {
+	      fMuonCalibPar->SetUseUnmap();
+	      continue;
+	    }
+	  fMuonCalibPar->fHistPhi->Fill(ang*kRad2Deg, pix.GetNumPhotons());
+	  MuonSize += pix.GetNumPhotons();
+	}
+
+      // use only the inner pixles. This is geometry dependent. This has to
+      // be fixed!
+      if(pix.GetPixId()>397)
+	continue;  
+      
+      fMuonCalibPar->fHistWidth
+	->Fill(dist*(*fGeomCam).GetConvMm2Deg(), pix.GetNumPhotons());
+    }
+
+  fMuonCalibPar->SetMuonSize(MuonSize);
+
+  // error estimation (temporaly)
+  //  The error is estimated from the signal. In order to do so, we have to
+  // once convert the signal from ADC to photo-electron. Then we can get
+  // the fluctuation such as F-factor*sqrt(phe). 
+  //  Up to now, the error of pedestal is not taken into accout. This is not 
+  // of course correct. We will include this soon.
+    Double_t ADC2PhEl = 0.14;
+    Double_t Ffactor = 1.4;
+    for(Int_t i=0; i<binnumphi+1; i++)
+      {
+	Float_t rougherr  = TMath::Sqrt(TMath::Abs(fMuonCalibPar->fHistPhi->GetBinContent(i))*ADC2PhEl)/ADC2PhEl*Ffactor;
+	{
+	  fMuonCalibPar->fHistPhi->SetBinError(i, rougherr);
+	}
+      }
+    for(Int_t i=0; i<binnumwid+1; i++)
+      {
+	Float_t rougherr = TMath::Sqrt(TMath::Abs(fMuonCalibPar->fHistWidth->GetBinContent(i))*ADC2PhEl)/ADC2PhEl*Ffactor;
+	{
+	  fMuonCalibPar->fHistWidth->SetBinError(i, rougherr);
+	}
+      }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Photon distribution along the estimated circle is fitted with theoritical
+// function in order to get some more information such as Arc Phi and Arc 
+// Length.
+//
+void MMuonCalibParCalc::CalcPhi()
+{
+  Float_t thres = fMuonCalibPar->GetArcPhiThres();
+  Float_t startval = fMuonCalibPar->fArcPhiHistStartVal;
+  Float_t endval = fMuonCalibPar->fArcPhiHistEndVal;
+  Int_t   binnum = fMuonCalibPar->fArcPhiBinNum;
+
+  Float_t convbin2val = (endval-startval)/(Float_t)binnum;
+
+    // adjust the peak to 0
+    Float_t maxval = 0.;
+    Int_t   maxbin = 0;
+    maxval = fMuonCalibPar->fHistPhi->GetMaximum();
+    maxbin = fMuonCalibPar->fHistPhi->GetMaximumBin();
+    fMuonCalibPar->SetPeakPhi(180.-(Float_t)(maxbin-1.)*convbin2val); 
+    TArrayD tmp;
+    tmp.Set(binnum+1);
+    for(Int_t i=1; i<binnum+1; i++)
+      {
+	tmp[i] = fMuonCalibPar->fHistPhi->GetBinContent(i);
+      }
+    for(Int_t i=1; i<binnum+1; i++)
+      {
+	Int_t id;
+	id = i + (maxbin-(Int_t)((Float_t)binnum/2.)-1);
+	if(id>binnum)
+	  {
+	    id-=(binnum);
+	  }
+	if(id<=0)
+	  {
+	    id+=(binnum);
+	  }
+	fMuonCalibPar->fHistPhi->SetBinContent(i,tmp[id]);
+      }
+    maxbin = (Int_t)((Float_t)binnum/2.)+1;
+
+  // Determination of fitting region
+  // The threshold is fixed with 100 [photons or ADC] in a bin. Therefore,
+  // if you change the bin number, YOU HAVE TO CHANGE THIS VALUE!!!
+  Float_t startfitval = 0.;
+  Float_t endfitval   = 0.;
+  Bool_t  IsInMaxim = kFALSE;
+  Int_t effbinnum = 0;
+  for(Int_t i=1; i<binnum+1; i++)
+    {
+      Float_t content = fMuonCalibPar->fHistPhi->GetBinContent(i);
+      Float_t content_pre = fMuonCalibPar->fHistPhi->GetBinContent(i-1);
+      
+      if(content > thres && content_pre < thres)
+	{
+	  startfitval = (Float_t)(i-1)*convbin2val+startval;
+	}
+      if(i==maxbin)
+	IsInMaxim = kTRUE;
+      
+      if(content < thres && IsInMaxim == kTRUE)
+	{
+	  endfitval = (Float_t)(i-1)*convbin2val+startval;
+	  break;
+	}
+      endfitval = endval;
+    }
+  
+  effbinnum = (Int_t)((endfitval-startfitval)/convbin2val);
+
+  fMuonCalibPar->SetArcPhi(endfitval-startfitval);
+
+  fMuonCalibPar->SetArcLength( fMuonCalibPar->GetArcPhi()*TMath::DegToRad()*(*fMuonSearchPar).GetRadius()*(*fGeomCam).GetConvMm2Deg());
+  
+  if(fEnableImpactCalc)
+      CalcImpact(effbinnum, startfitval, endfitval);
+}
+
+// --------------------------------------------------------------------------
+//
+//  An impact parameter is calculated by fitting the histogram of photon
+// distribution along the circle with a theoritical model. 
+// (See G. Vacanti et. al., Astroparticle Physics 2, 1994, 1-11. 
+// The function (6) is used here.) 
+//
+//  By default this calculation is suppressed because this calculation is 
+// very time consuming. If you want to calculate an impact parameter,
+// you can call the function of EnableImpactCalc().
+//
+void MMuonCalibParCalc::CalcImpact
+(Int_t effbinnum, Float_t startfitval, Float_t endfitval)
+{
+  // Fit the distribution with Vacanti function. The function is different
+  // for the impact parameter of inside or outside of our reflector. 
+  // Then two different functions are applied to the photon distribution,
+  // and the one which give us smaller chisquare value is taken as a 
+  // proper one.
+  Double_t val1,err1,val2,err2;
+  // impact parameter inside mirror radius (8.5m)
+  TString func1;
+  Float_t tmpval = (*fMuonSearchPar).GetRadius()*(*fGeomCam).GetConvMm2Deg()*TMath::DegToRad();
+  tmpval = sin(2.*tmpval)*8.5;
+  func1 += "[0]*";
+  func1 += tmpval;
+  func1 += "*(sqrt(1.-([1]/8.5)**2*sin((x-[2])*3.1415926/180.)**2)+([1]/8.5)*cos((x-[2])*3.1415926/180.))";
+  
+  TF1 f1("f1",func1,startfitval,endfitval);
+  f1.SetParameters(2000,3,0);
+  f1.SetParLimits(1,0,8.5);
+  f1.SetParLimits(2,-180.,180.);
+  
+  fMuonCalibPar->fHistPhi->Fit("f1","RQEM");
+  
+  Float_t chi1 = -1;
+  Float_t chi2 = -1;
+  if(effbinnum>3)
+    chi1 = f1.GetChisquare()/((Float_t)(effbinnum-3));
+  
+  gMinuit->GetParameter(1,val1,err1);  // get the estimated IP
+  Float_t estip1 = val1;
+  
+  // impact parameter beyond mirror area (8.5m)
+  TString func2;
+  Float_t tmpval2 = (*fMuonSearchPar).GetRadius()*(*fGeomCam).GetConvMm2Deg()*TMath::DegToRad();
+  tmpval2 = sin(2.*tmpval2)*8.5*2.;
+  func2 += "[0]*";
+  func2 += tmpval2;
+  func2 += "*sqrt(1.-(([1]/8.5)*sin((x-[2])*3.1415926/180.))**2)";
+  
+  TF1 f2("f2",func2,startfitval,endfitval);
+  f2.SetParameters(2000,20,0);
+  f2.SetParLimits(1,8.5,300.);
+  f2.SetParLimits(2,-180.,180.);
+  
+  fMuonCalibPar->fHistPhi->Fit("f2","RQEM+");
+  
+  if(effbinnum>3)
+    chi2 = f2.GetChisquare()/((Float_t)(effbinnum-3));
+  
+  gMinuit->GetParameter(1,val2,err2);  // get the estimated IP
+  Float_t estip2 = val2;
+  
+  if(effbinnum<=3)
+    {
+      fMuonCalibPar->SetEstImpact(-1.);
+    }
+  if(chi2 > chi1)
+    {
+      fMuonCalibPar->SetEstImpact(estip1);
+      fMuonCalibPar->SetChiArcPhi(chi1);
+    }
+  else
+    {
+      fMuonCalibPar->SetEstImpact(estip2);
+      fMuonCalibPar->SetChiArcPhi(chi2);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Photon distribution of distance from the center of estimated ring is 
+// fitted in order to get some more information such as ARC WIDTH which 
+// can represent to the PSF of our reflector.
+//
+Float_t MMuonCalibParCalc::CalcWidth()
+{
+  Float_t startval = fMuonCalibPar->fArcWidthHistStartVal;
+  Float_t endval = fMuonCalibPar->fArcWidthHistEndVal;
+  Int_t   binnum = fMuonCalibPar->fArcWidthBinNum;
+  Float_t thres = fMuonCalibPar->GetArcWidthThres();
+
+  Float_t convbin2val = (endval - startval)
+    /(Float_t)binnum;
+
+    // determination of fitting region
+    Int_t maxbin = fMuonCalibPar->fHistWidth->GetMaximumBin();
+    Float_t startfitval = 0.;
+    Float_t endfitval   = 0.;
+    Bool_t   IsInMaxim = kFALSE;
+    Int_t    effbinnum = 0;
+    for(Int_t i=1; i<binnum+1; i++)
+      {
+	Float_t content = fMuonCalibPar->fHistWidth->GetBinContent(i);
+	Float_t content_pre = fMuonCalibPar->fHistWidth->GetBinContent(i-1);
+
+	if(content > thres)
+	  effbinnum++;
+
+	if(content > thres && content_pre < thres)
+	  {
+	    startfitval = (Float_t)(i-4)*convbin2val + startval;
+	    if(startfitval<0.) startfitval = 0.;
+	  }
+	if(i==maxbin)
+	  IsInMaxim = kTRUE;
+
+	if(content < thres && IsInMaxim == kTRUE)
+	  {
+	    endfitval = (Float_t)(i+2)*convbin2val + startval;
+	    if(endfitval>180.) endfitval = 180.;
+	    break;
+	  }
+	endfitval = endval;
+      }
+    effbinnum = (Int_t)((endfitval-startfitval)/convbin2val);
+
+    TF1 f1("f1","gaus",startfitval,endfitval);
+
+    fMuonCalibPar->fHistWidth->Fit("f1","QR","",startfitval,endfitval);
+    
+    if(effbinnum>3)
+      fMuonCalibPar->SetChiArcWidth(f1.GetChisquare()/((Float_t)(effbinnum-3)));
+
+    Double_t val,err;
+    gMinuit->GetParameter(2,val,err); // get the sigma value
+
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of muon parameters
+//
+Int_t MMuonCalibParCalc::Calc(const Float_t *cuts)
+{
+  // sanity check
+  if((*fCerPhotEvt).GetNumPixels() < 3)
+    return kCONTINUE;
+
+  // If an event does not seem to be like muon, the calculation will be skipped.
+  if((*fMuonSearchPar).IsNoMuon()) 
+    return kCONTINUE; 
+
+  // Pre Cuts 1
+  if(!fDisablePreCuts)
+    {
+      if((*fMuonSearchPar).GetRadius() < cuts[0] || (*fMuonSearchPar).GetRadius() > cuts[1])
+	{
+	  (*fMuonSearchPar).SetNoMuon();
+	  return kCONTINUE;
+	}
+      if((*fMuonSearchPar).GetDeviation() > cuts[2])
+	{
+	  (*fMuonSearchPar).SetNoMuon();
+	  return kCONTINUE;
+	}
+    }
+
+  // initialization
+  (*fMuonCalibPar).Reset();
+
+  // Fill signals to histograms
+  FillHist();
+
+  // Calculation of Arc Phi etc...
+  CalcPhi();
+
+  // Pre Cuts 2
+  if(!fDisablePreCuts)
+    {
+      if(fMuonCalibPar->GetMuonSize() < cuts[3] 
+	 || fMuonCalibPar->GetArcPhi() < cuts[4])
+	{
+	  (*fMuonSearchPar).SetNoMuon();
+	  return kCONTINUE;
+	}
+    }
+
+  // Calculation of Arc Width etc...
+  fMuonCalibPar->SetArcWidth(CalcWidth()); 
+  
+  return kTRUE;
+} 
+
+
+// -------------------------------------------------------------------------
+//
+Int_t MMuonCalibParCalc::Process()
+{
+  fMuonCalibPar->SetMargin(fMargin);
+  fMuonCalibPar->SetArcPhiThres(fArcPhiThres);
+  fMuonCalibPar->SetArcWidthThres(fArcWidthThres);
+
+  if(!Calc(fPreCuts))
+    return kCONTINUE;
+
+  return kTRUE;
+}
+
+void MMuonCalibParCalc::SetPreCuts
+(Float_t radcutlow, Float_t radcuthigh, Float_t devcuthigh,
+ Float_t musizecutlow, Float_t arcphicutlow)
+{
+  fPreCuts[0] = radcutlow;
+  fPreCuts[1] = radcuthigh;
+  fPreCuts[2] = devcuthigh;
+  fPreCuts[3] = musizecutlow;
+  fPreCuts[4] = arcphicutlow;
+}
+
Index: /tags/Mars-V0.9/mmuon/MMuonCalibParCalc.h
===================================================================
--- /tags/Mars-V0.9/mmuon/MMuonCalibParCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MMuonCalibParCalc.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MMuonCalibParCalc
+#define MARS_MMuonCalibParCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMuonSearchPar;
+class MMuonCalibPar;
+class MSrcPosCam;
+class MGeomCam;
+class MCerPhotEvt;
+
+class MMuonCalibParCalc : public MTask
+{
+private:
+    MGeomCam       *fGeomCam;
+    MCerPhotEvt    *fCerPhotEvt;
+    MMuonCalibPar  *fMuonCalibPar;  
+    MMuonSearchPar *fMuonSearchPar; 
+
+    Float_t fMargin;           // margin to evaluate muons [mm]. The defaut value is 60 mm, corresponding to 0.2 deg. This value can be changed by using the function of SetMargin
+    Float_t fArcPhiThres;     // The threshold value to define arc phi
+    Float_t fArcWidthThres;   // The threshold value to define arc width
+    Bool_t fEnableImpactCalc; // If true, the impact calculation will be done, which consumes a lot of time.
+    Bool_t fDisablePreCuts;   // If true, the pre cuts to select muons for the calibration will be disabled.
+
+    Float_t fPreCuts[5];  // The values for pre cuts.
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+    TString fNameCerPhot;
+
+public:
+    MMuonCalibParCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetMargin(Float_t margin)       { fMargin = margin; }
+    void SetArcPhiThres(Float_t thres)   { fArcPhiThres = thres; }
+    void SetArcWidthThres(Float_t thres) { fArcWidthThres = thres; }
+    void EnableImpactCalc()              { fEnableImpactCalc = kTRUE; }
+    void DisablePreCuts()                { fDisablePreCuts = kTRUE; }
+    void SetPreCuts(Float_t radcutlow, Float_t radcuthigh, Float_t devcuthigh,
+		    Float_t musizecutlow, Float_t arcphicutlow);
+
+    void SetNameCerPhotEvt(const char *name) { fNameCerPhot = name; }
+
+    void FillHist();
+    void CalcPhi();
+    void CalcImpact(Int_t effbinnum, Float_t startfitval, Float_t endfitval);
+    Float_t CalcWidth();
+    Int_t   Calc(const Float_t *cuts);
+
+    ClassDef(MMuonCalibParCalc, 0) // task to calculate muon parameters
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mmuon/MMuonSearchPar.cc
===================================================================
--- /tags/Mars-V0.9/mmuon/MMuonSearchPar.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MMuonSearchPar.cc	(revision 9772)
@@ -0,0 +1,309 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Keiichi Mase 10/2004 <mailto:mase@mppmu.mpg.de>
+!              Markus Meyer 10/2004 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMuonSearchPar
+//
+// Storage Container for muon
+//
+//  This class is the container for muon parameters. Actually, the calculation
+// is done here. Muons are searched by fitting the image with a circle. 
+// (This function will be called by using the class of MMuonSearchParCalc.) 
+// This container especially holds the information of the results of the 
+// search (fit of a image by a circle).
+//
+//  In order to use further information of muons such as the width of arcs,
+// the arc length along it, the muons size. Use the infomation stored in 
+// MMuonCalibPar. The information will be available by using the task of 
+// MMuonCalibParCalc.
+// 
+// 
+// --- How to search muons --- 
+//  (This information is a little bit technical. You can skip to read if you 
+//   don't need the technical information.)
+// 
+// 1. A temporal center position of a circle is determined by using 
+//  the Hillas parameters. Assumed that the center position will be on the
+//  line which is perpendicular to the longitudinal image axis and the 
+//  distance from the gravity center of the image to the center position of
+//  a ring is approximately 1 deg. (corresponding to the Cherenkov angle.).
+//  Therefore, we will have two candidates of the center positions.
+// 2. Find the ring radius which gives the minimum RMS between the camera
+//  images and the estimated circle.
+// 3. Select one temporal position which gives smaller RMS as a true temporal
+//  center position.
+// 4. Changing the center position of a circle on the camera plane from the 
+// determined temporal center position, find the position which gives the 
+// minimum RMS of the fit.
+//
+//
+// --- Remark ---
+//  This method to search for muons is not fully optimized yet. However,
+// it is good idea to use the temporal estimated center position from
+// the Hillas parameters in order to reduce time to search. In addition,
+// This method is faster than the MINUIT.
+//
+//
+//  Input Containers:
+//   [MGeomCam]
+//   [MHillas]
+//   [MCerPhotEvt]
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMuonSearchPar.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MHillas.h"
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+
+using namespace std;
+
+ClassImp(MMuonSearchPar);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMuonSearchPar::MMuonSearchPar(const char *name, const char *title)
+{
+  fName  = name  ? name  : "MMuonSearchPar";
+  fTitle = title ? title : "Muon search parameters";
+}
+
+// --------------------------------------------------------------------------
+//
+void MMuonSearchPar::Reset()
+{
+  fRadius  = -1.;
+  fDeviation  = -1.;
+  fCenterX = 0.;
+  fCenterY = 0.;
+  fNoMuon = kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Get the tempolary center of a ring from the Hillas parameters.
+//  Two candidates of the position is returened.
+//
+void MMuonSearchPar::CalcTempCenter(const MHillas &hillas, 
+      Float_t &xtmp1, Float_t &ytmp1, Float_t &xtmp2, Float_t &ytmp2)
+{
+  Float_t a,dx,dy;
+  Float_t tmp_r = 300.;  // assume that the temporal cherenkov angle is 1 deg. (300 mm).
+
+  a = TMath::Tan(hillas.GetDelta());
+
+  dx = a/TMath::Sqrt(tmp_r+a*a)/3.;
+  dy = -tmp_r/TMath::Sqrt(1+a*a)/3.;
+
+  xtmp1 = hillas.GetMeanX() + dx;
+  ytmp1 = hillas.GetMeanY() + dy;
+  xtmp2 = hillas.GetMeanX() - dx;
+  ytmp2 = hillas.GetMeanY() - dy;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This function gives you the ring radius fitted best to the camera image
+//  and its RMS for the input position.
+//
+Bool_t MMuonSearchPar::CalcRadius(const MGeomCam &geom, const MCerPhotEvt &evt,
+      Float_t x, Float_t y, Float_t &r, Float_t &sigma)
+{
+  Float_t mean_r=0., dev_r=0., sums=0., tmp=0.;
+
+  const Int_t entries = evt.GetNumPixels();
+
+  for (Int_t i=0; i<entries; i++ ){
+    const MCerPhotPix &pix = evt[i];
+
+    if (!pix.IsPixelUsed())
+      continue;
+
+    const MGeomPix &gpix = geom[pix.GetPixId()];
+
+    tmp=TMath::Sqrt((gpix.GetX()-x)*(gpix.GetX()-x)
+		    +(gpix.GetY()-y)*(gpix.GetY()-y));
+
+    mean_r += pix.GetNumPhotons()*tmp;
+    dev_r  += pix.GetNumPhotons()*tmp*tmp;
+    sums   += pix.GetNumPhotons();
+  }
+
+  if(sums<1.E-10)
+      return kFALSE;
+
+  r = mean_r/sums;
+
+  if(dev_r/sums-(r)*(r)<1.E-10)
+      return kFALSE;
+
+  sigma = TMath::Sqrt(dev_r/sums-(r)*(r)); 
+
+  return kTRUE;
+} 
+
+// --------------------------------------------------------------------------
+//
+//  This function finds the center position of the circle which gives minimum 
+// RMS of the fit, changing the center position of the circle.
+//
+void MMuonSearchPar::CalcMinimumDeviation
+( const MGeomCam &geom, const MCerPhotEvt &evt, Float_t x, Float_t y, 
+ Float_t xcog, Float_t ycog, Float_t sigma, Float_t &opt_rad, 
+ Float_t &new_sigma, Float_t &newx, Float_t &newy )
+{
+  Float_t delta = 3.;  // 3 mm (1/10 of an inner pixel size) Step to move.
+  Float_t rad_tmp,sig_tmp;
+  Float_t r2;
+
+  while(1) 
+  {
+      r2=(xcog-x)*(xcog-x)+(ycog-y)*(ycog-y);
+      // Exit if the new estimated radius is above 2 deg. (600 mm).
+      if(r2 > 360000.)
+      { 
+	  new_sigma=sigma;
+	  opt_rad=rad_tmp;
+	  newx=x; 
+	  newy=y;
+	  fNoMuon = kTRUE;
+	  break;
+      }
+      if(CalcRadius(geom,evt,x,y+delta,rad_tmp,sig_tmp))
+      {
+	  if(sig_tmp<sigma)
+	  {
+	      sigma=sig_tmp; 
+	      opt_rad=rad_tmp;
+	      y=y+delta;
+	      continue;
+	  }
+      }
+      if(CalcRadius(geom,evt,x-delta,y,rad_tmp,sig_tmp))
+      {
+	  if(sig_tmp<sigma)
+	  {
+	      sigma=sig_tmp; 
+	      opt_rad=rad_tmp;
+	      x=x-delta;
+	      continue;
+	  }
+      }
+      if(CalcRadius(geom,evt,x+delta,y,rad_tmp,sig_tmp))
+      {
+	  if(sig_tmp<sigma)
+	  {
+	      sigma=sig_tmp; 
+	      opt_rad=rad_tmp;
+	      x=x+delta;
+	      continue;
+	  }
+      }
+      if(CalcRadius(geom,evt,x,y-delta,rad_tmp,sig_tmp))
+      {
+	  if(sig_tmp<sigma)
+	  {
+	      sigma=sig_tmp; 
+	      opt_rad=rad_tmp;
+	      y=y-delta;
+	      continue;
+	  }
+      }
+      new_sigma=sigma;
+      newx=x; 
+      newy=y;
+      break;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of muon parameters
+//
+void MMuonSearchPar::Calc
+(const MGeomCam &geom, const MCerPhotEvt &evt, const MHillas &hillas)
+{
+  Reset();
+  
+  Float_t xtmp1,xtmp2,ytmp1,ytmp2;
+  Float_t rad,dev,rad2,dev2;
+  Float_t opt_rad,new_sigma,newx,newy;
+    
+  // gets temporaly center
+  CalcTempCenter(hillas,xtmp1,ytmp1,xtmp2,ytmp2);
+  
+  // determine which position will be the true position. Here mainly
+  // the curvature of a muon arc is relied on.
+  CalcRadius(geom, evt, xtmp1,ytmp1,rad,dev);
+  CalcRadius(geom, evt, xtmp2,ytmp2,rad2,dev2);
+  if(dev2<dev){
+    xtmp1=xtmp2; ytmp1=ytmp2; dev=dev2; rad=rad2;
+  }
+  
+  // find the best fit.
+  CalcMinimumDeviation(geom, evt, xtmp1,ytmp1,hillas.GetMeanX(),
+		       hillas.GetMeanY(), dev, opt_rad, new_sigma, 
+		       newx, newy);
+
+  fRadius = opt_rad;
+  fDeviation = new_sigma;
+  
+  fCenterX = newx;
+  fCenterY = newy;
+  
+  SetReadyToSave();
+} 
+
+void MMuonSearchPar::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Muon Parameters (" << GetName() << ")" << endl;
+    *fLog << " - Est. Radius   [mm]  = " << fRadius  << endl;
+    *fLog << " - Deviation     [mm]  = " << fDeviation  << endl;
+    *fLog << " - Center Pos. X [mm]  = " << fCenterX << endl;
+    *fLog << " - Center Pos. Y [mm]  = " << fCenterY << endl;
+}
+
+void MMuonSearchPar::Print(const MGeomCam &geom, Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Muon Parameters (" << GetName() << ")" << endl;
+    *fLog << " - Est. Radius   [deg.]  = " << fRadius*geom.GetConvMm2Deg()   << endl;
+    *fLog << " - Deviation     [deg.]  = " << fDeviation*geom.GetConvMm2Deg()   << endl;
+    *fLog << " - Center Pos. X [deg.]  = " << fCenterX*geom.GetConvMm2Deg()  << endl;
+    *fLog << " - Center Pos. Y [deg.]  = " << fCenterY*geom.GetConvMm2Deg()  << endl;
+}
+
+
+
Index: /tags/Mars-V0.9/mmuon/MMuonSearchPar.h
===================================================================
--- /tags/Mars-V0.9/mmuon/MMuonSearchPar.h	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MMuonSearchPar.h	(revision 9772)
@@ -0,0 +1,50 @@
+#ifndef MARS_MMuonSearchPar
+#define MARS_MMuonSearchPar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MCerPhotEvt;
+
+class MMuonSearchPar : public MParContainer
+{
+private:
+    Float_t fRadius;    // An estimated radius of the muon ring [mm]
+    Float_t fDeviation; // The standard deviation from the estimated ring [mm]
+    Float_t fCenterX;   // An estimated center position in X of the muon ring [mm]
+    Float_t fCenterY;   // An estimated center position in Y of the muon ring [mm]
+    Bool_t  fNoMuon;    // if the radius is estimated above 600 mm (2 deg.), assumed it's not muon. Later on, at the stage of MMuonCalibParCalc, this flag will be changed if the task judge the event as no muon.
+
+public:
+    MMuonSearchPar(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Float_t GetRadius()    const { return fRadius; }
+    Float_t GetDeviation() const { return fDeviation; }
+    Float_t GetCenterX()   const { return fCenterX; }
+    Float_t GetCenterY()   const { return fCenterY; }
+    Bool_t  IsNoMuon()     const { return fNoMuon; }
+    void    SetNoMuon()          { fNoMuon = kTRUE; }
+
+    void   CalcTempCenter(const MHillas &hillas, Float_t &xtmp1, 
+			  Float_t &ytmp1, Float_t &xtmp2, Float_t &ytmp2);
+    Bool_t CalcRadius(const MGeomCam &geom, const MCerPhotEvt &evt, Float_t x,
+		      Float_t y, Float_t &r, Float_t &sigma);
+    void   CalcMinimumDeviation(const MGeomCam &geom, const MCerPhotEvt &evt, 
+			     Float_t x, Float_t y, Float_t xcog, 
+			     Float_t ycog, Float_t sigma, Float_t &opt_rad, 
+			     Float_t &new_sigma, Float_t &newx, Float_t &newy);
+    void   Calc(const MGeomCam &geom, const MCerPhotEvt &evt,
+		const MHillas &hillas);
+
+    void   Print(Option_t *opt=NULL) const;
+    void   Print(const MGeomCam &geom, Option_t *opt=NULL) const;
+
+    ClassDef(MMuonSearchPar, 1) // Container to hold muon search parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mmuon/MMuonSearchParCalc.cc
===================================================================
--- /tags/Mars-V0.9/mmuon/MMuonSearchParCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MMuonSearchParCalc.cc	(revision 9772)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Keiichi Mase 09/2004 <mailto:mase@mppmu.mpg.de>
+!              Markus Meyer 09/2004 <mailto:meyer@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MMuonSearchParCalc
+//
+// Task to calculate the muon parameters
+//
+//  This class search for muons and store the information into the container 
+// of MMuonSearchPar. The actual calculation is done in the class of 
+// MMuonSearchPar. Please see the manual.
+//
+//  In order to use further information of muons such as the width of arcs,
+// the arc length along it, the muons size. Use the infomation stored in 
+// MMuonCalibPar. The information will be available by using the task of 
+// MMuonCalibParCalc.
+//
+//
+//  Input Containers:
+//   [MGeomCam]
+//   [MHillas]
+//   [MCerPhotEvt]
+//
+//  Output Containers:
+//   [MMuonSearchPar]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MMuonSearchParCalc.h"
+
+#include <fstream>
+
+#include "MParList.h"
+#include "MGeomCam.h"
+#include "MCerPhotEvt.h"
+#include "MMuonSearchPar.h"
+#include "MLog.h"
+#include "MLogManip.h"
+
+using namespace std;
+
+ClassImp(MMuonSearchParCalc);
+
+static const TString gsDefName  = "MMuonSearchParCalc";
+static const TString gsDefTitle = "Calculate muon parameters";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MMuonSearchParCalc::MMuonSearchParCalc
+(const char *mupar, const char *name, const char *title)
+  : fHillas(NULL), fMuonPar(NULL), fCerPhotName("MCerPhotEvt")
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fMuparName  = mupar;
+    fHillasInput = "MHillas";
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MMuonSearchParCalc::PreProcess(MParList *pList)
+{
+    fHillas = (MHillas*)pList->FindObject(fHillasInput, "MHillas");
+    if (!fHillas)
+    {
+        *fLog << err << fHillasInput << " [MHillas] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber(fCerPhotName), "MCerPhotEvt");
+    if (!fCerPhotEvt)
+    {
+        *fLog << err << fCerPhotName << " [MCerPhotEvt] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMuonPar = (MMuonSearchPar*)pList->FindCreateObj("MMuonSearchPar", fMuparName);
+    if (!fMuonPar)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MMuonSearchParCalc::Process()
+{
+
+  fMuonPar->Calc(*fGeomCam, *fCerPhotEvt, *fHillas);
+
+  return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mmuon/MMuonSearchParCalc.h
===================================================================
--- /tags/Mars-V0.9/mmuon/MMuonSearchParCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MMuonSearchParCalc.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifndef MARS_MMuonSearchParCalc
+#define MARS_MMuonSearchParCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MHillas;
+class MMuonSearchPar;
+class MGeomCam;
+class MCerPhotEvt;
+
+class MMuonSearchParCalc : public MTask
+{
+private:
+    MGeomCam    *fGeomCam;
+    MCerPhotEvt *fCerPhotEvt;
+    MHillas     *fHillas;      //! Pointer to the source independent hillas parameters
+    MMuonSearchPar *fMuonPar;  //! Pointer to the output container for the new image parameters
+
+    TString fMuparName;
+    TString fHillasInput;
+    TString fCerPhotName;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+public:
+    MMuonSearchParCalc(const char *mupar="MMuonSearchPar",
+		       const char *name=NULL, const char *title=NULL);
+
+    void SetInput(TString hilname) { fHillasInput = hilname; }
+
+    void SetNameCerPhotEvt(const char *name) { fCerPhotName = name; }
+
+    ClassDef(MMuonSearchParCalc, 0) // task to calculate muon parameters
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mmuon/Makefile
===================================================================
--- /tags/Mars-V0.9/mmuon/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/Makefile	(revision 9772)
@@ -0,0 +1,47 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Muon
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mmc -I../mraw -I../mgeom -I../mfilter \
+	   -I../mdata -I../mhbase -I../mhist -I../mgui -I../mimage   \
+           -I../mhistmc -I../mfileio -I../mmain -I../mhcalib -I../mcalib \
+           -I../msignal -I../mpointing -I../mtools -I../mfbase       \
+           -I../mbadpixels -I../mastro -I../mpedestal -I../manalysis
+
+SRCFILES = MMuonSearchPar.cc \
+           MMuonSearchParCalc.cc \
+           MMuonCalibPar.cc \
+           MMuonCalibParCalc.cc 
+
+############################################################
+
+all:  $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mmuon/MuonIncl.h
===================================================================
--- /tags/Mars-V0.9/mmuon/MuonIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MuonIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mmuon/MuonLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mmuon/MuonLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mmuon/MuonLinkDef.h	(revision 9772)
@@ -0,0 +1,19 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MMuonSearchPar+;
+#pragma link C++ class MMuonSearchParCalc+;
+#pragma link C++ class MMuonCalibPar+;
+#pragma link C++ class MMuonCalibParCalc+;
+
+#endif
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mona.cc
===================================================================
--- /tags/Mars-V0.9/mona.cc	(revision 9772)
+++ /tags/Mars-V0.9/mona.cc	(revision 9772)
@@ -0,0 +1,347 @@
+#include <TApplication.h>
+
+#include <TThread.h>
+#include <TCanvas.h>
+#include <TMethod.h>          // GetMenuItems
+
+#include <TGButton.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MLogManip.h"
+
+#include "MRawSocketRead.h"
+#include "MGeomApply.h"
+#include "MCerPhotAnal2.h"
+#include "MFillH.h"
+#include "MFRealTimePeriod.h"
+#include "MHTriggerLvl0.h"
+#include "MHCamera.h"         // ::Class(), SetFreezed
+#include "MHCamEvent.h"       // MHCamEvent
+#include "MHEvent.h"          // MHEvent::GetHist()
+
+#include "MOnlineDump.h"
+#include "MOnlineDisplay.h"
+
+#include "MImgCleanStd.h"
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+#include "MEventRateCalc.h"
+
+#include "MArgs.h"
+
+// --------------------------------------------------------------------
+
+#include "MTime.h"
+#include "MRawEvtHeader.h"       // MRawEvtHeader
+#include "MRawRunHeader.h"       // MRawRunHeader
+
+using namespace std;
+
+void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "                    MONA V" << MARSVER << "                      " << endl;
+    gLog << "              Magic Online Analysis               " << endl;
+    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
+    gLog << "               Using ROOT v" << ROOTVER             << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+void Remove(TMethod *m, const char *name)
+{
+    if (TString(m->GetName()).BeginsWith(name))
+        m->SetMenuItem(kMenuNoMenu);
+}
+
+void ChangeContextMenus()
+{
+    TList l;
+    MHCamera::Class()->GetMenuItems(&l);
+    TIter Next(&l);
+    TMethod *m=NULL;
+    while ((m=(TMethod*)Next()))
+    {
+        Remove(m, "DrawClone");
+        Remove(m, "SetName");
+        Remove(m, "Delete");
+        Remove(m, "DrawClass");
+        Remove(m, "Dump");
+        Remove(m, "Inspect");
+        Remove(m, "Smooth");
+        Remove(m, "Fit");
+        Remove(m, "Divide");
+        Remove(m, "Add");
+        Remove(m, "Multiply");
+        Remove(m, "Delete");
+        Remove(m, "SetLineAttributes");
+        Remove(m, "SetFillAttributes");
+        Remove(m, "SetMarkerAttributes");
+        Remove(m, "SetDrawOption");
+    }
+}
+
+#include "MPedPhotCam.h"
+Bool_t Loop(MOnlineDisplay *display, Int_t port)
+{
+    display->Reset();
+
+    //
+    // create the tasks which should be executed and add them to the list
+    // in the case you don't need parameter containers, all of them can
+    // be created by MRawFileRead::PreProcess
+    //
+    MRawSocketRead reader;
+    reader.SetPort(port);
+
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    //
+    MParList plist;
+
+    MTaskList tasks;
+    plist.AddToList(&tasks);
+    tasks.AddToList(&reader);
+
+    MPedPhotCam pcam;
+    plist.AddToList(&pcam);
+
+    MGeomApply geomapl;
+    MCerPhotAnal2 ncalc;
+    tasks.AddToList(&geomapl);
+    tasks.AddToList(&ncalc);
+
+    MEventRateCalc tcalc;
+    tcalc.SetNumEvents(100);
+    tasks.AddToList(&tcalc);
+
+    MFillH fill1("MHEvent",    "MCerPhotEvt", "MFillEvent");
+    MFillH fill2("MHCamEvent", "MCerPhotEvt", "MFillCamEvent");
+
+    MFRealTimePeriod filter;
+    fill1.SetFilter(&filter);
+
+    MHTriggerLvl0 trigmap(128, "Above 128");
+    MFillH fill3(&trigmap, "MRawEvtData", "MFillTriggerLvl0");
+
+    tasks.AddToList(&filter);
+
+    tasks.AddToList(&fill1);
+    tasks.AddToList(&fill2);
+    tasks.AddToList(&fill3);
+
+    MHCamEvent hist("PedestalRms");
+    hist.SetType(1);
+    plist.AddToList(&hist);
+
+    // -------------------------------------------
+
+    MHCamEvent maxhi("MaxIdxHi", "Index of slice with maximum content (hi-gain)");
+    MHCamEvent maxlo("MaxIdxLo", "Index of slice with maximum content (lo-gain)");
+    maxhi.SetType(3);
+    maxlo.SetType(4);
+    plist.AddToList(&maxhi);
+    plist.AddToList(&maxlo);
+
+    // -------------------------------------------
+
+    MFillH hfilla("MaxIdxHi", "MRawEvtData", "FillMaxIdxHi");
+    MFillH hfillb("MaxIdxLo", "MRawEvtData", "FillMaxIdxLo");
+    MFillH hfillc("Pedestals [MHCamEvent]", "MPedPhotCam", "FillPedestal");
+    MFillH hfilld("PedestalRms", "MPedPhotCam", "FillPedestalRms");
+    tasks.AddToList(&hfilla);
+    tasks.AddToList(&hfillb);
+    tasks.AddToList(&hfillc);
+    tasks.AddToList(&hfilld);
+
+    MOnlineDump dump;
+    dump.SetFilter(&filter);
+    display->SetTask(&dump);
+    tasks.AddToList(&dump);
+
+
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+    MFillH hfill3("MHHillas",   "MHillas",    "MFillHillas");
+    MFillH hfill4("MHHillasSrc","MHillasSrc", "MFillHillasSrc");
+    tasks.AddToList(&clean);
+    tasks.AddToList(&hcalc);
+    tasks.AddToList(&scalc);
+    tasks.AddToList(&hfill3);
+    tasks.AddToList(&hfill4);
+
+    MEvtLoop magic;
+    magic.SetParList(&plist);
+
+    magic.SetDisplay(display);
+    magic.SetProgressBar((TGProgressBar*)NULL);
+
+    if (!magic.Eventloop())
+    {
+        gLog << err << "Mona Eventloop error..." << endl;
+        return kFALSE;
+    }
+
+    tasks.PrintStatistics();
+    return kTRUE;
+}
+
+//
+// By defining the function return type 'void' instead of
+// 'void*' we tell TThread to create a detached thread,
+// but calling Exit() in a detached thread results in a crash
+// when the TGApplication is terminated.
+//
+void *thread(void *ptr)
+{
+    const Int_t port = *((Int_t**)ptr)[0];
+    MOnlineDisplay &d = *((MOnlineDisplay**)ptr)[1];
+
+    //
+    // If a loop is stopped reinitialize a new loop until the
+    // user requested to exit the program.
+    //
+    while (d.CheckStatus()!=MStatusDisplay::kFileExit)
+        Loop(&d, port);
+
+
+    gLog << dbg << "Loop stopped... exit thread()" << endl;
+
+    return 0;
+}
+
+/*
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,02)
+#include <TRootGuiFactory.h>
+#include <TPluginManager.h>
+void InitGuiFactory()
+{
+   if (gROOT->IsBatch())
+       gROOT->SetBatch(kFALSE);
+
+    //
+    // Must be loaded by hand, because it is not loaded by TGApplication.
+    // We could also use TApplication instead, but TApplication doesn't
+    // deal with the DISPLAY variable in a convient way.
+    //
+    TPluginHandler *h;
+    if ((h = gROOT->GetPluginManager()->FindHandler("TGuiFactory", "root")))
+    {
+        if (h->LoadPlugin() == -1)
+            return;
+        gGuiFactory = (TGuiFactory*)h->ExecPlugin(0);
+    }
+}
+#endif
+*/
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   mona [-?] [-h] [-a0] [-h] [-pn] [-vn]" << endl << endl;
+    gLog << "     -a0: Do not use Ansii codes." << endl;
+    gLog << "     -pn: TCP/IP port n [default=7000]" << endl;
+    gLog << "     -vn: Verbosity level n [default=2]" << endl << endl;
+    gLog << "     -?/-h: This help" << endl << endl;
+}
+
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+
+    if (arg.HasOption("-?") || arg.HasOption("-h"))
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Set verbosity to highest level.
+    //
+    gLog.SetDebugLevel(arg.HasOption("-v") ? arg.GetIntAndRemove("-v") : 2);
+
+    if (arg.HasOption("-a") && arg.GetIntAndRemove("-a")==0)
+        gLog.SetNoColors();
+
+    const Int_t port = arg.HasOption("-p") ? arg.GetIntAndRemove("-p") : 7000;
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()>0)
+    {
+        Usage();
+        return -1;
+    }
+
+    TApplication app("Mona", &argc, argv);
+    if (gROOT->IsBatch() || !gClient)
+    {
+        gLog << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    /*
+    TGApplication app("Mona", &argc, argv);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,10,02)
+    InitGuiFactory();
+#endif
+    */
+
+    ChangeContextMenus();
+
+    //
+    // Starting MStatusDisplay in the thread results in hangs
+    // if the thread is terminated (by return)
+    //
+    gLog << dbg << "Starting Display..." << flush;
+    MOnlineDisplay d;
+    d.SetWindowName("Magic ONline Analysis");
+    d.SetIconName("Mona");
+
+    d.SetBit(MStatusDisplay::kExitLoopOnExit);
+    gLog << "done." << endl;
+
+    // gDebug=1;
+
+    gLog << dbg << "Starting Thread..." << flush;
+    const void *ptr[2] = { &port, &d };
+    TThread t(thread, ptr);
+    t.Run();
+    gLog << "done." << endl;
+
+    gLog << dbg << "Starting System loop... " << endl;
+    app.Run(kTRUE);
+    gLog << dbg << "System loop stopped." << endl;
+
+    d.UnmapWindow();
+
+    gLog << dbg << "Waiting for termination of thread... (be patient)" << endl;
+    while (t.GetState()!=TThread::kCanceledState)
+        gSystem->ProcessEvents();
+
+    gLog << dbg << "Thread terminated... joining." << endl;
+
+    TThread::Join(t.GetId()); //- seems that it is implicitly done... why?
+
+    gLog << dbg << "Exit MONA." << endl;
+
+    return 0;
+}
Index: /tags/Mars-V0.9/mpedestal/MExtractPedestal.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MExtractPedestal.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MExtractPedestal.cc	(revision 9772)
@@ -0,0 +1,689 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 01/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+// 
+//   MExtractPedestal
+//
+//  Pedestal Extractor base class
+//
+//  Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MGeomCam
+//   MPedestalCam
+//
+//  Output Containers:
+//   MPedestalCam
+//
+//  This class should be used for pedestal extractors with the following facilities:
+//  a) Standardized calculation of AB-noise, mean pedestals and RMS
+//  b) Standardized treatment of area- and sector averaged pedestals values
+//  c) Possibility to use a signal extractor to be applied on the pedestals
+//  d) Possibility to handle two MPedestalCams: one for the signal extractor and 
+//     a second to be filled during the pedestal calculating process.  
+//
+//  ad a): Every calculated value is referred to one FADC slice (e.g. Mean pedestal per slice),
+//         RMS per slice. 
+//         MExtractPedestal applies the following formula (1):
+// 
+//         Pedestal per slice = sum(x_i) / n / slices
+//         PedRMS per slice   = Sqrt(  ( sum(x_i^2) - sum(x_i)^2/n ) / n-1 / slices )
+//         AB-Offset per slice = (sumAB0 - sumAB1) / n / slices 
+//
+//         where x_i is the sum of "slices" FADC slices and sum means the sum over all
+//         events. "n" is the number of events, "slices" is the number of summed FADC samples.
+// 
+//         Note that the slice-to-slice fluctuations are not Gaussian, but Poissonian, thus 
+//         asymmetric and they are correlated.
+// 
+//         It is important to know that the Pedestal per slice and PedRMS per slice depend 
+//         on the number of used FADC slices, as seen in the following plots:
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyInner.gif">
+*/
+//End_Html
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyOuter.gif">
+*/
+//End_Html
+//
+//        The plots show the inner and outer pixels, respectivly and have the following meaning:
+// 
+//        1) The calculated mean pedestal per slice (from MPedCalcPedRun)
+//        2) The fitted mean pedestal per slice     (from MHPedestalCam)
+//        3) The calculated pedestal RMS per slice  (from MPedCalcPedRun)
+//        4) The fitted sigma of the pedestal distribution per slice
+//                                                  (from MHPedestalCam)
+//        5) The relative difference between calculation and histogram fit
+//           for the mean
+//        6) The relative difference between calculation and histogram fit
+//           for the sigma or RMS, respectively.
+// 
+//        The calculated means do not change significantly except for the case of 2 slices, 
+//        however the RMS changes from 5.7 per slice in the case of 2 extracted slices 
+//        to 8.3 per slice in the case of 26 extracted slices. This change is very significant.
+// 
+// ad b)  Every calculated value is referred to one FADC slice and one (averaged) pixel,
+//        (e.g. Mean Pedestal per area index per slice per pixel, etc. )
+//
+//         MExtractPedestal applies the following formula (2):
+// 
+//         Averaged Pedestal per slice = sum(x_i) / n / slices / n_pix
+//         PedRMS per slice   = Sqrt(  ( sum(x_i^2) - sum(x_i)^2/n ) / n-1 / slices / n_pix )
+//         AB-Offset per slice = (sumAB0 - sumAB1) / n / slices / n_pix
+//
+//         where x_i is the sum of "slices" FADC slices and sum means the sum over all
+//         events and all concerned pixels. 
+//         "n" is the number of events, "slices" is the number of summed FADC samples and
+//         "n_pix" is the number of pixels belonging to the specific area index or camera sector. 
+// 
+//         Calculating these averaged event-by-event values is very important to trace coherent
+//         fluctuations. An example is given in the following plots:
+//
+//Begin_Html
+/*
+<img src="images/PedestalOscillations.gif">
+*/
+//End_Html
+//
+//        The plots show the extracted pedestals of the inner pixels (obtained
+//        with MHPedestalCam), averaged on an event-by-event basis from 
+//        run 13428 with switched off camera LV. 
+//        The meaning of the four plots is:
+// 
+//        1) The distribution of the averaged pedestals
+//        2) The averaged pedestals vs. time. 
+//           One can see clearly the oscillation pattern
+//        3) The fourier transform of the averaged pedestals vs. time. 
+//           One can see clearly a peak at a certain frequency
+//        4) The projection of the fourier components with the non-exponential
+//           (and therefore significant) outlier.
+//
+//    ad c) Many signal extractors, especially those using a sliding window
+//          have biases and their resolutions for zero-signals do not agree 
+//          with the pedestal RMS. For the F-Factor method in the calibration
+//          and the image cleaning, however, both have to be known and measured. 
+//          
+//          For this reason, a signal extractor can be handed over to the 
+//          pedestal extractor and applied on the pedestal events with the 
+//          function SetExtractor(). 
+//          The results will get stored in an MPedestalCam. 
+//        
+//          Note that only extractors deriving from MExtractTimeAndCharge
+//          can be used.
+//
+//   ad d)  The signal extractors themselves need a pedestal to be subtracted 
+//          from the FADC slices. 
+//          If the user wishes that the pededestals do not get overwritten by 
+//          the results from the signal extractor, a different named MPedestalCam
+//          can be created with the function: SetNamePedestalOut(). 
+//
+//  See also: MPedestalCam, MPedestalPix, MPedCalcPedRun, MPedCalcFromLoGain
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractPedestal.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"  
+#include "MRawEvtHeader.h"  
+#include "MRawEvtPixelIter.h"
+#include "MRawEvtData.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MTaskEnv.h"
+#include "MExtractTimeAndCharge.h"
+
+ClassImp(MExtractPedestal);
+
+using namespace std;
+
+const TString MExtractPedestal::fgNamePedestalCam = "MPedestalCam";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor: 
+//
+// Sets:
+// - all pointers to NULL
+//
+// 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)
+{
+    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  );
+
+    SetNamePedestalCamIn();
+    SetNamePedestalCamOut();
+    SetNumDump();
+
+    Clear();
+}
+
+void MExtractPedestal::ResetArrays()
+{
+    // Reset contents of arrays.
+    fSumx.Reset();
+    fSumx2.Reset();
+    fSumAB0.Reset();
+    fSumAB1.Reset();
+    fAreaSumx.Reset();
+    fAreaSumx2.Reset();
+    fAreaSumAB0.Reset();
+    fAreaSumAB1.Reset();
+    fAreaFilled.Reset();
+    fAreaValid.Reset();
+    fSectorSumx.Reset();
+    fSectorSumx2.Reset();
+    fSectorSumAB0.Reset();
+    fSectorSumAB1.Reset();
+    fSectorFilled.Reset();
+    fSectorValid.Reset();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Resets Arrays:
+//
+// Sets:
+// - fRawEvt to NULL
+// - fRunHeader to NULL
+// - fEvtHeader to NULL
+//
+void MExtractPedestal::Clear(const Option_t *o)
+{
+ 
+  fRawEvt       = NULL;
+  fRunHeader    = NULL;
+  fEvtHeader    = NULL;
+
+  // If the size is yet set, set the size
+  if (fSumx.GetSize()>0)
+    ResetArrays();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is odd
+// 
+Bool_t MExtractPedestal::SetExtractWindow(UShort_t windowf, UShort_t windows)
+{
+
+  Bool_t rc = kTRUE;
+
+  const Int_t odd  = windows & 0x1;
+  
+  if (odd && !fExtractor)
+  {
+      *fLog << warn << GetDescriptor();
+      *fLog << " - WARNING: Window size in SetExtractWindow has to be even... ";
+      *fLog << " raising from " << windows << " to ";
+      windows += 1;
+      *fLog << windows << "!" << endl;
+      rc = kFALSE;
+  }
+
+  if (windows==0)
+  {
+      *fLog << warn << GetDescriptor();
+      *fLog << " - WARNING: Window size in SetExtractWindow has to be > 0... adjusting to 2!" << endl;
+      windows = 2;
+      rc = kFALSE;
+  }
+
+  fExtractWinSize  = windows;
+  fExtractWinFirst = windowf;
+  fExtractWinLast  = fExtractWinFirst+fExtractWinSize-1;
+  
+  return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Look for the following input containers:
+//
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MRawEvtHeader
+//  - MGeomCam
+// 
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedestalCam with the name fPedContainerName
+//
+Int_t MExtractPedestal::PreProcess(MParList *pList)
+{
+
+  Clear();
+  
+  fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+  if (!fRawEvt)
+  {
+      *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+  
+  fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+  if (!fRunHeader)
+  {
+      *fLog << err << AddSerialNumber("MRawRunHeader") << " not found... aborting." << endl;
+      return kFALSE;
+  }
+  
+  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;
+  }
+
+  if (fExtractor && !fPedestalsIn)
+  {
+      fPedestalsIn = (MPedestalCam*)pList->FindObject(AddSerialNumber(fNamePedestalCamIn), "MPedestalCam");
+      if (!fPedestalsIn)
+      {
+          *fLog << err << AddSerialNumber(fNamePedestalCamIn) << " not found... aborting." << endl;
+          return kFALSE;
+      }
+  }
+
+  if (!fPedestalsInter && fIntermediateStorage)
+  {
+      fPedestalsInter = (MPedestalCam*)pList->FindCreateObj("MPedestalCam", AddSerialNumber(fNamePedestalCamInter));
+      if (!fPedestalsInter)
+          return kFALSE;
+  }
+
+  if (!fPedestalsOut)
+  {
+      fPedestalsOut = (MPedestalCam*)pList->FindCreateObj("MPedestalCam", AddSerialNumber(fNamePedestalCamOut));
+      if (!fPedestalsOut)
+          return kFALSE;
+  }
+
+  *fLog << inf;
+  Print();
+
+  return fExtractor ? fExtractor->CallPreProcess(pList) : kTRUE;
+}
+
+Int_t MExtractPedestal::Process()
+{
+    if (fExtractor)
+        fExtractor->SetNoiseCalculation(fRandomCalculation);
+
+    const Int_t rc = Calc();
+
+    if (fExtractor)
+        fExtractor->SetNoiseCalculation(kFALSE);
+
+    return rc;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Sets the size (from MPedestalCam::GetSize() ) and resets the following arrays:
+//  - fSumx
+//  - fSumx2
+//  - fSumAB0
+//  - fSumAB1
+//  - fAreaSumx
+//  - fAreaSumx2
+//  - fAreaSumAB0
+//  - fAreaSumAB1
+//  - fAreaFilled
+//  - fAreaValid 
+//  - fSectorSumx 
+//  - fSectorSumx2
+//  - fSectorSumAB0
+//  - fSectorSumAB1
+//  - fSectorFilled
+//  - fSectorValid
+//
+Bool_t MExtractPedestal::ReInit(MParList *pList)
+{
+  // If the size is not yet set, set the size
+  if (fSumx.GetSize()==0)
+  {
+      const Int_t npixels  = fPedestalsOut->GetSize();
+      const Int_t areas    = fPedestalsOut->GetNumAverageArea();
+      const Int_t sectors  = fPedestalsOut->GetNumAverageSector();
+
+      fSumx.  Set(npixels);
+      fSumx2. Set(npixels);
+      fSumAB0.Set(npixels);
+      fSumAB1.Set(npixels);
+
+      fAreaSumx.  Set(areas);
+      fAreaSumx2. Set(areas);
+      fAreaSumAB0.Set(areas);
+      fAreaSumAB1.Set(areas);
+      fAreaFilled.Set(areas);
+      fAreaValid .Set(areas);
+
+      fSectorSumx.  Set(sectors);
+      fSectorSumx2. Set(sectors);
+      fSectorSumAB0.Set(sectors);
+      fSectorSumAB1.Set(sectors);
+      fSectorFilled.Set(sectors);
+      fSectorValid .Set(sectors);
+
+      for (Int_t i=0; i<npixels; i++)
+      {
+          const UInt_t aidx   = (*fGeom)[i].GetAidx();
+          const UInt_t sector = (*fGeom)[i].GetSector();
+
+          fAreaValid  [aidx]  ++;
+          fSectorValid[sector]++;
+      }
+  }
+
+  if (fExtractor)
+  {
+    if (!((MTask*)fExtractor)->ReInit(pList))
+        return kFALSE;
+
+      if (!fExtractor->InitArrays())
+          return kFALSE;
+
+      SetExtractWindow(fExtractor->GetHiGainFirst(), (Int_t)TMath::Nint(fExtractor->GetNumHiGainSamples()));
+  }
+
+  return kTRUE;
+}
+
+Int_t MExtractPedestal::PostProcess()
+{
+  fPedestalsIn = NULL;
+  return fExtractor ? fExtractor->CallPostProcess() : kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  The following resources are available:
+//    ExtractWindowFirst:    15
+//    ExtractWindowSize:      6
+//    NumEventsDump:        500
+//    PedestalUpdate:       yes
+//    RandomCalculation:    yes
+//
+Int_t MExtractPedestal::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc=kFALSE;
+
+    // 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;
+    }
+
+    if (IsEnvDefined(env, prefix, "IntermediateStorage", print))
+    {
+        SetIntermediateStorage(GetEnvValue(env, prefix, "IntermediateStorage", fIntermediateStorage));
+        rc = kTRUE;
+    }
+
+    // find resource for random calculation
+    if (IsEnvDefined(env, prefix, "RandomCalculation", print))
+    {
+        SetRandomCalculation(GetEnvValue(env, prefix, "RandomCalculation", fRandomCalculation));
+        rc = kTRUE;
+    }
+
+    // Find resources for ExtractWindow
+    Int_t ef = fExtractWinFirst;
+    Int_t es = fExtractWinSize;
+    if (IsEnvDefined(env, prefix, "ExtractWinFirst", print))
+    {
+        ef = GetEnvValue(env, prefix, "ExtractWinFirst", ef);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "ExtractWinSize", print))
+    {
+        es = GetEnvValue(env, prefix, "ExtractWinSize", es);
+        rc = kTRUE;
+    }
+
+    SetExtractWindow(ef,es);
+
+    // find resource for MPedestalCam
+    if (IsEnvDefined(env, prefix, "NamePedestalCamIn", print))
+    {
+        SetNamePedestalCamIn(GetEnvValue(env, prefix, "NamePedestalCamIn", fNamePedestalCamIn));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "NamePedestalCamInter", print))
+    {
+        SetNamePedestalCamInter(GetEnvValue(env, prefix, "NamePedestalCamInter", fNamePedestalCamInter));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "NamePedestalCamOut", print))
+    {
+        SetNamePedestalCamOut(GetEnvValue(env, prefix, "NamePedestalCamOut", fNamePedestalCamOut));
+        rc = kTRUE;
+    }
+
+    return rc;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Calculates for pixel "idx":
+//
+// Ped per slice      = sum / n / fExtractWinSize;
+// RMS per slice      = sqrt { (sum2 -  sum*sum/n) / (n-1) / fExtractWinSize }
+// ABOffset per slice = (fSumAB0[idx] - fSumAB1[idx]) / n / fExtractWinSize;
+//
+// Stores the results in MPedestalCam[pixid]
+//
+void MExtractPedestal::CalcPixResults(const UInt_t nevts, const UInt_t pixid)
+{
+    const Float_t sum  = fSumx[pixid];
+    const Float_t sum2 = fSumx2[pixid];
+
+    // 1. Calculate the mean of the sums:
+    Float_t ped        = sum/nevts;
+
+    // 2. Calculate the Variance of the sums:
+    Float_t var = (sum2-sum*sum/nevts)/(nevts-1.);
+
+    // 3. Calculate the amplitude of the 150MHz "AB" noise
+    Float_t abOffs = (fSumAB0[pixid] - fSumAB1[pixid]) / nevts;
+
+    // 4. Scale the mean, variance and AB-noise to the number of slices:
+    ped    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+
+    // 5. Calculate the RMS from the Variance:
+    const Float_t rms = var<0 ? 0 : TMath::Sqrt(var);
+
+    (*fPedestalsOut)[pixid].Set(ped, rms, abOffs, nevts);
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Calculates for area idx "aidx" with "napix" valid pixels:
+//
+// Ped per slice      = sum / nevts / fExtractWinSize / napix;
+// RMS per slice      = sqrt { (sum2 -  sum*sum/nevts) / (nevts-1) / fExtractWinSize / napix }
+// ABOffset per slice = (fSumAB0[idx] - fSumAB1[idx]) / nevts / fExtractWinSize / napix;
+//
+// Stores the results in MPedestalCam::GetAverageArea(aidx)
+//
+void MExtractPedestal::CalcAreaResults(const UInt_t nevts, const UInt_t napix, const UInt_t aidx)
+{
+    const Float_t sum  = fAreaSumx[aidx];
+    const Float_t sum2 = fAreaSumx2[aidx];
+
+    // 1. Calculate the mean of the sums:
+    Float_t ped        = sum/nevts;
+
+    // 2. Calculate the Variance of the sums:
+    Float_t var = (sum2-sum*sum/nevts)/(nevts-1.);
+
+    // 3. Calculate the amplitude of the 150MHz "AB" noise
+    Float_t abOffs = (fAreaSumAB0[aidx] - fAreaSumAB1[aidx]) / nevts;
+
+    // 4. Scale the mean, variance and AB-noise to the number of slices:
+    ped    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+
+    // 5. Scale the mean, variance and AB-noise to the number of pixels:
+    ped    /= napix;
+    var    /= napix;
+    abOffs /= napix;
+
+    // 6. Calculate the RMS from the Variance:
+    const Float_t rms = var<0 ? 0 : TMath::Sqrt(var);
+
+    fPedestalsOut->GetAverageArea(aidx).Set(ped, rms, abOffs, nevts);
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Calculates for sector idx "sector" with "nspix" valid pixels:
+//
+// Ped per slice      = sum / nevts / fExtractWinSize / nspix;
+// RMS per slice      = sqrt { (sum2 -  sum*sum/nevts) / (nevts-1) / fExtractWinSize / nspix }
+// ABOffset per slice = (fSumAB0[idx] - fSumAB1[idx]) / nevts / fExtractWinSize / nspix;
+//
+// Stores the results in MPedestalCam::GetAverageSector(sector)
+//
+void MExtractPedestal::CalcSectorResults(const UInt_t nevts, const UInt_t nspix, const UInt_t sector)
+{
+    const Float_t sum  = fSectorSumx[sector];
+    const Float_t sum2 = fSectorSumx2[sector];
+
+    // 1. Calculate the mean of the sums:
+    Float_t ped        = sum/nevts;
+
+    // 2. Calculate the Variance of the sums:
+    Float_t var = (sum2-sum*sum/nevts)/(nevts-1.);
+
+    // 3. Calculate the amplitude of the 150MHz "AB" noise
+    Float_t abOffs = (fSectorSumAB0[sector] - fSectorSumAB1[sector]) / nevts;
+
+    // 4. Scale the mean, variance and AB-noise to the number of slices:
+    ped    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    var    /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+    abOffs /= fExtractor ? fExtractor->GetNumHiGainSamples() : fExtractWinSize;
+
+    // 5. Scale the mean, variance and AB-noise to the number of pixels:
+    ped    /= nspix;
+    var    /= nspix;
+    abOffs /= nspix;
+
+    // 6. Calculate the RMS from the Variance:
+    const Float_t rms = var<0 ? 0 : TMath::Sqrt(var);
+
+    fPedestalsOut->GetAverageSector(sector).Set(ped, rms, abOffs, nevts);
+}
+
+void MExtractPedestal::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << "Name of input  MPedestalCam:  " << (fPedestalsIn?fPedestalsIn->GetName():fNamePedestalCamIn.Data()) << " (" << fPedestalsIn << ")" << endl;
+    *fLog << "Name of interm. MPedestalCam: " << (fPedestalsInter?fPedestalsInter->GetName():fNamePedestalCamInter.Data()) << " (" << fPedestalsInter << ")" << endl;
+    *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;
+    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)
+    {
+        *fLog << "Extractor used:               " << fExtractor->ClassName() << " (";
+        *fLog << (fRandomCalculation?"":"non-") << "random)" << endl;
+    }
+}
Index: /tags/Mars-V0.9/mpedestal/MExtractPedestal.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MExtractPedestal.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MExtractPedestal.h	(revision 9772)
@@ -0,0 +1,122 @@
+#ifndef MARS_MExtractPedestal
+#define MARS_MExtractPedestal
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MArrayD
+#include <MArrayD.h>
+#endif
+
+#ifndef MARS_MArrayI
+#include <MArrayI.h>
+#endif
+
+class MGeomCam;
+class MPedestalCam;
+class MRawEvtData;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MExtractTimeAndCharge;
+
+class MExtractPedestal : public MTask
+{
+private:
+  static const TString  fgNamePedestalCam;  //! "MPedestalCam"
+
+  TString fNamePedestalCamIn;        // Name of the incoming 'MPedestalCam' container
+  TString fNamePedestalCamOut;       // Name of the outgoing 'MPedestalCam' container
+  TString fNamePedestalCamInter;     // Name of the intermediate 'MPedestalCam' container  
+
+  Bool_t  fRandomCalculation;        // Is pedestalextraction by extractor random?
+  
+protected:
+  
+  Bool_t  fIntermediateStorage;      // Is pedestal stored every event?
+
+  MGeomCam      *fGeom;              //! Camera geometry
+  MPedestalCam  *fPedestalsIn;       //! Pedestals of all pixels in the camera (incoming)
+  MPedestalCam  *fPedestalsInter;    //! Pedestals of all pixels in the camera (intermediate)
+  MPedestalCam  *fPedestalsOut;      //! Pedestals of all pixels in the camera (outgoing)
+  MRawEvtData   *fRawEvt;            //! Raw event data (time slices)
+  MRawRunHeader *fRunHeader;         //! RunHeader information
+  MRawEvtHeader *fEvtHeader;         //! EvtHeader information
+  MExtractTimeAndCharge *fExtractor; //  Possible Extractor
+  
+  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
+
+  MArrayD fSumx;                     // sum of values
+  MArrayD fSumx2;                    // sum of squared values
+  MArrayD fSumAB0;                   // sum of ABFlag=0 slices
+  MArrayD fSumAB1;                   // sum of ABFlag=1 slices
+  MArrayD fAreaSumx;                 // averaged sum of values per area idx
+  MArrayD fAreaSumx2;                // averaged sum of squared values per area idx
+  MArrayD fAreaSumAB0;               // averaged sum of ABFlag=0 slices per area idx
+  MArrayD fAreaSumAB1;               // averaged sum of ABFlag=1 slices per area idx
+  MArrayI fAreaFilled;               // number of valid entries with area idx
+  MArrayI fAreaValid;                // number of valid pixels  within area idx
+  MArrayD fSectorSumx;               // averaged sum of values per sector
+  MArrayD fSectorSumx2;              // averaged sum of squared values per sector
+  MArrayD fSectorSumAB0;             // averaged sum of ABFlag=0 slices per sector
+  MArrayD fSectorSumAB1;             // averaged sum of ABFlag=1 slices per sector 
+  MArrayI fSectorFilled;             // number of valid entries with sector idx
+  MArrayI fSectorValid;              // number of valid pixels within sector idx
+
+  // MTask virtual functions
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  PostProcess();
+  Bool_t ReInit(MParList *pList);
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+  // Interface to be overwritten by a new class
+  virtual void  ResetArrays();
+  virtual Int_t Calc() = 0;
+
+  // Helper functions
+  void CalcPixResults   (const UInt_t nevts, const UInt_t pixid);
+  void CalcAreaResults  (const UInt_t nevts, const UInt_t napix, const UInt_t aidx);
+  void CalcSectorResults(const UInt_t nevts, const UInt_t nspix, const UInt_t sector);
+
+public:
+  MExtractPedestal(const char *name=NULL, const char *title=NULL);
+
+  void Clear(const Option_t *o="");
+  void Print(const Option_t *o="") const;
+
+  Bool_t SetExtractWindow(UShort_t first, UShort_t size);
+
+  void SetNumEventsDump (UInt_t dumpevents=500)  { fNumEventsDump  = dumpevents; }
+  void SetNumAreasDump  (UInt_t dumpevents=500)  { fNumAreasDump   = dumpevents; }
+  void SetNumSectorsDump(UInt_t dumpevents=500)  { fNumSectorsDump = dumpevents; }
+  void SetNumDump       (UInt_t n=500) { fNumEventsDump=n; fNumAreasDump=n; fNumSectorsDump=n; }
+
+  // names
+  void SetNamePedestalCamIn   (const char *name=fgNamePedestalCam.Data()) { fNamePedestalCamIn    = name; }
+  void SetNamePedestalCamInter(const char *name=fgNamePedestalCam.Data()) { fNamePedestalCamInter = name; }  
+  void SetNamePedestalCamOut  (const char *name=fgNamePedestalCam.Data()) { fNamePedestalCamOut   = name; }
+
+  // pointers
+  void SetExtractor     ( MExtractTimeAndCharge *e) { fExtractor      = e; }
+  void SetPedestalsIn   ( MPedestalCam *pedcam    ) { fPedestalsIn    = pedcam; }
+  void SetPedestalsInter( MPedestalCam *pedcam    ) { fPedestalsInter = pedcam; }
+  void SetPedestalsOut  ( MPedestalCam *pedcam    ) { fPedestalsOut   = pedcam; }
+
+  // flags
+  void SetIntermediateStorage (Bool_t b=kTRUE) { fIntermediateStorage = b; }
+  void SetPedestalUpdate      (Bool_t b=kTRUE) { fPedestalUpdate      = b; }
+  void SetRandomCalculation   (Bool_t b=kTRUE) { fRandomCalculation   = b; }
+
+  ClassDef(MExtractPedestal, 0)   // Base class for pedestal extractors
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/MHPedestalCam.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MHPedestalCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MHPedestalCam.cc	(revision 9772)
@@ -0,0 +1,561 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@atsro.uni-wuerzburh.de>
+!   Author(s): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPedestalCam
+//
+// Fills the extracted pedestals of MExtractedSignalCam into
+// the MHCalibrationPix-classes MHPedestalPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray
+//   or MHCalibrationCam::fHiGainArray, respectively, depending if
+//   MArrivalTimePix::IsLoGainUsed() is set.
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and
+//   MHCalibrationCam::fAverageHiGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera),
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainSectors
+//   and MHCalibrationCam::fAverageHiGainSectors
+//
+// Every pedestal is directly taken from MExtractedSignalCam, filled by the
+// appropriate extractor.
+//
+// The pedestals are filled into a histogram and an array, in order to perform
+// a Fourier analysis (see MHGausEvents). The signals are moreover averaged on an
+// event-by-event basis and written into the corresponding average pixels.
+//
+// The histograms are fitted to a Gaussian, mean and sigma with its errors
+// and the fit probability are extracted. If none of these values are NaN's and
+// if the probability is bigger than MHGausEvents::fProbLimit (default: 0.5%),
+// the fit is declared valid.
+// Otherwise, the fit is repeated within ranges of the previous mean
+// +- MHCalibrationPix::fPickupLimit (default: 5) sigma (see MHCalibrationPix::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are
+// taken directly (see MHCalibrationPix::BypassFit()).
+//
+// Outliers of more than MHCalibrationPix::fPickupLimit (default: 5) sigmas
+// from the mean are counted as Pickup events (stored in MHCalibrationPix::fPickup)
+//
+// The number of summed FADC slices is taken to re-normalize
+// the result to a pedestal per pixel with the formulas (see MHPedestalPix::Renorm()):
+// - Mean Pedestal        / slice = Mean Pedestal        / Number slices
+// - Mean Pedestal Error  / slice = Mean Pedestal Error  / Number slices
+// - Sigma Pedestal       / slice = Sigma Pedestal       / Sqrt (Number slices)
+// - Sigma Pedestal Error / slice = Sigma Pedestal Error / Sqrt (Number slices)
+//
+// The class also fills arrays with the signal vs. event number, creates a fourier
+// spectrum (see MHGausEvents::CreateFourierSpectrum()) and investigates if the
+// projected fourier components follow an exponential distribution.
+//
+// This same procedure is performed for the average pixels.
+//
+// The following results are written into MPedestalCam:
+//
+// - MCalibrationPix::SetMean()
+// - MCalibrationPix::SetMeanErr()
+// - MCalibrationPix::SetSigma()
+// - MCalibrationPix::SetSigmaErr()
+// - MCalibrationPix::SetProb()
+// - MCalibrationPix::SetNumPickup()
+//
+// For all averaged areas, the fitted sigma is multiplied with the square root of
+// the number involved pixels in order to be able to compare it to the average of
+// sigmas in the camera.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPedestalCam.h"
+#include "MHPedestalPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationPedCam.h"
+
+#include "TH1.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MHPedestalCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes:
+// - fExtractHiGainSlices to 0.
+// - fExtractLoGainSlices to 0.
+// - the event frequency to 1200 Hz.
+// - the fRenorm flag to kTRUE
+//
+MHPedestalCam::MHPedestalCam(const char *name, const char *title) 
+    : fExtractHiGainSlices(0.), fExtractLoGainSlices(0.)
+{
+
+  fName  = name  ? name  : "MHPedestalCam";
+  fTitle = title ? title : "";
+  
+  SetPulserFrequency(1200);
+  SetRenorm();
+
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Searches pointer to:
+// - MPedestalCam
+// - MExtractedSignalCam
+//
+// Searches or creates:
+// - MCalibrationPedCam
+//
+// Retrieves from MExtractedSignalCam:
+// - number of used High Gain FADC slices (MExtractedSignalCam::GetNumUsedHiGainFADCSlices())
+// - number of used Low  Gain FADC slices (MExtractedSignalCam::GetNumUsedLoGainFADCSlices())
+//
+// Initializes, if empty to MGeomCam::GetNumPixels():
+// - MHCalibrationCam::fHiGainArray, MHCalibrationCam::fLoGainArray
+//
+// Initializes, if empty to MGeomCam::GetNumAreas() for:
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+//
+// Initializes, if empty to MGeomCam::GetNumSectors() for:
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+// 
+// Calls MHCalibrationCam::InitPedHists() for every entry in:
+// - MHCalibrationCam::fHiGainArray, MHCalibrationCam::fLoGainArray
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+//
+// Sets Titles and Names for the Histograms 
+// - MHCalibrationCam::fAverageHiGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors
+// 
+Bool_t MHPedestalCam::ReInitHists(MParList *pList)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!signal)
+    {
+      gLog << err << "Cannot find MExtractedSignalCam... abort." << endl;
+      return kFALSE;
+    }
+  
+
+  fPedestals = (MPedestalCam*)pList->FindObject("MPedestalCam");
+
+  if (!fPedestals)
+    {
+      gLog << err << "Cannot find MPedestalCam ... abort." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  fCam = (MCalibrationCam*)pList->FindObject("MCalibrationPedCam");
+  if (!fCam)
+  {
+      fCam = (MCalibrationCam*)pList->FindCreateObj(AddSerialNumber("MCalibrationPedCam"));
+      if (!fCam)
+          return kFALSE;
+
+      fCam->Init(*fGeom);
+  }
+  
+  Float_t sliceshi = signal->GetNumUsedHiGainFADCSlices();
+  Float_t sliceslo = signal->GetNumUsedLoGainFADCSlices();
+
+  if (sliceshi == 0.)
+    {
+      gLog << err << "Number of used signal slices in MExtractedSignalCam is zero  ... abort." 
+           << endl;
+      return kFALSE;
+    }
+
+  if (fExtractHiGainSlices != 0. && sliceshi != fExtractHiGainSlices )
+    {
+      gLog << err << "Number of used High Gain signal slices changed in MExtractedSignalCam  ... abort." 
+           << endl;
+      return kFALSE;
+    }
+
+  if (fExtractLoGainSlices != 0. && sliceslo != fExtractLoGainSlices )
+    {
+      gLog << err << "Number of used Low Gain signal slices changed in MExtractedSignalCam  ... abort." 
+           << endl;
+      return kFALSE;
+    }
+
+  fExtractHiGainSlices = sliceshi;
+  fExtractLoGainSlices = sliceslo;
+
+  if (fHiGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fHiGainArray->AddAt(new MHPedestalPix(Form("%s%4i","MHPedestalHiGainPix",i),
+                                              Form("%s%4i","Pedestals High Gain Pixel",i)),i);
+        InitPedHists((MHPedestalPix&)(*this)[i],i,fExtractHiGainSlices);
+          
+      if ((*fBadPixels)[i].IsBad())
+            (*this)[i].SetExcluded();
+
+          (*fPedestals)[i].InitUseHists();
+      }
+
+  }
+
+  if (fLoGainArray->GetSize()==0)
+  {
+      for (Int_t i=0; i<npixels; i++)
+      {
+        fLoGainArray->AddAt(new MHPedestalPix(Form("%s%4i","MHPedestalLoGainPix",i),
+                                              Form("%s%4i","Pedestals Low Gain Pixel",i)),i);
+        InitPedHists((MHPedestalPix&)(*this)(i),i,fExtractLoGainSlices);
+
+        if ((*fBadPixels)[i].IsBad())
+          (*this)(i).SetExcluded();
+      }
+  }
+
+  if (fAverageHiGainAreas->GetSize()==0)
+  {
+    
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageHiGainAreas->AddAt(new MHPedestalPix(Form("%s%d","AverageHiGainArea",j),
+                                                     Form("%s%d","Average Pedestals area idx ",j)),j);
+
+        InitPedHists((MHPedestalPix&)GetAverageHiGainArea(j),j,fExtractHiGainSlices);
+
+      }
+  }
+
+  if (fAverageLoGainAreas->GetSize()==0)
+  {
+    
+    for (Int_t j=0; j<nareas; j++)
+      {
+        fAverageLoGainAreas->AddAt(new MHPedestalPix(Form("%s%d","AverageLoGainArea",j),
+                                                     Form("%s%d","Pedestals average Area idx ",j)),j);
+
+        InitPedHists((MHPedestalPix&)GetAverageLoGainArea(j),j,fExtractLoGainSlices);
+
+      }
+  }
+
+  if (fAverageHiGainSectors->GetSize()==0)
+  {
+
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  fAverageHiGainSectors->AddAt(new MHPedestalPix(Form("%s%2i","AverageHiGainSector",j),
+                                                         Form("%s%2i","Pedestals average sector ",j)),j);
+
+          InitPedHists((MHPedestalPix&)GetAverageHiGainSector(j),j,fExtractHiGainSlices);
+      }
+  }
+
+  if (fAverageLoGainSectors->GetSize()==0)
+  {
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  fAverageLoGainSectors->AddAt(new MHPedestalPix(Form("%s%2i","AverageLoGainSector",j),
+                                                         Form("%s%2i","Pedestals average sector ",j)),j);
+
+          InitPedHists((MHPedestalPix&)GetAverageLoGainSector(j),j,fExtractLoGainSlices);
+      }
+  }
+
+  return kTRUE;
+}
+
+
+// -------------------------------------------------------------
+//
+// If MBadPixelsPix::IsBad():
+// - calls MHCalibrationPix::SetExcluded()
+//
+// Calls:
+// - MHGausEvents::InitBins()
+// - MHCalibrationPix::ChangeHistId(i)
+// - MHCalibrationPix::SetEventFrequency(fPulserFrequency)
+// - MHPedestalPix::SetNSlices(nslices)
+//
+void MHPedestalCam::InitPedHists(MHPedestalPix &hist, const Int_t i, const Float_t nslices)
+{
+
+  hist.InitBins();
+  hist.SetEventFrequency(fPulserFrequency);
+
+  if (fRenorm)
+    hist.SetNSlices(nslices);
+
+  hist.SetProbLimit(0.);
+
+}
+// -------------------------------------------------------------------------------
+//
+// Retrieves pointer to MExtractedSignalCam:
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// Fills HiGain or LoGain histograms (MHGausEvents::FillHistAndArray()), respectively
+// with the signals MExtractedSignalCam::GetExtractedSignalHiGain() and 
+// MExtractedSignalCam::GetExtractedSignalLoGain(), respectively.
+//
+Bool_t MHPedestalCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)par;
+  if (!signal)
+    {
+      gLog << err << "No argument in MExtractedSignalCam::Fill... abort." << endl;
+      return kFALSE;
+    }
+  
+  
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  TArrayF sumareahi(nareas);
+  TArrayF sumarealo(nareas);
+  TArrayF sumsectorhi(nsectors);
+  TArrayD sumsectorlo(nsectors);
+  TArrayI numareahi(nareas);
+  TArrayI numarealo(nareas);
+  TArrayI numsectorhi(nsectors);
+  TArrayI numsectorlo(nsectors);
+
+  for (UInt_t i=0; i<npixels; i++)
+  {
+      MHCalibrationPix &histhi = (*this)[i];
+      MHCalibrationPix &histlo = (*this)(i);
+
+      if (histhi.IsExcluded())
+          continue;
+
+      const MExtractedSignalPix &pix = (*signal)[i];
+
+      const Float_t pedhi = pix.GetExtractedSignalHiGain();
+      const Float_t pedlo = pix.GetExtractedSignalLoGain();
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      histhi.FillHistAndArray(pedhi) ;
+      sumareahi  [aidx]   += pedhi;
+      numareahi  [aidx]   ++;
+      sumsectorhi[sector] += pedhi;
+      numsectorhi[sector] ++;
+
+      histlo.FillHistAndArray(pedlo);
+      sumarealo  [aidx]   += pedlo;
+      numarealo  [aidx]   ++;
+      sumsectorlo[sector] += pedlo;
+      numsectorlo[sector] ++;
+
+    }
+  
+  for (UInt_t j=0; j<nareas; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+
+      MHCalibrationPix &histlo = GetAverageLoGainArea(j);
+      histlo.FillHistAndArray(numarealo[j] == 0 ? 0. : sumarealo[j]/numarealo[j]);
+    }
+  
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+      MHCalibrationPix &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+      MHCalibrationPix &histlo = GetAverageLoGainSector(j);
+      histlo.FillHistAndArray(numsectorlo[j] == 0 ? 0. : sumsectorlo[j]/numsectorlo[j]);
+    }
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls:
+// - MHCalibrationCam::FitHiGainArrays() with Bad Pixels flags 0
+// - MHCalibrationCam::FitLoGainArrays() with Bad Pixels flags 0
+// 
+Bool_t MHPedestalCam::FinalizeHists()
+{
+
+  FitHiGainArrays((*fCam),*fBadPixels, 
+                  MBadPixelsPix::kHiGainNotFitted,
+                  MBadPixelsPix::kHiGainOscillating);
+  FitLoGainArrays((*fCam),*fBadPixels,
+                  MBadPixelsPix::kLoGainNotFitted,
+                  MBadPixelsPix::kLoGainOscillating);
+
+
+  return kTRUE;
+  
+
+}
+
+// ------------------------------------------------------------------
+//
+// The types are as follows:
+// 
+// Fitted values:
+// ============== 
+//
+// 0: Fitted Charge
+// 1: Error of fitted Charge
+// 2: Sigma of fitted Charge
+// 3: Error of Sigma of fitted Charge
+//
+//
+// Useful variables derived from the fit results:
+// =============================================
+//
+// 4: Returned probability of Gauss fit to Charge distribution
+// 5: Relative differenc of calculated pedestal (per slice) and fitted (per slice)
+// 6: Error of the Relative differenc of calculated pedestal (per slice) and fitted (per slice)
+// 7: Relative difference of the error of the mean pedestal (per slice) - calculated and fitted
+// 8: Relative differenc of calculated pedestal RMS (per slice) and fitted sigma (per slice)
+// 9: Error of Relative differenc of calculated pedestal RMS (per slice) and fitted sigma (per slice)
+// 10: Relative difference of the error of the pedestal RMS (per slice) - calculated and fitted
+//
+// Localized defects:
+// ==================
+//
+// 11: Gaus fit not OK
+// 12: Fourier spectrum not OK
+//
+Bool_t MHPedestalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (fHiGainArray->GetSize() <= idx)
+    return kFALSE;
+
+  if ((*this)[idx].IsExcluded())
+    return kFALSE;
+
+  const Float_t ped      = (*fPedestals)[idx].GetPedestal();
+  const Float_t rms      = (*fPedestals)[idx].GetPedestalRms();
+
+  const Float_t entsqr    =  TMath::Sqrt((Float_t)fPedestals->GetTotalEntries());
+
+  const Float_t pederr   = rms/entsqr;
+  const Float_t rmserr   = rms/entsqr/2.;
+
+  const Float_t mean     = (*this)[idx].GetMean();
+  const Float_t meanerr  = (*this)[idx].GetMeanErr();
+  const Float_t sigma    = (*this)[idx].GetSigma() ;
+  const Float_t sigmaerr = (*this)[idx].GetSigmaErr();
+
+  switch (type)
+    {
+    case 0:
+      val = mean;
+      break;
+    case 1:
+      val = meanerr;
+      break;
+    case 2:
+      val = sigma;
+      break;
+    case 3:
+      val = sigmaerr;
+      break;
+    case 4:
+      val = (*this)[idx].GetProb();
+      break;
+    case 5:
+      val = 2.*(mean-ped)/(ped+mean);
+      break;
+    case 6:
+      val = TMath::Sqrt((pederr*pederr + meanerr*meanerr) * (ped*ped + mean*mean))
+            *2./(ped+mean)/(ped+mean);
+      break;
+    case 7:
+      val = 2.*(meanerr-pederr)/(pederr + meanerr);
+      break;
+    case 8:
+      val = 2.*(sigma-rms)/(sigma+rms);
+      break;
+    case 9:
+      val = TMath::Sqrt((rmserr*rmserr + sigmaerr*sigmaerr) * (rms*rms + sigma*sigma))
+            *2./(rms+sigma)/(rms+sigma);
+      break;
+    case 10:
+      val = 2.*(sigmaerr - rmserr)/(sigmaerr + rmserr);
+      break;
+    case 11:
+      if (!(*this)[idx].IsGausFitOK())
+        val = 1.;
+      break;
+    case 12:
+      if (!(*this)[idx].IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHGausEvents::DrawClone() for pixel idx
+//
+void MHPedestalCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
Index: /tags/Mars-V0.9/mpedestal/MHPedestalCam.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MHPedestalCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MHPedestalCam.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHPedestalCam
+#define MARS_MHPedestalCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+class MGeomCam;
+class MPedestalCam;
+class MHPedestalPix;
+class MHPedestalCam : public MHCalibrationCam
+{
+
+private:
+
+  void   InitPedHists(MHPedestalPix &hist, const Int_t i, const Float_t nslices);
+  
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  
+  Float_t fExtractHiGainSlices;           // Number of FADC slices used for high gain signal extraction
+  Float_t fExtractLoGainSlices;           // Number of FADC slices used for low  gain signal extraction
+
+  Bool_t  fRenorm;
+
+  MPedestalCam *fPedestals;               //! Pedestal Cam filled by MPedCalcPedRun
+  
+public:
+  MHPedestalCam(const char *name=NULL, const char *title=NULL);
+  ~MHPedestalCam() {}
+  
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+  
+  void SetRenorm( const Bool_t b=kTRUE )  {  fRenorm = b; }
+
+  ClassDef(MHPedestalCam, 1)	// Histogram class for Charge Camera Pedestals 
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mpedestal/MMcPedestalCopy.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MMcPedestalCopy.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MMcPedestalCopy.cc	(revision 9772)
@@ -0,0 +1,167 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMcPedestalCopy
+//
+//  This task looks for the ìnformation about FADC pedestals in
+//  MMcFadcHeader and translates it to the pedestal values in
+//  MPedestalCam
+//
+//  Input Containers:
+//   MMcFadcHeader
+//   [MMcRunHeader]
+//   [MRawRunHeader]
+//
+//  Output Containers:
+//   MPedestalCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcPedestalCopy.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+#include "MRawRunHeader.h"
+#include "MMcRunHeader.hxx"
+#include "MMcFadcHeader.hxx"
+
+ClassImp(MMcPedestalCopy);
+
+using namespace std;
+
+MMcPedestalCopy::MMcPedestalCopy(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcPedestalCopy";
+    fTitle = title ? title : "Copy MC pedestals into MPedestal Container";
+
+    //
+    // This is not needed here using MReadMarsFile because for the
+    // RunHeader tree the auto scheme is disabled by default
+    //
+    AddToBranchList("MMcFadcHeader.fPedesMean");
+    AddToBranchList("MMcFadcHeader.fElecNoise");
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the run type. Return kTRUE if it is a MC run or if there
+// is no MC run header (old camera files) kFALSE in case of a different
+// run type
+//
+Bool_t MMcPedestalCopy::CheckRunType(MParList *pList) const
+{
+    const MRawRunHeader *run = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!run)
+    {
+        *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+        return kTRUE;
+    }
+
+    return run->IsMonteCarloRun();
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Make sure that there is a MPedestalCam object in the parameter list.
+//
+Int_t  MMcPedestalCopy::PreProcess(MParList *pList)
+{
+  if ( ! pList->FindObject(AddSerialNumber("MPedestalCam")) )
+    pList->FindCreateObj(AddSerialNumber("MPedestalCam"));
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the runtype.
+// Search for MPedestalCam and MMcFadcHeader.
+//
+Bool_t MMcPedestalCopy::ReInit(MParList *pList)
+{
+    //
+    // If it is no MC file skip this function...
+    //
+    if (!CheckRunType(pList))
+      {
+	*fLog << inf << "This is no MC file... skipping." << endl;
+        return kTRUE;
+      }
+
+    //
+    // Now check the existance of all necessary containers. This has
+    // to be done only if this is a MC file.
+    //
+    MMcFadcHeader *fadc = (MMcFadcHeader*)pList->FindObject(AddSerialNumber("MMcFadcHeader"));
+    if (!fadc)
+    {
+        *fLog << err << dbginf << "MMcFadcHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    MPedestalCam *pedcam = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!pedcam)
+      {
+        *fLog << err << dbginf << "Cannot create " << AddSerialNumber("MPedestalCam") <<"... Exiting." << endl;
+
+        return kFALSE;
+      }
+
+    MMcRunHeader *mcrun = (MMcRunHeader*)pList->FindObject("MMcRunHeader");
+    if (!mcrun)
+        *fLog << warn << dbginf << "MMcRunHeader not found... assuming camera<0.7" << endl;
+
+    const int num = pedcam->GetSize();
+
+    const Bool_t camver70 = mcrun && mcrun->GetCamVersion()>=70;
+
+    for (int i=0; i<num; i++)
+    {
+        MPedestalPix &pix = (*pedcam)[i];
+
+        // Here one should compute the Pedestal taking into account how
+        // the MC makes the transformation analogic-digital for the FADC.
+        // This is done only once per file -> not time critical.
+
+        const Float_t pedest = fadc->GetPedestal(i);
+        const Float_t sigma  = camver70 ? fadc->GetPedestalRmsHigh(i) : fadc->GetElecNoise(i);
+
+        pix.Set(pedest, sigma);
+
+    }
+
+    if (camver70)
+        pedcam->SetReadyToSave();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mpedestal/MMcPedestalCopy.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MMcPedestalCopy.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MMcPedestalCopy.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MMcPedestalCopy
+#define MARS_MMcPedestalCopy
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcPedestalCopy : public MTask
+{
+private:
+    Bool_t CheckRunType(MParList *pList) const;
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MMcPedestalCopy(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MMcPedestalCopy, 0)   // Task which copies the pedestals from the MC into the standard container
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/MMcPedestalNSBAdd.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MMcPedestalNSBAdd.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MMcPedestalNSBAdd.cc	(revision 9772)
@@ -0,0 +1,227 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch, 11/2001 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MMcPedestalNSBAdd
+//  -----------------
+//
+//  This Task adds the contribution of the diffuse NSB to the FADC
+//  pedestals. We assume that NSB introduces larger fluctuation but does
+//  not change the mean value.
+//  To be precise we add quadratically to the rms, which is already in
+//  MPedestalCam, the NSB contribution.
+//  The number of photons from the diffuse NSB follows a poisson
+//  distribution with expected mean value X, then its standard deviation
+//  is sqrt(X).
+//  X is the number of phe per ns so we have to convert in FADC counts per
+//  slice:
+//
+//  Y = sqrt(X * FADC_time / Number_of_slices * pixel_size)
+//      * Amp_single_phe_response
+//
+//  Input Containers:
+//   MMcFadcHeader
+//   MRawRunHeader
+//   [MMcRunHeader]
+//
+//  Output Containers:
+//   MPedestalCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMcPedestalNSBAdd.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+#include "MRawRunHeader.h"
+#include "MMcRunHeader.hxx"
+#include "MMcFadcHeader.hxx"
+
+ClassImp(MMcPedestalNSBAdd);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMcPedestalNSBAdd::MMcPedestalNSBAdd(const Float_t difnsb,
+                                     const char *name, const char *title)
+    : fDnsbPixel(difnsb)
+{
+    fName  = name  ? name  : "MMcPedestalNSBAdd";
+    fTitle = title ? title : "Add diffuse NSB to the pedestal signal";
+
+    //
+    // This is not needed here using MReadMarsFile because for the
+    // RunHeader tree the auto scheme is disabled by default
+    //
+    AddToBranchList("MMcFadcHeader.fPedesMean");
+    AddToBranchList("MMcFadcHeader.fElecNoise");
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the run type. Return kTRUE if it is a MC run or if there
+// is no MC run header (old camera files) kFALSE in case of a different
+// run type
+//
+Bool_t MMcPedestalNSBAdd::CheckRunType(MParList *pList) const
+{
+    const MRawRunHeader *runheader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!runheader)
+    {
+        *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+        return kTRUE;
+    }
+
+    return runheader->IsMonteCarloRun();
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the camera version. This class should not be used with
+// camera files >= 0.7
+//
+Bool_t MMcPedestalNSBAdd::CheckCamVersion(MParList *pList) const
+{
+    const MMcRunHeader *run = (MMcRunHeader*)pList->FindObject("MMcRunHeader");
+    if (!run)
+        *fLog << warn << dbginf << "MMcRunHeader not found... assuming camera<0.7" << endl;
+
+    return !run || run->GetCamVersion()<70;
+}
+
+// --------------------------------------------------------------------------
+//
+// If a MMcRunHeader is available the DNSB MMcRunHeader::GetNumPheFromDNSB
+// is returned. Otherwise the user given number is used.
+//
+Float_t MMcPedestalNSBAdd::GetDnsb(MParList *pList) const
+{
+    const MMcRunHeader *mcrunheader = (MMcRunHeader*)pList->FindObject("MMcRunHeader");
+    if (!mcrunheader && fDnsbPixel<0)
+    {
+        *fLog << err << dbginf << "Using the default argument only ";
+        *fLog << "allowed if MMcRunHeader is available... aborting." << endl;
+        return -1;
+    }
+
+    if (!mcrunheader)
+        return fDnsbPixel;
+
+    if (fDnsbPixel >= 0 && fDnsbPixel != mcrunheader->GetNumPheFromDNSB())
+    {
+        *fLog << warn << dbginf << "The MC file has been generated with diffuse nsb " << mcrunheader->GetNumPheFromDNSB();
+        *fLog <<" but you set up the diffuse NSB to " << fDnsbPixel << endl;
+
+        return fDnsbPixel;
+    }
+
+    return mcrunheader->GetNumPheFromDNSB();
+}
+
+// --------------------------------------------------------------------------
+//
+//  This function is called each time MReadTree::Notify is called, which 
+//  happens when it  changes the file to read from.
+//  Here we add the contribution from NSB to the pedestals.
+//  The ReInit searches for the following input containers:
+//   - MRawRunHeader
+//   - MMcRunHeader
+//   - MMcFacdHeader
+//   - MGeomCam
+//
+//   The following output containers are also searched and created if
+//   they were not found:
+//   - MPedestalCam
+//
+Bool_t MMcPedestalNSBAdd::ReInit(MParList *pList)
+{
+    //
+    // If it is no MC file skip this function...
+    //
+    if (!CheckRunType(pList))
+        return kTRUE;
+
+    //
+    // If it is the wrong camera version this algorithm is not needed...
+    //
+    if (!CheckCamVersion(pList))
+        return kTRUE;
+
+    //
+    // Now check the existance of all necessary containers. This has
+    // to be done only if this is a MC file and the camera version
+    // is correct.
+    //
+    MPedestalCam *pedcam = (MPedestalCam*)pList->FindCreateObj(AddSerialNumber("MPedestalCam"));
+    if (!pedcam)
+	return kFALSE;
+
+    MMcFadcHeader *fadc = (MMcFadcHeader*)pList->FindObject(AddSerialNumber("MMcFadcHeader"));
+    if (!fadc)
+    {
+        *fLog << err << dbginf << "MMcFadcHeader not found... aborting." << endl;
+	return kFALSE;
+    }
+
+    MGeomCam *geom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!geom)
+    {
+        *fLog << err << dbginf << "MGeomCam not found... aborting." << endl;
+	return kFALSE;
+    }
+
+    const Float_t dnsbpix = GetDnsb(pList) * 50.0/15.0;
+
+    if (dnsbpix < 0)
+        return kFALSE;
+
+    const int num = pedcam->GetSize();
+
+    for (int i=0; i<num; i++)
+    {
+        MPedestalPix &pix    = (*pedcam)[i];
+
+        const Float_t pedrms = pix.GetPedestalRms();
+        const Float_t ratio  = geom->GetPixRatio(i);
+        const Float_t ampl   = fadc->GetAmplitud();
+
+	pix.SetPedestalRms(sqrt(pedrms*pedrms + dnsbpix*ampl*ampl/ratio));
+    }
+
+    pedcam->SetReadyToSave();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mpedestal/MMcPedestalNSBAdd.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MMcPedestalNSBAdd.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MMcPedestalNSBAdd.h	(revision 9772)
@@ -0,0 +1,27 @@
+#ifndef MARS_MMcPedestalNSBAdd
+#define MARS_MMcPedestalNSBAdd
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcPedestalNSBAdd : public MTask
+{
+private:
+    Float_t fDnsbPixel;
+
+    Bool_t CheckCamVersion(MParList *pList) const;
+    Bool_t CheckRunType(MParList *pList) const;
+
+    Float_t GetDnsb(MParList *pList) const;
+
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MMcPedestalNSBAdd(const Float_t difnsb = -1.0,
+                      const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MMcPedestalNSBAdd, 0)   // Task which adds the NSB fluctuations to the pedestals rms
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/MPedCalcFromData.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedCalcFromData.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedCalcFromData.cc	(revision 9772)
@@ -0,0 +1,197 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix 06/2004 <mailto:jflix@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MPedCalcFromData                                                      //
+//                                                                         //
+//  Input Containers:                                                      //
+//   MRawEvtData                                                           //
+//                                                                         //
+//  Output Containers:                                                     //
+//   MPedestalCam                                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MPedCalcFromData.h"
+#include "MExtractor.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"  
+#include "MRawEvtPixelIter.h"
+#include "MRawEvtData.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+ClassImp(MPedCalcFromData);
+
+using namespace std;
+
+MPedCalcFromData::MPedCalcFromData(const char *name, const char *title) 
+{
+    fName  = name  ? name  : "MPedCalcFromData";
+    fTitle = title ? title : "Task to calculate pedestals from data runs";
+
+    AddToBranchList("fHiGainPixId");
+    AddToBranchList("fHiGainFadcSamples");
+
+    SetRange(fLoGainFirst, fLoGainLast);
+    Clear();
+}
+
+void MPedCalcFromData::Clear(const Option_t *o)
+{
+
+  fRawEvt    = NULL;
+  fRunHeader = NULL;
+
+}
+
+void MPedCalcFromData::SetLoRange(Byte_t lofirst, Byte_t lolast)
+{
+    fLoGainFirst = lofirst;
+    fLoGainLast = lolast;
+    
+    fWindowSizeLoGain = lolast - lofirst;
+
+}
+
+Int_t MPedCalcFromData::PreProcess( MParList *pList )
+{
+    Clear();
+    
+    fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvt)
+    {
+	*fLog << err << "MRawEvtData not found... aborting." << endl;
+	return kFALSE;
+    }
+    
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+	*fLog << err << AddSerialNumber("MRawRunHeader") << " not found... aborting." << endl;
+	return kFALSE;
+    }
+    
+    fPedestals = (MPedestalCam*)pList->FindCreateObj("MPedestalCam");
+    if (!fPedestals)
+	return kFALSE;
+    
+    return kTRUE;
+}
+
+
+Bool_t MPedCalcFromData::ReInit(MParList *pList)
+{
+  
+  Int_t npixels  = fPedestals->GetSize();
+  
+  if (fSumx.GetSize()==0)
+    {
+      fSumx. Set(npixels);
+      fSumx2.Set(npixels);
+      fEvtCounter.Set(npixels);
+      fTotalCounter.Set(npixels);
+
+      fEvtCounter.Reset();
+      fTotalCounter.Reset();
+      fSumx.Reset();
+      fSumx2.Reset();
+    }
+  
+  return kTRUE;
+      
+}
+
+Int_t MPedCalcFromData::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  
+  while (pixel.Next())
+    {
+
+      const UInt_t idx    = pixel.GetPixelId();
+      
+      if ( (UInt_t)pixel.GetMaxHiGainSample() < fHiGainThreshold ) {
+	  
+	  fEvtCounter[idx]++;
+
+	  Byte_t *ptr = pixel.GetLoGainSamples() + fLoGainFirst;
+	  Byte_t *end = ptr + fWindowSizeLoGain;
+	  
+	  UInt_t sum = 0;
+	  UInt_t sqr = 0;
+	  
+	  if (fWindowSizeLoGain != 0)
+	  {
+	      do
+	      {
+		  sum += *ptr;
+		  sqr += *ptr * *ptr;
+	      }
+	      while (++ptr != end);
+	  }
+	  
+	  const Float_t msum = (Float_t)sum;
+	  fSumx[idx]          += msum;
+	  
+	  const Float_t sqrsum  = msum*msum;
+	  fSumx2[idx]          += sqrsum;
+
+	  if ((UInt_t)fEvtCounter[idx] == fDump){
+	      
+	      // Compute pedestals and rms from the sample
+	      const ULong_t n     = fWindowSizeLoGain*fDump;
+
+	      const Float_t sum  = fSumx.At(idx);
+	      const Float_t sum2 = fSumx2.At(idx);
+	      const Float_t higainped = sum/n;	      
+
+	      // 1. Calculate the Variance of the sums:
+	      Float_t higainVar = (sum2-sum*sum/fDump)/(fDump-1.);
+	      // 2. Scale the variance to the number of slices:
+	      higainVar /= (Float_t)(fWindowSizeLoGain);
+	      // 3. Calculate the RMS from the Variance:
+	      (*fPedestals)[idx].Set(higainped, higainVar < 0 ? 0. : TMath::Sqrt(higainVar));
+
+	      fTotalCounter[idx]++;
+	      fEvtCounter[idx]=0;
+	      fSumx[idx]=0;
+	      fSumx2[idx]=0;
+	  };
+      }
+      
+    };
+  
+  fPedestals->SetReadyToSave();
+  return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mpedestal/MPedCalcFromData.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedCalcFromData.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedCalcFromData.h	(revision 9772)
@@ -0,0 +1,59 @@
+#ifndef MARS_MPedCalcFromData
+#define MARS_MPedCalcFromData
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         
+// MPedCalcFromData
+//                                                                         
+// Evaluate the pedestal from real data. Uses pixels which have no switched to Low Gain
+// to take pedestals from Low Gain samples.
+//
+// Author: J. Flix (jflix@ifae.es)
+// Date: 25-06-2004
+//                                                                         
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MPedCalcFromData : public MExtractor
+{
+
+    UInt_t fDump; // Number for dumping.
+    Byte_t fLoGainFirst;      // First FADC slice Lo-Gain (currently set to: 3) 
+    Byte_t fLoGainLast;       // Last FADC slice Lo-Gain (currently set to: 14) 
+    Byte_t fWindowSizeLoGain;             // Number of Lo Gain slices in window
+    Byte_t fHiGainThreshold;
+
+    TArrayD fSumx;         // sum of values
+    TArrayD fSumx2;        // sum of squared values
+
+    TArrayI fEvtCounter; // Counter for dumping values to Pedestal Container
+    TArrayI fTotalCounter; // Counter for dumping values to Pedestal Container
+
+    Int_t  PreProcess ( MParList *pList );
+    Bool_t ReInit     ( MParList *pList );
+    Int_t  Process    ();
+
+public:
+
+    MPedCalcFromData(const char *name=NULL, const char *title=NULL);
+ 
+    void Clear(const Option_t *o="");
+    void SetDumpEvents(UInt_t dumpevents = 0){fDump = dumpevents;}
+    void SetfHiGainThreshold(Byte_t Threshold = 0){fHiGainThreshold = Threshold;}
+    void SetLoRange(Byte_t lofirst=0, Byte_t lolast=0);
+
+    ClassDef(MPedCalcFromData, 0)   // Task to calculate pedestals from data runs 
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/MPedCalcFromLoGain.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedCalcFromLoGain.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedCalcFromLoGain.cc	(revision 9772)
@@ -0,0 +1,521 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix 04/2001 <mailto:jflix@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Sebastian Commichau 12/2003 
+!   Author(s): Javier Rico 01/2004 <mailto:jrico@ifae.es> 
+!   Author(s): Markus Gaug 01/2004 <mailto:markus@ifae.es>
+!   Author(s): Florian Goebel 06/2004 <mailto:fgoebel@mppmu.mpg.de>
+!   Author(s): Nepomuk Otte 10/2004 <mailto:otte@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+// 
+//   MPedCalcLoGain
+//
+//  This task derives from MExtractPedestal. 
+//  It calculates the pedestals using the low gain slices, whenever the difference 
+//  between the highest and the lowest slice in the high gain
+//  slices is below a given threshold (SetMaxHiGainVar). In this case the receiver
+//  boards do not switch to lo gain and the so called lo gain slices are actually
+//  high gain slices. 
+//
+//  MPedCalcLoGain also fills the ABoffset in MPedestalPix which allows to correct 
+//  the 150 MHz clock noise.
+//
+//  This task takes a pedestal run file and fills MPedestalCam during
+//  the Process() with the pedestal and rms computed in an event basis.
+//  In the PostProcess() MPedestalCam is finally filled with the pedestal
+//  mean and rms computed in a run basis.
+//  More than one run (file) can be merged
+//
+//  MPedCalcPedRun applies the following formula (1):
+// 
+//  Pedestal per slice = sum(x_i) / n / slices
+//  PedRMS per slice   = Sqrt(  ( sum(x_i^2) - sum(x_i)^2/n ) / n-1 / slices )
+// 
+//  where x_i is the sum of "slices" FADC slices and sum means the sum over all
+//  events. "n" is the number of events, "slices" is the number of summed FADC samples.
+// 
+//  Note that the slice-to-slice fluctuations are not Gaussian, but Poissonian, thus 
+//  asymmetric and they are correlated.
+// 
+//  It is important to know that the Pedestal per slice and PedRMS per slice depend 
+//  on the number of used FADC slices, as seen in the following plots:
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyInner.gif">
+*/
+//End_Html
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyOuter.gif">
+*/
+//End_Html
+//
+// The plots show the inner and outer pixels, respectivly and have the following meaning:
+// 
+// 1) The calculated mean pedestal per slice (from MPedCalcFromLoGain)
+// 2) The fitted mean pedestal per slice     (from MHPedestalCam)
+// 3) The calculated pedestal RMS per slice  (from MPedCalcFromLoGain)
+// 4) The fitted sigma of the pedestal distribution per slice
+//                                           (from MHPedestalCam)
+// 5) The relative difference between calculation and histogram fit
+//    for the mean
+// 6) The relative difference between calculation and histogram fit
+//    for the sigma or RMS, respectively.
+// 
+// The calculated means do not change significantly except for the case of 2 slices, 
+// however the RMS changes from 5.7 per slice in the case of 2 extracted slices 
+// to 8.3 per slice in the case of 26 extracted slices. This change is very significant.
+// 
+// The plots have been produced on run 20123. You can reproduce them using
+// the macro pedestalstudies.C
+// 
+//  Usage of this class: 
+//  ====================
+//  
+// 
+//   fCheckWinFirst   =  fgCheckWinFirst   =  0 
+//   fCheckWinLast    =  fgCheckWinLast    =  29
+//   fExtractWinFirst =  fgExtractWinFirst =  17
+//   fExtractWinSize  =  fgExtractWinSize  =  6
+//   fMaxSignalVar    =  fgMaxSignalVar    = 40;
+//
+//  Call: 
+//  SetCheckRange(fCheckWinFirst,fCheckWinLast); 
+//  to set the Window in which a signal is searched
+//
+//  SetExtractWindow(fExtractWinFirst,fExtractWinSize);
+//  to set the Window from which a signal is extracted
+//
+//  SetMaxSignalVar(fMaxSignalVar);
+//  set the maximum allowed difference between maximum and minimal signal in CheckWindow  
+//
+//   Variables:
+//   fgCheckWinFirst;      First FADC slice to check for signal (currently set to: 0)
+//   fgCheckWinLast:       Last FADC slice to check for signal (currently set to: 29)
+//   fgExtractWinFirst:    First FADC slice to be used for pedestal extraction (currently set to: 15)
+//   fgExtractWinSize:     Window size in slices used for pedestal extraction (currently set to: 6)
+//   fgMaxSignalVar:       The maximum difference between the highest and lowest slice
+//                         in the check window allowed in order to use event
+//
+//  Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MGeomCam
+//
+//  Output Containers:
+//   MPedestalCam
+//
+//  See also: MPedestalCam, MPedestalPix, MHPedestalCam, MExtractor
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedCalcFromLoGain.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"  
+#include "MRawEvtPixelIter.h"
+#include "MRawEvtData.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MExtractPedestal.h"
+#include "MExtractTimeAndCharge.h"
+
+ClassImp(MPedCalcFromLoGain);
+
+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;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor: 
+//
+// Sets:
+// - all pointers to NULL
+//
+// Calls: 
+// - AddToBranchList("fHiGainPixId");
+// - AddToBranchList("fHiGainFadcSamples");
+// - SetCheckRange(fgCheckWinFirst, fgCheckWinLast, fgExtractWinFirst, fgExtractWinSize)
+//
+MPedCalcFromLoGain::MPedCalcFromLoGain(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPedCalcFromLoGain";
+    fTitle = title ? title : "Task to calculate pedestals from lo-gains";
+
+    SetCheckRange(fgCheckWinFirst, fgCheckWinLast);
+    SetExtractWindow(fgExtractWinFirst, fgExtractWinSize);
+
+    SetMaxSignalVar(fgMaxSignalVar);
+}
+
+void MPedCalcFromLoGain::ResetArrays()
+{
+    MExtractPedestal::ResetArrays();
+
+    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;
+}
+
+// ---------------------------------------------------------------------------------
+//
+// Checks:
+// - if the number of available slices 
+//   (fRunHeader->GetNumSamplesHiGain()+(Int_t)fRunHeader->GetNumSamplesLoGain()-1)
+//   is smaller than the number of used slices
+//   (fExtractWinSize+ fExtractWinFirst-1) or 
+//    fCheckWinLast
+//
+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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the MPedestalCam container with the signal mean and rms for the event.
+// Store the measured signal in arrays fSumx and fSumx2 so that we can 
+// calculate the overall mean and rms in the PostProcess()
+//
+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);
+
+    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();
+
+        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;
+
+        fSumx[idx]           += sum;
+        fSumx2[idx]          += sqrsum;
+        fAreaSumx[aidx]      += sum;
+        fAreaSumx2[aidx]     += sqrsum;
+        fSectorSumx[sector]  += sum;
+        fSectorSumx2[sector] += sqrsum;
+
+        if (fIntermediateStorage)
+          (*fPedestalsInter)[idx].Set(sum,0.,0.,fNumEventsUsed[idx]);
+
+        fNumEventsUsed[idx]   ++;
+        fAreaFilled   [aidx]  ++;
+        fSectorFilled [sector]++;
+
+        if (!fExtractor)
+        {
+            //
+            // 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;
+            }
+        }
+
+        if (!fPedestalUpdate || (UInt_t)fNumEventsUsed[idx]<fNumEventsDump)
+            continue;
+
+        CalcPixResults(fNumEventsDump, idx);
+        fTotalCounter[idx]++;
+
+        fNumEventsUsed[idx]=0;
+        fSumx[idx]=0;
+        fSumx2[idx]=0;
+        fSumAB0[idx]=0;
+        fSumAB1[idx]=0;
+    }
+
+    if (!(GetNumExecutions() % fNumAreasDump))
+        CalcAreaResult();
+
+    if (!(GetNumExecutions() % fNumSectorsDump))
+        CalcSectorResult();
+
+    if (fPedestalUpdate)
+        fPedestalsOut->SetReadyToSave();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over the sector indices to get the averaged pedestal per sector
+//
+void MPedCalcFromLoGain::CalcSectorResult()
+{
+    for (UInt_t sector=0; sector<fSectorFilled.GetSize(); sector++)
+        if (fSectorValid[sector]>0)
+            CalcSectorResults(fSectorFilled[sector], fSectorValid[sector], sector);
+}
+
+// --------------------------------------------------------------------------
+//
+// Loop over the (two) area indices to get the averaged pedestal per aidx
+//
+void MPedCalcFromLoGain::CalcAreaResult()
+{
+    for (UInt_t aidx=0; aidx<fAreaFilled.GetSize(); aidx++)
+        if (fAreaValid[aidx]>0)
+            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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Compute signal mean and rms in the whole run and store it in MPedestalCam
+//
+Int_t MPedCalcFromLoGain::PostProcess()
+{
+    // Compute pedestals and rms from the whole run
+    if (fPedestalUpdate)
+        return kTRUE;
+
+    *fLog << flush << inf << "Calculating Pedestals..." << flush;
+
+    const Int_t npix = fGeom->GetNumPixels();
+    for (Int_t idx=0; idx<npix; idx++)
+    {
+        const ULong_t n = fNumEventsUsed[idx];
+        if (n>1)
+        {
+            CalcPixResults(n, idx);
+            fTotalCounter[idx]++;
+        }
+    }
+
+    CalcAreaResult();
+    CalcSectorResult();
+
+    fPedestalsOut->SetReadyToSave();
+
+    return MExtractPedestal::PostProcess();
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  The following resources are available:
+//    FirstCheckWindowSlice:  0
+//    LastCheckWindowSlice:  29
+//    MaxSignalVar:          40
+//
+Int_t MPedCalcFromLoGain::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    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);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "CheckWinLast", print))
+    {
+        ls = GetEnvValue(env, prefix, "CheckWinLast", ls);
+        rc = kTRUE;
+    }
+
+    SetCheckRange(fs,ls);
+
+    // find resource for maximum signal variation
+    if (IsEnvDefined(env, prefix, "MaxSignalVar", print))
+    {
+        SetMaxSignalVar(GetEnvValue(env, prefix, "MaxSignalVar", fMaxSignalVar));
+        rc = kTRUE;
+    }
+
+    return MExtractPedestal::ReadEnv(env,prefix,print) ? kTRUE : 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;
+}
Index: /tags/Mars-V0.9/mpedestal/MPedCalcFromLoGain.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedCalcFromLoGain.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedCalcFromLoGain.h	(revision 9772)
@@ -0,0 +1,67 @@
+#ifndef MARS_MPedCalcFromLoGain
+#define MARS_MPedCalcFromLoGain
+
+#ifndef MARS_MExtractPedestal
+#include "MExtractPedestal.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_MArrayB
+#include "MArrayB.h"
+#endif
+
+class MRawEvtPixelIter;
+class MPedestalPix;
+
+class MPedCalcFromLoGain : public MExtractPedestal
+{
+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)
+
+    UShort_t fMaxSignalVar;
+    UShort_t fCheckWinFirst;
+    UShort_t fCheckWinLast;
+
+    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 fRandomCalculation;
+
+    Bool_t ReInit(MParList *pList);
+    Int_t  Calc();
+    Int_t  PostProcess();
+
+    Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    //Helper function to extract slice values by slice number
+    void CalcExtractor(const MRawEvtPixelIter &pixel, Float_t &sum, MPedestalPix &ped);
+    void ResetArrays();
+
+    void CalcSectorResult();
+    void CalcAreaResult();
+
+public:
+    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; }
+
+    ClassDef(MPedCalcFromLoGain, 1)   // Task to calculate pedestals from data runs
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/MPedCalcPedRun.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedCalcPedRun.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedCalcPedRun.cc	(revision 9772)
@@ -0,0 +1,498 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix 04/2001 <mailto:jflix@ifae.es>
+!   Author(s): Thomas Bretz 05/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Sebastian Commichau 12/2003 
+!   Author(s): Javier Rico 01/2004 <mailto:jrico@ifae.es>
+!   Author(s): Markus Gaug 01/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MPedCalcPedRun
+//
+//  This task takes a pedestal run file and fills MPedestalCam during
+//  the Process() with the pedestal and rms computed in an event basis.
+//  In the PostProcess() MPedestalCam is finally filled with the pedestal
+//  mean and rms computed in a run basis.
+//  More than one run (file) can be merged
+//
+//  MPedCalcPedRun applies the following formula (1):
+// 
+//  Pedestal per slice = sum(x_i) / n / slices
+//  PedRMS per slice   = Sqrt(  ( sum(x_i^2) - sum(x_i)^2/n ) / n-1 / slices )
+// 
+//  where x_i is the sum of "slices" FADC slices and sum means the sum over all
+//  events. "n" is the number of events, "slices" is the number of summed FADC samples.
+// 
+//  Note that the slice-to-slice fluctuations are not Gaussian, but Poissonian, thus 
+//  asymmetric and they are correlated.
+// 
+//  It is important to know that the Pedestal per slice and PedRMS per slice depend 
+//  on the number of used FADC slices, as seen in the following plots:
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyInner.gif">
+*/
+//End_Html
+//
+//Begin_Html
+/*
+<img src="images/PedestalStudyOuter.gif">
+*/
+//
+// The plots show the inner and outer pixels, respectivly and have the following meaning:
+// 
+// 1) The calculated mean pedestal per slice (from MPedCalcPedRun)
+// 2) The fitted mean pedestal per slice     (from MHPedestalCam)
+// 3) The calculated pedestal RMS per slice  (from MPedCalcPedRun)
+// 4) The fitted sigma of the pedestal distribution per slice
+//                                           (from MHPedestalCam)
+// 5) The relative difference between calculation and histogram fit
+//    for the mean
+// 6) The relative difference between calculation and histogram fit
+//    for the sigma or RMS, respectively.
+// 
+// The calculated means do not change significantly except for the case of 2 slices, 
+// however the RMS changes from 5.7 per slice in the case of 2 extracted slices 
+// to 8.3 per slice in the case of 26 extracted slices. This change is very significant.
+// 
+// The plots have been produced on run 20123. You can reproduce them using
+// the macro pedestalstudies.C
+// 
+//  Usage of this class: 
+//  ====================
+// 
+//  Call: SetRange(higainfirst, higainlast, logainfirst, logainlast) 
+//  to modify the ranges in which the window is allowed to move. 
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  29
+//   fLoGainFirst =  fgLoGainFirst =  0 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//  Call: SetWindowSize(windowhigain, windowlogain) 
+//  to modify the sliding window widths. Windows have to be an even number. 
+//  In case of odd numbers, the window will be modified.
+//
+//  Defaults are:
+//
+//   fHiGainWindowSize = fgHiGainWindowSize = 14
+//   fLoGainWindowSize = fgLoGainWindowSize = 0
+//
+//
+// ToDo:
+//   - Take a setup file (ReadEnv-implementation) as input
+//
+//
+//  Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MGeomCam
+//
+//  Output Containers:
+//   MPedestalCam
+//
+//  See also: MPedestalCam, MPedestalPix, MHPedestalCam, MExtractor
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedCalcPedRun.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"  
+#include "MRawEvtHeader.h"  
+#include "MRawEvtPixelIter.h"
+#include "MRawEvtData.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MExtractPedestal.h"
+#include "MExtractTimeAndCharge.h"
+
+#include "MTriggerPattern.h"
+
+ClassImp(MPedCalcPedRun);
+
+using namespace std;
+
+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)
+//
+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;
+}
+
+void MPedCalcPedRun::Reset()
+{
+
+  MExtractPedestal::ResetArrays();
+  fUsedEvents    = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set fIsFirstPedRun=kTRUE
+//
+Int_t MPedCalcPedRun::PreProcess(MParList *pList)
+{
+
+  fUsedEvents    = 0;
+  fIsFirstPedRun = kTRUE;
+  fIsNotPedRun   = kFALSE;
+  
+  fTrigPattern = (MTriggerPattern*)pList->FindObject("MTriggerPattern");
+  if (!fTrigPattern)
+    *fLog << warn << "MTriggerPattern not found... Cannot use interlaced pedestal events." << endl;
+
+  return MExtractPedestal::PreProcess(pList);
+}
+
+// --------------------------------------------------------------------------
+//
+// The run type is checked for "kRTPedestal"
+// and the variable fIsNotPedRun is set in that case
+//
+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
+  //
+  if (fRunHeader->GetRunType()==MRawRunHeader::kRTPedestal)
+    {
+      fIsFirstPedRun = kFALSE;
+      fIsNotPedRun   = kFALSE;
+      return kTRUE;
+    }
+  
+  if (fRunHeader->GetRunType()==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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return kTRUE (without doing anything) in case that the run type is not 
+// equal to 1 (pedestal run)
+//
+// Fill the MPedestalCam container with the signal mean and rms for the event.
+// Store the measured signal in arrays fSumx and fSumx2 so that we can 
+// calculate the overall mean and rms in the PostProcess()
+//
+Int_t MPedCalcPedRun::Calc()
+{
+
+  if (fIsNotPedRun && !IsPedBitSet())
+    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();
+      const UInt_t aidx   = (*fGeom)[idx].GetAidx();
+      const UInt_t sector = (*fGeom)[idx].GetSector();      
+
+      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;
+      fAreaSumx[aidx]      += sum;
+      fSectorSumx[sector]  += sum;
+
+      if (fIntermediateStorage)
+        (*fPedestalsInter)[idx].Set(sum,0.,0.,fUsedEvents);
+
+      const Float_t sqrsum   = sum*sum;
+      fSumx2[idx]           += sqrsum;
+      fAreaSumx2[aidx]      += sqrsum;
+      fSectorSumx2[sector]  += sqrsum;
+
+      fSumAB0[idx]         += ab0;
+      fSumAB1[idx]         += ab1;
+
+      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;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Compute signal mean and rms in the whole run and store it in MPedestalCam
+//
+Int_t MPedCalcPedRun::Finalize()
+{
+
+  if (fUsedEvents == 0)
+    return kTRUE;
+  
+  MRawEvtPixelIter pixel(fRawEvt);
+  while (pixel.Next())
+    CalcPixResults(fUsedEvents, pixel.GetPixelId());
+  
+  //
+  // Loop over the (two) area indices to get the averaged pedestal per aidx
+  //
+  for (UInt_t aidx=0; aidx<fAreaValid.GetSize(); aidx++)
+    if (fAreaValid[aidx]>0)
+      CalcAreaResults(fUsedEvents, fAreaValid[aidx], aidx);
+  
+  //
+  // Loop over the (six) sector indices to get the averaged pedestal per sector
+  //
+  for (UInt_t sector=0; sector<fSectorValid.GetSize(); sector++)
+    if (fSectorValid[sector]>0)
+      CalcSectorResults(fUsedEvents, fSectorValid[sector], sector);
+  
+  fPedestalsOut->SetTotalEntries(fUsedEvents*fExtractWinSize);
+  fPedestalsOut->SetReadyToSave();
+  
+  return kTRUE;
+}
+
+Int_t MPedCalcPedRun::PostProcess()
+{
+  if (!Finalize())
+    return kFALSE;
+  
+  return MExtractPedestal::PostProcess();
+}
+
+//-------------------------------------------------------------
+// 
+// Return if the pedestal bit was set from the calibration trigger box.
+// The last but one bit is used for the "pedestal-bit".
+//
+// This bit is set since run gkFirstRunWithFinalBits
+//
+Bool_t MPedCalcPedRun::IsPedBitSet()
+{
+
+  if (!fTrigPattern)
+    return kTRUE;
+
+  if (fRunHeader->GetRunNumber() < gkFirstRunWithFinalBits)
+    return kTRUE;
+  
+  return (fTrigPattern->GetPrescaled() & MTriggerPattern::kPedestal) ? kTRUE : kFALSE;
+}
+
+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: /tags/Mars-V0.9/mpedestal/MPedCalcPedRun.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedCalcPedRun.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedCalcPedRun.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MPedCalcPedRun
+#define MARS_MPedCalcPedRun
+
+#ifndef MARS_MExtractPedestal
+#include "MExtractPedestal.h"
+#endif
+
+class MTriggerPattern;
+class MRawEvtPixelIter;
+class MPedestalPix;
+
+class MPedCalcPedRun : public MExtractPedestal
+{
+private:
+    static const UShort_t fgExtractWinFirst;  // First FADC slice Hi-Gain (currently set to: 3)
+    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
+    Bool_t  fIsNotPedRun;      //! Flag to tell if the current run is a pedestal run
+    UInt_t  fUsedEvents;       // Number of used (not skipped) events
+
+    MTriggerPattern *fTrigPattern;  //! Trigger pattern decoded
+
+    Bool_t IsPedBitSet();
+
+    Bool_t ReInit(MParList *pList);
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Calc();
+    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);
+
+public:
+    MPedCalcPedRun(const char *name=NULL, const char *title=NULL);
+
+    void Print(Option_t *o="") const;
+    void Reset();
+    
+    Int_t Finalize();
+
+    ClassDef(MPedCalcPedRun, 2)   // Task to calculate pedestals from pedestal runs
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/MPedPhotCalc.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedPhotCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedPhotCalc.cc	(revision 9772)
@@ -0,0 +1,187 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix 1/2004 <mailto:jflix@ifae.es>
+!   Author(s): Javier Rico 1/2004 <mailto:jrico@ifae.es>
+!   Author(s): Markus Gaug 4/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MPedPhotCalc
+//
+//  This is a Task class to compute, for each pixel, the signal mean and
+//  rms from a pedestal run file that has undergone the standard signal
+//  extration  and calibration procedure. The signal rms can be used as
+//  reference to compute the significance of the measured signals in the
+//  following data runs (e.g. during the image cleaning).
+//
+//  Input Containers:
+//   MSignalCam
+//
+//  Output Containers:
+//   MPedPhotCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotCalc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawRunHeader.h"
+
+#include "MSignalPix.h"
+#include "MSignalCam.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+#include "MBadPixelsPix.h"
+#include "MBadPixelsCam.h"
+
+ClassImp(MPedPhotCalc);
+
+using namespace std;
+
+//
+// Default constructor
+//
+MPedPhotCalc::MPedPhotCalc(const char *name, const char *title)
+    : fPedestals(NULL), fCerPhot(NULL), fBadPixels(NULL)
+{
+  fName  = name  ? name  : "MPedPhotCalc";
+  fTitle = title ? title : "Task to calculate pedestals in units of photons";
+}
+
+// --------------------------------------------------------------------------
+//
+// Look for the following input containers:
+//
+//  - MSignalCam
+//  - MBadPixelsCam
+// 
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedPhotCam
+//
+Int_t MPedPhotCalc::PreProcess( MParList *pList )
+{      
+  // Look for input container
+  fCerPhot = (MSignalCam*)pList->FindObject("MSignalCam");
+  if (!fCerPhot)
+    {
+      *fLog << err << "MSignalCam not found... aborting." << endl;
+      return kFALSE;
+    }
+
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBadPixels)
+      *fLog << warn << "WARNING - MBadPixelsCam not found... ignored." << endl;
+
+  // Create output container
+  fPedestals = (MPedPhotCam*)pList->FindCreateObj("MPedPhotCam");
+  if (!fPedestals)
+    return kFALSE;
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit searches for the following input containers:
+//  - MRawRunHeader
+//
+// It also initializes the data arrays fSumx and fSumx2 
+// (only for the first read file)
+// 
+Bool_t MPedPhotCalc::ReInit(MParList *pList)
+{
+  // Initialize arrays
+  if(fSumx.GetSize()==0)
+  {
+      const UShort_t num = fPedestals->GetSize();
+
+      fSumx.Set(num);
+      fSumx2.Set(num);
+
+      memset(fSumx.GetArray(),  0, sizeof(Float_t)*num);
+      memset(fSumx2.GetArray(), 0, sizeof(Float_t)*num);
+  }
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Store the measured number of photons in arrays fSumx and fSumx2
+// so that we can calculate the mean and rms in the PostProcess()
+//
+Int_t MPedPhotCalc::Process()
+{
+    const UInt_t n = fCerPhot->GetNumPixels();
+    for(UInt_t idx=0; idx<n; idx++)
+    {
+       const Float_t nphot = (*fCerPhot)[idx].GetNumPhotons();
+       
+       fSumx[idx]  += nphot;
+       fSumx2[idx] += nphot*nphot;
+    }
+
+    fPedestals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compute mean and rms of the measured charge distribution (in photons)
+//
+Int_t MPedPhotCalc::PostProcess()
+{
+    // Compute pedestals and rms from fSumx and fSumx2 arrays
+    const Int_t n    = GetNumExecutions();
+    const Int_t npix = fSumx.GetSize();
+
+    for(Int_t i=0; i<npix; i++)
+    {
+
+      if (fBadPixels)
+        {
+          const MBadPixelsPix &bad = (*fBadPixels)[i];
+          if (bad.IsBad())
+            continue;
+        }
+
+      const Float_t sum  = fSumx[i];
+      const Float_t sum2 = fSumx2[i];
+      
+      const Float_t photped = sum/n;
+      const Float_t photrms = TMath::Sqrt((sum2-sum*sum/n)/(n-1.));
+      
+      (*fPedestals)[i].Set(photped,photrms);
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mpedestal/MPedPhotCalc.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedPhotCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedPhotCalc.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MPedPhotCalc
+#define MARS_MPedPhotCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MPedPhotCam;
+class MSignalCam;
+class MBadPixelsCam;
+class MPedPhotCalc : public MTask
+{
+
+  MPedPhotCam   *fPedestals;  // Pedestals of all pixels in the camera
+  MSignalCam    *fCerPhot;    // Calibrated Cherenkov events
+  MBadPixelsCam *fBadPixels;  // Bad Pixels
+  
+  TArrayF fSumx;   // sum of values
+  TArrayF fSumx2;  // sum of squared values
+
+  Bool_t ReInit(MParList *pList);
+
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess();
+  
+public:
+  MPedPhotCalc(const char *name=NULL, const char *title=NULL);
+
+  ClassDef(MPedPhotCalc, 0) //Task to calculate pedestals in units of photons
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/MPedPhotCam.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedPhotCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedPhotCam.cc	(revision 9772)
@@ -0,0 +1,338 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Hendrik Bartko, 07/2003 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedPhotCam
+//
+// Hold the Pedestal information for all pixels in the camera (in usints
+// of photons)
+//
+// Version 2:
+// ----------
+//   - added fAreas
+//   - added fSectors
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotCam.h"
+
+#include <TClonesArray.h>
+
+#include "MArrayI.h"
+#include "MArrayD.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MPedPhotPix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MPedPhotCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates a MPedPhotPix object for each pixel
+//
+MPedPhotCam::MPedPhotCam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPedPhotCam";
+    fTitle = title ? title : "Storage container for all Pedestal Information in the camera (in units of photons)";
+
+    fArray   = new TClonesArray("MPedPhotPix", 1);
+    fAreas   = new TClonesArray("MPedPhotPix", 1);
+    fSectors = new TClonesArray("MPedPhotPix", 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the array conatining the pixel pedest information
+//
+MPedPhotCam::~MPedPhotCam()
+{
+    delete fArray;
+    delete fAreas;
+    delete fSectors;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MPedPhotCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageAreas
+//
+void MPedPhotCam::InitAreas(const UInt_t i)
+{
+    fAreas->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageSectors
+//
+void MPedPhotCam::InitSectors(const UInt_t i)
+{
+    fSectors->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MPedPhotCam::Init(const MGeomCam &geom)
+{
+    InitSize(geom.GetNumPixels());
+    InitAreas(geom.GetNumAreas());
+    InitSectors(geom.GetNumSectors());
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MPedPhotCam
+//
+Int_t MPedPhotCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MPedPhotCam
+//
+Int_t MPedPhotCam::GetNumSectors() const
+{
+    return fSectors->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MPedPhotCam
+//
+Int_t MPedPhotCam::GetNumAreas() const
+{
+    return fAreas->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MPedPhotPix &MPedPhotCam::operator[](Int_t i)
+{
+    return *static_cast<MPedPhotPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MPedPhotPix &MPedPhotCam::operator[](Int_t i) const
+{
+    return *static_cast<MPedPhotPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MPedPhotPix &MPedPhotCam::GetArea(UInt_t i)
+{
+    return *static_cast<MPedPhotPix*>(fAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MPedPhotPix &MPedPhotCam::GetSector(UInt_t i)
+{
+    return *static_cast<MPedPhotPix*>(fSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MPedPhotPix &MPedPhotCam::GetArea(UInt_t i)const
+{
+    return *static_cast<MPedPhotPix*>(fAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MPedPhotPix &MPedPhotCam::GetSector(UInt_t i) const
+{
+    return *static_cast<MPedPhotPix*>(fSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Call clear of all three TClonesArray
+//
+void MPedPhotCam::Clear(Option_t *o)
+{
+    { fArray->ForEach(TObject, Clear)(); }
+    { fAreas->ForEach(TObject, Clear)(); }
+    { fSectors->ForEach(TObject, Clear)(); }
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MPedPhotCam::ReCalc(const MGeomCam &geom, MBadPixelsCam *bad)
+{
+    const Int_t np = GetSize();
+    const Int_t ns = GetNumSectors();
+    const Int_t na = GetNumAreas();
+
+    // Using MArray instead of TArray because they don't do range checks
+    MArrayI acnt(na);
+    MArrayI scnt(ns);
+    MArrayD asumx(na);
+    MArrayD ssumx(ns);
+    MArrayD asumr(na);
+    MArrayD 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 MPedPhotPix &pix = (*this)[i];
+
+        const UInt_t  ne   = pix.GetNumEvents();
+        const Float_t mean = ne*pix.GetMean();
+	const Float_t rms  = ne*pix.GetRms();
+
+        const UInt_t aidx = geom[i].GetAidx();
+        asumx[aidx] += mean;
+	asumr[aidx] += rms;
+        acnt[aidx]  += ne;
+
+        const UInt_t sect = geom[i].GetSector();
+        ssumx[sect] += mean;
+	ssumr[sect] += 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).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();
+}
+
+// --------------------------------------------------------------------------
+//
+// print contents
+//
+void MPedPhotCam::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << endl;
+    int id = 0;
+
+    TIter Next(fArray);
+    MPedPhotPix *pix;
+    while ((pix=(MPedPhotPix*)Next()))
+    {
+        id++;
+
+        if (!pix->IsValid())
+            continue;
+
+        *fLog << id-1 << ": ";
+        *fLog << pix->GetMean() << " " << pix->GetRms() << endl;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// See MCamEvent
+//
+Bool_t MPedPhotCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    switch (type)
+    {
+    case 0:
+        val = (*this)[idx].GetMean();
+        break;
+    case 1:
+        val = (*this)[idx].GetRms();
+        break;
+    case 2:
+        val = (*this)[idx].GetNumEvents()>0 ? (*this)[idx].GetRms()/TMath::Sqrt((Float_t)(*this)[idx].GetNumEvents()) : -1;
+        break;
+    case 3:
+        val = (*this)[idx].GetNumEvents()>0 ? (*this)[idx].GetRms()/TMath::Sqrt((Float_t)(*this)[idx].GetNumEvents())/2. : -1;
+        break;
+    case 4:
+        val = (*this)[idx].GetMean()*cam.GetPixRatio(idx);
+        break;
+    case 5:
+        val = (*this)[idx].GetRms()*TMath::Sqrt(cam.GetPixRatio(idx));
+        break;
+    default:
+	return kFALSE;
+    }
+    return val>=0;
+}
+
+void MPedPhotCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MPedPhotCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars-V0.9/mpedestal/MPedPhotCam.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedPhotCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedPhotCam.h	(revision 9772)
@@ -0,0 +1,62 @@
+#ifndef MARS_MPedPhotCam
+#define MARS_MPedPhotCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+
+class MGeomCam;
+class MPedPhotPix;
+class MBadPixelsCam;
+
+class MPedPhotCam : public MParContainer, public MCamEvent
+{
+private:
+    TClonesArray *fArray;    // FIXME: Change TClonesArray away from a pointer?
+    TClonesArray *fAreas;    //-> Array of MPedPhotPix, one per pixel area
+    TClonesArray *fSectors;  //-> Array of MPedPhotPix, one per camera sector
+
+    //  void InitSize(const UInt_t i);
+    void InitAreas(const UInt_t i);
+    void InitSectors(const UInt_t i);
+
+public:
+    MPedPhotCam(const char *name=NULL, const char *title=NULL);
+    ~MPedPhotCam();
+
+    void Clear(Option_t *o="");
+
+    void Init(const MGeomCam &geom);
+    void InitSize(const UInt_t i); // HB
+    Int_t GetSize() const;
+
+    MPedPhotPix &operator[](Int_t i);
+    const MPedPhotPix &operator[](Int_t i) const;
+
+          MPedPhotPix &GetArea(UInt_t i);
+    const MPedPhotPix &GetArea(UInt_t i) const;
+
+    Int_t GetNumAreas() const;
+
+          MPedPhotPix &GetSector(UInt_t i);
+    const MPedPhotPix &GetSector(UInt_t i) const;
+
+    Int_t GetNumSectors() const;
+
+    void Print(Option_t *o="") const;
+
+    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;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MPedPhotCam, 2)	// Storage Container for all pedestal information of the camera (in units of photons)
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mpedestal/MPedPhotPix.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedPhotPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedPhotPix.cc	(revision 9772)
@@ -0,0 +1,57 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedPhotPix
+//
+// This is the storage container to hold informations about the pedestal
+// (offset) value of one Pixel (PMT) in units of photons.
+//
+// Version 2:
+// ----------
+//   - added fNumEvents
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotPix.h"
+
+#include "MLog.h"
+
+ClassImp(MPedPhotPix);
+
+MPedPhotPix::MPedPhotPix()
+{
+    Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MPedPhotPix::Clear(Option_t *o)
+{
+    fMean = -1;
+    fRms  = -1;
+    fNumEvents = 0;
+}
Index: /tags/Mars-V0.9/mpedestal/MPedPhotPix.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedPhotPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedPhotPix.h	(revision 9772)
@@ -0,0 +1,38 @@
+#ifndef MARS_MPedPhotPix
+#define MARS_MPedPhotPix
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef MARS_MMath
+#include "MMath.h"
+#endif
+
+class MPedPhotPix : public TObject
+{
+private:
+    Float_t fMean;      // [phot] mean value of pedestal (should be 0)
+    Float_t fRms;       // [phot] rms of mean
+
+    UInt_t  fNumEvents; // [n] number of events used to calculate mean (0=n/a)
+
+public:
+    MPedPhotPix();
+
+    void Clear(Option_t *o="");
+
+    Float_t GetMean() const      { return fMean; }
+    Float_t GetRms() const       { return fRms; }
+    UInt_t  GetNumEvents() const { return fNumEvents; }
+
+    //void SetMean(Float_t f) { fMean = f; }
+    void SetRms(Float_t f)  { MMath::ReducePrecision(f);  fRms  = f; }
+    void Set(Float_t m, Float_t r, UInt_t n=1) { MMath::ReducePrecision(r); MMath::ReducePrecision(m); fMean = m; fRms = r; fNumEvents=n; }
+
+    Bool_t IsValid() const { return fRms>=0; }
+
+    ClassDef(MPedPhotPix, 2) // Storage Container for Pedestal information of one pixel in units of photons
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mpedestal/MPedestalCalc.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedestalCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedestalCalc.cc	(revision 9772)
@@ -0,0 +1,229 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix 11/2002 <mailto:jflix@ifae.es>
+!   Author(s): Thomas Bretz 11/2002 <mailto:tbretz@astro.uni-wuerburg.de>
+!
+!   Copyright: MAGIC Software Development, 2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MPedestalCalc
+//
+//  Task to calculate the pedestals from the event stream.
+//
+//  From the events two streams of pedestals are created like in the
+//  following table
+//  MRawEvtData:    1   2   3   4   5   6   7   8   9  10  11  12
+//  MPedestalCam;1: ------1------   ------2------   ------3------...
+//  MPedestalCam;2:         ------1------   ------2------  ------...
+//
+//  Input Containers:
+//   MRawEvtData
+//
+//  Output Containers:
+//   MPedestalCam;1
+//   MPedestalCam;2
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MHFadcCam.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MPedestalCalc);
+
+MPedestalCalc::MPedestalCalc(const char *name, const char *title)
+    : fNumBranches(2), fTimeSlot(6), fHists(NULL)
+{
+    fName  = name  ? name  : "MPedestalCalc";
+    fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
+
+    AddToBranchList("fHiGainPixId");
+    AddToBranchList("fLoGainPixId");
+    AddToBranchList("fHiGainFadcSamples");
+    AddToBranchList("fLoGainFadcSamples");
+}
+
+Int_t MPedestalCalc::PreProcess(MParList *pList)
+{
+    if (fHists)
+    {
+        *fLog << err << "ERROR - Previous PostProcess not called." << endl;
+        return kFALSE;
+    }
+
+    fHists = new MHFadcCam[fNumBranches];
+    fStart = new MTime    [fNumBranches];
+
+    fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvt)
+    {
+        *fLog << dbginf << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindCreateObj("MPedestalCam");
+    if (!fPedestals)
+        return kFALSE;
+
+    fPedTime = (MTime*)pList->FindCreateObj("MTime", "MPedestalTime");
+    if (!fPedTime)
+        return kFALSE;
+
+    //
+    // Fixme: FindCreateObj --> FindObject
+    //
+    fEvtTime = (MTime*)pList->FindCreateObj("MTime", "MRawEvtTime");
+    if (!fEvtTime)
+        return kFALSE;
+
+    for (int i=0; i<fNumBranches; i++)
+        fStart[i].SetTime(fTimeSlot*10/fNumBranches*i, 0);
+
+    fPedTime->SetDuration(fTimeSlot);
+    fEvtTime->SetTime(0, 0);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Checks whether the current event exceed the validity range of a pedestal
+//  in one of the streams. If this is the case the data from the histogram
+//  is dumped as pedestals into the corresponding containers and the
+//  histograms are reset.
+//
+//  Then the current event is filled into the histograms.
+//
+Int_t MPedestalCalc::Process()
+{
+    //
+    // Time when filling of stream a/b must be restarted
+    //
+    for (int i=0; i<fNumBranches; i++)
+    {
+        Check(i);
+        Fill(i);
+    }
+
+    fEvtTime->SetTime(fEvtTime->GetTimeLo()+10, 0);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill the event in the histogram if the current time of the
+//  event is _after_ the start time for filling
+//
+void MPedestalCalc::Fill(Int_t i)
+{
+    if (*fEvtTime < fStart[i])
+        return;
+
+    fHists[i].Fill(fRawEvt);
+}
+
+// --------------------------------------------------------------------------
+//
+//  If the current time of the event is equal or after the time
+//  which is given by the start time plus the validity range
+//  calculate the corresponding set of pedestals and reset the
+//  histograms
+//
+void MPedestalCalc::Check(Int_t i)
+{
+    if (*fEvtTime-fStart[i] < fTimeSlot*10)
+        return;
+
+    Calc(i);
+
+    fStart[i] = *fEvtTime;
+    fHists[i].ResetHistograms();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes all dynamicly allocated arrays
+//
+Bool_t MPedestalCalc::PostProcess()
+{
+    delete fHists;
+    delete fStart;
+
+    fHists=NULL;
+
+    return kTRUE;
+}
+
+/*
+ #include "MRawEvtData.h"
+ */
+// --------------------------------------------------------------------------
+//
+//  Dumps the mean, rms and their errors from the filled histograms into
+//  the Pedestal container. Sets the ReadyToSaveFlag of the MPedestalCam
+//  container.
+//
+void MPedestalCalc::Calc(Int_t i) const
+{
+    // FIXME! Fit +- 3 sigma to avoid outliers...
+
+    MRawEvtPixelIter pixel(fRawEvt);
+    while (pixel.Next())
+    {
+        const UInt_t pixid = pixel.GetPixelId();
+
+        const TH1 &h = *fHists[i].GetHistHi(pixid);
+
+        const Int_t   entries = (Int_t)h.GetEntries();
+        const Float_t meanhi  = h.GetMean();
+        const Float_t rmshi   = h.GetRMS();
+
+        const Float_t meanhierr = rmshi/sqrt(entries);
+        const Float_t rmshierr  = rmshi/sqrt(entries*2);
+
+        MPedestalPix &pix = (*fPedestals)[pixid];
+        pix.SetPedestal(meanhi, rmshi);
+        pix.SetPedestalRms(meanhierr, rmshierr);
+    }
+
+    *fPedTime = fStart[i];
+
+    fPedTime->SetReadyToSave();
+    fPedestals->SetReadyToSave();
+
+    /*
+     *fLog << i << "[" << fHists[i].GetHistHi(0)->GetEntries()/fRawEvt->GetNumHiGainSamples() << "]:  ";
+     *fLog << fEvtTime->GetTimeLo() << ": Calc [";
+     *fLog << fStart[i].GetTimeLo() << " < ";
+     *fLog << fStart[i].GetTimeLo()+fTimeSlot*10 << "]" << endl;
+     */
+}
Index: /tags/Mars-V0.9/mpedestal/MPedestalCalc.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedestalCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedestalCalc.h	(revision 9772)
@@ -0,0 +1,59 @@
+#ifndef MARS_MPedestalCalc
+#define MARS_MPedestalCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPedestalCalc                                                           //
+//                                                                         //
+// Implementation of ped. Eval. defined in Jan 02                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MHFadCam
+#include "MHFadcCam.h"
+#endif
+
+class MTime;
+class MRawEvtData;
+class MPedestalCam;
+
+class MPedestalCalc : public MTask 
+{
+private:
+    Int_t   fNumBranches;
+    Float_t fTimeSlot;
+
+    MRawEvtData  *fRawEvt;
+    MPedestalCam *fPedestals;  //
+
+    MHFadcCam *fHists;         //[fNumBranches]
+
+    MTime     *fPedTime; // time of the pedestal event
+    MTime     *fEvtTime; // time of the current event
+    MTime     *fStart;   //[fNumBranches] starting time of the current pedestal
+
+
+    void Calc(Int_t i) const;
+    void Fill(Int_t i);
+    void Check(Int_t i);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MPedestalCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetTimeSlot(Float_t newslot) { fTimeSlot = newslot; }
+    void SetNumBranches(Int_t num) { fNumBranches = num; }
+
+    ClassDef(MPedestalCalc, 0) // Task to calculate the pestels from pedestal events
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/mpedestal/MPedestalCam.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedestalCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedestalCam.cc	(revision 9772)
@@ -0,0 +1,560 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz   12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!              Markus Gaug    02/2004 <mailto:markus@ifae.es>
+!              Florian Goebel 06/2004 <mailto:fgoebel@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPedestalCam                                                            //
+//                                                                         //
+// Hold the Pedestal information for all pixels in the camera              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include <TArrayI.h>
+#include <TArrayF.h>
+#include <TArrayD.h>
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MPedestalCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Creates a TClonesArray of MPedestalPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MPedestalCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MPedestalPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MPedestalCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MPedestalPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MPedestalCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+MPedestalCam::MPedestalCam(const char *name, const char *title) 
+    : fTotalEntries(0)
+{
+  fName  = name  ? name  : "MPedestalCam";
+  fTitle = title ? title : "Storage container for all Pedestal Information in the camera";
+  
+  fArray            = new TClonesArray("MPedestalPix", 1);
+  fAverageAreas     = new TClonesArray("MPedestalPix", 1);
+  fAverageSectors   = new TClonesArray("MPedestalPix", 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the following TClonesArray's of MPedestalPix containers (if exist):
+// - fArray
+// - fAverageAreas
+// - fAverageSectors
+//  
+MPedestalCam::~MPedestalCam()
+{
+  delete fArray;
+  delete fAverageAreas;
+  delete fAverageSectors;
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MPedestalCam::Copy(TObject &obj) const
+{
+
+  MParContainer::Copy(obj);
+
+  MPedestalCam &cam = (MPedestalCam&)obj;
+  
+  Int_t n = GetSize();
+  
+  if (n==0)
+    return;
+  
+  cam.InitSize(n);
+  for (int i=0; i<n; i++)
+    (*this)[i].Copy(cam[i]);
+
+  n = GetNumAverageArea();
+  cam.InitAverageAreas(n);
+  for (int i=0; i<n; i++)
+    GetAverageArea(i).Copy(cam.GetAverageArea(i));
+
+  n = GetNumAverageSector();
+  cam.InitAverageSectors(n);
+  for (int i=0; i<n; i++)
+    GetAverageSector(i).Copy(cam.GetAverageSector(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MPedestalCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageAreas
+//
+void MPedestalCam::InitAverageAreas(const UInt_t i)
+{
+  fAverageAreas->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageSectors
+//
+void MPedestalCam::InitAverageSectors(const UInt_t i)
+{
+  fAverageSectors->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MPedestalCam::Init(const MGeomCam &geom)
+{
+  InitSize          (geom.GetNumPixels() );
+  InitAverageAreas  (geom.GetNumAreas()  );
+  InitAverageSectors(geom.GetNumSectors());
+}
+
+// --------------------------------------------------------------------------
+//
+// This function returns the current size of the TClonesArray 
+// independently if the MPedestalPix is filled with values or not.
+//
+// Get the size of the MPedestalCam
+//
+Int_t MPedestalCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageAreas
+// independently if the MPedestalPix is filled with values or not.
+//
+const Int_t MPedestalCam::GetNumAverageArea() const
+{
+  return fAverageAreas->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageSectors
+// independently if the MPedestalPix is filled with values or not.
+//
+const Int_t MPedestalCam::GetNumAverageSector() const
+{
+  return fAverageSectors->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MPedestalPix &MPedestalCam::operator[](Int_t i)
+{
+    return *static_cast<MPedestalPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MPedestalPix &MPedestalCam::operator[](Int_t i) const
+{
+    return *static_cast<MPedestalPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MPedestalPix &MPedestalCam::GetAverageArea(UInt_t i)
+{
+  return *static_cast<MPedestalPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MPedestalPix &MPedestalCam::GetAverageArea(UInt_t i) const 
+{
+  return *static_cast<MPedestalPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MPedestalPix &MPedestalCam::GetAverageSector(UInt_t i)
+{
+  return *static_cast<MPedestalPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MPedestalPix &MPedestalCam::GetAverageSector(UInt_t i) const 
+{
+  return *static_cast<MPedestalPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------
+//
+// Calls the ForEach macro for the TClonesArray fArray with the argument Clear()
+// 
+// Loops over the fAverageAreas, calling the function Clear() for 
+// every entry in fAverageAreas
+//
+// Loops over the fAverageSectors, calling the function Clear() for 
+// every entry in fAverageSectors
+// 
+void MPedestalCam::Clear(Option_t *o)
+{
+    { fArray->ForEach(TObject, Clear)(); }
+    { fAverageAreas->ForEach(TObject, Clear)(); }
+    { fAverageSectors->ForEach(TObject, Clear)(); }
+  
+    fTotalEntries = 0;
+}
+
+void MPedestalCam::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << endl;
+    int id = 0;
+
+    TIter Next(fArray);
+    MPedestalPix *pix;
+    while ((pix=(MPedestalPix*)Next()))
+    {
+        id++;
+
+        if (!pix->IsValid())
+            continue;
+
+        *fLog << id-1 << ": ";
+        *fLog << pix->GetPedestal() << " " << pix->GetPedestalRms() << endl;
+    }
+}
+
+Float_t MPedestalCam::GetPedestalMin(const MGeomCam *geom) const
+{
+    if (fArray->GetEntries() <= 0)
+        return 50.;
+
+    Float_t minval = (*this)[0].GetPedestalRms();
+
+    for (Int_t i=1; i<fArray->GetEntries(); i++)
+    {
+        const MPedestalPix &pix = (*this)[i];
+
+        Float_t testval = pix.GetPedestalRms();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval < minval)
+            minval = testval;
+    }
+    return minval;
+}
+
+Float_t MPedestalCam::GetPedestalMax(const MGeomCam *geom) const
+{
+    if (fArray->GetEntries() <= 0)
+        return 50.;
+
+    Float_t maxval = (*this)[0].GetPedestalRms();
+
+    for (Int_t i=1; i<fArray->GetEntries(); i++)
+    {
+        const MPedestalPix &pix = (*this)[i];
+
+        Float_t testval = pix.GetPedestalRms();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average pedestal for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index) If the bad pixel
+// container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged pedestal (default: -1.)
+// arr[1]: Error (rms) of averaged pedestal (default: 0.)
+//
+TArrayF MPedestalCam::GetAveragedPedPerArea(const MGeomCam &geom, const UInt_t ai, MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean  = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr    = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+
+      const MPedestalPix &pix = (*this)[i];
+      
+      mean  += pix.GetPedestal();
+      mean2 += pix.GetPedestal()*pix.GetPedestal();
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1.;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average pedestal rms for pixel sizes. 
+// The geometry container is used to get the necessary
+// geometry information (area index) If the bad pixel
+// container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged pedestal RMS (default: -1.)
+// arr[1]: Error (rms) of averaged pedestal RMS (default: 0.)
+//
+TArrayF MPedestalCam::GetAveragedRmsPerArea(const MGeomCam &geom, const UInt_t ai, MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t rms  = 0.;
+  Double_t rms2 = 0.;
+  Int_t    nr   = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue; 
+      
+      const UInt_t aidx = geom[i].GetAidx();
+      
+      if (ai != aidx)
+        continue;
+
+      const MPedestalPix &pix = (*this)[i];
+      
+      rms  += pix.GetPedestalRms();
+      rms2 += pix.GetPedestalRms()*pix.GetPedestalRms();
+      nr   ++;
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? rms/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((rms2 - rms*rms/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average pedestal for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index) If the bad pixel
+// container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged pedestal (default: -1.)
+// arr[1]: Error (rms) of averaged pedestal (default: 0.)
+//
+TArrayF MPedestalCam::GetAveragedPedPerSector(const MGeomCam &geom, const UInt_t sec, MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t mean = 0.;
+  Double_t mean2 = 0.;
+  Int_t    nr   = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sec != sector)
+        continue;
+
+      const MPedestalPix &pix = (*this)[i];
+      
+      mean  += pix.GetPedestal();
+      mean2 += pix.GetPedestal()*pix.GetPedestal();
+      nr    ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? mean/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((mean2 - mean*mean/nr)/(nr-1)) : 0;
+  return arr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the average pedestal rms for camera sectors. 
+// The geometry container is used to get the necessary
+// geometry information (area index) If the bad pixel
+// container is given all pixels which have the flag 'kUnsuitableRun' are ignored
+// in the calculation of the size average.
+//
+// Returns a TArrayF of dimension 2: 
+// arr[0]: averaged pedestal RMS (default: -1.)
+// arr[1]: Error (rms) of averaged pedestal RMS (default: 0.)
+//
+TArrayF MPedestalCam::GetAveragedRmsPerSector(const MGeomCam &geom, const UInt_t sec, MBadPixelsCam *bad)
+{
+
+  const Int_t np = GetSize();
+
+  Double_t rms  = 0.;
+  Double_t rms2 = 0.;
+  Int_t    nr   = 0;
+
+  for (int i=0; i<np; i++)
+    {
+      if (bad && (*bad)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        continue;
+      
+      const UInt_t sector = geom[i].GetSector();
+      
+      if (sec != sector)
+        continue;
+
+      const MPedestalPix &pix = (*this)[i];
+      
+      rms  += pix.GetPedestalRms();
+      rms2 += pix.GetPedestalRms()*pix.GetPedestalRms();
+      nr   ++;
+      
+    }
+
+  TArrayF arr(2);
+  arr[0] = nr   ? rms/nr : -1;
+  arr[1] = nr>1 ? TMath::Sqrt((rms2 - rms*rms/nr)/(nr-1)) : 0;
+  return arr;
+  
+}
+
+
+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;
+
+    const Float_t ped      = (*this)[idx].GetPedestal();
+    const Float_t rms      = (*this)[idx].GetPedestalRms();
+
+    switch (type)
+    {
+    case 0:
+        val = ped;
+        break;
+    case 1:
+        val = fTotalEntries > 0 ?
+            rms/TMath::Sqrt((Float_t)fTotalEntries)
+          : (*this)[idx].GetPedestalError();
+        break;
+    case 2:
+        val = rms;
+        break;
+    case 3:
+        val = fTotalEntries > 0 ?
+          rms/TMath::Sqrt((Float_t)fTotalEntries*2.)
+          : (*this)[idx].GetPedestalRmsError();
+        break;
+    default:
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+void MPedestalCam::DrawPixelContent(Int_t idx) const
+{
+    *fLog << warn << "MPedestalCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars-V0.9/mpedestal/MPedestalCam.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedestalCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedestalCam.h	(revision 9772)
@@ -0,0 +1,71 @@
+#ifndef MARS_MPedestalCam
+#define MARS_MPedestalCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+
+class MGeomCam;
+class MPedestalPix;
+class MBadPixelsCam;
+class TArrayF;
+class MPedestalCam : public MParContainer, public MCamEvent
+{
+private:
+
+  TClonesArray *fArray;           //-> FIXME: Change TClonesArray away from a pointer?
+  TClonesArray *fAverageAreas;    //-> Array of MPedestalPix, one per pixel area
+  TClonesArray *fAverageSectors;  //-> Array of MPedestalPix, one per camera sector
+
+  UInt_t fTotalEntries;  // Total number of times, the Process was executed (to estimate the error of pedestal)
+
+public:
+
+  MPedestalCam(const char *name=NULL, const char *title=NULL);
+  ~MPedestalCam();
+  
+  void Clear(Option_t *o="");
+  void Copy(TObject &object) const;
+  
+  // Getters 
+        MPedestalPix &GetAverageArea   ( UInt_t i );
+  const MPedestalPix &GetAverageArea   ( UInt_t i )            const;
+  const Int_t         GetNumAverageArea()                      const;
+        MPedestalPix &GetAverageSector ( UInt_t i );
+  const MPedestalPix &GetAverageSector ( UInt_t i )            const;
+  const Int_t         GetNumAverageSector()                    const;
+  Float_t             GetPedestalMin   ( const MGeomCam *cam ) const;
+  Float_t             GetPedestalMax   ( const MGeomCam *cam ) const;
+  Int_t               GetSize          ()                      const;
+  ULong_t             GetTotalEntries  ()                      const { return fTotalEntries; }
+
+  TArrayF GetAveragedPedPerArea  ( const MGeomCam &geom, const UInt_t ai=0,  MBadPixelsCam *bad=NULL );
+  TArrayF GetAveragedPedPerSector( const MGeomCam &geom, const UInt_t sec=0, MBadPixelsCam *bad=NULL );
+  TArrayF GetAveragedRmsPerArea  ( const MGeomCam &geom, const UInt_t ai=0,  MBadPixelsCam *bad=NULL );
+  TArrayF GetAveragedRmsPerSector( const MGeomCam &geom, const UInt_t sec=0, MBadPixelsCam *bad=NULL );
+  
+        MPedestalPix &operator[]       ( Int_t i             );
+  const MPedestalPix &operator[]       ( Int_t i             ) const;
+
+  void  Init                           ( const MGeomCam &geom);
+  void  InitSize                       ( const UInt_t i      );
+  void  InitAverageAreas               ( const UInt_t i      );
+  void  InitAverageSectors             ( const UInt_t i      );
+
+  void Print(Option_t *o="") const;
+  
+  // Setters
+  void SetTotalEntries(const ULong_t n) { fTotalEntries = n; }
+  
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+
+  ClassDef(MPedestalCam, 1)	// Storage Container for all pedestal information of the camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/MPedestalPix.cc
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedestalPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedestalPix.cc	(revision 9772)
@@ -0,0 +1,134 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz   12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Markus Gaug    04/2004 <mailto:markus@ifae.es>
+!   Author(s): Florian Goebel 06/2004 <mailto:fgoebel@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedestalPix
+//
+// This is the storage container to hold informations about the pedestal
+// (offset) value of one Pixel (PMT).
+//
+//  Float_t fPedestal:
+//   - mean value of pedestal (PMT offset)
+//  Float_t fPedestalRms:
+//   - root mean square / sigma  / standard deviation of pedestal
+//  Float_t fPedestalABoffset:
+//   - the difference between odd slice pedestal mean and the
+//     total pedestal mean (fPedestal). For even slices pedestal
+//     use -fPedestalABoffset.
+//  UInt_t  fNumEvents:
+//   - number of times, the Process was executed (to estimate the error
+//     of pedestal)
+//
+// version 2:
+// ----------
+// added:
+//  fPedestalABoffset   difference between pedestal mean of odd slices and
+//                      the total pedestal mean (fPedestal)
+//  fNumEvents          number of times, the Process was executed
+//                      (to estimate the error of pedestal)
+//
+// version 3:
+// ----------
+// - fValid removed
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MPedestalPix);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Default constructor. Calls Clear()
+//
+MPedestalPix::MPedestalPix()
+{
+    Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MPedestalPix::Clear(Option_t *o)
+{
+    fPedestal         = -1;
+    fPedestalRms      = -1;
+    fPedestalABoffset = -1;
+    fNumEvents        =  0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy 'constructor'
+//
+void MPedestalPix::Copy(TObject &object) const
+{
+
+  MPedestalPix &pix =  (MPedestalPix&)object;
+
+  pix.fPedestal         = fPedestal         ;
+  pix.fPedestalRms      = fPedestalRms      ;
+  pix.fPedestalABoffset = fPedestalABoffset ;
+}
+
+// ------------------------------------------------------------------------
+//
+// Set all values to 0
+//
+void MPedestalPix::InitUseHists()
+{
+    fPedestal         = 0;
+    fPedestalRms      = 0;
+    fPedestalABoffset = 0;
+    fNumEvents        = 0;
+}
+
+// ------------------------------------------------------------------------
+//
+// Set fPedestal=m, fPedestalRms=r, fPedestalABoffset=offs, fNumEvents=n
+//
+void MPedestalPix::Set(Float_t m, Float_t r, Float_t offs, UInt_t n)
+{
+    fPedestal         = m;
+    fPedestalRms      = r;
+    fPedestalABoffset = offs;
+    fNumEvents        = n;
+}
+
+// ------------------------------------------------------------------------
+//
+// Return kTRUE if pedestal rms is valid (>=0)
+//
+Bool_t MPedestalPix::IsValid() const
+{
+    return fPedestalRms>=0;
+}
Index: /tags/Mars-V0.9/mpedestal/MPedestalPix.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/MPedestalPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/MPedestalPix.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MPedestalPix
+#define MARS_MPedestalPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MPedestalPix : public MParContainer
+{
+private:
+    Float_t fPedestal;         // mean value of pedestal (PMT offset)
+    Float_t fPedestalRms;      // root mean square / sigma  / standard deviation of pedestal
+    Float_t fPedestalABoffset; // the difference between odd slice pedestal mean and total mean
+    UInt_t  fNumEvents;        // number of times, the Process was executed (to estimate the error of pedestal)
+
+public:
+    MPedestalPix();
+
+    void Clear(Option_t *o="");
+    void Copy(TObject &object) const;
+    
+    // Using histograms
+    void InitUseHists();
+
+    // Setters
+    void SetPedestal(const Float_t f)         { fPedestal = f; }
+    void SetPedestalRms(const Float_t f)      { fPedestalRms = f; }
+    void SetPedestalABoffset(const Float_t f) { fPedestalABoffset = f; }
+    void SetNumEvents(const UInt_t n)         { fNumEvents = n; }
+
+    void Set(const Float_t m, const Float_t r, const Float_t offs=0, const UInt_t n=0);
+
+    // Getters
+    Float_t GetPedestal()    const { return fPedestal; }
+    Float_t GetPedestalRms() const { return fPedestalRms; }
+    Float_t GetPedestalABoffset() const { return fPedestalABoffset; }
+    Float_t GetPedestalError()    const { return fNumEvents>0 ? fPedestalRms/TMath::Sqrt((Float_t)fNumEvents)   : 0; }
+    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;
+
+    ClassDef(MPedestalPix, 3) // Storage Container for Pedestal information of one pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/mpedestal/Makefile
===================================================================
--- /tags/Mars-V0.9/mpedestal/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/Makefile	(revision 9772)
@@ -0,0 +1,52 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Pedestal
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mraw -I../mmc -I../mgeom \
+           -I../msignal -I../manalysis -I../mbadpixels -I../mhcalib \
+           -I../mhbase -I../mcalib -I../mtrigger
+# MCamEvent
+# MMcPedestalCopy   (MRawRunHeader)
+# MMcPedestalCopy   (MMcRunHeader)
+# MMcPedestalNSBAdd (MGeomCam)
+# MPedCalcPedRun    (MExtractedSignal)
+# MPedPhotCalc      (MCerPhotEvt)
+# MPedPhotCalc      (MBadPixelsCam)
+
+SRCFILES = MMcPedestalCopy.cc \
+           MMcPedestalNSBAdd.cc \
+	   MExtractPedestal.cc \
+           MPedCalcPedRun.cc \
+	   MPedCalcFromLoGain.cc \
+           MPedPhotCalc.cc \
+           MPedPhotCam.cc \
+           MPedPhotPix.cc \
+           MPedestalCam.cc \
+	   MPedestalPix.cc \
+	   MPedCalcFromData.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mpedestal/PedestalIncl.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/PedestalIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/PedestalIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mpedestal/PedestalLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mpedestal/PedestalLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mpedestal/PedestalLinkDef.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MMcPedestalCopy+;
+#pragma link C++ class MMcPedestalNSBAdd+;
+
+#pragma link C++ class MPedPhotCalc+;
+#pragma link C++ class MPedPhotCam+;
+#pragma link C++ class MPedPhotPix+;
+
+#pragma link C++ class MExtractPedestal+;
+#pragma link C++ class MPedCalcPedRun+;
+#pragma link C++ class MPedCalcFromLoGain+;
+#pragma link C++ class MPedestalCam+;
+#pragma link C++ class MPedestalPix+;
+#pragma link C++ class MPedCalcFromData+;
+
+#endif
Index: /tags/Mars-V0.9/mpointing/MPointing.cc
===================================================================
--- /tags/Mars-V0.9/mpointing/MPointing.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MPointing.cc	(revision 9772)
@@ -0,0 +1,709 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPointing
+// =========
+//
+// This is the class used for the pointing correction done in the MAGIC
+// drive software cosy. NEVER CHANGE IT WITHOUT CONTACTING THE AUTHOR FIRST!
+//
+// Variables/Coefficients
+// ----------------------
+//
+//    Double_t fIe   ; // [rad] Index Error in Elevation
+//    Double_t fIa   ; // [rad] Index Error in Azimuth
+//
+//    Double_t fFlop ; // [rad] Vertical Sag
+//     * do not use if not data: Zd<0
+//
+//    Double_t fNpae ; // [rad] Az-El Nonperpendicularity
+//
+//    Double_t fCa   ; // [rad] Left-Right Collimation Error
+//
+//    Double_t fAn   ; // [rad] Azimuth Axis Misalignment (N-S)
+//    Double_t fAw   ; // [rad] Azimuth Axis Misalignment (E-W)
+//
+//    Double_t fTf   ; // [rad] Tube fluxture (sin)
+//     * same as ecec if no data: Zd<0
+//    Double_t fTx   ; // [rad] Tube fluxture (tan)
+//     * do not use with NPAE if no data: Zd<0
+//
+//    Double_t fNrx  ; // [rad] Nasmyth rotator displacement, horizontan
+//    Double_t fNry  ; // [rad] Nasmyth rotator displacement, vertical
+//
+//    Double_t fCrx  ; // [rad] Alt/Az Coude Displacement (N-S)
+//    Double_t fCry  ; // [rad] Alt/Az Coude Displacement (E-W)
+//
+//    Double_t fEces ; // [rad] Elevation Centering Error (sin)
+//    Double_t fAces ; // [rad] Azimuth Centering Error (sin)
+//    Double_t fEcec ; // [rad] Elevation Centering Error (cos)
+//    Double_t fAcec ; // [rad] Azimuth Centering Error (cos)
+//
+//    Double_t fMagic1;// [rad] ZA Hysteresis
+//    Double_t fMagic2;// [rad] undefined
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MPointing.h"
+
+#include <fstream>
+
+#include <TVector3.h>
+
+#include <TMinuit.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+
+ClassImp(AltAz);
+ClassImp(ZdAz);
+ClassImp(MPointing);
+
+using namespace std;
+
+#undef DEBUG
+//#define DEBUG(txt) txt
+#define DEBUG(txt)
+
+const Int_t MPointing::fNumPar=19;
+
+void MPointing::Init(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPointing";
+    fTitle = title ? title : "Pointing correction model for the MAGIC telescope";
+
+    fCoeff = new Double_t*[fNumPar];
+    fNames = new TString[fNumPar];
+    fDescr = new TString[fNumPar];
+
+    fCoeff[ 0] = &fIa;      fNames[ 0] = "IA";
+    fCoeff[ 1] = &fIe;      fNames[ 1] = "IE";
+    fCoeff[ 2] = &fFlop;    fNames[ 2] = "FLOP";
+    fCoeff[ 3] = &fAn;      fNames[ 3] = "AN";
+    fCoeff[ 4] = &fAw;      fNames[ 4] = "AW";
+    fCoeff[ 5] = &fNpae;    fNames[ 5] = "NPAE";
+    fCoeff[ 6] = &fCa;      fNames[ 6] = "CA";
+    fCoeff[ 7] = &fTf;      fNames[ 7] = "TF";
+    fCoeff[ 8] = &fTx;      fNames[ 8] = "TX";
+    fCoeff[ 9] = &fEces;    fNames[ 9] = "ECES";
+    fCoeff[10] = &fAces;    fNames[10] = "ACES";
+    fCoeff[11] = &fEcec;    fNames[11] = "ECEC";
+    fCoeff[12] = &fAcec;    fNames[12] = "ACEC";
+    fCoeff[13] = &fNrx;     fNames[13] = "NRX";
+    fCoeff[14] = &fNry;     fNames[14] = "NRY";
+    fCoeff[15] = &fCrx;     fNames[15] = "CRX";
+    fCoeff[16] = &fCry;     fNames[16] = "CRY";
+    fCoeff[17] = &fMagic1;  fNames[17] = "MAGIC1";
+    fCoeff[18] = &fMagic2;  fNames[18] = "MAGIC2";
+
+    fDescr[ 0] =  "Index Error Azimuth";
+    fDescr[ 1] =  "Index Error Zenith Distance";
+    fDescr[ 2] =  "Vertical Sag";
+    fDescr[ 3] =  "Azimuth Axis Misalignment (N-S)";
+    fDescr[ 4] =  "Azimuth Axis Misalignment (E-W)";
+    fDescr[ 5] =  "Az-El Nonperpendicularity";
+    fDescr[ 6] =  "Left-Right Collimation Error";
+    fDescr[ 7] =  "Tube fluxture (sin)";
+    fDescr[ 8] =  "Tube fluxture (tan)";
+    fDescr[ 9] =  "Elevation Centering Error (sin)";
+    fDescr[10] =  "Azimuth Centering Error (sin)";
+    fDescr[11] =  "Elevation Centering Error (cos)";
+    fDescr[12] =  "Azimuth Centering Error (cos)";
+    fDescr[13] =  "Nasmyth rotator displacement (horizontal)";
+    fDescr[14] =  "Nasmyth rotator displacement (vertical)";
+    fDescr[15] =  "Alt/Az Coude Displacement (N-S)";
+    fDescr[16] =  "Alt/Az Coude Displacement (E-W)";
+    fDescr[17] =  "n/a <ZA Hysteresis>";
+    fDescr[18] =  "n/a";
+}
+void MPointing::Reset()
+{
+    Clear();
+}
+
+void MPointing::Load(const char *name)
+{
+    /*
+     ! MMT 1987 July 8
+     ! T   36   7.3622   41.448  -0.0481
+     !   IA        -37.5465    20.80602
+     !   IE        -13.9180     1.25217
+     !   NPAE       +7.0751    26.44763
+     !   CA         -6.9149    32.05358
+     !   AN         +0.5053     1.40956
+     !   AW         -2.2016     1.37480
+     ! END
+     */
+
+    ifstream fin(name);
+    if (!fin)
+    {
+        *fLog << err << "ERROR - Cannot open file '" << name << "'" << endl;
+        return;
+    }
+
+    char c;
+    while (fin && fin.get()!='\n');
+    fin >> c;
+
+    if (c!='S' && c!='s')
+    {
+        *fLog << err << "Error: This in not a model correcting the star position (" << c << ")" << endl;
+        return;
+    }
+
+    Clear();
+
+    cout << endl;
+
+    Double_t val;
+    fin >> val;
+    *fLog << inf << "Number of observed stars: " << val << endl;
+    fin >> val;
+    *fLog << inf << "Sky RMS: " << val << "\"" << endl;
+    fin >> val;
+    *fLog << inf << "Refraction Constant A: " << val << "\"" << endl;
+    fin >> val;
+    *fLog << inf << "Refraction Constant B: " << val << "\"" << endl;
+
+    *fLog << inf << endl;
+
+    *fLog << inf << "  & = Name            Value                  Sigma" << endl;
+    *fLog << inf << "--------------------------------------------------" << endl;
+
+    while (fin)
+    {
+        TString str;
+        fin >> str;
+
+        if (str=="END")
+            break;
+
+        if (str[0]=='&')
+        {
+            *fLog << inf << " & ";
+            str.Remove(0);
+        }
+        else
+            cout << "   ";
+
+        if (str[1]=='=')
+        {
+            *fLog << inf << "=  ";
+            str.Remove(0);
+        }
+        else
+            *fLog << inf << "   ";
+
+        fin >> val;
+        *fLog << inf << str << "\t" << setw(11) << val << "°     \t";
+        val *= TMath::DegToRad();
+
+        // Find parameter
+        Int_t n = -1;
+        for (int i=0; i<fNumPar; i++)
+            if (str==fNames[i])
+            {
+                n = i;
+                *fCoeff[i] = val;
+                break;
+            }
+
+        fin >> val;
+        *fLog << inf << setw(9) << val << "°" << endl;
+
+        // corresponding error
+        fError[n] = val*TMath::DegToRad();
+    }
+    *fLog << inf << endl;
+}
+
+void MPointing::Save(const char *name)
+{
+    /*
+     ! MMT 1987 July 8
+     ! T   36   7.3622   41.448  -0.0481
+     !   IA        -37.5465    20.80602
+     !   IE        -13.9180     1.25217
+     !   NPAE       +7.0751    26.44763
+     !   CA         -6.9149    32.05358
+     !   AN         +0.5053     1.40956
+     !   AW         -2.2016     1.37480
+     ! END
+     */
+
+    ofstream fout(name);
+    if (!fout)
+    {
+        cout << "Error: Cannot open file '" << name << "'" << endl;
+        return;
+    }
+
+    MTime t;
+    t.Now();
+
+    fout << "MAGIC1 " << t << endl;
+    fout << "S   00   000000   000000  0000000" << endl;
+    fout << setprecision(8);
+    for (int i=0; i<fNumPar; i++)
+    {
+        fout << " " << setw(6) << GetVarName(i) << " ";
+        fout << setw(13) << *fCoeff[i]*kRad2Deg << "   ";
+        fout << setw(11) << fError[i]*kRad2Deg << endl;
+    }
+    fout << "END" << endl;
+}
+
+Double_t MPointing::Sign(Double_t val, Double_t alt)
+{
+    // Some pointing corrections are defined as Delta ZA, which
+    // is (P. Wallace) defined [0,90]deg while Alt is defined
+    // [0,180]deg
+    return (TMath::Pi()/2-alt < 0 ? -val : val);
+}
+
+AltAz MPointing::AddOffsets(const AltAz &aa) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p = aa;
+
+    const AltAz I(fIe, fIa);
+    p += I;
+
+    return p;
+}
+
+AltAz MPointing::SubtractOffsets(const AltAz &aa) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p = aa;
+
+    const AltAz I(fIe, fIa);
+    p -= I;
+
+    return p;
+}
+
+AltAz MPointing::CalcAnAw(const AltAz &p, Int_t sign) const
+{
+    // Corrections for AN and AW without approximations
+    // as done by Patrick Wallace. The approximation cannot
+    // be used for MAGIC because the correctioon angle
+    // AW (~1.5deg) is not small enough.
+
+    // Vector in cartesian coordinates
+    TVector3 v1;
+
+    // Set Azimuth and Elevation
+    v1.SetMagThetaPhi(1, TMath::Pi()/2-p.Alt(), p.Az());
+
+
+    TVector3 v2(v1);
+//    cout << sign << endl;
+
+//    cout << "v1: " << v1.Theta()*TMath::RadToDeg() << " " << v1.Phi()*TMath::RadToDeg() << endl;
+
+    // Rotate around the x- and y-axis
+    v1.RotateY(sign*fAn);
+    v1.RotateX(sign*fAw);
+
+//    cout << "v1: " << v1.Theta()*TMath::RadToDeg() << " " << v1.Phi()*TMath::RadToDeg() << endl;
+//    cout << "v2: " << v2.Theta()*TMath::RadToDeg() << " " << v2.Theta()*TMath::RadToDeg() << endl;
+
+   // cout << "dv: " << (v2.Theta()-v1.Theta())*TMath::RadToDeg() << " " << (v2.Phi()-v1.Phi())*TMath::RadToDeg() << endl;
+
+    Double_t dalt = v1.Theta()-v2.Theta();
+    Double_t daz  = v1.Phi()  -v2.Phi();
+
+    //cout << dalt*TMath::RadToDeg() << " " << daz*TMath::RadToDeg() << endl;
+
+    if (daz>TMath::Pi())
+        daz -= TMath::TwoPi();
+    if (daz<-TMath::Pi())
+        daz += TMath::TwoPi();
+
+//    if (daz>TMath::Pi()/2)
+//    {
+//    }
+
+    AltAz d(dalt, daz);
+    return d;
+
+    // Calculate Delta Azimuth and Delta Elevation
+    /*
+    AltAz d(TMath::Pi()/2-v1.Theta(), v1.Phi());
+
+    cout << "p :  " << p.Alt()*TMath::RadToDeg() << " " << p.Az()*TMath::RadToDeg() << endl;
+    cout << "d :  " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+    d -= p;
+    cout << "d-p: " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+    d *= sign;
+    cout << "d* : " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+
+
+    cout << "p2:  " << 90-p.Alt()*TMath::RadToDeg() << " " << p.Az()*TMath::RadToDeg() << endl;
+    cout << "d2:  " << 90-d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+
+    Int_t s1 = 90-d.Alt()*TMath::RadToDeg() < 0 ? -1 : 1;
+    Int_t s2 = 90-p.Alt()*TMath::RadToDeg() < 0 ? -1 : 1;
+
+
+    if (s1 != s2)
+    {
+        //90-d.Alt() <-- -90+d.Alt()
+
+        d.Alt(d.Alt()-TMath::Pi());
+        cout << "Alt-" << endl;
+    }
+    cout << "d': " << 90-d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;*/
+ /*
+    // Fix 'direction' of output depending on input vector
+    if (TMath::Pi()/2-sign*p.Alt()<0)
+    {
+        d.Alt(d.Alt()-TMath::Pi());
+        cout << "Alt-" << endl;
+    }
+    //if (TMath::Pi()/2-sign*p.Alt()>TMath::Pi())
+    //{
+    //    d.Alt(TMath::Pi()-d.Alt());
+    //    cout << "Alt+" << endl;
+    //}
+
+    // Align correction into [-180,180]
+    while (d.Az()>TMath::Pi())
+    {
+        d.Az(d.Az()-TMath::Pi()*2);
+        cout << "Az-" << endl;
+    }
+    while (d.Az()<-TMath::Pi())
+    {
+        d.Az(d.Az()+TMath::Pi()*2);
+        cout << "Az+" << endl;
+    }
+   */
+    return d;
+}
+
+
+AltAz MPointing::Correct(const AltAz &aa) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p = aa;
+
+    DEBUG(cout << setprecision(16));
+    DEBUG(cout << "Bend7: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz CRX(-fCrx*sin(p.Az()-p.Alt()),  fCrx*cos(p.Az()-p.Alt())/cos(p.Alt()));
+    const AltAz CRY(-fCry*cos(p.Az()-p.Alt()), -fCry*sin(p.Az()-p.Alt())/cos(p.Alt()));
+    p += CRX;
+    p += CRY;
+
+    DEBUG(cout << "Bend6: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz NRX(fNrx*sin(p.Alt()), -fNrx);
+    const AltAz NRY(fNry*cos(p.Alt()), -fNry*tan(p.Alt()));
+    p += NRX;
+    p += NRY;
+
+    DEBUG(cout << "Bend5: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz CES(-fEces*sin(p.Alt()), -fAces*sin(p.Az()));
+    const AltAz CEC(-fEcec*cos(p.Alt()), -fAcec*cos(p.Az()));
+    p += CES;
+    p += CEC;
+
+    DEBUG(cout << "Bend4: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz TX(Sign(fTx/tan(p.Alt()), p.Alt()), 0);
+    const AltAz TF(Sign(fTf*cos(p.Alt()), p.Alt()), 0);
+    //p += TX;
+    p += TF;
+
+
+    DEBUG(cout << "Bend3: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    /*
+     //New Corrections for NPAE and CA:
+     TVector3 v(1.,1.,1.); // Vector in cartesian coordinates
+
+     //Set Azimuth and Elevation
+     v.SetPhi(p.Az());
+     v.SetTheta(TMath::Pi()/2-p.Alt());
+     //Rotation Vectors:
+     TVector3 vNpae(             cos(p.Az()),              sin(p.Az()),             0);
+     TVector3   vCa( -cos(p.Az())*cos(p.Alt()), -sin(p.Az())*cos(p.Alt()), sin(p.Alt()));
+     //Rotate around the vectors vNpae and vCa
+     v.Rotate(fNpae, vNpae);
+     v.Rotate(fCa,     vCa);
+
+     p.Az(v.Phi());
+     p.Alt(TMath::Pi()/2-v.Theta());
+     */
+
+    //Old correction terms for Npae and Ca:
+    const AltAz CA(0, -fCa/cos(p.Alt()));
+    p += CA;
+
+    const AltAz NPAE(0, -fNpae*tan(p.Alt()));
+    p += NPAE;
+
+    DEBUG(cout << "Bend2: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz ANAW(CalcAnAw(p, -1));
+    p += ANAW;
+
+    /* Old correction terms for An and Aw:
+     const AltAz AW( fAw*sin(p.Az()), -fAw*cos(p.Az())*tan(p.Alt()));
+     const AltAz AN(-fAn*cos(p.Az()), -fAn*sin(p.Az())*tan(p.Alt()));
+     p += AW;
+     p += AN;
+    */
+
+    DEBUG(cout << "Bend1: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz FLOP(Sign(fFlop, p.Alt()), 0);
+    p += FLOP;
+
+    const AltAz MAGIC1(fMagic1*TMath::Sign(1., sin(p.Az())), 0);
+    p += MAGIC1;
+
+    const AltAz I(fIe, fIa);
+    p += I;
+
+    DEBUG(cout << "Bend0: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    return p;
+}
+
+AltAz MPointing::CorrectBack(const AltAz &aa) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p = aa;
+
+    DEBUG(cout << setprecision(16));
+    DEBUG(cout << "Back0: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz I(fIe, fIa);
+    p -= I;
+
+    const AltAz MAGIC1(fMagic1*TMath::Sign(1., sin(p.Az())), 0);
+    p -= MAGIC1;
+
+    //const AltAz MAGIC1(fMagic1*sin(p.Az()), 0);
+    //p -= MAGIC1;
+
+    const AltAz FLOP(Sign(fFlop, p.Alt()), 0);
+    p -= FLOP;
+
+    DEBUG(cout << "Back1: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    /* Old correction terms for An and Aw:
+     const AltAz AN(-fAn*cos(p.Az()), -fAn*sin(p.Az())*tan(p.Alt()));
+     const AltAz AW( fAw*sin(p.Az()), -fAw*cos(p.Az())*tan(p.Alt()));
+     p -= AN;
+     p -= AW;
+     */
+
+    const AltAz ANAW(CalcAnAw(p, -1));
+    p -= ANAW;
+
+    DEBUG(cout << "Back2: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    //Old Correction terms for Npae and Ca:
+    const AltAz NPAE(0, -fNpae*tan(p.Alt()));
+    p -= NPAE;
+
+    const AltAz CA(0, -fCa/cos(p.Alt()));
+    p -= CA;
+
+    /*
+     //New Correction term for Npae and Ca:
+     TVector3 v2(1.,1.,1.); // Vector in cartesian coordinates
+     //Set Azimuth and Elevation
+     v2.SetPhi(p.Az());
+     v2.SetTheta(TMath::Pi()/2-p.Alt());
+     //Rotation Vectors:
+     TVector3 vNpae(             cos(p.Az()),              sin(p.Az()),             0);
+     TVector3   vCa( -cos(p.Az())*cos(p.Alt()), -sin(p.Az())*cos(p.Alt()), sin(p.Alt()));
+     //Rotate around the vectors vCa and vNpae
+     v2.Rotate(-fCa,     vCa);
+     v2.Rotate(-fNpae, vNpae);
+
+     p.Az(v2.Phi());
+     p.Alt(TMath::Pi()/2-v2.Theta());
+    */
+
+    DEBUG(cout << "Back3: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz TF(Sign(fTf*cos(p.Alt()), p.Alt()), 0);
+    const AltAz TX(Sign(fTx/tan(p.Alt()), p.Alt()), 0);
+    p -= TF;
+    //p -= TX;
+
+    DEBUG(cout << "Back4: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz CEC(-fEcec*cos(p.Alt()), -fAcec*cos(p.Az()));
+    const AltAz CES(-fEces*sin(p.Alt()), -fAces*sin(p.Az()));
+    p -= CEC;
+    p -= CES;
+
+    DEBUG(cout << "Back5: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz NRY(fNry*cos(p.Alt()), -fNry*tan(p.Alt()));
+    const AltAz NRX(fNrx*sin(p.Alt()), -fNrx);
+    p -= NRY;
+    p -= NRX;
+
+    DEBUG(cout << "Back6: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    const AltAz CRY(-fCry*cos(p.Az()-p.Alt()), -fCry*sin(p.Az()-p.Alt())/cos(p.Alt()));
+    const AltAz CRX(-fCrx*sin(p.Az()-p.Alt()),  fCrx*cos(p.Az()-p.Alt())/cos(p.Alt()));
+    p -= CRY;
+    p -= CRX;
+
+    DEBUG(cout << "Back7: " << 90-p.Alt()*180/TMath::Pi() << " " << p.Az()*180/TMath::Pi() << endl);
+
+    return p;
+}
+
+ZdAz MPointing::Correct(const ZdAz &zdaz) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p(TMath::Pi()/2-zdaz.Zd(), zdaz.Az());
+    AltAz c = Correct(p);
+    return ZdAz(TMath::Pi()/2-c.Alt(), c.Az());
+}
+
+TVector3 MPointing::Correct(const TVector3 &v) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p(TMath::Pi()/2-v.Theta(), v.Phi());
+    AltAz c = Correct(p);
+    TVector3 rc;
+    rc.SetMagThetaPhi(1, TMath::Pi()/2-c.Alt(), c.Az());
+    return rc;
+}
+
+ZdAz MPointing::CorrectBack(const ZdAz &zdaz) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p(TMath::Pi()/2-zdaz.Zd(), zdaz.Az());
+    AltAz c = CorrectBack(p);
+    return ZdAz(TMath::Pi()/2-c.Alt(), c.Az());
+}
+
+TVector3 MPointing::CorrectBack(const TVector3 &v) const
+{
+    // Correct [rad]
+    // zdaz    [rad]
+    AltAz p(TMath::Pi()/2-v.Theta(), v.Phi());
+    AltAz c = CorrectBack(p);
+    TVector3 rc;
+    rc.SetMagThetaPhi(1, TMath::Pi()/2-c.Alt(), c.Az());
+    return rc;
+}
+
+void MPointing::SetParameters(const Double_t *par, Int_t n)
+{
+    Clear();
+
+    while (n--)
+        *fCoeff[n] = par[n]/kRad2Deg;
+}
+
+void MPointing::GetParameters(Double_t *par, Int_t n) const
+{
+    while (n--)
+        par[n] = *fCoeff[n]*kRad2Deg;
+}
+
+void MPointing::SetMinuitParameters(TMinuit &m, Int_t n) const
+{
+    if (n<0)
+        n = fNumPar;
+
+    Int_t ierflg = 0;
+
+    while (n--)
+        m.mnparm(n, fNames[n], *fCoeff[n]*kRad2Deg,  1, -360, 360, ierflg);
+}
+
+void MPointing::GetMinuitParameters(TMinuit &m, Int_t n)
+{
+    if (n<0 || n>m.GetNumPars())
+        n = m.GetNumPars();
+
+    while (n--)
+    {
+        m.GetParameter(n, *fCoeff[n], fError[n]);
+        *fCoeff[n] /= kRad2Deg;
+        fError[n]  /= kRad2Deg;
+    }
+}
+/*
+void FormatPar(TMinuit &m, Int_t n)
+{
+    Double_t par, err;
+    m.GetParameter(n, par, err);
+
+    int expp = (int)log10(par);
+    int expe = (int)log10(err);
+
+    if (err<2*pow(10, expe))
+        expe--;
+
+    Int_t exp = expe>expp ? expp : expe;
+
+    par = (int)(par/pow(10, exp)) * pow(10, exp);
+    err = (int)(err/pow(10, exp)) * pow(10, exp);
+
+    cout << par << " +- " << err << flush;
+}
+*/
+void MPointing::PrintMinuitParameters(TMinuit &m, Int_t n) const
+{
+    if (n<0)
+        n = m.GetNumPars();
+
+    cout << setprecision(3);
+
+    Double_t par, err;
+
+    while (n--)
+    {
+        m.GetParameter(n, par, err);
+        cout << Form(" %2d %6s: ", n, (const char*)fNames[n]);
+        cout << setw(8) << par << " \xb1 " << setw(6) <<  err << endl;
+    }
+}
Index: /tags/Mars-V0.9/mpointing/MPointing.h
===================================================================
--- /tags/Mars-V0.9/mpointing/MPointing.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MPointing.h	(revision 9772)
@@ -0,0 +1,222 @@
+#ifndef MARS_MPointing
+#define MARS_MPointing
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+// ---------------------------------------------------
+// FIXME: Replace coord.h completely with this!
+#ifndef __MARS__
+#include "coord.h"
+#else
+#include <TVector2.h>
+class AltAz : public TVector2
+{
+public:
+    AltAz(Double_t alt, Double_t az) : TVector2(alt, az)
+    {
+    }
+    Double_t Alt() const { return fX; }
+    Double_t Az() const  { return fY; }
+    ClassDef(AltAz, 1)
+};
+
+class ZdAz : public TVector2
+{
+public:
+    ZdAz(Double_t zd, Double_t az) : TVector2(zd, az)
+    {
+    }
+    Double_t Zd() const { return fX; }
+    Double_t Az() const { return fY; }
+    ClassDef(ZdAz, 1)
+};
+#endif
+// ---------------------------------------------------
+
+class TMinuit;
+
+class MPointing : public MParContainer
+{
+private:
+    static const Int_t fNumPar;
+
+    Double_t fIe   ; // [rad] Index Error in Elevation
+    Double_t fIa   ; // [rad] Index Error in Azimuth
+    Double_t fFlop ; // [rad] Vertical Sag
+    Double_t fNpae ; // [rad] Az-El Nonperpendicularity
+    Double_t fCa   ; // [rad] Left-Right Collimation Error
+    Double_t fAn   ; // [rad] Azimuth Axis Misalignment (N-S)
+    Double_t fAw   ; // [rad] Azimuth Axis Misalignment (E-W)
+    Double_t fTf   ; // [rad] Tube fluxture (sin)
+    Double_t fTx   ; // [rad] Tube fluxture (tan)
+    Double_t fNrx  ; // [rad] Nasmyth rotator displacement, horizontal
+    Double_t fNry  ; // [rad] Nasmyth rotator displacement, vertical
+    Double_t fCrx  ; // [rad] Alt/Az Coude Displacement (N-S)
+    Double_t fCry  ; // [rad] Alt/Az Coude Displacement (E-W)
+    Double_t fEces ; // [rad] Elevation Centering Error (sin)
+    Double_t fAces ; // [rad] Azimuth Centering Error (sin)
+    Double_t fEcec ; // [rad] Elevation Centering Error (cos)
+    Double_t fAcec ; // [rad] Azimuth Centering Error (cos)
+    Double_t fMagic1; // [rad] Magic Term (what is it?)
+    Double_t fMagic2; // [rad] Magic Term (what is it?)
+
+    Double_t **fCoeff; //!
+    TString   *fNames; //!
+    TString   *fDescr; //!
+
+    TArrayD   fError;
+
+    void Init(const char *name=0, const char *title=0);
+
+    void Clear(Option_t *o="")
+    {
+        for (int i=0; i<fNumPar; i++)
+        {
+            *fCoeff[i] = 0;
+            fError[i] = 0;
+        }
+    }
+
+    static Double_t Sign(Double_t val, Double_t alt);
+    AltAz CalcAnAw(const AltAz &p, Int_t sign) const;
+
+public:
+    MPointing() { fError.Set(fNumPar); Init(); Clear(); }
+    MPointing(const char *name) { fError.Set(fNumPar); Init(); Clear(); Load(name); }
+    virtual ~MPointing() { delete fNames; delete fCoeff; delete fDescr; }
+
+    void Load(const char *name);
+    void Save(const char *name);
+
+    void Reset();
+
+    ZdAz     Correct(const ZdAz &zdaz) const;
+    AltAz    Correct(const AltAz &aaz) const;
+    TVector3 Correct(const TVector3 &v) const;
+
+    ZdAz     CorrectBack(const ZdAz &zdaz) const;
+    AltAz    CorrectBack(const AltAz &aaz) const;
+    TVector3 CorrectBack(const TVector3 &v) const;
+
+    ZdAz     operator()(const ZdAz &zdaz)  const { return Correct(zdaz); }
+    AltAz    operator()(const AltAz &aaz)  const { return Correct(aaz); }
+    TVector3 operator()(const TVector3 &v) const { return Correct(v); }
+
+    ZdAz operator()(const ZdAz &zdaz, void (*fcn)(ZdAz &zdaz, Double_t *par)) const
+    {
+        Double_t par[fNumPar];
+        GetParameters(par);
+        ZdAz za = zdaz;
+        fcn(za, par);
+        return za;
+    }
+
+    AltAz operator()(const AltAz &aaz, void (*fcn)(AltAz &aaz, Double_t *par)) const
+    {
+        Double_t par[fNumPar];
+        GetParameters(par);
+        AltAz aa = aaz;
+        fcn(aa, par);
+        return aa;
+    }
+
+    TVector3 operator()(const TVector3 &aaz, void (*fcn)(TVector3 &aaz, Double_t *par)) const
+    {
+        Double_t par[fNumPar];
+        GetParameters(par);
+        TVector3 v = aaz;
+        fcn(v, par);
+        return v;
+    }
+
+    AltAz  AddOffsets(const AltAz &aa) const;
+    ZdAz   AddOffsets(const ZdAz &zdaz) const
+    {
+        AltAz p(TMath::Pi()/2-zdaz.Zd(), zdaz.Az());
+        AltAz c = AddOffsets(p);
+        return ZdAz(TMath::Pi()/2-c.Alt(), c.Az());
+    }
+    TVector3 AddOffsets(const TVector3 &v) const
+    {
+        AltAz p(TMath::Pi()/2-v.Theta(), v.Phi());
+        AltAz c = AddOffsets(p);
+        TVector3 rc;
+        rc.SetMagThetaPhi(1, TMath::Pi()/2-c.Alt(), c.Az());
+        return rc;
+    }
+
+    AltAz  SubtractOffsets(const AltAz &aa) const;
+    ZdAz   SubtractOffsets(const ZdAz &zdaz) const
+    {
+        AltAz p(TMath::Pi()/2-zdaz.Zd(), zdaz.Az());
+        AltAz c = SubtractOffsets(p);
+        return ZdAz(TMath::Pi()/2-c.Alt(), c.Az());
+    }
+    TVector3 SubtractOffsets(const TVector3 &v) const
+    {
+        AltAz p(TMath::Pi()/2-v.Theta(), v.Phi());
+        AltAz c = SubtractOffsets(p);
+        TVector3 rc;
+        rc.SetMagThetaPhi(1, TMath::Pi()/2-c.Alt(), c.Az());
+        return rc;
+    }
+
+    void SetParameters(const Double_t *par, Int_t n=fNumPar);
+    void GetParameters(Double_t *par, Int_t n=fNumPar) const;
+
+    void SetParameters(const TArrayD &par)
+    {
+        SetParameters(par.GetArray(), par.GetSize());
+    }
+    void GetParameters(TArrayD &par) const
+    {
+        par.Set(fNumPar);
+        GetParameters(par.GetArray());
+    }
+    void GetError(TArrayD &par) const
+    {
+        par = fError;
+        for (int i=0; i<fNumPar; i++)
+            par[i] *= TMath::RadToDeg();
+    }
+
+    void SetMinuitParameters(TMinuit &m, Int_t n=-1) const;
+    void GetMinuitParameters(TMinuit &m, Int_t n=-1);
+    void PrintMinuitParameters(TMinuit &m, Int_t n=-1) const;
+
+    const TString &GetVarName(int i) const { return fNames[i]; }
+    const TString &GetDescription(int i) const { return fDescr[i]; }
+
+    /*
+     Double_t GetIe() const { return fIe; }
+     Double_t GetIa() const { return fIa; }
+     Double_t GetCa() const { return fCa; }
+     Double_t GetAn() const { return fAn; }
+     Double_t GetAw() const { return fAw; }
+     Double_t GetNrx() const { return fNrx; }
+     Double_t GetNry() const { return fNry; }
+     Double_t GetCrx() const { return fNrx; }
+     Double_t GetCry() const { return fNry; }
+     Double_t GetEces() const { return fEces; }
+     Double_t GetEcec() const { return fEcec; }
+     Double_t GetAces() const { return fAces; }
+     Double_t GetAcec() const { return fAcec; }
+     Double_t GetNpae() const { return fNpae; }
+     */
+
+    static const Int_t GetNumPar() { return fNumPar; }
+
+    ClassDef(MPointing, 1) // Pointing Model for MAGIC
+};
+
+#endif
Index: /tags/Mars-V0.9/mpointing/MPointingPos.cc
===================================================================
--- /tags/Mars-V0.9/mpointing/MPointingPos.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MPointingPos.cc	(revision 9772)
@@ -0,0 +1,76 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPointingPos
+//
+// In this container we store the corrected pointing position of the
+// telscope. The pointing coordinates are read into MReportDrive together
+// with its time.
+//
+// MPointingPosCalc afterwards calculates corrections and checks for the
+// cosistency of the coordinates. The result (the real coordinates)
+// are stored in this container. No further correction should be necessary
+// using MPointingPos.
+//
+// If you need the rotation angle of the starfield in the camera you can
+// get it from here.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPointingPos.h"
+
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MAstroSky2Local.h"
+
+ClassImp(MPointingPos);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Get the corresponding rotation angle of the sky coordinate system
+// seen with an Alt/Az telescope calculated from the stored local
+// (Zd/Az) coordinates.
+//
+// For more information see MAstro::RotationAngle
+//
+Double_t MPointingPos::RotationAngle(const MObservatory &o) const
+{
+    return o.RotationAngle(fZd*TMath::DegToRad(), fAz*TMath::DegToRad());
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the corresponding rotation angle of the sky coordinate system
+// seen with an Alt/Az telescope calculated from the stored sky
+// (Ra/Dec) coordinates.
+//
+// For more information see MAstro::RotationAngle
+//
+Double_t MPointingPos::RotationAngle(const MObservatory &o, const MTime &t) const
+{
+    return MAstroSky2Local(t, o).RotationAngle(GetRaRad(), GetDecRad());
+}
Index: /tags/Mars-V0.9/mpointing/MPointingPos.h
===================================================================
--- /tags/Mars-V0.9/mpointing/MPointingPos.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MPointingPos.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MPointingPos
+#define MARS_MPointingPos
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+// FIXME: Should not be here...
+#ifndef MARS_MPointing
+#include "MPointing.h"
+#endif
+
+class MTime;
+class MObservatory;
+
+class MPointingPos : public MParContainer
+{
+private:
+    Double_t fZd;  // [deg] Zenith distance (ZA)
+    Double_t fAz;  // [deg] Azimuth
+
+    Double_t fRa;  // [h]   Right ascension
+    Double_t fHa;  // [h]   Hour angle
+    Double_t fDec; // [deg] Declination
+
+public:
+    MPointingPos(const char *name=0, const char *title=0) : fZd(0), fAz(0), fRa(0), fHa(0), fDec(0)
+    {
+        fName  = name ? name   : "MPointingPos";
+        fTitle = title ? title : "Container storing the (corrected) telescope pointing position";
+    }
+
+    void SetLocalPosition(Double_t zd, Double_t az) { fZd=zd; fAz=az; }
+    void SetSkyPosition(Double_t ra, Double_t dec, Double_t ha=0) { fRa=ra; fDec=dec; fHa=ha; }
+
+    Double_t GetZd() const  { return fZd; }
+    Double_t GetAz() const  { return fAz; }
+
+    Double_t GetZdRad() const  { return fZd*TMath::DegToRad(); }
+    Double_t GetAzRad() const  { return fAz*TMath::DegToRad(); }
+
+    ZdAz GetZdAz() const { return ZdAz(fZd, fAz); }
+
+    Double_t GetRa() const  { return fRa; }
+    Double_t GetHa() const  { return fHa; }
+    Double_t GetDec() const { return fDec; }
+
+    Double_t GetRaRad() const  { return fRa*TMath::DegToRad()*15; }
+    Double_t GetDecRad() const { return fDec*TMath::DegToRad(); }
+
+    Double_t RotationAngle(const MObservatory &o) const;
+    Double_t RotationAngle(const MObservatory &o, const MTime &t) const;
+    Double_t RotationAngle(const MObservatory &o, const MTime *t) const
+    {
+        return t ? RotationAngle(o, *t) : RotationAngle(o);
+    }
+
+    ClassDef(MPointingPos, 1) //Container storing the (corrected) telescope pointing position
+};
+
+#endif
Index: /tags/Mars-V0.9/mpointing/MPointingPosCalc.cc
===================================================================
--- /tags/Mars-V0.9/mpointing/MPointingPosCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MPointingPosCalc.cc	(revision 9772)
@@ -0,0 +1,151 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPointingPosCalc
+//
+// Currently:
+//
+//  * MC files:  Copy the simulated telescope position (Telescope Theta,
+//               Telescope Phi in MMcEvt) to MPointingPosition
+//
+//  * Real Data: Copy the nominal poiting position (Nominal Zd, Nominal Az
+//               in MReportDrive) to MPointingPosition
+//
+// Future: Interpolate the pointing position for each event between two
+//         consecutive drive reports.
+//
+// Input Container:
+//   MRawRunHeader
+//   [MMcEvt, MReportDrive]
+//
+// Output Container:
+//   MPointingPosition
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPointingPosCalc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MPointingPos.h"
+#include "MRawRunHeader.h"
+#include "MReportDrive.h"
+#include "MMcEvt.hxx"
+
+ClassImp(MPointingPosCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Search for MRawRunHeader. Get the run type from there. Depending on
+// the run type search either for MMcEvt or MReportDrive.
+//
+Bool_t MPointingPosCalc::ReInit(MParList *plist)
+{
+    MRawRunHeader *run = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!run)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunType = run->GetRunType();
+
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTData:
+        fReport = (MReportDrive*)plist->FindObject("MReportDrive");
+        if (!fReport)
+        {
+            *fLog << err << "MReportDrive not found... aborting." << endl;
+            return kFALSE;
+        }
+        return kTRUE;
+
+    case MRawRunHeader::kRTMonteCarlo:
+        fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+        if (!fMcEvt)
+        {
+            *fLog << err << "MMcEvt not found... aborting." << endl;
+            return kFALSE;
+        }
+        return kTRUE;
+
+    case MRawRunHeader::kRTPedestal:
+        *fLog << err << "Cannot work in a pedestal Run!... aborting." << endl;
+        return kFALSE;
+
+    case MRawRunHeader::kRTCalibration:
+        *fLog << err << "Cannot work in a calibration Run!... aborting." << endl;
+        return kFALSE;
+
+    default:
+        *fLog << err << "Run Type " << fRunType << " unknown!... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Search for 'MPointingPos'. Create if not found.
+//
+Int_t MPointingPosCalc::PreProcess(MParList *plist)
+{
+    fPosition = (MPointingPos*)plist->FindCreateObj("MPointingPos");
+    return fPosition ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  See class description.
+//
+Int_t MPointingPosCalc::Process()
+{
+    if (!fReport && fRunType == MRawRunHeader::kRTData)
+    {
+        *fLog << warn << "WARNING - MPointingPosCalc::Process was called BEFORE the first" << endl;
+        *fLog <<         "          data event was read (means ReInit was executed!" << endl;
+        return kTRUE;
+    }
+
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTData:
+        fPosition->SetLocalPosition(fReport->GetNominalZd(), fReport->GetNominalAz());
+        fPosition->SetSkyPosition(fReport->GetRa(), fReport->GetDec());
+        return kTRUE;
+
+    case MRawRunHeader::kRTMonteCarlo:
+        fPosition->SetLocalPosition(fMcEvt->GetTelescopeTheta()*TMath::RadToDeg(), fMcEvt->GetTelescopePhi()*TMath::RadToDeg());
+        return kTRUE;
+    }
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mpointing/MPointingPosCalc.h
===================================================================
--- /tags/Mars-V0.9/mpointing/MPointingPosCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MPointingPosCalc.h	(revision 9772)
@@ -0,0 +1,35 @@
+#ifndef MARS_MPointingPositionCalc
+#define MARS_MPointingPositionCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcEvt;
+class MReportDrive;
+class MPointingPos;
+
+class MPointingPosCalc : public MTask
+{
+private:
+    MMcEvt       *fMcEvt;    //! MMcEvt to get simulated poiting position from
+    MReportDrive *fReport;   //! MReportDrive to get real poiting position from
+    MPointingPos *fPosition; //! Output container to store pointing position
+
+    UShort_t fRunType;            //! Run Type to decide where to get pointing position from
+
+    Bool_t ReInit(MParList *plist);
+    Int_t  PreProcess(MParList *plist);
+    Int_t  Process();
+
+public:
+    MPointingPosCalc() : fMcEvt(0), fReport(0), fPosition(0)
+    {
+        fName  = "MPointingPosCalc";
+        fTitle = "Task calculating the pointing position";
+    }
+
+    ClassDef(MPointingPosCalc, 0) //Task calculating the pointing position
+};
+
+#endif
Index: /tags/Mars-V0.9/mpointing/MPointingPosInterpolate.cc
===================================================================
--- /tags/Mars-V0.9/mpointing/MPointingPosInterpolate.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MPointingPosInterpolate.cc	(revision 9772)
@@ -0,0 +1,412 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez 03/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MExtrapolatePointingPos
+//
+//   In the PreProcess, read the drive report and store it in an TSpline.
+//   In the Process, use the TSpline to calculate the PointingPos for the 
+//   time of the current event.
+// 
+//  Input Containers:
+//    MRawEvtData
+//    MReportDrive
+//    MTimeDrive
+//    MTime
+//
+//  Output Containers:
+//    MPointingPos
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MPointingPosInterpolate.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include <TSpline.h>
+
+#include "MTaskList.h"
+#include "MParList.h"
+#include "MEvtLoop.h"
+#include "MReadReports.h"
+#include "MReportDrive.h"
+#include "MPointingPos.h"
+#include "MTime.h"
+#include "MRawRunHeader.h"
+#include "MDirIter.h"
+
+#include <TCanvas.h>
+
+ClassImp(MPointingPosInterpolate);
+
+using namespace std;
+
+const Int_t MPointingPosInterpolate::fgNumStartEvents = 1;
+// --------------------------------------------------------------------------
+//
+//  Constructor
+//
+MPointingPosInterpolate::MPointingPosInterpolate(const char *name, const char *title)
+  : fEvtTime(NULL), fPointingPos(NULL), fRunHeader(NULL), fDirIter(NULL), 
+    fSplineZd(NULL), fSplineAz(NULL), fRa(0.), fDec(0.),
+    fTimeMode(MPointingPosInterpolate::kEventTime)
+
+{
+    fName  = name  ? name  : "MPointingPosInterpolate";
+    fTitle = title ? title : "Task to interpolate the pointing positons from drive reports";
+
+    fFilename = "";
+    fDebug = kFALSE;
+
+    SetNumStartEvents();
+}
+
+
+MPointingPosInterpolate::~MPointingPosInterpolate()
+{
+  Clear();
+}
+
+void MPointingPosInterpolate::Clear(Option_t *o)
+{
+  if(fSplineZd)
+    delete fSplineZd;
+  if(fSplineAz)
+    delete fSplineAz;
+}
+
+// ---------------------------------------------------------------------------
+//
+// Read the drive report file for the whole night, a build from it the splines
+//
+Bool_t MPointingPosInterpolate::ReadDriveReport()
+{
+
+    *fLog << inf << "Loading report file \"" << fFilename << "\" into TSpline..." << endl;
+
+    if (!fDebug)
+        gLog.SetNullOutput();
+
+    //
+    // ParList
+    //
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+
+    //
+    // TaskList
+    //
+    MReadReports read;
+    read.AddTree("Drive");
+    if (fDirIter)
+      read.AddFiles(*fDirIter);
+    else 
+      read.AddFile(fFilename);     // after the reading of the trees!!!
+
+    read.AddToBranchList("MReportDrive.*");
+    
+    tlist.AddToList(&read);
+    
+    //
+    // EventLoop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.PreProcess())
+    {
+        gLog.SetNullOutput(kFALSE);
+        return kFALSE;
+    }
+
+    TArrayD reportTime(fNumStartEvents);
+    TArrayD currentZd(fNumStartEvents);
+    TArrayD currentAz(fNumStartEvents); 
+    TArrayD nominalZd(fNumStartEvents);
+    TArrayD nominalAz(fNumStartEvents);
+    
+    Int_t n=1;
+    while (tlist.Process())
+    { 
+	MReportDrive* report = (MReportDrive*)plist.FindObject("MReportDrive");
+	MTime* reporttime = (MTime*)plist.FindObject("MTimeDrive");
+	
+	if(n==1)
+	  fFirstDriveTime = *reporttime;
+	else 
+	  fLastDriveTime = *reporttime;
+
+	//
+	// Update the number of entries
+	//
+	if (n>fNumStartEvents)
+	  {
+	    reportTime.Set(n);
+	    currentZd.Set(n);
+	    currentAz.Set(n); 
+	    nominalZd.Set(n);
+	    nominalAz.Set(n);
+	  }
+	//
+	// Sometimes there are two reports with the same time
+	//
+	if (n>1)
+	  if (reporttime->GetTime() == reportTime[n-2])
+	    { 
+	      *fLog << warn <<"["<< GetName() 
+		    << "]: Warning: this report has the same time that the previous one...skipping it " << endl;
+	      continue;
+	    }
+
+	reportTime[n-1] = reporttime->GetTime();
+	currentZd [n-1] = report->GetCurrentZd();
+	currentAz [n-1] = report->GetCurrentAz();
+	nominalZd [n-1] = report->GetNominalZd();
+	nominalAz [n-1] = report->GetNominalAz();
+	fRa             = report->GetRa();
+	fDec            = report->GetDec();
+
+	if (fDebug)
+	  {
+	    *fLog << " GetTime(): " << reporttime->GetTime() << endl;
+	    *fLog << " GetCurrentZd(): " << report->GetCurrentZd() << endl;
+	  }
+	n++;
+    }
+
+    tlist.PrintStatistics();
+
+    gLog.SetNullOutput(kFALSE);
+
+    *fLog << inf << GetDescriptor() << ": loaded " << n-1 << " ReportDrive from "
+	  << fFirstDriveTime << " to " << fLastDriveTime << endl;
+
+    if (fDebug)
+      {
+     	for (int i=0;i<reportTime.GetSize();i++)
+	  *fLog << i            << " " << reportTime[i] << " " 
+ 	      	<< currentZd[i] << " " << currentAz[i]  << " " 
+		<< nominalZd[i] << " " << nominalAz[i]  << endl;
+      }
+
+    fSplineZd = new TSpline3("zenith",
+			     reportTime.GetArray(), nominalZd.GetArray(), n-1);
+    fSplineAz = new TSpline3("azimuth",
+			     reportTime.GetArray(), nominalAz.GetArray(), n-1);
+
+    
+    if (fDebug)
+    {
+        *fLog << n-1 << " " << reportTime.GetSize() << endl;
+        *fLog << n-1 << " " << nominalZd.GetSize() << endl;
+        *fLog << fFirstDriveTime.GetTime() << " " << fSplineZd->Eval((fFirstDriveTime.GetTime()+fLastDriveTime.GetTime())/2.) << endl;
+	TCanvas* c = new TCanvas();
+      	c->Divide(2,1);
+      	c->cd(1);
+   	fSplineZd->Draw();
+   	c->cd(2);
+   	fSplineAz->Draw();
+   	c->Modified();
+   	c->Update();
+        c->SaveAs("pointing.root");
+    }
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Input:
+//  - MTime
+// 
+//  Output:
+//  - MPointingPos
+//
+Int_t MPointingPosInterpolate::PreProcess( MParList *pList )
+{
+
+    Clear();
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+    
+    fEvtTime = (MTime*)pList->FindObject("MTime");
+    if (!fEvtTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointingPos = (MPointingPos*)pList->FindCreateObj("MPointingPos");
+    if (!fPointingPos)
+      return kFALSE;
+
+    if (fFilename.IsNull() && !fDirIter)
+      {
+	*fLog << err << "File name is empty or no MDirIter has been handed over... aborting" << endl;
+	return kFALSE;
+      }
+
+    if( !ReadDriveReport() )
+	return kFALSE;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Get the run start time, and get the pointing position for that time
+//
+Int_t MPointingPosInterpolate::Process()
+{
+
+    //const Int_t run = fRunHeader->GetRunNumber();
+  const MTime &StartRunTime = fRunHeader->GetRunStart();
+  const MTime &EndRunTime   = fRunHeader->GetRunEnd();
+  Int_t time = StartRunTime.GetTime();
+
+   switch(fTimeMode)
+    {
+     case kRunTime:
+         //
+         // Check that we have drive report for this time
+         //
+
+         time = (EndRunTime.GetTime() + StartRunTime.GetTime())/2;
+
+         if( StartRunTime<fFirstDriveTime || StartRunTime>fLastDriveTime)
+         {
+             *fLog << err << GetDescriptor() << ": Run time " << StartRunTime
+                   << " outside range of drive reports  (" << fFirstDriveTime
+                   << ", " << fLastDriveTime << ")" << endl;
+
+            if ( *fEvtTime<fFirstDriveTime )  time = fFirstDriveTime.GetTime();
+            if ( *fEvtTime>fLastDriveTime )   time = fLastDriveTime.GetTime();
+
+             *fLog << " PointingPos: time = " << time << " (" << *fEvtTime << ")  (zd, az) = (" 
+		   << fSplineZd->Eval( time )<< ", "  <<fSplineAz->Eval( time )<< ")" << endl;
+         }
+         break;
+
+    case kEventTime:
+      
+        time = fEvtTime->GetTime();       
+
+        //
+        // Check that we have drive report for this time
+        //
+        if( *fEvtTime<fFirstDriveTime || *fEvtTime>fLastDriveTime)
+        {
+	    if (fDebug)
+	      {
+		*fLog << err << GetDescriptor() << ": Run time = "
+		      << *fEvtTime << " outside range of drive reports  ("
+    	              << fFirstDriveTime << ", "<< fLastDriveTime << ")" << endl;
+               }		
+
+	    if ( *fEvtTime < (fFirstDriveTime) )   time = fFirstDriveTime.GetTime();
+	    else                                   time = fLastDriveTime.GetTime();
+		
+        }
+        break;
+    }
+
+   if (fDebug)
+     {
+       *fLog << " real time : " << time 
+	     << " first time: " << fFirstDriveTime.GetTime()
+	     << " last time: " << fLastDriveTime.GetTime() << endl;
+       *fLog << " PointingPos: time = " << time << " (" << *fEvtTime << ")  (zd, az) = (" 
+	     << fSplineZd->Eval( time )<< ", "  <<fSplineAz->Eval( time )<< ")" << endl;
+     }
+    //
+    // Check that we have drive report for this time
+    //
+    //if( *StartRunTime<fFirstDriveTime || *StartRunTime>fLastDriveTime)
+    if( StartRunTime>fLastDriveTime)
+    {
+	*fLog << err << GetDescriptor() << ": Run time " << StartRunTime
+	      << " outside range of drive reports  (" << fFirstDriveTime 
+	      << ", " << fLastDriveTime << ")" << endl;
+	return kERROR;
+    }
+
+    const Double_t zd = fSplineZd->Eval( time );
+    const Double_t az = fSplineAz->Eval( time );
+
+    if(TMath::Abs(zd)>90 || TMath::Abs(az)>360)
+      {
+        *fLog << warn << GetDescriptor() << ": Wrong Interpolated Pointing Position." << endl;
+	*fLog << " PointingPos: time = " << time << " (" << *fEvtTime << ")  (zd, az, ra, dec) = (" 
+	      << zd << ", "  << az << "," << fRa << "," << fDec << ")" << endl;
+      }
+
+    fPointingPos->SetLocalPosition( zd, az );
+    //fPointingPos->SetSkyPosition( fRa*TMath::DegToRad()/15, fDec*TMath::DegToRad());
+    fPointingPos->SetSkyPosition( fRa, fDec);
+
+    return kTRUE;
+}
+
+
+
+Int_t MPointingPosInterpolate::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "NumStartEvents", print))
+      {
+	SetNumStartEvents(GetEnvValue(env, prefix, "NumStartEvents", fNumStartEvents));
+	rc = kTRUE;
+      }
+
+    if (IsEnvDefined(env, prefix, "TimeMode", print))
+      {
+
+	TString dat(GetEnvValue(env, prefix, "TimeMode", ""));
+	dat.ToLower();
+
+	rc = kTRUE;
+
+	if (dat.Contains("eventtime"))
+	  SetTimeMode(kEventTime);
+	else if (dat.Contains("runtime"))
+	  SetTimeMode(kRunTime);
+	else
+	  rc = kFALSE;
+      }
+    return rc;
+}
+
Index: /tags/Mars-V0.9/mpointing/MPointingPosInterpolate.h
===================================================================
--- /tags/Mars-V0.9/mpointing/MPointingPosInterpolate.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MPointingPosInterpolate.h	(revision 9772)
@@ -0,0 +1,81 @@
+#ifndef MARS_MPointingPosInterpolate
+#define MARS_MPointingPosInterpolate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TSpline
+#include <TSpline.h>
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class MTime;
+class MPointingPos;
+class MRawRunHeader;
+class MDirIter;
+
+class MPointingPosInterpolate : public MTask
+{
+public:
+
+    enum TimeMode_t {
+        kRunTime,
+        kEventTime
+    };
+
+private:
+
+  static const Int_t fgNumStartEvents; //! Default for fNumStartEvents (now set to: 10000)
+
+  Int_t fNumStartEvents;               //  Start number of allowed events
+
+  Bool_t fDebug;
+
+  TString fFilename;
+  MTime   fFirstDriveTime;
+  MTime   fLastDriveTime;
+  
+  MTime         *fEvtTime;             //! Raw event time
+  MPointingPos  *fPointingPos;         //! Telescope pointing postion
+  MRawRunHeader *fRunHeader;           //! Run Header
+  MDirIter      *fDirIter;             //! Dir Iter
+  
+  TSpline3* fSplineZd;                 //! Zd vs. time
+  TSpline3* fSplineAz;                 //! Az vs. time
+
+  Double_t  fRa;                       // RA of source
+  Double_t  fDec;                      // Dec of source
+
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Bool_t ReadDriveReport();    
+
+  TimeMode_t fTimeMode;
+
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+    
+  MPointingPosInterpolate(const char *name=NULL, const char *title=NULL);
+
+  ~MPointingPosInterpolate();
+
+  void AddFiles(MDirIter *dir) { fDirIter = dir; }
+  void AddFile(const char *name) { fFilename = name; }
+
+  void SetTimeMode( TimeMode_t mode) { fTimeMode = mode; }
+  void SetDebug( const Bool_t b=kTRUE) { fDebug = b; }
+
+  void Clear(Option_t *o="");
+  
+  Int_t GetNumStartEvents() const { return fNumStartEvents; }
+  void  SetNumStartEvents ( const Int_t i=fgNumStartEvents ) { fNumStartEvents = i; }
+
+  ClassDef(MPointingPosInterpolate, 1)  // Interpolate the drive pointing positions
+};
+
+#endif
Index: /tags/Mars-V0.9/mpointing/MSrcPosCalc.cc
===================================================================
--- /tags/Mars-V0.9/mpointing/MSrcPosCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MSrcPosCalc.cc	(revision 9772)
@@ -0,0 +1,402 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Abelardo Moralejo 1/2005 <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosCalc
+//
+// Calculate the current source position in the camera from the (possibly already
+// corrected, by starguider) J2000 sky coordinates of the camera center (contained
+// in MPointingPos), and the source J2000 sky coordinates contained in MSourcePos
+// (of type MPointingPos as well). If no MSourcePos is found in the parameter list, 
+// source position is assumed to be the same for all events, that specified in 
+// MSrcPosCam (if it already existed in the parameter list), or (0,0), the center 
+// of the camera, if no MSrcPosCam was present in the parameter list. In both cases,
+// no calculation is necessary and then the PreProcess returns kSKIP so that the task
+// is removed from the task list.
+//
+// The conversion factor between the camera plain (mm) and the
+// sky (deg) is taken from MGeomCam. The time is taken from MTime, and the coordinates
+// of the observatory from MObservatory.
+//
+// Input Container:
+//   MPointingPos
+//   MObservatory
+//   MGeomCam
+//   MTime
+//   [MSourcePos] (of type MPointingPos)
+//
+// Output Container:
+//   MSrcPosCam
+//
+// To be done:
+//   - wobble mode missing   /// NOTE, A. Moralejo: I see no need for special code
+//
+//   - a switch between using sky-coordinates and time or local-coordinates
+//     from MPointingPos for determine the rotation angle
+/////  NOTE, A. Moralejo: the above is not possible if MAstroSky2Local does not 
+/////  account for precession and nutation.
+//
+//   - the center of rotation need not to be the camera center
+/////  NOTE, A. Moralejo: I don't see the need for special code either.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSrcPosCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MSrcPosCam.h"
+
+#include "MAstro.h"
+#include "MVector3.h"
+#include "MAstroSky2Local.h"
+
+ClassImp(MSrcPosCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize fY and fY with 0
+//
+MSrcPosCalc::MSrcPosCalc(const char *name, const char *title)
+    : fObservatory(NULL), fPointPos(NULL), fSourcePos(NULL), fSrcPosCam(NULL),
+    fSrcPosAnti(NULL), fGeom(NULL), fTime(NULL), fIsWobbleMode(kFALSE)
+{
+    fName  = name  ? name  : "MSrcPosCalc";
+    fTitle = title ? title : "Calculates the source position in the camera";
+}
+
+// --------------------------------------------------------------------------
+//
+//  delete fSourcePos if kIsOwner
+//  set fSourcePos to NULL
+//
+void MSrcPosCalc::FreeSourcePos()
+{
+    if (fSourcePos && TestBit(kIsOwner))
+        delete fSourcePos;
+
+    fSourcePos = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  ra  [h]
+//  dec [deg]
+//
+void MSrcPosCalc::SetSourcePos(Double_t ra, Double_t dec)
+{
+    FreeSourcePos();
+
+    fSourcePos = new MPointingPos("MSourcePos");
+    fSourcePos->SetSkyPosition(ra, dec);
+
+    SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return ra/dec as string
+//
+TString MSrcPosCalc::GetRaDec(const MPointingPos &pos) const
+{
+    const TString rstr = MAstro::Angle2Coordinate(pos.GetRa());
+    const TString dstr = MAstro::Angle2Coordinate(pos.GetDec());
+
+    return Form("Ra=%sh Dec=%sdeg", rstr.Data(), dstr.Data());
+}
+
+// --------------------------------------------------------------------------
+//
+// Search and if necessary create MSrcPosCam in the parameter list. Search MSourcePos.
+// If not found, do nothing else, and skip the task. If MSrcPosCam did not exist
+// before and has been created here, it will contain as source position the camera
+// center (0,0).
+// In the case that MSourcePos is found, go ahead in searching the rest of necessary 
+// containers. The source position will be calculated for each event in Process.
+//
+Int_t MSrcPosCalc::PreProcess(MParList *pList)
+{
+    fSrcPosCam = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam");
+    if (!fSrcPosCam)
+        return kFALSE;
+
+    fSrcPosAnti = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam", "MSrcPosAnti");
+    if (!fSrcPosAnti)
+        return kFALSE;
+
+    if (!fSourcePos)
+    {
+        fSourcePos = (MPointingPos*)pList->FindObject("MSourcePos", "MPointingPos");
+        if (!fSourcePos)
+        {
+            *fLog << warn << "MSourcePos [MPointPos] not found... The source position" << endl;
+            *fLog << warn << "set in MSrcPosCam (camera center if not set explicitely) will" << endl;
+            *fLog << warn << "be left unchanged, same for all events." << endl;
+            return kSKIP;
+        }
+    }
+    // FIXME: Maybe we have to call FreeSourcePos in PostProcess()?
+
+    fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointPos = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fObservatory = (MObservatory*)pList->FindObject("MObservatory");
+    if (!fObservatory)
+    {
+        *fLog << err << "MObservatory not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTime = (MTime*)pList->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    *fLog << "Pointing Position: " << GetRaDec(*fPointPos)  << endl;
+    *fLog << "Source   Position: " << GetRaDec(*fSourcePos) << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Loc0LocToCam
+//
+// Input :   (theta0, phi0)   direction for the position (0,0) in the camera  
+//           ( theta,  phi)   some other direction
+// 
+// Output :  (X, Y)      position in the camera corresponding to (theta, phi)
+//
+TVector2 MSrcPosCalc::CalcXYinCamera(const MVector3 &pos0, const MVector3 &pos) const
+{
+    const Double_t theta0 = pos0.Theta();
+    const Double_t phi0   = pos0.Phi();
+
+    const Double_t theta  = pos.Theta();
+    const Double_t phi    = pos.Phi();
+
+    //--------------------------------------------
+
+    // pos0[3] = TMath::Cos(theta0)
+
+    const Double_t YC0 = TMath::Cos(theta0)*TMath::Tan(theta)*TMath::Cos(phi-phi0) - TMath::Sin(theta0);
+    const Double_t YC1 = TMath::Cos(theta0) + TMath::Sin(theta0)*TMath::Tan(theta);
+    const Double_t YC  = YC0 / YC1;
+
+    //--------------------------------------------
+
+    const Double_t XC0 =  TMath::Cos(theta0) - YC*TMath::Sin(theta0);
+    const Double_t XC  = -TMath::Sin(phi-phi0) * TMath::Tan(theta) * XC0;
+
+    //--------------------------------------------
+    return TVector2(XC, YC);
+}
+
+// --------------------------------------------------------------------------
+//
+// Derotate fX/fY by the current rotation angle, set MSrcPosCam
+//
+Int_t MSrcPosCalc::Process()
+{
+  //     *fLog << dbg << "Camera center : Zd=" << fPointPos->GetZd() << " Az=" << fPointPos->GetAz() << endl;
+  //     *fLog << dbg << "Camera center : RA=" << fPointPos->GetRa() << " Dec=" << fPointPos->GetDec() << endl;
+  //     *fLog << dbg << "MJD: " << fTime->GetMjd() << ", time [ms]: " << fTime->GetTime() << endl;
+
+  MVector3 pos, pos0;  // pos: source position;  pos0: camera center
+
+  if (fSourcePos)
+    {
+      // Set Sky coordinates of source, taken from container "MSourcePos" of type MPointingPos. The sky 
+      // coordinates must be J2000, as the sky coordinates of the camera center that we get from the container 
+      // "MPointingPos" filled by the Drive.
+
+      pos.SetRaDec(fSourcePos->GetRaRad(), fSourcePos->GetDecRad());
+
+      // 	*fLog << dbg << "Sky position of source: Ra=" << fSourcePos->GetRa() << 
+      // 	  " Dec=" << fSourcePos->GetDec() << endl;
+    }
+
+  // Convert sky coordinates of source to local coordinates. Warning! These are not the "true" local 
+  // coordinates, since this transformation ignores precession and nutation effects.
+  const MAstroSky2Local conv(*fTime, *fObservatory);
+  pos *= conv;
+
+
+  // Set sky coordinates of camera center in pos0, and then convert to local. Same comment as above. These 
+  // coordinates differ from the true local coordinates of the camera center that one could get from 
+  // "MPointingPos", calculated by the Drive: the reason is that the Drive takes into account precession 
+  // and nutation corrections, while MAstroSky2Local (as of Jan 27 2005 at least) does not. Since we just 
+  // want to get the source position on the camera from the local coordinates of the center and the source,
+  // it does not matter that the coordinates contained in pos and pos0 ignore precession and nutation... 
+  // since the shift would be the same in both cases. What would be wrong is to set in pos0 directly the 
+  // local coordinates found in MPointingPos!
+
+  pos0.SetRaDec(fPointPos->GetRaRad(), fPointPos->GetDecRad());
+  pos0 *= conv;
+
+  //     *fLog << dbg << "From MAstroSky2Local, without precession and nutation corrections:" << endl;
+  //     *fLog << dbg << "- Camera center (2) from RA,dec and time : Zd=" << pos0.Theta()*180./TMath::Pi() 
+  //  	  << " Az=" << pos0.Phi()*180./TMath::Pi() << endl;
+  //     *fLog << dbg << "- Local position of source: Zd=" << pos.Theta()*TMath::RadToDeg() << " Az=" << pos.Phi()*TMath::RadToDeg() << endl;
+
+
+  // Calculate source position in camera, and convert to mm:
+  TVector2 v = CalcXYinCamera(pos0, pos)*fGeom->GetCameraDist()*1000;
+  if (fIsWobbleMode)
+  {
+      fSrcPosAnti->SetXY(v);
+      v *= -1;
+      fSrcPosCam->SetXY(v);
+  }
+  else
+  {
+      fSrcPosCam->SetXY(v);
+      v *= -1;
+      fSrcPosAnti->SetXY(v);
+  }
+
+  //     v *= fGeom->GetConvMm2Deg();
+  //     *fLog << dbg << "X=" << v.X() << " deg,  Y=" << v.Y() << " deg" << endl;
+  //     *fLog << *fTime << endl;
+  //     *fLog << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Convert a coordinate stored in str into a double, stored in ret.
+// Returns kTRUE on success, otherwise kFALSE
+//
+// Allowed formats are:
+//     12.5
+//    -12.5
+//    +12.5
+//  -12:30:00.0
+//   12:30:00.0
+//  +12:30:00.0
+//
+Bool_t MSrcPosCalc::GetCoordinate(TString str, Double_t &ret) const
+{
+    str = str.Strip(TString::kBoth);
+
+    if (str.First(':')<0)
+        return atof(str);
+
+    if (MAstro::Coordinate2Angle(str, ret))
+        return kTRUE;
+
+    *fLog << err << GetDescriptor() << endl;
+    *fLog << "Interpretation of Coordinate '" << str << "' not successfull... abort." << endl;
+    *fLog << "Corrdinate must have the format: '-12:30:00.0', '12:30:00.0' or '+12:30:00.0'" << endl;
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MSrcPosCalc.SourceRa:  ra
+//   MSrcPosCalc.SourceDec: dec
+//   MSrcPosCalc.SourcePos: ra dec
+//
+// For format of 'ra' and 'dec' see GetCoordinate()
+//
+// Coordinates are J2000.0
+//
+Int_t MSrcPosCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Double_t ra=0;
+    Double_t dec=0;
+
+    if (IsEnvDefined(env, prefix, "SourceRaDec", print))
+    {
+        TString str = GetEnvValue(env, prefix, "SourceRaDec", "");
+        str = str.Strip(TString::kBoth);
+
+        const Ssiz_t pos = str.First(' ');
+        if (pos<0)
+        {
+            *fLog << err << GetDescriptor() << "SourceRaDec empty... abort." << endl;
+            return kERROR;
+        }
+
+        if (!GetCoordinate(str(0, pos), ra))
+            return kERROR;
+        if (!GetCoordinate(str(pos+1, str.Length()), dec))
+            return kERROR;
+
+        SetSourcePos(ra, dec);
+        return kTRUE;
+    }
+
+    Bool_t rc = kFALSE;
+    if (IsEnvDefined(env, prefix, "SourceRa", print))
+    {
+        TString str = GetEnvValue(env, prefix, "SourceRa", "");
+
+        if (!GetCoordinate(str, ra))
+            return kERROR;
+
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "SourceDec", print))
+    {
+        TString str = GetEnvValue(env, prefix, "SourceDec", "");
+
+        if (!GetCoordinate(str, dec))
+            return kERROR;
+
+        rc = kTRUE;
+    }
+
+    if (!rc)
+        return kFALSE;
+
+    SetSourcePos(ra, dec);
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mpointing/MSrcPosCalc.h
===================================================================
--- /tags/Mars-V0.9/mpointing/MSrcPosCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MSrcPosCalc.h	(revision 9772)
@@ -0,0 +1,62 @@
+#ifndef MARS_MSrcPosCalc
+#define MARS_MSrcPosCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TVector2
+#include <TVector2.h>
+#endif
+
+class MObservatory;
+class MPointingPos;
+class MSrcPosCam;
+class MGeomCam;
+class MTime;
+class MVector3;
+
+class MSrcPosCalc : public MTask
+{
+private:
+    enum {
+        kIsOwner = BIT(14)
+    };
+
+    MObservatory *fObservatory;
+    MPointingPos *fPointPos;
+    MPointingPos *fSourcePos;
+    MSrcPosCam   *fSrcPosCam;
+    MSrcPosCam   *fSrcPosAnti;
+    MGeomCam     *fGeom;
+    MTime        *fTime;
+
+    Bool_t fIsWobbleMode;
+
+    // MSrcPosCalc
+    TVector2 CalcXYinCamera(const MVector3 &pos0, const MVector3 &pos) const;
+    TString  GetRaDec(const MPointingPos &pos) const;
+    Bool_t   GetCoordinate(TString str, Double_t &ret) const;
+    void     FreeSourcePos();
+
+    // MParContainer
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    // MTask
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MSrcPosCalc(const char *name=NULL, const char *title=NULL);
+    ~MSrcPosCalc() { FreeSourcePos(); }
+
+    // MSrcPosCalc
+    void SetSourcePos(MPointingPos *pos) { FreeSourcePos(); fSourcePos = pos; }
+    void SetSourcePos(Double_t ra, Double_t dec);
+    void SetOwner(Bool_t b=kTRUE) { b ? SetBit(kIsOwner) : ResetBit(kIsOwner); } // Make MSrcPosCalc owner of fSourcePos
+    void SetWobbleMode(Bool_t b=kTRUE) { fIsWobbleMode = b; }
+
+    ClassDef(MSrcPosCalc, 0) // Calculates the source position in the camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mpointing/MSrcPosCam.cc
===================================================================
--- /tags/Mars-V0.9/mpointing/MSrcPosCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MSrcPosCam.cc	(revision 9772)
@@ -0,0 +1,120 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz    12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Rudolf Bock     10/2001 <mailto:Rudolf.Bock@cern.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosCam
+//
+// Storage Container to hold the current position of the source (or
+// anti/false source) in the camera plain
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSrcPosCam.h"
+
+#include <fstream>
+
+#include <TVector2.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSrcPosCam);
+
+using namespace std;
+
+static const TString gsDefName  = "MSrcPosCam";
+static const TString gsDefTitle = "Virtual source position in the camera";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MSrcPosCam::MSrcPosCam(const char *name, const char *title) : fX(0), fY(0)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// -----------------------------------------------------------------------
+//
+void MSrcPosCam::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Source position in the camera plain (" << GetName() << ")" << endl;
+    *fLog << " - x [mm] = " << fX << endl;
+    *fLog << " - y [mm] = " << fY << endl;
+}
+
+void MSrcPosCam::SetXY(const TVector2 &v)
+{
+    fX = v.X();
+    fY = v.Y();
+}
+
+TVector2 MSrcPosCam::GetXY() const
+{
+    return TVector2(fX, fY);
+}
+
+/*
+// -----------------------------------------------------------------------
+//
+// overloaded MParContainer to read MSrcPosCam from an ascii file
+//
+void MSrcPosCam::AsciiRead(ifstream &fin)
+{
+    fin >> fX;
+    fin >> fY;
+}
+
+// -----------------------------------------------------------------------
+//
+// overloaded MParContainer to write MSrcPosCam to an ascii file
+//
+void MSrcPosCam::AsciiWrite(ofstream &fout) const
+{
+    fout << fX << " " << fY;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MSrcPosCam::StreamPrimitive(ofstream &out) const
+{
+    out << "   MSrcPosCam " << GetUniqueName();
+    if (fName!=gsDefName)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl;
+
+    out << "   " << GetUniqueName() << ".SetXY(" << fX << ", " << fY << ");" << endl;}
Index: /tags/Mars-V0.9/mpointing/MSrcPosCam.h
===================================================================
--- /tags/Mars-V0.9/mpointing/MSrcPosCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MSrcPosCam.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MSrcPosCam
+#define MARS_MSrcPosCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TVector2;
+
+class MSrcPosCam : public MParContainer
+{
+private:
+    Float_t fX; // [mm] x position of source in camera
+    Float_t fY; // [mm] y position of source in camera
+
+public:
+    MSrcPosCam(const char *name=NULL, const char *title=NULL);
+
+    void Clear(Option_t *)           { fX = 0; fY = 0; }
+
+    void SetX(Float_t x)             { fX = x; }
+    void SetY(Float_t y)             { fY = y; }
+    void SetXY(Float_t x, Float_t y) { fX = x; fY = y; }
+    void SetXY(const TVector2 &v);
+
+    Float_t GetX() const             { return fX; }
+    Float_t GetY() const             { return fY; }
+    TVector2 GetXY() const;
+
+    void Print(Option_t *opt=NULL) const;
+    void StreamPrimitive(ofstream &out) const;
+
+    //void AsciiRead(ifstream &fin);
+    //void AsciiWrite(ofstream &fout) const;
+
+    ClassDef(MSrcPosCam, 1) // container to store source position in the camera plain
+};
+
+#endif
Index: /tags/Mars-V0.9/mpointing/MSrcPosFromModel.cc
===================================================================
--- /tags/Mars-V0.9/mpointing/MSrcPosFromModel.cc	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MSrcPosFromModel.cc	(revision 9772)
@@ -0,0 +1,152 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosFromModel
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSrcPosFromModel.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MPointing.h"
+#include "MSrcPosCam.h"
+#include "MAstro.h"
+#include "MAstroCatalog.h" // MVector3
+#include "MAstroSky2Local.h"
+#include "MPointingPos.h"
+#include "MGeomCam.h"
+#include "MReportDrive.h"
+
+ClassImp(MSrcPosFromModel);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize fY and fY with 0
+//
+MSrcPosFromModel::MSrcPosFromModel(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MSrcPosFromModel";
+    fTitle = title ? title : "";
+
+    fPoint0401 = new MPointing("bending-fit.txt");
+    fPoint0405 = new MPointing("bending0405.txt");
+}
+
+MSrcPosFromModel::~MSrcPosFromModel()
+{
+    delete fPoint0401;
+    delete fPoint0405;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search and if necessary create MSrcPosCam in the parameter list
+//
+Int_t MSrcPosFromModel::PreProcess(MParList *pList)
+{
+    fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeom)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointPos = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointPos)
+    {
+        *fLog << err << "MPointPos not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRun = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRun)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fObservatory = (MObservatory*)pList->FindObject("MObservatory");
+    if (!fObservatory)
+    {
+        *fLog << err << "MObservatory not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTime = (MTime*)pList->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSrcPos = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam");
+    if (!fSrcPos)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Derotate fX/fY by the current rotation angle, set MSrcPosCam
+//
+Int_t MSrcPosFromModel::Process()
+{
+    MPointing *conv = 0;
+
+    if (!conv && fRun->GetRunNumber()<26237)
+        conv = fPoint0401;
+    if (!conv && fRun->GetRunNumber()<31684)
+        conv = fPoint0405;
+
+    TVector2 d;
+
+    if (conv)
+    {
+        MVector3 sky;
+        sky.SetRaDec(fPointPos->GetRaRad(), fPointPos->GetDecRad());
+
+        // Get current star position (off center)
+        MVector3 vl2 = MAstroSky2Local(*fTime, *fObservatory)*sky;
+        // Get corrected position camera center)
+        TVector3 vl1 = conv->Correct(vl2);
+
+        // Calculate x,y of za2
+        d = MAstro::GetDistOnPlain(vl1, vl2, fGeom->GetCameraDist()*1000);
+    }
+
+    // Set Source position
+    fSrcPos->SetXY(d);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mpointing/MSrcPosFromModel.h
===================================================================
--- /tags/Mars-V0.9/mpointing/MSrcPosFromModel.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/MSrcPosFromModel.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MSrcPosFromModel
+#define MARS_MSrcPosFromModel
+
+//#ifndef ROOT_TVector2
+//#include <TVector2.h>
+//#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MPointingPos;
+class MSrcPosCam;
+class MGeomCam;
+class MPointing;
+class MRawRunHeader;
+class MTime;
+class MObservatory;
+
+class MSrcPosFromModel : public MTask
+{
+private:
+    MPointingPos  *fPointPos;   //! Poiting position as recorded by the drive system
+    MSrcPosCam    *fSrcPos;     //! Source position in the camera
+    MGeomCam      *fGeom;       //! Camera geometry
+    MRawRunHeader *fRun;        //! Run Header storing the run-number
+    MTime         *fTime;
+    MObservatory  *fObservatory;
+
+    MPointing    *fPoint0401;   //! Pointing Model used since 1/2004
+    MPointing    *fPoint0405;   //! Pointing Model used since 5/2004
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+/*
+    TVector2 CalcXYinCamera(const ZdAz &pos0, const ZdAz &pos) const;
+    TVector2 CalcXYinCamera(const MVector3 &pos0, const MVector3 &pos) const;
+    */
+
+public:
+    MSrcPosFromModel(const char *name=NULL, const char *title=NULL);
+    ~MSrcPosFromModel();
+
+    ClassDef(MSrcPosFromModel, 0) // Calculates the source position from a corrected pointing model
+};
+
+#endif
Index: /tags/Mars-V0.9/mpointing/Makefile
===================================================================
--- /tags/Mars-V0.9/mpointing/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/Makefile	(revision 9772)
@@ -0,0 +1,38 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT = Pointing
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mraw -I../mreport -I../mmc \
+           -I../mastro -I../mgeom -I../mfileio
+
+SRCFILES = MPointing.cc \
+	   MPointingPos.cc \
+	   MPointingPosCalc.cc \
+	   MPointingPosInterpolate.cc \
+           MSrcPosCam.cc \
+           MSrcPosCalc.cc \
+           MSrcPosFromModel.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mpointing/PointingIncl.h
===================================================================
--- /tags/Mars-V0.9/mpointing/PointingIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/PointingIncl.h	(revision 9772)
@@ -0,0 +1,5 @@
+#ifndef __CINT__
+
+#include <TVector2.h>
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mpointing/PointingLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mpointing/PointingLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mpointing/PointingLinkDef.h	(revision 9772)
@@ -0,0 +1,20 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MPointing+;
+
+#pragma link C++ class MPointingPos+;
+#pragma link C++ class MPointingPosCalc+;
+#pragma link C++ class MPointingPosInterpolate+;
+
+#pragma link C++ class MSrcPosCam+;
+#pragma link C++ class MSrcPosCalc+;
+#pragma link C++ class MSrcPosFromModel+;
+
+#pragma link C++ class AltAz+;
+#pragma link C++ class ZdAz+;
+
+#endif
Index: /tags/Mars-V0.9/mranforest/MHRanForest.cc
===================================================================
--- /tags/Mars-V0.9/mranforest/MHRanForest.cc	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MHRanForest.cc	(revision 9772)
@@ -0,0 +1,194 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHRanForest
+//
+// This histogram shows the evolution of the standard deviation 
+// of est. hadronness as the number of trees increases. 
+// It helps you to find out how many trees are really needed in g/h-sep.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHRanForest.h"
+
+#include <TPad.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MRanForest.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+
+ClassImp(MHRanForest);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms, nbins is the number of bins used for the evaluation.
+// The default is 100 bins.
+//
+MHRanForest::MHRanForest(Int_t nbins, const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHRanForest";
+    fTitle = title ? title : "Histogram showing Standard deviation of estimated hadronness";
+
+    fGraphSigma = new TGraph;
+    fGraphSigma->SetTitle("Evolution of Standard deviation of estimated hadronness in tree combination");
+    fGraphSigma->SetMarkerStyle(kFullDotSmall);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms.
+//
+MHRanForest::~MHRanForest()
+{
+    delete fGraphSigma;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup Filling of the histograms. It needs:
+//  MMcEvt and MRanForest
+//
+Bool_t MHRanForest::SetupFill(const MParList *plist)
+{
+    fMcEvt = (MMcEvt*)plist->FindObject(AddSerialNumber("MMcEvt"));
+    if (!fMcEvt)
+    {
+        *fLog << err << AddSerialNumber("MMcEvt") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanForest = (MRanForest*)plist->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        *fLog << err << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSigma.Set(fRanForest->GetNumTrees());
+    fNumEvent=0;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MHRanForest::Fill(const MParContainer *par, const Stat_t w)
+{
+    fNumEvent++;
+
+    Double_t hest=0;
+    Double_t htrue=fMcEvt->GetPartId()==MMcEvt::kGAMMA ? 0. : 1.;
+
+    Int_t ntrees=fRanForest->GetNumTrees();
+
+    for (Int_t i=0;i<ntrees;i++)
+    {
+        for(Int_t j=0;j<=i;j++)
+            hest+=fRanForest->GetTreeHad(j);
+
+        hest/=i+1;
+
+        const Double_t val = htrue-hest;
+        fSigma[i] += val*val;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Finalize the histogram:
+// calculate standard deviation and set histogram max and min
+//
+Bool_t MHRanForest::Finalize()
+{
+    Int_t n = fSigma.GetSize();
+
+    fGraphSigma->Set(n);
+
+    Stat_t max=0.;
+    Stat_t min=0.;
+    for (Int_t i=0; i<n; i++)
+    {
+	fSigma[i] = TMath::Sqrt(fSigma[i]/fNumEvent);
+
+        const Stat_t ig = fSigma[i];
+        if (ig>max) max = ig;
+        if (ig<min) min = ig;
+        fGraphSigma->SetPoint(i, i+1, ig);
+    }
+
+    // This is used in root>3.04/? so that SetMaximum/Minimum can succeed
+    fGraphSigma->GetHistogram();
+
+    fGraphSigma->SetMaximum(1.05*max);
+    fGraphSigma->SetMinimum(0.95*min);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw histogram. (For the Meaning see class description)
+//
+void MHRanForest::Draw(Option_t *)
+{
+   if (fGraphSigma->GetN()==0)
+        return;
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    fGraphSigma->Draw("ALP");
+    pad->Modified();
+    pad->Update();
+
+    TH1 *h=fGraphSigma->GetHistogram();
+    if (!h)
+        return;
+
+    //h->GetXaxis()->SetRangeUser(0, fNumEvent+1);
+    h->SetXTitle("No.of Trees");
+    h->SetYTitle("\\sigma of est.hadronness");
+
+    pad->Modified();
+    pad->Update();
+}
Index: /tags/Mars-V0.9/mranforest/MHRanForest.h
===================================================================
--- /tags/Mars-V0.9/mranforest/MHRanForest.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MHRanForest.h	(revision 9772)
@@ -0,0 +1,43 @@
+#ifndef MARS_MHRanForest
+#define MARS_MHRanForest
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class TH1D;
+class TGraph;
+class MParList;
+class MMcEvt;
+class MRanForest;
+
+class MHRanForest : public MH
+{
+private:
+    const MMcEvt *fMcEvt;           //!
+    const MRanForest *fRanForest;   //!
+
+    TArrayF fSigma;                 //!
+    Int_t fNumEvent;                //!
+    TGraph *fGraphSigma;            //->
+
+public:
+    MHRanForest(Int_t nbins=100, const char *name=NULL, const char *title=NULL);
+    ~MHRanForest();
+
+    TGraph *GetGraphSigma() const  { return fGraphSigma; }
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHRanForest, 1) // Histogram showing variance of estimated Hadronness
+};
+
+#endif
Index: /tags/Mars-V0.9/mranforest/MHRanForestGini.cc
===================================================================
--- /tags/Mars-V0.9/mranforest/MHRanForestGini.cc	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MHRanForestGini.cc	(revision 9772)
@@ -0,0 +1,174 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHRanForest
+//
+// This histogram shows a measure of variable importance (mean decrease in
+// Gini-index)
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHRanForestGini.h"
+
+#include <TPad.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include "MParList.h"
+#include "MBinning.h"
+#include "MRanTree.h"
+#include "MRanForest.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHRanForestGini);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms, nbins is the number of bins used for the evaluation.
+// The default is 100 bins.
+//
+MHRanForestGini::MHRanForestGini(Int_t nbins, const char *name, const char *title)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHRanForestGini";
+    fTitle = title ? title : "Measure of importance of Random Forest-input parameters";
+
+    fGraphGini = new TGraph;
+    fGraphGini->SetTitle("Importance of RF-input parameters measured by mean Gini decrease");
+    fGraphGini->SetMarkerStyle(kFullDotSmall);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms.
+//
+MHRanForestGini::~MHRanForestGini()
+{
+    delete fGraphGini;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup Filling of the histograms. It needs:
+//  MMcEvt and MRanForest
+//
+Bool_t MHRanForestGini::SetupFill(const MParList *plist)
+{
+    fRanForest = (MRanForest*)plist->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        *fLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGini.Set(fRanForest->GetNumDim());
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the RanForest from a MRanForest container into the corresponding
+// histogram dependant on the particle id.
+//
+//
+Bool_t MHRanForestGini::Fill(const MParContainer *par, const Stat_t w)
+{
+    for (Int_t i=0;i<fRanForest->GetNumDim();i++)
+        fGini[i]+=fRanForest->GetCurTree()->GetGiniDec(i);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MHRanForestGini::Finalize()
+{
+    const Int_t n = fGini.GetSize();
+
+    fGraphGini->Set(n);
+
+    Stat_t max=0;
+    Stat_t min=0;
+    for (Int_t i=0; i<n; i++)
+    {
+        fGini[i] /= fRanForest->GetNumTrees();
+        fGini[i] /= fRanForest->GetNumData();
+
+        const Stat_t ip = i+1;
+        const Stat_t ig = fGini[i];
+
+        if (ig>max) max=ig;
+        if (ig<min) min=ig;
+
+        fGraphGini->SetPoint(i,ip,ig);
+    }
+
+    // This is used in root>3.04/? so that SetMaximum/Minimum can succeed
+    fGraphGini->GetHistogram();
+
+    fGraphGini->SetMaximum(1.05*max);
+    fGraphGini->SetMinimum(0.95*min);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw histogram. (For the Meaning see class description)
+//
+void MHRanForestGini::Draw(Option_t *)
+{
+    if (fGraphGini->GetN()==0)
+        return;
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    fGraphGini->Draw("ALP");
+    pad->Modified();
+    pad->Update();
+
+    TH1 *h = fGraphGini->GetHistogram();
+    if (!h)
+        return;
+
+    //h->GetXaxis()->SetRangeUser(0, fGini.GetSize()+1);
+    h->SetXTitle("No.of RF-input parameter");
+    h->SetYTitle("Mean decrease in Gini-index [a.u.]");
+
+    pad->Modified();
+    pad->Update();
+}
Index: /tags/Mars-V0.9/mranforest/MHRanForestGini.h
===================================================================
--- /tags/Mars-V0.9/mranforest/MHRanForestGini.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MHRanForestGini.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MHRanForestGini
+#define MARS_MHRanForestGini
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class TH1D;
+class TGraph;
+class MParList;
+class MRanForest;
+class MRanTree;
+
+class MHRanForestGini : public MH
+{
+private:
+    MRanForest *fRanForest;  //!
+
+    TArrayF fGini;           //!
+    TGraph *fGraphGini;      //->
+
+public:
+    MHRanForestGini(Int_t nbins=100, const char *name=NULL, const char *title=NULL);
+    ~MHRanForestGini();
+
+    TGraph *GetGraphGini() const  { return fGraphGini; }
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHRanForestGini, 1)
+};
+
+#endif
Index: /tags/Mars-V0.9/mranforest/MRFEnergyEst.cc
===================================================================
--- /tags/Mars-V0.9/mranforest/MRFEnergyEst.cc	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRFEnergyEst.cc	(revision 9772)
@@ -0,0 +1,455 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 2/2005 <mailto:hengsteb@physik.hu-berlin.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRFEnergyEst
+//
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MRFEnergyEst.h"
+
+#include <TFile.h>
+#include <TList.h>
+
+#include <TH1F.h>
+#include <TH2F.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MRanTree.h"
+#include "MRanForest.h"
+#include "MRanForestGrow.h"
+
+#include "MData.h"
+
+#include "TFile.h"
+#include "TList.h"
+
+#include "TH1F.h"
+#include "TH2F.h"
+#include "TStyle.h"
+#include "TCanvas.h"
+#include "TMath.h"
+#include "TVector.h"
+
+#include "MEnergyEst.h"
+
+
+ClassImp(MRFEnergyEst);
+
+using namespace std;
+
+static const TString gsDefName  = "MRFEnergyEst";
+static const TString gsDefTitle = "RF for energy estimation";
+
+// --------------------------------------------------------------------------
+//
+//
+MRFEnergyEst::MRFEnergyEst(const char *name, const char *title):fNumTrees(-1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the data chains
+//
+MRFEnergyEst::~MRFEnergyEst()
+{
+    //    delete fData;
+}
+
+// --------------------------------------------------------------------------
+Int_t MRFEnergyEst::Train()
+{
+    if(!fMatrixTrain)
+    {
+        *fLog << err << dbginf << "fMatrixTrain not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if(!fMatrixTrain->GetColumns())
+    {
+        *fLog << err << dbginf << "fMatrixTrain does not contain rules... aborting." << endl;
+        return kFALSE;
+    }
+
+    const Int_t ncols = (fMatrixTrain->GetM()).GetNcols();
+    const Int_t nrows = (fMatrixTrain->GetM()).GetNrows();
+
+    cout<<"ncols="<<ncols<<" nrows="<<nrows<<endl<<flush;
+
+    if(ncols<=0 || nrows <=0)
+    {
+        *fLog << err << dbginf << "No. of columns or no. of rows of fMatrixTrain equal 0 ... aborting." << endl;
+        return kFALSE;
+    }
+
+    // rules (= combination of image par) to be used for energy estimation
+    MDataArray used_rules;
+    TString energy_rule;
+    for(Int_t i=0;i<ncols;i++)
+    {
+        MDataArray *rules=fMatrixTrain->GetColumns();
+        MData &data=(*rules)[i];
+
+        if(i<ncols-1)
+            used_rules.AddEntry(data.GetRule());
+        else
+            energy_rule=data.GetRule();
+    }
+
+    if(!energy_rule.Contains("fEnergy"))
+    {
+        *fLog << err << dbginf << "Can not accept "<<energy_rule<<" as true energy ... aborting." << endl;
+        return kFALSE;
+    }
+
+    TFile fileRF(fRFfileName,"recreate");
+    if(!fileRF.IsOpen())
+    {
+        *fLog << err << dbginf << "File to store RFs could not be opened... aborting." << endl;
+        return kFALSE;
+    }
+
+    TMatrix *mptr=(TMatrix*)&(fMatrixTrain->GetM());
+    const Int_t nbins = fEnergyGrid.GetSize()-1;
+    if(nbins<=0)
+    {
+        *fLog << err << dbginf << "Energy grid not vaild... aborting." << endl;
+        return kFALSE;
+    }
+
+    // training of RF for each energy bin
+    Int_t numbins=0;
+    for(Int_t ie=0;ie<nbins;ie++)
+    {
+        TMatrix mat1(nrows,ncols);
+        TMatrix mat0(nrows,ncols);
+
+        // prepare matrix for current energy bin
+        Int_t irow1=0;
+        Int_t irow0=0;
+
+        for(Int_t j=0;j<nrows;j++)
+        {
+            Double_t energy=(*mptr)(j,ncols-1);
+            if(energy>pow(10.,fEnergyGrid[ie]) && energy<=pow(10.,fEnergyGrid[ie+1]))
+            {
+                TMatrixRow(mat1, irow1) = TMatrixRow(*mptr,j);
+                irow1++;
+            }else{
+                TMatrixRow(mat0, irow0) = TMatrixRow(*mptr,j);
+                irow0++;
+            }
+        }
+        if(irow1*irow0==0)continue;
+
+        *fLog << inf << dbginf << "Training RF for energy bin "<<ie<< endl;
+
+        // last column must be removed (true energy col.)
+        mat1.ResizeTo(irow1,ncols-1);
+        mat0.ResizeTo(irow0,ncols-1);
+
+        // create MHMatrix as input for RF
+        MHMatrix matrix1(mat1,"MatrixHadrons");
+        MHMatrix matrix0(mat0,"MatrixGammas");
+
+        MDataArray *rules1=matrix1.GetColumns();
+        MDataArray *rules0=matrix0.GetColumns();
+        // rules of new matrices be re-set
+        if(rules1)delete rules1; rules1=new MDataArray();
+        if(rules0)delete rules0; rules0=new MDataArray();
+
+        for(Int_t i=0;i<ncols-1;i++)
+        {
+            //MDataArray *rules=fMatrixTrain->GetColumns();
+            //MData &data=(*rules)[i];
+            MData &data=used_rules[i];
+            rules1->AddEntry(data.GetRule());
+            rules0->AddEntry(data.GetRule());
+        }
+
+        // training of RF
+        MParList plist;
+        MTaskList tlist;
+        plist.AddToList(&tlist);
+        plist.AddToList(&matrix0);
+        plist.AddToList(&matrix1);
+
+        MRanForestGrow rfgrow;
+        rfgrow.SetNumTrees(fNumTrees); // number of trees
+        rfgrow.SetNumTry(fNumTry);     // number of trials in random split selection
+        rfgrow.SetNdSize(fNdSize);     // limit for nodesize
+
+        tlist.AddToList(&rfgrow);
+    
+        MEvtLoop evtloop;
+        evtloop.SetParList(&plist);
+
+        //gLog.SetNullOutput(kTRUE);
+
+        if (!evtloop.Eventloop()) return kFALSE;
+
+        //gLog.SetNullOutput(kFALSE);
+
+        // save whole forest
+        MRanForest *forest=(MRanForest*)plist.FindObject("MRanForest");
+        forest->SetTitle(Form("%f",0.5*(fEnergyGrid[ie]+fEnergyGrid[ie+1])));
+        forest->Write(Form("%d",numbins));
+        numbins++;
+    }
+
+    // save rules
+    used_rules.Write("rules");
+
+    fileRF.Close();
+
+    return kTRUE;
+}
+
+Int_t MRFEnergyEst::Test()
+{
+    if(!fMatrixTest)
+    {
+        *fLog << err << dbginf << "fMatrixTest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const Int_t ncols = (fMatrixTest->GetM()).GetNcols();
+    const Int_t nrows = (fMatrixTest->GetM()).GetNrows();
+
+    if(ncols<=0 || nrows <=0)
+    {
+        *fLog << err << dbginf << "No. of columns or no. of rows of fMatrixTrain equal 0 ... aborting." << endl;
+        return kFALSE;
+    }
+
+    TMatrix *mptr=(TMatrix*)&(fMatrixTest->GetM());
+
+    if(!ReadForests())
+    {
+        *fLog << err << dbginf << "Reading RFs failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    const Int_t nbins=fEForests.GetSize();
+
+    Double_t e_low = 100;
+    Double_t e_up  = 0;
+
+    for(Int_t j=0;j<nbins;j++)
+    {
+        e_low = TMath::Min(atof((fEForests[j])->GetTitle()),e_low);
+        e_up  = TMath::Max(atof((fEForests[j])->GetTitle()),e_up);
+    }
+
+    TH1F hres("hres","",1000,-10,10);
+    TH2F henergy("henergy","",100,e_low,e_up,100,e_low,e_up);
+
+    for(Int_t i=0;i<nrows;i++)
+    {
+        Double_t e_true = (*mptr)(i,ncols-1);
+        Double_t e_est = 0;
+        Double_t hmax  = 0;
+        Double_t hsum  = 0;
+
+        for(Int_t j=0;j<nbins;j++)
+        {
+            const TVector v=TMatrixRow(*mptr,i);
+            Double_t h = ((MRanForest*) (fEForests[j]))->CalcHadroness(v);
+            Double_t e = atof((fEForests[j])->GetTitle());
+            /*if(h>=hmax)
+            {
+                hmax=h;
+                e_est=pow(10.,e);
+            }*/
+            hsum+=h;
+            e_est+=h*e;
+        }
+        e_est/=hsum;
+        e_est=pow(10.,e_est);
+
+        if(e_true>80.) hres.Fill((e_est-e_true)/e_true);
+        henergy.Fill(log10(e_true),log10(e_est));
+    }
+
+    if(TestBit(kEnableGraphicalOutput))
+    {
+        if(gStyle) gStyle->SetOptFit(1);
+        // show results
+        TCanvas *c=MH::MakeDefCanvas("c","",300,900);
+
+        c->Divide(1,3);
+        c->cd(1);
+        henergy.SetTitle("Estimated vs true energy");
+        henergy.GetXaxis()->SetTitle("log10(E_{true}[GeV])");
+        henergy.GetYaxis()->SetTitle("log10(E_{est}[GeV])");
+        henergy.DrawCopy();
+
+        c->cd(2);
+
+        TH1F *hptr=(TH1F*)henergy.ProfileX("_px",1,100,"S");
+        hptr->SetTitle("Estimated vs true energy - profile");
+        hptr->GetXaxis()->SetTitle("log10(E_{true}[GeV])");
+        hptr->GetYaxis()->SetTitle("log10(E_{est}[GeV])");
+        hptr->DrawCopy();
+
+        c->cd(3);
+        hres.Fit("gaus");
+        hres.SetTitle("Energy resolution for E_{true}>80Gev");
+        hres.GetXaxis()->SetTitle("(E_{estimated}-E_{true})/E_{true})");
+        hres.GetYaxis()->SetTitle("counts");
+        hres.DrawCopy();
+
+
+        c->GetPad(1)->SetGrid();
+        c->GetPad(2)->SetGrid();
+        c->GetPad(3)->SetGrid();
+
+    }
+
+    return kTRUE;
+}
+
+Int_t MRFEnergyEst::ReadForests(MParList *plist)
+{
+    TFile fileRF(fRFfileName,"read");
+    if(!fileRF.IsOpen())
+    {
+        *fLog << err << dbginf << "File containing RFs could not be opened... aborting." << endl;
+        return kFALSE;
+    }
+
+    TList *list=(TList*)fileRF.GetListOfKeys();
+    const Int_t n=list->GetSize()-1;// subtract 1 since 1 key belongs to MDataArray
+
+    fEForests.Expand(n);
+
+    MRanForest forest;
+    for(Int_t i=0;i<n;i++)
+    {
+        forest.Read(Form("%d",i));
+        MRanForest *curforest=(MRanForest*)forest.Clone();
+        const char *energy=list->FindObject(Form("%d",i))->GetTitle();
+        const char *bin   =list->FindObject(Form("%d",i))->GetName();
+
+        curforest->SetTitle(energy);
+        curforest->SetName(bin);
+
+        fEForests[i]=curforest;
+    }
+
+    if(plist)
+    {
+        fData=(MDataArray*)plist->FindCreateObj("MDataArray");
+        fData->Read("rules");
+    }
+    fileRF.Close();
+
+    return kTRUE;
+}
+
+Int_t MRFEnergyEst::PreProcess(MParList *plist)
+{
+    fEnergyEst = (MEnergyEst*)plist->FindCreateObj("MEnergyEst");
+    if (!fEnergyEst)
+    {
+        *fLog << err << dbginf << "MEnergyEst not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if(!ReadForests(plist))
+    {
+        *fLog << err << dbginf << "Reading RFs failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fData)
+    {
+        *fLog << err << dbginf << "MDataArray not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fData->PreProcess(plist))
+    {
+        *fLog << err << dbginf << "PreProcessing of the MDataArray failed for the columns failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MRFEnergyEst::Process()
+{
+    TVector event;
+    *fData >> event;
+
+    Double_t e_est = 0;
+    Double_t hmax  = 0;
+    Double_t hsum  = 0;
+        
+    for(Int_t j=0;j<fEForests.GetSize();j++)
+    {
+        Double_t h = ((MRanForest*) (fEForests[j]))->CalcHadroness(event);
+        Double_t e = atof((fEForests[j])->GetTitle());
+        /*if(h>=hmax)
+        {
+            hmax=h;
+            e_est=pow(10.,e);
+        }*/
+        hsum+=h;
+        e_est+=h*e;
+    }
+    e_est/=hsum;
+    e_est=pow(10.,e_est);
+
+    fEnergyEst->SetEnergy(e_est);
+    fEnergyEst->SetReadyToSave();
+
+    return kTRUE;
+}
+
+Int_t MRFEnergyEst::PostProcess()
+{
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mranforest/MRFEnergyEst.h
===================================================================
--- /tags/Mars-V0.9/mranforest/MRFEnergyEst.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRFEnergyEst.h	(revision 9772)
@@ -0,0 +1,63 @@
+#ifndef MARS_MRFEnergyEst
+#define MARS_MRFEnergyEst
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MHMatrix;
+class MDataArray;
+class MEnergyEst;
+
+class MRFEnergyEst : public MTask
+{
+private:
+    Int_t fNumTrees;
+    Int_t fNumTry;
+    Int_t fNdSize;
+
+    TString fRFfileName;
+    MHMatrix *fMatrixTrain;
+    MHMatrix *fMatrixTest;
+    TArrayD fEnergyGrid;
+
+    MDataArray  *fData;       //! Used to store the MDataChains to get the event values
+    TObjArray fEForests;
+
+    MEnergyEst *fEnergyEst;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Int_t ReadForests(MParList *plist=NULL);
+
+public:
+    MRFEnergyEst(const char *name=NULL, const char *title=NULL);
+    ~MRFEnergyEst();
+
+    void SetMatrixTrain(MHMatrix *mat) { fMatrixTrain = mat; }
+    void SetMatrixTest( MHMatrix *mat) { fMatrixTest  = mat; }
+    void SetFile(TString str) { fRFfileName = str; }
+
+    void SetLogEnergyGrid(TArrayD &egrid) { fEnergyGrid = egrid ; }
+
+    void SetNumTrees(UShort_t n=100) { fNumTrees = n; }
+    void SetNdSize(UShort_t n=1)     { fNdSize   = n; }
+    void SetNumTry(UShort_t n)       { fNumTry   = n; }
+
+    Int_t Train();
+    Int_t Test();
+
+    ClassDef(MRFEnergyEst, 0) // Task
+};
+
+#endif
Index: /tags/Mars-V0.9/mranforest/MRanForest.cc
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanForest.cc	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanForest.cc	(revision 9772)
@@ -0,0 +1,438 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MRanForest                                                              //
+//                                                                         //
+// ParameterContainer for Forest structure                                 //
+//                                                                         //
+// A random forest can be grown by calling GrowForest.                     //
+// In advance SetupGrow must be called in order to initialize arrays and   //
+// do some preprocessing.                                                  //
+// GrowForest() provides the training data for a single tree (bootstrap    //
+// aggregate procedure)                                                    //
+//                                                                         //
+// Essentially two random elements serve to provide a "random" forest,     //
+// namely bootstrap aggregating (which is done in GrowForest()) and random //
+// split selection (which is subject to MRanTree::GrowTree())              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MRanForest.h"
+
+#include <TMatrix.h>
+#include <TRandom3.h>
+
+#include "MHMatrix.h"
+#include "MRanTree.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MRanForest);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MRanForest::MRanForest(const char *name, const char *title) : fNumTrees(100), fRanTree(NULL),fUsePriors(kFALSE)
+{
+    fName  = name  ? name  : "MRanForest";
+    fTitle = title ? title : "Storage container for Random Forest";
+
+    fForest=new TObjArray();
+    fForest->SetOwner(kTRUE);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MRanForest::~MRanForest()
+{
+    delete fForest;
+}
+
+void MRanForest::SetNumTrees(Int_t n)
+{
+    //at least 1 tree
+    fNumTrees=TMath::Max(n,1);
+    fTreeHad.Set(fNumTrees);
+    fTreeHad.Reset();
+}
+
+void MRanForest::SetPriors(Float_t prior_had, Float_t prior_gam)
+{
+    const Float_t sum=prior_gam+prior_had;
+
+    prior_gam/=sum;
+    prior_had/=sum;
+
+    fPrior[0]=prior_had;
+    fPrior[1]=prior_gam;
+
+    fUsePriors=kTRUE;
+}
+
+Int_t MRanForest::GetNumDim() const
+{
+    return fGammas ? fGammas->GetM().GetNcols() : 0;
+}
+
+
+Double_t MRanForest::CalcHadroness(const TVector &event)
+{
+    Double_t hadroness=0;
+    Int_t ntree=0;
+
+    TIter Next(fForest);
+
+    MRanTree *tree;
+    while ((tree=(MRanTree*)Next()))
+    {
+        fTreeHad[ntree]=tree->TreeHad(event);
+        hadroness+=fTreeHad[ntree];
+        ntree++;
+    }
+    return hadroness/ntree;
+}
+
+Bool_t MRanForest::AddTree(MRanTree *rantree=NULL)
+{
+    if (rantree)
+        fRanTree=rantree;
+    if (!fRanTree)
+        return kFALSE;
+
+    fForest->Add((MRanTree*)fRanTree->Clone());
+
+    return kTRUE;
+}
+
+Int_t MRanForest::GetNumData() const
+{
+    return fHadrons && fGammas ? fHadrons->GetM().GetNrows()+fGammas->GetM().GetNrows() : 0;
+}
+
+Bool_t MRanForest::SetupGrow(MHMatrix *mhad,MHMatrix *mgam)
+{
+    // pointer to training data
+    fHadrons=mhad;
+    fGammas=mgam;
+
+    // determine data entries and dimension of Hillas-parameter space
+    //fNumHad=fHadrons->GetM().GetNrows();
+    //fNumGam=fGammas->GetM().GetNrows();
+
+    const Int_t dim = GetNumDim();
+
+    if (dim!=fGammas->GetM().GetNcols())
+        return kFALSE;
+
+    const Int_t numdata = GetNumData();
+
+    // allocating and initializing arrays
+    fHadTrue.Set(numdata);
+    fHadTrue.Reset();
+    fHadEst.Set(numdata);
+
+    fPrior.Set(2);
+    fClassPop.Set(2);
+    fWeight.Set(numdata);
+    fNTimesOutBag.Set(numdata);
+    fNTimesOutBag.Reset();
+
+    fDataSort.Set(dim*numdata);
+    fDataRang.Set(dim*numdata);
+
+    // calculating class populations (= no. of gammas and hadrons)
+    fClassPop.Reset();
+    for(Int_t n=0;n<numdata;n++)
+        fClassPop[fHadTrue[n]]++;
+
+    // setting weights taking into account priors
+    if (!fUsePriors)
+        fWeight.Reset(1.);
+    else
+    {
+        for(Int_t j=0;j<2;j++)
+            fPrior[j] *= (fClassPop[j]>=1) ? (Float_t)numdata/fClassPop[j]:0;
+
+        for(Int_t n=0;n<numdata;n++)
+            fWeight[n]=fPrior[fHadTrue[n]];
+    }
+
+    // create fDataSort
+    CreateDataSort();
+
+    if(!fRanTree)
+    {
+        *fLog << err << dbginf << "MRanForest, fRanTree not initialized... aborting." << endl;
+        return kFALSE;
+    }
+    fRanTree->SetRules(fGammas->GetColumns());
+    fTreeNo=0;
+
+    return kTRUE;
+}
+
+void MRanForest::InitHadEst(Int_t from, Int_t to, const TMatrix &m, TArrayI &jinbag)
+{
+    for (Int_t ievt=from;ievt<to;ievt++)
+    {
+        if (jinbag[ievt]>0)
+            continue;
+        fHadEst[ievt] += fRanTree->TreeHad(m, ievt-from);
+        fNTimesOutBag[ievt]++;
+    }
+}
+
+Bool_t MRanForest::GrowForest()
+{
+    if(!gRandom)
+    {
+        *fLog << err << dbginf << "gRandom not initialized... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTreeNo++;
+
+    // initialize running output
+    if (fTreeNo==1)
+    {
+        *fLog << inf << endl;
+        *fLog << underline; // << "1st col        2nd col" << endl;
+        *fLog << "no. of tree    error in % (calulated using oob-data -> overestim. of error)" << endl;
+    }
+
+    const Int_t numdata = GetNumData();
+
+    // bootstrap aggregating (bagging) -> sampling with replacement:
+    //
+    // The integer k is randomly (uniformly) chosen from the set
+    // {0,1,...,fNumData-1}, which is the set of the index numbers of
+    // all events in the training sample
+    TArrayF classpopw(2);
+    TArrayI jinbag(numdata); // Initialization includes filling with 0
+    TArrayF winbag(numdata); // Initialization includes filling with 0
+
+    for (Int_t n=0; n<numdata; n++)
+    {
+        const Int_t k = Int_t(gRandom->Rndm()*numdata);
+
+        classpopw[fHadTrue[k]]+=fWeight[k];
+        winbag[k]+=fWeight[k];
+        jinbag[k]=1;
+    }
+
+    // modifying sorted-data array for in-bag data:
+    //
+    // In bagging procedure ca. 2/3 of all elements in the original
+    // training sample are used to build the in-bag data
+    TArrayI datsortinbag=fDataSort;
+    Int_t ninbag=0;
+
+    ModifyDataSort(datsortinbag, ninbag, jinbag);
+
+    const TMatrix &hadrons=fHadrons->GetM();
+    const TMatrix &gammas =fGammas->GetM();
+
+    // growing single tree
+    fRanTree->GrowTree(hadrons,gammas,fHadTrue,datsortinbag,
+                       fDataRang,classpopw,jinbag,winbag);
+
+    // error-estimates from out-of-bag data (oob data):
+    //
+    // For a single tree the events not(!) contained in the bootstrap sample of
+    // this tree can be used to obtain estimates for the classification error of
+    // this tree.
+    // If you take a certain event, it is contained in the oob-data of 1/3 of
+    // the trees (see comment to ModifyData). This means that the classification error
+    // determined from oob-data is underestimated, but can still be taken as upper limit.
+
+    const Int_t numhad = hadrons.GetNrows();
+    InitHadEst(0, numhad, hadrons, jinbag);
+    InitHadEst(numhad, numdata, gammas, jinbag);
+    /*
+    for (Int_t ievt=0;ievt<numhad;ievt++)
+    {
+        if (jinbag[ievt]>0)
+            continue;
+        fHadEst[ievt] += fRanTree->TreeHad(hadrons, ievt);
+        fNTimesOutBag[ievt]++;
+    }
+
+    for (Int_t ievt=numhad;ievt<numdata;ievt++)
+    {
+        if (jinbag[ievt]>0)
+            continue;
+        fHadEst[ievt] += fRanTree->TreeHad(gammas, ievt-numhad);
+        fNTimesOutBag[ievt]++;
+    }
+    */
+    Int_t n=0;
+    Double_t ferr=0;
+    for (Int_t ievt=0;ievt<numdata;ievt++)
+        if (fNTimesOutBag[ievt]!=0)
+        {
+            const Double_t val = fHadEst[ievt]/fNTimesOutBag[ievt]-fHadTrue[ievt];
+            ferr += val*val;
+            n++;
+        }
+
+    ferr = TMath::Sqrt(ferr/n);
+
+    // give running output
+    *fLog << inf << setw(5) << fTreeNo << Form("%15.2f", ferr*100) << endl;
+
+    // adding tree to forest
+    AddTree();
+
+    return fTreeNo<fNumTrees;
+}
+
+void MRanForest::CreateDataSort()
+{
+    // The values of concatenated data arrays fHadrons and fGammas (denoted in the following by fData,
+    // which does actually not exist) are sorted from lowest to highest.
+    //
+    //
+    //                   fHadrons(0,0) ... fHadrons(0,nhad-1)   fGammas(0,0) ... fGammas(0,ngam-1)
+    //                        .                 .                   .                .
+    //  fData(m,n)   =        .                 .                   .                .
+    //                        .                 .                   .                .
+    //                   fHadrons(m-1,0)...fHadrons(m-1,nhad-1) fGammas(m-1,0)...fGammas(m-1,ngam-1)
+    //
+    //
+    // Then fDataSort(m,n) is the event number in which fData(m,n) occurs.
+    // fDataRang(m,n) is the rang of fData(m,n), i.e. if rang = r, fData(m,n) is the r-th highest
+    // value of all fData(m,.). There may be more then 1 event with rang r (due to bagging).
+    const Int_t numdata = GetNumData();
+
+    TArrayF v(numdata);
+    TArrayI isort(numdata);
+
+    const TMatrix &hadrons=fHadrons->GetM();
+    const TMatrix &gammas=fGammas->GetM();
+
+    const Int_t numgam = gammas.GetNrows();
+    const Int_t numhad = hadrons.GetNrows();
+
+    for (Int_t j=0;j<numhad;j++)
+        fHadTrue[j]=1;
+
+    for (Int_t j=0;j<numgam;j++)
+        fHadTrue[j+numhad]=0;
+
+    const Int_t dim = GetNumDim();
+    for (Int_t mvar=0;mvar<dim;mvar++)
+    {
+        for(Int_t n=0;n<numhad;n++)
+        {
+            v[n]=hadrons(n,mvar);
+            isort[n]=n;
+        }
+
+        for(Int_t n=0;n<numgam;n++)
+        {
+            v[n+numhad]=gammas(n,mvar);
+            isort[n+numhad]=n;
+        }
+
+        TMath::Sort(numdata,v.GetArray(),isort.GetArray(),kFALSE);
+
+        // this sorts the v[n] in ascending order. isort[n] is the event number
+        // of that v[n], which is the n-th from the lowest (assume the original
+        // event numbers are 0,1,...).
+
+        for(Int_t n=0;n<numdata-1;n++)
+        {
+            const Int_t n1=isort[n];
+            const Int_t n2=isort[n+1];
+
+            fDataSort[mvar*numdata+n]=n1;
+            if(n==0) fDataRang[mvar*numdata+n1]=0;
+            if(v[n1]<v[n2])
+            {
+                fDataRang[mvar*numdata+n2]=fDataRang[mvar*numdata+n1]+1;
+            }else{
+                fDataRang[mvar*numdata+n2]=fDataRang[mvar*numdata+n1];
+            }
+        }
+        fDataSort[(mvar+1)*numdata-1]=isort[numdata-1];
+    }
+}
+
+void MRanForest::ModifyDataSort(TArrayI &datsortinbag, Int_t ninbag, const TArrayI &jinbag)
+{
+    const Int_t numdim=GetNumDim();
+    const Int_t numdata=GetNumData();
+
+    ninbag=0;
+    for (Int_t n=0;n<numdata;n++)
+        if(jinbag[n]==1) ninbag++;
+
+    for(Int_t m=0;m<numdim;m++)
+    {
+        Int_t k=0;
+        Int_t nt=0;
+        for(Int_t n=0;n<numdata;n++)
+        {
+            if(jinbag[datsortinbag[m*numdata+k]]==1)
+            {
+                datsortinbag[m*numdata+nt]=datsortinbag[m*numdata+k];
+                k++;
+            }else{
+                for(Int_t j=1;j<numdata-k;j++)
+                {
+                    if(jinbag[datsortinbag[m*numdata+k+j]]==1)
+                    {
+                        datsortinbag[m*numdata+nt]=datsortinbag[m*numdata+k+j];
+                        k+=j+1;
+                        break;
+                    }
+                }
+            }
+            nt++;
+            if(nt>=ninbag) break;
+        }
+    }
+}
+
+Bool_t MRanForest::AsciiWrite(ostream &out) const
+{
+    Int_t n=0;
+    MRanTree *tree;
+    TIter forest(fForest);
+
+    while ((tree=(MRanTree*)forest.Next()))
+    {
+        tree->AsciiWrite(out);
+        n++;
+    }
+
+    return n==fNumTrees;
+}
Index: /tags/Mars-V0.9/mranforest/MRanForest.h
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanForest.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanForest.h	(revision 9772)
@@ -0,0 +1,114 @@
+#ifndef MARS_MRanForest
+#define MARS_MRanForest
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MRanTree
+#include "MRanTree.h"
+#endif
+
+#ifndef MARS_MDataArray
+#include "MDataArray.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef ROOT_TRandom
+#include <TRandom.h>
+#endif
+
+class MHMatrix;
+class MRanTree;
+class TVector;
+class TMatrix;
+
+class MRanForest : public MParContainer
+{
+private:
+    Int_t fNumTrees;
+    Int_t fTreeNo;      //!
+
+    MRanTree *fRanTree; //!
+    TObjArray *fForest;
+
+    // training data
+    MHMatrix *fGammas;  //!
+    MHMatrix *fHadrons; //!
+
+    // true  and estimated hadronness
+    TArrayI fHadTrue;   //!
+    TArrayF fHadEst;    //!
+
+    // data sorted according to parameters
+    TArrayI fDataSort;  //!
+    TArrayI fDataRang;  //!
+    TArrayI fClassPop;  //!
+
+    // weights
+    Bool_t  fUsePriors; //!
+    TArrayF fPrior;     //!
+    TArrayF fWeight;    //!
+    TArrayI fNTimesOutBag;//!
+
+    // estimates for classification error of growing forest
+    TArrayD fTreeHad;   //
+
+    void InitHadEst(Int_t from, Int_t to, const TMatrix &m, TArrayI &jinbag);
+
+protected:
+    // create and modify (->due to bagging) fDataSort
+    void CreateDataSort();
+    void ModifyDataSort(TArrayI &datsortinbag, Int_t ninbag, const TArrayI &jinbag);
+
+public:
+    MRanForest(const char *name=NULL, const char *title=NULL);
+    ~MRanForest();
+
+    // initialize forest
+    void SetPriors(Float_t prior_had, Float_t prior_gam);
+    void SetNumTrees(Int_t n);
+
+    // tree growing
+    //void   SetupForest();
+    Bool_t SetupGrow(MHMatrix *mhad,MHMatrix *mgam);
+    Bool_t GrowForest();
+    void SetCurTree(MRanTree *rantree) { fRanTree=rantree; }
+    Bool_t AddTree(MRanTree *rantree);
+
+    // getter methods
+    TObjArray  *GetForest()      { return fForest; }
+    MRanTree   *GetCurTree()     { return fRanTree; }
+    MRanTree   *GetTree(Int_t i) { return (MRanTree*)(fForest->At(i)); }
+    MDataArray *GetRules() { return ((MRanTree*)(fForest->At(0)))->GetRules(); }
+
+
+    Int_t      GetNumTrees() const { return fNumTrees; }
+    Int_t      GetNumData()  const;
+    Int_t      GetNumDim()   const;
+    Double_t   GetTreeHad(Int_t i) const { return fTreeHad.At(i); }
+ 
+    // use forest to calculate hadronness of event
+    Double_t CalcHadroness(const TVector &event);
+
+    Bool_t AsciiWrite(ostream &out) const;
+
+    ClassDef(MRanForest, 1) // Storage container for tree structure
+};
+
+#endif
Index: /tags/Mars-V0.9/mranforest/MRanForestCalc.cc
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanForestCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanForestCalc.cc	(revision 9772)
@@ -0,0 +1,317 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRanForestCalc
+//
+//  Calculates the hadroness of an event. It calculates a mean value of all
+//  classifications by the trees in a previously grown random forest.
+//
+//  To use only n trees for your calculation use:
+//  MRanForestCalc::SetUseNumTrees(n);
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MRanForestCalc.h"
+
+#include <TVector.h>
+
+#include "MHMatrix.h" // must be before MLogManip.h
+#include "MDataArray.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRanTree.h"
+#include "MRanForest.h"
+
+#include "MHadronness.h"
+
+#include "MEvtLoop.h"
+#include "MTaskList.h"
+#include "MFillH.h"
+#include "MStatusDisplay.h"
+#include "MRanForestGrow.h"
+#include "MRanForestFill.h"
+
+#include "MWriteRootFile.h"
+#include "MReadTree.h"
+
+ClassImp(MRanForestCalc);
+
+using namespace std;
+
+static const TString gsDefName  = "MRanForestCalc";
+static const TString gsDefTitle = "Tree Classification Loop 1/2";
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms and the number of distances which are used for
+// avaraging in CalcDist
+//
+MRanForestCalc::MRanForestCalc(const char *name, const char *title)
+    : fNum(100), fHadronnessName("MHadronness"), fData(NULL), fRanForest(0), fRanTree(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the data chains
+//
+MRanForestCalc::~MRanForestCalc()
+{
+    if (!IsOwner())
+        return;
+
+    delete fRanForest;
+    delete fRanTree;
+}
+
+// --------------------------------------------------------------------------
+//
+// Needs:
+//  - MatrixGammas  [MHMatrix]
+//  - MatrixHadrons [MHMatrix]
+//  - MHadronness
+//  - all data containers used to build the matrixes
+//
+// The matrix object can be filles using MFillH. And must be of the same
+// number of columns (with the same meaning).
+//
+Int_t MRanForestCalc::PreProcess(MParList *plist)
+{
+    if (!fRanForest)
+    {
+        fRanForest = (MRanForest*)plist->FindObject("MRanForest");
+        if (!fRanForest)
+        {
+            *fLog << err << dbginf << "MRanForest not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    if (!fRanTree)
+    {
+        fRanTree = (MRanTree*)plist->FindObject("MRanTree");
+        if (!fRanTree)
+        {
+            *fLog << err << dbginf << "MRanTree not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fData = fRanTree->GetRules();
+
+    if (!fData)
+    {
+        *fLog << err << dbginf << "Error matrix doesn't contain columns... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (!fData->PreProcess(plist))
+    {
+        *fLog << err << dbginf << "PreProcessing of the MDataArray failed for the columns failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHadroness = (MHadronness*)plist->FindCreateObj("MHadronness", fHadronnessName);
+    if (!fHadroness)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MRanForestCalc::Process()
+{
+    // first copy the data from the data array to a vector event
+    TVector event;
+    *fData >> event;
+
+    Double_t hadroness=fRanForest->CalcHadroness(event);
+    fHadroness->SetHadronness(hadroness);
+
+    return kTRUE;
+}
+
+Bool_t MRanForestCalc::Grow(MHMatrix *matrixg,MHMatrix *matrixh,Int_t ntree,
+                            Int_t numtry,Int_t ndsize,const char* treefile,
+                            const char* treename,const char* contname,
+                            const char* hgininame)
+{
+
+    treename  = treename  ? treename  : "Tree";
+    contname  = contname  ? contname  : "MRanTree";
+    hgininame  = hgininame  ? hgininame  : "MHRanForestGini";
+
+    if (!matrixg->IsValid())
+    {
+        *fLog << err << dbginf << " MRanForestCalc::Grow - ERROR: matrixg not valid." << endl;
+        return kFALSE;
+    }
+    if(!matrixh->IsValid())
+    {
+        *fLog << err << dbginf << " MRanForestCalc::Grow - ERROR: matrixh not valid." << endl;
+        return kFALSE;
+    }
+
+    MEvtLoop run(GetName());
+    MTaskList tlist;
+    MParList plist;
+    plist.AddToList(&tlist);
+    plist.AddToList(matrixg);
+    plist.AddToList(matrixh);
+
+    // creating training task and setting parameters
+    MRanForestGrow rfgrow;
+    rfgrow.SetNumTrees(ntree); // number of trees
+    rfgrow.SetNumTry(numtry);  // number of trials in random split selection
+    rfgrow.SetNdSize(ndsize);  // limit for nodesize
+    tlist.AddToList(&rfgrow);
+
+    if(treefile){
+        MWriteRootFile rfwrite(treefile);
+        rfwrite.AddContainer(contname,treename);
+        tlist.AddToList(&rfwrite);
+    }
+
+    MFillH fillh(hgininame);
+    tlist.AddToList(&fillh);
+
+    run.SetParList(&plist);
+    
+    // Execute tree growing
+    if (!run.Eventloop())
+    {
+        *fLog << err << dbginf << "Evtloop in MRanForestCalc::Grow failed." << endl;
+        return kFALSE;
+    }
+    tlist.PrintStatistics(0, kTRUE);
+
+    if (TestBit(kEnableGraphicalOutput))
+        plist.FindObject(hgininame)->DrawClone();
+
+    return kTRUE;
+}
+
+Bool_t MRanForestCalc::Fill(Int_t ntree,const char* treefile,const char* treename)
+{
+    treefile  = treefile  ? treefile  : "RF.root";
+    treename  = treename  ? treename  : "Tree";
+
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read(treename,treefile);
+    read.DisableAutoScheme();
+
+    MRanForestFill rffill;
+    rffill.SetNumTrees(ntree);
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&rffill);
+
+    MEvtLoop run(GetName());
+    run.SetParList(&plist);
+
+    //
+    // Execute tree reading
+    //
+    if (!run.Eventloop())
+    {
+        *fLog << err << dbginf << "Evtloop in MRanForestCalc::Fill failed." << endl;
+        return kFALSE;
+    }
+    tlist.PrintStatistics(0, kTRUE);
+
+    return kTRUE;
+}
+
+Int_t MRanForestCalc::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (!IsEnvDefined(env, prefix, "File",     print))
+        return kFALSE;
+
+    TString fname = GetEnvValue(env, prefix, "File", "RF.root");
+    TString tname = GetEnvValue(env, prefix, "Tree", "Tree");
+    const Int_t   num   = GetEnvValue(env, prefix, "NumTrees", 100);
+    const Bool_t  debug = GetEnvValue(env, prefix, "Debug", kFALSE);
+
+    fname.ReplaceAll("\015", "");
+    tname.ReplaceAll("\015", "");
+
+    *fLog << inf << dbginf << "Reading " << num << " trees " << tname << " from file " << fname << endl;
+
+    gLog.SetNullOutput(!debug);
+    MEvtLoop evtloop;
+    MParList  plist;
+    evtloop.SetParList(&plist);
+    MLog l;
+    l.SetNullOutput(!debug);
+    evtloop.SetLogStream(&l);
+    gLog.SetNullOutput(debug);
+
+    if (IsOwner())
+    {
+        delete fRanForest;
+        delete fRanTree;
+    }
+    fRanForest = new MRanForest;
+    fRanTree   = new MRanTree;
+    SetOwner();
+
+    plist.AddToList(fRanForest);
+    plist.AddToList(fRanTree);
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read(tname, fname);
+    read.DisableAutoScheme();
+
+    MRanForestFill rffill;
+    rffill.SetNumTrees(num);
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&rffill);
+
+    if (!evtloop.Eventloop())
+    {
+        *fLog << err << "ERROR - Reading " << tname << " from file " << fname << endl;
+        return kERROR;
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mranforest/MRanForestCalc.h
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanForestCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanForestCalc.h	(revision 9772)
@@ -0,0 +1,60 @@
+#ifndef MARS_MRanForestCalc
+#define MARS_MRanForestCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MHMatrix
+#include "MHMatrix.h"
+#endif
+
+class MParList;
+class MHadronness;
+class MDataArray;
+class MRanTree;
+class MRanForest;
+
+class MRanForestCalc : public MTask
+{
+private:
+    Int_t  fNum;              // number of trees used to compute hadronness
+
+    TString fHadronnessName;  // Name of container storing hadronness
+
+    MHadronness *fHadroness;  //! Output container for calculated hadroness
+    MDataArray  *fData;       //! Used to store the MDataChains to get the event values
+    MRanForest  *fRanForest;
+    MRanTree    *fRanTree;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+    enum { kIsOwner = BIT(14) };
+
+    Bool_t IsOwner() const { return TestBit(kIsOwner); }
+    void SetOwner() { SetBit(kIsOwner); }
+
+public:
+    MRanForestCalc(const char *name=NULL, const char *title=NULL);
+    ~MRanForestCalc();
+
+    Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+    TString GetHadronnessName() const { return fHadronnessName; }
+
+    void SetUseNumTrees(UShort_t n=100) { fNum = n; }
+
+    Bool_t Grow(MHMatrix *matrixg,MHMatrix *matrixh,Int_t ntree,
+                Int_t numtry,Int_t ndsize,const char* treefile=0,
+                const char* treename=0,const char* contname=0,
+                const char* hgininame=0);
+
+    Bool_t Fill(Int_t ntree,const char* treefile=0,const char* treename=0);
+
+
+    ClassDef(MRanForestCalc, 0) // Task
+};
+
+#endif
Index: /tags/Mars-V0.9/mranforest/MRanForestFill.cc
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanForestFill.cc	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanForestFill.cc	(revision 9772)
@@ -0,0 +1,113 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRanForestFill
+//
+//  Calculates the hadroness of an event. It calculates a mean value of all
+//  classifications by the trees in a previously grown random forest.
+//
+//  To use only n trees for your calculation use:
+//  MRanForestFill::SetUseNumTrees(n);
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MRanForestFill.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRanForest.h"
+
+ClassImp(MRanForestFill);
+
+using namespace std;
+
+static const TString gsDefName  = "MRanForestFill";
+static const TString gsDefTitle = "Tree Classification Loop";
+
+// --------------------------------------------------------------------------
+//
+//
+MRanForestFill::MRanForestFill(const char *name, const char *title):fNumTrees(-1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the data chains
+//
+MRanForestFill::~MRanForestFill()
+{
+    //    delete fData;
+}
+
+// --------------------------------------------------------------------------
+Int_t MRanForestFill::PreProcess(MParList *plist)
+{
+    fRanTree = (MRanTree*)plist->FindObject("MRanTree");
+    if (!fRanTree)
+    {
+        *fLog << err << dbginf << "MRanTree not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanForest = (MRanForest*)plist->FindCreateObj("MRanForest");
+    if (!fRanForest)
+    {
+        *fLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNum=0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MRanForestFill::Process()
+{
+    if (!(fRanForest->AddTree(fRanTree)))
+        return kFALSE;
+
+    fNum++;
+
+    return fNumTrees<0 ? kTRUE : fNum<fNumTrees;
+}
+
+Int_t MRanForestFill::PostProcess()
+{
+    fRanForest->SetNumTrees(fNum);
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mranforest/MRanForestFill.h
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanForestFill.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanForestFill.h	(revision 9772)
@@ -0,0 +1,35 @@
+#ifndef MARS_MRanForestFill
+#define MARS_MRanForestFill
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRanTree;
+class MRanForest;
+class MParList;
+class MDataArray;
+
+class MRanForestFill : public MTask
+{
+private:
+    MRanTree *fRanTree;
+    MRanForest *fRanForest;
+    MDataArray *fData;
+    Int_t fNumTrees;
+    Int_t fNum;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MRanForestFill(const char *name=NULL, const char *title=NULL);
+    ~MRanForestFill();
+
+    void SetNumTrees(UShort_t n=100) { fNumTrees = n; }
+
+    ClassDef(MRanForestFill, 0) // Task
+};
+
+#endif
Index: /tags/Mars-V0.9/mranforest/MRanForestGrow.cc
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanForestGrow.cc	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanForestGrow.cc	(revision 9772)
@@ -0,0 +1,138 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MRanForestGrow                                                         //
+//                                                                         //
+//  Grows a random forest.                                                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MRanForestGrow.h"
+
+#include "MHMatrix.h" // must be before MLogManip.h
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRanTree.h"
+#include "MRanForest.h"
+
+ClassImp(MRanForestGrow);
+
+using namespace std;
+
+static const TString gsDefName  = "MRanForestGrow";
+static const TString gsDefTitle = "Tree Classification Loop 1/2";
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms and the number of distances which are used for
+// avaraging in CalcDist
+//
+MRanForestGrow::MRanForestGrow(const char *name, const char *title)
+    : fNumTrees(100),fNumTry(3),fNdSize(1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Needs:
+//  - MatrixGammas  [MHMatrix]
+//  - MatrixHadrons {MHMatrix]
+//  - MHadroness
+//  - all data containers used to build the matrixes
+//
+// The matrix object can be filles using MFillH. And must be of the same
+// number of columns (with the same meaning).
+//
+Int_t MRanForestGrow::PreProcess(MParList *plist)
+{
+    fMGammas = (MHMatrix*)plist->FindObject("MatrixGammas", "MHMatrix");
+    if (!fMGammas)
+    {
+        *fLog << err << dbginf << "MatrixGammas [MHMatrix] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMHadrons = (MHMatrix*)plist->FindObject("MatrixHadrons", "MHMatrix");
+    if (!fMHadrons)
+    {
+        *fLog << err << dbginf << "MatrixHadrons [MHMatrix] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fMGammas->GetM().GetNcols() != fMHadrons->GetM().GetNcols())
+    {
+        *fLog << err << dbginf << "Error matrices have different numbers of columns... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plist->FindCreateObj("MRanTree");
+    if (!fRanTree)
+    {
+        *fLog << err << dbginf << "MRanTree not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanForest = (MRanForest*)plist->FindCreateObj("MRanForest");
+    if (!fRanForest)
+    {
+        *fLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree->SetNumTry(fNumTry);
+    fRanTree->SetNdSize(fNdSize);
+    fRanForest->SetCurTree(fRanTree);
+    fRanForest->SetNumTrees(fNumTrees);
+
+    return fRanForest->SetupGrow(fMHadrons,fMGammas);
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MRanForestGrow::Process()
+{
+    Bool_t not_last=fRanForest->GrowForest();
+    fRanTree->SetReadyToSave();
+
+    return not_last;
+}
+
+Int_t MRanForestGrow::PostProcess()
+{
+    fRanTree->SetReadyToSave();
+    fRanForest->SetReadyToSave();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mranforest/MRanForestGrow.h
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanForestGrow.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanForestGrow.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MRanForestGrow
+#define MARS_MRanForestGrow
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MRanForestGrow                                                          //
+//                                                                         //
+// Task to grow (train) a random forest                                    //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MHMatrix;
+class MParList;
+class MRanForest;
+class MRanTree;
+
+class MRanForestGrow : public MTask
+{
+private:
+    MRanTree   *fRanTree;
+    MRanForest *fRanForest;
+    MHMatrix   *fMGammas;   //! Gammas describing matrix
+    MHMatrix   *fMHadrons;  //! Hadrons (non gammas) describing matrix
+
+    Int_t fNumTrees;
+    Int_t fNumTry;
+    Int_t fNdSize;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MRanForestGrow(const char *name=NULL, const char *title=NULL);
+
+    void SetNumTrees(Int_t n){    fNumTrees=n;}
+    void SetNumTry(Int_t n)  {    fNumTry=n;  }
+    void SetNdSize(Int_t n)  {    fNdSize=n;  }
+
+    ClassDef(MRanForestGrow, 0) // Task to grow a random forest
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mranforest/MRanTree.cc
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanTree.cc	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanTree.cc	(revision 9772)
@@ -0,0 +1,526 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRanTree
+//
+// ParameterContainer for Tree structure
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRanTree.h"
+
+#include <iostream>
+
+#include <TVector.h>
+#include <TMatrix.h>
+#include <TRandom.h>
+
+#include "MDataArray.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MRanTree);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MRanTree::MRanTree(const char *name, const char *title):fNdSize(0), fNumTry(3), fData(NULL)
+{
+
+    fName  = name  ? name  : "MRanTree";
+    fTitle = title ? title : "Storage container for structure of a single tree";
+}
+
+void MRanTree::SetNdSize(Int_t n)
+{
+    // threshold nodesize of terminal nodes, i.e. the training data is splitted
+    // until there is only pure date in the subsets(=terminal nodes) or the
+    // subset size is LE n
+
+    fNdSize=TMath::Max(1,n);//at least 1 event per node
+}
+
+void MRanTree::SetNumTry(Int_t n)
+{
+    // number of trials in random split selection:
+    // choose at least 1 variable to split in
+
+    fNumTry=TMath::Max(1,n);
+}
+
+void MRanTree::GrowTree(const TMatrix &mhad, const TMatrix &mgam,
+                        const TArrayI &hadtrue, TArrayI &datasort,
+                        const TArrayI &datarang, TArrayF &tclasspop, TArrayI &jinbag,
+                        const TArrayF &winbag)
+{
+    // arrays have to be initialized with generous size, so number of total nodes (nrnodes)
+    // is estimated for worst case
+    const Int_t numdim =mhad.GetNcols();
+    const Int_t numdata=winbag.GetSize();
+    const Int_t nrnodes=2*numdata+1;
+
+    // number of events in bootstrap sample
+    Int_t ninbag=0;
+    for (Int_t n=0;n<numdata;n++)
+        if(jinbag[n]==1) ninbag++;
+
+    TArrayI bestsplit(nrnodes);
+    TArrayI bestsplitnext(nrnodes);
+
+    fBestVar.Set(nrnodes);
+    fTreeMap1.Set(nrnodes);
+    fTreeMap2.Set(nrnodes);
+    fBestSplit.Set(nrnodes);
+
+    fTreeMap1.Reset();
+    fTreeMap2.Reset();
+    fBestSplit.Reset();
+
+    fGiniDec.Set(numdim);
+    fGiniDec.Reset();
+
+    // tree growing
+    BuildTree(datasort,datarang,hadtrue,bestsplit,
+              bestsplitnext,tclasspop,winbag,ninbag);
+
+    // post processing, determine cut (or split) values fBestSplit
+    Int_t nhad=mhad.GetNrows();
+
+    for(Int_t k=0; k<nrnodes; k++)
+    {
+        if (GetNodeStatus(k)==-1)
+            continue;
+
+        const Int_t &bsp =bestsplit[k];
+        const Int_t &bspn=bestsplitnext[k];
+        const Int_t &msp =fBestVar[k];
+
+        fBestSplit[k]  = bsp<nhad  ? mhad(bsp, msp):mgam(bsp-nhad, msp);
+        fBestSplit[k] += bspn<nhad ? mhad(bspn,msp):mgam(bspn-nhad,msp);
+        fBestSplit[k] /= 2;
+    }
+
+    // resizing arrays to save memory
+    fBestVar.Set(fNumNodes);
+    fTreeMap1.Set(fNumNodes);
+    fTreeMap2.Set(fNumNodes);
+    fBestSplit.Set(fNumNodes);
+}
+
+Int_t MRanTree::FindBestSplit(const TArrayI &datasort,const TArrayI &datarang,
+                              const TArrayI &hadtrue,Int_t ndstart,Int_t ndend,TArrayF &tclasspop,
+                              Int_t &msplit,Float_t &decsplit,Int_t &nbest,
+                              const TArrayF &winbag)
+{
+    const Int_t nrnodes = fBestSplit.GetSize();
+    const Int_t numdata = (nrnodes-1)/2;
+    const Int_t mdim = fGiniDec.GetSize();
+
+    // weighted class populations after split
+    TArrayF wc(2); 
+    TArrayF wr(2); // right node
+
+    // For the best split, msplit is the index of the variable (e.g Hillas par., zenith angle ,...)
+    // split on. decsplit is the decreae in impurity measured by Gini-index.
+    // nsplit is the case number of value of msplit split on,
+    // and nsplitnext is the case number of the next larger value of msplit.
+
+    Int_t nbestvar=0;
+
+    // compute initial values of numerator and denominator of Gini-index,
+    // Gini index= pno/dno
+    Double_t pno=0;
+    Double_t pdo=0;
+    for (Int_t j=0; j<2; j++)
+    {
+        pno+=tclasspop[j]*tclasspop[j];
+        pdo+=tclasspop[j];
+    }
+
+    const Double_t crit0=pno/pdo;
+    Int_t jstat=0;
+
+    // start main loop through variables to find best split,
+    // (Gini-index as criterium crit)
+
+    Double_t critmax=-FLT_MAX;
+
+    // random split selection, number of trials = fNumTry
+    for (Int_t mt=0; mt<fNumTry; mt++)
+    {
+        const Int_t mvar=Int_t(gRandom->Rndm()*mdim);
+        const Int_t mn  = mvar*numdata;
+
+        // Gini index = rrn/rrd+rln/rld
+        Double_t rrn=pno;
+        Double_t rrd=pdo;
+        Double_t rln=0;
+        Double_t rld=0;
+
+        TArrayF wl(2); // left node
+        wr = tclasspop;
+
+        Double_t critvar=-1.0e20;
+
+        for(Int_t nsp=ndstart;nsp<=ndend-1;nsp++)
+        {
+            const Int_t &nc=datasort[mn+nsp];
+            const Int_t &k=hadtrue[nc];
+
+            const Float_t &u=winbag[nc];
+
+            rln+=u*(2*wl[k]+u);
+            rrn+=u*(-2*wr[k]+u);
+            rld+=u;
+            rrd-=u;
+
+            wl[k]+=u;
+            wr[k]-=u;
+
+            if (datarang[mn+nc]>=datarang[mn+datasort[mn+nsp+1]])
+                continue;
+            if (TMath::Min(rrd,rld)<=1.0e-5)
+                continue;
+
+            const Double_t crit=(rln/rld)+(rrn/rrd);
+            if (crit<=critvar)
+                continue;
+
+            nbestvar=nsp;
+            critvar=crit;
+        }
+
+        if (critvar<=critmax)
+            continue;
+
+        msplit=mvar;
+        nbest=nbestvar;
+        critmax=critvar;
+    }
+
+    decsplit=critmax-crit0;
+
+    return critmax<-1.0e10 ? 1 : jstat;
+}
+
+void MRanTree::MoveData(TArrayI &datasort,Int_t ndstart,
+                        Int_t ndend,TArrayI &idmove,TArrayI &ncase,Int_t msplit,
+                        Int_t nbest,Int_t &ndendl)
+{
+    // This is the heart of the BuildTree construction. Based on the best split
+    // the data in the part of datasort corresponding to the current node is moved to the
+    // left if it belongs to the left child and right if it belongs to the right child-node.
+    const Int_t numdata = ncase.GetSize();
+    const Int_t mdim    = fGiniDec.GetSize();
+
+    TArrayI tdatasort(numdata);
+
+    // compute idmove = indicator of case nos. going left
+
+    for (Int_t nsp=ndstart;nsp<=ndend;nsp++)
+    {
+        const Int_t &nc=datasort[msplit*numdata+nsp];
+        idmove[nc]= nsp<=nbest?1:0;
+    }
+    ndendl=nbest;
+
+    // shift case. nos. right and left for numerical variables.
+
+    for(Int_t msh=0;msh<mdim;msh++)
+    {
+        Int_t k=ndstart-1;
+        for (Int_t n=ndstart;n<=ndend;n++)
+        {
+            const Int_t &ih=datasort[msh*numdata+n];
+            if (idmove[ih]==1)
+                tdatasort[++k]=datasort[msh*numdata+n];
+        }
+
+        for (Int_t n=ndstart;n<=ndend;n++)
+        {
+            const Int_t &ih=datasort[msh*numdata+n];
+            if (idmove[ih]==0)
+                tdatasort[++k]=datasort[msh*numdata+n];
+        }
+
+        for(Int_t m=ndstart;m<=ndend;m++)
+            datasort[msh*numdata+m]=tdatasort[m];
+    }
+
+    // compute case nos. for right and left nodes.
+
+    for(Int_t n=ndstart;n<=ndend;n++)
+        ncase[n]=datasort[msplit*numdata+n];
+}
+
+void MRanTree::BuildTree(TArrayI &datasort,const TArrayI &datarang,
+                         const TArrayI &hadtrue, TArrayI &bestsplit,
+                         TArrayI &bestsplitnext, TArrayF &tclasspop,
+                         const TArrayF &winbag, Int_t ninbag)
+{
+    // Buildtree consists of repeated calls to two void functions, FindBestSplit and MoveData.
+    // Findbestsplit does just that--it finds the best split of the current node.
+    // MoveData moves the data in the split node right and left so that the data
+    // corresponding to each child node is contiguous.
+    //
+    // buildtree bookkeeping:
+    // ncur is the total number of nodes to date.  nodestatus(k)=1 if the kth node has been split.
+    // nodestatus(k)=2 if the node exists but has not yet been split, and =-1 if the node is
+    // terminal.  A node is terminal if its size is below a threshold value, or if it is all
+    // one class, or if all the data-values are equal.  If the current node k is split, then its
+    // children are numbered ncur+1 (left), and ncur+2(right), ncur increases to ncur+2 and
+    // the next node to be split is numbered k+1.  When no more nodes can be split, buildtree
+    // returns.
+    const Int_t mdim    = fGiniDec.GetSize();
+    const Int_t nrnodes = fBestSplit.GetSize();
+    const Int_t numdata = (nrnodes-1)/2;
+
+    TArrayI nodepop(nrnodes);
+    TArrayI nodestart(nrnodes);
+    TArrayI parent(nrnodes);
+
+    TArrayI ncase(numdata);
+    TArrayI idmove(numdata);
+    TArrayI iv(mdim);
+
+    TArrayF classpop(nrnodes*2);
+    TArrayI nodestatus(nrnodes);
+
+    for (Int_t j=0;j<2;j++)
+        classpop[j*nrnodes+0]=tclasspop[j];
+
+    Int_t ncur=0;
+    nodepop[0]=ninbag;
+    nodestatus[0]=2;
+
+    // start main loop
+    for (Int_t kbuild=0; kbuild<nrnodes; kbuild++)
+    {
+          if (kbuild>ncur) break;
+          if (nodestatus[kbuild]!=2) continue;
+
+          // initialize for next call to FindBestSplit
+
+          const Int_t ndstart=nodestart[kbuild];
+          const Int_t ndend=ndstart+nodepop[kbuild]-1;
+          for (Int_t j=0;j<2;j++)
+              tclasspop[j]=classpop[j*nrnodes+kbuild];
+
+          Int_t msplit, nbest;
+          Float_t decsplit=0;
+          const Int_t jstat=FindBestSplit(datasort,datarang,hadtrue,
+                                          ndstart,ndend,tclasspop,msplit,
+                                          decsplit,nbest,winbag);
+
+          if (jstat==1)
+          {
+              nodestatus[kbuild]=-1;
+              continue;
+          }
+
+          fBestVar[kbuild]=msplit;
+          fGiniDec[msplit]+=decsplit;
+
+          bestsplit[kbuild]=datasort[msplit*numdata+nbest];
+          bestsplitnext[kbuild]=datasort[msplit*numdata+nbest+1];
+
+          Int_t ndendl;
+          MoveData(datasort,ndstart,ndend,idmove,ncase,
+                   msplit,nbest,ndendl);
+
+          // leftnode no.= ncur+1, rightnode no. = ncur+2.
+
+          nodepop[ncur+1]=ndendl-ndstart+1;
+          nodepop[ncur+2]=ndend-ndendl;
+          nodestart[ncur+1]=ndstart;
+          nodestart[ncur+2]=ndendl+1;
+
+          // find class populations in both nodes
+
+          for (Int_t n=ndstart;n<=ndendl;n++)
+          {
+              const Int_t &nc=ncase[n];
+              const Int_t &j=hadtrue[nc];
+              classpop[j*nrnodes+ncur+1]+=winbag[nc];
+          }
+
+          for (Int_t n=ndendl+1;n<=ndend;n++)
+          {
+              const Int_t &nc=ncase[n];
+              const Int_t &j=hadtrue[nc];
+              classpop[j*nrnodes+ncur+2]+=winbag[nc];
+          }
+
+          // check on nodestatus
+
+          nodestatus[ncur+1]=2;
+          nodestatus[ncur+2]=2;
+          if (nodepop[ncur+1]<=fNdSize) nodestatus[ncur+1]=-1;
+          if (nodepop[ncur+2]<=fNdSize) nodestatus[ncur+2]=-1;
+
+          Double_t popt1=0;
+          Double_t popt2=0;
+          for (Int_t j=0;j<2;j++)
+          {
+              popt1+=classpop[j*nrnodes+ncur+1];
+              popt2+=classpop[j*nrnodes+ncur+2];
+          }
+
+          for (Int_t j=0;j<2;j++)
+          {
+              if (classpop[j*nrnodes+ncur+1]==popt1) nodestatus[ncur+1]=-1;
+              if (classpop[j*nrnodes+ncur+2]==popt2) nodestatus[ncur+2]=-1;
+          }
+
+          fTreeMap1[kbuild]=ncur+1;
+          fTreeMap2[kbuild]=ncur+2;
+          parent[ncur+1]=kbuild;
+          parent[ncur+2]=kbuild;
+          nodestatus[kbuild]=1;
+          ncur+=2;
+          if (ncur>=nrnodes) break;
+    }
+
+    // determine number of nodes
+    fNumNodes=nrnodes;
+    for (Int_t k=nrnodes-1;k>=0;k--)
+    {
+        if (nodestatus[k]==0) fNumNodes-=1;
+        if (nodestatus[k]==2) nodestatus[k]=-1;
+    }
+
+    fNumEndNodes=0;
+    for (Int_t kn=0;kn<fNumNodes;kn++)
+        if(nodestatus[kn]==-1)
+        {
+            fNumEndNodes++;
+            Double_t pp=0;
+            for (Int_t j=0;j<2;j++)
+            {
+                if(classpop[j*nrnodes+kn]>pp)
+                {
+                    // class + status of node kn coded into fBestVar[kn]
+                    fBestVar[kn]=j-2;
+                    pp=classpop[j*nrnodes+kn];
+                }
+            }
+            fBestSplit[kn] =classpop[1*nrnodes+kn];
+            fBestSplit[kn]/=(classpop[0*nrnodes+kn]+classpop[1*nrnodes+kn]);
+        }
+}
+
+void MRanTree::SetRules(MDataArray *rules)
+{
+    fData=rules;
+}
+
+Double_t MRanTree::TreeHad(const TVector &event)
+{
+    Int_t kt=0;
+    // to optimize on storage space node status and node class
+    // are coded into fBestVar:
+    // status of node kt = TMath::Sign(1,fBestVar[kt])
+    // class  of node kt = fBestVar[kt]+2 (class defined by larger
+    //  node population, actually not used)
+    // hadronness assigned to node kt = fBestSplit[kt]
+
+    for (Int_t k=0;k<fNumNodes;k++)
+    {
+        if (fBestVar[kt]<0)
+            break;
+
+        const Int_t m=fBestVar[kt];
+        kt = event(m)<=fBestSplit[kt] ? fTreeMap1[kt] : fTreeMap2[kt];
+    }
+
+    return fBestSplit[kt];
+}
+
+Double_t MRanTree::TreeHad(const TMatrixRow &event)
+{
+    Int_t kt=0;
+    // to optimize on storage space node status and node class
+    // are coded into fBestVar:
+    // status of node kt = TMath::Sign(1,fBestVar[kt])
+    // class  of node kt = fBestVar[kt]+2 (class defined by larger
+    //  node population, actually not used)
+    // hadronness assigned to node kt = fBestSplit[kt]
+
+    for (Int_t k=0;k<fNumNodes;k++)
+    {
+        if (fBestVar[kt]<0)
+            break;
+
+        const Int_t m=fBestVar[kt];
+        kt = event(m)<=fBestSplit[kt] ? fTreeMap1[kt] : fTreeMap2[kt];
+    }
+
+    return fBestSplit[kt];
+}
+
+Double_t MRanTree::TreeHad(const TMatrix &m, Int_t ievt)
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(4,00,8)
+    return TreeHad(TMatrixRow(m, ievt));
+#else
+    return TreeHad(TMatrixFRow_const(m, ievt));
+#endif
+}
+
+Double_t MRanTree::TreeHad()
+{
+    TVector event;
+    *fData >> event;
+
+    return TreeHad(event);
+}
+
+Bool_t MRanTree::AsciiWrite(ostream &out) const
+{
+    TString str;
+    Int_t k;
+
+    out.width(5);out<<fNumNodes<<endl;
+
+    for (k=0;k<fNumNodes;k++)
+    {
+        str=Form("%f",GetBestSplit(k));
+
+        out.width(5);  out << k;
+        out.width(5);  out << GetNodeStatus(k);
+        out.width(5);  out << GetTreeMap1(k);
+        out.width(5);  out << GetTreeMap2(k);
+        out.width(5);  out << GetBestVar(k);
+        out.width(15); out << str<<endl;
+        out.width(5);  out << GetNodeClass(k);
+    }
+    out<<endl;
+
+    return k==fNumNodes;
+}
Index: /tags/Mars-V0.9/mranforest/MRanTree.h
===================================================================
--- /tags/Mars-V0.9/mranforest/MRanTree.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/MRanTree.h	(revision 9772)
@@ -0,0 +1,95 @@
+#ifndef MARS_MRanTree
+#define MARS_MRanTree
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class TMatrix;
+class TMatrixRow;
+class TVector;
+class TRandom;
+class MDataArray;
+
+class MRanTree : public MParContainer
+{
+private:
+    Int_t fNdSize;
+    Int_t fNumTry;
+
+    Int_t fNumNodes;
+    Int_t fNumEndNodes;
+    MDataArray *fData;
+
+    TArrayI fBestVar;
+    TArrayI fTreeMap1;
+    TArrayI fTreeMap2;
+    TArrayF fBestSplit;
+
+    TArrayF fGiniDec;
+
+    Int_t FindBestSplit(const TArrayI &datasort, const TArrayI &datarang,
+                        const TArrayI &hadtrue,
+                        Int_t ndstart, Int_t ndend, TArrayF &tclasspop,
+                        Int_t &msplit, Float_t &decsplit, Int_t &nbest,
+                        const TArrayF &winbag);
+
+    void MoveData(TArrayI &datasort, Int_t ndstart, Int_t ndend,
+                  TArrayI &idmove, TArrayI &ncase, Int_t msplit,
+                  Int_t nbest, Int_t &ndendl);
+
+    void BuildTree(TArrayI &datasort, const TArrayI &datarang,
+                   const TArrayI &hadtrue,
+                   TArrayI &bestsplit,TArrayI &bestsplitnext,
+                   TArrayF &tclasspop,
+                   const TArrayF &winbag,
+                   Int_t ninbag);
+
+public:
+    MRanTree(const char *name=NULL, const char *title=NULL);
+
+    void SetNdSize(Int_t n);
+    void SetNumTry(Int_t n);
+    void SetRules(MDataArray *rules);
+
+    MDataArray *GetRules() { return fData;}
+
+    Int_t GetNdSize() const { return fNdSize; }
+    Int_t GetNumTry() const { return fNumTry; }
+    Int_t GetNumNodes()          const { return fNumNodes; }
+    Int_t GetNumEndNodes()       const { return fNumEndNodes; }
+
+    Int_t GetBestVar(Int_t i)    const { return fBestVar.At(i); }
+    Int_t GetTreeMap1(Int_t i)   const { return fTreeMap1.At(i); }
+    Int_t GetTreeMap2(Int_t i)   const { return fTreeMap2.At(i); }
+    Int_t GetNodeClass(Int_t i)  const { return fBestVar.At(i)+2; }
+    Int_t GetNodeStatus(Int_t i) const { return TMath::Sign(1,fBestVar.At(i));}
+    Float_t GetBestSplit(Int_t i)const { return fBestSplit.At(i); }
+
+    Float_t GetGiniDec(Int_t i)  const { return fGiniDec.At(i); }
+
+    // functions used in tree growing process
+    void GrowTree(const TMatrix &mhad, const TMatrix &mgam,
+                  const TArrayI &hadtrue, TArrayI &datasort,
+                  const TArrayI &datarang,
+                  TArrayF &tclasspop, TArrayI &jinbag, const TArrayF &winbag);
+
+    Double_t TreeHad(const TVector &event);
+    Double_t TreeHad(const TMatrixRow &event);
+    Double_t TreeHad(const TMatrix &m, Int_t ievt);
+    Double_t TreeHad();
+
+    Bool_t AsciiWrite(ostream &out) const;
+
+    ClassDef(MRanTree, 1) // Storage container for tree structure
+};
+
+#endif
Index: /tags/Mars-V0.9/mranforest/Makefile
===================================================================
--- /tags/Mars-V0.9/mranforest/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/Makefile	(revision 9772)
@@ -0,0 +1,39 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = RanForest
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mdata -I../manalysis -I../mmc -I../mfileio
+#               MParContainer MH     MDataArray MHadronness    MMcEvt
+
+SRCFILES = MRanTree.cc \
+           MRanForest.cc \
+           MRanForestGrow.cc \
+           MRanForestCalc.cc \
+           MRanForestFill.cc \
+	   MHRanForest.cc \
+	   MHRanForestGini.cc \
+	   MRFEnergyEst.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mranforest/RanForestIncl.h
===================================================================
--- /tags/Mars-V0.9/mranforest/RanForestIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/RanForestIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mranforest/RanForestLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mranforest/RanForestLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mranforest/RanForestLinkDef.h	(revision 9772)
@@ -0,0 +1,18 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MRanTree+;  
+#pragma link C++ class MRanForest+;
+#pragma link C++ class MRanForestGrow+;
+#pragma link C++ class MRanForestCalc+;
+#pragma link C++ class MRanForestFill+;    
+
+#pragma link C++ class MHRanForest+;
+#pragma link C++ class MHRanForestGini+;
+
+#pragma link C++ class MRFEnergyEst+;
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawCrateArray.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawCrateArray.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawCrateArray.cc	(revision 9772)
@@ -0,0 +1,128 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRawCrateArray
+//
+//  This class exists to make it possible to read in the crate data
+//  TClones Array. In principal we can directly write the TClonesArray
+//  to the root file, but when we read in again the root file we cannot
+//  put the TClonesArray into our parameter list, becaus it isn't derived
+//  from MParContainer. This class is derived from MParContainer and can be
+//  put in the list. The TClones Array containes conatiners which store
+//  the information about one crate (MRawCrateData).
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRawCrateArray.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MRawCrateData.h"
+
+ClassImp(MRawCrateArray);
+
+// --------------------------------------------------------------------------
+//
+//  Default Constructor. It creates the TClonesArray which is used to store
+//  the crate data.
+//
+MRawCrateArray::MRawCrateArray(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MRawCrateArray";
+    fTitle = title ? title : "Array of MRawCrateData Information";
+
+    //
+    // craete an (almost) empty array. The size is easily determined
+    // while filling the array
+    //
+    fArray = new TClonesArray("MRawCrateData", 0);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. Deletes the TClones Array which stores the crate information
+//
+MRawCrateArray::~MRawCrateArray()
+{
+    //  FIXME: Is the contained data deleted, too?
+    delete fArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// clear the entries in the TClonesArray
+//
+void MRawCrateArray::Clear(Option_t *opt)
+{
+    fArray->Clear();
+}
+
+void MRawCrateArray::Print(Option_t *t) const
+{
+    fArray->Print();
+}
+
+void MRawCrateArray::SetSize(Int_t i)
+{
+    if (fArray->GetEntriesFast() == i)
+        return;
+
+    fArray->ExpandCreateFast(i);
+}
+
+Int_t MRawCrateArray::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return a pointer the i-th entry in the array, without range check
+//
+MRawCrateData *MRawCrateArray::GetEntry(Int_t i)
+{
+    return (MRawCrateData*)fArray->UncheckedAt(i); // AddrAt would be with rcheck
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the i-th entry in the array, with range check
+//
+MRawCrateData* &MRawCrateArray::operator[](Int_t i)
+{
+    return (MRawCrateData*&)(*fArray)[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// return a pointer to the pointer of the array
+// (actually not used. You may need it if you want to write
+//  the TClonesArray directly)
+//
+TClonesArray **MRawCrateArray::GetArray()
+{
+    return &fArray;
+}
Index: /tags/Mars-V0.9/mraw/MRawCrateArray.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawCrateArray.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawCrateArray.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MRawCrateArray
+#define MARS_MRawCrateArray
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MRunHeader                                                        //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TClonesArray;
+class MRawCrateData;
+
+class MRawCrateArray : public MParContainer
+{
+private:
+    TClonesArray *fArray;
+
+public:
+    MRawCrateArray(const char *name=NULL, const char *title=NULL);
+    ~MRawCrateArray();
+
+    void Clear(Option_t *opt=NULL);
+    void Print(Option_t *t=NULL) const;
+
+    void SetSize(Int_t i);
+    Int_t GetSize() const;
+    MRawCrateData *GetEntry(Int_t i);
+
+    MRawCrateData* &operator[](Int_t i);
+
+    TClonesArray **GetArray();
+
+    ClassDef(MRawCrateArray, 1)	// Mapping container for the MRawCrateData TClonesArray
+};
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawCrateData.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawCrateData.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawCrateData.cc	(revision 9772)
@@ -0,0 +1,81 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRawCrateData
+//
+//  This container stores the information about one crate. A list of this
+//  informations can be find at MRawCrateArray
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRawCrateData.h"
+
+#include <iostream>
+#include <iomanip>
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MRawCrateData);
+
+using namespace std;
+
+MRawCrateData::MRawCrateData() : fDAQCrateNumber(0), fFADCEvtNumber(0), fFADCClockTick(0), fABFlags(0)
+{
+}
+
+// --------------------------------------------------------------------------
+//
+//  read the information from a binary input stream about the CRATE DATA,
+//  like specified in a TDAS note
+//
+void MRawCrateData::ReadEvt(istream& fin, UShort_t ver)
+{
+    fin.read((char*)&fDAQCrateNumber, 2);
+    fin.read((char*)&fFADCEvtNumber,  4);
+    fin.read((char*)&fFADCClockTick,  4);
+    if (ver>1)
+       fin.read((char*)&fABFlags, 1);
+}
+
+void MRawCrateData::SkipEvt(istream &fin, UShort_t ver)
+{
+    fin.seekg(ver>1?11:10);
+}
+
+// --------------------------------------------------------------------------
+//
+//  print all stored information to gLog
+//
+void MRawCrateData::Print(Option_t *t) const
+{
+    *fLog << all;
+    *fLog << "Crate #" << dec << fDAQCrateNumber << ":  ";
+    *fLog << "FADCEventNr = " << fFADCEvtNumber << "  ";
+    *fLog << "FADCClockTick = " << fFADCClockTick << " (20MHz)  ";
+    *fLog << "ABFlags = 0x" << Form("%02x", fABFlags) << endl;
+}
Index: /tags/Mars-V0.9/mraw/MRawCrateData.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawCrateData.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawCrateData.h	(revision 9772)
@@ -0,0 +1,36 @@
+#ifndef MARS_MRawCrateData
+#define MARS_MRawCrateData
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+//gcc 3.2
+//class ifstream;
+#include <iosfwd>
+
+class MRawCrateData : public MParContainer
+{
+private:
+    UShort_t fDAQCrateNumber;  // Crate number the information corresponds to
+    UInt_t   fFADCEvtNumber;   // event number from the fadc
+    UInt_t   fFADCClockTick;   // clock tick from the fadc (20MHz)
+    Byte_t   fABFlags;         // flag describing in which two-slice block the trigger was raised
+
+public:
+    MRawCrateData();
+
+    UChar_t GetDAQCrateNumber() const  { return fDAQCrateNumber; }
+    UInt_t  GetFADCEvtNumber() const   { return fFADCEvtNumber;  }
+    UInt_t  GetFADCClockTick() const   { return fFADCClockTick;  }
+    Byte_t  GetABFlags() const         { return fABFlags;        }
+
+    void Print(Option_t *t=NULL) const;
+
+    void ReadEvt(istream& fin, UShort_t ver);
+    void SkipEvt(istream& fin, UShort_t ver);
+
+    ClassDef(MRawCrateData, 2) //Container to store the Raw CRATE DATA
+};
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawEvtData.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawEvtData.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawEvtData.cc	(revision 9772)
@@ -0,0 +1,597 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MRawEvtData
+//
+//  Storage container to store the raw FADC values.
+//
+//  MArrayS fHiGainPixId
+//  ---------------------
+//  Array of Pixel Numbers for their high voltage channel in the order the
+//  FADC values are stored in fHiGainFadcSamples
+//
+//  MArrayB fHiGainFadcSaples
+//  -------------------------
+//  FADC samples (hi gain) of all pixels
+//
+//  MArrayS fLoGainPixId
+//  --------------------
+//  see fHiGainPixId
+//
+//  MArrayB fLoGainFadcSamples
+//  --------------------------
+//  see fHiGainFadcSaples
+//
+//
+//   Version 5 (0.8.5):
+//   ------------------
+//    - Changed type of ABFlags from TArrayC to MArrayB
+//
+//   Version 4 (0.8.4):
+//   ------------------
+//    - Changed derivement from MCamEvent to MParContainer and MCamEvent
+//
+//   Version 3 (0.8.4):
+//   ------------------
+//    - Added fABFlags
+//
+//   Version 2:
+//   ----------
+//    - Derives from MCamEvent now
+//
+//   Version 1:
+//   ----------
+//    - First implementation
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MRawEvtData.h"
+
+#include <fstream>
+
+#include <TH1.h>
+#include <TGraph.h>
+#include <TArrayC.h>
+#include <TVirtualPad.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayS.h"
+#include "MArrayB.h"
+#include "MGeomCam.h"
+
+#include "MRawCrateArray.h"
+#include "MRawCrateData.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MRawEvtData);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It initializes all arrays with zero size.
+//
+MRawEvtData::MRawEvtData(const char *name, const char *title)
+    : fRunHeader(0)
+{
+    fName  = name  ? name  : "MRawEvtData";
+    fTitle = title ? title : "Raw Event Data Information";
+
+    InitArrays();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes all the arrays.
+//
+MRawEvtData::~MRawEvtData()
+{
+    DeleteArrays();
+}
+
+// --------------------------------------------------------------------------
+//
+// reset all arrays
+//
+void MRawEvtData::Clear(Option_t *)
+{
+    /*
+     FIXME:
+     Is Reset (set all entries to zero) what you want to do
+     or Set(0) (delete the array)
+     */
+    fHiGainPixId->Reset();
+    fLoGainPixId->Reset();
+    fHiGainFadcSamples->Reset();
+    fLoGainFadcSamples->Reset();
+    fABFlags->Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of hi gain samples per pixel
+//
+UShort_t MRawEvtData::GetNumHiGainSamples() const
+{
+    return fHiGainPixId->GetSize() ? fHiGainFadcSamples->GetSize()/fHiGainPixId->GetSize() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of lo gain samples per pixel
+//
+UShort_t MRawEvtData::GetNumLoGainSamples() const
+{
+    return fLoGainPixId->GetSize() ? fLoGainFadcSamples->GetSize()/fLoGainPixId->GetSize() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of stored pixel
+//
+UShort_t MRawEvtData::GetNumPixels() const
+{
+    return fHiGainPixId->GetSize();
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Print out the onformation to *fLog.
+//  Options:
+//     "hex"      Prints the time slices hexadecimal (default)
+//     "dec"      Prints the time slices decimal
+//
+void MRawEvtData::Print(Option_t *opt) const
+{
+    //
+    // print fadc inforation to screen
+    // Possible Options:
+    // - DEC: Print values decimal instead of hexadecimal (default)
+    //
+    const UShort_t nHiSamp = GetNumHiGainSamples();
+    const UShort_t nLoSamp = GetNumLoGainSamples();
+
+    const UShort_t nHiPix = fHiGainPixId->GetSize();;
+    const UShort_t nLoPix = fLoGainPixId->GetSize();;
+
+    fLog->unsetf(ios::showbase);
+
+    *fLog << dec << all;
+    *fLog << GetDescriptor() << ": " << endl;
+    *fLog << "HiGain: " << nHiPix << " Pixels with " << (Int_t)nHiSamp << " Samples" << endl;
+    *fLog << "LoGain: " << nLoPix << " Pixels with " << (Int_t)nLoSamp << " Samples";
+
+    TString str(opt);
+    Int_t manip = str.Contains("dec", TString::kIgnoreCase);
+
+    Int_t l=0;
+    for (int i=0; i<nHiPix; i++)
+    {
+        const UShort_t idx = (*fHiGainPixId)[i];
+
+        *fLog << endl;
+        *fLog << " " << setfill(' ') << setw(3) << dec << i << " - " << setw(3);
+        *fLog << dec << idx << " ";
+
+        if (fABFlags->GetSize())
+        {
+            *fLog << "<" << hex << setfill('0') << setw(2);
+            *fLog << ((Int_t)(*fABFlags)[idx/8]&0xff) << "> ";
+        }
+
+        *fLog << (manip?dec:hex) << (manip ? setfill(' ') : setfill('0'));
+
+        for (int j=0; j<nHiSamp; j++)
+        {
+            *fLog << setw(manip?3:2);
+            *fLog << ((UShort_t)(*fHiGainFadcSamples)[j+i*nHiSamp]&0xff);
+            if (manip)
+                *fLog << ' ';
+        }
+
+        if (!(l<nLoPix && (*fLoGainPixId)[l]==idx))
+            continue;
+
+        if (manip)
+            *fLog << "/ ";
+
+        for (int j=0; j<nLoSamp; j++)
+        {
+            *fLog << setw(manip?3:2);
+            *fLog << ((UShort_t)(*fLoGainFadcSamples)[j+i*nLoSamp]&0xff);
+            if (manip)
+                *fLog << ' ';
+        }
+        l++;
+    }
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a pixel. A Histogram or Graph is created and it's draw function is
+// called.
+//  Options:
+//     "GRAPH"      A graph is drawn
+//     "HIST"       A histogram is drawn
+//     <index>      The pixel with the given index is drawn
+//
+void MRawEvtData::Draw(Option_t *opt)
+{
+    if (GetNumPixels()==0)
+    {
+        *fLog << warn << "Sorry, no pixel to draw!" << endl;
+        return;
+    }
+
+    TString str(opt);
+    str.ToLower();
+
+    UInt_t id = 0;
+
+    if (str.BeginsWith("graph"))
+        if (str.Length()>5)
+            sscanf(&str[5], "%d", &id);
+    if (str.BeginsWith("hist"))
+        if (str.Length()>4)
+            sscanf(&str[4], "%d", &id);
+
+    MRawEvtPixelIter pix(this);
+    if (!pix.Jump(id))
+    {
+        *fLog << warn << dec << "Pixel Idx #" << id << " doesn't exist!" << endl;
+        return;
+    }
+
+    const Byte_t *higains = pix.GetHiGainSamples();
+    const Byte_t *logains = pix.GetLoGainSamples();
+
+    const Int_t nh = GetNumHiGainSamples();
+    const Int_t nl = GetNumLoGainSamples();
+
+    TString name = "Pixel Idx.";
+    name += pix.GetPixelId();
+
+    Bool_t same = str.Contains("same");
+
+    if (str.BeginsWith("graph"))
+    {
+        *fLog << inf << "Drawing Graph: Pixel Idx #" << dec << pix.GetPixelId();
+        *fLog << " of " << (int)GetNumPixels() << "Pixels" << endl;
+
+        TGraph *graphhi = new TGraph;
+
+        for (int i=0; i<nh; i++)
+            graphhi->SetPoint(graphhi->GetN(), i, higains[i]);
+
+        graphhi->SetMaximum(256);
+        graphhi->SetMinimum(0);
+
+        graphhi->SetBit(kCanDelete);
+        graphhi->Draw(same ? "C*" : "AC*");
+
+        TH1F *histhi = graphhi->GetHistogram();
+        histhi->SetMinimum(0);
+        histhi->SetMaximum(255);
+ 
+        histhi->SetXTitle("Time/FADC Slices");
+        histhi->SetYTitle("Signal/FADC Units");
+
+        if (nl>0)
+        {
+            TGraph *graphlo = new TGraph;
+
+            for (int i=0; i<nl; i++)
+                graphlo->SetPoint(graphlo->GetN(), i, logains[i]);
+
+            graphlo->SetMaximum(256);
+            graphlo->SetMinimum(0);
+            graphlo->SetLineColor(kBlue);
+
+            graphlo->SetBit(kCanDelete);
+            graphlo->Draw("C*");
+
+            TH1F *histlo = graphlo->GetHistogram();
+
+            histlo->SetXTitle("Time/FADC Slices");
+            histlo->SetYTitle("Signal/FADC Units");
+        }
+
+        return;
+    }
+
+    if (str.BeginsWith("hist"))
+    {
+        // FIXME: Add Legend
+        *fLog << inf << "Drawing Histogram of Pixel with Idx #" << dec << pix.GetPixelId() << " to " << gPad << endl;
+
+        TH1F *histh = new TH1F(name, "FADC Samples", nh, -0.5, nh-.5);
+        histh->SetMinimum(0);
+        histh->SetMaximum(255);
+        histh->SetXTitle("Time [FADC Slices]");
+        histh->SetYTitle("Signal [FADC Units]");
+        histh->SetDirectory(NULL);
+        for (int i=0; i<nh; i++)
+            histh->Fill(i, higains[i]);
+        histh->SetBit(kCanDelete);
+        histh->Draw(same ? "same" : "");
+
+        if (nl>0)
+        {
+            TH1F *histl = new TH1F(name+";2", "FADC Samples", nl, -0.5, nl-.5);
+            histl->SetLineColor(kBlue);
+            histl->SetDirectory(NULL);
+            for (int i=0; i<nl; i++)
+                histl->Fill(i, logains[i]);
+            histl->SetBit(kCanDelete);
+            histl->Draw("same");
+        }
+        return;
+    }
+
+    *fLog << warn << dbginf << "Warning - You must specify either 'GRAPH' or 'HIST'" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes all the arrays
+//  The flag is for future usage.
+//
+void MRawEvtData::InitArrays(UShort_t numconnected, UShort_t maxid)
+{
+    const Int_t numhi = fRunHeader ? fRunHeader->GetNumSamplesHiGain() : 0;
+    const Int_t numlo = fRunHeader ? fRunHeader->GetNumSamplesLoGain() : 0;
+
+    fHiGainPixId       = new MArrayS(numconnected);
+    fLoGainPixId       = new MArrayS(numconnected);
+    fHiGainFadcSamples = new MArrayB(numconnected*numhi);
+    fLoGainFadcSamples = new MArrayB(numconnected*numlo);
+
+    fABFlags           = new MArrayB(maxid==0 ? 0 : maxid/8+1);
+
+    fConnectedPixels   = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes all the arrays
+//
+void MRawEvtData::DeleteArrays()
+{
+    delete fHiGainPixId;
+    delete fLoGainPixId;
+    delete fHiGainFadcSamples;
+    delete fLoGainFadcSamples;
+    delete fABFlags;
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes all arrays describing the pixel Id and Samples in pixels.
+// The flag is for future usage.
+//
+void MRawEvtData::ResetPixels(UShort_t numconnected, UShort_t maxid)
+{
+    //const int npix = fRunHeader->GetNumCrates()*fRunHeader->GetNumPixInCrate();
+    if (fHiGainPixId && fHiGainPixId->GetSize()==numconnected && (UShort_t)fABFlags->GetSize()==(maxid/8+1))
+    {
+        fConnectedPixels = 0;
+        return;
+    }
+
+    DeleteArrays();
+    InitArrays(numconnected, maxid);
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is to fill the data of one pixel to the MRawEvtHeader Class.
+//  The parameters are the pixelnumber and the FADC_SLICES values of ADCs
+//  Add to lo gains if lflag = 1
+//
+void MRawEvtData::AddPixel(UShort_t nOfPixel, TArrayC *data, Bool_t lflag)
+{
+    MArrayS *arrpix = lflag ? fLoGainPixId       : fHiGainPixId;
+    MArrayB *arrsam = lflag ? fLoGainFadcSamples : fHiGainFadcSamples;
+
+    //
+    // check whether we got the right number of new samples
+    // if there are no samples already stored: this is the new number of samples
+    //
+    const UShort_t ns    = data->GetSize();
+    const UShort_t nSamp = lflag ? GetNumLoGainSamples() : GetNumHiGainSamples();
+    if (nSamp && ns!=nSamp)
+    {
+        *fLog << err << "RawEvtData::AddPixel: Error, number of samples in ";
+        *fLog << "TArrayC " << ns << " doesn't match current number " << nSamp << endl;
+        return;
+    }
+
+    //
+    // enhance pixel array by one
+    //
+    arrpix->Set(arrpix->GetSize()+1);
+
+    //
+    // add the number of the new pixel to the array as last entry
+    //
+    arrpix->AddAt(nOfPixel, arrpix->GetSize()-1);
+
+    //
+    // enhance the array by the number of new samples
+    //
+    arrsam->Set(arrsam->GetSize()+ns);
+
+    //
+    // add the new slices as last entries to array
+    //
+    arrsam->AddAt((Byte_t*)data->GetArray(), arrsam->GetSize()-ns, ns);
+}
+
+void MRawEvtData::ReadPixel(istream &fin, Int_t npix, Bool_t ab)
+{
+    Byte_t *poshi = fHiGainFadcSamples->GetArray() + fConnectedPixels*fRunHeader->GetNumSamplesHiGain();
+    Byte_t *poslo = fLoGainFadcSamples->GetArray() + fConnectedPixels*fRunHeader->GetNumSamplesLoGain();
+
+    // Read data for one pixel
+    fin.read((char*)poshi, fRunHeader->GetNumSamplesHiGain());
+    fHiGainPixId->AddAt(npix, fConnectedPixels);
+
+    if (poslo)
+    {
+        fin.read((char*)poslo, fRunHeader->GetNumSamplesLoGain());
+        // FIXME: Not implemented in the raw files yet
+        //if (IsLoGainOn(i, j))
+        //{
+        fLoGainPixId->AddAt(npix, fConnectedPixels);
+        //}
+    }
+
+    if (ab)
+        SETBIT((*fABFlags)[npix/8], npix%8);
+    else
+        CLRBIT((*fABFlags)[npix/8], npix%8);
+
+    fConnectedPixels++;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills members with information from a magic binary file.
+//   WARNING: you have to use Init() before you can do this
+//
+/*
+void MRawEvtData::ReadEvt(istream &fin, Int_t posinarray)
+{
+
+    const UShort_t npic = fRunHeader->GetNumPixInCrate();
+
+    const UShort_t npos = npic*posinarray;
+
+    //const Byte_t ab = fCrateArray->GetEntry(posinarray)->GetABFlags();
+
+    for (int i=npos; i<npic+npos; i++)
+    {
+        // calc the spiral hardware pixel number
+        const UShort_t ipos = i;
+
+        // Get Hardware Id
+        const Short_t hwid = fRunHeader->GetPixAssignment(ipos);
+
+        // Check whether the pixel is connected or not
+        if (hwid==0)
+        {
+            const UShort_t n = fRunHeader->GetNumSamplesLoGain()+fRunHeader->GetNumSamplesHiGain();
+            fin.seekg(n, ios::cur);
+            return;
+        }
+
+        // -1 converts the hardware pixel Id into the software pixel index
+        const Int_t npix = (Int_t)hwid-1;
+
+        const Byte_t ab = fCrateArray->GetEntry(posinarray)->GetABFlags();
+        AddPixel(fin, npix, TESTBIT(ab, i-npos));
+    }
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// Return the size in bytes of one event data block
+//
+Int_t MRawEvtData::GetNumBytes() const
+{
+    const UShort_t nlo  = fRunHeader->GetNumSamplesLoGain();
+    const UShort_t nhi  = fRunHeader->GetNumSamplesHiGain();
+    const UShort_t npic = fRunHeader->GetNumPixInCrate();
+
+    return (nhi+nlo)*npic;
+}
+
+// --------------------------------------------------------------------------
+//
+// Make sure, that you skip the whole event. This function only skips a part
+// of the event - see MRawRead::SkipEvent
+//
+void MRawEvtData::SkipEvt(istream &fin)
+{
+    fin.seekg(GetNumBytes(), ios::cur);
+}
+
+Bool_t MRawEvtData::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    MRawEvtPixelIter Next(const_cast<MRawEvtData*>(this));
+    if (!Next.Jump(idx))
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+        val = Next.GetSumHiGainSamples()-(float)GetNumHiGainSamples()*fHiGainFadcSamples->GetArray()[0];
+        val*= cam.GetPixRatio(idx);
+        break;
+    case 1:
+        val = Next.GetMaxHiGainSample();
+        break;
+    case 2:
+        val = Next.GetMaxLoGainSample();
+        break;
+    case 3:
+        val = Next.GetIdxMaxHiGainSample();
+        break;
+    case 4:
+        val = Next.GetIdxMaxLoGainSample();
+        break;
+    case 5:
+        val = Next.GetIdxMaxHiLoGainSample();
+        return val >= 0;
+    }
+
+    return kTRUE;
+}
+
+void MRawEvtData::Copy(TObject &named)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+const
+#endif
+{
+    MRawEvtData &evt = (MRawEvtData &)named;
+
+    *evt.fHiGainPixId = *fHiGainPixId;
+    *evt.fLoGainPixId = *fLoGainPixId;
+
+    *evt.fHiGainFadcSamples = *fHiGainFadcSamples;
+    *evt.fLoGainFadcSamples = *fLoGainFadcSamples;
+
+    *evt.fABFlags = *fABFlags;
+
+    evt.fConnectedPixels = fConnectedPixels;
+}
Index: /tags/Mars-V0.9/mraw/MRawEvtData.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawEvtData.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawEvtData.h	(revision 9772)
@@ -0,0 +1,90 @@
+#ifndef MARS_MRawEvtData
+#define MARS_MRawEvtData
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+// gcc 3.2
+//class ifstream;
+#include <iosfwd>
+
+class MRawRunHeader;
+class MRawCrateArray;
+
+class TArrayC;
+class MArrayS;
+class MArrayB;
+
+class MRawEvtData : public MParContainer, public MCamEvent
+{
+    friend class MRawEvtPixelIter;
+private:
+    MRawRunHeader  *fRunHeader;   //! provides information about numbers
+
+    // FIXME: COMMENT ABOUT ORDERING
+
+    MArrayS *fHiGainPixId;        //-> list of pixel IDs of hi gain channel
+    MArrayB *fHiGainFadcSamples;  //-> list of hi gain samples of all pixels (ordering: see fHiGainPixId)
+
+    MArrayS *fLoGainPixId;        //-> list of pixel IDs of lo gain channel
+    MArrayB *fLoGainFadcSamples;  //-> list of lo gain samples of all pixels (ordering: see fLoGainPixId)
+
+    MArrayB *fABFlags;            //-> A information about the exact trigger position
+
+    Int_t fConnectedPixels;   //!
+
+    void InitArrays(UShort_t numconnected=0, UShort_t maxid=0);
+    void DeleteArrays();
+
+    Int_t GetNumBytes() const;
+
+public:
+    MRawEvtData(const char *name=NULL, const char *title=NULL);
+    ~MRawEvtData();
+
+    void InitRead(MRawRunHeader *rh)
+    {
+        //
+        // you have to set this before you can read information
+        // from a magic binary file
+        //
+        fRunHeader  = rh;
+    }
+
+    void Clear(Option_t * = NULL);
+    void Print(Option_t * = NULL) const;
+    void Draw (Option_t * = NULL);
+
+    void ResetPixels(UShort_t npix, UShort_t maxid);
+    void AddPixel(UShort_t nOfPixel, TArrayC *data, Bool_t lflag=kFALSE);
+
+    UShort_t GetNumHiGainSamples() const;
+    UShort_t GetNumLoGainSamples() const;
+    UShort_t GetNumPixels() const;
+
+    void ReadPixel(istream &fin, Int_t npix, Bool_t ab);
+    //void ReadEvt(istream &fin, Int_t posinarray);
+    void SkipEvt(istream &fin);
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void   DrawPixelContent(Int_t num) const
+    {
+        TString s("HIST");
+        s += num;
+        const_cast<MRawEvtData*>(this)->Draw(s);
+    }
+
+    void Copy(TObject &named)
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,04,01)
+        const
+#endif
+        ;
+
+    ClassDef(MRawEvtData, 5) //Container to store the raw Event Data
+};
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawEvtHeader.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawEvtHeader.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawEvtHeader.cc	(revision 9772)
@@ -0,0 +1,414 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRawEvtHeader 
+//    
+// One Event is a sample of FADC measurements of different Pixels 
+// (Photomultipliers) from the Camera of MAGIC. So all data (FADC) of the 
+// interesting pixels are the modules of an event. To describe pixels the 
+// class MRawPixel is used and the class MRawCrate to describe Crates.
+// To define a single events some other data members are needed 
+// (Time of the events, tirgger pattern of event..)
+// 
+// To describe one event on the level of FADC values the Class MRawEvtHeader is
+// created. It has the following data members: 
+//
+// UInt_t    fDAQEvtNumber
+// -----------------------
+// This it the number of the Event in one 
+// data run. The first event in this run get
+// the number zero. The next one is one bigger.
+//
+// Assuming that one run takes 1 hour and a
+// triggerrate of 1kHz the number must be able
+// to reach 3.6e6 Events. To reach this number
+// you need at least 22 bits. This is the reason
+// why we use an integer (of root type UInt_t)
+// with a range to 4.2e9. 
+//
+// MTime   fRawEvtTime
+// -------------------
+// Time of the event. 
+// The start point of the time determination can be
+// the millenium. From that start point the time is
+// measured in 200ns-count. One day for example
+// contains 432.e9 counts. An array of two unsigned Int is able to 
+// contain 1.8e19 200ns-counts. This corresponds to 41.e6
+// days. This should be more than the livetime of MAGIC.
+// Private member of MTime.h
+//
+// UInt_t  fNumTrigLvl1
+// --------------------
+//
+// Number of first level trigger
+// This member counts the number of First Level Trigger
+// between the last and this event. May be that due to 
+// dead time of the DAQ this number is different from 1.
+// If the DAQ is fast enough, this value should be 1. 
+// This may be usefull in GammaRayBursts and if we 
+// apply a data reduction in the DAQ-chain, which selects
+// only good events. 
+//
+// UInt_t  fNumTrigLvl2
+// --------------------
+//
+// Number of second level trigger
+// This member counts the number of Second Level Trigger
+// between the last and this event. 
+//
+// UInt_t  fTrigPattern[0]
+// -----------------------
+// Trigger Pattern used for this event
+// Each event triggers for a particular configuration and each  
+// configuration should have an ID (which is not fixed yet).
+//
+// UInt_t  fCalibPattern == fTrigPattern[1]  
+// -----------------------
+// Calibration Pattern used for this event
+// Each (calibration) event uses a particular LEDs configuration and 
+// particular strength and colour of the continunous light.
+// Bits 1-16: Pulser slot pattern: 16 LEDs slots.
+// Bits 17: CT1 Pulser
+// Bits 21-24: Colour of Continous light source:
+// Bits 25-32: Strength of continuous light source: 256 level
+//
+// UShort_t fAllLowGainOn
+// ----------------------
+// 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)
+//
+// Class Version 2:
+// ---------------
+//  - added fCalibPattern
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRawEvtHeader.h"
+
+#include <iomanip>
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MArrayB.h"
+#include "MRawRunHeader.h"
+
+ClassImp(MRawEvtHeader);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Create the array to store the data.
+//
+MRawEvtHeader::MRawEvtHeader(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MRawEvtHeader";
+    fTitle = title ? title : "Raw Event Header Information";
+
+    //
+    //   set all member to zero, init the pointer to ClonesArray,
+    //
+    fPixLoGainOn = new MArrayB;
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes the array to store pixlogainon
+//
+MRawEvtHeader::~MRawEvtHeader()
+{
+    delete fPixLoGainOn;
+}
+
+// --------------------------------------------------------------------------
+//
+// you have to init the conatainer before you can read from
+// a raw binary file
+//
+void MRawEvtHeader::InitRead(MRawRunHeader *rh, MTime *t)
+{
+    //
+    // this is the number of entries in the array like specification
+    //
+    UInt_t fN = (rh->GetNumCrates() * rh->GetNumPixInCrate() + 7) / 8;
+
+    //
+    // initialize the array
+    //
+    fPixLoGainOn->Set(fN);
+
+    //
+    // this is the conatiner where we have to store the time of the event we
+    // read from the input stream
+    //
+    fTime = t;
+}
+
+// --------------------------------------------------------------------------
+//
+//   Implementation of the Clear function
+//
+//   Resets all members to zero, clear the list of Pixels
+//
+void MRawEvtHeader::Clear(Option_t *)
+{
+    fDAQEvtNumber   = 0;
+    fNumTrigLvl1    = 0;
+    fNumTrigLvl2    = 0;
+    fTrigPattern[0] = 0;
+    fTrigPattern[1] = 0;
+    fTrigType       = 0;
+    fNumLoGainOn    = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This member function prints all Data of one Event to *fLog.
+//
+void MRawEvtHeader::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << "DAQEvtNr: " << dec << fDAQEvtNumber << "  (";
+    *fLog << "Trigger: ";
+    *fLog << "NumLvl1=" << fNumTrigLvl1 << " ";
+    *fLog << "NumLvl2=" << fNumTrigLvl2 << " ";
+    *fLog << "Pattern=" << hex << setfill('0');
+    *fLog << setw(2) << fTrigPattern[0];
+    *fLog << setw(2) << fTrigPattern[1] << " " << dec;
+
+    *fLog << "Type=";
+    switch (fTrigType)
+    {
+    case 0:
+        *fLog << "Trigger";
+        break;
+    case 1:
+        *fLog << "Pedestal";
+        break;
+    case 2:
+        *fLog << "Calibration";
+        break;
+    case 3:
+        *fLog << "PinDiode";
+        break;
+    }
+    *fLog << ")" << endl;
+    *fLog << "Number of Lo Gains On: " << fNumLoGainOn << endl;
+
+    TString str(o);
+    str.ToLower();
+
+    if (str.Contains("nogains"))
+        return;
+
+    for (unsigned int i=0; i<fPixLoGainOn->GetSize(); i++)
+    {
+        for (int j=0; j<8; j++)
+        {
+            const UInt_t on = (*fPixLoGainOn)[i]&(1<<j) ? 1 : 0;
+            *fLog << on;
+        }
+    }
+    if (fPixLoGainOn->GetSize())
+        *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the size in bytes of the event header.
+//
+Int_t MRawEvtHeader::GetNumBytes() const
+{
+    return 36+fPixLoGainOn->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Used to set the header information. This is for MC only. NEVER, NEVER
+// use this somewhere else!
+//
+void MRawEvtHeader::FillHeader(UInt_t uiN, Float_t ulTP)
+{
+    fDAQEvtNumber = uiN;
+    fTrigPattern[0] = (UInt_t)(ulTP/4294967296.0) ;
+    fTrigPattern[1] = (UInt_t)(ulTP-fTrigPattern[0]*4294967296.0);
+}
+
+// --------------------------------------------------------------------------
+//
+// Decode the binary Time Stamp. For more detailed information see the
+// source code.
+//
+Bool_t MRawEvtHeader::DecodeTime(UInt_t abstime[2], UShort_t ver) const
+{
+    //
+    // SuperSecond (20 bits giving hh:mm:ss)
+    // ------------
+    // 
+    // Reading the hours:
+    // Swap bits: 23->16, 22->17, 21->16, 20->19
+    //
+    abstime[0] =
+        abstime[0]>>7 & 0x00010000 |
+        abstime[0]>>5 & 0x00020000 |
+        abstime[0]>>3 & 0x00040000 |
+        abstime[0]>>1 & 0x00080000 |
+        abstime[0]    & 0xff00ffff;
+
+    // 
+    // SubSecond (24 bits giving number of clock ticks of a 5Mhz signal since 
+    // the beginning of last second, i.e., number of ns with a precision of to
+    // 200 ns) 
+    // ----------
+    //
+    // The last 8 bits must be flipped.
+    //
+    abstime[1] ^= 0x000000ff;
+
+    //
+    // Due to a problem with one Digital Module, three of the less significant
+    // eight bits of the subsecond are corrupted. So, until new DM's arrive to
+    // La Palma, we won't use the eight first bits of the subsecond. 
+    // This reduces the precision from 200 ns to of 51.2 us. (ver<5)
+    //
+    if (ver<5)
+        abstime[1] &= 0xffffff00;
+
+    //
+    // Decode Time Stamp
+    //
+    const Byte_t h  = (abstime[0]>>18 & 0x3)*10 + (abstime[0]>>14 & 0xf);
+    const Byte_t m  = (abstime[0]>>11 & 0x7)*10 + (abstime[0]>> 7 & 0xf);
+    const Byte_t s  = (abstime[0]>> 4 & 0x7)*10 + (abstime[0]>> 0 & 0xf);
+    const UInt_t ns =  abstime[1]*200;
+
+    //
+    // Update the time stamp with the current event time.
+    // Make sure, that the time stamp was initialized correctly
+    // with the start-date/time of the run (after reading the run header)
+    //
+    if (fTime->UpdMagicTime(h, m, s, ns))
+        return kTRUE;
+
+    *fLog << warn << "WARNING - Time (" << Form("%2d:%02d:%02d,%09d", h, m, s, ns);
+    *fLog << ") in header of event #" << dec << fDAQEvtNumber << " invalid..." << endl;
+ 
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// read the EVENT HEADER information from the input stream
+// return FALSE if there is now header anymore, else TRUE
+//
+// For version>2 we expect to have a valid time-stamp in the files.
+//
+// Updates the time stamp with the current event time.
+// Make sure, that the time stamp was initialized correctly
+// with the start-date/time of the run (after reading the run header)
+//
+// Remark: This 'feature' disallows single runs of more than 11h!
+//
+Int_t MRawEvtHeader::ReadEvt(istream &fin, UShort_t ver)
+{
+    Bool_t rc = kTRUE;
+
+    fin.read((char*)&fDAQEvtNumber, 4);  // Total=4
+    if (!fin)
+        return kFALSE;
+
+    UInt_t abstime[2];
+    fin.read((char*)abstime,        8);  // Total=12
+
+    if (ver>2)
+        if (!DecodeTime(abstime, ver))
+            rc = kCONTINUE;
+
+    Byte_t dummy[4];
+    fin.read((char*)&fNumTrigLvl1,  4);  // Total=16
+    fin.read((char*)&fNumTrigLvl2,  4);  // Total=20
+    fin.read((char*)fTrigPattern,   8);  // Total=28
+    fin.read((char*)&fTrigType,     2);  // Total=30
+    fin.read((char*)dummy,          2);  // Total=32, was fAllLoGainOn
+    fin.read((char*)fPixLoGainOn->GetArray(), fPixLoGainOn->GetSize());
+
+    fNumLoGainOn = 0;
+    for (unsigned int i=0; i<fPixLoGainOn->GetSize(); i++)
+        for (int j=0; j<8; j++)
+            if ((*fPixLoGainOn)[i] & (1<<j))
+                fNumLoGainOn++;
+
+    fin.read((char*)&dummy, 4);
+
+    return fin.eof() ? kFALSE : rc;
+}
+
+void MRawEvtHeader::SkipEvt(istream &fin, UShort_t ver)
+{
+    fin.seekg(GetNumBytes(), ios::cur);
+}
+
+// --------------------------------------------------------------------------
+//
+//   Low level decoding of the trigger pattern.
+//   The trigger pattern consists of 16 bits (8+8 bits) generated by the 
+//   trigger system.
+//   The first 8 bits correspond to the trigger configuration before the
+//   prescaling, the others after prescaling.
+//   The meaning of the configuration depends on the chosen trigger table
+//   (that is how the trigger has been programmed) and must be interpreted 
+//    at higher level by the analysis. 
+//   Bit structure:
+//          not prscd | prscaled
+//           xxxx xxxx xxxx xxxx    <-- pattern (x=0,1)
+//     bit   7654 3210 7654 3210
+//          H                   L
+//
+//    e.g.   1000 0000 1000 1000 (hex: 8080) is the pattern when no
+//         L2 trigger selection and no prescaling is applied. 
+//       
+//    Up to now only fTrigPattern[0] is used.
+//
+UInt_t MRawEvtHeader::GetTriggerID() const
+{
+    return fTrigPattern[0];
+}
+
+UInt_t MRawEvtHeader::GetCalibrationPattern() const
+{
+    return fTrigPattern[1];
+}
+
+UInt_t MRawEvtHeader::GetPulserSlotPattern() const
+{
+    return (fTrigPattern[1] >> 16) & 0x1ffff;
+}
+
Index: /tags/Mars-V0.9/mraw/MRawEvtHeader.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawEvtHeader.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawEvtHeader.h	(revision 9772)
@@ -0,0 +1,104 @@
+#ifndef MARS_MRawEvtHeader
+#define MARS_MRawEvtHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+// gcc 3.2
+//class ifstream;
+#include <iosfwd>
+
+class MTime;
+class MArrayB;
+class MRawRunHeader;
+
+class MRawEvtHeader : public MParContainer
+{
+public:
+    //
+    // Trigger Type (TT)
+    //
+    enum {
+        kTTEvent       = 0,
+        kTTPedestal    = 1,
+        kTTCalibration = 2,
+        kTTPinDiode    = 3
+    };
+
+    enum CLColor_t 
+      {
+        kCLUV       = BIT(0),
+        kCLGreen    = BIT(1),
+        kCLAmber    = BIT(2),
+        kCLRed      = BIT(3),
+        kCLRedAmber   = kCLRed & kCLAmber,
+        kCLRedGreen   = kCLRed & kCLGreen,
+        kCLRedUV      = kCLRed & kCLUV   ,
+        kCLAmberGreen = kCLAmber & kCLGreen,
+        kCLAmberUV    = kCLAmber & kCLUV   ,
+        kCLGreenUV    = kCLGreen & kCLUV   ,
+        kCLRedAmberGreen = kCLRedAmber & kCLGreen,
+        kCLRedGreenUV    = kCLRedGreen & kCLUV,
+        kCLAmberGreenUV  = kCLAmberGreen & kCLUV,
+        kCLAll           = kCLRedAmberGreen & kCLUV
+      };
+    
+
+private:
+    MTime   *fTime;            //! object to store the time in (ReadEvt)
+
+    UInt_t   fDAQEvtNumber;    // Number of Event
+
+    UInt_t   fNumTrigLvl1;     // Number of 1st level tiggers between 2 events
+    UInt_t   fNumTrigLvl2;     // Number of 2nd level tiggers between 2 events
+    UInt_t   fTrigPattern[2];  // Trigger configuration
+
+    UShort_t fNumLoGainOn;     // Indicating if no pixel has a neglegible
+                               // low gain signal (0), else it is the number
+                               // of pixels with lo gain on
+
+    //
+    // Informations only needed to read the raw file correctly
+    //
+    UShort_t fTrigType;        //! Trigger Type of this event
+    MArrayB *fPixLoGainOn;     //! Array which tell you which pixels have lo gain on
+
+    Bool_t DecodeTime(UInt_t abstime[2], UShort_t ver) const;
+
+    Int_t GetNumBytes() const;
+
+public:
+    MRawEvtHeader(const char *name=NULL, const char *title=NULL);
+    ~MRawEvtHeader();
+
+    void InitRead(MRawRunHeader *rh, MTime *t);
+
+    void Clear(Option_t * = NULL);
+    void Print(Option_t * = NULL) const;
+
+    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; }
+    
+    UInt_t     GetTriggerID() const;
+    UInt_t     GetCalibrationPattern() const;
+    UInt_t     GetPulserSlotPattern()  const;
+
+    void       SetTriggerPattern( const UInt_t pattern )  {  fTrigPattern[0] = pattern; } // Only for MC!
+    void       SetCalibrationPattern( const UInt_t pattern )  {  fTrigPattern[1] = pattern; } // Only for MC!
+
+    Int_t ReadEvt(istream& fin, UShort_t ver);
+    void  SkipEvt(istream& fin, UShort_t ver);
+
+    ClassDef(MRawEvtHeader, 1) // Parameter Conatiner for raw EVENT HEADER
+}; 
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawEvtPixelIter.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawEvtPixelIter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawEvtPixelIter.cc	(revision 9772)
@@ -0,0 +1,372 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Markus Gaus 10/2002 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////////
+//
+//  MRawEvtPixelIter
+//
+//  class to iterate over all pixels of one event.
+//  The calling is similar to a root iterator:
+//  
+//  MRawEvtData *evtdata;            // must be filled with data from somewhere
+//  MRawEvtPixelIter pixel(evtdata); // evtdata: ptr to event you want to iterate
+//
+//  while (pixel.Next())
+//  {
+//     // here you can access the actual time slices by using
+//     //   pixel.GetPixelId();
+//     //   pixel.GetHiGainFadcSamples()[i]; // i is the number of the slice
+//     //   pixel.HasLoGain();               // check if pixel has
+//     //   pixel.GetLoGainFadcSamples()[i]; // i is the number of the slice
+//
+//     // WARNING: Don't acces more time slices than available.
+//     //   Get the numbers by calling: evtdata->GetNum[Lo,Hi]GainSamples()
+//     //   This number is constant for one event
+//  }
+//
+///////////////////////////////////////////////////////////////////////////////
+#include "MRawEvtPixelIter.h"
+
+#include <TArrayC.h>
+
+#include "MRawEvtData.h"
+
+#include "MArrayS.h"
+#include "MArrayB.h"
+
+ClassImp(MRawEvtPixelIter);
+
+using namespace std;
+
+MRawEvtPixelIter::MRawEvtPixelIter(MRawEvtData *dat) : fABFlags(0), fData(dat)
+{
+    fNumHiGainSamples = dat->GetNumHiGainSamples();
+    fNumLoGainSamples = dat->GetNumLoGainSamples();
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// return kTRUE  the lo gains exist for the actual pixel, else return kFALSE
+//
+Bool_t MRawEvtPixelIter::HasLoGain() const
+{
+    // We have no lo-gain at all
+    if (!fLoGainId)
+        return kFALSE;
+
+    // This is to make the first call of this function in Next()
+    // work properly! NEVER call this function before Next()
+    if (fNumLoGainEntry==0)
+        return kTRUE;
+
+    if (fNumLoGainEntry>fData->fLoGainPixId->GetSize())
+        return kFALSE;
+
+    Bool_t rc = *fHiGainId!=*fLoGainId;
+
+    if (rc)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// It steps to the next pixel. If there is no next pixel NULL is returned.
+// If a next pixel where found, a pointer to the primary given (constructor)
+// data structur is returned.
+//
+MRawEvtData *MRawEvtPixelIter::Next()
+{
+    //
+    // if we are already at the last entry there is no 'next' entry anymore
+    //
+    if (fNumHiGainEntry==fData->fHiGainPixId->GetSize())
+        return NULL;
+
+    //
+    // if we are already at the last entry there is no 'next' entry anymore
+    //
+    if (HasLoGain())
+    {
+        //
+        // if higainpixid and logainpixid of the actual pixel are
+        // identical then we have to move the pointer to the next
+        // entry in the lo gains
+        //
+        fNumLoGainEntry++;
+        fLoGainId++;
+        fLoGainPos += fNumLoGainSamples;
+    }
+
+    //
+    // here we have to move the pointer to the next entry in the hi gains
+    //
+    fNumHiGainEntry++;
+    fHiGainId++;
+    fHiGainPos += fNumHiGainSamples;
+
+    //
+    // return a pointer to the 'source' class if we succeed
+    //
+    return fData;
+}
+
+// --------------------------------------------------------------------------
+//
+// Reset the iteration. Jump to the first pixel.
+//
+void MRawEvtPixelIter::Reset()
+{
+    //
+    // set counter to zero
+    //
+    fNumLoGainEntry = 0;
+    fNumHiGainEntry = 0;
+
+    //
+    // set pointer to first entry of arrays
+    //
+    fHiGainId   = fData->fHiGainPixId->GetArray()-1;
+    fLoGainId   = fData->fLoGainPixId->GetArray();
+    fHiGainPos  = fData->fHiGainFadcSamples->GetArray()-fNumHiGainSamples;
+    fLoGainPos  = fData->fLoGainFadcSamples->GetArray()-fNumLoGainSamples;
+    fABFlags    = fData->fABFlags->GetSize()==0 ? 0 : fData->fABFlags->GetArray();
+
+    //
+    // In case fLoGainPixId.GetSize()=0 some root versions seems to
+    // initialize the array with NULL. This makes both cases work.
+    //
+    if (fLoGainId)
+        fLoGainId -= 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls the draw-function of the actual pixel (see MRawEvtData::Draw)
+//
+void MRawEvtPixelIter::Draw(Option_t *t)
+{ 
+    fData->Draw(Form("%s%d", t, *fHiGainId));
+}
+
+// --------------------------------------------------------------------------
+//
+// returns the sum of all hi gain fadc samples of the actual pixel
+//
+ULong_t MRawEvtPixelIter::GetSumHiGainSamples() const
+{
+    //
+    // return the sum of the hi gain samples of the present pixel
+    //
+    Byte_t *ptr = fHiGainPos;
+    const Byte_t *end = fHiGainPos + fNumHiGainSamples;
+
+    ULong_t sum=0;
+
+    do sum += *ptr++;
+    while (ptr != end);
+
+    return sum;
+}
+
+// --------------------------------------------------------------------------
+//
+// returns the sum of squares of all hi gain fadc sample of the actual pixel
+//
+ULong_t MRawEvtPixelIter::GetSumSqrHiGainSamples() const
+{
+    //
+    // return the sum of the squares of the hi gain samples of the present pixel
+    //
+    Byte_t *ptr = fHiGainPos;
+    const Byte_t *end = fHiGainPos + fNumHiGainSamples;
+
+    ULong_t sum=0;
+
+    do sum += (*ptr)*(*ptr);
+    while (++ptr != end);
+
+    return sum;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the variance (sigma^2) of the HiGainSamples
+//
+Float_t MRawEvtPixelIter::GetVarHiGainSamples() const
+{
+    Byte_t *ptr = fHiGainPos;
+    const Byte_t *end = fHiGainPos + fNumHiGainSamples;
+
+    ULong_t sum=0;
+    ULong_t sqsum=0;
+
+    do {
+        sum += *ptr;
+        sqsum += (*ptr)*(*ptr);
+    } while (++ptr != end);
+
+    return (sqsum-(Float_t)sum*sum/fNumHiGainSamples)/(fNumHiGainSamples-1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the index of the FADC slice the maximum signal in. If the highest
+// slices have the same value the last one is returned.
+//
+Byte_t MRawEvtPixelIter::GetIdxMaxHiGainSample() const
+{
+    Byte_t *ptr = fHiGainPos+1;
+    Byte_t *max = fHiGainPos;
+    const Byte_t *end = fHiGainPos + fNumHiGainSamples;
+
+    do if (*ptr>*max) max = ptr;
+    while (++ptr != end);
+
+    return max-fHiGainPos;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the index of the FADC slice the maximum signal in. If no lo-gains
+// are available -1 is returned. If the highest slices have the same value the
+// last one is returned.
+//
+Short_t MRawEvtPixelIter::GetIdxMaxLoGainSample(const Byte_t lofirst) const
+{
+    if (!HasLoGain())
+        return -1; // means: not found
+
+    Byte_t *ptr = fLoGainPos+lofirst+1;
+    Byte_t *max = fLoGainPos+lofirst;
+    const Byte_t *end = fLoGainPos + fNumLoGainSamples;
+
+    do if (*ptr>*max) max = ptr;
+    while (++ptr != end);
+
+    return max-fLoGainPos;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the index of the maximum FADC slice from high gain at first. If 
+// high gain is saturated it returns the low gain one.
+// If no lo-gains are existing and the hi-gains have saturating values
+// a negative value (-1) is returned.
+// 
+Short_t MRawEvtPixelIter::GetIdxMaxHiLoGainSample() const
+{
+    Byte_t max  = 0;
+    Char_t maxi = 0;
+
+    for (int i=fNumHiGainSamples-1; i>=0; i--)
+        if (fHiGainPos[i]>max)
+        {
+            max  = fHiGainPos[i];
+            maxi = i;
+        }
+
+    return max<0xff ? maxi : GetIdxMaxLoGainSample();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the maximum signal of all sliced in the hi gain samples
+//
+Byte_t MRawEvtPixelIter::GetMaxHiGainSample() const
+{
+    Byte_t max = 0;
+
+    for (int i=0; i<fNumHiGainSamples; i++)
+        if (fHiGainPos[i]>max)
+            max = fHiGainPos[i];
+
+    return max;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the maximum signal of all sliced in the hi gain samples
+//
+Byte_t MRawEvtPixelIter::GetMaxLoGainSample() const
+{
+    Byte_t max = 0;
+
+    for (int i=fNumLoGainSamples-1; i>=0; i--)
+        if (fLoGainPos[i]>max)
+            max = fLoGainPos[i];
+
+    return max;
+}
+
+// --------------------------------------------------------------------------
+//
+// returns the sum of all lo gain fadc samples of the actual pixel.
+// if no lo gain information is available 0 is returned.
+//
+ULong_t MRawEvtPixelIter::GetSumLoGainSamples() const
+{
+    //
+    // return the sum of the lo gain samples of the present pixel
+    //
+    if (!HasLoGain())
+        return 0;
+
+    Byte_t *ptr = fLoGainPos;
+    const Byte_t *end = fLoGainPos + fNumLoGainSamples;
+
+    ULong_t sum=0;
+
+    do sum += *ptr++;
+    while (ptr != end);
+
+    return sum;
+}
+
+// --------------------------------------------------------------------------
+//
+// returns the sum of squares of all hi gain fadc sample of the actual pixel
+//
+ULong_t MRawEvtPixelIter::GetSumSqrLoGainSamples() const
+{
+    //
+    // return the sum of the lo gain samples squares of the present pixel
+    //
+    if (!HasLoGain())
+        return 0;
+
+    Byte_t *ptr = fLoGainPos;
+    const Byte_t *end = fLoGainPos + fNumLoGainSamples;
+
+    ULong_t sum=0;
+
+    do sum += (*ptr)*(*ptr);
+    while (++ptr != end);
+
+    return sum;
+}
Index: /tags/Mars-V0.9/mraw/MRawEvtPixelIter.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawEvtPixelIter.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawEvtPixelIter.h	(revision 9772)
@@ -0,0 +1,128 @@
+#ifndef MARS_MRawEvtPixelIter
+#define MARS_MRawEvtPixelIter
+///////////////////////////////////////////////////////////////////////////////
+//
+//  MRawEvtPixelIter
+//
+//  class to iterate over all pixels of one event.
+//
+///////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+class MRawEvtData;
+
+class MRawEvtPixelIter : public TObject
+{
+private:
+    UShort_t  fNumHiGainEntry;  //! actual number of entry in fHiGainPixId
+    UShort_t  fNumLoGainEntry;  //! actual number of entry in fLoGainPixId
+
+    UShort_t *fHiGainId;        //! actual entry of fHiGainPixId
+    UShort_t *fLoGainId;        //! actual entry of fLoGainPixId
+
+    Byte_t   *fHiGainPos;       //! pointer to hi-gain samples of actual pixel
+    Byte_t   *fLoGainPos;       //! pointer to lo-gain samples of actual pixel
+
+    Byte_t   *fABFlags;         //! pointer to AB flags
+
+    UShort_t  fNumEntry;
+
+    Byte_t fNumHiGainSamples;   //!
+    Byte_t fNumLoGainSamples;   //!
+
+    MRawEvtData *fData;         //! pointer to object which we are iterating
+
+public:
+    MRawEvtPixelIter(MRawEvtData *dat);
+
+    MRawEvtData *Next();
+
+    Bool_t Jump(UShort_t id)
+    {
+        //
+        // Jump to the pixel with the pixel-id ID
+        // If it doesn't exist return FALSE
+        //
+        Reset();
+        while (Next())
+            if (GetPixelId() == id)
+                return kTRUE;
+        return kFALSE;
+    }
+
+    UShort_t GetPixelId() const
+    {
+        //
+        // return Id of actual pixel
+        //
+        return *fHiGainId;
+    }
+
+    UShort_t GetNumEntry() const
+    {
+        return fNumHiGainEntry;
+    }
+
+    Byte_t *GetHiGainSamples() const
+    {
+        //
+        // return a pointer to the fadc samples of the hi gains
+        // WARNING: Don't forget to get the number of valid entries
+        //          (GetNumSamples) to know how many entries of the array
+        //          belong to the actual pixel
+        //
+        return fHiGainPos;
+    }
+
+    Byte_t  GetNumHiGainSamples() const { return fNumHiGainSamples ; }
+    Byte_t  GetNumLoGainSamples() const { return fNumLoGainSamples ; }
+
+    ULong_t GetSumHiGainSamples() const;
+    ULong_t GetSumSqrHiGainSamples() const;
+    Float_t GetVarHiGainSamples() const;
+
+    Byte_t  GetMaxHiGainSample() const;
+    Byte_t  GetMaxLoGainSample() const;
+    Byte_t  GetIdxMaxHiGainSample() const;
+    Short_t GetIdxMaxLoGainSample(const Byte_t lofirst=0) const;
+    Short_t GetIdxMaxHiLoGainSample() const;
+
+    Bool_t HasLoGain() const;
+    Bool_t IsABFlagValid() const { return fABFlags ? kTRUE : kFALSE; }
+    Bool_t HasABFlag() const
+    {
+        //
+        // return kTRUE  the lo gains exist for the actual pixel, else return kFALSE
+        //
+        return TESTBIT(GetABFlag(), GetPixelId()%8);
+    }
+    Byte_t GetABFlag() const
+    {
+        //
+        // return kTRUE  the lo gains exist for the actual pixel, else return kFALSE
+        //
+        return fABFlags ? fABFlags[GetPixelId()/8] : 0;
+    }
+
+    Byte_t *GetLoGainSamples() const
+    {
+        //
+        // return a pointer to the fadc samples of the lo gains if they exist
+        // for the actual pixel, else return zero
+        //
+        return HasLoGain() ? fLoGainPos : NULL;
+    }
+
+    ULong_t GetSumLoGainSamples() const;
+    ULong_t GetSumSqrLoGainSamples() const;
+
+    void Reset();
+
+    void Draw(Option_t *t="GRAPH");
+
+    ClassDef(MRawEvtPixelIter, 0) // iterates over all pixels of one MRawEvtData object
+};
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawFileRead.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawFileRead.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawFileRead.cc	(revision 9772)
@@ -0,0 +1,418 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MRawFileRead
+//
+//  This tasks reads the raw binary file like specified in the TDAS???
+//  and writes the data in the corresponding containers which are
+//  either retrieved from the parameter list or created and added.
+//
+//  Use SetInterleave() if you don't want to read all events, eg
+//    SetInterleave(5) reads only each 5th event.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MRawRunHeader, MRawEvtHeader, MRawEvtData, MRawCrateArray, MRawEvtTime
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawFileRead.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TSystem.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MParList.h"
+#include "MStatusDisplay.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateData.h"
+#include "MRawCrateArray.h"
+
+ClassImp(MRawFileRead);
+
+using namespace std;
+
+/*  ----------- please don't delete and don't care about (Thomas) ------------
+#define kBUFSZ 64 //1024*1024*64
+#include <iomanip.h>
+class bifstream : public istream, public streambuf
+{
+private:
+    char fBuffer[kBUFSZ]; //!
+    FILE *fd;
+
+    int sync()
+    {
+        memset(fBuffer, 0, kBUFSZ);
+        return 0; 
+    }
+    int underflow()
+    {
+        int sz=fread(fBuffer, kBUFSZ, 1, fd);
+        //int sz=fread(fBuffer, 1, kBUFSZ, fd);
+        setg(fBuffer, fBuffer, fBuffer+kBUFSZ);
+
+        return sz==1 ? *(unsigned char*)fBuffer : EOF;//EOF;
+        //return sz==kBUFSZ ? *(unsigned char*)fBuffer : EOF;//EOF;
+    }
+public:
+    bifstream(const char *name) : istream(this)
+    {
+        fd = fopen(name, "rb");
+        setbuf(fBuffer, kBUFSZ);
+    }
+};
+*/
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file.
+//
+MRawFileRead::MRawFileRead(const char *fname, const char *name, const char *title)
+    : fFileNames(NULL), fNumFile(0), fIn(NULL), fParList(NULL), fInterleave(1)
+{
+    fName  = name  ? name  : "MRead";
+    fTitle = title ? title : "Read task to read DAQ binary files";
+
+    fFileNames = new TList;
+    fFileNames->SetOwner();
+
+    if (fname!=NULL)
+        AddFile(fname);
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream.
+//
+MRawFileRead::~MRawFileRead()
+{
+    delete fFileNames;
+    if (fIn)
+        delete fIn;
+}
+
+Byte_t MRawFileRead::IsFileValid(const char *name)
+{
+    ifstream fin(name);
+    if (!fin)
+        return 0;
+
+    Byte_t c[4];
+    fin.read((char*)c, 4);
+    if (!fin)
+        return 0;
+
+    if (c[0]!=0xc0)
+        return 0;
+
+    if (c[1]==0xc0)
+        return 1;
+
+    if (c[1]==0xc1)
+        return 2;
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new file to a list of files to be processed, Returns the number
+// of files added. (We can enhance this with a existance chack and
+// wildcard support)
+//
+Int_t MRawFileRead::AddFile(const char *fname, Int_t entries)
+{
+    TNamed *name = new TNamed(fname, "");
+    fFileNames->AddLast(name);
+    return 1;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// This opens the next file in the list and deletes its name from the list.
+//
+Int_t MRawFileRead::OpenNextFile(Bool_t print)
+{
+    //
+    // open the input stream and check if it is really open (file exists?)
+    //
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    //
+    // Check for the existance of a next file to read
+    //
+    TObject *file = fFileNames->At(fNumFile);
+    if (!file)
+        return kFALSE;
+
+    //
+    // open the file which is the first one in the chain
+    //
+    const char *name = file->GetName();
+
+    const char *expname = gSystem->ExpandPathName(name);
+    fIn = new ifstream(expname);
+
+    const Bool_t noexist = !(*fIn);
+    if (noexist)
+    {
+        *fLog << err << "Cannot open file " << expname << ": ";
+        *fLog << strerror(errno) << endl;
+    }
+    else
+    {
+        *fLog << inf << "Open file: '" << name << "'" << endl;
+
+        if (fDisplay)
+        {
+            TString txt = GetFileName();
+            txt += " @ ";
+            txt += GetNumExecutions()-1;
+            fDisplay->SetStatusLine2(txt);
+        }
+    }
+
+    delete [] expname;
+
+    if (noexist)
+        return kFALSE;
+
+    fNumFile++;
+
+    //
+    // Read RUN HEADER (see specification) from input stream
+    //
+    if (!fRawRunHeader->ReadEvt(*fIn))
+        return kERROR;
+
+    if (!(*fIn))
+    {
+        *fLog << err << "Error: Accessing file '" << name << "'" << endl;
+        return kERROR;
+    }
+
+    if (!print)
+        return kTRUE;
+
+    //
+    // Print Run Header
+    //
+    fRawRunHeader->Print();
+    *fRawEvtTime = fRawRunHeader->GetRunStart();
+
+    fNumEvents += fRawRunHeader->GetNumEvents();
+
+    fRawRunHeader->SetReadyToSave();
+
+    //
+    // Give the run header information to the 'sub-classes'
+    // Run header must be valid!
+    //
+    fRawEvtHeader->InitRead(fRawRunHeader, fRawEvtTime);
+    fRawEvtData1 ->InitRead(fRawRunHeader);
+    fRawEvtData2 ->InitRead(fRawRunHeader);
+
+    //
+    // Search for MTaskList
+    //
+    MTask *tlist = (MTask*)fParList->FindObject("MTaskList");
+    if (!tlist)
+    {
+        *fLog << err << dbginf << "MTaskList not found... abort." << endl;
+        return kERROR;
+    }
+
+    //
+    // A new file has been opened and new headers have been read.
+    //  --> ReInit tasklist
+    //
+    return tlist->ReInit(fParList) ? kTRUE : kERROR;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return file name of current file.
+//
+TString MRawFileRead::GetFullFileName() const
+{
+    const TObject *file = fFileNames->At(fNumFile-1);
+    return file ? file->GetName() : "";
+}
+
+// --------------------------------------------------------------------------
+//
+// Restart with the first file
+//
+Bool_t MRawFileRead::Rewind()
+{
+    fNumFile=0;
+    fNumEvents=0;
+    return OpenNextFile()==kTRUE;
+}
+
+Bool_t MRawFileRead::CalcNumTotalEvents()
+{
+    fNumTotalEvents = 0;
+
+    Bool_t rc = kTRUE;
+
+    while (1)
+    {
+        switch (OpenNextFile(kFALSE))
+        {
+        case kFALSE:
+            break;
+        case kERROR:
+            rc = kFALSE;
+            break;
+        case kTRUE:
+            fNumTotalEvents += fRawRunHeader->GetNumEvents();
+            continue;
+        }
+        break;
+    }
+
+    if (fIn)
+        delete fIn;
+    fIn = NULL;
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess of this task checks for the following containers in the
+// list:
+//   MRawRunHeader <output>   if not found it is created
+//   MRawEvtHeader <output>   if not found it is created
+//   MRawEvtData <output>     if not found it is created
+//   MRawCrateArray <output>  if not found it is created
+//   MRawEvtTime <output>     if not found it is created (MTime)
+//
+// If all containers are found or created the run header is read from the
+// binary file and printed.  If the Magic-Number (file identification)
+// doesn't match we stop the eventloop.
+//
+// Now the EvtHeader and EvtData containers are initialized.
+//
+Int_t MRawFileRead::PreProcess(MParList *pList)
+{
+    fParList = pList;
+
+    //
+    // open the input stream
+    // first of all check if opening the file in the constructor was
+    // successfull
+    //
+    if (!MRawRead::PreProcess(pList))
+        return kFALSE;
+
+    *fLog << inf << "Calculating number of total events..." << flush;
+    if (!CalcNumTotalEvents())
+        return kFALSE;
+    *fLog << inf << " " << fNumTotalEvents << " found." << endl;
+
+    fNumFile=0;
+    fNumEvents=0;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The Process reads one event from the binary file:
+//  - The event header is read
+//  - the run header is read
+//  - all crate information is read
+//  - the raw data information of one event is read
+//
+Int_t MRawFileRead::Process()
+{
+    while (1)
+    {
+        if (fIn)
+        {
+            //
+            // skip events if requested
+            //
+            if (fInterleave>1 && GetNumExecutions()%fInterleave>0 && fIn->peek()!=EOF)
+            {
+                SkipEvent(*fIn);
+                return kCONTINUE;
+            }
+
+            //
+            // Read a single event from file
+            //
+            const Bool_t rc = ReadEvent(*fIn);
+            if (rc!=kFALSE)
+                return rc;
+        }
+
+        //
+        // If an event could not be read from file try to open new file
+        //
+        const Int_t rc = OpenNextFile();
+        if (rc!=kTRUE)
+            return rc;
+    }
+    return kTRUE; 
+}
+
+// --------------------------------------------------------------------------
+//
+//  Close the file. Check whether the number of read events differs from
+//  the number the file should containe (MRawRunHeader). Prints a warning
+//  if it doesn't match.
+//
+Int_t MRawFileRead::PostProcess()
+{
+    //
+    // Sanity check for the number of events
+    //
+    if (fNumEvents==GetNumExecutions()-1 || GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << warn << dec;
+    *fLog << "Warning - number of read events (" << GetNumExecutions()-1;
+    *fLog << ") doesn't match number in run header(s) (";
+    *fLog << fNumEvents << ")." << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mraw/MRawFileRead.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawFileRead.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawFileRead.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MRawFileRead
+#define MARS_MRawFileRead
+
+#ifndef MARS_MRawRead
+#include "MRawRead.h"
+#endif
+
+class TList;
+class MTaskList;
+
+class MRawFileRead : public MRawRead
+{
+private:
+    TList     *fFileNames;      // list of file names
+    UInt_t     fNumFile;        //! number of next file
+    UInt_t     fNumEvents;      //! input stream (file to read from)
+    UInt_t     fNumTotalEvents; //! total number of events in all files
+
+    ifstream  *fIn;             //! input stream (file to read from)
+
+    MParList  *fParList;        //! tasklist to call ReInit from
+
+    UInt_t     fInterleave;
+
+    Int_t  OpenNextFile(Bool_t print=kTRUE);
+    Bool_t CalcNumTotalEvents();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MRawFileRead(const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+    ~MRawFileRead();
+
+    static Byte_t IsFileValid(const char *name);
+
+    void SetInterleave(UInt_t i) { fInterleave = i; }
+
+    TString GetFullFileName() const;
+
+    Int_t  AddFile(const char *fname, Int_t entries=-1);
+    Bool_t Rewind();
+    UInt_t GetEntries() { return fNumTotalEvents/fInterleave; }
+
+    ClassDef(MRawFileRead, 0)	// Task to read the raw data binary file
+};
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawFileWrite.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawFileWrite.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawFileWrite.cc	(revision 9772)
@@ -0,0 +1,300 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+////////////////////////////////////////////////////////////////////////
+//
+//  MRawFileWrite
+//
+//  Here we write the root containers which contains the data from a
+//  root binary file to a root file. See also MRawFileRead
+//
+//  Input Containers:
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MRawEvtData
+//   MRawEvtData2 [MRawEvtData]
+//   MRawCrateArray
+//   MTime
+//
+//  Output Containers:
+//   -/-
+//
+////////////////////////////////////////////////////////////////////////
+
+#include "MRawFileWrite.h"
+
+#include <TFile.h>
+#include <TTree.h>
+#include <TBranch.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateArray.h"
+
+ClassImp(MRawFileWrite);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It opens the output file (root-file)
+//
+MRawFileWrite::MRawFileWrite(const char *fname,  const Option_t *opt,
+                             const char *ftitle, const Int_t comp,
+                             const char *name, const char *title)
+    : fTData(0), fSplit(kFALSE)
+{
+    fName  = name  ? name  : "MRawFileWrite";
+    fTitle = title ? title : "Write task to write DAQ root files";
+
+    //
+    // Open a rootfile
+    //
+    TString str(fname);
+    if (!str.EndsWith(".root", TString::kIgnoreCase))
+        str += ".root";
+
+    fOut = new TFile(str, opt, ftitle, comp);
+}
+
+MRawFileWrite::~MRawFileWrite()
+{
+    if (fTData)
+    {
+        if (fOut != fTData->GetCurrentFile())
+        {
+            *fLog << warn << endl;
+            *fLog << "WARNING - MWriteRootFile:   Root's  TTree/TFile   has  opened   a  new  file" << endl;
+            *fLog << "  automatically.  You can change this behaviour using TTree::SetMaxTreeSize." << endl;
+            *fLog << "  You won't be able to read splitted  files  correctly with MReadMarsFile if" << endl;
+            *fLog << "  they have more than one entry in 'RunHeaders' or you try to read more than" << endl;
+            *fLog << "  one of such sequences at once." << endl;
+            *fLog << endl;
+        }
+
+        //
+        // For more information see TTree:ChangeFile()
+        //
+        fOut = fTData->GetCurrentFile();
+    }
+
+    //
+    // delete instance, this also does a fOut->Close()
+    //
+    if (fOut->IsOpen())
+        fOut->Write();
+
+    delete fOut;
+
+    //
+    // Remark:
+    // - Trees are automatically deleted by the the file
+    //   (unless file.SetDirectory(0) was called)
+    // - Branches are automatically deleted by the tree destructor
+    //
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess function checks for the following input containers:
+//  - MRawEvtHeader
+//  - MRawEvtData
+//  - MRawCrateArray
+//  - MTime
+//  - MRawRunHeader
+// if a container isn't found the eventloop is stopped.
+//
+// The tree which should containe the run header is created. <RunHeaders>
+// The trees which contains the Events <Events>, <PedEvents>, <CalEvents>
+// are created.
+//
+Int_t MRawFileWrite::PreProcess (MParList *pList)
+{
+    //
+    // test whether file is now open or not
+    //
+    if (!fOut->IsOpen())
+    {
+        *fLog << dbginf << "Error: Cannot open file '" << fOut->GetName() << "'" << endl;
+        return kFALSE;
+    }
+
+    //
+    //  check if MEvtHeader exists in the Parameter list already.
+    //  if not create one and add them to the list
+    //
+    fRawEvtHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+    if (!fRawEvtHeader)
+    {
+        *fLog << err << "MRawEvtHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawEvtData1 = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvtData1)
+    {
+        *fLog << err << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+    fRawEvtData2 = (MRawEvtData*)pList->FindObject("MRawEvtData2", "MRawEvtData");
+    if (!fRawEvtData2)
+    {
+        *fLog << err << "MRawEvtData2 [MRawEvtData] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawCrateArray = (MRawCrateArray*)pList->FindObject("MRawCrateArray");
+    if (!fRawCrateArray)
+    {
+        *fLog << err << "MRawCrateArray not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTime = (MTime*)pList->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRawRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    //
+    // Remark:
+    // - Trees are automatically deleted by the the file
+    //   (unless file.SetDirectory(0) was called)
+    // - Branches are automatically deleted by the tree destructor
+    //
+    fTRunHeader = new TTree("RunHeaders", "Run headers of all runs in this file");
+    fTRunHeader->Branch("MRawRunHeader.", "MRawRunHeader", &fRawRunHeader, 32000);
+
+    //
+    // create data trees for the three types of data
+    //
+    fTData        =          new TTree("Events",      "Normal Triggered Events");
+    fTPedestal    = fSplit ? new TTree("Pedestals",   "Pedestal Triggered Events")    : fTData;
+    fTCalibration = fSplit ? new TTree("Calibration", "Calibration Triggered Events") : fTData;
+
+    //
+    // From the root dicumentation:
+    //
+    // Note that calling TTree::AutoSave too frequently (or similarly calling
+    // TTree::SetAutoSave with a small value) is an expensive operation.
+    // You should make tests for your own application to find a compromize
+    // between speed and the quantity of information you may loose in case of
+    // a job crash.
+    //
+    // In case your program crashes before closing the file holding this tree,
+    // the file will be automatically recovered when you will connect the file
+    // in UPDATE mode.
+    // The Tree will be recovered at the status corresponding to the last AutoSave.
+    //
+    fTData       ->SetAutoSave(2000000000); // 2GB
+    fTPedestal   ->SetAutoSave(2000000000); // 2GB
+    fTCalibration->SetAutoSave(2000000000); // 2GB
+
+    //
+    // create all branches which are necessary
+    //
+    // FIXME: Can we calculate a good buffer size out of the event size?
+    //        using splitlevel=0 sppeds up writing by a factor of 5-10%
+    fTData->Branch("MTime.",          "MTime",          &fTime,          32000);
+    fTData->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTData->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData1,   320000);
+    fTData->Branch("MRawEvtData2.",   "MRawEvtData",    &fRawEvtData2,   320000);
+    fTData->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+    if (!fSplit)
+        return kTRUE;
+
+    fTPedestal   ->Branch("MTime.",          "MTime",          &fTime,          32000);
+    fTCalibration->Branch("MTime.",          "MTime",          &fTime,          32000);
+    fTPedestal   ->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTCalibration->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTPedestal   ->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData1,   320000);
+    fTCalibration->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData1,   320000);
+    fTPedestal   ->Branch("MRawEvtData2.",   "MRawEvtData",    &fRawEvtData2,   320000);
+    fTCalibration->Branch("MRawEvtData2.",   "MRawEvtData",    &fRawEvtData2,   320000);
+    fTPedestal   ->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+    fTCalibration->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the run header information to the file
+//
+Bool_t MRawFileWrite::ReInit(MParList *pList)
+{
+    fTRunHeader->Fill();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets the trigger type from the run header to decide into which tree the
+// event should be filled in and fills  it into this tree.
+//
+Int_t MRawFileWrite::Process()
+{
+    //
+    // get the trigger type of the actual event
+    //
+    const UShort_t type = fRawEvtHeader->GetTrigType();
+
+    //
+    // writa data to the tree. the tree is choosen by the type of the event
+    //
+    switch (type)
+    {
+    case MRawEvtHeader::kTTEvent:
+        fTData->Fill();
+        return kTRUE;
+
+    case MRawEvtHeader::kTTPedestal:
+        fTPedestal->Fill();
+        return kTRUE;
+
+    case MRawEvtHeader::kTTCalibration:
+        fTCalibration->Fill();
+        return kTRUE;
+    }
+
+    *fLog << warn << dbginf << "Got wrong number for the trigger type: " << type;
+    *fLog << " - skipped" << endl;
+
+    return kCONTINUE;
+}
+
Index: /tags/Mars-V0.9/mraw/MRawFileWrite.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawFileWrite.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawFileWrite.h	(revision 9772)
@@ -0,0 +1,53 @@
+#ifndef MARS_MRawFileWrite
+#define MARS_MRawFileWrite
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TFile;
+class TTree;
+
+class MTime;
+class MParList;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MRawCrateArray;
+class MRawEvtData;
+
+class MRawFileWrite : public MTask
+{
+private:
+    MTime          *fTime;
+    MRawRunHeader  *fRawRunHeader;
+    MRawEvtHeader  *fRawEvtHeader;
+    MRawEvtData    *fRawEvtData1;
+    MRawEvtData    *fRawEvtData2;
+    MRawCrateArray *fRawCrateArray;
+
+    TTree *fTData;                  //!
+    TTree *fTPedestal;              //!
+    TTree *fTCalibration;           //!
+
+    TTree *fTRunHeader;             //!
+
+    TFile *fOut;                    //!
+
+    Bool_t fSplit;
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+    MRawFileWrite(const char *fname, const Option_t *opt="RECREATE",
+                  const char *ftitle="Untitled", const Int_t comp=2,
+                  const char *name=NULL, const char *title=NULL);
+    ~MRawFileWrite();
+
+    void EnableSplit(Bool_t b=kTRUE) { fSplit=b; }
+
+    ClassDef(MRawFileWrite, 0)	// Task to write the raw data containers to a root file
+};
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawRead.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawRead.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawRead.cc	(revision 9772)
@@ -0,0 +1,269 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MRawRead
+//
+//  This tasks reads the raw binary file like specified in the TDAS???
+//  and writes the data in the corresponding containers which are
+//  either retrieved from the parameter list or created and added.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:                                                      
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MRawEvtData
+//   MRawEvtData2 [MRawEvtData]
+//   MRawCrateArray
+//   MTime
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawRead.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MParList.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateData.h"
+#include "MRawCrateArray.h"
+
+ClassImp(MRawRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file.
+//
+MRawRead::MRawRead(const char *name, const char *title)
+    : fForceMode(kFALSE)
+{
+    fName  = name  ? name  : "MRawRead";
+    fTitle = title ? title : "Bas class for reading DAQ files";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess of this task checks for the following containers in the
+// list:
+//   MRawRunHeader <output>   if not found it is created
+//   MRawEvtHeader <output>   if not found it is created
+//   MRawEvtData <output>     if not found it is created
+//   MRawCrateArray <output>  if not found it is created
+//   MRawEvtTime <output>     if not found it is created (MTime)
+//
+// If all containers are found or created the run header is read from the
+// binary file and printed.  If the Magic-Number (file identification)
+// doesn't match we stop the eventloop.
+//
+// Now the EvtHeader and EvtData containers are initialized.
+//
+Int_t MRawRead::PreProcess(MParList *pList)
+{
+    if (!OpenStream())
+        return kFALSE;
+
+    //
+    //  check if all necessary containers exist in the Parameter list.
+    //  if not create one and add them to the list
+    //
+    fRawRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
+    if (!fRawRunHeader)
+        return kFALSE;
+
+    fRawEvtHeader = (MRawEvtHeader*)pList->FindCreateObj("MRawEvtHeader");
+    if (!fRawEvtHeader)
+        return kFALSE;
+
+    fRawEvtData1 = (MRawEvtData*)pList->FindCreateObj("MRawEvtData");
+    if (!fRawEvtData1)
+        return kFALSE;
+
+    fRawEvtData2 = (MRawEvtData*)pList->FindCreateObj("MRawEvtData", "MRawEvtData2");
+    if (!fRawEvtData2)
+        return kFALSE;
+
+    fRawCrateArray = (MRawCrateArray*)pList->FindCreateObj("MRawCrateArray");
+    if (!fRawCrateArray)
+        return kFALSE;
+
+    fRawEvtTime = (MTime*)pList->FindCreateObj("MTime");
+    if (!fRawEvtTime)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is a workaround for the oldest runs (file version<3)
+// for which no time stamp was available.
+// For this runs a fake time stamp is created
+//
+// Be carefull: This is NOT thread safe!
+//
+void MRawRead::CreateFakeTime() const
+{
+    static Double_t tm = 0; // Range of roughly 8min
+    const UInt_t ct = (*fRawCrateArray)[0]->GetFADCClockTick();
+
+    tm = ct<tm ? fmod(tm, (UInt_t)(-1))+(UInt_t)(-1)+ct : ct;
+
+    const Double_t mhz = 9.375;                        // [1e6 ticks/s]
+    const Double_t t   = tm/mhz;                       // [us]
+    const UInt_t ns    = (UInt_t)fmod(t*1e3, 1e6);
+    //const UShort_t ms  = (UShort_t)fmod(t/1e3, 1e3);
+    const Byte_t s     = (Byte_t)fmod(t/1e6, 60);
+
+    // Create an artificial time stamp!
+    UInt_t m = (Byte_t)fmod(t/60e6, 60);
+    //const Byte_t h     = (Byte_t)(t/3600e6);
+    m += fRawRunHeader->GetRunNumber()*10;
+    m %= 360; // 6h
+
+    fRawEvtTime->UpdMagicTime(m/60, m%60, s, ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// Read a single event from the stream
+//
+Bool_t MRawRead::ReadEvent(istream &fin)
+{
+    //
+    //  Get file format version
+    //
+    const UShort_t ver = fRawRunHeader->GetFormatVersion();
+
+    //
+    // Read in the next EVENT HEADER (see specification),
+    // if there is no next event anymore stop eventloop
+    //
+    const Int_t rc = fRawEvtHeader->ReadEvt(fin, ver);
+    if (rc==kCONTINUE && fForceMode==kFALSE)
+    {
+        *fLog << err << "Problem found reading the event header... abort." << endl;
+        return kFALSE;
+    }
+
+    //
+    //  Get number of crates from the run header
+    //
+    const UShort_t nc = fRawRunHeader->GetNumCrates();
+
+    //
+    // Delete arrays which stores the pixel information (time slices)
+    //
+    fRawEvtData1->ResetPixels(fRawRunHeader->GetNumNormalPixels(),  fRawRunHeader->GetMaxPixId());
+    fRawEvtData2->ResetPixels(fRawRunHeader->GetNumSpecialPixels(), fRawRunHeader->GetMinPixId());
+
+    //
+    // clear the TClonesArray which stores the Crate Information
+    // and create a new array of the correct size
+    //
+    fRawCrateArray->SetSize(nc);
+
+    //
+    // Calculate the number of byte to be skipped in a file if a pixel is not connected
+    //
+    const UShort_t nskip = fRawRunHeader->GetNumSamplesLoGain()+fRawRunHeader->GetNumSamplesHiGain();
+
+    //
+    // read the CRATE DATA (see specification) from file
+    //
+    Int_t posinarray=0;
+    for (int i=0; i<nc; i++)
+    {
+        fRawCrateArray->GetEntry(i)->ReadEvt(fin, ver);
+        if (!fin)
+            return kFALSE;
+
+        //fRawEvtData1->ReadEvt(fin, posinarray++);
+
+        const UShort_t npic = fRawRunHeader->GetNumPixInCrate();
+        const Byte_t   ab   = fRawCrateArray->GetEntry(posinarray)->GetABFlags();
+        for (int j=0; j<npic; j++)
+        {
+            // calc the spiral hardware pixel number
+             const UShort_t ipos = posinarray*npic+j;
+
+            // Get Hardware Id
+            const Short_t hwid = fRawRunHeader->GetPixAssignment(ipos);
+
+            // Check whether the pixel is connected or not
+            if (hwid==0)
+            {
+                fin.seekg(nskip, ios::cur);
+                continue;
+            }
+
+            // -1 converts the hardware pixel Id into the software pixel index
+            if (hwid>0)
+                fRawEvtData1->ReadPixel(fin,   hwid-1,  TESTBIT(ab, j));
+            else
+                fRawEvtData2->ReadPixel(fin, -(hwid+1), TESTBIT(ab, j));
+
+        }
+        if (!fin)
+            return kFALSE;
+
+        posinarray++;
+    }
+
+    // This is a workaround for the oldest runs (version<3)
+    // for which no time stamp was available.
+    // For this runs a fake time stamp is created
+    if (ver<3)
+        CreateFakeTime();
+
+    if (rc==kCONTINUE && fForceMode==kTRUE)
+        return kCONTINUE;
+
+    return kTRUE;
+}
+
+void MRawRead::SkipEvent(istream &fin)
+{
+    //
+    //  Get file format version
+    //
+    const UShort_t ver = fRawRunHeader->GetFormatVersion();
+    fRawEvtHeader->SkipEvt(fin, ver);
+
+    const UShort_t nc = fRawRunHeader->GetNumCrates();
+    for (int i=0; i<nc; i++)
+    {
+        fRawCrateArray->GetEntry(i)->SkipEvt(fin, ver);
+        fRawEvtData1->SkipEvt(fin);
+    }
+}
Index: /tags/Mars-V0.9/mraw/MRawRead.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawRead.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawRead.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MRawRead
+#define MARS_MRawRead
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MTime;
+class MParList;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MRawEvtData;
+class MRawCrateArray;
+
+class MRawRead : public MRead
+{
+protected:
+    MRawRunHeader  *fRawRunHeader;  // run header information container to fill from file
+    MRawEvtHeader  *fRawEvtHeader;  // event header information container to fill from file
+    MRawEvtData    *fRawEvtData1;   // raw evt data infomation container to fill from file
+    MRawEvtData    *fRawEvtData2;   // raw evt data for pixels with negative indices
+    MRawCrateArray *fRawCrateArray; // crate information array container to fill from file
+    MTime          *fRawEvtTime;    // raw evt time information container to fill from file
+
+    Bool_t          fForceMode;     // Force mode skipping defect events
+
+    void CreateFakeTime() const;
+
+    Bool_t ReadEvent(istream &fin);
+    void   SkipEvent(istream &fin);
+    Int_t  PreProcess(MParList *pList);
+
+private:
+    virtual Bool_t OpenStream() { return kTRUE; }
+
+public:
+    MRawRead(const char *name=NULL, const char *title=NULL);
+
+    UInt_t GetEntries() { return 0; }
+    Bool_t Rewind() {return kTRUE; }
+
+    void SetForceMode(Bool_t b=kTRUE) { fForceMode = b; }
+
+    ClassDef(MRawRead, 0)	// Task to read the raw data binary file
+};
+
+#endif
Index: /tags/Mars-V0.9/mraw/MRawRunHeader.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawRunHeader.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawRunHeader.cc	(revision 9772)
@@ -0,0 +1,389 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRawRunHeader
+//
+// Root storage container for the RUN HEADER information
+//
+//
+//  RAW DATA FORMAT VERSION
+//  =======================
+//
+//  Format Version 5:
+//  -----------------
+//   - now the sub millisecond information of the time is valid and decoded
+//     which enhances the precision from 51.2us to 200ns
+//
+//  Format Version 4:
+//  -----------------
+//   - added support for pixels with negative IDs
+//
+//  Format Version 3:
+//  -----------------
+//   - ???
+//
+//  Format Version 2:
+//  -----------------
+//   - removed mjd from data
+//   - added start time
+//   - added stop  time
+//
+//
+//  MRawRunHeader CLASS VERSION
+//  ===========================
+//
+//  Class Version 2:
+//  ----------------
+//   - removed fMJD, fYear, fMonth, fDay
+//   - added fRunStart
+//   - added fRunStop
+// 
+//  Class Version 1:
+//  ----------------
+//   - first implementation
+//
+////////////////////////////////////////////////////////////////////////////
+
+#include "MRawRunHeader.h"
+
+#include <fstream>
+#include <iomanip>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayS.h"
+
+ClassImp(MRawRunHeader);
+
+using namespace std;
+
+const UShort_t MRawRunHeader::kMagicNumber      = 0xc0c0;
+const Byte_t   MRawRunHeader::kMaxFormatVersion =      5;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates array which stores the pixel assignment.
+//
+//
+MRawRunHeader::MRawRunHeader(const char *name, const char *title) : fPixAssignment(NULL)
+{
+    fName  = name  ? name  : "MRawRunHeader";
+    fTitle = title ? title : "Raw Run Header Information";
+
+    fPixAssignment = new MArrayS(0);
+
+    fFormatVersion=0;
+    fSoftVersion=0;
+    fRunType=kRTNone;  // use 0xffff for invalidation, 0 means: Data run
+    fRunNumber=0;
+    fProjectName[0]=0;
+    fSourceName[0]=0;
+    fSourceEpochChar[0]=0;
+    fSourceEpochDate=0;
+    fNumCrates=0;
+    fNumPixInCrate=0;
+    fNumSamplesLoGain=0;
+    fNumSamplesHiGain=0;
+    fNumEvents=0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes the 'pixel-assignment-array'
+//
+MRawRunHeader::~MRawRunHeader()
+{
+    delete fPixAssignment;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read in one run header from the binary file
+//
+Bool_t MRawRunHeader::ReadEvt(istream& fin)
+{
+    //
+    // read one RUN HEADER from the input stream
+    //
+    fMagicNumber = 0;
+
+    fin.read((char*)&fMagicNumber, 2);          // Total=2
+
+    //
+    // check whether the the file has the right file type or not
+    //
+    if (fMagicNumber != kMagicNumber && fMagicNumber != kMagicNumber+1)
+    {
+        *fLog << err << "ERROR - Wrong Magic Number (0x" << hex << fMagicNumber << "): Not a Magic File!" << endl;
+        return kFALSE;
+    }
+
+    if (fMagicNumber == kMagicNumber+1)
+        *fLog << warn << "WARNING - This file maybe broken (0xc0c1) - DAQ didn't close it correctly!" << endl;
+
+    Byte_t dummy[16];
+
+    fin.read((char*)&fFormatVersion,    2);     // Total=4
+    if (fFormatVersion>kMaxFormatVersion)
+    {
+        *fLog << err << "ERROR - File vormat V" << fFormatVersion << " not implemented!" << endl;
+        return kFALSE;
+    }
+
+    fin.read((char*)&fSoftVersion,      2);     // Total=6
+    fin.read((char*)&fRunType,          2);     // Total=8
+    fin.read((char*)&fRunNumber,        4);     // Total=12
+    fin.read((char*)&fProjectName,     22);     // Total=34
+    fin.read((char*)&fSourceName,      12);     // Total=46
+    fin.read((char*)dummy,              4); // was RA  (moved to tracking system)
+    fin.read((char*)dummy,              4); // was DEC (moved to tracking system)
+    fin.read((char*)&fSourceEpochChar,  2);     // Total=56
+    fin.read((char*)&fSourceEpochDate,  2);     // Total=58
+    if (fFormatVersion<2)                       // Total += 10
+    {
+        UShort_t y, m, d;
+        fin.read((char*)dummy, 4); // Former fMJD[4],
+        fin.read((char*)&y,    2); // Former fDateYear[2]
+        fin.read((char*)&m,    2); // Former fDateMonth[2]
+        fin.read((char*)&d,    2); // Former fDateDay[2]
+        fRunStart.Set(y, m, d, 0, 0, 0, 0);
+    }
+    fin.read((char*)&fNumCrates,        2);     // Total=60
+    fin.read((char*)&fNumPixInCrate,    2);     // Total=62
+    fin.read((char*)&fNumSamplesLoGain, 2);     // Total=64
+    fin.read((char*)&fNumSamplesHiGain, 2);     // Total=66
+    fin.read((char*)&fNumEvents,        4);     // Total=70
+    if (fFormatVersion>1)
+    {
+        fRunStart.ReadBinary(fin);              // Total += 7
+        fRunStop.ReadBinary(fin);               // Total += 7
+    }
+
+    //
+    // calculate size of array, create it and fill it
+    //
+    Int_t nPixel = fNumCrates*fNumPixInCrate;
+    fPixAssignment->Set(nPixel);
+
+    fin.read((char*)fPixAssignment->GetArray(), nPixel*2);
+    fin.read((char*)&dummy, 16);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the run type as string ("Data", "Pedestal", ...), for example
+// to print it as readable text.
+//
+const char *MRawRunHeader::GetRunTypeStr() const
+{
+    switch (fRunType)
+    {
+    case kRTData:
+        return "Data";
+    case kRTPedestal:
+        return "Pedestal";
+    case kRTCalibration:
+        return "Calibration";
+    case kRTPointRun:
+        return "Point-Run";
+    case kRTMonteCarlo:
+        return "Monte Carlo";
+    case kRTNone:
+        return "<none>";
+    default:
+        return "<unknown>";
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// print run header information on *fLog. The option 'header' supresses
+// the pixel index translation table.
+//
+void MRawRunHeader::Print(Option_t *t) const
+{
+    *fLog << all << endl;
+    *fLog << "MagicNumber:  0x" << hex << fMagicNumber << " - ";
+    switch (fMagicNumber)
+    {
+    case kMagicNumber:   *fLog << "OK";               break;
+    case kMagicNumber+1: *fLog << "File not closed!"; break;
+    default:             *fLog << "Wrong!";           break;
+    }
+    *fLog << endl;
+    *fLog << "Version:      " << dec << "Format=" << fFormatVersion << "  ";
+    *fLog << "Software=" << fSoftVersion << endl;
+    *fLog << "RunNumber:    " << fRunNumber << " (Type=" << GetRunTypeStr() << ")" << endl;
+    *fLog << "ProjectName: '" << fProjectName << "'" << endl;
+    *fLog << "Source:      '" << fSourceName << "' " << "  ";
+    *fLog << fSourceEpochChar << dec << fSourceEpochDate << endl;
+    *fLog << "Run Start:    " << fRunStart << endl;
+    *fLog << "Run Stop:     " << fRunStop << endl;
+    *fLog << "Crates:       " << fNumCrates << " x " << fNumPixInCrate << " Pixel/Crate = " << fNumCrates*fNumPixInCrate << " Pixel/Evt" << endl;
+    *fLog << "Num Pixels:   " << GetNumNormalPixels() << " (normal) + " << GetNumSpecialPixels() << " (special) = " << GetNumConnectedPixels() << " (total)" << endl;
+    *fLog << "Samples:      " << fNumSamplesHiGain << "/" << fNumSamplesLoGain << " (hi/lo) = " << (fNumSamplesLoGain+fNumSamplesHiGain) * fNumCrates * fNumPixInCrate /1024 << "kB/Evt" << endl;
+    *fLog << "Evt Counter:  " << fNumEvents << endl;
+
+    if (TString(t).Contains("header", TString::kIgnoreCase))
+        return;
+
+    *fLog << inf << hex;
+    for (int i=0; i<GetNumPixel(); i++)
+        *fLog << setfill('0') << setw(3) << (*fPixAssignment)[i] << " ";
+
+    *fLog << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the assigned pixel number for the given FADC channel
+//
+Short_t MRawRunHeader::GetPixAssignment(UShort_t i) const
+{
+    // FIXME: Do we need a range check here?
+    return (Short_t)(*fPixAssignment)[i];
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of pixel which are markes as connected in the
+// pix assignment (!=0)
+//
+UShort_t MRawRunHeader::GetNumConnectedPixels() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    UShort_t rc = 0;
+    for (int i=0; i<num; i++)
+    {
+        if (GetPixAssignment(i)!=0)
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of pixel which are markes as connected and so-called
+// 'normal' pixels in the pix assignment (>0)
+//
+UShort_t MRawRunHeader::GetNumNormalPixels() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    UShort_t rc = 0;
+    for (int i=0; i<num; i++)
+    {
+        if (GetPixAssignment(i)>0)
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of pixel which are markes as connected and so-called
+// 'special' pixels in the pix assignment (<0)
+//
+UShort_t MRawRunHeader::GetNumSpecialPixels() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    UShort_t rc = 0;
+    for (int i=0; i<num; i++)
+    {
+        if (GetPixAssignment(i)<0)
+            rc++;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the maximum id which exists in the pix assignment
+//
+UShort_t MRawRunHeader::GetMaxPixId() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    Short_t rc = 0;
+    for (int i=0; i<num; i++)
+        rc = TMath::Max(GetPixAssignment(i), rc);
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return minus th minimum id which exists in the pix assignment
+//
+UShort_t MRawRunHeader::GetMinPixId() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    Short_t rc = 0;
+    for (int i=0; i<num; i++)
+        rc = TMath::Min(GetPixAssignment(i), rc);
+
+    return (UShort_t)-rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the number of pixel in this event.
+//
+// WARNING: This is the number of pixels stored in this file which is
+//          a multiple of the number of pixels per crate and in general
+//          a number which is larger than the camera size!
+//
+//          To know the range of the pixel indices please use the geometry
+//          container!
+//
+UShort_t MRawRunHeader::GetNumPixel() const
+{
+    return fPixAssignment->GetSize();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns absolute size in bytes of the run header as read from a raw file.
+// This must be done _after_ the header is read, because the header doesn't
+// have a fixed size (used in MRawSocketRead)
+//
+Int_t MRawRunHeader::GetNumTotalBytes() const
+{
+    switch (fFormatVersion)
+    {
+    case 1:
+        return 80+fNumCrates*fNumPixInCrate*2+16;
+    case 2:
+        return 84+fNumCrates*fNumPixInCrate*2+16;
+    }
+    return 0;
+}
Index: /tags/Mars-V0.9/mraw/MRawRunHeader.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawRunHeader.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawRunHeader.h	(revision 9772)
@@ -0,0 +1,120 @@
+#ifndef MARS_MRawRunHeader
+#define MARS_MRawRunHeader
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MRunHeader                                                        //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class TBuffer;
+class MArrayS;
+
+class MRawRunHeader : public MParContainer
+{
+public:
+    //
+    // enum for the Run Type. Monte Carlo Runs have
+    // to have a value greater than 255 (>0xff)
+    //
+    enum {
+        kRTData        = 0x0000,
+        kRTPedestal    = 0x0001,
+        kRTCalibration = 0x0002,
+        kRTPointRun    = 0x0007,
+        kRTMonteCarlo  = 0x0100,
+        kRTNone        = 0xffff
+    };
+
+    //
+    // Magic number to detect the magic file type
+    //
+    static const UShort_t kMagicNumber;
+    static const Byte_t   kMaxFormatVersion;
+
+private:
+    /* ---- Run Header Informations ---- */
+    UShort_t  fMagicNumber;
+    UShort_t  fFormatVersion;
+    UShort_t  fSoftVersion;
+    UShort_t  fRunType;
+    UInt_t    fRunNumber;
+    Char_t    fProjectName[22];
+    Char_t    fSourceName[12];
+    Char_t    fSourceEpochChar[2];
+    UShort_t  fSourceEpochDate;
+    UShort_t  fNumCrates;
+    UShort_t  fNumPixInCrate;
+    UShort_t  fNumSamplesLoGain;
+    UShort_t  fNumSamplesHiGain;
+    UInt_t    fNumEvents;
+    MTime     fRunStart;
+    MTime     fRunStop;
+    MArrayS  *fPixAssignment;
+
+public:
+    MRawRunHeader(const char *name=NULL, const char *title=NULL);
+    ~MRawRunHeader();
+
+    // This is to be used in the MC chain only!
+    void SetMagicNumber(UShort_t a)       { fMagicNumber=a; }
+    void SetFormatVersion(UShort_t a)     { fFormatVersion=a; }
+    void SetSoftVersion(UShort_t a)       { fSoftVersion=a; }
+    void SetRunType(UShort_t a)           { fRunType=a; }
+    void SetRunNumber(UInt_t a)           { fRunNumber=a; }
+    void SetNumEvents(UInt_t a)           { fNumEvents=a; }
+    void SetNumSamples(UShort_t low, UShort_t high)
+    {
+        fNumSamplesLoGain=low;
+        fNumSamplesHiGain=high;
+    }
+    void SetNumCrates(UShort_t a)         { fNumCrates=a; }
+    void SetNumPixInCrate(UShort_t a)     { fNumPixInCrate=a; }
+    void SetRunTime(Float_t start, Float_t stop)
+    { fRunStart.SetMjd(start); fRunStop.SetMjd(stop); }
+
+    // This is to get the numbers...
+    UShort_t GetMagicNumber() const       { return fMagicNumber; }
+    UShort_t GetFormatVersion() const     { return fFormatVersion; }
+    UShort_t GetSoftVersion() const       { return fSoftVersion; }
+    UInt_t   GetRunNumber() const         { return fRunNumber; }
+    UShort_t GetRunType() const           { return fRunType; }
+    const Char_t *GetRunTypeStr() const;
+    const Char_t *GetProjectName() const { return fProjectName; }
+    const Char_t *GetSourceName() const  { return fSourceName; }
+    const Char_t *GetSourceEpocheChar() const { return fSourceEpochChar; }
+    UShort_t GetSourceEpocheDate() const  { return fSourceEpochDate; }
+    UShort_t GetNumCrates() const         { return fNumCrates; }
+    UShort_t GetNumPixInCrate() const     { return fNumPixInCrate; }
+    UShort_t GetNumSamplesLoGain() const  { return fNumSamplesLoGain; }
+    UShort_t GetNumSamplesHiGain() const  { return fNumSamplesHiGain; }
+    UInt_t   GetNumEvents() const         { return fNumEvents; }
+    const MTime &GetRunStart() const      { return fRunStart; }
+    const MTime &GetRunEnd() const        { return fRunStop; }
+    Short_t GetPixAssignment(UShort_t i) const;
+    UShort_t GetMaxPixId() const;
+    UShort_t GetMinPixId() const;
+    UShort_t GetNumConnectedPixels() const;
+    UShort_t GetNumNormalPixels() const;
+    UShort_t GetNumSpecialPixels() const;
+
+    UInt_t GetNumSamplesPerCrate() const
+    {
+        return fNumPixInCrate*(fNumSamplesLoGain+fNumSamplesHiGain);
+    }
+
+    UShort_t GetNumPixel() const;
+    Int_t GetNumTotalBytes() const;
+
+    Bool_t IsMonteCarloRun() const { return fRunType>0x00ff; }
+
+    void Print(Option_t *t=NULL) const;
+
+    Bool_t ReadEvt(istream& fin);
+
+    ClassDef(MRawRunHeader, 2)	// storage container for general info
+};
+#endif
Index: /tags/Mars-V0.9/mraw/MRawSocketRead.cc
===================================================================
--- /tags/Mars-V0.9/mraw/MRawSocketRead.cc	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawSocketRead.cc	(revision 9772)
@@ -0,0 +1,293 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MRawSocketRead
+//
+//  This tasks reads the raw binary file like specified in the TDAS???
+//  and writes the data in the corresponding containers which are
+//  either retrieved from the parameter list or created and added.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   MRawRunHeader
+//   MRawEvtHeader
+//   MRawEvtData
+//   MRawCrateArray
+//   MTime
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawSocketRead.h"
+
+#include <stdlib.h>  // atoi
+
+#include <TArrayC.h> // TAraayC
+
+#include "MReadSocket.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MTime.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateData.h"
+#include "MRawCrateArray.h"
+
+#include "MStatusDisplay.h"
+
+ClassImp(MRawSocketRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file.
+//
+MRawSocketRead::MRawSocketRead(const char *name, const char *title)
+    : fIn(NULL), fPort(-1)
+{
+    fName  = name  ? name  : "MRawSocketRead";
+    fTitle = title ? title : "Task to read DAQ binary data from tcp/ip socket";
+
+    fIn = new MReadSocket;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream.
+//
+MRawSocketRead::~MRawSocketRead()
+{
+    delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// Open the socket. This blocks until the connection has been established,
+// an error occured opening the connection or the user requested to
+// quit the application.
+//
+Bool_t MRawSocketRead::OpenSocket()
+{
+    if (fDisplay)
+        fDisplay->SetStatusLine2(Form("Waiting for connection on port #%d...", fPort));
+
+    //
+    // Open socket connection
+    //
+    while (1)
+    {
+        //
+        // If port could be opened eveything is ok
+        //
+        if (fIn->Open(fPort))
+            return kTRUE;
+
+        //
+        // If a MStatusDisplay is attached the user might have
+        // requested to quit the application
+        //
+        if (fDisplay)
+            switch (fDisplay->CheckStatus())
+            {
+            case MStatusDisplay::kFileClose:
+            case MStatusDisplay::kFileExit:
+                *fLog << inf << "MRawSocketRead::PreProcess - MStatusDisplay triggered exit." << endl;
+                return kFALSE;
+            default:
+                break;
+            }
+
+        //
+        // If an error occured during opening the socket stop
+        //
+        if (fIn->fail())
+            break;
+    }
+
+    *fLog << err << "ERROR - Cannot open port #" << fPort << endl;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess of this task checks for the following containers in the
+// list:
+//   MRawRunHeader <output>   if not found it is created
+//   MRawEvtHeader <output>   if not found it is created
+//   MRawEvtData <output>     if not found it is created
+//   MRawCrateArray <output>  if not found it is created
+//   MTime <output>           if not found it is created
+//
+// If all containers are found or created the run header is read from the
+// binary file and printed.  If the Magic-Number (file identification)
+// doesn't match we stop the eventloop.
+//
+// Now the EvtHeader and EvtData containers are initialized.
+//
+Int_t MRawSocketRead::PreProcess(MParList *pList)
+{
+    if (!OpenSocket())
+        return kFALSE;
+
+    if (!MRawRead::PreProcess(pList))
+        return kFALSE;
+
+    fParList = pList;
+    fRunNumber = (UInt_t)-1;
+    fEvtNumber = (UInt_t)-1;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The Process reads one event from the binary file:
+//  - The event header is read
+//  - the run header is read
+//  - all crate information is read
+//  - the raw data information of one event is read
+//
+Int_t MRawSocketRead::Process()
+{
+    //
+    // Tag which could possibly be used for synchronizing the
+    // data stream. At the moment we check only its correctness.
+    // Synchronisation seems to work well - Why?
+    //
+    char dummy[4];
+    fIn->read(dummy, 4);   // \nEVT
+
+    if (!(dummy[0]=='\n' && dummy[1]=='E' && dummy[2]=='V' &&dummy[3]=='T'))
+    {
+        *fLog << warn << "EVT tag not found. Stream out of sync. Please try to restart..." << endl;
+        // FIXME: Synchronization missing...
+        return kFALSE;
+    }
+
+    //
+    // No we get some size information (each 5 bytes ascii)
+    //
+    char sizecc[6] = {0,0,0,0,0,0}; // 5 bytes plus trailing 0-byte
+    char sizerh[6] = {0,0,0,0,0,0}; // 5 bytes plus trailing 0-byte
+    char sizeev[6] = {0,0,0,0,0,0}; // 5 bytes plus trailing 0-byte
+    fIn->read(sizecc, 5); // Size CC info string
+    fIn->read(sizerh, 5); // Size run header
+    fIn->read(sizeev, 5); // Size Event (+ event header)
+
+    //
+    // Currently we skip the CC info string. We may decode this string
+    // in the future to get additional information
+    //
+    TArrayC dummy2(atoi(sizecc));
+    fIn->read(dummy2.GetArray(), dummy2.GetSize());
+
+    //
+    // Read RUN HEADER (see specification) from input stream
+    //
+    fLog->SetNullOutput();
+    const Bool_t rc = fRawRunHeader->ReadEvt(*fIn);
+    fLog->SetNullOutput(kFALSE);
+
+    if (!rc)
+    {
+        *fLog << err << "Reading MRawRunHeader failed." << endl;
+        return kFALSE;
+    }
+
+    if (fRunNumber!=fRawRunHeader->GetRunNumber())
+    {
+        fRawRunHeader->Print();
+
+        MTaskList *tlist = (MTaskList*)fParList->FindObject("MTaskList");
+        if (!tlist)
+        {
+            *fLog << err << dbginf << "ERROR - Task List not found in Parameter List." << endl;
+            return kFALSE;
+        }
+
+        if (!tlist->ReInit())
+            return kFALSE;
+
+        fRunNumber = fRawRunHeader->GetRunNumber();
+    }
+
+    if (atoi(sizerh)==fRawRunHeader->GetNumTotalBytes())
+    {
+        *fLog << err << "Retrieved size of run header mismatch... stopped." << endl;
+        return kFALSE;
+    }
+
+    if (atoi(sizeev)==0)
+    {
+        *fLog << dbg << "Event contains only run header information... skipped." << endl;
+        return kCONTINUE;
+    }
+
+    *fRawEvtTime = fRawRunHeader->GetRunStart();
+
+    //
+    // Give the run header information to the 'sub-classes'
+    // Run header must be valid!
+    //
+    fRawEvtHeader->InitRead(fRawRunHeader, fRawEvtTime);
+    fRawEvtData1 ->InitRead(fRawRunHeader);
+    fRawEvtData2 ->InitRead(fRawRunHeader);
+
+    if (!ReadEvent(*fIn))
+        return kFALSE;
+
+    //
+    // If no new event was recorded the DAQ resends an old event
+    //
+    if (fEvtNumber==fRawEvtHeader->GetDAQEvtNumber())
+    {
+        *fLog << dbg << "Event number #" << dec << fEvtNumber << " didn't change... skipped." << endl;
+        return kCONTINUE;
+    }
+
+    fEvtNumber=fRawEvtHeader->GetDAQEvtNumber();
+
+    return kTRUE;
+}
+
+Int_t MRawSocketRead::PostProcess()
+{
+    //
+    // Close Socket connection
+    //
+    fIn->Close();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mraw/MRawSocketRead.h
===================================================================
--- /tags/Mars-V0.9/mraw/MRawSocketRead.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/MRawSocketRead.h	(revision 9772)
@@ -0,0 +1,38 @@
+#ifndef MARS_MRawSocketRead
+#define MARS_MRawSocketRead
+
+#ifndef MARS_MRawRead
+#include "MRawRead.h"
+#endif
+
+class MReadSocket;
+
+class MRawSocketRead : public MRawRead
+{
+private:
+    MReadSocket *fIn;         //! buffered input stream (file to read from)
+    MParList    *fParList;    //!
+
+    UInt_t       fRunNumber;  //!
+    UInt_t       fEvtNumber;  //!
+
+    Int_t        fPort;       // Port on which we wait for the connection
+
+    Bool_t OpenSocket();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MRawSocketRead(const char *name=NULL, const char *title=NULL);
+    ~MRawSocketRead();
+
+    void SetPort(int port) { fPort = port; }
+
+    TString GetFullFileName() const { return "<socket>"; }
+
+    ClassDef(MRawSocketRead, 0)	//Task to read DAQ binary data from tcp/ip socket
+};
+
+#endif
Index: /tags/Mars-V0.9/mraw/Makefile
===================================================================
--- /tags/Mars-V0.9/mraw/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mraw/Makefile	(revision 9772)
@@ -0,0 +1,41 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Raw
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../MBase -I../mfileio -I../mcalib
+# mgui (MCamEvent), mgeom(MGeomCam)
+
+SRCFILES = MRawRunHeader.cc \
+	   MRawEvtHeader.cc \
+	   MRawEvtData.cc \
+	   MRawEvtPixelIter.cc \
+	   MRawCrateArray.cc \
+	   MRawCrateData.cc \
+           MRawRead.cc \
+           MRawFileWrite.cc \
+           MRawFileRead.cc \
+           MRawSocketRead.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mraw/RawIncl.h
===================================================================
--- /tags/Mars-V0.9/mraw/RawIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/RawIncl.h	(revision 9772)
@@ -0,0 +1,7 @@
+#ifndef __CINT__
+
+#include <TArrayC.h>
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mraw/RawLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mraw/RawLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mraw/RawLinkDef.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MRawRunHeader+;
+
+#pragma link C++ class MRawEvtHeader+;
+#pragma link C++ class MRawEvtData+;
+#pragma link C++ class MRawEvtPixelIter+;
+
+#pragma link C++ class MRawCrateArray+;
+#pragma link C++ class MRawCrateData+;
+
+#pragma link C++ class MRawRead+;
+#pragma link C++ class MRawSocketRead+;
+#pragma link C++ class MRawFileRead+;
+#pragma link C++ class MRawFileWrite+;
+
+#endif
Index: /tags/Mars-V0.9/mreflector/MRflEvtData.cc
===================================================================
--- /tags/Mars-V0.9/mreflector/MRflEvtData.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/MRflEvtData.cc	(revision 9772)
@@ -0,0 +1,159 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRflEvtData
+//
+// All Photons of a event from the reflector program
+//
+// Should be filled like this:
+//   MRflEvtData evt;
+//   evt.Reset();
+//   for (int i=0; i<10; i++)
+//      MRflSinglePhoton &ph = evt.GetNewPhoton();
+//   evt.FixSize();
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRflEvtData.h"
+
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHexagon.h"
+#include "MGeomCam.h"
+
+#include "MRflSinglePhoton.h"
+
+ClassImp(MRflEvtData);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MCerPhotPix object for each pixel in the event
+//
+MRflEvtData::MRflEvtData(const char *name, const char *title)
+   : fList("MRflSinglePhoton", 0), fPos(0)
+{
+    fName  = name  ? name  : "MRflEvtData";
+    fTitle = title ? title : "All Photons from a reflector event";
+}
+
+const MRflSinglePhoton &MRflEvtData::GetPhoton(Int_t i) const
+{
+    return *static_cast<MRflSinglePhoton*>(fList.UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Dump informations off all photons
+//
+void MRflEvtData::Print(Option_t *o) const
+{
+    *fLog << all << underline << GetDescriptor() << ":" << endl;
+    fList.Print();
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new photon to the list
+//
+MRflSinglePhoton &MRflEvtData::GetNewPhoton()
+{
+    // If necessary the []-operator creates a new element
+    // Warning: The virtual table may not be set correctly,
+    //          this is why you have to call the new-operator.
+    return *new (fList[fPos++]) MRflSinglePhoton;
+}
+
+// --------------------------------------------------------------------------
+//
+// If you have added all photon fix the size of the container.
+//
+void MRflEvtData::FixSize()
+{
+    if (fList.GetEntriesFast() == fPos)
+        return;
+
+    fList.ExpandCreate(fPos);
+}
+
+void MRflEvtData::DrawPixelContent(Int_t num) const
+{
+}
+
+// ------------------------------------------------------------------------
+//
+// Fill a reflector event. Sums all pixels in each pixel as the
+// pixel contents.
+//
+// WARNING: Due to the estimation in DistanceToPrimitive and the
+//          calculation in pixels instead of x, y this is only a
+//          rough estimate.
+//
+Bool_t MRflEvtData::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    //
+    // sum the photons content in each pixel
+    //
+    val = 0;
+
+    MHexagon hex(cam[idx]);
+
+    MRflSinglePhoton *ph=NULL;
+
+    TIter Next(&fList);
+    while ((ph=(MRflSinglePhoton*)Next()))
+        if (hex.DistanceToPrimitive(ph->GetX(), ph->GetY())<=0)
+            val += cam.GetPixRatio(idx);
+
+    return val>0;
+}
+
+// ------------------------------------------------------------------------
+//
+// You can call Draw() to add the photons to the current pad.
+// The photons are painted each tim ethe pad is updated.
+// Make sure that you use the right (world) coordinate system,
+// like created, eg. by the MHCamera histogram.
+//
+void MRflEvtData::Paint(Option_t *)
+{
+    MRflSinglePhoton *ph=NULL;
+
+    TMarker m;
+    m.SetMarkerStyle(kFullDotMedium); // Gtypes.h
+
+    TIter Next(&fList);
+    while ((ph=(MRflSinglePhoton*)Next()))
+    {
+        m.SetX(ph->GetX());
+        m.SetY(ph->GetY());
+        m.Paint();
+    }
+}
+
Index: /tags/Mars-V0.9/mreflector/MRflEvtData.h
===================================================================
--- /tags/Mars-V0.9/mreflector/MRflEvtData.h	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/MRflEvtData.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MRflEvtData
+#define MARS_MRflEvtData
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class MRflSinglePhoton;
+
+class MRflEvtData : public MParContainer, public MCamEvent
+{
+    TClonesArray fList;
+    Int_t fPos;
+
+public:
+    MRflEvtData(const char *name=NULL, const char *title=NULL);
+
+    void Reset() { fPos = 0; }
+
+    Int_t GetNumPhotons() const { return fList.GetEntriesFast(); }
+
+    MRflSinglePhoton &GetNewPhoton();
+    void FixSize();
+
+    const MRflSinglePhoton &GetPhoton(Int_t i) const;
+
+    void Print(Option_t *o="") const;
+    void Paint(Option_t *o="");
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void   DrawPixelContent(Int_t num) const;
+
+    ClassDef(MRflEvtData, 0) // All Photons of a event from the reflector program
+};
+
+#endif
Index: /tags/Mars-V0.9/mreflector/MRflEvtHeader.cc
===================================================================
--- /tags/Mars-V0.9/mreflector/MRflEvtHeader.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/MRflEvtHeader.cc	(revision 9772)
@@ -0,0 +1,41 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRflEvtHeader
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRflEvtHeader.h"
+
+ClassImp(MRflEvtHeader);
+
+// --------------------------------------------------------------------------
+//
+MRflEvtHeader::MRflEvtHeader(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MRflEvtHeader";
+    fTitle = title ? title : "Event header information from a reflector event";
+}
+
Index: /tags/Mars-V0.9/mreflector/MRflEvtHeader.h
===================================================================
--- /tags/Mars-V0.9/mreflector/MRflEvtHeader.h	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/MRflEvtHeader.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MRflEvtHeader
+#define MARS_MRflEvtHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MRflEvtHeader : public MParContainer
+{
+    Int_t fEvtNumber;
+
+public:
+    MRflEvtHeader(const char *name=NULL, const char *title=NULL);
+
+    Int_t GetEvtNumber() const { return fEvtNumber; }
+    void SetEvtNumber(Int_t n) { fEvtNumber = n; }
+
+    ClassDef(MRflEvtHeader, 0) // Header of an event from the reflector program
+};
+
+#endif
Index: /tags/Mars-V0.9/mreflector/MRflRunHeader.cc
===================================================================
--- /tags/Mars-V0.9/mreflector/MRflRunHeader.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/MRflRunHeader.cc	(revision 9772)
@@ -0,0 +1,41 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRflRunHeader
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRflRunHeader.h"
+
+ClassImp(MRflRunHeader);
+
+// --------------------------------------------------------------------------
+//
+MRflRunHeader::MRflRunHeader(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MRflRunHeader";
+    fTitle = title ? title : "Run header information from a reflector event";
+}
+
Index: /tags/Mars-V0.9/mreflector/MRflRunHeader.h
===================================================================
--- /tags/Mars-V0.9/mreflector/MRflRunHeader.h	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/MRflRunHeader.h	(revision 9772)
@@ -0,0 +1,21 @@
+#ifndef MARS_MRflRunHeader
+#define MARS_MRflRunHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MRflRunHeader : public MParContainer
+{
+    Int_t fRunNumber;
+
+public:
+    MRflRunHeader(const char *name=NULL, const char *title=NULL);
+
+    Int_t GetRunNumber() const { return fRunNumber; }
+    void SetRunNumber(Int_t n) { fRunNumber = n; }
+
+    ClassDef(MRflRunHeader, 0) // Header of an run from the reflector program
+};
+
+#endif
Index: /tags/Mars-V0.9/mreflector/MRflSinglePhoton.cc
===================================================================
--- /tags/Mars-V0.9/mreflector/MRflSinglePhoton.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/MRflSinglePhoton.cc	(revision 9772)
@@ -0,0 +1,48 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 5/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MRflSinglePhoton
+//
+// Single Photon of a event from the reflector program
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MRflSinglePhoton.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MRflSinglePhoton);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Dump all photon information
+//
+void MRflSinglePhoton::Print(Option_t *o) const
+{
+    *fLog << all << "x=" << fX << " y=" << fY << endl;
+}
Index: /tags/Mars-V0.9/mreflector/MRflSinglePhoton.h
===================================================================
--- /tags/Mars-V0.9/mreflector/MRflSinglePhoton.h	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/MRflSinglePhoton.h	(revision 9772)
@@ -0,0 +1,34 @@
+#ifndef MARS_MRflSinglePhoton
+#define MARS_MRflSinglePhoton
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MRflSinglePhoton : public MParContainer
+{
+private:
+    Float_t fX;      // [mm] camera impact point
+    Float_t fY;      // [mm] camera impact point
+    Float_t fCosU;   // [1] camera direction cosine
+    Float_t fCosV;   // [1] camera direction cosine
+    Float_t fTime;   // [ns] arrival time
+    Float_t fHeight; // [cm] production height
+    Float_t fPhi;    // [rad] camera inc. angle (rad)
+public:
+    void SetXY(Float_t x, Float_t y) { fX = x; fY=y; }
+    void SetCosUV(Float_t u, Float_t v) { fCosU = u; fCosV=v; }
+    void SetTime(Float_t t) { fTime = t; }
+    void SetHeight(Float_t h) { fHeight = h; }
+    void SetInclinationAngle(Float_t phi) { fPhi = phi; }
+
+    Float_t GetX() const { return fX; }
+    Float_t GetY() const { return fY; }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MRflSinglePhoton, 0) // Single Photon of a event from the reflector program
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mreflector/Makefile
===================================================================
--- /tags/Mars-V0.9/mreflector/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/Makefile	(revision 9772)
@@ -0,0 +1,34 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Reflector
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom
+
+SRCFILES = MRflEvtData.cc \
+	   MRflEvtHeader.cc \
+	   MRflRunHeader.cc \
+	   MRflSinglePhoton.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mreflector/ReflectorIncl.h
===================================================================
--- /tags/Mars-V0.9/mreflector/ReflectorIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/ReflectorIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mreflector/ReflectorLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mreflector/ReflectorLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mreflector/ReflectorLinkDef.h	(revision 9772)
@@ -0,0 +1,12 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MRflEvtData+;
+#pragma link C++ class MRflEvtHeader+;
+#pragma link C++ class MRflRunHeader+;
+#pragma link C++ class MRflSinglePhoton+;
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReport.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReport.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReport.cc	(revision 9772)
@@ -0,0 +1,161 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReport
+//
+//  This is a base class for all reports comming from subsystems stored in
+//  a report file.
+//
+//  Be carefull: The class name of all classes derived from this class
+//               should start with 'MReport', see SetupReading
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReport.h"
+
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MParList.h"
+
+ClassImp(MReport);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Interpretes the beginning of a line which starts like:
+//   status hour minute second millisec skip skip skip skip skip
+// The identifier is assumed to be removed.
+//
+// While skip are numbers which won't enter the analysis
+//
+// SetupReading must be called successfully before.
+//
+Bool_t MReport::InterpreteHeader(TString &str)
+{
+    int len, state;
+    int yea, mon, day, hor, min, sec, ms;
+
+    int n = sscanf(str.Data(),
+                   fHasReportTime ?
+                   " %d %d %d %d %d %d %d %d %*d %*d %*d %*d %*d %*d %*d %*d %n" :
+                   " %d %d %d %d %d %d %d %d %n",
+                   &state, &yea, &mon, &day, &hor, &min, &sec, &ms, &len);
+    if (n!=8)
+    {
+        *fLog << err << "ERROR - Cannot interprete Body of " << fIdentifier << " (n=" << n << ")" << endl;
+        return kFALSE;
+    }
+
+    fState=state;
+    if (!fTime->Set(yea, mon, day, hor, min, sec, ms))
+    {
+        *fLog << err << "ERROR - Event has invalid time: ";
+        *fLog << Form("%d.%d.%d %02d:%02d:%02d.%03d", day, mon, yea, hor, min, sec, ms);
+        *fLog << "... abort." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, len);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Report Body must be overwritten. It will get the line idetified to belong
+// to fIdentifier without the leading status and time infomration as an
+// argument.
+//
+Int_t MReport::InterpreteBody(TString &str, Int_t ver)
+{
+    *fLog << warn << "No interpreter existing for: " << fIdentifier << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprets Header and Body of a report file line. Calls SetReadyToSave()
+// in case the interpretation was successfull. And fTime->SetReadyToSave()
+// when a corresponding time container exists.
+//
+// SetupReading must be called successfully before.
+//
+Int_t MReport::Interprete(TString &str, const MTime &start, const MTime &stop, Int_t ver)
+{
+    if (!InterpreteHeader(str))
+        return kFALSE;
+
+    // return -1: This is the special case: out of time limit
+    if (start && *fTime<start)
+        return -1;
+    if (stop  && *fTime>stop)
+        return -1;
+
+    const Int_t rc = InterpreteBody(str, ver);
+    if (rc != kTRUE)
+        return rc;
+
+    SetReadyToSave();
+    fTime->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for the existance of a corresponding MTime in the given parameter
+// list. If it is not found a new one will be created. The name of the
+// MTime object is created by taking the ClassName() of the derived MReport
+// class and stripping the leading MReport
+//
+Bool_t MReport::SetupReading(MParList &plist)
+{
+    fTime = NULL;
+
+    TString id(ClassName());
+    if (!id.BeginsWith("MReport"))
+    {
+        *fLog << warn << " WARNING - Class name '" << id << "' ";
+        *fLog << " doesn't begin with 'MReport'... no MTime assigned." << endl;
+        return kFALSE;
+    }
+
+    id.Remove(0, 7);
+    if (id.IsNull())
+    {
+        *fLog << warn << " WARNING - No postfix existing... no MTime assigned." << endl;
+        return kFALSE;
+    }
+
+    id.Prepend("MTime");
+
+    fTime = (MTime*)plist.FindCreateObj("MTime", id);
+    if (!fTime)
+        return kFALSE;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mreport/MReport.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReport.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReport.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MReport
+#define MARS_MReport
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MTime;
+class MParList;
+
+class MReport : public MParContainer
+{
+private:
+    const TString fIdentifier;    //! Identifier of the subsystem
+    const Bool_t  fHasReportTime; //! Intermediate solution for DC currents
+
+    Byte_t  fState;               // Status of the subsystem
+    MTime  *fTime;                //! pointer to the corresponding time stamp
+
+    ULong_t Hash() const { return fIdentifier.Hash(); }
+    Bool_t InterpreteHeader(TString &str);
+
+public:
+    MReport(const char *id, Bool_t time=kTRUE) : fIdentifier(id), fHasReportTime(time), fState(0xff), fTime(0) { }
+
+    virtual Bool_t SetupReading(MParList &plist);
+    virtual Int_t  InterpreteBody(TString &str, Int_t ver);
+
+    Int_t  Interprete(TString &str, const MTime &start, const MTime &stop, const Int_t ver);
+    Bool_t CheckIdentifier(TString &str) const
+    {
+        if (!str.BeginsWith(fIdentifier))
+            return kFALSE;
+
+        str.Remove(0, fIdentifier.Length());
+        str = str.Strip(TString::kBoth);
+
+        return kTRUE;
+    }
+
+    const TString &GetIdentifier() const { return fIdentifier; }
+
+    Byte_t GetState() const { return fState; }
+
+    ClassDef(MReport, 1) // Base class for control reports
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportCC.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportCC.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportCC.cc	(revision 9772)
@@ -0,0 +1,89 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportCC
+//
+// This is the class interpreting and storing the CC-REPORT information.
+//
+// From here maily weather station data is decoded such as
+// temperature, humidity, wind-speed and solar radiation
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportCC.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+
+ClassImp(MReportCC);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "CC-REPORT" Report
+// is expected to have no 'subsystem' time.
+//
+MReportCC::MReportCC() : MReport("CC-REPORT", kFALSE)
+{
+    fName  = "MReportCC";
+    fTitle = "Class for CC-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the CC-REPORT string
+//
+Int_t MReportCC::InterpreteBody(TString &str, Int_t ver)
+{
+    // Remove the 30 tokens of the subsystem status
+    //  table 12.1 p59
+    for (int i=0; i<30; i++)
+        str.Remove(0, str.First(' ')+1);
+
+    Int_t len;
+    const Int_t n=sscanf(str.Data(),
+                         "%*f %*f %*f %*f %f %f %f %f %*f %*f %n",
+                         &fTemperature, &fSolarRadiation, &fWindSpeed,
+                         &fHumidity, &len);
+    if (n!=4)
+    {
+        *fLog << warn << "WARNING - Wrong number of arguments." << endl;
+        return kCONTINUE;
+    }
+    /*
+    str.Remove(0, len);
+
+    *fLog << dbg << str << endl;
+
+    if (str!=(TString)"OVER")
+    {
+        *fLog << err << "ERROR - Termination (OVER) too far away." << endl;
+        return kFALSE;
+    }
+    */
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mreport/MReportCC.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportCC.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportCC.h	(revision 9772)
@@ -0,0 +1,29 @@
+#ifndef MARS_MReportCC
+#define MARS_MReportCC
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportCC : public MReport
+{
+private:
+    Float_t fHumidity;       // [%]
+    Float_t fTemperature;    // [deg] celsius
+    Float_t fWindSpeed;      // [km/h]
+    Float_t fSolarRadiation; // [W/m^2] IR-Radiation
+
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportCC();
+
+    Float_t GetHumidity() const       { return fHumidity; }
+    Float_t GetTemperature() const    { return fTemperature; }
+    Float_t GetWindSpeed() const      { return fWindSpeed; }
+    Float_t GetSolarRadiation() const { return fSolarRadiation; }
+
+    ClassDef(MReportCC, 1) // Class for CC-REPORT information
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportCamera.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportCamera.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportCamera.cc	(revision 9772)
@@ -0,0 +1,488 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportCamera
+//
+// This is the class interpreting and storing the CAMERA-REPORT information.
+//
+// Most of the information is redirected to the classes MCamera* and stored
+// there.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportCamera.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+#include "MParList.h"
+
+#include "MCameraCalibration.h"
+#include "MCameraCooling.h"
+#include "MCameraHV.h"
+#include "MCameraLV.h"
+#include "MCameraAUX.h"
+#include "MCameraLids.h"
+
+ClassImp(MReportCamera);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "CAMERA-REPORT"
+//
+MReportCamera::MReportCamera() : MReport("CAMERA-REPORT")
+{
+    fName = "MReportCamera";
+    fTitle = "Class for CAMERA-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate the following objects:
+//  - MCameraCooling
+//  - MCameraLids
+//  - MCameraAUX
+//  - MCameraHV
+//  - MCameraLV
+//  - MCameraCalibration
+//
+Bool_t MReportCamera::SetupReading(MParList &plist)
+{
+    fCooling = (MCameraCooling*)plist.FindCreateObj("MCameraCooling");
+    if (!fCooling)
+        return kFALSE;
+
+    fLids = (MCameraLids*)plist.FindCreateObj("MCameraLids");
+    if (!fLids)
+        return kFALSE;
+
+    fAUX = (MCameraAUX*)plist.FindCreateObj("MCameraAUX");
+    if (!fAUX)
+        return kFALSE;
+
+    fHV = (MCameraHV*)plist.FindCreateObj("MCameraHV");
+    if (!fHV)
+        return kFALSE;
+
+    fLV = (MCameraLV*)plist.FindCreateObj("MCameraLV");
+    if (!fLV)
+        return kFALSE;
+
+    fCalibration = (MCameraCalibration*)plist.FindCreateObj("MCameraCalibration");
+    if (!fCalibration)
+        return kFALSE;
+
+    return MReport::SetupReading(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the given TString begins with the given tag. Remove
+// the tag from the string.
+//
+Bool_t MReportCamera::CheckTag(TString &str, const char *tag) const
+{
+    if (!str.BeginsWith(tag))
+    {
+        *fLog << warn << "WARNING - '" << tag << "' tag not found." << endl;
+        return kFALSE;
+    }
+    str.Remove(0, strlen(tag)); // Remove DC currents
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the DC* part of the report
+//
+Bool_t MReportCamera::InterpreteDC(TString &str)
+{
+    if (!CheckTag(str, "DC "))
+        return kFALSE;
+
+    str.Remove(0, 577*4); // Remove DC currents
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the HV* part of the report
+//
+Bool_t MReportCamera::InterpreteHV(TString &str)
+{
+    if (!CheckTag(str, "HV "))
+        return kFALSE;
+
+    const char *pos = str.Data();
+    const char *end = str.Data()+577*3;
+
+    Int_t i=0;
+    while (pos<end)
+    {
+        const Char_t hex[4] = { pos[0], pos[1], pos[2], 0 };
+        pos += 3;
+
+        const Int_t n=sscanf(hex, "%3hx", &fHV->fHV[i++]);
+        if (n==1)
+            continue;
+
+        *fLog << warn << "WARNING - Reading hexadecimal HV information." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, end-str.Data()); // Remove DC currents
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the COOL* part of the report
+//
+Bool_t MReportCamera::InterpreteCOOL(TString &str)
+{
+    if (!CheckTag(str, "COOL "))
+        return kFALSE;
+
+    Int_t len;
+
+    Int_t wall, opt, center, water;
+    Short_t hwall, hcenter, hip, lop, pump, ref, valv, res, fans;
+    const Int_t n=sscanf(str.Data(), "%d %d %d %d %hu %hu %hu %hu %hu %hu %hu %hu %hu %n",
+                         &wall, &opt, &center, &water, &hwall, &hcenter,
+                         &hip,  &lop, &pump, &ref, &valv, &res, &fans, &len);
+    if (n!=13)
+    {
+        *fLog << warn << "WARNING - Reading information of 'COOL' section." << endl;
+        return kFALSE;
+    }
+
+    fCooling->fTempWall            = 0.1*wall;
+    fCooling->fTempOptLink         = 0.1*opt;
+    fCooling->fTempCenter          = 0.1*center;
+    fCooling->fTempWater           = 0.1*water;
+    fCooling->fHumWall             = (Byte_t)hwall;
+    fCooling->fHumCenter           = (Byte_t)hcenter;
+    fCooling->fStatusPressureHi    = (Bool_t)hip;
+    fCooling->fStatusPressureLo    = (Bool_t)lop;
+    fCooling->fStatusPump          = (Bool_t)pump;
+    fCooling->fStatusRefrigrerator = (Bool_t)ref;
+    fCooling->fStatusValve         = (Bool_t)valv;
+    fCooling->fStatusResistor      = (Bool_t)res;
+    fCooling->fStatusFans          = (Bool_t)fans;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the LID* part of the report
+//
+Bool_t MReportCamera::InterpreteLID(TString &str)
+{
+    if (!CheckTag(str, "LID "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t limao, limac, limbo, limbc;
+    Short_t slimao, slimac, slimbo, slimbc;
+    Short_t slida, slidb, mlida, mlidb;
+    const Int_t n=sscanf(str.Data(), "%hu %hu %hu %hu %hu %hu %hu %hu %hu %hu %hu %hu %n",
+                         &limao, &limac, &limbo, &limbc,
+                         &slimao, &slimac, &slimbo, &slimbc,
+                         &slida, &slidb, &mlida, &mlidb,
+                         &len);
+    if (n!=12)
+    {
+        *fLog << warn << "WARNING - Reading information of 'LID' section." << endl;
+        return kFALSE;
+    }
+
+    fLids->fLidA.fLimitOpen       = (Bool_t)limao;
+    fLids->fLidA.fLimitClose      = (Bool_t)limac;
+    fLids->fLidA.fSafetyLimitOpen = (Bool_t)slimao;
+    fLids->fLidA.fSafetyLimitClose= (Bool_t)slimac;
+    fLids->fLidA.fStatusLid       = (Byte_t)slida;
+    fLids->fLidA.fStatusMotor     = (Byte_t)mlida;
+
+    fLids->fLidB.fLimitOpen       = (Bool_t)limbo;
+    fLids->fLidB.fLimitClose      = (Bool_t)limbc;
+    fLids->fLidB.fSafetyLimitOpen = (Bool_t)slimbo;
+    fLids->fLidB.fSafetyLimitClose= (Bool_t)slimbc;
+    fLids->fLidB.fStatusLid       = (Byte_t)slidb;
+    fLids->fLidB.fStatusMotor     = (Byte_t)mlidb;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the HVPS* part of the report
+//
+Bool_t MReportCamera::InterpreteHVPS(TString &str)
+{
+    if (!CheckTag(str, "HVPS "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t c1, c2;
+    const Int_t n=sscanf(str.Data(), "%hd %hd %hd %hd %n",
+                         &fHV->fVoltageA, &fHV->fVoltageB, &c1, &c2, &len);
+    if (n!=4)
+    {
+        *fLog << warn << "WARNING - Reading information of 'HVPS' section." << endl;
+        return kFALSE;
+    }
+
+    fHV->fCurrentA = (Byte_t)c1;
+    fHV->fCurrentB = (Byte_t)c2;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the LV* part of the report
+//
+Bool_t MReportCamera::InterpreteLV(TString &str)
+{
+    if (!CheckTag(str, "LV "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t vap5, vap12, van12, vbp5, vbp12, vbn12;
+    Short_t valp12, vblp12, cap5, cap12, can12, cbp5, cbp12;
+    Short_t cbn12, calp12, cblp12, lvps, temp, hum;
+    const Int_t n=sscanf(str.Data(), "%hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %n",
+                         &vap5, &vap12, &van12, &vbp5, &vbp12, &vbn12,
+                         &valp12, &vblp12, &cap5, &cap12, &can12, &cbp5, &cbp12,
+                         &cbn12, &calp12, &cblp12, &lvps, &temp, &hum, &len);
+    if (n!=19)
+    {
+        *fLog << warn << "WARNING - Reading information of 'LV' section." << endl;
+        return kFALSE;
+    }
+
+    fLV->fRequestPowerSupply = (Bool_t)lvps;
+    fLV->fTemp = 0.1*temp;
+    fLV->fHumidity = (Byte_t)hum;
+
+    fLV->fPowerSupplyA.fVoltagePos5V         = 0.01*vap5;
+    fLV->fPowerSupplyA.fVoltagePos12V        = 0.01*vap12;
+    fLV->fPowerSupplyA.fVoltageNeg12V        = 0.01*van12;
+    fLV->fPowerSupplyA.fVoltageOptLinkPos12V = 0.01*valp12;
+    fLV->fPowerSupplyA.fCurrentPos5V         = 0.001*cap5;
+    fLV->fPowerSupplyA.fCurrentPos12V        = 0.001*cap12;
+    fLV->fPowerSupplyA.fCurrentNeg12V        = 0.001*can12;
+    fLV->fPowerSupplyA.fCurrentOptLinkPos12V = 0.001*calp12;
+
+    fLV->fPowerSupplyB.fVoltagePos5V         = 0.01*vbp5;
+    fLV->fPowerSupplyB.fVoltagePos12V        = 0.01*vbp12;
+    fLV->fPowerSupplyB.fVoltageNeg12V        = 0.01*vbn12;
+    fLV->fPowerSupplyB.fVoltageOptLinkPos12V = 0.01*vblp12;
+    fLV->fPowerSupplyB.fCurrentPos5V         = 0.001*cbp5;
+    fLV->fPowerSupplyB.fCurrentPos12V        = 0.001*cbp12;
+    fLV->fPowerSupplyB.fCurrentNeg12V        = 0.001*cbn12;
+    fLV->fPowerSupplyB.fCurrentOptLinkPos12V = 0.001*cblp12;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the AUX* part of the report
+//
+Bool_t MReportCamera::InterpreteAUX(TString &str)
+{
+    if (!CheckTag(str, "AUX "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t led, fan;
+    const Int_t n=sscanf(str.Data(), "%hd %hd %n", &led, &fan, &len);
+    if (n!=2)
+    {
+        *fLog << warn << "WARNING - Reading information of 'AUX' section." << endl;
+        return kFALSE;
+    }
+
+    fAUX->fRequestCaosLEDs=(Bool_t)led;
+    fAUX->fRequestFansFADC=(Bool_t)fan;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the CAL* part of the report
+//
+Bool_t MReportCamera::InterpreteCAL(TString &str)
+{
+    if (!CheckTag(str, "CAL "))
+        return kFALSE;
+
+    Int_t len;
+    Short_t hv, lv, cont, pin;
+
+    const Int_t n=sscanf(str.Data(), "%hd %hd %hd %hd %n", &hv, &lv, &cont, &pin, &len);
+    if (n!=4)
+    {
+        *fLog << warn << "WARNING - Reading information of 'CAL' section." << endl;
+        return kFALSE;
+    }
+
+    fCalibration->fRequestHiVoltage = (Bool_t)hv;
+    fCalibration->fRequestLoVoltage = (Bool_t)lv;
+    fCalibration->fRequestContLight = (Bool_t)cont;
+    fCalibration->fRequestPinDiode  = (Bool_t)pin;
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the HOT* part of the report
+//
+Bool_t MReportCamera::InterpreteHOT(TString &str)
+{
+
+    if (!CheckTag(str, "HOT "))
+        return kFALSE;
+
+    Int_t len;
+    Int_t hot;
+
+    const Int_t n=sscanf(str.Data(), "%d %n", &hot, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Reading information of 'HOT' section." << endl;
+        return kFALSE;
+    }
+
+    str.Remove(0, len);
+    str=str.Strip(TString::kBoth);
+    return kTRUE;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the CAMERA-REPORT part
+//
+Bool_t MReportCamera::InterpreteCamera(TString &str)
+{
+    //
+    // I have tried to do it with pure pointer arithmentics, but most of the time is spent
+    // to do the sscanf. So we gain less than 5% not using TString like it is done here.
+    Int_t len;
+    Short_t cal, stat, hvps, lid, lv, cool, hv, dc, led, fan, can, io, clv;
+    Int_t n=sscanf(str.Data(), " %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %hd %n",
+                   &cal, &stat, &hvps, &lid, &lv, &cool, &hv,
+                   &dc, &led, &fan, &can, &io, &clv, &len);
+    if (n!=13)
+    {
+        *fLog << warn << "WARNING - Cannot interprete status' of subsystems." << endl;
+        return kFALSE;
+    }
+    str.Remove(0, len);
+    str=str.Strip(TString::kLeading);
+
+    fHV->fStatus                   = (Byte_t)hvps;
+    fLids->fStatus                 = (Byte_t)lid;
+    fLV->fStatus                   = (Byte_t)lv;
+    fCooling->fStatus              = (Byte_t)cool;
+    fHV->fStatusRamping            = (Byte_t)hv;
+    fAUX->fStatusCaosLEDs          = (Bool_t)led;
+    fAUX->fStatusFansFADC          = (Bool_t)fan;
+    fCalibration->fStatus          = (Bool_t)cal;
+    fCalibration->fStatusCANbus    = (Bool_t)can;
+    fCalibration->fStatusIO        = (Bool_t)io;
+    fCalibration->fStatusLoVoltage = (Bool_t)clv;
+    fStatus                        = (Byte_t)stat;
+    fStatusDC                      = (Byte_t)dc;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the CAMERA-REPORT string
+//
+Int_t MReportCamera::InterpreteBody(TString &str, Int_t ver)
+{
+    if (!InterpreteCamera(str))
+        return kCONTINUE;
+
+    if (!InterpreteDC(str))
+        return kCONTINUE;
+
+    if (!InterpreteHV(str))
+        return kCONTINUE;
+
+    if (!InterpreteCOOL(str))
+        return kCONTINUE;
+
+    if (!InterpreteLID(str))
+        return kCONTINUE;
+
+    if (!InterpreteHVPS(str))
+        return kCONTINUE;
+
+    if (!InterpreteLV(str))
+        return kCONTINUE;
+
+    if (!InterpreteAUX(str))
+        return kCONTINUE;
+
+    if (!InterpreteCAL(str))
+        return kCONTINUE;
+
+    if (!InterpreteHOT(str))
+        return kCONTINUE;
+
+    if (str!="OVER")
+    {
+        *fLog << warn << "WARNING - 'OVER' tag not found." << endl;
+        return kCONTINUE;
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mreport/MReportCamera.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportCamera.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportCamera.h	(revision 9772)
@@ -0,0 +1,53 @@
+#ifndef MARS_MReportCamera
+#define MARS_MReportCamera
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MCameraCooling;
+class MCameraLids;
+class MCameraHV;
+class MCameraLV;
+class MCameraAUX;
+class MCameraCalibration;
+
+class MReportCamera : public MReport
+{
+private:
+    Byte_t fStatus;   // CaCo monitored status of the sentinel (0-9), Sentinel_state
+    Byte_t fStatusDC; // CaCo monitored status of the DC currents (0-9), Cam.DC_state
+
+    MCameraCooling     *fCooling;     //!
+    MCameraLids        *fLids;        //!
+    MCameraAUX         *fAUX;         //!
+    MCameraHV          *fHV;          //!
+    MCameraLV          *fLV;          //!
+    MCameraCalibration *fCalibration; //!
+
+    Bool_t SetupReading(MParList &plist);
+    Bool_t CheckTag(TString &str, const char *tag) const;
+
+    Bool_t InterpreteCamera(TString &str);
+    Bool_t InterpreteDC(TString &str);
+    Bool_t InterpreteHV(TString &str);
+    Bool_t InterpreteCOOL(TString &str);
+    Bool_t InterpreteLID(TString &str);
+    Bool_t InterpreteHVPS(TString &str);
+    Bool_t InterpreteLV(TString &str);
+    Bool_t InterpreteAUX(TString &str);
+    Bool_t InterpreteCAL(TString &str);
+    Bool_t InterpreteHOT(TString &str);
+
+    Int_t  InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportCamera();
+
+    Byte_t GetStatus() const { return  fStatus; }
+    Byte_t GetStatusDC() const { return fStatusDC; }
+
+    ClassDef(MReportCamera, 1) // Class for CAMERA-REPORT information
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportCurrents.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportCurrents.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportCurrents.cc	(revision 9772)
@@ -0,0 +1,110 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportCurrents
+//
+// This is the class interpreting and storing the DC-REPORT information.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportCurrents.h"
+
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCameraDC.h"
+
+ClassImp(MReportCurrents);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "DC-REPORT" Reports
+// are expected to have no 'subsystem' time.
+//
+MReportCurrents::MReportCurrents() : MReport("DC-REPORT", kFALSE)
+{
+    fName  = "MReportCurrents";
+    fTitle = "Class for DC-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate the following objects:
+//  - MCameraDC
+//
+Bool_t MReportCurrents::SetupReading(MParList &plist)
+{
+    fDC = (MCameraDC*)plist.FindCreateObj("MCameraDC");
+    if (!fDC)
+        return kFALSE;
+
+    return MReport::SetupReading(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the DC-REPORT string
+//
+Int_t MReportCurrents::InterpreteBody(TString &str, Int_t ver)
+{
+    Int_t len;
+    Short_t err1, err2;
+    const Int_t n=sscanf(str.Data(), " %hd %hd %n", &err1, &err2, &len);
+    if (n!=2)
+    {
+        *fLog << warn << "WARNING - Reading status information." << endl;
+        return kCONTINUE;
+    }
+
+    fStatus1 = (Byte_t)err1;
+    fStatus2 = (Byte_t)err2;
+
+    const char *pos = str.Data()+len;
+    const char *end = pos+577*4;
+
+    Int_t i=0;
+    while (pos<end)
+    {
+        Int_t c;
+        const Char_t hex[5] = { pos[0], pos[1], pos[2], pos[3], 0 };
+        pos += 4;
+
+        const Int_t n=sscanf(hex, "%4x", &c);
+        if (n!=1)
+        {
+            *fLog << warn << "WARNING - Reading hexadecimal DC information." << endl;
+            return kCONTINUE;
+        }
+
+        (*fDC)[i++] = 0.001*c;
+    }
+
+    str.Remove(0, pos-str.Data()); // Remove DC currents
+    str=str.Strip(TString::kLeading);
+
+    return str.IsNull() ? kTRUE : kCONTINUE;
+}
Index: /tags/Mars-V0.9/mreport/MReportCurrents.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportCurrents.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportCurrents.h	(revision 9772)
@@ -0,0 +1,27 @@
+#ifndef MARS_MReportCurrents
+#define MARS_MReportCurrents
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MCameraDC;
+
+class MReportCurrents : public MReport
+{
+private:
+    Byte_t fStatus1;
+    Byte_t fStatus2;
+
+    MCameraDC *fDC; //!
+
+    Bool_t SetupReading(MParList &plist);
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportCurrents();
+
+    ClassDef(MReportCurrents, 1) // Class for DC-REPORT information
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportDAQ.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportDAQ.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportDAQ.cc	(revision 9772)
@@ -0,0 +1,54 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportDAQ
+//
+// This is the class interpreting and storing the DAQ-REPORT information.
+//
+// --> Currently unused
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportDAQ.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+
+ClassImp(MReportDAQ);
+
+using namespace std;
+
+MReportDAQ::MReportDAQ() : MReport("DAQ-REPORT")
+{
+    fName = "MReportDAQ";
+    fTitle = "Class for DAQ-REPORT information";
+}
+
+Int_t MReportDAQ::InterpreteBody(TString &str, Int_t ver)
+{
+    *fLog << dbg << "D" << flush;
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mreport/MReportDAQ.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportDAQ.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportDAQ.h	(revision 9772)
@@ -0,0 +1,19 @@
+#ifndef MARS_MReportDAQ
+#define MARS_MReportDAQ
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportDAQ : public MReport
+{
+private:
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportDAQ();
+
+    ClassDef(MReportDAQ, 1) // Class for DAQ-REPORT information
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportDrive.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportDrive.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportDrive.cc	(revision 9772)
@@ -0,0 +1,166 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportDrive
+//
+// This is the class interpreting and storing the DRIVE-REPORT information.
+//
+// This is NOT the place to get the pointing position from. The class
+// definition might change. But it is the place to calculate the
+// correct pointing position from.
+//
+//
+// Double_t fMjd;        // Modified Julian Date send by the drive system
+//  This is the MJD as it was calculated by the drive system when the report
+//  was send.
+//
+// Double_t fRa;         // [h]   Right ascension
+// Double_t fDec;        // [deg] Declination
+// Double_t fHa;         // [h]   Hour angle
+//  Currently this descries the nominal source position
+//
+// Double_t fNominalZd;  // [deg] Nominal zenith distance
+// Double_t fNominalAz;  // [deg] Nominal azimuth
+//  The nominal local position like it was calculated in the last
+//  control loop for time at which the last shaftencoder value has changed
+//
+// Double_t fCurrentZd;  // [deg] current zenith distance
+// Double_t fCurrentAz;  // [deg] current azimuth
+//  The current local position like it was calculated in the last
+//  control loop from interpolated shaftencoder values for time at which
+//  the last shaftencoder value has changed
+//
+// Double_t fErrorZd;    // [?] system error in the zenith angle axis
+// Double_t fErrorAz;    // [?] sistem error in the azimuth angle axis
+//  The system error on both axis derived from the two values above. Be
+//  carefull, eg near the zenith we a huge deviation in azimuth
+//  while having a small deviation in zenith angle might be meaingless.
+//  Please use GetAbsError to get the absolute distance between the
+//  twopositions.
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportDrive.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+
+ClassImp(MReportDrive);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "DRIVE-REPORT"
+//
+MReportDrive::MReportDrive() : MReport("DRIVE-REPORT"),
+    fMjd(0), fRa(0), fDec(0), fHa(0), fNominalZd(0), fNominalAz(0),
+    fCurrentZd(0), fCurrentAz(0), fErrorZd(0), fErrorAz(0)
+{
+    fName  = "MReportDrive";
+    fTitle = "Class for DRIVE-REPORT information (raw telescope position)";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the DRIVE-REPORT string
+//
+Int_t MReportDrive::InterpreteBody(TString &str, Int_t ver)
+{
+    MAstro::String2Angle(str, fRa);
+    MAstro::String2Angle(str, fDec);
+    MAstro::String2Angle(str, fHa);
+
+    Int_t len;
+    Int_t n=sscanf(str.Data(), "%lf %n", &fMjd, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+
+    str.Remove(0, len);
+
+    MAstro::String2Angle(str, fNominalZd);
+    MAstro::String2Angle(str, fNominalAz);
+    MAstro::String2Angle(str, fCurrentZd);
+    MAstro::String2Angle(str, fCurrentAz);
+
+    n=sscanf(str.Data(), "%lf %lf %n", &fErrorZd, &fErrorAz, &len);
+    if (n!=2)
+    {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+
+    str.Remove(0, len);
+
+    str = str.Strip(TString::kBoth);
+
+    return str.IsNull() ? kTRUE : kCONTINUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// GetAbsError [deg]
+//
+// Returns the absolute deviation from the nominal position calculated
+// from the system error.
+//
+//
+Double_t MReportDrive::GetAbsError() const
+{
+    const Double_t pzd = fNominalZd*TMath::DegToRad();
+    const Double_t azd = fErrorZd  *TMath::DegToRad();
+    const Double_t aaz = fErrorAz  *TMath::DegToRad();
+
+    const double el = TMath::Pi()/2-pzd;
+
+    const double dphi2 = aaz/2.;
+    const double cos2  = cos(dphi2)*cos(dphi2);
+    const double sin2  = sin(dphi2)*sin(dphi2);
+    const double d     = cos(azd)*cos2 - cos(2*el)*sin2;
+
+    //
+    // Original:
+    //   cos(Zd1)*cos(Zd2)+sin(Zd1)*sin(Zd2)*cos(dAz)
+    //
+    // Correct:
+    //   const double d = cos(azd)*cos2 - cos(el1+el2)*sin2;
+    //
+    // Estimated:
+    //   const double d = cos(azd)*cos2 - cos(2*el)*sin2;
+    //
+
+    return acos(d)*TMath::RadToDeg();
+}
+
+void MReportDrive::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ": Mjd=" << fMjd << " Ra=" << fRa << " Dec=" << fDec;
+    *fLog << " dZd=" << fErrorZd << " dAz=" << fErrorAz << " D=" << GetAbsError() << endl;
+}
Index: /tags/Mars-V0.9/mreport/MReportDrive.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportDrive.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportDrive.h	(revision 9772)
@@ -0,0 +1,51 @@
+#ifndef MARS_MReportDrive
+#define MARS_MReportDrive
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportDrive : public MReport
+{
+private:
+    Double_t fMjd;        // Modified Julian Date send by the drive system
+
+    Double_t fRa;         // [h]   Right ascension
+    Double_t fDec;        // [deg] Declination
+    Double_t fHa;         // [h]   Hour angle
+
+    Double_t fNominalZd;  // [deg] Nominal zenith distance
+    Double_t fNominalAz;  // [deg] Nominal azimuth
+    Double_t fCurrentZd;  // [deg] current zenith distance
+    Double_t fCurrentAz;  // [deg] current azimuth
+
+    Double_t fErrorZd;    // [deg] system error in the zenith angle axis
+    Double_t fErrorAz;    // [deg] sistem error in the azimuth angle axis
+
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportDrive();
+
+    Double_t GetMjd() const       { return fMjd;       }
+
+    Double_t GetRa() const        { return fRa;        }
+    Double_t GetDec() const       { return fDec;       }
+    Double_t GetHa() const        { return fHa;        }
+
+    Double_t GetNominalZd() const { return fNominalZd; }
+    Double_t GetNominalAz() const { return fNominalAz; }
+    Double_t GetCurrentZd() const { return fCurrentZd; }
+    Double_t GetCurrentAz() const { return fCurrentAz; }
+
+    Double_t GetErrorZd() const   { return fErrorZd;   }
+    Double_t GetErrorAz() const   { return fErrorAz;   }
+
+    Double_t GetAbsError() const;
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MReportDrive, 1) // Class for DRIVE-REPORT information
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportFileRead.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportFileRead.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportFileRead.cc	(revision 9772)
@@ -0,0 +1,262 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportFileRead
+//
+// Task to read the central control report file. For more information see
+// the base class of all reports MReport.
+//
+// To add a report which should be read use AddToList.
+//
+// eg. AddToList("Drive") will assume the existance of a class called
+//     MReportDrive. It will create such an object automatically. It will
+//     send all lines starting with 'MReportDrive::fIndetifier-REPORT'
+//     to this class.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportFileRead.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TRegexp.h>
+#include <THashTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MReportHelp.h"
+
+ClassImp(MReportFileRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file and creates a
+// THashTable which allows faster access to the MReport* objects.
+//
+MReportFileRead::MReportFileRead(const char *fname, const char *name, const char *title)
+    : fFileName(fname), fVersion(-1), fIn(NULL)
+{
+    fName  = name  ? name  : "MReportFileRead";
+    fTitle = title ? title : "Read task to read general report files";
+
+    fIn = new ifstream;
+    fList = new THashTable(1,1);
+    fList->SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream and hash table.
+//
+MReportFileRead::~MReportFileRead()
+{
+    delete fIn;
+    delete fList;
+}
+
+// --------------------------------------------------------------------------
+//
+// Wrapper. Returns the MReportHelp with the given identifier from the
+// hash table.
+//
+MReportHelp *MReportFileRead::GetReportHelp(const TString &str) const
+{
+    return (MReportHelp*)fList->FindObject(str);
+}
+
+// --------------------------------------------------------------------------
+//
+// Wrapper. Returns the MReport stored in the given MReportHelp
+//
+MReport *MReportFileRead::GetReport(MReportHelp *help) const
+{
+    return help ? help->GetReport() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Wrapper. Returns the MReport stored in the MReportHelp given by its
+// identifier.
+//
+MReport *MReportFileRead::GetReport(const TString &str) const
+{
+    return GetReport(GetReportHelp(str));
+}
+
+// --------------------------------------------------------------------------
+//
+// Add a new MReport* to the list (eg 'Drive' will add MReportDrive)
+// For convinience the object is created as a MReportHelp object.
+//
+Bool_t MReportFileRead::AddToList(const char *name) const
+{
+    MReportHelp *help = new MReportHelp(name, fLog);
+
+    if (!help->GetReport())
+        return kFALSE;
+
+    if (GetReport(help->GetName()))
+    {
+        *fLog << warn << "WARNING - Report with Identifier '";
+        *fLog << help->GetName() << "' already added to the list... ";
+        *fLog << "ignored." << endl;
+        delete help;
+        return kFALSE;
+    }
+
+    fList->Add(help);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Call SetupReading for all MReportHelp objects scheduled.
+// Try to open the file and check the file header.
+//
+Int_t MReportFileRead::PreProcess(MParList *pList)
+{
+    //MTime *time = (MTime*)pList->FindCreateObj("MTime");
+    //if (!time)
+    //    return kFALSE;
+    fNumLine = 0;
+
+    TIter Next(fList);
+    MReportHelp *help=0;
+    while ((help=(MReportHelp*)Next()))
+        if (!help->SetupReading(*pList))
+            return kFALSE;
+
+    fList->ForEach(MReportHelp, AddToList)(*pList);
+
+    //
+    // open the input stream
+    // first of all check if opening the file in the constructor was
+    // successfull
+    //
+    fIn->open(fFileName);
+    if (!(*fIn))
+    {
+        *fLog << err << "Cannot open file " << fFileName << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    if (TestBit(kHasNoHeader))
+        return kTRUE;
+
+    const Int_t n = CheckFileHeader();
+    fNumLine += n;
+    return n==2;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the file line by line as long as a matching MReport* class is found.
+// In this case call its interpreter (Interprete()) and remove the identifier
+// first (XYZ-REPORT)
+//
+Int_t MReportFileRead::Process()
+{
+    TString str;
+
+    MReportHelp *rep=NULL;
+    while (!GetReport(rep))
+    {
+        str.ReadLine(*fIn);
+        if (!*fIn)
+        {
+            *fLog << dbg << "EOF detected." << endl;
+            return kFALSE;
+        }
+
+        fNumLine++;
+
+        const Int_t pos = str.First(' ');
+        if (pos<=0)
+            continue;
+
+        rep = GetReportHelp(str(0,pos));
+        if (GetReport(rep))
+            str.Remove(0, pos);
+    }
+
+    const Int_t rc = rep->Interprete(str, fStart, fStop, fVersion);
+
+    switch (rc)
+    {
+    case kFALSE:
+        *fLog << err << "ERROR - Interpretation of '" << rep->GetName() << "' failed (Line #" << fNumLine << ")... abort." << endl;
+        break;
+    case kCONTINUE:
+        *fLog << warn << "WARNING - Interpretation of '" << rep->GetName() << "' failed (Line #" << fNumLine << ")... skipped." << endl;
+        break;
+    case -1: // This is the special case: out of time limit
+        return kCONTINUE;
+    }
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Close the file and print some execution statistics
+//
+Int_t MReportFileRead::PostProcess()
+{
+    fIn->close();
+
+    if (!GetNumExecutions())
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    TIter Next(fList);
+    MReportHelp *rep=0;
+
+    while ((rep=(MReportHelp*)Next()))
+    {
+        *fLog << inf;
+        *fLog << " " << setw(7) << rep->GetNumReports() << " (";
+        *fLog << setw(3) << (int)(100.*rep->GetNumReports()/GetNumExecutions());
+        *fLog << "%): " << rep->GetName() << endl;
+
+        if (rep->GetNumSkipped()==0)
+            continue;
+
+        *fLog << warn;
+        *fLog << " " << setw(7) << rep->GetNumSkipped() << " (";
+        *fLog << setw(3) << (int)(100.*rep->GetNumSkipped()/GetNumExecutions());
+        *fLog << "%): " << rep->GetName() << " skipped!" << endl;
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mreport/MReportFileRead.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportFileRead.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportFileRead.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MReportFileRead
+#define MARS_MReportFileRead
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+/*// gcc 3.2
+//class ifstream;
+#include <iosfwd>
+*/
+
+class THashTable;
+
+class MTime;
+class MReport;
+class MReportHelp;
+
+class MReportFileRead : public MTask
+{
+private:
+    TString     fFileName;  // Name of the input file
+
+    THashTable *fList;      // List of possible reports to be interpreted
+
+    MTime   fStart;         // Time range which should be read from file
+    MTime   fStop;          // Time range which should be read from file
+
+    ULong_t fNumLine;       // line counter
+
+    Int_t   fVersion;       // File format version
+
+    enum { kHasNoHeader = BIT(14) };
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    virtual Int_t CheckFileHeader() { return 0; }
+    MReport *GetReport(const TString &str) const;
+    MReport *GetReport(MReportHelp *help) const;
+    MReportHelp *GetReportHelp(const TString &str) const;
+
+protected:
+    ifstream   *fIn;         //! buffered input stream (file to read from)
+    void SetVersion(Int_t v) { fVersion = v; }
+
+public:
+    MReportFileRead(const char *filename, const char *name=NULL, const char *title=NULL);
+    ~MReportFileRead();
+
+    void SetHasNoHeader() { SetBit(kHasNoHeader); }
+    void SetTimeStart(const MTime &tm) { fStart = tm; }
+    void SetTimeStop(const MTime &tm)  { fStop = tm; }
+
+    Bool_t AddToList(const char *name) const;
+
+    ClassDef(MReportFileRead, 0)// Task to read general report file
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportFileReadCC.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportFileReadCC.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportFileReadCC.cc	(revision 9772)
@@ -0,0 +1,134 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MReportFileReadCC
+//
+// This is a report file reader which implements the CC header checking.
+// Because diffrent subsystem are writing different headers it is not
+// easily possible to have one Reader for all files. Because of this
+// you must know to which subsystem the file belongs before you can
+// instantiate your reader if you need the header or want to check the
+// header.
+//
+// If you want to restrict reading to 'single run report files' you can
+// call SetRunNumber(12345). In this case Checking the Header will fail
+// if no run information is available or the runnumber in the header
+// doesn't match. To request a 'all run' file use SetRunNumber(0).
+// To allow both file types to be read use SetRunNumber(-1) <default>
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportFileReadCC.h"
+
+#include <fstream>
+#include <stdlib.h> // atoi on gcc 2.95.3
+
+#include <TRegexp.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MReportFileReadCC);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file and creates a
+// THashTable which allows faster access to the MReport* objects.
+//
+MReportFileReadCC::MReportFileReadCC(const char *fname, const char *name, const char *title)
+    : MReportFileRead(fname, name, title), fRunNumber(-1)
+{
+    fName  = name  ? name  : "MReportFileReadCC";
+    fTitle = title ? title : "Read task to read Central Control report files";
+}
+
+// --------------------------------------------------------------------------
+//
+// Check whether the file header corresponds to a central control file
+// header and check for the existance of a correct version number.
+// The version number may later be used to be able to read different
+// file versions
+//
+Int_t MReportFileReadCC::CheckFileHeader()
+{
+    Int_t line = 0;
+
+    TString str;
+    str.ReadLine(*fIn);   // Read to EOF or newline
+    if (!*fIn)
+        return line;
+
+    line++;
+
+    Int_t run = -1;
+
+    // whole night report file
+    if (str==TString("[CC Report File]"))
+        run = 0;
+
+    // report file matching a single run
+    if (!str(TRegexp("^[CC Run [0-9]+ Control File]$")).IsNull())
+        run = atoi(str(TRegexp(" [0-9]+")).Data());
+
+    if (run<0)
+    {
+        *fLog << err << "ERROR - First line doesn't match '[CC Report File]' ";
+        *fLog << "nor '^[CC Run [0-9]+ Control File]$'" << endl;
+        return line;
+    }
+
+    if (fRunNumber!=-1 && fRunNumber!=run)
+    {
+        *fLog << err << "ERROR - Requested run #" << fRunNumber << " doesn't ";
+        *fLog << "match found run #" << run << endl;
+        return line;
+    }
+
+    str.ReadLine(*fIn);   // Read to EOF or newline
+    if (!*fIn)
+        return line;
+
+    if (str(TRegexp("^Arehucas Version Number [0-9]+-[0-9]$")).IsNull())
+    {
+        *fLog << err << "ERROR - Version '^Arehucas Version Number [0-9]+-[0-9]$' ";
+        *fLog << "not found in second line." << endl;
+        return line;
+    }
+    line++;
+
+    str = str(TRegexp("[0-9]+-[0-9]"));
+    str.Prepend("20");
+    str.ReplaceAll("-", "");
+
+    const Int_t ver = atoi(str.Data());
+
+    *fLog << dbg << "Report File version: <" << ver << ">" << endl;
+
+    SetVersion(ver);
+
+    return line;
+}
Index: /tags/Mars-V0.9/mreport/MReportFileReadCC.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportFileReadCC.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportFileReadCC.h	(revision 9772)
@@ -0,0 +1,22 @@
+#ifndef MARS_MReportFileReadCC
+#define MARS_MReportFileReadCC
+
+#ifndef MARS_MReportFileRead
+#include "MReportFileRead.h"
+#endif
+
+class MReportFileReadCC : public MReportFileRead
+{
+private:
+    Int_t fRunNumber;
+
+    Int_t CheckFileHeader();
+
+public:
+    MReportFileReadCC(const char *filename, const char *name=NULL, const char *title=NULL);
+    void SetRunNumber(Int_t run) { fRunNumber = run; }
+
+    ClassDef(MReportFileReadCC, 0)// Task to read the central control report file
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportHelp.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportHelp.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportHelp.cc	(revision 9772)
@@ -0,0 +1,168 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportHelp
+//
+// This is a wrapper class for MReport derived files. It provides root-like
+// access to the identifier of the report, such that this identifiers can
+// be used in hast tables to be able to speed up access to the class
+// corresponding to a report identifier. It also provides access to the
+// class by the name of the identifier.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportHelp.h"
+
+#include <TROOT.h>  // gROOT->GeClass
+#include <TClass.h> // TClass
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MReport.h"
+#include "MParList.h"
+
+ClassImp(MReportHelp);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Construtor. Takes the name of the MReport-class (eg MReportDrive) and
+// a log-stream as an argument. The log-stream is used for output in the
+// constructor  An instance of the MReport-class is created using its
+// default constructor.
+//
+MReportHelp::MReportHelp(const char *name, MLog *fLog) : fReport(NULL), fNumReports(0), fNumSkipped(0)
+{
+    TClass *cls = gROOT->GetClass(name);
+    Int_t rc = 0;
+    if (!cls)
+        rc =1;
+    else
+    {
+        if (!cls->Property())
+            rc = 5;
+        if (!cls->Size())
+            rc = 4;
+        if (!cls->IsLoaded())
+            rc = 3;
+        if (!cls->HasDefaultConstructor())
+            rc = 2;
+    }
+
+    if (rc)
+    {
+        *fLog << err << dbginf << "Cannot create new instance of class '" << name << "': ";
+        switch (rc)
+        {
+        case 1:
+            *fLog << "gROOT->GetClass() returned NULL." << endl;
+            return;
+        case 2:
+            *fLog << "no default constructor." << endl;
+            return;
+        case 3:
+            *fLog << "not loaded." << endl;
+            return;
+        case 4:
+            *fLog << "zero size." << endl;
+            return;
+        case 5:
+            *fLog << "no property." << endl;
+            return;
+        }
+    }
+
+    //
+    // create the parameter container of the the given class type
+    //
+    fReport = (MReport*)cls->New();
+}
+
+// --------------------------------------------------------------------------
+//
+// The instance of the MReport-class is deleted
+//
+MReportHelp::~MReportHelp()
+{
+    if (fReport)
+        delete fReport;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Identifier ("DRIVE-REPORT") as name. This allows
+// calling FindObject("[identifier]") in lists.
+//
+const char *MReportHelp::GetName() const
+{
+    return fReport->GetIdentifier();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the Identifier ("DRIVE-REPORT") hash value as hash value. This
+// allows faster access b usage of a THashTable
+//
+ULong_t MReportHelp::Hash() const
+{
+    return fReport->GetIdentifier().Hash();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls the Interprete function of the report and counts the number of
+// successfull interpretations.
+//
+Int_t MReportHelp::Interprete(TString &str, const MTime &start, const MTime &stop, Int_t ver)
+{
+    const Int_t rc = fReport->Interprete(str, start, stop, ver);
+
+    switch (rc)
+    {
+    case kTRUE:     fNumReports++; break;
+    case kCONTINUE: fNumSkipped++; break;
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls the Setip function for reading of the report
+//
+Bool_t MReportHelp::SetupReading(MParList &plist)
+{
+    return fReport->SetupReading(plist);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the report to the given parameter list.
+//
+void MReportHelp::AddToList(MParList &plist)
+{
+    plist.AddToList(fReport);
+}
Index: /tags/Mars-V0.9/mreport/MReportHelp.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportHelp.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportHelp.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MReportHelp
+#define MARS_MReportHelp
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+
+class TString;
+
+class MLog;
+class MTime;
+class MReport;
+class MParList;
+
+class MReportHelp : public TObject
+{
+private:
+    MReport *fReport;
+    ULong_t  fNumReports;
+    ULong_t  fNumSkipped;
+
+public:
+    MReportHelp(const char *name, MLog *fLog);
+    ~MReportHelp();
+
+    const char *GetName() const;
+    ULong_t GetNumReports() const { return fNumReports; }
+    ULong_t GetNumSkipped() const { return fNumSkipped; }
+    ULong_t Hash() const;
+    MReport *GetReport() { return fReport; }
+
+    Int_t Interprete(TString &str, const MTime &start, const MTime &stop, Int_t ver);
+
+    Bool_t SetupReading(MParList &plist);
+    
+    void AddToList(MParList &plist);
+
+    ClassDef(MReportHelp, 0) // Wrapper class for MReport to speed up finding the correct MReport-class
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportRun.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportRun.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportRun.cc	(revision 9772)
@@ -0,0 +1,100 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportRun
+//
+// This is the class interpreting and storing the RUN-REPORT information.
+//
+// PRELIMINARY!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportRun.h"
+
+#include "MLogManip.h"
+
+#include "MAstro.h"
+
+ClassImp(MReportRun);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "RUN-REPORT" No subsystem
+// is expected.
+//
+MReportRun::MReportRun() : MReport("RUN-REPORT", kFALSE), fRunNumber(-1)
+{
+    fName  = "MReportRun";
+    fTitle = "Class for RUN-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the RUN-REPORT string
+//
+Int_t MReportRun::InterpreteBody(TString &str, Int_t ver)
+{
+    const Int_t ws = str.First(' ');
+    if (ws<0)
+    {
+        *fLog << warn << "WARNING - Token not found." << endl;
+        return kCONTINUE;
+    }
+    const TString tok=str(0, ws);
+
+    str.Remove(0, ws);
+    str = str.Strip(TString::kBoth);
+
+    Int_t len, run;
+    const Int_t n=sscanf(str.Data(), "%d %n", &run, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Wrong number of arguments." << endl;
+        return kCONTINUE;
+    }
+    str.Remove(0, len);
+
+    if (tok=="START")
+    {
+        if (fRunNumber!=-1)
+            *fLog << warn << "WARNING - RUN-REPORT STOP missing for run #" << dec << fRunNumber <<  endl;
+        fRunNumber = run;
+    }
+    if (tok=="STOP")
+    {
+        if (fRunNumber==-1)
+            *fLog << warn << "WARNING - RUN-REPORT START missing for run #" << dec << fRunNumber << endl;
+        fRunNumber = -1;
+    }
+
+    Ssiz_t pos = str.First(' ');
+    if (pos<0)
+        pos = str.Length();
+    fSourceName = str(0, pos+1);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mreport/MReportRun.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportRun.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportRun.h	(revision 9772)
@@ -0,0 +1,27 @@
+#ifndef MARS_MReportRun
+#define MARS_MReportRun
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportRun : public MReport
+{
+private:
+    Int_t   fRunNumber;
+    TString fSourceName;
+
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportRun();
+
+    const TString &GetSourceName() const { return fSourceName; }
+    TString GetSourceName() { return fSourceName; }
+
+    Int_t GetRunNumber() const { return fRunNumber; }
+
+    ClassDef(MReportRun, 0) // Class for RUN-REPORT information
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportStarguider.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportStarguider.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportStarguider.cc	(revision 9772)
@@ -0,0 +1,86 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Benjamin Riegel, 01/2005 <mailto:riegel@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportStarguider
+//
+// This is the class interpreting and storing the STARG-REPORT information.
+//
+// This is the place to get the azimuth-/zenith mispointing of the telescope
+// given by the starguider-camera.
+//
+//
+//
+// Double_t fDevAz;          // [deg]   azimuth mispointing
+// Double_t fDevZd;          // [deg]   zenith  mispointing
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportStarguider.h"
+
+#include "MLogManip.h"
+
+ClassImp(MReportStarguider);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Initialize identifier to "STARG-REPORT"
+//
+MReportStarguider::MReportStarguider() : MReport("STARG-REPORT"),
+    fDevAz(0), fDevZd(0)
+{
+    fName  = "MReportStarguider";
+    fTitle = "Class for STARG-REPORT information (telescope mispointing)";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the STARG-REPORT string
+//
+Int_t MReportStarguider::InterpreteBody(TString &str, Int_t ver)
+{
+    Int_t len;
+    Int_t n=sscanf(str.Data(), "%lf %lf %n", &fDevAz, &fDevZd, &len);
+    if (n!=2)
+    {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+
+    str.Remove(0, len);
+
+     str = str.Strip(TString::kBoth);
+
+    return str.IsNull() ? kTRUE : kCONTINUE;
+}
+
+
+void MReportStarguider::Print(Option_t *o) const
+{
+    *fLog << GetDescriptor() << ": DevZd=" << fDevZd << " DevAz=" << fDevAz << endl;
+}
Index: /tags/Mars-V0.9/mreport/MReportStarguider.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportStarguider.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportStarguider.h	(revision 9772)
@@ -0,0 +1,27 @@
+#ifndef MARS_MReportStarguider
+#define MARS_MReportStarguider
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+class MReportStarguider : public MReport
+{
+private:
+    Double_t fDevAz;  // [deg]   azimuth mispointing
+    Double_t fDevZd;  // [deg]   zenith  mispointing
+
+    Int_t InterpreteBody(TString &str, Int_t ver);
+
+public:
+    MReportStarguider();
+
+    Double_t GetDevAz() const { return fDevAz; }
+    Double_t GetDevZd() const { return fDevZd; }
+
+    void Print(Option_t *o="") const;
+
+    ClassDef(MReportStarguider, 1) // Class for STARG-REPORT information
+};
+
+#endif
Index: /tags/Mars-V0.9/mreport/MReportTrigger.cc
===================================================================
--- /tags/Mars-V0.9/mreport/MReportTrigger.cc	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportTrigger.cc	(revision 9772)
@@ -0,0 +1,492 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+! 
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportTrigger
+//
+// This is the class interpreting and storing the TRIGGER-REPORT information.
+//  Updated to add IPR; data format follows TDAS 00-07 ver.6.3 jul-04
+//  http://hegra1.mppmu.mpg.de/MAGIC/private/software/doc/control/tdas0007_v6.3.ps.gz
+//  
+//  *Input:
+//
+//  The report is divided into 9 sections: 
+//  - the name of the Table                 (1 field)
+//  - the cell rates                       (32 fields)
+//  - L1 and L2 table name                 ( 2 fields)
+//  - prescaling factors                  (2x8 fields)
+//  - livetime and deadtime               (5x4 fields)
+//  - L2 output bit rates                (20 integers)
+//  - global rates (before/after presc.)    (2 floats)
+//  - 18 dummy fields                      (18 fields)
+//  - IPR                    (325 hexs + 397 integers) 
+//
+//  *Output:
+//
+//  The values read from the report string are used to fill the following 
+//  containers:
+//  - MTriggerIPR        (Individual Pixel Rates)
+//  - MTriggerCell       (Rate of trigger cells)
+//  - MTriggerBit        (Output Bits from prescaler (before and after presc.)
+//  - MTriggerPrescFact  (Prescaling factors for each bit)
+//  - MTriggerLiveTime   (Values of counters for dead/livetime)
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportTrigger.h"
+
+#include "MParList.h"
+
+#include "MLogManip.h"
+
+#include "MTriggerIPR.h"
+#include "MTriggerCell.h"
+#include "MTriggerBit.h"
+#include "MTriggerPrescFact.h"
+#include "MTriggerLiveTime.h"
+
+#include "MReportFileRead.h"
+
+ClassImp(MReportTrigger);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "TRIGGER-REPORT"
+//
+MReportTrigger::MReportTrigger() : MReport("TRIGGER-REPORT")
+{
+    fName  = "MReportTrigger";
+    fTitle = "Class for TRIGGER-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate the following objects:
+//  - MTriggerIPR
+//  - MTriggerCell
+//  - MTriggerBit
+//  - MTriggerPrescFact
+//  - MTriggerLiveTime
+//
+Bool_t MReportTrigger::SetupReading(MParList &plist)
+{
+  fIPR = (MTriggerIPR*)plist.FindCreateObj("MTriggerIPR");
+  if (!fIPR)
+    return kFALSE;
+
+  fCell = (MTriggerCell*)plist.FindCreateObj("MTriggerCell");
+  if (!fCell)
+    return kFALSE;
+
+  fBit = (MTriggerBit*)plist.FindCreateObj("MTriggerBit");
+  if (!fBit)
+    return kFALSE;
+
+  fPrescFactor = (MTriggerPrescFact*)plist.FindCreateObj("MTriggerPrescFact");
+  if (!fPrescFactor)
+    return kFALSE;
+
+  fLiveTime = (MTriggerLiveTime*)plist.FindCreateObj("MTriggerLiveTime");
+  if (!fLiveTime)
+    return kFALSE;
+  
+  return MReport::SetupReading(plist);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Cell rates section of the report
+//  Read 32 floats separated with a blank
+//
+Bool_t MReportTrigger::InterpreteCell(TString &str)
+{
+  Int_t len=0, n, i=0;
+  Int_t gsNCells=32;
+
+  for (i=0;i<gsNCells;i++)
+    {
+      n = sscanf(str.Data(), " %f %n", &fCell->fCellRate[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Cell Scaler Value #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove cell rates from report string
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Prescaling factors section of the report
+//
+Bool_t MReportTrigger::InterpretePrescFact(TString &str)
+{
+  Int_t len=0, n, i=0;
+  Int_t gsNPrescFacts=8;
+  
+  str.Remove(0, 1);
+
+  for (i=0;i<gsNPrescFacts;i++)
+    {
+    const Int_t ws = str.First(' ');
+    if (ws<=0)
+       {
+	 *fLog << warn << "WARNING - Cannot determine Prescaling factor #" << i << " descriptor" << endl;
+        return kCONTINUE;
+       }
+    TString descriptor = str(0, ws);
+    str.Remove(0, ws);
+      
+      n = sscanf(str.Data(), " %li %n", &fPrescFactor->fPrescFact[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - prescaler factor " << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove Prescal. factors from report string
+    }
+  str=str.Strip(TString::kLeading);  
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Scalers with Live-Deadtime section of the report
+//  Read 4x5 integers separated with a blank
+//  There are 5 scalers,each one with the live and deadtime.
+//  Live and deadtimes have two fields, with the most significant
+//  and less significant bits.
+//
+Bool_t MReportTrigger::InterpreteLiveTime(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNScalers=5;
+  Int_t  dLSB, dMSB,lLSB, lMSB;
+
+  for (i=0;i<gsNScalers;i++)
+    {
+      n = sscanf(str.Data(), " %d %d %d %d %n", &lLSB, &lMSB,&dLSB, &dMSB, &len);
+      if (n!=4)
+	{
+	  *fLog << warn << "WARNING - Live-Deadtime Scaler Value #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+
+      str.Remove(0, len); // Remove Live-Deadtimes from string
+
+      //convert to seconds and fill container
+      // (FIXME! only the MSB (seconds is now considered)
+      (fLiveTime->fLiveTime)[i] = lMSB;
+      (fLiveTime->fDeadTime)[i] = dMSB;      
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Bit rates section of the report
+// 20 integers. First and last two are not used
+//
+Bool_t MReportTrigger::InterpreteBit(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNBits=20;
+  
+  for (i=0;i<gsNBits;i++)
+    {
+      n = sscanf(str.Data(), " %f %n", &fBit->fBit[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Bit rate #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove output bit rates from string
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the L1 and L2 table names
+// 1String + 1Int +1 String
+//
+Bool_t MReportTrigger::InterpreteL1L2Table(TString &str)
+{
+    const Int_t wsL1 = str.First(' ');
+ 
+    if (wsL1<=0)
+       {
+        *fLog << warn << "WARNING - Cannot determine name of L1 trigger table." << endl;
+        return kCONTINUE;
+       }
+    
+    fL1Tablename = str(0, wsL1);
+    str.Remove(0, wsL1);
+
+    // remove an integer between names
+    Int_t len;
+    Int_t mi;
+    Int_t n=sscanf(str.Data(), "%d %n", &mi, &len);
+    if (n!=1)
+      {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+    str.Remove(0, len);
+
+    // L2 tablename
+    const Int_t wsL2 = str.First(' ');
+ 
+    if (wsL2<=0)
+      {
+        *fLog << warn << "WARNING - Cannot determine name of L2 trigger table." << endl;
+        return kCONTINUE;
+      }    
+    fL2Tablename = str(0, wsL2);
+    str.Remove(0,wsL2);
+    str.Strip(TString::kBoth);
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete an unused section of the report 
+// 18 integers
+//
+Bool_t MReportTrigger::InterpreteDummy(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNDummies=18;
+  Int_t dummy;  
+
+  for (i=0;i<gsNDummies;i++)
+    {
+      n = sscanf(str.Data(), " %d %n", &dummy, &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Dummy #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove dummies from report string
+
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the IPR section of the report
+//   sep-04
+//   The IPR are saved as 340 (=number of pixs in trigger area) hex numbers 
+//   and as 397 (= #pixs in inner region) dec numbers.
+//   Only the dec numbers are now saved in the MTriggerIPR container.
+//  
+
+Bool_t MReportTrigger::InterpreteIPR(TString &str)
+{
+
+  Int_t gsNhexIPR=340; //number of IPR saved in hex format
+  Int_t gsNdecIPR=397; //number of IPR saved in dec format
+  
+  // Read Individual pixel rates in hex format
+  const char *pos = str.Data();
+  const char *end = str.Data() + gsNhexIPR*8;
+  
+  Int_t i=0,n,len;
+  short dummy;
+  while (pos < end)
+    {
+      const Char_t hex[9] = { pos[0], pos[1], pos[2], pos[3],pos[4],pos[5],pos[6],pos[7],0 };
+      n = sscanf(hex, "%hx", &dummy);
+      pos+=8;
+      if (n!=1)
+        {
+	  *fLog << warn << "WARNING - Rate #" << i << " missing." << endl;
+	  return kFALSE;
+        }
+    }
+    
+  str.Remove(0, end-str.Data()); // Remove IPR hex  from report string
+  str.Strip(TString::kBoth);
+  
+  // ------  
+  // Read Individual pixel rates in dec format 
+  // and save them in the MTriggerIPR container
+  
+  for (i=0;i<gsNdecIPR;i++)
+    {
+      n = sscanf(str.Data(), " %ld %n", &fIPR->fIPR[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - IPR dec #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove IPR dec from report string      
+    }
+  
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the TRIGGER-REPORT string
+//  Read comments for details
+//
+Int_t MReportTrigger::InterpreteBody(TString &str, Int_t ver )
+{
+
+    str = str.Strip(TString::kLeading);
+ 
+    // Extract trigger table name
+    const Int_t ws = str.First(' ');
+ 
+   if (ws<=0)
+    {
+        *fLog << warn << "WARNING - Cannot determine name of trigger table." << endl;
+        return kCONTINUE;
+    }
+
+    fTablename = str(0, ws);
+    str.Remove(0, ws);
+
+    // Check the Version of CC file, and takes care of the differences
+    // introduced in the format of the report (on May 2004).
+
+    if (ver < 200405050)	
+      {
+	*fLog << warn << " WARNING - This is  an old TRIGGER-REPORT without IPRs" <<endl;
+        return InterpreteOldBody(str);
+      }
+
+    // Read the cell rates (32 fields)
+    if (!InterpreteCell(str))
+      return kCONTINUE;
+
+    // Read L1 and L2 table name (2 fields)
+    if (!InterpreteL1L2Table(str))
+      return kCONTINUE;    
+
+    // Read prescaling factors  (2x8 fields)
+    if (!InterpretePrescFact(str))
+      return kCONTINUE;
+    
+    // Read livetime and deadtime (5x4 fields)
+    if (!InterpreteLiveTime(str))
+      return kCONTINUE;
+
+    // Read L2 outout bit rates
+    if (!InterpreteBit(str))
+      return kCONTINUE;
+
+    // Read global rates (before and after prescaling)
+    Int_t len, n;
+    n = sscanf(str.Data(), " %f %f %n", &fL2BeforePrescaler, &fL2AfterPrescaler, &len);
+    if (n!=2)
+    {
+         *fLog << warn << "WARNING - Couldn't read Trigger rates." << endl;
+        return kFALSE;
+    }
+    str.Remove(0,len);
+    str.Strip(TString::kBoth);
+
+    // Read 18 dummy fields
+    if (!InterpreteDummy(str))
+      return kCONTINUE;
+
+    // Read IPR
+    if (!InterpreteIPR(str))
+      return kCONTINUE;
+
+    return str==(TString)"OVER" ? kTRUE : kCONTINUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the TRIGGER-REPORT string
+//  for OLD runs (older than may-04)
+//
+Bool_t MReportTrigger::InterpreteOldBody(TString &str)
+{
+
+  Int_t len, n;
+  Float_t fPrescalerRates[100]; 
+
+    const char *pos = str.Data();
+    for (int i=0; i<19; i++)
+      {
+        n = sscanf(pos, " %f %n", &fPrescalerRates[i], &len);
+        if (n!=1)
+	  {
+            *fLog << warn << "WARNING - Scaler Value #" << i << " missing." << endl;
+            return kCONTINUE;
+	  }
+        pos += len;
+      }
+
+    n = sscanf(pos, " %f %f %n", &fL2BeforePrescaler, &fL2AfterPrescaler, &len);    if (n!=2)
+      {
+        *fLog << warn << "WARNING - Couldn't read Trigger rates." << endl;
+        return kFALSE;
+      }
+    pos += len;
+    for (int i=0; i<11; i++)
+      {
+        Float_t dummy;
+        n = sscanf(pos, " %f %n", &dummy/*fRates[i]*/, &len);
+        if (n!=1)
+	  {
+            *fLog << warn << "WARNING - Rate #" << i << " missing." << endl;
+            return kFALSE;
+	  }
+        pos += len;
+      }
+    str.Remove(0, pos-str.Data());
+    str.Strip(TString::kBoth);
+    
+    return str==(TString)"OVER" ? kTRUE : kCONTINUE;
+}
Index: /tags/Mars-V0.9/mreport/MReportTrigger.h
===================================================================
--- /tags/Mars-V0.9/mreport/MReportTrigger.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/MReportTrigger.h	(revision 9772)
@@ -0,0 +1,60 @@
+#ifndef MARS_MReportTrigger
+#define MARS_MReportTrigger
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerIPR;
+class MTriggerCell;
+class MTriggerBit;
+class MTriggerPrescFact;
+class MTriggerLiveTime;
+
+class MReportTrigger : public MReport
+{
+private:
+  
+  Float_t fL2BeforePrescaler;       // L2 trigger rate before prescaler
+  Float_t fL2AfterPrescaler;        // L2 trigger rate after prescaler
+  TString fTablename;               // Name of the trigger table
+  TString fL1Tablename;             // Name of the L1 trigger table
+  TString fL2Tablename;             // Name of the L2 trigger table
+  
+  MTriggerBit *fBit;                //! container of the L2 prescaler rates
+  MTriggerIPR *fIPR;                //! container of the IPR
+  MTriggerCell *fCell;              //! container of the L1 cell trigger rates
+  MTriggerPrescFact *fPrescFactor;  //! container of the L2 prescaling factors
+  MTriggerLiveTime *fLiveTime;      //! container of the scaler live-deadtime
+  
+  Bool_t SetupReading(MParList &plist);
+
+  Bool_t InterpreteIPR(TString &str);
+  Bool_t InterpreteCell(TString &str);
+  Bool_t InterpreteBit(TString &str);
+  Bool_t InterpretePrescFact(TString &str);
+  Bool_t InterpreteLiveTime(TString &str);
+  Bool_t InterpreteDummy(TString &str);
+  Bool_t InterpreteL1L2Table(TString &str);
+
+  Int_t InterpreteBody(TString &str, Int_t ver);
+  
+  Bool_t InterpreteOldBody(TString &str);
+
+public:
+    MReportTrigger();
+
+    Float_t GetL2BeforePrescaler() const { return fL2BeforePrescaler; }
+    Float_t GetL2AfterPrescaler() const { return fL2AfterPrescaler; }
+    TString GetTablename() const { return fTablename; } 
+    TString GetL1Tablename() const { return fL1Tablename; } 
+    TString GetL2Tablename() const { return fL2Tablename; } 
+
+    ClassDef(MReportTrigger, 2) // Class for TRIGGER-REPORT information
+ };
+
+#endif
Index: /tags/Mars-V0.9/mreport/Makefile
===================================================================
--- /tags/Mars-V0.9/mreport/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mreport/Makefile	(revision 9772)
@@ -0,0 +1,42 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Report
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mastro -I../mcamera -I../mgui -I../mtrigger
+# mgui - MCameraDC <MCamEvent>
+
+SRCFILES = MReport.cc \
+           MReportCC.cc \
+           MReportRun.cc \
+           MReportDAQ.cc \
+           MReportHelp.cc \
+           MReportDrive.cc \
+           MReportCamera.cc \
+           MReportTrigger.cc \
+           MReportCurrents.cc \
+           MReportFileRead.cc \
+           MReportFileReadCC.cc \
+           MReportStarguider.cc
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mreport/ReportIncl.h
===================================================================
--- /tags/Mars-V0.9/mreport/ReportIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/ReportIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mreport/ReportLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mreport/ReportLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mreport/ReportLinkDef.h	(revision 9772)
@@ -0,0 +1,22 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MReport+;
+
+#pragma link C++ class MReportCC+;
+#pragma link C++ class MReportRun+;
+#pragma link C++ class MReportDAQ+;
+#pragma link C++ class MReportDrive+;
+#pragma link C++ class MReportStarguider+;
+#pragma link C++ class MReportCamera+;
+#pragma link C++ class MReportTrigger+;
+#pragma link C++ class MReportCurrents+;
+
+#pragma link C++ class MReportHelp+;
+#pragma link C++ class MReportFileRead+;
+#pragma link C++ class MReportFileReadCC+;
+
+#endif
Index: /tags/Mars-V0.9/msignal/MArrivalTimeCalc.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MArrivalTimeCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MArrivalTimeCalc.cc	(revision 9772)
@@ -0,0 +1,191 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Sebastian Raducci 12/2003 <mailto:raducci@fisica.uniud.it>
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MArrivalTimeCalc
+//
+//   This is a task that calculates the arrival times of photons. 
+//   It returns the absolute maximum of the spline that interpolates
+//   the FADC slices 
+//
+// Input Containers:
+//   MRawEvtData
+//
+// Output Containers:
+//   MArrivalTime
+//   MRawEvtData
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrivalTimeCalc.h"
+
+#include "MCubicSpline.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MRawEvtData.h"      
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MArrivalTimeCalc);
+
+using namespace std;
+
+const Byte_t MArrivalTimeCalc::fgSaturationLimit = 254;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// 
+MArrivalTimeCalc::MArrivalTimeCalc(const char *name, const char *title) 
+{
+
+    fName  = name  ? name  : "MArrivalTimeCalc";
+    fTitle = title ? title : "Calculate photons arrival time";
+    
+    SetSaturationLimit();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//  - MArrivalTimeCam
+//
+
+Int_t MArrivalTimeCalc::PreProcess(MParList *pList)
+{
+
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+    
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        return kFALSE;
+    }
+
+
+    fArrTime = (MArrivalTimeCam*)pList->FindCreateObj(AddSerialNumber("MArrivalTimeCam"));
+    if (!fArrTime)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Evaluation of the mean arrival times (spline interpolation)
+// per pixel and store them in the MArrivalTime container.
+//
+Int_t MArrivalTimeCalc::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  
+  while (pixel.Next())
+    {
+      
+      const UInt_t idx = pixel.GetPixelId();
+      Float_t time = 0.;
+
+
+      //
+      // If pixel is saturated we use LoGains
+      //
+      if ((pixel.GetMaxHiGainSample() >= fSaturationLimit) && pixel.HasLoGain())
+        {
+          
+          const Short_t nslices = fRawEvt->GetNumLoGainSamples();
+          time = Calc(pixel.GetLoGainSamples(),nslices,idx);
+        }
+      
+
+      //
+      // Use HiGains
+      //
+      else if (pixel.HasLoGain())
+        {
+          
+          const Short_t nslices = fRawEvt->GetNumHiGainSamples();
+          time = Calc(pixel.GetHiGainSamples(),nslices,idx);
+        }
+      
+      //
+      // If pixel is saturated and hasn't lo gains we do nothing, it's value remains -1
+      //
+      MArrivalTimePix &pix = (*fArrTime)[idx];
+      pix.SetArrivalTime(time,0.);
+    }
+    
+  fArrTime->SetReadyToSave();
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+// Possible Methods 
+// Case 1: MCubicSpline (3rd order spline)
+//
+Float_t MArrivalTimeCalc::Calc(const Byte_t *fadcSamples, const Short_t nslices, const UInt_t idx)
+{
+
+  //
+  // Initialize the spline
+  //
+  MCubicSpline *spline = new MCubicSpline(fadcSamples);  
+
+  //
+  // Now find the maximum  
+  //
+  Double_t abMaximum = spline->EvalAbMax();
+  Double_t maximum = spline->EvalMax();
+  const MPedestalPix &ped = (*fPedestals)[idx];
+  const Double_t pedestal = ped.GetPedestal();
+  const Double_t halfMax = (maximum + pedestal)/2.;
+  Float_t time = (halfMax > pedestal) ? (Float_t ) spline->FindVal(halfMax,abMaximum,'l'): 0.0;
+  delete spline;
+  return time;
+    
+}
+
Index: /tags/Mars-V0.9/msignal/MArrivalTimeCalc.h
===================================================================
--- /tags/Mars-V0.9/msignal/MArrivalTimeCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MArrivalTimeCalc.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MArrivalTimeCalc
+#define MARS_MArrivalTimeCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+class MArrivalTimeCam;
+class MPedestalCam;
+class MArrivalTimeCalc : public MTask
+{
+
+  static const Byte_t fgSaturationLimit; // Default for fSaturationLimit
+  Byte_t              fSaturationLimit; // Maximum FADC counts before being considered as saturated
+  
+  MRawEvtData    *fRawEvt;     // raw event data (time slices)
+  MRawRunHeader  *fRunHeader;  // RunHeader information
+  MPedestalCam   *fPedestals;  // pedestal information
+  
+  MArrivalTimeCam *fArrTime;   // Container with the photons arrival times
+  
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess() {return kTRUE;}
+  
+  Float_t Calc(const Byte_t *fadcSamples, const Short_t nslices, const UInt_t idx);
+  
+public:
+    MArrivalTimeCalc(const char *name=NULL, const char *title=NULL);
+    ~MArrivalTimeCalc(){}
+ 
+    void SetSaturationLimit(const Byte_t lim=fgSaturationLimit) { fSaturationLimit = lim; }
+    
+    ClassDef(MArrivalTimeCalc, 0)   // Task to calculate Arrival Times from raw data
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/msignal/MArrivalTimeCalc2.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MArrivalTimeCalc2.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MArrivalTimeCalc2.cc	(revision 9772)
@@ -0,0 +1,259 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Hendrik Bartko, 02/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MArrivalTimeCalc2
+//
+//  Calculates the arrival time as the mean time of the fWindowSize time slices
+//  which have the highest integral content.
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrivalTimeCalc2.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+
+ClassImp(MArrivalTimeCalc2);
+
+using namespace std;
+
+const Byte_t MArrivalTimeCalc2::fgSaturationLimit = 254;
+const Byte_t MArrivalTimeCalc2::fgFirst  =  0;
+const Byte_t MArrivalTimeCalc2::fgLast   = 14;
+const Byte_t MArrivalTimeCalc2::fgWindowSize = 6;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MArrivalTimeCalc2::MArrivalTimeCalc2(const char *name, const char *title)
+  : fSaturationLimit(fgSaturationLimit)
+{
+
+    fName  = name  ? name  : "MArrivalTimeCalc2";
+    fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+    AddToBranchList("MRawEvtData.*");
+
+    SetRange();
+}
+
+void MArrivalTimeCalc2::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast, Byte_t windowsize)
+{
+    fNumHiGainSamples = hilast-hifirst+1;
+    fNumLoGainSamples = lolast-lofirst+1;
+
+    fHiGainFirst = hifirst;
+    fLoGainFirst = lofirst;
+
+    fWindowSize = windowsize & ~1;
+
+    if (fWindowSize != windowsize)
+      *fLog << warn << "MArrivalTimeCalc2::SetRange - window size has to be even, set to: " << int(fWindowSize) << " samples " << endl;
+
+    if (fWindowSize<2) 
+    {
+      fWindowSize = 2;
+      *fLog << warn << "MArrivalTimeCalc2::SetRange - window size set to two samples" << endl;
+    }
+
+    if (fWindowSize > fNumHiGainSamples)
+    {
+      fWindowSize = fNumLoGainSamples & ~1;
+      *fLog << warn << "MArrivalTimeCalc2::SetRange - window size set to " << int(fWindowSize) << " samples " << endl;
+    }
+
+    if (fWindowSize > fNumLoGainSamples)
+    {
+      fWindowSize = fNumLoGainSamples & ~1;
+      *fLog << warn << "MArrivalTimeCalc2::SetRange - window size set to " << int(fWindowSize) << " samples " << endl;
+    }
+
+    fWindowSizeSqrt = TMath::Sqrt((Float_t)fWindowSize);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MArrivalTimeCalc2::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        return kFALSE;
+    }
+
+    fArrivalTime = (MArrivalTimeCam*)pList->FindCreateObj(AddSerialNumber("MArrivalTimeCam"));
+    if (!fArrivalTime)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+void MArrivalTimeCalc2::FindSignalTime(Byte_t *ptr, Byte_t size, Float_t &time, Float_t &deltatime, Int_t &sat, Float_t pedes, Float_t pedrms) const
+{
+    const Byte_t *end = ptr + size;
+
+    Int_t sum=0;    // integral content of the actual window
+    Int_t max = 0;  // highest integral content of all windows
+
+    //
+    // Calculate the sum of the first fWindowSize slices
+    //
+    sat = 0;
+    Byte_t *p = ptr;
+
+    while (p<ptr+fWindowSize)
+    {
+        sum += *p;
+        if (*p++ >= fSaturationLimit)
+            sat++;
+    }
+
+    //
+    // Check for saturation in all other slices
+    //
+    while (p<end)
+        if (*p++ >= fSaturationLimit)
+            sat++;
+
+    //
+    // Calculate the i-th sum as
+    //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+    // This is fast and accurate (because we are using int's)
+    //
+    max=sum;
+    Byte_t *ptrmax=ptr;  // pointer to the first slice of the maximum window
+
+    for (p=ptr; p+fWindowSize<end; p++)
+    {
+        sum += *(p+fWindowSize) - *p;
+		
+	if (sum>max)
+	{
+	  max = sum;
+	  ptrmax = p+1;
+	}
+    }
+
+    // now calculate the time for the maximum window
+    Int_t timesignalsum = 0;
+    Int_t timesquaredsum =0;
+    Int_t timesum =0;
+
+    for (p=ptrmax; p < ptrmax + fWindowSize; p++)
+    {
+        timesignalsum += *p*(p-ptr);
+        timesum += p-ptr;
+        timesquaredsum  += (p-ptr)*(p-ptr);
+    }
+
+    const Float_t pedsubsum = max - fWindowSize*pedes;
+    const Float_t pedsubtimesignalsum = timesignalsum - timesum*pedes;
+
+    time      = pedsubsum != 0 ? pedsubtimesignalsum / pedsubsum : 1;
+    deltatime = pedsubsum != 0 ? pedrms / pedsubsum * sqrt(timesquaredsum - fWindowSize*time) : 1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculates the arrival time as the mean time of the fWindowSize time slices
+//  which have the highest integral content.
+//
+Int_t MArrivalTimeCalc2::Process()
+{
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    Int_t sat=0;
+    while (pixel.Next())
+    {
+        //
+        // Find signal in hi- and lo-gain
+        //
+        Float_t timehi, timelo, deltatimehi, deltatimelo;
+        Int_t sathi, satlo;
+
+	//
+        // Take correspodning pedestal
+        //
+        const Int_t pixid = pixel.GetPixelId();
+
+	const MPedestalPix  &ped = (*fPedestals)[pixid];
+
+	MArrivalTimePix &pix = (*fArrivalTime)[pixid];
+
+	const Float_t pedes  = ped.GetPedestal();
+	const Float_t pedrms = ped.GetPedestalRms();
+
+	FindSignalTime(pixel.GetHiGainSamples()+fHiGainFirst, fNumHiGainSamples, timehi, deltatimehi, sathi, pedes, pedrms);
+        FindSignalTime(pixel.GetLoGainSamples()+fLoGainFirst, fNumLoGainSamples, timelo, deltatimelo, satlo, pedes, pedrms);
+
+        if (satlo)
+            sat++;
+
+        pix.SetArrivalTime(timehi+ Float_t(fHiGainFirst), deltatimehi, timelo + Float_t(fLoGainFirst), deltatimelo); 
+	pix.SetGainSaturation(sathi, sathi, satlo);
+    }
+
+    fArrivalTime->SetReadyToSave();
+
+    //
+    // Print a warning if event has saturationg lo-gains
+    //
+    //    if (sat)
+    //        *fLog << warn << "WARNING - Lo Gain saturated in " << sat << " pixels." << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/msignal/MArrivalTimeCalc2.h
===================================================================
--- /tags/Mars-V0.9/msignal/MArrivalTimeCalc2.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MArrivalTimeCalc2.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MArrivalTimeCalc2
+#define MARS_MArrivalTimeCalc2
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalCam;
+class MArrivalTimeCam;
+
+class MArrivalTimeCalc2 : public MTask
+{
+private:
+    static const Byte_t fgSaturationLimit;
+    static const Byte_t fgFirst;
+    static const Byte_t fgLast;
+    static const Byte_t fgWindowSize;
+
+    MPedestalCam        *fPedestals;    // Pedestals of all pixels in the camera
+
+    MRawEvtData         *fRawEvt;       // raw event data (time slices)
+    MRawRunHeader       *fRunHeader;    // RunHeader information
+
+    
+    MArrivalTimeCam        *fArrivalTime;  // Arrival Time of FADC sample
+     
+  
+    Byte_t  fHiGainFirst;       // First hi gain to be used
+    Byte_t  fLoGainFirst;       // First lo gain to be used
+
+    Byte_t  fNumHiGainSamples;  // Number of hi gain to be used
+    Byte_t  fNumLoGainSamples;  // Number of lo gain to be used
+
+    Byte_t  fWindowSize;            // Number of gains in window
+    Float_t fWindowSizeSqrt;        // Sqaure root of number of gains in window
+
+    Byte_t  fSaturationLimit;
+
+    void   FindSignalTime(Byte_t *ptr, Byte_t size, Float_t &time,  Float_t &deltatime, Int_t &sat, Float_t pedes, Float_t pedrms) const;
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+public:
+    MArrivalTimeCalc2(const char *name=NULL, const char *title=NULL);
+
+    void SetRange(Byte_t hifirst=fgFirst, Byte_t hilast=fgLast, Byte_t lofirst=fgFirst, Byte_t lolast=fgLast, Byte_t windowsize=fgWindowSize);
+    void SetSaturationLimit(Byte_t lim) { fSaturationLimit = lim; }
+
+    ClassDef(MArrivalTimeCalc2, 0) // Calculates the arrival time as the mean time of the fWindowSize time slices
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/msignal/MArrivalTimeCam.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MArrivalTimeCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MArrivalTimeCam.cc	(revision 9772)
@@ -0,0 +1,170 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  12/2003 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko 02/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MArrivalTimeCam
+//
+// Hold the ArrivalTime information for all pixels in the camera
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MArrivalTimeCam.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrivalTimePix.h"
+
+ClassImp(MArrivalTimeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates a MArrivalTimePix object for each pixel
+//
+MArrivalTimeCam::MArrivalTimeCam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MArrivalTimeCam";
+    fTitle = title ? title : "Storage container for all Extracted Signal Information in the camera";
+
+    fArray = new TClonesArray("MArrivalTimePix", 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the array conatining the pixel pedest information
+//
+MArrivalTimeCam::~MArrivalTimeCam()
+{
+    delete fArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// Distribute logging stream to all childs
+//
+void MArrivalTimeCam::SetLogStream(MLog *lg)
+{
+    fArray->ForEach(MParContainer, SetLogStream)(lg);
+    MParContainer::SetLogStream(lg);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MArrivalTimeCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MArrivalTimeCam
+//
+Int_t MArrivalTimeCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel index)
+//
+MArrivalTimePix &MArrivalTimeCam::operator[](Int_t i)
+{
+    return *static_cast<MArrivalTimePix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel index)
+//
+const MArrivalTimePix &MArrivalTimeCam::operator[](Int_t i) const
+{
+    return *static_cast<MArrivalTimePix*>(fArray->UncheckedAt(i));
+}
+
+void MArrivalTimeCam::Clear(Option_t *o)
+{
+    fArray->ForEach(TObject, Clear)();
+}
+
+void MArrivalTimeCam::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << endl;
+    int idx = -1;
+
+    TIter Next(fArray);
+    MArrivalTimePix *pix;
+    while ((pix=(MArrivalTimePix*)Next()))
+    {
+        idx++;
+
+        if (!pix->IsValid())
+            continue;
+
+        *fLog << idx << ": ";
+	pix->Print();
+    }
+}
+
+Bool_t MArrivalTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    switch (type)
+    {
+    case 0:
+        val = (*this)[idx].GetArrivalTimeHiGain();
+        break;
+    case 1:
+        val = (*this)[idx].GetArrivalTimeHiGainError();
+        break;
+    case 2:
+        val = (*this)[idx].GetArrivalTimeLoGain();
+        break;
+    case 3:
+        val = (*this)[idx].GetArrivalTimeLoGainError();
+        break;
+    case 4:
+    case 6:
+	if ((*this)[idx].GetNumHiGainSaturated() > 0)
+	    val = (*this)[idx].GetArrivalTimeLoGain();
+	else
+	    val = (*this)[idx].GetArrivalTimeHiGain();
+        break;
+    default:
+	return kFALSE;
+    }
+    return val>=0;
+}
+
+void MArrivalTimeCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MArrivalTimeCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars-V0.9/msignal/MArrivalTimeCam.h
===================================================================
--- /tags/Mars-V0.9/msignal/MArrivalTimeCam.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MArrivalTimeCam.h	(revision 9772)
@@ -0,0 +1,68 @@
+#ifndef MARS_MArrivalTimeCam
+#define MARS_MArrivalTimeCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+class MArrivalTimePix;
+
+class MArrivalTimeCam : public MParContainer, public MCamEvent
+{
+private:
+    TClonesArray *fArray; //-> FIXME: Change TClonesArray away from a pointer?
+
+    Byte_t fFirstUsedSliceHiGain;
+    Byte_t fFirstUsedSliceLoGain;
+
+    Byte_t fLastUsedSliceHiGain;
+    Byte_t fLastUsedSliceLoGain;
+
+public:
+
+    MArrivalTimeCam(const char *name=NULL, const char *title=NULL);
+    ~MArrivalTimeCam();
+
+    void Print(Option_t *o="") const;
+    void Clear(Option_t *o="");
+    void SetLogStream(MLog *lg);
+    void Reset() { Clear(); }
+
+    void InitSize(const UInt_t i);
+    Int_t GetSize() const;
+
+    Byte_t GetNumUsedFADCSlices() const       { return fLastUsedSliceHiGain-fFirstUsedSliceHiGain+1; }
+    Byte_t GetNumUsedHiGainFADCSlices() const { return fLastUsedSliceHiGain-fFirstUsedSliceHiGain+1; }
+    Byte_t GetNumUsedLoGainFADCSlices() const { return fLastUsedSliceLoGain-fFirstUsedSliceLoGain+1; }
+
+    Byte_t GetFirstUsedSliceHiGain() const    { return fFirstUsedSliceHiGain; }
+    Byte_t GetLastUsedSliceHiGain() const     { return fLastUsedSliceHiGain; }
+
+    Byte_t GetFirstUsedSliceLoGain() const    { return fFirstUsedSliceLoGain; }
+    Byte_t GetLastUsedSliceLoGain() const     { return fLastUsedSliceLoGain; }
+
+    void   SetUsedFADCSlices(Byte_t firsth, Byte_t lasth, 
+                             Byte_t firstl, Byte_t lastl)
+    {
+      fFirstUsedSliceHiGain    = firsth;
+      fLastUsedSliceHiGain     = lasth;
+      fFirstUsedSliceLoGain    = firstl;
+      fLastUsedSliceLoGain     = lastl;
+    }
+
+    MArrivalTimePix &operator[](Int_t i);
+    const MArrivalTimePix &operator[](Int_t i) const;
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MArrivalTimeCam, 1)	// Storage Container for the ArrivalTime in the camera
+};
+
+#endif
+
Index: /tags/Mars-V0.9/msignal/MArrivalTimePix.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MArrivalTimePix.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MArrivalTimePix.cc	(revision 9772)
@@ -0,0 +1,111 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  12/2003 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko 02/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MArrivalTimePix
+//
+// This is the storage container to hold informations about the ArrivalTime
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MArrivalTimePix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MArrivalTimePix);
+
+using namespace std;
+
+static const Float_t gkSignalInitializer = 99999.9;
+
+// ------------------------------------------------------------------------
+//
+// MArrivalTimePix holds the ArrivalTime (HiGain and LoGain) 
+// of the FADC slices and its error. 
+//
+// Additionally, the number of saturated HiGain and LoGain Slices are stored. 
+// 
+// Default values for the ArrivalTime are: 99999.9 
+//
+MArrivalTimePix::MArrivalTimePix(const char* name, const char* title)
+{
+  fName  = name  ? name  : "MArrivalTimePix";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MArrivalTimePix::Clear(Option_t *o)
+{
+  fArrivalTimeHiGain      = gkSignalInitializer;
+  fArrivalTimeHiGainError = -1;
+  fArrivalTimeLoGain      = gkSignalInitializer;
+  fArrivalTimeLoGainError = -1;
+  
+  fNumHiGainSaturated = 0;
+  fNumLoGainSaturated = 0;
+}
+
+void MArrivalTimePix::SetArrivalTime(Float_t sig, Float_t sigerr)   
+{
+  fArrivalTimeHiGain      = sig; 
+  fArrivalTimeHiGainError = sigerr;
+}
+
+void MArrivalTimePix::SetArrivalTime(Float_t sighi, Float_t sighierr,
+                                     Float_t siglo, Float_t sigloerr)   
+{
+  fArrivalTimeHiGain = sighi;
+  fArrivalTimeHiGainError = sighierr;
+  fArrivalTimeLoGain = siglo;
+  fArrivalTimeLoGainError = sigloerr;
+}
+
+Bool_t MArrivalTimePix::IsValid() const
+{
+    return (!IsLoGainUsed() && fArrivalTimeHiGainError >= 0) || (IsLoGainUsed() && fArrivalTimeLoGainError >= 0);
+}
+
+void MArrivalTimePix::SetGainSaturation(Bool_t sat, Byte_t higain, Byte_t logain) 
+{
+
+  fNumHiGainSaturated = higain; 
+  fNumLoGainSaturated = logain;
+}
+
+void MArrivalTimePix::Print(Option_t *o) const
+{
+    *fLog << " Signal: " << fArrivalTimeHiGain
+        << " +- " << fArrivalTimeHiGainError
+        << " Nr. Sat. Hi Gain: " <<  fNumHiGainSaturated
+        << " Nr. Sat. Lo Gain: " <<  fNumLoGainSaturated
+        << endl;
+}
Index: /tags/Mars-V0.9/msignal/MArrivalTimePix.h
===================================================================
--- /tags/Mars-V0.9/msignal/MArrivalTimePix.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MArrivalTimePix.h	(revision 9772)
@@ -0,0 +1,46 @@
+#ifndef MARS_MArrivalTimePix
+#define MARS_MArrivalTimePix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MArrivalTimePix : public MParContainer
+{
+private:
+  Float_t fArrivalTimeHiGain;      // mean value of the ArrivalTime
+  Float_t fArrivalTimeHiGainError; // error of the mean value of the ArrivalTime
+  Float_t fArrivalTimeLoGain;      // mean value of the ArrivalTime
+  Float_t fArrivalTimeLoGainError; // error of the mean value of the ArrivalTime
+
+  Byte_t fNumHiGainSaturated;
+  Byte_t fNumLoGainSaturated;
+
+public:
+    MArrivalTimePix(const char* name=NULL, const char* title=NULL);
+
+    void Clear(Option_t *o="");
+    void Print(Option_t *o="") const;
+
+    // Setter
+    void SetArrivalTime(Float_t sig, Float_t sigerr);
+    void SetArrivalTime(Float_t sighi, Float_t sighierr,Float_t siglo, Float_t sigloerr);
+    void SetGainSaturation(Bool_t sat, Byte_t higain, Byte_t logain);
+
+    // Getter
+    Float_t GetArrivalTimeHiGain()      const { return fArrivalTimeHiGain; }
+    Float_t GetArrivalTimeHiGainError() const { return fArrivalTimeHiGainError; }
+
+    Float_t GetArrivalTimeLoGain()      const { return fArrivalTimeLoGain; }
+    Float_t GetArrivalTimeLoGainError() const { return fArrivalTimeLoGainError; }
+
+    Byte_t GetNumHiGainSaturated()      const { return fNumHiGainSaturated; }
+    Byte_t GetNumLoGainSaturated()      const { return fNumLoGainSaturated; }
+
+    Bool_t IsLoGainUsed()               const { return fNumHiGainSaturated > 0; }
+    Bool_t IsValid()                    const;   
+
+    ClassDef(MArrivalTimePix, 1)	// Storage Container for ArrivalTime information of one pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MC_calibration_weights_UV.dat
===================================================================
--- /tags/Mars-V0.9/msignal/MC_calibration_weights_UV.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MC_calibration_weights_UV.dat	(revision 9772)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time) 
+.144275 -0.325693
+0.0365677 -0.618716
+-0.131366 -0.820721
+-0.298134 -0.939382
+-0.473474 -0.943559
+-0.596868 -0.886693
+-0.700565 -0.803137
+-0.753448 -0.69643
+-0.820552 -0.495037
+-0.927318 -0.202966
+-1.06201 0.464466
+-0.886816 1.16679
+-0.540286 1.71193
+-0.188573 2.06458
+0.213454 2.1621
+0.498775 2.22228
+0.798589 2.31987
+0.943493 2.27996
+1.15367 2.01435
+1.50645 1.76439
+1.96441 1.52311
+2.27059 0.985492
+2.38228 0.279391
+2.33178 -0.329482
+2.19421 -0.803578
+2.05111 -1.17768
+1.87349 -1.50399
+1.77825 -1.77376
+1.60108 -1.85125
+1.24554 -1.9492
+0.721033 -2.06902
+0.242888 -1.83369
+-0.0543716 -1.26806
+-0.172805 -0.801241
+-0.219495 -0.362599
+-0.224623 -0.148551
+-0.229815 -0.043156
+-0.240542 0.0983054
+-0.241541 0.286027
+-0.184459 0.344107
+-0.0821337 0.387117
+0.0123865 0.309283
+0.0425298 0.12844
+0.0479833 0.0450856
+0.0393249 -0.0305098
+0.0294022 -0.0464634
+0.0265841 -0.00154482
+0.0404535 -0.0920062
+0.0291382 -0.194845
+-0.0131835 -0.140969
+-0.0712672 -0.0987324
+-0.0942702 -0.0155111
+-0.0787429 0.0429505
+-0.0810953 0.0181423
+-0.0727905 0.0499553
+-0.063661 0.0436562
+-0.064196 0.0209196
+-0.0645723 0.0570405
+-0.0589239 0.0830538
+-0.0363984 0.0507948
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time) 
+.144275 -0.325693
+0.0365677 -0.618716
+-0.131366 -0.820721
+-0.298134 -0.939382
+-0.473474 -0.943559
+-0.596868 -0.886693
+-0.700565 -0.803137
+-0.753448 -0.69643
+-0.820552 -0.495037
+-0.927318 -0.202966
+-1.06201 0.464466
+-0.886816 1.16679
+-0.540286 1.71193
+-0.188573 2.06458
+0.213454 2.1621
+0.498775 2.22228
+0.798589 2.31987
+0.943493 2.27996
+1.15367 2.01435
+1.50645 1.76439
+1.96441 1.52311
+2.27059 0.985492
+2.38228 0.279391
+2.33178 -0.329482
+2.19421 -0.803578
+2.05111 -1.17768
+1.87349 -1.50399
+1.77825 -1.77376
+1.60108 -1.85125
+1.24554 -1.9492
+0.721033 -2.06902
+0.242888 -1.83369
+-0.0543716 -1.26806
+-0.172805 -0.801241
+-0.219495 -0.362599
+-0.224623 -0.148551
+-0.229815 -0.043156
+-0.240542 0.0983054
+-0.241541 0.286027
+-0.184459 0.344107
+-0.0821337 0.387117
+0.0123865 0.309283
+0.0425298 0.12844
+0.0479833 0.0450856
+0.0393249 -0.0305098
+0.0294022 -0.0464634
+0.0265841 -0.00154482
+0.0404535 -0.0920062
+0.0291382 -0.194845
+-0.0131835 -0.140969
+-0.0712672 -0.0987324
+-0.0942702 -0.0155111
+-0.0787429 0.0429505
+-0.0810953 0.0181423
+-0.0727905 0.0499553
+-0.063661 0.0436562
+-0.064196 0.0209196
+-0.0645723 0.0570405
+-0.0589239 0.0830538
+-0.0363984 0.0507948
Index: /tags/Mars-V0.9/msignal/MC_weights.dat
===================================================================
--- /tags/Mars-V0.9/msignal/MC_weights.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MC_weights.dat	(revision 9772)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.192984 -0.132188
+0.187675 -0.364451
+0.00639783 -0.707397
+-0.271769 -0.782098
+-0.433992 -0.65188
+-0.506172 -0.520614
+-0.545446 -0.427854
+-0.577498 -0.363785
+-0.616145 -0.311347
+-0.692899 -0.24808
+-0.876771 -0.000954896
+-0.928628 0.555715
+-0.599175 1.43251
+0.0173513 1.74512
+0.405197 1.54212
+0.587034 1.30229
+0.690943 1.14398
+0.779392 1.06243
+0.882825 1.0425
+1.08657 1.13784
+1.35004 1.22203
+1.61967 1.12679
+1.96215 0.718709
+2.009 0.117553
+1.91269 -0.249042
+1.83371 -0.456316
+1.77704 -0.626166
+1.71784 -0.814262
+1.62782 -1.0514
+1.38952 -1.44307
+1.04176 -1.85012
+0.586193 -2.06507
+-0.116844 -1.75114
+-0.378321 -0.918193
+-0.329607 -0.381089
+-0.269525 -0.145645
+-0.245833 -0.035611
+-0.243367 0.0319466
+-0.246348 0.0900604
+-0.230933 0.158395
+-0.200143 0.237071
+-0.142623 0.29298
+-0.0413303 0.255565
+-0.00517261 0.132402
+-0.0159254 0.0535915
+-0.0269696 0.0219578
+-0.0310746 0.0102674
+-0.030882 0.00589682
+-0.028929 0.0044246
+-0.0274387 0.00685789
+0.0088518 0.0211059
+0.011564 0.0345383
+0.0276757 0.0606363
+0.051436 0.065177
+0.0652995 0.0526172
+0.0713662 0.0397629
+0.0744256 0.0299231
+0.0765017 0.0223275
+0.0782008 0.0160109
+0.0799735 0.0112381
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0138311 -0.0165919
+0.0117372 -0.0354005
+0.00232654 -0.0581018
+-0.00791094 -0.0631271
+-0.0131845 -0.0558022
+-0.0154786 -0.0480772
+-0.0171358 -0.0420274
+-0.0199068 -0.0340744
+-0.02688 -0.0117278
+-0.0404328 0.0754397
+-0.0357035 0.342673
+0.00409834 0.849274
+0.248584 1.52181
+0.528673 1.67974
+0.67261 1.47068
+0.735023 1.24965
+0.778865 1.10395
+0.832049 1.02856
+0.907609 1.00924
+1.07304 1.09208
+1.25051 1.14906
+1.37475 1.0253
+1.52056 0.653112
+1.53175 0.163076
+1.49683 -0.15273
+1.47188 -0.344252
+1.45258 -0.50129
+1.42348 -0.670218
+1.3673 -0.87756
+1.19832 -1.20557
+0.99973 -1.53248
+0.808836 -1.68211
+0.533208 -1.45238
+0.446023 -0.900265
+0.459037 -0.529769
+0.470945 -0.368053
+0.465845 -0.313525
+0.446981 -0.311926
+0.415815 -0.342317
+0.348688 -0.425439
+0.271752 -0.495437
+0.211195 -0.503879
+0.131582 -0.413276
+0.109187 -0.245156
+0.114005 -0.139006
+0.117671 -0.0939116
+0.116527 -0.078572
+0.11177 -0.0772896
+0.103901 -0.0840098
+0.0871027 -0.102357
+0.0758618 -0.119019
+0.0611863 -0.118991
+0.0430436 -0.0930814
+0.0390695 -0.0517162
+0.0409257 -0.027711
+0.0420581 -0.0186558
+0.0419035 -0.0164813
+0.0408279 -0.0174564
+0.0389147 -0.0202082
+0.0345678 -0.025232
Index: /tags/Mars-V0.9/msignal/MC_weights4.dat
===================================================================
--- /tags/Mars-V0.9/msignal/MC_weights4.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MC_weights4.dat	(revision 9772)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.483688 -0.498619
+-0.52105 -0.409251
+-0.551668 -0.347732
+-0.588621 -0.297486
+-0.661896 -0.2371
+-0.754507 -0.0572828
+-0.809786 0.380243
+-0.569956 1.15886
+-0.0188177 1.56188
+0.366116 1.43988
+0.560145 1.24361
+0.659133 1.09171
+0.743506 1.01359
+0.842199 0.994443
+1.03659 1.08537
+1.27803 1.17221
+1.52592 1.11221
+1.87086 0.786182
+1.9451 0.195753
+1.84721 -0.202808
+1.74892 -0.438476
+1.6951 -0.598997
+1.63854 -0.777709
+1.55247 -1.00352
+1.32498 -1.37711
+1.00846 -1.77543
+0.590272 -2.03408
+-0.111902 -1.86442
+-0.42886 -1.06692
+-0.383767 -0.46555
+-0.258546 -0.122314
+-0.237253 -0.0243087
+-0.234402 0.036867
+-0.236007 0.0905807
+-0.22029 0.156137
+-0.191449 0.235519
+-0.139186 0.309597
+-0.0270788 0.320152
+0.0388423 0.213534
+0.0424905 0.116622
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.0150435 -0.0456535
+-0.0167019 -0.0398625
+-0.0194073 -0.032228
+-0.0261603 -0.0107884
+-0.0393003 0.072764
+-0.0383678 0.323756
+0.000454566 0.807731
+0.23557 1.45054
+0.504239 1.60174
+0.641895 1.40233
+0.696427 1.19531
+0.740101 1.0546
+0.791986 0.981974
+0.86479 0.963146
+1.02308 1.04186
+1.19338 1.09617
+1.31232 0.977824
+1.45116 0.622149
+1.4609 0.154384
+1.42695 -0.14665
+1.4151 -0.336941
+1.39615 -0.485034
+1.36751 -0.645756
+1.31284 -0.843784
+1.14997 -1.15775
+0.956626 -1.4693
+0.772909 -1.61173
+0.5089 -1.39031
+0.426731 -0.860608
+0.440367 -0.505876
+0.459554 -0.35905
+0.453541 -0.305066
+0.434575 -0.303057
+0.403893 -0.332238
+0.338482 -0.412519
+0.268138 -0.482693
+0.208943 -0.491638
+0.131208 -0.403936
+0.109532 -0.240282
+0.114424 -0.136913
Index: /tags/Mars-V0.9/msignal/MC_weights_2GSamples.dat
===================================================================
--- /tags/Mars-V0.9/msignal/MC_weights_2GSamples.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MC_weights_2GSamples.dat	(revision 9772)
@@ -0,0 +1,206 @@
+# High Gain Weights: 10 10
+# (Amplitude)  (Time) 
+-0.58121 -5.87941
+-0.6795 -5.93277
+-0.778453 -5.94334
+-0.877262 -5.90919
+-0.975084 -5.82862
+-1.07106 -5.70014
+-1.16428 -5.52262
+-1.25386 -5.29528
+-1.33889 -5.01745
+-1.41845 -4.68897
+-1.10123 -0.503345
+-1.1055 0.00732161
+-1.10071 0.538021
+-1.08651 1.08556
+-1.06265 1.6465
+-1.0289 2.21712
+-0.985169 2.79381
+-0.931382 3.3729
+-0.867577 3.95017
+-0.793869 4.52156
+-0.732148 6.94018
+-0.61223 7.48841
+-0.482946 8.00584
+-0.344906 8.48814
+-0.198799 8.93154
+-0.0453747 9.33193
+0.114514 9.68562
+0.27998 9.98929
+0.450051 10.2395
+0.623709 10.4337
+1.27929 9.89078
+1.44405 9.91358
+1.60887 9.87489
+1.7726 9.77404
+1.9341 9.61064
+2.09222 9.38519
+2.24585 9.09791
+2.39386 8.74972
+2.5352 8.34248
+2.6688 7.87747
+2.20159 7.6767
+2.32457 7.09547
+2.43719 6.46977
+2.53867 5.80405
+2.62833 5.10291
+2.70558 4.37122
+2.76995 3.6143
+2.82107 2.83714
+2.85865 2.04486
+2.88252 1.24321
+2.73623 -0.842288
+2.71582 -1.62074
+2.68205 -2.38851
+2.63517 -3.14004
+2.57555 -3.87047
+2.50362 -4.57514
+2.41992 -5.24919
+2.32509 -5.88822
+2.21982 -6.48816
+2.10491 -7.04516
+2.41839 -8.75222
+2.269 -9.20297
+2.1124 -9.59137
+1.94975 -9.91647
+1.78221 -10.1768
+1.61098 -10.372
+1.43725 -10.5021
+1.26219 -10.5673
+1.08697 -10.5684
+0.912718 -10.5064
+0.894181 -10.3883
+0.722625 -10.2278
+0.554397 -10.0119
+0.390485 -9.74353
+0.231815 -9.42622
+0.0792163 -9.0635
+-0.0665269 -8.65917
+-0.204746 -8.21739
+-0.334828 -7.74192
+-0.456247 -7.237
+-0.939311 -4.14822
+-1.00319 -3.52754
+-1.05625 -2.90491
+-1.0985 -2.28475
+-1.13004 -1.67152
+-1.15106 -1.06907
+-1.16181 -0.481082
+-1.16263 0.0887083
+-1.15391 0.636921
+-1.13612 1.16048
+-1.28655 4.74683
+-1.20495 5.05336
+-1.11851 5.30847
+-1.02818 5.5127
+-0.934869 5.66709
+-0.839486 5.77285
+-0.742903 5.83146
+-0.645946 5.84479
+-0.549406 5.81487
+-0.454032 5.74392
+# Low Gain Weights: 10 10
+# (Amplitude)  (Time) 
+-0.58121 -5.87941
+-0.6795 -5.93277
+-0.778453 -5.94334
+-0.877262 -5.90919
+-0.975084 -5.82862
+-1.07106 -5.70014
+-1.16428 -5.52262
+-1.25386 -5.29528
+-1.33889 -5.01745
+-1.41845 -4.68897
+-1.10123 -0.503345
+-1.1055 0.00732161
+-1.10071 0.538021
+-1.08651 1.08556
+-1.06265 1.6465
+-1.0289 2.21712
+-0.985169 2.79381
+-0.931382 3.3729
+-0.867577 3.95017
+-0.793869 4.52156
+-0.732148 6.94018
+-0.61223 7.48841
+-0.482946 8.00584
+-0.344906 8.48814
+-0.198799 8.93154
+-0.0453747 9.33193
+0.114514 9.68562
+0.27998 9.98929
+0.450051 10.2395
+0.623709 10.4337
+1.27929 9.89078
+1.44405 9.91358
+1.60887 9.87489
+1.7726 9.77404
+1.9341 9.61064
+2.09222 9.38519
+2.24585 9.09791
+2.39386 8.74972
+2.5352 8.34248
+2.6688 7.87747
+2.20159 7.6767
+2.32457 7.09547
+2.43719 6.46977
+2.53867 5.80405
+2.62833 5.10291
+2.70558 4.37122
+2.76995 3.6143
+2.82107 2.83714
+2.85865 2.04486
+2.88252 1.24321
+2.73623 -0.842288
+2.71582 -1.62074
+2.68205 -2.38851
+2.63517 -3.14004
+2.57555 -3.87047
+2.50362 -4.57514
+2.41992 -5.24919
+2.32509 -5.88822
+2.21982 -6.48816
+2.10491 -7.04516
+2.41839 -8.75222
+2.269 -9.20297
+2.1124 -9.59137
+1.94975 -9.91647
+1.78221 -10.1768
+1.61098 -10.372
+1.43725 -10.5021
+1.26219 -10.5673
+1.08697 -10.5684
+0.912718 -10.5064
+0.894181 -10.3883
+0.722625 -10.2278
+0.554397 -10.0119
+0.390485 -9.74353
+0.231815 -9.42622
+0.0792163 -9.0635
+-0.0665269 -8.65917
+-0.204746 -8.21739
+-0.334828 -7.74192
+-0.456247 -7.237
+-0.939311 -4.14822
+-1.00319 -3.52754
+-1.05625 -2.90491
+-1.0985 -2.28475
+-1.13004 -1.67152
+-1.15106 -1.06907
+-1.16181 -0.481082
+-1.16263 0.0887083
+-1.15391 0.636921
+-1.13612 1.16048
+-1.28655 4.74683
+-1.20495 5.05336
+-1.11851 5.30847
+-1.02818 5.5127
+-0.934869 5.66709
+-0.839486 5.77285
+-0.742903 5.83146
+-0.645946 5.84479
+-0.549406 5.81487
+-0.454032 5.74392 
+
+
Index: /tags/Mars-V0.9/msignal/MExtractAmplitudeSpline.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractAmplitudeSpline.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractAmplitudeSpline.cc	(revision 9772)
@@ -0,0 +1,644 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug       05/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeSpline
+//
+//   Fast Spline extractor using a cubic spline algorithm of Numerical Recipes. 
+//   It returns the integral below the interpolating spline. 
+// 
+//   Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//         to modify the ranges. Ranges have to be an even number. In case of odd 
+//         ranges, the last slice will be reduced by one.
+//
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  3 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractAmplitudeSpline.h"
+
+#include "MExtractedSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractAmplitudeSpline);
+
+using namespace std;
+
+const Byte_t  MExtractAmplitudeSpline::fgHiGainFirst  = 2;
+const Byte_t  MExtractAmplitudeSpline::fgHiGainLast   = 14;
+const Byte_t  MExtractAmplitudeSpline::fgLoGainFirst  = 3;
+const Byte_t  MExtractAmplitudeSpline::fgLoGainLast   = 14;
+const Float_t MExtractAmplitudeSpline::fgResolution   = 0.003;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+MExtractAmplitudeSpline::MExtractAmplitudeSpline(const char *name, const char *title) 
+    : fHiGainSignal(NULL), fLoGainSignal(NULL),
+      fHiGainFirstDeriv(NULL), fLoGainFirstDeriv(NULL),
+      fHiGainSecondDeriv(NULL), fLoGainSecondDeriv(NULL)
+{
+
+  fName  = name  ? name  : "MExtractAmplitudeSpline";
+  fTitle = title ? title : "Signal Extractor for a fixed FADC window using a fast spline";
+
+  SetResolution();
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+MExtractAmplitudeSpline::~MExtractAmplitudeSpline()
+{
+  
+  if (fHiGainSignal)
+    delete [] fHiGainSignal;
+  if (fLoGainSignal)
+    delete [] fLoGainSignal;
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fLoGainFirstDeriv)
+    delete [] fLoGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+  if (fLoGainSecondDeriv)
+    delete [] fLoGainSecondDeriv;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Checks: 
+// - if the window defined by (fHiGainLast-fHiGainFirst-1) are odd, subtract one
+// - if the window defined by (fLoGainLast-fLoGainFirst-1) are odd, subtract one
+// - if the Hi Gain window is smaller than 2, set fHiGainLast to fHiGainFirst+1
+// - if the Lo Gain window is smaller than 2, set fLoGainLast to fLoGainFirst+1
+// 
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)(fHiGainLast-fHiGainFirst+1)
+// - fNumLoGainSamples to: (Float_t)(fLoGainLast-fLoGainFirst+1)
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractAmplitudeSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  fNumHiGainSamples = 2.;
+  fNumLoGainSamples = lolast == 0 ? 0. : 2.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+
+  fHiLoLast  = 0;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit
+//
+// Calls:
+// - MExtractor::ReInit(pList);
+// - fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+// 
+// Deletes all arrays, if not NULL
+// Creates new arrays according to the extraction range
+//
+Bool_t MExtractAmplitudeSpline::ReInit(MParList *pList)
+{
+
+  if (!MExtractor::ReInit(pList))
+    return kFALSE;
+
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+  if (fHiGainSignal)
+    delete [] fHiGainSignal;
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+  if (fLoGainSignal)
+    delete [] fLoGainSignal;
+  if (fLoGainFirstDeriv)
+    delete [] fLoGainFirstDeriv;
+  if (fLoGainSecondDeriv)
+    delete [] fLoGainSecondDeriv;
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1 + fHiLoLast;
+
+  fHiGainSignal      = new Float_t[range];
+  memset(fHiGainSignal,0,range*sizeof(Float_t));
+  fHiGainFirstDeriv  = new Float_t[range];
+  memset(fHiGainFirstDeriv,0,range*sizeof(Float_t));
+  fHiGainSecondDeriv = new Float_t[range];
+  memset(fHiGainSecondDeriv,0,range*sizeof(Float_t));
+
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() << ": Using for High-Gain Extraction " << range
+        << " FADC samples from " 
+        << Form("%s%2i%s"," High Gain slice ",(Int_t)fHiGainFirst," to (including) ")
+        << Form("%s%2i",fHiLoLast ? "Low Gain slice " : " High Gain slice ",
+                fHiLoLast ?  (Int_t)fHiLoLast : (Int_t)fHiGainLast ) 
+        << endl;
+
+  range = fLoGainLast ? fLoGainLast - fLoGainFirst + 1 : 0;
+
+  fLoGainSignal = new Float_t[range];
+  memset(fLoGainSignal,0,range*sizeof(Float_t));
+  fLoGainFirstDeriv  = new Float_t[range];
+  memset(fLoGainFirstDeriv,0,range*sizeof(Float_t));
+  fLoGainSecondDeriv = new Float_t[range];
+  memset(fLoGainSecondDeriv,0,range*sizeof(Float_t));
+  
+  *fLog << endl;
+  *fLog << inf << GetDescriptor() << ": Using for Low-Gain Extraction " << range
+        << " FADC samples from " 
+        << Form("%s%2i%s%2i"," Low Gain slice ",(Int_t)fLoGainFirst,
+                " to (including) ",(Int_t)fLoGainLast) << endl;
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+// - If fHiLoLast is not 0, loop also from logain to (logain+fHiLoLast)
+// - Sum up contents of logain
+// - If *logain is greater than fSaturationLimit, raise sat by 1
+//
+void MExtractAmplitudeSpline::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const
+{
+  
+  Int_t count   = 0;
+  Float_t abmaxpos = 0.;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+  Byte_t *end = ptr + range;
+  Byte_t *p     = ptr;
+  //
+  // Check for saturation in all other slices
+  //
+  while (++p<end)
+    {
+      
+      fHiGainSignal[count] = (Float_t)*p;
+      
+      if (*p > max)
+        {
+          max    = *p;
+          maxpos =  count;
+        }
+      
+      count++;
+      
+      if (*p >= fSaturationLimit)
+        {
+          sat++;
+              break;
+        }
+    }
+  
+  if (fHiLoLast != 0)
+    {
+      
+      p    = logain;
+      end  = logain + fHiLoLast + 1;
+      
+      while (p<end)
+        {
+          
+          fHiGainSignal[count] = (Float_t)*p;
+
+          if (*p > max)
+            {
+              max    = *p;
+              maxpos =  count;
+            }
+          
+          range++;
+          count++;
+
+          if (*p++ >= fSaturationLimit)
+            {
+              sat++;
+              break;
+            }
+        }
+    }
+
+  //
+  // allow one saturated slice 
+  //
+  if (sat > 1)
+    return;
+
+  //
+  // Don't start if the maxpos is too close to the left limit.
+  //
+  if (maxpos < 2)
+    return;
+
+  Float_t pp;
+  fHiGainSecondDeriv[0] = 0.;
+  fHiGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      pp = fHiGainSecondDeriv[i-1] + 4.;
+      fHiGainSecondDeriv[i] = -1.0/pp;
+      fHiGainFirstDeriv [i] = fHiGainSignal[i+1] - fHiGainSignal[i] - fHiGainSignal[i] + fHiGainSignal[i-1];
+      fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+      p++;
+    }
+
+  fHiGainSecondDeriv[range-1] = 0.;
+  for (Int_t k=range-2;k>=0;k--)
+    fHiGainSecondDeriv[k] = (fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k])/6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = fHiGainSignal[klo];
+  Float_t khicont = fHiGainSignal[khi];
+  sum       = khicont;
+  abmaxpos  = lower;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1. If no maximum is found, go to 
+  // interval maxpos+1.
+  //
+  while (x<upper-0.3)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+
+      if (y > sum)
+        {
+          sum      = y;
+          abmaxpos = x;
+        }
+    }
+
+  if (abmaxpos > upper-0.1)
+    {
+      
+      upper = (Float_t)maxpos+1;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = fHiGainSignal[klo];
+      khicont = fHiGainSignal[khi];
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+            + (b*b*b-b)*fHiGainSecondDeriv[khi];
+          
+          if (y > sum)
+            {
+              sum    = y;
+              abmaxpos = x;
+            }
+        }
+    }
+
+ const Float_t up = abmaxpos+step-0.055;
+ const Float_t lo = abmaxpos-step+0.055;
+ const Float_t maxpossave = abmaxpos;
+ 
+ x     = abmaxpos;
+ a     = upper - x;
+ b     = x - lower;
+
+  step  = 0.04; // step size of 83 ps 
+
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > sum)
+        {
+          sum    = y;
+          abmaxpos = x;
+        }
+    }
+
+ if (abmaxpos < klo + 0.02)
+    {
+      klo--;
+      khi--;
+      klocont = fHiGainSignal[klo];
+      khicont = fHiGainSignal[khi];
+      upper--;
+      lower--;
+    }
+ 
+  x     = maxpossave;
+  a     = upper - x;
+  b     = x - lower;
+
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > sum)
+        sum      = y;
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractAmplitudeSpline::FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const
+{
+  
+  Int_t count   = 0;
+  Float_t abmaxpos = 0.;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+  
+  Int_t range = fLoGainLast - fLoGainFirst + 1;
+  Byte_t *end = ptr + range;
+  Byte_t *p   = ptr;
+  //
+  // Check for saturation in all other slices
+  //
+  while (++p<end)
+    {
+      
+      fLoGainSignal[count] = (Float_t)*p;
+      
+      if (*p > max)
+        {
+          max    = *p;
+          maxpos =  count;
+        }
+      
+      range++;
+      count++;
+      
+      if (*p >= fSaturationLimit)
+        {
+          sat++;
+              break;
+        }
+    }
+  
+
+  //
+  // allow one saturated slice 
+  //
+  if (sat > 1)
+    return;
+
+  //
+  // Don't start if the maxpos is too close to the left limit.
+  //
+  if (maxpos < 2)
+    return;
+
+  Float_t pp;
+  fLoGainSecondDeriv[0] = 0.;
+  fLoGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      pp = fLoGainSecondDeriv[i-1] + 4.;
+      fLoGainSecondDeriv[i] = -1.0/pp;
+      fLoGainFirstDeriv [i] = fLoGainSignal[i+1] - fLoGainSignal[i] - fLoGainSignal[i] + fLoGainSignal[i-1];
+      fLoGainFirstDeriv [i] = (6.0*fLoGainFirstDeriv[i]-fLoGainFirstDeriv[i-1])/pp;
+      p++;
+    }
+
+  fLoGainSecondDeriv[range-1] = 0.;
+  for (Int_t k=range-2;k>=0;k--)
+    fLoGainSecondDeriv[k] = (fLoGainSecondDeriv[k]*fLoGainSecondDeriv[k+1] + fLoGainFirstDeriv[k])/6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = fLoGainSignal[klo];
+  Float_t khicont = fLoGainSignal[khi];
+  sum       = khicont;
+  abmaxpos  = lower;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1. If no maximum is found, go to 
+  // interval maxpos+1.
+  //
+  while (x<upper-0.3)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+
+      if (y > sum)
+        {
+          sum      = y;
+          abmaxpos = x;
+        }
+    }
+
+  if (abmaxpos > upper-0.1)
+    {
+      
+      upper = (Float_t)maxpos+1;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = fLoGainSignal[klo];
+      khicont = fLoGainSignal[khi];
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+            + (b*b*b-b)*fLoGainSecondDeriv[khi];
+          
+          if (y > sum)
+            {
+              sum    = y;
+              abmaxpos = x;
+            }
+        }
+    }
+
+ const Float_t up = abmaxpos+step-0.055;
+ const Float_t lo = abmaxpos-step+0.055;
+ const Float_t maxpossave = abmaxpos;
+ 
+ x     = abmaxpos;
+ a     = upper - x;
+ b     = x - lower;
+
+  step  = 0.04; // step size of 83 ps 
+
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > sum)
+        {
+          sum    = y;
+          abmaxpos = x;
+        }
+    }
+
+ if (abmaxpos < klo + 0.02)
+    {
+      klo--;
+      khi--;
+      klocont = fLoGainSignal[klo];
+      khicont = fLoGainSignal[khi];
+      upper--;
+      lower--;
+    }
+ 
+  x     = maxpossave;
+  a     = upper - x;
+  b     = x - lower;
+
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > sum)
+        sum      = y;
+    }
+}
+
Index: /tags/Mars-V0.9/msignal/MExtractAmplitudeSpline.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractAmplitudeSpline.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractAmplitudeSpline.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MExtractAmplitudeSpline
+#define MARS_MExtractAmplitudeSpline
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractAmplitudeSpline : public MExtractor
+{
+
+private:
+  
+  static const Byte_t  fgHiGainFirst;    // Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t  fgHiGainLast;     // Default for fHiGainLast   (now set to: 14)
+  static const Byte_t  fgLoGainFirst;    // Default for fLOGainFirst  (now set to: 3)
+  static const Byte_t  fgLoGainLast;     // Default for fLoGainLast   (now set to: 14)
+  static const Float_t fgResolution;     // Default for fResolution   (now set to: 0.003)
+
+  Float_t *fHiGainSignal;                     // Need fast access to the signals in a float way
+  Float_t *fLoGainSignal;                     // Need fast access to the signals in a float way  
+  Float_t *fHiGainFirstDeriv;
+  Float_t *fLoGainFirstDeriv;  
+  Float_t *fHiGainSecondDeriv;
+  Float_t *fLoGainSecondDeriv;  
+
+  Float_t fResolution;                        // The time resolution in FADC units
+  
+  Bool_t ReInit    (MParList *pList);
+  
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const;
+
+public:
+
+  MExtractAmplitudeSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractAmplitudeSpline();
+  
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+  void SetResolution(Float_t f=fgResolution)     { fResolution = f;  }
+  
+  ClassDef(MExtractAmplitudeSpline, 0)   // Task to Extract the Amplitude using a Fast Spline
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/msignal/MExtractBlindPixel.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractBlindPixel.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractBlindPixel.cc	(revision 9772)
@@ -0,0 +1,768 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractBlindPixel
+//
+//  Extracts the signal from a fixed window in a given range.
+//
+//    Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//    to modify the ranges. The "low-gain" ranges are used for the NSB rejection 
+//    whereas the high-gain ranges for blind pixel signal extraction. "High-gain" 
+//    ranges can extend to the slices stored as "low-gain" in MRawEvtPixelIter
+//
+//    Defaults are: 
+// 
+//     fHiGainFirst =  fgHiGainFirst =  10 
+//     fHiGainLast  =  fgHiGainLast  =  29
+//     fLoGainFirst =  fgLoGainFirst =  0 
+//     fLoGainLast  =  fgLoGainLast  =  7
+//
+//  The switches: 
+//  - SetExtractionType ( kAmplitude ) and  SetExtractionType ( kIntegral ) 
+//    can be used to choose between amplitude extraction (using a spline) and
+//    summed integral. 
+//  - SetExtractionType ( kFilter    ) 
+//    can be used to apply a filter discarding events passing over a threshold 
+//    defined in fNSBFilterLimit
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractBlindPixel.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalBlindPixel.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MExtractBlindPixel);
+
+using namespace std;
+
+const UInt_t  MExtractBlindPixel::fgBlindPixelIdx    = 559;
+const Byte_t  MExtractBlindPixel::fgHiGainFirst      =  10;
+const Byte_t  MExtractBlindPixel::fgHiGainLast       =  19;
+const Byte_t  MExtractBlindPixel::fgLoGainFirst      =   0;
+const Byte_t  MExtractBlindPixel::fgLoGainLast       =   7;
+const Int_t   MExtractBlindPixel::fgNSBFilterLimit   =  70;
+const Float_t MExtractBlindPixel::fgResolution       = 0.003;
+const Float_t MExtractBlindPixel::gkOverflow         = 300.;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes:
+// - fBlindPixelIdx to fgBlindPixelIdx
+// - fNSBFilterLimit to fgNSBFilterLimit
+// - fResolution to fgResolution
+// - fExtractionType to 0.
+//
+// Calls:
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+//
+MExtractBlindPixel::MExtractBlindPixel(const char *name, const char *title)
+    : fHiGainSignal(NULL),
+      fHiGainFirstDeriv(NULL), 
+      fHiGainSecondDeriv(NULL),
+      fDataType(0)
+{
+  
+  fName  = name  ? name  : "MExtractBlindPixel";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+  
+  SetResolution();
+  SetNSBFilterLimit();
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+  
+  SetNumBlindPixels();
+
+  Clear();
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor: 
+// 
+// - Deletes, (if not NULL):
+//   fHiGainSignal;
+//   fHiGainFirstDeriv;
+//   fHiGainSecondDeriv;
+// 
+MExtractBlindPixel::~MExtractBlindPixel()
+{
+
+  if (fHiGainSignal)
+    delete [] fHiGainSignal;
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Clear
+//
+// Initializes:
+// - fBlindPixelIdx to 0
+// - fExtractionType to 0
+// 
+// Calls:
+// - SetBlindPixelIdx()
+// 
+// Deletes and sets to NULL (if exists):
+// - fHiGainSignal
+// - fHiGainFirstDeriv
+// - fHiGainSecondDeriv
+//
+void MExtractBlindPixel::Clear( const Option_t *o)
+{
+
+  fExtractionType = 0;
+
+  fBlindPixelIdx.Set(0);
+  SetBlindPixelIdx();
+
+  if (fHiGainSignal)
+    {
+      delete [] fHiGainSignal;
+      fHiGainSignal = NULL;
+    }
+  if (fHiGainFirstDeriv)
+    {
+      delete [] fHiGainFirstDeriv;
+      fHiGainFirstDeriv = NULL;
+    }
+  if (fHiGainSecondDeriv)
+    {
+      delete [] fHiGainSecondDeriv;
+      fHiGainSecondDeriv = NULL;
+    }
+
+}
+
+void MExtractBlindPixel::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  fNumHiGainSamples = (Float_t)(fHiGainLast-fHiGainFirst+1);
+  if (lolast)
+    fNumLoGainSamples = (Float_t)(fLoGainLast-fLoGainFirst+1);
+  else
+    fNumLoGainSamples = 0.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);  
+  
+  fHiLoFirst = 0;
+  fHiLoLast  = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls: 
+// - MExtractor::PreProcess(pList)
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedBlindPixel
+//
+Int_t MExtractBlindPixel::PreProcess(MParList *pList)
+{
+
+  if (!MExtractor::PreProcess(pList))
+    return kFALSE;
+
+  fBlindPixel = (MExtractedSignalBlindPixel*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalBlindPixel"));
+  if (!fBlindPixel)
+    return kFALSE;
+
+  if (IsDataType(kRawEvt2))
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData2"));
+  else
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+
+  if (!fRawEvt)
+    {
+      *fLog << err << GetDescriptor() 
+            << Form("%s%s",IsDataType(kRawEvt2) ? "MRawEvtData2" : "MRawEvtData",
+                    " not found... aborting.") << endl;
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------- //
+//
+// The ReInit searches for:
+// -  MRawRunHeader::GetNumSamplesHiGain()
+// -  MRawRunHeader::GetNumSamplesLoGain()
+//
+// In case that the variables fHiGainLast and fLoGainLast are smaller than 
+// the even part of the number of samples obtained from the run header, a
+// warning is given an the range is set back accordingly. A call to:  
+// - SetRange(fHiGainFirst, fHiGainLast-diff, fLoGainFirst, fLoGainLast) or 
+// - SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast-diff) 
+// is performed in that case. The variable diff means here the difference 
+// between the requested range (fHiGainLast) and the available one. Note that 
+// the functions SetRange() are mostly overloaded and perform more checks, 
+// modifying the ranges again, if necessary.
+//
+Bool_t MExtractBlindPixel::ReInit(MParList *pList)
+{
+  
+  if (fHiGainSignal)
+    delete [] fHiGainSignal;
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+
+  for (Int_t i=0;i<fNumBlindPixels;i++)
+    fBlindPixel->SetBlindPixelIdx(fBlindPixelIdx.At(i),i);
+
+  fBlindPixel->SetExtractionType(fExtractionType);
+
+  for (Int_t i=0;i<fBlindPixelIdx.GetSize();i++)
+  {
+
+      MPedestalPix &pedpix  = (*fPedestals)[fBlindPixelIdx.At(i)];    
+      
+      if (&pedpix)
+      {
+	  fBlindPixel->SetPed      ( pedpix.GetPedestal()   * fNumLoGainSamples, i );
+	  fBlindPixel->SetPedErr   ( pedpix.GetPedestalRms()* fNumLoGainSamples 
+                                 / TMath::Sqrt((Float_t)fPedestals->GetTotalEntries()), i );
+	  fBlindPixel->SetPedRms   ( pedpix.GetPedestalRms()* TMath::Sqrt((Float_t)fNumLoGainSamples), i );
+	  fBlindPixel->SetPedRmsErr( fBlindPixel->GetPedErr()/2., i );
+      }
+  }
+
+  const Int_t higainsamples = fRunHeader->GetNumSamplesHiGain();
+  const Int_t logainsamples = fRunHeader->GetNumSamplesLoGain();
+  Int_t lastavailable       =  higainsamples-1;
+
+  if (logainsamples)
+    {
+      //
+      // If the signal is searched entirely in the low-gain range, have 
+      // to skip the higain completely. This is steered by the variable fHiLoFirst
+      // 
+      const Int_t firstdesired   = (Int_t)fHiGainFirst;
+  
+      if (firstdesired > lastavailable)
+        {
+          const Int_t diff = firstdesired - lastavailable;
+          *fLog << endl;
+          *fLog << warn << "First Hi Gain slice " << (int)fHiGainFirst << " out of range [0,";
+          *fLog << lastavailable << "]... start at slice " << diff << " of the Lo Gain " << endl;
+          
+          fHiLoFirst   = diff;
+        }
+    }
+  
+  const Int_t lastdesired = (Int_t)fHiGainLast;
+
+  if (lastdesired > lastavailable)
+    {
+      Int_t diff     = lastdesired - lastavailable;
+      lastavailable += logainsamples ? logainsamples-1 : 0;
+      
+      if (lastdesired > lastavailable)
+        {
+          *fLog << endl;
+          *fLog << "Last Hi Gain slice " << (int)fHiGainLast << " out of range [0,";
+          *fLog << lastavailable << "]... reduce upper limit by " << diff << endl;
+          diff = logainsamples;
+        }
+
+      fHiGainLast = higainsamples - 1;
+      fHiLoLast   = logainsamples ? diff : 0;
+    }
+
+  const Int_t range = fHiLoFirst ? fHiLoLast - fHiLoFirst + 1 : fHiGainLast - fHiGainFirst + fHiLoLast + 1;
+
+  fHiGainSignal      = new Float_t[range];
+  memset(fHiGainSignal,0,range*sizeof(Float_t));
+  fHiGainFirstDeriv  = new Float_t[range];
+  memset(fHiGainFirstDeriv,0,range*sizeof(Float_t));
+  fHiGainSecondDeriv = new Float_t[range];
+  memset(fHiGainSecondDeriv,0,range*sizeof(Float_t));
+
+  *fLog << endl;
+  *fLog << inf << "Extracting "
+      << (IsExtractionType(kAmplitude) ? "Amplitude" : " Integral")
+      << " using " << range << " FADC samples from "
+      << (fHiLoFirst ? "Low Gain slice" : " High Gain slice")
+      << (fHiLoFirst ? (Int_t)fHiLoFirst : (Int_t)fHiGainFirst)
+      << " to (including) "
+      << (fHiLoLast ? "Low Gain slice" : "High Gain slice")
+      << (fHiLoLast ?  (Int_t)fHiLoLast-1 : (Int_t)fHiGainLast)
+      << endl;
+
+  if (IsExtractionType(kFilter))
+    *fLog << inf << "Will use Filter using "
+	  << (Int_t)(fLoGainLast-fLoGainFirst+1) << " FADC slices"
+	  << " from High Gain slice " << (Int_t)fLoGainFirst
+	  << " to High Gain slice " << (Int_t)fLoGainLast << endl;
+
+  fBlindPixel->SetUsedFADCSlices(fHiGainFirst, range);
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - If fHiLoLast is set, loop from logain to (logain+fHiLoLast)
+// - Add contents of *logain to sum
+// 
+void MExtractBlindPixel::FindIntegral(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat)
+{
+
+  Int_t summ = 0;
+  Byte_t *p   = ptr;
+  Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+  if (fHiLoFirst == 0)
+    {
+
+      while (p<end)
+        {
+          summ += *ptr;
+          
+          if (*p++ >= fSaturationLimit)
+            sat++;
+        }
+      
+    }
+  
+  p   = logain + fHiLoFirst;  
+  end = logain + fHiLoLast;
+  while (p<end)
+    {
+      summ += *p;
+
+      if (*p++ >= fSaturationLimit)
+            sat++;
+    }
+
+  sum = (Float_t)summ;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalPhe:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - If fHiLoLast is set, loop from logain to (logain+fHiLoLast)
+// - Add contents of *logain to sum
+// 
+void MExtractBlindPixel::FindAmplitude(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) 
+{
+
+  Int_t range   = 0;
+  Int_t count   = 0;
+  Float_t abmaxpos = 0.;
+  Byte_t *p     = ptr;
+  Byte_t *end;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+  Int_t summ   = 0;
+
+  if (fHiLoFirst == 0)
+    {
+
+      range = fHiGainLast - fHiGainFirst + 1;
+
+      end   = ptr + range;
+      //
+      // Check for saturation in all other slices
+      //
+      while (p++<end)
+        {
+          
+          fHiGainSignal[count] = (Float_t)*p;
+          summ += *p;
+
+          if (*p > max)
+            {
+              max    = *p;
+              maxpos =  count;
+            }
+          
+          count++;
+
+          if (*p >= fSaturationLimit)
+              sat++;
+        }
+    }
+  
+  if (fHiLoLast != 0)
+    {
+      
+      p    = logain + fHiLoFirst;
+      end  = logain + fHiLoLast;
+      
+      while (p<end)
+        {
+          
+          fHiGainSignal[count] = (Float_t)*p;
+          summ += *p;
+
+          if (*p > max)
+            {
+              max    = *p;
+              maxpos =  count;
+            }
+          
+          range++;
+          count++;
+
+          if (*p++ >= fSaturationLimit)
+              sat++;
+        }
+    }
+
+  //
+  // allow one saturated slice 
+  //
+  if (sat > 1)
+  {
+    sum = gkOverflow;
+    return;
+  }
+
+  //
+  // Don't start if the maxpos is too close to the left limit.
+  //
+  if (maxpos < 2)
+  {
+    sum = (Float_t)max;
+    return;
+  }
+
+  Float_t pp;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      pp = fHiGainSecondDeriv[i-1] + 4.;
+      fHiGainSecondDeriv[i] = -1.0/pp;
+      fHiGainFirstDeriv [i] = fHiGainSignal[i+1] - fHiGainSignal[i] - fHiGainSignal[i] + fHiGainSignal[i-1];
+      fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+      p++;
+    }
+
+  fHiGainSecondDeriv[range-1] = 0.;
+  for (Int_t k=range-2;k>=0;k--)
+    fHiGainSecondDeriv[k] = (fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k])/6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = fHiGainSignal[klo];
+  Float_t khicont = fHiGainSignal[khi];
+  sum       = (Float_t)khicont;
+  abmaxpos  = lower;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1. If no maximum is found, go to 
+  // interval maxpos+1.
+  //
+  while (x<upper-0.3)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+
+      if (y > sum)
+        {
+          sum      = y;
+          abmaxpos = x;
+        }
+    }
+
+  if (abmaxpos > upper-0.1)
+    {
+      
+      upper = (Float_t)maxpos+1;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = fHiGainSignal[klo];
+      khicont = fHiGainSignal[khi];
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+            + (b*b*b-b)*fHiGainSecondDeriv[khi];
+          
+          if (y > sum)
+            {
+              sum    = y;
+              abmaxpos = x;
+            }
+        }
+    }
+
+ const Float_t up = abmaxpos+step-0.055;
+ const Float_t lo = abmaxpos-step+0.055;
+ const Float_t maxpossave = abmaxpos;
+ 
+ x     = abmaxpos;
+ a     = upper - x;
+ b     = x - lower;
+
+  step  = 0.04; // step size of 83 ps 
+
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > sum)
+        {
+          sum    = y;
+          abmaxpos = x;
+        }
+    }
+
+ if (abmaxpos < klo + 0.02)
+    {
+      klo--;
+      khi--;
+      klocont = fHiGainSignal[klo];
+      khicont = fHiGainSignal[khi];
+      upper--;
+      lower--;
+    }
+ 
+  x     = maxpossave;
+  a     = upper - x;
+  b     = x - lower;
+
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > sum)
+        {
+          sum    = y;
+          abmaxpos = x;
+        }
+    }
+
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalFilter:
+//
+// - Loop from ptr to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractBlindPixel::FindSignalFilter(Byte_t *ptr, Int_t &sum, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr + fLoGainLast - fLoGainFirst + 1;
+  
+  while (ptr<end)
+    {
+      sum += *ptr;
+      
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedBlindPixel container.
+//
+Int_t MExtractBlindPixel::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  
+  fBlindPixel->Clear();
+  
+  for (Int_t id=0;id<fBlindPixelIdx.GetSize();id++)
+    {
+  
+      pixel.Jump(fBlindPixelIdx[id]);
+      
+      Int_t sum   = 0;
+      Byte_t sat  = 0;
+
+      if (IsExtractionType(kFilter))
+      {
+
+	  FindSignalFilter(pixel.GetHiGainSamples()+fLoGainFirst, sum, sat);
+	  
+	  if (sum > fNSBFilterLimit)
+	  {
+	      fBlindPixel->SetExtractedSignal(-1.,id);
+	      fBlindPixel->SetNumSaturated(sat,id);
+	      fBlindPixel->SetReadyToSave();
+	      continue;
+	  }
+
+          sum = 0;
+          if (pixel.HasLoGain())
+            FindSignalFilter(pixel.GetLoGainSamples(), sum, sat);          
+
+          /*
+          if (fModified)
+            {
+              if (sum > fNSBFilterLimit)
+                {
+                  fBlindPixel->SetExtractedSignal(-1.,id);
+                  fBlindPixel->SetNumSaturated(sat,id);
+                  fBlindPixel->SetReadyToSave();
+                  continue;
+                }
+            }
+          */
+      }
+      
+      Float_t newsum = 0.;
+      sat = 0;
+      
+      if (IsExtractionType(kAmplitude))
+	FindAmplitude   (pixel.GetHiGainSamples()+fHiGainFirst, pixel.GetLoGainSamples(), newsum, sat);
+      else
+	FindIntegral    (pixel.GetHiGainSamples()+fHiGainFirst, pixel.GetLoGainSamples(), newsum, sat);
+  
+
+      fBlindPixel->SetExtractedSignal(newsum,id);
+      fBlindPixel->SetNumSaturated(sat,id);
+    }
+  
+  fBlindPixel->SetReadyToSave();
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------------------
+//
+// Returns true if the Data type. Available are: kAmplitude, kIntegral and kFilter
+// The flags kIntegral and kFilter may be set both. 
+//
+Bool_t MExtractBlindPixel::IsDataType( const DataType_t typ )
+{
+  
+  return TESTBIT( fDataType, typ );
+
+}
+
+// ------------------------------------------------------------------------------------
+//
+// Returns true if the extraction type. Available are: kAmplitude, kIntegral and kFilter
+// The flags kIntegral and kFilter may be set both. 
+//
+Bool_t MExtractBlindPixel::IsExtractionType( const ExtractionType_t typ )
+{
+  
+  return TESTBIT( fExtractionType, typ );
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the Data type. Available are: kAmplitude and kIntegral
+//
+void MExtractBlindPixel::SetDataType( const DataType_t typ )
+{
+  SETBIT( fDataType, typ );
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets the extraction type. Available are: kAmplitude and kIntegral
+//
+void MExtractBlindPixel::SetExtractionType( const ExtractionType_t typ )
+{
+  SETBIT( fExtractionType, typ );
+}
Index: /tags/Mars-V0.9/msignal/MExtractBlindPixel.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractBlindPixel.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractBlindPixel.h	(revision 9772)
@@ -0,0 +1,85 @@
+#ifndef MARS_MExtractBlindPixel
+#define MARS_MExtractBlindPixel
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MExtractedSignalBlindPixel;
+class MExtractBlindPixel : public MExtractor
+{
+private:
+
+  static const UInt_t  fgBlindPixelIdx;    //! Default blind pixels index before modification run
+  static const Byte_t  fgHiGainFirst;      //! Default First FADC slice Hi-Gain Signal (currently set to: 10   ) 
+  static const Byte_t  fgHiGainLast;       //! Default Last  FADC slice Hi-Gain Signal (currently set to: 29   ) 
+  static const Byte_t  fgLoGainFirst;      //! Default First FADC slice Filter         (currently set to: 0    ) 
+  static const Byte_t  fgLoGainLast;       //! Default Last  FADC slice Filter         (currently set to: 6    ) 
+  static const Int_t   fgNSBFilterLimit;   //! Default for fNSBFilterLimit
+  static const Float_t fgResolution;       //! Default for fResolution         (currently set to: 0.003)
+  static const Float_t gkOverflow;         //! Default sum to assign overflow in case of saturation
+
+  MExtractedSignalBlindPixel *fBlindPixel; // Extracted signal of the Blind Pixel
+
+  Byte_t   fHiLoFirst;                     // If not zero, start extraction from fHiLoFirst slice of Low-Gain
+
+  Float_t *fHiGainSignal;                  // Need fast access to the signals in a float way
+  Float_t *fHiGainFirstDeriv;              // First derivative at intersection
+  Float_t *fHiGainSecondDeriv;             // Second derivative at intersection
+
+  Float_t fResolution;                     // The time resolution in FADC units
+  TArrayI fBlindPixelIdx;                  // Array holding the IDs of the blind pixel(s)
+  Int_t   fNSBFilterLimit;                 // Limit of sum of FADC slices for filter part
+
+  Byte_t  fExtractionType;                 // What extraction type has been chosen?
+  Byte_t  fDataType;                       // What data container type is needed?  
+  Int_t   fNumBlindPixels;                 // Current number of blind pixels
+
+public:
+  enum ExtractionType_t { kAmplitude, kIntegral, kFilter };
+  enum DataType_t       { kRawEvt, kRawEvt2 };
+
+private:
+  void FindAmplitude   (Byte_t *firstused, Byte_t *lowgain, Float_t &sum, Byte_t &sat);
+  void FindIntegral    (Byte_t *firstused, Byte_t *lowgain, Float_t &sum, Byte_t &sat);
+  void FindSignalFilter(Byte_t *ptr,                          Int_t &sum, Byte_t &sat) const;
+  
+  Int_t  PreProcess(MParList *pList);
+  Bool_t ReInit(MParList *pList);
+  Int_t  Process();
+
+public:
+
+  MExtractBlindPixel(const char *name=NULL, const char *title=NULL);
+  ~MExtractBlindPixel();
+
+  void Clear( const Option_t *o ="");
+  
+  // Getters
+  Bool_t IsExtractionType ( const ExtractionType_t typ );
+  Bool_t IsDataType       ( const DataType_t       typ );
+
+  // Setters
+  void SetBlindPixelIdx(  const Int_t  idx=fgBlindPixelIdx, const Int_t nr=0 ) {
+    if (nr>fBlindPixelIdx.GetSize()-1)
+      fBlindPixelIdx.Set(nr+1);
+    fBlindPixelIdx.AddAt(idx,nr); }
+  void SetExtractionType( const ExtractionType_t typ=kAmplitude );
+  void SetDataType    ( const DataType_t       typ=kRawEvt    );  
+  void SetNSBFilterLimit( const Int_t   lim=fgNSBFilterLimit )  { fNSBFilterLimit = lim;   }     
+  
+  void SetNumBlindPixels( const Int_t   num=1 )  { fNumBlindPixels = num;   }
+  
+  void SetRange         ( const Byte_t  hifirst=0, const Byte_t hilast=0, 
+   		          const Byte_t  lofirst=0, const Byte_t lolast=0 );
+  void SetResolution    ( const Float_t f=fgResolution       )  { fResolution     = f;     }
+  
+  ClassDef(MExtractBlindPixel, 0) // Signal Extractor for the Blind Pixel
+};
+
+#endif
+
Index: /tags/Mars-V0.9/msignal/MExtractFixedWindow.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractFixedWindow.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractFixedWindow.cc	(revision 9772)
@@ -0,0 +1,296 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!              Thomas Bretz, 01/2004 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MExtractFixedWindow
+//
+//  Extracts the signal from a fixed window in a given range by summing up the 
+//  slice contents.
+//
+//  Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//  to modify the ranges. Ranges have to be an even number. In case of odd 
+//  ranges, the last slice will be reduced by one.
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  3 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractFixedWindow.h"
+#include "MExtractor.h"
+
+#include <fstream>
+
+#include "MExtractedSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractFixedWindow);
+
+using namespace std;
+
+const Byte_t MExtractFixedWindow::fgHiGainFirst =  3;
+const Byte_t MExtractFixedWindow::fgHiGainLast  =  14;
+const Byte_t MExtractFixedWindow::fgLoGainFirst =  3;
+const Byte_t MExtractFixedWindow::fgLoGainLast  =  14;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls:
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractFixedWindow::MExtractFixedWindow(const char *name, const char *title)
+{
+  fName  = name  ? name  : "MExtractFixedWindow";
+  fTitle = title ? title : "Signal Extractor for a fixed FADC window";
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Checks: 
+// - if the window defined by (fHiGainLast-fHiGainFirst-1) are odd, subtract one
+// - if the window defined by (fLoGainLast-fLoGainFirst-1) are odd, subtract one
+// - if the Hi Gain window is smaller than 2, set fHiGainLast to fHiGainFirst+1
+// - if the Lo Gain window is smaller than 2, set fLoGainLast to fLoGainFirst+1
+// 
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)(fHiGainLast-fHiGainFirst+1)
+// - fNumLoGainSamples to: (Float_t)(fLoGainLast-fLoGainFirst+1)
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractFixedWindow::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  const Byte_t windowhi = hilast-hifirst+1;
+  const Byte_t whieven = windowhi & ~1;
+
+  if (whieven != windowhi)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Hi Gain window size has to be even, set last slice from "
+                    ,(int)hilast," to ",(int)(hilast-1)) << endl;
+      hilast -= 1;
+    }
+  
+  if (whieven<2) 
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Hi Gain window is smaller than 2 FADC sampes, set last slice from" 
+                    ,(int)hilast," to ",(int)(hifirst+1)) << endl;
+      hilast = hifirst+1;
+    }
+  
+
+  if (lolast != 0)
+    {
+      const Byte_t windowlo = lolast-lofirst+1;
+      const Byte_t wloeven = windowlo & ~1;
+
+      if (wloeven != windowlo)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i",": Lo Gain window size has to be even, set last slice from "
+                        ,(int)lolast," to ",(int)(lolast-1)) << endl;
+          lolast -= 1;
+        }
+      
+      if (wloeven<2) 
+        {
+          *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Lo Gain window is smaller than 2 FADC sampes, set last slice from" 
+                    ,(int)lolast," to ",(int)(lofirst+1)) << endl;
+          lolast = lofirst+1;        
+        }
+    }
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  fNumHiGainSamples = (Float_t)(fHiGainLast-fHiGainFirst+1);
+  if (fLoGainLast != 0)
+    fNumLoGainSamples = (Float_t)(fLoGainLast-fLoGainFirst+1);  
+  else
+    fNumLoGainSamples = 0.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);  
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+// -  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+//
+Bool_t MExtractFixedWindow::ReInit(MParList *pList)
+{
+
+  MExtractor::ReInit(pList);
+  
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+
+  *fLog << endl;
+  *fLog << inf << "Taking " << fNumHiGainSamples
+        << " HiGain samples from slice " << (Int_t)fHiGainFirst
+        << " to " << (Int_t)(fHiGainLast+fHiLoLast) << " incl" << endl;
+  *fLog << inf << "Taking " << fNumLoGainSamples
+        << " LoGain samples from slice " << (Int_t)fLoGainFirst
+        << " to " << (Int_t)fLoGainLast << " incl" << endl;
+  return kTRUE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+// - If fHiLoLast is not 0, loop also from logain to (logain+fHiLoLast)
+// - Sum up contents of logain
+// - If *logain is greater than fSaturationLimit, raise sat by 1
+//
+void MExtractFixedWindow::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const
+{
+
+  Int_t summ = 0;
+
+  Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+  while (ptr<end)
+    {
+      summ += *ptr;
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+
+  Byte_t *p = logain;
+  end = logain + fHiLoLast;
+  while (p<end)
+    {
+      summ += *p;
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+
+  sum = (Float_t)summ;
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - If fHiLoLast is set, loop from logain to (logain+fHiLoLast)
+// - Add contents of *logain to sum
+// 
+void MExtractFixedWindow::FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const
+{
+
+  Int_t summ = 0;
+
+  Byte_t *end = ptr + fLoGainLast - fLoGainFirst + 1;
+  
+  while (ptr<end)
+    {
+      summ += *ptr;
+      
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+
+  sum = (Float_t)summ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MExtractFixedWindow::StreamPrimitive(ofstream &out) const
+{
+
+  out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+  out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+  
+  if (fSaturationLimit!=fgSaturationLimit)
+    {
+      out << "   " << GetUniqueName() << ".SetSaturationLimit(";
+      out << (int)fSaturationLimit << ");" << endl;
+    }
+  
+  const Bool_t arg4 = fNumLoGainSamples+fLoGainFirst-1 != fgLoGainLast;
+  const Bool_t arg3 = arg4 || fLoGainFirst != fgLoGainFirst;
+  const Bool_t arg2 = arg3 || fNumHiGainSamples+fHiGainFirst-1 != fgHiGainLast;
+  const Bool_t arg1 = arg2 || fHiGainFirst != fgHiGainFirst;
+  
+  if (!arg1)
+    return;
+  
+  out << "   " << GetUniqueName() << ".SetRange(";
+  out << (int)fLoGainFirst;
+  if (arg2)
+    {
+      out << ", " << (int)(fNumHiGainSamples+fHiGainFirst-1);
+      if (arg3)
+        {
+          out << ", " << (int)fLoGainFirst;
+          if (arg4)
+            out << ", " << (int)(fNumLoGainSamples+fLoGainFirst-1);
+        }
+    }
+  out << ");" << endl;
+}
+
+void MExtractFixedWindow::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    MExtractor::Print(o);
+}
Index: /tags/Mars-V0.9/msignal/MExtractFixedWindow.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractFixedWindow.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractFixedWindow.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MExtractFixedWindow
+#define MARS_MExtractFixedWindow
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractFixedWindow                                                          //
+//                                                                         //
+// Integrates the time slices of the all pixels in a fixed window          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractFixedWindow : public MExtractor
+{
+private:
+  static const Byte_t fgHiGainFirst;     // First FADC slice Hi-Gain (currently set to: 3) 
+  static const Byte_t fgHiGainLast;      // Last FADC slice Hi-Gain (currently set to: 14) 
+  static const Byte_t fgLoGainFirst;     // First FADC slice Lo-Gain (currently set to: 3) 
+  static const Byte_t fgLoGainLast;      // Last FADC slice Lo-Gain (currently set to: 14) 
+
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const;
+  void   StreamPrimitive(ofstream &out) const;
+  
+  Bool_t ReInit(MParList *pList);
+  
+public:
+
+  MExtractFixedWindow(const char *name=NULL, const char *title=NULL);
+
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+
+  void Print(Option_t *o="") const;
+  
+  ClassDef(MExtractFixedWindow, 1) // Signal Extractor for a fixed extraction window
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractFixedWindowPeakSearch.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractFixedWindowPeakSearch.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractFixedWindowPeakSearch.cc	(revision 9772)
@@ -0,0 +1,564 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Abelardo Moralejo, 04/2004 <mailto:moralejo@pd.infn.it>
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractFixedWindowPeakSearch
+//
+//  Calculate the signal integrating fWindowSize time slices, the same for 
+//  all pixels. The integrated slices change from event to event, since the
+//  pulse positions in the FADC jump between events, but apparently in a 
+//  "coherent" fashion. We first loop over all pixels and find the one 
+//  which has the highest sum of fPeakSearchWindowSize (default: 4) consecutive 
+//  non-saturated high gain slices. The position of the peak in this pixel 
+//  determines the integration window position for all pixels of this event. 
+//  For the moment we neglect time delays between pixels (which are in most 
+//  cases small). The class is based on MExtractSlidingWindow.
+//
+//  Call: SetRange(higainfirst, higainlast, logainfirst, logainlast) 
+//  to modify the ranges in which the window is allowed to move. 
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//  Call: SetWindows(windowhigain, windowlogain,peaksearchwindow) 
+//  to modify the sliding window widths. Windows have to be an even number. 
+//  In case of odd numbers, the window will be modified.
+//
+//  Call: SetOffsetFromWindow() to adjust the positionning of the extraction
+//  window w.r.t. the peak search window. An fOffsetFromWindow of 0 means that
+//  the starting slice of the extraction window is equal to the starting slice
+//  of the maximizing peak search window. fOffsetFromWindow equal to 1 (default)
+//  means that the extraction window starts one slice earlier than the peak 
+//  search window result. It is recommanded to always use a smaller peak search
+//  window than the extraction window.
+//
+//  Defaults are:
+//
+//   fHiGainWindowSize     = fgHiGainWindowSize     = 6
+//   fLoGainWindowSize     = fgLoGainWindowSize     = 6
+//   fPeakSearchWindowSize = fgPeakSearchWindowSize = 4
+//   fLoGainPeakShift      = fgLoGainPeakShift      = 0
+//   fOffsetFromWindow     = fgOffsetFromWindow     = 1
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractFixedWindowPeakSearch.h"
+#include "MExtractor.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+ClassImp(MExtractFixedWindowPeakSearch);
+
+using namespace std;
+
+const Byte_t MExtractFixedWindowPeakSearch::fgHiGainFirst          = 0;
+const Byte_t MExtractFixedWindowPeakSearch::fgHiGainLast           = 16;
+const Byte_t MExtractFixedWindowPeakSearch::fgLoGainFirst          = 3;
+const Byte_t MExtractFixedWindowPeakSearch::fgLoGainLast           = 14;
+const Byte_t MExtractFixedWindowPeakSearch::fgHiGainWindowSize     = 6;
+const Byte_t MExtractFixedWindowPeakSearch::fgLoGainWindowSize     = 6;
+const Byte_t MExtractFixedWindowPeakSearch::fgPeakSearchWindowSize = 4;
+const Byte_t MExtractFixedWindowPeakSearch::fgOffsetFromWindow     = 1;
+const Byte_t MExtractFixedWindowPeakSearch::fgLoGainPeakShift      = 1;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fHiGainWindowSize to fgHiGainWindowSize
+// - fLoGainWindowSize to fgLoGainWindowSize
+// - fPeakSearchWindowSize to fgPeakSearchWindowSize
+// - fLoGainPeakShift to fgLoGainPeakShift
+//
+// Calls: 
+// - SetOffsetFromWindow()
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractFixedWindowPeakSearch::MExtractFixedWindowPeakSearch(const char *name, const char *title)
+    : fHiGainWindowSize(fgHiGainWindowSize), 
+      fLoGainWindowSize(fgLoGainWindowSize),
+      fPeakSearchWindowSize(fgPeakSearchWindowSize),
+      fLoGainPeakShift(fgLoGainPeakShift)
+{
+
+  fName  = name  ? name  : "MExtractFixedWindowPeakSearch";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+  SetOffsetFromWindow();
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - SetWindows(fHiGainWindowSize,fLoGainWindowSize,fPeakSearchWindowSize);
+//
+void MExtractFixedWindowPeakSearch::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
+  //
+  SetWindows(fHiGainWindowSize,fLoGainWindowSize,fPeakSearchWindowSize);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is odd, subtract one
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// - if a window is smaller than 2, set it to 2
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)fHiGainWindowSize
+// - fNumLoGainSamples to: (Float_t)fLoGainWindowSize
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractFixedWindowPeakSearch::SetWindows(Byte_t windowh, Byte_t windowl, Byte_t peaksearchwindow)
+{
+
+  fHiGainWindowSize     = windowh & ~1;
+  fLoGainWindowSize     = windowl & ~1;
+  fPeakSearchWindowSize = peaksearchwindow & ~1;
+
+  if (fHiGainWindowSize != windowh)
+    *fLog << warn << GetDescriptor() << ": Hi Gain window size has to be even, set to: " 
+          << int(fHiGainWindowSize) << " samples " << endl;
+  
+  if (fLoGainWindowSize != windowl)
+    *fLog << warn << GetDescriptor() << ": Lo Gain window size has to be even, set to: " 
+          << int(fLoGainWindowSize) << " samples " << endl;
+    
+  if (fPeakSearchWindowSize != peaksearchwindow)
+    *fLog << warn << GetDescriptor() << ": Peak Search window size has to be even, set to: " 
+          << int(fPeakSearchWindowSize) << " samples " << endl;
+
+  const Byte_t availhirange = (fHiGainLast-fHiGainFirst+1) & ~1;
+  const Byte_t availlorange = (fLoGainLast-fLoGainFirst+1) & ~1;
+
+  if (fHiGainWindowSize > availhirange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",(int)fHiGainWindowSize,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availhirange << endl;
+      fHiGainWindowSize = availhirange;
+    }
+  
+  
+  if (fLoGainWindowSize > availlorange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",(int)fLoGainWindowSize,
+                    " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availlorange << endl;
+      fLoGainWindowSize = availlorange;
+    }
+  
+  if (fHiGainWindowSize<2) 
+    {
+      fHiGainWindowSize = 2;
+      *fLog << warn << GetDescriptor() << ": Hi Gain window size set to two samples" << endl;
+    }
+  
+  if (fLoGainWindowSize<2) 
+    {
+      fLoGainWindowSize = 2;
+      *fLog << warn << GetDescriptor() << ": Lo Gain window size set to two samples" << endl;
+    }
+
+  if (fPeakSearchWindowSize<2) 
+    {
+      fPeakSearchWindowSize = 2;
+      *fLog << warn << GetDescriptor() 
+            << ": Peak Search window size set to two samples" << endl;
+    }
+
+  fNumHiGainSamples = (Float_t)fHiGainWindowSize;
+  fNumLoGainSamples = (Float_t)fLoGainWindowSize;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+// -  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+//
+Bool_t MExtractFixedWindowPeakSearch::ReInit(MParList *pList)
+{
+
+  MExtractor::ReInit(pList);
+  
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+  *fLog << dec << endl;
+  *fLog << inf << "Taking " << fNumHiGainSamples
+        << " HiGain samples starting with slice " << (Int_t)fHiGainFirst
+        << " to " << (Int_t)(fHiGainLast+fHiLoLast) << " incl" << endl;
+  *fLog << inf << "Taking " << fNumLoGainSamples
+        << " LoGain samples starting with slice " << (Int_t)fLoGainFirst
+        << " to " << (Int_t)fLoGainLast << " incl" << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindPeak
+// Finds highest sum of "window" consecutive FADC slices in a pixel, and store
+// in "startslice" the first slice of the group which yields the maximum sum.
+// In "max" the value of the maximum sum is stored, in "sat" the number of 
+// saturated slices.
+//
+void MExtractFixedWindowPeakSearch::FindPeak(Byte_t *ptr, Byte_t window, Byte_t &startslice, Int_t &max, 
+                                             Int_t &sat, Byte_t &satpos) const
+{
+
+  const Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+  sat = 0;
+  satpos = 0;
+  
+  startslice = 0;
+  Int_t sum=0;
+
+  //
+  // Calculate the sum of the first "window" slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+
+  while (p<ptr+window)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+        {
+          if (sat == 0)
+              satpos = p-ptr;
+          sat++;
+        }
+    }
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      {
+        if (sat == 0)
+          satpos = p-ptr;
+        sat++;
+      }
+  
+  //
+  // Calculate the i-th sum of n as
+  //    sum_i+1 = sum_i + slice[i+window] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  for (p=ptr; p+window<end; p++)
+    {
+      sum += *(p+window) - *p;
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = p-ptr+1;
+	}
+    }
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainWindowSize)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractFixedWindowPeakSearch::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr + fHiGainWindowSize-fHiLoLast;
+
+  Int_t summ = 0;
+  //
+  // Calculate the sum of the "window" slices starting in ptr
+  //
+  while (ptr<end)
+    {
+      summ += *ptr;
+      if (*ptr++ >= fSaturationLimit)
+	sat++;
+    }
+
+  //
+  // If part of the "lo-Gain" slices are used,
+  // repeat steps one and two for the logain part until fHiLoLast
+  //
+  Byte_t *p = logain;
+  end = logain + fHiLoLast;
+  while (p<end)
+    {
+  
+      summ += *p;
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+
+  sum = (Float_t)summ;
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fLoGainWindowSize)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractFixedWindowPeakSearch::FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const
+{
+  //
+  // Calculate the sum of the "window" slices starting in ptr
+  //
+  Byte_t *p = ptr;
+  Int_t summ = 0;
+
+  while (p<ptr+fLoGainWindowSize)
+    {
+      summ += *p;
+      if (*p++ >= fSaturationLimit)
+	sat++;
+    }
+
+  sum = (Float_t)summ;
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process
+// First find the pixel with highest sum of fPeakSearchWindowSize slices (default:4)
+// "startslice" will mark the slice at which the highest sum begins for that pixel.
+// Then define the beginning of the integration window for ALL pixels as the slice
+// before that: startslice-fOffsetFromWindow, unless of course startslice-fOffsetFromWindow<=0,
+// in which case we start at 0. We will also check that the integration window does not 
+// go beyond the FADC limits.
+//
+Int_t MExtractFixedWindowPeakSearch::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  Int_t sat;
+  Byte_t  satpos;
+  ULong_t gsatpos = 0;
+
+  Int_t maxsumhi = -1000000;
+  Int_t numsat   = 0;
+  Byte_t startslice;
+  Byte_t hiGainFirst = 0;
+  Byte_t loGainFirst = 0;
+  fHiLoLast = 0;
+
+  while (pixel.Next())
+    {
+      Int_t sumhi;
+      sat = 0;
+
+      FindPeak(pixel.GetHiGainSamples()+fHiGainFirst, fPeakSearchWindowSize, startslice, sumhi, sat, satpos);
+
+      if (sumhi > maxsumhi && sat == 0)
+	{
+	  maxsumhi = sumhi;
+	  if (startslice > fOffsetFromWindow)
+            hiGainFirst = fHiGainFirst + startslice - fOffsetFromWindow;
+	  else
+	    hiGainFirst = fHiGainFirst;
+	}
+      else if (sat)
+        {
+          numsat++;
+          gsatpos += satpos;
+        }
+    }
+
+  // Check necessary for calibration events
+  if (numsat > fSignals->GetSize()*0.9)
+    hiGainFirst = gsatpos/numsat - 1;
+
+  loGainFirst = ( hiGainFirst+fLoGainPeakShift > fLoGainFirst ) 
+    ? hiGainFirst+fLoGainPeakShift 
+    : fLoGainFirst;
+
+  // Make sure we will not integrate beyond the hi gain limit:
+  if (hiGainFirst+fHiGainWindowSize > pixel.GetNumHiGainSamples())
+    fHiLoLast = hiGainFirst+fHiGainWindowSize - pixel.GetNumHiGainSamples();
+  //    hiGainFirst = pixel.GetNumHiGainSamples()-fHiGainWindowSize;
+
+  // Make sure we will not integrate beyond the lo gain limit:
+  if (loGainFirst+fLoGainWindowSize > pixel.GetNumLoGainSamples())
+    loGainFirst = pixel.GetNumLoGainSamples()-fLoGainWindowSize;
+
+  pixel.Reset();
+
+  while (pixel.Next())
+    {
+      //
+      // Find signal in hi- and lo-gain
+      //
+      Float_t sumhi=0.;
+      Byte_t sathi=0;
+
+      FindSignalHiGain(pixel.GetHiGainSamples()+hiGainFirst, pixel.GetLoGainSamples(), sumhi, sathi);
+
+      Float_t sumlo=0.;
+      Byte_t satlo=0;
+      if (pixel.HasLoGain())
+        FindSignalLoGain(pixel.GetLoGainSamples()+loGainFirst, sumlo, satlo);
+
+      //
+      // Take corresponding pedestal
+      //
+      const Int_t pixid = pixel.GetPixelId();
+
+      const MPedestalPix  &ped = (*fPedestals)[pixid];
+      MExtractedSignalPix &pix = (*fSignals)[pixid];
+
+      const Float_t pedes  = ped.GetPedestal();
+      const Float_t pedrms = ped.GetPedestalRms();
+      //
+      // Set extracted signal with pedestal substracted
+      //
+      pix.SetExtractedSignal(sumhi - pedes*fNumHiGainSamples, pedrms*fSqrtHiGainSamples,
+                             sumlo - pedes*fNumLoGainSamples, pedrms*fSqrtLoGainSamples);
+
+      pix.SetGainSaturation(sathi, sathi, satlo);
+
+      //      pix.SetNumHiGainSlices(fNumHiGainSamples);
+      //      pix.SetNumLoGainSlices(fNumLoGainSamples);      
+      
+    } /* while (pixel.Next()) */
+
+
+  fSignals->SetReadyToSave();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//   MJPedestal.MExtractor.PeakSearchWindow: 4
+//   MJPedestal.MExtractor.OffsetFromWindow: 1
+//   MJPedestal.MExtractor.LoGainPeakShift:  1
+//
+Int_t MExtractFixedWindowPeakSearch::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Byte_t hw = fHiGainWindowSize;
+    Byte_t lw = fLoGainWindowSize;
+    Byte_t pw = fPeakSearchWindowSize;
+
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "PeakSearchWindow", print))
+    {
+        pw = GetEnvValue(env, prefix, "PeakSearchWindow", pw);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "HiGainWindowSize", print))
+    {
+        hw = GetEnvValue(env, prefix, "HiGainWindowSize", hw);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainWindowSize", print))
+    {
+        lw = GetEnvValue(env, prefix, "LoGainWindowSize", lw);
+        rc = kTRUE;
+    }
+
+    if (rc)
+        SetWindows(hw, lw, pw);
+
+
+    if (IsEnvDefined(env, prefix, "OffsetFromWindow", print))
+    {
+        SetOffsetFromWindow(GetEnvValue(env, prefix, "OffsetFromWindow", fOffsetFromWindow));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "LoGainPeakShift", print))
+    {
+        SetLoGainPeakShift(GetEnvValue(env, prefix, "LoGainPeakShift", fLoGainPeakShift));
+        rc = kTRUE;
+    }
+
+    rc = MExtractor::ReadEnv(env, prefix, print) ? kTRUE : rc;
+
+    return rc;
+}
+
+void MExtractFixedWindowPeakSearch::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " Windows: Hi-Gain=" << (int)fHiGainWindowSize << "  Lo-Gain=" << (int)fLoGainWindowSize;
+    *fLog << "  Peak-Search=" << (int)fPeakSearchWindowSize << endl;
+    *fLog << " Offset From Window: " << (int)fOffsetFromWindow << endl;
+    *fLog << " Lo-Gain peak Shift: " << (int)fLoGainPeakShift << endl;
+    MExtractor::Print(o);
+}
Index: /tags/Mars-V0.9/msignal/MExtractFixedWindowPeakSearch.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractFixedWindowPeakSearch.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractFixedWindowPeakSearch.h	(revision 9772)
@@ -0,0 +1,56 @@
+#ifndef MARS_MExtractFixedWindowPeakSearch
+#define MARS_MExtractFixedWindowPeakSearch
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractFixedWindowPeakSearch : public MExtractor
+{
+private:
+
+  static const Byte_t fgHiGainFirst;          //! Default for fHiGainFirst          (now set to:  0)
+  static const Byte_t fgHiGainLast;           //! Default for fHiGainLast 	    (now set to: 16)
+  static const Byte_t fgLoGainFirst;          //! Default for fLoGainFirst	    (now set to:  3)
+  static const Byte_t fgLoGainLast;           //! Default for fLoGainLast 	    (now set to: 14)
+  static const Byte_t fgHiGainWindowSize;     //! Default for fWindowSizeHiGain     (now set to:  6)
+  static const Byte_t fgLoGainWindowSize;     //! Default for fWindowSizeLoGain     (now set to:  6)
+  static const Byte_t fgPeakSearchWindowSize; //! Default for fPeakSearchWindowSize (now set to:  4)
+  static const Byte_t fgOffsetFromWindow;     //! Default for fOffsetFromWindow     (now set to:  1)
+  static const Byte_t fgLoGainPeakShift;      //! Default for fLowGainPeakShift     (now set to:  1)
+
+  Byte_t  fHiGainWindowSize;     // Number of Hi Gain slices in window
+  Byte_t  fLoGainWindowSize;     // Number of Lo Gain slices in window
+  Byte_t  fPeakSearchWindowSize; // Size of FADC window in the search for the highest peak of all pixels.
+  Byte_t  fOffsetFromWindow;     // Number of slices to start extraction before search window
+  Byte_t  fLoGainPeakShift;      // Shift of the low gain pulse with respect to the high gain pulse, in slices: it is 0 if the low gain is delayed with respect to HG by 15 slices.
+
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const;  
+
+  void   FindPeak(Byte_t *ptr, Byte_t window, Byte_t &startslice, Int_t &signal, Int_t &sat, Byte_t &satpos) const;
+
+  Bool_t ReInit(MParList *pList);
+  Int_t  Process();
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MExtractFixedWindowPeakSearch(const char *name=NULL, const char *title=NULL);
+  
+  Byte_t GetHiGainWindowSize() const { return fHiGainWindowSize; }
+  Byte_t GetLoGainWindowSize() const { return fLoGainWindowSize; }
+
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);    
+  void SetWindows(Byte_t windowh=fgHiGainWindowSize, Byte_t windowl=fgLoGainWindowSize, 
+                  Byte_t peaksearchwindow=fgPeakSearchWindowSize);
+  void SetOffsetFromWindow(Byte_t offset=fgOffsetFromWindow)  {  fOffsetFromWindow = offset; }
+  
+  void SetLoGainPeakShift(Byte_t shift=fgLoGainPeakShift) { fLoGainPeakShift = shift; }
+  
+  void Print(Option_t *o="") const;
+
+  ClassDef(MExtractFixedWindowPeakSearch, 1) // Signal Extractor for fixed size trigger-corrected extraction window
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractFixedWindowSpline.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractFixedWindowSpline.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractFixedWindowSpline.cc	(revision 9772)
@@ -0,0 +1,440 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug       05/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeSpline
+//
+//   Fast Spline extractor using a cubic spline algorithm of Numerical Recipes. 
+//   It returns the integral below the interpolating spline. 
+// 
+//   Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//         to modify the ranges. 
+//
+//         The spline will then be integrated from fHiGainFirst to fHiGainLast, 
+//         including half of the outer edges. The effective number of intergrated
+//         slices ("range") is thus: 
+// 
+//         range = fHiGainLast - fHiGainFirst
+//
+//         Ranges have to be an even number. In case of odd ranges, the last slice 
+//         will be reduced by one.
+//
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  2 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  13
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractFixedWindowSpline.h"
+
+#include "MExtractedSignalCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractFixedWindowSpline);
+
+using namespace std;
+
+const Byte_t  MExtractFixedWindowSpline::fgHiGainFirst  = 2;
+const Byte_t  MExtractFixedWindowSpline::fgHiGainLast   = 14;
+const Byte_t  MExtractFixedWindowSpline::fgLoGainFirst  = 3;
+const Byte_t  MExtractFixedWindowSpline::fgLoGainLast   = 13;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+MExtractFixedWindowSpline::MExtractFixedWindowSpline(const char *name, const char *title) 
+{
+
+  fName  = name  ? name  : "MExtractFixedWindowSpline";
+  fTitle = title ? title : "Signal Extractor for a fixed FADC window using a fast spline";
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Checks: 
+// - if the window defined by (fHiGainLast-fHiGainFirst-1) are odd, subtract one
+// - if the window defined by (fLoGainLast-fLoGainFirst-1) are odd, subtract one
+// - if the Hi Gain window is smaller than 2, set fHiGainLast to fHiGainFirst+1
+// - if the Lo Gain window is smaller than 2, set fLoGainLast to fLoGainFirst+1
+// 
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)(fHiGainLast-fHiGainFirst+1)
+// - fNumLoGainSamples to: (Float_t)(fLoGainLast-fLoGainFirst+1)
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractFixedWindowSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  const Byte_t windowhi = hilast-hifirst;
+  const Byte_t whieven  = windowhi & ~1;
+
+  if (whieven != windowhi)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Hi Gain window size has to be uneven, set last slice from "
+                    ,(int)hilast," to ",(int)(hilast-1)) << endl;
+      hilast -= 1;
+    }
+  
+  if (whieven<2) 
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Hi Gain window is smaller than 2 FADC sampes, set last slice from" 
+                    ,(int)hilast," to ",(int)(hifirst+2)) << endl;
+      hilast = hifirst+2;
+    }
+
+  const Byte_t windowlo = lolast-lofirst;
+  const Byte_t wloeven  = windowlo & ~1;
+
+  if (lolast != 0)
+    {
+      if (wloeven != windowlo)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i",": Lo Gain window size has to be uneven, set last slice from "
+                        ,(int)lolast," to ",(int)(lolast-1)) << endl;
+          lolast -= 1;
+        }
+      
+      
+      if (wloeven<2) 
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i",": Lo Gain window is smaller than 2 FADC sampes, set last slice from" 
+                        ,(int)lolast," to ",(int)(lofirst+2)) << endl;
+          lolast = lofirst+2;        
+        }
+    }
+  
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  //
+  // Very important: Because the spline interpolates between the slices, 
+  //                 the number of samples for the pedestal subtraction 
+  //                 is now 1 less than with e.g. MExtractFixedWindow
+  //
+  fNumHiGainSamples = (Float_t)(fHiGainLast-fHiGainFirst);
+  if (fLoGainLast != 0)
+    fNumLoGainSamples = (Float_t)(fLoGainLast-fLoGainFirst);  
+  else
+    fNumLoGainSamples = 0.;
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);  
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// ReInit
+//
+// Calls:
+// - MExtractor::ReInit(pList);
+// - fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+// 
+// Deletes all arrays, if not NULL
+// Creates new arrays according to the extraction range
+//
+Bool_t MExtractFixedWindowSpline::ReInit(MParList *pList)
+{
+
+  if (!MExtractor::ReInit(pList))
+    return kFALSE;
+
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+  Int_t range = fHiGainLast - fHiGainFirst + 1 + fHiLoLast;
+
+  fHiGainFirstDeriv.Set(range);
+  fHiGainSecondDeriv.Set(range);
+
+  range = fLoGainLast - fLoGainFirst + 1;
+
+  fLoGainFirstDeriv.Set(range);
+  fLoGainSecondDeriv.Set(range);
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+// - If fHiLoLast is not 0, loop also from logain to (logain+fHiLoLast)
+// - Sum up contents of logain
+// - If *logain is greater than fSaturationLimit, raise sat by 1
+//
+void MExtractFixedWindowSpline::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const
+{
+  
+  const Byte_t *end = ptr + fHiGainLast - fHiGainFirst;
+  Int_t range = fHiGainLast - fHiGainFirst + fHiLoLast + 1;
+  
+  Float_t pp;
+  //  Int_t   i = 0;
+
+  Int_t summ = 0;
+  // 
+  // Take half of the first slice content
+  // 
+  Float_t *firstderiv = fHiGainFirstDeriv.GetArray();
+  Float_t *secondderiv = fHiGainSecondDeriv.GetArray();
+  sum = (Float_t)*ptr/2.;
+  // 
+  // The first slice has already been treated now!
+  // 
+  ptr++; // i++;
+  firstderiv++; 
+  secondderiv++;
+  //
+  // Check for saturation in all other slices
+  //
+  while (ptr<end)
+    {
+
+      summ += *ptr;
+
+      // pp = fHiGainSecondDeriv[i-1] + 4.;
+      // fHiGainSecondDeriv[i] = -1.0/pp;
+      // fHiGainFirstDeriv [i] = *(ptr+1) - 2.* *(ptr) + *(ptr-1);
+      // fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+
+      pp = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(ptr+1) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+
+      secondderiv++;
+      firstderiv++;
+
+      //      i++;
+    }
+  
+  switch (fHiLoLast)
+    {
+    case 0:
+      // Treat the last slice of the high-gain as half slice:
+      sum += (Float_t)*ptr/2.;
+      break;
+    case 1:
+      // Treat the last slice of the high-gain as full slice:
+      summ += *ptr;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      if (*logain >= fSaturationLimit)
+        sat++;
+      // Treat the first slice of the low-gain as half slice:
+      sum  += (Float_t)*logain/2;
+      break;
+    case 2:
+      // Treat the last slice of the high-gain as full slice:
+      summ += *ptr;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      // Treat the last first slice of the low-gain as full slice:
+      summ += *logain;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain+1) - 2.* *(logain) + *(ptr);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      if (*logain++ >= fSaturationLimit)
+        sat++;
+      // Treat the second slice of the low-gain as half slice:
+      sum  += (Float_t)*logain/2;
+      if (*logain >= fSaturationLimit)
+        sat++;
+      break;
+    default:
+      // Treat the last slice of the high-gain as full slice:
+      summ += *ptr;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      // Treat the last first slice of the low-gain as full slice:
+      summ += *logain;
+      pp    = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(logain+1) - 2.* *(logain) + *(ptr);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+      secondderiv++;
+      firstderiv++;
+      if (*logain++ >= fSaturationLimit)
+        sat++;
+      // Treat the rest of the slices:
+      const Byte_t *end = logain+fHiLoLast;
+      while (logain<end)
+	{
+	  summ += *logain;
+	  pp    = *(secondderiv-1) + 4.;
+	  *secondderiv = -1.0/pp;
+	  *firstderiv  = *(logain+1) - 2.* *(logain) + *(logain-1);
+	  *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+	  //	  pp = fHiGainSecondDeriv[i-1] + 4.;
+	  //	  fHiGainSecondDeriv[i] = -1.0/pp;
+	  //	  fHiGainFirstDeriv [i] = *(logain+1) - 2.* *(logain) + *(logain-1);
+	  //	  fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+	  secondderiv++;
+	  firstderiv++;
+	  if (*logain++ >= fSaturationLimit)
+	    sat++;
+	}
+      break;
+    }
+  
+  //
+  // Go back to last but one element:
+  //
+  secondderiv--;
+  firstderiv--;
+
+  for (Int_t k=range-2;k>0;k--)
+    {
+      *secondderiv = *secondderiv * *(secondderiv+1) + *firstderiv;
+      sum += 0.25* *secondderiv;
+      firstderiv--;
+      secondderiv--;
+      //      fHiGainSecondDeriv[k] = fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k];
+      //      sum += 0.25*fHiGainSecondDeriv[k];
+    }
+
+  sum += (Float_t)summ;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// 
+void MExtractFixedWindowSpline::FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const
+{
+  
+  const Byte_t *end = ptr + fLoGainLast - fLoGainFirst;
+  Int_t range = fLoGainLast - fLoGainFirst + 1;
+  
+  Float_t pp;
+  //  Int_t   i = 0;
+
+  Int_t summ = 0;
+  // 
+  // Take half of the first slice content
+  // 
+  Float_t *firstderiv = fLoGainFirstDeriv.GetArray();
+  Float_t *secondderiv = fLoGainSecondDeriv.GetArray();
+  sum = (Float_t)*ptr/2.;
+  // 
+  // The first slice has already been treated now!
+  // 
+  ptr++; // i++;
+  secondderiv++;
+  firstderiv++;
+  //
+  // Check for saturation in all other slices
+  //
+  while (ptr<end)
+    {
+
+      summ += *ptr;
+      //      i++;
+
+      // pp = fLoGainSecondDeriv[i-1] + 4.;
+      // fLoGainSecondDeriv[i] = -1.0/pp;
+      // fLoGainFirstDeriv [i] = *(ptr+1) - 2.* *(ptr) + *(ptr-1);
+      // fLoGainFirstDeriv [i] = (6.0*fLoGainFirstDeriv[i]-fLoGainFirstDeriv[i-1])/pp;
+
+      pp = *(secondderiv-1) + 4.;
+      *secondderiv = -1.0/pp;
+      *firstderiv  = *(ptr+1) - 2.* *(ptr) + *(ptr-1);
+      *firstderiv  = (6.0* *(firstderiv) - *(firstderiv-1))/pp;
+
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+
+      secondderiv++;
+      firstderiv++;
+    }
+  
+  sum += (Float_t)*ptr/2.;
+  
+  //
+  // Go back to last but one element:
+  //
+  secondderiv--;
+  firstderiv--;
+
+  for (Int_t k=range-2;k>0;k--)
+    {
+      *secondderiv = *secondderiv * *(secondderiv+1) + *firstderiv;
+      sum += 0.25* *secondderiv;
+      firstderiv--;
+      secondderiv--;
+      //      fLoGainSecondDeriv[k] = fLoGainSecondDeriv[k]*fLoGainSecondDeriv[k+1] + fLoGainFirstDeriv[k];
+      //      sum += 0.25*fLoGainSecondDeriv[k];
+    }
+  
+  sum += (Float_t)summ;
+}
+
Index: /tags/Mars-V0.9/msignal/MExtractFixedWindowSpline.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractFixedWindowSpline.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractFixedWindowSpline.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MExtractFixedWindowSpline
+#define MARS_MExtractFixedWindowSpline
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+#ifndef MARS_MArrayF   
+#include "MArrayF.h"
+#endif
+
+class MExtractFixedWindowSpline : public MExtractor
+{
+
+private:
+  
+  static const Byte_t  fgHiGainFirst;    // Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t  fgHiGainLast;     // Default for fHiGainLast   (now set to: 14)
+  static const Byte_t  fgLoGainFirst;    // Default for fLOGainFirst  (now set to: 3)
+  static const Byte_t  fgLoGainLast;     // Default for fLoGainLast   (now set to: 14)
+
+  MArrayF fHiGainFirstDeriv;             //! Temporary storage
+  MArrayF fLoGainFirstDeriv;             //! Temporary storage
+  MArrayF fHiGainSecondDeriv;            //! Temporary storage
+  MArrayF fLoGainSecondDeriv;            //! Temporary storage
+
+  Bool_t ReInit    (MParList *pList);
+  
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &sum, Byte_t &sat) const;
+
+public:
+
+  MExtractFixedWindowSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractFixedWindowSpline() {}
+  
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+  
+  ClassDef(MExtractFixedWindowSpline, 0)   // Task to Extract the Arrival Times using a Fast Spline
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/msignal/MExtractPINDiode.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractPINDiode.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractPINDiode.cc	(revision 9772)
@@ -0,0 +1,280 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractPINDiode
+//
+//  Extracts the signal from a fixed window in a given range.
+//
+//  Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//  to modify the ranges. Ranges have to be an even number. In case of odd 
+//  ranges, the last slice will be reduced by one.
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  3 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractPINDiode.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalPINDiode.h"
+
+ClassImp(MExtractPINDiode);
+
+using namespace std;
+
+const UInt_t MExtractPINDiode::fgPINDiodeIdx     = 100;
+const Byte_t MExtractPINDiode::fgHiGainFirst =  0;
+const Byte_t MExtractPINDiode::fgHiGainLast  =  14;
+const Byte_t MExtractPINDiode::fgLoGainFirst =  0;
+const Byte_t MExtractPINDiode::fgLoGainLast  =  14;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// - SetPINDiodeIdx()
+//
+MExtractPINDiode::MExtractPINDiode(const char *name, const char *title)
+{
+  
+  fName  = name  ? name  : "MExtractPINDiode";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+  
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+  SetPINDiodeIdx();
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Checks: 
+// - if the window defined by (fHiGainLast-fHiGainFirst-1) are odd, subtract one
+// - if the window defined by (fLoGainLast-fLoGainFirst-1) are odd, subtract one
+// - if the Hi Gain window is smaller than 2, set fHiGainLast to fHiGainFirst+1
+// - if the Lo Gain window is smaller than 2, set fLoGainLast to fLoGainFirst+1
+// 
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)(fHiGainLast-fHiGainFirst+1)
+// - fNumLoGainSamples to: (Float_t)(fLoGainLast-fLoGainFirst+1)
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractPINDiode::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  const Byte_t window = hilast-hifirst+1+lolast-lofirst+1;
+  const Byte_t weven  = window & ~1;
+
+  if (weven != window)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Total window size has to be even, set last slice from "
+                    ,(int)lolast," to ",(int)(lolast-1)) << endl;
+      lolast -= 1;
+    }
+  
+  if (window<2) 
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i",": Total window is smaller than 2 FADC sampes, set last slice from" 
+                    ,(int)lolast," to ",(int)(lofirst+1)) << endl;
+      hilast = hifirst+1;
+    }
+  
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  fNumHiGainSamples = (Float_t)(fHiGainLast-fHiGainFirst+1);
+  fNumLoGainSamples = (fLoGainLast == 0) ? 0. : (Float_t)(fLoGainLast-fLoGainFirst+1);  
+
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);  
+  
+  fNumSamples = (fLoGainLast == 0) 
+    ? fHiGainLast-fHiGainFirst+1 
+    : fHiGainLast-fHiGainFirst+1+fLoGainLast-fLoGainFirst+1;
+  fSqrtSamples = TMath::Sqrt((Float_t)fNumSamples);
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls: 
+// - MExtractor::PreProcess
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedPINDiode
+//
+Int_t MExtractPINDiode::PreProcess(MParList *pList)
+{
+
+  if (!MExtractor::PreProcess(pList))
+    return kFALSE;
+  
+  fPINDiode = (MExtractedSignalPINDiode*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalPINDiode"));
+  if (!fPINDiode)
+    return kFALSE;
+
+  const MPedestalPix &ped   = (*fPedestals)[fPINDiodeIdx]; 
+
+    if (&ped)
+      {
+        fPedestal = ped.GetPedestal();
+        fPedRms   = ped.GetPedestalRms();
+      }
+    else
+      {
+        *fLog << err << " Cannot find MPedestalPix of the PIN Diode (idx=" 
+              << fPINDiodeIdx << ")" << endl;
+        return kFALSE;
+      }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+// -  fPINDiode->SetUsedFADCSlices(fHiGainFirst, fLoGainLast);
+//
+Bool_t MExtractPINDiode::ReInit(MParList *pList)
+{
+
+  MExtractor::ReInit(pList);
+  
+  fPINDiode->SetUsedFADCSlices(fHiGainFirst, fLoGainLast);
+  
+  return kTRUE;
+  
+}
+
+
+
+void MExtractPINDiode::FindSignalandVarianceHiGain(Byte_t *ptr, Int_t &sum, Int_t &sum2, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+  while (ptr<end)
+    {
+      sum  += *ptr;
+      sum2 += *ptr * *ptr;
+
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+}
+
+void MExtractPINDiode::FindSignalandVarianceLoGain(Byte_t *ptr, Int_t &sum, Int_t &sum2, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr +  fLoGainLast - fLoGainFirst  + 1;
+
+  while (ptr<end)
+    {
+      sum  += *ptr;
+      sum2 += *ptr * *ptr;
+      
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedPINDiode container.
+//
+Int_t MExtractPINDiode::Process()
+{
+
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  
+  fPINDiode->Clear();
+  
+  pixel.Jump(fPINDiodeIdx);
+  
+  Int_t sum   = 0;
+  Int_t sum2  = 0;
+  Byte_t sat  = 0;
+  Int_t max   = 0;
+  
+  // 
+  // Calculate first the time:
+  //
+  const Int_t maxhi = pixel.GetIdxMaxHiGainSample();
+  const Int_t maxlo = pixel.GetIdxMaxLoGainSample();
+  
+  if (maxhi > maxlo)
+    max = maxhi;
+  else
+    max = maxlo + pixel.GetNumHiGainSamples();
+  
+  FindSignalandVarianceHiGain(pixel.GetHiGainSamples()+fHiGainFirst,sum,sum2,sat);
+  if (pixel.HasLoGain())
+    FindSignalandVarianceLoGain(pixel.GetLoGainSamples()+fLoGainFirst,sum,sum2,sat);
+
+  const Float_t var = ((Float_t)sum2 - (Float_t)sum*sum/fNumSamples)/(fNumSamples-1);
+  const Float_t rms = TMath::Sqrt(var);
+  
+  // 
+  // FIXME: The following formulae have to be revised!!
+  //
+  fPINDiode->SetExtractedSignal(sum - fPedestal*fNumSamples, fPedRms*fSqrtSamples);
+  fPINDiode->SetExtractedRms   (rms, rms/2./fSqrtSamples);
+  fPINDiode->SetExtractedTime  (max, rms/fSqrtSamples);
+  fPINDiode->SetSaturation(sat);
+  fPINDiode->SetReadyToSave();
+  
+  return kTRUE;
+}
+
Index: /tags/Mars-V0.9/msignal/MExtractPINDiode.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractPINDiode.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractPINDiode.h	(revision 9772)
@@ -0,0 +1,54 @@
+#ifndef MARS_MExtractPINDiode
+#define MARS_MExtractPINDiode
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractPINDiode                                                        //
+//                                                                         //
+// Integrates the time slices of the all pixels of a calibration event     //
+// and substract the pedestal value                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractedSignalPINDiode;
+class MExtractPINDiode : public MExtractor
+{
+private:
+
+  static const UInt_t fgPINDiodeIdx;  
+  static const Byte_t fgHiGainFirst;     // First FADC slice Hi-Gain (currently set to: 3) 
+  static const Byte_t fgHiGainLast;      // Last FADC slice Hi-Gain (currently set to: 14) 
+  static const Byte_t fgLoGainFirst;     // First FADC slice Lo-Gain (currently set to: 3) 
+  static const Byte_t fgLoGainLast;      // Last FADC slice Lo-Gain (currently set to: 14) 
+
+  MExtractedSignalPINDiode  *fPINDiode;     // Extracted signal of the PIN Diode
+
+  UInt_t  fPINDiodeIdx;
+  Float_t fPedestal;
+  Float_t fPedRms;
+  Int_t   fNumSamples;
+  Float_t fSqrtSamples;
+  
+  void   FindSignalandVarianceHiGain(Byte_t *ptr, Int_t &sum, Int_t &sum2, Byte_t &sat) const;
+  void   FindSignalandVarianceLoGain(Byte_t *ptr, Int_t &sum, Int_t &sum2, Byte_t &sat) const;
+
+  Int_t  PreProcess(MParList *pList);
+  Bool_t ReInit(MParList *pList);  
+  Int_t  Process();
+  
+public:
+
+  MExtractPINDiode(const char *name=NULL, const char *title=NULL);
+
+  // Setters
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+  void SetPINDiodeIdx(    const UInt_t idx=fgPINDiodeIdx    ) { fPINDiodeIdx     = idx; }   
+
+  ClassDef(MExtractPINDiode, 0) // Signal Extractor for the PIN Diode
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractSignal.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSignal.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSignal.cc	(revision 9772)
@@ -0,0 +1,228 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 09/2003 <mailto:markus@ifae.es>
+!              Thomas Bretz, 01/2004 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSignal
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractSignal.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MExtractSignal);
+
+using namespace std;
+
+const Byte_t MExtractSignal::fgSaturationLimit = 254;
+const Byte_t MExtractSignal::fgFirst =  3;
+const Byte_t MExtractSignal::fgLast  = 14;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MExtractSignal::MExtractSignal(const char *name, const char *title)
+    : fSaturationLimit(fgSaturationLimit)
+{
+
+    fName  = name  ? name  : "MExtractSignal";
+    fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+    AddToBranchList("MRawEvtData.*");
+
+    SetRange();
+}
+
+void MExtractSignal::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+    fNumHiGainSamples = hilast-hifirst+1;
+    fNumLoGainSamples = lolast-lofirst+1;
+
+    fHiGainFirst = hifirst;
+    fLoGainFirst = lofirst;
+
+    fSqrtHiGainSamples = TMath::Sqrt((Float_t)fNumHiGainSamples);
+    fSqrtLoGainSamples = TMath::Sqrt((Float_t)fNumLoGainSamples);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MExtractSignal::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    fSignals = (MExtractedSignalCam*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalCam"));
+    if (!fSignals)
+        return kFALSE;
+
+    fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainFirst+fNumHiGainSamples-1, (Float_t)fNumHiGainSamples,
+                                fLoGainFirst, fLoGainFirst+fNumLoGainSamples-1, (Float_t)fNumLoGainSamples);
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+void MExtractSignal::FindSignal(Byte_t *ptr, Int_t size, Int_t &sum, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr + size;
+  
+  sum = 0;
+  sat = 0;
+  
+  while (ptr<end)
+    {
+      sum += *ptr;
+      
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedSignalCam container.
+//
+Int_t MExtractSignal::Process()
+{
+    MRawEvtPixelIter pixel(fRawEvt);
+    fSignals->Clear();
+
+    UInt_t  sat=0;
+
+    while (pixel.Next())
+    {
+        Int_t sumhi;
+        Byte_t sathi;
+
+        FindSignal(pixel.GetHiGainSamples()+fHiGainFirst, fNumHiGainSamples, sumhi, sathi);
+
+        Int_t  sumlo = 0;
+        Byte_t satlo = 0;
+        if (pixel.HasLoGain())
+        {
+            FindSignal(pixel.GetLoGainSamples()+fLoGainFirst, fNumLoGainSamples, sumlo, satlo);
+
+            if (satlo)
+              sat++;
+        }
+
+        const Int_t pixid = pixel.GetPixelId();
+
+        const MPedestalPix  &ped = (*fPedestals)[pixid]; 
+	MExtractedSignalPix &pix = (*fSignals)[pixid];
+
+        const Float_t pedes  = ped.GetPedestal();
+        const Float_t pedrms = ped.GetPedestalRms();
+
+        pix.SetExtractedSignal(sumhi - pedes*fNumHiGainSamples, pedrms*fSqrtHiGainSamples,
+                               sumlo - pedes*fNumLoGainSamples, pedrms*fSqrtLoGainSamples);
+
+	pix.SetGainSaturation(sathi, sathi, satlo);
+
+    } /* while (pixel.Next()) */
+
+    fSignals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MExtractSignal::StreamPrimitive(ofstream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    if (fSaturationLimit!=fgSaturationLimit)
+    {
+        out << "   " << GetUniqueName() << ".SetSaturationLimit(";
+        out << (int)fSaturationLimit << ");" << endl;
+    }
+
+    const Bool_t arg4 = fNumLoGainSamples+fLoGainFirst-1 != fgLast;
+    const Bool_t arg3 = arg4 || fLoGainFirst != fgFirst;
+    const Bool_t arg2 = arg3 || fNumHiGainSamples+fHiGainFirst-1 != fgLast;
+    const Bool_t arg1 = arg2 || fHiGainFirst != fgFirst;
+
+    if (!arg1)
+        return;
+
+    out << "   " << GetUniqueName() << ".SetRange(";
+    out << (int)fLoGainFirst;
+    if (arg2)
+    {
+        out << ", " << (int)(fNumHiGainSamples+fHiGainFirst-1);
+        if (arg3)
+        {
+            out << ", " << (int)fLoGainFirst;
+            if (arg4)
+                out << ", " << (int)(fNumLoGainSamples+fLoGainFirst-1);
+        }
+    }
+    out << ");" << endl;
+}
Index: /tags/Mars-V0.9/msignal/MExtractSignal.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSignal.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSignal.h	(revision 9772)
@@ -0,0 +1,62 @@
+#ifndef MARS_MExtractSignal
+#define MARS_MExtractSignal
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractSignal                                                          //
+//                                                                         //
+// Integrates the time slices of the all pixels of a calibration event     //
+// and substract the pedestal value                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalCam;
+class MExtractedSignalCam;
+
+class MExtractSignal : public MTask
+{
+private:
+    static const Byte_t fgSaturationLimit;
+    static const Byte_t fgFirst;
+    static const Byte_t fgLast;
+
+    MPedestalCam        *fPedestals;    // Pedestals of all pixels in the camera
+    MExtractedSignalCam *fSignals;      // Extracted signal of all pixels in the camera
+
+    MRawEvtData         *fRawEvt;       // raw event data (time slices)
+    MRawRunHeader       *fRunHeader;    // RunHeader information
+
+    Byte_t  fHiGainFirst;
+    Byte_t  fLoGainFirst;
+
+    Byte_t  fNumHiGainSamples;
+    Byte_t  fNumLoGainSamples;
+
+    Float_t fSqrtHiGainSamples;
+    Float_t fSqrtLoGainSamples;
+
+    Byte_t  fSaturationLimit;
+
+    void   FindSignal(Byte_t *ptr, Int_t size, Int_t &sum, Byte_t &sat) const;
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    void   StreamPrimitive(ofstream &out) const;
+
+public:
+    MExtractSignal(const char *name=NULL, const char *title=NULL);
+
+    void SetRange(Byte_t hifirst=fgFirst, Byte_t hilast=fgLast, Byte_t lofirst=fgFirst, Byte_t lolast=fgLast);
+    void SetSaturationLimit(Byte_t lim) { fSaturationLimit = lim; }
+
+    ClassDef(MExtractSignal, 0) // Task to fill the Extracted Signal Containers from raw data
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractSignal2.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSignal2.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSignal2.cc	(revision 9772)
@@ -0,0 +1,259 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Hendrik Bartko, 01/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSignal2
+//
+//  Calculate the signal as the fWindowSize time slices which have the highest
+// integral contents.
+//
+// 
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractSignal2.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+//#include "MArrivalTime.h"
+
+ClassImp(MExtractSignal2);
+
+using namespace std;
+
+const Byte_t MExtractSignal2::fgSaturationLimit = 254;
+const Byte_t MExtractSignal2::fgFirst      =  3;
+const Byte_t MExtractSignal2::fgLast       = 14;
+const Byte_t MExtractSignal2::fgWindowSize = 6;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MExtractSignal2::MExtractSignal2(const char *name, const char *title)
+  : fSaturationLimit(fgSaturationLimit)
+{
+
+    fName  = name  ? name  : "MExtractSignal2";
+    fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+    AddToBranchList("MRawEvtData.*");
+
+    SetRange();
+}
+
+void MExtractSignal2::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t windowh, Byte_t lofirst, Byte_t lolast, Byte_t windowl)
+{
+
+    fNumHiGainSamples = hilast-hifirst+1;
+    fNumLoGainSamples = lolast-lofirst+1;
+
+    fHiGainFirst = hifirst;
+    fLoGainFirst = lofirst;
+
+    fWindowSizeHiGain = windowh & ~1;
+    fWindowSizeLoGain = windowl & ~1;
+
+    if (fWindowSizeHiGain != windowh)
+      *fLog << warn << "MExtractSignal2::SetRange - Hi Gain window size has to be even, set to: " 
+            << int(fWindowSizeHiGain) << " samples " << endl;
+    
+    if (fWindowSizeLoGain != windowl)
+      *fLog << warn << "MExtractSignal2::SetRange - Lo Gain window size has to be even, set to: " 
+            << int(fWindowSizeLoGain) << " samples " << endl;
+    
+    if (fWindowSizeHiGain<2) 
+    {
+      fWindowSizeHiGain = 2;
+      *fLog << warn << "MExtractSignal2::SetRange - Hi Gain window size set to two samples" << endl;
+    }
+
+    if (fWindowSizeLoGain<2) 
+    {
+      fWindowSizeLoGain = 2;
+      *fLog << warn << "MExtractSignal2::SetRange - Lo Gain window size set to two samples" << endl;
+    }
+
+    if (fWindowSizeHiGain > fNumHiGainSamples)
+    {
+      fWindowSizeHiGain = fNumHiGainSamples & ~1;
+      *fLog << warn << "MExtractSignal2::SetRange - Hi Gain window size set to " 
+            << int(fWindowSizeHiGain) << " samples " << endl;
+    }
+    
+    if (fWindowSizeLoGain > fNumLoGainSamples)
+    {
+      fWindowSizeLoGain = fNumLoGainSamples & ~1;
+      *fLog << warn << "MExtractSignal2::SetRange - Lo Gain window size set to " 
+            << int(fWindowSizeLoGain) << " samples " << endl;
+    }
+
+    fWindowSqrtHiGain = TMath::Sqrt((Float_t)fWindowSizeHiGain);
+    fWindowSqrtLoGain = TMath::Sqrt((Float_t)fWindowSizeLoGain);
+
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MExtractSignal2::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    fSignals = (MExtractedSignalCam*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalCam"));
+    if (!fSignals)
+        return kFALSE;
+
+    fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainFirst+fNumHiGainSamples-1, (Float_t)fWindowSizeHiGain,
+                                fLoGainFirst, fLoGainFirst+fNumLoGainSamples-1, (Float_t)fWindowSizeLoGain);
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        return kFALSE;
+    }
+    return kTRUE;
+}
+
+void MExtractSignal2::FindSignal(Byte_t *ptr, Byte_t size, Byte_t window, Int_t &max, Int_t &sat) const
+{
+    const Byte_t *end = ptr + size;
+
+    Int_t sum=0;
+
+    //
+    // Calculate the sum of the first fWindowSize slices
+    //
+    sat = 0;
+    Byte_t *p = ptr;
+    while (p<ptr+window)
+    {
+        sum += *p;
+        if (*p++ >= fSaturationLimit)
+            sat++;
+    }
+
+    //
+    // Check for saturation in all other slices
+    //
+    while (p<end)
+        if (*p++ >= fSaturationLimit)
+            sat++;
+
+    //
+    // Calculate the i-th sum as
+    //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+    // This is fast and accurate (because we are using int's)
+    //
+    max=sum;
+    for (p=ptr; p+window<end; p++)
+    {
+        sum += *(p+window) - *p;
+        if (sum>max)
+            max = sum;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC of fWindowSize time slices which have the
+// highest signal
+//
+Int_t MExtractSignal2::Process()
+{
+    MRawEvtPixelIter pixel(fRawEvt);
+    fSignals->Clear();
+
+    Int_t sat=0;
+    while (pixel.Next())
+    {
+        //
+        // Find signal in hi- and lo-gain
+        //
+        Int_t sumhi, sathi;
+        FindSignal(pixel.GetHiGainSamples()+fHiGainFirst, fNumHiGainSamples, fWindowSizeHiGain, sumhi, sathi);
+
+        Int_t sumlo=0;
+        Int_t satlo=0;
+        if (pixel.HasLoGain())
+        {
+            FindSignal(pixel.GetLoGainSamples()+fLoGainFirst, fNumLoGainSamples, fWindowSizeLoGain, sumlo, satlo);
+            if (satlo)
+                sat++;
+        }
+
+        //
+        // Take correspodning pedestal
+        //
+        const Int_t pixid = pixel.GetPixelId();
+
+        const MPedestalPix  &ped = (*fPedestals)[pixid];
+        MExtractedSignalPix &pix = (*fSignals)[pixid];
+
+        const Float_t pedes  = ped.GetPedestal();
+        const Float_t pedrms = ped.GetPedestalRms();
+
+        //
+        // Set extracted signal with pedestal substracted
+        //
+        pix.SetExtractedSignal(sumhi - pedes*fWindowSizeHiGain, pedrms*fWindowSqrtHiGain,
+                               sumlo - pedes*fWindowSizeLoGain, pedrms*fWindowSqrtLoGain);
+
+        pix.SetGainSaturation(sathi, sathi, satlo);
+    } /* while (pixel.Next()) */
+
+
+    fSignals->SetReadyToSave();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/msignal/MExtractSignal2.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSignal2.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSignal2.h	(revision 9772)
@@ -0,0 +1,62 @@
+#ifndef MARS_MExtractSignal2
+#define MARS_MExtractSignal2
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalCam;
+class MExtractedSignalCam;
+//class MArrivalTime;
+
+class MExtractSignal2 : public MTask
+{
+private:
+    static const Byte_t fgSaturationLimit;
+    static const Byte_t fgFirst;
+    static const Byte_t fgLast;
+    static const Byte_t fgWindowSize;
+
+    MPedestalCam        *fPedestals;    // Pedestals of all pixels in the camera
+    MExtractedSignalCam *fSignals;      // Extracted signal of all pixels in the camera
+
+    MRawEvtData         *fRawEvt;       // raw event data (time slices)
+    MRawRunHeader       *fRunHeader;    // RunHeader information
+
+    /*
+     MArrivalTime        *fArrivalTime;  // Arrival Time of FADC sample
+     */
+  
+    Byte_t  fHiGainFirst;       // First hi gain to be used
+    Byte_t  fLoGainFirst;       // First lo gain to be used
+
+    Byte_t  fNumHiGainSamples;  // Number of hi gain to be used
+    Byte_t  fNumLoGainSamples;  // Number of lo gain to be used
+
+    Byte_t  fWindowSizeHiGain;  // Number of Hi Gain slices in window
+    Float_t fWindowSqrtHiGain;  // Sqaure root of number of Hi Gain slices in window
+
+    Byte_t  fWindowSizeLoGain;  // Number of Lo Gain slices in window
+    Float_t fWindowSqrtLoGain;  // Sqaure root of number of Lo Gain slices in window
+
+    Byte_t  fSaturationLimit;
+
+    void   FindSignal(Byte_t *ptr, Byte_t size, Byte_t window, Int_t &max, Int_t &sat) const;
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+public:
+    MExtractSignal2(const char *name=NULL, const char *title=NULL);
+
+    void SetRange(Byte_t hifirst=fgFirst, Byte_t hilast=fgLast, Byte_t windowh=fgWindowSize,
+                  Byte_t lofirst=fgFirst, Byte_t lolast=fgLast, Byte_t windowl=fgWindowSize);
+    void SetSaturationLimit(Byte_t lim) { fSaturationLimit = lim; }
+
+    ClassDef(MExtractSignal2, 0) // Extracted Signal as highest integral content
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractSignal3.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSignal3.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSignal3.cc	(revision 9772)
@@ -0,0 +1,365 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Abelardo Moralejo, 4/2004 <mailto:moralejo@pd.infn.it>
+   !
+   !   Copyright: MAGIC Software Development, 2000-2004
+   !
+   !
+   \* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSignal3
+//
+//  Calculate the signal integrating fWindowSize time slices, the same for 
+//  all pixels. The integrated slices change from event to event, since the
+//  pulse positions in the FADC jump between events, but apparently in a 
+//  "coherent" fashion. We first loop over all pixels and find the one 
+//  which has the highest sum of fPeakSearchWindowSize (default: 4) consecutive 
+//  non-saturated high gain slices. The position of the peak in this pixel 
+//  determines the integration window position for all pixels of this event. 
+//  For the moment we neglect time delays between pixels (which are in most 
+//  cases small). The class is based on MExtractSignal2.
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MExtractSignal3.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MExtractSignal3);
+
+using namespace std;
+
+const Byte_t MExtractSignal3::fgSaturationLimit = 254;
+const Byte_t MExtractSignal3::fgFirst  =  0;
+const Byte_t MExtractSignal3::fgLast   = 14;
+const Byte_t MExtractSignal3::fgWindowSize = 6;
+const Byte_t MExtractSignal3::fgPeakSearchWindowSize = 4;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MExtractSignal3::MExtractSignal3(const char *name, const char *title)
+  : fNumHiGainSamples(15), fNumLoGainSamples(15), fSaturationLimit(fgSaturationLimit)
+{
+
+  fName  = name  ? name  : "MExtractSignal3";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+  AddToBranchList("MRawEvtData.*");
+
+  SetWindows();
+}
+
+void MExtractSignal3::SetWindows(Byte_t windowh, Byte_t windowl, Byte_t peaksearchwindow)
+{
+  //
+  // Set windows to even number of slices due to clock noise (odd/even slice effect).
+  //
+  fWindowSizeHiGain = windowh & ~1;
+  fWindowSizeLoGain = windowl & ~1;
+  fPeakSearchWindowSize = peaksearchwindow & ~1;
+
+
+  if (fWindowSizeHiGain != windowh)
+    *fLog << endl << warn << 
+      "MExtractSignal3::SetWindows - Hi Gain window size has to be even, set to: " 
+	  << int(fWindowSizeHiGain) << " samples " << endl;
+    
+  if (fWindowSizeLoGain != windowl)
+    *fLog << endl << warn << 
+      "MExtractSignal3::SetWindows - Lo Gain window size has to be even, set to: " 
+	  << int(fWindowSizeLoGain) << " samples " << endl;
+
+  if (fPeakSearchWindowSize != peaksearchwindow)
+    *fLog << endl << warn << 
+      "MExtractSignal3::SetWindows - Peak Search window size has to be even, set to: " 
+	  << int(fPeakSearchWindowSize) << " samples " << endl;
+
+
+  if (fWindowSizeHiGain<2) 
+    {
+      fWindowSizeHiGain = 2;
+      *fLog << warn << "MExtractSignal3::SetWindows - Hi Gain window size set to two samples" << endl;
+    }
+
+  if (fWindowSizeLoGain<2) 
+    {
+      fWindowSizeLoGain = 2;
+      *fLog << warn << "MExtractSignal3::SetWindows - Lo Gain window size set to two samples" << endl;
+    }
+
+  if (fPeakSearchWindowSize<2) 
+    {
+      fPeakSearchWindowSize = 2;
+      *fLog << warn << "MExtractSignal3::SetWindows - Peak Search window size set to two samples" << endl;
+    }
+
+
+  if (fWindowSizeHiGain > fNumHiGainSamples)
+    {
+      fWindowSizeHiGain = fNumHiGainSamples & ~1;
+      *fLog << warn << "MExtractSignal3::SetWindows - Hi Gain window size set to " 
+            << int(fWindowSizeHiGain) << " samples " << endl;
+    }
+  
+  if (fWindowSizeLoGain > fNumLoGainSamples)
+    {
+      fWindowSizeLoGain = fNumLoGainSamples & ~1;
+      *fLog << warn << "MExtractSignal3::SetWindows - Lo Gain window size set to " 
+            << int(fWindowSizeLoGain) << " samples " << endl;
+    }
+
+  fWindowSqrtHiGain = TMath::Sqrt((Float_t)fWindowSizeHiGain);
+  fWindowSqrtLoGain = TMath::Sqrt((Float_t)fWindowSizeLoGain);
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MExtractSignal3::PreProcess(MParList *pList)
+{
+  fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+  if (!fRawEvt)
+    {
+      *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  fSignals = (MExtractedSignalCam*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalCam"));
+  if (!fSignals)
+    return kFALSE;
+
+  //
+  // FIXME? We should keep track in MExtractedSignalCam of the signal extraction method used.
+  //
+  fSignals->SetUsedFADCSlices(0, fNumHiGainSamples-1, (Float_t)fWindowSizeHiGain,
+			      0, fNumLoGainSamples-1, (Float_t)fWindowSizeLoGain);
+
+  fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+  if (!fPedestals)
+    {
+      *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindPeak
+// Finds highest sum of "window" consecutive FADC slices in a pixel, and store
+// in "startslice" the first slice of the group which yields the maximum sum.
+// In "max" the value of the maximum sum is stored, in "sat" the number of 
+// saturated slices.
+//
+void MExtractSignal3::FindPeak(Byte_t *ptr, Byte_t window, Byte_t &startslice, 
+			       Int_t &max, Int_t &sat) const
+{
+  const Byte_t *end = ptr + fNumHiGainSamples;
+
+  Int_t sum=0;
+
+  //
+  // Calculate the sum of the first "window" slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+
+  while (p<ptr+window)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+	sat++;
+    }
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+
+  //
+  // Calculate the i-th sum of n as
+  //    sum_i+1 = sum_i + slice[i+window] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  for (p=ptr; p+window<end; p++)
+    {
+      sum += *(p+window) - *p;
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = p-ptr;
+	}
+    }
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindSignal
+// Adds up "window" slices starting in slice to which "ptr" points. The result 
+// is stored in "sum", and the number of saturated  slices in "sat".
+//
+void MExtractSignal3::FindSignal(Byte_t *ptr, Byte_t window, Int_t &sum, Int_t &sat) const
+{
+  //
+  // Calculate the sum of the "window" slices starting in ptr
+  //
+  sum=0;
+  sat = 0;
+  Byte_t *p = ptr;
+
+  while (p<ptr+window)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+	sat++;
+    }
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// Process
+// First find the pixel with highest sum of fPeakSearchWindowSize slices (default:4)
+// "startslice" will mark the slice at which the highest sum begins for that pixel.
+// Then define the beginning of the integration window for ALL pixels as the slice
+// before that: startslice-1 (this is somehow arbitrary), unless of course startslice=0,
+// in which case we start at 0. We will also check that the integration window does not 
+// go beyond the FADC limits.
+//
+Int_t MExtractSignal3::Process()
+{
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  Int_t sat;
+  Int_t maxsumhi = 0;
+  Byte_t startslice;
+  Byte_t hiGainFirst = 0;
+  Byte_t loGainFirst = 0;
+
+  while (pixel.Next())
+    {
+      Int_t sumhi;
+      sat = 0;
+
+      FindPeak(pixel.GetHiGainSamples(), fPeakSearchWindowSize, startslice, sumhi, sat);
+      if (sumhi > maxsumhi && sat == 0 )
+	{
+	  maxsumhi = sumhi;
+	  if (startslice > 0)
+	    hiGainFirst = startslice-1;
+	  else
+	    hiGainFirst = 0;
+	}
+    }
+
+
+  loGainFirst = hiGainFirst;
+
+  // Make sure we will not integrate beyond the hi gain limit:
+  if (hiGainFirst+fWindowSizeHiGain > pixel.GetNumHiGainSamples())
+    hiGainFirst = pixel.GetNumHiGainSamples()-fWindowSizeHiGain;
+
+  // Make sure we will not integrate beyond the lo gain limit:
+  if (loGainFirst+fWindowSizeLoGain > pixel.GetNumLoGainSamples())
+    loGainFirst = pixel.GetNumLoGainSamples()-fWindowSizeLoGain;
+
+  pixel.Reset();
+  fSignals->Clear();
+
+  sat = 0;
+  while (pixel.Next())
+    {
+      //
+      // Find signal in hi- and lo-gain
+      //
+      Int_t sumhi, sathi;
+
+      FindSignal(pixel.GetHiGainSamples()+hiGainFirst, fWindowSizeHiGain, sumhi, sathi);
+
+      Int_t sumlo=0;
+      Int_t satlo=0;
+      if (pixel.HasLoGain())
+        {
+	  FindSignal(pixel.GetLoGainSamples()+loGainFirst, fWindowSizeLoGain, sumlo, satlo);
+	  if (satlo)
+	    sat++;
+        }
+
+      //
+      // Take corresponding pedestal
+      //
+      const Int_t pixid = pixel.GetPixelId();
+
+      const MPedestalPix  &ped = (*fPedestals)[pixid];
+      MExtractedSignalPix &pix = (*fSignals)[pixid];
+
+      const Float_t pedes  = ped.GetPedestal();
+      const Float_t pedrms = ped.GetPedestalRms();
+
+      //
+      // Set extracted signal with pedestal substracted
+      //
+      pix.SetExtractedSignal(sumhi - pedes*fWindowSizeHiGain, pedrms*fWindowSqrtHiGain,
+			     sumlo - pedes*fWindowSizeLoGain, pedrms*fWindowSqrtLoGain);
+
+      pix.SetGainSaturation(sathi, sathi, satlo);
+    } /* while (pixel.Next()) */
+
+  //
+  // Print a warning if event has saturationg lo-gains
+  //
+  if (sat)
+    *fLog << warn << "WARNING - Lo Gain saturated in " << sat << " pixels." << endl;
+
+  fSignals->SetReadyToSave();
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/msignal/MExtractSignal3.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSignal3.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSignal3.h	(revision 9772)
@@ -0,0 +1,63 @@
+#ifndef MARS_MExtractSignal3
+#define MARS_MExtractSignal3
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalCam;
+class MExtractedSignalCam;
+
+class MExtractSignal3 : public MTask
+{
+private:
+    static const Byte_t fgSaturationLimit;
+    static const Byte_t fgFirst;
+    static const Byte_t fgLast;
+    static const Byte_t fgWindowSize;
+    static const Byte_t fgPeakSearchWindowSize;
+
+    MPedestalCam        *fPedestals;    // Pedestals of all pixels in the camera
+    MExtractedSignalCam *fSignals;      // Extracted signal of all pixels in the camera
+
+    MRawEvtData         *fRawEvt;       // raw event data (time slices)
+    MRawRunHeader       *fRunHeader;    // RunHeader information
+
+
+    Byte_t  fPeakSearchWindowSize; // Size of FADC window in the search for the highest peak
+                                   // of all pixels.
+
+    Byte_t  fNumHiGainSamples;
+    Byte_t  fNumLoGainSamples;
+
+    Byte_t  fWindowSizeHiGain;  // Number of Hi Gain slices in window
+    Float_t fWindowSqrtHiGain;  // Square root of number of Hi Gain slices in window
+
+    Byte_t  fWindowSizeLoGain;  // Number of Lo Gain slices in window
+    Float_t fWindowSqrtLoGain;  // Square root of number of Lo Gain slices in window
+
+    Byte_t  fSaturationLimit;
+
+    void   FindSignal(Byte_t *ptr, Byte_t window, Int_t &sum, Int_t &sat) const;
+
+    void   FindPeak(Byte_t *ptr, Byte_t window, Byte_t &startslice, Int_t &signal, Int_t &sat) const;
+
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+public:
+    MExtractSignal3(const char *name=NULL, const char *title=NULL);
+
+    void SetWindows(Byte_t windowh=fgWindowSize, Byte_t windowl=fgWindowSize, 
+		    Byte_t peaksearchwindow=fgPeakSearchWindowSize);
+
+    void SetSaturationLimit(Byte_t lim) { fSaturationLimit = lim; }
+
+    ClassDef(MExtractSignal3, 0) // Extracted Signal algorithm #3
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractSignalABcorr.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSignalABcorr.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSignalABcorr.cc	(revision 9772)
@@ -0,0 +1,248 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 09/2003 <mailto:markus@ifae.es>
+!              Thomas Bretz, 01/2004 
+!              Florian Goebel, 06/2004
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSignalABcorr
+//
+//   this class is basically a copy of MExtractSignal and is mainly ment as 
+//   an example of how to use the "AB pedestal offset" to correct for the 
+//   150 MHz clock noise. It allows to extract a signal using an odd number 
+//   of slices 
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractSignalABcorr.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MExtractSignalABcorr);
+
+using namespace std;
+
+const Byte_t MExtractSignalABcorr::fgSaturationLimit = 254;
+const Byte_t MExtractSignalABcorr::fgFirst =  3;
+const Byte_t MExtractSignalABcorr::fgLast  = 14;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MExtractSignalABcorr::MExtractSignalABcorr(const char *name, const char *title)
+    : fSaturationLimit(fgSaturationLimit)
+{
+
+    fName  = name  ? name  : "MExtractSignalABcorr";
+    fTitle = title ? title : "Task to extract the signal from the FADC slices";
+
+    AddToBranchList("MRawEvtData.*");
+
+    SetRange();
+}
+
+void MExtractSignalABcorr::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+    fNumHiGainSamples = hilast-hifirst+1;
+    fNumLoGainSamples = lolast-lofirst+1;
+
+    fHiGainFirst = hifirst;
+    fLoGainFirst = lofirst;
+
+    fSqrtHiGainSamples = TMath::Sqrt((Float_t)fNumHiGainSamples);
+    fSqrtLoGainSamples = TMath::Sqrt((Float_t)fNumLoGainSamples);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MExtractSignalABcorr::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    fSignals = (MExtractedSignalCam*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalCam"));
+    if (!fSignals)
+        return kFALSE;
+
+    fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainFirst+fNumHiGainSamples-1, (Float_t)fNumHiGainSamples,
+                                fLoGainFirst, fLoGainFirst+fNumLoGainSamples-1, (Float_t)fNumLoGainSamples);
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+void MExtractSignalABcorr::FindSignal(Byte_t *ptr, Int_t size, Int_t &sum, Byte_t &sat) const
+{
+
+  Byte_t *end = ptr + size;
+  
+  sum = 0;
+  sat = 0;
+  
+  while (ptr<end)
+    {
+      sum += *ptr;
+      
+      if (*ptr++ >= fSaturationLimit)
+        sat++;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedSignalCam container.
+//
+Int_t MExtractSignalABcorr::Process()
+{
+    MRawEvtPixelIter pixel(fRawEvt);
+    fSignals->Clear();
+
+    UInt_t  sat=0;
+
+    const Bool_t ApplyABcorrHi = fNumHiGainSamples&0x1;
+    const Bool_t ApplyABcorrLo = fNumLoGainSamples&0x1;
+
+    while (pixel.Next())
+    {
+        Int_t sumhi;
+        Byte_t sathi;
+
+        FindSignal(pixel.GetHiGainSamples()+fHiGainFirst, fNumHiGainSamples, sumhi, sathi);
+
+        Int_t  sumlo = 0;
+        Byte_t satlo = 0;
+        if (pixel.HasLoGain())
+        {
+            FindSignal(pixel.GetLoGainSamples()+fLoGainFirst, fNumLoGainSamples, sumlo, satlo);
+
+            if (satlo)
+              sat++;
+        }
+
+        const Int_t pixid   = pixel.GetPixelId();
+	const Bool_t ABFlag = pixel.HasABFlag();
+
+        const MPedestalPix  &ped = (*fPedestals)[pixid]; 
+	MExtractedSignalPix &pix = (*fSignals)[pixid];
+
+        const Float_t pedes  = ped.GetPedestal();
+        const Float_t pedrms = ped.GetPedestalRms();
+	const Float_t ABoffs = ped.GetPedestalABoffset();
+
+	Float_t pedtothi = pedes*fNumHiGainSamples;
+	Float_t pedtotlo = pedes*fNumLoGainSamples;
+
+	if (ApplyABcorrHi) {
+	  pedtothi += ABoffs*(1-2*((fHiGainFirst+ABFlag)&0x1));
+	}
+	if (ApplyABcorrLo) {
+	  pedtotlo += ABoffs*(1-2*((fLoGainFirst+ABFlag)&0x1));
+	}
+
+        pix.SetExtractedSignal(sumhi - pedtothi, pedrms*fSqrtHiGainSamples,
+                               sumlo - pedtotlo, pedrms*fSqrtLoGainSamples);
+
+	pix.SetGainSaturation(sathi, sathi, satlo);
+
+    } /* while (pixel.Next()) */
+
+    fSignals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MExtractSignalABcorr::StreamPrimitive(ofstream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    if (fSaturationLimit!=fgSaturationLimit)
+    {
+        out << "   " << GetUniqueName() << ".SetSaturationLimit(";
+        out << (int)fSaturationLimit << ");" << endl;
+    }
+
+    const Bool_t arg4 = fNumLoGainSamples+fLoGainFirst-1 != fgLast;
+    const Bool_t arg3 = arg4 || fLoGainFirst != fgFirst;
+    const Bool_t arg2 = arg3 || fNumHiGainSamples+fHiGainFirst-1 != fgLast;
+    const Bool_t arg1 = arg2 || fHiGainFirst != fgFirst;
+
+    if (!arg1)
+        return;
+
+    out << "   " << GetUniqueName() << ".SetRange(";
+    out << (int)fLoGainFirst;
+    if (arg2)
+    {
+        out << ", " << (int)(fNumHiGainSamples+fHiGainFirst-1);
+        if (arg3)
+        {
+            out << ", " << (int)fLoGainFirst;
+            if (arg4)
+                out << ", " << (int)(fNumLoGainSamples+fLoGainFirst-1);
+        }
+    }
+    out << ");" << endl;
+}
Index: /tags/Mars-V0.9/msignal/MExtractSignalABcorr.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSignalABcorr.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSignalABcorr.h	(revision 9772)
@@ -0,0 +1,62 @@
+#ifndef MARS_MExtractSignalABcorr
+#define MARS_MExtractSignalABcorr
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractSignalABcorr                                                          //
+//                                                                         //
+// Integrates the time slices of the all pixels of a calibration event     //
+// and substract the pedestal value                                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalCam;
+class MExtractedSignalCam;
+
+class MExtractSignalABcorr : public MTask
+{
+private:
+    static const Byte_t fgSaturationLimit;
+    static const Byte_t fgFirst;
+    static const Byte_t fgLast;
+
+    MPedestalCam        *fPedestals;    // Pedestals of all pixels in the camera
+    MExtractedSignalCam *fSignals;      // Extracted signal of all pixels in the camera
+
+    MRawEvtData         *fRawEvt;       // raw event data (time slices)
+    MRawRunHeader       *fRunHeader;    // RunHeader information
+
+    Byte_t  fHiGainFirst;
+    Byte_t  fLoGainFirst;
+
+    Byte_t  fNumHiGainSamples;
+    Byte_t  fNumLoGainSamples;
+
+    Float_t fSqrtHiGainSamples;
+    Float_t fSqrtLoGainSamples;
+
+    Byte_t  fSaturationLimit;
+
+    void   FindSignal(Byte_t *ptr, Int_t size, Int_t &sum, Byte_t &sat) const;
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    void   StreamPrimitive(ofstream &out) const;
+
+public:
+    MExtractSignalABcorr(const char *name=NULL, const char *title=NULL);
+
+    void SetRange(Byte_t hifirst=fgFirst, Byte_t hilast=fgLast, Byte_t lofirst=fgFirst, Byte_t lolast=fgLast);
+    void SetSaturationLimit(Byte_t lim) { fSaturationLimit = lim; }
+
+    ClassDef(MExtractSignalABcorr, 0) // Task to fill the Extracted Signal Containers from raw data
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractSlidingWindow.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSlidingWindow.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSlidingWindow.cc	(revision 9772)
@@ -0,0 +1,344 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 01/2004 <mailto:hbartko@mppmu.mpg.de>
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSlidingWindow
+//
+//  Extracts the signal from a sliding window of size fHiGainWindowSize and 
+//  fLoGainWindowSize. The signal is the one which maximizes the integral 
+//  contents. 
+//
+//  Call: SetRange(higainfirst, higainlast, logainfirst, logainlast) 
+//  to modify the ranges in which the window is allowed to move. 
+//  Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  3 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//  Call: SetWindowSize(windowhigain, windowlogain) 
+//  to modify the sliding window widths. Windows have to be an even number. 
+//  In case of odd numbers, the window will be modified.
+//
+//  Defaults are:
+//
+//   fHiGainWindowSize = fgHiGainWindowSize = 6
+//   fLoGainWindowSize = fgLoGainWindowSize = 6
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractSlidingWindow.h"
+#include "MExtractor.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MExtractedSignalCam.h"
+
+ClassImp(MExtractSlidingWindow);
+
+using namespace std;
+
+const Byte_t MExtractSlidingWindow::fgHiGainFirst      = 0;
+const Byte_t MExtractSlidingWindow::fgHiGainLast       = 14;
+const Byte_t MExtractSlidingWindow::fgLoGainFirst      = 3;
+const Byte_t MExtractSlidingWindow::fgLoGainLast       = 14;
+const Byte_t MExtractSlidingWindow::fgHiGainWindowSize = 6;
+const Byte_t MExtractSlidingWindow::fgLoGainWindowSize = 6;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fWindowSizeHiGain to fgHiGainWindowSize
+// - fWindowSizeLoGain to fgLoGainWindowSize
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractSlidingWindow::MExtractSlidingWindow(const char *name, const char *title)
+    : fWindowSizeHiGain(fgHiGainWindowSize), 
+      fWindowSizeLoGain(fgLoGainWindowSize)
+{
+
+  fName  = name  ? name  : "MExtractSlidingWindow";
+  fTitle = title ? title : "Signal Extractor for a sliding FADC window";
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - SetWindowSize(fWindowSizeHiGain,fWindowSizeLoGain);
+//
+void MExtractSlidingWindow::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);
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+// -  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+//                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+//
+Bool_t MExtractSlidingWindow::ReInit(MParList *pList)
+{
+
+  MExtractor::ReInit(pList);
+  
+  fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                              fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+
+  *fLog << dec << endl;
+  *fLog << inf << "Taking " << fNumHiGainSamples
+        << " HiGain samples starting with slice " << (Int_t)fHiGainFirst
+        << " to " << (Int_t)(fHiGainLast+fHiLoLast) << " incl" << endl;
+  *fLog << inf << "Taking " << fNumLoGainSamples
+        << " LoGain samples starting with slice " << (Int_t)fLoGainFirst
+        << " to " << (Int_t)fLoGainLast << " incl" << endl;
+
+  return kTRUE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is odd, subtract one
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// - if a window is smaller than 2, set it to 2
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)fWindowSizeHiGain
+// - fNumLoGainSamples to: (Float_t)fWindowSizeLoGain
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractSlidingWindow::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;
+  
+  if (fWindowSizeLoGain != windowl)
+    *fLog << warn << GetDescriptor() << ": Lo Gain window size has to be even, set to: " 
+          << int(fWindowSizeLoGain) << " samples " << endl;
+    
+  const Byte_t availhirange = (fHiGainLast-fHiGainFirst+1) & ~1;
+
+  if (fWindowSizeHiGain > availhirange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",(int)fWindowSizeHiGain,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availhirange << endl;
+      fWindowSizeHiGain = availhirange;
+    }
+  
+  if (fWindowSizeHiGain<2) 
+    {
+      fWindowSizeHiGain = 2;
+      *fLog << warn << GetDescriptor() << ": Hi Gain window size set to two samples" << endl;
+    }
+  
+  if (fLoGainLast != 0 && fWindowSizeLoGain != 0)
+    {
+      const Byte_t availlorange = (fLoGainLast-fLoGainFirst+1) & ~1;
+      
+      if (fWindowSizeLoGain > availlorange)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",(int)fWindowSizeLoGain,
+                        " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+          *fLog << warn << GetDescriptor() 
+                << ": Will set window size to: " << (int)availlorange << endl;
+          fWindowSizeLoGain = availlorange;
+        }
+      
+      if (fWindowSizeLoGain<2) 
+        {
+          fWindowSizeLoGain = 2;
+          *fLog << warn << GetDescriptor() << ": Lo Gain window size set to two samples" << endl;
+        }
+    }
+  
+  fNumHiGainSamples = (Float_t)fWindowSizeHiGain;
+  fNumLoGainSamples = (Float_t)fWindowSizeLoGain;
+  
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalHiGain:
+//
+// - Loop from ptr to (ptr+fWindowSizeHiGain)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - Loop from (ptr+fWindowSizeHiGain) to (ptr+fHiGainLast-fHiGainFirst)
+// - Sum the content of *(ptr+fWindowSizeHiGain) and subtract *ptr
+// - Check if the sum has become bigger and store it in case yes.
+// 
+void MExtractSlidingWindow::FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &max, Byte_t &sat) const
+{
+    const Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+    Int_t sum=0;
+    Int_t sumtot =0;
+
+    //
+    // Calculate the sum of the first fWindowSize slices
+    //
+    sat = 0;
+    Byte_t *p = ptr;
+    
+    while (p<ptr+fWindowSizeHiGain-fHiLoLast)
+    {
+        sum += *p;
+        if (*p++ >= fSaturationLimit)
+            sat++;
+    }
+
+    //
+    // Check for saturation in all other slices
+    //
+    while (p<end)
+        if (*p++ >= fSaturationLimit)
+            sat++;
+
+    //
+    // If part of the "low-Gain" slices are used, 
+    // repeat steps one and two for the logain part until fHiLoLast
+    //
+    Byte_t *l = logain;
+    while (l<logain+fHiLoLast)
+      {
+        sum += *l;
+        if (*l++ >= fSaturationLimit)
+            sat++;
+      }
+
+
+    //
+    // Calculate the i-th sum as
+    //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+    // This is fast and accurate (because we are using int's)
+    //
+    sumtot=sum;
+    for (p=ptr; p+fWindowSizeHiGain-fHiLoLast<end; p++)
+    {
+        sum += *(p+fWindowSizeHiGain-fHiLoLast) - *p;
+        if (sum>sumtot)
+            sumtot = sum;
+    }
+
+    for (l=logain; l<logain+fHiLoLast; l++)
+    {
+        sum += *l - *p++;
+        if (sum>sumtot)
+            sumtot = sum;
+    }
+    max = (Float_t)sumtot;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// FindSignalLoGain:
+//
+// - Loop from ptr to (ptr+fWindowSizeLoGain)
+// - Sum up contents of *ptr
+// - If *ptr is greater than fSaturationLimit, raise sat by 1
+// - Loop from (ptr+fWindowSizeLoGain) to (ptr+fLoGainLast-fLoGainFirst)
+// - Sum the content of *(ptr+fWindowSizeLoGain) and subtract *ptr
+// - Check if the sum has become bigger and store it in case yes.
+// 
+void MExtractSlidingWindow::FindSignalLoGain(Byte_t *ptr, Float_t &max, Byte_t &sat) const
+{
+    const Byte_t *end = ptr + fLoGainLast - fLoGainFirst + 1;
+
+    Int_t sum=0;
+    Int_t sumtot=0;
+    //
+    // Calculate the sum of the first fWindowSize slices
+    //
+    sat = 0;
+    Byte_t *p = ptr;
+    while (p<ptr+fWindowSizeLoGain)
+    {
+        sum += *p;
+        if (*p++ >= fSaturationLimit)
+            sat++;
+    }
+
+    //
+    // Check for saturation in all other slices
+    //
+    while (p<end)
+        if (*p++ >= fSaturationLimit)
+            sat++;
+
+    //
+    // Calculate the i-th sum as
+    //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+    // This is fast and accurate (because we are using int's)
+    //
+    sumtot=sum;
+    for (p=ptr; p+fWindowSizeLoGain<end; p++)
+    {
+        sum += *(p+fWindowSizeLoGain) - *p;
+        if (sum>sumtot)
+            sumtot = sum;
+    }
+    max = (Float_t)sumtot;
+}
+
+
Index: /tags/Mars-V0.9/msignal/MExtractSlidingWindow.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractSlidingWindow.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractSlidingWindow.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MExtractSlidingWindow
+#define MARS_MExtractSlidingWindow
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MExtractSlidingWindow : public MExtractor
+{
+private:
+  
+  static const Byte_t fgHiGainFirst;      // First FADC slice Hi-Gain (currently set to: 3) 
+  static const Byte_t fgHiGainLast;       // Last FADC slice Hi-Gain (currently set to: 14) 
+  static const Byte_t fgLoGainFirst;      // First FADC slice Lo-Gain (currently set to: 3) 
+  static const Byte_t fgLoGainLast;       // Last FADC slice Lo-Gain (currently set to: 14) 
+  static const Byte_t fgHiGainWindowSize; // The extraction window Hi-Gain
+  static const Byte_t fgLoGainWindowSize; // The extraction window Lo-Gain
+
+  Byte_t  fWindowSizeHiGain;             // Number of Hi Gain slices in window
+  Byte_t  fWindowSizeLoGain;             // Number of Lo Gain slices in window  
+  
+  void   FindSignalHiGain(Byte_t *ptr, Byte_t *logain, Float_t &max, Byte_t &sat) const;
+  void   FindSignalLoGain(Byte_t *ptr, Float_t &max, Byte_t &sat) const;  
+
+  Bool_t  ReInit(MParList *pList);
+  
+public:
+  MExtractSlidingWindow(const char *name=NULL, const char *title=NULL);
+
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+  void SetWindowSize(Byte_t windowh=fgHiGainWindowSize,
+                     Byte_t windowl=fgLoGainWindowSize);
+
+  ClassDef(MExtractSlidingWindow, 1) // Signal Extractor for sliding extraction window
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractTime.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTime.cc	(revision 9772)
@@ -0,0 +1,198 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTime
+//
+//   Base class for the signal extractors, used the functions 
+//   FindTimeHiGain() and FindTimeLoGain() to extract the signal and 
+//   substract the pedestal value    
+//
+//   The following figure gives and example of possible inheritance trees. 
+//   An extractor class can inherit from each of the following base classes:
+//    - MExtractor
+//    - MExtractTime
+//    - MExtractTimeAndCharge
+//
+//Begin_Html
+/*
+<img src="images/ExtractorClasses.gif">
+*/
+//End_Html
+//
+//   The following variables have to be set by the derived class and 
+//   do not have defaults:
+//   - fNumHiGainSamples
+//   - fNumLoGainSamples
+//   - fSqrtHiGainSamples
+//   - fSqrtLoGainSamples
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//
+// Output Containers:
+//   MArrivalTimeCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTime.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+#include "MRawRunHeader.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+ClassImp(MExtractTime);
+
+using namespace std;
+
+const TString MExtractTime::fgNameTimeCam   = "MArrivalTimeCam";
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Set: 
+// - all pointers to NULL
+// - all variables to 0
+// - fSaturationLimit to fgSaturationLimit
+// - fNameTimeCam to fgNameTimeCam
+//
+// Call:
+// -  AddToBranchList("MRawEvtData.*")
+//
+MExtractTime::MExtractTime(const char *name, const char *title)
+  : fArrTime(NULL)
+{
+
+  fName  = name  ? name  : "MExtractTime";
+  fTitle = title ? title : "Base class for signal extractors";
+  
+  SetNameTimeCam();
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MArrivalTimeCam
+//
+Int_t MExtractTime::PreProcess(MParList *pList)
+{
+  fArrTime = (MArrivalTimeCam*)pList->FindCreateObj("MArrivalTimeCam",AddSerialNumber(fNameTimeCam));
+  if (!fArrTime)
+      return kFALSE;
+
+  return PreProcessStd(pList);
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+//
+// Call: 
+// - MArrivalTimeCam::SetUsedFADCSlices(fHiGainFirst, fHiGainLast, fNumHiGainSamples,
+//                                      fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+//
+Bool_t MExtractTime::ReInit(MParList *pList)
+{
+    if (!MExtractor::ReInit(pList))
+        return kFALSE;
+
+    if (fArrTime)
+      fArrTime->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fLoGainFirst, fLoGainLast);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MArrivalTimeCam container.
+//
+Int_t MExtractTime::Process()
+{
+
+
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  while (pixel.Next())
+    {
+      //
+      // Find signal in hi- and lo-gain
+      //
+      Float_t timehi=0., deltatimehi=0.;
+      Byte_t sathi=0;
+
+      const Int_t pixid = pixel.GetPixelId();
+      const MPedestalPix  &ped = (*fPedestals)[pixid];
+      MArrivalTimePix &pix = (*fArrTime)[pixid];
+
+      FindTimeHiGain(pixel.GetHiGainSamples()+fHiGainFirst, timehi, deltatimehi, sathi, ped);
+
+      Float_t timelo=0., deltatimelo=0.;
+      Byte_t satlo=0;
+
+      if ((sathi)&&pixel.HasLoGain())
+	  FindTimeLoGain(pixel.GetLoGainSamples()+fLoGainFirst, timelo, deltatimelo, satlo, ped);
+
+      pix.SetArrivalTime(timehi, deltatimehi, timelo-fOffsetLoGain, deltatimelo);
+      pix.SetGainSaturation(sathi, sathi, satlo);
+ 
+    } /* while (pixel.Next()) */
+
+    fArrTime->SetReadyToSave();
+
+    return kTRUE;
+}
+
+void MExtractTime::Print(Option_t *o) const
+{
+    if (IsA()==MExtractTime::Class())
+        *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " Offset Lo-Gain:     " << fOffsetLoGain << endl;
+    MExtractor::Print(o);
+}
Index: /tags/Mars-V0.9/msignal/MExtractTime.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTime.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTime.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifndef MARS_MExtractTime
+#define MARS_MExtractTime
+
+#ifndef MARS_MExtractor
+#include "MExtractor.h"
+#endif
+
+class MPedestalPix;
+class MArrivalTimeCam;
+
+class MExtractTime : public MExtractor
+{
+protected:
+  
+  static const TString fgNameTimeCam; //! "MArrivalTimeCam"
+  TString  fNameTimeCam;              // Name of the 'MArrivalTimeCam' container
+  
+  MArrivalTimeCam *fArrTime;          //! Container with the photons arrival times
+  
+  virtual void FindTimeHiGain(Byte_t *firstused, Float_t &time, Float_t &dtime,
+                              Byte_t &sat, const MPedestalPix &ped) const {}
+  virtual void FindTimeLoGain(Byte_t *firstused, Float_t &time, Float_t &dtime,
+                              Byte_t &sat, const MPedestalPix &ped) const {}
+
+  Int_t  PreProcess( MParList *pList );
+  Bool_t ReInit    ( MParList *pList );
+  Int_t  Process   ();
+
+public:
+
+  MExtractTime(const char *name=NULL, const char *title=NULL);
+
+  void Print(Option_t *o) const;
+
+  void SetNameTimeCam   ( const char *name=fgNameTimeCam.Data()) { fNameTimeCam = name; }
+  
+  ClassDef(MExtractTime, 3)   // Arrival Time Extractor Base Class
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndCharge.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndCharge.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndCharge.cc	(revision 9772)
@@ -0,0 +1,304 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 05/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndCharge
+//
+//   Base class for the signal extractors which extract the arrival time 
+//   and the signal at the same time. Uses the functions 
+//   FindTimeAndChargeHiGain() and FindTimeAndChargeLoGain() to extract the signal and 
+//   substract the pedestal value.
+//
+//   The following figure gives and example of possible inheritance trees. 
+//   An extractor class can inherit from each of the following base classes:
+//    - MExtractor
+//    - MExtractTime
+//    - MExtractTimeAndCharge
+//
+//Begin_Html
+/*
+<img src="images/ExtractorClasses.gif">
+*/
+//End_Html
+//
+//   The following variables have to be set by the derived class and 
+//   do not have defaults:
+//   - fNumHiGainSamples
+//   - fNumLoGainSamples
+//   - fSqrtHiGainSamples
+//   - fSqrtLoGainSamples
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//
+// Output Containers:
+//   MArrivalTimeCam
+//   MExtractedSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndCharge.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+#include "MRawRunHeader.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MExtractTimeAndCharge);
+
+using namespace std;
+
+const Float_t MExtractTimeAndCharge::fgLoGainStartShift = -3.5; 
+const Byte_t  MExtractTimeAndCharge::fgLoGainSwitch = 120; 
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets: 
+// - fLoGainFirstSave to 0
+// - fWindowSizeHiGain and fWindowSizeLoGain to 0
+// - fLoGainStartShift to fgLoGainStartShift+fgOffsetLoGain
+// - fLoGainSwitch     to fgLoGainSwitch
+//
+MExtractTimeAndCharge::MExtractTimeAndCharge(const char *name, const char *title)
+    : fLoGainFirstSave(0), fWindowSizeHiGain(0), fWindowSizeLoGain(0)
+{
+    fName  = name  ? name  : "MExtractTimeAndCharge";
+    fTitle = title ? title : "Base class for signal and time extractors";
+
+    SetLoGainStartShift();
+    SetLoGainSwitch();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//  - MArrivalTimeCam    
+//
+Int_t MExtractTimeAndCharge::PreProcess(MParList *pList)
+{
+
+  if (!MExtractTime::PreProcess(pList))
+    return kFALSE;
+  
+  fSignals = (MExtractedSignalCam*)pList->FindCreateObj("MExtractedSignalCam",AddSerialNumber(fNameSignalCam));
+  if (!fSignals)
+      return kFALSE;
+
+  *fLog << flush << inf;
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit calls:
+// -  MExtractor::ReInit()
+//
+// Call: 
+// - MArrivalTimeCam::SetUsedFADCSlices(fHiGainFirst, fHiGainLast, fNumHiGainSamples,
+//                                      fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+// - InitArrays();
+//
+Bool_t MExtractTimeAndCharge::ReInit(MParList *pList)
+{
+
+  if (!MExtractTime::ReInit(pList))
+    return kFALSE;
+
+  if (!InitArrays())
+    return kFALSE;
+  
+  if (fSignals)
+    fSignals->SetUsedFADCSlices(fHiGainFirst, fHiGainLast+fHiLoLast, fNumHiGainSamples,
+                                fLoGainFirst, fLoGainLast, fNumLoGainSamples);
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MArrivalTimeCam container.
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedSignalCam container. 
+// The functions FindTimeAndChargeHiGain() and FindTimeAndChargeLoGain() are 
+// supposed to extract the signal themselves.
+//
+Int_t MExtractTimeAndCharge::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  while (pixel.Next())
+    {
+      //
+      // Find signal in hi- and lo-gain
+      //
+      Float_t sumhi =0., deltasumhi =0; // Set hi-gain of MExtractedSignalPix valid
+      Float_t timehi=0., deltatimehi=0; // Set hi-gain of MArrivalTimePix valid
+      Byte_t sathi=0;
+
+      // Initialize fMaxBinContent for the case, it gets not set by the derived class
+      fMaxBinContent = fLoGainSwitch + 1; 
+
+      const Int_t pixidx = pixel.GetPixelId();
+      const MPedestalPix  &ped = (*fPedestals)[pixidx];
+      const Bool_t higainabflag = pixel.HasABFlag();
+
+      FindTimeAndChargeHiGain(pixel.GetHiGainSamples()+fHiGainFirst, pixel.GetLoGainSamples(), 
+                              sumhi, deltasumhi, 
+                              timehi, deltatimehi, 
+                              sathi, ped, higainabflag);
+
+      // Make sure that in cases the time couldn't be correctly determined
+      // more meaningfull default values are assigned
+      if (timehi<0)
+          timehi = -1;
+      if (timehi>pixel.GetNumHiGainSamples())
+          timehi = pixel.GetNumHiGainSamples();
+      
+      Float_t sumlo =0., deltasumlo =-1.; // invalidate logain of MExtractedSignalPix
+      Float_t timelo=0., deltatimelo=-1;  // invalidate logain of MArrivalTimePix
+      Byte_t satlo=0;
+      
+      //
+      // Adapt the low-gain extraction range from the obtained high-gain time
+      //
+      if (pixel.HasLoGain() && (fMaxBinContent > fLoGainSwitch) )
+      {
+          deltasumlo  = 0; // make logain of MExtractedSignalPix valid
+          deltatimelo = 0; // make logain of MArrivalTimePix valid
+
+          fLoGainFirstSave = fLoGainFirst;
+          const Byte_t logainstart = sathi 
+            ? (sathi > (Int_t)(-1*fLoGainStartShift) ? sathi + (Int_t)fLoGainStartShift : fLoGainFirst)
+            : (timehi+fLoGainStartShift > 0. ? (Byte_t)(timehi + fLoGainStartShift) : fLoGainFirst);
+          fLoGainFirst = logainstart > fLoGainFirstSave ? logainstart : fLoGainFirstSave;
+
+          // *fLog << err << (Int_t)fLoGainFirst << endl;
+
+          if ( fLoGainFirst <= fLoGainLast-fWindowSizeLoGain)
+            {
+              const Bool_t logainabflag = (higainabflag + pixel.GetNumHiGainSamples()) & 0x1;
+              FindTimeAndChargeLoGain(pixel.GetLoGainSamples()+fLoGainFirst,
+                                      sumlo, deltasumlo,
+                                      timelo, deltatimelo,
+                                      satlo, ped, logainabflag);
+          }
+          fLoGainFirst = fLoGainFirstSave;
+
+          // Make sure that in cases the time couldn't be correctly determined
+          // more meaningfull default values are assigned
+          if (timelo<0)
+              timelo = -1;
+          if (timelo>pixel.GetNumLoGainSamples())
+              timelo = pixel.GetNumLoGainSamples();
+      }
+
+      MExtractedSignalPix &pix = (*fSignals)[pixidx];
+      MArrivalTimePix     &tix = (*fArrTime)[pixidx];
+      pix.SetExtractedSignal(sumhi, deltasumhi,sumlo, deltasumlo);
+      pix.SetGainSaturation(sathi, sathi, satlo);
+
+      tix.SetArrivalTime(timehi, deltatimehi, timelo-fOffsetLoGain, deltatimelo);
+      tix.SetGainSaturation(sathi, sathi, satlo);
+ 
+    } /* while (pixel.Next()) */
+
+  fArrTime->SetReadyToSave();
+  fSignals->SetReadyToSave();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.LoGainStartShift: -2.8
+//
+Int_t MExtractTimeAndCharge::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+    Bool_t rc = MExtractTime::ReadEnv(env, prefix, print);
+
+    if (rc)
+      SetLoGainStartShift();
+
+    if (IsEnvDefined(env, prefix, "LoGainStartShift", print))
+    {
+        fLoGainStartShift = GetEnvValue(env, prefix, "LoGainStartShift", fgLoGainStartShift);
+	SetLoGainStartShift(fLoGainStartShift);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "LoGainSwitch", print))
+    {
+        fLoGainSwitch = GetEnvValue(env, prefix, "LoGainSwitch", fLoGainSwitch);
+        rc = kTRUE;
+    }
+
+    return rc;
+}
+
+void MExtractTimeAndCharge::Print(Option_t *o) const
+{
+  if (IsA()==Class())
+    *fLog << GetDescriptor() << ":" << endl;
+
+  *fLog << dec;
+  *fLog << " Taking " << fWindowSizeHiGain
+        << " HiGain samples from slice " << (Int_t)fHiGainFirst
+        << " to " << (Int_t)(fHiGainLast+fHiLoLast) << " incl" << endl;
+  *fLog << " Taking " << fWindowSizeLoGain
+        << " LoGain samples from slice " << (Int_t)fLoGainFirst
+        << " to " << (Int_t)fLoGainLast << " incl" << endl;
+  
+  *fLog << " LoGainStartShift:   " << fLoGainStartShift << endl;
+  *fLog << " LoGainSwitch:       " << (Int_t)fLoGainSwitch << endl;
+  MExtractTime::Print(o);
+}
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndCharge.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndCharge.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndCharge.h	(revision 9772)
@@ -0,0 +1,66 @@
+#ifndef MARS_MExtractTimeAndCharge
+#define MARS_MExtractTimeAndCharge
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MPedestalPix;
+class MExtractTimeAndCharge : public MExtractTime
+{
+private:
+
+  static const Float_t fgLoGainStartShift; //! Default for fLoGainStartShift (now set to: -2.8)
+  static const Byte_t  fgLoGainSwitch;     //! Default for fLoGainSwitch     (now set to: 100)
+  
+protected:
+
+  Byte_t  fLoGainFirstSave;       //! Temporary variable to store the original position of low-gain start slice
+  Float_t fLoGainStartShift;      // Shift to start searching the low-gain signal obtained from the high-gain times.
+
+  Byte_t  fLoGainSwitch;          // Limit for max. bin content before the low-gain gets extracted
+
+  Int_t  fWindowSizeHiGain;       //  Window Size High-Gain
+  Int_t  fWindowSizeLoGain;       //  Window Size Low-Gain
+
+  Byte_t fMaxBinContent;          //  Maximum bin content
+
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Bool_t ReInit(MParList *pList);
+
+  Int_t  ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+
+  MExtractTimeAndCharge(const char *name=NULL, const char *title=NULL);
+  
+  Int_t  GetWindowSizeHiGain  () const { return fWindowSizeHiGain; }
+  Int_t  GetWindowSizeLoGain  () const { return fWindowSizeLoGain; }
+  Byte_t GetLoGainSwitch      () const { return fLoGainSwitch;     }
+
+  void Print(Option_t *o="") const;
+  
+  void SetLoGainStartShift( const Float_t f=fgLoGainStartShift ) { fLoGainStartShift = f + fOffsetLoGain;  }
+  void SetLoGainSwitch    ( const Byte_t  i=fgLoGainSwitch     ) { fLoGainSwitch     = i; }
+
+  virtual void SetWindowSize(Int_t windowh, Int_t windowl) { fWindowSizeHiGain = windowh;
+                                                           fWindowSizeLoGain = windowl;  }
+  
+  virtual Bool_t InitArrays() { return kTRUE; }
+
+  virtual void FindTimeAndChargeHiGain(Byte_t *firstused, Byte_t *logain, Float_t &sum, Float_t &dsum,
+                                       Float_t &time, Float_t &dtime,
+                                       Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag) { }
+  
+  virtual void FindTimeAndChargeLoGain(Byte_t *firstused, Float_t &sum,  Float_t &dsum,
+                                       Float_t &time, Float_t &dtime,
+                                       Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag) { } 
+
+  ClassDef(MExtractTimeAndCharge, 2)   // Time And Charge Extractor Base Class
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilter.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilter.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilter.cc	(revision 9772)
@@ -0,0 +1,1055 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko, 09/2004 <mailto:hbartko@mppmu.mpg.de> 
+!   Author(s): Markus Gaug, 05/2004 <mailto:markus@ifae.es>
+!   Author(s): Diego Tescaro, 05/2004 <mailto:tescaro@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeDigitalFilter
+//
+//   Hendrik has promised to write more documentation
+//
+//
+//   The following variables have to be set by the derived class and 
+//   do not have defaults:
+//   - fNumHiGainSamples
+//   - fNumLoGainSamples
+//   - fSqrtHiGainSamples
+//   - fSqrtLoGainSamples
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//
+// Output Containers:
+//   MArrivalTimeCam
+//   MExtractedSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndChargeDigitalFilter.h"
+
+#include <errno.h>
+#include <fstream>
+
+#include <TFile.h>
+#include <TH1F.h>
+#include <TH2F.h>
+#include <TString.h>
+#include <TMatrix.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MPedestalPix.h"
+
+ClassImp(MExtractTimeAndChargeDigitalFilter);
+
+using namespace std;
+
+const Byte_t MExtractTimeAndChargeDigitalFilter::fgHiGainFirst             =  0;
+const Byte_t MExtractTimeAndChargeDigitalFilter::fgHiGainLast              = 15;
+const Byte_t MExtractTimeAndChargeDigitalFilter::fgLoGainFirst             =  1;
+const Byte_t MExtractTimeAndChargeDigitalFilter::fgLoGainLast              = 14;
+const Int_t  MExtractTimeAndChargeDigitalFilter::fgWindowSizeHiGain        =  6;
+const Int_t  MExtractTimeAndChargeDigitalFilter::fgWindowSizeLoGain        =  6;
+const Int_t  MExtractTimeAndChargeDigitalFilter::fgBinningResolutionHiGain = 10;
+const Int_t  MExtractTimeAndChargeDigitalFilter::fgBinningResolutionLoGain = 10;
+const Int_t  MExtractTimeAndChargeDigitalFilter::fgSignalStartBinHiGain    =  4;
+const Int_t  MExtractTimeAndChargeDigitalFilter::fgSignalStartBinLoGain    =  4;
+const TString MExtractTimeAndChargeDigitalFilter::fgNameWeightsFile        = "msignal/cosmics_weights.dat";
+const Float_t MExtractTimeAndChargeDigitalFilter::fgOffsetLoGain           =  1.7; // 5 ns
+const Float_t MExtractTimeAndChargeDigitalFilter::fgLoGainStartShift       = -1.8;  
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls: 
+// - SetWindowSize();
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// - SetBinningResolution();
+//
+// Sets all weights to 1.
+//
+MExtractTimeAndChargeDigitalFilter::MExtractTimeAndChargeDigitalFilter(const char *name, const char *title) 
+    : fTimeShiftHiGain(0.), fTimeShiftLoGain(0.), fWeightsSet(kFALSE), fRandomIter(0)
+{
+    fName  = name  ? name  : "MExtractTimeAndChargeDigitalFilter";
+    fTitle = title ? title : "Digital Filter";
+
+    SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+    SetWindowSize();
+    SetBinningResolution();
+    SetSignalStartBin();
+
+    SetNameWeightsFile();
+    SetOffsetLoGain(fgOffsetLoGain);
+    SetLoGainStartShift(fgLoGainStartShift);
+}
+
+// ---------------------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)fWindowSizeHiGain
+// - fNumLoGainSamples to: (Float_t)fWindowSizeLoGain
+//  
+void MExtractTimeAndChargeDigitalFilter::SetWindowSize(Int_t windowh, Int_t windowl)
+{
+
+  if (windowh != fgWindowSizeHiGain)
+    *fLog << warn << GetDescriptor() 
+          << ": ATTENTION!!! If you are not Hendrik Bartko, do NOT use a different window size than the default." << endl;
+  if (windowl != fgWindowSizeLoGain)
+    *fLog << warn << GetDescriptor() 
+          << ": ATTENTION!!! If you are not Hendrik Bartko, do NOT use a different window size than the default" << endl;
+
+  fWindowSizeHiGain = windowh;
+  fWindowSizeLoGain = windowl;
+  
+  const Int_t availhirange = (Int_t)(fHiGainLast-fHiGainFirst+1);
+
+  if (fWindowSizeHiGain > availhirange)
+  {
+      // Please simplify this!
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",fWindowSizeHiGain,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      fHiGainLast = fHiGainFirst + fWindowSizeHiGain;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set the upper range to: " << (int)fHiGainLast << endl;
+    }
+  
+  if (fWindowSizeHiGain < 2) 
+    {
+      fWindowSizeHiGain = 2;
+      *fLog << warn << GetDescriptor() << ": High Gain window size set to two samples" << endl;
+    }
+  
+  if (fLoGainLast != 0 && fWindowSizeLoGain != 0)
+    {
+      const Int_t availlorange = (Int_t)(fLoGainLast-fLoGainFirst+1);
+      
+      if (fWindowSizeLoGain > availlorange)
+        {
+      // Please simplify this!
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",fWindowSizeLoGain,
+                        " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+          fLoGainLast = fLoGainFirst + fWindowSizeLoGain;
+          *fLog << warn << GetDescriptor() 
+            << ": Will set the upper range to: " << (int)fLoGainLast << endl;
+        }
+      
+      if (fWindowSizeLoGain<2) 
+        {
+          fWindowSizeLoGain = 2;
+          *fLog << warn << GetDescriptor() << ": Low Gain window size set to two samples" << endl;
+        }
+    }
+  // 
+  // We need here the effective number of samples which is about 2.5 in the case of a window
+  // size of 6. The exact numbers have to be found still.
+  //
+  fNumHiGainSamples = (Float_t)fWindowSizeHiGain/2.4;
+  fNumLoGainSamples = (Float_t)fWindowSizeLoGain/2.4;
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// InitArrays
+//
+// Gets called in the ReInit() and initialized the arrays
+//
+Bool_t MExtractTimeAndChargeDigitalFilter::InitArrays()
+{
+
+  Int_t range = (Int_t)(fHiGainLast - fHiGainFirst + 1 + fHiLoLast);
+
+  fHiGainSignal.Set(range);
+
+  range = (Int_t)(fLoGainLast - fLoGainFirst + 1);
+
+  fLoGainSignal.Set(range);
+
+  if (!fWeightsSet)
+    if (!ReadWeightsFile(fNameWeightsFile))
+      return kFALSE;
+
+  fTimeShiftHiGain = (Float_t)fHiGainFirst + 0.5 + 1./fBinningResolutionHiGain;
+  fTimeShiftLoGain = 0.5 + 1./fBinningResolutionLoGain;
+  // 
+  // We need here the effective number of samples which is about 2.5 in the case of a window
+  // size of 6. The exact numbers have to be found still.
+  //
+  fNumHiGainSamples = (Float_t)fWindowSizeHiGain/2.4;
+  fNumLoGainSamples = (Float_t)fWindowSizeLoGain/2.4;
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+  
+  return kTRUE;
+}
+
+void MExtractTimeAndChargeDigitalFilter::CalcBinningResArrays()
+{
+
+  fArrBinningResHiGain.Set(fWindowSizeHiGain);
+  fArrBinningResHalfHiGain.Set(fWindowSizeHiGain);
+
+  for (int i=0; i<fWindowSizeHiGain; i++)
+    {
+      fArrBinningResHiGain[i] = fBinningResolutionHiGain*i;
+      fArrBinningResHalfHiGain[i] = fArrBinningResHiGain[i] + fBinningResolutionHalfHiGain;
+    }
+
+  fArrBinningResLoGain.Set(fWindowSizeLoGain);
+  fArrBinningResHalfLoGain.Set(fWindowSizeLoGain);
+  
+  for (int i=0; i<fWindowSizeLoGain; i++)
+    {
+      fArrBinningResLoGain[i] = fBinningResolutionLoGain*i;
+      fArrBinningResHalfLoGain[i] = fArrBinningResLoGain[i] + fBinningResolutionHalfLoGain;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the digital filter algorithm to the high-gain slices.
+//
+void MExtractTimeAndChargeDigitalFilter::FindTimeAndChargeHiGain(Byte_t *ptr, Byte_t *logain, Float_t &sum, Float_t &dsum, 
+                                                                 Float_t &time, Float_t &dtime,
+                                                                 Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag)
+{
+
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+  
+  const Byte_t *end = ptr + range;
+  Byte_t *p     = ptr;
+  Byte_t maxpos = 0;
+
+  //
+  // Preparations for the pedestal subtraction (with AB-noise correction)
+  //
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t ABoffs = ped.GetPedestalABoffset();
+
+  const Float_t pedmean[2] = { pedes + ABoffs, pedes - ABoffs };
+
+  range += fHiLoLast;
+  fMaxBinContent = 0;
+  //
+  // Check for saturation in all other slices
+  //
+  Int_t ids = fHiGainFirst;
+  Float_t *sample = fHiGainSignal.GetArray();
+  while (p<end)
+    {
+      *sample++ = (Float_t)*p - pedmean[(ids++ + abflag) & 0x1];
+
+      if (*p > fMaxBinContent)
+	{
+	  maxpos = p-ptr;
+	  if (maxpos > 1 && maxpos < (range - fWindowSizeHiGain + 1))
+	    fMaxBinContent = *p;
+	}
+
+      if (*p++ >= fSaturationLimit)
+        if (!sat)
+          sat = ids-3;
+    }
+
+  //
+  // Slide with a window of size fWindowSizeHiGain over the sample 
+  // and multiply the entries with the corresponding weights
+  //
+  if (IsNoiseCalculation())
+    {
+      if (fRandomIter == fBinningResolutionHiGain)
+        fRandomIter = 0;
+      for (Int_t ids=0; ids < fWindowSizeHiGain; ids++)
+        {
+          const Int_t   idx = fArrBinningResHiGain[ids] + fRandomIter;
+          sum              += fAmpWeightsHiGain [idx]*fHiGainSignal[ids]; 
+        }
+      fRandomIter++;
+      return;
+    }
+  
+  if (fHiLoLast != 0)
+    {
+
+      end = logain + fHiLoLast;
+
+      while (logain<end)
+        {
+
+          *sample++ = (Float_t)*logain - pedmean[(ids++ + abflag) & 0x1];
+
+          if (*logain++ >= fSaturationLimit)
+            if (!sat)
+              sat = ids-3;
+        }
+    }
+
+  //
+  // allow no saturated slice 
+  //
+  //  if (sat > 0)
+  //    return;
+  
+  Float_t time_sum  = 0.;
+  Float_t fmax      = -9999.;
+  Float_t ftime_max = 0.;
+  Int_t   max_p     = 0;
+  
+  //
+  // Calculate the sum of the first fWindowSize slices
+  //
+  for (Int_t i=0;i<range-fWindowSizeHiGain+1;i++)
+    {
+      sum      = 0.;
+      time_sum = 0.;
+
+      //
+      // Slide with a window of size fWindowSizeHiGain over the sample
+      // and multiply the entries with the corresponding weights
+      //
+      for (Int_t sample=0; sample < fWindowSizeHiGain; sample++)
+      {
+        const Int_t   idx = fBinningResolutionHiGain*sample+fBinningResolutionHalfHiGain;
+        const Float_t pex = fHiGainSignal[sample+i];
+        sum              += fAmpWeightsHiGain [idx]*pex;
+        time_sum         += fTimeWeightsHiGain[idx]*pex;
+      }
+
+      if (sum>fmax)
+      {
+        fmax      = sum;
+        ftime_max = time_sum;
+        max_p     = i;
+      }
+    } /*   for (Int_t i=0;i<range-fWindowSizeHiGain+1;i++) */
+
+  if (fmax==0)
+      return;
+
+  ftime_max        /= fmax;
+  Int_t t_iter      = Int_t(ftime_max*fBinningResolutionHiGain);
+  Int_t sample_iter = 0;
+
+  while ( t_iter > fBinningResolutionHalfHiGain-1 || t_iter < -fBinningResolutionHalfHiGain )
+    {
+      if (t_iter > fBinningResolutionHalfHiGain-1)
+        {
+          t_iter -= fBinningResolutionHiGain;
+          max_p--; 
+          sample_iter--;
+        }
+      if (t_iter < -fBinningResolutionHalfHiGain)
+        {
+          t_iter += fBinningResolutionHiGain;
+          max_p++; 
+          sample_iter++;
+        }
+    }
+
+  sum = 0.;
+  time_sum = 0.;
+  if (max_p < 0)
+    max_p = 0;
+  if (max_p+fWindowSizeHiGain > range)
+    max_p = range-fWindowSizeHiGain;
+  //
+  // Slide with a window of size fWindowSizeHiGain over the sample 
+  // and multiply the entries with the corresponding weights
+  //
+  for (Int_t sample=0; sample < fWindowSizeHiGain; sample++)
+  {
+    const Int_t   idx = fArrBinningResHalfHiGain[sample] + t_iter;
+    const Int_t   ids = max_p + sample;
+    const Float_t pex = fHiGainSignal[ids];
+    sum              += fAmpWeightsHiGain [idx]*pex; 
+    time_sum         += fTimeWeightsHiGain[idx]*pex;
+  }
+
+  if (sum == 0)
+      return;
+
+  time = max_p + fTimeShiftHiGain + (Float_t)fHiGainFirst /* this shifts the time to the start of the rising edge */
+      - ((Float_t)t_iter)/fBinningResolutionHiGain;
+
+  const Float_t timefineadjust = time_sum/sum;
+  
+  if (timefineadjust < 2./fBinningResolutionHiGain)
+    time -= timefineadjust;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply the digital filter algorithm to the low-gain slices.
+//
+void MExtractTimeAndChargeDigitalFilter::FindTimeAndChargeLoGain(Byte_t *ptr, Float_t &sum, Float_t &dsum, 
+                                                                 Float_t &time, Float_t &dtime,
+                                                                 Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag)
+{
+
+  const Int_t range = fLoGainLast - fLoGainFirst + 1;
+
+  const Byte_t *end = ptr + range;
+  Byte_t *p     = ptr;
+  //
+  // Prepare the low-gain pedestal
+  //
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t ABoffs = ped.GetPedestalABoffset();
+	
+  const Float_t pedmean[2] = { pedes + ABoffs, pedes - ABoffs };
+
+  //
+  // Check for saturation in all other slices
+  //
+  Float_t *sample = fLoGainSignal.GetArray();
+  Int_t    ids    = fLoGainFirst;
+  while (p<end)
+    {
+      *sample++ = (Float_t)*p - pedmean[(ids++ + abflag) & 0x1];
+
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+
+  //
+  // Slide with a window of size fWindowSizeLoGain over the sample 
+  // and multiply the entries with the corresponding weights
+  //
+  if (IsNoiseCalculation())
+    {
+      if (fRandomIter == fBinningResolutionLoGain)
+        fRandomIter = 0;
+      for (Int_t ids=0; ids < fWindowSizeLoGain; ids++)
+        {
+          const Int_t   idx = fArrBinningResLoGain[ids] + fRandomIter;
+          sum              += fAmpWeightsLoGain [idx]*fLoGainSignal[ids]; 
+        }
+      return;
+    }
+
+  Float_t time_sum  = 0.;
+  Float_t fmax      = 0.;
+  Float_t ftime_max = 0.;
+  Int_t   max_p     = 0;
+  
+  //
+  // Calculate the sum of the first fWindowSize slices
+  //
+  for (Int_t i=0;i<range-fWindowSizeLoGain+1;i++)
+    {
+      sum      = 0.;
+      time_sum = 0.;
+      
+      //
+      // Slide with a window of size fWindowSizeLoGain over the sample 
+      // and multiply the entries with the corresponding weights
+      //
+      for (Int_t sample=0; sample < fWindowSizeLoGain; sample++)
+      {
+        const Int_t   idx = fArrBinningResHalfLoGain[sample];
+        const Float_t pex = fLoGainSignal[sample+i];
+	sum              += fAmpWeightsLoGain [idx]*pex; 
+	time_sum         += fTimeWeightsLoGain[idx]*pex;
+      }
+
+      if (sum>fmax)
+      {
+	fmax      = sum;
+	ftime_max = time_sum;
+	max_p     = i;
+      }
+    } /*   for (Int_t i=0;i<range-fWindowSizeLoGain+1;i++) */
+
+  time = 0;
+  if (fmax==0)
+      return;
+
+  ftime_max        /= fmax;
+  Int_t t_iter      = Int_t(ftime_max*fBinningResolutionLoGain);
+  Int_t sample_iter = 0;
+
+  while ( t_iter > fBinningResolutionHalfLoGain-1 || t_iter < -fBinningResolutionHalfLoGain )
+    {
+      if (t_iter > fBinningResolutionHalfLoGain-1)
+        {
+          t_iter -= fBinningResolutionLoGain;
+          max_p--; 
+          sample_iter--;
+        }
+      if (t_iter < -fBinningResolutionHalfLoGain)
+        {
+          t_iter += fBinningResolutionLoGain;
+          max_p++; 
+          sample_iter++;
+        }
+    }
+  
+  sum = 0.;
+  time_sum = 0.;
+
+  //
+  // Slide with a window of size fWindowSizeLoGain over the sample 
+  // and multiply the entries with the corresponding weights
+  //
+  for (Int_t sample=0; sample < fWindowSizeLoGain; sample++)
+  {
+    const Int_t   idx = fArrBinningResHalfLoGain[sample] + t_iter;
+    const Int_t   ids = max_p + sample;
+    const Float_t pex = ids < 0 ? 0. : ( ids >= range ? 0. : fLoGainSignal[ids]);
+    sum              += fAmpWeightsLoGain [idx]*pex; 
+    time_sum         += fTimeWeightsLoGain[idx]*pex;
+  }
+
+  if (sum == 0)
+      return;
+
+  time = max_p + fTimeShiftLoGain + (Float_t)fLoGainFirst /* this shifts the time to the start of the rising edge */
+      - ((Float_t)t_iter)/fBinningResolutionLoGain;
+
+  const Float_t timefineadjust = time_sum/sum;
+  
+  if (timefineadjust < 2./fBinningResolutionLoGain)
+    time -= timefineadjust;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//   MJPedestal.MExtractor.BinningResolutionHiGain: 10
+//   MJPedestal.MExtractor.BinningResolutionLoGain: 10
+//   MJPedestal.MExtractor.WeightsFile: filename
+//
+Int_t MExtractTimeAndChargeDigitalFilter::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Byte_t hw = fWindowSizeHiGain;
+  Byte_t lw = fWindowSizeLoGain;
+  Bool_t rc = kFALSE;
+  
+  if (IsEnvDefined(env, prefix, "WindowSizeHiGain", print))
+    {
+      hw = GetEnvValue(env, prefix, "WindowSizeHiGain", hw);
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "WindowSizeLoGain", print))
+    {
+      lw = GetEnvValue(env, prefix, "WindowSizeLoGain", lw);
+      rc = kTRUE;
+    }
+  
+  if (rc)
+    SetWindowSize(hw, lw);
+  
+  Bool_t rc2 = kFALSE;
+  Int_t brh = fBinningResolutionHiGain;
+  Int_t brl = fBinningResolutionLoGain;
+  
+  if (IsEnvDefined(env, prefix, "BinningResolutionHiGain", print))
+    {
+      brh = GetEnvValue(env, prefix, brh);
+      rc2 = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "BinningResolutionLoGain", print))
+    {
+      brl = GetEnvValue(env, prefix, brl);
+      rc2 = kTRUE;
+    }
+  
+  if (rc2)
+    {
+      SetBinningResolution(brh, brl);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "WeightsFile", print))
+    {
+      if (!ReadWeightsFile(GetEnvValue(env, prefix, "WeightsFile", "")))
+        return kERROR;
+      rc = kTRUE;
+    }
+  
+  return MExtractTimeAndCharge::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
+
+//----------------------------------------------------------------------------
+//
+// Read a pre-defined weights file into the class. 
+// This is mandatory for the extraction
+//
+// If filenname is empty, then all weights will be set to 1.
+//
+Bool_t MExtractTimeAndChargeDigitalFilter::ReadWeightsFile(TString filename)
+{
+  
+    // This is a fix for TEnv files edited with windows editors
+    filename.ReplaceAll("\015", "");
+
+    SetNameWeightsFile(filename);
+
+    fAmpWeightsHiGain .Set(fBinningResolutionHiGain*fWindowSizeHiGain);
+    fAmpWeightsLoGain .Set(fBinningResolutionLoGain*fWindowSizeLoGain);
+    fTimeWeightsHiGain.Set(fBinningResolutionHiGain*fWindowSizeHiGain);
+    fTimeWeightsLoGain.Set(fBinningResolutionLoGain*fWindowSizeLoGain);
+
+    if (fNameWeightsFile.IsNull())
+    {
+        fAmpWeightsHiGain.Reset(1);
+        fTimeWeightsHiGain.Reset(1);
+        fAmpWeightsLoGain.Reset(1);
+        fTimeWeightsLoGain.Reset(1);
+        return kTRUE;
+    }
+
+    ifstream fin(filename.Data());
+    if (!fin)
+    {
+        *fLog << err << GetDescriptor() << ": ERROR - Cannot open file " << filename << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << "Reading weights file " << filename << "..." << flush;
+
+    Int_t len = 0;
+    Int_t cnt = 0;
+    Int_t line = 0;
+    Bool_t hi = kFALSE;
+    Bool_t lo = kFALSE;
+
+    TString str;
+
+    while (1)
+    {
+        str.ReadLine(fin);
+        if (!fin)
+            break;
+
+        line++;
+
+        if (str.Contains("# High Gain Weights:"))
+        {
+            if (hi)
+            {
+                *fLog << err << "ERROR - 'High Gain Weights' found twice in line #" << line << "." << endl;
+                return kFALSE;
+            }
+
+            if (2!=sscanf(str.Data(), "# High Gain Weights:%2i %2i", &fWindowSizeHiGain, &fBinningResolutionHiGain))
+            {
+                *fLog << err << "ERROR - Wrong number of arguments in line #" << line << ":" << endl;
+                *fLog << str << endl;
+                return kFALSE;
+            }
+
+            len = fBinningResolutionHiGain*fWindowSizeHiGain;
+            fAmpWeightsHiGain .Set(len);
+            fTimeWeightsHiGain.Set(len);
+            hi = kTRUE;
+            continue;
+        }
+
+        if (str.Contains("# Low Gain Weights:"))
+        {
+            if (lo)
+            {
+                *fLog << err << "ERROR - 'Lo Gain Weights' found twice in line #" << line << "." << endl;
+                return kFALSE;
+            }
+
+            if (2!=sscanf(str.Data(),"# Low Gain Weights:%2i %2i", &fWindowSizeLoGain, &fBinningResolutionLoGain))
+            {
+                *fLog << err << "ERROR - Wrong number of arguments in line #" << line << ":" << endl;
+                *fLog << str << endl;
+                return kFALSE;
+            }
+
+            len = fBinningResolutionLoGain*fWindowSizeLoGain;
+            fAmpWeightsLoGain .Set(len);
+            fTimeWeightsLoGain.Set(len);
+            lo = kTRUE;
+            continue;
+        }
+
+        // Handle lines with comments
+        if (str.Contains("#"))
+            continue;
+
+        // Nothing found so far
+        if (len == 0)
+            continue;
+
+        if (2!=sscanf(str.Data(), "%f %f",
+                      lo ? &fAmpWeightsLoGain [cnt] : &fAmpWeightsHiGain [cnt],
+                      lo ? &fTimeWeightsLoGain[cnt] : &fTimeWeightsHiGain[cnt]))
+        {
+            *fLog << err << "ERROR - Wrong number of arguments in line #" << line << ":" << endl;
+            *fLog << str << endl;
+            return kFALSE;
+        }
+
+        if (++cnt == len)
+        {
+            len = 0;
+            cnt = 0;
+        }
+    }
+
+    if (cnt != len)
+    {
+        *fLog << err << "Size mismatch in weights file " << filename << endl;
+        return kFALSE;
+    }
+
+    if (!hi)
+    {
+        *fLog << err << "No correct header found in weights file " << filename << endl;
+        return kFALSE;
+    }
+
+    *fLog << "done." << endl;
+
+    *fLog << inf << " File contains " << fWindowSizeHiGain << " hi-gain slices ";
+    *fLog << "with a resolution of " << fBinningResolutionHiGain << endl;
+
+    *fLog << inf << " File contains " << fWindowSizeLoGain << " lo-gain slices ";
+    *fLog << "with a resolution of " << fBinningResolutionLoGain << endl;
+
+    CalcBinningResArrays();
+
+    fWeightsSet = kTRUE;
+
+    return kTRUE;
+}
+
+//----------------------------------------------------------------------------
+//
+// Create the weights file
+// Beware that the shape-histogram has to contain the pulse starting at bin 1
+//
+Bool_t MExtractTimeAndChargeDigitalFilter::WriteWeightsFile(TString filename, TH1F *shapehi, TH2F *autocorrhi,
+                                                            TH1F *shapelo, TH2F *autocorrlo )
+{
+
+  const Int_t nbinshi = shapehi->GetNbinsX();
+  Float_t binwidth    = shapehi->GetBinWidth(1);
+
+  TH1F *derivativehi = new TH1F(Form("%s%s",shapehi->GetName(),"_der"),
+                                Form("%s%s",shapehi->GetTitle()," derivative"),
+                                nbinshi,
+                                shapehi->GetBinLowEdge(1),
+                                shapehi->GetBinLowEdge(nbinshi)+binwidth);
+
+  //
+  // Calculate the derivative of shapehi
+  // 
+  for (Int_t i = 1; i<nbinshi+1;i++)
+    {
+      derivativehi->SetBinContent(i,
+                                ((shapehi->GetBinContent(i+1)-shapehi->GetBinContent(i-1))/2./binwidth));
+      derivativehi->SetBinError(i,
+                              (sqrt(shapehi->GetBinError(i+1)*shapehi->GetBinError(i+1)
+                                    +shapehi->GetBinError(i-1)*shapehi->GetBinError(i-1))/2./binwidth));
+    }
+  
+  //
+  // normalize the shapehi, such that the integral for fWindowSize slices is one!
+  //
+  Float_t sum    = 0;
+  Int_t lasttemp = fBinningResolutionHiGain * (fSignalStartBinHiGain + fWindowSizeHiGain);
+  lasttemp       = lasttemp > nbinshi ? nbinshi : lasttemp;
+  
+  for (Int_t i=fBinningResolutionHiGain*fSignalStartBinHiGain; i<lasttemp; i++) {
+    sum += shapehi->GetBinContent(i);
+  }
+  sum /= fBinningResolutionHiGain;
+
+  shapehi->Scale(1./sum);
+  derivativehi->Scale(1./sum);
+
+  //
+  // read in the noise auto-correlation function:
+  //
+  TMatrix Bhi(fWindowSizeHiGain,fWindowSizeHiGain);
+
+  for (Int_t i=0; i<fWindowSizeHiGain; i++){
+    for (Int_t j=0; j<fWindowSizeHiGain; j++){
+      Bhi[i][j]=autocorrhi->GetBinContent(i+1,j+1); //+fSignalStartBinHiGain +fSignalStartBinHiGain
+    }
+  }  
+  Bhi.Invert();
+
+  const Int_t nsizehi = fWindowSizeHiGain*fBinningResolutionHiGain;
+  fAmpWeightsHiGain.Set(nsizehi);
+  fTimeWeightsHiGain.Set(nsizehi);  
+  
+  //
+  // Loop over relative time in one BinningResolution interval
+  //
+  Int_t start = fBinningResolutionHiGain*(fSignalStartBinHiGain + 1);
+
+  for (Int_t i = -fBinningResolutionHalfHiGain+1; i<=fBinningResolutionHalfHiGain; i++)
+    {
+  
+      TMatrix g(fWindowSizeHiGain,1);
+      TMatrix gT(1,fWindowSizeHiGain);
+      TMatrix d(fWindowSizeHiGain,1);
+      TMatrix dT(1,fWindowSizeHiGain);
+    
+      for (Int_t count=0; count < fWindowSizeHiGain; count++){
+      
+        g[count][0]=shapehi->GetBinContent(start
+                                         +fBinningResolutionHiGain*count+i); 
+        gT[0][count]=shapehi->GetBinContent(start
+                                          +fBinningResolutionHiGain*count+i);
+        d[count][0]=derivativehi->GetBinContent(start
+                                              +fBinningResolutionHiGain*count+i);
+        dT[0][count]=derivativehi->GetBinContent(start
+                                               +fBinningResolutionHiGain*count+i);
+      }
+    
+      TMatrix m_denom = (gT*(Bhi*g))*(dT*(Bhi*d)) - (dT*(Bhi*g))*(dT*(Bhi*g));
+      Float_t   denom = m_denom[0][0];  // ROOT thinks, m_denom is still a matrix
+      
+      TMatrix m_first = dT*(Bhi*d);       // ROOT thinks, m_first is still a matrix
+      Float_t   first = m_first[0][0]/denom;
+      
+      TMatrix m_last  = gT*(Bhi*d);       // ROOT thinks, m_last  is still a matrix
+      Float_t   last  = m_last[0][0]/denom;
+      
+      TMatrix m1 = gT*Bhi;
+      m1 *= first;
+      
+      TMatrix m2 = dT*Bhi; 
+      m2 *=last;
+      
+      TMatrix w_amp = m1 - m2;
+      
+      TMatrix m_first1 = gT*(Bhi*g);
+      Float_t   first1 = m_first1[0][0]/denom;
+      
+      TMatrix m_last1  = gT*(Bhi*d);
+      Float_t   last1  = m_last1 [0][0]/denom;
+      
+      TMatrix m11 = dT*Bhi; 
+      m11 *=first1;
+      
+      TMatrix m21 = gT*Bhi;
+      m21 *=last1;
+      
+      TMatrix w_time= m11 - m21; 
+      
+      for (Int_t count=0; count < fWindowSizeHiGain; count++)
+        {
+          const Int_t idx = i+fBinningResolutionHalfHiGain+fBinningResolutionHiGain*count-1;
+          fAmpWeightsHiGain [idx] = w_amp [0][count];
+          fTimeWeightsHiGain[idx] = w_time[0][count];
+        }
+      
+    } // end loop over i
+
+  //
+  // Low Gain histograms
+  //
+  TH1F *derivativelo = NULL;
+  if (shapelo)
+    {
+      const Int_t nbinslo  = shapelo->GetNbinsX();
+      binwidth = shapelo->GetBinWidth(1);
+      
+      derivativelo = new TH1F(Form("%s%s",shapelo->GetName(),"_der"),
+                              Form("%s%s",shapelo->GetTitle()," derivative"),
+                              nbinslo,
+                              shapelo->GetBinLowEdge(1),
+                              shapelo->GetBinLowEdge(nbinslo)+binwidth);
+      
+      //
+      // Calculate the derivative of shapelo
+      // 
+      for (Int_t i = 1; i<nbinslo+1;i++)
+        {
+          derivativelo->SetBinContent(i,
+                                      ((shapelo->GetBinContent(i+1)-shapelo->GetBinContent(i-1))/2./binwidth));
+          derivativelo->SetBinError(i,
+                                    (sqrt(shapelo->GetBinError(i+1)*shapelo->GetBinError(i+1)
+                                          +shapelo->GetBinError(i-1)*shapelo->GetBinError(i-1))/2./binwidth));
+        }
+      
+      //
+      // normalize the shapelo, such that the integral for fWindowSize slices is one!
+      //
+      sum      = 0;
+      lasttemp = fBinningResolutionLoGain * (fSignalStartBinLoGain + fWindowSizeLoGain);
+      lasttemp = lasttemp > nbinslo ? nbinslo : lasttemp;
+      
+      for (Int_t i=fBinningResolutionLoGain*fSignalStartBinLoGain; i<lasttemp; i++) 
+        sum += shapelo->GetBinContent(i);
+
+      sum /= fBinningResolutionLoGain;
+      
+      shapelo->Scale(1./sum);
+      derivativelo->Scale(1./sum);
+      
+      //
+      // read in the noise auto-correlation function:
+      //
+      TMatrix Blo(fWindowSizeLoGain,fWindowSizeLoGain);
+      
+      for (Int_t i=0; i<fWindowSizeLoGain; i++){
+        for (Int_t j=0; j<fWindowSizeLoGain; j++){
+          Blo[i][j]=autocorrlo->GetBinContent(i+1+fSignalStartBinLoGain,j+1+fSignalStartBinLoGain);
+        }
+      }  
+      Blo.Invert();
+
+      const Int_t nsizelo = fWindowSizeLoGain*fBinningResolutionLoGain;
+      fAmpWeightsLoGain.Set(nsizelo);
+      fTimeWeightsLoGain.Set(nsizelo);  
+  
+      //
+      // Loop over relative time in one BinningResolution interval
+      //
+      Int_t start = fBinningResolutionLoGain*fSignalStartBinLoGain + fBinningResolutionHalfLoGain;
+      
+      for (Int_t i = -fBinningResolutionHalfLoGain+1; i<=fBinningResolutionHalfLoGain; i++)
+        {
+          
+          TMatrix g(fWindowSizeLoGain,1);
+          TMatrix gT(1,fWindowSizeLoGain);
+          TMatrix d(fWindowSizeLoGain,1);
+          TMatrix dT(1,fWindowSizeLoGain);
+          
+          for (Int_t count=0; count < fWindowSizeLoGain; count++){
+            
+            g[count][0] = shapelo->GetBinContent(start
+                                             +fBinningResolutionLoGain*count+i); 
+            gT[0][count]= shapelo->GetBinContent(start
+                                              +fBinningResolutionLoGain*count+i);
+            d[count][0] = derivativelo->GetBinContent(start
+                                                  +fBinningResolutionLoGain*count+i);
+            dT[0][count]= derivativelo->GetBinContent(start
+                                                   +fBinningResolutionLoGain*count+i);
+          }
+          
+          TMatrix m_denom = (gT*(Blo*g))*(dT*(Blo*d)) - (dT*(Blo*g))*(dT*(Blo*g));
+          Float_t   denom = m_denom[0][0];  // ROOT thinks, m_denom is still a matrix
+          
+          TMatrix m_first = dT*(Blo*d);       // ROOT thinks, m_first is still a matrix
+          Float_t   first = m_first[0][0]/denom;
+          
+          TMatrix m_last  = gT*(Blo*d);       // ROOT thinks, m_last  is still a matrix
+          Float_t   last  = m_last[0][0]/denom;
+          
+          TMatrix m1 = gT*Blo;
+          m1 *= first;
+          
+          TMatrix m2 = dT*Blo; 
+          m2 *=last;
+          
+          TMatrix w_amp = m1 - m2;
+          
+          TMatrix m_first1 = gT*(Blo*g);
+          Float_t   first1 = m_first1[0][0]/denom;
+          
+          TMatrix m_last1  = gT*(Blo*d);
+          Float_t   last1  = m_last1 [0][0]/denom;
+          
+          TMatrix m11 = dT*Blo; 
+          m11 *=first1;
+          
+          TMatrix m21 = gT*Blo;
+          m21 *=last1;
+          
+          TMatrix w_time= m11 - m21; 
+          
+          for (Int_t count=0; count < fWindowSizeLoGain; count++)
+            {
+              const Int_t idx = i+fBinningResolutionHalfLoGain+fBinningResolutionLoGain*count-1;
+              fAmpWeightsLoGain [idx] = w_amp [0][count];
+              fTimeWeightsLoGain[idx] = w_time[0][count];
+            }
+      
+        } // end loop over i
+    }
+  
+  ofstream fn(filename.Data());
+
+  fn << "# High Gain Weights: " << fWindowSizeHiGain << " " << fBinningResolutionHiGain << endl;
+  fn << "# (Amplitude)  (Time) " << endl;
+
+  for (Int_t i=0; i<nsizehi; i++)
+    fn << "\t" << fAmpWeightsHiGain[i] << "\t" << fTimeWeightsHiGain[i] << endl;
+
+  fn << "# Low Gain Weights: " << fWindowSizeLoGain << " " << fBinningResolutionLoGain << endl;
+  fn << "# (Amplitude)  (Time) " << endl;
+
+  for (Int_t i=0; i<nsizehi; i++)
+    fn << "\t" << fAmpWeightsLoGain[i] << "\t" << fTimeWeightsLoGain[i] << endl;
+
+  delete derivativehi;
+  if (derivativelo)
+    delete derivativelo;
+
+  return kTRUE;
+}
+
+void MExtractTimeAndChargeDigitalFilter::Print(Option_t *o) const
+{
+    if (IsA()==Class())
+        *fLog << GetDescriptor() << ":" << endl;
+
+    MExtractTimeAndCharge::Print(o);
+    *fLog << " Time Shift  HiGain: " << fTimeShiftHiGain         << "  LoGain: " << fTimeShiftLoGain << endl;
+    *fLog << " Window Size HiGain: " << fWindowSizeHiGain        << "  LoGain: " << fWindowSizeLoGain << endl;
+    *fLog << " Binning Res HiGain: " << fBinningResolutionHiGain << "  LoGain: " << fBinningResolutionHiGain << endl;
+    *fLog << " Weights File:       " << fNameWeightsFile << endl;
+
+    TString opt(o);
+    if (!opt.Contains("weights"))
+        return;
+
+    *fLog << endl;
+    *fLog << inf << "Using the following weights: " << endl;
+    *fLog << "Hi-Gain:" << endl;
+    for (Int_t i=0; i<fBinningResolutionHiGain*fWindowSizeHiGain; i++)
+        *fLog << " " << fAmpWeightsHiGain[i] << " \t " << fTimeWeightsHiGain[i] << endl;
+
+    *fLog << "Lo-Gain:" << endl;
+    for (Int_t i=0; i<fBinningResolutionLoGain*fWindowSizeLoGain; i++)
+        *fLog << " " << fAmpWeightsLoGain[i] << " \t " << fTimeWeightsLoGain[i] << endl;
+}
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilter.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilter.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilter.h	(revision 9772)
@@ -0,0 +1,116 @@
+#ifndef MARS_MExtractTimeAndChargeDigitalFilter
+#define MARS_MExtractTimeAndChargeDigitalFilter
+
+#ifndef MARS_MExtractTimeAndCharge
+#include "MExtractTimeAndCharge.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+class TH1F;
+class TH2F;
+class MPedestalPix;
+class MExtractTimeAndChargeDigitalFilter : public MExtractTimeAndCharge
+{
+private:
+
+  static const Byte_t fgHiGainFirst;             //! Default for fHiGainFirst       (now set to: 0)
+  static const Byte_t fgHiGainLast;              //! Default for fHiGainLast        (now set to:14)
+  static const Byte_t fgLoGainFirst;             //! Default for fLoGainFirst       (now set to: 3)
+  static const Byte_t fgLoGainLast;              //! Default for fLoGainLast        (now set to:14)
+  static const Int_t  fgWindowSizeHiGain;        //! Default for fWindowSizeHiGain  (now set to: 6)
+  static const Int_t  fgWindowSizeLoGain;        //! Default for fWindowSizeLoGain  (now set to: 6)
+  static const Int_t  fgBinningResolutionHiGain; //! Default for fBinningResolutionHiGain (now set to: 10)
+  static const Int_t  fgBinningResolutionLoGain; //! Default for fBinningResolutionLoGain (now set to: 10)
+  static const Int_t  fgSignalStartBinHiGain;    //! Default for fSignalStartBinHiGain (now set to: 4)
+  static const Int_t  fgSignalStartBinLoGain;    //! Default for fSignalStartBinLoGain (now set to: 4)
+  static const TString fgNameWeightsFile;        //! "cosmics_weights.dat"
+  static const Float_t fgOffsetLoGain;           //! Default for fOffsetLoGain (now set to 1.7)
+  static const Float_t fgLoGainStartShift;       //! Default for fLoGainStartShift (now set to -1.8)
+  
+  MArrayF fHiGainSignal;                        //! Need fast access to the signals in a float way
+  MArrayF fLoGainSignal;                        //! Store them in separate arrays
+
+  MArrayI fArrBinningResHiGain;                 //! helping arrays to hold binningres * i 
+  MArrayI fArrBinningResLoGain;                 //! helping arrays to hold binningres * i 
+  MArrayI fArrBinningResHalfHiGain;             //! helping arrays to hold binningres * i + binningreshalf
+  MArrayI fArrBinningResHalfLoGain;             //! helping arrays to hold binningres * i + binningreshalf
+  
+  Float_t fTimeShiftHiGain;                     //  Time shift from when on to apply the filter
+  Float_t fTimeShiftLoGain;                     //  Time shift from when on to apply the filter
+  
+  Int_t   fSignalStartBinHiGain;                //! Start bin from when on to apply weights
+  Int_t   fSignalStartBinLoGain;                //! Start bin from when on to apply weights
+
+  Int_t   fBinningResolutionHiGain;             //  Number of weights per bin High-Gain
+  Int_t   fBinningResolutionHalfHiGain;         //  Half Number of weights per bin High-Gain
+  Int_t   fBinningResolutionLoGain;             //  Number of weights per bin Low-Gain
+  Int_t   fBinningResolutionHalfLoGain;         //  Half Number of weights per bin Low-Gain
+  
+  MArrayF fAmpWeightsHiGain;                    //! Amplitude weights High-Gain (from weights file)
+  MArrayF fTimeWeightsHiGain;                   //! Time weights High-Gain (from weights file)
+  MArrayF fAmpWeightsLoGain;                    //! Amplitude weights Low-Gain (from weights file)
+  MArrayF fTimeWeightsLoGain;                   //! Time weights Low-Gain (from weights file)
+
+  TString fNameWeightsFile;                     //  Name of the weights file
+  Bool_t  fWeightsSet;                          //! Flag if weights have alreayd been set
+  Int_t   fRandomIter;                          //! Counter used to randomize weights for noise calculation
+
+  Bool_t  InitArrays();
+
+  void CalcBinningResArrays();
+
+protected:
+  
+  Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+
+  MExtractTimeAndChargeDigitalFilter(const char *name=NULL, const char *title=NULL);  
+  ~MExtractTimeAndChargeDigitalFilter() { }
+  
+  Bool_t WriteWeightsFile(TString filename,
+                          TH1F *shapehi, TH2F *autocorrhi,
+                          TH1F *shapelo=NULL, TH2F *autocorrlo=NULL );
+
+  Bool_t ReadWeightsFile(TString filename);
+
+  void SetNameWeightsFile( TString s = fgNameWeightsFile )   { fNameWeightsFile = s; }
+
+  void SetBinningResolution(const Int_t rh=fgBinningResolutionHiGain, const Int_t rl=fgBinningResolutionLoGain)  {
+    fBinningResolutionHiGain     = rh & ~1;
+    fBinningResolutionHalfHiGain = fBinningResolutionHiGain/2;
+    fBinningResolutionLoGain     = rl & ~1;
+    fBinningResolutionHalfLoGain = fBinningResolutionLoGain/2;
+  }
+  
+  void SetSignalStartBin( const Int_t sh=fgSignalStartBinHiGain, const Int_t sl=fgSignalStartBinLoGain) {
+    fSignalStartBinHiGain = sh;
+    fSignalStartBinLoGain = sl; 
+  }
+
+  void SetWindowSize( Int_t windowh=fgWindowSizeHiGain, Int_t windowl=fgWindowSizeLoGain);
+
+  const char* GetNameWeightsFile() const  { return fNameWeightsFile.Data(); }
+
+  void Print(Option_t *o="") const;
+
+  Bool_t IsWeightsSet() const  { return fWeightsSet;  }
+
+  void FindTimeAndChargeHiGain(Byte_t *firstused, Byte_t *logain, Float_t &sum, Float_t &dsum,
+                               Float_t &time, Float_t &dtime,
+                               Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+  void FindTimeAndChargeLoGain(Byte_t *firstused, Float_t &sum,  Float_t &dsum,
+                               Float_t &time, Float_t &dtime,
+                               Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+  
+  ClassDef(MExtractTimeAndChargeDigitalFilter, 2)   // Hendrik's digital filter
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.cc	(revision 9772)
@@ -0,0 +1,573 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 02/2005 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeDigitalFilterPeakSearch
+//
+//   An extractor using the digital filter in combination with a global
+//   peak search, analogue to the class MExtractFixedWindowPeakSearch.
+//
+//   The extractor returns kFALSE if too many events lie outside the 
+//   range: (peak - fOffsetLeftFromPeak, peak - fOffsetRightFromPeak)
+//
+//   Input Containers:
+//    MRawEvtData
+//    MRawRunHeader
+//    MPedestalCam
+//
+//   Output Containers:
+//    MArrivalTimeCam
+//    MExtractedSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndChargeDigitalFilterPeakSearch.h"
+
+#include <fstream>
+
+#include <TFile.h>
+#include <TH1F.h>
+#include <TH2F.h>
+#include <TString.h>
+#include <TMatrix.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MExtractTimeAndChargeDigitalFilterPeakSearch);
+
+using namespace std;
+
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgHiGainFirst             =  0;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgHiGainLast              = 20;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgLoGainFirst             =  0;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgLoGainLast              = 14;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgOffsetLeftFromPeak      =  3;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgOffsetRightFromPeak     =  3;
+const Byte_t MExtractTimeAndChargeDigitalFilterPeakSearch::fgPeakSearchWindowSize    =  2;
+const Int_t  MExtractTimeAndChargeDigitalFilterPeakSearch::fgHiGainFailureLimit      = 10;
+const Int_t  MExtractTimeAndChargeDigitalFilterPeakSearch::fgLoGainFailureLimit      = 25;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets:
+// - fOffsetLeftFromPeak    to fgOffsetLeftFromPeak
+// - fOffsetRightFromPeak   to fgOffsetRightFromPeak
+// - fPeakSearchWindowSize  to fgPeakSearchWindowSize
+// - fHiGainFailureLimit to fgHiGainFailureLimit
+// - fLoGainFailureLimit to fgLoGainFailureLimit
+//
+MExtractTimeAndChargeDigitalFilterPeakSearch::MExtractTimeAndChargeDigitalFilterPeakSearch(const char *name, const char *title) 
+    :   fHiGainOutOfRangeLeft(0), fHiGainOutOfRangeRight(0),
+        fLoGainOutOfRangeLeft(0), fLoGainOutOfRangeRight(0),
+        fBadPixels(NULL)
+{
+    fName  = name  ? name  : "MExtractTimeAndChargeDigitalFilterPeakSearch";
+    fTitle = title ? title : "Digital Filter";
+
+    SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+
+    SetOffsetLeftFromPeak();
+    SetOffsetRightFromPeak();
+    SetPeakSearchWindowSize();
+    SetHiGainFailureLimit();
+    SetLoGainFailureLimit();
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//  - MArrivalTimeCam    
+//
+// The following variables are set to 0:
+//
+//  - fHiGainOutOfRangeLeft
+//  - fHiGainOutOfRangeRight
+//  - fLoGainOutOfRangeLeft
+//  - fLoGainOutOfRangeRight
+//
+Int_t MExtractTimeAndChargeDigitalFilterPeakSearch::PreProcess(MParList *pList)
+{
+
+  if (!MExtractTimeAndCharge::PreProcess(pList))
+    return kFALSE;
+  
+  fHiGainOutOfRangeLeft  = 0;
+  fHiGainOutOfRangeRight = 0;
+  fLoGainOutOfRangeLeft  = 0;
+  fLoGainOutOfRangeRight = 0;
+  
+  fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+  if (!fBadPixels)
+    {
+      *fLog << err << "Cannot find MBadPixelsCam ... abort." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// FindPeak
+//
+// Finds highest sum of "window" consecutive FADC slices in a pixel, and store
+// in "startslice" the first slice of the group which yields the maximum sum.
+// In "max" the value of the maximum sum is stored, in "sat" the number of 
+// saturated slices.
+//
+void MExtractTimeAndChargeDigitalFilterPeakSearch::FindPeak(Byte_t *ptr, Byte_t *logain, Byte_t &startslice, Int_t &max, 
+							    Int_t &sat, Byte_t &satpos) const
+{
+
+  Byte_t *end = ptr + fHiGainLast - fHiGainFirst + 1;
+
+  sat = 0;
+  satpos = 0;
+  
+  startslice = 0;
+  Int_t sum=0;
+
+  //
+  // Calculate the sum of the first "fPeakSearchWindowSize" slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+
+  while (p<ptr+fPeakSearchWindowSize)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+        {
+          if (sat == 0)
+              satpos = p-ptr;
+          sat++;
+        }
+    }
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      {
+        if (sat == 0)
+          satpos = p-ptr;
+        sat++;
+      }
+  
+  //
+  // Calculate the i-th sum of n as
+  //    sum_i+1 = sum_i + slice[i+fPeakSearchWindowSize] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  for (p=ptr; p+fPeakSearchWindowSize<end; p++)
+    {
+      sum += *(p+fPeakSearchWindowSize) - *p;
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = p-ptr+1;
+	}
+    }
+
+  if (!fHiLoLast)
+    return;
+
+  Byte_t *l = logain;
+
+  while (++p < end && l < logain+fHiLoLast)
+    {
+      sum += *l - *p;
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = p-ptr+1;
+	}
+
+      if (*l++ >= fSaturationLimit)
+        {
+          if (sat == 0)
+            satpos = l-logain + fHiGainLast - fHiGainFirst;
+          sat++;
+        }
+    }
+  
+  if (fHiLoLast <= fPeakSearchWindowSize)
+    return;
+
+  while (l < logain+fHiLoLast)
+    {
+      if (*l++ >= fSaturationLimit)
+        {
+          if (sat == 0)
+            satpos = l-logain+fHiGainLast-fHiGainFirst;
+          sat++;
+        }
+
+      sum += *l - *(l-fPeakSearchWindowSize);
+      if (sum > max)
+	{
+	  max = sum;
+	  startslice = l-logain + fHiGainLast - fHiGainFirst - fPeakSearchWindowSize + 1;
+	}
+    }
+
+  return;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Process
+//
+// First find the pixel with highest sum of fPeakSearchWindowSize slices (default:2)
+// "startslice" will mark the slice at which the highest sum begins for that pixel.
+//
+// Then define the beginning of the digital filter search window for ALL pixels as the slice
+// before that: startslice-fOffsetLeftFromPeak until: startslice+fOffsetRightFromPeak
+//
+Int_t MExtractTimeAndChargeDigitalFilterPeakSearch::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  Int_t   sat        = 0;
+  Byte_t  satpos     = 0;
+  ULong_t gsatpos    = 0;
+
+  Int_t   maxsumhi   = -1000000;
+  Int_t   numsat     = 0;
+  Byte_t  startslice = 0;
+
+  Byte_t hiGainFirstsave = fHiGainFirst;
+  Byte_t hiGainLastsave  = fHiGainLast;
+  Byte_t loGainFirstsave = fLoGainFirst;
+  Byte_t loGainLastsave  = fLoGainLast; 
+  Byte_t hiLoLastsave    = fHiLoLast;
+
+  Byte_t higainfirst     = fHiGainFirst;
+  UInt_t peakpixel       = 0;
+
+  while (pixel.Next())
+    {
+
+      Int_t sumhi;
+      sat = 0;
+
+      MBadPixelsPix &bad = (*fBadPixels)[pixel.GetPixelId()];
+      
+      if (!bad.IsUnsuitable())
+        FindPeak(pixel.GetHiGainSamples()+fHiGainFirst, pixel.GetLoGainSamples(), startslice, sumhi, sat, satpos);
+
+      if (sumhi > maxsumhi && sat == 0)
+	{
+	  maxsumhi     = sumhi;
+	  higainfirst  = fHiGainFirst + startslice;
+          peakpixel    = pixel.GetPixelId();
+	}
+      else if (sat)
+        {
+          numsat++;
+          gsatpos += satpos;
+        }
+    }
+
+  //
+  // Check necessary for calibration events
+  //
+  if (numsat > fSignals->GetSize()*0.9)
+    higainfirst = gsatpos/numsat - 1;
+
+  //
+  // Shift the start slice to the left:
+  //
+  if (higainfirst >= fHiGainFirst + fOffsetLeftFromPeak)
+    fHiGainFirst = higainfirst - fOffsetLeftFromPeak;
+  else
+    {
+      //      *fLog << err << (Int_t)higainfirst << "   " << peakpixel << endl;      
+      fHiGainOutOfRangeLeft++;
+    }
+  
+  //
+  // Shift the last slice to the right:
+  //
+  const Byte_t rlim = higainfirst + fOffsetRightFromPeak + fWindowSizeHiGain - 1;
+  if (rlim <= fHiGainLast+fHiLoLast)
+    if (rlim > fHiGainLast)
+      {
+        fHiLoLast   = rlim - fHiGainLast;
+        fHiGainLast = pixel.GetNumHiGainSamples() - 1;
+      }
+    else
+      {
+        fHiLoLast   = 0;
+        fHiGainLast = rlim;
+      }
+  else 
+    {
+      fHiGainOutOfRangeRight++;
+      //      *fLog << err << (Int_t)higainfirst << "   " << peakpixel << endl;      
+    }
+  
+  const Byte_t llim = higainfirst + (Int_t)fOffsetLoGain;
+  if ( llim  >= fLoGainFirst + fOffsetLeftFromPeak) 
+    fLoGainFirst = llim - fOffsetLeftFromPeak;
+  else
+    fLoGainOutOfRangeLeft++;
+  
+  //
+  // Make sure we will not integrate beyond the lo gain limit:
+  //
+  const Byte_t lolast = fLoGainFirst+fWindowSizeLoGain+fOffsetRightFromPeak-1;  
+  if (lolast < pixel.GetNumLoGainSamples())
+    fLoGainLast = lolast;
+  else
+    {
+      fLoGainOutOfRangeRight++;
+      //      *fLog << err << (Int_t)higainfirst << "   " << peakpixel << "  " << (int)fLoGainFirst << endl;      
+    }
+  
+  //  *fLog << inf << (int)fHiGainFirst << "  " << (int)higainfirst << "  " << (int)fHiGainLast 
+  //        << "  " << (int)fLoGainFirst << "  " << (int)fLoGainLast << endl;
+
+  pixel.Reset();
+
+  while (pixel.Next())
+    {
+
+      //
+      // Find signal in hi- and lo-gain
+      //
+      Float_t sumhi =0., deltasumhi =0; // Set hi-gain of MExtractedSignalPix valid
+      Float_t timehi=0., deltatimehi=0; // Set hi-gain of MArrivalTimePix valid
+      Byte_t sathi=0;
+
+      // Initialize fMaxBinContent for the case, it gets not set by the derived class
+      fMaxBinContent = fLoGainSwitch + 1; 
+
+      const Int_t pixidx = pixel.GetPixelId();
+      const MPedestalPix  &ped = (*fPedestals)[pixidx];
+      const Bool_t higainabflag = pixel.HasABFlag();
+
+      FindTimeAndChargeHiGain(pixel.GetHiGainSamples()+fHiGainFirst, pixel.GetLoGainSamples(), 
+                              sumhi, deltasumhi, 
+                              timehi, deltatimehi, 
+                              sathi, ped, higainabflag);
+
+      //
+      // Make sure that in cases the time couldn't be correctly determined
+      // more meaningfull default values are assigned
+      //
+      if (timehi<0)
+          timehi = -1;
+      if (timehi>pixel.GetNumHiGainSamples())
+          timehi = pixel.GetNumHiGainSamples();
+      
+      Float_t sumlo =0., deltasumlo =-1.; // invalidate logain of MExtractedSignalPix
+      Float_t timelo=0., deltatimelo=-1;  // invalidate logain of MArrivalTimePix
+      Byte_t satlo=0;
+      
+      //
+      // Adapt the low-gain extraction range from the obtained high-gain time
+      //
+      if (pixel.HasLoGain() && (fMaxBinContent > fLoGainSwitch) )
+      {
+          deltasumlo  = 0; // make logain of MExtractedSignalPix valid
+          deltatimelo = 0; // make logain of MArrivalTimePix valid
+
+          fLoGainFirstSave = fLoGainFirst;
+          const Byte_t logainstart = sathi 
+            ? sathi + (Int_t)fLoGainStartShift
+            : (Byte_t)(timehi + fLoGainStartShift);
+        
+	  fLoGainFirst = logainstart > fLoGainFirstSave ? logainstart : fLoGainFirstSave;
+
+          if ( fLoGainFirst < fLoGainLast )
+            {
+              const Bool_t logainabflag = (higainabflag + pixel.GetNumHiGainSamples()) & 0x1;
+              FindTimeAndChargeLoGain(pixel.GetLoGainSamples()+fLoGainFirst,
+                                      sumlo, deltasumlo,
+                                      timelo, deltatimelo,
+                                      satlo, ped, logainabflag);
+          }
+          fLoGainFirst = fLoGainFirstSave;
+
+          // Make sure that in cases the time couldn't be correctly determined
+          // more meaningfull default values are assigned
+          if (timelo<0)
+              timelo = -1;
+          if (timelo>pixel.GetNumLoGainSamples())
+              timelo = pixel.GetNumLoGainSamples();
+      }
+
+      MExtractedSignalPix &pix = (*fSignals)[pixidx];
+      MArrivalTimePix     &tix = (*fArrTime)[pixidx];
+      pix.SetExtractedSignal(sumhi, deltasumhi,sumlo, deltasumlo);
+      pix.SetGainSaturation(sathi, sathi, satlo);
+
+      tix.SetArrivalTime(timehi, deltatimehi, timelo-fOffsetLoGain, deltatimelo);
+      tix.SetGainSaturation(sathi, sathi, satlo);
+ 
+    } /* while (pixel.Next()) */
+
+  fArrTime->SetReadyToSave();
+  fSignals->SetReadyToSave();
+
+  fHiGainFirst  = hiGainFirstsave;
+  fHiGainLast   = hiGainLastsave ; 
+  fLoGainFirst  = loGainFirstsave;
+  fLoGainLast   = loGainLastsave ; 
+  fHiLoLast     = hiLoLastsave;
+
+  return kTRUE;
+}
+
+Int_t MExtractTimeAndChargeDigitalFilterPeakSearch::PostProcess()
+{
+
+  if (GetNumExecutions() < 1)
+    return kTRUE;
+
+  *fLog << warn << endl;
+
+  const Int_t higainfailure = ((fHiGainOutOfRangeLeft+fHiGainOutOfRangeRight)*100)/GetNumExecutions();
+  const Int_t logainfailure = ((fLoGainOutOfRangeLeft+fLoGainOutOfRangeRight)*100)/GetNumExecutions();
+
+  if (fHiGainOutOfRangeLeft > 0)
+    *fLog << Form("%5.1f",((Float_t)fHiGainOutOfRangeLeft*100)/GetNumExecutions())
+          << "% ranging out of hi-gain window to the left!" << endl;
+  if (fHiGainOutOfRangeRight > 0)
+    *fLog << Form("%5.1f",((Float_t)fHiGainOutOfRangeRight*100)/GetNumExecutions())
+	  << "% ranging out of hi-gain window to the right!" << endl;
+  if (fLoGainOutOfRangeLeft > 0)
+    *fLog << Form("%5.1f",((Float_t)fLoGainOutOfRangeLeft*100)/GetNumExecutions())
+          << "% ranging out of lo-gain window to the left!" << endl;
+  if (fLoGainOutOfRangeRight > 0)
+    *fLog << Form("%5.1f",((Float_t)fLoGainOutOfRangeRight*100)/GetNumExecutions())
+	  << "% ranging out of lo-gain window to the right!" << endl;
+
+  
+  if (higainfailure > fHiGainFailureLimit)
+    {
+      *fLog << err << higainfailure << "% range failures in high gain above limit of: " << fHiGainFailureLimit << "%." << endl;
+      return kFALSE;
+    }
+  
+  if (logainfailure > fLoGainFailureLimit)
+    {
+      *fLog << err << logainfailure << "% range failures in low gain above limit of: " << fLoGainFailureLimit << "%." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//   MJPedestal.MExtractor.BinningResolutionHiGain: 10
+//   MJPedestal.MExtractor.BinningResolutionLoGain: 10
+//   MJPedestal.MExtractor.WeightsFile: filename
+//
+Int_t MExtractTimeAndChargeDigitalFilterPeakSearch::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+
+  if (IsEnvDefined(env, prefix, "OffsetLeftFromPeak", print))
+    {
+      fOffsetLeftFromPeak = GetEnvValue(env, prefix, "OffsetLeftFromPeak", fOffsetLeftFromPeak);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "OffsetRightFromPeak", print))
+    {
+      fOffsetRightFromPeak = GetEnvValue(env, prefix, "OffsetRightFromPeak", fOffsetRightFromPeak);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "PeakSearchWindowSize", print))
+    {
+      fPeakSearchWindowSize = GetEnvValue(env, prefix, "PeakSearchWindowSize", fPeakSearchWindowSize);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "HiGainFailureLimit", print))
+    {
+      fHiGainFailureLimit = GetEnvValue(env, prefix, "HiGainFailureLimit", fHiGainFailureLimit);
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "LoGainFailureLimit", print))
+    {
+      fLoGainFailureLimit = GetEnvValue(env, prefix, "LoGainFailureLimit", fLoGainFailureLimit);
+      rc = kTRUE;
+    }
+  
+  return MExtractTimeAndChargeDigitalFilter::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
+
+
+void MExtractTimeAndChargeDigitalFilterPeakSearch::Print(Option_t *o) const
+{
+    if (IsA()==Class())
+        *fLog << GetDescriptor() << ":" << endl;
+
+    MExtractTimeAndChargeDigitalFilter::Print(o);
+    *fLog << " Offset from Peak left:   " << (int)fOffsetLeftFromPeak   << endl;
+    *fLog << " Offset from Peak right:  " << (int)fOffsetRightFromPeak  << endl;
+    *fLog << " Peak search window size: " << (int)fPeakSearchWindowSize << endl;
+    *fLog << " High Gain Failure limit: " << fHiGainFailureLimit << endl;
+    *fLog << " Low Gain Failure limit:  " << fLoGainFailureLimit << endl;
+}
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndChargeDigitalFilterPeakSearch.h	(revision 9772)
@@ -0,0 +1,73 @@
+#ifndef MARS_MExtractTimeAndChargeDigitalFilterPeakSearch
+#define MARS_MExtractTimeAndChargeDigitalFilterPeakSearch
+
+#ifndef MARS_MExtractTimeAndChargeDigitalFilter
+#include "MExtractTimeAndChargeDigitalFilter.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+#ifndef MARS_MArrayI
+#include "MArrayI.h"
+#endif
+
+class TH1F;
+class TH2F;
+class MPedestalPix;
+class MBadPixelsCam;
+
+class MExtractTimeAndChargeDigitalFilterPeakSearch : public MExtractTimeAndChargeDigitalFilter
+{
+private:
+
+  static const Byte_t fgHiGainFirst;           //! Default for fHiGainFirst           (now set to: 0)
+  static const Byte_t fgHiGainLast;            //! Default for fHiGainLast            (now set to:18)
+  static const Byte_t fgLoGainFirst;           //! Default for fLoGainFirst           (now set to: 2)
+  static const Byte_t fgLoGainLast;            //! Default for fLoGainLast            (now set to:14)
+  static const Byte_t fgOffsetLeftFromPeak;    //! Default for fOffsetLeftFromPeak    (now set to: 1)  
+  static const Byte_t fgOffsetRightFromPeak;   //! Default for fOffsetRightFromPeak   (now set to: 2)  
+  static const Byte_t fgPeakSearchWindowSize;  //! Default for fPeakSearchWindowSize  (now set to: 2)
+  static const Int_t  fgHiGainFailureLimit;    //! Default for fHiGainMaxFailureLimit (now set to: 5)
+  static const Int_t  fgLoGainFailureLimit;    //! Default for fHiGainMaxFailureLimit (now set to: 10)
+
+  Byte_t  fOffsetLeftFromPeak;                 // Number of slices to start extraction before peak slice
+  Byte_t  fOffsetRightFromPeak;                // Number of slices to stop  extraction after  peak slice
+  Byte_t  fPeakSearchWindowSize;               // Size of FADC window in the search for the highest peak of all pixels.
+  Int_t   fHiGainFailureLimit;                 // Limit for percentage of events ranging out of limits in high gain
+  Int_t   fLoGainFailureLimit;                 // Limit for percentage of events ranging out of limits in low gain
+
+  ULong_t fHiGainOutOfRangeLeft;               // Number of events out of range to the left side in high gain
+  ULong_t fHiGainOutOfRangeRight;              // Number of events out of range to the right side in high gain
+  ULong_t fLoGainOutOfRangeLeft;               // Number of events out of range to the left side in low gain
+  ULong_t fLoGainOutOfRangeRight;              // Number of events out of range to the right side in low gain
+
+  MBadPixelsCam *fBadPixels;                   // Bad Pixels Camera
+  
+  void    FindPeak(Byte_t *ptr, Byte_t *logain,
+                   Byte_t &startslice, Int_t &max, Int_t &sat, Byte_t &satpos) const;
+
+  Int_t   PreProcess(MParList *pList);
+  Int_t   Process();
+  Int_t   PostProcess();
+
+  Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+
+  MExtractTimeAndChargeDigitalFilterPeakSearch(const char *name=NULL, const char *title=NULL);  
+  ~MExtractTimeAndChargeDigitalFilterPeakSearch() { }
+  
+  void SetOffsetLeftFromPeak  ( Byte_t offset=fgOffsetLeftFromPeak   )  { fOffsetLeftFromPeak   = offset; }
+  void SetOffsetRightFromPeak ( Byte_t offset=fgOffsetRightFromPeak  )  { fOffsetRightFromPeak  = offset; }
+  void SetPeakSearchWindowSize( Byte_t size  =fgPeakSearchWindowSize )  { fPeakSearchWindowSize = size;   }
+  void SetHiGainFailureLimit  ( Int_t  lim   =fgHiGainFailureLimit   )  { fHiGainFailureLimit   = lim;    }     
+  void SetLoGainFailureLimit  ( Int_t  lim   =fgLoGainFailureLimit   )  { fLoGainFailureLimit   = lim;    }
+
+  void Print(Option_t *o="") const;
+
+  ClassDef(MExtractTimeAndChargeDigitalFilterPeakSearch, 1)   // Digital filter with global Peak Search
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSlidingWindow.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSlidingWindow.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSlidingWindow.cc	(revision 9772)
@@ -0,0 +1,446 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug,    09/2004 <mailto:markus@ifae.es> 
+!   Author(s): Hendrik Bartko, 01/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2002-2005
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractSlidingWindow
+//
+//   Extracts the signal from a sliding window of size fHiGainWindowSize and 
+//   fLoGainWindowSize, respectively. The signal is the one which maximizes 
+//   the clock-noise and pedestal-corrected integral contents.
+//
+//   The amplitude-weighted arrival time is calculated from the window with 
+//   the highest integral using the following formula:
+//
+//   t = sum(s(i) * i) / sum(i) 
+// 
+//   where i denotes the FADC slice index and s(i) the clock-noise and 
+///  pedestal-corrected FADC value at slice index i. The sum runs over the 
+//   extraction window size.
+//
+//   Call: SetRange(higainfirst, higainlast, logainfirst, logainlast) 
+//         to modify the ranges in which the window is allowed to move. 
+//
+//   Defaults are: 
+// 
+//   fHiGainFirst =  fgHiGainFirst =  0 
+//   fHiGainLast  =  fgHiGainLast  =  14
+//   fLoGainFirst =  fgLoGainFirst =  2 
+//   fLoGainLast  =  fgLoGainLast  =  14
+//
+//  Call: SetWindowSize(windowhigain, windowlogain) 
+//        to modify the sliding window widths. Windows have to be an even number. 
+//        Odd numbers are possible since the clock-noise is corrected for.
+//
+//  Defaults are:
+//
+//  fHiGainWindowSize = 6
+//  fLoGainWindowSize = 6
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndChargeSlidingWindow.h"
+
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractTimeAndChargeSlidingWindow);
+
+using namespace std;
+
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgHiGainFirst  = 0;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgHiGainLast   = 16;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgLoGainFirst  = 2;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgLoGainLast   = 14;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgHiGainWindowSize = 6;
+const Byte_t  MExtractTimeAndChargeSlidingWindow::fgLoGainWindowSize = 6;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+// Initializes:
+// - fWindowSizeHiGain to fgHiGainWindowSize
+// - fWindowSizeLoGain to fgLoGainWindowSize
+//
+MExtractTimeAndChargeSlidingWindow::MExtractTimeAndChargeSlidingWindow(const char *name, const char *title) 
+{
+  
+  fName  = name  ? name  : "MExtractTimeAndChargeSlidingWindow";
+  fTitle = title ? title : "Calculate arrival times and charges using a sliding window";
+
+  fWindowSizeHiGain = fgHiGainWindowSize;
+  fWindowSizeLoGain = fgLoGainWindowSize;
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+//-------------------------------------------------------------------
+//
+// Set the ranges
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - SetWindowSize(fWindowSizeHiGain,fWindowSizeLoGain);
+//
+void MExtractTimeAndChargeSlidingWindow::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);
+  
+}
+
+// -----------------------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// - if a window is smaller than 2, set it to 2
+// 
+// Sets:
+// - fNumHiGainSamples to: (Float_t)fWindowSizeHiGain
+// - fNumLoGainSamples to: (Float_t)fWindowSizeLoGain
+// - fSqrtHiGainSamples to: TMath::Sqrt(fNumHiGainSamples)
+// - fSqrtLoGainSamples to: TMath::Sqrt(fNumLoGainSamples)  
+//  
+void MExtractTimeAndChargeSlidingWindow::SetWindowSize(Int_t windowh, Int_t windowl)
+{
+  
+  fWindowSizeHiGain = windowh;
+  fWindowSizeLoGain = windowl;
+
+  const Int_t availhirange = (Int_t)(fHiGainLast-fHiGainFirst+1);
+
+  if (fWindowSizeHiGain > availhirange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",(int)fWindowSizeHiGain,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availhirange << endl;
+      fWindowSizeHiGain = availhirange;
+    }
+  
+  if (fWindowSizeHiGain<1) 
+    {
+      fWindowSizeHiGain = 1;
+      *fLog << warn << GetDescriptor() << ": High Gain window size too small, set to one sample" << endl;
+    }
+  
+  if (fLoGainLast != 0 && fWindowSizeLoGain != 0)
+    {
+      const Int_t availlorange = (Int_t)(fLoGainLast-fLoGainFirst+1);
+      
+      if (fWindowSizeLoGain > availlorange)
+        {
+          *fLog << warn << GetDescriptor() 
+                << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",(int)fWindowSizeLoGain,
+                        " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+          *fLog << warn << GetDescriptor() 
+                << ": Will set window size to: " << (int)availlorange << endl;
+          fWindowSizeLoGain = availlorange;
+        }
+    }
+  
+  fNumHiGainSamples = (Float_t)fWindowSizeHiGain;
+  fNumLoGainSamples = fLoGainLast ? (Float_t)fWindowSizeLoGain : 0.;
+  
+  fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// InitArrays
+//
+// Gets called in the ReInit() and initialized the arrays
+//
+Bool_t MExtractTimeAndChargeSlidingWindow::InitArrays()
+{
+  Int_t range = (Int_t)(fHiGainLast - fHiGainFirst + 1 + fHiLoLast);
+  fHiGainSignal.Set(range);
+  range = (Int_t)(fLoGainLast - fLoGainFirst + 1);
+  fLoGainSignal.Set(range);
+
+  return kTRUE;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeAndChargeSlidingWindow::FindTimeAndChargeHiGain(Byte_t *first, Byte_t *logain, Float_t &sum, Float_t &dsum, 
+                                                          Float_t &time, Float_t &dtime, 
+                                                          Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag)
+{
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t       *p  = first;
+  
+  Float_t max = 0;  // highest integral content of all windows
+  sat         = 0;
+
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t ABoffs = ped.GetPedestalABoffset();
+
+  const Float_t PedMean[2] = { pedes + ABoffs, pedes - ABoffs };
+
+  fMaxBinContent = 0;
+  //
+  // Check for saturation in all other slices
+  //
+  Int_t ids = fHiGainFirst;
+  Float_t *sample = fHiGainSignal.GetArray();
+
+  while (p<first+fWindowSizeHiGain)
+    {
+
+      const Float_t signal = (Float_t)*p - PedMean[(ids++ + abflag) & 0x1];      
+      sum                 += signal;
+      *sample++            = signal;
+      
+      if (*p > fMaxBinContent)
+	fMaxBinContent = *p;
+
+      if (*p++ >= fSaturationLimit)
+        if (!sat)
+            sat = ids-2;
+    }
+
+  if (IsNoiseCalculation())
+    return;
+   
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    {
+      if (*p > fMaxBinContent)
+	fMaxBinContent = *p;
+      
+      if (*p++ >= fSaturationLimit)
+	if (!sat)
+	  sat = ids-2;
+    }
+
+  //
+  // Calculate the i-th sum as
+  //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  Int_t count    = 0;
+  max            = sum;
+  Int_t idx      =  0;  // idx of the first slice of the maximum window
+  
+  for (p=first; p+fWindowSizeHiGain<end; p++)
+    {
+      
+      const Float_t signal = (Float_t)*(p+fWindowSizeHiGain) - PedMean[(ids++ + abflag) & 0x1];      
+      sum                 += signal - *(sample-fWindowSizeHiGain);
+      *sample++            = signal;
+      
+      if (sum>max)
+        {
+          max   = sum;
+          idx   = count+1;
+        }
+      count++;
+    }
+  
+  // 
+  // overlap bins
+  // 
+  Byte_t *l = logain;
+  while (l < logain+fHiLoLast)
+    {
+      
+      const Float_t signal = (Float_t)*l - PedMean[(ids++ + abflag) & 0x1];          
+      sum                 += signal - *(sample-fWindowSizeHiGain);
+      *sample++            = signal;
+
+      if (*l > fMaxBinContent)
+        fMaxBinContent = *logain;
+      
+      if (*l++ >= fSaturationLimit)
+        if (!sat)
+          sat = ids-2;
+      
+      if (sum>max)
+        {
+          max   = sum;
+          idx   = count+1;
+        }
+      count++;
+    } /* while (l<logain+fHiLoLast) */
+
+  //
+  // now calculate the time for the maximum window
+  //
+  Float_t timesignalsum  = 0.;
+  Int_t   timesquaredsum = 0;
+  
+  for (Int_t i=idx; i<idx+fWindowSizeHiGain; i++)
+    {
+      timesignalsum   += fHiGainSignal[i]*i;
+      timesquaredsum  += i*i;
+    }
+  
+  sum   = max;
+
+  time  = max > 0.1 ? timesignalsum / max  + Float_t(fHiGainFirst) : 1.;
+  dtime = max > 0.1 ? ped.GetPedestalRms() / max * sqrt(timesquaredsum - fWindowSizeHiGain*time) : 1.;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeAndChargeSlidingWindow::FindTimeAndChargeLoGain(Byte_t *first, Float_t &sum, Float_t &dsum, 
+                                                          Float_t &time, Float_t &dtime, 
+                                                          Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag) 
+{
+  
+  Int_t range = fLoGainLast - fLoGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t       *p  = first;
+  
+  Float_t max = 0;  // highest integral content of all windows
+  Int_t count = 0;  // counter to recognize the AB-flag
+
+  Float_t pedes        = ped.GetPedestal();
+  const Float_t ABoffs = ped.GetPedestalABoffset();
+
+  Float_t PedMean[2] = { pedes + ABoffs, pedes - ABoffs };
+  //
+  // Check for saturation in all other slices
+  //
+  Int_t ids = fLoGainFirst;
+
+  while (p<first+fWindowSizeLoGain)
+    {
+      const Float_t signal = (Float_t)*p - PedMean[(ids++ + abflag) & 0x1];      
+      sum                 += signal;
+      fLoGainSignal[count] = signal;
+      
+      if (*p++ >= fSaturationLimit)
+        sat++;
+
+      count++;
+    }
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+  
+  if (IsNoiseCalculation())
+    return;
+
+  //
+  // Calculate the i-th sum as
+  //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  count          = 0;
+  max            = sum;
+  Int_t idx      =  0;  // idx of the first slice of the maximum window
+  
+  for (p=first; p+fWindowSizeLoGain<end; p++)
+    {
+
+      const Float_t signal = (Float_t)*(p+fWindowSizeLoGain) - PedMean[(ids++ + abflag) & 0x1];      
+      sum                 += signal - fLoGainSignal[count];
+      fLoGainSignal[count + fWindowSizeLoGain] = signal;
+
+      if (sum>max)
+	{
+	  max   = sum;
+          idx   = count+1;
+	}
+      count++;
+    }
+  
+  //
+  // now calculate the time for the maximum window
+  //
+  Float_t timesignalsum  = 0;
+  Int_t   timesquaredsum = 0;
+  
+  for (Int_t i=idx; i<idx+fWindowSizeLoGain; i++)
+    {
+      timesignalsum   += fLoGainSignal[i]*i;
+      timesquaredsum  += i*i;
+    }
+  
+  sum   = max;
+
+  time  = max > 0.1 ? timesignalsum / max  + Float_t(fLoGainFirst) : 1.;
+  dtime = max > 0.1 ? ped.GetPedestalRms() / max * sqrt(timesquaredsum - fWindowSizeLoGain*time) : 1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//
+Int_t MExtractTimeAndChargeSlidingWindow::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+  
+  Byte_t hw = fWindowSizeHiGain;
+  Byte_t lw = fWindowSizeLoGain;
+  
+  Bool_t rc = kFALSE;
+  
+  if (IsEnvDefined(env, prefix, "HiGainWindowSize", print))
+    {
+      hw = GetEnvValue(env, prefix, "HiGainWindowSize", hw);
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "LoGainWindowSize", print))
+    {
+      lw = GetEnvValue(env, prefix, "LoGainWindowSize", lw);
+      rc = kTRUE;
+    }
+  
+  if (rc)
+    SetWindowSize(hw, lw);
+  
+  return MExtractTimeAndCharge::ReadEnv(env, prefix, print) ? kTRUE : rc;
+
+}
+
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSlidingWindow.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSlidingWindow.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSlidingWindow.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MExtractTimeAndChargeSlidingWindow
+#define MARS_MExtractTimeAndChargeSlidingWindow
+
+#ifndef MARS_MExtractTimeAndCharge
+#include "MExtractTimeAndCharge.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MPedestalPix;
+class MExtractTimeAndChargeSlidingWindow : public MExtractTimeAndCharge
+{
+
+private:
+  
+  static const Byte_t fgHiGainFirst;      //! Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t fgHiGainLast;       //! Default for fHiGainLast   (now set to: 14)
+  static const Byte_t fgLoGainFirst;      //! Default for fLOGainFirst  (now set to: 2)
+  static const Byte_t fgLoGainLast;       //! Default for fLoGainLast   (now set to: 14)
+  static const Byte_t fgHiGainWindowSize; //! The extraction window Hi-Gain
+  static const Byte_t fgLoGainWindowSize; //! The extraction window Lo-Gain
+
+  Float_t fHiGainWindowSizeSqrt;         // Square root of number of gains in window
+  Float_t fLoGainWindowSizeSqrt;         // Square root of number of gains in window
+  
+  MArrayF fHiGainSignal;                 //! Need fast access to the signals in a float way
+  MArrayF fLoGainSignal;                 //! Store them in separate arrays
+
+  Bool_t  InitArrays();
+  
+  Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MExtractTimeAndChargeSlidingWindow(const char *name=NULL, const char *title=NULL);
+  ~MExtractTimeAndChargeSlidingWindow() {}
+
+  void SetRange    ( Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0 );  
+  void SetWindowSize(Int_t windowh=fgHiGainWindowSize,
+                     Int_t windowl=fgLoGainWindowSize);
+
+  void FindTimeAndChargeHiGain(Byte_t *first, Byte_t *logain, Float_t &sum, Float_t &dsum,
+                               Float_t &time, Float_t &dtime,
+                               Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+  void FindTimeAndChargeLoGain(Byte_t *first, Float_t &sum,  Float_t &dsum,
+                               Float_t &time, Float_t &dtime,
+                               Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+
+  ClassDef(MExtractTimeAndChargeSlidingWindow, 0)   // Task to Extract Times and Charges using a Sliding Window
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSpline.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSpline.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSpline.cc	(revision 9772)
@@ -0,0 +1,1228 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug       09/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeAndChargeSpline
+//
+//   Fast Spline extractor using a cubic spline algorithm, adapted from 
+//   Numerical Recipes in C++, 2nd edition, pp. 116-119.
+//   
+//   The coefficients "ya" are here denoted as "fHiGainSignal" and "fLoGainSignal"
+//   which means the FADC value subtracted by the clock-noise corrected pedestal.
+//
+//   The coefficients "y2a" get immediately divided 6. and are called here 
+//   "fHiGainSecondDeriv" and "fLoGainSecondDeriv" although they are now not exactly 
+//   the second derivative coefficients any more. 
+// 
+//   The calculation of the cubic-spline interpolated value "y" on a point 
+//   "x" along the FADC-slices axis becomes:
+// 
+//   y =    a*fHiGainSignal[klo] + b*fHiGainSignal[khi] 
+//       + (a*a*a-a)*fHiGainSecondDeriv[klo] + (b*b*b-b)*fHiGainSecondDeriv[khi]
+//
+//   with:
+//   a = (khi - x)
+//   b = (x - klo)
+//
+//   and "klo" being the lower bin edge FADC index and "khi" the upper bin edge FADC index.
+//   fHiGainSignal[klo] and fHiGainSignal[khi] are the FADC values at "klo" and "khi".
+//
+//   An analogues formula is used for the low-gain values.
+//
+//   The coefficients fHiGainSecondDeriv and fLoGainSecondDeriv are calculated with the 
+//   following simplified algorithm:
+//
+//   for (Int_t i=1;i<range-1;i++) {
+//       pp                   = fHiGainSecondDeriv[i-1] + 4.;
+//       fHiGainFirstDeriv[i] = fHiGainSignal[i+1] - 2.*fHiGainSignal[i] + fHiGainSignal[i-1]
+//       fHiGainFirstDeriv[i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+//   }
+// 
+//   for (Int_t k=range-2;k>=0;k--)
+//       fHiGainSecondDeriv[k] = (fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k])/6.;
+// 
+//
+//   This algorithm takes advantage of the fact that the x-values are all separated by exactly 1
+//   which simplifies the Numerical Recipes algorithm.
+//   (Note that the variables "fHiGainFirstDeriv" are not real first derivative coefficients.)
+//
+//   The algorithm to search the time proceeds as follows:
+//
+//   1) Calculate all fHiGainSignal from fHiGainFirst to fHiGainLast 
+//      (note that an "overlap" to the low-gain arrays is possible: i.e. fHiGainLast>14 in the case of 
+//      the MAGIC FADCs).
+//   2) Remember the position of the slice with the highest content "fAbMax" at "fAbMaxPos".
+//   3) If one or more slices are saturated or fAbMaxPos is less than 2 slices from fHiGainFirst, 
+//      return fAbMaxPos as time and fAbMax as charge (note that the pedestal is subtracted here).
+//   4) Calculate all fHiGainSecondDeriv from the fHiGainSignal array
+//   5) Search for the maximum, starting in interval fAbMaxPos-1 in steps of 0.2 till fAbMaxPos-0.2.
+//      If no maximum is found, go to interval fAbMaxPos+1. 
+//      --> 4 function evaluations
+//   6) Search for the absolute maximum from fAbMaxPos to fAbMaxPos+1 in steps of 0.2 
+//      --> 4 function  evaluations
+//   7) Try a better precision searching from new max. position fAbMaxPos-0.2 to fAbMaxPos+0.2
+//      in steps of 0.025 (83 psec. in the case of the MAGIC FADCs).
+//      --> 14 function evaluations
+//   8) If Time Extraction Type kMaximum has been chosen, the position of the found maximum is 
+//      returned, else:
+//   9) The Half Maximum is calculated. 
+//  10) fHiGainSignal is called beginning from fAbMaxPos-1 backwards until a value smaller than fHalfMax
+//      is found at "klo". 
+//  11) Then, the spline value between "klo" and "klo"+1 is halfed by means of bisection as long as 
+//      the difference between fHalfMax and spline evaluation is less than fResolution (default: 0.01).
+//      --> maximum 12 interations.
+//   
+//  The algorithm to search the charge proceeds as follows:
+//
+//  1) If Charge Type: kAmplitude was chosen, return the Maximum of the spline, found during the 
+//     time search.
+//  2) If Charge Type: kIntegral was chosen, sum the fHiGainSignal between:
+//     (Int_t)(fAbMaxPos - fRiseTimeHiGain) and 
+//     (Int_t)(fAbMaxPos + fFallTimeHiGain)
+//     (default: fRiseTime: 1.5, fFallTime: 4.5)
+//                                           sum the fLoGainSignal between:
+//     (Int_t)(fAbMaxPos - fRiseTimeHiGain*fLoGainStretch) and 
+//     (Int_t)(fAbMaxPos + fFallTimeHiGain*fLoGainStretch)
+//     (default: fLoGainStretch: 1.5)
+//       
+//  The values: fNumHiGainSamples and fNumLoGainSamples are set to:
+//  1) If Charge Type: kAmplitude was chosen: 1.
+//  2) If Charge Type: kIntegral was chosen: fRiseTimeHiGain + fFallTimeHiGain
+//                 or: fNumHiGainSamples*fLoGainStretch in the case of the low-gain
+//
+//  Call: SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast) 
+//        to modify the ranges.
+// 
+//        Defaults: 
+//        fHiGainFirst =  2 
+//        fHiGainLast  =  14
+//        fLoGainFirst =  2 
+//        fLoGainLast  =  14
+//
+//  Call: SetResolution() to define the resolution of the half-maximum search.
+//        Default: 0.01
+//
+//  Call: SetRiseTime() and SetFallTime() to define the integration ranges 
+//        for the case, the extraction type kIntegral has been chosen.
+//
+//  Call: - SetChargeType(MExtractTimeAndChargeSpline::kAmplitude) for the 
+//          computation of the amplitude at the maximum (default) and extraction 
+//          the position of the maximum (default)
+//          --> no further function evaluation needed
+//        - SetChargeType(MExtractTimeAndChargeSpline::kIntegral) for the 
+//          computation of the integral beneith the spline between fRiseTimeHiGain
+//          from the position of the maximum to fFallTimeHiGain after the position of 
+//          the maximum. The Low Gain is computed with half a slice more at the rising
+//          edge and half a slice more at the falling edge.
+//          The time of the half maximum is returned.
+//          --> needs one function evaluations but is more precise
+//        
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeAndChargeSpline.h"
+
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractTimeAndChargeSpline);
+
+using namespace std;
+
+const Byte_t  MExtractTimeAndChargeSpline::fgHiGainFirst      = 2;
+const Byte_t  MExtractTimeAndChargeSpline::fgHiGainLast       = 14;
+const Byte_t  MExtractTimeAndChargeSpline::fgLoGainFirst      = 1;
+const Byte_t  MExtractTimeAndChargeSpline::fgLoGainLast       = 14;
+const Float_t MExtractTimeAndChargeSpline::fgResolution       = 0.05;
+const Float_t MExtractTimeAndChargeSpline::fgRiseTimeHiGain   = 0.5;
+const Float_t MExtractTimeAndChargeSpline::fgFallTimeHiGain   = 1.5;
+const Float_t MExtractTimeAndChargeSpline::fgLoGainStretch    = 1.5;
+const Float_t MExtractTimeAndChargeSpline::fgOffsetLoGain     = 1.7;  // 5 ns
+const Float_t MExtractTimeAndChargeSpline::fgLoGainStartShift = -1.8;  
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+// Initializes:
+// - fResolution     to fgResolution
+// - fRiseTimeHiGain to fgRiseTimeHiGain
+// - fFallTimeHiGain to fgFallTimeHiGain
+// - Charge Extraction Type to kAmplitude
+// - fLoGainStretch  to fgLoGainStretch
+//
+MExtractTimeAndChargeSpline::MExtractTimeAndChargeSpline(const char *name, const char *title) 
+    : fAbMax(0.), fAbMaxPos(0.), fHalfMax(0.), 
+      fRandomIter(0), fExtractionType(kIntegral)
+{
+
+  fName  = name  ? name  : "MExtractTimeAndChargeSpline";
+  fTitle = title ? title : "Calculate photons arrival time using a fast spline";
+
+  SetResolution();
+  SetLoGainStretch();
+  SetOffsetLoGain(fgOffsetLoGain);
+  SetLoGainStartShift(fgLoGainStartShift);
+
+  SetRiseTimeHiGain();
+  SetFallTimeHiGain();
+
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+
+//-------------------------------------------------------------------
+//
+// Set the ranges
+// In order to set the fNum...Samples variables correctly for the case, 
+// the integral is computed, have to overwrite this function and make an 
+// explicit call to SetChargeType().
+//
+void MExtractTimeAndChargeSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst, hilast, lofirst, lolast);
+
+  SetChargeType(fExtractionType);
+}
+
+//-------------------------------------------------------------------
+//
+// Set the Charge Extraction type. Possible are:
+// - kAmplitude: Search the value of the spline at the maximum
+// - kIntegral:  Integral the spline from fHiGainFirst to fHiGainLast,   
+//               by counting the edge bins only half and setting the 
+//               second derivative to zero, there.
+//
+void MExtractTimeAndChargeSpline::SetChargeType( ExtractionType_t typ )
+{
+
+  fExtractionType = typ;
+
+  if (fExtractionType == kAmplitude)
+    {
+      fNumHiGainSamples = 1.;
+      fNumLoGainSamples = fLoGainLast ? 1. : 0.; 
+      fSqrtHiGainSamples = 1.;
+      fSqrtLoGainSamples = 1.;
+      fWindowSizeHiGain  = 1;
+      fWindowSizeLoGain  = 1;
+      fRiseTimeHiGain    = 0.5;
+      
+      return;
+    }
+
+  if (fExtractionType == kIntegral)
+    {
+
+      fNumHiGainSamples  = fRiseTimeHiGain + fFallTimeHiGain;
+      fNumLoGainSamples  = fLoGainLast ? fRiseTimeLoGain + fFallTimeLoGain : 0.;
+      //      fNumLoGainSamples  *= 0.75;      
+
+      fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+      fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+      fWindowSizeHiGain  = (Int_t)(fRiseTimeHiGain + fFallTimeHiGain);
+      fWindowSizeLoGain  = (Int_t)((fRiseTimeLoGain + fFallTimeLoGain)*fLoGainStretch);
+      //      fNumLoGainSamples  *= 0.75;      
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// InitArrays
+//
+// Gets called in the ReInit() and initialized the arrays
+//
+Bool_t MExtractTimeAndChargeSpline::InitArrays()
+{
+
+  Int_t range = fHiGainLast - fHiGainFirst + 1 + fHiLoLast;
+
+  fHiGainSignal     .Set(range);
+  fHiGainFirstDeriv .Set(range);
+  fHiGainSecondDeriv.Set(range);
+
+  range = fLoGainLast - fLoGainFirst + 1;
+
+  fLoGainSignal     .Set(range);
+  fLoGainFirstDeriv .Set(range);
+  fLoGainSecondDeriv.Set(range);
+
+  fHiGainSignal     .Reset();
+  fHiGainFirstDeriv .Reset();
+  fHiGainSecondDeriv.Reset();
+
+  fLoGainSignal     .Reset();
+  fLoGainFirstDeriv .Reset();
+  fLoGainSecondDeriv.Reset();
+  
+  if (fExtractionType == kAmplitude)
+    {
+      fNumHiGainSamples = 1.;
+      fNumLoGainSamples = fLoGainLast ? 1. : 0.; 
+      fSqrtHiGainSamples = 1.;
+      fSqrtLoGainSamples = 1.;
+      fWindowSizeHiGain  = 1;
+      fWindowSizeLoGain  = 1;
+      fRiseTimeHiGain    = 0.5;
+    }
+
+  fRiseTimeLoGain    = fRiseTimeHiGain * fLoGainStretch;
+  fFallTimeLoGain    = fFallTimeHiGain * fLoGainStretch;      
+
+  if (fExtractionType == kIntegral)
+    {
+
+      fNumHiGainSamples  = fRiseTimeHiGain + fFallTimeHiGain;
+      fNumLoGainSamples  = fLoGainLast ? fRiseTimeLoGain + fFallTimeLoGain : 0.;
+      //      fNumLoGainSamples  *= 0.75;      
+
+      fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+      fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+      fWindowSizeHiGain  = (Int_t)(fRiseTimeHiGain + fFallTimeHiGain);
+      fWindowSizeLoGain  = (Int_t)(fRiseTimeLoGain + fFallTimeLoGain);
+    }
+
+  return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time and charge for each pixel 
+//
+void MExtractTimeAndChargeSpline::FindTimeAndChargeHiGain(Byte_t *first, Byte_t *logain, Float_t &sum, Float_t &dsum, 
+                                                          Float_t &time, Float_t &dtime, 
+                                                          Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag)
+{
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t       *p  = first;
+
+  sat = 0;
+
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t ABoffs = ped.GetPedestalABoffset();
+
+  const Float_t pedmean[2] = { pedes + ABoffs, pedes - ABoffs };
+
+  fAbMax         = 0.;
+  fAbMaxPos      = 0.;
+  fHalfMax       = 0.;
+  fMaxBinContent = 0;
+  Int_t  maxpos  = 0;
+
+  //
+  // Check for saturation in all other slices
+  //
+  Int_t ids = fHiGainFirst;
+  Float_t *sample = fHiGainSignal.GetArray();
+  while (p<end)
+    {
+
+      *sample++ = (Float_t)*p - pedmean[(ids++ + abflag) & 0x1];
+
+      if (*p > fMaxBinContent)
+        {
+          maxpos = ids-fHiGainFirst-1;
+          fMaxBinContent = *p;
+        }
+
+      if (*p++ >= fSaturationLimit)
+        if (!sat)
+          sat = ids-3;
+      
+    }
+  
+  if (fHiLoLast != 0)
+    {
+
+      end = logain + fHiLoLast;
+
+      while (logain<end)
+        {
+
+          *sample++ = (Float_t)*logain - pedmean[(ids++ + abflag) & 0x1];
+
+          if (*logain > fMaxBinContent)
+            { 
+              maxpos = ids-fHiGainFirst-1;
+              fMaxBinContent = *logain;
+            }
+          
+          if (*logain++ >= fSaturationLimit)
+            if (!sat)
+              sat = ids-3;
+
+          range++;
+        }
+    }
+  
+  fAbMax = fHiGainSignal[maxpos];
+
+  Float_t pp;
+
+  fHiGainSecondDeriv[0] = 0.;
+  fHiGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      pp = fHiGainSecondDeriv[i-1] + 4.;
+      fHiGainSecondDeriv[i] = -1.0/pp;
+      fHiGainFirstDeriv [i] = fHiGainSignal[i+1] - fHiGainSignal[i] - fHiGainSignal[i] + fHiGainSignal[i-1];
+      fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+    }
+
+  fHiGainSecondDeriv[range-1] = 0.;
+
+  for (Int_t k=range-2;k>=0;k--)
+    fHiGainSecondDeriv[k] = fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k];
+  for (Int_t k=range-2;k>=0;k--)
+    fHiGainSecondDeriv[k] /= 6.;
+  
+  if (IsNoiseCalculation())
+    {
+
+      if (fRandomIter == int(1./fResolution))
+        fRandomIter = 0;
+      
+      const Float_t nsx = fRandomIter * fResolution;
+
+      if (fExtractionType == kAmplitude)
+        {
+          const Float_t b = nsx;
+          const Float_t a = 1. - nsx;
+          
+          sum = a*fHiGainSignal[1]
+            + b*fHiGainSignal[2]
+            + (a*a*a-a)*fHiGainSecondDeriv[1] 
+            + (b*b*b-b)*fHiGainSecondDeriv[2];
+        }
+      else
+        {
+          Float_t start = 2. + nsx;
+          Float_t last  = start + fRiseTimeHiGain + fFallTimeHiGain;
+      
+          if (int(last) > range)
+            {
+              const Int_t diff = range - int(last);
+              last  -= diff;
+              start -= diff;
+            }
+          
+          CalcIntegralHiGain(sum, start, last);
+        }
+      fRandomIter++;
+      return;
+    }
+
+  //
+  // Allow no saturated slice 
+  // and 
+  // Don't start if the maxpos is too close to the limits.
+  //
+  if (sat || maxpos < TMath::Ceil(fRiseTimeHiGain) || maxpos > range-2)
+    {
+
+      dtime = 1.0;
+      if (fExtractionType == kAmplitude)
+        {
+          sum  = fAbMax;
+          time = (Float_t)(fHiGainFirst + maxpos);
+          return;
+        }
+      
+      if (maxpos > range - 2)
+        CalcIntegralHiGain(sum, (Float_t)range - fRiseTimeHiGain - fFallTimeHiGain, (Float_t)range - 0.001);
+      else
+        CalcIntegralHiGain(sum, 0.001, fRiseTimeHiGain + fFallTimeHiGain);
+
+      time =  (Float_t)(fHiGainFirst + maxpos - 1);
+      return;
+    }
+      
+  dtime = fResolution;
+
+  //
+  // Now find the maximum  
+  //
+  Float_t step    = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower   = -1. + maxpos;
+  Float_t upper   = (Float_t)maxpos;
+  fAbMaxPos       = upper;
+  Float_t x       = lower;
+  Float_t y       = 0.;
+  Float_t a       = 1.;
+  Float_t b       = 0.;
+  Int_t   klo     = maxpos-1;
+  Int_t   khi     = maxpos;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1 in steps of 0.2 till maxpos-0.2.
+  // If no maximum is found, go to interval maxpos+1.
+  //
+  while ( x < upper - 0.3 )
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*fHiGainSignal[klo]
+        + b*fHiGainSignal[khi]
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+
+      if (y > fAbMax)
+        {
+          fAbMax    = y;
+          fAbMaxPos = x;
+        }
+
+    }
+
+  //
+  // Search for the absolute maximum from maxpos to maxpos+1 in steps of 0.2
+  //
+  if (fAbMaxPos > upper-0.1)
+    {
+
+      upper   = 1. + maxpos;
+      lower   = (Float_t)maxpos;
+      x       = lower;
+      a       = 1.;
+      b       = 0.;
+      khi     = maxpos+1;
+      klo     = maxpos;
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a*fHiGainSignal[klo]
+            + b*fHiGainSignal[khi]
+            + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+            + (b*b*b-b)*fHiGainSecondDeriv[khi];
+
+          if (y > fAbMax)
+            {
+              fAbMax    = y;
+              fAbMaxPos = x;
+            }
+        }
+  }
+  //
+  // Now, the time, abmax and khicont and klocont are set correctly within the previous precision.
+  // Try a better precision. 
+  //
+  const Float_t up = fAbMaxPos+step - 3.0*fResolution;
+  const Float_t lo = fAbMaxPos-step + 3.0*fResolution;
+  const Float_t maxpossave = fAbMaxPos;
+  
+  x     = fAbMaxPos;
+  a     = upper - x;
+  b     = x - lower;
+ 
+  step  = 2.*fResolution; // step size of 0.1 FADC slices
+ 
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a*fHiGainSignal[klo]
+        + b*fHiGainSignal[khi]
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > fAbMax)
+        {
+          fAbMax    = y;
+          fAbMaxPos = x;
+        }
+    }
+
+  //
+  // Second, try from time down to time-0.2 in steps of fResolution.
+  //
+  x     = maxpossave;
+
+  //
+  // Test the possibility that the absolute maximum has not been found between
+  // maxpos and maxpos+0.05, then we have to look between maxpos-0.05 and maxpos
+  // which requires new setting of klocont and khicont
+  //
+  if (x < lower + fResolution)
+    {
+      klo--;
+      khi--;
+      upper -= 1.;
+      lower -= 1.;
+    }
+
+  a     = upper - x;
+  b     = x - lower;
+  
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a*fHiGainSignal[klo]
+        + b*fHiGainSignal[khi]
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > fAbMax)
+        {
+          fAbMax    = y;
+          fAbMaxPos = x;
+        }
+    }
+
+  if (fExtractionType == kAmplitude)
+    {
+      time  = fAbMaxPos + (Int_t)fHiGainFirst;
+      sum   = fAbMax;
+      return;
+    }
+
+  fHalfMax = fAbMax/2.;
+  
+  //
+  // Now, loop from the maximum bin leftward down in order to find the position of the half maximum.
+  // First, find the right FADC slice:
+  // 
+  klo  = maxpos;
+  while (klo > 0)
+    {
+      klo--;
+      if (fHiGainSignal[klo] < fHalfMax)
+        break;
+    }
+  
+  khi = klo+1;
+  //
+  // Loop from the beginning of the slice upwards to reach the fHalfMax:
+  // With means of bisection:
+  // 
+  x     = (Float_t)klo;
+  a     = 1.;
+  b     = 0.;
+  
+  step = 0.5;
+  Bool_t back = kFALSE;
+  
+  Int_t maxcnt = 20;
+  Int_t cnt    = 0;
+  
+  while (TMath::Abs(y-fHalfMax) > fResolution)
+    {
+      
+      if (back)
+        {
+          x -= step;
+          a += step;
+          b -= step;
+        }
+      else
+        {
+          x += step;
+          a -= step;
+          b += step;
+        }
+      
+      y = a*fHiGainSignal[klo]
+        + b*fHiGainSignal[khi]
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+      
+      if (y > fHalfMax)
+        back = kTRUE;
+      else
+        back = kFALSE;
+      
+      if (++cnt > maxcnt)
+        break;
+      
+      step /= 2.;
+    }
+  
+  time  = (Float_t)fHiGainFirst + x;
+  //
+  // Now integrate the whole thing!
+  // 
+  
+  Float_t start = fAbMaxPos - fRiseTimeHiGain;
+  Float_t last  = fAbMaxPos + fFallTimeHiGain;
+  
+  const Int_t diff = int(last) - range;
+  
+  if (diff > 0)
+    {
+      last  -= diff;
+      start -= diff;
+    }
+  
+  CalcIntegralHiGain(sum, start, last);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time and charge for each pixel 
+//
+void MExtractTimeAndChargeSpline::FindTimeAndChargeLoGain(Byte_t *first, Float_t &sum, Float_t &dsum, 
+                                                          Float_t &time, Float_t &dtime, 
+                                                          Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag) 
+{
+  
+  Int_t range = fLoGainLast - fLoGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t       *p  = first;
+
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t ABoffs = ped.GetPedestalABoffset();
+
+  const Float_t pedmean[2] = { pedes + ABoffs, pedes - ABoffs };
+
+  fAbMax        = 0.;
+  fAbMaxPos     = 0.;
+  Int_t  maxpos = 0;
+  Int_t  max    = -9999;
+
+  //
+  // Check for saturation in all other slices
+  //
+  Int_t    ids    = fLoGainFirst;
+  Float_t *sample = fLoGainSignal.GetArray();
+  while (p<end)
+    {
+
+      *sample++ = (Float_t)*p - pedmean[(ids++ + abflag) & 0x1];
+
+      if (*p > max)
+        {
+          maxpos = ids-fLoGainFirst-1;
+          max    = *p;
+        }
+
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+  
+  fAbMax = fLoGainSignal[maxpos];
+  
+  Float_t pp;
+
+  fLoGainSecondDeriv[0] = 0.;
+  fLoGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      pp = fLoGainSecondDeriv[i-1] + 4.;
+      fLoGainSecondDeriv[i] = -1.0/pp;
+      fLoGainFirstDeriv [i] = fLoGainSignal[i+1] - fLoGainSignal[i] - fLoGainSignal[i] + fLoGainSignal[i-1];
+      fLoGainFirstDeriv [i] = (6.0*fLoGainFirstDeriv[i]-fLoGainFirstDeriv[i-1])/pp;
+    }
+
+  fLoGainSecondDeriv[range-1] = 0.;
+
+  for (Int_t k=range-2;k>=0;k--)
+    fLoGainSecondDeriv[k] = fLoGainSecondDeriv[k]*fLoGainSecondDeriv[k+1] + fLoGainFirstDeriv[k];
+  for (Int_t k=range-2;k>=0;k--)
+    fLoGainSecondDeriv[k] /= 6.;
+  
+  if (IsNoiseCalculation())
+    {
+      if (fRandomIter == int(1./fResolution))
+        fRandomIter = 0;
+      
+      const Float_t nsx = fRandomIter * fResolution;
+
+      if (fExtractionType == kAmplitude)
+        {
+          const Float_t b = nsx;
+          const Float_t a = 1. - nsx;
+          
+          sum = a*fLoGainSignal[1]
+            + b*fLoGainSignal[2]
+            + (a*a*a-a)*fLoGainSecondDeriv[1] 
+            + (b*b*b-b)*fLoGainSecondDeriv[2];
+        }
+      else
+        {
+          Float_t start = 2. + nsx;
+          Float_t last  = start + fRiseTimeLoGain + fFallTimeLoGain;
+      
+          if (int(last) > range)
+            {
+              const Int_t diff = range - int(last);
+              last  -= diff;
+              start -= diff;
+            }
+          
+          CalcIntegralLoGain(sum, start, last);
+        }
+      fRandomIter++;
+      return;
+    }
+  //
+  // Allow no saturated slice 
+  // and 
+  // Don't start if the maxpos is too close to the limits.
+  //
+  if (sat || maxpos < TMath::Ceil(fRiseTimeLoGain) || maxpos > range-2)
+    {
+
+      dtime = 1.0;
+      if (fExtractionType == kAmplitude)
+        {
+          time = (Float_t)(fLoGainFirst + maxpos);
+          sum = fAbMax;
+          return;
+        }
+      
+      if (maxpos > range-2)
+        CalcIntegralLoGain(sum, (Float_t)range - fRiseTimeLoGain - fFallTimeLoGain -1., (Float_t)range - 0.001);
+      else
+        CalcIntegralLoGain(sum, 0.001, fRiseTimeLoGain + fFallTimeLoGain + 1.);
+
+      time = (Float_t)(fLoGainFirst + maxpos - 1);
+      return;
+    }
+
+  dtime = fResolution;
+
+  //
+  // Now find the maximum  
+  //
+  Float_t step    = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower   = -1. + maxpos;
+  Float_t upper   = (Float_t)maxpos;
+  fAbMaxPos       = upper;
+  Float_t x       = lower;
+  Float_t y       = 0.;
+  Float_t a       = 1.;
+  Float_t b       = 0.;
+  Int_t   klo     = maxpos-1;
+  Int_t   khi     = maxpos;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1 in steps of 0.2 till maxpos-0.2.
+  // If no maximum is found, go to interval maxpos+1.
+  //
+  while ( x < upper - 0.3 )
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*fLoGainSignal[klo]
+        + b*fLoGainSignal[khi]
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+
+      if (y > fAbMax)
+        {
+          fAbMax    = y;
+          fAbMaxPos = x;
+        }
+
+    }
+
+  //
+  // Test the possibility that the absolute maximum has not been found before the 
+  // maxpos and search from maxpos to maxpos+1 in steps of 0.2
+  //
+  if (fAbMaxPos > upper-0.1)
+    {
+
+      upper   = 1. + maxpos;
+      lower   = (Float_t)maxpos;
+      x       = lower;
+      a       = 1.;
+      b       = 0.;
+      khi     = maxpos+1;
+      klo     = maxpos;
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a*fLoGainSignal[klo]
+            + b*fLoGainSignal[khi]
+            + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+            + (b*b*b-b)*fLoGainSecondDeriv[khi];
+
+          if (y > fAbMax)
+            {
+              fAbMax    = y;
+              fAbMaxPos = x;
+            }
+        }
+  }
+
+
+  //
+  // Now, the time, abmax and khicont and klocont are set correctly within the previous precision.
+  // Try a better precision. 
+  //
+  const Float_t up = fAbMaxPos+step - 3.0*fResolution;
+  const Float_t lo = fAbMaxPos-step + 3.0*fResolution;
+  const Float_t maxpossave = fAbMaxPos;
+  
+  x     = fAbMaxPos;
+  a     = upper - x;
+  b     = x - lower;
+ 
+  step  = 2.*fResolution; // step size of 0.1 FADC slice
+ 
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a*fLoGainSignal[klo]
+        + b*fLoGainSignal[khi]
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > fAbMax)
+        {
+          fAbMax    = y;
+          fAbMaxPos = x;
+        }
+    }
+
+  //
+  // Second, try from time down to time-0.2 in steps of 0.025.
+  //
+  x     = maxpossave;
+
+  //
+  // Test the possibility that the absolute maximum has not been found between
+  // maxpos and maxpos+0.05, then we have to look between maxpos-0.05 and maxpos
+  // which requires new setting of klocont and khicont
+  //
+  if (x < lower + fResolution)
+    {
+      klo--;
+      khi--;
+      upper -= 1.;
+      lower -= 1.;
+    }
+
+  a     = upper - x;
+  b     = x - lower;
+  
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a*fLoGainSignal[klo]
+        + b*fLoGainSignal[khi]
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > fAbMax)
+        {
+          fAbMax    = y;
+          fAbMaxPos = x;
+        }
+    }
+
+  if (fExtractionType == kAmplitude)
+    {
+      time = fAbMaxPos + (Int_t)fLoGainFirst;
+      sum  = fAbMax;
+      return;
+    }
+  
+  fHalfMax = fAbMax/2.;
+  
+  //
+  // Now, loop from the maximum bin leftward down in order to find the position of the half maximum.
+  // First, find the right FADC slice:
+  // 
+  klo  = maxpos;
+  while (klo > 0)
+    {
+      klo--;
+      if (fLoGainSignal[klo] < fHalfMax)
+        break;
+    }
+  
+  khi = klo+1;
+  //
+  // Loop from the beginning of the slice upwards to reach the fHalfMax:
+  // With means of bisection:
+  // 
+  x     = (Float_t)klo;
+  a     = 1.;
+  b     = 0.;
+  
+  step = 0.5;
+  Bool_t back = kFALSE;
+  
+  Int_t maxcnt = 20;
+  Int_t cnt    = 0;
+  
+  while (TMath::Abs(y-fHalfMax) > fResolution)
+    {
+      
+      if (back)
+        {
+          x -= step;
+          a += step;
+          b -= step;
+        }
+      else
+        {
+          x += step;
+          a -= step;
+          b += step;
+        }
+      
+      y = a*fLoGainSignal[klo]
+        + b*fLoGainSignal[khi]
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > fHalfMax)
+        back = kTRUE;
+      else
+        back = kFALSE;
+      
+      if (++cnt > maxcnt)
+        break;
+      
+      step /= 2.;
+    }
+  
+  time  = x + (Int_t)fLoGainFirst;
+
+  //
+  // Now integrate the whole thing!
+  // 
+  Float_t start = fAbMaxPos - fRiseTimeLoGain;
+  Float_t last  = fAbMaxPos + fFallTimeLoGain;
+  
+  const Int_t diff = int(last) - range;
+  
+  if (diff > 0)
+    {
+      last  -= diff;
+      start -= diff;
+    }
+  CalcIntegralLoGain(sum, start, last);
+}
+
+void MExtractTimeAndChargeSpline::CalcIntegralHiGain(Float_t &sum, Float_t start, Float_t last)
+{
+
+  const Float_t step = 0.2;
+
+  if (start < 0)
+    {
+      last -= start;
+      start = 0.;
+    }
+  
+  Int_t klo = int(start);
+  Int_t khi = klo+1;
+
+  Float_t lo = TMath::Floor(start);
+  Float_t up = lo + 1.;
+
+  const Int_t m = int((start-klo)/step);
+  start = step*m + klo; // Correct start for the digitization due to resolution
+
+  Float_t x = start;
+  Float_t a = up-start;
+  Float_t b = start-lo;
+
+  while (1)
+    {
+      
+      while (x<up)
+        {
+          x += step;
+
+          if (x > last)
+            {
+              sum *= step;
+              return;
+            }
+          
+          a -= step;
+          b += step;
+          
+          sum += a*fHiGainSignal[klo]
+          + b*fHiGainSignal[khi]
+            + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+            + (b*b*b-b)*fHiGainSecondDeriv[khi];
+        }
+
+      up += 1.;
+      lo += 1.;
+      klo++;
+      khi++;
+      start += 1.;
+      a = 1.;
+      b = 0.;
+    }
+  
+}
+void MExtractTimeAndChargeSpline::CalcIntegralLoGain(Float_t &sum, Float_t start, Float_t last)
+{
+
+  const Float_t step = 0.1;
+
+  if (start < 0)
+    {
+      last -= start;
+      start = 0.;
+    }
+  
+  Int_t klo = int(start);
+  Int_t khi = klo+1;
+
+  Float_t lo = TMath::Floor(start);
+  Float_t up = lo + 1.;
+
+  const Int_t m = int((start-klo)/step);
+  start = step*m + klo; // Correct start for the digitization due to resolution
+
+  Float_t x = start;
+  Float_t a = up-start;
+  Float_t b = start-lo;
+
+  while (1)
+    {
+      
+      while (x<up)
+        {
+          x += step;
+          
+          if (x > last)
+            {
+              sum *= step;
+              return;
+            }
+          
+          a -= step;
+          b += step;
+          
+          sum += a*fLoGainSignal[klo]
+          + b*fLoGainSignal[khi]
+            + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+            + (b*b*b-b)*fLoGainSecondDeriv[khi];
+          
+        }
+
+      up += 1.;
+      lo += 1.;
+      klo++;
+      khi++;
+      start += 1.;
+      a = 1.;
+      b = 0.;
+    }
+  
+}
+
+
+
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   Resolution
+//   RiseTimeHiGain
+//   FallTimeHiGain
+//   LoGainStretch
+//   ExtractionType: amplitude, integral
+//
+Int_t MExtractTimeAndChargeSpline::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+
+  Bool_t rc = kFALSE;
+  
+  if (IsEnvDefined(env, prefix, "Resolution", print))
+    {
+      SetResolution(GetEnvValue(env, prefix, "Resolution",fResolution));
+      rc  = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "RiseTimeHiGain", print))
+    {
+      SetRiseTimeHiGain(GetEnvValue(env, prefix, "RiseTimeHiGain", fRiseTimeHiGain));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "FallTimeHiGain", print))
+    {
+      SetFallTimeHiGain(GetEnvValue(env, prefix, "FallTimeHiGain", fFallTimeHiGain));
+      rc = kTRUE;
+    }
+  if (IsEnvDefined(env, prefix, "LoGainStretch", print))
+    {
+      SetLoGainStretch(GetEnvValue(env, prefix, "LoGainStretch", fLoGainStretch));
+      rc = kTRUE;
+    }
+  
+  if (IsEnvDefined(env, prefix, "ExtractionType", print))
+  {
+      TString type = GetEnvValue(env, prefix, "ExtractionType", "");
+      type.ToLower();
+      type = type.Strip(TString::kBoth);
+      if (type==(TString)"amplitude")
+          SetChargeType(kAmplitude);
+      if (type==(TString)"integral")
+          SetChargeType(kIntegral);
+      rc=kTRUE;
+  }
+
+  return MExtractTimeAndCharge::ReadEnv(env, prefix, print) ? kTRUE : rc;
+
+}
+
+
Index: /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSpline.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSpline.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeAndChargeSpline.h	(revision 9772)
@@ -0,0 +1,109 @@
+#ifndef MARS_MExtractTimeAndChargeSpline
+#define MARS_MExtractTimeAndChargeSpline
+
+#ifndef MARS_MExtractTimeAndCharge
+#include "MExtractTimeAndCharge.h"
+#endif
+
+#ifndef MARS_MArrayF
+#include "MArrayF.h"
+#endif
+
+class MPedestalPix;
+class MExtractTimeAndChargeSpline : public MExtractTimeAndCharge
+{
+
+private:
+  
+  static const Byte_t  fgHiGainFirst;      //! Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t  fgHiGainLast;       //! Default for fHiGainLast   (now set to: 14)
+  static const Byte_t  fgLoGainFirst;      //! Default for fLoGainFirst  (now set to: 2)
+  static const Byte_t  fgLoGainLast;       //! Default for fLoGainLast   (now set to: 14)
+  static const Float_t fgResolution;       //! Default for fResolution   (now set to: 0.003)
+  static const Float_t fgRiseTimeHiGain;   //! Default for fRiseTime     (now set to: 1.5)
+  static const Float_t fgFallTimeHiGain;   //! Default for fFallTime     (now set to: 4.5)
+  static const Float_t fgLoGainStretch;    //! Default for fLoGainStretch    (now set to: 1.5)
+  static const Float_t fgOffsetLoGain;     //! Default for fOffsetLoGain     (now set to 1.7)
+  static const Float_t fgLoGainStartShift; //! Default for fLoGainStartShift (now set to -1.6)
+  
+  MArrayF fHiGainSignal;                //! Need fast access to the signals in a float way
+  MArrayF fLoGainSignal;                //! Store them in separate arrays
+  MArrayF fHiGainFirstDeriv;            //! High-gain discretized first derivatives
+  MArrayF fLoGainFirstDeriv;            //! Low-gain discretized first derivatives
+  MArrayF fHiGainSecondDeriv;           //! High-gain discretized second derivatives
+  MArrayF fLoGainSecondDeriv;           //! Low-gain discretized second derivatives
+
+  Float_t fAbMax;                       //! Current maximum of the spline
+  Float_t fAbMaxPos;                    //! Current position of the maximum of the spline
+  Float_t fHalfMax;                     //! Current half maximum of the spline
+
+  Float_t fResolution;                  // The time resolution in FADC units
+
+  Float_t fRiseTimeHiGain;              // The usual rise time of the pulse in the high-gain
+  Float_t fFallTimeHiGain;              // The usual fall time of the pulse in the high-gain
+  Float_t fRiseTimeLoGain;              // The usual rise time of the pulse in the low-gain
+  Float_t fFallTimeLoGain;              // The usual fall time of the pulse in the low-gain
+
+  Float_t fLoGainStretch;               // The stretch of the low-gain w.r.t. the high-gain pulse
+
+  Int_t   fRandomIter;                  //! Counter used to randomize weights for noise calculation
+  
+  Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+  Bool_t  InitArrays();
+  
+  void CalcIntegralHiGain(Float_t &sum, Float_t start, Float_t last);
+  void CalcIntegralLoGain(Float_t &sum, Float_t start, Float_t last);
+
+public:  
+  enum ExtractionType_t { kAmplitude, kIntegral };    //! Possible time and charge extraction types
+
+private:
+  
+  ExtractionType_t fExtractionType;
+
+public:
+
+  MExtractTimeAndChargeSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractTimeAndChargeSpline() {}
+
+  Float_t GetRiseTimeHiGain() const { return fRiseTimeHiGain; }
+  Float_t GetFallTimeHiGain() const { return fFallTimeHiGain; }
+
+  void SetRange      ( Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0 );  
+  void SetResolution ( const Float_t f=fgResolution  )  { fResolution  = f;  }
+  void SetRiseTimeHiGain( const Float_t f=fgRiseTimeHiGain    )
+    {
+      fRiseTimeHiGain    = f;
+      fRiseTimeLoGain    = f*fLoGainStretch;
+      fSqrtHiGainSamples = TMath::Sqrt(fNumHiGainSamples);
+      fWindowSizeHiGain  = (Int_t)(fRiseTimeHiGain + fFallTimeHiGain);
+    }
+  void SetFallTimeHiGain( const Float_t f=fgFallTimeHiGain    )
+    {
+      fFallTimeHiGain    = f;
+      fFallTimeLoGain    = f*fLoGainStretch;
+      fNumHiGainSamples  = fRiseTimeHiGain + fFallTimeHiGain;
+      fNumLoGainSamples  = fLoGainLast ? fRiseTimeLoGain + fFallTimeLoGain : 0.;
+      fSqrtLoGainSamples = TMath::Sqrt(fNumLoGainSamples);
+      fWindowSizeLoGain  = (Int_t)(fRiseTimeLoGain + fFallTimeLoGain);
+    }
+
+  void SetLoGainStretch ( const Float_t f=fgLoGainStretch    )  { fLoGainStretch = f;   }
+  
+  void SetChargeType ( const ExtractionType_t typ=kIntegral);
+  
+  void FindTimeAndChargeHiGain(Byte_t *first, Byte_t *logain, Float_t &sum, Float_t &dsum,
+                               Float_t &time, Float_t &dtime,
+                               Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+  void FindTimeAndChargeLoGain(Byte_t *first, Float_t &sum,  Float_t &dsum,
+                               Float_t &time, Float_t &dtime,
+                               Byte_t &sat, const MPedestalPix &ped, const Bool_t abflag);
+
+  ClassDef(MExtractTimeAndChargeSpline, 4)   // Task to Extract Arrival Times and Charges using a Cubic Spline
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/msignal/MExtractTimeFastSpline.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeFastSpline.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeFastSpline.cc	(revision 9772)
@@ -0,0 +1,744 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Markus Gaug       05/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeFastSpline
+//
+//   Fast arrival Time extractor using a cubic spline algorithm of Numerical Recipes. 
+//   It returns the position of the half maximum between absolute maximum 
+//   and pedestal of the spline that interpolates the FADC slices.
+//
+//   The precision of the half-maximum searches can be chosen by:
+//   SetPrecision().
+//
+//   The precision of the maximum-finder is fixed to 0.025 FADC units.
+// 
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeFastSpline.h"
+
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MExtractTimeFastSpline);
+
+using namespace std;
+
+const Byte_t  MExtractTimeFastSpline::fgHiGainFirst  = 2;
+const Byte_t  MExtractTimeFastSpline::fgHiGainLast   = 14;
+const Byte_t  MExtractTimeFastSpline::fgLoGainFirst  = 3;
+const Byte_t  MExtractTimeFastSpline::fgLoGainLast   = 14;
+const Float_t MExtractTimeFastSpline::fgResolution   = 0.003;
+const Float_t MExtractTimeFastSpline::fgRiseTime     = 2.;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+// 
+// Initializes:
+// - fResolution to fgResolution
+//
+MExtractTimeFastSpline::MExtractTimeFastSpline(const char *name, const char *title) 
+    : fHiGainFirstDeriv(NULL), fLoGainFirstDeriv(NULL),
+      fHiGainSecondDeriv(NULL), fLoGainSecondDeriv(NULL)
+{
+
+  fName  = name  ? name  : "MExtractTimeFastSpline";
+  fTitle = title ? title : "Calculate photons arrival time using a fast spline";
+
+  SetResolution();
+  SetRiseTime  ();
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+
+}
+
+MExtractTimeFastSpline::~MExtractTimeFastSpline()
+{
+  
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fLoGainFirstDeriv)
+    delete [] fLoGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+  if (fLoGainSecondDeriv)
+    delete [] fLoGainSecondDeriv;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - Deletes x, if not NULL
+// - Creates x according to the range
+//
+void MExtractTimeFastSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  if (fHiGainFirstDeriv)
+    delete [] fHiGainFirstDeriv;
+  if (fLoGainFirstDeriv)
+    delete [] fLoGainFirstDeriv;
+  if (fHiGainSecondDeriv)
+    delete [] fHiGainSecondDeriv;
+  if (fLoGainSecondDeriv)
+    delete [] fLoGainSecondDeriv;
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+
+  if (range < 2)
+    {
+      *fLog << warn << GetDescriptor()
+            << Form("%s%2i%s%2i%s",": Hi-Gain Extraction range [",(int)fHiGainFirst,","
+                    ,fHiGainLast,"] too small, ") << endl;
+      *fLog << warn << GetDescriptor()
+            << " will move higher limit to obtain 4 slices " << endl;
+      SetRange(fHiGainFirst, fHiGainLast+4-range,fLoGainFirst,fLoGainLast);
+      range = fHiGainLast - fHiGainFirst + 1;
+    }
+  
+
+  fHiGainFirstDeriv = new Float_t[range];
+  memset(fHiGainFirstDeriv,0,range*sizeof(Float_t));
+  fHiGainSecondDeriv = new Float_t[range];
+  memset(fHiGainSecondDeriv,0,range*sizeof(Float_t));
+
+  range = fLoGainLast - fLoGainFirst + 1;
+
+  if (range >= 2)
+    {
+      
+      fLoGainFirstDeriv = new Float_t[range];
+      memset(fLoGainFirstDeriv,0,range*sizeof(Float_t));
+      fLoGainSecondDeriv = new Float_t[range];
+      memset(fLoGainSecondDeriv,0,range*sizeof(Float_t));
+
+    }
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeFastSpline::FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, 
+                                        Byte_t &sat, const MPedestalPix &ped) const
+{
+
+  const Int_t range = fHiGainLast - fHiGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t *p = first;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    {
+      if (*p > max)
+        {
+          max    = *p;
+          maxpos =  p-first;
+        }
+
+      if (*p++ >= fSaturationLimit)
+        {
+          sat++;
+          break;
+        }
+    }
+  
+  //
+  // allow one saturated slice 
+  //
+  if (sat > 1)
+    return;
+
+  if (maxpos < 1)
+    {
+      time = -999.;
+      return;
+    }
+  
+  Float_t pp;
+
+  p = first;
+  fHiGainSecondDeriv[0] = 0.;
+  fHiGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      p++;
+      pp = fHiGainSecondDeriv[i-1] + 4.;
+      fHiGainSecondDeriv[i] = -1.0/pp;
+      fHiGainFirstDeriv [i] = *(p+1) - 2.* *(p) + *(p-1);
+      fHiGainFirstDeriv [i] = (6.0*fHiGainFirstDeriv[i]-fHiGainFirstDeriv[i-1])/pp;
+    }
+
+  fHiGainSecondDeriv[range-1] = 0.;
+
+  for (Int_t k=range-2;k>0;k--)
+    fHiGainSecondDeriv[k] = fHiGainSecondDeriv[k]*fHiGainSecondDeriv[k+1] + fHiGainFirstDeriv[k];
+  for (Int_t k=range-2;k>0;k--)
+    fHiGainSecondDeriv[k] /= 6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = (Float_t)*(first+klo);
+  Float_t khicont = (Float_t)*(first+khi);
+  time          = upper;
+  Float_t abmax = khicont;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1 in steps of 0.2 till maxpos-0.2.
+  // If no maximum is found, go to interval maxpos+1.
+  //
+  Float_t higainklo = fHiGainSecondDeriv[klo];
+  Float_t higainkhi = fHiGainSecondDeriv[khi];
+
+  while ( x < upper - 0.3 )
+    {
+      
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*higainklo
+        + (b*b*b-b)*higainkhi;
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+    }
+  
+  //
+  // Search for the absolute maximum from maxpos to maxpos+1 in steps of 0.2
+  //
+  if (time > upper-0.1)
+    {
+
+      upper = (Float_t)maxpos+1.;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = (Float_t)*(first+klo);
+      khicont = (Float_t)*(first+khi);
+
+      higainklo = fHiGainSecondDeriv[klo];
+      higainkhi = fHiGainSecondDeriv[khi];
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*higainklo
+            + (b*b*b-b)*higainkhi;
+          
+          if (y > abmax)
+            {
+              abmax  = y;
+              time   = x;
+            }
+        }
+  }
+
+  //
+  // Now, the time, abmax and khicont and klocont are set correctly within the previous precision.
+  // Try a better precision. 
+  //
+  const Float_t up = time+step-0.035;
+  const Float_t lo = time-step+0.035;
+  const Float_t maxpossave = time;
+  
+  x     = time;
+  a     = upper - x;
+  b     = x - lower;
+
+  step  = 0.025; // step size of 83 ps 
+
+  higainklo = fHiGainSecondDeriv[klo];
+  higainkhi = fHiGainSecondDeriv[khi];
+
+  //
+  // First, try from time up to time+0.2 in steps of 83ps.
+  //
+  while ( x < up )
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*higainklo
+        + (b*b*b-b)*higainkhi;
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+      
+    }
+
+
+  //
+  // Second, try from time down to time-0.2 in steps of 0.04.
+  //
+  x     = maxpossave;
+  //
+  // Test the possibility that the absolute maximum has not been found between
+  // maxpos and maxpos+0.02, then we have to look between maxpos-0.02 and maxpos
+  // which requires new setting of klocont and khicont
+  //
+  if (x < klo + 0.02)
+    {
+      klo--;
+      khi--;
+      klocont = (Float_t)*(first+klo);
+      khicont = (Float_t)*(first+khi);
+      upper--;
+      lower--;
+    }
+  
+  a     = upper - x;
+  b     = x - lower;
+
+  higainklo = fHiGainSecondDeriv[klo];
+  higainkhi = fHiGainSecondDeriv[khi];
+
+  while ( x > lo )
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*higainklo
+        + (b*b*b-b)*higainkhi;
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+    }
+
+#if 0
+  const Float_t pedes   = ped.GetPedestal();
+  const Float_t halfmax = pedes + (abmax - pedes)/2.;
+
+  //
+  // Now, loop from the maximum bin leftward down in order to find the position of the half maximum.
+  // First, find the right FADC slice:
+  // 
+  klo   = maxpos;
+  while (klo > maxpos-fStartBeforeMax)
+    {
+      if (*(first+klo) < (Byte_t)halfmax)
+        break;
+      klo--;
+    }
+
+  //
+  // Loop from the beginning of the slice upwards to reach the halfmax:
+  // With means of bisection:
+  // 
+  x     = (Float_t)klo;
+  a     = 1.;
+  b     = 0.;
+  klocont = (Float_t)*(first+klo);
+  khicont = (Float_t)*(first+klo+1);
+
+  step = 0.5;
+  Bool_t back = kFALSE;
+
+  while (step > fResolution)
+    {
+      
+      if (back)
+        {
+          x -= step;
+          a += step;
+          b -= step;
+        }
+      else
+        {
+          x += step;
+          a -= step;
+          b += step;
+        }
+      
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fHiGainSecondDeriv[klo] 
+        + (b*b*b-b)*fHiGainSecondDeriv[khi];
+
+      if (y >= halfmax)
+        back = kTRUE;
+      else
+        back = kFALSE;
+
+      step /= 2.;
+      
+    }
+  time  = (Float_t)fHiGainFirst + x;
+
+#endif
+  dtime = 0.035;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeFastSpline::FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, 
+                                        Byte_t &sat, const MPedestalPix &ped) const
+{
+  
+  const Int_t range = fLoGainLast - fLoGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t       *p   = first;
+  Byte_t max    = 0;
+  Byte_t maxpos = 0;
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    {
+      if (*p > max)
+        {
+          max    = *p;
+          maxpos =  p-first;
+        }
+
+      if (*p++ >= fSaturationLimit)
+        {
+          sat++;
+          break;
+        }
+    }
+  
+  if (sat)
+    return;
+
+  if (maxpos < 1)
+    return;
+  
+  Float_t pp;
+
+  p = first;
+  fLoGainSecondDeriv[0] = 0.;
+  fLoGainFirstDeriv[0]  = 0.;
+
+  for (Int_t i=1;i<range-1;i++)
+    {
+      p++;
+      pp = fLoGainSecondDeriv[i-1] + 4.;
+      fLoGainSecondDeriv[i] = -1.0/pp;
+      fLoGainFirstDeriv [i] = *(p+1) - 2.* *(p) + *(p-1);
+      fLoGainFirstDeriv [i] = (6.0*fLoGainFirstDeriv[i]-fLoGainFirstDeriv[i-1])/pp;
+    }
+
+  fLoGainSecondDeriv[range-1] = 0.;
+
+  for (Int_t k=range-2;k>0;k--)
+    fLoGainSecondDeriv[k] = fLoGainSecondDeriv[k]*fLoGainSecondDeriv[k+1] + fLoGainFirstDeriv[k];
+  for (Int_t k=range-2;k>0;k--)
+    fLoGainSecondDeriv[k] /= 6.;
+  
+  //
+  // Now find the maximum  
+  //
+  Float_t step  = 0.2; // start with step size of 1ns and loop again with the smaller one
+  Float_t lower = (Float_t)maxpos-1.;
+  Float_t upper = (Float_t)maxpos;
+  Float_t x     = lower;
+  Float_t y     = 0.;
+  Float_t a     = 1.;
+  Float_t b     = 0.;
+  Int_t   klo = maxpos-1;
+  Int_t   khi = maxpos;
+  Float_t klocont = (Float_t)*(first+klo);
+  Float_t khicont = (Float_t)*(first+khi);
+  time          = upper;
+  Float_t abmax = khicont;
+
+  //
+  // Search for the maximum, starting in interval maxpos-1. If no maximum is found, go to 
+  // interval maxpos+1.
+  //
+  while (x<upper-0.3)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+
+    }
+
+ if (time > upper-0.1)
+    {
+
+      upper = (Float_t)maxpos+1.;
+      lower = (Float_t)maxpos;
+      x     = lower;
+      a     = 1.;
+      b     = 0.;
+      khi   = maxpos+1;
+      klo   = maxpos;
+      klocont = (Float_t)*(first+klo);
+      khicont = (Float_t)*(first+khi);
+
+      while (x<upper-0.3)
+        {
+
+          x += step;
+          a -= step;
+          b += step;
+          
+          y = a* klocont
+            + b* khicont
+            + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+            + (b*b*b-b)*fLoGainSecondDeriv[khi];
+          
+          if (y > abmax)
+            {
+              abmax  = y;
+              time   = x;
+            }
+        }
+  }
+ 
+  const Float_t up = time+step-0.055;
+  const Float_t lo = time-step+0.055;
+  const Float_t maxpossave = time;
+
+  x     = time;
+  a     = upper - x;
+  b     = x - lower;
+
+  step  = 0.025; // step size of 165 ps 
+
+  while (x<up)
+    {
+
+      x += step;
+      a -= step;
+      b += step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+      
+    }
+
+  if (time < klo + 0.01)
+    {
+      klo--;
+      khi--;
+      klocont = (Float_t)*(first+klo);
+      khicont = (Float_t)*(first+khi);
+      upper--;
+      lower--;
+    }
+  
+  x     = maxpossave;
+  a     = upper - x;
+  b     = x - lower;
+
+  while (x>lo)
+    {
+
+      x -= step;
+      a += step;
+      b -= step;
+      
+      y = a* klocont
+        + b* khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+      
+      if (y > abmax)
+        {
+          abmax  = y;
+          time   = x;
+        }
+      
+    }
+
+  const Float_t pedes   = ped.GetPedestal();
+  const Float_t halfmax = pedes + (abmax - pedes)/2.;
+
+  //
+  // Now, loop from the maximum bin leftward down in order to find the position of the half maximum.
+  // First, find the right FADC slice:
+  // 
+  klo   = maxpos;
+  while (klo > maxpos-4)
+    {
+      if (*(first+klo) < (Byte_t)halfmax)
+        break;
+      klo--;
+    }
+
+  //
+  // Loop from the beginning of the slice upwards to reach the halfmax:
+  // With means of bisection:
+  // 
+  x     = (Float_t)klo;
+  a     = 1.;
+  b     = 0.;
+  klocont = (Float_t)*(first+klo);
+  khicont = (Float_t)*(first+klo+1);
+  time  = x;
+
+  step = 0.5;
+  Bool_t back = kFALSE;
+
+  while (step > fResolution)
+    {
+      
+      if (back)
+        {
+          x -= step;
+          a += step;
+          b -= step;
+        }
+      else
+        {
+          x += step;
+          a -= step;
+          b += step;
+        }
+      
+      y = a*klocont
+        + b*khicont
+        + (a*a*a-a)*fLoGainSecondDeriv[klo] 
+        + (b*b*b-b)*fLoGainSecondDeriv[khi];
+
+      if (y >= halfmax)
+        back = kTRUE;
+      else
+        back = kFALSE;
+
+      step /= 2.;
+
+    }
+
+  time  = (Float_t)fLoGainFirst + x;
+  dtime = fResolution;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.Resolution: 0.003
+//   MJPedestal.MExtractor.RiseTime:   1.5
+//
+Int_t MExtractTimeFastSpline::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "HiGainWindowSize", print))
+    {
+        SetResolution(GetEnvValue(env, prefix, "Resolution", fResolution));
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainWindowSize", print))
+    {
+        SetRiseTime(GetEnvValue(env, prefix, "RiseTime", fRiseTime));
+        rc = kTRUE;
+    }
+
+    return MExtractTime::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
+
+void MExtractTimeFastSpline::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " Resolution:     " << fResolution << endl;
+    *fLog << " RiseTime:       " << fRiseTime << endl;
+    MExtractTime::Print(o);
+}
Index: /tags/Mars-V0.9/msignal/MExtractTimeFastSpline.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeFastSpline.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeFastSpline.h	(revision 9772)
@@ -0,0 +1,51 @@
+#ifndef MARS_MExtractTimeFastSpline
+#define MARS_MExtractTimeFastSpline
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MPedestalPix;
+
+class MExtractTimeFastSpline : public MExtractTime
+{
+private:
+  static const Byte_t  fgHiGainFirst;    // Default for fHiGainFirst  (now set to: 2)
+  static const Byte_t  fgHiGainLast;     // Default for fHiGainLast   (now set to: 14)
+  static const Byte_t  fgLoGainFirst;    // Default for fLOGainFirst  (now set to: 3)
+  static const Byte_t  fgLoGainLast;     // Default for fLoGainLast   (now set to: 14)
+  static const Float_t fgResolution;     // Default for fResolution   (now set to: 0.003)
+  static const Float_t fgRiseTime  ;     // Default for fRiseTime     (now set to: 1.5  )  
+
+  Float_t *fHiGainFirstDeriv;            //!
+  Float_t *fLoGainFirstDeriv;            //!
+  Float_t *fHiGainSecondDeriv;           //!
+  Float_t *fLoGainSecondDeriv;           //!
+
+  Float_t fResolution;                   // The time resolution in FADC units
+  Float_t fRiseTime  ;                   // The rise time of the pulse
+  Byte_t  fStartBeforeMax;               // Slices to start searching for the halfmax before max
+  
+  void FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+  void FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+
+  Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+
+  MExtractTimeFastSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractTimeFastSpline();
+    
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);      
+  void SetResolution(Float_t f=fgResolution)     { fResolution = f;  }
+  void SetRiseTime  (Float_t f=fgRiseTime  )     { fRiseTime   = f; fStartBeforeMax = (Int_t)(1.5*fRiseTime); }  
+
+  void Print(Option_t *o) const;
+  
+  ClassDef(MExtractTimeFastSpline, 1)   // Task to Extract the Arrival Times using a Fast Spline
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/msignal/MExtractTimeHighestIntegral.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeHighestIntegral.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeHighestIntegral.cc	(revision 9772)
@@ -0,0 +1,336 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 02/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Hendrik Bartko, 02/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeHighestIntegral
+//
+//  Calculates the arrival time as the mean time of the fWindowSize time slices
+//  which have the highest integral content.
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeHighestIntegral.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MPedestalPix.h"
+
+ClassImp(MExtractTimeHighestIntegral);
+
+using namespace std;
+
+const Byte_t MExtractTimeHighestIntegral::fgHiGainFirst  =  0;
+const Byte_t MExtractTimeHighestIntegral::fgHiGainLast   = 14;
+const Byte_t MExtractTimeHighestIntegral::fgLoGainFirst  =  3;
+const Byte_t MExtractTimeHighestIntegral::fgLoGainLast   = 14;
+const Byte_t MExtractTimeHighestIntegral::fgHiGainWindowSize = 6;
+const Byte_t MExtractTimeHighestIntegral::fgLoGainWindowSize = 6;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractTimeHighestIntegral::MExtractTimeHighestIntegral(const char *name, const char *title)
+    : fHiGainWindowSize(fgHiGainWindowSize), 
+      fLoGainWindowSize(fgLoGainWindowSize)
+{
+
+  fName  = name  ? name  : "MExtractTimeHighestIntegral";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+  
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+}
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+//
+void MExtractTimeHighestIntegral::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+  
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+  
+  if (range < 2)
+    {
+      *fLog << warn << GetDescriptor()
+            << Form("%s%2i%s%2i%s",": Hi-Gain Extraction range [",(int)fHiGainFirst,","
+                    ,fHiGainLast,"] too small, ") << endl;
+      *fLog << warn << GetDescriptor()
+            << " will move higher limit to obtain 4 slices " << endl;
+      SetRange(fHiGainFirst, fHiGainLast+4-range,fLoGainFirst,fLoGainLast);
+    }
+  
+  if (fLoGainLast != 0)
+    {
+      range = fLoGainLast - fLoGainFirst + 1;
+      
+      if (range < 2)
+        {
+          *fLog << warn << GetDescriptor()
+                << Form("%s%2i%s%2i%s",": Lo-Gain Extraction range [",(int)fLoGainFirst,","
+                        ,fLoGainLast,"] too small, ") << endl;
+          *fLog << warn << GetDescriptor()
+                << " will move lower limit to obtain 4 slices " << endl;
+          SetRange(fHiGainFirst, fHiGainLast,fLoGainFirst,fLoGainLast+4-range);
+        }
+    }
+
+  SetWindowSize(fHiGainWindowSize,fLoGainWindowSize);
+
+  fNumHiGainSamples = fHiGainLast-fHiGainFirst+1;
+  fNumLoGainSamples = fLoGainLast ? fLoGainLast-fLoGainFirst+1 : 0;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks:
+// - if a window is odd, subtract one
+// - if a window is bigger than the one defined by the ranges, set it to the available range
+// - if a window is smaller than 2, set it to 2
+// 
+void MExtractTimeHighestIntegral::SetWindowSize(Byte_t windowh, Byte_t windowl)
+{
+
+  fHiGainWindowSize = windowh & ~1;
+  fLoGainWindowSize = windowl & ~1;
+
+  if (fHiGainWindowSize != windowh)
+    *fLog << warn << GetDescriptor() << ": Hi Gain window size has to be even, set to: " 
+          << int(fHiGainWindowSize) << " samples " << endl;
+  
+  if (fLoGainWindowSize != windowl)
+    *fLog << warn << GetDescriptor() << ": Lo Gain window size has to be even, set to: " 
+          << int(fLoGainWindowSize) << " samples " << endl;
+    
+  const Byte_t availhirange = (fHiGainLast-fHiGainFirst+1) & ~1;
+  const Byte_t availlorange = (fLoGainLast-fLoGainFirst+1) & ~1;
+
+  if (fHiGainWindowSize > availhirange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Hi Gain window size: ",(int)fHiGainWindowSize,
+                    " is bigger than available range: [",(int)fHiGainFirst,",",(int)fHiGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availhirange << endl;
+      fHiGainWindowSize = availhirange;
+    }
+  
+  if (fLoGainWindowSize > availlorange)
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%2i%s%2i%s%2i%s",": Lo Gain window size: ",(int)fLoGainWindowSize,
+                    " is bigger than available range: [",(int)fLoGainFirst,",",(int)fLoGainLast,"]") << endl;
+      *fLog << warn << GetDescriptor() 
+            << ": Will set window size to: " << (int)availlorange << endl;
+      fLoGainWindowSize= availlorange;
+    }
+
+  fHiGainWindowSizeSqrt = TMath::Sqrt((Float_t)fHiGainWindowSize);
+  fLoGainWindowSizeSqrt = TMath::Sqrt((Float_t)fLoGainWindowSize);
+}
+
+
+void MExtractTimeHighestIntegral::FindTimeHiGain(Byte_t *ptr, Float_t &time, Float_t &deltatime, Byte_t &sat, const MPedestalPix &ped) const
+{
+
+  const Byte_t *end = ptr + fHiGainLast - fHiGainFirst +1 ;
+
+  Int_t sum=0;    // integral content of the actual window
+  Int_t max = 0;  // highest integral content of all windows
+  
+  //
+  // Calculate the sum of the first fWindowSize slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+  
+  while (p<ptr+fHiGainWindowSize)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+  
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+  
+  //
+  // Calculate the i-th sum as
+  //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  Byte_t *ptrmax=ptr;  // pointer to the first slice of the maximum window
+  
+  for (p=ptr; p+fHiGainWindowSize<end; p++)
+    {
+      sum += *(p+fHiGainWindowSize) - *p;
+      
+      if (sum>max)
+	{
+	  max = sum;
+	  ptrmax = p+1;
+	}
+    }
+  
+  // now calculate the time for the maximum window
+  Int_t timesignalsum = 0;
+  Int_t timesquaredsum =0;
+  Int_t timesum =0;
+  
+  for (p=ptrmax; p < ptrmax + fHiGainWindowSize; p++)
+    {
+      timesignalsum += *p*(p-ptr);
+      timesum += p-ptr;
+      timesquaredsum  += (p-ptr)*(p-ptr);
+    }
+  
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t pedrms = ped.GetPedestalRms();
+  const Float_t pedsubsum = max - fHiGainWindowSize*pedes;
+  const Float_t pedsubtimesignalsum = timesignalsum - timesum*pedes;
+
+  time      = pedsubsum != 0 ? pedsubtimesignalsum / pedsubsum  + Float_t(fHiGainFirst): 1;
+  deltatime = pedsubsum != 0 ? pedrms / pedsubsum * sqrt(timesquaredsum - fHiGainWindowSize*time) : 1;
+}
+
+void MExtractTimeHighestIntegral::FindTimeLoGain(Byte_t *ptr, Float_t &time, Float_t &deltatime, Byte_t &sat, const MPedestalPix &ped) const
+{
+
+  const Byte_t *end = ptr + fLoGainLast - fLoGainFirst +1 ;
+
+  Int_t sum=0;    // integral content of the actual window
+  Int_t max = 0;  // highest integral content of all windows
+  
+  //
+  // Calculate the sum of the first fWindowSize slices
+  //
+  sat = 0;
+  Byte_t *p = ptr;
+  
+  while (p<ptr+fLoGainWindowSize)
+    {
+      sum += *p;
+      if (*p++ >= fSaturationLimit)
+        sat++;
+    }
+  
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+  
+  //
+  // Calculate the i-th sum as
+  //    sum_i+1 = sum_i + slice[i+8] - slice[i]
+  // This is fast and accurate (because we are using int's)
+  //
+  max=sum;
+  Byte_t *ptrmax=ptr;  // pointer to the first slice of the maximum window
+  
+  for (p=ptr; p+fLoGainWindowSize<end; p++)
+    {
+      sum += *(p+fLoGainWindowSize) - *p;
+      
+      if (sum>max)
+	{
+	  max = sum;
+	  ptrmax = p+1;
+	}
+    }
+  
+  // now calculate the time for the maximum window
+  Int_t timesignalsum = 0;
+  Int_t timesquaredsum =0;
+  Int_t timesum =0;
+  
+  for (p=ptrmax; p < ptrmax + fLoGainWindowSize; p++)
+    {
+      timesignalsum += *p*(p-ptr);
+      timesum += p-ptr;
+      timesquaredsum  += (p-ptr)*(p-ptr);
+    }
+  
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t pedrms = ped.GetPedestalRms();
+  const Float_t pedsubsum = max - fLoGainWindowSize*pedes;
+  const Float_t pedsubtimesignalsum = timesignalsum - timesum*pedes;
+
+  time      = pedsubsum != 0 ? pedsubtimesignalsum / pedsubsum  + Float_t(fLoGainFirst) : 1;
+  deltatime = pedsubsum != 0 ? pedrms / pedsubsum * sqrt(timesquaredsum - fLoGainWindowSize*time) : 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// In addition to the resources of the base-class MExtractor:
+//   MJPedestal.MExtractor.WindowSizeHiGain: 6
+//   MJPedestal.MExtractor.WindowSizeLoGain: 6
+//
+Int_t MExtractTimeHighestIntegral::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Byte_t hw = fHiGainWindowSize;
+    Byte_t lw = fLoGainWindowSize;
+
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "HiGainWindowSize", print))
+    {
+        hw = GetEnvValue(env, prefix, "HiGainWindowSize", hw);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainWindowSize", print))
+    {
+        lw = GetEnvValue(env, prefix, "LoGainWindowSize", lw);
+        rc = kTRUE;
+    }
+
+    if (rc)
+        SetWindowSize(hw, lw);
+
+    return MExtractTime::ReadEnv(env, prefix, print) ? kTRUE : rc;
+}
+
+void MExtractTimeHighestIntegral::Print(Option_t *o) const
+{
+    *fLog << all;
+    *fLog << GetDescriptor() << ":" << endl;
+    *fLog << " Windows: Hi-Gain=" << (int)fHiGainWindowSize << "  Lo-Gain=" << (int)fLoGainWindowSize << endl;
+    MExtractTime::Print(o);
+}
Index: /tags/Mars-V0.9/msignal/MExtractTimeHighestIntegral.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeHighestIntegral.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeHighestIntegral.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MExtractTimeHighestIntegral
+#define MARS_MExtractTimeHighestIntegral
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MExtractTimeHighestIntegral : public MExtractTime
+{
+private:
+  static const Byte_t fgHiGainFirst;
+  static const Byte_t fgHiGainLast;
+  static const Byte_t fgLoGainFirst;
+  static const Byte_t fgLoGainLast;
+  static const Byte_t fgHiGainWindowSize;
+  static const Byte_t fgLoGainWindowSize;
+
+  Byte_t  fHiGainWindowSize;            // Number of gains in window
+  Float_t fHiGainWindowSizeSqrt;        // Sqaure root of number of gains in window
+  Byte_t  fLoGainWindowSize;            // Number of gains in window
+  Float_t fLoGainWindowSizeSqrt;        // Sqaure root of number of gains in window
+
+  void FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+  void FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+
+  Int_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+  
+public:
+  MExtractTimeHighestIntegral(const char *name=NULL, const char *title=NULL);
+
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);        
+  void SetWindowSize(Byte_t windowh=fgHiGainWindowSize,
+                     Byte_t windowl=fgLoGainWindowSize);
+
+  void Print(Option_t *o="") const;
+
+  ClassDef(MExtractTimeHighestIntegral, 1) // Task to Extract the Arrival Times As the mean time of the fWindowSize time slices
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/msignal/MExtractTimeSpline.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeSpline.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeSpline.cc	(revision 9772)
@@ -0,0 +1,203 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analyzing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Sebastian Raducci 12/2003 <mailto:raducci@fisica.uniud.it>
+!              Markus Gaug       04/2004 <mailto:markus@ifae.es> 
+!
+!   Copyright: MAGIC Software Development, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractTimeSpline
+//
+//   This is a task that calculates the arrival times of photons. 
+//   It returns the absolute maximum of the spline that interpolates
+//   the FADC slices 
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractTimeSpline.h"
+#include "MCubicSpline.h"
+
+#include "MGeomCam.h"
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MExtractTimeSpline);
+
+using namespace std;
+
+const Byte_t MExtractTimeSpline::fgHiGainFirst  = 0;
+const Byte_t MExtractTimeSpline::fgHiGainLast   = 14;
+const Byte_t MExtractTimeSpline::fgLoGainFirst  = 3;
+const Byte_t MExtractTimeSpline::fgLoGainLast   = 14;
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+// Calls: 
+// - SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast)
+//
+MExtractTimeSpline::MExtractTimeSpline(const char *name, const char *title) 
+    : fXHiGain(NULL), fXLoGain(NULL)
+{
+
+  fName  = name  ? name  : "MExtractTimeSpline";
+  fTitle = title ? title : "Calculate photons arrival time using a spline";
+    
+  SetRange(fgHiGainFirst, fgHiGainLast, fgLoGainFirst, fgLoGainLast);
+
+}
+
+MExtractTimeSpline::~MExtractTimeSpline()
+{
+  
+  if (fXHiGain)
+    delete fXHiGain;
+  if (fXLoGain)
+    delete fXLoGain;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//
+// SetRange: 
+//
+// Calls:
+// - MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+// - Deletes x, if not NULL
+// - Creates x according to the range
+//
+void MExtractTimeSpline::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+
+  MExtractor::SetRange(hifirst,hilast,lofirst,lolast);
+
+  if (fXHiGain)
+    delete fXHiGain;
+
+  if (fXLoGain)
+    delete fXLoGain;
+  
+  Int_t range = fHiGainLast - fHiGainFirst + 1;
+
+  if (range < 2)
+    {
+      *fLog << warn << GetDescriptor()
+            << Form("%s%2i%s%2i%s",": Hi-Gain Extraction range [",(int)fHiGainFirst,","
+                    ,fHiGainLast,"] too small, ") << endl;
+      *fLog << warn << GetDescriptor()
+            << " will move higher limit to obtain 4 slices " << endl;
+      SetRange(fHiGainFirst, fHiGainLast+4-range,fLoGainFirst,fLoGainLast);
+      range = fHiGainLast - fHiGainFirst + 1;
+    }
+  
+  fXHiGain = new Byte_t[range+1];
+  for (Int_t i=0; i<range+1; i++)
+    fXHiGain[i] = i;
+  
+  range = fLoGainLast - fLoGainFirst + 1;
+
+  if (range >= 2)
+    {
+      
+      fXLoGain = new Byte_t[range+1];
+      for (Int_t i=0; i<range+1; i++)
+        fXLoGain[i] = i;
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeSpline::FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, 
+                                        Byte_t &sat, const MPedestalPix &ped) const
+{
+  
+  const Int_t range = fHiGainLast - fHiGainFirst + 1;
+  const Byte_t *end = first + range;
+  Byte_t *p = first;
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+
+  //
+  // Initialize the spline
+  //
+  MCubicSpline spline(first,fXHiGain,kTRUE,range,0.0,0.0);  
+
+  //
+  // Now find the maximum  
+  //
+  Double_t abMaximum = spline.EvalAbMax();
+  Double_t maximum = spline.EvalMax();
+  const Double_t pedestal = ped.GetPedestal();
+  const Double_t halfMax = (maximum + pedestal)/2.;
+  time = (halfMax > pedestal) ? (Float_t ) spline.FindVal(halfMax,abMaximum,'l') + (Float_t)fHiGainFirst : 0.0;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculates the arrival time for each pixel 
+//
+void MExtractTimeSpline::FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, 
+                                        Byte_t &sat, const MPedestalPix &ped) const
+{
+  
+  const Int_t range = fLoGainLast - fLoGainFirst + 1;
+
+  if (range < 2)
+    return;
+
+  const Byte_t *end = first + range;
+  Byte_t *p = first;
+
+  //
+  // Check for saturation in all other slices
+  //
+  while (p<end)
+    if (*p++ >= fSaturationLimit)
+      sat++;
+
+  //
+  // Initialize the spline
+  //
+  MCubicSpline spline(first,fXLoGain,kTRUE,range,0.0,0.0);  
+
+  //
+  // Now find the maximum  
+  //
+  Double_t abMaximum = spline.EvalAbMax();
+  Double_t maximum = spline.EvalMax();
+  const Double_t pedestal = ped.GetPedestal();
+  const Double_t halfMax = (maximum + pedestal)/2.;
+
+  time = (halfMax > pedestal) ? (Float_t )spline.FindVal(halfMax,abMaximum,'l') + (Float_t)fLoGainFirst : 0.0;
+}
+
Index: /tags/Mars-V0.9/msignal/MExtractTimeSpline.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractTimeSpline.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractTimeSpline.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MExtractTimeSpline
+#define MARS_MExtractTimeSpline
+
+#ifndef MARS_MExtractTime
+#include "MExtractTime.h"
+#endif
+
+class MPedestalPix;
+
+class MExtractTimeSpline : public MExtractTime
+{
+private:
+  static const Byte_t fgHiGainFirst;
+  static const Byte_t fgHiGainLast;
+  static const Byte_t fgLoGainFirst;
+  static const Byte_t fgLoGainLast;
+
+  Byte_t *fXHiGain;
+  Byte_t *fXLoGain;  
+  
+  void FindTimeHiGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+  void FindTimeLoGain(Byte_t *first, Float_t &time, Float_t &dtime, Byte_t &sat, const MPedestalPix &ped) const;
+  
+public:
+
+  MExtractTimeSpline(const char *name=NULL, const char *title=NULL);
+  ~MExtractTimeSpline();
+    
+  void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);      
+  
+  ClassDef(MExtractTimeSpline, 0)   // Task to Extract the Arrival Times using a Spline
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/msignal/MExtractedSignalBlindPixel.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractedSignalBlindPixel.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractedSignalBlindPixel.cc	(revision 9772)
@@ -0,0 +1,143 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MExtractedSignalBlindPixel
+//
+// The storage container of the extracted signal of the calibration Blind Pixel(s). 
+// Additionally, the number of saturated Slices are stored. 
+// There is place for various blind pixels set into the camera in  July. Default 
+// is one blind pixel.
+//
+// Default values for the extracted signals are: gkSignalInitializer
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractedSignalBlindPixel.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractedSignalBlindPixel);
+
+using namespace std;
+
+const Int_t MExtractedSignalBlindPixel::gkSignalInitializer = 99999;
+// ------------------------------------------------------------------------
+//
+//
+// Sets:
+// - the dimenstion of fBlindPixelIdx to 1
+// - the dimenstion of fExtractedSignal to 1
+// - the dimenstion of fNumSaturated to 1
+// - the dimenstion of fPed. to 1;      
+// - the dimenstion of fPedErr. to 1;
+// - the dimenstion of fPedRms. to 1;   
+// - the dimenstion of fPedRmsErr. to 1;
+//
+// Calls:
+// - Clear()
+//
+MExtractedSignalBlindPixel::MExtractedSignalBlindPixel(const char* name, const char* title)
+{
+
+  fName  = name  ? name  : "MExtractedSignalBlindPixel";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  fBlindPixelIdx.Set(1);
+  fExtractedSignal.Set(1);
+  fNumSaturated.Set(1);
+
+  fPed.Set(1);      
+  fPedErr.Set(1);   
+  fPedRms.Set(1);   
+  fPedRmsErr.Set(1);
+
+  Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Set values of:
+// - fNumSaturated   
+// - fExtractedSignal
+// to gkSignalInitializer
+//
+void MExtractedSignalBlindPixel::Clear(Option_t *o)
+{
+
+  for (Int_t i=0;i<fBlindPixelIdx.GetSize();i++)
+    {
+      fNumSaturated   .AddAt(gkSignalInitializer,i);
+      fExtractedSignal.AddAt(gkSignalInitializer,i);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Set number num of used FADC slices, starting from (including) first 
+//
+void MExtractedSignalBlindPixel::SetUsedFADCSlices(const Byte_t first, const Byte_t num)   
+{
+  fFirst          = first; 
+  fNumFADCSamples = num;
+}
+
+// --------------------------------------------------------------------------------------------
+//
+// Returns true, if fExtractedSignal is greater or equal 0 and smaller than gkSignalInitializer
+//
+Bool_t MExtractedSignalBlindPixel::IsValid( const Int_t i ) const
+{
+    return fExtractedSignal.At(i) >= 0 && fExtractedSignal.At(i) <  gkSignalInitializer;
+}
+
+// --------------------------------------------------------------------------------------------
+//
+// Prints for all stored blind pixels the ID, the signal and the number of saturated slices
+//
+void MExtractedSignalBlindPixel::Print(Option_t *o) const
+{
+
+  for (Int_t i=0;i<fBlindPixelIdx.GetSize();i++)
+    {
+      
+      *fLog << "Blind Pixel ID: " << fBlindPixelIdx.At(i)
+            << ": Signal: " << fExtractedSignal.At(i)
+            << " Saturated Slices: " <<  fNumSaturated.At(i)
+            << endl;
+    }
+}
+
+// ------------------------------------------------------------------------------------
+//
+// Returns true if the extraction type. Available are: kAmplitude, kIntegral and kFilter
+// The flags kIntegral and kFilter may be set both. 
+//
+Bool_t MExtractedSignalBlindPixel::IsExtractionType( const MExtractBlindPixel::ExtractionType_t typ )
+{
+  
+  return TESTBIT( fExtractionType, typ );
+
+}
Index: /tags/Mars-V0.9/msignal/MExtractedSignalBlindPixel.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractedSignalBlindPixel.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractedSignalBlindPixel.h	(revision 9772)
@@ -0,0 +1,102 @@
+#ifndef MARS_MExtractedSignalBlindPixel
+#define MARS_MExtractedSignalBlindPixel
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef MARS_MExtractBlindPixel
+#include <MExtractBlindPixel.h>
+#endif
+
+class MExtractedSignalBlindPixel : public MParContainer
+{
+private:
+
+  static const Int_t gkSignalInitializer; //! Initializer for variables
+
+  TArrayI fBlindPixelIdx;                 // Array Blind Pixel IDs
+  TArrayF fExtractedSignal;               // Array Extracted signals per Blind Pixel ID
+  TArrayI fNumSaturated;                  // Array Number of saturated slices per Blind Pixel ID 
+  					  
+  TArrayF fPed;                           // Array Pedestal per Blind Pixel IDs                               
+  TArrayF fPedErr;                        // Array Pedestal Error per Blind Pixel ID          
+  TArrayF fPedRms;                        // Array Pedestal RMS per Blind Pixel ID 
+  TArrayF fPedRmsErr;                     // Array Pedestal RMS Error per Blind Pixel ID 
+					  
+  Byte_t  fFirst;                         // First FADC extraction slice
+  Byte_t  fNumFADCSamples;                // Number of summed FADC slices
+  Byte_t  fExtractionType;                // What extraction type has been chosen?
+  
+public:
+
+  MExtractedSignalBlindPixel(const char* name=NULL, const char* title=NULL);
+
+  void Clear(Option_t *o="");
+  void Print(Option_t *o="") const;
+  
+  // Getters
+  Int_t   GetBlindPixelIdx   ( const Int_t i=0 )  const { return fBlindPixelIdx.At(i)    ; }  
+  Float_t GetExtractedSignal ( const Int_t i=0 )  const { return fExtractedSignal.At(i)  ; }
+  Int_t   GetNumBlindPixels  ()                   const { return fBlindPixelIdx.GetSize(); }
+  Int_t   GetNumSaturated    ( const Int_t i=0 )  const { return fNumSaturated.At(i)     ; }
+  Byte_t  GetNumFADCSamples  ()                   const { return fNumFADCSamples         ; }
+
+  Float_t GetPed             ( const Int_t i=0 )  const { return fPed.At(i)              ; }
+  Float_t GetPedErr          ( const Int_t i=0 )  const { return fPedErr.At(i)           ; }
+  Float_t GetPedRms          ( const Int_t i=0 )  const { return fPedRms.At(i)           ; }
+  Float_t GetPedRmsErr       ( const Int_t i=0 )  const { return fPedRmsErr.At(i)        ; }
+
+  Bool_t  IsExtractionType   ( const MExtractBlindPixel::ExtractionType_t typ );
+  Bool_t  IsValid            ( const Int_t i=0 )  const;   
+
+  // Setter
+  void SetExtractionType( const Byte_t b=0 )            { fExtractionType  = b           ; }
+  void SetNumFADCSamples( const Byte_t num )            { fNumFADCSamples  = num         ; }    
+  void SetUsedFADCSlices( const Byte_t first, const Byte_t num );
+
+  void SetBlindPixelIdx  ( const Int_t i,   const Int_t nr=0)      {
+    if (nr>fBlindPixelIdx.GetSize()-1)
+      {
+	fBlindPixelIdx.Set(nr+1);
+	fExtractedSignal.Set(nr+1);
+	fNumSaturated.Set(nr+1);
+	fPed.Set(nr+1);
+	fPedErr.Set(nr+1);
+	fPedRms.Set(nr+1);
+	fPedRmsErr.Set(nr+1);
+      }
+    fBlindPixelIdx.AddAt(i,nr); }
+  void SetExtractedSignal( const Float_t f, const Int_t nr=0 )     {
+    fExtractedSignal.AddAt(f,nr); }
+  void SetNumSaturated   ( const Int_t i,   const Int_t nr=0 )     {
+    fNumSaturated.AddAt(i,nr); }
+  void SetPed            ( const Float_t f, const Int_t nr=0 )     {
+    fPed.AddAt(f,nr); }
+  void SetPedErr         ( const Float_t f, const Int_t nr=0 )     {
+    fPedErr.AddAt(f,nr); }
+  void SetPedRms         ( const Float_t f, const Int_t nr=0 )     {
+    fPedRms.AddAt(f,nr); }
+  void SetPedRmsErr      ( const Float_t f, const Int_t nr=0 )     {
+    fPedRmsErr.AddAt(f,nr); }
+
+  ClassDef(MExtractedSignalBlindPixel, 3)	// Storage Container for extracted signal of Blind Pixel
+};
+
+#endif
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/msignal/MExtractedSignalCam.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractedSignalCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractedSignalCam.cc	(revision 9772)
@@ -0,0 +1,174 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  12/2003 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MExtractedSignalCam
+//
+// Hold the Extracted Signal information for all pixels in the camera
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractedSignalCam.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MExtractedSignalPix.h"
+
+ClassImp(MExtractedSignalCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. Creates a MExtractedSignalPix object for each pixel
+//
+MExtractedSignalCam::MExtractedSignalCam(const char *name, const char *title)
+    : fFirstUsedSliceHiGain(0), fFirstUsedSliceLoGain(0),
+      fLastUsedSliceHiGain(0), fLastUsedSliceLoGain(0), 
+      fUsedWindowHiGain(0.), fUsedWindowLoGain(0.), fNdf(-1)
+{
+    fName  = name  ? name  : "MExtractedSignalCam";
+    fTitle = title ? title : "Storage container for all Extracted Signal Information in the camera";
+
+    fArray = new TClonesArray("MExtractedSignalPix", 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the array conatining the pixel pedest information
+//
+MExtractedSignalCam::~MExtractedSignalCam()
+{
+    delete fArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// Distribute logging stream to all childs
+//
+void MExtractedSignalCam::SetLogStream(MLog *lg)
+{
+    fArray->ForEach(MParContainer, SetLogStream)(lg);
+    MParContainer::SetLogStream(lg);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MExtractedSignalCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MExtractedSignalCam
+//
+Int_t MExtractedSignalCam::GetSize() const
+{
+    return fArray->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel index)
+//
+MExtractedSignalPix &MExtractedSignalCam::operator[](Int_t i)
+{
+    return *static_cast<MExtractedSignalPix*>(fArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel index)
+//
+const MExtractedSignalPix &MExtractedSignalCam::operator[](Int_t i) const
+{
+    return *static_cast<MExtractedSignalPix*>(fArray->UncheckedAt(i));
+}
+
+Float_t MExtractedSignalCam::GetProb( const Int_t pixidx )   const
+{ 
+
+  if (pixidx > GetSize()-1)
+    return -1.;
+  
+  return TMath::Prob((*this)[pixidx].GetChisquare(),fNdf); 
+}
+
+void MExtractedSignalCam::Clear(Option_t *o)
+{
+    fArray->ForEach(TObject, Clear)();
+}
+
+void MExtractedSignalCam::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << endl;
+    int idx = -1;
+
+    TIter Next(fArray);
+    MExtractedSignalPix *pix;
+    while ((pix=(MExtractedSignalPix*)Next()))
+    {
+        idx++;
+
+        if (!pix->IsValid())
+            continue;
+
+        *fLog << idx << ": ";
+	pix->Print();
+    }
+}
+
+Bool_t MExtractedSignalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    switch (type)
+    {
+    case 0:
+        val = (*this)[idx].GetExtractedSignalHiGain();
+        break;
+    case 1:
+        val = (*this)[idx].GetExtractedSignalHiGainError();
+        break;
+    case 2:
+        val = (*this)[idx].GetExtractedSignalLoGain();
+        break;
+    case 3:
+        val = (*this)[idx].GetExtractedSignalLoGainError();
+        break;
+    default:
+	return kFALSE;
+    }
+    return val>=0;
+}
+
+void MExtractedSignalCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MExtractedSignaCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars-V0.9/msignal/MExtractedSignalCam.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractedSignalCam.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractedSignalCam.h	(revision 9772)
@@ -0,0 +1,79 @@
+#ifndef MARS_MExtractedSignalCam
+#define MARS_MExtractedSignalCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+class MExtractedSignalPix;
+
+class MExtractedSignalCam : public MParContainer, public MCamEvent
+{
+private:
+
+  TClonesArray *fArray;                //-> FIXME: Change TClonesArray away from a pointer?
+
+  Byte_t fFirstUsedSliceHiGain;        // First High Gain FADC used for extraction (incl.)
+  Byte_t fFirstUsedSliceLoGain;        // First Low Gain FADC used for extraction (incl.)
+  
+  Byte_t fLastUsedSliceHiGain;         // Last High Gain FADC used for extraction (incl.)
+  Byte_t fLastUsedSliceLoGain;         // Last Low Gain FADC used for extraction (incl.)
+  
+  Float_t fUsedWindowHiGain;           // High Gain FADC extraction window 
+  Float_t fUsedWindowLoGain;           // Low Gain FADC extraction window 
+
+  Int_t   fNdf;                        // Number of degrees of freedom for a possible fit
+  
+public:
+
+    MExtractedSignalCam(const char *name=NULL, const char *title=NULL);
+    ~MExtractedSignalCam();
+
+    void    Print(Option_t *o="") const;
+    void    Clear(Option_t *o="");
+    void    Reset() { Clear(); }
+
+    void    InitSize(const UInt_t i);
+    Int_t   GetSize () const;
+
+    Byte_t  GetFirstUsedSliceHiGain()    const { return fFirstUsedSliceHiGain; }
+    Byte_t  GetFirstUsedSliceLoGain()    const { return fFirstUsedSliceLoGain; }
+
+    Byte_t  GetLastUsedSliceHiGain()     const { return fLastUsedSliceHiGain;  }
+    Byte_t  GetLastUsedSliceLoGain()     const { return fLastUsedSliceLoGain;  }
+
+    Float_t GetNumUsedHiGainFADCSlices() const { return fUsedWindowHiGain;     }
+    Float_t GetNumUsedLoGainFADCSlices() const { return fUsedWindowLoGain;     }
+
+    Float_t GetNdf()                     const { return fNdf;                  }
+    Float_t GetProb( const Int_t pixidx) const;
+
+    void    SetLogStream     ( MLog *lg  );
+    void    SetNdf           ( Int_t ndf ) { fNdf = ndf;  }
+    void    SetUsedFADCSlices(Byte_t firsth, Byte_t lasth, Float_t winh,
+                              Byte_t firstl, Byte_t lastl, Float_t winl)
+    {
+      fFirstUsedSliceHiGain    = firsth;
+      fLastUsedSliceHiGain     = lasth;
+      fUsedWindowHiGain        = winh;
+      fFirstUsedSliceLoGain    = firstl;
+      fLastUsedSliceLoGain     = lastl;
+      fUsedWindowLoGain        = winl;
+    }
+
+    MExtractedSignalPix &operator[](Int_t i);
+    const MExtractedSignalPix &operator[](Int_t i) const;
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    ClassDef(MExtractedSignalCam, 2)	// Storage Container for extracted signals in the camera
+};
+
+#endif
+
Index: /tags/Mars-V0.9/msignal/MExtractedSignalPINDiode.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractedSignalPINDiode.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractedSignalPINDiode.cc	(revision 9772)
@@ -0,0 +1,120 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MExtractedSignalPINDiode
+//
+// This is the storage container to hold informations about the extracted signal 
+// (offset) value of the calibration PIN Diode
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractedSignalPINDiode.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractedSignalPINDiode);
+
+using namespace std;
+
+static const Float_t gkSignalInitializer = 99999.9;
+
+// ------------------------------------------------------------------------
+//
+// MExtractedSignalPINDiode holds the extracted signal
+// of the FADC slices and its error. 
+//
+// Additionally, the number of saturated Slices are stored. 
+// 
+// Default values for the extracted signals are: 99999.9 
+//
+MExtractedSignalPINDiode::MExtractedSignalPINDiode(const char* name, const char* title)
+{
+
+  fName  = name  ? name  : "MExtractedSignalPINDiode";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MExtractedSignalPINDiode::Clear(Option_t *o)
+{
+  fExtractedSignal          = gkSignalInitializer;
+  fExtractedSignalErr       = gkSignalInitializer;
+  fExtractedTime            = gkSignalInitializer;
+  fExtractedTimeErr         = gkSignalInitializer; 
+  fExtractedRms             = gkSignalInitializer; 
+  fExtractedRmsErr          = gkSignalInitializer; 
+
+  fNumSaturated       = 0;
+}
+
+void MExtractedSignalPINDiode::SetUsedFADCSlices(const Byte_t first, const Byte_t num)   
+{
+  fFirst          = first; 
+  fNumFADCSamples = num;
+}
+
+
+void MExtractedSignalPINDiode::SetExtractedSignal(const Float_t sig, const Float_t sigerr)   
+{
+  fExtractedSignal      = sig; 
+  fExtractedSignalErr = sigerr;
+}
+
+void MExtractedSignalPINDiode::SetExtractedRms(const Float_t sig, const Float_t sigerr)   
+{
+  fExtractedRms      = sig; 
+  fExtractedRmsErr = sigerr;
+}
+
+void MExtractedSignalPINDiode::SetExtractedTime(const Float_t sig, const Float_t sigerr)   
+{
+  fExtractedTime      = sig; 
+  fExtractedTimeErr = sigerr;
+}
+
+
+Bool_t MExtractedSignalPINDiode::IsValid() const
+{
+    return fExtractedSignal >= 0. || fExtractedSignalErr >= 0.;
+}
+
+void MExtractedSignalPINDiode::SetSaturation(const Byte_t numsat)
+{
+  fNumSaturated = numsat; 
+}
+
+void MExtractedSignalPINDiode::Print(Option_t *o) const
+{
+  *fLog << " Signal: " << fExtractedSignal
+        << " +- " << fExtractedSignalErr
+        << " Nr. Saturation: " <<  fNumSaturated
+        << endl;
+}
Index: /tags/Mars-V0.9/msignal/MExtractedSignalPINDiode.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractedSignalPINDiode.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractedSignalPINDiode.h	(revision 9772)
@@ -0,0 +1,52 @@
+#ifndef MARS_MExtractedSignalPINDiode
+#define MARS_MExtractedSignalPINDiode
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MExtractedSignalPINDiode : public MParContainer
+{
+private:
+
+  Float_t fExtractedSignal;    // mean value of the extracted signal
+  Float_t fExtractedSignalErr; // error of the mean value of the extracted signal
+  Float_t fExtractedTime; 
+  Float_t fExtractedTimeErr; 
+  Float_t fExtractedRms; 
+  Float_t fExtractedRmsErr; 
+
+  Byte_t fFirst;
+  Byte_t fNumFADCSamples;
+  Byte_t fNumSaturated;
+
+public:
+    MExtractedSignalPINDiode(const char* name=NULL, const char* title=NULL);
+
+    void Clear(Option_t *o="");
+    void Print(Option_t *o="") const;
+
+    // Setter
+    void SetExtractedSignal(const Float_t sig, const Float_t sigerr);
+    void SetExtractedRms(  const Float_t sig, const Float_t sigerr);
+    void SetExtractedTime(  const Float_t sig, const Float_t sigerr);
+    void SetSaturation(   const Byte_t numsat);
+    void SetUsedFADCSlices( const Byte_t first, const Byte_t num);
+    
+    // Getter
+    Float_t GetExtractedSignal()    const { return fExtractedSignal;       }
+    Float_t GetExtractedSignalErr() const { return fExtractedSignalErr;    }
+    Float_t GetExtractedTime()      const { return fExtractedTime;         }
+    Float_t GetExtractedTimeErr()   const { return fExtractedTimeErr;      }
+    Float_t GetExtractedRms()       const { return fExtractedRms;          }
+    Float_t GetExtractedRmsErr()    const { return fExtractedRmsErr;       }
+    Byte_t  GetNumFADCSamples()     const { return fNumFADCSamples;        }
+    Byte_t  GetFirstUsedSlice()     const { return fFirst;                 }
+    Byte_t  GetLastUsedSlice()      const { return fFirst+fNumFADCSamples; }    
+    
+    Bool_t IsValid() const;   
+
+    ClassDef(MExtractedSignalPINDiode, 1)	// Storage Container for Extracted Signal information of one pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractedSignalPix.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractedSignalPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractedSignalPix.cc	(revision 9772)
@@ -0,0 +1,118 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug  12/2003 <mailto:markus@ifae.es>
+!   Author(s): Thomas Bretz 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MExtractedSignalPix
+//
+// This is the storage container to hold informations about the pedestal
+// (offset) value of one Pixel (PMT).
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractedSignalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractedSignalPix);
+
+using namespace std;
+
+static const Float_t gkSignalInitializer = -99999.9;
+// ------------------------------------------------------------------------
+//
+// MExtractedSignalPix holds the extracted signal (HiGain and LoGain) 
+// of the FADC slices and its error. 
+//
+// Additionally, the number of saturated HiGain and LoGain Slices are stored. 
+// 
+// Default values for the extracted signals are: 99999.9 
+//
+MExtractedSignalPix::MExtractedSignalPix(const char* name, const char* title)
+{
+  fName  = name  ? name  : "MExtractedSignalPix";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  Clear();
+  
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MExtractedSignalPix::Clear(Option_t *o)
+{
+  fExtractedSignalHiGain      = gkSignalInitializer;
+  fExtractedSignalHiGainError = -1;
+  fExtractedSignalLoGain      = gkSignalInitializer;
+  fExtractedSignalLoGainError = -1;
+  
+  fLoGainUsed = kFALSE;
+
+  fNumHiGainSaturated = 0;
+  fNumLoGainSaturated = 0;
+
+  fChisquare          = -1.;
+}
+
+void MExtractedSignalPix::SetExtractedSignal(Float_t sig, Float_t sigerr)   
+{
+  fExtractedSignalHiGain      = sig; 
+  fExtractedSignalHiGainError = sigerr;
+}
+
+void MExtractedSignalPix::SetExtractedSignal(Float_t sighi, Float_t sighierr,
+                                             Float_t siglo, Float_t sigloerr)   
+{
+  fExtractedSignalHiGain = sighi;
+  fExtractedSignalHiGainError = sighierr;
+  fExtractedSignalLoGain = siglo;
+  fExtractedSignalLoGainError = sigloerr;
+}
+
+Bool_t MExtractedSignalPix::IsValid() const
+{
+    return (!IsLoGainUsed() && fExtractedSignalHiGainError >= 0) || (IsLoGainUsed() && fExtractedSignalLoGainError >= 0);
+}
+
+void MExtractedSignalPix::SetGainSaturation(Bool_t sat, Byte_t higain, Byte_t logain) 
+{
+
+  fLoGainUsed = sat; 
+  fNumHiGainSaturated = higain; 
+  fNumLoGainSaturated = logain;
+}
+
+void MExtractedSignalPix::Print(Option_t *o) const
+{
+    *fLog << " Signal: " << fExtractedSignalHiGain
+        << " +- " << fExtractedSignalHiGainError
+        << " LoGain? " << fLoGainUsed
+        << " Nr. Sat. Hi Gain: " <<  fNumHiGainSaturated
+        << " Nr. Sat. Lo Gain: " <<  fNumLoGainSaturated
+        << endl;
+}
Index: /tags/Mars-V0.9/msignal/MExtractedSignalPix.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractedSignalPix.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractedSignalPix.h	(revision 9772)
@@ -0,0 +1,53 @@
+#ifndef MARS_MExtractedSignalPix
+#define MARS_MExtractedSignalPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MExtractedSignalPix : public MParContainer
+{
+private:
+
+  Float_t fExtractedSignalHiGain;      // mean value of the extracted signal
+  Float_t fExtractedSignalHiGainError; // error of the mean value of the extracted signal
+  Float_t fExtractedSignalLoGain;      // mean value of the extracted signal
+  Float_t fExtractedSignalLoGainError; // error of the mean value of the extracted signal
+
+  Float_t fChisquare;                  // Chi-square of a possible fit the pulse
+  
+  Bool_t fLoGainUsed;
+  Byte_t fNumHiGainSaturated;
+  Byte_t fNumLoGainSaturated;
+
+public:
+  MExtractedSignalPix(const char* name=NULL, const char* title=NULL);
+
+  void Clear(Option_t *o="");
+  void Print(Option_t *o="") const;
+
+  // Setter
+  void SetExtractedSignal( Float_t sig, Float_t sigerr);
+  void SetExtractedSignal( Float_t sighi, Float_t sighierr,Float_t siglo, Float_t sigloerr);
+  void SetGainSaturation ( Bool_t sat, Byte_t higain, Byte_t logain);
+  void SetChisquare      ( Float_t chi2 )   { fChisquare = chi2; }
+    
+  // Getter
+  Float_t GetExtractedSignalHiGain()      const { return fExtractedSignalHiGain;       }
+  Float_t GetExtractedSignalHiGainError() const { return fExtractedSignalHiGainError;  }
+
+  Float_t GetExtractedSignalLoGain()      const { return fExtractedSignalLoGain;       }
+  Float_t GetExtractedSignalLoGainError() const { return fExtractedSignalLoGainError;  }
+
+  Byte_t GetNumHiGainSaturated()          const { return fNumHiGainSaturated;          }
+  Byte_t GetNumLoGainSaturated()          const { return fNumLoGainSaturated;          }
+
+  Float_t GetChisquare()                  const { return fChisquare;                   }
+    
+  Bool_t IsLoGainUsed()                   const { return fLoGainUsed;                  }
+  Bool_t IsValid()                        const;   
+
+  ClassDef(MExtractedSignalPix, 2) // Storage Container for Extracted Signal information of one pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MExtractor.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractor.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractor.cc	(revision 9772)
@@ -0,0 +1,429 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+// MExtractor
+// ==========
+//
+//   Base class for the signal extractors, used the functions 
+//   FindSignalHiGain() and FindSignalLoGain() to extract the signal and 
+//   substract the pedestal value    
+//
+//   The following variables have to be set by the derived class and 
+//   do not have defaults:
+//   - fNumHiGainSamples
+//   - fNumLoGainSamples
+//   - fSqrtHiGainSamples
+//   - fSqrtLoGainSamples
+//
+//   The signal extractor classes can be setup from an environmental
+//   setup file. For more information see ReadEnv and MEvtLoop::ReadEnv
+//
+//
+// IMPORTANT: For all classes you derive from MExtractor make sure that:
+//    - Print() is correctly implemented
+//    - Clone() works
+//    - Class Version number != 0 and the I/O works PERFECTLY
+//    - only data members which are necessary for the setup (not the ones
+//      created in PreProcess and Process) are written
+//    - the version number is maintained!
+//    - If the flag fNoiseCalculation is set, the signal extractor should 
+//      calculate the pure noise contriubtion from a fixed window in time.
+//
+// The following figure gives and example of possible inheritance trees. 
+// An extractor class can inherit from each of the following base classes:
+//    - MExtractor
+//    - MExtractTime
+//    - MExtractTimeAndCharge
+//
+//Begin_Html
+/*
+<img src="images/ExtractorClasses.gif">
+*/
+//End_Html
+//
+// Input Containers:
+//   MRawEvtData
+//   MRawRunHeader
+//   MPedestalCam
+//
+// Output Containers:
+//   MExtractedSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractor.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+#include "MRawRunHeader.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MExtractor);
+
+using namespace std;
+
+const Byte_t  MExtractor::fgSaturationLimit = 250;
+const TString MExtractor::fgNamePedestalCam = "MPedestalCam";
+const TString MExtractor::fgNameSignalCam   = "MExtractedSignalCam";
+const Float_t MExtractor::fgOffsetLoGain    = 1.51;   // 5 ns
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Set: 
+// - all pointers to NULL
+// - all variables to 0
+// - fSaturationLimit to fgSaturationLimit
+// - fNamePedestalCam to fgNamePedestalCam
+// - fNameSignalCam to fgNameSignalCam
+// - fNoiseCalculation to kFALSE 
+//
+// Call:
+// -  AddToBranchList("MRawEvtData.*")
+//
+MExtractor::MExtractor(const char *name, const char *title)
+    : fPedestals(NULL), fSignals(NULL), fRawEvt(NULL), fRunHeader(NULL),
+      fHiLoLast(0), fNumHiGainSamples(0.), fNumLoGainSamples(0.)
+{
+    fName  = name  ? name  : "MExtractor";
+    fTitle = title ? title : "Base class for signal extractors";
+
+    AddToBranchList("MRawEvtData.*");
+
+    SetNamePedestalCam();
+    SetNameSignalCam();
+    SetOffsetLoGain();
+    SetSaturationLimit();
+    SetNoiseCalculation(kFALSE);
+}
+
+void MExtractor::SetRange(Byte_t hifirst, Byte_t hilast, Byte_t lofirst, Byte_t lolast)
+{
+ 
+  Clear();
+
+  fHiGainFirst = hifirst;
+  fHiGainLast  = hilast;
+  
+  fLoGainFirst = lofirst;
+  fLoGainLast  = lolast;
+}
+
+//-----------------------------------------------------------------------
+//
+// - Set the variable fHiLoLast to 0 (will be initialized later in ReInit()
+// - Get the pointers to: 
+//     MRawEvtData
+//     MRawRunHeader
+//     MPedestalCam
+//
+Int_t MExtractor::PreProcessStd(MParList *pList)
+{
+
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+        *fLog << err << AddSerialNumber("MRawRunHeader") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    if (fPedestals)
+        return kTRUE;
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber(fNamePedestalCam), "MPedestalCam");
+    if (!fPedestals)
+    {
+        *fLog << err << fNamePedestalCam << " not found... aborting" << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MRawRunHeader
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedSignalCam
+//
+Int_t MExtractor::PreProcess(MParList *pList)
+{
+    fSignals = (MExtractedSignalCam*)pList->FindCreateObj("MExtractedSignalCam",AddSerialNumber(fNameSignalCam));
+    if (!fSignals)
+        return kFALSE;
+
+    return PreProcessStd(pList);
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit searches for:
+// -  MRawRunHeader::GetNumSamplesHiGain()
+// -  MRawRunHeader::GetNumSamplesLoGain()
+//
+// In case that the variable fLoGainLast is smaller than 
+// the even part of the number of samples obtained from the run header, a
+// warning is given an the range is set back accordingly. A call to:  
+// - SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast-diff) 
+// is performed in that case. The variable diff means here the difference 
+// between the requested range (fLoGainLast) and the available one. Note that 
+// the functions SetRange() are mostly overloaded and perform more checks, 
+// modifying the ranges again, if necessary.
+//
+// In case that the variable fHiGainLast is smaller than the available range 
+// obtained from the run header, a warning is given that a part of the low-gain 
+// samples are used for the extraction of the high-gain signal. 
+//
+Bool_t MExtractor::ReInit(MParList *pList)
+{
+
+  const Int_t logainsamples = fRunHeader->GetNumSamplesLoGain();
+
+  Int_t lastdesired;
+  Int_t lastavailable;
+
+  if (logainsamples)
+    {
+
+      lastdesired   = (Int_t)(fLoGainLast);
+      lastavailable = logainsamples-1;
+      
+      if (lastavailable < 0)
+        *fLog << warn << GetDescriptor() << " - WARNING: Number of available Low-Gain Slices is smaller than or equal zero!" << endl;
+      
+    if (lastdesired > lastavailable)
+      {
+        const Int_t diff = lastdesired - lastavailable;
+        
+        *fLog << endl;
+        *fLog << warn << GetDescriptor() << ": Selected Lo Gain FADC Window [";
+        *fLog << Form("%2i,%2i", (int)fLoGainFirst, lastdesired);
+        *fLog << "] ranges out of the available limits: [0," << Form("%2i", lastavailable) << "]" << endl;
+        *fLog << GetDescriptor() << ": Will reduce the upper edge to " << (int)(fLoGainLast - diff) << endl;
+        SetRange(fHiGainFirst, fHiGainLast, fLoGainFirst, fLoGainLast-diff);
+      }
+    }
+  else
+    SetRange(fHiGainFirst, fHiGainLast, 0,0);      
+  
+  const Int_t higainsamples = fRunHeader->GetNumSamplesHiGain();
+
+  if (higainsamples <= 0)
+    {
+      *fLog << err << GetDescriptor();
+      *fLog << " - ERROR: Number of available High-Gain Slices is smaller than or equal zero!" << endl;
+      return kFALSE;
+    }
+
+  lastdesired   = (Int_t)fHiGainLast;
+  lastavailable = higainsamples-1;
+  
+  if (lastdesired > lastavailable)
+    {
+      const Int_t diff = lastdesired - lastavailable;
+      
+      *fLog << endl;
+      *fLog << inf << GetDescriptor() << ": Selected Hi Gain FADC Window [";
+      *fLog << Form("%2i,%2i", (int)fHiGainFirst,lastdesired);
+      *fLog << "] ranges out of the available limits: [0," << Form("%2i", lastavailable) << "]" << endl;
+      *fLog << inf << GetDescriptor() << ": Will use ";
+      *fLog << Form("%2i", diff) << " samples from the Low-Gain for the High-Gain extraction";
+      *fLog << endl;
+      
+      fHiGainLast -= diff;
+      fHiLoLast    = diff;
+    }
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MExtractedSignalCam container.
+//
+Int_t MExtractor::Process()
+{
+
+  MRawEvtPixelIter pixel(fRawEvt);
+
+  while (pixel.Next())
+    {
+      Float_t sumhi = 0.;
+      Byte_t sathi = 0;
+
+      FindSignalHiGain(pixel.GetHiGainSamples()+fHiGainFirst, pixel.GetLoGainSamples(), sumhi, sathi);
+
+      Float_t sumlo  = 0.;
+      Byte_t  satlo  = 0;
+
+      if (pixel.HasLoGain())
+	FindSignalLoGain(pixel.GetLoGainSamples()+fLoGainFirst, sumlo, satlo);
+
+      const Int_t pixid = pixel.GetPixelId();
+      
+      const MPedestalPix  &ped = (*fPedestals)[pixid]; 
+      MExtractedSignalPix &pix = (*fSignals)[pixid];
+      
+      const Float_t pedes  = ped.GetPedestal();
+      const Float_t pedrms = ped.GetPedestalRms();
+
+      pix.SetExtractedSignal(sumhi - pedes*fNumHiGainSamples, pedrms*fSqrtHiGainSamples,
+                             sumlo - pedes*fNumLoGainSamples, pedrms*fSqrtLoGainSamples);
+      
+      pix.SetGainSaturation(sathi, sathi, satlo);
+      
+    } /* while (pixel.Next()) */
+
+    fSignals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Implementation of SavePrimitive. Used to write the call to a constructor
+// to a macro. In the original root implementation it is used to write
+// gui elements to a macro-file.
+//
+void MExtractor::StreamPrimitive(ofstream &out) const
+{
+  out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+  out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+  
+  if (fSaturationLimit!=fgSaturationLimit)
+  {
+      out << "   " << GetUniqueName() << ".SetSaturationLimit(";
+      out << (int)fSaturationLimit << ");" << endl;
+  }
+  
+  out << "   " << GetUniqueName() << ".SetRange(";
+  out << (int)fHiGainFirst;
+  out << ", " << (int)fHiGainLast;
+  out << ", " << (int)fLoGainFirst;
+  out << ", " << (int)fLoGainLast;
+  out << ");" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the setup from a TEnv, eg:
+//   MJPedestal.MExtractor.HiGainFirst: 5
+//   MJPedestal.MExtractor.LoGainFirst: 5
+//   MJPedestal.MExtractor.HiGainLast:  10
+//   MJPedestal.MExtractor.LoGainLast:  10
+//   MJPedestal.MExtractor.SaturationLimit: 88
+//
+Int_t MExtractor::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    Byte_t hf = fHiGainFirst;
+    Byte_t lf = fLoGainFirst;
+    Byte_t hl = fHiGainLast;
+    Byte_t ll = fLoGainLast;
+
+    Bool_t rc = kFALSE;
+
+    if (IsEnvDefined(env, prefix, "HiGainFirst", print))
+    {
+        hf = GetEnvValue(env, prefix, "HiGainFirst", hf);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainFirst", print))
+    {
+        lf = GetEnvValue(env, prefix, "LoGainFirst", lf);
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "HiGainLast", print))
+    {
+        hl = GetEnvValue(env, prefix, "HiGainLast", hl);
+        rc = kTRUE;
+    }
+    if (IsEnvDefined(env, prefix, "LoGainLast", print))
+    {
+        ll = GetEnvValue(env, prefix, "LoGainLast", ll);
+        rc = kTRUE;
+    }
+
+    SetRange(hf, hl, lf, ll);
+
+    if (IsEnvDefined(env, prefix, "OffsetLoGain", print))
+    {
+        SetOffsetLoGain(GetEnvValue(env, prefix, "OffsetLoGain", fOffsetLoGain));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "SaturationLimit", print))
+    {
+        SetSaturationLimit(GetEnvValue(env, prefix, "SaturationLimit", fSaturationLimit));
+        rc = kTRUE;
+    }
+
+    if (IsEnvDefined(env, prefix, "NoiseCalculation", print))
+    {
+        SetNoiseCalculation(GetEnvValue(env, prefix, "NoiseCalculation", fNoiseCalculation));
+        rc = kTRUE;
+    }
+
+    // Be carefull: Returning kERROR is not forseen in derived classes
+    return rc;
+}
+
+void MExtractor::Print(Option_t *o) const
+{
+    if (IsA()==MExtractor::Class())
+        *fLog << GetDescriptor() << ":" << endl;
+
+    *fLog << " Hi Gain Range:      " << (int)fHiGainFirst << " " << (int)fHiGainLast << endl;
+    *fLog << " Lo Gain Range:      " << (int)fLoGainFirst << " " << (int)fLoGainLast << endl;
+    *fLog << " Gain Overlap to Lo: " << (int)fHiLoLast    << endl;
+    *fLog << " Saturation Lim:     " << (int)fSaturationLimit << endl;
+    *fLog << " Num Samples HiGain: " << fNumHiGainSamples << "  LoGain: " << fNumLoGainSamples << endl;
+}
Index: /tags/Mars-V0.9/msignal/MExtractor.h
===================================================================
--- /tags/Mars-V0.9/msignal/MExtractor.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MExtractor.h	(revision 9772)
@@ -0,0 +1,104 @@
+#ifndef MARS_MExtractor
+#define MARS_MExtractor
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractor                                                              //
+//                                                                         //
+// Base class for the signal extractors                                    //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalCam;
+class MExtractedSignalCam;
+
+class MExtractor : public MTask
+{
+private:
+
+  static const Float_t fgOffsetLoGain;     //! Default for fOffsetLoGain (now set to 1.51 (= 5ns)
+  
+  Bool_t  fNoiseCalculation;               //! Flag if extractor determines noise contribution from pedestal file.
+  
+protected:
+
+  static const Byte_t  fgSaturationLimit;  //! Default for fSaturationLimit (now set to: 254)
+  static const TString fgNamePedestalCam;  //! "MPedestalCam"
+  static const TString fgNameSignalCam;    //! "MExtractedSignalCam"
+  
+  Float_t fOffsetLoGain;                   // Offset of the low-gain signal w.r.t. the High-Gain slices
+
+  MPedestalCam        *fPedestals;         //! Pedestals of all pixels in the camera
+  MExtractedSignalCam *fSignals;           //! Extracted signal of all pixels in the camera
+                                       
+  MRawEvtData         *fRawEvt;            //! Raw event data (time slices)
+  MRawRunHeader       *fRunHeader;         //! RunHeader information
+                                       
+  Byte_t   fHiGainFirst;                   // First FADC slice nr. to extract the High Gain signal
+  Byte_t   fHiGainLast;                    // Last FADC slice nr. to extract the High Gain signal
+  Byte_t   fLoGainFirst;                   // First FADC slice nr. to extract the Low Gain signal
+  Byte_t   fLoGainLast;                    // Last FADC slice nr. to extract the Low Gain signal
+                                           
+  Byte_t   fHiLoLast;                      // Number of slices in fLoGainSamples counted for the High-Gain signal
+                                           
+  Float_t  fNumHiGainSamples;              // Number High Gain FADC slices used to extract the signal
+  Float_t  fNumLoGainSamples;              // Number Low  Gain FADC slices used to extract the signal
+                                           
+  Float_t  fSqrtHiGainSamples;             // Sqrt. nr. High Gain FADC slices used to extract the signal
+  Float_t  fSqrtLoGainSamples;             // Sqrt. nr. Low  Gain FADC slices used to extract the signal
+                                           
+  Byte_t   fSaturationLimit;               // Highest FADC slice value until being declared saturated
+  TString  fNamePedestalCam;               // Name of the 'MPedestalCam' container
+  TString  fNameSignalCam;                 // Name of the 'MExtractedSignalCam' container
+
+  virtual void FindSignalHiGain(Byte_t *firstused, Byte_t *lowgain, Float_t &sum, Byte_t &sat) const { }
+  virtual void FindSignalLoGain(Byte_t *firstused, Float_t &sum, Byte_t &sat) const { }
+  
+  Int_t   PreProcessStd(MParList *pList);
+  Int_t   PreProcess( MParList *pList );
+  Bool_t  ReInit    ( MParList *pList );
+  Int_t   Process   ();
+  void    StreamPrimitive(ofstream &out) const;
+  Int_t   ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+public:
+  MExtractor(const char *name=NULL, const char *title=NULL);
+  
+  void Clear(Option_t *o="") 
+    {
+      fHiGainFirst = fHiGainLast = fLoGainFirst = fLoGainLast = fHiLoLast = 0;
+    }
+
+  Byte_t  GetHiGainFirst()      const { return fHiGainFirst;      }
+  Byte_t  GetHiGainLast ()      const { return fHiGainLast ;      }
+  Byte_t  GetLoGainFirst()      const { return fLoGainFirst;      }
+  Byte_t  GetLoGainLast ()      const { return fLoGainLast ;      }
+  Float_t GetNumHiGainSamples() const { return fNumHiGainSamples; }
+  Float_t GetNumLoGainSamples() const { return fNumLoGainSamples; }
+  Float_t GetOffsetLoGain()     const { return fOffsetLoGain;     }
+
+  Bool_t  IsNoiseCalculation () const { return fNoiseCalculation; }
+  
+  virtual void SetRange(Byte_t hifirst=0, Byte_t hilast=0, Byte_t lofirst=0, Byte_t lolast=0);
+
+  void SetOffsetLoGain    ( const Float_t  f=fgOffsetLoGain          ) { fOffsetLoGain     = f;    }
+  void SetSaturationLimit ( const Byte_t lim=fgSaturationLimit       ) { fSaturationLimit  = lim;  }
+  void SetNamePedestalCam ( const char *name=fgNamePedestalCam.Data()) { fNamePedestalCam  = name; }
+  void SetNameSignalCam   ( const char *name=fgNameSignalCam.Data()  ) { fNameSignalCam    = name; }
+  void SetNoiseCalculation( const Bool_t   b=kTRUE                   ) { fNoiseCalculation = b;    }
+
+  void SetPedestals (MPedestalCam *pedcam)   { fPedestals = pedcam; }
+
+  void Print(Option_t *o="") const;
+
+  ClassDef(MExtractor, 5) // Signal Extractor Base Class
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MSignalCalc.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MSignalCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MSignalCalc.cc	(revision 9772)
@@ -0,0 +1,293 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MSignalCalc
+//
+//   This is a task which calculates the number of photons from the FADC
+//   time slices. At the moment it integrates simply the FADC values.
+//
+//  Input Containers:
+//   MRawEvtData, MPedestalCam
+//
+//  Output Containers:
+//   MSignalCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MSignalCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"       // MRawEvtData::GetNumPixels
+#include "MSignalCam.h"
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MSignalCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. b is the number of slices before the maximum slice,
+// a the number of slices behind the maximum slice which is taken as signal.
+//
+MSignalCalc::MSignalCalc(Byte_t b, Byte_t a, const char *name, const char *title)
+    : fBefore(b), fAfter(a)
+{
+    fName  = name  ? name  : "MSignalCalc";
+    fTitle = title ? title : "Task to calculate Cerenkov photons from raw data";
+
+    AddToBranchList("MRawEvtData.fHiGainPixId");
+    AddToBranchList("MRawEvtData.fLoGainPixId");
+    AddToBranchList("MRawEvtData.fHiGainFadcSamples");
+    AddToBranchList("MRawEvtData.fLoGainFadcSamples");
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawRunHeader
+//  - MRawEvtData
+//  - MPestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//  - MSignalCam
+//
+Int_t MSignalCalc::PreProcess(MParList *pList)
+{
+    fSkip = 0;
+
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << dbginf << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvt)
+    {
+        *fLog << dbginf << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCerPhotEvt = (MSignalCam*)pList->FindCreateObj("MSignalCam");
+    if (!fCerPhotEvt)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Bool_t MSignalCalc::ReInit(MParList *pList)
+{
+    fPedestals=NULL;
+
+    // This must be done in ReInit because in PreProcess the
+    // headers are not available
+    const MRawRunHeader *runheader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!runheader)
+        *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+    else
+    {
+        if (runheader->IsMonteCarloRun())
+            return kTRUE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindCreateObj("MPedestalCam");
+    if (runheader && !fPedestals)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MSignalCam container.
+//
+Int_t MSignalCalc::Process()
+{
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    while (pixel.Next())
+    {
+        Byte_t *ptr   = pixel.GetHiGainSamples();
+        Byte_t *max   = ptr+pixel.GetIdxMaxHiGainSample();
+	Byte_t *end   = ptr+fRawEvt->GetNumHiGainSamples();
+        Byte_t *first = max-fBefore;
+        Byte_t *last  = max+fAfter;
+
+        ULong_t sumb  = 0;   // sum background
+        ULong_t sqb   = 0;   // sum sqares background
+        ULong_t sumsb = 0;   // sum signal+background
+        ULong_t sqsb  = 0;   // sum sqares signal+background
+
+        Int_t sat  = 0; // saturates?
+        Int_t ishi = 0; // has a high content?
+        Int_t nb   = 0;
+        Int_t nsb  = 0;
+
+        if (*max==255)
+            sat++;
+
+        if (*max>80)
+            ishi++;
+
+        while (ptr<end)
+        {
+            if (ptr<first || ptr>last)
+            {
+                sumb += *ptr;
+                sqb  += *ptr* *ptr;
+                nb++;
+            }
+            else
+            {
+                sumsb += *ptr;
+                sqsb  += *ptr* *ptr;
+                nsb++;
+            }
+            ptr++;
+        }
+
+        if (sat==0 && ishi)
+        {
+            // Area: x9
+            ptr = pixel.GetLoGainSamples();
+            end = ptr+fRawEvt->GetNumLoGainSamples();
+
+            sumb = 0;   // sum background
+            sqb  = 0;   // sum sqares background
+            nb   = 0;
+
+            while (ptr<end)
+            {
+                // Background already calced from hi-gains!
+                sumb += *ptr;
+                sqb  += *ptr* *ptr;
+                nb++;
+                ptr++;
+            }
+        }
+
+        if (sat>1 && !ishi)
+        {
+            // Area: x9
+            ptr = pixel.GetLoGainSamples();
+            max = ptr+pixel.GetIdxMaxLoGainSample();
+
+            if (*max>250)
+            {
+                fSkip++;
+                return kCONTINUE;
+            }
+
+            end   = ptr+fRawEvt->GetNumLoGainSamples();
+            first = max-fBefore;
+            last  = max+fAfter;
+
+            sumsb = 0;   // sum signal+background
+            sqsb  = 0;   // sum sqares signal+background
+            //sumb  = 0;   // sum background
+            //sqb   = 0;   // sum sqares background
+
+            //nb = 0;
+            nsb = 0;
+            while (ptr<end)
+            {
+                if (ptr<first || ptr>last)
+                {
+                    /*
+                     // Background already calced from hi-gains!
+                    sumb += ptr[i];
+                    sqb  += ptr[i]*ptr[i];
+                    nb++;*/
+                }
+                else
+                {
+                    sumsb += *ptr;
+                    sqsb  += *ptr* *ptr;
+                    nsb++;
+                }
+                ptr++;
+            }
+        }
+
+        Float_t b  = (float)sumb/nb;       // background
+        Float_t sb = (float)sumsb/nsb;     // signal+background
+
+        Float_t msb  = (float)sqb/nb;      // mean square background
+        //Float_t mssb = (float)sqsb/nsb;    // mean square signal+background
+
+        Float_t sigb  = sqrt(msb-b*b);     // sigma background
+        //Float_t sigsb = sqrt(mssb-sb*sb);  // sigma signal+background
+
+        Float_t s   = sb-b;                // signal
+        Float_t sqs = sqsb-nsb*b;          // sum sqaures signal
+
+        Float_t mss  = (float)sqs/nsb;     // mean quare signal
+        //Float_t sigs = sqrt(mss-s*s);      // sigma signal
+
+        if (sat>1)
+            s*=10; // tgb has measured 9, but Florian said it's 10.
+
+        Int_t idx = pixel.GetPixelId();
+//        fCerPhotEvt->AddPixel(idx, s, sigs);
+
+        // Preliminary: Do not overwrite pedestals calculated by
+        // MMcPedestalCopy and MMcPedestalNSBAdd
+        if (fPedestals)
+            (*fPedestals)[idx].Set(b, sigb);
+    }
+
+//    fCerPhotEvt->FixSize();
+//    fCerPhotEvt->SetReadyToSave();
+
+    if (fPedestals)
+        fPedestals->SetReadyToSave();
+
+    return kTRUE;
+}
+
+Int_t MSignalCalc::PostProcess()
+{
+    if (GetNumExecutions()==0 || fSkip==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fSkip << " (" << setw(3) << (int)(fSkip*100/GetNumExecutions()) << "%) Evts skipped due to: lo gain saturated." << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/msignal/MSignalCalc.h
===================================================================
--- /tags/Mars-V0.9/msignal/MSignalCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MSignalCalc.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MSignalCalc
+#define MARS_MSignalCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MPedestalCam;
+class MSignalCam;
+class MRawRunHeader;
+
+class MSignalCalc : public MTask
+{
+private:
+    MPedestalCam  *fPedestals;  // Pedestals of all pixels in the camera
+    MRawEvtData   *fRawEvt;     // raw event data (time slices)
+    MSignalCam   *fCerPhotEvt; // Cerenkov Photon Event used for calculation
+    MRawRunHeader *fRunHeader;  // RunHeader information
+
+    Byte_t fBefore;
+    Byte_t fAfter;
+
+    Int_t fSkip;                //!
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+public:
+    MSignalCalc(Byte_t b=2, Byte_t a=5, const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MSignalCalc, 0)   // Task to calculate cerenkov photons from raw data
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/MSignalCam.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MSignalCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MSignalCam.cc	(revision 9772)
@@ -0,0 +1,662 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 03/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//            
+// MSignalCam
+//
+// Class Version 1:
+// ----------------
+//  - first version
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSignalCam.h"
+
+#include <math.h>
+#include <limits.h>
+#include <fstream>
+
+#include <TArrayD.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MSignalCam);
+ClassImp(MSignalCamIter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MSignalPix object for each pixel in the event
+//
+MSignalCam::MSignalCam(const char *name, const char *title) /*: fNumPixels(0)*/
+{
+    fName  = name  ? name  : "MSignalCam";
+    fTitle = title ? title : "(Number of Photon)-Event Information";
+
+    fPixels = new TClonesArray("MSignalPix", 0);
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// This is not yet implemented like it should.
+//
+/*
+void MSignalCam::Draw(Option_t* option) 
+{
+    //
+    //   FIXME!!! Here the Draw function of the CamDisplay
+    //   should be called to add the CamDisplay to the Pad.
+    //   The drawing should be done in MCamDisplay::Paint
+    //
+
+    //    MGeomCam *geom = fType ? new MGeomCamMagic : new MGeomCamCT1;
+    //    MCamDisplay *disp = new MCamDisplay(geom);
+    //    delete geom;
+    //    disp->DrawPhotNum(this);
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// reset counter and delete netries in list.
+//
+void MSignalCam::Reset()
+{
+    //fNumPixels        =  0;
+    fNumSinglePixels  =  0;
+    fSizeSinglePixels =  0;
+    fSizeSubIslands   =  0;
+    fSizeMainIsland   =  0;
+    //fMaxIndex         = -1;
+    fNumIslands       = -1;
+    //fLut.Set(0);
+
+    fNumPixelsSaturatedHiGain = -1;
+    fNumPixelsSaturatedLoGain = -1;
+
+    fPixels->ForEach(TObject, Clear)();
+}
+/*
+void MSignalCam::FixSize()
+{
+    fLut.Set(fMaxIndex+1);
+
+    if (fPixels->GetEntriesFast() == (Int_t)fNumPixels)
+        return;
+
+    fPixels->ExpandCreateFast(fNumPixels);
+}*/
+
+// --------------------------------------------------------------------------
+//
+//  Dump the cerenkov photon event to *fLog
+//
+void MSignalCam::Print(Option_t *) const
+{
+    const Int_t entries = fPixels->GetEntries();
+
+    *fLog << GetDescriptor() << dec << endl;
+    *fLog << " Number of Pixels: " << GetNumPixels() << "(" << entries << ")" << endl;
+
+    for (Int_t i=0; i<entries; i++ )
+        (*this)[i].Print();
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks if in the pixel list is an entry with pixel id
+//
+Bool_t MSignalCam::IsPixelExisting(Int_t id) const
+{
+    return GetPixById(id) ? kTRUE : kFALSE;
+} 
+
+// --------------------------------------------------------------------------
+//
+//   Checks if in the pixel list is an entry with pixel id
+//
+Bool_t MSignalCam::IsPixelUsed(Int_t id) const
+{
+    const MSignalPix *pix = GetPixById(id);
+    return pix ? pix->IsPixelUsed() : kFALSE;
+} 
+
+// --------------------------------------------------------------------------
+//
+//   Checks if in the pixel list is an entry with pixel id
+//
+Bool_t MSignalCam::IsPixelCore(Int_t id) const
+{
+    const MSignalPix *pix = GetPixById(id);
+    return pix ? pix->IsPixelCore() : kFALSE;
+} 
+
+// --------------------------------------------------------------------------
+//
+// get the minimum number of photons  of all valid pixels in the list
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MSignalCam::GetNumPhotonsMin(const MGeomCam *geom) const
+{
+    if (GetNumPixels() <= 0)
+        return -5.;
+
+    const UInt_t n = GetNumPixels();
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        //const UInt_t id = pix.GetPixId();
+        //if (id<0 || id>=n)
+        //    continue;
+
+        Float_t testval = pix.GetNumPhotons();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval < minval)
+            minval = testval;
+    }
+
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum number of photons of all valid pixels in the list
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MSignalCam::GetNumPhotonsMax(const MGeomCam *geom) const
+{
+    if (GetNumPixels() <= 0)
+        return 50.;
+
+    const UInt_t n = GetNumPixels();
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<n; i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        //const UInt_t id = pix.GetPixId();
+        //if (id<0 || id>=n)
+        //    continue;
+
+        Float_t testval = pix.GetNumPhotons();
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the minimum ratio of photons/error
+//
+Float_t MSignalCam::GetRatioMin(const MGeomCam *geom) const
+{
+    if (GetNumPixels() <= 0)
+        return -5.;
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetNumPhotons()/pix.GetErrorPhot();
+        if (geom)
+            testval *= TMath::Sqrt(geom->GetPixRatio(i/*pix.GetPixId()*/));
+
+        if (testval < minval)
+            minval = testval;
+    }
+
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum ratio of photons/error
+//
+Float_t MSignalCam::GetRatioMax(const MGeomCam *geom) const
+{
+    if (GetNumPixels() <= 0)
+        return -5.;
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetNumPhotons()/pix.GetErrorPhot();
+        if (geom)
+            testval *= TMath::Sqrt(geom->GetPixRatio(i/*pix.GetPixId()*/));
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+
+    return maxval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the minimum of error
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MSignalCam::GetErrorPhotMin(const MGeomCam *geom) const
+{
+    if (GetNumPixels() <= 0)
+        return 50.;
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetErrorPhot();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i/*pix.GetPixId()*/);
+
+        if (testval < minval)
+            minval = testval;
+    }
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum ratio of photons/error
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MSignalCam::GetErrorPhotMax(const MGeomCam *geom) const
+{
+    if (GetNumPixels() <= 0)
+        return 50.;
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<GetNumPixels(); i++)
+    {
+        const MSignalPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetErrorPhot();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i/*pix.GetPixId()*/);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+/*
+void MSignalCam::RemoveUnusedPixels()
+{
+    // Create iterator
+    TIter Next(fPixels);
+    MSignalPix *pix = NULL;
+
+    fMaxIndex = -1;
+
+    // Remove all unused pixels from list, calculate new fMaxIndex
+    while ((pix=(MSignalPix*)Next()))
+    {
+        if (!pix->IsPixelUsed())
+            fPixels->Remove(pix);
+        else
+            fMaxIndex = TMath::Max(fMaxIndex, pix->GetPixId());
+    }
+
+    // Crompress array
+    fPixels->Compress();
+
+    // Get new number of entries in array
+    fNumPixels=fPixels->GetEntriesFast();
+
+    // Rebuild lookup table
+    RebuildLut();
+}
+*/
+// --------------------------------------------------------------------------
+//
+// Return a pointer to the pixel with the requested idx. NULL if it doesn't
+// exist. The Look-up-table fLut is used. If its size is zero (according
+// to Rene this will happen if an old class object is loaded) we still
+// try to search in the array.
+//
+MSignalPix *MSignalCam::GetPixById(Int_t idx) const
+{
+    return (MSignalPix*)(fPixels->UncheckedAt(idx));
+    /*
+    if (idx<0)
+        return 0;
+
+    if (fLut.GetSize()>0)
+    {
+        if (idx>=fLut.GetSize())
+            return 0;
+        return fLut[idx]<0 ? 0 : (MSignalPix*)(fPixels->UncheckedAt(fLut[idx]));
+    }
+
+    TIter Next(fPixels);
+    MSignalPix *pix = NULL;
+
+    while ((pix=(MSignalPix*)Next()))
+        if (pix->GetPixId()==idx)
+            return pix;
+
+    return NULL;*/
+}
+
+MSignalPix *MSignalCam::AddPixel(Int_t idx, Float_t nph, Float_t er)
+{
+    /*
+    //
+    // If this is too slow or takes to much space we might use
+    // MGeomApply and an InitSize member function instead.
+    //
+    if (idx>=fLut.GetSize())
+    {
+        const Int_t n = fLut.GetSize();
+        fLut.Set(idx*2+1); //idx+1 is slower than idx*2+1
+        for (int i=n; i<idx*2+1; i++)
+            fLut[i] = -1;
+    }
+
+    fLut[idx] = fNumPixels;
+    if (idx>fMaxIndex)
+        fMaxIndex=idx;
+
+    return new ((*fPixels)[fNumPixels++]) MSignalPix(idx, nph, er);
+    */
+    //return new ((*fPixels)[idx]) MSignalPix(nph, er);
+
+    MSignalPix *pix = static_cast<MSignalPix*>((*fPixels)[idx]);
+    pix->Set(nph, er);
+    return pix;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function recursively finds all pixels of one island and assigns
+// the number num as island number to the pixel.
+//
+//  1) Check whether a pixel with the index idx exists, is unused
+//     and has not yet a island number assigned.
+//  2) Assign the island number num to the pixel
+//  3) Loop over all its neighbors taken from the geometry geom. For all
+//     neighbors recursively call this function (CalcIsland)
+//  4) Sum the size of the pixel and all neighbors newly assigned
+//     (by CalcIsland) to this island
+//
+// Returns the sum of the pixel size.
+//
+Double_t MSignalCam::CalcIsland(const MGeomCam &geom, Int_t idx, Int_t num)
+{
+    // Try to get the pixel information of a pixel with this index
+    MSignalPix *pix = GetPixById(idx);
+
+    // If a pixel with this index is not existing... do nothing.
+    if (!pix)
+        return 0;
+
+    // If an island number was already assigned to this pixel... do nothing.
+    if (pix->GetIdxIsland()>=0)
+        return 0;
+
+    // If the pixel is an unused pixel... do nothing.
+    if (!pix->IsPixelUsed())
+        return 0;
+
+    // Assign the new island number num to this used pixel
+    pix->SetIdxIsland(num);
+
+    // Get the geometry information (neighbors) of this pixel
+    const MGeomPix &gpix = geom[idx];
+
+    // Get the size of this pixel
+    Double_t size = pix->GetNumPhotons();
+
+    // Now do the same with all its neighbors and sum the
+    // sizes which they correspond to
+    const Int_t n = gpix.GetNumNeighbors();
+    for (int i=0; i<n; i++)
+        size += CalcIsland(geom, gpix.GetNeighbor(i), num);
+
+    // return size of this (sub)cluster
+    return size;
+}
+
+// --------------------------------------------------------------------------
+//
+// Each pixel which is maked as used is assigned an island number
+// (starting from 0). A pixel without an island number assigned
+// has island number -1.
+//
+// The index 0 corresponds to the island with the highest size (sum
+// of GetNumPhotons() in island). The size is decreasing with
+// increasing indices.
+//
+// The information about pixel neighbory is taken from the geometry
+// MGeomCam geom;
+//
+// You can access this island number of a pixel with a call to
+// MSignalPix->GetIdxIsland. The total number of islands available
+// can be accessed with MSignalCam->GetNumIslands.
+//
+// CalcIslands returns the number of islands found. If an error occurs,
+// eg the geometry has less pixels than the highest index stored, -1 is
+// returned.
+//
+Int_t MSignalCam::CalcIslands(const MGeomCam &geom)
+{
+    const UInt_t numpix = GetNumPixels();
+
+    if (/*fMaxIndex<0 ||*/ numpix==0)
+    {
+        *fLog << err << "ERROR - MSignalCam doesn't contain pixels!" << endl;
+        fNumIslands = 0;
+        return -1;
+    }
+/*
+    if ((UInt_t)fMaxIndex>=geom.GetNumPixels())
+    {
+        *fLog << err << "ERROR - MSignalCam::CalcIslands: Size mismatch - geometry too small!" << endl;
+        return -1;
+    }
+  */
+    // Create a list to hold the sizes of the islands (The maximum
+    // number of islands possible is roughly fNumPixels/4)
+    TArrayD size(numpix/3);
+
+    // Calculate Islands
+    Int_t   n=0;
+    Float_t totsize = 0;
+
+    for (UInt_t idx=0; idx<numpix; idx++)
+    {
+        const MSignalPix &pix = (*this)[idx];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        // This 'if' is necessary (although it is done in GetIsland, too)
+        // because otherwise the counter (n) would be wrong.
+        // So only 'start' a new island for used pixels (selected by
+        // using the Iterator) which do not yet belong to another island.
+        if (pix.GetIdxIsland()<0)
+        {
+            // Don't put this in one line! n is used twice...
+            const Double_t sz = CalcIsland(geom, idx/*pix->GetPixId()*/, n);
+            size[n++] = sz;
+            totsize += sz;
+        }
+    }
+
+    // Create an array holding the indices
+    TArrayI idxarr(n);
+
+    // Sort the sizes descending
+    TMath::Sort(n, size.GetArray(), idxarr.GetArray(), kTRUE);
+
+    // Replace island numbers by size indices -- After this
+    // islands indices are sorted by the island size
+    for (UInt_t idx=0; idx<numpix; idx++)
+    {
+        MSignalPix &pix = (*this)[idx];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        const Short_t i = pix.GetIdxIsland();
+
+        // Find new index
+        Short_t j;
+        for (j=0; j<n; j++)
+            if (idxarr[j]==i)
+                break;
+
+        pix.SetIdxIsland(j==n ? -1 : j);
+    }
+
+    // Now assign number of islands found
+    fNumIslands     = n;
+    fSizeSubIslands = n>0 ? totsize-size[idxarr[0]] : 0;
+    fSizeMainIsland = n>0 ? size[idxarr[0]] : 0;
+
+    // return number of island
+    return fNumIslands;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns, depending on the type flag:
+//
+//  0: Number of Photons*PixRatio
+//  1: Error*sqrt(PixRatio)
+//  2: Cleaning level = Num Photons*sqrt(PixRatio)/Error
+//  3: Number of Photons
+//  4: Error
+//  5: Island index
+//
+Bool_t MSignalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    MSignalPix *pix = GetPixById(idx);
+
+    if ((!pix || !pix->IsPixelUsed()) && type<6)
+        return kFALSE;
+
+    const Double_t ratio = cam.GetPixRatio(idx);
+
+    switch (type)
+    {
+    case 1:
+        val = pix->GetErrorPhot()*TMath::Sqrt(ratio);
+        return kTRUE;
+    case 2:
+        if (pix->GetErrorPhot()<=0)
+            return kFALSE;
+        val = pix->GetNumPhotons()*TMath::Sqrt(ratio)/pix->GetErrorPhot();
+        return kTRUE;
+    case 3:
+        val = pix->GetNumPhotons();
+        break;
+    case 4:
+        val = pix->GetErrorPhot();
+        break;
+    case 5:
+        val = pix->GetIdxIsland();
+        break;
+    case 6:
+        val = pix->GetArrivalTime();
+        break;
+    case 7:
+        if (pix->GetNumPhotons()*ratio<15) // maybe 15 as static data member?
+            return kFALSE;
+        val = pix->GetArrivalTime();
+        break;
+    default:
+        val = pix->GetNumPhotons()*ratio;
+        return kTRUE;
+    }
+    return kTRUE;
+}
+
+void MSignalCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MSignalCam::DrawPixelContent - not available." << endl;
+}
+
+TObject *MSignalCamIter::Next()
+{
+    if (!fUsedOnly)
+    {
+        fIdx++;
+        return TObjArrayIter::Next();
+    }
+
+    MSignalPix *pix;
+    while ((pix = (MSignalPix*)TObjArrayIter::Next()))
+    {
+        fIdx++;
+        if (pix->IsPixelUsed())
+            return pix;
+    }
+    return pix;
+}
Index: /tags/Mars-V0.9/msignal/MSignalCam.h
===================================================================
--- /tags/Mars-V0.9/msignal/MSignalCam.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MSignalCam.h	(revision 9772)
@@ -0,0 +1,119 @@
+#ifndef MARS_MSignalCam
+#define MARS_MSignalCam
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MSignalPix
+#include "MSignalPix.h"
+#endif
+
+class MGeomCam;
+class MSignalPix;
+class MSignalCamIter;
+
+class MSignalCam : public MParContainer, public MCamEvent
+{
+    friend class MSignalCamIter;
+private:
+    Short_t       fNumIslands;
+    Short_t       fNumSinglePixels;
+    Float_t       fSizeSinglePixels;
+    Float_t       fSizeSubIslands;
+    Float_t       fSizeMainIsland;
+
+    Int_t         fNumPixelsSaturatedHiGain;
+    Int_t         fNumPixelsSaturatedLoGain;
+    TClonesArray *fPixels;     //-> FIXME: Change TClonesArray away from a pointer?
+
+    Double_t CalcIsland(const MGeomCam &geom, Int_t idx, Int_t num);
+
+public:
+    MSignalCam(const char *name=NULL, const char *title=NULL);
+    ~MSignalCam() { delete fPixels; }
+
+    // Setter function to fill pixels
+    MSignalPix *AddPixel(Int_t idx, Float_t nph=0, Float_t er=0);
+    void InitSize(const UInt_t i)
+    {
+        fPixels->ExpandCreate(i);
+    }
+
+    // Getter functions
+    UInt_t  GetNumPixels() const { return fPixels->GetEntriesFast(); }
+    Short_t GetNumIslands() const { return fNumIslands; };
+    Short_t GetNumSinglePixels() const { return fNumSinglePixels; }
+    Float_t GetSizeSinglePixels() const { return fSizeSinglePixels; }
+    Float_t GetSizeSubIslands() const { return fSizeSubIslands; }
+    Float_t GetSizeMainIsland() const { return fSizeMainIsland; }
+    Int_t   GetNumPixelsSaturatedHiGain() const { return fNumPixelsSaturatedHiGain; }
+    Int_t   GetNumPixelsSaturatedLoGain() const { return fNumPixelsSaturatedLoGain; }
+
+    // Setter functions for use in image cleaning classes only
+    void SetSinglePixels(Short_t num, Float_t size)  { fNumSinglePixels=num; fSizeSinglePixels=size; }
+    void SetNumPixelsSaturated(UInt_t hi, UInt_t lo) { fNumPixelsSaturatedHiGain=hi;fNumPixelsSaturatedLoGain=lo; }
+
+    Bool_t  IsPixelExisting(Int_t id) const;
+    Bool_t  IsPixelUsed    (Int_t id) const;
+    Bool_t  IsPixelCore    (Int_t id) const;
+
+    Float_t GetNumPhotonsMin(const MGeomCam *geom=NULL) const;
+    Float_t GetNumPhotonsMax(const MGeomCam *geom=NULL) const;
+
+    Float_t GetRatioMin(const MGeomCam *geom=NULL) const;
+    Float_t GetRatioMax(const MGeomCam *geom=NULL) const;
+
+    Float_t GetErrorPhotMin(const MGeomCam *geom=NULL) const;
+    Float_t GetErrorPhotMax(const MGeomCam *geom=NULL) const;
+
+    // Getter functions to access single pixels
+    MSignalPix &operator[](int i)       { return *(MSignalPix*)(fPixels->UncheckedAt(i)); }
+    MSignalPix &operator[](int i) const { return *(MSignalPix*)(fPixels->UncheckedAt(i)); }
+
+    MSignalPix *GetPixById(Int_t idx) const;
+
+    // Functions to change the contained data
+    void Scale(Double_t f) { fPixels->ForEach(MSignalPix, Scale)(f); }
+    Int_t CalcIslands(const MGeomCam &geom);
+
+    // class MParContainer
+    void Reset();
+
+    // class TObject
+    void Print(Option_t *opt=NULL) const;
+    void Clear(Option_t *opt=NULL) { Reset(); }
+
+    // class MCamEvent
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+    void DrawPixelContent(Int_t num) const;
+
+    // To build an iterator for this class
+    operator TIterator*() const;
+
+    ClassDef(MSignalCam, 1) // class for an event containing cerenkov photons
+};
+
+class MSignalCamIter : public TObjArrayIter
+{
+private:
+    Bool_t fUsedOnly;
+    Int_t fIdx;
+
+public:
+    MSignalCamIter(const MSignalCam *evt, Bool_t usedonly=kTRUE, Bool_t dir=kIterForward) : TObjArrayIter(evt->fPixels, dir), fUsedOnly(usedonly), fIdx(-1) { }
+    TObject *Next();
+    void Reset() { fIdx=-1; TObjArrayIter::Reset(); }
+    TIterator &operator=(const TIterator &) { return *this; }
+    Int_t GetIdx() const { return fIdx; }
+    ClassDef(MSignalCamIter, 0)
+};
+
+inline MSignalCam::operator TIterator*() const { return new MSignalCamIter(this); }
+
+#endif
Index: /tags/Mars-V0.9/msignal/MSignalPix.cc
===================================================================
--- /tags/Mars-V0.9/msignal/MSignalPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MSignalPix.cc	(revision 9772)
@@ -0,0 +1,102 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Harald Kornmayer 1/2001
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MSignalPix
+//
+// Storage container for the signal in a pixel in number of photons.
+//
+// NOTE: This container is NOT ment for I/O. Write it to a file on your
+//       own risk!
+//
+// fIsSaturated: boolean variable set to kTRUE whenever one or more of
+//               the low gain FADC slices of the pixel is in saturation.
+//
+// Version 2:
+// ----------
+//  - added fIsSaturated
+//
+// Version 4:
+// ----------
+//  - added fIsHGSaturated
+//
+// Version 5:
+// ----------
+//  - added fIdxIsland
+//
+// Version 6:
+// ----------
+//  - put the '!' into the comment line for
+//      Bool_t   fIsCore;        //! the pixel is a Core pixel -> kTRUE
+//      Short_t  fRing;          //! NT: number of analyzed rings around the core pixels, fRing>0 means: used, fRing= 0 means: unused, fRing= -1 means: unmapped (no possible to use in the calculation of the image parameters)
+//      Short_t  fIdxIsland;     //! the pixel is a Core pixel -> kTRUE
+//      Bool_t   fIsHGSaturated; //! the pixel's high gain is saturated
+//    This is a queick hack to gain storage space - the structure of
+//    the container for calibrated data will change soon.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MSignalPix.h"
+
+#include "MLog.h"
+
+ClassImp(MSignalPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. The pixel is assumed as used and not a core pixel.
+// NT 29/04/2003: A pixel is considered used when fRing > 0.
+//
+MSignalPix::MSignalPix(Float_t phot, Float_t errphot) :
+    fIsCore(kFALSE), fRing(1), fIdxIsland(-1),
+    fPhot(phot), fErrPhot(errphot)
+{
+    MMath::ReducePrecision(fPhot);
+    MMath::ReducePrecision(fErrPhot);
+} 
+
+void MSignalPix::Clear(Option_t *o)
+{
+    fIsCore    =  kFALSE;
+    fRing      =  1;
+    fIdxIsland = -1;
+    fPhot      =  0;
+    fErrPhot   =  0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Print information to gLog.
+//
+void MSignalPix::Print(Option_t *) const
+{ 
+    gLog << GetDescriptor();// << " Pixel: "<< fPixId;
+    gLog << (fRing>0?"   Used ":" Unused ");
+    gLog << (fIsCore?" Core ":"      ");
+    gLog << "Nphot= " << fPhot << " Error(Nphot)=" << fErrPhot << endl;
+}
Index: /tags/Mars-V0.9/msignal/MSignalPix.h
===================================================================
--- /tags/Mars-V0.9/msignal/MSignalPix.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/MSignalPix.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MSignalPix
+#define MARS_MSignalPix
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MMath
+#include "MMath.h"
+#endif
+
+class MSignalPix : public MParContainer
+{
+private:
+    Bool_t   fIsCore;        //! the pixel is a Core pixel -> kTRUE
+    Short_t  fRing;          //! NT: number of analyzed rings around the core pixels, fRing>0 means: used, fRing= 0 means: unused, fRing= -1 means: unmapped (no possible to use in the calculation of the image parameters)
+    Short_t  fIdxIsland;     //! the pixel is a Core pixel -> kTRUE
+
+    Float_t  fPhot;          // The number of Cerenkov photons
+    Float_t  fErrPhot;       // the error of fPhot
+    Float_t  fArrivalTime;   // Calibrated Arrival Time
+    // FIXME: arrival time t, and it's error sigma t
+
+public:
+    MSignalPix(/*Int_t pix=-1,*/ Float_t phot=0, Float_t errphot=0);
+
+    void Clear(Option_t *o=0);
+
+    Float_t GetNumPhotons() const       { return fPhot;    }
+    Float_t GetErrorPhot() const        { return fErrPhot; }
+    Float_t GetArrivalTime() const      { return fArrivalTime; }
+    
+    Bool_t  IsPixelUsed() const         { return fRing>0; }
+    Bool_t  IsPixelUnmapped() const     { return fRing==-1; }
+    void    SetPixelUnused()            { fRing=0; }
+    void    SetPixelUsed()              { fRing=1; }
+    void    SetPixelUnmapped()          { fRing=-1;}
+    void    SetIdxIsland(Short_t num)   { fIdxIsland=num; }
+    Short_t GetIdxIsland() const        { return fIdxIsland; }
+
+    void    SetRing(UShort_t r)         { fRing = r;   }
+    Short_t GetRing() const             { return fRing;}
+
+    void    SetPixelCore(Bool_t b=kTRUE){ fIsCore = b; }
+    Bool_t  IsPixelCore() const         { return fIsCore;  }
+
+    void    SetNumPhotons(Float_t f)    { MMath::ReducePrecision(f); fPhot     = f; }
+    void    SetErrorPhot(Float_t f)     { MMath::ReducePrecision(f); fErrPhot = f; }
+    void    Set(Float_t np, Float_t ep) { MMath::ReducePrecision(np); MMath::ReducePrecision(ep);  fPhot = np; fErrPhot = ep; }
+    void    SetArrivalTime(Float_t tm)  { MMath::ReducePrecision(tm); fArrivalTime = tm; }
+
+    void    AddNumPhotons(Float_t f)    { fPhot += f; }
+
+    void    Scale(Float_t f)            { fPhot/=f; }
+
+    void    Print(Option_t *opt = NULL) const;
+    Bool_t  IsSortable() const { return kTRUE; }
+
+    ClassDef(MSignalPix, 6)  // class containing information about the Cerenkov Photons in a pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/msignal/Makefile
===================================================================
--- /tags/Mars-V0.9/msignal/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/msignal/Makefile	(revision 9772)
@@ -0,0 +1,67 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Signal
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES =  -I. -I../mbase -I../mgui -I../mraw -I../manalysis \
+            -I../mgeom -I../mtools -I../mpedestal -I../mbadpixels
+
+# mgui (MCamEvent):         MExtractSignalCam
+# mgeom(MGeomCam):          MArrivalTime
+# mtools(MCubicSpline):     MArrivalTime
+# mraw (MRawEvtData):       MExtractSignal
+# manalysis (MPedestalCam): MExtractSignal
+
+SRCFILES = MExtractedSignalCam.cc \
+           MExtractedSignalPix.cc \
+	   MExtractedSignalPINDiode.cc \
+	   MExtractedSignalBlindPixel.cc \
+           MExtractor.cc \
+           MExtractFixedWindow.cc \
+           MExtractSlidingWindow.cc \
+           MExtractFixedWindowPeakSearch.cc \
+           MExtractFixedWindowSpline.cc \
+           MExtractAmplitudeSpline.cc \
+           MExtractSignal.cc \
+           MExtractSignal2.cc \
+           MExtractSignal3.cc \
+           MExtractSignalABcorr.cc \
+	   MExtractPINDiode.cc \
+	   MExtractBlindPixel.cc \
+           MExtractTime.cc \
+           MExtractTimeSpline.cc \
+           MExtractTimeFastSpline.cc \
+           MExtractTimeHighestIntegral.cc \
+           MExtractTimeAndCharge.cc \
+           MExtractTimeAndChargeSlidingWindow.cc \
+           MExtractTimeAndChargeSpline.cc \
+           MExtractTimeAndChargeDigitalFilter.cc \
+           MExtractTimeAndChargeDigitalFilterPeakSearch.cc \
+           MSignalCam.cc \
+           MSignalPix.cc \
+           MSignalCalc.cc \
+           MArrivalTimeCam.cc \
+	   MArrivalTimePix.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/msignal/SignalIncl.h
===================================================================
--- /tags/Mars-V0.9/msignal/SignalIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/SignalIncl.h	(revision 9772)
@@ -0,0 +1,7 @@
+#ifndef __CINT__
+
+#include <TArrayC.h>
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/msignal/SignalLinkDef.h
===================================================================
--- /tags/Mars-V0.9/msignal/SignalLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/msignal/SignalLinkDef.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MExtractedSignalCam+;
+#pragma link C++ class MExtractedSignalPix+;
+#pragma link C++ class MExtractedSignalPINDiode+;
+#pragma link C++ class MExtractedSignalBlindPixel+;
+
+#pragma link C++ class MExtractSignal+;
+#pragma link C++ class MExtractSignal2+;
+#pragma link C++ class MExtractSignal3+;
+#pragma link C++ class MExtractSignalABcorr+;
+
+#pragma link C++ class MExtractor+;
+#pragma link C++ class MExtractFixedWindow+;
+#pragma link C++ class MExtractSlidingWindow+;
+#pragma link C++ class MExtractFixedWindowPeakSearch+;
+#pragma link C++ class MExtractFixedWindowSpline+;
+#pragma link C++ class MExtractAmplitudeSpline+;
+#pragma link C++ class MExtractPINDiode+;
+#pragma link C++ class MExtractBlindPixel+;
+
+#pragma link C++ class MExtractTime+;
+#pragma link C++ class MExtractTimeSpline+;
+#pragma link C++ class MExtractTimeFastSpline+;
+#pragma link C++ class MExtractTimeHighestIntegral+;
+
+#pragma link C++ class MExtractTimeAndCharge+;
+#pragma link C++ class MExtractTimeAndChargeSlidingWindow+;
+#pragma link C++ class MExtractTimeAndChargeSpline+;
+#pragma link C++ class MExtractTimeAndChargeDigitalFilter+;
+#pragma link C++ class MExtractTimeAndChargeDigitalFilterPeakSearch+;
+
+#pragma link C++ class MArrivalTimeCam+;
+#pragma link C++ class MArrivalTimePix+;
+
+#pragma link C++ class MSignalPix+;
+#pragma link C++ class MSignalCam+;
+#pragma link C++ class MSignalCamIter+;
+#pragma link C++ class MSignalCalc+;
+
+#endif
Index: /tags/Mars-V0.9/msignal/calibration_weights_UV.dat
===================================================================
--- /tags/Mars-V0.9/msignal/calibration_weights_UV.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/calibration_weights_UV.dat	(revision 9772)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+-0.135294 -0.845262
+-0.307049 -0.967471
+-0.487632 -0.971773
+-0.614716 -0.913206
+-0.721512 -0.827152
+-0.775976 -0.717254
+-0.845087 -0.509839
+-0.955046 -0.209035
+-1.00224 0.2472
+-0.903555 0.817093
+-0.556441 1.76312
+-0.194211 2.12631
+0.219836 2.22675
+0.513689 2.28873
+0.822468 2.38924
+0.971705 2.34813
+1.18817 2.07459
+1.5515 1.81714
+1.97131 1.69619
+2.33012 1.28281
+2.45352 0.287745
+2.4015 -0.339334
+2.25982 -0.827606
+2.11244 -1.2129
+1.92951 -1.54897
+1.83142 -1.8268
+1.64896 -1.90661
+1.28279 -2.00748
+0.793985 -2.24883
+0.262309 -2.15446
+-0.0559972 -1.30597
+-0.177972 -0.825199
+-0.226058 -0.373441
+-0.231339 -0.152992
+-0.236687 -0.0444464
+-0.247735 0.101245
+-0.248764 0.294579
+-0.189974 0.354396
+-0.109625 0.435904
+-0.00029747 0.373219
+0.0438014 0.13228
+0.049418 0.0464338
+0.0405008 -0.0314221
+0.0302813 -0.0478527
+0.027379 -0.00159103
+0.0416632 -0.0947573
+0.0300094 -0.200671
+-0.0135778 -0.145184
+-0.0426915 -0.130517
+-0.0753977 -0.0119239
+-0.0810973 0.0442347
+-0.0835202 0.0186848
+-0.074967 0.051449
+-0.0655645 0.0449615
+-0.0661155 0.0215451
+-0.0665032 0.0587461
+-0.0606857 0.0855372
+-0.0374867 0.0523137
+-0.0270469 0.0100236
+-0.0249475 -0.0585201
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273
+0.038191 -0.00418687
+0.0386966 0.0212324
+0.0402881 0.0744799
+0.0415794 0.229615
+0.0598731 0.44332
+0.0758477 0.661518
+0.101509 1.10641
+0.159323 1.64997
+0.497256 2.83685
+0.245087 3.27499
+0.140546 2.46177
+0.58086 2.2849
+0.632721 2.45587
+0.72819 2.52835
+0.889583 2.48099
+0.980812 2.50031
+1.09885 2.55892
+1.21374 2.78769
+1.61928 3.08069
+1.38544 1.95583
+1.31998 1.1792
+1.50633 0.591226
+1.50916 0.0793899
+1.5008 -0.33188
+1.47339 -0.575386
+1.45362 -0.915309
+1.40214 -1.31593
+1.34175 -1.77904
+1.0661 -2.05471
+1.31087 -1.49798
+1.33793 -1.34758
+1.10172 -1.21719
+1.08133 -1.09356
+1.04007 -0.981455
+0.976745 -1.08299
+0.930979 -1.14774
+0.874203 -1.18348
+0.816708 -1.20126
+0.587354 -1.92869
+0.783078 -1.89621
+0.792771 -1.03439
+0.622278 -0.781807
+0.61184 -0.745831
+0.578792 -0.683741
+0.537336 -0.596328
+0.51443 -0.592858
+0.482294 -0.560586
+0.462351 -0.827587
+0.317989 -1.05649
+0.459672 -0.775035
+0.468287 -0.619961
+0.374182 -0.31635
+0.376946 -0.225242
+0.367075 -0.347444
+0.340737 -0.393231
+0.321054 -0.187384
+0.320654 -0.225558
+0.302148 -0.399499
+0.232954 -0.607578
Index: /tags/Mars-V0.9/msignal/calibration_weights_UV4.dat
===================================================================
--- /tags/Mars-V0.9/msignal/calibration_weights_UV4.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/calibration_weights_UV4.dat	(revision 9772)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.735581 -0.673266
+-0.800386 -0.47606
+-0.902801 -0.192719
+-0.945945 0.237423
+-0.851618 0.770424
+-0.598107 1.28444
+-0.290663 1.69546
+0.0967702 1.89144
+0.362204 1.98161
+0.610111 2.06506
+0.919902 2.20752
+1.12282 1.94486
+1.46305 1.70309
+1.85728 1.58904
+2.19155 1.21011
+2.37154 0.603168
+2.37187 0.000360131
+2.25639 -0.535921
+2.12495 -0.948388
+1.97328 -1.286
+1.72155 -1.70358
+1.55218 -1.75991
+1.21489 -1.86382
+0.759117 -2.09403
+0.266577 -2.03167
+-0.102906 -1.60487
+-0.284545 -1.16641
+-0.367327 -0.679947
+-0.376403 -0.3943
+-0.379568 -0.229929
+-0.218954 0.0443019
+-0.22659 0.163101
+-0.195144 0.249649
+-0.136182 0.328464
+-0.0541723 0.334035
+-0.00249719 0.207255
+0.00794832 0.102902
+0.00785676 0.0396167
+0.00459524 0.0111356
+0.00887564 0.0405
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+0.178287 2.98244
+0.0799794 2.25048
+0.501997 2.04566
+0.559993 2.18952
+0.636334 2.28558
+0.784832 2.29757
+0.894393 2.36602
+1.01571 2.62578
+1.14191 3.14701
+1.70405 4.27635
+1.25503 1.69442
+1.19843 1.00804
+1.36974 0.493838
+1.37759 0.0452029
+1.37174 -0.336051
+1.34423 -0.563321
+1.31669 -0.852661
+1.26602 -1.28826
+1.20062 -1.85625
+0.874127 -2.44773
+1.2433 -1.47361
+1.27171 -1.3052
+1.03025 -1.1211
+1.00417 -0.992811
+0.968251 -0.911359
+0.907626 -1.02038
+0.852293 -1.06813
+0.797164 -1.16276
+0.739386 -1.25445
+0.447754 -2.34757
+0.777349 -1.83155
+0.779564 -1.01577
+0.600426 -0.733238
+0.5863 -0.688006
+0.557156 -0.650488
+0.514926 -0.584649
+0.485323 -0.569089
+0.454047 -0.573249
+0.429026 -0.907077
+0.245526 -1.35434
Index: /tags/Mars-V0.9/msignal/calibration_weights_UV46.dat
===================================================================
--- /tags/Mars-V0.9/msignal/calibration_weights_UV46.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/calibration_weights_UV46.dat	(revision 9772)
@@ -0,0 +1,104 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.735581 -0.673266
+-0.800386 -0.47606
+-0.902801 -0.192719
+-0.945945 0.237423
+-0.851618 0.770424
+-0.598107 1.28444
+-0.290663 1.69546
+0.0967702 1.89144
+0.362204 1.98161
+0.610111 2.06506
+0.919902 2.20752
+1.12282 1.94486
+1.46305 1.70309
+1.85728 1.58904
+2.19155 1.21011
+2.37154 0.603168
+2.37187 0.000360131
+2.25639 -0.535921
+2.12495 -0.948388
+1.97328 -1.286
+1.72155 -1.70358
+1.55218 -1.75991
+1.21489 -1.86382
+0.759117 -2.09403
+0.266577 -2.03167
+-0.102906 -1.60487
+-0.284545 -1.16641
+-0.367327 -0.679947
+-0.376403 -0.3943
+-0.379568 -0.229929
+-0.218954 0.0443019
+-0.22659 0.163101
+-0.195144 0.249649
+-0.136182 0.328464
+-0.0541723 0.334035
+-0.00249719 0.207255
+0.00794832 0.102902
+0.00785676 0.0396167
+0.00459524 0.0111356
+0.00887564 0.0405
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273
+0.038191 -0.00418687
+0.0386966 0.0212324
+0.0402881 0.0744799
+0.0415794 0.229615
+0.0598731 0.44332
+0.0758477 0.661518
+0.101509 1.10641
+0.159323 1.64997
+0.497256 2.83685
+0.245087 3.27499
+0.140546 2.46177
+0.58086 2.2849
+0.632721 2.45587
+0.72819 2.52835
+0.889583 2.48099
+0.980812 2.50031
+1.09885 2.55892
+1.21374 2.78769
+1.61928 3.08069
+1.38544 1.95583
+1.31998 1.1792
+1.50633 0.591226
+1.50916 0.0793899
+1.5008 -0.33188
+1.47339 -0.575386
+1.45362 -0.915309
+1.40214 -1.31593
+1.34175 -1.77904
+1.0661 -2.05471
+1.31087 -1.49798
+1.33793 -1.34758
+1.10172 -1.21719
+1.08133 -1.09356
+1.04007 -0.981455
+0.976745 -1.08299
+0.930979 -1.14774
+0.874203 -1.18348
+0.816708 -1.20126
+0.587354 -1.92869
+0.783078 -1.89621
+0.792771 -1.03439
+0.622278 -0.781807
+0.61184 -0.745831
+0.578792 -0.683741
+0.537336 -0.596328
+0.51443 -0.592858
+0.482294 -0.560586
+0.462351 -0.827587
+0.317989 -1.05649
+0.459672 -0.775035
+0.468287 -0.619961
+0.374182 -0.31635
+0.376946 -0.225242
+0.367075 -0.347444
+0.340737 -0.393231
+0.321054 -0.187384
+0.320654 -0.225558
+0.302148 -0.399499
+0.232954 -0.607578
Index: /tags/Mars-V0.9/msignal/calibration_weights_UV_logaintest.dat
===================================================================
--- /tags/Mars-V0.9/msignal/calibration_weights_UV_logaintest.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/calibration_weights_UV_logaintest.dat	(revision 9772)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time) 
+	-0.123301	0.281176
+	-0.0989162	0.189014
+	-0.0744146	0.109115
+	-0.0579067	-0.00970563
+	-0.08634	-0.175186
+	-0.153627	-0.35012
+	-0.248048	-0.509518
+	-0.368571	-0.608264
+	-0.457643	-0.603256
+	-0.514441	-0.531277
+	-0.63496	-0.822575
+	-0.700206	-0.606683
+	-0.779942	-0.340557
+	-0.792388	0.0335111
+	-0.691357	0.514475
+	-0.473932	1.0154
+	-0.210221	1.47267
+	0.143091	1.75857
+	0.413054	1.93247
+	0.689521	2.07962
+	0.848796	2.39505
+	1.08333	2.1765
+	1.43826	1.98218
+	1.81403	1.94894
+	2.1227	1.64159
+	2.30177	1.09338
+	2.33713	0.518179
+	2.27011	-0.077444
+	2.17053	-0.546523
+	2.03214	-0.930314
+	1.99228	-1.61593
+	1.80151	-1.73669
+	1.4472	-1.90893
+	0.979215	-2.22413
+	0.476345	-2.27293
+	0.0815403	-1.99688
+	-0.158713	-1.69048
+	-0.332713	-1.22056
+	-0.412026	-0.947722
+	-0.486163	-0.785726
+	-0.559431	0.115011
+	-0.524321	0.280475
+	-0.453902	0.377856
+	-0.352013	0.515131
+	-0.221563	0.552559
+	-0.128697	0.485583
+	-0.0563877	0.46736
+	0.00608425	0.387754
+	0.0461686	0.367825
+	0.0998553	0.408476
+	0.0575847	-0.020068
+	0.0361577	-0.0950281
+	0.021779	-0.0724483
+	0.00683997	-0.0950705
+	-0.0143629	-0.0588636
+	-0.014106	-0.0472336
+	-0.0404541	-0.112081
+	-0.0567406	-0.0926997
+	-0.069889	-0.109181
+	-0.0940175	-0.135339
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time) 
+	-0.123301	0.281176
+	-0.0989162	0.189014
+	-0.0744146	0.109115
+	-0.0579067	-0.00970563
+	-0.08634	-0.175186
+	-0.153627	-0.35012
+	-0.248048	-0.509518
+	-0.368571	-0.608264
+	-0.457643	-0.603256
+	-0.514441	-0.531277
+	-0.63496	-0.822575
+	-0.700206	-0.606683
+	-0.779942	-0.340557
+	-0.792388	0.0335111
+	-0.691357	0.514475
+	-0.473932	1.0154
+	-0.210221	1.47267
+	0.143091	1.75857
+	0.413054	1.93247
+	0.689521	2.07962
+	0.848796	2.39505
+	1.08333	2.1765
+	1.43826	1.98218
+	1.81403	1.94894
+	2.1227	1.64159
+	2.30177	1.09338
+	2.33713	0.518179
+	2.27011	-0.077444
+	2.17053	-0.546523
+	2.03214	-0.930314
+	1.99228	-1.61593
+	1.80151	-1.73669
+	1.4472	-1.90893
+	0.979215	-2.22413
+	0.476345	-2.27293
+	0.0815403	-1.99688
+	-0.158713	-1.69048
+	-0.332713	-1.22056
+	-0.412026	-0.947722
+	-0.486163	-0.785726
+	-0.559431	0.115011
+	-0.524321	0.280475
+	-0.453902	0.377856
+	-0.352013	0.515131
+	-0.221563	0.552559
+	-0.128697	0.485583
+	-0.0563877	0.46736
+	0.00608425	0.387754
+	0.0461686	0.367825
+	0.0998553	0.408476
+	0.0575847	-0.020068
+	0.0361577	-0.0950281
+	0.021779	-0.0724483
+	0.00683997	-0.0950705
+	-0.0143629	-0.0588636
+	-0.014106	-0.0472336
+	-0.0404541	-0.112081
+	-0.0567406	-0.0926997
+	-0.069889	-0.109181
+	-0.0940175	-0.135339
Index: /tags/Mars-V0.9/msignal/calibration_weights_blue.dat
===================================================================
--- /tags/Mars-V0.9/msignal/calibration_weights_blue.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/calibration_weights_blue.dat	(revision 9772)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+-0.605623 -1.11881
+-0.764793 -1.10531
+-0.86103 -1.1367
+-0.90412 -1.1014
+-0.953294 -0.946356
+-1.01994 -0.665753
+-1.11013 -0.378876
+-1.26403 -0.0260436
+-1.22181 0.842651
+-0.482293 1.76104
+0.284962 2.31134
+0.611944 2.38608
+0.8414 2.6344
+0.951306 2.73879
+1.07472 2.52913
+1.16903 2.19412
+1.3172 1.95371
+1.87082 1.59091
+2.61481 1.15287
+2.86574 0.237112
+2.50204 -0.745746
+2.30737 -1.23243
+2.13806 -1.71705
+2.07571 -2.05767
+1.9644 -2.17221
+1.9001 -2.20019
+1.70573 -2.2269
+1.03329 -2.16862
+-0.1132 -2.07192
+-0.746055 -1.21823
+-0.489468 -0.0876857
+-0.310262 0.331252
+-0.227732 0.591827
+-0.182658 0.617976
+-0.184889 0.639342
+-0.153689 0.670494
+-0.0841314 0.571983
+0.086702 0.514434
+0.343918 0.474596
+0.470154 0.180966
+0.351024 -0.122442
+0.303044 -0.230226
+0.262699 -0.349064
+0.243201 -0.354185
+0.238138 -0.351845
+0.226132 -0.380497
+0.161807 -0.296499
+0.0464236 -0.18346
+-0.0407385 -0.132386
+-0.0350163 0.0786269
+0.0827034 0.113955
+0.0865831 0.097233
+0.103917 0.121197
+0.108297 0.106561
+0.109348 0.104756
+0.128509 0.0501978
+0.142551 -0.0127797
+0.146076 -0.0501855
+0.11112 -0.100616
+0.0495201 -0.157116
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0911607 1.86069
+0.134612 2.42822
+0.11393 2.54774
+0.239782 2.89304
+0.38454 3.39314
+0.506359 4.46877
+0.655883 5.52101
+0.73793 6.57492
+0.626733 5.91162
+0.622878 5.2788
+0.875104 5.70684
+1.0185 4.05712
+1.03351 2.62644
+1.17511 1.6677
+1.25046 1.13376
+1.2901 0.924149
+1.31334 0.437335
+1.31663 0.507458
+1.31277 0.427002
+1.32304 -0.0901286
+1.38784 -0.706265
+1.37487 -0.901873
+1.36665 -0.786355
+1.32075 -0.6806
+1.28396 -0.713758
+1.26222 -1.18985
+1.21343 -1.68063
+1.19453 -2.03872
+1.2299 -2.06586
+1.22115 -1.76823
+1.18887 -2.03884
+1.14439 -1.67582
+1.13325 -1.30011
+1.06283 -1.09575
+1.00479 -1.1072
+0.966371 -1.32491
+0.920684 -1.40639
+0.905236 -1.87588
+0.933327 -1.81847
+0.931535 -1.5951
+0.890207 -1.70808
+0.853004 -0.945718
+0.845928 -0.714034
+0.810665 -0.763716
+0.766765 -0.886576
+0.733744 -0.826087
+0.710135 -0.687648
+0.701588 -1.26231
+0.71366 -1.04794
+0.719342 -0.998027
+0.732828 -1.5976
+0.699252 -1.20079
+0.690217 -0.920725
+0.639485 -0.679626
+0.604624 -0.636375
+0.582796 -0.785263
+0.555253 -0.706474
+0.55048 -0.932222
+0.560973 -0.88078
+0.567122 -0.86762
Index: /tags/Mars-V0.9/msignal/calibration_weights_blue4.dat
===================================================================
--- /tags/Mars-V0.9/msignal/calibration_weights_blue4.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/calibration_weights_blue4.dat	(revision 9772)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.902168 -0.585312
+-0.984524 -0.32831
+-1.12036 -0.0157807
+-1.08172 0.756907
+-0.427114 1.56066
+0.186216 1.92954
+0.509304 2.06633
+0.699549 2.27174
+0.776041 2.3434
+0.8686 2.15573
+1.04178 1.93083
+1.17443 1.71284
+1.66255 1.38999
+2.31293 1.00065
+2.53376 0.210701
+2.3316 -0.460552
+2.11661 -0.992708
+1.95813 -1.43769
+1.91826 -1.72912
+1.83121 -1.83277
+1.6757 -1.91204
+1.50581 -1.93994
+0.91874 -1.89528
+-0.086052 -1.81483
+-0.651007 -1.09872
+-0.615758 -0.392913
+-0.393843 0.132625
+-0.284098 0.418838
+-0.258366 0.437323
+-0.262974 0.468126
+0.0180038 0.377062
+0.0449773 0.327324
+0.128299 0.336854
+0.297876 0.323257
+0.402965 0.18143
+0.373367 -0.00201841
+0.315525 -0.13922
+0.279239 -0.242999
+0.275543 -0.242753
+0.279876 -0.233989
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+0.65753 5.13268
+0.809076 4.33176
+0.831737 3.71302
+1.1134 4.00049
+1.43596 5.0645
+1.79077 7.81167
+2.41467 11.9052
+2.51185 13.4427
+2.24589 11.6437
+2.4845 12.1853
+1.22189 -0.852173
+1.20546 -1.07064
+1.19308 -1.07012
+1.1102 -1.13675
+1.03029 -1.34782
+0.866849 -3.1326
+0.41862 -6.79244
+0.502624 -6.45882
+0.577826 -6.33469
+0.49339 -6.35753
+1.0849 -2.02333
+1.03231 -1.8621
+1.01565 -1.75607
+0.879394 -2.04283
+0.704799 -2.79451
+0.524634 -4.2905
+0.242824 -6.03388
+0.198697 -6.9872
+0.323405 -6.28596
+0.175753 -6.97616
+0.843516 -1.76069
+0.790041 -1.14628
+0.778283 -1.04629
+0.693194 -1.51392
+0.537627 -2.42885
+0.460845 -2.70401
+0.459979 -2.10235
+0.239633 -4.66788
+0.413692 -3.09085
+0.310226 -3.82814
Index: /tags/Mars-V0.9/msignal/cosmics_weights.dat
===================================================================
--- /tags/Mars-V0.9/msignal/cosmics_weights.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/cosmics_weights.dat	(revision 9772)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.296762 -0.632805
+0.052669 -1.03525
+-0.259279 -0.926851
+-0.435774 -0.963835
+-0.583858 -0.843637
+-0.653866 -0.665019
+-0.722997 -0.627056
+-0.7894 -0.481322
+-0.916398 -0.314016
+-1.05471 0.000154063
+-1.23631 1.12827
+-0.772589 1.98746
+-0.166435 1.84358
+0.202461 2.02063
+0.509947 1.80846
+0.669284 1.54607
+0.834405 1.63452
+0.998756 1.44834
+1.28039 1.37314
+1.63214 1.43295
+2.18222 1.3064
+2.41072 0.532674
+2.32602 -0.191982
+2.17997 -0.682484
+2.01379 -0.865313
+1.91545 -1.0259
+1.79855 -1.3302
+1.64895 -1.45366
+1.34434 -1.67446
+0.873027 -2.09955
+0.0473139 -2.34944
+-0.451361 -1.53652
+-0.523845 -0.485103
+-0.431676 -0.0878126
+-0.332904 0.169116
+-0.297262 0.238137
+-0.270423 0.350654
+-0.245929 0.419744
+-0.173941 0.511192
+-0.0119864 0.561345
+0.202838 0.416069
+0.267667 0.122226
+0.200201 -0.132905
+0.133702 -0.24494
+0.0701731 -0.285589
+0.0385833 -0.252528
+0.0188702 -0.259152
+0.00219847 -0.281877
+-0.0460886 -0.324774
+-0.155267 -0.309696
+-0.257781 -0.0760684
+-0.259848 0.0358922
+-0.225765 0.0960974
+-0.20464 0.128228
+-0.176549 0.157698
+-0.15318 0.150098
+-0.144226 0.132703
+-0.133485 0.149325
+-0.111339 0.194484
+-0.0410094 0.201485
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273
+0.038191 -0.00418687
+0.0386966 0.0212324
+0.0402881 0.0744799
+0.0415794 0.229615
+0.0598731 0.44332
+0.0758477 0.661518
+0.101509 1.10641
+0.159323 1.64997
+0.497256 2.83685
+0.245087 3.27499
+0.140546 2.46177
+0.58086 2.2849
+0.632721 2.45587
+0.72819 2.52835
+0.889583 2.48099
+0.980812 2.50031
+1.09885 2.55892
+1.21374 2.78769
+1.61928 3.08069
+1.38544 1.95583
+1.31998 1.1792
+1.50633 0.591226
+1.50916 0.0793899
+1.5008 -0.33188
+1.47339 -0.575386
+1.45362 -0.915309
+1.40214 -1.31593
+1.34175 -1.77904
+1.0661 -2.05471
+1.31087 -1.49798
+1.33793 -1.34758
+1.10172 -1.21719
+1.08133 -1.09356
+1.04007 -0.981455
+0.976745 -1.08299
+0.930979 -1.14774
+0.874203 -1.18348
+0.816708 -1.20126
+0.587354 -1.92869
+0.783078 -1.89621
+0.792771 -1.03439
+0.622278 -0.781807
+0.61184 -0.745831
+0.578792 -0.683741
+0.537336 -0.596328
+0.51443 -0.592858
+0.482294 -0.560586
+0.462351 -0.827587
+0.317989 -1.05649
+0.459672 -0.775035
+0.468287 -0.619961
+0.374182 -0.31635
+0.376946 -0.225242
+0.367075 -0.347444
+0.340737 -0.393231
+0.321054 -0.187384
+0.320654 -0.225558
+0.302148 -0.399499
+0.232954 -0.607578
Index: /tags/Mars-V0.9/msignal/cosmics_weights4.dat
===================================================================
--- /tags/Mars-V0.9/msignal/cosmics_weights4.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/cosmics_weights4.dat	(revision 9772)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.637443 -0.648763
+-0.707555 -0.610204
+-0.772465 -0.469694
+-0.896081 -0.305143
+-1.02783 0.00696361
+-1.03684 0.731979
+-0.73698 1.49428
+-0.23419 1.57509
+0.12767 1.83675
+0.441087 1.70526
+0.639658 1.50546
+0.806192 1.58667
+0.966865 1.41151
+1.24058 1.34506
+1.58293 1.39453
+2.02092 1.46038
+2.31508 0.8539
+2.31705 0.051831
+2.18497 -0.493294
+2.01129 -0.749924
+1.8675 -0.959329
+1.75322 -1.25026
+1.60962 -1.37231
+1.3216 -1.58832
+0.880364 -1.9924
+0.219661 -2.50675
+-0.35077 -1.96955
+-0.553454 -0.855454
+-0.491715 -0.387673
+-0.38701 -0.0297507
+-0.293549 0.092153
+-0.278646 0.194742
+-0.263716 0.25195
+-0.221238 0.323789
+-0.121941 0.381038
+0.00379863 0.393009
+0.0805122 0.201843
+0.0443888 -0.0531952
+-0.0199606 -0.175625
+-0.0809393 -0.21419
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+0.178287 2.98244
+0.0799794 2.25048
+0.501997 2.04566
+0.559993 2.18952
+0.636334 2.28558
+0.784832 2.29757
+0.894393 2.36602
+1.01571 2.62578
+1.14191 3.14701
+1.70405 4.27635
+1.25503 1.69442
+1.19843 1.00804
+1.36974 0.493838
+1.37759 0.0452029
+1.37174 -0.336051
+1.34423 -0.563321
+1.31669 -0.852661
+1.26602 -1.28826
+1.20062 -1.85625
+0.874127 -2.44773
+1.2433 -1.47361
+1.27171 -1.3052
+1.03025 -1.1211
+1.00417 -0.992811
+0.968251 -0.911359
+0.907626 -1.02038
+0.852293 -1.06813
+0.797164 -1.16276
+0.739386 -1.25445
+0.447754 -2.34757
+0.777349 -1.83155
+0.779564 -1.01577
+0.600426 -0.733238
+0.5863 -0.688006
+0.557156 -0.650488
+0.514926 -0.584649
+0.485323 -0.569089
+0.454047 -0.573249
+0.429026 -0.907077
+0.245526 -1.35434
Index: /tags/Mars-V0.9/msignal/cosmics_weights46.dat
===================================================================
--- /tags/Mars-V0.9/msignal/cosmics_weights46.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/cosmics_weights46.dat	(revision 9772)
@@ -0,0 +1,104 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.637443 -0.648763
+-0.707555 -0.610204
+-0.772465 -0.469694
+-0.896081 -0.305143
+-1.02783 0.00696361
+-1.03684 0.731979
+-0.73698 1.49428
+-0.23419 1.57509
+0.12767 1.83675
+0.441087 1.70526
+0.639658 1.50546
+0.806192 1.58667
+0.966865 1.41151
+1.24058 1.34506
+1.58293 1.39453
+2.02092 1.46038
+2.31508 0.8539
+2.31705 0.051831
+2.18497 -0.493294
+2.01129 -0.749924
+1.8675 -0.959329
+1.75322 -1.25026
+1.60962 -1.37231
+1.3216 -1.58832
+0.880364 -1.9924
+0.219661 -2.50675
+-0.35077 -1.96955
+-0.553454 -0.855454
+-0.491715 -0.387673
+-0.38701 -0.0297507
+-0.293549 0.092153
+-0.278646 0.194742
+-0.263716 0.25195
+-0.221238 0.323789
+-0.121941 0.381038
+0.00379863 0.393009
+0.0805122 0.201843
+0.0443888 -0.0531952
+-0.0199606 -0.175625
+-0.0809393 -0.21419
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+0.0446612 -0.385273
+0.038191 -0.00418687
+0.0386966 0.0212324
+0.0402881 0.0744799
+0.0415794 0.229615
+0.0598731 0.44332
+0.0758477 0.661518
+0.101509 1.10641
+0.159323 1.64997
+0.497256 2.83685
+0.245087 3.27499
+0.140546 2.46177
+0.58086 2.2849
+0.632721 2.45587
+0.72819 2.52835
+0.889583 2.48099
+0.980812 2.50031
+1.09885 2.55892
+1.21374 2.78769
+1.61928 3.08069
+1.38544 1.95583
+1.31998 1.1792
+1.50633 0.591226
+1.50916 0.0793899
+1.5008 -0.33188
+1.47339 -0.575386
+1.45362 -0.915309
+1.40214 -1.31593
+1.34175 -1.77904
+1.0661 -2.05471
+1.31087 -1.49798
+1.33793 -1.34758
+1.10172 -1.21719
+1.08133 -1.09356
+1.04007 -0.981455
+0.976745 -1.08299
+0.930979 -1.14774
+0.874203 -1.18348
+0.816708 -1.20126
+0.587354 -1.92869
+0.783078 -1.89621
+0.792771 -1.03439
+0.622278 -0.781807
+0.61184 -0.745831
+0.578792 -0.683741
+0.537336 -0.596328
+0.51443 -0.592858
+0.482294 -0.560586
+0.462351 -0.827587
+0.317989 -1.05649
+0.459672 -0.775035
+0.468287 -0.619961
+0.374182 -0.31635
+0.376946 -0.225242
+0.367075 -0.347444
+0.340737 -0.393231
+0.321054 -0.187384
+0.320654 -0.225558
+0.302148 -0.399499
+0.232954 -0.607578
Index: /tags/Mars-V0.9/msignal/cosmics_weights4_logaintest.dat
===================================================================
--- /tags/Mars-V0.9/msignal/cosmics_weights4_logaintest.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/cosmics_weights4_logaintest.dat	(revision 9772)
@@ -0,0 +1,85 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time) 
+-0.990564 0.813232
+-0.806484 1.74836
+-0.43829 2.4249
+0.0451181 2.67058
+0.463887 3.01401
+0.714 3.23898
+0.887111 3.15779
+1.05327 3.24712
+1.32499 3.86809
+1.44213 4.59276
+2.06205 4.04486
+2.45161 2.90439
+2.6494 1.52572
+2.66069 0.436417
+2.55694 -0.362778
+2.43585 -1.04956
+2.34313 -1.55472
+2.24881 -2.11859
+2.03605 -2.86169
+1.95231 -3.51744
+1.6486 -3.72459
+1.2416 -3.07972
+0.925084 -2.32165
+0.684032 -1.68812
+0.589887 -1.32468
+0.570156 -1.05064
+0.561215 -0.620602
+0.551184 -0.200923
+0.562483 -0.388106
+0.561862 -1.06923
+0.511264 -0.720139
+0.418279 -0.712441
+0.378939 -0.269248
+0.425153 0.0483749
+0.467989 0.158911
+0.512818 0.306459
+0.533694 0.107538
+0.515955 -0.211784
+0.483112 -0.217814
+0.463744 0.0214888
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time) 
+-0.461712  -0.478171
+-0.508663  -0.456735
+-0.550858  -0.358047
+-0.615084  -0.230953
+-0.655615  0.0171828
+-0.593359  0.573597
+-0.354573  1.15547
+-0.0166319  1.26005
+0.226452  1.52102
+0.451298  1.45511
+0.527201  1.27282
+0.680384  1.38144
+0.826361  1.26079
+1.05602  1.22515
+1.30687  1.29254
+1.59171  1.40908
+1.77973  0.952821
+1.79484  0.245375
+1.7262  -0.21442
+1.62411  -0.484694
+1.73426  -0.615484
+1.64165  -0.907105
+1.52898  -1.07112
+1.30084  -1.29905
+0.983446  -1.68008
+0.532795  -2.19838
+0.133827  -1.90033
+-0.0392906  -1.02741
+-0.0357089  -0.721406
+-0.0139902  -0.385772
+-0.414459  -0.200187
+-0.406329  -0.0821537
+-0.403955  0.0227461
+-0.391219  0.127372
+-0.347919  0.206207
+-0.29191  0.277449
+-0.234367  0.24775
+-0.228396  0.104672
+-0.238849  0.0733048
+-0.245189  0.0500998
+
Index: /tags/Mars-V0.9/msignal/cosmics_weights_logaintest.dat
===================================================================
--- /tags/Mars-V0.9/msignal/cosmics_weights_logaintest.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/cosmics_weights_logaintest.dat	(revision 9772)
@@ -0,0 +1,125 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time) 
+-0.0851354 -0.0818943
+-0.121924 -0.584977
+-0.269186 -0.874395
+-0.470451 -1.00063
+-0.662756 -1.12938
+-0.770093 -1.10388
+-0.835339 -0.995019
+-0.899395 -0.884381
+-0.983397 -0.628212
+-0.997415 -0.00715026
+-1.11376 -0.0168757
+-1.0091 1.14057
+-0.638545 2.07741
+-0.107314 2.54285
+0.380996 3.02362
+0.731444 3.34887
+0.959498 3.28988
+1.17934 3.38254
+1.57619 4.01168
+1.8263 4.58323
+2.07564 5.08144
+2.53926 3.80961
+2.86297 2.12543
+2.91748 0.749097
+2.80503 -0.228309
+2.6423 -1.05946
+2.50982 -1.64579
+2.36653 -2.27444
+2.05553 -3.101
+1.87853 -3.72935
+2.03964 -4.75531
+1.43034 -4.09923
+0.877873 -2.95319
+0.551859 -1.99114
+0.451674 -1.45197
+0.44424 -1.0055
+0.467447 -0.55123
+0.471455 -0.160571
+0.48432 -0.250935
+0.432957 -0.747835
+-0.195425 0.688031
+-0.128512 0.426902
+-0.0250589 0.67848
+0.111442 0.594296
+0.137021 0.454404
+0.18465 0.425805
+0.173857 0.191566
+0.166493 -0.088923
+0.129184 -0.103965
+0.150974 0.0291908
+0.43261 -0.441491
+0.385866 -0.245876
+0.281277 -0.66199
+0.148729 -0.538564
+0.153182 -0.382713
+0.106348 -0.355415
+0.123019 -0.263842
+0.0911191 -0.197345
+0.0963107 -0.229423
+0.0550985 -0.187527
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time) 
+	0.190173	-0.352992
+	0.155921	-0.475234
+	0.111158	-0.510688
+	0.0258716	-0.585781
+	-0.0846783	-0.752984
+	-0.259831	-1.02767
+	-0.439926	-1.02041
+	-0.585558	-0.734472
+	-0.663611	-0.690174
+	-0.73984	-0.576795
+	-0.672748	-0.173961
+	-0.693405	-0.0130429
+	-0.699736	0.1524
+	-0.698901	0.407909
+	-0.638204	0.836755
+	-0.44419	1.55279
+	-0.142557	1.8777
+	0.153996	1.59209
+	0.356156	1.7666
+	0.564031	1.65896
+	0.707804	1.38728
+	0.85022	1.45257
+	0.99052	1.2707
+	1.22473	1.15456
+	1.46489	1.05566
+	1.70603	0.973196
+	1.857	0.57388
+	1.8993	0.113422
+	1.88339	-0.2337
+	1.83839	-0.429011
+	1.78206	-0.626315
+	1.71376	-0.903836
+	1.61136	-1.05343
+	1.41208	-1.25025
+	1.14602	-1.52358
+	0.805571	-1.90971
+	0.502163	-1.71115
+	0.294872	-1.13556
+	0.189728	-1.07744
+	0.084943	-0.887703
+	-0.0316251	-0.719687
+	-0.109198	-0.668266
+	-0.185341	-0.531971
+	-0.300562	-0.397775
+	-0.390757	-0.259113
+	-0.449349	-0.0664538
+	-0.438326	0.189747
+	-0.387571	0.299769
+	-0.33554	0.456087
+	-0.272877	0.508469
+	-0.0686699	0.350793
+	-0.0289917	0.38007
+	0.0150257	0.319358
+	0.0807497	0.267639
+	0.144026	0.199999
+	0.187235	0.0767841
+	0.183333	-0.124801
+	0.139438	-0.239748
+	0.0952476	-0.3751
+	0.0410329	-0.38942
+
Index: /tags/Mars-V0.9/msignal/pulpo_weights.dat
===================================================================
--- /tags/Mars-V0.9/msignal/pulpo_weights.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/pulpo_weights.dat	(revision 9772)
@@ -0,0 +1,124 @@
+# High Gain Weights: 6 10
+# (Amplitude)  (Time)
+-0.12431 0.185239
+-0.0267055 0.0037991
+-0.0259801 -0.423405
+-0.183327 -0.800635
+-0.40724 -0.758845
+-0.54078 -0.801479
+-0.662083 -0.722269
+-0.720992 -0.554825
+-0.773543 -0.498706
+-0.825219 -0.351983
+-0.862103 -0.262895
+-1.00393 0.21406
+-0.930389 1.22904
+-0.520129 1.99452
+-0.0150508 1.81237
+0.292189 1.98133
+0.570068 1.78746
+0.719691 1.52423
+0.864022 1.60506
+1.02168 1.41713
+1.26558 1.35391
+1.61344 1.34607
+2.01336 1.22433
+2.20595 0.50917
+2.15054 -0.160944
+2.04229 -0.623651
+1.90462 -0.810952
+1.81945 -0.967633
+1.72207 -1.25811
+1.58263 -1.37678
+1.30022 -1.58265
+0.85573 -1.91552
+0.25147 -2.17209
+-0.16104 -1.45872
+-0.249172 -0.520003
+-0.199678 -0.182078
+-0.142631 0.0632378
+-0.123823 0.124224
+-0.113025 0.213306
+-0.102673 0.272495
+0.0188075 0.287166
+0.108756 0.28294
+0.192197 0.181065
+0.209837 -0.00954936
+0.157036 -0.154499
+0.113306 -0.229067
+0.0699705 -0.249718
+0.0446349 -0.217674
+0.0293213 -0.222187
+0.0159978 -0.24989
+-0.309299 -0.195262
+-0.355871 -0.195246
+-0.410243 -0.208791
+-0.458189 -0.179693
+-0.486599 -0.0937612
+-0.502873 -0.0553459
+-0.50502 0.00789869
+-0.494301 0.0521942
+-0.492681 0.0475246
+-0.486371 0.0990417
+# Low Gain Weights: 6 10
+# (Amplitude)  (Time)
+-0.508787 -1.8512
+-0.482402 -1.06646
+-0.764704 -1.0321
+-0.89732 -1.08093
+-1.00112 -0.949638
+-1.08997 -0.731505
+-1.15379 -0.55427
+-1.23129 -0.208521
+-1.24038 0.181441
+-1.0946 1.5747
+-0.760548 3.89286
+-0.768054 2.78435
+-0.0388176 2.74531
+0.30468 3.00492
+0.607574 3.03692
+0.919068 3.02925
+1.21051 3.06817
+1.56039 3.21235
+1.83534 3.54928
+2.60839 4.14646
+2.29192 1.47429
+2.26241 0.98134
+2.41491 0.106406
+2.32984 -0.768902
+2.19051 -1.3234
+2.03991 -1.59426
+1.88649 -2.01044
+1.63313 -2.5487
+1.42679 -3.31539
+0.649283 -3.91761
+0.937235 -1.55157
+0.904694 -1.63591
+0.549783 -1.06607
+0.524229 -0.397922
+0.54955 -0.0404911
+0.546924 -0.138923
+0.506861 -0.00935328
+0.519261 0.118637
+0.48628 0.51656
+0.571592 -0.313517
+0.60678 -1.15412
+0.601982 -0.153964
+0.566105 -0.196816
+0.523068 -0.415408
+0.464942 -0.445999
+0.428435 -0.354879
+0.40545 -0.523187
+0.321979 -0.606825
+0.312933 -1.06197
+0.0312496 -1.21027
+-0.113826 -0.71054
+-0.123841 -0.810667
+-0.28705 -0.429981
+-0.298861 -0.222333
+-0.315921 -0.263296
+-0.353192 -0.316989
+-0.397503 -0.0799875
+-0.375387 -0.0788394
+-0.411545 -0.0428121
+-0.404853 -0.296136
Index: /tags/Mars-V0.9/msignal/pulpo_weights4.dat
===================================================================
--- /tags/Mars-V0.9/msignal/pulpo_weights4.dat	(revision 9772)
+++ /tags/Mars-V0.9/msignal/pulpo_weights4.dat	(revision 9772)
@@ -0,0 +1,84 @@
+# High Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.830773 -0.513332
+-0.883684 -0.367084
+-0.981636 -0.181162
+-1.0654 0.181257
+-0.989822 0.940191
+-0.64358 1.59018
+-0.170784 1.55768
+0.153406 1.78731
+0.443244 1.66404
+0.589961 1.42946
+0.834668 1.56661
+0.99416 1.38965
+1.26811 1.31138
+1.60335 1.32056
+1.99633 1.31936
+2.23206 0.747258
+2.22358 0.0467182
+2.11605 -0.439809
+1.97093 -0.678148
+1.88466 -0.862697
+1.70404 -1.19545
+1.56508 -1.315
+1.28049 -1.51062
+0.853542 -1.84239
+0.269082 -2.21694
+-0.1855 -1.69602
+-0.332178 -0.756789
+-0.286346 -0.395196
+-0.215935 -0.0982026
+-0.194873 0.00415795
+-0.181069 0.0877068
+-0.176841 0.139735
+-0.149863 0.184439
+-0.081151 0.160871
+-0.0351086 0.0185016
+-0.0674657 -0.19927
+-0.184774 -0.322906
+-0.280436 -0.407465
+-0.362954 -0.392359
+-0.393249 -0.299451
+# Low Gain Weights: 4 10
+# (Amplitude)  (Time)
+-0.895686 2.74051
+-0.894816 2.07478
+-0.29184 2.11503
+0.0665281 2.43427
+0.35031 2.52029
+0.568335 2.53046
+0.747945 2.56963
+0.943671 2.77718
+1.09444 3.22759
+1.66295 4.63169
+2.24768 1.97632
+2.20569 1.23156
+2.40659 0.413157
+2.29192 -0.421216
+2.12793 -1.00932
+2.01982 -1.29659
+1.9169 -1.66267
+1.77059 -2.21215
+1.65931 -3.01017
+1.07882 -4.32181
+0.697307 -1.78007
+0.660479 -1.69108
+0.291088 -1.17701
+0.307283 -0.541925
+0.385063 -0.125812
+0.379987 -0.167953
+0.3629 -0.0595063
+0.376758 0.0997659
+0.347217 0.48611
+0.4555 -0.0459001
+0.386874 -1.7207
+0.414701 -0.700196
+0.264508 -0.520446
+0.179367 -0.635974
+0.0945086 -0.675258
+0.0590596 -0.576493
+0.0266148 -0.56912
+-0.0221451 -0.604525
+-0.0287237 -0.951405
+-0.225035 -1.19463
Index: /tags/Mars-V0.9/msql/MSQLServer.cc
===================================================================
--- /tags/Mars-V0.9/msql/MSQLServer.cc	(revision 9772)
+++ /tags/Mars-V0.9/msql/MSQLServer.cc	(revision 9772)
@@ -0,0 +1,657 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 2/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+////////////////////////////////////////////////////////////////////////
+//
+//  MSQLServer
+//
+//  Using this instead of a TSQLServer gives the possibility to
+//  browse a database server through the TBrowser and it will offer
+//  many features usefull working with relational tables.
+//
+//  Use it like TSQlServer:
+//    new MSQLServer("mysql://localhost:3306", "hercules", "stdmagicpassword");
+//    // now start your TBrowser
+//    new TBrowser;
+//
+////////////////////////////////////////////////////////////////////////
+#include "MSQLServer.h"
+
+#include <iostream>
+#include <iomanip>
+#include <stdlib.h>
+
+#include <TROOT.h>
+
+#include <TH1.h>
+#include <TEnv.h>
+
+#include <TSQLResult.h>
+#include <TSQLServer.h>
+#include <TSQLRow.h>
+
+#include <TBrowser.h>
+
+ClassImp(MSQLServer);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Used in virtual function TObject::Browse() to create the
+//
+void MSQLServer::BrowseColumn(TBrowser *b) /*FOLD00*/
+{
+    const TString query0(Form("EXPLAIN %s.%s %s", (const char*)fDataBase, (const char*)fTable, (const char*)fColumn));
+    const TString query1(Form("SELECT %s FROM %s.%s", (const char*)fColumn, (const char*)fDataBase, (const char*)fTable));
+
+    //cout << query0 << endl;
+    TSQLResult *res = fServ->Query(query0);
+    if (!res)
+    {
+        cout << "query - failed: " << query0 << endl;
+        return;
+    }
+
+    TSQLRow *row=res->Next();
+    const TString desc((*row)[1]);
+
+    delete res;
+
+    const Bool_t isnum =
+        !desc.Contains("char", TString::kIgnoreCase) &&
+        !desc.Contains("text", TString::kIgnoreCase);
+
+    cout << query1 << endl;
+    res = fServ->Query(query1);
+    if (!res)
+    {
+        cout << "query - failed: " << query1 << endl;
+        return;
+    }
+
+    TArrayD arr(2);
+    Int_t num=0;
+    Double_t max=0;
+    Double_t min=0;
+    Double_t sum=0;
+    Double_t sqr=0;
+
+    while ((row=res->Next()))
+    {
+        const TString row0((*row)[0]);
+
+        if (!isnum)
+        {
+            cout << row0 << endl;
+            continue;
+        }
+
+        if (num==arr.GetSize())
+            arr.Set(arr.GetSize()*2);
+
+        arr[num] = atof(row0.Data());
+
+        if (num==0)
+            min=max=arr[0];
+
+        if (arr[num]>max) max = arr[num];
+        if (arr[num]<min) min = arr[num];
+
+        sum += arr[num];
+        sqr += arr[num]*arr[num];
+
+        num++;
+    }
+
+    delete res;
+
+    if (!isnum)
+        return;
+
+    if (max==min) max += 1;
+
+    Int_t num0 = 1;
+
+    if (num>0)
+    {
+        /*
+         cout << "Num:   " << num << endl;
+         cout << "Mean:  " << sum/num << endl;
+         cout << "Range: " << max-min << endl;
+         cout << "RMS:   " << TMath::Sqrt(sqr/num-sum*sum/num/num) << endl;
+         */
+
+        num0 = (Int_t)((max-min)*40/TMath::Sqrt(sqr/num-sum*sum/num/num));
+    }
+
+    const TString title(Form("#splitline{%s}{<%s>}", (const char*)query1, (const char*)desc));
+
+    TH1F *hist=new TH1F(fColumn, title, num0, min, max);
+    for (int i=0; i<num; i++)
+        hist->Fill(arr[i]);
+
+    //cout << "Done." << endl;
+
+    hist->Draw();
+    hist->SetBit(kCanDelete);
+}
+
+void MSQLServer::BrowseTable(TBrowser *b) /*FOLD00*/
+{
+    TSQLResult *res = fServ->GetColumns(fDataBase, fTable);
+    if (!res)
+        return;
+
+    TSQLRow *row;
+    while ((row=res->Next()))
+    {
+        TString row0((*row)[0]);
+
+        MSQLServer *sql = (MSQLServer*)fList.FindObject(Form("%s/%s/%s", (const char*)fDataBase, (const char*)fTable, (const char*)row0));
+        if (!sql)
+        {
+            sql = new MSQLColumn(fServ, fDataBase, fTable, row0);
+            fList.Add(sql);
+        }
+        b->Add(sql, row0);
+    }
+}
+
+void MSQLServer::BrowseDataBase(TBrowser *b) /*FOLD00*/
+{
+    TSQLResult *res = fServ->GetTables(fDataBase);
+    if (!res)
+        return;
+
+    TSQLRow *row;
+    while ((row=res->Next()))
+    {
+        TString row0((*row)[0]);
+
+        MSQLServer *sql = (MSQLServer*)fList.FindObject(Form("%s/%s", (const char*)fDataBase, (const char*)row0));
+        if (!sql)
+        {
+            sql = new MSQLServer(fServ, fDataBase, row0);
+            fList.Add(sql);
+        }
+        b->Add(sql, row0);
+    }
+}
+
+void MSQLServer::BrowseServer(TBrowser *b) /*FOLD00*/
+{
+    TSQLResult *res = fServ->GetDataBases();
+    if (!res)
+        return;
+
+    TSQLRow *row;
+    while ((row=res->Next()))
+    {
+        const TString row0((*row)[0]);
+
+        MSQLServer *sql = (MSQLServer*)fList.FindObject(row0);
+        if (!sql)
+        {
+            sql = new MSQLServer(fServ, row0);
+            fList.Add(sql);
+        }
+        b->Add(sql, row0);
+    }
+}
+
+void MSQLServer::PrintLine(const TArrayI &max) /*FOLD00*/
+{
+    cout << "+" << setfill('-');
+    for (int i=0; i<max.GetSize(); i++)
+        cout << setw(max[i]+1) << "-" << "-+";
+    cout << endl;
+}
+
+void MSQLServer::PrintTable(TSQLResult &res) /*FOLD00*/
+{
+    Int_t n = res.GetFieldCount();
+
+    TArrayI max(n);
+
+    for (int i=0; i<n; i++)
+        max[i] = strlen(res.GetFieldName(i));
+
+    TSQLRow *row;
+
+    TList rows;
+    while ((row=res.Next()))
+    {
+        for (int i=0; i<n; i++)
+            max[i] = TMath::Max((ULong_t)max[i], row->GetFieldLength(i));
+        rows.Add(row);
+    }
+
+    cout << endl;
+
+    PrintLine(max);
+
+    cout << "|" << setfill(' ');
+    for (int i=0; i<n; i++)
+        cout << setw(max[i]+1) << res.GetFieldName(i) << " |";
+    cout << endl;
+
+    PrintLine(max);
+
+    cout << setfill(' ');
+    TIter Next(&rows);
+    while ((row=(TSQLRow*)Next()))
+    {
+        cout << "|";
+        for (int i=0; i<n; i++)
+        {
+            const char *c = (*row)[i];
+            cout << setw(max[i]+1) << (c?c:"") << " |";
+        }
+        cout << endl;
+    }
+
+    PrintLine(max);
+}
+
+TString MSQLServer::GetFields() const /*FOLD00*/
+{
+    TSQLResult *res = fServ->GetColumns(fDataBase, fTable);
+    if (!res)
+        return "";
+
+    TString fields;
+
+    TSQLRow *row;
+
+    TList rows;
+    while ((row=res->Next()))
+        rows.Add(row);
+
+    TIter Next(&rows);
+    while ((row=(TSQLRow*)Next()))
+    {
+        fields += (*row)[0];
+        if (row!=rows.Last())
+            fields += ", ";
+    }
+
+    return fields;
+}
+
+void MSQLServer::PrintQuery(const char *query) const /*FOLD00*/
+{
+    TSQLResult *res = fServ->Query(query);
+    if (res)
+    {
+        PrintTable(*res);
+        delete res;
+    }
+    else
+        cout << "Query failed: " << query << endl;
+}
+
+void MSQLServer::Print(Option_t *o) const /*FOLD00*/
+{
+    switch (fType)
+    {
+    case kIsServer:
+        PrintQuery("SHOW DATABASES");
+        break;
+
+    case kIsDataBase:
+        PrintQuery(Form("SHOW TABLES FROM %s", (const char*)fDataBase));
+        break;
+
+    case kIsTable:
+        PrintQuery(Form("SELECT * FROM %s.%s", (const char*)fDataBase, (const char*)fTable));
+        break;
+
+    case kIsColumn:
+        PrintQuery(Form("SELECT %s FROM %s.%s", (const char*)fColumn, (const char*)fDataBase, (const char*)fTable));
+        break;
+
+    default:
+        break;
+    }
+}
+
+void MSQLServer::ShowColumns() const /*FOLD00*/
+{
+    switch (fType)
+    {
+    case kIsTable:
+        PrintQuery(Form("SHOW FULl COLUMNS FROM %s.%s", (const char*)fDataBase, (const char*)fTable));
+        break;
+
+    case kIsColumn:
+        PrintQuery(Form("SHOW FULl COLUMNS FROM %s.%s LIKE %s", (const char*)fDataBase, (const char*)fTable, (const char*)fColumn));
+        break;
+
+    default:
+        //Print();
+        break;
+    }
+}
+
+void MSQLServer::ShowStatus() const /*FOLD00*/
+{
+    switch (fType)
+    {
+    case kIsServer:
+        PrintQuery("SHOW STATUS");
+        break;
+
+    case kIsDataBase:
+        PrintQuery(Form("SHOW TABLE STATUS FROM %s", (const char*)fDataBase));
+        break;
+
+    case kIsTable:
+        PrintQuery(Form("SHOW TABLE STATUS FROM %s LIKE %s", (const char*)fDataBase, (const char*)fTable));
+        break;
+
+    default:
+        break;
+    }
+}
+
+void MSQLServer::ShowTableIndex() const /*FOLD00*/
+{
+    switch (fType)
+    {
+    case kIsTable:
+    case kIsColumn:
+        PrintQuery(Form("SHOW INDEX FROM %s.%s", (const char*)fDataBase, (const char*)fTable));
+        break;
+
+    default:
+        break;
+    }
+}
+
+void MSQLServer::ShowTableCreate() const /*FOLD00*/
+{
+    switch (fType)
+    {
+    case kIsTable:
+    case kIsColumn:
+        PrintQuery(Form("SHOW CREATE TABLE %s.%s", (const char*)fDataBase, (const char*)fTable));
+        break;
+
+    default:
+        break;
+    }
+}
+
+void MSQLServer::Close(Option_t *option) /*FOLD00*/
+{
+    if (fType==kIsServer)
+        fServ->Close(option);
+}
+
+// --------------------------------------------------------------------------
+//
+// Send a SQL query to the SQl server.
+//
+// If MSQLServer is no server (column, row, ...) NULL is returned and an
+//  error message is send to stdout.
+//
+// If the query failed for some reason an error message is send to stdout
+//  and NULL is returned.
+//
+// If everything works fine a TSQLResult is returned. Make sure that you
+// delete it!
+//
+TSQLResult *MSQLServer::Query(const char *sql) /*FOLD00*/
+{
+    if (fType!=kIsServer)
+    {
+        cout << "ERROR: MSQLServer::Query - this is not a server!" << endl;
+        return NULL;
+    }
+
+    TSQLResult *res = fServ->Query(sql);
+    if (!res)
+    {
+        cout << "ERROR: MSQLServer::Query - Query failed: " << sql << endl;
+        return NULL;
+    }
+
+    return res;
+}
+
+Int_t MSQLServer::SelectDataBase(const char *dbname) /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->SelectDataBase(dbname) : 0;
+}
+
+TSQLResult *MSQLServer::GetDataBases(const char *wild) /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->GetDataBases(wild) : NULL;
+}
+
+TSQLResult *MSQLServer::GetTables(const char *dbname, const char *wild) /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->GetTables(dbname, wild) : NULL;
+}
+
+TSQLResult *MSQLServer::GetColumns(const char *dbname, const char *table, const char *wild) /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->GetColumns(dbname, table, wild) : NULL;
+}
+
+Int_t MSQLServer::CreateDataBase(const char *dbname) /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->CreateDataBase(dbname) : 0;
+}
+
+Int_t MSQLServer::DropDataBase(const char *dbname) /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->DropDataBase(dbname) : 0;
+}
+
+Int_t MSQLServer::Reload() /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->Reload() : 0;
+}
+
+Int_t MSQLServer::Shutdown() /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->Shutdown() : 0;
+}
+
+const char *MSQLServer::ServerInfo() /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->ServerInfo() : "";
+}
+
+Bool_t MSQLServer::IsConnected() const
+{
+    return fType==kIsServer ? fServ->IsConnected() : kFALSE;
+}
+
+const char *MSQLServer::GetName() const
+{
+    switch (fType)
+    {
+    case kIsServer:   return Form("%s://%s:%d", fServ->GetDBMS(), fServ->GetHost(), fServ->GetPort());
+    case kIsDataBase: return GetNameDataBase();
+    case kIsTable:    return GetNameTable();
+    case kIsColumn:   return GetNameColumn();
+    default:          return "n/a";
+    }
+}
+
+Bool_t MSQLServer::Split(TString &url, TString &user, TString &pasw) const
+{
+    const Ssiz_t pos1 = url.First("://")+3;
+    const Ssiz_t pos2 = url.Last(':')   +1;
+    const Ssiz_t pos3 = url.First('@');
+
+    if (pos1<0 || pos2<0 || pos3<0 || pos1>pos2 || pos2>pos3)
+        return kFALSE;
+
+    user = url(pos1, pos2-pos1-1);
+    pasw = url(pos2, pos3-pos2);
+
+    url.Remove(pos1, pos3+1-pos1);
+
+    return kTRUE;
+}
+
+void MSQLServer::Init(const char *connection, const char *user, const char *password) /*FOLD00*/
+{
+    fType = kIsZombie;
+
+    fServ = TSQLServer::Connect(connection, user, password);
+    if (fServ)
+    {
+        gROOT->GetListOfBrowsables()->Add(this, connection);
+        fType = kIsServer;
+    }
+    else
+        SetBit(kZombie);
+
+    fList.SetOwner();
+}
+
+void MSQLServer::InitEnv(TEnv &env, const char *prefix)
+{
+    TString url; 
+    TString user;
+    TString pass;
+
+    if (prefix)
+    {
+        url  = env.GetValue(Form("%s.URL", prefix),      "");
+        user = env.GetValue(Form("%s.User", prefix),     "");
+        pass = env.GetValue(Form("%s.Password", prefix), "");
+    }
+    if (url.IsNull())
+        url  = env.GetValue("URL",      "");
+    if (user.IsNull())
+        user = env.GetValue("User",     "");
+    if (pass.IsNull())
+        pass = env.GetValue("Password", "");
+
+    if (user.IsNull() && pass.IsNull())
+    {
+        if (!Split(url, user, pass))
+        {
+            SetBit(kIsZombie);
+            return;
+        }
+    }
+
+    Init(url, user, pass);
+}
+
+MSQLServer::MSQLServer(const char *connection, const char *user, const char *password) /*FOLD00*/
+{
+    Init(connection, user, password);
+}
+
+MSQLServer::MSQLServer(const char *u) : fType(kIsZombie) /*FOLD00*/
+{
+    TString url(u);
+    TString user, pasw;
+
+    if (!Split(url, user, pasw))
+    {
+        SetBit(kIsZombie);
+        return;
+    }
+    Init(url, user, pasw);
+}
+
+MSQLServer::MSQLServer(TEnv &env, const char *prefix)
+{
+    InitEnv(env, prefix);
+}
+
+MSQLServer::MSQLServer()
+{
+    if (gEnv)
+        InitEnv(*gEnv);
+}
+
+MSQLServer::~MSQLServer() /*FOLD00*/
+{
+    Close();
+    if (gDebug>0)
+        cout << "Delete: " << GetName() << endl;
+}
+
+Bool_t MSQLServer::PrintError(const char *txt, const char *q) const /*FOLD00*/
+{
+    cout << "Fatal error acessing database: " << txt << endl;
+    cout << "Query: " << q << endl;
+    return kFALSE;
+}
+
+TString MSQLServer::GetEntry(const char *where, const char *col, const char *table) const /*FOLD00*/
+{
+    if (!fServ)
+        return "";
+
+    if (table==0)
+        table = Form("%s.%s", (const char *)fDataBase, (const char*)fTable);
+    if (col==0)
+        col = (const char *)fColumn;
+
+    const TString query(Form("SELECT %s FROM %s WHERE %s", col, table, where));
+
+    TSQLResult *res = fServ->Query(query);
+    if (!res)
+        return (PrintError("GetEntry - TSQLResult==NULL", query), "");
+
+    if (res->GetFieldCount()!=1)
+    {
+        delete res;
+        return (PrintError("GetEntry - Number of columns != 1", query), "");
+    }
+
+    if (res->GetRowCount()>1)
+    {
+        delete res;
+        return (PrintError("GetEntry - Number of rows > 1", query), "");
+    }
+
+    if (res->GetRowCount()==0)
+    {
+        delete res;
+        return "";
+    }
+
+    const char *fld = res->Next()->GetField(0);
+    if (!fld)
+    {
+        delete res;
+        return (PrintError("GetEntry - Entry is empty", query), "");
+    }
+
+    const TString rc(fld);
+    delete res;
+    return rc;
+}
Index: /tags/Mars-V0.9/msql/MSQLServer.h
===================================================================
--- /tags/Mars-V0.9/msql/MSQLServer.h	(revision 9772)
+++ /tags/Mars-V0.9/msql/MSQLServer.h	(revision 9772)
@@ -0,0 +1,137 @@
+#ifndef MARS_MSQLServer
+#define MARS_MSQLServer
+
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+
+class TEnv;
+class TArrayI;
+
+class TSQLServer;
+class TSQLResult;
+
+class MSQLServer : public TObject
+{
+    TSQLServer *fServ;
+
+    TString fDataBase;
+    TString fTable;
+    TString fColumn;
+
+    TList   fList;
+
+    enum Type_t { kIsZombie, kIsServer, kIsDataBase, kIsTable, kIsColumn };
+
+    Type_t  fType;
+
+    Bool_t IsFolder() const { return kTRUE; }
+
+    Bool_t PrintError(const char *txt, const char *q) const;
+
+    TString GetFields() const;
+
+    void BrowseDataBase(TBrowser *b);
+    void BrowseTable(TBrowser *b);
+    void BrowseColumn(TBrowser *b);
+    void BrowseServer(TBrowser *b);
+
+    void Browse(TBrowser *b)
+    {
+        if (!b)
+            return;
+
+        switch (fType)
+        {
+        case kIsServer:   BrowseServer(b);   break;
+        case kIsDataBase: BrowseDataBase(b); break;
+        case kIsTable:    BrowseTable(b);    break;
+        case kIsColumn:   BrowseColumn(b);   break;
+        default:
+            break;
+        }
+    }
+
+    const char *GetNameDataBase() const { return fDataBase; }
+    const char *GetNameTable()    const { return Form("%s/%s",    (const char*)fDataBase, (const char*)fTable); }
+    const char *GetNameColumn()   const { return Form("%s/%s/%s", (const char*)fDataBase, (const char*)fTable, (const char*)fColumn); }
+
+    Bool_t Split(TString &url, TString &user, TString &pasw) const;
+
+    void Init(const char *connection, const char *user, const char *password);
+    void InitEnv(TEnv &env, const char *prefix=0);
+
+public:
+    MSQLServer(TSQLServer *serv, const char *dbname=0, const char *tname=0, const char *col=0)
+        : fServ(serv), fDataBase(dbname), fTable(tname), fColumn(col), fType(kIsZombie)
+    {
+        fList.SetOwner();
+
+        fType = kIsColumn;
+
+        if (fColumn.IsNull())
+            fType = kIsTable;
+
+        if (fTable.IsNull() && fColumn.IsNull())
+            fType = kIsDataBase;
+
+        if (fDataBase.IsNull() && fTable.IsNull() && fColumn.IsNull())
+            fType = kIsZombie;
+
+        if (!serv)
+            fType = kIsZombie;
+    }
+
+    MSQLServer(const char *connection, const char *user, const char *password);
+    MSQLServer(const char *link);
+    MSQLServer(TEnv &env, const char *prefix=0);
+    MSQLServer();
+    ~MSQLServer();
+
+    static void PrintLine(const TArrayI &max);
+    static void PrintTable(TSQLResult &res);
+
+    const char *GetName() const;
+
+    void Print(Option_t *o) const;
+    void Print() const { Print(""); } //*MENU*
+    void PrintQuery(const char *query) const; //*MENU*
+    void ShowColumns() const; //*MENU*
+    void ShowStatus() const; //*MENU*
+    void ShowTableIndex() const; //*MENU*
+    void ShowTableCreate() const; //*MENU*
+    void ShowVariables() const { PrintQuery("SHOW VARIABLES"); } //*MENU*
+    void ShowProcesses() const { PrintQuery("SHOW PROCESSLIST"); } //*MENU*
+
+    void Close(Option_t *option="");
+    TSQLResult *Query(const char *sql);
+    Int_t       SelectDataBase(const char *dbname);
+    TSQLResult *GetDataBases(const char *wild = 0);
+    TSQLResult *GetTables(const char *dbname, const char *wild = 0);
+    TSQLResult *GetColumns(const char *dbname, const char *table, const char *wild = 0);
+    Int_t       CreateDataBase(const char *dbname);
+    Int_t       DropDataBase(const char *dbname);
+    Int_t       Reload();
+    Int_t       Shutdown();
+    const char *ServerInfo();
+    Bool_t      IsConnected() const;
+
+    TString     GetEntry(const char *where, const char *col=0, const char *table=0) const;
+
+    ClassDef(MSQLServer, 0) // An enhancement of TSQLServer
+};
+
+class MSQLColumn : public MSQLServer
+{
+private:
+    Bool_t IsFolder() const { return kFALSE; }
+
+public:
+    MSQLColumn(TSQLServer *serv, const char *dbname=0, const char *tname=0, const char *col=0)
+        : MSQLServer(serv, dbname, tname, col)
+    {
+    }
+    ClassDef(MSQLColumn, 0) // A workarount to let MSQLServer return kFALSE for IsFolder
+};
+
+#endif
Index: /tags/Mars-V0.9/msql/MSqlInsertRun.cc
===================================================================
--- /tags/Mars-V0.9/msql/MSqlInsertRun.cc	(revision 9772)
+++ /tags/Mars-V0.9/msql/MSqlInsertRun.cc	(revision 9772)
@@ -0,0 +1,512 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 2/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+////////////////////////////////////////////////////////////////////////
+//
+//  MSqlInsertRun
+//
+//  Input Containers:
+//   MRawRunHeader
+//
+//  Output Containers:
+//    -/-
+//
+////////////////////////////////////////////////////////////////////////
+#include "MSqlInsertRun.h"
+
+#include <TSystem.h>
+
+#include <TSQLResult.h>
+#include <TSQLRow.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MRawFileRead.h"
+#include "MRawRunHeader.h"
+
+#include "MSQLServer.h"
+
+ClassImp(MSqlInsertRun);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+MSqlInsertRun::MSqlInsertRun(const char *db, const char *user, const char *pw)
+    : fIsUpdate(kFALSE)
+{
+    fName  = "MSqlInsertRun";
+    fTitle = "Write run into database";
+
+    *fLog << dbg << "Connecting to: " << db << " as " << user << " <" << pw << ">" << endl;
+
+    fSqlServer = new MSQLServer(db, user, pw);
+}
+
+// --------------------------------------------------------------------------
+//
+MSqlInsertRun::MSqlInsertRun(const char *u)
+    : fSqlServer(0), fIsUpdate(kFALSE)
+{
+    fName  = "MSqlInsertRun";
+    fTitle = "Write run into database";
+
+    fSqlServer = new MSQLServer(u); //::Connect(url, user, pasw);
+}
+
+MSqlInsertRun::~MSqlInsertRun()
+{
+    if (fSqlServer)
+        delete fSqlServer;
+}
+
+Bool_t MSqlInsertRun::PrintError(const char *txt, const char *q) const
+{
+    *fLog << err;
+    *fLog << "Fatal error acessing database: " << txt << endl;
+    fLog->Underline();
+    *fLog << "Query:" << flush << " " << q << endl;
+    return kFALSE;
+}
+
+TString MSqlInsertRun::GetEntry(const char *table, const char *col, const char *where)
+{
+    return fSqlServer->GetEntry(where, col, table);
+}
+
+Bool_t MSqlInsertRun::IsRunExisting(MRawRunHeader *h, Bool_t &exist)
+{
+    exist = kFALSE;
+
+    const TString str(GetEntry("RunData", "fRunNumber", Form("fRunNumber=%d", h->GetRunNumber())));
+    if (str.IsNull())
+        return kFALSE;
+
+    exist = kTRUE;
+    return kTRUE;
+}
+
+Int_t MSqlInsertRun::GetKey(const char *table, const char *where)
+{
+    const TString str(GetEntry(table, Form("f%sKEY", table), where));
+
+    Int_t key;
+    return sscanf(str.Data(), "%d", &key)==1 ? key : -1;
+}
+
+TString MSqlInsertRun::GetKeyStr(const char *table, const char *where, Bool_t &rc)
+{
+    const TString str(GetEntry(table, Form("f%sKEY", table), where));
+    if (str.IsNull())
+        rc = kFALSE;
+
+    return str;
+}
+
+TString MSqlInsertRun::MagicNumber(MRawRunHeader *h, Bool_t &ok)
+{
+    Int_t key = GetKey("MagicNumber", Form("fMagicNumber=%d", h->GetMagicNumber()));
+    if (key<0)
+        key = GetKey("MagicNumber", "fMagicNumber=0xffff");
+    if (key<0)
+    {
+        ok = kFALSE;
+        return TString("");
+    }
+    return TString(Form("%d", key));
+}
+
+TString MSqlInsertRun::RunType(MRawRunHeader *h, Bool_t &ok)
+{
+    Int_t key = GetKey("RunType", Form("fRunType=%d", h->GetRunType()));
+    if (key<0)
+        key = GetKey("RunType", "fRunTye=0xffff");
+    if (key<0)
+    {
+        ok = kFALSE;
+        return TString("");
+    }
+    return TString(Form("%d", key));
+}
+
+TString MSqlInsertRun::Source(MRawRunHeader *h, Bool_t &ok)
+{
+    Int_t key = GetKey("Source", Form("fSourceName='%s'", h->GetSourceName()));
+    if (key<0)
+    {
+        const char *q = Form("INSERT Source (fSourceName, fSourceTxt) VALUES ('%s', 'MSqlInsert: %s')",
+                             h->GetSourceName(), h->GetSourceName());
+
+        TSQLResult *res = fSqlServer->Query(q);
+        if (!res)
+        {
+            ok = kFALSE;
+            return TString("");
+        }
+        key = GetKey("Source", Form("fSourceName='%s'", h->GetSourceName()));
+        if (key>0)
+            *fLog << inf << "New Source '" << h->GetSourceName() << "' inserted into table Source of database." << endl;
+    }
+    else
+    {
+        // FIXME: check for consistency!
+    }
+    if (key<0)
+    {
+        ok = kFALSE;
+        return TString("");
+    }
+
+    return TString(Form("%d", key));
+}
+
+TString MSqlInsertRun::Project(MRawRunHeader *h, Bool_t &ok)
+{
+    Int_t key = GetKey("Project", Form("fProjectName='%s'", h->GetProjectName()));
+    if (key<0)
+    {
+        const char *q = Form("INSERT Project (fProjectName, fProjectTxt) VALUES ('%s', 'MSqlInsert: %s')",
+                             h->GetProjectName(), h->GetProjectName());
+
+        TSQLResult *res = fSqlServer->Query(q);
+        if (!res)
+        {
+            ok = kFALSE;
+            return TString("");
+        }
+        key = GetKey("Project", Form("fProjectName='%s'", h->GetProjectName()));
+        if (key>0)
+            *fLog << inf << "New Project '" << h->GetProjectName() << "' inserted into table Project of database." << endl;
+    }
+    if (key<0)
+    {
+        ok = kFALSE;
+        return TString("");
+    }
+
+    return TString(Form("%d", key));
+}
+
+TString MSqlInsertRun::RawFilePath(const char *path, Bool_t &ok)
+{
+    Int_t key = GetKey("FilePath", Form("fFilePathName='%s'", path));
+    if (key<0)
+    {
+        const char *q = Form("INSERT FilePath (fFilePathName, fFilePath) VALUES ('%s', 'MSqlInsert: %s')",
+                             path, path);
+
+        TSQLResult *res = fSqlServer->Query(q);
+        if (!res)
+        {
+            ok = kFALSE;
+            return TString("");
+        }
+        key = GetKey("FilePath", Form("fFilePathName='%s'", path));
+        if (key>0)
+            *fLog << inf << "New FilePath '" << path << "' inserted into table FilePath of database." << endl;
+
+    }
+    if (key<0)
+    {
+        ok = kFALSE;
+        return TString("");
+    }
+
+    return TString(Form("%d", key));
+}
+/*
+#include <TArrayI.h>
+
+void Line(const TArrayI &max)
+{
+    cout << "+" << setfill('-');
+    for (int i=0; i<max.GetSize(); i++)
+        cout << setw(max[i]+1) << "-" << "-+";
+    cout << endl;
+}
+
+void PrintResult(TSQLResult *res)
+{
+    Int_t n = res->GetFieldCount();
+
+    TArrayI max(n);
+
+    for (int i=0; i<n; i++)
+        max[i] = strlen(res->GetFieldName(i));
+
+    TSQLRow *row;
+
+    TList rows;
+    while ((row=res->Next()))
+    {
+        for (int i=0; i<n; i++)
+            max[i] = TMath::Max((ULong_t)max[i], row->GetFieldLength(i));
+        rows.Add(row);
+    }
+
+    Line(max);
+
+    cout << "|" << setfill(' ');
+    for (int i=0; i<n; i++)
+        cout << setw(max[i]+1) << res->GetFieldName(i) << " |";
+    cout << endl;
+
+    Line(max);
+
+    cout << setfill(' ');
+    TIter Next(&rows);
+    while ((row=(TSQLRow*)Next()))
+    {
+        cout << "|";
+        for (int i=0; i<n; i++)
+        {
+            const char *c = (*row)[i];
+            cout << setw(max[i]+1) << (c?c:"") << " |";
+        }
+        cout << endl;
+    }
+
+    Line(max);
+}
+*/
+Bool_t MSqlInsertRun::InsertRun(MRawRunHeader *h, Bool_t update)
+{
+    // FIXME: Insert input file (PreProcess), output file (PostProcess)
+
+    TString query(update ? "UPDATE" : "INSERT");
+
+    Bool_t ok=kTRUE;
+
+    query += " RunData SET fMagicNumberKEY='";
+    query += MagicNumber(h, ok);
+    query += "', fFormatVersion='";
+    query += h->GetFormatVersion();
+    query += "', fRunTypeKEY='";
+    query += RunType(h, ok);
+    query += "', fRunNumber='";
+    query += h->GetRunNumber();
+    query += "', fProjectKEY='";
+    query += Project(h, ok);
+    query += "', fSourceKEY='";
+    query += Source(h, ok);
+    query += "', fNumEvents='";
+    query += h->GetNumEvents();
+    query += "', fRunStart='";
+    query += h->GetRunStart().GetSqlDateTime();
+    query += "', fRunStop='";
+    query += h->GetRunEnd().GetSqlDateTime();
+    query += "'";
+
+    if (update)
+    {
+        query += " WHERE fRunNumber=";
+        query += h->GetRunNumber();
+    }
+
+    if (!ok)
+    {
+        *fLog << err << "ERROR - while concatenating query..." << endl;
+        *fLog << query << endl;
+        return kFALSE;
+    }
+
+    TSQLResult *res = fSqlServer->Query(query);
+    if (!res)
+        return PrintError("TSQLResult==NULL", query);
+
+    *fLog << inf << dec;
+    *fLog << "Run #" << h->GetRunNumber() << " ";
+    *fLog << (update ? "updated" : "inserted");
+    *fLog << " in database successfully." << endl;
+
+    return kTRUE;
+}
+
+Int_t MSqlInsertRun::GetIndex(MRawRunHeader *h)
+{
+    Bool_t ok=kTRUE;
+
+    TString query("SELECT fRunDataKEY from RunData WHERE fMagicNumberKEY='");
+
+    query += MagicNumber(h, ok);
+    query += "' AND fFormatVersion='";
+    query += h->GetFormatVersion();
+    query += "' AND fRunTypeKEY='";
+    query += RunType(h, ok);
+    query += "' AND fRunNumber='";
+    query += h->GetRunNumber();
+    query += "' AND fProjectKEY='";
+    query += Project(h, ok);
+    query += "' AND fSourceKEY='";
+    query += Source(h, ok);
+    query += "' AND fNumEvents='";
+    query += h->GetNumEvents();
+    query += "' AND fRunStart='";
+    query += h->GetRunStart().GetSqlDateTime();
+    query += "' AND fRunStop='";
+    query += h->GetRunEnd().GetSqlDateTime();
+    query += "'";
+
+    if (!ok)
+    {
+        *fLog << err << "ERROR - while concatenating query..." << endl;
+        *fLog << query << endl;
+        return -1;
+    }
+
+    TSQLResult *res = fSqlServer->Query(query);
+    if (!res)
+        return (PrintError("TSQLResult==NULL", query), -1);
+
+    if (res->GetFieldCount()!=1)
+        return (PrintError("Number of columns != 1", query), -1);
+
+    if (res->GetRowCount()>1)
+        return (PrintError("Number of rows > 1", query), -1);
+
+    if (res->GetRowCount()==0)
+        return 0;
+
+    const char *fld = res->Next()->GetField(0);
+    if (!fld)
+        return (PrintError("Entry is empty", query), -1);
+
+    return atoi(fld);
+}
+
+Bool_t MSqlInsertRun::InsertFile(MRawRunHeader *h, MParList *pList, Bool_t update)
+{
+    const Int_t key = GetIndex(h);
+    if (key<0)
+        return kFALSE;
+
+    if (key==0)
+        return kTRUE;
+
+    MTaskList *tasks = (MTaskList*)pList->FindObject("MTaskList");
+    if (!tasks)
+    {
+        *fLog << err << "MTaskList not found in parameter list... aborting." << endl;
+        return kFALSE;
+    }
+    MRawFileRead *read = (MRawFileRead*)tasks->FindObject("MRawFileRead");
+    if (!read)
+    {
+        *fLog << err << "MRawFileRead not found in task list... aborting." << endl;
+        return kFALSE;
+    }
+
+    const char *base = gSystem->BaseName(read->GetFileName());
+    const char *path = gSystem->DirName(read->GetFileName());
+
+    const TString str(GetEntry("RawFile", "fRawFileName", Form("fRawFileName='%s'", base)));
+    if (!update && !str.IsNull())
+    {
+        *fLog << err << "ERROR - fRawFileName=" << base << " already existing in RawFile... aborting." << endl;
+        return kFALSE;
+    }
+
+    Bool_t ok = kTRUE;
+
+    TString query(update ? "UPDATE" : "INSERT");
+    query += " RawFile SET fRawFileName='";
+    query += base;
+    query += "', fFilePathKEY=";
+    query += RawFilePath(path, ok);
+    query += ", fRawFileKEY=";
+    query += key;
+
+    if (!ok)
+    {
+        *fLog << err << "ERROR - while concatenating query..." << endl;
+        *fLog << query << endl;
+        return kFALSE;
+    }
+
+    TSQLResult *res = fSqlServer->Query(query);
+    if (!res)
+        return PrintError("TSQLResult==NULL", query);
+
+    *fLog << inf << dec;
+    *fLog << "File '" << base << "' ";
+    *fLog << (update ? "updated" : "inserted");
+    *fLog << " in database successfully." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MSqlInsertRun::PreProcess(MParList *pList)
+{
+    if (!fSqlServer)
+    {
+        *fLog << err << "Connection to SQL server failed... aborting." << endl;
+        return kFALSE;
+    }
+
+    MRawRunHeader *header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!header)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+/*
+    if (header->GetFormatVersion()<3)
+    {
+        *fLog << err << "MSqlInsertRun cannot be used for files with format <3... abort." << endl;
+        return kTRUE;
+    }
+ */
+    Bool_t update = kFALSE;
+
+    // Is run already in databae?
+    const TString str(GetEntry("MRawRunHeader", "fRunNumber", Form("fRunNumber=%d", header->GetRunNumber())));
+    if (!str.IsNull())
+    {
+        if (!fIsUpdate)
+        {
+            *fLog << err << "Run #" << dec << header->GetRunNumber() << " already in database... abort." << endl;
+            return kFALSE;
+        }
+        update=kTRUE;
+    }
+
+    if (!InsertRun(header, update))
+        return kFALSE;
+
+    if (!InsertFile(header, pList, update))
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Int_t MSqlInsertRun::PostProcess()
+{
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/msql/MSqlInsertRun.h
===================================================================
--- /tags/Mars-V0.9/msql/MSqlInsertRun.h	(revision 9772)
+++ /tags/Mars-V0.9/msql/MSqlInsertRun.h	(revision 9772)
@@ -0,0 +1,51 @@
+#ifndef MARS_MRawRunInsertSql
+#define MARS_MRawRunInsertSql
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MSQLServer;
+
+class MRawRunHeader;
+
+class MSqlInsertRun : public MTask
+{
+private:
+    MSQLServer *fSqlServer;
+
+    Bool_t fIsUpdate;
+
+    Int_t   GetIndex(MRawRunHeader *h);
+    Int_t   GetKey(const char *table, const char *where);
+    TString GetKeyStr(const char *table, const char *where, Bool_t &rc);
+    TString GetEntry(const char *table, const char *col, const char *where);
+
+    Bool_t  IsRunExisting(MRawRunHeader *h, Bool_t &ok);
+    Bool_t  IsFileExisting(MRawRunHeader *h, Bool_t &ok);
+
+    TString MagicNumber(MRawRunHeader *h, Bool_t &ok);
+    TString RunType(MRawRunHeader *h, Bool_t &ok);
+    TString Source(MRawRunHeader *h, Bool_t &ok);
+    TString Project(MRawRunHeader *h, Bool_t &ok);
+    TString RawFilePath(const char *path, Bool_t &ok);
+
+    Bool_t InsertRun(MRawRunHeader *h, Bool_t update);
+    Bool_t InsertFile(MRawRunHeader *h, MParList *pList, Bool_t update);
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  PostProcess();
+
+    Bool_t PrintError(const char *txt, const char *q) const;
+
+public:
+    MSqlInsertRun(const char *db, const char *user, const char *pw);
+    MSqlInsertRun(const char *url);
+    ~MSqlInsertRun();
+
+    void SetUpdate(Bool_t u=kTRUE) { fIsUpdate=u; }
+
+    ClassDef(MSqlInsertRun, 0) // Task to insert run into database
+};
+
+#endif
Index: /tags/Mars-V0.9/msql/Makefile
===================================================================
--- /tags/Mars-V0.9/msql/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/msql/Makefile	(revision 9772)
@@ -0,0 +1,32 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+############################################################
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Sql
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mraw -I../mfileio
+
+SRCFILES = \
+	MSQLServer.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/msql/SqlIncl.h
===================================================================
--- /tags/Mars-V0.9/msql/SqlIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/msql/SqlIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/msql/SqlLinkDef.h
===================================================================
--- /tags/Mars-V0.9/msql/SqlLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/msql/SqlLinkDef.h	(revision 9772)
@@ -0,0 +1,10 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MSQLColumn+;
+#pragma link C++ class MSQLServer+;
+
+#endif
Index: /tags/Mars-V0.9/mstarcam/MStarCam.cc
===================================================================
--- /tags/Mars-V0.9/mstarcam/MStarCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/MStarCam.cc	(revision 9772)
@@ -0,0 +1,113 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 04/2004 <mailto:jlopez@ifae.es>
+!   Author(s): Jordi Albert 04/2004 <mailto:albert@astro.uni-wuerzburg.de>
+!   Author(s): Robert Wagner 08/2004 <mailto:rwagner@mppmu.mpg.de>
+!                 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MStarCam                                                                //
+//                                                                         //
+// A Container to hold star positions in the camera                        //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MStarCam.h"
+
+#include <TList.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MStarPos.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+// Default constructor. 
+//
+//
+MStarCam::MStarCam(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MStarCam";
+  fTitle = title ? title : "";
+  
+  fStars = new TList;
+
+  fInnerPedestalDC = 0.;
+  fOuterPedestalDC = 0.;
+  fInnerPedestalRMSDC = 0.;
+  fOuterPedestalRMSDC = 0.;
+  
+}
+
+MStarCam::~MStarCam()
+{
+    fStars->SetOwner();
+    fStars->Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+MStarPos &MStarCam::operator[] (Int_t i)
+{
+  MStarPos& star = *static_cast<MStarPos*>(fStars->At(i));
+  return star;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+const MStarPos &MStarCam::operator[] (Int_t i) const
+{
+    return *static_cast<MStarPos*>(fStars->At(i));
+}
+
+void MStarCam::Paint(Option_t *o)
+{
+	TIter Next(fStars);
+	MStarPos* star;
+	while ((star=(MStarPos*)Next())) 
+	    star->Paint(o);
+}
+
+void MStarCam::Print(Option_t *o) const
+{
+      *fLog << inf << "DCs baseline:" << endl;
+      *fLog << inf << " Inner Pixels Mean pedestal \t" << setw(4) << fInnerPedestalDC << " uA  and RMS " << setw(4) << fInnerPedestalRMSDC << " uA for DCs" << endl;
+      *fLog << inf << " Outer Pixels Mean pedestal \t" << setw(4) << fOuterPedestalDC << " uA  and RMS " << setw(4) << fOuterPedestalRMSDC << " uA for DCs" << endl;
+      
+      TIter Next(fStars);
+      MStarPos* star;
+      UInt_t starnum = 0;
+      while ((star=(MStarPos*)Next())) 
+        {
+          *fLog << inf << "Star[" << starnum << "] info:" << endl;
+          star->Print(o);
+          starnum++;
+        }
+}
Index: /tags/Mars-V0.9/mstarcam/MStarCam.h
===================================================================
--- /tags/Mars-V0.9/mstarcam/MStarCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/MStarCam.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MStarCam
+#define MARS_MStarCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+class TList;
+
+class MGeomCam;
+class MStarPos;
+
+class MStarCam : public MParContainer
+{
+private:
+
+  TList  *fStars;  //-> FIXME: Change TClonesArray away from a pointer?
+
+  // BaseLine DCs info
+  Float_t fInnerPedestalDC;         //[ua]
+  Float_t fOuterPedestalDC;         //[ua]
+
+  Float_t fInnerPedestalRMSDC;      //[ua]
+  Float_t fOuterPedestalRMSDC;      //[ua]
+
+  MHCamera fDisplay;
+
+ public:
+
+  MStarCam(const char *name=NULL, const char *title=NULL);
+  ~MStarCam();
+
+  MStarPos &operator[] (Int_t i);
+  const MStarPos &operator[] (Int_t i) const;
+
+  TList *GetList() const { return fStars; }
+  UInt_t GetNumStars() const { return fStars->GetSize(); }
+
+  //Getters
+
+  Float_t GetInnerPedestalDC() {return fInnerPedestalDC;}
+  Float_t GetOuterPedestalDC() {return fOuterPedestalDC;}
+  Float_t GetInnerPedestalRMSDC() { return fInnerPedestalRMSDC;}
+  Float_t GetOuterPedestalRMSDC() { return fOuterPedestalRMSDC;}
+
+  MHCamera& GetDisplay() { return fDisplay; }
+
+    //Setters
+  void SetInnerPedestalDC(Float_t ped) {fInnerPedestalDC = ped;}
+  void SetOuterPedestalDC(Float_t ped) {fOuterPedestalDC = ped;}
+  void SetInnerPedestalRMSDC(Float_t rms){fInnerPedestalRMSDC = rms;}
+  void SetOuterPedestalRMSDC(Float_t rms){fOuterPedestalRMSDC = rms;}
+
+  void Paint(Option_t *o=NULL);
+  void Print(Option_t *o=NULL) const;
+
+  ClassDef(MStarCam, 1)	// Storage Container for star positions in the camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mstarcam/MStarCamTrans.cc
===================================================================
--- /tags/Mars-V0.9/mstarcam/MStarCamTrans.cc	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/MStarCamTrans.cc	(revision 9772)
@@ -0,0 +1,1233 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 08/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MStarCamTrans
+// ---------------
+//
+// this is a collection of transformations between
+//
+// a) celestial (declination, hourangle)      = (  dec,   h); units (deg,hour)
+// b) local     (zenith angle, azimuth angle) = (theta, phi); units (deg, deg)
+// c) camera    (x-coordinate, y-coordinate)  = (    X,   Y); units ( mm,  mm)
+//
+// coordinates. As to the definition of the coordinates, the conventions
+// of TDAS 00-11 are used. 
+//
+// The transformations use 
+//   - cos(Lat) and sin(Lat) from an MObservatory container, 
+//     where 'Lat' is the geographical latitude of the telescope.
+//   - fDistCam from an MGeomCam container,
+//     which is the distance of the camera from the reflector center
+//   
+//   in order to apply one of the transformations the  
+//      'MGeomCam' and 'MObservatory' containers have to be present;
+//      the corresponding objects 'mgeom' and 'mobserv' have to be used as 
+//      arguments of the constructor
+//
+//               MStarCamTrans(mgeom, mobserv);
+//
+// The tranformations ignore effects like nutation, precession, refraction, ...
+// This is not a real problem as long as relative positions are considered, as
+// in all the transformations, except in CelToLoc and LocToCel.
+//
+// The camera coordinates (X, Y) are assumed to be the coordinates for an ideal
+// imaging, without imaging errors. The x-axis is assumed to be horizonthal,
+// the y-axis is pointing upwards.
+//
+// the azimuthal angle is defined as :   0 degrees  = north
+//                                      90 degrees  = east
+//                                     180 degrees  = south
+//                                     270 degrees  = west  
+// 
+// Examples for the use of the transformations :
+//
+// - if the local coordinates (theta1, phi1) of a point (X1, Y1) in the camera
+//   are known one may caculate the local coordinates (theta2, phi2) of any 
+//   other point (X2, Y2) in the camera :
+//
+//         LocCamCamToLoc(theta1, phi1, X1, Y1, X2, Y2, theta2, phi2);
+//
+//   if (X1, Y1) = (0, 0) one may use
+//                        Loc0CamToLoc(theta1, phi1, X2, Y2, theta2, phi2);
+//
+
+// - if the local coordinates (theta1, phi1) of a point (X1, Y1) in the camera
+//   are known one may caculate the position (X2, Y2) for another direction
+//   (theta2, phi2) :
+//
+//         LocCamLocToCam(theta1, phi1, X1, Y1, theta2, phi2, X2, Y2);
+//
+//   if (X1, Y1) = (0, 0) one may use
+//                        Loc0LocToCam(theta1, phi1, X2, Y2, theta2, phi2);
+//
+// - if the celestial coordinates (dec1, h1) of a point (X1, Y1) in the camera
+//   are known one may caculate the celestial coordinates (dec2, h2) of any 
+//   other point (X2, Y2) in the camera :
+//
+//         CelCamCamToCel(dec1, h1, X1, Y1, X2, Y2, dec2, h2);
+//
+//   if (X1, Y1) = (0, 0) one may use
+//                        Cel0CamToCel(dec1, h1, X2, Y2, dec2, h2);
+//
+//
+// - if the celestial coordinates (dec1, h1) of a point (X1, Y1) in the camera
+//   are known one may caculate the position (X2, Y2) for any other direction :
+//
+//         CelCamCelToCam(dec1, h1, X1, Y1, dec2, h2, X2, Y2);
+//
+//   if (X1, Y1) = (0, 0) one may use
+//                        Cel0CelToCam(dec1, h1, dec2, h2, X2, Y2);
+//
+//
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MStarCamTrans.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TPad.h>
+#include <TStyle.h>
+#include <TGraph.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+
+//#include "MH.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MGeomCam.h"
+#include "MObservatory.h"
+
+using namespace std;
+
+ClassImp(MStarCamTrans);
+
+
+// --------------------------------------------------------------------------
+//
+// Constructor
+// 
+//    get distance between camera and reflector from an MGeomCam     container
+//    get cos(Lat) and sin(Lat) from                 an MObservatory container
+//
+MStarCamTrans::MStarCamTrans(const MGeomCam &cam, const MObservatory &obs) 
+{
+  if (&cam == NULL)
+  {
+    gLog << err << "MStarCamTrans::MStarCamTrans;  MGeomCam container is not available"
+          << endl;
+    return;
+  }
+
+  if (&obs == NULL)
+  {
+    gLog << err << "MStarCamTrans::MStarCamTrans;  MObservatory container is not available"
+          << endl;
+    return;
+  }
+
+  fDistCam = cam.GetCameraDist() * 1000.0;     //  [mm]
+  fCLat    = obs.GetCosPhi();
+  fSLat    = obs.GetSinPhi();
+
+  if (fDistCam*fCLat*fSLat == 0.0)
+  {
+    gLog << "MStarCamTrans::TransCelLocCam; one of 'fDistCam, fCLat, fSLat' is zero !!!$$$$$$$$$$$$$$$$$ : "
+        << fDistCam << ",  " << fCLat << ",  " << fSLat << endl;
+  }
+
+
+  fGridBinning = 0.50;   // degrees
+  fGridFineBin = 0.01;   // degrees
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Loc0CamToLoc
+//
+// Input :   (theta0, phi0)    direction for the position (0,0) in the camera  
+//           (     X,    Y)    a position in the camera
+// 
+// Output :  ( theta,  phi)    direction for the position (X,Y) in the camera
+//
+Bool_t MStarCamTrans::Loc0CamToLoc(Double_t theta0deg, Double_t phi0deg,
+                                     Double_t X,         Double_t Y,
+                                     Double_t &thetadeg, Double_t &phideg) 
+{
+  Double_t theta0 = theta0deg / kRad2Deg;
+  Double_t phi0   = phi0deg   / kRad2Deg;
+
+  Double_t XC = X / fDistCam;
+  Double_t YC = Y / fDistCam;
+
+  Double_t theta;
+  Double_t phiminphi0;
+
+  //--------------------------------------------
+  Double_t sip = -XC;
+  Double_t cop = sin(theta0) + YC*cos(theta0);
+
+  Double_t sit = sqrt(cop*cop + XC*XC);
+  Double_t cot = cos(theta0) - YC*sin(theta0);
+
+  // there is an ambiguity in the sign of cos(theta)
+  // - if theta0 is close to 0 or Pi 
+  //   choose that theta which is closer to theta0,
+  //   i.e. require the same sign for cos(theta) and cos(theta0)
+  // - otherwise choose that theta which is compatible with a small
+  //   difference |phi-phi0|, i.e. cos(phi-phi0) > 0
+
+  if( fabs(theta0deg - 90.0) > 45.0 )
+    theta = TMath::ATan2( sit, TMath::Sign(cot, cos(theta0)) );
+  else
+    theta = TMath::ATan2( sit, TMath::Sign(cot, cop/cot) );
+
+  Double_t sig = TMath::Sign(1.0, cot*tan(theta));
+  phiminphi0 = TMath::ATan2(sig*sip, sig*cop);
+
+  //--------------------------------------------
+  phideg   = (phi0 + phiminphi0) * kRad2Deg;
+  thetadeg =               theta * kRad2Deg;
+
+  //gLog << "MStarCamTrans::Loc0Cam2Log; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Loc0LocToCam
+//
+// Input :   (theta0, phi0)   direction for the position (0,0) in the camera  
+//           ( theta,  phi)   some other direction
+// 
+// Output :  (X, Y)      position in the camera corresponding to (theta, phi)
+//
+//  (see also MAstro::GetDistOnPlain())
+//
+Bool_t MStarCamTrans::Loc0LocToCam(Double_t theta0deg, Double_t phi0deg,
+                                     Double_t thetadeg,  Double_t phideg,
+                                     Double_t &X,        Double_t &Y)
+{
+  Double_t theta0 = theta0deg / kRad2Deg;
+  Double_t phi0   = phi0deg   / kRad2Deg;
+
+  Double_t theta = thetadeg / kRad2Deg;
+  Double_t phi   = phideg   / kRad2Deg;
+
+  //--------------------------------------------
+  Double_t YC =   (cos(theta0)*tan(theta)*cos(phi-phi0) - sin(theta0))
+                / (cos(theta0) + sin(theta0)*tan(theta)); 
+  Double_t XC = -sin(phi-phi0) * (cos(theta0) - YC*sin(theta0)) * tan(theta);
+
+  //--------------------------------------------
+  X = XC * fDistCam;
+  Y = YC * fDistCam;
+
+
+  //gLog << "MStarCamTrans::Loc0LocToCam; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// LocCamToLoc0
+//
+// Input :   ( X, Y)         a position in the camera
+//           (theta, phi)    direction for the position (X,Y) in the camera
+// 
+// Output :  ( theta0,  phi0)    direction for the position (0,0) in the camera
+//
+Bool_t MStarCamTrans::LocCamToLoc0(Double_t thetadeg,   Double_t phideg,
+                                     Double_t X,          Double_t Y,
+                                     Double_t &theta0deg, Double_t &phi0deg) 
+{
+  Double_t theta = thetadeg / kRad2Deg;
+  Double_t phi   = phideg   / kRad2Deg;
+
+  Double_t XC = X / fDistCam;
+  Double_t YC = Y / fDistCam;
+
+  //--------------------------------------------
+
+  Double_t theta0;
+  Double_t phiminphi0;
+
+  Double_t tant1 = 0.0;
+  Double_t tant2 = 0.0;
+
+  Double_t ip;
+
+  // calculate tan(theta0)
+  // dummy loop to avoid a 'go to'
+  for (Int_t i=0; i<1; i++)
+  {
+    if ( tan(theta) == 0.0 )
+    {
+      if (XC != 0.0)
+      {
+        // this can never occur
+        gLog << "MStarCamTrans::LocCam2Loc0; thetadeg, XC = " << thetadeg
+              << ",  " << XC << endl;
+         return kFALSE;
+      }
+      tant1 = -YC;
+
+      theta0 = TMath::Pi() *
+               modf( (atan(tant1)+TMath::Pi()) / TMath::Pi(), &ip );
+      phiminphi0 = 0.0;
+
+      break;
+    }
+
+    Double_t a = 1.0   + XC*XC -  YC*YC*tan(theta)*tan(theta);
+    Double_t b = 2.0   * YC    * (1.0 + tan(theta)*tan(theta));
+    Double_t c = XC*XC + YC*YC -        tan(theta)*tan(theta);
+
+    if (a == 0.0)
+    {
+      if (b == 0.0)
+      {
+        // this can never occur
+        gLog << "MStarCamTrans::LocCam2Loc0; a, b = " << a << ",  "
+              << b << endl;
+         return kFALSE;
+      }
+      tant1 = -c/b;  
+    }
+    else
+    {
+      Double_t discr = b*b - 4.0*a*c;
+      if (discr < 0.0)
+      {
+        gLog << "MStarCamTrans::LocCam2Loc0; discr = " << discr << endl;
+        return kFALSE;
+      }
+
+      // two solutions for tan(theta0)
+      tant1 = (-b + sqrt(discr)) / (2.0*a);
+      tant2 = (-b - sqrt(discr)) / (2.0*a);
+
+      if (fabs(tant1-tant2) < 1.e-5)
+        tant2 = 0.0;
+    }
+
+    // define the sign of tan(theta0) and 
+    // reject the solution with the wrong sign
+
+    if ( fabs(thetadeg - 90.0) > 45.0 )
+    {
+      Double_t sig = TMath::Sign(1.0, cos(theta));
+      if ( tant1 != 0.0  &&  TMath::Sign(1.0, tant1) != sig )
+	   tant1 = 0.0; 
+
+      if ( tant2 != 0.0  &&  TMath::Sign(1.0, tant2) != sig )
+	   tant2 = 0.0; 
+    }
+    else
+    {
+      // require sign of cos(phi-phi0) to be > 0
+      if ( tant1 != 0.0  &&
+           TMath::Sign( 1.0, (tant1+YC)/ ((1.0-YC*tant1)*tan(theta)) ) != 1.0 )
+        tant1 = 0.0;
+
+      if ( tant2 != 0.0  &&
+           TMath::Sign( 1.0, (tant2+YC)/ ((1.0-YC*tant2)*tan(theta)) ) != 1.0 )
+        tant2 = 0.0;
+    }
+
+    if (tant1 != 0.0  &&  tant2 != 0.0)
+    {
+      gLog << "MStarCamTrans::LocCam2Loc0; there are 2 solutions for tan(theta0),  tant1, tant2 = " 
+            << tant1 << ",  " << tant2 << endl;
+    }
+
+    if (tant1 != 0.0)
+      theta0 = TMath::Pi() *
+               modf( (atan(tant1)+TMath::Pi()) / TMath::Pi(), &ip );
+    else if (tant2 != 0.0)
+      theta0 = TMath::Pi() *
+               modf( (atan(tant2)+TMath::Pi()) / TMath::Pi(), &ip );
+    else
+    {
+      theta0 = theta;
+      gLog << "MStarCamTrans::LocCam2Loc0; there is no solution for tan(theta0)"
+            << endl;
+    }
+
+    Double_t sip = -XC;
+    Double_t cop = sin(theta0) + YC*cos(theta0);
+    Double_t cot = cos(theta0) - YC*sin(theta0);
+    Double_t sig = TMath::Sign(1.0, cot*tan(theta));
+
+    phiminphi0 = TMath::ATan2(sig*sip, sig*cop);
+  } // end of dummy loop
+
+  //--------------------------------------------
+  phi0deg   = (phi - phiminphi0) * kRad2Deg;
+  theta0deg =             theta0 * kRad2Deg;
+
+  //gLog << "MStarCamTrans::LocCamToLoc0; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cel0CamToCel
+//
+// Input :   (dec0, h0)    direction for the position (0,0) in the camera  
+//           (   X,  Y)    a position in the camera
+// 
+// Output :  (dec,   h)    direction for the position (X,Y) in the camera
+//
+Bool_t MStarCamTrans::Cel0CamToCel(Double_t dec0deg, Double_t h0hour,
+                                     Double_t X,       Double_t Y,
+                                     Double_t &decdeg, Double_t &hhour) 
+{
+  //--------------------------------------------
+
+  // transform celestial coordinates (  dec0,   h0) 
+  //      into local coordinates     (theta0, phi0)
+  Double_t theta0deg;
+  Double_t phi0deg;
+  CelToLoc(dec0deg, h0hour, theta0deg, phi0deg);
+
+  // get the local coordinates (theta, phi) 
+  //         for the position (X, Y) in the camera
+  Double_t thetadeg;
+  Double_t phideg;
+  Loc0CamToLoc(theta0deg, phi0deg, X, Y, thetadeg, phideg);
+
+  // transform local coordinates     (theta, phi)
+  //      into celestial coordinates (  dec,   h) 
+  LocToCel(thetadeg, phideg, decdeg, hhour);
+
+  //--------------------------------------------
+
+
+  //gLog << "MStarCamTrans::Cel0CamToCel; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cel0CelToCam
+//
+// Input :   (dec0, h0)   direction for the position (0,0) in the camera  
+//           (dec,   h)   some other direction
+// 
+// Output :  (X, Y)      position in the camera corresponding to (dec, h)
+//
+Bool_t MStarCamTrans::Cel0CelToCam(Double_t dec0deg, Double_t h0hour,
+                                     Double_t decdeg,  Double_t hhour,
+                                     Double_t &X,        Double_t &Y)
+{
+  //--------------------------------------------
+
+  // transform celestial coordinates (  dec0,   h0) 
+  //      into local coordinates     (theta0, phi0)
+  Double_t theta0deg;
+  Double_t phi0deg;
+  CelToLoc(dec0deg, h0hour, theta0deg, phi0deg);
+
+  // transform celestial coordinates (  dec,   h) 
+  //      into local coordinates     (theta, phi)
+  Double_t thetadeg;
+  Double_t phideg;
+  CelToLoc(decdeg, hhour, thetadeg, phideg);
+
+  // get the position (X, Y) in the camera
+  // from the local coordinates (theta, phi) 
+  Loc0LocToCam(theta0deg, phi0deg, thetadeg, phideg, X, Y);
+
+  //--------------------------------------------
+
+  //gLog << "MStarCamTrans::Cel0CelToCam; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// CelCamToCel0
+//
+// Input :   ( X,    Y)    a position in the camera
+//           (dec,   h)    direction for the position (X,Y) in the camera
+// 
+// Output :  (dec0, h0)    direction for the position (0,0) in the camera
+//
+
+Bool_t MStarCamTrans::CelCamToCel0(Double_t decdeg,   Double_t hhour, 
+                                     Double_t X,        Double_t Y,
+                                     Double_t &dec0deg, Double_t &h0hour) 
+{
+  //--------------------------------------------
+
+  // transform celestial coordinates (  dec,   h) 
+  //      into local coordinates     (theta, phi)
+  Double_t thetadeg;
+  Double_t phideg;
+  CelToLoc(decdeg, hhour, thetadeg, phideg);
+
+  // get the local coordinates (theta, phi) 
+  //         for the position (0, 0) in the camera
+  Double_t theta0deg;
+  Double_t phi0deg;
+  LocCamToLoc0(thetadeg, phideg, X, Y, theta0deg, phi0deg);
+
+  // transform local coordinates     (theta0, phi0)
+  //      into celestial coordinates (  dec0,   h0) 
+  LocToCel(theta0deg, phi0deg, dec0deg, h0hour);
+
+  //--------------------------------------------
+
+
+  //gLog << "MStarCamTrans::CelCamToCel0; theta0deg, phi0deg, X, Y, thetadeg, phideg = " 
+  //      << theta0deg << ",  " << phi0deg << ",  " << X << ",  " << Y << ",  "
+  //      << thetadeg << ",  " << phideg << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// LocCamCamToLoc
+//
+// Input :   (theta1, phi1)  direction for the position (X1,Y1) in the camera  
+//           (    X1,   Y1)  a position in the camera
+//           (    X2,   Y2)  another position in the camera 
+// 
+// Output :  (theta2, phi2)  direction for the position (X2,Y2) in the camera
+//
+Bool_t MStarCamTrans::LocCamCamToLoc(Double_t theta1deg, Double_t phi1deg,
+                                      Double_t X1,         Double_t Y1,
+                                      Double_t X2,         Double_t Y2,
+                                      Double_t &theta2deg, Double_t &phi2deg)
+{
+  if (X1 == 0.0  && Y1 == 0.0)
+  {
+    Loc0CamToLoc(theta1deg, phi1deg, X2, Y2, theta2deg, phi2deg); 
+    return kTRUE;
+  }
+
+  if (X2 == 0.0  && Y2 == 0.0)
+  {
+    LocCamToLoc0(theta1deg, phi1deg, X1, Y1, theta2deg, phi2deg); 
+    return kTRUE;
+  }
+
+  Double_t theta0deg;
+  Double_t phi0deg;
+  LocCamToLoc0(theta1deg, phi1deg, X1, Y1, theta0deg, phi0deg); 
+
+  Loc0CamToLoc(theta0deg, phi0deg, X2, Y2, theta2deg, phi2deg); 
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// LocCamLocToCam
+//
+// Input :   (theta1, phi1)  direction for the position (X1,Y1) in the camera  
+//           (    X1,   Y1)  a position in the camera
+//           (theta2, phi2)  another direction
+// 
+// Output :  (    X2,   Y2)  position corresponding to (theta2, phi2)
+//
+Bool_t MStarCamTrans::LocCamLocToCam(Double_t theta1deg, Double_t phi1deg,
+                                       Double_t X1,        Double_t Y1,
+				       Double_t theta2deg, Double_t phi2deg,
+				       Double_t &X2,       Double_t &Y2)
+
+{
+  if (X1 == 0.0  && Y1 == 0.0)
+  {
+    Loc0LocToCam(theta1deg, phi1deg, theta2deg, phi2deg, X2, Y2);
+
+    return kTRUE;
+  }
+
+
+  Double_t theta0deg;
+  Double_t phi0deg;
+  LocCamToLoc0(theta1deg, phi1deg, X1, Y1, theta0deg, phi0deg); 
+
+  Loc0LocToCam(theta0deg, phi0deg, theta2deg, phi2deg, X2, Y2);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// CelCamCamToCel
+//
+// Input :   (dec1, h1)  direction for the position (X1,Y1) in the camera  
+//           (  X1, Y1)  a position in the camera
+//           (  X2, Y2)  another position in the camera 
+// 
+// Output :  (dec2, h2)  direction for the position (X2,Y2) in the camera
+//
+Bool_t MStarCamTrans::CelCamCamToCel(Double_t dec1deg, Double_t h1deg,
+                                      Double_t X1,       Double_t Y1,
+                                      Double_t X2,       Double_t Y2,
+                                      Double_t &dec2deg, Double_t &h2deg) 
+{
+  if (X1 == 0.0  && Y1 == 0.0)
+  {
+    Cel0CamToCel(dec1deg, h1deg, X2, Y2, dec2deg, h2deg); 
+    return kTRUE;
+  }
+
+  if (X2 == 0.0  && Y2 == 0.0)
+  {
+    CelCamToCel0(dec1deg, h1deg, X1, Y1, dec2deg, h2deg); 
+    return kTRUE;
+  }
+
+  Double_t dec0deg;
+  Double_t h0deg;
+  CelCamToCel0(dec1deg, h1deg, X1, Y1, dec0deg, h0deg); 
+
+  Cel0CamToCel(dec0deg, h0deg, X2, Y2, dec2deg, h2deg); 
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// CelCamCelToCam
+//
+// Input :   (dec1, h1)  direction for the position (X1,Y1) in the camera  
+//           (  X1, Y1)  a position in the camera
+//           (dec2, h2)  another direction
+// 
+// Output :  (  X2, Y2)  position corresponding to (dec2, h2)
+//
+Bool_t MStarCamTrans::CelCamCelToCam(Double_t dec1deg, Double_t h1deg,
+                                       Double_t X1,      Double_t Y1,
+				       Double_t dec2deg, Double_t h2deg,
+				       Double_t &X2,     Double_t &Y2)
+
+{
+  if (X1 == 0.0  && Y1 == 0.0)
+  {
+    Cel0CelToCam(dec1deg, h1deg, dec2deg, h2deg, X2, Y2);
+
+    return kTRUE;
+  }
+
+
+  Double_t dec0deg;
+  Double_t h0deg;
+  CelCamToCel0(dec1deg, h1deg, X1, Y1, dec0deg, h0deg); 
+
+  Cel0CelToCam(dec0deg, h0deg, dec2deg, h2deg, X2, Y2);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// CelToLoc
+//
+// Input :   (dec,     h)    celestial coordinates
+// 
+// Output :  (theta, phi)    corresponding local coordinates
+//
+// (see also MAstroCatalog and MAstroSky2Local)
+//
+Bool_t MStarCamTrans::CelToLoc(Double_t decdeg,    Double_t hhour,
+                                 Double_t &thetadeg, Double_t &phideg) 
+{
+  Double_t a1 =  fCLat;
+  Double_t a3 = -fSLat;
+
+  Double_t dec = decdeg / kRad2Deg;
+  Double_t h   =  hhour / 24.0 * TMath::TwoPi();
+
+  // transform celestial coordinates (  dec,   h) 
+  //      into local coordinates     (theta, phi)
+  Double_t xB =   cos(dec) * cos(h);
+  Double_t yB =   cos(dec) * sin(h);
+  Double_t zB = - sin(dec);
+
+  Double_t xA =  a3*xB        - a1*zB;
+  Double_t yA =         - yB;
+  Double_t zA = -a1*xB        - a3*zB;
+
+  thetadeg = acos(-zA)             * kRad2Deg;
+  phideg   = TMath::ATan2(yA, xA)  * kRad2Deg;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// LocToCel
+// 
+// Input :   (theta, phi)    local coordinates
+//
+// Output :  (dec,     h)    corresponding celestial coordinates
+//
+// (see also MAstroCatalog and MAstroSky2Local)
+//
+Bool_t MStarCamTrans::LocToCel(Double_t thetadeg, Double_t phideg,
+                                 Double_t &decdeg,  Double_t &hhour) 
+{
+  Double_t a1 =  fCLat;
+  Double_t a3 = -fSLat;
+
+  Double_t theta = thetadeg / kRad2Deg;
+  Double_t phi   =   phideg / kRad2Deg;
+
+  //--------------------------------------------
+
+  // transform local coordinates     (theta, phi)
+  //      into celestial coordinates (  dec,   h) 
+  Double_t xA =   sin(theta) * cos(phi);
+  Double_t yA =   sin(theta) * sin(phi);
+  Double_t zA = - cos(theta);
+
+  Double_t xB =  a3*xA        - a1*zA;
+  Double_t yB =         - yA;
+  Double_t zB = -a1*xA        - a3*zA;
+  
+  Double_t dec = asin(-zB);
+  Double_t h   = TMath::ATan2(yB, xB);
+
+  //--------------------------------------------
+  decdeg = dec * kRad2Deg;
+  hhour  = h * 24.0 / TMath::TwoPi();
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PlotGridAtDec0H0
+// 
+//     set the celestial coordinates of the camera center     
+//     and plot the lines of constant (Theta, Phi)
+//          and the lines of constant (Dec,   H  )
+//
+// (see also MAstroCatalog::Draw and MAstroCamera::Draw)
+//
+// Warning: Leaks Memory!
+//
+Bool_t MStarCamTrans::PlotGridAtDec0H0(TString name,
+                                         Double_t dec0deg, Double_t h0hour) 
+{
+  Double_t theta0deg;
+  Double_t phi0deg;
+  CelToLoc(dec0deg, h0hour, theta0deg, phi0deg);
+
+  PlotGrid(name, theta0deg, phi0deg, dec0deg, h0hour);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PlotGridAtTheta0Phi0
+// 
+//     set the local coordinates of the camera center     
+//     and plot the lines of constant (Theta, Phi)
+//          and the lines of constant (Dec,   H  )
+//
+// (see also MAstroCatalog::Draw and MAstroCamera::Draw)
+//
+// Warning: Leaks Memory!
+//
+Bool_t MStarCamTrans::PlotGridAtTheta0Phi0(TString name,
+                                    Double_t theta0deg, Double_t phi0deg) 
+{
+  Double_t dec0deg;
+  Double_t h0hour;
+  LocToCel(theta0deg, phi0deg, dec0deg, h0hour);
+
+  PlotGrid(name, theta0deg, phi0deg, dec0deg, h0hour);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetGridParameters
+// 
+//     set the binning for the grid    (fGridBinning)
+//     set the binning along the lines (fGridFineBin)
+//
+Bool_t MStarCamTrans::SetGridParameters(
+             Double_t gridbinning, Double_t gridfinebin) 
+{
+  fGridBinning = gridbinning;
+  fGridFineBin = gridfinebin;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// PlotGrid
+// 
+// - plot the lines of constant (Theta, Phi) 
+//                              with the camera center at (Theta0, Phi0)
+// -  and the lines of constant (Dec,   H  ) 
+//                              with the camera center at (Dec0,   H0  )
+//
+// (see also MAstroCatalog::Draw and MAstroCamera::Draw)
+//
+// Warning: Leaks Memory! 
+//
+Bool_t MStarCamTrans::PlotGrid(TString name,
+                                 Double_t theta0deg, Double_t phi0deg,
+                                 Double_t dec0deg,   Double_t h0hour) 
+{
+    Double_t mmtodeg = 180.0 / TMath::Pi() / fDistCam ;
+    //gLog << "mmtodeg = " << mmtodeg << endl;
+
+    // aberr   is the ratio r_optaberr/r_ideal between 
+    //         the distance from the camera center with optical aberration and
+    //         the distance from the camera center with an ideal imaging
+    // the value 1.07 is valid if the expected position (with aberration)
+    // in the camera is calculated as the average of the positions obtained
+    // from the reflections at the individual mirrors
+    Double_t aberr = 1.07;
+
+    //--------------------------------------------------------------------
+
+    TCanvas *c1 = new TCanvas(name, name, 0, 0, 300, 600);
+
+    //gROOT->Reset();
+    gStyle->SetCanvasColor(0);
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetPadBorderMode(0);
+    gStyle->SetFrameBorderMode(0);
+    gStyle->SetOptStat(0000000);
+    gStyle->SetPalette(1);
+
+    c1->Divide(1,2);
+    c1->SetBorderMode(0);
+
+    Double_t xlo = -534.0 * mmtodeg;
+    Double_t xup =  534.0 * mmtodeg;
+
+    Double_t ylo = -534.0 * mmtodeg;
+    Double_t yup =  534.0 * mmtodeg;
+
+    TString nam1 = name;
+    nam1 += "_:_Theta-Phi";
+    TString tit1 = name;
+    tit1 += "_:_Theta-Phi-lines";
+    TH2D *plot1 = new TH2D(nam1, tit1, 1, xlo, xup, 1, ylo, yup);
+    plot1->GetXaxis()->SetTitle("x [deg]");
+    plot1->GetYaxis()->SetTitle("y [deg]");
+
+
+    TString nam2 = name;
+    nam2 += "_:_Dec-Hour";
+    TString tit2 = name;
+    tit2 += "_:_Dec-Hour-lines";
+    TH2D *plot2 = new TH2D(nam2, tit2, 1, xlo, xup, 1, ylo, yup);
+    plot2->GetXaxis()->SetTitle("x [deg]");
+    plot2->GetYaxis()->SetTitle("y [deg]");
+
+
+    c1->cd(1);
+    plot1->Draw();
+    //delete plot1;
+
+    c1->cd(2);
+    plot2->Draw();
+    //delete plot2;
+
+    TGraph *graph1;
+    TLatex *pix;
+
+    Char_t tit[100];
+    Double_t xtxt;
+    Double_t ytxt;
+
+    Double_t xx;
+    Double_t yy;
+
+    Double_t gridbinning = fGridBinning;
+    Double_t gridfinebin = fGridFineBin;
+    Int_t    numgridlines = (Int_t)(4.0/gridbinning);
+
+
+    //--------------------------------------------------------------------
+    // Theta-Phi lines
+
+    // direction for the center of the camera
+    Double_t theta0 = theta0deg;
+    Double_t phi0   = phi0deg;
+    
+
+    //-----   lines for fixed theta   ------------------------------------
+
+    const Int_t Ntheta = numgridlines;
+    Double_t theta[Ntheta];
+    Double_t dtheta = gridbinning;
+
+    Int_t nphi = (Int_t)(4.0/gridfinebin);
+    const Int_t Nphi   = nphi+1;
+    Double_t phi[Nphi];
+    Double_t dphi = gridfinebin/sin(theta0/180.0*3.1415926);
+    if ( dphi > 360.0/((Double_t)(Nphi-1)) )
+      dphi = 360.0/((Double_t)(Nphi-1));
+
+    for (Int_t j=0; j<Ntheta; j++)
+    {
+      theta[j] = theta0 + ((Double_t)j)*dtheta 
+                        - ((Double_t)(Ntheta/2)-1.0)*dtheta;
+    }
+
+    for (Int_t k=0; k<Nphi; k++)
+    {
+      phi[k] = phi0 + ((Double_t)k)*dphi - ((Double_t)(Nphi/2)-1.0)*dphi;
+    }
+
+
+    Double_t x[Nphi];
+    Double_t y[Nphi];
+	
+    
+
+    for (Int_t j=0; j<Ntheta; j++)
+    {
+      if (theta[j] < 0.0) continue;
+
+      for (Int_t k=0; k<Nphi; k++)
+      {
+        Loc0LocToCam(theta0, phi0, theta[j], phi[k],
+                           xx, yy);
+        x[k] = xx * mmtodeg * aberr;
+        y[k] = yy * mmtodeg * aberr;
+
+        //gLog << "theta0, phi0 = " << theta0 << ",  " << phi0 
+        //     << " : theta, phi, x, y = " << theta[j] << ",  "
+        //     << phi[k] << ";   " << x[k] << ",  " << y[k] << endl;  
+      }
+
+      c1->cd(1);
+      graph1 = new TGraph(Nphi,x,y);
+      graph1->SetLineColor(j+1);
+      graph1->SetLineStyle(1);
+      graph1->SetMarkerColor(j+1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      graph1->Draw("PL");
+      //delete graph1;
+
+      sprintf(tit,"Theta = %6.2f", theta[j]);
+      xtxt = xlo + (xup-xlo)*0.1;
+      ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)j) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(j+1);
+      pix->SetTextSize(.03);
+      pix->Draw("");
+      //delete pix;
+
+    }
+
+    //-----   lines for fixed phi   ------------------------------------
+
+    Int_t ntheta1 = (Int_t)(4.0/gridfinebin);
+    const Int_t Ntheta1 = ntheta1;
+    Double_t theta1[Ntheta1];
+    Double_t dtheta1 = gridfinebin;
+
+    const Int_t Nphi1   = numgridlines;
+    Double_t phi1[Nphi1];
+    Double_t dphi1 = gridbinning/sin(theta0/180.0*3.1415926);
+    if ( dphi1 > 360.0/((Double_t)Nphi1) )
+      dphi1 = 360.0/((Double_t)Nphi1);
+
+    for (Int_t j=0; j<Ntheta1; j++)
+    {
+      theta1[j] = theta0 + ((Double_t)j)*dtheta1 
+                        - ((Double_t)(Ntheta1/2)-1.0)*dtheta1;
+    }
+
+    for (Int_t k=0; k<Nphi1; k++)
+    {
+      phi1[k] = phi0 + ((Double_t)k)*dphi1 - ((Double_t)(Nphi1/2)-1.0)*dphi1;
+    }
+
+
+    Double_t x1[Ntheta1];
+    Double_t y1[Ntheta1];
+	
+    for (Int_t k=0; k<Nphi1; k++)
+    {
+      Int_t count = 0;
+      for (Int_t j=0; j<Ntheta1; j++)
+      {
+        if (theta1[j] < 0.0) continue;
+                 
+        Loc0LocToCam(theta0, phi0, theta1[j], phi1[k],
+                           xx, yy);
+        x1[count] = xx * mmtodeg * aberr;
+        y1[count] = yy * mmtodeg * aberr;
+
+        //gLog << "theta0, phi0 = " << theta0 << ",  " << phi0 
+        //     << " : theta1, phi1, x1, y1 = " << theta1[j] << ",  "
+        //     << phi1[k] << ";   " << x1[count] << ",  " << y1[count] << endl;  
+        count++;
+      }
+
+      c1->cd(1);
+      graph1 = new TGraph(count,x1,y1);
+      graph1->SetLineColor(k+1);
+      graph1->SetLineStyle(2);
+      graph1->SetMarkerColor(k+1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      graph1->Draw("PL");
+      //delete graph1;
+
+      sprintf(tit,"Phi = %6.2f", phi1[k]);
+      Double_t xtxt = xlo + (xup-xlo)*0.75;
+      Double_t ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)k) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(k+1);
+      pix->SetTextSize(.03);
+      pix->Draw("");
+      //delete pix;
+
+    }
+
+    c1->cd(1);
+    sprintf(tit,"Theta0 = %6.2f    Phi0 = %6.2f", theta0, phi0);
+    xtxt = xlo + (xup-xlo)*0.05;
+    ytxt = ylo + (yup-ylo)*0.92;
+    pix = new TLatex(xtxt, ytxt, tit);
+    pix->SetTextColor(1);
+    pix->SetTextSize(.06);
+    pix->Draw("");
+    //delete pix;
+
+    sprintf(tit,"                 [deg]                [deg]");
+    xtxt = xlo + (xup-xlo)*0.05;
+    ytxt = ylo + (yup-ylo)*0.86;
+    pix = new TLatex(xtxt, ytxt, tit);
+    pix->SetTextColor(1);
+    pix->SetTextSize(.06);
+    pix->Draw("");
+    //delete pix;
+
+
+    //--------------------------------------------------------------------
+    // Dec-Hour lines 
+
+    // direction for the center of the camera
+    Double_t dec0 = dec0deg;
+    Double_t h0   = h0hour;
+    //trans.LocToCel(theta0, phi0, dec0, h0);
+    
+
+    //-----   lines for fixed dec   ------------------------------------
+
+    const Int_t Ndec = numgridlines;
+    Double_t dec[Ndec];
+    Double_t ddec = gridbinning;
+
+    Int_t nh = (Int_t)(4.0/gridfinebin);
+    const Int_t Nh   = nh+1;
+    Double_t h[Nh];
+    Double_t dh = gridfinebin/cos(dec0/180.0*3.1415926);
+    if ( dh > 360.0/((Double_t)(Nh-1)) )
+      dh = 360.0/((Double_t)(Nh-1));
+
+
+    for (Int_t j=0; j<Ndec; j++)
+    {
+      dec[j] = dec0 + ((Double_t)j)*ddec 
+                        - ((Double_t)(Ndec/2)-1.0)*ddec;
+    }
+
+    for (Int_t k=0; k<Nh; k++)
+    {
+      h[k] = h0 + ((Double_t)k)*dh - ((Double_t)(Nh/2)-1.0)*dh;
+    }
+
+
+    Double_t xh[Nh];
+    Double_t yh[Nh];
+	
+    
+
+    for (Int_t j=0; j<Ndec; j++)
+    {
+      if (fabs(dec[j]) > 90.0) continue;
+
+      for (Int_t k=0; k<Nh; k++)
+      {
+        Double_t hh0 = h0   *24.0/360.0;                 
+        Double_t hx = h[k]*24.0/360.0;
+        Cel0CelToCam(dec0, hh0, dec[j], hx,
+                           xx, yy);
+        xh[k] = xx * mmtodeg * aberr;
+        yh[k] = yy * mmtodeg * aberr;
+
+        //gLog << "dec0, h0 = " << dec0 << ",  " << h0 
+        //     << " : dec, h, xh, yh = " << dec[j] << ",  "
+        //     << h[k] << ";   " << xh[k] << ",  " << yh[k] << endl;  
+      }
+
+      c1->cd(2);
+      graph1 = new TGraph(Nh,xh,yh);
+      graph1->SetLineColor(j+1);
+      graph1->SetLineStyle(1);
+      graph1->SetMarkerColor(j+1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      graph1->Draw("PL");
+      //delete graph1;
+
+      sprintf(tit,"Dec = %6.2f", dec[j]);
+      xtxt = xlo + (xup-xlo)*0.1;
+      ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)j) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(j+1);
+      pix->SetTextSize(.03);
+      pix->Draw("");
+      //delete pix;
+
+    }
+
+    //-----   lines for fixed hour angle   ------------------------------------
+
+    Int_t ndec1 = (Int_t)(4.0/gridfinebin);
+    const Int_t Ndec1 = ndec1;
+    Double_t dec1[Ndec1];
+    Double_t ddec1 = gridfinebin;
+
+    const Int_t Nh1   = numgridlines;
+    Double_t h1[Nh1];
+    Double_t dh1 = gridbinning/cos(dec0/180.0*3.1415926);
+    if ( dh1 > 360.0/((Double_t)Nh1) )
+      dh1 = 360.0/((Double_t)Nh1);
+
+
+    for (Int_t j=0; j<Ndec1; j++)
+    {
+      dec1[j] = dec0 + ((Double_t)j)*ddec1 
+                        - ((Double_t)(Ndec1/2)-1.0)*ddec1;
+    }
+
+    for (Int_t k=0; k<Nh1; k++)
+    {
+      h1[k] = h0 + ((Double_t)k)*dh1 - ((Double_t)(Nh1/2)-1.0)*dh1;
+    }
+
+
+    Double_t xd[Ndec1];
+    Double_t yd[Ndec1];
+	
+    for (Int_t k=0; k<Nh1; k++)
+    {
+      Int_t count = 0;
+      for (Int_t j=0; j<Ndec1; j++)
+      {
+        if (fabs(dec1[j]) > 90.0) continue;
+
+        Double_t hh0 = h0   *24.0/360.0;                 
+        Double_t hhx = h1[k]*24.0/360.0;   
+        Cel0CelToCam(dec0, hh0, dec1[j], hhx,
+                           xx, yy);
+        xd[count] = xx * mmtodeg * aberr;
+        yd[count] = yy * mmtodeg * aberr;
+
+        //gLog << "dec0, h0 = " << dec0 << ",  " << h0 
+        //     << " : dec1, h1, xd, yd = " << dec1[j] << ",  "
+        //     << h1[k] << ";   " << xd[count] << ",  " << yd[count] << endl;  
+
+        count++;
+      }
+
+      c1->cd(2);
+      graph1 = new TGraph(count,xd,yd);
+      graph1->SetLineColor(k+1);
+      graph1->SetLineStyle(2);
+      graph1->SetMarkerColor(k+1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      graph1->Draw("PL");
+      //delete graph1;
+
+      sprintf(tit,"H = %6.2f", h1[k]);
+      Double_t xtxt = xlo + (xup-xlo)*0.75;
+      Double_t ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)k) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(k+1);
+      pix->SetTextSize(.03);
+      pix->Draw("");
+      //delete pix;
+
+    }
+
+    c1->cd(2);
+    sprintf(tit,"Dec0 = %6.2f    H0 = %6.2f", dec0, h0);
+    xtxt = xlo + (xup-xlo)*0.05;
+    ytxt = ylo + (yup-ylo)*0.92;
+    pix = new TLatex(xtxt, ytxt, tit);
+    pix->SetTextColor(1);
+    pix->SetTextSize(.06);
+    pix->Draw("");
+    //delete pix;
+
+    sprintf(tit,"              [deg]             [deg]");
+    xtxt = xlo + (xup-xlo)*0.05;
+    ytxt = ylo + (yup-ylo)*0.86;
+    pix = new TLatex(xtxt, ytxt, tit);
+    pix->SetTextColor(1);
+    pix->SetTextSize(.06);
+    pix->Draw("");
+    //delete pix;
+ 
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mstarcam/MStarCamTrans.h
===================================================================
--- /tags/Mars-V0.9/mstarcam/MStarCamTrans.h	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/MStarCamTrans.h	(revision 9772)
@@ -0,0 +1,103 @@
+#ifndef MARS_MStarCamTrans
+#define MARS_MStarCamTrans
+
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+class MGeomCam;
+class MObservatory;
+
+class MStarCamTrans
+{
+private:
+  Double_t  fDistCam;   // distance camera reflector [mm]
+  Double_t  fCLat;      // cos(Lat)
+  Double_t  fSLat;      // sin(Lat)
+
+  Double_t fGridBinning;   // degrees
+  Double_t fGridFineBin;   // degrees
+
+public:
+  MStarCamTrans(const MGeomCam &cam, const MObservatory &obs);
+
+  Bool_t Loc0CamToLoc(Double_t theta0deg, Double_t phi0deg, 
+                      Double_t X,         Double_t Y,
+                      Double_t &thetadeg, Double_t &phideg); 
+
+  Bool_t Loc0LocToCam(Double_t theta0deg, Double_t phi0deg,
+                      Double_t thetadeg,  Double_t phideg,
+                      Double_t &X,        Double_t &Y);
+
+  Bool_t LocCamToLoc0(Double_t thetadeg,   Double_t phideg, 
+                      Double_t X,          Double_t Y,
+                      Double_t &theta0deg, Double_t &phi0deg); 
+
+  Bool_t Cel0CamToCel(Double_t dec0deg, Double_t h0hour, 
+                      Double_t X,       Double_t Y,
+                      Double_t &decdeg, Double_t &hhour); 
+
+  Bool_t Cel0CelToCam(Double_t dec0deg, Double_t h0hour,
+                      Double_t decdeg,  Double_t hhour,
+                      Double_t &X,      Double_t &Y);
+
+  Bool_t CelCamToCel0(Double_t decdeg,   Double_t hhour, 
+                      Double_t X,        Double_t Y,
+                      Double_t &dec0deg, Double_t &h0hour); 
+
+  Bool_t LocCamCamToLoc(Double_t theta1deg,  Double_t phi1deg, 
+                        Double_t X1,         Double_t Y1,
+                        Double_t X2,         Double_t Y2,
+                        Double_t &theta2deg, Double_t &phi2deg); 
+
+  Bool_t LocCamLocToCam(Double_t theta1deg, Double_t phi1deg,
+                        Double_t X1,        Double_t Y1,
+                        Double_t theta2deg, Double_t phi2deg,
+                        Double_t &X2,       Double_t &Y2);
+
+  Bool_t CelCamCamToCel(Double_t dec1deg,  Double_t h1hour, 
+                        Double_t X1,       Double_t Y1,
+                        Double_t X2,       Double_t Y2,
+                        Double_t &dec2deg, Double_t &h2hour); 
+
+  Bool_t CelCamCelToCam(Double_t dec1deg, Double_t h1hour, 
+                        Double_t X1,      Double_t Y1,
+                        Double_t dec2deg, Double_t h2hour,
+                        Double_t &X2,     Double_t &Y2);
+
+  Bool_t CelToLoc(Double_t decdeg,    Double_t hhour, 
+                  Double_t &thetadeg, Double_t &phideg); 
+
+  Bool_t LocToCel(Double_t thetadeg, Double_t phideg, 
+                  Double_t &decdeg,  Double_t &hhour);
+
+  Bool_t PlotGridAtDec0H0(TString name, 
+                          Double_t dec0deg,   Double_t h0hour);
+  Bool_t PlotGridAtTheta0Phi0(TString name,
+                              Double_t theta0deg, Double_t phi0deg);
+
+  Bool_t SetGridParameters(Double_t gridbinning,  Double_t gridfinebin);
+
+  Bool_t PlotGrid(TString name,
+                  Double_t theta0deg, Double_t phi0deg,
+	          Double_t dec0deg,   Double_t h0hour);
+
+  ClassDef(MStarCamTrans, 0) // Class for transformations between Celestial, Local and Camera coordinates 
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mstarcam/MStarPos.cc
===================================================================
--- /tags/Mars-V0.9/mstarcam/MStarPos.cc	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/MStarPos.cc	(revision 9772)
@@ -0,0 +1,279 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López ,   4/2004 <mailto:jlopez@ifae.es>
+!              Robert Wagner,   7/2004 <mailto:rwagner@mppmu.mpg.de>
+!              Wolfgang Wittek, 8/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MStarPos.h"
+
+#include <TEllipse.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MStarPos);
+
+using namespace std;
+
+MStarPos::MStarPos(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MStarPos";
+    fTitle = title ? title : "";
+    
+    Reset();
+}
+
+void MStarPos::Reset()
+{
+
+    //Expected position on camera
+     fMagExp = 0.;
+     fXExp   = 0.;
+     fYExp   = 0.;
+
+    //Ideal position on camera
+     fMagIdeal = 0.;
+     fXIdeal   = 0.;
+     fYIdeal   = 0.;
+
+    //Info from calculation
+     fMagCalc    = 0.;
+     fMaxCalc    = 0.;
+     fMeanXCalc  = 0.;
+     fMeanYCalc  = 0.;
+     fSigmaXCalc = 0.;
+     fSigmaYCalc = 0.;
+     fCorrXYCalc = 0.;
+     fXXErrCalc  = 0.;
+     fXYErrCalc  = 0.;
+     fYYErrCalc  = 0.;
+
+    //Info from Gauss fit
+     fMagFit    = 0.;
+     fMaxFit    = 0.;
+     fMeanXFit  = 0.;
+     fMeanYFit  = 0.;
+     fSigmaXFit = 0.;
+     fSigmaYFit = 0.;
+     fCorrXYFit = 0.;
+     fXXErrFit  = 0.;
+     fXYErrFit  = 0.;
+     fYYErrFit  = 0.;
+
+     fChiSquareFit = 0.;
+     fNdofFit      = 1;
+
+}
+
+void MStarPos::SetExpValues(Float_t mag, Float_t x, Float_t y)
+{
+     fMagExp = mag;
+     fXExp = x;
+     fYExp = y;
+}
+
+void MStarPos::SetIdealValues(Float_t mag, Float_t x, Float_t y)
+{
+     fMagIdeal = mag;
+     fXIdeal = x;
+     fYIdeal = y;
+}
+
+void MStarPos::SetCalcValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+               Float_t sigmaX,    Float_t sigmaY, Float_t correlation, 
+	       Float_t xx,        Float_t xy,     Float_t yy)
+{
+     fMagCalc    = mag;
+     fMaxCalc    = max;
+     fMeanXCalc  = x;
+     fMeanYCalc  = y;
+     fSigmaXCalc = sigmaX;
+     fSigmaYCalc = sigmaY;
+     fCorrXYCalc = correlation;
+     fXXErrCalc  = xx;
+     fXYErrCalc  = xy;
+     fYYErrCalc  = yy;
+}
+
+
+void MStarPos::SetFitValues(
+               Float_t mag,       Float_t max,    Float_t x,    Float_t y, 
+               Float_t sigmaX,    Float_t sigmaY, Float_t correlation, 
+               Float_t xx,        Float_t xy,     Float_t yy,
+               Float_t chiSquare, Int_t ndof)
+{
+     fMagFit    = mag;
+     fMaxFit    = max;
+     fMeanXFit  = x;
+     fMeanYFit  = y;
+     fSigmaXFit = sigmaX;
+     fSigmaYFit = sigmaY;
+     fCorrXYFit = correlation;
+     fXXErrFit  = xx;
+     fXYErrFit  = xy;
+     fYYErrFit  = yy;
+
+     fChiSquareFit = chiSquare;
+     fNdofFit      = ndof;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MStarPos::Paint(Option_t *opt)
+{
+  //Print a cross in the expected position
+  TMarker mexp(fXExp, fYExp, 29);
+  mexp.SetMarkerSize(3);
+  mexp.SetMarkerColor(94);
+  mexp.Paint(); 
+
+  if (fSigmaXCalc>0. && fSigmaYCalc>0.)
+    {
+      TEllipse ecalc(fMeanXCalc, fMeanYCalc, fSigmaXCalc, fSigmaYCalc, 
+                     0, 360, 0);
+      ecalc.SetLineWidth(3);
+      //ecalc.SetLineColor(kBlue);
+      ecalc.SetLineColor(kMagenta);
+      ecalc.Paint();
+    }
+
+  if (fSigmaXFit>0. && fSigmaYFit>0.)
+    {
+      //Print a cross in the fitted position
+      //TMarker mFit(fMeanXFit, fMeanYFit, 3);
+      //mFit.SetMarkerSize(3);
+      //mFit.SetMarkerColor(1);
+      //mFit.Paint(); 
+
+      Double_t cxx = fSigmaXFit*fSigmaXFit;
+      Double_t cyy = fSigmaYFit*fSigmaYFit;
+      Double_t d   = cyy - cxx;
+      Double_t cxy = fCorrXYFit * fSigmaXFit * fSigmaYFit;
+      Double_t tandel;
+      if (cxy != 0.0)
+        tandel = ( d + sqrt(d*d + 4.0*cxy*cxy) ) / (2.0*cxy); 
+      else
+        tandel = 0.0;
+
+      Double_t sindel = tandel / sqrt(1.0 + tandel*tandel);
+      Double_t delta = TMath::ASin(sindel);
+
+      Double_t major =   (cxx + 2.0*tandel*cxy + tandel*tandel*cyy)
+	                / (1.0 + tandel*tandel);  
+
+      Double_t minor =   (tandel*tandel*cxx - 2.0*tandel*cxy + cyy)
+	                / (1.0 + tandel*tandel);  
+
+      TEllipse efit(fMeanXFit, fMeanYFit, sqrt(major), sqrt(minor), 
+                    0, 360,      delta*kRad2Deg);
+      efit.SetLineWidth(3);
+      //efit.SetLineColor(kMagenta);
+      //efit.SetLineColor(kBlack);
+      efit.Paint();
+    }
+}
+  
+void MStarPos::Print(Option_t *opt) const
+{
+  TString o = opt;
+
+  if (o.Contains("name", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Name: \"" << this->GetName() << "\"" << endl;
+    }
+      
+  if (o.Contains("mag", TString::kIgnoreCase) || opt == NULL)
+    {
+  
+      *fLog << inf << "Star magnitude:" << endl;
+      *fLog << inf << " Ideal \t" << setw(4) << fMagIdeal << endl;
+      *fLog << inf << " Expected \t" << setw(4) << fMagExp << endl;
+      *fLog << inf << " Calcultated \t " << setw(4) << fMagCalc << endl;
+      *fLog << inf << " Fitted \t " << setw(4) << fMagFit << endl;
+    }
+  
+  if (o.Contains("max", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Maximum:" << endl;
+      *fLog << inf << " Calcultated \t " << setw(4) << fMaxCalc << " uA" 
+            << endl;
+      *fLog << inf << " Fitted \t " << setw(4) << fMaxFit << " uA" << endl;
+    }
+  
+  if (o.Contains("pos", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star position:" << endl;
+      *fLog << inf << " Ideal \t X " << setw(4) << fXIdeal 
+            << " mm \tY " << setw(4) << fYIdeal << " mm" << endl;
+      *fLog << inf << " Expected \t X " << setw(4) << fXExp 
+            << " mm \tY " << setw(4) << fYExp << " mm" << endl;
+      *fLog << inf << " Calcultated \t X " << setw(4) << fMeanXCalc 
+            << " mm \tY " << setw(4) << fMeanYCalc << " mm" << endl;
+      *fLog << inf << " Fitted \t X " << setw(4) << fMeanXFit 
+            << " mm \tY " << setw(4) << fMeanYFit << " mm" << endl;
+    }
+
+  if (o.Contains("siz", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star size:" << endl;
+      *fLog << inf << " Calcultated \t X " << setw(4) << fSigmaXCalc 
+            << " mm \tY " << setw(4) << fSigmaYCalc << " mm \t correlation " 
+            << setw(4) << fCorrXYCalc << endl;
+      *fLog << inf << " Fitted \t X " << setw(4) << fSigmaXFit 
+            << " mm \tY " << setw(4) << fSigmaYFit << " mm \t correlation " 
+            << setw(4) << fCorrXYFit << endl;
+    }
+
+  if (o.Contains("chi", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Fit Quality:" << endl;
+      *fLog << inf << " ChiSquareFit/NdofFit \t " << setw(3) 
+            << fChiSquareFit << "/" << fNdofFit << endl;
+    }
+
+  if (o.Contains("err", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Error Matrix of (fMeanX,fMeanY) :" 
+            << endl;
+      *fLog << inf << " xxCalc,xyCalc,yyCalc \t " << setw(3) << fXXErrCalc 
+            << ", " << fXYErrCalc << ", " << fYYErrCalc << endl;
+      *fLog << inf << " xxFit,xyFit,yyFit \t " << setw(3) << fXXErrFit << ", " 
+            << fXYErrFit << ", " << fYYErrFit << endl;
+    }
+
+
+}
+//--------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mstarcam/MStarPos.h
===================================================================
--- /tags/Mars-V0.9/mstarcam/MStarPos.h	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/MStarPos.h	(revision 9772)
@@ -0,0 +1,121 @@
+#ifndef MARS_MStarPos
+#define MARS_MStarPos
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MStarPos : public MParContainer
+{
+private:
+
+    //Expected position on camera
+    Float_t fMagExp;
+    Float_t fXExp;    //[mm]
+    Float_t fYExp;    //[mm]
+
+    //Ideal position on camera
+    Float_t fMagIdeal;
+    Float_t fXIdeal;    //[mm]
+    Float_t fYIdeal;    //[mm]
+
+    //Info from calculation
+    Float_t fMagCalc;
+    Float_t fMaxCalc;            //[uA]
+    Float_t fMeanXCalc;          //[mm]
+    Float_t fMeanYCalc;          //[mm]
+    Float_t fSigmaXCalc;         //[mm]
+    Float_t fSigmaYCalc;         //[mm]
+    Float_t fCorrXYCalc;          // correlation coefficient
+    Float_t fXXErrCalc;           // error matrix of (fMeanXCalc,fMeanYCalc)
+    Float_t fXYErrCalc;
+    Float_t fYYErrCalc;
+
+    //Info from Gauss fit
+    Float_t fMagFit;
+    Float_t fMaxFit;             //[uA]
+    Float_t fMeanXFit;           //[mm]
+    Float_t fMeanYFit;           //[mm]
+    Float_t fSigmaXFit;          //[mm]
+    Float_t fSigmaYFit;          //[mm]
+    Float_t fCorrXYFit;          // correlation coefficient
+    Float_t fXXErrFit;           // error matrix of (fMeanXFit,fMeanYFit)
+    Float_t fXYErrFit;
+    Float_t fYYErrFit;
+
+    Float_t fChiSquareFit;
+    Int_t   fNdofFit;
+
+
+public:
+
+    MStarPos(const char *name=NULL, const char *title=NULL);
+    //~MStarPos();
+
+    Float_t GetMagExp() {return fMagExp;}
+    Float_t GetXExp() {return fXExp;}
+    Float_t GetYExp() {return fYExp;}
+
+    Float_t GetMagIdeal() {return fMagIdeal;}
+    Float_t GetXIdeal() {return fXIdeal;}
+    Float_t GetYIdeal() {return fYIdeal;}
+
+    Float_t GetMagCalc() {return fMagCalc;}
+    Float_t GetMaxCalc() {return fMaxCalc;}
+    Float_t GetMeanXCalc() {return fMeanXCalc;}
+    Float_t GetMeanYCalc() {return fMeanYCalc;}
+    Float_t GetSigmaXCalc() {return fSigmaXCalc;}
+    Float_t GetSigmaYCalc() {return fSigmaYCalc;}
+    Float_t GetCorrXYCalc()        {return fCorrXYCalc;}
+    Float_t GetXXErrCalc()         {return fXXErrCalc;}
+    Float_t GetXYErrCalc()         {return fXYErrCalc;}
+    Float_t GetYYErrCalc()         {return fYYErrCalc;}
+
+    
+    // getters for the Gauss fit
+    Float_t GetMagFit()           {return fMagFit;}
+    Float_t GetMaxFit()           {return fMaxFit;}
+    Float_t GetMeanXFit()         {return fMeanXFit;}
+    Float_t GetMeanYFit()         {return fMeanYFit;}
+    Float_t GetSigmaXFit()        {return fSigmaXFit;}
+    Float_t GetSigmaYFit()        {return fSigmaYFit;}
+    Float_t GetCorrXYFit()        {return fCorrXYFit;}
+    Float_t GetXXErrFit()         {return fXXErrFit;}
+    Float_t GetXYErrFit()         {return fXYErrFit;}
+    Float_t GetYYErrFit()         {return fYYErrFit;}
+    Float_t GetChiSquareFit()     {return fChiSquareFit;}
+    UInt_t  GetNdofFit()          {return fNdofFit;}
+    Float_t GetChiSquareNdofFit() {return fChiSquareFit/fNdofFit;}
+
+    // -----
+    Float_t GetMeanX() {return fMeanXFit!=0?fMeanXFit:fMeanXCalc;}
+    Float_t GetMeanY() {return fMeanYFit!=0?fMeanYFit:fMeanYCalc;}
+
+    Float_t GetSigmaX() {return fSigmaXFit!=0?fSigmaXFit:fSigmaXCalc;}
+    Float_t GetSigmaY() {return fSigmaYFit!=0?fSigmaYFit:fSigmaYCalc;}
+
+
+    void Reset();
+
+    void SetExpValues(Float_t mag, Float_t x, Float_t y);
+
+    void SetIdealValues(Float_t mag, Float_t x, Float_t y);
+
+    void SetCalcValues(Float_t mag,    Float_t max,    Float_t x, Float_t y, 
+                       Float_t sigmaX, Float_t sigmaY, Float_t correlation, 
+		       Float_t xx,     Float_t xy,     Float_t yy);
+
+    void SetFitValues(Float_t mag,    Float_t max,    Float_t x, Float_t y, 
+                      Float_t sigmaX, Float_t sigmaY, Float_t correlation, 
+                      Float_t xx,     Float_t xy,     Float_t yy,
+                      Float_t chi,   Int_t ndof);
+
+    void Paint(Option_t *opt=NULL);
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MStarPos, 1) // Container that holds the star information in the PMT camera
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mstarcam/Makefile
===================================================================
--- /tags/Mars-V0.9/mstarcam/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/Makefile	(revision 9772)
@@ -0,0 +1,27 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. -I../mbase -I../mhbase -I../mhist -I../mgeom -I../mastro
+
+CINT = Starcam
+
+SRCFILES = MStarCam.cc \
+	   MStarPos.cc \
+           MStarCamTrans.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mstarcam/StarcamIncl.h
===================================================================
--- /tags/Mars-V0.9/mstarcam/StarcamIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/StarcamIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mstarcam/StarcamLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mstarcam/StarcamLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mstarcam/StarcamLinkDef.h	(revision 9772)
@@ -0,0 +1,13 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MStarPos+;
+#pragma link C++ class MStarCam+;
+
+#pragma link C++ class MStarCamTrans+;
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/Changelog
===================================================================
--- /tags/Mars-V0.9/mtemp/Changelog	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/Changelog	(revision 9772)
@@ -0,0 +1,371 @@
+Please  do  not write behind the end of line tag so that it is  possible
+to   send  a   Changelog   file  to  a  line  printer  directly.  Thanks.
+
+For your entries please follow this style:
+
+_yyyy/mm/dd:_[Your Name]
+_
+___*_filename:
+_____-_description
+_
+___*_filename2, filename3:
+_____-_description
+_
+_
+_
+
+While an underscore is a placeholder for a white-space or an empty line.
+
+                                                 -*-*- END OF LINE -*-*-
+
+
+2005/02/14: Hendrik Bartko
+   * mtemp/mmpi/macros/noise_autocorrelation_AB_all.C
+     - add new macro to calculate the noise autocorrelation for all
+       inner pixels
+
+
+
+2005/02/14: Robert Wagner
+   * mtemp/mmpi/FluxCalcAndUnfold.C
+     - Example macro for calculating a flux and unfolding it using
+       MUnfoldSpectrum and MUnfold
+
+
+
+
+2005/02/11: Robert Wagner
+   * mtemp/mmpi/MUnfoldSpectrum.[cc,h]
+     - A wrapper class which applies the general unfolding algorithms
+       of MUnfold to a gamma spectrum
+
+
+
+2005/01/07: Hendrik Bartko
+   * mtemp/mmpi/macros/noise_autocorrelation_AB.C
+     - corrected bug in AB noise correction
+
+
+
+2004/12/09: Hendrik Bartko
+   * mtemp/mmpi/macros/calculate_of_weights.C
+     - included the theoretical error calculation of the reconstructed
+       signal and arrival time in the weights computation
+
+
+
+2004/12/03: Robert Wagner
+   * mtemp/mmpi/MUnfold.[cc,h]
+     - add new class MUnfold for unfolding 
+
+   * mtemp/mmpi/macros/fluxMUnfold.C
+     - example macro based on macros/fluxUnfold.C, but using the 
+       MUnfold class
+
+
+
+2004/11/22: Marcos Lopez
+   * mtemp/mucm/classes
+     - add new classes MHFlux.{h,cc} and MHExcessEnergyTheta.{h,cc} for the
+       flux calculation.
+
+
+
+2004/10/05: Javier Rico
+   * mtemp/Makefile, TempLinkDef.h
+     - add missing MStarLocalCam
+
+
+
+2004/10/03: Hendrik Bartko
+   * mtemp/mmpi/macros/calculate_of_weights.C
+     - fixed a bug in the histogram naming
+
+
+
+2004/09/24: Hendrik Bartko
+   * mtemp/mmpi/macros/calibration_shape.C
+     - fine tuning of the plots
+   * mtemp/mmpi/macros/data_shape.C
+     - added new macro to compute the signal shape for cosmics runs
+   * mtemp/mmpi/macros/calculate_of_weights.C
+     - added new macro to compute the weights for the optimal filter
+
+
+
+2004/09/19: Hendrik Bartko
+   * mtemp/mmpi/macros/noise_autocorrelation_AB.C
+     - added new macro to compute the noise auto correlation matrix from 
+       a pedestal run
+   * mtemp/mmpi/macros/calibration_shape.C
+     - added new macro to compute the signal shape for calibration runs
+
+
+2004/09/14: Hendrik Bartko
+   * mtemp/mmpi/macros/calibrate_data_ped_standard.C
+     - added new macro to calibrate the data. The pedestals are deter-
+       mined from the cosmics events and the source position is deter-
+       mined from the an analysis of the DC current information.
+
+
+2004/09/10: Nicola Galante
+   * mtemp/mpisa/triggerdisplay/MagicTriggerDisplay.[h,cc]
+     - added the trigger display
+   * mtemp/mpisa/triggerdisplay/MagicTriggerButton.[h,cc]
+     - added custom buttons
+   * mtemp/mpisa/triggerdisplay/MMcTriggerLvl2.[h,cc]
+     - added the last modified MMcTriggerLvl2 with the new
+       changes for the trigger display
+
+
+ 2004/08/23: Robert Wagner
+   * mtemp/MLocalStarPos.[h,cc], mtemp/MLocalStarCam.[h,cc],
+     - removed (have been moved to /mstarcam)
+
+   * mtemp/Makefile, mtemp/TempLinkDef.h
+     - removed entries for mtemp/MLocalStarPos.cc
+       mtemp/MLocalStarCam.cc
+
+   * mtemp/MSourceDirections.[h,cc]
+     - report names of directions already before first
+       Process() call, containers are empty apart from that,
+       though  
+
+
+
+2004/08/19: Marcos Lopez
+   * mtemp/Makefile
+     - added the mstarcam directory in the includes list.
+ 
+
+
+ 2004/08/18: Marcos Lopez
+   * mtemp/mucm
+     - new directory for containing classes of the Madrid group.
+
+
+
+ 2004/08/17: Robert Wagner
+   * mtemp/mmpi/MAstroCamera.[h,cc]
+     - removed (merged with mastro/MAstroCamera.[h,cc])
+
+
+
+ 2004/08/16: Robert Wagner
+   * mtemp/MStarLocalPos.[h,cc]
+     - added member variables, setters and getters for ideal position,
+       i.e. position without aberration effects
+
+   * mtemp/mmpi/MAstroCamera.cc
+     - Ideal position of star is filled in MLocalStarPos container  
+
+
+
+ 2004/08/09: Robert Wagner
+   * mtemp/MSourceDirections.[h,cc]
+     - move from mtemp/mmpi to mtemp
+
+
+
+ 2004/08/05: Robert Wagner
+
+   * mtemp/mmpi/MSourceDirections.[h,cc]
+     - Converts objects given by their sky coordinates into 
+       camera coordinates by using MAstroCamera the same way
+       as MFindStars does.
+
+
+
+ 2004/08/02: Robert Wagner
+
+   * mtemp/mmpi/MFindStars.[h,cc]
+     - Functionality for finding stars by using stars from star catalog
+   
+   * mtemp/mmpi/MAstroCamera.[h,cc]
+     - Filling stars into a MStarLocalCam instead of painting them
+       (Functionality also in mastro/MAsstroCamera.[h,cc], but 
+       commented out there since MStarLocalCam not part of standard
+       MARS)
+
+   * mtemp/mmpi/macros/findstars.C
+     - sample macro for determining star positions (both with and 
+       without using a star catalog)
+
+   * mtemp/mmpi/macros/bsc5.dat
+     - Bright star catalog as used by findstars.C
+
+
+
+ 2004/07/30: Nicola Galante
+
+   * mtemp/mpisa/macros/AnalCurrents.C
+      - Added new macros AnalCurrents.C which reads DC files
+        and looks for DC clusters. Still preliminary! 
+        It currently just looks for starting pixels of clusters.
+
+
+
+ 2004/07/22: Sabrina Stark
+
+   * /mtemp/meth/MFindStars.[h,cc]
+      - new fit function, incl. constant background and rotation of 
+	2d gauss
+      - initialization of MAstroCamera
+      - new functions: 
+	     - CorrSourcePos -> calculates a corrected
+	       source position using the images of two stars
+	     - DistBetweenStars -> calculates the distances between
+	       two stars and the source
+	
+   * /mtemp/meth/MAstroCamera.[h,cc]
+      - TList *fCatList: list with star positions from catalog
+      - new functions: 
+	     - StarPosInCamera (similar to FillStarList, but
+               incl. aberration)
+      - GetCatList -> Access function to fCatList
+
+   * /mtemp/meth/MStarLocalPos.[h,cc]
+      - in function SetFitValue -> background included
+	
+
+   * /mtemp/meth/macros/CorrectSrcPos.C
+      - macro to calculate a corrected source position using
+	the images of two stars, these positions are written
+	to an output file
+
+
+	
+ 2004/07/20: David Paneque
+
+   * /mtemp/mmpi/SupercutsONOFFClasses directory containing the 
+   classes needed to optimize supercuts (and extract gamma signal) 
+   using the ON and OFF data. These classes are listed below:
+
+   MFRandomSplit.cc     
+   MSupercutsCalcONOFF.cc 
+   MTSupercutsApplied.cc
+   MHFindSignificanceONOFF.cc       
+   MFindSupercutsONOFFThetaLoop.cc 
+   MFindSupercutsONOFF.cc 
+
+   In order to add (to the compiled mars version) these classes you must add the 
+   following line to the SUBDIRS field of the general Makefile
+
+   mtemp/mmpi/SupercutsONOFFClasses
+
+
+   And that's it. It should compile without problems... there is no interference 
+   with the other classes.
+
+   I also add few macros (in the directory /mtemp/mmpi/macros/) which should help 
+   the user to use (correctly) the mentioned classes. 
+
+   SuperCutsONOFFMacro.C
+   SCDynamicalSupercutsApplied.C
+   SCNexSignificanceVSAlphaCut.C
+   
+   
+   The whole analysis is set and executed by running the macro  SuperCutsONOFFMacro.C.
+   I wrote quite some comments on it; it should be self-explanatory. 
+   The macro SCDynamicalSupercutsApplied.C can be used to make a quick 
+   inspection to the cuts applied to the events that survived the cuts, and the 
+   macro    SCNexSignificanceVSAlphaCut.C plots the significance and the excess events 
+   vs the cut in the ALPHA parameter.
+
+   I also included the directory mtemp/mmpi/asciifiles containing ascii files with 
+   some initial supercuts values and the optimized supercuts for Mkn421 Feb 15, 
+   that are used as input for the supercuts ON-OFF analysis.
+						 
+
+ 2004/06/29: Javier Rico
+
+   * MIslands.[h,cc], MIslandCalc.[h,cc]
+      - Remove obsolete versions of these classes whose up-to-date ver-
+	sions are available at mifae/library
+
+
+ 2004/06/26: Eva Domingo - Pepe Flix
+
+   * mifae/library/MDisp.[h,cc]
+   * mifae/library/MDispCalc.[h,cc]
+      - Added classes for evaluation of DISP method.
+
+ 2004/06/25: Sebastian Commichau
+
+   * meth/macros/analysis.C 
+      -Added macro to analyze data
+
+   * meth/macros/analysis_read.C 
+      -Added macro that reads the output of analysis.C	
+
+ 2004/06/24: Nicola Galante
+
+   * mpisa/macros/AlphaPlot.C
+     -Added a new macro to plot eccess in alpha
+
+ 2004/05/26: Nicola Galante
+
+   * mpisa/macros/timedist3.C
+     - Added a new macro to plot signal time distributions
+
+ 2004/05/26: Nicola Galante
+
+   * mpisa/macros/production3.C
+     - Added a new production macro. It is based on 
+       bootcampstandardanalisys.C
+
+ 2004/05/23: Thomas Hengstebeck
+   * mberlin/macros/ScaleHillas.C , SrcCorrect.C , Convert2Matrix.C , 
+     CutOptim.C , AlphaPlot.C , IOMkn421.h
+     - Added analysis macros
+
+
+ 2004/05/18: Daniel Mazin
+   * mmpi/macros/hillasread.C  
+     - Removed a small bug
+
+   * mmpi/macros/callalphaplot.C
+     - Added. macro to produce an alpha plot for a chosen position in the sky map
+     - Derotation is possible if theta and phi for each event are available 
+     - Using OFF data to estimate significance is optional 
+
+ 2004/05/18: Sebastian Commichau
+   * meth/MHillasSrc.cc/h
+     - Added. This is a modified version, containing now
+       the DCA parameter.
+
+   * meth/MDCACalc.cc/h, MDCA.cc/h
+     - Added. Based on MHillasCalc/MHillas, it calculates
+       the DCA parameter and provides a nice draw function
+
+ 2004/05/17: Daniel Mazin
+   * mmpi/macros 
+     - Added to put analysis macros there
+
+   * mmpi/macros/callcleaning.C , cleaninghillas.C
+     - Added. macros to make cleaning and calculate Hillas parameters
+	
+   * mmpi/macros/mtools.C
+     -Added. some simple mathematical functions 
+
+   * mmpi/macros/falsesourcemethod.C, skyplot.h, hillasread.C, gridloop.C
+     -Added. macros to produce 2D plots of False Source Method 
+
+ 2004/04/28: Javier Rico
+   * mifae/Changelog
+     - Added. Next changes in directory mifae will be reported 
+       exclusively in there
+
+	
+ 2004/04/27: Javier Rico
+   * mifae
+     - Add new directory for IFAE temporal stuff
+	
+   * mifae/Makefile,IFAEIncl.h,IFAELinkDef.h
+     - Add basic stuff to run the directory
+	
+   * mifae/MDCA.[h,cc]
+     - Add Commichau & Starks's MDCA (provisional)
+
+   * mifae/makeHillas.cc,makehillas.datacard
+     - Add program to generate hillas parameters' file
Index: /tags/Mars-V0.9/mtemp/MFindStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MFindStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MFindStars.cc	(revision 9772)
@@ -0,0 +1,1278 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Robert Wagner,   2/2004 <mailto:rwagner@mppmu.mpg.de>
+!              Javier López ,   4/2004 <mailto:jlopez@ifae.es>
+!              Wolfgang Wittek, 8/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFindStars
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFindStars.h"
+
+#include <TMinuit.h>
+#include <TStopwatch.h>
+#include <TTimer.h>
+#include <TString.h>
+#include <TFile.h>
+#include <TTree.h>
+#include <TCanvas.h>
+#include <TH1F.h>
+#include <TF1.h>
+#include <TEllipse.h>
+
+
+#include "MObservatory.h"
+#include "MAstroCamera.h"
+#include "MMcConfigRunHeader.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+#include "MTime.h"
+#include "MReportDrive.h"
+#include "MStarCam.h"
+#include "MStarPos.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MFindStars);
+using namespace std;
+
+const Float_t sqrt2 = sqrt(2.);
+const Float_t sqrt3 = sqrt(3.);
+const UInt_t  lastInnerPixel = 396;
+    
+
+//______________________________________________________________________________
+//
+// The 2D uncorrelated gaussian function used to fit the spot of the star
+//
+static Double_t func(float x,float y,Double_t *par)
+{
+    Double_t value=par[0]*exp( -(x-par[1])*(x-par[1])/(2*par[2]*par[2]) )
+                         *exp( -(y-par[3])*(y-par[3])/(2*par[4]*par[4]) );
+    return value;
+}
+
+//______________________________________________________________________________
+//
+// The 2D correlated gaussian function used to fit the spot of the star
+//
+static Double_t funcCG(float x,float y,Double_t *par)
+{
+  Double_t temp  = 1.0-par[5]*par[5];
+  //  Double_t value = par[0] / (2.0*TMath::Pi()*par[2]*par[4]*sqrt(temp))
+  Double_t value = par[0] 
+    * exp( -0.5/temp * (   (x-par[1])*(x-par[1])/(par[2]*par[2])
+	     -2.0*par[5] * (x-par[1])*(y-par[3])/(par[2]*par[4])
+			 + (y-par[3])*(y-par[3])/(par[4]*par[4]) ) );
+    return value;
+}
+
+//______________________________________________________________________________
+//
+// Function used by Minuit to do the fit
+//
+static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+
+  MParList*      plist = (MParList*)gMinuit->GetObjectFit();
+  MTaskList*     tlist = (MTaskList*)plist->FindObject("MTaskList");
+  MFindStars*    find  = (MFindStars*)tlist->FindObject("MFindStars");
+  MStarCam* stars = 
+          (MStarCam*)plist->FindObject("MStarCam","MStarCam");
+  MGeomCam*      geom  = (MGeomCam*)plist->FindObject("MGeomCam");
+
+  MHCamera& display = (MHCamera&)find->GetDisplay();
+  
+  Float_t innerped = stars->GetInnerPedestalDC();
+  Float_t innerrms = stars->GetInnerPedestalRMSDC();
+  Float_t outerped = stars->GetOuterPedestalDC();
+  Float_t outerrms = stars->GetOuterPedestalRMSDC();
+
+  UInt_t numPixels = geom->GetNumPixels();
+  
+
+//calculate chisquare
+    Double_t chisq = 0;
+    Double_t delta;
+    Double_t x,y,z;
+    Double_t errorz=0;
+
+    UInt_t usedPx=0;
+    for (UInt_t pixid=1; pixid<numPixels; pixid++) 
+    {
+
+
+	if (display.IsUsed(pixid))
+	{
+	    x = (*geom)[pixid].GetX();
+	    y = (*geom)[pixid].GetY();
+
+            z = display.GetBinContent(pixid+1)
+                -  (pixid>lastInnerPixel?outerped:innerped);
+            errorz=(pixid>lastInnerPixel?outerrms:innerrms);
+
+
+	    if (errorz > 0.0)
+	    {
+              usedPx++;
+
+              Double_t fu;
+              if (find->GetUseCorrelatedGauss())
+                fu = funcCG(x,y,par);
+              else
+                fu = func(x,y,par);
+
+              delta  = (z-fu) / errorz;
+              chisq += delta*delta; 
+
+              if (iflag == 3)
+	      {
+                gLog  << "fcn : usedPx, pixid, content, pedestal,z, fu, errorz, delta = "
+                      << usedPx << ",  " << pixid << ",  "
+                      << display.GetBinContent(pixid+1) << ",  "
+                      << (pixid>lastInnerPixel?outerped:innerped)
+                      << ",  " << z << ",  " << fu << ",  " << errorz 
+                      << ",  " << delta << endl;
+	      }
+	    }
+	    else
+		cerr << " TMinuit::fcn errorz[" << pixid << "] " << errorz << endl;
+	}
+    }
+    f = chisq;
+
+    find->SetChisquare(chisq);
+    find->SetDegreesofFreedom(usedPx);
+
+    //gLog << "fcn : chisq, usedPx = " << chisq << ",  " << usedPx << endl;
+}
+
+//-------------------------------------------------------------------------
+//
+// Constructor
+//
+
+MFindStars::MFindStars(const char *name, const char *title): 
+  fGeomCam(NULL), fCurr(NULL), fTimeCurr(NULL), fDrive(NULL), fStars(NULL), 
+  fNumVar(6)
+{
+  fName  = name  ? name  : "MFindStars";
+  fTitle = title ? title : "Tool to find stars from DC Currents";
+
+  // the correlated Gauss function  
+  // is fitted by default
+  fNumVar = 6;
+  fUseCorrelatedGauss = kTRUE;
+
+  fNumIntegratedEvents=0;
+  fMaxNumIntegratedEvents = 10;
+  fRingInterest = 125.; //[mm] ~ 0.4 deg
+  fDCTailCut = 4;
+  
+  fPixelsUsed.Set(577);
+  fPixelsUsed.Reset((Char_t)kTRUE);
+  
+  //Fitting(Minuit) initialitation
+  const Float_t pixelSize = 31.5; //[mm]
+  fMinuitPrintOutLevel = -1;
+  //fMinuitPrintOutLevel = 3;
+  
+  fVname = new TString[fNumVar];
+  fVinit.Set(fNumVar); 
+  fStep.Set(fNumVar); 
+  fLimlo.Set(fNumVar); 
+  fLimup.Set(fNumVar); 
+  fFix.Set(fNumVar);
+
+  fVname[0] = "max";
+  fVinit[0] = 10.*fMaxNumIntegratedEvents;
+  fStep[0]  = fVinit[0]/sqrt2;
+  fLimlo[0] = fMinDCForStars;
+  fLimup[0] = 30.*fMaxNumIntegratedEvents;
+  fFix[0]   = 0;
+
+  fVname[1] = "meanx";
+  fVinit[1] = 0.;
+  fStep[1]  = fVinit[1]/sqrt2;
+  fLimlo[1] = -600.;
+  fLimup[1] = 600.;
+  fFix[1]   = 0;
+
+  fVname[2] = "sigmax";
+  fVinit[2] = pixelSize;
+  fStep[2]  = fVinit[2]/sqrt2;
+  fLimlo[2] = pixelSize/(2*sqrt3);
+  fLimup[2] = 500.;
+  fFix[2]   = 0;
+
+  fVname[3] = "meany";
+  fVinit[3] = 0.;
+  fStep[3]  = fVinit[3]/sqrt2;
+  fLimlo[3] = -600.;
+  fLimup[3] = 600.;
+  fFix[3]   = 0;
+
+  fVname[4] = "sigmay";
+  fVinit[4] = pixelSize;
+  fStep[4]  = fVinit[4]/sqrt2;
+  fLimlo[4] = pixelSize/(2*sqrt3);
+  fLimup[4] = 500.;
+  fFix[4]   = 0;
+
+  if (fUseCorrelatedGauss)
+  {
+    fVname[5] = "xycorr";
+    fVinit[5] = 0.0;
+    fStep[5]  = 0.1;
+    fLimlo[5] = -1.0;
+    fLimup[5] =  1.0;
+    fFix[5]   = 0;
+  }
+
+  fObjectFit  = NULL;
+  //  fMethod     = "SIMPLEX";
+  fMethod     = "MIGRAD";
+  //  fMethod     = "MINIMIZE";
+  fNulloutput = kFALSE;
+
+  // Set output level
+  //  fLog->SetOutputLevel(3); // No dbg messages
+
+  fGeometryFile="";
+  fBSCFile="";
+}
+
+//-------------------------------------------------------------------------
+//
+// Set 'fUseCorrelatedGauss' flag
+//
+//     if 'fUseCorrelatedGauss' is TRUE a 2dim Gaussian with correlation
+//                                 will be fitted
+//
+
+void MFindStars::SetUseCorrelatedGauss(Bool_t usecorrgauss)
+{
+  fUseCorrelatedGauss = usecorrgauss;
+
+  if (usecorrgauss)
+    fNumVar = 6;
+  else
+    fNumVar = 5;
+}
+
+//-------------------------------------------------------------------------
+//
+// PreProcess
+//
+
+Int_t MFindStars::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+
+    if (!fGeomCam)
+    {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    // Initialize camera display with the MGeomCam information
+    fDisplay.SetGeometry(*fGeomCam,"FindStarsDisplay","FindStarsDisplay");
+    fDisplay.SetUsed(fPixelsUsed);
+
+    fCurr = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+
+    if (!fCurr)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fTimeCurr = (MTime*)pList->FindObject(AddSerialNumber("MTimeCurrents"));
+
+    if (!fTimeCurr)
+    {
+      *fLog << err << AddSerialNumber("MTimeCurrents") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fDrive = (MReportDrive*)pList->FindObject(AddSerialNumber("MReportDrive"));
+
+    if (!fDrive)
+      {
+
+        *fLog << warn << AddSerialNumber("MReportDrive") << " not found ... ignored." << endl;
+
+      }
+    else
+      {
+	
+	MObservatory magic1;
+
+	MMcConfigRunHeader *config=0;
+	MGeomCam           *geom=0;
+
+	TFile file(fGeometryFile);
+	TTree *tree = (TTree*)file.Get("RunHeaders");
+	tree->SetBranchAddress("MMcConfigRunHeader", &config);
+	if (tree->GetBranch("MGeomCam")) tree->SetBranchAddress("MGeomCam", &geom);
+	tree->GetEntry(0);
+	
+	fAstro.SetMirrors(*config->GetMirrors());
+	fAstro.SetGeom(*geom);	
+	fAstro.ReadBSC(fBSCFile);
+	
+	fAstro.SetObservatory(magic1);
+	
+      }
+    
+
+    fStars = (MStarCam*)pList->FindCreateObj(AddSerialNumber("MStarCam"),"MStarCam");
+    if (!fStars)
+    {
+      *fLog << err << AddSerialNumber("MStarCam") << " cannot be created ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fMinDCForStars = 1.*fMaxNumIntegratedEvents; //[uA]
+
+    // Initialize the TMinuit object
+
+    TMinuit *gMinuit = new TMinuit(fNumVar);  //initialize TMinuit with a maximum of params
+    gMinuit->SetFCN(fcn);
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+    arglist[0] = fMinuitPrintOutLevel;
+    gMinuit->mnexcm("SET PRI", arglist ,1,ierflg);
+
+    // suppress warnings
+    Int_t errWarn;
+    Double_t tmpwar = 0;
+    gMinuit->mnexcm("SET NOW", &tmpwar, 0, errWarn);
+
+
+    // Set MParList object pointer to allow mimuit to access internally
+    gMinuit->SetObjectFit(pList);
+
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Process :
+//              
+//
+//
+//
+
+Int_t MFindStars::Process()
+{
+
+  UInt_t numPixels = fGeomCam->GetNumPixels();
+  TArrayC origPixelsUsed;
+  origPixelsUsed.Set(numPixels);
+
+  if (fNumIntegratedEvents >= fMaxNumIntegratedEvents) {
+
+    //Fist delete the previous stars in the list
+    fStars->GetList()->Delete();
+
+    if (fDrive) {
+
+      //If drive information is provided we take RaDec info
+      //from the drive and let the star list fill by the astrocamera.
+
+      //FIXME: rwagner: Doesn't work as expected
+      //FIXME: rwagner: For the time being set manually.
+      //fAstro.SetRaDec(fDrive->GetRa(), fDrive->GetDec());              
+
+      fAstro.SetTime(*fTimeCurr);
+      fAstro.SetGuiActive();
+      fAstro.FillStarList(fStars->GetList());      
+
+      //cout << "Number of Stars added by astrocamera is " 
+      //     <<fStars->GetList()->GetSize() << endl;
+      
+      MStarPos* starpos;
+      TIter Next(fStars->GetList());
+      while ((starpos=(MStarPos*)Next())) {
+	//starpos->SetCalcValues(40,40,starpos->GetXExp(), starpos->GetYExp(),
+        //                       fRingInterest/2,          fRingInterest/2,
+        //                       0.,   0., 0., 0.);
+	//starpos->SetFitValues (40,40,starpos->GetXExp(), starpos->GetYExp(),
+        //                       fRingInterest/2,          fRingInterest/2, 0.,
+        //                       0., 0., 0.,   0., -1);
+      }
+
+      for (UInt_t pix=1; pix<numPixels; pix++) {
+	if (fDisplay.IsUsed(pix))
+	  origPixelsUsed[pix]=(Char_t)kTRUE;
+	else
+	  origPixelsUsed[pix]=(Char_t)kFALSE;
+      }
+      
+      DCPedestalCalc();
+
+    } 
+    else 
+    {
+      
+      cout << "No drive information available: Will not use a star catalog to identify stars."<< endl;
+      
+      for (UInt_t pix=1; pix<numPixels; pix++) {
+	if (fDisplay.IsUsed(pix))
+	  origPixelsUsed[pix]=(Char_t)kTRUE;
+	else
+	  origPixelsUsed[pix]=(Char_t)kFALSE;
+      }
+          
+      if (DCPedestalCalc()) {
+
+	Float_t innermin = fStars->GetInnerPedestalDC()+fDCTailCut*fStars->GetInnerPedestalRMSDC();
+	Float_t outermin = fStars->GetOuterPedestalDC()+fDCTailCut*fStars->GetOuterPedestalRMSDC();
+	fMinDCForStars = innermin>outermin?innermin:outermin;
+	if (fMinuitPrintOutLevel>=0) *fLog << dbg << "fMinDCForStars = " << fMinDCForStars << endl;
+              
+	// Find the star candidates searching the most brights pairs of pixels
+	Float_t maxPixelDC;
+	MGeomPix maxPixel;
+	
+	while(FindPixelWithMaxDC(maxPixelDC, maxPixel)) {
+	  MStarPos *starpos = new MStarPos;
+
+  	  starpos->SetExpValues(maxPixelDC,maxPixel.GetX(),maxPixel.GetY());
+
+	  //starpos->SetCalcValues(maxPixelDC,      maxPixelDC,
+          //                       maxPixel.GetX(), maxPixel.GetY(),
+          //                       fRingInterest/2, fRingInterest/2,
+          //                       0.,   0., 0., 0.);
+
+	  //starpos->SetFitValues(maxPixelDC,      maxPixelDC,
+          //                      maxPixel.GetX(), maxPixel.GetY(),
+          //                      fRingInterest/2, fRingInterest/2, 0.,
+          //                      0., 0., 0.,      0., -1);
+
+	  fStars->GetList()->Add(starpos);
+	  ShadowStar(starpos);
+	}	
+	fDisplay.SetUsed(origPixelsUsed);
+      }      
+    }
+
+    //Show the stars found
+    //fStars->Print("namepossizechierr");
+   
+    //loop to extract position of stars on the camera
+    if (fStars->GetList()->GetSize() == 0) {
+      *fLog << err << GetName() << "No stars candidates in the camera." << endl;
+      return kCONTINUE;
+    } else
+    {
+      //*fLog << inf << GetName() << " found " << fStars->GetList()->GetSize() 
+      //	    << " star candidates in the camera." << endl;
+    }    
+
+    for (UInt_t pix=1; pix<numPixels; pix++) {
+      if (fDisplay.IsUsed(pix))
+	origPixelsUsed[pix]=(Char_t)kTRUE;
+      else
+	origPixelsUsed[pix]=(Char_t)kFALSE;
+    }
+
+    TIter Next(fStars->GetList());
+    MStarPos* star;
+    while ((star=(MStarPos*)Next())) {
+       FindStar(star);
+       ShadowStar(star);
+    }
+
+    //Show the stars found: Here it is interesting to see what FindStars
+    //made out of the positions we gave to it.
+    if (fMinuitPrintOutLevel>=0)
+      fStars->Print("namepossizchierr");
+
+    //After finding stars reset all variables
+    fDisplay.Reset();
+    fStars->GetDisplay().Reset(); //FIXME: Put this display just in the container
+    fDisplay.SetUsed(origPixelsUsed);
+    fNumIntegratedEvents=0;
+  }
+
+  for (UInt_t pix=1; pix<numPixels; pix++) {
+    if (fDisplay.IsUsed(pix))
+      origPixelsUsed[pix]=(Char_t)kTRUE;
+    else
+      origPixelsUsed[pix]=(Char_t)kFALSE;
+    
+  }
+  
+  fDisplay.AddCamContent(*fCurr);
+  fNumIntegratedEvents++;
+  fDisplay.SetUsed(origPixelsUsed);
+  
+  return kTRUE;
+}
+
+Int_t MFindStars::PostProcess()
+{
+  return kTRUE;
+}
+
+void MFindStars::SetBlindPixels(TArrayS blindpixels)
+{
+    Int_t npix = blindpixels.GetSize();
+
+    for (Int_t idx=0; idx<npix; idx++)
+      {
+	fPixelsUsed[blindpixels[idx]]=(Char_t)kFALSE;
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << "MFindStars::SetBlindPixels fDisplay.IsUsed(" <<blindpixels[idx]  << ") kFALSE" << endl;
+      }
+    
+    fDisplay.SetUsed(fPixelsUsed);
+}
+
+//-------------------------------------------------------------------------
+//
+// DCPedestalCalc :
+//
+//  
+//
+//
+
+Bool_t MFindStars::DCPedestalCalc()
+{
+    //-------------------------------------------------------------
+    // save pointer to the MINUIT object for optimizing the supercuts
+    // because it will be overwritten 
+    // when fitting the alpha distribution in MHFindSignificance
+    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+   UInt_t numPixels = fGeomCam->GetNumPixels();
+   Float_t ped;
+   Float_t rms;
+
+   //TH1F **dchist = new TH1F*[2];
+   TH1F *dchist[2];
+   TString tit;
+   TString nam;
+   for (UInt_t i=0; i<2; i++)
+   {
+      nam = i;
+      tit = "dchist[";
+      tit += i;
+      tit += "]";
+      dchist[i] = new TH1F(nam, tit,
+                  26,0.4*fMaxNumIntegratedEvents,3.*fMaxNumIntegratedEvents);
+   }   
+
+   for (UInt_t pix=1; pix<=lastInnerPixel; pix++)
+       dchist[0]->Fill(fDisplay.GetBinContent(pix+1));
+   for (UInt_t pix=lastInnerPixel+1; pix<numPixels; pix++)
+       dchist[1]->Fill(fDisplay.GetBinContent(pix+1));
+
+   // inner/outer pixels
+   for (UInt_t i=0; i<2; i++)
+   {
+      Float_t nummaxprobdc = dchist[i]->GetBinContent(dchist[i]->GetMaximumBin());
+      Float_t maxprobdc = dchist[i]->GetBinCenter(dchist[i]->GetMaximumBin());
+      UInt_t bin = dchist[i]->GetMaximumBin();
+      do
+        {
+          bin++;
+        }
+      while(dchist[i]->GetBinContent(bin)/nummaxprobdc > 0.5);
+      Float_t halfmaxprobdc = dchist[i]->GetBinCenter(bin);
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " maxprobdc[high] " << maxprobdc << "[" << nummaxprobdc << "] ";
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " halfmaxprobdc[high] " << halfmaxprobdc << "[" << dchist[i]->GetBinContent(bin) << "]" << endl;
+      
+      Float_t rmsguess = TMath::Abs(maxprobdc-halfmaxprobdc);
+      Float_t min = maxprobdc-3*rmsguess;
+      min = (min<0.?0.:min);
+      Float_t max = maxprobdc+3*rmsguess;
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+      
+      TF1 func("func","gaus",min,max);
+      func.SetParameters(nummaxprobdc, maxprobdc, rmsguess);
+      
+      dchist[i]->Fit("func","QR0");
+      
+      UInt_t aproxnumdegrees = 6*(bin-dchist[i]->GetMaximumBin());
+      Float_t chiq = func.GetChisquare();
+      ped = func.GetParameter(1);
+      rms = func.GetParameter(2);
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " ped " << ped << " rms " << rms << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+      
+      Int_t numsigmas = 5;
+      Axis_t minbin = ped-numsigmas*rms/dchist[i]->GetBinWidth(1);
+      minbin=minbin<1?1:minbin;
+      Axis_t maxbin = ped+numsigmas*rms/dchist[i]->GetBinWidth(1);
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " Number of pixels with dc under " << numsigmas << " sigmas = " << dchist[i]->Integral((int)minbin,(int)maxbin) << endl;
+      
+      //Check results from the fit are consistent
+      if (ped < 0. || rms < 0.)
+        {
+          *fLog << dbg << "dchist[i]->GetEntries()" << dchist[i]->GetEntries();
+//            TCanvas *c1 = new TCanvas("c2","c2",500,800);
+//            dchist[i]->Draw();
+//            c1->Print("dchist.ps");
+//            delete c1;
+//            exit(1);
+        }
+      else if (TMath::Abs(ped-maxprobdc) > rmsguess || rms > rmsguess)
+        {
+          *fLog << warn << GetName() << " Pedestal DC fit give non consistent results for " << (i==0?"Inner":"Outer") << "pixels." << endl;
+          *fLog << warn << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+          *fLog << warn << " ped " << ped << " rms " << rms << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+          ped = maxprobdc;
+          rms = rmsguess/1.175; // FWHM=2.35*rms
+        }
+   
+      if (i == 0)
+        {
+          fStars->SetInnerPedestalDC(ped);
+          fStars->SetInnerPedestalRMSDC(rms);
+        }
+      else
+        {
+          fStars->SetOuterPedestalDC(ped);
+          fStars->SetOuterPedestalRMSDC(rms);
+        }
+   }
+   
+
+
+   for (UInt_t i=0; i<2; i++)
+   {
+      delete dchist[i];
+   }
+   //delete [] dchist;
+
+   //=================================================================
+
+   // reset gMinuit to the MINUIT object for optimizing the supercuts 
+   gMinuit = savePointer;
+   //-------------------------------------------
+   
+   if (fStars->GetInnerPedestalDC() < 0. ||  fStars->GetInnerPedestalRMSDC() < 0. || fStars->GetOuterPedestalDC() < 0. ||  fStars->GetOuterPedestalRMSDC() < 0.)
+     return kFALSE;
+  
+   return kTRUE;
+}
+    
+Bool_t MFindStars::FindPixelWithMaxDC(Float_t &maxDC, MGeomPix &maxPix)
+{
+    UInt_t numPixels = fGeomCam->GetNumPixels();
+
+// Find the two close pixels with the maximun dc
+    UInt_t maxPixIdx[2];
+
+    maxDC = 0;
+
+    for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+	if(fDisplay.IsUsed(pix))
+	{
+	    Float_t dc[2];
+	    dc[0] = fDisplay.GetBinContent(pix+1);
+	    if (dc[0] < fMinDCForStars)
+		continue;
+
+	    MGeomPix &g = (*fGeomCam)[pix];
+	    Int_t numNextNeighbors = g.GetNumNeighbors();
+	    
+	    Float_t dcsum;
+	    for(Int_t nextNeighbor=0; nextNeighbor<numNextNeighbors; nextNeighbor++)
+	    {
+              UInt_t swneighbor = g.GetNeighbor(nextNeighbor);
+              if(fDisplay.IsUsed(swneighbor))
+                {
+                  dc[1] = fDisplay.GetBinContent(swneighbor+1);
+                  if (dc[1] < fMinDCForStars)
+                    continue;
+                  
+                  dcsum = dc[0] + dc[1];
+                  
+                  if(dcsum > maxDC*2)
+                    {
+                      if(dc[0]>=dc[1])
+                        {
+                          maxPixIdx[0] = pix;
+                          maxPixIdx[1] = swneighbor;
+                          maxDC = dc[0];
+                        }
+                      else
+                        {
+                          maxPixIdx[1] = pix;
+                          maxPixIdx[0] = swneighbor;
+                          maxDC = dc[1];
+                        }
+                    }	
+                }
+            }
+        }
+    }
+
+    if (maxDC == 0)
+      {
+        *fLog << warn << " No found pixels with maximum dc" << endl;
+	return kFALSE;
+      }
+    
+    maxPix = (*fGeomCam)[maxPixIdx[0]];
+
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << "Star candidate maxDC(" << setw(3) << maxDC << " uA) x position(" << setw(3) << maxPix.GetX() <<  " mm) x position(" << setw(3) << maxPix.GetY() << " mm) swnumber(" << maxPixIdx[0] << ")" << endl;
+
+    return kTRUE;
+}
+
+
+//----------------------------------------------------------------------------
+//
+// FindStar
+//
+//
+//
+
+Bool_t MFindStars::FindStar(MStarPos* star)
+{    
+  UInt_t numPixels = fGeomCam->GetNumPixels();
+  Float_t innerped = fStars->GetInnerPedestalDC();
+  Float_t outerped = fStars->GetOuterPedestalDC();
+
+  TArrayC origPixelsUsed;
+  origPixelsUsed.Set(numPixels);
+  
+  for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+      if (fDisplay.IsUsed(pix))
+        origPixelsUsed[pix]=(Char_t)kTRUE;
+      else
+        origPixelsUsed[pix]=(Char_t)kFALSE;
+    }
+  
+  Float_t expX = star->GetXExp();
+  Float_t expY = star->GetYExp();
+
+  Float_t max         =0;
+  UInt_t  pixmax      =0;
+  Float_t meanX       =0;
+  Float_t meanY       =0;
+  Float_t meanSqX     =0;
+  Float_t meanSqY     =0;
+  Float_t sumCharge   =0;
+  Float_t sumSqCharge =0;
+  UInt_t  usedInnerPx =0;	
+  UInt_t  usedOuterPx =0;	
+  Float_t factor = 1.0;
+
+  Float_t meanXold = 1.e10;
+  Float_t meanYold = 1.e10;
+
+  const Float_t meanPresition = 3.; //[mm]
+  const UInt_t maxNumIterations = 10;
+  UInt_t numIterations = 0;
+
+  //--------------------   start of iteration loop   -----------------------
+  for (UInt_t it=0; it<maxNumIterations; it++)
+  {
+      //rwagner: Need to find px with highest dc and need to assume it is
+      // somewhere near the center of the star
+      //after that we need to REDEFINE our roi! because expected pos could be
+      // quite off that px!
+      
+      // 1.) Initial roi around expected position
+
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	{
+	  
+	  Float_t pixXpos=(*fGeomCam)[pix].GetX();
+	  Float_t pixYpos=(*fGeomCam)[pix].GetY();
+	  Float_t dist = sqrt((pixXpos-expX)*(pixXpos-expX)+
+			      (pixYpos-expY)*(pixYpos-expY));
+	  
+	  if ((dist < fRingInterest) && fDisplay.IsUsed(pix))
+	    fPixelsUsed[pix]=(Char_t)kTRUE;
+	  else
+	    fPixelsUsed[pix]=(Char_t)kFALSE;
+	}
+      fDisplay.SetUsed(fPixelsUsed);
+
+      // 2.) Find px with highest dc in that region
+
+      max    = 0.0;
+      pixmax =   0;
+      for(UInt_t pix=0; pix<numPixels; pix++)	
+	if(fDisplay.IsUsed(pix))
+	  {
+	    Float_t charge  = fDisplay.GetBinContent(pix+1);	      
+	    if (charge>max)
+	      {
+		max=charge;
+		pixmax=pix;
+	      }
+	  }         
+
+      // 3.) make it new center
+
+      expX = (*fGeomCam)[pixmax].GetX();
+      expY = (*fGeomCam)[pixmax].GetY();
+
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	fPixelsUsed[pix]=(Char_t)kTRUE;       
+      fDisplay.SetUsed(fPixelsUsed);
+
+      // First define a area of interest around the expected position of the star
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	{
+	  Float_t pixXpos=(*fGeomCam)[pix].GetX();
+	  Float_t pixYpos=(*fGeomCam)[pix].GetY();
+	  Float_t dist = sqrt((pixXpos-expX)*(pixXpos-expX)+
+			      (pixYpos-expY)*(pixYpos-expY));
+	  
+	  if ((dist < fRingInterest) && fDisplay.IsUsed(pix))
+	    fPixelsUsed[pix]=(Char_t)kTRUE;
+	  else
+	    fPixelsUsed[pix]=(Char_t)kFALSE;
+	}
+  
+      fDisplay.SetUsed(fPixelsUsed);
+    
+      // determine mean x and mean y
+      max         = 0.0;
+      pixmax      =   0;
+      meanX       = 0.0;
+      meanY       = 0.0;
+      meanSqX     = 0.0;
+      meanSqY     = 0.0;
+      sumCharge   = 0.0;
+      sumSqCharge = 0.0;
+      usedInnerPx =   0;	
+      usedOuterPx =   0;	
+
+      for(UInt_t pix=0; pix<numPixels; pix++)
+	{
+	  if(fDisplay.IsUsed(pix))
+	    {
+	      pix>lastInnerPixel?usedOuterPx++:usedInnerPx++;
+	      
+	      Float_t charge  = fDisplay.GetBinContent(pix+1);
+	      Float_t pixXpos = (*fGeomCam)[pix].GetX();
+	      Float_t pixYpos = (*fGeomCam)[pix].GetY();
+	      
+	      if (charge>max)
+		{
+		  max=charge;
+		  pixmax=pix;
+		}
+	      
+	      meanX     += charge*pixXpos;
+	      meanY     += charge*pixYpos;
+	      meanSqX   += charge*pixXpos*pixXpos;
+	      meanSqY   += charge*pixYpos*pixYpos;
+	      sumCharge   += charge;
+	      sumSqCharge += charge*charge;
+	    }
+	} 
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " usedInnerPx " << usedInnerPx << " usedOuterPx " << usedOuterPx << endl;
+      
+      meanX   /= sumCharge;
+      meanY   /= sumCharge;
+      meanSqX /= sumCharge;
+      meanSqY /= sumCharge;
+      factor = sqrt( sumSqCharge/(sumCharge*sumCharge) );
+
+      // stop iteration when (meanX, meanY) becomes stable
+      if ( TMath::Abs(meanX-meanXold) < meanPresition  && 
+           TMath::Abs(meanY-meanYold) < meanPresition    )
+        break;
+
+      meanXold = meanX;
+      meanYold = meanY;
+      numIterations++;
+  }
+  // this statement was commented out because the condition 
+  // was never fulfilled :
+  //while(TMath::Abs(meanX-expX) > meanPresition || 
+  //      TMath::Abs(meanY-expY) > meanPresition);
+  //--------------------   end of iteration loop   -----------------------
+
+  if (numIterations >=  maxNumIterations)
+  {
+     *fLog << warn << GetName() << "Mean calculation not converged after " 
+           << maxNumIterations << " iterations" << endl;
+  }
+  
+
+  //Float_t rmsX = (meanSqX - meanX*meanX) - fRingInterest*fRingInterest/12;
+  //Float_t rmsY = (meanSqY - meanY*meanY) - fRingInterest*fRingInterest/12;
+
+  Float_t rmsX = (meanSqX - meanX*meanX);
+  Float_t rmsY = (meanSqY - meanY*meanY);
+  
+  if ( rmsX > 0)
+    rmsX =  TMath::Sqrt(rmsX);
+  else
+    {
+      *fLog << warn << " MFindStars::FindStar negative rmsX² " << rmsX << endl;
+      *fLog << warn << " meanSqX " << meanSqX << " meanX " << meanX << " fRingInterest " << fRingInterest << " sumCharge " << sumCharge << endl;
+      rmsX = 0.;
+    }
+  
+  if ( rmsY > 0)
+    rmsY =  TMath::Sqrt(rmsY);
+  else
+    {
+      *fLog << warn << " MFindStars::FindStar negative rmsY² " << rmsY << endl;
+      *fLog << warn << " meanSqY " << meanSqY << " meanY " << meanY << " fRingInterest " << fRingInterest << " sumCharge " << sumCharge<< endl;
+      rmsY = 0.;
+    }
+  
+  Float_t deltameanX = factor * rmsX;
+  Float_t deltameanY = factor * rmsY;
+
+
+  // Substrack pedestal DC
+  sumCharge-= (usedInnerPx*innerped+usedOuterPx*outerped)/(usedInnerPx+usedOuterPx);
+  max-=pixmax>lastInnerPixel?outerped:innerped;
+  
+  
+  star->SetCalcValues( sumCharge, max, meanX, meanY, rmsX, rmsY,
+                       0.,   deltameanX*deltameanX, 0., deltameanY*deltameanY);
+  
+  if (rmsX <= 0. || rmsY <= 0.)
+    return kFALSE;
+    
+    
+// fit the star spot using TMinuit
+
+    
+    for (UInt_t pix=1; pix<numPixels; pix++)
+      if (fDisplay.IsUsed(pix))
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << "[fit the star spot] fDisplay.IsUsed(" << pix << ") kTRUE" << endl;
+  
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << "fMinDCForStars " << fMinDCForStars << " pixmax>lastInnerPixel?outerped:innerped " << (pixmax>lastInnerPixel?outerped:innerped) << " fMaxNumIntegratedEvents " << fMaxNumIntegratedEvents << endl;
+
+  //Initialize variables for fit
+    fVinit[0] = max;
+    fLimlo[0] = fMinDCForStars-(pixmax>lastInnerPixel?outerped:innerped);
+    fLimup[0] = 30*fMaxNumIntegratedEvents-(pixmax>lastInnerPixel?outerped:innerped);
+    fVinit[1] = meanX;
+    fVinit[2] = rmsX;
+    fVinit[3] = meanY;
+    fVinit[4] = rmsY;
+    //Init steps
+    for(Int_t i=0; i<fNumVar; i++)
+    {
+	if (fVinit[i] != 0)
+	  fStep[i] = TMath::Abs(fVinit[i]/sqrt2);
+        else
+          fStep[i] = 0.1;
+
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fVinit[" << i << "] " << fVinit[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fStep[" << i << "] " << fStep[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fLimlo[" << i << "] " << fLimlo[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fLimup[" << i << "] " << fLimup[i] << endl;
+    }
+
+
+    // -------------------------------------------
+    // call MINUIT
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    for (Int_t i=0; i<fNumVar; i++)
+      gMinuit->mnparm(i, fVname[i], fVinit[i], fStep[i], fLimlo[i], fLimup[i], ierflg);
+
+    TStopwatch clock;
+    clock.Start();
+
+// Now ready for minimization step
+    arglist[0] = 500;
+    arglist[1] = 1.;
+    gMinuit->mnexcm(fMethod, arglist ,2,ierflg);
+
+    // call fcn with iflag = 3 
+    //arglist[0] = 3;
+    //Int_t ierflg3;
+    //gMinuit->mnexcm("CALL", arglist, 1, ierflg3);     
+
+    clock.Stop();
+
+    if(fMinuitPrintOutLevel>=0)
+      {
+	if (fMinuitPrintOutLevel>=0) *fLog << dbg << "Time spent for the minimization in MINUIT :   " << endl;;
+	clock.Print();
+      }
+
+
+    //----------  for the uncorrelated Gauss fit (start)   ---------
+    if (!fUseCorrelatedGauss)
+    {
+      Double_t integratedCharge;
+      Double_t maxFit,   maxFitError;
+      Double_t meanXFit, meanXFitError;
+      Double_t sigmaX,   sigmaXError;
+      Double_t meanYFit, meanYFitError;
+      Double_t sigmaY,   sigmaYError;
+      Float_t  chisquare = GetChisquare();
+      Int_t    degrees  = GetDegreesofFreedom()-fNumVar;
+
+      if (!ierflg)
+      {
+        gMinuit->GetParameter(0, maxFit,   maxFitError);
+        gMinuit->GetParameter(1, meanXFit, meanXFitError);
+        gMinuit->GetParameter(2, sigmaX,   sigmaXError);
+        gMinuit->GetParameter(3, meanYFit, meanYFitError);
+        gMinuit->GetParameter(4, sigmaY,   sigmaYError);
+        
+        //FIXME: Do the integral properlly
+        integratedCharge = 0.;
+      }
+      else
+      {
+        maxFit = 0.;
+        meanXFit = 0.;
+        sigmaX = 0.;
+        meanYFit = 0.;
+        sigmaY = 0.;
+        integratedCharge = 0.;
+
+	*fLog << err << "TMinuit::Call error " << ierflg << endl;
+      }
+
+      // get error matrix
+      Double_t matrix[5][5];
+      gMinuit->mnemat(&matrix[0][0],5);
+
+      star->SetFitValues(integratedCharge,maxFit,       meanXFit,    meanYFit,
+                         sigmaX,          sigmaY,       0.0,
+      	          	 matrix[1][1],    matrix[1][3], matrix[3][3],
+                         chisquare,   degrees);
+    }
+    //----------  for the uncorrelated Gauss fit (end)   ---------    
+
+    //----------  for the correlated Gauss fit (start)   ---------
+    if (fUseCorrelatedGauss)
+    {
+      TArrayD fValues(fNumVar);
+      TArrayD fErrors(fNumVar);
+
+      const static Int_t fNdim = 6;
+      Double_t matrix[fNdim][fNdim];
+
+      Double_t fmin   = 0.0;
+      Double_t fedm   = 0.0;
+      Double_t errdef = 0.0;
+      Int_t npari     =   0;
+      Int_t nparx     =   0;
+      Int_t istat     =   0;
+      gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, istat);
+      if (fMinuitPrintOutLevel>=0)
+      { 
+            *fLog << dbg  
+            << "Status of Correlated Gauss fit to the DC currents : " << endl;
+      }
+      if (fMinuitPrintOutLevel>=0) 
+      {
+            *fLog << dbg 
+            << "       fmin, fedm, errdef, npari, nparx, istat = "
+            << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+            << ",  " << nparx << ",  " << istat << endl;
+      }
+
+      if (!ierflg)
+      {
+        for (Int_t k=0; k<fNumVar; k++)
+          gMinuit->GetParameter( k, fValues[k], fErrors[k] );
+      }
+      else
+      {
+	*fLog << err << "Correlated Gauss fit failed : ierflg, istat = " 
+              << ierflg << ",  " << istat << endl;
+      }
+
+      Float_t  charge = 0.0;
+      Float_t  chi2   = fmin;
+      Int_t    ndof   = GetDegreesofFreedom()-fNumVar;
+
+      //get error matrix
+      if (istat >= 1)
+      {
+        gMinuit->mnemat( &matrix[0][0], fNdim);
+
+        // copy covariance matrix into a matrix which includes also the fixed
+        // parameters
+        TString  name;
+        Double_t bnd1, bnd2, val, err;
+        Int_t    jvarbl;
+        Int_t    kvarbl;
+        for (Int_t j=0; j<fNumVar; j++)
+        {
+            if (gMinuit)
+                gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+            for (Int_t k=0; k<fNumVar; k++)
+            {
+              if (gMinuit)
+                  gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+              matrix[j][k] = jvarbl==0 || kvarbl==0 ? 0 : matrix[jvarbl-1][kvarbl-1];
+            }
+        }
+      }
+      else
+      {
+        // error matrix was not calculated, construct it
+        if (fMinuitPrintOutLevel>=0)
+	{
+        *fLog << warn 
+              << "error matrix is not defined, construct it" << endl;
+	}
+        for (Int_t j=0; j<fNumVar; j++)
+        {
+          for (Int_t k=0; k<fNumVar; k++)
+              matrix[j][k] = 0;
+
+          matrix[j][j] = fErrors[j]*fErrors[j];
+        }
+      }
+
+      if (fMinuitPrintOutLevel>=0)
+      {
+        *fLog << "Before calling SetFitValues : " << endl; 
+        *fLog << "fValues = " << fValues[0] << ",  " << fValues[1] << ",  "
+              << fValues[2] << ",  " << fValues[3] << ",  " << fValues[4]
+              << ",  " << fValues[5] << endl;
+
+        *fLog << "fErrors = " << fErrors[0] << ",  " << fErrors[1] << ",  "
+              << fErrors[2] << ",  " << fErrors[3] << ",  " << fErrors[4]
+              << ",  " << fErrors[5] << endl;
+
+        *fLog << "error matrix = " << matrix[0][0] << "   " << matrix[0][1]
+                          << "   " << matrix[0][2] << "   " << matrix[0][3]
+                          << "   " << matrix[0][4] << "   " << matrix[0][5]
+              << endl;
+        *fLog << "               " << matrix[1][0] << "   " << matrix[1][1]
+                          << "   " << matrix[1][2] << "   " << matrix[1][3]
+                          << "   " << matrix[1][4] << "   " << matrix[1][5]
+              << endl;
+        *fLog << "               " << matrix[2][0] << "   " << matrix[2][1]
+                          << "   " << matrix[2][2] << "   " << matrix[2][3]
+                          << "   " << matrix[2][4] << "   " << matrix[2][5]
+              << endl;
+        *fLog << "               " << matrix[3][0] << "   " << matrix[3][1]
+                          << "   " << matrix[3][2] << "   " << matrix[3][3]
+                          << "   " << matrix[3][4] << "   " << matrix[3][5]
+              << endl;
+        *fLog << "               " << matrix[4][0] << "   " << matrix[4][1]
+                          << "   " << matrix[4][2] << "   " << matrix[4][3]
+                          << "   " << matrix[4][4] << "   " << matrix[4][5]
+              << endl;
+        *fLog << "               " << matrix[5][0] << "   " << matrix[5][1]
+                          << "   " << matrix[5][2] << "   " << matrix[5][3]
+                          << "   " << matrix[5][4] << "   " << matrix[5][5]
+              << endl;
+      }
+
+      star->SetFitValues(charge,       fValues[0],  fValues[1], fValues[3],
+                         fValues[2],   fValues[4],  fValues[5],
+  	       	         matrix[1][1], matrix[1][3],matrix[3][3],
+                         chi2,         ndof);
+    }
+
+    //----------  for the correlated Gauss fit (end)   ---------    
+
+
+    // reset the display to the starting values
+    fDisplay.SetUsed(origPixelsUsed);
+
+    if (ierflg)
+      return kCONTINUE;
+    return kTRUE;
+}
+
+Bool_t MFindStars::ShadowStar(MStarPos* star)
+{
+    UInt_t numPixels = fGeomCam->GetNumPixels();
+
+// Define an area around the star which will be set unused.
+    UInt_t shadowPx=0;	
+    for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+	Float_t pixXpos  = (*fGeomCam)[pix].GetX();
+	Float_t pixYpos  = (*fGeomCam)[pix].GetY();
+        Float_t starXpos = star->GetMeanX();
+        Float_t starYpos = star->GetMeanY();
+
+        Float_t starSize = 3*sqrt(   star->GetSigmaX()*star->GetSigmaX()
+				   + star->GetSigmaY()*star->GetSigmaY() );
+        
+	Float_t dist = sqrt((pixXpos-starXpos)*(pixXpos-starXpos)+
+			    (pixYpos-starYpos)*(pixYpos-starYpos));
+
+        if (dist > starSize && fDisplay.IsUsed(pix))
+	  fPixelsUsed[pix]=(Char_t)kTRUE;
+        else
+          {
+            fPixelsUsed[pix]=(Char_t)kFALSE;
+            shadowPx++;
+          }
+    }
+
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << " shadowPx " << shadowPx << endl;
+
+    fDisplay.SetUsed(fPixelsUsed);
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MFindStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MFindStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MFindStars.h	(revision 9772)
@@ -0,0 +1,123 @@
+#ifndef MARS_MFindStars
+#define MARS_MFindStars
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+#ifndef MARS_MAstroCamera
+#include "MAstroCamera.h"
+#endif
+
+class MGeomCam;
+class MGeomPix;
+class MCameraDC;
+class MTime;
+class MReportDrive;
+class MStarCam;
+class MStarPos;
+
+class MFindStars : public MTask
+{
+
+private:
+
+    MGeomCam      *fGeomCam;
+    MCameraDC     *fCurr;
+    MTime         *fTimeCurr;
+    MReportDrive  *fDrive;
+    MStarCam      *fStars;
+
+    MAstroCamera fAstro;
+    TArrayC      fPixelsUsed;
+    MHCamera     fDisplay;
+
+    UInt_t fMaxNumIntegratedEvents;
+    UInt_t fNumIntegratedEvents;
+
+    Float_t fRingInterest; //[mm]
+    Float_t fMinDCForStars; //[uA]
+
+    Float_t fDCTailCut;
+
+    //Fitting(Minuit) variables
+    Int_t fNumVar;
+    Float_t fTempChisquare;
+    Int_t fTempDegreesofFreedom;
+    Int_t fMinuitPrintOutLevel;
+    
+    Bool_t fUseCorrelatedGauss;
+
+    TString *fVname;
+    TArrayD fVinit; 
+    TArrayD fStep; 
+    TArrayD fLimlo; 
+    TArrayD fLimup; 
+    TArrayI fFix;
+    TObject *fObjectFit;
+    TString fMethod;
+    Bool_t fNulloutput;
+    
+    Bool_t DCPedestalCalc();
+    Bool_t FindPixelWithMaxDC(Float_t &maxDC, MGeomPix &maxPix);
+    Bool_t FindStar(MStarPos* star);
+    Bool_t ShadowStar(MStarPos* star);
+
+    TString fGeometryFile;
+    TString fBSCFile;
+
+  public:
+    
+    MFindStars(const char *name=NULL, const char *title=NULL);
+    
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    void SetUseCorrelatedGauss(Bool_t usecorrgauss = kTRUE);
+    Bool_t  GetUseCorrelatedGauss()          {return fUseCorrelatedGauss;}
+
+    // setters
+    void SetNumIntegratedEvents(UInt_t max)  {fMaxNumIntegratedEvents=max;}
+    void SetRingInterest(Float_t ring)       {fRingInterest=ring;}
+    void SetBlindPixels(TArrayS blindpixels);
+    void SetMinuitPrintOutLevel(Int_t level) {fMinuitPrintOutLevel=level;}
+    void SetDCTailCut(Float_t cut)           {fDCTailCut=cut;}
+
+    void SetChisquare(Float_t chi)           {fTempChisquare=chi;}
+    void SetDegreesofFreedom(Int_t free)     {fTempDegreesofFreedom=free;}
+
+    void SetGeometryFile(TString f)          {fGeometryFile=f;}
+    void SetBSCFile(TString f)               {fBSCFile=f;}
+    void SetRaDec(Double_t ra, Double_t dec) {fAstro.SetRaDec(ra,dec);}
+    void SetRaDec(TVector3 &v)               { fAstro.SetRaDec(v); }
+    void SetLimMag(Double_t mag)             { fAstro.SetLimMag(mag); } 
+    void SetRadiusFOV(Double_t deg)          { fAstro.SetRadiusFOV(deg); }
+
+
+    //Getters
+    MHCamera& GetDisplay()           { return fDisplay; }
+    
+    Float_t GetChisquare()           {return fTempChisquare;}
+    Int_t   GetDegreesofFreedom()    {return fTempDegreesofFreedom;}
+    UInt_t  GetNumIntegratedEvents() {return fMaxNumIntegratedEvents;}
+    Float_t GetRingInterest()        {return fRingInterest;}
+    
+  ClassDef(MFindStars, 0) // Tool to find stars from DC Currents
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mtemp/MHTelAxisFromStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MHTelAxisFromStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MHTelAxisFromStars.cc	(revision 9772)
@@ -0,0 +1,638 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  07/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHTelAxisFromStars
+//
+// This class contains histograms for MTelAxisFromStars
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHTelAxisFromStars.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MBinning.h"
+
+#include "MStarCam.h"
+#include "MStarPos.h"
+#include "MSkyCamTrans.h"
+#include "MSrcPosCam.h"
+
+
+ClassImp(MHTelAxisFromStars);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup the histograms 
+//
+MHTelAxisFromStars::MHTelAxisFromStars(const char *name, const char *title)
+    : fMm2Deg(1), fUseMmScale(kFALSE)
+{
+    fName  = name  ? name  : "MHTelAxisFromStars";
+    fTitle = title ? title : "Plots for MTelAxisFromStars";
+
+    fNStars     = new TH1D("NStars", "No. of stars", 10, -0.5, 9.5);
+    fNStars->SetDirectory(NULL);
+    fNStars->SetXTitle("Numder of stars");    
+    fNStars->SetYTitle("Counts");
+
+    fNdoF     = new TH1D("NdoF", "No. of degrees of freedom", 20, -0.5, 19.5);
+    fNdoF->SetDirectory(NULL);
+    fNdoF->SetXTitle("Numder of degrees of freedom");    
+    fNdoF->SetYTitle("Counts");
+
+    fLog10Chi2 = new TH1D("log10Chi2", "log10Chi2", 60, -10, 5);
+    fLog10Chi2->SetDirectory(NULL);
+    fLog10Chi2->SetXTitle("log10(Chi2)");
+    fLog10Chi2->SetYTitle("Counts");
+
+    fChi2Prob = new TH1D("Chi2-Prob", "Chi2 probability",     40,  0.0,  1.0);
+    fChi2Prob->SetDirectory(NULL);
+    fChi2Prob->SetXTitle("Chi2 probability");
+    fChi2Prob->SetYTitle("Counts");
+
+
+    fNumIter  = new TH1D("NumIter", "Number of iterations",   50, -0.5, 49.5);
+    fNumIter->SetDirectory(NULL);
+    fNumIter->SetXTitle("Number of iterations");
+    fNumIter->SetYTitle("Counts");
+
+
+    fLambda   = new TH1D("Lambda", "Scale factor lambda",     80, 0.90, 1.10);
+    fLambda->SetDirectory(NULL);
+    fLambda->SetXTitle("Scale factor lambda");
+    fLambda->SetYTitle("Counts");
+
+
+    fAlfa     = new TH1D("Alfa", "Rotation angle alfa",      100, -2.5,  2.5);
+    fAlfa->SetDirectory(NULL);
+    fAlfa->SetXTitle("Rotation angle alfa [\\circ]");
+    fAlfa->SetYTitle("Counts");
+
+
+    fShift = new TH2D("Shift", "Sky-Cam transformnation : (x,y) shift", 
+                      72, -534.0707, 534.0707, 72, -534.0707, 534.0707);
+    fShift->SetDirectory(NULL);
+    fShift->SetZTitle("Counts");
+    fShift->SetXTitle("x-shift [\\circ]");
+    fShift->SetYTitle("y-shift [\\circ]");
+
+
+    fEstPos1 = new TH2D("EstPos1", "Estimated position1", 
+                      72, -534.0707, 534.0707, 72, -534.0707, 534.0707);
+    fEstPos1->SetDirectory(NULL);
+    fEstPos1->SetZTitle("Counts");
+    fEstPos1->SetXTitle("Estimated position1    x [\\circ]");
+    fEstPos1->SetYTitle("Estimated position1    y [\\circ]");
+
+    fEstPos2 = new TH2D("EstPos2", "Estimated position2", 
+                      72, -534.0707, 534.0707, 72, -534.0707, 534.0707);
+    fEstPos2->SetDirectory(NULL);
+    fEstPos2->SetZTitle("Counts");
+    fEstPos2->SetXTitle("Estimated position2    x [\\circ]");
+    fEstPos2->SetYTitle("Estimated position2    y [\\circ]");
+
+    fEstPos3 = new TH2D("EstPos3", "Estimated position3", 
+                      72, -534.0707, 534.0707, 72, -534.0707, 534.0707);
+    fEstPos3->SetDirectory(NULL);
+    fEstPos3->SetZTitle("Counts");
+    fEstPos3->SetXTitle("Estimated position3    x [\\circ]");
+    fEstPos3->SetYTitle("Estimated position3    y [\\circ]");
+
+
+    // default input type : results from Gauss fit
+    fInputType = 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the type of the input
+//
+//     type = 0        calculated star positions (by averaging)
+//     type = 1        fitted star positions (by Gauss fit)
+//
+void MHTelAxisFromStars::SetInputType(Int_t type)
+{
+  *fLog << all << "MHTelAxisFromStars::SetInputType; input type is set equal to : " 
+        << type ;
+
+  if (type == 0)
+    *fLog << " (calculated star positions)" << endl;
+  else
+    *fLog << " (fitted star positions)" << endl;
+
+
+  fInputType = type;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms
+//
+MHTelAxisFromStars::~MHTelAxisFromStars()
+{
+  //*fLog << "MHTelAxisFromStars::Destructor" << endl;
+
+    delete fNStars;
+    delete fNdoF;
+    delete fLog10Chi2;
+    delete fChi2Prob;
+    delete fNumIter;
+    delete fLambda;
+    delete fAlfa;
+
+    delete fShift;
+    delete fEstPos1;
+    delete fEstPos2;
+    delete fEstPos3;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms. 
+//
+// Find the pointers to the containers.
+//
+// Use this function if you want to set the conversion factor which
+// is used to convert the mm-scale in the camera plane into the deg-scale.
+// The conversion factor is part of the camera geometry. Please create a 
+// corresponding MGeomCam container.
+//
+Bool_t MHTelAxisFromStars::SetupFill(const MParList *plist)
+{
+
+   fStarCam = (MStarCam*)plist->FindObject("MStarCam", "MStarCam");
+   if (!fStarCam)
+   {
+       *fLog << err << "MHTelAxisFromStars::SetupFill; container 'MStarCam' not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   
+   fSourceCam = (MStarCam*)plist->FindObject("MSourceCam", "MStarCam");
+   if (!fSourceCam)
+   {
+       *fLog << err << "MHTelAxisFromStars::SetupFill; container 'MSourceCam' not found... " << endl;
+   }
+   
+
+
+    fSrcPos = (MSrcPosCam*)plist->FindObject(AddSerialNumber("MSrcPosCam"));
+    if (!fSrcPos)
+    {
+        *fLog << err << "MHTelAxisFromStars::SetupFill;  MSrcPosCam not found...  aborting" << endl;
+        return kFALSE;
+    }
+
+    fSkyCamTrans = (MSkyCamTrans*)plist->FindObject(AddSerialNumber("MSkyCamTrans"));
+    if (!fSkyCamTrans)
+    {
+        *fLog << err << "MHTelAxisFromStars::SetupFill;  MSkyCamTrans not found...  aborting" << endl;
+        return kFALSE;
+    }
+
+
+   //------------------------------------------------------------------
+    const MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+    {
+        *fLog << warn << GetDescriptor() 
+          << ": No Camera Geometry available. Using mm-scale for histograms." 
+          << endl;
+        SetMmScale(kTRUE);
+    }
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+        SetMmScale(kFALSE);
+    }
+
+    ApplyBinning(*plist, "NStars",   fNStars);
+    ApplyBinning(*plist, "NdoF",     fNdoF);
+    ApplyBinning(*plist, "Log10Chi2",fLog10Chi2);
+    ApplyBinning(*plist, "Chi2Prob", fChi2Prob);
+    ApplyBinning(*plist, "NumIter",  fNumIter);
+    ApplyBinning(*plist, "Lambda",   fLambda);
+    ApplyBinning(*plist, "Alfa",     fAlfa);
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningCamera");
+    if (!bins)
+    {
+        float r = geom ? geom->GetMaxRadius() : 600;
+        r *= 0.9;
+        if (!fUseMmScale)
+            r *= fMm2Deg;
+
+        MBinning b;
+        b.SetEdges(61, -r, r);
+        SetBinning(fShift,   &b, &b);
+        SetBinning(fEstPos1, &b, &b);
+        SetBinning(fEstPos2, &b, &b);
+        SetBinning(fEstPos3, &b, &b);
+    }
+    else
+    {
+        SetBinning(fShift,   bins, bins);
+        SetBinning(fEstPos1, bins, bins);
+        SetBinning(fEstPos2, bins, bins);
+        SetBinning(fEstPos3, bins, bins);
+    }
+
+    //-------------------------------------------    
+    // copy names from MStarCam to the histograms
+    MStarPos* starpos;
+    Int_t istar = 0;
+    TIter Next(fSourceCam->GetList());
+
+    while ((starpos=(MStarPos*)Next())) {
+      fStarnames[istar] =  starpos->GetName();
+      //*fLog << "istar, star name = " << istar << ",  " 
+      //      << fStarnames[istar] << endl;
+      istar++;
+      if (istar >= fNstarnames) break;
+    }
+
+    if (fSourceCam)
+    {
+      MStarPos *starSource = 0;
+      TIter nextSource(fSourceCam->GetList());
+      while ( (starSource = (MStarPos*)nextSource()) )
+      {
+         if     ( fNstarnames > 0  &&  starSource->GetName() == fStarnames[0] )
+           fEstPos1->SetName(starSource->GetName());
+
+         else if( fNstarnames > 1  &&  starSource->GetName() == fStarnames[1] )
+           fEstPos2->SetName(starSource->GetName());
+
+         else if( fNstarnames > 2  &&  starSource->GetName() == fStarnames[2] )
+           fEstPos3->SetName(starSource->GetName());
+      }
+    }
+    
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this function to setup your own conversion factor between degrees
+// and millimeters. The conversion factor should be the one calculated in
+// MGeomCam. Use this function with Caution: You could create wrong values
+// by setting up your own scale factor.
+//
+void MHTelAxisFromStars::SetMm2Deg(Float_t mmdeg)
+{
+    if (mmdeg<0)
+    {
+        *fLog << warn << dbginf 
+              << "Warning - Conversion factor < 0 - nonsense. Ignored." 
+              << endl;
+        return;
+    }
+
+    if (fMm2Deg>=0)
+        *fLog << warn << dbginf 
+              << "Warning - Conversion factor already set. Overwriting" 
+              << endl;
+
+    fMm2Deg = mmdeg;
+}
+
+// --------------------------------------------------------------------------
+//
+// With this function you can convert the histogram ('on the fly') between
+// degrees and millimeters.
+//
+void MHTelAxisFromStars::SetMmScale(Bool_t mmscale)
+{
+    if (fUseMmScale == mmscale)
+        return;
+
+    if (fMm2Deg<0)
+    {
+        *fLog << warn << dbginf 
+         << "Warning - Sorry, no conversion factor for conversion available." 
+         << endl;
+        return;
+    }
+
+    const Double_t scale = mmscale ? 1./fMm2Deg : fMm2Deg;
+    MH::ScaleAxis(fShift,   scale, scale);
+    MH::ScaleAxis(fEstPos1, scale, scale);
+    MH::ScaleAxis(fEstPos2, scale, scale);
+    MH::ScaleAxis(fEstPos3, scale, scale);
+
+    if (mmscale)
+    {
+        fShift->SetXTitle("x-shift [mm]");
+        fShift->SetYTitle("y-shift [mm]");
+
+        fEstPos1->SetXTitle("Estimated position1 x [mm]");
+        fEstPos1->SetYTitle("Estimated position1 y [mm]");
+
+        fEstPos2->SetXTitle("Estimated position2 x [mm]");
+        fEstPos2->SetYTitle("Estimated position2 y [mm]");
+
+        fEstPos3->SetXTitle("Estimated position3 x [mm]");
+        fEstPos3->SetYTitle("Estimated position3 y [mm]");
+    }
+    else
+    {
+        fShift->SetXTitle("x-shift [\\circ]");
+        fShift->SetYTitle("y-shift [\\circ]");
+
+        fEstPos1->SetXTitle("Estimated position1 x [\\circ]");
+        fEstPos1->SetYTitle("Estimated position1 y [\\circ]");
+
+        fEstPos2->SetXTitle("Estimated position2 x [\\circ]");
+        fEstPos2->SetYTitle("Estimated position2 y [\\circ]");
+
+        fEstPos3->SetXTitle("Estimated position3 x [\\circ]");
+        fEstPos3->SetYTitle("Estimated position3 y [\\circ]");
+    }
+
+    fUseMmScale = mmscale;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms 
+// 
+//
+Bool_t MHTelAxisFromStars::Fill(const MParContainer *par, const Stat_t w)
+{
+    Int_t Ndof = fSkyCamTrans->GetNdof();
+    if (Ndof < 0)
+      return kTRUE;
+
+    const Double_t scale = fUseMmScale ? 1 : fMm2Deg;
+
+
+    fNStars   ->Fill(fSkyCamTrans->GetNStars(),               w);
+    fNdoF     ->Fill(fSkyCamTrans->GetNdof(),                 w);
+    if (fSkyCamTrans->GetChiSquare() > 0.0)
+      fLog10Chi2->Fill( log10(fSkyCamTrans->GetChiSquare() ), w);
+    fChi2Prob ->Fill(fSkyCamTrans->GetChiSquareProb(),        w);
+    fNumIter  ->Fill(fSkyCamTrans->GetNumIter(),              w);
+    fLambda   ->Fill(fSkyCamTrans->GetLambda(),               w);
+    fAlfa     ->Fill(fSkyCamTrans->GetAlfa(),                 w);
+
+
+    Double_t lowx;
+    Double_t higx;
+    Double_t lowy;
+    Double_t higy;
+    Double_t x;
+    Double_t y;
+    Int_t    nbix;
+    Int_t    nbiy;
+
+    nbix = fShift->GetXaxis()->GetNbins();
+    lowx = fShift->GetXaxis()->GetBinLowEdge(1);
+    higx = fShift->GetXaxis()->GetBinLowEdge(nbix+1);
+
+    nbiy = fShift->GetYaxis()->GetNbins();
+    lowy = fShift->GetYaxis()->GetBinLowEdge(1);
+    higy = fShift->GetYaxis()->GetBinLowEdge(nbiy+1);
+
+    x = scale * (fSkyCamTrans->GetShiftD())[0];
+    y = scale * (fSkyCamTrans->GetShiftD())[1];
+    if (x>lowx  && x<higx  && y>lowy  && y<higy)
+    {
+      fShift    ->Fill(x, y, w);
+    }
+
+    if (fSourceCam)
+    {
+      MStarPos *starSource = 0;
+      TIter nextSource(fSourceCam->GetList());
+
+      while( (starSource = (MStarPos*)nextSource()) )
+      {
+        if (fInputType == 1)
+        {
+          x = scale * starSource->GetMeanXFit(); 
+          y = scale * starSource->GetMeanYFit(); 
+        }
+        else 
+        {
+          x = scale * starSource->GetMeanXCalc(); 
+          y = scale * starSource->GetMeanYCalc(); 
+        }
+
+	if (x>lowx  && x<higx  && y>lowy  && y<higy)
+        {
+         if     ( fNstarnames > 0  &&  starSource->GetName() == fStarnames[0] )
+           fEstPos1->Fill(x, y, w);
+
+         else if( fNstarnames > 1  &&  starSource->GetName() == fStarnames[1] )
+           fEstPos2->Fill(x, y, w);
+
+         else if( fNstarnames > 2  &&  starSource->GetName() == fStarnames[2] )
+           fEstPos3->Fill(x, y, w);
+	}
+      }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Finalize :
+//
+//    it is called in the postprocessing
+//    reset pointers in order to allow cloning of the object
+//
+Bool_t MHTelAxisFromStars::Finalize()
+{
+  //*fLog << "MHTelAxisFromStars::Finalize;  fSourceCam = " 
+  //      << fSourceCam  << endl; 
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the histograms.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+
+void MHTelAxisFromStars::Draw(Option_t *opt)
+{
+  TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+  pad->SetBorderMode(0);
+
+  AppendPad("");
+  
+  //TCanvas *pad = new TCanvas("TelAxisFromStars", "TelAxis plots", 1200, 900);
+  //gROOT->SetSelectedPad(NULL);
+
+    pad->Divide(4,3);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fNStars->Draw(opt); 
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fNdoF->Draw(opt); 
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fLog10Chi2->Draw(opt); 
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fChi2Prob->Draw(opt); 
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    fNumIter->Draw(opt);
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    fLambda->Draw(opt);
+
+    pad->cd(7);
+    gPad->SetBorderMode(0);
+    fAlfa->Draw(opt);
+
+    pad->cd(8);
+    gPad->SetBorderMode(0);
+    //SetColors();
+    //fShift->Draw("colz");
+    fShift->Draw("");
+
+
+    //-----------------------------------------------
+    // plot the expected positions of some sources
+    //*fLog << "fSourcsCam = " << fSourceCam << endl;
+
+    if (fSourceCam)
+    {
+      *fLog << "MHTelAxisFromSrars::Draw; plotting" << endl;
+
+      pad->cd(9);
+      gPad->SetBorderMode(0);
+      //SetColors();
+      fEstPos1->Draw("");
+
+      pad->cd(10);
+      gPad->SetBorderMode(0);
+      //SetColors();
+      fEstPos2->Draw("");
+
+      pad->cd(11);
+      gPad->SetBorderMode(0);
+      //SetColors();
+      fEstPos3->Draw("");
+    }
+
+    pad->Modified();
+    pad->Update();
+}
+
+//---------------------------------------------------------------------
+//
+
+TH1 *MHTelAxisFromStars::GetHistByName(const TString name)
+{
+    if (name.Contains("NStars", TString::kIgnoreCase))
+        return fNStars;
+    if (name.Contains("NdoF", TString::kIgnoreCase))
+        return fNdoF;
+    if (name.Contains("Log10Chi2", TString::kIgnoreCase))
+        return fLog10Chi2;
+    if (name.Contains("Chi2Prob", TString::kIgnoreCase))
+        return fChi2Prob;
+    if (name.Contains("NumIter", TString::kIgnoreCase))
+        return fNumIter;
+    if (name.Contains("Lambda", TString::kIgnoreCase))
+        return fLambda;
+    if (name.Contains("Alfa", TString::kIgnoreCase))
+        return fAlfa;
+
+    if (name.Contains("Shift", TString::kIgnoreCase))
+        return fShift;
+    if (name.Contains("EstPos1", TString::kIgnoreCase))
+        return fEstPos1;
+    if (name.Contains("EstPos2", TString::kIgnoreCase))
+        return fEstPos2;
+    if (name.Contains("EstPos3", TString::kIgnoreCase))
+        return fEstPos3;
+
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup an inversed deep blue sea palette.
+//
+
+void MHTelAxisFromStars::SetColors() const
+{
+    gStyle->SetPalette(51, NULL);
+    Int_t c[50];
+    for (int i=0; i<50; i++)
+        c[49-i] = gStyle->GetColorPalette(i);
+    gStyle->SetPalette(50, c);
+}
+
+
+//---------------------------------------------------------------------
+//
+
+void MHTelAxisFromStars::Paint(Option_t *opt)
+{
+    SetColors();
+    MH::Paint();
+}
+
+//==========================================================================
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MHTelAxisFromStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MHTelAxisFromStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MHTelAxisFromStars.h	(revision 9772)
@@ -0,0 +1,86 @@
+#ifndef MARS_MHTelAxisFromStars
+#define MARS_MHTelAxisFromStars
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TH2D;
+class MTelAxisFromStars;
+class MSrcPosCam;
+class MSkyCamTrans;
+class MStarCam;
+
+class MHTelAxisFromStars : public MH
+{
+private:
+
+    TH1D *fNStars;     //-> Number of stars
+    TH1D *fNdoF;       //-> Number of degrees of freedom
+    TH1D *fLog10Chi2;  //-> log10(Chi2) 
+    TH1D *fChi2Prob;   //-> Chi2 probability
+    TH1D *fNumIter;    //-> Number of iterations
+    TH1D *fLambda;     //-> Scale factor lambda
+    TH1D *fAlfa;       //-> Rotation angle alfa
+
+    TH2D *fShift;      //-> Shift between Sky and Camera system
+    TH2D *fEstPos1;    //-> Estimated position 1
+    TH2D *fEstPos2;    //-> Estimated position 2
+    TH2D *fEstPos3;    //-> Estimated position 3
+
+    MStarCam        *fStarCam;     //!
+    MStarCam        *fSourceCam;   
+    MSrcPosCam      *fSrcPos;      //!
+    MSkyCamTrans    *fSkyCamTrans; //!
+
+    Float_t fMm2Deg;                    //!
+    Bool_t  fUseMmScale;                //!
+    Int_t   fInputType;                 //!
+
+    const static Int_t fNstarnames = 3;        //!
+    TString fStarnames[fNstarnames];    //!
+
+    void SetColors() const;
+    void Paint(Option_t *opt="");
+
+public:
+    MHTelAxisFromStars(const char *name=NULL, const char *title=NULL);
+    ~MHTelAxisFromStars();
+
+    void SetInputType(Int_t type=1);
+    void SetMmScale(Bool_t mmscale=kTRUE);
+    virtual void SetMm2Deg(Float_t mmdeg);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    TH1 *GetHistByName(const TString name);
+
+    TH1D *GetHistNStars()    { return fNStars;    }
+    TH1D *GetHistNdoF()      { return fNdoF;      }
+    TH1D *GetHistLog10Chi2() { return fLog10Chi2; }
+    TH1D *GetHistChi2Prob()  { return fChi2Prob;  }
+
+    TH1D *GetHistNumIter()   { return fNumIter;   }
+    TH1D *GetHistLambda()    { return fLambda;    } 
+
+    TH1D *GetHistAlfa()      { return fAlfa;      }
+
+    TH2D *GetHistShift()     { return fShift;     }
+    TH2D *GetHistEstPos1()   { return fEstPos1;   }
+    TH2D *GetHistEstPos2()   { return fEstPos2;   }
+    TH2D *GetHistEstPos3()   { return fEstPos3;   }
+
+    void Draw(Option_t *opt=NULL);
+
+    ClassDef(MHTelAxisFromStars, 1) // Container which holds histograms for MTelAxisFromStars
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MSkyCamTrans.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MSkyCamTrans.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MSkyCamTrans.cc	(revision 9772)
@@ -0,0 +1,118 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek , 7/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// MSkyCamTrans
+//
+//     container holding the parameters of the transformation from
+//     sky directions 'a' (projected onto the camera) 
+//     to positions 'b' in the camera
+//
+//                                          ( cos(fAlfa)   -sin(fAlfa) )
+//      b = fLambda * fA * a + fD      fA = (                        )
+//             ^       ^        ^           ( sin(fAlfa)    cos(fAlfa) )
+//             |       |        |
+//           scale  rotation  shift 
+//          factor  matrix
+//
+//     fNumIter             number of iterations
+//     fNdof                number of degrees of freedom
+//     fChiSquare           chi-square value
+//     fChiSquareProb       chi-square probability
+//
+// The units are assumed to be 
+//     [degrees]  for  fAlfa
+//     [mm]       for  a, b, fD
+//     [1]        for  fLambda                       
+//
+//
+// The container is filled by  the task 'MTelAxisFromStars' 
+//
+///////////////////////////////////////////////////////////////////////////
+
+
+#include "MSkyCamTrans.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSkyCamTrans);
+
+using namespace std;
+
+// ---------------------------------------------------------------------
+//
+//
+//
+MSkyCamTrans::MSkyCamTrans(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MSkyCamTrans";
+    fTitle = title ? title : "Sky-Cam transformation parameters";
+}
+
+// ---------------------------------------------------------------------
+//
+//
+//
+void MSkyCamTrans::SetParameters(Double_t &lambda, Double_t &alfa, 
+     Double_t a[2][2], Double_t d[2],  Double_t errd[2][2], 
+     Int_t &nstars,    Int_t &numiter,  
+     Int_t &ndof,      Double_t &chisquare,        Double_t &chisquareprob)
+{
+  fLambda = lambda;
+  fAlfa   = alfa;
+    
+  fA[0][0] = a[0][0];
+  fA[0][1] = a[0][1];
+  fA[1][0] = a[1][0];
+  fA[1][1] = a[1][1];
+
+  fD[0] = d[0];
+  fD[1] = d[1];
+
+  fErrD[0][0] = errd[0][0];
+  fErrD[0][1] = errd[0][1];
+  fErrD[1][0] = errd[1][0];
+  fErrD[1][1] = errd[1][1];
+
+  fNStars        = nstars;
+  fNumIter       = numiter;
+  fNdof          = ndof;
+  fChiSquare     = chisquare;
+  fChiSquareProb = chisquareprob;
+}
+// ---------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MSkyCamTrans.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MSkyCamTrans.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MSkyCamTrans.h	(revision 9772)
@@ -0,0 +1,55 @@
+#ifndef MARS_MSkyCamTrans
+#define MARS_MSkyCamTrans
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MSkyCamTrans : public MParContainer
+{
+private:
+
+    //Parameters of transformation from sky to camera
+    
+    Double_t fLambda;         // scale factor lambda
+    Double_t fAlfa;           // rotation angle alfa [degrees]
+    Double_t fA[2][2];        // rotation matrix A
+    Double_t fD[2];           // shift D [mm]
+    Double_t fErrD[2][2];     // error matrix of shift D   [mm*mm]
+
+    Int_t    fNStars;
+    Int_t    fNumIter;
+    Int_t    fNdof;
+    Double_t fChiSquare;
+    Double_t fChiSquareProb;
+
+public:
+
+    MSkyCamTrans(const char *name=NULL, const char *title=NULL);
+
+    void SetParameters(Double_t &,       Double_t &,
+		       Double_t[2][2],   Double_t[2], Double_t[2][2], 
+              Int_t &, Int_t &, Int_t &, Double_t &,  Double_t &);
+ 
+    Int_t    GetNStars()             { return fNStars;       }
+    Int_t    GetNumIter()            { return fNumIter;       }
+    Int_t    GetNdof()               { return fNdof;          }
+    Double_t GetChiSquare()          { return fChiSquare;     }
+    Double_t GetChiSquareProb()      { return fChiSquareProb; }
+    Double_t GetLambda()             { return fLambda;        }
+    Double_t GetAlfa()               { return fAlfa;          }
+
+    Double_t *GetRotationMatrix()    { return &fA[0][0];      }  
+    Double_t *GetShiftD()            { return &fD[0];         }  
+    Double_t *GetErrMatrixShiftD()   { return &fErrD[0][0];   }  
+
+    ClassDef(MSkyCamTrans, 1) // Container holding the sky-camera transformation parameters
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MSourceDirections.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MSourceDirections.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MSourceDirections.cc	(revision 9772)
@@ -0,0 +1,188 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!   Author(s): Robert Wagner, 8/2004 <mailto:rwagner@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSourceDirections
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSourceDirections.h"
+
+#include <TTimer.h>
+#include <TString.h>
+#include <TFile.h>
+#include <TTree.h>
+#include <TCanvas.h>
+#include <TH1F.h>
+#include <TF1.h>
+#include <TEllipse.h>
+
+
+#include "MObservatory.h"
+#include "MAstroCamera.h"
+#include "MMcConfigRunHeader.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+#include "MTime.h"
+#include "MReportDrive.h"
+#include "MStarCam.h"
+#include "MStarPos.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MSourceDirections);
+using namespace std;
+
+MSourceDirections::MSourceDirections(const char *name, const char *title): 
+  fGeomCam(NULL), fTimeCurr(NULL), fDrive(NULL), fStars(NULL)
+{
+  fName  = name  ? name  : "MSourceDirections";
+  fTitle = title ? title : "Convert Ra-Dec source positions into camera coordinates";
+  fGeometryFile="";
+}
+
+Int_t MSourceDirections::PreProcess(MParList *pList)
+{
+  fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+  if (!fGeomCam) {
+    *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+    return kFALSE;
+  }
+  
+  fTimeCurr = (MTime*)pList->FindObject(AddSerialNumber("MTimeCurrents"));
+  if (!fTimeCurr) {
+    *fLog << err << AddSerialNumber("MTimeCurrents") << " not found ... aborting" << endl;
+    return kFALSE;
+  }
+
+  fDrive = (MReportDrive*)pList->FindObject(AddSerialNumber("MReportDrive"));
+  if (!fDrive) {
+    *fLog << warn << AddSerialNumber("MReportDrive") << " not found ... aborting" << endl;
+    return kFALSE;
+  } 
+
+
+  fStars = (MStarCam*)pList->FindCreateObj(AddSerialNumber("MStarCam"),"MSourceCam");
+  if (!fStars) {
+    *fLog << err << AddSerialNumber("MStarCam") << " with name '"
+          << "MSourceCam" << " cannot be created ... aborting" << endl;
+    return kFALSE;
+  }
+  
+
+
+  MObservatory magic1;
+  
+  MMcConfigRunHeader *config=0;
+  MGeomCam           *geom=0;
+  
+  TFile file(fGeometryFile);
+  TTree *tree = (TTree*)file.Get("RunHeaders");
+  tree->SetBranchAddress("MMcConfigRunHeader", &config);
+  if (tree->GetBranch("MGeomCam")) tree->SetBranchAddress("MGeomCam", &geom);
+  tree->GetEntry(0);
+  
+  fAstro.SetMirrors(*config->GetMirrors());
+  fAstro.SetGeom(*geom);	
+  fAstro.SetObservatory(magic1);  
+
+
+  // make the starlist available already in the preprocessing
+  fStars->GetList()->Delete();
+  fAstro.SetTime(*fTimeCurr);
+  fAstro.SetGuiActive();
+  fAstro.FillStarList(fStars->GetList());      
+  //*fLog << inf << "in preprocessing " << GetName() << " found " 
+  //      << fStars->GetList()->GetSize() 
+  //	  << " directions inside the chosen FOV." << endl;          
+
+
+  return kTRUE;
+}
+
+Int_t MSourceDirections::AddDirection(Float_t ra, Float_t dec, Float_t mag, TString name) 
+{
+  *fLog << "MSourceDirections::AddDirection; add the direction : ra, dec, mag, name = " 
+        << ra << ",  " << dec << ",  " << mag << ",  " << name << endl;
+
+  Int_t rc = fAstro.AddObject(ra,dec,1,name);
+//   if (rc) {
+//     MStarPos *starpos = new MStarPos;
+//     starpos->SetName(name);
+//     fStars->GetList()->Add(starpos);
+//   }
+  return rc;
+}
+
+Int_t MSourceDirections::Process()
+{
+  //First delete the previous directions in the list
+  fStars->GetList()->Delete();
+
+  fAstro.SetTime(*fTimeCurr);
+  fAstro.SetGuiActive();
+  fAstro.FillStarList(fStars->GetList());      
+      
+  MStarPos* starpos;
+  TIter Next(fStars->GetList());
+  while ((starpos=(MStarPos*)Next())) {
+    //starpos->SetCalcValues(40,40,starpos->GetXExp(),starpos->GetYExp(),
+    //                       0.,0.,0.,    0.,0.,0.);
+    //starpos->SetFitValues (40,40,starpos->GetXExp(),starpos->GetYExp(),
+    //                       0.,0.,0.,    0.,0.,0.,  0., -1);
+  }
+
+  if (fStars->GetList()->GetSize() == 0) {
+    *fLog << err << GetName() << "No directions inside the chosen FOV." << endl;
+  } else {
+    //*fLog << inf << GetName() << " found " << fStars->GetList()->GetSize() 
+    //	  << " directions inside the chosen FOV." << endl;          
+  }
+  return kTRUE;
+}
+
+Int_t MSourceDirections::PostProcess()
+{
+  return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MSourceDirections.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MSourceDirections.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MSourceDirections.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MSourceDirections
+#define MARS_MSourceDirections
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MAstroCamera
+#include "MAstroCamera.h"
+#endif
+
+class MTime;
+class MReportDrive;
+class MStarCam;
+class MStarPos;
+
+class MSourceDirections : public MTask
+{
+
+private:
+
+    MGeomCam      *fGeomCam;
+    MTime         *fTimeCurr;
+    MReportDrive  *fDrive;
+    MStarCam *fStars;
+
+    MAstroCamera fAstro;
+  
+    TString fGeometryFile;
+
+  public:
+    
+    MSourceDirections(const char *name=NULL, const char *title=NULL);
+    
+    Int_t AddDirection(Float_t ra, Float_t dec, Float_t mag, TString name="");
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // setters
+    void SetGeometryFile(TString f) {fGeometryFile=f;}
+    void SetRaDec(Double_t ra, Double_t dec) {fAstro.SetRaDec(ra,dec);}
+    void SetRaDec(TVector3 &v) { fAstro.SetRaDec(v); }
+    void SetRadiusFOV(Double_t deg) { fAstro.SetRadiusFOV(deg); }
+    
+  ClassDef(MSourceDirections, 0) // Tool to translate RaDec Source Directions into camera coordinates
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/MStarLocalCam.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MStarLocalCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MStarLocalCam.cc	(revision 9772)
@@ -0,0 +1,111 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 04/2004 <mailto:jlopez@ifae.es>
+!   Author(s): Jordi Albert 04/2004 <mailto:albert@astro.uni-wuerzburg.de>
+!                 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MStarLocalCam
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MStarLocalCam.h"
+
+#include <TList.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MStarLocalPos.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+// Default constructor. 
+//
+//
+MStarLocalCam::MStarLocalCam(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MStarLocalCam";
+  fTitle = title ? title : "";
+  
+  fStars = new TList;
+
+  fInnerPedestalDC = 0.;
+  fOuterPedestalDC = 0.;
+  fInnerPedestalRMSDC = 0.;
+  fOuterPedestalRMSDC = 0.;
+  
+}
+
+MStarLocalCam::~MStarLocalCam()
+{
+    fStars->SetOwner();
+    fStars->Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+MStarLocalPos &MStarLocalCam::operator[] (Int_t i)
+{
+  MStarLocalPos& star = *static_cast<MStarLocalPos*>(fStars->At(i));
+  return star;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+const MStarLocalPos &MStarLocalCam::operator[] (Int_t i) const
+{
+    return *static_cast<MStarLocalPos*>(fStars->At(i));
+}
+
+void MStarLocalCam::Paint(Option_t *o)
+{
+	TIter Next(fStars);
+	MStarLocalPos* star;
+	while ((star=(MStarLocalPos*)Next())) 
+	    star->Paint(o);
+}
+
+void MStarLocalCam::Print(Option_t *o) const
+{
+      *fLog << inf << "DCs baseline:" << endl;
+      *fLog << inf << " Inner Pixels Mean pedestal \t" << setw(4) << fInnerPedestalDC << " uA  and RMS " << setw(4) << fInnerPedestalRMSDC << " uA for DCs" << endl;
+      *fLog << inf << " Outer Pixels Mean pedestal \t" << setw(4) << fOuterPedestalDC << " uA  and RMS " << setw(4) << fOuterPedestalRMSDC << " uA for DCs" << endl;
+      
+      TIter Next(fStars);
+      MStarLocalPos* star;
+      UInt_t starnum = 0;
+      while ((star=(MStarLocalPos*)Next())) 
+        {
+          *fLog << inf << "Star[" << starnum << "] info:" << endl;
+          star->Print(o);
+          starnum++;
+        }
+}
Index: /tags/Mars-V0.9/mtemp/MStarLocalCam.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MStarLocalCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MStarLocalCam.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MStarLocalCam
+#define MARS_MStarLocalCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+class TList;
+
+class MGeomCam;
+class MStarLocalPos;
+
+class MStarLocalCam : public MParContainer
+{
+private:
+
+  TList  *fStars;  //-> FIXME: Change TClonesArray away from a pointer?
+
+  // BaseLine DCs info
+  Float_t fInnerPedestalDC;         //[ua]
+  Float_t fOuterPedestalDC;         //[ua]
+
+  Float_t fInnerPedestalRMSDC;      //[ua]
+  Float_t fOuterPedestalRMSDC;      //[ua]
+
+  MHCamera fDisplay;
+
+ public:
+
+  MStarLocalCam(const char *name=NULL, const char *title=NULL);
+  ~MStarLocalCam();
+
+  MStarLocalPos &operator[] (Int_t i);
+  const MStarLocalPos &operator[] (Int_t i) const;
+
+  TList *GetList() const { return fStars; }
+  UInt_t GetNumStars() const { return fStars->GetSize(); }
+
+  //Getters
+
+  Float_t GetInnerPedestalDC() {return fInnerPedestalDC;}
+  Float_t GetOuterPedestalDC() {return fOuterPedestalDC;}
+  Float_t GetInnerPedestalRMSDC() { return fInnerPedestalRMSDC;}
+  Float_t GetOuterPedestalRMSDC() { return fOuterPedestalRMSDC;}
+
+  MHCamera& GetDisplay() { return fDisplay; }
+
+    //Setters
+  void SetInnerPedestalDC(Float_t ped) {fInnerPedestalDC = ped;}
+  void SetOuterPedestalDC(Float_t ped) {fOuterPedestalDC = ped;}
+  void SetInnerPedestalRMSDC(Float_t rms){fInnerPedestalRMSDC = rms;}
+  void SetOuterPedestalRMSDC(Float_t rms){fOuterPedestalRMSDC = rms;}
+
+  void Paint(Option_t *o=NULL);
+  void Print(Option_t *o=NULL) const;
+
+  ClassDef(MStarLocalCam, 1)	// Storage Container for star positions in the camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/MStarLocalPos.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MStarLocalPos.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MStarLocalPos.cc	(revision 9772)
@@ -0,0 +1,309 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López ,   4/2004 <mailto:jlopez@ifae.es>
+!              Robert Wagner,   7/2004 <mailto:rwagner@mppmu.mpg.de>
+!              Wolfgang Wittek, 8/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MStarLocalPos.h"
+
+#include <TEllipse.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MStarLocalPos);
+
+using namespace std;
+
+MStarLocalPos::MStarLocalPos(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MStarLocalPos";
+    fTitle = title ? title : "";
+    
+    Reset();
+}
+
+void MStarLocalPos::Reset()
+{
+
+    //Expected position on camera
+     fMagExp = 0.;
+     fXExp = 0.;
+     fYExp = 0.;
+
+    //Info from calculation
+     fMagCalc = 0.;
+     fMaxCalc = 0.;
+     fMeanXCalc = 0.;
+     fMeanYCalc = 0.;
+     fSigmaMinorAxisCalc = 0.;
+     fSigmaMajorAxisCalc = 0.;
+
+    //Info from uncorrelated Gauss fit
+     fMagFit = 0.;
+     fMaxFit = 0.;
+     fMeanXFit = 0.;
+     fMeanYFit = 0.;
+     fSigmaMinorAxisFit = 0.;
+     fSigmaMajorAxisFit = 0.;
+
+     fChiSquare = 0.;
+     fNdof = 1;
+
+    //Info from correlated Gauss fit
+     fMagCGFit    = 0.;
+     fMaxCGFit    = 0.;
+     fMeanXCGFit  = 0.;
+     fMeanYCGFit  = 0.;
+     fSigmaXCGFit = 0.;
+     fSigmaYCGFit = 0.;
+     fCorrXYCGFit = 0.;
+     fXXErrCGFit  = 0.;
+     fXYErrCGFit  = 0.;
+     fYYErrCGFit  = 0.;
+
+     fChiSquareCGFit = 0.;
+     fNdofCGFit      = 1;
+
+}
+
+void MStarLocalPos::SetExpValues(Float_t mag, Float_t x, Float_t y)
+{
+     fMagExp = mag;
+     fXExp = x;
+     fYExp = y;
+}
+
+void MStarLocalPos::SetIdealValues(Float_t mag, Float_t x, Float_t y)
+{
+     fMagIdeal = mag;
+     fXIdeal = x;
+     fYIdeal = y;
+}
+
+void MStarLocalPos::SetCalcValues(Float_t mag, Float_t max, 
+        Float_t x, Float_t y, Float_t sigmaMinorAxis, Float_t sigmaMajorAxis)
+{
+     fMagCalc = mag;
+     fMaxCalc = max;
+     fMeanXCalc = x;
+     fMeanYCalc = y;
+     fSigmaMinorAxisCalc = sigmaMinorAxis;
+     fSigmaMajorAxisCalc = sigmaMajorAxis;
+}
+
+void MStarLocalPos::SetFitValues(Float_t mag, Float_t max, 
+        Float_t x, Float_t y, Float_t sigmaMinorAxis, Float_t sigmaMajorAxis, 
+        Float_t chiSquare, Int_t ndof)
+{
+     fMagFit = mag;
+     fMaxFit = max;
+     fMeanXFit = x;
+     fMeanYFit = y;
+     fSigmaMinorAxisFit = sigmaMinorAxis;
+     fSigmaMajorAxisFit = sigmaMajorAxis;
+     fChiSquare = chiSquare;
+     fNdof = ndof;
+}
+
+void MStarLocalPos::SetFitValues(Float_t mag, Float_t max, 
+        Float_t x, Float_t y, Float_t sigmaMinorAxis, Float_t sigmaMajorAxis, 
+        Float_t chiSquare, Int_t ndof, 
+        Float_t xx, Float_t xy, Float_t yy)
+{
+  SetFitValues(mag, max, x, y, sigmaMinorAxis, sigmaMajorAxis, chiSquare, ndof);
+  fXXErr = xx;
+  fYYErr = yy;
+  fXYErr = xy;
+}
+
+void MStarLocalPos::SetCGFitValues(
+               Float_t mag,       Float_t max,    Float_t x,    Float_t y, 
+               Float_t sigmaX,    Float_t sigmaY, Float_t correlation, 
+               Float_t xx,        Float_t xy,     Float_t yy,
+               Float_t chiSquare, Int_t ndof)
+{
+     fMagCGFit    = mag;
+     fMaxCGFit    = max;
+     fMeanXCGFit  = x;
+     fMeanYCGFit  = y;
+     fSigmaXCGFit = sigmaX;
+     fSigmaYCGFit = sigmaY;
+     fCorrXYCGFit = correlation;
+     fXXErrCGFit  = xx;
+     fXYErrCGFit  = xy;
+     fYYErrCGFit  = yy;
+
+     fChiSquareCGFit = chiSquare;
+     fNdofCGFit      = ndof;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MStarLocalPos::Paint(Option_t *opt)
+{
+  //Print a cross in the expected position
+  TMarker mexp(fXExp, fYExp, 29);
+  mexp.SetMarkerSize(3);
+  mexp.SetMarkerColor(94);
+  mexp.Paint(); 
+
+  if (fSigmaMinorAxisCalc>0. && fSigmaMajorAxisCalc>0.)
+    {
+      TEllipse ecalc(fMeanXCalc, fMeanYCalc, fSigmaMinorAxisCalc, fSigmaMajorAxisCalc, 0, 360, 0);
+      ecalc.SetLineWidth(3);
+      ecalc.SetLineColor(kBlue);
+      ecalc.Paint();
+    }
+
+  if (fSigmaMinorAxisFit>0. && fSigmaMajorAxisFit>0.)
+    {
+      TEllipse efit(fMeanXFit, fMeanYFit, fSigmaMinorAxisFit, fSigmaMajorAxisFit, 0, 360, 0);
+      efit.SetLineWidth(3);
+      efit.SetLineColor(kBlack);
+      efit.Paint();
+    }
+
+  if (fSigmaXCGFit>0. && fSigmaYCGFit>0.)
+    {
+      //Print a cross in the fitted position
+      //TMarker mCGFit(fMeanXCGFit, fMeanYCGFit, 3);
+      //mCGFit.SetMarkerSize(3);
+      //mCGFit.SetMarkerColor(1);
+      //mCGFit.Paint(); 
+
+      Double_t cxx = fSigmaXCGFit*fSigmaXCGFit;
+      Double_t cyy = fSigmaYCGFit*fSigmaYCGFit;
+      Double_t d   = cyy - cxx;
+      Double_t cxy = fCorrXYCGFit * fSigmaXCGFit * fSigmaYCGFit;
+      Double_t tandel;
+      if (cxy != 0.0)
+        tandel = ( d + sqrt(d*d + 4.0*cxy*cxy) ) / (2.0*cxy); 
+      else
+        tandel = 0.0;
+
+      Double_t sindel = tandel / sqrt(1.0 + tandel*tandel);
+      Double_t delta = TMath::ASin(sindel);
+
+      Double_t major =   (cxx + 2.0*tandel*cxy + tandel*tandel*cyy)
+	                / (1.0 + tandel*tandel);  
+
+      Double_t minor =   (tandel*tandel*cxx - 2.0*tandel*cxy + cyy)
+	                / (1.0 + tandel*tandel);  
+
+      TEllipse efit(fMeanXCGFit, fMeanYCGFit, sqrt(major), sqrt(minor), 
+                    0, 360,      delta*kRad2Deg);
+      efit.SetLineWidth(3);
+      efit.SetLineColor(kMagenta);
+      efit.Paint();
+    }
+}
+  
+void MStarLocalPos::Print(Option_t *opt) const
+{
+  TString o = opt;
+
+  if (o.Contains("name", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Name: \"" << this->GetName() << "\"" << endl;
+    }
+      
+  if (o.Contains("mag", TString::kIgnoreCase) || opt == NULL)
+    {
+  
+      *fLog << inf << "Star magnitude:" << endl;
+      *fLog << inf << " Expected \t" << setw(4) << fMagExp << endl;
+      *fLog << inf << " Calcultated \t " << setw(4) << fMagCalc << endl;
+      *fLog << inf << " Fitted \t " << setw(4) << fMagFit << endl;
+      *fLog << inf << " CGFitted \t " << setw(4) << fMagCGFit << endl;
+    }
+  
+  if (o.Contains("max", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Maximum:" << endl;
+      *fLog << inf << " Calcultated \t " << setw(4) << fMaxCalc << " uA" 
+            << endl;
+      *fLog << inf << " Fitted \t " << setw(4) << fMaxFit << " uA" << endl;
+      *fLog << inf << " CGFitted \t " << setw(4) << fMaxCGFit << " uA" << endl;
+    }
+  
+  if (o.Contains("pos", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star position:" << endl;
+      *fLog << inf << " Expected \t X " << setw(4) << fXExp 
+            << " mm \tY " << setw(4) << fYExp << " mm" << endl;
+      *fLog << inf << " Calcultated \t X " << setw(4) << fMeanXCalc 
+            << " mm \tY " << setw(4) << fMeanYCalc << " mm" << endl;
+      *fLog << inf << " Fitted \t X " << setw(4) << fMeanXFit 
+            << " mm \tY " << setw(4) << fMeanYFit << " mm" << endl;
+      *fLog << inf << " CGFitted \t X " << setw(4) << fMeanXCGFit 
+            << " mm \tY " << setw(4) << fMeanYCGFit << " mm" << endl;
+    }
+
+  if (o.Contains("siz", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star size:" << endl;
+      *fLog << inf << " Calcultated \t X " << setw(4) << fSigmaMinorAxisCalc 
+            << " mm \tY " << setw(4) << fSigmaMajorAxisCalc << " mm" << endl;
+      *fLog << inf << " Fitted \t X " << setw(4) << fSigmaMinorAxisFit 
+            << " mm \tY " << setw(4) << fSigmaMajorAxisFit << " mm" << endl;
+      *fLog << inf << " CGFitted \t X " << setw(4) << fSigmaXCGFit 
+            << " mm \tY " << setw(4) << fSigmaYCGFit << " mm \t correlation" 
+            << setw(4) << fCorrXYCGFit << endl;
+    }
+
+  if (o.Contains("chi", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Fit Quality:" << endl;
+      *fLog << inf << " ChiSquare/Ndof \t " << setw(3) << fChiSquare 
+            << "/" << fNdof << endl;
+
+      *fLog << inf << "Star CGFit Quality:" << endl;
+      *fLog << inf << " ChiSquareCGFit/NdofCGFit \t " << setw(3) 
+            << fChiSquareCGFit << "/" << fNdofCGFit << endl;
+    }
+
+  if (o.Contains("err", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "CGFit Error Matrix of (fMeanXCGFit,fMeanYCGFit) :" 
+            << endl;
+      *fLog << inf << " xx,xy,yy \t " << setw(3) << fXXErrCGFit << ", " 
+            << fXYErrCGFit << ", " << fYYErrCGFit << endl;
+    }
+
+
+}
+//--------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MStarLocalPos.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MStarLocalPos.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MStarLocalPos.h	(revision 9772)
@@ -0,0 +1,142 @@
+#ifndef MARS_MStarLocalPos
+#define MARS_MStarLocalPos
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MStarLocalPos : public MParContainer
+{
+private:
+
+    //Expected position on camera
+    Float_t fMagExp;
+    Float_t fXExp;    //[mm]
+    Float_t fYExp;    //[mm]
+
+    //Ideal position on camera
+    Float_t fMagIdeal;
+    Float_t fXIdeal;    //[mm]
+    Float_t fYIdeal;    //[mm]
+
+    //Info from calculation
+    Float_t fMagCalc;
+    Float_t fMaxCalc;            //[uA]
+    Float_t fMeanXCalc;          //[mm]
+    Float_t fMeanYCalc;          //[mm]
+    Float_t fSigmaMinorAxisCalc; //[mm]
+    Float_t fSigmaMajorAxisCalc; //[mm]
+
+    //Info from uncorrelated Gauss fit
+    Float_t fMagFit;
+    Float_t fMaxFit;             //[uA]
+    Float_t fMeanXFit;           //[mm]
+    Float_t fMeanYFit;           //[mm]
+    Float_t fSigmaMinorAxisFit;  //[mm]
+    Float_t fSigmaMajorAxisFit;  //[mm]
+    Float_t fXXErr;          
+    Float_t fXYErr;
+    Float_t fYYErr;
+
+    Float_t fChiSquare;
+    Int_t   fNdof;
+
+    //Info from correlated Gauss fit
+    Float_t fMagCGFit;
+    Float_t fMaxCGFit;             //[uA]
+    Float_t fMeanXCGFit;           //[mm]
+    Float_t fMeanYCGFit;           //[mm]
+    Float_t fSigmaXCGFit;          //[mm]
+    Float_t fSigmaYCGFit;          //[mm]
+    Float_t fCorrXYCGFit;          // correlation coefficient
+    Float_t fXXErrCGFit;           // error matrix of (fMeanXCGFit,fMeanYCGFit)
+    Float_t fXYErrCGFit;
+    Float_t fYYErrCGFit;
+
+    Float_t fChiSquareCGFit;
+    Int_t   fNdofCGFit;
+
+
+public:
+
+    MStarLocalPos(const char *name=NULL, const char *title=NULL);
+    //~MStarLocalPos();
+
+    Float_t GetMagExp() {return fMagExp;}
+    Float_t GetXExp() {return fXExp;}
+    Float_t GetYExp() {return fYExp;}
+
+    Float_t GetMagIdeal() {return fMagIdeal;}
+    Float_t GetXIdeal() {return fXIdeal;}
+    Float_t GetYIdeal() {return fYIdeal;}
+
+    Float_t GetMagCalc() {return fMagCalc;}
+    Float_t GetMaxCalc() {return fMaxCalc;}
+    Float_t GetMeanXCalc() {return fMeanXCalc;}
+    Float_t GetMeanYCalc() {return fMeanYCalc;}
+    Float_t GetSigmaMinorAxisCalc() {return fSigmaMinorAxisCalc;}
+    Float_t GetSigmaMajorAxisCalc() {return fSigmaMajorAxisCalc;}
+
+    Float_t GetMagFit() {return fMagFit;}
+    Float_t GetMaxFit() {return fMaxFit;}
+    Float_t GetMeanXFit() {return fMeanXFit;}
+    Float_t GetMeanYFit() {return fMeanYFit;}
+    Float_t GetSigmaMinorAxisFit() {return fSigmaMinorAxisFit;}
+    Float_t GetSigmaMajorAxisFit() {return fSigmaMajorAxisFit;}
+    Float_t GetChiSquare() {return fChiSquare;}
+    UInt_t GetNdof() {return fNdof;}
+    Float_t GetChiSquareNdof() {return fChiSquare/fNdof;}
+
+    Float_t GetMeanX() {return fMeanXFit!=0?fMeanXFit:fMeanXCalc;}
+    Float_t GetMeanY() {return fMeanXFit!=0?fMeanYFit:fMeanYCalc;}
+    Float_t GetSigmaMinorAxis() {return fSigmaMinorAxisFit!=0?fSigmaMinorAxisFit:fSigmaMinorAxisCalc;}
+    Float_t GetSigmaMajorAxis() {return fSigmaMajorAxisFit!=0?fSigmaMajorAxisFit:fSigmaMajorAxisCalc;}
+    
+    // getters for the correlated Gauss fit
+    Float_t GetMagCGFit()           {return fMagCGFit;}
+    Float_t GetMaxCGFit()           {return fMaxCGFit;}
+    Float_t GetMeanXCGFit()         {return fMeanXCGFit;}
+    Float_t GetMeanYCGFit()         {return fMeanYCGFit;}
+    Float_t GetSigmaXCGFit()        {return fSigmaXCGFit;}
+    Float_t GetSigmaYCGFit()        {return fSigmaYCGFit;}
+    Float_t GetCorrXYCGFit()        {return fCorrXYCGFit;}
+    Float_t GetXXErrCGFit()         {return fXXErrCGFit;}
+    Float_t GetXYErrCGFit()         {return fXYErrCGFit;}
+    Float_t GetYYErrCGFit()         {return fYYErrCGFit;}
+    Float_t GetChiSquareCGFit()     {return fChiSquareCGFit;}
+    UInt_t GetNdofCGFit()           {return fNdofCGFit;}
+    Float_t GetChiSquareNdofCGFit() {return fChiSquareCGFit/fNdofCGFit;}
+
+
+    void Reset();
+
+    void SetExpValues(Float_t mag, Float_t x, Float_t y);
+
+    void SetIdealValues(Float_t mag, Float_t x, Float_t y);
+
+    void SetCalcValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+                       Float_t sigmaMinorAxis, Float_t sigmaMajorAxis);
+
+    void SetFitValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+                      Float_t sigmaMinorAxis, Float_t sigmaMajorAxis, 
+                      Float_t chi, Int_t ndof);
+
+    void SetFitValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+                      Float_t sigmaX, Float_t sigmaY, 
+                      Float_t chi, Int_t ndof, 
+                      Float_t xx, Float_t xy, Float_t yy);
+
+    void SetCGFitValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+                        Float_t sigmaX, Float_t sigmaY, Float_t correlation, 
+                        Float_t xx, Float_t xy, Float_t yy,
+                        Float_t chi, Int_t ndof);
+
+    void Paint(Option_t *opt=NULL);
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MStarLocalPos, 1) // Container that holds the star information in the PMT camera
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mtemp/MTelAxisFromStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MTelAxisFromStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MTelAxisFromStars.cc	(revision 9772)
@@ -0,0 +1,1266 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Wolfgang Wittek 07/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MTelAxisFromStars
+//
+//  This task 
+//  - determines the transformation from expected positions of stars
+//    in the camera to measured positions of these stars in the camera
+//  - applies this transformation to expected positions of other objects 
+//    to obtain the estimated positions of these objects in the camera
+//  - puts the estimated positions into the relevant containers
+//
+//  Input Containers :
+//   MStarCam[MStarCam], MStarCamSource[MStarCam]
+//
+//  Output Containers :
+//   MSkyCamTrans, MSrcPosCam 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <TMath.h>
+#include <TList.h>
+#include <TSystem.h>
+
+#include <fstream>
+
+#include "MTelAxisFromStars.h"
+
+#include "MParList.h"
+
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MReportDrive.h"
+#include "MPointingPos.h"
+#include "MSrcPosCam.h"
+
+#include "MStarCam.h"
+#include "MStarPos.h"
+#include "MSkyCamTrans.h"
+#include "MStarCamTrans.h"
+
+ClassImp(MTelAxisFromStars);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Constructor
+//
+MTelAxisFromStars::MTelAxisFromStars(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MTelAxisFromStars";
+    fTitle = title ? title : "Calculate source position from star positions";
+
+    // if scale factor fLambda should NOT be fixed set fFixdScaleFactor to 
+    // -1.0; otherwise set it to the value requested
+    fFixedScaleFactor   = 1.0;
+
+    // if rotation angle fAlfa should NOT be fixed set fFixdRotationAngle to 
+    // -1.0; otherwise set it to the requested value
+    fFixedRotationAngle = 0.0;
+
+    // default type of input is :    the result of the Gauss fit
+    // type 0 : result from the weighted average
+    // type 1 : result from the Gauss fit
+    fInputType = 1;
+
+    // default value of fAberr
+    // the value 1.07 is valid if the expected position (with aberration)
+    // in the camera is calculated as the average of the positions obtained
+    // from the reflections at the individual mirrors
+    fAberr = 1.07;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor
+//
+MTelAxisFromStars::~MTelAxisFromStars()
+{
+  delete fStarCamTrans;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set links to containers
+//
+
+Int_t MTelAxisFromStars::PreProcess(MParList *pList)
+{
+   fDrive = (MReportDrive*)pList->FindObject(AddSerialNumber("MReportDrive"));
+   if (!fDrive)
+   {
+       *fLog << err << AddSerialNumber("MReportDrive") 
+             << " not found... aborting." << endl;
+       return kFALSE;
+   }
+ 
+  
+   fStarCam = (MStarCam*)pList->FindObject("MStarCam", "MStarCam");
+   if (!fStarCam)
+   {
+       *fLog << err << "MStarCam not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   
+   fSourceCam = (MStarCam*)pList->FindObject("MSourceCam", "MStarCam");
+   if (!fSourceCam)
+   {
+       *fLog << warn << "MSourceCam[MStarCam] not found... continue  " << endl;
+   }
+
+
+   //-----------------------------------------------------------------
+    fSrcPos = (MSrcPosCam*)pList->FindCreateObj(AddSerialNumber("MSrcPosCam"), "MSrcPosCam");
+    if (!fSrcPos)
+        return kFALSE;
+
+    fPntPos = (MSrcPosCam*)pList->FindCreateObj(AddSerialNumber("MSrcPosCam"), "MPntPosCam");
+    if (!fPntPos)
+        return kFALSE;
+
+    fPointPos = (MPointingPos*)pList->FindCreateObj(AddSerialNumber("MPointingPos"), "MPointingPos");
+    if (!fPointPos)
+        return kFALSE;
+
+    fSourcePos = (MPointingPos*)pList->FindCreateObj(AddSerialNumber("MPointingPos"), "MSourcePos");
+    if (!fSourcePos)
+        return kFALSE;
+
+    fSkyCamTrans = (MSkyCamTrans*)pList->FindCreateObj(AddSerialNumber("MSkyCamTrans"));
+    if (!fSkyCamTrans)
+        return kFALSE;
+
+
+   //-----------------------------------------------------------------
+   // book an MStarCamTrans object
+   // this is needed when calling one of the member functions of MStarCamTrans
+
+   MGeomCam *geom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+   if (!geom)
+   {
+       *fLog << err << AddSerialNumber("MGeomCam") 
+             << " not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   MObservatory *obs = (MObservatory*)pList->FindObject(AddSerialNumber("MObservatory"));
+   if (!obs)
+   {
+       *fLog << err << AddSerialNumber("MObservatory") 
+             << " not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   //-----------------------------------------------------------------
+    fStarCamTrans = new MStarCamTrans(*geom, *obs);
+
+   *fLog << all   << "MTelAxisFromStars::Preprocess; the optical aberration factor is set equal to : " 
+         << fAberr ;
+
+   *fLog << all   << "MTelAxisFromStars::Preprocess; input type is set equal to : " 
+         << fInputType ;
+   if (fInputType == 0)
+     *fLog << " (calculated star positions)" << endl;
+   else
+     *fLog << " (fitted star positions)" << endl;
+
+   *fLog << all << "MTelAxisFromStars::Preprocess; scale factor will be fixed at : " 
+         << fFixedScaleFactor << endl;
+
+   *fLog << all << "MTelAxisFromStars::Preprocess; rotation angle will be fixed at : " 
+         << fFixedRotationAngle << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set optical aberration factor
+//
+//   fAberr   is the ratio between 
+//            the distance from the camera center with optical aberration and
+//            the distance from the camera center with an ideal imaging
+//
+//   fAberr = r_real/r_ideal 
+//
+void MTelAxisFromStars::SetOpticalAberr(Double_t aberr)
+{
+  fAberr = aberr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the type of the input
+//
+//     type = 0        calculated star positions (by averaging)
+//     type = 1        fitted star positions (by Gauss fit)
+//
+void MTelAxisFromStars::SetInputType(Int_t type)
+{
+  fInputType = type;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fix the scale factor fLambda
+//
+//
+void MTelAxisFromStars::FixScaleFactorAt(Double_t lambda)
+{
+  fFixedScaleFactor = lambda;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fix rotation angle fAlfa
+//
+//
+void MTelAxisFromStars::FixRotationAngleAt(Double_t alfa)
+{
+  fFixedRotationAngle = alfa;    // [degrees]
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Process
+//
+//           call FindSkyCamTrans    to find the Sky-Camera transformation
+//           call TransSkyCam        to transform some sky directions
+//                                   into the camera system
+//           put the estimated source position into MSrcPosCam
+//
+
+Int_t MTelAxisFromStars::Process()
+{
+  //Int_t run = fRun->GetRunNumber();
+  //*fLog << "MTelAxisFromStars::Process; run = " << run << endl;
+
+  //--------------------------------------
+  // Define the input for FindSkyCamTrans
+  //
+
+  // get the expected (axy[0], axy[1]) and the measured positions 
+  // (bxy[0], bxy[1]) of stars in the camera from MStarCam 
+  Int_t fNumStars = fStarCam->GetNumStars();
+
+  if (fNumStars <= 0)
+    return kTRUE;
+
+  TArrayD  axy[2];
+  axy[0].Set(fNumStars);
+  axy[1].Set(fNumStars);
+
+  TArrayD  bxy[2];
+  bxy[0].Set(fNumStars);
+  bxy[1].Set(fNumStars);
+
+  // error matrix of bxy
+  TArrayD  exy[2][2];
+  exy[0][0].Set(fNumStars);
+  exy[0][1].Set(fNumStars);
+  exy[1][0].Set(fNumStars);
+  exy[1][1].Set(fNumStars);
+
+  // transformation parameters
+  Double_t fLambda;
+  Double_t fAlfa;
+  Double_t fA[2][2];
+  Double_t fD[2];
+  Double_t fErrD[2][2];
+  Int_t    fNumIter;
+  Int_t    fNdof;
+  Double_t fChi2;
+  Double_t fChi2Prob;
+
+  MStarPos *star = 0;
+  TIter next(fStarCam->GetList());
+  Int_t ix = 0;
+
+  // loop over all stars
+  while ( (star = (MStarPos*)next()) )
+  {
+    axy[0][ix]   = star->GetXExp(); 
+    axy[1][ix]   = star->GetYExp(); 
+
+    if (fInputType == 0)
+    {
+      // values from averaging
+      bxy[0][ix]     = star->GetMeanXCalc(); 
+      bxy[1][ix]     = star->GetMeanYCalc(); 
+
+      // this is the error matrix for (MeanXCalc, MeanYCalc);
+      // this is the error matrix which should be used
+      exy[0][0][ix]  =  star->GetXXErrCalc(); 
+      exy[0][1][ix]  =  star->GetXYErrCalc();
+      exy[1][0][ix]  =  star->GetXYErrCalc();
+      exy[1][1][ix]  =  star->GetYYErrCalc();
+
+      //exy[0][0][ix]  = star->GetSigmaXCalc()*star->GetSigmaXCalc(); 
+      //exy[0][1][ix]  =  0.0;
+      //exy[1][0][ix]  =  0.0;
+      //exy[1][1][ix]  = star->GetSigmaYCalc()*star->GetSigmaYCalc(); 
+    }
+
+    else if (fInputType == 1)
+    {
+      // values from Gauss fit
+      bxy[0][ix]   = star->GetMeanXFit(); 
+      bxy[1][ix]   = star->GetMeanYFit(); 
+
+      // this is the error matrix for (MeanXFit, MeanYFit);
+      // this is the error matrix which should be used
+      exy[0][0][ix]  =  star->GetXXErrFit(); 
+      exy[0][1][ix]  =  star->GetXYErrFit();
+      exy[1][0][ix]  =  star->GetXYErrFit();
+      exy[1][1][ix]  =  star->GetYYErrFit();
+
+      // this is the error matrix constructed from SigmaXFit and SigmaYFit;
+      // it is used because the errors above are too small, at present
+      //exy[0][0][ix]  =  star->GetSigmaXFit() * star->GetSigmaXFit(); 
+      //exy[0][1][ix]  =  star->GetCorrXYFit() * 
+      //                  star->GetSigmaXFit() * star->GetSigmaYFit();
+      //exy[1][0][ix]  =  exy[0][1][ix];
+      //exy[1][1][ix]  =  star->GetSigmaYFit() * star->GetSigmaYFit();
+    }
+
+    else
+    {
+      *fLog << err << "MTelAxisFromStars::Process;  type of input is not defined" 
+            << endl;
+      return kFALSE;
+    }   
+
+    // don't include stars with undefined error
+    Double_t deter =   exy[0][0][ix]*exy[1][1][ix]
+                     - exy[0][1][ix]*exy[1][0][ix];
+
+    //*fLog << "ix ,deter, xx, xy, yy = " << ix << ":    "
+    //      << deter << ",  " << exy[0][0][ix] << ",  "
+    //      << exy[0][1][ix] << ",  " << exy[1][1][ix] << endl;
+    if (deter <= 0.0)
+      continue;
+
+    //*fLog << "MTelAxisFromStars : " << endl;
+    //*fLog << "      ix, XExp, YExp, XFit, YFit, SigmaX2, SigmaXY, SigmaY2 = " 
+    //      << ix << " :  " 
+    //      << axy[0][ix] << ",  " << axy[1][ix] << ",  "
+    //      << bxy[0][ix] << ",  " << bxy[1][ix] << ",  "
+    //      << exy[0][0][ix] << ",  " << exy[0][1][ix] << ",  " 
+    //      << exy[1][1][ix] << endl;
+
+    ix++;
+  }
+
+  //--------------------------------------
+  // Find the transformation from expected positions (axy[1], axy[2]) 
+  // to measured positions (bxy[1], bxy[2]) in the camera
+
+  Int_t fNStars = ix;
+
+  if (ix < fNumStars)
+  {
+    // reset the sizes of the arrays
+    Int_t fNStars = ix;
+    axy[0].Set(fNStars);
+    axy[1].Set(fNStars);
+
+    bxy[0].Set(fNStars);
+    bxy[1].Set(fNStars);
+
+    exy[0][0].Set(fNStars);
+    exy[0][1].Set(fNStars);
+    exy[1][0].Set(fNStars);
+    exy[1][1].Set(fNStars);
+  }
+
+  Bool_t fitOK;
+  if (fNStars < 1)
+  {
+    //*fLog << "MTelAxisFromStars::Process; no star for MTelAxisFromStars"
+    //      << endl;
+    fitOK = kFALSE;
+  }
+  else
+  {
+    fitOK =  FindSkyCamTrans(axy,      bxy,   exy,   
+               fFixedRotationAngle,    fFixedScaleFactor, fLambda,
+               fAlfa  ,  fA,    fD,    fErrD,
+               fNumIter, fNdof, fChi2, fChi2Prob);
+  }
+
+  if (!fitOK  &&  fNStars >= 1)
+  {
+    *fLog << err 
+          << "MTelAxisFromStars::Process;  Fit to find transformation from star to camera system failed" 
+          << endl;
+    
+    //if (fNStars > 0)
+    //{
+    //  *fLog << err 
+    //        << "    fNumIter, fNdof, fChi2, fChi2Prob = " << fNumIter
+    //        << ",  " << fNdof << ",  " << fChi2 << ",  " << fChi2Prob << endl;
+    //}
+
+    return kTRUE;
+  }
+
+
+  //--------------------------------------
+  // Put the transformation parameters into the MSkyCamTrans container
+
+  fSkyCamTrans->SetParameters(fLambda,   fAlfa,    fA,    fD,    fErrD,
+                              fNumStars, fNumIter, fNdof, fChi2, fChi2Prob);
+  fSkyCamTrans->SetReadyToSave();
+
+  //--------------------------------------
+  // Put the camera position (X, Y) 
+  //         obtained by transforming the camera center (0, 0)
+  // into MPntPosCam[MSrcPosCam]
+
+  fPntPos->SetXY(fD[0], fD[1]);
+  fPntPos->SetReadyToSave();       
+
+
+  //--------------------------------------
+  // Put the corrected pointing position into MPointingPos 
+  //
+  SetPointingPosition(fStarCamTrans, fDrive, fSkyCamTrans, fPointPos);
+
+
+  //--------------------------------------
+  // Put the estimated position of the source into SrcPosCam
+  //
+  // get the source direction from MReportDrive
+  // Note : this has to be changed for the wobble mode, where the source 
+  //        isn't in the center of the camera
+  Double_t decsource = fDrive->GetDec();
+  Double_t rasource  = fDrive->GetRa();
+  //
+  Double_t radrive = fDrive->GetRa();
+  Double_t hdrive  = fDrive->GetHa();
+  Double_t hsource = hdrive + radrive - rasource;
+  fSourcePos->SetSkyPosition(rasource, decsource, hsource);
+
+  SetSourcePosition(fStarCamTrans, fPointPos, fSourcePos, fSrcPos);
+
+  //*fLog << "after calling SetSourcePosition : , X, Y ,fD = " 
+  //      << fSrcPos->GetX() << ",  " << fSrcPos->GetY() << ",  "
+  //      << fD[0] << ",  " << fD[1] << endl;
+
+  //--------------------------------------
+  // Apply the transformation to some expected positions (asxy[1], asxy[2]) 
+  // to obtain estimated positions (bsxy[1], bsxy[2]) in the camera 
+  //      and their error matrices esxy[2][2]
+
+  // get the expected positions (asxy[1], asxy[2]) from another MStarCam 
+  // container (with the name "MSourceCam") 
+  Int_t fNumStarsSource = 0; 
+
+  if (fSourceCam)
+    fNumStarsSource = fSourceCam->GetNumStars();
+
+  //*fLog << "MTelAxisFromStars::Process;  fNumStarsSource = " 
+  //      << fNumStarsSource << endl;
+
+  if (fNumStarsSource > 0)
+  {
+    TArrayD  asxy[2];
+    asxy[0].Set(fNumStarsSource);
+    asxy[1].Set(fNumStarsSource);
+
+    TArrayD  bsxy[2];
+    bsxy[0].Set(fNumStarsSource);
+    bsxy[1].Set(fNumStarsSource);
+
+    TArrayD  esxy[2][2];
+    esxy[0][0].Set(fNumStarsSource);
+    esxy[0][1].Set(fNumStarsSource);
+    esxy[1][0].Set(fNumStarsSource);
+    esxy[1][1].Set(fNumStarsSource);
+
+    MStarPos *starSource = 0;
+    TIter nextSource(fSourceCam->GetList());
+    ix = 0;
+    while ( (starSource = (MStarPos*)nextSource()) )
+    {
+      asxy[0][ix]  = starSource->GetXExp(); 
+      asxy[1][ix]  = starSource->GetYExp(); 
+
+      ix++;
+    }
+
+    TransSkyCam(fLambda, fA, fD, fErrD, asxy, bsxy,  esxy);   
+
+    // put the estimated positions into the MStarCam container
+    // with name "MSourceCam"
+    TIter setnextSource(fSourceCam->GetList());
+    ix = 0;
+    while ( (starSource = (MStarPos*)setnextSource()) )
+    {
+       Double_t corr = esxy[0][1][ix] / 
+                       TMath::Sqrt( esxy[0][0][ix] * esxy[1][1][ix] );
+       if (fInputType == 1)
+       {
+         starSource->SetFitValues(100.0, 100.0, bsxy[0][ix], bsxy[1][ix],
+	       TMath::Sqrt(esxy[0][0][ix]), TMath::Sqrt(esxy[1][1][ix]), corr,
+               esxy[0][0][ix],       esxy[0][1][ix],       esxy[1][1][ix], 
+               fChi2, fNdof); 
+       }
+       else
+       {
+         starSource->SetCalcValues(100.0, 100.0, bsxy[0][ix], bsxy[1][ix],
+	       TMath::Sqrt(esxy[0][0][ix]), TMath::Sqrt(esxy[1][1][ix]), corr,
+               esxy[0][0][ix],       esxy[0][1][ix],       esxy[1][1][ix]); 
+       }
+
+      ix++;
+    }
+
+  }
+
+  //--------------------------------------
+
+  return kTRUE;
+}
+
+
+
+//---------------------------------------------------------------------------
+//
+// FindSkyCamTrans
+//
+// This routine determines the transformation 
+//
+//                                      ( cos(alfa)   -sin(alfa) )
+//      b = lambda * A * a + d      A = (                        )
+//             ^     ^       ^          ( sin(alfa)    cos(alfa) )
+//             |     |       |
+//           scale rotation shift 
+//          factor matrix
+//
+// from sky coordinates 'a' (projected onto the camera) to camera 
+// coordinates 'b', using the positions of known stars in the camera. 
+// The latter positions may have been determined by analysing the 
+// DC currents in the different pixels.
+//
+// Input  : a[2]    x and y coordinates of stars projected onto the camera;
+//                  they were obtained from (RA, dec) of the stars and
+//                  (ThetaTel, PhiTel) and the time of observation;
+//                  these are the 'expected positions' of stars in the camera
+//          b[2]    'measured positions' of these stars in the camera;
+//                  they may have been obtained from the DC currents
+//          e[2][2] error matrix of b[2]
+//          fixedrotationangle  value [in degrees] at which rotation angle 
+//                              alfa should be fixed; -1 means don't fix
+//          fixedscalefactor    value at which scale factor lambda  
+//                              should be fixed; -1 means don't fix
+//
+// Output : lambda, alfadeg, A[2][2], d[2]   fit results;
+//                               parameters describing the transformation 
+//                               from 'expected positions' to the 'measured 
+//                               positions' in the camera
+//          errd[2][2]           error matrix of d[2]
+//          fNumIter             number of iterations
+//          fNdoF                number of degrees of freedom
+//          fChi2                chi-square value
+//          fChi2Prob            chi-square probability
+//
+// The units are assumed to be 
+//     [degrees]  for  alfadeg
+//     [mm]       for  a, b, d
+//     [1]        for  lambda                       
+
+Bool_t MTelAxisFromStars::FindSkyCamTrans(
+   TArrayD a[2],      TArrayD b[2],     TArrayD e[2][2], 
+   Double_t &fixedrotationang, Double_t &fixedscalefac,  Double_t &lambda,  
+   Double_t &alfadeg, Double_t A[2][2], Double_t d[2],   Double_t errd[2][2],
+   Int_t &fNumIter,   Int_t &fNdof,     Double_t &fChi2, Double_t &fChi2Prob)
+{
+  Int_t fNumStars = a[0].GetSize();
+
+  //*fLog << "MTelAxisFromStars::FindSkyCamTrans; expected and measured positions :"
+  //        << endl;
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+    //*fLog << "    ix, a[0], a[1], b[0], b[1], errxx, errxy, erryy = " 
+    //        << ix << " :   " 
+    //        << a[0][ix] << ",  " << a[1][ix] << ";    " 
+    //        << b[0][ix] << ",  " << b[1][ix] << ";    " 
+    //        << e[0][0][ix] << ",  " << e[0][1][ix] << ",  "
+    //        << e[1][1][ix] << endl;
+  }
+
+
+  //-------------------------------------------
+  // fix some parameters if the number of degrees of freedom is too low
+  // (<= 0.0)
+
+  Double_t fixedscalefactor   = fixedscalefac;
+  Double_t fixedrotationangle = fixedrotationang;
+
+  // calculate number of degrees of freedom
+  fNdof = 2 * fNumStars - 4;
+  if (fixedscalefactor != -1.0)
+     fNdof += 1;
+  if (fixedrotationangle != -1.0)
+     fNdof += 1;
+
+  // if there is only 1 star fix both rotation angle and scale factor
+  if (fNumStars == 1)
+  {
+     if (fixedscalefactor == -1.0)
+     {  
+       fixedscalefactor = 1.0;
+       *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; scale factor is fixed at "
+	     << fixedscalefactor << endl;
+     }
+     if (fixedrotationangle == -1.0)
+     {
+       fixedrotationangle = 0.0;
+       *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; rotation angle is fixed at "
+	     << fixedrotationangle << endl;
+     }
+  }
+  // otherwise fix only 1 parameter if possible
+  else if (fNdof < 0)
+  {
+    if (fNdof < -2)
+    {
+      *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; number of degrees of freedom is too low : " 
+            << fNdof << ";  fNumStars = " << fNumStars << endl;
+      return kFALSE;
+    }
+    else if (fNdof == -2)
+    {
+      if (fixedscalefactor == -1.0  &&  fixedrotationangle == -1.0)
+      {
+        fixedscalefactor   = 1.0;
+        fixedrotationangle = 0.0;
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; scale factor and rotation angle are fixed at " 
+              << fixedscalefactor << "  and  " << fixedrotationangle 
+              << " respectively" << endl;
+      }
+      else
+      {
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; number of degrees of freedom is too low : " 
+              << fNdof << ";  fNumStars = " << fNumStars << endl;
+        return kFALSE;
+      }
+    }
+    else if (fNdof == -1)
+    {
+      if (fixedrotationangle == -1.0)
+      {
+        fixedrotationangle = 0.0;
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; rotation angle is fixed at "
+	      << fixedrotationangle << endl;
+      }
+      else if (fixedscalefactor == -1.0)
+      {
+        fixedscalefactor = 1.0;
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; scale factor is fixed at "
+	      << fixedscalefactor << endl;
+      }
+      else
+      {
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; number of degrees of freedom is too low : " 
+              << fNdof << ";  fNumStars = " << fNumStars<< endl;
+        return kFALSE;
+      }
+    }
+  }
+
+  // recalculate number of degrees of freedom
+  fNdof = 2 * fNumStars - 4;
+  if (fixedscalefactor != -1.0)
+     fNdof += 1;
+  if (fixedrotationangle != -1.0)
+     fNdof += 1;
+
+  if (fNdof < 0)
+    return kFALSE;
+  //-------------------------------------------
+
+
+  // get first approximation of scaling factor
+  if (fixedscalefactor != -1.0)
+    lambda = fixedscalefactor;
+  else
+    lambda = 1.0;
+
+  Double_t lambdaold = lambda;
+  Double_t dlambda = 0.0;
+
+  // get first approximation of rotation angle
+  Double_t alfa = 0.0;
+  if (fixedrotationangle != -1.0)
+    alfa = fixedrotationangle / TMath::RadToDeg();
+
+  Double_t alfaold   = alfa;
+  // maximum allowed change of alfa in 1 iteration step (5 degrees)
+  Double_t dalfamax = 5.0 / TMath::RadToDeg();
+  Double_t dalfa = 0.0;
+
+  Double_t cosal = TMath::Cos(alfa);
+  Double_t sinal = TMath::Sin(alfa);
+
+  A[0][0] =  cosal;
+  A[0][1] = -sinal;
+  A[1][0] =  sinal;
+  A[1][1] =  cosal;
+
+
+  Double_t absdold2    = 10000.0;
+  Double_t fChangeofd2 = 10000.0;
+
+
+  TArrayD Aa[2];
+  Aa[0].Set(fNumStars);
+  Aa[1].Set(fNumStars);
+
+
+  Double_t sumEbminlamAa[2];
+
+  TArrayD Ebminlambracd[2];
+  Ebminlambracd[0].Set(fNumStars);
+  Ebminlambracd[1].Set(fNumStars);
+
+  TArrayD EAa[2];
+  EAa[0].Set(fNumStars);
+  EAa[1].Set(fNumStars);
+
+  // invert the error matrices
+  TArrayD  c[2][2];
+  c[0][0].Set(fNumStars);
+  c[0][1].Set(fNumStars);
+  c[1][0].Set(fNumStars);
+  c[1][1].Set(fNumStars);
+
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+    Double_t XX = e[0][0][ix]; 
+    Double_t XY = e[0][1][ix]; 
+    Double_t YY = e[1][1][ix]; 
+
+    // get inverse of error matrix
+    Double_t determ = XX*YY - XY*XY;
+    c[0][0][ix]  =  YY / determ; 
+    c[0][1][ix]  = -XY / determ; 
+    c[1][0][ix]  = -XY / determ;
+    c[1][1][ix]  =  XX / determ; 
+  }
+
+
+
+  // calculate sum of inverted error matrices
+  Double_t determsumc;
+  Double_t sumc[2][2];
+  sumc[0][0] = 0.0;
+  sumc[0][1] = 0.0;
+  sumc[1][0] = 0.0;
+  sumc[1][1] = 0.0;
+
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+       sumc[0][0]  += c[0][0][ix]; 
+       sumc[0][1]  += c[0][1][ix]; 
+       sumc[1][0]  += c[1][0][ix]; 
+       sumc[1][1]  += c[1][1][ix]; 
+  }
+  determsumc = sumc[0][0]*sumc[1][1] - sumc[0][1]*sumc[1][0];
+
+  // calculate inverse of sum of inverted error matrices
+  Double_t sumcinv[2][2];
+  sumcinv[0][0]  =  sumc[1][1] / determsumc; 
+  sumcinv[0][1]  = -sumc[0][1] / determsumc; 
+  sumcinv[1][0]  = -sumc[1][0] / determsumc;
+  sumcinv[1][1]  =  sumc[0][0] / determsumc; 
+
+  //*fLog << "sumcinv = " << sumcinv[0][0] << ",  " << sumcinv[0][1] 
+  //      << ",  " << sumcinv[1][1] << endl;
+
+
+  // minimize chi2 by iteration *****   start   **********************
+  
+  // stop iteration when change in |d|*|d| is less than 'told2'
+  //                and  change in alfa    is less than 'toldalfa'
+  //                and  change in lambda  is less than 'toldlambda'
+  //                 or  chi2              is less than 'tolchi2'
+  Double_t told2 = 0.3*0.3;  // [mm*mm]; 1/100 of an inner pixel diameter
+  Double_t toldalfa = 0.01 / TMath::RadToDeg();  // 0.01 degrees 
+  Double_t toldlambda = 0.00006;   // uncertainty of 1 mm of distance 
+                                   // between camera and reflector
+  Double_t tolchi2 = 1.e-5;
+
+  Int_t fNumIterMax  = 100;
+  fNumIter           =   0;
+
+  for (Int_t i=0; i<fNumIterMax; i++)
+  {
+    fNumIter++;
+
+    // get next approximation of d  ------------------
+    for (Int_t ix=0; ix<fNumStars; ix++)
+    {
+        Aa[0][ix] = A[0][0] * a[0][ix]  +  A[0][1]*a[1][ix];
+        Aa[1][ix] = A[1][0] * a[0][ix]  +  A[1][1]*a[1][ix];
+
+        //*fLog << "ix, Aa = " << ix << " :  " << Aa[0][ix] << ",  "
+        //      << Aa[1][ix] << endl;
+    }
+
+    sumEbminlamAa[0] = 0.0;
+    sumEbminlamAa[1] = 0.0;
+
+    for (Int_t ix=0; ix<fNumStars; ix++)
+    {
+      sumEbminlamAa[0] +=   c[0][0][ix] * (b[0][ix] - lambda*Aa[0][ix])
+                          + c[0][1][ix] * (b[1][ix] - lambda*Aa[1][ix]);
+
+      sumEbminlamAa[1] +=   c[1][0][ix] * (b[0][ix] - lambda*Aa[0][ix])
+                          + c[1][1][ix] * (b[1][ix] - lambda*Aa[1][ix]);
+    }
+
+    //*fLog << "sumEbminlamAa = " << sumEbminlamAa[0] << ",  "
+    //      << sumEbminlamAa[1] << endl;
+
+    d[0] =      sumcinv[0][0] * sumEbminlamAa[0]
+	      + sumcinv[0][1] * sumEbminlamAa[1] ;
+
+    d[1] =      sumcinv[1][0] * sumEbminlamAa[0] 
+              + sumcinv[1][1] * sumEbminlamAa[1] ;
+
+    Double_t absdnew2 = d[0]*d[0] + d[1]*d[1]; 
+    fChangeofd2 = absdnew2 - absdold2;
+
+    //*fLog << "fNumIter : " << fNumIter 
+    //      << "; alfa, lambda, d[0], d[1], absdold2, absdnew2 = " << endl; 
+    //*fLog << alfa << ",  " << lambda << ",  " << d[0] << ",  " << d[1] 
+    //      << ",  " << absdold2 << ",  " << absdnew2 << endl;
+     
+
+    if ( fabs(fChangeofd2) < told2   &&  fabs(dalfa) < toldalfa  &&
+         fabs(dlambda)     < toldlambda ) 
+    {
+      //*fLog << "Iteration stopped because of small changes : fChangeofd2, dalfa, dlambda = "
+      //      << fChangeofd2 << ",  " << dalfa << ",  "  << dlambda << endl;
+      break;
+    }
+    absdold2 = absdnew2;
+
+    // get next approximation of matrix A  ----------------
+    if (fFixedRotationAngle == -1.0)
+    {     
+        for (Int_t ix=0; ix<fNumStars; ix++)
+        {
+          Ebminlambracd[0][ix] =   
+             c[0][0][ix] * ( b[0][ix] - lambda*Aa[0][ix] - d[0] )
+           + c[0][1][ix] * ( b[1][ix] - lambda*Aa[1][ix] - d[1] );
+
+          Ebminlambracd[1][ix] =   
+             c[1][0][ix] * ( b[0][ix] - lambda*Aa[0][ix] - d[0] )
+           + c[1][1][ix] * ( b[1][ix] - lambda*Aa[1][ix] - d[1] );
+
+          //*fLog << "ix, Ebminlambracd = " << ix << " :  "
+          //      << Ebminlambracd[0][ix] << ",  "
+          //      << Ebminlambracd[1][ix] << endl;
+        }
+
+        // stop iteration if fChi2 is small enough
+        fChi2 = 0.0;
+        for (Int_t ix=0; ix<fNumStars; ix++)
+        {
+          fChi2 +=  (b[0][ix]-lambda*Aa[0][ix]-d[0] ) * Ebminlambracd[0][ix]
+                  + (b[1][ix]-lambda*Aa[1][ix]-d[1] ) * Ebminlambracd[1][ix];
+        }
+        if ( fChi2 < tolchi2 ) 
+        {
+          //*fLog << "iteration stopped because of small fChi2 :  "
+          //      << fChi2 << endl;
+          break;
+        }
+
+
+        Double_t dchi2dA[2][2];
+        dchi2dA[0][0] = 0.0; 
+        dchi2dA[0][1] = 0.0;
+        dchi2dA[1][0] = 0.0;
+        dchi2dA[1][1] = 0.0;
+		
+        for (Int_t ix=0; ix<fNumStars; ix++)
+        {
+          dchi2dA[0][0] += Ebminlambracd[0][ix] * a[0][ix];
+          dchi2dA[0][1] += Ebminlambracd[0][ix] * a[1][ix];
+          dchi2dA[1][0] += Ebminlambracd[1][ix] * a[0][ix];
+          dchi2dA[1][1] += Ebminlambracd[1][ix] * a[1][ix];
+        }
+
+        //*fLog << "dchi2dA = " << dchi2dA[0][0] << ",  " << dchi2dA[0][1]
+        //      << ",  " << dchi2dA[1][0] << ",  " << dchi2dA[1][1] << endl;
+
+        // *********  1st derivative (d chi2) / (d alfa) ************
+        Double_t dchi2dalfa =   -2.0*lambda * 
+                              ( - sinal*(dchi2dA[0][0]+dchi2dA[1][1])
+                                + cosal*(dchi2dA[1][0]-dchi2dA[0][1]) );
+        
+
+        //Double_t dalfa1st = - fChi2 / dchi2dalfa;
+
+        //*fLog << "fChi2, dchi2dalfa = " << fChi2 << ",  " 
+        //      << dchi2dalfa << endl;
+        //*fLog << "proposed change of alfa using 1st derivative = " 
+        //      << dalfa1st << endl;
+
+        // *********  2nd derivative (d2 chi2) / (d alfa2) ******
+        Double_t term1 = 0.0;
+        Double_t term2 = 0.0;
+        Double_t term3 = 0.0;
+        Double_t term4 = 0.0;
+
+        for (Int_t ix=0; ix<fNumStars; ix++)
+        {
+          term1 += a[0][ix]*c[0][0][ix]*a[0][ix] + a[1][ix]*c[1][0][ix]*a[0][ix]
+	         + a[0][ix]*c[0][1][ix]*a[1][ix] + a[1][ix]*c[1][1][ix]*a[1][ix];
+
+          term2 += a[0][ix]*c[1][0][ix]*a[0][ix] - a[1][ix]*c[0][0][ix]*a[0][ix]
+	         + a[0][ix]*c[1][1][ix]*a[1][ix] - a[1][ix]*c[0][1][ix]*a[1][ix];
+
+          term3 = a[0][ix]*c[0][0][ix]*a[1][ix] + a[1][ix]*c[1][0][ix]*a[1][ix]
+	         - a[0][ix]*c[0][1][ix]*a[0][ix] - a[1][ix]*c[1][1][ix]*a[0][ix];
+
+          term4 += a[0][ix]*c[1][0][ix]*a[1][ix] - a[1][ix]*c[0][0][ix]*a[1][ix]
+	         - a[0][ix]*c[1][1][ix]*a[0][ix] + a[1][ix]*c[0][1][ix]*a[0][ix];
+        }
+
+        Double_t d2chi2dalfa2 = 
+                  - 2.0*lambda * ( - cosal*(dchi2dA[0][0]+dchi2dA[1][1])
+                                   - sinal*(dchi2dA[1][0]-dchi2dA[0][1]) )
+	   + 2.0*lambda*lambda * ( sinal*sinal * term1 - sinal*cosal * term2
+		  	         + sinal*cosal * term3 - cosal*cosal * term4);
+
+        // Gauss-Newton step
+        Double_t dalfa2nd = - dchi2dalfa / d2chi2dalfa2;
+
+        //*fLog << "proposed change of alfa using 2st derivative = " 
+        //    << dalfa2nd << endl;
+
+        //dalfa = dalfa1st;
+        dalfa = dalfa2nd;
+
+        // ******************************************
+
+
+        // restrict change of alfa
+        if ( fabs(dalfa) > dalfamax )
+        {
+          dalfa = TMath::Sign( dalfamax, dalfa ); 
+        }
+        alfa = alfaold + dalfa;
+
+        if ( alfa < -5.0/TMath::RadToDeg() )
+          alfa = -5.0/TMath::RadToDeg();
+        else if ( alfa > 5.0/TMath::RadToDeg() )
+          alfa = 5.0/TMath::RadToDeg();
+        
+        dalfa = alfa - alfaold;
+
+        alfaold = alfa;
+
+        sinal = TMath::Sin(alfa);
+        cosal = TMath::Cos(alfa);
+
+        A[0][0] =  cosal;
+        A[0][1] = -sinal;
+        A[1][0] =  sinal;
+        A[1][1] =  cosal;
+
+        //*fLog << "alfa-alfaold = " << dalfa << endl;
+        //*fLog << "new alfa = " << alfa << endl;
+    }
+
+
+    // get next approximation of lambda  ----------------
+    if (fFixedScaleFactor == -1.0)
+    {
+      for (Int_t ix=0; ix<fNumStars; ix++)
+      {
+        Aa[0][ix] = A[0][0]*a[0][ix] + A[0][1]*a[1][ix];
+        Aa[1][ix] = A[1][0]*a[0][ix] + A[1][1]*a[1][ix];
+
+        EAa[0][ix] =   
+           c[0][0][ix] * Aa[0][ix]  +  c[0][1][ix] * Aa[1][ix];
+        EAa[1][ix] =   
+           c[1][0][ix] * Aa[0][ix]  +  c[1][1][ix] * Aa[1][ix];
+
+        //*fLog << "ix, Aa = " << ix << " :  " << Aa[0][ix] << ",  "
+        //      << Aa[1][ix] << endl;
+
+        //*fLog << "ix, EAa = " << ix << " :  " << EAa[0][ix] << ",  "
+        //      << EAa[1][ix] << endl;
+      }
+
+      Double_t num   = 0.0;
+      Double_t denom = 0.0;
+      for (Int_t ix=0; ix<fNumStars; ix++)
+      {
+        num    +=   (b[0][ix]-d[0]) * EAa[0][ix] 
+                  + (b[1][ix]-d[1]) * EAa[1][ix];
+
+        denom  +=    Aa[0][ix]      * EAa[0][ix]  
+                  +  Aa[1][ix]      * EAa[1][ix]; 
+
+        //*fLog << "ix : b-d = " << ix << " :  " << b[0][ix]-d[0]
+	//      << ",  " << b[1][ix]-d[1] << endl;
+
+        //*fLog << "ix : Aa = " << ix << " :  " << Aa[0][ix]
+	//      << ",  " << Aa[1][ix] << endl;
+      }
+
+      lambda = num / denom;
+
+      if ( lambda < 0.9 )
+        lambda = 0.9;
+      else if ( lambda > 1.1 )
+        lambda = 1.1;
+
+      dlambda = lambda - lambdaold;
+      lambdaold = lambda;
+
+      //*fLog << "num, denom, lambda, dlambda = " << num
+      //      << ",  " << denom << ",  " << lambda << ",  "
+      //      << dlambda << endl;
+    }
+
+  }
+  //-------   end of iteration *****************************************
+
+  alfadeg = alfa * TMath::RadToDeg();
+
+  // calculate error matrix of d[2]
+  errd[0][0] = sumcinv[0][0];
+  errd[0][1] = sumcinv[0][1];
+  errd[1][0] = sumcinv[1][0];
+  errd[1][1] = sumcinv[1][1];
+
+  // evaluate quality of fit
+
+  // calculate chi2
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+    Ebminlambracd[0][ix] =   
+       c[0][0][ix] * ( b[0][ix] - lambda*Aa[0][ix] - d[0] )
+     + c[0][1][ix] * ( b[1][ix] - lambda*Aa[1][ix] - d[1] );
+
+    Ebminlambracd[1][ix] =   
+       c[1][0][ix] * (b[0][ix] - lambda*Aa[0][ix] - d[0] )
+     + c[1][1][ix] * (b[1][ix] - lambda*Aa[1][ix] - d[1] );
+  }
+
+  fChi2 = 0.0;
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+    fChi2 +=  (b[0][ix] - lambda*Aa[0][ix] - d[0] ) * Ebminlambracd[0][ix]
+            + (b[1][ix] - lambda*Aa[1][ix] - d[1] ) * Ebminlambracd[1][ix];
+  }
+
+  fChi2Prob = TMath::Prob(fChi2, fNdof);
+
+  //*fLog << "MTelAxisFromStars::FindSkyCamTrans :" << endl;
+  //*fLog <<  "   fNumStars, fChi2, fNdof, fChi2Prob, fNumIter, fChangeofd2, dalfa, dlambda = "
+  //      << fNumStars << ",  " << fChi2 << ",  " << fNdof << ",  " 
+  //      << fChi2Prob << ",  " 
+  //      << fNumIter << ",  "  << fChangeofd2 << ",  " << dalfa << ",  "
+  //      << dlambda << endl;
+  //*fLog << "    lambda, alfadeg, d[0], d[1] = " << lambda << ",  " 
+  //      << alfadeg   << ",  " << d[0] << ",  " << d[1] << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply transformation (lambda, A, d)
+//       to the        expected  positions (a[1], a[2]) 
+//       to obtain the estimated positions (b[1], b[2])
+//
+//       e[2][2]       is the error matrix of b[2]
+
+void MTelAxisFromStars::TransSkyCam(
+    Double_t &lambda, Double_t A[2][2], Double_t d[2], Double_t errd[2][2],
+    TArrayD a[2],     TArrayD b[2],     TArrayD e[2][2])   
+{
+  Int_t numpos = a[0].GetSize();
+  if (numpos <= 0)
+    return;
+
+  //*fLog << "MTelAxisFromStars::TransSkyCam; lambda, A, d = " 
+  //      << lambda << ";    " << A[0][0] << ",  " << A[0][1] << ",  "
+  //      << A[1][1] << ";   " << d[0] << ",  " << d[1] << endl;   
+
+  //*fLog << "MTelAxisFromStars::TransSkyCam; expected and estimated positions :"
+  //      << endl;
+
+  for (Int_t ix=0; ix<numpos; ix++)
+  {
+    //    *fLog << "MTelAxisFromStars;  ix = " << ix << endl;
+
+      b[0][ix] = lambda * (A[0][0]*a[0][ix] + A[0][1]*a[1][ix]) + d[0];
+      b[1][ix] = lambda * (A[1][0]*a[0][ix] + A[1][1]*a[1][ix]) + d[1];
+
+      e[0][0][ix] = errd[0][0];
+      e[0][1][ix] = errd[0][1];
+      e[1][0][ix] = errd[1][0];
+      e[1][1][ix] = errd[1][1];
+
+      // *fLog << "    ix, a[0], a[1], b[0], b[1], errxx, errxy, erryy = " 
+      //      << ix << " :   " 
+      //      << a[0][ix] << ",  " << a[1][ix] << ";    " 
+      //      << b[0][ix] << ",  " << b[1][ix] << ";    " 
+      //      << e[0][0][ix] << ",  " << e[0][1][ix] << ",  "
+      //      << e[1][1][ix] << endl;
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// SetPointingPosition
+//
+//    put the corrected pointing direction into MPointingPos[MPointingPos];
+//    this direction corresponds to the position (0,0) in the camera
+//
+
+Bool_t MTelAxisFromStars::SetPointingPosition(MStarCamTrans *fstarcamtrans,
+       MReportDrive *fdrive, MSkyCamTrans *ftrans, MPointingPos *fpointpos)
+{
+  Double_t decdrive = fdrive->GetDec();
+  Double_t hdrive   = fdrive->GetHa();
+  Double_t radrive  = fdrive->GetRa();
+
+  // this is the estimated position (with optical aberration) in the camera 
+  // corresponding to the direction in MReportDrive
+  Double_t Xpoint = (ftrans->GetShiftD())[0];    
+  Double_t Ypoint = (ftrans->GetShiftD())[1];    
+
+  // get the sky direction corresponding to the position (0,0) in the camera
+  Double_t decpoint = 0.0;
+  Double_t hpoint   = 0.0;
+  fstarcamtrans->CelCamToCel0(decdrive, hdrive, 
+                         Xpoint/fAberr, Ypoint/fAberr, decpoint, hpoint);
+  Double_t rapoint = radrive - hpoint + hdrive;
+  fpointpos->SetSkyPosition(rapoint, decpoint, hpoint);
+
+  // get the local direction corresponding to the position (0,0) in the camera
+  Double_t thetadrive = fdrive->GetNominalZd();
+  Double_t phidrive   = fdrive->GetNominalAz();
+  Double_t thetapoint = 0.0;
+  Double_t phipoint   = 0.0;
+  fstarcamtrans->LocCamToLoc0(thetadrive, phidrive, 
+               Xpoint/fAberr, Ypoint/fAberr, thetapoint, phipoint); 
+  fpointpos->SetLocalPosition(thetapoint, phipoint);
+  fpointpos->SetReadyToSave();
+
+  //*fLog << "SetPointingPosition : decdrive, hdrive, radrive Xpoint, Ypoint = "
+  //      << decdrive << ",  " << hdrive << ",  " << radrive << ",  "
+  //      << Xpoint << ",  " << Ypoint << endl;
+
+  //*fLog << "SetPointingPosition : thetadrive, phidrive, thetapoint, phipoint = "       
+  //      << thetadrive << ",  " << phidrive << ",  " << thetapoint << ",  "
+  //      << phipoint << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetSourcePosition
+//
+//    put the estimated position of the source in the camera into 
+//    MSrcPosCam[MSrcPosCam]
+//
+//    and the estimated local direction of the source into
+//    MSourcePos[MPointingPos]
+//
+
+Bool_t MTelAxisFromStars::SetSourcePosition(MStarCamTrans *fstarcamtrans,
+       MPointingPos *fpointpos, MPointingPos *fsourcepos, MSrcPosCam *fsrcpos)
+{
+  // get the corrected pointing direction
+  // corresponding to the position (0,0) in the camera
+  Double_t decpoint = fpointpos->GetDec();
+  Double_t hpoint   = fpointpos->GetHa();
+
+  // get the sky direction of the source
+  Double_t decsource = fsourcepos->GetDec();
+  Double_t hsource   = fsourcepos->GetHa();
+
+  // get the estimated position (Xsource, Ysource) of the source in the camera;
+  // this is a position for an ideal imaging, without optical aberration
+  Double_t Xsource = 0.0;
+  Double_t Ysource = 0.0;
+  fstarcamtrans->Cel0CelToCam(decpoint,  hpoint, 
+                              decsource, hsource, Xsource, Ysource);
+  fsrcpos->SetXY(Xsource*fAberr, Ysource*fAberr);
+  fsrcpos->SetReadyToSave();
+
+  // get the estimated local direction of the source
+  Double_t thetapoint = fpointpos->GetZd();
+  Double_t phipoint   = fpointpos->GetAz();
+  Double_t thetasource = 0.0;
+  Double_t phisource   = 0.0;
+  fstarcamtrans->Loc0CamToLoc(thetapoint, phipoint, 
+                              Xsource, Ysource, thetasource, phisource);
+  fsourcepos->SetLocalPosition(thetasource, phisource);
+  fsourcepos->SetReadyToSave();
+
+  //*fLog << "SetSourcePosition : decpoint, hpoint, decsource, hsource, Xsource, Ysource = "
+  //      << decpoint << ",  " << hpoint << ",  " << decsource << ",  "
+  //      << hsource  << ",  " << Xsource << ",  " << Ysource << endl;
+  //*fLog << "SetSourcePosition : thetapoint, phipoint, thetasource, phisource = "
+  //      << thetapoint << ",  " << phipoint << ",  " << thetasource << ",  "
+  //      << phisource << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MTelAxisFromStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MTelAxisFromStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MTelAxisFromStars.h	(revision 9772)
@@ -0,0 +1,88 @@
+#ifndef MARS_MTelAxisFromStars
+#define MARS_MTelAxisFromStars
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MTelAxisFromStars                                                       //
+//                                                                         //
+// Task to calculate the position (in the camera) 
+//      of certain sky directions (source position, tracking direction, ...) 
+//      from the positions (in the camera) of known stars 
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MReportDrive;
+class MPointingPos;
+class MSrcPosCam;
+class MStarCam;
+class MSkyCamTrans;
+class MStarCamTrans;
+
+class MTelAxisFromStars : public MTask
+{
+ private:
+
+    const MStarCam *fStarCam;          //!
+    const MStarCam *fSourceCam;        //!
+
+    MReportDrive        *fDrive;          //!
+    MPointingPos        *fPointPos;       //!
+    MPointingPos        *fSourcePos;      //!
+    MSrcPosCam          *fSrcPos;         //!
+    MSrcPosCam          *fPntPos;         //!
+    MSkyCamTrans        *fSkyCamTrans;    //!
+    MStarCamTrans       *fStarCamTrans;   //!
+
+    Double_t fFixedScaleFactor;           //!
+    Double_t fFixedRotationAngle;         //! [degrees]
+    Double_t fAberr;                      //! optical aberration factor
+
+    Int_t fInputType;                     //! type of input
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+ public:
+
+    MTelAxisFromStars(const char *name=NULL, const char *title=NULL);
+    ~MTelAxisFromStars();
+
+    void FixScaleFactorAt(Double_t lambda = 1.0);
+    void FixRotationAngleAt(Double_t alfa = 0.0);  // alfa in [degrees]
+
+    void SetOpticalAberr(Double_t aberr);   
+    void SetInputType(Int_t type = 1);
+
+    Bool_t FindSkyCamTrans(TArrayD[2],      TArrayD[2],  TArrayD[2][2], 
+		  	   Double_t &,      Double_t &,  Double_t &,
+	       Double_t &, Double_t[2][2] , Double_t[2], Double_t[2][2],
+               Int_t &,    Int_t &,         Double_t &,  Double_t &); 
+
+    void TransSkyCam(Double_t &,  Double_t[2][2], Double_t[2], Double_t[2][2],
+                     TArrayD[2],  TArrayD[2],     TArrayD[2][2]);   
+
+    Bool_t SetPointingPosition(MStarCamTrans *fstarcamtrans,
+       MReportDrive *fdrive, MSkyCamTrans *ftrans, MPointingPos *fpointpos);
+    Bool_t SetSourcePosition(MStarCamTrans *fstarcamtrans,
+       MPointingPos *fpointpos, MPointingPos *fsourcepos, MSrcPosCam *fsrcpos);
+
+    ClassDef(MTelAxisFromStars, 0) // Task to calculate the source position from star positions
+};
+
+#endif
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/MVPObject.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MVPObject.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MVPObject.cc	(revision 9772)
@@ -0,0 +1,280 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner <mailto:magicsoft@rwagner.de> 10/2002
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MVPObject                                                              //
+//                                                                         //
+//  Class used by the visibility plotter to convert RA/Dec to Alt/Az       //
+//                                                                         //
+//  This class represents an object and is used with the Visibility        //
+//  macro. It must be provided with its RA/Dec coordinates and an          //
+//  object name (cf. MVPObject::SetRA, MVPObject::SetDec, and              //
+//  MVPObject::SetName). Alternatively, you can require the MVPObject      //
+//  to be a solar system object like the Sun, Mars or the Moon             //
+//  (cf. MVPObject::SetObject).                                            //
+//                                                                         //
+//  MVPObject is ready to be used in a Mars Eventloop. You must provide    //
+//  an Observatory Location as well as a time at which the position        //
+//  of the MVPObject is to be calculated. MVPObject::PreProcess            //
+//  checks the existence of the required containers and also makes sure    //
+//  all necessary setters have been called. MVPObject::Process             //
+//  then calculates the Alt/Az position of the object, as well as the      //
+//  Zenith angle and the object diameter (Solar system objects).           //
+//                                                                         //
+//  The astronomical algorithms used are taken from SLALIB 2.4-8.          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MVPObject.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+
+#include "../../slalib/slalib.h"
+
+ClassImp(MVPObject);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MVPObject::MVPObject(const char *name, const char *title) : fDiameter(0), fCalcEc(kFALSE), fUT1(52000), fBody(10), fGotRA(kFALSE), fGotDec(kFALSE), fGotName(kFALSE)
+{
+  fName  = name  ? name  : "MVPObject";
+  fTitle = title ? title : "Task to calculate Alt, Az of a given object";
+  
+  fgDegToRad=2*TMath::Pi()/360;
+  fgHrsToRad=2*TMath::Pi()/24;  
+}
+
+MVPObject::~MVPObject()
+{
+  //Destructor: nothing special yet.
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if necessary containers exist in the parameter list already.
+//  We need an ObservatoryLocation and a MVPTime object.
+//
+Bool_t MVPObject::PreProcess(MParList *pList)
+{
+  fObservatory = (MObservatoryLocation*)pList->FindObject("MObservatoryLocation");
+  if (!fObservatory)
+    {
+      *fLog << dbginf << "MObservatoryLocation not found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fTime = (MVPTime*)pList->FindObject("MVPTime");
+  if (!fTime)
+    {
+      *fLog << dbginf << "MVPTime not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  if (!fGotRA || !fGotDec || !fGotName)
+    {
+      *fLog << dbginf << "Object information is not complete." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets coordinates from object name. Instead of providing RA, Dec and Name
+// of an object, you may also just provide the object name in the from
+// HHMMsDDT, where RA is given in hours and minutes and Declination is
+// given by degrees DD and tenths of degrees T. "s" may be "+" or
+// "-", eg. "1959+650"
+//
+void MVPObject::SetObjectByName(const char *object)
+{
+  fObjectName=object;
+  fGotName=kTRUE;
+  
+  Int_t ra, dec;
+  sscanf(object, "%d%d", &ra, &dec);
+
+  fRA  = fgHrsToRad * (0.01*ra + (r%100)/60.);
+  fDec = fgDegToRad * 0.1 * dec;
+
+  fGotRA=kTRUE;
+  fGotDec=kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Sets RA position of object. Position is to be provided in hours, minutes,
+// seconds, and microseconds (if needed)
+//
+void MVPObject::SetRA(Int_t rh, Int_t rm, Int_t rs, Int_t ru)
+{
+  // Rect is a timelike value...
+  fRA = fgHrsToRad*((Double_t)rh + (Double_t)rm/60 + (Double_t)rs/(60*60) + (Double_t)ru/(36000));
+  fBody = 10;
+  fGotRA = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets Dec position of object. Position is to be provided in degrees, 
+// minutes, seconds, and microseconds (if needed)
+//
+void MVPObject::SetDec(Int_t dh, Int_t dm, Int_t ds, Int_t du)
+{
+  // Dec is an anglelike value
+  fDec = fgDegToRad*((Double_t)dh + (Double_t)dm/60 + (Double_t)ds/(60*60) + (Double_t)du/(36000));
+  fBody = 10;
+  fGotDec = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Alternatively to providing RA, Dec and Name of an object, you may provide 
+// a solar system object (which has no fixed RA, Dec, by the way!) with
+// MVPObject::SetObject.
+// -
+// UInt_t body | Object      Sun and Moon will be objects needed at most,
+//           0 | Sun         presumably.
+//           1 | Mercury
+//           2 | Venus
+//           3 | Moon
+//           4 | Mars
+//           5 | Jupiter
+//           6 | Saturn
+//           7 | Uranus
+//           8 | Neptune
+//           9 | Pluto
+//
+Bool_t MVPObject::SetObject(UInt_t body)
+{
+  if (body > 9) 
+    {
+      *fLog << dbginf << "No solar system object associated with value " << body <<"! Ignoring request." << endl;
+      return kFALSE;
+    }
+  else  // We are working on a solar system body.
+    {                   
+      switch (body) 
+       	{
+	case 1: fObjectName="Mercury"; break;
+       	case 2: fObjectName="Venus"; break;
+       	case 3: fObjectName="Moon"; break;
+       	case 4: fObjectName="Mars"; break;
+       	case 5: fObjectName="Jupiter"; break;
+       	case 6: fObjectName="Saturn"; break;
+       	case 7: fObjectName="Uranus"; break;
+       	case 8: fObjectName="Neptune"; break;
+       	case 9: fObjectName="Pluto"; break;
+       	default: fObjectName="Sun"; 
+       	}            
+    }
+  
+  fBody = body; 
+  fGotRA = fGotDec = fGotName = kTRUE;
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Given RA, Dec or a solar system object as well as an observatory
+// location and a MVPTime, MVPObject::Process() calculates
+// Alt, Az, ZA and (in the case of solar system objects) the apparent
+// object diameter
+//
+Bool_t MVPObject::Process()
+{
+  Double_t diameter = 0.0;
+
+  if (fBody < 10) // We are working on a solar system body.
+    {      
+      slaRdplan(fTime->GetMJD(), fBody, fObservatory->GetLongitudeRad(), fObservatory->GetLatitudeRad(), &fRA, &fDec, &diameter);         
+    }
+  
+  if (fCalcEc) slaEqecl(fRA, fDec, fTime->GetMJD(), &fEcLong, &fEcLat);
+  
+  Float_t azimuth;
+  Float_t elevation;
+  
+  Float_t hourAngle = (Float_t)UT1ToGMST(fTime->GetMJD()) - fRA;
+
+  //  cout << "ha: " << hourAngle  << " ra: " << fRA << " dec " << fDec <<endl;
+
+  slaE2h (hourAngle, (Float_t)fDec, (Float_t)fObservatory->GetLatitudeRad(), &azimuth, &elevation);
+   
+  fZA  = slaZd(hourAngle, fDec, fObservatory->GetLatitudeRad());
+  fAlt = (Double_t)elevation;
+  fAz  = (Double_t)azimuth; 
+  fDiameter = diameter;
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns distance of given object to this object in degrees
+//
+Double_t MVPObject::GetDistance(MVPObject* object)
+{
+  return slaSep(fRA, fDec, object->GetRARad(), object->GetDecRad())/fgDegToRad;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns distance of given object to this object in radians
+//
+Double_t MVPObject::GetDistanceRad(MVPObject* object)
+{
+  return slaSep(fRA, fDec, object->GetRARad(), object->GetDecRad());
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Converts UT1 (given as MJD) to Greenwich mean star time in radians
+//
+Double_t MVPObject::UT1ToGMST(Double_t ut1)
+{
+  return slaGmst(ut1);
+}
+
+void MVPObject::Print(Option_t *) const
+{
+  *fLog << all;
+  *fLog << "Position of "<< fObjectName << 
+    ": Dec " << fDec/fgDegToRad << " deg, " << 
+    "RA  " << fRA/fgHrsToRad << " hrs" << endl;
+  if (fCalcEc) *fLog << "Ecliptic Long: " << fEcLong/fgDegToRad << " deg, " << 
+		  "Ecliptic Lat: " << fEcLat/fgDegToRad << " deg, " << endl; 
+}
+
+
Index: /tags/Mars-V0.9/mtemp/MVPObject.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MVPObject.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MVPObject.h	(revision 9772)
@@ -0,0 +1,100 @@
+#ifndef MARS_MVPObject
+#define MARS_MVPObject
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MObservatoryLocation
+#include "MObservatoryLocation.h"
+#endif
+
+#ifndef MARS_MVPTime
+#include "MVPTime.h"
+#endif
+
+class MVPObject : public MTask
+{
+private:
+  MObservatoryLocation *fObservatory;  
+
+  Double_t fRA;
+  Double_t fDec;
+  Double_t fAlt;
+  Double_t fAz;
+  Double_t fZA;
+  Double_t fDiameter;
+  Double_t fEcLat;
+  Double_t fEcLong;
+  Bool_t fCalcEc;
+
+  Double_t fUT1;
+  MVPTime *fTime;
+ 
+  char* fObjectName;
+  UInt_t fBody;
+
+  Double_t UT1ToGMST(Double_t ut1);
+ 
+  Double_t fgDegToRad;
+  Double_t fgHrsToRad;
+
+  Bool_t fGotRA;
+  Bool_t fGotDec;
+  Bool_t fGotName;
+
+public:
+
+  MVPObject(const char *name=NULL, const char *title=NULL);
+  ~MVPObject();
+
+  Bool_t PreProcess(MParList *pList);
+  Bool_t Process();
+
+  void SetObservatory(MObservatoryLocation *observatory);
+
+  void SetRA(Double_t rad) { fRA = rad; fBody = 10; fGotRA = kTRUE; }
+  void SetDec(Double_t rad) { fDec = rad; fBody = 10; fGotDec = kTRUE; }
+
+  void SetRA(Int_t rh, Int_t rm, Int_t rs, Int_t ru = 0);
+  void SetDec(Int_t dh, Int_t dm, Int_t ds, Int_t du = 0);
+
+  void SetCalcEc(Bool_t calcEc) { fCalcEc = calcEc; }
+
+  void SetObjectName(char* name) { fObjectName = name; fGotName = kTRUE; } 
+  void SetObjectByName(char* object);
+
+  Bool_t SetObject(UInt_t body);
+
+  Double_t GetRA() { return fRA/fgHrsToRad; }
+  Double_t GetDec() { return fDec/fgDegToRad; }
+
+  Double_t GetRARad()  { return fRA; }
+  Double_t GetDecRad() { return fDec; }
+
+  Double_t GetZA() { return fZA; }
+  Double_t GetAltitude() { return fAlt; }
+  Double_t GetAzimut() { return fAz; }
+  Double_t GetDiameter() { return fDiameter; }
+
+  Double_t GetEcLat() { return fEcLat; }
+  Double_t GetEcLong() { return fEcLong; }
+
+  Double_t GetZADeg() { return fZA/fgDegToRad; }
+  Double_t GetAltitudeDeg() { return fAlt/fgDegToRad; }
+  Double_t GetAzimutDeg() { return fAz/fgDegToRad; }
+
+  Double_t GetDistance(MVPObject* object);
+  Double_t GetDistanceRad(MVPObject* object);
+
+  char* GetObjectName() { return fObjectName; }
+  
+  void Print(Option_t *) const;
+
+  Double_t MJDStartOfYear(UInt_t year);
+
+  ClassDef(MVPObject, 1)
+}; 
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/MVPPlotter.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MVPPlotter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MVPPlotter.cc	(revision 9772)
@@ -0,0 +1,587 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner <magicdev@rwagner.de> 12/2002
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MVPPlotter                                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MVPPlotter.h"
+
+#include <stream.h>
+
+#include "TCanvas.h"
+#include "TH1.h"
+#include "TH2.h"
+#include "TPaveText.h"
+#include "TPaveLabel.h"
+#include "TGraph.h"
+#include "TString.h"
+#include "TStyle.h"
+
+#include "MParList.h"
+#include "MVPTime.h"
+
+ClassImp(MVPPlotter);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MVPPlotter::MVPPlotter(const char *name, const char *title) : fUseSun(kTRUE), fUseMoon(kTRUE), fUsePlanets(kTRUE), fAstronomicalDarkness(-18.0)
+{
+  //  fName  = name  ? name  : "MVPPlotter";
+  //  fTitle = title ? title : "Generates visibility histograms and information";
+
+  fgSecPerDay = 86400;
+  fgMJD010170 = 40586; // 01-01-70 is JD 40586
+  fgDegToRad = 2*TMath::Pi()/360;
+
+}
+
+MVPPlotter::~MVPPlotter()
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes objects if allocated.
+//
+{
+  if (fUseSun) delete fSun;
+  if (fUseMoon) delete fMoon;
+  if (fUsePlanets) {
+    delete fVenus;
+    delete fMars;
+    delete fJupiter;
+    delete fSaturn;
+  }
+}
+   
+void MVPPlotter::SetupObjects()
+// --------------------------------------------------------------------------
+//
+// Create instances for Sun, Moon, Planets if requested.
+//
+{
+  
+  fTime = new MVPTime();
+  fPlist.AddToList(fTime);
+  fPlist.AddToList(fObs);
+
+  if (fObject==NULL) {
+    cout << "You didn't specify an object!" << endl;  
+  }
+
+  fObject->PreProcess(&fPlist);
+  cout << "Processing object " << fObject->GetObjectName() << endl;
+
+  if (fUseSun) {
+    fSun = new MVPObject();
+    fSun->SetObject(0); // Sun
+    fSun->PreProcess(&fPlist);
+    fSun->SetCalcEc(kTRUE);
+  }
+
+  if (fUseMoon) {
+    fMoon = new MVPObject();
+    fMoon->SetObject(3); // Moon
+    fMoon->PreProcess(&fPlist);
+    fMoon->SetCalcEc(kTRUE);
+  }
+
+  if (fUsePlanets) {
+    fVenus = new MVPObject();
+    fVenus->SetObject(2); 
+    fVenus->PreProcess(&fPlist);
+    fVenus->SetCalcEc(kTRUE);
+
+    fMars = new MVPObject();
+    fMars->SetObject(4); 
+    fMars->PreProcess(&fPlist);
+    fMars->SetCalcEc(kTRUE);
+
+    fJupiter = new MVPObject();
+    fJupiter->SetObject(5); 
+    fJupiter->PreProcess(&fPlist);
+    fJupiter->SetCalcEc(kTRUE);
+
+    fSaturn = new MVPObject();
+    fSaturn->SetObject(6); 
+    fSaturn->PreProcess(&fPlist);
+    fSaturn->SetCalcEc(kTRUE);
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// Plots for a single object and a whole year are generated.
+// 
+// Currently we do the following:
+// - Create a plot MJD vs UTC for one year
+// - Create a plot maxObjHeight vs Week for one year
+// - Create visibility tables for one year (ZA, hours)
+//
+Bool_t MVPPlotter::CalcYear(Int_t year, UInt_t daySlices=96)
+{
+  SetupObjects();
+  
+  UInt_t startday = (UInt_t)fTime->MJDStartOfYear(year);
+  UInt_t stopday  = (UInt_t)fTime->MJDStartOfYear(year+1)-1;
+
+  cout << "Processing period MJD "<< startday << " to MJD "<< stopday  << endl;
+
+  ULong_t startdayROOT = fgSecPerDay * (startday-fgMJD010170);
+  ULong_t stopdayROOT  = fgSecPerDay * (stopday-fgMJD010170);
+      
+  // 2D Plot ZA vs MJD and UTC
+  fMjdUtcYear = new TH2D("fMjdUtcYear", "Visibility of object",
+			  stopday-startday+1,startdayROOT,stopdayROOT, 
+			  daySlices+1,-450,fgSecPerDay+450);
+
+  // Observability hours per day MJD
+  fMjdObsHours = new TH1D("fMjdObsHours", "Observation hours per day",
+			  stopday-startday+1,startdayROOT,stopdayROOT);
+
+  if (fUseMoon) {
+    // 2D Plot ZA of moon vs MJD and UTC
+    fMjdUtcYearMoon =new TH2D("fMjdUtcYearMoon", "Moon ZA",
+     			 stopday-startday+1,startdayROOT,stopdayROOT,
+     			 daySlices+1,-450,fgSecPerDay+450);
+
+    // Moon phase vs MJD
+    fMjdMoonPhase =new TH1D("fMjdMoonPhase", "Moon phase",
+     			 stopday-startday+1,startdayROOT,stopdayROOT);
+    // Moon distance of object vs MJD
+    fMjdMoonDistance =new TH1D("fMjdMoonDistance", "Moon distance",
+     			 stopday-startday+1,startdayROOT,stopdayROOT);
+    // Moon intensity at object vs MJD
+    fMjdMoonIntensity =new TH1D("fMjdMoonIntensity", "Moon intensity at locus of object",
+     			 stopday-startday+1,startdayROOT,stopdayROOT);
+
+  }
+
+  if (fUsePlanets) {
+    // Distance of closest planet vs MJD
+    fMjdPlanetDistance =new TH1D("fMjdPlanetDistance", "PlanetDistance",
+     			 stopday-startday+1,startdayROOT,stopdayROOT);
+  }
+
+   
+  // Array which holds total visibility time for whole year [0] and
+  // each month [1]..[12]
+  Float_t visibility[13][18];
+  memset(visibility, 0, 13*18*sizeof(Float_t));
+  /*
+  for (int m=0;m<13;m++)
+    for (int z=0;z<18;z++)
+      visibility[m][z]=0;
+  */
+  int fday, ftime;
+  Double_t phase=0;	
+  Double_t obsHours;
+
+  for (UInt_t day=startday; day<stopday+1; day++) {     
+    Double_t todaysPhase=0;
+    Double_t moonIntensity;
+    obsHours=0;
+    for (UInt_t i=0; i<daySlices; i++)
+      {	 
+	// Rearrange filling of bins such that a "day" doesn't start at midnight,
+	// but rather at noon. This results in plots in which a "day" covers
+	// a whole night.
+	if (i>=(daySlices/2)) {
+	  fday=day;
+	  ftime=i-(daySlices/2);
+	} else {
+	  fday=day-1;
+	  ftime=i+(daySlices/2);
+	}
+
+	// Objects access fTime via parameter list...
+	fTime->SetMJD(day,(Double_t)i/daySlices);
+
+	if (fUseSun)  fSun->Process();
+	if (fUseMoon) fMoon->Process();
+
+	if (fUseSun && fUseMoon) {
+
+	  // Calculate moon phase...
+	  phase = fSun->GetEcLong() - fMoon->GetEcLong();	 
+	  phase = TMath::Pi()-(acos(cos(phase)*cos(fMoon->GetEcLat())));
+	  phase = phase*180/TMath::Pi();
+	  todaysPhase+=phase;
+      
+	}
+	
+	// If sun is not up (or we should not use sun information...)
+	if (fSun->GetAltitudeDeg() < fAstronomicalDarkness) {
+	  // Calculate Position of object:	  
+	  fObject->Process();		 	 	    
+
+	  // Calculate moon brightness at locus of object
+	  // now this is gonna be fun...
+
+	  /* Evaluates predicted LUNAR part of sky brightness, in
+	   * V magnitudes per square arcsecond,
+	   */
+
+	  moonIntensity = LunSkyBright(phase/180, fObject->GetDistance(fMoon),
+						fMoon->GetAltitudeDeg(), fObject->GetAltitudeDeg());
+	  fMjdMoonIntensity->Fill(fgSecPerDay*(fday-fgMJD010170),moonIntensity);
+
+	
+
+	  // If moon is not up (or we should not use moon information...)
+	  if (!fUseMoon || fMoon->GetAltitudeDeg()<=0 || moonIntensity<60) {
+	    // Fill MJD-UTC histogram
+	    fMjdUtcYear->Fill(fgSecPerDay*(fday-fgMJD010170),fgSecPerDay*ftime/daySlices,fObject->GetAltitudeDeg());
+	  }
+	  
+	  // Sum up visibility time (only if moon not visible or moon
+	  // info shouldn't be used at all)
+	  if ((!fUseMoon)||(fMoon->GetAltitudeDeg()<=0)||(moonIntensity<60)) {
+	    // Calculate 
+	    for (int z=0;z<18;z++) {
+	      if (fObject->GetAltitudeDeg()>(z*5)) {
+		visibility[0][z]+=(Double_t)(60*24/daySlices);
+		visibility[(Int_t)fTime->GetMonth()][z]+=(Double_t)(60*24/daySlices);
+	      }
+	    }	//for
+	  
+	    if ((fObject->GetAltitudeDeg())>40) {
+	      fMjdObsHours->Fill(fgSecPerDay*(fday-fgMJD010170),(Double_t)(24/(Double_t)daySlices));
+	    }
+
+	  }
+
+	 
+	} //fi sun 	 	  
+
+	// Optional: Fill histo with moon-up times...
+	// if (fMoon->GetAltitudeDeg() >0) 
+	// fMjdUtcYearMoon->Fill(fgSecPerDay*(day-fgMJD010170),fgSecPerDay*i/daySlices,phase);	
+	// fMoon->Process();
+	// Double_t phase;	
+	// phase = fSun->GetEcLong() - moon->GetEcLong();	 
+	// phase = TMath::Pi()-(acos(cos(phase)*cos(moon->GetEcLat())));
+	// cout << "Phase: " << phase*180/TMath::Pi() << endl;
+	
+      } //for daySlices
+
+    // Distance of Venus to object
+
+    if (fUsePlanets) {
+      fVenus->Process();
+      fMars->Process();
+      fJupiter->Process();
+      fSaturn->Process();
+
+      Double_t distance = fVenus->GetDistance(fObject);
+      distance = TMath::Min(distance, fMars->GetDistance(fObject));
+      distance = TMath::Min(distance, fJupiter->GetDistance(fObject));
+      distance = TMath::Min(distance, fSaturn->GetDistance(fObject));
+
+      fMjdPlanetDistance->Fill(fgSecPerDay*(fday-fgMJD010170),distance);      
+    }
+
+    fMjdMoonPhase->Fill(fgSecPerDay*(fday-fgMJD010170),todaysPhase/i);
+    fMjdMoonDistance->Fill(fgSecPerDay*(fday-fgMJD010170),fMoon->GetDistance(fObject));
+
+    
+  } //for days
+
+    
+  // Here we print the tables with visibilities...
+  cout << "Visibility time [hours]: " << endl;
+   
+  for (int z=1;z<17;z++) {
+    if (visibility[0][z]==0) break;
+    printf("Alt>%2d|%6d|",z*5,(Int_t)(visibility[0][z]/60));      
+    for (int m=1;m<13;m++) {
+      printf("%5d ",(Int_t)(visibility[m][z]/60));	
+    }
+    printf("\n");
+  }
+  
+  int vistimestart=0;
+  int vistimeend=0;  
+  for (int m=1; m<13; m++) {
+    int n = (m==1 ? 12 : m-1);
+    if (visibility[m][8]/60>20 && visibility[n][8]/60<=20) {
+      vistimestart=m; // we're on the rising slope
+    }
+  }
+  
+  for (int m=1; m<13; m++) {
+    int n = (m==1 ? 12 : m-1);
+    if (visibility[m][8]/60<20 && visibility[n][8]/60>=20) {
+      vistimeend=n; // we're on the falling slope
+    }
+  }
+  
+  cout << "Visibility (Alt>40) during months: " << vistimestart << "-" << vistimeend << " approx " << visibility[0][8]/60 << "hrs" <<endl;
+
+
+  /*!!!!!!!!!!!!!!!!!!!!!!!*/gROOT->Reset();
+
+  TCanvas *cMjdUtcYear = new TCanvas("cMjdUtcYear", "Object Visibility MjdUtcYear", 1100,500);
+  cMjdUtcYear->cd(0);
+
+  gStyle->SetPalette(1);
+  //  gStyle->SetOptStat(0);
+  gStyle->SetOptFit(0);
+  gStyle->SetFillStyle(0);
+  gStyle->SetFillColor(10);
+  gStyle->SetCanvasColor(10);
+  gStyle->SetDrawBorder(0);
+  gStyle->SetPadColor(10);
+  gStyle->SetPadBorderSize(0);
+  gStyle->SetPadLeftMargin(0.12);
+  gStyle->SetTitleYOffset(1.2);
+  gStyle->SetTitleXOffset(1.2);
+  
+  gStyle->SetPadLeftMargin(0.01);
+  gStyle->SetPadRightMargin(0.1);
+  gStyle->SetPadTopMargin(0.03);
+  gStyle->SetPadBottomMargin(0.12);
+  
+  fMjdUtcYear->SetTitle(fObject->GetObjectName());
+  fMjdUtcYear->GetXaxis()->SetTimeDisplay(1);
+  fMjdUtcYear->GetXaxis()->SetTimeFormat("%b %y");
+  fMjdUtcYear->GetYaxis()->SetTimeDisplay(1);
+  fMjdUtcYear->GetYaxis()->SetTimeFormat("%Hh");
+  gStyle->SetTimeOffset(43200);
+  fMjdUtcYear->GetYaxis()->SetLabelOffset(0.01);
+  fMjdUtcYear->SetMinimum(0);
+  fMjdUtcYear->SetMaximum(90);
+  
+  fMjdUtcYear->GetYaxis()->SetTitle("Hour");
+  fMjdUtcYear->GetXaxis()->SetTitle("Day of year");
+  fMjdUtcYear->GetZaxis()->SetTitle("Altitude");
+  fMjdUtcYear->Draw("SURF2BB9Z");
+  gPad->SetPhi(0);
+  gPad->SetTheta(90);
+  gPad->Modified();
+  
+  TPaveText *pt = new TPaveText(-0.74,-0.35,-0.58,0.52,"");  
+  char ptLine[80];
+  pt->AddText("Visibility time [hrs]:");
+  pt->SetTextAlign(13);
+  pt->SetFillStyle(0);
+  pt->SetBorderSize(0);
+  pt->SetTextFont(42);
+  for (int j=1;j<17;j++) {
+    sprintf (ptLine, "Alt>%i: %i", j*5, (Int_t)visibility[0][j]/60);
+    pt->AddText(ptLine);
+    if (visibility[0][j]==0) break;
+  }
+  pt->Draw();
+
+
+  if (fUseMoon) {
+    TCanvas *cMjdMoon = new TCanvas("cMjdMoon", "the Moon phase", 600,600);
+    gStyle->SetOptTitle(1);
+    cMjdMoon->Divide(1,3);
+    cMjdMoon->cd(1);
+    fMjdMoonPhase->Draw();
+    cMjdMoon->cd(2);
+    fMjdMoonDistance->Draw();
+    cMjdMoon->cd(3);
+    fMjdMoonIntensity->Draw();
+  }
+
+  TCanvas *cObsHours = new TCanvas("cObsHours", "ObsHours per day", 600,400);
+  fMjdObsHours->Draw();
+
+
+
+  if (fUsePlanets) {
+    TCanvas *cMjdPlanets = new TCanvas("cMjdPlanets", "the distance to planets", 600,200);
+    cMjdPlanets->cd(0);
+    fMjdPlanetDistance->Draw();
+  }
+
+    
+  // next histogram
+  Float_t objectHeight[55];
+  Float_t simpleCounter[55];
+  Int_t weekCounter=0;
+  
+  simpleCounter[weekCounter]=0;
+  objectHeight[weekCounter]=0;
+  weekCounter++;
+  
+  const Int_t startday2 = fTime->MJDStartOfYear(year);
+  const Int_t stopday2  = fTime->MJDStartOfYear(year+1)-1;
+  
+    for (int day=startday2; day<stopday2+1; day+=7)
+    {
+        simpleCounter[weekCounter]=weekCounter-1;
+        objectHeight[weekCounter]=0;
+        for (int i=0; i<daySlices; i++)
+        {
+            if (i>=48)
+            {
+                fday=day;
+                ftime=i-48;
+            }
+            else
+            {
+                fday=day-1;
+                ftime=i+48;
+            }
+
+            fTime->SetMJD(day,(Double_t)i/daySlices);
+            fObject->Process();
+            fSun->Process();
+
+            if (fSun->GetAltitudeDeg() < -25.0)
+            {
+                if (objectHeight[weekCounter]<(fObject->GetAltitudeDeg()))
+                    objectHeight[weekCounter]=fObject->GetAltitudeDeg();
+            }
+
+        } //i
+        weekCounter++;
+    } //day
+    simpleCounter[weekCounter]=weekCounter-2;
+    objectHeight[weekCounter]=0;
+    weekCounter++;
+
+    TString months[12] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
+
+    TCanvas *c2 = new TCanvas("c2", "Object Visibility",600,100);
+ 
+    //  gStyle->SetOptTitle(0);
+    //   gStyle->SetPadLeftMargin(0.000001);
+    //   gStyle->SetPadRightMargin(0.000001);
+    //   gStyle->SetPadTopMargin(0.001);
+    //   gStyle->SetPadBottomMargin(0.000001);
+    gPad->SetGrid();
+
+    c2->SetGrid();
+    TGraph *tg=new TGraph(weekCounter,simpleCounter,objectHeight);
+
+    tg->SetMinimum(1);
+    tg->SetMaximum(90);
+
+    Double_t maxza = abs(fObject->GetDec()-fObs->GetLatitude());
+
+    if (maxza > 90) maxza=90;
+    if (maxza < 0) maxza=00;
+
+    cout << "MaxZA:    ";
+    cout << maxza << endl;
+
+    if (maxza < 30) { //colors=green to yellow
+        maxza *= 9/30;
+        maxza += 80;
+
+    } else { //colors=yellow to red
+        maxza -= 30;
+        maxza *= 11/60;
+        maxza += 89;
+    }
+
+  tg->SetFillColor((Int_t)maxza);
+  tg->SetLineColor((Int_t)maxza);
+  tg->SetLineWidth((Int_t)maxza);
+  tg->Draw("AF");
+  
+  tg->GetXaxis()->SetLimits(0,52);
+  tg->GetXaxis()->SetTickLength(0.1);
+  tg->GetXaxis()->SetNdivisions(0);
+  tg->GetYaxis()->SetNdivisions(202);
+  
+  TPaveLabel* l= new TPaveLabel(2,46,35,88, fObject->GetObjectName());
+  l->SetBorderSize(0);
+  l->SetFillStyle(0);
+  l->SetTextAlign(12);
+  l->Draw();
+  
+  if ((vistimestart<13)&&(vistimeend>0)) {
+    TString label=months[vistimestart-1]+"-"+months[vistimeend-1];
+    TPaveLabel* l2= new TPaveLabel(35,46,50,88, label);
+    l2->SetBorderSize(0);
+    l2->SetFillStyle(0);
+    l2->SetTextAlign(32);
+    l2->Draw();
+    
+  }
+  
+  c2->Modified();
+  c2->Update();
+  
+  return kTRUE;
+}
+
+Double_t MVPPlotter::LunSkyBright(Double_t moon_phase,Double_t rho,Double_t altmoon,Double_t alt)
+{
+/* Evaluates predicted LUNAR part of sky brightness, in
+ * V magnitudes per square arcsecond, following K. Krisciunas
+ * and B. E. Schaeffer (1991) PASP 103, 1033.
+ *
+ * moon_phase  = Phase of the Moon, between 0. (no moon) and 1. (full moon),
+ * rho (deg)   = separation of moon and object,
+ * altmoon (deg) = altitude of moon above horizon,
+ * alt (deg)   = altitude of object above horizon
+ */
+
+    double kzen=1.;
+
+    double rho_rad = rho*fgDegToRad;
+    double alpha = 180.*(1. - moon_phase);
+    double Zmoon = (90. - altmoon)*fgDegToRad;
+    double Z = (90. - alt)*fgDegToRad;
+
+    double istar = -0.4*(3.84 + 0.026*fabs(alpha) + 4.0e-9*pow(alpha,4.)); /*eqn 20*/
+    istar =  pow(10.,istar);
+    if(fabs(alpha) < 7.)   /* crude accounting for opposition effect */
+	istar *= 1.35 - 0.05 * fabs(istar);
+	/* 35 per cent brighter at full, effect tapering linearly to
+	   zero at 7 degrees away from full. mentioned peripherally in
+	   Krisciunas and Scheafer, p. 1035. */
+    double fofrho = 229087. * (1.06 + cos(rho_rad)*cos(rho_rad));
+    if(fabs(rho) > 10.)
+        fofrho+=pow(10.,(6.15 - rho/40.));            /* eqn 21 */
+    else if (fabs(rho) > 0.25)
+        fofrho+=6.2e7 / (rho*rho);   /* eqn 19 */
+    else fofrho = fofrho+9.9e8;  /*for 1/4 degree -- radius of moon! */
+
+    double Xzm = sqrt(1.0 - 0.96*sin(Zmoon)*sin(Zmoon));
+
+    if(Xzm != 0.) Xzm = 1./Xzm;
+    else Xzm = 10000.;
+
+    double Xo = sqrt(1.0 - 0.96*sin(Z)*sin(Z));
+    if(Xo != 0.) Xo = 1./Xo;
+    else Xo = 10000.;
+
+    double Bmoon = fofrho * istar * pow(10.,(-0.4*kzen*Xzm))
+        * (1. - pow(10.,(-0.4*kzen*Xo)));   /* nanoLamberts */
+    //    cout << " Bmoon=" << Bmoon;
+    if(Bmoon > 0.001)
+      return(Bmoon); 
+    else return(99999.);
+}
+
+
Index: /tags/Mars-V0.9/mtemp/MVPPlotter.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MVPPlotter.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MVPPlotter.h	(revision 9772)
@@ -0,0 +1,77 @@
+#ifndef MARS_MVPPlotter
+#define MARS_MVPPlotter
+
+#ifndef MARS_MTaskList
+#include "MTaskList.h"
+#endif
+
+#ifndef MARS_MVPObject
+#include "MVPObject.h"
+#endif
+
+#ifndef MARS_MVPTime
+#include "MVPTime.h"
+#endif
+
+#ifndef MARS_MObservatoryLocation
+#include "MObservatoryLocation.h"
+#endif
+
+class TH1D;
+class TH2D;
+class TCanvas;
+
+class MVPPlotter
+{
+private:
+
+  MVPTime   *fTime;
+  MObservatoryLocation *fObs;
+
+  MParList fPlist;
+  MTaskList fTlist;
+
+  Bool_t fUseSun;
+  Bool_t fUseMoon;
+  Bool_t fUsePlanets;
+
+  Double_t fAstronomicalDarkness;
+
+  Int_t fgSecPerDay;
+  Int_t fgMJD010170; // 01-01-70 is JD 40586
+  Double_t fgDegToRad;
+
+  TH2D *fMjdUtcYear;
+  TH2D *fMjdUtcYearMoon;
+  TH1D *fMjdMoonPhase;
+  TH1D *fMjdMoonDistance;
+  TH1D *fMjdPlanetDistance;
+  TH1D *fMjdMoonIntensity;
+  TH1D *fMjdObsHours;
+
+  MVPObject *fObject;
+  MVPObject *fSun;
+  MVPObject *fMoon;
+  MVPObject *fVenus;
+  MVPObject *fMars;
+  MVPObject *fJupiter;
+  MVPObject *fSaturn;
+
+  void SetupObjects();
+
+public:
+    MVPPlotter(const char *name=NULL, const char *title=NULL);
+    ~MVPPlotter();
+
+    void SetObject(MVPObject *o) { fObject=o; }
+    void SetObservatory(MObservatoryLocation *l) { fObs=l; }
+    void SetAstronomicalDarkness(Double_t d) { fAstronomicalDarkness=d; }
+
+    Double_t LunSkyBright(Double_t moon_phase,Double_t rho,Double_t altmoon,Double_t alt);
+    Bool_t CalcYear(Int_t year, UInt_t daySlices);
+
+    ClassDef(MVPPlotter, 2) // Visibility Plotter: The Plotter Routine itself
+}; 
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/MVPTime.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/MVPTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MVPTime.cc	(revision 9772)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner  11/2002 <mailto:magicsoft@rwagner.de>
+!
+!   Copyright: MAGIC Software Development, 2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MVPTime                                                                 //
+//                                                                         //
+// Time Container used by the visibility plotter storing times in MJD      //
+//                                                                         //
+// This is a simple time container for the Visibility Plotter. It takes    //
+// "normal" or MJD-formatted time, converts it to MJD and can return MJD.  //
+//                                                                         //
+// The astronomical algorithms used are taken from SLALIB 2.4-8.           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MVPTime.h"
+
+#include <slalib.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MVPTime);
+
+MVPTime::MVPTime(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MVPTime";
+    fTitle = title ? title : "Storage container for time";      
+}
+
+MVPTime::~MVPTime()
+{
+  // do nothing special.
+}
+
+void MVPTime::SetTime(UInt_t yr, UInt_t mo, UInt_t dy, UInt_t hr, UInt_t mi, UInt_t se)
+{
+  fUT1 = CalendarToUT1(yr, mo, dy, hr, mi, se);  
+  fYear = yr;
+  fMonth = mo;
+  fDay = dy;
+}
+
+void MVPTime::SetMJD(Double_t mjd, Double_t fracMjd)
+{
+  fUT1 = mjd + fracMjd;
+  Double_t fd;
+  Int_t status;
+  slaDjcl (mjd, &fYear, &fMonth, &fDay, &fd, &status);  
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Double_t MVPTime::CalendarToUT1(UInt_t yr, UInt_t mo, UInt_t dy, UInt_t hr, UInt_t mi, UInt_t se)
+{
+  int status;
+  Double_t mjd;
+  slaCldj(yr, mo, dy, &mjd, &status); 
+  switch (status)
+    {
+    case 1:
+      *fLog << "CalendarToMJD Warn: bad year" << endl;
+      break;
+    case 2:
+      *fLog << "CalendarToMJD Warn: bad month" << endl;
+      break;
+    case 3:
+      *fLog << "CalendarToMJD Warn: bad day" << endl;
+      break;
+    }
+  
+  mjd += ((Double_t)hr/24) + ((Double_t)mi/(24*60)) + ((Double_t)se/(24*60*60));
+  return mjd;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Double_t MVPTime::MJDStartOfYear(UInt_t year)
+{
+  int status;
+  Double_t mjd;
+  slaCldj(year, 1, 1, &mjd, &status); 
+  switch (status)
+    {
+    case 1:
+      *fLog << "CalendarToMJD Warn: bad year" << endl;
+      break;
+    case 2:
+      *fLog << "CalendarToMJD Warn: bad month" << endl;
+      break;
+    case 3:
+      *fLog << "CalendarToMJD Warn: bad day" << endl;
+      break;
+    }
+  return mjd;
+}
+
+void MVPTime::Print(Option_t *) const
+{
+  *fLog << all;
+  *fLog << "Time (MJD) is: " << fUT1 << endl;
+}
Index: /tags/Mars-V0.9/mtemp/MVPTime.h
===================================================================
--- /tags/Mars-V0.9/mtemp/MVPTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/MVPTime.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MVPTime
+#define MARS_MVPTime
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MVPTime : public MParContainer
+{
+private:
+  Double_t fUT1;
+  Int_t fYear;
+  Int_t fMonth;
+  Int_t fDay;
+  Double_t MVPTime::CalendarToUT1(UInt_t yr, UInt_t mo, UInt_t dy, UInt_t hr, UInt_t mi, UInt_t se);
+ 
+public:
+  MVPTime(const char *name=NULL, const char *title=NULL);
+  ~MVPTime();
+
+  void SetTime(UInt_t yr, UInt_t mo, UInt_t dy, UInt_t hr, UInt_t mi, UInt_t se);
+  void SetMJD(Double_t mjd, Double_t fracMjd = 0);
+  inline Double_t GetMJD() { return fUT1; }
+
+  void Print(Option_t *) const;
+
+  Double_t MJDStartOfYear(UInt_t year);
+  Double_t GetYear() { return fYear; }
+  Double_t GetMonth() { return fMonth; }
+  Double_t GetDay() { return fDay; }
+  
+  ClassDef(MVPTime, 1)
+
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/Makefile	(revision 9772)
@@ -0,0 +1,55 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+CINT     = Temp
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../mbase \
+	   -I../mjobs \
+	   -I../mpedestal \
+	   -I../mbadpixels \
+	   -I../mfileio \
+           -I../mraw \
+           -I../manalysis \
+	   -I../mgui \
+	   -I../mgeom \
+	   -I../msignal \
+	   -I../mcalib \
+	   -I../mfilter \
+	   -I../mhbase \
+	   -I../mimage \
+	   -I../mpointing \
+	   -I../mcamera \
+	   -I../mhist \
+	   -I../mmc \
+	   -I../mreport \
+	   -I../mastro \
+           -I../mstarcam
+
+SRCFILES = \
+        MFindStars.cc \
+        MTelAxisFromStars.cc \
+        MHTelAxisFromStars.cc \
+        MSkyCamTrans.cc \
+	MStarLocalCam.cc \
+        MSourceDirections.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mtemp/PaddingExample.C
===================================================================
--- /tags/Mars-V0.9/mtemp/PaddingExample.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/PaddingExample.C	(revision 9772)
@@ -0,0 +1,673 @@
+
+void InitBinnings(MParList *plist)
+{
+        gLog << "InitBinnings" << endl;
+
+        //--------------------------------------------
+        MBinning *binse = new MBinning("BinningE");
+        //binse->SetEdgesLog(30, 1.0e2, 1.0e5);
+
+	//This is Daniel's binning in energy:
+        binse->SetEdgesLog(14, 296.296, 86497.6);
+        plist->AddToList(binse);
+
+        //--------------------------------------------
+
+        MBinning *binssize = new MBinning("BinningSize");
+        binssize->SetEdgesLog(50, 10, 1.0e5);
+        plist->AddToList(binssize);
+
+        MBinning *binsdistc = new MBinning("BinningDist");
+        binsdistc->SetEdges(50, 0, 1.4);
+        plist->AddToList(binsdistc);
+
+        MBinning *binswidth = new MBinning("BinningWidth");
+        binswidth->SetEdges(50, 0, 1.0);
+        plist->AddToList(binswidth);
+
+        MBinning *binslength = new MBinning("BinningLength");
+        binslength->SetEdges(50, 0, 1.0);
+        plist->AddToList(binslength);
+
+        MBinning *binsalpha = new MBinning("BinningAlpha");
+        binsalpha->SetEdges(100, -100, 100);
+        plist->AddToList(binsalpha);
+
+        MBinning *binsasym = new MBinning("BinningAsym");
+        binsasym->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsasym);
+
+        MBinning *binsm3l = new MBinning("BinningM3Long");
+        binsm3l->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3l);
+
+        MBinning *binsm3t = new MBinning("BinningM3Trans");
+        binsm3t->SetEdges(50, -1.5, 1.5);
+        plist->AddToList(binsm3t);
+
+   
+        //.....
+        MBinning *binsb = new MBinning("BinningSigmabar");
+        binsb->SetEdges( 100,  0.0,  50.0);
+        plist->AddToList(binsb);
+
+        MBinning *binssig = new MBinning("BinningSigma");
+        binssig->SetEdges( 100,  0.0, 120.0);
+        plist->AddToList(binssig);
+
+        MBinning *binth = new MBinning("BinningTheta");
+        // this is Daniel's binning in theta
+        //Double_t yedge[8] = 
+        //  {9.41, 16.22, 22.68, 28.64, 34.03, 38.84, 43.08, 44.99};
+        // this is our binning
+        //Double_t yedge[9] = 
+        //               {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        //TArrayD yed;
+        //yed.Set(9,yedge);
+        //binth->SetEdges(yed);
+        
+        //binth->SetEdges(     1, 0.0, 90.0);
+        binth->SetEdgesCos( 10, 0.0, 90.0);
+        plist->AddToList(binth);
+
+        //MBinning *bincosth = new MBinning("BinningCosTheta");
+        //Double_t yedge[9] = 
+        //               {0.0, 17.5, 23.5, 29.5, 35.5, 42., 50., 60., 70.};
+        //Double_t zedge[9]; 
+        //for (Int_t i=0; i<9; i++)
+	//{
+	//zedge[8-i] = cos(yedge[i]/kRad2Deg);
+	//}
+        //TArrayD zed;
+        //zed.Set(9,zedge);
+        //bincosth->SetEdges(zed);
+        //plist->AddToList(bincosth);
+
+        MBinning *binsdiff = new MBinning("BinningDiffsigma2");
+        binsdiff->SetEdges(100, -500.0, 1500.0);
+        plist->AddToList(binsdiff);
+
+        // robert ----------------------------------------------
+        MBinning *binsalphaf = new MBinning("BinningAlphaFlux");
+        binsalphaf->SetEdges(100, -100, 100);
+        plist->AddToList(binsalphaf);
+
+	MBinning *binsdifftime = new MBinning("BinningTimeDiff");
+	binsdifftime->SetEdges(50, 0, 10);
+	plist->AddToList(binsdifftime);
+
+	MBinning *binstime = new MBinning("BinningTime");
+	binstime->SetEdges(50, 44500, 61000);
+	plist->AddToList(binstime);
+}
+
+
+void DeleteBinnings(MParList *plist)
+{
+        gLog << "DeleteBinnings" << endl;
+
+        TObject *bin;
+
+        //--------------------------------------------
+        bin = plist->FindObject("BinningE");
+        if (bin) delete bin;
+
+        //--------------------------------------------
+
+        bin = plist->FindObject("BinningSize");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDist");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningWidth");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningLength");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAlpha");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningAsym");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Long");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningM3Trans");
+        if (bin) delete bin;
+
+        //.....
+        bin = plist->FindObject("BinningSigmabar");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningSigma");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningCosTheta");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningDiffsigma2");
+        if (bin) delete bin;
+
+
+        // robert ----------------------------------------------
+        bin = plist->FindObject("BinningAlphaFlux");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTimeDiff");
+        if (bin) delete bin;
+
+        bin = plist->FindObject("BinningTime");
+        if (bin) delete bin;
+}
+
+
+
+//************************************************************************
+void PaddingExample()
+{
+      gLog.SetNoColors();
+
+      if (gRandom)
+        delete gRandom;
+      gRandom = new TRandom3(0);
+
+      //-----------------------------------------------
+      TString tag = "080000";
+
+      const char *offfile  = "*OffCrab11*";
+
+      const char *onfile  = "*CrabNebula*";
+
+      const char *mcfile = "calibrated_MCdata2";
+
+      //-----------------------------------------------
+
+      // path for input for Mars
+
+     if (tag == "080000")  
+     { 
+       TString inPathON  = "/.magic/magicserv01/MAGIC/calibrateddata/2004_09_21/";
+       TString inPathOFF = "/.magic/magicserv01/MAGIC/calibrateddata/2004_09_21/";
+       TString inPathMC  = "/.magic/data21a/mase/Mars/Mars041103/DataCalibUV/";
+
+     }
+
+      // path for output from Mars
+     TString outPath = "/.magic/data21a/wittek/PaddedData/";
+//     outPath += tag;
+//     outPath += "/";
+
+      //-----------------------------------------------
+
+
+    //************************************************************************
+
+    // Job A : 
+    //  - produce MHSigmaTheta plots for ON, OFF and MC data
+    //  - write out (or read in) these MHSigmaTheta plots
+    //  - read ON (or OFF or MC) data
+    //  - pad the events; 
+    //  - write root file for ON (or OFF or MC) data (ON1.root, ...);
+
+    Bool_t JobA    = kTRUE;  
+    Bool_t GPadON  = kTRUE;    // \  generate Pad histograms 
+    Bool_t GPadOFF = kFALSE;    //  | and write them onto disk
+    Bool_t GPadMC  = kFALSE;    // /
+    Bool_t Merge   = kFALSE;   // read the Pad histograms, merge them
+                               // and write them onto disk
+    Bool_t Wout    = kFALSE;   // \  read in merged padding histograms and
+                               //  | write out root file of padded data
+                               // /  (ON1.root, OFF1.root or MC1.root) 
+    TString typeInput("ON");
+    //TString typeInput("OFF");
+    //TString typeInput("MC");
+
+
+
+
+    //************************************************************************
+
+    
+  //---------------------------------------------------------------------
+  // Job A
+  //=========
+
+    //  - produce the histograms "sigmabar versus Theta", etc. 
+    //    for ON, OFF and MC data (to be used for the padding)
+    //
+    //  - write root file of padded ON (OFF, MC) events (ON1.root, ...) 
+    //    (after the standard cuts, before the g/h separation)
+
+
+ if (JobA)
+ {
+    gLog << "=====================================================" << endl;
+    gLog << "Macro ONOFFAnalysis : Start of Job A" << endl;
+    gLog << "" << endl;
+    gLog << "Macro ONOFFAnalysis : JobA, GPadON, GPadOFF, GPadMC, Merge, Wout = " 
+         << (JobA    ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadON  ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadOFF ? "kTRUE" : "kFALSE")  << ",  " 
+         << (GPadMC  ? "kTRUE" : "kFALSE")  << ",  " 
+         << (Merge   ? "kTRUE" : "kFALSE")  << ",  " 
+         << (Wout    ? "kTRUE" : "kFALSE")  << endl;
+    
+    //--------------------------------------------------
+
+
+    // name of MPedPhotCam container
+    TString fNamePedPhotCam("MPedPhotCam");
+
+
+    //************************************************************
+    // generate histograms to be used in the padding
+    // 
+    // read ON, OFF and MC data files
+    // generate (or read in) the padding histograms for ON, OFF and MC data
+    //
+
+    MPad pad;
+    pad.SetName("MPad");
+
+    //--------------------------------------------------
+    // names of ON and OFF files to be read
+    // for generating the histograms to be used in the padding 
+    TString fileON  = inPathON;
+    fileON += onfile;
+    fileON += ".root";
+
+    TString fileOFF = inPathOFF;
+    fileOFF += offfile;
+    fileOFF += ".root";
+
+    TString fileMC = inPathMC;
+    fileMC += mcfile;
+    fileMC += ".root";
+
+    //--------------------------------------------------
+    // name of files to contain the paddding histograms of ON, OFF and MC data
+      TString NamePadON(outPath);
+      NamePadON += "PadON";
+      NamePadON += ".root";
+
+      TString NamePadOFF(outPath);
+      NamePadOFF += "PadOFF";
+      NamePadOFF += ".root";
+
+      TString NamePadMC(outPath);
+      NamePadMC += "PadMC";
+      NamePadMC += ".root";
+
+    // name of file to conatin the merged histograms for the padding
+    TString outNameSigTh = outPath;
+    outNameSigTh += "SigmaTheta";
+    outNameSigTh += ".root";
+
+    //--------------------------------------------------
+
+    if (GPadON || GPadOFF || GPadMC)
+    {
+      // generate the padding histograms
+      gLog << "=====================================================" << endl;
+      gLog << "Start generating the padding histograms" << endl;
+
+
+    gLog << "fileON, fileOFF, fileMC = " << fileON << ",  " 
+         << fileOFF << ",  " << fileMC   << endl;
+
+
+
+    //--------------------------------------------------
+      MMakePadHistograms makepad;
+      makepad.SetMaxEvents(-1);
+      makepad.SetNamePedPhotCam(fNamePedPhotCam);
+      makepad.SetPedestalLevel(2.0);
+      makepad.SetUseInterpolation(kTRUE);
+      makepad.SetProcessPedestal(kTRUE);
+      makepad.SetProcessTime(kFALSE);
+
+      //-----------------------------------------
+      // ON events
+
+      if (GPadON)
+      {
+        makepad.SetDataType("ON");
+        makepad.SetNameInputFile(fileON);
+        makepad.SetNameOutputFile(NamePadON);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+      // OFF events
+
+      if (GPadOFF)
+      {
+        makepad.SetDataType("OFF");
+        makepad.SetNameInputFile(fileOFF);
+        makepad.SetNameOutputFile(NamePadOFF);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+      // MC events
+
+      if (GPadMC)
+      {
+        makepad.SetDataType("MC");
+        makepad.SetNameInputFile(fileMC);
+        makepad.SetNameOutputFile(NamePadMC);
+        makepad.MakeHistograms();
+      }
+
+      //-----------------------------------------
+
+
+      gLog << "" << endl;
+      gLog << "End of generating the padding histograms" << endl;
+      gLog << "=====================================================" << endl;
+    }
+
+    //************************************************************
+
+    if (Merge)
+    {
+      gLog << "=====================================================" << endl;
+      gLog << "Start of merging the padding histograms" << endl;
+      gLog << "" << endl;
+
+      //pad.MergeONOFFMC(NamePadON, NamePadOFF, NamePadMC, outNameSigTh);
+      //pad.MergeONOFFMC(NamePadON, "", NamePadMC, outNameSigTh);
+      pad.MergeONOFFMC(NamePadON, NamePadOFF, "", outNameSigTh);
+      //pad.MergeONOFFMC("", NamePadOFF, NamePadMC, outNameSigTh);
+
+      gLog << "" << endl;
+      gLog << "End of merging the padding histograms" << endl;
+      gLog << "=====================================================" << endl;
+    }
+    // end of Merge
+
+
+
+    //************************************************************
+
+  if (Wout)
+  {
+    // read the target padding histograms ---------------------------
+    pad.ReadPaddingDist(outNameSigTh);
+
+
+    gLog << "=====================================================" << endl;
+    gLog << "Start the padding" << endl;
+
+    //--------------------------------------------------
+    // type of data to be padded 
+    gLog << "typeInput = " << typeInput << endl;
+
+    //-------------------------------------------
+    // name of input root file
+    if (typeInput == "ON")
+      TString filenamein(fileON);
+    else if (typeInput == "OFF")
+      TString filenamein(fileOFF);
+    else if (typeInput == "MC")
+      TString filenamein(fileMC);
+    gLog << "data to be padded : " << filenamein << endl;
+
+    // name of output root file
+    TString outNameImage = outPath;
+    outNameImage += "Hillas";
+    outNameImage += typeInput;
+    outNameImage += "1.root";
+    gLog << "padded data to be written onto : " << outNameImage << endl;
+
+    //-----------------------------------------------------------
+    pad.SetDataType(typeInput);
+    pad.SetNamePedPhotCam(fNamePedPhotCam);
+
+    MTaskList tliston;
+    MParList pliston;
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadReports read;
+    read.AddTree("Drive");
+    read.AddTree("Events","MTime.",kTRUE);
+    static_cast<MRead&>(read).AddFile(filenamein);
+
+    read.AddToBranchList("MReportDrive.*");
+    read.AddToBranchList("MRawEvtHeader.*");
+
+
+//    MReadMarsFile read("Events", filenamein);
+//    read.DisableAutoScheme();
+
+    MGeomApply        apply;
+
+    // a way to find out whether one is dealing with MC :
+    //MFDataMember f1("MRawRunHeader.fRunType", '>', 255.5);  // MC
+    //f1.SetName("Select MC");
+    //MFDataMember f2("MRawRunHeader.fRunType", '<', 255.5);  // data
+    //f2.SetName("Select Data");
+
+
+
+      MBadPixelsCalc badcalc;
+      badcalc.SetNamePedPhotContainer(fNamePedPhotCam);
+      badcalc.SetPedestalLevel(2.0);
+      badcalc.SetName("BadCalc");
+
+      MBadPixelsTreat badtreat;
+      badtreat.SetNamePedPhotCam(fNamePedPhotCam);
+      badtreat.SetUseInterpolation(kTRUE);
+      badtreat.SetProcessPedestal(kTRUE);
+      badtreat.SetProcessTimes(kFALSE);
+      badtreat.SetName("BadTreat");
+
+      MPointingPosCalc mpointcalc;
+
+      MFSelBasic selbasic;
+      selbasic.SetCuts(20.0, 0.0, 25.8419, 90.0, 126.0);
+
+      MContinue contbasic(&selbasic);
+      contbasic.SetName("SelBasic");
+
+      MHBadPixels bad("BadPixels");
+      bad.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillbad("BadPixels[MHBadPixels]", "MBadPixelsCam");
+      fillbad.SetName("FillBad");
+
+      MHSigmaTheta sigth("SigmaTheta");
+      sigth.SetNamePedPhotCam(fNamePedPhotCam);
+      MFillH fillsigtheta ("SigmaTheta[MHSigmaTheta]", "");
+      fillsigtheta.SetName("FillSigTheta");    
+
+
+    MImgCleanStd    clean(3.0, 2.5);
+    clean.SetMethod(MImgCleanStd::kScaled);
+    clean.SetCleanRings(1); 
+    clean.SetName("Clean");
+    clean.SetNamePedPhotCam(fNamePedPhotCam);
+
+    // calculation of  image parameters ---------------------
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImagePar(fImgParName);
+
+    MHillasSrcCalc hsrccalc("MSrcPosCam", fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+    MFillH hfill1("MHHillas",    fHilName);
+    hfill1.SetName("HHillas");
+
+    MFillH hfill2("MHStarMap",   fHilName);
+    hfill2.SetName("HStarMap");
+
+    MFillH hfill3("MHHillasExt",   fHilNameSrc);
+    hfill3.SetName("HHillasExt");
+
+    MFillH hfill4("MHHillasSrc",   fHilNameSrc);
+    hfill4.SetName("HHillasSrc");
+
+    MFillH hfill5("MHNewImagePar", fImgParName);
+    hfill5.SetName("HNewImagePar");
+    // --------------------------------------------------
+
+    MFSelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+    selstandard.SetCuts(500, 2, 20, 0.0, 5.0, 0.001, 0.001);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+      
+    /*
+      MWriteRootFile write(outNameImage);
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      //write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+      //write.AddContainer("MTime",         "Events");
+      write.AddContainer("MPointingPos", "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+      write.AddContainer("MTime",         "Events");
+      write.AddContainer("MImagePar",     "Events");
+
+      write.AddContainer("MReportDrive",  "Drive", kFALSE);
+      write.AddContainer("MTimeDrive",    "Drive", kFALSE);  //new
+    */
+
+    //*****************************
+    // entries in MParList
+    
+    pliston.AddToList(&tliston);
+    InitBinnings(&pliston);
+    pliston.AddToList(&bad);
+    pliston.AddToList(&sigth);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+    //tliston.AddToList(&f1);
+    //tliston.AddToList(&f2);
+    tliston.AddToList(&apply);
+    tliston.AddToList(&mpointcalc, "Events");
+
+//    tliston.AddToList(&badcalc); done in callisto
+//    tliston.AddToList(&badtreat); done in callisto
+
+    tliston.AddToList(&contbasic, "Events");
+    //tliston.AddToList(&pad, "Events"); 
+
+    
+    tliston.AddToList(&fillbad, "Events");
+    tliston.AddToList(&fillsigtheta, "Events");
+    tliston.AddToList(&clean, "Events");
+
+    tliston.AddToList(&hcalc, "Events");
+    tliston.AddToList(&hsrccalc, "Events");
+
+    tliston.AddToList(&hfill1, "Events");
+    tliston.AddToList(&hfill2, "Events");
+    tliston.AddToList(&hfill3, "Events");
+    tliston.AddToList(&hfill4, "Events");
+    tliston.AddToList(&hfill5, "Events");
+
+    tliston.AddToList(&contstandard, "Events");
+    //tliston.AddToList(&write);
+    
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //  evtloop.Write();
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 2000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // Display the histograms
+
+    pliston.FindObject("SigmaTheta", "MHSigmaTheta")->DrawClone();
+    pliston.FindObject("BadPixels",  "MHBadPixels")->DrawClone();
+
+    pliston.FindObject("MHHillas")->DrawClone();
+    pliston.FindObject("MHHillasExt")->DrawClone();
+    pliston.FindObject("MHHillasSrc")->DrawClone();
+    pliston.FindObject("MHNewImagePar")->DrawClone();
+    pliston.FindObject("MHStarMap")->DrawClone();
+
+    //DeleteBinnings(&pliston);
+
+      gLog << "End of padding" << endl;
+      gLog << "=====================================================" << endl;
+  }  
+
+
+    gLog << "Macro ONOFFAnalysis : End of Job A" << endl;
+    gLog << "===================================================" << endl;
+ }
+
+}
+
+
+
+
+
+
+
+   
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/TempIncl.h
===================================================================
--- /tags/Mars-V0.9/mtemp/TempIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/TempIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtemp/TempLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtemp/TempLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/TempLinkDef.h	(revision 9772)
@@ -0,0 +1,14 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MFindStars+;
+#pragma link C++ class MTelAxisFromStars+;
+#pragma link C++ class MHTelAxisFromStars+;
+#pragma link C++ class MSkyCamTrans+;
+#pragma link C++ class MStarLocalCam+;
+#pragma link C++ class MSourceDirections+;
+
+#endif
Index: /tags/Mars-V0.9/mtemp/findTelAxisFromStars.C
===================================================================
--- /tags/Mars-V0.9/mtemp/findTelAxisFromStars.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/findTelAxisFromStars.C	(revision 9772)
@@ -0,0 +1,413 @@
+void ReadSetup(TString fname, MAstroCamera &cam)
+{
+    MMcConfigRunHeader *config=0;
+    MGeomCam           *geom=0;
+
+    TFile file(fname);
+    TTree *tree = (TTree*)file.Get("RunHeaders");
+    tree->SetBranchAddress("MMcConfigRunHeader", &config);
+    if (tree->GetBranch("MGeomCam"))
+        tree->SetBranchAddress("MGeomCam", &geom);
+    tree->GetEntry(0);
+
+    cam.SetMirrors(*config->GetMirrors());
+    cam.SetGeom(*geom);
+}
+
+//--------------------------------------------------------------------------
+//
+//  findTelAxisFromStars
+//
+//  macro to 
+//    - determine the positions of stars in the camera from the DC currents 
+//    - and to find the expected position of the source in the camera
+//
+
+void findTelAxisFromStars(const TString filename="20040422_23213_D_Mrk421_E.root", const TString directory="/.magic/magicserv01/MAGIC/rootdata/2004_04_22/", const UInt_t numEvents = 0)
+{
+  gLog.SetNoColors();
+
+  //-------------------------------------------------------------------
+  // book some histograms which are to be filled in the event loop
+  //
+
+  TH2D *aberr = new TH2D("OpticalAberr", "Opt_Aberr",
+                         100, 0.0, 650.0,  100, 0.0, 650.0);
+  aberr->SetXTitle("Ideal distance from center [mm]");
+  aberr->SetYTitle("Expected distance from center [mm]");
+
+  TProfile *reldiff = new TProfile("RelativeDiff", "Rel_Diff",
+				   100, 0.0, 650.0, -0.2, 0.2, "S");
+  reldiff->SetXTitle("Ideal distance from center [mm]");
+  reldiff->SetYTitle("(R - R0)/R0");
+
+  //-------------------------------------------------------------------
+
+
+  MParList  plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MStarCam      starcam;
+
+  //$$$$$$$$$$$$$$$$ ww
+  MObservatory  obs;
+  MStarCam      sourcecam;
+  sourcecam.SetName("MSourceCam");
+
+  MHTelAxisFromStars htelaxis;
+
+  plist.AddToList(&obs);
+  plist.AddToList(&htelaxis);
+  //$$$$$$$$$$$$$$$$ ww
+
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&starcam);
+  plist.AddToList(&sourcecam);
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddTree("Drive"); // If you do not include Drive info, the MFindStars class
+                         // will not use the star catalog method
+  read.AddFile(directory+filename); // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+  read.AddToBranchList("MReportDrive.*");
+
+  MGeomApply geomapl;
+  //  TString continuoslightfile =   
+  //   "/data/MAGIC/Period016/rootdata/2004_04_16/20040416_22368_P_Off3c279-2CL100_E.root";
+
+  TString continuoslightfile =
+"/.magic/magicserv01/MAGIC/rootdata/2004_04_16/20040416_22368_P_Off3c279-2CL100_E.root";
+
+
+  Float_t mindc = 0.9; //[uA]
+
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 5;
+  const Short_t x[numblind] = { 47, 124, 470, 475, 571};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 2.5;
+  UInt_t integratedevents = 1;
+
+  // We need the MAGIC mirror geometry from a MC header:
+  //TString geometryfile = "/mcdata/standard/camera/NSB_013/Gamma/Gamma_zbin9_90_7_1480to1489_w0.root";
+  TString geometryfile =
+"/.magic/magicserv01/MAGIC/mcdata/standard/camera/NSB_013/Gamma/Gamma_zbin9_90_7_1480to1489_w0.root";
+
+
+
+
+  // We need the Bright Star Catalog:
+  //TString catalogfile = "/home/rwagner/bsc5.dat";
+  TString catalogfile = "mtemp/mmpi/macros/bsc5.dat";
+
+  //$$$$$$$$$$$$$$$$ ww
+  MSourceDirections sdirs;
+  sdirs.SetGeometryFile(geometryfile);
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 26);
+  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  sdirs.SetRaDec(ra,dec);
+  sdirs.AddDirection(ra,dec,1,"Mkn 421");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  0, 50);
+  const Double_t dec = MAstro::Dms2Rad(39, 12, 44);
+  sdirs.AddDirection(ra,dec,1,"My_UMa 49");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(38, 14, 29);
+  sdirs.AddDirection(ra,dec,1,"My_UMa 51");
+
+  // dummy source dirtections
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(38, 20,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy1");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(38, 20,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy2");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(38, 30,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy3");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(38, 40,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy4");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(38, 50,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy5");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(39,  0,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy6");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(39, 10,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy7");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(39, 20,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy8");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(39, 30,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy9");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(39, 40,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy10");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(39, 50,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy11");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(40,  0,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy12");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(40, 10,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy13");
+
+  const Double_t ra  = MAstro::Hms2Rad(11,  4, 31);
+  const Double_t dec = MAstro::Dms2Rad(40, 20,  0);
+  sdirs.AddDirection(ra,dec,1,"Dummy14");
+
+
+  sdirs.SetRadiusFOV(3);
+  //$$$$$$$$$$$$$$$$ ww
+
+  MFindStars findstars;
+  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+  findstars.SetGeometryFile(geometryfile);
+  findstars.SetBSCFile(catalogfile);
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26);
+  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  findstars.SetRaDec(ra,dec);
+  findstars.SetLimMag(8);
+  findstars.SetRadiusFOV(1.5);
+
+
+
+  //$$$$$$$$$$$$$$$$ ww
+  Int_t InputType = 0;
+  //findstars.SetUseCorrelatedGauss(kFALSE);
+
+  MTelAxisFromStars telaxis;
+  //telaxis.FixRotationAngleAt(-1.0);
+  //telaxis.FixScaleFactorAt(-1.0);
+  telaxis.SetInputType(InputType);
+
+  MFillH fillhisto("MHTelAxisFromStars[MHTelAxisFromStars]","");
+  htelaxis.SetInputType(InputType);
+  //$$$$$$$$$$$$$$$$ ww
+
+
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal);
+  tlist.AddToList(&findstars, "Currents");
+
+  //$$$$$$$$$$$$$$$$ ww
+  tlist.AddToList(&sdirs);
+  tlist.AddToList(&telaxis);
+  tlist.AddToList(&fillhisto);
+  //$$$$$$$$$$$$$$$$ ww
+
+
+  
+  // The following lines you only need if in addition you want to display
+  // independent MAstroCamera output
+  //
+  //  TString fname = "/mcdata/standard/camera/NSB_013/Gamma/Gamma_zbin9_90_7_1480to1489_w0.root";
+  //  MObservatory magic1;      
+  //  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26); //Mkn421
+  //  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  //
+  //  MAstroCamera stars;        
+  //  ReadSetup(fname, stars); 
+  //  stars.SetLimMag(9);
+  //  stars.SetRadiusFOV(3);
+  //  stars.SetRaDec(ra, dec);
+  //  stars.ReadBSC("/home/rwagner/bsc5.dat");
+  //  stars.SetObservatory(magic1);
+
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  if (!evtloop.PreProcess())
+    return;
+  
+  MHCamera display(geomcam);
+  display.SetPrettyPalette();
+  display.Draw();
+  gPad->cd(1);
+  starcam.Draw();
+  
+  UInt_t numevents=0;
+  
+  while (tlist.Process())
+    {
+      //gLog << "---------------------------------------------" << endl;
+      //gLog << "Macro : MStarPos content = " << endl;
+      //starcam.Print("namepossizchierr");
+      //gLog << "---------------------------------------------" << endl;
+      //gLog << "Macro : MSourcePos content = " << endl;
+      //sourcecam.Print("namepossizchierr");
+      //gLog << "---------------------------------------------" << endl;
+
+      numevents++;
+      if (numevents%integratedevents==0)
+	{
+	  display.SetCamContent(findstars.GetDisplay());
+	  gPad->Modified();
+	  gPad->Update();	      
+        // This line prints the results:
+	// 	  starcam.Print();
+
+	// This is how to access the TList of stars:
+	//	  TList* starlist = starcam.GetList();
+
+	// This is how to iterate over stars found:
+	//	  TIter Next(starlist);
+	// 	  MStarPos* star;
+	// 	  UInt_t starnum = 0;
+	//        cout << filename << " ";
+	//        cout << "Iterating over list" << endl;
+	// 	  while ( (star=(MStarPos*)Next()) ) 
+	// 	  {
+	//          cout << "star[" << starnum << "] ";
+	//          cout << star->GetMeanX() << " " 
+	//               << star->GetMeanY() << " ";
+	//	    starnum++;
+	//	  }
+	//        cout << endl;
+	}
+
+      // fill the histograms
+      // loop over stars in "MSourceCam"
+      TList* sourcelist = sourcecam.GetList();
+      TIter Nextsource(sourcelist);
+      MStarPos* source;
+      while ( (source=(MStarPos*)Nextsource()) ) 
+      {
+        Double_t R = sqrt( source->GetXExp()*source->GetXExp()
+      		   + source->GetYExp()*source->GetYExp() );
+
+        Double_t R0= sqrt( source->GetXIdeal()*source->GetXIdeal()
+      		   + source->GetYIdeal()*source->GetYIdeal() );
+
+        //cout << "R0, R = " << R0 << ",  " << R << endl;
+
+	aberr->Fill(R0, R, 1.0);
+        reldiff->Fill(R0, (R-R0)/R0), 1.0);
+      }
+	
+      //--------------------------------------
+      MTime time;
+      time.Set(2004, 4, 22, 21, 51, 15);
+      
+      //superimpose star picture
+      //       stars.SetTime(time);
+      //       TObject *o = stars.Clone();
+      //       o->SetBit(kCanDelete);
+      //       o->Draw();
+      
+      // wait after each event
+      //if (!HandleInput())
+      //  break;
+
+    }
+
+
+
+  evtloop.PostProcess();
+  tlist.PrintStatistics();
+    
+  plist.Print();
+
+  //$$$$$$$$$$$$$$$$ ww
+  
+  //gLog << "Event loop finished; call DrawClone of MHTelAxisFromStars" << endl;
+
+  //TObject *srccam = plist.FindObject("MSourceCam");
+  //gLog << "srccam = " << srccam << endl;
+
+  TObject *obj = plist.FindObject("MHTelAxisFromStars");
+  if (obj)
+  {
+    //obj->Print();
+    //obj->Dump();
+    obj->DrawClone();
+  }
+  else
+    gLog << "address of MHTelAxisFromStars container is zero" << endl;
+  
+  //$$$$$$$$$$$$$$$$ ww
+
+  // plot the histograms
+  TCanvas *canv = new TCanvas("Optical_Aberration", "Optical aberration",
+			      0, 0, 600, 300);
+  canv->Divide(2,1);
+  canv->SetBorderMode(0); 
+  
+  canv->cd(1);
+  aberr->Draw();
+
+  canv->cd(2);
+  reldiff->Draw();
+
+}
+
+//----------------------------------------------------------------------
+//
+//
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+//=========================================================================
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mberlin/macros/AlphaPlot.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mberlin/macros/AlphaPlot.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mberlin/macros/AlphaPlot.C	(revision 9772)
@@ -0,0 +1,250 @@
+#include "TString.h"
+#include "TChain.h"
+#include "TCanvas.h"
+#include "TH1F.h"
+#include "TF1.h"
+#include "TLegend.h"
+#include "TArrayF.h"
+#include "TGraphErrors.h"
+#include "MRawRunHeader.h"
+#include "TPad.h"
+#include "TPaveText.h"
+#include "iostream.h"
+#include "TObjArray.h"
+#include "TFile.h"
+
+//--------------------------------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//--------------------------------------------------------------------------------------
+
+Double_t signal(Double_t *x, Double_t *par)
+{
+    return par[0]/(TMath::Sqrt(2.*TMath::Pi())*par[1])*TMath::Exp(-(x[0]-par[2])*(x[0]-par[2])/2./par[1]/par[1]);
+}
+
+Double_t background(Double_t *x, Double_t *par)
+{
+    return par[0]+par[1]*x[0]+par[2]*x[0]*x[0]+par[3]*x[0]*x[0]*x[0];
+}
+
+Double_t fitFunction(Double_t *x, Double_t *par)
+{
+    return signal(x,par) + background(x,&par[3]);
+}
+
+void AlphaPlot()
+{
+    DistLo*=deg2mm;
+    DistUp*=deg2mm;
+
+    Double_t acut = 10; // alpha region of excess
+    Int_t nbins   = 36;
+    Int_t nbin_flat= nbins/3;
+
+    // input file chain
+    TChain *fEvents=new TChain("Events");
+    fEvents->Add(fileOn1.Data());
+    fEvents->Add(fileOn2.Data());
+
+    TChain *fEventsOff=new TChain("Events");
+    fEventsOff->Add(fileOff1.Data());
+    fEventsOff->Add(fileOff2.Data());
+
+
+    cout<<"Non="<<fEvents->GetEntries()<<"  Noff="<<fEventsOff->GetEntries()<<endl;
+    //************************************************************************
+    // alpha plot + fit
+
+    // make alpha plot (after cuts)
+    TCanvas *c1 = new TCanvas("c1","Alpha distribution after g/h separation",200,10,800,500);
+    c1->SetFillColor(0);
+    c1->SetBorderMode(0);
+    c1->cd();
+
+    TH1F *halpha=new TH1F("halpha","",nbins,0.,90.);
+    halpha->GetXaxis()->SetTitle("Alpha [deg]");
+    halpha->GetYaxis()->SetTitle("Counts");
+
+    TH1F *halphaOff=new TH1F("halphaOff","",nbins,0.,90.);
+    halpha->SetStats(kFALSE);
+    halphaOff->SetStats(kFALSE);
+
+    TString strcut=Form("MHillas.fSize>%f",SizeLo);
+
+    strcut+=Form("&& MHillasSrc.fDist>%f",DistLo);
+    strcut+=Form("&& MHillasSrc.fDist<%f",DistUp);
+
+    strcut+=Form("&& MHillas.fWidth>%f",WidthLo);
+    strcut+=Form("&& MHillas.fWidth<%f",WidthUp);
+
+    strcut+=Form("&& MHillas.fLength>%f",LengthLo);
+    strcut+=Form("&& MHillas.fLength<%f",LengthUp);
+
+    // fill histograms
+    fEvents->Project("halpha","TMath::Abs(MHillasSrc.fAlpha)",strcut.Data());
+    halpha->SetLineWidth(2);
+    halpha->DrawCopy("e");
+
+    fEventsOff->Project("halphaOff","TMath::Abs(MHillasSrc.fAlpha)",strcut.Data());
+    halphaOff->SetLineColor(2);
+    halphaOff->SetLineWidth(2);
+
+
+    // scale Off histogram to On data using bins nbin_flat(first bin after peak) - nbins
+    Double_t nsample_on=0;
+    Double_t nsample_off=0;
+    for(Int_t i=nbin_flat;i<nbins;i++)
+        nsample_on+=halpha->GetBinContent(i);
+    for(Int_t i=nbin_flat;i<nbins;i++)
+        nsample_off+=halphaOff->GetBinContent(i);
+
+    Double_t scal=nsample_on/nsample_off;
+    halphaOff->Sumw2();
+    halphaOff->Scale(scal);
+    halphaOff->Draw("e same");
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    //--------------------------------------------------------------------------
+    // fit alpha hist
+    TF1 *backFcn = new TF1("backFcn",background,20.,89.5,4);
+    backFcn->SetLineWidth(2);
+    backFcn->SetLineColor(kRed);
+
+    TF1 *signalFcn = new TF1("signalFcn",signal,0.,89.5,3);
+    signalFcn->SetLineWidth(2);
+    signalFcn->SetLineColor(kBlue);
+    signalFcn->SetNpx(500);
+
+    TF1 *fitFcn = new TF1("fitFcn",fitFunction,0.,89.5,7);
+    fitFcn->SetNpx(500);
+    fitFcn->SetLineWidth(2);
+    fitFcn->SetLineColor(kMagenta);
+
+    // start-parameters
+    Double_t p3start=halpha->GetBinContent(halpha->GetNbinsX()-1);
+    Double_t p4start=0.;
+    Double_t p5start=0.;
+    Double_t p6start=0.;
+
+    Double_t p0start=(halpha->GetEntries()-p3start*nbins)*halpha->GetBinWidth(1);
+    Double_t p1start=5.;
+    Double_t p2start=0.;
+
+    cout<<"Start values for fit:"<<endl;
+
+    cout<<" Gaussian:"<<endl;
+    cout<<"  p0 = "<<p0start<<endl;
+    cout<<"  p1 = "<<p1start<<endl;
+    cout<<"  p2 = "<<p2start<<endl;
+
+    cout<<" Pol3:"<<endl;
+    cout<<"  p0 = "<<p3start<<endl;
+    cout<<"  p1 = "<<p4start<<endl;
+    cout<<"  p2 = "<<p5start<<endl;
+    cout<<"  p3 = "<<p6start<<endl<<endl<<endl;
+
+    // background fit
+    Double_t parb[4];
+    backFcn->SetParameters(p3start,p4start,p5start,p6start);
+    backFcn->FixParameter(1,0);   // deriv. at zero equal zero
+    //backFcn->FixParameter(2,0); // no 2nd order term
+    backFcn->FixParameter(3,0);   // no 3rd order term
+    halpha->Fit ("backFcn","RN");
+    backFcn->GetParameters(parb);
+
+    // total fit
+    Double_t par[7];
+    fitFcn->SetParameters(p0start,p1start,p2start,
+                          parb[0],parb[1],parb[2],parb[3]);
+
+    fitFcn->FixParameter(2,0.);
+    fitFcn->FixParameter(3,parb[0]);
+    fitFcn->FixParameter(4,parb[1]);
+    fitFcn->FixParameter(5,parb[2]);
+    fitFcn->FixParameter(6,parb[3]);
+    halpha->Fit ("fitFcn","RN");
+
+    // draw fit results + legend
+    TLegend *legend=new TLegend(0.4,0.5,0.93,0.65);
+    legend->SetTextFont(40);
+    legend->SetTextSize(0.04);
+    legend->SetFillColor(19);
+    legend->AddEntry(halpha,"Data","lp");
+    TString strpol("");
+    strpol=Form("Polynom");
+    legend->AddEntry(backFcn,strpol.Data(),"l");
+    legend->AddEntry(fitFcn,"Global Fit","l");
+    //legend->Draw();
+
+    fitFcn->GetParameters(par);
+    fitFcn->SetRange(-90.,90.);
+    fitFcn->SetLineWidth(2);
+    fitFcn->Draw("same");
+
+    signalFcn->SetParameters(par);
+    //signalFcn->SetLineWidth(2);
+    //signalFcn->Draw("same");
+
+    backFcn->SetParameters(&par[3]);
+    backFcn->SetRange(-90,90);
+    backFcn->SetLineWidth(2);
+    backFcn->Draw("same");
+
+    //-----------------------------------------------------------------------
+    // calculate significance
+
+    // analytical method
+    Double_t nSig=signalFcn->Integral(0.,acut)/halpha->GetBinWidth(1);
+    Double_t nOffScaled=backFcn->Integral(0.,acut)/halpha->GetBinWidth(1);
+
+    Double_t nOn=nSig+nOffScaled;
+
+    // significance after Li/Ma
+    Double_t theta=1.; // should be = Ton/Toff ???
+    Double_t nOff=nOffScaled/theta;
+    Double_t siglima = sqrt(2*(nOn*TMath::Log((1+theta)*nOn/(theta*(nOn+nOff)))
+                               +nOff*TMath::Log((1+theta)*(nOff/(nOn+nOff)))));
+
+    // "standard" significance
+    Double_t sigstd  = nSig/sqrt(nOn+nOffScaled);
+
+    TPaveText *pt = new TPaveText(0.25,0.75,0.56,0.98,"brNDC");
+    pt->SetTextFont(60);
+    pt->SetTextSize(0.03);
+    pt->SetTextAlign(12);
+
+    TString strcut1(Form("cuts:"));
+    TString strcut3(Form(" |alpha| <  %4.2f ",acut));
+    pt->AddText(strcut3.Data());
+    TString str("");
+    pt->AddText(str);
+
+    TString strsig(Form("NExcess = %d",Int_t(nSig)));
+    pt->AddText(strsig.Data());
+    TString strbak(Form("NOff    = %d",Int_t(nOffScaled)));
+    pt->AddText(strbak.Data());
+    pt->AddText(str);
+
+    TString strsg(Form("Significance (Li/Ma) = %4.2f",siglima));
+    pt->AddText(strsg.Data());
+    strsg=Form("Significance (std) = %4.2f",sigstd);
+    pt->AddText(strsg.Data());
+    pt->Draw();
+
+    cout<<endl<<"Results for events with |alpha| < "<<acut<<" degrees :"<<endl;
+    cout<<" noff         ="<<nOffScaled<<endl;
+    cout<<" nexcess      ="<<nSig<<endl;
+    cout<<" sig. (Li/Ma) ="<<siglima<<endl;
+    cout<<" sig.-std     ="<<sigstd<<endl<<endl<<endl;
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    c1->Update();
+
+    return;
+}
Index: /tags/Mars-V0.9/mtemp/mberlin/macros/Convert2Matrix.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mberlin/macros/Convert2Matrix.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mberlin/macros/Convert2Matrix.C	(revision 9772)
@@ -0,0 +1,93 @@
+#include "TString.h"
+#include "TChain.h"
+#include "TFile.h"
+#include "TH1F.h"
+#include "TMatrix.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MReadTree.h"
+#include "MHMatrix.h"
+#include "MFillH.h"
+#include "MEvtLoop.h"
+
+//--------------------------------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//--------------------------------------------------------------------------------------
+
+void Convert2Matrix()
+{
+    //------------------------------------------------------
+    // ON + OFF data to be filled into matrix
+
+    MReadTree readOn("Events", fileOptOn);
+    MReadTree readOff("Events", fileOptOff);
+
+    const Int_t nent=readOn.GetEntries();
+
+    //------------------------------------------------------
+
+    // process On data
+    MParList plistOn;
+    MTaskList tlistOn;
+    plistOn.AddToList(&tlistOn);
+
+    readOn.DisableAutoScheme();
+
+    TString sdist  = Form("MHillasSrc.fDist*%f",mm2deg);
+  
+    MHMatrix matOn("Matrix");
+    matOn.AddColumn("MHillas.fSize");  // 0
+    matOn.AddColumn(sdist.Data());     // 1
+    matOn.AddColumn("MHillas.fWidth"); // 2
+    matOn.AddColumn("MHillas.fLength");// 3
+    matOn.AddColumn("MHillasSrc.fAlpha");
+    plistOn.AddToList(&matOn);
+    MFillH fillOn("Matrix");
+
+    tlistOn.AddToList(&readOn);
+    tlistOn.AddToList(&fillOn);
+
+    MEvtLoop evtloopOn;
+    evtloopOn.SetParList(&plistOn);
+
+    if (!evtloopOn.Eventloop(0.5*nent))
+        return;
+
+    tlistOn.PrintStatistics();
+
+    TFile fileOn2(fileMatOn.Data(),"recreate","");
+    matOn.Write();
+    fileOn2.Close();
+
+
+    // process Off data
+
+    MParList plistOff;
+    MTaskList tlistOff;
+    plistOff.AddToList(&tlistOff);
+
+    readOff.DisableAutoScheme();
+
+    MHMatrix matOff("Matrix");
+    matOff.AddColumns(matOn.GetColumns());
+    plistOff.AddToList(&matOff);
+    MFillH fillOff("Matrix");
+
+    tlistOff.AddToList(&readOff);
+    tlistOff.AddToList(&fillOff);
+
+    MEvtLoop evtloopOff;
+    evtloopOff.SetParList(&plistOff);
+
+    if (!evtloopOff.Eventloop())
+        return;
+
+    tlistOff.PrintStatistics();
+
+    TFile fileOff2(fileMatOff.Data(),"recreate","");
+    matOff.Write();
+    fileOff2.Close();
+}
Index: /tags/Mars-V0.9/mtemp/mberlin/macros/CutOptim.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mberlin/macros/CutOptim.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mberlin/macros/CutOptim.C	(revision 9772)
@@ -0,0 +1,468 @@
+#include "TMinuit.h"
+#include "TMatrix.h"
+#include "TString.h"
+#include "TCanvas.h"
+#include "TH1F.h"
+#include "TF1.h"
+#include "TLegend.h"
+#include "TFile.h"
+#include "TArrayF.h"
+#include "TGraphErrors.h"
+#include "MRawRunHeader.h"
+#include "TPad.h"
+#include "TPaveText.h"
+#include "iostream.h"
+#include "TObjArray.h"
+
+#include "MHMatrix.h"
+
+//--------------------------------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//--------------------------------------------------------------------------------------
+
+Double_t acut = 10; // alpha region of excess
+Bool_t aplot  = 1;  // make only alpha plot (1) , do sig. optimization and alpha plot (0)
+
+//--------------------------------------------------------------------------------------------------------------
+//--------------------------------------------------------------------------------------------------------------
+
+const TMatrix *matOn;
+const TMatrix *matOff;
+
+Int_t isize   = 0;
+Int_t idist   = 1;
+Int_t iwidth  = 2;
+Int_t ilength = 3;
+Int_t ialpha  = 4;
+
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+
+Double_t signal(Double_t *x, Double_t *par){
+    return par[0]/(TMath::Sqrt(2.*TMath::Pi())*par[1])*TMath::Exp(-(x[0]-par[2])*(x[0]-par[2])/2./par[1]/par[1]);
+}
+
+Double_t background(Double_t *x, Double_t *par){
+    return par[0]+par[1]*x[0]+par[2]*pow(x[0],2.)+par[3]*x[0]*x[0]*x[0];
+    //return par[0]+par[1]*x[0]+par[2]*x[0]*x[0]+par[3]*x[0]*x[0]*x[0];
+}
+
+Double_t fitFunction(Double_t *x, Double_t *par){
+    return signal(x,par) + background(x,&par[3]);
+}
+
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+    Double_t w1=par[0];
+    Double_t w2=par[1];
+    Double_t l1=par[2];
+    Double_t l2=par[3];
+    Double_t d1=par[4];
+    Double_t d2=par[5];
+
+    Double_t non=0;
+    Double_t noff=0;
+
+    TH1F hon("hon","",18,0.,90.);//5 deg bins
+    for(Int_t i=0;i<matOn->GetNrows();i++)
+    {
+        if( (*matOn)(i,isize)<SizeLo) continue;
+        if(((*matOn)(i,idist)>d1)  ||((*matOn)(i,idist)<d2  )) continue;
+
+        if(((*matOn)(i,iwidth)>w1) ||((*matOn)(i,iwidth)<w2))  continue;
+        if(((*matOn)(i,ilength)>l1)||((*matOn)(i,ilength)<l2)) continue;
+
+        Float_t alpha=(*matOn)(i,ialpha);
+        hon.Fill(TMath::Abs(alpha));
+    }
+
+    for(Int_t i=1;i<=4;i++)
+        non+=hon.GetBinContent(i);
+
+    //-----------------------------------------------------------------
+    /*TH1F hoff("hoff","",18,0.,90.);//5 deg bins
+    for(Int_t i=0;i<matOff->GetNrows();i++)
+    {
+        if( (*matOff)(i,isize)<SizeLo) continue;
+        if(((*matOff)(i,idist)>d1)  ||((*matOff)(i,idist)<d2  )) continue;
+
+        if(((*matOff)(i,iwidth)>w1) ||((*matOff)(i,iwidth)<w2))  continue;
+        if(((*matOff)(i,ilength)>l1)||((*matOff)(i,ilength)<l2)) continue;
+
+        Float_t alpha=(*matOff)(i,ialpha);
+        hoff.Fill(TMath::Abs(alpha));
+    }
+
+    for(Int_t i=1;i<=4;i++)
+        noff+=hoff.GetBinContent(i);*/
+    //-----------------------------------------------------------------
+
+    // flat background region
+    for(Int_t i=7;i<=15;i++)
+        noff+=hon.GetBinContent(i);
+
+    Float_t offscale=4./9.;
+    noff*=offscale;
+
+    if(non+noff<0.001)
+        f=0.;
+    else
+        f = -(non-noff)/(TMath::Sqrt(non+noff));
+
+    cout<<"Non="<<non<<" Noff="<<noff*offscale<<" Sig="<<-f<<endl;
+}
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+void CutOptim()
+{
+    //-----------------------------------------------------------------------
+    // read matrices
+
+    MHMatrix hmatOn;
+    TFile *fileOn=new TFile(fileMatOn.Data());
+    hmatOn.Read("Matrix");
+    delete fileOn;
+    const TMatrix &mOn=hmatOn.GetM();
+    matOn=(const TMatrix*)&mOn;
+
+    MHMatrix hmatOff;
+    TFile *fileOff=new TFile(fileMatOff.Data());
+    hmatOff.Read("Matrix");
+    delete fileOff;
+    const TMatrix &mOff=hmatOff.GetM();
+    matOff=(const TMatrix*)&mOff;
+
+    //-----------------------------------------------------------------------
+
+    Int_t nrowOn  = matOn->GetNrows();
+    Int_t nrowOff = matOff->GetNrows();
+
+    Int_t ncolOn  = matOn->GetNcols();
+    Int_t ncolOff = matOff->GetNcols();
+
+    cout<<"matrix On:  ncol="<<ncolOn<<" nrow="<<nrowOn<<endl;
+    cout<<"matrix Off: ncol="<<ncolOff<<" nrow="<<nrowOff<<endl;
+
+    TCanvas *c = new TCanvas("c1","Alpha distribution after g/h separation",200,10,800,500);
+    c->SetFillColor(0);
+
+    //-----------------------------------------------------------------------
+    // optimize cuts
+
+    Int_t iflag;
+    Double_t val;
+    Double_t vstart[6];
+
+    Double_t *gin=NULL;
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    TMinuit *gMinuit = new TMinuit(10);
+    TGraph* gr=NULL;
+
+    if(!aplot)
+        c->Divide(2,1);
+    else
+        goto APlot;
+
+    // start values
+    vstart[0]=WidthUp;
+    vstart[1]=WidthLo;
+    vstart[2]=LengthUp;
+    vstart[3]=LengthLo;
+    vstart[4]=DistUp;
+    vstart[5]=DistLo;
+
+    gMinuit->SetFCN(fcn);
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+
+    // Set starting values and step sizes for parameters
+    static Double_t step[6];
+    const Double_t def_step=0.2;
+    step[0]=def_step;
+    step[1]=def_step;
+    step[2]=def_step;
+    step[3]=def_step;
+    step[4]=def_step;
+    step[5]=def_step;
+
+    gMinuit->mnparm(0,"w1", vstart[0], step[0], 0.,0.,ierflg);
+    gMinuit->mnparm(1,"w2", vstart[1], step[1], 0.,0.,ierflg);
+    gMinuit->mnparm(2,"l1", vstart[2], step[2], 0.,0.,ierflg);
+    gMinuit->mnparm(3,"l2", vstart[3], step[3], 0.,0.,ierflg);
+    gMinuit->mnparm(4,"d1", vstart[4], step[4], 0.2,1.,ierflg);
+    gMinuit->mnparm(5,"d2", vstart[5], step[5], 0.5,1.5,ierflg);
+
+    //gMinuit->FixParameter(0);  // WidthUp
+    gMinuit->FixParameter(1);   // WidthLo
+    //gMinuit->FixParameter(2);  // LengthUp
+    gMinuit->FixParameter(3);   // LengthLo
+    gMinuit->FixParameter(4);   // DistUp
+    gMinuit->FixParameter(5);   // DistLo
+
+    gMinuit->Eval(6,gin,val,vstart,iflag);
+
+    arglist[0] = 5000;
+    arglist[1] = 1.;
+
+    //gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);
+    gMinuit->mnexcm("SIM", arglist ,2,ierflg);
+
+    // Print results
+    Double_t amin,edm,errdef;
+    Int_t nvpar,nparx,icstat;
+    gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
+    gMinuit->mnprin(3,amin);
+
+    Double_t fpar[6];
+    Double_t fparerr[6];
+    for(Int_t i=0;i<6;i++)
+        gMinuit->GetParameter(i,fpar[i],fparerr[i]);
+
+    WidthUp  = fpar[0];
+    WidthLo  = fpar[1];
+    LengthUp = fpar[2];
+    LengthLo = fpar[3];
+    DistUp   = fpar[4];
+    DistLo   = fpar[5];
+
+
+    // parameter's sigma plots
+    c->cd(2);
+    // 2 sigma contour
+    /*
+    gMinuit->SetErrorDef(4);
+    gr = (TGraph*) gMinuit->Contour(100,0,2);
+    gr->DrawClone("AL");*/
+
+    // 1 sigma contour
+    gMinuit->SetErrorDef(1);
+    gr = (TGraph*) gMinuit->Contour(100,0,2);
+    gr->DrawClone("AL");
+    /*
+    // contour of min. function
+    c->cd(2);
+    arglist[0] = 1; // WidthUp
+    gMinuit->mnexcm("SCA", arglist ,1,ierflg);
+    TGraph* gr = (TGraph*)gMinuit->GetPlot();
+    gr->DrawClone("al");
+
+    c->cd(4);
+    arglist[0] = 4; // LengthLo
+    gMinuit->mnexcm("SCA", arglist ,1,ierflg);
+    gr = (TGraph*)gMinuit->GetPlot();
+    gr->DrawClone("al");//*/
+
+    c->cd(1);
+
+APlot:
+    //-----------------------------------------------------------------------
+    // plot alpha histogram with current cuts and calc significance
+
+    // alpha histogram
+    TH1F *halpha=new TH1F("halpha","",18,0.,90.);
+    TH1F *halphaOff=new TH1F("halphaOff","",18,0.,90.);
+
+    halpha->SetStats(kFALSE);
+    halphaOff->SetStats(kFALSE);
+
+    for(Int_t i=0;i<nrowOn;i++)
+    {
+        if (mOn(i,isize)<SizeLo) continue;
+        if((mOn(i,idist)<DistLo)||(mOn(i,idist)>DistUp)) continue;
+
+        if((mOn(i,iwidth) < WidthLo) ||(mOn(i,iwidth) > WidthUp))  continue;
+        if((mOn(i,ilength)< LengthLo)||(mOn(i,ilength)> LengthUp)) continue;
+
+        halpha->Fill(TMath::Abs(mOn(i,ialpha)));
+    }
+    halpha->SetLineWidth(2);
+    halpha->DrawClone();
+
+    for(Int_t i=0;i<nrowOff;i++)
+    {
+        if (mOff(i,isize)<SizeLo) continue;
+        if((mOff(i,idist)<DistLo)||(mOff(i,idist)>DistUp)) continue;
+
+        if((mOff(i,iwidth) < WidthLo) ||(mOff(i,iwidth) > WidthUp))  continue;
+        if((mOff(i,ilength)< LengthLo)||(mOff(i,ilength)> LengthUp)) continue;
+
+        halphaOff->Fill(TMath::Abs(mOff(i,ialpha)));
+
+    }
+
+    // scale Off histogram to On data using bins 6-18
+    Double_t nsample_on=0;
+    Double_t nsample_off=0;
+    for(Int_t i=6;i<18;i++)
+        nsample_on+=halpha->GetBinContent(i);
+    for(Int_t i=6;i<18;i++)
+        nsample_off+=halphaOff->GetBinContent(i);
+
+    Double_t scal=nsample_on/nsample_off;
+
+    halphaOff->SetLineColor(2);
+    halphaOff->Scale(scal);
+    halphaOff->Draw("same");
+
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    // define functions
+    TF1 *backFcn = new TF1("backFcn",background,20.,89.5,4);
+    backFcn->SetLineWidth(2);
+    backFcn->SetLineColor(kRed);
+
+    TF1 *signalFcn = new TF1("signalFcn",signal,0.,89.5,3);
+    signalFcn->SetLineWidth(2);
+    signalFcn->SetLineColor(kBlue);
+    signalFcn->SetNpx(500);
+
+    TF1 *fitFcn = new TF1("fitFcn",fitFunction,0.,89.5,7);
+    fitFcn->SetNpx(500);
+    fitFcn->SetLineWidth(2);
+    fitFcn->SetLineColor(kMagenta);
+
+    // start-parameters
+    Double_t p3start=halpha->GetBinContent(halpha->GetNbinsX()-1);
+    Double_t p4start=0.;
+    Double_t p5start=0.;
+    Double_t p6start=0.;
+
+    Double_t p0start=(halpha->GetEntries()*halpha->GetBinWidth(1)-p3start)*0.05;
+    Double_t p1start=5.;
+    Double_t p2start=0.;
+
+    cout<<"start values:"<<endl;
+
+    cout<<" gaussian:"<<endl;
+    cout<<"  p0 = "<<p0start<<endl;
+    cout<<"  p1 = "<<p1start<<endl;
+    cout<<"  p2 = "<<p2start<<endl;
+
+    cout<<" pol3:"<<endl;
+    cout<<"  p0 = "<<p3start<<endl;
+    cout<<"  p1 = "<<p4start<<endl;
+    cout<<"  p2 = "<<p5start<<endl;
+    cout<<"  p3 = "<<p6start<<endl<<endl;
+
+
+    // background fit
+    Double_t parb[4];
+    backFcn->SetParameters(p3start,p4start,p5start,p6start);
+    backFcn->FixParameter(1,0);    // deriv. at zero equal zero
+    //backFcn->FixParameter(2,0);  // no 2nd order term
+    backFcn->FixParameter(3,0);    // no 3rd order term
+    //halphaOff->Fit ("backFcn","RN");
+    halpha->Fit ("backFcn","RN");
+    backFcn->GetParameters(parb);
+
+    // total fit
+    Double_t par[7];
+    fitFcn->SetParameters(p0start,p1start,p2start,
+                          parb[0],parb[1],parb[2],parb[3]);
+
+    fitFcn->FixParameter(2,0.);
+    fitFcn->FixParameter(3,parb[0]);
+    fitFcn->FixParameter(4,parb[1]);
+    fitFcn->FixParameter(5,parb[2]);
+    fitFcn->FixParameter(6,parb[3]);
+    halpha->Fit ("fitFcn","RN");
+
+    // draw the legend
+    TLegend *legend=new TLegend(0.4,0.5,0.93,0.65);
+    legend->SetTextFont(40);
+    legend->SetTextSize(0.04);
+    legend->SetFillColor(19);
+    legend->AddEntry(halpha,"Data","lp");
+    TString strpol("");
+    strpol=Form("Polynom");
+    legend->AddEntry(backFcn,strpol.Data(),"l");
+    legend->AddEntry(fitFcn,"Global Fit","l");
+    //legend->Draw();
+
+    // drawing the functions
+    fitFcn->GetParameters(par);
+    fitFcn->SetRange(-90.,90.);
+    fitFcn->SetLineWidth(2);
+    fitFcn->Draw("same");
+
+    signalFcn->SetParameters(par);
+    signalFcn->SetLineWidth(2);
+    //signalFcn->Draw("same");
+
+    backFcn->SetParameters(&par[3]);
+    backFcn->SetRange(-90,90);
+    backFcn->SetLineWidth(2);
+    backFcn->Draw("same");
+
+
+    //-----------------------------------------------------------------------
+    // calculate significance
+
+    // analytical method
+    Double_t nSig=signalFcn->Integral(0.,acut)/halpha->GetBinWidth(1);
+    Double_t nOffScaled=backFcn->Integral(0.,acut)/halpha->GetBinWidth(1);
+
+    Double_t nOn=nSig+nOffScaled;
+
+    // significance after Li/Ma
+    Double_t theta=1.; // should be = Ton/Toff ???
+    nSig=nOn-nOffScaled;
+    Double_t nOff=nOffScaled/theta;
+
+    Double_t siglima = sqrt(2*(nOn*TMath::Log((1+theta)*nOn/(theta*(nOn+nOff)))
+                               +nOff*TMath::Log((1+theta)*(nOff/(nOn+nOff)))));
+
+    // "standard" significance
+    Double_t sigstd  = nSig/sqrt(nOn+nOffScaled);
+
+
+    TPaveText *pt = new TPaveText(0.25,0.75,0.56,0.98,"brNDC");
+ 
+    pt->SetTextFont(60);
+    pt->SetTextSize(0.03);
+    pt->SetTextAlign(12);
+
+    TString strcut1(Form("cuts:"));
+    TString strcut3(Form(" |alpha| <  %4.2f ",acut));
+    pt->AddText(strcut3.Data());
+    TString str("");
+    pt->AddText(str);
+
+    TString strsig(Form("NExcess = %d",Int_t(nSig)));
+    pt->AddText(strsig.Data());
+    TString strbak(Form("NOff    = %d",Int_t(nOffScaled)));
+    pt->AddText(strbak.Data());
+    pt->AddText(str);
+
+    TString strsg(Form("Significance (Li/Ma) = %4.2f",siglima));
+    pt->AddText(strsg.Data());
+
+    cout<<"results for events with alpha < "<<acut<<" degrees :"<<endl;
+    cout<<" nbackground  = "<<nOffScaled<<endl;
+    cout<<" theta        = "<<theta<<endl;
+    cout<<" nsignal      = "<<nSig<<endl;
+    cout<<" sig. (Li/Ma) = "<<siglima<<endl;
+    cout<<" sig.-std     = "<<sigstd<<endl;
+    pt->Draw();
+    gPad->SetGridx();
+    gPad->SetGridy();
+
+    c->Update();
+
+    cout<<endl<<"Optimized Cuts:"<<endl;
+    cout<<" "<<DistLo<<" < dist <"<<DistUp<<endl;
+    cout<<" "<<WidthLo<<" < width <"<<WidthUp<<endl;
+    cout<<" "<<LengthLo<<" < length <"<<LengthUp<<endl;
+
+    return;
+}
+
Index: /tags/Mars-V0.9/mtemp/mberlin/macros/IOMkn421.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mberlin/macros/IOMkn421.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mberlin/macros/IOMkn421.h	(revision 9772)
@@ -0,0 +1,152 @@
+//**************************************************************************************************************
+//
+// Sample A ON  = Runs 17206 - 17265
+// Sample A OFF = Runs 17269 - 17283
+//
+// Sample B ON  = Runs 17286 - 17456
+// Sample B OFF = Runs 17459 - 17543
+//
+//**************************************************************************************************************
+
+//**************************************************************************************************************
+// general INPUT
+//**************************************************************************************************************
+
+// pi
+const double  PI=3.14159265358979333;  //atan(1)*4.0
+
+// conversion from deg to mm and vice versa
+const Double_t mm2deg = 180./17000./PI;
+const Double_t deg2mm = 1./mm2deg;
+
+// conversion from rad to deg and vice versa
+const Double_t rad2deg = 180./PI;
+const Double_t deg2rad = 1./rad2deg;
+
+// conversion from millisec to min
+const Double_t msec2min=1./1000./60.;
+
+//--------------------------------------------------------------------------------------------------------------
+// main path
+
+// HUB
+TString inpath = "/users/eeh/hengsteb/MAGIC/Mkn421Feb2004/SlidingWindow/";
+TString path = "/users/eeh/hengsteb/MAGIC/Mkn421Feb2004/";
+
+// laptop
+//TString inpath = "/home/hengsteb/MAGIC/Mkn421Feb2004/";
+//TString path = "/home/hengsteb/MAGIC/Mkn421Feb2004/";
+
+//**************************************************************************************************************
+// INPUT/OUTPUT for MagicHillas.C, ScaleHillas.C, SrcCorrect.C, FSrcPlot.C
+//**************************************************************************************************************
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 ON A
+TString dataOnA="SLIDINGRun17206-17265CalibRun17193_D_Mkn421On_E";
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 OFF A
+TString dataOffA="SLIDINGRun17269-17283CalibRun17268_D_OffMkn421_E";
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 ON B
+TString dataOnB="SLIDINGRun17286-17456CalibRun17285_D_Mkn421On_E";
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 OFF B
+TString dataOffB="SLIDINGRun17459-17543CalibRun17458_D_OffMkn421_E";
+
+//--------------------------------------------------------------------------------------------------------------
+// select the sample!
+TString data=dataOnB;
+
+TString fileCalibData =  inpath + data + ".root";
+TString fileHillas    =  path + data + "_Hillas.root";
+TString fileHScaled   =  path + data + "_HScaled.root";
+TString fileHScalHist =  path + data + "_HScalHist.root";
+
+TString fileFSrcPlot  =  path + data + "_FSrcPlot.root";
+TString fileSrcPos    =  path + data + "_SrcPos.dat";
+
+TString fileFSrcPlotC =  path + data + "_FSrcPlotC.root"; //corrected with known src pos
+TString fileHScaledC  =  path + data + "_HScaledC.root";  //corrected with known src pos
+
+//--------------------------------------------------------------------------------------------------------------
+// dead pixels
+
+const Int_t NDEAD=54;
+const Short_t DEADPIX[NDEAD]=
+{  0,  25,  26,  34,  38,  46,  54, 124, 125, 155, 156, 157, 158, 162, 170, 172, 201, 202, 203, 204, 205,
+ 206, 207, 208, 224, 388, 395 ,397, 440, 441, 442, 443, 444, 445, 446, 483, 484, 485, 486, 487, 488, 489,
+ 490, 532, 533, 534, 535, 536, 537, 538, 539, 540, 543, 559 };
+// 1    2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21
+
+TArrayS blindpix(NDEAD,DEADPIX);
+
+//--------------------------------------------------------------------------------------------------------------
+// default cuts for false source plots
+/*
+//Double_t SizeLo   = 1000.; // #ph
+//Double_t SizeLo   = 1111.; // #ph
+Double_t SizeLo   = 2000.; // #ph
+Double_t DistLo   = 0.6;   // degree
+Double_t DistUp   = 1.4;   // degree
+
+// static cuts
+//Double_t LengthLo = 0.14*deg2mm;  // degree
+//Double_t LengthUp = 0.26*deg2mm;  // degree
+//Double_t WidthLo  = 0.05*deg2mm;  // degree
+//Double_t WidthUp  = 0.14*deg2mm;  // degree
+
+// scaled Hillas
+
+Double_t LengthLo = 0.2525;
+Double_t LengthUp = 0.9312;
+Double_t WidthLo  = 0.2875;
+Double_t WidthUp  = 0.738;
+//*/
+
+//**************************************************************************************************************
+// INPUT/OUTPUT for AlphaPlot.C, CutOptim.C
+//**************************************************************************************************************
+
+//--------------------------------------------------------------------------------------------------------------
+// Mkn421 A + B
+
+// AlphaPlot + LightCurve, CutOptim
+TString fileOn1      = path + dataOnA + "_HScaledC.root";
+TString fileOn2      = path + dataOnB + "_HScaledC.root";
+
+TString fileOff1     = path + dataOffA + "_HScaled.root";
+TString fileOff2     = path + dataOffB + "_HScaled.root";
+
+TString fileRateCFac = path + "Mkn421A+B_CFac.dat";
+TString fileLCurve   = path + "Mkn421A+B_LCurve.dat";
+TString fileAPlots   = path + "Mkn421A+B_APlot.root";
+
+// matrices needed for cut optimization, optimize on sample A
+TString fileOptOn    = path + dataOnA  + "_HScaledC.root";
+TString fileOptOff   = path + dataOffA + "_HScaled.root";
+
+TString fileMatOn    = path + dataOnA  + "_Matrix.root";
+TString fileMatOff   = path + dataOffA + "_Matrix.root";
+
+//--------------------------------------------------------------------------------------------------------------
+// optimized cuts for 1-dim aplot
+
+//Double_t SizeLo   = 1111.; // #ph
+Double_t SizeLo   = 2000.; // #ph
+Double_t DistLo   = 0.55;
+Double_t DistUp   = 1.27;
+//Double_t DistLo   = 1.;
+//Double_t DistUp   = 1.5;
+//Double_t DistLo   = 0.5;
+//Double_t DistUp   = 1.22;
+
+// optimized on half of sample A for scaled Hillas with dist-cut 0.6 - 1.25, size > 1300
+Double_t LengthLo = 0.318;
+Double_t LengthUp = 0.809;
+Double_t WidthLo  = 0.3;
+Double_t WidthUp  = 0.705;
+//*/
Index: /tags/Mars-V0.9/mtemp/mberlin/macros/ScaleHillas.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mberlin/macros/ScaleHillas.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mberlin/macros/ScaleHillas.C	(revision 9772)
@@ -0,0 +1,626 @@
+#include "TH1F.h"
+#include "TH2F.h"
+#include "TH3F.h"
+#include "TLine.h"
+#include "TTree.h"
+
+#include "TCanvas.h"
+#include "TStyle.h"
+#include "TString.h"
+#include "TFile.h"
+#include "TMath.h"
+
+#include "MReadTree.h"
+#include "MSrcPosCam.h"
+#include "MWriteRootFile.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+
+#include "MTaskInteractive.h"
+
+#include "iostream.h"
+#include "stdlib.h"
+#include "stdio.h"
+#include "string.h"
+
+//--------------------------------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//--------------------------------------------------------------------------------------
+
+Double_t estposx =  0.;
+Double_t estposy =  0.;
+
+//--------------------------------------------------------------------------------------
+// setting for hists
+const Int_t nBinSize=200;
+const Int_t nBinDist=1;
+const Int_t nBinLW=1000;
+
+// limits for size and dist for histograms
+Double_t hSizeLo=2.;
+Double_t hSizeUp=6.;
+Double_t hDistLo=0.5;
+Double_t hDistUp=1.15;
+
+// limits for length, width for histograms
+Double_t hLengthLo=0.;
+Double_t hLengthUp=0.8;
+Double_t hWidthLo =0.;
+Double_t hWidthUp =0.6;
+
+// limits for scaled Hillas for histograms
+Double_t hSLenLo =0.;
+Double_t hSLenUp =15.;
+Double_t hSWidLo =0.;
+Double_t hSWidUp =7.;
+
+// special limits for hLength, hWidth (see ReadHillas())
+const Int_t nBinLWFine=1000;
+Double_t hLenFineLo=0.;
+Double_t hLenFineUp=1.;
+Double_t hWidFineLo=0.;
+Double_t hWidFineUp=1.;
+
+// hists for mean of unscaled Hillas
+TH2F hLenMean("hLenMean","",nBinSize,hSizeLo,hSizeUp, nBinDist,hDistLo,hDistUp);
+TH2F hWidMean("hWidMean","",nBinSize,hSizeLo,hSizeUp, nBinDist,hDistLo,hDistUp);
+
+TH1F hLenMeanSize("hLenMeanSize","",nBinSize,hSizeLo,hSizeUp);
+TH1F hLenMeanDist("hLenMeanDist","",nBinDist,hDistLo,hDistUp);
+TH1F hWidMeanSize("hWidMeanSize","",nBinSize,hSizeLo,hSizeUp);
+TH1F hWidMeanDist("hWidMeanDist","",nBinDist,hDistLo,hDistUp);
+
+// hists for unscaled Hillas
+TH2F hLenSize("hLenSize","",nBinSize,hSizeLo,hSizeUp, nBinLW,hLengthLo,hLengthUp);
+TH2F hLenDist("hLenDist","",nBinDist,hDistLo,hDistUp, nBinLW,hLengthLo,hLengthUp);
+
+TH2F hWidSize("hWidSize","",nBinSize,hSizeLo,hSizeUp, nBinLW,hWidthLo,hWidthUp);
+TH2F hWidDist("hWidDist","",nBinDist,hDistLo,hDistUp, nBinLW,hWidthLo,hWidthUp);
+
+// hists for mean-scaled Hillas
+TH2F hSLenSize("hSLenSize","",nBinSize,hSizeLo,hSizeUp,nBinLW,hSLenLo,hSLenUp);
+TH2F hSLenDist("hSLenDist","",nBinDist,hDistLo,hDistUp,nBinLW,hSLenLo,hSLenUp);
+
+TH2F hSWidSize("hSWidSize","",nBinSize,hSizeLo,hSizeUp,nBinLW,hSWidLo,hSWidUp);
+TH2F hSWidDist("hSWidDist","",nBinDist,hDistLo,hDistUp,nBinLW,hSWidLo,hSWidUp);
+
+
+//****************************************************************************************
+// first part: prepare for scaling, read Hillas to calc mean
+//****************************************************************************************
+
+void ReadHillas()
+{
+    // fill hillas into histograms to calc mean
+    TFile *file=new TFile(fileHillas.Data());
+    TTree *fEvents=(TTree*)file->Get("Events");
+
+    // hists for Hillas
+    // in following 2  hists the binning in length/width should be
+    // very fine (like unbinned) and the limits should be generous
+    TH3F hLength("hLength","",nBinSize,hSizeLo,hSizeUp, nBinDist,hDistLo,hDistUp, nBinLWFine,hLenFineLo,hLenFineUp);
+    TH3F hWidth("hWidth",  "",nBinSize,hSizeLo,hSizeUp, nBinDist,hDistLo,hDistUp, nBinLWFine,hWidFineLo,hWidFineUp);
+
+    TString strlen = Form("MHillas.fLength*%f:MHillasSrc.fDist*%f:log10(MHillas.fSize)",mm2deg,mm2deg);
+    TString strwid = Form("MHillas.fWidth*%f :MHillasSrc.fDist*%f:log10(MHillas.fSize)",mm2deg,mm2deg);
+
+    TString strcut="MHillas.fSize>0";
+    fEvents->Project("hLength",strlen.Data(),strcut.Data());
+    fEvents->Project("hWidth", strwid.Data(),strcut.Data());
+
+    file->Close();
+
+    // fill hists hLenMean, hWidMean (2-dim (size,dist)-hists)
+    for(Int_t i=1;i<=nBinSize;i++)
+        for(Int_t j=1;j<=nBinDist;j++)
+        {
+            Double_t lsum=0.; Double_t lsum2=0.; Double_t lcnt=0.;
+            Double_t wsum=0.; Double_t wsum2=0.; Double_t wcnt=0.;
+
+            for(Int_t k=1;k<=nBinLWFine;k++)
+            {
+                Double_t nl = hLength.GetBinContent(i,j,k);
+                Double_t xl = hLength.GetZaxis()->GetBinCenter(k);
+                
+                lsum +=nl*xl;
+                lsum2+=nl*xl*xl;
+                lcnt +=nl;
+
+                Double_t nw = hWidth.GetBinContent(i,j,k);
+                Double_t xw = hWidth.GetZaxis()->GetBinCenter(k);
+
+                wsum +=nw*xw;
+                wsum2+=nw*xw*xw;
+                wcnt +=nw;
+            }
+
+            Double_t lmean=0.;
+            Double_t lmeanerr=0.;
+            if(lcnt>1)lmean=lsum/lcnt;
+            if(lcnt>2)lmeanerr=(lsum2/lcnt-lmean*lmean)/(lcnt-1.);
+            lmeanerr=TMath::Sqrt(lmeanerr);
+
+            hLenMean.SetBinContent(i,j,lmean);
+            hLenMean.SetBinError(i,j,lmeanerr);
+
+            Double_t wmean=0.;
+            Double_t wmeanerr=0.;
+            if(wcnt>1)wmean=wsum/wcnt;
+            if(wcnt>2)wmeanerr=(wsum2/wcnt-wmean*wmean)/(wcnt-1.);
+            wmeanerr=TMath::Sqrt(wmeanerr);
+
+            hWidMean.SetBinContent(i,j,wmean);
+            hWidMean.SetBinError(i,j,wmeanerr);
+        }
+
+    // fill hists hLenMeanSize, hWidMeanSize (1-dim hists, x-axis = size)
+    for(Int_t i=1;i<=nBinSize;i++)
+    {
+        Double_t lsum=0.; Double_t lsum2=0.; Double_t lcnt=0.;
+        Double_t wsum=0.; Double_t wsum2=0.; Double_t wcnt=0.;
+
+        for(Int_t j=1;j<=nBinDist;j++)
+            for(Int_t k=1;k<=nBinLWFine;k++)
+            {
+                Double_t nl = hLength.GetBinContent(i,j,k);
+                Double_t xl = hLength.GetZaxis()->GetBinCenter(k);
+                
+                lsum +=nl*xl;
+                lsum2+=nl*xl*xl;
+                lcnt +=nl;
+
+                Double_t nw = hWidth.GetBinContent(i,j,k);
+                Double_t xw = hWidth.GetZaxis()->GetBinCenter(k);
+
+                wsum +=nw*xw;
+                wsum2+=nw*xw*xw;
+                wcnt +=nw;
+            }
+
+        Double_t lmean=0.;
+        Double_t lmeanerr=0.;
+        if(lcnt>1)lmean=lsum/lcnt;
+        if(lcnt>2)lmeanerr=(lsum2/lcnt-lmean*lmean)/(lcnt-1.);
+        lmeanerr=TMath::Sqrt(lmeanerr);
+
+        hLenMeanSize.SetBinContent(i,lmean);
+        hLenMeanSize.SetBinError(i,lmeanerr);
+
+        Double_t wmean=0.;
+        Double_t wmeanerr=0.;
+        if(wcnt>1)wmean=wsum/wcnt;
+        if(wcnt>2)wmeanerr=(wsum2/wcnt-wmean*wmean)/(wcnt-1.);
+        wmeanerr=TMath::Sqrt(wmeanerr);
+
+        hWidMeanSize.SetBinContent(i,wmean);
+        hWidMeanSize.SetBinError(i,wmeanerr);
+    }
+
+    // fill hists hLenMeanDist, hWidMeanDist (1-dim hists, x-axis = dist)
+    for(Int_t j=1;j<=nBinDist;j++)
+    {
+        Double_t lsum=0.; Double_t lsum2=0.; Double_t lcnt=0.;
+        Double_t wsum=0.; Double_t wsum2=0.; Double_t wcnt=0.;
+
+        for(Int_t i=1;i<=nBinSize;i++)
+            for(Int_t k=1;k<=nBinLWFine;k++)
+            {
+                Double_t nl = hLength.GetBinContent(i,j,k);
+                Double_t xl = hLength.GetZaxis()->GetBinCenter(k);
+                
+                lsum +=nl*xl;
+                lsum2+=nl*xl*xl;
+                lcnt +=nl;
+
+                Double_t nw = hWidth.GetBinContent(i,j,k);
+                Double_t xw = hWidth.GetZaxis()->GetBinCenter(k);
+
+                wsum +=nw*xw;
+                wsum2+=nw*xw*xw;
+                wcnt +=nw;
+            }
+
+        Double_t lmean=0.;
+        Double_t lmeanerr=0.;
+        if(lcnt>1)lmean=lsum/lcnt;
+        if(lcnt>2)lmeanerr=(lsum2/lcnt-lmean*lmean)/(lcnt-1.);
+        lmeanerr=TMath::Sqrt(lmeanerr);
+
+        hLenMeanDist.SetBinContent(j,lmean);
+        hLenMeanDist.SetBinError(j,lmeanerr);
+
+        Double_t wmean=0.;
+        Double_t wmeanerr=0.;
+        if(wcnt>1)wmean=wsum/wcnt;
+        if(wcnt>2)wmeanerr=(wsum2/wcnt-wmean*wmean)/(wcnt-1.);
+        wmeanerr=TMath::Sqrt(wmeanerr);
+
+        hWidMeanDist.SetBinContent(j,wmean);
+        hWidMeanDist.SetBinError(j,wmeanerr);
+    }
+
+    return;
+}
+
+
+//****************************************************************************************
+// second part: do scaling
+//****************************************************************************************
+
+// pointer to Hillas ParContainer
+MHillas *fHillas=NULL;
+MHillasSrc *fHillasSrc=NULL;
+
+
+Int_t PreProcess(MParList *plist)
+{
+    fHillas = (MHillas*) plist->FindObject("MHillas");
+    fHillasSrc = (MHillasSrc*) plist->FindObject("MHillasSrc");
+
+    return (fHillas && fHillasSrc) ? kTRUE : kFALSE;
+}
+
+Int_t Process()
+{
+    // estimated source pos.
+    MSrcPosCam srcpos;
+    srcpos.SetXY(estposx*deg2mm,estposy*deg2mm);
+    fHillasSrc->SetSrcPos(&srcpos);
+    fHillasSrc->Calc(fHillas);
+
+    Float_t width   = fHillas->GetWidth();
+    Float_t length  = fHillas->GetLength();
+    Float_t size    = fHillas->GetSize();
+    Float_t meanx   = fHillas->GetMeanX();
+    Float_t meany   = fHillas->GetMeanY();
+    Float_t logsize = TMath::Log10(fHillas->GetSize());
+    Float_t delta   = fHillas->GetDelta();
+    Float_t dist    = fHillasSrc->GetDist();
+
+    width *=mm2deg;
+    length*=mm2deg;
+    dist  *=mm2deg;
+
+    hLenSize.Fill(logsize,length);
+    hLenDist.Fill(dist,length);
+    hWidSize.Fill(logsize,width);
+    hWidDist.Fill(dist,width);
+
+    // (log(size), dist) - bin
+    Int_t ix=hLenMean.GetXaxis()->FindBin(logsize);
+    Int_t iy=hLenMean.GetYaxis()->FindBin(dist);
+
+    // check for over-/underflow
+    /*if(ix*iy==0 || ix>nBinSize || iy>nBinDist)
+    {
+        cout<<"Warning, over-/underflow: Log(size)-bin="<<ix;
+        cout<<" Dist-bin="<<iy<<endl<<flush;
+    }*/
+    if(ix==0)ix=1;if(ix==nBinSize+1)ix=nBinSize;
+    if(iy==0)iy=1;if(iy==nBinDist+1)iy=nBinDist;
+
+    Float_t lq=hLenMean.GetBinContent(ix,iy);
+    Float_t wq=hWidMean.GetBinContent(ix,iy);
+
+    if(lq>0.)lq=1./lq;
+    if(wq>0.)wq=1./wq;
+
+    width *=wq;
+    length*=lq;
+
+    hSLenSize.Fill(logsize,length);
+    hSLenDist.Fill(dist,length);
+    hSWidSize.Fill(logsize,width);
+    hSWidDist.Fill(dist,width);
+
+    // --------------------------------------------------------------------------
+    //
+    // This function is ment for special usage, please never try to set
+    // values via this function
+    //
+    /* void MHillas::Set(const TArrayF &arr)
+    {
+        if (arr.GetSize() != 6)
+            return;
+    
+        fLength = arr.At(0);  // [mm]        major axis of ellipse
+        fWidth  = arr.At(1);  // [mm]        minor axis of ellipse
+        fDelta  = arr.At(2);  // [rad]       angle of major axis with x-axis
+        fSize   = arr.At(3);  // [#CerPhot]  sum of content of all pixels (number of Cherenkov photons)
+        fMeanX  = arr.At(4);  // [mm]        x-coordinate of center of ellipse
+        fMeanY  = arr.At(5);  // [mm]        y-coordinate of center of ellipse
+    }*/
+
+    TArrayF farr(6);
+    farr[0]=length;
+    farr[1]=width;
+    farr[2]=delta;
+    farr[3]=size;
+    farr[4]=meanx;
+    farr[5]=meany;
+
+    fHillas->Set(farr);
+
+    fHillas->SetReadyToSave();
+    fHillasSrc->SetReadyToSave();
+
+    return kTRUE;
+}
+
+Int_t PostProcess()
+{
+
+    return kTRUE;
+}
+
+void ScaleHillas(Int_t nent)
+{
+    //---------------------------------------------------------------
+    // scale Hillas (length, width) to mean
+
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read("Events", fileHillas);
+    read.DisableAutoScheme();
+
+    MTaskInteractive scale;
+    scale.SetPreProcess(PreProcess);
+    scale.SetProcess(Process);
+    scale.SetPostProcess(PostProcess);
+
+    MWriteRootFile write(fileHScaled.Data());
+    write.AddContainer("MHillas",      "Events");
+    write.AddContainer("MHillasExt",   "Events");
+    write.AddContainer("MHillasSrc",   "Events");
+    write.AddContainer("MNewImagePar", "Events");
+    write.AddContainer("MRawRunHeader","Events");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&scale);
+    tlist.AddToList(&write);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop(nent))
+        return;
+
+    tlist.PrintStatistics();
+
+    return;
+}
+
+
+//****************************************************************************************
+// third part: check scaling
+//****************************************************************************************
+
+void CheckScaling()
+{
+    //---------------------------------------------------------------
+    // check scaling
+    TFile fileHist(fileHScalHist,"recreate");
+
+    gStyle->SetPalette(1);
+
+
+    TCanvas *c1=new TCanvas("c1","",800,400);
+    if(nBinDist>1)
+        c1->Divide(2,2);
+    else
+        c1->Divide(2,1);
+
+    c1->cd(1);
+    gPad->SetGrid();
+    hSLenSize.SetStats(kFALSE);
+    hSLenSize.GetXaxis()->SetTitle("log(size [#phot])");
+    hSLenSize.GetYaxis()->SetTitle("scaled length");
+    hSLenSize.SetLineWidth(2);
+    hSLenSize.DrawCopy("colz");
+    hSLenSize.Write();
+
+    TLine lLen(2.7,1.,hSizeUp,1.);
+    TLine lLenUp(2.7,LengthUp,hSizeUp,LengthUp);
+    TLine lLenLo(2.7,LengthLo,hSizeUp,LengthLo);
+
+    lLen.SetLineColor(2);
+    lLen.SetLineWidth(2);
+    lLenUp.SetLineWidth(2);
+    lLenLo.SetLineWidth(2);
+    lLen.DrawClone();
+    lLenUp.DrawClone();
+    lLenLo.DrawClone();
+
+
+    c1->cd(2);
+    gPad->SetGrid();
+    hLenSize.SetStats(kFALSE);
+    hLenSize.SetTitle("");
+    hLenSize.GetXaxis()->SetTitle("log(size [#phot])");
+    hLenSize.GetYaxis()->SetTitle("length [deg]");
+    hLenSize.SetLineWidth(2);
+    hLenSize.DrawCopy("colz");
+    hLenSize.Write();
+    hLenMeanSize.SetLineColor(2);
+    hLenMeanSize.SetLineWidth(2);
+    hLenMeanSize.DrawCopy("e same");
+    hLenMeanSize.Write();
+
+    TH1F hLenCutLo("hLenCutLo","",nBinSize,hSizeLo,hSizeUp);
+    TH1F hLenCutUp("hLenCutUp","",nBinSize,hSizeLo,hSizeUp);
+    for(Int_t i=1;i<=nBinSize;i++)
+    {
+        Float_t meanval=hLenMeanSize.GetBinContent(i);
+        hLenCutLo.SetBinContent(i,meanval*LengthLo);
+        hLenCutUp.SetBinContent(i,meanval*LengthUp);
+    }
+    hLenCutLo.SetLineWidth(2);
+    hLenCutUp.SetLineWidth(2);
+    hLenCutLo.DrawCopy("][ same");
+    hLenCutUp.DrawCopy("][ same");
+
+
+    if(nBinDist>1)
+    {
+        c1->cd(3);
+        gPad->SetGrid();
+        hSLenDist.SetStats(kFALSE);
+        hSLenDist.GetXaxis()->SetTitle("dist [deg]");
+        hSLenDist.GetYaxis()->SetTitle("scaled length");
+        hSLenDist.SetLineWidth(2);
+        hSLenDist.DrawCopy("colz");
+        hSLenDist.Write();
+    
+        c1->cd(4);
+        gPad->SetGrid();
+        hLenDist.SetStats(kFALSE);
+        hLenDist.SetTitle("");
+        hLenDist.GetXaxis()->SetTitle("dist [deg]");
+        hLenDist.GetYaxis()->SetTitle("length");
+        hLenDist.SetLineWidth(2);
+        hLenDist.DrawCopy("colz");
+        hLenDist.Write();
+        hLenMeanDist.SetLineColor(2);
+        hLenMeanDist.SetLineWidth(2);
+        hLenMeanDist.DrawCopy("e same");
+        hLenMeanDist.Write();
+    }
+
+    TCanvas *c2=new TCanvas("c2","",800,400);
+    if(nBinDist>1)
+        c2->Divide(2,2);
+    else
+        c2->Divide(2,1);
+
+    c2->cd(1);
+    gPad->SetGrid();
+    hSWidSize.SetStats(kFALSE);
+    hSWidSize.GetXaxis()->SetTitle("log(size [#phot])");
+    hSWidSize.GetYaxis()->SetTitle("scaled width");
+    hSWidSize.SetLineWidth(2);
+    hSWidSize.DrawCopy("colz");
+    hSWidSize.Write();
+
+    TLine lWid(2.7,1.,hSizeUp,1.);
+    TLine lWidUp(2.7,WidthUp,hSizeUp,WidthUp);
+    TLine lWidLo(2.7,WidthLo,hSizeUp,WidthLo);
+
+    lWid.SetLineColor(2);
+    lWid.SetLineWidth(2);
+    lWidUp.SetLineWidth(2);
+    lWidLo.SetLineWidth(2);
+    lWid.DrawClone();
+    lWidUp.DrawClone();
+    lWidLo.DrawClone();
+
+    c2->cd(2);
+    gPad->SetGrid();
+    hWidSize.SetStats(kFALSE);
+    hWidSize.SetTitle("");
+    hWidSize.GetXaxis()->SetTitle("log(size [#phot])");
+    hWidSize.GetYaxis()->SetTitle("width [deg]");
+    hWidSize.SetLineWidth(2);
+    hWidSize.DrawCopy("colz");
+    hWidSize.Write();
+    hWidMeanSize.SetLineColor(2);
+    hWidMeanSize.SetLineWidth(2);
+    hWidMeanSize.DrawCopy("e same");
+    hWidMeanSize.Write();
+
+    TH1F hWidCutLo("hWidCutLo","",nBinSize,hSizeLo,hSizeUp);
+    TH1F hWidCutUp("hWidCutUp","",nBinSize,hSizeLo,hSizeUp);
+    for(Int_t i=1;i<=nBinSize;i++)
+    {
+        Float_t meanval=hWidMeanSize.GetBinContent(i);
+        hWidCutLo.SetBinContent(i,meanval*WidthLo);
+        hWidCutUp.SetBinContent(i,meanval*WidthUp);
+    }
+    hWidCutLo.SetLineWidth(2);
+    hWidCutUp.SetLineWidth(2);
+    hWidCutLo.DrawCopy("][ same");
+    hWidCutUp.DrawCopy("][ same");
+
+    if(nBinDist>1)
+    {
+        c2->cd(3);
+        gPad->SetGrid();
+        hSWidDist.SetStats(kFALSE);
+        hSWidDist.GetXaxis()->SetTitle("dist [deg]");
+        hSWidDist.GetYaxis()->SetTitle("scaled width");
+        hSWidDist.SetLineWidth(2);
+        hSWidDist.DrawCopy("colz");
+        hSWidDist.Write();
+    
+        c2->cd(4);
+        gPad->SetGrid();
+        hWidDist.SetStats(kFALSE);
+        hWidDist.SetTitle("");
+        hWidDist.GetXaxis()->SetTitle("dist [deg]");
+        hWidDist.GetYaxis()->SetTitle("width");
+        hWidDist.SetLineWidth(2);
+        hWidDist.DrawCopy("colz");
+        hWidDist.Write();
+        hWidMeanDist.SetLineColor(2);
+        hWidMeanDist.SetLineWidth(2);
+        hWidMeanDist.DrawCopy("e same");
+        hWidMeanDist.Write();
+    }
+
+    // mean values
+    if(nBinDist>1)
+    {
+        TCanvas *c4=new TCanvas("c4","",800,400);
+        c4->Divide(1,2);
+    
+        c4->cd(1);
+        gPad->SetGrid();
+        hLenMean.SetStats(kFALSE);
+        hLenMean.SetTitle("mean_length(log(size),dist)");
+        hLenMean.GetXaxis()->SetTitle("log(size [#phot])");
+        hLenMean.GetYaxis()->SetTitle("dist [deg])");
+        hLenMean.DrawCopy("colz");
+        hLenMean.Write();
+    
+        c4->cd(2);
+        gPad->SetGrid();
+        hWidMean.SetStats(kFALSE);
+        hWidMean.SetTitle("mean_width(log(size),dist)");
+        hWidMean.GetXaxis()->SetTitle("log(size [#phot])"); ;
+        hWidMean.GetYaxis()->SetTitle("dist [deg])");
+        hWidMean.DrawCopy("colz");
+        hWidMean.Write("colz");
+    }
+
+    fileHist.Close();
+
+    return;
+}
+
+//****************************************************************************************
+// main
+//****************************************************************************************
+
+void RunScaling(Int_t nent=-1)
+{
+    printf("Prepare for scaling...");
+    ReadHillas();
+    printf("done.\n");
+
+    ScaleHillas(nent);
+
+    CheckScaling();
+
+    return;
+}
+
Index: /tags/Mars-V0.9/mtemp/mberlin/macros/SrcCorrect.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mberlin/macros/SrcCorrect.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mberlin/macros/SrcCorrect.C	(revision 9772)
@@ -0,0 +1,768 @@
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MReadTree.h"
+
+#include "MHillasSrc.h"
+#include "MSrcPosCam.h"
+
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+#include "MTaskInteractive.h"
+#include "MContinue.h"
+#include "MRawRunHeader.h"
+#include "MWriteRootFile.h"
+
+#include "TH2F.h"
+#include "TF2.h"
+#include "TArrayF.h"
+#include "TObjArray.h"
+#include "TStyle.h"
+#include "TFile.h"
+#include "TMath.h"
+#include "TString.h"
+#include "TCanvas.h"
+#include "TGraphErrors.h"
+#include "TMarker.h"
+
+#include "iostream.h"
+
+//----------------------------------------------------------------
+// MAIN INPUT/OUTPUT
+
+#include "IOMkn421.h"
+//----------------------------------------------------------------
+
+Double_t rmean=0.3;
+Double_t dtlimit=10;  // time slice width [min]
+//Double_t hlimit =0.85;
+Double_t hlimit =0.9;
+
+//----------------------------------------------------------------
+// false source hist ---------------------------------------------
+//----------------------------------------------------------------
+const Int_t nx = 100; // no. of points in x-grid
+const Int_t ny = 100; // no. of points in y-grid
+
+Double_t alimit = 8.; // signal region in alpha-plot [degree]
+
+Double_t xmin = -1.;  // units in degree !!
+Double_t xmax =  1.;
+Double_t ymin = -1.;
+Double_t ymax =  1.;
+
+Double_t dx=(xmax-xmin)/Double_t(nx);
+Double_t dy=(ymax-ymin)/Double_t(ny);
+
+TH2F FSrcHist("FSrcHist","",nx,xmin-dx,xmax+dx,ny,ymin-dy,ymax+dy);
+TObjArray FSrcArray(1);
+
+TH1F APlot("APlot","",36,0,90);
+TObjArray APlotArray(1);
+
+TArrayF xpeak(100);
+TArrayF ypeak(100);
+
+TArrayF xpeakerr(100);
+TArrayF ypeakerr(100);
+
+Int_t runno     = -1;
+Int_t runno_old = -1;
+Int_t runno_lo  = -1;
+Int_t runno_up  = -1;
+
+Double_t mjdend_old  = -1.;
+Double_t mjdstart_lo = -1.;
+Double_t mjdstart_up = -1.;
+
+Double_t mjd_lo  = -1.;
+Double_t mjd_up  = -1.;
+
+Double_t dt  = 0.;
+Int_t islice = 0;
+
+TF2  *fpeak   = NULL;
+FILE *fsrcpos = NULL;
+
+//****************************************************************************************
+// first part: track the source in time-intervalls of duration dtlimit
+//****************************************************************************************
+
+MHillas       *hil=NULL;
+MRawRunHeader *run=NULL;
+
+Double_t gaus2d(Double_t *x,Double_t *par)
+{
+    Double_t N=par[0];  //integral
+    Double_t mx=par[1]; //mean_x
+    Double_t my=par[2]; //mean_y
+    Double_t sx=par[3]; //sigma_x
+    Double_t sy=par[4]; //sigma_y
+    Double_t rho=par[5];//correlation factor
+    Double_t b=par[6];  //constant background
+
+    Double_t z=(x[0]-mx)*(x[0]-mx)/sx/sx;
+    z+=(x[1]-my)*(x[1]-my)/sy/sy;
+    z-=2.*rho*(x[0]-mx)*(x[1]-my)/sx/sy;
+
+    Double_t val=N/(2.*TMath::Pi()*sx*sy*sqrt(1-rho*rho));
+    val*=exp( -z/(2.*(1.-rho*rho)) );
+    val+=b;
+    return val;
+}
+
+Bool_t CalcPeakXY(Double_t *xmean, Double_t *ymean,
+                  Double_t *xmeanerr, Double_t *ymeanerr)
+{
+    Int_t mbin=FSrcHist.GetMaximumBin();
+    Int_t biny = mbin/(nx+2);
+    Int_t binx = mbin%(nx+2);
+  
+    if(mbin!=FSrcHist.GetBin(binx,biny))
+    {
+        cout<<"Error extracting binx, biny from global bin!"<<endl;
+        cout<<" mbin="<<mbin<<" binfound="<<FSrcHist.GetBin(binx,biny)<<endl;
+        cout<<" binx="<<binx<<" biny="<<biny<<endl;
+  
+        return kFALSE;
+    }
+  
+    Double_t ndelta = rmean/FSrcHist.GetBinWidth(mbin);
+
+    Double_t nmax=FSrcHist.GetBinContent(binx,biny);
+
+    Int_t ilo=Int_t(binx-ndelta);
+    Int_t iup=Int_t(binx+ndelta);
+
+    Int_t jlo=Int_t(biny-ndelta);
+    Int_t jup=Int_t(biny+ndelta);
+
+    Double_t xsum  = 0.; Double_t xsum2 = 0.;
+    Double_t ysum  = 0.; Double_t ysum2 = 0.;
+    Double_t cnt   = 0.;
+    //Double_t cov   = 0.;
+
+    for(Int_t i=ilo;i<=iup;i++)
+        for(Int_t j=jlo;j<=jup;j++)
+        {
+            Double_t n=(Double_t)FSrcHist.GetBinContent(i,j);
+            if(n<hlimit*nmax)continue;
+            Double_t x=(Double_t)FSrcHist.GetXaxis()->GetBinCenter(i);
+            Double_t y=(Double_t)FSrcHist.GetYaxis()->GetBinCenter(j);
+
+            cnt+=n;
+
+            xsum +=n*x;
+            xsum2+=n*x*x;
+            ysum +=n*y;
+            ysum2+=n*y*y;
+        }
+
+    Double_t xbar=0.; Double_t xbarerr=0.;
+    Double_t ybar=0.; Double_t ybarerr=0.;
+
+    if(cnt>1)
+    {
+        xbar=xsum/cnt;
+        ybar=ysum/cnt;
+    }
+    if(cnt>2)
+    {
+        xbarerr=cnt*(xsum2/cnt-xbar*xbar)/(cnt-1.);
+        xbarerr=TMath::Sqrt(xbarerr);
+
+        ybarerr=cnt*(ysum2/cnt-ybar*ybar)/(cnt-1.);
+        ybarerr=TMath::Sqrt(ybarerr);
+    }
+
+    /*
+    //fit not yet tested!!
+    Double_t b=FSrcHist.GetEntries()/nx/ny;
+    Double_t nn=b*ndelta*ndelta;
+
+    fpeak->SetParameter(0,nn);     // integral
+    fpeak->SetParameter(1,*xmean); // mean_x
+    fpeak->SetParameter(2,*ymean); // mean_y
+    fpeak->SetParameter(3,0.15);   // sigma_x
+    fpeak->SetParameter(4,0.15);   // sigma_y
+    fpeak->SetParameter(5,0.);     // correlation factor
+    fpeak->SetParameter(6,b);      // constant background
+
+    FSrcHist.Fit("fpeak");
+    xbar=fpeak->GetParameter(1);
+    ybar=fpeak->GetParameter(2);
+    xbarerr=fpeak->GetParameter(3);
+    ybarerr=fpeak->GetParameter(4);
+    */
+
+    *xmean=xbar;
+    *ymean=ybar;
+    *xmeanerr=xbarerr;
+    *ymeanerr=ybarerr;
+
+    return kTRUE;
+}
+
+void AddFSrcHist(Int_t i,Double_t delta)
+{
+    Int_t n=FSrcArray.GetSize();
+    if(i>=n) FSrcArray.Expand(n+1);
+
+    TH2F *htemp=(TH2F*)FSrcHist.Clone();
+    TString name=Form("%d",i);
+    TString title=Form("TimeIntervall = %f min",delta);
+
+    htemp->SetName(name.Data());
+    htemp->SetTitle(title.Data());
+    htemp->SetDrawOption("colz");
+
+    FSrcArray[i] = htemp;
+
+    return;
+}
+
+void AddAPlot(Int_t i,Double_t delta)
+{
+    Int_t n=APlotArray.GetSize();
+    if(i>=n) APlotArray.Expand(n+1);
+
+    TH1F *htemp=(TH1F*)APlot.Clone();
+    TString name=Form("%d",i);
+    TString title=Form("TimeIntervall = %f min",delta);
+
+    htemp->SetName(name.Data());
+    htemp->SetTitle(title.Data());
+    htemp->SetFillColor(16);
+
+    APlotArray[i] = htemp;
+
+    return;
+}
+
+//----------------------------------------------------------------
+// Source Position Grid ------------------------------------------
+//----------------------------------------------------------------
+
+Int_t STrackPreProc(MParList *plist)
+{
+    hil = (MHillas*) plist->FindObject("MHillas");
+    run = (MRawRunHeader*) plist->FindObject("MRawRunHeader");
+
+    return (hil && run) ? kTRUE : kFALSE;
+}
+
+Int_t STrackProc()
+{
+    runno  = run->GetRunNumber();
+    if(runno==0) return kTRUE;
+
+    Double_t mjdstart = (run->GetRunStart()).GetMjd();
+    Double_t mjdend   = (run->GetRunEnd()).GetMjd();
+    Double_t t = (mjdend-mjdstart)*24.*60.;
+
+    Double_t dtrun;
+    if(runno!=runno_old)
+    {
+        if(dt<0.001) {runno_lo=runno;mjd_lo=mjdstart;mjdend_old=mjdstart;} // very first run
+
+        dtrun=(mjdend_old-mjd_lo)*24.*60.;
+        //if(dt>dtlimit)
+        if(dtrun>dtlimit)
+        {
+            runno_up=runno_old;
+            mjd_up=mjdend_old;
+
+            Double_t x; Double_t xerr;
+            Double_t y; Double_t yerr;
+
+            if(!CalcPeakXY(&x,&y,&xerr,&yerr)) return kFALSE;
+            AddFSrcHist(islice,dt);
+
+            xpeak[islice]=x;
+            ypeak[islice]=y;
+            xpeakerr[islice]=xerr;
+            ypeakerr[islice]=yerr;
+
+            printf("\n TimeSlice %d   RunNo %d-%d  Mjd %f-%f  Dt=%f \n",islice,runno_lo,runno_up,mjd_lo,mjd_up,dt);
+            printf(" X=%f+-%f  Y=%f+-%f \n\n",x,xerr,y,yerr);
+            fprintf(fsrcpos,"%d %d %d %f %f %f %f %f %f %f\n",islice,runno_lo,runno_up,x,y,xerr,yerr,mjd_lo,mjd_up,dt);
+
+            FSrcHist.Reset();
+            dt=0.;
+
+            runno_lo=runno;
+            mjd_lo=mjdstart;
+
+            islice++;
+        }
+
+        dt+=t;
+        printf("Runno=%d  MjdStart=%f  MjdEnde=%f dt=%f \n",runno,mjdstart,mjdend,dt);
+        runno_old=runno;
+        mjdend_old=mjdend;
+    }
+
+
+    MHillasSrc hillas_src;
+    MSrcPosCam srcpos;
+
+    Double_t length=hil->GetLength();
+    Double_t width=hil->GetWidth();
+
+    // size cut
+    if(hil->GetSize()<SizeLo) return kTRUE;
+
+    // cuts in scaled length, width
+    if((length>LengthUp) || (length<LengthLo) || (width>WidthUp) || (width<WidthLo))
+        return kTRUE;
+
+    // cut in dist from camera center
+    srcpos.SetXY(0,0);
+    hillas_src.SetSrcPos(&srcpos);
+    hillas_src.Calc(hil);
+
+    Double_t dist=hillas_src.GetDist()*mm2deg;
+    if(dist>DistUp || dist<DistLo) return kTRUE;
+
+    // false source grid
+    for (Int_t i=0;i<nx;i++)
+        for (Int_t j=0;j<ny;j++)
+        {
+            Double_t x=(xmax-xmin)*Double_t(i)/Double_t(nx-1)+xmin;
+            Double_t y=(ymax-ymin)*Double_t(j)/Double_t(ny-1)+ymin;
+
+            srcpos.SetXY(x*deg2mm,y*deg2mm);
+            hillas_src.SetSrcPos(&srcpos);
+            hillas_src.Calc(hil);
+
+            if(TMath::Abs(hillas_src.GetAlpha())<alimit)
+                FSrcHist.Fill(x,y);
+
+        }
+
+    return kTRUE;
+}
+
+Int_t STrackPostProc()
+{
+    if(dt>0.001)
+    {
+        runno_up=runno_old;
+        mjd_up=mjdend_old;
+
+        Double_t x; Double_t xerr;
+        Double_t y; Double_t yerr;
+
+        if(!CalcPeakXY(&x,&y,&xerr,&yerr)) return kFALSE;
+        AddFSrcHist(islice,dt);
+
+        xpeak[islice]=x;
+        ypeak[islice]=y;
+        xpeakerr[islice]=xerr;
+        ypeakerr[islice]=yerr;
+
+        printf("\n TimeSlice %d   RunNo %d-%d  Mjd %f-%f  Dt=%f \n",islice,runno_lo,runno_up,mjd_lo,mjd_up,dt);
+        printf(" X=%f+-%f  Y=%f+-%f \n\n",x,xerr,y,yerr);
+        fprintf(fsrcpos,"%d %d %d %f %f %f %f %f %f %f\n",islice,runno_lo,runno_up,x,y,xerr,yerr,mjd_lo,mjd_up,dt);
+
+        islice++;
+    }
+
+    return kTRUE;
+}
+
+//----------------------------------------------------------------
+//----------------------------------------------------------------
+
+void SourceTrack(Int_t nent)
+{
+
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read("Events",fileHScaled);
+    read.DisableAutoScheme();
+
+    //TString runcuts("(MRawRunHeader.fRunNumber<17427)");
+    //runcuts+="|| (MRawRunHeader.fRunNumber>17428)";
+    //MContinue runsel(runcuts.Data());
+
+    MTaskInteractive strack;
+    strack.SetPreProcess(STrackPreProc);
+    strack.SetProcess(STrackProc);
+    strack.SetPostProcess(STrackPostProc);
+
+    tlist.AddToList(&read);
+    //tlist.AddToList(&runsel);
+    tlist.AddToList(&strack);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //------------------------------------------
+    // initializations
+
+    FSrcHist.SetDrawOption("colz");
+    FSrcHist.SetStats(kFALSE);
+
+    fpeak=new TF2("fpeak",gaus2d,-1,1,-1,1,6);
+    fsrcpos=fopen(fileSrcPos.Data(),"w");
+
+    //------------------------------------------
+    // standard eventloop
+
+    if (!evtloop.Eventloop(nent))
+        return;
+
+    tlist.PrintStatistics();
+
+    fclose(fsrcpos);
+
+    TFile file(fileFSrcPlot.Data(),"recreate");
+    FSrcArray.Write();
+    FSrcHist.Write();
+    file.Close();
+
+    const Int_t dim=islice;
+    TGraphErrors g(dim,xpeak.GetArray(),ypeak.GetArray(),
+                   xpeakerr.GetArray(),ypeakerr.GetArray());
+
+    //------------------------------------------
+    // canvas with complete hist
+    TCanvas *c1=new TCanvas("c1","",400,800);
+    gStyle->SetPalette(1);
+
+    c1->Divide(2,1);
+    c1->cd(1);
+    gPad->Update();
+
+    FSrcHist.Reset();
+    for(Int_t i=0;i<dim;i++)
+    {
+        TH2F *hptr = (TH2F*) (FSrcArray[i]);
+        FSrcHist.Add(hptr);
+    }
+
+    TString label=Form("Size>%f  ",SizeLo);
+    label+=Form("%f<Dist<%f  ",  DistLo,DistUp);
+    label+=Form("%f<Width<%f  " ,WidthLo,WidthUp);
+    label+=Form("%f<Length<%f  ",LengthLo,LengthUp);
+    label+=Form("|Alpha|<%f"  ,alimit);
+
+    FSrcHist.SetTitle(label.Data());
+    FSrcHist.GetXaxis()->SetTitle("X");
+    FSrcHist.GetYaxis()->SetTitle("Y");
+
+    FSrcHist.DrawClone("colz");
+    g.DrawClone("pl");
+
+    c1->cd(2);
+    gPad->Update();
+    g.GetXaxis()->SetRangeUser(-1.,1.);
+    g.GetYaxis()->SetRangeUser(-1.,1.);
+    g.DrawClone("apl");
+
+    //------------------------------------------
+    // canvas with slides
+    TCanvas *c2=new TCanvas("c2","",800,800);
+    gStyle->SetPalette(1);
+
+    Int_t n=Int_t(TMath::Ceil(sqrt(double(dim))));
+
+    c2->Divide(n,n);
+    for(Int_t i=0;i<dim;i++)
+    {
+        Int_t col=i/n;
+        Int_t row=i%n;
+        c2->cd(row*n+col+1);
+
+        gPad->Update();
+        TH2F *hptr = (TH2F*) (FSrcArray[i]);
+
+        TMarker m;
+        m.SetMarkerStyle(2);
+        m.SetMarkerSize(4);
+        m.SetMarkerColor(1);
+        m.SetX(xpeak[i]);
+        m.SetY(ypeak[i]);
+
+        hptr->DrawClone("colz");
+        m.DrawClone();
+    }
+
+    return;
+}
+
+//****************************************************************************************
+// second part: correct for moving source position
+//****************************************************************************************
+
+// initilizations
+
+Double_t dtref=0.;
+Int_t islice_old;
+Double_t dtref_old=0;
+
+Double_t xref = 0.; Double_t xreferr = 0.;
+Double_t yref = 0.; Double_t yreferr = 0.;
+
+MSrcPosCam *src=NULL;
+
+//----------------------------------------------------------------
+// Source Position Grid ------------------------------------------
+//----------------------------------------------------------------
+Int_t SCorrectPreProc(MParList *plist)
+{
+    hil = (MHillas*) plist->FindObject("MHillas");
+    src = (MSrcPosCam*) plist->FindCreateObj("MSrcPosCam");
+    run = (MRawRunHeader*) plist->FindObject("MRawRunHeader");
+
+    return (hil && run && src) ? kTRUE : kFALSE;
+}
+
+Int_t SCorrectProc()
+{
+    if(hil->GetSize()<=0.) return kTRUE;
+
+    Int_t runno    = run->GetRunNumber();
+    if(runno==0) return kTRUE;
+
+    Double_t mjdstart = (run->GetRunStart()).GetMjd();
+    Double_t mjdend   = (run->GetRunEnd()).GetMjd();
+    Double_t t=(mjdend-mjdstart)*24.*60.;
+
+    if(runno!=runno_old)
+    {
+        if((runno<runno_lo)||(runno>runno_up))
+        {
+            dt=t;
+
+            fscanf(fsrcpos,"%d %d %d %lf %lf %lf %lf %lf %lf %lf\n",&islice,&runno_lo,&runno_up,&xref,&yref,&xreferr,&yreferr,&mjd_lo,&mjd_up,&dtref);
+            printf("\nApplying correction for runs %d - %d (MJD %f - %f), DtRef=%f :\n",runno_lo,runno_up,mjd_lo,mjd_up,dtref);
+            printf("Source pos set to X=%f  Y=%f \n\n",xref,yref);
+
+            if(islice>0)
+            {
+                AddAPlot(islice_old,dtref_old);
+                APlot.Reset();
+            }
+            islice_old=islice;
+            dtref_old=dtref;
+        }
+        else
+        {
+            dt+=t;
+        }
+        printf("Runno=%d  MjdStart=%f  MjdEnde=%f Dt=%f \n",runno,mjdstart,mjdend,dt);
+        runno_old=runno;
+
+    }
+
+    src->SetXY(xref*deg2mm,yref*deg2mm);
+    src->SetReadyToSave();
+    // false source grid
+
+    MHillasSrc hillas_src;
+    MSrcPosCam srcpos;
+
+    Double_t length=hil->GetLength();
+    Double_t width =hil->GetWidth();
+
+    // size cut
+    if(hil->GetSize()<SizeLo) return kTRUE;
+
+    // cuts in scaled length, width
+    if((length>LengthUp) || (length<LengthLo) || (width>WidthUp) || (width<WidthLo))
+        return kTRUE;
+
+    // cut in dist from camera center
+    srcpos.SetXY(0,0);
+    hillas_src.SetSrcPos(&srcpos);
+    hillas_src.Calc(hil);
+
+    Double_t dist=hillas_src.GetDist()*mm2deg;
+    if(dist>DistUp || dist<DistLo) return kTRUE;
+
+    // fill 1-dim APlot for extracted source position
+    srcpos.SetXY(xref*deg2mm,yref*deg2mm);
+    hillas_src.SetSrcPos(&srcpos);
+    hillas_src.Calc(hil);
+    APlot.Fill(TMath::Abs(hillas_src.GetAlpha()));
+
+    // false source plot for corrected source movement
+    for (Int_t i=0;i<nx;i++)
+        for (Int_t j=0;j<ny;j++)
+        {
+            Double_t x=(xmax-xmin)*Double_t(i)/Double_t(nx-1)+xmin;
+            Double_t y=(ymax-ymin)*Double_t(j)/Double_t(ny-1)+ymin;
+
+            //printf("xref=%f  yref=%f \n",xref,yref);
+            srcpos.SetXY((x+xref)*deg2mm,(y+yref)*deg2mm);
+            hillas_src.SetSrcPos(&srcpos);
+            hillas_src.Calc(hil);
+
+            if(TMath::Abs(hillas_src.GetAlpha())<alimit)
+                FSrcHist.Fill(x,y);
+        }
+
+    return kTRUE;
+}
+
+Int_t SCorrectPostProc()
+{
+    AddAPlot(islice_old,dtref_old);
+
+    return kTRUE;
+}
+
+//----------------------------------------------------------------
+//----------------------------------------------------------------
+
+void SourceCorrect(Int_t nent)
+{
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadTree read("Events", fileHScaled);
+    read.DisableAutoScheme();
+
+    MTaskInteractive scorrect;
+    scorrect.SetPreProcess(SCorrectPreProc);
+    scorrect.SetProcess(SCorrectProc);
+    scorrect.SetPostProcess(SCorrectPostProc);
+
+    MHillasSrcCalc scalc;
+
+    MWriteRootFile write(fileHScaledC.Data());
+    write.AddContainer("MSrcPosCam",   "Events");
+    write.AddContainer("MHillas",      "Events");
+    write.AddContainer("MHillasExt",   "Events");
+    write.AddContainer("MHillasSrc",   "Events");
+    write.AddContainer("MNewImagePar", "Events");
+    write.AddContainer("MRawRunHeader","Events");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&scorrect);
+    tlist.AddToList(&scalc);
+    tlist.AddToList(&write);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //------------------------------------------
+    // standard eventloop
+
+    fsrcpos=fopen(fileSrcPos.Data(),"r");
+    if(!fsrcpos)
+    {
+        cout<<"fsrcpos does not exist!"<<endl;
+        return;
+    }
+
+    if (!evtloop.Eventloop(nent))
+        return;
+
+    tlist.PrintStatistics();
+
+    fclose(fsrcpos);
+
+
+    gStyle->SetPalette(1);
+    TFile file(fileFSrcPlotC.Data(),"recreate");
+    FSrcHist.Write();
+    APlotArray.Write();
+    file.Close();
+
+    //------------------------------------------
+    // canvas with complete hist
+    TCanvas *c=new TCanvas("c","",800,400);
+    c->cd();
+
+    TString label=Form("Size>%f  ",SizeLo);
+    label+=Form("%f<Dist<%f  ",  DistLo,DistUp);
+    label+=Form("%f<Width<%f  " ,WidthLo,WidthUp);
+    label+=Form("%f<Length<%f  ",LengthLo,LengthUp);
+    label+=Form("|Alpha|<%f"  ,alimit);
+
+    FSrcHist.SetTitle(label.Data());
+    FSrcHist.GetXaxis()->SetTitle("X");
+    FSrcHist.GetYaxis()->SetTitle("Y");
+
+    FSrcHist.DrawCopy("colz");
+
+    //------------------------------------------
+    // canvas with alpha hists
+    TCanvas *c2=new TCanvas("c2","",800,800);
+    gStyle->SetPalette(1);
+
+    const Int_t dim=islice+1;
+    Int_t n=Int_t(TMath::Ceil(sqrt(double(dim))));
+
+    c2->Divide(n,n);
+    for(Int_t i=0;i<dim;i++)
+    {
+        Int_t col=i/n;
+        Int_t row=i%n;
+        c2->cd(row*n+col+1);
+
+        gPad->Update();
+        TH1F *hptr = (TH1F*) (APlotArray[i]);
+
+        hptr->DrawClone();
+    }
+
+    return;
+}
+
+//****************************************************************************************
+// main
+//****************************************************************************************
+
+void SrcCorrect(Int_t icorrect,Int_t nent=-1)
+{
+
+    if(!icorrect)
+    {
+        // (re-) initilizations
+        islice=0;
+        runno_old=-1;
+        runno_lo=-1;
+        runno_up=-1;
+
+        dt=0;
+
+        mjd_lo=-1;
+        mjd_up=-1;
+
+        hil=NULL; run=NULL;
+
+        cout<<"Starting source track reconstruction."<<endl<<flush;
+        FSrcHist.Reset();
+        SourceTrack(nent);
+
+    }else{
+
+        // (re-) initilizations
+        islice=0;
+        runno_old=-1;
+        runno_lo=-1;
+        runno_up=-1;
+
+        dt=0;
+
+        mjd_lo=-1;
+        mjd_up=-1;
+
+        hil=NULL; run=NULL;
+
+        cout<<"Starting source correct."<<endl<<flush;
+        FSrcHist.Reset();
+        SourceCorrect(nent);
+    }
+
+    return;
+}
Index: /tags/Mars-V0.9/mtemp/meth/MDCA.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/MDCA.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/MDCA.cc	(revision 9772)
@@ -0,0 +1,281 @@
+
+
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Sebastian Commichau 05/2004 <mailto:commichau@particle.phys.ethz.ch>
+!   Author(s): Sabrina Stark       05/2004 <mailto:lstark@particle.phys.ethz.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+// Container to store the DCA stuff - it offers a nice draw option...                   
+
+
+#include "MDCA.h"
+
+using namespace std;
+
+ClassImp(MDCA); 
+
+// Default constructor
+MDCA::MDCA(const char *name, const char *title) : fXRef(0.0), fYRef(0.0)
+{
+    fName = name ? name : "MDCA";
+    fTitle = title ? title : "Storage container for Hillas parameters and DCA of one event";
+ 
+    Reset();
+   
+    fEllipse = new TEllipse;
+    fRefCircle = new TEllipse;
+    
+    fLineL = new TLine;
+    fLineW = new TLine;
+    fLineX = new TLine;
+    fLineY = new TLine;
+    fLineDCA = new TLine;
+    fLineMean = new TLine;
+  
+}
+
+// Destructor: Deletes ellipse and lines if they do exist
+
+MDCA::~MDCA()
+{
+    Clear();
+}
+
+// Initialize parameters with default values
+
+void MDCA::Reset()
+{
+
+    fLength = -1;
+    fWidth  = -1;
+    fDelta0 =  0;
+    fMeanX  =  0;
+    fMeanY  =  0;
+    fDelta1 =  0;
+    fDCA    = -1;
+    fX1W    =  0;
+    fY1W    =  0;
+    fX2W    =  0;
+    fY2W    =  0;
+    fX1L    =  0;
+    fY1L    =  0;
+    fX2L    =  0;
+    fY2L    =  0;
+    fXDCA   =  0;
+    fYDCA   =  0;
+  
+}
+
+
+// Print parameters to *fLog
+
+void MDCA::Print(Option_t *) const
+{
+    Double_t atg = atan2(fMeanY, fMeanX)*kRad2Deg;
+
+    if (atg<0)
+        atg += 180;
+
+    *fLog << all;
+    *fLog << "Basic Image Parameters (" << GetName() << ")" << endl;
+    *fLog << " - Length      [mm]  = " << fLength << endl;
+    *fLog << " - Width       [mm]  = " << fWidth  << endl;
+    *fLog << " - Delta0      [deg] = " << fDelta0*kRad2Deg << endl;
+    *fLog << " - Meanx       [mm]  = " << fMeanX  << endl;
+    *fLog << " - Meany       [mm]  = " << fMeanY  << endl;
+    *fLog << " - atg(y/x)    [deg] = " << atg     << endl;
+    *fLog << " - DCA         [mm]  = " << fDCA << endl;
+    *fLog << " - Delta1      [deg] = " << fDelta1*kRad2Deg << endl;
+
+    
+}
+
+void MDCA::Paint(Option_t *opt)
+{
+    Clear();
+
+    if (fLength<=0 || fWidth<=0) //fLength<0 || fWidth<0 doesn't look nice...
+        return;                  //We get a circle!
+
+    // Length line
+    fLineL = new TLine(fX1L, fY1L, fX2L, fY2L);
+    fLineL->SetLineWidth(2);
+    fLineL->SetLineColor(2);
+    fLineL->Draw();
+
+    // Width line
+    fLineW = new TLine(fX1W, fY1W, fX2W, fY2W);
+    fLineW->SetLineWidth(2);
+    fLineW->SetLineColor(2);
+    fLineW->Draw();
+
+    // Coordinate system
+    fLineX = new TLine(-600,fYRef,600,fYRef);
+    fLineY = new TLine(fXRef,-600,fXRef,600);
+    fLineX->SetLineWidth(2);
+    fLineX->SetLineColor(1);
+    fLineY->SetLineWidth(2);
+    fLineY->SetLineColor(1);
+    fLineX->Draw();
+    fLineY->Draw();
+    
+    // DCA line
+    fLineDCA = new TLine(fXRef,fYRef,fXDCA+fXRef,fYDCA+fYRef);
+    fLineDCA->SetLineWidth(2);
+    fLineDCA->SetLineColor(2);
+    fLineDCA->Draw();
+
+    // COG line
+    fLineMean = new TLine(fXRef,fYRef,fMeanX,fMeanY);
+    fLineMean->SetLineWidth(2);
+    fLineMean->SetLineColor(2);
+    fLineMean->Draw();
+
+    // Reference point marker
+    fRefCircle = new TEllipse(fXRef, fYRef, 5, 5, 0, 360, 0);
+    fRefCircle->SetLineColor(8);
+    fRefCircle->SetFillColor(8);
+    fRefCircle->Draw();
+
+    // Hillas ellipse
+    fEllipse = new TEllipse(fMeanX, fMeanY, fLength, fWidth, 0, 360, fDelta0*kRad2Deg+180);
+    fEllipse->SetLineWidth(2);
+    fEllipse->SetLineColor(2);
+    fEllipse->Draw();
+
+}
+
+
+// If an ellipse and lines exist they will be deleted 
+
+void MDCA::Clear(Option_t *)
+{
+    if (!fEllipse && !fRefCircle && !fLineL && !fLineW && !fLineX && !fLineY && !fLineDCA && !fLineMean) 
+        return;
+ 
+    delete fEllipse;
+    delete fRefCircle;
+    delete fLineL;
+    delete fLineW;
+    delete fLineX;
+    delete fLineY;
+    delete fLineDCA;
+    delete fLineMean;
+     
+    fLineL = NULL;
+    fLineX = NULL;
+    fLineY = NULL;
+    fLineW = NULL;
+    fLineDCA = NULL;
+    fLineMean = NULL;
+    fEllipse = NULL;
+    fRefCircle = NULL;
+}
+
+
+Int_t MDCA::Calc(const MGeomCam &geom, const MCerPhotEvt &evt, const MHillas &hil)
+{
+    // Get basic Hillas parameters from MHillas
+    fDelta0 = hil.GetDelta();
+    fMeanX  = hil.GetMeanX();
+    fMeanY  = hil.GetMeanY();
+    fLength = hil.GetLength();
+    fWidth  = hil.GetWidth();
+
+    // The Length Line - rotation and shift
+    fX1L = - (fLength+OffsetL)*cos(fDelta0) + fMeanX; // [mm]    
+    fY1L = - (fLength+OffsetL)*sin(fDelta0) + fMeanY; // [mm]    
+    fX2L =   (fLength+OffsetL)*cos(fDelta0) + fMeanX; // [mm]    
+    fY2L =   (fLength+OffsetL)*sin(fDelta0) + fMeanY; // [mm]
+
+    // The Width Line - rotation and shift
+    fX1W =   (fWidth+OffsetW)*sin(fDelta0) + fMeanX;  // [mm]   
+    fY1W = - (fWidth+OffsetW)*cos(fDelta0) + fMeanY;  // [mm]   
+    fX2W = - (fWidth+OffsetW)*sin(fDelta0) + fMeanX;  // [mm]   
+    fY2W =   (fWidth+OffsetW)*cos(fDelta0) + fMeanY;  // [mm]  
+
+    // Vector of orientation of the shower axis
+    fr1 = fX2L-fX1L;  
+    fr2 = fY2L-fY1L;  
+       
+    // Determine parameters to calculate coordinates of the DCA vector
+    flambda = (fr1*(fXRef-fMeanX) + fr2*(fYRef-fMeanY))/(fr1*fr1 + fr2*fr2);
+    fmu = (fMeanY-fYRef)/fr1 + flambda*fr2/fr1;
+
+    // Components of the DCA vector
+    fXDCA = -fmu*fr2;
+    fYDCA =  fmu*fr1;
+  
+    // Components of vector going from intersection point of the DCA vector
+    // with the shower axis to the COG
+    fd1 = fMeanX + fmu*fr2 - fXRef;
+    fd2 = fMeanY - fmu*fr1 - fYRef;
+
+    // Calculate DCA value 
+    fDCA = sqrt(fXDCA*fXDCA + fYDCA*fYDCA);
+
+    // Calculate angle of the shower axis with respect to the x-axis
+    fDelta1 = acos(fd1/sqrt(fd1*fd1 + fd2*fd2));
+
+    // Calculate angle of the shower axis with respect to the y-axis
+    //fDelta1 = acos(fd2/sqrt(fd1*fd1 + fd2*fd2)); 
+
+    // Determine the correct sign of the DCA (cross product of DCA vector and 
+    // vector going from the intersection point of the DCA vector with the shower axis
+    // to the COG)
+    if((fmu*(-fr2*(fMeanY-fYRef)-fr1*(fMeanX-fXRef)))<0)
+       fDCA = -fDCA;    
+
+    gRandom->Rannor(gx,gy);
+    gx = fabs(gx);
+  
+    // This is nice but does not remove the systematics in the profile plot...
+    //if(((1-0.6*gx)*(180-kRad2Deg*fDelta1)>120) || ((1-0.6*gx)*kRad2Deg*fDelta1>120))
+      // fDCA = -1;
+
+    // Enlarge the interval of Delta correctly...
+    if((fMeanY-fYRef-fmu*fr1)<0)
+       fDelta1 = TwoPi-fDelta1;
+
+    // Enlarge the interval of Delta correctly... (Delta with respect to the y-axis)
+    // if(-(fMeanX-fXRef+fmu*fr2)<0)
+     //  fDelta1 = TwoPi-fDelta1;
+
+    // This has to be improved...
+    if(fr1 == 0 || fr2 == 0 || (fr1*fr1+fr2*fr2) == 0 || sqrt(fd1*fd1+fd2*fd2) == 0)
+       fDCA = -fDCA;
+
+    SetReadyToSave();
+   
+    return 0;
+}
+
+void MDCA::SetRefPoint(const Float_t fXRef0, const Float_t fYRef0)
+{
+    fXRef = fXRef0;
+    fYRef = fYRef0;
+}
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/meth/MDCA.h
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/MDCA.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/MDCA.h	(revision 9772)
@@ -0,0 +1,109 @@
+#ifndef MARS_MDCA 
+#define MARS_MDCA
+
+
+#include <TArrayF.h>
+#include <TEllipse.h>
+#include <TLine.h>
+#include <TCanvas.h>
+#include <TROOT.h>
+#include <TStyle.h> 
+#include <TMath.h>
+#include <math.h>
+#include <TPad.h>
+#include <TRandom.h>
+#include <TRandom2.h>
+#include <fstream>
+#include <iostream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+#include "MHillas.h"
+
+// Add offsets to the Width and Length to draw nice lines
+#define OffsetW 20.0
+#define OffsetL 440.0
+
+#define kmm2Deg 0.00317460317
+#define TwoPi 6.28318530717958623 
+
+class TArrayF;
+class TEllipse;
+class MGeoCam;
+class MCerPhotEvt;
+class MHillas;
+
+class MDCA : public MParContainer
+{
+ private:
+    
+    Float_t fLength;  // [mm]   major axis of ellipse
+    Float_t fWidth;   // [mm]   minor axis of ellipse
+    Float_t fDelta0;  // [rad]  angle of major axis with x-axis (-Pi/2 .. Pi/2)
+    Float_t fDelta1;  // [rad]  my angle of major axis with x-axis (0 .. 2*Pi)
+    Float_t fMeanX;   // [mm]   x-coordinate of center of ellipse
+    Float_t fMeanY;   // [mm]   y-coordinate of center of ellipse
+    Float_t fX1W;     // [mm]   x-coordinate of 1st point of Lline
+    Float_t fY1W;     // [mm]   y-coordinate of 1st point of Lline
+    Float_t fX2W;     // [mm]   x-coordinate of 2nd point of Lline
+    Float_t fY2W;     // [mm]   y-coordinate of 2nd point of Lline
+    Float_t fX1L;     // [mm]   x-coordinate of 1st point of Wline
+    Float_t fY1L;     // [mm]   y-coordinate of 1st point of Wline
+    Float_t fX2L;     // [mm]   x-coordinate of 2nd point of Wline
+    Float_t fY2L;     // [mm]   y-coordinate of 2nd point of Wline
+    Double_t fDCA;    // [mm]   Distance of Cloasest Approach 
+    Float_t fXDCA;    // [mm]   x-coordinate of 2nd point of the DCA-line 
+    Float_t fYDCA;    // [mm]   y-coordinate of 2nd point of the DCA-line  
+    Float_t fXRef;    // [mm]   x-coordinate of reference point
+    Float_t fYRef;    // [mm]   y-coordinate of reference point
+    Float_t fmu;
+    Float_t flambda;  
+    Float_t fr1, fr2; // [mm] Coordinates of the orientation vector of the shower axis
+    Float_t fd1, fd2; // [mm] Coordinates of the DCA vector
+    Float_t gx, gy;
+   
+    TEllipse *fEllipse;   // Graphical object to draw the ellipse, ROOT!
+    TEllipse *fRefCircle; // To draw reference point
+
+    TLine *fLineL;        // Shower axis
+    TLine *fLineW;        // Line perpendicular to the shower axis
+    TLine *fLineX;        // x-axis of the coordinate system 
+    TLine *fLineY;        // y-axis of the coordinate system  
+    TLine *fLineDCA;      // DCA line
+    TLine *fLineMean;     // Line to COG of the shower 
+
+ public:
+    MDCA(const char *name=NULL, const char *title=NULL);
+
+    ~MDCA();
+
+    void Reset();
+
+    Int_t Calc(const MGeomCam &geom, const MCerPhotEvt &pix, const MHillas &hil);
+
+    void Print(Option_t *opt=NULL) const;
+
+    void Paint(Option_t *opt=NULL);
+
+    void Clear(Option_t *opt=NULL);
+
+    void SetRefPoint(const Float_t fXRef0, const Float_t fYRef0);
+    
+    Float_t GetDCA() const { return fDCA; }
+ 
+    Float_t GetDelta() const { return fDelta1; }
+
+    ClassDef(MDCA, 1) 
+
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/meth/MDCACalc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/MDCACalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/MDCACalc.cc	(revision 9772)
@@ -0,0 +1,118 @@
+
+
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Sebastian Commichau 05/2004 <mailto:commichau@particle.phys.ethz.ch>
+!   Author(s): Sabrina Stark       05/2004 <mailto:lstark@particle.phys.ethz.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+//Task to calculate the DCA parameter
+
+
+#include "MDCACalc.h"
+
+ClassImp(MDCACalc);
+
+using namespace std; 
+
+MDCACalc::MDCACalc(const char *name, const char *title)
+    : fDCAName("MDCA"), fFlags(0xff)
+{
+    fName  = name  ? name  : "MDCACalc";
+    fTitle = title ? title : "Calculate Hillas, DCA and other image parameters";
+    
+}
+
+Int_t MDCACalc::PreProcess(MParList *pList)
+{
+    fErrors = 0;
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fCerPhotEvt)
+    {
+        *fLog << err << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHillas = (MHillas*)pList->FindObject(AddSerialNumber("MHillas"));
+    if (!fHillas)
+    {
+        *fLog << err << "MHillas missing in Parameter List... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (TestFlag(kCalcDCA))
+        fMDCA = (MDCA*)pList->FindCreateObj("MDCA", AddSerialNumber(fDCAName));
+    else
+    {
+        fMDCA = (MDCA*)pList->FindObject(AddSerialNumber(fDCAName), "MDCA");
+        *fLog << err << fDCAName << " [MDCA] not found... aborting." << endl;
+    }
+    if (!fMDCA)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// If the calculation wasn't sucessfull skip this event
+
+Int_t MDCACalc::Process()
+{
+
+    if (TestFlag(kCalcDCA))
+    {
+        Int_t rc = fMDCA->Calc(*fGeomCam, *fCerPhotEvt, *fHillas);
+          
+
+	if (rc == -1)
+        {
+	    fErrors++;
+            *fLog << err << dbginf << "MDCA::Calc returned ... error!" << endl;
+            return kFALSE;
+        }
+   }
+   
+    return kTRUE;
+}
+
+Int_t MDCACalc::PostProcess()
+{
+
+    *fLog << fErrors << " errors occured..." << endl;
+    *fLog << endl;
+
+    return kTRUE;
+} 
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/meth/MDCACalc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/MDCACalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/MDCACalc.h	(revision 9772)
@@ -0,0 +1,60 @@
+
+#ifndef MARS_MDCACalc
+#define MARS_MDCACalc
+
+#include "MTask.h"
+#include "MParList.h"
+#include "MDCA.h"
+#include "MCerPhotEvt.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MHillasCalc.h"
+
+class MGeomCam;
+class MCerPhotEvt;
+class MDCA;
+
+class MDCACalc : public MTask
+{
+    const MGeomCam    *fGeomCam;    // Camera Geometry used to calculate Hillas
+    const MCerPhotEvt *fCerPhotEvt; // Cerenkov Photon Event used for calculation
+    const MHillas     *fHillas;
+
+    MDCA        *fMDCA;  // Output container to store the result
+
+    TString      fDCAName;
+
+    Double_t par[6];
+    Double_t dca;
+
+    Int_t    fErrors;
+    Int_t    fFlags;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+     enum CalcCont_t {
+        kCalcDCA      = BIT(0),
+    };
+
+     MDCACalc(const char *name=NULL, const char *title=NULL);
+
+    void SetNameDCA(const char *name)    { fDCAName = name; }
+
+    void SetFlags(Int_t f) { fFlags  =  f; }
+    void Enable(Int_t f)   { fFlags |=  f; }
+    void Disable(Int_t f)  { fFlags &= ~f; }
+    Bool_t TestFlag(CalcCont_t i) const { return fFlags&i; }
+    
+    
+    ClassDef(MDCACalc, 0) // Task to calculate DCA 
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/meth/MHillasSrc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/MHillasSrc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/MHillasSrc.cc	(revision 9772)
@@ -0,0 +1,231 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz        12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Harald Kornmayer    01/2001
+!   Author(s): Rudolf Bock         10/2001 <mailto:Rudolf.Bock@cern.ch>
+!   Author(s): Wolfgang Wittek     06/2002 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Sabrina Stark       05/2004 <mailto:stark@particle.phys.ethz.ch> 
+!   Author(s): Sebastian Commichau 05/2004 <mailto:commichau@particle.phys.ethz.ch>  
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHillasSrc
+//
+// Storage Container for image parameters
+//
+//    source-dependent image parameters
+//
+//
+// Version 1:
+// ----------
+//  fAlpha          angle between major axis and line source-to-center
+//  fDist           distance from source to center of ellipse
+//
+//
+// Version 2:
+// ----------
+//  fHeadTail       added
+//
+//
+// Version 3:
+// ----------
+//  fCosDeltaAlpha  cosine of angle between d and a, where
+//                   - d is the vector from the source position to the
+//                     center of the ellipse
+//                   - a is a vector along the main axis of the ellipse,
+//                     defined with positive x-component
+//
+//
+// Version 4:
+// ----------
+//
+// fHeadTail        removed
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHillasSrc.h"
+
+#include <fstream>
+#include <TArrayF.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+
+ClassImp(MHillasSrc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillasSrc::MHillasSrc(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHillasSrc";
+    fTitle = title ? title : "Parameters depending in source position";
+}
+
+void MHillasSrc::Reset()
+{
+    fDist          = -1;
+    fAlpha         =  0;
+    fCosDeltaAlpha =  0;
+    fDCA           =  0;
+    fDDCA           = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of source-dependent parameters
+//  In case you don't call Calc from within an eventloop make sure, that
+//  you call the Reset member function before.
+//
+Bool_t MHillasSrc::Calc(const MHillas *hillas)
+{
+    const Double_t mx = hillas->GetMeanX();     // [mm]
+    const Double_t my = hillas->GetMeanY();     // [mm]
+
+    const Double_t sx = mx - fSrcPos->GetX();   // [mm]
+    const Double_t sy = my - fSrcPos->GetY();   // [mm]
+
+    //
+    // DCA: Distance of Closest Approach.
+    // Minimal distance from the shower axis to a reference point.
+
+    Double_t fDdca = hillas->GetDelta();
+    
+    // Distance between intersection point (DCA vector and the shower axis) and COG.
+    const Double_t fl = -(sx*TMath::Cos(fDdca) + sy*TMath::Sin(fDdca));
+
+    // Components of DCA vector
+    const Double_t fpd1 = TMath::Cos(fDdca)*fl+sx;
+    const Double_t fpd2 = TMath::Sin(fDdca)*fl+sy;
+
+    // Calculate DCA value 
+    Double_t fdca = sqrt(fpd1*fpd1 + fpd2*fpd2);
+
+    // Determine the correct sign of the DCA (cross product of DCA vector and the
+    // vector going from the intersection point of the DCA vector with the shower axis
+    // to the COG)
+    if ((sx-fpd1)*fpd2-(sy-fpd2)*fpd1<0.)
+      fdca = -fdca;
+
+    // Calculate angle of the shower axis with respect to the x-axis
+    fDdca = TMath::ACos((sx-fpd1)/TMath::Abs(fl));
+
+    // Enlarge the interval of fDdca to [0, 2pi]
+    if((sy-fpd2)<0)
+       fDdca = 360/kRad2Deg-fDdca;
+
+
+    //
+    // Distance from source position to center of ellipse.
+    // If the distance is 0 distance, Alpha is not specified.
+    // The calculation has failed and returnes kFALSE.
+    //
+    const Double_t dist = sqrt(sx*sx + sy*sy);  // [mm]
+    if (dist==0)
+        return kFALSE;
+
+    // Calculate Alpha and Cosda = cos(d,a)
+    // The sign of Cosda will be used for quantities containing 
+    // a head-tail information
+    //
+    // *OLD* const Double_t arg = (sy-tand*sx) / (dist*sqrt(tand*tand+1));
+    // *OLD* fAlpha = asin(arg)*kRad2Deg;
+    //
+    //    const Double_t arg1 = cd*sy-sd*sx;          // [mm]  ... equal abs(fdca)
+    //    const Double_t arg2 = cd*sx+sd*sy;          // [mm]  ... equal abs(fl)
+    const Double_t arg1 = TMath::Abs(fdca);          // [mm]  
+    const Double_t arg2 = TMath::Abs(fl);          // [mm] 
+
+    //
+    // Due to numerical uncertanties in the calculation of the
+    // square root (dist) and arg1 it can happen (in less than 1e-5 cases)
+    // that the absolute value of arg exceeds 1. Because this uncertainty
+    // results in an Delta Alpha which is still less than 1e-3 we don't care
+    // about this uncertainty in general and simply set values which exceed
+    // to 1 saving its sign.
+    //
+    const Double_t arg = arg1/dist;
+    fAlpha = TMath::Abs(arg)>1 ? TMath::Sign(90., arg) : asin(arg)*kRad2Deg;  // [deg]
+
+    fCosDeltaAlpha = arg2/dist;                 // [1]
+    fDist          = dist;                      // [mm]
+    fDCA = fdca;                                // [mm]
+    fDDCA = fDdca;                              // [rad]
+
+    SetReadyToSave();
+
+    return kTRUE;
+} 
+
+// --------------------------------------------------------------------------
+//
+// Print contents of MHillasSrc to *fLog
+//
+void MHillasSrc::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Source dependant Image Parameters (" << GetName() << ")" << endl;
+    *fLog << " - Dist           [mm]  = " << fDist << endl;
+    *fLog << " - Alpha          [deg] = " << fAlpha << endl;
+    *fLog << " - CosDeltaAlpha        = " << fCosDeltaAlpha << endl;
+    *fLog << " - DCA            [mm]  = " << fDCA << endl;
+    *fLog << " - DeltaDCA       [mm]  = " << fDDCA << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print contents of MHillasSrc to *fLog depending on the geometry in
+// units of deg.
+//
+void MHillasSrc::Print(const MGeomCam &geom) const
+{
+    *fLog << all;
+    *fLog << "Source dependant Image Parameters (" << GetName() << ")" << endl;
+    *fLog << " - Dist           [deg] = " << fDist*geom.GetConvMm2Deg() << endl;
+    *fLog << " - Alpha          [deg] = " << fAlpha << endl;
+    *fLog << " - CosDeltaAlpha        = " << fCosDeltaAlpha << endl;
+    *fLog << " - DCA            [deg] = " << fDCA*geom.GetConvMm2Deg() << endl;
+    *fLog << " - DeltaDCA       [mm]  = " << fDDCA << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// This function is ment for special usage, please never try to set
+// values via this function
+//
+void MHillasSrc::Set(const TArrayF &arr)
+{
+    if (arr.GetSize() != 5)
+        return;
+
+    fAlpha = arr.At(0);         // [deg]  angle of major axis with vector to src
+    fDist  = arr.At(1);         // [mm]   distance between src and center of ellipse
+    fCosDeltaAlpha = arr.At(2); // [1]    cosine of angle between d and a
+    fDCA   = arr.At(3);         // [mm]   distance between ref. point and shower axis
+    fDDCA   = arr.At(4);         // [rad] angle between shower axis and x-axis
+}
Index: /tags/Mars-V0.9/mtemp/meth/MHillasSrc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/MHillasSrc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/MHillasSrc.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MHillasSrc
+#define MARS_MHillasSrc
+
+#ifndef MARS_MHillas
+#include "MHillas.h"
+#endif
+
+class MSrcPosCam;
+
+class MHillasSrc : public MParContainer
+{
+private:
+    const MSrcPosCam *fSrcPos; //! Source position in the camere
+
+    Float_t fAlpha;         // [deg]  angle of major axis with vector to src
+    Float_t fDist;          // [mm]   distance between src and center of ellipse
+    Float_t fDCA;          // [mm]   distance between ref. point and shower axis
+    Float_t fDDCA;          // [rad]  angle between major axis and x-axis [0, 2*pi]
+    Float_t fCosDeltaAlpha; // [1]    cosine of angle between d and a
+
+public:
+    MHillasSrc(const char *name=NULL, const char *title=NULL);
+
+    void SetSrcPos(const MSrcPosCam *pos) { fSrcPos = pos; }
+    const MSrcPosCam *GetSrcPos() const   { return fSrcPos; }
+
+    void Reset();
+
+    Float_t GetAlpha()         const { return fAlpha; }
+    Float_t GetDist()          const { return fDist; }
+    Float_t GetDCA()          const { return fDCA; }
+    Float_t GetDDCA()          const { return fDDCA; }
+    Float_t GetCosDeltaAlpha() const { return fCosDeltaAlpha; }
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+
+    virtual Bool_t Calc(const MHillas *hillas);
+
+    void Set(const TArrayF &arr);
+
+    ClassDef(MHillasSrc, 5) // Container to hold source position dependant parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/meth/macros/CorrectSrcPos.C
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/macros/CorrectSrcPos.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/macros/CorrectSrcPos.C	(revision 9772)
@@ -0,0 +1,359 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Luisa Sabrina Stark Schneebeli, 07/2004 <stark@particle.phys.ethz.ch>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!   This macro is partially derived from findstars.C
+\* ======================================================================== */
+
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+
+void CorrectSrcPos(const TString filename="dc_2004_04_21_22_*_Mrk421.root", const TString directory="/scratch/Period016/cacodata/2004_04_22/", const UInt_t numEvents = 0)
+{
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MStarLocalCam starcam;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&starcam);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+
+  MGeomApply geomapl;
+  TString continuoslightfile = 
+    "/scratch/Period016/cacodata/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  
+
+  const Int_t numblind = 12;
+  const Short_t x[numblind] = {  8,  27,
+                               507, 508, 509, 510, 511,
+                               543, 559, 560, 561, 567};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 3.5;
+  UInt_t integratedevents = 5;
+
+  MFindStars findstars;
+  //  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(0);
+
+  findstars.SetSourceRaH(11);   //  Mrk421
+  findstars.SetSourceRaM(4);
+  findstars.SetSourceRaS(26.0);
+  findstars.SetSourceDecD(38);
+  findstars.SetSourceDecM(12);
+  findstars.SetSourceDecS(36.0);
+
+
+  // prints
+  MPrint pdc("MCameraDC");
+  MPrint pstar("MStarLocalCam");
+  
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal);
+  //  tlist.AddToList(&pdc, "Currents");
+  tlist.AddToList(&findstars, "Currents");
+  //  tlist.AddToList(&pstar, "Currents");
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  const Int_t numpar = 3;
+  Float_t starpos[10*numpar];       
+  Float_t starposcat[10*numpar];       
+  
+  if (numEvents > 0)
+  {
+      if (!evtloop.Eventloop(numEvents))
+	  return;
+  }
+  else
+  {
+      if (!evtloop.PreProcess())
+	  return;
+      
+       MHCamera display(geomcam);
+       display.SetPrettyPalette();
+       
+       TCanvas *c = new TCanvas("c", "FindStars", 100, 100,600,600); 
+       
+       TH2D *h0 = new TH2D("h0","",1,-2,2,1,-2,2);
+       h0->GetXaxis()->SetTitle("(deg)");
+       h0->GetYaxis()->SetTitle("(deg)");
+       h0->Draw();
+       
+       display.Draw();
+       gPad->cd(1);
+       //display.Draw("same");
+       starcam.Draw();
+
+       UShort_t year;
+       Byte_t month, day;
+
+       MTime *evttime = (MTime*)plist->FindObject("MTimeCurrents");
+
+       TList *starcatalog = new TList;
+       TList *stardc = new TList;
+       TVector3 *res = new TVector3;
+
+       Int_t maxdist = 100;
+       UInt_t numevents=0;
+       Int_t numEvt=0;
+       const Int_t maxnumEvt = 10000;
+       Int_t col = 2;
+       const Double_t kDeg2mm = 189/0.6;
+
+       Double_t resx[maxnumEvt];
+       Double_t resy[maxnumEvt];
+       Double_t time[maxnumEvt];
+
+       
+//
+// Find in the file name the date, run and project name 
+
+       Size_t pos = filename.Last('/');
+       TString iRun = TString(filename(pos+24,5));
+       TString iYear = TString(filename(pos+4,4));
+       TString iMonth = TString(filename(pos+9,2));
+       TString iDay = TString(filename(pos+12,2));
+       
+       TString iHour = TString(filename(pos+15,2));
+       TString iMin = TString(filename(pos+18,2));
+       TString iSec = TString(filename(pos+21,2));
+       
+       Size_t poslast = filename.Last('.');
+       Size_t posfirst = poslast-1;
+       while (filename[posfirst] != '_')
+	 posfirst--;
+       
+       TString iSource = TString(filename(posfirst+1,poslast-posfirst-1));
+       char str[100];
+       char str2[100];
+       sprintf(str,"Date %s %s %s  Run %s   Source %s",iYear.Data(),iMonth.Data(),iDay.Data(),iRun.Data(),iSource.Data());
+       sprintf(str2,"CorrectSrcPos_%s%s%s_%s_%s.txt",iYear.Data(),iMonth.Data(),iDay.Data(),iRun.Data(),iSource.Data());
+       
+       UInt_t evtyear, evtmonth, evtday, evthour, evtmin, evtsec;
+       UShort_t evtmsec;
+
+       ofstream fposout1;
+       //       fposout1.open (str2, ofstream::app);
+       fposout1.open (str2, ofstream::trunc);
+
+       while (tlist.Process())
+         {
+           if (numevents >= integratedevents)
+             {
+	       evttime->GetTime(evthour, evtmin, evtsec,evtmsec);
+	       evttime->Print();
+	       evthour = evttime->Hour();
+	       evtmin = evttime->Min();
+	       evtsec = evttime->Sec();
+
+               //               display.SetCamContent(dccam);
+               display.SetCamContent(findstars.GetDisplay());
+	       gPad->Modified();
+	       gPad->Update();
+	       Int_t numStars = starcam.GetNumStars();
+	       starcam.Print("bkmaxposrotsizechi");
+
+	       res = findstars.GetCorrSrcPos();
+	       cout<<"Corrected source position = "<<res->X()<<" , "<<res->Y()<<endl;
+	       resx[numEvt] = res->X();
+	       resy[numEvt] = res->Y();
+	       time[numEvt] = numEvt;
+	       numEvt ++;
+
+	       // write the corrected source position and the star positions to file
+	       if (!fposout1)
+		 cout << "Could not open output file to write the center of the fit." << endl;
+	       else{
+		 for ( Int_t i = 0; i < numStars; i++)
+		   {
+		     if (i == 0){
+		       fposout1 << str<<" "<<evthour<< " "<<evtmin<<" "<<evtsec<<" "<<evtmsec;
+		       fposout1 <<" "<< res->X()<< " " << res->Y();
+		     }
+		     fposout1 <<" "<< starcam[i].GetMeanX()<< " " << starcam[i].GetMeanY();
+		   }
+		 }
+	       fposout1 << endl;
+	       numevents = 0;
+
+               // Remove the comments if you want to go through the file
+               // event-by-event:
+	       //if (!HandleInput())
+	       // break;
+             }
+           numevents++;
+	 } 
+       fposout1.close();
+
+       // Print source position
+       gROOT->Reset();
+       gStyle->SetCanvasColor(0);
+       gStyle->SetCanvasBorderMode(0);
+       gStyle->SetPadBorderMode(0);
+       gStyle->SetFrameBorderMode(0);
+       gStyle->SetOptStat(00000000);
+
+       TCanvas *c1 = new TCanvas("c1", "SourcePosition", 200, 200,600,1200); 
+       c1->Divide(1,3);
+
+       TMath math;
+    
+       Double_t minresx, maxresx;
+       minresx = resx[math.LocMin(numEvt,resx)];
+       maxresx = resx[math.LocMax(numEvt,resx)];
+       
+       Double_t minresy, maxresy;
+       minresy = resy[math.LocMin(numEvt,resy)];
+       maxresy = resy[math.LocMax(numEvt,resy)];
+       
+       Double_t minres, maxres;
+       minres = math.Min(minresx,minresy);
+       maxres = math.Max(maxresx,maxresy);
+
+       Double_t diff;
+       diff = maxres - minres;
+       diff = 0.1*diff;
+       minres = minres - diff;
+       maxres = maxres + diff;
+
+       Double_t mintime, maxtime;
+       mintime = time[math.LocMin(numEvt,time)];
+       maxtime = time[math.LocMax(numEvt,time)];
+
+       c1->cd(1);
+       TH2D *h1 = new TH2D("h1","",1,mintime-1,maxtime+1,1,minres,maxres);
+       h1->GetXaxis()->SetTitle("(evt.nr)");
+       h1->GetYaxis()->SetTitle("(mm)");
+       h1->Draw();
+
+       TGraph *grtimeevolx = new TGraph(numEvt,time,resx);
+       grtimeevolx->SetMarkerColor(215);
+       grtimeevolx->SetMarkerStyle(20);
+       grtimeevolx->SetMarkerSize (0.4);
+       grtimeevolx->Draw("P");
+       
+       TGraph *grtimeevoly = new TGraph(numEvt,time,resy);
+       grtimeevoly->SetMarkerColor(6);
+       grtimeevoly->SetMarkerStyle(24);
+       grtimeevoly->SetMarkerSize (0.4);
+       grtimeevoly->Draw("P");
+       
+       legxy = new TLegend(0.8,0.85,0.95,0.95);
+       legxy.SetTextSize(0.03);
+       legxy.AddEntry(grtimeevolx,"src pos x","P");
+       legxy.AddEntry(grtimeevoly,"src pos y","P");
+       legxy.Draw();
+
+       c1->cd(2);
+       TH2D *h2 = new TH2D("h2","",1,mintime-1,maxtime+1,1,minresx,maxresx);
+       h2->GetXaxis()->SetTitle("(evt.nr)");
+       h2->GetYaxis()->SetTitle("(mm)");
+       h2->Draw();
+
+       TGraph *grtimeevolx = new TGraph(numEvt,time,resx);
+       grtimeevolx->SetMarkerColor(215);
+       grtimeevolx->SetMarkerStyle(20);
+       grtimeevolx->SetMarkerSize (0.4);
+       grtimeevolx->Draw("P");
+       
+       legxy = new TLegend(0.8,0.85,0.95,0.95);
+       legxy.SetTextSize(0.03);
+       legxy.AddEntry(grtimeevolx,"src pos x","P");
+       legxy.Draw();
+
+       c1->cd(3);
+       TH2D *h3 = new TH2D("h3","",1,mintime-1,maxtime+1,1,minresy,maxresy);
+       h3->GetXaxis()->SetTitle("(evt.nr)");
+       h3->GetYaxis()->SetTitle("(mm)");
+       h3->Draw();
+
+       TGraph *grtimeevoly = new TGraph(numEvt,time,resy);
+       grtimeevoly->SetMarkerColor(6);
+       grtimeevoly->SetMarkerStyle(24);
+       grtimeevoly->SetMarkerSize (0.4);
+       grtimeevoly->Draw("P");
+       
+       legxy = new TLegend(0.8,0.85,0.95,0.95);
+       legxy.SetTextSize(0.03);
+       legxy.AddEntry(grtimeevoly,"src pos y","P");
+       legxy.Draw();
+
+       evtloop.PostProcess();
+  }
+
+  tlist.PrintStatistics();
+
+}
+
+
Index: /tags/Mars-V0.9/mtemp/meth/macros/analysis.C
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/macros/analysis.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/macros/analysis.C	(revision 9772)
@@ -0,0 +1,529 @@
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// analysis.C                                                              //
+//                                                                         //
+// Author(s): S.C. Commichau, 6/2004                                       //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+
+// This macro calculates source independent and dependent image parameter 
+// distributions from data and writes them into a file called hillas.root. 
+// To look at the distributions use the macro analysis_read.C
+// Up to now no derotation and mispointing correction is taken into account!
+
+const TString inpathcal = "/ihp/MAGIC/Period016/rootdata2/2004_04_22/";
+//const TString inpath = "/ihp/MAGIC/Period016/rootdata2/2004_04_23/";
+const TString inpath = "/ihp/MAGIC/Period016/rootdata2/2004_04_23/";
+
+
+const TString dname = "/ihp/MAGIC/Period016/rootdata2/2004_04_23/20040423_2375*_D_OffMrk421-6_E.root";
+
+//const TString dname = "/ihp/MAGIC/Period016/rootdata2/2004_04_23/20040423_2343*_D_Mrk421_E.root";
+
+
+const Int_t  pedrun  = 23745;//23427;  // Pedestal file
+const Int_t  calrun1 = 23205;  // Calibration files
+const Int_t  calrun2 = 0;
+const Int_t  datrun1 = 23429;  // Data files
+
+const Bool_t usedisplay = kFALSE;
+
+// Range of slices that are taken into account
+const Byte_t hifirst = 1;
+const Byte_t hilast  = 14;
+const Byte_t lofirst = 3;
+const Byte_t lolast  = 14;
+
+
+void analysis()                             
+{
+
+    /*******************************************
+     * Define some parameters for the analysis *
+     *******************************************/
+        
+    // Change the following line toggle pedestal display 
+    Bool_t DrawPedestals = kFALSE;//kTRUE; 
+    
+    // Set calibration mode
+    // kDefault, kNone, kDummy, kFfactor, kPinDiode,...
+    MCalibrate::CalibrationMode_t CalMode=MCalibrate::kDefault;
+
+    // Cleaning: Core and Tailcut
+    TArrayF clvl(2);
+    clvl[0] = 3.5;
+    clvl[1] = 3.0;	
+
+    // Set bad pixels
+    const Short_t x[16] = {330,395,329,396,389,
+			   323,388,322,384,385,
+			   386,387,321,320,319,
+			   394};
+
+    // Set output filename
+    TString oname = "hillas.root";
+   
+    
+    /***************************************
+     * Define general tasks and containers *
+     ***************************************/
+
+    MCalibrationQECam         qecam;
+    MBadPixelsCam             badcam;
+    MGeomCamMagic             geomcam;
+    MGeomApply                geomapl;
+    MExtractFixedWindow       extractor; 
+    extractor.SetRange(hifirst, hilast, lofirst, lolast);
+    //MExtractFixedWindowPeakSearch extractor;
+    //extractor.SetWindows(8,8);
+    //MExtractSlidingWindow         extractor;
+
+
+    // Iterate over runs
+    MRunIter pruns;
+    MRunIter cruns;
+    MRunIter druns;
+  
+    MReadMarsFile   dread("Events", dname);
+    dread.DisableAutoScheme();
+
+    // Pedestal runs
+    pruns.AddRun(pedrun,inpath);
+    
+    // Calibration runs
+    if (calrun2==0)
+        cruns.AddRun(calrun1,inpathcal);
+    else
+        cruns.AddRuns(calrun1,calrun2,inpath);
+
+    // Data 
+/*    if (1)//datrun2==0)
+	druns.AddRun(datrun1,inpath);
+    else
+	druns.AddRuns(datrun1,datrun2,inpath);//,datrun3,datrun4,datrun5,datrun6,inpath);
+*/
+
+    // Look for the pulser colors 
+    MCalibrationCam::PulserColor_t color;
+ 
+    if (calrun1 < 20000)
+	color = MCalibrationCam::kCT1;
+    else
+	color = FindColor((MDirIter*)&cruns);
+    
+    if (color==MCalibrationCam::kNONE)
+    {
+	TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+	
+	while (1)
+	{
+	    timer.TurnOn();
+	    TString input = Getline("Couldn't find the pulser colour, type 'q' to exit, "
+				    "'green', 'blue', 'uv' or 'ct1' to go on: ");
+	    timer.TurnOff();
+	    
+	    if (input=="q\n")
+		return;
+	    
+	    if (input=="green\n")
+	    {
+		color = MCalibrationCam::kGREEN;
+		break;
+	    }
+	    if (input=="blue\n")
+	    {
+		color = MCalibrationCam::kBLUE;
+		break;
+	    }
+	    if (input=="uv\n" || input=="UV\n")
+	    {
+		color = MCalibrationCam::kUV;
+		break;
+	    }
+	    if (input=="ct1\n" || input=="CT1\n")
+	    {
+		color = MCalibrationCam::kCT1;
+		break;
+	    }
+	}
+    }
+    
+ 
+    /**********************************
+     * 1st Loop: Pedestal Computation *
+     **********************************/
+    
+    // If pixels have to be excluded from the beginning, read 
+    // an ASCII-file with the corresponding pixel numbers (MBadPixelsCam)
+    badcam.AsciiRead("badpixels.txt");
+    
+    MJPedestal                pedloop;
+    pedloop.SetInput(&pruns);   
+    pedloop.SetExtractor(&extractor);
+    pedloop.SetBadPixels(badcam);
+    
+    if (!pedloop.Process())
+	return;
+        
+    // Print the content of MPedestalCam
+    MPedestalCam *pedcam = (MPedestalCam*)pedloop.GetPedestalCam();
+    pedcam->Print(); 
+    
+    // Draw Pedestals and RMS into a camera - ADC counts
+    if (DrawPedestals)
+    {
+	MHCamera *disp0 = new MHCamera(geomcam, "Pedestals", "");
+	MHCamera *disp1 = new MHCamera(geomcam, "PedestalRMS", "");
+	
+	disp0->SetMinimum(0);
+	disp1->SetMinimum(0);
+	
+	TCanvas *c1 = new TCanvas("Pedestals", "Pedestals", 50, 50, 400, 400);
+	TCanvas *c2 = new TCanvas("RMS", "RMS", 460, 50, 400, 400);
+	
+	c1->SetBorderMode(0);
+	c1->SetFillColor(0);
+	
+	c2->SetBorderMode(0);
+	c2->SetFillColor(0);
+	
+	gStyle->SetOptStat(1101);
+	gStyle->SetStatColor(0);
+	gStyle->SetStatBorderSize(1);
+	
+	gPad->SetBorderMode(0);
+	
+	disp0.SetPrettyPalette();
+	disp1.SetPrettyPalette();
+	
+	c1->cd();
+	disp0.Draw();
+	
+	gPad->cd(1);
+	
+	disp0.SetCamContent(*pedcam,0);
+	disp0.SetCamError(*pedcam,1);
+	
+	c2->cd();
+	disp1.Draw();
+	
+	disp1.SetCamContent(*pedcam,2);
+	disp1.SetCamError(*pedcam,3);
+    }
+    
+   
+    /*************************
+     * 2nd Loop: Calibration *
+     *************************/
+
+    MJCalibration     calloop;
+    //calloop.SetColor(color);
+    calloop.SetInput(&cruns);
+    calloop.SetExtractor(&extractor);
+    //calloop.SetQECam(qecam);
+    calloop.SetBadPixels(pedloop.GetBadPixels());
+    
+    // Choose the arrival time Extractor:
+    //MExtractTimeHighestIntegral timeext;
+    //MExtractTimeSpline timeext;
+    // Set Ranges or Windows
+    //timeext.SetRange(0,14,6,14);
+    //calloop.SetTimeExtractor(&timeext);
+    
+    // To calibrate times enable the following line
+    //Bool_t UseTimes = kFALSE;
+    // Bool_t calibrateTimes = kFALSE;
+    //calloop.SetRelTimeCalibration(UseTimes);
+    
+    if (!calloop.Process(pedloop.GetPedestalCam()))
+    return;
+    
+    /**********************************
+     * 3rd Loop: Pedestal Calibration *
+     **********************************/
+
+    // Create a Parameter and a Task List
+    MParList                  plist3;
+    MTaskList                 tlist3;
+    plist3.AddToList(&tlist3);
+
+    // Parameter Containers
+    MCerPhotEvt               evtphot;
+    MPedPhotCam               pedphot;
+    MExtractedSignalCam       sigcam;
+    
+    // Add also some containers from previous loops
+    plist3.AddToList(&geomcam);
+    plist3.AddToList(&pedloop.GetPedestalCam());
+
+    plist3.AddToList(&calloop.GetCalibrationCam());
+    plist3.AddToList(&calloop.GetQECam());          // I have to check this! 
+    //plist3.AddToList(&calloop.GetRelTimeCam());
+    //plist3.AddToList(&calloop.GetBadPixels());
+    plist3.AddToList(&badcam);
+    plist3.AddToList(&sigcam);
+    plist3.AddToList(&evtphot);
+    plist3.AddToList(&pedphot);
+
+    
+    // Tasks
+    MReadMarsFile read3("Events");
+    static_cast<MRead&>(read3).AddFiles(pruns);  
+    read3.DisableAutoScheme();
+    
+    //MExtractSignal            extsig;
+    //extsig.SetRange(hifirst, hilast, lofirst, lolast);
+    MCalibrate                calphot;
+    calphot.SetCalibrationMode(CalMode);
+    MPedPhotCalc              pedphotcalc;  
+    
+    tlist3.AddToList(&read3);
+    tlist3.AddToList(&geomapl);
+    tlist3.AddToList(&extractor);
+    //tlist3.AddToList(&extsig);
+    tlist3.AddToList(&calphot);
+    tlist3.AddToList(&pedphotcalc);
+  
+    
+    // Create and setup the eventloop
+    MProgressBar              bar3;
+    bar3.SetWindowName("Calibrating Pedestals...");
+    
+    MEvtLoop                  evtloop3;
+    evtloop3.SetProgressBar(&bar3);
+    evtloop3.SetParList(&plist3);
+    
+    if (!evtloop3.Eventloop())
+	return;
+    
+    tlist3.PrintStatistics();
+
+
+    /****************************
+     * 4th Loop: Photonize Data *
+     ****************************/
+
+    // Create a Parameter and a Task List
+    MParList                  plist4;
+    MTaskList                 tlist4;
+    plist4.AddToList(&tlist4);
+
+    // Parameter Containers
+    MHillas                   hillas;
+    //MDCA                      dca;
+    MHillasSrc                hillassrc;
+    MSrcPosCam                source;
+    source.SetX(0.0*189/0.6);
+    source.SetY(0.0*189/0.6);
+    MRawRunHeader             runhead;
+    MArrivalTimeCam           timecam;
+    
+    // False Source stuff
+    MTime                     time;
+    MObservatory              obsv;
+    MPointingPos              poin;
+    
+    hillassrc.SetSrcPos(&source);
+    
+
+    // Add also some containers from previous loops
+    //plist4.AddToList(&timecam);
+    plist4.AddToList(&geomcam);
+    plist4.AddToList(&pedloop.GetPedestalCam());
+    plist4.AddToList(&calloop.GetCalibrationCam());
+    //plist4.AddToList(&badcam);
+    plist4.AddToList(&calloop.GetQECam());
+    //plist4.AddToList(&calloop.GetRelTimeCam());
+    //plist4.AddToList(&calloop.GetBadPixels());
+    plist4.AddToList(&source);
+    plist4.AddToList(&hillas);
+    plist4.AddToList(&hillassrc);
+    //plist4.AddToList(&dca);    
+    plist4.AddToList(&evtphot);
+    plist4.AddToList(&pedphot);
+
+    plist4.AddToList(&time);
+    plist4.AddToList(&obsv);
+    plist4.AddToList(&poin);
+    
+    
+    //MArrivalTime times;
+    //plist4.AddToList(&times);
+    
+    // Tasks
+/*  MReadMarsFile read4("Events");
+    static_cast<MRead&>(read4).AddFiles(druns);  
+    read4.DisableAutoScheme();
+*/
+    // Set bad pixels
+    MBlindPixelCalc           blind;
+
+    const TArrayS bp(16,(Short_t*)x);
+    blind.SetPixelIndices(bp);
+
+    MImgCleanStd              clean(clvl[0],clvl[1]);
+    MHillasCalc               hilcalc;
+    MHillasSrcCalc            hilsrc;
+    //MDCACalc                  dcacalc;
+    
+    
+    
+
+    MWriteRootFile write(oname,"RECREATE"); //Alternative options: NEW, UPDATE
+
+    //write.AddContainer("MDCA"         , "Parameters");
+    write.AddContainer("MHillas"        , "Parameters");
+    write.AddContainer("MHillasSrc"     , "Parameters");
+    write.AddContainer("MHillasExt"     , "Parameters");
+    write.AddContainer("MNewImagePar"   , "Parameters");
+    write.AddContainer("MRawEvtHeader"  , "Parameters");
+    write.AddContainer("MRawRunHeader"  , "Parameters");
+    write.AddContainer("MConcentration" , "Parameters");
+    write.AddContainer("MSrcPosCam"     , "Parameters");
+
+    
+    // False Source stuff
+    MHFalseSource             fshist;
+    fshist.SetAlphaCut(12.5);
+    //fshist.SetBgMean(35);
+    MFillH                   hfill(&fshist, "MHillas");
+    //MFillH                   hfill("MHFalseSource", "MHillas");
+
+    //MFalseSrcCalc     falsecalc;
+    //falsecalc.SetAlphaCut(12.5);
+    //falsecalc.SetDistCuts(.25,1.0);
+    //falsecalc.SetSizeCut(1000);
+    //falsecalc.SetWidthCuts(.04,.14);
+    //falsecalc.SetLengthCuts(.14,.26);
+    //falsecalc.SetOutput("ON.root");//outname);
+    //falsecalc.SetRefPoint(0,0);
+
+    //tlist4.AddToList(&read4);
+    tlist4.AddToList(&dread);
+    tlist4.AddToList(&geomapl);
+    tlist4.AddToList(&extractor);
+    //tlist4.AddToList(&blind);
+    //tlist4.AddToList(&timecalc);
+    tlist4.AddToList(&calphot);
+    //tlist4.AddToList(&timecal);
+    tlist4.AddToList(&clean);
+    tlist4.AddToList(&hilcalc);
+    //tlist4.AddToList(&dcacalc);
+    tlist4.AddToList(&hilsrc);
+//    tlist4.AddToList(&falsecalc);
+    //tlist4.AddToList(&hfill);
+    tlist4.AddToList(&write);  
+
+    // Create and setup the eventloop
+    MProgressBar              bar4;
+    bar4.SetWindowName("Analyzing Data...");
+
+    MEvtLoop                  evtloop4;
+    evtloop4.SetProgressBar(&bar4);
+    evtloop4.SetParList(&plist4);
+
+    if (!evtloop4.Eventloop())
+	return;
+
+    tlist4.PrintStatistics();
+
+    //fshist.Draw();
+
+
+}
+
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+
+    while (1)
+    {
+        // While reading the input process GUI events asynchronously
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+
+// Find the correct pulser color, done by M. Gaug
+MCalibrationCam::PulserColor_t FindColor(MDirIter* run) 
+{
+  
+  MCalibrationCam::PulserColor_t col = MCalibrationCam::kNONE;
+
+  TString filenames;
+
+  while (!(filenames=run->Next()).IsNull())
+    {
+
+      filenames.ToLower();
+
+      if (filenames.Contains("green"))
+        if (col == MCalibrationCam::kNONE)
+          {
+            cout << "Found colour: Green  in " << filenames << endl;
+            col = MCalibrationCam::kGREEN;
+          }
+        else if (col != MCalibrationCam::kGREEN)
+          {
+            cout << "Different colour found in " << filenames << "... abort" << endl;
+            return MCalibrationCam::kNONE;
+          }
+
+      if (filenames.Contains("blue"))
+        if (col == MCalibrationCam::kNONE)
+          {
+            cout << "Found colour: Blue  in " << filenames << endl;
+            col = MCalibrationCam::kBLUE;
+          }
+        else if (col != MCalibrationCam::kBLUE)
+          {
+            cout << "Different colour found in " << filenames << "... abort" << endl;
+            return MCalibrationCam::kNONE;
+          }
+
+      if (filenames.Contains("uv"))
+        if (col == MCalibrationCam::kNONE)
+          {
+            cout << "Found colour: Uv  in " << filenames << endl;
+            col = MCalibrationCam::kUV;
+          }
+        else if (col != MCalibrationCam::kUV)
+          {
+            cout << "Different colour found in " << filenames << "... abort" << endl;
+            return MCalibrationCam::kNONE;
+          }
+
+      if (filenames.Contains("ct1"))
+        if (col == MCalibrationCam::kNONE)
+          {
+            cout << "Found colour: Ct1  in " << filenames << endl;
+            col = MCalibrationCam::kCT1;
+          }
+        else if (col != MCalibrationCam::kCT1)
+          {
+            cout << "Different colour found in " << filenames << "... abort" << endl;
+            return MCalibrationCam::kNONE;
+          }
+      
+    }
+  
+     
+  if (col == MCalibrationCam::kNONE)
+    cout <<  "No colour found in filenames of runs: " << ((MRunIter*)run)->GetRunsAsString() 
+         << "... abort" << endl;
+  
+  return col;      
+}
Index: /tags/Mars-V0.9/mtemp/meth/macros/analysis_read.C
===================================================================
--- /tags/Mars-V0.9/mtemp/meth/macros/analysis_read.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/meth/macros/analysis_read.C	(revision 9772)
@@ -0,0 +1,568 @@
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// analysis_read.C                                                         //
+//                                                                         //
+// Author(s): S.C. Commichau, 3/2004                                       //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+
+// This macro reads the output of analysis.C and plots some of the
+// image parameters. It also produces an ALPHA plot and calculates
+// the significance
+
+void analysis_read(){
+
+    gROOT->Reset();
+    
+    // Some parameters for the ALPHA-plot
+    const Int_t inibin = 9;
+    const Int_t nbins  = 18;
+
+    // ON data chain
+    TChain* CON  = new TChain("Parameters");
+
+    // OFF data chain
+    TChain* COFF = new TChain("Parameters");
+
+    // Add the root file(s) to the chain and treat it like a tree
+    CON->Add("~/Mars/on1.root");
+    COFF->Add("~/Mars/off1.root");
+
+    //CON->Add("~/no_back/hillas_on_all23.root");
+    //COFF->Add("~/no_back/hillas_off_all23.root");
+
+    TString title = "Mrk421 - 04/23/2004";
+
+    // Set some global style options
+    //gStyle->SetOptDate(10);
+    //gStyle->SetDateX(.1);
+    //gStyle->SetDateY(.905);
+    gStyle->SetOptFit(0);
+    gStyle->SetOptStat(110011);
+    gStyle->SetFrameBorderMode(0);
+    //gStyle->SetPalette(1);
+    gStyle->SetPalette(1,0);
+    gStyle->SetFrameBorderSize(0);
+    gStyle->SetCanvasColor(0);
+    gStyle->SetFrameFillColor(0);
+    gStyle->SetTitleFillColor(0);
+    gStyle->SetTitleBorderSize(0);
+    gStyle->SetStatColor(0);
+    gStyle->SetStatBorderSize(1);
+    // Put the statistics box into the right corner!
+    gStyle->SetStatX(.9);
+    gStyle->SetStatY(.9);
+    //gStyle->SetStatTextColor(2);
+
+    // Set alias for each quantity to simplify the handling
+    CON->SetAlias("length","MHillas.fLength*0.6/189.0");
+    CON->SetAlias("width","MHillas.fWidth*0.6/189.0");
+    CON->SetAlias("meanx","MHillas.fMeanX*0.6/189.0");
+    CON->SetAlias("meany","MHillas.fMeanY*0.6/189.0");
+    CON->SetAlias("size","MHillas.fSize");
+    CON->SetAlias("dist","MHillasSrc.fDist*0.6/189.0");
+    CON->SetAlias("alpha","MHillasSrc.fAlpha");
+    CON->SetAlias("delta","abs(MHillas.fDelta)*180/3.1415");
+    //CON->SetAlias("delta","MDCA.fDelta1*180/3.1415");
+    //CON->SetAlias("dca","MDCA.fDCA*0.6/189.0");
+
+    COFF->SetAlias("length","MHillas.fLength*0.6/189.0");
+    COFF->SetAlias("width","MHillas.fWidth*0.6/189.0");
+    COFF->SetAlias("meanx","MHillas.fMeanX*0.6/189.0");
+    COFF->SetAlias("meany","MHillas.fMeanY*0.6/189.0");
+    COFF->SetAlias("size","MHillas.fSize");
+    COFF->SetAlias("dist","MHillasSrc.fDist*0.6/189.0");
+    COFF->SetAlias("alpha","MHillasSrc.fAlpha");
+    COFF->SetAlias("delta","abs(MHillas.fDelta)*180/3.1415");
+
+
+    // Cuts...
+    // Cut for ALPHA
+    TString cut1 = "(dist>0.2) && (dist<.7) && (width>0.04) && (width<0.14) && (length>0.14) && (length<0.26) && (size>500)";
+        
+    TString cut2 = "";//size>1000 && size<2000";
+
+    TString cut3 = "";
+
+    TString cut4 = "";
+
+    TString cut5 = "";
+    
+
+    // And now the draw area
+    
+    //************ Width vs Length ************
+
+    TCanvas* CWL = new TCanvas("CWL","Canvas",0,0,300,300);
+    CWL->cd();
+    CWL->SetBorderMode(0); 
+    gPad->SetBorderMode(0);
+    gStyle->SetOptStat(0);
+            
+    TH2F* hWL = new TH2F("hWL","",200,0,0.7,200,0,1);
+    
+    // Leaf, Cuts, Draw option, use >>+ to append data to an ex. histogram
+    CON->Draw("length:width>>hWL",cut2);
+
+    hWL->SetTitle(title); 
+    hWL->GetXaxis()->SetTitle("WIDTH [#circ]");
+    hWL->GetYaxis()->SetTitle("LENGTH [#circ]");
+    hWL->GetYaxis()->SetTitleOffset(1.2);
+    hWL->SetMarkerColor(2);
+     
+    hWL->SetMaximum(150);
+    hWL->Draw("COLZ");//CONT
+
+
+    //************ Width and Length ************
+
+    // Create Canvas and set Canvas some options
+    TCanvas* Cwl = new TCanvas("Cwl","Canvas",325,0,300,300);
+    Cwl->cd();
+    Cwl->SetBorderMode(0);   
+    gPad->SetBorderMode(0);
+    gStyle->SetOptStat(110011);
+
+    TH1F* hLength = new TH1F("hLength","",100,0,1.1);
+        
+    CON->Draw("length>>hLength",cut5,"");
+
+    hLength->SetTitle(title); 
+    hLength->GetXaxis()->SetTitle("LENGTH and WIDTH [#circ]");
+    hLength->GetYaxis()->SetTitle("Entries");
+    hLength->GetYaxis()->SetTitleOffset(1.6);
+    hLength->SetFillColor(50);
+    hLength->SetLineColor(50);
+    hLength->SetLineWidth(2);
+    hLength->SetFillStyle(3005);
+    //hLength->SetMaximum(55000);
+    hLength->SetName("LENGTH");
+
+    TH1F* hWidth = new TH1F("hWidth","",100,0,1.1);
+
+    CON->Draw("width>>hWidth",cut5,"");
+ 
+    gStyle->SetStatTextColor(4);
+    hWidth->SetFillColor(4);
+    hWidth->SetLineColor(4);
+    hWidth->SetFillStyle(3004);
+    hWidth->SetLineWidth(2);
+    hWidth->SetName("WIDTH");
+
+    TLegend* leg = new TLegend(.59,.75,.8,.84);
+    leg->AddEntry(hLength,"LENGTH","F");
+    leg->AddEntry(hWidth,"WIDTH","F");
+    leg->SetFillColor(0);
+    leg->SetLineColor(1);
+    leg->SetBorderSize(0);
+
+    hLength->Draw();//DrawNormalized or DrawCopy are possible options
+    hWidth->Draw("sames");
+    //leg->Draw("same");
+
+    // Beautify the statistic boxes!
+    gPad->Update();
+    TPaveStats* pavstat = (TPaveStats*) hLength->GetListOfFunctions()->FindObject("stats");
+    if(pavstat)
+    {
+	Float_t shiftx = pavstat->GetX2NDC()-pavstat->GetX1NDC();
+	pavstat->SetX1NDC(pavstat->GetX1NDC()-shiftx);
+	pavstat->SetX2NDC(pavstat->GetX2NDC()-shiftx);
+	pavstat->SetTextColor(50);
+    }
+
+    gPad->Modified();
+    gPad->Update();
+
+
+    //************ Dist ************
+    
+    TCanvas* CDist = new TCanvas("CDist","Canvas",650,0,300,300);
+    CDist->cd();
+    CDist->SetBorderMode(0); 
+    gStyle->SetOptStat(110011);
+    //CDist->SetLogy();
+
+    TH1F* hDist = new TH1F("hDist","",90,0,1.8);
+
+    CON->Draw("dist>>hDist");
+
+    hDist->GetXaxis()->SetTitle("DIST [#circ]");
+    hDist->GetYaxis()->SetTitle("Entries");
+    hDist->GetYaxis()->SetTitleOffset(1.6);
+    //hDist->GetXaxis()->SetTitleOffset(1.3);
+    hDist->SetLineColor(4);
+    hDist->SetMarkerColor(4);
+    hDist->SetFillColor(4);
+    hDist->SetFillStyle(3004);
+    hDist->SetLineWidth(2);
+    hDist->SetTitle(title);
+    hDist->SetName("DIST");
+    
+    hDist->Draw();
+
+
+    //************ MeanY vs MeanX ************
+    
+    TCanvas* CXY = new TCanvas("CXY","Canvas",975,0,300,300);
+    CXY->cd();
+    CXY->SetBorderMode(0);  
+    gStyle->SetOptStat(0);
+    
+    TH2F* hXY = new TH2F("hXY","",500,-1.5,1.5,500,-1.5,1.5);
+
+    CON->Draw("meany:meanx>>hXY",cut3,"");
+
+    TString titlexy = TString(title);
+
+    hXY->SetTitle(titlexy); 
+    hXY->GetXaxis()->SetTitle("MeanX [#circ]");
+    hXY->GetYaxis()->SetTitle("MeanY [#circ]");
+    hXY->GetYaxis()->SetTitleOffset(1.2);
+    hXY->SetMaximum(15);
+     
+    hXY->Draw("COLZ");
+
+
+    //************ DCA ************
+    /*     
+    TCanvas* CDCA = new TCanvas("CDCA","Canvas",10,400,300,300);
+    CDCA->cd();
+    CDCA->SetBorderMode(0); 
+    gStyle->SetOptStat(110011);
+    
+    TH1F* hDCA = new TH1F("hDCA","",100,-1.5,1.5);
+
+    CON->Draw("dca>>hDCA");
+
+    hDCA->GetXaxis()->SetTitle("DCA [#circ]");
+    hDCA->GetYaxis()->SetTitle("Entries");
+    hDCA->GetYaxis()->SetTitleOffset(2);
+    hDCA->SetLineColor(4);
+    hDCA->SetFillColor(4);
+    hDCA->SetFillStyle(3004);
+    hDCA->SetTitle(title);
+    hDCA->SetName("DCA");
+
+    hDCA->Draw();
+    */    
+
+
+    //************ Delta ************
+     
+    TCanvas* CDelta = new TCanvas("CDelta","Canvas",0,335,300,300);
+    CDelta->cd();
+    CDelta->SetBorderMode(0); 
+    gStyle->SetOptStat(110011);
+
+    TH1F* hDelta = new TH1F("hDelta","",100,0,90);
+
+    CON->Draw("delta>>hDelta",cut3);
+    
+    hDelta->GetXaxis()->SetTitle("#delta [#circ]");
+    hDelta->GetYaxis()->SetTitle("Entries");
+    hDelta->GetYaxis()->SetTitleOffset(1.4);
+    hDelta->SetLineColor(4);
+    hDelta->SetFillColor(4);
+    hDelta->SetFillStyle(3004);
+    hDelta->SetLineWidth(2);
+    hDelta->SetTitle(title);
+    hDelta->SetName("Delta");
+
+    hDelta->Draw();
+
+
+    //************ Size ************
+     
+    TCanvas* CSize = new TCanvas("CSize","Canvas",325,335,300,300);
+    CSize->cd();
+    CSize->SetBorderMode(0); 
+    gStyle->SetOptStat(110011);
+
+    TH1F* hSize = new TH1F("hSize","",100,0.1,5000);
+
+    CON->Draw("size>>hSize");
+    
+    hSize->GetXaxis()->SetTitle("Size [Photons]");
+    hSize->GetYaxis()->SetTitle("Entries");
+    hSize->GetYaxis()->SetTitleOffset(1.6);
+    hSize->GetXaxis()->SetTitleOffset(1.2);
+    hSize->SetLineColor(4);
+    hSize->SetFillColor(4);
+    hSize->SetLineWidth(2);
+    hSize->SetFillStyle(3004);
+    hSize->SetTitle(title);
+    hSize->SetName("SIZE");
+    
+    hSize->Draw();
+
+
+    //************ Alpha ************
+       
+    TCanvas* CAlpha = new TCanvas("CAlpha","Canvas",650,335,300,300);
+    CAlpha->cd();
+    CAlpha->SetBorderMode(0); 
+    CAlpha->SetGridx();
+    CAlpha->SetGridy();
+    gStyle->SetOptStat(11);
+    
+    TH1F *hAlpha = (TH1F*)new TH1F("hAlpha","Alpha ON",nbins,0,90);
+    TH1F *hAlphaoff = (TH1F*)new TH1F("hAlphaoff","Alpha OFF",nbins,0,90);
+
+    CON->Draw("abs(alpha)>>hAlpha",cut1);
+
+    COFF->Draw("abs(alpha)>>hAlphaoff",cut1);
+
+
+    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
+    // Normalize ON and OFF data
+    cout << "******************************************************" << endl;
+    cout << " Bin error before scaling: " << hAlphaoff->GetBinError(2) << endl;
+
+    // If TH1::Sumw2 has been called before filling, the sum of squares of
+    // weights is also stored - I do not understand this!!
+    hAlphaoff->Sumw2();
+    
+    Float_t level = 0, leveloff = 0;
+    
+    // Calculate the mean of entries beside the signal region
+    for(Int_t ibin = inibin; ibin<=nbins; ibin++)
+	level += hAlpha->GetBinContent(ibin);
+    level /= (nbins-inibin+1);
+    
+    cout << " Mean beside signal: " << level << endl;
+
+    for(Int_t ibin = inibin; ibin<=nbins; ibin++)
+	leveloff += hAlphaoff->GetBinContent(ibin);
+    leveloff /= (nbins-inibin+1);
+
+    // Compare the mean values of both histograms
+    if(leveloff>0)
+	const Float_t norm = level/leveloff;//*nbins/hAlphaoff->GetEntries();
+    cout << " Normalizing by factor " << norm <<endl;
+    hAlphaoff->Scale(norm);
+    
+    cout << " Bin error after scaling: " << hAlphaoff->GetBinError(2) << endl;
+
+    cout << " Cut on (ALPHA): " << cut1 << endl;
+    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
+
+   //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
+    // Significance calculation
+    Float_t significance = 0;
+    const Int_t signbins = 3;
+    
+    Int_t Non  = 0;
+    Int_t Noff = 0;
+
+    cout << " Significance Bins: " << signbins << endl;
+
+    // Determine number of excess events and off events in the same region 
+    for(Int_t ibin = 1; ibin<=signbins;ibin++)
+    {
+	Non +=hAlpha->GetBinContent(ibin);
+	Noff+=hAlphaoff->GetBinContent(ibin);
+    }
+
+    cout << " Non = " << Non << " Noff = " << Noff << endl;
+
+    significance = Significance(Non, Noff, 1.0, 0); //norm
+
+    cout << " Significance: " << significance << endl;
+    cout << "******************************************************" << endl;
+    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
+
+    // Set some draw options and draw the histograms
+    hAlphaoff->GetXaxis()->SetTitle("ALPHA [#circ]");
+    hAlphaoff->GetYaxis()->SetTitle("Entries");
+    hAlphaoff->GetYaxis()->SetTitleOffset(1.4);
+    hAlphaoff->GetXaxis()->SetTitleOffset(1.1);
+
+    char legentry[128];
+    sprintf(legentry,"  (Sign.: %2.3f #sigma,  Norm.: %2.3f,  |ALPHA| #leq %d#circ)", significance, norm, 90/nbins*signbins);
+
+    hAlphaoff->SetTitle(title+legentry);
+    hAlphaoff->SetName("OFF source");
+    hAlphaoff->SetLineColor(4);
+    hAlphaoff->SetLineWidth(2);
+    hAlphaoff->SetMarkerColor(8);
+    hAlphaoff->SetMarkerStyle(21);
+    hAlphaoff->SetMarkerSize(0);
+    hAlphaoff->SetFillColor(18);
+    hAlphaoff->SetMaximum(hAlpha->GetMaximum()+200);
+
+    hAlpha->SetLineColor(1);
+    hAlpha->SetLineWidth(2);
+    hAlpha->SetMarkerColor(50);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.9);
+    hAlpha->SetName("ON source");
+    //hAlpha->SetMaximum(hAlpha->GetMaximum());
+
+    hAlphaoff->Draw("eH");
+    hAlpha->Draw("e1sames");
+
+    // Beautify the statistic boxes!
+    gPad->Update();
+    TPaveStats* pavstat = (TPaveStats*) hAlphaoff->GetListOfFunctions()->FindObject("stats");
+    if(pavstat)
+    {
+	Float_t shiftx = pavstat->GetX2NDC()-pavstat->GetX1NDC();
+	pavstat->SetX1NDC(pavstat->GetX1NDC()-shiftx);
+	pavstat->SetX2NDC(pavstat->GetX2NDC()-shiftx);
+	pavstat->SetTextColor(4);
+    }
+
+    TPaveStats* pavstaton = (TPaveStats*) hAlpha->GetListOfFunctions()->FindObject("stats");
+    if(pavstaton)
+    {
+	pavstaton->SetTextColor(50);
+    }
+
+    gPad->Modified();
+    gPad->Update();
+
+
+    //************ Length/Size ************
+    
+    TCanvas* CLSiz = new TCanvas("CLSiz","Canvas",975,335,300,300);
+    CLSiz->cd();
+    CLSiz->SetBorderMode(0); 
+    gStyle->SetOptStat(110011);
+
+    TH1F* hLenSiz = new TH1F("hLenSiz","",100,0,0.005);
+
+    CON->Draw("length/size>>hLenSiz",cut2,"");
+
+    hLenSiz->GetXaxis()->SetTitle("LENGTH/SIZE [#circ/Photons]");
+    hLenSiz->GetYaxis()->SetTitle("Entries");
+    hLenSiz->GetYaxis()->SetTitleOffset(1.5);
+    hLenSiz->GetXaxis()->SetTitleOffset(1.1);
+    hLenSiz->SetLineColor(4);
+    hLenSiz->SetFillColor(4);
+    hLenSiz->SetLineWidth(2);
+    hLenSiz->SetFillStyle(3004);
+    hLenSiz->SetNdivisions(505);
+
+    hLenSiz->SetTitle(title);
+    hLenSiz->SetName("LENGTH/SIZE");
+
+    hLenSiz->Draw();
+
+
+    // Uncomment the following lines for MC only!
+
+    //************ Energy ************
+    /*
+   
+    TH1F *hEnergy = (TH1F*)gDirectory->Get("hEnergy");
+    
+    TCanvas* CEnergy = new TCanvas("CEnergy","Canvas",0,670,300,300);
+    CEnergy->cd();
+    CEnergy->SetBorderMode(0); 
+    //CEnergy->SetLogy();
+    gStyle->SetOptStat(110011);
+
+    TH1F* hEnergy = new TH1F("hEnergy","",100,0,1000);
+
+    CON->Draw("energy>>hEnergy","","");
+     
+    hEnergy->GetXaxis()->SetTitle("Energy [GeV]");
+    hEnergy->GetYaxis()->SetTitle("Entries");
+    hEnergy->GetYaxis()->SetTitleOffset(1.2);
+    hEnergy->GetXaxis()->SetTitleOffset(1.1);
+    hEnergy->SetLineColor(4);
+    hEnergy->SetFillColor(4);
+    hEnergy->SetLineWidth(2);
+    hEnergy->SetFillStyle(3004);
+    hEnergy->SetNdivisions(505);
+
+    hEnergy->SetTitle(title);
+    hEnergy->SetName("Energy");
+
+    hEnergy->Draw();
+    */
+
+
+    //************ MeanX and MeanY ************
+
+    // Create Canvas and set Canvas some options
+    TCanvas* Cxy = new TCanvas("Cxy","Canvas",325,670,300,300);
+    Cxy->cd();    
+    Cxy->SetBorderMode(0);   
+    gPad->SetBorderMode(0);
+    gStyle->SetOptStat(111);
+
+    TH1F* hMeanX = new TH1F("hMeanX","",100,-1.5,1.5);
+    
+    CON->Draw("meanx>>hMeanX",cut3,"");
+
+    TH1F* hMeanY = new TH1F("hMeanY","",100,-1.5,1.5);
+
+    CON->Draw("meany>>hMeanY",cut3,"");
+    
+    hMeanX->SetTitle(title); 
+    hMeanX->GetXaxis()->SetTitle("MeanX and MeanY [#circ]");
+    hMeanX->GetYaxis()->SetTitle("Entries");
+    hMeanX->GetYaxis()->SetTitleOffset(1.6);
+    hMeanX->SetFillColor(50);
+    hMeanX->SetLineColor(50);
+    hMeanX->SetLineWidth(2);
+    hMeanX->SetFillStyle(3005);
+    //hMeanX->SetMaximum(16000);
+    //hMeanX->SetMaximum(6500);
+    hMeanX->SetName("MeanX");
+ 
+    gStyle->SetStatTextColor(4);
+    hMeanY->SetFillColor(4);
+    hMeanY->SetLineColor(4);
+    hMeanY->SetFillStyle(3004);
+    hMeanY->SetLineWidth(2);
+    hMeanY->SetName("MeanY");
+
+    hMeanX->Draw();//DrawNormalized or DrawCopy are possible options
+    hMeanY->Draw("sames");//esames
+
+    // Beautify the statistic boxes!
+    gPad->Update();
+    TPaveStats* pavstat = (TPaveStats*) hMeanX->GetListOfFunctions()->FindObject("stats");
+    if(pavstat)
+    {
+	Float_t shiftx = pavstat->GetX2NDC()-pavstat->GetX1NDC();
+	pavstat->SetX1NDC(pavstat->GetX1NDC()-shiftx);
+	pavstat->SetX2NDC(pavstat->GetX2NDC()-shiftx);
+	pavstat->SetTextColor(50);
+    }
+
+    gPad->Modified();
+    gPad->Update();
+
+    //delete hWL;
+    //delete hXY;
+}
+
+
+Double_t Significance(Float_t Non, Float_t Noff, Float_t alpha, Int_t type = 0)
+{
+    // Calculate significance after Li and Ma
+    
+    // Formula Nr. 17
+    if(type == 0)
+	return TMath::Sqrt(2*(Non*TMath::Log(((1+alpha)/alpha)*(Non/(Non+Noff))) + Noff*TMath::Log((1+alpha)*Noff/(Non+Noff))));
+
+    // Formula Nr. 9
+    if(type == 1)
+	return (Non-alpha*Noff)/TMath::Sqrt(alpha*(Non+Noff));
+
+}
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/.rootrc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/.rootrc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/.rootrc	(revision 9772)
@@ -0,0 +1,45 @@
+#############################################################################
+#                                                                           #
+# This is the path where root seraches for macros                           #
+# to execute (eg. .x merpp.C)                                               #
+#                                                                           #
+#############################################################################
+
+Unix.*.Root.MacroPath:       .:./macros:../../macros
+
+#############################################################################
+#                                                                           #
+# This is the path where the dynamic loader (eg. gSystem->Load("mars.so")   #
+# is searching for the shared objects                                       #
+#                                                                           #
+#############################################################################
+
+Unix.*.Root.DynamicPath:     .:./lib
+
+#############################################################################
+#                                                                           #
+# This is the name of the logon macro (executed at root startup) and the    #
+# logoff macro (executed when quiting root)                                 #
+#                                                                           #
+#############################################################################
+
+Rint.Logon:                  rootlogon.C
+Rint.Logoff:                 rootlogoff.C
+
+#############################################################################
+#                                                                           #
+# This is used if you want to use the root documentation facility to        #
+# create the documentation of the code out of the code                      #
+#                                                                           #
+#############################################################################
+
+Root.Html.DescriptionStyle:  Doc++
+
+Root.Html.Author:            !   Author(s):
+Root.Html.Copyright:         !   Copyright
+Root.Html.Modified:          !   Modified:
+Root.Html.Description        // ----
+
+Root.Html.Root:              http://root.cern.ch/root/htmldoc/
+Root.Html.HomePage:          http://magic.astro.uni-wuerzburg.de/mars/
+Root.Html.SearchEngine:      http://magic.astro.uni-wuerzburg.de/mars/search.html
Index: /tags/Mars-V0.9/mtemp/mifae/Changelog
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/Changelog	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/Changelog	(revision 9772)
@@ -0,0 +1,738 @@
+Please  do  not write behind the end of line tag so that it is  possible
+to   send  a   Changelog   file  to  a  line  printer  directly.  Thanks.
+
+For your entries please follow this style:
+
+_yyyy/mm/dd:_[Your Name]
+_
+___*_filename:
+_____-_description
+_
+___*_filename2, filename3:
+_____-_description
+_
+_
+_
+
+While an underscore is a placeholder for a white-space or an empty line.
+
+                                                 -*-*- END OF LINE -*-*-
+ 2005/03/03 Javier Rico
+    * programs/makeHillas.cc programs/makehillas.datacard
+      - read initial list of bad pixels from ascii file
+      - include MImagePar as output container
+
+ 2005/02/15 Javier Rico
+    * library/MEffAreaAndCoeffCalc.[h,cc]
+    * macros/computeCoeff.C
+      - extend the energy bounds to compute weights
+      - add possibility to set the zenith angle binning from outside
+
+ 2005/02/14 Javier Rico
+    * library/MEffAreaAndCoeffCalc.[h,cc]
+    * macros/computeCoeff.C
+      - compute the coefficients in the big bins
+      - migrate to new data format
+      
+	
+ 2005/02/10 Javier Rico
+    * library/MEffAreaAndCoeffCalc.[h,cc]
+      - added class to compute Effective areas and unfolding coefficients
+    * library/Makefile, IFAELinkDef.h
+      - add MEffAreaAndCoeffCalc
+    * macros/computeCoeff.C
+      - add macro example to use MEffAreaAndCoeffCalc	
+	
+ 2005/02/02 Oscar Blanch Bigas
+    * library/MGainFluctuationPix.[h,cc],MGainFluctuationCam.[h,cc]
+      - added parameter containers to handle gain fluctuaions
+    * library/MAddGainFluctuation.[h,cc]
+      - added task to add gain fluctuaions
+    * library/Makefile,IFAELinkDef.h
+      - modified to compile new classes
+    * macros/makeHillasMC.C
+      - modified to compute also Mhadronness and MDisp
+      - modified adding class to introduce gain fluctuations
+      - modified adding display hillas
+
+ 2005/01/27 Javier Rico
+    * programs/DISPstd.root, programs/RF*.root
+     - removed, will be available at 
+       http://atlas.ifae.es/~jrico/Mars_Standard06/mtemp/mifae/bin/
+
+ 2005/01/27 Eva Domingo
+    * programs/DISPstd.root
+     - updated optimal DISP parameters, running over the MC treated
+       with the Spline signal extractor
+    * macros/DispSkymap.C
+     - added first version of a macro that creates the On, Off and
+       On-Off skymaps from the makeHillas program output files
+    * macros/makeHillasMC.C
+     - added macro equivalent to current makeHillas program 
+       for MC files (it is in fact a version of several already 
+       existing macros)
+
+ 2005/01/25 Javier Rico
+    * macros/mmcCleaning.C
+     - added extractor spline and input arguments
+	
+ 2005/01/24 Javier Rico
+    * programs/RFstd.root, programs/RFdist.root, programs/RFalpha.root
+     - added default forest files for standard analysis, for 
+       off-axis or exteded sources (disp analysis), and analysis 
+       on hadronness including alpha.
+	
+ 2005/01/24 Eva Domingo
+    * library/MFDisp.[cc,h] 
+     - Number of islands read from MImagePar container
+       to be used as cut parameter if wanted
+    * library/MHDisp.cc 
+     - corrected to be able to run Disp method also over
+       data (MMcEvt container info just used if available)
+    * library/MDispCalc.cc
+     - introduced DISP = Xi*(1/(1+width/length)) as default
+       Disp parameterization for the moment
+
+ 2005/01/24 Eva Domingo
+    * programs/makeHillas.cc 
+      programs/makehillas.datacard
+      programs/DISPstd.root, default DISP parameters values
+     - Add Disp computation
+
+ 2005/01/21 Javier Rico
+    * programs/makeHillas.cc, programs/Makefile, 
+      programs/makehillas.datacard
+     - Add Random Forest computation
+	
+ 2005/01/20 Eva Domingo
+    * library/MDispParameters.[cc,h]
+     - Added substituting previous MDisp.[cc,h] classes.
+       Old MDisp::Calc function moved to MDispCalc task.
+    * library/MDispCalc.[cc,h]
+     - Now includes the DISP parameterization, defined in 
+       MDispCalc::Calc. MDispCalc::InitMapping now defines 
+       training and test matrices with only the columns of 
+       variables needed in the DISP expression.
+    * library/MHDisp.[cc,h]
+     - Changed the Chi2 name by MinPar (to clarify it accounts for 
+       the parameter asked to be minimized in the Disp optimization).
+       Added MHDisp::InitMapping, defines matrices with only the columns
+       of variables needed for computing the minimization parameter 
+       and for filling the DISP histograms.
+
+ 2005/01/18 Javier Rico & Markus Gaug
+    * programs/controlPlot.cc, programs/controlplot.datacard,
+      programs/Makefile
+     - correct bugs: cuts in the proper units; separate ON and OFF 
+       task lists since before it was reading who knows what
+    * library/MControlPlots.[h,cc]
+     - add Clear() method and remove some (minor) memory leaks
+    * library/MIslands.cc
+     - place call to SetOwner() in the correct place
+	
+ 2005/01/10 Javier Rico
+    * programs/makeHillas, programs/makehillas.datacard
+     - adapt to new mars version
+	
+ 2004/12/22 Eva Domingo
+    * library/MImageParDisp.[cc,h]
+     - Container for the estimated distance to source position DISP.
+    * library/MDisp.[cc,h]
+     - Container holding the parameters used for the DISP expression.
+       The current DISP parameterization is defined in MDisp::Calc.
+    * library/MDispCalc.[cc,h]
+     - Task calculating DISP with the expression and parameter values
+       stored in MDisp. Training and test matrix of variables to be 
+       used in the DISP optimization are also defined within 
+       MDispCalc::InitMapping.
+    * library/MHDisp.[cc,h]
+     - Container for the histograms to judge the quality of the DISP 
+       estimate. MHDisp::GetChi2 returns the value of the quantity 
+       requested to be minimized by Minuit, which is defined and 
+       computed in MHDisp::Fill and MHDisp::Finalize. 
+       MHDisp::GetSkymapXY returns the reconstructed map of source 
+       positions. MHDisp::SetSelectedPos function to choose the 
+       selection method of the DISP source position solution.
+    * library/MFDisp.[cc,h]
+     - Filter to select a sample of events to do the DISP optimization.
+       Use MFDisp::SetCuts function.
+    * library/MFindDisp.[cc,h]
+     - Main class for DISP optimization:
+        ::DefineTrainMatrix, ::DefineTestMatrix, ::DefineTrainTestMatrix
+       generate the training and test samples (in the form of matrices)
+       from the input file.
+	::FindParams is the function steering the optimization (over the
+       training sample), calling Minuit, passing the fcn function to be 
+       minimize and defining the event loop to be executed in each step.
+	::TestParams tests the quality of the DISP estimate using the 
+       test matrix sample
+    * macros/OptimizeDisp.C
+     - macro for estimating the DISP parameter: create training and test
+       matrix; optimize DISP; test quality optimization; calculate DISP
+       and construct skymap for an input file.
+    * library/Makefile, library/IFAELinkDef.h
+     - include Disp classes.
+
+ 2004/12/21 Pepe Flix (represented by jrico)
+    * library/MTopology.[cc,h], library/MTopologyCalc.[cc,h], 
+      library/Makefile, library/IFAELinkDef.h
+     - include topology classes
+	
+ 2004/12/21 Javier Rico
+    * programs/makeHillas.cc, programs/makehillas.datacard
+     - Include spline extractor and remove possibility of computing 
+       pedestals from pedestal runs instead of from low gains
+
+ 2004/11/24  Ester Aliu
+    * library/MIslandsCalc.h
+     - Remove a memmory leak, and add a sort function to order the 
+     pixels by index after their interpolation
+     - Other minor changes 
+    * library/MImgIsland.[h,cc]
+     - Reset some variables
+
+ 2004/11/11  Ester Aliu
+    * library/MIslands.h
+     - Add the variable AlphaW
+    * library/MImgIsland.[h,cc]
+     - Add alpha for each island
+    * library/MIslandsCalc.cc
+     - Bug solved
+    * library/MIslandsClean.cc
+     - More different island cleanings added	
+
+  2004/10/20  Javier Rico
+    * programs/makeHillas.cc
+     - Correct reading in MReportDrive
+	
+  2004/10/15  Javier Rico
+    * programs/makeHillas.cc, programs/Makefile
+     - Write out MReportDrive
+	
+  2004/10/15  Javier Rico
+    * macros/mmcCleaning.C
+     - Include islands
+     - Do not save uncalibrated nonoise file
+
+  2004/10/08  Javier Rico
+    * programs/makeHillas.cc, programs/makehillas.datacard
+     - Include possibility to select signal extractor in datacard
+     - Include possitility to compute pedestals from data themselves, 
+       by selecting word PRUNS 0. For the time being, the old option
+       of computing them from a pedestal run is still available
+	
+  2004/10/05  Javier Rico
+    * programs/srcPos.cc
+     - Change kRotate by kRotating since the former is a used name
+    * programs/makeHillas.cc
+     - Change SetProcessRMS by SetProcessPedestal since name has changed
+    * programs/Makefile
+     - add mhcalib to the list of include dirs since it is now needed
+
+  2004/10/05  Ester Aliu
+    * library/Makefile ,library/IFAELinkDef
+     - modified according to the new classes implemented
+    * programs/makeHillas.cc
+     - modified according to the new classes implemented 
+
+  2004/10/05  Ester Aliu
+    * library MIslands.[h,cc] ,library/MIslandCalc.[h,cc],
+      MIslandClean.[h,cc]
+     - removed
+    * library MIslands.[h,cc],library/MIslandsCalc.[h,cc], 
+     MIslandsClean.[h,cc] , MImgIsland.[h,cc]
+     - added
+    * library/MControlPlots.[h,cc], MIslands.[h,cc]
+     - changed. A bug in the islands has been solved and a new structure
+     for the islands classes similar to the MStarPos and MStarCam classes
+     is proposed
+
+  2004/09/16 Javier Rico
+    * macros/pedrmsonoff.C
+     - Added
+
+  2004/09/02 Javier Rico
+    * programs/srcPos.cc
+     - Add include MArgs.h to cope with changes in Mars
+
+  2004/08/31 Javier Rico
+    * macros/mergeClean.C, mmcCleaning, cleanComp.C
+     - Added macros for the cleaning comparison analysis
+
+  2004/08/27 Javier Rico
+    * library/MDisplay.[cc,h]
+     - Dump run and event numbers
+     - Add possibility to produce ps file of the image
+
+  2004/08/10 Javier Rico
+    * programs/makeHillas.cc
+     - include recomendations of Nadia to interpolate bad pixels
+
+  2004/08/10 Ester Aliu
+    * library/MIslands.[h,cc], MIslandCalc.[h,cc]
+     - remove som bugs
+    * programs/makeHillas.[cc]
+     - fixed window(14 slices) by default 
+  
+  2004/08/04 Javier Rico
+    * programs/makeHillas.cc
+     - remove "#include" of obsolete MBlindPixel.h
+     - do not interpolate "unreliable" pixels
+	
+    * library/MIslands.[cc]
+     - Correct tiny compilation error
+    
+    * library/MDisplay.cc, library/MHillasDisplay.[h,cc]
+     - Print hillas source position dependent stuff
+
+  2004/08/03 Ester Aliu Fusté
+    * library/MIslands.[h, cc], MIslandCalc.[h,cc]
+     - Add the delete for the pointers  
+
+  2004/08/02 Ester Aliu Fusté
+    * library/MIslands.[h, cc], MIslandCalc.[h,cc]
+     - Added the variables: distance (Dist) between the larger island and 
+       the other ones, width and lenght of the larger island. 
+     
+     - Written pointers instead of vectors 
+     
+  2004/07/28 Javi Lopez
+    * script/
+     - Created directory call scripts
+     - Added srcPosRun.sh script to create the *.pos file for the MSrcPosFromFile
+       task.
+     - Added makeHillas.sh script that run several makeHillas making groups of
+       data runs with preavius pedestal run.
+  
+  2004/07/28 Ester Aliu Fuste
+    * programa/makeHillas.cc
+     - Add a flag for the time calibration
+ 
+  2004/07/26 Ester Aliu Fuste
+    * library/MIslandCalc.cc
+     - Add the initialization of Dist(to -1) and MeanX/MeanY (to -10000) vectors
+
+  2004/07/22 Oscar Blanch Bigas
+    * programs/makeHillas.cc
+     - Solved backwards compatibility on the CLEANLEVEL
+       options.
+
+  2004/07/22 Ester Aliu 
+    * library/MIslands.[h,cc],MIslandCalc.cc
+     - Add meanX, meanY and dist of each of the islands
+     - Now the island with id 0 is the larger one
+
+  2004/07/21  Javier Rico
+    * programs/makeHillas.cc, srcPos.cc
+      - Add time information
+
+    * programs/makehillas.datacard
+      - Add comment
+
+  2004/07/20  Javier Lopez
+    * library/MLiveTime.[h,cc]
+      - Containers to hold the live time. It has the option to
+      have several time bins.
+    * library/MLiveTimeCalc.[h,cc]
+      - Task to compute the live time from the data. 
+    * macros/runlivetime.C
+      - Macro to use the MLiveTime+ stuff.
+
+  2004/07/15  Javier Lopez
+    * macros/ligthcurve.C
+      - Macro to compute a light curve from hillas files.
+
+  2004/07/04  Oscar Blanch Bigas
+    * library/MControlPlots.cc
+      - Off MHCamera normalised to On
+
+    * programs/makeHillas.cc
+      - Added clean flags to chose: number of rings and kDemocratic.
+      - Using different Pedestal run for the calibration.
+
+    * programs/optimizeCuts.cc
+      - Added alias for MNewImageParameters.fInnerLeakage
+
+    * calib.[cc,datacard]
+      - Added : produces ascci file with relevant factors of
+                Calibration
+
+    * controlPlot.cc, controlplot.datacard
+      - Added : It makes Number of hits plot.
+
+  2004/06/30: Javier Rico
+
+    * mifae/library/MDisp.cc
+      - Remove include of deprecated library
+      - Define namespace
+
+    * mifae/library/MControlPlots.cc
+      - Define style
+      - Add projection
+      - Plot 3rd plot correctly
+      - Search for "MIsland" instead of "MIsland1" container
+
+  2004/06/26: Eva Domingo - Pepe Flix
+
+    * mifae/library/MDisp.[h,cc]
+    * mifae/library/MDispCalc.[h,cc]
+      - Added classes for evaluation of DISP method.
+
+  2004/06/22  Javier Rico
+    * library/MControlPlots.[h,cc]
+      - Added
+
+    * library/Makefile, IFAELinkDef.h
+      - Add MControlPlots. So far, it produces plots with the number
+        of times each pixel survives the cleaning. It needs a MIsland
+        object to be included on the parameter list
+
+    * programs/makeHillas.cc
+      - Change pointer to MWriteRootFile object for MWriteRootFile 
+	object (otherwise the tree "Parameters" is not saved)
+      - Islands are always computed since are needed for some control
+        plots
+
+    * programs/srcPos.cc
+      - Add MControlPlots to the task list
+
+    * library/MSrcPosFromFile.cc
+      - Cope with case where first analyzed run is not in input file
+
+  2004/06/15  Javier Lopez
+    * library/MSrcPosFromStars.[h,cc]
+      - Task to compute the position of a source from
+        the positions of several stars.
+
+    * library/MHPSFFromStars.[h,cc]
+      - Histogram task that holds and fills the histograms of 
+        positioning and point spread function of an star.
+
+    * macros/distancebetweenstars.C
+      - Add macros that show in an histogram the distance between
+        the stars in a field of view. 
+
+    * macros/psffromstars.C
+      - Add task that show the point spread funtion and positon of
+        the most central star in the field of view. This information
+        is compute using the MFindStars tool.
+
+ 2004/06/11 Ester Aliu 
+   * programs/makeHillas.cc
+     - add the possibility of using more than one algorithm to 
+      calculate the islands and use different algorithms for counting
+      islands
+
+   * library/MIslands.[h,cc],MIslandCalc.[h,cc], MIslandCleaning.[h,cc]
+     - add a new island cleaning which consists in removing all the
+      islands except the larger one
+     - add a new algorithm of counting islands consisting in consider
+      as the same islands those islands separated by 2 or less pixels
+
+ 2004/06/02 Javier Rico
+   * srcpositions, srcpositions/Mrk421_220404_pos.txt
+     - add directory to store files with source positions and a first
+       sample file (with real data)
+
+ 2004/06/01 Javier Rico
+   * macros/observationTime.C
+     - add macro to compute observation time
+
+ 2004/05/28 Javier Rico
+   * programs/optimizeCuts.cc programs/optimizecuts.datacard
+     - Include loop on size
+
+ 2004/05/27 Ester Aliu 
+   * programs/makeHillas.cc
+     - Add the name of the MIslands container
+
+   * library/MHillasDisplay.[h,cc]
+     - Add a function which retuns the name of the MIslands container
+
+   * library/MIslands.[h,cc],MIslandCalc.cc
+     - Add MIslands::Print() function wich prints the island parameters
+     - Change some part of the code to take into account that some 
+     times there are bad pixels
+
+ 2004/05/27 Javier Rico
+   * programs/makeHillas.cc, programs/makehillas.datacard
+     - Remove unneeded MCalibrationQECam and MBadPixelsCam objects, 
+       trying to trace back a bug in the calibration
+     - Add possibility to interpolate bad pixels
+
+   * library/MHillasDisplay.cc
+     - Initialize MIslands object in constructor
+	
+ 2004/05/26 Javier Rico
+   * library/MHillasDisplay.[h,cc]
+     - Call for MIslands::Print() in the process if any MIslands is 
+       found
+	
+ 2004/05/24 Javier Rico
+   * library/MDisplay.[h,cc], programs/makeHillas.cc, 
+     programs/makehillas.datacard
+     - Add possibility to save a ps file
+     - Update documentation
+     - Cope with the case when no cut is provided
+	
+   * library/MHillasDisplay[h.cc]
+     - correct minor axis paint
+     - include MNewImagePar dumping
+     - update documentation
+	
+ 2004/05/21 Oscar Blanch
+   * makeHillas.cc
+     - Adde a couple of conditionals to allow makeHillas in 
+       NON calibration mode without giving a Cailbration file,
+	
+ 2004/05/21  Javier Rico
+   * library/MDCA.[cc.h]
+     - removed
+
+   * library/MDisplay.[h,cc], library/MHillasDisplay.[h,cc]
+     - added
+
+   * library/Makefile, library/IFAELinkDef.h
+     - remove MDCA
+     - add MDisplay and MHillasDisplay
+
+   * library/MSrcPlace.[h,cc], library/MSrcRotate.[h,cc],
+     library/MSrcTranslate.[h,cc], library/MSrcPosFromFile.cc
+     - remove MDCA dependences
+
+   * programs/makeHillas.cc, programs/makehillas.datacard
+     - include display and selection cuts options
+	
+   * programs/Makefile
+     - include mfbase in the list of includes directory
+
+ 2004/05/18  Javier Rico
+   * macros/plotOptimal.C
+     - dump value of maximal significance and cuts
+
+ 2004/05/18  Javier Rico
+   * library/MSrcPlace.[cc,h], library/MSrcRotate.[cc,h], 
+     library/MSrcTranslate.[cc,h], library/MSrcPosFromFile.[cc,h]
+     - Add the possibility of having different input and output 
+       MSrcPosCam containers (CONSTRUCTORS HAVE CHANGED!)
+     - Move the creation of internal histogram to PreProcess, so that
+       it can be configured before creation. Now configurable: whether
+       histo must be created or not (fCreateHisto), histo bin size 
+       (fHistoBinPrec), histogram name (fHistoName), with corresponding
+       getters and setters
+     - Update documentation
+
+   * library/MSrcPosFromFile.cc	
+     - If no position has been measured for the first analyzed run, use
+       the one of the first run in file instead.
+
+   * programs/falseSource.cc
+     - Change obsolete MSrcPosCam predefinitions for modern 
+       MSrcTranslate objects, which allow relative displacement of the
+       source position from a previously assigned one. 
+     - Add flag for relative translation
+     - Include control histograms (hOn[Off]SrcPos) for the source 
+       position
+
+   * programs/falsesource.datacard
+     - Add datacard SRCABS for relative/absolute source translation
+
+   * programs/srcPos.cc
+     - Avoid creation of internal histograms for the translation
+
+   * programs/optimizeCuts.cc
+     - Correct bug on width initial value
+
+   * programs/makeHillas.cc
+     - Pass MCalibrationQECam from the MJCalibration to the following
+       loops (to be able to perform calibration of data)
+	
+	
+ 2004/05/17  Javier Rico
+   * library/MSrcPlace.[cc,h], library/MSrcRotate.cc, 
+     library/MSrcTranslate.cc
+     - Assign the internal histogram a class-dependent name
+     - Add some log lines to trace the classes behaviour
+     - Remove function SearchForSrcPos
+
+   * library/MSrcPosFromFile.[cc,h]
+     - Correct behaviour for not found runs
+     - Keep latest good MSrcPosCam to fill for next events
+     - Initialize pointers to NULL
+     - Fill also MDCA
+
+	
+ 2004/05/14  Javier Rico
+   * library/MSrcPlace.[cc,h]
+     - added
+
+   * library/MSrcPosFromFile.[cc,h], library/MSrcRotate.[cc,h],
+     library/MSrcTranslate.[cc,h]
+     - inherit from MSrcPlace
+
+   * programs/srcPos.cc programs/srcpos.datacard
+     - adapt to new MSrcPlace class
+	
+   * library/Makefile, library/IFAELinkDef.h
+     - include MSrcPlace
+
+ 2004/05/13  Javier Rico
+   * macros/rotation.C
+     - added
+
+
+ 2004/05/13  Javier Lopez
+   * library/MCalibrateDC.[h,cc]
+     - Task to intercalibrate the dc response of the dc
+       current for all the pmts from a continuos light
+       run.
+
+ 2004/05/12: Javier Rico
+   * macros/alpha.C, macros/plotOptimal.C
+     - added
+
+   * library/MSrcRotate.[cc.h]
+     - correct bug in computation of run time for rotation
+	
+   * programs/srcPos.cc
+     - change mjdpos type to Double_t
+	
+	
+	
+ 2004/05/11: Javier Rico
+   * programs/optimizeCuts.cc, programs/optimizecuts.datacard
+     - added
+
+   * programs/Makefile
+     - include optimizeCuts
+
+   * programs/srcPos.cc, programs/srcpos.datacard
+     - add reference rotation angle
+
+	
+ 2004/05/11: Ester Aliu
+   *  macros/signal.cc 
+     - change some things
+   *  programs/falseSource.cc 
+     - change some mathematical functions to root equivalents 
+   *  programs/psffit.cc
+     - add <stdlib.h> library 
+
+ 2004/05/11: Ester Aliu 
+   * programs/makeHillas.cc, programs/makehillas.datacard
+     - add island calculations
+ 
+ 2004/05/11: Javier Rico
+   * programs/makeHillas.cc
+     - prevent it from bombing because of the mjobs
+
+
+ 2004/05/10: Javier Rico
+   * programs/Makefile
+     - specify libmars.so with absolute path
+
+	
+ 2004/05/07: Javier Rico
+   * programs/pedvsslices.cc
+     - added
+
+	
+ 2004/05/05: Ester Aliu
+   * library/MPSFFitCalc.cc library/MSrcRotate.cc
+     - change some mathematical functions to root equivalents 
+
+   * library/MIslands.[h,cc], library/MIslandCalc.[h,cc],
+    library/MIslandClean.[h,cc]
+     - added
+
+   * library/Makefile, library/IFAELinkDef.h
+     - add MIslands, MIslandCalc, MIslandClean
+ 
+ 2004/05/05: Javier Lopez
+   * library/MFHVNotNominal.[h,cc]
+     - filter to flag events(pixels) with non nominal hv
+ 
+   * macros/hvnotnominal.C
+     - macro to test MFHVNotNominal filter
+
+ 2004/05/05: Javier Rico
+   * library/MSrcTranslate.[h,cc]
+     - added
+
+   * library/Makefile, library/IFAELinkDef.h
+     - add MSrcTranslate
+
+   * library/MSrcRotate.[h.cc]
+     - adapted to changes in MObservatory and MAstro
+   
+   * programs/falseSource.cc programs/falsesource.datacard 
+     programs/srcPos.cc programs/srcpos.datacard
+     - added
+
+   * programs/Makefile
+     - add falseSource and srcPos
+
+   * macros/signal.C macros/signalPoint.C
+     - added
+	
+ 2004/05/03: Javier Rico
+   * makeHillas.cc
+     - put back Jobs for pedestal and calibration parts
+
+   * .rootrc
+     - added
+
+ 2004/05/03: Javier Rico
+   * library,programs,macros,*:
+     - new directories added
+     - directory macros contains macros (.C) and scripts (.sh)
+     - directory programs contains root compilables and associated
+       [input] files
+     - directory library contains routines to be linked with libmars.so
+	
+ 2004/04/30: Javier López
+   * alpha_plot.C
+     - macro to display hillas disttributions with corrected 
+       miss pointing
+
+   * srcPosRun.sh
+     - Script to produce the file with the positions of UMa51 using 
+       psffit executable
+
+   * MSrcPosFromFile.[h,cc]
+     - Tool to correct the position of the source for on and off data 
+       from a file
+ 
+   * psffit.C & psffit.cc
+     - Macro and executable to calculate the mean position of a star.
+
+   * MPSFFit.[h,cc] & MPSFFitCalc.[h,cc]
+     - Container and taks to do calculation of the psf and position of 
+       stars.
+
+ 2004/04/28: Javier Rico
+   * makeHillas.cc, makehillas.datacard
+     - Use MJPedestal and MJCalibration and simplified datacard
+
+   * Makefile
+     - include mjobs
+
+	
+ 2004/04/28: Javier Rico
+   * mifae/Changelog
+     - Added. Next changes in directory mifae will be reported 
+       exclusively in here
+
+	
+ 2004/04/27: Javier Rico
+   * mifae
+     - Add new directory for IFAE temporal stuff
+	
+   * mifae/Makefile,IFAEIncl.h,IFAELinkDef.h
+     - Add basic stuff to run the directory
+	
+   * mifae/MDCA.[h,cc]
+     - Add Commichau & Starks's MDCA (provisional)
+
+   * mifae/makeHillas.cc,makehillas.datacard
+     - Add program to generate hillas parameters' file
Index: /tags/Mars-V0.9/mtemp/mifae/library/IFAEIncl.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/IFAEIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/IFAEIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtemp/mifae/library/IFAELinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/IFAELinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/IFAELinkDef.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MDisplay+;
+#pragma link C++ class MHillasDisplay+;
+#pragma link C++ class MPSFFit+;
+#pragma link C++ class MPSFFitCalc+;
+#pragma link C++ class MSrcPlace+;
+#pragma link C++ class MSrcPosFromFile+;
+#pragma link C++ class MSrcRotate+;
+#pragma link C++ class MSrcTranslate+;
+#pragma link C++ class MIslands+;
+#pragma link C++ class MImgIsland+;
+#pragma link C++ class MIslandsCalc+;
+#pragma link C++ class MIslandsClean+;
+#pragma link C++ class MFHVNotNominal+;
+#pragma link C++ class MCalibrateDC+;
+#pragma link C++ class MHPSFFromStars+;
+#pragma link C++ class MControlPlots+;
+#pragma link C++ class MSrcPosFromStars+;
+#pragma link C++ class MLiveTime+;
+#pragma link C++ class MLiveTimeCalc+;
+#pragma link C++ class MTopology+;
+#pragma link C++ class MTopologyCalc+;
+#pragma link C++ class MImageParDisp+;
+#pragma link C++ class MDispParameters+;
+#pragma link C++ class MDispCalc+;
+#pragma link C++ class MHDisp+;
+#pragma link C++ class MFDisp+;
+#pragma link C++ class MFindDisp+;
+#pragma link C++ class MEffAreaAndCoeffCalc+;
+#pragma link C++ class MGainFluctuationPix+;
+#pragma link C++ class MGainFluctuationCam+;
+#pragma link C++ class MGainFluctuationCamIter+;
+#pragma link C++ class MAddGainFluctuation+;
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MAddGainFluctuation.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MAddGainFluctuation.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MAddGainFluctuation.cc	(revision 9772)
@@ -0,0 +1,219 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch Bigas 01/2005  <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2002-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MAddGainFluctuation
+//
+//   This is a task which add gain fluctuatins
+//
+//  Input Containers:
+//   MCerPhotEvt
+//   MGainFluctuationCam
+//   MGeomCam
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MAddGainFluctuation.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+#include "MGainFluctuationCam.h"
+
+#include "TRandom.h"
+
+ClassImp(MAddGainFluctuation);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MAddGainFluctuation::MAddGainFluctuation(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MAddGainFluctuation";
+    fTitle = title ? title : "Add gain fluctuation";
+
+    FillHist(1,0.1);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MCerPhotEvt
+//  - MGeomCam
+//
+// The following containers are also searched and created if
+// they were not found:
+// - MGainFluctuationCam
+//
+//
+Int_t MAddGainFluctuation::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fCerPhotEvt)
+        return kFALSE;
+
+    fGainFlucCam = (MGainFluctuationCam*)pList->FindCreateObj(AddSerialNumber("MGainFluctuationCam"));
+    if (!fGainFlucCam)
+        return kFALSE;
+
+
+    Fill();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MAddGainFluctuation::ReInit(MParList *pList)
+{
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scale the content of MCerPhotPix by Gain fluctuaion
+//
+Int_t MAddGainFluctuation::Process()
+{
+    //fCerPhotEvt->InitSize(fRawEvt->GetNumPixels());
+
+//    if (fIsMcFile)
+//        ScalePedestals();
+
+    if(!fAddFluctuations)
+      return kTRUE;
+
+    Double_t gain;
+
+    MCerPhotPix *pix = 0;
+
+    TIter Next(*fCerPhotEvt);
+
+    while ((pix=(MCerPhotPix*)Next()))
+    {
+        const UInt_t idx = pix->GetPixId();
+
+	fGainFlucCam->GetPixelContent(gain,idx,*fGeomCam,1);
+	pix->Scale(1.0/gain);
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill Histogram with Gain Fluctuations distribution in the Camera
+//
+//  flag:
+//
+//     0 : All to one
+//     1 : Gaussian centered at one with sigma "sigma"
+//     2 : Uniform distribution from 1/sigma to 1*sigma
+void MAddGainFluctuation::FillHist(int flag, float sigma){
+
+  TRandom rnd;
+  Float_t val;
+
+  fGainsDistribution = new TH1F("Gain","Gain Fluctuatins",1000,0.0,2.0);
+
+  switch(flag){
+  case 0:
+    fAddFluctuations=0;
+    break;
+  case 1:
+    fAddFluctuations=1;
+    for(int i=0;i<10000;i++){
+      val=rnd.Gaus(1.0,sigma);
+      fGainsDistribution->Fill(val);
+    }
+    break;
+  case 2:
+    fAddFluctuations=1;
+    for(int i=0;i<10000;i++){
+      val=rnd.Uniform(1.0/sigma,1.0*sigma);
+      fGainsDistribution->Fill(val);
+    }
+    break;
+  default:
+    fAddFluctuations=0;
+    for(int i=0;i<10000;i++){
+      val=rnd.Gaus(1.0,sigma);
+      fGainsDistribution->Fill(val);
+    }
+    break;
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set and Fill Histogram with Gain Fluctuations distribution in the Camera
+//
+void MAddGainFluctuation::SetHist(int bins, float fb, float lb, float *values){
+
+  fGainsDistribution = new TH1F("Gain","Gain Fluctuatins",bins,fb,lb);
+  
+  for(int i=0;i<bins;i++){
+    fGainsDistribution->SetBinContent(i,values[i]);
+  }
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill MGainFluctuatinCam 
+//
+void MAddGainFluctuation::Fill(){
+
+  const Int_t pixels=fGeomCam->GetNumPixels();
+  
+  if(fAddFluctuations)
+    for (int idx=0;idx<pixels;idx++)
+      fGainFlucCam->AddPixel(idx,fGainsDistribution->GetRandom());
+  else
+    for (int idx=0;idx<pixels;idx++)
+      fGainFlucCam->AddPixel(idx,1.0);
+
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MAddGainFluctuation.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MAddGainFluctuation.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MAddGainFluctuation.h	(revision 9772)
@@ -0,0 +1,54 @@
+#ifndef MARS_MAddGainFluctuation
+#define MARS_MAddGainFluctuation
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCerPhotCalc                                                            //
+//                                                                         //
+// Integrates the desired ADC time slices of one pixel and substracts the  //
+// pedestal (offset) value                                                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TH1F
+#include <TH1F.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MCerPhotEvt;
+class MGainFluctuationCam;
+class MGeomCam;
+class TH1F;
+
+class MAddGainFluctuation : public MTask
+{
+    const MGeomCam     *fGeomCam;
+    MCerPhotEvt    *fCerPhotEvt; // Cerenkov Photon Event used for calculation
+    MGainFluctuationCam    *fGainFlucCam; // Gain Fluctuation
+    TH1F *fGainsDistribution;   // Distribution of Gain fluctuatins in the Camera
+    Int_t fAddFluctuations;     // If 0 skip Process
+
+    void Fill();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MAddGainFluctuation(const char *name=NULL, const char *title=NULL);
+
+    void SetHist(int bins, float fb, float lb, float *values);
+    void FillHist(int flag, float sigma);
+
+    ClassDef(MAddGainFluctuation, 0)   // Task to add Gain fluctuations
+};
+ 
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MCalibrateDC.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MCalibrateDC.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MCalibrateDC.cc	(revision 9772)
@@ -0,0 +1,272 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier López , 5/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MCalibrateDC
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateDC.h"
+
+#include <TString.h>
+#include <TH1F.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+#include "MTime.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MReadReports.h"
+#include "MGeomApply.h"
+
+ClassImp(MCalibrateDC);
+using namespace std;
+
+MCalibrateDC::MCalibrateDC(TString filename, const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MCalibrateDC";
+  fTitle = title ? title : "Taks to intercalibrate the DC of all pmts from a continuos light run";
+
+  fFileName = filename;
+  
+  fStartingMissCalibration.Set(2004,3,8);
+  fEndingMissCalibration.Set(2004,4,15);
+  
+  Int_t   nbins = 120;
+  Float_t min = 0;
+  Float_t max = 30.;
+  fCalHist = new TH1F("calhist","",nbins,min,max);
+
+  fDCCalibration = 1.;
+  fDCCalibrationRMS = 0.;
+
+  fDCMissCalibrationFactor = 30./40.95;
+}
+MCalibrateDC::~MCalibrateDC()
+{
+  delete  fCalHist;
+}
+
+Int_t MCalibrateDC::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+
+    if (!fGeomCam)
+    {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    // Initialization of objects that need the information from MGeomCam
+    fDisplay.SetGeometry(*fGeomCam);
+    fNumPixels = fGeomCam->GetNumPixels();
+
+    fCurr = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+
+    if (!fCurr)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fTimeCurr = (MTime*)pList->FindObject(AddSerialNumber("MTimeCurrents"));
+
+    if (!fTimeCurr)
+    {
+      *fLog << err << AddSerialNumber("MTimeCurrents") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    // Run over the continuos light run to get the DC intercalibration factors
+    fDCCalibrationFactor.Set(fNumPixels);
+    fDCCalibrationFactor.Reset(1.);
+
+    if ( fFileName != "" )
+      {
+        ProcessFile();
+        DCCalibrationCalc();
+ 
+        UInt_t numPixelsSetUnsuedForDC = 0;
+        
+        for (UInt_t pix=1; pix<fNumPixels; pix++)
+          {
+            if (fDisplay.GetBinContent(pix+1) > fMinDCAllowed)
+              fDCCalibrationFactor[pix] = fDCCalibration/fDisplay.GetBinContent(pix+1);
+            else
+              {
+                numPixelsSetUnsuedForDC++;
+                fDCCalibrationFactor[pix] = 0.; //FIXME: Maybe to introduce a setunused in MCameraDC ?
+              }
+          }
+
+        *fLog << inf << GetName() << " set unused " << numPixelsSetUnsuedForDC << " because too low dc." << endl;
+        
+      }
+
+    return kTRUE;
+}
+
+Int_t MCalibrateDC::Process()
+{
+
+  if (*fTimeCurr >= fStartingMissCalibration && *fTimeCurr <= fEndingMissCalibration)
+    {
+      for (UInt_t pix=1; pix<fNumPixels; pix++)
+        {
+          MGeomPix& pixel = (*fGeomCam)[pix];
+          if (pixel.GetSector() >=3 && pixel.GetSector() <=5)
+            (*fCurr)[pix] *= fDCCalibrationFactor[pix]*fDCMissCalibrationFactor;
+          else
+            (*fCurr)[pix] *= fDCCalibrationFactor[pix];
+
+        }
+    }
+  else
+    for (UInt_t pix=1; pix<fNumPixels; pix++)
+      (*fCurr)[pix] *= fDCCalibrationFactor[pix];
+	  
+  return kTRUE;
+}
+
+Bool_t MCalibrateDC::ProcessFile()
+{
+
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MCameraDC     dccam;
+    plist.AddToList(&dccam);
+
+    // Reads the trees of the root file and the analysed branches
+    MReadReports read;
+    read.AddTree("Currents"); 
+    read.AddFile(fFileName);     // after the reading of the trees!!!
+    read.AddToBranchList("MReportCurrents.*");
+    
+    MGeomApply geomapl;
+
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&read);
+
+    // Enable logging to file
+    //*fLog.SetOutputFile(lname, kTRUE);
+
+    //
+    // Execute the eventloop
+    //
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetLogStream(fLog);
+
+    // Execute first analysis
+      if (!evtloop.PreProcess())
+        {
+          *fLog << err << GetDescriptor() << ": Failed." << endl;
+	  return kFALSE;
+        }
+        
+      while (tlist.Process())
+        fDisplay.AddCamContent(dccam);
+        
+      evtloop.PostProcess();
+
+    tlist.PrintStatistics();
+
+    UInt_t numexecutions = read.GetNumExecutions();
+    UInt_t numPixels = fDisplay.GetNumPixels();
+    for (UInt_t pix = 1; pix <= numPixels; pix++)
+      fDisplay[pix] /= numexecutions;
+    
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+
+    return kTRUE;
+}
+
+Bool_t MCalibrateDC::DCCalibrationCalc()
+{
+
+   for (UInt_t pix=1; pix<fNumPixels; pix++)
+       fCalHist->Fill(fDisplay.GetBinContent(pix+1));
+
+   Float_t nummaxprobdc = fCalHist->GetBinContent(fCalHist->GetMaximumBin());
+   Float_t maxprobdc = fCalHist->GetBinCenter(fCalHist->GetMaximumBin());
+   UInt_t bin = fCalHist->GetMaximumBin();
+   do
+   {
+       bin++;
+   }
+   while(fCalHist->GetBinContent(bin)/nummaxprobdc > 0.5);
+   Float_t halfmaxprobdc = fCalHist->GetBinCenter(bin);
+
+   *fLog << dbg << " maxprobdc[high] " << maxprobdc << "[" << nummaxprobdc << "] ";
+   *fLog << dbg << " halfmaxprobdc[high] " << halfmaxprobdc << "[" << fCalHist->GetBinContent(bin) << "]" << endl;
+
+   Float_t rmsguess = TMath::Abs(maxprobdc-halfmaxprobdc);
+   Float_t min = maxprobdc-3*rmsguess;
+   min = (min<0.?0.:min);
+   Float_t max = maxprobdc+3*rmsguess;
+
+   *fLog << dbg << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+
+   TF1 func("func","gaus",min,max);
+   func.SetParameters(nummaxprobdc, maxprobdc, rmsguess);
+   
+   fCalHist->Fit("func","QR0");
+
+   UInt_t aproxnumdegrees = 6*(bin-fCalHist->GetMaximumBin());
+   Float_t chiq = func.GetChisquare();
+   fDCCalibration = func.GetParameter(1);
+   fDCCalibrationRMS = func.GetParameter(2);
+
+   *fLog << dbg << " fDCCalibration " << fDCCalibration << " fDCCalibrationRMS " << fDCCalibrationRMS << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+
+   Int_t numsigmas = 5;
+   Axis_t minbin = fDCCalibration-numsigmas*fDCCalibrationRMS/fCalHist->GetBinWidth(1);
+   minbin=minbin<1?1:minbin;
+   Axis_t maxbin = fDCCalibration+numsigmas*fDCCalibrationRMS/fCalHist->GetBinWidth(1);
+   *fLog << dbg << " Number of pixels with dc under " << numsigmas << " sigmas = " << fCalHist->Integral((int)minbin,(int)maxbin) << endl;
+
+    //Check results from the fit are consistent
+    if (TMath::Abs(fDCCalibration-maxprobdc) > rmsguess || fDCCalibrationRMS > rmsguess)
+      {
+        *fLog << warn << GetName() << " Calibration DC fit give non consistent results." << endl;
+        *fLog << warn << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+        *fLog << warn << " fDCCalibration " << fDCCalibration << " fDCCalibrationRMS " << fDCCalibrationRMS << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+        fDCCalibration = maxprobdc;
+        fDCCalibrationRMS = rmsguess/1.175; // FWHM=2.35*rms
+      }
+
+   return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MCalibrateDC.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MCalibrateDC.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MCalibrateDC.h	(revision 9772)
@@ -0,0 +1,76 @@
+#ifndef MARS_MCalibrateDC
+#define MARS_MCalibrateDC
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TH1F;
+class MGeomCam;
+class MCameraDC;
+
+class MCalibrateDC : public MTask
+{
+
+private:
+
+    MGeomCam      *fGeomCam;
+    MCameraDC     *fCurr;
+    MTime         *fTimeCurr;
+
+    MTime fStartingMissCalibration;
+    MTime fEndingMissCalibration;
+    
+    TString fFileName;
+    
+    TH1F *fCalHist;
+    MHCamera fDisplay;
+
+    Double_t fMinDCAllowed; //[uA]
+    
+    UInt_t fNumPixels ;
+    TArrayD  fDCCalibrationFactor;
+    Double_t fDCMissCalibrationFactor;
+    
+    Double_t fDCCalibration; //[uA]
+    Double_t fDCCalibrationRMS; //[uA]
+    
+    Bool_t ProcessFile();
+    Bool_t DCCalibrationCalc();
+    
+  public:
+    
+    MCalibrateDC(TString filename="", const char *name=NULL, const char *title=NULL);
+    ~MCalibrateDC();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    //Setters
+    void SetFileName(TString filename="") {fFileName=filename;}
+    void SetMinDCAllowed(Double_t mindc=0.5) {fMinDCAllowed=mindc;}
+    
+    //Getters
+    MHCamera& GetDisplay() { return fDisplay; }
+    TArrayD&  GetDCCalibrationFactor() { return fDCCalibrationFactor; }
+
+    ClassDef(MCalibrateDC, 0) // Taks to intercalibrate the DC of all pmts from a continuos light run
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MControlPlots.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MControlPlots.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MControlPlots.cc	(revision 9772)
@@ -0,0 +1,262 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     04/2004 <mailto:jrico@ifae.es>
+!              Ester Aliu      10/2004 <mailto:aliu@ifae.es> (update according
+!                                        the new classes of the islands)
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MControlPlots
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+
+#include "TStyle.h"
+
+#include "MParList.h"
+#include "MControlPlots.h"
+#include "MIslands.h"
+#include "MImgIsland.h"
+#include "MHCamera.h"
+#include "MGeomCamMagic.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MControlPlots);
+
+using namespace std;
+
+static const TString gsDefName  = "MControlPlots";
+static const TString gsDefTitle = "Produce some control plots";
+
+// -------------------------------------------------------------------------
+//
+// Constructor
+//
+MControlPlots::MControlPlots(TString filename,const char* name, const char* title)
+  : fMode(kOn), fFileName(filename), fGeomCam(NULL), fIslands(NULL), fProduceFile(kTRUE)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fCameraHisto[kOn] = NULL;
+    fCameraHisto[kOff] = NULL;
+
+}
+// -------------------------------------------------------------------------
+//
+// Destructor
+//
+MControlPlots::~MControlPlots()
+{
+  Clear();
+
+  if(fCameraHisto[kOn])
+    delete fCameraHisto[kOn];
+  if(fCameraHisto[kOff])
+    delete fCameraHisto[kOff];
+}
+
+void MControlPlots::Clear(const Option_t *o)
+{
+
+  if(fGeomCam)
+    delete fGeomCam;
+
+  fGeomCam = NULL;
+}
+
+
+// -------------------------------------------------------------------------
+//
+// Look for needed containers.
+//
+Int_t MControlPlots::PreProcess(MParList* pList)
+{ 
+
+  Reset();
+
+  // FIXME! only valid for Magic geometry for the time being!
+  fGeomCam = new MGeomCamMagic;
+
+  // look for MIslands object
+  fIslands = (MIslands*)pList->FindObject("MIslands");
+  if (!fIslands)
+    *fLog << warn << AddSerialNumber("MIslands") << " [MIslands] not found... Some control plots will not be produced" << endl;
+  else
+    {  
+      if (fCameraHisto[fMode])
+	{
+	  *fLog << err << GetDescriptor() 
+		<< "Camera with mode " << fMode << " already existing " << endl;
+	  return kFALSE;
+	}
+      TString name = "";
+      switch (fMode)
+	{
+	case kOn:
+	  name += "On";
+	  break;
+	case kOff:
+	  name += "Off";
+	  break;
+	}
+      fCameraHisto[fMode] = new MHCamera(*fGeomCam,
+					 name.Data(),
+					 "Pixels surviving Image Cleaning");
+    }
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+//
+Int_t MControlPlots::Process()
+{ 
+  if(!fIslands) return kTRUE;
+
+  MImgIsland *imgIsl = NULL;
+  TIter Next(fIslands->GetList());
+  
+  Int_t pixNum = 0;  
+  Int_t idPix = -1;
+  
+  while ((imgIsl=(MImgIsland*)Next())) 
+    {
+      pixNum = imgIsl->GetPixNum();
+      
+      for(Int_t k = 0; k<pixNum; k++)
+	{
+	  idPix = imgIsl->GetPixList(k);
+	  fCameraHisto[fMode]->Fill(idPix,1.);
+	  fCameraHisto[fMode]->SetUsed(idPix);
+	}
+    }
+
+  /*  for (UInt_t i=0;i<fGeomCam->GetNumPixels();i++)
+    {
+      //      cout << fIslands->GetIslId(i) << " ";
+      if (fIslands->GetIslId(i)>=0)
+	{
+	  fCameraHisto[fMode]->Fill(i,1);
+	  fCameraHisto[fMode]->SetUsed(i);
+	}
+	}*/
+
+  //  cout << endl;
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+//
+Int_t MControlPlots::PostProcess()
+{
+  if(!fProduceFile) return kTRUE;
+  if(fProduceFile && !fFileName.Length())
+    {
+      *fLog << warn <<  "MControlPlots::PostProcess Warning: output file requested but no name for it" << endl;
+      return kTRUE;
+    }
+
+  // Canvas style
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+  gStyle->SetStatColor(0);
+  gStyle->SetTitleFillColor(0);
+
+  TCanvas* c = new TCanvas("survivals","Pixels surviving Image Cleaning",800,800);
+  MHCamera* diff=NULL;
+
+  // in case both on and off histos are present, print both and the difference between them
+  if(fCameraHisto[kOn] && fCameraHisto[kOff])
+    {      
+      diff = new MHCamera(*fGeomCam,"Diff","Difference of pixels surviving Image Cleaning");
+
+      // Normalize Off to On
+      Float_t NormOn=0;
+      Float_t NormOff=0;
+      for(Int_t i=1;i<diff->GetSize()-2;i++)
+	{
+	  NormOff+=fCameraHisto[kOff]->GetBinContent(i);
+	  NormOn+=fCameraHisto[kOn]->GetBinContent(i);
+	}      
+
+      fCameraHisto[kOff]->Scale(NormOn/NormOff);
+
+      for(Int_t i=1;i<diff->GetSize()-2;i++)
+	{
+	  diff->SetBinContent(i,(Double_t)fCameraHisto[kOn]->GetBinContent(i)-fCameraHisto[kOff]->GetBinContent(i));
+	  diff->SetUsed(i);
+	}      
+      fCameraHisto[kOn]->SetPrettyPalette();
+      fCameraHisto[kOff]->SetPrettyPalette();
+      diff->SetPrettyPalette();
+
+      c->Divide(2,2);
+
+      Float_t max = TMath::Max(fCameraHisto[kOn]->GetMaximum(),fCameraHisto[kOff]->GetMaximum());
+      Float_t min = TMath::Min(fCameraHisto[kOn]->GetMinimum(),fCameraHisto[kOff]->GetMinimum());
+      fCameraHisto[kOn]->SetMaximum(max);
+      fCameraHisto[kOn]->SetMinimum(min); 
+      fCameraHisto[kOff]->SetMaximum(max);
+      fCameraHisto[kOff]->SetMinimum(min); 
+      
+      c->cd(1);
+      fCameraHisto[kOn]->Draw();
+      gPad->Modified();
+      gPad->Update();
+
+      c->cd(2);
+      fCameraHisto[kOff]->Draw();
+      gPad->Modified();
+      gPad->Update();
+
+      c->cd(3);
+      diff->Draw();
+      gPad->Modified();
+      gPad->Update();      
+
+      c->cd(4);
+      diff->DrawProjection();
+      gPad->Modified();
+      gPad->Update();
+    }
+  // plot the existing histo
+  else
+    {
+      c->cd(1);
+      fCameraHisto[fMode]->Draw();
+      gPad->Modified();
+      gPad->Update();
+    }
+  
+  c->SaveAs(fFileName);
+  delete c;  
+  if(diff)
+    delete diff;
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MControlPlots.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MControlPlots.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MControlPlots.h	(revision 9772)
@@ -0,0 +1,47 @@
+#ifndef MARS_MControlPlots
+#define MARS_MControlPlots
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TString;
+class MIslands;
+class MImgIsland;
+class MGeomCam;
+class MHCamera;
+
+class MControlPlots : public MTask
+{
+ public:
+  enum OnOffMode_t {kOn=0,kOff=1};
+  
+ private:
+  OnOffMode_t  fMode;           // On/Off data mode 
+  TString      fFileName;       // name of the ps file
+  MGeomCam*    fGeomCam;        // pointer to camera geometry object
+  MIslands*    fIslands;        // pointer to the island object
+  MHCamera*    fCameraHisto[2]; // pointer to camera histos
+  Bool_t       fProduceFile;    // flag to produce the ouput (ps) file
+  
+  Int_t PreProcess(MParList *plist);
+  Int_t Process();
+  Int_t PostProcess();
+
+ public:
+  MControlPlots(TString filename="",const char* name=NULL, const char* title=NULL);
+
+  virtual ~MControlPlots();
+
+  void Reset() { Clear(); }
+  void Clear(const Option_t *o="");
+
+  void SetFilename(TString fname)           {fFileName=fname;}
+  void SetMode(OnOffMode_t mode)            {fMode=mode;}
+  void SetProduceFile(Bool_t mod=kTRUE)     {fProduceFile=mod;}  
+
+  ClassDef(MControlPlots, 0) // task to produce some control plots
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MDispCalc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MDispCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MDispCalc.cc	(revision 9772)
@@ -0,0 +1,345 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Eva Domingo    , 12/2004 <mailto:domingo@ifae.es>
+!              Wolfgang Wittek, 12/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MDispCalc                                                             //
+//                                                                         //
+//   This task calculates Disp with a given parameterization               //
+//   (parameters are stored in the MDispParameters container)              //
+//   Also the matrix of variables to be used in the Disp                   //
+//   parameterization is defined                                           //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MDispCalc.h"
+
+#include <math.h>
+#include <TArray.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MNewImagePar.h"
+#include "MMcEvt.hxx"
+#include "MPointingPos.h"
+#include "MImageParDisp.h"
+#include "MDispParameters.h"
+
+#include "MHMatrix.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MDispCalc);
+
+using namespace std;
+
+static const Int_t nPars=5;   // number of parameters used in the Disp expression
+
+enum dispVar_t {kSize,kWidth,kLength,kConc,kLeakage1,kLeakage2,kTotVar};  // enum variables for the
+                                                                          // matrix columns mapping
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+MDispCalc::MDispCalc(const char *imagepardispname, 
+		     const char *dispparametersname, 
+                     const char *name, const char *title)
+  :     fImageParDispName(imagepardispname), 
+	fDispParametersName(dispparametersname),
+	fLogSize0(3.), fLength0(0.1), fWidth0(0.05), 
+	fConc0(0.35), fLeakage10(0.05), fLeakage20(0.1)
+{
+    fName  = name  ? name  : "MDispCalc";
+    fTitle = title ? title : "Class to calculate Disp";
+
+    // object of MDispParamteres that will hold the Disp parameters
+    fDispParameters = new MDispParameters(fDispParametersName);
+    // initialize the size of the Disp parameters and parameters stepsizes arrays
+    fDispParameters->GetParameters().Set(nPars);
+    fDispParameters->GetStepsizes().Set(nPars);
+    // set Disp parameters to their default values
+    fDispParameters->InitParameters();
+
+    fMatrix = NULL;
+
+    // initialize mapping array dimension to the number of columns of fMatrix
+    fMap.Set(kTotVar);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MDispCalc::~MDispCalc()
+{
+    delete fDispParameters;
+}
+
+
+// --------------------------------------------------------------------------
+//
+Int_t MDispCalc::PreProcess(MParList *pList)
+{
+    // look for the defined camera geometry to get mm to deg conversion factor
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." 
+              << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+
+    // look for Disp related containers
+    fImageParDisp = (MImageParDisp*)pList->FindCreateObj("MImageParDisp", 
+                                                         fImageParDispName);
+    if (!fImageParDisp)
+    {
+        *fLog << err << fImageParDispName 
+              << " [MImageParDisp] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    //-----------------------------------------------------------
+    // if fMatrix exists, skip preprocessing and just read events from matrix;
+    // if doesn't exist, read variables values from containers, so look for them
+    if (fMatrix)
+        return kTRUE;
+
+    fSrcPos = (MSrcPosCam*)pList->FindObject("MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << "MSrcPosCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHil = (MHillas*)pList->FindObject("MHillas");
+    if (!fHil)
+    {
+        *fLog << err << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject("MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << "MHillasExt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject("MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << "MNewImagePar not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... This is not a MC file,"
+	      << " you are not trying to optimize Disp, just calculating it."
+	      << endl;
+	//        return kFALSE;
+    }
+
+    fPointing = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointing)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+	return kFALSE;
+    }
+
+    //------------------------------------------
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers for the Disp parameterization. This function adds all 
+// necessary columns to the given matrix. Afterwards, you should fill 
+// the matrix with the corresponding data (eg from a file by using 
+// MHMatrix::Fill). Then, if you loop through the matrix (eg using 
+// MMatrixLoop), MDispCalc::Calc will take the values from the matrix 
+// instead of the containers.
+//
+void MDispCalc::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    fMap[kSize]      = fMatrix->AddColumn("MHillas.fSize");
+    fMap[kWidth]     = fMatrix->AddColumn("MHillas.fWidth");
+    fMap[kLength]    = fMatrix->AddColumn("MHillas.fLength");
+
+    fMap[kConc]      = fMatrix->AddColumn("MNewImagePar.fConc");
+    fMap[kLeakage1]  = fMatrix->AddColumn("MNewImagePar.fLeakage1");
+    fMap[kLeakage2]  = fMatrix->AddColumn("MNewImagePar.fLeakage2");
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns a mapped value from the Matrix
+//
+Double_t MDispCalc::GetVal(Int_t i) const
+{
+    Double_t val = (*fMatrix)[fMap[i]];
+
+    //    *fLog << "MDispCalc::GetVal; i, fMatrix, fMap, val = "
+    //          << i << ",  " << fMatrix << ",  " << fMap[i] << ",  " << val << endl;
+
+    return val;
+}
+
+
+// ---------------------------------------------------------------------------
+//
+// Calculate Disp 
+// 
+//
+Int_t MDispCalc::Process()
+{
+    // get variables needed to compute disp from the matrix or the containers
+    const Double_t size     = fMatrix ? GetVal(kSize)     : fHil->GetSize();
+    const Double_t width0   = fMatrix ? GetVal(kWidth)    : fHil->GetWidth();
+    const Double_t length0  = fMatrix ? GetVal(kLength)   : fHil->GetLength();
+    const Double_t conc     = fMatrix ? GetVal(kConc)     : fNewPar->GetConc();
+    const Double_t leakage1 = fMatrix ? GetVal(kLeakage1) : fNewPar->GetLeakage1();
+    const Double_t leakage2 = fMatrix ? GetVal(kLeakage2) : fNewPar->GetLeakage2();
+
+    // convert to deg
+    const Double_t width   = width0  * fMm2Deg;
+    const Double_t length  = length0 * fMm2Deg;
+
+    // create an array to pass the variables to MDispCalc::Calc
+    TArrayD imagevars(kTotVar);
+    imagevars[kSize]      = log10(size);
+    imagevars[kWidth]     = width;
+    imagevars[kLength]    = length;
+    imagevars[kConc]      = conc;
+    imagevars[kLeakage1]  = leakage1;
+    imagevars[kLeakage2]  = leakage2;
+
+    // compute Disp
+    Double_t disp = Calc(imagevars); 
+
+    // save value into MImageParDisp container
+    fImageParDisp->SetDisp(disp);
+    fImageParDisp->SetReadyToSave();
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the Disp parameterization and Calculate Disp
+//
+//
+Double_t MDispCalc::Calc(TArrayD &imagevar)
+{
+    // get parameters
+    const TArrayD& p = fDispParameters->GetParameters();
+
+    // get image variables to be used in the Disp parameterization
+    Double_t logsize  = imagevar[0];
+    Double_t width    = imagevar[1];
+    Double_t length   = imagevar[2];
+    //    Double_t conc     = imagevar[3];
+    //    Double_t leakage1 = imagevar[4];
+    //    Double_t leakage2 = imagevar[5];
+    
+    // Disp parameterization to be optimized
+    //  Note: fLogSize0, fLength0... variables are introduced to uncorrelate as much
+    //        as possible the parameters in the Disp expression, with the purpose of
+    //        helping the minimization algorithm to converge. They are set approx.
+    //        to their distribution mean value in the MDisp constructor, but can be 
+    //        changed using the corresponding set function.
+    //
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0))*width/length;
+
+//    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(length-fLength0) 
+//      + (p[2] + p[3]*(logsize-fLogSize0))*width/length;
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(length-fLength0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0))*length/width;
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(length-fLength0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0) + p[5]*(length-fLength0))*width/length;
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(width-fWidth0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0))*width/length;   // + p[5]*(width-fWidth0))*width/length;
+
+    //    Double_t disp = p[0] + p[1]*(logsize-fLogSize0) + p[4]*(conc-fConc0) 
+    //      + (p[2] + p[3]*(logsize-fLogSize0))*width/length;   // + p[5]*(conc-fConc0))*width/length;
+
+    //    Double_t disp = ( p[0] + p[1]*(logsize-fLogSize0) 
+    //		      + p[2]*pow(logsize-fLogSize0,2)
+    //		      + p[3]*pow(logsize-fLogSize0,3) 
+    //		      + p[4]*pow(logsize-fLogSize0,4) )
+    //                    *(1-width/length);
+
+    
+    Double_t disp = ( p[0] + p[1]*(logsize-fLogSize0) 
+    		    + p[2]*pow(logsize-fLogSize0,2)
+    		    + p[3]*pow(logsize-fLogSize0,3) 
+    		    + p[4]*pow(logsize-fLogSize0,4) )
+                        *( 1./(1.+width/length) );
+
+    /*
+    Double_t disp = ( p[0] + p[1]*(logsize) 
+		    + p[2]*pow(logsize,2)
+    		    + p[3]*pow(logsize,3) 
+		    + p[4]*pow(logsize,4) )
+                        *( 1./(1.+width/length) );
+    */
+
+    return disp;
+}
+
+//===========================================================================
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MDispCalc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MDispCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MDispCalc.h	(revision 9772)
@@ -0,0 +1,107 @@
+#ifndef MARS_MDispCalc
+#define MARS_MDispCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MSrcPosCam;
+class MHillas;
+class MHillasExt;
+class MNewImagePar;
+class MMcEvt;
+class MPointingPos;
+class MImageParDisp;
+class MDispParameters;
+class MHMatrix;
+class MParList;
+
+class MDispCalc : public MTask
+{
+private:
+
+    MSrcPosCam      *fSrcPos;
+    MHillas         *fHil;
+    MHillasExt      *fHilExt;
+    MNewImagePar    *fNewPar;
+    MMcEvt          *fMcEvt;
+    MPointingPos    *fPointing;        
+    
+    MImageParDisp   *fImageParDisp;    //! output container for Disp value
+    MDispParameters *fDispParameters;  //!  container for Disp parameters
+
+    TString  fImageParDispName;    // name of container to store Disp
+    TString  fDispParametersName;  // name of container for Disp parameters
+
+    Double_t fLogSize0;            // Variables introduced in the Disp expression
+    Double_t fLength0;             // to shift the minimization around the mean
+    Double_t fWidth0;              // values of the variables, so it makes easier
+    Double_t fConc0;               // to MINUIT to converge. Default values are set
+    Double_t fLeakage10;           // in the constructor (to their standard mean 
+    Double_t fLeakage20;           // distribution values) but can be changed with
+                                   // the corresponding set function.
+
+    Double_t fMm2Deg;              // conversion factor from mm to deg
+
+    MHMatrix *fMatrix;             // matrix defined to have as much columns as 
+                                   // variables wanted to parameterize Disp,
+                                   // and as much rows as events used for the 
+                                   // optimization (filled at MFindDisp)
+
+    TArrayI  fMap;                 // array storing the matrix mapping column
+                                   // numbers corresponding to each variable
+                                   // added to fMatrix
+
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Double_t GetVal(Int_t i) const;        // get value of variable entered in the
+                                           // matrix at column fMap[i]
+
+
+public:
+
+    MDispCalc(const char *imagepardispname = "MImageParDisp",
+	      const char *dispname         = "MDisp",
+              const char *name=NULL, const char *title=NULL);
+    ~MDispCalc();
+
+    void InitMapping(MHMatrix *mat);       // define the matrix of variables
+                                           // needed for the Disp parameterization 
+
+    Double_t Calc(TArrayD &imagevar);      // calculate Disp with a given expression
+
+    void SetLogSize0(Double_t newmeanval)  { fLogSize0  = newmeanval; }
+    void SetWidth0(Double_t newmeanval)    { fWidth0    = newmeanval; }
+    void SetLength0(Double_t newmeanval)   { fLength0   = newmeanval; }
+    void SetConc0(Double_t newmeanval)     { fConc0     = newmeanval; }
+    void SetLeakage10(Double_t newmeanval) { fLeakage10 = newmeanval; }
+    void SetLeakage20(Double_t newmeanval) { fLeakage20 = newmeanval; }
+
+    MDispParameters *GetDispParameters()   { return fDispParameters; }
+
+    ClassDef(MDispCalc, 0) // Task to evaluate Disp
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MDispParameters.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MDispParameters.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MDispParameters.cc	(revision 9772)
@@ -0,0 +1,129 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Eva Domingo,     12/2004 <mailto:domingo@ifae.es>
+!              Wolfgang Wittek, 12/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MDispParameters                                                       //
+//                                                                         //
+//   this is the container for the Disp parameters                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MDispParameters.h"
+
+#include <math.h>
+#include <fstream>
+
+#include <TArrayD.h>
+
+#include "MImageParDisp.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MDispParameters);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+MDispParameters::MDispParameters(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MDispParameters";
+    fTitle = title ? title : "Container for the Disp parameters";
+}
+
+
+// --------------------------------------------------------------------------
+//
+// set default values for the Disp parameters
+//
+void MDispParameters::InitParameters()
+{
+    //---------------------------------------------------
+    //  these are the default values
+
+    fParameters[0] =  0.93227;
+    fParameters[1] =  0.187132;
+    fParameters[2] = -0.192808;
+    fParameters[3] =  0.0350143;
+    fParameters[4] = -0.0110078;
+
+
+    //---------------------------------------------------
+    // fStepsizes 
+    // if == 0.0    the parameter will be fixed in the minimization
+    //    != 0.0    initial step sizes for the parameters
+
+    fStepsizes[0] = 0.010;
+    fStepsizes[1] = 0.002;
+    fStepsizes[2] = 0.002;
+    fStepsizes[3] = 0.0004;
+    fStepsizes[4] = 0.0001;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the parameter values from the array 'd'
+//
+//
+Bool_t MDispParameters::SetParameters(const TArrayD &d)
+{
+    if (d.GetSize() != fParameters.GetSize())
+    {
+        *fLog << err << "Sizes of d and of fParameters are different : "
+              << d.GetSize() << ",  " << fParameters.GetSize() << endl;
+        return kFALSE;
+    }
+
+    fParameters = d;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the step sizes from the array 'd'
+//
+//
+Bool_t MDispParameters::SetStepsizes(const TArrayD &d)
+{
+    if (d.GetSize() != fStepsizes.GetSize())
+    {
+        *fLog << err << "Sizes of d and of fStepsizes are different : "
+              << d.GetSize() << ",  " << fStepsizes.GetSize() << endl;
+        return kFALSE;
+    }
+
+    fStepsizes = d;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MDispParameters.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MDispParameters.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MDispParameters.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifndef MARS_MDispParameters
+#define MARS_MDispParameters
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MDispParameters : public MParContainer
+{
+private:
+
+    TArrayD fParameters;      // Disp parameters
+    TArrayD fStepsizes;       //! step sizes of Disp parameters
+
+
+public:
+
+    MDispParameters(const char *name=NULL, const char *title=NULL);
+
+    void InitParameters();
+
+    Bool_t SetParameters(const TArrayD &d);
+    Bool_t SetStepsizes(const TArrayD &d);
+
+    void SetVariables(const TArrayD &d)    { SetParameters(d); }
+ 
+    TArrayD &GetParameters() { return fParameters; }
+    TArrayD &GetStepsizes()  { return fStepsizes;  }
+
+    ClassDef(MDispParameters, 1) // Container for the Disp parameters
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MDisplay.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MDisplay.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MDisplay.cc	(revision 9772)
@@ -0,0 +1,176 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     05/2004 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MDisplay
+//
+// Class to display camera events (MCamEvent)
+// You can set an event-by-event display with pause between two consecutive 
+// events. You can set an output PS file.
+//
+// Input containers (to be provided to the constructor):
+//
+//  MCamEvent
+//  MGeomCam
+//
+// Output containers:
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <math.h>
+
+#include "TCanvas.h"
+#include "TPostScript.h"
+
+#include "MParList.h"
+#include "MDisplay.h"
+#include "MCamEvent.h"
+#include "MGeomCam.h"
+#include "MHCamera.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MDisplay);
+
+using namespace std;
+
+static const TString gsDefName       = "MDisplay";
+static const TString gsDefTitle      = "Camera display task";
+static const TString gsDefPSFileName = "display.ps";
+
+// -------------------------------------------------------------------------
+//
+// Constructor. Need to provide the MCamEvent container to be displayed <event>
+// and camera geometry <geom>. Also the display type <type> can be specified
+// (see the MHCamera documentation for more details)
+//
+MDisplay::MDisplay(MCamEvent* event, MGeomCam* geom, Int_t type, const char* name, const char* title) 
+  :  fGeomCam(geom), fCamEvent(event),  fCanvas(NULL), fPSFile(NULL), fDisplayType(type), fCreatePSFile(kFALSE), fPause(kTRUE)
+{
+  fName  = name  ? name  : gsDefName.Data();
+  fTitle = title ? title : gsDefTitle.Data();
+
+  fDisplay = new MHCamera(*geom);
+  fDisplay->SetPrettyPalette();
+  
+  fPSFileName = gsDefPSFileName;
+}
+// -------------------------------------------------------------------------
+//
+// Destructor
+//
+MDisplay::~MDisplay()
+{
+  delete fDisplay;
+  if(fCanvas)
+    delete fCanvas;
+  if(fPSFile)
+    delete fPSFile;
+}
+
+// -------------------------------------------------------------------------
+//
+// Create the canvas, eventually set the batch mode and open ps file
+//
+Int_t MDisplay::PreProcess(MParList* pList)
+{ 
+  fCanvas = new TCanvas("myCanvas","Event Display",600,600);
+  if(fCreatePSFile) 
+    fPSFile = new TPostScript(fPSFileName,111);
+  if(!fPause)
+    fCanvas->SetBatch();
+  fCanvas->cd(1);
+  fDisplay->Draw();
+
+  //look for the run and event headers
+  fEvtHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+  if (!fEvtHeader)
+    {
+      *fLog << err << "MRawEvtHeader not found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+  if (!fRunHeader)
+    {
+      *fLog << err << AddSerialNumber("MRawRunHeader") << " not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the new containt of the camera event and update the display.
+// Set new page if ps file is requested
+// Pause execution if event-by-event display is chosen
+//
+Int_t MDisplay::Process()
+{  
+  // new page in ps file
+  if(fPSFile)
+    fPSFile->NewPage();
+
+  // update the display contents
+  fDisplay->SetCamContent(*fCamEvent,fDisplayType);
+  fCanvas->GetPad(1)->Modified();
+  fCanvas->GetPad(1)->Update();
+  
+  *fLog << all << "Run: " << fRunHeader->GetRunNumber() << ", Event: " << fEvtHeader->GetDAQEvtNumber() << endl;
+
+  // pause execution
+  if(fPause)
+    {
+      cout << "Type 'q' to exit, 'p' to print event into ps file, <return> to go on: ";      
+      TString input;
+      input =cin.get(); 
+      
+      if (input=='q')
+	return kFALSE;
+      if(input=='p')
+	{
+	  Char_t psfile[200];
+	  sprintf(psfile,"Run%06dEvent%07d.ps", fRunHeader->GetRunNumber(), fEvtHeader->GetDAQEvtNumber());
+	  fCanvas->Print(psfile);
+	}
+    }
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Close ps file if it was open
+//
+Int_t MDisplay::PostProcess()
+{
+  if(fPSFile) fPSFile->Close();
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MDisplay.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MDisplay.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MDisplay.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MDisplay
+#define MARS_MDisplay
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawRunHeader;
+class MRawEvtHeader;
+class MHCamera;
+class MCamEvent;
+class MGeomCam;
+class TCanvas;
+class TPostScript;
+
+class MDisplay : public MTask
+{
+ private:
+  MRawEvtHeader*  fEvtHeader;    // event header
+  MRawRunHeader*  fRunHeader;    // run header
+  MHCamera*       fDisplay;      // pointer to the camera display
+  MGeomCam*       fGeomCam;      // pointer to the camera geometry
+  MCamEvent*      fCamEvent;     // pointer to camera event
+  TCanvas*        fCanvas;       // pointer to the canvas
+  TPostScript*    fPSFile;       // pointer to ps file
+  TString         fPSFileName;   // name for ps file
+  Int_t           fDisplayType;  // display type (see MHCamera)
+  Bool_t          fCreatePSFile; // flag to produce a ps file with events
+  Bool_t          fPause;        // flag to pause execution between events
+  
+
+  virtual Int_t PostProcess();
+
+ protected:
+  virtual Int_t PreProcess(MParList *plist);  
+  virtual Int_t Process();
+
+ public:
+  MDisplay(MCamEvent* event, MGeomCam* geom, Int_t type=0, const char* name=NULL, const char* title=NULL);
+  virtual ~MDisplay();
+
+  virtual void Paint(Option_t* option)     {};
+
+  MGeomCam*    GetGeomCam()                {return fGeomCam;}
+  Bool_t       GetPauseMode()              {return fPause;}
+  Bool_t       GetCreatePSFile()           {return fCreatePSFile;}
+
+  void         SetDisplayType(Int_t type)  {fDisplayType=type;}
+  void         SetPSFile(Bool_t set=kTRUE) {fCreatePSFile=set;}
+  void         SetPSFileName(TString name) {fPSFileName=name;}
+  void         SetPause(Bool_t set=kTRUE)  {fPause=set;}
+
+  ClassDef(MDisplay, 0) // Task to display camera containers
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MEffAreaAndCoeffCalc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MEffAreaAndCoeffCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MEffAreaAndCoeffCalc.cc	(revision 9772)
@@ -0,0 +1,420 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     02/2005 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Computes the Effective areas and coefficients for unfolding for a given
+// spectrum that can be parametrized by a function
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <math.h>
+
+#include "MEffAreaAndCoeffCalc.h"
+
+#include "TF1.h"
+#include "MHillas.h"
+#include "MMcEvt.hxx"
+#include "TH2F.h"
+#include "TFile.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEffAreaAndCoeffCalc);
+
+using namespace std;
+
+const Int_t ntbins=1;                      // default number of theta bins
+const Double_t tbin[ntbins+1] = {0,90};    // default theta bins bounds
+const Int_t nebins = 10;                   // default number of energy bins
+const Float_t emin = 10.;                  // default minimum energy value
+const Float_t emax = 10000.;               // default maximum energy value
+const Int_t nsubbins = 20;                 // default number of subbins per bin
+const Char_t* deff = "4.e9*pow(x,-2.6+1)"; // default spectrum function
+
+// -------------------------------------------------------------------------
+//
+// Constructor
+//
+MEffAreaAndCoeffCalc::MEffAreaAndCoeffCalc()
+  : fSpec(NULL),  fEmin(emin), fEmax(emax), fEbins(nebins), fEsubbins(nsubbins), 
+    fWeight(NULL), fCoeff(NULL), fEffA(NULL)//, fFile(NULL)
+{
+  // set the default function
+  SetFunction(deff);  
+
+  // create the TChains 
+  fCini = new TChain("OriginalMC");
+  fCcut = new TChain("Events");
+
+  // define some useful aliases
+  fCini->SetAlias("logenergy","log10(MMcEvtBasic.fEnergy)");
+  fCini->SetAlias("theta","MMcEvtBasic.fTelescopeTheta*180./3.14159");
+
+  fCcut->SetAlias("logenergy","log10(MMcEvt.fEnergy)");
+  fCcut->SetAlias("theta","MMcEvt.fTelescopeTheta*180./3.14159");
+
+  fCcut->SetBranchAddress("MHillas.",&fHillas);
+  fCcut->SetBranchAddress("MMcEvt.",&fMcEvt);
+
+  // initial value of the zenith angle binning
+  SetThetaBinning(ntbins,tbin);
+  
+  // borra
+  //  fFile = new TFile("coeftest.root","RECREATE");
+}
+
+// -------------------------------------------------------------------------
+//
+// Destructor
+//
+MEffAreaAndCoeffCalc::~MEffAreaAndCoeffCalc()
+{
+  if(fSpec)
+    delete fSpec;
+
+  if(fTbin)
+    delete [] fTbin;
+
+  if(fWeight)
+    delete [] fWeight;
+
+  if(fCoeff)
+    delete fCoeff;
+
+  if(fEffA)
+    delete fEffA;
+
+
+  delete fCini;
+  delete fCcut;
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the binning in zenith angle
+//
+void MEffAreaAndCoeffCalc::SetThetaBinning(Int_t n, const Double_t* binlist)
+{
+  fNTbins=n;
+  if(fTbin) delete [] fTbin;
+  fTbin = new Double_t[n+1];
+  for(Int_t i=0;i<n+1;i++)
+    fTbin[i] = binlist[i];
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the function by expression and minimum and maximum energies
+//
+void MEffAreaAndCoeffCalc::SetFunction(const Char_t* chfunc, Float_t emin, Float_t emax)
+{
+  if(fSpec)
+    delete fSpec;
+  if(emin<=0 || emax<=0 || emax<emin)
+    {
+      emin = fEmin;
+      emax = fEmax;
+    }
+  else
+    {
+      fEmin = emin;
+      fEmax = emax;
+    }
+  fSpec = new TF1("fspec",chfunc,emin,emax);
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the function by function pointer
+//
+void MEffAreaAndCoeffCalc::SetFunction(TF1* newf)
+{
+  if(fSpec)
+    delete fSpec;
+  fSpec = newf;
+}
+
+// -------------------------------------------------------------------------
+//
+// fill the histogram containing the original sample energy spectrum
+//
+void MEffAreaAndCoeffCalc::FillOriginalSpectrum()
+{  
+}
+
+// -------------------------------------------------------------------------
+//
+// compute the weights for a particular input spectrum
+//
+void MEffAreaAndCoeffCalc::ComputeWeights()
+{  
+  // OJO!! maybe this should be hard-coded somewhere else
+  const Float_t abslogmin=0.;
+  const Float_t abslogmax=5.;
+
+  const Float_t logemin = TMath::Log10(fEmin);
+  const Float_t logemax = TMath::Log10(fEmax);
+  const Float_t de    = (logemax-logemin)/fEbins; // bin size (in log)
+  const Float_t desub = de/fEsubbins; // subbin size (in log)
+  const Int_t esbins   = fEbins*fEsubbins; // total number of subbins
+
+  // compute the binning for weights histogram
+  const Int_t nmindist = (logemin>abslogmin)? Int_t((logemin-abslogmin)/desub) : 0;
+  const Int_t nmaxdist = (logemax<abslogmax)? Int_t((abslogmax-logemax)/desub) : 0;
+
+  fLogEWmin = logemin-desub*nmindist;
+  fLogEWmax = logemax+desub*nmaxdist;
+  fEWbins   = nmindist+esbins+nmaxdist;
+  
+  // reset the weights array
+  if(fWeight)
+    delete [] fWeight;
+  fWeight = new Double_t[fEWbins];
+    
+
+  TH1F* horigs = new TH1F("horigs","Original energy spectrum",fEWbins,fLogEWmin,fLogEWmax);
+  fCini->Draw("logenergy>>horigs","","goff");
+  // borra
+  //  horigs->Write();
+
+  // borra
+  //  TH1F hw("hw","hw",fEWbins,fLogEWmin,fLogEWmax);
+  for(Int_t i=0;i<fEWbins;i++)
+    {
+      const Float_t denom = horigs->GetBinContent(i+1);               // number of events in initial spectrum
+      const Float_t ew    = TMath::Power(10,fLogEWmin+(i+0.5)*desub); // real energy
+      const Float_t numer = fSpec->Eval(ew);                          // number of events for the required spectrum
+      if(denom>10)
+	fWeight[i]=numer/denom;
+      else
+	{
+	  //	  cout << "MEffAreaAndCoeffCalc::ComputeWeights Warning: no statistic to compute weight for energy " << ew << ", setting it to -1 "  << endl;
+	  fWeight[i]=-1;
+	}
+      // borra
+      //      hw.SetBinContent(i+1,fWeight[i]);
+    }
+  // borra
+  //  hw.Write();
+
+  delete horigs;
+}
+
+// --------------------------------------------------------------
+//
+// compute the coefficients used for the (iterative) unfolding 
+//
+void MEffAreaAndCoeffCalc::ComputeCoefficients()
+{ 
+  if(!fWeight)
+    {
+      cout << "MEffAreaAndCoeffCalc::ComputeCoefficients Warning: No weights computed! nothing done" << endl;
+      return;
+    }
+
+  const Float_t logemin = TMath::Log10(fEmin);
+  const Float_t logemax = TMath::Log10(fEmax);
+  const Float_t de = (logemax-logemin)/fEbins; // bin size (in log)
+  const Float_t desub = de/fEsubbins; // subbin size (in log)
+  const Int_t nentries = Int_t(fCcut->GetEntries());
+ 
+  // declare needed histos
+  TH2F* hest = new TH2F("hest","Estimated energy",fEbins,logemin,logemax,fNTbins,fTbin);
+  TH2F* hmc  = new TH2F("hmc","MC energy",fEbins,logemin,logemax,fNTbins,fTbin);
+
+  // borra
+  //  TH1F* hest1  = new TH1F("hest1","Estimated energy",fEbins,logemin,logemax);
+  //  TH1F* hmc1   = new TH1F("hmc1","MC energy",fEbins,logemin,logemax);
+  //  TH1F* coef1  = new TH1F("coef1","coefficients",fEbins,logemin,logemax);
+
+  // reset the coefficients
+  if(fCoeff)
+    delete fCoeff;
+  fCoeff = new TH2F("fcoeff","Coefficients for unfolding",fEbins,logemin,logemax,fNTbins,fTbin);
+
+  // fill the histograms of estimated and measured energy for weighted events
+  for(Int_t i=0;i<nentries;i++)
+    {
+      fCcut->GetEntry(i);  
+
+      // mc and estimated energy
+      // OJO!! Estimated energy will be taken directly from some input container
+      Float_t emc   = fMcEvt->GetEnergy();
+      Float_t estim = fHillas->GetSize()/0.18/15.;
+
+      if((emc<fEmin && estim<fEmin) || (emc>fEmax && estim>fEmax) ||
+	 (emc<fEmin && estim>fEmax) || (emc>fEmax && estim<fEmin))
+	continue;
+
+      Float_t theta = fMcEvt->GetTheta()*180./3.14159; // zenith angle (in degrees)
+
+      // compute the bin where the weight is taken from
+      Int_t wbin = Int_t((TMath::Log10(emc)-fLogEWmin)/desub);
+
+      // fill the histograms
+      if(wbin<fEWbins)
+	{
+	  if(fWeight[wbin]>0)
+	    {
+	      hest->Fill(TMath::Log10(estim),theta,fWeight[wbin]); 
+	      hmc->Fill(TMath::Log10(emc),theta,fWeight[wbin]);
+	      // borra
+// 	      if(theta<fTbin[1])
+// 		{
+// 		  hest1->Fill(TMath::Log10(estim),fWeight[wbin]); 
+// 		  hmc1->Fill(TMath::Log10(emc),fWeight[wbin]);
+// 		}
+	    }
+	  else
+	    cout << "MEffAreaAndCoeffCalc::ComputeCoefficients Warning: event " << i << " with energy " << emc << " has no computed weight (lack of MC statistics), skipping" << endl;
+	}
+      else
+      	cout << "MEffAreaAndCoeffCalc::ComputeCoefficients Warning: event " << i << " with energy " << emc << " has energy out of bounds, skipping" << endl;
+    }
+
+  // divide the previous histos to get the coefficients for unfolding
+  for(Int_t j=0;j<fNTbins;j++)
+    for(Int_t i=0;i<fEbins;i++)
+      {
+	const Float_t num = hmc->GetBinContent(i+1,j+1);
+	const Float_t den = hest->GetBinContent(i+1,j+1);
+	//borra
+// 	const Float_t num1 = hmc1->GetBinContent(i+1);
+// 	const Float_t den1 = hest1->GetBinContent(i+1);
+	if(den)
+	  {
+	    fCoeff->SetBinContent(i+1,j+1,num/den);
+	    //borra
+// 	    if(j==0 && den1)
+// 	      coef1->SetBinContent(i+1,num1/den1);
+	  }
+	else
+	  {
+	    cout << "MEffAreaAndCoeffCalc::ComputeCoefficients Warning: energy bin " << i << ", thetabin " << j << " has no survivors, setting coefficient to 0" << endl;
+	    fCoeff->SetBinContent(i+1,j+1,0.);
+	  }
+      }
+
+
+  //borra
+//   hmc1->Write();
+//   hest1->Write();
+//   coef1->Write();
+
+  delete hmc;
+  delete hest;
+}
+
+// --------------------------------------------------------------
+//
+// compute the coefficients used for the (iterative) unfolding 
+//
+void MEffAreaAndCoeffCalc::ComputeEffectiveAreas()
+{
+  if(!fWeight)
+    {
+      cout << "MEffAreaAndCoeffCalc::ComputeEffectiveAreas Warning: No weights computed! nothing done" << endl;
+      return;
+    }
+
+  //OJO!! radius should be read from somewhere!
+  const Float_t radius = 30000.; // generation radius (in cm)
+  const Float_t Atot = 3.14159*radius*radius; //total area (in cm^2)
+  const Float_t logemin = TMath::Log10(fEmin);
+  const Float_t logemax = TMath::Log10(fEmax);
+  const Int_t esbins = fEbins*fEsubbins; // total number of subbins
+  const Float_t de = (logemax-logemin)/fEbins; // bin size (in log)
+  const Float_t desub = de/fEsubbins; // subbin size (in log)
+
+  // reset the effective areas
+  if(fEffA)
+    delete fEffA;
+  fEffA = new TH2F("feffa","Effective area",fEbins,logemin,logemax,fNTbins,fTbin);
+  //borra
+//   TH1F eff("eff","Effective area",fEbins,logemin,logemax);
+  
+  // fill the spectrum of the survivors
+  TH2F* hpass= new TH2F("hpass","Survivors",esbins,logemin,logemax,fNTbins,fTbin);
+  TH2F* horig= new TH2F("horig","Original events",esbins,logemin,logemax,fNTbins,fTbin);
+
+  fCcut->Draw("theta:logenergy>>hpass","","goff");
+  fCini->Draw("theta:logenergy>>horig","","goff");
+  
+  // compute the effective areas
+  for(Int_t j=0;j<fNTbins;j++)
+    for(Int_t i=0;i<fEbins;i++)
+      {
+	Float_t effarea =0;
+	Float_t wtot = 0;
+	for(Int_t k=0;k<fEsubbins;k++)
+	  {
+	    Float_t numerator = hpass->GetBinContent(i*fEsubbins+k+1,j+1);
+	    Float_t denominator = horig->GetBinContent(i*fEsubbins+k+1,j+1);
+	    
+	    if(denominator<=0)
+	      cout << "MEffAreaAndCoeffCalc::ComputeEffectiveAreas Warning: energy subbin " << i*fEsubbins+k <<", theta bin " << j << " contains no events" << endl;
+	    else
+	      {
+		const Float_t ew = TMath::Power(10,logemin+(i*fEsubbins+k+0.5)*desub);
+		const Float_t ww = fSpec->Eval(ew);
+		effarea+=Atot*numerator/denominator*ww;
+		wtot   += ww;
+	      }
+	  }
+	if(!wtot)
+	  {
+	    cout << "MEffAreaAndCoeffCalc::ComputeEffectiveAreas Warning: energy bin " << i <<", theta bin " << j << " contains no events setting effective area to 0" << endl;
+	    fEffA->SetBinContent(i+1,j+1,0);
+	  }	    
+	else
+	  {
+	    fEffA->SetBinContent(i+1,j+1,effarea/wtot);	
+	    // borra
+// 	    if(j==0)
+// 	      {
+// 		//		cout << "*****" << i << ": " << effarea/wtot << endl;
+// 		eff.SetBinContent(i+1,effarea/wtot);
+// 	      }
+	  }
+      }
+
+  // borra
+//   eff.Write();
+  
+  delete hpass;
+  delete horig;
+}
+
+// --------------------------------------------------------------
+//
+// Call the internal functions to compute all the factors
+//
+void MEffAreaAndCoeffCalc::ComputeAllFactors()
+{
+  ComputeWeights();
+  ComputeCoefficients();
+  ComputeEffectiveAreas();
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MEffAreaAndCoeffCalc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MEffAreaAndCoeffCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MEffAreaAndCoeffCalc.h	(revision 9772)
@@ -0,0 +1,79 @@
+#ifndef MARS_MEffAreaAndCoeffCalc
+#define MARS_MEffAreaAndCoeffCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TF1;
+class TH1F;
+class TH2F;
+class MHillas;
+class MMcEvt;
+
+#include "TChain.h"
+
+class MEffAreaAndCoeffCalc
+{
+ private:
+
+  TF1* fSpec;        // function used to parametrize the spectrum
+
+  Float_t fEmin;    // Minimum energy in GeV
+  Float_t fEmax;    // Maximum energy in GeV
+  Int_t fEbins;      // number of bins to build spectrum
+  Int_t fEsubbins;   // number of subbins per big bin (to compute weights, eff areas...)
+
+  Float_t fLogEWmin; // Log Minimum energy for weights (in GeV)
+  Float_t fLogEWmax; // Log Maximum energy for weights (in GeV)
+  Int_t    fEWbins;   // Number of bins for weights
+
+  Int_t fNTbins;      // Number of bins in zenith angle
+  Double_t* fTbin;     // array containing bin boundaries (size must be fNTbins+)
+
+  Double_t* fWeight; // array containing weights
+  TH2F* fCoeff;      // histogram containing unfolding coefficients
+  TH2F* fEffA;       // histogram containing effective areas
+
+  TChain* fCini;     // chain for initial MC files (before trigger)
+  TChain* fCcut;     // chain for surviving MC events (after cuts)
+
+  MHillas* fHillas;  // pointer to the MHillas Branch
+  MMcEvt*  fMcEvt;   // pointer to the MMcEvt Branch
+
+  //  TFile* fFile; // output file (for debugging only)
+
+ protected:
+
+  void FillOriginalSpectrum();
+  void ComputeCoefficients();
+  void ComputeWeights();
+  void ComputeEffectiveAreas();
+
+ public:
+
+  MEffAreaAndCoeffCalc();
+
+  virtual ~MEffAreaAndCoeffCalc();
+
+  void SetFunction(const Char_t* chfunc, Float_t emin=0., Float_t emax=0.);
+  void SetFunction(TF1*);
+  void SetEbins(Int_t i)    {fEbins=i;}
+  void SetEsubbins(Int_t i) {fEsubbins=i;}
+  void SetEmin(Float_t x)   {fEmin=x;}
+  void SetEmax(Float_t x)   {fEmax=x;}
+
+  void SetThetaBinning(Int_t n, const Double_t* binlist);
+
+  void AddFile(const Char_t* name) {fCini->Add(name); fCcut->Add(name);}
+
+  TH2F* GetEffectiveAreaHisto() {return fEffA;}
+  TH2F* GetCoefficientHisto()   {return fCoeff;}
+
+  void ComputeAllFactors();
+
+  ClassDef(MEffAreaAndCoeffCalc, 0) // task to compute the Effective areas and Coefficients for the unfolding 
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MFDisp.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MFDisp.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MFDisp.cc	(revision 9772)
@@ -0,0 +1,299 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Eva Domingo,     12/2004 <mailto:domingo@ifae.es> 
+!              Wolfgang Wittek, 12/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MFDisp                                                                  //
+//                                                                          //
+//  This is a class to set cuts to select an event sample                   //
+//  for the Disp optimization                                               //
+//                                                                          //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MFDisp.h"
+
+#include "MGeomCam.h"
+#include "MHillas.h"
+#include "MHillasSrc.h"
+#include "MImagePar.h"
+#include "MNewImagePar.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MFDisp);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFDisp::MFDisp(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFDisp";
+    fTitle = title ? title : "Cuts for Disp optimization";
+
+    // default values of cuts
+    SetCuts(0, 1000,   0, 1000,   0, 1000, 
+            0.0, 1.e10,  0.0, 1.0,  0.0, 1.0,   0.0, 0.0);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the values for the cuts 
+// 
+void MFDisp::SetCuts(Int_t islandsmin,      Int_t islandsmax,
+                     Int_t usedpixelsmin,   Int_t usedpixelsmax, 
+                     Int_t corepixelsmin,   Int_t corepixelsmax,
+                     Float_t sizemin,       Float_t sizemax,
+                     Float_t leakage1min,   Float_t leakage1max,
+                     Float_t leakage2min,   Float_t leakage2max,
+                     Float_t lengthmin,     Float_t widthmin)
+{ 
+  fIslandsMin    = islandsmin;
+  fIslandsMax    = islandsmax;
+
+  fUsedPixelsMin = usedpixelsmin;
+  fUsedPixelsMax = usedpixelsmax;
+
+  fCorePixelsMin = corepixelsmin;
+  fCorePixelsMax = corepixelsmax;
+
+  fSizeMin       = sizemin;
+  fSizeMax       = sizemax;
+
+  fLeakage1Min   = leakage1min;
+  fLeakage1Max   = leakage1max;
+
+  fLeakage2Min   = leakage2min;
+  fLeakage2Max   = leakage2max;
+
+  fLengthMin     = lengthmin;
+  fWidthMin      = widthmin;
+}
+
+
+// --------------------------------------------------------------------------
+//
+Int_t MFDisp::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+
+    fHil = (MHillas*)pList->FindObject("MHillas");
+    if (!fHil)
+    {
+        *fLog << err << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject("MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << "MHillasSrc not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fImgPar = (MImagePar*)pList->FindObject("MImagePar");
+    if (!fImgPar)
+    {
+        *fLog << err << "MImagePar not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewImgPar = (MNewImagePar*)pList->FindObject("MNewImagePar");
+    if (!fNewImgPar)
+    {
+        *fLog << err << "MNewImagePar not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    memset(fCut, 0, sizeof(fCut));
+
+
+    //--------------------
+    *fLog << inf << "MFDisp cut values :" << endl; 
+
+    *fLog << inf << "     fIslandsMin, fIslandsMax = "
+          << fIslandsMin << ",  " << fIslandsMax << endl;
+
+    *fLog << inf << "     fUsedPixelsMin, fUsedPixelsMax = "
+          << fUsedPixelsMin << ",  " << fUsedPixelsMax << endl;
+
+    *fLog << inf << "     fCorePixelsMin, fCorePixelsMax = "
+          << fCorePixelsMin << ",  " << fCorePixelsMax << endl;
+
+    *fLog << inf << "     fSizeMin, fSizeMax = " 
+          << fSizeMin << ",  " << fSizeMax << endl;
+
+    *fLog << inf << "     fLeakage1Min, fLeakage1Max = " 
+          << fLeakage1Min << ",  " << fLeakage1Max << endl;
+
+    *fLog << inf << "     fLeakage2Min, fLeakage2Max = " 
+          << fLeakage2Min << ",  " << fLeakage2Max << endl;
+
+    *fLog << inf << "     fLengthMin, fWidthMin = " 
+          << fLengthMin << ",  " << fWidthMin << endl;
+    //--------------------
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Sum up the number of events passing each cut
+//
+Bool_t MFDisp::Set(Int_t rc)
+{
+    fResult = kTRUE;
+    fCut[rc]++;
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Evaluate cuts for Disp optimization
+// if selections are fulfilled set fResult = kTRUE;
+// 
+Int_t MFDisp::Process()
+{
+    const Double_t length     = fHil->GetLength() * fMm2Deg;
+    const Double_t width      = fHil->GetWidth()  * fMm2Deg;
+    //const Double_t dist       = fHilSrc->GetDist()* fMm2Deg;
+    //const Double_t delta      = fHil->GetDelta()  * kRad2Deg;
+    const Double_t size       = fHil->GetSize();
+
+    const Double_t leakage1   = fNewImgPar->GetLeakage1();
+    const Double_t leakage2   = fNewImgPar->GetLeakage2();
+
+    const Int_t numusedpixels = fNewImgPar->GetNumUsedPixels();
+    const Int_t numcorepixels = fNewImgPar->GetNumCorePixels();
+    const Int_t numislands    = fImgPar->GetNumIslands();
+
+    fResult = kFALSE;
+
+    if  (numislands<fIslandsMin  || numislands>fIslandsMax )
+        return Set(1);
+
+    if  (numusedpixels<fUsedPixelsMin  || numusedpixels>fUsedPixelsMax )
+        return Set(2);
+
+    if  (numcorepixels<fCorePixelsMin  || numcorepixels>fCorePixelsMax )
+        return Set(3);
+
+    if (size<fSizeMin  ||  size>fSizeMax)
+        return Set(4);
+
+    if (leakage1<fLeakage1Min || leakage1>fLeakage1Max)
+        return Set(5);
+
+    if (leakage2<fLeakage2Min || leakage2>fLeakage2Max)
+        return Set(6);
+
+    if (length<fLengthMin || width<fWidthMin)
+        return Set(7);
+
+    fCut[0]++;
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the cuts selections
+//
+Int_t MFDisp::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3);
+    *fLog << (int)(fCut[1]*100/GetNumExecutions()+0.5) ;
+    *fLog << "%) Evts skipped due to: No.of islands < " << fIslandsMin ;
+    *fLog << " or > " << fIslandsMax << endl;
+
+    *fLog << " " << setw(7) << fCut[2] << " (" << setw(3);
+    *fLog << (int)(fCut[2]*100/GetNumExecutions()+0.5) ;
+    *fLog << "%) Evts skipped due to: No.of used pixels < " << fUsedPixelsMin ;
+    *fLog << " or > " << fUsedPixelsMax << endl;
+
+    *fLog << " " << setw(7) << fCut[3] << " (" << setw(3);
+    *fLog << (int)(fCut[3]*100/GetNumExecutions()+0.5) ;
+    *fLog << "%) Evts skipped due to: No.of core pixels < " << fCorePixelsMin ;
+    *fLog << " or > " << fCorePixelsMax << endl;
+
+    *fLog << " " << setw(7) << fCut[4] << " (" << setw(3) ;
+    *fLog << (int)(fCut[4]*100/GetNumExecutions()+0.5) ;
+    *fLog << "%) Evts skipped due to: SIZE < " << fSizeMin;
+    *fLog << " or > " << fSizeMax << endl;
+
+    *fLog << " " << setw(7) << fCut[5] << " (" << setw(3) ;
+    *fLog << (int)(fCut[5]*100/GetNumExecutions()+0.5) ;
+    *fLog << "%) Evts skipped due to: Leakage1 < " << fLeakage1Min;
+    *fLog << " or > " << fLeakage1Max << endl;
+
+    *fLog << " " << setw(7) << fCut[6] << " (" << setw(3) ;
+    *fLog << (int)(fCut[6]*100/GetNumExecutions()+0.5) ;
+    *fLog << "%) Evts skipped due to: Leakage2 < " << fLeakage2Min;
+    *fLog << " or > " << fLeakage2Max << endl;
+
+    *fLog << " " << setw(7) << fCut[7] << " (" << setw(3) ;
+    *fLog << (int)(fCut[7]*100/GetNumExecutions()+0.5) ;
+    *fLog << "%) Evts skipped due to: LENGTH <= " << fLengthMin;
+    *fLog << " or WIDTH <= " << fWidthMin << endl;
+
+    *fLog << " " << fCut[0] << " (" ;
+    *fLog << (int)(fCut[0]*100/GetNumExecutions()+0.5) ;
+    *fLog << "%) Evts survived the Disp cuts!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MFDisp.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MFDisp.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MFDisp.h	(revision 9772)
@@ -0,0 +1,90 @@
+#ifndef MARS_MFDisp
+#define MARS_MFDisp
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MHillas;
+class MHillasSrc;
+class MImagePar;
+class MNewImagePar;
+
+class MFDisp : public MFilter
+{
+private:
+
+    MHillas      *fHil;
+    MHillasSrc   *fHilSrc;
+    MImagePar    *fImgPar;
+    MNewImagePar *fNewImgPar;
+
+    //--------------------------    
+
+    // cutting variables to select the sample
+    // for the Disp optimization
+
+    Int_t      fIslandsMin;
+    Int_t      fIslandsMax;
+
+    Int_t      fUsedPixelsMin;
+    Int_t      fUsedPixelsMax;
+
+    Int_t      fCorePixelsMin;
+    Int_t      fCorePixelsMax;
+
+    Float_t      fSizeMin;
+    Float_t      fSizeMax;
+
+    Float_t      fLeakage1Min;
+    Float_t      fLeakage1Max;
+
+    Float_t      fLeakage2Min;
+    Float_t      fLeakage2Max;
+
+    Float_t      fLengthMin;
+    Float_t      fWidthMin;
+
+    //--------------------------    
+
+    Double_t     fMm2Deg;     // conversion mm to degrees in camera
+
+    Int_t        fCut[8];     // array to save cuts statistics
+
+    Bool_t       fResult;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t IsExpressionTrue() const  { return fResult; }
+
+    Bool_t Set(Int_t rc);
+
+public:
+
+    MFDisp(const char *name=NULL, const char *title=NULL);
+
+    void SetCuts(Int_t islandsmin,      Int_t islandsmax,
+                 Int_t usedpixelsmin,   Int_t usedpixelsmax,
+                 Int_t corepixelsmin,   Int_t corepixelsmax,
+                 Float_t sizemin,       Float_t sizemax, 
+                 Float_t leakage1min,   Float_t leakage1max,
+                 Float_t leakage2min,   Float_t leakage2max,
+                 Float_t lengthmin,     Float_t widthmin);
+
+    ClassDef(MFDisp, 0)   // Class to set cuts for Disp optimization
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MFHVNotNominal.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MFHVNotNominal.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MFHVNotNominal.cc	(revision 9772)
@@ -0,0 +1,250 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 5/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MFHVNotNominal
+//
+//   Filter to look if the HV monitored value is in agreement with the
+//   expected nominal value. If this is not true it sets a flag in MBadPixelsCam
+//   to not use this pixel in the analysis.
+//   Moreover if more than a certain number of pixels (set by defauld to 230) is
+//   deviated from the nominal value the event is rejected.
+//
+//  Input Containers:
+//   MCameraHV
+//
+//  Output Containers:
+//   MBadPixelsCam
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MFHVNotNominal.h"
+
+#include <fstream>
+#include <stdlib.h>
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCameraHV.h"
+
+#include "MBadPixelsPix.h"
+#include "MBadPixelsCam.h"
+
+ClassImp(MFHVNotNominal);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MFHVNotNominal::MFHVNotNominal(const char *name, const char *title)
+  : fHV(NULL), fBadPixels(NULL), fHVConfFile("NULL"), fMaxHVDeviation(0.03), fMaxNumPixelsDeviated(230)
+{
+    fName  = name  ? name  : "MFHVNotNominal";
+    fTitle = title ? title : "Filter to reject events with too many pixels out of nominal HV";
+
+    fCut[0] = 0;
+    fCut[1] = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MCameraHV
+//
+// The following containers are searched and created if they were not found:
+//  - MBadPixelsCam
+//
+Int_t MFHVNotNominal::PreProcess(MParList *pList)
+{
+  // 
+  // Containers that have to be there.
+  //
+    fHV = (MCameraHV*)pList->FindObject("MCameraHV");
+    if (!fHV)
+    {
+      *fLog << err << "MCameraHV not found... aborting." << endl;
+      return kFALSE;
+    }
+
+    // 
+    // Containers that are created in case that they are not there.
+    //
+    fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+    if (!fBadPixels)
+      {
+	*fLog << err << "Cannot find nor create MBadPixelsCam... aborting" << endl;
+	return kFALSE;
+      }
+
+    if (fHVConfFile != "NULL")
+      {
+        
+	const UInt_t npix = 577;
+	fHVNominal.Set(npix);
+
+	// Here we get the nominal HV values directitly from a CC 
+	// HV configuration file.
+	// Those files have the following structure:
+	//  [HV]
+	//  pixel_'hwnumber'='hvvalue'
+    
+	ifstream fin(fHVConfFile);
+    
+	TString str;
+	
+	if(!fin)
+	  {
+	    *fLog << err << "Imposible to open CC HV configuration file " << fHVConfFile << endl;
+	    return kFALSE;
+	  }
+	else
+	    *fLog << dbg << "Opened CC HV configuration file " << fHVConfFile << endl;
+
+	
+	fin >> str;
+	if(str != "[HV]")
+	  {
+	    *fLog << err << fHVConfFile << " file is not a CC HV configuration file" << endl;
+	    return kFALSE;
+	  }
+        else
+	    *fLog << dbg << fHVConfFile << " file is a good CC HV configuration file" << endl;
+
+	UInt_t npixinfile=0;
+	while(1)
+	  {
+	    fin >> str;
+	    if (fin.eof())
+	      break;
+
+	    UInt_t equalpos = str.Index("=");
+	    UInt_t underpos = str.Index("_");
+	    UInt_t length   = str.Length();
+
+	    TString tmp = str(underpos+1,equalpos-(underpos+1));
+	    UInt_t   hwpix = atoi((const char*)tmp);
+	    tmp = str(equalpos+1,length-(equalpos+1));
+	    Double_t value = atof((const char*)tmp);
+				  
+	    fHVNominal[hwpix-1]=value;
+	    npixinfile++;
+	  }
+	
+	fin.close();
+
+	if (npixinfile!=npix)
+	  {
+	    *fLog << err << fHVConfFile << " CC HV configuration file contain " << npixinfile << " pixels while the camera have " << npix << " pixels." << endl;
+	    return kFALSE;
+	  }	    
+      }
+
+    return kTRUE;
+}
+
+
+// ---------------------------------------------------------
+//
+// HVNotNominal rejection: 
+// 
+// Requiring less than fMaxHVDeviation deviation of HV monitored values
+// from nominal ones.
+// 
+// fMaxNumPixelsDeviated is set to 230 by default which is slightly higher 
+// than the number of outer pixels in MAGIC (for the case that 
+// the outer pixels have some defect).
+//
+Bool_t MFHVNotNominal::HVNotNominalRejection()
+{
+  UInt_t npix = fHVNominal.GetSize();
+
+  UInt_t notnominalpix = 0;
+
+  for (UInt_t idx=1; idx<npix; idx++)
+    {
+      Double_t hv = (*fHV)[idx];
+      Double_t nominal = fHVNominal[idx];
+      Double_t dev = 2.*TMath::Abs(nominal-hv)/(nominal+hv);
+      
+      if (dev > fMaxHVDeviation)
+	{
+	  MBadPixelsPix &bad = (*fBadPixels)[idx];
+	  bad.SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+	  bad.SetHardware(MBadPixelsPix::kHVNotNominal);
+	  notnominalpix++;
+	}
+    }
+
+    if (notnominalpix!=0)
+      fCut[0]++;
+
+    //
+    // If the camera contains more than fMaxNumPixelsDeviated
+    // pixels with deviated HV, then the event is discarted.
+    //
+
+    return notnominalpix > fMaxNumPixelsDeviated;
+}
+
+// -----------------------------------------------------------
+//
+//  Compare the HV monitored valued with the HV nominal ones.
+//
+Int_t MFHVNotNominal::Process()
+{
+    fResult = HVNotNominalRejection();
+
+    if (fResult)
+      fCut[1]++;
+
+    return kTRUE;
+}
+
+Int_t MFHVNotNominal::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    *fLog << " " << setw(7) << fCut[0] << " (" << setw(3) ;
+    *fLog << (Int_t)(fCut[0]*100/GetNumExecutions()) ;
+    *fLog << "%) 'some not nominal pixel' events" << endl;
+
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (Int_t)(fCut[1]*100/GetNumExecutions()) ;
+    *fLog << "%) rejected events" ;
+    *fLog << " (with fMaxNumPixelsDeviated = " << fMaxNumPixelsDeviated << ")" << endl;
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MFHVNotNominal.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MFHVNotNominal.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MFHVNotNominal.h	(revision 9772)
@@ -0,0 +1,61 @@
+#ifndef MARS_MFHVNotNominal
+#define MARS_MFHVNotNominal
+
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MCameraHV;
+class MBadPixelsCam;
+
+class MFHVNotNominal : public MFilter
+{
+private:
+    MCameraHV      *fHV;          // HV monitored values of all pixels in the camera
+    MBadPixelsCam  *fBadPixels;   // Bad Pixels storage container
+
+    TString fHVConfFile;
+    TArrayD fHVNominal;
+    Bool_t  fResult;
+
+    Float_t fMaxHVDeviation;         // Maximum HV deviation from nominal values in %.
+    Float_t fMaxNumPixelsDeviated;   // Maximum number of pixels with HV deviated from nominal values.
+
+    UInt_t fCut[2];
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+    Int_t  PostProcess();
+
+    Bool_t HVNotNominalRejection();
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+  
+public:
+    MFHVNotNominal(const char *name=NULL, const char *title=NULL);
+
+    void    SetHVNominalValues(const TString hvconf)    { fHVConfFile = hvconf; }
+    void    SetHVNominalValues(const TArrayD hvnominal) { fHVNominal  = hvnominal; }
+
+    void    SetMaxHVDeviation(const Float_t d)       { fMaxHVDeviation = d; }
+    void    SetMaxNumPixelsDeviated(const Float_t n) { fMaxNumPixelsDeviated = n; }
+
+    Float_t GetfMaxHVDeviation() const          { return fMaxHVDeviation; }
+    Float_t GetfMaxNumPixelsDeviated() const    { return fMaxNumPixelsDeviated; }
+    TArrayD GetHVNominal() const { return fHVNominal; }
+    
+    ClassDef(MFHVNotNominal, 0)   // Filter to filter the events with HV out of nominal values 
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MFindDisp.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MFindDisp.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MFindDisp.cc	(revision 9772)
@@ -0,0 +1,1158 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Eva Domingo,     12/2004 <mailto:domingo@ifae.es>
+!              Wolfgang Wittek, 12/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFindDisp                                                               //
+//                                                                         //
+// Class for otimizing the estimation of Disp                              //
+//                                                                         //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MFindDisp.h"
+
+#include <math.h>            // fabs 
+
+#include <TArrayD.h>
+#include <TCanvas.h>
+#include <TFile.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TMinuit.h>
+#include <TStopwatch.h>
+#include <TVirtualFitter.h>
+
+#include "MBinning.h"
+#include "MContinue.h"
+#include "MDispParameters.h"
+#include "MDispCalc.h"
+#include "MDataElement.h"
+#include "MDataMember.h"
+
+#include "MEvtLoop.h"
+#include "MFSelFinal.h"
+#include "MF.h"
+#include "MFDisp.h"
+#include "MFEventSelector.h"
+#include "MFEventSelector2.h"
+#include "MFillH.h"
+#include "MFEventSelector.h"
+#include "MGeomCamMagic.h"
+#include "MH3.h"
+#include "MHDisp.h"
+#include "MHFindSignificance.h"
+#include "MHMatrix.h"
+#include "MHOnSubtraction.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMatrixLoop.h"
+#include "MMinuitInterface.h"
+#include "MParameters.h"
+#include "MParList.h"
+#include "MProgressBar.h"
+#include "MReadMarsFile.h"
+#include "MReadTree.h"
+#include "MStatusDisplay.h"
+#include "MTaskList.h"
+
+
+ClassImp(MFindDisp);
+
+using namespace std;
+
+
+//------------------------------------------------------------------------
+// fcnDisp 
+//------------------------------------------------------------------------
+//
+// - calculates the quantity to be minimized (by TMinuit)
+//
+// - the quantity to be minimized is defined in 
+//   MHDisp::Fill() and MHDisp::Finalize()
+//
+// - the parameters to be varied in the minimization are the parameters
+//   appearing in the parametrization of Disp (MDispCalc::Calc())
+//
+//------------------------------------------------------------------------
+
+static void fcnDisp(Int_t &npar, Double_t *gin, Double_t &f, 
+                    Double_t *par, Int_t iflag)
+{
+    cout <<  "entry fcnDisp" << endl;
+
+    // save pointer to the MINUIT object (for optimizing Disp) for the case
+    // that it is overwritten by the pointer to another Minuit object
+    //    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+
+    MEvtLoop *evtloopfcn = (MEvtLoop*)gMinuit->GetObjectFit();
+
+    MParList *plistfcn   = (MParList*)evtloopfcn->GetParList();
+    MTaskList *tasklistfcn   = (MTaskList*)plistfcn->FindObject("MTaskList");
+
+    // get needed Disp containers from the existing parList
+    MDispParameters *dispparams = (MDispParameters*)plistfcn->FindObject("MDispParameters");
+    if (!dispparams)
+    {
+        gLog << "fcnDisp : MDispParameters object '" << "MDispParameters"
+            << "' not found... aborting" << endl;
+        return;
+    }
+
+    MHDisp *hdisp = (MHDisp*)plistfcn->FindObject("MHDisp");
+    if (!hdisp)
+    {
+        gLog << "fcnDisp : MHDisp object '" << "MHDisp"
+            << "' not found... aborting" << endl;
+        return;
+    }
+
+    MParameterD *minpar = (MParameterD*)plistfcn->FindObject("MinimizationParameter");
+
+    //
+    // transfer current parameter values to MDispParameters
+    //
+    // Attention : npar is the number of variable parameters
+    //                  not the total number of parameters
+    //
+    Double_t fMin,   fEdm,   fErrdef;
+    Int_t    fNpari, fNparx, fIstat;
+    gMinuit->mnstat(fMin, fEdm, fErrdef, fNpari, fNparx, fIstat);
+
+    dispparams->SetParameters(TArrayD(fNparx, par));
+
+    // checking that parameters have been properly set
+    TArrayD checkparameters = dispparams->GetParameters();
+    gLog << "fcnDisp : fNpari, fNparx =" << fNpari << ",  " 
+         << fNparx  << endl;
+    gLog << "fcnDisp : i, par, checkparameters =" << endl;
+    for (Int_t i=0; i<fNparx; i++)
+    {
+      gLog << i << ",  " << par[i] << ",  " << checkparameters[i] << endl;
+    }
+
+    //
+    // loop over the events in the training matrices to compute the parameter 
+    // to minimize for the current Disp parameter values
+    evtloopfcn->Eventloop();
+
+    tasklistfcn->PrintStatistics(0, kTRUE);
+
+    //-------------------------------------------
+    // get the Minimization parameter value for the current values 
+    // of the Disp parameters
+    if (minpar)
+      f = minpar->GetVal();
+    else
+    {
+      gLog << "fcnDisp : MParameterD object '" << "MinimizationParameter"
+	   << "' not found... aborting" << endl;
+      return;
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFindDisp::MFindDisp(MFDisp *fdisp, const char *name, const char *title)
+  : fHowManyTrain(10000), fHowManyTest(10000)
+{
+    fName  = name  ? name  : "MFindDisp";
+    fTitle = title ? title : "Optimizer of Disp";
+
+    //---------------------------
+    // camera geometry is needed for conversion mm ==> degree
+    fCam = new MGeomCamMagic; 
+
+    // initialize MFDisp filter cuts to default (no cutting) values
+    // (done at MFDisp constructor)
+    fDispFilter = fdisp;
+
+    // matrices to contain the training/test samples
+    fMatrixTrainCalc  = new MHMatrix("MatrixTrainCalc");
+    fMatrixTrainHists = new MHMatrix("MatrixTrainHists");
+    fMatrixTestCalc   = new MHMatrix("MatrixTestCalc");
+    fMatrixTestHists  = new MHMatrix("MatrixTestHists");
+
+    // objects of MDispCalc where the first part of the matrices mapping is defined
+    fDispCalcTrain = new MDispCalc("DispTrain","MDispParameters");
+    fDispCalcTest  = new MDispCalc("DispTest","MDispParametersTest");
+
+    // objects of MHDisp where the second part of the matrices mapping is defined
+    fHDispTrain = new MHDisp("DispTrain");
+    fHDispTest  = new MHDisp("DispTest");
+
+    // define columns of matrices
+    // Train matrix
+    fDispCalcTrain->InitMapping(fMatrixTrainCalc);
+    fHDispTrain->InitMapping(fMatrixTrainHists);
+    // Test matrix
+    fDispCalcTest->InitMapping(fMatrixTestCalc);
+    fHDispTest->InitMapping(fMatrixTestHists);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MFindDisp::~MFindDisp()
+{
+    delete fCam;
+    delete fMatrixTrainCalc;
+    delete fMatrixTrainHists;
+    delete fMatrixTestCalc;
+    delete fMatrixTestHists;
+    delete fDispCalcTrain;
+    delete fDispCalcTest;
+    delete fHDispTrain;
+    delete fHDispTest;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices 'fMatrixTrainCalc' and 'fMatrixTrainHists' 
+// for the TRAINING sample
+//
+// alltogether 'howmanytrain' events are read from file 'nametrain';
+// the events are selected according to a target distribution 'hreftrain'
+//
+//
+Bool_t MFindDisp::DefineTrainMatrix(
+			  const TString &nametrain, MH3 &hreftrain, 
+			  const Int_t howmanytrain, const TString &filetrain, 
+			  Int_t iflag)
+{
+    if (nametrain.IsNull() || howmanytrain <= 0)
+        return kFALSE;
+
+    *fLog   << "=============================================" << endl;
+    *fLog   << "Fill TRAINING Matrices from file '" << nametrain << endl;
+    *fLog   << "     select " << howmanytrain << " events " << endl;
+    if (!hreftrain.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftrain.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+    *fLog   << "=============================================" << endl;
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    // initialize display to check the reference distribution
+    // for the event selection (just if iflag==1)
+    MStatusDisplay *display = NULL;
+    if (iflag)
+      display = new MStatusDisplay;
+
+    MReadMarsFile read("Events", nametrain);
+    read.DisableAutoScheme();
+
+    // apply cuts for event selection
+    MContinue contdisp(fDispFilter);
+    contdisp.SetName("ContFilterSelector2");
+
+    // choose a reference distribution
+    MFEventSelector2 seltrain(hreftrain);
+    seltrain.SetNumMax(howmanytrain);
+    seltrain.SetName("selectTrain");
+
+    MFillH filltraincalc(fMatrixTrainCalc);
+    filltraincalc.SetFilter(&seltrain);
+    filltraincalc.SetName("fillMatrixTrainCalc");
+
+    MFillH filltrainhists(fMatrixTrainHists);
+    filltrainhists.SetFilter(&seltrain);
+    filltrainhists.SetName("fillMatrixTrainHists");
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrainCalc);
+    plist.AddToList(fMatrixTrainHists);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    if (fDispFilter != NULL)
+      tlist.AddToList(&contdisp);
+    tlist.AddToList(&seltrain);
+    tlist.AddToList(&filltraincalc);
+    tlist.AddToList(&filltrainhists);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    if (display != NULL)
+      evtloop.SetDisplay(display);
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrain");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+
+    // print the filled Training Matrices
+    fMatrixTrainCalc->Print("SizeCols");
+    fMatrixTrainHists->Print("SizeCols");
+
+    // check that number of generated events is compatible with the resquested
+    Int_t howmanygeneratedcalc = fMatrixTrainCalc->GetM().GetNrows();
+    if (TMath::Abs(howmanygeneratedcalc-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MFindDisp::DefineTrainMatrix; no.of generated events ("
+	    << howmanygeneratedcalc 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    Int_t howmanygeneratedhists = fMatrixTrainHists->GetM().GetNrows();
+    if (TMath::Abs(howmanygeneratedhists-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MFindDisp::DefineTrainMatrix; no.of generated events ("
+	    << howmanygeneratedhists 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+
+    *fLog << "TRAINING Matrices were filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+    //--------------------------
+    // write out training matrices
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrainCalc->Write();
+      fMatrixTrainHists->Write();
+      filetr.Close();
+
+      *fLog << "MFindDisp::DefineTrainMatrix; Training matrices were written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+
+    if (display != NULL)
+      delete display;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices 'fMatrixTestCalc' and 'fMatrixTestHists' 
+// for the TEST sample
+//
+// alltogether 'howmanytest' events are read from file 'nametest'
+// the events are selected according to a target distribution 'hreftest'
+//
+//
+Bool_t MFindDisp::DefineTestMatrix(
+			  const TString &nametest, MH3 &hreftest,
+	                  const Int_t howmanytest, const TString &filetest,
+			  Int_t iflag)
+{
+    if (nametest.IsNull() || howmanytest<=0)
+        return kFALSE;
+
+    *fLog   << "=============================================" << endl;
+    *fLog   << "Fill TEST Matrices from file '" << nametest << endl;
+    *fLog   << "     select " << howmanytest << " events " << endl;
+    if (!hreftest.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftest.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    // initialize display to check the reference distribution
+    // for the event selection (just if iflag==1)
+    MStatusDisplay *display = NULL;
+    if (iflag)
+      display = new MStatusDisplay;
+
+    MReadMarsFile read("Events", nametest);
+    read.DisableAutoScheme();
+
+    // apply cuts for event selection
+    MContinue contdisp(fDispFilter);
+    contdisp.SetName("ContFilterSelector2");
+ 
+    // choose a reference distribution 
+    MFEventSelector2 seltest(hreftest);
+    seltest.SetNumMax(howmanytest);
+    seltest.SetName("selectTest");
+ 
+    MFillH filltestcalc(fMatrixTestCalc);
+    filltestcalc.SetFilter(&seltest);
+    filltestcalc.SetName("fillMatrixTestCalc");
+
+    MFillH filltesthists(fMatrixTestHists);
+    filltesthists.SetFilter(&seltest);
+    filltesthists.SetName("fillMatrixTestHists");
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTestCalc);
+    plist.AddToList(fMatrixTestHists);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    if (fDispFilter != NULL)
+      tlist.AddToList(&contdisp);
+    tlist.AddToList(&seltest);
+    tlist.AddToList(&filltestcalc);
+    tlist.AddToList(&filltesthists);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    if (display != NULL)
+      evtloop.SetDisplay(display);
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTest");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+
+    // print the filled Test Matrices
+    fMatrixTestCalc->Print("SizeCols");
+    fMatrixTestHists->Print("SizeCols");
+
+    // check that number of generated events is compatible with the resquested
+    const Int_t howmanygeneratedcalc = fMatrixTestCalc->GetM().GetNrows();
+    if (TMath::Abs(howmanygeneratedcalc-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MFindDisp::DefineTestMatrix; no.of generated events ("
+	    << howmanygeneratedcalc
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+    const Int_t howmanygeneratedhists = fMatrixTestHists->GetM().GetNrows();
+    if (TMath::Abs(howmanygeneratedhists-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MFindDisp::DefineTestMatrix; no.of generated events ("
+	    << howmanygeneratedhists
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+    *fLog << "TEST Matrices were filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+    //--------------------------
+    // write out test matrices
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE");
+      fMatrixTestCalc->Write();
+      fMatrixTestHists->Write();
+      filete.Close();
+
+      *fLog << "MFindDisp::DefineTestMatrix; Test matrices were written onto file '"
+            << filetest << "'" << endl;
+    }
+
+
+    if (display != NULL)
+      delete display;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices for the TRAINING and TEST sample respectively
+//
+//   - this is for the case that training and test samples are generated
+//     from the same input file (which has the name 'name')
+//
+Bool_t MFindDisp::DefineTrainTestMatrix(
+			  const TString &name, MH3 &href,
+	                  const Int_t howmanytrain, const Int_t howmanytest,
+                          const TString &filetrain, const TString &filetest,
+			  Int_t iflag)
+{
+    *fLog   << "=============================================" << endl;
+    *fLog   << "Fill TRAINING and TEST Matrices from file '" << name << endl;
+    *fLog   << "     select "   << howmanytrain 
+	    << " training and " << howmanytest << " test events " << endl;
+    if (!href.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << href.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    // initialize display to check the reference distribution
+    // for the event selection (just if iflag==1)
+    MStatusDisplay *display = NULL;
+    if (iflag)
+      display = new MStatusDisplay;
+
+    MReadMarsFile read("Events", name);
+    read.DisableAutoScheme();
+
+    // apply cuts for event selection
+    MContinue contdisp(fDispFilter);
+    contdisp.SetName("ContFilterSelector2");
+
+    // choose a reference distribution 
+    MFEventSelector2 selector(href);
+    selector.SetNumMax(howmanytrain+howmanytest);
+    selector.SetName("selectTrainTest");
+    selector.SetInverted();
+    MContinue cont(&selector);
+    cont.SetName("ContTrainTest");
+
+    // choose randomly the events to fill the Training Matrix
+    Double_t prob =  ( (Double_t) howmanytrain )
+                   / ( (Double_t)(howmanytrain+howmanytest) );
+    MFEventSelector split;
+    split.SetSelectionRatio(prob);
+
+    MFillH filltraincalc(fMatrixTrainCalc);
+    filltraincalc.SetFilter(&split);
+    filltraincalc.SetName("fillMatrixTrainCalc");
+
+    MFillH filltrainhists(fMatrixTrainHists);
+    filltrainhists.SetFilter(&split);
+    filltrainhists.SetName("fillMatrixTrainHists");
+
+    // consider this event as candidate for a test event 
+    // only if event was not accepted as a training event
+    MContinue conttrain(&split);
+    conttrain.SetName("ContTrain");
+
+    MFillH filltestcalc(fMatrixTestCalc);
+    filltestcalc.SetName("fillMatrixTestCalc");
+
+    MFillH filltesthists(fMatrixTestHists);
+    filltesthists.SetName("fillMatrixTestHists");
+
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrainCalc);
+    plist.AddToList(fMatrixTrainHists);
+    plist.AddToList(fMatrixTestCalc);
+    plist.AddToList(fMatrixTestHists);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    if (fDispFilter != NULL)
+      tlist.AddToList(&contdisp);
+    tlist.AddToList(&cont);
+    tlist.AddToList(&filltraincalc);
+    tlist.AddToList(&filltrainhists);
+    tlist.AddToList(&conttrain);
+    tlist.AddToList(&filltestcalc);
+    tlist.AddToList(&filltesthists);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    if (display != NULL)
+      evtloop.SetDisplay(display);
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrainTest");
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxev = -1;
+    if (!evtloop.Eventloop(maxev))
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+
+    // print the filled Train Matrices
+    fMatrixTrainCalc->Print("SizeCols");
+    fMatrixTrainHists->Print("SizeCols");
+
+    // check that number of generated events is compatible with the resquested
+    const Int_t generatedtraincalc = fMatrixTrainCalc->GetM().GetNrows();
+    if (TMath::Abs(generatedtraincalc-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MFindDisp::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtraincalc
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+    const Int_t generatedtrainhists = fMatrixTrainHists->GetM().GetNrows();
+    if (TMath::Abs(generatedtrainhists-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MFindDisp::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtrainhists
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+
+    // print the filled Test Matrices
+    fMatrixTestCalc->Print("SizeCols");
+    fMatrixTestHists->Print("SizeCols");
+
+    // check that number of generated events is compatible with the resquested
+    const Int_t generatedtestcalc = fMatrixTestCalc->GetM().GetNrows();
+    if (TMath::Abs(generatedtestcalc-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MFindDisp::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtestcalc
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+    const Int_t generatedtesthists = fMatrixTestHists->GetM().GetNrows();
+    if (TMath::Abs(generatedtesthists-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MFindDisp::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtesthists
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+
+    *fLog << "TRAINING and TEST Matrices were filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+    //----------------------------
+    // write out training matrices
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrainCalc->Write();
+      fMatrixTrainHists->Write();
+      filetr.Close();
+
+      *fLog << "MFindDisp::DefineTrainTestMatrix; Training matrices were written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+    //--------------------------
+    // write out test matrices
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE");
+      fMatrixTestCalc->Write();
+      fMatrixTestHists->Write();
+      filete.Close();
+
+      *fLog << "MFindDisp::DefineTrainTestMatrix; Test matrices were written onto file '"
+            << filetest << "'" << endl;
+    }
+
+    if (display != NULL)
+      delete display;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Read training and test matrices from files
+//
+//
+Bool_t MFindDisp::ReadMatrix(const TString &filetrain, const TString &filetest)
+{
+  //--------------------------
+  // read in training matrices
+
+  TFile filetr(filetrain);
+  fMatrixTrainCalc->Read("MatrixTrainCalc");
+  fMatrixTrainHists->Read("MatrixTrainHists");
+  fMatrixTrainCalc->Print("SizeCols");
+  fMatrixTrainHists->Print("SizeCols");
+
+  *fLog << "MFindDisp::ReadMatrix; Training matrices were read in from file '"
+        << filetrain << "'" << endl;
+  filetr.Close();
+
+
+  //--------------------------
+  // read in test matrices
+
+  TFile filete(filetest);
+  fMatrixTestCalc->Read("MatrixTestCalc");
+  fMatrixTestHists->Read("MatrixTestHists");
+  fMatrixTestCalc->Print("SizeCols");
+  fMatrixTestHists->Print("SizeCols");
+
+  *fLog << "MFindDisp::ReadMatrix; Test matrices were read in from file '"
+        << filetest << "'" << endl;
+  filete.Close();
+
+  return kTRUE;  
+}
+
+
+//------------------------------------------------------------------------
+//
+// Steering program for optimizing Disp
+// ------------------------------------
+//
+//      the criterion for the 'optimum' is defined in 
+//      MHDisp::Fill()  and  MHDisp::Finalize(); 
+//      for example : smallest sum (over all events) of d^2, where d is the 
+//                    distance between the estimated source position 
+//                    (calculated using the current value of Disp) and
+//                    the true source position     
+//
+// The various steps are :
+//
+// - setup the event loop to be executed for each call to fcnDisp 
+//
+// - call TMinuit to do the minimization :
+//        the fcnDisp function calculates the parameter to minimize 
+//                            for the current Disp parameter values;
+//        for this - Disp is calculated in the event loop by calling 
+//                   MDispCalc::Process() ==> MDispCalc::Calc() 
+//                 - the Minimization parameter contributions are summed up 
+//                   in the event loop by calling MHDisp::Fill()
+//                 - after the event loop the final value of the Minimization
+//                   parameter is calculated by calling MHDisp::Finalize()
+//
+// Needed as input : (to be set by the Set functions)
+//
+// - fFilenameParam      name of file to which optimum values of the 
+//                       parameters are written
+//
+// - for the minimization, the starting values of the parameters are taken  
+//     - from the file parDispInit (if it is != "")
+//     - or from the arrays params and/or steps 
+//     - or from the DispParameters constructor
+//
+//----------------------------------------------------------------------
+Bool_t MFindDisp::FindParams(TString parDispInit,
+                             TArrayD &params, TArrayD &steps)
+{
+    // Setup the event loop which will be executed in the 
+    //                 fcnDisp function  of MINUIT
+    //
+    // parDispInit is the name of the file containing the initial values 
+    // of the parameters; 
+    // if parDispInit = ""   'params' and 'steps' are taken as initial values
+    //
+
+    *fLog << "=============================================" << endl;
+    *fLog << "Setup event loop for fcnDisp" << endl;
+
+
+    if (fMatrixTrainCalc == NULL || fMatrixTrainHists == NULL)
+    {
+      *fLog << "MFindDisp::FindParams; training matrices are not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrainCalc->GetM().GetNrows() <= 0  ||  fMatrixTrainHists->GetM().GetNrows() <= 0)
+    {
+      *fLog << "MFindDisp::FindParams; training matrices have no entries"
+            << endl;
+      return kFALSE;
+    }
+
+    //---------------------------------------------------------
+    MParList  parlistfcn;
+    MTaskList tasklistfcn;
+
+    // loop over rows of matrix
+    MMatrixLoop loopcalc(fMatrixTrainCalc);
+    MMatrixLoop loophists(fMatrixTrainHists);
+
+    //--------------------------------
+    // create container for the Disp parameters
+    // and set them to their initial values
+    MDispParameters *dispparams = fDispCalcTrain->GetDispParameters();
+
+    // take initial values from file parDispInit
+    if (parDispInit != "")
+    {
+      TFile inparam(parDispInit);
+      dispparams->Read("MDispParameters");
+      inparam.Close();
+      *fLog << "MFindDisp::FindParams; initial values of parameters are taken from file "
+            << parDispInit << endl;
+    }
+
+    // take initial values from 'params' and/or 'steps'
+    else if (params.GetSize() != 0  || steps.GetSize()  != 0 )
+    {
+      if (params.GetSize()  != 0)
+      {
+        *fLog << "MFindDisp::FindParams; initial values of parameters are taken from 'params'"
+              << endl;
+        dispparams->SetParameters(params);
+      }
+      if (steps.GetSize()  != 0)
+      {
+        *fLog << "MFindDisp::FindParams; initial step sizes are taken from 'steps'"
+              << endl;
+        dispparams->SetStepsizes(steps);
+      }
+    }
+    else
+    {
+        *fLog << "MFindDisp::FindParams; initial values and step sizes are taken "
+	      << "from the MDispParameters constructor" << endl;
+    }
+
+    // fill the plots for Disp and sum up the Minimization parameter contributions
+    MFillH filldispplots("MHDisp", "");
+
+    //******************************
+    // entries in MParList
+    
+    parlistfcn.AddToList(&tasklistfcn);
+    parlistfcn.AddToList(dispparams);
+    parlistfcn.AddToList(fHDispTrain);
+    parlistfcn.AddToList(fCam);
+    parlistfcn.AddToList(fMatrixTrainCalc);
+    parlistfcn.AddToList(fMatrixTrainHists);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklistfcn.AddToList(&loopcalc);
+    tasklistfcn.AddToList(&loophists);
+    tasklistfcn.AddToList(fDispCalcTrain);
+    tasklistfcn.AddToList(&filldispplots);
+
+    //******************************
+
+    MEvtLoop evtloopfcn("EvtLoopFCN");
+    evtloopfcn.SetParList(&parlistfcn);
+    *fLog << "Event loop for fcnDisp has been setup" << endl;
+
+    // address of evtloopfcn is used in CallMinuit()
+
+
+    //-----------------------------------------------------------------------
+    //
+    //----------   Start of minimization part   --------------------
+    //
+    // Do the minimization with MINUIT
+    //
+    // Be careful: This is not thread safe
+    //
+    *fLog << "========================================================" << endl;
+    *fLog << "Start minimization for Disp" << endl;
+
+
+    // -------------------------------------------
+    // prepare call to MINUIT
+    //
+
+    // get initial values of parameters 
+    fVinit = dispparams->GetParameters();
+    fStep  = dispparams->GetStepsizes();
+
+    TString name[fVinit.GetSize()];
+    fStep.Set(fVinit.GetSize());
+    fLimlo.Set(fVinit.GetSize());
+    fLimup.Set(fVinit.GetSize());
+    fFix.Set(fVinit.GetSize());
+
+    fNpar = fVinit.GetSize();
+
+    // define names, step sizes, lower and upper limits of the parameters
+    // fFix[] = 0;  means the parameter is not fixed
+    for (UInt_t i=0; i<fNpar; i++)
+    {
+        name[i]   = "p";
+        name[i]  += i+1;
+        //fStep[i]  = TMath::Abs(fVinit[i]/10.0);
+        fLimlo[i] = -100.0;
+        fLimup[i] =  100.0;
+        fFix[i]   =     0;
+    }
+
+    // fix some parameters
+    //for (UInt_t i=0; i<fNpar; i++)
+    //{
+    //  if (i == 1  ||  i==3)
+    //	{
+    //      fStep[i] = 0.0;
+    //      fFix[i]  =   1;
+    //	}
+    //}
+ 
+
+    // -------------------------------------------
+    // call MINUIT
+
+    TStopwatch clock;
+    clock.Start();
+
+    *fLog << "before calling CallMinuit" << endl;
+
+    MMinuitInterface inter;               
+    Bool_t rc = inter.CallMinuit(fcnDisp, name,
+                                 fVinit, fStep, fLimlo, fLimup, fFix,
+                                 &evtloopfcn, "MIGRAD", kFALSE);
+ 
+    *fLog << "after calling CallMinuit" << endl;
+
+    *fLog << "Time spent for the minimization in MINUIT :   " << endl;;
+    clock.Stop();
+    clock.Print();
+
+
+    if (!rc)
+        return kFALSE;
+
+    *fLog << "Minimization for Disp finished" << endl;
+    *fLog << "========================================================" << endl;
+
+
+    // -----------------------------------------------------------------
+    // in 'fcnDisp' the optimum parameter values were put into MDisp
+
+    // write optimum parameter values onto file fFilenameParam
+    
+    TFile outparam(fFilenameParam, "RECREATE"); 
+    dispparams->Write();
+    outparam.Close();
+
+    *fLog << "Optimum parameter values for Disp were written onto file '"
+              << fFilenameParam << "' :" << endl;
+
+    const TArrayD &check = dispparams->GetParameters();
+    for (Int_t i=0; i<check.GetSize(); i++)
+        *fLog << check[i] << ",  ";
+    *fLog << endl;
+
+
+
+    //-------------------------------------------
+    // draw the plots
+    fHDispTrain->Draw();
+
+    *fLog << "End of Disp optimization part" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
+
+// -----------------------------------------------------------------------
+//
+// Test the result of the Disp optimization on the test sample
+//
+
+Bool_t MFindDisp::TestParams()
+{
+    if (fMatrixTestCalc == NULL || fMatrixTestHists == NULL)
+    {
+      *fLog << "MFindDisp::TestParams; test matrices are not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTestCalc->GetM().GetNrows() <= 0  ||  fMatrixTestHists->GetM().GetNrows() <= 0)
+    {
+        *fLog << "MFindDisp::TestParams; test matrices have no entries" 
+              << endl;
+        return kFALSE;
+    }
+
+    // -------------   TEST the Disp optimization    -------------------
+    //
+    *fLog << "Test the Disp optimization on the test sample" << endl;
+
+    // -----------------------------------------------------------------
+    // read optimum parameter values from file fFilenameParam
+    // into array 'dispPar'
+
+    TFile inparam(fFilenameParam);
+    MDispParameters dispin; 
+    dispin.Read("MDispParameters");
+    inparam.Close();
+
+    *fLog << "Optimum parameter values for Disp were read from file '";
+    *fLog << fFilenameParam << "' :" << endl;
+
+    const TArrayD &dispPar = dispin.GetParameters();
+    for (Int_t i=0; i<dispPar.GetSize(); i++)
+        *fLog << dispPar[i] << ",  ";
+    *fLog << endl;
+    //---------------------------
+
+
+    // -----------------------------------------------------------------
+    MParList  parlist2;
+    MTaskList tasklist2;
+
+    MDispParameters *dispparams = fDispCalcTest->GetDispParameters();
+    dispparams->SetParameters(dispPar);
+
+    MMatrixLoop loopcalc(fMatrixTestCalc);
+    MMatrixLoop loophists(fMatrixTestHists);
+
+    MHMatrix *imatrix = NULL;
+    TArrayI  imap;
+    fHDispTest->GetMatrixMap(imatrix,imap);
+
+    // attention: argument of MHDisp is the name of MImageParDisp container, that should
+    // be the same than the name given to it when creating MDispCalc object at the MFindDisp
+    // constructor:  fDispCalcTrain = new MDispCalc("DispTest");
+    // fill the plots for Disp and sum up the Minimization parameter contributions
+    MHDisp hdisp1("DispTest");
+    hdisp1.SetName("MHDispCorr");
+    hdisp1.SetSelectedPos(1);
+    hdisp1.SetMatrixMap(imatrix,imap);
+    MFillH filldispplots1("MHDispCorr[MHDisp]", "");
+    
+    MHDisp hdisp2("DispTest");
+    hdisp2.SetName("MHDispWrong");
+    hdisp2.SetSelectedPos(2);
+    hdisp2.SetMatrixMap(imatrix,imap);
+    MFillH filldispplots2("MHDispWrong[MHDisp]", "");
+    
+    MHDisp hdisp3("DispTest");
+    hdisp3.SetName("MHDispM3Long");
+    hdisp3.SetSelectedPos(3);
+    hdisp3.SetMatrixMap(imatrix,imap);
+    MFillH filldispplots3("MHDispM3Long[MHDisp]", "");
+    
+    MHDisp hdisp4("DispTest");
+    hdisp4.SetName("MHDispAsym");
+    hdisp4.SetSelectedPos(4);
+    hdisp4.SetMatrixMap(imatrix,imap);
+    MFillH filldispplots4("MHDispAsym[MHDisp]", "");
+    
+
+    //******************************
+    // entries in MParList
+
+    parlist2.AddToList(&tasklist2);
+    parlist2.AddToList(dispparams);
+    parlist2.AddToList(&hdisp1);
+    parlist2.AddToList(&hdisp2);
+    parlist2.AddToList(&hdisp3);
+    parlist2.AddToList(&hdisp4);
+    parlist2.AddToList(fCam);
+    parlist2.AddToList(fMatrixTestCalc);
+    parlist2.AddToList(fMatrixTestHists);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklist2.AddToList(&loopcalc);
+    tasklist2.AddToList(&loophists);
+    tasklist2.AddToList(fDispCalcTest);
+    tasklist2.AddToList(&filldispplots1);
+    tasklist2.AddToList(&filldispplots2);
+    tasklist2.AddToList(&filldispplots3);
+    tasklist2.AddToList(&filldispplots4);
+
+    //******************************
+
+    MProgressBar bar2;
+    MEvtLoop evtloop2;
+    evtloop2.SetParList(&parlist2);
+    evtloop2.SetName("EvtLoopTestParams");
+    evtloop2.SetProgressBar(&bar2);
+    Int_t maxevents2 = -1;
+    if (!evtloop2.Eventloop(maxevents2))
+        return kFALSE;
+
+    tasklist2.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // draw the plots
+
+    hdisp1.Draw();
+    hdisp2.Draw();
+    hdisp3.Draw();
+    hdisp4.Draw();
+
+    //-------------------------------------------
+
+
+    *fLog << "Test of Disp otimization finished" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MFindDisp.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MFindDisp.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MFindDisp.h	(revision 9772)
@@ -0,0 +1,134 @@
+#ifndef MARS_MFindDisp
+#define MARS_MFindDisp
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MHMatrix;
+class MDispCalc;
+class MHDisp;
+class MFDisp;
+class MFilter;
+class MH3;
+class MGeomCam;
+class MEvtLoop;
+
+class MFindDisp : public MParContainer
+{
+private:
+
+  TString   fFilenameParam;  // filename to store optimum Disp parameters
+
+  TString   fFilenameTrain;
+  TString   fFilenameTest;
+
+  Int_t     fHowManyTrain;   // number of events for training
+  Int_t     fHowManyTest;    // number of events for testing
+
+  MHMatrix  *fMatrixTrainCalc;    // training matrix with variables needed in MDispCalc
+  MHMatrix  *fMatrixTrainHists;   // training matrix with variables needed in MHDisp
+  MHMatrix  *fMatrixTestCalc;     // testing matrix with variables needed in MDispCalc
+  MHMatrix  *fMatrixTestHists;    // testing matrix with variables needed in MHDisp
+
+  MDispCalc *fDispCalcTrain;
+  MDispCalc *fDispCalcTest;
+
+  MHDisp    *fHDispTrain;
+  MHDisp    *fHDispTest;
+
+  MFDisp    *fDispFilter;    // filter to select an events sample
+
+  MGeomCam  *fCam;
+
+  MEvtLoop  *fObjectFit;
+
+  //--------------------------------------------
+  // To comunicate with MINUIT
+  //--------------------------------------------
+  // attention : dimensions must agree with those in 
+  //             MMinuitInterface::CallMinuit()
+  //char  fParName [80][100];
+  TArrayD   fVinit;
+  TArrayD   fStep;
+  TArrayD   fLimlo;
+  TArrayD   fLimup;
+  TArrayI   fFix;
+
+  UInt_t    fNpar;
+
+  TString   fMethod;
+
+  Double_t  fMin,   fEdm,   fErrdef;
+  Int_t     fNpari, fNparx, fIstat;
+  Int_t     fErrMinimize;
+  //--------------------------------------------
+
+public:
+
+  MFindDisp(MFDisp *fdisp=NULL, const char *name=NULL, const char *title=NULL);
+  ~MFindDisp();
+
+  void SetFilenameParam(const TString &name)    {fFilenameParam  = name;}
+
+  void SetFilenameTraining(const TString &name, const Int_t howmany) 
+      {fFilenameTrain = name;  fHowManyTrain = howmany; }
+
+  void SetFilenameTest(const TString &name, const Int_t howmany)     
+      {fFilenameTest     = name;  fHowManyTest  = howmany; }
+
+  Bool_t DefineTrainMatrix(const TString &name, MH3 &href,
+                           const Int_t howmany, const TString &filetrain,
+			   Int_t iflag=0); 
+
+  Bool_t DefineTestMatrix(const TString &name, MH3 &href,
+                          const Int_t howmany, const TString &filetest,
+			  Int_t iflag=0); 
+
+  Bool_t DefineTrainTestMatrix(const TString &name, MH3 &href,
+			       const Int_t howmanytrain, const Int_t howmanytest, 
+			       const TString &filetrain, const TString &filetest,
+			       Int_t iflag=0); 
+
+  MHMatrix *GetMatrixTrainCalc()  { return fMatrixTrainCalc;  }
+  MHMatrix *GetMatrixTrainHists() { return fMatrixTrainHists; }
+  MHMatrix *GetMatrixTestCalc()   { return fMatrixTestCalc;   }
+  MHMatrix *GetMatrixTestHists()  { return fMatrixTestHists;  }
+
+  Bool_t ReadMatrix( const TString &filetrain, const TString &filetest);
+
+  Bool_t FindParams(TString parSCinit, TArrayD &params, TArrayD &steps);
+
+  Bool_t TestParams();
+
+  ClassDef(MFindDisp, 1) // Class for optimizing Disp
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationCam.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationCam.cc	(revision 9772)
@@ -0,0 +1,259 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 1/2005 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//            
+// MGainFluctuationCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MGainFluctuationCam.h"
+
+#include <math.h>
+#include <limits.h>
+#include <fstream>
+
+#include <TArrayD.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+ClassImp(MGainFluctuationCam);
+ClassImp(MGainFluctuationCamIter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MGainFluctuationPix object for each pixel in the event
+//
+MGainFluctuationCam::MGainFluctuationCam(const char *name, const char *title) : fNumPixels(0)
+{
+    fName  = name  ? name  : "MGainFluctuationCam";
+    fTitle = title ? title : "(Gain Fluctuation)-Event Information";
+
+    fPixels = new TClonesArray("MGainFluctuationPix", 0);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// reset counter and delete netries in list.
+//
+void MGainFluctuationCam::Reset()
+{
+    fNumPixels  =  0;
+    fMaxIndex   = -1;
+    fLut.Set(0);
+    // fPixels->Delete();
+}
+
+void MGainFluctuationCam::FixSize()
+{
+    fLut.Set(fMaxIndex+1);
+
+    if (fPixels->GetEntriesFast() == (Int_t)fNumPixels)
+        return;
+
+    fPixels->ExpandCreateFast(fNumPixels);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Dump the gain fluctuation event to *fLog
+//
+void MGainFluctuationCam::Print(Option_t *) const
+{
+    const Int_t entries = fPixels->GetEntries();
+
+    *fLog << GetDescriptor() << dec << endl;
+    *fLog << " Number of Pixels: " << fNumPixels << "(" << entries << ")" << endl;
+
+    for (Int_t i=0; i<entries; i++ )
+        (*this)[i].Print();
+}
+
+Float_t MGainFluctuationCam::GetGain(int i) const
+{
+  const MGainFluctuationPix &pix = (*this)[i];
+  
+  return pix.GetGain();
+}
+
+// --------------------------------------------------------------------------
+//
+// get the minimum number of photons  of all valid pixels in the list
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MGainFluctuationCam::GetGainMin(const MGeomCam *geom) const
+{
+    if (fNumPixels <= 0)
+        return -5.;
+
+    const UInt_t n = geom->GetNumPixels();
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGainFluctuationPix &pix = (*this)[i];
+
+        const UInt_t id = pix.GetPixId();
+        if (id<0 || id>=n)
+            continue;
+
+        Float_t testval = pix.GetGain();
+
+        if (testval < minval)
+            minval = testval;
+    }
+
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum number of photons of all valid pixels in the list
+// If you specify a geometry the number of photons is weighted with the
+// area of the pixel
+//
+Float_t MGainFluctuationCam::GetGainMax(const MGeomCam *geom) const
+{
+    if (fNumPixels <= 0)
+        return 50.;
+
+    const UInt_t n = geom->GetNumPixels();
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MGainFluctuationPix &pix = (*this)[i];
+
+        const UInt_t id = pix.GetPixId();
+        if (id<0 || id>=n)
+            continue;
+
+        Float_t testval = pix.GetGain();
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return a pointer to the pixel with the requested idx. NULL if it doesn't
+// exist. The Look-up-table fLut is used. If its size is zero (according
+// to Rene this will happen if an old class object is loaded) we still
+// try to search in the array.
+//
+MGainFluctuationPix *MGainFluctuationCam::GetPixById(Int_t idx) const
+{
+    if (idx<0)
+        return 0;
+
+    if (fLut.GetSize()>0)
+    {
+        if (idx>=fLut.GetSize())
+            return 0;
+        return fLut[idx]<0 ? 0 : (MGainFluctuationPix*)(fPixels->UncheckedAt(fLut[idx]));
+    }
+
+    TIter Next(fPixels);
+    MGainFluctuationPix *pix = NULL;
+
+    while ((pix=(MGainFluctuationPix*)Next()))
+        if (pix->GetPixId()==idx)
+            return pix;
+
+    return NULL;
+}
+
+MGainFluctuationPix *MGainFluctuationCam::AddPixel(Int_t idx, Float_t gain)
+    {
+        //
+        // If this is too slow or takes to much space we might use
+        // MGeomApply and an InitSize member function instead.
+        //
+        if (idx>=fLut.GetSize())
+        {
+            const Int_t n = fLut.GetSize();
+            fLut.Set(idx*2+1); //idx+1 is slower than idx*2+1
+            for (int i=n; i<idx*2+1; i++)
+                fLut[i] = -1;
+        }
+
+        fLut[idx] = fNumPixels;
+        if (idx>fMaxIndex)
+            fMaxIndex=idx;
+
+        return new ((*fPixels)[fNumPixels++]) MGainFluctuationPix(idx, gain);
+    }
+
+// --------------------------------------------------------------------------
+//
+// Returns, depending on the type flag:
+//
+//  0: Number of Photons*PixRatio
+//  1: Error*sqrt(PixRatio)
+//  2: Cleaning level = Num Photons*sqrt(PixRatio)/Error
+//  3: Number of Photons
+//  4: Error
+//  5: Island index
+//
+Bool_t MGainFluctuationCam::GetPixelContent(Double_t &val, Int_t idx,const MGeomCam&, Int_t type) const
+{
+    MGainFluctuationPix *pix = GetPixById(idx);
+
+    switch (type)
+    {
+    case 1:
+        val = pix->GetGain();
+        return kTRUE;
+    }
+    return kTRUE;
+}
+
+void MGainFluctuationCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MGainFluctuationCam::DrawPixelContent - not available." << endl;
+}
+
+TObject *MGainFluctuationCamIter::Next()
+{
+    if (!fUsedOnly)
+        return TObjArrayIter::Next();
+
+    MGainFluctuationPix *pix;
+    while ((pix = (MGainFluctuationPix*)TObjArrayIter::Next()))
+            return pix;
+    return pix;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationCam.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationCam.h	(revision 9772)
@@ -0,0 +1,104 @@
+#ifndef MARS_MGainFluctuationCam
+#define MARS_MGainFluctuationCam
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MGainFluctuationPix
+#include "MGainFluctuationPix.h"
+#endif
+
+class MGeomCam;
+class MGainFluctuationPix;
+class MGainFluctuationCamIter;
+
+class MGainFluctuationCam : public MParContainer, public MCamEvent
+{
+    friend class MGainFluctuationCamIter;
+private:
+    UInt_t        fNumPixels;
+     Int_t        fMaxIndex;
+    TArrayI       fLut;        // Lookup tabel to lookup pixel by index
+    TClonesArray *fPixels;     //-> FIXME: Change TClonesArray away from a pointer?
+
+    void RebuildLut()
+    {
+        // Resize Lut
+        fLut.Set(fMaxIndex+1);
+
+        // Reset Lut
+        fLut.Reset(-1);
+
+        // Rebuild Lut
+        for (UInt_t i=0; i<GetNumPixels(); i++)
+        {
+            const MGainFluctuationPix &pix = (*this)[i];
+            fLut[pix.GetPixId()] = i;
+        }
+    }
+
+public:
+    MGainFluctuationCam(const char *name=NULL, const char *title=NULL);
+    ~MGainFluctuationCam() { delete fPixels; }
+
+    // Setter function to fill pixels
+    MGainFluctuationPix *AddPixel(Int_t idx, Float_t gain);
+    void FixSize();
+
+    // Getter functions
+    UInt_t  GetNumPixels() const { return fNumPixels; }
+    Float_t GetGain(int i) const;
+
+    Float_t GetGainMin(const MGeomCam *geom=NULL) const;
+    Float_t GetGainMax(const MGeomCam *geom=NULL) const;
+
+    // Getter functions to access single pixels
+    MGainFluctuationPix &operator[](int i)       { return *(MGainFluctuationPix*)(fPixels->UncheckedAt(i)); }
+    MGainFluctuationPix &operator[](int i) const { return *(MGainFluctuationPix*)(fPixels->UncheckedAt(i)); }
+
+    MGainFluctuationPix *GetPixById(Int_t idx) const;
+
+    void Sort(Int_t upto = kMaxInt)
+    {
+        // Sort pixels by index
+        fPixels->Sort(upto);
+        RebuildLut();
+    } // For convinience: Sort pixels by index
+
+    // class MParContainer
+    void Reset();
+
+    // class TObject
+    void Print(Option_t *opt=NULL) const;
+    void Clear(Option_t *opt=NULL) { Reset(); }
+
+    // class MCamEvent
+    Bool_t GetPixelContent(Double_t &val, Int_t idx,const MGeomCam&, Int_t type=1) const;
+    void DrawPixelContent(Int_t num) const;
+
+    // To build an iterator for this class
+    operator TIterator*() const;
+
+    ClassDef(MGainFluctuationCam, 1)    // class for an event containing cerenkov photons
+};
+
+class MGainFluctuationCamIter : public TObjArrayIter
+{
+private:
+    Bool_t fUsedOnly;
+public:
+    MGainFluctuationCamIter(const MGainFluctuationCam *evt, Bool_t usedonly=kTRUE, Bool_t dir=kIterForward) : TObjArrayIter(evt->fPixels, dir), fUsedOnly(usedonly) { }
+    TObject *Next();
+    TIterator &operator=(const TIterator &) { return *this; }
+    ClassDef(MGainFluctuationCamIter, 0)
+};
+
+inline MGainFluctuationCam::operator TIterator*() const { return new MGainFluctuationCamIter(this); }
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationPix.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationPix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationPix.cc	(revision 9772)
@@ -0,0 +1,59 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch 1/2005 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MGainFluctuationPix
+//
+// Storage container for the gain fluctuation in a pixel in relative value.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MGainFluctuationPix.h"
+
+#include "MLog.h"
+
+ClassImp(MGainFluctuationPix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MGainFluctuationPix::MGainFluctuationPix(Int_t pix, Float_t gain):
+  fPixId(pix), fGain(gain)
+{
+} 
+
+
+// --------------------------------------------------------------------------
+//
+//  Print information to gLog.
+//
+void MGainFluctuationPix::Print(Option_t *) const
+{ 
+    gLog << GetDescriptor() <<" Pixel: "<< fPixId;
+    gLog << "Relative gain " << fGain << endl;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationPix.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationPix.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MGainFluctuationPix.h	(revision 9772)
@@ -0,0 +1,28 @@
+#ifndef MARS_MGainFluctuationPix_H
+#define MARS_MGainFluctuationPix_H
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGainFluctuationPix : public MParContainer
+{
+private:
+
+    Int_t    fPixId;     // the pixel Id
+
+    Float_t  fGain;      // The relative gain repect to nominal one
+
+public:
+    MGainFluctuationPix(Int_t pix=-1, Float_t gain=0);
+
+    Int_t   GetPixId() const            { return fPixId;   }
+    Float_t GetGain() const             { return fGain;    }
+    void    SetGain(Float_t g)          { fGain    = g; }
+
+    void    Print(Option_t *opt = NULL) const;
+
+    ClassDef(MGainFluctuationPix, 1)  // class containing information about the Cerenkov Photons in a pixel
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MHDisp.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MHDisp.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MHDisp.cc	(revision 9772)
@@ -0,0 +1,717 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Eva Domingo,     12/2004 <mailto:domingo@ifae.es>
+!              Wolfgang Wittek, 12/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MHDisp                                                                //
+//                                                                         //
+//   container holding the histograms for Disp                             //
+//   also computes the minimization parameter of the Disp optimization     // 
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MHDisp.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TProfile.h>
+#include <TArrayI.h>
+#include <TPad.h>
+#include <TCanvas.h>
+#include <TStyle.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MNewImagePar.h"
+#include "MMcEvt.hxx"
+#include "MPointingPos.h"
+#include "MImageParDisp.h"
+
+#include "MHMatrix.h"
+#include "MParameters.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHDisp);
+
+using namespace std;
+
+enum dispVar_t {kX,kY,kMeanX,kMeanY,kDelta,kSize,kM3Long,kAsym,
+		kEnergy,kImpact,kLongitmax,kZd,kAz,kTotVar};    // enum variables for the
+                                                                // matrix columns mapping
+
+// --------------------------------------------------------------------------
+//
+// Constructor 
+//
+MHDisp::MHDisp(const char *imagepardispname,
+	       const char *name, const char *title)
+  : fImageParDispName(imagepardispname)
+{
+    fName  = name  ? name  : "MHDisp";
+    fTitle = title ? title : "Histograms for Disp";
+
+    fSelectedPos = 1;  // default MHDisp flag (selects Correct Disp source position solution)
+
+    fMatrix = NULL;
+
+    // initialize mapping array dimension to the number of columns of fMatrix
+    fMap.Set(kTotVar);
+
+    //--------------------------------------------------
+    // creating the Disp related histograms
+
+    fHistEnergy   = new TH1F("fHistEnergy", 
+	 "log10(Energy)", 50, 1., 3.);
+    fHistEnergy->SetDirectory(NULL);
+    fHistEnergy->UseCurrentStyle();
+    fHistEnergy->SetXTitle("log10(Energy) [GeV]");
+    fHistEnergy->SetYTitle("# events");
+
+    fHistSize   = new TH1F("fHistSize", 
+	 "log10(Size)", 50, 2., 4.);
+    fHistSize->SetDirectory(NULL);
+    fHistSize->UseCurrentStyle();
+    fHistSize->SetXTitle("log10(Size) [#phot]");
+    fHistSize->SetYTitle("# events");
+
+    fHistcosZA   = new TH1F("fHistcosZA", 
+	 "cos(Zenith Angle)", 10, 0., 1.);
+    fHistcosZA->SetDirectory(NULL);
+    fHistcosZA->UseCurrentStyle();
+    fHistcosZA->SetXTitle("cos(Theta)");
+    fHistcosZA->SetYTitle("# events");
+
+    fSkymapXY = new TH2F("fSkymapXY", 
+         "Disp estimated source positions Skymap", 71, -2., 2., 71, -2., 2.);
+    fSkymapXY->SetDirectory(NULL);
+    fSkymapXY->UseCurrentStyle();
+    fSkymapXY->SetXTitle("X Disp source position [deg]");
+    fSkymapXY->SetYTitle("Y Disp source position [deg]");
+
+    fHistMinPar   = new TH1F("fHistMinPar"  , 
+         "Distance^2 between Disp and real srcpos", 100, 0., 2.);
+    fHistMinPar->SetDirectory(NULL);
+    fHistMinPar->UseCurrentStyle();
+    fHistMinPar->SetXTitle("Minimization parameter = d^2 Disp to real srcpos [deg^2]");
+    fHistMinPar->SetYTitle("# events");
+    
+    fHistDuDv   = new TH2F("fHistDuDv", 
+	 "Du vs. Dv (distances between Disp and real srcpos)", 
+	 100, -2., 2., 100, -2., 2.);
+    fHistDuDv->SetDirectory(NULL);
+    fHistDuDv->UseCurrentStyle();
+    fHistDuDv->SetXTitle("Dv = transveral distance [deg]");
+    fHistDuDv->SetYTitle("Du = longitudinal distance [deg]");
+
+    fHistMinParEnergy   = new TH2F("fHistMinParEnergy", 
+	 "Minimization parameter vs. Energy", 50, 1., 3., 100, 0., 2.);
+    fHistMinParEnergy->SetDirectory(NULL);
+    fHistMinParEnergy->UseCurrentStyle();
+    fHistMinParEnergy->SetXTitle("log10(Energy) [GeV]");
+    fHistMinParEnergy->SetYTitle("Minimization parameter = d^2 Disp to real srcpos [deg^2]");
+
+    fHistMinParSize   = new TH2F("fHistMinParSize", 
+	 "Minimization parameter vs. Size", 50, 2., 4., 100, 0., 2.);
+    fHistMinParSize->SetDirectory(NULL);
+    fHistMinParSize->UseCurrentStyle();
+    fHistMinParSize->SetXTitle("log10(Size) [#phot]");
+    fHistMinParSize->SetYTitle("Minimization parameter = d^2 Disp to real srcpos [deg^2]");
+
+    fHistDuEnergy   = new TH2F("fHistDuEnergy", 
+	 "Du vs. Energy", 50, 1., 3., 100, -2., 2.);
+    fHistDuEnergy->SetDirectory(NULL);
+    fHistDuEnergy->UseCurrentStyle();
+    fHistDuEnergy->SetXTitle("log10(Energy) [GeV]");
+    fHistDuEnergy->SetYTitle("Du = longitudinal distance Disp to real srcpos [deg]");
+
+    fHistDuSize   = new TH2F("fHistDuSize", 
+	 "Du vs. Size", 50, 2., 4., 100, -2., 2.);
+    fHistDuSize->SetDirectory(NULL);
+    fHistDuSize->UseCurrentStyle();
+    fHistDuSize->SetXTitle("log10(Size) [#phot]");
+    fHistDuSize->SetYTitle("Du = longitudinal distance Disp to real srcpos [deg]");
+
+    fHistDvEnergy   = new TH2F("fHistDvEnergy", 
+	 "Dv vs. Energy", 50, 1., 3., 100, -2., 2.);
+    fHistDvEnergy->SetDirectory(NULL);
+    fHistDvEnergy->UseCurrentStyle();
+    fHistDvEnergy->SetXTitle("log10(Energy) [GeV]");
+    fHistDvEnergy->SetYTitle("Dv = transveral distance Disp to real srcpos [deg]");
+
+    fHistDvSize   = new TH2F("fHistDvSize", 
+	 "Dv vs. Size", 50, 2., 4., 100, -2., 2.);
+    fHistDvSize->SetDirectory(NULL);
+    fHistDvSize->UseCurrentStyle();
+    fHistDvSize->SetXTitle("log10(Size) [#phot]");
+    fHistDvSize->SetYTitle("Dv = transveral distance Disp to real srcpos [deg]");
+
+    fEvCorrAssign   = new TProfile("fEvCorrAssign", 
+	 "Fraction events srcpos well assign vs. Size", 50, 2., 4., 0., 1.);
+    fEvCorrAssign->SetDirectory(NULL);
+    fEvCorrAssign->SetStats(0);
+    fEvCorrAssign->SetXTitle("log10(Size) [#phot]");
+    fEvCorrAssign->SetYTitle("Fraction of events with srcpos well assign");
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Destructor 
+//
+MHDisp::~MHDisp()
+{
+  delete fHistEnergy;
+  delete fHistSize;
+  delete fHistcosZA;
+  delete fSkymapXY;
+  delete fHistMinPar;
+  delete fHistDuDv;
+  delete fHistMinParEnergy;
+  delete fHistMinParSize;
+  delete fHistDuEnergy;
+  delete fHistDuSize;
+  delete fHistDvEnergy;
+  delete fHistDvSize;
+  delete fEvCorrAssign;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the pointers to the containers 
+// 
+//
+Bool_t MHDisp::SetupFill(const MParList *pList)
+{
+    // reset all histograms and Minimization parameter computing variables
+    // before each new eventloop
+    fNumEv = 0;
+    fSumMinPar  = 0.;
+    fMinPar = (MParameterD*)const_cast<MParList*>(pList)->FindCreateObj("MParameterD", "MinimizationParameter");
+    if (!fMinPar)
+    {
+      *fLog << err << "MParameterD (MinimizationParameter) not found and could not be created... aborting." 
+	    << endl;
+      return kFALSE;
+    }
+    fMinPar->SetVal(0);
+
+    fHistEnergy->Reset();
+    fHistSize->Reset();
+    fHistcosZA->Reset();
+    fSkymapXY->Reset();
+    fHistMinPar->Reset();
+    fHistDuDv->Reset();
+    fHistMinParEnergy->Reset();
+    fHistMinParSize->Reset();
+    fHistDuEnergy->Reset();
+    fHistDuSize->Reset();
+    fHistDvEnergy->Reset();
+    fHistDvSize->Reset();
+    fEvCorrAssign->Reset();
+
+
+    // look for the defined camera geometry to get mm to deg conversion factor
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." 
+              << endl;
+        return kFALSE;
+    }
+    fMm2Deg = cam->GetConvMm2Deg();
+
+
+    // look for Disp related containers
+    fImageParDisp = (MImageParDisp*)pList->FindObject(fImageParDispName,
+						      "MImageParDisp");
+    if (!fImageParDisp)
+    {
+        *fLog << err << fImageParDispName 
+              << " [MImageParDisp] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    //-----------------------------------------------------------
+    // if fMatrix exists, skip preprocessing and just read events from matrix;
+    // if doesn't exist, read variables values from containers, so look for them
+    if (fMatrix)
+      return kTRUE;
+    
+    fSrcPos = (MSrcPosCam*)pList->FindObject("MSrcPosCam");
+    if (!fSrcPos)
+    {
+        *fLog << err << "MSrcPosCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHil = (MHillas*)pList->FindObject("MHillas");
+    if (!fHil)
+    {
+        *fLog << err << "MHillas not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject("MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << "MHillasExt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject("MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << "MNewImagePar not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... This is not a MC file,"
+	      << " you are not trying to optimize Disp, just calculating it."
+	      << endl;
+	//        return kFALSE;
+    }
+
+    fPointing = (MPointingPos*)pList->FindObject("MPointingPos");
+    if (!fPointing)
+    {
+        *fLog << err << "MPointingPos not found... aborting." << endl;
+	return kFALSE;
+    }
+
+    //------------------------------------------
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set which selection algorithm for the Disp estimated source position 
+// solutions we want to follow when filling the histograms:
+//  * iflag == 1 --> Correct source position, the closest to the real srcpos
+//                   (only applicable to MC or well known source real data)
+//  * iflag == 2 --> Wrong source position, the furthest to the real srcpos
+//                   (same applicability than case 1)
+//  * iflag == 3 --> Source position assigned as M3Long sign indicates
+//  * iflag == 4 --> Source position assigned as Asym sign indicates
+//
+void MHDisp::SetSelectedPos(Int_t iflag)
+{ 
+    fSelectedPos = iflag; 
+}    
+
+
+// --------------------------------------------------------------------------
+//
+// Sets the Matrix and the array of mapped values for each Matrix column
+//
+void MHDisp::SetMatrixMap(MHMatrix *matrix, TArrayI &map)
+{
+    fMatrix = matrix;
+    fMap = map;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns the Matrix and the mapped value for each Matrix column
+//
+void MHDisp::GetMatrixMap(MHMatrix* &matrix, TArrayI &map)
+{
+    map = fMap;
+    matrix = fMatrix;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers for the Disp optimization. This function adds all 
+// necessary columns to the given matrix. Afterwards, you should fill 
+// the matrix with the corresponding data (eg from a file by using 
+// MHMatrix::Fill). Then, if you loop through the matrix (eg using 
+// MMatrixLoop), MHDisp::Fill will take the values from the matrix 
+// instead of the containers.
+//
+void MHDisp::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    fMap[kX]          = fMatrix->AddColumn("MSrcPosCam.fX");
+    fMap[kY]          = fMatrix->AddColumn("MSrcPosCam.fY");
+    fMap[kMeanX]      = fMatrix->AddColumn("MHillas.fMeanX");
+    fMap[kMeanY]      = fMatrix->AddColumn("MHillas.fMeanY");
+    fMap[kDelta]      = fMatrix->AddColumn("MHillas.fDelta");
+
+    fMap[kSize]       = fMatrix->AddColumn("MHillas.fSize");
+    
+    fMap[kM3Long]     = fMatrix->AddColumn("MHillasExt.fM3Long");
+    fMap[kAsym]       = fMatrix->AddColumn("MHillasExt.fAsym");
+    
+    fMap[kEnergy]     = fMatrix->AddColumn("MMcEvt.fEnergy");
+    fMap[kImpact]     = fMatrix->AddColumn("MMcEvt.fImpact");
+    fMap[kLongitmax]  = fMatrix->AddColumn("MMcEvt.fLongitmax");
+    
+    fMap[kZd]         = fMatrix->AddColumn("MPointingPos.fZd");
+    fMap[kAz]         = fMatrix->AddColumn("MPointingPos.fAz");
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns a mapped value from the Matrix
+//
+Double_t MHDisp::GetVal(Int_t i) const
+{
+    Double_t val = (*fMatrix)[fMap[i]];
+
+    //*fLog << "MHDisp::GetVal; i, fMatrix, fMap, val = "
+    //    << i << ",  " << fMatrix << ",  " << fMap[i] << ",  " << val << endl;
+
+    return val;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms and sum up the Minimization paramter outcome 
+// of each processed event
+//
+Bool_t MHDisp::Fill(const MParContainer *par, const Stat_t w)
+{
+    Double_t energy = 0.;
+    Double_t impact = 0.;
+    Double_t xmax = 0.;
+
+    if ( fMatrix || (!fMatrix && fMcEvt) )
+    {  
+      energy   = fMatrix ? GetVal(kEnergy)     : fMcEvt->GetEnergy();
+      impact   = fMatrix ? GetVal(kImpact)     : fMcEvt->GetImpact();
+      xmax     = fMatrix ? GetVal(kLongitmax)  : fMcEvt->GetLongitmax();      
+    }
+
+    Double_t theta      = fMatrix ? GetVal(kZd)  : fPointing->GetZd();
+    //    Double_t phi        = fMatrix ? GetVal(kAz)  : fPointing->GetAz();
+
+    Double_t xsrcpos0   = fMatrix ? GetVal(kX)       : fSrcPos->GetX();
+    Double_t ysrcpos0   = fMatrix ? GetVal(kY)       : fSrcPos->GetY();
+    Double_t xmean0     = fMatrix ? GetVal(kMeanX)   : fHil->GetMeanX();  
+    Double_t ymean0     = fMatrix ? GetVal(kMeanY)   : fHil->GetMeanY();
+    Double_t delta      = fMatrix ? GetVal(kDelta)   : fHil->GetDelta();
+    
+    Double_t size       = fMatrix ? GetVal(kSize)    : fHil->GetSize();
+    
+    Double_t m3long     = fMatrix ? GetVal(kM3Long)  : fHilExt->GetM3Long();
+    Double_t asym       = fMatrix ? GetVal(kAsym)    : fHilExt->GetAsym();
+
+    //------------------------------------------
+    // convert to deg
+    Double_t xsrcpos  = xsrcpos0 * fMm2Deg;
+    Double_t ysrcpos  = ysrcpos0 * fMm2Deg;
+    Double_t xmean    = xmean0 * fMm2Deg;
+    Double_t ymean    = ymean0 * fMm2Deg;
+    
+    // calculate cosinus of the angle between d and a vectors
+    Double_t a = (xmean-xsrcpos)*cos(delta) + (ymean-ysrcpos)*sin(delta);
+    Double_t b = sqrt( (xmean-xsrcpos)*(xmean-xsrcpos) + (ymean-ysrcpos)*(ymean-ysrcpos) );
+    Double_t cosda = a/b;
+    
+    // sign of cosda
+    Int_t s0 = cosda>0 ? 1 : -1;   
+    
+    // get the sign of M3Long and Asym variables
+    Int_t sm3 = m3long>0 ? 1 : -1;
+    Int_t sa  =   asym>0 ? 1 : -1;
+    
+    // set the sign "s" that will select one Disp source position for each
+    // shower, according to each of the possible algorithms for solution selection:
+    //   SelectedPos = 1  means choose the right source position
+    //                 2                   wrong
+    //                 3               the position according to M3Long
+    //                 4               the position according to Asym
+    Int_t s = s0;
+    if (fSelectedPos == 1)    
+      s = s0;  
+    else if (fSelectedPos == 2)
+      s = -s0;
+    else if (fSelectedPos == 3)
+      s = sm3;
+    else if (fSelectedPos == 4)
+      s = sa;
+    else
+      *fLog << "Illegal value for Disp srcpos selection algorithm: " 
+	    << " fSelectedPos = " << fSelectedPos << endl;
+    
+    // count the number of events where source position has been correctly assigned
+    if (s == s0)
+      fEvCorrAssign->Fill(log10(size), 1.);
+    else
+      fEvCorrAssign->Fill(log10(size), 0.);
+    
+    // get estimated Disp value
+    Double_t disp = fImageParDisp->GetDisp();
+    
+    //------------------------------------------
+    // Disp estimated source position
+    Double_t xdisp = xmean - s*cos(delta)*disp;
+    Double_t ydisp = ymean - s*sin(delta)*disp;
+    fSkymapXY->Fill(xdisp,ydisp);
+    
+    // Distance between estimated Disp and real source position
+    Double_t d2 = (xdisp-xsrcpos)*(xdisp-xsrcpos) +  (ydisp-ysrcpos)*(ydisp-ysrcpos); 
+    fHistMinPar->Fill(d2);
+    
+    // Longitudinal and transversal distances between Disp and real source positon
+    Double_t Du = -s*( (xdisp-xsrcpos)*cos(delta) + (ydisp-ysrcpos)*sin(delta));
+    Double_t Dv = -s*(-(xdisp-xsrcpos)*sin(delta) + (ydisp-ysrcpos)*cos(delta));
+    fHistDuDv->Fill(Dv,Du);
+    
+    // Fill Energy, Size and ZA distributions
+    if (fMatrix || (!fMatrix && fMcEvt))
+      fHistEnergy->Fill(log10(energy));
+    fHistSize->Fill(log10(size));
+    fHistcosZA->Fill(cos(theta/kRad2Deg));
+    
+    // to check the size and energy dependence of the optimization
+    if (fMatrix || (!fMatrix && fMcEvt))
+    {
+      fHistMinParEnergy->Fill(log10(energy),d2);
+      fHistDuEnergy->Fill(log10(energy),Du);
+      fHistDvEnergy->Fill(log10(energy),Dv);
+    }
+    fHistMinParSize->Fill(log10(size),d2);
+    fHistDuSize->Fill(log10(size),Du);
+    fHistDvSize->Fill(log10(size),Dv);
+    
+    // variables for the Minimization parameter calculation (= d^2)
+    fNumEv += 1;
+    fSumMinPar += d2;  
+    
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Calculates the final Minimization parameter of the Disp optimization
+//
+Bool_t MHDisp::Finalize()
+{
+    fMinPar->SetVal(fSumMinPar/fNumEv);
+    *fLog << endl;
+    *fLog << "MHDisp::Finalize: SumMinPar, NumEv = " << fSumMinPar << ", " << fNumEv << endl;
+    *fLog << "MHDisp::Finalize: Final MinPar = " << fMinPar->GetVal() << endl;
+    
+    fMinPar->SetVal(fHistMinPar->GetMean());
+    *fLog << "MHDisp::Finalize: Final MinPar = " << fMinPar->GetVal() << endl;
+
+    SetReadyToSave();
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the Disp related histograms into it.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+void MHDisp::Draw(Option_t *opt)
+{
+    gStyle->SetPalette(1);
+
+    TString title = GetName();
+    title += ": ";
+    title += GetTitle();
+
+    TCanvas *pad = new TCanvas(GetName(),title,0,0,900,1500);    
+    pad->SetBorderMode(0);
+    pad->Divide(3,5);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fHistcosZA->SetTitleOffset(1.2,"Y");
+    fHistcosZA->DrawClone(opt);
+    fHistcosZA->SetBit(kCanDelete);
+    gPad->Modified();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fHistEnergy->SetTitleOffset(1.2,"Y");
+    fHistEnergy->DrawClone(opt);
+    fHistEnergy->SetBit(kCanDelete);
+    gPad->Modified();
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fHistSize->SetTitleOffset(1.2,"Y");
+    fHistSize->DrawClone(opt);
+    fHistSize->SetBit(kCanDelete);
+    gPad->Modified();
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fHistMinPar->SetTitleOffset(1.2,"Y");
+    fHistMinPar->DrawClone(opt);
+    fHistMinPar->SetBit(kCanDelete);
+    gPad->Modified();
+
+    TProfile *profMinParEnergy = fHistMinParEnergy->ProfileX("Minimization parameter vs. Energy",0,99999,"s");
+    profMinParEnergy->SetXTitle("log10(Energy) [GeV]");
+    profMinParEnergy->SetYTitle("Minimization parameter = d^2 Disp to real srcpos [deg^2]");
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    profMinParEnergy->SetTitleOffset(1.2,"Y");
+    profMinParEnergy->SetStats(0);
+    profMinParEnergy->DrawClone(opt);
+    profMinParEnergy->SetBit(kCanDelete);
+    gPad->Modified();
+
+    TProfile *profMinParSize = fHistMinParSize->ProfileX("Minimization parameter vs. Size",0,99999,"s");
+    profMinParSize->SetXTitle("log10(Size) [#phot]");
+    profMinParSize->SetYTitle("Minimization parameter = d^2 Disp to real srcpos [deg^2]");
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    profMinParSize->SetTitleOffset(1.2,"Y");
+    profMinParSize->SetStats(0);
+    profMinParSize->DrawClone(opt);
+    profMinParSize->SetBit(kCanDelete);
+    gPad->Modified();
+
+    pad->cd(7);
+    gPad->SetBorderMode(0);
+    fSkymapXY->SetTitleOffset(1.2,"Y");
+    fSkymapXY->DrawClone("COLZ");
+    fSkymapXY->SetBit(kCanDelete);
+    gPad->Modified();
+
+    pad->cd(8);
+    gPad->SetBorderMode(0);
+    fEvCorrAssign->SetTitleOffset(1.2,"Y");
+    fEvCorrAssign->DrawClone(opt);
+    fEvCorrAssign->SetBit(kCanDelete);
+    gPad->Modified();
+
+    pad->cd(9);
+    gPad->SetBorderMode(0);
+    fHistDuDv->SetTitleOffset(1.2,"Y");
+    fHistDuDv->DrawClone("COLZ");
+    fHistDuDv->SetBit(kCanDelete);
+    gPad->Modified();
+
+    TH1F *histDu = (TH1F*)fHistDuDv->ProjectionY("histDu");
+    histDu->SetTitle("Longitudinal distance Du");
+    histDu->SetXTitle("Du = longitudinal distance [deg]");
+    pad->cd(10);
+    gPad->SetBorderMode(0);
+    histDu->SetTitleOffset(1.2,"Y");
+    histDu->DrawClone(opt);
+    histDu->SetBit(kCanDelete);
+    gPad->Modified();
+
+    TProfile *profDuEnergy = fHistDuEnergy->ProfileX("Du vs. Energy",0,99999,"s");
+    profDuEnergy->SetXTitle("log10(Energy) [GeV]");
+    profDuEnergy->SetYTitle("Du = longitudinal distance [deg]");
+    pad->cd(11);
+    gPad->SetBorderMode(0);
+    profDuEnergy->SetTitleOffset(1.2,"Y");
+    profDuEnergy->SetStats(0);
+    profDuEnergy->DrawClone(opt);
+    profDuEnergy->SetBit(kCanDelete);
+    gPad->Modified();
+
+    TProfile *profDuSize = fHistDuSize->ProfileX("Du vs. Size",0,99999,"s");
+    profDuSize->SetXTitle("log10(Size) [#phot]");
+    profDuSize->SetYTitle("Du = longitudinal distance [deg]");
+    pad->cd(12);
+    gPad->SetBorderMode(0);
+    profDuSize->SetTitleOffset(1.2,"Y");
+    profDuSize->SetStats(0);
+    profDuSize->DrawClone(opt);
+    profDuSize->SetBit(kCanDelete);
+    gPad->Modified();
+
+    TH1F *histDv = (TH1F*)fHistDuDv->ProjectionX("histDv");
+    histDv->SetTitle("Transversal distance Dv");
+    histDv->SetXTitle("Dv = transversal distance [deg]");
+    pad->cd(13);
+    gPad->SetBorderMode(0);
+    histDv->SetTitleOffset(1.2,"Y");
+    histDv->DrawClone(opt);
+    histDv->SetBit(kCanDelete);
+    gPad->Modified();
+
+    TProfile *profDvEnergy = fHistDvEnergy->ProfileX("Dv vs. Energy",0,99999,"s");
+    profDvEnergy->SetXTitle("log10(Energy) [GeV]");
+    profDvEnergy->SetYTitle("Dv = transversal distance [deg]");
+    pad->cd(14);
+    gPad->SetBorderMode(0);
+    profDvEnergy->SetTitleOffset(1.2,"Y");
+    profDvEnergy->SetStats(0);
+    profDvEnergy->DrawClone(opt);
+    profDvEnergy->SetBit(kCanDelete);
+    gPad->Modified();
+
+    TProfile *profDvSize = fHistDvSize->ProfileX("Dv vs. Size",0,99999,"s");
+    profDvSize->SetXTitle("log10(Size) [#phot]");
+    profDvSize->SetYTitle("Dv = transversal distance [deg]");
+    pad->cd(15);
+    gPad->SetBorderMode(0);
+    profDvSize->SetTitleOffset(1.2,"Y");
+    profDvSize->SetStats(0);
+    profDvSize->DrawClone(opt);
+    profDvSize->SetBit(kCanDelete);
+    gPad->Modified();
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MHDisp.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MHDisp.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MHDisp.h	(revision 9772)
@@ -0,0 +1,111 @@
+#ifndef MARS_MHDisp
+#define MARS_MHDisp
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class TH1F;
+class TH2F;
+class TProfile;
+class MImageParDisp;
+class MSrcPosCam;
+class MHillas;
+class MHillasExt;
+class MNewImagePar;
+class MMcEvt;
+class MPointingPos;
+class MHMatrix;
+class MParameterD;
+
+class MHDisp : public MH
+{
+private:
+
+    MImageParDisp *fImageParDisp;  // container with the estimated Disp
+    MSrcPosCam    *fSrcPos;
+    MHillas       *fHil;
+    MHillasExt    *fHilExt;
+    MNewImagePar  *fNewPar;
+    MMcEvt        *fMcEvt;
+    MPointingPos  *fPointing;
+
+    TString fImageParDispName;
+
+    Int_t fSelectedPos;      // flag to select which of the two Disp source position
+                             // solutions we want to fill the histograms (see Set function)
+
+    TH1F *fHistEnergy;       // Energy distribution of events
+    TH1F *fHistSize;         // Size distribution of events
+    TH1F *fHistcosZA;        // cosinus Zenith angle distribution of events
+    TH2F *fSkymapXY;         // 2D histogram for Disp estimated source positions
+    TH1F *fHistMinPar;       // Histogram of the event Minimization Parameter (= d^2 = 
+                             // = distance^2 between Disp estimated and true source position)
+    TH2F *fHistDuDv;         // Distribution of longitudinal (Du) and transversal 
+                             // (Dv) distances between Disp and true source position    
+    TH2F *fHistMinParEnergy; // Minimization Parameter (= d^2) vs. Energy
+    TH2F *fHistMinParSize;   // Minimization Parameter (= d^2) vs. Size
+    TH2F *fHistDuEnergy;     // Du vs. Energy
+    TH2F *fHistDuSize;       // Du vs. Size
+    TH2F *fHistDvEnergy;     // Dv vs. Energy
+    TH2F *fHistDvSize;       // Dv vs. Size
+    TProfile *fEvCorrAssign; // % events with source position well assign vs. Size 
+
+
+    Double_t fMm2Deg;        // conversion factor from mm to deg
+
+    MHMatrix *fMatrix;       // matrix storing variables needed for the Disp optimization
+    TArrayI fMap;            // array storing the matrix mapping column numbers corresponding
+                             // to each variable added to fMatrix
+
+    Double_t GetVal(Int_t i) const;
+
+    Int_t fNumEv;            // total number of events
+    Double_t fSumMinPar;     // current sum of the minimization parameter   
+    MParameterD *fMinPar;    // final minimization parameters of the Disp optimization
+
+public:
+
+    MHDisp(const char *imagepardispname = "MImageParDisp",
+	   const char *name=NULL, const char *title=NULL);
+    ~MHDisp();
+
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();  
+
+    void SetSelectedPos(Int_t iflag);
+
+    void SetMatrixMap(MHMatrix *matrix, TArrayI &map);    
+    void GetMatrixMap(MHMatrix* &matrix, TArrayI &map);  // get matrix and its mapping array
+
+    void InitMapping(MHMatrix *mat);       // define the matrix of variables
+                                           // needed for the Disp optimization
+
+    TH1F *GetHistEnergy()       { return fHistEnergy; } 
+    TH1F *GetHistSize()         { return fHistSize; } 
+    TH1F *GetHistcosZA()        { return fHistcosZA; } 
+    TH2F *GetSkymapXY()         { return fSkymapXY; }
+    TH1F *GetHistMinPar()       { return fHistMinPar; }
+    TH2F *GetHistDuDv()         { return fHistDuDv; }
+    TH2F *GetHistMinParEnergy() { return fHistMinParEnergy; }
+    TH2F *GetHistMinParSize()   { return fHistMinParSize; }
+    TH2F *GetHistDuEnergy()     { return fHistDuEnergy; }
+    TH2F *GetHistDuSize()       { return fHistDuSize; }
+    TH2F *GetHistDvEnergy()     { return fHistDvEnergy; }
+    TH2F *GetHistDvSize()       { return fHistDvSize; }
+    TProfile *GetEvCorrAssign() { return fEvCorrAssign; }
+
+    void Draw(Option_t *opt="");
+
+    ClassDef(MHDisp, 1) // Container holding the Histograms for Disp and
+                        // the parameter to minimize in the Disp optimization
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MHPSFFromStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MHPSFFromStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MHPSFFromStars.cc	(revision 9772)
@@ -0,0 +1,476 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López 05/2004 <mailto:jlopezs@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MHPSFFromStars                                               
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHPSFFromStars.h"
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TText.h>
+#include <TPaveText.h>
+#include <TF1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+
+#include "MStarLocalCam.h"
+#include "MStarLocalPos.h"
+
+#include "MParList.h"
+
+ClassImp(MHPSFFromStars);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+MHPSFFromStars::MHPSFFromStars(Int_t starpos, const char *name, const char *title)
+    : fGeom(NULL), fCurr(NULL), fSelectedStarPos(starpos)
+{
+    fName  = name  ? name  : "MHPSFFromStars";
+    fTitle = title ? title : "Class to fill the Point Spread Function histograms";
+
+    fNumEvents=0;
+
+    fHistMeanX.SetName("MeanX");
+    fHistMeanX.SetTitle("Mean X of the Fit");
+    fHistMeanX.SetDirectory(NULL);
+    fHistMeanX.UseCurrentStyle();
+    fHistMeanX.SetXTitle("Mean X [\\circ]");
+    fHistMeanX.SetYTitle("Counts [#]");
+    fHistMeanX.SetBins(800,-2.0,2.0);
+
+    fHistMeanY.SetName("MeanY");
+    fHistMeanY.SetTitle("Mean Y of the Fit");
+    fHistMeanY.SetDirectory(NULL);
+    fHistMeanY.UseCurrentStyle();
+    fHistMeanY.SetXTitle("Mean Y [\\circ]");
+    fHistMeanY.SetYTitle("Counts [#]");
+    fHistMeanY.SetBins(800,-2.0,2.0);
+
+    fHistSigmaMinor.SetName("SigmaMinor");
+    fHistSigmaMinor.SetTitle("Sigma X of the Fit");
+    fHistSigmaMinor.SetDirectory(NULL);
+    fHistSigmaMinor.UseCurrentStyle();
+    fHistSigmaMinor.SetXTitle("Sigma X [\\circ]");
+    fHistSigmaMinor.SetYTitle("Counts [#]");
+    fHistSigmaMinor.SetBins(160,0,0.8);
+    
+    fHistSigmaMajor.SetName("SigmaMajor");
+    fHistSigmaMajor.SetTitle("Sigma Y of the Fit");
+    fHistSigmaMajor.SetDirectory(NULL);
+    fHistSigmaMajor.UseCurrentStyle();
+    fHistSigmaMajor.SetXTitle("Sigma Y [\\circ]");
+    fHistSigmaMajor.SetYTitle("Counts [#]");
+    fHistSigmaMajor.SetBins(160,0,0.8);
+
+    fProjectionX.SetName("ProjetionX");
+    fProjectionX.SetTitle("Star projection in X axis");
+    fProjectionX.SetDirectory(NULL);
+    fProjectionX.UseCurrentStyle();
+    fProjectionX.SetXTitle("X [\\circ]");
+    fProjectionX.SetYTitle("DC [uA]");
+    fProjectionX.SetBins(16,-0.8,0.8);
+
+    fProjectionY.SetName("ProjetionY");
+    fProjectionY.SetTitle("Star projection in Y axis");
+    fProjectionY.SetDirectory(NULL);
+    fProjectionY.UseCurrentStyle();
+    fProjectionY.SetXTitle("Y [\\circ]");
+    fProjectionY.SetYTitle("DC [uA]");
+    fProjectionY.SetBins(16,-0.8,0.8);
+
+    fProfile.SetName("Profile");
+    fProfile.SetTitle("Star profile");
+    fProfile.SetDirectory(NULL);
+    fProfile.UseCurrentStyle();
+    fProfile.SetXTitle("X [\\circ]");
+    fProfile.SetYTitle("X [\\circ]");
+    fProfile.SetZTitle("DC [uA]");
+    fProfile.SetBins(16,-0.8,0.8,16,-0.8,0.8);
+
+    fvsTimeMeanX.Set(0);
+    fvsTimeMeanY.Set(0);
+    fvsTimeSigmaMinor.Set(0);
+    fvsTimeSigmaMajor.Set(0);
+
+    //  fTime.Set(0);
+    fEvent.Set(0);
+
+}
+
+MHPSFFromStars::~MHPSFFromStars()
+{
+  delete fGraphMeanX;
+  delete fGraphMeanY;
+  delete fGraphSigmaMinor;
+  delete fGraphSigmaMajor;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// TObject *MHPSFFromStars::lone(const char *) const
+// {
+//   MHPSFFromStars *hpsf = new MHPSFFromStars();
+  
+//   return hpsf;
+// }
+
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+//
+Bool_t MHPSFFromStars::SetupFill(const MParList *pList)
+{
+  
+  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+  {
+      *fLog << err << GetDescriptor() 
+            << ": MGeomCam not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  TArrayC PixelsUsed;
+  PixelsUsed.Set(577);
+  PixelsUsed.Reset((Char_t)kTRUE);
+  fCamera.SetGeometry(*fGeom,"StarsDisplay","StarsDisplay");
+  fCamera.SetUsed(PixelsUsed);
+
+  fCurr = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+  
+  if (!fCurr)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+//--------------------------------------------------------------------------------
+//
+//
+Bool_t MHPSFFromStars::Fill(const MParContainer *par, const Stat_t w)
+{
+  const UInt_t numPixels = fGeom->GetNumPixels();
+
+  MStarLocalCam* stars = (MStarLocalCam*)par;
+  if (!stars)
+    {
+      *fLog << err << "No argument in " << GetName() << "::Fill... abort." << endl;
+      return kFALSE;
+    }
+
+  //
+  MStarLocalPos* star = SelectStar(stars);
+  if (star == NULL)
+    return kCONTINUE;
+  
+
+  //Check good conditions of the fitting procedure
+  Float_t expectedStarXPos = star->GetMeanX();
+  Float_t expectedStarYPos = star->GetMeanY();
+
+  if ( star->GetChiSquareNdof() == 0 
+       || star->GetChiSquareNdof()>5.)
+//       || TMath::Sqrt(expectedStarXPos*expectedStarXPos+expectedStarYPos*expectedStarYPos)>150.)
+    {
+      *fLog << warn << "Star selected were bad reconstructed" << endl;
+      return kCONTINUE;
+    }
+  
+
+
+  //Fill Histograms
+  fHistMeanX.Fill(star->GetMeanX()*fGeom->GetConvMm2Deg());
+  fHistMeanY.Fill(star->GetMeanY()*fGeom->GetConvMm2Deg());
+  if (star->GetSigmaMinorAxis() < 0)
+    *fLog << err << GetName() << " Sigma of the fit " << star->GetSigmaMinorAxis() << " negative" << endl;
+  if (star->GetSigmaMajorAxis() < 0)
+    *fLog << err << GetName() << " Sigma of the fit " << star->GetSigmaMajorAxis() << " negative" << endl;
+  fHistSigmaMinor.Fill(star->GetSigmaMinorAxis()*fGeom->GetConvMm2Deg());
+  fHistSigmaMajor.Fill(star->GetSigmaMajorAxis()*fGeom->GetConvMm2Deg());
+  
+  fCamera.AddCamContent(*fCurr);
+  
+  //Selected star X(andY) projections
+  Float_t ringofinterest = 4*(star->GetSigmaMajorAxis()>star->GetSigmaMinorAxis()?star->GetSigmaMajorAxis():star->GetSigmaMinorAxis());
+
+  // First define a area of interest around the expected position of the star
+  for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+      Float_t pixelXCenter = (*fGeom)[pix].GetX();
+      Float_t pixelYCenter = (*fGeom)[pix].GetY();
+      Float_t dist = TMath::Sqrt((pixelXCenter-expectedStarXPos)*(pixelXCenter-expectedStarXPos)+
+                          (pixelYCenter-expectedStarYPos)*(pixelYCenter-expectedStarYPos));
+      
+      if ((dist < ringofinterest))
+        {
+          fProjectionX.Fill((pixelXCenter-expectedStarXPos)*fGeom->GetConvMm2Deg(), (*fCurr)[pix]);
+          fProjectionY.Fill((pixelYCenter-expectedStarYPos)*fGeom->GetConvMm2Deg(), (*fCurr)[pix]);
+          //FIXME          fProfile.Fill((pixelXCenter-expectedStarXPos)*fGeom->GetConvMm2Deg(),(pixelYCenter-expectedStarYPos)*fGeom->GetConvMm2Deg(), (*fCurr)[pix]);
+        }
+    }
+  
+  
+  //
+  fvsTimeMeanX.Set(fNumEvents+1);
+  fvsTimeMeanY.Set(fNumEvents+1);
+  fvsTimeSigmaMinor.Set(fNumEvents+1);
+  fvsTimeSigmaMajor.Set(fNumEvents+1);
+  
+  //  fTime.Set(fNumEvents+1);
+  fEvent.Set(fNumEvents+1);
+
+  fvsTimeMeanX[fNumEvents] = star->GetMeanX()*fGeom->GetConvMm2Deg();
+  fvsTimeMeanY[fNumEvents] = star->GetMeanY()*fGeom->GetConvMm2Deg();
+  fvsTimeSigmaMinor[fNumEvents] = star->GetSigmaMinorAxis()*fGeom->GetConvMm2Deg();
+  fvsTimeSigmaMajor[fNumEvents] = star->GetSigmaMajorAxis()*fGeom->GetConvMm2Deg();
+
+  //  fTime[fNumEvents] = ?;
+  fEvent[fNumEvents] = fNumEvents;
+
+  fNumEvents++;
+  
+//   fGraphMeanX.SetPoint(fNumEvents,fNumEvents,star->GetMeanX()*fGeom->GetConvMm2Deg());
+//   fGraphMeanY.SetPoint(fNumEvents,fNumEvents,star->GetMeanY()*fGeom->GetConvMm2Deg());
+//   fGraphSigmaMinor.SetPoint(fNumEvents,fNumEvents,star->GetSigmaMinorAxis()*fGeom->GetConvMm2Deg());
+//   fGraphSigmaMajor.SetPoint(fNumEvents,fNumEvents,star->GetSigmaMajorAxis()*fGeom->GetConvMm2Deg());
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Bool_t MHPSFFromStars::Finalize()
+{
+  *fLog << inf << GetName() << " Statistics: " << fNumEvents << " events" << endl;
+  //Fit  the profile plot with a gaussian(+baseline)
+
+  return kTRUE;
+}
+
+MStarLocalPos* MHPSFFromStars::SelectStar(MStarLocalCam* stars)
+{
+  TIter Next(stars->GetList());
+  MStarLocalPos* star = NULL;
+  MStarLocalPos* selectedStar = NULL;
+  
+  Float_t dist;
+  
+  if (fSelectedStarPos >= 0)
+    for (Int_t i=0; i<=fSelectedStarPos; i++)
+        star = (MStarLocalPos*)Next();
+  else //Look for the closer star to the center
+    {
+      Float_t mindist = 600; //mm
+      while ((star=(MStarLocalPos*)Next())) 
+        {
+          dist = TMath::Sqrt(star->GetMeanX()*star->GetMeanX() +
+                             star->GetMeanY()*star->GetMeanY());
+          if (dist < mindist)
+            {
+              selectedStar = star;
+              mindist = dist;
+            }
+        }
+      
+      star = selectedStar;
+      if (star == NULL)
+          *fLog << warn << "Not found star closer to center" << endl;
+      
+    }
+      
+  return star;
+}
+
+static Double_t fitfunc(Double_t *x, Double_t *par)
+{
+   Double_t fitval = 
+     par[0] + par[1]*TMath::Exp(-0.5*(x[0]-par[2])*(x[0]-par[2])/(par[3]*par[3]));
+
+   return fitval;
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Default draw:
+//
+//
+void MHPSFFromStars::Draw(const Option_t *opt)
+{
+
+  TString option(opt);
+  option.ToLower();
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  if (fNumEvents==0)
+    {
+      *fLog << err << GetName() << " no entries to be drawn" << endl;
+      return;
+    }
+  
+    
+
+  if (option.Contains("mean"))
+    {
+      fGraphMeanX = new TGraph((Int_t)fNumEvents,fEvent.GetArray(),fvsTimeMeanX.GetArray());
+      fGraphMeanX->SetName("GraphMeanX");
+      fGraphMeanX->SetTitle("Star X position v.s. event ");
+      fGraphMeanX->UseCurrentStyle();
+      fGraphMeanX->GetXaxis()->SetTitle("Event [#]");
+      fGraphMeanX->GetYaxis()->SetTitle("X [\\circ]");
+
+      fGraphMeanY = new TGraph((Int_t)fNumEvents,fEvent.GetArray(),fvsTimeMeanY.GetArray());
+      fGraphMeanY->SetName("GraphMeanY");
+      fGraphMeanY->SetTitle("Star Y position v.s. event ");
+      fGraphMeanY->UseCurrentStyle();
+      fGraphMeanY->GetXaxis()->SetTitle("Event [#]");
+      fGraphMeanY->GetYaxis()->SetTitle("Y [\\circ]");
+
+      pad->Divide(2,2);
+
+      pad->cd(1);
+      fHistMeanX.DrawClone();
+      pad->cd(2);
+      fHistMeanY.DrawClone();
+      pad->cd(3);
+      fGraphMeanX->SetMarkerStyle(20);
+      fGraphMeanX->SetMarkerSize(0.4);
+      fGraphMeanX->Draw("AP");
+      pad->cd(4);
+      fGraphMeanY->SetMarkerStyle(20);
+      fGraphMeanY->SetMarkerSize(0.4);
+      fGraphMeanY->Draw("AP");
+    }
+  else if (option.Contains("sig"))
+    {
+
+      fGraphSigmaMinor = new TGraph((Int_t)fNumEvents,fEvent.GetArray(),fvsTimeSigmaMinor.GetArray());
+      fGraphSigmaMinor->SetName("GraphSigmaMinor");
+      fGraphSigmaMinor->SetTitle("Star X sigma v.s. event ");
+      fGraphSigmaMinor->UseCurrentStyle();
+      fGraphSigmaMinor->GetXaxis()->SetTitle("Event [#]");
+      fGraphSigmaMinor->GetYaxis()->SetTitle("Sigma X [\\circ]");
+
+      fGraphSigmaMajor = new TGraph((Int_t)fNumEvents,fEvent.GetArray(),fvsTimeSigmaMajor.GetArray());
+      fGraphSigmaMajor->SetName("GraphSigmaMajor");
+      fGraphSigmaMajor->SetTitle("Star Y sigma v.s. event ");
+      fGraphSigmaMajor->UseCurrentStyle();
+      fGraphSigmaMajor->GetXaxis()->SetTitle("Event [#]");
+      fGraphSigmaMajor->GetYaxis()->SetTitle("Sigma Y [\\circ]");
+
+      pad->Divide(2,2);
+
+      pad->cd(1);
+      fHistSigmaMinor.DrawClone();
+      pad->cd(2);
+      fHistSigmaMajor.DrawClone();
+      pad->cd(3);
+      fGraphSigmaMinor->SetMarkerStyle(21);
+      fGraphSigmaMinor->SetMarkerSize(0.4);
+//       fGraphSigmaMinor->SetMarkerColor(kBlue);
+      fGraphSigmaMinor->Draw("AP");
+      fGraphSigmaMajor->SetMarkerStyle(21);
+      fGraphSigmaMajor->SetMarkerSize(0.4);
+      pad->cd(4);
+      fGraphSigmaMajor->Draw("AP");
+    }
+  else if (option.Contains("proj"))
+  {
+      pad->Divide(2,1);
+
+      pad->cd(1);
+// Creates a Root function based on function fitf above
+      TF1 *funcX = new TF1("fitfuncX",fitfunc,-0.4,0.4,4);
+
+      Float_t sigguess = fHistSigmaMinor.GetMean();
+      Float_t max = fProjectionX.GetMaximum();
+// Sets initial values and parameter names
+      funcX->SetParNames("base","Max","Mean","Sigma");
+      funcX->SetParameters(1.,max,0.,sigguess);
+
+// Fit histogram in range defined by function
+      fProjectionX.Fit("fitfuncX","QR");
+      //      fProjectionX.DrawClone();
+
+      pad->cd(2);
+      TF1 *funcY = new TF1("fitfuncY",fitfunc,-0.4,0.4,4);
+
+      sigguess = fHistSigmaMajor.GetMean();
+      max = fProjectionY.GetMaximum();
+// Sets initial values and parameter names
+      funcY->SetParNames("base","Max","Mean","Sigma");
+      funcY->SetParameters(1.,max,0.,sigguess);
+
+// Fit histogram in range defined by function
+      fProjectionY.Fit("fitfuncX","QR");
+      fProjectionY.DrawClone();
+  }
+//   else if (option.Contains("prof"))
+//   {
+//       fProfile.DrawClone();
+//   }
+  else if (option.Contains("cam"))
+    {
+      pad->cd(1);
+
+      TArrayF x(fNumEvents);
+      TArrayF y(fNumEvents);
+      for (UInt_t i=0; i<fNumEvents; i++)
+        {
+          x[i] = fvsTimeMeanX[i]/fGeom->GetConvMm2Deg();
+          y[i] = fvsTimeMeanY[i]/fGeom->GetConvMm2Deg();
+        }
+      
+      fGraphPath = new TGraph((Int_t)fNumEvents,x.GetArray(),y.GetArray());
+      fGraphPath->SetName("GraphPath");
+      fGraphPath->UseCurrentStyle();
+
+      fCamera.DrawClone();
+      fCamera.SetPrettyPalette();
+      fGraphPath->Draw("P");
+      fGraphPath->SetMarkerStyle(21);
+      fGraphPath->SetMarkerSize(0.4);
+    }
+  else
+    *fLog << err << GetName() << "::Draw Uknown option " << option << endl;
+  
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MHPSFFromStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MHPSFFromStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MHPSFFromStars.h	(revision 9772)
@@ -0,0 +1,101 @@
+#ifndef MARS_MHPSFFromStars
+#define MARS_MHPSFFromStars
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef ROOT_TH1F
+#include <TH1F.h>
+#endif
+
+#ifndef ROOT_TGraph
+#include <TGraph.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TProfile
+#include <TProfile.h>
+#endif
+
+#ifndef ROOT_TProfile2D
+#include <TProfile2D.h>
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TObject;
+class MCameraDC;
+class MStarLocalPos;
+class MStarLocalCam;
+
+class MHPSFFromStars : public MH
+{
+ private:
+
+  MGeomCam* fGeom;
+  MCameraDC* fCurr;
+  
+  TH1F fHistMeanX;
+  TH1F fHistMeanY;
+  TH1F fHistSigmaMinor;
+  TH1F fHistSigmaMajor;
+
+  TGraph *fGraphMeanX;
+  TGraph *fGraphMeanY;
+  TGraph *fGraphPath;
+  TGraph *fGraphSigmaMinor;
+  TGraph *fGraphSigmaMajor;
+
+  TArrayF fvsTimeMeanX;
+  TArrayF fvsTimeMeanY;
+  TArrayF fvsTimeSigmaMinor;
+  TArrayF fvsTimeSigmaMajor;
+
+  TArrayF fTime;
+  TArrayF fEvent;
+
+  ULong_t fNumEvents;
+
+  MHCamera fCamera;
+  TProfile fProjectionX;
+  TProfile fProjectionY;
+  TProfile2D fProfile;
+
+  Int_t fSelectedStarPos;
+  MStarLocalPos* SelectStar(MStarLocalCam* stars);
+
+  public:
+
+  MHPSFFromStars(Int_t starpos=-1, const char *name=NULL, const char *title=NULL);
+  ~MHPSFFromStars();
+
+  Bool_t SetupFill(const MParList *pList);
+  Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+  Bool_t Finalize();
+
+  void Draw(const Option_t*);
+/*   TObject* Clone(const char *) const; */
+
+  //Getter
+  TProfile& GetProjectionX() { return fProjectionX; }
+  TProfile& GetProjectionY() { return fProjectionY; }
+  
+  ClassDef(MHPSFFromStars, 1) // A list of histograms storing star information from PMT DCs
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MHillasDisplay.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MHillasDisplay.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MHillasDisplay.cc	(revision 9772)
@@ -0,0 +1,217 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     05/2004 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MDisplayHillas
+//
+// Display the camera event of type MCerPhotEvt plus the computed hillas
+// parameters.
+//
+// Input containers (in constructor):
+//  MCerPhotEvt
+//  MGeomCam
+//
+// Input containers
+//  MHillas
+//  [MSrcPosCam]
+//  [MIslands]
+//
+// Output containers
+//  [...]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include <fstream>
+#include <math.h>
+
+#include "TVirtualPad.h"
+#include "TLine.h"
+#include "TEllipse.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MHillasDisplay.h"
+#include "MCerPhotEvt.h"
+#include "MGeomCam.h"
+#include "MHillas.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MSrcPosCam.h"
+#include "MIslands.h"
+
+ClassImp(MHillasDisplay);
+
+using namespace std;
+
+static const TString gsDefName  = "MHillasDisplay";
+static const TString gsDefTitle = "Hillas Camera display task";
+
+// -------------------------------------------------------------------------
+//
+// Constructor (see MDisplay documentation for more information)
+//
+MHillasDisplay::MHillasDisplay(MCerPhotEvt* event, MGeomCam* geom, Int_t type, const char* name, const char* title) 
+  :  MDisplay(event,geom,type), fHillas(NULL), fHillasSrc(NULL), fNewImage(NULL), fSrcPos(NULL), fIslands(NULL)
+{
+  fName  = name  ? name  : gsDefName.Data();
+  fTitle = title ? title : gsDefTitle.Data();
+}
+// -------------------------------------------------------------------------
+//
+// Call for MHillas::PreProcess and look for MHillas and look for the
+// needed containers
+//
+Int_t MHillasDisplay::PreProcess(MParList* pList)
+{  
+  if(!MDisplay::PreProcess(pList))
+    return kFALSE;
+
+  // Look for the MHillas container  
+  if(!fHillas)
+    fHillas = (MHillas*)pList->FindObject(AddSerialNumber("MHillas"), "MHillas");
+  if(!fHillas)
+    *fLog << warn << "MHillasDisplay::PreProcess Warning: MHillas object not found" << endl;
+  else
+    {
+      gPad->cd(1);
+      Draw();
+    }
+
+  // Look for src dependent hillas parameters container
+  if(!fHillasSrc)
+    fHillasSrc = (MHillasSrc*)pList->FindObject(AddSerialNumber("MHillasSrc"), "MHillasSrc");
+
+
+  // Look for the MNewImagePar container  
+  if(!fNewImage)
+    fNewImage = (MNewImagePar*)pList->FindObject(AddSerialNumber("MNewImagePar"), "MNewImagePar");
+  if(!fNewImage)
+    *fLog << warn << "MHillasDisplay::PreProcess Warning: MNewImagePar object not found" << endl;
+
+  // Look for the MSrcPosCam container  
+  if(!fSrcPos)
+    fSrcPos = (MSrcPosCam*)pList->FindObject(AddSerialNumber("MSrcPosCam"), "MSrcPosCam");
+  if(!fSrcPos)
+    *fLog << warn << "MHillasDisplay::PreProcess Warning: MSrcPosCam object not found" << endl;
+
+  // Look for the MIslands container
+  if (strlen(fIslName) > 0)
+    fIslands = (MIslands*)pList->FindObject(AddSerialNumber(fIslName));
+  else
+    fIslands = (MIslands*)pList->FindObject(AddSerialNumber("MIslands"));
+  if (!fIslands)
+    *fLog << warn << "MHillasDisplay::PreProcess Warning: MIslands object not found" << endl;
+    
+  return kTRUE;
+
+}
+// -------------------------------------------------------------------------
+//
+// Display event AND hillas parameters
+//
+Int_t MHillasDisplay::Process()
+{
+   // draw the hillas parameters
+  if(GetPauseMode())
+    {
+      if(fHillas)
+	fHillas->Print();
+      if(fHillasSrc)
+	fHillasSrc->Print();
+      if(fNewImage)
+	fNewImage->Print();
+      if(fIslands)
+	fIslands->Print();
+    }      
+   
+  // draw the event
+  if(!MDisplay::Process())
+    return kFALSE;
+  return kTRUE;
+}
+// -------------------------------------------------------------------------
+//
+// Stuff to be painted when canvas will be updated
+//
+void MHillasDisplay::Paint(Option_t* option)
+{
+  const Float_t OffsetW=20.0;
+  const Float_t OffsetL=300.0;
+
+  Float_t meanX  = fHillas->GetMeanX();
+  Float_t meanY  = fHillas->GetMeanY();
+  Float_t length = fHillas->GetLength();
+  Float_t width  = fHillas->GetWidth();
+  Float_t delta  = fHillas->GetDelta();
+
+
+  if (length<=0 || width<=0)
+    return;
+  
+  // Length line
+  TLine lineL(-(length+OffsetL)*cos(delta) + meanX,
+              -(length+OffsetL)*sin(delta) + meanY,
+	      (length+OffsetL)*cos(delta)  + meanX,
+	      (length+OffsetL)*sin(delta)  + meanY);
+
+  lineL.SetLineWidth(1);
+  lineL.SetLineColor(2);
+  lineL.Paint();
+
+  // Width line
+  TLine lineW((width+OffsetW)*sin(delta)  + meanX,
+              -(width+OffsetW)*cos(delta) + meanY,
+	      -(width+OffsetW)*sin(delta) + meanX,
+	      (width+OffsetW)*cos(delta)  + meanY);
+
+  lineW.SetLineWidth(1);
+  lineW.SetLineColor(2);
+  lineW.Paint();
+
+  // Coordinate system
+  Float_t xSrc   = fSrcPos? fSrcPos->GetX() : 0.;
+  Float_t ySrc   = fSrcPos? fSrcPos->GetY() : 0.;
+  Float_t radius = GetGeomCam()->GetMaxRadius();
+  TLine lineX(-radius,ySrc,radius,ySrc);
+  TLine lineY(xSrc,-radius,xSrc,radius);
+  lineX.SetLineWidth(1);
+  lineX.SetLineColor(108);
+  lineY.SetLineWidth(1);
+  lineY.SetLineColor(108);
+  lineX.Paint();
+  lineY.Paint();
+  
+  // COG line
+  TLine lineMean(xSrc,ySrc,meanX,meanY);
+  lineMean.SetLineWidth(1);
+  lineMean.SetLineColor(2);
+  lineMean.Paint();
+  
+  // Hillas ellipse
+  TEllipse ellipse(meanX,meanY,length,width,0,360,delta*kRad2Deg+180);
+  ellipse.SetLineWidth(2);
+  ellipse.SetLineColor(2);
+  ellipse.Paint(); 
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MHillasDisplay.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MHillasDisplay.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MHillasDisplay.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MHillasDisplay
+#define MARS_MHillasDisplay
+
+#ifndef MARS_MDisplay
+#include "MDisplay.h"
+#endif
+
+class MCerPhotEvt;
+class MSrcPosCam;
+class MGeomCam;
+class MHillas;
+class MHillasSrc;
+class MIslands;
+class MNewImagePar;
+
+class MHillasDisplay : public MDisplay
+{
+ private:
+  MHillas*      fHillas;    // pointer to container with the hillas parameters
+  MHillasSrc*   fHillasSrc; // pointer to container with source dependent hillas parameters
+  MNewImagePar* fNewImage;  // pointer to container with the new image parameters
+  MSrcPosCam*   fSrcPos;    // pointer to the source position in camera
+  MIslands*     fIslands;   // pointer to the islands
+
+  TString       fIslName;
+
+  virtual Int_t PreProcess(MParList *plist);
+  virtual Int_t Process();
+  
+
+ public:
+  MHillasDisplay(MCerPhotEvt* event, MGeomCam* geom, Int_t type=0,
+		 const char* name=NULL, const char* title=NULL);
+
+  virtual ~MHillasDisplay(){};
+
+  void SetHillas(MHillas* hillas)    {fHillas=hillas;}
+  void SetSrcPos(MSrcPosCam* srcpos) {fSrcPos=srcpos;}
+  void SetIslands(MIslands* islands) {fIslands=islands;}
+  
+  void SetIslandsName(TString inname)    {fIslName = inname;}
+  
+  virtual void Paint(Option_t* option);
+  
+  ClassDef(MHillasDisplay, 0) // task to display cleaned events with hillas parameters
+    };
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MImageParDisp.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MImageParDisp.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MImageParDisp.cc	(revision 9772)
@@ -0,0 +1,69 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Eva Domingo    , 12/2004 <mailto:domingo@ifae.es>
+!              Wolfgang Wittek, 12/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MImageParDisp
+//
+// Storage Container for estimated distance to source position (Disp)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImageParDisp.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MImageParDisp);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MImageParDisp::MImageParDisp(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MImageParDisp";
+    fTitle = title ? title : "Estimated distance to source position (Disp)";
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+void MImageParDisp::Reset()
+{
+    fDisp = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+void MImageParDisp::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Estimated distance to source position (" << GetName() << ")" << endl;
+    *fLog << " - Disp [deg] = " << fDisp << endl;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MImageParDisp.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MImageParDisp.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MImageParDisp.h	(revision 9772)
@@ -0,0 +1,30 @@
+#ifndef MARS_MImageParDisp
+#define MARS_MImageParDisp
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MImageParDisp : public MParContainer
+{
+private:
+
+    Float_t fDisp;     // [deg] distance between the image center
+                       //       and the estimated source position,
+                       //       along the major axis of the image
+
+public:
+
+    MImageParDisp(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    void SetDisp(Float_t disp)  { fDisp = disp; }
+    Float_t GetDisp() const     { return fDisp; }
+
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MImageParDisp, 1) // Container to hold estimated distance to source position (Disp)
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MImgIsland.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MImgIsland.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MImgIsland.cc	(revision 9772)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Ester Aliu ,  9/2004 <mailto:aliu@ifae.es>
+!             
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MImgIsland.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MImgIsland);
+
+using namespace std;
+
+MImgIsland::MImgIsland(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MImgIsland";
+    fTitle = title ? title : "Storage container for one island information";
+    //    cout << "Creo 1 isla" << endl;      
+    Reset();
+}
+MImgIsland::~MImgIsland()
+{
+  //  cout << "Destruyo 1 isla" << endl;
+}
+
+void MImgIsland::Reset()
+{
+  fPixNum = 0;
+  fSigToNoise = -1;
+  fTimeSpread = -1;
+  fMeanX = -1000;
+  fMeanY = -1000;
+  fDist = -1;
+  fDistW = -1;
+  fDistL = -1;
+  fDistS = -1;
+ 
+  fWidth = -1;
+  fLength = -1;
+  fSizeIsl = -1;
+  fAlpha = -1000;
+  
+  fPixList.Reset(-1);
+  fPeakPulse.Reset(-1);
+   
+}
+
+// -------------------------------------------------------------------------
+// 
+// Initialize
+// 
+void MImgIsland::InitSize(Int_t i)
+{
+  fPixList.Set(i);
+  fPeakPulse.Set(i);
+}
+
+
+// -------------------------------------------------------------------------
+// 
+// Set the pixels id in the island
+//
+void MImgIsland::SetPixList(const Int_t i, const Int_t idx)
+{
+    fPixList[i] = idx;   
+}
+
+
+
+
+// -------------------------------------------------------------------------
+// 
+// Set the arrival time in one pixel of the island
+//
+void MImgIsland::SetPeakPulse(const Int_t i, const Float_t t)
+{
+    fPeakPulse[i] = t;
+}
+
+
+// -------------------------------------------------------------------------
+// 
+// Print the island information
+//
+void MImgIsland::Print(Option_t *opt) const
+{
+
+  // TString o = opt;
+
+  *fLog << inf << "  Number of pixels = " << fPixNum << endl;
+  *fLog << inf << "  Signal-To-Noise ="  << fSigToNoise << endl;
+  *fLog << inf << "  Time Spread (Core pixels) = " << fTimeSpread << endl;
+  *fLog << inf << "  DistL = " << fDistL << endl;
+  *fLog << inf << "  DistW = " << fDistW << endl;
+  *fLog << inf << "  DistS = " << fDistS << endl;
+  *fLog << inf << "  Alpha = " << fAlpha << endl;
+
+}
+      
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MImgIsland.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MImgIsland.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MImgIsland.h	(revision 9772)
@@ -0,0 +1,100 @@
+#ifndef MARS_MImgIsland
+#define MARS_MImgIsland
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+
+class MImgIsland : public MParContainer
+{
+ private:
+
+  Int_t   fPixNum;
+  Float_t fSigToNoise;
+  Float_t fTimeSpread;
+  Float_t fDist;
+  Float_t fDistL;
+  Float_t fDistW;
+  Float_t fDistS;
+  
+  Float_t fWidth;
+  Float_t fLength;
+  Float_t fSizeIsl;
+  Float_t fMeanX;
+  Float_t fMeanY;
+ 
+  Float_t fAlpha;
+
+
+  TArrayI fPixList;
+  TArrayF fPeakPulse;
+  
+public:
+
+  MImgIsland(const char *name=NULL, const char *title=NULL);
+  ~MImgIsland();
+
+  Int_t   GetPixNum()      { return fPixNum; }
+  Float_t GetSigToNoise()  { return fSigToNoise; }
+  Float_t GetTimeSpread()  { return fTimeSpread; }
+  Float_t GetDist()        { return fDist; }  
+  Float_t GetDistL()       { return fDistL; }
+  Float_t GetDistW()       { return fDistW; }
+  Float_t GetDistS()       { return fDistS; }
+
+  //hillas parameters
+  Float_t GetSizeIsl()     { return fSizeIsl; }
+  Float_t GetMeanX()       { return fMeanX; }
+  Float_t GetMeanY()       { return fMeanY; }
+  Float_t GetWidth()       { return fWidth; }
+  Float_t GetLength()      { return fLength; }
+
+  // hillas src parameters
+  Float_t GetAlpha()       { return fAlpha; }
+  
+  void    InitSize(Int_t i);
+  UInt_t  GetSize() const { return fPixList.GetSize(); }
+
+  Int_t    GetPixList(const Int_t i = 0)   const { return fPixList.At(i); };
+  Float_t   GetPeakPulse(const Int_t i = 0) const { return fPeakPulse.At(i); };
+ 
+  void Reset();
+
+  void SetPixNum    (Int_t   i)   { fPixNum = i; }
+  void SetSigToNoise(Float_t val) { fSigToNoise = val; }
+  void SetTimeSpread(Float_t val) { fTimeSpread = val; }
+  void SetDist      (Float_t val) { fDist = val; } 
+  void SetDistL     (Float_t val) { fDistL = val; }
+  void SetDistW     (Float_t val) { fDistW = val; }
+  void SetDistS     (Float_t val) { fDistS = val; } 
+
+  //hillas parameters
+  void SetSizeIsl   (Float_t val) { fSizeIsl = val; }
+  void SetMeanX     (Float_t val) { fMeanX = val; }
+  void SetMeanY     (Float_t val) { fMeanY = val; }
+  void SetWidth     (Float_t val) { fWidth = val; }
+  void SetLength    (Float_t val) { fLength = val; }
+  
+  // hillas src parameters
+  void SetAlpha     (Float_t val) { fAlpha = val; }
+ 
+  void SetPixList( const Int_t i, const Int_t id);
+  void SetPeakPulse( const Int_t i, const Float_t time);
+
+  //  void Paint(Option_t *opt=NULL);
+  void Print(Option_t *opt=NULL) const;  
+
+  ClassDef(MImgIsland, 2) // Container that holds the island information
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MIslands.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MIslands.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MIslands.cc	(revision 9772)
@@ -0,0 +1,83 @@
+#include "MIslands.h"
+
+#include <TList.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MImgIsland.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MIslands::MIslands(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MIslands";
+    fTitle = title ? title : "Storage container for the island information of one event";
+
+    fIslands = new TList;
+    fIslands->SetOwner();    
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor.
+//
+MIslands::~MIslands()
+{
+   fIslands->Delete();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+
+MImgIsland &MIslands::operator[] (Int_t i)
+{
+  MImgIsland& isl = *static_cast<MImgIsland*>(fIslands->At(i));
+  return isl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+
+const MImgIsland &MIslands::operator[] (Int_t i) const
+{
+    return *static_cast<MImgIsland*>(fIslands->At(i));
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Print the island parameters to *fLog
+//
+ 
+void MIslands::Print(Option_t *opt) const
+{
+  *fLog << all;
+  *fLog << "Island Parameters (" << GetName() << ")"  << endl;
+
+  TIter Next(fIslands);
+  MImgIsland* isl;
+  UInt_t islnum = 0;
+  while ((isl=(MImgIsland*)Next())) 
+    {
+      *fLog << inf << "*** Island #" << islnum << " parameters ***" << endl;
+      isl->Print();
+      islnum++;
+    }  
+  
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MIslands.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MIslands.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MIslands.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MIslands
+#define MARS_MIslands
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+class TList;
+
+class MImgIsland;
+
+class MIslands : public MParContainer
+{
+ private:
+
+  TList*  fIslands;  //-> FIXME: Change TClonesArray away from a pointer?
+
+  //MHCamera fDisplay;
+  
+  Int_t fIslNum; 
+  Float_t fAlphaW;
+
+ public:
+
+  MIslands(const char *name=NULL, const char *title=NULL);
+  ~MIslands();
+
+  MImgIsland &operator[] (Int_t i);
+  const MImgIsland &operator[] (Int_t i) const;
+
+  TList* GetList() const { return fIslands; }
+  UInt_t GetIslNum() const { return fIslands->GetSize(); } //number of islands
+  Float_t GetAlphaW() const { return fAlphaW; }     //alpha weighted
+
+  void SetIslNum       (Int_t   i)   { fIslNum = i; }
+  void SetAlphaW(Float_t val) { fAlphaW = val; }
+  //  MHCamera& GetDisplay() { return fDisplay; }
+
+  //  void Paint(Option_t *o=NULL);
+  void Print(Option_t *o=NULL) const;
+
+  ClassDef(MIslands, 2)	// Storage Container for islands
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MIslandsCalc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MIslandsCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MIslandsCalc.cc	(revision 9772)
@@ -0,0 +1,826 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Ester Aliu, 2/2004 <aliu@ifae.es>
+|
+!   Last Update: 7/2004
+!
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MIslandsCalc
+//
+// The Island Calc task calculates some islands parameters for each 
+// of the events such as:
+// 
+//   - fPixNum                 //  number of pixels in the island
+//   - fSigToNoise             //  signal to noise of the island
+//   - fTimeSpread             //  "time" of the island
+//   - fMeanX                  //  mean X position of the island
+//   - fMeanY                  //  mean Y position of the island
+//   - fDist                   //  dist between an island and the continent
+//   - fLength                 //  major axis of the island ellipse
+//   - fWidth                  //  minor axis of the island ellipse
+//   - fDistL                  //  dist divided by lenght of the larger island
+//   - fDistW                  //  dist divided by width of the larger island
+//   - fDistS                  //  dist divided by size of the larger island
+//
+//   - fPixList                //  list of pixels in the island (TArrayI)
+//   - fPeakPulse              //  mean arrival time of the pixels in the island (TArrayF)
+//
+// Input Containers:
+//   MGeomCam
+//   MCerPhotEvt
+//   MPedestalCam
+//   MArrivalTimeCam
+//
+// Output Containers:
+//   MIslands
+//   MImgIsland
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MIslandsCalc.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIslands.h"
+#include "MImgIsland.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+ClassImp(MIslandsCalc);
+
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MIslandsCalc::MIslandsCalc(const char* name, const char* title)    
+  : fIsl(NULL)
+{
+    fName  = name  ? name  : "MIslandsCalc";
+    fTitle = title ? title : "Calculate island parameters";
+}
+
+
+// --------------------------------------------------------------------------
+Int_t MIslandsCalc::PreProcess (MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fCam)
+    {
+        *fLog << dbginf << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPed)
+      {
+        *fLog << dbginf << "MPedestalCam not found... aborting." << endl;
+        return kFALSE;
+      }
+
+    fTime = (MArrivalTimeCam*)pList->FindObject(AddSerialNumber("MArrivalTimeCam"));
+    if (!fTime)
+      {
+        *fLog << dbginf << "MArrivalTimeCam not found... aborting." << endl;
+        return kFALSE;
+      }
+   
+    if (strlen(fIslName) > 0)
+      {
+	fIsl = (MIslands*)pList->FindCreateObj("MIslands", AddSerialNumber(fIslName));
+      }
+    else
+      {
+      fIsl = (MIslands*)pList->FindCreateObj(AddSerialNumber("MIslands"));
+      }
+    if (!fIsl)
+      return kFALSE;
+    
+    return kTRUE;
+}
+
+
+Int_t MIslandsCalc::Process(){
+ 
+  fIsl->GetList()->Delete();
+  IslandPar();
+  
+  return kTRUE;     
+}
+
+
+Int_t MIslandsCalc::IslandPar(){
+
+  //calculates all the island parameters 
+
+  const Int_t nPix=fCam->GetNumPixels();
+  const Int_t nVect=50;
+  Int_t numisl;
+
+  Int_t** vect;
+  vect = new Int_t*[nVect];
+  for(Int_t i=0;i<nVect;i++)
+    vect[i]= new Int_t[nPix];
+  
+  Int_t* num;
+  num = new Int_t[nVect];
+  
+  if (fIslandAlgorithm == 1)
+    Calc1(numisl,nVect,nPix,vect,num);
+  if (fIslandAlgorithm == 2)
+    Calc2(numisl,nVect,nPix,vect,num);
+  
+  //set the number of islands in one event
+  fIsl->SetIslNum(numisl);
+
+  //cout << "code numisl " << numisl << endl;
+  //examine each island...
+
+  Float_t  noise;
+  Float_t  signal;
+ 
+  Int_t PixelNumIsl[numisl];
+  Float_t SigToNoise[numisl];
+  Float_t time[nPix];
+  Float_t timeVariance[numisl];
+  Float_t meanX[numisl];
+  Float_t meanY[numisl];
+  Float_t length[numisl];
+  Float_t width[numisl];
+  Float_t dist[numisl];
+  Float_t distL[numisl];
+  Float_t distW[numisl];
+  Float_t distS[numisl];
+
+
+  Float_t size[numisl], sizeLargeIsl, distance, alpha, alphaW, sizetot;
+
+  sizeLargeIsl = 0;
+  alphaW = 0;
+  sizetot = 0;
+
+  for(Int_t i = 1; i<=numisl ; i++)
+    {
+     
+      MImgIsland *imgIsl = new MImgIsland;
+      
+      imgIsl->InitSize(num[i]);
+      
+      Int_t n = 0;
+      
+      Float_t minTime = 10000.;
+      Float_t maxTime = 0.;
+
+      Float_t minX = 10000.;
+      Float_t maxX = 0.;
+
+      Float_t minY = 10000.;
+      Float_t maxY = 0.;
+
+      signal = 0;
+      noise = 0;
+      
+      size[i-1] = 0;
+      meanX[i-1] = 0;
+      meanY[i-1] = 0;
+      dist[i-1] = 0;
+      
+      PixelNumIsl[i-1] = 0;
+      timeVariance[i-1] = 0;
+           
+      for(Int_t idx=0 ; idx<nPix ; idx++)
+	{
+	  MCerPhotPix *pix = fEvt->GetPixById(idx);
+	  if(!pix) continue;
+	  const MGeomPix &gpix2 = (*fCam)[pix->GetPixId()];
+	  const MPedestalPix &ped  = (*fPed)[idx];
+	  const MArrivalTimePix &timepix = (*fTime)[idx];
+	  const Float_t nphot = pix->GetNumPhotons();
+
+	  if (vect[i][idx]==1){
+	    
+	    PixelNumIsl[i-1]++;
+	    signal += nphot * (fCam->GetPixRatio(idx));
+	    noise += pow(ped.GetPedestalRms(),2);
+	    
+	    size[i-1] += nphot;
+	    if (i == 1)
+	      sizeLargeIsl += nphot;
+	    
+	    meanX[i-1] += nphot * gpix2.GetX();
+	    meanY[i-1] += nphot * gpix2.GetY();
+	    
+	    time[i-1] = timepix.IsLoGainUsed() ? timepix.GetArrivalTimeLoGain() : timepix.GetArrivalTimeHiGain();
+	    
+	    imgIsl->SetPixList(PixelNumIsl[i-1]-1,pix->GetPixId());
+	    imgIsl->SetPeakPulse(PixelNumIsl[i-1]-1,time[i-1]);     	  	
+	    
+	    //calculates the time spread only for core pixels  
+	    if (fEvt->IsPixelCore(idx)){ 
+	      
+	      if (time[i-1] > maxTime){
+		maxTime = time[i-1];
+		maxX = gpix2.GetX();
+		maxY = gpix2.GetY();
+	      }
+	      if (time[i-1] < minTime){
+		minTime = time[i-1];
+		minX = gpix2.GetX();
+		minY = gpix2.GetY();
+	      }
+	      
+	    }
+	    n++;
+	  }	  
+	}  
+      
+      meanX[i-1] /= size[i-1];
+      meanY[i-1] /= size[i-1];
+
+      dist[i-1] = TMath::Power(meanX[i-1]-meanX[0],2) + TMath::Power(meanY[i-1]-meanY[i-1],2);
+      dist[i-1] = TMath::Sqrt(dist[i-1]);
+      
+      //timeVariance[i-1] = (maxTime-minTime);
+      
+      if (maxX!=minX && maxY!=minY)
+	timeVariance[i-1] = (maxTime-minTime)/sqrt(TMath::Power(maxX-minX,2) + TMath::Power(maxY-minY,2)); 
+      else
+	timeVariance[i-1] = -1;
+      
+      //noise = 0, in the case of MC w/o noise
+      if (noise == 0) noise = 1;
+      
+      SigToNoise[i-1]= (Float_t)signal/(Float_t)sqrt(noise);
+      
+      imgIsl->SetPixNum(PixelNumIsl[i-1]);
+      imgIsl->SetSigToNoise(SigToNoise[i-1]);
+      imgIsl->SetTimeSpread(timeVariance[i-1]);
+      imgIsl->SetMeanX(meanX[i-1]);
+      imgIsl->SetMeanY(meanY[i-1]);
+      imgIsl->SetDist(dist[i-1]);
+      imgIsl->SetSizeIsl(size[i-1]);
+      
+
+      // sanity check: if one island has 2 or less pixels
+      if (num[i]>2){
+      
+
+      // calculate width and lenght of each island
+
+      Double_t corrxx=0;              // [m^2]
+      Double_t corrxy=0;              // [m^2]
+      Double_t corryy=0;              // [m^2]
+      
+      for(Int_t idx=0 ; idx<nPix ; idx++){
+	
+	MCerPhotPix *pix = fEvt->GetPixById(idx);
+	if(!pix) continue;
+	const MGeomPix &gpix3 = (*fCam)[pix->GetPixId()];
+	const Float_t nphot = pix->GetNumPhotons();
+	
+	if (vect[i][idx]==1){
+	  
+	  const Float_t dx = gpix3.GetX() - meanX[i-1];     // [mm]
+	  const Float_t dy = gpix3.GetY() - meanY[i-1];     // [mm]
+	  
+	  corrxx += nphot * dx*dx;                     // [mm^2]
+	  corrxy += nphot * dx*dy;                     // [mm^2]
+	  corryy += nphot * dy*dy;                     // [mm^2]	       
+	  
+	}
+      }
+   
+      const Double_t d0    = corryy - corrxx;
+      const Double_t d1    = corrxy*2;
+      const Double_t d2    = d0 + TMath::Sqrt(d0*d0 + d1*d1);
+      const Double_t tand  = d2 / d1;
+      const Double_t tand2 = tand*tand;
+      
+      const Double_t s2 = tand2+1;
+      const Double_t s  = TMath::Sqrt(s2);
+      
+      const Double_t CosDelta =  1.0/s;   // need these in derived classes
+      const Double_t SinDelta = tand/s;   // like MHillasExt
+      
+      const Double_t axis1 = (tand2*corryy + d2 + corrxx)/s2/size[i-1];
+      const Double_t axis2 = (tand2*corrxx - d2 + corryy)/s2/size[i-1];
+      
+      //
+      // fLength^2 is the second moment along the major axis of the ellipse
+      // fWidth^2  is the second moment along the minor axis of the ellipse
+      //
+      // From the algorithm we get: fWidth <= fLength is always true
+      //
+      // very small numbers can get negative by rounding
+      //
+      length[i-1] = axis1<0 ? 0 : TMath::Sqrt(axis1);  // [mm]
+      width[i-1]  = axis2<0 ? 0 : TMath::Sqrt(axis2);  // [mm]
+      
+      
+      // alpha calculation
+      
+      const Double_t mx = meanX[i-1];     // [mm]
+      const Double_t my = meanY[i-1];     // [mm]
+      
+      //FIXME: xpos, ypos from MSrcPos
+      const Double_t xpos = 0.;
+      const Double_t ypos = 0.;
+      
+      const Double_t sx = mx - xpos;   // [mm]
+      const Double_t sy = my - ypos;   // [mm]
+      
+      const Double_t sd = SinDelta;  // [1]
+      const Double_t cd = CosDelta;  // [1]
+      
+      //
+      // Distance from source position to center of ellipse.
+      // If the distance is 0 distance, Alpha is not specified.
+      // The calculation has failed and returnes kFALSE.
+      //
+      distance = TMath::Sqrt(sx*sx + sy*sy);  // [mm]
+      if (distance==0){
+	
+	for (Int_t l = 0; l< nVect; l++)
+	  delete [] vect[l]; 
+	
+	delete [] vect;
+	delete [] num;
+	
+	return 1;
+      }
+      
+      //
+      // Calculate Alpha and Cosda = cos(d,a)
+      // The sign of Cosda will be used for quantities containing
+      // a head-tail information
+      //
+      // *OLD* const Double_t arg = (sy-tand*sx) / (dist*sqrt(tand*tand+1));
+      // *OLD* fAlpha = asin(arg)*kRad2Deg;
+      //
+      const Double_t arg2 = cd*sx + sd*sy;          // [mm]
+      if (arg2==0){
+	
+	for (Int_t l = 0; l< nVect; l++)
+	  delete [] vect[l]; 
+	
+	delete [] vect;
+	delete [] num;
+	
+	return 2;
+      }
+
+      const Double_t arg1 = cd*sy - sd*sx;          // [mm]
+      
+      //
+      // Due to numerical uncertanties in the calculation of the
+      // square root (dist) and arg1 it can happen (in less than 1e-5 cases)
+      // that the absolute value of arg exceeds 1. Because this uncertainty
+      // results in an Delta Alpha which is still less than 1e-3 we don't care
+      // about this uncertainty in general and simply set values which exceed
+      // to 1 saving its sign.
+      //
+      const Double_t arg = arg1/distance;
+      alpha = TMath::Abs(arg)>1 ? TMath::Sign(90., arg) : TMath::ASin(arg)*TMath::RadToDeg(); // [deg]
+      
+      alphaW += alpha*size[i-1];
+      sizetot += size[i-1];
+      
+      ////////////////////////////////////////
+      
+      distL[i-1]=dist[i-1]/length[0];
+      distW[i-1]=dist[i-1]/width[0];
+      distS[i-1]= dist[i-1]/size[0];
+      
+      imgIsl->SetLength(length[i-1]);
+      imgIsl->SetWidth(width[i-1]);
+      
+      imgIsl->SetDistL(distL[i-1]);
+      imgIsl->SetDistW(distW[i-1]);
+      imgIsl->SetDistS(distS[i-1]);
+      
+      imgIsl->SetAlpha(alpha);
+
+      }
+
+      fIsl->GetList()->Add(imgIsl);
+      
+    }
+  
+  fIsl->SetAlphaW(alphaW/sizetot);   
+  //fIsl->SetReadyToSave();
+  
+  for (Int_t l = 0; l< nVect; l++)
+    delete [] vect[l]; 
+
+ delete [] vect;
+ delete [] num;
+
+  return kTRUE;  
+}
+
+//------------------------------------------------------------------------------------------
+void MIslandsCalc::Calc1(Int_t& numisl, const Int_t nv, const Int_t npix, Int_t** vect, Int_t* num){
+  
+  
+  /////////////////////////////
+  //
+  //        ALGORITHM # 1
+  // counts the number of islands as you can see in 
+  // the event display after doing the std image cleaning
+  //
+  /////////////////////////////
+  
+  Int_t    sflag;
+  Int_t    control = 0;
+  
+  Int_t    nvect = 0;
+  
+  numisl = 0;
+
+  Int_t    zeros[nv];
+  
+  for(Int_t m = 0; m < nv ; m++)
+    for(Int_t n = 0; n < npix ; n++)
+	vect[m][n] = 0;
+    
+  for(Int_t n = 0; n < nv ; n++)
+    zeros[n] = 0;
+  
+  //cout << "new event" <<endl;
+  MCerPhotPix *pix;
+
+  // Loop over used pixels only
+  TIter Next(*fEvt);
+  
+  //after the interpolation of the pixels, these can be disordered by index. This is important for this algorithm of calculating islands
+  fEvt->Sort();
+
+  while ((pix=static_cast<MCerPhotPix*>(Next())))
+    {
+      const Int_t idx = pix->GetPixId();
+
+      const MGeomPix &gpix  = (*fCam)[idx];
+      const Int_t    nnmax  = gpix.GetNumNeighbors();
+
+      if( fEvt->IsPixelUsed(idx)) 
+     	{
+	  //cout <<idx <<endl;
+	  sflag = 0;
+	  
+	  for(Int_t j=0; j < nnmax ; j++)
+	    {
+	      const Int_t idx2 = gpix.GetNeighbor(j);
+	      
+	      if (idx2 < idx)
+		{
+		  for(Int_t k = 1; k <= nvect; k++)
+		    {
+		      if (vect[k][idx2] == 1)
+			{
+			  sflag = 1;
+			  vect[k][idx] = 1;
+			}
+		    }
+		}
+	    }
+	  
+	  if (sflag == 0)
+	    {
+	      nvect++;
+	      vect[nvect][idx] = 1;	     
+	    }
+	  
+	}
+    }
+  
+  numisl = nvect;
+  
+    
+  // Repeated Chain Corrections
+
+  Int_t jmin = 0;
+  
+  for(Int_t i = 1; i <= nvect; i++){
+    control=0;
+    for(Int_t j = i+1; j <= nvect; j++){
+      control = 0;
+      for(Int_t k = 0; k < npix; k++){
+	if (vect[i][k] == 1 && vect[j][k] == 1){
+	  control = 1;
+	  k=npix;
+	}
+      }
+      if (control == 1){
+	for(Int_t k = 0; k < npix; k++){
+	  if(vect[j][k] == 1) vect[i][k] = 1;
+	  vect[j][k] = 0;
+	  zeros[j] = 1;
+	}	
+	numisl = numisl-1;	    
+      }
+    }
+    
+    for(Int_t j = 1; j <= i-1; j++){
+      for(Int_t k = 0; k < npix; k++){
+	if (vect[i][k] == 1 && vect[j][k] == 1){
+	  control = 2; 
+	  jmin=j;
+	  k=npix;
+	  j=i;
+	}
+      }
+      
+      if (control == 2){
+	for (Int_t k = 0; k < npix; k++){
+	  if(vect[i][k]==1) vect[jmin][k]=1;
+	  vect[i][k] = 0;
+	  zeros[i] = 1;
+	}
+	numisl = numisl-1;	    
+      }	   
+    } 
+  }
+  
+  Int_t pixMAX = 0;
+  Int_t idMAX = 1;
+  Int_t l = 1;
+  Int_t numpixels;
+  
+  for(Int_t i = 1;  i<= nvect ; i++)
+    {
+      numpixels = 0;
+
+      if (zeros[i] == 0)
+	{
+	  for(Int_t k=0; k<npix; k++)
+	    {
+	      vect[l][k] = vect[i][k];
+	      if (vect[l][k] == 1)
+		numpixels++;      		
+	    }
+
+	  num[l] = numpixels;      	
+
+	  if (numpixels>pixMAX)
+	    {
+	      pixMAX = numpixels;
+	      idMAX = l;
+	    }
+	  l++;
+	}
+    }
+
+
+  //the larger island will correspond to the 1st component of the vector
+  
+  num[nvect+1] = num[1];
+  num[1] = num[idMAX];
+  num[idMAX] = num[nvect+1];
+
+  
+  for(Int_t k = 0; k<npix; k++) 
+    {
+      vect[nvect+1][k] = vect[1][k];
+      vect[1][k] = vect[idMAX][k];
+      vect[idMAX][k] = vect[nvect+1][k];
+    }
+}
+
+//------------------------------------------------------------------------------------------
+
+void MIslandsCalc::Calc2(Int_t& numisl, const Int_t nv, const Int_t npix, Int_t** vect, Int_t* num){  
+
+  
+  /////////////////////////////
+  //
+  //        ALGORITHM # 2
+  // counts the number of islands considering as the same 
+  // islands the ones separated for 2 or less pixels
+  //
+  /////////////////////////////
+  
+  Int_t    sflag;
+  Int_t    control;
+  
+  Int_t    nvect = 0;
+  numisl = 0;
+ 
+  Int_t    zeros[nv];
+  
+  Int_t kk[npix];
+
+  for(Int_t m = 0; m < nv ; m++)
+    for(Int_t n = 0; n < npix ; n++)
+	vect[m][n] = 0;
+    
+  for(Int_t n = 0; n < nv ; n++)
+    zeros[n] = 0;
+  
+  for(Int_t n = 0; n < npix ; n++)
+    kk[n] = 0;
+  
+  MCerPhotPix *pix;
+
+  //after the interpolation of the pixels, these can be disordered by index. This is important for this algorithm of calculating islands
+  fEvt->Sort();
+
+  // 1st loop over used pixels only
+  TIter Next0(*fEvt);
+ 
+  while ((pix=static_cast<MCerPhotPix*>(Next0())))
+    {
+      const Int_t idx = pix->GetPixId();
+      
+      const MGeomPix &gpix  = (*fCam)[idx]; 
+      const Int_t    nnmax  = gpix.GetNumNeighbors();
+
+      if( fEvt->IsPixelUsed(idx))
+	{
+	  kk[idx] = 1 ;
+	  for(Int_t j=0; j< nnmax; j++)
+	    {
+	      kk[gpix.GetNeighbor(j)] = 1;
+	    }
+	} 
+      
+    }
+      
+ 
+  //2nd loop over all pixels
+  TIter Next(*fEvt);
+   
+  while ((pix=static_cast<MCerPhotPix*>(Next())))
+    {
+      const Int_t idx = pix->GetPixId();
+      
+      const MGeomPix &gpix  = (*fCam)[idx];
+      const Int_t    nnmax  = gpix.GetNumNeighbors();
+      
+      if ( kk[idx] > 0)
+     	{
+	  sflag = 0;
+	  
+	  for(Int_t j=0; j < nnmax ; j++)
+	    {
+	      const Int_t idx2 = gpix.GetNeighbor(j);
+	      
+	      if (idx2 < idx)
+		{
+		  for(Int_t k = 1; k <= nvect; k++)
+		    {
+		      if (vect[k][idx2] == 1)
+			{
+			  sflag = 1;
+			  vect[k][idx] = 1;
+			}
+		    }
+		}
+	    }
+	  
+	  if (sflag == 0)
+	    {
+	      nvect++;
+	      vect[nvect][idx] = 1;	     
+	    }
+	  
+	}
+    }
+  
+  numisl = nvect;
+  
+ // Repeated Chain Corrections
+
+  Int_t jmin = 0;
+  
+  for(Int_t i = 1; i <= nvect; i++){
+    control=0;
+    for(Int_t j = i+1; j <= nvect; j++){
+      control = 0;
+      for(Int_t k = 0; k < npix; k++){
+	if (vect[i][k] == 1 && vect[j][k] == 1){
+	  control = 1;
+	  k=npix;
+	}
+      }
+      if (control == 1){
+	for(Int_t k = 0; k < npix; k++){
+	  if(vect[j][k] == 1) vect[i][k] = 1;
+	  vect[j][k] = 0;
+	  zeros[j] = 1;
+	}	
+	numisl = numisl-1;	    
+      }
+    }
+    
+    for(Int_t j = 1; j <= i-1; j++){
+      for(Int_t k = 0; k < npix; k++){
+	if (vect[i][k] == 1 && vect[j][k] == 1){
+	  control = 2; 
+	  jmin=j;
+	  k=npix;
+	  j=i;
+	}
+      }
+      
+      if (control == 2){
+	for (Int_t k = 0; k < npix; k++){
+	  if(vect[i][k]==1) vect[jmin][k]=1;
+	  vect[i][k] = 0;
+	  zeros[i] = 1;
+	}
+	numisl = numisl-1;	    
+      }	   
+    } 
+  } 
+  
+  Int_t l = 1;
+  Int_t numpixels;
+  Int_t pixMAX = 0;
+  Int_t idMAX = 1;
+
+  for(Int_t i = 1;  i<= nvect ; i++)
+    {
+      numpixels = 0;
+
+      if (zeros[i] == 0)
+	{
+	  for(Int_t k = 0; k<npix; k++)
+	    {
+	      vect[l][k] = vect[i][k];
+	      if (vect[l][k] == 1)
+		numpixels++;
+	    }
+
+	  num[l] = numpixels;
+	  
+	  if (numpixels>pixMAX)
+	    {
+	      pixMAX = numpixels;
+	      idMAX = l;
+	    }
+	  l++;
+	}
+    }
+  
+  
+  //the larger island will correspond to the 1st component of the vector
+
+  num[nvect +1] = num[1];
+  num[1] = num[idMAX];
+  num[idMAX]=num[nvect+1];
+
+  for(Int_t k = 0; k<npix; k++) 
+    {
+      vect[nvect+1][k] = vect[1][k];
+      vect[1][k] = vect[idMAX][k];
+      vect[idMAX][k] = vect[nvect+1][k];
+    }
+
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MIslandsCalc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MIslandsCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MIslandsCalc.h	(revision 9772)
@@ -0,0 +1,55 @@
+#ifndef MARS_MIslandsCalc
+#define MARS_MIslandsCalc
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MGeomCam;
+class MSigmabar;
+class MCerPhotPix;
+class MCerPhotEvt;
+class MPedestalCam;
+class MArrivalTimeCam;
+class MArrivalTimePix;
+class MGeomCam;
+class MIslands;
+class MImgIsland;
+
+class MIslandsCalc : public MGTask
+{
+ private:
+    const MGeomCam    *fCam;        //!
+    MCerPhotEvt       *fEvt;        //!
+    MSigmabar         *fSgb;        //!
+    MPedestalCam      *fPed;        //!
+    MArrivalTimeCam   *fTime;       //!
+    MGeomCam          *fGeomCam;
+
+    MIslands          *fIsl;        //!   output container to store result
+  
+    TString           fIslName;     //    name of the 'MIslands' container
+  
+    Int_t  fIslandAlgorithm;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t IslandPar();               //
+    void  Calc1(Int_t&,const Int_t,const Int_t,Int_t**,Int_t*);    // algorithm of counting islands #1
+    void  Calc2(Int_t&,const Int_t,const Int_t,Int_t**,Int_t*);    // algorithm of counting islands #2
+    
+           
+ public:
+    MIslandsCalc(const char* name=NULL, const char* title=NULL);
+    void SetOutputName(TString outname)   { fIslName = outname; }
+    
+    void SetAlgorithm(Int_t m)   {fIslandAlgorithm = m;}
+    
+    ClassDef(MIslandsCalc, 0)        // task doing the image cleaning
+}; 
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MIslandsClean.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MIslandsClean.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MIslandsClean.cc	(revision 9772)
@@ -0,0 +1,373 @@
+/* ======================================================================== *\
+!
+!
+!   Author(s): Ester Aliu, 3/2004
+!  
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MIslandClean
+//
+// The Island Cleaning task selects the islands you use for the Hillas
+// parameters calculation, after the normal image cleaning.
+//
+// There are two methods to make the selection: 
+//
+//    - No time method, as used is Whipple. It calculates an island parameter 
+//   called "signal to noise" and adds a new threshold that eliminates some   
+//   of the islands. The way the island is eliminated is seeting the pixels 
+//   of the islands as UNUSED 
+//
+//    - Time method, taking profit of the time information in MAGIC.
+//   Calculates the maximum time difference (in time slices) for each island 
+//   and corrects for the island size. With an other new threshold "noise" 
+//   islands are supposed to be eliminated.     
+//
+// Other cleanings that are allowed in this code are:
+// 
+//    - Resting only with the continent, i.e. the larger island
+//    
+//  Example:
+//
+//  MIslands   isl;
+//  isl.SetName("MIslands1");
+
+//  MImgCleanStd clean;
+//  MIslandClean islclean(0.2);
+//  islclean.SetInputName("MIslands1");  
+//  islclean.SetMethod(0); // for timing method 
+//
+//  tlist.AddToList(&clean);
+//  tlist.AddToList(&islclean);
+//
+//
+//  Input Containers:
+//    MGeomCam
+//    MCerPhotEvt
+//    MPedestalCam
+//    MArrivalTime
+//    MIslands
+//
+//  Output Containers:
+//    MCerPhotEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MIslandsClean.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIslands.h"
+#include "MImgIsland.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+ClassImp(MIslandsClean);
+
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MIslandsClean::MIslandsClean(const Float_t newThres, const char *name, const char *title)    
+  : fIsl(NULL), fIslandCleaningMethod(kNoTiming), fIslCleanThres(newThres)
+{
+    fName  = name  ? name  : "MIslandsClean";
+    fTitle = title ? title : "Clean islands";
+}
+
+
+Int_t MIslandsClean::PreProcess (MParList *pList)
+{
+    fCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fCam)
+    {
+        *fLog << dbginf << "MGeomCam not found (no geometry information available)... aborting." << endl;
+        return kFALSE;
+    }
+
+    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fEvt)
+    {
+        *fLog << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPed)
+      {
+        *fLog << dbginf << "MPedestalCam not found... aborting." << endl;
+        return kFALSE;
+      }
+
+    fTime = (MArrivalTimeCam*)pList->FindObject(AddSerialNumber("MArrivalTimeCam"));
+    if (!fTime)
+      {
+        *fLog << dbginf << "MArrivalTimeCam not found... aborting." << endl;
+        return kFALSE;
+      }
+
+    if (strlen(fIslName) > 0)
+      fIsl = (MIslands*)pList->FindObject(AddSerialNumber(fIslName));
+    else
+      fIsl = (MIslands*)pList->FindObject(AddSerialNumber("MIslands"));
+    if (!fIsl)
+      {
+        *fLog << dbginf << "MIslands not found... aborting." << endl;
+        return kFALSE;
+      }
+    
+    return kTRUE;
+}
+
+
+
+Int_t MIslandsClean::Process()
+{
+  
+  MImgIsland *imgIsl = new MImgIsland;
+  TIter Next(fIsl->GetList());
+
+  Int_t pixNum = 0;  
+  Int_t idPix = -1;
+
+  ////////////////////////////////////////////////////
+  //
+  //       TIME SPREAD ISLAND CLEANING
+  //  eliminates the island with a time spread 
+  //         higher than a given limit 
+  /////////////////////////////////////////////////// 
+  if( fIslandCleaningMethod == 0 ){
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      //fIslCleanThreshold has different values, FIXME, put two variables
+      if(imgIsl->GetTimeSpread() > fIslCleanThres)
+	{
+	  pixNum = imgIsl->GetPixNum();
+	  
+	  for(Int_t k = 0; k<pixNum; k++)
+	    {
+	      idPix = imgIsl->GetPixList(k);
+	      MCerPhotPix &pix  = (*fEvt)[idPix];
+	      pix.SetPixelUnused();
+	    }
+	}
+    }
+    
+  }
+  
+
+  ////////////////////////////////////////////////////
+  //
+  //      SIGNAL TO NOISE ISLAND CLEANING
+  //  eliminates the island with a signal-to-noise 
+  //         lower than a given limit 
+  /////////////////////////////////////////////////// 
+  else if ( fIslandCleaningMethod == 1 ) {
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      if(imgIsl->GetSigToNoise() < fIslCleanThres)
+	{
+	  pixNum = imgIsl->GetPixNum();
+	  
+	  for(Int_t k = 0; k<pixNum; k++)
+	    {
+	      idPix = imgIsl->GetPixList(k);
+	      MCerPhotPix &pix  = (*fEvt)[idPix];
+	      pix.SetPixelUnused();
+	    }
+	}
+    }	
+  }  
+  
+
+  ////////////////////////////////////////////////////
+  //
+  //      ISLAND SIZE OVER EVENT SIZE ISLAND CLEANING
+  //  eliminates the island with an island size over event size  
+  //         lower than a given limit 
+  /////////////////////////////////////////////////// 
+  else if ( fIslandCleaningMethod == 2 ) {
+    Float_t size = 0;
+    while ((imgIsl=(MImgIsland*)Next())) {
+      size += imgIsl->GetSizeIsl();
+    }
+    
+    Next.Reset();
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      if(imgIsl->GetSizeIsl()/size < fIslCleanThres)
+	{
+	  pixNum = imgIsl->GetPixNum();
+	  
+	  for(Int_t k = 0; k<pixNum; k++)
+	    {
+	      idPix = imgIsl->GetPixList(k);
+	      MCerPhotPix &pix  = (*fEvt)[idPix];
+	      pix.SetPixelUnused();
+	    }
+	}
+    }	
+  }  
+  
+  
+  ////////////////////////////////////////////////////
+  //
+  //       CONTINENT ISLAND CLEANING
+  //  eliminates all the islands except the continent 
+  //      i.e. the larger island in the event
+  //     according the number of pixels
+  /////////////////////////////////////////////////// 
+  else if( fIslandCleaningMethod == 3 ){
+    Int_t i = 0;
+    while ((imgIsl=(MImgIsland*)Next())) {
+      if (i != 0){
+	
+	pixNum = imgIsl->GetPixNum();
+	
+	for(Int_t k = 0; k<pixNum; k++)
+	  {
+	    idPix = imgIsl->GetPixList(k);
+	    MCerPhotPix &pix  = (*fEvt)[idPix];
+	    pix.SetPixelUnused();
+	  }
+      }
+      i++;   
+    }
+  }
+  
+
+  ////////////////////////////////////////////////////
+  //
+  //       LARGER and SECOND LARGER ISLAND CLEANING
+  // eliminates all the islands except the two biggest 
+  //               ones according size
+  //                
+  /////////////////////////////////////////////////// 
+  else if( fIslandCleaningMethod == 4 ){
+
+    Int_t i = 0;
+    Int_t islnum = fIsl->GetIslNum();
+    Float_t islSize[islnum]; 
+    Int_t islIdx[islnum]; 
+
+    for (Int_t j = 0; j<islnum ; j++){
+      islSize[j] = -1;
+      islIdx[j] = -1;
+    }
+    
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      islSize[i] = imgIsl->GetSizeIsl();
+      i++;
+    }
+ 
+    
+    TMath::Sort(islnum, islSize, islIdx, kTRUE);
+    
+    i = 0;
+    Next.Reset();
+    while ((imgIsl=(MImgIsland*)Next())) {
+      if (islnum > 1 && islIdx[0]!=i && islIdx[1]!=i){
+	
+	//cout <<  "removed " << i << " isl 0" << islIdx[0] << " isl 1" << islIdx[1] << endl;
+	  
+	pixNum = imgIsl->GetPixNum();
+	
+	for(Int_t k = 0; k<pixNum; k++)
+	  {
+	    idPix = imgIsl->GetPixList(k);
+	    MCerPhotPix &pix  = (*fEvt)[idPix];
+	    pix.SetPixelUnused();
+	  }
+      }
+      i++;   
+    }  
+  }
+
+
+
+  ///////////////////////////////////////////////////////
+  //
+  //       LARGER and SECOND LARGER ISLAND CLEANING II
+  // eliminates all the islands except the two biggest 
+  // ones according size, if the second one almost has 
+  // the 80% of the size of the biggest one
+  //
+  //                
+  ////////////////////////////////////////////////////// 
+  else if( fIslandCleaningMethod == 5 ){
+
+    Int_t i = 0;
+    Int_t islnum = fIsl->GetIslNum();
+    Float_t islSize[islnum]; 
+    Int_t islIdx[islnum]; 
+
+    for (Int_t j = 0; j<islnum ; j++){
+      islSize[j] = -1;
+      islIdx[j] = -1;
+    }
+    
+    while ((imgIsl=(MImgIsland*)Next())) {
+      
+      islSize[i] = imgIsl->GetSizeIsl();
+      i++;
+    }
+    
+    TMath::Sort(islnum, islSize, islIdx, kTRUE);
+    
+    i = 0;
+    Next.Reset();
+
+    while ((imgIsl=(MImgIsland*)Next())) {
+
+      if (i!=0 && islIdx[0]!=i && islIdx[1]!=i){
+	  
+	pixNum = imgIsl->GetPixNum();
+	
+	for(Int_t k = 0; k<pixNum; k++)
+	  {
+	    idPix = imgIsl->GetPixList(k);
+	    MCerPhotPix &pix  = (*fEvt)[idPix];
+	    pix.SetPixelUnused();
+	  }
+      }
+      else if(i!=0 && islSize[islIdx[i]]<0.6*islSize[islIdx[0]]){
+	
+	pixNum = imgIsl->GetPixNum();
+      
+	for(Int_t k = 0; k<pixNum; k++)
+	  {
+	    idPix = imgIsl->GetPixList(k);
+	    MCerPhotPix &pix  = (*fEvt)[idPix];
+	    pix.SetPixelUnused();
+	  }
+      }
+      i++;   
+    }  
+  }
+  
+  fEvt->SetReadyToSave();
+  
+  return kTRUE;
+  
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MIslandsClean.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MIslandsClean.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MIslandsClean.h	(revision 9772)
@@ -0,0 +1,60 @@
+#ifndef MARS_MIslandsClean
+#define MARS_MIslandsClean
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MGeomCam;
+class MSigmabar;
+class MCerPhotPix;
+class MCerPhotEvt;
+class MPedestalCam;
+class MArrivalTimeCam;
+class MArrivalTimePix;
+class MIslands;
+class MImgIsland;
+
+class MIslandsClean : public MGTask
+{
+ public: 
+
+  typedef enum {
+    kTiming,
+    kNoTiming
+  } IslandCleaningMethod_t;
+  
+ private:
+    const MGeomCam    *fCam;        //!
+    MCerPhotEvt       *fEvt;        //!
+    MSigmabar         *fSgb;        //!
+    MPedestalCam      *fPed;        //!
+    MArrivalTimeCam   *fTime;       //!
+    MIslands          *fIsl;        //!   
+   
+    TString           fIslName;
+
+    // IslandCleaningMethod_t fIslandCleaningMethod;
+    Int_t fIslandCleaningMethod;
+   
+    Float_t fIslCleanThres;
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+           
+ public:
+    MIslandsClean(const Float_t newThres=50, const char *name=NULL, const char *title=NULL);
+    
+    void SetInputName(TString inname)    {fIslName = inname;}
+    
+    //void SetMethod(IslandCleaningMethod_t m)   {fIslandCleaningMethod = m;}
+    void SetMethod(Int_t m)   {fIslandCleaningMethod = m;}
+    
+    ClassDef(MIslandsClean, 0)        // task doing the island cleaning
+}; 
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MLiveTime.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MLiveTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MLiveTime.cc	(revision 9772)
@@ -0,0 +1,75 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López , 7/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+#include "MLiveTime.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MLiveTime);
+
+using namespace std;
+
+MLiveTime::MLiveTime(UInt_t numberbins, const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MLiveTime";
+    fTitle = title ? title : "Container to hold the live time for a certain time bin";
+    
+    Set(numberbins);
+}
+
+void MLiveTime::Set(UInt_t numberbins)
+{
+  fNumberTimeBins = numberbins;
+  fLiveTimeBin.Set(numberbins);
+  fMeanRealTimeBin.Set(numberbins);
+  fWidthRealTimeBin.Set(numberbins);
+}
+
+void MLiveTime::Print(const Option_t* o) const
+{
+    TString opt = o;
+
+    Double_t totalLiveTime = 0;
+
+    if (opt.Contains("last", TString::kIgnoreCase))
+    {
+	*fLog << GetName() << ": Present real time bin " << setprecision(10) << fMeanRealTimeBin[fNumberTimeBins-1] << " +- " << setprecision(5) << fWidthRealTimeBin[fNumberTimeBins-1] << " [" <<  2*fWidthRealTimeBin[fNumberTimeBins-1]*24*60*60 << " sec] MJD" << endl;
+	*fLog << GetName() << ": Present live time " << fLiveTimeBin[fNumberTimeBins-1] << " sec" << endl;
+    }
+    else if (opt.Contains("all", TString::kIgnoreCase))
+    {
+	*fLog << GetName() << ": " << fNumberTimeBins << " time bins" << endl;
+	for (UInt_t bin = 0; bin<fNumberTimeBins; bin++)
+	{
+	    *fLog << GetName() << ": Present real time bin " << setprecision(10) << fMeanRealTimeBin[bin] << " +- " << setprecision(5) <<  fWidthRealTimeBin[bin] << " [" <<  2*fWidthRealTimeBin[bin]*24*60*60 << " sec] MJD" << endl;
+	    *fLog << GetName() << ": Present live time " << fLiveTimeBin[bin] << " sec" << endl;
+	    totalLiveTime += fLiveTimeBin[bin];
+	}		
+	*fLog << GetName() << ": Total live time " << totalLiveTime << " sec" << endl;
+    }
+    else
+	*fLog << GetName() << warn << "::Print() Bad argument " << opt << endl; 
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MLiveTime.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MLiveTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MLiveTime.h	(revision 9772)
@@ -0,0 +1,51 @@
+#ifndef MARS_MLiveTime
+#define MARS_MLiveTime
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MLiveTime : public MParContainer
+{
+ private:
+  
+  UInt_t fNumberTimeBins;
+  TArrayD fLiveTimeBin;
+  TArrayD fMeanRealTimeBin;
+  TArrayD fWidthRealTimeBin;
+  
+  void Set(UInt_t numberbins);
+
+ public:
+
+  MLiveTime(UInt_t numberbins = 1, const char *name=NULL, const char *title=NULL);
+  //~MLiveTime;
+
+  void AddBin() { Set(fNumberTimeBins+1); }
+  void AddTime(Double_t time) { fLiveTimeBin[fNumberTimeBins-1]+=time; }
+  void SetRealTime (Double_t mean, Double_t width)
+      {
+	  fMeanRealTimeBin[fNumberTimeBins-1]=mean;
+	  fWidthRealTimeBin[fNumberTimeBins-1]=width;
+      }
+
+  UInt_t GetNumberTimeBins() { return fNumberTimeBins;}
+  Double_t GetLiveTime() { return fLiveTimeBin[fNumberTimeBins-1]; }
+  Double_t GetMeanRealTime() { return fMeanRealTimeBin[fNumberTimeBins-1]; }
+  Double_t GetWidthRealTime() { return fWidthRealTimeBin[fNumberTimeBins-1]; }
+
+  TArrayD& GetLiveTimeTArray()      { return fLiveTimeBin; }
+  TArrayD& GetMeanRealTimeTArray()  { return fMeanRealTimeBin; }
+  TArrayD& GetWidthRealTimeTArray() { return fWidthRealTimeBin; }
+
+  void Print(const Option_t*) const;
+
+ ClassDef(MLiveTime, 1)    // Storage for the live time extracted from real data
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MLiveTimeCalc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MLiveTimeCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MLiveTimeCalc.cc	(revision 9772)
@@ -0,0 +1,360 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier López , 7/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MLiveTimeCalc
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MLiveTimeCalc.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MLiveTime.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MLiveTimeCalc)
+using namespace std;
+
+Bool_t Debug = kFALSE;
+Bool_t PrintNewRun = kTRUE;
+
+MLiveTimeCalc::MLiveTimeCalc(const char *name, const char *title) : kSecTomSec(1e3), kDayToSec(24.*60.*60.), fRunHeader(NULL), fEvtHeader(NULL), fPresentEventTime(NULL), fLiveTime(NULL)
+{
+
+  fName  = name  ? name  : "MLiveTimeCalc";
+  fTitle = title ? title : "Task to compute the live time from real data.";
+
+  for (Int_t i=0; i<10; i++)
+    fNumberLostEvents[i] = 0;
+  
+  fFirstEventMjd = 0.;
+  fPresentEventMjd = 0.;
+  fLastEventMjd = 0.;
+
+  fPresentEventNumber = 0;
+  fLastEventNumber = 0;
+
+  fPresentEventRunNumber = 0;
+  fLastEventRunNumber = 0;
+
+  fRealTimeBinSize = 0.;
+
+  fPrintNextEvent = kFALSE;
+}
+
+Int_t MLiveTimeCalc::PreProcess(MParList *pList)
+{
+  
+  fEvtHeader = (MRawEvtHeader*)pList->FindObject(AddSerialNumber("MRawEvtHeader"));
+  if (!fEvtHeader)
+    {
+      *fLog << err << AddSerialNumber("MRawEvtHeader") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+  
+  fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+  if (!fRunHeader)
+    {
+      *fLog << err << AddSerialNumber("MRawRunHeader") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+  
+  fPresentEventTime = (MTime*)pList->FindObject(AddSerialNumber("MTime"));
+  if (!fPresentEventTime)
+    {
+      *fLog << err << AddSerialNumber("MTime") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+  
+  
+  fLiveTime = (MLiveTime*)pList->FindCreateObj(AddSerialNumber("MLiveTime"));
+  if (!fLiveTime)
+    {
+      *fLog << err << AddSerialNumber("MLiveTime") << " cannot be created ... aborting" << endl;
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+Int_t MLiveTimeCalc::Process()
+{
+
+  fPresentEventMjd       = fPresentEventTime->GetMjd(); 
+  fLastEventMjd          = fLastEventTime.GetMjd();
+  fPreaviusLastEventMjd  = fPreaviusLastEventTime.GetMjd();
+
+  fPresentEventNumber    = fEvtHeader->GetDAQEvtNumber();
+  fPresentEventRunNumber = fRunHeader->GetRunNumber();;
+  
+  if (fPrintNextEvent && Debug)
+  {
+      *fLog << dbg << GetName() << ": Printing next event" << endl;
+      Print("all");
+      fLiveTime->Print("last");
+      *fLog << inf << endl; 
+      fPrintNextEvent = kFALSE;
+  }
+	  
+  if (fFirstEventMjd == 0)
+  {
+      fFirstEventMjd = fPresentEventMjd;
+
+      fPreaviusLastEventTime = fLastEventTime;
+      fLastEventTime = *fPresentEventTime;
+
+      fPreaviusLastEventRunNumber = fLastEventRunNumber;
+      fLastEventRunNumber = fPresentEventRunNumber;
+
+      fPreaviusLastEventNumber = fLastEventNumber;
+      fLastEventNumber = fPresentEventNumber;
+  }
+  else
+  {
+      if (isTimeStampOk())
+      {
+	  if (fRealTimeBinSize > 0 &&
+	      (fPresentEventMjd - fFirstEventMjd)*kDayToSec > fRealTimeBinSize)
+	  {
+
+	      Double_t width = (fLastEventMjd - fFirstEventMjd)/2;
+	      Double_t mean  = fFirstEventMjd + width;
+	      
+	      fLiveTime->SetRealTime(mean,width);
+	      
+	      if (Debug)
+		{
+		  *fLog << inf << GetName() << ": New time bin" << endl;
+		  Print("all");
+		  *fLog << GetName() << ": First event time " << setprecision(10) << fFirstEventMjd << setprecision(5) << endl;
+		  fLiveTime->Print("last");
+		}
+	      
+	      fLiveTime->AddBin();
+	      fFirstEventMjd = fPresentEventMjd;
+	  }      
+
+	  if (fPresentEventRunNumber!=fLastEventRunNumber)
+	  {
+	      if (fLastEventRunNumber != 0 && PrintNewRun)
+	      {
+		  *fLog << dbg << GetName() << ": New run" << endl;
+		  Print("all");
+		  fLiveTime->Print("last");
+		  *fLog << inf << endl;
+	      }
+	      fLastEventRunNumber = fPresentEventRunNumber;
+	  }
+	  else
+	      fLiveTime->AddTime((fPresentEventMjd-fLastEventMjd)*kDayToSec);
+	  
+
+      
+      fPreaviusLastEventTime = fLastEventTime;
+      fLastEventTime = *fPresentEventTime;
+
+      fPreaviusLastEventRunNumber = fLastEventRunNumber;
+      fLastEventRunNumber = fPresentEventRunNumber;
+
+      fPreaviusLastEventNumber = fLastEventNumber;      
+      fLastEventNumber = fPresentEventNumber;
+
+      }
+  }
+
+  return kTRUE;
+}
+  
+Int_t MLiveTimeCalc::PostProcess()
+{
+  Double_t width = (fLastEventMjd - fFirstEventMjd)/2;
+  Double_t mean  = fFirstEventMjd + width;
+ 
+  fLiveTime->SetRealTime(mean,width);
+
+  *fLog << dbg << endl;
+  *fLog << dbg << GetName() << ": PostProcess" << endl;
+  fLiveTime->Print("all");
+  *fLog << inf << endl;
+
+  *fLog << GetName() << " execution statistics:" << endl;
+  *fLog << dec << setfill(' ');
+
+  ULong_t fTotalNumberLostEvents = 0;
+  for (Int_t i=0; i<6; i++)
+    fTotalNumberLostEvents += fNumberLostEvents[i];
+
+  *fLog << " " << setw(7) << fTotalNumberLostEvents << " (" << setw(3) ;
+  *fLog << (Int_t)(fTotalNumberLostEvents*100/GetNumExecutions()) ;
+  *fLog << "%) bad time stamp events" << endl;
+
+  *fLog << "\t\t(" << setw(3) << (Int_t)(fNumberLostEvents[0]*100/fTotalNumberLostEvents) ;
+  *fLog << "%) time stamp == 0" << endl;
+
+  *fLog << "\t\t(" << setw(3) << (Int_t)(fNumberLostEvents[1]*100/fTotalNumberLostEvents) ;
+  *fLog << "%) last time stamp  == 0" << endl;
+
+  *fLog << "\t\t(" << setw(3) << (Int_t)(fNumberLostEvents[2]*100/fTotalNumberLostEvents) ;
+  *fLog << "%) time stamp in the past" << endl;
+
+  *fLog << "\t\t(" << setw(3) << (Int_t)(fNumberLostEvents[3]*100/fTotalNumberLostEvents) ;
+  *fLog << "%) time stamp == last one" << endl;
+
+  *fLog << "\t\t(" << setw(3) << (Int_t)(fNumberLostEvents[4]*100/fTotalNumberLostEvents) ;
+  *fLog << "%) time stamp just with integer part" << endl;
+
+  *fLog << "\t\t(" << setw(3) << (Int_t)(fNumberLostEvents[5]*100/fTotalNumberLostEvents) ;
+  *fLog << "%) run number < last one" << endl;
+
+  return kTRUE;
+}
+
+Bool_t MLiveTimeCalc::isTimeStampOk()
+{
+
+  Bool_t result = kTRUE;
+  
+
+  if (fPresentEventMjd == 0)
+    {
+	
+      if (Debug)
+	{
+	    *fLog << err << GetName() << ": Present event time stamp equal to 0" << endl;
+	    Print("all");
+	}
+
+      fNumberLostEvents[0]++;
+      result = kFALSE;
+      fPrintNextEvent = kTRUE;
+    }
+  else if (fLastEventMjd == 0)
+    {
+	
+      if (Debug)
+	{
+	    *fLog << err << GetName() << ": Last event time stamp equal to 0" << endl;
+	    Print("all");
+	}
+
+      fNumberLostEvents[1]++;
+      result = kFALSE;
+      fPrintNextEvent = kTRUE;
+    }
+  else if (fPresentEventMjd-fLastEventMjd < 0)
+    {
+      
+      if (Debug)
+	{
+	    *fLog << err << GetName() << ": Present event with time stamp in the past" << endl;
+	    Print("all");
+	}
+	  
+      fNumberLostEvents[2]++;
+      result = kFALSE;
+      fPrintNextEvent = kTRUE;
+    }
+  else if (fPresentEventMjd-fLastEventMjd == 0)
+    {
+      
+      if (Debug)
+	{
+	    *fLog << err << GetName() << ": Present event time stamp equal than last event" << endl;
+	    Print("all");
+	}
+      
+      fNumberLostEvents[3]++;
+      result = kFALSE;
+      fPrintNextEvent = kTRUE;
+    }
+  else if (fPresentEventNumber- fLastEventNumber<= 0 && fPresentEventRunNumber == fLastEventRunNumber)
+    {
+      
+      if (Debug)
+	{
+	    *fLog << warn << GetName() << ": Present event number equal or smaller than last event" << endl;
+	  Print("all");
+	}
+
+      result = kTRUE;
+      fPrintNextEvent = kTRUE;
+    }
+  else if ((Int_t)fPresentEventMjd == fPresentEventMjd)
+    {
+      
+      if (Debug)
+	{
+	    *fLog << err << GetName() << ": Present event time stamp idetical to midnight" << endl;
+	    Print("all");
+	}
+      
+      fNumberLostEvents[4]++;
+      result = kFALSE;
+      fPrintNextEvent = kTRUE;
+    }
+  else if  ((fPresentEventMjd-fLastEventMjd)*kDayToSec > 1.)
+  {
+      
+      if (Debug)
+      {
+	  *fLog << warn << GetName() << ": Time from last event bigger than 1 sec" << endl;
+	  Print("all");
+      }
+      
+      result = kTRUE;
+      fPrintNextEvent = kTRUE;
+  }
+  else if  (fPresentEventRunNumber-fLastEventRunNumber < 0)
+  {
+      
+      if (Debug)
+      {
+	  *fLog << warn << GetName() << ": Present run number previuos than last one" << endl;
+	  Print("all");
+      }
+      
+      fNumberLostEvents[5]++;
+      result = kTRUE;
+      fPrintNextEvent = kTRUE;
+  }
+
+  return result;
+}
+
+void MLiveTimeCalc::Print(const Option_t *o) const
+{
+
+  *fLog << "Present event run number       ["  << fPresentEventRunNumber << "] event number [" << fPresentEventNumber << ']' << endl;
+  *fLog << "Last event run number          ["  << fLastEventRunNumber << "] event number [" << fLastEventNumber << ']' << endl;
+  *fLog << "Preavius last event run number ["  << fPreaviusLastEventRunNumber << "] event number [" << fPreaviusLastEventNumber << ']' << endl;
+  *fLog << "Present, last and preavius to last event times:"  << endl;
+  fPresentEventTime->Print();
+  fLastEventTime.Print();
+  fPreaviusLastEventTime.Print();
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MLiveTimeCalc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MLiveTimeCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MLiveTimeCalc.h	(revision 9772)
@@ -0,0 +1,71 @@
+#ifndef MARS_MLiveTimeCalc
+#define MARS_MLiveTimeCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+class MRawRunHeader;
+class MRawEvtHeader;
+class MLiveTime;
+
+class MLiveTimeCalc : public MTask
+{
+ public:
+  
+  const Double_t kSecTomSec;
+  const Double_t kDayToSec;
+  
+ private:
+  
+  MRawRunHeader* fRunHeader;
+  MRawEvtHeader* fEvtHeader;
+
+  MTime*         fPresentEventTime;
+  MTime          fLastEventTime;
+  MTime          fPreaviusLastEventTime;
+
+  MLiveTime*     fLiveTime;
+
+  
+  UInt_t   fNumberLostEvents[10];
+
+  Double_t fFirstEventMjd;
+  Double_t fPresentEventMjd;
+  Double_t fLastEventMjd;
+  Double_t fPreaviusLastEventMjd;
+
+  Int_t    fPresentEventNumber;
+  Int_t    fLastEventNumber;
+  Double_t fPreaviusLastEventNumber;
+
+  Int_t    fPresentEventRunNumber;
+  Int_t    fLastEventRunNumber;
+  Double_t fPreaviusLastEventRunNumber;
+
+  Double_t fRealTimeBinSize;
+  
+  Bool_t fPrintNextEvent;
+
+ public:
+
+  MLiveTimeCalc(const char *name=NULL, const char *title=NULL);
+  //~MLiveTimeCalc;
+
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess();
+
+  void SetRealTimeBinSize(Double_t time) { fRealTimeBinSize=time; }
+
+  Bool_t isTimeStampOk();
+  void Print(const Option_t *o) const;
+
+ ClassDef(MLiveTimeCalc, 0)    // Task to compute the live time from real data
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MPSFFit.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MPSFFit.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MPSFFit.cc	(revision 9772)
@@ -0,0 +1,86 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López , 4/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MPSFFit.h"
+
+#include <TEllipse.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MPSFFit);
+
+using namespace std;
+
+MPSFFit::MPSFFit(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MPSFFit";
+    fTitle = title ? title : "Container that holds the values of the PSF fit.";
+
+    fMaximun = -666.; 
+    fMeanMinorAxis = -666.; 
+    fMeanMajorAxis = -666.; 
+    fSigmaMinorAxis = -666.; 
+    fSigmaMajorAxis = -666.; 
+    fChisquare = -666.; 
+}
+
+void MPSFFit::Print(Option_t *opt) const
+{
+
+    *fLog << all << GetDescriptor() << " " << GetTitle() << endl;
+
+    *fLog << all << " Maximun \t " << fMaximun << " uA" << endl;
+    *fLog << all << " Mean Minor Axis \t " << fMeanMinorAxis << " mm \t";
+    *fLog << all << " Sigma Minor Axis \t " << fSigmaMinorAxis << " mm" << endl;
+    *fLog << all << " Mean Major Axis \t " << fMeanMajorAxis << " mm \t";
+    *fLog << all << " Sigma Major Axis \t " << fSigmaMajorAxis << " mm" << endl;
+    *fLog << all << " Chi Square \t " << fChisquare;
+    *fLog << all << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MPSFFit::Paint(Option_t *opt)
+{
+    if (fSigmaMinorAxis<0 || fSigmaMajorAxis<0)
+        return;
+
+    TEllipse e(fMeanMinorAxis, fMeanMajorAxis, fSigmaMinorAxis, fSigmaMajorAxis, 0, 360, 0);
+    e.SetLineWidth(2);
+    e.Paint();
+}
+
+void MPSFFit::Reset()
+{
+     SetMaximun(0.0);
+     SetMeanMinorAxis(0.0);
+     SetMeanMajorAxis(0.0);
+     SetSigmaMinorAxis(0.0);
+     SetSigmaMajorAxis(0.0);
+     SetChisquare(0.0);
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MPSFFit.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MPSFFit.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MPSFFit.h	(revision 9772)
@@ -0,0 +1,45 @@
+#ifndef MARS_MPSFFit
+#define MARS_MPSFFit
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MPSFFit : public MParContainer
+{
+private:
+
+    Float_t fMaximun;
+    Float_t fMeanMinorAxis;
+    Float_t fMeanMajorAxis;
+    Float_t fSigmaMinorAxis;
+    Float_t fSigmaMajorAxis;
+    Float_t fChisquare;
+
+public:
+    MPSFFit(const char *name=NULL, const char *title=NULL);
+    //~MPSFFit();
+
+    void SetMaximun(Float_t Maximun_) {fMaximun=Maximun_;}
+    void SetMeanMinorAxis(Float_t MeanMinorAxis_) {fMeanMinorAxis=MeanMinorAxis_;}
+    void SetMeanMajorAxis(Float_t MeanMajorAxis_) {fMeanMajorAxis=MeanMajorAxis_;}
+    void SetSigmaMinorAxis(Float_t SigmaMinorAxis_) {fSigmaMinorAxis=SigmaMinorAxis_;}
+    void SetSigmaMajorAxis(Float_t SigmaMajorAxis_) {fSigmaMajorAxis=SigmaMajorAxis_;}
+    void SetChisquare(Float_t Chisquare_) {fChisquare=Chisquare_;}
+
+    Float_t GetMaximun() {return fMaximun;}
+    Float_t GetMeanMinorAxis() {return fMeanMinorAxis;}
+    Float_t GetMeanMajorAxis() {return fMeanMajorAxis;}
+    Float_t GetSigmaMinorAxis() {return fSigmaMinorAxis;}
+    Float_t GetSigmaMajorAxis() {return fSigmaMajorAxis;}
+    Float_t GetChisquare() {return fChisquare;}
+
+    void Reset();
+
+    void Paint(Option_t *opt=NULL);
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MPSFFit, 1) // Container that holds the values of the PSF fit.
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MPSFFitCalc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MPSFFitCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MPSFFitCalc.cc	(revision 9772)
@@ -0,0 +1,569 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López , 4/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MPSFFitCalc.h"
+
+#include <iostream>
+
+
+#include <TH1D.h>
+#include <TString.h>
+#include <TArrayS.h>
+#include <TArrayI.h>
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TStopwatch.h>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+#include "MMinuitInterface.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MPSFFitCalc);
+
+using namespace std;
+
+
+const Int_t numVar = 5;
+const Float_t pixelSize = 31.5; //[mm]
+const Float_t sqrt2 = sqrt(2.);
+const Float_t sqrt3 = sqrt(3.);
+const Bool_t usePrintOut = kTRUE;
+const Int_t minuitPrintOut = 0;
+
+UInt_t  numPixels;
+Bool_t  isPixelUsed[577];
+UInt_t  numPixelsUsed;
+Float_t pixelPosX[577];
+Float_t pixelPosY[577];
+Float_t pixelValue[577];
+Float_t ChiSquare;
+
+MPSFFitCalc::MPSFFitCalc(ImgCleanMode_t imgmode, const char *name, const char *title)
+{
+    fName  = name  ? name  : "MPSFFitCalc";
+    fTitle = title ? title : "Task that fits the PSF using the dc readout of the camera.";
+
+    fImgCleanMode = imgmode;
+    fNumRings     = 6;
+    fPedLevel     = 3.0; 
+
+
+// Initialization of the camera dc mask 'fIsPixelused[]'
+    numPixels = 577;
+    for (UInt_t pixid=0; pixid<numPixels; pixid++)
+	isPixelUsed[pixid] = kTRUE;
+
+    fTotalMeanFit.Reset();
+    fNumTotalMeanFits = 0;
+
+    fMaxDC = 30.;
+
+    fPedestalDCHist = new TH1D("ped","",(Int_t)fMaxDC*10,0.,fMaxDC);
+
+    fVname = new TString[numVar];
+    fVinit.Set(numVar); 
+    fStep.Set(numVar); 
+    fLimlo.Set(numVar); 
+    fLimup.Set(numVar); 
+    fFix.Set(numVar);
+
+
+    fVname[0] = "max";
+    fVinit[0] = fMaxDC;
+    fStep[0]  = fVinit[0]/sqrt2;
+    fLimlo[0] = 1.;
+    fLimup[0] = 40.;
+    fFix[0]   = 0;
+
+    fVname[1] = "meanminor";
+    fVinit[1] = 0.;
+    fStep[1]  = fVinit[0]/sqrt2;
+    fLimlo[1] = -600.;
+    fLimup[1] = 600.;
+    fFix[1]   = 0;
+
+    fVname[2] = "sigmaminor";
+    fVinit[2] = pixelSize;
+    fStep[2]  = fVinit[0]/sqrt2;
+    fLimlo[2] = pixelSize/(2*sqrt3);
+    fLimup[2] = 500.;
+    fFix[2]   = 0;
+
+    fVname[3] = "meanmajor";
+    fVinit[3] = 0.;
+    fStep[3]  = fVinit[0]/sqrt2;
+    fLimlo[3] = -600.;
+    fLimup[3] = 600.;
+    fFix[3]   = 0;
+
+    fVname[4] = "sigmamajor";
+    fVinit[4] = pixelSize;
+    fStep[4]  = fVinit[0]/sqrt2;
+    fLimlo[4] = pixelSize/(2*sqrt3);
+    fLimup[4] = 500.;
+    fFix[4]   = 0;
+
+    fObjectFit  = NULL;
+    //    fMethod     = "SIMPLEX";
+    fMethod     = "MIGRAD";
+    fNulloutput = kFALSE;
+}
+
+MPSFFitCalc::~MPSFFitCalc()
+{
+  delete fPedestalDCHist;
+}
+
+//______________________________________________________________________________
+//
+// The 2D gaussian fucntion used to fit the spot of the star
+//
+static Double_t func(float x,float y,Double_t *par)
+{
+    Double_t value=par[0]*exp(-(x-par[1])*(x-par[1])/(2*par[2]*par[2]))*exp(-(y-par[3])*(y-par[3])/(2*par[4]*par[4]));
+    return value;
+}
+
+//______________________________________________________________________________
+//
+// Function used by Minuit to do the fit
+//
+static void fcnPSF(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+
+//calculate chisquare
+    Double_t chisq = 0;
+    Double_t delta;
+    Double_t x,y,z;
+    Double_t errorz = 0.2; //[uA]
+
+
+    for (UInt_t pixid=1; pixid<numPixels; pixid++) 
+    {
+
+	if (isPixelUsed[pixid] && pixelValue[pixid]>0.)
+	{
+	    x = pixelPosX[pixid];
+	    y = pixelPosY[pixid];
+	    z = pixelValue[pixid];
+
+	    if (errorz > 0.0)
+	    {
+		delta  = (z-func(x,y,par))/errorz;
+		chisq += delta*delta;
+	    }
+	    else
+		cerr << "ERROR fcnPSF: This should never happen errorz[" << pixid << "] " << errorz << endl;
+	}
+    }
+    f = chisq;
+    ChiSquare = chisq;
+
+}
+
+
+void MPSFFitCalc::InitFitVariables()
+{
+
+  for (UInt_t pixid=1; pixid<577; pixid++) 
+    pixelValue[pixid]=(Float_t)((*fCamera)[pixid]);
+
+  numPixelsUsed = 0;
+  Float_t totalDC = 0.0;
+  
+    fVinit[0] = fMaxDC;
+
+    if(usePrintOut)
+      *fLog << dbg << "Pixels used in the fit \t";
+
+    for (UInt_t idx=0; idx<numPixels; idx++)
+    {
+	if (isPixelUsed[idx])
+	{
+	    fVinit[1] += pixelPosX[idx]*pixelValue[idx];
+	    fVinit[3] += pixelPosY[idx]*pixelValue[idx];
+	    totalDC += pixelValue[idx];
+	    numPixelsUsed++;
+
+	    if(usePrintOut)
+	      *fLog << dbg << ' ' << idx; 
+	}
+    }
+    if(usePrintOut)
+      *fLog << dbg << endl;
+
+     
+    fVinit[1] /= totalDC;
+    fVinit[3] /= totalDC;
+    
+
+    fVinit[2] = pixelSize*sqrt((Float_t)numPixelsUsed)/2;
+    fVinit[4] = pixelSize*sqrt((Float_t)numPixelsUsed)/3;
+
+    //Init steps
+
+    for(Int_t i=0; i<numVar; i++)
+	if (fVinit[i] != 0)
+	  fStep[i] = TMath::Abs(fVinit[i]/sqrt2);
+
+    
+    for (UInt_t pixidx=0; pixidx<numPixels; pixidx++)
+      if ( (*fGeomCam)[pixidx].GetSector() == 6)
+	fPedestalDCHist->Fill(pixelValue[pixidx]);
+    
+    fPedestalDC = fPedestalDCHist->GetBinCenter(fPedestalDCHist->GetMaximumBin());
+
+    for (UInt_t pixid=1; pixid<577; pixid++) 
+      pixelValue[pixid]-=fPedestalDC;
+
+    if(usePrintOut)
+      {
+	*fLog << dbg << "numPixelsUsed \t" << numPixelsUsed << endl;
+	*fLog << dbg << "fPedestalDC \t" << fPedestalDC << endl;
+	*fLog << dbg << "Maximun DC Init. value \t" << fVinit[0] << endl;
+	*fLog << dbg << "Mean Minor Axis Init. value \t" << fVinit[1] << " mm\t";
+	*fLog << dbg << "Sigma Minor Axis Init. value \t" << fVinit[2] << endl;
+	*fLog << dbg << "Mean Major Axis Init. value \t" << fVinit[3] << " mm\t";
+	*fLog << dbg << "Sigma Major Axis Init. value \t" << fVinit[4] << endl;
+      }
+}
+
+void MPSFFitCalc::RingImgClean()
+{
+
+  Bool_t  isPixelUsedTmp[577];
+
+  fMaxDC=0;
+  UInt_t maxDCpix[2];
+
+
+// Look for the two neighbor pixels with the maximun signal and set all pixels as unused
+    Float_t dc[2];
+    Float_t dcsum;
+
+// Find the two close pixels with the maximun dc
+    for(UInt_t pixidx=0; pixidx<numPixels; pixidx++)
+    {
+
+      if(isPixelUsed[pixidx])
+	{
+	  dc[0] = (Float_t)(*fCamera)[pixidx];
+	  isPixelUsedTmp[pixidx] = kFALSE;
+	  
+	  MGeomPix g = (*fGeomCam)[pixidx];
+	  Int_t numNextNeighbors = g.GetNumNeighbors();
+	  
+	  for(Int_t nextNeighbor=0; nextNeighbor<numNextNeighbors; nextNeighbor++)
+	    {
+	      if(isPixelUsed[pixidx])
+		{
+		  UInt_t swneighbor = g.GetNeighbor(nextNeighbor);
+		  dc[1] = (Float_t)(*fCamera)[swneighbor];
+		  
+		  dcsum = dc[0] + dc[1];
+		  
+		  if(dcsum > fMaxDC*2)
+		    {
+		      maxDCpix[0] = pixidx;
+		      maxDCpix[1] = swneighbor;
+		      fMaxDC = dcsum/2;
+		    }	
+		}
+	    }
+	}
+    }
+
+// Those variables are:
+// 1. an array of 2 dimensions
+//    1.1 the first dimension store the ring around the 'maxiun signal pixel'
+//    1.2 the sw numbers of the pixels in this ring
+// 2. an array with the number of pixels in each ring
+    UInt_t isPixelUesdInRing[fNumRings][577];
+    UInt_t numPixelsUsedInRing[fNumRings];
+
+// Store the 'maximun signal pixel in the [0] ring and set it as used 
+
+    for (Int_t core=0; core<2; core++)
+    {
+	isPixelUesdInRing[0][0] = maxDCpix[core];
+	numPixelsUsedInRing[0] = 1;
+	isPixelUsedTmp[isPixelUesdInRing[0][0]] = kTRUE;
+	
+	UInt_t count;
+	
+// Loop over the neighbors of the previus ring and store the sw numbers in the 2D array to be 
+// use in the next loop/ring 
+	for (UShort_t ring=0; ring<fNumRings-1; ring++)
+	{
+	    count = 0;  // In this variable we count the pixels we are in each ring
+	    for(UInt_t nextPixelUsed=0; nextPixelUsed<numPixelsUsedInRing[ring]; nextPixelUsed++)
+	    {
+		MGeomPix g = (*fGeomCam)[isPixelUesdInRing[ring][nextPixelUsed]];
+		Int_t numNextNeighbors = g.GetNumNeighbors();
+		for(Int_t nextNeighbor=0; nextNeighbor<numNextNeighbors; nextNeighbor++)
+		{
+		    UInt_t swneighbor = g.GetNeighbor(nextNeighbor);
+		    if (!isPixelUsedTmp[swneighbor])
+		    {
+			isPixelUsedTmp[swneighbor] = kTRUE;
+			isPixelUesdInRing[ring+1][count] = swneighbor;
+			count++;
+		    }
+		}
+		numPixelsUsedInRing[ring+1] = count;
+	    }
+	}
+
+
+    if(usePrintOut)
+      {
+	for (UInt_t row=0; row<fNumRings; row++)
+	  {
+	    
+	    *fLog << dbg  << "fIsPixeUsed[" << row << "][" << numPixelsUsedInRing[row] << "] ";
+	    for (UInt_t column=0; column<numPixelsUsedInRing[row]; column++)
+	      *fLog << dbg << isPixelUesdInRing[row][column] << ' ';
+	    *fLog << dbg << endl;
+	  }	
+      }
+    }
+
+
+    for(UInt_t pixidx=0; pixidx<numPixels; pixidx++)
+      {
+      if(isPixelUsed[pixidx] && isPixelUsedTmp[pixidx])
+	  isPixelUsed[pixidx] = kTRUE;
+      else
+	  isPixelUsed[pixidx] = kFALSE;
+      }
+
+}
+
+void MPSFFitCalc::RmsImgClean(Float_t pedestal)
+{}
+
+void MPSFFitCalc::MaskImgClean(TArrayS blindpixels)
+{
+    
+    Int_t npix = blindpixels.GetSize();
+
+    for (Int_t idx=0; idx<npix; idx++)
+	isPixelUsed[blindpixels[idx]] = kFALSE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MCameraDC
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPSFFit
+//
+Int_t MPSFFitCalc::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+
+    if (!fGeomCam)
+    {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+// Initialize positions of the pixels to be used in the minuit minimizations
+
+    for (UInt_t pixid=1; pixid<577; pixid++) 
+    {
+	MGeomPix &pix=(*fGeomCam)[pixid];
+	pixelPosX[pixid] = pix.GetX();
+	pixelPosY[pixid] = pix.GetY();
+    }
+   
+    fCamera = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+
+    if (!fCamera)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fFit = (MPSFFit*)pList->FindCreateObj(AddSerialNumber("MPSFFit"));
+    if (!fFit)
+    {
+      *fLog << err << AddSerialNumber("MPSFFit") << " cannot be created ... aborting" << endl;
+      return kFALSE;
+    }
+    
+    // Minuit initialization
+
+    TMinuit *gMinuit = new TMinuit(6);  //initialize TMinuit with a maximum of 5 params
+    gMinuit->SetFCN(fcnPSF);
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+    arglist[0] = minuitPrintOut;
+    gMinuit->mnexcm("SET PRI", arglist ,1,ierflg);
+
+    return kTRUE;
+
+}
+
+Int_t MPSFFitCalc::Process()
+{
+
+    // ------------------------------------------
+    // image cleaning
+
+    switch(fImgCleanMode)
+    {
+	case kRing:
+	{
+	    RingImgClean();
+	    break;
+	}
+	case kRms:
+	{
+	    RmsImgClean(fPedLevel);
+	    break;
+	}
+	case kMask:
+	{
+	    MaskImgClean(fBlindPixels);
+	    break;
+	}
+	case kCombined:
+	{
+	    MaskImgClean(fBlindPixels);
+	    RingImgClean();
+	    MaskImgClean(fBlindPixels);
+	    break;
+	}
+	default:
+	{
+	    *fLog << err << "Image Cleaning mode " << fImgCleanMode << " not defined" << endl;
+	    return kFALSE;
+	}
+    }
+
+    InitFitVariables();
+
+    // -------------------------------------------
+    // call MINUIT
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    for (Int_t i=0; i<numVar; i++)
+      gMinuit->mnparm(i, fVname[i], fVinit[i], fStep[i], fLimlo[i], fLimup[i], ierflg);
+
+    TStopwatch clock;
+    clock.Start();
+
+// Now ready for minimization step
+    arglist[0] = 500;
+    arglist[1] = 1.;
+    gMinuit->mnexcm(fMethod, arglist ,2,ierflg);
+
+    clock.Stop();
+
+    if(usePrintOut)
+      {
+	*fLog << dbg << "Time spent for the minimization in MINUIT :   " << endl;;
+	clock.Print();
+      }
+
+    if (ierflg)
+    {
+	*fLog << err << "MMinuitInterface::CallMinuit error " << ierflg << endl;
+	return kCONTINUE;
+    }
+    
+    fNumTotalMeanFits++;
+
+    Double_t parm,parmerr;
+    
+    gMinuit->GetParameter(0,parm,parmerr);
+    fFit->SetMaximun(parm);
+    fTotalMeanFit.SetMaximun(fTotalMeanFit.GetMaximun()+parm);
+
+    gMinuit->GetParameter(1,parm,parmerr);
+    fFit->SetMeanMinorAxis(parm);
+    fTotalMeanFit.SetMeanMinorAxis(fTotalMeanFit.GetMeanMinorAxis()+parm);
+
+    gMinuit->GetParameter(2,parm,parmerr);
+    fFit->SetSigmaMinorAxis(parm);
+    fTotalMeanFit.SetSigmaMinorAxis(fTotalMeanFit.GetSigmaMinorAxis()+parm);
+
+    gMinuit->GetParameter(3,parm,parmerr);
+    fFit->SetMeanMajorAxis(parm);
+    fTotalMeanFit.SetMeanMajorAxis(fTotalMeanFit.GetMeanMajorAxis()+parm);
+
+    gMinuit->GetParameter(4,parm,parmerr);
+    fFit->SetSigmaMajorAxis(parm);
+    fTotalMeanFit.SetSigmaMajorAxis(fTotalMeanFit.GetSigmaMajorAxis()+parm);
+
+    fFit->SetChisquare(ChiSquare/(numPixelsUsed-numVar));
+    fTotalMeanFit.SetChisquare(fTotalMeanFit.GetChisquare()+ChiSquare/(numPixelsUsed-numVar));
+
+    if(usePrintOut)
+      {
+	fFit->Print();
+	fTotalMeanFit.Print();
+      }
+
+    return kTRUE;
+}
+
+Int_t MPSFFitCalc::PostProcess()
+{
+  
+  fTotalMeanFit.SetMaximun(fTotalMeanFit.GetMaximun()/fNumTotalMeanFits);
+  fTotalMeanFit.SetMeanMinorAxis(fTotalMeanFit.GetMeanMinorAxis()/fNumTotalMeanFits);
+  fTotalMeanFit.SetSigmaMinorAxis(fTotalMeanFit.GetSigmaMinorAxis()/fNumTotalMeanFits);
+  fTotalMeanFit.SetMeanMajorAxis(fTotalMeanFit.GetMeanMajorAxis()/fNumTotalMeanFits);
+  fTotalMeanFit.SetSigmaMajorAxis(fTotalMeanFit.GetSigmaMajorAxis()/fNumTotalMeanFits);
+  fTotalMeanFit.SetChisquare(fTotalMeanFit.GetChisquare()/fNumTotalMeanFits);
+
+  fFit->SetMaximun(fTotalMeanFit.GetMaximun());
+  fFit->SetMeanMinorAxis(fTotalMeanFit.GetMeanMinorAxis());
+  fFit->SetSigmaMinorAxis(fTotalMeanFit.GetSigmaMinorAxis());
+  fFit->SetMeanMajorAxis(fTotalMeanFit.GetMeanMajorAxis());
+  fFit->SetSigmaMajorAxis(fTotalMeanFit.GetSigmaMajorAxis());
+  fFit->SetChisquare(fTotalMeanFit.GetChisquare());
+
+    if(usePrintOut)
+      fTotalMeanFit.Print();
+    
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MPSFFitCalc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MPSFFitCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MPSFFitCalc.h	(revision 9772)
@@ -0,0 +1,93 @@
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPSFFitCalc                                                             //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MPSFFitCalc
+#define MARS_MPSFFitCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class TSring;
+class TH1D;
+
+class MGeomCam;
+#ifndef MARS_MCameraDC
+#include "MCameraDC.h"
+#endif
+#ifndef MARS_MPSFFit
+#include "MPSFFit.h"
+#endif
+
+class MPSFFitCalc : public MTask
+{
+
+private:
+ 
+    MGeomCam  *fGeomCam;
+    MCameraDC *fCamera; 
+    MPSFFit   *fFit;
+
+    MPSFFit   fTotalMeanFit;
+    UInt_t    fNumTotalMeanFits;
+    
+    TH1D *fPedestalDCHist;
+    Float_t fPedestalDC;
+
+    TString *fVname;
+    TArrayD fVinit; 
+    TArrayD fStep; 
+    TArrayD fLimlo; 
+    TArrayD fLimup; 
+    TArrayI fFix;
+    TObject *fObjectFit;
+    TString fMethod;
+    Bool_t fNulloutput;
+
+    Float_t fMaxDC;
+    UShort_t fImgCleanMode;
+    UShort_t fNumRings;
+    Float_t fPedLevel;
+    TArrayS fBlindPixels;
+
+    void RingImgClean();
+    void RmsImgClean(Float_t pedestal);
+    void MaskImgClean(TArrayS blindpixels);
+
+    void InitFitVariables();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+
+    enum ImgCleanMode_t{kNone=0,kRing,kRms,kMask,kCombined};
+    static const ImgCleanMode_t kDefault = kRing;
+
+    MPSFFitCalc(ImgCleanMode_t imgmode=kDefault, const char *name=NULL, const char *title=NULL);
+    ~MPSFFitCalc();
+    
+    void SetImgCleanMode(ImgCleanMode_t imgmode=kDefault){ fImgCleanMode=imgmode;};
+    void SetNumRings(UShort_t numRings) {fNumRings=numRings;}
+    void SetPedLevel(Float_t pedestal) {fPedLevel=pedestal;}
+    void SetBlindPixels(TArrayS blindpixels) {fBlindPixels=blindpixels;}
+    
+
+    ClassDef(MPSFFitCalc, 0)   // Task that fits the PSF using the dc readout of the camera.
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcPlace.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcPlace.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcPlace.cc	(revision 9772)
@@ -0,0 +1,213 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Lopez    04/2004 <mailto:jlopez@ifae.es>
+!   Author(s): Javier Rico     04/2004 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPlace
+//
+// Abstract task to set the source position in any place in the camera
+// It keeps a 2D histogram with the assigned positions, so that the same
+// distribution can be applied later to any data set (tipically the OFF data)
+// Classes inheritating MSrcPlace should override the ComputeNewSrcPosition() 
+// method and probably include a call to MsrcPlace::PreProcess in their
+// PreProcess method (see, e.g., MSrcPosFromFile or MSrcRotate classes)
+//
+//  Input Containers:
+//    MSrcPosCam
+//
+//  Output Containers:
+//    MSrcPosCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <math.h>
+
+#include "TH2F.h"
+
+#include "MParList.h"
+#include "MSrcPlace.h"
+#include "MSrcPosCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSrcPlace);
+
+using namespace std;
+
+static const TString gsDefName  = "MSrcPlace";
+static const TString gsDefTitle = "Set the position of the source";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. The first argument is the name of the internal histo, 
+// the second (third) argument is the name of the input (output) container
+// containing the source position in the camera plain. 
+//
+MSrcPlace::MSrcPlace(const char* srcPosIn, const char* srcPosOut,  const char *name, const char *title)
+  : fSrcPosIn(NULL), fSrcPosOut(NULL), fHistoName("SrcPosHist"), 
+    fHistoBinPrec(1.), fHistPos(NULL)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    fSrcPosInName   = srcPosIn;
+    fSrcPosOutName  = srcPosOut;
+
+    fMode=kOn;
+    fCreateHisto=kTRUE;
+}
+// -------------------------------------------------------------------------
+//
+// Destructor
+//
+MSrcPlace::~MSrcPlace()
+{
+  if(fHistPos)
+    delete fHistPos;
+}
+
+// -------------------------------------------------------------------------
+//
+// Save the position of the source in the histogram
+//
+void MSrcPlace::SavePosIntoHisto()
+{  
+  if(fHistPos)
+    fHistPos->Fill(fSrcPosOut->GetX(),fSrcPosOut->GetY());
+}
+// -------------------------------------------------------------------------
+//
+// Read the position of the source from the histogram
+//
+void MSrcPlace::ReadPosFromHisto()
+{  
+  if(fHistPos)
+    {
+      Axis_t x;
+      Axis_t y;
+      
+      fHistPos->GetRandom2(x,y);
+      fSrcPosOut->SetXY(x,y);
+    }
+}
+// -------------------------------------------------------------------------
+//
+// Look for needed containers.
+// Check processing mode and if histogram is filled in case kOff mode
+//
+Int_t MSrcPlace::PreProcess(MParList* pList)
+{ 
+  // create (if needed and requested) internal histogram
+  if(fCreateHisto && !fHistPos)
+    {
+      const Float_t cameraSize   = 600; //[mm]
+      const UInt_t nbins =  (UInt_t)(cameraSize*2/fHistoBinPrec);
+      fHistPos = new TH2F(fHistoName,"",nbins,-cameraSize,cameraSize,nbins,-cameraSize,cameraSize);
+      fHistPos->SetDirectory(0);
+      *fLog << inf << "MSrcPlace::PreProcess Message: internal histogram " << fHistoName << " created with " << nbins << "x" << nbins << " bins" << endl;
+    }
+
+  // look for/create input MSrcPosCam
+  fSrcPosIn = (MSrcPosCam*)pList->FindObject(AddSerialNumber(fSrcPosInName), "MSrcPosCam");
+  if (!fSrcPosIn)
+    {
+      *fLog << warn << AddSerialNumber(fSrcPosInName) << " [MSrcPosCam] not found... creating default container." << endl;
+      fSrcPosIn = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam", AddSerialNumber(fSrcPosInName));
+      if(!fSrcPosIn)
+	return kFALSE;
+    }
+
+  // look for/create output MSrcPosCam
+  fSrcPosOut = (MSrcPosCam*)pList->FindObject(AddSerialNumber(fSrcPosOutName), "MSrcPosCam");
+  if (!fSrcPosOut)
+    {
+      *fLog << warn << AddSerialNumber(fSrcPosOutName) << " [MSrcPosCam] not found... creating default container." << endl;
+      fSrcPosOut = (MSrcPosCam*)pList->FindCreateObj("MSrcPosCam", AddSerialNumber(fSrcPosOutName));
+      if(!fSrcPosOut)
+	return kFALSE;
+    }
+
+  // check mode, look for a filled histogram in case kOff
+  if(fHistPos)
+    {
+      if(fMode==kOn)
+	*fLog << inf << "MSrcPlace PreProcess Message: source postions will be stored in internal histo (" << fHistPos->GetName() << ")" << endl;
+      else
+	{
+	  if(fHistPos->GetEntries())
+	    *fLog << inf << "MSrcPlace PreProcess Message: source postions will be read from internal histo (" << fHistPos->GetName() << ")" << endl;
+	  else
+	    {
+	      *fLog << err << "MSrcPlace PreProcess Error: source postions attempted to be read from empty histo (" << fHistPos->GetName() << ")" << endl;
+	      return kFALSE;
+	    }
+	}
+    }
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Call to compute a new position and then save it in the histogram (fMode==kOn) 
+// of to read the new position from the histogram (fMode==kOff)
+//
+Int_t MSrcPlace::Process()
+{  
+  switch(fMode)
+    {
+    case kOn:
+      if(!ComputeNewSrcPosition())
+	return kFALSE;
+      SavePosIntoHisto();
+      break;
+    case kOff:
+      ReadPosFromHisto();
+      break;
+    default:
+      *fLog << err << "MSrcPlace::Process Warning: Wrong mode " << fMode << endl;
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Dump 2D histo statistics
+//
+Int_t MSrcPlace::PostProcess()
+{
+  if(fMode==kOn && fHistPos)
+    {
+      *fLog << inf << endl;
+      *fLog << inf << "MSrcPlace::PostProcess Message: Created internal histogram with: " << endl;
+      *fLog << inf << "Entries: " << fHistPos->GetEntries() << endl;
+      *fLog << inf << "X projection mean: " << fHistPos->ProjectionX()->GetMean() << endl;
+      *fLog << inf << "X projection rms:  " << fHistPos->ProjectionX()->GetRMS() << endl;
+      *fLog << inf << "Y projection mean: " << fHistPos->ProjectionY()->GetMean() << endl;
+      *fLog << inf << "Y projection rms:  " << fHistPos->ProjectionY()->GetRMS() << endl;
+    }
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcPlace.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcPlace.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcPlace.h	(revision 9772)
@@ -0,0 +1,65 @@
+#ifndef MARS_MSrcPlace
+#define MARS_MSrcPlace
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MSrcPosCam;
+class TH2F;
+
+class MSrcPlace : public MTask
+{
+ public:
+  enum OnOffMode_t {kOn=0,kOff};
+  
+ private:
+  MSrcPosCam*  fSrcPosIn;       //  Pointer to the input source position container
+  MSrcPosCam*  fSrcPosOut;      //  Pointer to the output source position container
+  
+  TString      fSrcPosInName;   //  Name of the input MSrcPosCam object
+  TString      fSrcPosOutName;  //  Name of the output MSrcPosCam object
+
+  TString      fHistoName;      //  Name of internal histogram
+  Float_t      fHistoBinPrec;   //  [mm] internal histo bin size 
+
+  TH2F*        fHistPos;     //  histogram of the used source positions
+  OnOffMode_t   fMode;        //  On/Off data mode (write/read to/from the histogram)
+  Bool_t       fCreateHisto; //  flag to decide whether internal histo is created or not
+
+  void  SavePosIntoHisto();
+  void  ReadPosFromHisto();
+
+  virtual Int_t Process();
+  virtual Int_t PostProcess();
+
+ protected:
+  virtual Int_t PreProcess(MParList *plist);
+
+ public:
+  MSrcPlace(const char* srcin="MSrcPosCam",const char* srcout="MSrcPosCam", 
+	    const char* name=NULL, const char* title=NULL);
+
+  virtual ~MSrcPlace();
+
+  void SetMode(OnOffMode_t mode)            {fMode=mode;}
+  void SetInputSrcPosName(TString name)     {fSrcPosInName=name;}
+  void SetOutputSrcPosName(TString name)    {fSrcPosOutName=name;}
+  void SetInternalHistoName(TString name)   {fHistoName=name;}
+  void SetInternalHistoBinSize(Float_t size){fHistoBinPrec=size;}
+  void SetPositionHisto(TH2F* histo)     {fHistPos=histo;}
+  void SetCreateHisto(Bool_t inp=kTRUE)     {fCreateHisto=inp;}
+
+  OnOffMode_t   GetMode()              {return fMode;}
+  TH2F*         GetPositionHisto()     {return fHistPos;}
+  MSrcPosCam*   GetInputSrcPosCam()    {return fSrcPosIn;}
+  MSrcPosCam*   GetOutputSrcPosCam()   {return fSrcPosOut;}
+  TString       GetInternalHistoName() {return fHistoName;}
+  
+  virtual Int_t ComputeNewSrcPosition() {return kTRUE;}
+
+  ClassDef(MSrcPlace, 0) // task to rotate the position of the source as a function of Azimuth and Zenith angles
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromFile.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromFile.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromFile.cc	(revision 9772)
@@ -0,0 +1,227 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López  04/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosFromFile
+//
+// Task to set the position of the source as a function of run number according
+// to the positions read from an input file
+//
+//  Output Containers:
+//    MSrcPosCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+
+#include "MParList.h"
+#include "MSrcPosFromFile.h"
+
+#include "MRawRunHeader.h"
+#include "MSrcPosCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MSrcPosFromFile);
+
+using namespace std;
+
+static const TString gsDefName  = "MSrcPosFromFile";
+static const TString gsDefTitle = "Set the position of the (off axis) source according to input file";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. cardpath is the name of the input file (.pos) where the
+// source positions are stored in the format Run# x y (in mm). mode indicates whether
+// to read or to save the positions of the source in/from the internal histogram
+//
+MSrcPosFromFile::MSrcPosFromFile(TString cardpath, OnOffMode_t mode, const char *name, const char *title)
+  : fRawRunHeader(NULL), fSourcePositionFilePath(cardpath)
+{
+  fName  = name  ? name  : gsDefName.Data();
+  fTitle = title ? title : gsDefTitle.Data();
+  SetMode(mode);
+
+  fRunList=0x0;
+  fRunSrcPos=0x0;
+  fRunMap=0x0;
+
+  fLastRun  = 0;
+  fFirstRun = 0;
+  fLastValidSrcPosCam=0x0;
+
+  SetInternalHistoName(TString(fName)+"Hist");
+}
+// -------------------------------------------------------------------------
+//
+// Destructor
+//
+MSrcPosFromFile::~MSrcPosFromFile()
+{
+  if(fRunList)
+    delete [] fRunList;
+  if(fRunSrcPos)
+    delete [] fRunSrcPos;
+  if(fRunMap)
+    delete fRunMap;
+}
+
+// -------------------------------------------------------------------------
+//
+// Open and read the input file.
+Int_t MSrcPosFromFile::PreProcess(MParList *pList)
+{
+  if(GetMode()==MSrcPlace::kOn)
+    {
+      // Count the number of runs in the card with the source poistions
+      ReadSourcePositionsFile(kCount);
+      
+      if(!fRunList)
+	fRunList = new Int_t[fNumRuns];
+      if(!fRunSrcPos)
+	fRunSrcPos = new MSrcPosCam[fNumRuns];
+      if(!fRunMap)
+	fRunMap = new TExMap(fNumRuns);
+      
+      // Read card with the source poistions
+      ReadSourcePositionsFile(kRead);
+    }
+
+  if(!MSrcPlace::PreProcess(pList))
+    return kFALSE;
+  
+  fRawRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+  if (!fRawRunHeader)
+    {
+      *fLog << err << AddSerialNumber("MRawRunHeader") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// In case we enter a new run, look for the position in the read list
+// If there is no value for that run, take the previous one
+// 
+Int_t MSrcPosFromFile::ComputeNewSrcPosition()
+{
+  const UInt_t run = fRawRunHeader->GetRunNumber();
+  if(run!=fLastRun)
+    {      
+      fLastRun=run;
+      MSrcPosCam* srcpos = (MSrcPosCam*)fRunMap->GetValue(run);
+
+      *fLog << inf << "Source position for run " << run;
+
+      if(srcpos)
+	fLastValidSrcPosCam = srcpos;
+      else if(run>fFirstRun)
+	for(UInt_t irun=run-1; irun>=fFirstRun;irun--)
+	  if((srcpos=(MSrcPosCam*)fRunMap->GetValue(irun)))
+	    {
+	      *fLog << inf << " not found in file. Taking position for run "<< irun;
+	      fLastValidSrcPosCam = srcpos;
+	      break;
+	    }
+      else if(fLastValidSrcPosCam)
+	*fLog << inf << " not found in file. Taking previous position: ";
+	
+      if(!fLastValidSrcPosCam)
+	{
+	  *fLog << warn << "MSrcPosFromFile::ComputeNewSrcPosition warning: no value for the first run. Taking first found run in file, run number " << fFirstRun;
+	  fLastValidSrcPosCam = (MSrcPosCam*)fRunMap->GetValue(fFirstRun);
+	}
+
+      *fLog << inf << "\tX\t" << setprecision(3) << fLastValidSrcPosCam->GetX();
+      *fLog << inf << "\tY\t" << setprecision(3) << fLastValidSrcPosCam->GetY() << endl;      
+    }
+
+  GetOutputSrcPosCam()->SetXY(fLastValidSrcPosCam->GetX(),fLastValidSrcPosCam->GetY());
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read file with table of source positions as function of run
+// 
+Int_t MSrcPosFromFile::ReadSourcePositionsFile(UShort_t readmode)
+{
+  
+  ifstream fin(fSourcePositionFilePath);
+  if(!fin)
+    {
+      *fLog << err << "MSrcPosFromFile::ReadSourcePositionsFile. Cannot open file " << fSourcePositionFilePath << endl;
+      return kFALSE;
+    }
+  
+  UInt_t run;
+  Float_t x,y;
+  
+  fNumRuns=0;
+  
+  *fLog << dbg << "MSrcPosFromFile::ReadSourcePositionsFile(" << readmode << ')' << endl;
+  while(1)
+    {
+      fin >> run >> x >> y;
+      if(!fFirstRun) fFirstRun=run;
+      if(fin.eof())
+	break;
+      
+      switch(readmode)
+	{
+	case kCount:
+	  {
+	    
+	    *fLog << dbg << "Source position for run " << run;
+	    *fLog << dbg << "\tX\t" << x << " mm";
+	    *fLog << dbg << "\tY\t" << y << " mm" << endl;
+	    
+	    fNumRuns++;
+	    break;
+	  }
+	case kRead:
+	  {
+	    fRunList[fNumRuns] = run;
+	    fRunSrcPos[fNumRuns].SetXY(x,y);
+	    fRunMap->Add(fRunList[fNumRuns],(Long_t)&(fRunSrcPos[fNumRuns]));
+	    fNumRuns++;
+	    break;
+	  }
+	default:
+	  *fLog << err << "Read mode " << readmode << " node defined" << endl;
+	  return kFALSE;
+	}
+    }
+  
+  fin.close();
+  
+  
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromFile.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromFile.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromFile.h	(revision 9772)
@@ -0,0 +1,48 @@
+#ifndef MARS_MSrcPosFromFile
+#define MARS_MSrcPosFromFile
+
+#ifndef MARS_MSrcPlace
+#include "MSrcPlace.h"
+#endif
+
+#ifndef ROOT_TMap
+#include <TExMap.h>
+#endif
+
+class MRawRunHeader;
+class MSrcPosCam;
+
+class MSrcPosFromFile : public MSrcPlace
+{
+ private:
+
+    MRawRunHeader *fRawRunHeader;
+
+    Int_t  fNumRuns;
+    UInt_t  fFirstRun;
+    UInt_t  fLastRun;
+
+    Int_t      *fRunList;
+    MSrcPosCam *fRunSrcPos;
+    MSrcPosCam *fLastValidSrcPosCam;
+    TExMap     *fRunMap;   // list of run numbers positions
+
+    TString fSourcePositionFilePath;
+
+    virtual Int_t ReadSourcePositionsFile(UShort_t readmode);
+    virtual Int_t ComputeNewSrcPosition();
+    
+    virtual Int_t PreProcess(MParList *plist);
+    
+public:    
+    enum ReadMode_t {kCount=0,kRead};
+
+    MSrcPosFromFile(TString cardpath=0, OnOffMode_t mode=kOn, const char *name=NULL, const char *title=NULL);
+    ~MSrcPosFromFile();
+
+    void SetInputFileName(TString fname) {fSourcePositionFilePath=fname;}
+
+    ClassDef(MSrcPosFromFile, 0) // task to calculate the position of the source as a function of the run number 
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromStars.cc	(revision 9772)
@@ -0,0 +1,335 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Roger Firpo   04/2004 <mailto:jlopez@ifae.es>
+!   Author(s): Javier López  05/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosFromStars
+//
+// Task to set the position of the source using the positions of the stars
+// in the field of view of the source
+//
+//  Output Containers:
+//    MSrcPosCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+#include "MSrcPosFromStars.h"
+
+#include <TList.h>
+#include <TH2F.h>
+#include <TF2.h>
+#include <TTimer.h>
+#include <TString.h>
+#include <TCanvas.h>
+
+#include "MSrcPosCam.h"
+#include "MStarLocalCam.h"
+#include "MStarLocalPos.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MSrcPosFromStars);
+
+using namespace std;
+
+static const TString gsDefName  = "MSrcPosFromStars";
+static const TString gsDefTitle = "task to calculate the position of the source using the position of stars";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MSrcPosFromStars::MSrcPosFromStars(const char *name, const char *title)
+    : fStars(NULL)
+{
+  fName  = name  ? name  : gsDefName.Data();
+  fTitle = title ? title : gsDefTitle.Data();
+  
+  fDistances.Set(0);
+
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MSrcPosFromStars::PreProcess(MParList *pList)
+{
+
+  if(!MSrcPlace::PreProcess(pList))
+    return kFALSE;
+  
+  fStars = (MStarLocalCam*)pList->FindObject(AddSerialNumber("MStarLocalCam"));
+  if (!fStars)
+    {
+      *fLog << err << AddSerialNumber("MStarLocalCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+  
+  fNumStars = fDistances.GetSize();
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 
+static Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        cout << "Type 'q' to exit, <return> to go on: " << endl;
+        TString input;
+        input = getchar();
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+Int_t MSrcPosFromStars::ComputeNewSrcPosition()
+{
+
+  if (fNumStars == 0)
+    {
+      if (fStars->GetNumStars() > 0)
+        {
+
+          //Look for the star closer to the center of the camera
+          TIter Next(fStars->GetList());
+          MStarLocalPos* star;
+          Float_t mindist = 600; //mm
+          UInt_t starnum = 0;
+          Int_t select = -1;
+          while ((star=(MStarLocalPos*)Next())) 
+            {
+              Float_t dist = TMath::Sqrt(star->GetMeanX()*star->GetMeanX() +
+                                         star->GetMeanY()*star->GetMeanY());
+              if (dist < mindist)
+                {
+                  mindist = dist;
+                  select = starnum;
+                }
+              
+              starnum++;
+            }
+
+          if (select < 0)
+            {
+              *fLog << err << "Not found star closer to center" << endl;
+              return kFALSE;
+            }
+          
+          MStarLocalPos& selecStar = (*fStars)[select];
+
+          if (selecStar.GetChiSquareNdof() > 0. && selecStar.GetChiSquareNdof() < 10.)
+            {
+              
+              Float_t selecStarPosX = selecStar.GetMeanX();
+              Float_t selecStarPosY = selecStar.GetMeanY();
+        
+              GetOutputSrcPosCam()->SetXY(selecStarPosX,selecStarPosY);
+            }
+        }
+    }
+  else if (fStars->GetNumStars() >= fNumStars)
+    {
+      
+      Float_t diameterInnerPixel = 30; //[mm]
+      Float_t diameterOuterPixel = 60; //[mm]
+      
+      Double_t probability = 1.;
+
+      // Resolution and computing time are proportional to bins^2
+      const Int_t bins  = 200;
+      Double_t max_x_mm = 600;
+      Double_t min_x_mm = -max_x_mm;
+      Double_t max_y_mm = max_x_mm;
+      Double_t min_y_mm = -max_x_mm;
+      
+      // bins to mmrees
+      const Double_t bin2mm = 2 * max_x_mm / bins;
+      
+      // First run, to find the maximum peak and define the area
+      TH2F *hgrid = new TH2F("hgrid", "", bins, min_x_mm, max_x_mm, bins, min_y_mm, max_y_mm);
+      
+      for (Int_t ny = 1; ny <= bins; ny++)
+        for (Int_t nx = 1; nx <= bins; nx++)
+          hgrid->SetBinContent(nx, ny, 1.);
+
+      for (UInt_t numstar = 0; numstar < fNumStars; numstar++)
+        {
+          probability = 1;
+          
+          MStarLocalPos& star  = (*fStars)[numstar];
+          
+          if (star.GetChiSquareNdof() > 0. && star.GetChiSquareNdof() < 10.)
+            {
+              
+              Float_t starPosX  = star.GetMeanX();
+              Float_t starPosY  = star.GetMeanY();
+              Float_t starDist  = Dist(0.,0.,starPosX,starPosY);
+              Float_t starSigma = (starDist<350.?diameterInnerPixel:diameterOuterPixel);
+              
+//               *fLog << dbg << "Star[" << numstar << "] pos (" << starPosX << "," << starPosY << ") dist " << starDist << " size " << starSigma << endl;
+              
+              if (starSigma != 0)
+                {
+                  for (Int_t ny = 1; ny < bins + 1; ny++)
+                    {
+                      for (Int_t nx = 0; nx < bins + 1; nx++)
+                        {
+                          Float_t dist = Dist(min_x_mm + nx * bin2mm, starPosX, min_y_mm + ny * bin2mm, starPosY);
+                          Float_t prob = Prob(dist, fDistances[numstar], starSigma);
+                          
+//                           if ( prob > 0.8)
+//                             *fLog << dbg << " x " << min_x_mm + nx * bin2mm << " y " << min_y_mm + ny * bin2mm << " dist " << dist << " stardist " << fDistances[numstar] << " prob " << prob << endl;
+
+                          probability = hgrid->GetBinContent(nx, ny)*prob;
+                          hgrid->SetBinContent(nx, ny, probability);
+
+                        }
+                    }
+                }
+              else probability *= 1;
+              
+            }
+        }
+      
+      // Finding the peak
+      Double_t peak[2] = {0,0};
+      Double_t peak_value = 0;
+      
+      for (Int_t ny = 0; ny < bins + 1; ny++)
+        {
+          for (Int_t nx = 0; nx < bins + 1; nx++)
+            {
+              if (hgrid->GetBinContent(nx, ny) > peak_value)
+                {
+                  peak_value = hgrid->GetBinContent(nx, ny);
+                  peak[0] = min_x_mm + nx * bin2mm;
+                  peak[1] = min_y_mm + ny * bin2mm;
+                }
+            }
+        }
+      
+      *fLog << dbg << "The peak is at (x, y) = (" << peak[0] << ", " << peak[1] << ") mm" << endl;
+      
+      
+//       TCanvas c1;
+//       hgrid->Draw("lego");
+//       if(!HandleInput())
+//         exit(1);
+      
+      
+      // Here we define a small area surrounding the peak to avoid wasting time and resolution anywhere else
+      
+      min_x_mm = peak[0] - diameterInnerPixel;
+      max_x_mm = peak[0] + diameterInnerPixel;
+      min_y_mm = peak[1] - diameterInnerPixel;
+      max_y_mm = peak[1] + diameterInnerPixel;
+      
+      const Double_t xbin2mm = (max_x_mm - min_x_mm) / bins;
+      const Double_t ybin2mm = (max_y_mm - min_y_mm) / bins;
+      
+      // Other run centered in the peak for more precision
+      TH2F *hagrid = new TH2F("hagrid", "", bins, min_x_mm, max_x_mm, bins, min_y_mm, max_y_mm);
+
+      for (Int_t ny = 1; ny <= bins; ny++)
+        for (Int_t nx = 1; nx <= bins; nx++)
+          hagrid->SetBinContent(nx, ny, 1.);
+          
+      
+      for (UInt_t numstar = 0; numstar < fNumStars; numstar++)
+        {
+          probability = 1;
+          
+          MStarLocalPos& star  = (*fStars)[numstar];
+          
+          if (star.GetChiSquareNdof() > 0. && star.GetChiSquareNdof() < 10.)
+            {
+              
+              Float_t starPosX  = star.GetMeanX();
+              Float_t starPosY  = star.GetMeanY();
+              Float_t starDist  = Dist(0.,0.,starPosX,starPosY);
+              Float_t starSigma = (starDist<350.?diameterInnerPixel:diameterOuterPixel);
+              
+              if (starSigma != 0)
+                {
+                  for (Int_t ny = 0; ny < bins; ny++)
+                    {
+                      for (Int_t nx = 0; nx < bins; nx++)
+                        {
+                          Float_t prob = Prob(Dist(min_x_mm + nx * xbin2mm, starPosX, min_y_mm + ny * ybin2mm, starPosY), fDistances[numstar], starSigma);
+                          
+                          probability = hagrid->GetBinContent(nx, ny)*prob;
+                          hagrid->SetBinContent(nx, ny, probability);
+                        }
+                    }
+                }
+              else probability *= 1;                          
+              
+            }
+        }
+      
+      // This time we fit the histogram with a 2D gaussian
+      // Although we don't expect our function to be gaussian...
+      TF2 *gauss2d = new TF2("gauss2d","[0]*exp(-(x-[1])*(x-[1])/(2*[2]*[2]))*exp(-(y-[3])*(y-[3])/(2*[4]*[4]))", min_x_mm, max_x_mm, min_y_mm, max_y_mm);
+      
+      gauss2d->SetParName(0,"f0");
+      gauss2d->SetParName(1,"meanx");
+      gauss2d->SetParName(2,"sigmax");
+      gauss2d->SetParName(3,"meany");
+      gauss2d->SetParName(4,"sigmay");
+      
+      gauss2d->SetParameter(0,10);
+      gauss2d->SetParameter(1,peak[0]);
+      gauss2d->SetParameter(2,0.002);
+      gauss2d->SetParameter(3,peak[1]);
+      gauss2d->SetParameter(4,0.002);
+      
+      GetOutputSrcPosCam()->SetXY(gauss2d->GetParameter(1), gauss2d->GetParameter(3));
+      
+      delete hgrid;
+      delete hagrid;
+    }
+  
+
+  return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcPosFromStars.h	(revision 9772)
@@ -0,0 +1,52 @@
+#ifndef MARS_MSrcPosFromStars
+#define MARS_MSrcPosFromStars
+
+#ifndef ROOT_TArrayF
+#include "TArrayF.h"
+#endif
+
+#ifndef ROOT_TMath
+#include "TMath.h"
+#endif
+
+#ifndef MARS_MSrcPlace
+#include "MSrcPlace.h"
+#endif
+
+class MStarLocalCam;
+class MSrcPosCam;
+
+class MSrcPosFromStars : public MSrcPlace
+{
+ private:
+
+  MStarLocalCam *fStars;
+
+  UInt_t fNumStars;
+  TArrayF fDistances;
+
+  virtual Int_t ComputeNewSrcPosition();
+  virtual Int_t PreProcess(MParList *plist);
+    
+public:    
+
+  MSrcPosFromStars(const char *name=NULL, const char *title=NULL);
+
+
+// This fuction is to compute the probability using a ring distribution
+  Double_t Prob(Double_t d, Double_t dist, Double_t sigma)
+    {
+      return TMath::Exp(-(d-dist)*(d-dist)/(2*sigma*sigma));///(sigma*TMath::Sqrt(2*3.141592654));
+    }
+ 
+  Double_t Dist(Double_t x1, Double_t x2, Double_t y1, Double_t y2)
+    {
+      return TMath::Sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
+    }
+  
+  void SetDistances(TArrayF dist) { fDistances = dist; }
+  
+  ClassDef(MSrcPosFromStars, 0) // task to calculate the position of the source using the position of stars
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcRotate.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcRotate.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcRotate.cc	(revision 9772)
@@ -0,0 +1,196 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     04/2004 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcRotate
+//
+// Task to rotate the position of the source as a function of time
+//
+//  Input Containers:
+//    MSrcPosCam
+//
+//  Output Containers:
+//    MSrcPosCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <math.h>
+
+#include "MParList.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MSrcRotate.h"
+
+#include "MAstroSky2Local.h"
+#include "MObservatory.h"
+#include "MSrcPosCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSrcRotate);
+
+using namespace std;
+
+static const TString gsDefName  = "MSrcRotate";
+static const TString gsDefTitle = "Rotate position of the source";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. The first (second) argument is the name of the
+// input (output) MSrcPosCam object containing the source position in the 
+// camera plain
+//
+MSrcRotate::MSrcRotate(const char* srcPosIn, const char* srcPosOut, const char *name, const char *title)
+  : fRA(0), fDEC(0), fRefMJD(0), fRunNumber(0)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetInputSrcPosName(srcPosIn);
+    SetOutputSrcPosName(srcPosOut);
+
+    SetInternalHistoName(TString(fName)+"Hist");
+}
+
+// -------------------------------------------------------------------------
+//
+// Look for/create the needed containers
+// Check whether RA and DEC have been initialized
+//
+Int_t MSrcRotate::PreProcess(MParList *pList)
+{
+  if(!MSrcPlace::PreProcess(pList))
+    return kFALSE;
+  
+  // look for MRawRunHeader
+  fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!fRunHeader)
+    {
+      *fLog << err << "MSrcRotate::PreProcess Error: MRawRunHeader not found... aborting" << endl;
+      return kFALSE;
+    }
+  
+  // look for MRawEvtHeader
+  fEvtHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
+  if (!fEvtHeader)
+    {
+      *fLog << err << "MSrcRotate::PreProcess Error: MRawEvtHeader not found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  // look for/create the MObservatory
+  fObservatory = (MObservatory*)pList->FindCreateObj("MObservatory");
+  if(!fObservatory)
+    {
+      *fLog << err << "MSrcRotate::PreProcess Error: MObservatory not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  // check RA and DEC
+  if(fRA==0. || fDEC ==0)
+    *fLog << warn << "MSrcRotate::PreProcess Warning: RA=" << fRA << "or DEC=" << fDEC << " could be not initialized" << endl;    
+	
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Perform the rotation of the source position 
+// 
+// FIXME: for the time being, this is computed by assuming constant event rate
+//
+Int_t MSrcRotate::ComputeNewSrcPosition()
+{  
+  if(fRunHeader->GetRunNumber()!=fRunNumber)
+    {
+      fRunNumber=fRunHeader->GetRunNumber();
+      
+      // save the number of events, initial and final times
+      fNEvts    = fRunHeader->GetNumEvents();
+      fIniTime  = fRunHeader->GetRunStart();
+      fFinTime  = fRunHeader->GetRunEnd();
+      fDeltaT   = (fFinTime.GetMjd()-fIniTime.GetMjd())/fNEvts;
+      
+      if((ULong_t)TMath::Nint(fIniTime.GetMjd())!=(ULong_t)TMath::Nint(fFinTime.GetMjd()))
+	{
+	  *fLog << err << "MSrcRotate::ComputeNewSrcPosition Error: Inial and final MJDs are different ("<<fIniTime.GetMjd()<<"!="<<fFinTime.GetMjd()<<")" << endl;
+	  return kFALSE;
+	}
+      
+#ifdef DEBUG
+      cout << endl << "********************"  << endl;
+      cout << "Run number: " << fRunHeader->GetRunNumber() << endl;
+      cout << "Number of events: " << fNEvts << endl;
+      cout << "Initial MJD date: " << fIniTime.GetMjd() << endl;
+      cout << "Final MJD   date: " << fFinTime.GetMjd() << endl;
+      cout << "Delta t: " << fDeltaT << endl;
+#endif
+    }
+  
+  
+  // Compute the event time
+  // FIXME: for the time being, this is computed by assuming constant event rate
+  MTime eventTime;
+  Double_t newMJD = fIniTime.GetMjd() + (fFinTime.GetMjd()-fIniTime.GetMjd())*fEvtHeader->GetDAQEvtNumber()/fNEvts;  
+  eventTime.SetMjd(newMJD);    
+  MTime refTime;
+  refTime.SetMjd(fRefMJD);
+  
+  // de-rotate the source position
+  const MAstroSky2Local Observation(eventTime, *fObservatory);
+  const MAstroSky2Local RefObservation(refTime, *fObservatory);
+  
+#ifdef DEBUG
+  printf("Run:%d, Event:%d, iniMJD=%15.5f, finMJD=%15.5f, fDeltaT=%15.5f, newMJD=%15.5f, fRefMJD=%15.5f, rotation=%15.5f, ref=%15.5f\n",
+	 fRunHeader->GetRunNumber(),fEvtHeader->GetDAQEvtNumber(),
+	 fIniTime.GetMjd(),fFinTime.GetMjd(),fDeltaT,
+	 newMJD,fRefMJD,Observation.RotationAngle(fRA,fDEC),
+	 RefObservation.RotationAngle(fRA,fDEC));
+  //  cout << "newMJD=" << newMJD << ", fRefMJD="<<fRefMJD<<", rotation="<<Observation.RotationAngle(fRA,fDEC)<<", ref="<<RefObservation.RotationAngle(fRA,fDEC)<< endl;
+#endif
+  
+  Double_t rotationAngle = fRefMJD ? 
+    Observation.RotationAngle(fRA,fDEC)-RefObservation.RotationAngle(fRA,fDEC) :
+    Observation.RotationAngle(fRA,fDEC) ;
+  MSrcPosCam* srcposIn  = GetInputSrcPosCam();
+  MSrcPosCam* srcposOut = GetOutputSrcPosCam();
+  
+  Float_t c = TMath::Cos(rotationAngle);
+  Float_t s = TMath::Sin(rotationAngle);
+  // perform a rotation of -rotationAngle to move the source back to the "initial" position
+  Float_t newX = c*srcposIn->GetX()-s*srcposIn->GetY();
+  Float_t newY = s*srcposIn->GetX()+c*srcposIn->GetY();
+  
+#ifdef DEBUG
+  Double_t rotationAngleComp = fObservatory->RotationAngle(0.1256,2.63);
+  cout << "Event " << fEvtHeader->GetDAQEvtNumber() << endl;
+  cout << "newMJD=" << newMJD <<", rotationAngle=" << rotationAngle <<", rotationAngleComp=" << rotationAngleComp << ", oldX="<<fIniSrcPosIn.GetX()<< ", oldY="<<fIniSrcPosIn.GetY()<< ", newX="<<newX<< ", newY="<<newY << endl;
+#endif
+  
+  srcposOut->SetXY(newX,newY);
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcRotate.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcRotate.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcRotate.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MSrcRotate
+#define MARS_MSrcRotate
+
+#ifndef MARS_MSrcPlace
+#include "MSrcPlace.h"
+#endif
+
+#include "MTime.h"
+
+class MObservatory;
+class MRawEvtHeader;
+class MRawRunHeader;
+
+class MSrcRotate : public MSrcPlace
+{
+ private:
+  MRawEvtHeader* fEvtHeader;   //  Pointer to the event header
+  MRawRunHeader* fRunHeader;   //  Pointer to the run header
+  MObservatory*  fObservatory; //  Pointer to the MObservatory    
+  
+  Double_t   fRA;          //  [rad] Right ascenssion 
+  Double_t   fDEC;         //  [rad] Declination
+  Double_t   fRefMJD;      //  [MJ date] reference time for rotation
+  UInt_t     fNEvts;       //  Number of events in file
+  MTime      fIniTime;     //  Run initial time 
+  MTime      fFinTime;     //  Run final time 
+  Double_t   fDeltaT;      //  DeltaT between two events
+  UInt_t     fRunNumber;   //  Current run number
+  
+  virtual Int_t PreProcess(MParList *plist);
+  
+ public:
+  MSrcRotate(const char* srcIn="MSrcPosCam",const char* srcOut="MSrcPosCam",
+	     const char* name=NULL, const char* title=NULL);
+  
+  void SetRAandDECandRefMJD(Double_t ra, Double_t dec, Double_t ref=0) {fRA=ra;fDEC=dec;fRefMJD=ref;}
+  void SetRAandDEC(Double_t ra, Double_t dec){SetRAandDECandRefMJD(ra,dec);}
+  virtual Int_t ComputeNewSrcPosition();
+  
+  ClassDef(MSrcRotate, 0) // task to rotate the position of the source as a function of Azimuth and Zenith angles
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcTranslate.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcTranslate.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcTranslate.cc	(revision 9772)
@@ -0,0 +1,118 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Javier Rico     04/2004 <mailto:jrico@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcTranslate
+//
+// Task to translate the position of the source, starting from previous source
+// position (fTranslationIsRelative=kTRUE) or from camera center 
+// (fTranslationIsRelative=kFALSE). This task allows you to modify the position
+// of the source in an event-by-event basis
+//
+//  Input Containers:
+//    MSrcPosCam
+//
+//  Output Containers:
+//    MSrcPosCam
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <math.h>
+
+#include "MParList.h"
+
+#include "MSrcTranslate.h"
+#include "MSrcPosCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSrcTranslate);
+
+using namespace std;
+
+static const TString gsDefName  = "MSrcTranslate";
+static const TString gsDefTitle = "De-rotate position of the source";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor. The first (second) argument is the name of the
+// input (output) MSrcPosCam object containing the source position in the 
+// camera plain
+//
+MSrcTranslate::MSrcTranslate(const char* srcPosIn, const char* srcPosOut, const char *name, const char *title)
+  : fShiftX(0.), fShiftY(0.), fTranslationIsRelative(kTRUE)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    SetInputSrcPosName(srcPosIn);
+    SetOutputSrcPosName(srcPosOut);
+
+    SetInternalHistoName(TString(fName)+"Hist");
+}
+
+// -------------------------------------------------------------------------
+//
+// Look for/create the needed containers
+//
+Int_t MSrcTranslate::PreProcess(MParList *pList)
+{
+  // look for/create MSrcPosCam 
+  if(!MSrcPlace::PreProcess(pList))
+    return kFALSE;
+
+  if(fShiftX==0. && fShiftY==0.)
+    *fLog << warn << "MSrcTranslate::PreProcess Warning: Null translation" << endl;    
+
+  return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Perform the translation of the source position 
+// 
+Int_t MSrcTranslate::ComputeNewSrcPosition()
+{  
+  Double_t newX,newY;
+
+  MSrcPosCam* srcPosOut = GetOutputSrcPosCam();
+  
+  if(fTranslationIsRelative)
+    {
+      MSrcPosCam* srcPosIn  = GetInputSrcPosCam();
+      newX=srcPosIn->GetX()+fShiftX;
+      newY=srcPosIn->GetY()+fShiftY;
+    }
+  else
+    {
+      newX=fShiftX;
+      newY=fShiftY;
+    }
+
+  srcPosOut->SetXY(newX,newY);
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MSrcTranslate.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MSrcTranslate.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MSrcTranslate.h	(revision 9772)
@@ -0,0 +1,30 @@
+#ifndef MARS_MSrcTranslate
+#define MARS_MSrcTranslate
+
+#ifndef MARS_MSrcPlace
+#include "MSrcPlace.h"
+#endif
+
+class MSrcTranslate : public MSrcPlace
+{
+ private:
+  
+  Double_t fShiftX;
+  Double_t fShiftY;
+  Bool_t   fTranslationIsRelative;
+  
+  Int_t PreProcess(MParList *plist);
+
+ public:
+  MSrcTranslate(const char* srcIn="MSrcPosCam", const char* srcOut="MSrcPosCam", 
+		const char* name=NULL, const char* title=NULL);
+  
+  void SetTranslation(Double_t x=0.,Double_t y=0) {fShiftX=x,fShiftY=y;};
+  void SetRelativeTranslation(Bool_t inp=kTRUE) {fTranslationIsRelative=inp;};
+  virtual Int_t ComputeNewSrcPosition();
+
+  ClassDef(MSrcTranslate, 0) // task to set the position of the source within the camera in an event by event basis
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mifae/library/MTopology.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MTopology.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MTopology.cc	(revision 9772)
@@ -0,0 +1,129 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix   09/2004 <mailto:jflix@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTopology
+//
+// Storage Container for topology parameters:
+//
+// fDistance = SUM_(i,j) D_ij , where i,j<UsedPixels and d_ij are distances
+//                              between pixels. This characterizes topology.
+//
+// fUsed = Used Pixels after image cleaning.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MTopology.h"
+
+#include <iostream>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+using namespace std;
+ClassImp(MTopology);
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+
+MTopology::MTopology(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MTopology";
+    fTitle = title ? title : "Parameters related to Topology of images after image cleaning";
+
+    Reset();
+}
+
+void MTopology::Reset()
+{
+    fDistance = -1;
+    fUsed = -1;
+}
+
+void MTopology::Print(Option_t *opt) const
+{
+      *fLog << all << GetDescriptor() << ":" << endl;
+      *fLog << "Topology Distance [mm] = " << fDistance << ": ";
+      *fLog << "Used Pixels = " << fUsed << ": " << endl;
+
+}
+
+Int_t MTopology::Calc(const MGeomCam &geom, const MCerPhotEvt &evt)
+{
+    const Int_t Pixels = evt.GetNumPixels();
+   
+    Double_t X[Pixels];
+    Double_t Y[Pixels];
+    Int_t NPixels[Pixels];
+ 
+    if (Pixels < 3)
+    {
+	Reset();
+	return 1;
+    };
+
+    MCerPhotPix *pix = 0;
+    
+    TIter Next(evt);
+    
+    fN_Pixels = 0;
+
+    Double_t fDist = 0.;
+    
+    while ((pix=(MCerPhotPix*)Next()))
+    {
+	const MGeomPix &gpix = geom[pix->GetPixId()];
+	
+	NPixels[fN_Pixels] = pix->GetPixId();
+	X[fN_Pixels] = gpix.GetX();
+	Y[fN_Pixels] = gpix.GetY();
+	
+	fN_Pixels++;
+    };
+
+    for (int i = 0; i < fN_Pixels ; i++){
+	for (int j = 0; j < fN_Pixels ; j++){
+	    fDist += sqrt(pow(X[j]-X[i],2) + pow(Y[j]-Y[i],2));
+	};		
+    };
+
+    fDistance = (Int_t)(fDist+.5);
+
+    SetDistance(fDistance);
+    SetUsedPixels(fN_Pixels);
+
+    SetReadyToSave();
+
+    return 0;
+	    
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MTopology.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MTopology.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MTopology.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MTopology
+#define MARS_MTopology
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MGeomCam;
+class MCerPhotEvt;
+
+class MTopology : public MParContainer
+{
+private:
+
+    Int_t fDistance; // Evaluated sum of distances between 'used' pixels after image cleaning [mm]
+    Int_t fUsed;     // Number of pixels contained in an image
+
+    Int_t fN_Pixels;
+
+public:
+
+    MTopology(const char *name=NULL, const char *title=NULL);
+
+    void Reset();
+
+    Int_t Calc(const MGeomCam &geom, const MCerPhotEvt &evt);
+    
+    void Print(Option_t *opt=NULL) const;
+    
+    Int_t GetDistance()             { return fDistance; } 
+    Int_t GetUsedPixels()           { return fUsed; }
+
+    void SetDistance(Int_t Dist)    { fDistance=Dist; } 
+    void SetUsedPixels(Int_t Used)  { fUsed=Used; }
+
+    ClassDef(MTopology, 1) // Container to hold Topology related parameters
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/MTopologyCalc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MTopologyCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MTopologyCalc.cc	(revision 9772)
@@ -0,0 +1,133 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Josep Flix   09/2004 <mailto:jflix@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTopologyCalc
+//
+// Taks that evaluates the Topological Parameters of images after image cleaning
+//
+// fDistance = SUM_(i,j) D_ij , where i,j<UsedPixels and d_ij are distances
+//                              between pixels. This characterizes topology.
+//
+// fUsed = Used Pixels after image cleaning.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MTopologyCalc.h"
+
+#include "MParList.h"
+
+#include "MTopology.h"
+
+#include "MCerPhotEvt.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTopologyCalc);
+
+using namespace std;
+
+static const TString gsDefName  = "MTopologyCalc";
+static const TString gsDefTitle = "Calculate Topology related parameters";
+
+// -------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MTopologyCalc::MTopologyCalc(const char *name, const char *title)
+    : fTopology(NULL)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MTopologyCalc::PreProcess(MParList *pList)
+{
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+    if (!fCerPhotEvt)
+    {
+        *fLog << err << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << err << dbginf << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTopology = (MTopology*)pList->FindCreateObj("MTopology");
+    if (!fTopology)
+        return kFALSE;
+ 
+    return kTRUE;
+
+}
+
+// -------------------------------------------------------------------------
+//
+Int_t MTopologyCalc::Process()
+{
+
+    Int_t rc = fTopology->Calc(*fGeomCam, *fCerPhotEvt);
+    
+    if (rc == 1)
+	fErrors++;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Topology calculation. The percentage
+//  is calculated with respect to the number of executions of this task.
+//
+Int_t MTopologyCalc::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << fErrors << " (" << (int)(fErrors*100/GetNumExecutions()) 
+	  << "%) Evts skipped due to UsedPixels == -1" << endl;
+    *fLog << endl;
+
+    /*
+    delete fHillas;
+    delete fHillasSrc;
+    delete fSrcPos;
+    delete fTopology;
+    */
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/library/MTopologyCalc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/MTopologyCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/MTopologyCalc.h	(revision 9772)
@@ -0,0 +1,34 @@
+#ifndef MARS_MTopologyCalc
+#define MARS_MTopologyCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MCerPhotEvt;
+class MTopology;
+
+class MTopologyCalc : public MTask
+{
+private:
+
+    const MGeomCam     *fGeomCam;
+    const MCerPhotEvt  *fCerPhotEvt;
+
+    MTopology      *fTopology;
+
+    Int_t       fErrors;
+   
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+
+    MTopologyCalc(const char *name=NULL, const char *title=NULL);
+    
+    ClassDef(MTopologyCalc, 0) // task to calculate....
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mifae/library/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/library/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/library/Makefile	(revision 9772)
@@ -0,0 +1,96 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS IFAE library
+#
+##################################################################
+# @maintitle
+
+# @code
+
+#
+#  please change all system depend values in the 
+#  config.mk.${OSTYPE} file 
+#
+#
+include ../../../Makefile.conf.$(OSTYPE)
+include ../../../Makefile.conf.general
+
+#
+CINT     = IFAE
+#
+
+SOLIB    = ../../../libmars.so
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../../../mbase \
+	   -I../../../mjobs \
+	   -I../../../mpedestal \
+	   -I../../../mbadpixels \
+	   -I../../../mfileio \
+           -I../../../mraw \
+           -I../../../manalysis \
+	   -I../../../mgui \
+	   -I../../../mgeom \
+	   -I../../../msignal \
+	   -I../../../mcalib \
+	   -I../../../mfilter \
+	   -I../../../mhbase \
+	   -I../../../mimage \
+	   -I../../../mpointing \
+	   -I../../../mcamera \
+	   -I../../../mastro \
+	   -I../../../mhist \
+	   -I../../../mfbase \
+	   -I../../../mmc \
+	   -I../../../mdata \
+	   -I../../
+
+
+SRCFILES = \
+	MDisplay.cc \
+	MHillasDisplay.cc \
+        MPSFFit.cc \
+        MPSFFitCalc.cc \
+	MSrcPlace.cc \
+        MSrcPosFromFile.cc \
+	MSrcRotate.cc \
+	MSrcTranslate.cc \
+        MIslands.cc \
+	MImgIsland.cc \
+        MIslandsCalc.cc \
+        MIslandsClean.cc \
+        MFHVNotNominal.cc \
+        MCalibrateDC.cc \
+        MHPSFFromStars.cc \
+	MControlPlots.cc \
+        MSrcPosFromStars.cc \
+        MLiveTime.cc \
+        MLiveTimeCalc.cc \
+	MTopology.cc \
+	MTopologyCalc.cc \
+	MImageParDisp.cc \
+	MDispParameters.cc \
+	MDispCalc.cc \
+	MHDisp.cc \
+	MFDisp.cc \
+	MFindDisp.cc \
+	MEffAreaAndCoeffCalc.cc \
+	MGainFluctuationPix.cc \
+	MGainFluctuationCam.cc \
+	MAddGainFluctuation.cc
+
+
+############################################################
+
+all: $(OBJS)
+
+include ../../../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper: clean rmbak
+
+# @endcode
Index: /tags/Mars-V0.9/mtemp/mifae/macros/DispSkymap.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/DispSkymap.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/DispSkymap.C	(revision 9772)
@@ -0,0 +1,223 @@
+//************************************************************************
+//
+// Authors : Eva Domingo,     1/2005 <mailto:domingo@ifae.es>
+//
+//
+// Macro for generating DISP Skymap of the FoV
+// -------------------------------------------
+//
+//************************************************************************
+
+void DispSkymap(TString onfilename  = "ONhillasfile.root",
+		TString offfilename = "OFFhillasfile.root",
+		TString outfilename = "skymaps.root",
+		Float_t HadronnessCut = 0.06, 
+		Float_t SizeCut = 1000.)
+{
+  //======================================================================
+  // Make Disp plots
+  //======================================================================
+  
+  gLog << "-----------------------------------------------------" << endl; 
+  gLog << "Make Disp related plots" << endl;
+  gLog << "-----------------------------------------------------" << endl; 
+  
+  // Input root file/s storing the computed Hillas and Disp parameters
+  gLog << "Input ON file/s: "  <<  onfilename  << endl;
+  gLog << "Input OFF file/s: " <<  offfilename << endl;
+  
+
+  //----------------------------------------------------
+  MTaskList tliston;
+  MParList  pliston;
+
+  MTaskList tlistoff;
+  MParList  plistoff;
+  
+  // MReadMarsFile readon("Events", onfilename);
+  MReadTree readon("Parameters", onfilename);
+  readon.DisableAutoScheme();
+
+  // MReadMarsFile readoff("Events", offfilename);
+  MReadTree readoff("Parameters", offfilename);
+  readoff.DisableAutoScheme();
+  
+  MGeomCamMagic geomcam;
+
+  // set cuts to select an event sample to apply Disp
+  MFDisp *fdisp = NULL;
+  //      fdisp = new MFDisp;
+  //      fdisp->SetCuts(0,1,7,600,0,600,0.,3000000.,0.,0.,0.,0.,0.,0.);
+  //      MContinue contdisp(fdisp);
+
+  // Hadroness cut
+  TString hadrcut = "MHadronness.fHadronness<";
+  hadrcut += HadronnessCut;
+  gLog << "Hadronness Cut applied = " << hadrcut << endl;
+  MF hadrfilter(hadrcut);  
+  MContinue conthadr(&hadrfilter);
+  conthadr.SetInverted(kTRUE);
+
+  // Size cut
+  TString sizecut = "MHillas.fSize>";
+  sizecut += SizeCut;
+  gLog << "Size Cut applied = " << sizecut << endl;
+  MF sizefilter(sizecut);  
+  MContinue contsize(&sizefilter);
+  contsize.SetInverted(kTRUE);
+
+  // make Disp plots
+  // SelectedPos = 1  means choose the right source position
+  //               2                   wrong
+  //               3               the position according to M3Long
+  //               4               the position according to Asym
+  MHDisp hdispon;
+  hdispon.SetName("MHDispAsymOn");
+  hdispon.SetSelectedPos(4);
+  MFillH filldispon("MHDispAsymOn[MHDisp]", "");
+
+  MHDisp hdispoff;
+  hdispoff.SetName("MHDispAsymOff");
+  hdispoff.SetSelectedPos(4);
+  MFillH filldispoff("MHDispAsymOff[MHDisp]", "");
+  
+  
+  //*****************************
+  // entries in MParList On
+  pliston.AddToList(&tliston);
+  pliston.AddToList(&geomcam);
+  pliston.AddToList(&hdispon);
+
+  // entries in MParList Off
+  plistoff.AddToList(&tlistoff);
+  plistoff.AddToList(&geomcam);
+  plistoff.AddToList(&hdispoff);
+
+  
+  //*****************************
+  // entries in MTaskList On
+  tliston.AddToList(&readon);
+  if (fdisp != NULL)
+    tliston.AddToList(&contdisp);
+  tliston.AddToList(&conthadr);
+  tliston.AddToList(&contsize);
+  tliston.AddToList(&filldispon);
+
+  // entries in MTaskList Off
+  tlistoff.AddToList(&readoff);
+  if (fdisp != NULL)
+    tlist.AddToList(&contdisp);
+  tlistoff.AddToList(&conthadr);
+  tlistoff.AddToList(&contsize);
+  tlistoff.AddToList(&filldispoff);
+  
+  //*****************************
+  
+  //-------------------------------------------
+  // Execute event loop On
+  MProgressBar barOn;
+  MEvtLoop evtloopOn;
+  evtloopOn.SetParList(&pliston);
+  evtloopOn.SetProgressBar(&barOn);
+  
+  Int_t maxeventsOn = -1;
+  if ( !evtloopOn.Eventloop(maxeventsOn) )
+    return;
+  
+  tliston.PrintStatistics(0, kTRUE);
+
+  //-------------------------------------------
+  // Execute event loop Off
+  MProgressBar barOff;
+  MEvtLoop evtloopOff;
+  evtloopOff.SetParList(&plistoff);
+  evtloopOff.SetProgressBar(&barOff);
+  
+  Int_t maxeventsOff = -1;
+  if ( !evtloopOff.Eventloop(maxeventsOff) )
+    return;
+  
+  tlistoff.PrintStatistics(0, kTRUE);
+  
+
+  //-------------------------------------------
+  // Get the skymaps
+  TH2F *skymapOn  = hdispon.GetSkymapXY();
+  skymapOn->SetName("fSkymapXYOn");
+  skymapOn->SetTitle("ON DATA: Disp estimated source positions Skymap");
+  skymapOn->SetTitleOffset(1.2,"Y");
+  TH2F *skymapOff = hdispoff.GetSkymapXY();
+  skymapOff->SetName("fSkymapXYOff");
+  skymapOff->SetTitle("OFF DATA: Disp estimated source positions Skymap");
+  skymapOff->SetTitleOffset(1.2,"Y");
+
+  // Normalize to the number of events and subtract Off to On skymap
+  Double_t onentries  = skymapOn->GetEntries();
+  Double_t offentries = skymapOff->GetEntries();
+  Double_t norm = onentries/offentries;
+  cout << "Number of ON events after cuts = "  << onentries  << endl;
+  cout << "Number of OFF events after cuts = " << offentries << endl;
+  cout << "Normalization factor = " << norm << endl;
+
+  TH2F *skymap = new TH2F("fSkymapXY", 
+         "ON-OFF: Disp estimated source positions Skymap", 71, -2., 2., 71, -2., 2.);
+  skymap->Add(skymapOn,skymapOff,1.,-norm);
+  skymap->SetTitleOffset(1.2,"Y");
+  
+  //-------------------------------------------
+  // Display the skymaps
+  gLog << endl;
+  gLog << "Drawing DISP Skymaps for the FoV ...... "   << endl;
+  gLog << "(srcpos solution selected according Asym sign)" << endl; 
+
+  gStyle->SetPalette(1);
+  gStyle->SetOptStat(11);
+
+  TCanvas *c = new TCanvas("c","Disp Skymaps",0,0,900,900);    
+  c->SetBorderMode(0);
+  c->Divide(2,2);
+
+  c->cd(1);
+  gPad->SetBorderMode(0);
+  skymapOn->DrawClone("COLZ");
+  skymapOn->SetBit(kCanDelete);
+  gPad->Modified();
+
+  c->cd(2);
+  gPad->SetBorderMode(0);
+  skymapOff->DrawClone("COLZ");
+  skymapOff->SetBit(kCanDelete);
+  gPad->Modified();
+
+  c->cd(3);
+  gPad->SetBorderMode(0);
+  skymap->DrawClone("COLZ");
+  skymap->SetBit(kCanDelete);
+  gPad->Modified();
+
+  //-------------------------------------------
+  // Save the skymaps in a .root file
+  TFile outfile(outfilename,"RECREATE");
+  skymapOn->Write();
+  skymapOff->Write();
+  skymap->Write();
+  outfile.Close();
+  gLog << endl << "Skymaps stored in file: " << outfilename <<endl;
+
+  //-------------------------------------------
+  gLog << endl << "Disp plots were made for files: " << endl;
+  gLog << "ON data:  " << onfilename  << endl; 
+  gLog << "OFF data: " << offfilename << endl; 
+  gLog << "-----------------------------------------------------" << endl; 
+
+}
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/OptimizeDisp.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/OptimizeDisp.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/OptimizeDisp.C	(revision 9772)
@@ -0,0 +1,555 @@
+//************************************************************************
+//
+// Authors : Eva Domingo,     12/2004 <mailto:domingo@ifae.es>
+//           Wolfgang Wittek, 12/2004 <mailto:wittek@mpppmu.mpg.de>
+//
+//
+// Macro for estimating the DISP parameter
+// ---------------------------------------
+//
+// DISP is the distance between the center of gravity of the shower image
+//      and the estimated source position, assumed to lie on the major 
+//      axis of the shower
+//
+// In order to get an estimate of DISP 
+// - one assumes a parametrization DISP = f(p[0],p[1],p[2],... ; s1,s2,s3,...)
+//           where s1,s2,s3,... are measurable quantities like
+//                              image parameters, (theta, phi), etc.
+//           and p[0],p[1],p[2], ... are free parameters
+//
+// - and determines the free parameters p[0],p[1],p[2]... from MC gamma data 
+//   by minimizing a parameter which measures the deviation of the estimated
+//   source position (using DISP) and the true source position
+//
+// The following classes are used :
+//
+// MDispParameters  container holding the parameters p[0],p[1],p[2],...
+//
+// MDispCalc        task calculating DISP with the parameters stored in 
+//                  MDispParameters
+//
+//   ::Calc         member function where the DISP parameterization is 
+//                  defined. It calculates DISP for a given event;
+//                  it is called by MDispCalc::Process()      
+//
+// MFindDisp        class with several functions :
+//
+//  ::DefineTrainMatrix     \  member functions which generate the training
+//  ::DefineTestMatrix       | and test samples (in the form of matrices)
+//  ::DefineTrainTestMatrix /  from the MC gamma data
+//
+//  ::FindParams    member function steering the minimization
+//                  (definition of the fcn function for Minuit, setting up the 
+//                  event loop to be executed in each minimization step,
+//                  call to Minuit);
+//                  for the minimization the training matrices are used
+//
+//  ::TestParams    member function testing the quality of the DISP estimate;
+//                  for the test the test matrices are used
+//
+// MHDisp           container for histograms which are useful for judging
+//                  the quality of the DISP estimate
+//                  Also task calculating the Minimization parameter
+//                  contribution of an event (in Fill()) 
+//                  and computing the final Minimization parameter of the 
+//                  whole event sample (in Finalize())
+//
+// MFDisp           filter to select sample for the optimization     
+//
+// 
+// The classes are stored in the CVS directory Mars/mtemp/mifae/library
+//                                   and       Mars/mtemp/mifae/macros
+//
+//
+//************************************************************************
+
+void OptimizeDisp()
+{
+    //************************************************************************
+
+    Bool_t CMatrix     = kFALSE;  // Create training and test matrices 
+    Bool_t WOptimize   = kFALSE;  // Do optimization using the training sample
+                                  // and write Disp parameter values 
+                                  // onto the file parDispfile
+                                  // Optimize Disp with :
+                        //TString typeOpt = "Data";
+                        TString typeOpt = "MC";
+    Bool_t RTest       = kFALSE;  // Test the quality of the Disp estimate
+                                  // using the test matrix
+    Bool_t WDisp       = kTRUE;  // Make Disp plots for the data of type :
+                        //TString typeInput = "ON";
+                        //TString typeInput = "OFF";
+                        TString typeInput = "MC";
+
+    //************************************************************************
+
+    gLog.SetNoColors();
+
+    if (gRandom)
+      delete gRandom;
+    gRandom = new TRandom3(0);
+    
+    //-----------------------------------------------
+    //names of files to be read for generating the training and test matrices
+    const char *filetrain  = "...";
+    const char *filetest   = "...";
+    
+    //-----------------------------------------------
+    // path for input for Mars
+    TString inPathON  = 
+      "/home/pcmagic14/wittek/CalibData/CrabLow42/2004_10_16/";
+    TString inPathOFF = 
+      "/home/pcmagic14/wittek/CalibData/CrabLow42/2004_10_17/";
+    TString inPathMC  = 
+    //"/discpepe/root_0.73mirror/wuerzburg/";
+    "~domingo/MAGIC/Disp05/";
+    
+    // path for output from Mars
+    TString outPath = "~domingo/MAGIC/Disp05/DispOptimization/";
+    
+    //-----------------------------------------------
+    // names of files for which Disp plots should be made
+    const char *offfile  = "*OffCrabLow42*";
+    const char *onfile   = "*CrabLowEn42*";
+    const char *mcfile   = "All_gammas0.73wuerzburg_zbin0to12_cleaned_3020_PeakSearch6_RunHeaders";
+    //-----------------------------------------------
+    
+    
+    //---------------------------------------------------------------------
+    gLog << "=====================================================" << endl;
+    gLog << "Macro OptimizeDisp : Start " << endl;
+    
+    gLog << "" << endl;
+    gLog << "Macro OptimizeDisp : CMatrix, WOptimize, RTest, WDisp = "
+         << (CMatrix    ? "kTRUE" : "kFALSE")  << ",  "
+         << (WOptimize  ? "kTRUE" : "kFALSE")  << ",  "
+         << (RTest      ? "kTRUE" : "kFALSE")  << ",  "
+         << (WDisp      ? "kTRUE" : "kFALSE")  << endl;
+    
+
+    //--------------------------------------------
+    // files to contain the matrices (generated from filenameTrain and
+    //                                               filenameTest)
+    // 
+    // for the training
+    TString fileMatrixTrain = outPath;
+    fileMatrixTrain += "MatrixTrainDisp";
+    fileMatrixTrain += ".root";
+    gLog << "" << endl;
+    gLog << "Files containing the Training and Test matrices :" << endl;
+    gLog << "      fileMatrixTrain = " << fileMatrixTrain << endl; 
+    
+    // for testing
+    TString fileMatrixTest = outPath;
+    fileMatrixTest += "MatrixTestDisp";
+    fileMatrixTest += ".root";
+    gLog << "      fileMatrixTest = " << fileMatrixTest << endl; 
+    gLog << "" << endl;
+    
+
+    //---------------
+    // file to contain the optimum Disp parameter values  
+    TString parDispFile = outPath;
+    //    parDispFile += "parDispMC.root";
+    parDispFile += "parDispMC_withcuts.root";
+
+    gLog << "" << endl;
+    gLog << "File containing the optimum Disp parameter values : parDispFile = " 
+         << parDispFile << endl;
+
+
+    // Set the filter cuts to select a sample of events for the Disp optimization
+    //    (islandsmin,islandsmax,usedpixelsmin,usedpixelsmax,corepixelsmin,
+    //     corepixelsmax,sizemin,sizemax,leakage1min,leakage1max,leakage2min,
+    //     leakage2max,lengthmin,widthmin);
+    MFDisp *fdisp = NULL;
+    fdisp = new MFDisp;
+    fdisp->SetCuts(0,2,7,600,0,600,0.,3000.,0.,0.,0.,0.,0.,0.);
+    fdisp->SetName("FilterSelector2");
+
+
+    // Create the MFindDisp object and set the file to store optimium Disp parameters
+    MFindDisp finddisp(fdisp);
+    finddisp.SetFilenameParam(parDispFile);
+
+
+    
+    //======================================================================
+    // Create matrices and write them onto files 
+    //======================================================================
+    
+    if (CMatrix)
+    {
+      gLog << "-----------------------------------------------------" << endl; 
+      gLog << "Generate the training and test samples" << endl;
+      
+      //--------------------------------------------
+      // files to be read for optimizing the Disp parameters
+      // 
+      // for the training
+      TString filenameTrain = inPathMC;
+      filenameTrain += mcfile;
+      filenameTrain += ".root";
+      Int_t howManyTrain = 30000;
+      gLog << "filenameTrain = " << filenameTrain << ",   howManyTrain = "
+	   << howManyTrain  << endl; 
+      
+      // for testing
+      TString filenameTest = inPathMC;
+      filenameTest += mcfile;
+      filenameTest += ".root";
+      Int_t howManyTest = 30000;
+      gLog << "filenameTest = " << filenameTest << ",   howManyTest = "
+	   << howManyTest  << endl; 
+      
+      
+      //--------------------------------------------      
+      // For the events in the matrices define requested distribution
+      // in some quantities; this may be a 1-dim, 2-dim or 3-dim distribution
+      
+      /*
+      // Define the cos(theta) distribution
+      TString mname("costheta");
+      MBinning bincost("Binning"+mname);
+      bincost.SetEdges(10, 0., 1.0);
+      
+      //MH3 mh3("cos((MPointingPos.fZd)/kRad2Deg)");
+      MH3 mh3("cos(MMcEvt.fTelescopeTheta)");
+      mh3.SetName(mname);
+      MH::SetBinning(&mh3.GetHist(), &bincost);
+      
+      for (Int_t i=1; i<=mh3.GetNbins(); i++)
+	mh3.GetHist().SetBinContent(i, 1.0);
+      */
+
+      // Define the log10(Etrue) distribution
+      TString mh3name("log10Etrue");
+      MBinning binslogE("Binning"+mh3name);
+      binslogE.SetEdges(50, 1., 3.);
+      
+      MH3 mh3("log10(MMcEvt.fEnergy)");
+      mh3.SetName(mh3name);
+      MH::SetBinning(&mh3.GetHist(), &binslogE);
+      
+      // Flat energy distribution 
+      //      for (Int_t i=1; i<=mh3.GetNbins(); i++)
+      //      	mh3.GetHist().SetBinContent(i, 1.0);
+      
+      // Power law energy distribution
+      //      for (Int_t i=1; i<=mh3.GetNbins(); i++)
+      //      {
+      //        Double_t weight = pow((Double_t)i, -1.7);
+      //        mh3.GetHist().SetBinContent(i, weight);
+      //      }      
+
+      /* 
+      // define the 'cos(Theta) vs. log10(Etrue)' distribution
+      TString mh3name("cosThetaVslog10Etrue");
+      MBinning binslogE("Binning"+mh3name+"X");
+      binslogE.SetEdges(18, 1.5, 2.2);
+      MBinning binscost("Binning"+mh3name+"Y");
+      binscost.SetEdges(10, 0., 1.0);
+      
+      //    MH3 mh3("log10(MMcEvt.fEnergy)", "cos((MPointingPos.fZd)/kRad2Deg)");
+      MH3 mh3("log10(MMcEvt.fEnergy)", "cos(MMcEvt.fTelescopeTheta)");
+      mh3.SetName(mh3name);
+      MH::SetBinning((TH2*)&mh3.GetHist(), &binslogE, &binscost);
+      
+      for (Int_t i=1; i<=((TH2*)mh3.GetHist()).GetNbinsX(); i++)
+      {
+	//	Double_t weight = pow((Double_t)i, -1.7);
+	for (Int_t j=1; j<=((TH2*)mh3.GetHist()).GetNbinsY(); j++)
+	{
+	  //	  mh3.GetHist().SetBinContent(i, j, weight);
+	  mh3.GetHist().SetBinContent(i, j, 1.);
+	}
+      }
+      */
+      
+      //--------------------------
+      // Training and test samples are generated from the same input files
+      if (filenameTrain == filenameTest)
+      {
+        if ( !finddisp.DefineTrainTestMatrix(
+                              filenameTrain,   mh3, 
+                              howManyTrain,    howManyTest,  
+                              fileMatrixTrain, fileMatrixTest, 0)     )
+	{
+	  *fLog << "OptimizeDisp.C : DefineTrainTestMatrix failed" << endl;
+          return;
+        }	
+      }
+      
+      //--------------------------
+      // Training and test samples are generated from different input files
+      else
+      {
+        if ( !finddisp.DefineTrainMatrix(filenameTrain, mh3,
+					 howManyTrain,  fileMatrixTrain, 0) )
+        {
+          *fLog << "OptimizeDisp.C : DefineTrainMatrix failed" << endl;
+          return;
+        }
+
+	if ( !finddisp.DefineTestMatrix( filenameTest, mh3, 
+					 howManyTest,  fileMatrixTest, 0)  )
+	{
+          *fLog << "OptimizeDisp.C : DefineTestMatrix failed" << endl;
+          return;
+        }
+      }
+
+      gLog << "Generation of training and test samples finished" << endl;
+      gLog << "-----------------------------------------------------" << endl; 
+    }
+    
+    
+
+    //======================================================================
+    // Optimize Disp parameters using the training sample
+    // 
+    // the initial values of the parameters are taken 
+    //     - from the file parDispInit (if != "")
+    //     - or from the arrays params and steps (if their sizes are != 0)
+    //     - or from the MDispParameters constructor
+    //======================================================================
+    
+    if (WOptimize)
+    {
+      gLog << "-----------------------------------------------------" << endl; 
+      gLog << "Optimize the Disp parameters over a " 
+	   << typeOpt << " sample, using the training matrices" << endl;
+      
+      // Read training matrices from file
+      finddisp.ReadMatrix(fileMatrixTrain, fileMatrixTest);
+
+      //--------------------------------------------
+      // file which contains the initial values for the Disp parameters; 
+      // if parDispInit ="" 
+      //    - the initial values are taken from the arrays params and steps
+      //      if their sizes are different from 0
+      //    - otherwise they are taken from the MDispParameters constructor
+      
+      TString parDispInit = outPath;
+      //parDispInit += "parDispInit.root";
+      parDispInit = "";
+      
+      //--------------------------------------------
+      
+      TArrayD params(0);
+      TArrayD steps(0);
+      
+      if (parDispInit == "")
+      {
+	Double_t vparams[5] = {
+	// p[0],     p[1],     p[2],     p[3],     p[4],     p[5]
+	   1.0,      0.6,     -0.8,     -0.8,     -1.2/*,      0.5*/};
+	// 0.5,      0.,       0.03,     0.,       0./*,       0.5*/};
+	// 0.8,      0.,       0.,       0.,       0./*,       0.5*/};
+	
+	Double_t vsteps[5] = {
+	// dp[0],    dp[1],    dp[2],    dp[3],    dp[4],    dp[5]
+	   0.01,     0.005,    0.005,    0.005,    0.01/*,    0.001*/};
+	// 0.01,     0.01,     0.01,     0.01,     0.01/*,     0.001*/};
+	// 0.01,     0.01,     0.01,     0.01,     0.01/*,     0.001*/};
+
+	params.Set(5, vparams);
+	steps.Set (5, vsteps );
+      }
+
+      
+      Bool_t rf;
+      rf = finddisp.FindParams(parDispInit, params, steps);
+      
+      if (!rf) 
+      {
+	gLog << "OptimizeDisp.C : optimization of the Disp parameters failed" << endl;
+	return;
+      }
+      
+      gLog << "Optimization of Disp parameters finished" << endl;
+      gLog << "-----------------------------------------------------" << endl; 
+    }
+
+
+
+    //======================================================================
+    // Test the Disp parameters on the test sample
+    //======================================================================
+    
+    if (RTest)
+    {
+      // Read test matrices from file
+      finddisp.ReadMatrix(fileMatrixTrain, fileMatrixTest);
+      
+      gLog << "-----------------------------------------------------" << endl; 
+      gLog << "Test the Disp parameters using the test matrices" << endl;
+      Bool_t rt = finddisp.TestParams();
+      if (!rt) 
+      {
+	gLog << "Test of the Disp parameters on the test matrices failed" 
+	     << endl;
+      }
+      gLog << "Test of the Disp parameters finished" << endl;
+      gLog << "-----------------------------------------------------" << endl; 
+    }
+    
+    
+
+
+    //======================================================================
+    // Make Disp plots
+    //======================================================================
+
+    if (WDisp)
+    {
+      gLog << "" << endl;
+      gLog << "-----------------------------------------------------" << endl; 
+      gLog << "Make plots for Disp for data of the type " << typeInput << endl;
+      
+      //--------------------------------------------
+      // type of data to be read (ON, OFF or MC)
+      if (typeInput == "ON")
+	TString file(onfile);
+      else if (typeInput == "OFF")
+	TString file(offfile);
+      else if (typeInput == "MC")
+	TString file(mcfile);
+      
+      // name of input root file
+      TString filenameData = inPathMC;
+      filenameData += mcfile;
+      filenameData += ".root";
+      gLog << "Input file '" <<  filenameData << endl;
+      
+      //----------------------------------------------------
+      // read in optimum Disp parameter values 
+      
+      TFile inparam(parDispFile);
+      MDispParameters dispin;
+      dispin.Read("MDispParameters");
+      inparam.Close();
+      
+      gLog << "Disp parameter values were read in from file '"
+	   << parDispFile << "'" << endl;
+      
+      TArrayD dispPar;
+      dispPar =  dispin.GetParameters();
+      
+      TArrayD dispStep;
+      dispStep =  dispin.GetStepsizes();
+      
+      gLog << "optimum parameter values for calculating Disp : " << endl;
+      for (Int_t i=0; i<dispPar.GetSize(); i++)
+      {
+	gLog << dispPar[i] << ",  ";
+      }
+      gLog << endl;
+      
+      
+      //----------------------------------------------------
+      MTaskList tliston;
+      MParList  pliston;
+      
+      MReadMarsFile read("Events", filenameData);
+      read.DisableAutoScheme();
+      
+      // set cuts to select an event sample to apply Disp
+      MContinue contdisp(fdisp);
+      
+      // calculate Disp
+      MDispCalc dispcalc;
+      
+      // make Disp plots
+      // SelectedPos = 1  means choose the right source position
+      //               2                   wrong
+      //               3               the position according to M3Long
+      //               4               the position according to Asym
+      MHDisp hdisp1;
+      hdisp1.SetName("MHDispCorr");
+      hdisp1.SetSelectedPos(1);
+      MFillH filldisp1("MHDispCorr[MHDisp]", "");
+      
+      MHDisp hdisp2;
+      hdisp2.SetName("MHDispWrong");
+      hdisp2.SetSelectedPos(2);
+      MFillH filldisp2("MHDispWrong[MHDisp]", "");
+      
+      MHDisp hdisp3;
+      hdisp3.SetName("MHDispM3Long");
+      hdisp3.SetSelectedPos(3);
+      MFillH filldisp3("MHDispM3Long[MHDisp]", "");
+      
+      MHDisp hdisp4;
+      hdisp4.SetName("MHDispAsym");
+      hdisp4.SetSelectedPos(4);
+      MFillH filldisp4("MHDispAsym[MHDisp]", "");
+      
+      
+      //*****************************
+      // entries in MParList
+
+      pliston.AddToList(&tliston);
+      pliston.AddToList(&dispin);
+      pliston.AddToList(&hdisp1);
+      pliston.AddToList(&hdisp2);
+      pliston.AddToList(&hdisp3);
+      pliston.AddToList(&hdisp4);
+      
+      //*****************************
+      // entries in MTaskList
+    
+      tliston.AddToList(&read);
+      if (fdisp != NULL)
+	tliston.AddToList(&contdisp);
+      tliston.AddToList(&dispcalc);
+      tliston.AddToList(&filldisp1);
+      tliston.AddToList(&filldisp2);
+      tliston.AddToList(&filldisp3);
+      tliston.AddToList(&filldisp4);
+      
+      //*****************************
+      
+      //-------------------------------------------
+      // Execute event loop
+      //
+      MProgressBar bar;
+      MEvtLoop evtloop;
+      evtloop.SetParList(&pliston);
+      evtloop.SetProgressBar(&bar);
+      
+      Int_t maxevents = -1;
+      if ( !evtloop.Eventloop(maxevents) )
+        return;
+      
+      tliston.PrintStatistics(0, kTRUE);
+      
+      //-------------------------------------------
+      // Display the histograms
+      //
+      hdisp1.Draw();
+      hdisp2.Draw();
+      hdisp3.Draw();
+      hdisp4.Draw();
+      
+      //-------------------------------------------
+      
+      gLog << "Disp plots were made for file '" << filenameData << endl; 
+      gLog << "-----------------------------------------------------" << endl; 
+    }
+    
+    delete fdisp;
+    
+    gLog << "Macro OptimizeDisp.C : End " << endl;
+    gLog << "=======================================================" << endl;
+    
+}
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/alpha.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/alpha.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/alpha.C	(revision 9772)
@@ -0,0 +1,175 @@
+/* ======================================================================== *\!
+!   Author(s): Oscar Blanch & Javier Rico
+\* ======================================================================== */
+
+void alpha(
+    Float_t cutsize=2000,
+    Float_t upcutsize=9999999,
+    Float_t lengthlowcut=0.,
+    Float_t lengthcut=0.26,
+    Float_t widthlowcut=0.,
+    Float_t widthcut=0.12
+)
+{    
+    // constants
+    const Int_t nbins = 9;
+    TString psname("alphaMrk.gif");
+    // general settings
+    gROOT->Reset();
+    gStyle->SetCanvasColor(0);
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetPadBorderMode(0);
+    gStyle->SetFrameBorderMode(0);
+    gStyle->SetOptTitle(0);
+    gStyle->SetTitleOffset(1.7,"y");
+    gStyle->SetPadLeftMargin(0.15);
+    gStyle->SetOptStat(111110);
+    gStyle->SetStatColor(0);
+    gStyle->SetStatBorderSize(1);
+    gStyle->SetStatW(0.2);
+    gStyle->SetStatH(0.1);
+    gStyle->SetStatX(0.9);
+    gStyle->SetStatY(0.9);
+    
+    // define files, chain, trees, canvas...
+    TChain* ton= new TChain("Parameters");
+    
+    // ON data
+    ton->Add("/mnt/users/jrico/magic/mars/mars/mtemp/mifae/hillas/crab20040215OnRotateCalA-D.root");
+
+    TChain* toff= new TChain("Parameters");
+
+    // OFF data
+    toff->Add("/mnt/users/jrico/magic/mars/mars/mtemp/mifae/hillas/crab20040215OffRotateCalA-H.root");
+    
+    TCanvas *c1 = new TCanvas("c1","c1",800,500);
+    c1->cd(1);
+
+    // define aliases
+    ton->SetAlias("length","MHillas.fLength*0.6/189");
+    ton->SetAlias("width","MHillas.fWidth*0.6/189");
+    ton->SetAlias("dist","MHillasSrc.fDist*0.6/189");
+    ton->SetAlias("conc","MNewImagePar.fConc");
+    ton->SetAlias("size","MHillas.fSize");
+    ton->SetAlias("event","MRawEvtHeader.fDAQEvtNumber");
+    ton->SetAlias("alpha","abs(MHillasSrc.fAlpha)");
+    ton->SetAlias("leakage","MNewImagePar.fInnerLeakage1");
+    
+    toff->SetAlias("length","MHillas.fLength*0.6/189");
+    toff->SetAlias("width","MHillas.fWidth*0.6/189");
+    toff->SetAlias("dist","MHillasSrc.fDist*0.6/189");
+    toff->SetAlias("conc","MNewImagePar.fConc");
+    toff->SetAlias("size","MHillas.fSize");
+    toff->SetAlias("event","MRawEvtHeader.fDAQEvtNumber");
+    toff->SetAlias("alpha","abs(MHillasSrc.fAlpha)");
+    toff->SetAlias("leakage","MNewImagePar.fInnerLeakage1");
+
+    // define  cut(s)
+//    const char* eventcut="event%4==0 &&";
+    const char* eventcut="";
+    const char varcut[512];
+    //    sprintf(varcut,"size>%f && size<%f && length>%f  &&length<%f && width>%f &&  width<%f",cutsize,upcutsize,lengthlowcut,lengthcut,widthlowcut,widthcut);
+    sprintf(varcut,"size>%f && size<%f  && dist>0.2 && dist<1.1 && leakage==0 && length>%f  &&length<%f && width>%f &&  width<%f",cutsize,upcutsize,lengthlowcut,lengthcut,widthlowcut,widthcut);
+//    sprintf(varcut,"size>%f && dist>0.2 && dist<0.8 && length<0.21 && width<0.125",cutsize,upcutsize,lengthcut,widthcut);
+//    sprintf(varcut,"size>%f && size<%f  && dist>0.2 && dist<0.8 && length<0.21 && width<0.125",cutsize,upcutsize);
+//    sprintf(varcut,"size>%f && size<%f  && dist>0.2 && dist<0.8 && length<0.21",cutsize,upcutsize);
+//    sprintf(varcut,"size>%f && size<%f  && dist>0.2 && dist<0.8",cutsize,upcutsize);
+//    sprintf(varcut,"size>%f && size<%f",cutsize,upcutsize)
+//    sprintf(varcut,"");
+    Char_t cut[256];
+    Char_t cutoff[256];
+    strcat(cut,eventcut);
+    strcat(cut,varcut);
+    strcat(cutoff,varcut);
+
+    // fill on/off histos
+    TH1F* onhisto       = new TH1F("OnHist" ,"Alpha Plot",nbins,0,90);
+    TH1F* offhisto      = new TH1F("OffHist","Alpha Plot",nbins,0,90);    
+    ton->Draw("alpha>>OnHist",cut);
+    toff->Draw("alpha>>OffHist",cutoff);
+    cout << "Applied cut: " << cut << endl;
+    
+    // line/normalization
+    const Int_t inibin = 20./90.*nbins+1;
+    Float_t level=0;
+    Float_t leveloff=0;
+    Float_t levelofferror=0;
+    for(Int_t ibin = inibin; ibin<=nbins;ibin++)
+    {
+	level+=onhisto->GetBinContent(ibin);
+	leveloff+=offhisto->GetBinContent(ibin);
+    }
+    level/=(nbins-inibin+1);
+    leveloff/=(nbins-inibin+1);
+    
+    // normalize on/off
+    offhisto->Sumw2(); // needed to compute correct errors after normalization
+    const Float_t norm = level/leveloff;
+    cout << "Normalizing by factor " << norm <<endl;
+    offhisto->Scale(norm);    
+
+    // significance:
+    Float_t sig=0,bg=0,esig=0,ebg=0;
+    Float_t significance=0;
+    const Int_t signbins = inibin-1;
+    for(Int_t ibin = 1; ibin<=signbins;ibin++)
+    {
+//	Float_t sigma = (onhisto->GetBinContent(ibin)-level)/onhisto->GetBinError(ibin);
+//	significance+=sigma*sigma;
+	sig  += onhisto->GetBinContent(ibin);
+	esig += onhisto->GetBinError(ibin)*onhisto->GetBinError(ibin);
+	bg   += offhisto->GetBinContent(ibin);
+	ebg  += offhisto->GetBinError(ibin)*offhisto->GetBinError(ibin);
+    }
+    Float_t error= TMath::Sqrt(esig+ebg);
+    significance = (sig-bg)/error;
+    
+    cout << "Excess: " << sig-bg << endl;
+    cout << "N bkg: "  << bg << endl; 
+    cout << "Significance: " << significance << endl;
+
+    // plot
+    onhisto->SetXTitle("alpha (deg)");
+    onhisto->SetYTitle("Entries");
+    onhisto->SetMarkerColor(4);
+    onhisto->SetMarkerStyle(20);
+    onhisto->SetMarkerSize(.7);
+    onhisto->SetLineColor(4);
+    onhisto->SetMaximum(onhisto->GetBinContent(nbins)*1.5);
+
+    offhisto->SetFillColor(2);
+    offhisto->SetMaximum(offhisto->GetBinContent(nbins)*1.5);
+    offhisto->SetXTitle("alpha (deg)");
+    offhisto->SetYTitle("Entries");
+
+    offhisto->Draw("HIST");
+    offhisto->Draw("ESAME");
+    onhisto->Draw("ESAMES");
+    //    onhisto->Draw("E");
+
+    // move stat box to make them all visible
+    gPad->Update();
+    TPaveStats* offpavstat = (TPaveStats*) offhisto->GetListOfFunctions()->FindObject("stats");
+    if(offpavstat)
+    {
+	Float_t shiftx = offpavstat->GetX2NDC()-offpavstat->GetX1NDC();
+	offpavstat->SetX1NDC(offpavstat->GetX1NDC()-shiftx);
+	offpavstat->SetX2NDC(offpavstat->GetX2NDC()-shiftx);
+    }
+
+    // draw line
+    TLine* line = new TLine(0.,level,90.,level);
+    line->SetLineColor(2);
+    line->SetLineStyle(2);
+//    line->Draw();
+
+    gPad->Modified();
+    gPad->Update();
+
+    // produce ps
+    //  char psname[50];
+    //  sprintf(psname,"%s.ps",var);
+    c1->Print(psname);
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/alpha_plot.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/alpha_plot.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/alpha_plot.C	(revision 9772)
@@ -0,0 +1,835 @@
+Double_t ChiSquareNDof(TH1D *h1, TH1D *h2)
+{
+    Double_t chiq = 0.;
+    Double_t chi;
+    Double_t error;
+    Int_t nbinsnozero = 0;
+
+    Int_t nbins = h1->GetNbinsX();
+    if (nbins != h2->GetNbinsX() || nbins == 0)
+	return -1;
+
+    for (UInt_t bin=1; bin<=nbins; bin++)
+    {
+	error = sqrt(h1->GetBinError(bin)*h1->GetBinError(bin) +
+			   h2->GetBinError(bin)*h2->GetBinError(bin));
+	if (error != 0)
+	{
+	    chi = (h1->GetBinContent(bin)-h2->GetBinContent(bin))/error;
+	    chiq += chi*chi;
+	    nbinsnozero++;
+	}
+    }
+
+    return chiq/nbinsnozero;
+}
+
+void alpha_plot(TString f_on_name  = "../HillasFiles/Mrk421/*_H.root",
+		TString f_off_name = "../HillasFiles/OffMrk421/*_H.root",
+		TString f_src_name = "../HillasFiles/20040319_OffMrk421.fake.pos")	     
+{
+
+    const UInt_t numEntries = 100000000;
+    
+    //cuts
+    Float_t sizemin   = 2000.; //[ADC]
+    Float_t sizemax   = 10000000000.; //[ADC]
+    Float_t widthmin  = 0.06; 
+    Float_t widthmax  = 0.12;
+    Float_t lengthmin = 0.10; 
+    Float_t lengthmax = 0.26;
+    Float_t distmin   = 0.3; 
+    Float_t distmax   = 1.2;
+    Float_t alphamin   = 0.; 
+    Float_t alphamax   = 90.;
+
+    //integration
+    Float_t sigexccmin = 0.;
+    Float_t sigexccmax = 30.;
+    Float_t bkgnormmin = 30.;
+    Float_t bkgnormmax = 90.;
+    
+    gStyle->SetOptStat(111111);
+    gStyle->SetOptFit();
+    
+    //
+    // Make a loop only for the ON data:
+    //
+    
+    MParList plist_on;
+    MTaskList tlist_on;
+    plist_on.AddToList(&tlist_on);
+  
+    // ON containers
+    MGeomCamMagic geomcam;
+    MSrcPosCam source_on;
+    MHillas hillas;
+    MHillasSrc hillasscr;
+    
+    plist_on.AddToList(&geomcam);
+    plist_on.AddToList(&source_on);
+    plist_on.AddToList(&hillas);
+    plist_on.AddToList(&hillasscr);
+    
+    //create some 1-dim histo to test only for the ON distribution of dist, width , length, size...
+    MH3 hDist_on("MHillasSrc.fDist/315.");
+    hDist_on.SetName("Dist_on");
+    plist_on.AddToList(&hDist_on);
+    MBinning binsDist_on("BinningDist_on");
+    Int_t nbins_Dist = 20;
+    Float_t min_Dist = 0.;
+    Float_t max_Dist = distmax*1.2;
+    binsDist_on.SetEdges(nbins_Dist, min_Dist, max_Dist);
+    plist_on.AddToList(&binsDist_on);
+    
+    MH3 hWidth_on("MHillas.fWidth/315.");
+    hWidth_on.SetName("Width_on");
+    plist_on.AddToList(&hWidth_on);
+    MBinning binsWidth_on("BinningWidth_on");
+    Int_t nbins_Width = 20;
+    Float_t min_Width = 0.;
+    Float_t max_Width = widthmax*1.2;
+    binsWidth_on.SetEdges(nbins_Width, min_Width, max_Width);
+    plist_on.AddToList(&binsWidth_on);
+    
+    MH3 hLength_on("MHillas.fLength/315.");
+    hLength_on.SetName("Length_on");
+    plist_on.AddToList(&hLength_on);
+    MBinning binsLength_on("BinningLength_on");
+    Int_t nbins_Length = 20;
+    Float_t min_Length = 0.;
+    Float_t max_Length =  lengthmax*1.2;
+    binsLength_on.SetEdges(nbins_Length, min_Length, max_Length);
+    plist_on.AddToList(&binsLength_on);
+    
+    MH3 hSize_on("log10(MHillas.fSize)");
+    hSize_on.SetName("Size_on");
+    plist_on.AddToList(&hSize_on);
+    MBinning binsSize_on("BinningSize_on");
+    Int_t nbins_Size = 60;
+    Float_t min_Size = log10(sizemin)*0.8;
+    Float_t max_Size = log10(1000000)*1.2;
+    binsSize_on.SetEdges(nbins_Size, min_Size, max_Size);
+    plist_on.AddToList(&binsSize_on);
+    
+    //create a histo to fill the alpha values: one alpha plot form 0 to +90 deg in abs value
+    MH3 hAlpha_on_abs("abs(MHillasSrc.fAlpha)");
+    hAlpha_on_abs.SetName("Alpha_on_abs");
+    plist_on.AddToList(&hAlpha_on_abs);
+    MBinning binsAlpha_on_abs("BinningAlpha_on_abs");
+    Int_t nbins_abs = 9;
+    Float_t minalpha_abs = 0.;
+    Float_t maxalpha_abs =90.;
+    binsAlpha_on_abs.SetEdges(nbins_abs, minalpha_abs, maxalpha_abs);
+    plist_on.AddToList(&binsAlpha_on_abs);
+    
+    //create a histo to fill the alpha values: one alpha plot form -90 to +90 deg.
+    MH3 hAlpha_on("MHillasSrc.fAlpha");
+    hAlpha_on.SetName("Alpha_on");
+    plist_on.AddToList(&hAlpha_on);
+    MBinning binsAlpha_on("BinningAlpha_on");
+    Int_t nbins = nbins_abs*2;
+    Float_t minalpha = -90.;
+    Float_t maxalpha =  90.;
+    binsAlpha_on.SetEdges(nbins, minalpha, maxalpha);
+    plist_on.AddToList(&binsAlpha_on);
+    
+
+    MH3 hSrcPos_on("MSrcPosCam.fX","MSrcPosCam.fY");
+    hSrcPos_on.SetName("SrcPos_on");
+    plist_on.AddToList(&hSrcPos_on);
+    MBinning binsSrcPos_onX("BinningSrcPos_onX");
+    MBinning binsSrcPos_onY("BinningSrcPos_onY");
+    Int_t nbins_srcpos = 400;
+    Float_t minsrcpos = -600.;
+    Float_t maxsrcpos =  600.;
+    binsSrcPos_onX.SetEdges(nbins_srcpos, minsrcpos, maxsrcpos);
+    binsSrcPos_onY.SetEdges(nbins_srcpos, minsrcpos, maxsrcpos);
+    plist_on.AddToList(&binsSrcPos_onX);
+    plist_on.AddToList(&binsSrcPos_onY);
+
+    MH3 hDAQEvtNumber_on("MRawEvtHeader.fDAQEvtNumber");
+    hDAQEvtNumber_on.SetName("DAQEvtNumber_on");
+    plist_on.AddToList(&hDAQEvtNumber_on);
+    MBinning binsDAQEvtNumber_onX("BinningDAQEvtNumber_onX");
+    Int_t nbins_evtnum = 1000;
+    Float_t minevtnum =  0.;
+    Float_t maxevtnum =  1000.;
+    binsDAQEvtNumber_onX.SetEdges(nbins_evtnum,minevtnum,maxevtnum);
+    plist_on.AddToList(&binsDAQEvtNumber_onX);
+
+    //
+    //tasks
+    //
+    
+    MReadTree read_on("Parameters", f_on_name);
+    read_on.DisableAutoScheme();
+ 
+
+    //cuts
+    TString sizestr = "(MHillas.fSize < ";
+    sizestr += sizemin;
+    sizestr += ") || (";
+    sizestr += "MHillas.fSize > ";
+    sizestr += sizemax;
+    sizestr += ")";
+    MF sizefilter(sizestr);
+    
+    TString widthstr = "({MHillas.fWidth/315.} < ";
+    widthstr += widthmin;
+    widthstr += ") || (";
+    widthstr += "{MHillas.fWidth/315.} > ";
+    widthstr += widthmax;
+    widthstr += ")";
+    MF widthfilter(widthstr);
+    
+    TString lengthstr = "({MHillas.fLength/315.} < ";
+    lengthstr += lengthmin;
+    lengthstr += ") || (";
+    lengthstr += "{MHillas.fLength/315.} > ";
+    lengthstr += lengthmax;
+    lengthstr += ")";
+    MF lengthfilter(lengthstr);
+    
+    TString diststr = "({MHillasSrc.fDist/315.} < ";
+    diststr += distmin;
+    diststr += ") || (";
+    diststr += "{MHillasSrc.fDist/315.} > ";
+    diststr += distmax;
+    diststr += ")";
+    MF distfilter(diststr);
+    
+    TString alphastr = "({abs(MHillasSrc.fAlpha)} < ";
+    alphastr += alphamin;
+    alphastr += ") || (";
+    alphastr += "{abs(MHillasSrc.fAlpha)} > ";
+    alphastr += alphamax;
+    alphastr += ")";
+    MF alphafilter(alphastr);
+    
+    MF evenfilter("{MRawEvtHeader.fDAQEvtNumber%3}<0.5");
+    MF oddfilter("{MRawEvtHeader.fDAQEvtNumber%3}>0.5");
+
+    MContinue cont_size(&sizefilter);
+    MContinue cont_width(&widthfilter);
+    MContinue cont_length(&lengthfilter);
+    MContinue cont_dist(&distfilter);
+    MContinue cont_alpha(&alphafilter);
+    MContinue cont_even(&evenfilter);
+    MContinue cont_odd(&oddfilter);
+    
+    //    MSrcPosFromFile srccalc(f_src_name);
+    MSrcPlace srccalc;
+    
+    MHillasSrcCalc csrc_on;
+
+    // fill all histograms
+    MFillH falpha_on_abs(&hAlpha_on_abs);
+    MFillH falpha_on(&hAlpha_on);
+    MFillH fdist_on(&hDist_on);
+    MFillH fwidth_on(&hWidth_on);
+    MFillH flength_on(&hLength_on);
+    MFillH fsize_on(&hSize_on);
+    MFillH fsrcpos_on(&hSrcPos_on);
+    MFillH fevtnum_on(&hDAQEvtNumber_on);
+    
+
+    // prints
+    MPrint pevent("MRawEvtHeader");
+    MPrint phillas("MHillas");
+    MPrint phillassrc("MHillasSrc");
+    MPrint psrcpos("MSrcPosCam");
+
+    //tasklist
+    tlist_on.AddToList(&read_on);
+    tlist_on.AddToList(&srccalc);
+    tlist_on.AddToList(&csrc_on);
+    tlist_on.AddToList(&fsrcpos_on);
+//    tlist_on.AddToList(&cont_odd);
+    tlist_on.AddToList(&cont_size);
+    tlist_on.AddToList(&cont_width);
+    tlist_on.AddToList(&cont_length);
+    tlist_on.AddToList(&cont_dist);
+    tlist_on.AddToList(&cont_alpha);
+    tlist_on.AddToList(&falpha_on_abs);
+    tlist_on.AddToList(&falpha_on);
+    tlist_on.AddToList(&fdist_on);
+    tlist_on.AddToList(&fwidth_on);
+    tlist_on.AddToList(&flength_on);
+    tlist_on.AddToList(&fsize_on);
+    tlist_on.AddToList(&fevtnum_on);
+    
+    // Create and setup the eventloop
+    MEvtLoop loop_on;
+    loop_on.SetParList(&plist_on);
+  //loop_on.SetDisplay(display);
+    
+    MProgressBar bar;
+    loop_on.SetProgressBar(&bar);
+    
+    if (!loop_on.Eventloop(numEntries))
+	return;
+
+    tlist_on.PrintStatistics();
+    
+    // 
+    // Make a loop only for the OFF data:
+    //
+    
+    MParList plist_off;
+    MTaskList tlist_off;
+    plist_off.AddToList(&tlist_off);
+    
+    MSrcPosCam source_off;
+
+    plist_off.AddToList(&geomcam);
+    plist_off.AddToList(&source_off);
+    plist_off.AddToList(&hillas);
+    plist_off.AddToList(&hillasscr);
+
+    //create some 1-dim histo to test only for the OFF distribution of dist, width , length, size...
+    MH3 hDist_off("MHillasSrc.fDist/315.");
+    hDist_off.SetName("Dist_off");
+    plist_off.AddToList(&hDist_off);
+    MBinning binsDist_off("BinningDist_off");
+    binsDist_off.SetEdges(nbins_Dist, min_Dist, max_Dist);
+    plist_off.AddToList(&binsDist_off);
+    
+    MH3 hWidth_off("MHillas.fWidth/315.");
+    hWidth_off.SetName("Width_off");
+    plist_off.AddToList(&hWidth_off);
+    MBinning binsWidth_off("BinningWidth_off");
+    binsWidth_off.SetEdges(nbins_Width, min_Width, max_Width);
+    plist_off.AddToList(&binsWidth_off);
+
+    MH3 hLength_off("MHillas.fLength/315.");
+    hLength_off.SetName("Length_off");
+    plist_off.AddToList(&hLength_off);
+    MBinning binsLength_off("BinningLength_off");
+    binsLength_off.SetEdges(nbins_Length, min_Length, max_Length);
+    plist_off.AddToList(&binsLength_off);
+    
+    MH3 hSize_off("log10(MHillas.fSize)");
+    hSize_off.SetName("Size_off");
+    plist_off.AddToList(&hSize_off);
+    MBinning binsSize_off("BinningSize_off");
+    binsSize_off.SetEdges(nbins_Size, min_Size, max_Size);
+    plist_off.AddToList(&binsSize_off);
+    
+    //create a histo to fill the alpha values: from 0 to 90 deg -> abs value
+    MH3 hAlpha_off_abs("abs(MHillasSrc.fAlpha)");
+    hAlpha_off_abs.SetName("Alpha_off_abs");
+    plist_off.AddToList(&hAlpha_off_abs);
+    MBinning binsAlpha_off_abs("BinningAlpha_off_abs");
+    binsAlpha_off_abs.SetEdges(nbins_abs, minalpha_abs, maxalpha_abs);
+    plist_off.AddToList(&binsAlpha_off_abs);
+    
+    //create a histo to fill the alpha values: from -90 to 90 deg
+    MH3 hAlpha_off("MHillasSrc.fAlpha");
+    hAlpha_off.SetName("Alpha_off");
+    plist_off.AddToList(&hAlpha_off);
+    MBinning binsAlpha_off("BinningAlpha_off");
+    binsAlpha_off.SetEdges(nbins, minalpha, maxalpha);
+    plist_off.AddToList(&binsAlpha_off);
+    
+    
+    MH3 hSrcPos_off("MSrcPosCam.fX","MSrcPosCam.fY");
+    hSrcPos_off.SetName("SrcPos_off");
+    plist_off.AddToList(&hSrcPos_off);
+    MBinning binsSrcPos_offX("BinningSrcPos_offX");
+    MBinning binsSrcPos_offY("BinningSrcPos_offY");
+    binsSrcPos_offX.SetEdges(nbins_srcpos, minsrcpos, maxsrcpos);
+    binsSrcPos_offY.SetEdges(nbins_srcpos, minsrcpos, maxsrcpos);
+    plist_off.AddToList(&binsSrcPos_offX);
+    plist_off.AddToList(&binsSrcPos_offY);
+
+    MH3 hDAQEvtNumber_off("MRawEvtHeader.fDAQEvtNumber");
+    hDAQEvtNumber_off.SetName("DAQEvtNumber_off");
+    plist_off.AddToList(&hDAQEvtNumber_off);
+    MBinning binsDAQEvtNumber_offX("BinningDAQEvtNumber_offX");
+    Int_t nbins_evtnum = 100;
+    Float_t minevtnum =  0.;
+    Float_t maxevtnum =  100.;
+    binsDAQEvtNumber_offX.SetEdges(nbins_evtnum,minevtnum,maxevtnum);
+    plist_off.AddToList(&binsDAQEvtNumber_offX);
+
+   //tasks
+    MReadTree read_off("Parameters", f_off_name);
+    read_off.DisableAutoScheme();
+    
+    srccalc.SetMode(MSrcPlace::kOff);
+
+    MHillasSrcCalc csrc_off;
+
+    // fill all histograms
+    MFillH falpha_off_abs(&hAlpha_off_abs);
+    MFillH falpha_off(&hAlpha_off);
+    MFillH fdist_off(&hDist_off);
+    MFillH fwidth_off(&hWidth_off);
+    MFillH flength_off(&hLength_off);
+    MFillH fsize_off(&hSize_off);
+    MFillH fsrcpos_off(&hSrcPos_off);
+    MFillH fevtnum_off(&hDAQEvtNumber_off);
+   
+    //tasklist
+    tlist_off.AddToList(&read_off);
+    tlist_off.AddToList(&srccalc);
+    tlist_off.AddToList(&csrc_off);
+    tlist_off.AddToList(&fsrcpos_off);
+//    tlist_off.AddToList(&cont_even);
+    tlist_off.AddToList(&cont_size);
+    tlist_off.AddToList(&cont_width);
+    tlist_off.AddToList(&cont_length);
+    tlist_off.AddToList(&cont_dist);
+    tlist_off.AddToList(&cont_alpha);
+    tlist_off.AddToList(&falpha_off_abs);
+    tlist_off.AddToList(&falpha_off);
+    tlist_off.AddToList(&fdist_off);
+    tlist_off.AddToList(&fwidth_off);
+    tlist_off.AddToList(&flength_off);
+    tlist_off.AddToList(&fsize_off);
+    tlist_off.AddToList(&fevtnum_off);
+     
+    // Create and setup the eventloop
+    MEvtLoop loop_off;
+    loop_off.SetParList(&plist_off);
+    //loop_off.SetDisplay(display);
+    
+    MProgressBar bar_off;
+    loop_off.SetProgressBar(&bar_off);
+    
+    if (!loop_off.Eventloop(numEntries))
+	return;
+    
+    tlist_off.PrintStatistics();
+    
+  // ############################################################################
+  //  look for the histograms
+  // ############################################################################
+
+  TH1F *hist_size_on = (TH1F*)hSize_on.GetHist();
+  TH1F *hist_size_off = (TH1F*)hSize_off.GetHist();
+
+  TH1F *hist_dist_on = (TH1F*)hDist_on.GetHist();
+  TH1F *hist_dist_off = (TH1F*)hDist_off.GetHist();
+
+  TH1F *hist_width_on = (TH1F*)hWidth_on.GetHist();
+  TH1F *hist_width_off = (TH1F*)hWidth_off.GetHist();
+
+  TH1F *hist_length_on = (TH1F*)hLength_on.GetHist();
+  TH1F *hist_length_off = (TH1F*)hLength_off.GetHist();
+
+  TH1F *hist_on_abs = (TH1F*)hAlpha_on_abs.GetHist();
+  TH1F *hist_off_abs = (TH1F*)hAlpha_off_abs.GetHist();
+
+  TH1F *hist_on = (TH1F*)hAlpha_on.GetHist();
+  TH1F *hist_off = (TH1F*)hAlpha_off.GetHist();
+
+
+  // ############################################################################
+  // Calculate significance and excess: 
+  // ############################################################################
+
+  Double_t norm_on_abs  = (Double_t) hist_on_abs->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90+1);
+  Double_t exces_on_abs = (Double_t) hist_on_abs->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90+1);
+  Double_t norm_off_abs  = (Double_t) hist_off_abs->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90+1);
+  Double_t exces_off_abs = (Double_t) hist_off_abs->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90+1);
+  Double_t norm = norm_on_abs/norm_off_abs;
+
+  char text_tit_alpha[256];
+  sprintf(text_tit_alpha, " Alpha Plot On and Off ");
+  hist_off_abs->SetTitle(text_tit_alpha);
+  hist_on_abs->SetTitle(text_tit_alpha);
+
+  Double_t excess  = exces_on_abs - exces_off_abs*norm;
+  Double_t sign    = excess / sqrt( exces_on_abs + norm*norm*exces_off_abs );
+  Double_t int_off = (Double_t) hist_off_abs->Integral(1, 18);
+  int hist_on_entries  = (int) hist_on_abs->GetEntries();
+  int hist_off_entries = (int) hist_off_abs->GetEntries();
+    
+  cout << "---> Normalization F factor =\t" << norm <<endl;
+  cout << "---> Excess =\t\t\t" << excess <<endl;
+  cout << "---> Significancia =\t\t" << sign <<endl;    
+  cout << "---> entries on   =\t\t" << hist_on_entries  <<endl;
+  cout << "---> entries off  =\t\t" << hist_off_entries <<endl;
+  cout << "---> integral off =\t\t" << int_off <<endl;
+
+  Float_t shiftx;
+
+  //
+  //Create the display -> from now on, all histos are plotted
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+  
+  // ############################################################################
+  // Draw SIZE
+  // ############################################################################
+  display->AddTab("SIZE");
+
+  gPad->cd();
+
+  gPad->SetLogy();
+  hist_size_on->Sumw2();
+  hist_size_off->Sumw2();
+  hist_size_off->Scale(norm); 
+  hist_size_on->SetLineColor(kBlack);
+  hist_size_on->SetMarkerStyle(21);
+  hist_size_on->SetMarkerSize(0.7);
+  hist_size_on->SetMarkerColor(kBlack);
+  hist_size_off->SetFillColor(46);
+  hist_size_off->SetLineColor(46);
+  hist_size_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hist_size_off->SetMinimum(0.1);
+  hist_size_on->SetMinimum(0.1);
+  hist_size_on->SetTitle("SIZE distribution");
+  hist_size_off->SetTitle("SIZE distribution");
+
+  hist_size_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_size = (TPaveStats*) hist_size_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_size){
+    shiftx = pavs_on_size->GetX2NDC() - pavs_on_size->GetX1NDC();
+    pavs_on_size->SetX1NDC(pavs_on_size->GetX1NDC() - shiftx);
+    pavs_on_size->SetX2NDC(pavs_on_size->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hist_size_off->DrawCopy("HISTSAME");
+  hist_size_off->DrawCopy("ESAME");
+
+  gPad->Modified();
+  gPad->Update();
+
+  Double_t chisize = ChiSquareNDof((TH1D*)hist_size_on,(TH1D*)hist_size_off);
+
+  Double_t x_label_pos  = log10(1000000)*0.7;
+  Double_t y_label_pos  = log10((hist_size_on->GetBinContent(hist_size_on->GetMaximumBin()))/2.);
+  Double_t textsize = 0.03;
+
+  char text_size[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chisize);
+
+  TLatex *tsize = new TLatex(x_label_pos, y_label_pos, text_size);
+  tsize->SetTextSize(textsize);
+//  tsize->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  // ############################################################################
+  // DrawCopy DIST
+  // ############################################################################
+  display->AddTab("DIST");
+
+  gPad->cd();
+
+  hist_dist_on->Sumw2();
+  hist_dist_off->Sumw2();
+  hist_dist_off->Scale(norm); 
+  hist_dist_on->SetLineColor(kBlack);
+  hist_dist_on->SetMarkerStyle(21);
+  hist_dist_on->SetMarkerSize(0.7);
+  hist_dist_on->SetMarkerColor(kBlack);
+  hist_dist_off->SetFillColor(46);
+  hist_dist_off->SetLineColor(46);
+  hist_dist_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hist_dist_off->SetMinimum(0.);
+  hist_dist_on->SetTitle("DIST distribution");
+  hist_dist_off->SetTitle("DIST distribution");
+
+  hist_dist_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_dist = (TPaveStats*) hist_dist_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_dist){
+    shiftx = pavs_on_dist->GetX2NDC() - pavs_on_dist->GetX1NDC();
+    pavs_on_dist->SetX1NDC(pavs_on_dist->GetX1NDC() - shiftx);
+    pavs_on_dist->SetX2NDC(pavs_on_dist->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hist_dist_off->DrawCopy("HISTSAME");
+  hist_dist_off->DrawCopy("ESAME");
+  hist_dist_on->DrawCopy("E1PSAME");
+
+  Double_t chidist = ChiSquareNDof((TH1D*)hist_dist_on,(TH1D*)hist_dist_off);
+
+  x_label_pos  = distmax*0.7;
+  y_label_pos  = hist_dist_on->GetBinContent(hist_dist_on->GetMaximumBin())/2.;
+
+  char text_dist[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chidist);
+
+  TLatex *tdist = new TLatex(x_label_pos, y_label_pos, text_dist);
+  tdist->SetTextSize(textsize);
+//  tdist->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+   // ############################################################################
+  // DrawCopy WIDTH
+  // ############################################################################
+  display->AddTab("WIDTH");
+
+  gPad->cd();
+
+  hist_width_off->Sumw2();
+  hist_width_off->Scale(norm); 
+  hist_width_on->SetLineColor(kBlack);
+  hist_width_on->SetMarkerStyle(21);
+  hist_width_on->SetMarkerSize(0.7);
+  hist_width_on->SetMarkerColor(kBlack);
+  hist_width_off->SetFillColor(46);
+  hist_width_off->SetLineColor(46);
+  hist_width_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hist_width_off->SetMinimum(0.);
+  hist_width_on->SetTitle("WIDTH distribution");
+  hist_width_off->SetTitle("WIDTH distribution");
+
+  hist_width_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_width = (TPaveStats*) hist_width_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_width){
+    shiftx = pavs_on_width->GetX2NDC() - pavs_on_width->GetX1NDC();
+    pavs_on_width->SetX1NDC(pavs_on_width->GetX1NDC() - shiftx);
+    pavs_on_width->SetX2NDC(pavs_on_width->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hist_width_off->DrawCopy("HISTSAME");
+  hist_width_off->DrawCopy("ESAME");
+  hist_width_on->DrawCopy("E1PSAME");
+
+  Double_t chiwidth = ChiSquareNDof((TH1D*)hist_width_on,(TH1D*)hist_width_off);
+
+  x_label_pos  = widthmax*0.7;
+  y_label_pos  = hist_width_on->GetBinContent(hist_width_on->GetMaximumBin())/2.;
+
+  char text_width[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chiwidth);
+
+  TLatex *twidth = new TLatex(x_label_pos, y_label_pos, text_width);
+  twidth->SetTextSize(textsize);
+//  twidth->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+ 
+  // ############################################################################
+  // DrawCopy LENGTH
+  // ############################################################################
+  display->AddTab("LENGTH");
+ 
+  gPad->cd();
+
+  hist_length_on->Sumw2();
+  hist_length_off->Sumw2();
+  hist_length_off->Scale(norm); 
+  hist_length_on->SetLineColor(kBlack);
+  hist_length_on->SetMarkerStyle(21);
+  hist_length_on->SetMarkerSize(0.7);
+  hist_length_on->SetMarkerColor(kBlack);
+  hist_length_off->SetFillColor(46);
+  hist_length_off->SetLineColor(46);
+  hist_length_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hist_length_off->SetMinimum(0.);
+  hist_length_on->SetTitle("LENGTH distribution");
+  hist_length_off->SetTitle("LENGTH distribution");
+
+  hist_length_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_length = (TPaveStats*) hist_length_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_length){
+    shiftx = pavs_on_length->GetX2NDC() - pavs_on_length->GetX1NDC();
+    pavs_on_length->SetX1NDC(pavs_on_length->GetX1NDC() - shiftx);
+    pavs_on_length->SetX2NDC(pavs_on_length->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hist_length_off->DrawCopy("HISTSAME");
+  hist_length_off->DrawCopy("ESAME");
+  hist_length_on->DrawCopy("E1PSAME");
+
+  Double_t chilength = ChiSquareNDof((TH1D*)hist_length_on,(TH1D*)hist_length_off);
+
+  x_label_pos  = lengthmax*0.7;
+  y_label_pos  = hist_length_on->GetBinContent(hist_length_on->GetMaximumBin())/2.;
+
+  char text_length[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chilength);
+
+  TLatex *tlength = new TLatex(x_label_pos, y_label_pos, text_length);
+  tlength->SetTextSize(textsize);
+//  tlength->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  // ############################################################################
+  // DrawCopy normalized ALPHA plot
+  // ############################################################################
+  display->AddTab("ALPHA");
+  
+  gPad->cd();
+
+  hist_on_abs->Sumw2();
+  hist_off_abs->SetStats(0);
+  hist_off_abs->Sumw2();
+  hist_off_abs->Scale(norm); 
+  hist_on_abs->SetStats(0); //-> Do NOT show the legend with statistics
+  hist_on_abs->SetLineColor(kBlack);
+  hist_on_abs->SetMarkerStyle(21);
+  //hist_on_abs->SetMarkerSize();
+  hist_on_abs->SetMarkerColor(kBlack);
+  hist_on_abs->SetMarkerSize(0.7);
+  hist_off_abs->SetFillColor(46);
+  hist_off_abs->SetLineColor(46);
+  hist_off_abs->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hist_off_abs->SetMinimum(0.);
+  hist_on_abs->SetTitle("Alpha plot");
+  hist_off_abs->SetTitle("Alpha plot");
+
+  
+  hist_on_abs->DrawCopy("E1P");
+  hist_off_abs->DrawCopy("HISTSAME");
+  hist_off_abs->DrawCopy("ESAME");
+  hist_on_abs->DrawCopy("E1PSAME");
+
+
+   //draw the LEGEND with excess and significance values in the alpha plot:
+  char text_Fnorm[256], text_excess[256], text_sign[256];
+  char text_entries_on[256], text_entries_off[256], text_integral_off[256];
+  int hist_on_entries  = (int) hist_on_abs->GetEntries();
+  int hist_off_entries = (int) hist_off_abs->GetEntries();
+  sprintf(text_Fnorm,       " F norm =       %.3f", norm);
+  sprintf(text_excess,      " Excess =       %.3f", excess);
+  sprintf(text_sign,        " Significance = %.3f", sign);
+  sprintf(text_entries_on,  " Entries ON   = %d",  hist_on_entries);
+  sprintf(text_entries_off, " Entries OFF  = %d",  hist_off_entries);
+  sprintf(text_integral_off," Integral OFF = %d",  int_off);
+  
+  x_label_pos  = alphamax*0.7;
+  y_label_pos  = (hist_on_abs->GetBinContent(hist_on_abs->GetMaximumBin()))/1.6; //2.;
+  Double_t y_label_step = y_label_pos / 8.;
+
+  TLatex *t0 = new TLatex(x_label_pos, y_label_pos - y_label_step*0, text_Fnorm);
+  t0->SetTextSize(textsize);
+  t0->Draw();
+  TLatex *t1 = new TLatex(x_label_pos, y_label_pos - y_label_step*1, text_excess);
+  t1->SetTextSize(textsize);
+  t1->Draw();
+  TLatex *t2 = new TLatex(x_label_pos, y_label_pos - y_label_step*2, text_sign);
+  t2->SetTextSize(textsize);
+  t2->Draw();
+  TLatex *t3 = new TLatex(x_label_pos, y_label_pos - y_label_step*3, text_entries_on);
+  t3->SetTextSize(textsize);
+  t3->Draw();
+  TLatex *t4 = new TLatex(x_label_pos, y_label_pos - y_label_step*4, text_entries_off);
+  t4->SetTextSize(textsize);
+  t4->Draw();
+  TLatex *t5 = new TLatex(x_label_pos, y_label_pos - y_label_step*5, text_integral_off);
+  t5->SetTextSize(textsize);
+  t5->Draw();
+  
+
+  Double_t chialpha = ChiSquareNDof((TH1D*)hist_on_abs,(TH1D*)hist_off_abs);
+
+  y_label_pos  = (hist_on_abs->GetBinContent(hist_on_abs->GetMaximumBin()))/2.;
+
+  char text_alpha[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chialpha);
+
+  TLatex *talpha = new TLatex(x_label_pos, y_label_pos, text_alpha);
+  talpha->SetTextSize(textsize);
+//  talpha->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  // ############################################################################
+  // DrawCopy normalized alpha histos for alpha form -90 to 90 deg.
+  // ############################################################################
+  display->AddTab("ALPHA +-90");
+
+  gPad->cd();
+
+  hist_on->Sumw2();
+  hist_off->SetStats(0);
+  hist_off->Sumw2();
+  hist_off->Scale(norm); 
+  hist_off->SetFillColor(46);
+  hist_off->SetLineColor(46);
+  hist_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hist_off->SetMinimum(0.); 
+  hist_on->SetStats(0); //-> Do NOT show the legend with statistics
+  hist_on->SetLineColor(kBlack);
+  hist_on->SetMarkerStyle(21);
+  hist_on->SetMarkerSize(0.7);
+  hist_on->SetMarkerColor(kBlack);
+  hist_on->SetTitle("Alpha plot form -90 to 90 deg");
+  hist_off->SetTitle("Alpha plot form -90 to 90 deg");
+
+  hist_on->DrawCopy("E1P");
+  hist_off->DrawCopy("HISTSAME");
+  hist_off->DrawCopy("ESAME");
+  hist_on->DrawCopy("E1PSAME");
+
+  Double_t chialpha90 = ChiSquareNDof((TH1D*)hist_on,(TH1D*)hist_off);
+
+  x_label_pos  = alphamax*0.5;
+  y_label_pos  = hist_on->GetBinContent(hist_on->GetMaximumBin())/2.;
+
+  char text_alpha90[256];
+  sprintf(text_alpha90,"ChiSquare/NDof = %4.2f",chialpha90);
+
+  TLatex *talpha90 = new TLatex(x_label_pos, y_label_pos, text_alpha90);
+  talpha90->SetTextSize(textsize);
+//  talpha90->Draw();
+
+  gPad->Update();
+  gPad->Modified();
+
+
+  cout << "---> ChiSquare/NDof [Size] =\t\t" << chisize << endl;
+  cout << "---> ChiSquare/NDof [Dist] =\t\t" << chidist << endl;
+  cout << "---> ChiSquare/NDof [Width] =\t\t" << chiwidth << endl;
+  cout << "---> ChiSquare/NDof [Length] =\t\t" << chilength << endl;
+  cout << "---> ChiSquare/NDof [Abs(Alpha)] =\t" << chialpha << endl;
+  cout << "---> ChiSquare/NDof [Alpha] =\t\t" << chialpha90 << endl;
+
+
+  display->AddTab("SRCPOS ON");
+  TH2F *hist_srcpos_on = (TH2F*)hSrcPos_on.GetHist();
+  hist_srcpos_on->DrawCopy("BOX");
+
+  display->AddTab("SRCPOS OFF");
+  TH2F *hist_srcpos_off = (TH2F*)hSrcPos_off.GetHist();
+  hist_srcpos_off->DrawCopy("BOX");
+
+  display->AddTab("EVTNUM ON");
+  TH1F *hist_evtnum_on = (TH1F*)hDAQEvtNumber_on.GetHist();
+  hist_evtnum_on->DrawCopy();
+
+  display->AddTab("EVTNUM OFF");
+  TH1F *hist_evtnum_off = (TH1F*)hDAQEvtNumber_off.GetHist();
+  hist_evtnum_off->DrawCopy();
+
+  cout << "Done!!" <<endl;
+
+}
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/cleanComp.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/cleanComp.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/cleanComp.C	(revision 9772)
@@ -0,0 +1,445 @@
+/* ======================================================================== *\!
+!   Author(s): Javier Rico
+\* ======================================================================== */
+
+void cleanComp()
+{    
+  // general settings
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+  gStyle->SetOptTitle(1);
+  //  gStyle->SetTitleOffset(1.7,"y");
+  //  gStyle->SetPadLeftMargin(0.15);
+  gStyle->SetOptStat(111110);
+  gStyle->SetStatColor(0);
+  gStyle->SetStatBorderSize(1);
+  gStyle->SetStatW(0.2);
+  gStyle->SetStatH(0.1);
+  gStyle->SetStatX(0.9);
+  gStyle->SetStatY(0.9);
+  
+  // define files, chain, trees, canvas...
+  TChain* ton;
+  ton= new TChain("Events");
+  
+  // data file(s)
+  ton->Add("/local_disk/jrico/mc/cleanComp0-3.root");
+  
+  // define aliases
+  ton->SetAlias("run","MRawRunHeader.fRunNumber");
+  ton->SetAlias("event","MRawEvtHeader.fDAQEvtNumber");
+  ton->SetAlias("energy","MMcEvt.fEnergy");
+
+  // alpha0 is for the file without noise
+  // alphaNOCL is for the file with noise and no cleaning
+  ton->SetAlias("alpha0","MHillasSrc0.fAlpha");
+  ton->SetAlias("alphaNOCL","MHillasSrcnoclean.fAlpha");
+  ton->SetAlias("alpha3015","MHillasSrc3015.fAlpha");
+  ton->SetAlias("alpha4025","MHillasSrc4025.fAlpha");
+  ton->SetAlias("alpha5035","MHillasSrc5035.fAlpha");
+  ton->SetAlias("alpha6045","MHillasSrc6045.fAlpha");
+  
+  //  ton->Scan("run:event","alpha0<-30 && energy>2500 && energy<5000");
+  
+  //  plotAlphaWidth(ton);
+   plotAlphaWidthVsEnergy(ton);
+  // plotEfficiencies(ton);
+}
+
+void plotAlphaWidth(TChain* ton)
+{
+  // define and fill histos
+  const Int_t nbins=90;
+  TH1F* halpha3015 = new TH1F("Alpha3015" ,"Alpha3015",nbins,-180,180);
+  TH1F* halpha4025 = new TH1F("Alpha4025" ,"Alpha4025",nbins,-180,180);
+  TH1F* halpha5035 = new TH1F("Alpha5035" ,"Alpha5035",nbins,-180,180);
+  TH1F* halpha6045 = new TH1F("Alpha6045" ,"Alpha6045",nbins,-180,180);
+  
+  halpha3015->SetXTitle("alpha-alpha0 (deg)");
+  halpha3015->SetYTitle("Entries");
+  
+  halpha3015->SetLineColor(1);
+  halpha4025->SetLineColor(2);
+  halpha5035->SetLineColor(3);
+  halpha6045->SetLineColor(4);
+  
+  ton->Draw("alpha3015-alpha0>>Alpha3015","alpha3015!=0");
+  ton->Draw("alpha4025-alpha0>>Alpha4025","alpha4025!=0");
+  ton->Draw("alpha5035-alpha0>>Alpha5035","alpha5035!=0");
+  ton->Draw("alpha6045-alpha0>>Alpha6045","alpha6045!=0");
+  
+  // plot
+  TCanvas *c1 = new TCanvas("c1","c1",800,500);
+  c1->cd(1);
+  
+  halpha3015->Draw("HIST");
+  halpha4025->Draw("HISTSAMES");
+  halpha5035->Draw("HISTSAMES");
+  halpha6045->Draw("HISTSAMES");
+  
+  gPad->Update();
+  TPaveStats* pvstat4025  = (TPaveStats*) halpha4025->GetListOfFunctions()->FindObject("stats");
+  TPaveStats* pvstat5035  = (TPaveStats*) halpha5035->GetListOfFunctions()->FindObject("stats");
+  TPaveStats* pvstat6045  = (TPaveStats*) halpha6045->GetListOfFunctions()->FindObject("stats");
+  
+  Float_t shifty = pvstat4025->GetY2NDC()-pvstat4025->GetY1NDC();
+  
+  pvstat4025->SetY1NDC(pvstat4025->GetY1NDC()-shifty);
+  pvstat4025->SetY2NDC(pvstat4025->GetY2NDC()-shifty);
+  pvstat5035->SetY1NDC(pvstat5035->GetY1NDC()-2*shifty);
+  pvstat5035->SetY2NDC(pvstat5035->GetY2NDC()-2*shifty);
+  pvstat6045->SetY1NDC(pvstat6045->GetY1NDC()-3*shifty);
+  pvstat6045->SetY2NDC(pvstat6045->GetY2NDC()-3*shifty);
+  
+  gPad->Modified();
+  gPad->Update();
+  
+  c1->Print("cleanComp.ps");
+}
+
+/*******************************************************************************/
+void plotAlphaWidthVsEnergy(TChain* ton)
+{
+  const Int_t nbins = 8;
+  Float_t bound[nbins+1] ={0,30,50,80,150,300,600,1200,3000}; // boundary of considered size bins
+  
+  // define the arrays that will feed the graphs
+  // value of rms of the alpha-alpha0 distribution, and errors
+  Float_t alpha0[nbins];
+  Float_t alpha3015[nbins];
+  Float_t alpha4025[nbins];
+  Float_t alpha5035[nbins];
+  Float_t alpha6045[nbins];
+
+  Float_t ealpha0[nbins];
+  Float_t ealpha3015[nbins];
+  Float_t ealpha4025[nbins];
+  Float_t ealpha5035[nbins];
+  Float_t ealpha6045[nbins];
+
+  // x axis and error
+  Float_t x[nbins];
+  Float_t ex[nbins];
+
+  TH1F* hp[nbins];
+
+  // define the function that will be used to fit the histograms
+  TF1 f2("f2","[0]+[1]/[3]*exp(-(x-[2])*(x-[2])/(2*[3]*[3]))",-180.,180.);
+  f2.SetParameters(0,100,0,02);
+  f2.FixParameter(0,0);
+  f2.SetLineWidth(1);
+
+  // fill the arrays
+  for(Int_t i=0;i<nbins;i++)
+    {
+      //      cout << "Bin " << i << endl;
+      TH1F dummy0("dummy0" ,"dummy0",100,-90,90);
+      TH1F dummy3015("dummy3015" ,"dummy3015",100,-180,180);
+      TH1F dummy4025("dummy4025" ,"dummy4025",100,-180,180);
+      TH1F dummy5035("dummy5035" ,"dummy5035",100,-180,180);
+      TH1F dummy6045("dummy6045" ,"dummy6045",100,-180,180);
+
+      TH1F xdummy("xdummy" ,"xdummy",100,bound[i],bound[i+1]);
+
+      // define the cuts for each of the cleaning levels
+      char cut[100];
+      sprintf(cut,"energy>%f && energy<%f && alpha0!=0",bound[i],bound[i+1]);
+      char cut3015[200];
+      sprintf(cut3015,"%s && alpha3015!=0",cut);
+      char cut4025[200];
+      sprintf(cut4025,"%s && alpha4025!=0",cut);
+      char cut5035[200];
+      sprintf(cut5035,"%s && alpha5035!=0",cut);
+      char cut6045[200];
+      sprintf(cut6045,"%s && alpha6045!=0",cut);
+
+      TF1 f1("f1","[0]+[1]/[3]*exp(-(x-[2])*(x-[2])/(2*[3]*[3]))",-180.,180.);
+      f1.SetParameters(0,100,0,02);
+      f1.FixParameter(0,0);
+
+
+      // fill the histograms to extract later the information from rms, entries, means, etc
+      ton->Draw("alpha0>>dummy0",cut);
+      ton->Draw("alpha3015-alpha0>>dummy3015",cut3015);
+      ton->Draw("alpha4025-alpha0>>dummy4025",cut4025);
+      ton->Draw("alpha5035-alpha0>>dummy5035",cut5035);
+      ton->Draw("alpha6045-alpha0>>dummy6045",cut6045);
+
+      ton->Draw("energy>>xdummy",cut);
+
+      // fit to a gaussian and get the sigma to be plotted later
+      dummy0.Fit("f1");
+      alpha0[i]   =f1.GetParameter(3);
+      dummy3015.Fit("f1");
+      alpha3015[i]=f1.GetParameter(3);
+      dummy4025.Fit("f1");
+      alpha4025[i]=f1.GetParameter(3);
+      dummy5035.Fit("f1");
+      alpha5035[i]=f1.GetParameter(3);
+      dummy6045.Fit("f1");
+      alpha6045[i]=f1.GetParameter(3);
+
+      Float_t nevt0    = dummy0.GetEntries();
+      Float_t nevt3015 = dummy3015.GetEntries();
+      Float_t nevt4025 = dummy4025.GetEntries();
+      Float_t nevt5035 = dummy5035.GetEntries();
+      Float_t nevt6045 = dummy6045.GetEntries();
+
+      // since gaussian is not so good aproximation, compute error like follows
+      ealpha0[i]   = alpha0[i]/TMath::Sqrt(2*nevt0);
+      ealpha3015[i]= alpha3015[i]/TMath::Sqrt(2*nevt3015);
+      ealpha4025[i]= alpha4025[i]/TMath::Sqrt(2*nevt4025);
+      ealpha5035[i]= alpha5035[i]/TMath::Sqrt(2*nevt5035);
+      ealpha6045[i]= alpha6045[i]/TMath::Sqrt(2*nevt6045);
+
+      // copy some histos to be plotted later
+      Char_t nom[10];
+      sprintf(nom,"hp[%02d]",i);
+      hp[i] = new TH1F(nom,nom,100,-180,180);
+      hp[i]->GetXaxis()->SetTitle("alpha (deg)");
+      hp[i]->Add(&dummy6045);
+      hp[i]->Fit("f2");
+
+      //      cout << xdummy.GetMean() << " " << xdummy.GetRMS()<< " " << xdummy.GetEntries() << endl;
+      x[i]  = xdummy.GetMean();            
+      //      Float_t rms = xdummy.GetRMS();
+      ex[i] = 0;//rms*rms/xdummy.GetEntries();
+    }
+
+  //#if 0
+  TCanvas* cdum = new TCanvas("cdum","cdum",600,900);
+  cdum->Divide(2,nbins/2+1);
+  for(Int_t i=0;i<nbins;i++)
+    {
+      cdum->cd(i+1);
+      hp[i]->Draw();
+      gPad->Modified();
+      gPad->Update();
+    }
+  //#endif
+  
+  // create the graphs
+  TGraphErrors* gr0    = new TGraphErrors(nbins,x,alpha0,ex,ealpha0);
+  TGraphErrors* gr3015 = new TGraphErrors(nbins,x,alpha3015,ex,ealpha3015);
+  TGraphErrors* gr4025 = new TGraphErrors(nbins,x,alpha4025,ex,ealpha4025);
+  TGraphErrors* gr5035 = new TGraphErrors(nbins,x,alpha5035,ex,ealpha5035);
+  TGraphErrors* gr6045 = new TGraphErrors(nbins,x,alpha6045,ex,ealpha6045);  
+
+  // marker/line colors
+  gr0->SetMarkerStyle(20);
+  gr3015->SetMarkerStyle(24);
+  gr4025->SetMarkerStyle(21);
+  gr5035->SetMarkerStyle(25);
+  gr6045->SetMarkerStyle(22);
+
+  gr0->SetMarkerColor(1);
+  gr3015->SetMarkerColor(2);
+  gr4025->SetMarkerColor(3);
+  gr5035->SetMarkerColor(4);
+  gr6045->SetMarkerColor(6);
+
+  gr0->SetLineColor(1);
+  gr3015->SetLineColor(2);
+  gr4025->SetLineColor(3);
+  gr5035->SetLineColor(4);
+  gr6045->SetLineColor(6);
+
+  //////////////////////
+  // plot alpha width //
+  //////////////////////
+  TCanvas *c1 = new TCanvas("c1","c1",800,500);
+  c1->cd(1);
+  gPad->SetGridx();  
+  gPad->SetGridy();  
+  gPad->SetLogx();
+
+  TGraphErrors* grfirst = gr4025;
+  grfirst->Draw("APL");
+  gr0->Draw("PL");
+  gr3015->Draw("PL");
+  gr4025->Draw("PL");
+  gr5035->Draw("PL");
+  gr6045->Draw("PL");
+
+  grfirst->GetHistogram()->SetTitle("Cleaning comparison (alpha)");
+  grfirst->GetHistogram()->GetXaxis()->SetTitle("E_{MC} [GeV]");
+  grfirst->GetHistogram()->GetYaxis()->SetTitle("#sigma (alpha-alpha_{0}) [deg]");
+  grfirst->GetHistogram()->SetMaximum(80);
+
+  TPaveLabel* label = new TPaveLabel(0.25,0.75,0.6,0.85,"MC Gammas - zbins 0-3","NDC");
+  label->SetBorderSize(0);
+  label->SetFillColor(0);
+  label->Draw();
+
+  // legend
+  TLegend* leg = new TLegend(.6,.5,.8,.8);
+  leg->SetHeader("");
+  leg->SetFillColor(0);
+  leg->SetLineColor(0);
+  leg->SetBorderSize(0);
+  leg->AddEntry(gr0,"No noise","p");
+  leg->AddEntry(gr3015,"(3.0,1.5)","p");
+  leg->AddEntry(gr4025,"(4.0,2.5)","p");
+  leg->AddEntry(gr5035,"(5.0,3.5)","p");
+  leg->AddEntry(gr6045,"(6.0,4.5)","p");
+  leg->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+  // print to file
+  c1->Print("cleanAlphaWidthVSEnergy.ps");
+}
+
+/*******************************************************************************/
+void plotEfficiencies(TChain* ton)
+{
+  const Int_t nbins = 8;
+  Float_t bound[nbins+1] ={0,30,50,80,150,300,600,1200,3000}; // boundary of considered size bins
+  
+  // define the arrays that will feed the graphs
+  // gamma detection efficiency, and errors  
+  Float_t effNOCL[nbins];
+  Float_t eff3015[nbins];
+  Float_t eff4025[nbins];
+  Float_t eff5035[nbins];
+  Float_t eff6045[nbins];
+
+  Float_t eeffNOCL[nbins];
+  Float_t eeff3015[nbins];
+  Float_t eeff4025[nbins];
+  Float_t eeff5035[nbins];
+  Float_t eeff6045[nbins];
+
+  // x axis and error
+  Float_t x[nbins];
+  Float_t ex[nbins];
+
+  // fill the arrays
+  for(Int_t i=0;i<nbins;i++)
+    {
+      //      cout << "Bin " << i << endl;
+      TH1F dummyNOCL("dummyNOCL" ,"dummyNOCL",100,-90,90);
+      TH1F dummy3015("dummy3015" ,"dummy3015",100,-90,90);
+      TH1F dummy4025("dummy4025" ,"dummy4025",100,-90,90);
+      TH1F dummy5035("dummy5035" ,"dummy5035",100,-90,90);
+      TH1F dummy6045("dummy6045" ,"dummy6045",100,-90,90);
+
+      TH1F xdummy("xdummy" ,"xdummy",100,bound[i],bound[i+1]);
+
+      // define the cuts for each of the cleaning levels
+      char cut[100];
+      sprintf(cut,"energy>%f && energy<%f && alpha0!=0",bound[i],bound[i+1]);
+      char cutNOCL[200];
+      sprintf(cutNOCL,"%s && alphaNOCL!=0",cut);
+      char cut3015[200];
+      sprintf(cut3015,"%s && alpha3015!=0",cut);
+      char cut4025[200];
+      sprintf(cut4025,"%s && alpha4025!=0",cut);
+      char cut5035[200];
+      sprintf(cut5035,"%s && alpha5035!=0",cut);
+      char cut6045[200];
+      sprintf(cut6045,"%s && alpha6045!=0",cut);
+
+
+      // fill the histograms to extract later the information from rms, entries, means, etc
+      ton->Draw("alpha0>>dummyNOCL",cutNOCL);
+      ton->Draw("alpha0>>dummy3015",cut3015);
+      ton->Draw("alpha0>>dummy4025",cut4025);
+      ton->Draw("alpha0>>dummy5035",cut5035);
+      ton->Draw("alpha0>>dummy6045",cut6045);
+
+      ton->Draw("energy>>xdummy",cut);
+
+      Float_t nevt0    = dummyNOCL.GetEntries();
+      Float_t nevt3015 = dummy3015.GetEntries();
+      Float_t nevt4025 = dummy4025.GetEntries();
+      Float_t nevt5035 = dummy5035.GetEntries();
+      Float_t nevt6045 = dummy6045.GetEntries();
+
+      // fill the array of efficiencies
+      eff3015[i] = nevt3015/nevt0*100;
+      eff4025[i] = nevt4025/nevt0*100;
+      eff5035[i] = nevt5035/nevt0*100;
+      eff6045[i] = nevt6045/nevt0*100;
+
+      eeff3015[i] = TMath::Sqrt(nevt3015)/nevt0*100;
+      eeff4025[i] = TMath::Sqrt(nevt4025)/nevt0*100;
+      eeff5035[i] = TMath::Sqrt(nevt5035)/nevt0*100;
+      eeff6045[i] = TMath::Sqrt(nevt6045)/nevt0*100;
+
+      //      cout << xdummy.GetMean() << " " << xdummy.GetRMS()<< " " << xdummy.GetEntries() << endl;
+      x[i]  = xdummy.GetMean();            
+      //      Float_t rms = xdummy.GetRMS();
+      ex[i] = 0;//rms*rms/xdummy.GetEntries();
+    }
+
+  // create the graphs
+  TGraphErrors* efgr3015 = new TGraphErrors(nbins,x,eff3015,ex,eeff3015);
+  TGraphErrors* efgr4025 = new TGraphErrors(nbins,x,eff4025,ex,eeff4025);
+  TGraphErrors* efgr5035 = new TGraphErrors(nbins,x,eff5035,ex,eeff5035);
+  TGraphErrors* efgr6045 = new TGraphErrors(nbins,x,eff6045,ex,eeff6045);  
+
+  // marker/line colors
+  efgr3015->SetMarkerStyle(24);
+  efgr4025->SetMarkerStyle(21);
+  efgr5035->SetMarkerStyle(25);
+  efgr6045->SetMarkerStyle(22);
+
+  efgr3015->SetMarkerColor(2);
+  efgr4025->SetMarkerColor(3);
+  efgr5035->SetMarkerColor(4);
+  efgr6045->SetMarkerColor(6);
+
+  efgr3015->SetLineColor(2);
+  efgr4025->SetLineColor(3);
+  efgr5035->SetLineColor(4);
+  efgr6045->SetLineColor(6);
+
+  ///////////////////////
+  // plot efficiencies //
+  ///////////////////////
+  TCanvas *c1 = new TCanvas("c1","c1",800,500);
+  c1->cd(1);
+  gPad->SetGridx();  
+  gPad->SetGridy();  
+  gPad->SetLogx();
+
+  TGraphErrors* efgrfirst = efgr6045;
+  efgrfirst->Draw("APL");
+  efgr3015->Draw("PL");
+  efgr4025->Draw("PL");
+  efgr5035->Draw("PL");
+  efgr6045->Draw("PL");
+
+  efgrfirst->GetHistogram()->SetTitle("Cleaning comparison (efficiency)");
+  efgrfirst->GetHistogram()->GetXaxis()->SetTitle("E_{MC} [GeV]");
+  efgrfirst->GetHistogram()->GetYaxis()->SetTitle("Detection efficiency (%)");
+
+  // label
+  TPaveLabel* eflabel = new TPaveLabel(0.5,0.49,0.85,0.59,"MC Gammas - zbins 0-3","NDC");
+  eflabel->SetBorderSize(0);
+  eflabel->SetFillColor(0);
+  eflabel->Draw();
+ 
+  // legend
+  TLegend* efleg = new TLegend(.6,.2,.8,.5);
+  efleg->SetHeader("");
+  efleg->SetFillColor(0);
+  efleg->SetLineColor(0);
+  efleg->SetBorderSize(0);
+  efleg->AddEntry(efgr3015,"(3.0,1.5)","p");
+  efleg->AddEntry(efgr4025,"(4.0,2.5)","p");
+  efleg->AddEntry(efgr5035,"(5.0,3.5)","p");
+  efleg->AddEntry(efgr6045,"(6.0,4.5)","p");
+  efleg->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  // print to file
+  c1->Print("cleanEfficiency.ps");
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/computeCoeff.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/computeCoeff.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/computeCoeff.C	(revision 9772)
@@ -0,0 +1,61 @@
+
+
+void computeCoeff()
+{    
+  MEffAreaAndCoeffCalc calc;
+  calc.AddFile("/data/star_gamma_test.root");
+
+  /************************************************/
+  /* Build spectrum                               */
+  /* now it's just a cross check with the same MC */
+  /************************************************/
+  const Int_t ebins = 20;              // number of bins to build spectrum
+  const Double_t emin=10;
+  const Double_t emax=200;
+  const Int_t tbins = 2;
+  const Double_t thetab[tbins+1] = {0,10,20};
+  calc.SetEbins(ebins);
+  calc.SetEmin(emin);
+  calc.SetEmax(emax);
+  calc.SetThetaBinning(tbins,thetab);
+  
+  // define the funtion of the desired spectrum
+  calc.SetFunction("4.e9*pow(x,-2.6+1)");
+  calc.ComputeAllFactors();
+  
+  const UInt_t ncutfiles=1;
+  Char_t* cutName[ncutfiles]={"/data/star_gamma_test.root"};
+
+  TChain* ccut = new TChain("Events");
+  for(Int_t i = 0; i < ncutfiles; i++)
+    ccut->Add(cutName[i]);
+  ccut->SetAlias("logestenergy","log10(MHillas.fSize/0.18/15.)");
+  ccut->SetAlias("theta","MMcEvt.fTelescopeTheta*180./3.14159");
+
+
+  const Double_t logemin = TMath::Log10(emin);
+  const Double_t logemax = TMath::Log10(emax);
+  TH1D* hspec = new TH1D("hspec","Spectrum",ebins,logemin,logemax);
+  hspec->Sumw2();
+  ccut->Draw("logestenergy>>hspec","theta<10","goff");
+
+  for(Int_t i=0;i<ebins;i++)
+    {
+      const Float_t uncorrval = hspec->GetBinContent(i+1);
+      const Float_t effa  =  calc.GetEffectiveAreaHisto()->GetBinContent(i+1,1);
+      const Float_t unfold = calc.GetCoefficientHisto()->GetBinContent(i+1,1);
+      Float_t corrval;
+      if(effa)
+	corrval = uncorrval*unfold/effa*1e9;
+      else
+	corrval = 0;
+      hspec->SetBinContent(i+1,corrval);
+    }
+
+  // SAVE RESULTS
+  TFile file("prueba.root","RECREATE");
+  hspec->Write();
+  calc.GetEffectiveAreaHisto()->Write();
+  calc.GetCoefficientHisto()->Write();
+  return;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/distancebetweenstars.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/distancebetweenstars.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/distancebetweenstars.C	(revision 9772)
@@ -0,0 +1,249 @@
+ /* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 05/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+Double_t fitfunc(Double_t *x, Double_t *par);
+
+void distancebetweenstars(const TString filename="dc_2004_03_17_01_16_51_20440_Mrk421.root", const TString directory="/nfs/magic/CaCodata/rootdata/Mrk421/Period015/2004_03_17/", const UInt_t numEvents = 100000000)
+{
+
+    // general settings
+    gROOT->Reset();
+    gStyle->SetCanvasColor(0);
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetPadBorderMode(0);
+    gStyle->SetFrameBorderMode(0);
+    gStyle->SetOptTitle(0);
+    gStyle->SetTitleOffset(1.7,"y");
+    gStyle->SetPadLeftMargin(0.15);
+    gStyle->SetOptStat(111110);
+    gStyle->SetOptFit(1);
+    gStyle->SetStatColor(0);
+    gStyle->SetStatBorderSize(1);
+    gStyle->SetStatW(0.2);
+    gStyle->SetStatH(0.1);
+    gStyle->SetStatX(0.9);
+    gStyle->SetStatY(0.9);
+
+  Int_t nbins  = 100;
+  Float_t mindist = 0.0;
+  Float_t maxdist = 400.0;
+  
+  TH1F* histStarsDintances = new TH1F("StarsDintances","Distance between stars",nbins,mindist,maxdist);
+  histStarsDintances->SetXTitle("Distance [mm]");
+  histStarsDintances->SetYTitle("Counts [#]");
+  TH1F* histStarsDintances1 = new TH1F("StarsDintances1","Distance between stars",nbins,mindist,maxdist);
+  TH1F* histStarsDintances2 = new TH1F("StarsDintances2","Distance between stars [1]-[3]",nbins,mindist,maxdist);
+  TH1F* histStarsDintances3 = new TH1F("StarsDintances3","Distance between stars [2]-[3]",nbins,mindist,maxdist);
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MStarLocalCam starcam;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&starcam);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+
+  MGeomApply geomapl;
+  TString continuoslightfile = 
+    //    "/home/Javi/mnt_magic_data/CaCo/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+        "/nfs/magic/CaCodata/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+
+  Float_t mindc = 0.7;
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 5;
+  const Short_t x[numblind] = { 47, 124, 470, 475, 571};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 4.0;
+  UInt_t integratedevents = 1;
+
+  MFindStars findstars;
+  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal);
+  tlist.AddToList(&findstars, "Currents");
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+//   MProgressBar bar;
+//   evtloop.SetProgressBar(&bar);
+  
+  //
+  // Execute your analysis
+  //
+  
+//   if (!evtloop.Eventloop(numEvents))
+//     return;
+
+  if (!evtloop.PreProcess())
+    return;
+
+  Float_t maxchindof = 4.;
+  
+  while (tlist.Process())
+    {
+  
+      Int_t numStars = starcam.GetNumStars();
+      if ( numStars == 3)
+        {
+          
+          for (Int_t first=0; first<numStars; first++)
+            {
+              if (starcam[first].GetChiSquareNdof()>0. && starcam[first].GetChiSquareNdof()<maxchindof)
+                {
+                  for (Int_t second=first+1; second<numStars; second++)
+                    {
+                      if (starcam[second].GetChiSquareNdof()>0. && starcam[second].GetChiSquareNdof()<maxchindof)
+                        {
+                          Float_t dist = TMath::Sqrt((starcam[first].GetMeanX()-starcam[second].GetMeanX())*
+                                                     (starcam[first].GetMeanX()-starcam[second].GetMeanX()) +
+                                                     (starcam[first].GetMeanY()-starcam[second].GetMeanY())*
+                                                     (starcam[first].GetMeanY()-starcam[second].GetMeanY()));
+
+                            histStarsDintances->Fill(dist);
+                          if (first == 0 && second == 1)
+                            histStarsDintances1->Fill(dist);
+                          else if (first == 0 && second == 2)
+                            histStarsDintances2->Fill(dist);
+                          else if (first == 1 && second == 2)
+                            histStarsDintances3->Fill(dist);
+
+                        }
+                    }
+                }
+            }
+        }
+    }
+  
+  
+
+  evtloop.PostProcess();
+
+  tlist.PrintStatistics();
+
+  //Draw results
+
+  //   histStarsDintances->Draw();
+
+// Creates a Root function based on function fitf above
+   TF1 *func = new TF1("fitfunc",fitfunc,mindist,maxdist,7);
+
+// Sets initial values and parameter names
+   func->SetParNames("ConvF","Max0","Sig0","Max1","Sig1","Max2","Sig2");
+   func->SetParameters(300.,500.,5.,500.,5.,500.,5.);
+
+// Fit histogram in range defined by function
+   histStarsDintances->Fit("fitfunc","R");
+
+//   histStarsDintances1->Draw();
+//   histStarsDintances2->Fit("gaus","0");
+//   histStarsDintances2->Draw("same");
+//   histStarsDintances2->Fit("gaus","0");
+//   histStarsDintances3->Draw("same");
+//   histStarsDintances3->Fit("gaus","0");
+
+  if (!HandleInput())
+
+  delete histStarsDintances;
+  delete histStarsDintances1;
+  delete histStarsDintances2;
+  delete histStarsDintances3;
+  
+}
+
+Double_t fitfunc(Double_t *x, Double_t *par)
+{
+  Double_t dist[3] = 
+    {
+      0.64,0.750,1.203
+    };
+  
+  
+   Double_t fitval = 
+     par[1]*TMath::Exp(-0.5*(x[0]-par[0]*dist[0])*(x[0]-par[0]*dist[0])/(par[2]*par[2])) +
+     par[3]*TMath::Exp(-0.5*(x[0]-par[0]*dist[1])*(x[0]-par[0]*dist[1])/(par[4]*par[4])) +
+     par[5]*TMath::Exp(-0.5*(x[0]-par[0]*dist[2])*(x[0]-par[0]*dist[2])/(par[6]*par[6]));
+
+   //   cout << "x "  << x[0] << " fitval " << fitval << endl;
+   
+
+   return fitval;
+}
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/findstars.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/findstars.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/findstars.C	(revision 9772)
@@ -0,0 +1,175 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 05/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+
+void findstars(const TString filename="20040422_*_D_Mrk421_E.root", const TString directory="/local_disk/Data/rootdata/Mrk421/Period016/2004_04_22/", const UInt_t numEvents = 0)
+{
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MStarLocalCam starcam;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&starcam);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+
+  MGeomApply geomapl;
+  TString continuoslightfile = 
+    "/local_disk/CaCoData/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+
+  Float_t mindc = 0.9; //[uA]
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 5;
+  const Short_t x[numblind] = { 47, 124, 470, 475, 571};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 3.5;
+  UInt_t integratedevents = 4;
+
+  MFindStars findstars;
+  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+
+  
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal);
+  tlist.AddToList(&findstars, "Currents");
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  //
+  // Execute your analysis
+  //
+
+  if (numEvents > 0)
+  {
+      if (!evtloop.Eventloop(numEvents))
+	  return;
+  }
+  else
+  {
+      if (!evtloop.PreProcess())
+	  return;
+      
+//        MHCamera display0(geomcam);
+//        display0.SetPrettyPalette();
+//        display0.Draw();
+//        //       display0.SetCamContent(dccal.GetDisplay());
+//        display0.SetCamContent(dccal.GetDCCalibrationFactor());
+//        gPad->Modified();
+//        gPad->Update();
+
+//        // Remove the comments if you want to go through the file
+//        // event-by-event:
+//        if (!HandleInput())
+//          break;
+
+       MHCamera display(geomcam);
+       display.SetPrettyPalette();
+       display.Draw();
+       gPad->cd(1);
+       starcam.Draw();
+      
+       UInt_t numevents=0;
+       
+       while (tlist.Process())
+         {
+           numevents++;
+           if (numevents%integratedevents==0)
+             {
+               //               display.SetCamContent(dccam);
+               display.SetCamContent(findstars.GetDisplay());
+               gPad->Modified();
+               gPad->Update();
+               starcam.Print("maxpossizechi");
+               // Remove the comments if you want to go through the file
+               // event-by-event:
+               if (!HandleInput())
+                 break;
+             }
+      } 
+
+      evtloop.PostProcess();
+  }
+
+  tlist.PrintStatistics();
+
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/hillasONOFF.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/hillasONOFF.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/hillasONOFF.C	(revision 9772)
@@ -0,0 +1,1339 @@
+/////////////////////////////////////////////////////////////////////////////
+//
+//           _____Macro for checking the hillas parameters_____
+//
+//                       Ester Aliu  <aliu@ifae.es>
+////////////////////////////////////////////////////////////////////////////
+void hillasONOFF()
+{    
+    // general settings
+    gROOT->Reset();
+    gStyle->SetCanvasColor(0);
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetPadBorderMode(0);
+    gStyle->SetFrameBorderMode(0);
+    gStyle->SetOptStat(kFALSE);
+    // gStyle->SetTitleSize(0);
+    gStyle->SetStatColor(0);
+    gStyle->SetStatBorderSize(1);
+    gStyle->SetStatW(0.2);
+    gStyle->SetStatH(0.1);
+    gStyle->SetStatX(0.9);
+    gStyle->SetStatY(0.9);
+ 
+       
+    // define file, tree, canvas
+    TChain* t= new TChain("Parameters");
+    //    t->AddFile("/local_disk/jrico/hillas/hillasOn21.root");
+    //    t->AddFile("/local_disk/jrico/hillas/hillasOn22.root");
+    t->AddFile("/local_disk/jrico/hillas/RFOnnoAlpha.root");
+    
+    // define file, tree, canvas
+    TChain *t2 = new TChain("Parameters");
+    //    t2->AddFile("/local_disk/jrico/hillas/hillasOff09.root");
+    //    t2->AddFile("/local_disk/jrico/hillas/hillasOff18.root");
+    //    t2->AddFile("/local_disk/jrico/hillas/hillasOff21.root");
+    t2->AddFile("/local_disk/jrico/hillas/RFOffnoAlpha.root");
+
+   
+    TString psname="hillasonoff.ps";
+    TString title;
+
+    TH1F* hLength; 
+    TH1F* hWidth; 
+    TH1F* hDist;
+    TH1F* hConc;
+    TH1F* hConc1;
+    TH1F* hConc6;
+    TH1F* hAlpha; 
+    TH1F* hSize; 
+
+    TH2F *hXY;
+
+    // define aliases
+    t->SetAlias("length","MHillas.fLength*0.6/189");
+    t->SetAlias("width","MHillas.fWidth*0.6/189");
+    t->SetAlias("dist","MHillasSrc.fDist*0.6/189");
+    t->SetAlias("conc","MNewImagePar.fConc");
+    t->SetAlias("conc1","MNewImagePar.fConc1");
+    t->SetAlias("conc6","MConcentration.fConc[6]");
+    t->SetAlias("size","MHillas.fSize");
+    t->SetAlias("alpha","abs(MHillasSrc.fAlpha)");
+    t->SetAlias("meanx","MHillas.fMeanX");
+    t->SetAlias("meany","MHillas.fMeanY");
+
+    // define aliases
+    t2->SetAlias("length","MHillas.fLength*0.6/189");
+    t2->SetAlias("width","MHillas.fWidth*0.6/189");
+    t2->SetAlias("dist","MHillasSrc.fDist*0.6/189");
+    t2->SetAlias("conc","MNewImagePar.fConc");
+    t2->SetAlias("conc1","MNewImagePar.fConc1");
+    t2->SetAlias("conc6","MConcentration.fConc[6]");
+    t2->SetAlias("size","MHillas.fSize");
+    t2->SetAlias("alpha","abs(MHillasSrc.fAlpha)");
+    t2->SetAlias("meanx","MHillas.fMeanX");
+    t2->SetAlias("meany","MHillas.fMeanY");
+
+      
+    // define  cuts
+    const char* cut1 = "size>500 && MHadronness.fHadronness<0.1";
+    const char* cut2 = "size>1000";
+    const char* cut3 = "size>2000";
+    const char* cut4 = "size>5000";
+    const char* cut5 = "size>10000";
+
+    const char* cutDist = "MHillasSrc.fDist*0.6/189.>0.2 && MHillasSrc.fDist*0.6/189.<0.8";
+
+
+    /*****************************************************************
+    ****                         PLOTS                            ****
+    *****************************************************************/
+    
+    Int_t nbin;
+    Float_t min;
+    Float_t max;
+
+
+    TString openpsname;
+    openpsname = psname + "(";
+
+    TString closepsname;
+    closepsname = psname  + ")";
+
+
+    //////////////////////////////////////////////////////////////
+    //                    Cuts in Size
+    //////////////////////////////////////////////////////////////
+    TCanvas *c1 = new TCanvas("c1","c1",500,800);
+    c1->Divide(2,3);
+    /////////////////////////////////////////////////////////////////
+
+    char* var="length>>hLength";    
+
+    nbin = 40; min = 0.; max = 1.;
+
+    c1->cd(1);
+    c1->GetPad(1)->SetGrid();    
+    title = "length " ;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t->Draw(var, "","goff");  
+    hLength->SetXTitle("degrees");
+    hLength->SetNormFactor(1.);
+    hLength->Draw("Ehist");
+    c1->GetPad(1)->Update();    
+    
+    c1->cd(2);
+    c1->GetPad(2)->SetGrid();    
+    title = "length ";  
+    title = title + cut1;
+    hLength = new TH1F("hLength",title, nbin, min, max);
+    t->Draw(var,cut1,"goff");
+    hLength->SetXTitle("degrees");
+    hLength->SetNormFactor(1.);
+    hLength->Draw("Ehist");    
+    c1->GetPad(2)->Update();
+  
+    c1->cd(3);
+    c1->GetPad(3)->SetGrid();    
+    title = "length ";  
+    title = title + cut2;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t->Draw(var,cut2,"goff");
+    hLength->SetXTitle("degrees");
+    hLength->SetNormFactor(1.);
+    hLength->Draw("Ehist");
+    c1->GetPad(3)->Update();
+  
+    c1->cd(4);
+    c1->GetPad(4)->SetGrid();    
+    title = "length ";  
+    title = title + cut3;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t->Draw(var,cut3, "goff");
+    hLength->SetXTitle("degrees");
+    hLength->SetNormFactor(1.);
+    hLength->Draw("Ehist");
+    c1->GetPad(4)->Update();
+        
+    c1->cd(5);
+    c1->GetPad(5)->SetGrid();    
+    title = "length ";  
+    title = title + cut4;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t->Draw(var,cut4, "goff");
+    hLength->SetXTitle("degrees");
+    hLength->SetNormFactor(1.);
+    hLength->Draw("Ehist");
+    c1->GetPad(5)->Update();
+        
+    c1->cd(6);
+    c1->GetPad(6)->SetGrid();    
+    title = "length ";  
+    title = title + cut5;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t->Draw(var,cut5, "goff");
+    hLength->SetXTitle("degrees");
+    hLength->SetNormFactor(1.);
+    hLength->Draw("Ehist");
+    c1->GetPad(6)->Update();
+   
+    //off data
+
+    c1->cd(1);
+    title = "length " ;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t2->Draw(var, "","goff");  
+    hLength->SetXTitle("degrees");
+    //hLength->SetLineStyle(2);
+    hLength->SetMarkerStyle(20);
+    hLength->SetMarkerSize(0.4);
+    hLength->SetNormFactor(1);
+    hLength->Draw("samePE");
+    c1->GetPad(1)->Modified();    
+    c1->GetPad(1)->Update();    
+    
+    c1->cd(2);
+    title = "length ";  
+    title = title + cut1;
+    hLength = new TH1F("hLength",title, nbin, min, max);
+    t2->Draw(var,cut1,"goff");
+    hLength->SetXTitle("degrees");
+    //hLength->SetLineStyle(2);
+    hLength->SetMarkerSize(0.4);
+    hLength->SetMarkerStyle(20);
+    hLength->SetNormFactor(1);
+    hLength->Draw("samePE");    
+    c1->GetPad(2)->Modified();    
+    c1->GetPad(2)->Update();
+  
+    c1->cd(3);
+    title = "length ";  
+    title = title + cut2;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t2->Draw(var,cut2,"goff");
+    //hLength->SetXTitle("degrees");
+    hLength->SetMarkerSize(0.4);
+    hLength->SetMarkerStyle(20);
+    //hLength->SetLineStyle(2);
+    hLength->SetNormFactor(1);
+    hLength->Draw("samePE");
+    c1->GetPad(3)->Modified();    
+    c1->GetPad(3)->Update();
+  
+    c1->cd(4);
+    title = "length ";  
+    title = title + cut3;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t2->Draw(var,cut3, "goff");
+    hLength->SetXTitle("degrees");
+    //    hLength->SetLineStyle(2);
+    hLength->SetMarkerStyle(20);
+    hLength->SetMarkerSize(0.4);
+    hLength->SetNormFactor(1);
+    hLength->Draw("samePE");
+    c1->GetPad(4)->Modified();    
+    c1->GetPad(4)->Update();
+        
+    c1->cd(5);
+    title = "length ";  
+    title = title + cut4;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t2->Draw(var,cut4, "goff");
+    hLength->SetXTitle("degrees");
+    //hLength->SetLineStyle(2);
+    hLength->SetMarkerStyle(20);
+    hLength->SetMarkerSize(0.4);
+    hLength->SetNormFactor(1);
+    hLength->Draw("samePE");
+    c1->GetPad(5)->Modified();    
+    c1->GetPad(5)->Update();
+        
+    c1->cd(6);
+    title = "length ";  
+    title = title + cut5;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t2->Draw(var,cut5, "goff");
+    hLength->SetXTitle("degrees");
+    // hLength->SetLineStyle(2);
+    hLength->SetMarkerStyle(20);
+    hLength->SetMarkerSize(0.4);
+    hLength->SetNormFactor(1);
+    hLength->Draw("samePE");
+    c1->GetPad(6)->Modified();    
+    c1->GetPad(6)->Update();
+    
+    c1->Print(openpsname); 
+
+    /////////////////////////////////////////////////////////////////
+    char* var="width>>hWidth";
+
+    nbin = 40; min = 0.; max = 0.8;
+
+    c1->cd(1);
+    title = "width ";  
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t->Draw(var, "", "goff");
+    hWidth->SetXTitle("degrees");
+    hWidth->SetNormFactor(1.);
+    hWidth->Draw("Ehist");
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "width ";  
+    title = title + cut1;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t->Draw(var,cut1, "goff");
+    hWidth->SetXTitle("degrees");
+    hWidth->SetNormFactor(1.);
+    hWidth->Draw("Ehist");    
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "width ";  
+    title = title + cut2;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t->Draw(var,cut2, "goff");
+    hWidth->SetXTitle("degrees");
+    hWidth->SetNormFactor(1.);
+    hWidth->Draw("Ehist");
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "width ";  
+    title = title + cut3;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t->Draw(var,cut3, "goff");
+    hWidth->SetXTitle("degrees");
+    hWidth->SetNormFactor(1.);
+    hWidth->Draw("Ehist");
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "width ";  
+    title = title + cut4;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t->Draw(var,cut4, "goff");
+    hWidth->SetXTitle("degrees");
+    hWidth->SetNormFactor(1.);
+    hWidth->Draw("Ehist");
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "width ";  
+    title = title + cut5;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t->Draw(var,cut5, "goff");
+    hWidth->SetXTitle("degrees");
+    hWidth->SetNormFactor(1.);
+    hWidth->Draw("Ehist");
+    c1->GetPad(6)->Update();
+
+    // offdata
+   
+    c1->cd(1);
+    title = "width ";  
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t2->Draw(var, "", "goff");
+    hWidth->SetXTitle("degrees");
+    //hWidth->SetLineStyle(2);
+    hWidth->SetMarkerStyle(20);
+    hWidth->SetMarkerSize(0.4);
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("samePE");
+    c1->GetPad(1)->Modified();    
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "width ";  
+    title = title + cut1;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t2->Draw(var,cut1, "goff");
+    hWidth->SetXTitle("degrees");
+    //hWidth->SetLineStyle(2);
+    hWidth->SetMarkerStyle(20);
+    hWidth->SetMarkerSize(0.4);
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("samePE");    
+    c1->GetPad(2)->Modified();    
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "width ";  
+    title = title + cut2;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t2->Draw(var,cut2, "goff");
+    hWidth->SetXTitle("degrees");
+    //hWidth->SetLineStyle(2);
+    hWidth->SetMarkerStyle(20);
+    hWidth->SetMarkerSize(0.4);
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("samePE");
+    c1->GetPad(3)->Modified();    
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "width ";  
+    title = title + cut3;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t2->Draw(var,cut3, "goff");
+    hWidth->SetXTitle("degrees");
+    //hWidth->SetLineStyle(2);
+    hWidth->SetMarkerStyle(20);
+    hWidth->SetMarkerSize(0.4);
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("samePE");
+    c1->GetPad(4)->Modified();    
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "width ";  
+    title = title + cut4;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t2->Draw(var,cut4, "goff");
+    hWidth->SetXTitle("degrees");
+    // hWidth->SetLineStyle(2);
+    hWidth->SetMarkerStyle(20);
+    hWidth->SetMarkerSize(0.4);
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("samePE");
+    c1->GetPad(5)->Modified();    
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "width ";  
+    title = title + cut5;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t2->Draw(var,cut5, "goff");
+    hWidth->SetXTitle("degrees");
+    //hWidth->SetLineStyle(2);
+    hWidth->SetMarkerStyle(20);
+    hWidth->SetMarkerSize(0.4);
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("samePE");
+    c1->GetPad(6)->Modified();    
+    c1->GetPad(6)->Update();
+
+   
+    c1->Print(psname); 
+ 
+    /////////////////////////////////////////////////////////////////
+
+    char* var="dist>>hDist";
+      
+    nbin = 40; min = 0.; max = 1.6;
+
+    c1->cd(1);
+    title = "dist ";  
+    hDist = new TH1F("hDist",title,nbin, min, max);   
+    t->Draw(var, "", "goff");
+    hDist->SetXTitle("degrees");
+    hDist->SetNormFactor(1.);
+    hDist->Draw("Ehist");
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "dist ";  
+    title = title + cut1;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t->Draw(var,cut1, "goff");
+    hDist->SetXTitle("degrees");
+    hDist->SetNormFactor(1.);
+    hDist->Draw("Ehist");    
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "dist ";  
+    title = title + cut2;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t->Draw(var,cut2, "goff");
+    hDist->SetXTitle("degrees");
+    hDist->SetNormFactor(1.);
+    hDist->Draw("Ehist");
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "dist ";  
+    title = title + cut3;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t->Draw(var,cut3, "goff");
+    hDist->SetXTitle("degrees");
+    hDist->SetNormFactor(1.);
+    hDist->Draw("Ehist");
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "dist ";  
+    title = title + cut4;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t->Draw(var,cut4, "goff");
+    hDist->SetXTitle("degrees");
+    hDist->SetNormFactor(1.);
+    hDist->Draw("Ehist");
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "dist ";  
+    title = title + cut5;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t->Draw(var,cut5,"goff");
+    hDist->SetXTitle("degrees");
+    hDist->SetNormFactor(1.);
+    hDist->Draw("Ehist");
+    c1->GetPad(6)->Update();
+
+    //offdata
+
+    c1->cd(1);
+    title = "dist ";  
+    hDist = new TH1F("hDist",title,nbin, min, max);   
+    t2->Draw(var, "", "goff");
+    hDist->SetXTitle("degrees");
+    //hDist->SetLineStyle(2);
+    hDist->SetMarkerStyle(20);
+    hDist->SetMarkerSize(0.4);
+    hDist->SetNormFactor(1);
+    hDist->Draw("samePE");
+    c1->GetPad(1)->Modified();    
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "dist ";  
+    title = title + cut1;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t2->Draw(var,cut1, "goff");
+    hDist->SetXTitle("degrees");
+    //hDist->SetLineStyle(2);
+    hDist->SetMarkerStyle(20);
+    hDist->SetMarkerSize(0.4);
+    hDist->SetNormFactor(1);
+    hDist->Draw("samePE");    
+    c1->GetPad(2)->Modified();    
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "dist ";  
+    title = title + cut2;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t2->Draw(var,cut2, "goff");
+    hDist->SetXTitle("degrees");
+    //hDist->SetLineStyle(2);
+    hDist->SetMarkerStyle(20);
+    hDist->SetMarkerSize(0.4);   
+    hDist->SetNormFactor(1);
+    hDist->Draw("samePE");
+    c1->GetPad(3)->Modified();    
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "dist ";  
+    title = title + cut3;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t2->Draw(var,cut3, "goff");
+    hDist->SetXTitle("degrees");
+    //hDist->SetLineStyle(2);
+    hDist->SetMarkerStyle(20);
+    hDist->SetMarkerSize(0.4);
+    hDist->SetNormFactor(1);
+    hDist->Draw("samePE");
+    c1->GetPad(4)->Modified();    
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "dist ";  
+    title = title + cut4;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t2->Draw(var,cut4, "goff");
+    hDist->SetXTitle("degrees");
+    //hDist->SetLineStyle(2);
+    hDist->SetMarkerStyle(20);
+    hDist->SetMarkerSize(0.4);
+    hDist->SetNormFactor(1);
+    hDist->Draw("samePE");
+    c1->GetPad(5)->Modified();    
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "dist ";  
+    title = title + cut5;
+    hDist = new TH1F("hDist",title,nbin, min, max);
+    t2->Draw(var,cut5,"goff");
+    hDist->SetXTitle("degrees");
+    //hDist->SetLineStyle(2);
+    hDist->SetMarkerStyle(20);
+    hDist->SetMarkerSize(0.4);
+    hDist->SetNormFactor(1);
+    hDist->Draw("samePE");
+    c1->GetPad(6)->Modified();    
+    c1->GetPad(6)->Update();
+
+    c1->Print(psname); 
+
+    /////////////////////////////////////////////////////////////////
+    char* var="conc>>hConc";
+
+    nbin = 40; min = 0.; max = 1.;
+
+    c1->cd(1);
+    title = "conc ";  
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t->Draw(var,"","goff");
+    hConc->SetNormFactor(1.);
+    hConc->Draw("Ehist");
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "conc ";  
+    title = title + cut1;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t->Draw(var,cut1,"goff");    
+    hConc->SetNormFactor(1.);
+    hConc->Draw("Ehist");
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "conc ";  
+    title = title + cut2;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t->Draw(var,cut2,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->Draw("Ehist");
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "conc ";  
+    title = title + cut3;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t->Draw(var,cut3,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->Draw("Ehist");
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "conc ";  
+    title = title + cut4;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t->Draw(var,cut4,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->Draw("Ehist");
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "conc ";  
+    title = title + cut5;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t->Draw(var,cut5,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->Draw("Ehist");
+    c1->GetPad(6)->Update();
+  
+    //offdata 
+
+    c1->cd(1);
+    title = "conc ";  
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t2->Draw(var, "","goff");
+    hConc->SetNormFactor(1.);
+    //hConc->SetLineStyle(2);
+    hConc->SetMarkerStyle(20);
+    hConc->SetMarkerSize(0.4);
+    hConc->Draw("samePE");
+    c1->GetPad(1)->Modified();    
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "conc ";  
+    title = title + cut1;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t2->Draw(var,cut1,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->SetMarkerStyle(20);
+    hConc->SetMarkerSize(0.4);
+    // hConc->SetLineStyle(2);
+    hConc->Draw("samePE");
+    c1->GetPad(2)->Modified();        
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "conc ";  
+    title = title + cut2;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t2->Draw(var,cut2,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->SetMarkerStyle(20);
+    hConc->SetMarkerSize(0.4);
+    //hConc->SetLineStyle(2);
+    hConc->Draw("samePE");
+    c1->GetPad(3)->Modified();    
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "conc ";  
+    title = title + cut3;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t2->Draw(var,cut3,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->SetMarkerStyle(20);
+    hConc->SetMarkerSize(0.4);
+    //hConc->SetLineStyle(2);
+    hConc->Draw("samePE");
+    c1->GetPad(4)->Modified();    
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "conc ";  
+    title = title + cut4;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t2->Draw(var,cut4,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->SetMarkerStyle(20);
+    hConc->SetMarkerSize(0.4);
+    //hConc->SetLineStyle(2);
+    hConc->Draw("samePE");
+    c1->GetPad(5)->Modified();    
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "conc ";  
+    title = title + cut5;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t2->Draw(var,cut5,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->SetMarkerStyle(20);
+    hConc->SetMarkerSize(0.4);
+    //hConc->SetLineStyle(2);
+    hConc->Draw("samePE");
+    c1->GetPad(6)->Modified();    
+    c1->GetPad(6)->Update();
+  
+    c1->Print(psname); 
+
+    /////////////////////////////////////////////////////////////////
+    char* var="conc6>>hConc6";
+
+    nbin = 40; min = 0.; max = 1.;
+
+    c1->cd(1);
+    title = "conc6 ";  
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t->Draw(var,"","goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("Ehist");
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "conc6 ";  
+    title = title + cut1;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t->Draw(var,cut1,"goff");  
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("Ehist");  
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "conc6 ";  
+    title = title + cut2;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t->Draw(var,cut2,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("Ehist");
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "conc6 ";  
+    title = title + cut3;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t->Draw(var,cut3,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("Ehist");
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "conc6 ";  
+    title = title + cut4;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t->Draw(var,cut4,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("Ehist");
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "conc6 ";  
+    title = title + cut5;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t->Draw(var,cut5,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("Ehist");
+    c1->GetPad(6)->Update();
+
+    //offdata
+
+    c1->cd(1);
+    title = "conc6 ";  
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t2->Draw(var,"","goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->SetMarkerStyle(20);
+    hConc6->SetMarkerSize(0.4);
+    //hConc6->SetLineStyle(2);
+    hConc6->Draw("samePE");
+    c1->GetPad(1)->Modified();    
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "conc6 ";  
+    title = title + cut1;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t2->Draw(var,cut1,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->SetMarkerStyle(20);
+    hConc6->SetMarkerSize(0.4);
+    //hConc6->SetLineStyle(2);
+    hConc6->Draw("samePE");
+    c1->GetPad(2)->Modified();        
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "conc6 ";  
+    title = title + cut2;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t2->Draw(var,cut2,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->SetMarkerStyle(20);
+    hConc6->SetMarkerSize(0.4);
+    //hConc6->SetLineStyle(2);
+    hConc6->Draw("samePE");
+    c1->GetPad(3)->Modified();    
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "conc6 ";  
+    title = title + cut3;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t2->Draw(var,cut3,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->SetMarkerStyle(20);
+    hConc6->SetMarkerSize(0.4);
+    //hConc6->SetLineStyle(2);
+    hConc6->Draw("samePE");
+    c1->GetPad(4)->Modified();    
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "conc6 ";  
+    title = title + cut4;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t2->Draw(var,cut4,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->SetMarkerStyle(20);
+    hConc6->SetMarkerSize(0.4);
+    // hConc6->SetLineStyle(2);
+    hConc6->Draw("samePE");
+    c1->GetPad(5)->Modified();    
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "conc6 ";  
+    title = title + cut5;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t2->Draw(var,cut5,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->SetMarkerStyle(20);
+    hConc6->SetMarkerSize(0.4);
+    //hConc6->SetLineStyle(2);
+    hConc6->Draw("samePE");
+    c1->GetPad(6)->Modified();    
+    c1->GetPad(6)->Update();
+
+    c1->Print(psname); 
+
+    /////////////////////////////////////////////////////////////////
+    char* var="alpha>>hAlpha";
+
+    nbin = 18; min = 0.; max = 90.;
+    
+    c1->cd(1);
+    title = "alpha ";  
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t->Draw(var, "", "goff");
+    hAlpha->SetXTitle("degrees");
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("Ehist");
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "alpha ";  
+    title = title + cut1;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t->Draw(var,cut1, "goff");
+    hAlpha->SetXTitle("degrees");
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("Ehist");    
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "alpha ";  
+    title = title + cut2;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t->Draw(var,cut2, "goff");
+    hAlpha->SetXTitle("degrees");
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("Ehist");
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "alpha ";  
+    title = title + cut3;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t->Draw(var,cut3, "goff");
+    hAlpha->SetXTitle("degrees");
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("Ehist");
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "alpha ";  
+    title = title + cut4;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t->Draw(var,cut4, "goff");
+    hAlpha->SetXTitle("degrees");
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("Ehist");
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "alpha ";  
+    title = title + cut5;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t->Draw(var,cut5, "goff");
+    hAlpha->SetXTitle("degrees");
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("Ehist");
+    c1->GetPad(6)->Update();
+
+    //offdata
+
+    c1->cd(1);
+    title = "alpha ";  
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t2->Draw(var, "", "goff");
+    hAlpha->SetXTitle("degrees");
+    //hAlpha->SetLineStyle(2);
+    hAlpha->SetNormFactor(1);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.4);
+    hAlpha->Draw("samePE");
+    c1->GetPad(1)->Modified();    
+    c1->GetPad(1)->Update();    
+
+    c1->cd(2);
+    title = "alpha ";  
+    title = title + cut1;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t2->Draw(var,cut1, "goff");
+    hAlpha->SetXTitle("degrees");
+    //hAlpha->SetLineStyle(2);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.4);
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("samePE");    
+    c1->GetPad(2)->Modified();    
+    c1->GetPad(2)->Update();
+    
+    c1->cd(3);
+    title = "alpha ";  
+    title = title + cut2;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t2->Draw(var,cut2, "goff");
+    hAlpha->SetXTitle("degrees");
+    //hAlpha->SetLineStyle(2);
+    hAlpha->SetNormFactor(1);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.4);
+    hAlpha->Draw("samePE");
+    c1->GetPad(3)->Modified();    
+    c1->GetPad(3)->Update();
+    
+    c1->cd(4);
+    title = "alpha ";  
+    title = title + cut3;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t2->Draw(var,cut3, "goff");
+    hAlpha->SetXTitle("degrees");
+    //hAlpha->SetLineStyle(2);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.4);
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("samePE");
+    c1->GetPad(4)->Modified();    
+    c1->GetPad(4)->Update();
+    
+    c1->cd(5);
+    title = "alpha ";  
+    title = title + cut4;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t2->Draw(var,cut4, "goff");
+    hAlpha->SetXTitle("degrees");
+    //hAlpha->SetLineStyle(2);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.4);
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("samePE");
+    c1->GetPad(5)->Modified();    
+    c1->GetPad(5)->Update();
+    
+    c1->cd(6);
+    title = "alpha ";  
+    title = title + cut5;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t2->Draw(var,cut5, "goff");
+    hAlpha->SetXTitle("degrees");
+    //hAlpha->SetLineStyle(2);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.4);
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("samePE");
+    c1->GetPad(6)->Modified();    
+    c1->GetPad(6)->Update();
+
+    c1->Print(psname); 
+
+    /////////////////////////////////////////////////////////////////
+    //                     Cuts in Dist
+    /////////////////////////////////////////////////////////////////
+
+    TCanvas *c2 = new TCanvas("c2","Cuts in Dist",500,800);
+    c2->Divide(2,3);
+    /////////////////////////////////////////////////////////////////
+    char* var="length>>hLength";
+
+    nbin = 40; min = 0.; max = 1.;
+
+    c2->cd(1);
+    //    c2->GetPad(1)->SetGrid();    
+    title = "length "; 
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t->Draw(var, "", "goff");
+    hLength->SetXTitle("degrees");
+    hLength->SetNormFactor(1);
+    hLength->Draw("Ehist");
+    c2->GetPad(1)->Update();
+ 
+    c2->cd(2);
+    //c2->GetPad(2)->SetGrid();    
+    title = "length ";  
+    title = title + cutDist;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t->Draw(var,cutDist, "goff");
+    hLength->SetXTitle("degrees");
+    hLength->SetNormFactor(1);
+    hLength->Draw("Ehist");
+    c2->GetPad(2)->Update();
+
+    //offdata
+        
+    c2->cd(1);
+    c2->GetPad(1)->SetGrid();    
+    title = "length "; 
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t2->Draw(var, "", "goff");
+    hLength->SetXTitle("degrees");
+    //   hLength->SetLineStyle(2);
+    hLength->SetMarkerStyle(20);
+    hLength->SetMarkerSize(0.4);
+    hLength->SetNormFactor(1);
+    hLength->Draw("samePE");
+    c2->GetPad(1)->Modified();    
+    c2->GetPad(1)->Update();
+ 
+    c2->cd(2);
+    c2->GetPad(2)->SetGrid();    
+    title = "length ";  
+    title = title + cutDist;
+    hLength = new TH1F("hLength",title,nbin, min, max);
+    t2->Draw(var,cutDist, "goff");
+    hLength->SetXTitle("degrees");
+    hLength->SetMarkerStyle(20);
+    hLength->SetMarkerSize(0.4);
+    //hLength->SetLineStyle(2);
+    hLength->SetNormFactor(1);
+    hLength->Draw("samePE");
+    c2->GetPad(1)->Modified();    
+    c2->GetPad(2)->Update();
+
+    /////////////////////////////////////////////////////////////////
+    char* var="width>>hWidth";
+
+    nbin = 40; min = 0.; max = 1.;
+
+    c2->cd(3);
+    c2->GetPad(3)->SetGrid();    
+    title = "width ";  
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t->Draw(var, "", "goff");
+    hWidth->SetXTitle("degrees");
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("Ehist");
+    c2->GetPad(3)->Update();
+    
+    c2->cd(4);
+    c2->GetPad(4)->SetGrid();    
+    title = "width ";  
+    title = title + cutDist;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t->Draw(var,cutDist, "goff");
+    hWidth->SetXTitle("degrees");
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("Ehist");
+    c2->GetPad(4)->Update();
+    
+    //offdata
+
+    c2->cd(3);
+    c2->GetPad(3)->SetGrid();    
+    title = "width ";  
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t2->Draw(var, "", "goff");
+    hWidth->SetXTitle("degrees");
+    //hWidth->SetLineStyle(2);
+    hWidth->SetMarkerStyle(20);
+    hWidth->SetMarkerSize(0.4);
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("samePE");
+    c2->GetPad(3)->Modified();    
+    c2->GetPad(3)->Update();
+    
+    c2->cd(4);
+    c2->GetPad(4)->SetGrid();    
+    title = "width ";  
+    title = title + cutDist;
+    hWidth = new TH1F("hWidth",title,nbin, min, max);
+    t2->Draw(var,cutDist, "goff");
+    hWidth->SetXTitle("degrees");
+    //hWidth->SetLineStyle(2);
+    hWidth->SetMarkerStyle(20);
+    hWidth->SetMarkerSize(0.4);
+    hWidth->SetNormFactor(1);
+    hWidth->Draw("samePE");
+    c2->GetPad(4)->Modified();    
+    c2->GetPad(4)->Update();
+
+    /////////////////////////////////////////////////////////////////
+    char* var="conc>>hConc";
+
+    nbin = 40; min = 0.; max = 1.;
+
+    c2->cd(5);
+    c2->GetPad(5)->SetGrid();    
+    title = "conc ";  
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t->Draw(var,"","goff");
+    hConc->SetNormFactor(1.);
+    hConc->Draw("Ehist");
+    c2->GetPad(5)->Update();
+    
+    c2->cd(6);
+    c2->GetPad(6)->SetGrid();    
+    title = "conc ";  
+    title = title + cutDist;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t->Draw(var,cutDist,"goff");
+    hConc->SetNormFactor(1.);
+    hConc->Draw("Ehist");
+    c2->GetPad(6)->Update();
+    
+    //offdata
+
+    c2->cd(5);
+    c2->GetPad(5)->SetGrid();    
+    title = "conc ";  
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t2->Draw(var,"", "goff");
+    //  hConc->SetLineStyle(2);
+    hConc->SetMarkerStyle(20);
+    hConc->SetMarkerSize(0.4);
+    hConc->SetNormFactor(1.);
+    hConc->Draw("samePE");
+    c2->GetPad(5)->Modified();    
+    c2->GetPad(5)->Update();
+    
+    c2->cd(6);
+    c2->GetPad(6)->SetGrid();    
+    title = "conc ";  
+    title = title + cutDist;
+    hConc = new TH1F("hConc",title,nbin, min, max);
+    t2->Draw(var,cutDist,"goff");
+    //hConc->SetLineStyle(2);
+    hConc->SetMarkerStyle(20);
+    hConc->SetMarkerSize(0.4);
+    hConc->SetNormFactor(1.);
+    hConc->Draw("samePE");
+    c2->GetPad(6)->Modified();    
+    c2->GetPad(6)->Update();
+    
+    c2->Print(psname); 
+
+    /////////////////////////////////////////////////////////////////
+    char* var="conc6>>hConc6";
+
+    nbin = 40; min = 0.; max = 1.;
+
+    c2->cd(1);
+    title = "conc6 ";  
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t->Draw(var,"","goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("Ehist");
+    c2->GetPad(1)->Update();
+    
+    c2->cd(2);
+    title = "conc6 ";  
+    title = title + cutDist;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t->Draw(var,cutDist,"goff");
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("Ehist");
+    c2->GetPad(2)->Update();
+
+    //offdata
+
+    c2->cd(1);
+    title = "conc6 ";  
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t2->Draw(var,"","goff");
+    //hConc6->SetLineStyle(2);
+    hConc6->SetMarkerStyle(20);
+    hConc6->SetMarkerSize(0.4);
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("samePE");
+    c2->GetPad(1)->Modified();    
+    c2->GetPad(1)->Update();
+    
+    c2->cd(2);
+    title = "conc6 ";  
+    title = title + cutDist;
+    hConc6 = new TH1F("hConc6",title,nbin, min, max);
+    t2->Draw(var,cutDist,"goff");
+    // hConc6->SetLineStyle(2);
+    hConc6->SetMarkerStyle(20);
+    hConc6->SetMarkerSize(0.4);
+    hConc6->SetNormFactor(1.);
+    hConc6->Draw("samePE");
+    c2->GetPad(2)->Modified();    
+    c2->GetPad(2)->Update(); 
+  
+    /////////////////////////////////////////////////////////////////
+    char* var="alpha>>hAlpha";
+
+    nbin = 18; min = 0.; max = 90.;
+
+    c2->cd(3);
+    title = "alpha ";  
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t->Draw(var, "", "goff");
+    hAlpha->SetXTitle("degrees");
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("Ehist");
+    c2->GetPad(3)->Update();
+    
+    c2->cd(4);
+    title = "alpha ";  
+    title = title + cutDist;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t->Draw(var,cutDist, "goff");
+    hAlpha->SetXTitle("degrees");
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("Ehist");
+    c2->GetPad(4)->Update();
+   
+    //offdata
+
+    c2->cd(3);
+    title = "alpha ";  
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t2->Draw(var, "", "goff");
+    hAlpha->SetXTitle("degrees");
+    //hAlpha->SetLineStyle(2);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.4);
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("samePE");
+    c2->GetPad(3)->Modified();    
+    c2->GetPad(3)->Update();
+    
+    c2->cd(4);
+    title = "alpha ";  
+    title = title + cutDist;
+    hAlpha = new TH1F("hAlpha",title,nbin, min, max);
+    t2->Draw(var,cutDist, "goff");
+    hAlpha->SetXTitle("degrees");
+    //hAlpha->SetLineStyle(2);
+    hAlpha->SetMarkerStyle(20);
+    hAlpha->SetMarkerSize(0.4);
+    hAlpha->SetNormFactor(1);
+    hAlpha->Draw("samePE");
+    c2->GetPad(4)->Modified();    
+    c2->GetPad(4)->Update();
+
+
+    /////////////////////////////////////////////////////////////////
+    char* var="log10(size)>>hSize";
+
+    nbin = 40; min = 0.5; max = 4.5;
+
+    c2->cd(5);
+    c2->GetPad(5)->SetLogy(); 
+    title = "size ";  
+    hSize = new TH1F("hSize",title,nbin, min, max);
+    t->Draw(var, "1/MHillas.fSize", "goff");
+    hSize->SetNormFactor(1.);
+    hSize->SetXTitle("log10(ADC counts)");
+    hSize->Draw("Ehist");
+    c2->GetPad(5)->Update();
+    
+    c2->cd(6);
+    c2->GetPad(6)->SetLogy(); 
+    title = "size ";  
+    title = title + cutDist;
+    hSize = new TH1F("hSize",title,nbin, min, max);
+    t->Draw(var,"1/MHillas.fSize*(MHillasSrc.fDist*0.6/189.>0.2 && MHillasSrc.fDist*0.6/189<0.8)", "goff");
+    hSize->SetXTitle("log10(ADC counts)");
+    hSize->SetNormFactor(1.);
+    hSize->Draw("Ehist");
+    c2->GetPad(6)->Update(); 
+
+    //offdata
+    c2->cd(5);
+    c2->GetPad(5)->SetLogy(); 
+    title = "size ";  
+    hSize = new TH1F("hSize",title,nbin, min, max);
+    t2->Draw(var, "1/MHillas.fSize", "goff");
+    hSize->SetXTitle("log10(ADC counts)");
+    hSize->SetNormFactor(1.);
+    hSize->SetMarkerStyle(20);
+    hSize->SetMarkerSize(0.4);
+    //hSize->SetLineStyle(2);
+    hSize->Draw("samePE");
+    c2->GetPad(5)->Modified();    
+    c2->GetPad(5)->Update();
+    
+    c2->cd(6);
+    c2->GetPad(6)->SetLogy(); 
+    title = "size ";  
+    title = title + cutDist;
+    hSize = new TH1F("hSize",title,nbin, min, max);
+    t2->Draw(var,"1/MHillas.fSize*(MHillasSrc.fDist*0.6/189.>0.2 && MHillasSrc.fDist*0.6/189<0.8)", "goff");
+    hSize->SetXTitle("log10(ADC counts)");
+    //hSize->SetLineStyle(2);
+    hSize->SetNormFactor(1.);
+    hSize->SetMarkerStyle(20);
+    hSize->SetMarkerSize(0.4);
+    hSize->Draw("samePE");
+    c2->GetPad(6)->Modified();    
+    c2->GetPad(6)->Update(); 
+       
+    c2->Print(closepsname);                                                    
+  
+}
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/hvnotnominal.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/hvnotnominal.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/hvnotnominal.C	(revision 9772)
@@ -0,0 +1,167 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 04/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+
+void hvnotnominal(const TString filename="20040319_20821_D_Mrk421_S.root", const TString directory="/nfs/magic/CaCodata/2004_03_19/", Float_t percent = 0.01)
+{
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+
+  MGeomCamMagic geomcam;
+  MBadPixelsCam badcam;
+  MCameraHV     hvcam;
+
+  // this line is needed because the CC rep rootified file don't have run header,
+  // then the MGeomApply can not initialitaze the containers with the number of 
+  // pixels because this is done in the reinit().
+  badcam.InitSize(geomcam.GetNumPixels());
+  
+  plist.AddToList(&geomcam);
+  plist.AddToList(&badcam);
+  plist.AddToList(&hvcam);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Camera"); 
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCamera.*");
+
+  MGeomApply geomapl;
+  MFHVNotNominal fHVNominal;
+  TString hvnominal = "/mnt/users/jlopez/Mars/Files4Mars/Config/HVSettings_FF35q.conf";
+  fHVNominal.SetHVNominalValues(hvnominal);
+  //  fHVNominal.SetMaxNumPixelsDeviated(10);
+  MContinue cont_hv(&fHVNominal);
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&cont_hv);
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  //
+  // Execute your analysis
+  //
+
+  MHCamera hvnotnominal(geomcam);
+  MHCamera lowhvnotnominal(geomcam);
+  MHCamera uphvnotnominal(geomcam);
+
+  if (!evtloop.PreProcess())
+    return;
+
+  TArrayD nominal = fHVNominal.GetHVNominal();
+  TArrayD lownominal = nominal;
+  TArrayD upnominal = nominal;
+  
+  for (UInt_t pix=0; pix<nominal.GetSize(); pix++)
+    {
+      lownominal[pix] *= (1-percent);
+      upnominal[pix]  *= (1+percent);
+    }
+  
+  
+  while(tlist.Process())
+    {
+      
+      hvnotnominal.CntCamContent(hvcam,lownominal,0,kFALSE);
+      hvnotnominal.CntCamContent(hvcam,upnominal,0,kTRUE);
+      
+      lowhvnotnominal.CntCamContent(hvcam,lownominal,0,kFALSE);
+      uphvnotnominal.CntCamContent(hvcam,upnominal,0,kTRUE);
+    }
+  
+
+  evtloop.PostProcess();
+  
+  tlist.PrintStatistics();
+  
+  TCanvas c1;
+  c1.Divide(2,1);
+  c1.cd(1);
+  lowhvnotnominal.SetPrettyPalette();
+  lowhvnotnominal.Draw();
+  gPad->cd(1);
+  gPad->Modified();
+  gPad->Update();
+  c1.cd(2);
+  uphvnotnominal.SetPrettyPalette();
+  uphvnotnominal.Draw();
+  gPad->cd(2);
+  gPad->Modified();
+  gPad->Update();
+
+  TCanvas c2;
+  hvnotnominal.SetPrettyPalette();
+  hvnotnominal.Draw();
+  gPad->cd(1);
+  gPad->Modified();
+  gPad->Update();
+
+  if (!HandleInput())
+    break;
+
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/lightcurve.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/lightcurve.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/lightcurve.C	(revision 9772)
@@ -0,0 +1,1178 @@
+
+Double_t ChiSquareNDof(TH1D *h1, TH1D *h2);
+Int_t GetBin(Double_t size, Int_t numberSizeBins, Double_t sizeBins[]);
+
+void lightcurve(TString f_on_name = "../HillasFiles/Mrk421/*_H.root", 
+                TString f_off_name = "../HillasFiles/OffMrk421/*_H.root")
+{
+
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+  gStyle->SetTimeOffset(-3600);
+
+  // Configuration
+  const Bool_t debug = kFALSE;
+  const Double_t timebin = 1380.; //[sec]
+  TString psname = "./20040421_Mrk421.1380s.ps";
+
+  //Constanst
+  const Double_t kConvDegToRad = TMath::Pi()/180.;
+  const Double_t kSec = 1e3;  //[sec/milisec]
+  const Double_t kDay = 24.*60.*60.;  //[Day/sec]
+
+  UInt_t numberTimeBins = 1;
+  TArrayI numberOnEvents(1);
+  TArrayD numberOnEventsAfterCleaning(1);
+  TArrayD numberBkgEventsToNormOn(1);
+  TArrayD timeOn(1);
+  
+  TArrayD meanTimeBinOn(1);
+  TArrayD widthTimeBinOn(1);
+
+  TArrayD zenithMinimumOn(1);
+  TArrayD zenithMaximumOn(1);
+
+  TArrayD deadFractionOn(1);
+  
+  TObjArray coszenithHistoOn;
+  TObjArray alphaHistoOn;
+  TObjArray srcposHistoOn;
+  TObjArray timediffHistoOn;
+  
+  const Int_t numberSizeBins = 3;
+  Double_t sizeBins[numberSizeBins] = {1897., 2785., 4087.}; //[Photons]
+
+  //cuts
+
+  Double_t widthmin[numberSizeBins]  = { 0.06, 0.06, 0.06 }; 
+  Double_t widthmax[numberSizeBins]  = { 0.10, 0.12, 0.12 };
+  Double_t lengthmin[numberSizeBins] = { 0.10, 0.10, 0.10 }; 
+  Double_t lengthmax[numberSizeBins] = { 0.25, 0.26, 0.36 };
+  Double_t distmin[numberSizeBins]   = { 0.30, 0.30, 0.30 }; 
+  Double_t distmax[numberSizeBins]   = { 1.20, 1.20, 1.20 };
+
+//   const Int_t numberSizeBins = 4;
+//   Double_t sizeBins[numberSizeBins] = {1292., 1897., 2785., 4087.}; //[Photons]
+
+//   //cuts
+
+//   Double_t widthmin[numberSizeBins]  = { 0.06, 0.06, 0.06, 0.06 }; 
+//   Double_t widthmax[numberSizeBins]  = { 0.10, 0.10, 0.12, 0.12 };
+//   Double_t lengthmin[numberSizeBins] = { 0.10, 0.10, 0.10, 0.10 }; 
+//   Double_t lengthmax[numberSizeBins] = { 0.20, 0.25, 0.26, 0.36 };
+//   Double_t distmin[numberSizeBins]   = { 0.30, 0.30, 0.30, 0.30 }; 
+//   Double_t distmax[numberSizeBins]   = { 1.20, 1.20, 1.20, 1.20 };
+
+  //alpha plot integration for gammas
+  Double_t sigexccmin = 0.;
+  Double_t sigexccmax = 15.;
+  Double_t bkgnormmin = 40.;
+  Double_t bkgnormmax = 80.;
+  
+  gStyle->SetOptStat(111111);
+  gStyle->SetOptFit();
+  
+  //
+  // Make a loop only for the ON data:
+  //
+  
+  MParList plist_on;
+  MTaskList tlist_on;
+  plist_on.AddToList(&tlist_on);
+  
+  // ON containers
+  MGeomCamMagic geomcam;
+  MRawRunHeader runheader_on;
+  MRawEvtHeader evtheader_on;
+  MTime              time_on;
+  MLiveTime      livetime_on;
+  MHillas          hillas_on;
+  MHillasSrc    hillassrc_on;
+  MSrcPosCam       srcpos_on;
+  MReportDrive      drive_on;
+
+  plist_on.AddToList(&geomcam);
+  plist_on.AddToList(&runheader_on);
+  plist_on.AddToList(&evtheader_on);
+  plist_on.AddToList(&time_on);
+  plist_on.AddToList(&livetime_on);
+  plist_on.AddToList(&hillas_on);
+  plist_on.AddToList(&hillassrc_on);
+  plist_on.AddToList(&srcpos_on);
+  plist_on.AddToList(&drive_on);
+
+  Int_t nbins_Size = 60;
+  Double_t min_Size = log10(sizeBins[0])*0.8;
+  Double_t max_Size = log10(1000000)*1.2;
+  TH1F *hSize_on = new TH1F ("hSizeOn","",nbins_Size,min_Size,max_Size);
+
+  Int_t nbins_Width = 20;
+  Double_t min_Width = 0.;
+  Double_t max_Width = widthmax[numberSizeBins-1]*1.2;
+  TH1F *hWidth_on = new TH1F ("hWidthOn","",nbins_Width,min_Width,max_Width);
+
+  Int_t nbins_Length = 20;
+  Double_t min_Length = 0.;
+  Double_t max_Length =  lengthmax[numberSizeBins-1]*1.2;
+  TH1F *hLength_on = new TH1F ("hLengthOn","",nbins_Length,min_Length,max_Length);
+
+  Int_t nbins_Dist = 20;
+  Double_t min_Dist = 0.;
+  Double_t max_Dist = distmax[numberSizeBins-1]*1.2;
+  TH1F *hDist_on = new TH1F ("hDistOn","",nbins_Dist,min_Dist,max_Dist);
+
+  Int_t nbins_abs = 18;
+  Double_t minalpha_abs = 0.;
+  Double_t maxalpha_abs =90.;
+  TH1F *hAlpha_on_abs = new TH1F ("hAbsAlphaOn","",nbins_abs,minalpha_abs,maxalpha_abs);
+
+  Int_t nbins = nbins_abs*2;
+  Double_t minalpha = -90.;
+  Double_t maxalpha =  90.;
+  TH1F *hAlpha_on = new TH1F ("hAlphaOn","",nbins,minalpha,maxalpha);
+
+  Int_t nbins_srcpos = 200;
+  Double_t minsrcpos = -200.;
+  Double_t maxsrcpos =  200.;  //[mm]  //!!! position precition 3mm ~ 0.01 deg
+  TH2F *hSrcPos_on = new TH2F ("hSrcPosOn","",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+
+  //
+  //tasks
+  //
+  
+  MReadTree read_on("Parameters", f_on_name);
+  read_on.DisableAutoScheme();
+ 
+  MSrcPlace srcplace;
+  MHillasSrcCalc csrc_on;
+
+  MLiveTimeCalc livetimecalc_on;
+  livetimecalc_on.SetRealTimeBinSize(timebin);
+
+//   // prints
+//   MPrint pevent("MRawEvtHeader");
+//   MPrint phillas("MHillas");
+//   MPrint phillassrc("MHillasSrc");
+//   MPrint psrcpos("MSrcPosCam");
+  
+  //tasklist
+  tlist_on.AddToList(&read_on);
+  tlist_on.AddToList(&livetimecalc_on);
+  tlist_on.AddToList(&srcplace);
+  tlist_on.AddToList(&csrc_on);
+  
+  // Create and setup the eventloop
+  MEvtLoop loop_on;
+  loop_on.SetParList(&plist_on);
+  //loop_on.SetDisplay(display);
+  
+//   MProgressBar bar;
+//   loop_on.SetProgressBar(&bar);
+  
+//   if (!loop_on.Eventloop())
+//     return;
+
+  if (!loop_on.PreProcess())
+    return;
+  
+  numberOnEventsAfterCleaning[numberTimeBins-1] = 0;
+  zenithMinimumOn[numberTimeBins-1] = 100.;
+  zenithMaximumOn[numberTimeBins-1] = 0.;
+  timeOn[numberTimeBins-1] = 0;
+
+  //create histos needed in the time bins
+
+  TString alphaTitle = Form("%s%02i","hAlphaOn",numberTimeBins-1);
+  TH1F *hAlpha_on_abs_timebin = new TH1F (alphaTitle,"",nbins_abs,minalpha_abs,maxalpha_abs);
+
+  TString srcposTitle =  Form("%s%02i","hSrcPosOn",numberTimeBins-1);
+  TH2F *hSrcPos_on_timebin = new TH2F (srcposTitle,"",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+
+  Int_t nbins_coszenith = 200;
+  Double_t mincoszenith = 0.;  
+  Double_t maxcoszenith = 1.;  
+  TString coszenithTitle =  Form("%s%02i","hCosZenithOn",numberTimeBins-1);
+  TH1F *hCosZenith_on_timebin = new TH1F (coszenithTitle,"",nbins_coszenith,mincoszenith,maxcoszenith);
+
+  Int_t nbins_timediff = 2000;
+  Double_t mintimediff = 0.;  
+  Double_t maxtimediff = 40.;  
+  TString timediffTitle =  Form("%s%02i","hTimeDiffOn",numberTimeBins-1);
+  TH1F *hTimeDiff_on_timebin = new TH1F (timediffTitle,"",nbins_timediff,mintimediff,maxtimediff);
+  TF1 *f1 = new TF1("exp","expo",mintimediff,maxtimediff);	      
+
+  Double_t lastSrcPosX = 0;
+  Double_t lastSrcPosY = 0;
+
+  while(tlist_on.Process())
+    {
+      numberOnEventsAfterCleaning[numberTimeBins-1]++;
+      
+      if (srcpos_on.GetX() == 0. && srcpos_on.GetY() == 0.)
+	srcpos_on.SetXY(lastSrcPosX,lastSrcPosY);
+      else
+	{
+	  lastSrcPosX = srcpos_on.GetX();
+	  lastSrcPosY = srcpos_on.GetY();
+	}
+      srcplace.CallProcess();
+      csrc_on.CallProcess();
+
+      
+      Double_t size = hillas_on.GetSize();
+      Double_t width = hillas_on.GetWidth()*geomcam.GetConvMm2Deg();
+      Double_t length = hillas_on.GetLength()*geomcam.GetConvMm2Deg();
+      Double_t meanx = hillas_on.GetMeanX()*geomcam.GetConvMm2Deg();
+      Double_t meany = hillas_on.GetMeanY()*geomcam.GetConvMm2Deg();
+      Double_t centerdist = TMath::Sqrt(meanx*meanx + meany*meany);
+      Double_t dist = hillassrc_on.GetDist()*geomcam.GetConvMm2Deg();
+      Double_t alpha = hillassrc_on.GetAlpha();
+      Double_t srcposx = srcpos_on.GetX();
+      Double_t srcposy = srcpos_on.GetY();
+      Double_t zenith = drive_on.GetNominalZd();
+	  
+
+      Int_t sizebin = GetBin(size,numberSizeBins,sizeBins);
+	  
+      if (sizebin >= 0)
+	{
+	  if (width > widthmin[sizebin] && width < widthmax[sizebin])
+	    {
+	      if (length > lengthmin[sizebin] && length < lengthmax[sizebin])
+		{
+		  if (dist > distmin[sizebin] && centerdist < distmax[sizebin])
+		    {      
+		      
+		      //General histos
+		      hSize_on->Fill(log10(size));
+		      hWidth_on->Fill(width);
+		      hLength_on->Fill(length);
+		      hDist_on->Fill(dist);
+		      hAlpha_on_abs->Fill(TMath::Abs(alpha));
+		      hAlpha_on->Fill(alpha);
+		      hSrcPos_on->Fill(srcposx,srcposy);
+		      
+		      // Time bin histos
+		      hAlpha_on_abs_timebin->Fill(TMath::Abs(alpha));
+		      hSrcPos_on_timebin->Fill(srcposx,srcposy);
+		      hCosZenith_on_timebin->Fill(TMath::Cos(zenith*kConvDegToRad));
+		      
+		      if (zenith != 0 && zenith < zenithMinimumOn[numberTimeBins-1])
+			zenithMinimumOn[numberTimeBins-1] = zenith;
+		      if (zenith>zenithMaximumOn[numberTimeBins-1])
+			zenithMaximumOn[numberTimeBins-1] = zenith;
+		      
+		    }
+		}
+	    }
+	}
+      
+      
+      // Check if you are overload the maxim time bin
+      if (numberTimeBins != livetime_on.GetNumberTimeBins())
+	{
+	  timeOn[numberTimeBins-1] = livetime_on.GetLiveTimeTArray().At(numberTimeBins-1);
+	  meanTimeBinOn[numberTimeBins-1] = livetime_on.GetMeanRealTimeTArray().At(numberTimeBins-1);
+	  widthTimeBinOn[numberTimeBins-1] = livetime_on.GetWidthRealTimeTArray().At(numberTimeBins-1);
+
+	  //Compute the number of on events
+	  numberOnEvents[numberTimeBins-1] = (Double_t) hAlpha_on_abs_timebin->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+	  numberBkgEventsToNormOn[numberTimeBins-1] =  (Double_t)  hAlpha_on_abs_timebin->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);	      
+	  
+// 	  hTimeDiff_on_timebin->Fit("exp","RQ0");
+// 	  deadFractionOn[numberTimeBins-1] = (nbins_timediff/(maxtimediff-mintimediff))*TMath::Exp(f1->GetParameter(0))/(TMath::Abs(f1->GetParameter(1))*hTimeDiff_on_timebin->GetEntries());
+// 	  cout << "1-> Exp(" << f1->GetParameter(0) << " + " << f1->GetParameter(1) << "*x) +- [" <<  f1->GetParError(0) << ' ' << f1->GetParError(1) << "]" << endl;
+// 	  cout << "Calc entries " << (nbins_timediff/(maxtimediff-mintimediff))*TMath::Exp(f1->GetParameter(0))/(TMath::Abs(f1->GetParameter(1))) << " +- Nt*(" << TMath::Sqrt( f1->GetParameter(0)*f1->GetParError(0)*f1->GetParameter(0)*f1->GetParError(0) + (f1->GetParError(1)*f1->GetParError(1))/(f1->GetParameter(1)*f1->GetParameter(1)))  << ") meas entries " << hTimeDiff_on_timebin->GetEntries() << " dead fraction " << deadFractionOn[numberTimeBins-1] << endl;
+	  deadFractionOn[numberTimeBins-1] = 1.;
+	  
+	  alphaHistoOn.AddLast(hAlpha_on_abs_timebin);
+	  srcposHistoOn.AddLast(hSrcPos_on_timebin);
+	  coszenithHistoOn.AddLast(hCosZenith_on_timebin);
+	  timediffHistoOn.AddLast(hTimeDiff_on_timebin);
+	  
+	  numberTimeBins = livetime_on.GetNumberTimeBins();
+	  
+	  timeOn.Set(numberTimeBins);
+	  numberOnEvents.Set(numberTimeBins);
+	  numberBkgEventsToNormOn.Set(numberTimeBins);
+	  widthTimeBinOn.Set(numberTimeBins);
+	  meanTimeBinOn.Set(numberTimeBins);
+	  zenithMinimumOn.Set(numberTimeBins);
+	  zenithMaximumOn.Set(numberTimeBins);
+	  deadFractionOn.Set(numberTimeBins);
+	  numberOnEventsAfterCleaning.Set(numberTimeBins);
+	  
+	  timeOn[numberTimeBins-1] = 0.;
+	  zenithMinimumOn[numberTimeBins-1] = 100.;
+	  zenithMaximumOn[numberTimeBins-1] = 0.;
+	  numberOnEventsAfterCleaning[numberTimeBins-1] = 0;
+	  
+	  alphaTitle =  Form("%s%02i","hAlphaOn",numberTimeBins-1);         
+	  hAlpha_on_abs_timebin = new TH1F (alphaTitle,"",nbins_abs,minalpha_abs,maxalpha_abs);
+	  
+	  srcposTitle =  Form("%s%02i","hSrcPosOn",numberTimeBins-1);
+	  hSrcPos_on_timebin = new TH2F (srcposTitle,"",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+	  
+	  coszenithTitle =  Form("%s%02i","hCosZenithOn",numberTimeBins-1);
+	  hCosZenith_on_timebin = new TH1F (coszenithTitle,"",nbins_coszenith,mincoszenith,maxcoszenith);
+	  
+	  timediffTitle =  Form("%s%02i","hTimeDiffOn",numberTimeBins-1);
+	  hTimeDiff_on_timebin = new TH1F (timediffTitle,"",nbins_timediff,mintimediff,maxtimediff);
+	  
+	}
+      
+    }
+	
+  loop_on.PostProcess();
+  
+  tlist_on.PrintStatistics();
+  
+  timeOn[numberTimeBins-1] = livetime_on.GetLiveTimeTArray().At(numberTimeBins-1);
+  meanTimeBinOn[numberTimeBins-1] = livetime_on.GetMeanRealTimeTArray().At(numberTimeBins-1);
+  widthTimeBinOn[numberTimeBins-1] = livetime_on.GetWidthRealTimeTArray().At(numberTimeBins-1);
+  
+  //Compute the number of on events for the last time bin
+  numberOnEvents[numberTimeBins-1] = (Double_t) hAlpha_on_abs_timebin->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+  numberBkgEventsToNormOn[numberTimeBins-1] =  (Double_t)  hAlpha_on_abs_timebin->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);	      
+
+//   hTimeDiff_on_timebin->Fit("exp","RQ0");
+//   deadFractionOn[numberTimeBins-1] = (nbins_timediff/(maxtimediff-mintimediff))*TMath::Exp(f1->GetParameter(0))/(TMath::Abs(f1->GetParameter(1))*hTimeDiff_on_timebin->GetEntries());
+
+//   cout.precision(5);
+//   cout << "2-> Exp(" << f1->GetParameter(0) << " + 
+//   cout << "Calc entries " << (nbins_timediff/(maxtimediff-mintimediff))*TMath::Exp(f1->GetParameter(0))/TMath::Abs(f1->GetParameter(1)) << " +- Nt*(" << TMath::Sqrt( f1->GetParameter(0)*f1->GetParError(0)*f1->GetParameter(0)*f1->GetParError(0) + (f1->GetParError(1)*f1->GetParError(1))/(f1->GetParameter(1)*f1->GetParameter(1)))  << ") meas entries " << hTimeDiff_on_timebin->GetEntries() << " dead fraction " << deadFractionOn[numberTimeBins-1] << endl;
+  deadFractionOn[numberTimeBins-1] = 1.;
+
+  alphaHistoOn.AddLast(hAlpha_on_abs_timebin);
+  srcposHistoOn.AddLast(hSrcPos_on_timebin);
+  coszenithHistoOn.AddLast(hCosZenith_on_timebin);
+  timediffHistoOn.AddLast(hTimeDiff_on_timebin);
+
+  //-----------------------OFF------------------------
+
+  TObjArray alphaHistoOff;
+  TObjArray srcposHistoOff;
+
+  TArrayD timeOff(numberTimeBins);
+
+  TArrayI numberOffEvents(numberTimeBins);
+
+  TArrayD numberBkgEventsToNormOff(numberTimeBins);
+  TArrayD onOffNormFactor(numberTimeBins);
+  TArrayD onOffNormFactorWithEvents(numberTimeBins);
+  TArrayD onOffNormFactorWithLiveTime(numberTimeBins);
+
+  TArrayD numberExcessEvents(numberTimeBins);
+  TArrayD errorNumberExcessEvents(numberTimeBins);
+
+  TArrayD numberExcessEventsPerSec(numberTimeBins);
+  TArrayD errorNumberExcessEventsPerSec(numberTimeBins);
+
+  TArrayD numberExcessEventsPerMin(numberTimeBins);
+  TArrayD errorNumberExcessEventsPerMin(numberTimeBins);
+
+  timeOff.Set(numberTimeBins);
+  
+  TH1F* hAlpha_off_abs_timebin;
+  TH2F* hSrcPos_off_timebin;
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      alphaTitle =  Form("%s%02i","hAlphaOff",bin);
+      hAlpha_off_abs_timebin = new TH1F (alphaTitle,"",nbins_abs,minalpha_abs,maxalpha_abs);;
+      alphaHistoOff.AddLast(hAlpha_off_abs_timebin);
+      //      cout << "hAlpha_off_abs_timebin " << hAlpha_off_abs_timebin <<  " alphaHistoOff [" << bin << "] " << alphaHistoOff[bin] << endl;
+
+      srcposTitle =  Form("%s%02i","hSrcPosOff",bin);
+      hSrcPos_off_timebin = new TH2F (srcposTitle,"",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+      srcposHistoOff.AddLast(hSrcPos_off_timebin);
+      //      cout << "hSrcPos_off_timebin " << hSrcPos_off_timebin <<  " srcposHistoOff [" << bin << "] " << srcposHistoOff[bin] << endl;
+    }
+
+  // 
+  // Make a loop only for the OFF data:
+  //
+  
+  MParList plist_off;
+  MTaskList tlist_off;
+  plist_off.AddToList(&tlist_off);
+  
+  MRawRunHeader runheader_off;
+  MRawEvtHeader evtheader_off;
+  MTime              time_off;
+  MLiveTime      livetime_off;
+  MHillas          hillas_off;
+  MHillasSrc    hillassrc_off;
+  MSrcPosCam       srcpos_off;
+  MReportDrive      drive_off;
+  
+  plist_off.AddToList(&geomcam);
+  plist_off.AddToList(&runheader_off);
+  plist_off.AddToList(&evtheader_off);
+  plist_off.AddToList(&time_off);
+  plist_off.AddToList(&livetime_off);
+  plist_off.AddToList(&hillas_off);
+  plist_off.AddToList(&hillassrc_off);
+  plist_off.AddToList(&srcpos_off);
+  plist_off.AddToList(&drive_off);
+
+  TH1F *hSize_off      = new TH1F ("hSizeOff","",nbins_Size,min_Size,max_Size);
+  TH1F *hWidth_off     = new TH1F ("hWidthOff","",nbins_Width,min_Width,max_Width);
+  TH1F *hLength_off    = new TH1F ("hLengthOff","",nbins_Length,min_Length,max_Length);
+  TH1F *hDist_off      = new TH1F ("hDistOff","",nbins_Dist,min_Dist,max_Dist);
+  TH1F *hAlpha_off_abs = new TH1F ("hAbsAlphaOff","",nbins_abs,minalpha_abs,maxalpha_abs);
+  TH1F *hAlpha_off     = new TH1F ("hAlphaOff","",nbins,minalpha,maxalpha);
+  TH2F *hSrcPos_off    = new TH2F ("hSrcPosOff","",nbins_srcpos,minsrcpos,maxsrcpos,nbins_srcpos,minsrcpos,maxsrcpos);
+
+  //tasks
+  MReadTree read_off("Parameters", f_off_name);
+  read_off.DisableAutoScheme();
+
+  // taks to set the src position in the off data for the time bins
+  // --------------------------------------------------------------
+  MSrcPlace srcplace_timebin;
+  srcplace_timebin.SetCreateHisto(kFALSE);
+  srcplace_timebin.SetMode(MSrcPlace::kOff);
+  // --------------------------------------------------------------
+
+  //  srcplace.SetMode(MSrcPlace::kOff);
+  
+  MHillasSrcCalc csrc_off;
+  
+  MLiveTimeCalc livetimecalc_off;
+
+ //tasklist
+  tlist_off.AddToList(&read_off);
+  tlist_off.AddToList(&livetimecalc_off);
+  tlist_off.AddToList(&srcplace_timebin); // This is just to run the preprocess correctely
+  tlist_off.AddToList(&csrc_off); // This is just to run the preprocess correctely
+  
+  // Create and setup the eventloop
+  MEvtLoop loop_off;
+  loop_off.SetParList(&plist_off);
+  //loop_off.SetDisplay(display);
+  
+//   MProgressBar bar_off;
+//   loop_off.SetProgressBar(&bar_off);
+  
+//   if (!loop_off.Eventloop(numEntries))
+//     return;
+  
+  if (!loop_off.PreProcess())
+    return;
+
+  while(tlist_off.Process())
+    {
+
+      //First read the variables source(i.e. time bin) independent
+      Double_t zenith = drive_off.GetNominalZd();
+
+      Double_t size = hillas_off.GetSize();
+      Double_t width = hillas_off.GetWidth()*geomcam.GetConvMm2Deg();
+      Double_t length = hillas_off.GetLength()*geomcam.GetConvMm2Deg();
+      Double_t meanx = hillas_off.GetMeanX()*geomcam.GetConvMm2Deg();
+      Double_t meany = hillas_off.GetMeanY()*geomcam.GetConvMm2Deg();
+      Double_t centerdist = TMath::Sqrt(meanx*meanx + meany*meany);
+      
+      Int_t sizebin = GetBin(size,numberSizeBins,sizeBins);
+      
+      if (sizebin >= 0)
+	{
+	  if (width > widthmin[sizebin] && width < widthmax[sizebin])
+	    {
+	      if (length > lengthmin[sizebin] && length < lengthmax[sizebin])
+		{
+		  if (centerdist < distmax[sizebin])
+		    {
+		      //General histos
+
+		      srcplace_timebin.SetPositionHisto(hSrcPos_on);
+		      srcplace_timebin.CallProcess();
+		      csrc_off.CallProcess();
+		      
+		      Double_t dist = hillassrc_off.GetDist()*geomcam.GetConvMm2Deg();
+		      Double_t alpha = hillassrc_off.GetAlpha();
+		      Double_t srcposx = srcpos_off.GetX();
+		      Double_t srcposy = srcpos_off.GetY();
+		      
+		      if (dist > distmin[sizebin] )
+			{
+			  hSize_off->Fill(log10(size));
+			  hWidth_off->Fill(width);
+			  hLength_off->Fill(length);
+			  
+			  hDist_off->Fill(dist);
+			  hAlpha_off_abs->Fill(TMath::Abs(alpha));
+			  hAlpha_off->Fill(alpha);
+			  hSrcPos_off->Fill(srcposx,srcposy);
+			}
+		      
+		      // Time bin histos
+		      for (UInt_t bin=0; bin<numberTimeBins; bin++)
+			{
+			  srcplace_timebin.SetPositionHisto((TH2F*)srcposHistoOn[bin]);
+			  srcplace_timebin.CallProcess();
+			  csrc_off.CallProcess();
+			  
+			  dist = hillassrc_off.GetDist()*geomcam.GetConvMm2Deg();
+			  alpha = hillassrc_off.GetAlpha();
+			  srcposx = srcpos_off.GetX();
+			  srcposy = srcpos_off.GetY();
+			  
+			  if (dist > distmin[sizebin])
+			    {
+			      ((TH1F*)alphaHistoOff[bin])->Fill(TMath::Abs(alpha));
+			      ((TH2F*)srcposHistoOff[bin])->Fill(srcposx,srcposy);
+			    }
+			}
+		    }
+		}
+	    }
+	}
+    }
+  
+  loop_off.PostProcess();
+
+  tlist_off.PrintStatistics();
+
+  TArrayD meanTimeBinOnInSec(numberTimeBins);
+  TArrayD widthTimeBinOnInSec(numberTimeBins);
+  
+  TArrayD meanTriggerRateOn(numberTimeBins);
+  TArrayD errorMeanTriggerRateOn(numberTimeBins);
+
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      cout.precision(5);
+      cout << bin << " timeOn " << timeOn[bin] << " mean-width time " << meanTimeBinOn[bin] << "-" << widthTimeBinOn[bin] << endl;
+    }
+  livetime_off.Print("last");
+  livetime_off.Print("all");
+  cout << "livetime_off.GetLiveTime() " << livetime_off.GetLiveTime() << endl;
+
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      timeOff[bin] = livetime_off.GetLiveTime();
+
+      //
+      meanTriggerRateOn[bin] = numberOnEventsAfterCleaning[bin]/timeOn[bin];
+      errorMeanTriggerRateOn[bin] = TMath::Sqrt(numberOnEventsAfterCleaning[bin])/timeOn[bin];
+
+      meanTimeBinOnInSec[bin]  = (meanTimeBinOn[bin]-(Int_t)meanTimeBinOn[bin]);
+      if (meanTimeBinOnInSec[bin] > 0.5)
+	meanTimeBinOnInSec[bin] = meanTimeBinOnInSec[bin] - 1 ;
+      meanTimeBinOnInSec[bin] *= kDay;
+
+      widthTimeBinOnInSec[bin] = widthTimeBinOn[bin]*kDay;
+
+      numberOffEvents[bin] = (Double_t) ((TH1F*)alphaHistoOff[bin])->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+      numberBkgEventsToNormOff[bin] =  (Double_t) ((TH1F*)alphaHistoOff[bin])->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);
+      if (numberOffEvents[bin] != 0 && numberBkgEventsToNormOff[bin] != 0)
+	{
+	  onOffNormFactorWithEvents[bin] = numberBkgEventsToNormOn[bin]/numberBkgEventsToNormOff[bin];
+	  onOffNormFactorWithLiveTime[bin] = timeOn[bin]/timeOff[bin];
+	  onOffNormFactor[bin] = onOffNormFactorWithEvents[bin];
+	  numberExcessEvents[bin] = numberOnEvents[bin] - onOffNormFactor[bin]*numberOffEvents[bin];
+	  errorNumberExcessEvents[bin] = TMath::Sqrt(numberOnEvents[bin] + onOffNormFactor[bin]*onOffNormFactor[bin]*numberOffEvents[bin]);
+	  numberExcessEventsPerSec[bin] = numberExcessEvents[bin]/timeOn[bin]*(deadFractionOn[bin]>1.?deadFractionOn[bin]:1.);
+	  errorNumberExcessEventsPerSec[bin] = errorNumberExcessEvents[bin]/timeOn[bin];
+	  numberExcessEventsPerMin[bin] = 60.*numberExcessEvents[bin]/timeOn[bin]*(deadFractionOn[bin]>1.?deadFractionOn[bin]:1.);
+	  errorNumberExcessEventsPerMin[bin] = 60.*errorNumberExcessEvents[bin]/timeOn[bin];
+
+	}
+    }
+  
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      cout.precision(5);
+      cout << bin << " timeOn " << timeOn[bin] << " mean-width time " << meanTimeBinOnInSec[bin] << "-" << widthTimeBinOnInSec[bin] << endl;
+      cout << " numberOnEvents\t " << numberOnEvents[bin] << endl;
+      cout << " numberOffEvents\t " << numberOffEvents[bin] << endl;
+      cout << " numberBkgEventsToNormOn\t " << numberBkgEventsToNormOn[bin] << endl;
+      cout << " numberBkgEventsToNormOff\t " << numberBkgEventsToNormOff[bin] << endl;
+      cout << " onOffNormFactorWithEvents\t " << onOffNormFactorWithEvents[bin] << endl;
+      cout << " onOffNormFactorWithLiveTime\t " << onOffNormFactorWithLiveTime[bin] << endl;
+      cout << " numberExcessEvents\t " <<  numberExcessEvents[bin] <<  " +- " << errorNumberExcessEvents[bin] << endl;
+      cout << " deadFraction\t" << deadFractionOn[bin] << endl;
+      cout << " Excess/Sec\t " << numberExcessEventsPerSec[bin] << " +- " << errorNumberExcessEventsPerSec[bin] << endl;
+      cout << " Trigger Rate\t " << meanTriggerRateOn[bin] << " +- " << errorMeanTriggerRateOn[bin] << endl;
+    }
+
+  
+
+  TString openpsname = psname + "(";
+  TString closepsname = psname + ")";
+
+  TCanvas *c0 = new TCanvas;
+  c0->cd(1);
+  TGraphErrors* lightcurvegraph = new TGraphErrors(numberTimeBins,meanTimeBinOnInSec.GetArray(),numberExcessEventsPerMin.GetArray(),widthTimeBinOnInSec.GetArray(),errorNumberExcessEventsPerMin.GetArray());
+  lightcurvegraph->SetTitle("LightCurve");
+  lightcurvegraph->SetMinimum(0.);
+  lightcurvegraph->SetMarkerStyle(21);
+  lightcurvegraph->SetMarkerSize(0.03);
+  lightcurvegraph->Draw("AP");
+  lightcurvegraph->GetYaxis()->SetTitle("Excess/min");
+  lightcurvegraph->GetXaxis()->SetTitle("UTC Time");
+  lightcurvegraph->GetXaxis()->SetTimeDisplay(1);
+  c0->Print(openpsname);
+      
+  TCanvas *c00 = new TCanvas;
+  c00->cd(1);
+  TGraphErrors* cosmicrategraph = new TGraphErrors(numberTimeBins,meanTimeBinOnInSec.GetArray(),meanTriggerRateOn.GetArray(),widthTimeBinOnInSec.GetArray(),errorMeanTriggerRateOn.GetArray());
+  cosmicrategraph->SetTitle("Cosmic Rate");
+  cosmicrategraph->SetMarkerStyle(21);
+  cosmicrategraph->SetMarkerSize(0.03);
+  cosmicrategraph->Draw("AP");
+  cosmicrategraph->GetYaxis()->SetTitle("[Hz]");
+  cosmicrategraph->GetXaxis()->SetTitle("UTC Time");
+  cosmicrategraph->GetXaxis()->SetTimeDisplay(1);
+  c00->Print(psname);
+
+  TCanvas** c = new TCanvas*[numberTimeBins];
+  
+  //Compute the maximum of all hAlphaOn histograms
+  Float_t maxAlphaHistoHeight = 0;
+  
+  for (UInt_t bin=0; bin<numberTimeBins; bin++)
+    {
+      for (UInt_t i=1; i<=nbins_abs; i++)
+	if (((TH1F*)alphaHistoOn[bin])->GetBinContent(i) > maxAlphaHistoHeight)
+	  maxAlphaHistoHeight = ((TH1F*)alphaHistoOn[bin])->GetBinContent(i);
+    }      
+  
+  cout << "maxAlphaHistoHeight " << maxAlphaHistoHeight << endl;
+
+  for (UInt_t bin=0; bin<numberTimeBins-1; bin++)
+    {
+      c[bin] = new TCanvas;
+      c[bin]->cd(1);
+      
+      ((TH1F*)alphaHistoOn[bin])->Sumw2();
+      ((TH1F*)alphaHistoOff[bin])->SetStats(0);
+      ((TH1F*)alphaHistoOff[bin])->Sumw2();
+      ((TH1F*)alphaHistoOff[bin])->Scale(onOffNormFactor[bin]); 
+      ((TH1F*)alphaHistoOn[bin])->SetStats(0); //-> Do NOT show the legend with statistics
+      ((TH1F*)alphaHistoOn[bin])->SetLineColor(kBlack);
+      ((TH1F*)alphaHistoOn[bin])->SetMarkerStyle(21);
+      ((TH1F*)alphaHistoOn[bin])->SetMarkerColor(kBlack);
+      ((TH1F*)alphaHistoOn[bin])->SetMarkerSize(0.7);
+      ((TH1F*)alphaHistoOff[bin])->SetFillColor(46);
+      ((TH1F*)alphaHistoOff[bin])->SetLineColor(46);
+      ((TH1F*)alphaHistoOff[bin])->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+      ((TH1F*)alphaHistoOn[bin])->SetMaximum(maxAlphaHistoHeight*1.2);
+      ((TH1F*)alphaHistoOff[bin])->SetMinimum(0.);
+      alphaTitle =  Form("%s%02i","hAlphaOnOff",bin);
+      ((TH1F*)alphaHistoOn[bin])->SetTitle(alphaTitle);
+      
+      
+      ((TH1F*)alphaHistoOn[bin])->DrawCopy("E1P");
+      ((TH1F*)alphaHistoOff[bin])->DrawCopy("HISTSAME");
+      ((TH1F*)alphaHistoOff[bin])->DrawCopy("ESAME");
+      ((TH1F*)alphaHistoOn[bin])->DrawCopy("E1PSAME");
+
+      c[bin]->Print(psname);
+    }
+
+  c[numberTimeBins-1] = new TCanvas;
+  c[numberTimeBins-1]->cd(1);
+  
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->Sumw2();
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetStats(0);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->Sumw2();
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->Scale(onOffNormFactor[numberTimeBins-1]); 
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetStats(0); //-> Do NOT show the legend with statistics
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetLineColor(kBlack);
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetMarkerStyle(21);
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetMarkerColor(kBlack);
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetMarkerSize(0.7);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetFillColor(46);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetLineColor(46);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetMaximum(maxAlphaHistoHeight*1.2);
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->SetMinimum(0.);
+  alphaTitle =  Form("%s%02i","hAlphaOnOff",numberTimeBins-1);
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->SetTitle(alphaTitle);
+  
+  
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->DrawCopy("E1P");
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->DrawCopy("HISTSAME");
+  ((TH1F*)alphaHistoOff[numberTimeBins-1])->DrawCopy("ESAME");
+  ((TH1F*)alphaHistoOn[numberTimeBins-1])->DrawCopy("E1PSAME");
+  
+  c[numberTimeBins-1]->Print(psname);
+
+  //  TString rootname = psname.ReplaceAll(".ps",".root");
+  TString rootname = "./prueba.root";
+  TFile input(rootname, "RECREATE");
+
+   for (UInt_t bin=0; bin<numberTimeBins; bin++)
+     {
+       ((TH1F*)alphaHistoOn[bin])->Write();
+       ((TH2F*)srcposHistoOn[bin])->Write();
+       ((TH1F*)coszenithHistoOn[bin])->Write();
+       ((TH1F*)timediffHistoOn[bin])->Write();
+       ((TH1F*)alphaHistoOff[bin])->Write();
+       ((TH2F*)srcposHistoOff[bin])->Write();
+    }
+  
+  input.Close();
+
+  // ############################################################################
+  // Calculate significance and excess: 
+  // ############################################################################
+
+  Double_t norm_on_abs  = (Double_t) hAlpha_on_abs->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);
+  Double_t exces_on_abs = (Double_t) hAlpha_on_abs->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+  Double_t norm_off_abs  = (Double_t) hAlpha_off_abs->Integral((Int_t)bkgnormmin*nbins_abs/90+1,(Int_t)bkgnormmax*nbins_abs/90);
+  Double_t exces_off_abs = (Double_t) hAlpha_off_abs->Integral((Int_t)sigexccmin*nbins_abs/90+1,(Int_t)sigexccmax*nbins_abs/90);
+  Double_t norm = norm_on_abs/norm_off_abs;
+
+  char text_tit_alpha[256];
+  sprintf(text_tit_alpha, " Alpha Plot On and Off ");
+  hAlpha_off_abs->SetTitle(text_tit_alpha);
+  hAlpha_on_abs->SetTitle(text_tit_alpha);
+
+  Double_t excess  = exces_on_abs - exces_off_abs*norm;
+  Double_t sign    = excess / sqrt( exces_on_abs + norm*norm*exces_off_abs );
+  Double_t int_off = (Double_t) hAlpha_off_abs->Integral(1, 18);
+  int hAlpha_on_entries  = (int) hAlpha_on_abs->GetEntries();
+  int hAlpha_off_entries = (int) hAlpha_off_abs->GetEntries();
+    
+  cout << "---> Normalization F factor =\t" << norm <<endl;
+  cout << "---> Excess =\t\t\t" << excess <<endl;
+  cout << "---> Significancia =\t\t" << sign <<endl;    
+  cout << "---> entries on   =\t\t" << hAlpha_on_entries  <<endl;
+  cout << "---> entries off  =\t\t" << hAlpha_off_entries <<endl;
+  cout << "---> integral off =\t\t" << int_off <<endl;
+
+  Double_t shiftx;
+
+  // ############################################################################
+  // Draw SIZE
+  // ############################################################################
+  TCanvas *c1 = new TCanvas;
+
+  gPad->cd();
+
+  gPad->SetLogy();
+  hSize_on->Sumw2();
+  hSize_off->Sumw2();
+  hSize_off->Scale(norm); 
+  hSize_on->SetLineColor(kBlack);
+  hSize_on->SetMarkerStyle(21);
+  hSize_on->SetMarkerSize(0.7);
+  hSize_on->SetMarkerColor(kBlack);
+  hSize_off->SetFillColor(46);
+  hSize_off->SetLineColor(46);
+  hSize_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hSize_off->SetMinimum(0.1);
+  hSize_on->SetMinimum(0.1);
+  hSize_on->SetTitle("SIZE distribution");
+  hSize_off->SetTitle("SIZE distribution");
+
+  hSize_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_size = (TPaveStats*) hSize_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_size){
+    shiftx = pavs_on_size->GetX2NDC() - pavs_on_size->GetX1NDC();
+    pavs_on_size->SetX1NDC(pavs_on_size->GetX1NDC() - shiftx);
+    pavs_on_size->SetX2NDC(pavs_on_size->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hSize_off->DrawCopy("HISTSAME");
+  hSize_off->DrawCopy("ESAME");
+
+  gPad->Modified();
+  gPad->Update();
+
+  Double_t chisize = ChiSquareNDof((TH1D*)hSize_on,(TH1D*)hSize_off);
+
+  Double_t x_label_pos  = log10(1000000)*0.7;
+  Double_t y_label_pos  = log10((hSize_on->GetBinContent(hSize_on->GetMaximumBin()))/2.);
+  Double_t textsize = 0.03;
+
+  char text_size[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chisize);
+
+  TLatex *tsize = new TLatex(x_label_pos, y_label_pos, text_size);
+  tsize->SetTextSize(textsize);
+//  tsize->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  c1->Print(psname);
+
+  // ############################################################################
+  // DrawCopy DIST
+  // ############################################################################
+  TCanvas *c2 = new TCanvas;
+
+  gPad->cd();
+
+  hDist_on->Sumw2();
+  hDist_off->Sumw2();
+  hDist_off->Scale(norm); 
+  hDist_on->SetLineColor(kBlack);
+  hDist_on->SetMarkerStyle(21);
+  hDist_on->SetMarkerSize(0.7);
+  hDist_on->SetMarkerColor(kBlack);
+  hDist_off->SetFillColor(46);
+  hDist_off->SetLineColor(46);
+  hDist_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hDist_off->SetMinimum(0.);
+  hDist_on->SetTitle("DIST distribution");
+  hDist_off->SetTitle("DIST distribution");
+
+  hDist_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_dist = (TPaveStats*) hDist_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_dist){
+    shiftx = pavs_on_dist->GetX2NDC() - pavs_on_dist->GetX1NDC();
+    pavs_on_dist->SetX1NDC(pavs_on_dist->GetX1NDC() - shiftx);
+    pavs_on_dist->SetX2NDC(pavs_on_dist->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hDist_off->DrawCopy("HISTSAME");
+  hDist_off->DrawCopy("ESAME");
+  hDist_on->DrawCopy("E1PSAME");
+
+  Double_t chidist = ChiSquareNDof((TH1D*)hDist_on,(TH1D*)hDist_off);
+
+  x_label_pos  = distmax[numberSizeBins-1]*0.7;
+  y_label_pos  = hDist_on->GetBinContent(hDist_on->GetMaximumBin())/2.;
+
+  char text_dist[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chidist);
+
+  TLatex *tdist = new TLatex(x_label_pos, y_label_pos, text_dist);
+  tdist->SetTextSize(textsize);
+//  tdist->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  c2->Print(psname);
+
+   // ############################################################################
+  // DrawCopy WIDTH
+  // ############################################################################
+  TCanvas *c3 = new TCanvas;
+
+  gPad->cd();
+
+  hWidth_off->Sumw2();
+  hWidth_off->Scale(norm); 
+  hWidth_on->SetLineColor(kBlack);
+  hWidth_on->SetMarkerStyle(21);
+  hWidth_on->SetMarkerSize(0.7);
+  hWidth_on->SetMarkerColor(kBlack);
+  hWidth_off->SetFillColor(46);
+  hWidth_off->SetLineColor(46);
+  hWidth_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hWidth_off->SetMinimum(0.);
+  hWidth_on->SetTitle("WIDTH distribution");
+  hWidth_off->SetTitle("WIDTH distribution");
+
+  hWidth_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_width = (TPaveStats*) hWidth_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_width){
+    shiftx = pavs_on_width->GetX2NDC() - pavs_on_width->GetX1NDC();
+    pavs_on_width->SetX1NDC(pavs_on_width->GetX1NDC() - shiftx);
+    pavs_on_width->SetX2NDC(pavs_on_width->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hWidth_off->DrawCopy("HISTSAME");
+  hWidth_off->DrawCopy("ESAME");
+  hWidth_on->DrawCopy("E1PSAME");
+
+  Double_t chiwidth = ChiSquareNDof((TH1D*)hWidth_on,(TH1D*)hWidth_off);
+
+  x_label_pos  = widthmax[numberSizeBins-1]*0.7;
+  y_label_pos  = hWidth_on->GetBinContent(hWidth_on->GetMaximumBin())/2.;
+
+  char text_width[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chiwidth);
+
+  TLatex *twidth = new TLatex(x_label_pos, y_label_pos, text_width);
+  twidth->SetTextSize(textsize);
+//  twidth->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+ 
+  c3->Print(psname);
+
+  // ############################################################################
+  // DrawCopy LENGTH
+  // ############################################################################
+  TCanvas *c4 = new TCanvas;
+ 
+  gPad->cd();
+
+  hLength_on->Sumw2();
+  hLength_off->Sumw2();
+  hLength_off->Scale(norm); 
+  hLength_on->SetLineColor(kBlack);
+  hLength_on->SetMarkerStyle(21);
+  hLength_on->SetMarkerSize(0.7);
+  hLength_on->SetMarkerColor(kBlack);
+  hLength_off->SetFillColor(46);
+  hLength_off->SetLineColor(46);
+  hLength_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hLength_off->SetMinimum(0.);
+  hLength_on->SetTitle("LENGTH distribution");
+  hLength_off->SetTitle("LENGTH distribution");
+
+  hLength_on->DrawCopy("E1P");
+
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* pavs_on_length = (TPaveStats*) hLength_on->GetListOfFunctions()->FindObject("stats");
+  if(pavs_on_length){
+    shiftx = pavs_on_length->GetX2NDC() - pavs_on_length->GetX1NDC();
+    pavs_on_length->SetX1NDC(pavs_on_length->GetX1NDC() - shiftx);
+    pavs_on_length->SetX2NDC(pavs_on_length->GetX2NDC() - shiftx);  
+  }
+  gPad->Modified();
+  gPad->Update();
+
+  hLength_off->DrawCopy("HISTSAME");
+  hLength_off->DrawCopy("ESAME");
+  hLength_on->DrawCopy("E1PSAME");
+
+  Double_t chilength = ChiSquareNDof((TH1D*)hLength_on,(TH1D*)hLength_off);
+
+  x_label_pos  = lengthmax[numberSizeBins-1]*0.7;
+  y_label_pos  = hLength_on->GetBinContent(hLength_on->GetMaximumBin())/2.;
+
+  char text_length[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chilength);
+
+  TLatex *tlength = new TLatex(x_label_pos, y_label_pos, text_length);
+  tlength->SetTextSize(textsize);
+//  tlength->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  c4->Print(psname);
+
+ // ############################################################################
+  // DrawCopy normalized ALPHA plot
+  // ############################################################################
+  TCanvas *c5 = new TCanvas;
+  
+  gPad->cd();
+
+  hAlpha_on_abs->Sumw2();
+  hAlpha_off_abs->SetStats(0);
+  hAlpha_off_abs->Sumw2();
+  hAlpha_off_abs->Scale(norm); 
+  hAlpha_on_abs->SetStats(0); //-> Do NOT show the legend with statistics
+  hAlpha_on_abs->SetLineColor(kBlack);
+  hAlpha_on_abs->SetMarkerStyle(21);
+  //hAlpha_on_abs->SetMarkerSize();
+  hAlpha_on_abs->SetMarkerColor(kBlack);
+  hAlpha_on_abs->SetMarkerSize(0.7);
+  hAlpha_off_abs->SetFillColor(46);
+  hAlpha_off_abs->SetLineColor(46);
+  hAlpha_off_abs->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hAlpha_off_abs->SetMinimum(0.);
+  hAlpha_on_abs->SetTitle("Alpha plot");
+  hAlpha_off_abs->SetTitle("Alpha plot");
+
+  
+  hAlpha_on_abs->DrawCopy("E1P");
+  hAlpha_off_abs->DrawCopy("HISTSAME");
+  hAlpha_off_abs->DrawCopy("ESAME");
+  hAlpha_on_abs->DrawCopy("E1PSAME");
+
+
+   //draw the LEGEND with excess and significance values in the alpha plot:
+  char text_Fnorm[256], text_excess[256], text_sign[256];
+  char text_entries_on[256], text_entries_off[256], text_integral_off[256];
+  int hAlpha_on_entries  = (int) hAlpha_on_abs->GetEntries();
+  int hAlpha_off_entries = (int) hAlpha_off_abs->GetEntries();
+  sprintf(text_Fnorm,       " F norm =       %.3f", norm);
+  sprintf(text_excess,      " Excess =       %.3f", excess);
+  sprintf(text_sign,        " Significance = %.3f", sign);
+  sprintf(text_entries_on,  " Entries ON   = %d",  hAlpha_on_entries);
+  sprintf(text_entries_off, " Entries OFF  = %d",  hAlpha_off_entries);
+  sprintf(text_integral_off," Integral OFF = %d",  int_off);
+  
+  x_label_pos  = 90.*0.7;
+  y_label_pos  = (hAlpha_on_abs->GetBinContent(hAlpha_on_abs->GetMaximumBin())); //2.;
+  Double_t y_label_step = y_label_pos / 8.;
+
+  TLatex *t0 = new TLatex(x_label_pos, y_label_pos - y_label_step*0, text_Fnorm);
+  t0->SetTextSize(textsize);
+  t0->Draw();
+  TLatex *t1 = new TLatex(x_label_pos, y_label_pos - y_label_step*1, text_excess);
+  t1->SetTextSize(textsize);
+  t1->Draw();
+  TLatex *t2 = new TLatex(x_label_pos, y_label_pos - y_label_step*2, text_sign);
+  t2->SetTextSize(textsize);
+  t2->Draw();
+  TLatex *t3 = new TLatex(x_label_pos, y_label_pos - y_label_step*3, text_entries_on);
+  t3->SetTextSize(textsize);
+  t3->Draw();
+  TLatex *t4 = new TLatex(x_label_pos, y_label_pos - y_label_step*4, text_entries_off);
+  t4->SetTextSize(textsize);
+  t4->Draw();
+  TLatex *t5 = new TLatex(x_label_pos, y_label_pos - y_label_step*5, text_integral_off);
+  t5->SetTextSize(textsize);
+  t5->Draw();
+  
+
+  Double_t chialpha = ChiSquareNDof((TH1D*)hAlpha_on_abs,(TH1D*)hAlpha_off_abs);
+
+  y_label_pos  = (hAlpha_on_abs->GetBinContent(hAlpha_on_abs->GetMaximumBin()))/2.;
+
+  char text_alpha[256];
+  sprintf(text_size,"ChiSquare/NDof = %4.2f",chialpha);
+
+  TLatex *talpha = new TLatex(x_label_pos, y_label_pos, text_alpha);
+  talpha->SetTextSize(textsize);
+//  talpha->Draw();
+
+  gPad->Modified();
+  gPad->Update();
+
+  c5->Print(psname);
+
+  // ############################################################################
+  // DrawCopy normalized alpha histos for alpha form -90 to 90 deg.
+  // ############################################################################
+  TCanvas *c6 = new TCanvas;
+
+  gPad->cd();
+
+  hAlpha_on->Sumw2();
+  hAlpha_off->SetStats(0);
+  hAlpha_off->Sumw2();
+  hAlpha_off->Scale(norm); 
+  hAlpha_off->SetFillColor(46);
+  hAlpha_off->SetLineColor(46);
+  hAlpha_off->SetFillStyle(3004); //(1001)-> To set the pad NOT transparent and solid; (3004)-> pattern lines
+  hAlpha_off->SetMinimum(0.); 
+  hAlpha_on->SetStats(0); //-> Do NOT show the legend with statistics
+  hAlpha_on->SetLineColor(kBlack);
+  hAlpha_on->SetMarkerStyle(21);
+  hAlpha_on->SetMarkerSize(0.7);
+  hAlpha_on->SetMarkerColor(kBlack);
+  hAlpha_on->SetTitle("Alpha plot form -90 to 90 deg");
+  hAlpha_off->SetTitle("Alpha plot form -90 to 90 deg");
+
+  hAlpha_on->DrawCopy("E1P");
+  hAlpha_off->DrawCopy("HISTSAME");
+  hAlpha_off->DrawCopy("ESAME");
+  hAlpha_on->DrawCopy("E1PSAME");
+
+  Double_t chialpha90 = ChiSquareNDof((TH1D*)hAlpha_on,(TH1D*)hAlpha_off);
+
+  x_label_pos  = 90.*0.5;
+  y_label_pos  = hAlpha_on->GetBinContent(hAlpha_on->GetMaximumBin())/2.;
+
+  char text_alpha90[256];
+  sprintf(text_alpha90,"ChiSquare/NDof = %4.2f",chialpha90);
+
+  TLatex *talpha90 = new TLatex(x_label_pos, y_label_pos, text_alpha90);
+  talpha90->SetTextSize(textsize);
+//  talpha90->Draw();
+
+  gPad->Update();
+  gPad->Modified();
+
+  c6->Print(psname);
+
+  cout << "---> ChiSquare/NDof [Size] =\t\t" << chisize << endl;
+  cout << "---> ChiSquare/NDof [Dist] =\t\t" << chidist << endl;
+  cout << "---> ChiSquare/NDof [Width] =\t\t" << chiwidth << endl;
+  cout << "---> ChiSquare/NDof [Length] =\t\t" << chilength << endl;
+  cout << "---> ChiSquare/NDof [Abs(Alpha)] =\t" << chialpha << endl;
+  cout << "---> ChiSquare/NDof [Alpha] =\t\t" << chialpha90 << endl;
+
+
+  TCanvas *c7 = new TCanvas;
+  hSrcPos_on->DrawCopy("BOX");
+  c7->Print(psname);
+
+  TCanvas *c8 = new TCanvas;
+  hSrcPos_off->DrawCopy("BOX");
+  c8->Print(closepsname);
+
+  cout << "Done!!" <<endl;
+  
+}
+
+
+Double_t ChiSquareNDof(TH1D *h1, TH1D *h2)
+{
+    Double_t chiq = 0.;
+    Double_t chi;
+    Double_t error;
+    Int_t nbinsnozero = 0;
+
+    Int_t nbins = h1->GetNbinsX();
+    if (nbins != h2->GetNbinsX() || nbins == 0)
+	return -1;
+
+    for (UInt_t bin=1; bin<=nbins; bin++)
+    {
+	error = sqrt(h1->GetBinError(bin)*h1->GetBinError(bin) +
+			   h2->GetBinError(bin)*h2->GetBinError(bin));
+	if (error != 0)
+	{
+	    chi = (h1->GetBinContent(bin)-h2->GetBinContent(bin))/error;
+	    chiq += chi*chi;
+	    nbinsnozero++;
+	}
+    }
+
+    return (nbinsnozero>0?chiq/nbinsnozero:0);
+}
+
+Int_t GetBin(Double_t size, Int_t numberSizeBins, Double_t sizeBins[])
+{
+
+  Int_t result = -1;
+
+  Int_t lowerbin = 0;
+  Int_t upperbin = numberSizeBins;
+  Int_t bin;
+
+  Int_t count = 0;
+
+  if (size >= sizeBins[0])
+    {
+      while (upperbin - lowerbin > 1 && count++<=numberSizeBins)
+	{
+	  bin = (upperbin+lowerbin)/2;
+	  if (size >= sizeBins[bin])
+	    lowerbin = bin;
+	  else
+	    upperbin = bin;
+	}
+      result = count<=numberSizeBins?lowerbin:-1;
+    }
+
+  return result;
+
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/makeHillas.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/makeHillas.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/makeHillas.C	(revision 9772)
@@ -0,0 +1,558 @@
+/*********************************/
+/* Compute the hillas parameters */
+/*********************************/
+
+Bool_t readDatacards(TString& filename);
+
+// initial and final time slices to be used in signal extraction
+const Byte_t hifirst = 0;
+const Byte_t hilast  = 13;
+const Byte_t lofirst = 3;
+const Byte_t lolast  = 12;
+
+// declaration of variables read from datacards
+TString  outname;
+TString  idirname;
+MRunIter pedcaliter;
+MRunIter caliter;
+MRunIter pediter;
+MRunIter datiter;
+ULong_t  nmaxevents=999999999;
+Short_t  calflag=1;
+Float_t  lcore = 3.0;
+Float_t  ltail = 1.5;
+Int_t islflag = 0;
+Float_t  lnew  = 40;
+Int_t  kmethod = 1;
+Int_t    nfiles = 0;
+
+const TString defaultcard="input.datacard";
+
+//Slow control varialbles
+Short_t slowflag=0;
+Bool_t  isSlowControlAvailable = kFALSE;
+TString hvConfigFile="/mnt/users/jlopez/Mars/Files4Mars/Config/HVSettings_FF35q.conf";
+TString continuosLightFile="/local_disk/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+
+
+/*************************************************************/
+int makeHillas(TString datacard = defaultcard)
+{
+
+  if(!datacard.Length())
+    datacard = defaultcard;
+
+  if(!readDatacards(datacard))
+    {
+      cout << "Error reading datacards. Stoping" << endl;
+      return -1;
+    }
+
+  // Set the general tasks/containers
+  MExtractFixedWindow    extractor;
+  extractor.SetRange(hifirst,hilast,lofirst,lolast);
+
+  MCalibrationQECam   qecam;
+  MBadPixelsCam       badcam;
+  MGeomCamMagic       geomcam;
+  MGeomApply          geomapl;
+
+  cout << endl;
+  cout << "/****************************************************/" << endl;
+  cout << "/* FIRST LOOP: PEDESTAL FOR CALIBRATION COMPUTATION */" << endl;
+  cout << "/****************************************************/" << endl;
+  cout << endl;
+
+  // If you want to exclude pixels from the beginning, read 
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)  
+  ifstream fin("badpixels.dat");
+  badcam.AsciiRead(fin);
+  fin.close();
+
+  MJPedestal pedloop0;
+  pedloop0.SetOutputPath("./");
+  pedloop0.SetInput(&pedcaliter);
+  pedloop0.SetExtractor(&extractor);
+  pedloop0.SetBadPixels(badcam);
+
+  if (!pedloop0.Process())
+    return;
+
+  cout << endl;
+  cout << "/*****************************/" << endl;
+  cout << "/* SECOND LOOP: CALIBRATION  */" << endl;
+  cout << "/*****************************/" << endl;        
+  cout << endl;
+
+  MJCalibration calloop;
+
+  calloop.SetOutputPath("./");
+  calloop.SetExtractor(&extractor);
+  calloop.SetInput(&caliter);
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop0.GetBadPixels());
+  if (!calloop.Process(pedloop0.GetPedestalCam()))
+    return;
+
+  cout << endl;
+  cout << "/*************************************************/" << endl;
+  cout << "/* THIRD LOOP: PEDESTAL CALIBRATION INTO PHOTONS */" << endl;
+  cout << "/*************************************************/" << endl;
+  cout << endl;
+
+  // First Compute the pedestals
+  MJPedestal pedloop;
+  pedloop.SetOutputPath("./");
+  pedloop.SetInput(&pediter);
+
+  if (!pedloop.Process())
+    return;
+
+  MPedestalCam pedcam = pedloop.GetPedestalCam();
+
+  // Now convert this pedestals in photons
+  MParList  plist3;
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+  
+  // containers
+  MCerPhotEvt         nphot;
+  MPedPhotCam         nphotrms;
+  MExtractedSignalCam sigcam;
+
+  plist3.AddToList(&geomcam);
+  plist3.AddToList(&pedcam);
+  plist3.AddToList(&calloop.GetCalibrationCam());
+  plist3.AddToList(&qecam);
+  plist3.AddToList(&badcam);
+  plist3.AddToList(&sigcam);
+  plist3.AddToList(&nphot);
+  plist3.AddToList(&nphotrms);
+
+  
+  MCalibrate::CalibrationMode_t calMode=MCalibrate::kDefault;  
+  if(calflag==0)
+    calMode=MCalibrate::kNone;
+  if(calflag==-1)
+    calMode=MCalibrate::kDummy;
+
+  //tasks
+  MReadMarsFile read3("Events");
+  static_cast<MRead&>(read3).AddFiles(pediter); 
+  read3.DisableAutoScheme();
+ 
+//   MReadReports read3;
+//   read3.AddTree("Events","MTime.",kFALSE);
+//   static_cast<MRead&>(read3).AddFiles(pediter); 
+
+   //  MExtractSignal  extsig;
+  //  extsig.SetRange(hifirst,hilast,lofirst,lolast);
+  MCalibrate      photcalc(calMode);
+  MPedPhotCalc    photrmscalc; 
+  
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&extractor);
+  tlist3.AddToList(&photcalc);
+  tlist3.AddToList(&photrmscalc);
+
+  // Create and setup the eventloop
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+  if (!evtloop3.Eventloop())
+    return;
+  
+  tlist3.PrintStatistics();
+
+  cout << "/**********************************************/" << endl;
+  cout << "/* FOURTH LOOP: DATA CALIBRATION INTO PHOTONS */" << endl;
+  cout << "/**********************************************/" << endl;
+
+  MParList  plist4;
+  MTaskList tlist4;
+  plist4.AddToList(&tlist4);
+  
+  // containers 
+  MHillas       hillas;
+  MSrcPosCam    source;
+  MRawRunHeader runhead;
+
+  MArrivalTimeCam   timecam;
+     
+  MIslands      isl;
+  isl.SetName("MIslands1");
+  
+  MIslands      isl2;
+  isl2.SetName("MIslands2");
+
+  MReportDrive  drive;
+  MStarLocalCam starcam;
+
+  if (islflag == 1 || islflag == 2)
+    {
+      plist4.AddToList(&timecam);
+      plist4.AddToList(&isl);
+    }
+  
+  if (islflag == 2)
+    {
+      plist4.AddToList(&isl2);
+    }
+
+  if (isSlowControlAvailable)
+    {
+      plist4.AddToList(&starcam);
+    }
+  
+  
+  plist4.AddToList(&geomcam);
+  plist4.AddToList(&pedcam);
+  plist4.AddToList(&calloop.GetCalibrationCam());
+  plist4.AddToList(&qecam);
+  plist4.AddToList(&badcam);
+  plist4.AddToList(&nphot);
+  plist4.AddToList(&nphotrms);
+  plist4.AddToList(&source);
+  plist4.AddToList(&hillas);
+  plist4.AddToList(&runhead);
+  
+  //tasks
+//   MReadMarsFile read4("Events");
+//   static_cast<MRead&>(read4).AddFiles(datiter); 
+//   read4.DisableAutoScheme();
+
+  MReadReports read4;
+  read4.AddTree("Events","MTime.",kTRUE);
+  read4.AddTree("Currents");
+  read4.AddTree("Camera");
+  read4.AddTree("Drive");
+  static_cast<MRead&>(read4).AddFiles(datiter); 
+  read4.AddToBranchList("MReportCurrents.*");
+
+  // Task that use Slow control information 
+  MFHVNotNominal fhvnotnominal;
+  fhvnotnominal.SetHVNominalValues(hvConfigFile);
+  fhvnotnominal.SetMaxNumPixelsDeviated(40);
+ 
+  MContinue hvnotnominal(&fhvnotnominal);
+
+  MCalibrateDC dccalib;
+  dccalib.SetFileName(continuosLightFile);
+
+  const Int_t numblind = 5;
+  const Short_t w[numblind] = { 47, 124, 470, 475, 571};
+  const TArrayS blindpixels(numblind,(Short_t*)w);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 3.5;
+  UInt_t integratedevents = 4;
+
+  MFindStars findstars;
+  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+
+  MSrcPosFromStars srcposfromstar;
+    
+  MBadPixelsTreat   interpolatebadpixels;
+  interpolatebadpixels.SetUseInterpolation();
+  
+  MImgCleanStd      clean(lcore,ltail);
+
+  MArrivalTimeCalc2 timecalc;
+  
+  MIslandCalc       island;
+  island.SetOutputName("MIslands1");
+
+  MIslandClean      islclean(lnew);
+  islclean.SetInputName("MIslands1");
+  islclean.SetMethod(kmethod);
+      
+  MIslandCalc       island2;
+  island2.SetOutputName("MIslands2");  
+  
+  
+  MHillasCalc       hcalc;
+  MHillasSrcCalc    csrc1;
+  
+  MWriteRootFile write(outname,"RECREATE");
+  
+  write.AddContainer("MTime"          , "Parameters");
+  write.AddContainer("MHillas"        , "Parameters");
+  write.AddContainer("MHillasSrc"     , "Parameters");
+  write.AddContainer("MHillasExt"     , "Parameters");
+  write.AddContainer("MNewImagePar"   , "Parameters");
+  write.AddContainer("MRawEvtHeader"  , "Parameters");
+  write.AddContainer("MRawRunHeader"  , "Parameters");
+  write.AddContainer("MConcentration" , "Parameters");
+  write.AddContainer("MSrcPosCam"     , "Parameters");
+
+  if (islflag == 1 || islflag == 2)
+    write.AddContainer("MIslands1" , "Parameters");
+  if (islflag == 2) 
+    write.AddContainer("MIslands2" , "Parameters");
+  if (isSlowControlAvailable)
+    {
+      write.AddContainer("MStarLocalCam" , "Parameters");
+      write.AddContainer("MReportDrive" , "Parameters");
+    }
+  
+  tlist4.AddToList(&read4);
+  tlist4.AddToList(&geomapl);
+  if (isSlowControlAvailable)
+    {
+      tlist4.AddToList(&hvnotnominal,"Events");
+      tlist4.AddToList(&dccalib,"Currents");
+      tlist4.AddToList(&findstars,"Currents");
+      tlist4.AddToList(&srcposfromstar,"Events");
+    }
+                       
+  tlist4.AddToList(&extractor,"Events");
+  tlist4.AddToList(&photcalc,"Events");
+  if(calflag==11)
+    tlist4.AddToList(&interpolatebadpixels);
+  tlist4.AddToList(&clean,"Events");
+
+  if (islflag == 1 || islflag == 2)
+    {
+      tlist4.AddToList(&timecalc,"Events");
+      tlist4.AddToList(&island,"Events");
+    }
+
+  if (islflag == 2)
+    {
+      tlist4.AddToList(&islclean,"Events");
+      tlist4.AddToList(&island2,"Events");
+    }
+  
+  //tlist4.AddToList(&blind2,"Events");
+  tlist4.AddToList(&hcalc,"Events");
+  tlist4.AddToList(&csrc1,"Events");
+  tlist4.AddToList(&write,"Events");
+
+  // Create and setup the eventloop
+  MEvtLoop datloop;
+  datloop.SetParList(&plist4);
+
+  cout << endl;
+  cout << "******************************************************" << endl;
+  cout << "* COMPUTING DATA USING EXTRACTED SIGNAL (IN PHOTONS) *" << endl;
+  cout << "******************************************************" << endl;
+  cout << endl;
+
+  if (!datloop.Eventloop(nmaxevents))
+    return;
+
+  tlist4.PrintStatistics();    
+
+}
+//-------------------------------------------------------------------------------
+
+Bool_t readDatacards(TString& filename)
+{
+  ifstream ifun(filename.Data());
+  if(!ifun)
+    {
+      cout << "File " << filename << " not found" << endl;
+      return kFALSE;
+    }
+
+  TString word;
+  
+  while(ifun >> word)
+    {
+
+      // skip comments
+      if(word[0]=='/' && word[1]=='/')
+	{
+	  while(ifun.get()!='\n'); // skip line
+	  continue;
+	}
+
+      // number of events
+      if(strcmp(word.Data(),"NEVENTS")==0)
+	ifun >> nmaxevents;
+
+
+      // input file directory
+      if(strcmp(word.Data(),"IDIR")==0)
+	{
+	  if(idirname.Length())
+	    cout << "readDataCards Warning: overriding input directory file name" << endl;
+	  ifun >> idirname;
+	}
+
+       // pedestal runs for calibration
+      if(strcmp(word.Data(),"PCRUNS")==0)
+	{
+	  if(pedcaliter.GetNumRuns())
+	    cout << "readDataCards Warning: adding pedestal runs for calibration to the existing list" << endl;
+	  ifun >> word;
+	  pedcaliter.AddRuns(word.Data(),idirname.Data());
+	}
+
+      // calibration runs
+      if(strcmp(word.Data(),"CRUNS")==0)
+	{
+	  if(caliter.GetNumRuns())
+	    cout << "readDataCards Warning: adding calibration runs to the existing list" << endl;
+	  ifun >> word;
+	  caliter.AddRuns(word.Data(),idirname.Data());
+	}
+
+     // pedestal runs for data
+      if(strcmp(word.Data(),"PRUNS")==0)
+	{
+	  if(pediter.GetNumRuns())
+	    cout << "readDataCards Warning: adding pedestal runs for data to the existing list" << endl;
+	  ifun >> word;
+	  pediter.AddRuns(word.Data(),idirname.Data());
+	}
+
+      // data runs
+      if(strcmp(word.Data(),"DRUNS")==0)
+	{
+	  if(datiter.GetNumRuns())
+	    cout << "readDataCards Warning: adding data runs to the existing list" << endl;
+	  ifun >> word;
+	  datiter.AddRuns(word.Data(),idirname.Data());
+	}
+      
+      // output file name
+      if(strcmp(word.Data(),"OUTFILE")==0)
+	{
+	  if(outname.Length())
+	    cout << "readDataCards Warning: overriding output file name" << endl;
+	  ifun >> outname;
+	}
+
+      // calibration flag
+      if(strcmp(word.Data(),"CALFLAG")==0)
+	ifun >> calflag;
+
+      // cleaning level
+      if(strcmp(word.Data(),"CLEANLEVEL")==0)
+	{
+	  ifun >> lcore;
+	  ifun >> ltail;
+	}
+
+      if(strcmp(word.Data(),"ISLFLAG")==0)
+	{
+	  ifun >> islflag;
+	}
+
+      // island cleaning 
+      if (islflag == 2){
+	if(strcmp(word.Data(),"ISLANDCLEAN")==0)
+	  {
+	    ifun >> kmethod;
+	    ifun >> lnew;
+	  }
+      }
+
+      // slow control data available
+      if(strcmp(word.Data(),"SLOWCRT")==0)
+	{
+	  ifun >> slowflag;
+          if (slowflag == 1) isSlowControlAvailable = kTRUE;
+	}
+
+      // hv configuration file
+      if(strcmp(word.Data(),"HVCONFFILE")==0)
+	{
+	  ifun >> hvConfigFile;
+	}
+
+      // countinous light file to calibrate the dc data
+      if(strcmp(word.Data(),"CLFILE")==0)
+	{
+	  ifun >> continuosLightFile;
+	}
+    }
+
+  pedcaliter.Reset();
+  pediter.Reset();
+  caliter.Reset();
+  datiter.Reset();
+  TString pfile;
+
+  // Dump read values
+  cout << "************************************************" << endl;
+  cout << "* Datacards read from file " << filename << endl;
+  cout << "************************************************" << endl;
+  cout << "Pedestal file (s) for calibration: "  << endl;
+  while(kTRUE)
+  {
+      pfile=pedcaliter.Next();
+      if (pfile.IsNull())
+	  break;
+      cout << pfile << endl;
+  }
+  cout << "Calibration file (s): "  << endl;
+  while(kTRUE)
+  {
+      pfile=caliter.Next();
+      if (pfile.IsNull())
+	  break;
+      cout << pfile << endl;
+  }
+  cout << "Pedestal file (s) for data: "  << endl;
+  while(kTRUE)
+  {
+      pfile=pediter.Next();
+      if (pfile.IsNull())
+	  break;
+      cout << pfile << endl;
+  }
+  cout << "Data file (s): "  << endl;
+  while(kTRUE)
+  {
+      pfile=datiter.Next();
+      if (pfile.IsNull())
+	  break;
+      cout << pfile << endl;
+  }
+  cout << "Maximum number of events: " << nmaxevents << endl;
+  cout << "Output file name: " << outname << endl;
+  cout << "Calibration flag: " << calflag << endl;
+  cout << "Cleaning level: ("<<lcore<<","<<ltail<<")" << endl;
+  if (islflag == 1 || islflag == 2)
+    cout << "Island calcultation..." << endl;
+  if (islflag == 2)
+    {
+      cout << "Island Cleaning: "<< kmethod <<" method  "<< lnew << " new threshold" << endl;
+    }
+  cout << "***********" << endl << endl;
+  
+  if(!pediter.GetNumEntries())
+    {
+      cout << "No pedestal file name specified" << endl;
+      return kFALSE;
+    }
+  if(!caliter.GetNumEntries())
+    {
+      cout << "No calibration file name specified" << endl;
+      return kFALSE;
+    }
+  if(!datiter.GetNumEntries())
+    {
+      cout << "No data file name specified" << endl;
+      return kFALSE;
+    }
+  if(!outname.Length())
+    {
+      cout << "No output file name specified" << endl;
+      return kFALSE;
+    }
+
+  if (isSlowControlAvailable)
+    {
+      cout << "HV Configuratin file: " << hvConfigFile << endl;
+      cout << "Continous Light file: " << continuosLightFile << endl;
+    }
+  
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/makeHillasMC.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/makeHillasMC.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/makeHillasMC.C	(revision 9772)
@@ -0,0 +1,435 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Thomas Bretz      5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+   !              Abelardo Moralejo 1/2004 <mailto:moralejo@pd.infn.it>
+   !              Eva Domingo       1/2005 <mailto:domingo@ifae.es>
+   !             
+   !   Copyright: MAGIC Software Development, 2000-2004
+   !
+   !
+   \* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  STARMC - STandard Analysis and Reconstruction (MC example)
+//
+//  This macro is a version of the standard converter to convert raw data 
+//  into image parameters, made to show how to run analysis on MC files. 
+//
+//  (1/2005):: Spline extractor added and additional containers written out
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MImgCleanStd.h"
+
+void makeHillasMC()
+{
+  //
+  // This is a demonstration program which calculates the image 
+  // parameters from Magic Monte Carlo files (output of camera).
+
+
+  TString* CalibrationFilename;
+  TString* AnalysisFilename;
+  TString* OutFilename1;
+  TString* OutFilename2;
+
+  TString  rffilename;
+  TString  dispfilename;
+
+  // ------------- USER CHANGE -----------------
+  // Comment line starting "CalibrationFileName" to disable calibration. 
+  // In that case the units of the MHillas.fSize parameter will be ADC counts 
+  // (rather, equivalent ADC counts in inner pixels, since we correct for the 
+  // possible differences in gain of outer pixels)
+
+  // File to be used in the calibration (must be a camera file without added noise)
+  CalibrationFilename = new TString("/mnt/local_wdjrico/jrico/mc/Gammas/Gamma_zbin3_90_7_1290to1299_w0_nonoise.root");
+  // File to be analyzed
+  AnalysisFilename = new TString("/mnt/users/blanch/magic/TestSample/file*.root");
+
+  // Change output file names as desired. 
+  // If you want only one output (not dividing the events in Train and Test samples),
+  // comment the initialization of OutFilename2.
+  OutFilename1 = new TString("/mnt/users/blanch/Temp/Prova.root");
+  //  OutFilename2 = new TString("star_test.root");    // Output file name 2 (train)
+
+  // File to read RandomForest
+  rffilename="/mnt/users/blanch/magic/Mars-All/Mars_Standard06/mtemp/mifae/programs/RFstd.root";
+  // File to read Disp
+  dispfilename="/mnt/users/blanch/magic/Mars-All/Mars_Standard06/mtemp/mifae/programs/DISPstd.root";
+
+  // Fraction of events (taken at random) which one wants to process from the 
+  // file to be analyzed (useful to make smaller files if starting sample is too large).
+  Float_t accepted_fraction = 1.;
+
+
+  // ------------- USER CHANGE -----------------
+  // Cleaning levels
+  Float_t CleanLev[2] = {4.0, 3.5}; // Tail cuts for image analysis
+
+  // Signal extractor
+  // (default=Spline, other extraction methods can be used)
+  const Int_t wsize=2;
+  MExtractor* sigextract = new MExtractTimeAndChargeSpline();
+  ((MExtractTimeAndChargeSpline*)sigextract)->SetTimeType(MExtractTimeAndChargeSpline::kHalfMaximum);
+  ((MExtractTimeAndChargeSpline*)sigextract)->SetChargeType(MExtractTimeAndChargeSpline::kIntegral);      
+  ((MExtractTimeAndChargeSpline*)sigextract)->SetRiseTime((Float_t)wsize*0.25); 
+  ((MExtractTimeAndChargeSpline*)sigextract)->SetFallTime((Float_t)wsize*0.75);  
+  // Define FADC slices to be integrated in high and low gain:
+  sigextract->SetRange(1, 11, 2, 12);
+  // Defines when to switch to low gain
+  sigextract->SetSaturationLimit(240);
+
+
+  // -------------------------------------------
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  //  MGeomCamMagic geomcam;
+
+  //  MSrcPosCam src;
+  // WOBBLE MODE!!
+  //  src.SetX(120.);  // units: mm
+  //  src.SetXY(0.,0.4/geomcam.GetConvMm2Deg());
+  //  src.SetXY(0.,0.); 
+  //  src.SetReadyToSave();
+
+  MBadPixelsCam badpix;
+
+  //  plist.AddToList(&geomcam);
+  //  plist.AddToList(&src);
+  plist.AddToList(&badpix);
+
+  MCerPhotEvt     nphot;
+  // Stores number of phe
+  plist.AddToList(&nphot);
+  
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+  if (CalibrationFilename)
+    read.AddFile(CalibrationFilename->Data());
+  read.DisableAutoScheme();
+
+  MGeomApply geom; 
+  // Reads in geometry from MC file and sets the right sizes for
+  // several parameter containers.
+
+  MMcPedestalCopy   pcopy; 
+  // Copies pedestal data from the MC file run fadc header to the MPedestalCam container.
+
+  MPointingPosCalc pointcalc;
+  // Creates MPointingPos object and fill it with the telescope orientation
+  // information taken from MMcEvt.
+
+  MMcCalibrationUpdate  mccalibupdate;
+
+  MCalibrateData calib; 
+  // Transforms signals from ADC counts into photons. In the first
+  // loop it applies a "dummy" calibration supplied by MMcCalibrationUpdate, just 
+  // to equalize inner and outer pixels. At the end of the first loop, in the
+  // PostProcess of MMcCalibrationCalc (see below) the true calibration constants
+  // are calculated.
+  calib.SetCalibrationMode(MCalibrateData::kFfactor);
+
+  //    MBlindPixelCalc   blind;
+  //    blind.SetUseInterpolation();
+
+  MMcCalibrationCalc mccalibcalc; 
+  // Calculates calibration constants to convert from ADC counts to photons.
+
+  MAddGainFluctuation gainfluc;
+  //gainfluc.FillHist(1,0.5);
+  gainfluc.FillHist(0,0.1); // defaul line to not add fluctuations
+  // Adds Gain fluctuations
+
+  MImgCleanStd  clean(CleanLev[0], CleanLev[1]); 
+  // Applies tail cuts to image. Since the calibration is performed on 
+  // noiseless camera files, the precise values of the cleaning levels 
+  // are unimportant for the calibration file processing (in any case, 
+  // only pixels without any C-photon will be rejected).
+  clean.SetCleanRings(1);
+  //  clean.SetRemoveSingle(kFALSE);
+  //  clean.SetMethod(MImgCleanStd::kDemocratic);
+
+  MHillasCalc   hcalc; 
+  // Calculates Hillas parameters.
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geom);
+  tlist.AddToList(&pcopy);
+  tlist.AddToList(&pointcalc);
+  tlist.AddToList(sigextract);
+  tlist.AddToList(&mccalibupdate);
+  tlist.AddToList(&calib);
+  tlist.AddToList(&clean);
+  //  tlist.AddToList(&blind);
+  tlist.AddToList(&hcalc);
+  tlist.AddToList(&mccalibcalc);
+
+
+  //
+  // Open output files:
+  //
+
+  MWriteRootFile write1(OutFilename1->Data()); // Writes output1
+  write1.AddContainer("MRawRunHeader",       "RunHeaders");
+  write1.AddContainer("MMcRunHeader",        "RunHeaders");
+  write1.AddContainer("MSrcPosCam",          "RunHeaders");
+  write1.AddContainer("MGeomCam",            "RunHeaders");
+  write1.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+  write1.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+  write1.AddContainer("MMcFadcHeader",       "RunHeaders");
+  write1.AddContainer("MMcTrigHeader",       "RunHeaders");
+  write1.AddContainer("MGainFluctuationCam", "RunHeaders");
+
+  write1.AddContainer("MRawEvtHeader",   "Events");
+  write1.AddContainer("MMcEvt",          "Events");
+  write1.AddContainer("MHillas",         "Events");
+  write1.AddContainer("MHillasExt",      "Events");
+  write1.AddContainer("MHillasSrc",      "Events");
+  write1.AddContainer("MImagePar",       "Events");
+  write1.AddContainer("MNewImagePar",    "Events");
+  write1.AddContainer("MConcentration",  "Events");
+  write1.AddContainer("MIslands",        "Events");
+  write1.AddContainer("MTopology",       "Events");
+  write1.AddContainer("MPointingPos",    "Events");
+  write1.AddContainer("MHadronness",     "Events");
+  write1.AddContainer("MImageParDisp"  , "Events");
+  //write1.AddContainer("MArrivalTimeCam", "Events");
+  //write1.AddContainer("MCerPhotEvt",     "Events");
+
+  if (OutFilename2)
+    {
+      MWriteRootFile write2(OutFilename2->Data()); // Writes output2
+      write2.AddContainer("MRawRunHeader",       "RunHeaders");
+      write2.AddContainer("MMcRunHeader",        "RunHeaders");
+      write2.AddContainer("MSrcPosCam",          "RunHeaders");
+      write2.AddContainer("MGeomCam",            "RunHeaders");
+      write2.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+      write2.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+      write2.AddContainer("MMcFadcHeader",       "RunHeaders");
+      write2.AddContainer("MMcTrigHeader",       "RunHeaders");
+      write2.AddContainer("MGainFluctuationCam", "RunHeaders");
+
+      write2.AddContainer("MRawEvtHeader",   "Events");
+      write2.AddContainer("MMcEvt",          "Events");
+      write2.AddContainer("MHillas",         "Events");
+      write2.AddContainer("MHillasExt",      "Events");
+      write2.AddContainer("MHillasSrc",      "Events");
+      write2.AddContainer("MImagePar",       "Events");
+      write2.AddContainer("MNewImagePar",    "Events");
+      write2.AddContainer("MConcentration",  "Events");
+      write2.AddContainer("MIslands",        "Events");
+      write2.AddContainer("MTopology",       "Events");
+      write2.AddContainer("MPointingPos",    "Events");
+      write2.AddContainer("MHadronness",     "Events");
+      write2.AddContainer("MImageParDisp"  , "Events");
+      //write2.AddContainer("MArrivalTimeCam", "Events");
+      //write2.AddContainer("MCerPhotEvt",     "Events");
+
+
+      // Divide output in train and test samples, using the event number
+      // (odd/even) to achieve otherwise unbiased event samples:
+      MF filter1("{MMcEvt.fEvtNumber%2}>0.5");
+      MF filter2("{MMcEvt.fEvtNumber%2}<0.5");
+
+      write1.SetFilter(&filter1);
+      write2.SetFilter(&filter2);
+    }
+
+
+  //
+  // FIRST LOOP: Calibration loop (with no noise file)
+  //
+  MProgressBar bar;
+  bar.SetWindowName("Calibrating...");
+
+  MEvtLoop evtloop;
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (CalibrationFilename)
+    {
+      if (!evtloop.Eventloop())
+	return;
+      mccalibcalc.GetHistADC2PhotEl()->Write();
+      mccalibcalc.GetHistPhot2PhotEl()->Write();
+      // Writes out the histograms used for calibration.
+    }
+
+  //
+  // SECOND LOOP: TO READ THE RANDOM FOREST FILE(S) 
+  //
+
+  MParList   plistrf;
+  MTaskList  tlistrf;
+  MRanForest ranforest;
+  MRanTree   rantree;
+
+  if(rffilename.Length())
+    {
+      plistrf.AddToList(&tlistrf);
+      plistrf.AddToList(&ranforest);
+      plistrf.AddToList(&rantree);
+
+      MReadTree readrf("Tree",rffilename);
+      readrf.DisableAutoScheme();
+      
+      MRanForestFill rffill;
+      rffill.SetNumTrees(100);
+      
+      tlistrf.AddToList(&readrf);
+      tlistrf.AddToList(&rffill);
+      
+      MEvtLoop evtlooprf;
+      evtlooprf.SetParList(&plistrf);
+      if (!evtlooprf.Eventloop())
+	return;
+      
+      tlistrf.PrintStatistics();
+    }
+  
+
+  //
+  // THIRD LOOP: Analysis loop (process file with noise)
+  //
+  bar.SetWindowName("Analyzing...");
+
+  MIslands         isl;
+  MArrivalTimeCam  timecam;      
+  MTopology        topology;
+  plist.AddToList(&isl);
+  plist.AddToList(&timecam);
+  plist.AddToList(&topology);
+  plist.AddToList(&rantree);
+  plist.AddToList(&ranforest);
+ 
+  MArrivalTimeCalc2  timecalc;
+  // Calculates the arrival time as the mean time of the fWindowSize 
+  // time slices which have the highest integral content.
+  //  MArrivalTimeCalc timecalc;            
+  // Calculates the arrival times of photons. Returns the absolute 
+  // maximum of the spline that interpolates the FADC slices.
+
+  MIslandsCalc       islcalc;
+  islcalc.SetOutputName("MIslands");
+  islcalc.SetAlgorithm(1);
+  //  MIslandsClean      islclean(40);
+  //  islclean.SetInputName("MIslands");
+  //  islclean.SetMethod(1);
+
+  MTopologyCalc      topcalc;
+
+  // Change the read task by another one which reads the file we want to analyze:
+  MReadMarsFile read2("Events","/mnt/users/blanch/magic/TestSample/file*.root");
+  //  MReadMarsFile read2("Events","/mnt/users/blanch/magic/TestSample/file53.root");
+  //  read2.AddFile(AnalysisFilename->Data());
+  read2.DisableAutoScheme();
+  tlist.AddToListBefore(&read2, &read);
+  tlist.RemoveFromList(&read);
+
+
+  // Add new tasks (Islands and Topology calculations)
+  tlist.AddToListBefore(&timecalc,&mccalibupdate);
+  tlist.AddToListBefore(&islcalc,&hcalc);
+  //  tlist.AddToListBefore(&islclean,&hcalc);
+  tlist.AddToListBefore(&topcalc,&hcalc);
+
+  // Add Task to Add Gain Fluctuations
+  tlist.AddToListBefore(&gainfluc, &hcalc);
+
+  MGeomCamMagic geomcam;// = new MGeomCam();
+  plist.AddToList(&geomcam);
+
+
+  MHillasDisplay*  disphillas=NULL;
+  disphillas = new MHillasDisplay(&nphot,&geomcam);
+
+  // Analyze only the desired fraction of events, skip the rest:
+  MFEventSelector eventselector;
+  Float_t rejected_fraction = 1. - accepted_fraction; 
+  eventselector.SetSelectionRatio(rejected_fraction);
+  MContinue skip(&eventselector);
+  tlist.AddToListBefore(&skip, sigextract);
+
+  // Remove calibration task from list.
+  tlist.RemoveFromList(&mccalibcalc); 
+
+  // disp
+  // (read in optimum Disp parameter values)  
+  MDispParameters dispin;
+  TArrayD dispPar;
+  if(dispfilename.Length())
+    {
+      TFile inparam(dispfilename);
+      dispin.Read("MDispParameters");
+      cout << "Optimum parameter values taken for calculating Disp : " << endl;
+
+      dispPar =  dispin.GetParameters();
+      for (Int_t i=0; i<dispPar.GetSize(); i++)
+	cout << dispPar[i] << ",  ";
+      cout << endl;
+      
+      inparam.Close();
+    }
+  // Disp results container
+  MImageParDisp imagepardisp;
+  // Disp histograms
+  MHDisp hdisp;
+  hdisp.SetName("MHDispAsym");
+  hdisp.SetSelectedPos(4);
+  MFillH filldisp("MHDispAsym[MHDisp]", "");
+  
+  // Add RandomForest and Disp task computation
+  MRanForestCalc hadrcalc;
+  MDispCalc         dispcalc;  
+
+  tlist.AddToList(&dispcalc);
+  tlist.AddToList(&filldisp);
+  if(rffilename.Length())
+    tlist.AddToList(&hadrcalc);
+ 
+  // Add tasks to write output:
+  if (OutFilename2)
+    {
+      tlist.AddToList(&filter1);
+      tlist.AddToList(&filter2);
+      tlist.AddToList(&write2); 
+    }
+  tlist.AddToList(&write1); 
+
+  // Add display image with hillas
+  disphillas->SetPSFile();
+  disphillas->SetPSFileName("provaGF.ps");
+  disphillas->SetPause(kFALSE);	
+  //tlist.AddToList(disphillas);
+  
+
+  if (!evtloop.Eventloop())
+    return;
+
+  tlist.PrintStatistics();
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/mergeClean.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/mergeClean.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/mergeClean.C	(revision 9772)
@@ -0,0 +1,411 @@
+/* ======================================================================== *\
+!   Take different MC input files and combine them into single one
+!   Author(s): Oscar Blanch & Javier Rico
+\* ======================================================================== */
+
+void mergeClean()
+{
+  const TString fileout = "/local_disk/jrico/mc/prueba.root";
+
+  const Int_t nfiles = 11;
+  const Int_t nlevels= 5;
+
+  const Char_t* levelname[nlevels]={"noclean","3015","4025","5035","6045"};
+
+  // input files -- no noise
+  const Char_t* NonoiseOutFilename[nfiles] = 
+    {"/local_disk/jrico/mc/Gamma_zbin0_0_7_1000to1009_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin0_0_7_1130to1139_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin0_90_7_1260to1269_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin1_0_7_1010to1019_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin1_0_7_1140to1149_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin1_90_7_1270to1279_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin2_0_7_1020to1029_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin2_0_7_1150to1159_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin3_0_7_1030to1039_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin3_0_7_1160to1169_w0_cleaned_nonoise.root",
+     "/local_disk/jrico/mc/Gamma_zbin3_90_7_1290to1299_w0_cleaned_nonoise.root"
+    };
+
+  // input files -- different cleaning levels
+  const Char_t* NoiseOutFilename[nlevels][nfiles]   = 
+    {{"/local_disk/jrico/mc/Gamma_zbin0_0_7_1000to1009_w0_cleaned_noclean.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_0_7_1130to1139_w0_cleaned_noclean.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_90_7_1260to1269_w0_cleaned_noclean.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1010to1019_w0_cleaned_noclean.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1140to1149_w0_cleaned_noclean.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_90_7_1270to1279_w0_cleaned_noclean.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1020to1029_w0_cleaned_noclean.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1150to1159_w0_cleaned_noclean.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1030to1039_w0_cleaned_noclean.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1160to1169_w0_cleaned_noclean.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_90_7_1290to1299_w0_cleaned_noclean.root"},
+     {"/local_disk/jrico/mc/Gamma_zbin0_0_7_1000to1009_w0_cleaned_3015.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_0_7_1130to1139_w0_cleaned_3015.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_90_7_1260to1269_w0_cleaned_3015.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1010to1019_w0_cleaned_3015.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1140to1149_w0_cleaned_3015.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_90_7_1270to1279_w0_cleaned_3015.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1020to1029_w0_cleaned_3015.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1150to1159_w0_cleaned_3015.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1030to1039_w0_cleaned_3015.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1160to1169_w0_cleaned_3015.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_90_7_1290to1299_w0_cleaned_3015.root"},
+     {"/local_disk/jrico/mc/Gamma_zbin0_0_7_1000to1009_w0_cleaned_4025.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_0_7_1130to1139_w0_cleaned_4025.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_90_7_1260to1269_w0_cleaned_4025.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1010to1019_w0_cleaned_4025.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1140to1149_w0_cleaned_4025.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_90_7_1270to1279_w0_cleaned_4025.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1020to1029_w0_cleaned_4025.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1150to1159_w0_cleaned_4025.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1030to1039_w0_cleaned_4025.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1160to1169_w0_cleaned_4025.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_90_7_1290to1299_w0_cleaned_4025.root"},   
+     {"/local_disk/jrico/mc/Gamma_zbin0_0_7_1000to1009_w0_cleaned_5035.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_0_7_1130to1139_w0_cleaned_5035.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_90_7_1260to1269_w0_cleaned_5035.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1010to1019_w0_cleaned_5035.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1140to1149_w0_cleaned_5035.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_90_7_1270to1279_w0_cleaned_5035.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1020to1029_w0_cleaned_5035.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1150to1159_w0_cleaned_5035.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1030to1039_w0_cleaned_5035.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1160to1169_w0_cleaned_5035.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_90_7_1290to1299_w0_cleaned_5035.root"},
+     {"/local_disk/jrico/mc/Gamma_zbin0_0_7_1000to1009_w0_cleaned_6045.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_0_7_1130to1139_w0_cleaned_6045.root",   
+      "/local_disk/jrico/mc/Gamma_zbin0_90_7_1260to1269_w0_cleaned_6045.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1010to1019_w0_cleaned_6045.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_0_7_1140to1149_w0_cleaned_6045.root",
+      "/local_disk/jrico/mc/Gamma_zbin1_90_7_1270to1279_w0_cleaned_6045.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1020to1029_w0_cleaned_6045.root",
+      "/local_disk/jrico/mc/Gamma_zbin2_0_7_1150to1159_w0_cleaned_6045.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1030to1039_w0_cleaned_6045.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_0_7_1160to1169_w0_cleaned_6045.root",
+      "/local_disk/jrico/mc/Gamma_zbin3_90_7_1290to1299_w0_cleaned_6045.root"}
+    };   
+
+
+  // Getting input braches 
+  TChain* tno  = new TChain("Events");
+  TChain* tyes[nlevels];
+  for(Int_t i=0;i<nlevels;i++)
+    tyes[i] = new TChain("Events");
+
+  for(Int_t i=0;i<nfiles;i++)
+    {
+      tno->Add(NonoiseOutFilename[i]);
+      for(Int_t j=0;j<nlevels;j++)
+	tyes[j]->Add(NoiseOutFilename[j][i]);
+    }
+
+  // input braches for no noise file
+  MCerPhotEvt*   nphotNo;
+  MHillas*       hillasNo;
+  MHillasSrc*    hillassrcNo;
+  MMcEvt*        mcevtNo;
+  MRawEvtHeader* evtheaderNo;
+  MRawRunHeader* runheaderNo;
+
+  tno->SetBranchAddress("MCerPhotEvt.",&nphotNo);
+  tno->SetBranchAddress("MHillas.",&hillasNo);
+  tno->SetBranchAddress("MHillasSrc.",&hillassrcNo);
+  tno->SetBranchAddress("MMcEvt.",&mcevtNo);
+  tno->SetBranchAddress("MRawEvtHeader.",&evtheaderNo);
+  tno->SetBranchAddress("MRawRunHeader.",&runheaderNo);
+
+  
+  // input branches for noise files
+  MCerPhotEvt*   nphotYes[nlevels];
+  MHillas*       hillasYes[nlevels];
+  MHillasSrc*    hillassrcYes[nlevels];
+  MMcEvt*        mcevtYes[nlevels];
+  MRawEvtHeader* evtheaderYes[nlevels];
+  MRawRunHeader* runheaderYes[nlevels];
+
+  for(Int_t i=0;i<nlevels;i++)
+    {      
+      tyes[i]->SetBranchAddress("MCerPhotEvt.",&nphotYes[i]);
+      tyes[i]->SetBranchAddress("MHillas.",&hillasYes[i]);
+      tyes[i]->SetBranchAddress("MHillasSrc.",&hillassrcYes[i]);
+      tyes[i]->SetBranchAddress("MMcEvt.",&mcevtYes[i]);
+      tyes[i]->SetBranchAddress("MRawEvtHeader.",&evtheaderYes[i]);
+      tyes[i]->SetBranchAddress("MRawRunHeader.",&runheaderYes[i]);
+    }
+
+  // Setting ouput branches
+  TFile* fout = new TFile(fileout,"RECREATE");
+  TTree* to   = new TTree("Events","Events");   
+
+  // common containers
+  TBranch* bmcevt        = to->Branch("MMcEvt.",       "MMcEvt",       &mcevtNo);
+  TBranch* brawevtheader = to->Branch("MRawEvtHeader.","MRawEvtHeader",&evtheaderNo);
+  TBranch* brawrunheader = to->Branch("MRawRunHeader.","MRawRunHeader",&runheaderNo);
+
+  // noise/cleaning dependent containers
+  to->Branch("MCerPhotEvt0.",  "MCerPhotEvt",  &nphotNo);
+  to->Branch("MHillas0.",      "MHillas",      &hillasNo);
+  to->Branch("MHillasSrc0.",   "MHillasSrc",   &hillassrcNo);
+
+  //  cout << "llego1" << endl;
+  for(Int_t i=0;i<nlevels;i++)
+    {
+      //      cout << "i: " << i << endl;
+      
+      char mcerphot[100];
+      char mhillas[100];
+      char mhillassrc[100];
+
+
+      sprintf(mcerphot,  "MCerPhotEvt%s.",levelname[i]);
+      sprintf(mhillas,   "MHillas%s."    ,levelname[i]);
+      sprintf(mhillassrc,"MHillasSrc%s." ,levelname[i]);
+
+      to->Branch(mcerphot,  "MCerPhotEvt",  &nphotYes[i]);
+      to->Branch(mhillas,   "MHillas",      &hillasYes[i]);
+      to->Branch(mhillassrc,"MHillasSrc",   &hillassrcYes[i]);      
+    }
+  //  cout << "llego2" << endl;
+  
+      
+  Int_t nentries1 = (Int_t)tno->GetEntries();
+  cout << "Entries: No noise file: " << nentries1 << endl;
+  Int_t nentries2[nlevels];
+  Int_t latestk[nlevels];
+  Int_t latestevt[nlevels];
+  Int_t nfound[nlevels];
+  for(Int_t i=0;i<nlevels;i++)
+    {
+      nfound[i]=0;
+      latestk[i]=0;
+      latestevt[i]=99999999;
+      nentries2[i] = (Int_t)tyes[i]->GetEntries();
+      cout << "Entries: cleaning level [" << levelname[i] << "] :" << nentries2[i] << endl;
+    }
+
+  // loop over all events in no-noise file and look for them in the other files
+  for(Int_t i=0;i<nentries1;i++)
+    //  for(Int_t i=0;i<100;i++)
+    {      
+      tno->GetEntry(i);
+      Int_t runno = runheaderNo->GetRunNumber();
+      Int_t evtno = evtheaderNo->GetDAQEvtNumber();
+
+      cout << "Checking run " << runno<< ", event " << evtno << endl;
+
+      //check if the no-noise event is present in all of the other files
+      for(Int_t j=0;j<nlevels;j++)
+	{
+	  Int_t runyes;
+	  Int_t evtyes;
+	  cout << "Level " << levelname[j] << endl;
+	  Int_t k=latestk[j];	  
+	  while(k<nentries2[j])
+	    {
+	      //	      cout << k << endl;
+	      tyes[j]->GetEntry(k++);
+	      runyes = runheaderYes[j]->GetRunNumber();
+	      evtyes = evtheaderYes[j]->GetDAQEvtNumber();
+	      if(runyes==runno && evtyes==evtno)
+		break;
+	      // next condition speeds up selection when events are grouped by runs and
+	      // in event increasing order
+	      if(runyes==runno && latestevt[j]<evtno && evtno<evtyes)
+		break;
+	      // next condition speeds up selection when events are grouped by runs
+	      // and in run increasing order
+	      //	      if(runyes>runno)
+	      //		break;
+	    }
+
+	  if(k>=nentries2[j])
+	    {
+	      k=0;
+	      while(k<latestk[j])
+		{
+		  //		  cout << k << endl;
+		  tyes[j]->GetEntry(k++);
+		  runyes = runheaderYes[j]->GetRunNumber();
+		  evtyes = evtheaderYes[j]->GetDAQEvtNumber();
+		  if(runyes==runno && evtyes==evtno)
+		    break;
+		  // next condition speeds up selection when events are grouped by runs and
+		  // in event increasing order
+		  if(runyes==runno && latestevt[j]<evtno && evtno<evtyes)
+		    break;
+		  // next condition speeds up selection when events are grouped by runs
+		  // and in run increasing order
+		  //		  if(runyes>runno)
+		  //		    break;
+		}
+	    }
+	  
+	  // the event has not been found, assign dummy containers
+	  if(runyes=!runno || evtyes!=evtno)
+	    {
+	      cout << "Not Found!" << endl;	      
+	      for(Int_t l=j;l<nlevels;l++)
+		{
+		  nphotYes[l]->Reset();
+		  hillasYes[l]->Reset();
+		  hillassrcYes[l]->Reset();		  
+		}
+	      break;
+	    }
+	  else
+	    {
+	      cout << "Found!" << endl;
+	      latestevt[j] = evtyes;
+	      latestk[j]=k;	  
+	      nfound[j]++;
+	    }
+	}
+      to->Fill();
+    }
+
+  // loop over all events in first noise file and look for them in the no-noise file in order to save also purely noisy events  
+  cout << "***************************************" << endl;
+  cout << "*** Looking for purely noisy events ***" << endl;
+  cout << "***************************************" << endl;
+  Int_t nfound2[nlevels];
+  for(Int_t i=0;i<nlevels;i++)
+    {
+      nfound2[i]=0;
+      latestk[i]=0;
+      latestevt[i]=99999999;
+    }
+  
+  // readdress the common container addresses
+  bmcevt->SetAddress(&mcevtYes[0]);
+  brawevtheader->SetAddress(&evtheaderYes[0]);
+  brawrunheader->SetAddress(&runheaderYes[0]);
+
+  for(Int_t i=0;i<nentries2[0];i++)
+  //  for(Int_t i=0;i<100;i++)
+    {      
+      tyes[0]->GetEntry(i);
+      Int_t run = runheaderYes[0]->GetRunNumber();
+      Int_t evt = evtheaderYes[0]->GetDAQEvtNumber();
+      Int_t runno;
+      Int_t evtno;
+
+      cout << "Checking run " << run << ", event " << evt << endl;
+
+      //check if the event is present in the no-noise file
+      Int_t kk=latestk[0];	  
+      while(kk<nentries1)
+	{
+	  //	  cout << kk << endl;
+	  tno->GetEntry(kk++);
+	  runno = runheaderNo->GetRunNumber();
+	  evtno = evtheaderNo->GetDAQEvtNumber();
+	  if(run==runno && evt==evtno)
+	    break;
+	  if(run==runno && latestevt[0]<evt && evt<evtno)
+	    break;
+	  //	  if(runno>run)
+	  //	    break;
+	}
+
+      if(kk>=nentries1)
+	{
+	  kk=0;
+	  while(kk<latestk[0])
+	    {
+	      //		  cout << kk << endl;
+	      tno->GetEntry(kk++);
+	      runno = runheaderNo->GetRunNumber();
+	      evtno = evtheaderNo->GetDAQEvtNumber();
+	      if(run==runno && evt==evtno)
+		break;
+	      if(run==runno && latestevt[0]<evt && evt<evtno)
+		break;
+	      //	      if(runno>run)
+	      //		break;
+	    }
+	}
+
+      // the event is already included because it is also a no-noise event, dismiss it
+      if(run==runno && evt==evtno)
+	{
+	  cout << "Found already in the no-noise sample, continuing... " << endl;
+	  latestevt[0] = evtno;
+	  latestk[0]=kk;	  
+	  continue;
+	}
+
+      nfound2[0]++;
+      nphotNo->Reset();
+      hillasNo->Reset();
+      hillassrcNo->Reset();
+
+      // look for the event in the rest of the noisy samples
+      for(Int_t j=1;j<nlevels;j++)
+	{
+	  Int_t runyes;
+	  Int_t evtyes;
+	  cout << "Level " << levelname[j] << endl;
+	  Int_t k=latestk[j];	  
+	  while(k<nentries2[j])
+	    {
+	      //	      cout << k << endl;
+	      tyes[j]->GetEntry(k++);
+	      runyes = runheaderYes[j]->GetRunNumber();
+	      evtyes = evtheaderYes[j]->GetDAQEvtNumber();
+	      if(runyes==run && evtyes==evt)
+		break;
+	      if(runyes==run && latestevt[j]<evt && evt<evtyes)
+		break;
+	      //	      if(runyes>run)
+	      //		break;
+	    }
+
+	  if(k>=nentries2[j])
+	    {
+	      k=0;
+	      while(k<latestk[j])
+		{
+		  //		  cout << k << endl;
+		  tyes[j]->GetEntry(k++);
+		  runyes = runheaderYes[j]->GetRunNumber();
+		  evtyes = evtheaderYes[j]->GetDAQEvtNumber();
+		  if(runyes==run && evtyes==evt)
+		    break;
+		  if(runyes==run && latestevt[j]<evt && evt<evtyes)
+		    break;
+		  //		  if(runyes>run)
+		  //		    break;
+		}
+	    }
+	  
+	  // the event has not been found, assign dummy containers
+	  if(runyes=!run || evtyes!=evt)
+	    {
+	      cout << "Not Found!" << endl;	      
+	      for(Int_t l=j;l<nlevels;l++)
+		{
+		  nphotYes[l]->Reset();
+		  hillasYes[l]->Reset();
+		  hillassrcYes[l]->Reset();		  
+		}
+	      break;
+	    }
+	  else
+	    {
+	      cout << "Found!" << endl;
+	      latestevt[j] = evtyes;
+	      latestk[j]=k;	  
+	      nfound2[j]++;
+	    }
+	}
+      to->Fill();    
+    }
+
+  fout->Write();
+  fout->Close();
+
+  for(Int_t i=0;i<nlevels;i++)
+    cout << "Found " << nfound[i] << "+" << nfound2[i] << " for cleaning level " << levelname[i] << endl;
+
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/mmcCleaning.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/mmcCleaning.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/mmcCleaning.C	(revision 9772)
@@ -0,0 +1,197 @@
+/////////////////////////////////////////////////////////////////////////////
+//
+//  mmcCleaning - calibrate/clean mc events
+//
+/////////////////////////////////////////////////////////////////////////////
+
+
+void mmcCleaning(TString NoiseFilename, TString NoiseOutFilename)
+{
+  //
+  // This is a demonstration program which reads in MC camera files
+  // and produces and output with calibrated events (signal in photons
+  // for all pixels, in MCerPhotEvt containers).
+  //
+
+  // ------------- user change -----------------
+  Char_t*  NonoiseFilename = "/local_disk/jrico/mc/Gamma_zbin0_0_7_1000to1009_w0.root";
+  //  Char_t*  NoiseFilename   = "/mnt/wdflix/root_0.73mirror/wuerzburg/gammas/Gamma_zbin3_0_7_1160to1169_w0.root"; // File to be analyzed
+
+  //  Char_t* NoiseOutFilename   = "/mnt/users/jrico/prueba.root";   // Output file name
+
+  const Int_t wsize=2;
+  // Signal sigextract
+  // (other extraction methods can be used)
+  MExtractor* sigextract = new MExtractTimeAndChargeSpline();
+  ((MExtractTimeAndChargeSpline*)sigextract)->SetTimeType(MExtractTimeAndChargeSpline::kHalfMaximum);
+  ((MExtractTimeAndChargeSpline*)sigextract)->SetChargeType(MExtractTimeAndChargeSpline::kIntegral);      
+  ((MExtractTimeAndChargeSpline*)sigextract)->SetRiseTime((Float_t)wsize*0.25); 
+  ((MExtractTimeAndChargeSpline*)sigextract)->SetFallTime((Float_t)wsize*0.75);
+  
+  // Define FADC slices to be integrated in high and low gain:
+  sigextract->SetRange(1, 11, 2, 12);
+
+  // Defines when to switch to low gain
+  sigextract->SetSaturationLimit(240);
+
+  // ---------------------------------------------------------------------
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  MPedestalCam  pedcam;
+  MGeomCamMagic geomcam;
+  MCerPhotEvt   nphot;
+
+  plist.AddToList(&pedcam);
+  plist.AddToList(&geomcam);
+  plist.AddToList(&nphot);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+  read.AddFile(NonoiseFilename);
+  read.DisableAutoScheme();
+
+  MGeomApply geom; 
+  // Reads in geometry from MC file and sets the right sizes for
+  // several parameter containers.
+
+  MMcPedestalCopy   pcopy; 
+  // Copies pedestal data from the MC file run fadc header to the 
+  // MPedestalCam container.
+
+  MDisplay       display(&nphot,&geomcam);
+  MHillasDisplay display2(&nphot,&geomcam);
+
+  MPointingPosCalc pointcalc;
+  // Creates MPointingPos object and fill it with the telescope orientation
+  // information taken from MMcEvt.
+
+  MMcCalibrationUpdate  mccalibupdate;
+
+  MCalibrate calib; 
+  // MCalibrate transforms signals from ADC counts into photons. In the first
+  // loop it applies a "dummy" calibration supplied by MMcCalibrationUpdate, just 
+  // to equalize inner and outer pixels. At the end of the first loop, in the
+  // PostProcess of MMcCalibrationCalc (see below) the true calibration constants
+  // are calculated.
+
+  calib.SetCalibrationMode(MCalibrate::kFfactor);
+
+  MImgCleanStd clean(4.0,3.5);
+  clean.SetCleanRings(1);
+  //  clean.SetRemoveSingle(kFALSE);
+  //
+  // Applies tail cuts to image. Since the calibration is performed on 
+  // noiseless camera files, the precise values of the cleaning levels 
+  // are unimportant (in any case, only pixels without any C-photon will
+  // be rejected).
+  //
+
+  MHillasCalc hcalc; // Calculates Hillas parameters not dependent on source position.
+  MHillasSrcCalc hsrccalc;
+
+  MMcCalibrationCalc mccalibcalc; 
+  // Calculates calibration constants to convert from ADC counts to photons.
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geom);
+  tlist.AddToList(&pcopy);
+  tlist.AddToList(&pointcalc);
+  tlist.AddToList(sigextract);
+  tlist.AddToList(&mccalibupdate);
+  tlist.AddToList(&calib);
+  tlist.AddToList(&clean);
+  tlist.AddToList(&hcalc);
+  tlist.AddToList(&hsrccalc); 
+  tlist.AddToList(&mccalibcalc);
+  //tlist.AddToList(&display2);
+
+  //
+  // First loop: No noise
+  //
+  MProgressBar bar;
+  bar.SetWindowName("No noise...");
+
+  MEvtLoop evtloop;
+  //  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (!evtloop.Eventloop())
+    return;
+  mccalibcalc.GetHistADC2PhotEl()->Write();
+  mccalibcalc.GetHistPhot2PhotEl()->Write();
+  // Writes out the histograms used for calibration.
+
+
+  //
+  // Second loop: process file with noise
+  //  
+  MIslands      isl;
+  MArrivalTimeCam timecam;      
+  MTopology     topology;
+  plist.AddToList(&isl);
+  plist.AddToList(&timecam);
+  plist.AddToList(&topology);
+
+  MArrivalTimeCalc2 timecalc;
+  MIslandsCalc      islandcalc;
+  islandcalc.SetOutputName("MIslands");
+  islandcalc.SetAlgorithm(1);
+  MIslandsClean     islclean(40);
+  islclean.SetInputName("MIslands");
+  islclean.SetMethod(1);
+  MTopologyCalc     topcalc;
+
+  MReadMarsFile read2("Events");
+  read2.AddFile(NoiseFilename);
+  read2.DisableAutoScheme();
+  tlist.AddToListBefore(&read2, &read, "All");
+  tlist.RemoveFromList(&read);
+
+  tlist.AddToListBefore(&timecalc,&mccalibupdate,"All");
+  tlist.AddToListBefore(&islandcalc,&hcalc,"All");
+  tlist.AddToListBefore(&topcalc,&hcalc,"All");
+
+  MWriteRootFile write(NoiseOutFilename); // Writes output
+  write.AddContainer("MRawRunHeader", "RunHeaders");
+  write.AddContainer("MMcRunHeader",  "RunHeaders");
+  write.AddContainer("MSrcPosCam",    "RunHeaders");
+  write.AddContainer("MGeomCam",      "RunHeaders");
+  write.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+  write.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+  write.AddContainer("MMcFadcHeader",  "RunHeaders");
+  write.AddContainer("MMcTrigHeader",  "RunHeaders");
+
+  write.AddContainer("MMcEvt",        "Events");
+  write.AddContainer("MRawEvtHeader", "Events");
+  write.AddContainer("MHillas",       "Events");
+  write.AddContainer("MHillasSrc",    "Events");
+  write.AddContainer("MHillasExt",    "Events");
+  write.AddContainer("MConcentration","Events");
+  write.AddContainer("MImagePar",     "Events");
+  write.AddContainer("MNewImagePar",  "Events");
+  write.AddContainer("MIslands",      "Events");
+  write.AddContainer("MPointingPos",  "Events");
+  write.AddContainer("MTopology",      "Events");
+
+  tlist.RemoveFromList(&mccalibcalc);
+  tlist.AddToList(&write);
+  //  tlist.AddToListBefore(&display2,&write, "All");
+
+  bar.SetWindowName("Calibrating/Cleaning...");
+  //  clean.SetRemoveSingle();
+  //  clean.SetMethod(MImgCleanStd::kDemocratic);
+
+  if (!evtloop.Eventloop())
+    return;
+
+  tlist.PrintStatistics();
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/observationTime.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/observationTime.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/observationTime.C	(revision 9772)
@@ -0,0 +1,48 @@
+/* ======================================================================== *\!
+!   Author(s): Javier Rico
+\* ======================================================================== */
+
+void observationTime(
+		     Int_t iniRun=0,
+		     Int_t finRun=99999,
+		     TString filename="/mnt/users/jrico/magic/mars/mars/mtemp/mifae/hillas/AllCrabNebula_3015_kDefault_MispE.root"
+)
+{    
+    // define files, chains...
+    TChain* t= new TChain("Parameters");
+    t->Add(filename);
+
+    // define aliases
+    t->SetAlias("run",     "MRawRunHeader.fRunNumber");
+    t->SetAlias("runiniT", "MRawRunHeader.fRunStart.fTime.fMilliSec/1000");
+    t->SetAlias("runfinT", "MRawRunHeader.fRunStop.fTime.fMilliSec/1000");
+
+    TH1I* hrun = new TH1I("hrun","",finRun-iniRun+1,iniRun,finRun+1);
+    TH1I* hent = new TH1I("hent","",finRun-iniRun+1,iniRun,finRun+1);
+	
+    const char varcut[512];
+    const char runcut[512];
+    sprintf(runcut,"(run>=%d && run<=%d)",iniRun,finRun);
+    sprintf(varcut,"%s*(runfinT-runiniT)",runcut);
+
+    t->Draw("run>>hrun",runcut);
+    t->Draw("run>>hent",varcut);
+
+    Float_t seconds=0;
+    for(Int_t irun = 1; irun<=finRun-iniRun+1; irun++)
+      {
+	Int_t nev;
+	if(nev=hrun->GetBinContent(irun))
+	  {
+	    Float_t time = hent->GetBinContent(irun)/nev;
+	    seconds += time;	    
+	    cout << "run " << iniRun-1+irun << ", " << time <<  " seconds" << endl;
+	  }
+      }
+    
+    cout << "Total observation time = " << seconds << " seconds = " << seconds/60. << " minutes = " << seconds/3600. << " hours" << endl;
+    delete hrun;
+    delete hent;
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/pedrmsonoff.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/pedrmsonoff.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/pedrmsonoff.C	(revision 9772)
@@ -0,0 +1,284 @@
+// pedrmsonoff.C
+// compare pedestal rms for two different sets
+//
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MPedestalCam.h"
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MPedCalcPedRun.h"
+#include "MEvtLoop.h"
+#include "MPedestalPix.h"
+#include "MHCamera.h"
+
+#include "TTimer.h"
+#include "TString.h"
+#include "TCanvas.h"
+#include "TFile.h"
+#include "TGraphErrors.h"
+#include "TMultiGraph.h"
+#include "TLegend.h"
+#include "TPaveStats.h"
+#include "TH1F.h"
+#include "TStyle.h"
+#include "TROOT.h"
+
+#include <iostream>
+
+using namespace std;	     
+
+void compare(TCanvas* canvas,TString onfname, TString offfname,TString descon, TString descoff, UInt_t index=-1);
+
+void pedrmsonoff()
+//int main()
+{
+  // general settings
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetStatColor(0);
+  gStyle->SetStatBorderSize(1);
+  gStyle->SetOptStat(111111);
+  gStyle->SetStatW(0.2);
+  gStyle->SetStatH(0.1);
+  gStyle->SetStatX(0.9);
+  gStyle->SetStatY(0.9);
+
+  // create canvas
+  TCanvas* canvas = new TCanvas("canvas","On/Off crab pedestal rms", 0, 100, 800, 500);
+  canvas->SetBorderMode(0);    // Delete the Canvas' border line     
+  canvas->cd();
+
+#ifdef TEMPLATE
+  // define input files/parameters
+  const UInt_t ncomp = 9;
+
+  //  const TString onfile ="/mnt/disc02/Data/rootdata/CrabNebula/2004_01_26/20040125_10412_P_Crab-On_E.root";
+  TString onfile[ncomp] = {
+    "/local_disk/jrico/rootdata/20040126_12149_P_Cab-On_E.root",
+    "/local_disk/jrico/rootdata/20040125_10412_P_Crab-On_E.root", 
+    "/local_disk/jrico/rootdata/20040125_10412_P_Crab-On_E.root",
+    "/local_disk/jrico/rootdata/20040119_04642_P_Crab-On_E.root",
+    "/local_disk/jrico/rootdata/20040128_1342*_P_ClosedLidsHVoff_E.root",
+    "/local_disk/jrico/rootdata/20040128_1342*_P_ClosedLidsLVoff_E.root",
+    "/local_disk/jrico/rootdata/20040128_1343*_P_ReciversOff_E.root",
+    "/local_disk/jrico/rootdata/20040126_12386_P_Cab-On_E.root",
+    "/local_disk/jrico/rootdata/20040126_12543_P_OffCrab-1_E.root"};
+
+  
+  TString ondesc[ncomp] = {"Run 12149 Jan 27th, Crab On, #theta 28 deg",
+			   "Run 10412 Jan 26th, Crab On, #theta 12.5 deg",
+			   "Run 10412 Jan 26th, Crab On, #theta 12.5 deg",			      
+			   "Run 4642 Jan 20th, Crab On, #theta 14.1 deg",
+			   "Runs 13426-7 Jan 29th, Closed lids HV off",
+			   "Runs 13428-9 Jan 29th, Closed lids LV off",
+			   "Runs 13430-1 Jan 29th, Recivers Off",
+			   "Run 12386 Jan 27th, Crab On #theta 37.1 deg",
+			   "Run 12543 Jan 27th, Crab Off #theta 8.6 deg"};
+
+  
+  TString offfile[ncomp] = {
+    "/local_disk/jrico/rootdata/20040121_06773_P_OffCrab1_E.root",
+    "/local_disk/jrico/rootdata/20040125_11477_P_OffCrab1_E.root",
+    "/local_disk/jrico/rootdata/20040125_10415_P_Crab-On_E.root",
+    "/local_disk/jrico/rootdata/20040125_10415_P_Crab-On_E.root",
+    "/local_disk/jrico/rootdata/20040128_13425_P_ClosedLidsHVon_E.root",
+    "/local_disk/jrico/rootdata/20040128_13425_P_ClosedLidsHVon_E.root",
+    "/local_disk/jrico/rootdata/20040128_13425_P_ClosedLidsHVon_E.root",
+    "/local_disk/jrico/rootdata/20040128_13425_P_ClosedLidsHVon_E.root",
+    "/local_disk/jrico/rootdata/20040128_13425_P_ClosedLidsHVon_E.root"};
+
+  
+  TString offdesc[ncomp] = {"Run 6773 Jan 22nd, Crab Off #theta 28 deg",
+			    "Run 11477 Jan 26th, Crab Off #theta 9.2 deg",
+			    "Run 10415 Jan 26th, Crab On, #theta 13.8 deg",
+			    "Run 10415 Jan 26th, Crab On, #theta 13.8 deg",
+			    "Run 13425 Jan 29th, Closed lids HV on",
+			    "Run 13425 Jan 29th, Closed lids HV on",
+			    "Run 13425 Jan 29th, Closed lids HV on",
+			    "Run 13425 Jan 29th, Closed lids HV on",
+			    "Run 13425 Jan 29th, Closed lids HV on"};
+#endif
+
+  // define input files/parameters
+  const UInt_t ncomp = 1;
+
+  TString onfile[ncomp] = {"/local_disk/jrico/rootdata/pedestals/20040619_*_P_OffPSR1957-1_E.root"};  
+  TString ondesc[ncomp] = {"Off-PSR1957"};  
+  TString offfile[ncomp] = {"/local_disk/jrico/mc/empty_disc00.root"};  
+  TString offdesc[ncomp] = {"MC (Vela)"};
+
+  canvas->Print("pedrmsonoff.ps[");  
+  for(UInt_t i=0;i<ncomp;i++)    
+    compare(canvas,onfile[i],offfile[i],ondesc[i],offdesc[i],i);
+  canvas->Print("pedrmsonoff.ps]");  
+}
+
+
+void compare(TCanvas* canvas,TString onfname, TString offfname,TString descon, TString descoff,UInt_t index)
+{
+  /*************************/
+  /* FIRST LOOP: ON DATA   */
+  /*************************/
+
+  // basic lists
+  MParList plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+  
+  // containers
+  MPedestalCam   onpedcam;
+  plist.AddToList(&onpedcam);
+    
+  //tasks
+  MReadMarsFile read("Events", onfname);
+  MGeomApply     geomapl;
+  MPedCalcPedRun pedcalc;
+
+  read.DisableAutoScheme();
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&pedcalc);
+
+  // Create and execute the event looper
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+  cout << "*********************" << endl;
+  cout << "** RUNNING ON DATA **" << endl;
+  cout << "*********************" << endl;
+
+  if (!evtloop.Eventloop())
+    return;
+  
+  tlist.PrintStatistics();
+
+  /**************************/
+  /* SECOND LOOP: OFF DATA  */
+  /**************************/
+  MReadMarsFile read2("Events",offfname);
+  read2.DisableAutoScheme();
+  tlist.AddToListBefore(&read2, &read, "All");
+  tlist.RemoveFromList(&read);
+  
+  // containers
+  MPedestalCam   offpedcam;
+  plist.Remove(&onpedcam);
+  plist.AddToList(&offpedcam);
+  
+  // Execute the event looper
+  cout << "**********************" << endl;
+  cout << "** RUNNING OFF DATA **" << endl;
+  cout << "**********************" << endl;
+
+  if (!evtloop.Eventloop())
+    return;
+  
+  tlist.PrintStatistics();
+
+  /*******************/
+  /* FILL HISTOGRAMS */
+  /*******************/
+  const UInt_t npix = 577;
+  const UInt_t ninner = 397;
+  const UInt_t imin =  0;
+  const UInt_t imax = 20;
+  const UInt_t itot = 50;
+  
+  TH1F* honinpedrms  = new TH1F(descon+TString(" Inner"),"Pedestal RMS" ,itot,imin,imax);
+  TH1F* hoffinpedrms = new TH1F(descoff+TString(" Inner"),"Pedestal RMS",itot,imin,imax);
+  TH1F* honoutpedrms  = new TH1F(descon+TString(" Outer"),"Pedestal RMS" ,itot,imin,imax);
+  TH1F* hoffoutpedrms = new TH1F(descoff+TString(" Outer"),"Pedestal RMS",itot,imin,imax);
+
+  for(UInt_t i=0;i<npix;i++)
+    {
+      const Float_t onpedrms  =  onpedcam[i].GetPedestalRms();
+      const Float_t offpedrms = offpedcam[i].GetPedestalRms();
+      
+      if(i<ninner)
+	{
+	  honinpedrms->Fill(onpedrms);
+	  hoffinpedrms->Fill(offpedrms);
+	}
+      else
+	{
+	  honoutpedrms->Fill(onpedrms);
+	  hoffoutpedrms->Fill(offpedrms);
+	}
+    }
+
+  /*******************/
+  /* DRAW HISTOGRAMS */
+  /*******************/
+     
+  // draw pedestal histos
+  honinpedrms->GetXaxis()->SetTitle("Pedestal RMS (ADC cnts)");
+  honinpedrms->GetYaxis()->SetTitle("# pixels");
+  honinpedrms->SetFillStyle(3004);
+  honinpedrms->SetFillColor(1);
+
+  hoffinpedrms->GetXaxis()->SetTitle("Pedestal RMS (ADC cnts)");
+  hoffinpedrms->GetYaxis()->SetTitle("# pixels");
+  hoffinpedrms->SetFillStyle(3005);
+  hoffinpedrms->SetFillColor(2);
+  hoffinpedrms->SetLineColor(2);
+
+  honoutpedrms->GetXaxis()->SetTitle("Pedestal RMS (ADC cnts)");
+  honoutpedrms->GetYaxis()->SetTitle("# pixels");
+  honoutpedrms->SetFillStyle(3017);
+  honoutpedrms->SetFillColor(1);
+
+  hoffoutpedrms->GetXaxis()->SetTitle("Pedestal RMS (ADC cnts)");
+  hoffoutpedrms->GetYaxis()->SetTitle("# pixels");
+  hoffoutpedrms->SetFillStyle(3018);
+  hoffoutpedrms->SetFillColor(2);
+  hoffoutpedrms->SetLineColor(2);
+
+  hoffinpedrms->Draw();
+  hoffoutpedrms->Draw("sames");
+  honinpedrms->Draw("sames");
+  honoutpedrms->Draw("sames");
+
+  // move stat boxes to make them all visible
+  gPad->Update();
+  TPaveStats* onoutpavstat  = (TPaveStats*) honoutpedrms->GetListOfFunctions()->FindObject("stats");
+  TPaveStats* offinpavstat  = (TPaveStats*) hoffinpedrms->GetListOfFunctions()->FindObject("stats");
+  TPaveStats* offoutpavstat = (TPaveStats*) hoffoutpedrms->GetListOfFunctions()->FindObject("stats");
+  Float_t shifty = offinpavstat->GetY2NDC()-offinpavstat->GetY1NDC();
+  Float_t shiftx = onoutpavstat->GetX2NDC()-onoutpavstat->GetX1NDC();
+
+  onoutpavstat->SetX1NDC(onoutpavstat->GetX1NDC()-shiftx);
+  onoutpavstat->SetX2NDC(onoutpavstat->GetX2NDC()-shiftx);
+
+  offinpavstat->SetY1NDC(offinpavstat->GetY1NDC()-shifty);
+  offinpavstat->SetY2NDC(offinpavstat->GetY2NDC()-shifty);
+
+  offoutpavstat->SetX1NDC(offoutpavstat->GetX1NDC()-shiftx);
+  offoutpavstat->SetX2NDC(offoutpavstat->GetX2NDC()-shiftx);
+  offoutpavstat->SetY1NDC(offoutpavstat->GetY1NDC()-shifty);
+  offoutpavstat->SetY2NDC(offoutpavstat->GetY2NDC()-shifty);
+
+  // include legend
+  TLegend* leg1 = new TLegend(.52,.25,.88,.45);
+  leg1->SetHeader("");
+  leg1->AddEntry(honinpedrms,descon+TString(" (Inner)"),"f");
+  leg1->AddEntry(hoffinpedrms,descoff+TString(" (Inner)"),"f");
+  leg1->AddEntry(honoutpedrms,descon+TString(" (Outer)"),"f");
+  leg1->AddEntry(hoffoutpedrms,descoff+TString(" (Outer)"),"f");
+  leg1->SetFillColor(0);
+  leg1->SetLineColor(0);
+  leg1->SetBorderSize(0);
+  leg1->Draw();
+
+  if(index>=0)
+    {
+      char fname[100];
+      sprintf(fname,"pedrmsonoff%02d.eps",index);
+      canvas->Print(fname);        
+    }
+  canvas->Print("pedrmsonoff.ps");  
+
+  return; 
+  
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/plotOptimal.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/plotOptimal.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/plotOptimal.C	(revision 9772)
@@ -0,0 +1,124 @@
+////////////////////////////////////////////////////////////////////////////////////
+//
+//             _____ Plot Optimized cuts _____
+//
+//  Take as input an output from programs/optimizeCuts and plot the results
+//  You only need to specify the input file name
+//
+//                 Jose Flix    <jflix@ifae.es>
+//                 Javier Rico  <jrico@ifae.es>
+////////////////////////////////////////////////////////////////////////////////////
+
+
+void plotOptimal(TString fname="optimize.out")
+{
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+  gStyle->SetOptStat(000000);
+  gStyle->SetPalette(1);
+
+  ifstream ifun(fname.Data());
+  Float_t width,length,excess,significance;
+
+  Float_t wmin=9999999;
+  Float_t lmin=9999999;
+  Float_t wmax=-9999999;
+  Float_t lmax=-9999999;
+  Float_t emax=-9999999;
+  Float_t smax=-9999999;
+
+  Float_t dw=-1;
+  Float_t dl=-1;
+  Float_t prevw=-1;
+  Float_t prevl=-1;
+
+  // first loop to get parameters
+  Int_t i=0;
+  while(ifun >> width)
+    {
+      // read data
+      ifun >> length;
+      ifun >> excess;
+      ifun >> significance;
+      
+      // keep max/min
+      if(width<wmin)  wmin=width;
+      if(length<lmin) lmin=length;
+      if(width>wmax)  wmax=width;
+      if(length>lmax) lmax=length;
+      if(significance>smax) 
+	{
+	  smax=significance;
+	  emax=excess;
+	}
+
+      if(width!=prevw)   dw=width-prevw;
+      if(length!=prevl) dl=length-prevl;
+
+      prevw=width;
+      prevl=length;
+      i++;
+    }
+  ifun.close();
+
+  cout << "wmin: " << wmin << ", wmax: " << wmax+dw << ", lmin: " << lmin << ", lmax: " << lmax+dl << endl;
+
+  // define histos
+  Int_t nx = TMath::Nint((wmax-wmin)/dw)+1;
+  Int_t ny = TMath::Nint((lmax-lmin)/dl)+1;
+  TH2F *ex  = new TH2F("Excess","Excess",nx,wmin,wmax+dw,ny,lmin,lmax+dl);
+  TH2F *sig = new TH2F("Significance","Significance",nx,wmin,wmax+dw,ny,lmin,lmax+dl);
+
+  cout << "nx: " << nx << ", ny: " << ny << endl;
+  cout << "dw: " << dw << ", dl: " << dl << endl;
+
+  ifstream ifun2;
+  ifun2.open(fname.Data());
+  
+  // second loop to fill the histograms
+  Float_t wopt,lopt,eopt;
+  while(ifun2 >> width)
+    {
+      // read data
+      ifun2 >> length;
+      ifun2 >> excess;
+      ifun2 >> significance;
+
+      cout << "Width: " << width << '\t' << "Length: " << length << '\t' << "Excess: " << excess << '\t' << "Significance: " << significance;
+      if(significance==smax)
+	{
+	  cout << " *****";
+	  wopt=width;
+	  lopt=length;
+	  eopt=excess;
+	}
+	    
+      cout << endl;
+
+      Int_t binx = TMath::Nint(((width-wmin)/dw));
+      Int_t biny = TMath::Nint(((length-lmin)/dl));
+
+      //      cout << "binnx: " << binx+1 << ", biny: " << biny+1 << endl;
+
+      ex->SetBinContent(binx+1,biny+1,excess+.00001);
+      sig->SetBinContent(binx+1,biny+1,significance+.00001);    
+    }
+  cout << "Maximal significance: " << smax << " (excess=" << eopt << ") for width="<<wopt<<", length=" << lopt << endl;
+
+  // plot
+  TCanvas *c3 = new TCanvas("c3","c3",0,0,500,750);
+  c3->Divide(1,2);
+  
+  c3->cd(1);
+  ex->GetXaxis()->SetTitle("Width (degrees)");
+  ex->GetYaxis()->SetTitle("Length (degrees)");
+  ex->Draw("colz");
+  
+  c3->cd(2);
+  sig->GetXaxis()->SetTitle("Width (degrees)");
+  sig->GetYaxis()->SetTitle("Length (degrees)");
+  sig->Draw("colz");
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/psffit.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/psffit.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/psffit.C	(revision 9772)
@@ -0,0 +1,149 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 04/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+
+void psffit(const TString filename="dc_2004_03_19_00_36_50_20781_Mrk421.root", const TString directory="/nfs/magic/CaCodata/rootdata/Mrk421/Period015/2004_03_19/", const UInt_t numEvents = 0)
+{
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MPSFFit       psffit;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&psffit);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+
+  MGeomApply geomapl;
+
+  const Int_t numrings = 3;
+  const Int_t numblind = 23;
+  const Short_t x[numblind] = {  8,  27, 224, 279, 339,
+			       507, 508, 509, 510, 511, 512, 513, 514,
+			       543,
+			       559, 560, 561, 562, 563, 564, 565, 566, 567};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  MPSFFitCalc psfcalc;
+  //psfcalc.SetImgCleanMode(MPSFFitCalc::kRing);
+  psfcalc.SetImgCleanMode(MPSFFitCalc::kCombined);
+  psfcalc.SetNumRings(numrings);
+  psfcalc.SetBlindPixels(blindpixels);
+
+
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&psfcalc, "Currents");
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  //
+  // Execute your analysis
+  //
+
+  if (numEvents > 0)
+  {
+      if (!evtloop.Eventloop(numEvents))
+	  return;
+  }
+  else
+  {
+      if (!evtloop.PreProcess())
+	  return;
+      
+      MHCamera display(geomcam);
+      display.SetPrettyPalette();
+      display.Draw();
+      gPad->cd(1);
+      psffit.Draw();
+      
+      while (tlist.Process())
+      {
+	  display.SetCamContent(dccam);
+	  gPad->Modified();
+	  gPad->Update();
+          psffit.Print();
+	  // Remove the comments if you want to go through the file
+	  // event-by-event:
+	  if (!HandleInput())
+	      break;
+      } 
+
+      evtloop.PostProcess();
+  }
+
+  tlist.PrintStatistics();
+
+  psffit.Print();
+  cout << "RUN " << psffit.GetMeanMinorAxis() << ' ' << psffit.GetSigmaMinorAxis() << ' ' <<  psffit.GetMeanMajorAxis()  << ' ' <<  psffit.GetSigmaMajorAxis() << ' ' << psffit.GetChisquare() << endl;
+  
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/psffromstars.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/psffromstars.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/psffromstars.C	(revision 9772)
@@ -0,0 +1,157 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 05/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
+Double_t fitfunc(Double_t *x, Double_t *par);
+
+
+void psffromstars(const TString filename="dc_*.root", const TString directory="/nfs/magic/CaCodata/online_data/Period015/cacadata/2004_03_21/", const UInt_t numEvents = 100000000)
+{
+
+  gStyle->SetOptFit(1);
+  
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MStarLocalCam starcam;
+  MHPSFFromStars mhpsf;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&starcam);
+  plist.AddToList(&mhpsf);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddFile(directory+filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+
+  MGeomApply geomapl;
+  TString continuoslightfile = 
+    //    "/home/Javi/mnt_magic_data/CaCo/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+    "/nfs/magic/CaCodata/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+
+  Float_t mindc = 0.7; //[uA]
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 1;
+  const Short_t x[numblind] = { 124};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 3.5;
+  UInt_t integratedevents = 10;
+
+  MFindStars findstars;
+  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+
+  MFillH fpsf("MHPSFFromStars","MStarLocalCam");
+  
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal);
+  tlist.AddToList(&findstars, "Currents");
+  tlist.AddToList(&fpsf, "Currents");
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+//   MProgressBar bar;
+//   evtloop.SetProgressBar(&bar);
+  
+  //
+  // Execute your analysis
+  //
+  
+  if (!evtloop.Eventloop(numEvents))
+    return;
+
+  tlist.PrintStatistics();
+
+  //Draw results
+
+  MStatusDisplay *d = new MStatusDisplay;
+  d->SetTitle(Form("- %s -",filename));
+  d->SetLogStream(&gLog, kTRUE);            // Disables output to stdout
+
+  // Create a default canvas
+  TCanvas &c1 = d.AddTab("Star spot Position");
+  mhpsf.Draw("mean");
+  TCanvas &c2 = d.AddTab("Star's Path");
+  mhpsf.Draw("camera");
+  TCanvas &c3 = d.AddTab("Star spot Size");
+  mhpsf.Draw("sigma");
+  TCanvas &c4 = d.AddTab("Star XY Projection");
+  mhpsf.Draw("projection");
+  
+  d->Print("./psf.ps");
+  
+  //  if (!HandleInput()) {}
+
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/rotation.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/rotation.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/rotation.C	(revision 9772)
@@ -0,0 +1,101 @@
+
+// Macro to compare the rotation obtained from simple FOV rotation, with 
+// measured values
+
+void rotation()
+{
+  const Int_t rmax=17427;
+  gStyle->SetMarkerStyle(20);
+  gStyle->SetMarkerSize(1);
+
+  const char* fname="/mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/macros/20040215_Mrk421.B.pos";
+  TFile* file= new TFile("/mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/hillas/mrk20040215OnRotateNoCalB.root");
+  TTree* chain = (TTree*)file->Get("Parameters");
+
+  // read position data from file
+  ifstream ifun(fname);
+
+  Int_t irun;
+  Float_t ix;
+  Float_t iy;
+
+  // first loop to evaluate number of entries
+  Int_t nentries=0;  
+  while(ifun >> irun)
+    {
+      ifun >> ix;
+      ifun >> iy;
+      nentries++;
+    }
+  ifun.close();
+  const Int_t size = nentries;
+  Float_t x[size];
+  Float_t y[size];
+  Int_t run[size];
+
+  // second loop to actually read values into arrays
+  Int_t i=0;
+  ifstream ifun2(fname);
+  while(ifun2 >> run[i])
+    {
+      ifun2 >> x[i];
+      ifun2 >> y[i];
+      x[i]/=315.;
+      y[i]/=315.;
+      i++;
+    }  
+  ifun2.close();
+  TGraph* tray = new TGraph(nentries,x,y);
+
+  // get data from tree
+  MSrcPosCam* srpos = new MSrcPosCam; 
+  MRawRunHeader* hrun = new MRawRunHeader;
+  chain->SetBranchAddress("MSrcPosCam.",&srpos);
+  chain->SetBranchAddress("MRawRunHeader.",&hrun);
+
+  Int_t ntot = chain->GetEntries();
+  const Int_t ctot =ntot;
+  Float_t xth[ctot];
+  Float_t yth[ctot];
+  Int_t rtot=0;
+  for(Int_t j=0;j<ctot;j++)
+    {
+      chain->GetEntry(j);
+      Int_t arun=hrun->GetRunNumber();
+      if(arun<=rmax)
+	{
+	  xth[j]=srpos->GetX()/315.;
+	  yth[j]=srpos->GetY()/315.;
+	  rtot++;
+	}
+    }     
+  TGraph* trayth = new TGraph(rtot,xth,yth);
+  
+
+  // Plot   
+  TPostScript myps("rotation.ps",111);
+  myps.Range(15,15);
+  TCanvas* myC = new TCanvas("myC","pedestal studies",500,500);
+  myC->cd(1);
+
+  // Null graph to adjust plot limits
+  Float_t nullx[2]={-0.4,0.4};
+  Float_t nully[2]={-0.4,0.4};
+
+  TGraph grnull(2,nullx,nully);
+  grnull.SetMarkerSize(0);
+  grnull.SetMarkerColor(0);
+  grnull.GetXaxis()->SetTitle("x (deg)");
+  grnull.GetYaxis()->SetTitle("y (deg)");
+  grnull.SetTitle("Source position in camera Mrk421 15th February");
+  grnull.DrawClone("AP");
+
+  tray->SetMarkerStyle(2);
+  tray->SetMarkerSize(2);
+  trayth->SetMarkerStyle(6);
+  trayth->SetMarkerColor(2);
+
+  tray->DrawClone("P");
+  trayth->DrawClone("P");
+  myps.Close();
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/runlivetime.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/runlivetime.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/runlivetime.C	(revision 9772)
@@ -0,0 +1,96 @@
+void runlivetime(TString filename)
+{
+
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+
+  //
+  // Make a loop only for the ON data:
+  //
+  
+  MParList plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  //Containers
+  
+  MLiveTime livetime;
+
+  plist.AddToList(&livetime);
+  
+  //
+  //tasks
+  //
+  
+  MReadTree read("Parameters");
+  read.DisableAutoScheme();
+
+  TString tmpfile = "./runlivetime.ls.tmp";
+  TString cmd = "ls " + filename + " > " + tmpfile;
+  gSystem->Exec(cmd);
+  TString tmpline;
+  ifstream in(tmpfile);
+  while(1)
+  {
+      in >> tmpline;
+      if(in.eof())
+	  break;
+      read.AddFile(tmpline);
+  }
+  TString cmd = "rm " + tmpfile;
+  gSystem->Exec(cmd);
+
+  Double_t timebin = 500.; //[sec]
+  MLiveTimeCalc livetimecalc;
+  livetimecalc.SetRealTimeBinSize(timebin);
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&livetimecalc);
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop loop;
+  loop.SetParList(&plist);
+     
+
+  if (!loop.Eventloop())
+      return;
+
+//   if (!loop.PreProcess())
+//     return;
+
+//   while(loop.Process())
+//     {}
+  
+//   loop.PostProcess();
+
+  tlist.PrintStatistics();
+
+  UInt_t numbertimebins = livetime.GetNumberTimeBins();
+  TArrayD y(numbertimebins);
+  TArrayD erry(numbertimebins);
+
+  for (UInt_t bin=0; bin<numbertimebins; bin++)
+    {
+      y[bin] = bin+1.;
+      erry[bin] = 0.;
+    }
+
+  TCanvas *c0 = new TCanvas;
+  c0->cd(1);
+  TGraphErrors *graph = new TGraphErrors(numbertimebins,livetime.GetMeanRealTimeArray(),y.GetArray(),livetime.GetWidthRealTimeArray(),erry.GetArray());
+  graph->SetTitle("");
+  graph->SetMinimum(0.);
+  graph->SetMarkerStyle(21);
+  graph->SetMarkerSize(0.03);
+  graph->Draw("AP");
+  graph->GetXaxis()->SetLabelSize(0.03);
+  graph->GetXaxis()->SetTitle("Time [MJD]");
+  //  lightcurvegraph->GetXaxis()->SetTimeDisplay(1);
+
+  
+}
Index: /tags/Mars-V0.9/mtemp/mifae/macros/signal.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/signal.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/signal.C	(revision 9772)
@@ -0,0 +1,180 @@
+/////////////////////////////////////////////////////////////////////////////
+//
+//       This macro makes the two-dimension plot of the False Source Method:
+//        root > .x signal.C(TString name, TString psname)
+//
+//                 Ester Aliu   <aliu@ifae.es>
+//                 Oscar Blanch <blanch@ifae.es>
+//                 Javier Rico  <jrico@ifae.es>
+////////////////////////////////////////////////////////////////////////////
+void signal(
+TString fname ="hillasCrab/falseSourceCrab20040215.root",
+TString psname ="kk.ps")
+{
+  Float_t excess;
+  Float_t significance;
+  Float_t array[2];
+  
+  Int_t nbin2d = 5;
+  Int_t ntotal = 2*nbin2d+1;
+  
+  Int_t nx = 0;
+  Int_t ny = 0;
+  
+  Float_t max = -10000;
+  Int_t imax;
+  Int_t jmax;
+  Float_t A ;
+  Float_t B;
+  
+  TH2F *hsignif = new TH2F("hsignif","Significance", ntotal, -1.0, 1.0, ntotal, -1.0, 1.0);
+  TH2F *hexcess = new TH2F("hexcess","Excess", ntotal, -1.0, 1.0, ntotal, -1.0, 1.0);
+  
+  
+  // loop on the histos and compute excess and significance
+  for( Int_t i = -nbin2d; i <= nbin2d ; i++)  
+    {    
+      nx++;
+      ny = 0;
+      for( Int_t j = -nbin2d; j <= nbin2d ; j++)  
+	{	
+	  ny++;	  
+	  step_signal(i,j,&array[0], fname);
+	  
+	  excess = array[0];
+	  significance = array[1];
+
+	  hexcess->SetBinContent(nx, ny, excess);
+	  hsignif->SetBinContent(nx, ny, significance);
+
+	  if ( significance > max)
+	    {
+	      max = significance;
+	      imax = i;
+	      jmax = j;
+	      A = excess;
+	      B = significance;
+	    }
+	}
+    }
+  
+  cout << "The position of maximum significance is ( " << imax << " , " << jmax << " )" << endl;
+  cout << "Excess: " << A << endl;
+  cout << "Significance: " << B << endl;
+    
+  // Plot 
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+  gStyle->SetOptTitle(0);
+  gStyle->SetTitleOffset(1.7,"y");
+  gStyle->SetPadLeftMargin(0.15);
+  gStyle->SetOptStat(kFALSE);
+  gStyle->SetStatColor(0);
+  gStyle->SetStatBorderSize(1);
+  gStyle->SetStatW(0.2);
+  gStyle->SetStatH(0.1);
+  gStyle->SetStatX(0.9);
+  gStyle->SetStatY(0.9);
+  
+
+  TPostScript myps(psname,111);
+  myps.Range(15,15);
+  TCanvas *c2d = new TCanvas("c2d", "Matrices", 0, 0, 800,800);  
+  c2d->Divide(2,2);
+  gStyle->SetPalette(1); 
+  
+  c2d->cd(1);
+  hexcess->Draw("colz");
+  hexcess->SetXTitle("X position (deg)");
+  hexcess->SetYTitle("Y position (deg)");
+  gPad->Update();    
+  
+  c2d->cd(2);
+  hsignif->Draw("colz");
+  hsignif->SetXTitle("X position (deg)");
+  hsignif->SetYTitle("Y position (deg)");
+  gPad->Update();
+
+  c2d->cd(3);
+  hexcess->Draw("lego2");
+  hexcess->SetXTitle("X position (deg)");
+  hexcess->SetYTitle("Y position (deg)");
+  gPad->Update();    
+  
+  c2d->cd(4);
+  hsignif->Draw("lego2");
+  hsignif->SetXTitle("X position (deg)");
+  hsignif->SetYTitle("Y position (deg)");
+  gPad->Update();    
+
+  myps.Close();
+}
+  
+  
+void step_signal(Int_t i, Int_t j, Float_t *array, TString fname) 
+{
+  cout << "Bin (" << i << "," << j << ")" << endl;
+  TH1F *onhisto;
+  TH1F *offhisto;
+
+  // open file and access to the histograms  
+  TFile *f = new TFile(fname);
+  Char_t name[20]; 
+  Char_t title[50]; 
+
+  // histo name
+  sprintf(name,"hOnAlpha[%d][%d]", i, j);
+  sprintf(title,"Alpha-Plot(On data) (%d ,%d)", i, j);
+  onhisto = (TH1F*)gDirectory->Get(name);   
+  
+  sprintf(name,"hOffAlpha[%d][%d]", i, j);
+  sprintf(title,"Alpha-Plot(Off data) (%d ,%d)", i, j);
+  offhisto = (TH1F*)gDirectory->Get(name);   
+  
+  // line/normalization
+  const Int_t nbins = 18;
+  const Int_t inibin = 20./90.*nbins+1;
+  Float_t level=0;
+  Float_t leveloff=0;
+  Float_t levelofferror=0;
+  for(Int_t ibin = inibin; ibin<=nbins;ibin++)
+    {
+      level+=onhisto->GetBinContent(ibin);
+      leveloff+=offhisto->GetBinContent(ibin);
+    }
+  level/=(nbins-inibin+1);
+  leveloff/=(nbins-inibin+1);
+  
+  // normalize on/off
+  offhisto->Sumw2(); // needed to compute correct errors after normalization
+  const Float_t norm = level/leveloff;
+  cout << "Normalizing by factor " << norm <<endl;
+  offhisto->Scale(norm);    
+  
+  // significance:
+  Float_t sig=0,bg=0,esig=0,ebg=0;
+  Float_t significance=0;
+  const Int_t signbins = inibin-1;
+  for(Int_t ibin = 1; ibin<=signbins;ibin++)
+    {
+      sig  += onhisto->GetBinContent(ibin);
+      esig += onhisto->GetBinError(ibin)*onhisto->GetBinError(ibin);
+      bg   += offhisto->GetBinContent(ibin);
+      ebg  += offhisto->GetBinError(ibin)*offhisto->GetBinError(ibin);
+    }
+  Float_t error= TMath::Sqrt(esig+ebg);
+  Float_t excess = sig-bg;
+  Float_t significance = excess/error;
+  
+  cout << "Excess:       " << excess << endl;
+  cout << "Significance: " << significance << endl;
+  
+  array[0] = excess;
+  array[1] = significance;
+}
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/macros/signalPoint.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/macros/signalPoint.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/macros/signalPoint.C	(revision 9772)
@@ -0,0 +1,131 @@
+/////////////////////////////////////////////////////////////////////////////
+//
+//       This macro makes the alpha-plot for one of the positions of the 
+//     False Source Method:
+//
+//                 Ester Aliu   <aliu@ifae.es>
+//                 Oscar Blanch <blanch@ifae.es>
+//                 Javier Rico  <jrico@ifae.es>
+////////////////////////////////////////////////////////////////////////////
+
+void signalPoint(Int_t i=0, Int_t j=0, TString fname="hillasCrab/falseSourceCrab20040215.root")
+{  
+  // constants
+  const Int_t nbins = 18;
+  
+  // general settings
+  gROOT->Reset();
+  gStyle->SetCanvasColor(0);
+  gStyle->SetCanvasBorderMode(0);
+  gStyle->SetPadBorderMode(0);
+  gStyle->SetFrameBorderMode(0);
+  gStyle->SetOptTitle(0);
+  gStyle->SetTitleOffset(1.7,"y");
+  gStyle->SetPadLeftMargin(0.15);
+  gStyle->SetOptStat(111110);
+  gStyle->SetStatColor(0);
+  gStyle->SetStatBorderSize(1);
+  gStyle->SetStatW(0.2);
+  gStyle->SetStatH(0.1);
+  gStyle->SetStatX(0.9);
+  gStyle->SetStatY(0.9);
+  
+  
+  //  open file and access to the histograms
+  TFile *f = new TFile(fname);
+  
+  Char_t name[20]; 
+  Char_t title[50]; 
+  
+  sprintf(name,"hOnAlpha[%d][%d]", i, j);
+  sprintf(title,"Alpha-Plot(On data) (%d ,%d)", i, j);
+  TH1F* onhisto = (TH1F*)gDirectory->Get(name);   
+  
+  sprintf(name,"hOffAlpha[%d][%d]", i, j);
+  sprintf(title,"Alpha-Plot(Off data) (%d ,%d)", i, j);
+  TH1F* offhisto = (TH1F*)gDirectory->Get(name);   
+
+  TPostScript myps("signalpoint.ps",111);
+  myps.Range(15,15);
+  TCanvas *c1 = new TCanvas("c1","c1",800,600);
+  c1->cd(1);
+
+  // line/normalization
+  const Int_t inibin = 20./90.*nbins+1;
+  Float_t level=0;
+  Float_t leveloff=0;
+  Float_t levelofferror=0;
+  for(Int_t ibin = inibin; ibin<=nbins;ibin++)
+    {
+      level+=onhisto->GetBinContent(ibin);
+      leveloff+=offhisto->GetBinContent(ibin);
+    }
+  level/=(nbins-inibin+1);
+  leveloff/=(nbins-inibin+1);
+  
+  // normalize on/off
+  offhisto->Sumw2(); // needed to compute correct errors after normalization
+  const Float_t norm = level/leveloff;
+  cout << "Normalizing by factor " << norm <<endl;
+  offhisto->Scale(norm);    
+  
+  // significance:
+  Float_t sig=0,bg=0,esig=0,ebg=0;
+  Float_t significance=0;
+  const Int_t signbins = inibin-1;
+  for(Int_t ibin = 1; ibin<=signbins;ibin++)
+    {
+      //	Float_t sigma = (onhisto->GetBinContent(ibin)-level)/onhisto->GetBinError(ibin);
+      //	significance+=sigma*sigma;
+      sig  += onhisto->GetBinContent(ibin);
+      esig += onhisto->GetBinError(ibin)*onhisto->GetBinError(ibin);
+      bg   += offhisto->GetBinContent(ibin);
+      ebg  += offhisto->GetBinError(ibin)*offhisto->GetBinError(ibin);
+    }
+  Float_t error= TMath::Sqrt(esig+ebg);
+  significance = (sig-bg)/error;
+  
+  cout << "Significance: " << significance << endl;
+  
+  // plot
+  onhisto->SetXTitle("alpha (deg)");
+  onhisto->SetYTitle("Entries");
+  onhisto->SetMarkerColor(4);
+  onhisto->SetMarkerStyle(20);
+  onhisto->SetMarkerSize(.7);
+  onhisto->SetLineColor(4);
+  onhisto->SetMaximum(onhisto->GetBinContent(nbins)*1.5);
+  
+  offhisto->SetFillColor(2);
+  offhisto->SetMaximum(offhisto->GetBinContent(nbins)*1.5);
+  offhisto->SetXTitle("alpha (deg)");
+  offhisto->SetYTitle("Entries");
+  
+  offhisto->Draw("HIST");
+  offhisto->Draw("ESAME");
+  onhisto->Draw("ESAMES");
+  //    onhisto->Draw("E");
+  
+  // move stat box to make them all visible
+  gPad->Update();
+  TPaveStats* offpavstat = (TPaveStats*) offhisto->GetListOfFunctions()->FindObject("stats");
+  if(offpavstat)
+    {
+      Float_t shiftx = offpavstat->GetX2NDC()-offpavstat->GetX1NDC();
+      offpavstat->SetX1NDC(offpavstat->GetX1NDC()-shiftx);
+      offpavstat->SetX2NDC(offpavstat->GetX2NDC()-shiftx);
+    }
+  
+  // draw line
+  TLine* line = new TLine(0.,level,90.,level);
+  line->SetLineColor(2);
+  line->SetLineStyle(2);
+  //    line->Draw();
+  
+  gPad->Modified();
+  gPad->Update();
+  
+  myps.Close();
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/programs/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/Makefile	(revision 9772)
@@ -0,0 +1,65 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS IFAE library
+#
+##################################################################
+# @maintitle
+
+# @code
+
+#
+#  please change all system depend values in the 
+#  config.mk.${OSTYPE} file 
+#
+#
+include ../../../Makefile.conf.$(OSTYPE)
+include ../../../Makefile.conf.general
+
+PROGRAMS = makeHillas controlPlot
+#psffit falseSource srcPos optimizeCuts  controlPlot
+SOLIB    = $(MARSSYS)/libmars.so
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../library \
+	   -I../../../mbase \
+	   -I../../../mfbase \
+	   -I../../../mjobs \
+	   -I../../../mpedestal	 \
+	   -I../../../mbadpixels \
+	   -I../../../mfileio \
+           -I../../../mraw \
+           -I../../../manalysis \
+	   -I../../../mgui \
+	   -I../../../mgeom \
+	   -I../../../msignal \
+	   -I../../../mcalib \
+	   -I../../../mfilter \
+	   -I../../../mhbase \
+	   -I../../../mhcalib \
+	   -I../../../mimage \
+	   -I../../../mpointing \
+	   -I../../../mcamera \
+	   -I../../../mhist \
+	   -I../../../mastro \
+	   -I../../../mreport \
+	   -I../../../mranforest \
+           -I../../../mtemp
+
+all: $(PROGRAMS)
+
+include ../../../Makefile.rules
+
+$(PROGRAMS): $(PROGRAMS:=.o)
+	@echo " Linking $@ ..." 
+	$(CXX) $(CXXFLAGS) $(ROOTGLIBS) $(SOLIB) $@.o $(MARS_LIB) -o $@
+
+clean: rmobjs rmcore 
+mrproper: clean rmbak
+	rm -f $(PROGRAMS)
+
+
+# @endcode
Index: /tags/Mars-V0.9/mtemp/mifae/programs/calib.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/calib.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/calib.cc	(revision 9772)
@@ -0,0 +1,362 @@
+/*********************************/
+/* Compute the hillas parameters */
+/*********************************/
+
+#include "TString.h"
+#include "TArrayS.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MPedestalCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsTreat.h"
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MPedCalcPedRun.h"
+#include "MEvtLoop.h"
+#include "MGeomCamMagic.h"
+#include "MExtractedSignalCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationRelTimeCam.h"
+#include "MExtractor.h"
+#include "MExtractFixedWindow.h"
+#include "MExtractSlidingWindow.h"
+#include "MExtractSignal.h"
+#include "MCalibrationChargeCalc.h"
+#include "MFCosmics.h"
+#include "MContinue.h"
+#include "MLog.h"
+#include "MCerPhotEvt.h"
+#include "MPedPhotCam.h"
+#include "MCalibrate.h"
+#include "MPedPhotCalc.h"
+#include "MHillas.h"
+#include "MNewImagePar.h"
+#include "MRawRunHeader.h"
+#include "MSrcPosCam.h"
+#include "MBlindPixelCalc.h"
+#include "MImgCleanStd.h"
+#include "MHillasSrcCalc.h"
+#include "MHillasCalc.h"
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimeCalc2.h"
+#include "MIslands.h"
+#include "MIslandCalc.h"
+#include "MIslandClean.h"
+#include "MWriteRootFile.h"
+#include "MArgs.h"
+#include "MRunIter.h"
+#include "MJPedestal.h"
+#include "MJCalibration.h"
+#include "MHillasDisplay.h"
+#include "MF.h"
+#include "MContinue.h"
+
+#include "TApplication.h"
+
+#include <iostream>
+#include <fstream>
+#include <stdlib.h>
+
+using namespace std;
+
+Bool_t readDatacards(TString& filename);
+void calib();
+
+// initial and final time slices to be used in signal extraction
+const Byte_t hifirst = 1;
+const Byte_t hilast  = 14;
+const Byte_t lofirst = 3;
+const Byte_t lolast  = 14;
+
+// declaration of variables read from datacards
+TString  outname;
+TString  idirname;
+TString  filter;
+TString  psfilename("makehillas.ps");
+MRunIter caliter;
+MRunIter pediter;
+MRunIter datiter;
+UInt_t   display   = 0;
+ULong_t  nmaxevents= 999999999;
+Short_t  calflag   = 1;
+Float_t  lcore     = 3.0;
+Float_t  ltail     = 1.5;
+Int_t    islflag   = 0;
+Float_t  lnew      = 40;
+Int_t    kmethod   = 1;
+Int_t    kalgorithm = 1;
+Int_t    nfiles    = 0;
+
+const TString defaultcard="makehillas.datacard";
+/*************************************************************/
+static void Usage()
+{
+  gLog <<endl;
+  gLog << "Usage is:" << endl;
+  gLog << "   calib [-h] [-?] <datacards>" << endl << endl;
+  gLog << "     <datacards>: datacards file name (dafault input.datacards)" << endl;
+  gLog << "     -?/-h: This help" << endl << endl;
+}
+/*************************************************************/
+int main(int argc, char **argv)
+{
+  // create a TApplication to be able to 
+  TApplication app("Application",0,0);
+
+  // evaluate arguments
+  MArgs arg(argc, argv);
+  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+      Usage();
+      return -1;
+    }
+
+  TString datacard  = arg.GetArgumentStr(0);
+  if(!datacard.Length())
+    datacard = defaultcard;
+
+  if(!readDatacards(datacard))
+    {
+      cout << "Error reading datacards. Stoping" << endl;
+      return -1;
+    }
+
+  calib();
+}
+
+/*************************************************************/
+void calib()
+{
+  // Set the general tasks/containers
+  MExtractFixedWindow    extractor;
+  extractor.SetRange(hifirst,hilast,lofirst,lolast);
+ 
+  //  MExtractSlidingWindow    extractor;
+  // extractor.SetRange(hifirst,hilast,lofirst,lolast);
+  // extractor.SetWindowSize(2,2);
+  
+  MGeomCamMagic       geomcam;
+  MGeomApply          geomapl;
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+
+  // If you want to exclude pixels from the beginning, read 
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)  
+  //badcam.AsciiRead("badpixels.dat");
+
+  MJPedestal pedloop;
+  pedloop.SetInput(&pediter);
+  pedloop.SetExtractor(&extractor);
+  //  pedloop.SetBadPixels(badcam);
+
+  if (!pedloop.Process())
+    return;
+
+  /*****************************/
+  /* SECOND LOOP: CALIBRATION  */
+  /*****************************/        
+
+  MJCalibration calloop;
+
+  calloop.SetExtractor(&extractor);
+  calloop.SetInput(&caliter);
+  calloop.SetBadPixels(pedloop.GetBadPixels());
+  if(calflag==2)
+    calloop.SetUseBlindPixel();
+
+  if(calflag>0)
+    if (!calloop.Process(pedloop.GetPedestalCam()))
+      return;
+
+  Float_t meanCharge[577];
+  Float_t meanSigma[577];
+  Float_t meanFADC2Phe[577];
+  Float_t meanFADC2Phe_error[577];
+  Float_t meanFADCtoPh[577];
+  Float_t prob[577];
+  ofstream fout;
+
+  fout.open(outname);
+
+  for (Int_t i=0; i<577; i++)
+    {
+      meanCharge[i] = 0;
+      MCalibrationChargePix calpix = (MCalibrationChargePix&)(calloop.GetCalibrationCam())[i];
+      MCalibrationQEPix qepix = ( MCalibrationQEPix&)(calloop.GetQECam())[i];
+      meanCharge[i] = calpix.GetMean();
+      meanSigma[i] = calpix.GetSigma();
+      meanFADC2Phe[i]=calpix.GetMeanConvFADC2Phe();
+      meanFADC2Phe_error[i]=calpix.GetMeanConvFADC2PheErr();
+      meanFADCtoPh[i]=calpix.GetMeanConvFADC2Phe()/qepix.GetQECascadesFFactor(0);
+      prob[i]=calpix.GetProb();
+      fout << i << '\t' << meanCharge[i] << '\t' << meanSigma[i]<< '\t' << meanFADC2Phe[i]<< '\t' << meanFADC2Phe_error[i]<< '\t' <<meanFADCtoPh[i]<< '\t' <<prob[i]<< '\t' <<(Int_t)calpix.IsHiGainSaturation()<< '\t' <<(Int_t)calpix.IsFFactorMethodValid()<<endl;
+    }
+
+  fout.close();
+
+  /*****************************************************/
+  /* THIRD LOOP: Q in fadc event by event CALIBRATION  */
+  /*****************************************************/        
+
+  MParList  plist4;
+  MTaskList tlist4;
+  plist4.AddToList(&tlist4);
+  
+  // containers 
+
+  MCerPhotEvt         nphot;
+  plist4.AddToList(&geomcam);
+  plist4.AddToList(&pedloop.GetPedestalCam());
+  plist4.AddToList(&nphot);
+  
+  //tasks
+  MReadMarsFile read4("Events");
+  static_cast<MRead&>(read4).AddFiles(caliter); 
+  read4.DisableAutoScheme();
+  
+  MCalibrate::CalibrationMode_t calMode=MCalibrate::kNone;  
+
+  MCalibrate      photcalc(calMode);
+
+  tlist4.AddToList(&read4);
+  tlist4.AddToList(&geomapl);
+  tlist4.AddToList(&extractor);
+  tlist4.AddToList(&photcalc);
+
+  // Create and setup the eventloop
+  MEvtLoop datloop;
+  datloop.SetParList(&plist4);
+
+  //  if (!datloop.Eventloop(nmaxevents))
+  // return;
+  outname+="_evt";
+
+  datloop.PreProcess();
+
+  fout.open(outname);
+  while(tlist4.Process())
+    {
+      for(int i=0;i<577;i++)
+	fout<<nphot[i].GetNumPhotons()<<" ";
+      fout<<endl;
+    }
+  fout.close();
+  datloop.PostProcess();
+  return;
+
+}
+//-------------------------------------------------------------------------------
+
+Bool_t readDatacards(TString& filename)
+{
+  ifstream ifun(filename.Data());
+  if(!ifun)
+    {
+      cout << "File " << filename << " not found" << endl;
+      return kFALSE;
+    }
+
+  TString word;
+  
+  while(ifun >> word)
+    {
+      // skip comments
+      if(word[0]=='/' && word[1]=='/')
+	{
+	  while(ifun.get()!='\n'); // skip line
+	  continue;
+	}
+
+      // input file directory
+      if(strcmp(word.Data(),"IDIR")==0)
+	{
+	  if(idirname.Length())
+	    cout << "readDataCards Warning: overriding input directory file name" << endl;
+	  ifun >> idirname;
+	}
+
+      // pedestal runs
+      if(strcmp(word.Data(),"PRUNS")==0)
+	{
+	  if(pediter.GetNumRuns())
+	    cout << "readDataCards Warning: adding pedestal runs to the existing list" << endl;
+	  ifun >> word;
+	  pediter.AddRuns(word.Data(),idirname.Data());
+	}
+
+      // calibration runs
+      if(strcmp(word.Data(),"CRUNS")==0)
+	{
+	  if(caliter.GetNumRuns())
+	    cout << "readDataCards Warning: adding calibration runs to the existing list" << endl;
+	  ifun >> word;
+	  caliter.AddRuns(word.Data(),idirname.Data());
+	}
+
+      // output file name
+      if(strcmp(word.Data(),"OUTFILE")==0)
+	{
+	  if(outname.Length())
+	    cout << "readDataCards Warning: overriding output file name" << endl;
+	  ifun >> outname;
+	}
+
+      // calibration flag
+      if(strcmp(word.Data(),"CALFLAG")==0)
+	ifun >> calflag;
+
+
+    }
+
+  pediter.Reset();
+  caliter.Reset();
+  datiter.Reset();
+  TString pfile;
+
+  // Dump read values
+  cout << "************************************************" << endl;
+  cout << "* Datacards read from file " << filename << endl;
+  cout << "************************************************" << endl;
+  cout << "Pedestal file (s): "  << endl;
+  while(!(pfile=pediter.Next()).IsNull())
+    cout << pfile << endl;
+  cout << "Calibration file (s): "  << endl;
+  while(!(pfile=caliter.Next()).IsNull())
+    cout << pfile << endl;
+  cout << "Output file name: " << outname << endl;
+  cout << "Calibration: ";
+  if(calflag==0)    
+    cout << "Pixel area proportional intercalibration" << endl;
+  else if(calflag==-1)    
+    cout << "No calibration whatsoever" << endl;
+  else if(calflag==1)
+    cout << "Default calibration" << endl;
+  else if(calflag==11)
+    cout << "Default calibration + bad pixels interpolation" << endl;
+  
+  if(!pediter.GetNumEntries())
+    {
+      cout << "No pedestal file name specified" << endl;
+      return kFALSE;
+    }
+  if(!caliter.GetNumEntries() && calflag>0)
+    {
+      cout << "No calibration file name specified" << endl;
+      return kFALSE;
+    }
+  if(!outname.Length())
+    {
+      cout << "No output file name specified" << endl;
+      return kFALSE;
+    }
+
+
+  return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/programs/calib.datacard
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/calib.datacard	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/calib.datacard	(revision 9772)
@@ -0,0 +1,32 @@
+/////////////////////////////////////////////////////////
+// Data card template for calib executable             //
+//                                                     //
+// *** Compulsory cards are:                           //
+// PRUNS, CRUNS, DRUNS, OUTFILE                        //
+//                                                     //
+// the rest are optional                               //
+// *** Do NEVER add a datacard with no value after it  //
+/////////////////////////////////////////////////////////
+
+
+// data file directory
+IDIR /nfs/magic/CCdata/rootdata/Mrk421/Period016/2004_04_22/
+
+// Pedestal (PRUNS), calibration (CRUNS)
+PRUNS 30150
+CRUNS 30148
+
+// output file name
+OUTFILE ./prueba.root
+
+// calibration flag:
+// -1: kDummy
+//  0: kNone
+//  1: kDefault (F factor)
+//  2: kDefault (Blind Pixels)
+// 11: kDefault + bad pixel interpolation
+CALFLAG 1
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/programs/controlPlot.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/controlPlot.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/controlPlot.cc	(revision 9772)
@@ -0,0 +1,394 @@
+////////////////////////////////////////////////////////////////////////////////////
+//
+//             _____ Control Plot program_____
+//
+//  Take as input root files with hillas parameters and generates several
+//  control plots.
+//  Output is a file with :
+//       - Number of hits plot
+//
+//                 Ester Aliu   <aliu@ifae.es>
+//                 Oscar Blanch <blanch@ifae.es>
+//                 Javier Rico  <jrico@ifae.es>
+////////////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <iostream>
+
+#include "TString.h"
+
+#include "MHillasSrcCalc.h"
+#include "MHillasSrc.h"
+#include "MSrcRotate.h"
+#include "MSrcPosFromFile.h"
+#include "MSrcTranslate.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MHillas.h"
+#include "MReadTree.h"
+#include "MEvtLoop.h"
+#include "MLog.h"
+#include "MArgs.h"
+#include "MWriteRootFile.h"
+#include "MTime.h"
+#include "MControlPlots.h"
+#include "MIslands.h"
+#include "MContinue.h"
+#include "MF.h"
+
+using namespace std;
+
+Bool_t readDatacards(TString& filename);
+void controlPlot();
+
+//-----------------------------------------------------------------------------
+// declaration of variables read from datacards
+//-----------------------------------------------------------------------------
+
+TString  inputFile;
+TString  offFile;
+TString  outputFile;
+TString  filter;
+TString  sizecut;
+TString  distcut;
+TString  widthcut;
+TString  lengthcut;
+TString  centercut;
+ULong_t  nmaxevents=999999999;
+Float_t  xsrcpos=0.;
+Float_t  ysrcpos=0.;
+Double_t mjdpos=0;
+
+//-----------------------------------------------------------------------------
+// constants
+//-----------------------------------------------------------------------------
+
+const TString defaultcard="controlplot.datacard";
+const Float_t conver   = 189./0.6; // conversion factor degrees to mm
+
+//-----------------------------------------------------------------------------
+
+static void Usage()
+{
+  gLog <<endl;
+  gLog << "Usage is:" << endl;
+  gLog << "   controlPlot [-h] [-?] <datacards>" << endl << endl;
+  gLog << "     <datacards>: datacards file name (dafault " << defaultcard <<")" << endl;
+  gLog << "     -?/-h: This help" << endl << endl;
+}
+
+//-----------------------------------------------------------------------------
+int main(int argc, char **argv)
+{
+  // evaluate arguments
+  MArgs arg(argc, argv);
+  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+      Usage();
+      return -1;
+    }
+
+  TString datacard  = arg.GetArgumentStr(0);
+  if(!datacard.Length())
+    datacard = defaultcard;
+
+  if(!readDatacards(datacard))
+    {
+      cout << "Error reading datacards. Stoping" << endl;
+      return -1;
+    }
+
+  controlPlot();
+}
+
+//-----------------------------------------------------------------------------
+void  controlPlot()
+{
+  // containers
+  MParList  plist;  
+  MTaskList tlist;
+  MIslands  islands;
+
+  // include containers in parameter list
+  plist.AddToList(&tlist);
+	  	  
+  MF cut(filter);
+  MF cutS(sizecut);
+  MF cutD(distcut);
+  MF cutL(lengthcut);
+  MF cutW(widthcut);
+  MF cutC(centercut);
+
+  // tasks
+  MReadTree read("Parameters", inputFile);
+  read.DisableAutoScheme();  
+
+  MControlPlots controlplots(outputFile);
+  controlplots.SetProduceFile(kFALSE);
+  controlplots.SetMode(MControlPlots::kOn);
+  
+  MContinue applycutS(&cutS);
+  applycutS.SetInverted(kTRUE);
+
+  MContinue applycutD(&cutD);
+  applycutD.SetInverted(kTRUE);
+
+  MContinue applycutL(&cutL);
+  applycutL.SetInverted(kTRUE);
+
+  MContinue applycutW(&cutW);
+  applycutW.SetInverted(kTRUE);
+
+  MContinue applycutC(&cutC);
+  applycutC.SetInverted(kTRUE);
+
+  MContinue applycut(&cut);
+  applycut.SetInverted(kTRUE);
+
+
+  // include tasks in task list
+  tlist.AddToList(&read);
+  if(sizecut.Length())
+    tlist.AddToList(&applycutS);
+  if(distcut.Length())
+    tlist.AddToList(&applycutD);
+  if(lengthcut.Length())
+    tlist.AddToList(&applycutL);
+  if(widthcut.Length())
+    tlist.AddToList(&applycutW);
+  if(filter.Length())
+    tlist.AddToList(&applycut);
+  if(centercut.Length())
+    tlist.AddToList(&applycutC);
+  tlist.AddToList(&controlplots);
+
+  // Eventloop
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  if (!evtloop.Eventloop(nmaxevents))
+    return;  
+ 
+  tlist.PrintStatistics();
+  
+  // do off-data if input file was specified
+  if(!offFile.Length())
+    return;
+
+
+  // containers
+  MParList  plist2;  
+  MTaskList tlist2;
+  MIslands  islands2;
+
+  // include containers in parameter list
+  plist2.AddToList(&tlist2);
+	  	  
+  // tasks
+  MReadTree read2("Parameters", offFile);
+  read2.DisableAutoScheme();  
+  tlist2.AddToList(&read2);
+
+  controlplots.SetMode(MControlPlots::kOff);
+  controlplots.SetProduceFile(kTRUE);
+  controlplots.Reset();
+
+  // include tasks in task list
+  if(sizecut.Length())
+    tlist2.AddToList(&applycutS);
+  if(distcut.Length())
+    tlist2.AddToList(&applycutD);
+  if(lengthcut.Length())
+    tlist2.AddToList(&applycutL);
+  if(widthcut.Length())
+    tlist2.AddToList(&applycutW);
+  if(filter.Length())
+    tlist2.AddToList(&applycut);
+  if(centercut.Length())
+    tlist2.AddToList(&applycutC);
+  tlist2.AddToList(&controlplots);
+
+  // Eventloop
+  MEvtLoop evtloop2;
+  evtloop2.SetParList(&plist2);
+  if (!evtloop2.Eventloop(nmaxevents))
+    return;  
+ 
+  tlist2.PrintStatistics();
+  
+  // do off-data if input file was specified
+  if(!offFile.Length())
+    return;
+
+}
+
+//-----------------------------------------------------------------------
+  
+Bool_t readDatacards(TString& filename)
+{
+  ifstream ifun(filename.Data());
+  if(!ifun)
+    {
+      cout << "File " << filename << " not found" << endl;
+      return kFALSE;
+    }
+
+  TString word;
+  
+  while(ifun >> word)
+    {
+      // skip comments
+      if(word[0]=='/' && word[1]=='/')
+	{
+	  while(ifun.get()!='\n'); // skip line
+	  continue;
+	}
+      
+      // number of events
+      if(strcmp(word.Data(),"NEVENTS")==0)
+	ifun >> nmaxevents;
+
+      // input file name
+      if(strcmp(word.Data(),"ONFILES")==0)
+	{
+	  if(inputFile.Length())
+	    cout << "readDataCards Warning: overriding on-data file name" << endl;
+	  ifun >> inputFile;
+	}
+
+      // off-data file name
+      if(strcmp(word.Data(),"OFFFILES")==0)
+	{
+	  if(offFile.Length())
+	    cout << "readDataCards Warning: overriding off-data file name" << endl;
+	  ifun >> offFile;
+	}
+
+      // output file name
+      if(strcmp(word.Data(),"HITSFILE")==0)
+	{
+	  if(outputFile.Length())
+	    cout << "readDataCards Warning: overriding output file name" << endl;
+	  ifun >> outputFile;
+	}
+      // exclusion cut
+      if(strcmp(word.Data(),"FILTER")==0)
+	{
+	  if(filter.Length())
+	    cout << "readDataCards Warning: overriding existing cut" << endl;
+	  
+	  char ch;
+	  while((ch=ifun.get())!='\n')
+	    filter.Append(ch);	  
+	}
+      if(strcmp(word.Data(),"SIZECUT")==0)
+	{
+	  if(sizecut.Length())
+	    cout << "readDataCards Warning: overriding existing size cut" << endl;
+	  char ch[10];
+	  sizecut="(MHillas.fSize>";
+	  ifun >> ch;
+	  sizecut+=ch;
+	  sizecut+=") && (MHillas.fSize<";
+	  ifun >> ch;
+	  sizecut+=ch;
+	  sizecut+=")";
+	}
+      if(strcmp(word.Data(),"DISTCUT")==0)
+	{
+	  if(distcut.Length())
+	    cout << "readDataCards Warning: overriding existing DIST cut" << endl;
+	  char ch[10];
+	  distcut="(MHillasSrc.fDist>";
+	  ifun >> ch;
+	  distcut+=ch;
+	  distcut+="*";
+	  distcut+=conver;
+	  distcut+=") && (MHillasSrc.fDist<";
+	  ifun >> ch;
+	  distcut+=ch;
+	  distcut+="*";
+	  distcut+=conver;
+	  distcut+=")";
+	}
+      if(strcmp(word.Data(),"WIDTHCUT")==0)
+	{
+	  if(widthcut.Length())
+	    cout << "readDataCards Warning: overriding existing width cut" << endl;
+	  char ch[10];
+	  widthcut="(MHillas.fWidth>";
+	  ifun >> ch;
+	  widthcut+=ch;
+	  widthcut+="*";
+	  widthcut+=conver;
+	  widthcut+=") && (MHillas.fWidth<";
+	  ifun >> ch;
+	  widthcut+=ch;
+	  widthcut+="*";
+	  widthcut+=conver;
+	  widthcut+=")";
+	}
+      if(strcmp(word.Data(),"LENGTHCUT")==0)
+	{
+	  if(lengthcut.Length())
+	    cout << "readDataCards Warning: overriding existing length cut" << endl;
+	  char ch[10];
+	  lengthcut="(MHillas.fLength>";
+	  ifun >> ch;
+	  lengthcut+=ch;
+	  lengthcut+="*";
+	  lengthcut+=conver;
+	  lengthcut+=") && (MHillas.fLength<";
+	  ifun >> ch;
+	  lengthcut+=ch;
+	  lengthcut+="*";
+	  lengthcut+=conver;
+	  lengthcut+=")";
+	}
+      if(strcmp(word.Data(),"CENTERCUT")==0)
+	{
+	  if(centercut.Length())
+	    cout << "readDataCards Warning: overriding existing center cut" << endl;
+	  char ch[10];
+	  centercut="sqrt(MHillas.fMeanX*MHillas.fMeanX+MHillas.fMeanY*MHillas.fMeanY)<";
+	  ifun >> ch;
+	  centercut+=ch;
+	  centercut+="*";
+	  centercut+=conver;
+	}
+    }
+  
+  // check compulsory values
+  if(!inputFile.Length())
+    {
+      cout << "No on-data file name specified" << endl;
+      return kFALSE;
+    }
+
+  if(!offFile.Length())
+    {
+      cout << "No off-data file name specified" << endl;
+      return kFALSE;
+    }
+
+  if(!outputFile.Length())
+    {
+      cout << "No output file name specified" << endl;
+      return kFALSE;
+    }
+
+  MTime thetime(mjdpos);
+
+  // Dump read values
+  cout << "************************************************" << endl;
+  cout << "* Datacards read from file " << filename << endl;
+  cout << "************************************************" << endl;
+  cout << "Maximum number of input events: " << nmaxevents << endl;
+  cout << "Input file name(s): " << inputFile << endl;
+  cout << "Input file name(s) for off data: " << offFile << endl;
+  cout << "Output file name for # hits plot : " << outputFile << endl;
+  if(filter.Length())
+    cout << "Applying rejection cut: " << filter << endl;
+  cout << "***********" << endl << endl;
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/programs/controlplot.datacard
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/controlplot.datacard	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/controlplot.datacard	(revision 9772)
@@ -0,0 +1,38 @@
+
+// Maximun number of on and off events to be processed)
+NEVENTS 9999
+
+// On-data file name pattern
+ONFILES /mnt/users/jrico/magic/hillasCrab_200411_new.root
+
+// Off-data file name pattern
+OFFFILES /mnt/users/jrico/magic/hillasCrab_200411_new.root
+
+// output file name
+HITSFILE  ./prueba.ps
+
+//////////
+// CUTS //
+//////////
+
+// Size cut (lower and upper)
+SIZECUT  0   9999999
+
+// Dist cut (lower and upper) in degrees
+DISTCUT   0.2 1.2
+
+// Width cut (lower and upper) in degrees
+WIDTHCUT  0  0.15
+
+// Length cut (lower and upper) in degrees
+LENGTHCUT  0  0.25
+
+// maxX and maxY upper cut in degrees
+CENTERCUT  1.2
+
+// Other Additional cut
+// Selection cut. 
+// Condition "==" not supported.
+// Enclose all conditions between brakets, like: "(x<y) && (z<5)"
+// (see MF description class for more details)
+// FILTER (MHillas.fLength<100) && (MHillas.fLength>50)
Index: /tags/Mars-V0.9/mtemp/mifae/programs/falseSource.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/falseSource.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/falseSource.cc	(revision 9772)
@@ -0,0 +1,555 @@
+////////////////////////////////////////////////////////////////////////////////////
+//
+//             _____False Source Method macro_____
+//
+//  Take as input root files with hillas parameters, perform derotation (optional)
+//  and generates the alpha histograms for On and Off for different positions of the
+//  source. These histos can be ploted with signal.C and signalPoint.C
+//
+//                 Ester Aliu   <aliu@ifae.es>
+//                 Oscar Blanch <blanch@ifae.es>
+//                 Javier Rico  <jrico@ifae.es>
+////////////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <iostream>
+
+#include "TString.h"
+#include "TH2F.h"
+#include "TFile.h"
+
+#include "MHillasSrcCalc.h"
+#include "MSrcPosCam.h"
+#include "MSrcTranslate.h"
+#include "MHillasSrc.h"
+#include "MSrcRotate.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MHillas.h"
+#include "MReadTree.h"
+#include "MEvtLoop.h"
+#include "MLog.h"
+#include "MArgs.h"
+
+using namespace std;
+
+Bool_t readDatacards(TString& filename);
+void falseSource();
+
+//-----------------------------------------------------------------------------
+// declaration of variables read from datacards
+//-----------------------------------------------------------------------------
+
+TString onFile;
+TString offFile;
+TString outputFile;
+Bool_t  kRotate=1;
+Bool_t  kSrcPolicy=kFALSE;
+Double_t fRA= -1.;
+Double_t fDEC= -1.;
+ULong_t nmaxevents=999999999;
+
+// cuts (default values to be overriden by datacards)
+Float_t minsize   = 0;        // minimum size (# of photons)
+Float_t maxsize   = 9999999;  // maximum size (# of photons)
+Float_t mindist   = 0;        // minimum distance cut (deg)
+Float_t maxdist   = 10;       // maximum distance cut (deg)
+Float_t minwidth  = 0.;       // minimum width cut (deg)
+Float_t maxwidth  = 10;       // maximum width cut (deg)
+Float_t minlength = 0;        // minimum length cut (deg)
+Float_t maxlength = 10;       // maximum length cut (deg)
+Float_t maxXY     = maxdist;  // maximum X and Y distance from the camera center
+
+// binning
+Int_t binning = 21;           // number of bins in false source search (one coordinate) 
+Int_t nbin    = 18;           // number of bins for alpha plots
+Float_t field = 2.;           // width of the examined field (degrees)
+
+//-----------------------------------------------------------------------------
+// constants
+//-----------------------------------------------------------------------------
+
+const TString defaultcard="falsesource.datacard";
+
+const Float_t alphamin = 0.;       // minimum value in alpha (degrees) 
+const Float_t alphamax = 90.;      // maximum value in alpha (degrees)
+const Float_t conver   = 189./0.6; // conversion factor degrees to mm
+const Float_t srclimit = field*conver;
+const Float_t srcstep  = 3.;
+const Int_t   nsrcbin  = (Int_t) (srclimit/srcstep);
+
+//-----------------------------------------------------------------------------
+
+static void Usage()
+{
+  gLog <<endl;
+  gLog << "Usage is:" << endl;
+  gLog << "   falseSource [-h] [-?] <datacards>" << endl << endl;
+  gLog << "     <datacards>: datacards file name (dafault falsesource.datacards)" << endl;
+  gLog << "     -?/-h: This help" << endl << endl;
+}
+
+//-----------------------------------------------------------------------------
+int main(int argc, char **argv)
+{
+  // evaluate arguments
+  MArgs arg(argc, argv);
+  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+      Usage();
+      return -1;
+    }
+
+  TString datacard  = arg.GetArgumentStr(0);
+  if(!datacard.Length())
+    datacard = defaultcard;
+
+  if(!readDatacards(datacard))
+    {
+      cout << "Error reading datacards. Stoping" << endl;
+      return -1;
+    }
+  falseSource();
+}
+
+void falseSource()
+{
+  // CUTS
+
+  // variable declaration  
+  Float_t xpos;
+  Float_t ypos;  
+  Char_t name[20]; 
+  Char_t title[50];   
+  Float_t stepDegrees = field/(binning-1);    // degrees
+  Float_t step        = stepDegrees*conver;   // mm
+  Int_t   ival        =  (Int_t) ceil((Float_t)(binning-1)/2); // index bound
+  
+  // Hillas variables
+  Float_t alpha;
+  Float_t size;
+  Float_t dist;  
+  Float_t length;
+  Float_t width;
+  Float_t meanX;
+  Float_t meanY;
+  
+  // create the histograms (empty)
+  TH1F* hOnAlpha[binning][binning];
+  TH1F* hOffAlpha[binning][binning];
+  TH2F* hOnSrcPos[binning];
+  TH2F* hOffSrcPos[binning];
+
+  for(Int_t i = -ival; i <= ival ; i++){  
+    for(Int_t j = -ival; j <= ival ; j++){
+      
+      sprintf(name,"hOnAlpha[%d][%d]", i, j);
+      sprintf(title,"Alpha-Plot(On data) (%d ,%d)", i, j);
+      hOnAlpha[i+ival][j+ival] = new TH1F(name, title, nbin, alphamin, alphamax);
+      
+      sprintf(name,"hOffAlpha[%d][%d]", i, j);
+      sprintf(title,"Alpha-Plot(Off data) (%d ,%d)", i, j);
+      hOffAlpha[i+ival][j+ival] = new TH1F(name, title, nbin, alphamin, alphamax);
+
+      if(j==0)
+	{
+	  sprintf(name,"hOnSrcPos[%d]", i);
+	  sprintf(title,"Source position (On data) (%d)", i);
+	  hOnSrcPos[i+ival] = new TH2F(name, title, nsrcbin, -srclimit, srclimit, nsrcbin, -srclimit, srclimit);
+	  
+	  sprintf(name,"hOffSrcPos[%d]", i);
+	  sprintf(title,"Source position (Off data) (%d)", i);
+	  hOffSrcPos[i+ival] = new TH2F(name, title, nsrcbin, -srclimit, srclimit, nsrcbin, -srclimit, srclimit);
+	}
+    }
+  }
+  
+
+  
+  /******************************************************************
+                           FILL ON-DATA HISTOS
+  *******************************************************************/
+  
+  // source dependent hillas containers/tasks
+  MSrcPosCam*     source[binning][binning];
+  MHillasSrc*     hillasSrc[binning][binning];
+  MSrcTranslate*  srctranslate[binning][binning];
+  MSrcRotate*     srcrotate[binning][binning];
+  MHillasSrcCalc* csrc1[binning][binning];
+
+  // normal containers/classes
+  MParList  plist;  
+  MTaskList tlist;
+  MHillas   hillas;
+
+  plist.AddToList(&tlist);
+  plist.AddToList(&hillas);
+    
+  MReadTree read("Parameters", onFile);
+  read.DisableAutoScheme();  
+  tlist.AddToList(&read);
+    
+  char sourceName[100];  
+  char hillasSrcName[100];
+  char translateName[100];  
+  char rotateName[100];
+
+  // create the tasks/containers for the different source positions
+  for(Int_t i=-ival;i<=ival;i++)
+    {    
+      xpos = step*i;      
+      for(Int_t j=-ival;j<=ival;j++)
+	{
+	  ypos = step*j;
+	  
+	  // name the different containers
+	  if (i<0 && j<0)
+	    {
+	      Int_t k = -i;
+	      Int_t l = -j;
+	      sprintf(sourceName,    "MSrcPosCam_Min%dMin%d", k, l);
+	      sprintf(hillasSrcName, "MHillasSrc_Min%dMin%d", k, l);
+	      sprintf(translateName, "MSrcTranslate_Min%dMin%d", k, l);
+	      sprintf(rotateName,    "MSrcRotate_Min%dMin%d", k, l);
+	    }
+	  
+	  if (i<0 && j>=0)
+	    {
+	      Int_t k = -i;
+	      sprintf(sourceName,    "MSrcPosCam_Min%d%d", k, j);
+	      sprintf(hillasSrcName, "MHillasSrc_Min%d%d", k, j);
+	      sprintf(translateName, "MSrcTranslate_Min%d%d", k, j);
+	      sprintf(rotateName,    "MSrcRotate_Min%d%d", k, j);
+	    }
+	  
+	  if (i>=0 && j<0)
+	    {
+	      Int_t l = -j;
+	      sprintf(sourceName,    "MSrcPosCam_%dMin%d", i, l);
+	      sprintf(hillasSrcName, "MHillasSrc_%dMin%d", i, l);
+	      sprintf(translateName, "MSrcTranslate_%dMin%d", i, l);
+	      sprintf(rotateName,    "MSrcRotate_%dMin%d", i, l);
+	    }
+	  
+	  if (i>=0 && j>= 0)
+	    {
+	      sprintf(sourceName,    "MSrcPosCam_%d%d", i, j);
+	      sprintf(hillasSrcName, "MHillasSrc_%d%d", i, j);
+	      sprintf(translateName, "MSrcTranslate_%d%d", i, j);
+	      sprintf(rotateName,    "MSrcRotate_%d%d", i, j);
+	    }
+
+	  // include containers in parameter list
+	  source[i+ival][j+ival] = new MSrcPosCam(sourceName);
+	  plist.AddToList(source[i+ival][j+ival]);
+	  	  
+	  hillasSrc[i+ival][j+ival] = new MHillasSrc(hillasSrcName);	  
+	  plist.AddToList(hillasSrc[i+ival][j+ival]);      
+	  
+	  // define the different tasks and include them in the task list
+	  srctranslate[i+ival][j+ival] = new MSrcTranslate("MSrcPosCam",sourceName,"MDCA",translateName);	  
+	  srctranslate[i+ival][j+ival]->SetTranslation(xpos,ypos);	  
+	  srctranslate[i+ival][j+ival]->SetRelativeTranslation(kSrcPolicy);
+	  srctranslate[i+ival][j+ival]->SetInternalHistoBinSize(5.);
+	  srctranslate[i+ival][j+ival]->SetMode(MSrcPlace::kOn);
+      
+	  tlist.AddToList(srctranslate[i+ival][j+ival]);  
+
+	  if(kRotate && !kSrcPolicy)
+	    {
+	      srcrotate[i+ival][j+ival] = new MSrcRotate(sourceName,sourceName,"MDCA",rotateName);
+	      srcrotate[i+ival][j+ival]->SetRAandDEC(fRA,fDEC);	  
+
+	      srctranslate[i+ival][j+ival]->SetCreateHisto(kFALSE);
+	      srcrotate[i+ival][j+ival]->SetMode(MSrcPlace::kOn);	      
+	      srcrotate[i+ival][j+ival]->SetInternalHistoBinSize(5.);
+
+	      tlist.AddToList(srcrotate[i+ival][j+ival]);  
+	    }
+	  else
+	    srcrotate[i+ival][j+ival] = NULL;
+
+
+	  TString HilName = "MHillas";	  
+	  csrc1[i+ival][j+ival] = new MHillasSrcCalc(sourceName, hillasSrcName);
+	  csrc1[i+ival][j+ival]->SetInput(HilName);  
+	  
+	  tlist.AddToList(csrc1[i+ival][j+ival]);  
+	  
+	} // loop on j (y coordinate)
+    } // loop on i (x coordinate)
+  
+  
+  // Eventloop
+  MEvtLoop evtloop;  
+  evtloop.SetParList(&plist);
+  //  MProgressBar bar;
+  //  evtloop.SetProgressBar(&bar);  
+  if (!evtloop.PreProcess())
+    return;
+  
+  // select the events passing the cuts
+  UInt_t nread=0;
+  while (tlist.Process())
+    {
+      for(Int_t i = -ival; i <= ival ; i++)	
+	for(Int_t j = -ival; j <= ival ; j++)
+	  {
+	    width  = hillas.GetWidth()/conver;
+	    length = hillas.GetLength()/conver;
+	    size   = hillas.GetSize();
+	    dist   = hillasSrc[i+ival][j+ival]->GetDist()/conver;
+	    meanX  = hillas.GetMeanX()/conver;
+	    meanY  = hillas.GetMeanY()/conver;
+	    
+	    if (width<maxwidth && length<maxlength && dist>mindist && dist<maxdist && size>minsize && meanX<maxXY && meanY<maxXY)
+	      {
+		alpha = hillasSrc[i+ival][j+ival]->GetAlpha();
+		hOnAlpha[i+ival][j+ival]->Fill(TMath::Abs(alpha));
+	      }	
+
+	    // fill source position histo
+	    if(j==0)
+	      hOnSrcPos[i+ival]->Fill(source[i+ival][j+ival]->GetX(),source[i+ival][j+ival]->GetY());
+	  }
+      if(++nread>nmaxevents) break;
+    }
+      
+  // end 
+  evtloop.PostProcess();    
+  tlist.PrintStatistics();
+
+
+  /******************************************************************
+                        FILL OFF-DATA HISTOS
+  *******************************************************************/
+ for(Int_t i=-ival;i<=ival;i++)
+   for(Int_t j=-ival;j<=ival;j++)
+     {
+       if(srcrotate[i+ival][j+ival])
+	 srcrotate[i+ival][j+ival]->SetMode(MSrcPlace::kOff);
+       srctranslate[i+ival][j+ival]->SetMode(MSrcPlace::kOff);
+     }
+
+  
+  MReadTree read2("Parameters", offFile);
+  read2.DisableAutoScheme();
+  
+  tlist.AddToListBefore(&read2, &read, "All");
+  tlist.RemoveFromList(&read);
+  
+  if (!evtloop.PreProcess())
+    return;
+
+  nread=0;
+  while (tlist.Process())
+    {
+      for(Int_t i = -ival; i <= ival ; i++)
+	for(Int_t j = -ival; j <= ival ; j++)
+	  {	    
+	    width  = hillas.GetWidth()/conver;
+	    length = hillas.GetLength()/conver;
+	    size   = hillas.GetSize();   
+	    dist   = hillasSrc[i+ival][j+ival]->GetDist()/conver;
+	    meanX  = hillas.GetMeanX()/conver;
+	    meanY  = hillas.GetMeanY()/conver;
+	    
+	    if (width<maxwidth && length<maxlength && dist>mindist && dist<maxdist && size>minsize && meanX<maxXY && meanY<maxXY)
+	      {
+		alpha = hillasSrc[i+ival][j+ival]->GetAlpha();
+		hOffAlpha[i+ival][j+ival]->Fill(TMath::Abs(alpha));	      
+	      } 	
+
+	    // fill source position histo
+	    if(j==0)
+	      hOffSrcPos[i+ival]->Fill(source[i+ival][j+ival]->GetX(),source[i+ival][j+ival]->GetY());
+	  }
+      if(++nread>nmaxevents) break;
+    }
+        
+  evtloop.PostProcess();    
+
+  // Save results
+  TFile *f = new TFile(outputFile, "RECREATE");
+  
+  for(Int_t i = -ival; i <= ival ; i++){  
+    for(Int_t j = -ival; j <= ival ; j++){
+      hOnAlpha[i+ival][j+ival]->Write();
+      hOffAlpha[i+ival][j+ival]->Write();
+      if(j==0)
+	{
+	  hOnSrcPos[i+ival]->Write();
+	  hOffSrcPos[i+ival]->Write();
+	}
+    }
+  }
+
+  f->Close();
+
+ for(Int_t i=-ival;i<=ival;i++)
+   for(Int_t j=-ival;j<=ival;j++)
+     {
+       if(srcrotate[i+ival][j+ival])
+	 delete srcrotate[i+ival][j+ival];
+       delete srctranslate[i+ival][j+ival];
+       delete source[i+ival][j+ival];
+       delete hillasSrc[i+ival][j+ival];
+       delete csrc1[i+ival][j+ival];
+     }
+}
+//-----------------------------------------------------------------------
+  
+Bool_t readDatacards(TString& filename)
+{
+  ifstream ifun(filename.Data());
+  if(!ifun)
+    {
+      cout << "File " << filename << " not found" << endl;
+      return kFALSE;
+    }
+
+  TString word;
+  
+  while(ifun >> word)
+    {
+      // skip comments
+      if(word[0]=='/' && word[1]=='/')
+	{
+	  while(ifun.get()!='\n'); // skip line
+	  continue;
+	}
+
+      // number of events
+      if(strcmp(word.Data(),"NEVENTS")==0)
+	ifun >> nmaxevents;
+
+      // on-data file name
+      if(strcmp(word.Data(),"ONFILES")==0)
+	{
+	  if(onFile.Length())
+	    cout << "readDataCards Warning: overriding on-data file name" << endl;
+	  ifun >> onFile;
+	}
+
+      // off-data file name
+      if(strcmp(word.Data(),"OFFFILES")==0)
+	{
+	  if(offFile.Length())
+	    cout << "readDataCards Warning: overriding off-data file name" << endl;
+	  ifun >> offFile;
+	}
+
+      // output file name
+      if(strcmp(word.Data(),"OUTFILE")==0)
+	{
+	  if(outputFile.Length())
+	    cout << "readDataCards Warning: overriding output file name" << endl;
+	  ifun >> outputFile;
+	}
+
+      // rotation flag
+      if(strcmp(word.Data(),"ROTFLAG")==0)
+	ifun >> kRotate;
+
+      // source movement policy flag
+      if(strcmp(word.Data(),"SRCABS")==0)
+	ifun >> kSrcPolicy;	  
+
+
+      // source celestial coordinates 
+      if(strcmp(word.Data(),"SRCCOORDS")==0)
+	{
+	  ifun >> fRA;
+	  ifun >> fDEC;	  
+	}
+
+      // field width
+      if(strcmp(word.Data(),"FIELD")==0)
+	ifun >> field;
+
+      // binning
+      if(strcmp(word.Data(),"BINNING")==0)
+	ifun >> binning;
+
+      // Number of bins in alpha plots
+      if(strcmp(word.Data(),"NBIN")==0)
+	ifun >> nbin;
+
+      // size cut
+      if(strcmp(word.Data(),"SIZECUT")==0)
+	{
+	  ifun >> minsize;
+	  ifun >> maxsize;	  
+	}
+
+      // dist cut
+      if(strcmp(word.Data(),"DISTCUT")==0)
+	{
+	  ifun >> mindist;
+	  ifun >> maxdist;	  
+	}
+
+      // width cut
+      if(strcmp(word.Data(),"WIDTHCUT")==0)
+	{
+	  ifun >> minwidth;
+	  ifun >> maxwidth;	  
+	}
+      
+      // length cut
+      if(strcmp(word.Data(),"LENGTHCUT")==0)
+	{
+	  ifun >> minlength;
+	  ifun >> maxlength;	  
+	}
+
+      // maxX and maxY upper cut
+      if(strcmp(word.Data(),"CENTERCUT")==0)
+	ifun >> maxXY;	  
+    }
+
+  // check compulsory values
+  if(!onFile.Length())
+    {
+      cout << "No on-data file name specified" << endl;
+      return kFALSE;
+    }
+  if(!offFile.Length())
+    {
+      cout << "No off-data file name specified" << endl;
+      return kFALSE;
+    }
+  if(!outputFile.Length())
+    {
+      cout << "No output file name specified" << endl;
+      return kFALSE;
+    }
+
+
+  // Dump read values
+  cout << "************************************************" << endl;
+  cout << "* Datacards read from file " << filename << endl;
+  cout << "************************************************" << endl;
+  cout << "Maximum number of input events: " << nmaxevents << endl;
+  cout << "On-data file name(s): " << onFile << endl;
+  cout << "Off-data file name(s): " << offFile << endl;
+  cout << "Output file name: " << outputFile << endl;
+  if(kSrcPolicy)
+    cout << "Source position displaced with respect to the original existing one (no rotation applied)" << endl;
+  else
+    {
+      cout << "De-rotation flag " << kRotate << endl;
+      cout << "Source celestial coordiantes (rad): RA = " << fRA << ", DEC = " << fDEC << endl;
+    }
+  cout << "Field width (degrees): " << field << endl;
+  cout << "Field binning: " << binning << endl;
+  cout << "Number of alpha plot bins: " << nbin << endl;
+  cout << "Size cuts (# of photons): ("<<minsize<<","<<maxsize<<")" << endl;
+  cout << "Dist cuts (degrees): ("<<mindist<<","<<maxdist<<")" << endl;
+  cout << "Length cuts (degrees): ("<<minlength<<","<<maxlength<<")" << endl;
+  cout << "Width cuts (degrees): ("<<minwidth<<","<<maxwidth<<")" << endl;
+  cout << "maxX and maxY upper cut (degrees): " << maxXY << endl;
+  cout << "***********" << endl << endl;
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/programs/falsesource.datacard
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/falsesource.datacard	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/falsesource.datacard	(revision 9772)
@@ -0,0 +1,53 @@
+
+// Maximun number of on and off events to be processed)
+NEVENTS 99999999
+
+// On-data file name pattern
+ONFILES  ./srcPosPrueba.root
+
+// Off-data file name pattern
+OFFFILES ./srcPosOffPrueba.root
+
+// output file name
+OUTFILE  ./rotateprueba2.root
+
+// rotation flag:
+//  0: Do not rotate
+//  1: Do rotate
+ROTFLAG 1
+
+// source coordinates (RA DEC in rads)
+SRCCOORDS 1.46 0.384
+
+// Flag to determine whether source position is absolute (0) or relative to previous position (1)
+// In case SRCABS=1, no rotation is carried out
+SRCABS 1 
+
+// Width of examined field (degrees)
+FIELD 2
+
+// Number of source positions in one direction (total grid positions BINNING*BINNING)
+BINNING 11
+
+// Number of bins in alpha plots
+NBIN 18
+
+
+//////////
+// CUTS //
+//////////
+
+// Size cut (lower and upper) in # of photons
+SIZECUT   2000   9999999
+
+// Dist cut (lower and upper) in degrees
+DISTCUT   0.2   1.1
+
+// Width cut (lower and upper) in degrees
+WIDTHCUT  0  0.12
+
+// Length cut (lower and upper) in degrees
+LENGTHCUT  0  0.26
+
+// maxX and maxY upper cut in degrees
+CENTERCUT  1.1 
Index: /tags/Mars-V0.9/mtemp/mifae/programs/makeHillas.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/makeHillas.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/makeHillas.cc	(revision 9772)
@@ -0,0 +1,874 @@
+/*********************************/
+/* Compute the hillas parameters */
+/*********************************/
+
+#include "TString.h"
+#include "TArrayS.h"
+#include "TFile.h"
+#include "TH1.h"
+#include "TH2.h"
+#include "TProfile.h"
+
+#include "MArray.h"
+#include "MParContainer.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MPedestalCam.h"
+#include "MBadPixelsCam.h"
+#include "MBadPixelsTreat.h"
+#include "MReadMarsFile.h"
+#include "MReadReports.h"
+#include "MGeomApply.h"
+#include "MPedCalcPedRun.h"
+#include "MEvtLoop.h"
+#include "MGeomCamMagic.h"
+#include "MExtractedSignalCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationRelTimeCam.h"
+#include "MExtractor.h"
+#include "MExtractFixedWindow.h"
+#include "MExtractFixedWindowPeakSearch.h"
+#include "MExtractSlidingWindow.h"
+#include "MExtractTimeAndChargeSpline.h"
+#include "MPedCalcFromLoGain.h"
+#include "MExtractSignal.h"
+#include "MCalibrationChargeCalc.h"
+#include "MFCosmics.h"
+#include "MContinue.h"
+#include "MLog.h"
+#include "MCerPhotEvt.h"
+#include "MPedPhotCam.h"
+#include "MArrivalTime.h"
+#include "MCalibrateData.h"
+#include "MPedPhotCalc.h"
+#include "MHillas.h"
+#include "MNewImagePar.h"
+#include "MRawRunHeader.h"
+#include "MSrcPosCam.h"
+#include "MImgCleanStd.h"
+#include "MHillasSrcCalc.h"
+#include "MHillasCalc.h"
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimeCalc2.h"
+#include "MIslands.h"
+#include "MImgIsland.h"
+#include "MIslandsCalc.h"
+#include "MIslandsClean.h"
+#include "MWriteRootFile.h"
+#include "MArgs.h"
+#include "MRunIter.h"
+#include "MJPedestal.h"
+#include "MJCalibration.h"
+#include "MHillasDisplay.h"
+#include "MF.h"
+#include "MContinue.h"
+#include "MReportDrive.h"
+#include "MTopology.h"
+#include "MTopologyCalc.h"
+#include "MRanForest.h"
+#include "MRanTree.h"
+#include "MRanForestCalc.h"
+#include "MRanForestFill.h"
+#include "MPointingPos.h"
+#include "MPointingPosCalc.h"
+#include "MImageParDisp.h"
+#include "MDispParameters.h"
+#include "MDispCalc.h"
+#include "MHDisp.h"
+#include "MFillH.h"
+
+#include "TApplication.h"
+#include "TClass.h"
+
+#include <iostream>
+#include <fstream>
+#include <stdlib.h>
+
+using namespace std;
+
+Bool_t readDatacards(TString& filename);
+void makeHillas();
+
+
+// declaration of variables read from datacards
+TString  outname;
+const TString outpath = "./";
+TString  idirname;
+TString  filter;
+TString  psfilename("makehillas.ps");
+TString  bpfilename;
+MRunIter pedcaliter;
+MRunIter caliter;
+MRunIter datiter;
+UInt_t   display   = 0;
+ULong_t  nmaxevents= 999999999;
+Short_t  calflag   = 1;
+Bool_t   caltimeflag   = kFALSE;
+Short_t  cleanflag   = 1;
+UShort_t lrings     = 1;
+Float_t  lcore     = 3.0;
+Float_t  ltail     = 1.5;
+Int_t    islflag   = 0;
+Int_t    topflag   = 0;
+Float_t  lnew      = 40;
+Int_t    kmethod   = 1;
+Int_t    kalgorithm = 1;
+Int_t    nfiles    = 0;
+Int_t    hifirst = 0;
+Int_t    hilast  = 14;
+Int_t    lofirst = 2;
+Int_t    lolast  = 14;
+Int_t    wsize   = 6;
+Int_t    sext    = 0;
+TString  rffilename;
+TString  dispfilename;
+
+const TString defaultcard="makehillas.datacard";
+char* chext[4]={"Fixed window","Sliding window","Peak Search","Spline"};
+/*************************************************************/
+static void Usage()
+{
+  gLog <<endl;
+  gLog << "Usage is:" << endl;
+  gLog << "   makeHillas [-h] [-?] <datacards>" << endl << endl;
+  gLog << "     <datacards>: datacards file name (dafault makehillas.datacards)" << endl;
+  gLog << "     -?/-h: This help" << endl << endl;
+}
+/*************************************************************/
+int main(int argc, char **argv)
+{
+  // create a TApplication to be able to 
+  TApplication app("Application",0,0);
+
+  // to deal correctly with the streamer
+  MArray::Class()->IgnoreTObjectStreamer();
+  MParContainer::Class()->IgnoreTObjectStreamer();
+
+  // evaluate arguments
+  MArgs arg(argc, argv);
+  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+      Usage();
+      return -1;
+    }
+
+  TString datacard  = arg.GetArgumentStr(0);
+  if(!datacard.Length())
+    datacard = defaultcard;
+
+  if(!readDatacards(datacard))
+    {
+      cout << "Error reading datacards. Stoping" << endl;
+      return -1;
+    }
+
+  makeHillas();
+}
+
+/*************************************************************/
+void makeHillas()
+{
+  // Set the signal extractor
+  MExtractor* extractor;
+  switch(sext)
+    {
+    case 0:
+      extractor = new MExtractFixedWindow();
+      break;
+    case 1:
+      extractor = new MExtractSlidingWindow();
+      ((MExtractSlidingWindow*)extractor)->SetWindowSize(wsize,wsize);
+      break;
+    case 2:
+      extractor = new MExtractFixedWindowPeakSearch();
+      ((MExtractFixedWindowPeakSearch*)extractor)->SetWindows(wsize,wsize,4);
+      break;
+    case 3:
+      extractor = new MExtractTimeAndChargeSpline();
+      ((MExtractTimeAndChargeSpline*)extractor)->SetTimeType(MExtractTimeAndChargeSpline::kHalfMaximum);
+      ((MExtractTimeAndChargeSpline*)extractor)->SetChargeType(MExtractTimeAndChargeSpline::kIntegral);      
+      ((MExtractTimeAndChargeSpline*)extractor)->SetRiseTime((Float_t)wsize*0.25); 
+      ((MExtractTimeAndChargeSpline*)extractor)->SetFallTime((Float_t)wsize*0.75);
+      break;
+    default:
+      extractor = new MExtractFixedWindow();
+      break;
+    }
+
+  extractor->SetRange(hifirst,hilast,lofirst,lolast);
+ 
+
+  /****************************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION FOR CALIBRATION */
+  /****************************************************/
+  
+  // If you want to exclude pixels from the beginning, read 
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)  
+  //badcam.AsciiRead("badpixels.dat");
+  MBadPixelsCam badcam;
+  MGeomCamMagic geomcam;
+  MGeomApply      geomapl;
+  badcam.InitSize(geomcam.GetNumPixels());
+
+  if(bpfilename.Length()>0)
+    {
+      ifstream fin("/home/emma/Mars/mtemp/mifae/programs/badpixels.dat");
+      badcam.AsciiRead((istream&)fin);
+      badcam.Print();
+    }
+  
+  
+  MJPedestal pedloop1;
+  MJPedestal pedloop2;
+  MJCalibration calloop;
+
+  if(calflag>0)
+    {
+      pedloop1.SetInput(&pedcaliter);
+      pedloop1.SetExtractor(extractor);
+      pedloop1.SetBadPixels(badcam);
+     pedloop1.SetNoStorage();
+      if (!pedloop1.Process())
+	return;
+
+      if (extractor->InheritsFrom("MExtractTimeAndCharge"))
+        {
+          
+          /***********************************************************/
+          /* NEEDED FOR SECOND LOOP: EXTRACTOR RESOLUTION COMPUTATION */
+          /***********************************************************/
+          pedloop2.SetNoStorage();
+          pedloop2.SetExtractor(extractor); 
+	  pedloop2.SetBadPixels(pedloop1.GetBadPixels());
+	  pedloop2.SetPedestals(pedloop1.GetPedestalCam());  
+          pedloop2.SetInput(&pedcaliter);
+          
+          if (!pedloop2.Process())
+            return;
+          
+          calloop.SetExtractorCam(pedloop2.GetPedestalCam());
+        }
+    }
+
+  MPedestalCam& pedcammean = pedloop1.GetPedestalCam();      
+  extractor->SetPedestals(&pedcammean);
+
+  MPedestalCam pedcamrms;
+
+
+  /*****************************/
+  /* SECOND LOOP: CALIBRATION  */
+  /*****************************/        
+
+  calloop.SetRelTimeCalibration(caltimeflag);
+  calloop.SetExtractor(extractor);
+  calloop.SetInput(&caliter);
+  calloop.SetBadPixels(pedloop1.GetBadPixels());
+  if(calflag==2)
+    calloop.SetUseBlindPixel();
+  if(calflag>0)
+    if (!calloop.Process(pedcammean))
+      return;
+
+  MCalibrationChargeCam &chargecam = calloop.GetCalibrationCam();
+  chargecam.Print();
+
+  /************************************************************************/
+  /*                THIRD (SMALL) LOOP TO GET INITIAl PEDESTALS          */
+  /************************************************************************/      
+  MParList  plist3;
+  MTaskList tlist3;
+    
+  plist3.AddToList(&tlist3);
+  plist3.AddToList(&geomcam);
+  plist3.AddToList(&pedcammean);
+  
+  //tasks
+  MReadMarsFile read3("Events");
+  static_cast<MRead&>(read3).AddFiles(datiter); 
+  read3.DisableAutoScheme();
+  
+  MPedCalcFromLoGain pedlo1;
+  pedlo1.SetPedestalUpdate(kFALSE);
+  const Float_t win = extractor->GetNumHiGainSamples();
+  pedlo1.SetExtractWindow(15, (UShort_t)TMath::Nint(win));
+  pedlo1.SetNumEventsDump(500);
+  pedlo1.SetMaxSignalVar(40);
+  pedlo1.SetPedestalsOut(&pedcammean);
+  
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&pedlo1);
+  
+  // Create and setup the eventloop
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+  if (!evtloop3.Eventloop(500))
+    return;
+  
+  tlist3.PrintStatistics();
+
+
+  /************************************************************************/
+  /*                 FOURTH LOOP TO READ THE RANDOM FOREST FILE(S)         */
+  /************************************************************************/      
+  MParList   plistrf;
+  MTaskList  tlistrf;
+  MRanForest ranforest;
+  MRanTree   rantree;
+
+  if(rffilename.Length())
+    {
+      plistrf.AddToList(&tlistrf);
+      plistrf.AddToList(&ranforest);
+      plistrf.AddToList(&rantree);
+
+      MReadTree readrf("Tree",rffilename);
+      readrf.DisableAutoScheme();
+      
+      MRanForestFill rffill;
+      rffill.SetNumTrees(100);
+      
+      tlistrf.AddToList(&readrf);
+      tlistrf.AddToList(&rffill);
+      
+      MEvtLoop evtlooprf;
+      evtlooprf.SetParList(&plistrf);
+      if (!evtlooprf.Eventloop())
+	return;
+      
+      tlistrf.PrintStatistics();
+    }
+  
+  /************************************************************************/
+  /*       FIFTH LOOP: PEDESTAL+DATA CALIBRATION INTO PHOTONS             */
+  /************************************************************************/
+  
+  MParList  plist5;
+  MTaskList tlist5;
+  plist5.AddToList(&tlist5);
+  
+  //tasks
+  //      MReadMarsFile read5("Events");
+  MReadReports read5;
+  read5.AddTree("Drive");
+  read5.AddTree("Events","MTime.",kTRUE);
+  
+  read5.AddFiles(datiter);
+  read5.AddToBranchList("MReportDrive.*");
+  read5.AddToBranchList("MRawEvtData.*");
+  read5.AddToBranchList("MRawEvtHeader.*");
+  
+  //      read5.DisableAutoScheme();
+  //      static_cast<MRead&>(read5).AddFiles(datiter); 
+  tlist5.AddToList(&read5);
+  tlist5.AddToList(&geomapl);
+  tlist5.AddToList(&pedlo1);
+  pedlo1.SetPedestalUpdate(kTRUE);
+  
+  MCalibrateData::CalibrationMode_t calMode=MCalibrateData::kDefault;  
+  if(calflag==0)
+    calMode=MCalibrateData::kNone;
+  if(calflag==-1)
+    calMode=MCalibrateData::kDummy;
+  MCalibrateData  photcalc;
+  photcalc.SetCalibrationMode(calMode);
+  photcalc.EnablePedestalType(MCalibrateData::kRun);
+  photcalc.EnablePedestalType(MCalibrateData::kEvent);
+  photcalc.SetPedestalCamMean(&pedcammean);
+  
+  if (extractor->InheritsFrom("MExtractTimeAndCharge"))
+    {
+      /************************************************************************/
+      /*                 SIXTH (SMALL) LOOP TO GET INITIAl PEDESTALS RMS     */
+      /************************************************************************/      
+      MParList  plist4;
+      MTaskList tlist4;
+      
+      plist4.AddToList(&tlist4);
+      plist4.AddToList(&geomcam);
+      plist4.AddToList(&pedcamrms);
+
+      //tasks
+      MReadMarsFile read4("Events");
+      static_cast<MRead&>(read4).AddFiles(datiter); 
+      read4.DisableAutoScheme();
+      
+      MPedCalcFromLoGain pedlo2;
+      pedlo2.SetPedestalUpdate(kFALSE);
+      pedlo2.SetExtractor((MExtractTimeAndCharge*)extractor);
+      pedlo2.SetNumEventsDump(500);
+      pedlo2.SetMaxSignalVar(40);
+      pedlo2.SetPedestalsIn(&pedcammean);
+      pedlo2.SetPedestalsOut(&pedcamrms);
+      
+      tlist4.AddToList(&read4);
+      tlist4.AddToList(&geomapl);
+      tlist4.AddToList(&pedlo2);
+      
+      // Create and setup the eventloop
+      MEvtLoop evtloop4;
+      evtloop4.SetParList(&plist4);
+      if (!evtloop4.Eventloop(500))
+	return;
+      
+      tlist4.PrintStatistics();
+      
+      tlist5.AddToList(&pedlo2);
+      pedlo2.SetPedestalUpdate(kTRUE);
+      
+      photcalc.SetPedestalCamRms(&pedcamrms);
+    }
+  
+  // containers 
+  MCerPhotEvt     nphot;
+  MPedPhotCam     nphotrms;
+  MArrivalTime    arrtime;
+  MHillas         hillas;
+  MNewImagePar    newimagepar;
+  MSrcPosCam      source;
+  MRawRunHeader   runhead;      
+  MArrivalTimeCam timecam;      
+  MReportDrive    reportdrive;
+  // islands
+  MIslands      isl;
+  MIslands      isl2;
+  MIslands      isl3;
+  MTopology     topology;
+
+  // disp
+  // (read in optimum Disp parameter values)  
+  MDispParameters dispin;
+  TArrayD dispPar;
+  if(dispfilename.Length())
+    {
+      TFile inparam(dispfilename);
+      dispin.Read("MDispParameters");
+      cout << "Optimum parameter values taken for calculating Disp : " << endl;
+
+      dispPar =  dispin.GetParameters();
+      for (Int_t i=0; i<dispPar.GetSize(); i++)
+	cout << dispPar[i] << ",  ";
+      cout << endl;
+      
+      inparam.Close();
+    }
+  // Disp results container
+  MImageParDisp imagepardisp;
+  // Disp histograms
+  MHDisp hdisp;
+  hdisp.SetName("MHDispAsym");
+  hdisp.SetSelectedPos(4);
+  MFillH filldisp("MHDispAsym[MHDisp]", "");
+  
+  isl.SetName("MIslands");  
+  isl2.SetName("MIslands2");
+  isl3.SetName("MIslands3");
+  
+  plist5.AddToList(&timecam);
+  plist5.AddToList(&isl);
+  
+  if (islflag == 2)
+    plist5.AddToList(&isl2);
+  if (islflag == 3)
+    plist5.AddToList(&isl3);
+  
+  plist5.AddToList(&geomcam);
+  plist5.AddToList(&pedcammean);
+  plist5.AddToList(&calloop.GetCalibrationCam());
+  plist5.AddToList(&calloop.GetQECam());
+  plist5.AddToList(&calloop.GetRelTimeCam());
+  plist5.AddToList(&calloop.GetBadPixels());
+  plist5.AddToList(&nphot);
+  plist5.AddToList(&nphotrms);
+  plist5.AddToList(&arrtime);
+  plist5.AddToList(&source);
+  plist5.AddToList(&hillas);
+  plist5.AddToList(&newimagepar);
+  plist5.AddToList(&runhead);
+  plist5.AddToList(&reportdrive);
+  plist5.AddToList(&topology);
+  plist5.AddToList(&rantree);
+  plist5.AddToList(&ranforest);
+  if(dispfilename.Length())
+    {
+      plist5.AddToList(&dispin);  
+      plist5.AddToList(&imagepardisp);
+      plist5.AddToList(&hdisp);
+    }
+
+  // cuts
+  MF cut(filter);
+  
+  MImgCleanStd      clean(lcore,ltail);
+  clean.SetCleanRings(lrings);
+  MImgCleanStd::CleaningMethod_t cleanMeth= MImgCleanStd::kStandard;  
+  if(cleanflag==2)
+    cleanMeth=MImgCleanStd::kDemocratic;
+  clean.SetMethod(cleanMeth);
+  
+  MArrivalTimeCalc2 timecalc;
+  MIslandsCalc       island;
+  island.SetOutputName("MIslands");
+  island.SetAlgorithm(kalgorithm);
+  
+  MBadPixelsTreat   interpolatebadpixels;
+  interpolatebadpixels.SetUseInterpolation();
+  interpolatebadpixels.SetProcessPedestal();
+  
+  MIslandsClean      islclean(lnew);
+  islclean.SetInputName("MIslands");
+  islclean.SetMethod(kmethod);
+  
+  MIslandsCalc       island2;
+  island2.SetOutputName("MIslands2");  
+  island2.SetAlgorithm(kalgorithm);
+  
+  MIslandsCalc       island3;
+  island3.SetOutputName("MIslands3");  
+
+  MRanForestCalc hadrcalc;
+  
+  MHillasCalc       hcalc;
+  MHillasSrcCalc    csrc1;
+
+  MTopologyCalc     topcalc;
+  
+  MPointingPosCalc  pointingposcalc;
+  MDispCalc         dispcalc;  
+
+  MContinue applycut(&cut);
+  applycut.SetInverted(kTRUE);
+  MWriteRootFile write(outname,"RECREATE");
+  
+  MHillasDisplay*  disphillas=NULL;
+  
+  write.AddContainer("MHillas"        , "Parameters");
+  write.AddContainer("MHillasSrc"     , "Parameters");
+  write.AddContainer("MHillasExt"     , "Parameters");
+  write.AddContainer("MNewImagePar"   , "Parameters");
+  write.AddContainer("MRawEvtHeader"  , "Parameters");
+  write.AddContainer("MRawRunHeader"  , "Parameters");
+  write.AddContainer("MTime"          , "Parameters");
+  write.AddContainer("MConcentration" , "Parameters");
+  write.AddContainer("MSrcPosCam"     , "Parameters");
+  write.AddContainer("MIslands"       , "Parameters");
+  write.AddContainer("MReportDrive"   , "Parameters");
+  write.AddContainer("MTopology"      , "Parameters");
+  write.AddContainer("MPointingPos"   , "Parameters");
+  write.AddContainer("MImagePar"      , "Parameters");
+  if(rffilename.Length())
+    write.AddContainer("MHadronness",     "Parameters");
+  if(dispfilename.Length())
+    write.AddContainer("MImageParDisp"  , "Parameters");
+  if (islflag == 2) 
+    write.AddContainer("MIslands2" , "Parameters");
+  if (islflag == 3) 
+    write.AddContainer("MIslands3" , "Parameters");
+  
+      
+  if(display)
+    {
+      disphillas = new MHillasDisplay(&nphot,&geomcam);
+      disphillas->SetIslandsName("MIslands");
+      if (islflag == 2)
+	disphillas->SetIslandsName("MIslands2");
+      if (islflag == 3)
+	disphillas->SetIslandsName("MIslands3");
+    }      
+  
+  tlist5.AddToList(extractor);
+  tlist5.AddToList(&timecalc);
+  tlist5.AddToList(&photcalc);
+  if(calflag==11 || calflag==21)
+    tlist5.AddToList(&interpolatebadpixels);
+  tlist5.AddToList(&clean);
+  tlist5.AddToList(&island);
+  
+  if (islflag == 2)
+    {
+      tlist5.AddToList(&islclean);
+      tlist5.AddToList(&island2);
+    }
+  
+  if (islflag == 3)
+    {
+      tlist5.AddToList(&islclean);
+      tlist5.AddToList(&island3);
+    }
+  
+  tlist5.AddToList(&hcalc);
+  tlist5.AddToList(&csrc1);
+  if(filter.Length())
+    tlist5.AddToList(&applycut);
+  if(topflag>0)
+    tlist5.AddToList(&topcalc);
+  if(rffilename.Length())
+    tlist5.AddToList(&hadrcalc);
+  tlist5.AddToList(&pointingposcalc);
+  if(dispfilename.Length())
+    {
+      tlist5.AddToList(&dispcalc);
+      tlist5.AddToList(&filldisp);
+    } 
+  tlist5.AddToList(&write);
+  if(display)
+    {
+      disphillas->SetPSFile();
+      disphillas->SetPSFileName(psfilename);
+      if(display==2) 
+	disphillas->SetPause(kFALSE);	
+      tlist5.AddToList(disphillas);
+    }
+  
+  // Create and setup the eventloop
+  MEvtLoop datloop;
+  datloop.SetParList(&plist5);
+  
+  cout << "*************************************************************" << endl;
+  cout << "***   COMPUTING DATA USING EXTRACTED SIGNAL (IN PHOTONS)  ***" << endl;
+  cout << "*************************************************************" << endl;
+  
+  if (!datloop.Eventloop(nmaxevents))
+    return;
+  
+  tlist5.PrintStatistics();    
+  delete extractor;
+}
+  //-------------------------------------------------------------------------------
+
+Bool_t readDatacards(TString& filename)
+{
+  ifstream ifun(filename.Data());
+  if(!ifun)
+    {
+      cout << "File " << filename << " not found" << endl;
+      return kFALSE;
+    }
+
+  TString word;
+  
+  while(ifun >> word)
+    {
+      // skip comments
+      if(word[0]=='/' && word[1]=='/')
+	{
+	  while(ifun.get()!='\n'); // skip line
+	  continue;
+	}
+
+      // number of events
+      if(strcmp(word.Data(),"NEVENTS")==0)
+	ifun >> nmaxevents;
+
+
+      // input file directory
+      if(strcmp(word.Data(),"IDIR")==0)
+	{
+	  if(idirname.Length())
+	    cout << "readDataCards Warning: overriding input directory file name" << endl;
+	  ifun >> idirname;
+	}
+
+
+      // pedestal runs for calibration
+      if(strcmp(word.Data(),"PCRUNS")==0)
+	{
+	  if(pedcaliter.GetNumRuns())
+	    cout << "readDataCards Warning: adding pedestal runs for calibration to the existing list" << endl;
+	  ifun >> word;
+	  pedcaliter.AddRuns(word.Data(),idirname.Data());
+	}
+
+      // calibration runs
+      if(strcmp(word.Data(),"CRUNS")==0)
+	{
+	  if(caliter.GetNumRuns())
+	    cout << "readDataCards Warning: adding calibration runs to the existing list" << endl;
+	  ifun >> word;
+	  caliter.AddRuns(word.Data(),idirname.Data());
+	}
+
+      // data runs
+      if(strcmp(word.Data(),"DRUNS")==0)
+	{
+	  if(datiter.GetNumRuns())
+	    cout << "readDataCards Warning: adding data runs to the existing list" << endl;
+	  ifun >> word;
+	  datiter.AddRuns(word.Data(),idirname.Data());
+	}
+      
+      // output file name
+      if(strcmp(word.Data(),"OUTFILE")==0)
+	{
+	  if(outname.Length())
+	    cout << "readDataCards Warning: overriding output file name" << endl;
+	  ifun >> outname;
+	}
+
+      // exclusion cut
+      if(strcmp(word.Data(),"FILTER")==0)
+	{
+	  if(filter.Length())
+	    cout << "readDataCards Warning: overriding existing cut" << endl;
+	  
+	  char ch;
+	  while((ch=ifun.get())!='\n')
+	    filter.Append(ch);	  
+	}
+
+      // display flag
+      if(strcmp(word.Data(),"DISPLAY")==0)
+	ifun >> display;
+
+      // ps file name
+      if(strcmp(word.Data(),"PSFILENAME")==0)
+	ifun >> psfilename;
+
+      // excluded pixels file name
+      if(strcmp(word.Data(),"BADPIXELFILE")==0)
+	ifun >> bpfilename;
+
+      // calibration flag
+      if(strcmp(word.Data(),"CALFLAG")==0)
+	ifun >> calflag;
+
+      // calibration flag
+      if(strcmp(word.Data(),"CALTIME")==0)
+	ifun >> caltimeflag;
+
+      // cleaning level
+      if(strcmp(word.Data(),"CLEANLEVEL")==0)
+	{
+	  ifun >> lcore;
+	  ifun >> ltail;
+	  if(ifun.get()!='\n'){
+	    ifun.unget();
+	    ifun >> lrings;
+	    if(ifun.get()!='\n'){
+	      ifun.unget();
+	      ifun >> cleanflag;
+	    }
+	  }
+	}
+
+      // random forest file name
+      if(strcmp(word.Data(),"RANFOREST")==0)
+	{
+	  if(rffilename.Length())
+	    cout << "readDataCards Warning: overriding random forest file name" << endl;
+	  ifun >> rffilename;
+	}
+      
+      // disp file name
+      if(strcmp(word.Data(),"DISP")==0)
+	{
+	  if(dispfilename.Length())
+	    cout << "readDataCards Warning: overriding disp file name" << endl;
+	  ifun >> dispfilename;
+	}
+
+      // cleaning level
+      if(strcmp(word.Data(),"EXTRACTOR")==0)
+	ifun >> sext >> hifirst >> hilast >> lofirst >> lolast >> wsize;
+      
+      if(strcmp(word.Data(),"TOPFLAG")==0)
+	ifun >> topflag;
+
+      if(strcmp(word.Data(),"ISLFLAG")==0)
+	{
+	  ifun >> islflag;
+
+	  // if (islflag == 1 || islflag == 2)
+	    ifun >> kalgorithm;
+	}
+
+      // island cleaning 
+      if (islflag == 2){
+	if(strcmp(word.Data(),"ISLANDCLEAN")==0)
+	  {
+	    ifun >> kmethod;
+	    ifun >> lnew;
+	  }
+      }
+    }
+
+  pedcaliter.Reset();
+  caliter.Reset();
+  datiter.Reset();
+  TString pfile;
+
+  // Dump read values
+  cout << "************************************************" << endl;
+  cout << "* Datacards read from file " << filename << endl;
+  cout << "************************************************" << endl;
+  cout << "Pedestal file (s) for calibration: "  << endl;
+  while(!(pfile=pedcaliter.Next()).IsNull())
+    cout << pfile << endl;
+  cout << "Calibration file (s): "  << endl;
+  while(!(pfile=caliter.Next()).IsNull())
+    cout << pfile << endl;
+  cout << "Warning: Pedestals for data will be computed from data themselves" << endl;
+  cout << "Data file (s): "  << endl;
+  while(!(pfile=datiter.Next()).IsNull())
+    cout << pfile << endl;
+  cout << "Maximum number of events: " << nmaxevents << endl;
+  if(filter.Length())
+    cout << "Applying selection cut: " << filter << endl;
+  cout << "Output file name: " << outname << endl;
+  if(display)
+    cout << "Generating PS file: " << psfilename << endl;
+  if(bpfilename.Length())
+    cout << "Bad pixels will be read from " << bpfilename << endl;
+  cout << "Signal Extractor: " << chext[sext] << " with bounds ("<<hifirst<<","<<hilast<<","<<lofirst<<","<<lolast<<"), window size " << wsize << endl;
+  cout << "Calibration: ";
+  if(calflag==0)    
+    cout << "Pixel area proportional intercalibration (kNone)" << endl;
+  else if(calflag==-1)    
+    cout << "No calibration whatsoever" << endl;
+  else if(calflag==1)
+    cout << "Default calibration" << endl;
+  else if(calflag==11)
+    cout << "Default calibration + bad pixels interpolation" << endl;
+  cout << "Cleaning level: ("<<lcore<<","<<ltail<<") - " << lrings << "ring" << endl;
+  cout << "Cleaning method: "<< cleanflag << endl;
+  if(rffilename.Length())
+    cout << "Random Forest will be read from " << rffilename << endl;
+  if(dispfilename.Length())
+    cout << "Disp parameters will be read from " << dispfilename << endl;
+  if (islflag == 1 || islflag == 2)
+    cout << "Island calcultation..." << "using algorithm #" << kalgorithm <<endl;
+  if (topflag > 0)
+    cout << "Topology parameters will be computed" << endl;
+  if (islflag == 2)
+    {
+      cout << "Island Cleaning: "<< kmethod <<" method  "<< lnew << " new threshold" << endl;
+    }
+  cout << "***********" << endl << endl;
+  
+  if(!pedcaliter.GetNumEntries() && calflag>0)
+    {
+      cout << "No pedestal file for calibration specified" << endl;
+      return kFALSE;
+    }
+  if(!caliter.GetNumEntries() && calflag>0)
+    {
+      cout << "No calibration file name specified" << endl;
+      return kFALSE;
+    }
+  if(!datiter.GetNumEntries())
+    {
+      cout << "No data file name specified" << endl;
+      return kFALSE;
+    }
+  if(!outname.Length())
+    {
+      cout << "No output file name specified" << endl;
+      return kFALSE;
+    }
+
+
+  return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mtemp/mifae/programs/makehillas.datacard
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/makehillas.datacard	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/makehillas.datacard	(revision 9772)
@@ -0,0 +1,94 @@
+/////////////////////////////////////////////////////////
+// Data card template for makeHillas executable        //
+//                                                     //
+// *** Compulsory cards are:                           //
+// PRUNS, CRUNS, DRUNS, OUTFILE                        //
+//                                                     //
+// the rest are optional                               //
+// *** Do NEVER add a datacard with no value after it  //
+/////////////////////////////////////////////////////////
+
+
+// Maximun number of (data) events to be processed)
+NEVENTS 9999999
+
+// data file directory
+IDIR /home/ona/link_data/ 
+
+// Pedestal (PRUNS), calibration (CRUNS) and data runs (DRUNS), e.g 1500-23444,25444,25455-26544
+// if PRUNS 0, take pedestals from low gains
+PCRUNS 45469
+CRUNS  45470
+DRUNS 45220-45223,45228-45231,45233-45236,45238,45383-45386,45388-45390,45392-45394,45396-45398,45495-45498,45500
+
+// output file name
+// OUTFILE ~/magic/mars/mars/hillasCrab/crab20040215OnA.root
+OUTFILE /home/rico/magic/hillasFiles/hillasCrab_200411_new.root
+
+
+// Selection cut. 
+// Condition "==" not supported.
+// Enclose all conditions between brakets, like: "(x<y) && (z<5)"
+// (see MF description class for more details)
+FILTER (MNewImagePar.fNumUsedPixels<400)
+
+// Display flag 
+// DISPLAY 0 will simply produce the hillas parameters files
+// DISPLAY 1 will show event display and produce ps file
+// DISPLAY 2 will produce the ps files, no display
+DISPLAY 0
+
+// PS file name
+PSFILENAME makehillas.ps
+
+// If want to include a file with a list of bad pixels, add next word
+// followed by the name of the file (provide the whole path)
+BADPIXELFILE /home/emma/Mars/mtemp/mifae/programs/badpixels.dat
+
+// Signal extractor, higain first, higainlast, logainfirst, logainlast, window size
+// signal extractors: 0 fixed window, 1 sliding window, 2 peak search, 3 spline
+EXTRACTOR 3 1 11 3 14 2
+
+// calibration flag:
+// -1: kDummy
+//  0: kNone
+//  1: kDefault(F factor)
+//  2: kDemocratic
+// 11: kDefault(F factor) + bad pixel interpolation
+// 21: kDemocratic + bad pixel interpolation
+CALFLAG 11
+
+// calibration time:
+//   0: kFALSE (no time calibration)
+//   1: kTRUE  (time calibration)
+CALTIME 1
+
+
+// Cleaning level (tail cut, boundary cut, number of rings, cleaning method - 1=standard, 2=democratic)
+CLEANLEVEL 4.0 3.5 1 1
+
+// Add the following word if you want to include Hadronness calculation, 
+// followed by the name of the Random Forest file
+RANFOREST /home/rico/magic/mars/mtemp/mifae/programs/RFstd.root
+
+// Add the following word if you want to apply DISP method analysis, 
+// followed by the name of the file where the MDispParameters container
+// with the optimal values of the DISP parameters is stored
+DISP /home/rico/magic/mars/mtemp/mifae/programs/DISPstd_inv1pluswl_Spline.root
+
+//Island calculations
+// 0  same as 1                1:normal algorithm 
+// 1  islands w/o cleaning     2:alternative algorithm
+// 2  islands  w  cleaning
+ISLFLAG 0 1
+
+// island cleaning:
+// 0: timing method     val:0.2, 0.3, 0.5... 
+// 1: no timing method  val: 40, 50, 60...
+ISLANDCLEAN 1 40
+
+// topology flag
+// 0: do not calculate topology parameters
+// 1: calculate topology parameters
+TOPFLAG 1
+
Index: /tags/Mars-V0.9/mtemp/mifae/programs/optimizeCuts.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/optimizeCuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/optimizeCuts.cc	(revision 9772)
@@ -0,0 +1,357 @@
+////////////////////////////////////////////////////////////////////////////////////
+//
+//             _____ Optimize cuts _____
+//
+//  Take as input root files with hillas parameters and compute the optimal cuts by
+//  mapping the width/length plane (only upper cuts so far)
+//
+//                 Jose Flix    <jflix@ifae.es>
+//                 Javier Rico  <jrico@ifae.es>
+////////////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <iostream>
+
+#include "TString.h"
+#include "TChain.h"
+#include "TH1F.h"
+
+#include "MArgs.h"
+#include "MLog.h"
+
+using namespace std;
+
+Bool_t readDatacards(TString& filename);
+void optimizeCuts();
+
+
+//-----------------------------------------------------------------------------
+// declaration of variables read from datacards
+//-----------------------------------------------------------------------------
+
+TString  onFile;
+TString  offFile;
+TString  outputFile;
+ULong_t  nmaxevents=999999999;
+Float_t  lowdistcut=0;
+Float_t  uppdistcut=10;
+Float_t  lowsizecut=1800;
+Float_t  uppsizecut=1800;
+Int_t    nsizebins=1;
+UInt_t   onRate=1;
+Float_t  lowlgcut=0.01;
+Float_t  upplgcut=0.3;
+Float_t  lgstep=0.005;
+Float_t  lowwdcut=0.01;
+Float_t  uppwdcut=0.3;
+Float_t  wdstep=0.005;
+
+//-----------------------------------------------------------------------------
+// constants
+//-----------------------------------------------------------------------------
+
+const TString defaultcard="optimizecuts.datacard";
+const Float_t conver   = 189./0.6; // conversion factor degrees to mm
+const Int_t nbins=18; //number of bins in alpha plots
+const Float_t frontiere=20.; // [deg] value below (above) wich signal (background is computed (normalized)
+
+//-----------------------------------------------------------------------------
+
+static void Usage()
+{
+  gLog <<endl;
+  gLog << "Usage is:" << endl;
+  gLog << "   optimizeCuts [-h] [-?] <datacards>" << endl << endl;
+  gLog << "     <datacards>: datacards file name (default " << defaultcard <<")" << endl;
+  gLog << "     -?/-h: This help" << endl << endl;
+}
+
+//-----------------------------------------------------------------------------
+int main(int argc, char **argv)
+{
+  // evaluate arguments
+  MArgs arg(argc, argv);
+  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+      Usage();
+      return -1;
+    }
+
+  TString datacard  = arg.GetArgumentStr(0);
+  if(!datacard.Length())
+    datacard = defaultcard;
+
+  if(!readDatacards(datacard))
+    {
+      cout << "Error reading datacards. Stoping" << endl;
+      return -1;
+    }
+  optimizeCuts();
+}
+
+//-----------------------------------------------------------------------------
+void optimizeCuts()
+{
+  // create the TChains for ON and OFF data
+  TChain* ton= new TChain("Parameters");
+  TChain* toff= new TChain("Parameters");
+  if(!ton->Add(onFile))
+    {
+      cout << "On-data file not found or not valid format" << endl;
+      return;
+    }
+  if(!toff->Add(offFile))
+    {
+      cout << "Off-data file not found or not valid format" << endl;
+      return;
+    }
+
+  ofstream fout;
+  fout.open(outputFile.Data());
+
+  // define aliases
+  ton->SetAlias("length","MHillas.fLength*0.6/189");
+  ton->SetAlias("width","MHillas.fWidth*0.6/189");
+  //ton->SetAlias("length","MHillas.fLength");
+  //ton->SetAlias("width","MHillas.fWidth");
+  ton->SetAlias("dist","MHillasSrc.fDist*0.6/189");
+  ton->SetAlias("conc","MNewImagePar.fConc");
+  ton->SetAlias("size","MHillas.fSize");
+  ton->SetAlias("event","MRawEvtHeader.fDAQEvtNumber");
+  ton->SetAlias("alpha","abs(MHillasSrc.fAlpha)");
+  ton->SetAlias("leak","MNewImagePar.fInnerLeakage1");
+  
+  toff->SetAlias("length","MHillas.fLength*0.6/189");
+  toff->SetAlias("width","MHillas.fWidth*0.6/189");
+  //toff->SetAlias("length","MHillas.fLength");
+  //toff->SetAlias("width","MHillas.fWidth");
+  toff->SetAlias("dist","MHillasSrc.fDist*0.6/189");
+  toff->SetAlias("conc","MNewImagePar.fConc");
+  toff->SetAlias("size","MHillas.fSize");
+  toff->SetAlias("event","MRawEvtHeader.fDAQEvtNumber");
+  toff->SetAlias("alpha","abs(MHillasSrc.fAlpha)");
+  toff->SetAlias("leak","MNewImagePar.fInnerLeakage1");
+
+
+  // general cut
+  char gencut[256];
+  char evecut[256];
+  sprintf(evecut,"event%%%d==0",onRate);
+  sprintf(gencut,"dist>%f && dist<%f",lowdistcut,uppdistcut);
+  cout << "General cut " << gencut << " (" << evecut << " for on-data)" << endl;
+
+  Bool_t isDiff = kFALSE;
+  if(nsizebins<0)
+    {
+      nsizebins*=-1;
+      isDiff=kTRUE;
+    }
+  else
+    nsizebins+=1;
+
+  // loop on size, width and length cuts
+  for(Int_t isb=0;isb<nsizebins;isb++) // loop on size
+    {      
+      cout << isb << endl;      
+      Float_t minsize = isDiff ? 
+	TMath::Power(10,TMath::Log10(lowsizecut)+isb*(TMath::Log10(uppsizecut)-TMath::Log10(lowsizecut))/nsizebins) :
+	TMath::Power(10,TMath::Log10(lowsizecut)+isb*(TMath::Log10(uppsizecut)-TMath::Log10(lowsizecut))/(nsizebins-1));
+      Float_t maxsize = isDiff ? TMath::Power(10,TMath::Log10(lowsizecut)+(isb+1)*(TMath::Log10(uppsizecut)-TMath::Log10(lowsizecut))/nsizebins) : 9999999999.;
+      
+      Float_t length=lowlgcut;
+      while(length<=upplgcut) // loop on length
+	{
+	  Float_t width=lowwdcut;
+	  while(width<=uppwdcut) // loop on width
+	    {
+	      TH1F* onhisto  = new TH1F("OnHist" ,"Alpha Plot",nbins,0,90);
+	      TH1F* offhisto = new TH1F("OffHist","Alpha Plot",nbins,0,90);    
+	      
+	      // define the width/length cut
+	      char varcut[256];
+	      sprintf(varcut,"size>%f && size<%f && length<%f && width<%f",minsize,maxsize,length,width);
+	      cout << "Cutting " << varcut << endl;
+	      
+	      // define the on/off data cut
+	      char offcut[1024];
+	      sprintf(offcut,"%s && %s",gencut,varcut);
+	      char oncut[1024];
+	      sprintf(oncut,"%s && %s",evecut,offcut);
+	      
+	      // Fill the histos
+	      ton->Draw("alpha>>OnHist",oncut);
+	      toff->Draw("alpha>>OffHist",offcut);
+	      
+	      // Normalize histos
+	      const Int_t inibin = (Int_t)(frontiere/90.*nbins+1);
+	      Float_t level=0;
+	      Float_t leveloff=0;
+	      for(Int_t ibin = inibin; ibin<=nbins;ibin++)
+		{
+		  level+=onhisto->GetBinContent(ibin);
+		  leveloff+=offhisto->GetBinContent(ibin);
+		}
+	      offhisto->Sumw2(); // needed to compute correct errors after normalization
+	      const Float_t norm = leveloff ? level/leveloff: 1;
+	      cout << "Normalizing by factor " << norm <<endl;
+	      offhisto->Scale(norm);    
+	      
+	      // compute significance/excess
+	      Float_t sig=0,bg=0,esig=0,ebg=0;
+	      Float_t significance=0;
+	      const Int_t signbins = inibin-1;
+	      for(Int_t ibin = 1; ibin<=signbins;ibin++)
+		{
+		  sig  += onhisto->GetBinContent(ibin);
+		  esig += onhisto->GetBinError(ibin)*onhisto->GetBinError(ibin);
+		  bg   += offhisto->GetBinContent(ibin);
+		  ebg  += offhisto->GetBinError(ibin)*offhisto->GetBinError(ibin);
+		}
+	      Float_t error= TMath::Sqrt(esig+ebg);
+	      significance = error ? (sig-bg)/error : 0; 
+	      
+	      cout << "Excess: " << sig-bg << endl;
+	      cout << "N bkg: "  << bg << endl; 
+	      cout << "Significance: " << significance << endl;	  
+	      
+	      // save the result in file
+	      fout << minsize << '\t' 
+		   << maxsize << '\t' 
+		   << width << '\t' 
+		   << length << '\t'
+		   << sig-bg << '\t'
+		   << significance << '\t' << endl;
+	      
+	      delete onhisto;
+	      delete offhisto;
+	      
+	      width+=wdstep;
+	    }
+	  length+=lgstep;
+	}
+    }
+  fout.close();
+}
+//-----------------------------------------------------------------------
+  
+Bool_t readDatacards(TString& filename)
+{
+  ifstream ifun(filename.Data());
+  if(!ifun)
+    {
+      cout << "File " << filename << " not found" << endl;
+      return kFALSE;
+    }
+
+  TString word;
+  
+  while(ifun >> word)
+    {
+      // skip comments
+      if(word[0]=='/' && word[1]=='/')
+	{
+	  while(ifun.get()!='\n'); // skip line
+	  continue;
+	}
+      
+      // number of events
+      if(strcmp(word.Data(),"NEVENTS")==0)
+	ifun >> nmaxevents;
+      
+      // number of events
+      if(strcmp(word.Data(),"ONRATE")==0)
+	ifun >> onRate;
+      
+      // input file name (on data)
+      if(strcmp(word.Data(),"ONFILES")==0)
+	{
+	  if(onFile.Length())
+	    cout << "readDataCards Warning: overriding on-data file name" << endl;
+	  ifun >> onFile;
+	}
+
+      // input file name (off data)
+      if(strcmp(word.Data(),"OFFFILES")==0)
+	{
+	  if(offFile.Length())
+	    cout << "readDataCards Warning: overriding off-data file name" << endl;
+	  ifun >> offFile;
+	}
+
+      // output file name
+      if(strcmp(word.Data(),"OUTFILE")==0)
+	{
+	  if(outputFile.Length())
+	    cout << "readDataCards Warning: overriding output file name" << endl;
+	  ifun >> outputFile;
+	}
+
+      // size cuts
+      if(strcmp(word.Data(),"SIZECUTS")==0)
+	{
+	  ifun >> lowsizecut;
+	  ifun >> uppsizecut;
+	  ifun >> nsizebins;
+	}
+
+      // dist cuts
+      if(strcmp(word.Data(),"DISTCUTS")==0)
+	{
+	  ifun >> lowdistcut ; 
+	  ifun >> uppdistcut ; 
+	}
+
+      // length cuts
+      if(strcmp(word.Data(),"LENGTHCUTS")==0)
+	{
+	  ifun >> lowlgcut;
+	  ifun >> upplgcut;
+	  ifun >> lgstep;
+	}
+
+      // width cuts
+      if(strcmp(word.Data(),"WIDTHCUTS")==0)
+	{
+	  ifun >> lowwdcut;
+	  ifun >> uppwdcut;
+	  ifun >> wdstep;
+	}
+
+    }
+  
+  // check compulsory values
+  if(!onFile.Length())
+    {
+      cout << "No on-data file name specified" << endl;
+      return kFALSE;
+    }
+  
+  if(!offFile.Length())
+    {
+      cout << "No off-data file name specified" << endl;
+      return kFALSE;
+    }
+    
+  if(!outputFile.Length())
+    {
+      cout << "No output file name specified" << endl;
+      return kFALSE;
+    }
+
+  // Dump read values
+  cout << "************************************************" << endl;
+  cout << "* Datacards read from file " << filename << endl;
+  cout << "************************************************" << endl;
+  cout << "Maximum number of input events: " << nmaxevents << endl;
+  cout << "On-data acceptance rate: 1/" << onRate << endl;
+  cout << "On-data input file name(s): " << onFile << endl;
+  cout << "Off-data input file name(s): " << offFile << endl;
+  cout << "Output file name: " << outputFile << endl;
+  cout << "Dist cuts (deg): [" << lowdistcut<< ","<<uppdistcut<< "]" << endl;
+  cout << "Scanning size range: [" << lowsizecut << "," << uppsizecut << "]"<< " in " << nsizebins << " steps" << endl;
+  cout << "Scanning length range (deg): [" << lowlgcut<< ","<<upplgcut<< "], with step (deg): "<< lgstep << endl;
+  cout << "Scanning width range (deg): [" << lowwdcut<< ","<<uppwdcut<< "], with step (deg): "<< wdstep << endl;
+  cout << "***********" << endl << endl;
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/programs/optimizecuts.datacard
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/optimizecuts.datacard	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/optimizecuts.datacard	(revision 9772)
@@ -0,0 +1,43 @@
+/////////////////////////////////////////////////////////
+// Data card template for optimizeCuts executable      //
+//                                                     //
+// *** Compulsory cards are:                           //
+// ONFILES, OFFFILES, OUTFILE                          //
+//                                                     //
+// the rest are optional                               //
+// *** Do NEVER add a datacard with no value after it  //
+/////////////////////////////////////////////////////////
+
+// Maximun number of on and off events to be processed)
+NEVENTS 9999999
+
+// On data acceptance rate (e.g 4 for taking 1/4 of whole data sample)
+ONRATE 3
+
+// Input file name pattern (On data)
+ONFILES  /mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/hillas/mrk20040215OnRotateNoCalB.root
+
+// Input file name pattern (Off data)
+OFFFILES  /mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/hillas/mrk20040215OffRotateA-C.root
+
+// output file name
+OUTFILE  ./prueba.out
+
+
+// Preliminary distance lower and upper cuts (in deg)
+DISTCUTS 0.3 1.2
+
+// Size initial, final and number of steps 
+// it will take logarithmic constant intervals
+// positive number of steps means lower cut (integral)
+// negative number of steps means lower and upper cuts (diferential)
+SIZECUTS  500 10000 3
+
+// Length initial, final and step values (in deg)
+LENGTHCUTS 0.15 0.35 0.1 
+
+// Width initial, final and step values (in deg)
+WIDTHCUTS 0.05 0.15 0.1 
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/programs/pedvsslices.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/pedvsslices.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/pedvsslices.cc	(revision 9772)
@@ -0,0 +1,253 @@
+#include "TString.h"
+#include "TMultiGraph.h"
+#include "TGraphErrors.h"
+#include "TStyle.h"
+#include "TCanvas.h"
+#include "TLegend.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MEvtLoop.h"
+#include "MPedCalcPedRun.h"
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include <iostream>
+#include <fstream>
+#include <stdlib.h>
+
+using namespace std;
+
+
+const UInt_t nmaxslice = 30;
+const UInt_t step = 2;
+
+void pedvsslices2(TString pedname);
+
+int main()
+//void pedvsslices()
+{
+  pedvsslices2("~markus/Magic/Soft/Mars/20040303_20123_P_NewCalBoxTestLidOpen_E.root");
+}
+
+void pedvsslices2(TString pedname)
+{
+  const Int_t nbad = 22;
+  Int_t bad[nbad]={0,10,47,54,124,125,159,162,222,300,388,395,464,558,559,543,89,510,576,459,550,561};
+
+  static const UInt_t rnmax   = (nmaxslice/step)*step;
+  static const UInt_t nslices = rnmax/step;
+  static const UInt_t nloops  = rnmax*(rnmax-step+2)/(2*step);
+
+  cout << "nslices = " << nslices << endl;
+
+  // general settings
+  gStyle->SetCanvasColor(0);
+  gStyle->SetStatColor(0);
+  gStyle->SetStatBorderSize(1);
+  gStyle->SetMarkerSize(0.6);
+  gStyle->SetPadBorderMode(0);
+
+  // Define the graphs and their atributes
+  TGraphErrors grmeanIn[nslices];
+  TGraphErrors grrmsIn[nslices];
+  TGraphErrors grmeanOut[nslices];
+  TGraphErrors grrmsOut[nslices];
+
+  // Null graph to adjust plot limits
+  Float_t nullx[rnmax+1];
+  Float_t nullyM[rnmax+1];
+  Float_t nullyR[rnmax+1];
+  for(UInt_t i=0;i<=rnmax;i++)
+    {
+      nullx[i]=(Float_t)i;
+      nullyM[i]=9+2./rnmax*i;
+      nullyR[i]=3.5+5./rnmax*i;
+    }
+  TGraph grnullM(rnmax+1,nullx,nullyM);
+  TGraph grnullR(rnmax+1,nullx,nullyR);
+  grnullM.SetMarkerSize(0);
+  grnullR.SetMarkerSize(0);
+  grnullM.SetMarkerColor(0);
+  grnullR.SetMarkerColor(0);
+  grnullM.GetXaxis()->SetTitle("First used time slice");
+  grnullR.GetXaxis()->SetTitle("First used time slice");
+  grnullM.GetYaxis()->SetTitle("Average Pedestal mean (ADC cnts)");
+  grnullR.GetYaxis()->SetTitle("Average Pedestal rms (ADC cnts)");
+
+  for(UInt_t i=0;i<nslices;i++)
+    {
+      grmeanIn[i].SetMarkerColor(i%9+1);
+      grrmsIn[i].SetMarkerColor(i%9+1);
+      grmeanOut[i].SetMarkerColor(i%9+1);
+      grrmsOut[i].SetMarkerColor(i%9+1);
+
+      grmeanIn[i].SetMarkerStyle(20+i%19+1);
+      grrmsIn[i].SetMarkerStyle(20+i%19+1);
+      grmeanOut[i].SetMarkerStyle(20+i%19+1);
+      grrmsOut[i].SetMarkerStyle(20+i%19+1);
+    }
+
+
+  // Fill the graphs
+  UInt_t islice=0;
+  UInt_t fslice=step-1;    
+  for(UInt_t i=0;i<nloops;i++)
+    {
+      MParList plist;
+      MTaskList tlist;
+      MPedestalCam pedcam;
+  
+      plist.AddToList(&tlist);
+      plist.AddToList(&pedcam);
+      
+      MReadMarsFile read("Events", pedname);
+      read.DisableAutoScheme();
+      MGeomApply     geomapl;
+      MPedCalcPedRun pedcalc;
+      cout << "Checking slices from " << islice << " to " << fslice << endl;
+      pedcalc.SetRange(islice,fslice,0,0);
+      pedcalc.SetWindowSize(fslice-islice+1);
+
+      tlist.AddToList(&read);
+      tlist.AddToList(&geomapl);
+      tlist.AddToList(&pedcalc);
+      
+      MEvtLoop evtloop;
+      evtloop.SetParList(&plist);
+      if (!evtloop.Eventloop())
+	return;
+
+      // compute the pedestal mean and rms averaged in the camera
+      Float_t meansumIn =0;
+      Float_t meansum2In=0;
+      Float_t rmssumIn  =0;
+      Float_t rmssum2In =0;
+      Float_t meansumOut =0;
+      Float_t meansum2Out=0;
+      Float_t rmssumOut  =0;
+      Float_t rmssum2Out =0;
+
+      const Int_t ninn = 397;
+      Int_t rninn=0;
+      Int_t rnout=0;
+      for(Int_t j=0;j<pedcam.GetSize();j++)
+	{
+	  // skip bad pixels from list above
+	  Bool_t isBad=kFALSE;
+	  for(Int_t k=0;k<nbad;k++)
+	    if(bad[k]==j)
+	      {
+		isBad=kTRUE;
+		break;
+	      }
+	  if(isBad)
+	    continue;
+
+	  // keep the sum of values and of squares
+	  Float_t ped = pedcam[j].GetPedestal();
+	  Float_t rms = pedcam[j].GetPedestalRms();
+	  if(j<ninn)
+	    {
+	      meansumIn+= ped;
+	      meansum2In+=ped*ped;
+	      rmssumIn+=rms;
+	      rmssum2In+=rms*rms;
+	      rninn++;
+	    }
+	  else
+	    {
+	      meansumOut+= ped;
+	      meansum2Out+=ped*ped;
+	      rmssumOut+=rms;
+	      rmssum2Out+=rms*rms;
+	      rnout++;
+	    }	    
+	}
+      
+      Float_t avmeanIn  = meansumIn/rninn;
+      Float_t sigmeanIn = (meansum2In-meansumIn*meansumIn/rninn)/(rninn-1);
+      Float_t avrmsIn   = rmssumIn/rninn;
+      Float_t sigrmsIn  = (rmssum2In-rmssumIn*rmssumIn/rninn)/(rninn-1);
+       
+      Float_t avmeanOut  = meansumOut/rnout;
+      Float_t sigmeanOut = (meansum2Out-meansumOut*meansumOut/rnout)/(rnout-1);
+      Float_t avrmsOut   = rmssumOut/rnout;
+      Float_t sigrmsOut  = (rmssum2Out-rmssumOut*rmssumOut/rnout)/(rnout-1);
+      
+      // save the values into the graphs
+      grmeanIn[(fslice-islice+1)/step-1].SetPoint(islice,islice,avmeanIn);
+      grmeanIn[(fslice-islice+1)/step-1].SetPointError(islice,0,sigmeanIn/rninn);
+      grmeanOut[(fslice-islice+1)/step-1].SetPoint(islice,islice,avmeanOut);
+      grmeanOut[(fslice-islice+1)/step-1].SetPointError(islice,0,sigmeanOut/rnout);
+
+      grrmsIn[(fslice-islice+1)/step-1].SetPoint(islice,islice,avrmsIn);
+      grrmsIn[(fslice-islice+1)/step-1].SetPointError(islice,0,sigrmsIn/rninn);
+      grrmsOut[(fslice-islice+1)/step-1].SetPoint(islice,islice,avrmsOut);
+      grrmsOut[(fslice-islice+1)/step-1].SetPointError(islice,0,sigrmsOut/rnout);
+
+      // compute next initial and final slice values
+      islice++;
+      fslice++;
+      if(fslice>=nmaxslice)
+	{
+	  fslice=fslice-islice+step;
+	  islice=0;
+	}
+    }
+
+  TCanvas* myC = new TCanvas("myC","pedestal studies",900,1250);
+  myC->Divide(2,2);
+
+  TLegend* leg1 = new TLegend(.2,.2,.4,.5);
+  TLegend* leg2 = new TLegend(.44,.2,.88,.5);
+  leg1->SetEntrySeparation(0.1);
+  leg1->SetHeader("");
+  leg2->SetEntrySeparation(0.1);
+  leg2->SetHeader("");
+
+  myC->cd(1);
+  grnullM.SetTitle("Average pedestal mean for inner pixels");
+  grnullM.DrawClone("AP");
+  for(UInt_t i=0;i<nslices;i++)
+    {      
+      grmeanIn[i].DrawClone("P");
+      char leglab[100];
+      sprintf(leglab,"%d slices",(i+1)*step);
+      if(i<nslices/2)
+	leg1->AddEntry(&grmeanIn[i],leglab,"p");
+      else
+	leg2->AddEntry(&grmeanIn[i],leglab,"p");
+    }
+  leg1->SetFillColor(0);
+  leg1->SetLineColor(0);
+  leg1->SetBorderSize(0);
+  leg1->Draw();
+  leg2->SetFillColor(0);
+  leg2->SetLineColor(0);
+  leg2->SetBorderSize(0);
+  leg2->Draw();
+
+  myC->cd(2);
+  grnullR.SetTitle("Average pedestal rms for inner pixels");
+  grnullR.DrawClone("AP");
+  for(UInt_t i=0;i<nslices;i++)
+    grrmsIn[i].DrawClone("P");
+  
+  myC->cd(3);
+  grnullM.SetTitle("Average pedestal mean for outer pixels");
+  grnullM.DrawClone("AP");
+  for(UInt_t i=0;i<nslices;i++)
+    grmeanOut[i].DrawClone("P");
+  
+  myC->cd(4);
+  grnullR.SetTitle("Average pedestal rms for outer pixels");
+  grnullR.DrawClone("AP");
+  for(UInt_t i=0;i<nslices;i++)
+    grrmsOut[i].DrawClone("P");
+
+  myC->Print("pedestaSliceDependence.ps");
+
+}
Index: /tags/Mars-V0.9/mtemp/mifae/programs/psffit.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/psffit.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/psffit.cc	(revision 9772)
@@ -0,0 +1,175 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 04/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+#include <iostream>
+#include <stdlib.h>
+
+#include <TString.h>
+#include <TArrayS.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MGeomCamMagic.h"
+#include "MCameraDC.h"
+#include "MPSFFit.h"
+
+#include "MReadReports.h"
+#include "MGeomApply.h"
+#include "MPSFFitCalc.h"
+#include "MEvtLoop.h"
+#include "MCalibrateDC.h"
+
+using namespace std;
+
+int main(int argc, char *argv[])
+{
+    if(argc!=2 && argc!=3) 
+      {
+        printf("\n usage: %s filename numberEnvents \n\n",argv[0]);
+        return 1;
+      }
+    
+    UInt_t len=strlen(argv[1]);
+    
+    if(argv[1][len] == '/')
+      {
+	argv[1][len]='\0';
+      }
+    
+    TString filename;
+    filename=argv[1];
+
+    UInt_t numEvents = 1000000;
+    if(argc == 3)
+      {
+	len=strlen(argv[2]);
+    
+	if(argv[2][len] == '/')
+	  {
+	    argv[2][len]='\0';
+	  }
+	
+	numEvents=atoi(argv[2]);
+      }
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MPSFFit       psffit;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&psffit);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddFile(filename);     // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+
+  MGeomApply geomapl;
+
+  TString continuoslightfile = 
+    "/nfs/magic/CaCodata/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root";
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+ 
+  const Int_t numrings = 3;
+  //  const Int_t numblind = 187;
+
+
+  // 2004_02_15
+  /*  const Int_t numblind = 28;
+  const Short_t x[numblind] = {  8, 224, 279, 339,
+			       433, 434, 435, 436, 437, 438, 439, 
+			       475, 476, 477, 478, 479, 480, 481, 482,
+			       523, 524, 525, 526, 527, 528, 529, 530, 531};
+  */
+  const Int_t numblind = 260;
+  Short_t x[numblind];
+
+  for (int i=0;i<246;i++)
+    x[i+14]=i+331;
+  x[0]=124;
+  x[1]=123;
+  x[2]=125;
+  x[3]=166;
+  x[4]=165;
+  x[5]=88;
+  x[6]=89;
+  x[7]=282;
+  x[8]=283;
+  x[9]=226;
+  x[10]=227;
+  x[11]=228;
+  x[12]=177;
+  x[13]=178;
+
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  MPSFFitCalc psfcalc;
+  //psfcalc.SetImgCleanMode(MPSFFitCalc::kRing);
+  psfcalc.SetImgCleanMode(MPSFFitCalc::kCombined);
+  psfcalc.SetNumRings(numrings);
+  psfcalc.SetBlindPixels(blindpixels);
+
+
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal, "Currents");
+  tlist.AddToList(&psfcalc, "Currents");
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  //
+  // Execute your analysis
+  //
+
+  if (!evtloop.Eventloop(numEvents))
+    return kFALSE;
+
+  //  tlist.PrintStatistics();
+
+  cout << "RUN " << psffit.GetMeanMinorAxis() << ' ' << psffit.GetSigmaMinorAxis() << ' ' <<  psffit.GetMeanMajorAxis()  << ' ' <<  psffit.GetSigmaMajorAxis() << ' ' << psffit.GetChisquare() << endl;
+  
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/programs/srcPos.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/srcPos.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/srcPos.cc	(revision 9772)
@@ -0,0 +1,362 @@
+////////////////////////////////////////////////////////////////////////////////////
+//
+//             _____ Source Position macro_____
+//
+//  Take as input root files with hillas parameters and recompute the ones depending
+//  on the source position for a new (input) position, optionally rotating it in an
+//  event by event basis. Output is a file with recomputed hillas parameters
+//
+//                 Ester Aliu   <aliu@ifae.es>
+//                 Oscar Blanch <blanch@ifae.es>
+//                 Javier Rico  <jrico@ifae.es>
+////////////////////////////////////////////////////////////////////////////////////
+
+#include <fstream>
+#include <iostream>
+
+#include "TString.h"
+
+#include "MHillasSrcCalc.h"
+#include "MHillasSrc.h"
+#include "MSrcRotate.h"
+#include "MSrcPosFromFile.h"
+#include "MSrcTranslate.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MHillas.h"
+#include "MReadTree.h"
+#include "MEvtLoop.h"
+#include "MLog.h"
+#include "MArgs.h"
+#include "MWriteRootFile.h"
+#include "MTime.h"
+#include "MControlPlots.h"
+#include "MIslands.h"
+#include "MArgs.h"
+
+using namespace std;
+
+Bool_t readDatacards(TString& filename);
+void srcPos();
+
+//-----------------------------------------------------------------------------
+// declaration of variables read from datacards
+//-----------------------------------------------------------------------------
+
+TString  inputFile;
+TString  offFile;
+TString  outputFile;
+TString  offOutputFile;
+ULong_t  nmaxevents=999999999;
+Float_t  xsrcpos=0.;
+Float_t  ysrcpos=0.;
+Double_t mjdpos=0;
+Bool_t   kRotating=0;
+Bool_t   kSrcPolicy=kFALSE;
+Double_t fRA= -1.;
+Double_t fDEC= -1.;
+TString  srcFile;
+TString  controlplotsfilename="controlplots.ps";
+
+//-----------------------------------------------------------------------------
+// constants
+//-----------------------------------------------------------------------------
+
+const TString defaultcard="srcpos.datacard";
+const Float_t conver   = 189./0.6; // conversion factor degrees to mm
+
+//-----------------------------------------------------------------------------
+
+static void Usage()
+{
+  gLog <<endl;
+  gLog << "Usage is:" << endl;
+  gLog << "   srcPos [-h] [-?] <datacards>" << endl << endl;
+  gLog << "     <datacards>: datacards file name (dafault " << defaultcard <<")" << endl;
+  gLog << "     -?/-h: This help" << endl << endl;
+}
+
+//-----------------------------------------------------------------------------
+int main(int argc, char **argv)
+{
+  // evaluate arguments
+  MArgs arg(argc, argv);
+  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+      Usage();
+      return -1;
+    }
+
+  TString datacard  = arg.GetArgumentStr(0);
+  if(!datacard.Length())
+    datacard = defaultcard;
+
+  if(!readDatacards(datacard))
+    {
+      cout << "Error reading datacards. Stoping" << endl;
+      return -1;
+    }
+
+  srcPos();
+}
+
+//-----------------------------------------------------------------------------
+void srcPos()
+{
+  // variable declaration  
+  Float_t xpos=xsrcpos*conver; // [mm]
+  Float_t ypos=ysrcpos*conver; // [mm] 
+  
+  // containers
+  MParList  plist;  
+  MTaskList tlist;
+  MIslands  islands;
+
+  // include containers in parameter list
+  plist.AddToList(&tlist);
+  plist.AddToList(&islands);
+	  	  
+  // tasks
+  MReadTree read("Parameters", inputFile);
+  read.DisableAutoScheme();  
+
+  MSrcTranslate   srctranslate;
+  MSrcRotate      srcrotate;
+  MSrcPosFromFile srcfromfile;
+
+  if(srcFile.Length())
+    {
+      srcfromfile.SetInputFileName(srcFile);
+      srcfromfile.SetMode(MSrcPlace::kOn);
+    }
+  else
+    {
+      srctranslate.SetTranslation(xpos,ypos);
+      srctranslate.SetRelativeTranslation(kSrcPolicy);
+      srctranslate.SetCreateHisto(kFALSE);
+      srcrotate.SetRAandDECandRefMJD(fRA,fDEC,mjdpos); 
+      srcrotate.SetMode(MSrcPlace::kOn);
+    }
+
+  MHillasSrcCalc csrc1;	  
+
+  MWriteRootFile write(outputFile,"RECREATE");
+  write.AddContainer("MHillas"       , "Parameters");
+  write.AddContainer("MHillasSrc"    , "Parameters");
+  write.AddContainer("MHillasExt"    , "Parameters");
+  write.AddContainer("MNewImagePar"  , "Parameters");
+  write.AddContainer("MRawEvtHeader" , "Parameters");
+  write.AddContainer("MRawRunHeader" , "Parameters");
+  write.AddContainer("MTime"          , "Parameters");
+  write.AddContainer("MConcentration" , "Parameters");
+  write.AddContainer("MSrcPosCam"     , "Parameters");
+  write.AddContainer("MIslands"       , "Parameters");
+  //write.AddContainer("MIslands2"     ,  "Parameters");
+
+  MControlPlots controlplots(controlplotsfilename);
+  controlplots.SetProduceFile(kFALSE);
+  
+  // include tasks in task list
+  tlist.AddToList(&read);
+  if(srcFile.Length())
+    tlist.AddToList(&srcfromfile);
+  else
+    {
+      tlist.AddToList(&srctranslate);
+      if(kRotating) 
+	tlist.AddToList(&srcrotate);  
+    }
+  tlist.AddToList(&csrc1);  
+  tlist.AddToList(&controlplots);
+  tlist.AddToList(&write);
+
+  // Eventloop
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  if (!evtloop.Eventloop(nmaxevents))
+    return;  
+ 
+  tlist.PrintStatistics();
+  
+  // do off-data if input file was specified
+  if(!offFile.Length())
+    return;
+
+  MReadTree read2("Parameters", offFile);
+  read2.DisableAutoScheme();  
+  tlist.AddToListBefore(&read2, &read, "All");
+  tlist.RemoveFromList(&read);
+
+  MWriteRootFile write2(offOutputFile,"RECREATE");
+  write2.AddContainer("MHillas"       , "Parameters");
+  write2.AddContainer("MHillasSrc"    , "Parameters");
+  write2.AddContainer("MHillasExt"    , "Parameters");
+  write2.AddContainer("MNewImagePar"  , "Parameters");
+  write2.AddContainer("MRawEvtHeader" , "Parameters");
+  write2.AddContainer("MRawRunHeader" , "Parameters");
+  write2.AddContainer("MTime"          , "Parameters");
+  write2.AddContainer("MConcentration" , "Parameters");
+  write2.AddContainer("MSrcPosCam"     , "Parameters");
+  write2.AddContainer("MIslands"       , "Parameters");
+  // write2.AddContainer("MIslands2"     ,  "Parameters");
+  tlist.AddToListBefore(&write2,&write,"All");
+  tlist.RemoveFromList(&write);
+
+  if(srcFile.Length())
+    srcfromfile.SetMode(MSrcPlace::kOff);
+  else
+    srcrotate.SetMode(MSrcPlace::kOff);
+
+  controlplots.SetMode(MControlPlots::kOff);
+  controlplots.SetProduceFile(kTRUE);
+
+  if (!evtloop.Eventloop(nmaxevents))
+    return;  
+
+  tlist.PrintStatistics();
+}
+//-----------------------------------------------------------------------
+  
+Bool_t readDatacards(TString& filename)
+{
+  ifstream ifun(filename.Data());
+  if(!ifun)
+    {
+      cout << "File " << filename << " not found" << endl;
+      return kFALSE;
+    }
+
+  TString word;
+  
+  while(ifun >> word)
+    {
+      // skip comments
+      if(word[0]=='/' && word[1]=='/')
+	{
+	  while(ifun.get()!='\n'); // skip line
+	  continue;
+	}
+      
+      // number of events
+      if(strcmp(word.Data(),"NEVENTS")==0)
+	ifun >> nmaxevents;
+
+      // input file name
+      if(strcmp(word.Data(),"INPUTFILES")==0)
+	{
+	  if(inputFile.Length())
+	    cout << "readDataCards Warning: overriding on-data file name" << endl;
+	  ifun >> inputFile;
+	}
+
+      // off-data file name
+      if(strcmp(word.Data(),"OFFFILES")==0)
+	{
+	  if(offFile.Length())
+	    cout << "readDataCards Warning: overriding off-data file name" << endl;
+	  ifun >> offFile;
+	}
+
+      // output file name
+      if(strcmp(word.Data(),"OUTFILE")==0)
+	{
+	  if(outputFile.Length())
+	    cout << "readDataCards Warning: overriding output file name" << endl;
+	  ifun >> outputFile;
+	}
+
+      // output file name (off data)
+      if(strcmp(word.Data(),"OFFOUTFILE")==0)
+	{
+	  if(offOutputFile.Length())
+	    cout << "readDataCards Warning: overriding output file name for off data" << endl;
+	  ifun >> offOutputFile;
+	}
+
+      // source position input file
+      if(strcmp(word.Data(),"SRCFILE")==0)
+	{
+	  if(srcFile.Length())
+	    cout << "readDataCards Warning: overriding source-position file name" << endl;
+	  ifun >> srcFile;
+	}
+
+      // source position
+      if(strcmp(word.Data(),"SRCPOS")==0)
+	{
+	  ifun >> xsrcpos;
+	  ifun >> ysrcpos;	  
+	  ifun >> mjdpos;
+	}
+
+      // source celestial coordinates 
+      if(strcmp(word.Data(),"SRCCOORDS")==0)
+	{
+	  ifun >> fRA;
+	  ifun >> fDEC;	  
+	}
+
+      // source movement policy flag
+      if(strcmp(word.Data(),"SRCABS")==0)
+	ifun >> kSrcPolicy;	  
+
+      // rotation flag
+      if(strcmp(word.Data(),"ROTFLAG")==0)
+	ifun >> kRotating;
+    }
+  
+  // check compulsory values
+  if(!inputFile.Length())
+    {
+      cout << "No on-data file name specified" << endl;
+      return kFALSE;
+    }
+
+  if(!outputFile.Length())
+    {
+      cout << "No output file name specified" << endl;
+      return kFALSE;
+    }
+
+  if(offFile.Length() && !offOutputFile.Length())
+    {
+      cout << "No output file name specified for off data" << endl;
+      return kFALSE;
+    }
+
+  if(xsrcpos==0 && ysrcpos==0)
+    {
+      cout << "Source position is center of the camera (as in input file)" << endl;
+      return kFALSE;
+    }
+
+  MTime thetime(mjdpos);
+
+  // Dump read values
+  cout << "************************************************" << endl;
+  cout << "* Datacards read from file " << filename << endl;
+  cout << "************************************************" << endl;
+  cout << "Maximum number of input events: " << nmaxevents << endl;
+  cout << "Input file name(s): " << inputFile << endl;
+  if(offFile.Length())
+    cout << "Input file name(s) for off data: " << offFile << endl;
+  cout << "Output file name: " << outputFile << endl;
+  if(offFile.Length())
+    cout << "Output file name for off data: " << offOutputFile << endl;
+  if(srcFile.Length())
+    cout << "Reading source position from file " << srcFile << endl;
+  else
+    {
+      cout << "Source position (degrees) X=" << xsrcpos << ", Y="<<ysrcpos;
+      if(kSrcPolicy)
+	cout << " (RELATIVE TO INITIAL SOURCE POSITION)";
+      else
+	cout << " (ABSOLUTE POSITION IN THE CAMERA)";
+      cout << ", at " << thetime.GetSqlDateTime() << endl;
+      cout << "De-rotation flag " << kRotating << endl;
+      cout << "Source celestial coordiantes (rad): RA = " << fRA << ", DEC = " << fDEC << endl;
+    }
+  cout << "***********" << endl << endl;
+
+  return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mifae/programs/srcpos.datacard
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/programs/srcpos.datacard	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/programs/srcpos.datacard	(revision 9772)
@@ -0,0 +1,37 @@
+
+// Maximun number of on and off events to be processed)
+NEVENTS 9999999
+
+// Input file name pattern (wildcards allowed)
+INPUTFILES /mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/hillas/crab20040215OnCal*.root
+
+// Specify optionally the name of OFF-data files you want to apply the same source position distribution to
+OFFFILES  /mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/hillas/crab20040215OffCal*.root
+
+// output file name (on data)
+OUTFILE  /mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/hillas/crab20040215OnRotateCalA-D.root
+
+// output file name (off data)
+OFFOUTFILE /mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/hillas/crab20040215OffRotateCalA-H.root
+
+// X and Y position of the source (degrees) for a MJ date (days) -important only in case of rotation
+SRCPOS  0.3  0.1   53049.89
+
+// Flag to determine whether source position is absolute (0) or relative to previous position (1)
+SRCABS 0
+
+// rotation flag:
+//  0: Do not rotate
+//  1: Do rotate 
+ROTFLAG 1
+
+// source coordinates (RA DEC in rads)
+SRCCOORDS 1.46 0.384 // (Crab)
+// SRCCOORDS 2.899 0.667   // (Mrk 421)
+
+
+// File containing source position as a function of run number (invalidates SRCPOS, SRCABS, ROTFLAG and SRCCOORDS values)
+// SRCFILE /mnt/users/jrico/magic/mars/Mars_Standard02/mtemp/mifae/programs/20040215_Mrk421.B.pos
+
+
+
Index: /tags/Mars-V0.9/mtemp/mifae/scripts/makeHillas.sh
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/scripts/makeHillas.sh	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/scripts/makeHillas.sh	(revision 9772)
@@ -0,0 +1,142 @@
+#!/bin/bash
+# Author: Javi Lopez <jlopez@ifae.es>
+# Update: 2004/05/23
+# Description: Run the makeHillas program grouping
+#              the data files with the preavious
+#              pedestal run.
+
+
+STARTDATE=$(date)
+
+#--DATACARD INFO--
+NEVENTS=999999999
+CALFLAG=1
+CLEANLEVEL1=3.0
+CLEANLEVEL2=1.5
+ISLFLAG=0
+ISLANDCLEAN1=1
+ISLANDCLEAN2=40
+SLOWCRT=1
+HVCONFFILE=/mnt/users/jlopez/Mars/Files4Mars/Config/HVSettings_FF35q.conf
+CLFILE=/local_disk/CaCoData/rootdata/Miscellaneous/Period016/2004_04_16/dc_2004_04_16_04_46_18_22368_Off3c279-2CL100.root
+#------------------
+
+MARSPATH=/mnt/users/jlopez/Mars/Mars
+MACRO=makeHillas.C
+#BIN=makeHillas
+CARD=input.datacard
+
+LOCALDIR=$(pwd)
+cd ${MARSPATH}
+
+DATAPATH=/local_disk/Data/rootdata/Mrk421/Period016/2004_04_21
+RUNS=$(ls ${DATAPATH} | gawk -F_ '{print $2}')
+#RUNS='22999 23000'
+echo RUNS ${RUNS}
+PRUNS=$(ls ${DATAPATH} | grep _P_ | gawk -F_ '{print $2}')
+#PRUNS='23209 22990'
+
+#CRUN=$(ls ${DATAPATH} | grep _C_ | gawk -F_ '{print $2}')
+CRUN=23207
+echo CRUN ${CRUN}
+
+#Look for the closer pedestal run for the calibration
+MINDIST=99999
+for PRUN in ${PRUNS}
+do
+  DIST=$[${PRUN}-${CRUN}]
+  if [ ${DIST} -lt "0" ]; then
+   DIST=$[-${DIST}]
+  fi
+#  echo PRUN ${PRUN}
+#  echo DIST ${DIST}
+  if [ ${DIST} -lt ${MINDIST} ]; then
+    PRUNFORCAL=${PRUN}
+    MINDIST=${DIST}
+  fi
+done
+echo PRUNFORCAL ${PRUNFORCAL}
+ 
+FIRSTPRUN=$(echo ${PRUNS} | gawk '{print $1}')
+for RUN in ${RUNS}
+do
+  RUNTYPE=$(ls ${DATAPATH} | grep ${RUN} | gawk -F_ '{print $3}')
+  if [ ${RUNTYPE} == "P" ]; then
+     if [  ${RUN} != ${FIRSTPRUN} ]; then
+        if [ ! -z $(echo ${DRUNS} | gawk '{print $1}')  ]; then
+#          echo PRUN ${PRUN}
+#          echo DRUNS ${DRUNS} [${FIRSTDRUN}-${LASTDRUN}]
+          DATE=$(ls ${DATAPATH} | grep ${PRUN} | gawk -F_ '{print $1}')
+          SOURCE=$(ls ${DATAPATH} | grep ${PRUN} | gawk -F_ '{print $4}')
+          #produce the datacard and run makeHillas
+          echo "NEVENTS ${NEVENTS}" > ./${CARD}
+          echo "IDIR ${DATAPATH}" >> ./${CARD}
+          echo "PCRUNS ${PRUNFORCAL}" >> ./${CARD}
+          echo "CRUNS ${CRUN}" >> ./${CARD}
+          echo "PRUNS ${PRUN}" >> ./${CARD}
+          echo "DRUNS ${FIRSTDRUN}-${LASTDRUN}" >> ./${CARD}
+          echo "OUTFILE ${DATE}_C_${CRUN}_P_${PRUN}_D_${FIRSTDRUN}-${LASTDRUN}_${SOURCE}_H.root" >>  ./${CARD}
+          echo "CALFLAG ${CALFLAG}" >> ./${CARD}
+          echo "CLEANLEVEL ${CLEANLEVEL1} ${CLEANLEVEL2}" >> ./${CARD}
+          echo "ISLFLAG ${ISLFLAG}"  >> ./${CARD}
+          echo "ISLANDCLEAN ${ISLANDCLEAN1} ${ISLANDCLEAN2}" >> ./${CARD}
+          echo "SLOWCRT ${SLOWCRT}"  >> ./${CARD}
+          echo "HVCONFFILE ${HVCONFFILE}"  >> ./${CARD}
+          echo "CLFILE ${CLFILE}" >> ./${CARD} 
+	  echo "Produced datacard for makeHillas"
+          cat ./${CARD}
+          root -b -q ${MARSSYS}/mtemp/mifae/macros/${MACRO}
+          rm ./${CARD}
+
+	  mv *_H.root ${LOCALDIR}
+        fi
+     fi
+     PRUN=${RUN}
+     DRUNS=""
+     FIRSTDRUN=""
+  else
+   if [ ${RUNTYPE} == "D" ]; then
+     if [ -z ${FIRSTDRUN} ]; then
+        FIRSTDRUN=${RUN}
+     fi
+     LASTDRUN=${RUN}
+     DRUNS="${DRUNS} ${RUN}"
+   fi
+  fi
+done
+
+if [ ! -z $(echo ${DRUNS} | gawk '{print $1}') ]; then
+#   echo PRUN ${PRUN}
+#   echo DRUNS ${DRUNS}  [${FIRSTDRUN}-${LASTDRUN}]
+
+  DATE=$(ls ${DATAPATH} | grep ${RUN} | gawk -F_ '{print $1}')
+  SOURCE=$(ls ${DATAPATH} | grep ${RUN} | gawk -F_ '{print $4}')
+  #produce the datacard and run makeHillas
+  echo "NEVENTS 99999999" > ./${CARD}
+  echo "IDIR ${DATAPATH}" >> ./${CARD}
+  echo "PCRUNS ${PRUNFORCAL}" >> ./${CARD}
+  echo "CRUNS ${CRUN}" >> ./${CARD}
+  echo "PRUNS ${PRUN}" >> ./${CARD}
+  echo "DRUNS ${FIRSTDRUN}-${LASTDRUN}" >> ./${CARD}
+  echo "OUTFILE ${DATE}_C_${CRUN}_P_${PRUN}_D_${FIRSTDRUN}-${LASTDRUN}_${SOURCE}_H.root" >>  ./${CARD}
+  echo "CALFLAG ${CALFLAG}" >> ./${CARD}
+  echo "CLEANLEVEL ${CLEANLEVEL1} ${CLEANLEVEL2}" >> ./${CARD}
+  echo "ISLFLAG ${ISLFLAG}"  >> ./${CARD}
+  echo "ISLANDCLEAN ${ISLANDCLEAN1} ${ISLANDCLEAN1}" >> ./${CARD}
+  echo "SLOWCRT ${SLOWCRT}"  >> ./${CARD}
+  echo "HVCONFFILE ${HVCONFFILE}"  >> ./${CARD}
+  echo "CLFILE ${CLFILE}" >> ./${CARD} 
+  echo "Last produced datacard for makeHillas"
+  cat ./${CARD}
+  root -b -q ${MARSSYS}/mtemp/mifae/macros/${MACRO}
+  rm ./${CARD}
+
+  mv *_H.root ${LOCALDIR}
+fi
+
+cd  ${LOCALDIR}
+
+STOPDATE=$(date)
+
+echo "STARTING DATE ${STARTDATE}"
+echo "STOPING  DATE ${STOPDATE}"
Index: /tags/Mars-V0.9/mtemp/mifae/scripts/srcPosRun.sh
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/scripts/srcPosRun.sh	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/scripts/srcPosRun.sh	(revision 9772)
@@ -0,0 +1,28 @@
+#!/bin/bash
+
+DCFILESPATH=/nfs/magic/CaCodata/2004_03_19
+SOURCE=Mrk421
+BIN=./psffit
+
+DCFILES=$(ls ${DCFILESPATH}/*${SOURCE}*.root)
+#echo DCFILES ${DCFILES}
+
+echo RUN SRCX SRCY
+for DCFILE in ${DCFILES}
+do
+  DCFILE=${DCFILE//${DCFILESPATH}/.}
+  #echo DCFILE ${DCFILE}
+  RUN=${DCFILE:25:5}
+  #echo RUN ${RUN}
+  if [ RUN != '00000' ]; then
+      SRCPOS=$(./${BIN} ${DCFILESPATH}/${DCFILE} | tail -1)
+      #echo SRCPOS ${SRCPOS}
+      SRCX=$(echo ${SRCPOS} | gawk '{print $2}') 
+      SIGX=$(echo ${SRCPOS} | gawk '{print $3}') 
+      SRCY=$(echo ${SRCPOS} | gawk '{print $4}')
+      SIGY=$(echo ${SRCPOS} | gawk '{print $5}')
+      CHI2=$(echo ${SRCPOS} | gawk '{print $6}')
+      #echo ${RUN}  ${SRCX} ${SIGX} ${SRCY} ${SIGY} ${CHI2}
+      echo ${RUN} ${SRCX} ${SRCY}
+  fi
+done
Index: /tags/Mars-V0.9/mtemp/mifae/srcpositions/20040510_Mrk421.pos
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/srcpositions/20040510_Mrk421.pos	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/srcpositions/20040510_Mrk421.pos	(revision 9772)
@@ -0,0 +1,40 @@
+25791 -31.8904 -22.2868
+25793 -31.204 -25.1259
+25794 -30.8582 -26.1056
+25796 -30.8433 -27.315
+25800 -30.9893 -26.5873
+25801 -30.129 -28.5482
+25802 -30.0869 -29.0446
+25803 -29.6106 -29.6053
+25806 -29.5739 -30.2493
+25807 -29.1453 -30.803
+25811 -29.2426 -30.7231
+25812 -29.1423 -31.5773
+25813 -29.4705 -31.4197
+25814 -29.1459 -32.4534
+25816 -28.9612 -33.5763
+25817 -28.9655 -33.0914
+25819 -29.2206 -33.2739
+25820 -29.013 -33.6073
+25837 -23.6607 -37.5356
+25839 -23.2204 -38.3438
+25840 -23.2022 -38.145
+25842 -23.2352 -38.8685
+25843 -22.9597 -38.2165
+25845 -22.7618 -39.4373
+25846 -22.4334 -38.3265
+25848 -22.1283 -38.5474
+25850 -22.0476 -39.362
+25851 -21.3159 -38.6381
+25852 -20.51 -39.3704
+25854 -20.0418 -39.6989
+25855 -20.0536 -39.2094
+25858 -20.3918 -42.9825
+25860 -20.5511 -43.2302
+25861 -22.9288 -40.9434
+25862 -21.534 -43.0463
+25863 -23.9955 -41.2485
+25864 -23.6695 -42.2856
+25874 -23.8745 -43.3409
+25876 -20.2687 -43.5657
+25883 -24.6953 -42.6541
Index: /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_220404_pos.txt
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_220404_pos.txt	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_220404_pos.txt	(revision 9772)
@@ -0,0 +1,65 @@
+23203 49.2726 61.8901
+23204 41.693 83.1926
+23209 33.6331 88.5239
+23210 28.2513 92.6265
+23212 21.4295 96.1593
+23213 16.432 97.7467
+23216 0.550093 102.076
+23217 -8.98307 101.311
+23219 -19.9699 101.232
+23220 -48.3997 97.7073
+23222 -35.553 94.5315
+23223 -42.1249 90.7072
+23225 -49.72 87.585
+23226 -48.378 70.4774
+23229 -55.2906 60.7539
+23230 -56.1453 60.0578
+23232 -57.1738 52.706
+23233 -57.0943 47.5582
+23235 -63.7419 43.9618
+23236 -62.0881 37.9026
+23238 -73.589 36.2268
+23239 -70.8132 31.9569
+23241 -70.478 28.262
+23242 -69.6348 24.0415
+23244 -68.4586 20.6795
+23245 -67.2766 19.0235
+23250 -55.8484 0.194891
+23253 -53.7881 -3.28016
+23255 -52.8007 -4.84312
+23256 -51.2311 -6.88246
+23259 -48.3625 -9.56292
+23262 -45.6057 -11.7548
+23265 -43.3533 -13.5378
+23268 -44.4973 -14.4726
+23271 -43.343 -15.6643
+23273 -42.2395 -16.4098
+23275 -41.4118 -16.7661
+23278 -40.2932 -17.6661
+23279 -39.9929 -17.671
+23280 -39.711 -17.442
+23281 -39.0344 -18.3018
+23282 -38.4745 -18.2764
+23283 -35.0204 -18.1458
+23289 -34.7234 -20.9747
+23291 -34.1059 -22.5775
+23292 -34.7917 -21.5298
+23293 -33.2113 -22.229
+23294 -33.4358 -21.962
+23297 -32.7803 -21.0645
+23299 -31.8816 -21.61
+23300 -30.4907 -23.1672
+23301 -31.7465 -21.3046
+23302 -30.2575 -21.4706
+23303 -29.7285 -21.6212
+23304 -29.5768 -21.3276
+23305 -29.2646 -23.2172
+23306 -29.0006 -21.7169
+23307 -28.9752 -21.71
+23308 -29.1528 -21.6656
+23309 -28.5402 -21.0133
+23310 -28.6243 -21.7256
+23311 -29.0955 -21.5047
+23312 -29.5512 -22.1346
+23314 -29.679 -22.068
+23317 -30.901 -21.6827
Index: /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_april.pos
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_april.pos	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_april.pos	(revision 9772)
@@ -0,0 +1,326 @@
+20780 -61.6944 67.059
+20781 -64.6926 47.4227
+20783 -65.8374 43.1406
+20784 -66.6132 39.1829
+20786 -67.4031 35.7154
+20787 -66.244 32.1211
+20790 -65.9027 29.6755
+20791 -62.6377 59.1079
+20794 -65.6662 25.6452
+20795 -64.9428 22.9849
+20797 -64.1151 20.8169
+20798 -63.723 18.4919
+20800 -63.3643 16.6103
+20801 -63.1704 14.2815
+20804 -62.7876 13.6825
+20805 -62.4634 11.3297
+20806 -62.1662 9.6296
+20807 -60.0303 8.64362
+20808 -60.2703 0.509429
+20809 -59.386 -0.938021
+20811 -58.1121 -4.42333
+20812 -56.5063 -5.16089
+20813 -54.9194 -6.98546
+20814 -53.7668 -8.03962
+20818 -46.0907 -16.6877
+20819 -45.8623 -14.8199
+20820 -45.7539 -14.3919
+20821 -44.929 -16.358
+22245 10.2468 23.1621
+22249 25.85 25.9106
+22250 25.6546 29.1566
+22251 29.1613 25.4159
+22254 58.316 33.7302
+22255 37.5861 29.4664
+22257 57.9896 34.7069
+22258 61.9726 25.5081
+22260 81.5392 37.5373
+22261 70.6807 16.5722
+22264 58.1712 25.6161
+22266 66.3476 40.3227 
+22384 33.7108 44.2858
+22388 31.4939 45.9244
+22394 36.3619 47.3819
+22395 38.3426 48.5743
+22400 39.6094 48.8239
+22401 41.1102 50.745
+22406 42.1073 51.6704
+22407 43.8524 54.075
+22411 45.2629 54.7259
+22412 45.3289 58.2773
+22413 45.9415 58.2507
+22414 69.3919 87.317
+22429 52.0164 66.3798
+22439 45.8513 71.0317
+22440 45.5684 71.4425
+22450 43.789 74.1573
+22451 41.3883 76.8225
+22461 410.064 168.151
+22462 407.911 169.206
+22466 394.568 183.316
+22467 393.798 194.727
+22477 380.467 220.11
+22478 373.801 240.848
+22483 20.3671 101.709
+22484 14.4039 101.842
+22489 8.03032 103.608
+22490 0.0405639 104.229
+22495 289.384 348.55
+22496 255.487 359.161
+22503 -15.7097 106.418
+22504 -22.6365 102.47
+22511 -30.7607 100.265
+22512 -33.8572 100.537
+22516 -41.9986 100.456
+22517 -48.2052 90.4964
+22522 -65.668 42.6643
+22526 -65.0008 41.6949
+22527 -65.629 38.2615
+22531 -66.3627 35.6813
+22532 -67.0988 32.6288
+22534 -67.5101 30.7526
+22535 -66.7941 28.2758
+22538 -66.0013 26.5091
+22539 -65.0212 23.9648
+22541 -64.507 22.077
+22544 -63.4069 19.9872
+22558 276.466 -110.216
+22559 -263.554 -391.457
+22560 -284.903 -390.722
+22711 244.229 32.1922
+22717 587.4 109.335
+22718 53.802 53.875
+22719 44.9718 46.5444
+22720 48.771 45.2452
+22722 46.5953 51.4958
+22723 47.1241 57.9021
+22725 46.6285 59.6458
+22726 48.0192 62.5682
+22728 46.6808 63.3769
+22729 81.7319 131.281
+22731 41.5407 73.4151
+22732 38.9125 74.97
+22735 394.369 184.289
+22736 391.167 187.667
+22738 375.638 224.6
+22739 368.822 243.244
+22743 16.1032 94.8722
+22744 11.2596 95.7668
+22746 4.11151 98.6553
+22747 -5.51529 98.7573
+22749 258.705 353.641
+22750 228.989 359.292
+22752 -22.5239 97.8863
+22754 -25.7971 97.6711
+22755 -31.3562 96.3472
+22756 -35.3656 94.8347
+22757 -43.9467 89.2152
+22758 -54.7801 64.0827
+22763 -63.5534 45.2586
+22765 -64.7755 40.1216
+22766 -65.8142 38.821
+22768 -66.4905 35.2643
+22769 -67.0298 32.6377
+22810 -117.508 -441.851
+22811 -200.855 -401.565
+22962 40.604 36.4264
+22964 599.401 46.4693
+22965 63.519 44.8682
+22967 365.741 -0.122339
+22969 369.93 20.0097
+00000 300.355 -52.2264
+22970 280.213 -149.609
+22971 234.378 -216.905
+22973 254.659 189.151
+22974 101.128 -67.7792
+22976 47.8854 59.8481
+22977 47.2984 63.6432
+22979 46.9635 66.0826
+22980 44.1839 70.2999
+22982 43.3303 73.4819
+22983 37.8974 77.0181
+22985 395.191 176.371
+22986 393.522 190.227
+22988 390.085 162.713
+22989 375.7 224.23
+22995 259.366 357.751
+22996 223.73 362.435
+22998 -21.9336 102.655
+22999 -28.3336 97.6638
+23001 -44.8834 89.8799
+23002 -50.7141 85.5837
+23005 -60.7778 56.2697
+23008 -65.9688 42.2415
+23010 -66.5424 40.1167
+23011 -67.0799 36.9962
+23013 -67.3001 33.4055
+23014 -67.4957 32.6484
+23016 -67.5712 30.9981
+23017 -67.2629 28.5432
+23019 -66.3983 26.7778
+23020 -65.4753 24.7367
+23022 -64.1789 22.3838
+23023 -63.4728 20.7786
+23025 -60.7328 12.414
+23030 -57.9515 10.0549
+23031 -57.1479 7.4803
+23033 -53.4069 3.53683
+23035 -53.9728 -4.72199
+23036 -52.1748 -5.9891
+23037 -50.7731 -6.82306
+23038 -48.9648 -8.49934
+23041 -47.7019 -9.17361
+23042 -46.4665 -10.6739
+23044 -45.0935 -10.5075
+23045 -44.107 -12.1032
+23047 -43.4158 -11.1391
+23048 -43.0353 -13.1539
+23051 -42.7699 -12.5803
+23052 -42.1787 -13.5728
+23054 -41.6294 -13.8375
+23055 -41.2568 -14.0938
+23057 -290.439 250.263
+23062 -297.09 263.923
+23063 -298.562 260.606
+23065 -299.633 250.574
+23066 -300.793 248.678
+23069 -301.577 248.353
+23070 -305.353 240.577
+23072 -305.971 240.208
+23073 -308.467 237.252
+23076 -309.522 235.973
+23077 -308.17 235.072
+23081 -309.601 234.154
+23082 -307.69 232.974
+23084 -310.036 231.466
+23085 -310.173 229.806
+23086 -311.19 228.58
+23087 -311.67 226.48
+23088 -312.337 224.47
+23089 -313.102 222.753
+23091 -314.491 219.638
+23092 -315.423 219.455
+23093 -316.648 211.099
+23094 -317.449 216.1
+23096 -318.305 213.36
+23097 -319.057 212.771
+23098 -319.745 212.283
+00000 -319.947 211.413
+23099 -320.291 209.397
+23100 -320.67 210.915
+23101 -321.542 211.145
+23102 -322.189 209.441
+23104 -322.937 209.212
+23105 -323.247 207.812
+23107 -323.708 206.321
+23108 -323.338 200.837
+23203 45.1872 61.2712
+23204 394.129 182.738
+23209 376.848 222.488
+23210 91.4164 230.426
+23212 15.2987 98.4375
+23213 9.83596 100.328
+23216 -2.32038 104.881
+23217 -9.40899 104.143
+23219 245.469 359.594
+23220 219.868 376.786
+23223 143.542 397
+23225 130.714 401.776
+23226 125.609 404.129
+23229 -62.92 55.0264
+23230 -66.0427 47.7518
+23232 -67.3102 44.9688
+23233 -67.9107 41.3038
+23235 -68.3111 38.6037
+23236 -68.415 35.9021
+23238 -68.563 33.0559
+23239 -68.2589 29.757
+23241 -67.9479 28.7807
+23242 -67.3735 26.8282
+23244 -66.6344 25.2004
+23245 -66.0266 24.3683
+23278 -38.4621 -15.8849
+23279 -38.1683 -15.9046
+23280 -291.557 248.291
+23281 -295.06 263.191
+23282 -296.571 269.995
+23283 -297.366 266.598
+23286 -310.404 237.349
+23288 -311.872 235.932
+23289 -311.352 235.505
+23291 -305.265 238.91
+23292 -308.408 234.851
+23293 -310.426 224.93
+23294 -311.411 232.103
+23296 -312.035 231.051
+23297 -312.038 229.156
+23298 -312.824 228.12
+23299 -313.127 225.547
+23300 -313.222 222.556
+23301 -314.431 222.262
+23302 -315.148 220.916
+23303 -315.74 219.728
+23304 -316.556 218.823
+00000 -316.638 217.144
+23305 -316.76 217.022
+23306 -317.965 221.19
+23307 -318.97 214.2
+23308 -319.403 208.621
+23309 -320.184 206.064
+23310 -320.648 208.893
+23311 -322.682 215.685
+23312 -318.403 206.408
+23313 -599.997 13.1938
+23314 -59.0671 -27.9948
+23316 -234.741 196.301
+23317 -240.554 192.296
+23425 -66.5951 18.1945
+23426 -63.939 8.33197
+23427 -56.5394 -0.631792
+23428 -54.9475 -2.29846
+23442 -53.4959 -4.3676
+23443 -53.2873 -2.89022
+23449 -50.1898 -6.25351
+23450 -49.0202 -6.93665
+23464 -48.5527 -6.68196
+23465 -47.1345 -8.4623
+23479 -46.0659 -9.21844
+23480 -44.326 -9.73134
+23495 -43.4018 -9.54128
+23496 -41.9692 -10.3322
+23511 -286.402 284.23
+23512 -286.98 278.243
+23527 -290.011 278.777
+23528 -291.986 277.958
+23544 -293.79 277.126
+23545 -295.22 275.579
+23561 -307.265 242.111
+23562 -308.875 240.952
+23573 -309.08 237.911
+23574 -311.794 238.41
+23586 -311.922 233.851
+23588 -313.525 236.201
+23599 -313.652 233.38
+23600 -314.257 233.529
+23611 -310.519 233.267
+23612 -313.229 230.611
+23622 -315.964 226.994
+23623 -315.815 226.584
+23634 -317.842 222.603
+23636 -318.592 222.275
+23647 -319.315 221.166
+23648 -320.237 219.248
+23663 -320.955 218.693
+23664 -321.558 216.198
+23675 -322.119 214.459
+23676 -322.734 212.887
+23686 -323.392 211.242
+23687 -324.446 207.76
+23698 -325.499 205.158
+23699 -331.149 201.771
+23709 -333.366 199.833
+23710 -332.384 197
+23720 -315.361 196.689
+23721 92.2192 241.811
+23732 -332.349 193.469
+23733 90.7276 242.28
Index: /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_may.pos
===================================================================
--- /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_may.pos	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mifae/srcpositions/Mrk421_may.pos	(revision 9772)
@@ -0,0 +1,41 @@
+25791 -84.8946 47.6763
+25794 -122.125 48.4988
+25796 -122.461 49.1271
+25797 -158.079 50.8216
+25801 -84.0898 46.3166
+25802 -84.5659 47.6243
+25803 -83.9559 46.2252
+25806 -85.946 51.5223
+25807 -94.0789 51.5786
+25811 -84.4276 47.8788
+25812 -84.3594 47.8559
+25813 -84.5057 48.0659
+25814 -84.3513 47.8463
+25817 -94.3231 52.0249
+25820 -93.7396 50.8518
+25837 -100.304 51.9021
+25839 -100.155 51.9117
+25840 -133.041 50.619
+25842 -153.155 51.9754
+25843 -164.676 50.8785
+25845 -167.419 52.1466
+25846 -152.706 51.8807
+25847 -156.14 52.1006
+25848 -155.703 52.0932
+25850 -153.024 52.1258
+00000 -150.056 51.9723
+25851 -157.841 51.8809
+25852 -155.837 51.886
+25854 -158.421 51.9508
+25855 -156.322 51.9079
+25858 -103.452 52.2983
+25861 -103.909 52.3202
+25862 -98.145 52.5624
+25863 -99.9381 52.4628
+25865 -101.62 52.8831
+25874 -104.375 52.2092
+25875 -109.995 51.9257
+25876 -83.6544 48.1068
+25877 -108.161 52.0623
+25883 -83.6796 48.0056
+25884 -119.101 66.3904
Index: /tags/Mars-V0.9/mtemp/mmpi/FluxCalcAndUnfold.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/FluxCalcAndUnfold.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/FluxCalcAndUnfold.C	(revision 9772)
@@ -0,0 +1,59 @@
+void Flux6c() 
+{
+
+  TString datafile = "files/AlphaEnergyTheta.LastKeichiRF.27MC.root";
+  TString areafile = "files/area.root";
+
+  TFile* file = new TFile(datafile);
+
+  MHAlphaEnergyTheta hAlpha;
+  hAlpha.Read("MHAlphaEnergyTheta");
+  hAlpha.DrawClone();
+
+  MHEffectiveOnTime hEffTime;
+  hEffTime.Read("MHEffectiveOnTime");
+  hEffTime.DrawClone();
+
+  TFile* file3 = new TFile(areafile);
+  MHMcCollectionArea area;
+  area.Read("MHMcCollectionArea");
+  area.DrawClone();
+
+  //
+  // Read Migration Matrix
+  //
+  TFile* file4 = new TFile("files/EnergyParams.Keichi.Resized.root");
+  MHMcEnergyMigration migm;
+  migm.Read("MHMcEnergyMigration");
+  
+  // ----------------------------------------------------------------------- 
+  //
+  // Calculate # Excess events vs. Energy and Theta
+  //
+  MHExcessEnergyTheta *hex = new MHExcessEnergyTheta;
+  hex->Calc(&hAlpha);
+  hex->Draw();
+  
+  MHFlux* hFluxNUnf = new MHFlux;
+  hFluxNUnf->Calc(hex, &area, &hEffTime);
+  TH1D* fluxNUnf = hFluxNUnf->GetAverageFlux();
+
+  // ----------------------------------------------------------------------- 
+  //
+  // Unfold # Excess events vs. Energy and Theta
+  //
+  
+  TH2D* tobeunfolded = hex->GetHist();
+  TH2D* unfolded = new TH2D(*tobeunfolded);    
+  
+  MUnfoldSpectrum munfs;
+  munfs.SetDistToUnfold(tobeunfolded);
+  munfs.SetMigrationMatrix(migm->GetHist());
+  munfs.SetPriorConstant();
+  //munfs.SetPriorInput(hpr);
+  munfs.SetUnfoldingMethod(2);
+  munfs.Calc();
+  unfolded=munfs.GetUnfDist();
+
+}
+
Index: /tags/Mars-V0.9/mtemp/mmpi/MApplySupercuts.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MApplySupercuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MApplySupercuts.cc	(revision 9772)
@@ -0,0 +1,262 @@
+/* 
+======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  02/2005 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MApplySupercuts
+//
+// Apply supercuts to a file containing Hillas parameters
+// (usually a star file).
+//
+// Input:
+//   rootfile (starfile) of Hillas parameters
+//
+// Output:
+//   MHadronness estimated on event
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <TMath.h>
+#include <TFile.h>
+#include <TH1F.h>
+#include <TCanvas.h>
+
+#include "MGeomCamMagic.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+#include "MSupercuts.h"
+#include "MHadronness.h"
+#include "MHillas.h"
+#include "MHillasSrc.h"
+#include "MHFindSignificance.h"
+#include "MEnergyEst.h"
+#include "MApplySupercuts.h"
+
+ClassImp(MApplySupercuts);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MApplySupercuts::MApplySupercuts(const char *name, const char *title)
+  : fRunHeader(0), fEvtHeader(0), fSupercuts(0)
+{
+    fName  = name  ? name  : "MApplySupercuts";
+    fTitle = title ? title : "Task to apply supercuts to star files";
+
+    fPhe = kTRUE;
+    fPlot = kFALSE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+Int_t MApplySupercuts::PreProcess(MParList *pList)
+{
+  fGeom = (MGeomCamMagic *)pList->FindCreateObj("MGeomCamMagic");
+  if (!fGeom)
+    {
+      *fLog << err << "MGeomCamMagic not found... abort." << endl;
+      return kFALSE;
+    }
+  
+  fRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
+  if (!fRunHeader)
+    {
+      *fLog << err << "MRawRunHeader not found... abort." << endl;
+      return kFALSE;
+    }
+  
+  fEvtHeader = (MRawEvtHeader *)pList->FindObject("MRawEvtHeader");
+  if (!fEvtHeader)
+    {
+      *fLog << err << "MRawEvtHeader not found... but ok." << endl;
+    }
+  
+  fHillas = (MHillas *)pList->FindObject("MHillas");
+  if (!fHillas)
+    {
+      *fLog << err << "MHillas not found... abort." << endl;
+      return kFALSE;
+    }
+  
+  fHillasSrc = (MHillasSrc *)pList->FindObject("MHillasSrc");
+  if (!fHillasSrc)
+    {
+      *fLog << err << "MHillasSrc not found... abort." << endl;
+      return kFALSE;
+    }
+  
+  fHadronness = (MHadronness *)pList->FindCreateObj("MHadronness",AddSerialNumber("MHadronness"));
+  if (!fHadronness)
+    {
+      *fLog << err << "MHadronness not found... abort." << endl;
+      return kFALSE;
+    }
+
+  fEnergyEst = (MEnergyEst *)pList->FindCreateObj("MEnergyEst");
+  if (!fEnergyEst)
+    {
+      *fLog << err << "MEnergyEst not found... abort." << endl;
+      return kFALSE;
+    }
+
+  if(fPlot){
+    fAlpha = new TH1F("fHistAlpha","Alpha Plot",30,0,90);
+      if (!fAlpha)
+	{
+	  *fLog << err << "Impossible to create Alpha histogram... abort." << endl;
+	  return kFALSE;
+	}
+  }
+
+  fHFindSigma = (MHFindSignificance *)pList->FindCreateObj("MHFindSignificance");
+  if (!fHFindSigma)
+    {
+      *fLog << err << "MHFindSignificance not found... abort." << endl;
+      return kFALSE;
+    }
+
+  // Start reading supercuts
+  fSupercuts = (MSupercuts *)pList->FindCreateObj("MSupercuts",AddSerialNumber("MSupercuts"));
+  if (!fSupercuts)
+    {
+      *fLog << err << "MSupercuts not found... abort." << endl;
+      return kFALSE;
+    }
+  // read the cuts coefficients
+  TFile inparam(fSCFilename);
+  fSupercuts->Read("MSupercuts");
+  inparam.Close();
+  *fLog << "MFindSupercutsONOFF::FindParams; initial values of parameters are taken from file "
+	<< fSCFilename << endl;
+  
+  TArrayD params = fSupercuts->GetParameters();
+  
+  for (Int_t i=0; i<8; i++)
+    {
+      fLengthUp[i] = params[i];
+      fLengthLo[i] = params[i+8];
+      fWidthUp[i]  = params[i+16];
+      fWidthLo[i]  = params[i+24];
+      fDistUp[i]   = params[i+32];
+      fDistLo[i]   = params[i+40];
+    }
+    
+  // end reading supercuts
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MApplySupercuts::Process()
+{
+  fHadronness->SetHadronness(kHadronHadronness);
+
+  Float_t fMm2Deg = fGeom->GetConvMm2Deg();
+  Double_t log3000 = TMath::Log(fSizeOffset);
+  Float_t fsize = fHillas->GetSize();
+  if(fPhe)
+    fsize /= kPhe2Ph;
+  Float_t fdist = fHillasSrc->GetDist()*fMm2Deg;
+  Double_t logsize = TMath::Log((Double_t)fsize);
+  Double_t lgsize = logsize-log3000;
+  Double_t lgsize2 = lgsize*lgsize;
+  Double_t dist2 =  (Double_t)fdist*fdist - fDistOffset*fDistOffset;
+  //Double_t dist2 = (fDist-fDistOffset)*(fDist-fDistOffset);
+
+  // parameters:
+  Float_t flength = (fHillas->GetLength()) * fMm2Deg;
+  Float_t fwidth = (fHillas->GetWidth())*fMm2Deg;
+  //Float_t fsize = fHillas.GetSize()/0.18;
+  //Float_t fmeanx = (fHillas.GetMeanX())*fMm2Deg;
+  //Float_t fmeany = (fHillas.GetMeanY())*fMm2Deg;
+  //Float_t falpha = fHillasSrc.GetAlpha();
+  //Float_t fDCAdelta = fHillasSrc.GetDCADelta();
+
+
+
+  if ( flength < CalcLimit(fLengthUp, lgsize, lgsize2, dist2) &&
+       flength > CalcLimit(fLengthLo, lgsize, lgsize2, dist2) &&
+       fwidth  < CalcLimit(fWidthUp, lgsize, lgsize2, dist2)  &&
+       fwidth  > CalcLimit(fWidthLo, lgsize, lgsize2, dist2)  &&
+       fdist   < CalcLimit(fDistUp, lgsize, lgsize2, dist2)   &&
+       fdist   > CalcLimit(fDistLo, lgsize, lgsize2, dist2) )
+    {
+      // gamma candidates!
+      fHadronness->SetHadronness(kGammaHadronness);
+      if( fPlot && fHillas->GetSize()>fSizeLow && fHillas->GetSize()<fSizeUp )
+	fAlpha->Fill(TMath::Floor(TMath::Abs(fHillasSrc->GetAlpha())));
+    }
+
+  return kTRUE;
+}
+
+
+Int_t MApplySupercuts::PostProcess()
+{
+  if(fPlot){
+    TFile f("shit_file.root","RECREATE");
+    fAlpha->Write();
+    f.Close();
+    TCanvas c;
+    if(fHFindSigma!=NULL){
+      cout << "W el cogno " << fAlphaSignal <<endl;
+      fHFindSigma->FindSigma((TH1 *)fAlpha,fAlphaMin,fAlphaMax,fDegree,fAlphaSignal,kTRUE,kTRUE,kTRUE);
+      *fLog << "SIGNIFICANCE = " << fHFindSigma->GetSignificance() << endl;
+      c.SaveAs("Alpha.gif");
+    }
+    else
+      *fLog << err << "ERROR: fHFindSigma already deleted" << endl;
+  }
+  return kTRUE;
+}
+
+
+Double_t MApplySupercuts::CalcLimit(Double_t *a, Double_t ls, Double_t ls2, Double_t dd2)
+{
+  
+  Double_t  limit = a[0] + a[1] * dd2 +
+    ls  * (a[3] + a[4] * dd2) +
+    ls2 * (a[6] + a[7] * dd2);
+  
+  return limit;
+}
+
+
+void MApplySupercuts::SetPrintOutSignificance(Double_t bgalphamin=50.0, Double_t bgalphamax=90.0, 
+					      Double_t alphasig=15.0, Int_t degree=4)
+{
+  fAlphaMin = bgalphamin;
+  fAlphaMax = bgalphamax;
+  fDegree = degree;
+  fAlphaSignal = alphasig;
+
+  fPlot = kTRUE;
+}
+  
Index: /tags/Mars-V0.9/mtemp/mmpi/MApplySupercuts.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MApplySupercuts.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MApplySupercuts.h	(revision 9772)
@@ -0,0 +1,91 @@
+#ifndef MARS_MApplySupercuts
+#define MARS_MApplySupercuts
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MHadronness
+#include "MHadronness.h"
+#endif
+
+class MGeomCamMagic;
+class MParList;
+class MRawEvtHeader;
+class MRawRunHeader;
+class MSupercuts;
+class MHillas;
+class MHillasSrc;
+class MHadronness;
+class MHFindSignificance;
+class MEnergyEst;
+class TH1F;
+
+class MApplySupercuts : public MTask
+{
+ private:
+
+  // Constant to convert size in photoelectrons to photons
+  static const Float_t kPhe2Ph = 0.18;
+  static const Double_t kHadronHadronness = 0.75;
+  static const Double_t kGammaHadronness = 0.25;
+  static const Double_t fDistOffset = 0.9;
+  static const Double_t fSizeOffset = 3000.;
+
+  Bool_t fPhe;
+  Bool_t fPlot;
+  Double_t fLengthUp[8];
+  Double_t fLengthLo[8];
+  Double_t fWidthUp[8];
+  Double_t fWidthLo[8];
+  Double_t fDistUp[8];
+  Double_t fDistLo[8];
+  Double_t fAlphaMin;    // Minimum alpha of background region (deg)
+  Double_t fAlphaMax;    // Maximum alpha of background region (deg)
+  Double_t fAlphaSignal; // Maximum alpha of signal region (deg - Min=0)
+  Int_t fDegree;         // Degree of polinomial interpolating function
+  Double_t fSizeUp;
+  Double_t fSizeLow;
+
+  TString fSCFilename;
+  
+  MGeomCamMagic   *fGeom;
+  MRawRunHeader   *fRunHeader;
+  MRawEvtHeader   *fEvtHeader;
+  MSupercuts      *fSupercuts;
+  MHillas         *fHillas;
+  MHillasSrc      *fHillasSrc;
+
+  TH1F            *fAlpha;
+  MHadronness     *fHadronness;
+  MHFindSignificance *fHFindSigma;
+  MEnergyEst      *fEnergyEst;
+
+  Double_t CalcLimit(Double_t *a, Double_t ls, Double_t ls2, Double_t dd2);
+
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  Int_t PostProcess();
+  
+ public:
+  MApplySupercuts(const char *name=0, const char *title=0);
+
+  void SetPhotoelectrons() { fPhe = kTRUE; }
+  void SetPhotons() { fPhe = kFALSE; }
+  void SetSCFilename(TString filename) { fSCFilename = filename; }
+  void SetPrintOutSignificance(Double_t bgalphamin, Double_t bgalphamax, 
+			       Double_t alphasig, Int_t kDegree);
+  void SetPlotON() { fPlot = kTRUE; };
+  void SetPlotOFF() { fPlot = kFALSE; };
+  void SetBGAlphaMin(Double_t alphamin) { fAlphaMin=alphamin; SetPlotON(); };
+  void SetBGAlphaMax(Double_t alphamax) { fAlphaMax=alphamax; SetPlotON(); };
+  void SetAlphaSig(Double_t alphasig) { fAlphaSignal=alphasig; SetPlotON(); };
+  void SetPolDegree(Int_t deg) { fDegree=deg; SetPlotON(); };
+  void SetPlotSizeLow(Double_t size) { fSizeLow = size; };
+  void SetPlotSizeUp(Double_t size) { fSizeUp = size; };
+
+  ClassDef(MApplySupercuts, 1) // Task to apply supercuts
+};
+    
+#endif
+    
Index: /tags/Mars-V0.9/mtemp/mmpi/MFindStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MFindStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MFindStars.cc	(revision 9772)
@@ -0,0 +1,946 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Robert Wagner, 2/2004 <mailto:rwagner@mppmu.mpg.de>
+!   Author(s): Javier López , 4/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFindStars
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFindStars.h"
+
+#include <TMinuit.h>
+#include <TStopwatch.h>
+#include <TTimer.h>
+#include <TString.h>
+#include <TFile.h>
+#include <TTree.h>
+#include <TCanvas.h>
+#include <TH1F.h>
+#include <TF1.h>
+#include <TEllipse.h>
+
+
+#include "MObservatory.h"
+#include "MAstroCamera.h"
+#include "MMcConfigRunHeader.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+#include "MTime.h"
+#include "MReportDrive.h"
+#include "MStarLocalCam.h"
+#include "MStarLocalPos.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MFindStars);
+using namespace std;
+
+const Float_t sqrt2 = sqrt(2.);
+const Float_t sqrt3 = sqrt(3.);
+const UInt_t  lastInnerPixel = 396;
+    
+
+//______________________________________________________________________________
+//
+// The 2D gaussian fucntion used to fit the spot of the star
+//
+static Double_t func(float x,float y,Double_t *par)
+{
+    Double_t value=par[0]*exp(-(x-par[1])*(x-par[1])/(2*par[2]*par[2]))*exp(-(y-par[3])*(y-par[3])/(2*par[4]*par[4]));
+    return value;
+}
+
+//______________________________________________________________________________
+//
+// Function used by Minuit to do the fit
+//
+static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+
+  MParList*      plist = (MParList*)gMinuit->GetObjectFit();
+  MTaskList*     tlist = (MTaskList*)plist->FindObject("MTaskList");
+  MFindStars*    find = (MFindStars*)tlist->FindObject("MFindStars");
+  MStarLocalCam* stars = (MStarLocalCam*)plist->FindObject("MStarLocalCam");
+  MGeomCam*      geom = (MGeomCam*)plist->FindObject("MGeomCam");
+
+  MHCamera& display = (MHCamera&)find->GetDisplay();
+  
+  Float_t innerped = stars->GetInnerPedestalDC();
+  Float_t innerrms = stars->GetInnerPedestalRMSDC();
+  Float_t outerped = stars->GetOuterPedestalDC();
+  Float_t outerrms = stars->GetOuterPedestalRMSDC();
+
+  UInt_t numPixels = geom->GetNumPixels();
+  
+//calculate chisquare
+    Double_t chisq = 0;
+    Double_t delta;
+    Double_t x,y,z;
+    Double_t errorz=0;
+
+    UInt_t usedPx=0;
+    for (UInt_t pixid=1; pixid<numPixels; pixid++) 
+    {
+	if (display.IsUsed(pixid))
+	{
+	    x = (*geom)[pixid].GetX();
+	    y = (*geom)[pixid].GetY();
+            z = display.GetBinContent(pixid+1)-(pixid>lastInnerPixel?outerped:innerped);
+            errorz=(pixid>lastInnerPixel?outerrms:innerrms);
+
+	    if (errorz > 0.0)
+	    {
+              usedPx++;
+              delta  = (z-func(x,y,par))/errorz;
+              chisq += delta*delta;
+	    }
+	    else
+		cerr << " TMinuit::fcn errorz[" << pixid << "] " << errorz << endl;
+	}
+    }
+    f = chisq;
+
+    find->SetChisquare(chisq);
+    find->SetDegreesofFreedom(usedPx);
+}
+
+MFindStars::MFindStars(const char *name, const char *title): 
+  fGeomCam(NULL), fCurr(NULL), fTimeCurr(NULL), fDrive(NULL), fStars(NULL), fNumVar(5)
+{
+  fName  = name  ? name  : "MFindStars";
+  fTitle = title ? title : "Tool to find stars from DC Currents";
+
+  fNumIntegratedEvents=0;
+  fMaxNumIntegratedEvents = 10;
+  fRingInterest = 125.; //[mm] ~ 0.4 deg
+  fDCTailCut = 4;
+  
+  fPixelsUsed.Set(577);
+  fPixelsUsed.Reset((Char_t)kTRUE);
+  
+  //Fitting(Minuit) initialitation
+  const Float_t pixelSize = 31.5; //[mm]
+  fMinuitPrintOutLevel = -1;
+  
+  fVname = new TString[fNumVar];
+  fVinit.Set(fNumVar); 
+  fStep.Set(fNumVar); 
+  fLimlo.Set(fNumVar); 
+  fLimup.Set(fNumVar); 
+  fFix.Set(fNumVar);
+
+  fVname[0] = "max";
+  fVinit[0] = 10.*fMaxNumIntegratedEvents;
+  fStep[0]  = fVinit[0]/sqrt2;
+  fLimlo[0] = fMinDCForStars;
+  fLimup[0] = 30.*fMaxNumIntegratedEvents;
+  fFix[0]   = 0;
+
+  fVname[1] = "meanx";
+  fVinit[1] = 0.;
+  fStep[1]  = fVinit[1]/sqrt2;
+  fLimlo[1] = -600.;
+  fLimup[1] = 600.;
+  fFix[1]   = 0;
+
+  fVname[2] = "sigmaminor";
+  fVinit[2] = pixelSize;
+  fStep[2]  = fVinit[2]/sqrt2;
+  fLimlo[2] = pixelSize/(2*sqrt3);
+  fLimup[2] = 500.;
+  fFix[2]   = 0;
+
+  fVname[3] = "meany";
+  fVinit[3] = 0.;
+  fStep[3]  = fVinit[3]/sqrt2;
+  fLimlo[3] = -600.;
+  fLimup[3] = 600.;
+  fFix[3]   = 0;
+
+  fVname[4] = "sigmamajor";
+  fVinit[4] = pixelSize;
+  fStep[4]  = fVinit[4]/sqrt2;
+  fLimlo[4] = pixelSize/(2*sqrt3);
+  fLimup[4] = 500.;
+  fFix[4]   = 0;
+
+  fObjectFit  = NULL;
+  //  fMethod     = "SIMPLEX";
+  fMethod     = "MIGRAD";
+  //  fMethod     = "MINIMIZE";
+  fNulloutput = kFALSE;
+
+  // Set output level
+  //  fLog->SetOutputLevel(3); // No dbg messages
+
+  fGeometryFile="";
+  fBSCFile="";
+}
+
+Int_t MFindStars::PreProcess(MParList *pList)
+{
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+
+    if (!fGeomCam)
+    {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    // Initialize camera display with the MGeomCam information
+    fDisplay.SetGeometry(*fGeomCam,"FindStarsDisplay","FindStarsDisplay");
+    fDisplay.SetUsed(fPixelsUsed);
+
+    fCurr = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+
+    if (!fCurr)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fTimeCurr = (MTime*)pList->FindObject(AddSerialNumber("MTimeCurrents"));
+
+    if (!fTimeCurr)
+    {
+      *fLog << err << AddSerialNumber("MTimeCurrents") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fDrive = (MReportDrive*)pList->FindObject(AddSerialNumber("MReportDrive"));
+
+    if (!fDrive)
+      {
+
+        *fLog << warn << AddSerialNumber("MReportDrive") << " not found ... ignored." << endl;
+
+      }
+    else
+      {
+	
+	MObservatory magic1;
+
+	MMcConfigRunHeader *config=0;
+	MGeomCam           *geom=0;
+
+	TFile file(fGeometryFile);
+	TTree *tree = (TTree*)file.Get("RunHeaders");
+	tree->SetBranchAddress("MMcConfigRunHeader", &config);
+	if (tree->GetBranch("MGeomCam")) tree->SetBranchAddress("MGeomCam", &geom);
+	tree->GetEntry(0);
+	
+	fAstro.SetMirrors(*config->GetMirrors());
+	fAstro.SetGeom(*geom);	
+	fAstro.ReadBSC(fBSCFile);
+	
+	fAstro.SetObservatory(magic1);
+	
+      }
+    
+
+    fStars = (MStarLocalCam*)pList->FindCreateObj(AddSerialNumber("MStarLocalCam"));
+    if (!fStars)
+    {
+      *fLog << err << AddSerialNumber("MStarLocalCam") << " cannot be created ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fMinDCForStars = 1.*fMaxNumIntegratedEvents; //[uA]
+
+    // Initialize the TMinuit object
+
+    TMinuit *gMinuit = new TMinuit(fNumVar);  //initialize TMinuit with a maximum of params
+    gMinuit->SetFCN(fcn);
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+    arglist[0] = fMinuitPrintOutLevel;
+    gMinuit->mnexcm("SET PRI", arglist ,1,ierflg);
+
+    // Set MParList object pointer to allow mimuit to access internally
+    gMinuit->SetObjectFit(pList);
+
+    return kTRUE;
+}
+
+Int_t MFindStars::Process()
+{
+
+  UInt_t numPixels = fGeomCam->GetNumPixels();
+  TArrayC origPixelsUsed;
+  origPixelsUsed.Set(numPixels);
+
+  if (fNumIntegratedEvents >= fMaxNumIntegratedEvents) {
+
+    //Fist delete the previous stars in the list
+    fStars->GetList()->Delete();
+
+    if (fDrive) {
+
+      //If drive information is provided we take RaDec info
+      //from the drive and let the star list fill by the astrocamera.
+
+      //FIXME: rwagner: Doesn't work as expected
+      //FIXME: rwagner: For the time being set manually.
+      //fAstro.SetRaDec(fDrive->GetRa(), fDrive->GetDec());              
+
+      fAstro.SetTime(*fTimeCurr);
+      fAstro.SetGuiActive();
+      fAstro.FillStarList(fStars->GetList());      
+
+      cout << "Number of Stars added by astrocamera is " <<fStars->GetList()->GetSize() << endl;
+      
+      MStarLocalPos* starpos;
+      TIter Next(fStars->GetList());
+      while ((starpos=(MStarLocalPos*)Next())) {
+	starpos->SetCalcValues(40,40,starpos->GetXExp(),starpos->GetYExp(),fRingInterest/2,fRingInterest/2);
+	starpos->SetFitValues (40,40,starpos->GetXExp(),starpos->GetYExp(),fRingInterest/2,fRingInterest/2,0.,1);
+      }
+
+      for (UInt_t pix=1; pix<numPixels; pix++) {
+	if (fDisplay.IsUsed(pix))
+	  origPixelsUsed[pix]=(Char_t)kTRUE;
+	else
+	  origPixelsUsed[pix]=(Char_t)kFALSE;
+      }
+          
+      DCPedestalCalc();
+
+    } 
+    else 
+    {
+      
+      cout << "No drive information available: Will not use a star catalog to identify stars."<< endl;
+      
+      for (UInt_t pix=1; pix<numPixels; pix++) {
+	if (fDisplay.IsUsed(pix))
+	  origPixelsUsed[pix]=(Char_t)kTRUE;
+	else
+	  origPixelsUsed[pix]=(Char_t)kFALSE;
+      }
+          
+      if (DCPedestalCalc()) {
+
+	Float_t innermin = fStars->GetInnerPedestalDC()+fDCTailCut*fStars->GetInnerPedestalRMSDC();
+	Float_t outermin = fStars->GetOuterPedestalDC()+fDCTailCut*fStars->GetOuterPedestalRMSDC();
+	fMinDCForStars = innermin>outermin?innermin:outermin;
+	if (fMinuitPrintOutLevel>=0) *fLog << dbg << "fMinDCForStars = " << fMinDCForStars << endl;
+              
+	// Find the star candidates searching the most brights pairs of pixels
+	Float_t maxPixelDC;
+	MGeomPix maxPixel;
+	
+	while(FindPixelWithMaxDC(maxPixelDC, maxPixel)) {
+	  
+	  MStarLocalPos *starpos = new MStarLocalPos;
+	  starpos->SetExpValues(maxPixelDC,maxPixel.GetX(),maxPixel.GetY());
+	  starpos->SetCalcValues(maxPixelDC,maxPixelDC,maxPixel.GetX(),maxPixel.GetY(),fRingInterest/2,fRingInterest/2);
+	  starpos->SetFitValues(maxPixelDC,maxPixelDC,maxPixel.GetX(),maxPixel.GetY(),fRingInterest/2,fRingInterest/2,0.,1);
+	  fStars->GetList()->Add(starpos);
+	  
+	  ShadowStar(starpos);
+	}	
+	fDisplay.SetUsed(origPixelsUsed);
+      }      
+    }
+
+    //Show the stars found
+    //fStars->Print("namepos");
+   
+    //loop to extract position of stars on the camera
+    if (fStars->GetList()->GetSize() == 0) {
+      *fLog << err << GetName() << "No stars candidates in the camera." << endl;
+      return kCONTINUE;
+    } else
+      *fLog << inf << GetName() << " found " << fStars->GetList()->GetSize() 
+	    << " stars candidates in the camera." << endl;
+    
+    for (UInt_t pix=1; pix<numPixels; pix++) {
+      if (fDisplay.IsUsed(pix))
+	origPixelsUsed[pix]=(Char_t)kTRUE;
+      else
+	origPixelsUsed[pix]=(Char_t)kFALSE;
+    }
+
+    TIter Next(fStars->GetList());
+    MStarLocalPos* star;
+    while ((star=(MStarLocalPos*)Next())) {
+       FindStar(star);
+       ShadowStar(star);
+    }
+
+    //Show the stars found: Here it is interesting to see what FindStars
+    //made out of the positions we gave to it.
+    fStars->Print("namepos");
+
+    
+    //After finding stars reset all variables
+    fDisplay.Reset();
+    fStars->GetDisplay().Reset(); //FIXME: Put this display just in the container
+    fDisplay.SetUsed(origPixelsUsed);
+    fNumIntegratedEvents=0;
+  }
+
+  for (UInt_t pix=1; pix<numPixels; pix++) {
+    if (fDisplay.IsUsed(pix))
+      origPixelsUsed[pix]=(Char_t)kTRUE;
+    else
+      origPixelsUsed[pix]=(Char_t)kFALSE;
+    
+  }
+  
+  fDisplay.AddCamContent(*fCurr);
+  fNumIntegratedEvents++;
+  fDisplay.SetUsed(origPixelsUsed);
+  
+  return kTRUE;
+}
+
+Int_t MFindStars::PostProcess()
+{
+  return kTRUE;
+}
+
+void MFindStars::SetBlindPixels(TArrayS blindpixels)
+{
+    Int_t npix = blindpixels.GetSize();
+
+    for (Int_t idx=0; idx<npix; idx++)
+      {
+	fPixelsUsed[blindpixels[idx]]=(Char_t)kFALSE;
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << "MFindStars::SetBlindPixels fDisplay.IsUsed(" <<blindpixels[idx]  << ") kFALSE" << endl;
+      }
+    
+    fDisplay.SetUsed(fPixelsUsed);
+}
+
+Bool_t MFindStars::DCPedestalCalc()
+{
+    //-------------------------------------------------------------
+    // save pointer to the MINUIT object for optimizing the supercuts
+    // because it will be overwritten 
+    // when fitting the alpha distribution in MHFindSignificance
+    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+   UInt_t numPixels = fGeomCam->GetNumPixels();
+   Float_t ped;
+   Float_t rms;
+
+   TH1F **dchist = new TH1F*[2];
+   for (UInt_t i=0; i<2; i++)
+      dchist[i] = new TH1F("","",26,0.4*fMaxNumIntegratedEvents,3.*fMaxNumIntegratedEvents);
+   
+   for (UInt_t pix=1; pix<=lastInnerPixel; pix++)
+       dchist[0]->Fill(fDisplay.GetBinContent(pix+1));
+   for (UInt_t pix=lastInnerPixel+1; pix<numPixels; pix++)
+       dchist[1]->Fill(fDisplay.GetBinContent(pix+1));
+
+   // inner/outer pixels
+   for (UInt_t i=0; i<2; i++)
+    {
+      Float_t nummaxprobdc = dchist[i]->GetBinContent(dchist[i]->GetMaximumBin());
+      Float_t maxprobdc = dchist[i]->GetBinCenter(dchist[i]->GetMaximumBin());
+      UInt_t bin = dchist[i]->GetMaximumBin();
+      do
+        {
+          bin++;
+        }
+      while(dchist[i]->GetBinContent(bin)/nummaxprobdc > 0.5);
+      Float_t halfmaxprobdc = dchist[i]->GetBinCenter(bin);
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " maxprobdc[high] " << maxprobdc << "[" << nummaxprobdc << "] ";
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " halfmaxprobdc[high] " << halfmaxprobdc << "[" << dchist[i]->GetBinContent(bin) << "]" << endl;
+      
+      Float_t rmsguess = TMath::Abs(maxprobdc-halfmaxprobdc);
+      Float_t min = maxprobdc-3*rmsguess;
+      min = (min<0.?0.:min);
+      Float_t max = maxprobdc+3*rmsguess;
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+      
+      TF1 func("func","gaus",min,max);
+      func.SetParameters(nummaxprobdc, maxprobdc, rmsguess);
+      
+      dchist[i]->Fit("func","QR0");
+      
+      UInt_t aproxnumdegrees = 6*(bin-dchist[i]->GetMaximumBin());
+      Float_t chiq = func.GetChisquare();
+      ped = func.GetParameter(1);
+      rms = func.GetParameter(2);
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " ped " << ped << " rms " << rms << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+      
+      Int_t numsigmas = 5;
+      Axis_t minbin = ped-numsigmas*rms/dchist[i]->GetBinWidth(1);
+      minbin=minbin<1?1:minbin;
+      Axis_t maxbin = ped+numsigmas*rms/dchist[i]->GetBinWidth(1);
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " Number of pixels with dc under " << numsigmas << " sigmas = " << dchist[i]->Integral((int)minbin,(int)maxbin) << endl;
+      
+      //Check results from the fit are consistent
+      if (ped < 0. || rms < 0.)
+        {
+          *fLog << dbg << "dchist[i]->GetEntries()" << dchist[i]->GetEntries();
+//            TCanvas *c1 = new TCanvas("c2","c2",500,800);
+//            dchist[i]->Draw();
+//            c1->Print("dchist.ps");
+//            delete c1;
+//            exit(1);
+        }
+      else if (TMath::Abs(ped-maxprobdc) > rmsguess || rms > rmsguess)
+        {
+          *fLog << warn << GetName() << " Pedestal DC fit give non consistent results for " << (i==0?"Inner":"Outer") << "pixels." << endl;
+          *fLog << warn << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+          *fLog << warn << " ped " << ped << " rms " << rms << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+          ped = maxprobdc;
+          rms = rmsguess/1.175; // FWHM=2.35*rms
+        }
+   
+      if (i == 0)
+        {
+          fStars->SetInnerPedestalDC(ped);
+          fStars->SetInnerPedestalRMSDC(rms);
+        }
+      else
+        {
+          fStars->SetOuterPedestalDC(ped);
+          fStars->SetOuterPedestalRMSDC(rms);
+        }
+
+      
+
+    }
+   
+
+   for (UInt_t i=0; i<2; i++)
+      delete dchist[i];
+   delete [] dchist;
+
+   //=================================================================
+
+   // reset gMinuit to the MINUIT object for optimizing the supercuts 
+   gMinuit = savePointer;
+   //-------------------------------------------
+   
+   if (fStars->GetInnerPedestalDC() < 0. ||  fStars->GetInnerPedestalRMSDC() < 0. || fStars->GetOuterPedestalDC() < 0. ||  fStars->GetOuterPedestalRMSDC() < 0.)
+     return kFALSE;
+  
+   return kTRUE;
+}
+    
+Bool_t MFindStars::FindPixelWithMaxDC(Float_t &maxDC, MGeomPix &maxPix)
+{
+    UInt_t numPixels = fGeomCam->GetNumPixels();
+
+// Find the two close pixels with the maximun dc
+    UInt_t maxPixIdx[2];
+
+    maxDC = 0;
+
+    for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+	if(fDisplay.IsUsed(pix))
+	{
+	    Float_t dc[2];
+	    dc[0] = fDisplay.GetBinContent(pix+1);
+	    if (dc[0] < fMinDCForStars)
+		continue;
+
+	    MGeomPix &g = (*fGeomCam)[pix];
+	    Int_t numNextNeighbors = g.GetNumNeighbors();
+	    
+	    Float_t dcsum;
+	    for(Int_t nextNeighbor=0; nextNeighbor<numNextNeighbors; nextNeighbor++)
+	    {
+              UInt_t swneighbor = g.GetNeighbor(nextNeighbor);
+              if(fDisplay.IsUsed(swneighbor))
+                {
+                  dc[1] = fDisplay.GetBinContent(swneighbor+1);
+                  if (dc[1] < fMinDCForStars)
+                    continue;
+                  
+                  dcsum = dc[0] + dc[1];
+                  
+                  if(dcsum > maxDC*2)
+                    {
+                      if(dc[0]>=dc[1])
+                        {
+                          maxPixIdx[0] = pix;
+                          maxPixIdx[1] = swneighbor;
+                          maxDC = dc[0];
+                        }
+                      else
+                        {
+                          maxPixIdx[1] = pix;
+                          maxPixIdx[0] = swneighbor;
+                          maxDC = dc[1];
+                        }
+                    }	
+                }
+            }
+        }
+    }
+
+    if (maxDC == 0)
+      {
+        *fLog << warn << " No found pixels with maximum dc" << endl;
+	return kFALSE;
+      }
+    
+    maxPix = (*fGeomCam)[maxPixIdx[0]];
+
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << "Star candidate maxDC(" << setw(3) << maxDC << " uA) x position(" << setw(3) << maxPix.GetX() <<  " mm) x position(" << setw(3) << maxPix.GetY() << " mm) swnumber(" << maxPixIdx[0] << ")" << endl;
+
+    return kTRUE;
+}
+
+Bool_t MFindStars::FindStar(MStarLocalPos* star)
+{    
+ 
+  UInt_t numPixels = fGeomCam->GetNumPixels();
+  Float_t innerped = fStars->GetInnerPedestalDC();
+  Float_t outerped = fStars->GetOuterPedestalDC();
+
+  TArrayC origPixelsUsed;
+  origPixelsUsed.Set(numPixels);
+  
+  for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+      if (fDisplay.IsUsed(pix))
+        origPixelsUsed[pix]=(Char_t)kTRUE;
+      else
+        origPixelsUsed[pix]=(Char_t)kFALSE;
+    }
+  
+  Float_t expX = star->GetXExp();
+  Float_t expY = star->GetYExp();
+  
+  Float_t max=0;
+  UInt_t  pixmax=0;
+  Float_t meanX=0;
+  Float_t meanY=0;
+  Float_t meanSqX=0;
+  Float_t meanSqY=0;
+  Float_t sumCharge=0;
+  UInt_t usedInnerPx=0;	
+  UInt_t usedOuterPx=0;	
+
+  const Float_t meanPresition = 3.; //[mm]
+  const UInt_t maxNumIterations = 10;
+  UInt_t numIterations = 0;
+
+  do
+    {
+
+      //rwagner: Need to find px with highest dc and need to assume it is
+      // somewhere near the center of the star
+      //after that we need to REDEFINE our roi! because expected pos could be
+      // quite off that px!
+      
+      // 1.) Initial roi around expected position
+
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	{
+	  
+	  Float_t pixXpos=(*fGeomCam)[pix].GetX();
+	  Float_t pixYpos=(*fGeomCam)[pix].GetY();
+	  Float_t dist = sqrt((pixXpos-expX)*(pixXpos-expX)+
+			      (pixYpos-expY)*(pixYpos-expY));
+	  
+	  if ((dist < fRingInterest) && fDisplay.IsUsed(pix))
+	    fPixelsUsed[pix]=(Char_t)kTRUE;
+	  else
+	    fPixelsUsed[pix]=(Char_t)kFALSE;
+	}
+      fDisplay.SetUsed(fPixelsUsed);
+
+      // 2.) Find px with highest dc in that region
+
+      for(UInt_t pix=0; pix<numPixels; pix++)	
+	if(fDisplay.IsUsed(pix))
+	  {
+	    Float_t charge  = fDisplay.GetBinContent(pix+1);	      
+	    if (charge>max)
+	      {
+		max=charge;
+		pixmax=pix;
+	      }
+	    
+	  }         
+
+      // 3.) make it new center
+
+      expX = (*fGeomCam)[pixmax].GetX();
+      expY = (*fGeomCam)[pixmax].GetY();
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	fPixelsUsed[pix]=(Char_t)kTRUE;       
+      fDisplay.SetUsed(fPixelsUsed);
+
+      // First define a area of interest around the expected position of the star
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	{
+	  
+	  Float_t pixXpos=(*fGeomCam)[pix].GetX();
+	  Float_t pixYpos=(*fGeomCam)[pix].GetY();
+	  Float_t dist = sqrt((pixXpos-expX)*(pixXpos-expX)+
+			      (pixYpos-expY)*(pixYpos-expY));
+	  
+	  if ((dist < fRingInterest) && fDisplay.IsUsed(pix))
+	    fPixelsUsed[pix]=(Char_t)kTRUE;
+	  else
+	    fPixelsUsed[pix]=(Char_t)kFALSE;
+	}
+  
+      fDisplay.SetUsed(fPixelsUsed);
+    
+      // determine mean x and mean y
+      usedInnerPx=0;	
+      usedOuterPx=0;	
+      for(UInt_t pix=0; pix<numPixels; pix++)
+	{
+	  if(fDisplay.IsUsed(pix))
+	    {
+	      pix>lastInnerPixel?usedOuterPx++:usedInnerPx++;
+	      
+	      Float_t charge  = fDisplay.GetBinContent(pix+1);
+	      Float_t pixXpos = (*fGeomCam)[pix].GetX();
+	      Float_t pixYpos = (*fGeomCam)[pix].GetY();
+	      
+	      if (charge>max)
+		{
+		  max=charge;
+		  pixmax=pix;
+		}
+	      
+	      meanX     += charge*pixXpos;
+	      meanY     += charge*pixYpos;
+	      meanSqX   += charge*pixXpos*pixXpos;
+	      meanSqY   += charge*pixYpos*pixYpos;
+	      sumCharge += charge;
+	    }
+	} 
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " usedInnerPx " << usedInnerPx << " usedOuterPx " << usedOuterPx << endl;
+      
+      meanX   /= sumCharge;
+      meanY   /= sumCharge;
+      meanSqX /= sumCharge;
+      meanSqY /= sumCharge;
+      
+      expX = meanX;
+      expY = meanY;
+      
+      if (++numIterations >  maxNumIterations)
+	{
+	  *fLog << warn << GetName() << "Mean calculation not converge after " << maxNumIterations << " iterations" << endl;
+	  break;
+	}
+        
+    } while(TMath::Abs(meanX-expX) > meanPresition || TMath::Abs(meanY-expY) > meanPresition);
+  
+  Float_t rmsX = (meanSqX - meanX*meanX) - fRingInterest*fRingInterest/12;
+  Float_t rmsY = (meanSqY - meanY*meanY) - fRingInterest*fRingInterest/12;
+  
+  if ( rmsX > 0)
+    rmsX =  TMath::Sqrt(rmsX);
+  else
+    {
+      *fLog << warn << " MFindStars::FindStar negative rmsX² " << rmsX << endl;
+      *fLog << warn << " meanSqX " << meanSqX << " meanX " << meanX << " fRingInterest " << fRingInterest << " sumCharge " << sumCharge << endl;
+      rmsX = 0.;
+    }
+  
+  if ( rmsY > 0)
+    rmsY =  TMath::Sqrt(rmsY);
+  else
+    {
+      *fLog << warn << " MFindStars::FindStar negative rmsY² " << rmsY << endl;
+      *fLog << warn << " meanSqY " << meanSqY << " meanY " << meanY << " fRingInterest " << fRingInterest << " sumCharge " << sumCharge<< endl;
+      rmsY = 0.;
+    }
+  
+  // Substrack pedestal DC
+  sumCharge-= (usedInnerPx*innerped+usedOuterPx*outerped)/(usedInnerPx+usedOuterPx);
+  max-=pixmax>lastInnerPixel?outerped:innerped;
+  
+  
+  star->SetCalcValues(sumCharge,max,meanX,meanY,rmsX,rmsY);
+  
+  if (rmsX <= 0. || rmsY <= 0.)
+    return kFALSE;
+    
+    
+// fit the star spot using TMinuit
+
+    
+    for (UInt_t pix=1; pix<numPixels; pix++)
+      if (fDisplay.IsUsed(pix))
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << "[fit the star spot] fDisplay.IsUsed(" << pix << ") kTRUE" << endl;
+  
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << "fMinDCForStars " << fMinDCForStars << " pixmax>lastInnerPixel?outerped:innerped " << (pixmax>lastInnerPixel?outerped:innerped) << " fMaxNumIntegratedEvents " << fMaxNumIntegratedEvents << endl;
+
+  //Initialate variables for fit
+    fVinit[0] = max;
+    fLimlo[0] = fMinDCForStars-(pixmax>lastInnerPixel?outerped:innerped);
+    fLimup[0] = 30*fMaxNumIntegratedEvents-(pixmax>lastInnerPixel?outerped:innerped);
+    fVinit[1] = meanX;
+    fVinit[2] = rmsX;
+    fVinit[3] = meanY;
+    fVinit[4] = rmsY;
+    //Init steps
+    for(Int_t i=0; i<fNumVar; i++)
+      {
+	if (fVinit[i] != 0)
+	  fStep[i] = TMath::Abs(fVinit[i]/sqrt2);
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fVinit[" << i << "] " << fVinit[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fStep[" << i << "] " << fStep[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fLimlo[" << i << "] " << fLimlo[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fLimup[" << i << "] " << fLimup[i] << endl;
+      }
+    //
+
+    // -------------------------------------------
+    // call MINUIT
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    for (Int_t i=0; i<fNumVar; i++)
+      gMinuit->mnparm(i, fVname[i], fVinit[i], fStep[i], fLimlo[i], fLimup[i], ierflg);
+
+    TStopwatch clock;
+    clock.Start();
+
+// Now ready for minimization step
+    arglist[0] = 500;
+    arglist[1] = 1.;
+    gMinuit->mnexcm(fMethod, arglist ,2,ierflg);
+
+    clock.Stop();
+
+    if(fMinuitPrintOutLevel>=0)
+      {
+	if (fMinuitPrintOutLevel>=0) *fLog << dbg << "Time spent for the minimization in MINUIT :   " << endl;;
+	clock.Print();
+      }
+
+    Double_t integratedCharge;
+    Double_t maxFit, maxFitError;
+    Double_t meanXFit, meanXFitError;
+    Double_t sigmaMinorAxis, sigmaMinorAxisError;
+    Double_t meanYFit, meanYFitError;
+    Double_t sigmaMajorAxis, sigmaMajorAxisError;
+    Float_t chisquare = GetChisquare();
+    Int_t   dregrees  = GetDegreesofFreedom()-fNumVar;
+
+    if (!ierflg)
+      {
+        gMinuit->GetParameter(0,maxFit, maxFitError);
+        gMinuit->GetParameter(1,meanXFit,meanXFitError);
+        gMinuit->GetParameter(2,sigmaMinorAxis,sigmaMinorAxisError);
+        gMinuit->GetParameter(3,meanYFit,meanYFitError);
+        gMinuit->GetParameter(4,sigmaMajorAxis,sigmaMajorAxisError);
+        
+        //FIXME: Do the integral properlly
+        integratedCharge = 0.;
+
+        
+      }
+    else
+      {
+        maxFit = 0.;
+        meanXFit = 0.;
+        sigmaMinorAxis = 0.;
+        meanYFit = 0.;
+        sigmaMajorAxis = 0.;
+        integratedCharge = 0.;
+
+	*fLog << err << "TMinuit::Call error " << ierflg << endl;
+      }
+
+    //rwagner: get error matrix
+    Double_t matrix[2][2];
+    gMinuit->mnemat(&matrix[0][0],2);
+
+    star->SetFitValues(integratedCharge,maxFit,meanXFit,meanYFit,sigmaMinorAxis,sigmaMajorAxis,chisquare,dregrees,
+  		       matrix[0][0],matrix[1][0],matrix[1][1]);
+    
+    // reset the display to the starting values
+    fDisplay.SetUsed(origPixelsUsed);
+
+    if (ierflg)
+      return kCONTINUE;
+    return kTRUE;
+}
+
+Bool_t MFindStars::ShadowStar(MStarLocalPos* star)
+{
+    UInt_t numPixels = fGeomCam->GetNumPixels();
+
+// Define an area around the star which will be set unused.
+    UInt_t shadowPx=0;	
+    for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+	Float_t pixXpos  = (*fGeomCam)[pix].GetX();
+	Float_t pixYpos  = (*fGeomCam)[pix].GetY();
+        Float_t starXpos = star->GetMeanX();
+        Float_t starYpos = star->GetMeanY();
+        
+	Float_t starSize = 3*star->GetSigmaMajorAxis();
+        
+	Float_t dist = sqrt((pixXpos-starXpos)*(pixXpos-starXpos)+
+			    (pixYpos-starYpos)*(pixYpos-starYpos));
+
+        if (dist > starSize && fDisplay.IsUsed(pix))
+	  fPixelsUsed[pix]=(Char_t)kTRUE;
+        else
+          {
+            fPixelsUsed[pix]=(Char_t)kFALSE;
+            shadowPx++;
+          }
+    }
+
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << " shadowPx " << shadowPx << endl;
+
+    fDisplay.SetUsed(fPixelsUsed);
+
+    return kTRUE;
+}
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/MFindStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MFindStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MFindStars.h	(revision 9772)
@@ -0,0 +1,116 @@
+#ifndef MARS_MFindStars
+#define MARS_MFindStars
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+#ifndef MARS_MAstroCamera
+#include "MAstroCamera.h"
+#endif
+
+class MGeomCam;
+class MGeomPix;
+class MCameraDC;
+class MTime;
+class MReportDrive;
+class MStarLocalCam;
+class MStarLocalPos;
+
+class MFindStars : public MTask
+{
+
+private:
+
+    MGeomCam      *fGeomCam;
+    MCameraDC     *fCurr;
+    MTime         *fTimeCurr;
+    MReportDrive  *fDrive;
+    MStarLocalCam *fStars;
+
+    MAstroCamera fAstro;
+    TArrayC      fPixelsUsed;
+    MHCamera     fDisplay;
+
+    UInt_t fMaxNumIntegratedEvents;
+    UInt_t fNumIntegratedEvents;
+
+    Float_t fRingInterest; //[mm]
+    Float_t fMinDCForStars; //[uA]
+
+    Float_t fDCTailCut;
+
+    //Fitting(Minuit) variables
+    const Int_t fNumVar;
+    Float_t fTempChisquare;
+    Int_t fTempDegreesofFreedom;
+    Int_t fMinuitPrintOutLevel;
+    
+    TString *fVname;
+    TArrayD fVinit; 
+    TArrayD fStep; 
+    TArrayD fLimlo; 
+    TArrayD fLimup; 
+    TArrayI fFix;
+    TObject *fObjectFit;
+    TString fMethod;
+    Bool_t fNulloutput;
+    
+    Bool_t DCPedestalCalc();
+    Bool_t FindPixelWithMaxDC(Float_t &maxDC, MGeomPix &maxPix);
+    Bool_t FindStar(MStarLocalPos* star);
+    Bool_t ShadowStar(MStarLocalPos* star);
+
+    TString fGeometryFile;
+    TString fBSCFile;
+
+  public:
+    
+    MFindStars(const char *name=NULL, const char *title=NULL);
+    
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // setters
+    void SetNumIntegratedEvents(UInt_t max) {fMaxNumIntegratedEvents=max;}
+    void SetRingInterest(Float_t ring) {fRingInterest=ring;}
+    void SetBlindPixels(TArrayS blindpixels);
+    void SetMinuitPrintOutLevel(Int_t level) {fMinuitPrintOutLevel=level;}
+    void SetDCTailCut(Float_t cut) {fDCTailCut=cut;}
+
+    void SetChisquare(Float_t chi) {fTempChisquare=chi;}
+    void SetDegreesofFreedom(Int_t free) {fTempDegreesofFreedom=free;}
+
+    void SetGeometryFile(TString f) {fGeometryFile=f;}
+    void SetBSCFile(TString f) {fBSCFile=f;}
+    void SetRaDec(Double_t ra, Double_t dec) {fAstro.SetRaDec(ra,dec);}
+    void SetRaDec(TVector3 &v) { fAstro.SetRaDec(v); }
+    void SetLimMag(Double_t mag) { fAstro.SetLimMag(mag); } 
+    void SetRadiusFOV(Double_t deg) { fAstro.SetRadiusFOV(deg); }
+
+
+    //Getters
+    MHCamera& GetDisplay() { return fDisplay; }
+    
+    Float_t GetChisquare() {return fTempChisquare;}
+    Int_t GetDegreesofFreedom() {return fTempDegreesofFreedom;}
+    UInt_t GetNumIntegratedEvents() {return fMaxNumIntegratedEvents;}
+    Float_t GetRingInterest() {return fRingInterest;}
+    
+  ClassDef(MFindStars, 0) // Tool to find stars from DC Currents
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mmpi/MJCalibrateSignal.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MJCalibrateSignal.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MJCalibrateSignal.cc	(revision 9772)
@@ -0,0 +1,779 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJCalibrateSignal
+//
+// This class is reading the output written by callisto. It calibrates
+// signal and time.
+//
+// The signal and time extractors are read from the callisto-output. In
+// pricipal you could overwrite these default using the resource file,
+// but this is NOT recommended!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalibrateSignal.h"
+
+#include <TEnv.h>
+#include <TFile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MDirIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MStatusDisplay.h"
+
+#include "MGeomCam.h"
+#include "MHCamEvent.h"
+#include "MPedestalCam.h"
+#include "MBadPixelsCam.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationBlindCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationHiLoCam.h"
+
+#include "MCalibrationChargeCalc.h"
+#include "MCalibrationRelTimeCalc.h"
+
+#include "MCalibrationIntensityChargeCam.h"
+#include "MCalibrationIntensityBlindCam.h"
+#include "MCalibrationIntensityRelTimeCam.h"
+#include "MCalibrationIntensityQECam.h"
+#include "MBadPixelsIntensityCam.h"
+
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationChargeBlindCam.h"
+#include "MHCalibrationChargePINDiode.h"
+#include "MHCalibrationRelTimeCam.h"
+#include "MHCamera.h"
+
+#include "MCalibCalcFromPast.h"
+
+#include "MReadReports.h"
+#include "MReadMarsFile.h"
+#include "MRawFileRead.h"
+#include "MContinue.h"
+#include "MTriggerPatternDecode.h"
+#include "MFTriggerPattern.h"
+#include "MGeomApply.h"
+#include "MMcPedestalCopy.h"
+#include "MPointingPosCalc.h"
+#include "MInterpolatePointingPos.h"
+#include "MPedCalcFromLoGain.h"
+#include "MExtractor.h"
+#include "MExtractTimeAndCharge.h"
+#include "MExtractPINDiode.h"
+#include "MExtractBlindPixel.h"
+#include "MFCosmics.h"
+#include "MTaskEnv.h"
+#include "MCalibrateData.h"
+#include "MCalibrateRelTimes.h"
+#include "MBadPixelsMerge.h"
+#include "MBadPixelsCalc.h"
+#include "MBadPixelsTreat.h"
+#include "MFillH.h"
+#include "MWriteRootFile.h"
+
+ClassImp(MJCalibrateSignal);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fRuns to 0, fExtractor to NULL, fDataCheck to kFALSE
+//
+MJCalibrateSignal::MJCalibrateSignal(const char *name, const char *title)
+  : fIsDataCheck(kFALSE), fIsInterlaced(kTRUE), fIsRelTimesUpdate(kFALSE),
+    fIsHiLoCalibration(kTRUE)
+{
+    fName  = name  ? name  : "MJCalibrateSignal";
+    fTitle = title ? title : "Tool to calibrate data";
+}
+
+Bool_t MJCalibrateSignal::WriteResult(TObjArray &cont)
+{
+    if (fPathOut.IsNull())
+    {
+        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
+        return kTRUE;
+    }
+
+    const TString oname = Form("%s/signal%08d.root", (const char*)fPathOut, fSequence.GetSequence());
+
+    *fLog << inf << "Writing to file: " << oname << endl;
+
+    TFile file(oname, "RECREATE");
+
+    *fLog << inf << " - MStatusDisplay..." << flush;
+    if (fDisplay && fDisplay->Write()<=0)
+    {
+        *fLog << err << "Unable to write MStatusDisplay to " << oname << endl;
+        return kFALSE;
+    }
+    *fLog << inf << "ok." << endl;
+
+    return fIsInterlaced ? WriteContainer(cont) : kTRUE;
+}
+
+Bool_t MJCalibrateSignal::ReadCalibration(TObjArray &l, MBadPixelsCam &cam, MExtractor* &ext1, MExtractor* &ext2, TString &geom) const
+{
+    const TString fname = Form("%s/calib%08d.root", fPathIn.Data(), fSequence.GetSequence());
+
+    *fLog << inf << "Reading from file: " << fname << endl;
+
+    TFile file(fname, "READ");
+    if (!file.IsOpen())
+    {
+        *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
+        return kFALSE;
+    }
+
+    TObject *o = file.Get("ExtractSignal");
+    if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
+        return kFALSE;
+    }
+    ext1 = o ? (MExtractor*)o->Clone() : NULL;
+
+    o = file.Get("ExtractTime");
+    if (o && !o->InheritsFrom(MExtractor::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - ExtractTime read from " << fname << " doesn't inherit from MExtractor!" << endl;
+        return kFALSE;
+    }
+    ext2 = o ? (MExtractor*)o->Clone() : NULL;
+    if (!ext1 && !ext2)
+    {
+        *fLog << err << dbginf << "ERROR - Neither ExtractSignal nor ExrtractTime found in " << fname << "!" << endl;
+        return kFALSE;
+    }
+
+    o = file.Get("MGeomCam");
+    if (o && !o->InheritsFrom(MGeomCam::Class()))
+    {
+        *fLog << err << dbginf << "ERROR - MGeomCam read from " << fname << " doesn't inherit from MGeomCam!" << endl;
+        return kFALSE;
+    }
+    geom = o ? o->ClassName() : "";
+
+    TObjArray cont(l);
+    cont.Add(&cam);
+    return ReadContainer(cont);
+}
+
+// --------------------------------------------------------------------------
+//
+// MJCalibration allows to setup several option by a resource file:
+//   MJCalibrateSignal.DataCheck: yes,no
+//
+// For more details see the class description and the corresponding Getters
+//
+Bool_t MJCalibrateSignal::CheckEnvLocal()
+{
+
+    SetDataCheck(GetEnv("DataCheck", IsDataCheck()));
+    SetInterlaced(GetEnv("Interlaced", fIsInterlaced));
+    SetRelTimesUpdate(GetEnv("RelTimesUpdate", fIsRelTimesUpdate));
+    SetHiLoCalibration(GetEnv("HiLoCalibration", fIsHiLoCalibration));
+
+    return kTRUE;
+}
+
+Bool_t MJCalibrateSignal::ProcessFile(MPedestalCam &pedcamab, MPedestalCam &pedcambias, 
+				      MPedestalCam &pedcamextr)
+{
+    if (!fSequence.IsValid())
+    {
+        *fLog << err << "ERROR - Sequence invalid!" << endl;
+        return kFALSE;
+    }
+
+    //if (!CheckEnv())
+    //    return kFALSE;
+
+    CheckEnv();
+
+    // --------------------------------------------------------------------------------
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Calculate calibrated data from runs ";
+    *fLog << fSequence.GetName() << endl;
+    *fLog << endl;
+
+    // --------------------------------------------------------------------------------
+
+    MDirIter iter;
+    const Int_t n0 = fSequence.SetupDatRuns(iter, fPathData, "D", IsDataCheck());
+    const Int_t n1 = fSequence.GetNumDatRuns();
+    if (n0==0)
+    {
+        *fLog << err << "ERROR - No input files of sequence found!" << endl;
+        return kFALSE;
+    }
+    if (n0!=n1)
+    {
+        *fLog << err << "ERROR - Number of files found (" << n0 << ") doesn't match number of files in sequence (" << n1 << ")" << endl;
+        return kFALSE;
+    }
+
+    // Read File
+    MCalibrationIntensityChargeCam      ichcam;
+    MCalibrationIntensityQECam          iqecam;
+    MCalibrationIntensityBlindCam       iblcam;
+    MCalibrationIntensityRelTimeCam     itmcam;
+    MBadPixelsIntensityCam              ibdcam;
+
+    TObjArray interlacedcont;
+    interlacedcont.Add(&ichcam);
+    interlacedcont.Add(&iqecam);
+    interlacedcont.Add(&iblcam);
+    interlacedcont.Add(&itmcam);
+    interlacedcont.Add(&ibdcam);
+
+    MHCalibrationChargeCam      hchacam;
+    MHCalibrationChargeBlindCam hbndcam;
+    MHCalibrationChargePINDiode hpndiod;
+    MHCalibrationRelTimeCam     hrelcam;
+
+    hchacam.SetLoGain(kTRUE);
+    hchacam.SetOscillations(kFALSE);
+    hrelcam.SetOscillations(kFALSE);
+
+    interlacedcont.Add(&hchacam);
+    interlacedcont.Add(&hbndcam);
+    interlacedcont.Add(&hpndiod);
+    if (fIsRelTimesUpdate)
+      interlacedcont.Add(&hrelcam);
+
+    MCalibrationChargeCam      calcam;
+    MCalibrationQECam          qecam;
+    MCalibrationBlindCam       bndcam;
+    MCalibrationChargePINDiode pind;
+    MCalibrationRelTimeCam     tmcam;
+    MCalibrationHiLoCam        hilcam;
+
+    if (fIsHiLoCalibration)
+      interlacedcont.Add(&hilcam);      
+
+    MBadPixelsCam              badpix;
+
+    MExtractor *extractor1=0;
+    MExtractor *extractor2=0;
+    MExtractor *extractor3=0;
+    TString geom;
+
+    TObjArray calibcont;
+    calibcont.Add(&calcam);
+    calibcont.Add(&qecam);
+    calibcont.Add(&bndcam);
+    calibcont.Add(&pind);
+    calibcont.Add(&tmcam);
+
+    if (!ReadCalibration(calibcont, badpix, extractor1, extractor2, geom))
+        return kFALSE;
+
+    badpix.Print();
+
+    *fLog << all;
+    if (extractor1)
+    {
+        *fLog << underline << "Signal Extractor found in calibration file" << endl;
+        extractor1->Print();
+        *fLog << endl;
+	extractor3 = (MExtractor*)extractor1->Clone();
+    }
+    else
+        *fLog << inf << "No Signal Extractor: ExtractSignal in file." << endl;
+
+    if (extractor2)
+    {
+        *fLog << underline << "Time Extractor found in calibration file" << endl;
+        extractor2->Print();
+        *fLog << endl;
+    }
+    else
+        *fLog << inf << "No Time Extractor: ExtractTime in file." << endl;
+
+    if (!geom.IsNull())
+        *fLog << inf << "Camera geometry found in file: " << geom << endl;
+    else
+        *fLog << inf << "No Camera geometry found using default <MGeomCamMagic>" << endl;
+
+    // This is necessary for the case in which it is not in the files
+    MBadPixelsCam badcam;
+
+    // Setup Parlist
+    MParList plist;
+    plist.AddToList(this); // take care of fDisplay!
+    plist.AddToList(&badcam);
+    plist.AddToList(&calibcont);
+    plist.AddToList(&hilcam);
+
+    if (fIsInterlaced)
+      plist.AddToList(&interlacedcont);
+
+    // Setup Tasklist
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // FIXME: Move this to an intermediate class MJMagic
+    Byte_t filetype = 2;
+    /*
+    TString name = iter.Next();
+    Byte_t filetype = MRawFileRead::IsFileValid(name);
+    if (!filetype)
+        filetype = MReadMarsFile::IsFileValid(name)+1;
+    if (filetype<1||filetype>3)
+    {
+        gLog << err << "ERROR - FileType #" << (int)filetype << " of first file " << name << " unknown..." << endl;
+        return kFALSE;
+    } */
+    // 1 = raw-file
+    // 2 = raw-root file
+    // 3 = mc-raw file
+
+    MReadReports readreal;
+    readreal.AddTree("Events", "MTime.", kTRUE);
+    readreal.AddTree("Trigger");
+    readreal.AddTree("Camera");
+    readreal.AddTree("Drive");
+    readreal.AddTree("CC");
+    readreal.AddTree("Currents");
+
+    //MReadMarsFile read("Events");
+    //read.DisableAutoScheme();
+    MRawFileRead rawread(NULL);
+    if (IsDataCheck())
+        rawread.AddFiles(iter);
+    else
+        readreal.AddFiles(iter);
+
+    MInterpolatePointingPos pextr;
+//    pextr.SetDebug();  // take it out
+    pextr.AddFiles(&iter);
+    
+    MGeomApply             apply; // Only necessary to create geometry
+    if (!geom.IsNull())
+        apply.SetGeometry(geom);
+    MBadPixelsMerge        merge(&badpix);
+
+    // Make sure that pedcamab has the correct name
+    pedcamab.SetName("MPedestalFundamental");
+    pedcamextr.SetName("MPedestalFromExtractorRndm");
+    pedcambias.SetName("MPedestalFromExtractor");
+    plist.AddToList(&pedcamextr);
+    plist.AddToList(&pedcambias);
+    plist.AddToList(&pedcamab);
+
+    // Check for interleaved events
+    MTriggerPatternDecode decode;
+
+    MFTriggerPattern ftp;
+    ftp.RequireCalibration();
+    //    ftp.RequireCalibration(kTRUE);
+    //    ftp.DenyCalibration();
+    //    ftp.DenyPedestal();
+    //    ftp.DenyPinDiode();
+    //    ftp.SetInverted();
+    MContinue conttp(&ftp, "ContTrigPattern");
+    // --> tlist2
+
+    // Do signal and pedestal calculation
+    MPedCalcFromLoGain     pedlo1("MPedCalcFundamental");
+    pedlo1.SetPedestalUpdate(kTRUE);
+    pedlo1.SetNamePedestalCamOut("MPedestalFundamental");
+
+    MPedCalcFromLoGain     pedlo2("MPedCalcWithExtractorRndm");
+    pedlo2.SetPedestalUpdate(kTRUE);
+    pedlo2.SetRandomCalculation(kTRUE);
+    pedlo2.SetNamePedestalCamIn("MPedestalFundamental");
+    pedlo2.SetNamePedestalCamOut("MPedestalFromExtractorRndm");
+
+    MPedCalcFromLoGain     pedlo3("MPedCalcWithExtractor");
+    pedlo3.SetPedestalUpdate(kTRUE);
+    pedlo3.SetRandomCalculation(kFALSE);
+    pedlo3.SetNamePedestalCamIn("MPedestalFundamental");
+    pedlo3.SetNamePedestalCamOut("MPedestalFromExtractor");
+
+    if (extractor1)
+    {
+        extractor1->SetPedestals(&pedcamab);
+
+        if (extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        {
+            pedlo2.SetExtractor((MExtractTimeAndCharge*)extractor1);
+            pedlo3.SetExtractor((MExtractTimeAndCharge*)extractor1);
+            const Int_t win = ((MExtractTimeAndCharge*)extractor1)->GetWindowSizeHiGain();
+            pedlo1.SetExtractWindow(15, win);
+            pedlo2.SetExtractWindow(15, win/*obsolete*/);
+            pedlo3.SetExtractWindow(15, win/*obsolete*/);
+        }
+        else
+        {
+            // FIXME: How to get the fixed value 15 automatically?
+            const Int_t f = (Int_t)(15.5+extractor1->GetHiGainFirst());
+            const Int_t n = (Int_t)(15.5+extractor1->GetNumHiGainSamples());
+            pedlo1.SetExtractWindow(f, n);
+            pedlo2.SetExtractWindow(f, n);
+            pedlo3.SetExtractWindow(f, n);
+        }
+    }
+    if (extractor2)
+      extractor2->SetPedestals(&pedcamab);
+
+    if (extractor3)
+      extractor3->SetPedestals(&pedcamab);
+
+    MFCosmics fcosmics;
+    fcosmics.SetNamePedestalCam("MPedestalFundamental");
+    MContinue contcos(&fcosmics, "ContTrigEvts");
+    contcos.SetInverted();
+
+    MMcPedestalCopy pcopy;
+    MTaskEnv taskenv1("ExtractSignal");
+    MTaskEnv taskenv2("ExtractTime");
+    MTaskEnv taskenv3("ExtractInterlaced");
+    taskenv1.SetDefault(extractor1);
+    taskenv2.SetDefault(extractor2);
+    taskenv3.SetDefault(extractor3);
+
+    MCalibrateData         calib;
+    if (filetype==3) // MC file
+    {
+        calib.SetCalibrationMode(MCalibrateData::kFfactor);
+        calib.SetPedestalFlag(MCalibrateData::kRun);
+        // FIXME: What to do for MC files???
+        calib.AddPedestal("MPedestalCam", "MPedPhotFundamental");
+        calib.AddPedestal("MPedestalCam", "MPedPhotFromExtractor");
+        calib.AddPedestal("MPedestalCam", "MPedPhotFromExtractorRndm");
+    }
+    else
+    {
+        calib.AddPedestal("Fundamental");
+        calib.AddPedestal("FromExtractor");
+        calib.AddPedestal("FromExtractorRndm");
+        calib.SetPedestalFlag(MCalibrateData::kEvent);
+    }
+
+    MExtractPINDiode        pinext;
+    MExtractBlindPixel      bldext;
+
+    MFTriggerPattern        fcalib("CalibFilter");
+    MCalibrationChargeCalc  chcalc;
+    MCalibrationRelTimeCalc recalc;
+    MCalibCalcFromPast      pacalc;
+
+    fcalib.DenyCalibration();
+    fcalib.SetInverted();
+
+    pinext.SetPedestals(&pedcamab);
+    bldext.SetPedestals(&pedcamab);
+    chcalc.SetPedestals(&pedcamextr);
+
+    pacalc.SetChargeCalc(&chcalc);
+    if (fIsRelTimesUpdate)
+      pacalc.SetRelTimeCalc(&recalc);
+    pacalc.SetCalibrate(&calib);
+
+    //
+    // Intensity Calibration histogramming
+    //
+    MFillH filpin("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode",   "FillPINDiode");
+    MFillH filbnd("MHCalibrationChargeBlindCam", "MExtractedSignalBlindPixel", "FillBlindCam");
+    MFillH filcam("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillChargeCam");
+    MFillH filtme("MHCalibrationRelTimeCam",     "MArrivalTimeCam",            "FillRelTime");
+    MFillH filhil("MHCalibrationHiLoCam",        "MExtractedSignalCam",        "FillHiLoRatio");
+
+    filpin.SetBit(MFillH::kDoNotDisplay);
+    filbnd.SetBit(MFillH::kDoNotDisplay);
+    filcam.SetBit(MFillH::kDoNotDisplay);
+    filtme.SetBit(MFillH::kDoNotDisplay);
+    filhil.SetBit(MFillH::kDoNotDisplay);
+
+    MCalibrateRelTimes     caltm;
+    MBadPixelsCalc         bpcal;
+    MBadPixelsTreat        treat;
+
+    bpcal.SetNamePedPhotCam("MPedPhotFromExtractor");
+    treat.AddNamePedPhotCam("MPedPhotFundamental");
+    treat.AddNamePedPhotCam("MPedPhotFromExtractor");
+    treat.AddNamePedPhotCam("MPedPhotFromExtractorRndm");
+    if (!extractor2 && !extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        treat.SetProcessTimes(kFALSE);
+
+
+    MHCamEvent evt0(0, "PedFLG",      "Pedestal from Lo Gain;;P [fadc/sl]");
+    MHCamEvent evt1(2, "PedRmsFLG",   "Pedestal RMS from Lo Gain;;\\sigma_{p} [fadc/sl]");
+    MHCamEvent evt2(0, "Extra'd",     "Extracted Signal;;S [fadc/sl]");
+    MHCamEvent evt3(4, "PedPhot",     "Calibrated Pedestal;;P [\\gamma]");
+    MHCamEvent evt4(5, "PedRMS",      "Calibrated Pedestal RMS;;\\sigma_{p} [\\gamma]");
+    MHCamEvent evt5(0, "Interp'd",    "Interpolated Signal;;S [\\gamma]");
+    MHCamEvent evt6(2, "Unsuitable",  "Unsuitable event ratio;;%");
+    MHCamEvent evt7(0, "Times",       "Arrival Time;;T [slice]");
+    //    MHCamEvent evt8(0, "HiLoConv",    "Ratio Hi-Lo Gain Signal;;Ratio [1]");
+    //    MHCamEvent evt9(5, "HiLoDiff",    "Time Diff. Hi-Lo Gain Signal;;\\Delta T [3.33ns]");
+
+    evt0.EnableVariance();
+    evt1.EnableVariance();
+    evt2.EnableVariance();
+    evt3.EnableVariance();
+    evt4.EnableVariance();
+    evt5.EnableVariance();
+    evt7.EnableVariance();
+    //    evt8.EnableVariance();
+    //    evt9.EnableVariance();
+
+    MFillH fill0(&evt0, "MPedestalFundamental",   "FillPedFLG");
+    MFillH fill1(&evt1, "MPedestalFromExtractor", "FillPedRmsFLG");
+    MFillH fill2(&evt2, "MExtractedSignalCam",    "FillExtracted");
+    MFillH fill3(&evt3, "MPedPhotFundamental",    "FillPedPhot");
+    MFillH fill4(&evt4, "MPedPhotFromExtractor",  "FillPedRMS");
+    MFillH fill5(&evt5, "MCerPhotEvt",            "FillInterpolated");
+    MFillH fill6(&evt6, "MBadPixelsCam",          "FillUnsuitable");
+    MFillH fill7(&evt7, "MArrivalTime",           "FillTimes");
+    //    MFillH fill8(&evt8, "MCalibrationHiLoCam",    "FillRatio");
+    //    MFillH fill9(&evt9, "MCalibrationHiLoCam",    "FillDiff");
+
+    // The second rule is for the case reading raw-files!
+    MWriteRootFile write(2, Form("%s{s/_D_/_Y_}{s/.raw$/.root}", fPathOut.Data()), fOverwrite);
+    // Run Header
+    write.AddContainer("MRawRunHeader",             "RunHeaders");
+    write.AddContainer("MBadPixelsCam",             "RunHeaders");
+    write.AddContainer("MGeomCam",                  "RunHeaders");
+    // Monte Carlo Headers
+    write.AddContainer("MMcTrigHeader",             "RunHeaders", kFALSE);
+    write.AddContainer("MMcConfigRunHeader",        "RunHeaders", kFALSE);
+    write.AddContainer("MMcCorsikaRunHeader",       "RunHeaders", kFALSE);
+    // Monte Carlo
+    write.AddContainer("MMcEvt",                    "Events",     kFALSE);
+    write.AddContainer("MMcTrig",                   "Events",     kFALSE);
+    // Data
+    write.AddContainer("MCerPhotEvt",               "Events");
+    write.AddContainer("MPedPhotFundamental",       "Events");
+    write.AddContainer("MPedPhotFromExtractor",     "Events");
+    write.AddContainer("MPedPhotFromExtractorRndm", "Events");
+    write.AddContainer("MTime",                     "Events",     kFALSE);
+    write.AddContainer("MRawEvtHeader",             "Events");
+    write.AddContainer("MArrivalTime",              "Events",     kFALSE);
+    // Slow-Control: Current
+    write.AddContainer("MTimeCurrents",             "Currents",   kFALSE);
+    write.AddContainer("MCameraDC",                 "Currents",   kFALSE);
+    write.AddContainer("MReportCurrents",           "Currents",   kFALSE);
+    // Slow-Control: Camera
+    write.AddContainer("MReportCamera",             "Camera",     kFALSE);
+    write.AddContainer("MTimeCamera",               "Camera",     kFALSE);
+    write.AddContainer("MCameraAUX",                "Camera",     kFALSE);
+    write.AddContainer("MCameraCalibration",        "Camera",     kFALSE);
+    write.AddContainer("MCameraCooling",            "Camera",     kFALSE);
+    write.AddContainer("MCameraHV",                 "Camera",     kFALSE);
+    write.AddContainer("MCameraLV",                 "Camera",     kFALSE);
+    write.AddContainer("MCameraLids",               "Camera",     kFALSE);
+    // Slow-Control: Trigger
+    write.AddContainer("MReportTrigger",            "Trigger",    kFALSE);
+    write.AddContainer("MTimeTrigger",              "Trigger",    kFALSE);
+    // Slow-Control: Drive
+    write.AddContainer("MPointingPos",              "Events",     kFALSE);
+    write.AddContainer("MReportDrive",              "Drive",      kFALSE);
+    write.AddContainer("MTimeDrive",                "Drive",      kFALSE);
+    // Slow-Control: Central Control
+    write.AddContainer("MReportCC",                 "CC",         kFALSE);
+    write.AddContainer("MTimeCC",                   "CC",         kFALSE);
+
+    // Now setup tasklist for events
+    MTaskList tlist2;
+
+    tlist2.AddToList(&decode);
+    tlist2.AddToList(&apply);
+    tlist2.AddToList(&merge);
+    if (filetype==3)
+        tlist2.AddToList(&pcopy);
+    else
+    {
+        tlist2.AddToList(&pedlo1);
+        tlist2.AddToList(&pedlo2);
+        tlist2.AddToList(&pedlo3);
+    }
+    if (fIsInterlaced)
+      {
+	pinext.SetFilter(&fcalib);
+	bldext.SetFilter(&fcalib);
+	taskenv3.SetFilter(&fcalib);
+	pacalc.SetFilter(&fcalib);
+	filcam.SetFilter(&fcalib);
+	filtme.SetFilter(&fcalib);
+	filbnd.SetFilter(&fcalib);
+	filpin.SetFilter(&fcalib);
+	chcalc.SetFilter(&fcalib);
+	recalc.SetFilter(&fcalib);
+
+        tlist2.AddToList(&fcalib);
+        tlist2.AddToList(&pinext);
+        tlist2.AddToList(&bldext);
+	tlist2.AddToList(&taskenv3);
+        tlist2.AddToList(&pacalc);
+        tlist2.AddToList(&filcam);
+	if (fIsRelTimesUpdate)
+	  tlist2.AddToList(&filtme);
+        tlist2.AddToList(&filbnd);
+        tlist2.AddToList(&filpin);
+        tlist2.AddToList(&chcalc);
+	if (fIsRelTimesUpdate)
+	  tlist2.AddToList(&recalc);
+      }
+
+    tlist2.AddToList(&conttp);
+    if (extractor1)
+      tlist2.AddToList(&taskenv1);
+    if (extractor2)
+      tlist2.AddToList(&taskenv2);
+    tlist2.AddToList(&fill0);
+    tlist2.AddToList(&fill1);
+    tlist2.AddToList(&contcos);
+    if (fIsHiLoCalibration)
+      tlist2.AddToList(&filhil);
+    tlist2.AddToList(&fill2);
+    tlist2.AddToList(&calib);
+    if (extractor2 || extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        tlist2.AddToList(&caltm);
+
+    tlist2.AddToList(&bpcal);
+    tlist2.AddToList(&treat);
+    tlist2.AddToList(&fill6);
+    tlist2.AddToList(&fill3);
+    tlist2.AddToList(&fill4);
+    tlist2.AddToList(&fill5);
+    if (extractor2 || extractor1->InheritsFrom("MExtractTimeAndCharge"))
+        tlist2.AddToList(&fill7);
+
+    if (fIsHiLoCalibration)
+      {
+	//	tlist2.AddToList(&fill8);
+	//	tlist2.AddToList(&fill9);
+      }
+    // Setup List for Drive-tree
+    MPointingPosCalc pcalc;
+
+    // Now setup main tasklist
+    tlist.AddToList(IsDataCheck() ? (MTask*)&rawread : (MTask*)&readreal);
+    tlist2.AddToList(&pextr);
+    tlist.AddToList(&tlist2, IsDataCheck()?"All":"Events");
+
+    //
+    // !!! Replaced by MInterpolatePointingPos !!!
+    //
+    //    if (!IsDataCheck())
+    //        tlist.AddToList(&pcalc, "Drive");
+
+
+    tlist.AddToList(&write);
+
+    // Create and setup the eventloop
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+    if (!SetupEnv(evtloop))
+        return kFALSE;
+
+    // Execute first analysis
+    if (!evtloop.Eventloop(fMaxEvents))
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    tlist.PrintStatistics();
+
+    DisplayResult(plist);
+
+    if (!WriteResult(interlacedcont))
+        return kFALSE;
+
+    *fLog << all << GetDescriptor() << ": Done." << endl;
+    *fLog << endl << endl;
+
+    return kTRUE;
+}
+
+
+void MJCalibrateSignal::DisplayResult(MParList &plist)
+{
+
+    if (!fDisplay)
+        return;
+
+    if (!fIsHiLoCalibration)
+      return;
+
+    //    DrawTab(plist, "MHCalibrationHiLoCam", "HiLo",  " nonew");
+
+    //
+    // Get container from list
+    //
+    MGeomCam        &geomcam = *(MGeomCam*)plist.FindObject("MGeomCam");
+    MCalibrationHiLoCam *cam = (MCalibrationHiLoCam*)plist.FindObject("MCalibrationHiLoCam");
+
+    // Create histograms to display
+    MHCamera disp1 (geomcam, "HiLoConv", "Ratio Amplification HiGain vs. LoGain (Charges)");
+    MHCamera disp2 (geomcam, "HiLoDiff", "Arrival Time Diff. HiGain vs. LoGain (Times)");
+
+    disp1.SetCamContent(*cam,  0);
+    disp1.SetCamError(  *cam,  1);
+    disp2.SetCamContent(*cam,  5);
+    disp2.SetCamError(  *cam,  6);
+
+    disp1.SetYTitle("R [1]");
+    disp2.SetYTitle("\\Delta T [FADC sl.]");
+
+
+    TCanvas &c1 = fDisplay->AddTab("HiLoConv");
+    c1.Divide(2,3);
+    
+    disp1.CamDraw(c1, 1, 2, 1);
+    disp2.CamDraw(c1, 2, 2, 1);
+}
+
+void MJCalibrateSignal::DrawTab(MParList &plist, const char *cont, const char *name, Option_t *opt)
+{
+    TObject *obj = plist.FindObject(cont);
+    if (!obj)
+        return;
+
+    fDisplay->AddTab(name);
+    obj->DrawClone(opt);
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/MJCalibrateSignal.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MJCalibrateSignal.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MJCalibrateSignal.h	(revision 9772)
@@ -0,0 +1,52 @@
+#ifndef MARS_MJCalibrateSignal
+#define MARS_MJCalibrateSignal
+
+#ifndef MARS_MJob
+#include "MJob.h"
+#endif
+
+class TEnv;
+class TList;
+
+class MTask;
+class MParList;
+class MGeomCam;
+class MSequence;
+class MExtractor;
+class MPedestalCam;
+class MBadPixelsCam;
+
+class MJCalibrateSignal : public MJob
+{
+private:
+
+    Bool_t fIsDataCheck;
+    Bool_t fIsInterlaced;               // Distinguish interlaced from other calibration
+    Bool_t fIsRelTimesUpdate;           // Choose to update relative times from interlaced
+    Bool_t fIsHiLoCalibration;          // Choose to calibrate the high-gain vs. low-gains
+    
+    Bool_t CheckEnvLocal();
+
+    void   DisplayResult(MParList &plist);
+    void   DrawTab(MParList &plist, const char *cont, const char *name, Option_t *opt);
+
+    Bool_t WriteResult(TObjArray &cont);
+    Bool_t ReadCalibration(TObjArray &o, MBadPixelsCam &bpix,
+                           MExtractor* &ext1, MExtractor* &ext2, TString &geom) const;
+
+    Bool_t IsDataCheck() const { return fIsDataCheck; }
+    void SetDataCheck(Bool_t b) { fIsDataCheck = b; }
+
+public:
+    MJCalibrateSignal(const char *name=NULL, const char *title=NULL);
+
+    Bool_t ProcessFile(MPedestalCam &camab, MPedestalCam &cam1, MPedestalCam &cam2);
+
+    void SetInterlaced     ( const Bool_t b=kTRUE )  { fIsInterlaced      = b; }
+    void SetRelTimesUpdate ( const Bool_t b=kTRUE )  { fIsRelTimesUpdate  = b; }
+    void SetHiLoCalibration( const Bool_t b=kTRUE )  { fIsHiLoCalibration = b; }
+
+    ClassDef(MJCalibrateSignal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mmpi/MPointingPosCalcWA.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MPointingPosCalcWA.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MPointingPosCalcWA.cc	(revision 9772)
@@ -0,0 +1,181 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPointingPosCalc
+//
+// Currently:
+//
+//  * MC files:  Copy the simulated telescope position (Telescope Theta,
+//               Telescope Phi in MMcEvt) to MPointingPosition
+//
+//  * Real Data: Copy the nominal poiting position (Nominal Zd, Nominal Az
+//               in MReportDrive) to MPointingPosition
+//
+// Future: Interpolate the pointing position for each event between two
+//         consecutive drive reports.
+//
+// Input Container:
+//   MRawRunHeader
+//   [MMcEvt, MReportDrive]
+//
+// Output Container:
+//   MPointingPosition
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPointingPosCalcWA.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MVector3.h"
+
+#include "MPointingPos.h"
+#include "MAstro.h"
+#include "MObservatory.h"
+#include "MAstroSky2Local.h"
+#include "MRawRunHeader.h"
+#include "MReportDrive.h"
+#include "MMcEvt.hxx"
+
+ClassImp(MPointingPosCalcWA);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Search for MRawRunHeader. Get the run type from there. Depending on
+// the run type search either for MMcEvt or MReportDrive.
+//
+Bool_t MPointingPosCalcWA::ReInit(MParList *plist)
+{
+    fObs = (MObservatory*)plist->FindCreateObj("MObservatory");
+    if (!fObs)
+    {
+       *fLog << err << "MObservatory not found... aborting." << endl;
+        return kFALSE; 
+    }
+
+    fRunHeader = (MRawRunHeader*)plist->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRunType = fRunHeader->GetRunType();
+
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTData:
+        fReport = (MReportDrive*)plist->FindObject("MReportDrive");
+        if (!fReport)
+        {
+            *fLog << err << "MReportDrive not found... will set Az and Zd to a fixed value." << endl;
+            return kTRUE;
+        }
+        return kTRUE;
+
+    case MRawRunHeader::kRTMonteCarlo:
+        fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+        if (!fMcEvt)
+        {
+            *fLog << err << "MMcEvt not found... aborting." << endl;
+            return kFALSE;
+        }
+        return kTRUE;
+
+    case MRawRunHeader::kRTPedestal:
+        *fLog << err << "Cannot work in a pedestal Run!... aborting." << endl;
+        return kFALSE;
+
+    case MRawRunHeader::kRTCalibration:
+        *fLog << err << "Cannot work in a calibration Run!... aborting." << endl;
+        return kFALSE;
+
+    default:
+        *fLog << err << "Run Type " << fRunType << " unknown!... aborting." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Search for 'MPointingPos'. Create if not found.
+//
+Int_t MPointingPosCalcWA::PreProcess(MParList *plist)
+{
+    fPosition = (MPointingPos*)plist->FindCreateObj("MPointingPos");
+    return fPosition ? kTRUE : kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  See class description.
+//
+Int_t MPointingPosCalcWA::Process()
+{
+
+    const char plus = '+';
+    Char_t Rsgn;
+    UShort_t Rhour, Rmin, Rsec;
+    Double_t ra;
+
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTData:
+     if(!fReport)
+     {
+        MTime start = fRunHeader->GetRunStart();
+
+        MVector3 v;
+        v.SetRaDec(fRa,fDec);
+        v *= MAstroSky2Local(start,*fObs);
+        Double_t ZA = v.Theta()*180./acos(-1.);
+        Double_t Az = v.Phi()*180./acos(-1.);
+//        cout << " Za = " << ZA << " v.Theta() " << v.Theta() << " Az " << Az << " v.Phi " << v.Phi() << endl;
+        fPosition->SetLocalPosition(ZA, Az);
+        MAstro::Rad2Hms(fRa, Rsgn, Rhour, Rmin, Rsec);
+        if (Rsgn==plus) ra = Rhour + Rmin/60. + Rsec/3600.;
+        else ra = - (Rhour + Rmin/60. + Rsec/3600.);
+        fPosition->SetSkyPosition(ra, TMath::RadToDeg()*fDec);
+        return kTRUE;
+     }
+     else 
+     {
+        fPosition->SetLocalPosition(fReport->GetNominalZd(), fReport->GetNominalAz());
+        fPosition->SetSkyPosition(fReport->GetRa(), fReport->GetDec());
+        return kTRUE;
+     }
+
+    case MRawRunHeader::kRTMonteCarlo:
+        fPosition->SetLocalPosition(fMcEvt->GetTelescopeTheta()*TMath::RadToDeg(), fMcEvt->GetTelescopePhi()*TMath::RadToDeg());
+        return kTRUE;
+    }
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mmpi/MPointingPosCalcWA.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MPointingPosCalcWA.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MPointingPosCalcWA.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MPointingPositionCalcWA
+#define MARS_MPointingPositionCalcWA
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcEvt;
+class MReportDrive;
+class MPointingPos;
+class MRawRunHeader;
+class MObservatory;
+
+class MPointingPosCalcWA : public MTask
+{
+private:
+    MMcEvt        *fMcEvt;    //! MMcEvt to get simulated poiting position from
+    MReportDrive  *fReport;   //! MReportDrive to get real poiting position from
+    MPointingPos  *fPosition; //! Output container to store pointing position
+    MObservatory  *fObs;
+    MRawRunHeader *fRunHeader;
+    Double_t fRa;
+    Double_t fDec;
+    
+
+    UShort_t fRunType;            //! Run Type to decide where to get pointing position from
+
+    Bool_t ReInit(MParList *plist);
+    Int_t  PreProcess(MParList *plist);
+    Int_t  Process();
+
+public:
+    MPointingPosCalcWA()
+    {
+        fName  = "MPointingPosCalcWA";
+        fTitle = "Task calculating the pointing position";
+    }
+
+    void SetRaDec(Double_t ra, Double_t dec)  {fRa = ra; fDec = dec;}
+
+    ClassDef(MPointingPosCalcWA, 0) //Task calculating the pointing position
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mmpi/MSkyPlot.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MSkyPlot.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MSkyPlot.cc	(revision 9772)
@@ -0,0 +1,1346 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Daniel Mazin, 8/2004 <mailto:mazin@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSkyPlot
+//
+// Create a false source plot. For the Binning in x,y the object MBinning
+// "BinningFalseSource" is taken from the paremeter list.
+//
+// The binning in alpha is currently fixed as 18bins from 0 to 90deg.
+//
+// If MTime, MObservatory and MPointingPos is available in the paremeter
+// list each image is derotated.
+//
+// MSkyPlot fills a 3D histogram with alpha distribution for
+// each (derotated) x and y position.
+//
+// Only a radius of 1.2deg around the camera center is taken into account.
+//
+// The displayed histogram is the projection of alpha<fAlphaCut into
+// the x,y plain and the projection of alpha>90-fAlphaCut
+//
+// By using the context menu (find it in a small region between the single
+// pads) you can change the AlphaCut 'online'
+//
+// Each Z-Projection (Alpha-histogram) is scaled such, that the number
+// of entries fits the maximum number of entries in all Z-Projections.
+// This should correct for the different acceptance in the center
+// and at the border of the camera. This, however, produces more noise
+// at the border.
+//
+// Here is a slightly simplified version of the algorithm:
+// ------------------------------------------------------
+//    MHillas hil; // Taken as second argument in MFillH
+//
+//    MSrcPosCam src;
+//    MHillasSrc hsrc;
+//    hsrc.SetSrcPos(&src);
+//
+//    for (int ix=0; ix<nx; ix++)
+//        for (int iy=0; iy<ny; iy++)
+//        {
+//            TVector2 v(cx[ix], cy[iy]); //cx center of x-bin ix
+//            if (rho!=0)                 //cy center of y-bin iy
+//                v=v.Rotate(rho);         //image rotation angle
+//
+//            src.SetXY(v);               //source position in the camera
+//
+//            if (!hsrc.Calc(hil))        //calc source dependant hillas
+//                return;
+//
+//            //fill absolute alpha into histogram
+//            const Double_t alpha = hsrc.GetAlpha();
+//            fHist.Fill(cx[ix], cy[iy], TMath::Abs(alpha), w);
+//        }
+//    }
+//
+// Use MHFalse Source like this:
+// -----------------------------
+//    MFillH fill("MSkyPlot", "MHillas");
+// or
+//    MSkyPlot hist;
+//    hist.SetAlphaCut(12.5);  // The default value
+//    hist.SetBgmean(55);      // The default value
+//    MFillH fill(&hist, "MHillas");
+//
+// To be implemented:
+// ------------------
+//  - a switch to use alpha or |alpha|
+//  - taking the binning for alpha from the parlist (binning is
+//    currently fixed)
+//  - a possibility to change the fit-function (eg using a different TF1)
+//  - a possibility to change the fit algorithm (eg which paremeters
+//    are fixed at which time)
+//  - use a different varaible than alpha
+//  - a possiblity to change the algorithm which is used to calculate
+//    alpha (or another parameter) is missing (this could be done using
+//    a tasklist somewhere...)
+//  - a more clever (and faster) algorithm to fill the histogram, eg by
+//    calculating alpha once and fill the two coils around the mean
+//  - more drawing options...
+//  - Move Significance() to a more 'general' place and implement
+//    also different algorithms like (Li/Ma)
+//  - implement fit for best alpha distribution -- online (Paint)
+//  - currently a constant pointing position is assumed in Fill()
+//  - the center of rotation need not to be the camera center
+//  - ERRORS on each alpha bin to estimate the chi^2 correctly!
+//    (sqrt(N)/binwidth) needed for WOlfgangs proposed caluclation
+//    of alpha(Li/Ma)
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSkyPlot.h"
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TH1.h>
+#include <TGraph.h>
+#include <TStyle.h>
+#include <TLatex.h>
+#include <TCanvas.h>
+#include <TPaveLabel.h>
+#include <TPaveText.h>
+#include <TStopwatch.h>
+#include <TFile.h>
+
+#include "MGeomCam.h"
+#include "MSrcPosCam.h"
+#include "MReportDrive.h"
+#include "MHillasSrc.h"
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MNewImagePar.h"
+#include "MHadronness.h"
+#include "MTime.h"
+#include "MObservatory.h"
+#include "MPointingPos.h"
+#include "MAstroCatalog.h"
+#include "MAstroSky2Local.h"
+#include "MStarCamTrans.h"
+#include "MStatusDisplay.h"
+#include "MMath.h"
+#include "MSupercuts.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include <TOrdCollection.h>
+
+ClassImp(MSkyPlot);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MSkyPlot::MSkyPlot(const char *name, const char *title)
+  : fGeomCam(NULL),   
+    fTime(NULL),      
+    fPointPos(NULL),  
+    fRepDrive(NULL),  
+    fSrcPosCam(NULL), 
+    fPntPosCam(NULL), 
+    fObservatory(NULL),
+    fHillas(NULL),    
+    fHillasExt(NULL), 
+    fHillasSrc(NULL), 
+    fNewImagePar(NULL),
+    fMm2Deg(-1)
+{
+
+  *fLog << warn << "entering default constructor in MSkyPlot" << endl; 
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MSkyPlot";
+    fTitle = title ? title : "sky plot vs x, y";
+
+    fSetCenter=kTRUE;
+
+    fHistSignif.SetDirectory(NULL);
+    fHistNexcess.SetDirectory(NULL);
+    fHistOn.SetDirectory(NULL);
+    fHistSignifGaus.SetDirectory(NULL);
+
+    fHistSignif.UseCurrentStyle();
+    fHistNexcess.UseCurrentStyle();
+    fHistOn.UseCurrentStyle();
+    fHistSignifGaus.UseCurrentStyle();
+
+    fHistSignif.SetName("SkyPlotSignif");
+    fHistSignif.SetTitle("Sky Plot of significance vs x, y");
+    fHistSignif.SetXTitle("x [\\circ]");
+    fHistSignif.SetYTitle("y [\\circ]");
+
+    fHistNexcess.SetName("SkyPlotNexcess");
+    fHistNexcess.SetTitle("Sky Plot of number of excess vs x, y");
+    fHistNexcess.SetXTitle("x [\\circ]");
+    fHistNexcess.SetYTitle("y [\\circ]");
+
+    fHistOn.SetName("SkyPlotOn");
+    fHistOn.SetTitle("Sky Plot of number of On events vs x, y");
+    fHistOn.SetXTitle("x [\\circ]");
+    fHistOn.SetYTitle("y [\\circ]");
+
+    fHistSignifGaus.SetName("SignifDistrib");
+    fHistSignifGaus.SetTitle("Distribution of the significances from the sky plot");
+    fHistSignifGaus.SetXTitle("significance");
+    fHistSignifGaus.SetYTitle("counts");
+
+    // set some values for the sky plot geometry:
+    fMinXGrid    =-1.;  		// [deg] 
+    fMaxXGrid    = 1.;             //  [deg] , right edge of the skyplot
+    fMinYGrid    =-1.;            //  [deg] , upper edge of the skyplot
+    fMaxYGrid    = 1.;             //  [deg] , lower edge of the skyplot
+    fBinStepGrid = 0.05;         //  [deg], 
+    fAlphaONMax  = 5.;           //  [deg] , upper cut for alpha ON region in the alpha plot
+                      // [deg], ON region in the alpha plot, maybe 5 deg is better
+                      // NOTE: up to now only values of 5, 10, 15, 20 degrees are possible
+// ra,dec lines from wolfgang:
+    fGridBinning = 0.50;   // degrees
+    fGridFineBin = 0.01;   // degrees
+
+// elapsed time:
+    fElaTime = 0.;
+
+    // some filter cuts:
+    fSizeMin    = 2000.;             // min size in photons
+    fSizeMax    = 100000.;             // max size in photons
+    fLeakMax    = 0.25;             // leakmax  in per cent
+    fMaxDist = 1.4;          // dist max cut (ever possible)
+    fMinDist = 0.1;          // dist max cut (ever possible)
+    fHadrCut = 0.2;          // hadronness cut
+
+    fNumBinsAlpha   = 36; 	 // number of bins for alpha histograms
+    fAlphaLeftEdge  = 0.;        // [deg] left edge
+    fAlphaRightEdge = 90.;       // [deg] left edge
+
+    fAlphaBgLow     = 30.;
+    fAlphaBgUp      = 90.;
+
+    {
+// SET DEFAULT VALUES HERE	
+    fLengthUp[0] =  0.2;
+    fLengthUp[1] =  0.0;
+    fLengthUp[2] =  0.0;
+    fLengthUp[3] =  0.0;
+    fLengthUp[4] =  0.0;
+    fLengthUp[5] =  0.0;
+    fLengthUp[6] =  0.0;
+    fLengthUp[7] =  0.0;
+
+    fLengthLo[0] =  0.;
+    fLengthLo[1] =  0.;
+    fLengthLo[2] =  0.;
+    fLengthLo[3] =  0.;
+    fLengthLo[4] =  0.;
+    fLengthLo[5] =  0.;
+    fLengthLo[6] =  0.;
+    fLengthLo[7] =  0.;
+
+    fWidthUp[0] =  0.1;
+    fWidthUp[1] =  0.0;
+    fWidthUp[2] =  0.0;
+    fWidthUp[3] =  0.0;
+    fWidthUp[4] =  0.0;
+    fWidthUp[5] =  0.0;
+    fWidthUp[6] =  0.0;
+    fWidthUp[7] =  0.0;
+
+    fWidthLo[0] =  0.;
+    fWidthLo[1] =  0.;
+    fWidthLo[2] =  0.;
+    fWidthLo[3] =  0.;
+    fWidthLo[4] =  0.;
+    fWidthLo[5] =  0.;
+    fWidthLo[6] =  0.;
+    fWidthLo[7] =  0.;
+
+    fDistUp[0] =  1.e10;
+    fDistUp[1] =  0.0;
+    fDistUp[2] =  0.0;
+    fDistUp[3] =  0.0;
+    fDistUp[4] =  0.0;
+    fDistUp[5] =  0.0;
+    fDistUp[6] =  0.0;
+    fDistUp[7] =  0.0;
+
+    fDistLo[0] =  0.0;
+    fDistLo[1] =  0.0;
+    fDistLo[2] =  0.0;
+    fDistLo[3] =  0.0;
+    fDistLo[4] =  0.0;
+    fDistLo[5] =  0.0;
+    fDistLo[6] =  0.0;
+    fDistLo[7] =  0.0;
+    }
+
+    fSaveAlphaPlots=kTRUE;
+    fSaveSkyPlots=kTRUE;
+    fSaveNexPlot=kTRUE;
+    fUseRF=kFALSE;
+    fAlphaHName = "alphaplot.root";
+    fSkyHName   = "skyplot.root";
+    fNexHName   = "Nexcess.gif";
+
+    fHistAlpha = new TOrdCollection();
+    fHistAlpha->SetOwner();    
+
+}
+
+MSkyPlot::~MSkyPlot()
+{
+
+  if (fHistAlpha)
+    delete fHistAlpha;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th hist 
+//
+TH1D *MSkyPlot::GetAlphaPlot(Int_t i)
+{
+  if (GetSize() == 0)
+    return NULL;
+
+  return static_cast<TH1D*>(i==-1 ? fHistAlpha->At(GetSize()/2+1) : fHistAlpha->At(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th hist 
+//
+const TH1D *MSkyPlot::GetAlphaPlot(Int_t i) const 
+{
+  if (GetSize() == 0)
+    return NULL;
+
+  return static_cast<TH1D*>(i==-1 ? fHistAlpha->At(GetSize()/2+1) : fHistAlpha->At(i));
+}
+
+
+void MSkyPlot::ReadCuts(const TString parSCinit="OptSCParametersONOFFThetaRange0_1570mRad.root")
+{
+
+cout << " parameters read from file: " << parSCinit << endl;
+    //--------------------------------
+    // create container for the supercut parameters
+    // and set them to their initial values
+    MSupercuts super;
+
+  // read the cuts coefficients
+    TFile inparam(parSCinit);
+    super.Read("MSupercuts");
+    inparam.Close();
+    *fLog << "MFindSupercutsONOFF::FindParams; initial values of parameters are taken from file "
+          << parSCinit << endl;
+
+    TArrayD params = super.GetParameters();
+    TArrayD steps  = super.GetStepsizes();
+ // TMP2
+    if (params.GetSize() == steps.GetSize())
+    {
+            *fLog << "SC parameters and Setps are: " << endl;
+            for (Int_t z = 0; z < params.GetSize(); z++)
+            {
+                cout << params[z] << setw(20) << steps[z] << endl;
+            }
+    }
+ // ENDTMP2
+    for (Int_t i=0; i<8; i++)
+    {
+	fLengthUp[i]  = params[i];
+        fLengthLo[i] = params[i+8];
+	fWidthUp[i]   = params[i+16];
+	fWidthLo[i]  = params[i+24];
+        fDistUp[i]    = params[i+32];
+        fDistLo[i]   = params[i+40];
+    }
+}
+
+void MSkyPlot::SetSkyPlot(Float_t xmin, Float_t xmax, Float_t ymin, Float_t ymax, Float_t step)
+{
+    Float_t temp;
+
+    if (xmax<xmin)
+    {
+        *fLog << warn << "SetSkyPlot: xmax is smaller xmin ... exchanging them." << endl;
+	temp = xmax;
+	xmax = xmin;
+	xmin = temp;
+    }	
+
+    if (ymax<ymin)
+    {
+        *fLog << warn << "SetSkyPlot: ymax is smaller ymin ... exchanging them." << endl;
+	temp = ymax;
+	ymax = ymin;
+	ymin = temp;
+    }	
+    
+    if (step<0)
+        *fLog << warn << "SetSkyPlot: step<0... taking absolute value." << endl;
+
+    fBinStepGrid = TMath::Abs(step);
+    fMinXGrid    = xmin;
+    fMaxXGrid    = xmax;
+    fMinYGrid    = ymin;
+    fMaxYGrid    = ymax;
+    
+    *fLog << endl <<  inf << " SetSkyPlot: fMinXGrid, fMaxXGrid, fMinYGrid, fMaxYGrid, fBinStepGrid: " << endl;
+    *fLog << inf << "           " << fMinXGrid << ", " << fMaxXGrid << ", " << fMinYGrid << ", " 
+                 << fMaxYGrid<< ", " << fBinStepGrid << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the alpha cut (|alpha|<fAlphaCut) which is use to estimate the
+// number of excess events
+//
+void MSkyPlot::SetAlphaCut(Float_t alpha)
+{
+    if (alpha<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    fAlphaONMax = TMath::Abs(alpha);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the upper and lower limit for the background region in the alpha plot
+// to estimate the number of background events
+//
+void MSkyPlot::SetAlphaBGLimits(Float_t alphalow, Float_t alphaup)
+{
+    Float_t alphatemp;
+    if (alphalow<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    if (alphaup<0)
+        *fLog << warn << "Alpha<0... taking absolute value." << endl;
+
+    if (TMath::Abs(alphaup)<TMath::Abs(alphalow)) {
+        *fLog << warn << "AlphaLow > AlphaUp... exchanging limits." << endl;
+	alphatemp = alphaup;
+	alphaup = alphalow;
+	alphalow = alphatemp;
+    }
+
+    fAlphaBgLow = TMath::Abs(alphalow);
+    fAlphaBgUp  = TMath::Abs(alphaup);
+}
+
+// calculate the values for the cuts:
+Double_t MSkyPlot::CalcLimit(Double_t *a, Double_t ls, Double_t ls2, Double_t dd2)
+{
+
+    Double_t  limit = a[0] + a[1] * dd2 +
+                      ls  * (a[3] + a[4] * dd2) +
+                      ls2 * (a[6] + a[7] * dd2);
+
+     return limit;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings (takes BinningFalseSource) and prepare filling of the
+// histogram.
+//
+// Also search for MTime, MObservatory and MPointingPos
+// 
+Int_t MSkyPlot::PreProcess(MParList *plist)
+{
+
+  *fLog << warn << "entering PreProcess in MSkyPlot::PreProcess" << endl; 
+  
+    fGeomCam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!fGeomCam)
+    {
+        *fLog << err << "MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = fGeomCam->GetConvMm2Deg();
+
+    fRepDrive = (MReportDrive*)plist->FindObject(AddSerialNumber("MReportDrive"));
+    if (!fRepDrive)
+        *fLog << warn << "MReportDrive not found... could be problem for sky map." << endl;
+
+
+    fSrcPosCam = (MSrcPosCam*)plist->FindCreateObj(AddSerialNumber("MSrcPosCam"));
+    if (!fSrcPosCam)
+        *fLog << warn << "MSrcPosCam not found... no sky map." << endl;
+
+/*
+    fPntPosCam = (MSrcPosCam*)plist->FindObject(AddSerialNumber("MPntPosCam"));
+    if (!fPntPosCam)
+        *fLog << warn << "MPntPosCam not found... no sky map." << endl;
+*/
+
+    fPointPos = (MPointingPos*)plist->FindObject(AddSerialNumber("MPointingPos"));
+    if (!fPointPos)
+        *fLog << warn << "MPointingPos not found... no sky map." << endl;
+
+    fTime = (MTime*)plist->FindObject(AddSerialNumber("MTime"));
+    if (!fTime)
+        *fLog << warn << "MTime not found... could be problem for sky map." << endl;
+
+    fObservatory = (MObservatory*)plist->FindObject(AddSerialNumber("MObservatory"));
+    if (!fObservatory)
+        *fLog << warn << "MObservatory not found... no sky map." << endl;
+
+
+    fHillas = (MHillas*)plist->FindObject(AddSerialNumber("MHillas"));
+    if (!fHillas)
+        *fLog << err << "MHillas not found... no sky map." << endl;
+
+    fHillasExt = (MHillasExt*)plist->FindObject(AddSerialNumber("MHillasExt"));
+    if (!fHillasExt)
+        *fLog << err << "MHillasExt not found... no sky map." << endl;
+
+    fHillasSrc = (MHillasSrc*)plist->FindObject(AddSerialNumber("MHillasSrc"));
+    if (!fHillasSrc)
+        *fLog << err << "MHillasSrc not found... no sky map." << endl;
+
+    fNewImagePar = (MNewImagePar*)plist->FindObject(AddSerialNumber("MNewImagePar"));
+    if (!fNewImagePar)
+        *fLog << err << "MNewImagePar not found... no sky map." << endl;
+
+    if(fUseRF)
+    {
+       fHadron = (MHadronness*)plist->FindObject(AddSerialNumber("MHadronness"));
+       if (!fHadron)
+           *fLog << err << "MHadronness not found although specified... no sky map." << endl;
+
+       *fLog << inf << "Hadronness cut set to : " << fHadrCut << endl;
+    }
+
+    // FIXME: Because the pointing position could change we must check
+    // for the current pointing position and add a offset in the
+    // Fill function!
+
+   // prepare skyplot
+    fNumStepsX     =  (int) ((fMaxXGrid - fMinXGrid) / fBinStepGrid + 1.5);
+    fNumStepsY     =  (int) ((fMaxYGrid - fMinYGrid) / fBinStepGrid + 1.5);
+    fNumalphahist  =  (int) (fNumStepsX * fNumStepsY  + 0.5);
+
+    *fLog << inf << "SetSkyPlot: fNumStepsX, fNumStepsY, fNumalphahist: "
+                 << fNumStepsX << ", " << fNumStepsY << ", " << fNumalphahist << endl;
+
+   // fHistSignif.SetName("SPSignif2ndOrder");
+   // fHistSignif.SetTitle("Sky Plot of significance (2nd order fit)");
+    fHistSignif.SetBins(fNumStepsX, fMinXGrid-0.5*fBinStepGrid, fMaxXGrid+0.5*fBinStepGrid, 
+			fNumStepsY, fMinYGrid-0.5*fBinStepGrid, fMaxYGrid+0.5*fBinStepGrid);
+    fHistSignif.SetFillStyle(4000);
+
+   // fHistNexcess.SetName("SPNex2ndOrder");
+   // fHistNexcess.SetTitle("Sky Plot of Number of excess events (2nd order fit)");
+    fHistNexcess.SetBins(fNumStepsX, fMinXGrid-0.5*fBinStepGrid, fMaxXGrid+0.5*fBinStepGrid, 
+			fNumStepsY, fMinYGrid-0.5*fBinStepGrid, fMaxYGrid+0.5*fBinStepGrid);
+    fHistNexcess.SetFillStyle(4000);
+
+   // fHistOn.SetName("SPOnCounted");
+   // fHistOn.SetTitle("Sky Plot of ON events (counted)");
+    fHistOn.SetBins(fNumStepsX, fMinXGrid-0.5*fBinStepGrid, fMaxXGrid+0.5*fBinStepGrid, 
+			fNumStepsY, fMinYGrid-0.5*fBinStepGrid, fMaxYGrid+0.5*fBinStepGrid);
+    fHistOn.SetFillStyle(4000);
+
+    //fHistSignifGaus.SetName("SignifDistrib");
+    fHistSignifGaus.SetTitle("Distribution of the significances from the sky plot");
+    fHistSignifGaus.SetBins(100, -10., 10.); 
+
+    // create alpha histograms
+    for (Int_t i=0; i< fNumalphahist; i++)
+      {
+    	// temp histogram for an alpha plot
+	TH1D *temp = new TH1D("alphaplot","alphaplot",fNumBinsAlpha,fAlphaLeftEdge,fAlphaRightEdge);
+	temp->SetDirectory(NULL);
+	fHistAlpha->AddAt(temp,i);
+      }
+
+    fHistAlphaBinWidth = GetAlphaPlot()->GetBinWidth(1);
+//cout  << " (*fHistAlpha)[10].GetBinContent(5) " << (*fHistAlpha)[10].GetBinContent(5) << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram. For details see the code or the class description
+// 
+Int_t MSkyPlot::Process()
+{
+
+//      *fLog << err << "MPointingPos ENTERING the process" << endl;
+//      *fLog << err << "MPointingPos:: fUseRF " << (int)fUseRF << endl;
+  // check whether MPointingPos comtains something:
+  if (TMath::Abs(fPointPos->GetRa())<1e-3 && TMath::Abs(fPointPos->GetDec())<1e-3) 
+    {
+      *fLog << warn << "MPointingPos is not filled ... event skipped" << endl;
+      return kTRUE;
+    }
+  
+  // Get RA_0, DEC_0 for the camera center (Tracking MDrive?, can be set from outside)
+  if (fSetCenter==kTRUE)
+    {
+      if (fRepDrive)
+	{
+	  fRa0  = fRepDrive->GetRa();  // [h]
+	  fDec0 = fRepDrive->GetDec(); // [deg]
+	  if (fRa0 < 0. || fRa0 > 24. || fDec0 < -90. || fDec0 > 90. || (fRa0==0 && fDec0==0)) return kTRUE;  // temp!, should be changed
+	}
+      else
+	{
+	  fRa0 = fPointPos->GetRa(); 
+	  fDec0 = fPointPos->GetDec();
+	} 
+      *fLog << inf << "Ra (center) = " << fRa0 << ", Dec = " << fDec0 << endl;
+      fSetCenter=kFALSE;
+    }
+
+  // some filter cuts:
+  if ( fHillas->GetSize() > fSizeMin && fHillas->GetSize() < fSizeMax && fNewImagePar->GetLeakage1() < fLeakMax)
+    {
+      
+      Double_t xsource, ysource, cosgam, singam, x_0, y_0, xsourcam, ysourcam;
+      Double_t dx, dy, beta, tanbeta, alphapar, distpar;
+      Double_t logsize, lgsize, lgsize2, dist2, hadr; 
+      const Double_t log3000n = log(3000.*0.18);  // now in phe, thus must shift the offset
+      const Float_t fDistOffset = 0.9;
+      
+      //Get Hadronness if available:
+      if(fUseRF) 
+	{
+		hadr=fHadron->GetHadronness();
+//		cout << " will use RF " << hadr << endl;
+	}
+      // Get camera rotation angle
+      Double_t rho = 0;
+      if (fTime && fObservatory && fPointPos)
+	{
+	  rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+	  //*fLog << inf << " rho = " << rho*180./TMath::Pi() << ", Zd = " << fPointPos->GetZd() << 
+	  //                ", Az = " << fPointPos->GetAz() << ", Ra = " << fPointPos->GetRa() << ", Dec = " << fPointPos->GetDec() << endl;
+	  
+	  // => coord. system: xtilde, ytilde with center in RA_0, DEC_0 
+	  
+	  // Get Rot. Angle:
+	  cosgam = TMath::Cos(rho);
+	  singam = TMath::Sin(rho);
+	  // Get x_0, y_0 for RA_0,DEC_0 of the current event
+	}
+      else 
+	{
+	  //	rho = fPointPos->RotationAngle(*fObservatory);
+	  Double_t theta, phi, sing, cosg;
+	  theta = fPointPos->GetZd()*TMath::Pi()/180.;
+	  phi = fPointPos->GetAz()*TMath::Pi()/180.;
+	  printf("theta: %5.3f, phi: %5.3f\n", theta*180./4.1415, phi*180./4.1415);
+	  fObservatory->RotationAngle(theta, phi, sing, cosg);        
+	  cosgam = cosg;
+	  singam = sing;
+	}
+      // if (fPointPos)
+      //    rho = fPointPos->RotationAngle(*fObservatory);
+      
+      /*
+	//TEMP
+	//        theta = mcevt->GetTelescopeTheta();
+	Double_t theta, phi, sing, cosg;
+	theta = fPointPos->GetZd()*TMath::Pi()/180.;
+	phi = fPointPos->GetAz()*TMath::Pi()/180.;
+	//   printf("theta: %5.3f, phi: %5.3f\n", theta*180./4.1415, phi*180./4.1415);
+	fObservatory->RotationAngle(theta, phi, sing, cosg);
+	
+	// conclusion: diffference in rho = 7 deg
+	//  *fLog << "new thetaTel, phiTel, cosal, sinal, rho = " << theta << ",  "
+	//        << phi << ",  " << cosg << ",  " << sing << ", " << TMath::ATan2(sing,cosg)*180./TMath::Pi() << endl;
+	
+	Double_t a1 =  0.876627;
+	Double_t a3 = -0.481171;
+	Double_t thetaTel=theta, phiTel=phi;
+	
+	Double_t denom =  1./ sqrt( sin(thetaTel)*sin(phiTel) * sin(thetaTel)*sin(phiTel) +
+	( a1*cos(thetaTel)+a3*sin(thetaTel)*cos(phiTel) ) *
+	( a1*cos(thetaTel)+a3*sin(thetaTel)*cos(phiTel) )   );
+	Double_t cosal = - (a3 * sin(thetaTel) + a1 * cos(thetaTel) * cos(phiTel)) * denom;
+	Double_t sinal =    a1 * sin(phiTel) * denom;
+	
+	//  *fLog << "old thetaTel, phiTel, cosal, sinal, rho = " << thetaTel << ",  "
+	//        << phiTel << ",  " << cosal << ",  " << sinal << ", " << TMath::ATan2(sinal,cosal)*180./TMath::Pi() << endl;
+	
+	// END TEMP
+      */
+	    
+      // make the center of the plot different from the center of the camera
+      /*
+	x_0 = fPntPosCam->GetX()*fMm2Deg; 
+	y_0 = fPntPosCam->GetY()*fMm2Deg; 
+      */      
+      x_0 = 0.;  
+      y_0 = 0.;
+      
+      Int_t index = 0;  // index for alpha histograms
+      // loop over xtilde
+      for (Int_t gridy = 0; gridy < fNumStepsY; gridy++)   
+	{
+	  ysource = fMinYGrid + gridy * fBinStepGrid;
+	  // loop over ytilde
+	  for (Int_t gridx = 0; gridx < fNumStepsX; gridx++)
+	    {
+	      
+	      xsource = fMinXGrid + gridx * fBinStepGrid;
+	      
+	      /*     derotation    : rotate  into camera coordinates */
+	      /*     formel: (x_cam)      (cos(gam)  -sin(gam))   (xtilde)   (x_0)
+		     (     )  = - (                   ) * (      ) + (   ) 
+	        (y_cam)      (sin(gam)   cos(gam))   (ytilde)   (y_0)
+	      */
+	      xsourcam = - (cosgam * xsource - singam * ysource) + x_0;
+	      ysourcam = - (singam * xsource + cosgam * ysource) + y_0;
+	      
+	      
+	      /*    end derotatiom    */
+	      //           xsourcam = xsource;
+	      //           ysourcam = ysource;
+
+	      /* calculate ALPHA und DIST according to the source position */
+	      dx = fHillas->GetMeanX()*fMm2Deg - xsourcam;
+	      dy = fHillas->GetMeanY()*fMm2Deg - ysourcam;
+	      tanbeta = dy / dx ;
+	      beta = TMath::ATan(tanbeta);
+	      alphapar = (fHillas->GetDelta() - beta) * 180./ TMath::Pi();
+	      distpar = sqrt( dy*dy + dx*dx );
+	      if(alphapar >  90.) alphapar -= 180.;
+	      if(alphapar < -90.) alphapar += 180.;
+	      alphapar = TMath::Abs(alphapar);
+	      
+	      if(fUseRF)
+	      {
+		
+//		cout << " will use RF " << hadr << endl;
+		if(hadr<fHadrCut  &&  distpar < fMaxDist && distpar > fMinDist)
+		{
+		    TH1D *hist = GetAlphaPlot(index);
+                    hist->Fill(alphapar);
+		}
+	      }
+	      else
+	      {
+	      	// apply cuts
+	      	logsize = log(fHillas->GetSize());
+	      	lgsize = logsize-log3000n;
+	      	lgsize2 = lgsize*lgsize;
+	      	dist2 = distpar*distpar - fDistOffset*fDistOffset;
+	      
+	      	if ( (fHillas->GetLength()*fMm2Deg) < CalcLimit(fLengthUp, lgsize, lgsize2, dist2) &&
+		   (fHillas->GetLength()*fMm2Deg) > CalcLimit(fLengthLo, lgsize, lgsize2, dist2))
+			if ( (fHillas->GetWidth()*fMm2Deg) < CalcLimit(fWidthUp, lgsize, lgsize2, dist2) &&
+		     	(fHillas->GetWidth()*fMm2Deg) > CalcLimit(fWidthLo, lgsize, lgsize2, dist2))
+			  if ( distpar < CalcLimit(fDistUp, lgsize, lgsize2, dist2) &&
+		      	  distpar > CalcLimit(fDistLo, lgsize, lgsize2, dist2) &&
+		      	  distpar < fMaxDist && distpar > fMinDist)
+		    	{
+		      // gamma candidates!
+		      //*fLog <<  "Length : " << fHillas->GetLength()*fMm2Deg << ", Width : " << fHillas->GetWidth()*fMm2Deg << endl;
+		      //*fLog <<  "distpar: " << distpar << ", Size : " << fHillas->GetSize() << endl;
+		      	TH1D *hist = GetAlphaPlot(index);
+		      	hist->Fill(alphapar);
+		    	}
+		}
+	      	index++;
+	    }
+	}
+    }
+    return kTRUE;
+}
+
+// calculate number of events below alphacut, number of excess events, significance
+
+Int_t MSkyPlot::PostProcess()
+{
+
+    Int_t nrow, ncolumn;
+    Double_t Non, chisquarefit, numdegfreed, Noff_fit, Nex, Sign; 
+    const Int_t onbinsalpha = TMath::Nint(fAlphaONMax/fHistAlphaBinWidth);
+
+
+// fit function for the background
+    TF1 * fitbgpar = new TF1("fbgpar", "[0]*x*x + [1]", fAlphaBgLow, fAlphaBgUp);
+    fitbgpar->SetLineColor(2);
+
+// number degrees of freedom:
+    numdegfreed = (fAlphaBgUp - fAlphaBgLow) / fHistAlphaBinWidth - 2.; 
+
+    int index2 = 0;  // index of the TH2F histograms
+
+    TOrdCollectionIter Next(fHistAlpha);
+    TH1D *alpha_iterator = NULL;
+
+    fHistNexcess.Reset();
+    fHistOn.Reset();
+    fHistSignif.Reset();   
+    fHistSignifGaus.Reset();
+    
+    while ( (alpha_iterator = (TH1D*)Next())) {
+	 // find the bin in the 2dim histogram
+         nrow    = index2/fHistOn.GetNbinsX() + 1;              // row of the histogram (y)
+         ncolumn = index2%fHistOn.GetNbinsX()+1;   		// column of the histogram (x)
+         //ncolumn = TMath::Nint(fmod(index2,fHistOn.GetNbinsX()))+1;   // column of the histogram (x)
+
+         // number of ON events below fAlphaONMax
+         Non = 0.;
+         for(Int_t i=1; i<=onbinsalpha;i++) Non += (*alpha_iterator).GetBinContent(i);
+
+         fHistOn.SetBinContent(ncolumn, nrow, Non);		// fill in the fHistOn
+
+         // fit parabola to a background region
+         alpha_iterator->Fit(fitbgpar,"EQRN");  // NWR OK?????????????????????????
+         // get Chi2
+         chisquarefit = fitbgpar->GetChisquare();
+         if (chisquarefit/numdegfreed<2. && chisquarefit/numdegfreed>0.01);
+         else  *fLog << warn << "Fit is bad, chi2/ndf = " << chisquarefit/numdegfreed << endl;
+	 
+         // estimate Noff from the fit:
+       	 Noff_fit = (1./3. * (fitbgpar->GetParameter(0)) * TMath::Power(fAlphaONMax,3.) +
+		     (fitbgpar->GetParameter(1)) * fAlphaONMax) /  fHistAlphaBinWidth;
+	 
+	 Nex = Non - Noff_fit;
+
+         fHistNexcess.SetBinContent(ncolumn, nrow, Nex);	// fill in the fHistNexcess
+	 
+         if (Noff_fit<0.) Sign = 0.;
+	 //         else Sign = LiMa17(Non,Noff_fit,1.);
+         else Sign = MMath::SignificanceLiMaSigned(Non, Noff_fit, 1.);
+	 
+         fHistSignif.SetBinContent(ncolumn, nrow, Sign);	// fill in the fHistSignif
+         fHistSignifGaus.Fill(Sign);
+	 
+         index2++;
+    }
+    
+    // fit with gaus 
+    fHistSignifGaus.Fit("gaus","N");
+    
+    
+    //temp
+    /*
+      Double_t decl, hang;
+      MStarCamTrans mstarc(*fGeomCam, *fObservatory);
+      mstarc.LocToCel(fRepDrive->GetNominalZd(),fRepDrive->GetNominalAz(),decl, hang);
+      
+      *fLog << warn << "MDrive, RA, DEC = " << fRepDrive->GetRa() << ", " << fRepDrive->GetDec() << endl;
+      *fLog << warn << "MStarCamTrans, H angle , DEC = " << hang << ", " << decl << endl;
+      */
+    //endtemp
+    
+    
+    // save alpha plots:
+    //  TString stri1 = "alphaplots.root";
+    if(fSaveAlphaPlots==kTRUE) SaveAlphaPlots(fAlphaHName);
+    
+    // save sky plots:
+    //  TString stri2 = "skyplots.root";
+    if(fSaveSkyPlots==kTRUE) SaveSkyPlots(fSkyHName);
+    
+    // save nex plot:
+    if(fSaveNexPlot==kTRUE) SaveNexPlot(fNexHName);
+    
+    fHistAlpha->Clear();
+
+    delete fitbgpar;
+    
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get the MAstroCatalog corresponding to fRa, fDec. The limiting magnitude
+// is set to 9, while the fov is equal to the current fov of the false
+// source plot.
+//
+TObject *MSkyPlot::GetCatalog()
+{
+    const Double_t maxr = 0.98*TMath::Abs(fHistSignif.GetBinCenter(1));
+
+    // Create catalog...
+    MAstroCatalog stars;
+    stars.SetLimMag(9);
+    stars.SetGuiActive(kFALSE);
+    stars.SetRadiusFOV(maxr);
+    stars.SetRaDec(fRa*TMath::DegToRad()*15, fDec*TMath::DegToRad());
+    stars.ReadBSC("bsc5.dat");
+
+    TObject *o = (MAstroCatalog*)stars.Clone();
+    o->SetBit(kCanDelete);
+
+    return o;
+}
+
+void MSkyPlot::SaveNexPlot(TString nexplotname)
+{
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetCanvasBorderSize(0);
+    gStyle->SetCanvasColor(10);
+//    gStyle->SetPadBorderMode(0);
+//    gStyle->SetPadBorderSize(0);
+    gStyle->SetPadColor(10);
+    gStyle->SetOptFit(0);
+    gStyle->SetOptStat(0);
+    gStyle->SetStatColor(10);
+    gStyle->SetPalette(1);
+    gStyle->SetPadRightMargin(0.16);
+    gStyle->SetPadLeftMargin(0.13);
+
+    Char_t timet[100];
+
+    TH2D tmp = fHistNexcess;
+    tmp.SetMaximum(470); 
+    tmp.SetMinimum(-90); 
+    TCanvas can("SkyPlot","SkyPlot", 0, 0, 800, 400);
+    can.Divide(2,1);
+    can.cd(1);
+    tmp.GetYaxis()->SetTitleOffset(1.3);
+    tmp.Draw("colz"); 
+    TPaveLabel myname(fMinXGrid-0.5,fMinYGrid-0.4,fMinXGrid+0.3,fMinYGrid-0.2,"by D. Mazin");
+    myname.Draw();
+
+    can.cd(2);
+    fHistNexcess.SetMaximum(470);    
+    fHistNexcess.SetMinimum(-40);    
+    fHistNexcess.GetXaxis()->SetTitleOffset(1.3);
+    fHistNexcess.GetYaxis()->SetTitleOffset(1.6);
+    gPad->SetTheta(20);
+    fHistNexcess.Draw("lego2");
+    TLatex tu(0.5,0.8,"elapsed time:");
+    tu.Draw();
+    sprintf(timet,"%.1f min",fElaTime);
+    TLatex tut(0.5,0.7,timet);
+    tut.Draw();
+
+    can.Print(nexplotname);  
+//    can.Print("test.root");
+}
+
+void MSkyPlot::SaveSkyPlots(TString skyplotfilename)
+{
+
+  TFile rootfile(skyplotfilename, "RECREATE",
+		 "sky plots in some variations");
+  fHistSignif.Write();
+  fHistNexcess.Write();
+  fHistOn.Write();
+  fHistSignif.Write();
+     
+  // from Wolfgang: 
+  //--------------------------------------------------------------------
+  // Dec-Hour lines
+  Double_t rho, sinrho, cosrho;
+  Double_t theta, phi, sing, cosg;
+  // do I need it?
+  if (fTime && fObservatory && fPointPos)
+    {
+      rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+      sinrho=TMath::Sin(rho);
+      cosrho=TMath::Cos(rho);
+    }
+  
+  theta = fPointPos->GetZd()*TMath::Pi()/180.;
+  phi = fPointPos->GetAz()*TMath::Pi()/180.;
+  //   printf("theta: %5.3f, phi: %5.3f\n", theta*180./4.1415, phi*180./4.1415);
+  fObservatory->RotationAngle(theta, phi, sing, cosg);
+  
+  *fLog << "1: sinrho, cosrho = " << sinrho << ", " << cosrho << endl;
+  *fLog << "2: sinrho, cosrho = " << sing << ", " << cosg << endl;
+  sinrho=sing;
+  cosrho=cosg;
+
+  Double_t fDistCam = fGeomCam->GetCameraDist() * 1000.0;     //  [mm]
+  Double_t gridbinning = fGridBinning;
+  Double_t gridfinebin = fGridFineBin;
+  Int_t    numgridlines = (Int_t)(4.0/gridbinning);
+  Double_t aberr = 1.07;
+  Double_t mmtodeg = 180.0 / TMath::Pi() / fDistCam ;
+  
+  Double_t declin, hangle;  // [deg], [h]
+  MStarCamTrans mstarc(*fGeomCam, *fObservatory);
+  if (fRepDrive) mstarc.LocToCel(fRepDrive->GetNominalZd(),fRepDrive->GetNominalAz(),declin, hangle);
+  else mstarc.LocToCel(theta*180./TMath::Pi(),phi*180./TMath::Pi(),declin, hangle); // NOT GOOD!
+  
+  TLatex *pix;
+  
+  Char_t tit[100];
+  Double_t xtxt;
+  Double_t ytxt;
+  
+  Double_t xlo = -534.0 * mmtodeg;
+  Double_t xup =  534.0 * mmtodeg;
+  
+  Double_t ylo = -534.0 * mmtodeg;
+  Double_t yup =  534.0 * mmtodeg;
+  
+  Double_t xx, yy;
+  
+  
+  // direction for the center of the camera
+  Double_t dec0 = declin;
+  Double_t h0   = hangle*360./24.; //deg
+  //    Double_t RaHOffset = fRepDrive->GetRa() - h0;
+    //trans.LocToCel(theta0, phi0, dec0, h0);
+  
+  gStyle->SetOptFit(0);
+  gStyle->SetOptStat(0);
+  gStyle->SetPalette(1);
+  TCanvas *c1 = new TCanvas("SPlotsRaDecLines","SPlotsRaDecLines", 400, 0, 700, 600);
+  c1->Divide(2,2);
+  c1->cd(1);
+  fHistSignif.Draw("colz");
+  c1->cd(2);
+  fHistNexcess.Draw("colz");
+  c1->cd(3);
+  fHistOn.Draw("colz");
+  c1->cd(4);
+  gPad->SetLogy();
+  fHistSignifGaus.Draw(); 
+  
+  //-----   lines for fixed dec   ------------------------------------
+  
+  const Int_t Ndec = numgridlines;
+  Double_t dec[Ndec];
+  Double_t ddec = gridbinning;
+  
+  Int_t nh = (Int_t)(4.0/gridfinebin);
+  const Int_t Nh   = nh+1;
+  Double_t h[Nh];
+  Double_t dh = gridfinebin/cos(dec0/180.0*3.1415926);
+  if ( dh > 360.0/((Double_t)(Nh-1)) )
+    dh = 360.0/((Double_t)(Nh-1));
+  
+  // start to copy
+  for (Int_t j=0; j<Ndec; j++)
+    {
+      dec[j] = dec0 + ((Double_t)j)*ddec
+	- ((Double_t)(Ndec/2)-1.0)*ddec;
+    }
+  
+  for (Int_t k=0; k<Nh; k++)
+    {
+      h[k] = h0 + ((Double_t)k)*dh - ((Double_t)(Nh/2)-1.0)*dh;
+    }
+  
+  Double_t xh[Nh];
+  Double_t yh[Nh];
+  
+  for (Int_t j=0; j<Ndec; j++)
+    {
+      if (fabs(dec[j]) > 90.0) continue;
+      
+      for (Int_t k=0; k<Nh; k++)
+	{
+	  Double_t hh0 = h0   *24.0/360.0;
+	  Double_t hx = h[k]*24.0/360.0;
+	  mstarc.Cel0CelToCam(dec0, hh0, dec[j], hx,
+			      xx, yy);
+	  xx = xx * mmtodeg * aberr;
+	  yy = yy * mmtodeg * aberr;
+	  //        xh[k] = xx * mmtodeg * aberr;
+	  //        yh[k] = yy * mmtodeg * aberr;
+	  xh[k] = cosg * xx + sing * yy;
+	  yh[k] =-sing * xx + cosg * yy;
+	  //        xh[k] = cosrho * xx + sinrho * yy;
+	  //        yh[k] =-sinrho * xx + cosrho * yy;
+	  
+	  
+	  //gLog << "dec0, h0 = " << dec0 << ",  " << h0
+	  //     << " : dec, h, xh, yh = " << dec[j] << ",  "
+	  //     << h[k] << ";   " << xh[k] << ",  " << yh[k] << endl;
+	}
+      
+      //      c1->cd(2);
+      TGraph * graph1 = new TGraph(Nh,xh,yh);
+      //graph1->SetLineColor(j+1);
+      graph1->SetLineColor(36);
+      graph1->SetLineStyle(1);
+      graph1->SetLineWidth(1);
+      //graph1->SetMarkerColor(j+1);
+      graph1->SetMarkerColor(1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      
+      c1->cd(1);
+      graph1->Draw("L");
+      c1->cd(2);
+      graph1->Draw("L");
+      c1->cd(3);
+      graph1->Draw("L");
+      //delete graph1;
+      //      graphvec.push_back(*graph1);
+      //      graphvec[j].Draw("L");
+      
+      sprintf(tit,"Dec = %6.2f", dec[j]);
+      xtxt = xlo + (xup-xlo)*0.1;
+      ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)j) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(36);
+      pix->SetTextSize(.03);
+      //pix->Draw("");
+      //delete pix;
+      
+    }
+  //stop copy
+  //-----   lines for fixed hour angle   ------------------------------------
+  
+  Int_t ndec1 = (Int_t)(4.0/gridfinebin);
+  const Int_t Ndec1 = ndec1;
+  Double_t dec1[Ndec1];
+  Double_t ddec1 = gridfinebin;
+  
+  const Int_t Nh1   = numgridlines;
+  Double_t h1[Nh1];
+  Double_t dh1 = gridbinning/cos(dec0/180.0*3.1415926);
+  if ( dh1 > 360.0/((Double_t)Nh1) )
+    dh1 = 360.0/((Double_t)Nh1);
+  
+  // start copy
+  for (Int_t j=0; j<Ndec1; j++)
+    {
+      dec1[j] = dec0 + ((Double_t)j)*ddec1
+	- ((Double_t)(Ndec1/2)-1.0)*ddec1;
+    }
+  
+  for (Int_t k=0; k<Nh1; k++)
+    {
+      h1[k] = h0 + ((Double_t)k)*dh1 - ((Double_t)(Nh1/2)-1.0)*dh1;
+    }
+  
+  Double_t xd[Ndec1];
+  Double_t yd[Ndec1];
+  
+  for (Int_t k=0; k<Nh1; k++)
+    {
+      Int_t count = 0;
+      for (Int_t j=0; j<Ndec1; j++)
+	{
+	  if (fabs(dec1[j]) > 90.0) continue;
+	  
+	  Double_t hh0 = h0   *24.0/360.0;
+	  Double_t hhx = h1[k]*24.0/360.0;
+	  mstarc.Cel0CelToCam(dec0, hh0, dec1[j], hhx,
+                           xx, yy);
+	  //        xd[count] = xx * mmtodeg * aberr;
+	  //        yd[count] = yy * mmtodeg * aberr;
+	  
+	  xx = xx * mmtodeg * aberr;
+	  yy = yy * mmtodeg * aberr;
+	  xd[count] = cosg * xx + sing * yy;
+	  yd[count] =-sing * xx + cosg * yy;
+
+	  //gLog << "dec0, h0 = " << dec0 << ",  " << h0
+	  //     << " : dec1, h1, xd, yd = " << dec1[j] << ",  "
+	  //     << h1[k] << ";   " << xd[count] << ",  " << yd[count] << endl;
+	  
+	  count++;
+	}
+      
+      //      c1->cd(2);
+      TGraph * graph1 = new TGraph(count,xd,yd);
+      //graph1->SetLineColor(k+1);
+      graph1->SetLineColor(36);
+      graph1->SetLineWidth(2);
+      graph1->SetLineStyle(1);
+      //graph1->SetMarkerColor(k+1);
+      graph1->SetMarkerColor(1);
+      graph1->SetMarkerSize(.2);
+      graph1->SetMarkerStyle(20);
+      c1->cd(1);
+      graph1->Draw("L");
+      c1->cd(2);
+      graph1->Draw("L");
+      c1->cd(3);
+      graph1->Draw("L");
+
+      sprintf(tit,"RA = %6.2f", fRa0 + (h0 - h1[k]));
+      Double_t xtxt = xlo + (xup-xlo)*0.75;
+      Double_t ytxt = ylo + (yup-ylo)*0.80 - ((Double_t)k) *(yup-ylo)/20.0;
+      pix = new TLatex(xtxt, ytxt, tit);
+      pix->SetTextColor(36);
+      pix->SetTextSize(.03);
+      //pix->Draw("");
+      //delete pix;
+      
+    }
+  
+  //    c1->cd(2);
+  sprintf(tit,"Dec0 = %6.2f [deg]   Ra0 = %6.2f [h]", dec0, fRa0);
+  xtxt = xlo + (xup-xlo)*0.05 + 0.80;
+  ytxt = ylo + (yup-ylo)*0.75;
+  pix = new TLatex(xtxt, ytxt, tit);
+  pix->SetTextColor(1);
+  pix->SetTextSize(.05);
+  c1->cd(1);
+  pix->Draw("");
+  c1->cd(2);
+  pix->Draw("");
+  c1->cd(3);
+  pix->Draw("");
+  //delete pix;
+  
+  c1->Write();
+  // we suppose that the {skyplotfilename} ends with .root
+  Int_t sizeofout = skyplotfilename.Sizeof();
+  TString outps = skyplotfilename.Remove(sizeofout-5,5) + "ps";
+  c1->Print(outps);  // temporary!!!!!
+
+  TCanvas *c2 = new TCanvas("SkyPlotsWithRaDecLines","SkyPlotsWithRaDecLines", 0, 0, 300, 600);
+  c2->Divide(1,2);
+  c2->SetBorderMode(0);
+  c2->cd(1);
+  fHistSignif.Draw("colz");
+  c2->cd(2);
+  fHistNexcess.Draw("colz");
+  c2->Write();
+  
+  rootfile.Close();
+  delete c1;
+  delete c2;
+  delete pix;
+
+}
+
+void MSkyPlot::SaveAlphaPlots(const TString alphaplotfilename)
+{
+   TFile rootfile(alphaplotfilename, "RECREATE",
+                   "all the alpha plots");
+
+    int index = 0;  // index of the TH2F histograms
+    Char_t strtitle[100];
+    Char_t strname[100];
+    Float_t xpos, ypos, signif, nex;
+    Int_t nrow, ncolumn, non;
+
+    TH1D *alpha_iterator = NULL;
+    TOrdCollectionIter Next(fHistAlpha);
+
+    while( (alpha_iterator = (TH1D*)Next())) {
+
+          nrow    = index/fHistOn.GetNbinsX() + 1;                    // row of the histogram (y)
+          //ncolumn = TMath::Nint(fmod(index,fHistOn.GetNbinsX()))+1;   // column of the histogram (x)
+          ncolumn = index%fHistOn.GetNbinsX()+1;   // column of the histogram (x)
+          xpos    = fMinXGrid + fBinStepGrid*(ncolumn-1);
+          ypos    = fMinYGrid + fBinStepGrid*(nrow-1);
+          non     = TMath::Nint(fHistOn.GetBinContent(ncolumn,nrow));
+          nex     = fHistNexcess.GetBinContent(ncolumn,nrow);
+          signif  = fHistSignif.GetBinContent(ncolumn,nrow);
+
+          sprintf(strname,"AlphaPlotX%.2fY%.2f", xpos, ypos); 
+          sprintf(strtitle,"for x= %.2f deg, y= %.2f deg: S= %.2f sigma, Nex= %.2f, Non= %d", 
+			xpos, ypos, signif, nex, non);
+           
+	  alpha_iterator->SetName(strname);
+	  alpha_iterator->SetTitle(strtitle);
+          alpha_iterator->Write();
+          index++;
+    }
+
+   rootfile.Close();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// This is a preliminary implementation of a alpha-fit procedure for
+// all possible source positions. It will be moved into its own
+// more powerfull class soon.
+//
+// The fit function is "gaus(0)+pol2(3)" which is equivalent to:
+//   [0]*exp(-0.5*((x-[1])/[2])^2) + [3] + [4]*x + [5]*x^2
+// or
+//   A*exp(-0.5*((x-mu)/sigma)^2) + a + b*x + c*x^2
+//
+// Parameter [1] is fixed to 0 while the alpha peak should be
+// symmetric around alpha=0.
+//
+// Parameter [4] is fixed to 0 because the first derivative at
+// alpha=0 should be 0, too.
+//
+// In a first step the background is fitted between bgmin and bgmax,
+// while the parameters [0]=0 and [2]=1 are fixed.
+//
+// In a second step the signal region (alpha<sigmax) is fittet using
+// the whole function with parameters [1], [3], [4] and [5] fixed.
+//
+// The number of excess and background events are calculated as
+//   s = int(0, sigint, gaus(0)+pol2(3))
+//   b = int(0, sigint,         pol2(3))
+//
+// The Significance is calculated using the Significance() member
+// function.
+//
+
+// I might need this
+/*
+    TCanvas *c=new TCanvas;
+
+    gStyle->SetPalette(1, 0);
+
+    c->Divide(3,2, 0, 0);
+    c->cd(1);
+    gPad->SetBorderMode(0);
+    hists->Draw("colz");
+    hists->SetBit(kCanDelete);
+    catalog->Draw("mirror same");
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    hist->Draw("colz");
+    hist->SetBit(kCanDelete);
+    catalog->Draw("mirror same");
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    histb->Draw("colz");
+    histb->SetBit(kCanDelete);
+    catalog->Draw("mirror same");
+    c->cd(4);
+    gPad->Divide(1,3, 0, 0);
+    TVirtualPad *p=gPad;
+    p->SetBorderMode(0);
+    p->cd(1);
+    gPad->SetBorderMode(0);
+    h0b.DrawCopy();
+    h0a.DrawCopy("same");
+    p->cd(2);
+    gPad->SetBorderMode(0);
+    h3.DrawCopy();
+    p->cd(3);
+    gPad->SetBorderMode(0);
+    h2.DrawCopy();
+
+*/
Index: /tags/Mars-V0.9/mtemp/mmpi/MSkyPlot.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MSkyPlot.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MSkyPlot.h	(revision 9772)
@@ -0,0 +1,171 @@
+#ifndef MARS_MSkyPlot
+#define MARS_MSkyPlot
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef ROOT_TOrdCollection
+#include <TOrdCollection.h>
+#endif
+
+class TH2D;
+class TH1D;
+
+class MParList;
+class MTime;
+class MPointingPos;
+class MSrcPosCam;
+class MReportDrive;
+class MObservatory;
+class MHillas;
+class MHillasExt;
+class MHillasSrc;
+class MNewImagePar;
+class MHadronness;
+class MGeomCam;
+class TOrdCollection;
+class MSkyPlot : public MTask
+{
+private:
+
+    MGeomCam      *fGeomCam;     //! container to take the event time from
+    MTime         *fTime;        //! container to take the event time from
+    MPointingPos  *fPointPos;    //! container to take pointing position from
+    MReportDrive  *fRepDrive;    //!      
+    MSrcPosCam    *fSrcPosCam;   //! container with x and y of the source
+    MSrcPosCam    *fPntPosCam;   //! container with x and y of the position MReportDrive.GetRa, MReportDrive.GetDec
+    MObservatory  *fObservatory; //! container to take observatory location from
+    MHillas       *fHillas;      //!
+    MHillasExt    *fHillasExt;   //!
+    MHillasSrc    *fHillasSrc;   //!
+    MNewImagePar  *fNewImagePar; //!
+    MHadronness   *fHadron;      //!
+
+    TOrdCollection *fHistAlpha;  // vector of histograms for alpha
+
+    Float_t        fMm2Deg;      // conversion factor for display in degrees
+    Double_t       fGridBinning; // degrees
+    Double_t       fGridFineBin; // degrees
+
+//    Float_t fAlphaCut;           // Alpha cut
+//    Float_t fBgMean;             // Background mean
+
+//    Float_t fMinDist;            // Min dist
+//    Float_t fMaxDist;            // Max dist
+
+//    Float_t fMinLD;              // Minimum distance in percent of dist
+//    Float_t fMaxLD;              // Maximum distance in percent of dist
+
+    Int_t fNumalphahist;		// number of histograms for alpha
+    Int_t fNumBinsAlpha;
+    Float_t fHistAlphaBinWidth;
+    Float_t fAlphaLeftEdge;
+    Float_t fAlphaRightEdge;
+    Float_t fAlphaONMax;	//  [deg] , upper cut for alpha ON region in the alpha plot, [deg], ON region in the alpha plot, maybe 5 deg is better,  NOTE: up to now only values of 5, 10, 15, 20 degrees are possible
+    Float_t fAlphaBgLow;	   // lower limit for bg region in the ON alpha plot 
+    Float_t fAlphaBgUp;		   // upper limit for bg region in the ON alpha plot
+    
+    TH2D     fHistSignif;          // sky plot of significance vs. x and y
+    TH2D     fHistNexcess;         // sky plot of number of excess events vs. x and y
+    TH2D     fHistOn;              // sky plot of events below fAlphaONMax vs. x and y
+    TH1D     fHistSignifGaus;      // distribution of significance
+    Bool_t   fSetCenter;           // used to set the center of these histograms once
+    Bool_t   fUseRF;               // use RF hadronness cut instead of supercuts
+    Double_t fRa0;		   //    
+    Double_t fDec0;		   //
+    Bool_t   fSaveAlphaPlots;	   //
+    Bool_t   fSaveSkyPlots;	   //
+    Bool_t   fSaveNexPlot;	   //
+				   
+    Float_t fMinXGrid;		   //  [deg] , left edge of the skyplot
+    Float_t fMaxXGrid;		   //  [deg] , right edge of the skyplot
+    Float_t fMinYGrid;		   //  [deg] , upper edge of the skyplot
+    Float_t fMaxYGrid;		   //  [deg] , lower edge of the skyplot
+    Float_t fBinStepGrid;	   //  [deg] , grid size
+    Int_t fNumStepsX;		   // number of bins in x 
+    Int_t fNumStepsY;		   // number of bins in y
+
+
+    // some filter cuts:
+    Float_t fSizeMin;		// min size in photons
+    Float_t fSizeMax;		// max size in photons
+    Float_t fLeakMax;		// leakmax  in per cent
+    Float_t fMaxDist;          // dist max cut (ever possible)
+    Float_t fMinDist;          // dist min cut (ever possible)
+    Float_t fHadrCut;          // hadronness cut 
+
+    // coefficients for the cuts:
+    Double_t fLengthUp[8], fLengthLo[8], fWidthUp[8], fWidthLo[8], fDistUp[8], fDistLo[8];
+
+    Double_t fRa;
+    Double_t fDec;
+
+    TString fAlphaHName;          // name for histogram with alpha plots
+    TString fSkyHName;            // name for histogram with sky plots
+    TString fNexHName;            // name for canvas with Nex plot
+    Float_t fElaTime;             // elapsed time [min]
+
+    TObject *GetCatalog();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+
+public:
+    MSkyPlot(const char *name=NULL, const char *title=NULL);
+    ~MSkyPlot();
+
+    Double_t CalcLimit(Double_t *a, Double_t ls, Double_t ls2, Double_t dd2);
+
+    TH2D *GetHistSignif    () { return &fHistSignif;  }
+    TH2D *GetHistNexcess   () { return &fHistNexcess; }
+    TH2D *GetHistOn        () { return &fHistOn;      }
+    TH1D *GetHistSignifGaus() { return &fHistSignifGaus; }
+
+    Int_t GetSize()  const { return fHistAlpha->GetSize(); }
+
+    TH1D *GetAlphaPlot( const Int_t i=-1);
+    const TH1D *GetAlphaPlot( const Int_t=-1) const;
+
+    void ReadCuts(const TString parSCinit);
+
+    void SaveAlphaPlots(const TString stri2);
+    void SaveNexPlot(const TString stri3);
+    void SaveSkyPlots(TString stri);
+
+    void SetAlphaCut(Float_t alpha); 
+    void SetAlphaBGLimits(Float_t alphalow, Float_t alphalup); 
+
+    void SetMinDist(Float_t dist) { fMinDist = dist; } // Absolute minimum distance
+    void SetMaxDist(Float_t dist) { fMaxDist = dist; } // Absolute maximum distance
+    void SetSizeMin(Float_t size) { fSizeMin = size; } // Absolute minimum Size
+    void SetSizeMax(Float_t size) { fSizeMax = size; } // Absolute maximum Size
+    void SetSkyPlot(Float_t xmin, Float_t xmax, Float_t ymin, Float_t ymax, Float_t step);
+    void SetHadrCut(Float_t b)    { fHadrCut = b;    }  // hadronness cut
+
+    void SetOutputSkyName(TString outname2)     { fSkyHName = outname2; }
+    void SetNotSaveSkyPlots()                   { fSaveSkyPlots = kFALSE; }
+
+    void SetOutputAlphaName(TString outname1)   { fAlphaHName = outname1; }
+    void SetNotSaveAlphaPlots()                 { fSaveAlphaPlots = kFALSE; }
+
+    void SetOutputNexName(TString outname3)     { fNexHName = outname3; }
+    void SetElapsedTime(Float_t g)              { fElaTime = g; }
+    void SetNotSaveNexPlot()                    { fSaveNexPlot = kFALSE; }
+
+    void SetUseRF()                             { fUseRF = kTRUE; }
+
+    ClassDef(MSkyPlot, 1) //2D-histogram in alpha, x and y
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mmpi/MUnfold.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MUnfold.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MUnfold.cc	(revision 9772)
@@ -0,0 +1,3079 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s) : T. Bretz  02/2002 <mailto:tbretz@astro.uni-wuerzburg.de>   
+!               W. Wittek 09/2002 <mailto:wittek@mppmu.mpg.de>             
+!               R. Wagner, 11/2004 <mailto:rwagner@mppmu.mpg.de>           
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MUnfold
+//
+/////////////////////////////////////////////////////////////////////////////   
+#include "MUnfold.h"
+
+#include <TMath.h>
+#include <TRandom3.h>
+#include <TVector.h>
+#include <TMatrixD.h>
+#include <TMatrix.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TProfile.h>
+#include <TF1.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MUnfold);
+using namespace std;
+
+// -----------------------------------------------------------------------
+//
+// fcnSmooth     (used by SmoothMigrationMatrix)
+//
+// is called by MINUIT
+// for given values of the parameters it calculates the function 
+//                                               to be minimized
+//
+static void fcnSmooth(Int_t &npar, Double_t *gin, Double_t &f, 
+               Double_t *par, Int_t iflag)
+{
+    MUnfold &gUnfold = *(MUnfold*)gMinuit->GetObjectFit();
+
+    Double_t a0 = par[0];
+    Double_t a1 = par[1];
+    Double_t a2 = par[2];
+
+    Double_t b0 = par[3];
+    Double_t b1 = par[4];
+    Double_t b2 = par[5];
+
+    // loop over bins of log10(E-true)
+    Double_t chi2 = 0.0;
+    Int_t npoints = 0;
+    Double_t func[20];
+
+    for (UInt_t j=0; j<gUnfold.fNb; j++)
+    {
+        Double_t yj   = ((double)j) + 0.5;
+        Double_t mean = a0 + a1*yj + a2*yj*yj + yj;
+        Double_t RMS  = b0 + b1*yj + b2*yj*yj;
+
+        if (RMS <= 0.0)
+        {
+            chi2 = 1.e20;
+            break;
+        }
+
+        // loop over bins of log10(E-est)
+
+        //.......................................
+        Double_t function;
+        Double_t sum=0.0;
+        for (UInt_t i=0; i<gUnfold.fNa; i++)
+        {
+            Double_t xlow = (double)i;
+            Double_t xup  = xlow + 1.0;
+            Double_t xl  = (xlow- mean) / RMS;
+            Double_t xu  = (xup - mean) / RMS;
+            function = (TMath::Freq(xu) - TMath::Freq(xl));
+
+            //*fLog << "i, xl, xu, function = " <<  i <<  ",  "  << xl << ",  "
+            //     << xu  << ",  " << function << endl;
+
+            if (function < 1.e-10)
+                function = 0.0;
+
+            func[i] = function;
+            sum += function;
+        }
+
+        //      *fLog << "mean, RMS = "  << mean << ",  " << RMS
+        //     << ",   j , sum of function = " << j << ",  " << sum << endl;
+
+        //.......................................
+
+        for (UInt_t i=0; i<gUnfold.fNa; i++)
+        {
+            if (sum != 0.0)
+                func[i] /= sum;
+
+            gUnfold.fMigSmoo(i,j) = func[i];
+            gUnfold.fMigChi2(i,j) = 0.0;
+
+            // if relative error is greater than 30 % ignore the point
+
+            if (gUnfold.fMigOrig(i,j)     != 0 &&
+                gUnfold.fMigOrigerr2(i,j) != 0 &&
+                func[i] != 0  )
+            {
+                if (gUnfold.fMigOrigerr2(i,j)/
+                    (gUnfold.fMigOrig(i,j)*gUnfold.fMigOrig(i,j)) <= 0.09)
+                {
+                    gUnfold.fMigChi2(i,j) =   ( gUnfold.fMigOrig(i,j) - func[i] )
+                        * ( gUnfold.fMigOrig(i,j) - func[i] )
+                        /   gUnfold.fMigOrigerr2(i,j);
+                    chi2 += gUnfold.fMigChi2(i,j);
+                    npoints += 1;
+                }
+            }
+        }
+        //.......................................
+
+    }
+    f = chi2;
+
+    //*fLog << "fcnSmooth : f = " << f << endl;
+
+    //--------------------------------------------------------------------
+    // final calculations
+    if (iflag == 3)
+    {
+        Int_t     NDF = npoints - npar;
+        Double_t prob = TMath::Prob(chi2, NDF);
+
+        gLog << "fcnSmooth : npoints, chi2, NDF, prob = " << npoints << ",  ";
+        gLog << chi2 << ",  " << NDF << ",  " << prob << endl;
+        gLog << "=======================================" << endl;
+    }
+}
+
+
+// -----------------------------------------------------------------------
+//
+// fcnTikhonov2     (used by Tikhonov2)
+//
+// is called by MINUIT
+// for given values of the parameters it calculates the function F
+// the free parameters are the first (fNb-1) elements
+//                     of the normalized unfolded distribution
+//
+static void fcnTikhonov2(Int_t &npar, Double_t *gin, Double_t &f,
+                  Double_t *par, Int_t iflag)
+{
+    MUnfold &gUnfold = *(MUnfold*)gMinuit->GetObjectFit();
+
+    // (npar+1) is the number of bins of the unfolded distribuition (fNb)
+    //  npar    is the number of free parameters                    (fNb-1)
+
+    UInt_t npar1 = npar + 1;
+
+    UInt_t fNa = gUnfold.fNa;
+    UInt_t fNb = gUnfold.fNb;
+    if (npar1 != fNb)
+    {
+        gLog << "fcnTikhonov2 : inconsistency in number of parameters; npar, fNb = ";
+        gLog << npar << ",  " << fNb << endl;
+        //return;
+    }
+    npar1 = fNb;
+
+    TMatrixD p(npar1, 1);
+    TMatrixD &fVb = gUnfold.fVb;
+
+    // p is the normalized unfolded distribution
+    // sum(p(i,0)) from i=0 to npar is equal to 1
+    Double_t sum = 0.0;
+    for (Int_t i=0; i<npar; i++)
+    {
+        p(i,0) = par[i];
+        sum += par[i];
+    }
+    p(npar,0) = 1.0 - sum;
+
+
+    // all p(i,0) have to be greater than zero
+    for (UInt_t i=0; i<npar1; i++)
+        if (p(i,0) <= 0.0)
+        {
+            f = 1.e20;
+            return;
+        }
+
+    //.......................
+    // take least squares result for the normaliztion
+    TMatrixD alpha(gUnfold.fMigrat, TMatrixD::kMult, p);
+
+    //TMatrixD v4   (gUnfold.fVa, TMatrixD::kTransposeMult,
+    //                                 gUnfold.fVacovInv);
+    //TMatrixD norma(v4,  TMatrixD::kMult, gUnfold.fVa);
+
+    TMatrixD v5   (alpha, TMatrixD::kTransposeMult, gUnfold.fVacovInv);
+    TMatrixD normb(v5,    TMatrixD::kMult, alpha);
+
+    TMatrixD normc(v5,    TMatrixD::kMult, gUnfold.fVa);
+
+    Double_t norm  = normc(0,0)/normb(0,0);
+
+    //.......................
+
+    // b is the unnormalized unfolded distribution
+    // sum(b(i,0)) from i=0 to npar is equal to norm
+    //                       (the total number of events)
+    for (UInt_t i=0; i<npar1; i++)
+        fVb(i,0) = p(i,0) * norm;
+
+    TMatrixD Gb(gUnfold.fMigrat, TMatrixD::kMult, fVb);
+    TMatrixD v3(fNa, 1);
+    v3 = gUnfold.fVa;
+    v3 -= Gb;
+
+    TMatrixD v1(1,fNa);
+    for (UInt_t i=0; i<fNa; i++)
+    {
+        v1(0,i) = 0;
+        for (UInt_t j=0; j<fNa; j++)
+            v1(0,i) += v3(j,0) * gUnfold.fVacovInv(j,i) ;
+    }
+
+    for (UInt_t i = 0; i<fNa; i++)
+        gUnfold.Chi2(i,0) = v1(0,i) * v3(i,0);
+
+    Double_t chisqsum = 0;
+    for (Int_t i=0; i<gUnfold.Chi2.GetNrows(); i++)
+      chisqsum += gUnfold.Chi2(i, 0);
+    gUnfold.Chisq = chisqsum;
+    
+    //-----------------------------------------------------
+    // calculate 2nd derivative squared
+    // regularization term (second derivative squared)
+    gUnfold.SecDeriv = 0;
+    for (UInt_t j=1; j<(fNb-1); j++)
+     {
+         const Double_t temp =
+             + 2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+             - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+
+         gUnfold.SecDeriv += temp*temp;
+     }
+
+    gUnfold.ZerDeriv = 0;
+    for (UInt_t j=0; j<fNb; j++)
+        gUnfold.ZerDeriv += fVb(j,0) * fVb(j,0);
+
+    f = gUnfold.Chisq/2 * gUnfold.fW + gUnfold.SecDeriv;
+
+    //*fLog << "F=" << f      << " \tSecDeriv=" << gUnfold.SecDeriv
+    //     << " \tchi2="
+    //	  << gUnfold.Chisq << " \tfW=" << gUnfold.fW << endl;
+
+    //--------------------------------------------------------------------
+    // final calculations
+    if (iflag == 3)
+    {
+        //..............................................
+        // calculate external error matrix of the fitted parameters 'val'
+        // extend it with the covariances for y=1-sum(val)
+        Double_t emat[20][20];
+        Int_t    ndim = 20;
+        gMinuit->mnemat(&emat[0][0], ndim);
+
+        Double_t covv = 0;
+        for (UInt_t i=0; i<(gUnfold.fNb-1); i++)
+        {
+            Double_t cov = 0;
+            for (UInt_t k=0; k<(gUnfold.fNb-1); k++)
+                cov += emat[i][k];
+
+            emat[i][gUnfold.fNb-1] = -cov;
+            emat[gUnfold.fNb-1][i] = -cov;
+
+            covv += cov;
+        }
+        emat[gUnfold.fNb-1][gUnfold.fNb-1] = covv;
+
+        for (UInt_t i=0; i<gUnfold.fNb; i++)
+            for (UInt_t k=0; k<gUnfold.fNb; k++)
+                gUnfold.fVbcov(i,k) = emat[i][k] *norm*norm;
+
+        //-----------------------------------------------------
+        //..............................................
+        // put unfolded distribution into fResult
+        //     fResult(i,0)   value in bin i
+        //     fResult(i,1)   error of value in bin i
+
+        gUnfold.fResult.ResizeTo(gUnfold.fNb, 5);
+
+        Double_t sum = 0;
+        for (UInt_t i=0; i<(gUnfold.fNb-1); i++)
+        {
+            Double_t val;
+            Double_t err;
+            if (!gMinuit->GetParameter(i, val, err))
+            {
+                gLog << "Error getting parameter #" << i << endl;
+                return;
+            }
+
+            Double_t eplus;
+            Double_t eminus;
+            Double_t eparab;
+            Double_t gcc;
+            gMinuit->mnerrs(i, eplus, eminus, eparab, gcc);
+
+            gUnfold.fVb(i, 0)     = val    * norm;
+
+            gUnfold.fResult(i, 0) = val    * norm;
+            gUnfold.fResult(i, 1) = eparab * norm;
+            gUnfold.fResult(i, 2) = eplus  * norm;
+            gUnfold.fResult(i, 3) = eminus * norm;
+            gUnfold.fResult(i, 4) = gcc;
+            sum += val;
+        }
+        gUnfold.fVb(gUnfold.fNb-1, 0)     = (1.0-sum) * norm;
+
+        gUnfold.fResult(gUnfold.fNb-1, 0) = (1.0-sum) * norm;
+        gUnfold.fResult(gUnfold.fNb-1, 1) =
+            sqrt(gUnfold.fVbcov(gUnfold.fNb-1,gUnfold.fNb-1));
+        gUnfold.fResult(gUnfold.fNb-1, 2) = 0;
+        gUnfold.fResult(gUnfold.fNb-1, 3) = 0;
+        gUnfold.fResult(gUnfold.fNb-1, 4) = 1;
+        //..............................................
+
+        //-----------------------------------------------------
+        // calculate 0th derivative squared
+        gUnfold.ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            gUnfold.ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+
+        gUnfold.Entropy = 0;
+        for (UInt_t j=0; j<gUnfold.fNb; j++)
+            if (p(j,0) > 0)
+                gUnfold.Entropy += p(j,0) * log( p(j,0) );
+
+
+        //-----------------------------------------------------
+        // calculate SpurSigma
+        gUnfold.SpurSigma = 0.0;
+        for (UInt_t m=0; m<fNb; m++)
+            gUnfold.SpurSigma += gUnfold.fVbcov(m,m);
+        // *fLog << "SpurSigma =" << SpurSigma << endl;
+
+        //-----------------------------------------------------
+        gUnfold.SpurAR  = 0;
+        gUnfold.DiffAR2 = 0;
+
+        //-----------------------------------------------------
+        gUnfold.fNdf   = gUnfold.fNa;
+        gUnfold.fChisq   = gUnfold.Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          gUnfold.fChi2(i,0) = gUnfold.Chi2(i,0);
+	}
+
+
+        UInt_t iNdf = (UInt_t) (gUnfold.fNdf+0.5);
+
+        //*fLog << "fcnTikhonov2 : fW, chisq (from fcnF) = "
+        //     << gUnfold.fW << ",  " << gUnfold.fChisq << endl;
+
+        gUnfold.fProb = iNdf>0 ? TMath::Prob(gUnfold.fChisq, iNdf) : 0;
+    }
+}
+
+
+TH1 *MUnfold::DrawMatrixClone(const TMatrixD &m, Option_t *opt="")
+{
+    const Int_t nrows = m.GetNrows();
+    const Int_t ncols = m.GetNcols();
+
+    TMatrix m2(nrows, ncols);
+    for (int i=0; i<nrows; i++)
+        for (int j=0; j<ncols; j++)
+            m2(i, j) = m(i, j);
+
+    TH2F *hist = new TH2F(m2);
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+
+}
+
+
+TH1 *MUnfold::DrawMatrixColClone(const TMatrixD &m, Option_t *opt="", Int_t col=0)
+{
+    const Int_t nrows = m.GetNrows();
+
+    TVector vec(nrows);
+    for (int i=0; i<nrows; i++)
+        vec(i) = m(i, col);
+
+    TH1F *hist = new TH1F("TVector","",nrows,0,nrows);
+    for (int i=0; i<nrows; i++)
+      hist->SetBinContent(i+1, vec(i));
+    
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+}
+
+
+void MUnfold::PrintTH3Content(const TH3 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+      for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+        for (Int_t k=1; k<=hist.GetNbinsZ(); k++)
+            *fLog << hist.GetBinContent(i,j,k) << " \t";
+      *fLog << endl << endl;
+    }
+}
+
+void MUnfold::PrintTH3Error(const TH3 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+      for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+        for (Int_t k=1; k<=hist.GetNbinsZ(); k++)
+            *fLog << hist.GetBinError(i, j, k) << " \t";
+      *fLog << endl << endl;
+    }
+}
+
+void MUnfold::PrintTH2Content(const TH2 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            *fLog << hist.GetBinContent(i,j) << " \t";
+        *fLog << endl << endl;
+}
+
+void MUnfold::PrintTH2Error(const TH2 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            *fLog << hist.GetBinError(i, j) << " \t";
+        *fLog << endl << endl;
+}
+
+void MUnfold::PrintTH1Content(const TH1 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        *fLog << hist.GetBinContent(i) << " \t";
+    *fLog << endl << endl;
+}
+
+void MUnfold::PrintTH1Error(const TH1 &hist)
+{
+    *fLog << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    *fLog << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        *fLog << hist.GetBinError(i) << " \t";
+    *fLog << endl << endl;
+}
+
+void MUnfold::CopyCol(TMatrixD &m, const TH1 &h, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        m(i, col) = h.GetBinContent(i+1);
+}
+
+void MUnfold::CopyCol(TH1 &h, const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        h.SetBinContent(i+1, m(i, col));
+}
+
+void MUnfold::CopyH2M(TMatrixD &m, const TH2 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+            m(i, j) = h.GetBinContent(i+1, j+1);
+}
+
+void MUnfold::CopySqr(TMatrixD &m, const TH1 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+        {
+            const Double_t bin =  h.GetBinContent(i+1, j+1);
+            m(i, j) = bin*bin;
+        }
+}
+
+Double_t MUnfold::GetMatrixSumRow(const TMatrixD &m, Int_t row)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(row, i);
+
+    return sum;
+}
+
+Double_t MUnfold::GetMatrixSumDiag(const TMatrixD &m)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, i);
+
+    return sum;
+}
+
+Double_t MUnfold::GetMatrixSumCol(const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, col);
+
+    return sum;
+}
+
+Double_t MUnfold::GetMatrixSum(const TMatrixD &m)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += GetMatrixSumRow(m, i);
+
+    return sum;
+}
+
+
+Double_t MUnfold::CalcSpurSigma(TMatrixD &T, Double_t norm)
+{
+  Double_t spursigma = 0;
+  
+  for (UInt_t a=0; a<fNb; a++)
+    {
+      for (UInt_t b=0; b<fNb; b++)
+	{
+	  fVbcov(a,b) = 0;
+	  
+	  for (UInt_t c=0; c<fNa; c++)
+	    for (UInt_t d=0; d<fNa; d++)
+	      fVbcov(a,b) += T(a,d)*fVacov(d,c)*T(b,c);
+	  
+	  fVbcov(a,b) *= norm*norm;
+	}
+      spursigma += fVbcov(a,a);
+    }
+  
+  return spursigma;
+}
+
+
+MUnfold::MUnfold(TH1D &ha, TH2D &hacov, TH2D &hmig)
+        : fVEps(hmig.GetYaxis()->GetNbins(),1), fVEps0(fVEps, 0)
+    {
+        // ha      is the distribution to be unfolded
+        // hacov   is the covariance matrix of ha
+        // hmig    is the migration matrix;
+        //         this matrix will be used in the unfolding
+        //         unless SmoothMigrationMatrix(*hmigrat) is called;
+        //         in the latter case hmigrat is smoothed
+        //         and the smoothed matrix is used in the unfolding
+
+        // Eigen values of the matrix G, which are smaller than EpsLambda
+        // will be considered as being zero
+        EpsLambda = 1.e-10;
+        fW = 0.0;
+
+        fNa  = hmig.GetXaxis()->GetNbins();
+        const Double_t alow = hmig.GetXaxis()->GetXmin();
+        const Double_t aup  = hmig.GetXaxis()->GetXmax();
+
+        fNb  = hmig.GetYaxis()->GetNbins();
+        const Double_t blow = hmig.GetYaxis()->GetXmin();
+        const Double_t bup  = hmig.GetYaxis()->GetXmax();
+
+
+        UInt_t Na = ha.GetNbinsX();
+        if (fNa != Na)
+        {
+            *fLog << "MUnfold::MUnfold : dimensions do not match,  fNa = ";
+            *fLog << fNa << ",   Na = " << Na << endl;
+        }
+
+        *fLog << "MUnfold::MUnfold :" << endl;
+        *fLog << "==================" << endl;
+        *fLog << "   fNa = " << fNa << ",   fNb = " << fNb << endl;
+
+        // ------------------------
+
+        fVa.ResizeTo(fNa, 1);
+        CopyCol(fVa, ha, 0);
+
+        *fLog << "   fVa = ";
+
+        for (UInt_t i=0; i<fNa; i++)
+            *fLog << fVa(i,0) << " \t";
+        *fLog << endl;
+
+        Double_t vaevents = GetMatrixSumCol(fVa, 0);
+        *fLog << "   Total number of events in fVa = " << vaevents << endl;
+
+        // ------------------------
+
+        fChi2.ResizeTo(fNa,1);
+        Chi2.ResizeTo(fNa,1);
+
+        // ------------------------
+
+        fVacov.ResizeTo(fNa, fNa);
+        fSpurVacov = 0;
+
+        CopyH2M(fVacov, hacov);
+
+        fVapoints = 0;
+        for (UInt_t i=0; i<fNa; i++)
+            if (fVa(i,0)>0 && fVacov(i,i)<fVa(i,0)*fVa(i,0))
+                fVapoints++;
+
+        fSpurVacov = GetMatrixSumDiag(fVacov);
+
+        //*fLog << "MUnfold::MUnfold :   fVacov = " << endl;
+        //*fLog << "==============================" << endl;
+        //fVacov.Print();
+
+        *fLog << "   Number of significant points in fVa = ";
+        *fLog << fVapoints << endl;
+
+        *fLog << "   Spur of fVacov = ";
+        *fLog << fSpurVacov << endl;
+
+        // ------------------------
+
+        fVacovInv.ResizeTo(fNa, fNa);
+        fVacovInv = fVacov;
+        fVacovInv.InvertPosDef();
+
+        //*fLog << "MUnfold::MUnfold :   fVacovInv = " << endl;
+        //*fLog << "==================================" << endl;
+        //fVacovInv.Print();
+
+        // ------------------------
+        // fMigrat is the migration matrix to be used in the unfolding;
+        // fMigrat may be overwritten by SmoothMigrationMatrix
+
+        fMigrat.ResizeTo(fNa, fNb); // row, col
+
+        CopyH2M(fMigrat, hmig);
+
+
+        // ------------------------
+
+        fMigraterr2.ResizeTo(fNa, fNb); // row, col
+        CopySqr(fMigraterr2, hmig);
+
+        // normaxlize
+
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            const Double_t sum = GetMatrixSumCol(fMigrat, j);
+
+            if (sum==0)
+                continue;
+
+            TMatrixDColumn col1(fMigrat, j);
+            col1 *= 1./sum;
+
+            TMatrixDColumn col2(fMigraterr2, j);
+            col2 *= 1./(sum*sum);
+        }
+
+        //*fLog << "MUnfold::MUnfold :   fMigrat = " << endl;
+        //*fLog << "===============================" << endl;
+        //fMigrat.Print();
+
+        //*fLog << "MUnfold::MUnfold :   fMigraterr2 = " << endl;
+        //*fLog << "===================================" << endl;
+        //fMigraterr2.Print();
+
+        // ------------------------
+        G.ResizeTo(fNa, fNa);
+        EigenValue.ResizeTo(fNa);
+        Eigen.ResizeTo(fNa, fNa);
+
+        fMigOrig.ResizeTo(fNa, fNb); 
+        fMigOrigerr2.ResizeTo(fNa, fNb); 
+
+        fMigSmoo.ResizeTo    (fNa, fNb); 
+        fMigSmooerr2.ResizeTo(fNa, fNb); 
+        fMigChi2.ResizeTo    (fNa, fNb); 
+
+        // ------------------------
+
+        fVEps0 = 1./fNb;
+
+        //*fLog << "MUnfold::MUnfold :   Default prior distribution fVEps = " << endl;
+        //*fLog << "========================================================" << endl;
+        //fVEps.Print();
+
+        // ------------------------
+
+        fVb.ResizeTo(fNb,1);
+        fVbcov.ResizeTo(fNb,fNb);
+
+        // ----------------------------------------------------
+        // number and range of weights to be scanned
+        Nix  = 30;
+        xmin = 1.e-5;
+        xmax = 1.e5;
+        dlogx = (log10(xmax)-log10(xmin)) / Nix;
+
+        SpSig.ResizeTo (Nix);
+        SpAR.ResizeTo  (Nix);
+        chisq.ResizeTo (Nix);
+        SecDer.ResizeTo(Nix);
+        ZerDer.ResizeTo(Nix);
+        Entrop.ResizeTo(Nix);
+        DAR2.ResizeTo  (Nix);
+        Dsqbar.ResizeTo(Nix);
+
+        //------------------------------------
+        // plots as a function of the iteration  number
+
+        hBchisq = new TH1D("Bchisq", "chisq",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSpAR  = new TH1D("BSpAR", "SpurAR",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSpAR  = new TH1D("BDSpAR", "Delta(SpurAR)",
+                            Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSpSig = new TH1D("BSpSig", "SpurSigma/SpurC",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSpSig = new TH1D("BDSpSig", "Delta(SpurSigma/SpurC)",
+                            Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBSecDeriv = new TH1D("BSecDeriv", "Second Derivative squared",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDSecDeriv = new TH1D("BDSecDeriv", "Delta(Second Derivative squared)",
+                               Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBZerDeriv = new TH1D("BZerDeriv", "Zero Derivative squared",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDZerDeriv = new TH1D("BDZerDeriv", "Delta(Zero Derivative squared)",
+                               Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBEntropy = new TH1D("BEntrop", "Entropy",
+                             Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDEntropy = new TH1D("BDEntrop", "Delta(Entropy)",
+                              Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBDAR2 = new TH1D("BDAR2", "norm(AR-AR+)",
+                          Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        hBD2bar = new TH1D("BD2bar", "(b_unfolded-b_ideal)**2",
+                           Nix, log10(xmin)-dlogx/2.0, log10(xmax)-dlogx/2.0 );
+
+        //-------------------------------------
+        // original migration matrix
+        fhmig = new TH2D("fMigrat", "Migration matrix",
+                         fNa, alow, aup, fNb, blow, bup);
+        fhmig->Sumw2();
+
+        //-------------------------------------
+        // smoothed migration matrix
+        shmig = new TH2D("sMigrat", "Smoothed migration matrix",
+                         fNa, alow, aup, fNb, blow, bup);
+        shmig->Sumw2();
+
+        //-------------------------------------
+        // chi2 contributions for smoothing of migration matrix
+        shmigChi2 = new TH2D("sMigratChi2", "Chi2 contr. for smoothing",
+                             fNa, alow, aup, fNb, blow, bup);
+
+        //-------------------------------------
+        // eigen values of matrix G = M * M(transposed)
+        hEigen = new TH1D("Eigen", "Eigen values of M*MT",
+                          fNa, 0.5, fNa+0.5);
+
+        //------------------------------------
+        // Ideal distribution
+        
+        fhb0 = new TH1D("fhb0", "Ideal distribution", fNb, blow, bup);
+        fhb0->Sumw2();
+        
+
+        //------------------------------------
+        // Distribution to be unfolded
+        fha = new TH1D("fha", "Distribution to be unfolded", fNa, alow, aup);
+        fha->Sumw2();
+
+        //------------------------------------
+        // Prior distribution
+        hprior = new TH1D("Prior", "Prior distribution", fNb, blow, bup);
+
+        //-----------------------------S-------
+        // Unfolded distribution
+        hb = new TH1D("DataSp", "Unfolded distribution", fNb, blow, bup);
+        hb->Sumw2();
+
+    }
+
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+    MUnfold::~MUnfold()
+    {
+//       if (hBchisq) delete hBchisq;
+//       if (hBSpAR) delete hBSpAR;
+//       if (hBDSpAR) delete hBDSpAR;
+//       if (hBSpSig) delete hBSpSig;
+//       if (hBDSpSig) delete hBDSpSig;
+//       if (hBSecDeriv) delete hBSecDeriv;
+//       if (hBSecDeriv) delete hBDSecDeriv;
+//       if (hBZerDeriv) delete hBZerDeriv;
+//       if (hBDZerDeriv) delete hBDZerDeriv;
+//       if (hBEntropy) delete hBEntropy;
+//       if (hBDEntropy) delete hBDEntropy;
+//       if (hBDAR2) delete hBDAR2;
+//       if (hBD2bar) delete hBD2bar;
+//       if (fhmig) delete fhmig;
+//       if (shmig) delete shmig;
+//       if (shmigChi2) delete shmigChi2;
+//       if (hEigen) delete hEigen;
+//       if (fhb0) delete fhb0;
+//       if (fha) delete fha;
+//       if (hprior) delete hprior;
+//       if (hb) delete hb;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Define prior distribution to be a constant
+    //
+    void MUnfold::SetPriorConstant()
+    {
+        fVEps0 = 1./fNb;
+
+        CopyCol(*hprior, fVEps);
+
+        //*fLog << "SetPriorConstant : Prior distribution fVEps = " << endl;
+        //*fLog << "==============================================" << endl;
+        //fVEps.Print();
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Take prior distribution from the histogram 'ha'
+    // which may have a different binning than 'hprior'
+    //
+    Bool_t MUnfold::SetPriorRebin(TH1D &ha)
+    {
+
+        // ------------------------------------------------------------------
+        //
+        // fill the contents of histogram 'ha' into the histogram 'hprior';
+        // the histograms need not have the same binning;
+        // if the binnings are different, the bin contents of histogram 'ha'
+        //    are distributed properly (linearly) over the bins of 'hprior'
+        //
+
+        const Int_t    na   = ha.GetNbinsX();
+        const Double_t alow = ha.GetBinLowEdge(1);
+        const Double_t aup  = ha.GetBinLowEdge(na+1);
+
+        const Int_t    nb   = hprior->GetNbinsX();
+        const Double_t blow = hprior->GetBinLowEdge(1);
+        const Double_t bup  = hprior->GetBinLowEdge(nb+1);
+
+        // check whether there is an overlap
+        //       between the x ranges of the 2 histograms
+        if (alow>bup || aup<blow)
+        {
+            *fLog << "Rebinning not possible because there is no overlap of the x ranges of the two histograms" << endl;
+            return kFALSE;
+        }
+
+        // there is an overlap
+        //********************
+        Double_t sum = 0;
+        for (Int_t j=1; j<=nb; j++)
+        {
+            const Double_t yl = hprior->GetBinLowEdge(j);
+            const Double_t yh = hprior->GetBinLowEdge(j+1);
+
+            // search bins of histogram ha which contribute
+            // to bin j of histogram hb
+            //----------------
+            Int_t il=0;
+            Int_t ih=0;
+            for (Int_t i=2; i<=na+1; i++)
+            {
+                const Double_t xl = ha.GetBinLowEdge(i);
+                if (xl>yl)
+                {
+                    il = i-1;
+
+                    //.................................
+                    ih = 0;
+                    for (Int_t k=(il+1); k<=(na+1); k++)
+                    {
+                        const Double_t xh = ha.GetBinLowEdge(k);
+                        if (xh >= yh)
+                        {
+                            ih = k-1;
+                            break;
+                        }
+                    }
+                    //.................................
+                    if (ih == 0)
+                        ih = na;
+                    break;
+                }
+            }
+            //----------------
+            if (il == 0)
+            {
+                *fLog << "Something is wrong " << endl;
+                *fLog << "          na, alow, aup = " << na << ",  " << alow
+                    << ",  " << aup << endl;
+                *fLog << "          nb, blow, bup = " << nb << ",  " << blow
+                    << ",  " << bup << endl;
+                return kFALSE;
+            }
+
+            Double_t content=0;
+            // sum up the contribution to bin j
+            for (Int_t i=il; i<=ih; i++)
+            {
+                const Double_t xl = ha.GetBinLowEdge(i);
+                const Double_t xh = ha.GetBinLowEdge(i+1);
+                const Double_t bina = xh-xl;
+
+                if (xl<yl  &&  xh<yh)
+                    content += ha.GetBinContent(i) * (xh-yl) / bina;
+                else
+                    if (xl<yl  &&  xh>=yh)
+                        content += ha.GetBinContent(i) * (yh-yl) / bina;
+                    else
+                        if (xl>=yl  &&  xh<yh)
+                            content += ha.GetBinContent(i);
+                        else if (xl>=yl  &&  xh>=yh)
+                            content += ha.GetBinContent(i) * (yh-xl) / bina;
+            }
+            hprior->SetBinContent(j, content);
+            sum += content;
+        }
+
+        // normalize histogram hb
+        if (sum==0)
+        {
+            *fLog << "histogram hb is empty; sum of weights in ha = ";
+            *fLog << ha.GetSumOfWeights() << endl;
+            return kFALSE;
+        }
+
+        for (Int_t j=1; j<=nb; j++)
+        {
+            const Double_t content = hprior->GetBinContent(j)/sum;
+            hprior->SetBinContent(j, content);
+            fVEps0(j-1) = content;
+        }
+
+        //*fLog << "SetPriorRebin : Prior distribution fVEps = " << endl;
+        //*fLog << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Set prior distribution to a given distribution 'hpr'
+    //
+    Bool_t MUnfold::SetPriorInput(TH1D &hpr)
+    {
+        CopyCol(fVEps, hpr);
+
+        const Double_t sum = GetMatrixSumCol(fVEps, 0);
+
+        if (sum<=0)
+        {
+            *fLog << "MUnfold::SetPriorInput: invalid prior distribution" << endl;
+            return kFALSE;
+        }
+
+        // normalize prior distribution
+        fVEps0 *= 1./sum;
+
+        CopyCol(*hprior, fVEps);
+
+        //*fLog << "SetPriorInput : Prior distribution fVEps = " << endl;
+        //*fLog << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Define prior distribution to be a power law
+    // use input distribution 'hprior' only
+    //           for defining the histogram parameters
+    //
+    Bool_t MUnfold::SetPriorPower(Double_t gamma)
+    {
+        // generate distribution according to a power law
+        //                        dN/dE = E^{-gamma}
+        //  or with y = lo10(E),  E = 10^y :
+        //                        dN/dy = ln10 * 10^{y*(1-gamma)}
+        TH1D hpower(*hprior);
+
+        const UInt_t   nbin = hprior->GetNbinsX();
+        const Double_t xmin = hprior->GetBinLowEdge(1);
+        const Double_t xmax = hprior->GetBinLowEdge(nbin+1);
+
+        *fLog << "nbin, xmin, xmax = " << nbin << ",  ";
+        *fLog << xmin << ",  " << xmax << endl;
+
+        TF1* fpow = new TF1("fpow", "pow(10.0, x*(1.0-[0]))", xmin,xmax);
+        fpow->SetParName  (0,"gamma");
+        fpow->SetParameter(0, gamma );
+
+        hpower.FillRandom("fpow", 100000);
+
+        // fill prior distribution
+        CopyCol(fVEps, hpower);
+
+        const Double_t sum = GetMatrixSumCol(fVEps, 0);
+        if (sum <= 0)
+        {
+            *fLog << "MUnfold::SetPriorPower : invalid prior distribution"  << endl;
+            return kFALSE;
+        }
+
+        // normalize prior distribution
+        fVEps0 *= 1./sum;
+        CopyCol(*hprior, fVEps);
+
+        //*fLog << "SetPriorPower : Prior distribution fVEps = " << endl;
+        //*fLog << "===========================================" << endl;
+        //fVEps.Print();
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Set the initial weight
+    //
+    Bool_t MUnfold::SetInitialWeight(Double_t &weight)
+    {
+        if (weight == 0.0)
+        {
+            TMatrixD v1(fVa, TMatrixD::kTransposeMult, fVacovInv);
+            TMatrixD v2(v1, TMatrixD::kMult, fVa);
+            weight = 1./sqrt(v2(0,0));
+        }
+
+        *fLog << "MUnfold::SetInitialWeight : Initial Weight = "
+            << weight << endl;
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Print the unfolded distribution
+    //
+    void MUnfold::PrintResults()
+    {
+        *fLog << bintitle << endl;
+        *fLog << "PrintResults : Unfolded distribution fResult " << endl;
+        *fLog << "=============================================" << endl;
+        //*fLog << "val, eparab, eplus, eminus, gcc = "  << endl;
+
+        for (UInt_t i=0; i<fNb; i++)
+        {
+	  //    *fLog << fResult(i, 0) << " \t";
+          //  *fLog << fResult(i, 1) << " \t";
+          //  *fLog << fResult(i, 2) << " \t";
+          //  *fLog << fResult(i, 3) << " \t";
+          //  *fLog << fResult(i, 4) <<  endl;
+        }
+        *fLog << "Chisquared, NDF, chi2 probability, ixbest = "
+            << fChisq << ",  "
+            << fNdf << ",  " << fProb << ",  " << ixbest << endl;
+
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Schmelling  : unfolding by minimizing the function Z
+    //               by Gauss-Newton iteration
+    //
+    //               the weights are scanned between
+    //               1.e-5*fWinitial and 1.e5*fWinitial
+    //
+    Bool_t MUnfold::Schmelling(TH1D &hb0)
+    {
+    
+        //======================================================================
+        // copy ideal distribution
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+    
+        //-----------------------------------------------------------------------
+        // Initialization
+        // ==============
+
+        Int_t numGiteration;
+        Int_t MaxGiteration = 1000;
+
+        TMatrixD alpha;
+        alpha.ResizeTo(fNa, 1);
+
+
+        //-----------------------------------------------------------------------
+        // Newton iteration
+        // ================
+
+        Double_t dga2;
+        Double_t dga2old;
+        Double_t EpsG = 1.e-12;
+
+        TMatrixD wZdp_inv(fNa, fNa);
+        TMatrixD d(fNb, 1);
+        TMatrixD p(fNb, 1);
+
+        TMatrixD gamma (fNa, 1);
+        TMatrixD dgamma(fNa, 1);
+
+        Double_t fWinitial;
+        fWinitial = 0.0;
+        SetInitialWeight(fWinitial);
+        // for my example this fWinitial was not good; therefore :
+        fWinitial = 1.0;
+
+        Int_t ix;
+        Double_t xiter;
+
+        //--------   start  scanning weights   --------------------------
+        // if full == kFALSE   only quantities necessary for the Gauss-Newton
+        //                     iteration are calculated in SchmellCore
+        // if full == kTRUE    in addition the unfolded distribution,
+        //                     its covariance matrix and quantities like
+        //                     Chisq, SpurAR, etc. are computed in SchmellCore
+        //Bool_t full;
+        //full = kFALSE;
+        Int_t full;
+
+        *fLog << "Schmelling : start loop over weights" << endl;
+
+        dga2 = 1.e20;
+        for (ix=0; ix<Nix; ix++)
+        {
+            xiter = pow(10.0,log10(xmin)+ix*dlogx) * fWinitial;
+
+            //----------   start Gauss-Newton iteration   ----------------------
+            numGiteration = 0;
+
+            // if there was no convergence and the starting gamma was != 0
+            // redo unfolding for the same weight starting with gamma = 0
+            //
+            Int_t gamma0 = 0;
+            while (1)
+	    {
+              if (dga2 > EpsG)
+	      {
+                gamma0 = 1;
+                gamma.Zero();
+	      }
+
+              dga2 = 1.e20;
+
+              while (1)
+              {
+                dga2old = dga2;
+
+                full = 0;
+                SchmellCore(full, xiter, gamma, dgamma, dga2);
+
+                gamma += dgamma;
+
+                //*fLog << "Schmelling : ix, numGiteration, dga2, dga2old = "
+                //     << ix << ",  " << numGiteration << ",  "
+                //     << dga2 << ",  " << dga2old << endl;
+
+                numGiteration += 1;
+
+                // convergence
+                if (dga2 < EpsG)
+                    break;
+
+                // no convergence
+                if (numGiteration > MaxGiteration)
+                    break;
+
+                // gamma doesn't seem to change any more
+                if (fabs(dga2-dga2old) < EpsG/100.)
+                    break;
+              }
+              //----------   end Gauss-Newton iteration   ------------------------
+              if (dga2<EpsG || gamma0 != 0) break;
+	    }
+
+            // if Gauss-Newton iteration has not converged
+            // go to next weight
+            if (dga2 > EpsG)
+            {
+                *fLog << "Schmelling : Gauss-Newton iteration has not converged;"
+                    << "   numGiteration = " << numGiteration << endl;
+                *fLog << "             ix, dga2, dga2old = " << ix << ",  "
+                    << dga2 << ",  " << dga2old << endl;
+                continue;
+            }
+
+            //*fLog << "Schmelling : Gauss-Newton iteration has converged;" << endl;
+            //*fLog << "==================================================" << endl;
+            //*fLog << "             numGiteration = " << numGiteration << endl;
+            //*fLog << "             ix, dga2 = " << ix << ",  " << dga2 << endl;
+
+            // calculated quantities which will be useful for determining
+            // the best weight (Chisq, SpurAR, ...)
+            //full = kTRUE;
+            full = 1;
+            SchmellCore(full, xiter, gamma, dgamma, dga2);
+
+            // calculate difference between ideal and unfolded distribution
+            Double_t D2bar = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                D2bar += temp*temp;
+            }
+
+            SpAR(ix)  = SpurAR;
+            SpSig(ix) = SpurSigma;
+            chisq(ix) = Chisq;
+            SecDer(ix) = SecDeriv;
+            ZerDer(ix) = ZerDeriv;
+            Entrop(ix) = Entropy;
+            DAR2(ix)   = DiffAR2;
+            Dsqbar(ix) = D2bar;
+
+        }
+        //----------   end of scanning weights   -------------------------------
+        *fLog << "Schmelling : end of loop over weights" << endl;
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xbin = log10(xmin)+ix*dlogx;
+            xiter = pow(10.0,xbin) * fWinitial;
+
+            Int_t bin;
+            bin = hBchisq->FindBin( xbin );
+            hBchisq->SetBinContent(bin,chisq(ix));
+            hBSpAR->SetBinContent(bin,SpAR(ix));
+            hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+            hBSecDeriv->SetBinContent(bin,SecDer(ix));
+            hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+            hBEntropy->SetBinContent(bin,Entrop(ix));
+            hBDAR2->SetBinContent(bin,DAR2(ix));
+            hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+            if (ix > 0)
+            {
+                Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                hBDSpAR->SetBinContent(bin,DSpAR);
+
+                Double_t diff = SpSig(ix) - SpSig(ix-1);
+                Double_t DSpSig = diff;
+                hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                hBDEntropy->SetBinContent(bin,DEntrop);
+
+                Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                hBDZerDeriv->SetBinContent(bin,DZerDer);
+            }
+        }
+
+        // Select best weight
+        SelectBestWeight();
+
+        if (ixbest < 0.0)
+        {
+            *fLog << "Schmelling : no solution found; " << endl;
+            return kFALSE;
+        }
+
+        // do the unfolding using the best weight
+        //full = kTRUE;
+
+
+        xiter = pow(10.0,log10(xmin)+ixbest*dlogx) * fWinitial;
+
+        //----------   start Gauss-Newton iteration   ----------------------
+        numGiteration = 0;
+        gamma.Zero();
+        dga2 = 1.e20;
+
+        while (1)
+        {
+            full = 1;
+            SchmellCore(full, xiter, gamma, dgamma, dga2);
+            gamma += dgamma;
+
+            //*fLog << "Schmelling : sum(dgamma^2) = " << dga2 << endl;
+
+            numGiteration += 1;
+
+            if (numGiteration > MaxGiteration)
+                break;
+
+            if (dga2 < EpsG)
+                break;
+        }
+        //----------   end Gauss-Newton iteration   ------------------------
+
+
+        //-----------------------------------------------------------------------
+        // termination stage
+        // =================
+
+        *fLog << "Schmelling : best solution found; " << endl;
+        *fLog << "==================================" << endl;
+        *fLog << "             xiter, ixbest, numGiteration, Chisq = "
+            << xiter << ",  " << ixbest << ",  "
+            << numGiteration << ",  " << Chisq << endl;
+
+        //------------------------------------
+        //..............................................
+        // put unfolded distribution into fResult
+        //     fResult(i,0)   value in bin i
+        //     fResult(i,1)   error of value in bin i
+
+        fNdf = SpurAR;
+        fChisq = Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          fChi2(i,0) = Chi2(i,0);
+	}
+
+        UInt_t iNdf   = (UInt_t) (fNdf+0.5);
+        fProb = iNdf>0 ? TMath::Prob(fChisq, iNdf) : 0;
+
+        fResult.ResizeTo(fNb, 5);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            fResult(i, 0) = fVb(i,0);
+            fResult(i, 1) = sqrt(fVbcov(i,i));
+            fResult(i, 2) = 0.0;
+            fResult(i, 3) = 0.0;
+            fResult(i, 4) = 1.0; 
+	}
+
+        //--------------------------------------------------------
+
+        *fLog << "Schmelling : gamma = " << endl;
+        for (UInt_t i=0; i<fNa; i++)
+            *fLog << gamma(i,0) << " \t";
+        *fLog << endl;
+
+        return kTRUE;
+    }
+
+
+
+
+    // -----------------------------------------------------------------------
+    //
+    // SchmellCore     main part of Schmellings calculations
+    //
+    void MUnfold::SchmellCore(Int_t full, Double_t &xiter, TMatrixD &gamma,
+                     TMatrixD &dgamma, Double_t &dga2)
+    {
+        Double_t norm;
+        TMatrixD wZdp_inv(fNa, fNa);
+        TMatrixD d(fNb, 1);
+        TMatrixD p(fNb, 1);
+
+        //--------------------------------------------------------
+        //--      determine the probability vector p
+
+
+        TMatrixD v3(gamma, TMatrixD::kTransposeMult, fMigrat);
+        TMatrixD v4(TMatrixD::kTransposed, v3);
+        d = v4;
+        Double_t dmax  = -1.e10;
+        for (UInt_t j=0; j<fNb; j++)
+            if (d(j,0)>dmax)
+                dmax = d(j,0);
+
+        Double_t psum = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            d(j,0) -= dmax;
+            p(j,0)  = fVEps0(j)*exp(xiter*d(j,0));
+            psum += p(j,0);
+        }
+
+        p *= 1.0/psum;
+
+        //--      get the vector alpha
+
+        TMatrixD alpha(fMigrat, TMatrixD::kMult, p);
+
+        //--      determine the current normalization
+
+        TMatrixD v2   (alpha, TMatrixD::kTransposeMult, fVacovInv);
+        TMatrixD normb(v2,    TMatrixD::kMult, alpha);
+
+        TMatrixD normc(v2,    TMatrixD::kMult, fVa);
+
+        norm  = normc(0,0)/normb(0,0);
+
+        //--------------------------------------------------------
+        //--      determine the scaled slope vector s and Hessian H
+
+        TMatrixD Zp(fNa,1);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            Zp(i,0) = norm*alpha(i,0) - fVa(i,0);
+            for (UInt_t k=0; k<fNa; k++)
+                Zp(i,0) += gamma(k,0)*fVacov(k,i);
+        }
+
+
+        TMatrixD Q  (fNa, fNa);
+        TMatrixD wZdp(fNa, fNa);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                Q(i,j) = - alpha(i,0)*alpha(j,0);
+                for (UInt_t k=0; k<fNb; k++)
+                    Q(i,j) += fMigrat(i,k)*fMigrat(j,k)*p(k,0);
+                wZdp(i,j) = xiter*norm*Q(i,j) + fVacov(i,j);
+            }
+        }
+
+        //--      invert H and calculate the next Newton step
+
+        Double_t determ = 1.0;
+        wZdp_inv = wZdp;
+        wZdp_inv.Invert(&determ);
+
+        if(determ == 0.0)
+        {
+            *fLog << "SchmellCore: matrix inversion for H failed" << endl;
+            return;
+        }
+
+
+        dga2 = 0.0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            dgamma(i,0) = 0.0;
+            for (UInt_t j=0; j<fNa; j++)
+                dgamma(i,0) -= wZdp_inv(i,j)*Zp(j,0);
+            dga2 += dgamma(i,0)*dgamma(i,0);
+        }
+
+        if (full == 0)
+            return;
+
+        //--------------------------------------------------------
+        //--      determine chi2 and dNdf (#measurements ignored)
+        Double_t dNdf = 0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            Chi2(i,0) = 0;
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                Chi2(i,0) += fVacov(i,j) * gamma(i,0) * gamma(j,0);
+                dNdf       += fVacov(i,j) * wZdp_inv(j,i);
+            }
+        }
+        Chisq = GetMatrixSumCol(Chi2, 0);
+        SpurAR = fNa - dNdf;
+
+        //-----------------------------------------------------
+        // calculate the norm |AR - AR+|**2
+
+        TMatrixD AR(fNa, fNa);
+        DiffAR2 = 0.0;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                AR(i,j) = 0.0;
+                for (UInt_t k=0; k<fNa; k++)
+                    AR(i,j) +=  fVacov(i,k) * wZdp_inv(k,j);
+                DiffAR2 += AR(i,j) * AR(i,j);
+            }
+        }
+
+        //--------------------------------------------------------
+        //--      fill distribution b(*)
+        fVb = p;
+        fVb *= norm;
+
+        //--      determine the covariance matrix of b (very expensive)
+
+        TMatrixD T(fNb,fNa);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            for (UInt_t j=0; j<fNa; j++)
+            {
+                T(i,j) = 0.0;
+                for (UInt_t k=0; k<fNa; k++)
+                    T(i,j) += xiter*wZdp_inv(k,j)*(fMigrat(k,i)-alpha(k,0))*p(i,0);
+            }
+        }
+
+        SpurSigma = CalcSpurSigma(T, norm);
+
+        //--------------------------------------------------------
+
+        //-----------------------------------------------------
+        // calculate the second derivative squared
+
+        SecDeriv = 0;
+        for (UInt_t j=1; j<(fNb-1); j++)
+        {
+            Double_t temp =
+                + 2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+                - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+            SecDeriv += temp*temp;
+        }
+
+        ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+        Entropy = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            if (p(j,0) > 0.0)
+                Entropy += p(j,0) * log( p(j,0) );
+
+        //--------------------------------------------------------
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Smooth migration matrix
+    //              by fitting a function to the migration matrix
+    //
+    Bool_t MUnfold::SmoothMigrationMatrix(TH2D &hmigorig)
+    {
+        // copy histograms into matrices; the matrices will be used in fcnSmooth
+        // ------------------------
+
+      
+      //*fLog << "MUnfold::SmoothMigrationMatrix : fNa, fNb = " << fNa << ",  " << fNb << endl;
+
+      //*fLog << "MUnfold::SmoothMigrationMatrix:   fMigOrig = "  << endl;
+      //*fLog << "========================================"  << endl;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fMigOrig(i, j)     = hmigorig.GetBinContent(i+1, j+1);
+	        //*fLog << fMigOrig(i, j) << " \t";
+            }
+            //*fLog << endl;
+        }
+      
+
+        // ------------------------
+
+      
+        //*fLog << "MUnfold::SmoothMigrationMatrix :   fMigOrigerr2 = " << endl;
+        //*fLog << "=============================================" << endl;
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fMigOrigerr2(i, j) =   hmigorig.GetBinError(i+1, j+1)
+                    * hmigorig.GetBinError(i+1, j+1);
+
+                //*fLog << fMigOrigerr2(i, j) << " \t";
+            }
+            //*fLog << endl;
+        }
+      
+
+        // ------------------------
+        // the number of free parameters (npar) is equal to 6:
+        //     a0mean, a1mean, a2mean     
+        //     <log10(Eest)>    = a0 + a1*log10(Etrue) + a2*SQR(log10(Etrue))
+        //                                                     + log10(Etrue)  
+        //     b0RMS,  b1RMS, b2RMS      
+        //     RMS(log10(Eest)) = b0 + b1*log10(Etrue) + b2*SQR(log10(Etrue))
+        // 
+        UInt_t npar = 6;
+
+        if (npar > 20)
+        {
+            *fLog << "MUnfold::SmoothMigrationMatrix : too many parameters,  npar = "
+                << npar << endl;
+            return kFALSE;
+        }
+
+
+        //..............................................
+        // Find reasonable starting values for a0, a1 and b0, b1
+
+        Double_t xbar   = 0.0;
+        Double_t xxbar  = 0.0;
+
+        Double_t ybarm  = 0.0;
+        Double_t xybarm = 0.0;
+
+        Double_t ybarR  = 0.0;
+        Double_t xybarR = 0.0;
+
+        Double_t Sum = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            Double_t x = (double)j + 0.5;
+
+            Double_t meany = 0.0;
+            Double_t RMSy  = 0.0;
+            Double_t sum   = 0.0;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                Double_t y = (double)i + 0.5;
+                meany +=   y * fMigOrig(i, j);
+                RMSy  += y*y * fMigOrig(i, j);
+                sum   +=       fMigOrig(i, j);
+            }
+            if (sum > 0.0)
+            {
+                meany  = meany / sum;
+                RMSy   =  RMSy / sum  - meany*meany;
+                RMSy = sqrt(RMSy);
+
+                Sum += sum;
+                xbar  +=   x * sum;
+                xxbar += x*x * sum;
+
+                ybarm  +=   meany * sum;
+                xybarm += x*meany * sum;
+
+                ybarR  +=   RMSy  * sum;
+                xybarR += x*RMSy  * sum;
+            }
+        }
+
+        if (Sum > 0.0)
+        {
+            xbar   /= Sum;
+            xxbar  /= Sum;
+
+            ybarm  /= Sum;
+            xybarm /= Sum;
+
+            ybarR  /= Sum;
+            xybarR /= Sum;
+        }
+
+        Double_t a1start = (xybarm - xbar*ybarm) / (xxbar - xbar*xbar);
+        Double_t a0start = ybarm - a1start*xbar;
+        a1start = a1start - 1.0;
+
+        Double_t b1start = (xybarR - xbar*ybarR) / (xxbar - xbar*xbar);
+        Double_t b0start = ybarR - b1start*xbar;
+
+        *fLog << "MUnfold::SmoothMigrationMatrix : " << endl;
+        *fLog << "============================" << endl;
+        *fLog << "a0start, a1start = " << a0start << ",  " << a1start << endl;
+        *fLog << "b0start, b1start = " << b0start << ",  " << b1start << endl;
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+
+        char name[20][100];
+        Double_t vinit[20];
+        Double_t  step[20];
+        Double_t limlo[20];
+        Double_t limup[20];
+        Int_t    fix[20];
+
+        sprintf(&name[0][0], "a0mean");
+        vinit[0] = a0start;
+        //vinit[0] = 1.0;
+        step[0]  = 0.1;
+        limlo[0] = 0.0;
+        limup[0] = 0.0;
+        fix[0]   = 0;
+
+        sprintf(&name[1][0], "a1mean");
+        vinit[1] = a1start;
+        //vinit[1] = 0.0;
+        step[1]  = 0.1;
+        limlo[1] = 0.0;
+        limup[1] = 0.0;
+        fix[1]   = 0;
+
+        sprintf(&name[2][0], "a2mean");
+        vinit[2] = 0.0;
+        step[2]  = 0.1;
+        limlo[2] = 0.0;
+        limup[2] = 0.0;
+        fix[2]   = 0;
+
+        sprintf(&name[3][0], "b0RMS");
+        vinit[3] = b0start;
+          //vinit[3] = 0.8;
+        step[3]  = 0.1;
+        limlo[3] = 1.e-20;
+        limup[3] = 10.0;
+        fix[3]   = 0;
+
+        sprintf(&name[4][0], "b1RMS");
+        vinit[4] = b1start;
+        //vinit[4] = 0.0;
+        step[4]  = 0.1;
+        limlo[4] = 0.0;
+        limup[4] = 0.0;
+        fix[4]   = 0;
+
+        sprintf(&name[5][0], "b2RMS");
+        vinit[5] = 0.0;
+        step[5]  = 0.1;
+        limlo[5] = 0.0;
+        limup[5] = 0.0;
+        fix[5]   = 0;
+
+
+        if ( CallMinuit(fcnSmooth, npar, name, vinit,
+                        step, limlo, limup, fix) )
+        {
+
+            // ------------------------
+            // fMigrat is the migration matrix to be used in the unfolding;
+            // fMigrat, as set by the constructor, is overwritten
+            //          by the smoothed migration matrix
+
+            for (UInt_t i=0; i<fNa; i++)
+                for (UInt_t j=0; j<fNb; j++)
+                    fMigrat(i, j) = fMigSmoo(i, j);
+
+            // ------------------------
+
+            for (UInt_t i=0; i<fNa; i++)
+                for (UInt_t j=0; j<fNb; j++)
+                    fMigraterr2(i, j) = fMigSmooerr2(i, j);
+
+
+            // normalize
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                Double_t sum = 0.0;
+                for (UInt_t i=0; i<fNa; i++)
+                    sum += fMigrat(i, j);
+
+                //*fLog << "SmoothMigrationMatrix : normalization fMigrat; j, sum + "
+                //     << j << ",  " << sum << endl;
+
+                if (sum == 0.0)
+                    continue;
+
+                for (UInt_t i=0; i<fNa; i++)
+                {
+                    fMigrat(i, j)     /= sum;
+                    fMigraterr2(i, j) /= (sum*sum);
+                }
+            }
+
+            *fLog << "MUnfold::SmoothMigrationMatrix :   fMigrat = "  << endl;
+            *fLog << "========================================"  << endl;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                for (UInt_t j=0; j<fNb; j++)
+                    *fLog << fMigrat(i, j) << " \t";
+                *fLog << endl;
+            }
+
+	    /*
+            *fLog << "MUnfold::SmoothMigrationMatrix :   fMigraterr2 = "  << endl;
+            *fLog << "============================================"  << endl;
+            for (UInt_t i=0; i<fNa; i++)
+            {
+                for (UInt_t j=0; j<fNb; j++)
+                    *fLog << fMigraterr2(i, j) << " \t";
+                *fLog << endl;
+            }
+	    */
+
+            // ------------------------
+
+            return kTRUE;
+        }
+
+        return kFALSE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Prepare the call to MINUIT for the minimization of the function
+    //         f = chi2*w/2 + reg, where reg is the regularization term
+    //         reg is the sum the squared 2nd derivatives
+    //                        of the unfolded distribution
+    //
+    // the corresponding fcn routine is 'fcnTikhonov2'
+    //
+    Bool_t MUnfold::Tikhonov2(TH1D &hb0)
+    {
+        // the number of free parameters (npar) is equal to
+        // the number of bins (fNb) of the unfolded distribution minus 1,
+        // because of the constraint that the total number of events
+        // is fixed
+        UInt_t npar = fNb-1;
+
+        if (npar > 20)
+        {
+            *fLog << "MUnfold::Tikhonov2 : too many parameters,  npar = "
+                << npar << ",  fNb = " << fNb << endl;
+            return kFALSE;
+        }
+
+        // copy ideal distribution
+        
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+        
+
+        //---   start w loop -----------------------------------
+
+        *fLog << "Tikhonov2 : start loop over weights" << endl;
+
+        Int_t ix;
+        Double_t xiter;
+
+        for (ix=0; ix<Nix; ix++)
+        {
+            fW = pow(10.0,log10(xmin)+ix*dlogx);
+
+            //..............................................
+            // Set starting values and step sizes for parameters
+
+            char name[20][100];
+            Double_t vinit[20];
+            Double_t  step[20];
+            Double_t limlo[20];
+            Double_t limup[20];
+            Int_t    fix[20];
+
+            for (UInt_t i=0; i<npar; i++)
+            {
+                sprintf(&name[i][0], "p%d", i+1);
+                vinit[i] = fVEps0(i);
+                step[i]  = fVEps0(i)/10;
+
+                // lower and upper limits  (limlo=limup=0: no limits)
+                //limlo[i] = 1.e-20;
+                limlo[i] = -1.0;
+                limup[i] = 1.0;
+                fix[i]   = 0;
+            }
+
+            // calculate solution for the weight fW
+            // flag non-convergence by chisq(ix) = 0.0
+            chisq(ix) = 0.0;
+            if ( CallMinuit(fcnTikhonov2, npar, name, vinit,
+                            step, limlo, limup, fix) )
+            {
+                // calculate difference between ideal and unfolded distribution
+                Double_t D2bar = 0.0;
+                for (UInt_t i = 0; i<fNb; i++)
+                {
+                    Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                    D2bar += temp*temp;
+                }
+
+                SpAR(ix)   = SpurAR;
+                SpSig(ix)  = SpurSigma;
+                chisq(ix)  = Chisq;
+                SecDer(ix) = SecDeriv;
+                ZerDer(ix) = ZerDeriv;
+                Entrop(ix) = Entropy;
+                DAR2(ix)   = DiffAR2;
+                Dsqbar(ix) = D2bar;
+            }
+        }
+        *fLog << "Tikhonov2 : end of loop over weights" << endl;
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            // test whether minimization has converged
+            if (chisq(ix) != 0.0)
+            {
+                xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+                Int_t bin;
+                bin = hBchisq->FindBin( log10(xiter) );
+                hBchisq->SetBinContent(bin,chisq(ix));
+
+                //hBSpAR->SetBinContent(bin,SpAR(ix));
+                hBSpAR->SetBinContent(bin,0.0);
+
+                hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+                hBSecDeriv->SetBinContent(bin,SecDer(ix));
+                hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+                hBEntropy->SetBinContent(bin,Entrop(ix));
+
+                //hBDAR2->SetBinContent(bin,DAR2(ix));
+                hBDAR2->SetBinContent(bin,0.0);
+
+                hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+                if (ix > 0)
+                {
+                    //Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                    //hBDSpAR->SetBinContent(bin,DSpAR);
+
+                    Double_t diff = SpSig(ix) - SpSig(ix-1);
+                    Double_t DSpSig = diff;
+                    hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                    Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                    hBDEntropy->SetBinContent(bin,DEntrop);
+
+                    Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                    hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                    Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                    hBDZerDeriv->SetBinContent(bin,DZerDer);
+                }
+            }
+        }
+
+
+        //---   end w loop -----------------------------------
+
+        // Select best weight
+        SelectBestWeight();
+
+        *fLog << " Tikhonov2 : after SelectBestWeight" << endl;
+
+        if (ixbest < 0.0)
+        {
+            *fLog << "Tikhonov2 : no result found; " << endl;
+            return kFALSE;
+        }
+
+        *fLog << "Tikhonov2 : best result found; " << endl;
+        *fLog << "===============================" << endl;
+        *fLog << "           ixbest = " << ixbest << endl;
+
+
+        // do a final unfolding using the best weight
+
+        fW = pow(10.0,log10(xmin)+ixbest*dlogx);
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+
+        char name[20][100];
+        Double_t vinit[20];
+        Double_t  step[20];
+        Double_t limlo[20];
+        Double_t limup[20];
+        Int_t    fix[20];
+
+        for (UInt_t i=0; i<npar; i++)
+        {
+            sprintf(&name[i][0], "p%d", i+1);
+            vinit[i] = fVEps0(i);
+            step[i]  = fVEps0(i)/10;
+
+            // lower and upper limits  (limlo=limup=0: no limits)
+            //limlo[i] = 1.e-20;
+            limlo[i] = -1.0;
+            limup[i] = 1.0;
+            fix[i]   = 0;
+        }
+
+        // calculate solution for the best weight
+        CallMinuit(fcnTikhonov2, npar, name, vinit,
+                   step, limlo, limup, fix);
+
+
+        *fLog << "Tikhonov : Values for best weight " << endl;
+        *fLog << "==================================" << endl;
+        *fLog << "fW, ixbest, Chisq, SpurAR, SpurSigma, SecDeriv, ZerDeriv, Entrop, DiffAR2, D2bar = " << endl;
+        *fLog << "      " << fW << ",  " << ixbest << ",  "
+            << Chisq << ",  " << SpurAR << ",  "
+            << SpurSigma << ",  " << SecDeriv << ",  " << ZerDeriv << ",  "
+            << Entropy << ",  " << DiffAR2 << ",  "
+            << Dsqbar(ixbest) << endl;
+
+        return kTRUE;
+
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Bertero :
+    //
+    // the unfolded distribution is calculated iteratively;
+    // the number of iterations after which the iteration is stopped
+    //            corresponds to the 'weight' in other methods
+    // a small number of iterations corresponds to strong regularization
+    // a high number to no regularization
+    //
+    // see : M.Bertero, INFN/TC-88/2 (1988)
+    //       V.B.Anykeyev et al., NIM A303 (1991) 350
+    //
+    Bool_t MUnfold::Bertero(TH1D &hb0)
+    {
+        // copy ideal distribution
+        
+        for (UInt_t i=1; i<=fNb; i++)
+        {
+            fhb0->SetBinContent(i, hb0.GetBinContent(i));
+            fhb0->SetBinError  (i, hb0.GetBinError(i));
+        }
+        
+
+        TMatrixD bold(fNb, 1);
+        bold.Zero();
+
+        //----------------------------------------------------------
+
+        Double_t db2 = 1.e20;
+
+
+        TMatrixD aminusaest(fNa, 1);
+
+        //-------   scan number of iterations   -----------------
+
+        *fLog << "Bertero : start loop over number of iterations" << endl;
+
+        Int_t ix;
+
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+            // calculate solution for the iteration number xiter
+            BertCore(xiter);
+
+            // calculate difference between ideal and unfolded distribution
+            Double_t D2bar = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-hb0.GetBinContent(i+1,0);
+                D2bar += temp*temp;
+            }
+
+            SpAR(ix)   = SpurAR;
+            SpSig(ix)  = SpurSigma;
+            chisq(ix)  = Chisq;
+            SecDer(ix) = SecDeriv;
+            ZerDer(ix) = ZerDeriv;
+            Entrop(ix) = Entropy;
+            DAR2(ix)   = DiffAR2;
+            Dsqbar(ix) = D2bar;
+
+            db2 = 0.0;
+            for (UInt_t i = 0; i<fNb; i++)
+            {
+                Double_t temp = fVb(i,0)-bold(i,0);
+                db2 += temp*temp;
+            }
+            bold = fVb;
+
+            //if (db2 < Epsdb2) break;
+
+        }
+
+        *fLog << "Bertero : end of loop over number of iterations" << endl;
+
+        // plots ------------------------------
+        for (ix=0; ix<Nix; ix++)
+        {
+            Double_t xiter = pow(10.0,log10(xmin)+ix*dlogx);
+
+            Int_t bin;
+            bin = hBchisq->FindBin( log10(xiter) );
+            hBchisq->SetBinContent(bin,chisq(ix));
+            hBSpAR->SetBinContent(bin,SpAR(ix));
+            hBSpSig->SetBinContent(bin,SpSig(ix)/fSpurVacov);
+            hBSecDeriv->SetBinContent(bin,SecDer(ix));
+            hBZerDeriv->SetBinContent(bin,ZerDer(ix));
+            hBEntropy->SetBinContent(bin,Entrop(ix));
+            hBDAR2->SetBinContent(bin,DAR2(ix));
+            hBD2bar->SetBinContent(bin,Dsqbar(ix));
+
+            if (ix > 0)
+            {
+                Double_t DSpAR = SpAR(ix) - SpAR(ix-1);
+                hBDSpAR->SetBinContent(bin,DSpAR);
+
+                Double_t diff = SpSig(ix) - SpSig(ix-1);
+                Double_t DSpSig = diff;
+                hBDSpSig->SetBinContent(bin, DSpSig/fSpurVacov);
+
+                Double_t DEntrop = Entrop(ix) - Entrop(ix-1);
+                hBDEntropy->SetBinContent(bin,DEntrop);
+
+                Double_t DSecDer = SecDer(ix) - SecDer(ix-1);
+                hBDSecDeriv->SetBinContent(bin,DSecDer);
+
+                Double_t DZerDer = ZerDer(ix) - ZerDer(ix-1);
+                hBDZerDeriv->SetBinContent(bin,DZerDer);
+            }
+        }
+        //-------   end of scan of number of iterations   -----------------
+
+        // Select best weight
+        SelectBestWeight();
+
+
+        if (ixbest < 0.0)
+        {
+            *fLog << "Bertero : weight iteration has NOT converged; " << endl;
+            return kFALSE;
+        }
+
+        *fLog << "Bertero : weight iteration has converged; " << endl;
+        *fLog << "            ixbest = " << ixbest << endl;
+
+
+        // do a final unfolding using the best weight
+
+        // calculate solution for the iteration number xiter
+        Double_t xiter = pow(10.0,log10(xmin)+ixbest*dlogx);
+        BertCore(xiter);
+
+        *fLog << "Bertero : Values for best weight " << endl;
+        *fLog << "=================================" << endl;
+        *fLog << "fW, ixbest, Chisq, SpurAR, SpurSigma, SecDeriv, ZerDeriv, Entrop, DiffAR2, D2bar = " << endl;
+        *fLog << "      " << fW << ",  " << ixbest << ",  "
+            << Chisq << ",  " << SpurAR << ",  "
+            << SpurSigma << ",  " << SecDeriv << ",  " << ZerDeriv << ",  "
+            << Entropy << ",  " << DiffAR2 << ",  "
+            << Dsqbar(ixbest) << endl;
+
+        //----------------
+
+        fNdf   = SpurAR;
+        fChisq = Chisq;
+
+        for (UInt_t i=0; i<fNa; i++)
+	{
+          fChi2(i,0) = Chi2(i,0);
+	}
+
+        UInt_t iNdf   = (UInt_t) (fNdf+0.5);
+        fProb = iNdf>0 ? TMath::Prob(fChisq, iNdf) : 0;
+
+
+        fResult.ResizeTo(fNb, 5);
+        for (UInt_t i=0; i<fNb; i++)
+        {
+            fResult(i, 0) = fVb(i,0);
+            fResult(i, 1) = sqrt(fVbcov(i,i));
+            fResult(i, 2) = 0.0;
+            fResult(i, 3) = 0.0;
+            fResult(i, 4) = 1.0;
+        }
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // main part of Bertero's calculations
+    //
+    Bool_t MUnfold::BertCore(Double_t &xiter)
+    {
+        // ignore eigen values which are smaller than EpsLambda
+        TMatrixD G_inv(fNa, fNa);
+        TMatrixD Gtil_inv(fNa, fNa);
+        TMatrixD atil(fNb, fNa);
+        TMatrixD aminusaest(fNa, 1);
+
+        G_inv.Zero();
+        Gtil_inv.Zero();
+        SpurAR = 0.0;
+
+        // -----   loop over eigen values   ------------------
+        // calculate the approximate inverse of the matrix G
+        //*fLog << "flaml = " << endl;
+
+        UInt_t flagstart = 2;
+        Double_t flaml=0;
+
+        for (UInt_t l=0; l<fNa; l++)
+        {
+            if (EigenValue(l) < EpsLambda)
+                continue;
+
+            switch (flagstart)
+            {
+            case 1 :
+                // This is the expression for f(lambda) if the initial C^(0)
+                // is chosen to be zero
+                flaml = 1.0 - pow(1.0-tau*EigenValue(l),xiter);
+                break;
+
+            case 2 :
+                // This is the expression for f(lambda) if the initial C^(0)
+                // is chosen to be equal to the measured distribution
+                flaml =           1.0 - pow(1.0-tau*EigenValue(l),xiter)
+                    + EigenValue(l) * pow(1.0-tau*EigenValue(l),xiter);
+                break;
+            }
+
+            //  *fLog << flaml << ",  ";
+
+            for (UInt_t m=0; m<fNa; m++)
+            {
+                for (UInt_t n=0; n<fNa; n++)
+                {
+                    G_inv(m,n)    += 1.0  /EigenValue(l) * Eigen(m,l)*Eigen(n,l);
+                    Gtil_inv(m,n) += flaml/EigenValue(l) * Eigen(m,l)*Eigen(n,l);
+                }
+            }
+            SpurAR += flaml;
+        }
+        //*fLog << endl;
+
+
+        //*fLog << "Gtil_inv =" << endl;
+        //for (Int_t m=0; m<fNa; m++)
+        //{
+        //  for (Int_t n=0; n<fNa; n++)
+        //  {
+        //    *fLog << Gtil_inv(m,n) << ",  ";
+        //  }
+        //  *fLog << endl;
+        //}
+
+        //-----------------------------------------------------
+        // calculate the unfolded distribution b
+        TMatrixD v2(fMigrat, TMatrixD::kTransposeMult, Gtil_inv);
+        atil = v2;
+        TMatrixD v4(atil, TMatrixD::kMult, fVa);
+        fVb = v4;
+
+        //-----------------------------------------------------
+        // calculate AR and AR+
+        TMatrixD AR(v2, TMatrixD::kMult, fMigrat);
+
+        TMatrixD v3(fMigrat, TMatrixD::kTransposeMult, G_inv);
+        TMatrixD ARplus(v3, TMatrixD::kMult, fMigrat);
+
+
+        //-----------------------------------------------------
+        // calculate the norm |AR - AR+|**2
+
+        DiffAR2 = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+        {
+            for (UInt_t k=0; k<fNb; k++)
+            {
+                Double_t tempo = AR(j,k) - ARplus(j,k);
+                DiffAR2       += tempo*tempo;
+            }
+        }
+
+        //-----------------------------------------------------
+        // calculate the second derivative squared
+
+        SecDeriv = 0;
+        for (UInt_t j=1; j<(fNb-1); j++)
+        {
+            // temp = ( 2.0*fVb(j,0)-fVb(j-1,0)-fVb(j+1,0) ) / ( 2.0*fVb(j,0) );
+            Double_t temp =    2.0*(fVb(j+1,0)-fVb(j,0)) / (fVb(j+1,0)+fVb(j,0))
+                - 2.0*(fVb(j,0)-fVb(j-1,0)) / (fVb(j,0)+fVb(j-1,0));
+            SecDeriv += temp*temp;
+        }
+
+        ZerDeriv = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            ZerDeriv += fVb(j,0) * fVb(j,0);
+
+        //-----------------------------------------------------
+        // calculate the entropy
+
+        Double_t sumb = 0.0;
+        for (UInt_t j=0; j<fNb; j++)
+            sumb += fVb(j,0);
+
+        TMatrixD p(fNb,1);
+        p = fVb;
+        if (sumb > 0.0)
+            p *= 1.0/sumb;
+
+        Entropy = 0;
+        for (UInt_t j=0; j<fNb; j++)
+            if (p(j,0) > 0.0)
+                Entropy += p(j,0) * log( p(j,0) );
+
+        //-----------------------------------------------------
+
+        TMatrixD Gb(fMigrat, TMatrixD::kMult, fVb);
+        aminusaest = fVa;
+        aminusaest -= Gb;
+    
+        TMatrixD v1(1,fNa);
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            v1(0,i) = 0.0;
+            for (UInt_t j=0; j<fNa; j++)
+                v1(0,i) += aminusaest(j,0) * fVacovInv(j,i) ;
+        }
+
+        //-----------------------------------------------------
+        // calculate error matrix fVbcov of unfolded distribution
+        SpurSigma = CalcSpurSigma(atil);
+
+        //-----------------------------------------------------
+        // calculate the chi squared
+        for (UInt_t i = 0; i<fNa; i++)
+            Chi2(i,0) = v1(0,i) * aminusaest(i,0);
+
+        Chisq = GetMatrixSumCol(Chi2,0);
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Calculate the matrix G = M * M(transposed)
+    //           and its eigen values and eigen vectors
+    //
+    Bool_t MUnfold::CalculateG()
+    {
+        // Calculate matrix G = M*M(transposed)     (M = migration matrix)
+        //           the matrix Eigen of the eigen vectors of G
+        //           the vector EigenValues of the eigen values of G
+        //           the parameter tau = 1/lambda_max
+        //
+        TMatrixD v5(TMatrixD::kTransposed, fMigrat);
+        //TMatrixD G(fMigrat, TMatrixD::kMult, v5);
+        G.Mult(fMigrat, v5);
+
+        Eigen = G.EigenVectors(EigenValue);
+
+        RankG = 0.0;
+        for (UInt_t l=0; l<fNa; l++)
+        {
+            if (EigenValue(l) < EpsLambda) continue;
+            RankG += 1.0;
+        }
+
+        tau = 1.0 / EigenValue(0);
+
+        //  *fLog << "eigen values : " << endl;
+        //  for (Int_t i=0; i<fNa; i++)
+        //  {
+        //    *fLog << EigenValue(i) << ",  ";
+        //  }
+        //  *fLog << endl;
+
+        //*fLog << "eigen vectors : " << endl;
+        //for (Int_t i=0; i<fNa; i++)
+        //{
+        //  *fLog << "               vector " << i << endl;
+        //  for (Int_t j=0; j<fNa; j++)
+        //  {
+        //    *fLog << Eigen(j,i) << ",  ";
+        //  }
+        //  *fLog << endl;
+        //}
+        //*fLog << endl;
+
+        //*fLog << "G =" << endl;
+        //for (Int_t m=0; m<fNa; m++)
+        //{
+        //  for (Int_t n=0; n<fNa; n++)
+        //  {
+        //    *fLog << G(m,n) << ",  ";
+        //  }
+        //  *fLog << endl;
+        //}
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Select the best weight
+    //
+    Bool_t MUnfold::SelectBestWeight()
+    {
+        //-------------------------------
+        // select 'best' weight according to some criterion
+
+        Int_t ix;
+
+        Double_t DiffSpSigmax = -1.e10;
+        Int_t    ixDiffSpSigmax = -1;
+
+        Double_t DiffSigpointsmin = 1.e10;
+        Int_t    ixDiffSigpointsmin = -1;
+
+        Double_t DiffRankGmin = 1.e10;
+        Int_t    ixDiffRankGmin = -1;
+
+        Double_t D2barmin = 1.e10;
+        Int_t    ixD2barmin = -1;
+
+        Double_t DiffSpSig1min = 1.e10;
+        Int_t    ixDiffSpSig1min = -1;
+
+
+        Int_t ixmax = -1;
+
+        // first loop over all weights :
+        //       find smallest chi2
+        Double_t chisqmin = 1.e20;
+        for (ix=0; ix<Nix; ix++)
+        {
+            // consider only weights for which
+            //  - unfolding was successful
+            if (chisq(ix) != 0.0)
+            {
+                if (chisq(ix) < chisqmin)
+                    chisqmin = chisq(ix);
+            }
+        }
+        Double_t chisq0 = chisqmin > fVapoints ? chisqmin : fVapoints/2.0;
+
+        // second loop over all weights :
+        //        consider only weights for which chisq(ix) < chisq0
+        ixbest = -1;
+        for (ix=0; ix<Nix; ix++)
+        {
+            if (chisq(ix) != 0.0 && chisq(ix) < 2.0*chisq0)
+            {
+                // ixmax = highest weight with successful unfolding
+                //         (Least squares solution)
+                ixmax = ix;
+
+                SpurSigma = SpSig(ix);
+                SpurAR    = SpAR(ix);
+                Chisq    = chisq(ix);
+                D2bar     = Dsqbar(ix);
+
+                //----------------------------------
+                // search weight where SpurSigma changes most
+                //                               (as a function of the weight)
+                if (ix > 0  &&  chisq(ix-1) != 0.0)
+                {
+                    Double_t diff = SpSig(ix) - SpSig(ix-1);
+                    if (diff > DiffSpSigmax)
+                    {
+                        DiffSpSigmax   = diff;
+                        ixDiffSpSigmax = ix;
+                    }
+                }
+
+                //----------------------------------
+                // search weight where Chisq is close
+                //        to the number of significant measurements
+                Double_t DiffSigpoints = fabs(Chisq-fVapoints);
+
+                if (DiffSigpoints < DiffSigpointsmin)
+                {
+                    DiffSigpointsmin   = DiffSigpoints;
+                    ixDiffSigpointsmin = ix;
+                }
+
+                //----------------------------------
+                // search weight where Chisq is close
+                //        to the rank of matrix G
+                Double_t DiffRankG = fabs(Chisq-RankG);
+
+                if (DiffRankG < DiffRankGmin)
+                {
+                    DiffRankGmin   = DiffRankG;
+                    ixDiffRankGmin = ix;
+                }
+
+                //----------------------------------
+                // search weight where SpurSigma is close to 1.0
+                Double_t DiffSpSig1 = fabs(SpurSigma/fSpurVacov-1.0);
+
+                if (DiffSpSig1 < DiffSpSig1min)
+                {
+                    DiffSpSig1min   = DiffSpSig1;
+                    ixDiffSpSig1min = ix;
+                }
+
+                //----------------------------------
+                // search weight where D2bar is minimal
+
+                if (D2bar < D2barmin)
+                {
+                    D2barmin   = D2bar;
+                    ixD2barmin = ix;
+                }
+
+                //----------------------------------
+            }
+        }
+
+
+        // choose solution where increase of SpurSigma is biggest
+        //if ( DiffSpSigmax > 0.0)
+        //  ixbest = ixDiffSpSigmax;
+        //else
+        //  ixbest = ixDiffSigpointsmin;
+
+        // choose Least Squares Solution
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+        // ixbest = ixmax;
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+        // choose weight where chi2 is close to the number of significant
+        // measurements
+        // ixbest = ixDiffSigpointsmin;
+
+        // choose weight where chi2 is close to the rank of matrix G
+        // ixbest = ixDiffRankGmin;
+
+        // choose weight where chi2 is close to the rank of matrix G
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+           ixbest = ixDiffSpSig1min;
+	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
+
+        *fLog << "SelectBestWeight : ixDiffSpSigmax, DiffSpSigmax = "
+            << ixDiffSpSigmax << ",  " << DiffSpSigmax << endl;
+        *fLog << "================== ixDiffSigpointsmin, DiffSigpointsmin = "
+            << ixDiffSigpointsmin << ",  " << DiffSigpointsmin << endl;
+
+        *fLog << "                   ixDiffRankGmin, DiffRankGmin = "
+            << ixDiffRankGmin << ",  " << DiffRankGmin << endl;
+
+        *fLog << "                   ixDiffSpSig1min, DiffSpSig1min = "
+            << ixDiffSpSig1min << ",  " << DiffSpSig1min << endl;
+
+        *fLog << "                   ixD2barmin, D2barmin = "
+            << ixD2barmin << ",  " << D2barmin << endl;
+        *fLog << "                   ixmax  = " << ixmax  << endl;
+        *fLog << "                   ixbest = " << ixbest << endl;
+
+
+        return kTRUE;
+    }
+
+    // -----------------------------------------------------------------------
+    //
+    // Draw the plots
+    //
+    Bool_t MUnfold::DrawPlots()
+    {
+
+        // in the plots, mark the weight which has been selected
+        Double_t xbin = log10(xmin)+ixbest*dlogx;
+
+        TMarker *m = new TMarker();
+        m->SetMarkerSize(1);
+        m->SetMarkerStyle(20);
+
+        //-------------------------------------
+        // draw the iteration plots
+        TString ctitle = bintitle;
+        ctitle += "Plots versus weight";
+        TCanvas *c = new TCanvas("iter", ctitle, 900, 600);
+        c->Divide(3,2);
+
+        c->cd(1);
+        hBchisq->Draw();
+        gPad->SetLogy();
+        hBchisq->SetXTitle("log10(iteration number)");
+        hBchisq->SetYTitle("chisq");
+        m->DrawMarker(xbin, log10(chisq(ixbest)));
+
+        c->cd(2);
+        hBD2bar->Draw();
+        gPad->SetLogy();
+        hBD2bar->SetXTitle("log10(iteration number)");
+        hBD2bar->SetYTitle("(b_unfolded-b_ideal)**2");
+        m->DrawMarker(xbin, log10(Dsqbar(ixbest)));
+
+        /*
+         c->cd(3);
+         hBDAR2->Draw();
+         gPad->SetLogy();
+         strgx = "log10(iteration number)";
+         strgy = "norm(AR-AR+)";
+         hBDAR2->SetXTitle(strgx);
+         hBDAR2->SetYTitle(strgy);
+         m->DrawMarker(xbin, log10(DAR2(ixbest)));
+         */
+
+        c->cd(3);
+        hBSecDeriv->Draw();
+        hBSecDeriv->SetXTitle("log10(iteration number)");
+        hBSecDeriv->SetYTitle("Second Derivative squared");
+        m->DrawMarker(xbin, SecDer(ixbest));
+
+        /*
+         c->cd(8);
+         hBDSecDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Second Derivative squared)";
+         hBDSecDeriv->SetXTitle(strgx);
+         hBDSecDeriv->SetYTitle(strgy);
+         */
+
+        /*
+         c->cd(4);
+         hBZerDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Zero Derivative squared";
+         hBZerDeriv->SetXTitle(strgx);
+         hBZerDeriv->SetYTitle(strgy);
+         m->DrawMarker(xbin, ZerDer(ixbest));
+         */
+
+        /*
+         c->cd(5);
+         hBDZerDeriv->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Zero Derivative squared)";
+         hBDZerDeriv->SetXTitle(strgx);
+         hBDZerDeriv->SetYTitle(strgy);
+         */
+
+        c->cd(4);
+        hBSpAR->Draw();
+        hBSpAR->SetXTitle("log10(iteration number)");
+        hBSpAR->SetYTitle("SpurAR");
+        m->DrawMarker(xbin, SpAR(ixbest));
+
+
+        /*
+         c->cd(11);
+         hBDSpAR->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(SpurAR)";
+         hBDSpAR->SetXTitle(strgx);
+         hBDSpAR->SetYTitle(strgy);
+         */
+
+        c->cd(5);
+        hBSpSig->Draw();
+        hBSpSig->SetXTitle("log10(iteration number)");
+        hBSpSig->SetYTitle("SpurSig/SpurC");
+        m->DrawMarker(xbin, SpSig(ixbest)/fSpurVacov);
+
+        /*
+         c->cd(14);
+         hBDSpSig->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(SpurSig/SpurC)";
+         hBDSpSig->SetXTitle(strgx);
+         hBDSpSig->SetYTitle(strgy);
+         */
+
+        c->cd(6);
+        hBEntropy->Draw();
+        hBEntropy->SetXTitle("log10(iteration number)");
+        hBEntropy->SetYTitle("Entropy");
+        m->DrawMarker(xbin, Entrop(ixbest));
+
+        /*
+         c->cd(17);
+         hBDEntropy->Draw();
+         strgx = "log10(iteration number)";
+         strgy = "Delta(Entropy)";
+         hBDEntropy->SetXTitle(strgx);
+         hBDEntropy->SetYTitle(strgy);
+         */
+
+        //-------------------------------------
+
+        for (UInt_t i=0; i<fNa; i++)
+        {
+            fha->SetBinContent(i+1, fVa(i, 0)         );
+            fha->SetBinError  (i+1, sqrt(fVacov(i, i)));
+
+            for (UInt_t j=0; j<fNb; j++)
+            {
+                fhmig->SetBinContent(i+1, j+1, fMigOrig(i, j)           );
+                fhmig->SetBinError  (i+1, j+1, sqrt(fMigOrigerr2(i, j)) );
+
+                shmig->SetBinContent(i+1, j+1, fMigrat(i, j)           );
+                shmig->SetBinError  (i+1, j+1, sqrt(fMigraterr2(i, j)) );
+                shmigChi2->SetBinContent(i+1, j+1, fMigChi2(i, j)   );
+            }
+        }
+
+        //PrintTH2Content(*shmig);
+        //PrintTH2Content(*shmigChi2);
+
+        //-------------------------------------
+        CopyCol(*hprior, fVEps);
+        CopyCol(*hb,     fVb);
+        for (UInt_t i=0; i<fNb; i++)
+            hb->SetBinError(i+1, sqrt(fVbcov(i, i)));
+
+        PrintTH1Content(*hb);
+        PrintTH1Error(*hb);
+
+        //..............................................
+        for (UInt_t i=0; i<fNa; i++)
+            hEigen->SetBinContent(i+1, EigenValue(i));
+
+        //..............................................
+        // draw the plots
+        TString cctitle = bintitle;
+        cctitle +=  "Unfolding input";
+        TCanvas *cc = new TCanvas("input", cctitle, 900, 600);
+        cc->Divide(3, 2);
+
+        // distribution to be unfolded
+        cc->cd(1);
+        fha->Draw();
+        gPad->SetLogy();
+        fha->SetXTitle("log10(E_{est}/GeV)");
+        fha->SetYTitle("Counts");
+
+        // superimpose unfolded distribution
+        hb->Draw("*HSAME");
+	hb->SetMarkerColor(75);
+	hb->SetLineColor(75);
+
+        // prior distribution
+        cc->cd(2);
+        hprior->Draw();
+        gPad->SetLogy();
+        hprior->SetXTitle("log10(E_{true}/GeV)");
+        hprior->SetYTitle("Counts");
+
+        // migration matrix
+        cc->cd(3);
+        fhmig->Draw("box");
+        fhmig->SetXTitle("log10(E_{est}/GeV)");
+        fhmig->SetYTitle("log10(E_{true}/GeV)");
+
+        // smoothed migration matrix
+        cc->cd(4);
+        shmig->Draw("box");
+        shmig->SetXTitle("log10(E_{est}/GeV)");
+        shmig->SetYTitle("log10(E_{true}/GeV)");
+
+        // chi2 contributions for smoothing
+        cc->cd(5);
+        shmigChi2->Draw("box");
+        shmigChi2->SetXTitle("log10(E_{est}/GeV)");
+        shmigChi2->SetYTitle("log10(E_{true}/GeV)");
+
+        // Eigenvalues of matrix M*M(transposed)
+        cc->cd(6);
+        hEigen->Draw();
+        hEigen->SetXTitle("l");
+        hEigen->SetYTitle("Eigen values Lambda_l of M*M(transposed)");
+
+
+       //..............................................
+        // draw the results
+        TString crtitle = bintitle;
+        crtitle +=  "Unfolding results";
+        TCanvas *cr = new TCanvas("results", crtitle, 600, 600);
+        cr->Divide(2, 2);
+
+        // unfolded distribution
+        cr->cd(1);
+        hb->Draw();
+        gPad->SetLogy();
+        hb->SetXTitle("log10(E-true/GeV)");
+        hb->SetYTitle("Counts");
+
+	
+        // covariance matrix of unfolded distribution
+        cr->cd(2);
+        TH1 *hbcov=DrawMatrixClone(fVbcov, "lego");
+        hbcov->SetBins(fNb, hb->GetBinLowEdge(1), hb->GetBinLowEdge(fNb+1),
+                       fNb, hb->GetBinLowEdge(1), hb->GetBinLowEdge(fNb+1));
+
+        hbcov->SetName("hbcov");
+        hbcov->SetTitle("Error matrix of distribution hb");
+        hbcov->SetXTitle("log10(E_{true}/GeV)");
+        hbcov->SetYTitle("log10(E_{true}/GeV)");
+       
+	
+        // chi2 contributions
+        cr->cd(3);
+        TH1 *hchi2=DrawMatrixColClone(fChi2);
+        hchi2->SetBins(fNa, fha->GetBinLowEdge(1), fha->GetBinLowEdge(fNa+1));
+
+        hchi2->SetName("Chi2");
+        hchi2->SetTitle("chi2 contributions");
+        hchi2->SetXTitle("log10(E_{est}/GeV)");
+        hchi2->SetYTitle("Chisquared");
+	
+	
+        // ideal distribution
+        
+        cr->cd(4);
+        fhb0->Draw();
+        gPad->SetLogy();
+        fhb0->SetXTitle("log10(E_{true}/GeV)");
+        fhb0->SetYTitle("Counts");
+        
+
+        // superimpose unfolded distribution
+        hb->Draw("*Hsame");
+	
+
+        return kTRUE;
+    }
+
+
+    // -----------------------------------------------------------------------
+    //
+    // Interface to MINUIT
+    //
+    //
+    Bool_t MUnfold::CallMinuit(
+                      void (*fcnx)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t),
+                      UInt_t npar, char name[20][100],
+                      Double_t vinit[20], Double_t step[20],
+                      Double_t limlo[20], Double_t limup[20], Int_t fix[20])
+    {
+        //
+        // Be carefull: This is not thread safe
+        //
+        UInt_t maxpar = 100;
+
+        if (npar > maxpar)
+        {
+            *fLog << "MUnfold::CallMinuit : too many parameters,  npar = " << fNb
+                << ",   maxpar = " << maxpar << endl;
+            return kFALSE;
+        }
+
+        //..............................................
+        // Set the maximum number of parameters
+        TMinuit minuit(maxpar);
+
+
+        //..............................................
+        // Set the print level
+        // -1   no output except SHOW comands
+        //  0   minimum output
+        //  1   normal output (default)
+        //  2   additional ouput giving intermediate results
+        //  3   maximum output, showing progress of minimizations
+        //
+        Int_t printLevel = -1;
+        minuit.SetPrintLevel(printLevel);
+
+        //..............................................       
+        // Printout for warnings
+        //    SET WAR      print warnings
+        //    SET NOW      suppress warnings
+        Int_t errWarn;
+        Double_t tmpwar = 0;
+        minuit.mnexcm("SET NOW", &tmpwar, 0, errWarn);
+
+        //..............................................
+        // Set the address of the minimization function
+        minuit.SetFCN(fcnx);
+
+        //..............................................
+        // Set starting values and step sizes for parameters
+        for (UInt_t i=0; i<npar; i++)
+        {
+            if (minuit.DefineParameter(i, &name[i][0], vinit[i], step[i],
+                                       limlo[i], limup[i]))
+            {
+                *fLog << "MUnfold::CallMinuit: Error in defining parameter "
+                    << name << endl;
+                return kFALSE;
+            }
+        }
+
+        //..............................................
+        //Int_t NumPars = minuit.GetNumPars();
+        //*fLog << "MUnfold::CallMinuit :  number of free parameters = "
+        //     << NumPars << endl;
+
+        //..............................................
+        // Minimization
+        minuit.SetObjectFit(this);
+
+        //..............................................
+        // Error definition :
+        //
+        //    for2 chisquare function :
+        //      up = 1.0   means calculate 1-standard deviation error
+        //         = 4.0   means calculate 2-standard deviation error
+        //
+        //    for log(likelihood) function :
+        //      up = 0.5   means calculate 1-standard deviation error
+        //         = 2.0   means calculate 2-standard deviation error
+        Double_t up = 1.0;
+        minuit.SetErrorDef(up);
+
+
+
+        // Int_t errMigrad;
+        // Double_t tmp = 0;
+        // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+
+        //..............................................
+        // fix a parameter
+        for (UInt_t i=0; i<npar; i++)
+        {
+            if (fix[i] > 0)
+            {
+                Int_t parNo = i;
+                minuit.FixParameter(parNo);
+            }
+        }
+
+        //..............................................
+        // Set maximum number of iterations (default = 500)
+        Int_t maxiter = 100000;
+        minuit.SetMaxIterations(maxiter);
+
+        //..............................................
+        // minimization by the method of Migrad
+        // Int_t errMigrad;
+        // Double_t tmp = 0;
+        // minuit.mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+        //..............................................       
+        // same minimization as by Migrad
+        // but switches to the SIMPLEX method if MIGRAD fails to converge
+        Int_t errMinimize;
+        Double_t tmp = 0;
+        minuit.mnexcm("MINIMIZE", &tmp, 0, errMinimize);
+
+        //..............................................       
+        // check quality of minimization
+        // istat = 0   covariance matrix not calculated
+        //         1   diagonal approximation only (not accurate)
+        //         2   full matrix, but forced positive-definite
+        //         3   full accurate covariance matrix 
+        //             (indication of normal convergence)
+        Double_t fmin, fedm, errdef;
+        Int_t    npari, nparx, istat;
+        minuit.mnstat(fmin, fedm, errdef, npari, nparx, istat);
+
+        if (errMinimize || istat < 3)
+        {
+            *fLog << "MUnfold::CallMinuit : Minimization failed" << endl;
+            *fLog << "       fmin = " << fmin   << ",   fedm = "  << fedm
+                << ",   errdef = "  << errdef << ",   istat = " << istat
+                << endl;
+            return kFALSE;
+        }
+
+        //..............................................
+        // Minos error analysis
+        // minuit.mnmnos();
+
+        //..............................................       
+        // Print current status of minimization
+        // if nkode = 0    only function value
+        //            1    parameter values, errors, limits
+        //            2    values, errors, step sizes, internal values
+        //            3    values, errors, step sizes, 1st derivatives
+        //            4    values, paraboloc errors, MINOS errors
+  
+        //Int_t nkode = 4;
+        //minuit.mnprin(nkode, fmin);
+
+        //..............................................       
+        // call fcn with IFLAG = 3 (final calculation : calculate p(chi2))
+        // iflag = 1   initial calculations only
+        //         2   calculate 1st derivatives and function
+        //         3   calculate function only
+        //         4   calculate function + final calculations
+        const char *command = "CALL";
+        Double_t iflag = 3;
+        Int_t errfcn3;
+        minuit.mnexcm(command, &iflag, 1, errfcn3); 
+
+        return kTRUE;
+    }
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/MUnfold.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MUnfold.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MUnfold.h	(revision 9772)
@@ -0,0 +1,199 @@
+#ifndef MARS_MUnfold
+#define MARS_MUnfold
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef ROOT_TMatrixD
+#include <TMatrixD.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TH2;
+class TH3;
+class TString;
+class TVectorD;
+class TH2D;
+class TH3D;
+
+class MUnfold : public MTask
+{
+
+private:
+
+  TH1 *DrawMatrixClone(const TMatrixD &m, Option_t *opt);
+  TH1 *DrawMatrixColClone(const TMatrixD &m, Option_t *opt, Int_t col);
+  void PrintTH3Content(const TH3 &hist);
+  void PrintTH3Error(const TH3 &hist);
+  void PrintTH2Content(const TH2 &hist);
+  void PrintTH2Error(const TH2 &hist);
+  void PrintTH1Content(const TH1 &hist);
+  void PrintTH1Error(const TH1 &hist);
+  void CopyCol(TMatrixD &m, const TH1 &h, Int_t col);
+  void CopyCol(TH1 &h, const TMatrixD &m, Int_t col);
+  void CopyH2M(TMatrixD &m, const TH2 &h);
+  void CopySqr(TMatrixD &m, const TH1 &h);
+  Double_t GetMatrixSumRow(const TMatrixD &m, Int_t row);
+  Double_t GetMatrixSumDiag(const TMatrixD &m);
+  Double_t GetMatrixSumCol(const TMatrixD &m, Int_t col);
+  Double_t GetMatrixSum(const TMatrixD &m);
+
+public:
+    TString   bintitle;
+
+    UInt_t    fNa;        // Number of bins in the distribution to be unfolded
+    UInt_t    fNb;        // Number of bins in the unfolded distribution
+
+    TMatrixD  fMigrat;    // migration matrix                  (fNa, fNb)
+    TMatrixD  fMigraterr2;// error**2 of migration matrix      (fNa, fNb)
+
+    TMatrixD  fMigOrig;    // original migration matrix         (fNa, fNb)
+    TMatrixD  fMigOrigerr2;// error**2 oforiginal migr. matrix  (fNa, fNb)
+
+    TMatrixD  fMigSmoo;    // smoothed migration matrix M       (fNa, fNb)
+    TMatrixD  fMigSmooerr2;// error**2 of smoothed migr. matrix (fNa, fNb)
+    TMatrixD  fMigChi2;    // chi2 contributions for smoothing  (fNa, fNb)
+
+    TMatrixD  fVa;        // distribution to be unfolded       (fNa)
+    TMatrixD  fVacov;     // error matrix of fVa               (fNa, fNa)
+    TMatrixD  fVacovInv; // inverse of fVacov                 (fNa, fNa)
+    Double_t  fSpurVacov; // Spur of fVacov
+
+    //    UInt_t    fVaevents;  // total number of events
+    UInt_t    fVapoints;  // number of significant measurements
+
+    TMatrixD  fVb;        // unfolded distribution             (fNb)
+    TMatrixD  fVbcov;     // error matrix of fVb               (fNb, fNb)
+
+    TMatrixD  fVEps;      // prior distribution                (fNb)
+    TMatrixDColumn fVEps0;
+
+    Double_t  fW;         // weight
+    Double_t  fWbest;     // best weight
+    Int_t     ixbest;
+
+    TMatrixD  fResult;    // unfolded distribution and errors  (fNb, 5)
+    TMatrixD  fChi2;      // chisquared contribution           (fNa, 1)
+
+    Double_t  fChisq;     // total chisquared
+    Double_t  fNdf;       // number of degrees of freedom
+    Double_t  fProb;      // chisquared probability
+
+    TMatrixD  G;          // G = M * M(transposed)             (fNa, fNa)
+    TVectorD  EigenValue; // vector of eigenvalues lambda of G (fNa)
+    TMatrixD  Eigen;      // matrix of eigen vectors of G      (fNa, fNa)
+    Double_t  RankG;      // rank of G
+    Double_t  tau;        // 1 / lambda_max
+    Double_t  EpsLambda;
+
+    // quantities stored for each weight :
+    TVectorD SpSig;       // Spur of covariance matrix of fVbcov
+    TVectorD SpAR;        // effective rank of G^tilde
+    TVectorD chisq;       // chi squared (measures agreement between
+    // fVa and the folded fVb)
+    TVectorD SecDer;      // regularization term = sum of (2nd der.)**2
+    TVectorD ZerDer;      // regularization term = sum of (fVb)**2
+    TVectorD Entrop;      // regularization term = reduced cross-entropy
+    TVectorD DAR2;        //
+    TVectorD Dsqbar;      //
+
+    Double_t SpurAR;
+    Double_t SpurSigma;
+    Double_t SecDeriv;
+    Double_t ZerDeriv;
+    Double_t Entropy;
+    Double_t DiffAR2;
+    Double_t Chisq;
+    Double_t D2bar;
+
+    TMatrixD Chi2;
+
+    //
+
+    // plots versus weight
+    Int_t    Nix;
+    Double_t xmin;
+    Double_t xmax;
+    Double_t dlogx;
+
+    TH1D *hBchisq;
+    TH1D *hBSpAR;
+    TH1D *hBDSpAR;
+    TH1D *hBSpSig;
+    TH1D *hBDSpSig;
+    TH1D *hBSecDeriv;
+    TH1D *hBDSecDeriv;
+    TH1D *hBZerDeriv;
+    TH1D *hBDZerDeriv;
+    TH1D *hBEntropy;
+    TH1D *hBDEntropy;
+    TH1D *hBDAR2;
+    TH1D *hBD2bar;
+
+    //
+    TH1D *hEigen;
+
+    // plots for the best solution
+    TH2D *fhmig;
+    TH2D *shmig;
+    TH2D *shmigChi2;
+
+    TH1D *fhb0;
+
+    TH1D *fha;
+
+    TH1D *hprior;
+
+    TH1D *hb;
+
+    Double_t CalcSpurSigma(TMatrixD &T, Double_t norm=1);
+
+    // -----------------------------------------------------------------------
+    //
+    // Constructor
+    //              copy histograms into matrices
+    //
+    MUnfold(TH1D &ha, TH2D &hacov, TH2D &hmig);
+    ~MUnfold();
+   
+    void SetPriorConstant();
+    Bool_t SetPriorRebin(TH1D &ha);
+    Bool_t SetPriorInput(TH1D &hpr);
+    Bool_t SetPriorPower(Double_t gamma);
+    Bool_t SetInitialWeight(Double_t &weight);
+    void PrintResults();
+    Bool_t Schmelling(TH1D &hb0);
+    void SchmellCore(Int_t full, Double_t &xiter, TMatrixD &gamma,
+			      TMatrixD &dgamma, Double_t &dga2);
+    Bool_t SmoothMigrationMatrix(TH2D &hmigorig);
+    Bool_t Tikhonov2(TH1D &hb0);
+    Bool_t Bertero(TH1D &hb0);
+    Bool_t BertCore(Double_t &xiter);
+    Bool_t CalculateG();
+    Bool_t SelectBestWeight();
+    Bool_t DrawPlots();
+    Bool_t CallMinuit(
+                      void (*fcnx)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t),
+                      UInt_t npar, char name[20][100],
+                      Double_t vinit[20], Double_t step[20],
+                      Double_t limlo[20], Double_t limup[20], Int_t fix[20]);
+    TMatrixD &GetVb() { return fVb; }
+    TMatrixD &GetVbcov() { return fVbcov; }
+    TMatrixD &GetResult() { return fResult; }
+    TMatrixD &GetChi2() { return fChi2; }
+    Double_t &GetChisq() { return fChisq; }
+    Double_t &GetNdf() { return fNdf; }
+    Double_t &GetProb() { return fProb; }
+    TMatrixD &GetMigSmoo() { return fMigSmoo; }
+    TMatrixD &GetMigSmooerr2() { return fMigSmooerr2; }
+    TMatrixD &GetMigChi2() { return fMigChi2; }
+
+    ClassDef(MUnfold, 1)
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mmpi/MUnfoldSpectrum.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MUnfoldSpectrum.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MUnfoldSpectrum.cc	(revision 9772)
@@ -0,0 +1,313 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!   Author(s) : R. Wagner, 02/2004 <mailto:rwagner@mppmu.mpg.de>           
+!
+!   Copyright: MAGIC Software Development, 2000-2005
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MUnfoldSpectrum
+//
+//  Unfolds a gamma spectrum using the algorithms given in the MUnfold class
+//
+/////////////////////////////////////////////////////////////////////////////   
+#include "MUnfoldSpectrum.h"
+
+#include "TH1D.h"
+#include "TH2D.h"
+#include "TH3D.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MUnfold.h"
+
+ClassImp(MUnfoldSpectrum);
+using namespace std;
+
+MUnfoldSpectrum::MUnfoldSpectrum()
+  : fUnfoldingMethod(2), fPrior(0)
+{
+      
+}
+
+void MUnfoldSpectrum::Calc()
+{
+  // Unfold # Excess events vs. Energy and Theta
+  
+  //   TH2D* tobeunfolded = hex->GetHist();
+  //   TH2D* unfolded = new TH2D(*tobeunfolded);  
+  //   TH3D* migration = migm->GetHist();
+  
+  //const Int_t energyBins = fToBeUnfolded->GetXaxis()->GetNbins();
+  //const Int_t thetaBins =  fToBeUnfolded->GetYaxis()->GetNbins();
+  //const TAxis* axisEnergy = fToBeUnfolded->GetXaxis();
+  //const TAxis* axisTheta  = fToBeUnfolded->GetYaxis();
+  //cout << "Distribution to be unfolded has " << energyBins 
+  //     << ", " << thetaBins << " bins" <<endl;
+  
+  TAxis &taxis  = *fToBeUnfolded->GetYaxis();
+  Int_t numybins = taxis.GetNbins();
+  
+  cout << "Processing a total number of  " << numybins << " bins. " <<endl;
+  cout << "-------------------" << endl << endl;
+  
+  for (Int_t m=1; m<=numybins; m++) {
+    TString bintitle = "Bin ";
+    bintitle += m;
+    bintitle += ": ";
+    
+    cout << "Processing " << bintitle << endl;
+    
+    // -----------------------------------------
+    // ha : distribution to be unfolded
+    
+    TH1D &ha = *fToBeUnfolded->ProjectionX("", m, m, "e");
+    TString title = bintitle;
+    title += "E-est distr. to be unfolded";
+    ha.SetNameTitle("ha", title);
+    TAxis &aaxis = *ha.GetXaxis();
+    Int_t na = aaxis.GetNbins();
+    Double_t alow = aaxis.GetBinLowEdge(1);
+    Double_t aup  = aaxis.GetBinLowEdge(na+1);
+	
+    cout << ha.GetName() << ": " << ha.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=ha.GetNbinsX(); i++)
+      cout << ha.GetBinContent(i) << " \t";
+    cout << endl << endl;
+	
+    // -----------------------------------------
+    // covariance matrix of the distribution ha
+      
+    title = bintitle;
+    title +=  "Error matrix of distribution ha";
+    TH2D hacov("hacov", title, na, alow, aup, na, alow, aup);
+          
+    Double_t errmin = 3.0;
+    for (Int_t i=1; i<=na; i++) {
+      for (Int_t j=1; j<=na; j++) 
+	hacov.SetBinContent(i, j, 0.0);	
+      const Double_t content = ha.GetBinContent(i);
+      const Double_t error2  = (ha.GetBinError(i))*(ha.GetBinError(i));
+      if (content <= errmin  &&  error2 < errmin) 
+	hacov.SetBinContent(i, i, errmin);
+      else
+	hacov.SetBinContent(i, i, error2);
+    }
+    
+    //PrintTH2Content(hacov);
+      
+    // -----------------------------------------
+    // migration matrix :
+    //           x corresponds to measured quantity
+    //           y corresponds to true quantity
+    
+    // The projection is made for the selected bins only.
+    // To select a bin range along an axis, use TAxis::SetRange, eg
+    // h3.GetYaxis()->SetRange(23,56);
+    
+    //        taxis->SetRange(m,m);
+    TH2D &hmig = *(TH2D*)fMigrationMatrix->Project3D("yxe");
+    title = bintitle;
+    title += "Migration Matrix";
+    hmig.SetNameTitle("Migrat", title);
+    
+    TAxis &aaxismig = *hmig.GetXaxis();
+    Int_t namig = aaxismig.GetNbins();
+    
+    if (na != namig) {
+      cout << "doUnfolding : binnings are incompatible; na, namig = "
+	   << na << ",  " << namig << endl;
+      return;
+    }
+    
+    TAxis &baxismig = *hmig.GetYaxis();
+    Int_t nbmig = baxismig.GetNbins();
+    Double_t blow = baxismig.GetBinLowEdge(1);
+    Double_t bup  = baxismig.GetBinLowEdge(nbmig+1);
+          
+    // -----------------------------------------
+    // dummy ideal distribution
+    
+    Int_t nb = nbmig;
+      
+    title = bintitle;
+    title += "Dummy Ideal distribution";
+    TH1D hb0("dummyhb0", title, nb, blow, bup);
+    //MH::SetBinning(&hb0, &baxismig); 
+    hb0.Sumw2();
+    
+    for (Int_t k=1; k<=nb; k++) {
+      hb0.SetBinContent(k, 1.0/nb);
+      hb0.SetBinError  (k, 0.1/nb);
+    }
+	
+    //PrintTH1Content(hb0);
+        
+    // -----------------------------------------
+    // unfolded distribution
+	
+    title = bintitle;
+    title += "Unfolded distribution";
+    TH1D hb("hb", title, nb, blow, bup);
+	                    
+    // ha      is the distribution to be unfolded
+    // hacov   is the covariance matrix of the distribution ha
+    // hmig    is the migration matrix;
+    //         it is used in the unfolding unless it is overwritten
+    //         by SmoothMigrationMatrix by the smoothed migration matrix
+    // hmigor  is the migration matrix to be smoothed;
+    //         the smoothed migration matrix will be used in the unfolding
+    // hpr     the prior distribution
+    //         it is only used if SetPriorInput(*hpr) is called   
+    // hb      unfolded distribution
+
+    // create an MUnfold object;
+    MUnfold unfold(ha, hacov, hmig);
+    unfold.bintitle = bintitle;
+
+    // smooth the migration matrix;
+    //        the smoothed migration matrix will be used in the unfolding
+    //        hmig is the original (unsmoothed) migration matrix
+    unfold.SmoothMigrationMatrix(hmig);
+
+    // define prior distribution (has always to be defined) 
+    // the alternatives are 
+    //   SetPriorConstant():   isotropic distribution
+    //   SetPriorPower(gamma): dN/dE = E^{-gamma}
+    //   SetPriorInput(*hpr):  the distribution *hpr is used 
+    //   SetPriorRebin(*ha):   use rebinned histogram ha 
+    Bool_t errorprior=kTRUE;
+    switch (fPrior)
+    {
+    case 1:
+        unfold.SetPriorConstant();
+        break;
+    case 2:
+        errorprior = unfold.SetPriorPower(fPriorPowerGamma);
+        break;
+    case 3:
+        if (!fPriorInputHist)
+        {
+            cout << "Error: No hpr!" << endl;
+            return;
+        }
+        errorprior = unfold.SetPriorInput(*fPriorInputHist);
+        break;
+    case 4:
+        errorprior = unfold.SetPriorRebin(*fPriorRebinHist);
+        break;
+    }
+    if (!errorprior)
+    {
+        cout << "MUnfoldSpectrum::SetPrior... : failed.  fPrior = " ;
+        cout << fPrior << endl;
+        return;
+    }
+
+    // calculate the matrix G = M * M(transposed)
+    //           M being the migration matrix
+    unfold.CalculateG();
+
+    switch (fUnfoldingMethod)
+    {
+    case 1: // Schmelling:
+    // minimize the function Z by Gauss-Newton iteration;
+    // the parameters to be fitted are gamma(i) = lambda(i)/w;
+        cout << "Unfolding algorithm : Schmelling" << endl;
+        if (!unfold.Schmelling(hb0)) cout << "MUnfoldSpectrum::Schmelling : failed." << endl;
+        break;
+
+    case 2: // Tikhonov2 :
+    // regularization term is sum of (2nd deriv.)**2 ;
+    // minimization by using MINUIT;
+    // the parameters to be fitted are
+    // the bin contents of the unfolded distribution
+        cout << "Unfolding algorithm :   Tikhonov" << endl;
+        if (!unfold.Tikhonov2(hb0)) cout << "MUnfoldSpectrum::Tikhonov2 : failed." << endl;
+        break;
+
+    case 3: // Bertero: minimization by iteration
+        cout << "Unfolding algorithm :    Bertero" << endl;
+        if (!unfold.Bertero(hb0)) cout << "MUnfoldSpectrum::Bertero : failed." << endl;
+        break;
+    }    
+    unfold.PrintResults();
+    unfold.DrawPlots();
+
+    // get unfolded distribution
+    TMatrixD &Vb    = unfold.GetVb();
+    TMatrixD &Vbcov = unfold.GetVbcov();
+    UInt_t fNb = unfold.fNb;
+    for (UInt_t a=0; a<fNb; a++)
+    {
+      hb.SetBinContent(a+1, Vb(a,0));
+      hb.SetBinError(a+1, sqrt(Vbcov(a, a)) );
+    }
+    
+    for (Int_t k=1; k<=nb; k++) {
+      Double_t content = hb.GetBinContent(k);
+      Double_t error   = hb.GetBinError(k);
+      
+      fUnfolded->SetBinContent(k, m, content);
+      fUnfolded->SetBinError(k, m, error);
+      
+      //hex->FillBinContent(k, m, content, error);
+    }    	
+  }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MUnfoldSpectrum::~MUnfoldSpectrum()
+{
+}
+
+
+// -----------------------------------------------------------------------
+//
+// Define prior distribution to be a constant
+//
+void MUnfoldSpectrum::SetPriorConstant()
+{
+  fPrior=1;  
+}
+
+void MUnfoldSpectrum::SetPriorRebin(TH1D *ha)
+{
+  fPriorRebinHist=ha;
+  fPrior=2;
+}
+ 
+void MUnfoldSpectrum::SetPriorInput(TH1D *hpr)
+{
+  fPriorInputHist=hpr;
+  fPrior=3;
+}
+
+void MUnfoldSpectrum::SetPriorPower(Double_t gamma)
+{
+  fPriorPowerGamma=gamma;
+  fPrior=4;
+}
+
Index: /tags/Mars-V0.9/mtemp/mmpi/MUnfoldSpectrum.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MUnfoldSpectrum.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MUnfoldSpectrum.h	(revision 9772)
@@ -0,0 +1,43 @@
+#ifndef MARS_MUnfoldSpectrum
+#define MARS_MUnfoldSpectrum
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class TH1D;
+class TH2D;
+class TH3D;
+
+class MUnfoldSpectrum : public MTask
+{
+ public:
+  MUnfoldSpectrum();
+  ~MUnfoldSpectrum();
+
+ private:
+  TH2D *fToBeUnfolded;
+  TH2D *fUnfolded;
+  TH3D *fMigrationMatrix;
+  Short_t fUnfoldingMethod;
+  Short_t fPrior;
+  TH1D *fPriorRebinHist;
+  TH1D *fPriorInputHist;
+  Double_t fPriorPowerGamma;
+
+ public:
+  void Calc();
+  void SetDistToUnfold(TH2D* dist) { fToBeUnfolded = dist; }
+  void SetMigrationMatrix(TH3D* migm) { fMigrationMatrix = migm; }
+  TH2D* GetUnfDist() { return fUnfolded; }
+  void SetPriorConstant();
+  void SetPriorRebin(TH1D *ha);
+  void SetPriorInput(TH1D *hpr);
+  void SetPriorPower(Double_t gamma);
+  void SetUnfoldingMethod(Short_t method) { fUnfoldingMethod = method; }
+  
+  ClassDef(MUnfoldSpectrum, 1)
+
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mmpi/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/Makefile	(revision 9772)
@@ -0,0 +1,52 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../../Makefile.conf.$(OSTYPE)
+include ../../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+CINT     = Mpi
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../../mbase \
+	   -I../../mfbase \
+	   -I../../mjobs \
+	   -I../../mpedestal \
+	   -I../../mbadpixels \
+	   -I../../mfileio \
+           -I../../mraw \
+           -I../../manalysis \
+	   -I../../mgui \
+	   -I../../mgeom \
+	   -I../../msignal \
+	   -I../../mcalib \
+	   -I../../mfilter \
+	   -I../../mhbase \
+	   -I../../mimage \
+	   -I../../mpointing \
+	   -I../../mcamera \
+	   -I../../mstarcam \
+	   -I../../mhist \
+	   -I../../mmc \
+	   -I../../mreport \
+	   -I../../mastro \
+	   -I../../mdata 
+
+SRCFILES = MSkyPlot.cc \
+           MPointingPosCalcWA.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mtemp/mmpi/MpiIncl.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MpiIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MpiIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtemp/mmpi/MpiLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/MpiLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/MpiLinkDef.h	(revision 9772)
@@ -0,0 +1,10 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MSkyPlot+;
+#pragma link C++ class MPointingPosCalcWA+;
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFRandomSplit.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFRandomSplit.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFRandomSplit.cc	(revision 9772)
@@ -0,0 +1,113 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 11/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFRandomSplit
+//
+//  A filter which gives fResult = kTRUE with the probability fProb
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFRandomSplit.h"
+
+#include <fstream>
+#include <TRandom.h>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MFRandomSplit);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//     Constructor
+//
+MFRandomSplit::MFRandomSplit(Double_t f, const char *name, const char *title)
+    : fProb(f)
+{
+    fName  = name  ? name  : "MFRandomSplit";
+    fTitle = title ? title : "Filter for random splitting";
+
+    if (fProb < 0)
+    {
+        *fLog << warn << "WARNING - MFRandomSplit::MFRandomSplit: Probability less than 0... set to 0." << endl;
+        fProb = 0;
+    }
+
+    if (fProb > 1)
+    {
+        *fLog << warn << "WARNING - MFRandomSplit::MFRandomSplit: Probability greater than 1... set to 1." << endl;
+        fProb = 1;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  PreProcess. Set fNumSelectedEvts=0
+//
+Int_t MFRandomSplit::PreProcess(MParList *pList)
+{
+    fNumSelectedEvts = 0;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//  
+//  Select events randomly according to the probability fProb. Count all
+//  selected events
+//
+Int_t MFRandomSplit::Process()
+{
+    fResult = gRandom->Uniform() < fProb;
+
+    if (fResult)
+        fNumSelectedEvts++;
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+//  PostProcess. Prints execution statistics
+//
+Int_t MFRandomSplit::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    *fLog << " " << setw(7) << fNumSelectedEvts << " (";
+    *fLog << setw(3) << (int)(100.*fNumSelectedEvts/GetNumExecutions());
+    *fLog << "%) selected - out of " << GetNumExecutions() << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFRandomSplit.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFRandomSplit.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFRandomSplit.h	(revision 9772)
@@ -0,0 +1,41 @@
+#ifndef MARS_MFRandomSplit
+#define MARS_MFRandomSplit
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFRandomSplit                                                           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MParList;
+
+class MFRandomSplit : public MFilter
+{
+private:
+    Int_t    fNumSelectedEvts;
+    Double_t fProb;    // probability with which the result should be kTRUE
+
+    Bool_t   fResult;  // Result returned by IsExpressionTrue
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MFRandomSplit(Double_t f, const char *name=NULL, const char *title=NULL);
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    ClassDef(MFRandomSplit, 0) // A Filter giving kTRUE with a certain probability
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFF.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFF.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFF.cc	(revision 9772)
@@ -0,0 +1,4474 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek 9/2003 <mailto:wittek@mppmu.mpg.de>
+!              David Paneque   11/2003 <mailto:dpaneque@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFindSupercutsONOFF                                                       //
+//                                                                         //
+// Class for optimizing the parameters of the supercuts                     //
+// Using ON and OFF data                                                   //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MFindSupercutsONOFF.h"
+
+#include <math.h>            // fabs 
+
+#include <TFile.h>
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TStopwatch.h>
+#include <TVirtualFitter.h>
+
+#include "MBinning.h"
+#include "MContinue.h"
+#include "MSupercuts.h"
+#include "MSupercutsCalcONOFF.h"
+#include "MDataElement.h"
+#include "MDataMember.h"
+
+
+#include <TPostScript.h>
+
+#include "MEvtLoop.h"
+#include "MFCT1SelFinal.h"
+#include "MF.h"
+#include "MFEventSelector.h"
+#include "MFEventSelector2.h"
+#include "MFillH.h"
+//#include "MGeomCamCT1Daniel.h"
+//#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+#include "MFRandomSplit.h"
+#include "MH3.h"
+#include "MHCT1Supercuts.h"
+#include "MHFindSignificance.h" // To be removed at some point...
+#include "MHFindSignificanceONOFF.h"
+#include "MTSupercutsApplied.h"
+#include "MHMatrix.h"
+#include "MHOnSubtraction.h"
+#include "MDataValue.h"
+// #include "MDataString.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMatrixLoop.h"
+#include "MMinuitInterface.h"
+#include "MParList.h"
+#include "MProgressBar.h"
+#include "MReadMarsFile.h"
+#include "MReadTree.h"
+#include "MTaskList.h"
+
+
+ClassImp(MFindSupercutsONOFF);
+
+using namespace std;
+
+
+
+// Function that computes the normalization factor using COUNTED events in alpha histogram 
+// for ON data  and alpha histogram for OFF data;
+// in alpha region defined by AlphaBkgMin and AlphaBkgMax
+
+// It is defined outside the class MFindSupercutsONOFF so that it can be used 
+// in function fcnSupercuts
+
+
+static Double_t ComputeNormFactorFromAlphaBkg(TH1 *histON, TH1 *histOFF, 
+					      Double_t AlphaBkgMin, 
+					      Double_t AlphaBkgMax)
+{                                                      
+
+    Double_t NormFactor = 0.0;
+    Double_t ONEvents = 0.0; 
+    Double_t OFFEvents = 0.0;
+
+    const Double_t SmallQuantity = 0.01;
+    
+    Double_t xlo = 0.0;
+    Double_t xup = 0.0;
+    Double_t width = 0.0;
+
+    Int_t BinCounterOFF = 0;
+    Int_t BinCounterON = 0;
+    
+
+    // I make a copy of the histograms so that nothing happens to the 
+    // histograms used in argument
+
+    TH1* HistON = (TH1*) histON->Clone();
+    TH1* HistOFF = (TH1*) histOFF->Clone();
+
+    if ( !HistON )
+    {
+	gLog << "ComputeNormFactorFromAlphaBkg; " << endl
+	      << "Clone of ON histogram could not be generated" 
+	      << endl;
+	return 0.0;
+    }
+
+
+    
+    if ( !HistOFF )
+    {
+	gLog << "ComputeNormFactorFromAlphaBkg; " << endl
+	      << " Clone of OFF histogram could not be generated" 
+	      << endl;
+	return 0.0;
+    }
+
+  // Calculate the number of OFF events in the Bkg region 
+  // defined by AlphaBkgMin and AlphaBkgMax 
+  // ___________________________________________________
+  
+
+    Int_t nbinsOFF = HistOFF -> GetNbinsX();  
+    Double_t binwidthOFF = HistOFF -> GetBinWidth(1);
+
+    for (Int_t i=1; i<=nbinsOFF; i++)
+    {
+	xlo = HistOFF->GetBinLowEdge(i);
+	xup = HistOFF->GetBinLowEdge(i+1);
+ 
+	// bin must be completely contained in the bkg region
+	if ( xlo >= (AlphaBkgMin-SmallQuantity)  &&  xup <= (AlphaBkgMax+SmallQuantity)    )
+	{
+	    width = fabs(xup-xlo);
+	    if (fabs(width-binwidthOFF) > SmallQuantity)
+	    {
+		gLog << "ComputeNormFactorFromAlphaBkg; " 
+		      << endl << " HistOFF has variable binning, which is not allowed" 
+		      << endl;
+		return 0.0;
+	    }
+
+	    BinCounterOFF++;
+
+	    OFFEvents  += HistOFF->GetBinContent(i);
+	    
+	}
+    }
+
+
+    // Calculate the number of ON events in the Bkg region 
+  // defined by AlphaBkgMin and AlphaBkgMax 
+  // ___________________________________________________
+  
+
+    Int_t nbinsON = HistON -> GetNbinsX();  
+    Double_t binwidthON = HistON -> GetBinWidth(1);
+
+    for (Int_t i=1; i<=nbinsON; i++)
+    {
+	xlo = HistON->GetBinLowEdge(i);
+	xup = HistON->GetBinLowEdge(i+1);
+ 
+	// bin must be completely contained in the bkg region
+	if ( xlo >= (AlphaBkgMin-SmallQuantity)  &&  xup <= (AlphaBkgMax+SmallQuantity)    )
+	{
+	    width = fabs(xup-xlo);
+	    if (fabs(width-binwidthON) > SmallQuantity)
+	    {
+		gLog << "ComputeNormFactorFromAlphaBkg; " 
+		      << endl << " HistON has variable binning, which is not allowed" 
+		      << endl;
+		return 0.0;
+	    }
+
+	    BinCounterON++;
+	    ONEvents  += HistON->GetBinContent(i);
+	    
+	}
+    }
+
+
+  
+
+    // NormFactor is computed
+
+      if (ONEvents < SmallQuantity || OFFEvents < SmallQuantity)
+      {
+	  gLog << "ComputeNormFactorFromAlphaBkg; " 
+		<< endl 
+		<< "ONEvents or OFFEvents computed in bkg region are < " 
+		<< SmallQuantity << endl;
+	  return 0.0;
+	  
+      }
+
+     
+	  
+    
+    NormFactor = ONEvents/OFFEvents;
+
+    Double_t error = 1/ONEvents + 1/OFFEvents;
+    error = TMath::Sqrt(error);
+    error = error * NormFactor;
+
+     // tmp info
+      gLog << "ComputeNormFactorFromAlphaBkg;" << endl
+	   << "ON Events in bkg region = " << ONEvents 
+	   << " (" << BinCounterON << " bins)"
+	   << " , OFF Events in bkg region = " << OFFEvents 
+	   << " (" << BinCounterOFF << " bins)" << endl
+	   <<"NormFactor computed from bkg region = " << NormFactor 
+	   << " +/- " << error << endl;
+      // end temp
+
+    return NormFactor;
+
+}
+
+
+
+
+
+
+
+
+//------------------------------------------------------------------------
+//
+// fcnSupercuts 
+//
+// - calculates the quantity to be minimized (using TMinuit)
+//
+// - the quantity to be minimized is (-1)*significance of the gamma signal
+//   in the alpha distribution (after cuts)
+//
+// - the parameters to be varied in the minimization are the cut parameters
+//   (par)
+//
+static void fcnSupercuts(Int_t &npar, Double_t *gin, Double_t &f, 
+                         Double_t *par, Int_t iflag)
+{
+    //cout <<  "entry fcnSupercuts" << endl;
+
+    //-------------------------------------------------------------
+    // save pointer to the MINUIT object for optimizing the supercuts
+    // because it will be overwritten 
+    // when fitting the alpha distribution in MHFindSignificance
+    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+
+    MEvtLoop* evtloopfcn = (MEvtLoop*)gMinuit->GetObjectFit();
+
+    // Event loops for ON and OFF data are recovered. 
+
+    MEvtLoop* ONDataevtloopfcn = &evtloopfcn[0];
+    MEvtLoop* OFFDataevtloopfcn = &evtloopfcn[1];
+
+
+    // Parameter list from event loops for ON and OFF data are recovered
+
+    MParList *ONDataplistfcn   = (MParList*) ONDataevtloopfcn->GetParList();
+    MParList *OFFDataplistfcn   = (MParList*) OFFDataevtloopfcn->GetParList();
+    
+    // MTaskList *ONDataTasklistfcn   = (MTaskList*) ONDataevtloopfcn->GetTaskList();
+    // MTaskList *OFFDataTasklistfcn   = (MTaskList*) OFFDataevtloopfcn->GetTaskList();
+
+
+
+    // Container for supercuts is retrieved from ONDataplistfcn. 
+    // NOTE: The same supercuts parameter container is used in  OFFDataplistfcn
+
+    MSupercuts *super = (MSupercuts*) ONDataplistfcn->FindObject("MSupercuts");
+    if (!super)
+    {
+        gLog << "fcnSupercuts : MSupercuts object '" << "MSupercuts"
+            << "' not found... aborting" << endl;
+        return;
+    }
+
+
+    // Normalization factor for train sample (Train ON before cuts/ train OFF before cuts) 
+    // is retrieved from the ONDataplistfcn
+
+    Double_t NormalizationFactorTrain = 0.0;
+    
+    MDataValue* NormFactorContainer = (MDataValue*) ONDataplistfcn->FindObject("NormFactorTrain");
+    NormalizationFactorTrain = NormFactorContainer -> GetValue();
+
+    
+    gLog << "fcnSupercuts : Normalization factor retrieved from ONDataplistfcn: " << endl
+	 << "NormalizationFactorTrain = " << NormalizationFactorTrain << endl;
+    
+
+    // Degree of polynomials used to fit the ON and the OFF data are retrieved from 
+    // the event loop
+
+    Int_t degreeON;
+    Int_t degreeOFF;
+
+    MDataValue* DegreeONContainer = (MDataValue*) ONDataplistfcn->FindObject("DegreeON");
+    degreeON = int(DegreeONContainer -> GetValue());
+
+    MDataValue* DegreeOFFContainer = (MDataValue*) OFFDataplistfcn->FindObject("DegreeOFF");
+    degreeOFF = int(DegreeOFFContainer -> GetValue());
+
+    gLog << "fcnSupercuts : fDegreeON and fDegreeOFF retrieved from ONDataplistfcn and OFFDataplistfcn: " << endl
+         << "fDegreeON, fDegreeOFF: = " << degreeON << " ," << degreeOFF << endl;
+
+
+    Double_t AlphaSig = 0.0;
+    MDataValue* AlphaSigContainer = (MDataValue*) ONDataplistfcn->FindObject("AlphaSigValue");
+    AlphaSig = AlphaSigContainer -> GetValue();
+
+    Double_t AlphaBkgMin = 0.0;
+    MDataValue* AlphaBkgMinContainer = 
+	(MDataValue*) ONDataplistfcn->FindObject("AlphaBkgMinValue");
+    AlphaBkgMin = AlphaBkgMinContainer -> GetValue();
+
+    Double_t AlphaBkgMax = 0.0;
+    MDataValue* AlphaBkgMaxContainer = 
+	(MDataValue*) ONDataplistfcn->FindObject("AlphaBkgMaxValue");
+    AlphaBkgMax = AlphaBkgMaxContainer -> GetValue();
+
+    
+    gLog << "fcnSupercuts : AlphaSig and AlphaBkgMin-AlphaBkgMax retrieved from ONDataplistfcn: "
+	 << endl
+	 << "AlphaSig = " << AlphaSig << "; AlphaBkgMin-AlphaBkgMax = " 
+	 << AlphaBkgMin << "-" << AlphaBkgMax << endl;
+
+
+
+    // Variable fUseFittedQuantities is retrieved from ONDataplistfcn
+
+    Bool_t UseFittedQuantities;
+    MDataValue* UseFittedQuantitiesContainer = 
+	(MDataValue*) ONDataplistfcn->FindObject("UseFittedQuantitiesValue");
+    UseFittedQuantities = bool(UseFittedQuantitiesContainer -> GetValue());
+    
+    if (UseFittedQuantities)
+    {
+	gLog << "fcnSupercuts :  UseFittedQuantities variable set to kTRUE" << endl;
+    }
+    else
+    {
+	gLog << "fcnSupercuts :  UseFittedQuantities variable set to kFALSE" << endl;
+    }
+    
+
+    Bool_t UseNormFactorFromAlphaBkg;
+    MDataValue* UseNormFactorFromAlphaBkgContainer = 
+      (MDataValue*) ONDataplistfcn -> FindObject("UseNormFactorFromAlphaBkgValue");
+    UseNormFactorFromAlphaBkg = bool(UseNormFactorFromAlphaBkgContainer -> GetValue());
+
+
+    if (UseNormFactorFromAlphaBkg)
+    {
+	gLog << "fcnSupercuts :  UseNormFactorFromAlphaBkg variable set to kTRUE" << endl;
+    }
+    else
+    {
+	gLog << "fcnSupercuts :  UseNormFactorFromAlphaBkg variable set to kFALSE" << endl;
+    }
+
+
+
+
+    //
+    // transfer current parameter values to MSupercuts
+    //
+    // Attention : npar is the number of variable parameters
+    //                  not the total number of parameters
+    //
+    Double_t fMin, fEdm, fErrdef;
+    Int_t     fNpari, fNparx, fIstat;
+    gMinuit->mnstat(fMin, fEdm, fErrdef, fNpari, fNparx, fIstat);
+
+    super->SetParameters(TArrayD(fNparx, par));
+
+    //$$$$$$$$$$$$$$$$$$$$$
+    // for testing
+    //  TArrayD checkparameters = super->GetParameters();
+    //gLog << "fcnsupercuts : fNpari, fNparx =" << fNpari << ",  " 
+    //     << fNparx  << endl;
+    //gLog << "fcnsupercuts : i, par, checkparameters =" << endl;
+    //for (Int_t i=0; i<fNparx; i++)
+    //{
+    //gLog << i << ",  " << par[i] << ",  " << checkparameters[i] << endl;
+    //  }
+    //$$$$$$$$$$$$$$$$$$$$$
+
+    //
+    // plot alpha for ON data with the current cuts
+    //
+    if (!ONDataevtloopfcn->Eventloop())
+    {
+	gLog << "fcnsupercuts  : ONDataevtloopfcn->Eventloop() failed" << endl;
+    }
+    
+    // Somehow (??) I can not use the function MTaskList::PrintStatistics...
+    // it produces a segmentation fault...
+
+    //ONDataTasklistfcn->PrintStatistics(0, kFALSE);
+    
+    MH3* alpha = (MH3*)ONDataplistfcn->FindObject("AlphaFcn", "MH3");
+    if (!alpha)
+        return;
+
+    TH1 &alphaHist = alpha->GetHist();
+    alphaHist.SetName("alpha-fcnSupercuts");
+
+
+    //
+    // plot alpha for OFF data with the current cuts
+    //
+    if(!OFFDataevtloopfcn->Eventloop())
+    {
+	gLog << "fcnsupercuts  : OFFDataevtloopfcn->Eventloop() failed" << endl;
+    }
+
+    // Somehow (??) I can not use the function MTaskList::PrintStatistics...
+    // it produces a segmentation fault...
+
+    //OFFDataTasklistfcn->PrintStatistics(0, kFALSE);
+
+    MH3* alphaOFF = (MH3*) OFFDataplistfcn->FindObject("AlphaOFFFcn", "MH3");
+    if (!alphaOFF)
+        return;
+
+    TH1 &alphaHistOFF = alphaOFF->GetHist();
+    alphaHistOFF.SetName("alphaOFF-fcnSupercuts");
+
+
+
+
+
+    if (UseNormFactorFromAlphaBkg)
+      {
+	// Normalization factor computed using alpha bkg region
+	Double_t NewNormFactor = 
+	    ComputeNormFactorFromAlphaBkg(&alphaHist, &alphaHistOFF, 
+					  AlphaBkgMin, AlphaBkgMax);
+	
+	gLog << "Normalization factor computed from alpha plot (after cuts) " << endl
+	      << "using counted number of ON and OFF events in alpha region " << endl
+	      << "defined by range " << AlphaBkgMin << "-" << AlphaBkgMax << endl
+	      << "Normalization factor = " << NewNormFactor << endl;
+
+	gLog << "Normalization factor used is the one computed in bkg region; " << endl
+	      << "i.e. " << NewNormFactor << " instead of " << NormalizationFactorTrain << endl;
+
+	NormalizationFactorTrain = NewNormFactor;
+
+
+    }
+
+
+
+
+
+
+
+    //-------------------------------------------
+    // set Minuit pointer to zero in order not to destroy the TMinuit
+    // object for optimizing the supercuts
+    gMinuit = NULL;
+
+    //=================================================================
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    const Double_t alphasig = AlphaSig;
+    const Double_t alphamin = AlphaBkgMin; 
+   // alpha min for bkg region in ON data
+    const Double_t alphamax = AlphaBkgMax; // alpha max for bkg region in ON data
+
+
+    Bool_t drawpoly;
+    Bool_t fitgauss;
+    Bool_t saveplots;
+    
+
+    if (iflag == 3)
+    {// Even though minimization finished successfully, I will NOT produce 
+	// final plots now... i'll do it later via the function 
+	// "MFindSupercutsONOFF::OutputOptimizationOnTrainSample()"
+
+        drawpoly  = kFALSE;
+        fitgauss  = kFALSE;
+	saveplots = kFALSE;
+    }
+    else
+    {
+        drawpoly  = kFALSE;
+        fitgauss  = kFALSE;
+	saveplots = kFALSE;
+	
+	
+    }
+
+
+    const Bool_t print = kTRUE;
+
+    MHFindSignificanceONOFF findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+    findsig.SetUseFittedQuantities(UseFittedQuantities);
+    
+    // TPostScript* DummyPs  = new TPostScript("dummy.ps");
+    
+    TString DummyPs = ("Dummy");
+  
+
+    const Bool_t rc = findsig.FindSigmaONOFF(&alphaHist,&alphaHistOFF, 
+					     NormalizationFactorTrain, 
+					     alphamin, alphamax, 
+					     degreeON, degreeOFF,
+					     alphasig, drawpoly, fitgauss, 
+					     print, saveplots, 
+					     DummyPs);
+    //DummyPs -> Close();
+    //delete DummyPs;
+
+    
+    //=================================================================
+
+    // reset gMinuit to the MINUIT object for optimizing the supercuts 
+    gMinuit = savePointer;
+    //-------------------------------------------
+
+    if (!rc)
+    {
+        gLog << "fcnSupercuts : FindSigmaONOFF() failed" << endl;
+        f = 1.e10;
+        return;
+    }
+
+    /*
+
+    // plot some quantities during the optimization
+    MHCT1Supercuts *plotsuper = (MHCT1Supercuts*)ONDataplistfcn->FindObject("MHCT1Supercuts");
+    if (plotsuper)
+        plotsuper->Fill(&findsig);
+
+
+
+    */
+
+    //------------------------
+    // get significance
+    const Double_t significance = findsig.GetSignificance();
+    f = significance>0 ? -significance : 0;
+
+
+    gLog << " ///****************************************** ///" << endl;
+    gLog << "Significance (Li&Ma)is now: " << f << endl;
+    gLog << " ///****************************************** ///" << endl;
+
+    //------------------------
+    // optimize signal/background ratio
+    //Double_t ratio = findsig.GetNbg()>0.0 ? 
+    //                 findsig.GetNex()/findsig.GetNbg() : 0.0; 
+    //f = -ratio;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFindSupercutsONOFF::MFindSupercutsONOFF(const char *name, const char *title)
+    : fHowManyTrain(10000), fHowManyTest(10000), fMatrixFilter(NULL)
+{
+    fName  = name  ? name  : "MFindSupercutsONOFF";
+    fTitle = title ? title : "Optimizer of the supercuts";
+
+    //---------------------------
+    // camera geometry is needed for conversion mm ==> degree
+    //fCam = new MGeomCamCT1Daniel; 
+    // fCam = new MGeomCamCT1; 
+    fCam = new MGeomCamMagic; 
+
+    // matrices to contain the training/test samples
+    fMatrixTrain = new MHMatrix("MatrixTrain");
+    fMatrixTest  = new MHMatrix("MatrixTest");
+    fMatrixTrainOFF = new MHMatrix("MatrixTrainOFF");
+    fMatrixTestOFF  = new MHMatrix("MatrixTestOFF");
+    
+
+    // objects of MSupercutsCalcONOFF to which these matrices are attached
+    fCalcHadTrain = new MSupercutsCalcONOFF("SupercutsCalcTrain");
+    fCalcHadTest  = new MSupercutsCalcONOFF("SupercutsCalcTest");
+    fCalcHadTrainOFF = new MSupercutsCalcONOFF("SupercutsCalcTrainOFF");
+    fCalcHadTestOFF  = new MSupercutsCalcONOFF("SupercutsCalcTestOFF");
+
+    // Define columns of matrices
+    fCalcHadTrain->InitMapping(fMatrixTrain);
+    fCalcHadTest->InitMapping(fMatrixTest);
+    fCalcHadTrainOFF->InitMapping(fMatrixTrainOFF);
+    fCalcHadTestOFF->InitMapping(fMatrixTestOFF);
+
+    // For the time being weights method is not implemented
+    //UseWeights = kFALSE; 
+
+    // Normalization factors are initialized to -1
+    // Functions determining Number of excess events will not work 
+    // with negative norm factors;  
+    // This will ensure that Norm factors are computed before running
+    // DetExcessONOFF() function.
+
+    fNormFactorTrain = -1.0;
+    fNormFactorTest = -1.0;
+
+    // SigmaLiMa and Nex member variables are initialized to 0
+
+    fSigmaLiMaTrain = 0.0;
+    fSigmaLiMaTest = 0.0;
+    fNexTrain = 0.0; 
+    fNexTest = 0.0; 
+
+    
+    // Cuts (low and up) in variable MPointingPos.fZd
+    // (at some point real theta)
+    // The default is not cut, i.e. all values (0-1) are taken
+    
+    //fThetaMin = 0; // in miliradians  // FIXME: change name
+    //fThetaMax = 1570; // in miliradians // FIXME: change name
+    
+    fThetaMin = 0; // degrees (new in magic)
+    fThetaMax = 90; // degrees (new in magic)
+
+
+
+    fAlphaSig = 20; // By default, signal is expected in alpha<20 for CT1
+
+    // By default, bkg region is set to alpha range 30-90 for CT1
+    fAlphaBkgMin = 30; 
+    fAlphaBkgMax = 90;
+
+
+    // By default, bining for alpha plots is set to 
+    
+    fNAlphaBins = 54;
+    fAlphaBinLow = -12;
+    fAlphaBinUp = 96;
+
+
+
+    fNormFactorFromAlphaBkg = kTRUE; // By default normalization factor is 
+    // computed using bkg region in alpha histograms (after cuts)
+
+//    fActualCosThetaBinCenter = 0;
+
+    fTuneNormFactor = kTRUE; // Norm factors will be corrected using 
+    //the total amount of OFF events before cuts and the estimated excess events
+    // fNormFactorTrain = fNormFactorTrain - Ngammas/EventsInTrainMatrixOFF
+
+
+    // use quantities computed from the fits
+    // The variable allows the user to NOT use these quantities when there is not 
+    // enough statistics and fit not always is possible.
+    // Default value is kTRUE
+    fUseFittedQuantities = kTRUE;
+
+
+
+
+    // Boolean variable that allows the user to set some limits to the 
+    // some of the Minuit parameters. For the time being, only the limits
+    // for the parameters which do NOT depend in size, dist and theta are set, 
+    // i.e. static limits. The value of this boolean variable is set in the 
+    // constructor of the class.
+    
+    fSetLimitsToSomeMinuitParams = kTRUE;
+    
+    // Limits for the Minuit parameters. For the time being the values are set in the constructor 
+    // of the class. One MUST be very careful to set limits such that the expected final values 
+    // (optimized values) are far away from the limits.
+    
+    // Values in degrees
+    
+
+    fMinuitDistUPUpperLimit = 2.0;
+    fMinuitDistUPLowerLimit = 0.5;
+    fMinuitLengthUPUpperLimit = 0.8;
+    fMinuitLengthUPLowerLimit = 0.0;
+    fMinuitWidthUPUpperLimit = 0.5;
+    fMinuitWidthUPLowerLimit = 0.0;
+    fMinuitLeakage1UPUpperLimit = 1.5;
+    fMinuitLeakage1UPLowerLimit = -0.5;
+    
+    fMinuitDistLOWUpperLimit = 1.0;
+    fMinuitDistLOWLowerLimit = 0.0;
+    fMinuitLengthLOWUpperLimit = 0.5;
+    fMinuitLengthLOWLowerLimit = -0.3;
+    fMinuitWidthLOWUpperLimit = 0.4;
+    fMinuitWidthLOWLowerLimit = -0.3;
+
+
+
+    // Boolean variable that controls wether the optimization of the 
+    // parameters (MMinuitInterface::CallMinuit(..) in function FindParams(..))
+    // takes place or not. kTRUE will skip such optimization.
+    // This variable is useful to test the optmized parameters (previously found 
+    // and stored in root file) on the TRAIN sample.
+    
+    fSkipOptimization = kFALSE;
+
+    // Boolean variable that allows the user to write the initial parameters 
+    // into the root file that will be used to store the optimum cuts.
+    // If fUseInitialSCParams = kTRUE , parameters are written.
+    // In this way, the initial SC parameters can be applied on the data (train/test) 
+    
+    // The initial parameters are ONLY written to the root file if 
+    // there is NO SC params optimization, i.e., if variable 
+    // fSkipOptimization = kTRUE;
+
+    // The default value is obviously kFALSE.
+
+    fUseInitialSCParams = kTRUE;
+    
+
+    // Set wether to use or not hillas dist
+    fUseDist = kTRUE;
+
+
+
+
+    fGammaEfficiency = 0.5; // Fraction of gammas that remain after cuts
+    // Quantity that will have to be determined with MC, yet for the 
+    // time being I set it to 0.5 (standard value)
+
+    fPsFilename = NULL;
+    fPsFilename2 = NULL;
+
+
+    ////////////////////////////////////////////////////
+    // TMP
+
+    // There are quite some problems during the data preprocessing. 
+    // For the time being, I will add some cuts to the functions 
+    // DefineTrainTestMatrixThetaRange and for OFF, so that I can 
+    // make a kind of preprocess on my own. This allows me 
+    // to make a very silly preprocess with wolfgangs macro, which 
+    // might be free of corrupted data, and then I can do on my own.
+
+    fSizeCutLow = 0.1; // To prevent empty events
+    fSizeCutUp = 10000000;
+
+    // Angular cuts are converted to mm, which 
+    // are the units of the preprocessed data....
+
+
+    // Angular cuts not yet implemented ...
+    fConvMMToDeg = 0.00337034;
+
+    fDistCutLow = 0.4/fConvMMToDeg;
+    fDistCutUp = 1.5/fConvMMToDeg;
+    
+    fLengthCutLow = 0.1/fConvMMToDeg;
+    fLengthCutUp = 1/fConvMMToDeg;
+
+    fWidthCutLow = 0.07/fConvMMToDeg;
+    fWidthCutUp = 1/fConvMMToDeg;
+
+    // ENDTMP
+    ////////////////////////////////////////////////////
+    
+    
+    // Degree of polynomials used to fit the ON OFF data is 
+    // set initially to 2.
+
+    fDegreeON = 2;
+    fDegreeOFF = 2;
+
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MFindSupercutsONOFF::~MFindSupercutsONOFF()
+{
+
+    *fLog << "destructor of MFindSupercutsONOFF is called" << endl;
+
+    fPsFilename = NULL;
+    fPsFilename2 = NULL;
+
+
+    delete fCam;
+    delete fMatrixTrain;
+    delete fMatrixTest;
+    delete fCalcHadTrain;
+    delete fCalcHadTest;
+    delete fMatrixTrainOFF;
+    delete fMatrixTestOFF;
+    delete fCalcHadTrainOFF;
+    delete fCalcHadTestOFF;
+    
+    *fLog << "destructor of MFindSupercutsONOFF finished successfully" << endl;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Function that sets the name of the PostScript file where alpha distributions 
+// for the different Theta bins will be stored.
+// It also initializes 
+
+
+
+void MFindSupercutsONOFF::SetPostScriptFile (TPostScript* PsFile)
+{
+    fPsFilename = PsFile;
+
+    *fLog << "MFindSupercutsONOFF : Results (alpha distributions with excess and significances) will be stored in PostScript file " 
+	  << fPsFilename -> GetName() << endl;
+
+}
+
+void MFindSupercutsONOFF::SetPostScriptFile2 (TPostScript &PsFile)
+{
+    fPsFilename2 = new TPostScript (PsFile);
+
+    *fLog << "MFindSupercutsONOFF : Results (alpha distributions with excess and significances) will be stored in PostScript file " 
+	  << fPsFilename2 -> GetName() << endl;
+
+}
+
+void MFindSupercutsONOFF::SetPsFilenameString (const TString filename)
+{
+    fPsFilenameString = filename;
+}
+
+void MFindSupercutsONOFF::SetSkipOptimization(Bool_t b)
+{
+    fSkipOptimization = b;
+    if (fSkipOptimization)
+    {
+	*fLog << "MFindSupercutsONOFF :: SetSkipOptimization " << endl
+	      << "Variable fSkipOptimization is kTRUE, and therefore "
+	      << "the optimization of supercuts is skipped. Hope that's "
+	      << "what you want... " << endl;
+    }
+
+}
+
+
+void MFindSupercutsONOFF::SetUseInitialSCParams(Bool_t b)
+{
+    fUseInitialSCParams = b;
+    if (fUseInitialSCParams)
+    {
+	*fLog << "MFindSupercutsONOFF :: SetUseInitialSCParams " << endl
+	      << "Variable fUseInitialSCParams is kTRUE. " << endl;
+
+	if (fSkipOptimization)
+	{
+	    *fLog << "The Initial SC Parameters will be applied on the selected data."
+		  << endl;
+	}
+
+	else
+	{
+	    *fLog << "However, fSkipOptimization = kFALSE, and therefore, the " 
+		  << "the supercuts will be optimized. The final cuts that " 
+		  << "will be applied to the data will NOT be the initial SC parameters."
+		  << endl;
+
+	}
+
+
+
+    }
+    
+}
+
+
+
+Bool_t MFindSupercutsONOFF::SetAlphaSig(Double_t alphasig)
+{
+    // check that alpha is within the limits 0-90
+    if (alphasig <= 0 || alphasig > 90)
+    {
+	*fLog << "MFindSupercutsONOFF ::SetAlphaSig; " 
+	      << "value " << alphasig << " is not within the the "
+	      << "logical limits of alpha; 0-90" << endl;
+	return kFALSE;
+    }
+    
+
+    fAlphaSig = alphasig;
+
+    return kTRUE;
+}
+
+Bool_t MFindSupercutsONOFF::SetAlphaBkgMin(Double_t alpha)
+{
+    // check that alpha is within the limits 0-90
+    if (alpha <= 0 || alpha >= 90)
+    {
+	*fLog << "MFindSupercutsONOFF ::SetAlphaBkgMin; " 
+	      << "value " << alpha << " is not within the the "
+	      << "logical limits of alpha; 0-90" << endl;
+	return kFALSE;
+    }
+    
+
+    fAlphaBkgMin = alpha;
+
+    return kTRUE;
+}
+
+
+Bool_t MFindSupercutsONOFF::SetAlphaBkgMax(Double_t alpha)
+{
+    // check that alpha is within the limits 0-90
+    if (alpha <= 0 || alpha > 90.001)
+    {
+	*fLog << "MFindSupercutsONOFF ::SetAlphaBkgMax; " 
+	      << "value " << alpha << " is not within the the "
+	      << "logical limits of alpha; 0-90" << endl;
+	return kFALSE;
+    }
+    
+
+    fAlphaBkgMax = alpha;
+
+    return kTRUE;
+}
+
+
+// Function that checks that the values of the member data 
+// fAlphaSig, fAlphaBkgMin and fAlphaBkgMax make sense
+// (ie, fAlphaSig < fAlphaBkgMin < fAlphaBkgMax)
+
+Bool_t MFindSupercutsONOFF::CheckAlphaSigBkg()
+{
+
+    if (fAlphaSig > fAlphaBkgMin)
+    {
+	*fLog << "MFindSupercutsONOFF ::CheckAlphaSigBkg(); " << endl
+	      << "fAlphaSig > fAlphaBkgMin, which should not occur..." << endl
+	      << "fAlphaSig = " << fAlphaSig << ", fAlphaBkgMin = " << fAlphaBkgMin
+	      << endl;
+
+	return kFALSE;
+    }
+    
+    if (fAlphaBkgMax < fAlphaBkgMin)
+    {
+	*fLog << "MFindSupercutsONOFF ::CheckAlphaSigBkg(); " << endl
+	      << "fAlphaBkgMin > fAlphaBkgMax, which should not occur..." << endl
+	      << "fAlphaBkgMin = " << fAlphaBkgMin << ", fAlphaBkgMax = " << fAlphaBkgMax
+	      << endl;
+
+	return kFALSE;
+    }
+
+    return kTRUE;
+
+}
+
+
+/*
+// Function that computes the normalization factor using COUNTED events ON and OFF
+// in alpha region defined by fAlphaBkgMin and fAlphaBkgMax
+
+
+Double_t MFindSupercutsONOFF::ComputeNormFactorFromAlphaBkg(TH1 *histON, TH1 *histOFF)
+{
+
+    Double_t NormFactor = 0.0;
+    Double_t ONEvents = 0.0; 
+    Double_t OFFEvents = 0.0;
+
+    const Double_t SmallQuantity = 0.01;
+    
+    Double_t xlo = 0.0;
+    Double_t xup = 0.0;
+    Double_t width = 0.0;
+
+    Int_t BinCounterOFF = 0;
+    Int_t BinCounterON = 0;
+    
+
+    // I make a copy of the histograms so that nothing happens to the 
+    // histograms used in argument
+
+    TH1* HistON = (TH1*) histON->Clone();
+    TH1* HistOFF = (TH1*) histOFF->Clone();
+
+    if ( !HistON )
+    {
+	*fLog << "MFindSupercutsONOFF::ComputeNormFactorFromAlphaBkg; " << endl
+	      << "Clone of ON histogram could not be generated" 
+	      << endl;
+	return 0.0;
+    }
+
+
+    
+    if ( !HistOFF )
+    {
+	*fLog << "MFindSupercutsONOFF::ComputeNormFactorFromAlphaBkg; " << endl
+	      << " Clone of OFF histogram could not be generated" 
+	      << endl;
+	return 0.0;
+    }
+
+  // Calculate the number of OFF events in the Bkg region 
+  // defined by fAlphaBkgMin and fAlphaBkgMax 
+  // ___________________________________________________
+  
+
+    Int_t nbinsOFF = HistOFF -> GetNbinsX();  
+    Double_t binwidthOFF = HistOFF -> GetBinWidth(1);
+
+    for (Int_t i=1; i<=nbinsOFF; i++)
+    {
+	xlo = HistOFF->GetBinLowEdge(i);
+	xup = HistOFF->GetBinLowEdge(i+1);
+ 
+	// bin must be completely contained in the bkg region
+	if ( xlo >= (fAlphaBkgMin-SmallQuantity)  &&  xup <= (fAlphaBkgMax+SmallQuantity)    )
+	{
+	    width = fabs(xup-xlo);
+	    if (fabs(width-binwidthOFF) > SmallQuantity)
+	    {
+		*fLog << "MFindSupercutsONOFF::ComputeNormFactorFromAlphaBkg; " 
+		      << endl << " HistOFF has variable binning, which is not allowed" 
+		      << endl;
+		return 0.0;
+	    }
+
+	    BinCounterOFF++;
+
+	    OFFEvents  += HistOFF->GetBinContent(i);
+	    
+	}
+    }
+
+
+    // Calculate the number of ON events in the Bkg region 
+  // defined by fAlphaBkgMin and fAlphaBkgMax 
+  // ___________________________________________________
+  
+
+    Int_t nbinsON = HistON -> GetNbinsX();  
+    Double_t binwidthON = HistON -> GetBinWidth(1);
+
+    for (Int_t i=1; i<=nbinsON; i++)
+    {
+	xlo = HistON->GetBinLowEdge(i);
+	xup = HistON->GetBinLowEdge(i+1);
+ 
+	// bin must be completely contained in the bkg region
+	if ( xlo >= (fAlphaBkgMin-SmallQuantity)  &&  xup <= (fAlphaBkgMax+SmallQuantity)    )
+	{
+	    width = fabs(xup-xlo);
+	    if (fabs(width-binwidthON) > SmallQuantity)
+	    {
+		*fLog << "MFindSupercutsONOFF::ComputeNormFactorFromAlphaBkg; " 
+		      << endl << " HistON has variable binning, which is not allowed" 
+		      << endl;
+		return 0.0;
+	    }
+
+	    BinCounterON++;
+	    ONEvents  += HistON->GetBinContent(i);
+	    
+	}
+    }
+
+
+  
+
+    // NormFactor is computed
+
+      if (ONEvents < SmallQuantity || OFFEvents < SmallQuantity)
+      {
+	  *fLog << "MFindSupercutsONOFF::ComputeNormFactorFromAlphaBkg; " 
+		<< endl 
+		<< "ONEvents or OFFEvents computed in bkg region are < " 
+		<< SmallQuantity << endl;
+	  return 0.0;
+	  
+      }
+
+     
+	  
+    
+    NormFactor = ONEvents/OFFEvents;
+
+    Double_t error = 1/ONEvents + 1/OFFEvents;
+    error = TMath::Sqrt(error);
+    error = error * NormFactor;
+
+     // tmp info
+      cout << "MFindSupercutsONOFF::ComputeNormFactorFromAlphaBkg;" << endl
+	   << "ON Events in bkg region = " << ONEvents 
+	   << " (" << BinCounterON << " bins)"
+	   << " , OFF Events in bkg region = " << OFFEvents 
+	   << " (" << BinCounterOFF << " bins)" << endl
+	   <<"NormFactor computed from bkg region = " << NormFactor 
+	   << " +/- " << error << endl;
+      // end temp
+
+    return NormFactor;
+
+}
+
+
+*/
+
+
+// Function that set the values of fThetaMin and fThetaMax and also 
+// fThetaRangeString (with value in miliradians); 
+// data members that are used basically to print/plot
+// information. 
+
+Bool_t MFindSupercutsONOFF::SetThetaRange(Double_t ThetaMin, Double_t ThetaMax)
+{
+
+// Check  that values are reasonable... well ... i guess this was done 
+// in previous functions...
+
+  //    fThetaMin = int(ThetaMin*1000.0);
+  //  fThetaMax = int(ThetaMax*1000.0);
+
+
+  // in new magic theta is given in deg
+  // 0.5 is added so that the rounding to integer is correct
+  fThetaMin = int(ThetaMin + 0.5); 
+  fThetaMax = int(ThetaMax + 0.5); 
+
+    fThetaRangeString = ("ThetaRange");
+    fThetaRangeString += (fThetaMin);
+    fThetaRangeString += ("_");
+    fThetaRangeString += (fThetaMax);
+    // fThetaRangeString += ("mRad");
+    fThetaRangeString += ("_Degrees"); // new in magic
+
+
+    return kTRUE;
+
+}
+
+// Function that sets Size range
+Bool_t MFindSupercutsONOFF::SetSizeRange(Double_t SizeMin, Double_t SizeMax)
+{
+
+
+    fSizeCutLow = SizeMin;
+    fSizeCutUp = SizeMax;
+
+    *fLog << "MFindSupercutsONOFF::SetSizeRange" << endl
+	  << "Data matrices will be filled with events whose MHillas.fSize " << endl
+	  << "is in the range " 
+	  << fSizeCutLow <<"-"<<fSizeCutUp << endl;
+
+
+
+    return kTRUE;
+}
+
+
+Bool_t MFindSupercutsONOFF::SetFilters(Double_t LeakageMax, Double_t DistMax, Double_t DistMin)
+{
+
+    fDistCutLow = DistMin/fConvMMToDeg;
+    fDistCutUp  = DistMax/fConvMMToDeg;
+    fLeakageMax = LeakageMax;
+    
+    *fLog << "MFindSupercutsONOFF::SetSizeRange" << endl
+	  << "Data matrices will be filled with events whose MHillasSrc.fDist " << endl
+	  << "is in the range " 
+	  << fDistCutLow <<"-"<< fDistCutUp << " degrees" << endl
+	  << "and fLeakage " << "< " << fLeakageMax << endl;
+
+    return kTRUE;
+}
+
+
+
+// Function that sets the names of all parameter containers 
+// used to store the supercuts applied to ON/OFF Train/Test samples
+
+void MFindSupercutsONOFF::SetSupercutsAppliedTreeNames()
+{
+
+    char* sc = {"SupercutsApplied"};
+
+    fTrainONSupercutsAppliedName = (sc);  
+    fTrainONSupercutsAppliedName += ("TrainON");
+
+    fTrainOFFSupercutsAppliedName = (sc);       
+    fTrainOFFSupercutsAppliedName += ("TrainOFF");
+
+    fTestONSupercutsAppliedName = (sc);
+    fTestONSupercutsAppliedName += ("TestON");
+
+    fTestOFFSupercutsAppliedName = (sc); 
+    fTestOFFSupercutsAppliedName += ("TestOFF");
+    
+
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::SetSupercutsAppliedTreeNames; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+
+	fTrainONSupercutsAppliedName += ("ThetaRangeStringUndefined");
+	fTrainOFFSupercutsAppliedName += ("ThetaRangeStringUndefined");
+	fTestONSupercutsAppliedName += ("ThetaRangeStringUndefined");
+	fTestOFFSupercutsAppliedName += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	fTrainONSupercutsAppliedName += (fThetaRangeString);
+	fTrainOFFSupercutsAppliedName += (fThetaRangeString);
+	fTestONSupercutsAppliedName += (fThetaRangeString);
+	fTestOFFSupercutsAppliedName += (fThetaRangeString);
+    }
+     
+    // Info about names
+
+    *fLog << "MFindSupercutsONOFF::SetSupercutsAppliedTreeNames; " << endl
+	  << "Names of the MTSupercutsApplied Trees for Train (ON/OFF) " 
+	  << " and Test (ON/OFF) samples are the following ones: " << endl
+	  << fTrainONSupercutsAppliedName << ", " 
+	  << fTrainOFFSupercutsAppliedName << ", "
+	  << fTestONSupercutsAppliedName << ", "
+	  << fTestOFFSupercutsAppliedName << endl;
+  
+}
+
+
+void MFindSupercutsONOFF::SetUseOrigDistribution(Bool_t b)
+{
+  fUseOrigDistribution = b;
+
+  if (fUseOrigDistribution == kTRUE)
+  {
+ 
+      *fLog << "MFindSupercutsONOFF : when defining training and test matrices use the original distribution" 
+	    << endl;
+  }
+
+  else 
+  {
+      *fLog << "MFindSupercutsONOFF : when defining training and test matrices, events will be selected according to distribution given by a MH3 object" 
+	    << endl;
+  }
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Define the matrix 'fMatrixTrain' for the training sample
+//
+// alltogether 'howmanytrain' events are read from file 'nametrain';
+// the events are selected according to a target distribution 'hreftrain'
+//
+//
+Bool_t MFindSupercutsONOFF::DefineTrainMatrix(const TString &nametrain, MH3 &hreftrain,
+						 const Int_t howmanytrain, 
+						 const TString &filetrain)
+{
+    if (nametrain.IsNull() || howmanytrain <= 0)
+        return kFALSE;
+
+    *fLog << "=============================================" << endl;
+    *fLog << "fill training matrix from file '" << nametrain 
+          << "',   select " << howmanytrain 
+          << " events " << endl;
+
+    if (!fUseOrigDistribution)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftrain.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+    
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", nametrain);
+    read.DisableAutoScheme();
+
+
+    MFEventSelector2 seltrain(hreftrain);
+    seltrain.SetNumMax(howmanytrain);
+    seltrain.SetName("selectTrain");
+    if (fUseOrigDistribution)
+    {
+	*fLog << "MFindSupercutsONFF; MFEventSelector2::SetUseOrigDistribution(Bool)"
+	      << " DOES NOT EXIST NOW..." << endl;
+	// seltrain.SetUseOrigDistribution(kTRUE);
+    }
+
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetFilter(&seltrain);
+    filltrain.SetName("fillMatrixTrain");
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&seltrain);
+    tlist.AddToList(&filltrain);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrain");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrain->Print("SizeCols");
+    Int_t howmanygenerated = fMatrixTrain->GetM().GetNrows();
+    if (TMath::Abs(howmanygenerated-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MFindSupercutsONOFF::DefineTrainMatrix; no.of generated events ("
+	    << howmanygenerated 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    *fLog << "training matrix was filled" << endl;
+    *fLog << "=============================================" << endl;
+
+    //--------------------------
+    // write out training matrix
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MFindSupercuts::DefineTrainMatrix; Training matrix was written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+
+ 
+
+// --------------------------------------------------------------------------
+//
+// Define the matrix for the test sample
+//
+// alltogether 'howmanytest' events are read from file 'nametest'
+//
+// the events are selected according to a target distribution 'hreftest'
+//
+//
+Bool_t MFindSupercutsONOFF::DefineTestMatrix(const TString &nametest, MH3 &hreftest,
+						const Int_t howmanytest, const TString &filetest)
+{
+    if (nametest.IsNull() || howmanytest<=0)
+        return kFALSE;
+
+    *fLog << "=============================================" << endl;
+    *fLog << "fill test matrix from file '" << nametest 
+          << "',   select " << howmanytest << " events " << endl;
+
+
+    if (!fUseOrigDistribution)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftest.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", nametest);
+    read.DisableAutoScheme();
+
+    MFEventSelector2 seltest(hreftest);
+    seltest.SetNumMax(howmanytest);
+    seltest.SetName("selectTest");
+    if (fUseOrigDistribution)
+    {
+	*fLog << "MFindSupercutsONFF; MFEventSelector2::SetUseOrigDistribution(Bool)"
+	      << " DOES NOT EXIST NOW..." << endl;
+	// seltest.SetUseOrigDistribution(kTRUE);
+    }
+      
+
+    MFillH filltest(fMatrixTest);
+    filltest.SetFilter(&seltest);
+    filltest.SetName("fillMatrixTest");
+
+
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTest);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&seltest);
+    tlist.AddToList(&filltest);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTest");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTest->Print("SizeCols");
+    const Int_t howmanygenerated = fMatrixTest->GetM().GetNrows();
+    if (TMath::Abs(howmanygenerated-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MFindSupercutsONOFF::DefineTestMatrix; no.of generated events ("
+	    << howmanygenerated 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+    *fLog << "test matrix was filled" << endl;
+    *fLog << "=============================================" << endl;
+
+    //--------------------------
+    // write out test matrix
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MFindSupercutsONOFF::DefineTestMatrix; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+
+    
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices for the training and test sample respectively
+//
+//
+//
+Bool_t MFindSupercutsONOFF::DefineTrainTestMatrix(
+    const TString &name, MH3 &href,
+    const Int_t howmanytrain, const Int_t howmanytest,
+    const TString &filetrain, const TString &filetest)
+{
+    *fLog << "=============================================" << endl;
+    *fLog << "fill training and test matrix from file '" << name 
+          << "',   select "   << howmanytrain 
+          << " training and " << howmanytest << " test events " << endl;
+    if (!fUseOrigDistribution)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << href.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", name);
+    read.DisableAutoScheme();
+
+     MFEventSelector2 selector(href);
+    selector.SetNumMax(howmanytrain+howmanytest);
+    selector.SetName("selectTrainTest");
+    selector.SetInverted();
+    if (fUseOrigDistribution)
+    {
+	*fLog << "MFindSupercutsONFF; MFEventSelector2::SetUseOrigDistribution(Bool)"
+	      << " DOES NOT EXIST NOW..." << endl;
+	// selector.SetUseOrigDistribution(kTRUE);
+    }
+
+    MContinue cont(&selector);
+    cont.SetName("ContTrainTest");
+
+    Double_t prob =  ( (Double_t) howmanytrain )
+                   / ( (Double_t)(howmanytrain+howmanytest) );
+    MFRandomSplit split(prob);
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetFilter(&split);
+    filltrain.SetName("fillMatrixTrain");
+
+
+    // consider this event as candidate for a test event 
+    // only if event was not accepted as a training event
+
+    MContinue conttrain(&split);
+    conttrain.SetName("ContTrain");
+
+    MFillH filltest(fMatrixTest);
+    filltest.SetName("fillMatrixTest");
+
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+    plist.AddToList(fMatrixTest);
+
+    //******************************
+
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&cont);
+
+    tlist.AddToList(&split);
+    tlist.AddToList(&filltrain);
+    tlist.AddToList(&conttrain);
+
+    tlist.AddToList(&filltest);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrainTest");
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxev = -1;
+    if (!evtloop.Eventloop(maxev))
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrain->Print("SizeCols");
+
+    const Int_t generatedtrain = fMatrixTrain->GetM().GetNrows();
+    if (TMath::Abs(generatedtrain-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MFindSupercuts::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtrain 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    fMatrixTest->Print("SizeCols");
+    const Int_t generatedtest = fMatrixTest->GetM().GetNrows();
+    if (TMath::Abs(generatedtest-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MFindSupercuts::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtest 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+
+    *fLog << "training and test matrix were filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+    //--------------------------
+    // write out training matrix
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MFindSupercuts::DefineTrainTestMatrix; Training matrix was written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+    //--------------------------
+    // write out test matrix
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MFindSupercuts::DefineTrainTestMatrix; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices for the training and test OFF sample respectively
+//
+//
+//
+
+Bool_t MFindSupercutsONOFF::DefineTrainTestMatrixOFFThetaRange(
+    const TString &name, 
+    const Double_t whichfractiontrain, 
+    const Double_t whichfractiontest,  
+    Double_t ThetaMin, Double_t ThetaMax, 
+    const TString &filetrain, const TString &filetest)
+    
+
+
+{
+    *fLog << "=============================================" << endl;
+    *fLog << "Fill training and testing OFF matrices from file '" << name 
+          << "',   select a fraction of " << whichfractiontrain 
+          << " events for the training and a fraction of " << endl
+	  << whichfractiontest << " for the testing" << endl;
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    MReadMarsFile read("Events", name);
+    read.DisableAutoScheme();
+
+
+    
+
+    
+    // Cuts in Theta
+
+    // TString ThetaCutMinString ("ThetaOrig.fVal>");
+    TString ThetaCutMinString ("MPointingPos.fZd>"); // new! // for magic
+    ThetaCutMinString += ThetaMin;
+    MContinue ThetaCutMin(ThetaCutMinString);
+    ThetaCutMin.SetInverted();
+
+    //TString ThetaCutMaxString ("ThetaOrig.fVal<");
+    TString ThetaCutMaxString ("MPointingPos.fZd<"); // new! // for magic
+    ThetaCutMaxString += ThetaMax;
+    MContinue ThetaCutMax(ThetaCutMaxString);
+    ThetaCutMax.SetInverted();
+
+
+    
+    // Cuts in Size,
+
+    TString SizeCutMinString ("MHillas.fSize>"); 
+    SizeCutMinString += fSizeCutLow;
+    MContinue SizeCutMin(SizeCutMinString);
+    SizeCutMin.SetInverted();
+
+    
+    TString SizeCutMaxString ("MHillas.fSize<"); 
+    SizeCutMaxString += fSizeCutUp;
+    MContinue SizeCutMax(SizeCutMaxString);
+    SizeCutMax.SetInverted();
+    
+    // Cuts in Dist
+    TString DistCutMinString ("MHillasSrc.fDist>"); 
+    DistCutMinString += fDistCutLow;
+    MContinue DistCutMin(DistCutMinString);
+    DistCutMin.SetInverted();
+
+    TString DistCutMaxString ("MHillasSrc.fDist<"); 
+    DistCutMaxString += fDistCutUp; 
+    MContinue DistCutMax(DistCutMaxString);
+    DistCutMax.SetInverted();
+
+
+    // Cuts in leakage
+    TString LeakCutMaxString ("MNewImagePar.fLeakage1<"); 
+    LeakCutMaxString += fLeakageMax; 
+    MContinue LeakCutMax(LeakCutMaxString);
+    LeakCutMax.SetInverted();
+
+
+
+
+    Double_t prob = whichfractiontrain /(whichfractiontrain+whichfractiontest);
+                   
+    
+    
+
+    MFRandomSplit split(prob);
+
+    MFillH filltrain(fMatrixTrainOFF);
+    filltrain.SetName("fillMatrixTrainOFF");
+    filltrain.SetFilter(&split);
+    
+    
+    // consider this event as candidate for a test event 
+    // only if event was not accepted as a training event
+
+    MContinue conttrain(&split);
+    conttrain.SetName("ContTrain");
+
+    MFillH filltest(fMatrixTestOFF);
+    filltest.SetName("fillMatrixTestOFF");
+    
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrainOFF);
+    plist.AddToList(fMatrixTestOFF);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&ThetaCutMin);
+    tlist.AddToList(&ThetaCutMax);
+    
+    
+    tlist.AddToList(&SizeCutMin);
+    tlist.AddToList(&SizeCutMax);
+
+    tlist.AddToList(&DistCutMin);
+    tlist.AddToList(&DistCutMax);
+    tlist.AddToList(&LeakCutMax);
+
+    
+    tlist.AddToList(&split);
+    tlist.AddToList(&filltrain);
+
+    tlist.AddToList(&conttrain);
+    tlist.AddToList(&filltest);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrainTestOFF");
+    evtloop.SetProgressBar(&bar);
+    
+    Int_t maxev = -1;
+    if (!evtloop.Eventloop(maxev))
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrainOFF->Print("SizeCols");
+
+    
+    fMatrixTestOFF->Print("SizeCols");
+    
+
+    *fLog << "train and test matrix OFF were filled" << endl;
+    *fLog << "=============================================" << endl;
+    
+    
+    //--------------------------
+    // write out training matrix
+    
+    if (filetrain != "")
+    {
+	TFile filetr(filetrain, "RECREATE");
+	fMatrixTrainOFF->Write();
+	filetr.Close();
+	
+	*fLog << "MFindSupercutsONOFF::DefineTrainTestMatrixOFFThetaRange; Training matrix was written onto file '"
+	      << filetrain << "'" << endl;
+    }
+    
+    //--------------------------
+    // write out test matrix
+
+    if (filetest != "")
+    {
+	TFile filete(filetest, "RECREATE", "");
+	fMatrixTestOFF->Write();
+	filete.Close();
+	
+	*fLog << "MFindSupercutsONOFF::DefineTrainTestMatrixOFFThetaRange; Test matrix was written onto file '"
+	      << filetest << "'" << endl;
+    }
+    
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices for the training and test sample respectively
+//
+//
+//
+Bool_t MFindSupercutsONOFF::DefineTrainTestMatrixThetaRange(
+    const TString &name, 
+    const Double_t whichfractiontrain, 
+    const Double_t whichfractiontest,  
+    Double_t ThetaMin, Double_t ThetaMax, 
+    const TString &filetrain, const TString &filetest)
+
+   
+{
+    *fLog << "=============================================" << endl;
+    *fLog << "Fill training and testing ON matrices from file '" << name 
+          << "',   select a fraction of " << whichfractiontrain 
+          << " events for the training and a fraction of " << endl
+	  << whichfractiontest << " for the testing" << endl;
+
+
+    MParList  plist;
+    MTaskList tlist;
+
+    
+    MReadMarsFile read("Events", name);
+    read.DisableAutoScheme();
+
+
+     // Cuts in Theta
+
+    //TString ThetaCutMinString ("ThetaOrig.fVal>");
+    TString ThetaCutMinString ("MPointingPos.fZd>"); // for magic
+    ThetaCutMinString += ThetaMin;
+    MContinue ThetaCutMin(ThetaCutMinString);
+    ThetaCutMin.SetInverted();
+
+    //TString ThetaCutMaxString ("ThetaOrig.fVal<");
+    TString ThetaCutMaxString ("MPointingPos.fZd<"); // for magic
+    ThetaCutMaxString += ThetaMax;
+    MContinue ThetaCutMax(ThetaCutMaxString);
+    ThetaCutMax.SetInverted();
+
+
+    
+    // Cuts in Size,
+
+    TString SizeCutMinString ("MHillas.fSize>"); 
+    SizeCutMinString += fSizeCutLow;
+    MContinue SizeCutMin(SizeCutMinString);
+    SizeCutMin.SetInverted();
+
+    
+    TString SizeCutMaxString ("MHillas.fSize<"); 
+    SizeCutMaxString += fSizeCutUp;
+    MContinue SizeCutMax(SizeCutMaxString);
+    SizeCutMax.SetInverted();
+    
+
+    // Cuts in Dist
+    TString DistCutMinString ("MHillasSrc.fDist>");
+    DistCutMinString += fDistCutLow;
+    MContinue DistCutMin(DistCutMinString);
+    DistCutMin.SetInverted();
+
+    TString DistCutMaxString ("MHillasSrc.fDist<");
+    DistCutMaxString += fDistCutUp;
+    MContinue DistCutMax(DistCutMaxString);
+    DistCutMax.SetInverted();
+
+
+    // Cuts in leakage
+    TString LeakCutMaxString ("MNewImagePar.fLeakage1<");
+    LeakCutMaxString += fLeakageMax;
+    MContinue LeakCutMax(LeakCutMaxString);
+    LeakCutMax.SetInverted();
+
+
+    Double_t prob = whichfractiontrain/(whichfractiontrain + whichfractiontest);
+
+    
+
+    MFRandomSplit split(prob);
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetName("fillMatrixTrain");
+    filltrain.SetFilter(&split);
+    
+    
+    // consider this event as candidate for a test event 
+    // only if event was not accepted as a training event
+
+    MContinue conttrain(&split);
+    conttrain.SetName("ContTrain");
+
+    MFillH filltest(fMatrixTest);
+    filltest.SetName("fillMatrixTest");
+
+
+  
+
+    //******************************
+    // entries in MParList 
+    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+    plist.AddToList(fMatrixTest);
+
+    //******************************
+    // entries in MTaskList 
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&ThetaCutMin);
+    tlist.AddToList(&ThetaCutMax);
+    
+       
+    
+    tlist.AddToList(&SizeCutMin);
+    tlist.AddToList(&SizeCutMax);
+
+    tlist.AddToList(&DistCutMin);
+    tlist.AddToList(&DistCutMax);
+    tlist.AddToList(&LeakCutMax);
+
+    
+
+    tlist.AddToList(&split);
+    tlist.AddToList(&filltrain);
+
+    tlist.AddToList(&conttrain);
+    tlist.AddToList(&filltest);
+
+    //******************************
+
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrainTest");
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxev = -1;
+    if (!evtloop.Eventloop(maxev))
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrain->Print("SizeCols");
+    
+    fMatrixTest->Print("SizeCols");
+    
+
+    *fLog << "training and test matrix were filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+    //--------------------------
+    // write out training matrix
+
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MFindSupercutsONOFF::DefineTrainTestMatrixThetaRange; Train matrix was written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+
+     //--------------------------
+    // write out test matrix
+
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MFindSupercutsONOFF::DefineTrainTestMatrixThetaRange; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+  return kTRUE;
+}
+
+
+
+
+
+/// **********///
+
+// --------------------------------------------------------------------------
+//
+// Read only training matrices ON and OFF
+//
+//
+
+Bool_t MFindSupercutsONOFF::ReadMatrixTrain(const TString &filetrainON, const TString &filetrainOFF)
+{
+  //--------------------------
+  // read in training matrix ON sample
+
+  TFile filetr(filetrainON);
+  fMatrixTrain->Read("MatrixTrain");
+  fMatrixTrain->Print("SizeCols");
+
+  *fLog << "MFindSupercuts::ReadMatrixTrain; Training matrix for ON sample was read in from file '"
+        << filetrainON << "'" << endl;
+  filetr.Close();
+
+
+  // read in training matrix OFF sample
+
+  TFile filetrOFF(filetrainOFF);
+  fMatrixTrainOFF->Read("MatrixTrainOFF");
+  fMatrixTrainOFF->Print("SizeCols");
+
+  *fLog << "MFindSupercutsONOFF::ReadMatrixTrain; Training matrix for OFF sample was read in from file '"
+        << filetrainOFF << "'" << endl;
+  filetrOFF.Close();
+
+  return kTRUE;  
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Read only test matrices ON and OFF
+//
+//
+
+Bool_t MFindSupercutsONOFF::ReadMatrixTest(const TString &filetestON, const TString &filetestOFF)
+{
+  //--------------------------
+  // read in testing matrix ON sample
+
+//--------------------------
+  // read in test matrix for ON sample
+  
+  TFile filete(filetestON);
+  fMatrixTest->Read("MatrixTest");
+  fMatrixTest->Print("SizeCols");
+
+  *fLog << "MFindSupercuts::ReadMatrixTest; Test matrix for ON sample was read in from file '"
+        << filetestON << "'" << endl;
+  filete.Close();
+  
+
+   //--------------------------
+  // read in test matrix for OFF sample
+  
+  TFile fileteOFF(filetestOFF);
+  fMatrixTestOFF->Read("MatrixTestOFF");
+  fMatrixTestOFF->Print("SizeCols");
+
+  *fLog << "MFindSupercutsONOFF::ReadMatrixTest; Test matrix for OFF sample was read in from file '"
+        << filetestOFF << "'" << endl;
+  filete.Close();
+
+
+
+  return kTRUE;  
+
+}
+
+
+/// **********///
+
+// --------------------------------------------------------------------------
+//
+// Read training and test matrices from files
+//
+//
+
+Bool_t MFindSupercutsONOFF::ReadMatrix(const TString &filetrain, const TString &filetest)
+{
+  //--------------------------
+  // read in training matrix
+
+  TFile filetr(filetrain);
+  fMatrixTrain->Read("MatrixTrain");
+  fMatrixTrain->Print("SizeCols");
+
+  *fLog << "MFindSupercuts::ReadMatrix; Training matrix was read in from file '"
+        << filetrain << "'" << endl;
+  filetr.Close();
+
+
+  //--------------------------
+  // read in test matrix
+  
+  TFile filete(filetest);
+  fMatrixTest->Read("MatrixTest");
+  fMatrixTest->Print("SizeCols");
+
+  *fLog << "MFindSupercuts::ReadMatrix; Test matrix was read in from file '"
+        << filetest << "'" << endl;
+  filete.Close();
+  
+  return kTRUE;  
+}
+
+
+// Read training and test matrices OFF from files
+//
+//
+
+Bool_t MFindSupercutsONOFF::ReadMatrixOFF(const TString &filetrain, const TString &filetest)
+{
+  //--------------------------
+  // read in training matrix
+
+  TFile filetr(filetrain);
+  fMatrixTrainOFF->Read("MatrixTrainOFF");
+  fMatrixTrainOFF->Print("SizeCols");
+
+  *fLog << "MFindSupercutsONOFF::ReadMatrixOFF; Training matrix OFF was read in from file '"
+        << filetrain << "'" << endl;
+  filetr.Close();
+
+
+  //--------------------------
+  // read in test matrix
+  
+  TFile filete(filetest);
+  fMatrixTestOFF->Read("MatrixTestOFF");
+  fMatrixTestOFF->Print("SizeCols");
+
+  *fLog << "MFindSupercutsONOFF::ReadMatrixONOFF; Test matrix OFF was read in from file '"
+        << filetest << "'" << endl;
+  filete.Close();
+  
+  return kTRUE;  
+}
+
+
+
+// Function to compute the normalization factor for Train sample.
+// The normalization factor is defined as the ratio of OFF/ON events.
+
+Bool_t  MFindSupercutsONOFF::ComputeNormFactorTrain()
+{
+   Int_t EventsInTrainMatrixON = fMatrixTrain->GetM().GetNrows(); 
+   Int_t EventsInTrainMatrixOFF = fMatrixTrainOFF->GetM().GetNrows();
+
+   // Info...
+   *fLog << "MFindSupercutsONOFF::ComputeNormFactorTrain; " << endl
+	 << "EventsInTrainMatrixON = " << EventsInTrainMatrixON 
+	 << " , EventsInTrainMatrixOFF = " << EventsInTrainMatrixOFF << endl;
+
+
+   fNormFactorTrain = double(EventsInTrainMatrixON)/double(EventsInTrainMatrixOFF);
+
+   
+   *fLog << "MFindSupercutsONOFF::ComputeNormFactorTrain; fNormFactorTrain is : " 
+	 << fNormFactorTrain << endl;
+   
+   return kTRUE;
+}
+
+
+
+
+// Function to compute the normalization factor for Test sample.
+// The normalization factor is defined as the ratio of OFF/ON events.
+
+Bool_t  MFindSupercutsONOFF::ComputeNormFactorTest()
+{
+   Int_t EventsInTestMatrixON = fMatrixTest->GetM().GetNrows(); 
+   Int_t EventsInTestMatrixOFF = fMatrixTestOFF->GetM().GetNrows();
+
+   // Info...
+   *fLog << "MFindSupercutsONOFF::ComputeNormFactorTest; " << endl
+	 << "EventsInTestMatrixON = " << EventsInTestMatrixON 
+	 << " , EventsInTestMatrixOFF = " << EventsInTestMatrixOFF << endl;
+
+   fNormFactorTest = double(EventsInTestMatrixON)/double(EventsInTestMatrixOFF);
+   
+   *fLog << "MFindSupercutsONOFF::ComputeNormFactorTest; fNormFactorTest is : " 
+	 << fNormFactorTest << endl;
+
+   return kTRUE;
+}
+
+
+Bool_t  MFindSupercutsONOFF::SetGammaEfficiency(Double_t gammaeff)
+{
+
+    if (gammaeff < 0.0 || gammaeff >1.0)
+    {
+	*fLog << "MFindSupercutsONOFF::SetGammaEfficiency; " << endl
+	      << "The argument of SetGammaEfficiency ("
+	      << gammaeff << ") is outside the range 0-1" << endl
+	      << "This is not allowed..." << endl;
+	return kFALSE;
+	    
+    }
+
+    fGammaEfficiency = gammaeff;
+    
+    // TEMP INFO
+    cout << "fGammaEfficiency has been set to : " << fGammaEfficiency << endl;
+    // END TEMP
+    return kTRUE;
+	
+
+}
+
+//------------------------------------------------------------------------
+//
+// Steering program for optimizing the supercuts
+// ---------------------------------------------
+//
+//      the criterion for the 'optimum' is 
+//
+//          - a maximum significance of the gamma signal in the alpha plot, 
+//            in which the supercuts have been applied
+//
+// The various steps are :
+//
+// - setup the 2 event loops (ON and OFF) to be executed for each call to fcnSupercuts 
+// - call TMinuit to do the minimization of (-significance) :
+//        the fcnSupercuts function calculates the significance 
+//                                             for the current cut values
+//        for this - the 2 alpha plots (ON and OFF) are produced in the 2 event loops, 
+//                   in which the SAME cuts have been applied
+//                 - the significance of the gamma signal is extracted from the 
+//                   the 2 alpha plots (ON OFF) using MHFindSignificanceONOFF::FindSigmaONOFF.
+//                   
+//
+// Needed as input : (to be set by the Set functions)
+//
+// - fFilenameParam      name of file to which optimum values of the 
+//                       parameters are written
+//
+// - fHadronnessName     name of container where MSupercutsCalcONOFF will
+//                       put the supercuts hadronness for ON data
+
+// - fHadronnessNameOFF  name of container where MSupercutsCalcONOFF will
+//                       put the supercuts hadronness for OFF data
+//
+// - fAlphaSig, fAlphaBkgMin, fAlphaBkgMax ; Signal and Bkg region in alpha histo. 
+
+// - for the minimization, the starting values of the parameters are taken  
+//     - from file parSCinit (if it is != "")
+//     - or from the arrays params and/or steps 
+//
+//----------------------------------------------------------------------
+Bool_t MFindSupercutsONOFF::FindParams(TString parSCinit,
+					  TArrayD &params, TArrayD &steps)
+{
+    // Setup the event loops which will be executed in the 
+    //                 fcnSupercuts function  of MINUIT
+    //
+    // parSCinit is the name of the file containing the initial values 
+    // of the parameters; 
+    // if parSCinit = ""   'params' and 'steps' are taken as initial values
+
+    *fLog << "=============================================" << endl;
+    *fLog << "Setup event loop for fcnSupercuts" << endl;
+
+    if (fHadronnessName.IsNull())
+    {
+      *fLog << "MFindSupercutsONOFF::FindParams; hadronness name for ON data is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+
+    if (fHadronnessNameOFF.IsNull())
+    {
+      *fLog << "MFindSupercutsONOFF::FindParams; hadronness name for OFF data is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+
+    if (fMatrixTrain == NULL)
+    {
+      *fLog << "MFindSupercuts::FindParams; training matrix is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrain->GetM().GetNrows() <= 0)
+    {
+      *fLog << "MFindSupercuts::FindParams; training matrix has no entries"
+            << endl;
+      return kFALSE;
+    }
+
+    
+
+    if (fMatrixTrainOFF == NULL)
+    {
+      *fLog << "MFindSupercutsONOFF::FindParams; training matrix OFF is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrainOFF->GetM().GetNrows() <= 0)
+    {
+      *fLog << "MFindSupercutsONOFF::FindParams; training matrix OFF has no entries"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fAlphaDistributionsRootFilename.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::FindParams; fAlphaDistributionsRootFilename is not defined... program aborting..." << endl;
+
+	return kFALSE;
+    }
+
+   
+
+    //--------------------------------
+    // create container for the supercut parameters
+    // and set them to their initial values
+    MSupercuts super;
+
+    // take initial values from file parSCinit
+    if (parSCinit != "")
+    {
+      TFile inparam(parSCinit);
+      super.Read("MSupercuts");
+      inparam.Close();
+      *fLog << "MFindSupercutsONOFF::FindParams; initial values of parameters are taken from file "
+            << parSCinit << endl;
+    }
+
+    // take initial values from 'params' and/or 'steps'
+    else if (params.GetSize() != 0  || steps.GetSize()  != 0 )
+    {
+	if (params.GetSize()  != 0)
+	{
+	    *fLog << "MFindSupercutsONOFF::FindParams; initial values of parameters are taken from 'params'"
+		  << endl;
+	    super.SetParameters(params);
+	}
+	if (steps.GetSize()  != 0)
+	{
+	    *fLog << "MFindSupercutsONOFF::FindParams; initial step sizes are taken from 'steps'"
+		  << endl;
+	    super.SetStepsizes(steps);
+	}
+	
+	/*
+	// TMP
+	// Print parameters
+	if (params.GetSize() == steps.GetSize())
+	{
+	    *fLog << "MFindSupercutsONOFF; SC parameters and Setps are: " << endl;
+	    for (Int_t z = 0; z < params.GetSize(); z++)
+	    {
+		cout << params[z] << setw(20) << steps[z] << endl;
+	    }
+	}
+
+	// ENDTMP
+
+	*/
+
+	/*
+	// TMP2
+
+	TArrayD paramsBis = super.GetParameters();
+	TArrayD stepsBis = super.GetStepsizes();
+	if (paramsBis.GetSize() == stepsBis.GetSize())
+	{
+	    *fLog << "MFindSupercutsONOFF; SC parametersBis and SetpsBis are: " << endl;
+	    for (Int_t z = 0; z < paramsBis.GetSize(); z++)
+	    {
+		cout << paramsBis[z] << setw(20) << stepsBis[z] << endl;
+	    }
+	}
+	
+	// ENDTMP2
+	*/
+
+	else
+	{
+	    *fLog << "MFindSupercutsONOFF; ERROR: params.GetSize() != steps.GetSize() " 
+		  << endl;
+	    
+	}
+
+
+
+    }
+    else
+    {
+        *fLog << "MFindSupercutsONOFF::FindParams; initial values and step sizes are taken from the MSupercuts constructor"
+              << endl;
+    }
+
+
+    // Computation of fNormFactorTrain and creation of a container for 
+    // storing this value and include it  in the MParList for being 
+    // used by function fcnSupercuts
+
+    if (!ComputeNormFactorTrain())
+    {
+	*fLog << "Normalization factor for train sample (ON-OFF) could not be computed. Aborting..." << endl;
+	return kFALSE;
+    }
+
+    
+    *fLog << "MFindSupercutsONOFF::FindParams; fNormFactorTrain = " << fNormFactorTrain << endl;
+
+    
+
+    MDataValue NormFactorCont(fNormFactorTrain);
+    NormFactorCont.SetName("NormFactorTrain");
+                                 
+
+    // Value of fAlphaSig, fAlphaBkgMin and fAlphaBkgMax 
+    // are stored in MDataValue containers,
+    // then they will be passed to the MParList and will be 
+    // accessible to fcnsupercuts
+
+    MDataValue AlphaSigCont(fAlphaSig);
+    AlphaSigCont.SetName("AlphaSigValue");
+
+    MDataValue AlphaBkgMinCont(fAlphaBkgMin);
+    AlphaBkgMinCont.SetName("AlphaBkgMinValue");
+
+    MDataValue AlphaBkgMaxCont(fAlphaBkgMax);
+    AlphaBkgMaxCont.SetName("AlphaBkgMaxValue");
+    
+
+    MDataValue DegreeONCont (fDegreeON);
+    DegreeONCont.SetName("DegreeON");
+
+    MDataValue DegreeOFFCont (fDegreeOFF);
+    DegreeOFFCont.SetName("DegreeOFF");
+
+
+
+
+    
+    // Value of fUseFittedQuantities is stored in container 
+    // and passed to the MParList and will be 
+    // accessible to fcnsupercuts
+
+    
+
+    MDataValue UseFittedQuantitiesCont(fUseFittedQuantities);
+    UseFittedQuantitiesCont.SetName("UseFittedQuantitiesValue");
+
+
+     // Value of fNormFactorFromAlphaBkg is stored in container 
+    // and passed to the MParList and will be 
+    // accessible to fcnsupercuts
+
+    MDataValue UseNormFactorFromAlphaBkgCont(fNormFactorFromAlphaBkg);
+    UseNormFactorFromAlphaBkgCont.SetName("UseNormFactorFromAlphaBkgValue");
+
+
+
+    // A vector of pointers to objects of the class MEvtLoop is defined.
+    // One of the pointed loops will be used to compute ON data alpha plot
+    // and the other for computing OFF data alpha plot.
+
+    MEvtLoop evtloopfcn[2] = {MEvtLoop("ONDataEvtLoopFCN"), 
+			      MEvtLoop("OFFDataEvtLoopFCN")};
+
+
+
+
+    // ******************************************************************
+    // EVENT LOOP FOR COMPUTING ALPHA HISTOGRAM FOR ON DATA IS SET
+    // ******************************************************************
+
+    // -----------------------------------------------------------------
+
+    MParList  parlistfcn;
+    MTaskList tasklistfcn;
+
+    // loop over rows of matrix
+    MMatrixLoop loop(fMatrixTrain);
+
+
+    //--------------------------------
+    // calculate supercuts hadronness
+    fCalcHadTrain->SetHadronnessName(fHadronnessName);
+
+    // Boolean variable that controls in class MSupercutsCalcONOFF
+    // wether the supercuts are stored or not
+    // is set to the default value, kFALSE. (no storage of supercuts)
+
+    fCalcHadTrain -> SetStoreAppliedSupercuts(kFALSE);
+
+
+    
+    // Set boolean variable that controls wether cuts are 
+    // dynamic or static
+
+    fCalcHadTrain -> SetVariableUseStaticCuts(fUseStaticCuts);
+
+    if (!fUseStaticCuts)
+    {
+	// Set boolean variable that controls wether the theta variable 
+	// is used or not in the computation of the dynamical cuts
+	
+	fCalcHadTrain -> SetVariableNotUseTheta(fNotUseTheta);
+    }
+
+    // apply the supercuts
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue supercuts(&scfilter);
+
+    // plot |alpha|
+    const TString  mh3Name = "AlphaFcn";
+    MBinning binsalpha("Binning"+mh3Name);
+    //binsalpha.SetEdges(54, -12.0, 96.0);
+    binsalpha.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+     
+     
+    *fLog << warn << "WARNING------------>ALPHA IS ASSUMED TO BE IN COLUMN 7!!!!!!!!" << endl;
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alpha("MatrixTrain[7]");
+    alpha.SetName(mh3Name);
+
+    MFillH fillalpha(&alpha);
+
+    // book histograms to be filled during the optimization
+    //                              ! not in the event loop !
+    MHCT1Supercuts plotsuper;
+    plotsuper.SetupFill(&parlistfcn);
+
+    //******************************
+    // entries in MParList (extension of old MParList)
+    
+    parlistfcn.AddToList(&tasklistfcn);
+    parlistfcn.AddToList(&super);
+    parlistfcn.AddToList(&NormFactorCont);
+    parlistfcn.AddToList(&AlphaSigCont);
+    parlistfcn.AddToList(&AlphaBkgMinCont);
+    parlistfcn.AddToList(&AlphaBkgMaxCont);
+    parlistfcn.AddToList(&DegreeONCont);
+    parlistfcn.AddToList(&UseFittedQuantitiesCont);
+    parlistfcn.AddToList(&UseNormFactorFromAlphaBkgCont);
+
+    parlistfcn.AddToList(fCam);
+    parlistfcn.AddToList(fMatrixTrain);
+
+    parlistfcn.AddToList(&binsalpha);
+    parlistfcn.AddToList(&alpha);
+
+    parlistfcn.AddToList(&plotsuper);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklistfcn.AddToList(&loop);
+    tasklistfcn.AddToList(fCalcHadTrain);
+    tasklistfcn.AddToList(&supercuts);
+    tasklistfcn.AddToList(&fillalpha);
+
+    //******************************
+
+
+    // &evtloopfcn[0] = new MEvtLoop("ONDataEvtLoopFCN");
+    evtloopfcn[0].SetParList(&parlistfcn);
+    // MEvtLoop evtloopfcn("EvtLoopFCN");
+    // evtloopfcn.SetParList(&parlistfcn);
+    *fLog << "Event loop for computing ON data alpha histo in fcnSupercuts has been setup" << endl;
+
+
+//---- End of setting of loop for compuing ON data alpha plot ---------------
+
+    
+
+     // ******************************************************************
+    // EVENT LOOP FOR COMPUTING ALPHA HISTOGRAM FOR OFF DATA IS SET
+    // ******************************************************************
+
+    // -----------------------------------------------------------------
+
+    MParList  parlistfcnOFF;
+    MTaskList tasklistfcnOFF;
+
+    // loop over rows of matrix
+    MMatrixLoop loopOFF(fMatrixTrainOFF);
+
+
+    //--------------------------------
+    // calculate supercuts hadronness
+    fCalcHadTrainOFF->SetHadronnessName(fHadronnessNameOFF);
+
+
+    // Boolean variable that controls in class MSupercutsCalcONOFF
+    // wether the supercuts are stored or not
+    // is set to the default value, kFALSE. (no storage of supercuts)
+
+    fCalcHadTrainOFF -> SetStoreAppliedSupercuts(kFALSE);
+
+
+    
+    // Set boolean variable that controls wether cuts are 
+    // dynamic or static
+
+    fCalcHadTrainOFF -> SetVariableUseStaticCuts(fUseStaticCuts);
+
+
+    if (!fUseStaticCuts)
+    {
+	// Set boolean variable that controls wether the theta variable 
+	// is used or not in the computation of the dynamica cuts
+	
+	fCalcHadTrainOFF -> SetVariableNotUseTheta(fNotUseTheta);
+    }
+
+    // apply the supercuts
+    MF scfilterOFF(fHadronnessNameOFF+".fHadronness>0.5");
+    MContinue supercutsOFF(&scfilterOFF);
+
+    // plot |alpha|
+    const TString  mh3NameOFF = "AlphaOFFFcn";
+    MBinning binsalphaOFF("Binning"+mh3NameOFF);
+    //binsalphaOFF.SetEdges(54, -12.0, 96.0);
+    binsalphaOFF.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+
+
+    *fLog << warn << "WARNING------------>ALPHA IS ASSUMED TO BE IN COLUMN 7!!!!!!!!" << endl;
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alphaOFF("MatrixTrainOFF[7]");
+    alphaOFF.SetName(mh3NameOFF);
+
+    MFillH fillalphaOFF(&alphaOFF);
+
+    
+
+    //******************************
+    // entries in MParList (extension of old MParList)
+    
+    parlistfcnOFF.AddToList(&tasklistfcnOFF);
+    parlistfcnOFF.AddToList(&super);
+    parlistfcnOFF.AddToList(fCam);
+    parlistfcnOFF.AddToList(fMatrixTrainOFF);
+
+    parlistfcnOFF.AddToList(&binsalphaOFF);
+    parlistfcnOFF.AddToList(&alphaOFF);
+
+    parlistfcnOFF.AddToList(&DegreeOFFCont);
+    
+
+    //******************************
+    // entries in MTaskList
+
+    tasklistfcnOFF.AddToList(&loopOFF);
+    tasklistfcnOFF.AddToList(fCalcHadTrainOFF);
+    tasklistfcnOFF.AddToList(&supercutsOFF);
+    tasklistfcnOFF.AddToList(&fillalphaOFF);
+
+    //******************************
+
+
+    // &evtloopfcn[1] = new MEvtLoop("OFFDataEvtLoopFCN");
+    evtloopfcn[1].SetParList(&parlistfcnOFF);
+    // MEvtLoop evtloopfcn("EvtLoopFCN");
+    // evtloopfcn.SetParList(&parlistfcn);
+    *fLog << "Event loop for computing OFF data alpha histo in fcnSupercuts has been setup" << endl;
+
+
+//---- End of setting of loop for compuing OFF data alpha plot ---------------
+
+
+    // address of evtloopfcn is used in CallMinuit()
+
+
+    //-----------------------------------------------------------------------
+    //
+    //----------   Start of minimization part   --------------------
+    //
+    // Do the minimization with MINUIT
+    //
+    // Be careful: This is not thread safe
+    //
+    *fLog << "========================================================" << endl;
+    *fLog << "Start minimization for supercuts" << endl;
+
+
+    // -------------------------------------------
+    // prepare call to MINUIT
+    //
+
+    // get initial values of parameters 
+    fVinit = super.GetParameters();
+    fStep  = super.GetStepsizes();
+
+    TString name[fVinit.GetSize()];
+    fStep.Set(fVinit.GetSize());
+    fLimlo.Set(fVinit.GetSize());
+    fLimup.Set(fVinit.GetSize());
+    fFix.Set(fVinit.GetSize());
+
+    fNpar = fVinit.GetSize();
+
+    for (UInt_t i=0; i<fNpar; i++)
+    {
+        name[i]   = "p";
+        name[i]  += i+1;
+        //fStep[i]  = TMath::Abs(fVinit[i]/10.0);
+        fLimlo[i] = -100.0;
+        fLimup[i] =  100.0;
+        fFix[i]   =     0;
+    }
+
+
+    
+
+
+    if(fSetLimitsToSomeMinuitParams)
+      {
+
+	// Limits for some Minuit parameters are set. For the time being the values are set in the constructor 
+	// of the class. One MUST be very careful to set limits such that the expected final values 
+	// (optimized values) are far away from the limits.
+	// Limits are set to those Minuit parameters not depending in Size,dist and theta (static values). 
+	// Limits are set only to Dist, Length and Width.
+
+	
+	*fLog << endl 
+	      <<"Limits set to hillas parameters Length, Width, Dist and Leakage1 for the optimization with Minuit." 
+	      << endl;
+	
+
+	
+	fLimup[0] = fMinuitLengthUPUpperLimit;
+	fLimlo[0] = fMinuitLengthUPLowerLimit;
+	fLimup[8] = fMinuitLengthLOWUpperLimit;
+	fLimlo[8] = fMinuitLengthLOWLowerLimit;
+	fLimup[16] = fMinuitWidthUPUpperLimit;
+	fLimlo[16] = fMinuitWidthUPLowerLimit;
+	fLimup[24] = fMinuitWidthLOWUpperLimit;
+	fLimlo[24] = fMinuitWidthLOWLowerLimit;
+	fLimup[32] = fMinuitDistUPUpperLimit;
+	fLimlo[32] = fMinuitDistUPLowerLimit;
+	fLimup[40] = fMinuitDistLOWUpperLimit;
+	fLimlo[40] = fMinuitDistLOWLowerLimit;
+
+	fLimup[80] = fMinuitLeakage1UPUpperLimit;
+	fLimlo[80] = fMinuitLeakage1UPLowerLimit;
+
+	
+
+      }
+    
+   
+
+    // Wolfgang sets manyally some parameters.
+    // That might give an error if parameters are changed...
+    // To be changed in future...
+
+    // these parameters make no sense, fix them at 0.0
+    fVinit[33] = 0.0;
+    fStep[33]  = 0.0;
+    fFix[33]   = 1;
+
+    fVinit[36] = 0.0;
+    fStep[36]  = 0.0;
+    fFix[36]   = 1;
+
+    fVinit[39] = 0.0;
+    fStep[39]  = 0.0;
+    fFix[39]   = 1;
+
+    fVinit[41] = 0.0;
+    fStep[41]  = 0.0;
+    fFix[41]   = 1;
+
+    fVinit[44] = 0.0;
+    fStep[44]  = 0.0;
+    fFix[44]   = 1;
+
+    fVinit[47] = 0.0;
+    fStep[47]  = 0.0;
+    fFix[47]   = 1;
+
+
+   
+    // ADDITIONAL PARAMETERS ARE FIXED ACCORDING TO THE 
+    // VALUES OF THE BOOLEAN VARIABLES fUseStaticCuts, AND
+    // fNotUseTheta
+
+
+    if (fUseStaticCuts)
+    {    
+        // Static cuts will be used; all parameters with index 
+	// 1-7 are fixed for ALL variables (width, length, ...)
+	
+       for (UInt_t i=0; i<fNpar; i = i+8)
+       {
+	   // At some point, the number of paraemters in the 
+	   // dynamical cuts parameterezattion (currently 7) 
+           // will become a variable that can be set from 
+	   // outside the class
+
+	   for (UInt_t j=i+1; j<=i+7; j++)
+	   {
+	       fVinit[j] = 0.0;
+	       fStep[j]  = 0.0;
+	       fFix[j]   = 1;
+	   }
+       }
+    }
+    else
+    {
+	if(fNotUseTheta)
+	{
+	    // Theta is not used in the parameterization of the dynamical cut
+	    // Parameters with index 2 and 5 are fixed for all variables 
+	    // (width, length, ...)
+
+	    for (UInt_t i=0; i<fNpar; i = i+8)
+	    {
+		// At some point, the number of paraemters in the 
+		// dynamical cuts parameterezattion (currently 7) 
+		// will become a variable that can be set from 
+		// outside the class
+		
+		for (UInt_t j=i+2; j<=i+7; j = j+3)
+		{
+		    fVinit[j] = 0.0;
+		    fStep[j]  = 0.0;
+		    fFix[j]   = 1;
+		}
+	    }
+
+
+	}
+
+	if(!fUseDist)
+	  {
+	    // parameterization using dist is removed
+	    // Parameters with index 1 and 4 and 7 are fixed for all variables 
+	    // (width, length, ...)
+	     for (UInt_t i=0; i<fNpar; i = i+8)
+	    {
+		// At some point, the number of paraemters in the 
+		// dynamical cuts parameterezattion (currently 7) 
+		// will become a variable that can be set from 
+		// outside the class
+		
+		for (UInt_t j=i+1; j<=i+7; j = j+3)
+		{
+		    fVinit[j] = 0.0;
+		    fStep[j]  = 0.0;
+		    fFix[j]   = 1;
+		}
+	    }
+
+
+
+	  }
+
+
+
+
+    }
+
+
+
+
+
+
+    // vary only first 48 parameters
+    //for (UInt_t i=0; i<fNpar; i++)
+    //{
+    //    if (i >= 48)
+    //	{
+    //      fStep[i] = 0.0;
+    //      fFix[i]  =   1;
+    //	}
+    //}
+ 
+    // -------------------------------------------
+    // call MINUIT
+    
+    Bool_t rc;
+
+    if(fSkipOptimization)
+    {
+	*fLog << "Parameter optimization is skipped. Using previously optimized parameters."
+	      << endl;
+	
+
+	rc = kTRUE;
+	
+
+	if(fUseInitialSCParams)
+	{
+
+	    // write Initial parameter values onto root file filenameParam
+	    // so that later they can be applied on the data
+
+	     *fLog << "Initial SC parameter values are written onto file '"
+		  << fFilenameParam << "' :" << endl;
+
+	    
+	    TFile outparam(fFilenameParam, "RECREATE"); 
+	    super.Write();
+	    outparam.Close();
+	    
+
+	    
+	     const TArrayD &check = super.GetParameters();
+	    for (Int_t i=0; i<check.GetSize(); i++)
+		*fLog << check[i] << ",  ";
+	    *fLog << endl;
+
+	
+	}
+
+
+    }
+    else
+    {
+	TStopwatch clock;
+	clock.Start();
+	
+	*fLog << "before calling CallMinuit" << endl;
+    
+	MMinuitInterface inter;               
+	rc = inter.CallMinuit(fcnSupercuts, name,
+			      fVinit, fStep, fLimlo, fLimup, fFix,
+			      evtloopfcn, "SIMPLEX", kFALSE);
+	
+	*fLog << "after calling CallMinuit" << endl;
+	
+	*fLog << "Time spent for the minimization in MINUIT :   " << endl;;
+	clock.Stop();
+	clock.Print();
+
+	// plotsuper.DrawClone();
+
+	if (!rc)
+	{
+	    *fLog << "*************  ERROR !!! *********************" << endl
+		  << "Minimization could not finish properly..." << endl
+		  << "MMinuitInterface.CallMinuit() returned kFALSE" << endl;
+	    return kFALSE;
+	}
+	
+	
+	
+	
+	*fLog << "Minimization for supercuts finished" << endl;
+	*fLog << "========================================================" << endl;
+	
+	
+	// -----------------------------------------------------------------
+	// in 'fcnSupercuts' (IFLAG=3) the optimum parameter values were put 
+	//                    into MSupercuts
+	
+	// write optimum parameter values onto file filenameParam
+	
+	TFile outparam(fFilenameParam, "RECREATE"); 
+	super.Write();
+	outparam.Close();
+	
+	*fLog << "Optimum parameter values for supercuts were written onto file '"
+	      << fFilenameParam << "' :" << endl;
+    
+	const TArrayD &check = super.GetParameters();
+	for (Int_t i=0; i<check.GetSize(); i++)
+	    *fLog << check[i] << ",  ";
+	*fLog << endl;
+	
+	
+	
+	
+    }
+    
+	
+    
+    
+    
+    *fLog << "End of  supercuts optimization part" << endl;
+    *fLog << "======================================================" << endl;
+    
+    
+    *fLog << "Applying the optimized supercuts on the TRAIN sample and " 
+	  << "producing plots related to the output results" << endl;
+
+    *fLog << "======================================================" << endl;
+    
+    if (!TestParamsOnTrainSample())
+    {
+	*fLog << "MFindSupercutsONOFF::FindParams;" 
+	      << "TestParamsOnTrainSample failed"
+	      << endl;
+	
+	return kFALSE;
+    }
+    
+    
+    
+    return kTRUE;
+}
+
+
+
+
+
+
+
+// -----------------------------------------------------------------------
+//
+// Test the supercuts on the test sample using ON and OFF data
+// 2 loops are used to fill the 2 alpha distributions
+// Supercuts applied (LengthUp, LengthLow...) 
+// to all the individual events, as well as 
+// the features of the shower images (Length,Width...) are 
+// stored in 2 TTree objects (for ON and OFF data) in the 
+// root file specified by variable "fAlphaDistributionsRootFilename"
+
+
+
+Bool_t MFindSupercutsONOFF::TestParamsOnTestSample()
+{
+    if (fMatrixTest->GetM().GetNrows() <= 0)
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsOnTestSample; test matrix ON has no entries" 
+              << endl;
+        return kFALSE;
+    }
+
+
+    if (fMatrixTestOFF->GetM().GetNrows() <= 0)
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsOnTestSample; test matrix OFF has no entries" 
+              << endl;
+        return kFALSE;
+    }
+
+    // -------------   TEST the supercuts    ------------------------------
+    //
+    *fLog << "Test the supercuts on the test sample ON and OFF" << endl;
+
+    // -----------------------------------------------------------------
+    // read optimum parameter values from file filenameParam
+    // into array 'supercutsPar'
+
+    TFile inparam(fFilenameParam);
+    MSupercuts scin; 
+    scin.Read("MSupercuts");
+    inparam.Close();
+
+    *fLog << "Optimum parameter values for supercuts were read from file '";
+    *fLog << fFilenameParam << "' :" << endl;
+
+    const TArrayD &supercutsPar = scin.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+        *fLog << supercutsPar[i] << ",  ";
+    *fLog << endl;
+    //---------------------------
+
+
+    // -----------------------------------------------------------------
+    if (fHadronnessName.IsNull())
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsONOFF; hadronness name for ON data is not defined... aborting";
+        *fLog << endl;
+        return kFALSE;
+    }
+
+    if (fHadronnessNameOFF.IsNull())
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsONOFF; hadronness name for OFF data is not defined... aborting";
+        *fLog << endl;
+        return kFALSE;
+    }
+
+    if(fTestONSupercutsAppliedName.IsNull())
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsONOFF; " 
+	      << " MTSupercutsApplied tree name for ON Test data is not defined... aborting"
+	      << endl;
+        return kFALSE;
+    }
+
+    if(fTestOFFSupercutsAppliedName.IsNull())
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsONOFF; " 
+	      << " MTSupercutsApplied container name for OFF Test data is not defined... aborting"
+	      << endl;
+        return kFALSE;
+    }
+    
+
+    MSupercuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+
+    // Objects containing the trees used to store supercuts applied
+    // TTree Branches are also created
+    MTSupercutsApplied supapptestON(fTestONSupercutsAppliedName.Data(), "");
+    supapptestON.CreateTreeBranches();
+
+    MTSupercutsApplied supapptestOFF(fTestOFFSupercutsAppliedName.Data(), "");
+    supapptestOFF.CreateTreeBranches();
+
+    
+
+    
+    fCalcHadTestOFF -> SetHadronnessName(fHadronnessNameOFF);
+    fCalcHadTest -> SetHadronnessName(fHadronnessName);
+
+
+    // Settings related to the storage of teh supercuts applied 
+    fCalcHadTest -> SetSupercutsAppliedName(fTestONSupercutsAppliedName);
+    fCalcHadTest -> SetStoreAppliedSupercuts(kTRUE);
+
+    fCalcHadTestOFF -> SetSupercutsAppliedName(fTestOFFSupercutsAppliedName);
+    fCalcHadTestOFF -> SetStoreAppliedSupercuts(kTRUE);
+    
+
+
+    // Set boolean variable that controls wether cuts are 
+    // dynamic or static
+
+    fCalcHadTest -> SetVariableUseStaticCuts(fUseStaticCuts);
+    fCalcHadTestOFF -> SetVariableUseStaticCuts(fUseStaticCuts);
+
+    if (!fUseStaticCuts)
+    {
+	// Set boolean variable that controls wether the theta variable 
+	// is used or not in the computation of the dynamical cuts
+	
+	fCalcHadTest -> SetVariableNotUseTheta(fNotUseTheta);
+	fCalcHadTestOFF -> SetVariableNotUseTheta(fNotUseTheta);
+    }
+
+
+     // apply the supercuts to OFF data
+
+    MF scfilterOFF(fHadronnessNameOFF+".fHadronness>0.5");
+    MContinue applysupercutsOFF(&scfilterOFF);
+
+
+     // apply the supercuts to ON data
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue applysupercuts(&scfilter);
+
+   
+
+    // ****************************************************
+    // Filling OFF alpha distribution 
+
+    MParList parlistOFF;
+    MTaskList tasklistOFF;
+
+    MMatrixLoop loopOFF(fMatrixTestOFF);
+
+    // plot alpha before applying the supercuts
+    const TString  mh3NameOFFB = "AlphaOFFBefore";
+    MBinning binsalphaOFFbef("Binning"+mh3NameOFFB);
+    // binsalphaOFFbef.SetEdges(54, -12.0, 96.0);
+    binsalphaOFFbef.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alphaOFFbefore("MatrixTestOFF[7]");
+    alphaOFFbefore.SetName(mh3NameOFFB);
+
+
+    MFillH fillalphaOFFbefore(&alphaOFFbefore);
+    fillalphaOFFbefore.SetName("FillAlphaOFFBefore");
+
+   
+
+    // plot alpha OFF after applying the supercuts
+    const TString  mh3NameOFFA = "AlphaOFFAfter";
+    MBinning binsalphaOFFaft("Binning"+mh3NameOFFA);
+    // binsalphaOFFaft.SetEdges(54, -12.0, 96.0);
+    binsalphaOFFaft.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+    
+    MH3 alphaOFFafter("MatrixTestOFF[7]");
+    alphaOFFafter.SetName(mh3NameOFFA);
+
+
+    MFillH fillalphaOFFafter(&alphaOFFafter);
+    fillalphaOFFafter.SetName("FillAlphaOFFAfter");
+
+    //******************************
+    // entries in MParList
+
+    parlistOFF.AddToList(&tasklistOFF);
+
+    parlistOFF.AddToList(&supercuts);
+
+    parlistOFF.AddToList(&supapptestOFF);
+
+    parlistOFF.AddToList(fCam);
+    parlistOFF.AddToList(fMatrixTestOFF);
+
+    parlistOFF.AddToList(&binsalphaOFFbef);
+    parlistOFF.AddToList(&alphaOFFbefore);
+
+    parlistOFF.AddToList(&binsalphaOFFaft);
+    parlistOFF.AddToList(&alphaOFFafter);
+
+
+    //******************************
+    // Entries in MtaskList
+    tasklistOFF.AddToList(&loopOFF);
+    tasklistOFF.AddToList(&fillalphaOFFbefore);
+
+    tasklistOFF.AddToList(fCalcHadTestOFF);
+    tasklistOFF.AddToList(&applysupercutsOFF);
+
+    tasklistOFF.AddToList(&fillalphaOFFafter);
+
+    //******************************
+
+    MProgressBar barOFF;
+    MEvtLoop evtloopOFF;
+    evtloopOFF.SetParList(&parlistOFF);
+    evtloopOFF.SetName("EvtLoopTestParamsOFF");
+    evtloopOFF.SetProgressBar(&barOFF);
+    Int_t maxeventsOFF = -1;
+    if (!evtloopOFF.Eventloop(maxeventsOFF))
+        return kFALSE;
+
+    tasklistOFF.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // draw the alpha plots
+
+    MH3* alphaOFFBefore = (MH3*)parlistOFF.FindObject(mh3NameOFFB, "MH3");
+    TH1  &alphaOFFHistb = alphaOFFBefore->GetHist();
+    TString alphaOFFHistbName ("TestAlphaOFFBeforeCuts");
+    
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTestSample; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+	alphaOFFHistbName += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	alphaOFFHistbName += (fThetaRangeString);
+    }
+
+
+    alphaOFFHistb.SetXTitle("|\\alpha|  [\\circ]");
+    alphaOFFHistb.SetName(alphaOFFHistbName);
+
+
+    MH3* alphaOFFAfter = (MH3*)parlistOFF.FindObject(mh3NameOFFA, "MH3");
+    TH1  &alphaOFFHista = alphaOFFAfter->GetHist();
+    TString alphaOFFHistaName ("TestAlphaOFFAfterCuts");
+
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTestSample; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+	alphaOFFHistaName += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	alphaOFFHistaName += (fThetaRangeString);
+    }
+
+
+    alphaOFFHista.SetXTitle("|\\alpha|  [\\circ]");
+    alphaOFFHista.SetName(alphaOFFHistaName);
+
+    
+
+
+
+    // *****************************************************
+
+
+
+    //-------------------------------------------
+
+
+    MParList  parlist2;
+    MTaskList tasklist2;
+
+    MMatrixLoop loop(fMatrixTest);
+
+    // plot alpha before applying the supercuts
+    const TString  mh3NameB = "AlphaBefore";
+    MBinning binsalphabef("Binning"+mh3NameB);
+    //binsalphabef.SetEdges(54, -12.0, 96.0);
+    binsalphabef.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+    
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alphabefore("MatrixTest[7]");
+    alphabefore.SetName(mh3NameB);
+
+
+    MFillH fillalphabefore(&alphabefore);
+    fillalphabefore.SetName("FillAlphaBefore");
+
+
+    // plot alpha after applying the supercuts
+    const TString  mh3NameA = "AlphaAfter";
+    MBinning binsalphaaft("Binning"+mh3NameA);
+    // binsalphaaft.SetEdges(54, -12.0, 96.0);
+    binsalphaaft.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+
+    MH3 alphaafter("MatrixTest[7]");
+    alphaafter.SetName(mh3NameA);
+
+
+    MFillH fillalphaafter(&alphaafter);
+    fillalphaafter.SetName("FillAlphaAfter");
+
+    //******************************
+    // entries in MParList
+
+    parlist2.AddToList(&tasklist2);
+
+    parlist2.AddToList(&supercuts);
+
+    parlist2.AddToList(&supapptestON);
+
+    parlist2.AddToList(fCam);
+    parlist2.AddToList(fMatrixTest);
+
+    parlist2.AddToList(&binsalphabef);
+    parlist2.AddToList(&alphabefore);
+
+    parlist2.AddToList(&binsalphaaft);
+    parlist2.AddToList(&alphaafter);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklist2.AddToList(&loop);
+    tasklist2.AddToList(&fillalphabefore);
+
+    tasklist2.AddToList(fCalcHadTest);
+    tasklist2.AddToList(&applysupercuts);
+
+    tasklist2.AddToList(&fillalphaafter);
+
+    //******************************
+
+    MProgressBar bar2;
+    MEvtLoop evtloop2;
+    evtloop2.SetParList(&parlist2);
+    evtloop2.SetName("EvtLoopTestParams");
+    evtloop2.SetProgressBar(&bar2);
+    Int_t maxevents2 = -1;
+    if (!evtloop2.Eventloop(maxevents2))
+        return kFALSE;
+
+    tasklist2.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // draw the alpha plots
+
+    MH3* alphaBefore = (MH3*)parlist2.FindObject(mh3NameB, "MH3");
+    TH1  &alphaHist1 = alphaBefore->GetHist();
+    TString alphaHist1Name ("TestAlphaBeforeCuts");
+    
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTestSample; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+	alphaHist1Name += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	alphaHist1Name += (fThetaRangeString);
+    }
+
+
+
+
+    alphaHist1.SetName(alphaHist1Name);
+    alphaHist1.SetXTitle("|\\alpha|  [\\circ]");
+    
+
+
+    MH3* alphaAfter = (MH3*)parlist2.FindObject(mh3NameA, "MH3");
+    TH1  &alphaHist2 = alphaAfter->GetHist();
+    TString alphaHist2Name ("TestAlphaAfterCuts");
+    
+    
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTestSample; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+	alphaHist2Name += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	alphaHist2Name += (fThetaRangeString);
+    }
+
+    alphaHist2.SetXTitle("|\\alpha|  [\\circ]");
+    alphaHist2.SetName(alphaHist2Name);
+
+
+       
+    //fPsFilename  -> NewPage();
+
+
+    // Canvas is deleted after saving the plot in ps file
+    // This is to allow for GRID analysis
+
+    TCanvas *c = new TCanvas("TestAlphaBeforeAfterSC", 
+			     "TestAlphaBeforeAfterSC", 
+			     600, 600);
+    c->Divide(2,2);
+    
+    
+
+    c->cd(1);
+    alphaOFFHistb.DrawCopy();
+
+    c->cd(2);
+    alphaOFFHista.DrawCopy();
+    
+  
+
+    c->cd(3);
+    alphaHist1.DrawCopy();
+
+    c->cd(4);
+    alphaHist2.DrawCopy();
+
+    c->Modified();
+    c-> Update();
+
+
+    // ********************************************
+    // TMP solutions while the TPostScript thing is not working 
+    // PsFileName for storing these plots is derived 
+    // from PsFilenameString. 
+    
+
+    cout << "Alpha distributions will be saved in PostScript file  " ;
+
+
+    if (!fPsFilenameString.IsNull())
+    {
+	TString filename = (fPsFilenameString);
+	filename += ("AlphaTESTSampleONOFFBeforeAfterCuts.ps");
+	cout << filename << endl;	
+	c -> SaveAs(filename);
+    }
+
+    // END OF TEMPORAL SOLUTION
+    // ********************************************
+    
+    
+    // Canvas is deleted after saving the plot in ps file
+    // This is to allow for GRID analysis
+    delete c;
+
+    //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    const Double_t alphasig = fAlphaSig;
+    const Double_t alphamin = fAlphaBkgMin; 
+   // alpha min for bkg region in ON data
+    
+    const Double_t alphamax = fAlphaBkgMax;
+//    const Int_t    degree   =    2;
+//    const Int_t    degreeOFF   =    2;
+    const Bool_t   drawpoly  = kTRUE;
+    const Bool_t   fitgauss  = kTRUE;
+    const Bool_t   print     = kTRUE;
+    
+    const Bool_t saveplots   = kTRUE; // Save plots in Psfile
+   
+     
+
+    if (!ComputeNormFactorTest())
+    {
+	*fLog << "Normalization factor for test sample (ON-OFF) couold not be computed. Aborting..." << endl;
+	return kFALSE;
+    }
+
+
+
+     // Normalization factor factor is corrected using the estimated 
+    // number of excess events and the total number of ON events
+
+
+ 
+    if (fTuneNormFactor)
+    {
+
+
+	// Run MHFindSignificanceONOFF::FindSigmaONOFF
+	// to get estimation of number of excess gamma events. 
+	// This number will be used in the correction of the 
+	// normalization factor 
+	
+	// No plots will be produced this time...
+
+	const Bool_t   drawpolyTest  = kFALSE;
+	const Bool_t   fitgaussTest  = kFALSE;
+	const Bool_t   printTest     = kFALSE;
+	
+	const Bool_t saveplotsTest   = kFALSE; // Save plots in Psfile
+	
+	// TPostScript* DummyPs  = new TPostScript("dummy.ps");
+
+	TString DummyPs = ("Dummy");
+
+	MHFindSignificanceONOFF findsigTest;
+	findsigTest.SetRebin(kTRUE);
+	findsigTest.SetReduceDegree(kFALSE);
+	findsigTest.SetUseFittedQuantities(fUseFittedQuantities);
+	
+
+	if (findsigTest.FindSigmaONOFF(&alphaHist2, &alphaOFFHista, 
+				       fNormFactorTest, 
+        			       alphamin, alphamax, 
+				       fDegreeON, fDegreeOFF,
+				       alphasig, drawpolyTest, 
+				       fitgaussTest, printTest, 
+				       saveplotsTest, DummyPs))
+	{
+	    
+	    // Update values of Nex and SigmaLiMa for Test sammple
+	
+	    fSigmaLiMaTest = double(findsigTest.GetSignificance());
+
+	    if(fUseFittedQuantities)
+	    {
+		fNexTest = double(findsigTest.GetNexONOFFFitted());
+	    }
+	    else
+	    {
+		fNexTest = double(findsigTest.GetNexONOFF());
+	    }
+
+
+	}
+	else
+	{
+
+	    *fLog << "Normalization Factor tuning for Train sample is not possible"
+		  << endl;
+	    fSigmaLiMaTest = 0.0;
+	    fNexTest = 0.0;
+	}
+    
+
+//	DummyPs -> Close();
+	//DummyPs = NULL;
+	//      delete DummyPs;
+
+	
+   
+	
+	
+	Int_t EventsInTestMatrixOFF = fMatrixTestOFF->GetM().GetNrows();
+	Double_t Ngammas = fNexTest/fGammaEfficiency;
+	Double_t GammaFraction = Ngammas/EventsInTestMatrixOFF;
+	
+	
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTestSample; "
+	      << "fNormFactorTest is corrected with fraction of gammas in ON "
+	      << "Data Test sample and the number of OFF events before cuts." 
+	      << endl
+	      << "EventsInTestMatrixOFF = " << EventsInTestMatrixOFF
+	      << " Excess events in Test ON sample = " << fNexTest
+	      << " fGammaEfficiency = " << fGammaEfficiency << endl
+	      << "fNormFactorTest Value before correction is " 
+	      << fNormFactorTest << endl;
+	
+	fNormFactorTest = fNormFactorTest - GammaFraction;
+
+	*fLog << "fNormFactorTest Value after correction is "
+	      << fNormFactorTest << endl;
+	    
+
+    }
+    
+
+    
+   
+    if (fNormFactorFromAlphaBkg)
+    {
+	// Normalization factor computed using alpha bkg region
+	Double_t NewNormFactor = 
+	    ComputeNormFactorFromAlphaBkg(&alphaHist2, &alphaOFFHista, 
+					  fAlphaBkgMin, fAlphaBkgMax);
+	
+	*fLog << "Normalization factor computed from alpha plot (after cuts) " << endl
+	      << "using counted number of ON and OFF events in alpha region " << endl
+	      << "defined by range " << fAlphaBkgMin << "-" << fAlphaBkgMax << endl
+	      << "Normalization factor = " << NewNormFactor << endl;
+
+	*fLog << "Normalization factor used is the one computed in bkg region; " << endl
+	      << "i.e. " << NewNormFactor << " instead of " << fNormFactorTest << endl;
+
+	fNormFactorTest = NewNormFactor;
+
+
+    }
+
+
+
+    // Significance is found using MHFindSignificanceONOFF::FindSigmaONOFF
+
+
+    MHFindSignificanceONOFF findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+    findsig.SetUseFittedQuantities(fUseFittedQuantities);
+
+    TString psfilename; // Name of psfile where Alpha plot will be stored
+    if (!fPsFilenameString.IsNull())
+    {
+	psfilename += (fPsFilenameString);
+	psfilename += ("TESTSample"); 
+    }
+    else
+    {
+	psfilename += ("TESTSample");
+    }
+
+
+    findsig.FindSigmaONOFF(&alphaHist2, &alphaOFFHista, 
+			   fNormFactorTest, 
+			   alphamin, alphamax, 
+			   fDegreeON, fDegreeOFF,
+			   alphasig, drawpoly, fitgauss, print, 
+			   saveplots, psfilename);
+    
+    const Double_t significance = findsig.GetSignificance();
+    const Double_t alphasi = findsig.GetAlphasi();
+
+
+    // Update values of Nex and SigmaLiMa for Test sammple
+
+    fSigmaLiMaTest = double(findsig.GetSignificance());
+
+    if(fUseFittedQuantities)
+    {
+	fNexTest = double(findsig.GetNexONOFFFitted());
+    }
+    else
+    {
+	fNexTest = double(findsig.GetNexONOFF());
+    }
+
+
+    // Alpha distributions and containers with teh supercuts applied 
+    // are written into root file 
+
+    TFile rootfile(fAlphaDistributionsRootFilename, "UPDATE",
+		   "Alpha Distributions for several Theta bins");
+
+    alphaHist2.Write();
+    alphaOFFHista.Write();
+    
+    (supapptestON.GetTreePointer())->Write();
+    (supapptestOFF.GetTreePointer())->Write();
+
+    *fLog  << "TTree objects containing supercuts applied to TEST sample are "
+	   << "written into root file " << fAlphaDistributionsRootFilename << endl; 
+ 
+    (supapptestON.GetTreePointer())->Print();
+    (supapptestOFF.GetTreePointer())->Print();
+
+    //rootfile.Close();
+    
+
+    // Boolean variable that controls in class MSupercutsCalcONOFF
+    // wether the supercuts are stored or not
+    // is set to the default value, kFALSE.
+
+    fCalcHadTest -> SetStoreAppliedSupercuts(kFALSE);
+    fCalcHadTestOFF -> SetStoreAppliedSupercuts(kFALSE);
+
+
+
+    *fLog << "Significance of gamma signal after supercuts in Test sample : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+    //-------------------------------------------
+
+
+    *fLog << "Test of supercuts on TEST sample finished" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
+
+
+
+
+// Function that applies the optimized supercuts on the TEST sample.
+
+// Supercuts applied (LengthUp, LengthLow...) 
+// to all the individual events, as well as 
+// the features of the shower images (Length,Width...) are 
+// stored in 2 TTree objects (for ON and OFF data) in the 
+// root file specified by variable "fAlphaDistributionsRootFilename"
+
+
+Bool_t MFindSupercutsONOFF::TestParamsOnTrainSample()
+{
+    if (fMatrixTrain->GetM().GetNrows() <= 0)
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; train matrix ON has no entries" 
+              << endl;
+        return kFALSE;
+    }
+
+
+    if (fMatrixTrainOFF->GetM().GetNrows() <= 0)
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; train matrix OFF has no entries" 
+              << endl;
+        return kFALSE;
+    }
+
+    // -------------   TEST the supercuts on TRAIN sample  --------------------------
+    //
+    *fLog << "Producing output of the SUPERCUTS ON-OFF optimization " << endl;
+
+    // -----------------------------------------------------------------
+    // read optimum parameter values from file filenameParam
+    // into array 'supercutsPar'
+
+    TFile inparam(fFilenameParam);
+    MSupercuts scin; 
+    scin.Read("MSupercuts");
+    inparam.Close();
+
+    *fLog << "Optimum parameter values for supercuts were read from file '";
+    *fLog << fFilenameParam << "' :" << endl;
+
+    const TArrayD &supercutsPar = scin.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+        *fLog << supercutsPar[i] << ",  ";
+    *fLog << endl;
+    //---------------------------
+
+
+    // -----------------------------------------------------------------
+    if (fHadronnessName.IsNull())
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; hadronness name for ON data is not defined... aborting";
+        *fLog << endl;
+        return kFALSE;
+    }
+
+    if (fHadronnessNameOFF.IsNull())
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; hadronness name for OFF data is not defined... aborting";
+        *fLog << endl;
+        return kFALSE;
+    }
+
+
+    if(fTrainONSupercutsAppliedName.IsNull())
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; " 
+	      << " MTSupercutsApplied Tree name for ON Train data is not defined... aborting"
+	      << endl;
+        return kFALSE;
+    }
+
+    if(fTrainOFFSupercutsAppliedName.IsNull())
+    {
+        *fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; " 
+	      << " MTSupercutsApplied Tree name for OFF Train data is not defined... aborting"
+	      << endl;
+        return kFALSE;
+    }
+    
+   
+    MSupercuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+
+    // Objects containing the trees used to store supercuts applied
+    // TTree Branches are also created
+    MTSupercutsApplied supapptrainON(fTrainONSupercutsAppliedName,"");
+    supapptrainON.CreateTreeBranches();
+
+    MTSupercutsApplied supapptrainOFF(fTrainOFFSupercutsAppliedName,"");
+    supapptrainOFF.CreateTreeBranches();
+
+    fCalcHadTrainOFF -> SetHadronnessName(fHadronnessNameOFF);
+    fCalcHadTrain -> SetHadronnessName(fHadronnessName);
+
+
+    // Settings related to the storage of teh supercuts applied 
+    fCalcHadTrain -> SetSupercutsAppliedName(fTrainONSupercutsAppliedName);
+    fCalcHadTrain -> SetStoreAppliedSupercuts(kTRUE);
+
+    fCalcHadTrainOFF -> SetSupercutsAppliedName(fTrainOFFSupercutsAppliedName);
+    fCalcHadTrainOFF -> SetStoreAppliedSupercuts(kTRUE);
+    
+
+    // Set boolean variable that controls wether cuts are 
+    // dynamic or static
+
+    fCalcHadTrain -> SetVariableUseStaticCuts(fUseStaticCuts);
+    fCalcHadTrainOFF -> SetVariableUseStaticCuts(fUseStaticCuts);
+
+
+    if (!fUseStaticCuts)
+    {
+	// Set boolean variable that controls wether the theta variable 
+	// is used or not in the computation of the dynamical cuts
+	
+	fCalcHadTrain -> SetVariableNotUseTheta(fNotUseTheta);
+	fCalcHadTrainOFF -> SetVariableNotUseTheta(fNotUseTheta);
+    }
+
+
+    // apply the supercuts to OFF data
+
+    MF scfilterOFF(fHadronnessNameOFF+".fHadronness>0.5");
+    MContinue applysupercutsOFF(&scfilterOFF);
+
+     // apply the supercuts to ON data
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue applysupercuts(&scfilter);
+
+    
+
+
+    // ****************************************************
+    // Filling OFF alpha distribution 
+
+    MParList parlistOFF;
+    MTaskList tasklistOFF;
+
+    MMatrixLoop loopOFF(fMatrixTrainOFF);
+
+    // plot alpha before applying the supercuts
+    const TString  mh3NameOFFB = "AlphaOFFBefore";
+    MBinning binsalphaOFFbef("Binning"+mh3NameOFFB);
+    //binsalphaOFFbef.SetEdges(54, -12.0, 96.0);
+    binsalphaOFFbef.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alphaOFFbefore("MatrixTrainOFF[7]");
+    alphaOFFbefore.SetName(mh3NameOFFB);
+
+    
+    MFillH fillalphaOFFbefore(&alphaOFFbefore);
+    fillalphaOFFbefore.SetName("FillAlphaOFFBefore");
+
+   
+
+    // fill OFF alpha after applying the supercuts
+    const TString  mh3NameOFFA = "AlphaOFFAfter";
+    MBinning binsalphaOFFaft("Binning"+mh3NameOFFA);
+    //binsalphaOFFaft.SetEdges(54, -12.0, 96.0);
+    binsalphaOFFaft.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+
+    MH3 alphaOFFafter("MatrixTrainOFF[7]");
+    alphaOFFafter.SetName(mh3NameOFFA);
+
+    //TH1 &alphaOFFhista = alphaOFFafter.GetHist();
+    //alphaOFFhista.SetName("alphaOFFAfter-OptimizationParamOutput");
+
+    MFillH fillalphaOFFafter(&alphaOFFafter);
+    fillalphaOFFafter.SetName("FillAlphaOFFAfter");
+
+    //******************************
+    // entries in MParList
+
+    parlistOFF.AddToList(&tasklistOFF);
+
+    parlistOFF.AddToList(&supercuts);
+
+    parlistOFF.AddToList(&supapptrainOFF);
+
+    parlistOFF.AddToList(fCam);
+    parlistOFF.AddToList(fMatrixTrainOFF);
+
+    parlistOFF.AddToList(&binsalphaOFFbef);
+    parlistOFF.AddToList(&alphaOFFbefore);
+
+    parlistOFF.AddToList(&binsalphaOFFaft);
+    parlistOFF.AddToList(&alphaOFFafter);
+
+
+    //******************************
+    // Entries in MtaskList
+    tasklistOFF.AddToList(&loopOFF);
+    tasklistOFF.AddToList(&fillalphaOFFbefore);
+
+    tasklistOFF.AddToList(fCalcHadTrainOFF);
+    tasklistOFF.AddToList(&applysupercutsOFF);
+
+    tasklistOFF.AddToList(&fillalphaOFFafter);
+
+    //******************************
+
+    MProgressBar barOFF;
+    MEvtLoop evtloopOFF;
+    evtloopOFF.SetParList(&parlistOFF);
+    evtloopOFF.SetName("EvtLoopOptimizationParamOutputOFF");
+    evtloopOFF.SetProgressBar(&barOFF);
+    Int_t maxeventsOFF = -1;
+    if (!evtloopOFF.Eventloop(maxeventsOFF))
+        return kFALSE;
+
+    tasklistOFF.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // draw the alpha plots
+
+    MH3* alphaOFFBefore = (MH3*)parlistOFF.FindObject(mh3NameOFFB, "MH3");
+    TH1  &alphaOFFHistb = alphaOFFBefore->GetHist();
+    alphaOFFHistb.SetXTitle("|\\alpha|  [\\circ]");
+
+    TString alphaOFFHistbName ("TrainAlphaOFFBeforeCuts");
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+	alphaOFFHistbName += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	alphaOFFHistbName += (fThetaRangeString);
+    }
+
+    alphaOFFHistb.SetName(alphaOFFHistbName);
+
+    MH3* alphaOFFAfter = (MH3*)parlistOFF.FindObject(mh3NameOFFA, "MH3");
+    TH1  &alphaOFFHista = alphaOFFAfter->GetHist();
+    TString alphaOFFHistaName ("TrainAlphaOFFAfterCuts");
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+	alphaOFFHistaName += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	alphaOFFHistaName += (fThetaRangeString);
+    }
+
+
+    alphaOFFHista.SetXTitle("|\\alpha|  [\\circ]");
+    alphaOFFHista.SetName(alphaOFFHistaName);
+
+
+    // *****************************************************
+
+
+
+    //-------------------------------------------
+
+
+    MParList  parlist2;
+    MTaskList tasklist2;
+
+    MMatrixLoop loop(fMatrixTrain);
+
+    // plot alpha before applying the supercuts
+    const TString  mh3NameB = "AlphaBefore";
+    MBinning binsalphabef("Binning"+mh3NameB);
+    //binsalphabef.SetEdges(54, -12.0, 96.0);
+    binsalphabef.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+    
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alphabefore("MatrixTrain[7]");
+    alphabefore.SetName(mh3NameB);
+
+    MFillH fillalphabefore(&alphabefore);
+    fillalphabefore.SetName("FillAlphaBefore");
+
+
+    // plot alpha after applying the supercuts
+    const TString  mh3NameA = "AlphaAfter";
+    MBinning binsalphaaft("Binning"+mh3NameA);
+    //binsalphaaft.SetEdges(54, -12.0, 96.0);
+    binsalphaaft.SetEdges(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+
+    MH3 alphaafter("MatrixTrain[7]");
+    alphaafter.SetName(mh3NameA);
+
+    
+    MFillH fillalphaafter(&alphaafter);
+    fillalphaafter.SetName("FillAlphaAfter");
+
+    //******************************
+    // entries in MParList
+
+    parlist2.AddToList(&tasklist2);
+
+    parlist2.AddToList(&supercuts);
+
+    parlist2.AddToList(&supapptrainON);
+
+    parlist2.AddToList(fCam);
+    parlist2.AddToList(fMatrixTrain);
+
+    parlist2.AddToList(&binsalphabef);
+    parlist2.AddToList(&alphabefore);
+
+    parlist2.AddToList(&binsalphaaft);
+    parlist2.AddToList(&alphaafter);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklist2.AddToList(&loop);
+    tasklist2.AddToList(&fillalphabefore);
+
+    tasklist2.AddToList(fCalcHadTrain);
+    tasklist2.AddToList(&applysupercuts);
+
+    tasklist2.AddToList(&fillalphaafter);
+
+    //******************************
+
+    MProgressBar bar2;
+    MEvtLoop evtloop2;
+    evtloop2.SetParList(&parlist2);
+    evtloop2.SetName("EvtLoopOptimizationParamOutput");
+    evtloop2.SetProgressBar(&bar2);
+    Int_t maxevents2 = -1;
+    if (!evtloop2.Eventloop(maxevents2))
+        return kFALSE;
+
+    tasklist2.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // draw the alpha plots
+
+    MH3* alphaBefore = (MH3*)parlist2.FindObject(mh3NameB, "MH3");
+    TH1  &alphaHist1 = alphaBefore->GetHist();
+    TString alphaHist1Name ("TrainAlphaBeforeCuts");
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+	alphaHist1Name += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	alphaHist1Name += (fThetaRangeString);
+    }
+
+
+    alphaHist1.SetXTitle("|\\alpha|  [\\circ]");
+    alphaHist1.SetName(alphaHist1Name);
+
+    MH3* alphaAfter = (MH3*)parlist2.FindObject(mh3NameA, "MH3");
+    TH1  &alphaHist2 = alphaAfter->GetHist();
+    TString alphaHist2Name ("TrainAlphaAfterCuts");
+    if (fThetaRangeString.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; "
+	      << " fThetaRangeString is NOT defined..." << endl;
+	alphaHist2Name += ("ThetaRangeStringUndefined");
+    }
+    else
+    {
+	alphaHist2Name += (fThetaRangeString);
+    }
+
+    alphaHist2.SetXTitle("|\\alpha|  [\\circ]");
+    alphaHist2.SetName(alphaHist2Name);
+
+
+    // fPsFilename -> NewPage();
+
+    
+    // Canvas is deleted after saving the plot in ps file
+    // This is to allow for GRID analysis
+
+    TCanvas *c = new TCanvas("TrainAlphaBeforeAfterSC", 
+			     "TrainAlphaBeforeAfterSC", 
+			     600, 600);
+
+    c->Divide(2,2);
+
+
+
+    c->cd(1);
+    alphaOFFHistb.DrawCopy();
+
+    c->cd(2);
+    alphaOFFHista.DrawCopy();
+
+
+    //c->Modified();
+    //c-> Update();
+    
+
+    // fPsFilename -> NewPage();
+
+    c->cd(3);
+    alphaHist1.DrawCopy();
+
+    c->cd(4);
+    alphaHist2.DrawCopy();
+
+
+    c -> Modified();
+    c -> Update();
+    
+     // ********************************************
+    // TMP solutions while the TPostScript thing is not working 
+    // PsFileName for storing these plots is derived 
+    // from PsFilenameString. 
+
+    cout << "Alpha distributions will be saved in PostScript file  " ;
+
+    if (!fPsFilenameString.IsNull())
+    {
+	TString filename = (fPsFilenameString);
+	filename += ("AlphaTRAINSampleONOFFBeforeAfterCuts.ps");
+	cout << filename << endl;
+	c -> SaveAs(filename);
+    }
+
+    // END OF TEMPORAL SOLUTION
+    // ********************************************
+	    
+
+
+
+    // fPsFilename -> NewPage();
+
+
+    // Canvas is deleted after saving the plot in ps file
+    // This is to allow for GRID analysis
+
+    delete c;
+
+
+
+
+    //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    const Double_t alphasig = fAlphaSig;
+    const Double_t alphamin = fAlphaBkgMin; 
+   // alpha min for bkg region in ON data
+    
+    const Double_t alphamax = fAlphaBkgMax;
+//    const Int_t    degree   =    2;
+//    const Int_t    degreeOFF   =    2;
+    const Bool_t   drawpoly  = kTRUE;
+    const Bool_t   fitgauss  = kTRUE;
+    const Bool_t   print     = kTRUE;
+    
+    Bool_t saveplots   = kTRUE; // Save plots in Psfile
+  
+    
+
+    
+    
+
+    if (!ComputeNormFactorTrain())
+    {
+	*fLog << "Normalization factor for train sample (ON-OFF) could not be computed. Aborting..." << endl;
+	return kFALSE;
+    }
+	    
+
+    // Normalization factor factor is corrected using the estimated 
+    // number of excess events and the total number of OFF events
+    // fNormFactor = fNormFactor - Ngammas/EventsInMatrixOFF
+
+ 
+    if (fTuneNormFactor)
+    {
+
+
+	// Run MHFindSignificanceONOFF::FindSigmaONOFF
+	// to get estimation of number of excess gamma events. 
+	// This number will be used in the correction of the 
+	// normalization factor 
+	
+	// No plots will be produced this time...
+
+	const Bool_t   drawpolyTest  = kFALSE;
+	const Bool_t   fitgaussTest  = kFALSE;
+	const Bool_t   printTest     = kFALSE;
+	
+	const Bool_t saveplotsTest   = kFALSE; // Save plots in Psfile
+	
+	//TPostScript* DummyPs  = new TPostScript("dummy.ps");
+
+	TString DummyPs = ("Dummy");
+
+	MHFindSignificanceONOFF findsigTest;
+	findsigTest.SetRebin(kTRUE);
+	findsigTest.SetReduceDegree(kFALSE);
+	findsigTest.SetUseFittedQuantities(fUseFittedQuantities);
+
+	if(findsigTest.FindSigmaONOFF(&alphaHist2, &alphaOFFHista, 
+				      fNormFactorTrain, 
+				      alphamin, alphamax, 
+				      fDegreeON, fDegreeOFF,
+				      alphasig, drawpolyTest, 
+				      fitgaussTest, printTest, 
+				      saveplotsTest, DummyPs))
+
+	{
+
+	    // Update values of Nex and SigmaLiMa for Test sammple
+	
+	    fSigmaLiMaTrain = double(findsigTest.GetSignificance());
+
+	    if(fUseFittedQuantities)
+	    {
+		fNexTrain = double(findsigTest.GetNexONOFFFitted());
+	    }
+	    else
+	    {
+		fNexTrain = double(findsigTest.GetNexONOFF());
+	    }
+	    
+	}
+
+	else
+	{
+	    *fLog << "Normalization Factor tuning for Train sample is not possible"
+		  << endl;
+
+	    fSigmaLiMaTrain = 0.0;
+	    fNexTrain = 0.0;
+
+	}
+
+	//DummyPs -> Close();
+	//DummyPs = NULL;
+	//delete DummyPs;
+
+	
+
+
+	Int_t EventsInTrainMatrixOFF = fMatrixTrainOFF->GetM().GetNrows();
+	Double_t Ngammas = fNexTrain/fGammaEfficiency;
+	Double_t GammaFraction = Ngammas/EventsInTrainMatrixOFF;
+	
+
+	*fLog << "MFindSupercutsONOFF::TestParamsOnTrainSample; "
+	      << "fNormFactorTrain is corrected with fraction of gammas in ON "
+	      << "Data Train sample and the number of OFF events before cuts." 
+	      << endl
+	      << "EventsInTrainMatrixOFF = " << EventsInTrainMatrixOFF
+	      << " Excess events in Train ON sample = " << fNexTrain
+	      << " fGammaEfficiency = " << fGammaEfficiency << endl
+	      << "fNormFactorTrain Value before correction is " 
+	      << fNormFactorTrain << endl;
+
+	fNormFactorTrain = fNormFactorTrain - GammaFraction;
+
+	*fLog << "fNormFactorTrain Value after correction is "
+	      << fNormFactorTrain << endl;
+       
+	    
+
+    }
+
+    if (fNormFactorFromAlphaBkg)
+    {
+	Double_t NewNormFactor = 
+	    ComputeNormFactorFromAlphaBkg(&alphaHist2, &alphaOFFHista, 
+					  fAlphaBkgMin, fAlphaBkgMax);
+	
+	*fLog << "Normalization factor computed from alpha plot (after cuts) " << endl
+	      << "using counted number of ON and OFF events in alpha region " << endl
+	      << "defined by range " << fAlphaBkgMin << "-" << fAlphaBkgMax << endl
+	      << "Normalization factor = " << NewNormFactor << endl;
+
+	*fLog << "Normalization factor used is the one computed in bkg region; " << endl
+	      << "i.e. " << NewNormFactor << " instead of " << fNormFactorTrain << endl;
+
+	fNormFactorTrain = NewNormFactor;
+
+
+    }
+
+
+    MHFindSignificanceONOFF findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+    findsig.SetUseFittedQuantities(fUseFittedQuantities);
+
+    TString psfilename; // Name of psfile where Alpha plot will be stored
+    if (!fPsFilenameString.IsNull())
+    {
+	psfilename += (fPsFilenameString);
+	psfilename += ("TRAINSample"); 
+    }
+    else
+    {
+	psfilename += ("TRAINSample");
+    }
+
+
+    findsig.FindSigmaONOFF(&alphaHist2, &alphaOFFHista, 
+			   fNormFactorTrain, 
+			   alphamin, alphamax, 
+			   fDegreeON, fDegreeOFF,
+			   alphasig, drawpoly, fitgauss, print, 
+			   saveplots, psfilename);
+    
+    const Double_t significance = findsig.GetSignificance();
+    const Double_t alphasi = findsig.GetAlphasi();
+
+    // Update Train values Nex, SigmaLiMa
+
+  fSigmaLiMaTrain = double(findsig.GetSignificance());
+
+  if(fUseFittedQuantities)
+  {
+      fNexTrain = double(findsig.GetNexONOFFFitted()); 
+  }
+  else
+  {
+      fNexTrain = double(findsig.GetNexONOFF()); 
+  }
+  
+
+    // Alpha distributions and containers with the supercuts applied 
+    // are written into root file 
+
+    TFile rootfile(fAlphaDistributionsRootFilename, "UPDATE",
+		   "Alpha Distributions for several Theta bins");
+
+    alphaHist2.Write();
+    alphaOFFHista.Write();
+    
+    (supapptrainON.GetTreePointer())->Write();
+    (supapptrainOFF.GetTreePointer())->Write();
+
+    *fLog  << "TTree objects containing supercuts applied to TEST sample are "
+	   << "written into root file " << fAlphaDistributionsRootFilename << endl; 
+ 
+    (supapptrainON.GetTreePointer())->Print();
+    (supapptrainOFF.GetTreePointer())->Print();
+
+
+    //rootfile.Close();
+    
+
+    // Boolean variable that controls in class MSupercutsCalcONOFF
+    // wether the supercuts are stored or not
+    // is set to the default value, kFALSE.
+
+    fCalcHadTrain -> SetStoreAppliedSupercuts(kFALSE);
+    fCalcHadTrainOFF -> SetStoreAppliedSupercuts(kFALSE);
+    
+
+
+
+
+    *fLog << "Significance of gamma signal after supercuts in train sample : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+    //-------------------------------------------
+
+
+    *fLog << "Test of supercuts on TRAIN sample finished" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFF.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFF.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFF.h	(revision 9772)
@@ -0,0 +1,482 @@
+#ifndef MARS_MFindSupercutsONOFF
+#define MARS_MFindSupercutsONOFF
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TH1F
+#include <TH1F.h>
+#endif
+
+#ifndef ROOT_TPostScript
+#include <TPostScript.h>
+#endif
+
+
+class MFilter;
+class MEvtLoop;
+class MH3;
+class MSupercutsCalcONOFF;
+
+class MGeomCam;
+class MHMatrix;
+
+
+class MFindSupercutsONOFF : public MParContainer
+{
+ private:
+
+
+     // TMP
+    // There are quite some problems during the data preprocessing. 
+    // For the time being, I will add some cuts to the functions 
+    // DefineTrainTestMatrixThetaRange and for OFF, so that I can 
+    // make a kind of preprocess on my own. This allows me 
+    // to make a very silly preprocess with wolfgangs macro, which 
+    // might be free of corrupted data, and then I can do on my own.
+
+
+    // VARIABLES INITIALIZED IN CONSTRUCTOR
+
+    Double_t fSizeCutLow;
+    Double_t fSizeCutUp;
+
+    Double_t fDistCutLow;
+    Double_t fDistCutUp;
+    
+    Double_t fLengthCutLow;
+    Double_t fLengthCutUp;
+    
+    Double_t  fWidthCutLow;
+    Double_t  fWidthCutUp;
+
+    Double_t  fLeakageMax;
+
+    Double_t fConvMMToDeg;
+
+    // ENDTMP
+
+
+    Int_t fDegreeON;
+    Int_t fDegreeOFF;
+
+
+  TString fFilenameTrain;
+  TString fFilenameTest;
+
+  Int_t   fHowManyTrain;
+  Int_t   fHowManyTest;
+
+  Int_t   fHowManyTrainOFF;
+  Int_t   fHowManyTestOFF;
+
+
+  
+  Double_t fAlphaSig; // Max alpha value were signal is expected
+
+  // Background range (in alpha) is defined by the member variables 
+  // fAlphaBkgMin and fAlphaBkgMax
+  Double_t fAlphaBkgMin; 
+  Double_t fAlphaBkgMax; 
+  
+  Int_t fThetaMin; // Cut in Theta value (in degrees)
+  Int_t fThetaMax; // Cuts in Theta value (in degrees)
+  TString fThetaRangeString;
+
+ 
+
+  // Variables for binning of alpha plots
+  
+  Int_t fNAlphaBins;
+  Double_t fAlphaBinLow;
+  Double_t fAlphaBinUp;
+
+
+  Bool_t  fUseOrigDistribution;
+
+
+  Double_t fNormFactorTrain;
+  Double_t fNormFactorTest;
+  Double_t fSigmaLiMaTrain;
+  Double_t fSigmaLiMaTest;
+  Double_t fNexTrain; 
+  Double_t fNexTest; 
+  Double_t fGammaEfficiency; // Fraction of gammas that remain after cuts
+  // Quantity that will have to be determined with MC
+
+  Bool_t fTuneNormFactor; // If true, normalization factors are corrected using the estimated number of gammas and the gamma efficiency
+  // fNormFactorTrain = fNormFactorTrain - Ngammas/EventsInTrainMatrixOFF
+
+
+  // Boolean variable used to determine wether the normalization factor is 
+  // computed from method 1) or 2)
+  // 1) Using total number of ON and OFF events before cuts, and tuning the factor 
+  //    correcting for "contamination" of gamma events in ON sample
+  // 2) Using number of ON and OFF events after cuts in the background 
+  //    region determined by variables fAlphaBkgMin-fAlphaBkgMax
+ 
+  Bool_t fNormFactorFromAlphaBkg; // if kTRUE, method 2) is used
+
+
+
+  // Boolean variable used to disable the usage ("serious" usage) of the 
+  // quantities computed from fits. This will be useful in those cases 
+  // where there is too few events to perform a decent fit to the 
+  // alpha histograms. Default value will be kTRUE.
+  
+  Bool_t fUseFittedQuantities;
+
+  // Boolean variable that controls wether the optimization of the 
+  // parameters (MMinuitInterface::CallMinuit(..) in function FindParams(..))
+  // takes place or not. kTRUE will skip such optimization.
+  // This variable is useful to test the optmized parameters (previously found 
+  // and stored in root file) on the TRAIN sample.
+
+  Bool_t fSkipOptimization;
+
+
+
+  // Boolean variable that allows the user to set some limits to the 
+  // some of the Minuit parameters. For the time being, only the limits
+  // for the parameters which do NOT depend in size, dist and theta are set, 
+  // i.e. static limits. The value of this boolean variable is set in the 
+  // constructor of the class.
+
+  Bool_t fSetLimitsToSomeMinuitParams;
+
+  // Limits for the Minuit parameters. For the time being the values are set in the constructor 
+  // of the class. One MUST be very careful to set limits such that the expected final values 
+  // (optimized values) are far away from the limits.
+
+ 
+  
+  Double_t fMinuitDistUPUpperLimit;
+  Double_t fMinuitDistUPLowerLimit;
+  Double_t fMinuitLengthUPUpperLimit;
+  Double_t fMinuitLengthUPLowerLimit;
+  Double_t fMinuitWidthUPUpperLimit;
+  Double_t fMinuitWidthUPLowerLimit;
+  
+  Double_t fMinuitLeakage1UPUpperLimit;
+  Double_t fMinuitLeakage1UPLowerLimit;
+
+
+
+  Double_t fMinuitDistLOWUpperLimit;
+  Double_t fMinuitDistLOWLowerLimit;
+  Double_t fMinuitLengthLOWUpperLimit;
+  Double_t fMinuitLengthLOWLowerLimit;
+  Double_t fMinuitWidthLOWUpperLimit;
+  Double_t fMinuitWidthLOWLowerLimit;
+  
+
+
+  // Boolean variable used to control decide wether to use theta information 
+  // in the computation of teh dynamical cuts.
+  Bool_t fNotUseTheta;
+
+
+  // Boolean variable that allows to use/not use the dist info in the cuts parameterization
+  // kTRUE for use it.
+  // For the time being this variable is set in the constructor
+
+  Bool_t fUseDist;
+
+
+
+ // Boolean variable used to decide wether to use dynamical cuts or static cuts
+  // kTRUE means that static cuts are used. 
+  Bool_t fUseStaticCuts;
+
+  
+  // Boolean variable that allows the user to write the initial parameters 
+  // into the root file that will be used to store the optimum cuts.
+  // If fUseInitialSCParams = kTRUE , parameters are written.
+  // In this way, the initial SC parameters can be applied on the data (train/test) 
+  
+  // The initial parameters are ONLY written to the root file if 
+  // there is NO SC params optimization, i.e., if variable 
+  // fSkipOptimization = kTRUE;
+  
+  // The default value is obviously kFALSE.
+
+  Bool_t fUseInitialSCParams;
+
+  
+  TString  fFilenameParam;
+
+  TString  fHadronnessName;
+  TString  fHadronnessNameOFF;
+
+  // name for the containers to store the 
+  // supercuts applied to Train (ON/OFF) and Test(ON/OFF) samples
+
+  TString  fTrainONSupercutsAppliedName;        
+  TString  fTrainOFFSupercutsAppliedName;       
+
+  TString  fTestONSupercutsAppliedName;        
+  TString  fTestOFFSupercutsAppliedName;       
+
+  
+
+  // Name of Postscript file where, for each theta bin,  alpha ON and OFF distributions 
+  //  after cuts (and hence, Nex and SigmaLiMa computations) will be stored
+  // If fAlphaDistributionsPostScriptFilename is not defined, postscript file is not 
+  // produced. It is an optional variable...
+
+  // NOT WORKING YET !!!!
+  TPostScript* fPsFilename; 
+  TPostScript* fPsFilename2; 
+
+  TString fPsFilenameString; // Name of the file where plots will be stored while the 
+  // TPostScript option is not working 
+
+  TString fAlphaDistributionsRootFilename;
+  // Root file where histograms containing the ON alpha distribution and the 
+  // OFF alpha distribution (non normalized) , AFTER CUTS, are stored.
+  // Histograms containing the normalization factors, Nex and SigmaLiMa for 
+  // each theta bin will be also stored there.
+  // This name MUST be defined, since the histograms stored there will be used by 
+  // function XXX to compute an overall Nex and sigmaLiMa combining all those histograms
+
+
+  MSupercutsCalcONOFF *fCalcHadTrain;
+  MSupercutsCalcONOFF *fCalcHadTest;
+  MSupercutsCalcONOFF *fCalcHadTrainOFF;
+  MSupercutsCalcONOFF *fCalcHadTestOFF;
+  
+
+  MHMatrix          *fMatrixTrain;
+  MHMatrix          *fMatrixTest;
+  MHMatrix          *fMatrixTrainOFF;
+  MHMatrix          *fMatrixTestOFF;
+
+  MGeomCam          *fCam;
+
+  MEvtLoop *fObjectFit;
+
+  MFilter  *fMatrixFilter; 
+
+  // to comunicate with MINUIT -----------------
+  // attention : dimensions must agree with those in 
+  //             MMinuitInterface::CallMinuit()
+  //char    fParName [80][100];
+  TArrayD fVinit;
+  TArrayD fStep;
+  TArrayD fLimlo;
+  TArrayD fLimup;
+  TArrayI fFix;
+
+  UInt_t     fNpar;
+
+  TString    fMethod;
+
+  Double_t fMin,   fEdm,   fErrdef;
+  Int_t    fNpari, fNparx, fIstat;
+  Int_t    fErrMinimize;
+  //--------------------------------------------
+
+
+public:
+  MFindSupercutsONOFF(const char *name=NULL, const char *title=NULL);
+  ~MFindSupercutsONOFF();
+
+  void SetFilenameTraining(const TString &name, const Int_t howmany) 
+      {fFilenameTrain = name;  fHowManyTrain = howmany; }
+
+  void SetFilenameTest(const TString &name, const Int_t howmany)     
+      {fFilenameTest     = name;  fHowManyTest  = howmany; }
+
+  void SetFilenameParam(const TString &name)    {fFilenameParam  = name;}
+  void SetHadronnessName(const TString &name)   {fHadronnessName = name;}
+  void SetHadronnessNameOFF(const TString &name)   {fHadronnessNameOFF = name;}
+
+  
+  void SetSupercutsAppliedTreeNames();
+
+
+  void SetAlphaDistributionsRootFilename(const TString &name) 
+      {fAlphaDistributionsRootFilename = name;}
+
+  Bool_t SetAlphaSig (Double_t alphasig);
+  Bool_t SetAlphaBkgMin (Double_t alphabkgmin);
+  Bool_t SetAlphaBkgMax (Double_t alphabkgmax);
+
+  // Function that checks that the values of the member data 
+  // fAlphaSig, fAlphaBkgMin and fAlphaBkgMax make sense
+  // (ie, fAlphaSig < fAlphaBkgMin < fAlphaBkgMax)
+
+  Bool_t CheckAlphaSigBkg();
+
+  void SetDegreeON (Int_t d) {fDegreeON = d;}
+  void SetDegreeOFF (Int_t d) {fDegreeOFF = d;}
+
+
+  void SetUseFittedQuantities (Bool_t b)
+      {fUseFittedQuantities = b;}
+
+
+  void SetPostScriptFile(TPostScript* PsFile);
+  void SetPostScriptFile2(TPostScript &PsFile);
+
+  void SetPsFilenameString (const TString filename);
+
+
+  void SetMatrixFilter(MFilter *filter)          {fMatrixFilter = filter;}
+
+  
+
+
+  Bool_t DefineTrainMatrix(const TString &name, MH3 &href,
+                           const Int_t howmany, const TString &filetrain);
+  Bool_t DefineTestMatrix(const TString &name, MH3 &href,
+                          const Int_t howmany, const TString &filetest);
+
+
+
+  Bool_t DefineTrainTestMatrix(const TString &name, MH3 &href,
+			 const Int_t howmanytrain, const Int_t howmanytest, 
+                         const TString &filetrain, const TString &filetest);
+
+
+
+  Bool_t DefineTrainTestMatrixThetaRange(const TString &name, 
+					 const Double_t whichfractiontrain, 
+					 const Double_t whichfractiontest,  
+					 Double_t ThetaMin, Double_t ThetaMax, 
+					 const TString &filetrain, const TString &filetest);
+
+
+
+  
+  Bool_t DefineTrainTestMatrixOFFThetaRange(const TString &name, 
+					    const Double_t whichfractiontrain, 
+					    const Double_t whichfractiontest,  
+					    Double_t ThetaMin, Double_t ThetaMax, 
+					    const TString &filetrain, const TString &filetest);
+
+
+  MHMatrix *GetMatrixTrain() { return fMatrixTrain; }
+  MHMatrix *GetMatrixTest()  { return fMatrixTest;  }
+  MHMatrix *GetMatrixTrainOFF() { return fMatrixTrainOFF; }
+  MHMatrix *GetMatrixTestOFF()  { return fMatrixTestOFF;  }
+
+
+  void SetUseOrigDistribution(Bool_t b);
+
+
+  Bool_t ReadMatrix( const TString &filetrain, const TString &filetest);
+  
+  Bool_t ReadMatrixOFF( const TString &filetrainOFF, const TString &filetestOFF);
+
+
+  Bool_t ReadMatrixTrain(const TString &filetrainON, const TString &filetrainOFF);
+  Bool_t ReadMatrixTest(const TString &filetestON, const TString &filetestOFF);
+
+
+
+  Bool_t ComputeNormFactorTrain ();
+  Bool_t ComputeNormFactorTest ();
+
+  Bool_t FindParams(TString parSCinit, TArrayD &params, TArrayD &steps);
+  // Bool_t TestParams();
+
+  // Function used to apply the supercuts on the TEST sample.
+  // Two event loops (one after the other) 
+  // are used to fill the 2 alpha distributions (ON and OFF) 
+  // applying supercuts to the Test sample
+  Bool_t TestParamsOnTestSample(); 
+  
+
+  // Function used to apply the supercuts on the TRAIN sample.
+  // Two event loops (one after the other) 
+  // are used to fill the 2 alpha distributions (ON and OFF) 
+  // applying supercuts to the TRAIN sample
+  Bool_t TestParamsOnTrainSample();
+  
+
+
+  Bool_t SetThetaRange(Double_t ThetaMin, Double_t ThetaMax);
+
+  Bool_t SetSizeRange(Double_t SizeMin, Double_t SizeMax);
+
+  Bool_t SetFilters(Double_t LeakageMax, Double_t DistMax, Double_t DistMin);
+
+
+
+  void SetAlphaPlotBinining(Int_t nbins, Double_t binlow, Double_t binup)
+    { fNAlphaBins = nbins; fAlphaBinLow = binlow; fAlphaBinUp = binup;}
+
+  Double_t GetNormFactorTrain() {return fNormFactorTrain;}
+  Double_t GetNormFactorTest() {return fNormFactorTest;}
+  Double_t GetSigmaLiMaTrain() {return fSigmaLiMaTrain;}
+  Double_t GetSigmaLiMaTest() {return fSigmaLiMaTest;}
+  Double_t GetNexTrain() {return fNexTrain;}
+  Double_t GetNexTest() {return fNexTest;}
+
+
+  Double_t GetAlphaSig() {return fAlphaSig;}
+  Double_t GetAlphaBkgMin () {return fAlphaBkgMin;}
+  Double_t GetAlphaBkgMax () {return fAlphaBkgMax;}
+  
+  Bool_t GetUseFittedQuantities() {return fUseFittedQuantities;}
+  Bool_t GetSkipOptimization() {return fSkipOptimization;}
+  Bool_t GetUseInitialSCParams() {return fUseInitialSCParams;}
+
+  Bool_t SetGammaEfficiency (Double_t gammaeff);
+  Double_t GetGammaEfficiency() {return fGammaEfficiency;}
+  
+  
+
+  // Double_t ComputeNormFactorFromAlphaBkg(TH1 *histON, TH1 *histOFF);
+           
+  void SetTuneNormFactor(Bool_t b) {fTuneNormFactor = b;}
+
+  void SetNormFactorFromAlphaBkg (Bool_t b) {fNormFactorFromAlphaBkg = b;}
+
+  void SetSkipOptimization(Bool_t b);
+
+  void SetUseInitialSCParams(Bool_t b);
+
+  void SetVariableNotUseTheta(Bool_t b) {fNotUseTheta = b;}
+  Bool_t GetVariableNotUseTheta() { return fNotUseTheta;}
+
+  void SetVariableUseStaticCuts(Bool_t b) {fUseStaticCuts = b;}
+  Bool_t GetVariableUseStaticCuts() { return fUseStaticCuts;}
+
+  
+
+  
+
+
+  ClassDef(MFindSupercutsONOFF, 1) // Class for optimization of the Supercuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFFThetaLoop.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFFThetaLoop.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFFThetaLoop.cc	(revision 9772)
@@ -0,0 +1,4272 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): David Paneque   12/2003 <mailto:dpaneque@mppmu.mpg.de>
+!              
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFindSupercutsONOFFThetaLoop                                             //
+//                                                                         //
+// Class for optimizing the parameters of the supercuts                     //
+// Using ON and OFF data runing over data which are subdivided in 
+// several Theta ranges.                                                  //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+
+#include "MFindSupercutsONOFFThetaLoop.h"
+
+
+#include <math.h>            // fabs 
+
+#include <TFile.h>
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TStopwatch.h>
+#include <TVirtualFitter.h>
+
+#include <iostream.h>
+#include <fstream.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "MFindSupercutsONOFF.h"
+#include "MBinning.h"
+#include "MContinue.h"
+#include "MSupercuts.h"
+#include "MSupercutsCalcONOFF.h"
+#include "MDataElement.h"
+#include "MDataMember.h"
+
+
+#include <TPostScript.h>
+
+#include "MEvtLoop.h"
+#include "MFCT1SelFinal.h"
+#include "MF.h"
+#include "MFEventSelector.h"
+#include "MFEventSelector2.h"
+#include "MFillH.h"
+//#include "MGeomCamCT1Daniel.h"
+//#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h" // only for magic
+#include "MFRandomSplit.h"
+#include "MH3.h"
+#include "MHCT1Supercuts.h"
+#include "MHFindSignificance.h" // To be removed at some point...
+#include "MHFindSignificanceONOFF.h"
+#include "MHMatrix.h"
+#include "MHOnSubtraction.h"
+#include "MDataValue.h"
+// #include "MDataString.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMatrixLoop.h"
+#include "MMinuitInterface.h"
+#include "MParList.h"
+#include "MProgressBar.h"
+#include "MReadMarsFile.h"
+#include "MReadTree.h"
+#include "MTaskList.h"
+
+
+ClassImp(MFindSupercutsONOFF);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFindSupercutsONOFFThetaLoop::MFindSupercutsONOFFThetaLoop(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MFindSupercutsONOFF";
+    fTitle = title ? title : "Optimizer of the supercuts";
+    
+    //---------------------------
+
+    // *********************************
+    // ** NOT TRUE ANY LONGER... ** //
+    // Cuts (low and up) in variable ThetaOrig.fVal
+    // The default is not cut, i.e. all values (0-1) are taken
+    // fThetaOrig.fVal is measured in Radians; thus 1 = 57 degrees.
+
+    //    fThetaMin = 0.0;
+    //    fThetaMax = 1.0;
+    // *********************************
+
+
+    // For MAGIC new (July 2004) Theta is measured in degrees
+
+    fThetaMin = 0.0;
+    fThetaMax = 90.0;
+
+
+
+    fAlphaSig = 20; // By default, signal is expected in alpha<20 for CT1
+
+    // By default, bkg region is set to alpha range 30-90 for CT1
+    fAlphaBkgMin = 30; 
+    fAlphaBkgMax = 90;
+
+    fActualCosThetaBinCenter = 0;
+    
+    fNormFactorTrainHist = NULL;
+    //fNormFactorTrainHist -> SetDirectory(0);
+    fNormFactorTestHist = NULL;
+    //fNormFactorTestHist -> SetDirectory(0);
+    fSigmaLiMaTrainHist = NULL;
+    //fSigmaLiMaTrainHist -> SetDirectory(0);
+    fSigmaLiMaTestHist = NULL;
+    //fSigmaLiMaTestHist -> SetDirectory(0);
+    fNexTrainHist = NULL;
+    //fSigmaLiMaTestHist -> SetDirectory(0);
+    fNexTestHist = NULL;
+    //fNexTestHist -> SetDirectory(0);
+
+
+    fSuccessfulThetaBinsHist = NULL;
+
+    /*
+    fNexVSAlphaSigTrain = NULL;
+    fNexVSAlphaSigTest = NULL;
+    
+    fSignificanceVSAlphaSigTrain = NULL;
+    fSignificanceVSAlphaSigTest = NULL;
+    */
+
+
+    fNEvtsInTrainMatrixONHist = NULL; 
+    fNEvtsInTestMatrixONHist = NULL; 
+    fNEvtsInTrainMatrixOFFHist = NULL; 
+    fNEvtsInTestMatrixOFFHist = NULL; 
+
+
+    fTrainMatrixONFilenameVector = NULL;
+    fTestMatrixONFilenameVector= NULL;
+    fTrainMatrixOFFFilenameVector= NULL;
+    fTestMatrixOFFFilenameVector= NULL;
+
+    
+    fOptSCParamFilenameVector = NULL;
+
+    fThetaRangeStringVector = NULL;
+
+    fPsFilename = NULL;
+
+
+
+    fTuneNormFactor = kTRUE; // Norm factors will be corrected using the total amount of OFF events before cuts and the estimated excess events
+    
+    // fNormFactorTrain = fNormFactorTrain - Ngammas/EventsInTrainMatrixOFF
+    
+    fGammaEfficiency = 0.5; // Fraction of gammas that remain after cuts
+    // Quantity that will have to be determined with MC, yet for the 
+    // time being I set it to 0.5
+
+    // boolean variables are set to kFALSE as default 
+
+    fReadMatricesFromFile = kFALSE;
+    fOptimizeParameters = kFALSE;
+    fTestParameters = kFALSE;
+
+    // Fraction of Train/Test ON/OFF samples is set to 0.5 as default
+
+   fWhichFractionTrain = 0.5;  // number <= 1; specifying fraction of ON Train events
+   fWhichFractionTest = 0.5;  // number <= 1; specifying fraction of ON Test events
+
+   fWhichFractionTrainOFF = 0.5;  // number <= 1; specifying fraction of OFF  Train events
+   fWhichFractionTestOFF = 0.5;  // number <= 1; specifying fraction of OFF Test events
+
+
+
+    // use quantities computed from the fits
+    // The variable allows the user to NOT use these quantities when there is not 
+    // enough statistics and fit not always is possible
+    fUseFittedQuantities = kTRUE;
+
+
+
+    // Boolean variable that controls wether the optimization of the 
+    // parameters (MMinuitInterface::CallMinuit(..) in function FindParams(..))
+    // takes place or not. kTRUE will skip such optimization.
+    // This variable is useful to test the optmized parameters (previously found 
+    // and stored in root file) on the TRAIN sample.
+    
+    fSkipOptimization = kFALSE;
+
+    // Boolean variable that allows the user to write the initial parameters 
+    // into the root file that will be used to store the optimum cuts.
+    // If fUseInitialSCParams = kTRUE , parameters are written.
+    // In this way, the initial SC parameters can be applied on the data (train/test) 
+    
+    // The initial parameters are ONLY written to the root file if 
+    // there is NO SC params optimization, i.e., if variable 
+    // fSkipOptimization = kTRUE;
+
+    // The default value is obviously kFALSE.
+
+    fUseInitialSCParams = kTRUE;
+
+
+
+    // fInitSCPar  and fInitSCParSteps initialized to zero
+    
+    fInitSCPar.Set(0);
+
+    fInitSCParSteps.Set(0);
+        
+}
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MFindSupercutsONOFFThetaLoop::~MFindSupercutsONOFFThetaLoop()
+{
+
+    *fLog << "Destructor of MFindSupercutsONOFFThetaLoop is called" 
+	  << endl;
+
+    fPsFilename = NULL;
+
+    delete fNormFactorTrainHist;
+    delete fNormFactorTestHist;
+    delete fSigmaLiMaTrainHist;
+    delete fSigmaLiMaTestHist;
+    delete fNexTrainHist;
+    delete fNexTestHist;
+
+
+    
+    delete fSuccessfulThetaBinsHist;
+    
+
+    delete fNEvtsInTrainMatrixONHist; 
+    delete fNEvtsInTestMatrixONHist; 
+    delete fNEvtsInTrainMatrixOFFHist; 
+    delete fNEvtsInTestMatrixOFFHist; 
+
+    delete [] fTrainMatrixONFilenameVector;
+    delete [] fTestMatrixONFilenameVector;
+    delete [] fTrainMatrixOFFFilenameVector;
+    delete [] fTestMatrixOFFFilenameVector;
+    
+    delete [] fOptSCParamFilenameVector;
+    
+    delete [] fThetaRangeStringVector;
+
+
+    *fLog << "Destructor of MFindSupercutsONOFFThetaLoop finished " 
+	  << "successfully."  
+	  << endl;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Function that sets the name of the PostScript file where alpha distributions 
+// for the different Theta bins will be stored.
+// It also initializes 
+
+
+
+void MFindSupercutsONOFFThetaLoop::SetPostScriptFile (TPostScript* PsFile)
+{
+    fPsFilename = PsFile;
+
+    *fLog << "MFindSupercutsONOFF : Results (alpha distributions with excess and significances) will be stored in PostScript file " 
+	  << fPsFilename -> GetName() << endl;
+
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetGammaEfficiency (Double_t gammaeff)
+{
+    if (gammaeff <= 0.0 || gammaeff > 1)
+    {
+	*fLog << " ******   ERROR  *********"  << endl
+ 	      << "MFindSupercutsONOFFThetaLoop :: SetGammaEfficiency; " << endl
+	      << "The requested Gamma efficiency " << gammaeff << " can not occur" << endl
+	      << "Member data fGammaEfficiency can not be set properly." << endl
+	      << "Default value for fGammaEfficiency, which is " 
+	      << fGammaEfficiency << " will remain." << endl;
+
+
+	return kFALSE;
+    }
+
+    fGammaEfficiency = gammaeff;
+
+    return kTRUE;
+
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::ReadSCParamsFromAsciiFile(const char* filename,
+								  Int_t Nparams)
+{
+    const Int_t NColumns = 2; 
+    
+    Double_t tmp_vector[NColumns];
+    Int_t counter = 0;
+    Double_t tmpdouble = 0.0;
+
+    
+    // File is read and data stored in data_vector
+    
+    ifstream infile (filename, ios::in);
+    
+    if ( !infile )
+    {
+	cout << "Input file could not be opened" << endl; 	
+	return kFALSE;
+      //	exit (1);
+    }
+    
+    counter = 0;
+    while (infile >> tmp_vector [0])
+    {
+	for (Int_t i = 1; i < NColumns; i++)
+	{
+	    infile >> tmp_vector[i];
+	}
+	counter++;
+    }
+    
+    infile.close();
+    
+    
+    // Length of TArray vectors is set to the length of the 
+    // vectors defined in ascii file.
+    // If such length does not match with the specified 
+    // by variable Nparams, the function complains and 
+    // aborts.
+    
+    if (counter != Nparams)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::ReadSCParamsFromAsciiFile" << endl
+	      << "Length of vectors in ascii file " << filename << "  is  " << counter 
+	      << " , which does not match with the expected length " << Nparams << endl  
+	      << " fInitSCPar and fInitSCParSteps are NOT retrieved from ascii file" << endl;
+
+	return kFALSE;
+    }
+    
+    fInitSCPar.Set(counter);
+    fInitSCParSteps.Set(counter);
+    
+    
+  // Vectors are filled
+
+  ifstream infile2 (filename, ios::in);
+  
+  if ( !infile2 )
+    {
+      cout << "Input file could not be opened" << endl; 
+      return kFALSE;
+      // exit (1);
+    }
+  
+  for (Int_t i = 0; i < fInitSCPar.GetSize(); i++)
+    {
+
+	infile2 >> tmpdouble;
+	fInitSCPar[i] = tmpdouble;
+	
+	infile2 >> tmpdouble;
+	fInitSCParSteps[i] = tmpdouble;
+	
+    }
+
+
+  // Print the vectors read 
+
+  *fLog << "*****  INITIAL SC PARAMETERS AND STEPS TAKEN FROM ASCII FILE ********* " << endl;
+  for (Int_t i = 0; i < fInitSCPar.GetSize(); i++)
+    {
+	cout << fInitSCPar[i] << setw(20) <<  fInitSCParSteps[i] << endl;
+    }
+
+  // 
+  
+ // File close 
+  infile2.close();
+  
+  return kTRUE;
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetInitSCPar (TArrayD &d)
+{
+    *fLog << "MFindSupercutsONOFFThetaLoop; Initial SC parameters are "
+	  << "set using function SetInitSCPar (TArrayD &d)" << endl;
+
+    fInitSCPar = d;
+
+    return kTRUE;
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetInitSCParSteps (TArrayD &d)
+{
+
+    *fLog << "MFindSupercutsONOFFThetaLoop; Initial SC parameters STEPS are "
+	  << "set using function SetInitSCParSteps (TArrayD &d)" << endl;
+
+    fInitSCParSteps = d;
+
+    return kTRUE;
+}
+
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetAlphaSig(Double_t alphasig)
+{
+    // check that alpha is within the limits 0-90
+    if (alphasig <= 0 || alphasig > 90)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop ::SetAlphaSig; " 
+	      << "value " << alphasig << " is not within the the "
+	      << "logical limits of alpha; 0-90" << endl;
+	return kFALSE;
+    }
+    
+
+    fAlphaSig = alphasig;
+
+    return kTRUE;
+}
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetAlphaBkgMin(Double_t alpha)
+{
+    // check that alpha is within the limits 0-90
+    if (alpha <= 0 || alpha >= 90)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::SetAlphaBkgMin; " 
+	      << "value " << alpha << " is not within the the "
+	      << "logical limits of alpha; 0-90" << endl;
+	return kFALSE;
+    }
+    
+
+    fAlphaBkgMin = alpha;
+
+    return kTRUE;
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetAlphaBkgMax(Double_t alpha)
+{
+    // check that alpha is within the limits 0-90
+    if (alpha <= 0 || alpha > 90.001)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop ::SetAlphaBkgMax; " 
+	      << "value " << alpha << " is not within the the "
+	      << "logical limits of alpha; 0-90" << endl;
+	return kFALSE;
+    }
+    
+
+    fAlphaBkgMax = alpha;
+
+    return kTRUE;
+}
+
+
+// Function that checks that the values of the member data 
+// fAlphaSig, fAlphaBkgMin and fAlphaBkgMax make sense
+// (ie, fAlphaSig < fAlphaBkgMin < fAlphaBkgMax)
+
+Bool_t MFindSupercutsONOFFThetaLoop::CheckAlphaSigBkg()
+{
+
+    if (fAlphaSig > fAlphaBkgMin)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop ::CheckAlphaSigBkg(); " << endl
+	      << "fAlphaSig > fAlphaBkgMin, which should not occur..." << endl
+	      << "fAlphaSig = " << fAlphaSig << ", fAlphaBkgMin = " << fAlphaBkgMin
+	      << endl;
+
+	return kFALSE;
+    }
+    
+    if (fAlphaBkgMax < fAlphaBkgMin)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::CheckAlphaSigBkg(); " << endl
+	      << "fAlphaBkgMin > fAlphaBkgMax, which should not occur..." << endl
+	      << "fAlphaBkgMin = " << fAlphaBkgMin << ", fAlphaBkgMax = " << fAlphaBkgMax
+	      << endl;
+
+	return kFALSE;
+    }
+
+    return kTRUE;
+
+}
+
+
+
+
+// Function that sets the value of fCosThetaRangeVector and 
+// fCosThetaBinCenterVector
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetCosThetaRangeVector(
+    const TArrayD &d)
+{
+    if (d.GetSize() < 2)
+    {
+        *fLog << err 
+	      << "MFindSupercutsONOFFThetaLoop::SetCosThetaRangeVector: " 
+	      << endl
+	      << "Size of d is smaller than 2... "
+	      << "fCosThetaRangeVector can not be defined properly"
+	      << endl;
+        return kFALSE;
+    }
+
+    fCosThetaRangeVector.Set(d.GetSize());
+    fCosThetaRangeVector = d;
+
+
+    
+
+    // fCosThetaBinCenterVector is defined
+
+    Int_t dim = fCosThetaRangeVector.GetSize() - 1;
+    fCosThetaBinCenterVector.Set(dim);
+
+    for (Int_t i = 0; i < dim; i++)
+    {
+	fCosThetaBinCenterVector[i] = 
+	    (fCosThetaRangeVector[i+1]+fCosThetaRangeVector[i])/2;
+    }
+
+    return kTRUE;
+}
+
+// Function that sets the range of Theta (fThetaMin, fThetaMax) 
+// where data will be used in the iteration 
+// thetabin. This theta range is used when geting data from 
+// file and filling matrices. If matrices are already built 
+// and just read from root files, this theta range is useless. 
+
+
+// **** IMPORTANT *********
+// thetabin is an integer  value that goes from 1 to 
+// fCosThetaBinCenterVector.GetSize()
+// ************************
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetThetaRange (Int_t thetabin)
+{
+    // Check that iteration thetabin is smaller than 
+    // components of fCosThetaBinCenterVector
+   
+    if (fCosThetaRangeVector.GetSize() < 2 ||
+	fCosThetaBinCenterVector.GetSize() < 1)
+	
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::SetThetaRange; " << endl
+	      << "Dimension of vectors fCosThetaRangeVector or/and " 
+	      << "fCosThetaBinCenterVector are smaller than 2 and 1 " 
+	      << "respectively. Range for theta can not be defined." << endl;
+	
+	return kFALSE;
+    }
+    
+    if (thetabin < 1 || 
+	thetabin > fCosThetaBinCenterVector.GetSize())
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::SetThetaRange; " << endl
+	      << "thetabin value is " << thetabin 
+	      << " Is is outside the possible values given by " 
+	      << "vector fCosThetaRangeVector. "
+	      << "Range for theta can not be defined." << endl;
+	
+	return kFALSE;
+    }
+    
+    
+    fThetaMin = fCosThetaRangeVector[thetabin-1];
+    fThetaMax = fCosThetaRangeVector[thetabin];
+    
+
+    // Now costheta values have to be converted to Radians
+    // Function TMath::ACos(x) gives angle in Radians
+    
+    
+    fThetaMin = TMath::ACos(fThetaMin);
+    fThetaMax = TMath::ACos(fThetaMax);
+
+   
+    // For new MAGIC (July 2004), angles are given in degrees.
+    // So I convert angles into degrees by multiplying by a the 
+    // conversion rad/degree
+
+    fThetaMin = fThetaMin * TMath::RadToDeg();
+    fThetaMax = fThetaMax * TMath::RadToDeg();
+
+
+
+    // If fThetaMin > fThetaMax means that fCosThetaRangeVector
+    // is defined with increasing values of CosTheta, which 
+    // means decreasing values of Theta
+
+    // In such case, values of fThetaMin and fThetaMax are swapped
+
+    if (fThetaMin > fThetaMax)
+    {
+	Double_t tmp = fThetaMin;
+	fThetaMin = fThetaMax;
+	fThetaMax = tmp;
+    }
+
+    // Info for user
+    *fLog << "-------------------------------------------------"<< endl
+	  << "MFindSupercutsONOFFThetaLoop::SetThetaRange; " << endl
+	  << "Theta range for this iteration is set to "
+	  << fThetaMin << "-" << fThetaMax << " degrees." << endl 
+	  << "-------------------------------------------------"<< endl;
+    
+    return kTRUE;
+
+
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetNormFactorTrainHist()
+{
+    if (fCosThetaRangeVector.GetSize() <= 1)
+    {
+        *fLog << err << "MFindSupercutsONOFFThetaLoop::SetNormFactorTrainHist: " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is <=1 ... fCosThetaRangeVector must exist and have, at least, 2 components defining a single bin"
+	      << endl;
+        return kFALSE;
+    }
+
+    
+    Int_t HistoNbins = fCosThetaRangeVector.GetSize() - 1;
+    Double_t* BinsVector = fCosThetaRangeVector.GetArray();
+
+    fNormFactorTrainHist = new TH1F ("NormFactorTrainHist",
+				     "NormFactorTrainHist",
+				     HistoNbins,BinsVector );
+
+    return kTRUE;
+
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetNormFactorTestHist()
+{
+    if (fCosThetaRangeVector.GetSize() <= 1)
+    {
+        *fLog << err << "MFindSupercutsONOFFThetaLoop::SetNormFactorTestHist: " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is <=1 ... fCosThetaRangeVector must exist and have, at least, 2 components defining a single bin"
+	      << endl;
+        return kFALSE;
+    }
+
+
+    Int_t HistoNbins = fCosThetaRangeVector.GetSize() - 1;
+    Double_t* BinsVector = fCosThetaRangeVector.GetArray();
+
+    fNormFactorTestHist = new TH1F ("NormFactorTestHist",
+				     "NormFactorTestHist",
+				     HistoNbins, BinsVector);
+
+    return kTRUE;
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetSigmaLiMaTrainHist()
+{
+    if (fCosThetaRangeVector.GetSize() <= 1)
+    {
+        *fLog << err << "MFindSupercutsONOFFThetaLoop::SetSigmaLiMaTrainHist: " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is <=1 ... fCosThetaRangeVector must exist and have, at least, 2 components defining a single bin"
+	      << endl;
+        return kFALSE;
+    }
+
+
+    // At some point, definition of bins should be able to 
+    // contain variable bins...
+
+    Int_t HistoNbins = fCosThetaRangeVector.GetSize() - 1;
+    
+    Double_t* BinsVector = fCosThetaRangeVector.GetArray();
+
+    fSigmaLiMaTrainHist = new TH1F ("SigmaLiMaTrainHist",
+				     "SigmaLiMaTrainHist",
+				     HistoNbins, BinsVector);
+
+    return kTRUE;
+}
+
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetSigmaLiMaTestHist()
+{
+    if (fCosThetaRangeVector.GetSize() <= 1)
+    {
+        *fLog << err << "MFindSupercutsONOFFThetaLoop::SetSigmaLiMaTestHist: " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is <=1 ... fCosThetaRangeVector must exist and have, at least, 2 components defining a single bin"
+	      << endl;
+        return kFALSE;
+    }
+
+
+   
+    Int_t HistoNbins = fCosThetaRangeVector.GetSize() - 1;
+    
+    Double_t* BinsVector = fCosThetaRangeVector.GetArray();
+    fSigmaLiMaTestHist = new TH1F ("SigmaLiMaTestHist",
+				     "SigmaLiMaTestHist",
+				     HistoNbins, BinsVector);
+
+    return kTRUE;
+
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetNexTrainHist()
+{
+    if (fCosThetaRangeVector.GetSize() <= 1)
+    {
+        *fLog << err << "MFindSupercutsONOFFThetaLoop::SetNexTrainHist: " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is <=1 ... fCosThetaRangeVector must exist and have, at least, 2 components defining a single bin"
+	      << endl;
+        return kFALSE;
+    }
+
+
+    Int_t HistoNbins = fCosThetaRangeVector.GetSize() - 1;
+    
+    Double_t* BinsVector = fCosThetaRangeVector.GetArray();
+
+    fNexTrainHist = new TH1F ("NexTrainHist",
+			      "NexTrainHist",
+			      HistoNbins, BinsVector);
+
+    return kTRUE;
+
+}
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetNexTestHist()
+{
+    if (fCosThetaRangeVector.GetSize() <= 1)
+    {
+        *fLog << err << "MFindSupercutsONOFFThetaLoop::SetNexTestHist: " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is <=1 ... fCosThetaRangeVector must exist and have, at least, 2 components defining a single bin"
+	      << endl;
+        return kFALSE;
+    }
+
+
+    Int_t HistoNbins = fCosThetaRangeVector.GetSize() - 1;
+    Double_t* BinsVector = fCosThetaRangeVector.GetArray();
+
+    fNexTestHist = new TH1F ("NexTestHist",
+			     "NexTestHist",
+			     HistoNbins, BinsVector);
+
+    return kTRUE;
+
+}
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetSuccessfulThetaBinsHist()
+{
+    if (fCosThetaRangeVector.GetSize() <= 1)
+    {
+        *fLog << err << "MFindSupercutsONOFFThetaLoop::SetSuccessfulThetaBinsHist(): " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is <=1 ... "
+	      << "fCosThetaRangeVector must exist and have >= 2 components (defining a single bin)"
+	      << endl;
+        return kFALSE;
+    }
+
+
+    Int_t HistoNbins = fCosThetaRangeVector.GetSize() - 1;
+    Double_t* BinsVector = fCosThetaRangeVector.GetArray();
+
+    fSuccessfulThetaBinsHist = new TH1F ("SuccessfulThetaBinsHist",
+					 "SuccessfulThetaBinsHist",
+					 HistoNbins, BinsVector);
+
+    return kTRUE;
+
+}
+
+
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetNexSigmaLiMaNormFactorNEvtsTrainTestHist()
+{
+    if (fCosThetaRangeVector.GetSize() <= 1)
+    {
+        *fLog << err 
+	      << "MFindSupercutsONOFFThetaLoop::SetNexSigmaLiMaNormFactorTrainTestHist: " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is <=1 ... " 
+	      << "fCosThetaRangeVector must exist and have, at least, "
+	      << "2 components defining a single bin"
+	      << endl;
+        return kFALSE;
+    }
+
+
+    Int_t HistoNbins = fCosThetaRangeVector.GetSize() - 1;
+    
+    Double_t* BinsVector = fCosThetaRangeVector.GetArray();
+
+    char* x_axis_title = {"Cos(Theta)"};
+
+    fNormFactorTrainHist = new TH1F ("NormFactorTrainHist",
+				     "NormFactorTrainHist",
+				     HistoNbins, BinsVector);
+
+    
+    fNormFactorTrainHist -> SetXTitle(x_axis_title);
+    fNormFactorTrainHist -> SetYTitle("Normalization Factor (Non/Noff)");
+    
+
+    fNormFactorTestHist = new TH1F ("NormFactorTestHist",
+				     "NormFactorTestHist",
+				     HistoNbins, BinsVector);
+
+    fNormFactorTestHist -> SetXTitle(x_axis_title);
+    fNormFactorTestHist -> SetYTitle("Normalization Factor (Non/Noff)");
+
+    fSigmaLiMaTrainHist = new TH1F ("SigmaLiMaTrainHist",
+				     "SigmaLiMaTrainHist",
+				     HistoNbins, BinsVector);
+
+    fSigmaLiMaTrainHist -> SetXTitle(x_axis_title);
+    fSigmaLiMaTrainHist -> SetYTitle("Significance");
+
+
+    fSigmaLiMaTestHist = new TH1F ("SigmaLiMaTestHist",
+				   "SigmaLiMaTestHist",
+				   HistoNbins, BinsVector);
+
+    fSigmaLiMaTestHist -> SetXTitle(x_axis_title);
+    fSigmaLiMaTestHist -> SetYTitle("Significance");
+
+
+
+    fNexTrainHist = new TH1F ("NexTrainHist",
+			      "NexTrainHist",
+			      HistoNbins, BinsVector);
+
+    fNexTrainHist -> SetXTitle(x_axis_title);
+    fNexTrainHist -> SetYTitle("Excess Events");
+
+
+    fNexTestHist = new TH1F ("NexTestHist",
+			     "NexTestHist",
+			     HistoNbins, BinsVector);
+
+    fNexTestHist -> SetXTitle(x_axis_title);
+    fNexTestHist -> SetYTitle("Excess Events");
+
+
+
+    fNEvtsInTrainMatrixONHist = new TH1F("NEvtsInTrainMatrixONHist",
+					 "NEvtsInTrainMatrixONHist", 
+					 HistoNbins, BinsVector);
+
+
+    fNEvtsInTrainMatrixONHist -> SetXTitle(x_axis_title);
+    fNEvtsInTrainMatrixONHist -> SetYTitle("Number of ON Events");
+    
+
+    fNEvtsInTestMatrixONHist = new TH1F("NEvtsInTestMatrixONHist",
+					 "NEvtsInTestMatrixONHist", 
+					 HistoNbins, BinsVector);
+
+    fNEvtsInTestMatrixONHist -> SetXTitle(x_axis_title);
+    fNEvtsInTestMatrixONHist -> SetYTitle("Number of ON Events");
+    
+
+    fNEvtsInTrainMatrixOFFHist = new TH1F("NEvtsInTrainMatrixOFFHist",
+					  "NEvtsInTrainMatrixOFFHist", 
+					  HistoNbins, BinsVector);
+
+    fNEvtsInTrainMatrixOFFHist -> SetXTitle(x_axis_title);
+    fNEvtsInTrainMatrixOFFHist -> SetYTitle("Number of OFF Events");
+
+
+    fNEvtsInTestMatrixOFFHist = new TH1F("NEvtsInTestMatrixOFFHist",
+					 "NEvtsInTestMatrixOFFHist", 
+					 HistoNbins, BinsVector);
+
+    fNEvtsInTestMatrixOFFHist -> SetXTitle(x_axis_title);
+    fNEvtsInTestMatrixOFFHist -> SetYTitle("Number of OFF Events");
+    
+
+    
+
+
+    return kTRUE;
+
+}
+
+void MFindSupercutsONOFFThetaLoop::WriteSuccessfulThetaBinsHistToFile()
+{
+    *fLog << "MFindSupercutsONOFFThetaLoop : Writing histogram "
+	  << " 'SuccessfulThetaBinsHist'"
+	  << " (if contents != 0) into root file " 
+	  << fAlphaDistributionsRootFilename << endl;
+
+    TFile rootfile(fAlphaDistributionsRootFilename, "UPDATE",
+		   "Alpha Distributions for several Theta bins");
+
+
+    if (fSuccessfulThetaBinsHist)
+    {
+	if (fSuccessfulThetaBinsHist->GetEntries() > 0.5)
+	    fSuccessfulThetaBinsHist -> Write();
+    }
+
+
+    rootfile.Close();
+
+}
+
+void MFindSupercutsONOFFThetaLoop::WriteNexSigmaLiMaNormFactorNEvtsTrainTestHistToFile()
+{
+
+    *fLog << "MFindSupercutsONOFFThetaLoop : Writing histograms 'NexSigmaLiMaNormFactorNEvtsTrainTest'"
+	  << " (if they have contents != 0) into root file " 
+	  << fAlphaDistributionsRootFilename << endl;
+
+    TFile rootfile(fAlphaDistributionsRootFilename, "UPDATE",
+		   "Alpha Distributions for several Theta bins");
+
+
+    if (fNormFactorTrainHist)
+    {
+	if (fNormFactorTrainHist->GetEntries() > 0.5)
+	    fNormFactorTrainHist -> Write();
+    }
+
+    if (fNormFactorTestHist)
+    {
+	if (fNormFactorTestHist->GetEntries() > 0.5)
+	    fNormFactorTestHist -> Write();
+    }
+
+    if (fSigmaLiMaTrainHist)
+    {
+	if (fSigmaLiMaTrainHist->GetEntries() > 0.5)
+	    fSigmaLiMaTrainHist -> Write();
+    }
+
+    if (fSigmaLiMaTestHist)
+    {
+	if (fSigmaLiMaTestHist->GetEntries() > 0.5)
+	    fSigmaLiMaTestHist -> Write();
+    }
+
+    if (fNexTrainHist)
+    {
+	if (fNexTrainHist->GetEntries() > 0.5)
+	    fNexTrainHist -> Write();
+    }
+
+    if (fNexTestHist)
+    {
+	if (fNexTestHist->GetEntries() > 0.5)
+	    fNexTestHist -> Write();
+    }
+   
+
+    if (fNEvtsInTrainMatrixONHist)
+    {
+	if (fNEvtsInTrainMatrixONHist->GetEntries() > 0.5)
+	    fNEvtsInTrainMatrixONHist -> Write();
+    }
+
+    if (fNEvtsInTestMatrixONHist)
+    {
+	if (fNEvtsInTestMatrixONHist->GetEntries() > 0.5)
+	    fNEvtsInTestMatrixONHist -> Write();
+    }
+    
+    if (fNEvtsInTrainMatrixOFFHist)
+    {
+	if (fNEvtsInTrainMatrixOFFHist->GetEntries() > 0.5)
+	    fNEvtsInTrainMatrixOFFHist -> Write();
+    }
+
+
+    if (fNEvtsInTestMatrixOFFHist)
+    {
+	if (fNEvtsInTestMatrixOFFHist->GetEntries() > 0.5)
+	    fNEvtsInTestMatrixOFFHist -> Write();
+    }
+
+
+    rootfile.Close();
+
+}
+
+void  MFindSupercutsONOFFThetaLoop::SetFractionTrainTestOnOffEvents(
+    Double_t fontrain, 
+    Double_t fontest, 
+    Double_t fofftrain,
+    Double_t fofftest)
+{
+
+  // Check that fractions set by user are within the expected limits
+  
+  if (fontrain < 0.00 || fontrain > 1.00 ||
+      fontest < 0.00 || fontest > 1.00 ||
+      fofftrain < 0.00 || fofftrain > 1.00 ||
+      fofftest < 0.00 || fontest > 1.00)
+    {
+      *fLog << err 
+	    << "MFindSupercutsONOFFThetaLoop::SetFractionTrainTestOnOffEvents: " 
+	    << endl
+	    << "Fractions of ON/OFF data for TRAIN/TEST sample which were specified by user " << endl 
+	    << "are outside the natural limits 0.0-1.0. " << endl
+	    << "Set reasonable fraction numbers for TRAIN/TEST please. The program will be aborted."
+	    << endl;
+      
+      exit(1);
+
+
+    }
+  
+
+  if((fontrain+fontest) > 1.00 ||
+     (fofftrain+fofftest) >1.00)
+    
+    {
+      *fLog << err 
+	    << "MFindSupercutsONOFFThetaLoop::SetFractionTrainTestOnOffEvents: " 
+	    << endl
+	    << "The sum of the fractions of TRAIN/TEST for ON or OFF data which were specified by user " << endl 
+	    << "are larger than 1.0. " << endl
+	    << "Set reasonable fraction numbers for TRAIN/TEST please. The program will be aborted."
+	    << endl;
+      
+      exit(1);
+
+
+    }
+
+
+    fWhichFractionTrain = fontrain;
+    fWhichFractionTest = fontest;
+    fWhichFractionTrainOFF = fofftrain;
+    fWhichFractionTestOFF = fofftest;
+
+
+}
+
+void MFindSupercutsONOFFThetaLoop::SetReadMatricesFromFile (Bool_t b)
+{
+
+    *fLog << "---------------------------------------------------" << endl
+	  << "MFindSupercutsONOFFThetaLoop: " << endl;
+
+    if (b)
+    {	*fLog  << "Matrices are read from root files." << endl;}
+    else
+    {   *fLog  << "Matrices are produced and stored into root files." 
+	       << endl;
+    }
+
+
+    fReadMatricesFromFile = b;
+}
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetAlphaDistributionsRootFilename(
+    const TString &name)
+{
+
+    if (fPathForFiles.IsNull())
+    {
+	*fLog << err 
+	      << "MFindSupercutsONOFFThetaLoop::SetAlphaDistributionsRootFilename; " 
+	      << endl
+	      << "fPathForFiles is not defined yet, hence "
+	      << "name for rootfile containing alpha distributions " 
+	      << "can not be defined properly" << endl;
+
+	return kFALSE;
+    }
+
+    
+    fAlphaDistributionsRootFilename = (fPathForFiles);
+    fAlphaDistributionsRootFilename += (name);
+
+
+    *fLog << "MFindSupercutsONOFFThetaLoop: fAlphaDistributionsRootFilename = "
+	  << fAlphaDistributionsRootFilename << endl;
+
+
+    return kTRUE;
+
+
+}
+
+// Function to set Names of root files containing matrices and  
+// optimizedparameters and also fThetaRangeStringVector vector
+
+Bool_t MFindSupercutsONOFFThetaLoop::SetALLNames()
+{
+    // Names for files only possible if CosThetaRangeVector 
+    // is defined properly
+    if (fCosThetaRangeVector.GetSize() < 2)
+    {
+        *fLog << err 
+	      << "MFindSupercutsONOFFThetaLoop::SetALLNames; " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is smaller than 2... "
+	      << "fCosThetaRangeVector is not defined properly, "
+	      << "and thus, names for rootfiles containing data matrices "
+	      << "and optimized parameters for the different theta "
+	      << "ranges can not defined properly." << endl;
+ 
+        return kFALSE;
+    }
+
+    if (fPathForFiles.IsNull())
+    {
+	*fLog << err 
+	      << "MFindSupercutsONOFFThetaLoop::Setnames; " 
+	      << endl
+	      << "fPathForFiles is not defined yet, hence "
+	      << "names for rootfiles containing data matrices "
+	      << "and optimized parameters for the different theta "
+	      << "ranges can not defined properly." << endl;
+
+	return kFALSE;
+    }
+
+
+     // Name of rootfiles for Supercuts parameters follow the 
+    // follwing structure
+
+    // Path + "OptSCParametersONOFF" + "ThetaRange" 
+    // + int {(fThetaMin_fThetaMax)} + ".root"
+
+
+    // Name of rootfiles for Matrices follow the follwing structure
+
+    // Path + "ON(OFF)Data" + "Train(Test)" + "Matrix" + Fraction 
+    // + "ThetaRange" + int {(fThetaMin_fThetaMax)} + ".root"
+
+
+    Int_t tmpdim = fCosThetaRangeVector.GetSize() - 1;
+    const Int_t VectorDimension = tmpdim;
+
+    fThetaRangeStringVector = new TString[VectorDimension];
+
+    fOptSCParamFilenameVector = new TString[VectorDimension];
+
+    fTrainMatrixONFilenameVector = new TString[VectorDimension];
+    fTestMatrixONFilenameVector = new TString[VectorDimension];
+    fTrainMatrixOFFFilenameVector = new TString[VectorDimension];
+    fTestMatrixOFFFilenameVector = new TString[VectorDimension];
+
+
+    //    Int_t ThetaMinTimes1000 = 0;
+    // Int_t ThetaMaxTimes1000 = 0;
+
+    // For MAGIC new (July 2004) Theta is given in deg
+
+    Int_t ThetaMinInt = 0;
+    Int_t ThetaMaxInt = 0;
+
+
+    Int_t FractionONTrainTimes100 = 0;
+    Int_t FractionONTestTimes100 = 0;
+    Int_t FractionOFFTrainTimes100 = 0;
+    Int_t FractionOFFTestTimes100 = 0;
+
+    char ThetaRangeString[100];
+
+    for (Int_t i = 0; i < VectorDimension; i++)
+    {
+	if (!SetThetaRange(i+1))
+	{
+	    *fLog << "MFindSupercutsONOFFThetaLoop::SetALLNames; " 
+		  << endl
+		  << "Values for fThetaMin and fThetaMax could NOT "
+		  << "be computed for theta bin " 
+		  << (i+1) << "; SetNames can not go on successfully."
+		  << endl;
+
+	    return kFALSE;
+	}
+	
+	
+	//ThetaMinTimes1000 = int(fThetaMin*1000);
+	//ThetaMaxTimes1000 = int(fThetaMax*1000);
+	//sprintf(ThetaRangeString, "ThetaRange%d_%dmRad", 
+	//	ThetaMinTimes1000, ThetaMaxTimes1000);
+
+	// For New MAGIC (July 2004)
+	// Theta is given in deg, no need to multiply by 1000
+	
+	// 0.5 is added so that the rounding to integer is correct
+	ThetaMinInt = int(fThetaMin + 0.5);
+	ThetaMaxInt = int(fThetaMax + 0.5);
+	sprintf(ThetaRangeString, "ThetaRange%d_%d_Degrees", 
+		ThetaMinInt, ThetaMaxInt);
+
+	
+
+	fThetaRangeStringVector[i] = (ThetaRangeString);
+	
+	// tmp
+	*fLog << "ThetaRangeString = " << fThetaRangeStringVector[i] << endl;
+	// endtmp
+
+	// 0.5 is added so that the rounding to integer is correct
+
+	FractionONTrainTimes100 = int(fWhichFractionTrain*100 + 0.5);
+	FractionONTestTimes100 = int(fWhichFractionTest*100 + 0.5);
+	FractionOFFTrainTimes100 = int(fWhichFractionTrainOFF*100 + 0.5);
+	FractionOFFTestTimes100 = int(fWhichFractionTestOFF*100 + 0.5);
+	  
+
+	
+	
+
+	// File for SC parameters 
+	fOptSCParamFilenameVector[i] = (fPathForFiles);
+	fOptSCParamFilenameVector[i] += ("OptSCParametersONOFF");
+	fOptSCParamFilenameVector[i] += (fThetaRangeStringVector[i]);
+	fOptSCParamFilenameVector[i] += (".root");
+	
+	
+	
+	// File for Data Matrices
+
+	fTrainMatrixONFilenameVector[i] = (fPathForFiles);
+	fTrainMatrixONFilenameVector[i] += ("ONDataTrainMatrixFraction");
+	fTrainMatrixONFilenameVector[i] += (FractionONTrainTimes100);
+	fTrainMatrixONFilenameVector[i] += (fThetaRangeStringVector[i]);
+	fTrainMatrixONFilenameVector[i] += (".root");
+
+	fTestMatrixONFilenameVector[i] = (fPathForFiles);
+	fTestMatrixONFilenameVector[i] += ("ONDataTestMatrixFraction");
+	fTestMatrixONFilenameVector[i] += (FractionONTestTimes100);
+	fTestMatrixONFilenameVector[i] += (fThetaRangeStringVector[i]);
+	fTestMatrixONFilenameVector[i] += (".root");
+
+
+	fTrainMatrixOFFFilenameVector[i] = (fPathForFiles);
+	fTrainMatrixOFFFilenameVector[i] += ("OFFDataTrainMatrixFraction");
+	fTrainMatrixOFFFilenameVector[i] += (FractionOFFTrainTimes100);
+	fTrainMatrixOFFFilenameVector[i] += (fThetaRangeStringVector[i]);
+	fTrainMatrixOFFFilenameVector[i] += (".root");
+
+	fTestMatrixOFFFilenameVector[i] = (fPathForFiles);
+	fTestMatrixOFFFilenameVector[i] += ("OFFDataTestMatrixFraction");
+	fTestMatrixOFFFilenameVector[i] += (FractionOFFTestTimes100);
+	fTestMatrixOFFFilenameVector[i] += (fThetaRangeStringVector[i]);
+	fTestMatrixOFFFilenameVector[i] += (".root");
+
+    }
+    // Info concerning names is printed
+    
+    *fLog << "--------------------------------------------------" << endl
+	  << "MFindSupercutsONOFFThetaLoop::Setnames; " 
+	  << endl
+	  << "Names for root files containing Opt SC Param. and Data "
+	  << "matrices for the different theta bins are the "
+	  << "following ones: " << endl
+	  << "MeanCosTheta, OptSCParm, ONDataTrainMatrix, ..." << endl;
+    
+    for (Int_t i = 0; i < VectorDimension; i++)
+    {
+	*fLog << fCosThetaBinCenterVector[i] << ",  " << endl
+	      << fOptSCParamFilenameVector[i] << ",  "<< endl
+	      << fTrainMatrixONFilenameVector[i] << ",  " << endl
+	      << fTestMatrixONFilenameVector[i] << ",  " << endl
+	      << fTrainMatrixOFFFilenameVector[i] << ",  " << endl
+	      << fTestMatrixOFFFilenameVector[i] << ",  " << endl
+	      << endl << endl;
+    }
+    
+    *fLog << "--------------------------------------------------" << endl;
+    
+    return kTRUE;
+    
+}
+
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges()
+{
+
+
+    *fLog << "--------------------------------------------------------------" << endl
+	  << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges function starts " 
+	  << endl;
+	  
+
+
+    if (fDataONRootFilename.IsNull())
+    {
+      *fLog << "MFindSupercutsONOFF::LoopOverThetaRanges; root file for ON data is not defined... " 
+	    << "aborting..."
+            << endl;
+      return kFALSE;
+    }
+
+
+    if (fDataOFFRootFilename.IsNull())
+    {
+      *fLog << "MFindSupercutsONOFF:: LoopOverThetaRanges; root file for OFF data is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    
+    if (fHadronnessName.IsNull())
+    {
+      *fLog << "MFindSupercutsONOFF::LoopOverThetaRanges; hadronness name for ON data is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+
+    if (fHadronnessNameOFF.IsNull())
+    {
+      *fLog << "MFindSupercutsONOFF::LoopOverThetaRanges; hadronness name for OFF data is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+
+    if (fCosThetaRangeVector.GetSize() < 2)
+	
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+	      << "Dimension of vector fCosThetaRangeVector " 
+	      << "is smaller than 2" 
+	      << "Theta ranges are not well defined... aborting ..." << endl;
+	
+	return kFALSE;
+    }
+
+
+    // Check if pointers to root file names (opt SC parameters and matrices) 
+    // are empty
+
+
+    if (!fTrainMatrixONFilenameVector || 
+	!fTestMatrixONFilenameVector ||
+	!fTrainMatrixOFFFilenameVector ||
+	!fTestMatrixOFFFilenameVector ||
+	!fOptSCParamFilenameVector)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+	      << "Pointers to root files names for Opt SC parameters and data "
+	      << "matrices are not well defined. Aborting... " << endl;
+
+	return kFALSE;
+    }
+
+
+    if (fAlphaDistributionsRootFilename.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+	      << "Root filename where to store alpha distributions "
+	      << "(fAlphaDistributionsRootFilename) is not defined." << endl
+	      << "Loop over theta angles can not go on..." << endl;
+
+	return kTRUE;
+    }
+
+
+    
+	
+    if (!fPsFilename)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+	      << "Object from Class TPostScript is not defined. "
+	      << "Plots will be stored in a a file named 'PsFilesTmp.ps' located "
+	      << "in current directory" << endl;
+
+	// fPsFilename = new TPostScript("PsFilesTmp.ps" ,111);
+
+
+    }
+
+
+    
+
+
+
+    // All drinks are in house... the party starts !!
+
+    Int_t ThetaLoopIterations = fCosThetaRangeVector.GetSize() - 1;
+                                
+    *fLog << "looping over the following Cos Theta Angle Ranges : "<< endl;
+    for (Int_t i = 0; i < ThetaLoopIterations; i++)
+    {
+	*fLog << i+1 << " -> " 
+	      << fCosThetaRangeVector[i] << "-" << fCosThetaRangeVector[i+1] 
+	      << endl;
+    }
+	  
+    *fLog << "--------------------------------------------------------------------" 
+	  << endl;
+
+
+
+    // Let's create histograms where SigmaLiMa, Nex and Normfactors will be stored
+
+    if (!SetNexSigmaLiMaNormFactorNEvtsTrainTestHist())
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+	      << "Histograms where to store Significances, Nex and Normalization "
+	      << "factors, NEvts for all theta bins could not be created... Aborting."
+	      << endl;
+
+	return kFALSE;
+    }
+
+
+    // Let's create histogram where successfully optimized theta bins will be stored
+
+    if (!SetSuccessfulThetaBinsHist())
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+	      << "Histogram where to store successfully optimized theta bins "
+	      << " could not be created... Aborting."
+	      << endl;
+
+	return kFALSE;
+    }
+
+
+    
+
+
+    Double_t NormFactor = 0.0;
+    Double_t Nex = 0.0;
+    Double_t SigmaLiMa = 0.0;
+    Int_t NEvtsON = 0;
+    Int_t NEvtsOFF = 0;
+    
+    Bool_t MinimizationSuccessful = kTRUE;
+    Double_t MinimizationValue = 1.0; // Value quantifying the minimization, and stored in 
+    // histogram fSuccessfulThetaBinsHist. For the time being it is 0.0 (minimization failed). 
+    // and 1.0 (minimization succeeded). Yet in future it may take other values quantifying 
+    // other aspects...
+
+
+    for (Int_t i = 0; i < ThetaLoopIterations; i++)
+    {
+
+	// Get the Theta range that will be used in this iteration
+	// Remember that argument of the function is iteration number, 
+	// and it starts at 1...
+
+	if (!SetThetaRange(i+1))
+	{
+	    *fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " 
+		  << endl
+		  << "Values for fThetaMin and fThetaMax could NOT "
+		  << "be computed for theta bin " 
+		  << (i+1) << ";  LoopOverThetaRanges is aborting."
+		  << endl;
+
+	    return kFALSE;
+	}
+	
+
+
+	// Object of class MFindSupercutsONOFF will be created and used 
+
+
+	MFindSupercutsONOFF FindSupercuts("MFindSupercutsONOFF", 
+					     "Optimizer for the supercuts");
+
+	
+	// Set Theta range that will be used
+	FindSupercuts.SetThetaRange(fThetaMin, fThetaMax);
+
+
+	// Alphamax where signal is expected is set
+	FindSupercuts.SetAlphaSig(fAlphaSig);
+
+	// Bkg alpha region is set 
+	FindSupercuts.SetAlphaBkgMin(fAlphaBkgMin);
+	FindSupercuts.SetAlphaBkgMax(fAlphaBkgMax);
+
+	// alpha bkg and signal region set in object FindSupercuts
+	// are re-checked in order to be sure that make sense
+	
+	FindSupercuts.CheckAlphaSigBkg();
+
+
+	// Degree of polynomials used to fit ON and OFF alpha 
+	// distributions is set
+
+	FindSupercuts.SetDegreeON(fDegreeON);
+	FindSupercuts.SetDegreeOFF(fDegreeOFF);
+
+
+
+
+	// bining for alpha plots is set 
+	
+	FindSupercuts.SetAlphaPlotBinining(fNAlphaBins, fAlphaBinLow, fAlphaBinUp);
+
+
+
+	
+	// Bool variable NormFactorFromAlphaBkg is set in FindSupercuts
+	// in order to decide the way in which mormalization factors
+	// for TRAIN and TEST samples are computed
+
+
+	FindSupercuts.SetNormFactorFromAlphaBkg(fNormFactorFromAlphaBkg);
+
+
+	// Define size range of events used to fill the data matrices
+
+	FindSupercuts.SetSizeRange(fSizeCutLow, fSizeCutUp);
+
+        FindSupercuts.SetFilters(fLeakMax, fDistMax, fDistMin);
+
+
+	
+	// Boolean variable that controls wether the optimization of the 
+	// parameters (MMinuitInterface::CallMinuit(..) in function FindParams(..))
+	// takes place or not. kTRUE will skip such optimization.
+	// This variable is useful to test the optmized parameters (previously found 
+	// and stored in root file) on the TRAIN sample.
+
+	FindSupercuts.SetSkipOptimization(fSkipOptimization);
+
+	// Boolean variable that allows the user to write the initial parameters 
+	// into the root file that will be used to store the optimum cuts.
+	// If fUseInitialSCParams = kTRUE , parameters are written.
+	// In this way, the initial SC parameters can be applied on the data (train/test)
+
+	FindSupercuts.SetUseInitialSCParams(fUseInitialSCParams);
+
+
+        // Set boolean variable that controls wether the theta variable 
+	// is used or not in the computation of the dynamica cuts
+
+	FindSupercuts.SetVariableNotUseTheta(fNotUseTheta);
+
+	// Set boolean variable that controls wether cuts are dynamical 
+	// or static.
+
+	FindSupercuts.SetVariableUseStaticCuts(fUseStaticCuts);
+
+	
+	FindSupercuts.SetUseFittedQuantities(fUseFittedQuantities);
+
+	                                        
+	// fGammaEfficiency is set in object FindSupercuts
+
+	FindSupercuts.SetGammaEfficiency (fGammaEfficiency);
+
+
+	// Filename with SuperCuts parameters is set
+
+	FindSupercuts.SetFilenameParam(fOptSCParamFilenameVector[i]);
+
+	// Hadroness containers are set
+	
+	FindSupercuts.SetHadronnessName(fHadronnessName);
+	FindSupercuts.SetHadronnessNameOFF(fHadronnessNameOFF);
+    
+	// Rootfilename where to store alpha distribution histograms is set
+
+	FindSupercuts.SetAlphaDistributionsRootFilename(fAlphaDistributionsRootFilename);
+
+
+	// Set the names of all trees 
+        // used to store the supercuts applied to ON/OFF Train/Test samples
+
+	// In future, names might be controlled by user, but for the time 
+	// being I'll make things simple, and names are set to some defaults 
+	// taking into account the theta range used
+	
+	// Containers will be stored in rootfile specified by variable 
+	// fAlphaDistributionsRootFilename
+
+	FindSupercuts.SetSupercutsAppliedTreeNames();
+
+
+
+
+
+	// Object of the class TPostScritp is set...
+	// BUT THAT'S NOT WORKING PROPERLY !!!!!
+
+	// FindSupercuts.SetPostScriptFile (fPsFilename);
+
+	// ********************************************************
+	// Due to the failure of the use of object TPostScript
+	// to make a Ps document with all plots, I decided to use the 
+	// standard way (SaveAs(filename.ps)) to store plots related 
+	// to alpha distributions 
+	// for ON and OFF and BEFORE and AFTER cuts (VERY IMPORTANT
+	// TO COMPUTE EFFICIENCIES IN CUTS) 
+
+	// Psfilename is set inside function LoopOverThetaRanges()
+	// and given to the object MFindSupercutsONOFF created 
+	// within this loop.
+
+	// This will have to be removed as soon as the TPostScript
+	// solutions works...
+	// ********************************************************
+
+	TString PsFilenameString = (fPathForFiles);
+	PsFilenameString += ("SC");
+	PsFilenameString += (fThetaRangeStringVector[i]);
+	// Name to be completed inside object MFindSupercutsONOFF
+
+	FindSupercuts.SetPsFilenameString(PsFilenameString);
+
+
+	if (fReadMatricesFromFile)
+	{
+	    *fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+		  << "Reading Data matrices from root files... " << endl;
+
+	    /*
+	    FindSupercuts.ReadMatrix(fTrainMatrixONFilenameVector[i], 
+				     fTestMatrixONFilenameVector[i]);
+	    FindSupercuts.ReadMatrixOFF(fTrainMatrixOFFFilenameVector[i], 
+					fTestMatrixOFFFilenameVector[i]);
+	    */
+
+	    FindSupercuts.ReadMatrixTrain(fTrainMatrixONFilenameVector[i], 
+					  fTrainMatrixOFFFilenameVector[i]);
+
+	    if (fTestParameters)
+	      {
+		FindSupercuts.ReadMatrixTest(fTestMatrixONFilenameVector[i], 
+					     fTestMatrixOFFFilenameVector[i]);
+	      }
+
+	}
+
+	else
+	{
+	    *fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+		  << "Reading Data from files " << fDataONRootFilename 
+		  << " and " << fDataOFFRootFilename << "(for ON and OFF data "
+		  << "respectively " 
+		  << " and producing data matrices that will be stored "
+		  << "in root files. " << endl;
+
+	    // ON data 
+	    
+	    FindSupercuts.DefineTrainTestMatrixThetaRange(
+		fDataONRootFilename,
+		fWhichFractionTrain,
+		fWhichFractionTest, 
+		fThetaMin, fThetaMax, 
+		fTrainMatrixONFilenameVector[i], 
+		fTestMatrixONFilenameVector[i]);
+
+	    // OFF data
+	    
+	    FindSupercuts.DefineTrainTestMatrixOFFThetaRange(
+		fDataOFFRootFilename,
+		fWhichFractionTrainOFF,
+		fWhichFractionTestOFF, 
+		fThetaMin, fThetaMax, 
+		fTrainMatrixOFFFilenameVector[i], 
+		fTestMatrixOFFFilenameVector[i]);
+	    
+	}
+
+
+	MinimizationSuccessful = kTRUE;
+	
+	if (fOptimizeParameters)
+	{
+	    MinimizationSuccessful = 
+		FindSupercuts.FindParams("",fInitSCPar, fInitSCParSteps); 
+	    
+	    if (MinimizationSuccessful)
+	    {
+		// Minimization was successful	
+		// NormFactor, Nex, SigmaLiMa and NEvts Train histograms are updated 
+
+		*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " 
+		      << endl
+		      << "Minimization was successful" << endl
+		      << "Updating values for NormFactor, Nex, SigmaLiMa and NEvts " 
+		      << "Train histograms for " <<  fThetaRangeStringVector[i] << endl;
+		
+		
+		NormFactor = FindSupercuts.GetNormFactorTrain();
+		SigmaLiMa = FindSupercuts.GetSigmaLiMaTrain();
+		Nex = FindSupercuts.GetNexTrain();
+		
+		NEvtsON = FindSupercuts.GetMatrixTrain()->GetM().GetNrows();
+		NEvtsOFF = FindSupercuts.GetMatrixTrainOFF()->GetM().GetNrows();
+
+		// MinimizationValue is updated...
+
+		MinimizationValue = 1.0;		
+
+	    }
+	    else
+	    {
+		// Minimization was NOT successful	
+		// NormFactor, Nex, SigmaLiMa and NEvts Train histograms are updated 
+
+		*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " 
+		      << endl
+		      << "Minimization was NOT successful" << endl
+		      << "Updating values for NormFactor, and NEvts " 
+		      << "Train histograms for " <<  fThetaRangeStringVector[i] << endl
+		      << "Nex and SigmaLiMa are set to ZERO" << endl;
+		
+		
+		NormFactor = FindSupercuts.GetNormFactorTrain();
+		
+		NEvtsON = FindSupercuts.GetMatrixTrain()->GetM().GetNrows();
+		NEvtsOFF = FindSupercuts.GetMatrixTrainOFF()->GetM().GetNrows();
+
+		SigmaLiMa = 0.0;
+		Nex = 0.0;
+		
+		// MinimizationValue is updated...
+
+		MinimizationValue = 0.0;
+
+	    }
+
+
+	    
+	    cout << "---- Train Histograms will be updated with the following numbers: ------ " 
+		 << endl
+		 << "Mean CosTheta for this Thetabin = " 
+		 << fCosThetaBinCenterVector[i] << endl
+		 << "Minimization status (1.0 is successful, 0.0 is UNsuccessful) = "
+		 << MinimizationValue << endl
+		 << "Number of ON Events in Train sample used = "
+		 << NEvtsON << endl
+		 << "Number of OFF Events in Train sample used = "
+		 << NEvtsOFF << endl
+		 << "Normalization factor (Non/Noff) for Train sample = "
+		 << NormFactor << endl 
+		 << "Excess events and SigmaLiMa: "
+		 << Nex << "; " << SigmaLiMa << endl << endl;
+		 
+	    
+
+	    fNormFactorTrainHist -> Fill(fCosThetaBinCenterVector[i], 
+					  NormFactor);
+	    
+	    fNexTrainHist -> Fill(fCosThetaBinCenterVector[i], 
+				   Nex);
+
+	    fSigmaLiMaTrainHist -> Fill(fCosThetaBinCenterVector[i], 
+					 SigmaLiMa);
+
+
+	    fNEvtsInTrainMatrixONHist -> Fill(fCosThetaBinCenterVector[i], 
+					 NEvtsON);
+
+	    fNEvtsInTrainMatrixOFFHist -> Fill(fCosThetaBinCenterVector[i], 
+						NEvtsOFF);
+
+	    
+	    fSuccessfulThetaBinsHist -> Fill(fCosThetaBinCenterVector[i],
+					     MinimizationValue);
+	    
+	    cout << "Histograms (TRAIN) updated successfully " << endl;
+	    
+
+	    
+	    
+	}
+	
+	
+	if (fTestParameters && MinimizationSuccessful)
+	{
+	    
+	    // Cuts are applied to test sample
+	    
+	    FindSupercuts.TestParamsOnTestSample();
+
+	    // NormFactor, Nex and SigmaLiMa Test histograms are updated 
+
+	    *fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+		  << "Updating values for NormFactor, Nex, SigmaLiMa and NEvts " 		  
+		  << "Test histograms for " <<  fThetaRangeStringVector[i] << endl;
+
+
+	    NormFactor = FindSupercuts.GetNormFactorTest();
+	    SigmaLiMa = FindSupercuts.GetSigmaLiMaTest();
+	    Nex = FindSupercuts.GetNexTest();
+
+	    NEvtsON = FindSupercuts.GetMatrixTest()->GetM().GetNrows();
+	    NEvtsOFF = FindSupercuts.GetMatrixTestOFF()->GetM().GetNrows();
+
+
+       cout << "---- Test Histograms will be updated with the following numbers: ------ " 
+	    << endl
+		 << "Mean CosTheta for this Thetabin = " 
+		 << fCosThetaBinCenterVector[i] << endl
+		 << "Number of ON Events in Test sample used = "
+		 << NEvtsON << endl
+		 << "Number of OFF Events in Test sample used = "
+		 << NEvtsOFF << endl
+		 << "Normalization factor (Non/Noff) for Test sample = "
+		 << NormFactor << endl 
+		 << "Excess events and SigmaLiMa: "
+		 << Nex << "; " << SigmaLiMa << endl << endl;
+		 
+
+
+
+	    fNormFactorTestHist -> Fill(fCosThetaBinCenterVector[i], 
+					 NormFactor);
+	    
+	    fNexTestHist -> Fill(fCosThetaBinCenterVector[i], 
+				  Nex);
+
+	    fSigmaLiMaTestHist -> Fill(fCosThetaBinCenterVector[i], 
+				       SigmaLiMa);
+
+
+	    fNEvtsInTestMatrixONHist -> Fill(fCosThetaBinCenterVector[i], 
+					    NEvtsON);
+
+	    fNEvtsInTestMatrixOFFHist -> Fill(fCosThetaBinCenterVector[i], 
+					      NEvtsOFF);
+
+	    
+	    cout << "Histograms (TEST) updated successfully " << endl;
+	    
+
+
+
+	}
+
+    }
+
+
+    // PsFile is closed
+
+
+    //*fLog << "Closing PsFile ";
+    //*fLog << fPsFilename -> GetName() << endl;
+    
+    //fPsFilename -> Close();
+
+    
+
+    if (fOptimizeParameters || fTestParameters)
+    {
+	// Histograms cotanining SigmaLiMa, Nex and NormFactors and NEvts are written 
+	// in the same root file where alpha distributions where stored
+	// i.e. fAlphaDistributionsRootFilename
+	
+	*fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+	      << "Executing WriteNexSigmaLiMaNormFactorNEvtsTrainTestHistToFile()"
+	      << endl;
+
+	WriteNexSigmaLiMaNormFactorNEvtsTrainTestHistToFile();
+
+
+	if (fOptimizeParameters)
+	{   // Histogram containing minimization status for all theta bins defined 
+	    // in vector fCosThetaVector is stored in file fAlphaDistributionsRootFilename
+
+	    *fLog << "MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges; " << endl
+	      << "Executing WriteSuccessfulThetaBinsHistToFile()"
+	      << endl;
+
+	    WriteSuccessfulThetaBinsHistToFile();
+	    
+	}
+
+    }
+
+
+    return kTRUE;
+}
+
+
+
+
+
+ // Function that loops over the alpha distributions (ON-OFF)
+   // stored in root file defined by fAlphaDistributionsRootFilename
+   // and computes the significance and Nex (using MHFindSignificanceONOFF::FindSigma)
+   // for several cuts in alpha (0-fAlphaSig; in bins defined for alpha distributions 
+   // by user).
+
+   // It initializes the histograms (memeber data), fills them and store them 
+   // in root file defined by fAlphaDistributionsRootFilename. A single histogram 
+   // for each theta bin.
+
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()
+{
+
+
+  *fLog << endl << endl 
+	<< "****************************************************************************" << endl
+	<< "Computing number of excess events and significance vs " << endl
+	<< " the cut in alpha parameter (fAlphaSig) using function " << endl
+	<< " MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig() " << endl
+	<< "****************************************************************************" << endl
+	<< endl;
+  
+
+  // Check that all elements needed by the function are available
+ 
+
+  if (fAlphaDistributionsRootFilename.IsNull())
+    {
+	*fLog << err 
+	      << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig; " 
+	      << endl
+	      << "fAlphaDistributionsRootFilename is not defined yet, hence "
+	      << "histograms  containing alpha distributions for the different theta "
+	      << "ranges can not be retrieved. " << endl;
+
+	return kFALSE;
+    }
+
+
+
+    if (fCosThetaRangeVector.GetSize() < 2)
+    {
+        *fLog << err 
+	      << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig; " 
+	      << endl
+	      << "Size of fCosThetaRangeVector is smaller than 2... "
+	      << "fCosThetaRangeVector is not defined properly, "
+	      << "and thus, number of theta loops and names "
+	      << " of the histograms  containing alpha distributions "
+	      << "for the different theta "
+	      << "ranges can not defined properly." << endl;
+ 
+        return kFALSE;
+    }
+
+   
+
+    // It seems that i have all I need for the time being. Let's start the party...
+
+
+    Int_t tmpint =  0; // variable that will be used to store temporally integers 
+    Double_t tmpdouble = 0.0; // variable that will be used to store temporally doubles
+
+    tmpint = fCosThetaRangeVector.GetSize() - 1;
+    const Int_t NThetaBins = tmpint;
+ 
+
+    // Definition of the bins for Nex and Significance vs Alpha histograms
+    // The bins in Alpha will start with ZERO  and will end 
+    // with 5 bins further after fAlphaSig.
+
+    Double_t AlphaBinWidth = double((fAlphaBinUp-fAlphaBinLow)/fNAlphaBins);
+    Double_t FirstBinLow = 0.0;
+    tmpint = int((fAlphaSig/AlphaBinWidth) + 5.0);
+
+    while ((FirstBinLow + AlphaBinWidth*tmpint) > fAlphaBkgMin)
+      {
+	tmpint--;
+      }
+	
+    *fLog << "Information about the binning of the histograms Nex and Significance vs alphasig " 
+	  << endl
+	  << "FirstBinLow, AlphaBinWidth, NBins : " 
+	  << FirstBinLow << ", " << AlphaBinWidth << ", " << tmpint-1 << endl;
+
+
+
+    const Int_t NexSignVSAlphaXBinsVectorDimension = tmpint;
+                
+ 
+    Double_t* XBinsVector = new Double_t [NexSignVSAlphaXBinsVectorDimension];
+    
+    for (Int_t i = 0; i < NexSignVSAlphaXBinsVectorDimension; i++)
+      {
+	XBinsVector[i] = FirstBinLow + i*AlphaBinWidth;
+	// cout << XBinsVector[i] << endl;
+      }
+
+
+   
+    // Axis labels for Nex and Significance vs Alpha histograms
+
+    TString x_axis_label = ("Cut in alpha [\\circ]");
+    TString y_axis_label_nex = ("Excess Events");
+    TString y_axis_label_significance = ("Significance (LiMa formula 17)");
+
+
+    // Arguments for function MHFindSignificanceONOFF::FindSigmaONOFF()
+    // are defined in here. The same arguments (obviously) will be used 
+    // in all theta bins and TRAIN and TEST samples.
+
+    // variable alphasig will be defined and varied withing the theta loop
+
+    Double_t alphasig = 0.0;
+
+    // Minimum value of alpha for bkg region in ON data
+    const Double_t alphabkgmin = fAlphaBkgMin;
+    
+    // Maximum value of alpha for bkg region in ON data
+    const Double_t alphabkgmax = fAlphaBkgMax;
+    
+        
+    const Bool_t   drawpoly  = kFALSE;
+    const Bool_t   fitgauss  = kFALSE;
+    const Bool_t   print     = kFALSE;
+    
+    const Bool_t saveplots   = kFALSE; // No plots are saved
+   
+    const Bool_t RebinHistograms = kTRUE;
+    const Bool_t ReduceDegree = kFALSE;
+
+
+
+    Double_t Nex = 0.0;
+    Double_t Significance = 0.0;
+
+
+    // Names of histograms containing Nex and Significance vs alphasig
+
+    TString NexVSAlphaName = ("NexVSAlpha"); // Names to be completed in theta loop
+    TString SignificanceVSAlphaName = ("SignificanceVSAlpha");// Names to be completed in theta loop
+    
+
+
+    // Names of histograms to be retrieved from root file 
+    // fAlphaDistributionsRootFilename
+
+    TString NormFactorTrainHistoName = ("NormFactorTrainHist");
+    TString NormFactorTestHistoName = ("NormFactorTestHist");
+    
+    TString SuccessfulThetaBinsHistoName = ("SuccessfulThetaBinsHist");
+
+ 
+
+    // Histogram containing information about the success of the optimization
+    // for the several theta bins. The content of those bins where optimization was not 
+    // successful, are set to ZERO.
+
+    
+    TH1F* SuccessfulThetaBinsHisto;
+ 
+
+
+    // Histograms to store the normalization factors
+
+    TH1F* NormFactorTrainHisto;
+    TH1F* NormFactorTestHisto;
+
+
+
+    // Histograms that will be used to store the alpha distributions 
+    // retrieved from   fAlphaDistributionsRootFilename, and that will be use as arguments in 
+    // function MHFindSignificanceONOFF::FindSigma
+
+    // The same histograms (pointer to histograms actually) will be used for TRAIN and TEST 
+    // and for the different ThetaNBinsUsed.
+
+    TH1F* AlphaONAfterCuts;
+    TH1F* AlphaOFFAfterCuts;
+
+
+
+   
+      // Vector containing the histogram index of the successfully 
+    // optimized theta bins. 
+    // It is filled with the contents of the histogram 
+    // fSuccessfulThetaBinsHist retrieved from the root 
+    // file fAlphaDistributionsRootFilename
+    // Remember that histogram index START AT 1 !!!
+    TArrayI SuccessfulThetaBinsVector; 
+   
+
+
+    
+
+
+
+     // Open root file for retrieving information
+ 
+    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" << endl
+	  << "Opening root file " << fAlphaDistributionsRootFilename << endl;
+
+    TFile rootfile (fAlphaDistributionsRootFilename, "READ");
+
+    // Retrieving SuccessfulThetaBinsHisto from root file. 
+    
+    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" << endl
+	  << "Retrieving SuccessfulThetaBinsHisto from root file and filling vector "
+	  << " SuccessfulThetaBinsVector" << endl;
+
+                                    
+    cout << "Getting histogram with name " << SuccessfulThetaBinsHistoName << endl;
+
+    SuccessfulThetaBinsHisto = (TH1F*) rootfile.Get(SuccessfulThetaBinsHistoName);
+    
+
+
+    // Check that bins in this histo correspond with the 
+    // CosTheta intervals defined by vector fCosThetaRangeVector
+
+	
+    if (SuccessfulThetaBinsHisto -> GetNbinsX() != NThetaBins)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" 
+	      << endl
+	      << "Number of theta bins defined by vector fCosThetaRangeVector (" 
+	      << NThetaBins << ") does not match with the bins in histogram "
+	      << SuccessfulThetaBinsHistoName << "(" 
+	      << SuccessfulThetaBinsHisto -> GetNbinsX() << ")" << endl
+	      << "Function execution will be ABORTED." << endl;
+	return kFALSE;
+    }
+
+
+    // Filling vector SuccessfulThetaBinsVector
+
+    tmpint = 0;
+    for (Int_t i = 0; i < NThetaBins; i++)
+    {
+	if ((SuccessfulThetaBinsHisto -> GetBinContent(i+1)) > 0.5)
+	{
+	    tmpint++;
+	}
+    }
+
+    SuccessfulThetaBinsVector.Set(tmpint);
+    
+    tmpint = 0;
+    for (Int_t i = 0; i < NThetaBins; i++)
+    {
+	if ((SuccessfulThetaBinsHisto -> GetBinContent(i+1)) > 0.5)
+	{
+	    if(tmpint < SuccessfulThetaBinsVector.GetSize())
+	    {
+		SuccessfulThetaBinsVector[tmpint] = i+1;
+		tmpint++;
+	    }
+	    else
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" 
+		      << endl
+		      << "Problem when filling vector 'SuccessfulThetaBinsVector'" 
+		      << endl
+		      << "Function execution will be ABORTED." << endl;
+		return kFALSE;
+	    }
+	    
+
+	}
+    }
+
+    // variable defining the theta bins where optimization was successful, and 
+    // hence, alpha distributions stored in root file are meaningful (up to some extent)
+   
+    tmpint = SuccessfulThetaBinsVector.GetSize();
+    const Int_t SuccessfulNThetaBins = tmpint;
+    
+    // TEMP
+    //  cout << "const Int_t SuccessfulNThetaBins = " << SuccessfulNThetaBins << endl;
+    // ENDTEMP
+
+    // Vectors of pointers to histograms are defined to store the histograms 
+    // containing Nex and significance for TRAIN and TEST sample for all the 
+    // successful theta bins
+
+    // Histograms will be initialized in the loop over theta bins
+          
+    TH1F* NexVSAlphaSigTrainVector[SuccessfulNThetaBins];
+    TH1F* NexVSAlphaSigTestVector[SuccessfulNThetaBins];
+
+    
+    TH1F* SignificanceVSAlphaSigTrainVector[SuccessfulNThetaBins];
+    TH1F* SignificanceVSAlphaSigTestVector[SuccessfulNThetaBins];
+    
+    
+    // ***************************************************
+    // HISTOGRAMS FOR TRAIN SAMPLE ARE COMPUTED
+    // ***************************************************
+
+    
+
+    if (fOptimizeParameters)
+      { // Computation for TRAIN sample
+
+
+	*fLog << endl << endl
+	      << "****************************************************************************" << endl
+	      << "Computing Nex and significance vs cut in alpha (alphasig)  for TRAIN sample" << endl
+	      << "****************************************************************************" << endl
+	      << endl << endl;
+
+
+	// Retrieving NormFactorTrainHisto from root file. 
+
+	 cout << "Getting histogram with name " << NormFactorTrainHistoName << endl;
+
+	NormFactorTrainHisto = (TH1F*) rootfile.Get(NormFactorTrainHistoName);
+	
+
+	// Check that bins in this histo correspond with the 
+	// CosTheta intervals defined by vector fCosThetaRangeVector
+
+	////////////////// START CHECK  //////////////////////////////////////
+	
+	if (NormFactorTrainHisto -> GetNbinsX() != NThetaBins)
+	{
+	    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" 
+		  << endl
+		  << "Number of theta bins defined by vector fCosThetaRangeVector (" 
+		  << NThetaBins << ") does not match with the bins in histogram "
+		  << NormFactorTrainHistoName << "(" 
+		  << NormFactorTrainHisto -> GetNbinsX() << ")" << endl
+		  << "Function execution will be ABORTED." << endl;
+	    return kFALSE;
+	}
+
+	// histo test 
+	/*
+	cout << "NORMFACTORTRAINHIST  Test: BinCenter and Value" << endl;
+	for (Int_t k = 0; k < NThetaBins; k++)
+	{
+	    
+	    cout << NormFactorTrainHisto -> GetBinCenter(k+1) 
+		 << ";  " << NormFactorTrainHisto -> GetBinContent(k+1)<< endl;
+	}
+	*/
+
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	{
+	    tmpdouble = NormFactorTrainHisto -> GetBinCenter(SuccessfulThetaBinsVector[i]);
+	    if (fCosThetaRangeVector[SuccessfulThetaBinsVector[i]-1] > tmpdouble || 
+		fCosThetaRangeVector[SuccessfulThetaBinsVector[i]] < tmpdouble)
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" 
+		      << endl
+		      << "Bins defined by vector fCosThetaRangeVector " 
+		      << "do not match with the bins of histogram "
+		      << NormFactorTrainHistoName << endl
+		      << "CosTheta: " << fCosThetaRangeVector[SuccessfulThetaBinsVector[i]-1]
+		      << "-" << fCosThetaRangeVector[SuccessfulThetaBinsVector[i]] << endl
+		      << "NormFactorHist Bin: " <<  tmpdouble << endl
+		      << "Function execution will be ABORTED." << endl;
+
+		return kFALSE;
+	    }
+	    
+	}
+
+	////////////////// END CHECK  //////////////////////////////////////
+
+
+
+	
+	// Check that the theta range string (needed to compute names for alpha histograms)
+	// is well defined
+	
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	  {
+	    if (fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1].IsNull())
+	      {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" 
+		      << endl
+		      << "Component " << SuccessfulThetaBinsVector[i]-1 
+		      << " of fThetaRangeStringVector is EMPTY"
+		      << endl
+		      << "Function execution will be ABORTED." << endl;
+
+		return kFALSE;
+
+		
+	    }
+	  }
+
+
+	// *************************************************************
+	// *************************************************************
+	
+	// Normfactors and successfultheta bins are ok. 
+	// I can now compute the Nex and Sigma for train sample (ON-OFF) 
+	
+	// *************************************************************
+	// *************************************************************
+
+
+	
+
+	// Loop over the several successful theta bins doing the following 
+
+	// 0) Initializing histograms Nex and Significance (with names!!)
+	// 1) Retrieving alpha histograms (ON-OFF), and normalization factor
+	// 2) Computing Nex and Signficance vs alpha and filling histograms
+
+
+	*fLog << endl
+	      << "Starting loop over the successfully optimized theta ranges " << endl
+	      << endl;
+
+	Double_t NormalizationFactor = 0.0;
+	
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	  {
+
+	    *fLog << fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1] << endl << endl;
+	
+	    // 0) Initializing histograms Nex and Significance (with names!!)
+
+	    TString NexVSAlphaNameTmp = (NexVSAlphaName);
+	    TString SignificanceVSAlphaNameTmp = (SignificanceVSAlphaName);
+
+	    NexVSAlphaNameTmp += "Train";
+	    NexVSAlphaNameTmp += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    SignificanceVSAlphaNameTmp += "Train";
+	    SignificanceVSAlphaNameTmp += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	
+	    // TEMP    
+	    //cout << NexVSAlphaNameTmp << endl;
+	    //cout << SignificanceVSAlphaNameTmp << endl;
+	    // ENDTEMP
+	      
+
+
+    
+	    NexVSAlphaSigTrainVector[i] = new TH1F (NexVSAlphaNameTmp.Data(), 
+						    NexVSAlphaNameTmp.Data(), 
+						    NexSignVSAlphaXBinsVectorDimension - 1,
+						    XBinsVector);
+	    
+	    // It is important to unlink the the created histograms from 
+	    // the current directory (defined now by "rootfile"), 
+	    // so that we can do whatever we want to 
+	    // with them regardless of such directory is opened or closed 
+	    // The reference of the histogram is removed from the current 
+	    // directory by means of the member function  "SetDirectory(0)"
+
+
+	    NexVSAlphaSigTrainVector[i] -> SetDirectory(0);
+
+
+	    SignificanceVSAlphaSigTrainVector[i] = new TH1F (SignificanceVSAlphaNameTmp.Data(), 
+							     SignificanceVSAlphaNameTmp.Data(),
+							     NexSignVSAlphaXBinsVectorDimension - 1,
+							     XBinsVector);
+	    
+	    SignificanceVSAlphaSigTrainVector[i] -> SetDirectory(0);
+	    
+	    
+
+	    // axis are defined
+
+	    NexVSAlphaSigTrainVector[i] -> SetXTitle(x_axis_label.Data());
+	    NexVSAlphaSigTrainVector[i] -> SetYTitle(y_axis_label_nex.Data());
+	    
+	    SignificanceVSAlphaSigTrainVector[i] ->SetXTitle(x_axis_label.Data());
+	    SignificanceVSAlphaSigTrainVector[i] ->SetYTitle(y_axis_label_significance.Data());
+
+	
+	    // 1) Retrieving alpha histograms (ON-OFF) and normalization factor
+
+	    NormalizationFactor = 
+	      NormFactorTrainHisto -> GetBinContent(SuccessfulThetaBinsVector[i]);
+
+
+	    TString TmpAlphaHistoName = ("TrainAlphaAfterCuts");
+	    TmpAlphaHistoName += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    *fLog << "Getting Histogram with name " << endl
+		  << TmpAlphaHistoName << endl;
+
+	    AlphaONAfterCuts = (TH1F*) rootfile.Get(TmpAlphaHistoName);
+
+	    
+	    TString TmpAlphaOFFHistoName = ("TrainAlphaOFFAfterCuts");
+	    TmpAlphaOFFHistoName += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    *fLog << "Getting Histogram with name " << endl
+		  << TmpAlphaOFFHistoName << endl;
+
+	    AlphaOFFAfterCuts = (TH1F*) rootfile.Get(TmpAlphaOFFHistoName);
+
+	   
+
+	    
+
+	 // 2) Computing Nex and Signficance vs alpha and filling histograms
+	    // Significance is found using MHFindSignificanceONOFF::FindSigmaONOFF  
+
+
+	    *fLog  << endl << endl
+		   << "Starting loop to compute Nex and Significance vs alphasig " << endl
+		   << "for TRAIN sample and " 
+		   << fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1] 
+		   << " :" << endl;
+	    
+	   	    
+	    for (Int_t j = 1; j < NexSignVSAlphaXBinsVectorDimension; j++)
+	      {
+		
+
+		alphasig = XBinsVector[j];
+		
+		MHFindSignificanceONOFF findsig;
+		findsig.SetRebin(RebinHistograms);
+		findsig.SetReduceDegree(ReduceDegree);	
+		findsig.SetUseFittedQuantities(fUseFittedQuantities);
+
+		// Dummy name for psfile 
+		TString psfilename = ("DummyPs"); 
+	    
+		findsig.FindSigmaONOFF(AlphaONAfterCuts, AlphaOFFAfterCuts, 
+				       NormalizationFactor, 
+				       alphabkgmin, alphabkgmax, 
+				       fDegreeON, fDegreeOFF,
+				       alphasig, 
+				       drawpoly, fitgauss, print, 
+				       saveplots, psfilename);
+
+		
+		Significance = double(findsig.GetSignificance());
+
+		// so far there is not a variable that contains 
+		// NexONOFF or NexONOFFFitted (in class MHFindSignificanceONOFF) 
+		// according to the value of the variable fUseFittedQuantities.
+		// As soon as I have some time I will implement it (with the 
+		// corresponging GET member function) and will change 
+		// MFindSignificanceONOFF accordingly to make use of it.
+		
+		// For the time being, I will survive with an "if statement".
+
+		
+		if(fUseFittedQuantities)
+		  {
+		    Nex = double(findsig.GetNexONOFFFitted()); 
+		  }
+		else
+		  {
+		    Nex = double(findsig.GetNexONOFF()); 
+		  }
+
+
+				
+		*fLog << endl << "Cut in alpha, Nex and significance : " 
+		      << alphasig << ", " << Nex << ", " << Significance << endl << endl;
+		
+	      
+		// updating histograms
+
+		tmpdouble = alphasig - AlphaBinWidth/2.0;
+
+		NexVSAlphaSigTrainVector[i] -> Fill(tmpdouble, Nex);
+		SignificanceVSAlphaSigTrainVector[i] -> Fill(tmpdouble, Significance);
+		
+	  
+
+		
+
+
+
+	      }	  
+	
+
+	    // Dynamic memory allocated in this loop is released
+	    
+    
+	    *fLog  << "Memory allocated by temporal alpha histograms "
+		   << "will be released" << endl;
+	    
+	    delete AlphaONAfterCuts;
+	    delete AlphaOFFAfterCuts;
+	    
+	  }
+
+
+      }
+
+    
+    
+     // ***************************************************
+    // HISTOGRAMS FOR TEST SAMPLE ARE COMPUTED
+    // ***************************************************
+
+
+ 
+
+    if(fTestParameters)
+      {// computation for TEST sample
+	
+	*fLog << endl << endl
+	      << "**************************************************************************" << endl
+	      << "Computing Nex and significance vs cut in alpha (alphasig) for TEST sample" << endl
+	      << "**************************************************************************" << endl
+	      << endl << endl;
+
+	// Retrieving NormFactorTestHisto from root file. 
+
+	 *fLog << "Getting histogram with name " << NormFactorTestHistoName << endl;
+
+	NormFactorTestHisto = (TH1F*) rootfile.Get(NormFactorTestHistoName);
+	
+
+	// Check that bins in this histo correspond with the 
+	// CosTheta intervals defined by vector fCosThetaRangeVector
+
+	////////////////// START CHECK  //////////////////////////////////////
+	
+	if (NormFactorTestHisto -> GetNbinsX() != NThetaBins)
+	{
+	    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" 
+		  << endl
+		  << "Number of theta bins defined by vector fCosThetaRangeVector (" 
+		  << NThetaBins << ") does not match with the bins in histogram "
+		  << NormFactorTestHistoName << "(" 
+		  << NormFactorTestHisto -> GetNbinsX() << ")" << endl
+		  << "Function execution will be ABORTED." << endl;
+	    return kFALSE;
+	}
+
+	// histo test 
+	/*
+	cout << "NORMFACTORTRAINHIST  Test: BinCenter and Value" << endl;
+	for (Int_t k = 0; k < NThetaBins; k++)
+	{
+	    
+	    cout << NormFactorTestHisto -> GetBinCenter(k+1) 
+		 << ";  " << NormFactorTestHisto -> GetBinContent(k+1)<< endl;
+	}
+	*/
+
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	{
+	    tmpdouble = NormFactorTestHisto -> GetBinCenter(SuccessfulThetaBinsVector[i]);
+	    if (fCosThetaRangeVector[SuccessfulThetaBinsVector[i]-1] > tmpdouble || 
+		fCosThetaRangeVector[SuccessfulThetaBinsVector[i]] < tmpdouble)
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" 
+		      << endl
+		      << "Bins defined by vector fCosThetaRangeVector " 
+		      << "do not match with the bins of histogram "
+		      << NormFactorTestHistoName << endl
+		      << "CosTheta: " << fCosThetaRangeVector[SuccessfulThetaBinsVector[i]-1]
+		      << "-" << fCosThetaRangeVector[SuccessfulThetaBinsVector[i]] << endl
+		      << "NormFactorHist Bin: " <<  tmpdouble << endl
+		      << "Function execution will be ABORTED." << endl;
+
+		return kFALSE;
+	    }
+	    
+	}
+
+	////////////////// END CHECK  //////////////////////////////////////
+
+
+
+	
+	// Check that the theta range string (needed to compute names for alpha histograms)
+	// is well defined
+	
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	  {
+	    if (fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1].IsNull())
+	      {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" 
+		      << endl
+		      << "Component " << SuccessfulThetaBinsVector[i]-1 
+		      << " of fThetaRangeStringVector is EMPTY"
+		      << endl
+		      << "Function execution will be ABORTED." << endl;
+
+		return kFALSE;
+
+		
+	    }
+	  }
+
+
+	// *************************************************************
+	// *************************************************************
+	
+	// Normfactors and successfultheta bins are ok. 
+	// I can now compute the Nex and Sigma for test sample (ON-OFF) 
+	
+	// *************************************************************
+	// *************************************************************
+
+	// Loop over the several successful theta bins doing the following 
+
+	// 0) Initializing histograms Nex and Significance (with names!!)
+	// 1) Retrieving alpha histograms (ON-OFF), and normalization factor
+	// 2) Computing Nex and Signficance vs alpha and filling histograms
+
+
+	*fLog << endl
+	      << "Starting loop over the successfully optimized theta ranges " << endl
+	      << endl;
+
+	
+	Double_t NormalizationFactor = 0.0;
+	
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	  {
+
+	    *fLog << fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1] << endl << endl;
+
+	    // 0) Initializing histograms Nex and Significance (with names!!)
+
+	    TString NexVSAlphaNameTmp = (NexVSAlphaName);
+	    TString SignificanceVSAlphaNameTmp = (SignificanceVSAlphaName);
+
+	    NexVSAlphaNameTmp += "Test";
+	    NexVSAlphaNameTmp += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    SignificanceVSAlphaNameTmp += "Test";
+	    SignificanceVSAlphaNameTmp += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	
+	    // TEMP    
+	    // cout << NexVSAlphaNameTmp << endl;
+	    // cout << SignificanceVSAlphaNameTmp << endl;
+	    // ENDTEMP
+	      
+
+
+    
+	    NexVSAlphaSigTestVector[i] = new TH1F (NexVSAlphaNameTmp.Data(), 
+						    NexVSAlphaNameTmp.Data(), 
+						    NexSignVSAlphaXBinsVectorDimension - 1,
+						    XBinsVector);
+	    
+	    // It is important to unlink the the created histograms from 
+	    // the current directory (defined now by "rootfile"), 
+	    // so that we can do whatever we want to 
+	    // with them regardless of such directory is opened or closed 
+	    // The reference of the histogram is removed from the current 
+	    // directory by means of the member function  "SetDirectory(0)"
+
+
+	    NexVSAlphaSigTestVector[i] -> SetDirectory(0);
+
+
+	    SignificanceVSAlphaSigTestVector[i] = new TH1F (SignificanceVSAlphaNameTmp.Data(), 
+							     SignificanceVSAlphaNameTmp.Data(),
+							     NexSignVSAlphaXBinsVectorDimension - 1,
+							     XBinsVector);
+	    
+	    SignificanceVSAlphaSigTestVector[i] -> SetDirectory(0);
+	    
+	    
+
+	    // axis are defined
+
+	    NexVSAlphaSigTestVector[i] -> SetXTitle(x_axis_label.Data());
+	    NexVSAlphaSigTestVector[i] -> SetYTitle(y_axis_label_nex.Data());
+	    
+	    SignificanceVSAlphaSigTestVector[i] ->SetXTitle(x_axis_label.Data());
+	    SignificanceVSAlphaSigTestVector[i] ->SetYTitle(y_axis_label_significance.Data());
+
+	
+	    // 1) Retrieving alpha histograms (ON-OFF) and normalization factor
+
+	    NormalizationFactor = 
+	      NormFactorTestHisto -> GetBinContent(SuccessfulThetaBinsVector[i]);
+
+
+	    TString TmpAlphaHistoName = ("TestAlphaAfterCuts");
+	    TmpAlphaHistoName += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    *fLog << "Getting Histogram with name " << endl
+		  << TmpAlphaHistoName << endl;
+
+	    AlphaONAfterCuts = (TH1F*) rootfile.Get(TmpAlphaHistoName);
+
+	    
+	    TString TmpAlphaOFFHistoName = ("TestAlphaOFFAfterCuts");
+	    TmpAlphaOFFHistoName += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    *fLog << "Getting Histogram with name " << endl
+		  << TmpAlphaOFFHistoName << endl;
+
+	    AlphaOFFAfterCuts = (TH1F*) rootfile.Get(TmpAlphaOFFHistoName);
+	    
+
+	 // 2) Computing Nex and Signficance vs alpha and filling histograms
+	    // Significance is found using MHFindSignificanceONOFF::FindSigmaONOFF  
+
+
+	    *fLog  << endl << endl
+		   << "Starting loop to compute Nex and Significance vs alphasig " << endl
+		   << "for TRAIN sample and " 
+		   << fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1] 
+		   << " :" << endl;
+	    
+	   	    
+	    for (Int_t j = 1; j < NexSignVSAlphaXBinsVectorDimension; j++)
+	      {
+		
+
+		alphasig = XBinsVector[j];
+		
+		MHFindSignificanceONOFF findsig;
+		findsig.SetRebin(RebinHistograms);
+		findsig.SetReduceDegree(ReduceDegree);	
+		findsig.SetUseFittedQuantities(fUseFittedQuantities);
+
+		// Dummy name for psfile 
+		TString psfilename = ("DummyPs"); 
+	    
+		findsig.FindSigmaONOFF(AlphaONAfterCuts, AlphaOFFAfterCuts, 
+				       NormalizationFactor, 
+				       alphabkgmin, alphabkgmax, 
+				       fDegreeON, fDegreeOFF,
+				       alphasig, 
+				       drawpoly, fitgauss, print, 
+				       saveplots, psfilename);
+
+
+
+		Significance = double(findsig.GetSignificance());
+
+		// so far there is not a variable that contains 
+		// NexONOFF or NexONOFFFitted (in class MHFindSignificanceONOFF) 
+		// according to the value of the variable fUseFittedQuantities.
+		// As soon as I have some time I will implement it (with the 
+		// corresponging GET member function) and will change 
+		// MFindSignificanceONOFF accordingly to make use of it.
+		
+		// For the time being, I will survive with an "if statement".
+
+		
+		if(fUseFittedQuantities)
+		  {
+		    Nex = double(findsig.GetNexONOFFFitted()); 
+		  }
+		else
+		  {
+		    Nex = double(findsig.GetNexONOFF()); 
+		  }
+
+
+		*fLog << endl << "Cut in alpha, Nex and significance : " 
+		      << alphasig << ", " << Nex << ", " << Significance << endl << endl;
+		
+	      
+		// updating histograms
+
+		tmpdouble = alphasig - AlphaBinWidth/2.0;
+
+		NexVSAlphaSigTestVector[i] -> Fill(tmpdouble, Nex);
+		SignificanceVSAlphaSigTestVector[i] -> Fill(tmpdouble, Significance);
+		
+	  
+
+		
+
+
+
+	      }	  
+	
+
+	    // Dynamic memory allocated in this loop is released
+	    
+    
+	    *fLog  << "Memory allocated by temporal alpha histograms "
+		   << "will be released" << endl;
+	    
+	    delete AlphaONAfterCuts;
+	    delete AlphaOFFAfterCuts;
+	    
+	  }
+
+
+
+
+
+
+
+
+      }
+    
+    rootfile.Close();
+
+
+   
+     // *************************************************************
+    // Histograms Nex and Significance vs alpha are written into 
+    // root file fAlphaDistributionsRootFilename
+
+    
+
+
+     *fLog <<"Histograms containing Nex and significance vs alphasig " 
+	  << " are saved into root file " << endl 
+	  << fAlphaDistributionsRootFilename << endl;
+    
+
+    TFile rootfiletowrite (fAlphaDistributionsRootFilename, "UPDATE", 
+			   "Alpha Distributions for several Theta bins");
+
+ 
+   for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+    {
+
+      if (fOptimizeParameters)
+	{// Histograms for train sample are written to root file
+
+	  if(NexVSAlphaSigTrainVector[i])
+	    {
+	      if(NexVSAlphaSigTrainVector[i]-> GetEntries() > 0.5)
+		NexVSAlphaSigTrainVector[i]-> Write();
+
+	    }
+
+	   if(SignificanceVSAlphaSigTrainVector[i])
+	    {
+	      if(SignificanceVSAlphaSigTrainVector[i]-> GetEntries() > 0.5)
+		SignificanceVSAlphaSigTrainVector[i]-> Write();
+	      
+	    }
+	}
+
+
+
+      if (fTestParameters)
+	{// Histograms for test sample are written to root file
+
+	  if(NexVSAlphaSigTestVector[i])
+	    {
+	      if(NexVSAlphaSigTestVector[i]-> GetEntries() > 0.5)
+		NexVSAlphaSigTestVector[i]-> Write();
+
+	    }
+
+	   if(SignificanceVSAlphaSigTestVector[i])
+	    {
+	      if(SignificanceVSAlphaSigTestVector[i]-> GetEntries() > 0.5)
+		SignificanceVSAlphaSigTestVector[i]-> Write();
+	      
+	    }
+	}
+	  
+
+
+    }
+    
+
+    rootfiletowrite.Close();
+
+ 
+
+
+    // Dynamic memory allocated is released 
+    
+    delete  XBinsVector; 
+
+    // function finished successfully... hopefully...
+    return kTRUE;
+
+}
+
+
+
+// Function that gets the histograms with the alpha distributions
+// (for all the theta bins specified by fCosThetaRangeVector)
+// stored in fAlphaDistributionsRootFilename, and combine them
+// (correcting OFF histograms with the normalization factors stored 
+// in NormFactorTrain or NormFactorTest) to get one single 
+// Alpha distribution for ON and another one for OFF. 
+// Then these histograms are given as arguments to 
+// the function MHFindSignificanceONOFF::FindSigmaONOFF, 
+// (Object of this class is created) to compute the 
+// Overall Excess events and  significance, that will be 
+// stored in variables fOverallNexTrain/Test and fOverallSigmaLiMaTrain/Test
+
+
+
+
+Bool_t MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance(Bool_t CombineTrainData,
+								   Bool_t CombineTestData)
+{
+
+
+   *fLog << endl << endl 
+	<< "****************************************************************************" << endl
+	<< "Combining number of excess events and significance for the  " << endl
+	<< "selected bins in theta angle using the function " << endl
+	<< " MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance() " << endl
+	<< "****************************************************************************" << endl
+	<< endl;
+  
+
+
+ 
+
+
+    // First of all let's check that we have the proper the "drinks" for the party
+
+    if (fAlphaDistributionsRootFilename.IsNull())
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" << endl
+	      << "Root file containing all alpha distributions "
+	      <<" (fAlphaDistributionsRootFilename) is not well defined." << endl
+	      << "Execution of the function is ABORTED" << endl;
+	return kFALSE;
+    }
+
+
+    if (fCosThetaRangeVector.GetSize() < 2)
+	
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" << endl
+	      << "Dimension of vector fCosThetaRangeVector is smaller than 2." 
+	      << "So, vector fCosThetaRangeVector is NOT properly defined" << endl
+	      << "Function execution will be ABORTED" << endl;
+
+	return kFALSE;
+    }
+
+    
+    TArrayI SuccessfulThetaBinsVector; 
+    // Vector containing the histogram index of the successfully 
+    // optimized theta bins. 
+    // It is filled with the contents of the histogram 
+    // fSuccessfulThetaBinsHist retrieved from the root 
+    // file fAlphaDistributionsRootFilename
+    // Remember that histogram index START AT 1 !!!
+
+
+
+    // Histograms that will contain the alpha distributions 
+    // for the combined theta bins
+
+
+    TH1F* CombinedAlphaTrainON = NULL;
+    TString CombinedAlphaTrainONName = ("TrainSampleAlphaONCombinedThetaBins");
+    TH1F* CombinedAlphaTrainOFF = NULL;
+    TString CombinedAlphaTrainOFFName = ("TrainSampleAlphaOFFCombinedThetaBins");
+   
+    TH1F* CombinedAlphaTestON = NULL;
+    TString CombinedAlphaTestONName = ("TestSampleAlphaONCombinedThetaBins");
+   
+    TH1F* CombinedAlphaTestOFF = NULL;
+    TString CombinedAlphaTestOFFName = ("TestSampleAlphaONCombinedThetaBins");
+   
+    
+
+
+    
+    Int_t NAlphaBins = 0; // Amount of bins of alpha histograms is expected to 
+    // be equal for all alpha histograms
+
+    // Vectors storing the computed error for each of the NAlphaBins 
+    // Only 2 vectors are needed for OFF Train and OFF Test sample, whose 
+    // alpha distributions are corrected with normalization factors. 
+
+    // The ON sample is just added (no normalization factors are applied) 
+    // and therefore, the error of the bin is the assumed by default 
+    // (i.e Sqrt(BinContent)
+
+    TArrayD ErrorInCombinedAlphaTrainOFF;
+    TArrayD ErrorInCombinedAlphaTestOFF;
+
+    TArrayD CombinedAlphaTrainOFFWithoutNormalization;
+    TArrayD CombinedAlphaTestOFFWithoutNormalization;
+    
+
+
+    const Double_t SmallQuantity = 0.01; // This quantity will be used as the 
+    // maximum difference between quantities (double) that are expected to be equal, 
+    // as the center of the bins in the several alpha distributions 
+
+    TH1F* NormFactorTrainHisto;
+    TString NormFactorTrainHistoName = ("NormFactorTrainHist");
+    TH1F* NormFactorTestHisto;
+    TString NormFactorTestHistoName = ("NormFactorTestHist");
+    TString SuccessfulThetaBinsHistoName = ("SuccessfulThetaBinsHist");
+    
+
+    TH1F* SuccessfulThetaBinsHisto;
+
+    TH1F* TmpTH1FHisto;
+
+    
+    // Retrieve number of theta bins that have to be combined
+    // from TArrayD fCosThetaRangeVector
+
+    Int_t tmpdim = fCosThetaRangeVector.GetSize() - 1;
+    const Int_t NThetaBins = tmpdim;
+
+    // Variables to store the mean normalization factor of the 
+    // combined OFF sample. 
+    // MeanNormFactor = Sum (NormFactor_i*Noff_i)/Sum (Noff_i)
+    
+
+    Double_t MeanNormFactorTrain = 0.0;
+    Double_t MeanNormFactorTest = 0.0;
+    
+    Double_t TotalNumberOFFTrain = 0.0;
+    Double_t TotalNumberOFFTest = 0.0;
+    
+
+
+    Double_t EventCounter = 0.0;// variable used to count events used to fill histograms
+    // it is double (and not Int) because the contents of an histogram bin might not 
+    // be an integer value... due to normalization factors !!
+    Int_t tmpint = 0;
+    Double_t tmpdouble = 0.0; // tmp variable double
+    Double_t tmpdouble2 = 0.0; // tmp variable double
+    Double_t tmperror = 0.0; // quantity used to store 
+    // temporaly the bin error in OFF histogram
+    Double_t tmpnormfactor = 0.0; // variable used to store normalization factor 
+    // of the theta bin i (used for TRAIN and TEST sample)
+             
+
+
+
+    // Open root file
+
+    
+
+    
+    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" << endl
+	  << "Opening root file " << fAlphaDistributionsRootFilename << endl;
+
+
+
+    TFile rootfile (fAlphaDistributionsRootFilename, "READ");
+
+    // Retrieving SuccessfulThetaBinsHisto from root file. 
+    
+
+    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" << endl
+	  << "Retrieving SuccessfulThetaBinsHisto from root file and filling vector "
+	  << " SuccessfulThetaBinsVector" << endl;
+
+
+    cout << "Getting histogram " << SuccessfulThetaBinsHistoName << endl;
+
+    SuccessfulThetaBinsHisto = (TH1F*) rootfile.Get(SuccessfulThetaBinsHistoName);
+    
+
+
+    // Check that bins in this histo correspond with the 
+    // CosTheta intervals defined by vector fCosThetaRangeVector
+
+	
+    if (SuccessfulThetaBinsHisto -> GetNbinsX() != NThetaBins)
+    {
+	*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+	      << endl
+	      << "Number of theta bins defined by vector fCosThetaRangeVector (" 
+	      << NThetaBins << ") does not match with the bins in histogram "
+	      << SuccessfulThetaBinsHistoName << "(" 
+	      << SuccessfulThetaBinsHisto -> GetNbinsX() << ")" << endl
+	      << "Function execution will be ABORTED." << endl;
+	return kFALSE;
+    }
+
+
+    // Filling vector SuccessfulThetaBinsVector
+
+    tmpint = 0;
+    for (Int_t i = 0; i < NThetaBins; i++)
+    {
+	if ((SuccessfulThetaBinsHisto -> GetBinContent(i+1)) > 0.5)
+	{
+	    tmpint++;
+	}
+    }
+
+    SuccessfulThetaBinsVector.Set(tmpint);
+    
+    tmpint = 0;
+    for (Int_t i = 0; i < NThetaBins; i++)
+    {
+	if ((SuccessfulThetaBinsHisto -> GetBinContent(i+1)) > 0.5)
+	{
+	    if(tmpint < SuccessfulThetaBinsVector.GetSize())
+	    {
+		SuccessfulThetaBinsVector[tmpint] = i+1;
+		tmpint++;
+	    }
+	    else
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		      << endl
+		      << "Problem when filling vector 'SuccessfulThetaBinsVector'" 
+		      << endl
+		      << "Function execution will be ABORTED." << endl;
+		return kFALSE;
+	    }
+	    
+
+	}
+    }
+
+
+   
+
+
+    // *********  HISTOGRAMS FOR TRAIN SAMPLE WILL BE FILLED *********///
+
+    if (CombineTrainData)
+    {
+
+
+      
+      *fLog << endl 
+	<< "****************************************************************************" << endl
+	<< "Combining data for the TRAIN sample " << endl
+	<< "****************************************************************************" << endl
+	<< endl;
+
+	// Retrieving NormFactorTrainHisto from root file. 
+	
+	NormFactorTrainHisto = (TH1F*) rootfile.Get(NormFactorTrainHistoName);
+	// NormFactorTrainHisto-> DrawCopy();
+
+	// Check that bins in this histo correspond with the 
+	// CosTheta intervals defined by vector fCosThetaRangeVector
+
+	
+	if (NormFactorTrainHisto -> GetNbinsX() != NThetaBins)
+	{
+	    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		  << endl
+		  << "Number of theta bins defined by vector fCosThetaRangeVector (" 
+		  << NThetaBins << ") does not match with the bins in histogram "
+		  << NormFactorTrainHistoName << "(" 
+		  << NormFactorTrainHisto -> GetNbinsX() << ")" << endl
+		  << "Function execution will be ABORTED." << endl;
+	    return kFALSE;
+	}
+
+	// histo test 
+	/*
+	cout << "NORMFACTORTRAINHIST  TEST: BinCenter and Value" << endl;
+	for (Int_t k = 0; k < NThetaBins; k++)
+	{
+	    
+	    cout << NormFactorTrainHisto -> GetBinCenter(k+1) 
+		 << ";  " << NormFactorTrainHisto -> GetBinContent(k+1)<< endl;
+	}
+	*/
+
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	{
+	    tmpdouble = NormFactorTrainHisto -> GetBinCenter(SuccessfulThetaBinsVector[i]);
+	    if (fCosThetaRangeVector[SuccessfulThetaBinsVector[i]-1] > tmpdouble || 
+		fCosThetaRangeVector[SuccessfulThetaBinsVector[i]] < tmpdouble)
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		      << endl
+		      << "Bins defined by vector fCosThetaRangeVector " 
+		      << "do not match with the bins of histogram "
+		      << NormFactorTrainHistoName << endl
+		      << "CosTheta: " << fCosThetaRangeVector[SuccessfulThetaBinsVector[i]-1]
+		      << "-" << fCosThetaRangeVector[SuccessfulThetaBinsVector[i]] << endl
+		      << "NormFactorHist Bin: " <<  tmpdouble << endl
+		      << "Function execution will be ABORTED." << endl;
+
+		return kFALSE;
+	    }
+	    
+	}
+
+
+	// Let's summ up all ON alpha distributions
+	
+	EventCounter = 0;
+
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	{
+	    if (fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1].IsNull())
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		      << endl
+		      << "Component " << SuccessfulThetaBinsVector[i]-1 
+		      << " of fThetaRangeStringVector is EMPTY"
+		      << endl
+		      << "Function execution will be ABORTED." << endl;
+		return kFALSE;
+
+		
+	    }
+
+	
+
+	    TString TmpHistoName = ("TrainAlphaAfterCuts");
+	    TmpHistoName += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    *fLog << "Getting Histogram with name " << endl
+		  << TmpHistoName << endl;
+
+	    if (i == 0)
+	    {      
+		CombinedAlphaTrainON = (TH1F*) rootfile.Get(TmpHistoName);
+		NAlphaBins = CombinedAlphaTrainON -> GetNbinsX();
+
+		// Name of histogram is set
+		CombinedAlphaTrainON -> SetName(CombinedAlphaTrainONName);
+
+		// update EventCounter
+		EventCounter += CombinedAlphaTrainON -> GetEntries();
+
+		// tmp
+		cout << "NAlphaBins in histo CombinedAlphaTrainON: "
+		     << NAlphaBins << endl;
+		// endtmp
+	    }
+	    else
+	    {
+		TmpTH1FHisto = (TH1F*) rootfile.Get(TmpHistoName);
+		
+		// update EventCounter
+		EventCounter += TmpTH1FHisto -> GetEntries();
+		
+		for (Int_t j = 1; j <= NAlphaBins; j++)
+		{
+		    // At some time alpha bins might not be the same for 
+		    // the different alpha distributions. That's why
+		    // I will check it before summing the alpha histo contents
+		    tmpdouble =  CombinedAlphaTrainON->GetBinCenter(j) -
+			TmpTH1FHisto->GetBinCenter(j);
+		    tmpdouble = TMath::Abs(tmpdouble);
+		    
+
+		    if (tmpdouble > SmallQuantity)
+		    {
+			*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+			      << endl
+			      << "Bins among the several alpha ON histograms "
+			      << "for TRAIN sample do not match"
+			      << endl
+			      << "Function execution will be ABORTED." << endl;
+			return kFALSE;
+		    }
+		    
+		    tmpdouble = CombinedAlphaTrainON->GetBinContent(j) + 
+			TmpTH1FHisto->GetBinContent(j);
+
+		    
+		    CombinedAlphaTrainON-> SetBinContent(j,tmpdouble);
+
+		}
+		
+		// Dynamic memory allocated for TmpTH1FHisto is released
+
+
+		//tmp
+		cout << "Memory allocated by temporal histogram TmpTH1FHisto "
+		     << "will be released" << endl;
+		//endtmp
+		delete TmpTH1FHisto;
+	    
+	    }
+
+
+	}
+
+	// Entries of histogram CombinedAlphaTrainON is set to 
+	// the events counted in EventCounter
+
+	tmpint = int (EventCounter);
+	CombinedAlphaTrainON->SetEntries(tmpint);
+
+	// Let's summ up all OFF alpha distributions
+	
+	EventCounter = 0;
+
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	{
+	    if (fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1].IsNull())
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		      << endl
+		      << "Component " << SuccessfulThetaBinsVector[i]-1 
+		      << " of fThetaRangeStringVector is EMPTY"
+		      << endl
+		      << "Function execution will be ABORTED." << endl;
+		return kFALSE;
+
+		
+	    }
+
+	    TString TmpHistoName = ("TrainAlphaOFFAfterCuts");
+	    TmpHistoName += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    // Normalization constant for this theta bin is stored now in tmpnormfactor
+	    tmpnormfactor = NormFactorTrainHisto -> GetBinContent(SuccessfulThetaBinsVector[i]);
+
+	    // temp 
+	    cout << "Normalization factor for bin "
+		 << SuccessfulThetaBinsVector[i] << " is "
+		 << tmpnormfactor << endl;
+
+	    // endtemp
+
+	    if (i == 0)
+	    {
+		CombinedAlphaTrainOFF = (TH1F*) rootfile.Get(TmpHistoName);
+		NAlphaBins = CombinedAlphaTrainOFF -> GetNbinsX();
+		
+
+		// Name of histogram is set
+		CombinedAlphaTrainOFF -> SetName(CombinedAlphaTrainOFFName);
+
+		// Event counter is updated taking into account the 
+		// normalization factor
+
+		EventCounter += tmpnormfactor * CombinedAlphaTrainOFF -> GetEntries();
+
+		// Contribution to total number of OFF events and mean normfactor
+		// of this theta bin is computed
+
+		TotalNumberOFFTrain = CombinedAlphaTrainOFF -> GetEntries();
+		MeanNormFactorTrain = tmpnormfactor *
+		    CombinedAlphaTrainOFF -> GetEntries();
+		    
+		
+		
+		// ****
+		// Dimension of ErrorInCombinedAlphaTrainOFF is set
+		ErrorInCombinedAlphaTrainOFF.Set(NAlphaBins);
+		
+		CombinedAlphaTrainOFFWithoutNormalization.Set(NAlphaBins);
+
+		// Histogram now is normalized (to the respective ON data)
+		// by using the normalization constants stored in 
+		// histogram NormFactorTrainHisto
+
+		// Error of the normalized bins is computed and stored in 
+		// vector ErrorInCombinedAlphaTrainOFF
+		
+		for (Int_t j = 1; j <= NAlphaBins; j++)
+		{
+
+		    // Number of events (without normalization) are 
+		    // stored in vector CombinedAlphaTrainOFFWithoutNormalization
+
+			CombinedAlphaTrainOFFWithoutNormalization[j-1] = 
+			    CombinedAlphaTrainOFF -> GetBinContent(j);
+		   
+		    // Bin content is set
+		    tmpdouble2 = tmpnormfactor * 
+			CombinedAlphaTrainOFF -> GetBinContent(j);
+
+		    CombinedAlphaTrainOFF -> SetBinContent(j,tmpdouble2);
+
+		    // (Bin Error)^2 is computed and stored in 
+		    // ErrorInCombinedAlphaTrainOFF
+		    // Bin error = Sqrt(BinContent) X Normalization Factor
+
+		    tmperror = tmpdouble2*tmpnormfactor;
+		    ErrorInCombinedAlphaTrainOFF[j-1] = tmperror;
+
+		}
+
+	    }
+	    else
+	    {
+		TmpTH1FHisto = (TH1F*) rootfile.Get(TmpHistoName);
+
+
+		// Event counter is updated taking into account the 
+		// normalization factor
+
+		EventCounter += tmpnormfactor * TmpTH1FHisto -> GetEntries();
+
+		// Contribution to total number of OFF events and mean normfactor
+		// of this theta bin is computed
+
+		TotalNumberOFFTrain += TmpTH1FHisto -> GetEntries();
+		MeanNormFactorTrain += tmpnormfactor *
+		    TmpTH1FHisto -> GetEntries();
+
+		
+
+		for (Int_t j = 1; j <= NAlphaBins; j++)
+		{
+		    // At some time alpha bins might not be the same for 
+		    // the different alpha distributions. That's why
+		    // I will check it before summing the alpha histo contents
+		    tmpdouble2 =  CombinedAlphaTrainOFF->GetBinCenter(j) -
+			TmpTH1FHisto->GetBinCenter(j);
+		    tmpdouble2 = TMath::Abs(tmpdouble2);
+
+		    if (tmpdouble2 > SmallQuantity)
+		    {
+			*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+			      << endl
+			      << "Bins among the several alpha OFF histograms "
+			      << "for TRAIN sample do not match"
+			      << endl
+			      << "Function execution will be ABORTED." << endl;
+			return kFALSE;
+		    }
+		    
+
+		     // Number of events (without normalization) are 
+		    // added in vector CombinedAlphaTrainOFFWithoutNormalization
+		    
+		    CombinedAlphaTrainOFFWithoutNormalization[j-1] += 
+			TmpTH1FHisto -> GetBinContent(j);
+
+		    // Histogram bin contents must be normalized (to the respective ON data)
+		    // by using the normalization constants stored in 
+		    // histogram NormFactorTrainHisto before being added 
+		    // to CombinedAlphaTrainOFF
+
+		   
+		    tmpdouble2 = CombinedAlphaTrainOFF->GetBinContent(j) + 
+			(TmpTH1FHisto->GetBinContent(j) * tmpnormfactor);
+
+		    
+		    CombinedAlphaTrainOFF-> SetBinContent(j,tmpdouble2);
+
+
+		    // (Bin Error)^2 is computed and added to  
+		    // ErrorInCombinedAlphaTrainOFF 
+		    // Bin error = Sqrt(BinContent) X Normalization Factor
+
+		    tmperror = TmpTH1FHisto->GetBinContent(j) * tmpnormfactor;
+		    ErrorInCombinedAlphaTrainOFF[j-1] += tmperror;
+
+		}
+		
+		// Dynamic memory allocated for TmpTH1FHisto is released
+
+		delete TmpTH1FHisto;
+	    
+	    }
+
+	    
+
+
+
+	}
+
+	
+
+
+	// Mean Normalization factor is computed for the combined OFF histogram. 
+	// This factor will be used when computing the significance via 
+	// MHFindSignificance::FindSigmaONOFF().
+
+	// The bin contents (and errors) of teh combined OFF TRAIN histo will be 
+	// normalized (divided) by teh mean norm constant, so that 
+	// the histogram for OFF data given as argument in FindSigmaONOFF
+	// is equivalent to a non-normalized histogram. 
+	
+	MeanNormFactorTrain = MeanNormFactorTrain/TotalNumberOFFTrain;
+
+
+
+	// Sqrt(Contents) is performed in ErrorInCombinedAlphaTrainOFF, 
+	// in order to compute the real error in the bin content of histogram 
+	// CombinedAlphaTrainOFF.
+
+	// Then error and contents (normalized with mean normfctor) are
+	// set to histogram bin 	
+
+	for (Int_t j = 1; j <= NAlphaBins; j++)
+	{	    
+	    tmpdouble2 = 
+		(CombinedAlphaTrainOFF -> GetBinContent(j))/MeanNormFactorTrain;
+
+	    CombinedAlphaTrainOFF -> SetBinContent(j,tmpdouble2);
+
+	    ErrorInCombinedAlphaTrainOFF[j-1] = 
+		TMath::Sqrt(ErrorInCombinedAlphaTrainOFF[j-1])/MeanNormFactorTrain;
+	    // Proper error treatment when adding quantities to histogram bin 
+
+	    CombinedAlphaTrainOFF -> SetBinError(j,ErrorInCombinedAlphaTrainOFF[j-1]);
+
+	    // ******  TMP **************
+	    /*
+	    // Error computation assuming a given (no normalized) bin content
+
+	    tmpdouble = CombinedAlphaTrainOFF -> GetBinContent(j);
+
+	    if (CombinedAlphaTrainOFFWithoutNormalization[j-1] < SmallQuantity)
+	    {tmpnormfactor = 0;}
+	    else
+	    {tmpnormfactor = tmpdouble/CombinedAlphaTrainOFFWithoutNormalization[j-1];}
+
+	    tmperror = TMath::Sqrt(CombinedAlphaTrainOFFWithoutNormalization[j-1]) *
+		tmpnormfactor;
+
+	    CombinedAlphaTrainOFF -> SetBinError(j,tmperror);
+	    
+	    */
+	    // ******  END TMP **************			 
+
+	    // tmp
+	    /*
+	    cout << CombinedAlphaTrainOFF -> GetBinContent(j) << " +/-  " 
+		 << CombinedAlphaTrainOFF -> GetBinError(j)
+		 << "  Number Events without normalization: " 
+		 << CombinedAlphaTrainOFFWithoutNormalization[j-1] << endl;
+	    */
+	    // endtmp
+	    
+	}
+
+
+	// Entries of histogram CombinedAlphaTrainON is set to 
+	// the events counted during histogram filling
+
+	EventCounter = EventCounter/MeanNormFactorTrain;
+	tmpint = int (EventCounter);
+	CombinedAlphaTrainOFF->SetEntries(tmpint);
+
+	// Check that the number of events in the combined normalized histogram is 
+	// that of the initial sample
+
+	/*
+	cout << "SILLY INFO FOR TRAIN SAMPLE: Total number of events Before nomralization and " 
+	     << " re-re normalized" << endl
+	     << TotalNumberOFFTrain << " - " << EventCounter << endl;
+
+	*/
+    }
+
+    // *********  COMBINED  HISTOGRAMS FOR TRAIN SAMPLE ALREADY FILLED ********* ///
+
+
+
+
+    // *********  HISTOGRAMS FOR TEST SAMPLE WILL BE FILLED *********  ///
+
+
+    if (CombineTestData)
+    {
+
+      *fLog << endl 
+	<< "****************************************************************************" << endl
+	<< "Combining data for the TEST sample " << endl
+	<< "****************************************************************************" << endl
+	<< endl;
+
+
+	// Retrieving NormFactorTestHisto from root file. 
+	
+	NormFactorTestHisto = (TH1F*) rootfile.Get(NormFactorTestHistoName);
+	// NormFactorTestHisto-> DrawCopy();
+
+	// Check that bins in this histo correspond with the 
+	// CosTheta intervals defined by vector fCosThetaRangeVector
+
+	
+	if (NormFactorTestHisto -> GetNbinsX() != NThetaBins)
+	{
+	    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		  << endl
+		  << "Number of theta bins defined by vector fCosThetaRangeVector (" 
+		  << NThetaBins << ") does not match with the bins in histogram "
+		  << NormFactorTestHistoName << "(" 
+		  << NormFactorTestHisto -> GetNbinsX() << ")" << endl
+		  << "Function execution will be ABORTED." << endl;
+	    return kFALSE;
+	}
+
+	// histo test 
+	/*
+	cout << "NORMFACTORTRAINHIST  TEST: BinCenter and Value" << endl;
+	for (Int_t k = 0; k < NThetaBins; k++)
+	{
+	    
+	    cout << NormFactorTestHisto -> GetBinCenter(k+1) 
+		 << ";  " << NormFactorTestHisto -> GetBinContent(k+1)<< endl;
+	}
+	*/
+
+	
+
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	{
+	    tmpdouble = NormFactorTestHisto -> GetBinCenter(SuccessfulThetaBinsVector[i]);
+	    if (fCosThetaRangeVector[SuccessfulThetaBinsVector[i]-1] > tmpdouble || 
+		fCosThetaRangeVector[SuccessfulThetaBinsVector[i]] < tmpdouble)
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		      << endl
+		      << "Bins defined by vector fCosThetaRangeVector " 
+		      << "do not match with the bins of histogram "
+		      << NormFactorTestHistoName << endl
+		      << "CosTheta: " << fCosThetaRangeVector[SuccessfulThetaBinsVector[i]-1]
+		      << "-" << fCosThetaRangeVector[SuccessfulThetaBinsVector[i]] << endl
+		      << "NormFactorHist Bin: " <<  tmpdouble << endl
+		      << "Function execution will be ABORTED." << endl;
+
+		return kFALSE;
+	    }
+	    
+	}
+
+
+	// Let's summ up all ON alpha distributions
+
+	// Event counter (counts events used in the histogram filling) is 
+	// initialized to zero
+
+	EventCounter = 0;
+
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	{
+	    if (fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1].IsNull())
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		      << endl
+		      << "Component " << SuccessfulThetaBinsVector[i]-1 
+		      << " of fThetaRangeStringVector is EMPTY"
+		      << endl
+		      << "Function execution will be ABORTED." << endl;
+		return kFALSE;
+
+		
+	    }
+
+	
+
+	    TString TmpHistoName = ("TestAlphaAfterCuts");
+	    TmpHistoName += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    *fLog << "Getting Histogram with name " << endl
+		  << TmpHistoName << endl;
+
+	    if (i == 0)
+	    {      
+		CombinedAlphaTestON = (TH1F*) rootfile.Get(TmpHistoName);
+		NAlphaBins = CombinedAlphaTestON -> GetNbinsX();
+
+		// Name of histogram is set
+		CombinedAlphaTestON -> SetName(CombinedAlphaTestONName);
+
+		// EventCounter is updated
+		
+		EventCounter += CombinedAlphaTestON -> GetEntries();
+
+		// tmp
+		cout << "NAlphaBins in histo CombinedAlphaTestON: "
+		     << NAlphaBins << endl;
+		// endtmp
+	    }
+	    else
+	    {
+		TmpTH1FHisto = (TH1F*) rootfile.Get(TmpHistoName);
+
+		// EventCounter is updated
+		
+		EventCounter += TmpTH1FHisto -> GetEntries();
+
+		for (Int_t j = 1; j <= NAlphaBins; j++)
+		{
+		    // At some time alpha bins might not be the same for 
+		    // the different alpha distributions. That's why
+		    // I will check it before summing the alpha histo contents
+		    tmpdouble =  CombinedAlphaTestON->GetBinCenter(j) -
+			TmpTH1FHisto->GetBinCenter(j);
+		    tmpdouble = TMath::Abs(tmpdouble);
+		    
+
+		    if (tmpdouble > SmallQuantity)
+		    {
+			*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+			      << endl
+			      << "Bins among the several alpha ON histograms "
+			      << "for TEST sample do not match"
+			      << endl
+			      << "Function execution will be ABORTED." << endl;
+			return kFALSE;
+		    }
+		    
+		    tmpdouble = CombinedAlphaTestON->GetBinContent(j) + 
+			TmpTH1FHisto->GetBinContent(j);
+
+		    
+		    CombinedAlphaTestON-> SetBinContent(j,tmpdouble);
+
+		}
+		
+		// Dynamic memory allocated for TmpTH1FHisto is released
+
+
+		//tmp
+		cout << "Memory allocated by temporal histogram TmpTH1FHisto "
+		     << "will be released" << endl;
+		//endtmp
+		delete TmpTH1FHisto;
+	    
+	    }
+
+
+
+
+	}
+
+	// Entries of histogram CombinedAlphaTestON is set to 
+	// the events counted during histogram filling
+	tmpint = int (EventCounter);
+	CombinedAlphaTestON->SetEntries(tmpint);
+
+
+	// Let's summ up all OFF alpha distributions
+
+	EventCounter = 0;
+
+	for (Int_t i = 0; i < SuccessfulThetaBinsVector.GetSize(); i++)
+	{
+	    if (fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1].IsNull())
+	    {
+		*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+		      << endl
+		      << "Component " << SuccessfulThetaBinsVector[i]-1 
+		      << " of fThetaRangeStringVector is EMPTY"
+		      << endl
+		      << "Function execution will be ABORTED." << endl;
+		return kFALSE;
+
+		
+	    }
+
+	    TString TmpHistoName = ("TestAlphaOFFAfterCuts");
+	    TmpHistoName += fThetaRangeStringVector[SuccessfulThetaBinsVector[i]-1];
+
+	    // Normalization constant for this theta bin is stored now in tmpnormfactor
+	    tmpnormfactor = NormFactorTestHisto -> GetBinContent(SuccessfulThetaBinsVector[i]);
+
+	    // temp 
+	    cout << "Normalization factor for bin "
+		 << SuccessfulThetaBinsVector[i] << " is "
+		 << tmpnormfactor << endl;
+
+	    // endtemp
+
+	    if (i == 0)
+	    {
+		CombinedAlphaTestOFF = (TH1F*) rootfile.Get(TmpHistoName);
+		NAlphaBins = CombinedAlphaTestOFF -> GetNbinsX();
+	       
+
+		// Name of histogram is set
+		CombinedAlphaTestOFF -> SetName(CombinedAlphaTestOFFName);
+
+		// EventCounter is updated taking into account 
+		// normalization factor
+		
+		EventCounter += tmpnormfactor*CombinedAlphaTestOFF -> GetEntries();
+
+		
+		// Contribution to total number of OFF events and mean normfactor
+		// of this theta bin is computed
+
+		TotalNumberOFFTest = CombinedAlphaTestOFF -> GetEntries();
+		MeanNormFactorTest = tmpnormfactor *
+		    CombinedAlphaTestOFF -> GetEntries();
+
+
+		// Dimension of ErrorInCombinedAlphaTrainOFF is set
+		ErrorInCombinedAlphaTestOFF.Set(NAlphaBins);
+
+		CombinedAlphaTestOFFWithoutNormalization.Set(NAlphaBins);
+
+
+		// Histogram now is normalized (to the respective ON data)
+		// by using the normalization constants stored in 
+		// histogram NormFactorTestHisto
+
+		
+		for (Int_t j = 1; j <= NAlphaBins; j++)
+		{
+
+		    // Vector containing number of events without 
+		    // normalization is filled
+		   
+			CombinedAlphaTestOFFWithoutNormalization[j-1] = 
+			    CombinedAlphaTestOFF -> GetBinContent(j);
+		   
+
+
+		    tmpdouble2 = tmpnormfactor * 
+			CombinedAlphaTestOFF -> GetBinContent(j);
+
+		    CombinedAlphaTestOFF -> SetBinContent(j,tmpdouble2);
+
+		    // (Bin Error)^2 is computed and stored in 
+		    // ErrorInCombinedAlphaTestOFF
+		    // Bin error = Sqrt(BinContent) X Normalization Factor
+
+		    tmperror = tmpdouble2*tmpnormfactor;
+		    ErrorInCombinedAlphaTestOFF[j-1] = tmperror;
+
+
+		}
+
+	    }
+	    else
+	    {
+		TmpTH1FHisto = (TH1F*) rootfile.Get(TmpHistoName);
+
+
+		// EventCounter is updated taking into account 
+		// normalization factor
+		
+		EventCounter += tmpnormfactor* TmpTH1FHisto-> GetEntries();
+
+		// Contribution to total number of OFF events and mean normfactor
+		// of this theta bin is computed
+
+
+		TotalNumberOFFTest += TmpTH1FHisto -> GetEntries();
+		MeanNormFactorTest += tmpnormfactor *
+		    TmpTH1FHisto -> GetEntries();
+
+
+
+		for (Int_t j = 1; j <= NAlphaBins; j++)
+		{
+		    // At some time alpha bins might not be the same for 
+		    // the different alpha distributions. That's why
+		    // I will check it before summing the alpha histo contents
+		    tmpdouble2 =  CombinedAlphaTestOFF->GetBinCenter(j) -
+			TmpTH1FHisto->GetBinCenter(j);
+		    tmpdouble2 = TMath::Abs(tmpdouble2);
+
+		    if (tmpdouble2 > SmallQuantity)
+		    {
+			*fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance()" 
+			      << endl
+			      << "Bins among the several alpha OFF histograms "
+			      << "for TRAIN sample do not match"
+			      << endl
+			      << "Function execution will be ABORTED." << endl;
+			return kFALSE;
+		    }
+		    
+
+		    // Vector containing number of events without 
+		    // normalization is updated
+
+		    // Vector containing number of events without 
+		    // normalization is filled
+		   
+			CombinedAlphaTestOFFWithoutNormalization[j-1] += 
+			    TmpTH1FHisto -> GetBinContent(j);
+		   
+
+
+
+		    
+		    
+		    // Histogram bin contents must be normalized (to the respective ON data)
+		    // by using the normalization constants stored in 
+		    // histogram NormFactorTestHisto before being added 
+		    // to CombinedAlphaTestOFF
+
+		   
+		    tmpdouble2 = CombinedAlphaTestOFF->GetBinContent(j) + 
+			(TmpTH1FHisto->GetBinContent(j) * tmpnormfactor);
+
+		    
+		    CombinedAlphaTestOFF-> SetBinContent(j,tmpdouble2);
+
+
+		     // (Bin Error)^2 is computed and added to  
+		    // ErrorInCombinedAlphaTestOFF 
+		    // Bin error = Sqrt(BinContent) X Normalization Factor
+
+		    tmperror = TmpTH1FHisto->GetBinContent(j) * tmpnormfactor;
+		    ErrorInCombinedAlphaTestOFF[j-1] += tmperror;
+
+
+		}
+		
+		// Dynamic memory allocated for TmpTH1FHisto is released
+
+		delete TmpTH1FHisto;
+	    
+	    }
+
+	    
+
+
+
+	}
+
+
+
+	// Mean Normalization factor is computed for the combined OFF histogram. 
+	// This factor will be used when computing the significance via 
+	// MHFindSignificance::FindSigmaONOFF().
+
+	// The bin contents (and errors) of teh combined OFF TEST histo will be 
+	// normalized (divided) by teh mean norm constant, so that 
+	// the histogram for OFF data given as argument in FindSigmaONOFF
+	// is equivalent to a non-normalized histogram. 
+	
+	MeanNormFactorTest = MeanNormFactorTest/TotalNumberOFFTest;
+
+
+
+	// Sqrt(Contents) is performed in ErrorInCombinedAlphaTestOFF, 
+	// in order to compute the real error in the bin content of histogram 
+	// CombinedAlphaTestOFF.
+
+	// Then error and contents (normalized with mean normfctor) are
+	// set to histogram bin 	
+
+
+
+
+	
+	for (Int_t j = 1; j <= NAlphaBins; j++)
+	{
+
+	    tmpdouble2 = 
+		(CombinedAlphaTestOFF -> GetBinContent(j))/MeanNormFactorTest;
+
+	    CombinedAlphaTestOFF -> SetBinContent(j,tmpdouble2);
+
+	    ErrorInCombinedAlphaTestOFF[j-1] = 
+		TMath::Sqrt(ErrorInCombinedAlphaTestOFF[j-1])/MeanNormFactorTest;
+
+	    // Proper error treatment for the bin contents 
+	    CombinedAlphaTestOFF -> SetBinError(j,ErrorInCombinedAlphaTestOFF[j-1]);
+	    
+	    
+	    // ******  TMP **************
+	    /*
+	    // Error computation assuming a given (no normalized) bin content
+	    
+	    tmpdouble = CombinedAlphaTestOFF -> GetBinContent(j);
+
+	    if (CombinedAlphaTestOFFWithoutNormalization[j-1] < SmallQuantity)
+	    {tmpnormfactor = 0;}
+	    else
+	    {tmpnormfactor = tmpdouble/CombinedAlphaTestOFFWithoutNormalization[j-1];}
+	   
+	    tmperror = (TMath::Sqrt(CombinedAlphaTestOFFWithoutNormalization[j-1])) * tmpnormfactor;
+	    
+	    CombinedAlphaTestOFF -> SetBinError(j,tmperror);
+	    
+	    */
+	    
+	    // ******  ENDTMP **************
+	    
+	    // tmp
+	    // cout << CombinedAlphaTestOFF -> GetBinContent(j) << " +/-  " 
+	    //	 << CombinedAlphaTestOFF -> GetBinError(j) << endl;
+	    
+	    // endtmp
+
+	}
+
+
+	
+	// Entries of histogram CombinedAlphaTestOFF is set to 
+	// the events counted during histogram filling
+	
+	EventCounter = EventCounter/MeanNormFactorTest;
+	tmpint = int(EventCounter);
+	CombinedAlphaTestOFF->SetEntries(tmpint);
+
+
+	// Check that the number of events in the combined normalized histogram is 
+	// that of the initial sample
+
+	/*
+	cout << "SILLY INFO FOR TEST SAMPLE: Total number of events Before nomralization and " 
+	     << " re-re normalized" << endl
+	     << TotalNumberOFFTest << " - " << EventCounter << endl;
+
+	*/
+
+
+	/*
+	// Sumw2() test
+
+	cout << "********   TEST   ********* " << endl;
+	cout << "Sumw2() is executed: " << endl;
+	CombinedAlphaTestOFF -> Sumw2();
+	for (Int_t j = 1; j <= NAlphaBins; j++)
+	{
+	     // tmp
+	    cout << CombinedAlphaTestOFF -> GetBinContent(j) << " +/-  " 
+		 << CombinedAlphaTestOFF -> GetBinError(j) << endl;
+	    
+	    // endtmp
+
+	}
+	  
+	*/
+	
+	
+
+    }
+
+
+
+     // *********  COMBINED  HISTOGRAMS FOR TEST SAMPLE ALREADY FILLED ********* ///
+
+
+    /*
+    CombinedAlphaTrainON-> DrawCopy();
+    gPad -> SaveAs("tmpONTrain.ps");
+
+    CombinedAlphaTrainOFF-> DrawCopy();
+    gPad -> SaveAs("tmpOFFTrain.ps");
+
+
+    CombinedAlphaTestON-> DrawCopy();
+    gPad -> SaveAs("tmpONTest.ps");
+
+    CombinedAlphaTestOFF-> DrawCopy();
+    gPad -> SaveAs("tmpOFFTest.ps");
+
+    */
+    
+
+    // ****  COMPUTATION OF SIGNIFICANCES FOR COMBINED ALPHA HISTOGRAMS  ****** ///
+    
+    if (SuccessfulThetaBinsVector.GetSize() >= 1)
+    {
+
+
+      *fLog << endl 
+	<< "**************************************************************************************" << endl
+	<< "Computation of excess events and singnificance for the combined alpha histograms " << endl
+	<< "**************************************************************************************" << endl
+	<< endl;
+
+	// There is, at least, ONE theta bin for which optimization of 
+	// supercuts was SUCCESSFUL, and thus, it is worth to 
+	// compute significance of signal
+
+		
+	// Significance is found using MHFindSignificanceONOFF::FindSigmaONOFF
+	
+
+	
+	// Maximum value of alpha below which signal is expected
+	const Double_t alphasig = fAlphaSig; 
+
+	// Minimum value of alpha for bkg region in ON data
+	const Double_t alphabkgmin = fAlphaBkgMin;
+	
+	// Maximum value of alpha for bkg region in ON data
+	const Double_t alphabkgmax = fAlphaBkgMax;
+	
+	
+	const Bool_t   drawpoly  = kTRUE;
+	const Bool_t   fitgauss  = kTRUE;
+	const Bool_t   print     = kTRUE;
+    
+	const Bool_t saveplots   = kTRUE; // Save final alpha plot for ON and OFF 
+	// (with Nex and significance) in Psfile
+   
+
+
+
+	MHFindSignificanceONOFF findsig;
+	findsig.SetRebin(kTRUE);
+	findsig.SetReduceDegree(kFALSE);
+
+	
+
+	if (CombineTrainData)
+	{
+
+	    // Name of psfile where Alpha plot will be stored
+	  
+	    TString psfilename = (fPathForFiles);
+	    psfilename += ("TRAINSampleCombinedThetaBins"); 
+	    
+	    findsig.FindSigmaONOFF(CombinedAlphaTrainON, CombinedAlphaTrainOFF, 
+				   MeanNormFactorTrain, 
+				   alphabkgmin, alphabkgmax, 
+				   fDegreeON, fDegreeOFF,
+				   alphasig, 
+				   drawpoly, fitgauss, print, 
+				   saveplots, psfilename);
+
+
+	  fOverallSigmaLiMaTrain = double(findsig.GetSignificance());
+	  fOverallNexTrain = double(findsig.GetNexONOFF());
+
+	  *fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance" << endl
+		<< "After performing the combined analysis for TRAIN sample it was found " 
+		<< "the following Nex and Significance: " <<  fOverallNexTrain 
+		<< ", " << fOverallSigmaLiMaTrain << endl;
+	      
+
+	}
+
+
+	if (CombineTestData)
+	{
+
+	    // Name of psfile where Alpha plot will be stored
+	  TString psfilename = (fPathForFiles);
+	  psfilename += ("TESTSampleCombinedThetaBins"); 
+	    
+	    findsig.FindSigmaONOFF(CombinedAlphaTestON, CombinedAlphaTestOFF, 
+				   MeanNormFactorTest, 
+				   alphabkgmin, alphabkgmax, 
+				   fDegreeON, fDegreeOFF,
+				   alphasig, 
+				   drawpoly, fitgauss, print, 
+				   saveplots, psfilename);
+
+	    fOverallSigmaLiMaTest = double(findsig.GetSignificance());
+	    fOverallNexTest = double(findsig.GetNexONOFF());
+	    
+	    *fLog << "MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance" << endl
+		  << "After performing the combined analysis for TEST sample it was found " 
+		  << "the following Nex and Significance: " <<  fOverallNexTest 
+		  << ", " << fOverallSigmaLiMaTest << endl;
+	    
+	}
+	
+	
+
+	*fLog << endl 
+	      << "**************************************************************************************" << endl
+	      << "Alpha distributions (Train/Test and ON/OFF) for the combined  " << endl
+	      << " theta bins are stored in the root file " << endl 
+	      << fAlphaDistributionsRootFilename << endl
+	      << "**************************************************************************************" << endl
+	<< endl;
+
+
+
+	TFile rootfiletowrite(fAlphaDistributionsRootFilename, "UPDATE");
+
+
+	
+	// Histograms that will contain the Norm factors for the 
+	// combined TRAIN/TEST theta bins are created
+
+	
+	TString CombinedNormFactorTrainName = ("TrainSampleNormFactorCombinedThetaBins");
+	TH1F CombinedNormFactorTrain (CombinedNormFactorTrainName, 
+				      CombinedNormFactorTrainName, 
+				      1, 0.0, 1.0);
+
+	TString CombinedNormFactorTestName = ("TestSampleNormFactorCombinedThetaBins");
+	TH1F CombinedNormFactorTest (CombinedNormFactorTestName, 
+				     CombinedNormFactorTestName, 
+				     1, 0.0, 1.0);
+
+
+	if (CombineTrainData)
+	{
+
+	// Histogram that will contain the Norm factors for the 
+	// combined TRAIN theta bins are filled
+	
+	
+	CombinedNormFactorTrain.Fill(0.5, MeanNormFactorTrain);
+
+
+	// Train histos are written to root file
+	
+	CombinedAlphaTrainON -> Write();
+	CombinedAlphaTrainOFF -> Write();
+	CombinedNormFactorTrain.Write();
+
+
+
+	}
+
+
+	if (CombineTestData)
+	{
+
+	  // Histogram that will contain the Norm factors for the 
+	// combined TEST theta bins are filled
+
+	
+	  CombinedNormFactorTest.Fill(0.5, MeanNormFactorTest);
+
+	  // Test histos are written to root file
+
+	CombinedAlphaTestON -> Write();
+	CombinedAlphaTestOFF -> Write();
+	CombinedNormFactorTest.Write();
+	
+
+	}
+
+
+	// Root file is closed
+
+	rootfiletowrite.Close();
+
+	
+    }
+
+
+    return kTRUE;
+}
+
+    
+    
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFFThetaLoop.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFFThetaLoop.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MFindSupercutsONOFFThetaLoop.h	(revision 9772)
@@ -0,0 +1,467 @@
+#ifndef MARS_MFindSupercutsONOFFThetaLoop
+#define MARS_MFindSupercutsONOFFThetaLoop
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TH1F
+#include <TH1F.h>
+#endif
+
+#ifndef ROOT_TPostScript
+#include <TPostScript.h>
+#endif
+
+
+class MFilter;
+class MEvtLoop;
+class MH3;
+class MSupercutsCalcONOFF;
+class MFindSupercutsONOFF;
+class MGeomCam;
+class MHMatrix;
+
+
+class MFindSupercutsONOFFThetaLoop : public MParContainer
+{
+private:
+
+  TString fDataONRootFilename;
+  TString fDataOFFRootFilename;
+
+
+  TString fPathForFiles; // Path to directory where files (PsFiles, rootfiles) will be stored
+
+  
+  TString*  fOptSCParamFilenameVector; // Pointer to vector of TStrings containing name of the root files where optimized supercuts will be stored. To be created and filled once Vector of Costheta ranges is defined
+
+  
+
+
+  // Vectors containing the names of the root files where matrices 
+  // will be stored for Train/Test ON/OFF samples.
+  // To be defined and filled once vector fCosThetaRangeVector is 
+  // defined
+
+  TString* fTrainMatrixONFilenameVector;
+  TString* fTestMatrixONFilenameVector;
+  TString* fTrainMatrixOFFFilenameVector;
+  TString* fTestMatrixOFFFilenameVector;
+  
+
+  Double_t fAlphaSig; // Max alpha value were signal is expected
+
+
+  // Background range (in alpha) is defined by the member variables 
+  // fAlphaBkgMin and fAlphaBkgMax
+  Double_t fAlphaBkgMin; 
+  Double_t fAlphaBkgMax; 
+
+
+  // Degree used in the polyinomial fits for ON and OFF data
+
+  Int_t fDegreeON;
+  Int_t fDegreeOFF;
+
+
+
+
+
+  // Size range of events used to fill the data matrices  
+  // is defined by the following variables
+
+  Double_t fSizeCutLow;
+  Double_t fSizeCutUp;
+
+  Double_t fLeakMax;
+  Double_t fDistMax;
+  Double_t fDistMin;
+  
+ // Variables for binning of alpha plots
+  
+  Int_t fNAlphaBins;
+  Double_t fAlphaBinLow;
+  Double_t fAlphaBinUp;
+
+
+
+  // Boolean variable used to disable the usage ("serious" usage) of the 
+  // quantities computed from fits. This will be useful in those cases 
+  // where there is too few events to perform a decent fit to the 
+  // alpha histograms. In general this variable will be always kTRUE
+  
+  Bool_t fUseFittedQuantities;
+
+
+  Double_t fPolyGaussFitAlphaSigma;
+
+
+  Double_t fWhichFractionTrain;  // number <= 1; specifying fraction of ON Train events
+  Double_t fWhichFractionTest;  // number <= 1; specifying fraction of ON Test events
+
+   Double_t fWhichFractionTrainOFF;  // number <= 1; specifying fraction of OFF  Train events
+  Double_t fWhichFractionTestOFF;  // number <= 1; specifying fraction of OFF Test events
+
+  Double_t fThetaMin; // Cuts in ThetaOrig.fVal (in rad!!!)
+  Double_t fThetaMax; // Cuts in ThetaOrig.fVal (in rad !!!)
+  TArrayD fCosThetaRangeVector; // vector containing the 
+  // theta ranges that will be used in the 
+  // optimization
+
+  TString* fThetaRangeStringVector; // Pointer to vector of TStrings that contain Cos theta ranges specified in fCosThetaRangeVector. It will be used to identify alpha distributions stored in fAlphaDistributionsRootFilename
+
+  TArrayD fCosThetaBinCenterVector; // vector containing the 
+  // theta bin centers of the theta ranges/bins contained in 
+  // fCosThetaRangeVector
+
+  Double_t fActualCosThetaBinCenter; // Theta value used to fill 
+  // the histograms fNormFactorTrainHist, fNormFactorTestHist, 
+  // fSigmaLiMaTrainHist ...
+
+  
+
+  Double_t fOverallNexTrain;
+  Double_t fOverallNexTest;
+
+  Double_t fOverallSigmaLiMaTrain;
+  Double_t fOverallSigmaLiMaTest;
+  
+
+  TH1F* fSuccessfulThetaBinsHist; // Hist containing theta bins were optimization was successful
+
+  TH1F* fNormFactorTrainHist; // Hist containing norm factors train for all Cos theta ranges
+  TH1F* fNormFactorTestHist; // Hist containing norm factors test for all Cos theta ranges
+  TH1F* fSigmaLiMaTrainHist; // Hist containing SigmaLiMa for Train samples for all Cos theta ranges
+  TH1F* fSigmaLiMaTestHist; // Hist containing SigmaLiMa for Test samples for all Cos theta ranges
+  TH1F* fNexTrainHist; // Hist containing Number os excess events for Train sample for all Cos thetas
+  TH1F* fNexTestHist; // Hist containing Number os excess events for Test sample for all Cos theta
+
+  TH1F* fNEvtsInTrainMatrixONHist; // Hist containing total number of events in Train Matrices of ON data for all Cos theta ranges
+  TH1F* fNEvtsInTestMatrixONHist; // Hist containing total number of events in Test Matrices of ON data for all Cos theta ranges
+  TH1F* fNEvtsInTrainMatrixOFFHist; // Hist containing total number of events in Train Matrices of OFF data for all Cos theta ranges
+  TH1F* fNEvtsInTestMatrixOFFHist; // Hist containing total number of events in Test Matrices of OFF data for all Cos theta ranges
+  
+
+
+ 
+  // Boolean variable that controls wether the optimization of the 
+  // parameters (MMinuitInterface::CallMinuit(..) in function FindParams(..))
+  // takes place or not. kTRUE will skip such optimization.
+  // This variable is useful to test the optmized parameters (previously found 
+  // and stored in root file) on the TRAIN sample.
+
+  Bool_t fSkipOptimization;
+
+
+
+
+  // Boolean variable that allows the user to write the initial parameters 
+  // into the root file that will be used to store the optimum cuts.
+  // If fUseInitialSCParams = kTRUE , parameters are written.
+  // In this way, the initial SC parameters can be applied on the data (train/test) 
+  
+  // The initial parameters are ONLY written to the root file if 
+  // there is NO SC params optimization, i.e., if variable 
+  // fSkipOptimization = kTRUE;
+  
+  // The default value is obviously kFALSE.
+
+  Bool_t fUseInitialSCParams;
+
+
+  Double_t fGammaEfficiency; // Fraction of gammas that remain after cuts
+  // Quantity that will have to be determined with MC
+
+  Bool_t fTuneNormFactor; // If true, normalization factors are corrected 
+  // using the estimated number of gammas and the gamma efficiency
+  // fNormFactor = fNormFactor - Ngammas/EventsInMatrixOFF
+
+
+  // Boolean variable used to determine wether the normalization factor is 
+  // computed from method 1) or 2)
+  // 1) Using total number of ON and OFF events before cuts, and tuning the factor 
+  //    correcting for "contamination" of gamma events in ON sample
+  // 2) Using number of ON and OFF events after cuts in the background 
+  //    region determined by variables fAlphaBkgMin-fAlphaBkgMax
+ 
+  Bool_t fNormFactorFromAlphaBkg; // if kTRUE, method 2) is used
+
+
+  // Boolean variable used to control decide wether to use theta information 
+  // in the computation of teh dynamical cuts.
+  Bool_t fNotUseTheta;
+  
+  // Boolean variable used to decide wether to use dynamical cuts or static cuts
+  // kTRUE means that static cuts are used. 
+  Bool_t fUseStaticCuts;
+
+
+  // Names for the Hadronness containers for ON and OFF data
+
+  TString  fHadronnessName;
+  TString  fHadronnessNameOFF;
+
+  // Vectors where initial SC parameters and steps are stored. 
+  // If these vectors are empty, initial SC parameters and steps 
+  // are taken from Supercuts container. 
+  // They will be intialized to empty vectors in constructor
+
+  TArrayD fInitSCPar;
+  TArrayD fInitSCParSteps;
+
+  
+
+  // Name of Postscript file where, for each theta bin,  alpha ON and OFF distributions 
+  //  after cuts (and hence, Nex and SigmaLiMa computations) will be stored
+  // If fAlphaDistributionsPostScriptFilename is not defined, postscript file is not 
+  // produced. It is an optional variable...
+
+  // Still not working...
+ 
+  TPostScript* fPsFilename; 
+
+
+  // ********************************************************
+  // Due to the failure of the use of object TPostScript
+  // to make a Ps document with all plots, I decided to use the 
+  // standard way (SaveAs(filename.ps)) to store plots related 
+  // to alpha distributions 
+  // for ON and OFF and BEFORE and AFTER cuts (VERY IMPORTANT
+  // TO COMPUTE EFFICIENCIES IN CUTS) 
+  
+  // Psfilename is set inside function LoopOverThetaRanges()
+  // and given to the object MFindSupercutsONOFF created 
+  // within this loop.
+
+  // This will have to be removed as soon as the TPostScript
+  // solutions works...
+  // ********************************************************
+  
+
+  TString fAlphaDistributionsRootFilename;
+  // Root file where histograms containing the ON alpha distribution and the 
+  // OFF alpha distribution (non normalized) , AFTER CUTS, are stored.
+  // Histograms containing the normalization factors, Nex and SigmaLiMa for 
+  // each theta bin will be also stored there.
+  // This name MUST be defined, since the histograms 
+  // stored there will be used by 
+  // function XXX to compute an overall Nex and sigmaLiMa 
+  // combining all those histograms
+
+  // Boolean variables seting flags for loop over theta ranges
+
+  Bool_t fReadMatricesFromFile;
+  Bool_t fOptimizeParameters;
+  Bool_t fTestParameters;
+  
+   //--------------------------------------------
+
+
+public:
+  MFindSupercutsONOFFThetaLoop(const char *name=NULL, 
+				  const char *title=NULL);
+  ~MFindSupercutsONOFFThetaLoop();
+
+  void SetHadronnessName(const TString &name)   
+      {fHadronnessName = name;}
+  void SetHadronnessNameOFF(const TString &name)   
+      {fHadronnessNameOFF = name;}
+
+  void SetPathForFiles(const TString &path)
+      {fPathForFiles = path;}
+
+  void SetDataONOFFRootFilenames(const TString &name1, const TString &name2 ) 
+      {fDataONRootFilename = name1;  fDataOFFRootFilename = name2; }
+
+
+
+  // Names of root files containing matrices and  optimizedparameters 
+   Bool_t SetALLNames(); 
+
+  // Function to set names manually... in case matrices are 
+  // already defined...
+
+  Bool_t SetNamesManually(TString* OptSCParamFilenameVector, 
+			  TString* ThetaRangeStringVector,
+			  TString* TrainMatrixONFilenameVector,
+			  TString* TestMatrixONFilenameVector,
+			  TString* TrainMatrixOFFFilenameVector,
+			  TString* TestMatrixOFFFilenameVector) 
+
+      {   
+	  fOptSCParamFilenameVector = OptSCParamFilenameVector;
+	  fThetaRangeStringVector = ThetaRangeStringVector;
+	  fTrainMatrixONFilenameVector = TrainMatrixONFilenameVector;
+	  fTestMatrixONFilenameVector = TestMatrixONFilenameVector;
+	  fTrainMatrixOFFFilenameVector = TrainMatrixOFFFilenameVector;
+	  fTestMatrixOFFFilenameVector = TestMatrixOFFFilenameVector; 
+
+	  return kTRUE;
+      }
+  
+  Bool_t SetAlphaDistributionsRootFilename(const TString &name); 
+
+
+  Bool_t SetAlphaSig (Double_t alphasig);
+
+  Bool_t SetAlphaBkgMin (Double_t alphabkgmin);
+  Bool_t SetAlphaBkgMax (Double_t alphabkgmax);
+
+
+  void SetDegreeON (Int_t d) {fDegreeON = d;}
+  void SetDegreeOFF (Int_t d) {fDegreeOFF = d;}
+
+  Bool_t CheckAlphaSigBkg();
+
+  void SetPostScriptFile(TPostScript* PsFile);
+
+
+  Bool_t SetCosThetaRangeVector (const TArrayD &d);
+  
+  Bool_t SetThetaRange (Int_t thetabin);
+
+
+  void SetAlphaPlotBinining(Int_t nbins, Double_t binlow, Double_t binup)
+    { fNAlphaBins = nbins; fAlphaBinLow = binlow; fAlphaBinUp = binup;}
+
+  Bool_t SetNormFactorTrainHist();
+  Bool_t SetNormFactorTestHist();
+  Bool_t SetSigmaLiMaTrainHist();
+  Bool_t SetSigmaLiMaTestHist();
+  Bool_t SetNexTrainHist();
+  Bool_t SetNexTestHist();
+  Bool_t SetNexSigmaLiMaNormFactorNEvtsTrainTestHist();
+  Bool_t SetSuccessfulThetaBinsHist();
+  void WriteNexSigmaLiMaNormFactorNEvtsTrainTestHistToFile();
+
+  void WriteSuccessfulThetaBinsHistToFile();
+  
+  
+  Bool_t SetInitSCPar (TArrayD &d);
+  Bool_t SetInitSCParSteps (TArrayD &d);
+
+  
+
+  Bool_t ReadSCParamsFromAsciiFile(const char* filename, Int_t Nparams);
+
+
+  void SetFractionTrainTestOnOffEvents(Double_t fontrain, 
+				       Double_t fontest, 
+				       Double_t fofftrain,
+				       Double_t fofftest);
+
+   void SetTuneNormFactor(Bool_t b) {fTuneNormFactor = b;}
+   Bool_t SetGammaEfficiency (Double_t gammaeff);
+   
+
+
+   void SetNormFactorFromAlphaBkg (Bool_t b) {fNormFactorFromAlphaBkg = b;}
+
+   void SetUseFittedQuantities (Bool_t b)
+      {fUseFittedQuantities = b;}
+
+   void SetReadMatricesFromFile(Bool_t b);
+   void SetTrainParameters(Bool_t b) {fOptimizeParameters = b;}
+   void SetTestParameters(Bool_t b) {fTestParameters = b;}
+
+
+   void SetSkipOptimization(Bool_t b) {fSkipOptimization = b;}
+
+   void SetUseInitialSCParams(Bool_t b) {fUseInitialSCParams = b;}
+
+
+   void SetVariableNotUseTheta(Bool_t b) {fNotUseTheta = b;}
+   Bool_t GetVariableNotUseTheta() { return fNotUseTheta;}
+
+
+   void SetVariableUseStaticCuts(Bool_t b) {fUseStaticCuts = b;}
+   Bool_t GetVariableUseStaticCuts() { return fUseStaticCuts;}
+
+
+   void SetSizeRange(Double_t SizeMin, Double_t SizeMax)
+	{fSizeCutLow = SizeMin; fSizeCutUp = SizeMax; }
+
+//DM:
+   void SetFilters(Double_t LeakageMax, Double_t DistMax, Double_t DistMin)
+	{fLeakMax = LeakageMax; fDistMax = DistMax; fDistMin = DistMin; }
+
+   // Function that loops over the theta ranges defined by 
+   // fCosThetaRangeVector optimizing parameter and/or testing
+   // parameters
+
+   Bool_t LoopOverThetaRanges();
+
+
+   // Function that loops over the alpha distributions (ON-OFF)
+   // stored in root file defined by fAlphaDistributionsRootFilename
+   // and computes the significance and Nex (using MHFindSignificanceONOFF::FindSigma)
+   // for several cuts in alpha (0-fAlphaSig; in bins defined for alpha distributions 
+   // by user).
+
+   // It creates the histograms, fills them and store them 
+   // in root file defined by fAlphaDistributionsRootFilename. A single histogram 
+   // for each theta bin.
+
+   // The function returns kFALSE if it could not accomplish its duty
+
+   Bool_t ComputeNexSignificanceVSAlphaSig();
+
+   
+
+
+   // Function that gets the histograms with the alpha distributions
+   // (for all the theta bins specified by fCosThetaRangeVector)
+   // stored in fAlphaDistributionsRootFilename, and combine them
+   // (correcting OFF histograms with the normalization factors stored 
+   // in NormFactorTrain or NormFactorTest) to get one single 
+   // Alpha distribution for ON and another one for OFF. 
+   // Then these histograms are given as arguments to 
+   // the function MHFindSignificanceONOFF::FindSigmaONOFF, 
+   // (Object of this class is created) to compute the 
+   // Overall Excess events and  significance, that will be 
+   // stored in variables fOverallNexTrain and fOverallSigmaLiMaTrain
+   // and Test.
+
+ 
+
+   Bool_t ComputeOverallSignificance(Bool_t CombineTrainData,
+				     Bool_t CombineTestData);
+
+
+   Double_t GetOverallNexTrain() {return fOverallNexTrain;}
+   Double_t GetOverallNexTest() {return fOverallNexTest;}
+   
+   Double_t GetOverallSigmaLiMaTrain() {return fOverallSigmaLiMaTrain;}
+   Double_t GetOverallSigmaLiMaTest() {return fOverallSigmaLiMaTest;}
+
+   Double_t GetGammaEfficiency() {return fGammaEfficiency;}
+
+   Double_t GetAlphaSig() {return fAlphaSig;}
+  Double_t GetAlphaBkgMin () {return fAlphaBkgMin;}
+  Double_t GetAlphaBkgMax () {return fAlphaBkgMax;}
+
+  Int_t GetDegreeON () {return fDegreeON;}
+  Int_t GetDegreeOFF () {return fDegreeOFF;}
+
+   
+  Bool_t GetSkipOptimization() {return fSkipOptimization;}
+
+  Bool_t GetUseFittedQuantities() {return fUseFittedQuantities;}
+ 
+   ClassDef(MFindSupercutsONOFFThetaLoop, 1) 
+  // Class for optimization of the Supercuts
+};
+
+#endif
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MHFindSignificanceONOFF.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MHFindSignificanceONOFF.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MHFindSignificanceONOFF.cc	(revision 9772)
@@ -0,0 +1,3740 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek,  July 2003      <mailto:wittek@mppmu.mpg.de>
+!              David Paneque,    Nov 2003       <mailto:dpaneque@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHFindSignificanceONOFF
+//
+// determines the significance of a gamma signal in an |alpha| plot
+// it uses real OFF events in the computation of excess events
+//
+// Input :  2 TH1 histogram (ON and OFF) of |alpha| : with 0 < |alpha| < 90 degrees
+//  
+//************TEMP ************************************************
+
+
+//         alphamin, alphamax :     defining the background region
+//         alphasig           :     defining the signal region for which
+//                                  the significance is calculated
+//         degree : the degree of the polynomial to be fitted to the background
+//                  ( a0 + a1*x + a2*x**2 + a3*x**3 + ...) 
+//
+// Output : 
+//
+//
+//   - the number of events in the signal region (Non)
+//     the number of background events in the signal region (Nbg)
+//     (counted number of events 'NoffSig' and fitted number of events 'NoffSigFitted 
+//   - the number of excess events in the signal region (Nex = Non - Nbg)
+//     (again, counted 'NexONOFF' and fitted 'NexONOFFFitted'
+//   - thew effective number of background events (Noff), and gamma :
+//     Nbg = gamma * Noff
+//   - 
+//   - the significance of the gamma signal according to Li & Ma               
+//     3 significances are computed 
+//        a) LiMa formula (17) using fitted quantities; fSigLiMa
+//        b) LiMa formula (17) using counted quantities; fSigLiMa2
+//        c) LiMa formula (5) using counted quantities.
+//
+// call member function 'FindSigmaONOFF' 
+//      to fit the background and to determine the significance  
+//
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+
+////////// ***********  ENDTEMPORAL  *************************
+
+
+#include "MHFindSignificanceONOFF.h"
+
+#include <fstream>
+#include <math.h>
+
+#include <TArrayD.h>
+#include <TArrayI.h>
+#include <TH1.h>
+#include <TF1.h>
+#include <TCanvas.h>
+#include <TFitter.h>
+#include <TMinuit.h>
+#include <TPaveText.h>
+#include <TStyle.h>
+#include <TPostScript.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMinuitInterface.h"
+
+
+ClassImp(MHFindSignificanceONOFF);
+
+using namespace std;
+
+const TString MHFindSignificanceONOFF::gsDefName  = "MHFindSignificanceONOFF";
+const TString MHFindSignificanceONOFF::gsDefTitle = "Find Significance in alpha plot";
+
+
+
+// --------------------------------------------------------------------------
+//
+// fcnpoly
+//
+// calculates the chi2 for the fit of the polynomial function 'poly' 
+// to the histogram 'fhist'
+//
+// it is called by CallMinuit() (which is called in FitPolynomial()) 
+//
+// bins of fhist with huge errors are ignored in the calculation of the chi2
+// (the huge errors were set in 'FitPolynomial()')
+//
+
+static void fcnpoly(Int_t &npar, Double_t *gin, Double_t &f, 
+                    Double_t *par, Int_t iflag)
+{
+    TH1 *fhist = (TH1*)gMinuit->GetObjectFit();
+    TF1 *fpoly = fhist->GetFunction("Poly");    
+
+
+    //-------------------------------------------
+
+    Double_t chi2 = 0.0;
+
+    Int_t nbins = fhist->GetNbinsX();
+    Int_t mbins = 0;
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      Double_t content = fhist->GetBinContent(i);
+      Double_t error   = fhist->GetBinError(i);
+      Double_t center  = fhist->GetBinCenter(i);
+
+      //-----------------------------
+      // ignore unwanted points      if (error > 1.e19)
+        continue;
+
+      if (content <= 0.0)
+      {
+        gLog << "fcnpoly : bin with zero content; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      if (error <= 0.0)
+      {
+        gLog << "fcnpoly : bin with zero error; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      //-----------------------------
+      mbins++;
+
+      Double_t fu;
+      fu = fpoly->EvalPar(&center, par);
+
+      // the fitted function must not be negative
+      if (fu <= 0.0)
+      {
+        chi2 = 1.e10;
+        break;
+      }
+
+      Double_t temp = (content - fu) / error;
+      chi2 += temp*temp;
+    }
+
+    //-------------------------------------------
+
+    f = chi2;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+// --------------------------------------------------------------------------
+//
+// fcnpolyOFF
+//
+// calculates the chi2 for the fit of the polynomial function 'poly' 
+// to the histogram 'fhist'
+//
+// it is called by CallMinuit() (which is called in FitPolynomial()) 
+//
+// bins of fhist with huge errors are ignored in the calculation of the chi2
+// (the huge errors were set in 'FitPolynomial()')
+//
+
+static void fcnpolyOFF(Int_t &npar, Double_t *gin, Double_t &f, 
+		       Double_t *par, Int_t iflag)
+{
+    TH1 *fhist = (TH1*)gMinuit->GetObjectFit();
+    TF1 *fpoly = fhist->GetFunction("PolyOFF");    
+
+
+    //-------------------------------------------
+
+    Double_t chi2 = 0.0;
+
+    Int_t nbins = fhist->GetNbinsX();
+    Int_t mbins = 0;
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      Double_t content = fhist->GetBinContent(i);
+      Double_t error   = fhist->GetBinError(i);
+      Double_t center  = fhist->GetBinCenter(i);
+
+      //-----------------------------
+      // ignore unwanted points
+      if (error > 1.e19)
+        continue;
+
+      if (content <= 0.0)
+      {
+        gLog << "fcnpoly : bin with zero content; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      if (error <= 0.0)
+      {
+        gLog << "fcnpoly : bin with zero error; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      //-----------------------------
+      mbins++;
+
+      Double_t fu;
+      fu = fpoly->EvalPar(&center, par);
+
+      // the fitted function must not be negative
+      if (fu <= 0.0)
+      {
+        chi2 = 1.e10;
+        break;
+      }
+
+      Double_t temp = (content - fu) / error;
+      chi2 += temp*temp;
+    }
+
+    //-------------------------------------------
+
+    f = chi2;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+
+
+// --------------------------------------------------------------------------
+//
+// fcnpolygauss
+//
+// calculates the chi2 for the fit of the (polynomial+Gauss) function 
+// 'PolyGauss' to the histogram 'fhist'
+//
+// it is called by CallMinuit() (which is called in FitGaussPoly()) 
+//
+// bins of fhist with huge errors are ignored in the calculation of the chi2
+// (the huge errors were set in 'FitGaussPoly()')
+//
+
+static void fcnpolygauss(Int_t &npar, Double_t *gin, Double_t &f, 
+                         Double_t *par, Int_t iflag)
+{
+    TH1 *fhist = (TH1*)gMinuit->GetObjectFit();
+    TF1 *fpolygauss = fhist->GetFunction("PolyGauss");    
+
+
+    //-------------------------------------------
+
+    Double_t chi2 = 0.0;
+
+    Int_t nbins = fhist->GetNbinsX();
+    Int_t mbins = 0;
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      Double_t content = fhist->GetBinContent(i);
+      Double_t error   = fhist->GetBinError(i);
+      Double_t center  = fhist->GetBinCenter(i);
+
+      //-----------------------------
+      // ignore unwanted points
+      if (error > 1.e19)
+        continue;
+
+      if (content <= 0.0)
+      {
+        gLog << "fcnpolygauss : bin with zero content; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      if (error <= 0.0)
+      {
+        gLog << "fcnpolygauss : bin with zero error; i, content, error = "
+             << i << ",  " << content << ",  " << error << endl;
+        continue;
+      }        
+
+      //-----------------------------
+      mbins++;
+
+      Double_t fu;
+      fu = fpolygauss->EvalPar(&center, par);
+
+      // the fitted function must not be negative
+      if (fu <= 0.0)
+      {
+        chi2 = 1.e10;
+        break;
+      }
+
+      Double_t temp = (content - fu) / error;
+      chi2 += temp*temp;
+    }
+
+    //-------------------------------------------
+
+    f = chi2;
+
+    //-------------------------------------------
+    // final calculations
+    //if (iflag == 3)
+    //{
+    //}    
+
+    //-------------------------------------------------------------
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Constructor
+//
+MHFindSignificanceONOFF::MHFindSignificanceONOFF(const char *name, const char *title)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+//    fSigVsAlpha = NULL;
+
+    fPoly   = NULL;
+    fPolyOFF   = NULL;
+    fPolyOFFNormalized   = NULL;
+    fGPoly  = NULL;
+    fGBackg = NULL;
+
+    fHist     = NULL;
+    fHistOrig = NULL;
+
+    fHistOFF     = NULL;
+    fHistOrigOFF = NULL;
+    fHistOFFNormalized = NULL;
+
+    // allow rebinning of the alpha plot
+//    fRebin = kTRUE;
+
+    fRebin = kFALSE;
+
+    // allow reducing the degree of the polynomial
+    fReduceDegree = kTRUE;
+
+    // Low and Upper limits for the OFF alpha distribution fit
+    // are set to 0 and 90 degrees respectively
+
+    fAlphaminOFF = 0.0;
+    fAlphamaxOFF = 90.0;
+    
+    // use quantities computed from the fits
+    // The variable allows the user to NOT use these quantities when there is not 
+    // enough statistics and fit not always is possible.
+    // Default value is kTRUE.
+    fUseFittedQuantities = kTRUE;
+
+    // Bool variable used to decide wether to print or not the results 
+    // of the fit, significance, Nex... onto the final alpha plot. 
+    // for the time being, this variable is set in the constructor. 
+    // At some point, I might make it such it can be set externally...
+
+    fPrintResultsOntoAlphaPlot = kTRUE;
+    //fPrintResultsOntoAlphaPlot = kFALSE;
+
+
+
+    fCanvas = NULL;
+    
+    fSavePlots = kFALSE; // By default plots are not saved in Postscriptfiles
+
+    fPsFilename = NULL;
+
+   
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. 
+//
+// =====>  it is not clear why one obtains sometimes a segmentation violation
+//         when the destructor is active     <=======================
+//
+// therefore the 'return'statement
+//
+
+MHFindSignificanceONOFF::~MHFindSignificanceONOFF()
+{
+
+
+    
+     return;
+    
+    *fLog << "destructor of MHFindSignificanceONOFF is called" << endl;
+    
+
+    fPsFilename = NULL;
+  
+    cout << "PS set to null... " << endl;
+
+    delete fHist;
+    delete fHistOFF;
+
+    delete fHistOFFNormalized;
+
+    cout << "Histos removed..." << endl;
+
+    delete fPoly;
+    delete fPolyOFF;
+    delete fPolyOFFNormalized;
+    delete fGPoly;
+    delete fGBackg;
+  
+    cout << "Functions are also removed..." << endl;
+    
+    // delete fCanvas; if I removed fCanvas pointed memory address the 
+    // program crashes  ???
+
+    *fLog << "destructor of MHFindSignificanceONOFF finished successfully" << endl;
+
+   
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set flag fRebin 
+//
+//  if flag is kTRUE rebinning of the alpha plot is allowed
+//
+//
+void MHFindSignificanceONOFF::SetRebin(Bool_t b)
+{
+  fRebin = b;
+
+  *fLog << "MHFindSignificanceONOFF::SetRebin; flag fRebin set to " 
+        << (b? "kTRUE" : "kFALSE") << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set flag fReduceDegree 
+//
+//  if flag is kTRUE reducing of the degree of the polynomial is allowed
+//
+//
+void MHFindSignificanceONOFF::SetReduceDegree(Bool_t b)
+{
+  fReduceDegree = b;
+
+  *fLog << "MHFindSignificanceONOFF::SetReduceDegree; flag fReduceDegree set to " 
+        << (b? "kTRUE" : "kFALSE") << endl;
+}
+
+// Function that returns one of the 3 LiMa sigmas. 
+// The returned value is the one used in the optimization 
+// and final alpha plots. 
+
+// For the time being, if fUseFittedQuantities = kTRUE (default)
+// fSigLiMa is used, otherwise, fSigLiMa2 is used. 
+
+Double_t MHFindSignificanceONOFF::GetSignificance()
+{
+
+    if(fUseFittedQuantities)
+    {   
+	return fSigLiMa;
+    }
+
+    return fSigLiMa2;
+
+
+    
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  FindSigmaONOFF
+//
+//  calls FitPolynomialOFF  it gets bkg events in "signal" region 
+//                          from histogram histOFF which is the alpha 
+//                          distribution of OFF data NON normalized. 
+//                          Normalization factor is also one of the 
+//                          arguments.
+//  calls DetExcess         to determine the number of excess events
+//                          using the previously computed bkg events
+
+//  calls SigmaLiMa         to determine the significance of the gamma signal
+//                          in the range |alpha| < alphasig
+//  calls FitGaussPoly      to fit a (polynomial+Gauss) function in the
+//                          whole |alpha| region of ON - OFF diagram 
+//
+//
+
+Bool_t MHFindSignificanceONOFF::FindSigmaONOFF(TH1 *fhistON,  
+					       TH1 *fhistOFF,
+					       Double_t NormFactor,
+					       Double_t alphamin,
+					       Double_t alphamax,
+					       Int_t degreeON, 
+					       Int_t degreeOFF,
+					       Double_t alphasig, 
+					       Bool_t drawpoly,   
+					       Bool_t fitgauss, 
+					       Bool_t print, 
+					       Bool_t saveplots, 
+					       //TPostScript* PsFile
+					       const TString psfilename)
+{
+    
+    //*fLog << "MHFindSignificanceONOFF::FindSigma;" << endl;
+ 
+    // Pointer to object TPostScript where plots will be stored 
+    // is copied into member varialbe 
+    // NOT WORKING !!!
+    // fPsFilename = PsFile;
+
+    // Temporally (while TPostSctipt option is not working) psfiles 
+    // will be produced by the standard way (Canvas.SaveAs())
+
+    fPsFilenameString = psfilename;
+
+
+
+    // "3 Li and Ma significances" are initialized to 0.0
+
+    fSigLiMa = 0.0;
+    fSigLiMa2 = 0.0;
+    fSigLiMa3 = 0.0;
+   
+    
+    // fNormFactor is set 
+    
+    fNormFactor = NormFactor;
+
+    // Report when this histograms given in the 
+    // arguments are empty
+    
+    Double_t tmpdouble= -1.0;
+    
+    tmpdouble = double(fhistON->GetEntries());
+    if (tmpdouble < 0.5)
+    {
+	cout << "MHFindSignificanceONOFF::FindSigmaONOFF; ERROR " << endl
+	     << "fhistON has ZERO entries" << endl;
+   } 
+
+    tmpdouble = double(fhistOFF->GetEntries());
+    if (tmpdouble < 0.5)
+    {
+	cout << "MHFindSignificanceONOFF::FindSigmaONOFF; ERROR " << endl
+	     << "fhistOFF has ZERO entries" << endl;
+    } 
+
+
+
+   
+    // Variables set for alpha from ON events
+    fHistOrig = fhistON;
+    fHist = (TH1*)fHistOrig->Clone();
+    fHist->SetName(fhistON->GetName());
+    fDegree   = degreeON;
+
+
+     // Variables set for alpha from OFF events
+
+    fHistOrigOFF = fhistOFF;    
+    fHistOFF = (TH1*)fHistOrigOFF->Clone();
+    fHistOFF->SetName(fhistOFF->GetName());
+    fDegreeOFF   = degreeOFF;
+
+    if ( !fHist )
+    {
+	*fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; Clone of histogram could not be generated" 
+	      << endl;
+	return kFALSE;
+    }
+
+
+    
+    if ( !fHistOFF )
+    {
+	*fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; Clone of OFF histogram could not be generated" 
+	      << endl;
+	return kFALSE;
+    }
+
+
+
+  
+  fHist->Sumw2();
+  fHist->SetXTitle("|alpha|  [\\circ]");
+  fHist->SetYTitle("Counts");
+  fHist->UseCurrentStyle();
+  
+
+  fHistOFF->Sumw2(); // if error has been set (via function SetBinError(j))
+   // the errors set remain, i.e. are not overwritten with the sum of the square of weights.
+  // Which means that this function will not have any effect.
+
+  fHistOFF->SetXTitle("|alpha|  [\\circ]");
+  fHistOFF->SetYTitle("Counts");
+  fHistOFF->UseCurrentStyle();
+  
+
+  
+
+
+/////////////////////////////////////
+
+  fAlphamin = alphamin;
+  fAlphamax = alphamax;
+  fAlphammm = (alphamin+alphamax)/2.0;
+  fAlphasig = alphasig;
+
+
+
+
+  // UYpper limits for fit to OFF data set are taken also from alphamax
+  // fAlphaminOFF is set in constructor. Inn principle, it WILL ALWAYS BE ZERO.
+
+  fAlphamaxOFF = alphamax;
+
+  
+  fDraw     = drawpoly;
+  fSavePlots = saveplots;
+  fFitGauss = fitgauss;
+  
+
+  //--------------------------------------------
+  // fit a polynomial in the backgr  region
+  
+  //*fLog << "MHFindSignificanceONOFF::FindSigma;  calling FitPolynomial()" << endl;
+  if ( !FitPolynomialOFF())
+  {
+      *fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; PolynomialOFF failed"
+	    << endl;  
+      return kFALSE;
+  }
+      
+      
+  //--------------------------------------------
+  // calculate the number of excess events in the signal region
+  
+  //*fLog << "MHFindSignificanceONOFF::FindSigma;  calling DetExcess()" << endl;
+  if ( !DetExcessONOFF())
+  {
+      *fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; DetExcessONOFF failed"
+	    << endl;  
+      return kFALSE;
+  }
+
+  
+
+
+
+  //--------------------------------------------
+  // calculate the significance of the excess
+
+  //*fLog << "MHFindSignificanceONOFF::FindSigma;  calling SigmaLiMa()" << endl;
+
+  // For testing purposes "3 Li&Ma significances" will be computed
+  // At some point, only one will remain
+
+
+  Double_t siglima = 0.0;
+  
+
+  // Significance computed using effective number of OFF events  in signal 
+  // region (fNoff) and gamma factor (fGama).
+  // This is Wolfgang approach to the calulation of significance 
+  // using Li&Ma formula and estimated OFF events from polynomial fit.
+  
+  if(fUseFittedQuantities) 
+  {
+      if ( !SigmaLiMa(fNon, fNoff, fGamma, &siglima) )
+      {
+	  *fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; SigmaLiMa failed"
+		<< endl;  
+	  return kFALSE;
+      }
+
+      fSigLiMa = siglima;
+  }
+  else
+  {
+      fSigLiMa = 0.0;
+  }
+
+
+
+  // Significance computed using counted number of OFF events in signal 
+  // region (fNoffSig) and normalization factor (fNormFactor).
+  // This is the strictly speaking the significance in Li&Ma paper...
+  
+  
+  if ( !SigmaLiMa(fNon, fNoffSig, fNormFactor, &siglima) )
+  {
+      *fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; SigmaLiMa2 failed"
+	    << endl;  
+      return kFALSE;
+  }
+  fSigLiMa2 = siglima;
+  
+  
+  // Significance computed using counted number of OFF events in signal 
+  // region (fNoffSig) and normalization factor (fNormFactor). 
+  // significance of gamma signal according to Li & Ma using  
+  // formula (5)
+
+
+
+  if ( !SigmaLiMaForm5(fNon, fNoffSig, fNormFactor, &siglima) )
+      {
+	  *fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; SigmaLiMa failed"
+		<< endl;  
+	  return kFALSE;
+      }
+
+  fSigLiMa3 = siglima;
+  
+    
+  
+ 
+ 
+//--------------------------------------------
+// calculate the error of the number of excess events
+// using fitted quantities and counted quantities
+ 
+ 
+// from fit to OFF histogram
+
+ if (fSigLiMa > 0.0) 
+ {fdNexONOFFFitted = fNexONOFFFitted / fSigLiMa;}
+ else
+ {fdNexONOFFFitted = 0.0;}
+
+
+ // from counted OFF events
+ if (fSigLiMa2 > 0.0) 
+ {
+     fdNexONOFF = fNexONOFF / fSigLiMa2;
+ }
+ else
+ {
+     fdNexONOFF = 0.0;
+ }
+
+  if (fDraw || fFitGauss)
+  {
+      
+      // ------------------------------------------------
+      // Polynomial fit to bkg region from ON data is performed, 
+      // Because some of the quantities will be used as 
+      // initial values in the PolyGAuss fit.
+      
+      // Besides, this function will modify the binning of fHist 
+      // so that the number of events in each bin is big enough
+      
+      // This might change in future...
+      
+      if ( !FitPolynomial())
+      {
+	  *fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; Polynomial fit failed"
+		<< endl;  
+	  return kFALSE;
+      }
+  }
+
+
+  if (fDraw)
+  {
+
+      // Compute fHistOFFNormalized
+
+      if (!ComputeHistOFFNormalized())
+      {
+	  *fLog << "MHFindSignificanceONOFF::ComputeHistOFFNormalized; Normalization of fHistOFF was not possible"
+		<< endl;  
+	  return kFALSE;
+	  
+      }
+  }
+
+
+ 
+
+
+  //--------------------------------------------
+
+  //*fLog << "MHFindSignificanceONOFF::FindSigma;  calling PrintPoly()" << endl;
+  if (print)
+    PrintPolyOFF();
+
+
+
+  
+  
+
+
+
+
+  //--------------------------------------------
+  // fit a (polynomial + Gauss) function to the ON-OFF alpha distribution 
+
+  if (fFitGauss)
+  {
+
+    //--------------------------------------------------
+    // delete objects from this fit
+    // in order to have independent starting conditions for the next fit
+
+      delete gMinuit;
+      gMinuit = NULL;
+    //--------------------------------------------------
+
+       //*fLog << "MHFindSignificanceONOFF::FindSigma;  calling FitGaussPoly()" 
+      //      << endl;
+    if ( !FitGaussPoly() )
+    {
+      *fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; FitGaussPoly failed"  
+      	    << endl;  
+      return kFALSE;
+    }
+
+    if (print)
+    {
+      //*fLog << "MHFindSignificanceONOFF::FindSigma;  calling PrintPolyGauss()" 
+      //      << endl;
+      PrintPolyGauss();
+    }
+  }
+
+  //--------------------------------------------------
+  // draw the histogram if requested
+
+  if (fDraw)
+  {
+       // TEMPORALLY I will plot fHistOFF and fHistOFFNormalized (with the fits)
+
+      
+      if (!DrawHistOFF())
+      {
+	  *fLog << "MHFindSignificanceONOFF::DrawHistOFF; Drawing  of fHistOFF was not possible"
+		<< endl;  
+	  // return kFALSE;
+	  
+      }
+      
+     
+      if (!DrawHistOFFNormalized())
+      {
+	  *fLog << "MHFindSignificanceONOFF::DrawHistOFFNormalized; Drawing  of fHistOFFNormalized was not possible"
+		<< endl;  
+	  // return kFALSE;
+	  
+      }
+
+
+
+
+    //*fLog << "MHFindSignificanceONOFF::FindSigma;  calling DrawFit()" << endl;
+      if ( !DrawFit() )
+      {
+	  *fLog << "MHFindSignificanceONOFF::FindSigmaONOFF; DrawFit failed"  
+		<< endl;  
+	  return kFALSE;
+      }
+  }
+  
+
+  //--------------------------------------------------
+  // delete objects from this fit
+  // in order to have independent starting conditions for the next fit
+
+  delete gMinuit;
+  gMinuit = NULL;
+  //--------------------------------------------------
+  
+  return kTRUE;
+
+}
+
+ 
+//// ********************* end sigmaonoff ************************
+
+
+
+
+
+
+
+// UNDER CONSTRUCTION
+
+Bool_t MHFindSignificanceONOFF::SigmaVsAlphaONOFF(TH1 *fhistON, TH1 *fhistOFF,  
+					   Double_t alphamin, Double_t alphamax, 
+					   Int_t degree, Bool_t print)
+{
+    *fLog << "   MHFindSignificanceONOFF::SigmaVsAlphaONOFF still under construction !!!" << endl;
+
+    return kFALSE;
+
+}
+
+
+
+
+// --------------------------------------------------------------------------
+//
+//  FitPolynomialOFF
+//  - create a clone 'fHistOFF' of the |alpha| distribution 'fHistOrigOFF'
+//  - fit a polynomial of degree 'fDegreeOFF' to the alpha distribution 
+//    'fHistOFF' in the region alphaminOFF < |alpha| < alphamaxOFF
+
+
+
+Bool_t MHFindSignificanceONOFF::FitPolynomialOFF()
+
+{
+  //--------------------------------------------------
+  // check the histogram :
+  //       - calculate initial values of the parameters
+  //       - check for bins with zero entries
+  //       - set minimum errors
+  //       - save the original errors
+  //       - set errors huge outside the fit range
+  //         (in 'fcnpolyOFF' points with huge errors will be ignored)
+
+
+  Double_t dummy = 1.e20;
+
+  Double_t mean;
+  Double_t rms;
+  Double_t nclose;
+  Double_t nfar;
+  Double_t a2init = 0.0;
+  TArrayD  saveError;
+
+  Int_t nbins;
+  Int_t nrebin = 1;
+
+
+ //----------------   start while loop for rebinning   -----------------
+  while(1)
+  {
+
+  fNzeroOFF   = 0;
+  fMbinsOFF   = 0;
+  fMlowOFF   = 0;
+  fNoffTot = 0.0;
+
+  // same variables (as in fitpoly to ON data) are used
+  // here for naming the actual values for low/up limit for fit
+  fAlphami =  10000.0;
+  fAlphamm =  10000.0;
+  fAlphama = -10000.0;
+
+  mean   = 0.0;
+  rms    = 0.0;
+  nclose = 0.0;
+  nfar   = 0.0;
+
+  nbins = fHistOFF->GetNbinsX();
+  saveError.Set(nbins);
+
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    saveError[i-1] = fHistOFF->GetBinError(i);
+
+    // bin should be completely contained in the fit range
+    // (fAlphaminOFF, fAlphamaxOFF)
+    Double_t  xlo = fHistOFF->GetBinLowEdge(i);
+    Double_t  xup = fHistOFF->GetBinLowEdge(i+1);
+
+    if ( xlo >= fAlphaminOFF-fEps  &&  xlo <= fAlphamaxOFF+fEps  &&
+	 xup >= fAlphaminOFF-fEps  &&  xup <= fAlphamaxOFF+fEps     )
+    {
+      fMbinsOFF++;
+
+      if ( xlo < fAlphami )
+        fAlphami = xlo;
+
+      if ( xup > fAlphama )
+        fAlphama = xup;
+
+      Double_t content = fHistOFF->GetBinContent(i);
+      // fNoffTot += content;
+
+      mean += content;
+      rms  += content*content;
+
+// count events in low-alpha and high-alpha region
+      if ( xlo >= fAlphammm-fEps  &&  xup >= fAlphammm-fEps)
+      {
+        nfar   += content;
+        if ( xlo < fAlphamm )
+          fAlphamm = xlo;
+        if ( xup < fAlphamm )
+          fAlphamm = xup; 
+      }
+      else
+      {
+        nclose += content;
+        if ( xlo > fAlphamm )
+          fAlphamm = xlo;
+        if ( xup > fAlphamm )
+          fAlphamm = xup; 
+      }
+
+      // count bins with zero entry
+      if (content < 0.0001)
+        fNzeroOFF++;
+     
+      // set minimum error
+      // modified by K. Mase
+      if (content < 0.0)
+      {
+        fMlowOFF += 1;
+        fHistOFF->SetBinError(i, 3.0);
+      }
+
+      //*fLog << "Take : i, content, error = " << i << ",  " 
+      //      << fHist->GetBinContent(i) << ",  "
+      //      << fHist->GetBinError(i)   << endl;
+
+      continue;
+    }    
+    // bin is not completely contained in the fit range : set error huge
+
+    fHistOFF->SetBinError(i, dummy);
+
+    //*fLog << "Omit : i, content, error = " << i << ",  " 
+    //      << fHist->GetBinContent(i) << ",  " << fHist->GetBinError(i) 
+    //      << endl;
+
+  }
+
+  // mean of entries/bin in the fit range
+  if (fMbinsOFF > 0)
+  {
+    mean /= ((Double_t) fMbinsOFF);
+    rms  /= ((Double_t) fMbinsOFF);
+    rms = sqrt( rms - mean*mean );
+  }
+
+  
+
+  // if there are no events in the background region
+  //    there is no reason for rebinning
+  //    and this is the condition for assuming a constant background (= 0)
+  if (mean <= 0.0)
+    break;
+
+  Double_t helpmi = fAlphami*fAlphami*fAlphami;
+  Double_t helpmm = fAlphamm*fAlphamm*fAlphamm;
+  Double_t helpma = fAlphama*fAlphama*fAlphama;
+  Double_t help   =   (helpma-helpmm) * (fAlphamm-fAlphami)    
+	            - (helpmm-helpmi) * (fAlphama-fAlphamm);
+  if (help != 0.0)
+    a2init =  ( (fAlphamm-fAlphami)*nfar - (fAlphama-fAlphamm)*nclose )
+                * 1.5 * fHistOFF->GetBinWidth(1) / help;
+  else
+    a2init = 0.0;
+
+
+  //--------------------------------------------
+  // rebin the histogram
+  //   - if a bin has no entries 
+  //   - or if there are too many bins with too few entries
+  //   - or if the new bin width would exceed half the size of the 
+  //     signal region
+
+  if ( !fRebin  ||
+       ( fNzeroOFF <= 0 && (Double_t)fMlowOFF<0.05*(Double_t)fMbinsOFF )  || 
+       (Double_t)(nrebin+1)/(Double_t)nrebin * fHistOFF->GetBinWidth(1) 
+                                                           > fAlphasig/2.0 )
+  {
+    //*fLog << "before break" << endl;
+    break;
+  }
+
+  nrebin += 1;
+  TString histname = fHistOFF->GetName();
+  delete fHistOFF;
+  fHistOFF = NULL;
+
+  *fLog << "MHFindSignificanceONOFF::FitPolynomialOFF; rebin the |alpha|OFF plot, grouping "
+        << nrebin << " bins together" << endl;
+
+  // TH1::Rebin doesn't work properly
+  //fHist = fHistOrig->Rebin(nrebin, "Rebinned");
+  // use private routine RebinHistogram()
+  fHistOFF = new TH1F;
+  fHistOFF->Sumw2();
+  fHistOFF->SetNameTitle(histname, histname);
+  fHistOFF->UseCurrentStyle();
+
+  // do rebinning such that x0 remains a lower bin edge
+  Double_t x0 = 0.0;
+  if ( !RebinHistogramOFF(x0, nrebin) )
+  {
+    *fLog << "MHFindSignificanceONOFF::FitPolynomialOFF; RebinHistgramOFF() failed" 
+          << endl;
+    return kFALSE;
+  }
+
+  fHistOFF->SetXTitle("|alpha|  [\\circ]");
+  fHistOFF->SetYTitle("Counts");
+  
+  }
+  //----------------   end of while loop for rebinning   -----------------
+
+
+  // if there are still too many bins with too few entries don't fit
+  // and assume a constant background
+
+  fConstantBackg = kFALSE;
+  if ( fNzeroOFF > 0  ||  (Double_t)fMlowOFF>0.05*(Double_t)fMbinsOFF ) 
+  {
+    *fLog << "MHFindSignificanceONOFF::FitPolynomialOFF; polynomial fit not possible,  fNzeroOFF, fMlowOFF, fMbinsOFF = "
+          << fNzeroOFF << ",  " << fMlowOFF << ",  " << fMbinsOFF << endl;
+    *fLog << "                    assume a constant background" << endl;
+
+    fConstantBackg = kTRUE;
+    fDegreeOFF        = 0;
+
+    TString funcname = "PolyOFF";
+    Double_t xmin =   0.0;
+    Double_t xmax =  90.0;
+
+    TString formula = "[0]";
+
+    fPolyOFF = new TF1(funcname, formula, xmin, xmax);
+    TList *funclist = fHistOFF->GetListOfFunctions();
+    funclist->Add(fPolyOFF);
+
+    //--------------------
+    Int_t nparfree = 1;
+    fChisqOFF         = 0.0; 
+    fNdfOFF           = fMbinsOFF - nparfree;
+    fProbOFF          = 0.0;
+    fIstatOFF         = 0;
+
+    fValuesOFF.Set(1);
+    fErrorsOFF.Set(1);
+
+    Double_t val, err;
+    val = mean;
+    err = rms;
+    
+
+    fPolyOFF->SetParameter(0, val);
+    fPolyOFF->SetParError (0, err);
+
+    fValuesOFF[0] = val;
+    fErrorsOFF[0] = err; 
+
+    fEmaOFF[0][0]  = err*err;
+    fCorrOFF[0][0] = 1.0;
+    //--------------------
+    //--------------------------------------------------
+    // reset the errors of the points in the histogram
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      fHistOFF->SetBinError(i, saveError[i-1]);
+    }
+
+
+    return kTRUE;
+  }
+
+
+  //===========   start loop for reducing the degree   ==================
+  //              of the polynomial
+  while (1)
+  {
+      //--------------------------------------------------
+      // prepare fit of a polynomial :   (a0 + a1*x + a2*x**2 + a3*x**3 + ...)
+
+
+      TString funcname = "PolyOFF";
+      Double_t xmin =   0.0;
+      Double_t xmax =  90.0;
+
+      TString formula = "[0]";
+      TString bra1     = "+[";
+      TString bra2     =    "]";
+      TString xpower   = "*x";
+      TString newpower = "*x";
+      for (Int_t i=1; i<=fDegreeOFF; i++)
+      {
+          formula += bra1;
+          formula += i;
+          formula += bra2;
+          formula += xpower;
+
+          xpower += newpower;
+      }
+
+      //*fLog << "FitPolynomial : formula = " << formula << endl;
+
+      fPolyOFF = new TF1(funcname, formula, xmin, xmax);
+      TList *funclist = fHistOFF->GetListOfFunctions();
+      funclist->Add(fPolyOFF);
+
+      //------------------------
+      // attention : the dimensions must agree with those in CallMinuit()
+      const UInt_t npar = fDegreeOFF+1;
+
+      TString parname[npar];
+      TArrayD vinit(npar);
+      TArrayD  step(npar);
+      TArrayD limlo(npar);
+      TArrayD limup(npar);
+      TArrayI   fix(npar);
+
+      vinit[0] =   mean;
+      vinit[2] = a2init;
+
+      for (UInt_t j=0; j<npar; j++)
+      {
+          parname[j]  = "p";
+          parname[j] += j+1;
+
+          step[j] = vinit[j] != 0.0 ? TMath::Abs(vinit[j]) / 10.0 : 0.000001;
+      }
+
+      // limit the first coefficient of the polynomial to positive values
+      // because the background must not be negative
+      limup[0] = fHistOFF->GetEntries();
+
+      // use the subsequernt loop if you want to apply the
+      // constraint : uneven derivatives (at alpha=0) = zero
+      for (UInt_t j=1; j<npar; j+=2)
+      {
+          vinit[j] = 0;
+          step[j]  = 0;
+          fix[j]   = 1;
+      }
+
+      //*fLog << "FitPolynomial : before CallMinuit()" << endl;
+
+      MMinuitInterface inter;
+      const Bool_t rc = inter.CallMinuit(fcnpolyOFF, parname, vinit, step,
+                                         limlo, limup, fix, fHistOFF, "Migrad",
+                                         kFALSE);
+
+      //*fLog << "FitPolynomial : after CallMinuit()" << endl;
+
+      if (rc != 0)
+      {
+          //  *fLog << "MHFindSignificanceONOFF::FitPolynomial; polynomial fit failed"
+          //        << endl;
+          //  return kFALSE;
+      }
+
+      //-------------------
+      // get status of minimization
+      Double_t fmin   = 0;
+      Double_t fedm   = 0;
+      Double_t errdef = 0;
+      Int_t    npari  = 0;
+      Int_t    nparx  = 0;
+
+      if (gMinuit)
+          gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, fIstatOFF);
+
+      *fLog << "MHFindSignificanceONOFF::FitPolynomialOFF; fmin, fedm, errdef, npari, nparx, fIstat = "
+            << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+            << ",  " << nparx << ",  " << fIstatOFF << endl;
+
+
+      //-------------------
+      // store the results
+
+      Int_t nparfree = gMinuit!=NULL ? gMinuit->GetNumFreePars() : 0;
+      fChisqOFF         = fmin;
+      fNdfOFF          = fMbinsOFF - nparfree;
+      fProbOFF          = TMath::Prob(fChisqOFF, fNdfOFF);
+
+
+      // get fitted parameter values and errors
+      fValuesOFF.Set(npar);
+      fErrorsOFF.Set(npar);
+
+      for (Int_t j=0; j<=fDegreeOFF; j++)
+      {
+          Double_t val, err;
+          if (gMinuit)
+              gMinuit->GetParameter(j, val, err);
+
+          fPolyOFF->SetParameter(j, val);
+          fPolyOFF->SetParError(j, err);
+
+          fValuesOFF[j] = val;
+          fErrorsOFF[j] = err;
+      }
+
+      // if the highest coefficient (j0) of the polynomial
+      // is consistent with zero reduce the degree of the polynomial
+
+      Int_t j0 = 0;
+      for (Int_t j=fDegreeOFF; j>1; j--)
+      {
+          // ignore fixed parameters
+          if (fErrorsOFF[j] == 0)
+              continue;
+
+          // this is the highest coefficient
+          j0 = j;
+          break;
+      }
+
+      if (!fReduceDegree || j0==0 || TMath::Abs(fValuesOFF[j0]) > fErrorsOFF[j0])
+          break;
+
+      // reduce the degree of the polynomial
+      *fLog << "MHFindSignificanceONOFF::FitPolynomialOFF; reduce the degree of the polynomial from "
+          << fDegreeOFF << " to " << (j0-2) << endl;
+      fDegreeOFF = j0 - 2;
+
+      funclist->Remove(fPolyOFF);
+      //if (fPoly)
+      delete fPolyOFF;
+      fPolyOFF = NULL;
+
+      // delete the Minuit object in order to have independent starting
+      // conditions for the next minimization
+      //if (gMinuit)
+      delete gMinuit;
+      gMinuit = NULL;
+  }
+  //===========   end of loop for reducing the degree   ==================
+  //              of the polynomial
+
+
+  //--------------------------------------------------
+  // get the error matrix of the fitted parameters
+
+  if (fIstatOFF >= 1)
+  {
+      // error matrix was calculated
+      if (gMinuit)
+          gMinuit->mnemat(&fEmatOFF[0][0], fNdimOFF);
+
+      // copy covariance matrix into a matrix which includes also the fixed
+      // parameters
+      TString  name;
+      Double_t bnd1, bnd2, val, err;
+      Int_t    jvarbl;
+      Int_t    kvarbl;
+      for (Int_t j=0; j<=fDegreeOFF; j++)
+      {
+          if (gMinuit)
+              gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+          for (Int_t k=0; k<=fDegreeOFF; k++)
+          {
+              if (gMinuit)
+                  gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+              fEmaOFF[j][k] = jvarbl==0 || kvarbl==0 ? 0 : fEmatOFF[jvarbl-1][kvarbl-1];
+          }
+      }
+  }
+  else
+  {
+      // error matrix was not calculated, construct it
+      *fLog << "MHFindSignificanceONOFF::FitPolynomialOFF; error matrix not defined"
+          << endl;
+      for (Int_t j=0; j<=fDegreeOFF; j++)
+      {
+          for (Int_t k=0; k<=fDegreeOFF; k++)
+              fEmaOFF[j][k] = 0;
+
+          fEmaOFF[j][j] = fErrorsOFF[j]*fErrorsOFF[j];
+      }
+  }
+
+
+
+  
+  //--------------------------------------------------
+  // calculate correlation matrix
+  for (Int_t j=0; j<=fDegreeOFF; j++)
+  {
+      for (Int_t k=0; k<=fDegreeOFF; k++)
+      {
+          const Double_t sq = fEmaOFF[j][j]*fEmaOFF[k][k];
+          fCorrOFF[j][k] = 
+	      sq == 0 ? 0 : (fEmaOFF[j][k] / TMath::Sqrt(fEmaOFF[j][j]*fEmaOFF[k][k]));
+      }
+  }
+  
+  //--------------------------------------------------
+  // reset the errors of the points in the histogram
+  for (Int_t i=1; i<=nbins; i++)
+  {
+      fHistOFF->SetBinError(i, saveError[i-1]);
+  }
+  
+  return kTRUE;
+
+
+}
+
+
+
+
+
+
+
+
+// --------------------------------------------------------------------------
+//
+//  FitPolynomial
+//
+//  - create a clone 'fHist' of the |alpha| distribution 'fHistOrig'
+//  - fit a polynomial of degree 'fDegree' to the alpha distribution 
+//    'fHist' in the region alphamin < |alpha| < alphamax
+//
+//  in pathological cases the histogram is rebinned before fitting
+//     (this is done only if fRebin is kTRUE)
+//
+//  if the highest coefficient of the polynomial is compatible with zero
+//     the fit is repeated with a polynomial of lower degree
+//     (this is done only if fReduceDegree is kTRUE)
+//
+//
+
+Bool_t MHFindSignificanceONOFF::FitPolynomial()
+{
+  //--------------------------------------------------
+  // check the histogram :
+  //       - calculate initial values of the parameters
+  //       - check for bins with zero entries
+  //       - set minimum errors
+  //       - save the original errors
+  //       - set errors huge outside the fit range
+  //         (in 'fcnpoly' points with huge errors will be ignored)
+
+
+  Double_t dummy = 1.e20;
+
+  Double_t mean;
+  Double_t rms;
+  Double_t nclose;
+  Double_t nfar;
+  Double_t a2init = 0.0;
+  TArrayD  saveError;
+
+  Int_t nbins;
+  Int_t nrebin = 1;
+
+  //----------------   start while loop for rebinning   -----------------
+  while(1)
+  {
+
+  fNzero   = 0;
+  fMbins   = 0;
+  fMlow    = 0;
+  fNbgtot  = 0.0;
+
+  fAlphami =  10000.0;
+  fAlphamm =  10000.0;
+  fAlphama = -10000.0;
+
+  mean   = 0.0;
+  rms    = 0.0;
+  nclose = 0.0;
+  nfar   = 0.0;
+
+  nbins = fHist->GetNbinsX();
+  saveError.Set(nbins);
+
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    saveError[i-1] = fHist->GetBinError(i);
+
+    // bin should be completely contained in the fit range
+    // (fAlphamin, fAlphamax)
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+
+    if ( xlo >= fAlphamin-fEps  &&  xlo <= fAlphamax+fEps  &&
+	 xup >= fAlphamin-fEps  &&  xup <= fAlphamax+fEps     )
+    {
+      fMbins++;
+
+      if ( xlo < fAlphami )
+        fAlphami = xlo;
+
+      if ( xup > fAlphama )
+        fAlphama = xup;
+
+      Double_t content = fHist->GetBinContent(i);
+      fNbgtot += content;
+
+      mean += content;
+      rms  += content*content;
+
+      // count events in low-alpha and high-alpha region
+      if ( xlo >= fAlphammm-fEps  &&  xup >= fAlphammm-fEps)
+      {
+        nfar   += content;
+        if ( xlo < fAlphamm )
+          fAlphamm = xlo;
+        if ( xup < fAlphamm )
+          fAlphamm = xup; 
+      }
+      else
+      {
+        nclose += content;
+        if ( xlo > fAlphamm )
+          fAlphamm = xlo;
+        if ( xup > fAlphamm )
+          fAlphamm = xup; 
+      }
+
+      // count bins with zero entry
+      /*if (content <= 0.0)
+        fNzero++;*/
+     
+      // set minimum error
+      /*if (content < 9.0)
+      {
+        fMlow += 1;
+        fHist->SetBinError(i, 3.0);
+	}*/
+
+      //*fLog << "Take : i, content, error = " << i << ",  " 
+      //      << fHist->GetBinContent(i) << ",  "
+      //      << fHist->GetBinError(i)   << endl;
+
+      continue;
+    }    
+    // bin is not completely contained in the fit range : set error huge
+
+    fHist->SetBinError(i, dummy);
+
+    //*fLog << "Omit : i, content, error = " << i << ",  " 
+    //      << fHist->GetBinContent(i) << ",  " << fHist->GetBinError(i) 
+    //      << endl;
+
+  }
+
+  // mean of entries/bin in the fit range
+  if (fMbins > 0)
+  {
+    mean /= ((Double_t) fMbins);
+    rms  /= ((Double_t) fMbins);
+  }
+
+  rms = sqrt( rms - mean*mean );
+
+  // if there are no events in the background region
+  //    there is no reason for rebinning
+  //    and this is the condition for assuming a constant background (= 0)
+  if (mean <= 0.0)
+    break;
+
+  Double_t helpmi = fAlphami*fAlphami*fAlphami;
+  Double_t helpmm = fAlphamm*fAlphamm*fAlphamm;
+  Double_t helpma = fAlphama*fAlphama*fAlphama;
+  Double_t help   =   (helpma-helpmm) * (fAlphamm-fAlphami)    
+	            - (helpmm-helpmi) * (fAlphama-fAlphamm);
+  if (help != 0.0)
+    a2init =  ( (fAlphamm-fAlphami)*nfar - (fAlphama-fAlphamm)*nclose )
+                * 1.5 * fHist->GetBinWidth(1) / help;
+  else
+    a2init = 0.0;
+
+
+  //--------------------------------------------
+  // rebin the histogram
+  //   - if a bin has no entries 
+  //   - or if there are too many bins with too few entries
+  //   - or if the new bin width would exceed half the size of the 
+  //     signal region
+
+  if ( !fRebin  ||
+       ( fNzero <= 0 && (Double_t)fMlow<0.05*(Double_t)fMbins )  || 
+       (Double_t)(nrebin+1)/(Double_t)nrebin * fHist->GetBinWidth(1) 
+                                                           > fAlphasig/2.0 )
+  {
+    //*fLog << "before break" << endl;
+    break;
+  }
+
+  nrebin += 1;
+  TString histname = fHist->GetName();
+  delete fHist;
+  fHist = NULL;
+
+  *fLog << "MHFindSignificanceONOFF::FitPolynomial; rebin the |alpha| plot, grouping "
+        << nrebin << " bins together" << endl;
+
+  // TH1::Rebin doesn't work properly
+  //fHist = fHistOrig->Rebin(nrebin, "Rebinned");
+  // use private routine RebinHistogram()
+  fHist = new TH1F;
+  fHist->Sumw2();
+  fHist->SetNameTitle(histname, histname);
+  fHist->UseCurrentStyle();
+
+  // do rebinning such that x0 remains a lower bin edge
+  Double_t x0 = 0.0;
+  if ( !RebinHistogram(x0, nrebin) )
+  {
+    *fLog << "MHFindSignificanceONOFF::FitPolynomial; RebinHistgram() failed" 
+          << endl;
+    return kFALSE;
+  }
+
+  fHist->SetXTitle("|alpha|  [\\circ]");
+  fHist->SetYTitle("Counts");
+
+  }
+  //----------------   end of while loop for rebinning   -----------------
+
+
+  // if there are still too many bins with too few entries don't fit
+  // and assume a constant background
+
+  fConstantBackg = kFALSE;
+  if ( fNzero > 0  ||  (Double_t)fMlow>0.05*(Double_t)fMbins ) 
+  {
+    *fLog << "MHFindSignificanceONOFF::FitPolynomial; polynomial fit not possible,  fNzero, fMlow, fMbins = "
+          << fNzero << ",  " << fMlow << ",  " << fMbins << endl;
+    *fLog << "                    assume a constant background" << endl;
+
+    fConstantBackg = kTRUE;
+    fDegree        = 0;
+
+    TString funcname = "Poly";
+    Double_t xmin =   0.0;
+    Double_t xmax =  90.0;
+
+    TString formula = "[0]";
+
+    fPoly = new TF1(funcname, formula, xmin, xmax);
+    TList *funclist = fHist->GetListOfFunctions();
+    funclist->Add(fPoly);
+
+    //--------------------
+    Int_t nparfree = 1;
+    fChisq         = 0.0; 
+    fNdf           = fMbins - nparfree;
+    fProb          = 0.0;
+    fIstat         = 0;
+
+    fValues.Set(1);
+    fErrors.Set(1);
+
+    Double_t val, err;
+    val = mean;
+    err = sqrt( mean / (Double_t)fMbins );
+
+    fPoly->SetParameter(0, val);
+    fPoly->SetParError (0, err);
+
+    fValues[0] = val;
+    fErrors[0] = err; 
+
+    fEma[0][0]  = err*err;
+    fCorr[0][0] = 1.0;
+    //--------------------
+
+    //--------------------------------------------------
+    // reset the errors of the points in the histogram
+    for (Int_t i=1; i<=nbins; i++)
+    {
+      fHist->SetBinError(i, saveError[i-1]);
+    }
+
+
+    return kTRUE;
+  }
+
+
+  //===========   start loop for reducing the degree   ==================
+  //              of the polynomial
+  while (1)
+  {
+      //--------------------------------------------------
+      // prepare fit of a polynomial :   (a0 + a1*x + a2*x**2 + a3*x**3 + ...)
+ 
+      TString funcname = "Poly";
+      Double_t xmin =   0.0;
+      Double_t xmax =  90.0;
+
+      TString formula = "[0]";
+      TString bra1     = "+[";
+      TString bra2     =    "]";
+      TString xpower   = "*x";
+      TString newpower = "*x";
+      for (Int_t i=1; i<=fDegree; i++)
+      {
+          formula += bra1;
+          formula += i;
+          formula += bra2;
+          formula += xpower;
+
+          xpower += newpower;
+      }
+
+      //*fLog << "FitPolynomial : formula = " << formula << endl;
+
+      fPoly = new TF1(funcname, formula, xmin, xmax);
+      TList *funclist = fHist->GetListOfFunctions();
+      funclist->Add(fPoly);
+
+      //------------------------
+      // attention : the dimensions must agree with those in CallMinuit()
+      const UInt_t npar = fDegree+1;
+
+      TString parname[npar];
+      TArrayD vinit(npar);
+      TArrayD  step(npar);
+      TArrayD limlo(npar);
+      TArrayD limup(npar);
+      TArrayI   fix(npar);
+
+      vinit[0] =   mean;
+      vinit[2] = a2init;
+
+      for (UInt_t j=0; j<npar; j++)
+      {
+          parname[j]  = "p";
+          parname[j] += j+1;
+
+          step[j] = vinit[j] != 0.0 ? TMath::Abs(vinit[j]) / 10.0 : 0.000001;
+      }
+
+      // limit the first coefficient of the polynomial to positive values
+      // because the background must not be negative
+      limup[0] = fHist->GetEntries();
+
+      // use the subsequernt loop if you want to apply the
+      // constraint : uneven derivatives (at alpha=0) = zero
+      for (UInt_t j=1; j<npar; j+=2)
+      {
+          vinit[j] = 0;
+          step[j]  = 0;
+          fix[j]   = 1;
+      }
+
+      //*fLog << "FitPolynomial : before CallMinuit()" << endl;
+
+      MMinuitInterface inter;
+      const Bool_t rc = inter.CallMinuit(fcnpoly, parname, vinit, step,
+                                         limlo, limup, fix, fHist, "Migrad",
+                                         kFALSE);
+
+      //*fLog << "FitPolynomial : after CallMinuit()" << endl;
+
+      if (rc != 0)
+      {
+          //  *fLog << "MHFindSignificanceONOFF::FitPolynomial; polynomial fit failed"
+          //        << endl;
+          //  return kFALSE;
+      }
+
+
+      //-------------------
+      // get status of minimization
+      Double_t fmin   = 0;
+      Double_t fedm   = 0;
+      Double_t errdef = 0;
+      Int_t    npari  = 0;
+      Int_t    nparx  = 0;
+
+      if (gMinuit)
+          gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, fIstat);
+
+      *fLog << "MHFindSignificanceONOFF::FitPolynomial; fmin, fedm, errdef, npari, nparx, fIstat = "
+            << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+            << ",  " << nparx << ",  " << fIstat << endl;
+
+
+      //-------------------
+      // store the results
+
+      Int_t nparfree = gMinuit!=NULL ? gMinuit->GetNumFreePars() : 0;
+      fChisq         = fmin;
+      fNdf           = fMbins - nparfree;
+      fProb          = TMath::Prob(fChisq, fNdf);
+
+
+      // get fitted parameter values and errors
+      fValues.Set(npar);
+      fErrors.Set(npar);
+
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          Double_t val, err;
+          if (gMinuit)
+              gMinuit->GetParameter(j, val, err);
+
+          fPoly->SetParameter(j, val);
+          fPoly->SetParError(j, err);
+
+          fValues[j] = val;
+          fErrors[j] = err;
+      }
+
+
+      //--------------------------------------------------
+      // if the highest coefficient (j0) of the polynomial
+      // is consistent with zero reduce the degree of the polynomial
+
+      Int_t j0 = 0;
+      for (Int_t j=fDegree; j>1; j--)
+      {
+          // ignore fixed parameters
+          if (fErrors[j] == 0)
+              continue;
+
+          // this is the highest coefficient
+          j0 = j;
+          break;
+      }
+
+      if (!fReduceDegree || j0==0 || TMath::Abs(fValues[j0]) > fErrors[j0])
+          break;
+
+      // reduce the degree of the polynomial
+      *fLog << "MHFindSignificanceONOFF::FitPolynomial; reduce the degree of the polynomial from "
+          << fDegree << " to " << (j0-2) << endl;
+      fDegree = j0 - 2;
+
+      funclist->Remove(fPoly);
+      //if (fPoly)
+      delete fPoly;
+      fPoly = NULL;
+
+      // delete the Minuit object in order to have independent starting
+      // conditions for the next minimization
+      //if (gMinuit)
+      delete gMinuit;
+      gMinuit = NULL;
+  }
+  //===========   end of loop for reducing the degree   ==================
+  //              of the polynomial
+
+
+  //--------------------------------------------------
+  // get the error matrix of the fitted parameters
+
+
+  if (fIstat >= 1)
+  {
+      // error matrix was calculated
+      if (gMinuit)
+          gMinuit->mnemat(&fEmat[0][0], fNdim);
+
+      // copy covariance matrix into a matrix which includes also the fixed
+      // parameters
+      TString  name;
+      Double_t bnd1, bnd2, val, err;
+      Int_t    jvarbl;
+      Int_t    kvarbl;
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          if (gMinuit)
+              gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+          for (Int_t k=0; k<=fDegree; k++)
+          {
+              if (gMinuit)
+                  gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+              fEma[j][k] = jvarbl==0 || kvarbl==0 ? 0 : fEmat[jvarbl-1][kvarbl-1];
+          }
+      }
+  }
+  else
+  {
+      // error matrix was not calculated, construct it
+      *fLog << "MHFindSignificanceONOFF::FitPolynomial; error matrix not defined"
+          << endl;
+      for (Int_t j=0; j<=fDegree; j++)
+      {
+          for (Int_t k=0; k<=fDegree; k++)
+              fEma[j][k] = 0;
+
+          fEma[j][j] = fErrors[j]*fErrors[j];
+      }
+  }
+
+
+  //--------------------------------------------------
+  // calculate correlation matrix
+  for (Int_t j=0; j<=fDegree; j++)
+      for (Int_t k=0; k<=fDegree; k++)
+      {
+          const Double_t sq = fEma[j][j]*fEma[k][k];
+          fCorr[j][k] = sq==0 ? 0 : fEma[j][k] / TMath::Sqrt(fEma[j][j]*fEma[k][k]);
+      }
+
+
+  //--------------------------------------------------
+  // reset the errors of the points in the histogram
+  for (Int_t i=1; i<=nbins; i++)
+      fHist->SetBinError(i, saveError[i-1]);
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// ReBinHistogramOFF
+//
+// rebin the histogram 'fHistOrig' by grouping 'nrebin' bins together 
+// put the result into the histogram 'fHist'
+// the rebinning is made such that 'x0' remains a lower bound of a bin
+//
+
+Bool_t MHFindSignificanceONOFF::RebinHistogramOFF(Double_t x0, Int_t nrebin)
+{
+  //-----------------------------------------
+  // search bin i0 which has x0 as lower edge
+
+  Int_t i0 = -1;
+  Int_t nbold = fHistOrigOFF->GetNbinsX();
+  for (Int_t i=1; i<=nbold; i++)
+  {
+      if (TMath::Abs(fHistOrigOFF->GetBinLowEdge(i) - x0) < 1.e-4 )
+      {
+          i0 = i;
+          break;
+      }
+  }
+
+  if (i0 == -1)
+  {
+    i0 = 1;
+    *fLog << "MHFindsignificanceOFF::RebinOFF; no bin found with " << x0
+          << " as lower edge,  start rebinning with bin 1" << endl;
+  }
+
+  Int_t istart = i0 - nrebin * ( (i0-1)/nrebin );
+
+  //-----------------------------------------
+  // get new bin edges
+
+  const Int_t    nbnew = (nbold-istart+1) / nrebin;
+  const Double_t xmin  = fHistOrigOFF->GetBinLowEdge(istart);
+  const Double_t xmax  = xmin + (Double_t)nbnew * nrebin * fHistOrigOFF->GetBinWidth(1);
+  fHistOFF->SetBins(nbnew, xmin, xmax);
+
+  *fLog << "MHFindSignificanceONOFF::ReBinOFF; x0, i0, nbold, nbnew, xmin, xmax = "
+        << x0 << ",  " << i0 << ",  " << nbold << ",  " << nbnew << ",  "
+        << xmin << ",  " << xmax << endl;
+
+  //-----------------------------------------
+  // get new bin entries
+
+  for (Int_t i=1; i<=nbnew; i++)
+  {
+      Int_t j = nrebin*(i-1) + istart;
+
+      Double_t content = 0;
+      Double_t error2  = 0;
+      for (Int_t k=0; k<nrebin; k++)
+      {
+          content += fHistOrigOFF->GetBinContent(j+k);
+          error2  += fHistOrigOFF->GetBinError(j+k) * fHistOrigOFF->GetBinError(j+k);
+      }
+      fHistOFF->SetBinContent(i, content);
+      fHistOFF->SetBinError  (i, sqrt(error2));
+  }
+  fHistOFF->SetEntries( fHistOrigOFF->GetEntries() );
+
+  return kTRUE;
+}
+
+
+
+
+// --------------------------------------------------------------------------
+
+
+
+//
+// ReBinHistogram
+//
+// rebin the histogram 'fHistOrig' by grouping 'nrebin' bins together 
+// put the result into the histogram 'fHist'
+// the rebinning is made such that 'x0' remains a lower bound of a bin
+//
+
+Bool_t MHFindSignificanceONOFF::RebinHistogram(Double_t x0, Int_t nrebin)
+{
+  //-----------------------------------------
+  // search bin i0 which has x0 as lower edge
+
+  Int_t i0 = -1;
+  Int_t nbold = fHistOrig->GetNbinsX();
+  for (Int_t i=1; i<=nbold; i++)
+  {
+      if (TMath::Abs(fHistOrig->GetBinLowEdge(i) - x0) < 1.e-4 )
+      {
+          i0 = i;
+          break;
+      }
+  }
+
+  if (i0 == -1)
+  {
+    i0 = 1;
+    *fLog << "MHFindsignificance::Rebin; no bin found with " << x0
+          << " as lower edge,  start rebinning with bin 1" << endl;
+  }
+
+  Int_t istart = i0 - nrebin * ( (i0-1)/nrebin );
+
+  //-----------------------------------------
+  // get new bin edges
+
+  const Int_t    nbnew = (nbold-istart+1) / nrebin;
+  const Double_t xmin  = fHistOrig->GetBinLowEdge(istart);
+  const Double_t xmax  = xmin + (Double_t)nbnew * nrebin * fHistOrig->GetBinWidth(1);
+  fHist->SetBins(nbnew, xmin, xmax);
+
+  *fLog << "MHFindSignificanceONOFF::ReBin; x0, i0, nbold, nbnew, xmin, xmax = "
+        << x0 << ",  " << i0 << ",  " << nbold << ",  " << nbnew << ",  "
+        << xmin << ",  " << xmax << endl;
+
+  //-----------------------------------------
+  // get new bin entries
+
+  for (Int_t i=1; i<=nbnew; i++)
+  {
+      Int_t j = nrebin*(i-1) + istart;
+
+      Double_t content = 0;
+      Double_t error2  = 0;
+      for (Int_t k=0; k<nrebin; k++)
+      {
+          content += fHistOrig->GetBinContent(j+k);
+          error2  += fHistOrig->GetBinError(j+k) * fHistOrig->GetBinError(j+k);
+      }
+      fHist->SetBinContent(i, content);
+      fHist->SetBinError  (i, sqrt(error2));
+  }
+  fHist->SetEntries( fHistOrig->GetEntries() );
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  FitGaussPoly
+//
+//  fits a (Gauss + polynomial function) to the alpha distribution 'fhist' 
+//
+//
+Bool_t MHFindSignificanceONOFF::FitGaussPoly()
+{
+  *fLog << "Entry FitGaussPoly" << endl;
+
+  //--------------------------------------------------
+  // check the histogram :
+  //       - calculate initial values of the parameters
+  //       - check for bins with zero entries
+  //       - set minimum errors
+  //       - save the original errors
+  //       - set errors huge outside the fit range
+  //         (in 'fcnpoly' points with huge errors will be ignored)
+
+
+  Double_t dummy = 1.e20;
+
+  fGNzero   = 0;
+  fGMbins   = 0;
+
+  //------------------------------------------
+  // if a constant background has been assumed (due to low statistics)
+  // fit only in the signal region
+  if ( !fConstantBackg )
+  {
+    fAlphalow = 0.0;
+    fAlphahig = fAlphamax;
+  }
+  else
+  {
+    fAlphalow = 0.0;
+    fAlphahig = 2.0*fAlphasig>25.0 ? 25.0 : 2.0*fAlphasig;
+  }
+  //------------------------------------------
+
+
+  fAlphalo =  10000.0;
+  fAlphahi = -10000.0;
+
+
+  Int_t nbins = fHist->GetNbinsX();
+  TArrayD saveError(nbins);
+
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    saveError[i-1] = fHist->GetBinError(i);
+
+    // bin should be completely contained in the fit range
+    // (fAlphalow, fAlphahig)
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+
+    if ( xlo >= fAlphalow-fEps  &&  xlo <= fAlphahig+fEps  &&
+	 xup >= fAlphalow-fEps  &&  xup <= fAlphahig+fEps     )
+    {
+      fGMbins++;
+
+      if ( xlo < fAlphalo )
+        fAlphalo = xlo;
+
+      if ( xup > fAlphahi )
+        fAlphahi = xup;
+
+      Double_t content = fHist->GetBinContent(i);
+
+
+      // count bins with zero entry
+      if (content <= 0.0)
+        fGNzero++;
+     
+      // set minimum error
+      if (content < 9.0)
+        fHist->SetBinError(i, 3.0);
+
+      //*fLog << "Take : i, content, error = " << i << ",  " 
+      //      << fHist->GetBinContent(i) << ",  "
+      //      << fHist->GetBinError(i)   << endl;
+
+      continue;
+    }    
+    // bin is not completely contained in the fit range : set error huge
+
+    fHist->SetBinError(i, dummy);
+
+    //*fLog << "Omit : i, content, error = " << i << ",  " 
+    //      << fHist->GetBinContent(i) << ",  " << fHist->GetBinError(i) 
+    //      << endl;
+
+  }
+
+
+  // if a bin has no entries don't fit
+  if (fGNzero > 0)
+  {
+    *fLog << "MHFindSignificanceONOFF::FitGaussPoly; out of " << fGMbins 
+          << " bins there are " << fGNzero
+          << " bins with zero entry" << endl;
+
+    fGPoly = NULL;
+    return kFALSE;
+  }
+
+
+  //--------------------------------------------------
+  // prepare fit of a (polynomial+Gauss) :   
+  // (a0 + a1*x + a2*x**2 + a3*x**3 + ...) + A*exp( -0.5*((x-x0)/sigma)**2 )
+
+  TString funcname = "PolyGauss";
+  Double_t xmin =   0.0;
+  Double_t xmax =  90.0;
+
+  TString xpower   = "*x";
+  TString newpower = "*x";
+
+  TString formulaBackg = "[0]";
+  for (Int_t i=1; i<=fDegree; i++)
+      formulaBackg += Form("+[%d]*x^%d", i, i);
+
+  const TString formulaGauss = 
+        Form("[%d]/[%d]*exp(-0.5*((x-[%d])/[%d])^2)",
+             fDegree+1, fDegree+3, fDegree+2, fDegree+3);
+
+  TString formula = formulaBackg;
+  formula += "+";
+  formula += formulaGauss;
+
+  *fLog << "FitGaussPoly : formulaBackg = " << formulaBackg << endl;
+  *fLog << "FitGaussPoly : formulaGauss = " << formulaGauss << endl;
+  *fLog << "FitGaussPoly : formula = " << formula << endl;
+
+  fGPoly = new TF1(funcname, formula, xmin, xmax);
+  TList *funclist = fHist->GetListOfFunctions();
+  funclist->Add(fGPoly);
+
+  fGBackg = new TF1("Backg", formulaBackg, xmin, xmax);
+  //funclist->Add(fGBackg); 
+
+  //------------------------
+  // attention : the dimensions must agree with those in CallMinuit()
+  Int_t npar = fDegree+1 + 3;
+
+  TString parname[npar];
+  TArrayD vinit(npar);
+  TArrayD  step(npar); 
+  TArrayD limlo(npar); 
+  TArrayD limup(npar); 
+  TArrayI   fix(npar);
+
+
+  // take as initial values for the polynomial 
+  // the result from the polynomial fit
+  for (Int_t j=0; j<=fDegree; j++)
+    vinit[j] = fPoly->GetParameter(j);
+
+  Double_t sigma = 8;
+  vinit[fDegree+1] = 2.0 * fNexONOFF * fHist->GetBinWidth(1) / TMath::Sqrt(TMath::Pi()*2);
+  vinit[fDegree+2] = 0;
+  vinit[fDegree+3] = sigma;
+
+  *fLog << "FitGaussPoly : starting value for Gauss-amplitude = " 
+        << vinit[fDegree+1] << endl;
+
+  for (Int_t j=0; j<npar; j++)
+  {
+      parname[j]  = "p";
+      parname[j] += j+1;
+
+      step[j] = vinit[j]!=0 ? TMath::Abs(vinit[j]) / 10.0 : 0.000001;
+  }
+
+  // limit the first coefficient of the polynomial to positive values
+  // because the background must not be negative
+  limup[0] = fHist->GetEntries()*10;
+
+  // limit the sigma of the Gauss function
+  limup[fDegree+3] = 20;
+
+
+  // use the subsequernt loop if you want to apply the
+  // constraint : uneven derivatives (at alpha=0) = zero
+  for (Int_t j=1; j<=fDegree; j+=2)
+  {
+      vinit[j] = 0;
+      step[j]  = 0;
+      fix[j]   = 1;
+  }
+
+  // fix position of Gauss function
+  vinit[fDegree+2] = 0;
+  step[fDegree+2]  = 0;
+  fix[fDegree+2]   = 1;
+   
+  // if a constant background has been assumed (due to low statistics)
+  // fix the background
+  if (fConstantBackg)
+  {
+      step[0] = 0;
+      fix[0]  = 1;
+  }
+
+  MMinuitInterface inter;
+  const Bool_t rc = inter.CallMinuit(fcnpolygauss, parname, vinit, step,
+                                     limlo, limup, fix, fHist, "Migrad",
+                                     kFALSE);
+
+  if (rc != 0)
+  {
+  //  *fLog << "MHFindSignificanceONOFF::FitGaussPoly; (polynomial+Gauss) fit failed"
+  //        << endl;
+  //  return kFALSE;
+  }
+
+
+  //-------------------
+  // get status of the minimization
+  Double_t fmin;
+  Double_t fedm;
+  Double_t errdef;
+  Int_t    npari;
+  Int_t    nparx;
+
+  if (gMinuit)
+    gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, fGIstat);
+
+  *fLog << "MHFindSignificanceONOFF::FitGaussPoly; fmin, fedm, errdef, npari, nparx, fGIstat = "
+        << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+        << ",  " << nparx << ",  " << fGIstat << endl;
+
+
+  //-------------------
+  // store the results
+
+  Int_t nparfree  = gMinuit!=NULL ? gMinuit->GetNumFreePars() : 0;
+  fGChisq         = fmin; 
+  fGNdf           = fGMbins - nparfree;
+  fGProb          = TMath::Prob(fGChisq, fGNdf);
+
+
+  // get fitted parameter values and errors
+  fGValues.Set(npar);
+  fGErrors.Set(npar);
+
+  for (Int_t j=0; j<npar; j++)
+  {
+    Double_t val, err;
+    if (gMinuit)
+      gMinuit->GetParameter(j, val, err);
+
+    fGPoly->SetParameter(j, val);
+    fGPoly->SetParError(j, err);
+
+    fGValues[j] = val;
+    fGErrors[j] = err; 
+
+    if (j <=fDegree)
+    {
+      fGBackg->SetParameter(j, val);
+      fGBackg->SetParError(j, err);
+    }
+  }
+
+  fSigmaGauss  = fGValues[fDegree+3];
+  fdSigmaGauss = fGErrors[fDegree+3];
+  // fitted total number of excess events 
+  fNexGauss = fGValues[fDegree+1] * TMath::Sqrt(TMath::Pi()*2) /
+                                         (fHist->GetBinWidth(1)*2 );
+  fdNexGauss = fNexGauss * fGErrors[fDegree+1]/fGValues[fDegree+1];
+
+  //--------------------------------------------------
+  // get the error matrix of the fitted parameters
+
+
+  if (fGIstat >= 1)
+  {
+    // error matrix was calculated
+    if (gMinuit)
+      gMinuit->mnemat(&fGEmat[0][0], fGNdim);
+
+    // copy covariance matrix into a matrix which includes also the fixed
+    // parameters
+    TString  name;
+    Double_t bnd1, bnd2, val, err;
+    Int_t    jvarbl;
+    Int_t    kvarbl;
+    for (Int_t j=0; j<npar; j++)
+    {
+        if (gMinuit)
+            gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+        for (Int_t k=0; k<npar; k++)
+        {
+            if (gMinuit)
+                gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+            fGEma[j][k] = jvarbl==0 || kvarbl==0 ? 0 : fGEmat[jvarbl-1][kvarbl-1];
+        }
+    }
+  }
+  else
+  {
+    // error matrix was not calculated, construct it
+    *fLog << "MHFindSignificanceONOFF::FitPolynomial; error matrix not defined" 
+          << endl;
+    for (Int_t j=0; j<npar; j++)
+    {
+        for (Int_t k=0; k<npar; k++)
+            fGEma[j][k] = 0;
+
+        fGEma[j][j] = fGErrors[j]*fGErrors[j];
+    }
+  }
+
+
+  //--------------------------------------------------
+  // calculate correlation matrix
+  for (Int_t j=0; j<npar; j++)
+  {
+    for (Int_t k=0; k<npar; k++)
+    {
+        const Double_t sq = fGEma[j][j]*fGEma[k][k];
+        fGCorr[j][k] = sq==0 ? 0 : fGEma[j][k] / sqrt( fGEma[j][j]*fGEma[k][k] );
+    }
+  }
+
+
+  //--------------------------------------------------
+  // reset the errors of the points in the histogram
+  for (Int_t i=1; i<=nbins; i++)
+    fHist->SetBinError(i, saveError[i-1]);
+
+  return kTRUE;
+
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  DetExcessONOFF
+//
+//  using the result of the polynomial fit (fValuesOFF), DetExcessONOFF determines
+//
+//  - the total number of events in the signal region (fNon)
+//  - the number of backgound events (fitted) in the signal region (fNoffSigFitted)
+//  - the number of OFF (normalized evetns) in the alpha OFF distribution (fNoffSig)
+//  - the number of excess events (fNexONOFF)
+//  - the number of excess events using the fitted OFF (fNexONOFFFitted)
+//  - the effective number of background events (fNoff), and fGamma :
+//    fNoffSigFitted = fGamma * fNoff;  fdNoffSigFitted = fGamma * sqrt(fNoff);
+//
+//  It assumed that the polynomial is defined as
+//               a0 + a1*x + a2*x**2 + a3*x**3 + ..
+//
+//  and that the alpha distribution has the range 0 < alpha < 90 degrees
+//
+
+Bool_t MHFindSignificanceONOFF::DetExcessONOFF()
+{
+  //*fLog << "MHFindSignificanceONOFF::DetExcessONOFF;" << endl;
+
+//--------------------------------------------
+  // calculate the total number of events (fNon) in the signal region
+
+  fNon  = 0.0;
+  fdNon = 0.0;
+
+  Double_t alphaup = -1000.0; 
+  Double_t binwidth = fHist->GetBinWidth(1);
+
+  Int_t nbins = fHist->GetNbinsX();
+  for (Int_t i=1; i<=nbins; i++)
+  {
+    Double_t  xlo = fHist->GetBinLowEdge(i);
+    Double_t  xup = fHist->GetBinLowEdge(i+1);
+ 
+    // bin must be completely contained in the signal region
+    if ( xlo <= (fAlphasig+fEps)  &&  xup <= (fAlphasig+fEps)    )
+    {
+      Double_t width = fabs(xup-xlo);
+      if (fabs(width-binwidth) > fEps)
+      {
+        *fLog << "MHFindSignificanceONOFF::DetExcessONOFF; alpha plot has variable binning, which is not allowed" 
+          << endl;
+        return kFALSE;
+      }
+
+      if (xup > alphaup)
+        alphaup = xup;
+
+      fNon  += fHist->GetBinContent(i);
+      fdNon += fHist->GetBinError(i) * fHist->GetBinError(i);
+    }
+  }
+  fdNon = sqrt(fdNon);
+
+  *fLog << "MHFindSignificamceONOFF::DetExcessONOFF:" << endl
+	<< "fNon = " << fNon << " ; fdNon = " << fdNon << endl;
+
+
+  // tmp
+  //if (fNon == 0)
+  //{
+  //    cout << "ERROR... WITH COUNTED OF ON EVETNS: fAlphasig, fEps = "
+//	   << fAlphasig << ", " << fEps << endl;
+  //    fHist-> DrawCopy();
+  //   gPad -> SaveAs("HistON.ps");
+  //}
+  // endtmp
+
+
+  // the actual signal range is :
+  if (alphaup == -1000.0)
+    return kFALSE;
+
+  fAlphasi = alphaup;
+
+
+  //*fLog << "fAlphasi, fNon, fdNon, binwidth, fDegree = " << fAlphasi << ",  "
+  //      << fNon << ",  " << fdNon << ",  " << binwidth << ",  "
+  //      << fDegree << endl;
+
+
+  // Calculate the number of OFF events in the signal region
+  // ___________________________________________________
+  
+
+  fNoffSig = 0.0;
+  fdNoffSig = 0.0;
+
+  Double_t alphaupOFF = -1000.0; 
+  Double_t binwidthOFF = fHistOFF->GetBinWidth(1);
+
+  Int_t nbinsOFF = fHistOFF->GetNbinsX();
+
+  for (Int_t i=1; i<=nbinsOFF; i++)
+  {
+    Double_t xlo = fHistOFF->GetBinLowEdge(i);
+    Double_t xup = fHistOFF->GetBinLowEdge(i+1);
+ 
+    // bin must be completely contained in the signal region
+    if ( xlo <= (fAlphasig+fEps)  &&  xup <= (fAlphasig+fEps)    )
+    {
+      Double_t width = fabs(xup-xlo);
+      if (fabs(width-binwidthOFF) > fEps)
+      {
+        *fLog << "MHFindSignificanceONOFF::DetExcessONOFF; alphaOFF plot has variable binning, which is not allowed" 
+          << endl;
+        return kFALSE;
+      }
+
+      if (xup > alphaupOFF)
+        alphaup = xup;
+
+      fNoffSig  += fHistOFF->GetBinContent(i);
+      fdNoffSig += fHistOFF->GetBinError(i) * fHistOFF->GetBinError(i);
+    }
+  }
+  fdNoffSig = sqrt(fdNoffSig);
+
+  // tmp
+  //if (fNoffSig == 0)
+  //{
+  //   cout << "ERROR... WITH COUNTED OF OFF EVETNS: fAlphasig, fEps = "
+//	   << fAlphasig << ", " << fEps << endl;
+  //     fHistOFF-> DrawCopy();
+  //   gPad -> SaveAs("HistOFF.ps");
+  //}
+  //endtmp
+
+  // the actual signal range is :
+  if (alphaup == -1000.0)
+    return kFALSE;
+
+  fAlphasiOFF = alphaup;
+
+  if (fabs(fAlphasiOFF - fAlphasi) > fEps)
+  {
+      *fLog << "MHFindSignificanceONOFF::DetExcessONOFF; fAlphasiOFF ("
+	    << fAlphasiOFF << ") is not equal to fAlphasi (" 
+	    << fAlphasi << "), this is something that should not happen" 
+	    << endl;
+
+    //return kFALSE; It might happen in pathological cases (very few OFF)
+      // and I want to see the results, anyhow
+  }
+
+
+
+   // Calculate the number of OFF events in the total OFF region 
+  // defined by fAlphaminOFF and fAlphamaxOFF 
+  // ___________________________________________________
+  
+  fNoffTot = 0.0;
+  fdNoffTot = 0.0;
+
+  
+ 
+  for (Int_t i=1; i<=nbinsOFF; i++)
+  {
+    Double_t xlo = fHistOFF->GetBinLowEdge(i);
+    Double_t xup = fHistOFF->GetBinLowEdge(i+1);
+ 
+    // bin must be completely contained in the signal region
+    if ( xlo >= (fAlphaminOFF-fEps)  &&  xup <= (fAlphamaxOFF+fEps)    )
+    {
+      Double_t width = fabs(xup-xlo);
+      if (fabs(width-binwidthOFF) > fEps)
+      {
+        *fLog << "MHFindSignificanceONOFF::DetExcessONOFF; alphaOFF plot has variable binning, which is not allowed" 
+          << endl;
+        return kFALSE;
+      }
+
+      fNoffTot  += fHistOFF->GetBinContent(i);
+      fdNoffTot += fHistOFF->GetBinError(i) * fHistOFF->GetBinError(i);
+    }
+  }
+  fdNoffTot = sqrt(fdNoffTot);
+
+
+
+
+
+
+
+
+
+  //--------------------------------------------
+  // calculate the number of OFF fitted events (fNoffSigFitted) in the signal region
+  // and its error (fdNoffSigFitted) 
+
+ 
+
+ if (fUseFittedQuantities) 
+ {
+     //--------------------------------------------
+     // calculate the number of OFF fitted events (fNoffSigFitted) in the signal region
+     // and its error (fdNoffSigFitted) 
+     
+     Double_t fac = 1.0/binwidthOFF;
+     
+     fNoffSigFitted        = 0.0;
+     Double_t altothejplus1 = fAlphasi; // Limit for signal found for ON data is used. 
+     for (Int_t j=0; j<=fDegreeOFF; j++)
+     {
+	 fNoffSigFitted += fValuesOFF[j] * altothejplus1 / ((Double_t)(j+1));
+	 altothejplus1 *= fAlphasi;
+     }
+     fNoffSigFitted *= fac;
+     
+     // derivative of fNoffSigFitted 
+     Double_t facj;
+     Double_t fack;
+     
+     Double_t sum = 0.0;
+     altothejplus1 = fAlphasi;
+     for (Int_t j=0; j<=fDegreeOFF; j++)
+     {
+	 facj = altothejplus1 / ((Double_t)(j+1));
+	 
+	 Double_t altothekplus1 = fAlphasi;    
+	 for (Int_t k=0; k<=fDegreeOFF; k++)
+	 {
+	     fack = altothekplus1 / ((Double_t)(k+1));
+	     sum   += facj * fack * fEmaOFF[j][k];
+	     altothekplus1 *= fAlphasi;
+	 }
+	 altothejplus1 *= fAlphasi;
+     }
+     sum  *= fac*fac;
+     
+     if (sum < 0.0)
+     {
+	 *fLog << "MHFindsignificanceONOFF::DetExcessONOFF; error squared is negative" 
+	       << endl;
+	 return kFALSE;
+     }
+     
+     fdNoffSigFitted = sqrt(sum);
+     
+     
+     // We can now compare fNoffSig with fNoffSigFitted (and their errors)
+     // NUmbers should agree within 10 % (errors within 20%)
+     
+     if (fabs(fNoffSig - fNoffSigFitted) > 0.1 * fNoffSigFitted)
+     {
+	 *fLog << "MHFindsignificanceONOFF::DetExcessONOFF; number of OFF events and Fitted number of OFF events in signal region do not agree (within 10 %)" << endl;
+	 
+	 *fLog << "fNoffSig = " << fNoffSig << " ; fNoffSigFitted = " << fNoffSigFitted << endl;
+	 
+	 
+	 // return kFALSE; NOt yet...
+     }
+     
+     /*
+       if (fabs(fdNoffSig - fdNoffSigFitted) > 0.2 * fdNoffSigFitted)
+       {
+       *fLog << "MHFindsignificanceONOFF::DetExcessONOFF; error in number of OFF events and error in Fitted number of OFF events in signal region do not agree (within 20 %)" 
+       << endl;
+       
+       
+       *fLog << "fdNoffSig = " << fdNoffSig << " ; fdNoffSigFitted = " << fdNoffSigFitted << endl;
+       
+       
+       //return kFALSE; NOt yet...
+       }
+       
+     */
+     
+    
+     
+     // Calculate the number of OFF events in the whole fit region (fAlphaminOFF-fAlphamaxOFF)
+     // ___________________________________________________
+     
+     
+     
+     fNoffTotFitted = 0.0;
+     
+     altothejplus1 = fAlphamaxOFF; // Limit for OFF data fit 
+     for (Int_t j=0; j<=fDegreeOFF; j++)
+     {
+	 fNoffTotFitted += fValuesOFF[j] * altothejplus1 / ((Double_t)(j+1));
+	 altothejplus1 *= fAlphamaxOFF;
+     }
+     fNoffTotFitted *= fac;
+     
+     // derivative of fdNoffTotFitted 
+     
+     
+     sum = 0.0;
+     altothejplus1 = fAlphamaxOFF;
+     for (Int_t j=0; j<=fDegreeOFF; j++)
+     {
+	 facj = altothejplus1 / ((Double_t)(j+1));
+	 
+	 Double_t altothekplus1 = fAlphamaxOFF;    
+	 for (Int_t k=0; k<=fDegreeOFF; k++)
+	 {
+	     fack = altothekplus1 / ((Double_t)(k+1));
+	     
+	     sum   += facj * fack * fEmaOFF[j][k];
+	     altothekplus1 *= fAlphamaxOFF;
+	 }
+	 altothejplus1 *= fAlphamaxOFF;
+     }
+     sum  *= fac*fac;
+
+     if (sum < 0.0)
+     {
+	 *fLog << "MHFindsignificanceONOFF::DetExcessONOFF; error squared is negative" 
+	       << endl;
+	 return kFALSE;
+     }
+     
+     fdNoffTotFitted = sqrt(sum);
+     
+
+
+ }
+
+else
+ {
+     fNoffSigFitted = 0.0;
+     fdNoffSigFitted = 0.0;
+     fNoffTotFitted = 0.0;
+     fdNoffTotFitted = 0.0;
+ }
+
+
+
+ *fLog << "MHFindSignificamceONOFF::DetExcessONOFF; INFO ABOOUT COMPUTED OFF EVENTS..." << endl
+       << "fNoffSig = " << fNoffSig << "; fdNoffSig =  " << fdNoffSig << endl
+       << "fNoffSigFitted = " << fNoffSigFitted 
+       << "; fdNoffSigFitted =  " << fdNoffSigFitted << endl;
+ 
+
+
+
+
+  //--------------------------------------------
+  // calculate the number of excess events in the signal region
+
+  fNexONOFF = fNon - fNoffSig*fNormFactor;
+  fNexONOFFFitted = fNon - fNoffSigFitted*fNormFactor;
+  
+  
+  *fLog << "MHFindSignificamceONOFF::DetExcessONOFF;" << endl
+	<< "fNexONOFF (= fNon - fNoffSig*fNormFactor)  = " << fNexONOFF << endl
+	<< "fNexONOFFFitted (= fNon - fNoffSigFitted*fNormFactor)  = " << fNexONOFFFitted << endl;
+
+
+  //--------------------------------------------
+  // calculate the effective number of background events (fNoff) , and fGamma :
+  // fNbg = fGamma * fNoff = fNormFactor* fNoffSigFitted;   
+  // dfNbg = fGamma * sqrt(fNoff) = fNormFactor * fdNoffSigFitted;
+  
+  if (fNoffSigFitted < 0.0)
+  {
+      *fLog << "MHFindSignificamceONOFF::DetExcessONOFF; number of fitted OFF events in signal region is negative,  fNoffSigFitted, fdNoffSigFitted = "
+	    << fNoffSigFitted   << ",  " << fdNoffSigFitted << endl;
+      
+      fGamma = 1.0;
+      fNoff  = 0.0;
+      return kFALSE;
+  }
+  
+  if (fNoffSigFitted > 0.0)
+  {
+      fGamma = fNormFactor * fdNoffSigFitted*fdNoffSigFitted/fNoffSigFitted;
+      fNoff  = fNormFactor * fNoffSigFitted/fGamma; 
+  }
+  else
+  {
+      fGamma = 1.0;
+      fNoff  = 0.0;
+  }
+  
+   *fLog << "MHFindSignificamceONOFF::DetExcessONOFF: " << endl
+	 << "fGamma = " << fGamma << " ; fNoff = " << fNoff << endl;
+
+  
+  return kTRUE;
+}
+
+
+
+
+
+// --------------------------------------------------------------------------
+//
+//  SigmaLiMa
+//
+//  calculates the significance according to Li & Ma
+//  ApJ 272 (1983) 317; formula 17
+//
+Bool_t MHFindSignificanceONOFF::SigmaLiMa(Double_t non,   Double_t noff, 
+                                     Double_t gamma, Double_t *siglima)
+{
+  if (gamma <= 0.0  ||  non <= 0.0  ||  noff <= 0.0)
+  {
+    *siglima = 0.0;
+    return kFALSE;
+  }
+
+  Double_t help1 = non  * log( (1.0+gamma)*non  / (gamma*(non+noff)) );
+  Double_t help2 = noff * log( (1.0+gamma)*noff / (       non+noff ) );
+  *siglima = sqrt( 2.0 * (help1+help2) );
+
+  Double_t nex = non - gamma*noff;
+  if (nex < 0.0)
+    *siglima = - *siglima;
+
+  //*fLog << "MHFindSignificanceONOFF::SigmaLiMa; non, noff, gamma, *siglima = "
+  //      << non << ",  " << noff << ",  " << gamma << ",  " << *siglima << endl;
+
+  return kTRUE;
+}
+
+
+
+//  calculates the significance according to Li & Ma
+//  ApJ 272 (1983) 317; formula 5
+//
+Bool_t MHFindSignificanceONOFF::SigmaLiMaForm5(Double_t non,   Double_t noff, 
+					       Double_t gamma, Double_t *siglima)
+{
+  if (gamma <= 0.0  ||  non <= 0.0  ||  noff <= 0.0)
+  {
+    *siglima = 0.0;
+    return kFALSE;
+  }
+
+  Double_t nex = non - (gamma*noff);
+  Double_t tmp = non + (gamma*gamma)*noff;
+  tmp = TMath::Sqrt(tmp);
+
+  *siglima = nex/tmp;
+
+  if (nex < 0.0)
+    *siglima = - *siglima;
+
+  //*fLog << "MHFindSignificanceONOFF::SigmaLiMa; non, noff, gamma, *siglima = "
+  //      << non << ",  " << noff << ",  " << gamma << ",  " << *siglima << endl;
+
+  return kTRUE;
+}
+
+
+
+
+// --------------------------------------------------------------------------
+//
+
+// Following function computes a clone of fHistOFF and normalizes 
+// contents, errors and fPolyOFF (if exists) with the fNormFactor. 
+// This normalized OFF hist will be used when plotting OFF data 
+// together with ON data.
+
+Bool_t MHFindSignificanceONOFF::ComputeHistOFFNormalized()
+{
+
+    
+    if (!fHist)
+    {
+	*fLog << "MHFindsignificanceONOFF::ComputeHistOFFNormalized; fHist does not exist, normalization of HistOFF can not be performed properly..."
+	      << endl;
+	return kFALSE;
+	
+    }
+
+    
+
+    if (!fHistOFF)
+    {
+	*fLog << "MHFindsignificanceONOFF::ComputeHistOFFNormalized; fHistOFF does not exist, hence can not be normalized" 
+          << endl;
+    return kFALSE;
+	
+    }
+
+
+    if (fNormFactor <= 0)
+    {
+	*fLog << "MHFindsignificanceONOFF::ComputeHistOFFNormalized; fNormFactor is ZERO or NEGATIVE, it might have not been defined yet..."
+          << endl;
+    return kFALSE;
+
+    }
+
+
+    Double_t BinWidthAlphaON = fHist -> GetBinWidth(1);
+    Double_t BinWidthAlphaOFF = fHistOFF -> GetBinWidth(1);
+    Double_t BinWidthRatioONOFF = BinWidthAlphaON/BinWidthAlphaOFF;
+
+
+    *fLog << "MHFindsignificanceONOFF::ComputeHistOFFNormalized; INFO about alpha ON, OFF histo bins"
+	  << endl
+	//  << "fHist bin width = " << BinWidthAlphaON 
+	  << " fHistOFF bin width = " << BinWidthAlphaOFF << endl;
+
+
+
+    TString fHistOFFNormalizedName = fHistOFF -> GetName();
+    fHistOFFNormalizedName += (" (Normalized)");
+    // fHistOFFNormalized = (TH1*) fHistOFF -> Clone();
+    // fHistOFFNormalized -> SetNameTitle(fHistOFFNormalizedName, fHistOFFNormalizedName);
+
+
+    Int_t nbinsOFFNormalized = 0;
+    Int_t nbinsOFF = 0;
+    Double_t xlow = 0.0;
+    Double_t xup = 0.0;
+    Double_t content = 0.0;
+    Double_t error = 0.0;
+    Double_t BinCenter = 0.0;
+    
+
+    // Bins for normalized OFF histo will be the ones of ON histo
+
+    
+    nbinsOFF = fHistOFF -> GetNbinsX();
+    nbinsOFFNormalized = nbinsOFF;
+    xlow = fHistOFF -> GetBinLowEdge(1);
+    xup = fHistOFF -> GetBinLowEdge(nbinsOFFNormalized);
+    xup = xup + BinWidthAlphaON;
+
+    *fLog << "MHFindsignificanceONOFF::ComputeHistOFFNormalized; Limits for fHistOFFNormalized: " 
+	  << "nbins, xlow, xup: " << nbinsOFFNormalized << ", " 
+	  <<  xlow << ", " << xup << endl;
+    
+    fHistOFFNormalized = new TH1F (fHistOFFNormalizedName, fHistOFFNormalizedName, 
+				  nbinsOFFNormalized, xlow, xup);
+    
+
+    // fHistOFFNormalized is filled with data from fHistOFF, 
+    // taken into account the possible bin difference
+
+    
+    for (Int_t i = 1; i <= nbinsOFF; i++)
+    {
+	BinCenter = fHistOFF -> GetBinCenter(i);
+	fHistOFFNormalized -> Fill (BinCenter, fHistOFF -> GetBinContent(i));
+	fHistOFFNormalized -> SetBinError(i, fHistOFF -> GetBinError(i));
+    }
+	    
+
+    
+
+    for (Int_t i = 1; i <= nbinsOFFNormalized; i++)
+    {
+	content = fNormFactor * fHistOFFNormalized -> GetBinContent(i);
+	error = fNormFactor * fHistOFFNormalized -> GetBinError(i);
+	
+	fHistOFFNormalized -> SetBinContent (i, content);
+	fHistOFFNormalized -> SetBinError (i, error);
+    }
+	
+
+    // Number of entries is obtained from histOFF.
+    // and set to histOFFNoramlized; otherwise, the number 
+    // of entries in  histOFFNoramlized would be "nbins"
+
+    Double_t entries = fNormFactor * (fHistOFF -> GetEntries());
+    fHistOFFNormalized -> SetEntries(entries);
+
+
+
+
+    // If polynomial fit has been performed for fHistOFF, 
+    // it is defined a new polyfunction for fHistOFFNormalized, 
+    // which will be the polyfunction of fHistOFF normalized.
+    // Function will be added to the function list of fHistOFFNormalized
+
+
+    
+    if (fPolyOFF == NULL)
+    {
+	*fLog << "MHFindsignificanceONOFF::ComputeHistOFFNormalized; fPolyOFF does not exist..."
+	      << endl;
+    }
+
+    if (fPolyOFF)
+    {
+	*fLog << "MHFindsignificanceONOFF::ComputeHistOFFNormalized; fPolyOFF exists... will be also normalized and included in the list of functions of fHistOFFNormalized"
+	      << endl;
+	
+	
+
+	
+	// Normalization of the function using fNormFactor and 
+	// BinWidthON/BinWidthOFF relation of alpha ON/OFF histograms
+	// This makes possible to plot it together with ON alpha histo
+
+	TString FunctionName("PolyOFFNormalized");
+
+	Double_t xmin = fAlphaminOFF;
+	Double_t xmax = fAlphamaxOFF;
+
+	TString formula = "[0]";
+	TString bra1     = "+[";
+	TString bra2     =    "]";
+	TString xpower   = "*x";
+	TString newpower = "*x";
+	for (Int_t i=1; i<=fDegreeOFF; i++)
+	{
+	    formula += bra1;
+	    formula += i;
+	    formula += bra2;
+	    formula += xpower;
+	    
+	    xpower += newpower;
+	}
+
+      *fLog << "MHFindsignificanceONOFF::ComputeHistOFFNormalized; formula = " << formula << endl;
+
+
+	
+	fPolyOFFNormalized = new TF1 (FunctionName, formula, xmin, xmax);
+	
+	
+	Double_t Parameter = 0.0;
+	Double_t ParameterError = 0.0;
+
+	*fLog << " MHFindsignificanceONOFF::ComputeHistOFFNormalized; Fit parameters info: " << endl;
+	for (Int_t i = 0; i <= fDegreeOFF; i++)
+	{
+	    Parameter = fNormFactor * BinWidthRatioONOFF * fValuesOFF[i];
+	    ParameterError = fNormFactor * BinWidthRatioONOFF * fErrorsOFF[i];
+
+	    fPolyOFFNormalized -> SetParameter(i, Parameter);
+	    fPolyOFFNormalized -> SetParError(i,ParameterError);
+
+	   
+
+	    // Parameters are shown :
+	    
+	    *fLog  << " fValuesOFF[" << i<< "] = " << fValuesOFF[i] 
+		   << " ; Parameter for  fPolyOFFNormalized = " << Parameter  << endl;
+
+	}
+	    
+
+	TList *funclist = fHistOFFNormalized->GetListOfFunctions();
+	
+	// temporal...
+	//*fLog << "INFO concerning list of functions of fHistOFFNormalized :" << endl
+	//       << "List before adding OFF Normal., after adding it and after removing fPolyOFF..." 
+	//       << endl;
+	
+	//funclist-> Print();
+	funclist-> Add(fPolyOFFNormalized);
+	
+	//funclist-> Print();
+	
+		
+
+    }
+
+    return kTRUE;
+
+}
+
+// --------------------------------------------------------------------------
+//
+
+Bool_t MHFindSignificanceONOFF::DrawHistOFF()
+{
+    if (fHistOFF == NULL )
+    {
+	*fLog << "MHFindSignificanceONOFF::DrawHistOFF; fHistOFF = NULL" << endl;
+	return kFALSE;
+    }
+
+//    fPsFilename -> NewPage();
+
+    // PLOT DISABLE
+    /*
+    TCanvas* CanvasHistOFF = new TCanvas(fHistOFF->GetName(), fHistOFF->GetName(), 600, 600);
+
+    //gStyle->SetOptFit(1011);
+
+    gROOT->SetSelectedPad(NULL);    
+    gStyle->SetPadLeftMargin(0.1);
+    gStyle -> SetOptStat(1);
+
+    CanvasHistOFF->cd();
+
+
+    if (fHistOFF)
+    {
+      fHistOFF->DrawCopy();
+    }
+
+    // TF1 *fpolyOFF = fHistOFF->GetFunction("PolyOFF");    
+    if (fPolyOFF == NULL)
+	*fLog << "MHFindSignificanceONOFF::DrawHistOFF; fpolyOFF = NULL" << endl;
+
+    if (fPolyOFF)
+    {
+      // 2, 1 is red and solid
+      fPolyOFF->SetLineColor(2);
+      fPolyOFF->SetLineStyle(1);
+      fPolyOFF->SetLineWidth(2);
+      fPolyOFF->DrawCopy("same");
+    }
+
+    CanvasHistOFF -> Update();
+
+    
+    */
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+
+Bool_t MHFindSignificanceONOFF::DrawHistOFFNormalized()
+{
+    if (fHistOFFNormalized == NULL )
+    {
+	*fLog << "MHFindSignificanceONOFF::DrawHistOFF; fHistOFFNormalized = NULL" << endl;
+	return kFALSE;
+    }
+
+    //   fPsFilename -> NewPage();
+
+    // PLOT DISABLE TO PERFORM GRID ANALYSIS
+    /*
+    TCanvas* CanvasHistOFFNormalized = new TCanvas(fHistOFFNormalized->GetName(), 
+						   fHistOFFNormalized->GetName(), 600, 600);
+
+    //gStyle->SetOptFit(1011);
+
+    // gROOT->SetSelectedPad(NULL);    
+    gStyle->SetPadLeftMargin(0.1);
+    gStyle -> SetOptStat(1);
+
+    CanvasHistOFFNormalized->cd();
+    
+
+    if (fHistOFFNormalized)
+    {
+      fHistOFFNormalized->DrawCopy();
+    }       
+
+    // TF1 *fpolyOFFNormalized = fHistOFFNormalized->GetFunction("PolyOFFNormalized");    
+    if (fPolyOFFNormalized == NULL)
+	*fLog << "MHFindSignificanceONOFF::DrawHistOFF; fPolyOFFNormalized = NULL" << endl;
+
+    if (fPolyOFFNormalized)
+    {
+      // 2, 1 is red and solid
+      fPolyOFFNormalized->SetLineColor(2);
+      fPolyOFFNormalized->SetLineStyle(1);
+      fPolyOFFNormalized->SetLineWidth(2);
+      fPolyOFFNormalized->DrawCopy("same");
+    }
+
+    CanvasHistOFFNormalized -> Update();
+*/
+
+    return kTRUE;
+    
+}
+
+
+// --------------------------------------------------------------------------
+//
+
+Bool_t MHFindSignificanceONOFF::DrawFit(const Option_t *opt)
+{
+    if (fHistOFFNormalized == NULL ||  fHist == NULL)
+      *fLog << "MHFindSignificanceONOFF::DrawFit; fHistOFFNormalized = NULL or fHist == NULL" << endl;
+
+    //fPsFilename -> NewPage();
+
+
+    // PLOT DISABLE TO PERFORM GRID ANALYSIS
+    // I DO SAVE PS FILE, BUT CANVAS IS DELETED AFTERWARDS
+
+    fCanvas = new TCanvas("Alpha", "Alpha plot", 600, 600);
+    fCanvas -> SetFillColor(10);
+    
+
+
+
+    //gStyle->SetOptFit(1011);
+
+    gROOT->SetSelectedPad(NULL);    
+    gStyle -> SetFrameFillColor(10);
+    gStyle->SetPadLeftMargin(0.15);
+    gStyle -> SetOptStat(1);
+    
+    fCanvas->cd();
+    
+    if (fHist)
+      {
+	fHist -> SetTitle("Alpha Plot");
+	fHist-> SetTitleOffset(1.5, "Y");
+        fHist-> SetLineColor(kRed);
+	fHist-> DrawCopy();
+	
+      }
+
+
+    if (fHistOFFNormalized)
+    {
+	TF1 *fpoly = fHistOFFNormalized->GetFunction("PolyOFFNormalized");    
+	if (fpoly == NULL)
+	    *fLog << "MHFindSignificanceONOFF::DrawFit; fPolyOFFNormalized = NULL" << endl;
+
+	if (fpoly)
+	{
+	    // 2, 1 is red and solid
+	    fpoly->SetLineColor(2);
+	    fpoly->SetLineStyle(1);
+	    fpoly->SetLineWidth(2);
+	    fpoly->DrawCopy("same");
+	}
+
+
+//	fHistOFFNormalized->SetLineColor(kRed);
+//	fHistOFFNormalized->DrawCopy("same");
+
+    }
+
+    if (fFitGauss)
+    {
+      TF1 *fpolygauss = fHist->GetFunction("PolyGauss");    
+      if (fpolygauss == NULL)
+        *fLog << "MHFindSignificanceONOFF::DrawFit; fpolygauss = NULL" << endl;
+
+      if (fpolygauss)
+      {
+        // 4, 1 is blue and solid
+        fpolygauss->SetLineColor(4);
+        fpolygauss->SetLineStyle(1);
+        fpolygauss->SetLineWidth(4);
+        fpolygauss->DrawCopy("same");
+      }
+ 
+      TF1 *fbackg = fHist->GetFunction("Backg");    
+      if (fbackg == NULL)
+        *fLog << "MHFindSignificanceONOFF::DrawFit; fbackg = NULL" << endl;
+
+    if (fHistOFFNormalized)
+      {
+      fHistOFFNormalized->SetFillStyle(3002);
+      fHistOFFNormalized->SetFillColor(9);
+      fHistOFFNormalized->DrawCopy("Psamebar");}
+
+
+      if (fbackg)
+      {
+        // 10, 1 is white and solid
+        //fbackg->SetLineColor(kRed);
+        fbackg->SetLineColor(196);
+        fbackg->SetLineStyle(1);
+        fbackg->SetLineWidth(4);
+	fbackg->DrawCopy("same"); // I do not want to draw it... already too many things.
+      }
+    }
+
+//    fCanvas->SaveAs("plot.root");
+//    fCanvas->SaveAs("plot.ps");
+
+    //-------------------------------
+    // print results onto the figure
+    
+    
+    
+    TPaveText *pt = new TPaveText(0.30, 0.35, 0.70, 0.90, "NDC");
+    char tx[100];
+    
+    sprintf(tx, "Results of polynomial fit to OFF (order %2d) :", fDegreeOFF);
+    TText *t1 = pt->AddText(tx);
+    t1->SetTextSize(0.03);
+    t1->SetTextColor(2);
+    
+    sprintf(tx, "   (%6.2f< |alpha| <%6.2f [\\circ])", fAlphaminOFF, fAlphamaxOFF);
+    pt->AddText(tx);
+    
+    sprintf(tx, "   chi2 = %8.2f,  Ndof = %4d,  Prob = %6.2f", 
+	    fChisqOFF, fNdfOFF, fProbOFF);
+    pt->AddText(tx);
+    
+    sprintf(tx, "   OFF events (fit)= %8.1f #pm %8.1f", 
+	    fNoffTotFitted, fdNoffTotFitted);
+    pt->AddText(tx);
+    
+    sprintf(tx, "   OFF events (meas) = %8.1f #pm %8.1f", fNoffTot, fdNoffTot);
+    pt->AddText(tx);
+    
+    sprintf(tx, "   OFF Normalization Factor (= Non/Noff) = %4.4f", fNormFactor);
+    pt->AddText(tx);
+    
+    
+    
+    
+    //sprintf(tx, "     ");
+    //pt->AddText(tx);
+    
+    //--------------
+    sprintf(tx, "Results for |alpha|< %6.2f [\\circ] :", fAlphasi);
+    TText *t6 = pt->AddText(tx);
+    t6->SetTextSize(0.03);
+    t6->SetTextColor(8);
+    
+    sprintf(tx, "   Non = %8.1f #pm %8.1f", fNon, fdNon);
+    pt->AddText(tx);
+    
+    
+    if(fUseFittedQuantities)
+      {
+	//// **************************************************
+	///// PRINT INFORMATION ABOUT FITTED QUANTITIES  /////////
+	
+	
+	
+	Double_t NoffFitNormalized = fNoffSigFitted * fNormFactor;
+	Double_t ErrorNoffFitNormalized = fdNoffSigFitted * fNormFactor;
+	Double_t SignificanceUsed = GetSignificance();
+	
+	sprintf(tx, "   Noff Fitted (Normalized)  = %8.1f #pm %8.1f", 
+		NoffFitNormalized, ErrorNoffFitNormalized);
+	pt->AddText(tx);
+	
+	
+	sprintf(tx, "   Nex (ON - OFF Fitted) = %8.1f #pm %8.1f", 
+		fNexONOFFFitted, fdNexONOFFFitted);
+	pt->AddText(tx);
+	
+	
+	sprintf(tx, "   Gamma = %4.4f,   Effective Noff (i.e. fNoff) = %6.1f", 
+		fGamma, fNoff);
+	pt->AddText(tx);
+	
+	
+	Double_t ratio = fNoffSigFitted>0.0 ? fNexONOFFFitted/(fNoffSigFitted*fNormFactor) : 0.0;
+	sprintf(tx, "   Significance = %6.2f,    Nex/(Nbg*NormFactor) = %6.2f", 
+		SignificanceUsed, ratio);
+	pt->AddText(tx);
+	
+	
+      }
+    
+    else
+      {
+	//// **************************************************
+	///// PRINT INFORMATION ABOUT MEASURED QUANTITIES  /////////
+	
+	
+	Double_t NoffNormalized = fNoffSig * fNormFactor;
+	Double_t ErrorNoffNormalized = fdNoffSig * fNormFactor;
+	Double_t SignificanceUsed = GetSignificance();
+	
+	sprintf(tx, "   Noff measured (Normalized)  = %8.1f #pm %8.1f", 
+		NoffNormalized, ErrorNoffNormalized);
+	pt->AddText(tx);
+	
+	sprintf(tx, "   Nex (ON - OFF measured) = %8.1f #pm %8.1f", 
+		fNexONOFF, fdNexONOFF);
+	pt->AddText(tx);
+	
+	Double_t ratio = fNoffSig>0.0 ? fNexONOFF/(fNoffSig*fNormFactor) : 0.0;
+	sprintf(tx, "   Significance = %6.2f,    Nex/(Nbg*NormFactor) = %6.2f", 
+		SignificanceUsed, ratio);
+	pt->AddText(tx);
+	
+      }
+    
+    /*
+      // Temporally I will also show ALL SIGMALIMA COMPUTED.
+      
+      sprintf(tx, 
+      "  fSigLiMa1 =  %6.2f, fSigLiMa2 =  %6.2f, fSigLiMa3 =  %6.2f", 
+      fSigLiMa,fSigLiMa2, fSigLiMa3);
+      pt->AddText(tx);
+    */
+    
+    
+    //--------------
+    if (fFitGauss)
+      {
+	sprintf(tx, "Results of (polynomial+Gauss) fit  :");
+	TText *t7 = pt->AddText(tx);
+	t7->SetTextSize(0.03);
+	t7->SetTextColor(4);
+	
+	sprintf(tx, "   chi2 = %8.2f,  Ndof = %4d,  Prob = %6.2f", 
+		fGChisq, fGNdf, fGProb);
+	pt->AddText(tx);
+	
+	sprintf(tx, "   Sigma of Gauss = %8.1f #pm %8.1f  [\\circ]", 
+		fSigmaGauss, fdSigmaGauss);
+	pt->AddText(tx);
+	
+	sprintf(tx, "   total no.of excess events = %8.1f #pm %8.1f", 
+		fNexGauss, fdNexGauss);
+	pt->AddText(tx);
+      }
+    //--------------
+    
+    pt->SetFillStyle(0);
+    pt->SetBorderSize(0);
+    pt->SetTextAlign(12);
+    
+    
+    if(fPrintResultsOntoAlphaPlot)
+      {
+	pt->Draw();
+      }
+    fCanvas->Modified();
+    fCanvas->Update();
+    
+    //    fPsFilename -> NewPage();
+
+
+
+    if (fSavePlots)
+    {
+	// ********************************************
+	// TMP solution while the TPostScript thing is not working. 
+	// PsFileName for storing these histograms is derived 
+	// from fPsFilenameString. 
+	
+	
+	cout << "Alpha plot with ON-OFF data will be saved in PostScript file  " ;
+	
+	
+	if (!fPsFilenameString.IsNull())
+	{
+	    TString filename  = (fPsFilenameString);
+	    TString filename2 = (fPsFilenameString);
+	    // Train or Test Sample is specified outside 
+	    // class MHFindSignificanceONOFF, and included in 
+	    // fPsFilenameString
+	    
+	    filename  += ("AlphaPlot.ps");
+	    filename2 += ("AlphaPlot.C");
+	    cout << filename << endl;	
+	    fCanvas -> SaveAs(filename);
+	    fCanvas -> SaveAs(filename2);
+	}
+	
+	// END OF TEMPORAL SOLUTION
+	// ********************************************
+	
+    }
+    
+    // Canvvas deleted to allow for GRID analysis
+
+    delete fCanvas;
+	
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Print the results of the polynomial fit to the alpha OFF distribution
+// 
+//
+void MHFindSignificanceONOFF::PrintPolyOFF(Option_t *o) 
+{
+  *fLog << "---------------------------" << endl;
+  *fLog << "MHFindSignificanceONOFF::PrintPolyOFF :" << endl; 
+
+  *fLog << "fAlphaminOFF, fAlphamaxOFF, fDegreeOFF "
+        << fAlphaminOFF << ",  " << fAlphamaxOFF << ",  " << fDegreeOFF <<  endl;
+
+  *fLog << "fMbinsOFF, fNzeroOFF, fIstatOFF = " << fMbinsOFF << ",  "
+        << fNzeroOFF << ",  " << fIstatOFF << endl;
+
+  *fLog << "fChisqOFF, fNdfOFF, fProbOFF = " << fChisqOFF << ",  " 
+        << fNdfOFF << ",  " << fProbOFF << endl; 
+
+  *fLog << "fNon; fNoffSigFitted, fdNoffSigFitted; fNoffSig, fdNoffSig = "
+        << fNon << ";  " << fNoffSigFitted << ",  " << fdNoffSigFitted 
+	<< ";  " << fNoffSig << ",  " << fdNoffSig <<  endl;
+
+  Double_t sigtoback = fNoffSigFitted >0.0 ? fNexONOFFFitted/(fNoffSigFitted*fNormFactor) : 0.0;
+
+  
+  *fLog << "fNexONOFFFitted, fdNexONOFFFitted, fGamma, fNoff, fSigLiMa, sigtoback = "
+        << fNexONOFFFitted << ",  " << fdNexONOFFFitted << ",  " 
+	<< fGamma << ",  " << fNoff 
+        << ",  " << fSigLiMa << ",  "
+	<< sigtoback << endl;
+
+
+  Double_t sigtoback2 = fNoffSig >0.0 ? fNexONOFF/(fNoffSig*fNormFactor) : 0.0;
+  
+  *fLog << "fNexONOFF, fdNexONOFF, fNormFactor, fNoffSig, fSigLiMa2, sigtoback2 = "
+        << fNexONOFF << ",  " << fdNexONOFF << ",  " 
+	<< fNormFactor << ",  " << fNoffSig 
+        << ",  " << fSigLiMa2 << ",  "
+	<< sigtoback2 << endl;
+
+ *fLog << "---------------------------" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the results of the polynomial fit to the alpha distribution
+// 
+//
+void MHFindSignificanceONOFF::PrintPoly(Option_t *o) 
+{
+  *fLog << "---------------------------" << endl;
+  *fLog << "MHFindSignificanceONOFF::PrintPoly :" << endl; 
+
+  *fLog << "fAlphami, fAlphama, fDegree, fAlphasi = "
+        << fAlphami << ",  " << fAlphama << ",  " << fDegree << ",  " 
+        << fAlphasi << endl;
+
+  *fLog << "fMbins, fNzero, fIstat = " << fMbins << ",  "
+        << fNzero << ",  " << fIstat << endl;
+
+  *fLog << "fChisq, fNdf, fProb = " << fChisq << ",  " 
+        << fNdf << ",  " << fProb << endl; 
+
+  *fLog << "fNon, fNbg, fdNbg, fNbgtot, fNbgtotFitted, fdNbgtotFitted = "
+        << fNon << ",  " << fNbg << ",  " << fdNbg << ",  " << fNbgtot 
+        << ",  " << fNbgtotFitted << ",  " << fdNbgtotFitted << endl;
+
+  Double_t sigtoback = fNbg>0.0 ? fNex/fNbg : 0.0;
+  *fLog << "fNex, fdNex, fGamma, fNoff, fSigLiMa, sigtoback = "
+        << fNex << ",  " << fdNex << ",  " << fGamma << ",  " << fNoff 
+        << ",  " << fSigLiMa << ",  " << sigtoback << endl;
+
+  //------------------------------------
+  // get errors
+
+  /*
+  Double_t eplus; 
+  Double_t eminus; 
+  Double_t eparab; 
+  Double_t gcc;
+  Double_t errdiag;
+
+
+  if ( !fConstantBackg )
+  {
+    *fLog << "parameter value     error     eplus     eminus    eparab   errdiag   gcc"
+          << endl; 
+
+    for (Int_t j=0; j<=fDegree; j++)
+    {
+      if (gMinuit)
+        gMinuit->mnerrs(j, eplus, eminus, eparab, gcc);
+      errdiag = sqrt(fEma[j][j]);
+      *fLog << j << "  " << fValues[j] << "  "   << fErrors[j] << "  "
+            << eplus     << "  "       << eminus << "  " << eparab     << "  " 
+            <<  errdiag  << "  "       << gcc    << endl;
+    }
+  }  
+  else
+  {
+    *fLog << "parameter value     error     errdiag "
+          << endl; 
+
+    for (Int_t j=0; j<=fDegree; j++)
+    {
+      errdiag = sqrt(fEma[j][j]);
+      *fLog << j << "  " << fValues[j] << "  "   << fErrors[j] << "  "
+            <<  errdiag  << endl;
+    }
+  }  
+  */
+
+  //----------------------------------------
+  /*
+  *fLog << "Covariance matrix :" << endl;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      *fLog << fEma[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "Correlation matrix :" << endl;
+  for (Int_t j=0; j<=fDegree; j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=fDegree; k++)
+    {
+      *fLog << fCorr[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+  */
+
+  *fLog << "---------------------------" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the results of the (polynomial+Gauss) fit to the alpha distribution
+// 
+//
+void MHFindSignificanceONOFF::PrintPolyGauss(Option_t *o) 
+{
+  *fLog << "---------------------------" << endl;
+  *fLog << "MHFindSignificanceONOFF::PrintPolyGauss :" << endl; 
+
+  *fLog << "fAlphalo, fAlphahi = "
+        << fAlphalo << ",  " << fAlphahi << endl;
+
+  *fLog << "fGMbins, fGNzero, fGIstat = " << fGMbins << ",  "
+        << fGNzero << ",  " << fGIstat << endl;
+
+  *fLog << "fGChisq, fGNdf, fGProb = " << fGChisq << ",  " 
+        << fGNdf << ",  " << fGProb << endl; 
+
+
+  //------------------------------------
+  // get errors
+
+  Double_t eplus; 
+  Double_t eminus; 
+  Double_t eparab; 
+  Double_t gcc;
+  Double_t errdiag;
+
+  *fLog << "parameter value     error     eplus     eminus    eparab   errdiag   gcc"
+        << endl; 
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    if (gMinuit)
+      gMinuit->mnerrs(j, eplus, eminus, eparab, gcc);
+    errdiag = sqrt(fGEma[j][j]);
+    *fLog << j << "  " << fGValues[j] << "  "   << fGErrors[j] << "  "
+          << eplus     << "  "       << eminus << "  " << eparab     << "  " 
+          <<  errdiag  << "  "       << gcc    << endl;
+  }
+
+  
+  *fLog << "Covariance matrix :" << endl;
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=(fDegree+3); k++)
+    {
+      *fLog << fGEma[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "Correlation matrix :" << endl;
+  for (Int_t j=0; j<=(fDegree+3); j++)
+  {
+    *fLog << "j = " << j << " :   ";
+    for (Int_t k=0; k<=(fDegree+3); k++)
+    {
+      *fLog << fGCorr[j][k] << "   ";
+    }
+    *fLog << endl;
+  }
+
+  *fLog << "---------------------------" << endl;
+}
+
+//============================================================================
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MHFindSignificanceONOFF.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MHFindSignificanceONOFF.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MHFindSignificanceONOFF.h	(revision 9772)
@@ -0,0 +1,400 @@
+#ifndef MARS_MHFindSignificanceONOFF
+#define MARS_MHFindSignificanceONOFF
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+#ifndef ROOT_TPostScript
+#include <TPostScript.h>
+#endif
+
+
+class TF1;
+class TH1;
+class TCanvas;
+
+class MHFindSignificanceONOFF : public MH
+{
+private:
+
+    TH1  *fHistOrig;  // original plot of |alpha| (0.0 to 90.0 degrees)
+    TH1  *fHist;      // copy of fHistOrig or rebinned histogram
+
+
+    
+   TH1  *fHistOrigOFF;  // original plot of |alpha| (0.0 to 90.0 degrees)
+   TH1  *fHistOFF;      // copy of fHistOrig or rebinned histogram
+   TH1  *fHistOFFNormalized;   //  fHistOFF normalized (contents and errors) with 
+                               //   with fNormFactor; useful when plotting OFF 
+                               //  Data together with ON data
+
+ 
+  // Postscript file where, for each theta bin,  
+   // alpha ON and OFF distributions 
+  //  after cuts (and hence, Nex and SigmaLiMa computations) will be stored
+   // This TPostScript object has to be initialized and closed finally 
+   // outside this class.
+ 
+   // NOT WORKING WELL !!!
+   
+   TPostScript* fPsFilename;
+   
+
+   TString fPsFilenameString; // Name of the file where plots will be stored while the 
+  // TPostScript option is not working 
+
+
+
+    Double_t fAlphamin;  // requested lower limit of fit range
+    Double_t fAlphammm;  // center of fit range
+    Double_t fAlphamax;  // requested lower limit of fit range
+
+    Double_t fAlphaminOFF; // requested lower limit of fit range for OFF data
+    Double_t fAlphamaxOFF;  // requested lower limit of fit range for OFF data
+
+
+    Double_t fAlphami;  // actual lower limit of fit range 
+    Double_t fAlphamm;  // actual center of fit range 
+    Double_t fAlphama;  // actual upper limit of fit range
+
+    Double_t fAlphasig; // requested signal range
+    Double_t fAlphasi;  // actual signal range
+    Double_t fAlphasiOFF;  // actual signal range for OFF data
+
+
+    Double_t fAlphalow; // requested lower edge of signal range
+    Double_t fAlphalo;  // actual lower edge of signal range
+
+    Double_t fAlphahig; // requested upper edge of background range
+    Double_t fAlphahi;  // actual upper edge of background range
+ 
+    // number of events in signal region
+    Double_t fNon;     // total number of events in signal region
+    Double_t fNbg;     // number of background events in signal region
+    Double_t fNex;     // number of excess events in signal region
+
+    Double_t fdNon;
+    Double_t fdNbg;
+    Double_t fdNex;
+
+    // number of events in background region
+    Double_t fNbgtot;  // total number of events in background region
+    Double_t fNbgtotFitted;  // fitted total no. of events in background region
+    Double_t fdNbgtotFitted; // fitted error of this number
+
+    // Variables related to OFF data. 
+    // Many variables are defined for similarity with 
+    // existing program. Many of them might be removed in future...
+
+
+    Double_t fNexONOFF;     // number of excess events (ON-OFF) 
+                            // in signal region
+    Double_t fNexONOFFFitted;     // number of excess events (ON-OFF fitted) 
+                                  // in signal region
+
+    Double_t fdNexONOFF;     // error in number of excess events (ON-OFF) 
+                            // in signal region
+    Double_t fdNexONOFFFitted;     // error in number of excess events (ON-OFF fitted) 
+                                  // in signal region
+
+
+    
+    Double_t fNoffTot;       // Total number of OFF events
+    Double_t fNoffSig;    // Number of OFF events in "signal" region 
+    Double_t fNoffBg;     // Number of OFF events in "background" region
+    
+    // errors for previous quantities
+
+    Double_t fdNoffTot;       
+    Double_t fdNoffSig;    
+    Double_t fdNoffBg;     
+
+    // Fitted quantities for OFF alpha distribution
+
+    Double_t fNoffTotFitted;       // Total number of OFF events
+    Double_t fNoffSigFitted;    // Number of OFF events in "signal" region 
+    Double_t fNoffBgFitted;     // Number of OFF events in "background" region
+    
+    // errors for previous quantities
+
+    Double_t fdNoffTotFitted;       
+    Double_t fdNoffSigFitted;    
+    Double_t fdNoffBgFitted;     
+
+    
+    // Boolean variable used to disable the usage ("serious" usage) of the 
+    // quantities computed from fits. This will be useful in those cases 
+    // where there is too few events to perform a decent fit to the 
+    // alpha histograms.
+    
+    Bool_t fUseFittedQuantities;
+
+
+
+    // Bool variable used to decide wether to print or not the results 
+    // of the fit, significance, Nex... onto the final alpha plot. 
+    // for the time being, this variable is set in the constructor. 
+    // At some point, I might make it such it can be set externally...
+
+    Bool_t fPrintResultsOntoAlphaPlot;
+
+
+    // effective number of background events
+    Double_t fNoff; // fNoff = fNoffSig * fNormFactor
+    Double_t fGamma;   // 
+    Double_t fNormFactor; // = TotalNon/TotalNoff)
+
+    Double_t fSigLiMa; // significance of gamma signal according to Li & Ma
+                       // Computed using quantities fGama and Noff
+                       // and formula (17) 
+
+
+    Double_t fSigLiMa2; // significance of gamma signal according to Li & Ma
+                        // Computed using quantities  fNormFactor and fNoffSig
+                        // and formula (17)
+
+    Double_t fSigLiMa3; // significance of gamma signal according to Li & Ma
+                        // Computed using quantities  fNormFactor and fNoffSig
+                        // and formula (5)
+
+                       
+
+
+    const static Double_t fEps = 1.e-4;  // tolerance for floating point comparisons
+
+    Bool_t fDraw;          // if true : draw plots
+    Bool_t fSavePlots;     // if true : Save plots in Psfile
+    Bool_t fFitGauss;      // if true : do the (polynomial+Gauss fit)
+    Bool_t fRebin;         // if true : allow rebinning of the alpha plot    
+    Bool_t fReduceDegree;  // if true : allow reducing of the order of the polynomial
+
+    Bool_t fConstantBackg; // if set true if background fit is not possible
+                           // due to low statistics
+
+    TCanvas  *fCanvas;
+
+    Double_t fNexGauss;    // total number of excess events 
+                           // (from fitted Gauss function)
+    Double_t fdNexGauss;   // error of the total number of excess events
+ 
+    Double_t fSigmaGauss;  // sigma of fitted Gauss function
+    Double_t fdSigmaGauss; // error of this sigma
+
+    //--------------------
+    TF1      *fPoly;   // polynomial function
+    Int_t    fFitBad;  // if != 0 fit failed
+    Int_t    fDegree;  // degree of polynomial to be fitted to the background
+    Int_t    fNdf;     // number of degrees of freedom of polynomial fit
+    Double_t fChisq;   // chi squared of polynomial fit
+    Double_t fProb;    // chi squared probability ofg polynomial fit 
+
+    TArrayD fValues;
+    TArrayD fErrors;
+
+    const static Int_t    fNdim = 6;
+    Double_t fEmat[fNdim][fNdim];
+    Double_t fEma [fNdim][fNdim];
+    Double_t fCorr[fNdim][fNdim];
+
+    Int_t  fMbins;     // number of bins in the fit range
+    Int_t  fMlow;      // number of bins in the fit range with too few entries
+    Int_t  fNzero;     // number of bins in the fit range with zero entry
+    Int_t  fIstat;
+
+    //--------------------
+
+    // Fit to OFF data
+
+    
+    TF1      *fPolyOFF;   // polynomial function for OFF data
+    
+    TF1      *fPolyOFFNormalized;  //  polynomial function for OFF data normalized with fNormFactor*(BinWidthON/BinWidthOFF)
+
+    Int_t    fFitBadOFF;  // if != 0 fit failed
+    Int_t    fDegreeOFF;  // degree of polynomial to be fitted to the background
+    Int_t    fNdfOFF;     // number of degrees of freedom of polynomial fit
+    Double_t fChisqOFF;   // chi squared of polynomial fit
+    Double_t fProbOFF;    // chi squared probability ofg polynomial fit 
+
+    TArrayD fValuesOFF;
+    TArrayD fErrorsOFF;
+    TArrayD fValuesOFFNormalized;
+    TArrayD fErrorsOFFNormalized;
+
+    const static Int_t    fNdimOFF = 6;
+    Double_t fEmatOFF[fNdim][fNdim];
+    Double_t fEmaOFF [fNdim][fNdim];
+    Double_t fCorrOFF[fNdim][fNdim];
+
+    Int_t  fMbinsOFF;     // number of bins in the fit range
+    Int_t  fMlowOFF;      // number of bins in the fit range with too few entries
+    Int_t  fNzeroOFF;     // number of bins in the fit range with zero entry
+    Int_t  fIstatOFF;
+
+
+    //--------------------
+    TF1      *fGPoly;   // (Gauss+polynomial) function
+    TF1      *fGBackg;  // polynomial part of (Gauss+polynomial) function
+    Int_t    fGFitBad;  // if != 0 fit failed
+    Int_t    fGDegree;  // degree of polynomial to be fitted to the background
+    Int_t    fGNdf;     // number of degrees of freedom of polynomial fit
+    Double_t fGChisq;   // chi squared of polynomial fit
+    Double_t fGProb;    // chi squared probability ofg polynomial fit 
+
+    TArrayD fGValues;
+    TArrayD fGErrors;
+
+    const static Int_t    fGNdim = 9;
+    Double_t fGEmat[fGNdim][fGNdim];
+    Double_t fGEma[fGNdim][fGNdim];
+    Double_t fGCorr[fGNdim][fGNdim];
+
+    Int_t  fGMbins;     // number of bins in the fit range
+    Int_t  fGNzero;     // numnber of bins in the fit range with zero entry
+    Int_t  fGIstat;
+
+    //--------------------
+
+    static const TString gsDefName;  //! Default Name
+    static const TString gsDefTitle; //! Default Title
+
+    Bool_t DetExcess(); 
+    Bool_t DetExcessONOFF(); 
+    Bool_t FitPolynomial();
+    Bool_t FitPolynomialOFF();
+    Bool_t FitGaussPoly();
+    //Bool_t FitGaussPolyONOFF();
+    Bool_t RebinHistogram(Double_t x0, Int_t nrebin);
+    Bool_t RebinHistogramOFF(Double_t x0, Int_t nrebin);
+
+ public:
+    MHFindSignificanceONOFF(const char *name=NULL, const char *title=NULL);
+    ~MHFindSignificanceONOFF();
+
+    
+    // fhistOFF is the alpha distribution of OFF data (after cuts), 
+    // BUT NOT normalized. Normalization factor is also one of the 
+    // arguments. Off alpha distribution will be normalized 
+    // at the beginning of the function FindSigmaONOFF. 
+
+    Bool_t FindSigmaONOFF(TH1 *fhistON, TH1 *fhistOFF, 
+			  Double_t NormFactor,
+			  Double_t alphamin, Double_t alphamax,
+			  Int_t degreeON,  Int_t degreeOFF, 
+			  Double_t alphasig, 
+			  Bool_t drawpoly, 
+			  Bool_t fitgauss, 
+			  Bool_t print, Bool_t saveplots, 
+			  //TPostScript* PsFile
+			  const TString psfilename);
+
+    // Set limits for the polynomial fit of the OFF data
+    // It will give the user the possibility of using, 
+    // for the OFF data substraction, a fit in the region 
+    // of interest. Might be useful in case of "pathological"  
+    // alpha distribution for the OFF data.
+
+    void SetLimitsForOFFDataFit(Double_t Low, Double_t Up)
+	{ fAlphaminOFF = Low; fAlphamaxOFF = Up;  }
+
+    void SetAlphaSig (Double_t alphasig)
+	{ fAlphasig = alphasig; }
+
+
+    void SetUseFittedQuantities (Bool_t b)
+	{fUseFittedQuantities = b;}
+	    
+
+    Bool_t SigmaLiMa(Double_t non, Double_t noff, Double_t gamma,
+                     Double_t *siglima);
+
+    Bool_t SigmaLiMaForm5(Double_t non, Double_t noff, Double_t gamma,
+			  Double_t *siglima);
+
+   
+    Bool_t SigmaVsAlphaONOFF(TH1 *fhistON, TH1 *fhistOFF,  
+			     Double_t alphamin, Double_t alphamax, 
+			     Int_t degree, Bool_t print);
+    
+
+
+    // Function that returns one of the 3 LiMa sigmas. 
+    // The returned value is the one used in the optimization 
+    // and final alpha plots. 
+    
+
+    Double_t GetSignificance();//   { return fSigLiMa; }
+
+    Bool_t GetUseFittedQuantities() {return fUseFittedQuantities;}
+
+
+
+    // Following function computes a clone of fHistOFF and normalizes 
+    // contents, errors and fPolyOFF (if exists) with the fNormFactor. 
+    // This normalized OFF hist will be used when plotting OFF data 
+    // together with ON data.
+ 
+    Bool_t ComputeHistOFFNormalized(); 
+
+
+    Bool_t DrawFit(Option_t *opt=NULL);
+
+    Bool_t DrawHistOFF();
+    Bool_t DrawHistOFFNormalized();
+
+    Float_t GetDegree()     const { return fDegree;  }
+    Float_t GetProb()       const { return fProb;    }
+    Float_t GetNdf()        const { return fNdf;     }
+    Float_t GetGamma()      const { return fGamma;   }
+    Float_t GetNon()        const { return fNon;     }
+    Float_t GetNex()        const { return fNex;     }
+    Float_t GetNbg()        const { return fNbg;     }
+    Float_t GetSigLiMa1()    const { return fSigLiMa; }
+    Float_t GetSigLiMa2()    const { return fSigLiMa2; }
+    Float_t GetSigLiMa3()    const { return fSigLiMa3; }
+       
+    Float_t GetMbins()      const { return fMbins;   }
+    Float_t GetAlphasi()    const { return fAlphasi; }
+    Float_t GetNexONOFF() const {return fNexONOFF;}
+    Float_t GetNexONOFFFitted() const {return fNexONOFFFitted;}
+    
+    
+
+    void SetRebin(Bool_t b=kTRUE);
+    void SetReduceDegree(Bool_t b=kTRUE);
+
+    void SetPsFilename (TPostScript* PsFile) {fPsFilename = PsFile;}
+
+    void PrintPoly(Option_t *opt=NULL);
+    void PrintPolyOFF(Option_t *opt=NULL);
+    void PrintPolyGauss(Option_t *opt=NULL);
+
+    ClassDef(MHFindSignificanceONOFF, 1) // Determine significance from alpha plot
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MSupercutsCalcONOFF.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MSupercutsCalcONOFF.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MSupercutsCalcONOFF.cc	(revision 9772)
@@ -0,0 +1,907 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!               David Paneque,   02/2004 <mailto:dpaneque@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MSupercutsCalcONOFF                                                     //
+//                                                                         //
+//   this class calculates the hadronness for the supercuts                //
+//   the parameters of the supercuts are taken                             //
+//                  from the container MSupercuts                       //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MSupercutsCalcONOFF.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "TFile.h"
+#include "TArrayD.h"
+
+#include "MParList.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MPointingPos.h"
+#include "MCerPhotEvt.h"
+#include "MGeomCam.h"
+#include "MHadronness.h"
+#include "MTSupercutsApplied.h"
+#include "MHMatrix.h"
+#include "MSupercuts.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSupercutsCalcONOFF);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+
+MSupercutsCalcONOFF::MSupercutsCalcONOFF(const char *hilname, 
+                                     const char *hilsrcname, 
+                                     const char *name, const char *title)
+  : fHadronnessName("MHadronness"), fSupercutsAppliedName("MSupercutsApplied"), 
+    fHilName(hilname), fHilSrcName(hilsrcname),
+    fHilExtName("MHillasExt"), fNewParName("MNewImagePar"), 
+    fSuperName("MSupercuts") 
+{
+    fName  = name  ? name  : "MSupercutsCalcONOFF";
+    fTitle = title ? title : "Class to evaluate the Supercuts";
+
+    fMatrix = NULL;
+
+    fStoreAppliedSupercuts = kFALSE; // by default, applied SC parameters are not stored
+
+    fNotUseTheta = kFALSE; // by default, theta info is used in the computation of the cuts
+
+    fUseStaticCuts = kFALSE; // by default, dynamical cuts are used
+
+
+    // Usage of DIST parameter in the parameterization of the cuts.
+    // For the time being is in the constructor. If finally it comes out 
+    // that it is important to disable the DIST parameter from the 
+    // cut parameterization I will make a function that access this 
+    // data variable from outside the class.
+    fUseDist = kTRUE;
+
+
+
+    // OFFSETS FOR THE DYNAMICAL CUTS
+    // Values of Size (photons), Dist (degrees) and Theta (degrees) 
+    // for which the value of the dynamical cut is equal to the 
+    // non dependent parameter; i.e. to the static cut. 
+    // By adjusting these offsets the user can set the value in size, 
+    // dist and theta for which the dynamical cuts will be given by 
+    // the term that DOES not depend on size, dist and theta.
+
+    // For the time being, these quantities are set in the constructor. 
+    // In future, if they show to be useful, I will make them available 
+    // as external variables.
+
+    fSizeOffset = 3000; // still in photons !
+    fDistOffset = 0.9; // degrees  
+    fThetaOffset = 20; // degrees   NOT USED FOR THE TIME BEING
+
+    
+
+
+
+
+    // Variables defining upper limits for some of the hillas params.
+    // The default values are set to conservative 
+    // values so that no gamma showers are removed
+
+    // If a cut value computed by function MSupercutsCalcONOFF::CtsMCut, 
+    // (i.e. widthlow) exceeds (larger or smaller 
+    // depending on wether is cutUP or cutLOW) one of these values
+    // (i.e. fWidthLowerLimit), such cut value is replaced by the 
+    // the corresponding Limit (i.e. widthlow = fWidthLowerLimit)
+
+
+
+    fDistUpperLimit = 1.4; // in deg
+    fLengthUpperLimit = 0.6;
+    fWidthUpperLimit = 0.4;
+
+    // Temp upper limit to get rid of triangular events
+    fLog10ConcUpperLimit = -0.35; 
+
+    fLeakage1UpperLimit = 0.25; 
+
+    fLengthOverWidthUpperLimit = 1.0;
+
+    fDistLowerLimit = 0.1;
+    fLengthLowerLimit = 0.05; // values at October 21th 2004
+    fWidthLowerLimit = 0.03;  // values at October 21th 2004
+
+    
+
+
+
+
+}
+
+// --------------------------------------------------------------------------
+//
+
+
+void MSupercutsCalcONOFF::SetStoreAppliedSupercuts(Bool_t b)
+{
+    fStoreAppliedSupercuts = b;
+    if (fStoreAppliedSupercuts)
+    {
+	*fLog << "Supercuts applied to all the individual events will be stored " 
+	      << "in a container of the class MSupercutsApplied." << endl;
+    }
+
+}
+
+
+void MSupercutsCalcONOFF::SetVariableNotUseTheta(Bool_t b)
+{
+    fNotUseTheta = b;
+    if (fNotUseTheta)
+    {
+	*fLog << "Theta variable is NOT used in the computation of the the  " 
+	      << "dynamical cuts" << endl;
+    }
+    else
+    {
+	*fLog << "Theta variable is used in the computation of the the  " 
+	      << "dynamical cuts" << endl;
+    }
+
+}
+
+
+void MSupercutsCalcONOFF::SetVariableUseStaticCuts(Bool_t b)
+{
+    fUseStaticCuts = b;
+    if (fUseStaticCuts)
+    {
+	*fLog << "Supercuts DO NOT take into account Theta, Size and Dist dependence; "
+	      << "i.e, they are STATIC CUTS." << endl;
+    }
+    else
+    {
+	*fLog << "Supercuts are computed taking into account Theta, size and Dist dependence."
+	      << "i.e., they are DYNAMICAL CUTS" << endl;
+
+    }
+
+
+
+}
+
+
+void MSupercutsCalcONOFF::SetHillasDistLengthWidthUpperLowerLimits(Double_t distup, 
+							      Double_t lengthup, 
+							      Double_t widthup, 
+							      Double_t distlow, 
+							      Double_t lengthlow, 
+							      Double_t widthlow)
+{
+  
+  fDistUpperLimit = distup;
+  fLengthUpperLimit = lengthup;
+  fWidthUpperLimit = widthup;
+
+
+  fDistLowerLimit = distlow;
+  fLengthLowerLimit = lengthlow;
+  fWidthLowerLimit = widthlow;
+
+
+  *fLog << "MSupercutsCalcONOFF::SetHillasDistLengthWidthUpperLowerLimits" << endl
+	<< "Upper limits to Hillas parameters Dist, Length and Width " 
+	<< "are set respectively to : " 
+	<<  fDistUpperLimit << ", " 
+	<< fLengthUpperLimit << ", "
+	<< fWidthUpperLimit << " (in degrees!!)" << endl
+
+	<< "Lower limits to Hillas parameters Dist, Length and Width " 
+	<< "are set respectively to : " 
+	<<  fDistLowerLimit << ", " 
+	<< fLengthLowerLimit << ", "
+	<< fWidthLowerLimit << " (in degrees!!)" << endl
+
+	<< "The Hadronnes of those images exceeding one of these limits will " 
+	<< "be set to 0.75." << endl << endl;
+
+
+} 
+
+
+// Function implementing a filter for muon induced images 
+// (Values from Keichi cuts October 18th 2004)
+
+// Function returns kTRUE if the event does NOT survive the 
+// muon filter. So kTRUE means event MUST be rejected
+
+
+Bool_t MSupercutsCalcONOFF::MuonFilter (Double_t Size, 
+					Double_t Length)
+{
+  // Parametrization for cut in length. 
+  // Event is rejected if 
+  // Log10(Length) < k1*(log10(Size)) + k2   (Size<10000photons)
+  // k1 = 0.286; k2 = -1.91 (October 18th 2004)
+
+  // Length < 0.2 deg (Size > 10000)
+
+
+  // Parametrization for cut in Length/Size 
+  // Event is rejected if
+  // log10(LenOverSize) < k3*(log10(Size)) + k4 (Size<4000photons)
+  // k3 = -0.780; k4 = -1.71
+
+
+  Double_t LengthUpperLimit = 0.0;
+  Double_t LengthOverSizeUpperLimit = 0.0;
+  
+
+  Double_t SizeUpperLimitForCutInLength = 10000; // in photons
+  Double_t SizeUpperLimitForCutInLengthOverSize = 4000; // in photons
+  
+  Double_t k1 =  0.286;
+  Double_t k2 =  -1.91;
+  Double_t k3 =  -0.78;
+  Double_t k4 =  -1.71;
+  
+
+  
+
+
+  if (Size <= SizeUpperLimitForCutInLength)
+    {
+      LengthUpperLimit = k1 * TMath::Log10(Size) + k2;
+      LengthUpperLimit = TMath::Power(10, LengthUpperLimit);
+    }
+  else
+    {
+      LengthUpperLimit = 0.2;
+    }
+
+  // Apply cut in Length
+  
+  if (Length <  LengthUpperLimit)
+	return kTRUE;
+
+
+  
+  if (Size < SizeUpperLimitForCutInLengthOverSize)
+    {
+      LengthOverSizeUpperLimit = k3 * TMath::Log10(Size) + k4;
+      LengthOverSizeUpperLimit = TMath::Power(10,  LengthOverSizeUpperLimit);
+  
+      if (Length/Size <  LengthOverSizeUpperLimit)
+	return kTRUE;
+    }
+
+
+   return kFALSE;
+
+}
+
+
+
+
+
+
+
+
+Int_t MSupercutsCalcONOFF::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    fHadronness = (MHadronness*)pList->FindCreateObj("MHadronness", fHadronnessName);
+    if (!fHadronness)
+    {
+        *fLog << err << fHadronnessName << " [MHadronness] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSuper = (MSupercuts*)pList->FindObject(fSuperName, "MSupercuts");
+    if (!fSuper)
+    {
+        *fLog << err << fSuperName << " [MSupercuts] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fStoreAppliedSupercuts)
+    {
+	
+	fSupercutsApplied = (MTSupercutsApplied*)pList->FindObject(fSupercutsAppliedName,
+								  "MTSupercutsApplied");
+	if(!fSupercutsApplied)
+	{
+	    *fLog << err << fSupercutsAppliedName 
+		  << " [MTSupercutsApplied] not found... aborting." << endl;
+	    return kFALSE;
+	}
+	
+
+    }
+
+    if (fMatrix)
+        return kTRUE;
+
+    //-----------------------------------------------------------
+    fHil = (MHillas*)pList->FindObject(fHilName, "MHillas");
+    if (!fHil)
+    {
+        *fLog << err << fHilName << " [MHillas] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject(fHilExtName, "MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << fHilExtName << " [MHillasExt] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << fHilSrcName << " [MHillasSrc] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject(fNewParName, "MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << fNewParName << " [MNewImagePar] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+   fPointPos = (MPointingPos*)pList->FindCreateObj("MPointingPos");
+   if (!fPointPos)
+   {
+       *fLog << err << "MSupercutsCalcONOFF::PreProcess; MPointingPos not found... aborting." << endl;
+       return kFALSE;
+   }
+
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculation of upper and lower limits
+//
+Double_t MSupercutsCalcONOFF::CtsMCut(const Double_t* a,  Double_t ls, Double_t ct,
+                                    Double_t ls2, Double_t dd2) const
+{
+    // define cut-function
+    //
+    //   
+    //    dNOMCOSZA   = 1.0
+    //
+    //      a: array of cut parameters
+    //     ls: log(SIZE) - log(fSizeOffset)
+    //    ls2: ls^2
+    //     ct: Cos(ZA.) - Cos(fThetaOffset)
+    //    dd2: DIST^2 - fDistOffset^2
+
+  //     lconc: log10CONC   
+
+
+    Double_t limit;
+
+    if(fUseStaticCuts)
+    { // static cuts are used
+	limit = a[0];
+    }
+    else
+    {
+	if (fNotUseTheta)
+	{ // Theta info is NOT used in the computation of the dynamical cuts
+	  // For the time being dist info will not be used
+
+	  if(fUseDist)
+	    {
+
+	     
+	      limit = a[0] + a[1] * dd2 + 
+		      ls  * (a[3] + a[4] * dd2) + 
+		      ls2 * (a[6] + a[7] * dd2);
+	      
+
+	    }
+	  else
+	    {
+	      limit =  a[0] + ls  * (a[3])+   ls2 * (a[6]);
+	    }
+
+
+	}
+	else
+	{// Theta info IS used in the computation of the dynamical cuts
+	    
+	    limit =
+		a[0] + a[1] * dd2 + a[2] * ct  +
+		ls  * (a[3] + a[4] * dd2 + a[5] * ct) +
+		ls2 * (a[6] + a[7] * dd2);
+	}
+
+    }
+
+
+
+    //*fLog << "MSupercutsCalcONOFF::CtsMCut; *a = "
+    //      << *a     << ",  " << *(a+1) << ",  " << *(a+2) << ",  "
+    //      << *(a+3) << ",  " << *(a+4) << ",  " << *(a+5) << ",  "
+    //      << *(a+6) << ",  " << *(a+7) << endl;
+
+    //*fLog << "MSupercutsCalcONOFF::CtsMCut; ls, ls2, ct, dd2, limit = " << ls
+    //      << ",  " << ls2 << ",  " << ct << ",  " << dd2 << ",  "
+    //      << limit << endl;
+
+    return limit;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MSupercutsCalcONOFF::GetVal(Int_t i) const
+{
+
+    Double_t val = (*fMatrix)[fMap[i]];
+
+
+    //*fLog << "MSupercutsCalcONOFF::GetVal; i, fMatrix, fMap, val = "
+    //    << i << ",  " << fMatrix << ",  " << fMap[i] << ",  " << val << endl;
+
+
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam::Process
+// will take the values from the matrix instead of the containers.
+//
+
+
+void MSupercutsCalcONOFF::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+    fMap[0] = fMatrix->AddColumn("MPointingPos.fZd");  //deg
+    fMap[1] = fMatrix->AddColumn("MHillas.fWidth");
+    fMap[2] = fMatrix->AddColumn("MHillas.fLength");
+    fMap[3] = fMatrix->AddColumn("MHillas.fSize");
+    fMap[4] = fMatrix->AddColumn("MHillas.fMeanX");
+    fMap[5] = fMatrix->AddColumn("MHillas.fMeanY");
+    fMap[6] = fMatrix->AddColumn("MHillasSrc.fDist");
+    fMap[7] = fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+    fMap[8] = fMatrix->AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    fMap[9] = fMatrix->AddColumn("MNewImagePar.fConc");
+    fMap[10]= fMatrix->AddColumn("MNewImagePar.fLeakage1");
+}
+
+
+// ---------------------------------------------------------------------------
+//
+// Evaluate dynamical supercuts 
+// 
+//          set hadronness to 0.25 if cuts are fullfilled
+//                            0.75 otherwise
+//
+Int_t MSupercutsCalcONOFF::Process()
+{
+  //    const Double_t kNomLogSize = 4.1;
+    const Double_t kNomCosZA   = 1.0;
+
+    //const Double_t theta   = fMatrix ? GetVal(0) : fMcEvt->GetTelescopeTheta();
+    // For the time being I do it in a way that theta must be 
+    // the value used in the row 0 of fMatrix. That means that if there is 
+    // no matrix, the program will complain (and crash). And tehn I will know 
+    // that value 0 (supposed to be fThetaOrig.Val) could not be taken.
+    const Double_t theta   = GetVal(0);
+    const Double_t width0  = fMatrix ? GetVal(1) : fHil->GetWidth();
+    const Double_t length0 = fMatrix ? GetVal(2) : fHil->GetLength();
+    const Double_t size    = fMatrix ? GetVal(3) : fHil->GetSize();
+    const Double_t meanx   = fMatrix ? GetVal(4) : fHil->GetMeanX();
+    const Double_t meany   = fMatrix ? GetVal(5) : fHil->GetMeanY();
+    const Double_t dist0   = fMatrix ? GetVal(6) : fHilSrc->GetDist();
+
+    const Double_t alpha   = fMatrix ? GetVal(7) : fHilSrc->GetAlpha();
+
+    Double_t help;
+    if (!fMatrix)
+      help = TMath::Sign(fHilExt->GetM3Long(), 
+	      		 fHilSrc->GetCosDeltaAlpha());
+    const Double_t asym0   = fMatrix ? GetVal(8) : help;
+    const Double_t conc    = fMatrix ? GetVal(9) : fNewPar->GetConc();
+    const Double_t leakage = fMatrix ? GetVal(10): fNewPar->GetLeakage1();
+
+    const Double_t newdist = dist0 * fMm2Deg;
+
+    const Double_t dist2   = meanx*meanx + meany*meany;
+    const Double_t dist    = sqrt(dist2) * fMm2Deg;
+    
+    // const Double_t dd2     = dist*dist;
+
+
+
+    // The parametrization of upper cut in CONC is just provisional. 
+    // The aim is to get rid of triangular events. 
+    // The parametrization is 
+    // Log10(Conc)Uppercut = m*(log(Size) - log(SizeOffset)) + b
+
+
+    Double_t log10conc = TMath::Log10(conc);
+
+
+    // in the parameterization of the cuts 
+    // the dist parameter used is the one computed from the source position, 
+    // and not the one computed from the camera center.
+
+    // Actually the value used in the parameterization is newdist^2, 
+    // minus the offset_in_dist^2
+    
+    const Double_t dd2     = newdist*newdist - fDistOffset*fDistOffset;
+
+
+    
+    const Double_t dmls    = log(size) - log(fSizeOffset);
+    const Double_t dmls2   = dmls * dmls;
+
+    const Double_t dmcza   = cos(theta) - kNomCosZA;
+
+    const Double_t length  = length0 * fMm2Deg;
+    const Double_t width   = width0  * fMm2Deg;
+    const Double_t asym    = asym0   * fMm2Deg;
+
+    
+    // MuuonLikeEvent is a variable which is set 
+    // to kFALSE/kTRUE by the filter cuts implemented 
+    // in MuonFilter function. If kTRUE, the event 
+    // will be rejected.
+
+// DM:
+    //Bool_t MuonLikeEvent = MuonFilter (size, length); 
+    
+    
+    // computation of the cut limits
+
+    Double_t lengthup  = CtsMCut (fSuper->GetLengthUp(), dmls, dmcza, dmls2, dd2);    
+    Double_t lengthlow = CtsMCut (fSuper->GetLengthLo(), dmls, dmcza, dmls2, dd2);
+
+    Double_t widthup   = CtsMCut (fSuper->GetWidthUp(),  dmls, dmcza, dmls2, dd2);     
+    Double_t widthlow  =  CtsMCut (fSuper->GetWidthLo(),  dmls, dmcza, dmls2, dd2);
+
+    Double_t distup   =  CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2);
+    Double_t distlow  =  CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2);
+
+    Double_t asymup   = CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2);
+    Double_t asymlow  = CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2);
+
+    Double_t log10concup   = CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2);
+    Double_t log10conclow  = CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2);
+
+    Double_t  leakageup = CtsMCut (fSuper->GetLeakage1Up(),dmls, dmcza, dmls2, dd2);
+    Double_t  leakagelow = CtsMCut (fSuper->GetLeakage1Lo(),dmls, dmcza, dmls2, dd2); 
+
+    
+    Double_t lengthoverwidth = length/width;
+
+
+    // Cut in CONC is parametrized
+
+    Double_t hadronness = 0.0;
+
+
+    // If the cut values computed before for Dist, 
+    //  Length and Width exceed the upper limits set 
+    // by the user through function 
+    // MSupercutsCalcONOFF::SetHillasDistLengthWidthUpperLowerLimits,
+    // (or the default values defined in constructor); such cut values 
+    // are replaced by the 
+    // the limit values
+
+    
+
+    if (distup > fDistUpperLimit)
+      {
+	distup = fDistUpperLimit;
+      }
+
+   
+    if (lengthup > fLengthUpperLimit)
+      {
+	lengthup = fLengthUpperLimit;
+      }
+
+    if (widthup > fWidthUpperLimit)
+      {
+	widthup = fWidthUpperLimit;
+      }
+
+    
+
+    if (distlow < fDistLowerLimit)
+      {
+	distlow = fDistLowerLimit;
+      }
+                   
+    if (lengthlow < fLengthLowerLimit)
+      {
+	lengthlow = fLengthLowerLimit;
+      }
+
+    if (widthlow < fWidthLowerLimit)
+      {            
+	widthlow = fWidthLowerLimit;
+      }
+
+    if (log10concup > fLog10ConcUpperLimit)
+      {
+	log10concup = fLog10ConcUpperLimit;
+      }
+
+    
+    if (leakageup > fLeakage1UpperLimit)
+      {
+	leakageup = fLeakage1UpperLimit;
+      }
+    
+    
+
+
+    // Upper cut in leakage 1 also implemented
+
+    if (// 
+	newdist > distup ||
+	newdist < distlow ||	    
+	length  > lengthup ||
+	length  < lengthlow ||	    
+	width   > widthup ||
+	width   < widthlow ||	    
+	leakage > leakageup ||
+	leakage < leakagelow ||
+	lengthoverwidth < fLengthOverWidthUpperLimit ||
+	//
+	//asym    < asymup &&
+	//asym    > asymlow &&
+	
+	//dist    < distup &&
+	//dist    > distlow &&
+	
+	log10conc    > log10concup 
+	// log10conc    < log10conclow 	
+	//
+	//log10conc    > log10concup ||
+	// DM MuonLikeEvent // if KTRUE, event is rejected	
+	) 
+	  
+      {hadronness = 0.75;}
+    else
+      {
+	hadronness = 0.25;
+      }
+      
+    
+    fHadronness->SetHadronness(hadronness);
+    fHadronness->SetReadyToSave();
+    
+    
+    if(fStoreAppliedSupercuts)
+    {
+
+	// TArrayD vector with the shower parameters (matching the ones 
+	// specified in function MTSupercutsApplied::CreateTreeBranches)
+	// is created and filled with this event features
+
+	// Eventually this definition might be done from outside this 
+	// class, allowing for adding removing parameters without 
+	// recompiling mars. yet for the time being, let's keep it simple.
+	
+	TArrayD ShowerParams(10);
+	ShowerParams[0] = length;
+	ShowerParams[1] = width;
+	ShowerParams[2] = dist;
+	ShowerParams[3] = newdist;
+	ShowerParams[4] = asym;
+	ShowerParams[5] = log10conc;
+	ShowerParams[6] = leakage;
+	ShowerParams[7] = theta;
+	ShowerParams[8] = size;
+	ShowerParams[9] = alpha;
+	
+	
+	// TArrayD vector with the cut parameters (matching the ones 
+	// specified in function MTSupercutsApplied::CreateTreeBranches)
+	// is created and filled with this event features
+
+	// Eventually this definition might be done from outside this 
+	// class, allowing for adding removing parameters without 
+	// recompiling mars. yet for the time being, let's keep it simple.
+	
+	
+	TArrayD SuperCutParams(13);
+	SuperCutParams[0] = lengthup;
+	SuperCutParams[1] = lengthlow;
+	SuperCutParams[2] = widthup;
+	SuperCutParams[3] = widthlow;
+	SuperCutParams[4] = distup;
+	SuperCutParams[5] = distlow;
+	SuperCutParams[6] = asymup;
+	SuperCutParams[7] = asymlow;
+	SuperCutParams[8] = log10concup;
+	SuperCutParams[9] = log10conclow;
+	SuperCutParams[10] = leakageup;
+	SuperCutParams[11] = leakagelow;
+	SuperCutParams[12] = hadronness;
+
+	// SC parameters applied to this event, as well as the 
+	// shower parameters, are stored in the branches of the
+	// TTree object of a MTSupercutsApplied object
+
+   
+	if (!fSupercutsApplied ->FillTreeBranches(SuperCutParams, ShowerParams))
+	{
+	    *fLog << "MSupercutsCalcONOFF::Process()" << endl
+		  << "Supercuts applied could not be stored in tree..."
+		  << endl;
+	    
+	    return kFALSE;
+	}
+	
+
+    }
+     
+
+
+    return kTRUE;
+
+
+    // OLD STUFF
+
+    /*
+    *fLog << "newdist, length, width, asym, dist, conc, leakage = " 
+          << newdist << ",  " << length << ",  " << width << ",  "
+          << asym    << ",  " << dist   << ",  " << conc  << ",  " << leakage
+          << endl;
+  
+    *fLog << "upper cuts in newdist, length, width, asym, dist, conc, leakage = " 
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLengthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLengthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetWidthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetWidthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLeakage1Up(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLeakage1Lo(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << endl;
+    */
+
+    /*
+    if (
+        //dist    < 1.05                                                     &&
+        //newdist < 1.05                                                     &&
+
+        newdist < CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) &&
+        newdist > CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        length  < CtsMCut (fSuper->GetLengthUp(), dmls, dmcza, dmls2, dd2) &&
+        length  > CtsMCut (fSuper->GetLengthLo(), dmls, dmcza, dmls2, dd2) &&
+
+        width   < CtsMCut (fSuper->GetWidthUp(),  dmls, dmcza, dmls2, dd2) &&
+        width   > CtsMCut (fSuper->GetWidthLo(),  dmls, dmcza, dmls2, dd2) &&
+
+        asym    < CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) &&
+        asym    > CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        dist    < CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) &&
+        dist    > CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        conc    < CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) &&
+        conc    > CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) &&
+
+        leakage < CtsMCut (fSuper->GetLeakage1Up(),dmls, dmcza, dmls2, dd2) &&
+        leakage > CtsMCut (fSuper->GetLeakage1Lo(),dmls, dmcza, dmls2, dd2)  ) 
+
+      fHadronness->SetHadronness(0.25);
+    else
+      fHadronness->SetHadronness(0.75);
+
+   
+
+    // *fLog << "SChadroness = " << fHadronness->GetHadronness() << endl;
+
+    fHadronness->SetReadyToSave();
+    */
+
+    // END OF OLD STUFF
+}
+
+/*
+Bool_t MSupercutsCalcONOFF::StoreSupercutsAppliedToThisEvent(TArrayD CutParams, 
+							   TArrayD ShowerParams)
+{
+    // SC parameters applied to this event are stored in 
+    // TTree object of MTSupercutsApplied object
+
+   
+    if (!fSupercutsApplied ->FillTreeBranches(CutParams, ShowerParams))
+    {
+	*fLog << "MSupercutsCalcONOFF::StoreSupercutsAppliedToThisEvent" << endl
+	      << "Supercuts applied could not be stored in tree..."
+	      << endl;
+
+	return kFALSE;
+    }
+
+    
+    return kTRUE;
+}
+
+*/
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MSupercutsCalcONOFF.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MSupercutsCalcONOFF.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MSupercutsCalcONOFF.h	(revision 9772)
@@ -0,0 +1,183 @@
+#ifndef MARS_MSupercutsCalcONOFF
+#define MARS_MSupercutsCalcONOFF
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MParList;
+class MHillas;
+class MHillasSrc;
+class MHillasExt;
+class MNewImagePar;
+class MPointingPos;
+class MCerPhotEvt;
+class MGeomCam;
+class MHadronness;
+class MHMatrix;
+class MSupercuts;
+class MTSupercutsApplied;
+
+class MSupercutsCalcONOFF : public MTask
+{
+private:
+    MHillas       *fHil;
+    MHillasSrc    *fHilSrc;
+    MHillasExt    *fHilExt;
+    MNewImagePar  *fNewPar;
+    MPointingPos  *fPointPos;
+    MHadronness   *fHadronness; //! output container for hadronness
+    MTSupercutsApplied *fSupercutsApplied; // output container for applied supercuts
+    MSupercuts *fSuper;      // container for supercut parameters
+
+    TString  fHadronnessName;   // name of container to store hadronness
+    TString  fSupercutsAppliedName;        // name of the container to store applied supercuts
+    TString  fHilName;
+    TString  fHilSrcName;
+    TString  fHilExtName;
+    TString  fNewParName;
+    TString  fSuperName;        // name of container for supercut parameters
+
+    Double_t fMm2Deg;           //!
+
+    Int_t     fMap[11];         //!
+    MHMatrix *fMatrix;          //!
+
+    Bool_t fStoreAppliedSupercuts; // Boolean variable used to decided wether to store (kTRUE) or not (kFALSE) the supercuts applied
+
+
+    // Boolean variable used to control decide wether to use theta information 
+    // in the computation of teh dynamical cuts.
+    Bool_t fNotUseTheta;
+
+    // Boolean variable used to decide wether to use dynamical cuts or static cuts
+    // kTRUE means that static cuts are used
+    Bool_t fUseStaticCuts;
+
+
+    // Boolean variable that allows to use/not use the dist info in the cuts parameterization
+    // kTRUE for use it.
+    // For the time being this variable is set in the constructor
+
+    Bool_t fUseDist;
+
+
+
+     // OFFSETS FOR THE DYNAMICAL CUTS
+    // Values of Size (photons), Dist (degrees) and Theta (degrees) 
+    // for which the value of the dynamical cut is equal to the 
+    // non dependent parameter; i.e. to the static cut. 
+    // By adjusting these offsets the user can set the value in size, 
+    // dist and theta for which the dynamical cuts will be given by 
+    // the term that DOES not depend on size, dist and theta.
+
+    // For the time being, these quantities are set in the constructor. 
+    // In future, if they show to be useful, I will make them available 
+    // as external variables.
+
+    Double_t fSizeOffset; // photons
+    Double_t fDistOffset; // degrees   NOT USED FOR THE TIME BEING
+    Double_t fThetaOffset; // degrees   NOT USED FOR THE TIME BEING
+
+
+
+
+    // Variables defining upper/lower limits for some of the hillas params
+    // Variables in degrees !!
+
+    Double_t fDistUpperLimit;
+    Double_t fLengthUpperLimit;
+    Double_t fWidthUpperLimit;
+
+    Double_t fLog10ConcUpperLimit;
+
+     Double_t fDistLowerLimit;
+    Double_t fLengthLowerLimit;
+    Double_t fWidthLowerLimit;
+
+    // tmp
+
+    Double_t fLeakage1UpperLimit;
+
+    Double_t fLengthOverWidthUpperLimit;
+    
+    //endtemp
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Double_t GetVal(Int_t i) const;
+
+    Double_t CtsMCut(const Double_t* a, Double_t ls, Double_t ct,
+                     Double_t ls2, Double_t dd2) const;
+    /*
+    Bool_t StoreSupercutsAppliedToThisEvent(Double_t lengthup, Double_t lengthlow, 
+					    Double_t widthup, Double_t widthlow, 
+					    Double_t distup, Double_t distlow);
+    */     
+public:
+    MSupercutsCalcONOFF(const char *hilname="MHillas",
+                      const char *hilsrcname="MHillasSrc",
+                      const char *name=NULL, const char *title=NULL);
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+    TString GetHadronnessName() const { return fHadronnessName; }
+
+    void SetSupercutsAppliedName(const TString name) { fSupercutsAppliedName = name; }
+    TString GetSupercutsAppliedName() const { return fSupercutsAppliedName; }
+
+
+    void SetStoreAppliedSupercuts(Bool_t b);
+    Bool_t GetStoreAppliedSupercuts() {return fStoreAppliedSupercuts;}
+
+
+    void SetVariableNotUseTheta(Bool_t b);
+    Bool_t GetVariableNotUseTheta() { return fNotUseTheta;}
+
+    void SetVariableUseStaticCuts(Bool_t b);
+    Bool_t GetVariableUseStaticCuts() { return fUseStaticCuts;}
+
+
+    
+    void SetHillasDistLengthWidthUpperLowerLimits(Double_t distup, 
+						  Double_t lengthup, 
+						  Double_t widthup, 
+						  Double_t distlow, 
+						  Double_t lengthlow, 
+						  Double_t widthlow);
+
+      // Function implementing a filter for muon induced images 
+// (Keichi cuts October 18th 2004)
+
+  Bool_t MuonFilter (Double_t Size, 
+		     Double_t Length);
+
+
+
+    void InitMapping(MHMatrix *mat); // use quantity ThetaOrig.fVal at theta
+    
+    void StopMapping() { InitMapping(NULL); }
+
+    
+
+
+    ClassDef(MSupercutsCalcONOFF, 0) // A class to evaluate the Supercuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MTSupercutsApplied.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MTSupercutsApplied.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MTSupercutsApplied.cc	(revision 9772)
@@ -0,0 +1,281 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): David Paneque 02/2004 <mailto:dpaneque@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTSupercutsApplied
+//
+// Class derived from TObject and containing a TTree object 
+// used to store the values of the Supercuts applied 
+// to each single event. The supercuts are dynamic, which means that 
+// the cuts depend on the characterics (size, theta, distance) of the 
+// individual events. 
+// For the time being, only Length, Width and Dist are used, yet in 
+// the future more parameters will be added (conc, asym...)
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MTSupercutsApplied.h"
+
+#include <TObject.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTSupercutsApplied);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MTSupercutsApplied::MTSupercutsApplied(const char* name, const char* title)
+{
+    fName  = name  ? name  : "MTSupercutsApplied";
+    fTitle = title ? title : "Storage container for the dynamical supercuts";
+
+
+    // TTree object is initialized with same name and titles as parent object
+    
+    fRootTree = new TTree (name, title);
+
+    fBranchesCreated = kFALSE;
+
+}
+
+// --------------------------------------------------------------------------
+//   DESTRUCTOR deletes dynamic memory allocated for TTree and vectors
+
+MTSupercutsApplied::~MTSupercutsApplied()
+{
+
+    // If I release the dynamic memory ocupied by this guys a segmentation 
+    // fault is produced. I guess this is due to the fact that tryis to 
+    // remove something which has been writtenn into a root file... 
+    // not sure...
+
+    // Anyhow, this occupies very little memory... it will not load 
+    // too much the system.
+
+    //delete fCutParameters;
+    //delete fShowerParamBranchName;
+    //delete fRootTree;
+    
+
+}
+
+
+
+
+// Function that creates the branches of the TTree object
+
+Bool_t MTSupercutsApplied::CreateTreeBranches()
+{
+
+    // Names of the branches is fixed for the time being
+    
+    fCutParamBranchName = ("SupercutsApplied");
+    fShowerParamBranchName = ("ShowerParameters");
+
+   
+    // Number of parameters for the 2 branches is set in cosntructor. 
+    // In later versions I might do it in such a way that can be set 
+    // by user
+
+    fNCutParameters = 13;
+    fNShowerParameters = 10;
+
+    
+    const Int_t dimscparam = fNCutParameters;
+    const Int_t dimshowerparam = fNShowerParameters;
+
+    fCutParameters = new Double_t [dimscparam];
+    fShowerParameters = new Double_t [dimshowerparam];
+    
+
+
+    // Cut parameters names and types for branch CutParameters
+    // will be stored in a member data TString fCutParametersNamesTypes
+    // Eventually might be set from outside the class
+
+    TString StringVector[dimscparam];
+    StringVector[0] = ("LengthUp/D");
+    StringVector[1] = ("LengthLow/D");
+    StringVector[2] = ("WidthUp/D");
+    StringVector[3] = ("WidthLow/D");
+    StringVector[4] = ("DistUp/D");
+    StringVector[5] = ("DistLow/D");
+    StringVector[6] = ("AsymUp/D");
+    StringVector[7] = ("AsymLow/D");
+    StringVector[8] = ("Log10ConcUp/D");
+    StringVector[9] = ("Log10ConcLow/D");
+    StringVector[10] = ("LeakageUp/D");
+    StringVector[11] = ("LeakageLow/D");
+    StringVector[12] = ("Hadronness/D");
+
+    fCutParametersNamesTypes = StringVector[0];
+    for (Int_t i = 1; i < dimscparam; i++)
+    {
+	fCutParametersNamesTypes += (":");
+	fCutParametersNamesTypes += StringVector[i];
+    }
+	
+
+    // Cut parameters names and types for branch CutParameters
+    // will be stored in a member data TString fShowerParametersNamesTypes
+    // Eventually might be set from outside the class
+	
+    TString StringVector2[dimshowerparam];
+
+    StringVector2[0] = ("Length/D");
+    StringVector2[1] = ("Width/D");
+    StringVector2[2] = ("Dist/D");
+    StringVector2[3] = ("NewDist/D");
+    StringVector2[4] = ("Asym/D");
+    StringVector2[5] = ("Log10Conc/D");
+    StringVector2[6] = ("Leakage/D");
+    StringVector2[7] = ("Theta/D");
+    StringVector2[8] = ("Size/D");
+    StringVector2[9] = ("Alpha/D");
+
+
+ 
+    fShowerParametersNamesTypes = StringVector2[0];
+    for (Int_t i = 1; i < dimshowerparam; i++)
+    {
+	fShowerParametersNamesTypes += (":");
+	fShowerParametersNamesTypes += StringVector2[i];
+    }
+
+
+    *fLog << "MTSupercutsApplied::CreateTreeBranches()" << endl
+	  << "Branches created are the following ones (BranchName; Parameters)" << endl
+	  << fCutParamBranchName << " ; " << fCutParametersNamesTypes << endl
+	  << fShowerParamBranchName << " ; " << fShowerParametersNamesTypes << endl;
+
+    
+    // Branches are finally created
+
+    fRootTree -> Branch(fCutParamBranchName.Data(),
+			fCutParameters, fCutParametersNamesTypes.Data());
+
+    fRootTree -> Branch(fShowerParamBranchName.Data(),
+			fShowerParameters, fShowerParametersNamesTypes.Data());
+
+    fBranchesCreated = kTRUE;
+
+
+    /*
+
+    fRootTree -> Branch("LengthUp", &fLengthUp, "LengthUp/D");
+    fRootTree -> Branch("LengthLow", &fLengthLow, "LengthLow/D");
+    fRootTree -> Branch("WidthUp", &fWidthUp, "WidthUp/D");
+    fRootTree -> Branch("Widthlow", &fWidthLow, "WidthLow/D");
+    fRootTree -> Branch("DistUp", &fDistUp, "DistUp/D");
+    fRootTree -> Branch("DistLow", &fDistLow, "DistLow/D");
+
+    */
+
+
+    *fLog << "MTSupercutsApplied::CreateTreeBranches();" << endl
+	  << "Branches created successfully in TTree object" << endl;
+
+    return kTRUE;
+    
+}
+
+Bool_t MTSupercutsApplied::FillTreeBranches(const TArrayD cutparameters, 
+					    const TArrayD showerparameters)
+{
+
+    // Check that branches have been created 
+    if(!fBranchesCreated)
+    {
+	*fLog << "MTSupercutsApplied::FillTreeBranches" << endl
+	      << "Branches for the Tree object have not been created yet..." 
+	      << "Therefore Tree can not be filled" << endl;
+	
+	return kFALSE;
+
+    }
+
+    // Check that dimensions of the argument vectors match with the
+    // dimension of the vectors whose addresses are given to the branches
+
+    if (fNCutParameters != cutparameters.GetSize()
+	|| fNShowerParameters != showerparameters.GetSize())
+    {
+	*fLog << "MTSupercutsApplied::FillTreeBranches" << endl
+	      << "Dimension of arrays used in the argument of this function " 
+	      << "do not match with the dimension of the arrays used in the branches"
+	      << endl;
+
+	return kFALSE;
+    }
+
+    // Parameters are transferred to the member data vectors 
+
+    for (Int_t i = 0; i < fNCutParameters; i++)
+    {
+	fCutParameters[i] = double (cutparameters[i]);
+    }
+
+    for (Int_t i = 0; i < fNShowerParameters; i++)
+    {
+	fShowerParameters[i] = double (showerparameters[i]);
+    }
+
+
+    // Branches are finally filled
+
+    fRootTree -> Fill();
+    
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MTSupercutsApplied.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MTSupercutsApplied.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/MTSupercutsApplied.h	(revision 9772)
@@ -0,0 +1,98 @@
+#ifndef MARS_MTSupercutsApplied
+#define MARS_MTSupercutsApplied
+//////////////////////////////////////////////////////////////////////////
+//                                                                      //
+// MTSupercutsApplied                                                      //
+//                                                                      //
+// Class containing TTree object used to store 
+// supercuts applied to all individual events                               //
+//                                                                      //
+//////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TTree
+#include <TTree.h>
+#endif
+
+class MTSupercutsApplied : public MParContainer
+{
+private:
+    
+    Int_t fNCutParameters;
+    Int_t fNShowerParameters;
+
+    Double_t* fCutParameters;
+    Double_t* fShowerParameters;
+/*
+    Double_t fLengthUp;
+    Double_t fLengthLow;
+    Double_t fWidthUp;
+    Double_t fWidthLow;
+    Double_t fDistUp;
+    Double_t fDistLow;    
+*/
+    TTree* fRootTree;
+
+    Bool_t fBranchesCreated;
+
+    TString fCutParamBranchName;
+    TString fShowerParamBranchName;
+
+    TString fCutParametersNamesTypes;
+    TString fShowerParametersNamesTypes;
+
+public:
+    MTSupercutsApplied(const char* name=NULL, const char* title=NULL);
+    ~MTSupercutsApplied();
+
+    /*
+    Double_t GetLengthUp() const { return fLengthUp; }
+    Double_t GetLengthLow() const { return fLengthLow; }
+    Double_t GetWidthUp() const { return fWidthUp; }
+    Double_t GetWidthLow() const { return fWidthLow; }
+    Double_t GetDistUp() const { return fDistUp; }
+    Double_t GetDistLow() const { return fDistLow; }
+
+
+    void     SetLengthUp(Double_t x) { fLengthUp = x; }
+    void     SetLengthLow(Double_t x) { fLengthLow = x; }
+    void     SetWidthUp(Double_t x) { fWidthUp = x; }
+    void     SetWidthLow(Double_t x) { fWidthLow = x; }
+    void     SetDistUp(Double_t x) { fDistUp = x; }
+    void     SetDistLow(Double_t x) { fDistLow = x; }
+    */
+     
+    Bool_t CreateTreeBranches();
+
+    Bool_t FillTreeBranches(TArrayD CutParamVector, 
+			    TArrayD ShowerParamVector);
+    	
+    TTree* GetTreePointer() {return fRootTree;}
+    
+
+    ClassDef(MTSupercutsApplied, 1) // Storage Container for the supercuts applied
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/Makefile	(revision 9772)
@@ -0,0 +1,57 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../../../Makefile.conf.$(OSTYPE)
+include ../../../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+CINT     = SuperCutsONOFF
+LIB      = SuperCutsONOFF.a
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../../../mbase \
+	   -I../../../mfbase \
+	   -I../../../mjobs \
+	   -I../../../mpedestal \
+	   -I../../../mbadpixels \
+	   -I../../../mfileio \
+           -I../../../mraw \
+           -I../../../manalysis \
+	   -I../../../mgui \
+	   -I../../../mgeom \
+	   -I../../../msignal \
+	   -I../../../mcalib \
+	   -I../../../mfilter \
+	   -I../../../mhbase \
+	   -I../../../mimage \
+	   -I../../../mpointing \
+	   -I../../../mcamera \
+	   -I../../../mhist \
+	   -I../../../mmc \
+	   -I../../../mreport \
+	   -I../../../mastro \
+	   -I../../../mdata 
+
+SRCFILES = \
+	MFRandomSplit.cc \
+	MSupercutsCalcONOFF.cc \
+	MHFindSignificanceONOFF.cc \
+	MTSupercutsApplied.cc \
+	MFindSupercutsONOFF.cc \
+        MFindSupercutsONOFFThetaLoop.cc 
+
+############################################################
+
+all: $(OBJS)
+
+include ../../../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/SuperCutsONOFFIncl.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/SuperCutsONOFFIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/SuperCutsONOFFIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/SuperCutsONOFFLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/SuperCutsONOFFLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/SupercutsONOFFClasses/SuperCutsONOFFLinkDef.h	(revision 9772)
@@ -0,0 +1,15 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+
+#pragma link C++ class MFRandomSplit+;
+#pragma link C++ class MSupercutsCalcONOFF+;
+#pragma link C++ class MHFindSignificanceONOFF+;
+#pragma link C++ class MTSupercutsApplied+;
+#pragma link C++ class MFindSupercutsONOFF+;
+#pragma link C++ class MFindSupercutsONOFFThetaLoop+;
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mmpi/asciifiles/OptimizedCrabFrom400phe.txt
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/asciifiles/OptimizedCrabFrom400phe.txt	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/asciifiles/OptimizedCrabFrom400phe.txt	(revision 9772)
@@ -0,0 +1,107 @@
+0.27853			0.03
+0.0838561		0.01
+0.0			0.0
+0.0681442		0.003
+0.0			0.01
+0.0			0.0
+0.027287		0.001
+0.0			0.01
+-0.280023		0.01
+-0.42577		0.01
+0.0			0.0
+0.115018		0.003
+0.0			0.001
+0.0			0.0
+0.0129962		0.001
+0.0			0.001
+0.104082		0.01
+0.0231448		0.002
+0.0			0.0
+0.0119858		0.001
+0.0			0.001
+0.0			0.0
+0.00113329		0.001
+0.0			0.001
+0.0582382		0.005
+0.0134179		0.002
+0.0			0.0
+0.0111611		0.001
+0.0			0.001
+0.0			0.0
+0.00377006		0.001
+0.0			0.001
+0.895918		0.1
+0.0			0.0
+0.0			0.0
+0.272012		0.005
+0.0			0.0
+0.0			0.0
+-0.00791171		0.001
+0.0			0.0
+0.605796		0.06
+0.0			0.0
+0.0			0.0
+0.0389163		0.006
+0.0			0.0
+0.0			0.0
+0.000165784		0.001
+0.0			0.0
+1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+.25			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+13.123440		0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/asciifiles/OptimizedMkn421DynCutsGridWithSelected22pointsMay19.txt
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/asciifiles/OptimizedMkn421DynCutsGridWithSelected22pointsMay19.txt	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/asciifiles/OptimizedMkn421DynCutsGridWithSelected22pointsMay19.txt	(revision 9772)
@@ -0,0 +1,107 @@
+0.291162		0.03
+0.0767981		0.01
+0.0			0.0
+0.0319514		0.003
+0.0			0.00
+0.0			0.0
+0.00197097		0.001
+0.0			0.00
+0.136532		0.01
+0.0672596		0.01
+0.0			0.0
+-0.00328891		0.003
+0.0			0.000
+0.0			0.0
+0.00346991		0.001
+0.0			0.0
+0.121355		0.01
+0.00941745		0.002
+0.0			0.0
+0.0130449		0.001
+0.0			0.0
+0.0			0.0
+-7.67104e-05		0.001
+0.0			0.0
+0.0553008		0.005
+0.00677071		0.002
+0.0			0.0
+0.012681		0.001
+0.0			0.000
+0.0			0.0
+0.00110842		0.001
+0.0			0.0
+1.21178			0.1
+0.0			0.0
+0.0			0.0
+0.105799		0.005
+0.0			0.0
+0.0			0.0
+0.00212262		0.001
+0.0			0.0
+0.607549		0.06
+0.0			0.0
+0.0			0.0
+0.0390365		0.006
+0.0			0.0
+0.0			0.0
+0.000148364		0.001
+0.0			0.0
+1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+.25			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+13.123440		0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/asciifiles/StartingValuesForOptimizationMkn421DynCutsOnSizeAndDist.txt
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/asciifiles/StartingValuesForOptimizationMkn421DynCutsOnSizeAndDist.txt	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/asciifiles/StartingValuesForOptimizationMkn421DynCutsOnSizeAndDist.txt	(revision 9772)
@@ -0,0 +1,107 @@
+0.32			0.03
+0.05			0.01
+0.0			0.0
+0.034			0.003
+0.0			0.01
+0.0			0.0
+0.0			0.001
+0.0			0.01
+0.12			0.01
+0.05			0.01
+0.0			0.0
+0.034			0.003
+0.0			0.001
+0.0			0.0
+0.0			0.001
+0.0			0.001
+0.12			0.01
+0.007			0.002
+0.0			0.0
+0.013			0.001
+0.0			0.001
+0.0			0.0
+0.0			0.001
+0.0			0.001
+0.055			0.005
+0.007			0.002
+0.0			0.0
+0.013			0.001
+0.0			0.001
+0.0			0.0
+0.0			0.001
+0.0			0.001
+1.25			0.1
+0.0			0.0
+0.0			0.0
+0.059			0.005
+0.0			0.0
+0.0			0.0
+0.0			0.001
+0.0			0.0
+0.60			0.06
+0.0			0.0
+0.0			0.0
+0.059			0.006
+0.0			0.0
+0.0			0.0
+0.0			0.001
+0.0			0.0
+1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+.25			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+13.123440		0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/asciifiles/StartingValuesForSmallSizes1.txt
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/asciifiles/StartingValuesForSmallSizes1.txt	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/asciifiles/StartingValuesForSmallSizes1.txt	(revision 9772)
@@ -0,0 +1,107 @@
+0.32			0.03
+0.05			0.01
+0.0			0.0
+0.034			0.003
+0.0			0.01
+0.0			0.0
+0.0			0.001
+0.0			0.01
+0.12			0.01
+0.05			0.01
+0.0			0.0
+0.034			0.003
+0.0			0.001
+0.0			0.0
+0.0			0.001
+0.0			0.001
+0.12			0.01
+0.007			0.002
+0.0			0.0
+0.013			0.001
+0.0			0.001
+0.0			0.0
+0.0			0.001
+0.0			0.001
+0.055			0.005
+0.007			0.002
+0.0			0.0
+0.013			0.001
+0.0			0.001
+0.0			0.0
+0.0			0.001
+0.0			0.001
+1.25			0.1
+0.0			0.0
+0.0			0.0
+0.059			0.005
+0.0			0.0
+0.0			0.0
+0.0			0.001
+0.0			0.0
+0.60			0.06
+0.0			0.0
+0.0			0.0
+0.059			0.006
+0.0			0.0
+0.0			0.0
+0.0			0.001
+0.0			0.0
+1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+.25			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+-1.e10			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+13.123440		0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+0.0			0.0
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/hit.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/hit.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/hit.cc	(revision 9772)
@@ -0,0 +1,801 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TGClient.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include "MHMatrix.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MWriteRootFile.h"
+#include "MReadMarsFile.h"
+#include "MReadReports.h"
+#include "MApplySupercuts.h"
+#include "MHFindSignificance.h"
+#include "MEvtLoop.h"
+#include "MProgressBar.h"
+#include "MContinue.h"
+#include "MGeomApply.h"
+#include "MHadronness.h"
+#include "MFilterList.h"
+#include "MF.h"
+#include "MFindSupercutsONOFFThetaLoop.h"
+#include "MRanForestFill.h"
+
+#include "MArgs.h"
+#include "MArray.h"
+#include "MDirIter.h"
+
+#include "MStatusDisplay.h"
+
+#include "MSequence.h"
+#include "MJStar.h"
+#include "MH3.h"
+#include "MRFEnergyEst.h"
+
+#include "MRanForestCalc.h"
+#include "MTaskInteractive.h"
+#include "MHillas.h"
+//#include "MFHadAlpha.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MPrint.h"
+
+using namespace std;
+
+
+Int_t PreProcess(MParList *plist);
+Int_t Process();
+
+static void StartUpMessage()
+{
+  gLog << all << endl;
+
+  //                1         2         3         4         5         6
+  //       123456789012345678901234567890123456789012345678901234567890
+  gLog << "========================================================" << endl;
+  gLog << "                   Melibea - MARS V" << MARSVER              << endl;
+  gLog << "         MARS -- Supercuts Hillas Image Treatment"        << endl;
+  gLog << "               Compiled on <" << __DATE__ << ">"          << endl;
+  gLog << "                  Using ROOT v" << ROOTVER                << endl;
+  gLog << "========================================================" << endl;
+  
+  gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+
+
+}
+
+int main(int argc, char **argv)
+{
+  StartUpMessage();
+  
+  //
+  // Evaluate arguments
+  //
+  MArgs arg(argc, argv, kTRUE);
+  
+  if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+    return 0;
+  
+  if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+      Usage();
+      return -1;
+    }
+  
+  gLog.Setup(arg);
+
+  const Bool_t  kOptimize   = arg.HasOnlyAndRemove("--optimize");
+  const Bool_t  kSupercuts  = arg.HasOnlyAndRemove("--supercuts");
+  const Bool_t  kOverwrite  = arg.HasOnlyAndRemove("-f");
+  const Bool_t  kPrintSeq   = arg.HasOnlyAndRemove("--print-seq");
+  const Bool_t  kBatch      = arg.HasOnlyAndRemove("-b");
+  const Bool_t  kPlot       = arg.HasOnlyAndRemove("-p");
+  const Bool_t  kMc         = arg.HasOnlyAndRemove("--mc");
+  const Bool_t  kUseSeq     = !arg.HasOnlyAndRemove("--nouseseq");
+
+  // Variable that decides whether the optimized cuts are used 
+  // in the test sample.
+  const Bool_t TestParams   = !arg.HasOnlyAndRemove("--opttest");  
+  const Bool_t CombineCosThetaBinsForTrainSample = arg.HasOnlyAndRemove("--combcosthtrain"); 
+  const Bool_t CombineCosThetaBinsForTestSample = arg.HasOnlyAndRemove("--combcosthtest"); 
+  const Double_t whichfractiontrain = arg.GetFloatAndRemove("--ontrainfrac=",0.5);
+  const Double_t whichfractiontest = arg.GetFloatAndRemove("--ontestfrac=",0.5);
+  const Double_t whichfractiontrainOFF = arg.GetFloatAndRemove("--offtrainfrac=",0.5);
+  const Double_t whichfractiontestOFF = arg.GetFloatAndRemove("--offtestfrac=",0.5);
+  const Double_t gammaeff = arg.GetFloatAndRemove("--geff=",0.6);
+  const Double_t alphasig = arg.GetFloatAndRemove("--alphasig=",6);
+  const Double_t alphabkgmin = arg.GetFloatAndRemove("--alphabgmin=",20);
+  const Double_t alphabkgmax = arg.GetFloatAndRemove("--alphabgmax=",80);
+  const Double_t SizeLow = arg.GetFloatAndRemove("--sizelow=",60);
+  const Double_t SizeUp = arg.GetFloatAndRemove("--sizeup=",1000000);
+  const Double_t LeakageMax = arg.GetFloatAndRemove("--leakagemax=",0.25);
+  const Double_t DistMax = arg.GetFloatAndRemove("--distmax=",1.0);
+  const Double_t DistMin = arg.GetFloatAndRemove("--distmin=",0.2);
+  const Double_t fThetaMax = arg.GetFloatAndRemove("--zdmax=",30.);
+  const Double_t fThetaMin = arg.GetFloatAndRemove("--zdmin=",0.);
+  const Int_t NAlphaBins = arg.GetIntAndRemove("--nalphabin=",30);
+  const Double_t AlphaBinLow = arg.GetFloatAndRemove("--alphabinlow=",0);
+  const Double_t AlphaBinUp = arg.GetFloatAndRemove("--alphabinup=",90);
+  const Bool_t NormFactorFromAlphaBkg = !arg.HasOnlyAndRemove("--normbgmeth");
+  const Bool_t UseFittedQuantities = !arg.HasOnlyAndRemove("--usefittedq");
+  const Bool_t NotUseTheta = !arg.HasOnlyAndRemove("--notuseth");
+  const Bool_t UseStaticCuts = !arg.HasOnlyAndRemove("--staticcuts");
+  const Bool_t ReadInitParamsFromAsciiFile = !arg.HasOnlyAndRemove("--ascii");
+  const Bool_t kPrintFiles = !arg.HasOnlyAndRemove("--printseq");
+  const Int_t NInitSCPar = arg.GetIntAndRemove("--ninitscpar=",104);
+  const Int_t degree    = arg.GetIntAndRemove("--degree=",2);
+  const TString InitSCParamAsciiFile = arg.GetStringAndRemove("--inscparascii=","mtemp/mmpi/asciifiles/StartingValuesForSmallSizes1.txt");
+  const TString ONDataFilename = arg.GetStringAndRemove("--inondataopt=","./*CrabNebula*.root");
+  const TString OFFDataFilename = arg.GetStringAndRemove("--inoffdataopt=","./*OffCrab*.root");
+  const TString PathForFiles = arg.GetStringAndRemove("--outopt=","./");
+
+  const TString kInpath     = arg.GetStringAndRemove("--ind=", "");
+  const TString kOutpath    = arg.GetStringAndRemove("--out=", "");
+  const TString kSCfile     = arg.GetStringAndRemove("--scf=", "");
+  const TString kSource     = arg.GetStringAndRemove("--src=", "");
+  const TString kDate       = arg.GetStringAndRemove("--date=", "");
+  const TString kRFTreeFile = arg.GetStringAndRemove("--rftree=", "");
+  const Double_t kAlphaMin  = arg.GetFloatAndRemove("--alphamin=",-1);
+  const Double_t kAlphaMax  = arg.GetFloatAndRemove("--alphamax=",-1);
+  const Double_t kAlphaSig  = arg.GetFloatAndRemove("--alphasignal=",-1);
+  const Int_t    kDegree    = arg.GetIntAndRemove("--poldeg=",-1);
+  const Int_t    kNumTrees  = arg.GetIntAndRemove("--ntrees=",100);
+
+
+  if (arg.GetNumOptions()>0)
+    {
+      gLog << warn << "WARNING - Unknown commandline options..." << endl;
+      arg.Print("options");
+      gLog << endl;
+      return -1;
+    }
+  
+  if (arg.GetNumArguments()!=1)
+    {
+      Usage();
+      return -1;
+    }
+  //
+  // Setup sequence file and check for its existance
+  //
+  const TString kSequence = arg.GetArgumentStr(0);
+  
+  if (gSystem->AccessPathName(kSequence, kFileExists))
+    {
+      gLog << err << "Sorry, sequence file '" << kSequence << "' doesn't exist." << endl;
+      return -1;
+    }
+  
+  //
+  // Setup sequence and check its validity
+  //
+  MSequence seq(kSequence);
+  if (kPrintSeq)
+    {
+      gLog << all;
+      gLog.Separator(kSequence);
+      seq.Print();
+      gLog << endl;
+    }
+  if (!seq.IsValid())
+    {
+      gLog << err << "Sequence read but not valid!" << endl << endl;
+      return -1;
+    }
+  
+  //
+  // Process print options
+  //
+
+  MDirIter iter;
+
+  if(kUseSeq) {
+    gLog << inf;
+    gLog << "Calculate image parameters from sequence ";
+    gLog << seq.GetName() << endl;
+    gLog << endl;
+
+
+    const Int_t n0 = seq.SetupDatRuns(iter, kInpath, "I");
+    const Int_t n1 = seq.GetNumDatRuns();
+
+    if (n0==0)
+    {
+        gLog << err << "ERROR - No input files of sequence found!" << endl;
+        return kFALSE;
+    }
+    if (n0!=n1)
+    {
+        gLog << err << "ERROR - Number of files found (" << n0 << ") doesn't match number of files in sequence (" << n1 << ")" << endl;
+        return kFALSE;
+    }
+
+   }
+
+
+
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("Star", &argc, argv);
+    if (!gROOT->IsBatch() && !gClient || gROOT->IsBatch() && !kBatch)
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+    
+
+    // **************************************************** //
+    //           Setup flags for optimization               //
+    // **************************************************** //
+    
+    
+    // Name of the root file where alpha distributions, TTree objects
+    // with info about the events and cuts applied and  info support histograms 
+    // will be stored. 
+    // Write only the name of the file. The Path 
+    // is the one defined previously
+    
+    TString RootFilename = kOutpath + "RootFileDynCuts.root";
+    TString ONFiles = ONDataFilename + "*_I_*.root";
+    TString OFFFiles = OFFDataFilename + "*_I_*.root";
+    // Vector containing the theta bins in which data (ON/OFF train/test)
+    // will be divided. Actually this vector contains the cosinus of 
+    // these theta bins. The dimension of the vector is N+1, where 
+    // N is the number of theta bins intended. The first component of the 
+    // vector is the low bin edge of the first bin, and the last 
+    // vector component the upper bin edge of the last bin.
+    
+    TArrayD CosThetaRangeVector(2);
+    CosThetaRangeVector[1] = 0.866;  //30
+    CosThetaRangeVector[0] = 0.5;  // 60
+    
+    // Object of MCT1FindSupercutsONOFFThetaLoop created, data that was specified 
+    // above is introduced and ... and the party starts.
+    
+    MFindSupercutsONOFFThetaLoop FindSupercuts("MFindSupercutsONOFFThetaLoop", 
+					       "Optimizer for the supercuts");
+    
+    
+    // ****************************************************** //
+    //        Calculate and/or apply dynamical cuts           //
+    // ****************************************************** //
+    
+    // Hillas data file
+    //TString datafile = kInpath + "*_I_CrabNebula_E.root";
+    
+    TString datafile;
+    if (kUseSeq)
+       datafile = kInpath + kDate + "*_I_" + kSource + "*.root";
+    else
+       datafile = kInpath + "*" + kSource + "*.root";
+
+     MReadMarsFile read("Events");
+     read.DisableAutoScheme(); 
+     if (kUseSeq)
+        read.AddFiles(iter);
+     else
+        read.AddFile(datafile);
+
+     cout << " datafile is : " << datafile << endl;
+
+     MReadReports readreal;
+     readreal.AddTree("Events", "MTime.", kTRUE);
+     readreal.AddTree("Drive");
+     readreal.AddTree("EffectiveOnTime");  
+     if (kUseSeq) 
+	readreal.AddFiles(iter);        
+     else
+	readreal.AddFile(datafile); 
+
+//     readreal.AddToBranchList("MReportDrive.*");
+//     readreal.AddToBranchList("MRawEvtHeader.*");
+//     readreal.AddToBranchList("MEffectiveOnTime.*");  
+
+ 
+    MGeomApply geomapl;
+    
+    MApplySupercuts appcuts;
+    appcuts.SetSCFilename(kSCfile);
+    
+    MFilterList flist;
+    MF hadrf("MHadronness.fHadronness<0.5");
+    MF sizef("MHillas.fSize>300");
+    MF leakmax("MNewImagePar.fLeakage1<0.25");
+    MF distmax("MHillasSrc.fDist<300");
+    MF distmin("MHillasSrc.fDist>60");
+    MF widthmin("MHillas.fWidth>15");
+    MF widthmax("MHillas.fWidth<120");
+    
+    TString ThetaCutMinString ("MPointingPos.fZd>"); // new! // for magic
+    ThetaCutMinString += fThetaMin;
+    MContinue ThetaCutMin(ThetaCutMinString);
+    ThetaCutMin.SetInverted();
+
+    TString ThetaCutMaxString ("MPointingPos.fZd<"); // new! // for magic
+    ThetaCutMaxString += fThetaMax;
+    MContinue ThetaCutMax(ThetaCutMaxString);
+    ThetaCutMax.SetInverted();
+
+    MContinue cont("(MHillasSrc.fDist<300) && (MHillasSrc.fDist>60) && (MNewImagePar.fLeakage1<0.25) && (MHillas.fSize>60.)");
+    cont.SetInverted();
+
+
+    MRFEnergyEst rfs;
+    //rfs.SetFile("/datm3/data/RFEnergyEst/EForestsBeforeCutsLZA.root");
+    //rfs.SetFile("/datm3/data/RFEnergyEst/EForests19990101_10003_I_MCGamTrainHZA_E_10_5.root");
+    rfs.SetFile("/home/pcmagic16/mazin/mars/files/EForestsHZA.root");
+
+    
+    //TString outname = Form("%s{s/_I_/_Q_}", kOutpath.Data());
+    MWriteRootFile &write=*new MWriteRootFile(2,  Form("%s{s/_I_/_Q_}", kOutpath.Data()), "RECREATE");
+    // Write the Events tree
+    write.AddContainer("MHillas",       "Events");
+    write.AddContainer("MHillasExt",    "Events");
+    write.AddContainer("MHillasSrc",    "Events");
+    write.AddContainer("MImagePar",     "Events");
+    write.AddContainer("MNewImagePar",  "Events");
+    write.AddContainer("MRawEvtHeader", "Events", kFALSE);
+    write.AddContainer("MPointingPos",  "Events");
+    write.AddContainer("MHadronness","Events", kFALSE);
+    write.AddContainer("MEnergyEst","Events", kFALSE);
+
+    if(kMc)
+    {
+        // Monte Carlo
+        write.AddContainer("MMcEvt",              "Events");
+        write.AddContainer("MMcTrig",             "Events");
+        // Monte Carlo Headers
+        write.AddContainer("MMcTrigHeader",       "RunHeaders");
+        write.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+        write.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+        write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+    }
+    else
+    {
+        write.AddContainer("MTime",               "Events");
+        // Run Header
+        write.AddContainer("MRawRunHeader",       "RunHeaders");
+        write.AddContainer("MBadPixelsCam",       "RunHeaders", kFALSE);
+        write.AddContainer("MGeomCam",            "RunHeaders", kFALSE);
+        //write.AddContainer("MObservatory", "RunHeaders");
+        // Drive
+        //write.AddContainer("MSrcPosCam",   "Drive");
+        write.AddContainer("MReportDrive",        "Drive", kFALSE);
+        write.AddContainer("MTimeDrive",          "Drive", kFALSE);
+        // Effective On Time
+        write.AddContainer("MEffectiveOnTime",     "EffectiveOnTime", kFALSE);
+        write.AddContainer("MTimeEffectiveOnTime", "EffectiveOnTime", kFALSE);
+    }
+
+
+/*
+    write.AddContainer("MHillas","Events");
+    write.AddContainer("MHillasExt","Events");
+    write.AddContainer("MHillasSrc","Events");
+    write.AddContainer("MImagePar","Events");
+    write.AddContainer("MNewImagePar","Events");
+    write.AddContainer("MPointingPos","Events");
+    write.AddContainer("MRawEvtHeader","Events");
+    write.AddContainer("MTime","Events", kFALSE);
+    write.AddContainer("MHadronness","Events");
+    write.AddContainer("MEnergyEst","Events");
+    // Write the RunHeader tree
+    write.AddContainer("MRawRunHeader","RunHeaders", kFALSE);
+    write.AddContainer("MBadPixelsCam","RunHeaders",kFALSE);
+    write.AddContainer("MGeomCam","RunHeaders",kFALSE);
+    // Write the Drive tree
+    write.AddContainer("MReportDrive","Drive",kFALSE);
+    write.AddContainer("MTimeDrive","Drive",kFALSE);
+    // Write the EffectiveOnTime tree
+    write.AddContainer("MEffectiveOnTime","EffectiveOnTime",kFALSE);
+    write.AddContainer("MTimeEffectiveOnTime","EffectiveOnTime",kFALSE);
+    
+
+   write.AddContainer("MMcConfigRunHeader",  "RunHeaders", kFALSE);
+   write.AddContainer("MMcCorsikaRunHeader", "RunHeaders", kFALSE);
+   write.AddContainer("MMcFadcHeader",  "RunHeaders", kFALSE);
+   write.AddContainer("MMcTrigHeader",  "RunHeaders", kFALSE);
+   write.AddContainer("MMcEvt",        "Events", kFALSE); 
+   write.AddContainer("MMcTrig",       "Events", kFALSE);
+*/
+    cout << datafile << endl;
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    
+    MProgressBar bar;
+
+    switch(kSupercuts)
+                     {
+    case kTRUE:
+    switch(kOptimize){
+    case kTRUE:
+       //cout << ONFiles << endl;
+      FindSupercuts.SetPathForFiles(PathForFiles);
+      FindSupercuts.SetDataONOFFRootFilenames(ONFiles, OFFFiles);
+      FindSupercuts.SetFractionTrainTestOnOffEvents(whichfractiontrain, 
+						    whichfractiontest, 
+						    whichfractiontrainOFF, 
+						    whichfractiontestOFF);
+      FindSupercuts.SetGammaEfficiency(gammaeff);
+      FindSupercuts.SetAlphaSig(alphasig);
+      // Bkg alpha region is set 
+      FindSupercuts.SetAlphaBkgMin(alphabkgmin);
+      FindSupercuts.SetAlphaBkgMax(alphabkgmax);
+      // alpha bkg and signal region set in object FindSupercuts
+      // are re-checked in order to be sure that make sense
+      FindSupercuts.CheckAlphaSigBkg();
+      // Degree of the polynomials used to fit the ON OFF data is set
+      FindSupercuts.SetDegreeON(degree);
+      FindSupercuts.SetDegreeOFF(degree);
+      // binning for alpha plots is defined
+      FindSupercuts.SetAlphaPlotBinining(NAlphaBins, AlphaBinLow, AlphaBinUp);
+      // Size range is defined
+      FindSupercuts.SetSizeRange(SizeLow, SizeUp);
+      FindSupercuts.SetFilters(LeakageMax, DistMax, DistMin);
+      FindSupercuts.SetNormFactorFromAlphaBkg(NormFactorFromAlphaBkg);
+      FindSupercuts.SetUseFittedQuantities(UseFittedQuantities);
+      FindSupercuts.SetVariableUseStaticCuts(UseStaticCuts);
+      FindSupercuts.SetVariableNotUseTheta(NotUseTheta);
+      FindSupercuts.SetReadMatricesFromFile(kFALSE);// normal case kFALSE
+      FindSupercuts.SetTrainParameters(kTRUE);
+      FindSupercuts.SetSkipOptimization(kFALSE);
+      
+      FindSupercuts.SetUseInitialSCParams(kTRUE);
+      FindSupercuts.SetTestParameters(TestParams);
+      FindSupercuts.SetHadronnessName("MHadSC");
+      FindSupercuts.SetHadronnessNameOFF("MHadOFFSC");
+      FindSupercuts.SetAlphaDistributionsRootFilename (RootFilename);
+      FindSupercuts.SetCosThetaRangeVector (CosThetaRangeVector);
+
+// energy estimation from Thomas Hengstebeck
+
+      
+      // Names for all root files (matrices, alpha distributions...) are created 
+      FindSupercuts.SetALLNames();
+      
+      if(ReadInitParamsFromAsciiFile)
+	{
+	  // Initial SC Parameters and steps are retrieved from Ascii file
+	  if(!FindSupercuts.ReadSCParamsFromAsciiFile(InitSCParamAsciiFile,NInitSCPar))
+	    {
+	      cout << "Initial SC Parameters could not be read from Ascii file "
+		   << InitSCParamAsciiFile << endl
+		   << "Aborting execution of macro... " << endl;
+	      return -1;
+	    }
+	}
+      
+      // Finally loop over all theta bins defined is executed
+      if (!FindSupercuts.LoopOverThetaRanges())
+	{
+	  cout << "Function MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges()" << endl
+	       << "could not be performed" << endl;
+	}
+      
+      // Nex and Significance are computed vs alphasig
+      if (!FindSupercuts.ComputeNexSignificanceVSAlphaSig())
+	{
+	  cout << "Function MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" << endl
+	       << "could not be performed" << endl;
+	}
+    
+      // Several theta bins are combined to produced a single alpha plot (for train and test)
+      // with single Nex and significances
+      if (CombineCosThetaBinsForTrainSample || CombineCosThetaBinsForTestSample)
+	{
+	  if(!FindSupercuts.ComputeOverallSignificance(CombineCosThetaBinsForTrainSample, 
+						       CombineCosThetaBinsForTestSample))
+	    {
+	      cout << "Function MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance" << endl
+		   << "could not be performed" << endl;
+	    }
+	}
+      break;
+    case kFALSE:      
+      if(kAlphaMin!=-1)
+	appcuts.SetBGAlphaMin(kAlphaMin);
+      if(kAlphaMax!=-1)
+	appcuts.SetBGAlphaMax(kAlphaMax);
+      if(kAlphaSig!=-1)
+	appcuts.SetAlphaSig(kAlphaSig);
+      if(kDegree!=-1)
+	appcuts.SetPolDegree(kDegree);
+      if(kPlot)
+	appcuts.SetPlotON();
+      appcuts.SetPlotSizeLow(SizeLow);
+      appcuts.SetPlotSizeUp(SizeUp);
+      cout << "alphasignal=" << kAlphaSig << endl;
+      //flist.AddToList(&hadrf);
+      flist.AddToList(&leakmax);
+      flist.AddToList(&distmax);
+      flist.AddToList(&distmin);
+      flist.AddToList(&widthmin);
+      flist.AddToList(&widthmax);
+      flist.AddToList(&sizef);
+      appcuts.SetFilter(&flist);
+      //write.SetFilter(&flist);
+      
+      tlist.AddToList(kMc ? (MTask*)&read : (MTask*)&readreal);
+      cout << " is montecarlo  ? " << kMc << endl;
+
+      tlist.AddToList(&geomapl);
+      tlist.AddToList(&ThetaCutMin, "Events");
+      tlist.AddToList(&ThetaCutMax, "Events");
+      tlist.AddToList(&flist, "Events");
+      tlist.AddToList(&appcuts, "Events");
+      tlist.AddToList(&rfs, "Events");
+      tlist.AddToList(&cont, "Events");
+      
+      //tlist.AddToList(&hsigma);
+MPrint print1("MTimeDrive");
+MPrint print2("MEffectiveOnTime");
+//      tlist.AddToList(&print1, "Drive");
+//      tlist.AddToList(&print2, "EffectiveOnTime");
+
+      tlist.AddToList(&write);
+      MEvtLoop shitloop;
+      shitloop.SetParList(&plist);
+      //
+      // Start to loop over all events
+      //
+      MProgressBar bar;
+      shitloop.SetProgressBar(&bar);
+      
+      if (!shitloop.Eventloop())
+	return -1;
+      
+      /*
+	
+	if (!shitloop.PreProcess())
+	return -1;
+	
+	while (tlist.Process())
+	{
+	//MHadronness *fH = (MHadronness *)plist.FindObject("MHadronness");
+	//cout<< "Hadronness " << fH->GetHadronness() << endl;
+	}
+	
+	if (!shitloop.PostProcess())
+	return -1;
+      */ 
+      tlist.PrintStatistics();   
+
+
+      break;
+    }
+    break;
+    case kFALSE:
+      // PUT THINGS FOR THE RANDOM FOREST
+
+
+      gLog << endl;
+      gLog.Separator("Applying RF to data");
+      
+
+      //
+      // Create a empty Parameter List and an empty Task List
+      // The tasklist is identified in the eventloop by its name
+      //
+      //MParList  plist;
+      
+      //MTaskList tlist;
+      //plist.AddToList(&tlist);
+      //
+      // ---------------------------------------------------------------
+      // ---------------------------------------------------------------
+      // first event loop: the trees of the random forest are read in
+      // ---------------------------------------------------------------
+      // ---------------------------------------------------------------
+      //
+      MReadTree readrf("Tree",kRFTreeFile);
+      readrf.DisableAutoScheme();
+   
+      MRanForestFill rffill;
+      rffill.SetNumTrees(kNumTrees);
+      
+      tlist.AddToList(&readrf);
+      tlist.AddToList(&rffill);
+      
+      //
+      // Eventloop
+      //
+      MEvtLoop evtloop;
+      evtloop.SetParList(&plist);
+      evtloop.SetProgressBar(&bar);
+      
+      if (!evtloop.Eventloop())
+        return 1;
+
+
+      // ---------------------------------------------------------------
+      //
+      // Apply RF to data
+      // ---------------------------------------------------------------
+     // ---------------------------------------------------------------
+      MTaskList tlist3;
+      plist.Replace(&tlist3);
+
+      // Calc RF
+      MRanForestCalc calc;
+      
+      // Fill Hist (Only for MC file with Gammas & Hadrons mixed)
+      //MFillH fillh3a("MHHadronness");
+      //MFillH fillh3b("MHRanForest");
+
+
+    // My intercative task to apply cuts
+    //MTaskInteractive  mytask;
+    //mytask.SetPreProcess(PreProcess);
+    //mytask.SetProcess(Process);
+
+      //
+      // Hadronness cut
+      //
+//      MFHadAlpha cut;
+//      cut.SetCutType(MFHadAlpha::kHadCut );
+//      cut.SetInverted();
+//      MContinue contHad(&cut);
+
+
+
+
+    // Add to TaskList
+    tlist3.AddToList(kMc ? (MTask*)&read : (MTask*)&readreal);
+    //tlist3.AddToList(&SizeCut);
+    tlist3.AddToList(&calc);
+    tlist3.AddToList(&rfs);
+    // tlist3.AddToList(&fillh3a);
+//      tlist3.AddToList(&fillh3b);
+  
+    //tlist.AddToList(&mytask);
+    //tlist.AddToList(&contHad);
+
+
+//  tlist3.AddToList(&flist);
+  tlist3.AddToList(&ThetaCutMax);
+  tlist3.AddToList(&ThetaCutMin);
+  tlist3.AddToList(&write);
+
+
+
+
+  //
+    // Execute your analysis
+    //
+    //    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return 1;
+
+    tlist3.PrintStatistics();
+
+    //  plist.FindObject("MHRanForest")->DrawClone();
+//      plist.FindObject("MHHadronness")->DrawClone();
+
+
+
+
+// END OF PUTTING THINGS FOR THE RANDOM FOREST
+      break;
+    }
+
+//abelardo
+  ////////////////////////////////////////////////////////////////////
+  //
+  // Second event loop: simply copy the tree MMcEvtBasic in the tree
+  // "OriginalMC" from the input file to the output file:
+      delete &write;
+      if(kMc)
+      //if(0==1)
+	{
+	  MParList  plist2;
+	  MTaskList tlist2;
+
+	  plist2.AddToList(&tlist2);
+
+	  MReadMarsFile read2("OriginalMC",datafile);
+//  read2.AddFile(AnalysisFilename);
+	  read2.DisableAutoScheme();
+
+	  tlist2.AddToList(&read2);
+
+	  MWriteRootFile writeOrig(2, Form("%s{s/_I_/_Q_}", kOutpath.Data()),"UPDATE");
+	  writeOrig.AddContainer("MMcEvtBasic", "OriginalMC", kFALSE);
+
+	  tlist2.AddToList(&writeOrig);
+
+	  MEvtLoop evtloop2;
+	  bar.SetWindowName("Copying OriginalMC tree...");
+	  evtloop2.SetProgressBar(&bar);
+	  evtloop2.SetParList(&plist2);
+
+	  if (!evtloop2.Eventloop())
+	    return -1;
+
+	  tlist2.PrintStatistics();
+        }
+	// end ab
+    return 0;
+}
+
+Int_t OptimizeCuts()
+{
+  return 0;
+}
+
+
+
+
+
+
+// ---------------------------------------------------------------------
+//
+//  Interactive Task
+//
+//
+// Data members of the InteractiveTask
+MParList      *fParList;
+MTaskList     *fTaskList;
+MHadronness   *fHadronness;
+MHillas       *fHillas;
+
+
+Int_t PreProcess(MParList *plist)
+{
+    // Get parameter and tasklist, see Process
+    fParList = plist;
+    fTaskList = (MTaskList*)plist->FindObject("MTaskList");
+
+    // Search in the PreProcess for the objects
+    fHadronness = (MHadronness*)fParList->FindObject("MHadronness");
+    fHillas  = (MHillas*)fParList->FindObject("MHillas");
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------
+//
+Int_t Process()
+{
+    Float_t size = fHillas->GetSize()/0.18;  //photons!
+    Float_t had  =  fHadronness->GetHadronness();
+
+    if(size<500)
+        return kCONTINUE;
+    
+    if(size>500 && size <1000 && had>0.32)
+      return kCONTINUE;
+    
+    if(size>1000 && size <2000 && had>0.28)
+      return kCONTINUE;
+    
+    if(size>2000 && size <4000 && had>0.12)
+      return kCONTINUE;
+    
+    if(size>4000 && size <8000 && had>0.21)
+        return kCONTINUE;
+
+    if(size>8000 && had>0.49)
+        return kCONTINUE;
+
+    return kTRUE;
+}
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/MySkyPlot.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/MySkyPlot.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/MySkyPlot.C	(revision 9772)
@@ -0,0 +1,171 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cherenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Daniel Mazin, 05/2004 <mailto:mazin@imppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+// Daniel Mazin 26.09.2004  mazin@mppmu.mpg.de
+//**********************************************************
+// this macro :
+// 1)  take Hillas Parameters and produce a sky plot
+//**********************************************************
+
+gROOT->Reset();
+
+//************************************************************************
+void MySkyPlot(const char *onfile) 
+{
+
+    TString fileON  = onfile;
+
+    // name of input root file
+    TString filenamein(fileON);
+
+
+    //  set up the task list:
+    //-----------------------------------------------------------
+    MTaskList tlist;
+    MParList plist;
+
+
+    TString XPosMaxString ("MSrcPosCam.fX<0.1");
+    MContinue XPosMaxCut(XPosMaxString);
+    XPosMaxCut.SetInverted();
+
+    TString XPosMinString ("MSrcPosCam.fX>-0.1");
+    MContinue XPosMinCut(XPosMinString);
+    XPosMinCut.SetInverted();
+
+    TString YPosMaxString ("MSrcPosCam.fY<0.1");
+    MContinue YPosMaxCut(YPosMaxString);
+    YPosMaxCut.SetInverted();
+
+    TString YPosMinString ("MSrcPosCam.fY>-0.1");
+    MContinue YPosMinCut(YPosMinString);
+    YPosMinCut.SetInverted();
+
+
+
+    MSkyPlot skyplot; 
+    skyplot.SetMinDist(0.2);
+    //skyplot.ReadCuts("/local/supercuts/OptSCParametersONOFFThetaRange0_1570mRad.root");
+    //skyplot.ReadCuts("/remote/home/pc1/operator/mazin/supercuts/2004_09_13/Zd20_60all/Cuts.root");
+    //skyplot.ReadCuts("/local/supercuts/2004_09_13/OptDynCuts2000CrabNebula.root");
+    //skyplot.ReadCuts("/remote/home/pc17/operator/OnlineA/supercuts/OptDynCuts2000CrabNebula.root");
+    //skyplot.ReadCuts("/home/pcmagic04/pratik/crab_analysis/sept2k4/gt2000/RootFileDynCuts_crabsept_GREEN_15o30deg.root");
+    skyplot.ReadCuts("/home/pcmagic04/pratik/crab_analysis/sept2k4/gt2000/RootFileDynCuts_20to30deg_alldata.root");
+    skyplot.SetSkyPlot(-1.,1.,-1.,1.,0.05);
+    skyplot.SetSizeMin(2000.);
+    skyplot.SetSizeMax(1e6);
+    skyplot.SetOutputAlphaName("Crab21_UV.root");
+    skyplot.SetOutputSkyName("Crab21_UV.root");
+
+
+    MObservatory mobs;
+
+    plist.AddToList(&mobs);
+
+    // geometry is needed in  MHHillas... classes 
+    const MGeomCam *fGeom = 
+             (MGeomCam*)plist->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadReports read;
+    read.AddTree("Drive");
+//    read.AddTree("CC");
+//    read.AddTree("Events");
+    read.AddTree("Events","MTime.",kTRUE);
+ 
+    read.AddFile(filenamein);
+ 
+    read.AddToBranchList("MReportDrive.*");
+//    read.AddToBranchList("MRawEvtHeader.*");
+
+
+    //MReadMarsFile read("Events", filenamein);
+    //MReadMarsFile read(filenamein);
+    //read.DisableAutoScheme();
+
+    MGeomApply        apply;
+
+    
+
+    //*****************************
+    // entries in MParList
+    
+    plist.AddToList(&tlist);
+
+//    pliston.AddToList(&source);
+
+    //*****************************
+    // entries in MTaskList
+    
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+
+    tlist.AddToList(&XPosMaxCut);
+    tlist.AddToList(&XPosMinCut);
+
+    tlist.AddToList(&YPosMaxCut);
+    tlist.AddToList(&YPosMinCut);
+
+    tlist.AddToList(&skyplot);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetProgressBar(&bar);
+/*
+    Int_t maxevents = -1;
+    //Int_t maxevents = 1000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+*/
+    if (!evtloop.PreProcess())
+            return;
+
+    Int_t counter=0;
+    while(tlist.Process())
+    {
+      counter++;
+      if(counter%10000 == 0) cout << "events = " << counter << endl;
+//     MReportDrive * mrepdrive = (MReportDrive *)pliston.FindObject("MReportDrive");
+//     cout << "Ra " << mrepdrive->GetRa() << ", Dec " << mrepdrive->GetDec() << endl;
+//     MHillasSrc * mhs = (MHillasSrc*)pliston.FindObject("MHillasSrc");
+//     mhs->Print();
+    }
+
+    evtloop.PostProcess(); 
+ 
+    tlist.PrintStatistics(0, kTRUE);
+
+}
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/SCDynamicalSupercutsApplied.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/SCDynamicalSupercutsApplied.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/SCDynamicalSupercutsApplied.C	(revision 9772)
@@ -0,0 +1,273 @@
+// The aim of this macro is to show the cuts applied to the 
+// events that survive the g/h separation cuts + the alpha cut.
+// The macro can be modified easily to show other things...
+
+// This program reads a TTree (specified by the user) and 
+// stores the array containing the variables specified by 
+// the user into pointer to arrays. This is done through 
+// the member function TTree::Draw()
+
+// Selection rules (cuts) are allowed. In such case, only 
+// the variables of the events that pass the cuts specified are 
+// stored into the arrays. 
+
+
+// It  works with arrays of pointers 
+// and plot N quantities in the N pads of the same Canvas.
+// single strings that contain
+// the quantities to be plotted are used.
+
+// This program is an alternative to another (faster?) more 
+// professional way of getting info from a Tree.
+
+
+// As input, this macro needs a root file that is 
+// generated by the SupercutsONOFF programs, which is 
+// the root file containing the TTrees with the needed info.
+
+// The user must write
+
+// 1) Name of the root file with the info (Path included!!)
+
+// 2) Name of the output ps file produced by the macro (with path included!!)
+
+
+gROOT -> Reset();
+
+void SCDynamicalSupercutsApplied()
+{
+
+
+
+
+  char* RootFile = {"/.magic/magicserv01/scratch/Daniel/SuperCuts/Mrk421/2004_04_22/4slices_3520_nc/E800_1200_Opt_MC/RootFileDynCuts.root"};
+
+  char* OutputPsFilename = {"/.magic/magicserv01/scratch/Daniel/SuperCuts/Mrk421/2004_04_22/4slices_3520_nc/E800_1200_Opt_MC/DynamicalCutsLengthWidthDistApplied.eps"};
+  
+  
+  char* Xaxis = "log(SIZE/[photons])";
+  
+  char* YaxisVector[6] = {"LENGTH UP [\\circ]", "LENGTH LOW [\\circ]", 
+		       "WIDTH UP [\\circ]", "WIDTH LOW [\\circ]", 
+		       "DIST UP [\\circ]", "DIST LOW [\\circ]"}; 
+
+  
+  
+
+
+  
+  
+ 
+
+
+// Name of the root file that contains the Tree
+    char* TreeName = {"SupercutsAppliedTrainONThetaRange0_1570mRad"}; // Name of the Tree that contains the variables that have to plotted
+   
+
+    
+    const Int_t NQuantitiesToBePlot = 6;
+
+    // Write here the quantities to be plot
+    
+    TString QuantitiesToBePlot[NQuantitiesToBePlot] = 
+    {"SupercutsApplied.LengthUp:log10(ShowerParameters.Size)", 
+     "SupercutsApplied.LengthLow:log10(ShowerParameters.Size)", 
+     "SupercutsApplied.WidthUp:log10(ShowerParameters.Size)", 
+     "SupercutsApplied.WidthLow:log10(ShowerParameters.Size)",
+     "SupercutsApplied.DistUp:log10(ShowerParameters.Size)", 
+     "SupercutsApplied.DistLow:log10(ShowerParameters.Size)"};
+
+
+    // Write here the number of rows and columns in the ps file
+
+    const Int_t Nrows = 2;
+    const Int_t Ncolumns = 3;
+
+    // Title of Canvas.. not really important...
+
+    TString CanvasTitle = ("Dynamical cuts in Length, Width and Dist");
+
+    // 0 for not using and 1 for using Selection cut
+    Int_t UseSelectionCut = 1; 
+    // Section rule to be applied in the data to be plotted
+    char* SelectionCut = {"(SupercutsApplied.Hadronness < 0.5) && ShowerParameters.Alpha < 12"}; 
+    
+    
+
+    // Vectors where variables will be stored
+    Int_t ArrayDimension[NQuantitiesToBePlot];
+    Double_t* VarYArray[NQuantitiesToBePlot];
+    Double_t* VarXArray[NQuantitiesToBePlot];
+
+
+    
+
+    // Vector  of pointers to TFile objects and TTree objects that will be used to retrieve 
+    // requested info from root file. 
+
+    TFile* FileVector[NQuantitiesToBePlot];
+    TTree* TreeVector[NQuantitiesToBePlot];
+
+    // Vector of pointers to graph objects where quantities will be plot
+
+    TGraph* GraphVector[NQuantitiesToBePlot];
+
+
+    // Options available for plotting the histo are the following ones:
+    // "prof" -->> Profile
+    // "goff" -->> No draw variables in TTree::Draw()
+    // ""     -->> No special option is set
+
+    char* DrawingOption = {"goff"};
+
+
+    TString selection = UseSelectionCut ? SelectionCut : NULL;
+
+
+
+    // Tree is read and stored in dynamic memory pointed by pointer tree.
+    
+    //  TFile file (RootFile);
+    // TTree* tree = (TTree*) file.Get(TreeName);
+
+
+  
+
+    // Loop in which arrays are retrieved from root file and 
+    // array dimensions (with events surviving the selection)
+    // are retrieved too.
+
+    for (Int_t i = 0; i < NQuantitiesToBePlot; i++)
+      {
+
+
+	FileVector[i] = new TFile(RootFile, "READ");
+
+	TreeVector[i] = (TTree*) FileVector[i] -> Get(TreeName);
+	
+	 // Array dimension of temporal vectors where the variables 
+	// that will be plotted are stored can be modify accordingly 
+	// with the nnumber of events of the Tree
+	
+	TreeVector[i] -> SetEstimate(TreeVector[i] -> GetEntries());
+
+	// Requested info is "plotted"
+
+	TreeVector[i]  -> Draw(QuantitiesToBePlot[i].Data(), selection, DrawingOption);
+
+	
+	// Let's find out the REAL length of the vectors we want 
+	// to get from the tree (Selection rules may have removed some events)
+	
+	ArrayDimension[i] = TreeVector[i] -> GetSelectedRows();
+	
+	// Vectors are retrieved
+
+	VarYArray[i] = TreeVector[i] -> GetV1();
+	VarXArray[i] = TreeVector[i] -> GetV2();
+
+      }
+
+  
+   
+    // Silly info is displayed for testing...
+
+
+   
+    for (Int_t i = 0; i < NQuantitiesToBePlot; i++)
+      {
+	cout << "Events that passed the selection for quantity " 
+	     << QuantitiesToBePlot[i] << " : " << ArrayDimension[i] << endl;
+      }
+
+   
+    // Initialization of the graphs with the info contained in the vectors
+    // Kind of default features are set for all graphs
+
+
+     TAxis* axispointer;
+      
+     
+
+    for (Int_t i = 0; i < NQuantitiesToBePlot; i++)
+      {	
+	GraphVector[i] = new TGraph (ArrayDimension[i], VarXArray[i], VarYArray[i]);
+	
+	GraphVector[i] -> SetTitle(QuantitiesToBePlot[i].Data());
+
+	
+	GraphVector[i]->SetFillColor(19);
+	GraphVector[i]->SetMarkerColor(2);
+	GraphVector[i]->SetMarkerStyle(21);
+	GraphVector[i]->SetMarkerSize(0.5);
+
+	axispointer = GraphVector[i] -> GetXaxis();
+	axispointer -> SetTitle(Xaxis);
+	axispointer -> SetTitleOffset(1.3);
+	axispointer -> SetTitleSize(0.05);
+
+
+	axispointer =  GraphVector[i] -> GetYaxis();
+	axispointer -> SetTitle(YaxisVector[i]);
+	axispointer -> SetTitleOffset(1.5);
+	axispointer -> SetTitleSize(0.05);
+	
+
+      }
+
+
+
+   
+    /*
+    // Let's output some of their components:
+    
+    for ( Int_t i = 0; i < ArrayDimension[]0; i++)
+    {
+	cout << VarXArray[0][i] << "  " <<  VarYArray[0][i] << endl;
+
+    }
+    */
+
+    
+    // TCanvas is defined with the NQuantitiesToBePlot Pads where the graphs 
+    // will be plotted
+
+    TCanvas* Canvas = new TCanvas(CanvasTitle, CanvasTitle, 600, 800);
+    Canvas -> SetBorderMode(0);
+    Canvas -> Divide(Nrows, Ncolumns);
+    
+    
+    // gStyle -> SetFrameFillColor(10);
+    gStyle -> SetPadLeftMargin (0.15);
+    gStyle -> SetPadRightMargin (0.05);
+    gStyle -> SetPadTopMargin (0.00);
+    gStyle -> SetPadBottomMargin (0.20);
+    
+    gStyle -> SetOptTitle(0);
+
+    // Graphs are plot in canvas
+    
+    for (Int_t i = 0; i < NQuantitiesToBePlot; i++)
+      {	
+	Canvas -> cd(i+1);
+	gPad -> SetBorderMode(0);
+	gPad->SetGridx();
+	gPad->SetGridy(); 
+	//gPad -> SetPadTopMargin (0.05);
+	//gPad -> SetPadBottomMargin (0.15);
+	
+	GraphVector[i] -> Draw("AP");
+      }
+    
+    
+
+    Canvas -> SaveAs(OutputPsFilename);
+
+
+}
+    
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/SCNexSignificanceVSAlphaCut.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/SCNexSignificanceVSAlphaCut.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/SCNexSignificanceVSAlphaCut.C	(revision 9772)
@@ -0,0 +1,466 @@
+// This program produces a ps file with 
+// two graphs in the same TPad, but 
+// with different axis. 
+
+// The aim is to plot Nex and significance vs 
+// cut in alpha parameter.
+
+// As input, this macro needs a root file that is 
+// generated by the SupercutsONOFF programs.
+
+// It will read the histograms where Nex and significance 
+// vs alpha are stored and will plot this info in a single 
+// ps file. 
+
+// The user must write
+
+// 1) Name of the root file with the info (Path included!!)
+
+// 2) Name of the output ps file (with path included!!)
+
+// Depending on the values to be plotted the axis scale
+// as well as the axis offsets for labels might have to be 
+// modified. If I have time I will modify the program to 
+// make it automatic...
+
+
+
+
+#include <string.h>
+#include <iostream.h>
+#include <fstream.h>
+#include <iomanip.h>
+#include <stdlib.h>
+#include <math.h>
+
+
+gROOT -> Reset();
+
+void SCNexSignificanceVSAlphaCut() 
+{
+
+  
+  
+  char* SCRootFile = {"/.magic/magicserv01/scratch/Daniel/SuperCuts/Mrk421/2004_04_22/4slices_3520_nc/E800_1200_Opt/RootFileDynCuts.root"};
+
+  char* output_ps_file = {"/.magic/magicserv01/scratch/Daniel/SuperCuts/Mrk421/2004_04_22/4slices_3520_nc/E800_1200_Opt/NexSignificanceVSCutinAlpha.ps"};
+
+  
+ 
+  char* ps_title = 
+    {"Excess events (green) and significance (red) vs cut in alpha"};
+
+
+
+
+  // Name of the histograms (contained in root file) that contain the number of 
+  // excess events and significance vs alpha cut
+
+  TString ExcessEventsHistoName = ("NexVSAlphaTrainThetaRange0_1570mRad");
+  TString SignificanceHistoName = ("SignificanceVSAlphaTrainThetaRange0_1570mRad");
+
+
+  // Axis titles
+
+  char* xaxis_title = "Cut in alpha (degrees)";
+  char* yaxis_title = "Excess events";
+  char* yaxis_2_title = "Significance";
+
+  // Axis for plot
+
+  const Double_t pad_xlow = 0;
+  const Double_t pad_ylow = 0;
+  const Double_t pad_xup = 30;
+  const Double_t pad_yup = 1000;
+
+  
+  
+  
+  // Axis labels offsets for plot
+ 
+  const Double_t xaxis_label_xoffset_pad = 8;
+  const Double_t xaxis_label_yoffset_pad = -300;
+  const Double_t yaxis_label_xoffset_pad = -5;
+  const Double_t yaxis_label_yoffset_pad = 1200;
+  const Double_t yaxis_2_label_xoffset_pad = 35;
+  const Double_t yaxis_2_label_yoffset_pad = 1200;
+
+ 
+
+  // Vector of pointer to histograms that will be plotted
+  // Colors and marker types are also defined 
+
+
+  const Int_t n_graphs = 2; 
+  TGraph* graph_vector [n_graphs];
+  Int_t graph_colors_vector[n_graphs] = {3,2};
+  Int_t polimarker_style_vector[n_graphs] = {21,25};
+  char* additional_info_vector[n_graphs] = 
+    {"Excess events", "Significance"};
+
+
+
+  // TMP VARIABLES
+
+  Int_t tmp_int = 0;
+
+  TH1F* histo1;
+  TH1F* histo2;
+
+
+ 
+  Double_t y_axis_2_min_value = 0.0;
+  Double_t y_axis_2_max_value = 0.0;
+  
+  Double_t graph_y_minmax_vector [n_graphs][2];
+  // It contains y values min and max for graphs that 
+  // are plotted.
+  
+  Double_t graph_2_scale_factor = 0.0;
+
+  // ******************************************************************
+  // Data is read from the histograms contained in the input root file 
+  // and stored in vectors 
+  // ******************************************************************
+  
+  TFile rootfile (SCRootFile, "READ");
+
+  histo1 = (TH1F*) rootfile.Get(ExcessEventsHistoName);
+  histo2 = (TH1F*) rootfile.Get(SignificanceHistoName);
+
+  
+
+  // check that dimension is the same 
+
+  if (histo1 -> GetNbinsX() != histo2 -> GetNbinsX())
+    {
+      cout << "Dimension of histogram " << ExcessEventsHistoName 
+	   << " is not equal to dimension of histogram "<< SignificanceHistoName << endl
+	   << "Aborting ..." << endl;
+      
+      Exit(1);
+    }
+
+  
+  tmp_int = histo1 -> GetNbinsX();
+  
+  const Int_t vectors_dimension = tmp_int;
+
+
+  // Vectors that will be used to plot graphs are defined and filled
+
+  Double_t alpha_cut_vector[vectors_dimension] = {0.0};
+  Double_t excess_events_vector[vectors_dimension] = {0.0};
+  Double_t significance_vector[vectors_dimension] = {0.0};
+
+
+  for (Int_t i = 0 ; i < vectors_dimension; i++)
+    {
+      alpha_cut_vector[i] =  histo1-> GetBinCenter(i+1) + ((histo1->GetBinWidth(i+1))/2);
+      excess_events_vector[i] = histo1-> GetBinContent(i+1);
+      significance_vector[i] = histo2-> GetBinContent(i+1);
+    }
+
+  
+  
+
+   // Dynamic memory from is released and root file closed 
+
+  delete histo1;
+  delete histo2;
+
+  rootfile.Close();
+
+
+    // Information retrieved from histos is displayed in terminal
+  
+  cout << endl
+       << "Cut in alpha, excess events and significance values retrieved from root file: "
+       << endl;
+
+  for (Int_t i = 0 ; i < vectors_dimension; i++)
+    {
+      cout << alpha_cut_vector[i] << "        " 
+	   << excess_events_vector[i] << "        " 
+	   << significance_vector[i] << endl;
+    }
+  
+
+
+
+
+
+  //******************************************************
+  // Graph 2 is scaled so that it can be plotted in the 
+  // same TPad... kind of a trick in root.
+
+  // First, values min and max are needed for the 
+  // graphs to be plotted.
+
+  graph_y_minmax_vector [0][0] = pad_ylow;
+  graph_y_minmax_vector [0][1] = find_max (excess_events_vector, 
+					   vectors_dimension);
+    
+cout << " min set to : " <<  graph_y_minmax_vector [0][0] << endl;
+cout << " max set to : " <<  graph_y_minmax_vector [0][1] << endl;
+
+  graph_y_minmax_vector [1][0] = 0;
+					
+  graph_y_minmax_vector [1][1] = find_max (significance_vector, 
+					   vectors_dimension);
+  //TEST
+  /*
+  cout << graph_y_minmax_vector [0][1] << "  "  
+       << graph_y_minmax_vector [0][0] << endl;
+
+   cout << graph_y_minmax_vector [1][1] << "  "  
+       << graph_y_minmax_vector [1][0] << endl;
+   */
+
+
+   
+  graph_2_scale_factor = 
+    (graph_y_minmax_vector [0][1] - 
+     graph_y_minmax_vector [0][0])/(graph_y_minmax_vector [1][1] 
+				    - graph_y_minmax_vector [1][0]);
+
+  //  cout << "scale factor :  " << graph_2_scale_factor << endl;
+
+  for (Int_t i = 0 ; i < vectors_dimension; i++)
+    { 
+      
+      significance_vector[i] = ((graph_2_scale_factor * significance_vector[i])
+			   + graph_y_minmax_vector [0][0]);
+    }
+  
+  // ***********  END OF SCALING   ********************************
+
+  // Graphs are initialized and filled with vectors
+
+   
+  // Graph i initialized and filled 
+  graph_vector[0] = new TGraph(vectors_dimension,
+			       alpha_cut_vector, 
+			       excess_events_vector);
+      
+
+  graph_vector[1] = new TGraph(vectors_dimension,
+			       alpha_cut_vector, 
+			       significance_vector);
+  
+  // Some properties of graphs are set
+
+  for (Int_t i = 0; i < n_graphs; i++)
+    {
+      graph_vector[i]->SetTitle();
+      graph_vector[i]->SetFillColor(19);
+      graph_vector[i]->SetLineColor(graph_colors_vector[i]);
+      graph_vector[i]->SetLineWidth(1);
+      graph_vector[i]->SetMarkerColor(graph_colors_vector[i]);
+      graph_vector[i]->SetMarkerStyle(polimarker_style_vector[i]);
+      graph_vector[i]->SetMarkerSize(1);
+    }
+
+
+// Graphgrams are plotted
+
+
+ TCanvas *Window = new TCanvas("Plot","Plot",600,600); 
+  
+ gStyle->SetOptStat(0);   
+ // So that statistic information is not printed
+
+  Window -> SetFillColor(10);
+  gStyle -> SetFrameFillColor(10);
+  gStyle -> SetPadLeftMargin (0.15);
+  gStyle -> SetPadRightMargin (0.15);
+  gStyle -> SetPadTopMargin (0.05);
+  gStyle -> SetPadBottomMargin (0.15);
+
+  TPaveText *title = new TPaveText (.05,.95,.95,.99);
+  title -> SetFillColor (38);  
+  title -> AddText (ps_title);
+  title -> Draw();
+
+ 
+  
+  
+  /* TPad(const char *name, const char *title, 
+     Double_t xlow, Double_t ylow, 
+     Double_t xup, Double_t yup, Color_t color, 
+     Short_t bordersize,Short_t bordermode) 
+     : TVirtualPad(name,title,xlow,ylow,xup,yup,color,
+     bordersize,bordermode) 
+  */
+
+  TPad *pad = new TPad ("plot", "plot",0.0, 0.0, 1.0, 0.92, 
+			10, 0, 0); 
+  // I do not want any border effect.
+  pad -> Draw();
+   
+   
+  // Axis and axis labels for pad1 are created and drawn.
+
+  pad -> cd();
+  pad -> SetGrid(1,1); // Grid for x axis and for y axis.
+  pad -> DrawFrame(pad_xlow,pad_ylow,pad_xup,pad_yup); 
+  // dimensions of the pad are set.
+  
+  
+   
+  // Labels of the graph are set
+
+  TText *t = new TText();
+  t->SetTextFont(62);
+  t->SetTextColor(1);
+  t->SetTextSize(0.05);
+  t->SetTextAlign(11);
+
+  // X axis
+  t->SetTextAngle(0);
+  t->DrawText(xaxis_label_xoffset_pad,
+	      xaxis_label_yoffset_pad,
+	      xaxis_title);
+  // Y axis
+  t->SetTextAngle(90); 
+  t->DrawText(yaxis_2_label_xoffset_pad,
+	      yaxis_2_label_yoffset_pad, 
+	      yaxis_2_title);
+
+ 
+  
+
+  // Graphs are plotted in pad
+
+
+  for (Int_t j = 0; j < n_graphs; j++)
+    {  
+      
+      pad -> cd();
+      graph_vector[j]-> Draw("LP");
+      // "A" option is removed in order to 
+      //control de dimensionsn of the pad, 
+      // by means of the " DrawFrame()" function.
+      
+    }
+  
+  // **************************************************
+  // Second Axis is drawn with its label
+  
+  // First of all we must look for units at
+  // bottom and top of axis. This is found 
+
+  
+  y_axis_2_min_value = ((pad_ylow - graph_y_minmax_vector [0][0])/
+			graph_2_scale_factor);
+
+  y_axis_2_max_value = ((pad_yup - graph_y_minmax_vector [0][0])/
+			graph_2_scale_factor);
+
+  
+
+  TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),
+			    gPad->GetUxmax(), gPad->GetUymax(),
+			    y_axis_2_min_value,
+			    y_axis_2_max_value,510,"+L");
+
+   axis->SetLineColor(1);
+   axis->SetTextColor(1);
+   axis->Draw();
+
+    // Y axis 2
+  t->SetTextAngle(90); 
+  t->DrawText(yaxis_label_xoffset_pad,
+	      yaxis_label_yoffset_pad, 
+	      yaxis_title);
+
+  // Graph information is produced and drawn.
+
+  // Spectrum names
+  /*
+  char info_string[150] = 0;
+  char info_string_tmp [20] = 0;
+  Double_t xpos = 0;
+  Double_t ypos = 0;
+  TText *tt = new TText();
+  tt->SetTextFont(62);
+  tt->SetTextSize(0.04);
+  tt->SetTextAlign(12);
+  tt->SetTextAngle(0);
+  
+  for (Int_t i = 0; i < n_graphs; i++)
+    {
+      if (i < 1)
+	{xpos = 0.15; ypos =  0.91;} 
+      else 
+	{xpos = 0.15; ypos = 0.85;}
+      
+      //xpos = 0.02 + i*0.12 + i*(i-1)*0.15; //for three curves
+      //xpos = 0.1 + i*0.4; // for two curves
+      strcpy(info_string, additional_info_vector[i]);
+      tt->SetTextColor(graph_colors_vector[i]);
+      Window -> cd();
+      tt->DrawText(xpos,ypos,info_string);
+    }
+  */
+
+
+  Window -> SaveAs(output_ps_file);
+
+}
+
+
+
+
+// FUNCTION DEFINITIONS
+
+
+
+
+
+Double_t find_value (Double_t vector[], Int_t dimension, Int_t min_max)
+{
+  Double_t value = vector[0];
+  if (min_max < 0.5) // we look for min
+    {
+      for (Int_t i = 1; i < dimension; i++)
+	{
+	  if (value > vector[i])
+	    {
+	      value = vector[i];
+	    }
+	}
+    }
+
+  else // we look for max
+    {
+      for (Int_t i = 1; i < dimension; i++)
+	{
+	  if (value < vector[i])
+	    {
+	      value = vector[i];
+	    }
+	}
+    }
+
+  return value;
+}
+  
+
+
+Double_t find_min (Double_t vector[], Int_t dimension)
+{
+  Double_t min = 0.0;
+  min = find_value (vector, dimension, 0);
+  return min;
+}
+
+
+
+Double_t find_max (Double_t vector[], Int_t dimension)
+{
+  Double_t max = 0.0;
+  max = find_value (vector, dimension, 1);
+  return max;
+}
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/SuperCutsONOFFMacro.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/SuperCutsONOFFMacro.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/SuperCutsONOFFMacro.C	(revision 9772)
@@ -0,0 +1,435 @@
+// Silly macro to run the classes that optimize supercuts 
+// using ON and OFF data.
+
+// The user only needs to fill/change the variables that control 
+// the optimization procedure.
+
+
+gROOT -> Reset();
+
+void SuperCutsONOFFMacroNew()
+{
+  gLog.SetNoColors();
+
+    // File containing the data (ON/OFF DATA and path for files (root/ps))
+
+    // From magicserv01
+//    TString  ONDataFilename("/.magic/data16a/mazin/data/mcdata/2004_06_30/*HillasON.root");
+                                       
+//    TString  OFFDataFilename("/.magic/data16a/mazin/data/mcdata/2004_06_30/*HillasOFF.root");
+
+//   TString  ONDataFilename("/.magic/magicserv01/scratch/Period21/HillasFiles/CrabNebula_20040914.root");
+//   TString  ONDataFilename("/.magic/magicserv01/scratch/Period21/HillasFiles/CrabNebula_20040921.root");
+//   TString  ONDataFilename("/.magic/magicserv01/scratch/Period21/HillasFiles/CrabNebula_20040922.root");
+
+//   TString  ONDataFilename("/.magic/magicserv01/scratch/Period21/HillasFiles/CrabNebula_2004*.root");
+  
+   //TString  ONDataFilename("/.magic/data22a/mazin/HillasParam/Period24/2004_12_18/Crab_40_25_1_AbsHillas.root");
+   TString  ONDataFilename("/.magic/data04a/nadia/Analysis/starfiles/DF/40_25_1/CrabNebula_*_Hillas_Abs.root");
+   TString  OFFDataFilename("/.magic/data04a/nadia/Analysis/starfiles/DF/40_25_1/OffCrab1*Hillas_Abs.root");
+   //TString ONDataFilename("/.magic/data03a/mazin/results/2004_09_21/CrabNebulaNadiaHillas.root");  
+   //TString OFFDataFilename("/.magic/data03a/mazin/results/2004_09_21/CrabNebulaNadiaHillas.root");  
+
+
+    TString PathForFiles ("/.magic/data03a/mazin/results/Crab/DF/CrabNadia/SuperCuts/Size2000/");  
+
+//    TString PathForFiles ("/.magic/magicserv01/scratch/hbartko/SC/"); // was: Daniel/SuperCuts/Mrk421/2004_04_22/4slices_3520_nc/E800_1200_Opt_MC_Test/
+
+    
+
+    // Boolean variables defining the job of the 
+    // macro
+ 
+    // Boolean variable that decides wether data is read from files specified above
+    // (ON/OFF) or read from already existing Matrices (which are obviously stored
+    // in a root file). The names of the files storing those matrices are produced 
+    // automatically using information provided by some of the next variables whose 
+    // values must be specified by user.
+
+    Bool_t ReadMatrixFromRootFiles = kTRUE;  
+  
+
+    // Boolean variable that controls the supercuts 
+    // optimization using the training sample
+    // The optimized cuts will be  written in root file
+    // located in directory specified before. Name of 
+    // the root files is created automatically.
+
+    Bool_t TrainParams   = kTRUE;  
+
+    // Variable that allows the user to skip the optimization on the 
+    // train sample. If optimization is skipped (value kTRUE), the
+    // previously optimized supercuts (stored in root file) are used 
+    // on the train sample.
+    
+    Bool_t SkipOptimization = kFALSE;
+
+    // Boolean variable that allows the user to write the initial parameters 
+    // into the root file that will be used to store the optimum cuts.
+    // If fUseInitialSCParams = kTRUE , parameters are written.
+    // In this way, the initial SC parameters can be applied on the data (train/test) 
+    
+    // The initial parameters are ONLY written to the root file if 
+    // there is NO SC params optimization, i.e., if variable 
+    // fSkipOptimization = kTRUE;
+  
+    // NOTE: be aware that, if there was a file with the optimized cuts 
+    // (previously computed), it will be overwritten with the initial 
+    // SC parameters. This is something that I WILL HAVE TO CHANGE IN 
+    // future. Yet for the time being...
+
+    Bool_t UseInitialSCParams = kTRUE;  // was kFALSE 
+    
+
+
+    // Variable that decides whether the optimized cuts are used 
+    // in the test sample.
+
+    Bool_t TestParams = kTRUE;  
+
+
+    // Boolean variable that controls wether to combine, OR not, the 
+    // alpha distributions computed (after cuts) for the several theta bins
+    // in which the TRAIN sample was divided.
+
+    Bool_t CombineCosThetaBinsForTrainSample = kFALSE; 
+    
+    // Boolean variable that controls wether to combine, OR not, the 
+    // alpha distribution computed (after cuts) for the several theta bins
+    // in which the TEST sample was divided.
+
+    Bool_t CombineCosThetaBinsForTestSample = kFALSE; 
+    
+
+    // Fraction of ON events used for the training/testing
+    Double_t whichfractiontrain = 0.5;
+    Double_t whichfractiontest = 0.5;
+
+    // Fraction of OFF events used for the training/testing 
+    Double_t whichfractiontrainOFF = 0.5;
+    Double_t whichfractiontestOFF = 0.5;
+
+
+    // Efficiency for gammas when using this set of dynamical cuts
+    // (i.e., fraction of initial gammas that remain after cuts)
+
+    // Current value is the first estimation of the efficiency of cuts
+    // on Mkn421 at a SIZE > 2000 photons
+
+    Double_t gammaeff = 0.6;  
+                         
+
+    // Alpha value (degrees) below which signal is expected
+    
+    Double_t alphasig = 9; 
+
+    // Definition of alpha bkg region (where no signal is expected)
+
+    Double_t alphabkgmin = 30;
+    Double_t alphabkgmax = 90;
+    
+    // Definition of the Size range
+
+    Double_t SizeLow = 2000;
+//    Double_t SizeUp =  2000;
+    Double_t SizeUp = 1000000;
+    
+    Double_t LeakageMax = 0.04;
+    Double_t DistMax    = 1.5;
+    Double_t DistMin    = 0.1;
+
+     // Definition of binning of alpha plots
+    Int_t NAlphaBins = 35;
+    Double_t AlphaBinLow = -9;
+    Double_t AlphaBinUp = 96;
+
+ 
+    // Boolean variable used to determine wether the normalization factor is 
+    // computed from method 1) or 2)
+    // 1) Using total number of ON and OFF events before cuts, and tuning the factor 
+    //    correcting for "contamination" of gamma events in ON sample 
+    // 2) Using number of ON and OFF events after cuts in the background 
+    //    region determined by variables fAlphaBkgMin-fAlphaBkgMax
+    
+    Bool_t NormFactorFromAlphaBkg = kTRUE; // if kTRUE, method 2) is used
+
+
+    // Boolean variable used to disable the usage ("serious" usage) of the 
+    // quantities computed from fits. This will be useful in those cases 
+    // where there is too few events to perform a decent fit to the 
+    // alpha histograms.
+    
+    Bool_t UseFittedQuantities = kTRUE;
+
+
+    // Boolean variable used to control wether to use theta information 
+    // in the computation of teh dynamical cuts that take place within
+    // class MCT1SupercutsCalc
+    //Bool_t NotUseTheta = kFALSE; // kTRUE removes theta from the parameterization of cuts
+    Bool_t NotUseTheta = kTRUE; // kTRUE removes theta from the parameterization of cuts
+
+    // Boolean variable used to decide wether to use dynamical cuts or static cuts
+    // kTRUE means that static cuts are used.
+    Bool_t UseStaticCuts = kFALSE;
+
+
+
+
+
+    // Name of the Postscript document where all plots
+    // will be saved.
+    // STORAGE OF PSFILE IS NOT WORKING PROPERLY
+    // For the time being, several ps files are produced 
+    // and saved in the directory specified by PathForFiles
+
+    /*
+    TString PsFileName = ("PsTest23.ps");
+    TString CompletePsFileName = (PathForFiles);
+    CompletePsFileName += PsFileName;
+    TPostScript* PsFile = new TPostScript(CompletePsFileName, 111);
+    */
+
+    // Boolean variable used to decide wether initial parameters are 
+    // read from ascii file or not. If kTRUE, parameters are retrieved 
+    // from ascii file. 
+
+    Bool_t ReadInitParamsFromAsciiFile = kTRUE;
+
+    // Number of SC parameters. The aim of this variable is to cross check 
+    // that the number of parameters read from an ascii file 
+    // is teh one the user wants. 
+
+    Int_t NInitSCPar = 104;
+
+    // Name of  the ascii file containing the 2 columns, the first one 
+    // for initial parameters and the second one for the steps
+    // Name must contain also the path.
+ 
+    const char* InitSCParamAsciiFile = 
+      // {"../InitialSCParametersSteps/InitSCParamsAndStepsDanielModified1.txt"};
+      // {"../InitialSCParametersSteps/FixedStaticCutsInLengthWidthDist.txt"};
+      // {"../InitialSCParametersSteps/FixedStaticCutsInLengthWidthDist11.txt"};
+      // {"../InitialSCParametersSteps/InitSCParamsAndStepsDanielModified1.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsFixedPol2SizeCut3000.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynWithDistParametersFixed.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsVariablePol2.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsVariablePol2WidthCutLowFixed.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynCutsOnSize.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynCutsOnSizeAndDist.txt"};
+      //{"mtemp/mmpi/asciifiles/OptimizedMkn421DynCutsGridWithSelected22pointsMay19.txt"};
+      //{"/home/pcmagic16/mazin/mars/Mars260804/mtemp/mmpi/asciifiles/StartingValuesForSmallSizes1.txt"};
+//      {"/home/pcmagic16/mazin/mars/Mars260804/mtemp/mmpi/asciifiles/SmallSizeRFStartValues.txt"};
+      {"/home/pcmagic16/mazin/mars/Mars260804/mtemp/mmpi/asciifiles/OptimizedCrabFrom2000_a.txt"};
+      //{"mtemp/mmpi/asciifiles/VeryGoodDummyValuesWithConcCut.txt"};
+
+
+    // Name of the root file where alpha distributions, TTree objects
+    // with info about the events and cuts applied and  info support histograms 
+    // will be stored. 
+    // Write only the name of the file. The Path 
+    // is the one defined previously
+
+    TString RootFilename = ("RootFileDynCuts.root");
+
+    
+
+    
+    
+
+    // Vector containing the theta bins in which data (ON/OFF train/test)
+    // will be divided. Actually this vector contains the cosinus of 
+    // these theta bins. The dimension of the vector is N+1, where 
+    // N is the number of theta bins intended. The first component of the 
+    // vector is the low bin edge of the first bin, and the last 
+    // vector component the upper bin edge of the last bin.
+
+
+    TArrayD CosThetaRangeVector(2);
+    CosThetaRangeVector[1] = 0.866;  //30
+    //CosThetaRangeVector[1] = 0.74;  //42
+    //CosThetaRangeVector[1] = 0.82;  //35
+    //CosThetaRangeVector[1] = 0;
+    //CosThetaRangeVector[1] = 0.825;
+    //CosThetaRangeVector[2] = 0.921; 
+    //CosThetaRangeVector[3] = 0.961; 
+    CosThetaRangeVector[0] = 0.5;  // 60
+    //CosThetaRangeVector[0] = 1;
+
+
+    /*
+    TArrayD CosThetaRangeVector(2);
+    CosThetaRangeVector[0] = 0.622;
+    // CosThetaRangeVector[1] = 0.825;
+    //CosThetaRangeVector[2] = 0.921; 
+    //CosThetaRangeVector[0] = 0.961; 
+    CosThetaRangeVector[1] = 0.984;
+    
+    */
+    // Object of MCT1FindSupercutsONOFFThetaLoop created, data that was specified 
+    // above is introduced and ... and the party starts.
+     
+    MFindSupercutsONOFFThetaLoop FindSupercuts("MFindSupercutsONOFFThetaLoop", 
+					       "Optimizer for the supercuts");
+
+    
+    FindSupercuts.SetPathForFiles(PathForFiles);
+
+    FindSupercuts.SetDataONOFFRootFilenames(ONDataFilename, OFFDataFilename);
+
+    FindSupercuts.SetFractionTrainTestOnOffEvents(whichfractiontrain, 
+						  whichfractiontest, 
+						  whichfractiontrainOFF, 
+						  whichfractiontestOFF);
+
+
+    FindSupercuts.SetGammaEfficiency(gammaeff);
+
+
+    FindSupercuts.SetAlphaSig(alphasig);
+
+    // Bkg alpha region is set 
+    FindSupercuts.SetAlphaBkgMin(alphabkgmin);
+    FindSupercuts.SetAlphaBkgMax(alphabkgmax);
+
+    // alpha bkg and signal region set in object FindSupercuts
+    // are re-checked in order to be sure that make sense
+	
+    FindSupercuts.CheckAlphaSigBkg();
+
+
+    // binning for alpha plots is defined
+
+    FindSupercuts.SetAlphaPlotBinining(NAlphaBins, AlphaBinLow, 
+				       AlphaBinUp);
+
+
+
+
+    // Size range is defined
+
+    FindSupercuts.SetSizeRange(SizeLow, SizeUp);
+    FindSupercuts.SetFilters(LeakageMax, DistMax, DistMin);
+//    FindSupercuts.SetFilters(0.001, 1.5, 0.2);
+
+
+
+    FindSupercuts.SetNormFactorFromAlphaBkg(NormFactorFromAlphaBkg);
+
+    FindSupercuts.SetUseFittedQuantities(UseFittedQuantities);
+
+    FindSupercuts.SetVariableUseStaticCuts(UseStaticCuts);
+
+    FindSupercuts.SetVariableNotUseTheta(NotUseTheta);
+
+    FindSupercuts.SetReadMatricesFromFile(ReadMatrixFromRootFiles);
+
+    FindSupercuts.SetTrainParameters(TrainParams);
+    FindSupercuts.SetSkipOptimization(SkipOptimization);
+    FindSupercuts.SetUseInitialSCParams(UseInitialSCParams);
+
+    FindSupercuts.SetTestParameters(TestParams);
+
+   
+    
+    FindSupercuts.SetHadronnessName("MHadSC");
+    FindSupercuts.SetHadronnessNameOFF("MHadOFFSC");
+    
+    FindSupercuts.SetAlphaDistributionsRootFilename (RootFilename);
+    
+    // FindSupercuts.SetPostScriptFile (PsFile);
+
+    FindSupercuts.SetCosThetaRangeVector (CosThetaRangeVector);
+    
+
+    // Names for all root files (matrices, alpha distributions...)
+    // are created 
+    FindSupercuts.SetALLNames();
+
+    if(ReadInitParamsFromAsciiFile)
+    {
+	// Initial SC Parameters and steps are retrieved from 
+	// Ascii file
+	if(!FindSupercuts.ReadSCParamsFromAsciiFile(InitSCParamAsciiFile,
+						    NInitSCPar))
+	{
+	    cout << "Initial SC Parameters could not be read from Ascii file "
+		 << InitSCParamAsciiFile << endl
+		 << "Aborting execution of macro... " << endl;
+	    return;
+
+	}
+    }
+ 
+   
+
+
+    // Finally loop over all theta bins defined is executed
+    
+    if (!FindSupercuts.LoopOverThetaRanges())
+      {
+	cout << "Function MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges()" << endl
+	     << "could not be performed" << endl;
+
+      }
+
+    
+
+    // Nex and Significance are computed vs alphasig
+    
+    if (!FindSupercuts.ComputeNexSignificanceVSAlphaSig())
+      {
+	cout << "Function MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" << endl
+	     << "could not be performed" << endl;
+	
+
+      }
+    
+
+
+
+    // Option to store ps files in a single ps document is still not working
+    /*
+    PsFile -> Close();
+    PsFile = NULL;
+    */
+
+    // Several theta bins are combined to produced a single alpha plot (for train and test)
+    // with single Nex and significances
+
+    if (CombineCosThetaBinsForTrainSample || CombineCosThetaBinsForTestSample)
+    {
+	if(!FindSupercuts.ComputeOverallSignificance(CombineCosThetaBinsForTrainSample, 
+						     CombineCosThetaBinsForTestSample))
+	  {
+	    cout << "Function MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance" << endl
+		 << "could not be performed" << endl;
+	  }
+       
+
+    }
+
+
+   
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/SuperCutsONOFFMacroNew.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/SuperCutsONOFFMacroNew.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/SuperCutsONOFFMacroNew.C	(revision 9772)
@@ -0,0 +1,473 @@
+// Silly macro to run the classes that optimize supercuts 
+// using ON and OFF data.
+
+// The user only needs to fill/change the variables that control 
+// the optimization procedure.
+
+
+gROOT -> Reset();
+
+void SuperCutsONOFFMacroNew()
+{
+//  gLog.SetNoColors();
+
+    // File containing the data (ON/OFF DATA and path for files (root/ps))
+
+    // From magicserv01
+//    TString  ONDataFilename("/.magic/data16a/mazin/data/mcdata/2004_06_30/*HillasON.root");
+                                       
+//    TString  OFFDataFilename("/.magic/data16a/mazin/data/mcdata/2004_06_30/*HillasOFF.root");
+
+//   TString  ONDataFilename("/.magic/magicserv01/scratch/Period21/HillasFiles/CrabNebula_20040914.root");
+//   TString  ONDataFilename("/.magic/magicserv01/scratch/Period21/HillasFiles/CrabNebula_20040921.root");
+//   TString  ONDataFilename("/.magic/magicserv01/scratch/Period21/HillasFiles/CrabNebula_20040922.root");
+
+//   TString  ONDataFilename("/.magic/magicserv01/scratch/Period21/HillasFiles/CrabNebula_2004*.root");
+  
+   TString  ONDataFilename("/users/emc/mazin/HillasFiles/2004_12_18/55_28_1/CrabNebula*.root");
+   //TString  ONDataFilename("/.magic/data22a/mazin/HillasParam/MC_OffSep/ON/*.root");
+   //TString  ONDataFilename("/.magic/data04a/nadia/Analysis/starfiles/DF/40_25_1/1ES1959_*.root");
+   TString  OFFDataFilename("/users/emc/mazin/HillasFiles/Off/55_28_1/Off*.root");
+   //TString ONDataFilename("/.magic/data03a/mazin/results/2004_09_21/CrabNebulaNadiaHillas.root");  
+   //TString OFFDataFilename("/.magic/data03a/mazin/results/2004_09_21/CrabNebulaNadiaHillas.root");  
+
+
+    //TString PathForFiles ("/.magic/data03a/mazin/results/mcOffCrab/SuperCuts/Size1000/");  
+    //TString PathForFiles ("/.magic/data03a/mazin/results/Crab/DF/CrabNadia/SuperCuts/Size2000_cutsfrommc_all/");  
+    TString PathForFiles ("/users/emc/mazin/SuperCuts/Spline/SuperCuts/55_28_1/Size1k2k/");  
+    //TString PathForFiles ("/.magic/data03a/mazin/results/Crab/DF/CrabNadia/SuperCuts/1ES1959Size2000_cutsfrommc_all_2/");  
+    //TString PathForFiles ("/.magic/data03a/mazin/results/Crab/DF/CrabNadia/SuperCuts/1ES1959Size2000/");  
+//    TString PathForFiles ("/.magic/data03a/mazin/results/Crab/DF/CrabNadia/SuperCuts/Size2000_all/");  
+
+//    TString PathForFiles ("/.magic/magicserv01/scratch/hbartko/SC/"); // was: Daniel/SuperCuts/Mrk421/2004_04_22/4slices_3520_nc/E800_1200_Opt_MC_Test/
+
+    
+
+    // Boolean variables defining the job of the 
+    // macro
+ 
+    // Boolean variable that decides wether data is read from files specified above
+    // (ON/OFF) or read from already existing Matrices (which are obviously stored
+    // in a root file). The names of the files storing those matrices are produced 
+    // automatically using information provided by some of the next variables whose 
+    // values must be specified by user.
+
+    Bool_t ReadMatrixFromRootFiles = kTRUE;  
+  
+
+    // Boolean variable that controls the supercuts 
+    // optimization using the training sample
+    // The optimized cuts will be  written in root file
+    // located in directory specified before. Name of 
+    // the root files is created automatically.
+
+    Bool_t TrainParams   = kTRUE;  
+
+    // Variable that allows the user to skip the optimization on the 
+    // train sample. If optimization is skipped (value kTRUE), the
+    // previously optimized supercuts (stored in root file) are used 
+    // on the train sample.
+    
+    Bool_t SkipOptimization = kFALSE;
+
+    // Boolean variable that allows the user to write the initial parameters 
+    // into the root file that will be used to store the optimum cuts.
+    // If fUseInitialSCParams = kTRUE , parameters are written.
+    // In this way, the initial SC parameters can be applied on the data (train/test) 
+    
+    // The initial parameters are ONLY written to the root file if 
+    // there is NO SC params optimization, i.e., if variable 
+    // fSkipOptimization = kTRUE;
+  
+    // NOTE: be aware that, if there was a file with the optimized cuts 
+    // (previously computed), it will be overwritten with the initial 
+    // SC parameters. This is something that I WILL HAVE TO CHANGE IN 
+    // future. Yet for the time being...
+
+    Bool_t UseInitialSCParams = kTRUE;  // was kFALSE 
+    
+
+
+    // Variable that decides whether the optimized cuts are used 
+    // in the test sample.
+
+    Bool_t TestParams = kTRUE;  
+
+
+    // Boolean variable that controls wether to combine, OR not, the 
+    // alpha distributions computed (after cuts) for the several theta bins
+    // in which the TRAIN sample was divided.
+
+    Bool_t CombineCosThetaBinsForTrainSample = kFALSE; 
+    
+    // Boolean variable that controls wether to combine, OR not, the 
+    // alpha distribution computed (after cuts) for the several theta bins
+    // in which the TEST sample was divided.
+
+    Bool_t CombineCosThetaBinsForTestSample = kFALSE; 
+    
+
+    // Fraction of ON events used for the training/testing
+    Double_t whichfractiontrain = 0.5;
+    Double_t whichfractiontest = 0.5;
+
+    // Fraction of OFF events used for the training/testing 
+    Double_t whichfractiontrainOFF = 0.5;
+    Double_t whichfractiontestOFF = 0.5;
+
+
+    // Efficiency for gammas when using this set of dynamical cuts
+    // (i.e., fraction of initial gammas that remain after cuts)
+
+    // Current value is the first estimation of the efficiency of cuts
+    // on Mkn421 at a SIZE > 2000 photons
+
+    Double_t gammaeff = 0.6;  
+                         
+
+    // Alpha value (degrees) below which signal is expected
+    
+    Double_t alphasig = 6; 
+
+    // Definition of alpha bkg region (where no signal is expected)
+
+    Double_t alphabkgmin = 20;
+    Double_t alphabkgmax = 80;
+
+    // Definition of the degree of the polynomials used to fit 
+    // the ON and the OFF data
+
+    Int_t degree = 2;
+
+    
+    // Definition of the Size range
+
+    Double_t SizeLow = 1000;
+    Double_t SizeUp =  2000;
+//    Double_t SizeUp = 1000000;
+    
+/*
+    Double_t LeakageMax = 0.05;
+    Double_t DistMax    = 1.5;
+    Double_t DistMin    = 0.1;
+*/
+    //Double_t LeakageMax = 1.;
+    //Double_t DistMax    = 1.0;
+    //Double_t DistMin    = 0.2;
+
+    Double_t LeakageMax = 0.25;
+    Double_t DistMax    = 1.0;
+    Double_t DistMin    = 0.2;
+
+     // Definition of binning of alpha plots
+//    Int_t NAlphaBins = 35;
+//    Double_t AlphaBinLow = -9;
+//    Double_t AlphaBinUp = 96;
+
+    Int_t NAlphaBins = 30;
+    Double_t AlphaBinLow = 0;
+    Double_t AlphaBinUp = 90;
+
+//    Int_t NAlphaBins = 20;
+//    Double_t AlphaBinLow = 0;
+//    Double_t AlphaBinUp = 90;
+
+ 
+    // Boolean variable used to determine wether the normalization factor is 
+    // computed from method 1) or 2)
+    // 1) Using total number of ON and OFF events before cuts, and tuning the factor 
+    //    correcting for "contamination" of gamma events in ON sample 
+    // 2) Using number of ON and OFF events after cuts in the background 
+    //    region determined by variables fAlphaBkgMin-fAlphaBkgMax
+    
+    Bool_t NormFactorFromAlphaBkg = kTRUE; // if kTRUE, method 2) is used
+
+
+    // Boolean variable used to disable the usage ("serious" usage) of the 
+    // quantities computed from fits. This will be useful in those cases 
+    // where there is too few events to perform a decent fit to the 
+    // alpha histograms.
+    
+    Bool_t UseFittedQuantities = kTRUE;
+
+
+    // Boolean variable used to control wether to use theta information 
+    // in the computation of teh dynamical cuts that take place within
+    // class MCT1SupercutsCalc
+    //Bool_t NotUseTheta = kFALSE; // kTRUE removes theta from the parameterization of cuts
+    Bool_t NotUseTheta = kTRUE; // kTRUE removes theta from the parameterization of cuts
+
+    // Boolean variable used to decide wether to use dynamical cuts or static cuts
+    // kTRUE means that static cuts are used.
+    Bool_t UseStaticCuts = kFALSE;
+
+
+
+
+
+    // Name of the Postscript document where all plots
+    // will be saved.
+    // STORAGE OF PSFILE IS NOT WORKING PROPERLY
+    // For the time being, several ps files are produced 
+    // and saved in the directory specified by PathForFiles
+
+    /*
+    TString PsFileName = ("PsTest23.ps");
+    TString CompletePsFileName = (PathForFiles);
+    CompletePsFileName += PsFileName;
+    TPostScript* PsFile = new TPostScript(CompletePsFileName, 111);
+    */
+
+    // Boolean variable used to decide wether initial parameters are 
+    // read from ascii file or not. If kTRUE, parameters are retrieved 
+    // from ascii file. 
+
+    Bool_t ReadInitParamsFromAsciiFile = kTRUE;
+
+    // Number of SC parameters. The aim of this variable is to cross check 
+    // that the number of parameters read from an ascii file 
+    // is teh one the user wants. 
+
+    Int_t NInitSCPar = 104;
+
+    // Name of  the ascii file containing the 2 columns, the first one 
+    // for initial parameters and the second one for the steps
+    // Name must contain also the path.
+ 
+    const char* InitSCParamAsciiFile = 
+      // {"../InitialSCParametersSteps/InitSCParamsAndStepsDanielModified1.txt"};
+      // {"../InitialSCParametersSteps/FixedStaticCutsInLengthWidthDist.txt"};
+      // {"../InitialSCParametersSteps/FixedStaticCutsInLengthWidthDist11.txt"};
+      // {"../InitialSCParametersSteps/InitSCParamsAndStepsDanielModified1.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsFixedPol2SizeCut3000.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynWithDistParametersFixed.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsVariablePol2.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynStaticCutsVariablePol2WidthCutLowFixed.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynCutsOnSize.txt"};
+      // {"../InitialSCParametersSteps/StartingValuesForOptimizationMkn421DynCutsOnSizeAndDist.txt"};
+      //{"mtemp/mmpi/asciifiles/OptimizedMkn421DynCutsGridWithSelected22pointsMay19.txt"};
+        {"mtemp/mmpi/asciifiles/StartingValuesForSmallSizes1.txt"};
+      //{"mtemp/mmpi/asciifiles/SmallSizeRFStartValues.txt"};
+//      {"/home/pcmagic16/mazin/mars/Mars260804/mtemp/mmpi/asciifiles/OptimizedCrabFrom2000_a.txt"};
+      //{"mtemp/mmpi/asciifiles/VeryGoodDummyValuesWithConcCut.txt"};
+
+
+    // Name of the root file where alpha distributions, TTree objects
+    // with info about the events and cuts applied and  info support histograms 
+    // will be stored. 
+    // Write only the name of the file. The Path 
+    // is the one defined previously
+
+    TString RootFilename = ("RootFileDynCuts.root");
+
+    
+
+    
+    
+
+    // Vector containing the theta bins in which data (ON/OFF train/test)
+    // will be divided. Actually this vector contains the cosinus of 
+    // these theta bins. The dimension of the vector is N+1, where 
+    // N is the number of theta bins intended. The first component of the 
+    // vector is the low bin edge of the first bin, and the last 
+    // vector component the upper bin edge of the last bin.
+
+
+    TArrayD CosThetaRangeVector(2);
+    CosThetaRangeVector[1] = 0.866;  //30
+    //CosThetaRangeVector[1] = 0.74;  //42
+    //CosThetaRangeVector[1] = 0.82;  //35
+    //CosThetaRangeVector[1] = 0;
+    //CosThetaRangeVector[1] = 0.825;
+    //CosThetaRangeVector[2] = 0.921; 
+    //CosThetaRangeVector[3] = 0.961; 
+    CosThetaRangeVector[0] = 0.5;  // 60
+    //CosThetaRangeVector[0] = 1;
+
+
+    /*
+    TArrayD CosThetaRangeVector(2);
+    CosThetaRangeVector[0] = 0.622;
+    // CosThetaRangeVector[1] = 0.825;
+    //CosThetaRangeVector[2] = 0.921; 
+    //CosThetaRangeVector[0] = 0.961; 
+    CosThetaRangeVector[1] = 0.984;
+    
+    */
+    // Object of MCT1FindSupercutsONOFFThetaLoop created, data that was specified 
+    // above is introduced and ... and the party starts.
+     
+    MFindSupercutsONOFFThetaLoop FindSupercuts("MFindSupercutsONOFFThetaLoop", 
+					       "Optimizer for the supercuts");
+
+    
+    FindSupercuts.SetPathForFiles(PathForFiles);
+
+    FindSupercuts.SetDataONOFFRootFilenames(ONDataFilename, OFFDataFilename);
+
+    FindSupercuts.SetFractionTrainTestOnOffEvents(whichfractiontrain, 
+						  whichfractiontest, 
+						  whichfractiontrainOFF, 
+						  whichfractiontestOFF);
+
+
+    FindSupercuts.SetGammaEfficiency(gammaeff);
+
+
+    FindSupercuts.SetAlphaSig(alphasig);
+
+    // Bkg alpha region is set 
+    FindSupercuts.SetAlphaBkgMin(alphabkgmin);
+    FindSupercuts.SetAlphaBkgMax(alphabkgmax);
+
+    // alpha bkg and signal region set in object FindSupercuts
+    // are re-checked in order to be sure that make sense
+	
+    FindSupercuts.CheckAlphaSigBkg();
+
+
+    // Degree of the polynomials used to fit the ON OFF data 
+    // is set
+
+    FindSupercuts.SetDegreeON(degree);
+    FindSupercuts.SetDegreeOFF(degree);
+
+
+
+
+    // binning for alpha plots is defined
+
+    FindSupercuts.SetAlphaPlotBinining(NAlphaBins, AlphaBinLow, 
+				       AlphaBinUp);
+
+
+
+
+    // Size range is defined
+
+    FindSupercuts.SetSizeRange(SizeLow, SizeUp);
+    FindSupercuts.SetFilters(LeakageMax, DistMax, DistMin);
+//    FindSupercuts.SetFilters(0.001, 1.5, 0.2);
+
+
+
+    FindSupercuts.SetNormFactorFromAlphaBkg(NormFactorFromAlphaBkg);
+
+    FindSupercuts.SetUseFittedQuantities(UseFittedQuantities);
+
+    FindSupercuts.SetVariableUseStaticCuts(UseStaticCuts);
+
+    FindSupercuts.SetVariableNotUseTheta(NotUseTheta);
+
+    FindSupercuts.SetReadMatricesFromFile(ReadMatrixFromRootFiles);
+
+    FindSupercuts.SetTrainParameters(TrainParams);
+    FindSupercuts.SetSkipOptimization(SkipOptimization);
+    FindSupercuts.SetUseInitialSCParams(UseInitialSCParams);
+
+    FindSupercuts.SetTestParameters(TestParams);
+
+   
+    
+    FindSupercuts.SetHadronnessName("MHadSC");
+    FindSupercuts.SetHadronnessNameOFF("MHadOFFSC");
+    
+    FindSupercuts.SetAlphaDistributionsRootFilename (RootFilename);
+    
+    // FindSupercuts.SetPostScriptFile (PsFile);
+
+    FindSupercuts.SetCosThetaRangeVector (CosThetaRangeVector);
+    
+
+    // Names for all root files (matrices, alpha distributions...)
+    // are created 
+    FindSupercuts.SetALLNames();
+
+    if(ReadInitParamsFromAsciiFile)
+    {
+	// Initial SC Parameters and steps are retrieved from 
+	// Ascii file
+	if(!FindSupercuts.ReadSCParamsFromAsciiFile(InitSCParamAsciiFile,
+						    NInitSCPar))
+	{
+	    cout << "Initial SC Parameters could not be read from Ascii file "
+		 << InitSCParamAsciiFile << endl
+		 << "Aborting execution of macro... " << endl;
+	    return;
+
+	}
+    }
+ 
+   
+
+
+    // Finally loop over all theta bins defined is executed
+    
+    if (!FindSupercuts.LoopOverThetaRanges())
+      {
+	cout << "Function MFindSupercutsONOFFThetaLoop::LoopOverThetaRanges()" << endl
+	     << "could not be performed" << endl;
+
+      }
+
+    
+
+    // Nex and Significance are computed vs alphasig
+    
+    if (!FindSupercuts.ComputeNexSignificanceVSAlphaSig())
+      {
+	cout << "Function MFindSupercutsONOFFThetaLoop::ComputeNexSignificanceVSAlphaSig()" << endl
+	     << "could not be performed" << endl;
+	
+
+      }
+    
+
+
+
+    // Option to store ps files in a single ps document is still not working
+    /*
+    PsFile -> Close();
+    PsFile = NULL;
+    */
+
+    // Several theta bins are combined to produced a single alpha plot (for train and test)
+    // with single Nex and significances
+
+    if (CombineCosThetaBinsForTrainSample || CombineCosThetaBinsForTestSample)
+    {
+	if(!FindSupercuts.ComputeOverallSignificance(CombineCosThetaBinsForTrainSample, 
+						     CombineCosThetaBinsForTestSample))
+	  {
+	    cout << "Function MFindSupercutsONOFFThetaLoop::ComputeOverallSignificance" << endl
+		 << "could not be performed" << endl;
+	  }
+       
+
+    }
+
+
+   
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/calculate_of_weights.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/calculate_of_weights.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/calculate_of_weights.C	(revision 9772)
@@ -0,0 +1,164 @@
+const int no_samples=6;
+
+
+void calculate_of_weights(TH1F *shape, TString noise_file = "/mnt/home/pcmagic17/hbartko/mars/results/04sep12/noise_autocorr_AB_36038.root", Int_t t_offset = -10)
+{
+
+  
+  TH1F * derivative = new TH1F("derivative","derivative",161,-1.05,15.05);
+
+
+  for (int i = 1; i<162;i++){
+    derivative->SetBinContent(i,((shape->GetBinContent(i+1)-shape->GetBinContent(i-1))/0.2));
+    derivative->SetBinError(i,(sqrt(shape->GetBinError(i+1)*shape->GetBinError(i+1)+shape->GetBinError(i-1)*shape->GetBinError(i-1))/0.2));
+  }
+  
+  // normalize the shape, such that the integral for 6 slices is one!
+
+  float sum = 0;
+  for (int i=40; i<101; i++){sum+=shape->GetBinContent(i);}
+  sum /= 10;
+
+  shape->Scale(1./sum);
+  derivative->Scale(1./sum);
+
+
+  TCanvas * c1 = new TCanvas("c1","c1",600,400);
+  //c1= canvas();
+  shape->Draw();
+
+  TCanvas *c2 = new TCanvas("c2","c2",600,400);
+  //c2=canvas();
+  derivative->Draw();
+
+
+  // book the histograms for the weights
+
+  TH1F * hw_amp = new TH1F("hw_amp","hw_amp",no_samples*10,-0.5,no_samples-0.5);
+  TH1F * hw_time = new TH1F("hw_time","hw_time",no_samples*10,-0.5,no_samples-0.5);
+  TH1F * hshape = new TH1F("hshape","hshape",no_samples*10,-0.5,no_samples-0.5);
+  TH1F * hderivative = new TH1F("hderivative","hderivative",no_samples*10,-0.5,no_samples-0.5);
+
+
+  // read in the noise auto-correlation function:
+
+  TMatrix B(no_samples,no_samples);
+
+  f = new TFile(noise_file);
+  TH2F * noise_corr = (TH2F*)c_corr->FindObject("hcorr");
+  for (int i=0; i<no_samples; i++){
+    for (int j=0; j<no_samples; j++){
+      B[i][j]=noise_corr->GetBinContent(i+1,j+1);
+    }
+  }  
+  f->Close();
+
+  B.Invert();
+
+  // now the loop over t_{rel} in [-0.4;0.6[ :
+
+  for (int i=-4; i<6; i++){
+    
+  
+    TMatrix g(no_samples,1);
+    TMatrix gT(1,no_samples);
+    TMatrix d(no_samples,1);
+    TMatrix dT(1,no_samples);
+    
+    
+    for (int count=0; count < no_samples; count++){
+      
+      g[count][0]=shape->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i); 
+      gT[0][count]=shape->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i);
+      d[count][0]=derivative->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i);
+      dT[0][count]=derivative->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i);
+      
+      hshape->SetBinContent(i+5+10*count,shape->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i));
+      hderivative->SetBinContent(i+5+10*count,derivative->GetBinContent(55+t_offset-int((10*no_samples-50)/2.)+10*count+i));
+    }
+    
+    
+    TMatrix m_denom = (gT*(B*g))*(dT*(B*d)) - (dT*(B*g))*(dT*(B*g));
+    float denom = m_denom[0][0];  // m_denom is a real number
+    
+    TMatrix m_first = dT*(B*d);     // m_first is a real number
+    float first = m_first[0][0]/denom;
+    
+    TMatrix m_last = gT*(B*d);      // m_last is a real number 
+    float last = m_last[0][0]/denom;
+    
+    TMatrix m1 = gT*B;
+  
+    m1 *=first;
+    
+    TMatrix m2 = dT*B; 
+    
+    m2 *=last;
+    
+    TMatrix w_amp= m1 - m2;
+    
+    
+    TMatrix m_first1 = gT*(B*g);
+    float first1 = m_first1[0][0]/denom;
+    
+    TMatrix m_last1 = gT*(B*d);
+    float last1 = m_last1[0][0]/denom;
+    
+    TMatrix m11 = dT*B; 
+   
+    m11 *=first1;
+    
+    TMatrix m21 = gT*B;
+    
+    m21 *=last1;
+    
+    
+    TMatrix w_time= m11 - m21; 
+    
+    
+    float amp = 0;
+    float amp_time = 0;
+
+    for (int count=0; count < no_samples; count++){
+      hw_amp->SetBinContent(i+5+10*count,w_amp[0][count]);
+      hw_time->SetBinContent(i+5+10*count,w_time[0][count]);
+    }
+   
+
+    
+    TMatrix m_delta_E = dT*(B*d);      // m_last is a real number 
+    float delta_E = m_delta_E[0][0]/denom;
+
+
+    TMatrix m_delta_Et = gT*(B*g);      // m_last is a real number 
+    float delta_Et = m_delta_Et[0][0]/denom;
+
+    cout << " i " << i << " delta E " << sqrt(delta_E) << " delta Et " << sqrt(delta_Et) << endl;
+
+
+  } // end loop over t_rel
+
+
+  TCanvas * c3 = new TCanvas("c3","c3",600,400);
+  hw_amp->Draw();
+
+  TCanvas * c4 = new TCanvas("c4","c4",600,400);
+  hw_time->Draw();
+
+  TCanvas * c5 = new TCanvas("c5","c5",600,400);
+  hshape->Draw();
+
+  TCanvas * c6 = new TCanvas("c6","c6",600,400);
+  hderivative->Draw();
+
+  /*
+  f_out = new TFile("/home/pcmagic17/hbartko/mars/results/04sep15/calibration_weights_corr_iterated.root","RECREATE");  //"../of_weights_bin4.root"
+  hw_amp->Write();
+  hw_time->Write();
+  hshape->Write();
+  hderivative->Write();
+  shape->Write();
+  derivative->Write();
+  f_out->Close();
+  */
+}
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/calibrate_data_ped_standard.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/calibrate_data_ped_standard.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/calibrate_data_ped_standard.C	(revision 9772)
@@ -0,0 +1,737 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko, 03/2004 <mailto:hbartko@mppmu.mpg.de>
+!              Markus Gaug,    03/2004 <mailto:markus@ifae.es>
+!              Wolfgang Wittek 07/2004 <mailto:wittek@mppmu.mpg.de>
+!              Daniel Mazin    08/2004 <mailto:mazin@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//-------------------------------------
+//
+//  changes by W. Wittek :
+//      - call SetRange() and SetWindows() for 
+//                        MExtractedFixedWindowPeakSearch
+//      - call SetRange() and SetWindowSize() for MPedCalcPedRun
+//      - call MPedCalcFromData in 3rd loop (data calibration)
+//
+//-------------------------------------
+
+
+
+//const TString defpath = "/local/rootdata/2004_08_23/";
+
+//  const TString defpath = "/mnt/data21a/Crab_August/";
+
+   const TString defpath = "/home/pcmagic04/pratik/analysis/2004_08_14/";
+
+//const TString defcontinuoslightfile =   
+//    "/.magic/magicserv01/MAGIC/rootdata2/2004_04_22/20040813_32834_C_3EG1727+04-100CL_E.root";
+const TString defcontinuoslightfile =   
+    "/mnt/data21a/Crab_August/20040820_34060_C_CrabNebula-100CL_E.root";
+
+//  ON data Mkn 421
+
+const TString defrout = "34994_test.root";
+const Int_t defpedr  = 10060; //      {17191,17192};
+const Int_t defcalr  = 10051; //      {17193,17198,17200};
+const Int_t defdatar = 23210; //      {17206,17207,17208};
+
+
+//void calibrate_data_pedestal(const TString inpath=defpath, 
+//               const Int_t pedrun=defpedr, 
+//               const Int_t calrun=defcalr, 
+//               const Int_t datarun=defdatar, 
+//	       const TString continuoslightfile=defcontinuoslightfile,
+//               const TString resname=defrout)
+
+void calibrate_data_ped_standard(const TString inpath = defpath, 
+                                 const Int_t pedrun = defpedr, 
+                                 const Int_t calrun = defcalr, 
+                                 const Int_t datarun = defdatar, 
+	                         const TString continuoslightfile = defcontinuoslightfile,
+                                 const TString resname = defrout)
+
+{
+ cout << " inpath : " << inpath << endl;
+ cout << " pedrun : " << pedrun << endl;
+ cout << " calrun : " << calrun << endl;
+ cout << " datarun : " << datarun << endl;
+ cout << " continuoslightfile : " << continuoslightfile << endl;
+ cout << " FILE to write : " << resname << endl;
+
+  gLog.SetNoColors();
+  // the parameters should be identical to the ones of MPedCalcPedRun
+
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+ 
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+
+
+
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+  
+/*
+  for (Int_t i=0;i<psize;i++) {
+    cout << "Adding pedestal run: " << pedruns[i] << endl;
+    pruns.AddRun(pedruns[i],inpath);
+  }
+  for (Int_t i=0;i<csize;i++) {
+    cout << "Adding calibration run: " << calruns[i] << endl;
+    cruns.AddRun(calruns[i],inpath);
+  }
+  for (Int_t i=0;i<dsize;i++) {
+    cout << "Adding data run: " << dataruns[i] << endl;
+    druns.AddRun(dataruns[i],inpath);
+  }
+*/
+
+    cout << "Adding pedestal run: " << pedrun << endl;
+    pruns.AddRun(pedrun,inpath);
+    cout << "Adding calibration run: " << calrun << endl;
+    cruns.AddRun(calrun,inpath);
+    cruns.AddRun(10001,inpath);
+cruns.AddRun(10002,inpath);
+cruns.AddRun(10003,inpath);
+cruns.AddRun(10004,inpath);
+cruns.AddRun(10005,inpath);
+cruns.AddRun(10006,inpath);
+cruns.AddRun(10007,inpath);
+cruns.AddRun(10008,inpath);
+cruns.AddRun(10009,inpath);
+cruns.AddRun(10010,inpath);
+cruns.AddRun(10011,inpath);
+cruns.AddRun(10012,inpath);
+cruns.AddRun(10013,inpath);
+cruns.AddRun(10014,inpath);
+cruns.AddRun(10015,inpath);
+cruns.AddRun(10016,inpath);
+cruns.AddRun(10017,inpath);
+cruns.AddRun(10018,inpath);
+cruns.AddRun(10019,inpath);
+cruns.AddRun(10020,inpath);
+cruns.AddRun(10021,inpath);
+cruns.AddRun(10022,inpath);
+cruns.AddRun(10023,inpath);
+cruns.AddRun(10024,inpath);
+cruns.AddRun(10025,inpath);
+cruns.AddRun(10026,inpath);
+cruns.AddRun(10027,inpath);
+cruns.AddRun(10028,inpath);
+cruns.AddRun(10029,inpath);
+cruns.AddRun(10030,inpath);
+cruns.AddRun(10031,inpath);
+cruns.AddRun(10032,inpath);
+cruns.AddRun(10033,inpath);
+cruns.AddRun(10034,inpath);
+cruns.AddRun(10035,inpath);
+cruns.AddRun(10036,inpath);
+cruns.AddRun(10037,inpath);
+cruns.AddRun(10038,inpath);
+cruns.AddRun(10039,inpath);
+cruns.AddRun(10040,inpath);
+cruns.AddRun(10041,inpath);
+cruns.AddRun(10042,inpath);
+cruns.AddRun(10043,inpath);
+cruns.AddRun(10044,inpath);
+cruns.AddRun(10045,inpath);
+cruns.AddRun(10046,inpath);
+cruns.AddRun(10047,inpath);
+cruns.AddRun(10048,inpath);
+cruns.AddRun(10049,inpath);
+cruns.AddRun(10050,inpath);
+
+
+   cout << "Adding data run: " << datarun << endl;
+    druns.AddRun(datarun,inpath);
+
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MParList plist1;
+  MTaskList tlist1;
+  plist1.AddToList(&tlist1);
+  
+  // containers
+  MPedestalCam   pedcam;
+  MBadPixelsCam  badcam;
+  //
+  // for excluding pixels from the beginning:
+  //
+  // badcam.AsciiRead("badpixels.dat");
+
+
+  plist1.AddToList(&pedcam);
+  plist1.AddToList(&badcam);
+    
+  //tasks
+  MReadMarsFile  read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(pruns);
+
+  MGeomApply     geomapl;
+
+  // the parameters should be identical to the ones of the extractor
+  MPedCalcPedRun pedcalc;
+  pedcalc.SetRange(0,14,0,14);
+  pedcalc.SetWindowSize( WindowSize, WindowSize);
+
+  MGeomCamMagic  geomcam;
+    
+  tlist1.AddToList(&read);
+  tlist1.AddToList(&geomapl);
+  tlist1.AddToList(&pedcalc);
+
+  // Create and execute the event looper
+  MEvtLoop pedloop;
+  pedloop.SetParList(&plist1);
+  pedloop.SetDisplay(display);
+
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Eventloop())
+    return;
+  
+  tlist1.PrintStatistics();
+
+  // 
+  // Now the short version: 
+  //
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MJCalibration     calloop;
+  calloop.SetInput(&cruns);
+
+
+//  const MCalibrationCam::PulserColor_t color=MCalibrationCam::kGREEN;
+//cout << "COLOR = " << color << endl;
+
+
+  //calloop.SetColor(color);  // neu
+  //  calloop.SetFullDisplay();
+  //
+  calloop.SetExtractor(&extractor);
+  //
+  // Set the corr. cams:
+  //
+  calloop.SetBadPixels(badcam);
+  //
+  // The next two commands are for the display:
+  //
+  calloop.SetDisplay(display);
+//  calloop.SetFullDisplay(); //new
+  
+  //
+  // Apply rel. time calibration:
+  //
+    //calloop.SetRelTimeCalibration();
+    //calloop.SetTimeExtractor(&timeext);
+  //
+  // Do the event-loop:
+  //
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  
+  if (!calloop.Process(pedcam))
+    return;
+cout << " end of Process " << endl;
+
+  badcam.Print();
+  
+  MBadPixelsCam          &badbad  = calloop.GetBadPixels();
+  MCalibrationChargeCam  &calcam  = calloop.GetCalibrationCam();
+  MCalibrationRelTimeCam &timecam = calloop.GetRelTimeCam();
+  MCalibrationQECam      &qecam   = calloop.GetQECam();
+
+  badbad.Print();
+
+  /************************************************************************/
+  /*                THIRD LOOP: DATA CALIBRATION INTO PHOTONS             */
+  /************************************************************************/
+
+
+  // First: a small loop to calculate the pedestals from the data for the first some events
+
+
+  // Create an empty Parameter List and an empty Task List
+
+
+  MParList plist3a;
+  MTaskList tlist3a;
+  plist3a.AddToList(&tlist3a);
+  
+  MPedestalCam        pedcamdata;
+  pedcamdata.SetName("MPedestalCamFromData");
+ 
+
+  plist3a.AddToList(&pedcamdata);
+ 
+
+  MRawRunHeader       runhead3a;
+  plist3a.AddToList(&geomcam );
+  plist3a.AddToList(&runhead3a);
+
+
+   
+  //tasks
+ 
+  MPedCalcFromLoGain peddatacalc;
+ 
+
+  peddatacalc.SetPedContainerName("MPedestalCamFromData");
+  peddatacalc.SetPedestalUpdate(kFALSE);
+  peddatacalc.SetRange( 0, 11, 1, 14);
+  peddatacalc.SetWindowSize( 12, 14);
+  peddatacalc.SetNumEventsDump(500);
+  peddatacalc.SetMaxHiGainVar(40);
+
+ 
+  MReadMarsFile read3a("Events");
+  read3a.DisableAutoScheme();
+  static_cast<MRead&>(read3a).AddFiles(druns);
+  
+  tlist3a.AddToList(&read3a);
+  tlist3a.AddToList(&geomapl);
+  tlist3a.AddToList(&peddatacalc);
+
+
+  MEvtLoop evtloop3a;
+  evtloop3a.SetParList(&plist3a);
+  
+  cout << " event loop over the first 500 data events for pedestal calculation" << endl;
+
+  if ( !evtloop3a.Eventloop(500) )
+    return;
+
+//   if (!evtloop3a.PreProcess())
+//     return;
+  
+//   for (int i=0; i<500; i++){
+//     if (!tlist3a.Process()) break;
+//   }
+  
+//   evtloop3a.PostProcess();
+
+
+  // Now the main third loop for the cosmics and pedestal calibration
+
+
+  MParList  plist3;  
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+ 
+
+  // containers
+ 
+  MCerPhotEvt         photevt;
+  MPedPhotCam         pedphotcam;
+
+  MPedPhotCam         pedphotcamdata;
+  pedphotcamdata.SetName("MPedPhotCamFromData");
+ 
+  MSrcPosCam          srccam;
+  MRawRunHeader       runhead;
+  MExtractedSignalCam sigcam;
+//  MSrcPosCam          pntcam;  //new!
+//  pntcam.SetName("MPntPosCam");
+
+//  MCameraDC     dccam;
+//  MStarCam      starcam;
+
+// changes by wolfgang:
+  MObservatory  obs;
+//  MStarCam      sourcecam;
+//  sourcecam.SetName("MSourceCam");
+//  MHTelAxisFromStars htelaxis;
+  plist3.AddToList(&obs);
+//  plist3.AddToList(&htelaxis);
+//  plist3.AddToList(&sourcecam);
+//  plist3.AddToList(&pntcam);  //new!
+// end changes
+
+  plist3.AddToList(&geomcam );
+  plist3.AddToList(&pedcam);
+  plist3.AddToList(&pedcamdata);
+  plist3.AddToList(&calcam  );
+  plist3.AddToList(&qecam   );
+  plist3.AddToList(&badbad  );
+  plist3.AddToList(&timecam );
+  plist3.AddToList(&sigcam  );
+  plist3.AddToList(&photevt);
+  plist3.AddToList(&pedphotcam);
+  plist3.AddToList(&pedphotcamdata);
+  plist3.AddToList(&srccam);
+  plist3.AddToList(&runhead);
+//  plist3.AddToList(&dccam);
+//  plist3.AddToList(&starcam);
+
+
+  //tasks
+//  MReadMarsFile read3("Events");
+
+  MReadReports read3;
+  read3.AddTree("Currents"); 
+  read3.AddTree("Drive"); 
+  read3.AddTree("Events","MTime.",kTRUE); 
+
+//  read3.DisableAutoScheme();
+  static_cast<MRead&>(read3).AddFiles(druns);
+
+  read3.AddToBranchList("MReportCurrents.*");
+  read3.AddToBranchList("MReportDrive.*");
+  read3.AddToBranchList("MRawCrateArray.*");
+  read3.AddToBranchList("MRawEvtData.*");
+  read3.AddToBranchList("MRawEvtHeader.*");
+
+
+  Float_t mindc = 0.9; //[uA]
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 5;
+  const Short_t x[numblind] = { 47, 124, 470, 475, 571};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 2.5;
+  UInt_t integratedevents = 1;
+
+  // We need the MAGIC mirror geometry from a MC header:
+//  TString geometryfile = "../Mars/Gamma_zbin9_90_7_1480to1489_w0.root";
+  
+    TString geometryfile = "/.magic/magicserv01/MAGIC/mcdata/Period016/spot_1cm/standard/gamma/Gamma_zbin9_90_7_1740to1749_w0.root";
+
+  // We need the Bright Star Catalog:
+
+  // TString catalogfile = "mtemp/mmpi/macros/bsc5.dat";
+  
+  TString catalogfile = "bsc5.dat";
+  
+  MFindStars findstars;
+  // findstars.SetBlindPixels(blindpixels);  ?? WHY?
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+  findstars.SetGeometryFile(geometryfile);
+  findstars.SetBSCFile(catalogfile);
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26);
+  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+//  const Double_t ra  = MAstro::Hms2Rad(20, 0, 0);
+//  const Double_t dec = MAstro::Dms2Rad(20, 48, 0);
+  findstars.SetRaDec(ra,dec);
+  findstars.SetLimMag(8);
+  findstars.SetRadiusFOV(1.5);
+
+
+  //$$$$$$$$$$$$$$$$ ww
+/*
+  MSourceDirections sdirs;
+  sdirs.SetGeometryFile(geometryfile);
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26);
+  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  sdirs.SetRaDec(ra,dec);
+  sdirs.AddDirection(ra,dec,1,"Mkn 421");
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 31);
+  const Double_t dec = MAstro::Dms2Rad(38, 14, 29);
+  sdirs.AddDirection(ra,dec,1,"My_UMa 51");
+  sdirs.SetRadiusFOV(3);
+
+  Int_t InputType=1;
+  MTelAxisFromStars telaxis;
+  telaxis.SetInputType(InputType);
+  MFillH fillhisto("MHTelAxisFromStars[MHTelAxisFromStars]","");
+  htelaxis.SetInputType(InputType);
+*/
+  //$$$$$$$$$$$$$$$$ ww
+
+
+  peddatacalc.SetPedestalUpdate(kTRUE);
+  MArrivalTimeCalc2   timecalc;
+ 
+
+  MCalibrateData      photcalc;     
+  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);  
+  photcalc.EnablePedestalType(MCalibrateData::kEvent);
+  photcalc.EnablePedestalType(MCalibrateData::kRun);
+
+
+  MBadPixelsCalc  badcalc;
+ 
+  MPointingPosCalc pntposcalc;
+//  MPointingPosCalc mpntposcalc;  // not necessary, wolfgang calculates by himself
+  
+  // for the interpolation of the bad pixels comment the following lines in
+  // done in the next step (Analysis.C)
+  /*
+  MBadPixelsTreat badtreat;
+  badtreat.SetUseInterpolation();
+  badtreat.SetProcessRMS();
+  badtreat.SetNumMinNeighbors(int);
+  */
+
+
+  // set the names of the pedestal containers to be used:
+//  extractor.SetNamePedContainer("MPedestalCamFromData");
+  extractor.SetNamePedestalCam("MPedestalCamFromData");
+  timeext.SetNamePedestalCam("MPedestalCamFromData");
+//   photcalc.SetNamePedADCRunContainer("MPedestalCam");
+//   photcalc.SetNamePedADCEventContainer("MPedestalCamFromData");
+//   photcalc.SetNamePedPhotRunContainer("MPedPhotCam");
+//   photcalc.SetNamePedPhotEventContainer("MPedPhotCamFromData");
+  photcalc.SetNamePedADCContainer("MPedestalCamFromData");
+  photcalc.SetNamePedPhotContainer("MPedPhotCamFromData");
+
+  badcalc.SetNamePedPhotContainer("MPedPhotCamFromData");
+
+
+  
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+//  tlist3.AddToList(&dccal,     "Currents");
+//  tlist3.AddToList(&findstars, "Currents");
+//  tlist3.AddToList(&sdirs);
+//  tlist3.AddToList(&telaxis);
+//  tlist3.AddToList(&mpntposcalc);
+  tlist3.AddToList(&pntposcalc);
+//  tlist3.AddToList(&fillhisto);  // changed by wolfgang
+  
+  tlist3.AddToList(&peddatacalc, "Events");
+  tlist3.AddToList(&extractor,   "Events");
+  tlist3.AddToList(&timeext,     "Events");
+  tlist3.AddToList(&photcalc,    "Events");
+  tlist3.AddToList(&badcalc,     "Events");
+ 
+
+  MWriteRootFile write(resname);
+  
+  write.AddContainer("MGeomCam"              , "RunHeaders");
+  write.AddContainer("MRawRunHeader"         , "RunHeaders");
+//  write.AddContainer("MSrcPosCam"            , "RunHeaders");
+  write.AddContainer("MCalibrationChargeCam" , "RunHeaders");
+  write.AddContainer("MCalibrationQECam"     , "RunHeaders");
+  write.AddContainer("MCalibrationRelTimeCam", "RunHeaders");
+
+  write.AddContainer("MTime"         ,      "Events");
+  write.AddContainer("MPedestalCam"  ,      "Events");
+  write.AddContainer("MPedestalCamFromData","Events");
+  write.AddContainer("MCerPhotEvt"   ,      "Events");
+  write.AddContainer("MRawEvtHeader" ,      "Events");
+  write.AddContainer("MBadPixelsCam" ,      "Events");
+  write.AddContainer("MPedPhotCamFromData", "Events");
+  write.AddContainer("MArrivalTimeCam",     "Events");
+  
+//  write.AddContainer("MStarCam",            "Events");
+  write.AddContainer("MSrcPosCam",          "Events");
+
+  write.AddContainer("MReportDrive",         "Events");  //new
+//  write.AddContainer("MPntPosCam",           "Events"); 
+  write.AddContainer("MPointingPos",         "Events"); 
+
+  tlist3.AddToList(&write);
+  
+  // Create and execute eventloop
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+    
+  cout << "*************************************************************" << endl;
+  cout << "***   COMPUTING DATA USING EXTRACTED SIGNAL (IN PHOTONS)  ***" << endl;
+  cout << "*************************************************************" << endl;
+
+  int maxevents = 3000;
+  
+  if (!evtloop3.Eventloop(maxevents))  
+    return;  
+  tlist3.PrintStatistics();
+
+// changes by wolfgang
+//  TObject *obj = plist3.FindObject("MHTelAxisFromStars");
+//  obj->DrawClone();
+
+}
+
+void CamDraw(TCanvas &c, MHCamera &cam, MCamEvent &evt, Int_t i, Int_t j, Int_t fit)
+{
+
+  c.cd(i);
+  gPad->SetBorderMode(0);
+  MHCamera *obj1=(MHCamera*)cam.DrawCopy("hist");
+  //  obj1->AddNotify(evt);
+  
+  c.cd(i+j);
+  gPad->SetBorderMode(0);
+  obj1->Draw();
+  ((MHCamera*)obj1)->SetPrettyPalette();
+
+  if (fit != 0)
+    {
+      c.cd(i+2*j);
+      gPad->SetBorderMode(0);
+      TH1D *obj2 = (TH1D*)obj1->Projection(obj1.GetName());
+      
+//      obj2->Sumw2();
+      obj2->Draw();
+      obj2->SetBit(kCanDelete);
+
+      const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+      const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+      const Double_t integ = obj2->Integral("width")/2.5066283;
+      const Double_t mean  = obj2->GetMean();
+      const Double_t rms   = obj2->GetRMS();
+      const Double_t width = max-min;
+
+      if (rms == 0. || width == 0. )
+        return;
+      
+      switch (fit)
+        {
+        case 1:
+          TF1 *sgaus = new TF1("sgaus","gaus(0)",min,max);
+          sgaus->SetBit(kCanDelete);
+          sgaus->SetParNames("Area","#mu","#sigma");
+          sgaus->SetParameters(integ/rms,mean,rms);
+          sgaus->SetParLimits(0,0.,integ);
+          sgaus->SetParLimits(1,min,max);
+          sgaus->SetParLimits(2,0,width/1.5);
+          obj2->Fit("sgaus","QLR");
+          obj2->GetFunction("sgaus")->SetLineColor(kYellow);
+          break;
+
+        case 2:
+          TString dgausform = "([0]-[3])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])";
+          dgausform += "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
+          TF1 *dgaus = new TF1("dgaus",dgausform.Data(),min,max);
+          dgaus->SetBit(kCanDelete);
+          dgaus->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}","A_{2}","#mu_{2}","#sigma_{2}");
+          dgaus->SetParameters(integ,(min+mean)/2.,width/4.,
+                               integ/width/2.,(max+mean)/2.,width/4.);
+          // The left-sided Gauss 
+          dgaus->SetParLimits(0,integ-1.5,integ+1.5);
+          dgaus->SetParLimits(1,min+(width/10.),mean);
+          dgaus->SetParLimits(2,0,width/2.);
+          // The right-sided Gauss 
+          dgaus->SetParLimits(3,0,integ);
+          dgaus->SetParLimits(4,mean,max-(width/10.));
+          dgaus->SetParLimits(5,0,width/2.);
+          obj2->Fit("dgaus","QLRM");
+          obj2->GetFunction("dgaus")->SetLineColor(kYellow);
+          break;
+          
+        case 3:
+          TString tgausform = "([0]-[3]-[6])/[2]*exp(-0.5*(x-[1])*(x-[1])/[2]/[2])";
+          tgausform += "+[3]/[5]*exp(-0.5*(x-[4])*(x-[4])/[5]/[5])";
+          tgausform += "+[6]/[8]*exp(-0.5*(x-[7])*(x-[7])/[8]/[8])";
+          TF1 *tgaus = new TF1("tgaus",tgausform.Data(),min,max);
+          tgaus->SetBit(kCanDelete);
+          tgaus->SetParNames("A_{tot}","#mu_{1}","#sigma_{1}",
+                             "A_{2}","#mu_{2}","#sigma_{2}",
+                             "A_{3}","#mu_{3}","#sigma_{3}");
+          tgaus->SetParameters(integ,(min+mean)/2,width/4.,
+                               integ/width/3.,(max+mean)/2.,width/4.,
+                               integ/width/3.,mean,width/2.);
+          // The left-sided Gauss 
+          tgaus->SetParLimits(0,integ-1.5,integ+1.5);
+          tgaus->SetParLimits(1,min+(width/10.),mean);
+          tgaus->SetParLimits(2,width/15.,width/2.);
+          // The right-sided Gauss 
+          tgaus->SetParLimits(3,0.,integ);
+          tgaus->SetParLimits(4,mean,max-(width/10.));
+          tgaus->SetParLimits(5,width/15.,width/2.);
+          // The Gauss describing the outliers
+          tgaus->SetParLimits(6,0.,integ);
+          tgaus->SetParLimits(7,min,max);
+          tgaus->SetParLimits(8,width/4.,width/1.5);
+          obj2->Fit("tgaus","QLRM");
+          obj2->GetFunction("tgaus")->SetLineColor(kYellow);
+          break;
+        case 4:
+          obj2->Fit("pol0","Q");
+          obj2->GetFunction("pol0")->SetLineColor(kYellow);
+          break;
+        case 9:
+          break;
+        default:
+          obj2->Fit("gaus","Q");
+          obj2->GetFunction("gaus")->SetLineColor(kYellow);
+          break;
+        }
+      
+        TArrayI s0(3);
+        s0[0] = 6;
+        s0[1] = 1;
+        s0[2] = 2;
+
+        TArrayI s1(3);
+        s1[0] = 3;
+        s1[1] = 4;
+        s1[2] = 5;
+
+        TArrayI inner(1);
+        inner[0] = 0;
+
+        TArrayI outer(1);
+        outer[0] = 1;
+
+        // Just to get the right (maximum) binning
+        TH1D *half[4];
+        half[0] = obj1->ProjectionS(s0, inner, "Sector 6-1-2 Inner");
+        half[1] = obj1->ProjectionS(s1, inner, "Sector 3-4-5 Inner");
+        half[2] = obj1->ProjectionS(s0, outer, "Sector 6-1-2 Outer");
+        half[3] = obj1->ProjectionS(s1, outer, "Sector 3-4-5 Outer");
+
+        for (int i=0; i<4; i++)      
+        {
+            half[i]->SetLineColor(kRed+i);
+            half[i]->SetDirectory(0);
+            half[i]->SetBit(kCanDelete);
+            half[i]->Draw("same");
+        }
+
+      gPad->Modified();
+      gPad->Update();
+      
+    }
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/calibration_shape.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/calibration_shape.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/calibration_shape.C	(revision 9772)
@@ -0,0 +1,380 @@
+/* ======================================================================== *\
+!  
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MAGIC.h"
+
+
+const TString pedfile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12149_P_Cab-On_E.root";
+const TString calfile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12526_C_Cab-On_E.root";
+const TString datafile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12517_D_Cab-On_E.root";
+
+Int_t pedr = 36038;
+Int_t calr = 36042;
+//Int_t datar = 12517;
+
+
+
+void calibration_shape(const TString inpath = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_06/", Int_t pedruns = pedr, Int_t calruns = calr, Int_t ipix=316)
+
+{
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  
+  pruns.AddRun(pedruns,inpath);
+ 
+  cruns.AddRun(calruns,inpath);
+  
+ 
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MParList plist1;
+  MTaskList tlist1;
+  plist1.AddToList(&tlist1);
+  
+  // containers
+  MPedestalCam   pedcam;
+  MBadPixelsCam  badcam;
+
+ 
+  plist1.AddToList(&pedcam);
+  plist1.AddToList(&badcam);
+    
+  //tasks
+  MReadMarsFile  read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(pruns);
+
+  MGeomApply     geomapl;
+  // MPedCalcPedRun pedcalc;
+  MPedCalcFromLoGain pedcalc_ped;
+  pedcalc_ped.SetMaxHiGainVar(20);
+  pedcalc_ped.SetRange(0, 11, 1, 14);
+  pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+ 
+
+
+  MGeomCamMagic  geomcam;
+    
+  tlist1.AddToList(&read);
+  tlist1.AddToList(&geomapl);
+  tlist1.AddToList(&pedcalc_ped);
+
+  // Create and execute the event looper
+  MEvtLoop pedloop;
+  pedloop.SetParList(&plist1);
+ 
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Eventloop())
+    return;
+  
+  tlist1.PrintStatistics();
+
+ 
+
+  //
+  // Create a empty Parameter List and an empty Task List 
+  //
+  MParList  plist2;
+  MTaskList tlist2;
+  plist2.AddToList(&tlist2);
+  plist2.AddToList(&pedcam);
+  plist2.AddToList(&badcam);
+  
+   
+  MReadMarsFile read2("Events");
+  read2.DisableAutoScheme();
+  static_cast<MRead&>(read2).AddFiles(cruns);
+  
+  MGeomCamMagic              geomcam;
+  MExtractedSignalCam        sigcam;
+  MArrivalTimeCam            timecam;
+  MRawEvtData                evtdata;
+  
+  //
+  // Get the previously created MPedestalCam into the new Parameter List 
+  //
+  plist2.AddToList(&geomcam);
+  plist2.AddToList(&sigcam);
+  plist2.AddToList(&timecam);
+  plist2.AddToList(&evtdata);
+  
+  //
+  // We saw that the signal jumps between slices, 
+  // thus take the sliding window
+  //		
+  
+  MGeomApply             geomapl;
+  
+  
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+  
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+  
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  //timeext.SetWindowSize(10,10);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+  
+  
+  // timecalc->SetRange(8,14,8,14,6);
+  
+  // filter against cosmics
+  MFCosmics            cosmics;
+  MContinue            cont(&cosmics);
+  
+  tlist2.AddToList(&read2);
+  tlist2.AddToList(&geomapl);
+  tlist2.AddToList(&extractor);
+  tlist2.AddToList(&timeext);
+  
+  //
+  // In case, you want to skip the cosmics rejection, 
+  // uncomment the next line
+  //
+  tlist2.AddToList(&cont);
+  //
+  // In case, you want to skip the somewhat lengthy calculation
+  // of the arrival times using a spline, uncomment the next two lines
+  //
+  
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist2);
+  //    evtloop.SetDisplay(display);
+    
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  
+  //
+  // Execute second analysis
+  //
+  
+  
+  if (!evtloop.PreProcess())
+    return;
+  
+  int count = 1; 
+  
+  TH2F * shape = new TH2F("shape","shape",300,0,30,1000,-20,250);
+  TH2F * shape_corr = new TH2F("shape_corr","shape_corr",300,0,30,1000,-20,250);
+  TH2F * shape_corr_all = new TH2F("shape_corr_all","shape_corr_all",300,0,30,1000,-20,250);
+  TH1F * htime = new TH1F("htime","htime",150,0,15);
+  TH1F * hsig = new TH1F("hsig","hsig",300,-50,550);
+  
+  //   cout << " hello " << endl;
+  
+  const Float_t ped_mean = pedcam[ipix].GetPedestal();
+  const Float_t pedRMS   = pedcam[ipix].GetPedestalRms();
+  
+  while (tlist2.Process()){ //loop over the events  
+    
+    count++;
+    
+    if (count%1000==0)  cout << "Event #" <<  count << endl;  
+    
+    MRawEvtPixelIter pixel(&evtdata);
+    
+
+    double value = 0;
+    pedcam.GetPixelContent(value, ipix, geomcam, 0);
+    
+	
+    double time = 0;
+    timecam.GetPixelContent(time, ipix, geomcam, 0);  // was 0)
+    
+    double sig = 0;
+    sigcam.GetPixelContent(sig, ipix, geomcam, 0);
+    
+    Byte_t sat = (sigcam)[ipix].GetNumHiGainSaturated();
+
+
+    htime->Fill(time);
+    hsig->Fill(sig);
+    
+  
+    pixel.Jump(ipix);
+	
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+    const Int_t nh = evtdata.GetNumHiGainSamples();
+    const Int_t nl = evtdata.GetNumLoGainSamples(); 
+	
+    Bool_t ABFlag = pixel.HasABFlag();
+	
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+    
+    const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+    
+   
+    Float_t PedMean[2];
+    PedMean[0] = ped_mean + ABoffs;
+    PedMean[1] = ped_mean - ABoffs; 
+    
+    
+      
+	  
+    for (int sample=0; sample<nh; sample++){
+      shape->Fill(sample+0.5,higains[sample]-PedMean[(sample+ABFlag)&0x1]);
+      shape->Fill(sample+15.5,logains[sample]-PedMean[(sample+ABFlag)&0x1]);
+      shape_corr->Fill(sample+0.5+5.-time,higains[sample]-PedMean[(sample+ABFlag)&0x1]);
+      shape_corr->Fill(sample+15.5+5.-time,logains[sample]-PedMean[(sample+nh+ABFlag)&0x1]);
+      if (sat==0){
+	shape_corr_all->Fill(sample+0.5+5.-time,(higains[sample]-PedMean[(sample+ABFlag)&0x1])/sig*250);
+	shape_corr_all->Fill(sample+15.5+5.-time,(logains[sample]-PedMean[(sample+nh+ABFlag)&0x1])/sig*250);
+      }
+    }
+	
+	
+  } // end loop over the entries
+    
+  tlist2.PrintStatistics();
+  
+  
+  TCanvas * c_shape = new TCanvas("c_shape","c_shape",600,400);
+  c_shape->SetFillColor(0);
+  c_shape->SetBorderMode(0);
+  c_shape->SetGridx();
+  c_shape->SetGridy();
+  shape->SetStats(0);
+  TString title2 = "Raw Calibration Signal Shape, Pixel ";
+  title2+=ipix;
+  shape->SetTitle(title2);
+  shape->SetXTitle("FADC sample no.");
+  shape->SetYTitle("signal [FADC counts]");
+  shape->SetMarkerStyle(20);
+  shape->SetMarkerColor(4);
+  shape->SetMarkerSize(0.3);
+  shape->Draw();
+
+  
+  TCanvas * c_shape_corr = new TCanvas("c_shape_corr","c_shape_corr",600,400);
+  c_shape_corr->SetFillColor(0);
+  c_shape_corr->SetBorderMode(0);
+  c_shape_corr->SetGridx();
+  c_shape_corr->SetGridy();
+  shape_corr->SetStats(0);
+  TString title3 = "Calibration Signal Shape, Arrival Time Corrected, Pixel ";
+  title3+=ipix;
+  shape_corr->SetTitle(title3);
+  shape_corr->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr->SetYTitle("signal [FADC counts]");
+  shape_corr->SetMarkerStyle(20);
+  shape_corr->SetMarkerColor(4);
+  shape_corr->SetMarkerSize(0.3);
+  shape_corr->Draw();
+
+
+  TCanvas * c_shape_corr_all = new TCanvas("c_shape_corr_all","c_shape_corr_all",600,400);
+  c_shape_corr_all->SetFillColor(0);
+  c_shape_corr_all->SetBorderMode(0);
+  c_shape_corr_all->SetGridx();
+  c_shape_corr_all->SetGridy();
+  shape_corr_all->SetStats(0);
+  TString title3 = "Calibration Signal Shape, Arrival Time + Amplitude Corrected, Pixel ";
+  title3+=ipix;
+  shape_corr_all->SetTitle(title3);
+  shape_corr_all->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr_all->SetYTitle("signal  [a.u.]");
+  shape_corr_all->SetMarkerStyle(20);
+  shape_corr_all->SetMarkerColor(4);
+  shape_corr_all->SetMarkerSize(0.3);
+  shape_corr_all->Draw();
+ 
+  
+
+
+  TCanvas * c_sig = new TCanvas("c_sig","c_sig",600,400);
+  c_sig->SetFillColor(0);
+  c_sig->SetBorderMode(0);
+  c_sig->SetGridx();
+  c_sig->SetGridy();
+
+  hsig->SetStats(0);
+  TString title4 = "Calibration Extracted Charge, MExtractFixedWindowPeakSearch, Pixel ";
+  title4+=ipix;
+  hsig->SetTitle(title4);
+  hsig->SetXTitle("reco charge [FADC counts]");
+  hsig->SetYTitle("events / 2 FADC counts");
+  hsig->SetLineColor(4);
+  hsig->SetLineWidth(2);
+  hsig->Draw();
+
+  TCanvas * c_time = new TCanvas("c_time","c_time",600,400);
+  c_time->SetFillColor(0);
+  c_time->SetBorderMode(0);
+  c_time->SetGridx();
+  c_time->SetGridy();
+
+  htime->SetStats(0);
+  TString title5 = "Calibration Arrival Time, MExtractTimeHighestIntegral, Pixel ";
+  title5+=ipix;
+  htime->SetTitle(title5);
+  htime->SetXTitle("arrival time [T_{ADC}]");
+  htime->SetYTitle("events / 0.1 T_{ADC}");
+  htime->SetLineColor(4);
+  htime->SetLineWidth(2);
+  htime->Draw();
+
+
+  TCanvas * c7 = new TCanvas("c7","c7",600,400);
+  c7->cd();
+  c7->SetGridx();
+  c7->SetGridy();
+  c7->SetFillColor(0);
+  //  c7->SetBordermode(0);
+    
+  TProfile * shape_corr_all_pfx = (TProfile*)shape_corr_all->ProfileX();
+  
+  shape_corr_all_pfx->SetStats(0);
+  TString title6 = "Average Calibration Signal Shape, Amplitude + Arrival Time Corrected, Pixel";
+  title6+=ipix;
+  shape_corr_all_pfx->SetTitle(title6);
+  shape_corr_all_pfx->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr_all_pfx->SetYTitle("signal [a.u.]");
+  shape_corr_all_pfx->SetMarkerStyle(20);
+  shape_corr_all_pfx->SetMarkerColor(4);
+  shape_corr_all_pfx->SetMarkerSize(0.5);
+  shape_corr_all_pfx->Draw();
+}
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/callalphaplot.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/callalphaplot.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/callalphaplot.C	(revision 9772)
@@ -0,0 +1,1271 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cherenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Daniel Mazin, 05/2004 <mailto:mazin@imppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+// Daniel Mazin 18.05.2004  mazin@mppmu.mpg.de
+// **********************************************************************************
+// this macro is used to produce an alpha plot/plots for a chosen position in the sky map.
+// In case of several subsamples, the overall alpha plot is also produced.
+// The derotation is possible if Zd and Az are available for each event.
+// Using of OFF data to estimate Nex and Significance is optional (if such data available)
+//
+// input: hillas parameter file/files
+//      optional: a) ascii file with the estimated position of the source
+//                b) ascii file with fit parameters from the OFF sample 
+//                                  (needed for estimation of the background from OFF dada)
+// output: alpha plot for each subsample, overall alpha plot
+// **********************************************************************************
+
+
+#define XSOUR   0.05  // [deg]
+#define YSOUR   0.6  // [deg]
+#define NUM     0
+
+
+TString sourcename = "M87On";
+
+const Bool_t ROTOPTION  = kFALSE;  // kFALSE: do not derotate, use camera coordinates
+                                  // kTRUE: derotate into "quasi" sky coordinates
+
+const Bool_t USEOFFDATA = kFALSE; // kFALSE: do not use OFF data to estimate the significance
+                                  // kTRUE: use in addition OFF data to estimate the significance
+
+const char * offfile = "paramOffCrab2701.dat"; // file with parameters of the OFF sample
+                                               // needed only if USEOFFDATA = kTRUE
+
+const Bool_t USEFILE = kFALSE; // kFALSE : use XSOUR, YSOUR 
+                               // kTRUE: use "posfile" 
+                               // to specify the position for which alpha plot has to be produced
+
+const Bool_t SAMPLES = kFALSE; // kFALSE: one sample only
+                               // kTRUE: several samples, usage of posfile is preferred!  
+
+const char * posfile = "data/trackCrab1502_1305_Berlin_5deg.dat"; // file with best position
+                                                                  // if USEFILE == kFALSE : not needed
+
+TString dirname  = "~/data/M87/2004_02_17/";
+TString filename = "M87HillasON.root"; //  NOTE in case of several subsamples (SAMPLES=kTRUE)
+                                         // folllowing name construction is assumed:
+                                         // file = dirname + sample + <number> + / + filename
+                                         // e.g: ~/data/Crab/2004_01_27/sample2/CrabHillasON.root
+#define tolerance 1e-3
+/* ******************************************************   */
+      /*  dynamical cuts  Crab 27th Jan 2004 */
+/*
+#define LENGTHMINParA 0.136  // deg
+#define LENGTHMINParB 0.036  //
+#define LENGTHMINParC -0.0038  //
+#define LENGTHMAXParA 0.332  // deg
+#define LENGTHMAXParB 0.037  //
+#define LENGTHMAXParC 0.0261 //
+#define WIDTHMINParA  0.063  // deg
+#define WIDTHMINParB  0.013  //
+#define WIDTHMINParC  0.0003  //
+#define WIDTHMAXParA  0.123  // deg
+#define WIDTHMAXParB  0.019  //
+#define WIDTHMAXParC  0.0005 //
+#define DISTMINParA   0.6   // deg
+#define DISTMINParB   0.059  //
+#define DISTMINParC   0.  //
+#define DISTMAXParA   1.25   // deg
+#define DISTMAXParB   0.059  //
+#define DISTMAXParC   0.  //
+*/
+
+      /*  dynamical cuts  Mrk 421 and Crab 15th Feb 2004 */
+
+#define LENGTHMINParA 0.12  // deg
+#define LENGTHMINParB 0.034  //
+#define LENGTHMINParC 0.  //
+#define LENGTHMAXParA 0.32  // deg
+#define LENGTHMAXParB 0.034  //
+#define LENGTHMAXParC 0. //
+#define WIDTHMINParA  0.055  // deg
+#define WIDTHMINParB  0.013  //
+#define WIDTHMINParC  0.0  //
+#define WIDTHMAXParA  0.12  // deg
+#define WIDTHMAXParB  0.013  //
+#define WIDTHMAXParC  0.0 //
+#define DISTMINParA   0.6   // deg
+#define DISTMINParB   0.059  //
+#define DISTMINParC   0.  //
+#define DISTMAXParA   1.25   // deg
+#define DISTMAXParB   0.059  //
+#define DISTMAXParC   0.  //
+
+
+#define SIZEMIN 2000
+#define LEAKMAX 0.25
+#define ASYMMIN  -0.1 
+
+#include "mtools.C"
+
+#define ALPHAMAX 15.
+
+#define ALOFFMAX 90.
+#define ALOFFMIN 30.
+
+// histogram to store the sum of alpha plots
+   TH1F histalphaAll("alpha plot", "alpha plot, size cut 2000, 15 deg", 36, 0., 90.);
+   histalphaAll.SetXTitle("alpha (deg)");
+   histalphaAll.SetYTitle("Counts");
+   histalphaAll.SetDirectory(NULL);
+   histalphaAll.SetFillStyle(4000);
+   histalphaAll.UseCurrentStyle();
+
+
+void alphaplots(Int_t num, Double_t XSOURCE, Double_t YSOURCE)
+{
+
+// for USEOFFDATA = kTRUE the ascii file with fit parameters of the OFF sample is read.
+
+   if (USEOFFDATA == kTRUE)
+   {
+	    Int_t event, dummy, numbinsoff;
+	    Float_t binwidthOff, xpos, ypos, aparOff, bparOff, chi2par;
+
+	    FILE *fp;
+	    fp = fopen(offfile,"r");    
+	    while(fscanf(fp,"%d %f %f %f %f %f %f %f %f %f",
+		       &event, &xpos, &ypos,  &aparOff, &bparOff, &chi2par,
+		       &binwidthOff, &dummy, &dummy, &dummy) != EOF)
+	    {
+//cout << event << " " << xpos << " " << ypos << endl;
+		     if(TMath::Abs(xpos-XSOURCE) < tolerance && TMath::Abs(ypos-YSOURCE) < tolerance) break;
+	    }
+	    fclose(fp);
+   }
+
+
+    gStyle->SetCanvasBorderMode(0);
+    gStyle->SetCanvasBorderSize(0);
+    gStyle->SetCanvasColor(10);
+    gStyle->SetPadBorderMode(0);
+    gStyle->SetPadBorderSize(0);
+    gStyle->SetPadColor(10);
+    gStyle->SetOptFit(1);
+    gStyle->SetStatColor(10);
+//    gStyle->SetOptStat(0);
+    gStyle->SetPalette(1,0);
+
+
+
+// the name of the Hillas parameter file, which has to be read in
+    TString ddumy;
+
+    if (SAMPLES == kFALSE)
+        filename = dirname + filename;
+    else
+    {
+       ddumy = dirname;
+       ddumy += "sample"; 
+       ddumy += num; 
+       filename = ddumy + filename; 
+    }
+
+cout << "file to read :" << filename << endl;
+
+
+// create histograms   
+    MBinning bins;
+
+   TH1F histlength;
+   histlength.SetName("Length");
+   histlength.SetTitle("Length");
+   histlength.SetXTitle("Length [deg]");
+   histlength.SetYTitle("Counts");
+   histlength.SetDirectory(NULL);
+   histlength.SetFillStyle(4000);
+   histlength.UseCurrentStyle(); 
+
+
+    bins.SetEdges(100, 0., 1.);
+    bins.Apply(histlength);
+
+
+   TH1F histwidth;
+   histwidth.SetName("Width");
+   histwidth.SetTitle("Width");
+   histwidth.SetXTitle("Width [deg]");
+   histwidth.SetYTitle("Counts");
+   histwidth.SetDirectory(NULL);
+   histwidth.SetFillStyle(4000);
+   histwidth.UseCurrentStyle(); 
+
+    bins.SetEdges(100, 0., 0.5);
+    bins.Apply(histwidth);
+
+
+   TH1F histsize;
+   histsize.SetName("Size");
+   histsize.SetTitle("Size");
+   histsize.SetXTitle("Size");
+   histsize.SetYTitle("Counts");
+   histsize.SetDirectory(NULL);
+   histsize.SetFillStyle(4000);
+   histsize.UseCurrentStyle(); 
+
+//    bins.SetEdges(100, 100., 2e5);
+//    bins.Apply(histsize);
+
+    bins.SetEdgesLog(100, 100., 10e5);
+    bins.Apply(histsize);
+
+   TH1F histalpha;
+   histalpha.SetName("Alpha");
+   histalpha.SetTitle("Alpha");
+   histalpha.SetXTitle("Alpha [deg]");
+   histalpha.SetYTitle("Counts");
+   histalpha.SetDirectory(NULL);
+   histalpha.SetFillStyle(4000);
+   histalpha.UseCurrentStyle(); 
+
+    bins.SetEdges(100, -100., 100.);
+    bins.Apply(histalpha);
+
+   TH1F histdist;
+   histdist.SetName("Dist");
+   histdist.SetTitle("Dist");
+   histdist.SetXTitle("Dist [deg]");
+   histdist.SetYTitle("Counts");
+   histdist.SetDirectory(NULL);
+   histdist.SetFillStyle(4000);
+   histdist.UseCurrentStyle(); 
+
+    bins.SetEdges(100, 0., 2.);
+    bins.Apply(histdist);
+
+   TH1F histmeanx;
+   histmeanx.SetName("MeanX");
+   histmeanx.SetTitle("MeanX");
+   histmeanx.SetXTitle("MeanX [deg]");
+   histmeanx.SetYTitle("Counts");
+   histmeanx.SetDirectory(NULL);
+   histmeanx.SetFillStyle(4000);
+   histmeanx.UseCurrentStyle(); 
+
+    bins.SetEdges(100, -1.8, 1.8);
+    bins.Apply(histmeanx);
+
+   TH1F histmeany;
+   histmeany.SetName("MeanY");
+   histmeany.SetTitle("MeanY");
+   histmeany.SetXTitle("MeanY [deg]");
+   histmeany.SetYTitle("Counts");
+   histmeany.SetDirectory(NULL);
+   histmeany.SetFillStyle(4000);
+   histmeany.UseCurrentStyle(); 
+
+
+    bins.SetEdges(100, -1.8, 1.8);
+    bins.Apply(histmeany);
+
+   TH1F histalphafinal;
+   histalphafinal.SetName("ALPHA");
+   histalphafinal.SetTitle("ALPHA");
+   histalphafinal.SetXTitle("alpha [deg]");
+   histalphafinal.SetYTitle("Counts");
+   histalphafinal.SetDirectory(NULL);
+   histalphafinal.SetFillStyle(4000);
+   histalphafinal.UseCurrentStyle(); 
+
+    bins.SetEdges(36, 0.0, 90.);
+    bins.Apply(histalphafinal);
+
+   TH1F histAssym;
+   histAssym.SetName("Assymetry");
+   histAssym.SetTitle("Assymetry");
+   histAssym.SetXTitle("Assymetry");
+   histAssym.SetYTitle("Counts");
+   histAssym.SetDirectory(NULL);
+   histAssym.SetFillStyle(4000);
+   histAssym.UseCurrentStyle(); 
+
+    bins.SetEdges(100, -1, 1.);
+    bins.Apply(histAssym);
+
+   TH1F histAssymM3;
+   histAssymM3.SetName("Assymetry 3M");
+   histAssymM3.SetTitle("Assymetry 3rd moment");
+   histAssymM3.SetXTitle("Assymetry 3rd moment");
+   histAssymM3.SetYTitle("Counts");
+   histAssymM3.SetDirectory(NULL);
+   histAssymM3.SetFillStyle(4000);
+   histAssymM3.UseCurrentStyle(); 
+
+    bins.SetEdges(100, -1., 1.);
+    bins.Apply(histAssymM3);
+
+   TH2F hist2xy("CoG","Center of Gravity", 100, -1.8, 1.8, 100, -1.8, 1.8);
+   hist2xy.SetXTitle("MeanX [deg]");
+   hist2xy.SetYTitle("MeanY [deg]");
+   hist2xy.SetDirectory(NULL);
+   hist2xy.SetFillStyle(4000);
+   hist2xy.UseCurrentStyle();
+ 
+   TH1F histLoverS;
+   histLoverS.SetName("LoverS");
+   histLoverS.SetTitle("LoverS");
+   histLoverS.SetXTitle("LoverS");
+   histLoverS.SetYTitle("Counts");
+   histLoverS.SetDirectory(NULL);
+   histLoverS.SetFillStyle(4000);
+   histLoverS.UseCurrentStyle(); 
+
+    bins.SetEdges(100, -0., 0.0006);
+    bins.Apply(histLoverS);
+
+   TH2F hist2lw("Length-Width", "correlation Length-Width", 100, 0.0, 1.0, 100, 0.0, 0.5);
+   hist2lw.SetXTitle("Length [deg]");
+   hist2lw.SetYTitle("Width [deg]");
+   hist2lw.SetDirectory(NULL);
+   hist2lw.SetFillStyle(4000);
+   hist2lw.UseCurrentStyle();
+ 
+   TH2F hist2lalpha("Length-Alpha", "correlation Length-Alpha", 100, 0.0, 1.0, 100, -100., 100.);
+   hist2lalpha.SetXTitle("Length [deg]");
+   hist2lalpha.SetYTitle("Alpha [deg]");
+   hist2lalpha.SetDirectory(NULL);
+   hist2lalpha.SetFillStyle(4000);
+   hist2lalpha.UseCurrentStyle();
+ 
+   TH2F hist2ldist("Length-Dist","correlation Length-Dist", 100, 0.0, 1.0, 100, 0.0, 1.7);
+   hist2ldist.SetXTitle("Length [deg]");
+   hist2ldist.SetYTitle("Dist [deg]");
+   hist2ldist.SetDirectory(NULL);
+   hist2ldist.SetFillStyle(4000);
+   hist2ldist.UseCurrentStyle();
+ 
+   TH2F hist2walpha("Width-Alpha","correlation Width-Alpha", 100, 0.0, 0.5, 100, -100., 100.);
+   hist2walpha.SetXTitle("Width [deg]");
+   hist2walpha.SetYTitle("Alpha [deg]");
+   hist2walpha.SetDirectory(NULL);
+   hist2walpha.SetFillStyle(4000);
+   hist2walpha.UseCurrentStyle();
+ 
+   TH2F hist2wdist("Width-Dist","correlation Width-Dist", 100, 0.0, 0.5, 100, 0.0, 1.7);
+   hist2wdist.SetXTitle("Width [deg]");
+   hist2wdist.SetYTitle("Dist [deg]");
+   hist2wdist.SetDirectory(NULL);
+   hist2wdist.SetFillStyle(4000);
+   hist2wdist.UseCurrentStyle();
+ 
+   TH2F hist2alphadist("Alpha-Dist","correlation Alpha-Dist", 100, -100., 100, 100, 0.0, 1.7);
+   hist2alphadist.SetXTitle("Alpha [deg]");
+   hist2alphadist.SetYTitle("Dist [deg]");
+   hist2alphadist.SetDirectory(NULL);
+   hist2alphadist.SetFillStyle(4000);
+   hist2alphadist.UseCurrentStyle();
+ 
+   TH1F histphi;
+   histphi.SetName("TelPhia");
+   histphi.SetTitle("Telescope Phi");
+   histphi.SetXTitle("Phi [rad]");
+   histphi.SetYTitle("Counts");
+   histphi.SetDirectory(NULL);
+   histphi.SetFillStyle(4000);
+   histphi.UseCurrentStyle(); 
+
+    bins.SetEdges(100, -10, 10);
+    bins.Apply(histphi);
+
+   TH1F histtheta;
+   histtheta.SetName("TelTheta");
+   histtheta.SetTitle("Telescope Theta");
+   histtheta.SetXTitle("Theta [rad]");
+   histtheta.SetYTitle("Counts");
+   histtheta.SetDirectory(NULL);
+   histtheta.SetFillStyle(4000);
+   histtheta.UseCurrentStyle(); 
+
+    bins.SetEdges(100, -2, 2.);
+    bins.Apply(histtheta);
+
+   TH1F aftercuthistlength;
+   aftercuthistlength.SetName("Length");
+   aftercuthistlength.SetTitle("Length");
+   aftercuthistlength.SetXTitle("Length [deg]");
+   aftercuthistlength.SetYTitle("Counts");
+   aftercuthistlength.SetDirectory(NULL);
+   aftercuthistlength.SetFillStyle(4000);
+   aftercuthistlength.UseCurrentStyle();
+
+
+    bins.SetEdges(100, 0., 1.);
+    bins.Apply(aftercuthistlength);
+
+   TH1F aftercuthistwidth;
+   aftercuthistwidth.SetName("Width");
+   aftercuthistwidth.SetTitle("Width");
+   aftercuthistwidth.SetXTitle("Width [deg]");
+   aftercuthistwidth.SetYTitle("Counts");
+   aftercuthistwidth.SetDirectory(NULL);
+   aftercuthistwidth.SetFillStyle(4000);
+   aftercuthistwidth.UseCurrentStyle();
+
+    bins.SetEdges(100, 0., 0.5);
+    bins.Apply(aftercuthistwidth);
+
+   TH1F aftercuthistsize;
+   aftercuthistsize.SetName("Size");
+   aftercuthistsize.SetTitle("Size");
+   aftercuthistsize.SetXTitle("Size [photons]");
+   aftercuthistsize.SetYTitle("Counts");
+   aftercuthistsize.SetDirectory(NULL);
+   aftercuthistsize.SetFillStyle(4000);
+   aftercuthistsize.UseCurrentStyle();
+
+    bins.SetEdgesLog(100, 100., 10e5);
+    bins.Apply(aftercuthistsize);
+
+   TH1F aftercuthistalpha;
+   aftercuthistalpha.SetName("Alpha");
+   aftercuthistalpha.SetTitle("Alpha");
+   aftercuthistalpha.SetXTitle("Alpha [deg]");
+   aftercuthistalpha.SetYTitle("Counts");
+   aftercuthistalpha.SetDirectory(NULL);
+   aftercuthistalpha.SetFillStyle(4000);
+   aftercuthistalpha.UseCurrentStyle();
+
+    bins.SetEdges(20, 0., 100.);
+    bins.Apply(aftercuthistalpha);
+
+   TH1F aftercuthistdist;
+   aftercuthistdist.SetName("Dist");
+   aftercuthistdist.SetTitle("Dist");
+   aftercuthistdist.SetXTitle("Dist [deg]");
+   aftercuthistdist.SetYTitle("Counts");
+   aftercuthistdist.SetDirectory(NULL);
+   aftercuthistdist.SetFillStyle(4000);
+   aftercuthistdist.UseCurrentStyle();
+
+   bins.SetEdges(100, 0., 2.);
+    bins.Apply(aftercuthistdist);
+
+   TH1F aftercuthistmeanx;
+   aftercuthistmeanx.SetName("MeanX");
+   aftercuthistmeanx.SetTitle("MeanX");
+   aftercuthistmeanx.SetXTitle("MeanX [deg]");
+   aftercuthistmeanx.SetYTitle("Counts");
+   aftercuthistmeanx.SetDirectory(NULL);
+   aftercuthistmeanx.SetFillStyle(4000);
+   aftercuthistmeanx.UseCurrentStyle();
+
+    bins.SetEdges(100, -1.8, 1.8);
+    bins.Apply(aftercuthistmeanx);
+
+   TH1F aftercuthistmeany;
+   aftercuthistmeany.SetName("MeanY");
+   aftercuthistmeany.SetTitle("MeanY");
+   aftercuthistmeany.SetXTitle("MeanY [deg]");
+   aftercuthistmeany.SetYTitle("Counts");
+   aftercuthistmeany.SetDirectory(NULL);
+   aftercuthistmeany.SetFillStyle(4000);
+   aftercuthistmeany.UseCurrentStyle();
+
+
+    bins.SetEdges(100, -1.8, 1.8);
+    bins.Apply(aftercuthistmeany);
+
+   TH2F aftercuthist2xy("CoG","Center of Gravity", 100, -1.8, 1.8, 100, -1.8, 1.8);
+   aftercuthist2xy.SetXTitle("MeanX [deg]");
+   aftercuthist2xy.SetYTitle("MeanY [deg]");
+   aftercuthist2xy.SetDirectory(NULL);
+   aftercuthist2xy.SetFillStyle(4000);
+   aftercuthist2xy.UseCurrentStyle();
+
+
+
+   const Int_t n = 100;
+   Double_t binsize[n];
+
+   Float_t nmin = 100.;
+   Float_t nmax = 1e7;
+
+   for(Int_t i=0; i<n; i++)
+   {
+    binsize[i] = pow(10., log10(nmin) + i * (log10(nmax) - log10(nmin)) / (n-1.));
+   }
+
+   TH2F hist2wsize("Width-Size", "correlation Width-Size", 100, 0.0, 0.5, n-1, binsize);
+   hist2wsize.SetXTitle("Width [deg]");
+   hist2wsize.SetYTitle("Size");
+   hist2wsize.SetDirectory(NULL);
+   hist2wsize.SetFillStyle(4000);
+   hist2wsize.UseCurrentStyle();
+
+
+ 
+   TH2F hist2alphasize("Alpha-Size","correlation Alpha-Size", 100, -100., 100., n-1, binsize);
+   hist2alphasize.SetXTitle("Alpha [deg]");
+   hist2alphasize.SetYTitle("Size");
+   hist2alphasize.SetDirectory(NULL);
+   hist2alphasize.SetFillStyle(4000);
+   hist2alphasize.UseCurrentStyle();
+ 
+   TH2F hist2distsize("Dist-Size","correlation Dist-Size", 100, 0.0, 1.7, n-1, binsize);
+   hist2distsize.SetXTitle("Dist [deg]");
+   hist2distsize.SetYTitle("Size");
+   hist2distsize.SetDirectory(NULL);
+   hist2distsize.SetFillStyle(4000);
+   hist2distsize.UseCurrentStyle();
+// end create histograms
+
+
+ 
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+
+    read.AddFile(filename);
+
+    MHillas mhillas;
+    plist.AddToList(&mhillas);
+
+    MHillasSrc mhillassrc;
+    plist.AddToList(&mhillassrc);
+
+    MHillasExt mhillasext;
+    plist.AddToList(&mhillasext);
+
+    MNewImagePar mnewimpar;
+    plist.AddToList(&mnewimpar);
+
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+ 
+    MMcEvt mcevt;
+    plist.AddToList(&mcevt);
+ 
+    MPointingPos mpoint;
+    plist.AddToList(&mpoint);
+
+    MObservatory observ;
+    plist.AddToList(&observ);
+
+//    MRawRunHeader header;
+//    plist.AddToList(&header);
+    
+    tlist.AddToList(&read);
+   
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+   if (!tlist.PreProcess(&plist))
+      return;
+
+    Float_t fMm2Deg = cam->GetConvMm2Deg();
+    Int_t event = 0;
+    Int_t filenumber = 0;
+
+    Float_t ftheta, fphi, flength, fwidth, fsize, fmeanx, fmeany, falpha, fdist;
+    Float_t fsingam, fcosgam;
+    Double_t  xsournew, ysournew;
+    Float_t fdelta, fleak, fconc1, fcosda, fassym, fassymM3;
+    Int_t AsGrNull=0, AsLessNull=0;
+    Int_t AsGrNullAfter=0, AsLessNullAfter=0;
+    Float_t logsize, lgsize, lgsize2, tanbeta, beta;
+    const Float_t LOG3000 = log(3000.);
+    Char_t stringtriv1[80], stringlima[80], stringNex[80], stringsig[80];
+    Char_t stringNexOnOff[80], stringLiMaOnOff[80];
+
+// initial values:
+     Float_t  xsource = XSOURCE;
+     Float_t  ysource = YSOURCE;
+
+
+    while (tlist.Process())
+    {
+    event++;
+
+    if (mhillas->GetLength() != -1.)
+     {
+      // parameters:
+      flength = (mhillas->GetLength()) * fMm2Deg;
+      fwidth = (mhillas->GetWidth())*fMm2Deg;
+      fsize = mhillas->GetSize();
+      fmeanx = (mhillas->GetMeanX())*fMm2Deg;
+      fmeany = (mhillas->GetMeanY())*fMm2Deg;
+      falpha = mhillassrc->GetAlpha(); 
+      fdist = (mhillassrc->GetDist())*fMm2Deg;
+      fdelta = mhillas->GetDelta();
+      fconc1 = (mnewimpar->GetConc1());
+      fleak = mnewimpar->GetLeakage1();
+
+
+//      ftheta = mcevt->GetTelescopeTheta();
+      ftheta = mpoint->GetZd();
+//      fphi = mcevt->GetTelescopePhi();
+      fphi = mpoint->GetAz();
+// cout << " phi : " << fphi << " theta : " << ftheta << endl;
+      observ.RotationAngle(ftheta, fphi, fsingam, fcosgam);
+
+      fassym = (mhillasext->GetAsym()) * fMm2Deg;
+      fassymM3 = (mhillasext->GetM3Long()) * fMm2Deg;
+      fcosda = mhillassrc->GetCosDeltaAlpha();
+
+      if ((fassymM3*TMath::Sign(1.,fcosda)) > 0.) AsGrNull++;
+      else AsLessNull++;
+
+      if (ROTOPTION == kTRUE) // derotate into sky coordinates
+      {
+      /*     derotation    : correct sky coordinates into camera coordinates */
+             xsournew = fcosgam * xsource - fsingam * ysource;
+             ysournew = fsingam * xsource + fcosgam * ysource;
+       /*    end derotatiom    */
+      }
+      else // do not derotate, plot into camera coordinates
+      {
+             xsournew = xsource;
+             ysournew = ysource;
+      }
+
+      // basic plots:
+
+//    if (fsize > 3000.)
+    if (fsize > 0.)
+     {
+      histphi.Fill(fphi,1.);
+      histtheta.Fill(ftheta,1.);
+
+      histlength.Fill(flength,1.);
+      histwidth.Fill(fwidth,1.);
+      histsize.Fill(fsize,1.);
+      histLoverS.Fill(flength/fsize,1.);
+      histmeanx.Fill(fmeanx,1.);
+      histmeany.Fill(fmeany,1.);
+      histalpha.Fill(falpha,1.);
+      histdist.Fill(fdist,1.);
+      hist2xy.Fill(fmeanx, fmeany, 1.);
+     }
+
+// some cuts:
+     if (flength > 0.1 && flength < 0.32)
+        if (fwidth > 0.06 && fwidth < 0.15)
+          if (fdist > 0.6 && fdist < 1.3)
+            if (fsize > 3000.)
+//              if(sqrt(fmeanx*fmeanx + fmeany*fmeany) < 1.1)  
+//              if((fassymM3*fcosda < 0.3 && fassymM3*fcosda > 0.02) || 
+//                 (fassymM3*fcosda < -0.02 && fassymM3*fcosda > -0.2) )
+//                  if(fassym*fcosda > 0.) 
+                      {
+                       histAssymM3.Fill(fassymM3*TMath::Sign(1.,fcosda), 1.);
+                       histAssym.Fill(fassym*TMath::Sign(1.,fcosda), 1.);
+                       if ((fassymM3*TMath::Sign(1.,fcosda)) > 0.) AsGrNullAfter++;
+                       else AsLessNullAfter++;
+                      }
+
+// **********************************************************************  //
+// calculate alpha and dist according to the source location:
+           tanbeta = (fmeany - ysournew) / (fmeanx - xsournew);
+           beta = TMath::ATan(tanbeta);
+           falpha = (fdelta - beta) * 180./ TMath::Pi();
+           fdist = sqrt((fmeany - ysournew) * (fmeany - ysournew) +
+                             (fmeanx - xsournew) * (fmeanx - xsournew));
+
+          if(falpha > 90.) falpha -= 180.;
+          if(falpha < -90.) falpha += 180.;
+
+// **********************************************************************  //
+
+
+
+      if (fsize > 3000.)
+      {
+      // correlations:
+      hist2lw.Fill(flength, fwidth, 1.);
+      hist2lalpha.Fill(flength, falpha, 1.);
+      hist2ldist.Fill(flength, fdist, 1.);
+      hist2walpha.Fill(fwidth, falpha, 1.);
+      hist2wdist.Fill(fwidth, fdist, 1.);
+      hist2alphadist.Fill(falpha, fdist, 1.);
+      hist2wsize.Fill(fwidth, fsize, 1.);
+      hist2alphasize.Fill(falpha, fsize, 1.);
+      hist2distsize.Fill(fdist, fsize, 1.);
+      }     
+
+     // cuts:
+//cout << " before the cuts"  << "size :" << fsize << endl;
+                 logsize = log(fsize);
+                 lgsize = logsize-LOG3000;
+                 lgsize2 = lgsize*lgsize;
+                 if ( fsize > SIZEMIN )
+                 if ( fleak < LEAKMAX )
+                 if ( flength > (LENGTHMINParA + LENGTHMINParB*lgsize + LENGTHMINParC*lgsize2) &&
+                      flength < (LENGTHMAXParA + LENGTHMAXParB*lgsize + LENGTHMAXParC*lgsize2))
+                 if ( fwidth > (WIDTHMINParA + WIDTHMINParB*lgsize + WIDTHMINParC*lgsize2)  &&
+                      fwidth < (WIDTHMAXParA + WIDTHMAXParB*lgsize + WIDTHMAXParC*lgsize2) )
+                 if ( fdist > (DISTMINParA + DISTMINParB*lgsize + DISTMINParC*lgsize2)  &&
+                      fdist < (DISTMAXParA + DISTMAXParB*lgsize + DISTMAXParC*lgsize2) )
+//                 if ((fassym*TMath::Sign(1.,fcosda)) > ASYMMIN)   // asymmcut
+                 {
+                         falpha = TMath::Abs(falpha);
+                         histalphafinal.Fill(falpha,1.);
+                         histalphaAll.Fill(falpha,1.);
+
+                         aftercuthistlength.Fill(flength,1.);
+                         aftercuthistwidth.Fill(fwidth,1.);
+                         aftercuthistsize.Fill(fsize,1.);
+                         aftercuthistmeanx.Fill(fmeanx,1.);
+                         aftercuthistmeany.Fill(fmeany,1.);
+                         aftercuthistalpha.Fill(falpha,1.);
+                         aftercuthistdist.Fill(fdist,1.);
+                         aftercuthist2xy.Fill(fmeanx, fmeany, 1.);
+
+                 }
+
+
+     }
+    else filenumber++;
+    }
+
+//    cout << " conversion factor is: " << fMm2Deg <<  endl;
+    cout << " events read in from file : " << event <<  endl;
+    cout << " runs found in the file : " << filenumber <<  endl;
+
+    Int_t startbinoff;
+    Float_t Nex, Non, Noff, Sign, SignLiMa;
+    Float_t normf, integon, integoff, NexOnOff, NoffOFF, SignOnOff, SignLiMaOnOff;
+    Float_t binwidth = histalphafinal.GetBinWidth(1);
+    Float_t numbinMax = ALPHAMAX/binwidth;
+ 
+// **********************************************************************  //
+/* fit parabel from 30 to 90 degrees   */
+    TF1 * fitbgpar = new TF1("fbgpar", "[0]*x*x + [1]", ALOFFMIN, ALOFFMAX);
+    fitbgpar->SetLineColor(2);
+
+    histalphafinal.Fit("fbgpar","WNR");
+
+    Double_t apar = fitbgpar->GetParameter(0);
+    Double_t bpar = fitbgpar->GetParameter(1);
+
+    TF1 * bgoff = new TF1("bgoffON", parabfunc, 0., 90., 3);
+    bgoff->SetParameters(apar, bpar, 1.);
+    bgoff->FixParameter(0, apar);
+    bgoff->FixParameter(1, bpar);
+    bgoff->FixParameter(2, 1.);
+    bgoff->SetLineColor(9);
+
+/* end of the fit parabel from 30 to 90 degrees*/
+// **********************************************************************  //
+
+
+
+    if (!tlist.PostProcess())
+      return;
+
+    
+    gStyle->SetOptStat(11);
+
+// calculate significance: DO NOT USE FIT FOR Non!!!
+    Non = 0.;
+    for(Int_t i=1; i<=numbinMax;i++) Non += histalphafinal.GetBinContent(i);
+
+    Noff = (1./3. * (fitbgpar->GetParameter(0)) * pow(ALPHAMAX,3.) +
+           (fitbgpar->GetParameter(1)) * ALPHAMAX) /  binwidth;
+    Nex = Non - Noff;
+
+    Sign = Nex / sqrt(Nex + 2.* Noff);
+ 
+    cout << " Non : " << Non << " Noff : " << Noff << " Nex : " << Nex << endl;
+    cout << " significance : " << Sign << " sigma" << endl;
+
+    SignLiMa = LiMa17(Non,Noff,1.);
+    cout << " significance Li and Ma (17): " << SignLiMa << " sigma" << endl;
+
+    Char_t stringsig[80];
+ 
+    sprintf(stringsig,"S = %.2f sigma", Sign);
+    sprintf(stringtriv1,"Signif:  S = %.2f sigma", Sign);
+    sprintf(stringlima,"Li&Ma 17: S = %.2f sigma", SignLiMa);
+    sprintf(stringNex,"N excess: Nex = %.d ", Nex);
+
+// **********************************************************************  //
+//  use OFF data to estimate background   *******************************  //
+    TF1 * bgoff2 = new TF1("bgoffOFF", parabfunc, 0., 90., 3);
+  if (USEOFFDATA == kTRUE)
+  {
+        // ON:
+
+           integon = 0.;  // number of events between 30 and 90 degrees
+	   numbinsoff = TMath::Nint((ALOFFMAX - ALOFFMIN)/binwidth);
+           startbinoff = TMath::Nint(ALOFFMIN/binwidth) + 1;
+
+           for (Int_t ik = 0; ik < numbinsoff; ik++)
+           {
+            integon += histalphafinal.GetBinContent(startbinoff+ik);  
+           }
+           // OFF:
+
+           integoff = ((1./3. * aparOff * pow(90.,3.) + bparOff * 90.) -
+                      (1./3. * aparOff * pow(30.,3.) + bparOff * 30.)) / binwidthOff;
+
+           normf = integoff / integon;
+
+           NoffOFF = (1./3. * aparOff * pow(ALPHAMAX,3.) +
+                   (bparOff * ALPHAMAX)) /  binwidthOff / normf;
+
+           NexOnOff = Non - NoffOFF;
+
+           SignOnOff = NexOnOff / sqrt(NexOnOff + 2.* NoffOFF);
+
+        // calculate according to Li Ma:
+           SignLiMaOnOff = LiMa17(Non,NoffOFF*normf,1./normf);
+
+cout << " integon: " << integon << ",  integoff : " <<  integoff << ", normf: " << normf
+     << ", NoffOFF : " << NoffOFF << ", Non : " << Non
+     << ", NexOnOff : " << NexOnOff << ", SignOnOff : " << SignOnOff << endl;
+ cout << " significance (LiMa 17): " << SignLiMaOnOff << " sigma" << endl;
+
+ sprintf(stringNexOnOff,"N excess (ON - OFF) = %.d ", NexOnOff);
+ sprintf(stringLiMaOnOff,"Signif (ON - OFF) = %.2f ", SignLiMaOnOff);
+
+
+            bgoff2->SetParameters(aparOff, bparOff, normf/binwidth*binwidthOff);
+            bgoff2->FixParameter(0, aparOff);
+            bgoff2->FixParameter(1, bparOff);
+            bgoff2->FixParameter(2, normf/binwidth*binwidthOff);
+            bgoff2->SetLineColor(2);
+
+   }
+
+/*
+      TCanvas canv("c1", "basic histograms", 600, 500);
+      canv.SetBorderMode(0);
+      canv.Divide(3,3);
+
+     canv.cd(1);
+     gPad->SetBorderMode(0);
+     histlength.Draw();
+
+     canv.cd(2);
+     gPad->SetBorderMode(0);
+     histwidth.Draw();
+  
+     canv.cd(3);
+     gPad->SetBorderMode(0);
+     gPad->SetLogx();
+     gPad->SetLogy();
+     histsize.Draw();
+
+     canv.cd(4);
+     gPad->SetBorderMode(0);
+     histalpha.Draw();
+
+     canv.cd(5);
+     gPad->SetBorderMode(0);
+     histdist.Draw();
+
+     canv.cd(6);
+     gPad->SetBorderMode(0);
+     histmeanx.Draw();
+
+     canv.cd(7);
+     gPad->SetBorderMode(0);
+     histmeany.Draw();
+
+     canv.cd(8);
+     gPad->SetBorderMode(0);
+     hist2xy.Draw();
+
+     canv.cd(9);
+     gPad->SetBorderMode(0);
+     histLoverS.Draw();
+
+     canv.Modified();
+     canv.Update();
+
+     canv.DrawClone();
+
+
+
+
+      TCanvas canvcor("c2", "correlation histograms", 600, 500);
+      canvcor.SetBorderMode(0);
+      canvcor.Divide(3,3);
+
+     canvcor.cd(1);
+     gPad->SetBorderMode(0);
+     hist2lw.Draw();
+
+     canvcor.cd(2);
+     gPad->SetBorderMode(0);
+     hist2lalpha.Draw();
+
+     canvcor.cd(3);
+     gPad->SetBorderMode(0);
+     hist2ldist.Draw();
+
+     canvcor.cd(4);
+     gPad->SetBorderMode(0);
+     hist2walpha.Draw();
+
+     canvcor.cd(5);
+     gPad->SetBorderMode(0);
+     hist2wdist.Draw();
+
+     canvcor.cd(6);
+     gPad->SetBorderMode(0);
+     hist2alphadist.Draw();
+
+     canvcor.cd(7);
+     gPad->SetBorderMode(0);
+     gPad->SetLogy();
+     hist2wsize.Draw();
+
+
+     canvcor.cd(8);
+     gPad->SetBorderMode(0);
+     gPad->SetLogy();
+     hist2alphasize.Draw();
+
+     canvcor.cd(9);
+     gPad->SetBorderMode(0);
+     gPad->SetLogy();
+     hist2distsize.Draw();
+
+
+     canvcor.Modified();
+     canvcor.Update();
+
+     canvcor.DrawClone();
+*/
+
+/**********************************************************/
+/* plot the alpha plot for the current sample */
+
+    Char_t titelname[80];
+    sprintf(titelname,"alpha plot. sample %d assumed source position: x = %.2f y = %.2f", num, XSOURCE, YSOURCE);
+
+
+      TCanvas canval("c3", "canvas for alpha", 600, 500);
+      canval.SetBorderMode(0);
+
+     gPad->SetBorderMode(0);
+     histalphafinal.SetMarkerStyle(20);
+     histalphafinal.SetTitle(titelname);
+     histalphafinal.SetFillColor(8);
+     histalphafinal.Draw();
+     bgoff->Draw("same");
+     if (USEOFFDATA == kTRUE) bgoff2->Draw("same");
+
+    leg = new TLegend(0.1,0.15,0.52,0.35);
+//    leg->Draw();
+    leg->AddEntry(fitbgpar,"fit for OFF region (30-90 deg)","l");
+    leg->SetHeader("Legend");
+    leg->SetFillColor(19);
+//    leg->Draw();
+
+    if (USEOFFDATA == kFALSE) 
+    {
+	    text = new TPaveText(0.53,0.45,0.9,0.65,"NDC");
+	    text->AddText(0.4, 0.6, stringNex);
+	    text->AddText(0.5, 0.3, stringlima);
+	    text->SetTextSize(0.032);
+	    text->Draw();
+    }
+    else
+    {
+            text = new TPaveText(0.53,0.25,0.9,0.55,"NDC");
+	    text->AddText(0.4, 0.8, stringNex);
+	    text->AddText(0.45, 0.6, stringlima);
+            text->AddText(0.5, 0.4, stringNexOnOff);
+            text->AddText(0.4, 0.2, stringLiMaOnOff);
+            text->SetTextSize(0.032);
+            text->Draw();
+    }
+     canval.Modified();
+     canval.Update();
+
+//     canval.DrawClone();
+
+     TString strin = dirname + sourcename;
+//     TString strin = "data/plots/alpha/dummySize";
+     strin += SIZEMIN;
+     strin += "Sample";
+     if (num<10) strin +="0";
+     strin += num;
+     strin += ".root";
+
+
+     canval.SaveAs(strin);  // please enable if you want to save alphaplots
+cout << " alpha plot for the sample " << num << " has been saved into " << strin << endl;
+
+     if(bgoff2) delete bgoff2;
+     delete bgoff;
+
+/**********************************************************/
+
+/*
+      TCanvas canvt("c4", "telescope", 600, 500);
+      canvt.SetBorderMode(0);
+      canvt.Divide(2,1);
+
+     canvt.cd(1);
+     gPad->SetBorderMode(0);
+     histphi.Draw();
+
+     canvt.cd(2);
+     gPad->SetBorderMode(0);
+     histtheta.Draw();
+
+     canvt.DrawClone();
+
+      TCanvas canvass("c5", "assymetry", 600, 500);
+      canvass.SetBorderMode(0);
+      canvass.Divide(2,1);
+
+     canvass.cd(1);
+     gPad->SetGridx();
+     gPad->SetGridy();
+     gPad->SetBorderMode(0);
+     histAssym.Draw();
+
+     canvass.cd(2);
+     gPad->SetGridx();
+     gPad->SetGridy();
+     gPad->SetBorderMode(0);
+     histAssymM3.Draw();
+
+     canvass.DrawClone();
+
+    TCanvas aftercutcanv("c1a", "basic histograms", 600, 500);
+    aftercutcanv.SetBorderMode(0);
+    aftercutcanv.Divide(3,3);
+
+    aftercutcanv.cd(1);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    aftercuthistlength.Draw();
+
+    aftercutcanv.cd(2);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    aftercuthistwidth.Draw();
+
+    aftercutcanv.cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    gPad->SetLogy();
+    gPad->SetGridx();
+    gPad->SetGridy();
+    aftercuthistsize.Draw();
+
+    aftercutcanv.cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    aftercuthistalpha.Draw();
+
+    aftercutcanv.cd(5);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    aftercuthistdist.Draw();
+
+    aftercutcanv.cd(6);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    aftercuthistmeanx.Draw();
+
+    aftercutcanv.cd(7);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    aftercuthistmeany.Draw();
+
+
+    aftercutcanv.cd(8);
+    gPad->SetBorderMode(0);
+    gPad->SetGridx();
+    gPad->SetGridy();
+    aftercuthist2xy.Draw();
+
+    aftercutcanv.Modified();
+    aftercutcanv.Update();
+
+    aftercutcanv.DrawClone();
+*/
+    Double_t rat1, rat2;
+    rat1 = (double)AsGrNull / (double)AsLessNull;
+    rat2 = (double)AsGrNullAfter / (double)AsLessNullAfter;
+
+    cout << " Asymmetry M3 > 0 : " <<  AsGrNull << endl;
+    cout << " Asymmetry M3 < 0 : " <<  AsLessNull << endl;
+    cout << " Ratio (before cuts) : " <<  rat1 << endl;
+    cout << " Asymmetry M3 > 0 (after): " <<  AsGrNullAfter << endl;
+    cout << " Asymmetry M3 < 0 (after): " <<  AsLessNullAfter << endl;
+    cout << " Ratio (after cuts) : " <<  rat2 << endl;
+
+
+}
+
+void callalphaplot()
+{
+
+
+   Int_t num;
+   Double_t xpeakM, ypeakM, xpeakB, ypeakB;
+
+   FILE *fp;
+//   fp = fopen("data/trackMrk421_0505_2000.dat", "r");
+   if (USEFILE == kTRUE) 
+   {
+	fp = fopen("data/trackCrab1502_1305_Berlin_5deg.dat", "r");
+
+        for(Int_t i = 0; i < 2; i++)
+        {
+       		fscanf(fp,"%d %lf %lf %lf %lf", &num, &xpeakM, &ypeakM, &xpeakB, &ypeakB); 
+       		cout << endl << " SUBS NUMBER " << num << ", xpeakM = " << xpeakM << 
+                     ", ypeakM = " << ypeakM << endl;
+       		cout << "                   xpeakB = " << xpeakB << ", ypeakB = " << ypeakB << endl;
+       		if (num > 0 ) alphaplots(num, xpeakM, ypeakM);  
+   	}
+
+   	fclose(fp); 
+cout << "FERTIG" << endl;
+   }
+   else  
+     alphaplots(NUM, XSOUR, YSOUR);
+
+
+/**********************************************************/
+/* now calculate Nex and S for the overall alpha plot */:
+
+
+
+    TF1 * fitbgparAll = new TF1("fbgparA", "[0]*x*x + [1]", 30., 90.);
+    fitbgparAll->SetLineColor(2);
+    fitbgparAll->SetLineWidth(3);
+
+    histalphaAll.Fit("fbgparA","WR");
+
+    Double_t apar = fitbgparAll->GetParameter(0);
+    Double_t bpar = fitbgparAll->GetParameter(1);
+    Double_t normf = 1.;
+
+    TF1 * bgoff = new TF1("bgoff", parabfunc, 0., 90., 3);
+    bgoff->SetParameters(apar, bpar, normf);
+    bgoff->FixParameter(0, apar);
+    bgoff->FixParameter(1, bpar);
+    bgoff->FixParameter(2, normf);
+    bgoff->SetLineColor(8);
+
+// calc significance:
+    Double_t Sign, Non, Noff, Nex;
+    Double_t binwidth = histalphaAll.GetBinWidth(1);
+    Double_t numbinMax = ALPHAMAX / binwidth;
+
+    Non = 0.;
+    for(Int_t i=1; i<=numbinMax;i++) Non += histalphaAll.GetBinContent(i);
+
+//cout << histalphaAll.GetBinContent(1) + histalphaAll.GetBinContent(2) + 
+//        histalphaAll.GetBinContent(3) + histalphaAll.GetBinContent(4) << endl;
+    Noff = (1./3. * apar * pow(ALPHAMAX,3.) + bpar * ALPHAMAX)  /  binwidth;
+    Nex = Non - Noff;
+
+    Sign = LiMa17(Non,Noff,1.);
+
+    cout << " Non : " << Non << " Noff : " << Noff << " Nex : " << Nex << endl;
+    cout << " significance : " << Sign << " sigma" << endl;
+
+
+    Char_t stringsig[80], stringNex[80];
+
+    sprintf(stringsig,"Signif:  S = %.2f sigma", Sign);
+    sprintf(stringNex,"N excess: Nex = %.d ", Nex);
+/**********************************************************/
+
+
+//  plot all alpha plots together
+
+    TCanvas canvA("cA", "alphacanvas", 600, 500);
+    canvA.SetBorderMode(0);
+
+    gPad->SetBorderMode(0);
+    histalphaAll.SetXTitle("alpha [deg]");
+    histalphaAll.SetYTitle("Counts");
+    histalphaAll.SetMarkerStyle(20);
+    histalphaAll.SetFillColor(17);
+    histalphaAll.Draw();
+    bgoff->Draw("same");
+
+//    leg = new TLegend(0.1,0.15,0.52,0.35);
+//    leg->Draw();
+//    leg->AddEntry(fitbgpar,"fit for OFF region (30-90 deg)","l");
+//    leg->SetHeader("Legend");
+//    leg->SetFillColor(19);
+//    leg->Draw();
+
+     text = new TPaveText(0.53,0.45,0.9,0.65,"NDC");
+     text->AddText(0.4, 0.6, stringNex);
+     text->AddText(0.45, 0.3, stringsig);
+     text->SetTextSize(0.032);
+     text->Draw();
+
+     canvA.Modified();
+     canvA.Update();
+
+
+     Char_t xstr[20], ystr[20];
+     if (USEFILE == kTRUE) 
+     {
+	sprintf(xstr,"%3.2f",0.);
+	sprintf(ystr,"%3.2f",0.);
+     }
+     else
+     {
+	sprintf(xstr,"%3.2f",XSOUR);
+	sprintf(ystr,"%3.2f",YSOUR);
+     }
+
+
+     TString string = dirname + sourcename;
+     string += "X";
+     string += xstr;
+     string += "Y";
+     string += ystr;
+     string += "Size";
+     string += SIZEMIN;
+     string += "alpha";
+     string += TMath::Nint(ALPHAMAX);
+     string += ".root";
+
+     canvA.SaveAs(string);
+cout << " alpha plot has been saved into " << string << endl;
+
+}
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/callcleaning.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/callcleaning.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/callcleaning.C	(revision 9772)
@@ -0,0 +1,56 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cherenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Daniel Mazin, 05/2004 <mailto:mazin@imppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+// Daniel Mazin 14.05.2004  mazin@mppmu.mpg.de
+// **********************************************************************************
+// this macro is used to make an image cleaning and calculate the Hillas parameters
+// input:  calibrated data (one or more files using wild card)
+// output: hillas parameter
+// **********************************************************************************
+
+#include "cleaninghillas.C"
+void callcleaning()
+{
+  gROOT->Reset();
+
+  TString typeInput ="ON";  // -> please specify "ON" or "OFF"
+
+  const char *onfile="1*.ON";
+  const char *offfile="1*.OFF";
+
+
+  TString sourcename = "Crab";
+  TString inPath;  // directory where to find calibrated files
+  TString outPath; // directory where to write root-file with hillas parameters
+
+
+  inPath = "/.magic/magicserv01/scratch/David/CalibratedData/Crab/2004_01_27/";
+
+  outPath = "~mazin/data/Crab/2004_01_27/";
+
+  cleaninghillas(onfile, offfile, typeInput, inPath, outPath, sourcename);
+
+  cout << " finished, back from callcleaning " << endl;
+  cout << " Hillas file " << outPath << sourcename << "Hillas" << typeInput << ".root is created " << endl;
+
+}
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/cleaninghillas.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/cleaninghillas.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/cleaninghillas.C	(revision 9772)
@@ -0,0 +1,232 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cherenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Daniel Mazin, 05/2004 <mailto:mazin@imppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+// Daniel Mazin 14.05.2004  mazin@mppmu.mpg.de
+//**********************************************************
+// this macro is a short form of the macro ONOFFAnalysis.C
+// three jobs are executed:
+// 1)  image cleaning
+// 2)  calculation of hillas parameters
+// 3)  writing the root file
+//**********************************************************
+
+gROOT->Reset();
+
+//************************************************************************
+void cleaninghillas(const char *onfile, 
+                    const char *offfile, 
+                    TString typeInput, 
+                    TString inPath, 
+                    TString outPath,
+                    TString sourcename) 
+{
+
+    TString fileON  = inPath;
+    fileON += onfile;
+    fileON += ".root";
+
+    TString fileOFF = inPath;
+    fileOFF += offfile;
+    fileOFF += ".root";
+
+    // name of input root file
+    if (typeInput == "ON")
+      TString filenamein(fileON);
+    else if (typeInput == "OFF")
+      TString filenamein(fileOFF);
+
+    // name of output root file
+    if (typeInput == "ON")
+      TString file(onfile);
+    else if (typeInput == "OFF")
+      TString file(offfile);
+
+    TString outNameImage = outPath;
+    outNameImage += sourcename;
+    outNameImage += "Hillas";
+    outNameImage += typeInput;
+    outNameImage += ".root";
+
+
+    //  set up the task list:
+    //-----------------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    MObservatory observ;
+    pliston.AddToList(&observ);
+
+    MPointingPos mpos;
+    pliston.AddToList(&mpos);
+
+    MMcEvt mmc;
+    pliston.AddToList(&mmc);
+
+    char *sourceName = "MSrcPosCam";
+    MSrcPosCam source(sourceName);
+
+    // geometry is needed in  MHHillas... classes 
+    MGeomCam *fGeom = 
+             (MGeomCam*)pliston->FindCreateObj("MGeomCamMagic", "MGeomCam");
+
+    //-------------------------------------------
+    // create the tasks which should be executed 
+    //
+
+    MReadMarsFile read("Events", filenamein);
+    read.DisableAutoScheme();
+
+    MGeomApply        apply;
+
+ // NOTE: MMcEvt is used temporary. MPointingPos should be used as soon as synchronisation is working
+ //
+ // the following task is used to fill in a MMcEvt container with Theta and Phi values 
+ // for each event using an ascii file (which is generated from central control report file) 
+ // PLEASE NOTE: only needed if a derotation around the center of the camera is planned 
+ // to be performed afterwords
+    MSourcePosfromStarPos sourcefromstar;
+
+    if (typeInput == "ON")
+    {
+	    sourcefromstar.AddFile("~mazin/mars/MarsCVS/Mars/positionsON", 0);
+    }
+    else if (typeInput == "OFF")
+    {
+        sourcefromstar.AddFile("~mazin/mars/MarsCVS/Mars/positionsOFF", 0);
+    }
+
+
+
+// -----------------------------------------------------
+// image cleaning  -------------------------------------
+// -----------------------------------------------------    
+    MSigmabarCalc sigbar;
+
+    MBlindPixelsCalc2 blind;
+    blind.SetUseInterpolation();
+    blind.SetCheckPedestalRms();
+    blind.SetName("BlindAfterPadding");
+
+    MFSelBasic selbasic;
+    MContinue contbasic(&selbasic);
+    contbasic.SetName("SelBasic");
+
+//    MImgCleanStd    clean(3.0, 2.5);  // Crab 27th old calibr (Hendrik)
+    MImgCleanStd    clean(4.0, 3.0);
+//    clean.SetMethod(MImgCleanStd::kDemocratic);
+    clean.SetCleanRings(1); 
+
+
+// -----------------------------------------------------
+// calculation of  image parameters ---------------------
+// -----------------------------------------------------    
+    TString fHilName    = "MHillas";
+    TString fHilNameExt = "MHillasExt";
+    TString fHilNameSrc = "MHillasSrc";
+    TString fImgParName = "MNewImagePar";
+
+    MHillasCalc    hcalc;
+    hcalc.SetNameHillas(fHilName);
+    hcalc.SetNameHillasExt(fHilNameExt);
+    hcalc.SetNameNewImgPar(fImgParName);
+
+    MHillasSrcCalc hsrccalc(sourceName, fHilNameSrc);
+    hsrccalc.SetInput(fHilName);
+
+    MFSelStandard selstandard(fHilNameSrc);
+    selstandard.SetHillasName(fHilName);
+    selstandard.SetImgParName(fImgParName);
+//    selstandard.SetCuts(usedpixelsmax, corepixelsmin, sizemin, distmin, distmax, lengthmin, widthmin);
+    selstandard.SetCuts(200, 5, 200, 0.0, 5.0, 0.07, 0.05);
+    MContinue contstandard(&selstandard);
+    contstandard.SetName("SelStandard");
+
+// -----------------------------------------------------
+// write root file
+// -----------------------------------------------------    
+      MWriteRootFile write(outNameImage);
+
+      write.AddContainer("MRawRunHeader", "RunHeaders");
+      //write.AddContainer("MTime",         "Events");
+      write.AddContainer("MPointingPos",   "Events");
+      //write.AddContainer("ThetaOrig",     "Events");
+      write.AddContainer("MSrcPosCam",    "Events");
+      write.AddContainer("MSigmabar",     "Events");
+      write.AddContainer("MHillas",       "Events");
+      write.AddContainer("MHillasExt",    "Events");
+      write.AddContainer("MHillasSrc",    "Events");
+      write.AddContainer("MNewImagePar",  "Events");
+    
+
+    //*****************************
+    // entries in MParList
+    
+    pliston.AddToList(&tliston);
+    pliston.AddToList(&observ);
+
+    pliston.AddToList(&source);
+
+    //*****************************
+    // entries in MTaskList
+    
+
+    tliston.AddToList(&read);
+    tliston.AddToList(&apply);
+    tliston.AddToList(&sourcefromstar);
+
+
+    tliston.AddToList(&sigbar);
+    tliston.AddToList(&blind);
+    tliston.AddToList(&contbasic);
+
+    tliston.AddToList(&clean);
+
+    tliston.AddToList(&hcalc);
+    tliston.AddToList(&hsrccalc);
+    tliston.AddToList(&contstandard);
+    tliston.AddToList(&write);
+
+    //*****************************
+
+    //-------------------------------------------
+    // Execute event loop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&pliston);
+    //evtloop.ReadEnv(env, "", printEnv);
+    evtloop.SetProgressBar(&bar);
+    //  evtloop.Write();
+
+    Int_t maxevents = -1;
+    //Int_t maxevents = 1000;
+    if ( !evtloop.Eventloop(maxevents) )
+        return;
+
+    tliston.PrintStatistics(0, kTRUE);
+
+
+}
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/data_shape.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/data_shape.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/data_shape.C	(revision 9772)
@@ -0,0 +1,377 @@
+/* ======================================================================== *\
+!  
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+#include "MAGIC.h"
+
+
+const TString pedfile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12149_P_Cab-On_E.root";
+const TString calfile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12526_C_Cab-On_E.root";
+const TString datafile="/.magic/magicserv01/MAGIC/rootdata/2004_01_27/20040126_12517_D_Cab-On_E.root";
+
+Int_t pedr = 36058;
+Int_t calr = 36058;
+//Int_t datar = 12517;
+
+
+
+void data_shape(const TString inpath = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_06/", Int_t pedruns = pedr, Int_t calruns = calr, Int_t ipix=316)
+
+{
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  
+  pruns.AddRun(pedruns,inpath);
+ 
+  cruns.AddRun(calruns,inpath);
+  
+ 
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MParList plist1;
+  MTaskList tlist1;
+  plist1.AddToList(&tlist1);
+  
+  // containers
+  MPedestalCam   pedcam;
+  MBadPixelsCam  badcam;
+
+ 
+  plist1.AddToList(&pedcam);
+  plist1.AddToList(&badcam);
+    
+  //tasks
+  MReadMarsFile  read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(pruns);
+
+  MGeomApply     geomapl;
+  // MPedCalcPedRun pedcalc;
+  MPedCalcFromLoGain pedcalc_ped;
+  pedcalc_ped.SetMaxHiGainVar(20);
+  pedcalc_ped.SetRange(0, 11, 1, 14);
+  pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+ 
+
+
+  MGeomCamMagic  geomcam;
+    
+  tlist1.AddToList(&read);
+  tlist1.AddToList(&geomapl);
+  tlist1.AddToList(&pedcalc_ped);
+
+  // Create and execute the event looper
+  MEvtLoop pedloop;
+  pedloop.SetParList(&plist1);
+ 
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Eventloop())
+    return;
+  
+  tlist1.PrintStatistics();
+
+ 
+
+  //
+  // Create a empty Parameter List and an empty Task List 
+  //
+  MParList  plist2;
+  MTaskList tlist2;
+  plist2.AddToList(&tlist2);
+  plist2.AddToList(&pedcam);
+  plist2.AddToList(&badcam);
+  
+  
+  MReadMarsFile read2("Events");
+  read2.DisableAutoScheme();
+  static_cast<MRead&>(read2).AddFiles(cruns);
+  
+  MGeomCamMagic              geomcam;
+  MExtractedSignalCam        sigcam;
+  MArrivalTimeCam            timecam;
+  MRawEvtData                evtdata;
+  
+  //
+  // Get the previously created MPedestalCam into the new Parameter List 
+  //
+  plist2.AddToList(&geomcam);
+  plist2.AddToList(&sigcam);
+  plist2.AddToList(&timecam);
+  plist2.AddToList(&evtdata);
+  
+  //
+  // We saw that the signal jumps between slices, 
+  // thus take the sliding window
+  //		
+  
+  MGeomApply             geomapl;
+  
+  
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+  
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+  
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+  
+  
+  // timecalc->SetRange(8,14,8,14,6);
+  
+  // filter against cosmics
+  MFCosmics            cosmics;
+  MContinue            cont(&cosmics);
+  
+  tlist2.AddToList(&read2);
+  tlist2.AddToList(&geomapl);
+  tlist2.AddToList(&extractor);
+  tlist2.AddToList(&timeext);
+  
+  //
+  // In case, you want to skip the cosmics rejection, 
+  // uncomment the next line
+  //
+  tlist2.AddToList(&cont);
+  //
+  // In case, you want to skip the somewhat lengthy calculation
+  // of the arrival times using a spline, uncomment the next two lines
+  //
+  
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist2);
+  //    evtloop.SetDisplay(display);
+    
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  
+  //
+  // Execute second analysis
+  //
+  
+  
+  if (!evtloop.PreProcess())
+    return;
+  
+  int count = 1; 
+  
+  TH2F * shape = new TH2F("shape","shape",30,0,30,1000,-50,250);
+  TH2F * shape_corr = new TH2F("shape_corr","shape_corr",300,0,30,1000,-50,250);
+  TH2F * shape_corr_all = new TH2F("shape_corr_all","shape_corr_all",300,0,30,1000,-50,250);
+  TH1F * htime = new TH1F("htime","htime",150,0,15);
+  TH1F * hsig = new TH1F("hsig","hsig",300,-50,550);
+  
+  //   cout << " hello " << endl;
+  
+  const Float_t ped_mean = pedcam[ipix].GetPedestal();
+  const Float_t pedRMS   = pedcam[ipix].GetPedestalRms();
+  
+  while (tlist2.Process()){ //loop over the events  
+    
+    count++;
+    
+    if (count%1000==0)  cout << "Event #" <<  count << endl;  
+    
+    MRawEvtPixelIter pixel(&evtdata);
+    
+
+    double value = 0;
+    pedcam.GetPixelContent(value, ipix, geomcam, 0);
+    
+	
+    double time = 0;
+    timecam.GetPixelContent(time, ipix, geomcam, 0);  // was 0)
+    
+    double sig = 0;
+    sigcam.GetPixelContent(sig, ipix, geomcam, 0);
+    
+    Byte_t sat = (sigcam)[ipix].GetNumHiGainSaturated();
+
+    hsig->Fill(sig);
+    
+    if (sig>60 && sat==0){
+
+      htime->Fill(time);
+
+      pixel.Jump(ipix);
+      
+      const Byte_t *higains = pixel.GetHiGainSamples();
+      const Byte_t *logains = pixel.GetLoGainSamples();
+      const Int_t nh = evtdata.GetNumHiGainSamples();
+      const Int_t nl = evtdata.GetNumLoGainSamples(); 
+      
+      Bool_t ABFlag = pixel.HasABFlag();
+      
+      const Byte_t *higains = pixel.GetHiGainSamples();
+      const Byte_t *logains = pixel.GetLoGainSamples();
+      
+      const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+      
+      Float_t PedMean[2];
+      PedMean[0] = ped_mean + ABoffs;
+      PedMean[1] = ped_mean - ABoffs; 
+    
+    
+      
+	  
+      for (int sample=0; sample<nh; sample++){
+	shape->Fill(sample+0.5,higains[sample]-PedMean[(sample+ABFlag)&0x1]);
+	shape->Fill(sample+15.5,logains[sample]-PedMean[(sample+ABFlag)&0x1]);
+	shape_corr->Fill(sample+0.5+6.-time,higains[sample]-PedMean[(sample+ABFlag)&0x1]);
+	shape_corr->Fill(sample+15.5+6.-time,logains[sample]-PedMean[(sample+nh+ABFlag)&0x1]);
+	shape_corr_all->Fill(sample+0.5+6.-time,(higains[sample]-PedMean[(sample+ABFlag)&0x1])/sig*250);
+	shape_corr_all->Fill(sample+15.5+6.-time,(logains[sample]-PedMean[(sample+nh+ABFlag)&0x1])/sig*250);
+      }
+    }// end if (sig > 50)
+	
+  } // end loop over the entries
+    
+  tlist2.PrintStatistics();
+  
+  
+  TCanvas * c_shape = new TCanvas("c_shape","c_shape",600,400);
+  c_shape->SetFillColor(0);
+  c_shape->SetBorderMode(0);
+  c_shape->SetGridx();
+  c_shape->SetGridy();
+  shape->SetStats(0);
+  TString title2 = "Raw Data Signal Shape, Pixel ";
+  title2+=ipix;
+  shape->SetTitle(title2);
+  shape->SetXTitle("FADC sample no.");
+  shape->SetYTitle("signal [FADC counts]");
+  shape->SetMarkerStyle(20);
+  shape->SetMarkerColor(4);
+  shape->SetMarkerSize(0.3);
+  shape->Draw();
+
+  
+  TCanvas * c_shape_corr = new TCanvas("c_shape_corr","c_shape_corr",600,400);
+  c_shape_corr->SetFillColor(0);
+  c_shape_corr->SetBorderMode(0);
+  c_shape_corr->SetGridx();
+  c_shape_corr->SetGridy();
+  shape_corr->SetStats(0);
+  TString title3 = "Data Signal Shape, Arrival Time Corrected, Pixel ";
+  title3+=ipix;
+  shape_corr->SetTitle(title3);
+  shape_corr->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr->SetYTitle("signal [FADC counts]");
+  shape_corr->SetMarkerStyle(20);
+  shape_corr->SetMarkerColor(4);
+  shape_corr->SetMarkerSize(0.3);
+  shape_corr->Draw();
+
+
+  TCanvas * c_shape_corr_all = new TCanvas("c_shape_corr_all","c_shape_corr_all",600,400);
+  c_shape_corr_all->SetFillColor(0);
+  c_shape_corr_all->SetBorderMode(0);
+  c_shape_corr_all->SetGridx();
+  c_shape_corr_all->SetGridy();
+  shape_corr_all->SetStats(0);
+  TString title3 = "Data Signal Shape, Arrival Time + Amplitude Corrected, Pixel ";
+  title3+=ipix;
+  shape_corr_all->SetTitle(title3);
+  shape_corr_all->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr_all->SetYTitle("signal  [a.u.]");
+  shape_corr_all->SetMarkerStyle(20);
+  shape_corr_all->SetMarkerColor(4);
+  shape_corr_all->SetMarkerSize(0.3);
+  shape_corr_all->Draw();
+ 
+  
+
+
+  TCanvas * c_sig = new TCanvas("c_sig","c_sig",600,400);
+  c_sig->SetFillColor(0);
+  c_sig->SetBorderMode(0);
+  c_sig->SetGridx();
+  c_sig->SetGridy();
+
+  hsig->SetStats(0);
+  TString title4 = "Data Extracted Charge, MExtractFixedWindowPeakSearch, Pixel ";
+  title4+=ipix;
+  hsig->SetTitle(title4);
+  hsig->SetXTitle("reco charge [FADC counts]");
+  hsig->SetYTitle("events / 2 FADC counts");
+  hsig->SetLineColor(4);
+  hsig->SetLineWidth(2);
+  hsig->Draw();
+
+  TCanvas * c_time = new TCanvas("c_time","c_time",600,400);
+  c_time->SetFillColor(0);
+  c_time->SetBorderMode(0);
+  c_time->SetGridx();
+  c_time->SetGridy();
+
+  htime->SetStats(0);
+  TString title5 = "Data Arrival Time, MExtractTimeHighestIntegral, Pixel ";
+  title5+=ipix;
+  htime->SetTitle(title5);
+  htime->SetXTitle("arrival time [T_{ADC}]");
+  htime->SetYTitle("events / 0.1 T_{ADC}");
+  htime->SetLineColor(4);
+  htime->SetLineWidth(2);
+  htime->Draw();
+
+  TCanvas * c7 = new TCanvas("c7","c7",600,400);
+  c7->cd();
+  c7->SetGridx();
+  c7->SetGridy();
+  c7->SetFillColor(0);
+  //  c7->SetBordermode(0);
+    
+  TProfile * shape_corr_all_pfx = (TProfile*)shape_corr_all->ProfileX();
+  
+  shape_corr_all_pfx->SetStats(0);
+  TString title6 = "Average Data Signal Shape, Amplitude + Arrival Time Corrected, Pixel";
+  title6+=ipix;
+  shape_corr_all_pfx->SetTitle(title6);
+  shape_corr_all_pfx->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr_all_pfx->SetYTitle("signal [a.u.]");
+  shape_corr_all_pfx->SetMarkerStyle(20);
+  shape_corr_all_pfx->SetMarkerColor(4);
+  shape_corr_all_pfx->SetMarkerSize(0.5);
+  shape_corr_all_pfx->Draw();
+
+}
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/falsesourcemethod.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/falsesourcemethod.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/falsesourcemethod.C	(revision 9772)
@@ -0,0 +1,171 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cherenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Daniel Mazin, 05/2004 <mailto:mazin@imppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+
+// Daniel Mazin 14.05.2004  mazin@mppmu.mpg.de
+// **********************************************************************************
+// this macro is used to produce false source plots 
+// either using one sample only (usually used for OFF, set TYPEOPTION = kFALSE)
+// or in addition using the background estimation from OFF (set TYPEOPTION = kTRUE).
+// The later option can be used ONLY if false source method for the OFF data 
+// has taken place before.
+// input: hillas parameter file
+// output: several 2D plots in a root file + 
+// ascii file with parameters like significance, Nexcess etc.
+// **********************************************************************************
+
+
+// you may want to change these values:
+#define STEPGRID 0.05 //  [deg]
+#define MINXGRID -1.  //  [deg]
+#define MINYGRID -1.  //  [deg]
+#define MAXXGRID 1.   //  [deg]
+#define MAXYGRID 1.   //  [deg]
+
+#define ALPHAMAX 10.  // [deg], ON region in the alpha plot, maybe 5 deg is better
+                      // NOTE: up to now only values of 5, 10, 15, 20 degrees are possible
+
+// if you wish to rotate set to kTRUE, else kFALSE
+const Bool_t ROTOPTION = kFALSE; 
+const Bool_t TYPEOPTION = kFALSE; // kFALSE = estimate background from the same sample
+                                  // kTRUE  = estimate background also from OFF data
+const Bool_t CUTOPTION = kTRUE;  // kTRUE = dynamical cuts
+                                 // kFALSE = statical cuts
+
+/* ******************************************************   */
+      /*  static    cuts   */
+#define LENGTHMIN 0.10  // deg
+#define LENGTHMAX 0.32  // deg
+#define WIDTHMIN  0.06  // deg
+#define WIDTHMAX  0.15  // deg
+#define SIZEMIN   2000. // photons
+#define DISTMIN   0.6   // deg
+#define DISTMAX   1.3   // deg
+#define LEAKMAX   0.25  // deg
+/* ******************************************************   */
+
+/* ******************************************************   */
+      /*  dynamical cuts  Crab 27th Jan 2004 */
+#define LENGTHMINParA 0.136  // deg
+#define LENGTHMINParB 0.036  //
+#define LENGTHMINParC -0.0038  //
+#define LENGTHMAXParA 0.332  // deg
+#define LENGTHMAXParB 0.037  //
+#define LENGTHMAXParC 0.0261 //
+#define WIDTHMINParA  0.063  // deg
+#define WIDTHMINParB  0.013  //
+#define WIDTHMINParC  0.0003  //
+#define WIDTHMAXParA  0.123  // deg
+#define WIDTHMAXParB  0.019  //
+#define WIDTHMAXParC  0.0005 //
+#define DISTMINParA   0.6   // deg
+#define DISTMINParB   0.059  //
+#define DISTMINParC   0.  //
+#define DISTMAXParA   1.25   // deg
+#define DISTMAXParB   0.059  //
+#define DISTMAXParC   0.  //
+/* ******************************************************   */
+
+      /*  dynamical cuts  Mrk 421 and Crab 15th Feb 2004 */
+
+/*
+#define LENGTHMINParA 0.12  // deg
+#define LENGTHMINParB 0.034  //
+#define LENGTHMINParC 0.  //
+#define LENGTHMAXParA 0.32  // deg
+#define LENGTHMAXParB 0.034  //
+#define LENGTHMAXParC 0. //
+#define WIDTHMINParA  0.055  // deg
+#define WIDTHMINParB  0.013  //
+#define WIDTHMINParC  0.0  //
+#define WIDTHMAXParA  0.12  // deg
+#define WIDTHMAXParB  0.013  //
+#define WIDTHMAXParC  0.0 //
+#define DISTMINParA   0.6   // deg
+#define DISTMINParB   0.059  //
+#define DISTMINParC   0.  //
+#define DISTMAXParA   1.25   // deg
+#define DISTMAXParB   0.059  //
+#define DISTMAXParC   0.  //
+*/
+/* ******************************************************   */
+
+// please do not change these values:
+#define NUMSTEPS (int) ((MAXXGRID - MINXGRID) / STEPGRID + 1.5)
+#define GRIDBINS (int) (NUMSTEPS * NUMSTEPS  + 0.5)
+
+
+#include "mtools.C"
+#include <skyplot.h>  // needed histograms
+
+// this helps me to check if the binning is ok
+#define TOLERANCE 1e-3
+
+#include "hillasfileread.C"
+#include "gridloop.C"
+
+void falsesourcemethod()
+{
+
+  if (TYPEOPTION == kTRUE)  // output of OFF data sample
+//      DATPARAMIN = "data/ressignOffMrk3004.dat";  // 3000
+      DATPARAMIN = "paramOffCrab2701.dat";   // 2000
+
+
+   HILLASFILENAME = "~/data/Crab/2004_01_27/CrabHillasOFF.root";
+   DATPARAMOUT = "paramOffCrab2701.dat";
+   ROOTPLOTNAME = "/.magic/magicserv01/scratch/Daniel/plots/RootPlots/Crab/2004_01_27/CrabOffSkyPlots.root";
+   hillasfileread();
+   gridloop();  
+
+/*
+// use this loop for different subsamples
+  for(Int_t i=1; i<10; i++)
+  {
+   HILLASFILENAME = "~/data/Crab15022004Update/sample";
+   DATPARAMOUT = "data/ressignOnOffCrab1502Samp";
+   ROOTPLOTNAME = "/.magic/magicserv01/scratch/Daniel/plots/RootPlots/Crab15022004Update/Crab1502Sample";
+
+   HILLASFILENAME += i;
+   HILLASFILENAME += "/";
+   HILLASFILENAME += "CrabHillasON";
+   HILLASFILENAME += ".root";
+
+   DATPARAMOUT += i;
+   DATPARAMOUT += "_AlphaCut";
+   DATPARAMOUT += TMath::Nint(ALPHAMAX);
+   DATPARAMOUT += "deg";
+   DATPARAMOUT += ".dat";
+
+   ROOTPLOTNAME += i;
+   ROOTPLOTNAME += "_AlphaCut";
+   ROOTPLOTNAME += TMath::Nint(ALPHAMAX);
+   ROOTPLOTNAME += "deg";
+   ROOTPLOTNAME += ".root";
+
+
+   hillasfileread();
+   gridloop();  
+  }
+*/
+}
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/findstars.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/findstars.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/findstars.C	(revision 9772)
@@ -0,0 +1,184 @@
+void ReadSetup(TString fname, MAstroCamera &cam)
+{
+    MMcConfigRunHeader *config=0;
+    MGeomCam           *geom=0;
+
+    TFile file(fname);
+    TTree *tree = (TTree*)file.Get("RunHeaders");
+    tree->SetBranchAddress("MMcConfigRunHeader", &config);
+    if (tree->GetBranch("MGeomCam"))
+        tree->SetBranchAddress("MGeomCam", &geom);
+    tree->GetEntry(0);
+
+    cam.SetMirrors(*config->GetMirrors());
+    cam.SetGeom(*geom);
+}
+
+void findstars(const TString filename="20040422_23213_D_Mrk421_E.root", const TString directory="/data/MAGIC/Period016/rootdata2/2004_04_22/", const UInt_t numEvents = 0)
+{
+
+  MParList  plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  MGeomCamMagic geomcam;
+  MCameraDC     dccam;
+  MStarLocalCam starcam;
+
+  plist.AddToList(&geomcam);
+  plist.AddToList(&dccam);
+  plist.AddToList(&starcam);
+
+  // Reads the trees of the root file and the analysed branches
+  MReadReports read;
+  read.AddTree("Currents"); 
+  read.AddTree("Drive"); // If you do not include Drive info, the MFindStars class
+                         // will not use the star catalog method
+  read.AddFile(directory+filename); // after the reading of the trees!!!
+  read.AddToBranchList("MReportCurrents.*");
+  read.AddToBranchList("MReportDrive.*");
+
+  MGeomApply geomapl;
+  TString continuoslightfile =   
+     "/data/MAGIC/Period016/rootdata/2004_04_16/20040416_22368_P_Off3c279-2CL100_E.root";
+  Float_t mindc = 0.9; //[uA]
+
+  MCalibrateDC dccal;
+  dccal.SetFileName(continuoslightfile);
+  dccal.SetMinDCAllowed(mindc);
+
+  const Int_t numblind = 5;
+  const Short_t x[numblind] = { 47, 124, 470, 475, 571};
+  const TArrayS blindpixels(numblind,(Short_t*)x);
+  Float_t ringinterest = 100; //[mm]
+  Float_t tailcut = 2.5;
+  UInt_t integratedevents = 1;
+
+  // We need the MAGIC mirror geometry from a MC header:
+  TString geometryfile = "/mcdata/standard/camera/NSB_013/Gamma/Gamma_zbin9_90_7_1480to1489_w0.root";
+
+  // We need the Bright Star Catalog:
+  TString catalogfile = "/home/rwagner/bsc5.dat";
+
+  MFindStars findstars;
+  findstars.SetBlindPixels(blindpixels);
+  findstars.SetRingInterest(ringinterest);
+  findstars.SetDCTailCut(tailcut);
+  findstars.SetNumIntegratedEvents(integratedevents);
+  findstars.SetMinuitPrintOutLevel(-1);
+  findstars.SetGeometryFile(geometryfile);
+  findstars.SetBSCFile(catalogfile);
+  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26);
+  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  findstars.SetRaDec(ra,dec);
+  findstars.SetLimMag(8);
+  findstars.SetRadiusFOV(1.5);
+
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&read);
+  tlist.AddToList(&dccal);
+  tlist.AddToList(&findstars, "Currents");
+  
+  // The following lines you only need if in addition you want to display
+  // independent MAstroCamera output
+  //
+  //  TString fname = "/mcdata/standard/camera/NSB_013/Gamma/Gamma_zbin9_90_7_1480to1489_w0.root";
+  //  MObservatory magic1;      
+  //  const Double_t ra  = MAstro::Hms2Rad(11, 4, 26); //Mkn421
+  //  const Double_t dec = MAstro::Dms2Rad(38, 12, 36);
+  //
+  //  MAstroCamera stars;        
+  //  ReadSetup(fname, stars); 
+  //  stars.SetLimMag(9);
+  //  stars.SetRadiusFOV(3);
+  //  stars.SetRaDec(ra, dec);
+  //  stars.ReadBSC("/home/rwagner/bsc5.dat");
+  //  stars.SetObservatory(magic1);
+
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+     
+  if (!evtloop.PreProcess())
+    return;
+  
+  MHCamera display(geomcam);
+  display.SetPrettyPalette();
+  display.Draw();
+  gPad->cd(1);
+  starcam.Draw();
+  
+  UInt_t numevents=0;
+  
+  while (tlist.Process())
+    {
+      numevents++;
+      if (numevents%integratedevents==0)
+	{
+	  display.SetCamContent(findstars.GetDisplay());
+	  gPad->Modified();
+	  gPad->Update();	      
+        // This line prints the results:
+	// 	  starcam.Print();
+	// This is how to access the TList of stars:
+	// 	  TList* starlist = starcam.GetList();
+
+	// This is how to iterate over stars found:
+	// 	  TIter Next(starlist);
+	// 	  MStarLocalPos* star;
+	// 	  UInt_t starnum = 0;
+	// 	  cout << filename << " ";
+	// 	  cout << "Iterating over list" << endl;
+	// 	  while ((star=(MStarLocalPos*)Next())) 
+	// 	    {
+	// 	      cout << "star[" << starnum << "] ";
+	// 	      cout << star->GetMeanX() << " " 
+	// 		   << star->GetMeanY() << " ";
+	// 	      starnum++;
+	// 	    }
+	// 	  cout << endl;
+	
+	}//integratedevents
+
+      MTime time;
+      time.Set(2004, 4, 22, 21, 51, 15);
+      
+      //superimpose star picture
+      //       stars.SetTime(time);
+      //       TObject *o = stars.Clone();
+      //       o->SetBit(kCanDelete);
+      //       o->Draw();
+      
+      if (!HandleInput())
+        break;
+
+    }
+
+  evtloop.PostProcess();
+    
+  tlist.PrintStatistics();
+
+}
+
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/fluxMUnfold.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/fluxMUnfold.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/fluxMUnfold.C	(revision 9772)
@@ -0,0 +1,723 @@
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// This program should be run under root:                                 //
+//      root fluxMUnfold.C++                                              //
+//                                                                        //
+// Authors: T. Bretz  02/2002 <mailto:tbretz@astro.uni-wuerzburg.de>      //
+//          W. Wittek 09/2002 <mailto:wittek@mppmu.mpg.de>                //
+//          R. Wagner 11/2004 <mailto:rwagner@mppmu.mpg.de>               //
+//                                                                        //
+// this macro is prepared to be used in the analysis:                     //
+//                                                                        //
+//      the unfolding should be called by                                 //
+//      doUnfolding(TH2D &tobeunfolded,      // (E-est, Theta)            //
+//                  TH3D &migrationmatrix,   // (E-est, E-true, Theta)    //
+//                  TH2D &unfolded)          // (E-true,Theta)            //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+
+#include <TMath.h>
+#include <TRandom3.h>
+#include <TVector.h>
+#include <TMatrixD.h>
+#include <TMatrix.h>
+#include <TH1.h>
+#include <TH2.h>
+#include <TH3.h>
+#include <TProfile.h>
+#include <TF1.h>
+#include <iostream.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+
+#include <fstream.h>
+#include <iomanip.h>
+
+TH1 *DrawMatrixClone(const TMatrixD &m, Option_t *opt="")
+{
+    const Int_t nrows = m.GetNrows();
+    const Int_t ncols = m.GetNcols();
+
+    TMatrix m2(nrows, ncols);
+    for (int i=0; i<nrows; i++)
+        for (int j=0; j<ncols; j++)
+            m2(i, j) = m(i, j);
+
+    TH2F *hist = new TH2F(m2);
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+
+}
+
+TH1 *DrawMatrixColClone(const TMatrixD &m, Option_t *opt="", Int_t col=0)
+{
+    const Int_t nrows = m.GetNrows();
+
+    TVector vec(nrows);
+    for (int i=0; i<nrows; i++)
+        vec(i) = m(i, col);
+
+    TH1F *hist = new TH1F("TVector","",nrows,0,nrows);
+    for (int i=0; i<nrows; i++)
+    {
+      hist->SetBinContent(i+1, vec(i));
+    }
+
+    hist->SetBit(kCanDelete);
+    hist->Draw(opt);
+    hist->SetDirectory(NULL);
+
+    return hist;
+}
+
+
+void PrintTH3Content(const TH3 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+      for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+        for (Int_t k=1; k<=hist.GetNbinsZ(); k++)
+            cout << hist.GetBinContent(i,j,k) << " \t";
+      cout << endl << endl;
+    }
+}
+
+void PrintTH3Error(const TH3 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+    {
+      for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+        for (Int_t k=1; k<=hist.GetNbinsZ(); k++)
+            cout << hist.GetBinError(i, j, k) << " \t";
+      cout << endl << endl;
+    }
+}
+
+void PrintTH2Content(const TH2 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            cout << hist.GetBinContent(i,j) << " \t";
+        cout << endl << endl;
+}
+
+void PrintTH2Error(const TH2 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        for (Int_t j=1; j<=hist.GetNbinsY(); j++)
+            cout << hist.GetBinError(i, j) << " \t";
+        cout << endl << endl;
+}
+
+void PrintTH1Content(const TH1 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        cout << hist.GetBinContent(i) << " \t";
+    cout << endl << endl;
+}
+
+void PrintTH1Error(const TH1 &hist)
+{
+    cout << hist.GetName() << ": " << hist.GetTitle() << " <error>" << endl;
+    cout << "-----------------------------------------------------" << endl;
+    for (Int_t i=1; i<=hist.GetNbinsX(); i++)
+        cout << hist.GetBinError(i) << " \t";
+    cout << endl << endl;
+}
+
+void CopyCol(TMatrixD &m, const TH1 &h, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        m(i, col) = h.GetBinContent(i+1);
+}
+
+void CopyCol(TH1 &h, const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    for (Int_t i=0; i<n; i++)
+        h.SetBinContent(i+1, m(i, col));
+}
+
+void CopyH2M(TMatrixD &m, const TH2 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+            m(i, j) = h.GetBinContent(i+1, j+1);
+}
+
+void CopySqr(TMatrixD &m, const TH1 &h)
+{
+    const Int_t nx = m.GetNrows();
+    const Int_t ny = m.GetNcols();
+
+    for (Int_t i=0; i<nx; i++)
+        for (Int_t j=0; j<ny; j++)
+        {
+            const Double_t bin =  h.GetBinContent(i+1, j+1);
+            m(i, j) = bin*bin;
+        }
+}
+
+Double_t GetMatrixSumRow(const TMatrixD &m, Int_t row)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(row, i);
+
+    return sum;
+}
+
+Double_t GetMatrixSumDiag(const TMatrixD &m)
+{
+    const Int_t n = m.GetNcols();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, i);
+
+    return sum;
+}
+
+Double_t GetMatrixSumCol(const TMatrixD &m, Int_t col=0)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += m(i, col);
+
+    return sum;
+}
+Double_t GetMatrixSum(const TMatrixD &m)
+{
+    const Int_t n = m.GetNrows();
+
+    Double_t sum = 0;
+    for (Int_t i=0; i<n; i++)
+        sum += GetMatrixSumRow(m, i);
+
+    return sum;
+}
+
+
+// ======================================================
+//
+// SteerUnfold
+//
+void SteerUnfold(TString bintitle,
+                 TH1D &ha,     TH2D &hacov, TH2D &hmig,
+                 TH2D &hmigor, TH1D &hb0,   TH1D *hpr,
+                 TH1D &hb)
+{
+    // ha      is the distribution to be unfolded
+    // hacov   is the covariance matrix of the distribution ha
+    // hmig    is the migration matrix;
+    //         it is used in the unfolding unless it is overwritten
+    //         by SmoothMigrationMatrix by the smoothed migration matrix
+    // hmigor  is the migration matrix to be smoothed;
+    //         the smoothed migration matrix will be used in the unfolding
+    // hpr     the prior distribution
+    //         it is only used if SetPriorInput(*hpr) is called   
+    // hb      unfolded distribution
+
+    //..............................................       
+    // create an MUnfold object;
+    // fill histograms into vectors and matrices
+
+    MUnfold unfold(ha, hacov, hmig);
+    unfold.bintitle = bintitle;
+
+    //..............................................       
+    // smooth the migration matrix;
+    //        the smoothed migration matrix will be used in the unfolding
+    //        hmig is the original (unsmoothed) migration matrix
+
+    unfold.SmoothMigrationMatrix(hmigor);
+
+    //..............................................       
+    // define prior distribution (has always to be defined) 
+    // the alternatives are  :
+
+    // 1  SetPriorConstant() :   isotropic distribution
+    // 2  SetPriorPower(gamma) : dN/dE = E^{-gamma}
+    // 3  SetPriorInput(*hpr):   the distribution *hpr is used 
+    // 4  SetPriorRebin(*ha) :   use rebinned histogram ha 
+
+    UInt_t flagprior = 4;
+    cout << "SteerUnfold : flagprior = " << flagprior << endl;
+    cout << "==========================="<< endl;
+
+    Bool_t errorprior=kTRUE;
+    switch (flagprior)
+    {
+    case 1:
+        unfold.SetPriorConstant();
+        break;
+    case 2:
+        errorprior = unfold.SetPriorPower(1.5);
+        break;
+    case 3:
+        if (!hpr)
+        {
+            cout << "Error: No hpr!" << endl;
+            return;
+        }
+        errorprior = unfold.SetPriorInput(*hpr);
+        break;
+    case 4:
+        errorprior = unfold.SetPriorRebin(ha);
+        break;
+    }
+    if (!errorprior)
+    {
+        cout << "MUnfold::SetPrior... : failed.  flagprior = " ;
+        cout << flagprior << endl;
+        return;
+    }
+
+    //..............................................       
+    // calculate the matrix G = M * M(transposed)
+    //           M being the migration matrix
+
+    unfold.CalculateG();
+
+    //..............................................       
+    // call steering routine for the actual unfolding;
+    // the alternatives are :
+
+    // 1  Schmelling : minimize the function Z by Gauss-Newton iteration;
+    //                 the parameters to be fitted are gamma(i) = lambda(i)/w;
+
+    // 2  Tikhonov2 :  regularization term is sum of (2nd deriv.)**2 ;
+    //                 minimization by using MINUIT;
+    //                 the parameters to be fitted are
+    //                 the bin contents of the unfolded distribution
+
+    // 3  Bertero:     minimization by iteration
+    //                 
+
+    UInt_t flagunfold = 1;
+    cout << "SteerUnfold : flagunfold = "  << flagunfold << endl;
+    cout << "============================" << endl;
+
+
+
+    switch (flagunfold)
+    {
+    case 1: // Schmelling
+        cout << "" << endl;
+        cout << "Unfolding algorithm : Schmelling" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Schmelling(hb0))
+            cout << "MUnfold::Schmelling : failed." << endl;
+        break;
+
+    case 2: // Tikhonov2
+        cout << "" << endl;
+        cout << "Unfolding algorithm :   Tikhonov" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Tikhonov2(hb0))
+            cout << "MUnfold::Tikhonov2 : failed." << endl;
+        break;
+
+    case 3: // Bertero
+        cout << "" << endl;
+        cout << "Unfolding algorithm :    Bertero" << endl;
+        cout << "================================" << endl;
+        if (!unfold.Bertero(hb0))
+            cout << "MUnfold::Bertero : failed." << endl;
+        break;
+    }    
+
+
+    //..............................................       
+    // Print fResult
+    unfold.PrintResults();
+
+
+    //..............................................       
+    // Draw the plots
+    unfold.DrawPlots();
+
+    //..............................................       
+    // get unfolded distribution
+    TMatrixD &Vb    = unfold.GetVb();
+    TMatrixD &Vbcov = unfold.GetVbcov();
+
+    UInt_t fNb = unfold.fNb;
+
+    for (UInt_t a=0; a<fNb; a++)
+    {
+      hb.SetBinContent(a+1, Vb(a,0));
+      hb.SetBinError(a+1, sqrt(Vbcov(a, a)) );
+    }
+
+}
+
+//__________________________________________________________________________
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// doUnfolding    (to be called in the analysis)                          //
+//                                                                        //
+// arguments :                                                            //
+//                                                                        //
+//   INPUT                                                                //
+//      TH2D &tobeunfolded : no.of excess events and its error            //
+//                           vs. (E-est, Theta)                           //
+//      TH3D &migration    : migration matrix (E-est, E_true, Theta)      //
+//                                                                        //
+//   OUITPUT                                                              //
+//      TH2D &unfolded     : no.of excess events and its error            //
+//                           vs. (E-true, Theta)                          //
+//                                                                        //
+// calls SteerUnfold to do the unfolding                                  //
+//                                                                        //
+// The "Theta" axis is only used to loop over the bins of theta           //
+// and to do the unfolding for each bin of theta. Instead of theta        //
+// any other variable (or a dummy variable) may be used.                  //
+//                                                                        //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+
+void doUnfolding(TH2D &tobeunfolded, TH3D &migration, TH2D &unfolded)
+{
+  TAxis &taxis  = *tobeunfolded.GetYaxis();
+  Int_t numybins = taxis.GetNbins();
+
+  for (Int_t m=1; m<=numybins; m++)
+  {
+    TString bintitle = "Bin ";
+    bintitle += m;
+    bintitle += ": ";
+
+    // -----------------------------------------
+    // ha : distribution to be unfolded
+
+    TH1D &ha = *tobeunfolded.ProjectionX("", m, m, "e");
+    TString title = bintitle;
+    title += "E-est distr. to be unfolded";
+    ha.SetNameTitle("ha", title);
+    TAxis &aaxis = *ha.GetXaxis();
+    Int_t na = aaxis.GetNbins();
+    Double_t alow = aaxis.GetBinLowEdge(1);
+    Double_t aup  = aaxis.GetBinLowEdge(na+1);
+
+    PrintTH1Content(ha);
+    PrintTH1Error(ha);
+
+    // -----------------------------------------
+    // covariance matrix of the distribution ha
+
+    title = bintitle;
+    title +=  "Error matrix of distribution ha";
+    TH2D hacov("hacov", title, na, alow, aup, na, alow, aup);
+    //MH::SetBinning(&hacov, &aaxis, &aaxis); 
+
+    Double_t errmin = 3.0;
+    for (Int_t i=1; i<=na; i++)
+    {
+      for (Int_t j=1; j<=na; j++)
+      {
+        hacov.SetBinContent(i, j, 0.0);
+      }
+      const Double_t content = ha.GetBinContent(i);
+      const Double_t error2  = (ha.GetBinError(i))*(ha.GetBinError(i));
+      if (content <= errmin  &&  error2 < errmin) 
+        hacov.SetBinContent(i, i, errmin);
+      else
+        hacov.SetBinContent(i, i, error2);
+    }
+
+    //PrintTH2Content(hacov);
+    
+
+    // -----------------------------------------
+    // migration matrix :
+    //           x corresponds to measured quantity
+    //           y corresponds to true quantity
+    TH2D &hmig = *(TH2D*)migration.Project3D("yxe");
+    title = bintitle;
+    title += "Migration Matrix";
+    hmig.SetNameTitle("Migrat", title);
+
+    TAxis &aaxismig = *hmig.GetXaxis();
+    Int_t namig = aaxismig.GetNbins();
+
+    if (na != namig)
+    {
+      cout << "doUnfolding : binnings are incompatible; na, namig = "
+           << na << ",  " << namig << endl;
+      return;
+    }
+
+    TAxis &baxismig = *hmig.GetYaxis();
+    Int_t nbmig = baxismig.GetNbins();
+    Double_t blow = baxismig.GetBinLowEdge(1);
+    Double_t bup  = baxismig.GetBinLowEdge(nbmig+1);
+
+    PrintTH2Content(hmig);
+    //PrintTH2Error(hmig);
+
+
+    // -----------------------------------------
+    // dummy ideal distribution
+
+    Int_t nb = nbmig;
+
+    title = bintitle;
+    title += "Dummy Ideal distribution";
+    TH1D hb0("dummyhb0", title, nb, blow, bup);;
+    //MH::SetBinning(&hb0, &baxismig); 
+    hb0.Sumw2();
+
+    for (Int_t k=1; k<=nb; k++)
+    {
+        hb0.SetBinContent(k, 1.0/nb);
+        hb0.SetBinError  (k, 0.1/nb);
+    }
+
+    //PrintTH1Content(hb0);
+
+    // -----------------------------------------
+    // here the prior distribution can be defined for the call
+    // to SetPriorInput(*hpr)
+
+    title = bintitle;
+    title += "Dummy Prior distribution";
+    TH1D hpr("hpr", title, nb, blow, bup);
+    //MH::SetBinning(&hpr, &baxismig); 
+    
+    for (Int_t k=1; k<=nb; k++)
+        hpr.SetBinContent(k, 1.0/nb);
+
+    //PrintTH1Content(hpr);
+
+
+    // -----------------------------------------
+    // unfolded distribution
+
+
+    title = bintitle;
+    title += "Unfolded distribution";
+    TH1D hb("hb", title, nb, blow, bup);
+    //MH::SetBinning(&hb, &baxismig); 
+
+    // -----------------------------------------
+    SteerUnfold(bintitle, ha, hacov, hmig, hmig, hb0, &hpr, hb);
+
+    for (Int_t k=1; k<=nb; k++)
+    {
+      Double_t content = hb.GetBinContent(k);
+      Double_t error   = hb.GetBinError(k);
+
+      unfolded.SetBinContent(k, m, content);
+      unfolded.SetBinError(k, m, error);
+    }    
+
+    delete &ha;
+    delete &hmig;
+  }
+
+}
+//========================================================================//
+
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+// Main program   (for testing purposes)                                  //
+//                                                                        //
+//                defines the ideal distribution          (hb0)           //
+//                defines the migration matrix            (hMigrat)       //
+//                defines the distribution to be unfolded (hVa)           //
+//                                                                        //
+//                calls doUnfolding                                       //
+//                      to do the unfolding                               //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
+void fluxMUnfold()
+{
+  // -----------------------------------------
+  // migration matrix :
+  //           x corresponds to measured quantity
+  //           y corresponds to true quantity
+
+    const Int_t  na   =   13;
+    //const Int_t  na   =   18;
+    const Axis_t alow = 0.25;
+    const Axis_t aup  = 3.50;
+
+    const Int_t  nb   =   11;
+    //const Int_t  nb   =   22;
+    const Axis_t blow = 0.50;
+    const Axis_t bup  = 3.25;
+
+    const Int_t  nc   =     1;
+    const Axis_t clow =   0.0;
+    const Axis_t cup  =   1.0;
+
+    Int_t m = 1;
+
+    TH3D migration("migration", "Migration Matrix", 
+                   na, alow, aup, nb, blow, bup, nc, clow, cup);
+    migration.Sumw2();
+
+    // parametrize migration matrix as
+    //     <log10(Eest)>      = a0 + a1*log10(Etrue) + a2*log10(Etrue)**2 
+    //                             + log10(Etrue) 
+    //     RMS( log10(Eest) ) = b0 + b1*log10(Etrue) + b2*log10(Etrue)**2
+    Double_t a0 = 0.0;
+    Double_t a1 = 0.0;
+    Double_t a2 = 0.0;
+
+    Double_t b0 = 0.26;
+    Double_t b1 =-0.054;
+    Double_t b2 = 0.0;
+
+    TF1 f2("f2", "gaus(0)", alow, aup);
+    f2.SetParName(0, "ampl");
+    f2.SetParName(1, "mean");
+    f2.SetParName(2, "sigma");
+
+    // loop over log10(Etrue) bins
+    TAxis &yaxis = *migration.GetYaxis();
+    for (Int_t j=1; j<=nb; j++)
+    {
+        Double_t yvalue = yaxis.GetBinCenter(j);
+
+        const Double_t mean  = a0 + a1*yvalue + a2*yvalue*yvalue + yvalue;
+        const Double_t sigma = b0 + b1*yvalue + b2*yvalue*yvalue;
+        const Double_t ampl  = 1./ ( sigma*TMath::Sqrt(2.0*TMath::Pi()));
+
+        // gaus(0) is a substitute for [0]*exp( -0.5*( (x-[1])/[2] )**2 )
+        f2.SetParameter(0, ampl);
+        f2.SetParameter(1, mean);
+        f2.SetParameter(2, sigma);
+
+        // fill temporary 1-dim histogram with the function
+        // fill the histogram using
+        //    - either FillRandom
+        //    - or using Freq
+        TH1D htemp("temp", "temp", na, alow, aup);
+        htemp.Sumw2();
+
+        for (Int_t k=0; k<1000000; k++)
+            htemp.Fill(f2.GetRandom());
+
+        // copy it into the migration matrix
+        Double_t sum = 0;
+        for (Int_t i=1; i<=na; i++)
+        {
+            const Stat_t content = htemp.GetBinContent(i);
+            migration.SetBinContent(i, j, m, content);
+            sum += content;
+        }
+
+        // normalize migration matrix
+        if (sum==0)
+            continue;
+
+        for (Int_t i=1; i<=na; i++)
+        {
+            const Stat_t content = migration.GetBinContent(i,j,m);
+            migration.SetBinContent(i,j,m,       content/sum);
+            migration.SetBinError  (i,j,m, sqrt(content)/sum);
+        }
+    }
+
+    //PrintTH3Content(migration);
+    //PrintTH3Error(migration);
+
+    // -----------------------------------------
+    // ideal distribution
+
+    TH1D hb0("hb0", "Ideal distribution", nb, blow, bup);
+    hb0.Sumw2();
+
+    // fill histogram with random numbers according to 
+    // an exponential function dN/dE = E^{-gamma}
+    //    or with y = log10(E), E = 10^y :             
+    //                          dN/dy = ln10 * 10^{y*(1-gamma)}     
+    TF1 f1("f1", "pow(10.0, x*(1.0-[0]))", blow, bup);
+    f1.SetParName(0,"gamma");
+    f1.SetParameter(0, 2.7);
+
+    // ntimes is the number of entries
+    for (Int_t k=0; k<10000; k++)
+        hb0.Fill(f1.GetRandom());
+
+    // introduce energy threshold at 50 GeV
+
+    const Double_t  lgEth = 1.70;
+    const Double_t dlgEth = 0.09;
+
+    for (Int_t j=1; j<=nb; j++)
+    {
+        const Double_t lgE = hb0.GetBinCenter(j);
+        const Double_t c   = hb0.GetBinContent(j);
+        const Double_t dc  = hb0.GetBinError(j);
+        const Double_t f   = 1.0 / (1.0 + exp( -(lgE-lgEth)/dlgEth ));
+
+        hb0.SetBinContent(j, f* c);
+        hb0.SetBinError  (j, f*dc);
+    }
+
+    //PrintTH1Content(hb0);
+
+    // -----------------------------------------
+    // generate distribution to be unfolded (ha)
+    // by smearing the ideal distribution  (hb0)
+    //
+    TH2D tobeunfolded("tobeunfolded", "Distribution to be unfolded", 
+                      na, alow, aup, nc, clow, cup);
+    tobeunfolded.Sumw2();
+
+    for (Int_t i=1; i<=na; i++)
+    {
+        Double_t cont = 0;
+        for (Int_t j=1; j<=nb; j++)
+            cont += migration.GetBinContent(i, j, m) * hb0.GetBinContent(j);
+
+        tobeunfolded.SetBinContent(i, m, cont);
+        tobeunfolded.SetBinError(i, m, sqrt(cont));
+    }
+
+    //PrintTH2Content(tobeunfolded);
+    //PrintTH2Error(tobeunfolded);
+
+    // -----------------------------------------
+    // unfolded distribution
+
+    TH2D unfolded("unfolded", "Unfolded distribution", 
+                  nb, blow, bup, nc, clow, cup);
+    unfolded.Sumw2();
+
+    // -----------------------------------------
+    doUnfolding(tobeunfolded, migration, unfolded);
+
+}
+//========================================================================//
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/gridloop.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/gridloop.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/gridloop.C	(revision 9772)
@@ -0,0 +1,441 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cherenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Daniel Mazin, 05/2004 <mailto:mazin@imppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+// Daniel Mazin 17.05.2004  mazin@mppmu.mpg.de
+// **********************************************************************************
+// this macro is used to produce false source plots
+// and it is a part from the macro falsesourcemethod.C.
+// See falsesourcemethod.C for more explanation
+// input: hillas parameters as vectors
+// output: several 2D plots in a root file +
+// ascii file with parameters like significance, Nexcess etc.
+// **********************************************************************************
+
+
+void gridloop()
+{
+
+    printf("inside of gridloop() ... \n");
+
+/* emty histograms  */
+
+    histskyplot.Reset();
+    histNexOnOff.Reset();
+    histChi2Off.Reset();
+    histskyplotOnOff.Reset();
+    histNex.Reset();
+    histChi2.Reset();
+    histskyplot4.Reset();
+    histskyLiMa.Reset();
+    histsign.Reset();
+    histsign4.Reset();
+    histBerlin.Reset();
+
+/* end emty histograms  */
+
+
+    TH1F histalphagrid;
+    histalphagrid.SetName("Alpha");
+    histalphagrid.SetTitle("Alpha");
+    histalphagrid.SetXTitle("Alpha (deg)");
+    histalphagrid.SetYTitle("Counts");
+    histalphagrid.SetDirectory(NULL);
+    histalphagrid.SetFillStyle(4000);
+    histalphagrid.UseCurrentStyle();
+  
+    bins.SetEdges(18, 0.0, 90.);
+    bins.Apply(histalphagrid);
+
+    Double_t xcorr, ycorr, xtest, ytest, xtilde, ytilde, fconc1;
+
+    const Float_t binwidth1 = histalphagrid.GetBinWidth(1);
+    if (TMath::Abs( ALPHAMAX/binwidth1 - TMath::Nint(ALPHAMAX/binwidth1)) > TOLERANCE)
+    {
+         cout << "wrong binning for histogram: histalphagrid \n SORRY ... ABORT" << endl;
+         exit(1);
+    }
+    const Int_t numbbinOnMax = TMath::Nint(ALPHAMAX / binwidth1);  // number bins in ON region
+
+  /*   fit functions  */
+    TF1 * fitsig = new TF1("fsig", "[0]", 0., ALPHAMAX);
+    fitsig->SetLineColor(4); 
+    TF1 * fitbgpar = new TF1("fbgpar", "[0]*x*x + [1]", 30., 90.);
+    fitbgpar->SetLineColor(2); 
+
+    TF1 * fitbg4 = new TF1("fbg4", "[0]*x*x*x*x + [1]*x*x + [2]", 30., 90.);
+    fitbg4->SetLineColor(3);
+  /*   end fit functions  */
+
+    Float_t Nex, Non, Noff, Sign;
+    Float_t xsource, ysource, xsournew, ysournew;
+
+    Double_t Nex4, Noff4, Sign4; 
+    Double_t alpha, SignLiMa;
+ 
+    Double_t chisquarefit;
+
+    Double_t integon, integoff, normf, NoffOFF, SignOnOff, NexOnOff;
+    Float_t logsize, lgsize, lgsize2, tanbeta, beta;
+    const Float_t LOG3000 = log(3000.);
+
+
+
+    Double_t chi2par[GRIDBINS], apar[GRIDBINS], bpar[GRIDBINS]; // fit parameters from OFF sample
+    Float_t offbin1[GRIDBINS], offbin2[GRIDBINS], offbin3[GRIDBINS]; // Number of events in first 3 bins
+    Double_t xpos, ypos, binwidth2;
+    Int_t  numgrid;
+
+
+    Int_t numbinsoff = 12;  // FIXME: 12 should be changed according to the binning
+    Int_t nbinx, nbiny, gridpoint = 0;
+
+    Char_t psname[120], titelname[120], plot1name[120], plot2name[120], stringsig[120];
+ 
+    FILE * fp;
+
+    if (TYPEOPTION == kTRUE)  // read fit parameters from the OFF sample
+    {
+      Char_t * datin = DATPARAMIN;
+              
+      fp = fopen(datin, "r");
+
+      for (Int_t i=0; i<GRIDBINS; i++)
+      {
+        fscanf(fp,"%d %lf %lf %lf %lf %lf %lf %f %f %f",
+                 &numgrid, &xpos, &ypos,  &apar[i], &bpar[i], 
+                 &chi2par[i], &binwidth2,
+                 &offbin1[i], &offbin2[i], &offbin3[i]);
+//  cout << "numgrid: " << numgrid << ",  apar " << apar[i] << endl;
+      }
+
+       fclose(fp);
+    }
+
+
+    Char_t * chout = DATPARAMOUT;  // write parameters into file
+
+    fp = fopen(chout, "w");
+
+
+/* begin of the loop over all bins in the sky map */
+
+   for(Int_t gridx = 0; gridx < NUMSTEPS; gridx++)   
+   { 
+    xsource = MINXGRID + gridx * STEPGRID;
+//cout << xsource << endl;
+
+    for(Int_t gridy = 0; gridy < NUMSTEPS; gridy++)  
+    {
+      ysource = MINYGRID + gridy * STEPGRID;
+//cout << ysource << endl;
+    
+// empty histogram:
+//     nbinx = histalphagrid.GetNbinsX();
+//     for(Int_t ii = 0; ii< (nbinx+1); ii++) histalphagrid.SetBinContent(ii, 0.);
+//     histalphagrid.SetEntries(0);
+     histalphagrid.Reset();
+
+
+//      Bool_t anglephi = kFALSE;
+
+    /* loop over all events */
+      for(Int_t k=0; k< imnum; k++)
+      {
+
+          if (ROTOPTION == kTRUE) // derotate into sky coordinates
+          {
+      /*     derotation    : correct sky coordinates into camera coordinates */
+             xsournew = cosgam(k) * xsource - singam(k) * ysource;
+             ysournew = singam(k) * xsource + cosgam(k) * ysource;
+       /*    end derotatiom    */
+          }
+          else // do not derotate, plot into camera coordinates
+          {
+             xsournew = xsource;
+             ysournew = ysource;
+          }
+
+
+       /* calculate ALPHA und DIST acording to the source position */
+           tanbeta = (ypar(k) - ysournew) / (xpar(k) - xsournew);
+           beta = TMath::ATan(tanbeta);
+           alphapar(k) = (deltapar(k) - beta) * 180./ TMath::Pi();
+           distpar(k) = sqrt((ypar(k) - ysournew) * (ypar(k) - ysournew) +
+                             (xpar(k) - xsournew) * (xpar(k) - xsournew));
+
+
+
+          if(alphapar(k) > 90.) alphapar(k) -= 180.;
+          if(alphapar(k) < -90.) alphapar(k) += 180.;
+
+//          histalpha.Fill(alphapar(k),1.);
+//          histdist.Fill( distpar(k),1.);
+
+          if(CUTOPTION==kFALSE)
+          { 
+/* ******************************************************   */
+      /*   static   cuts   */
+                if (lengthpar(k) > LENGTHMIN && lengthpar(k) < LENGTHMAX)
+                if (widthpar(k) > WIDTHMIN && widthpar(k) < WIDTHMAX)
+                if (sizepar(k) > SIZEMIN)
+                if (distpar(k) > DISTMIN && distpar(k) < DISTMAX)
+                if (leak1(k) < LEAKMAX)
+/* ******************************************************   */
+                     {
+                         alphapar(k) = TMath::Abs(alphapar(k));
+//printf("alpha passed the cuts: %5.2f \n", alphapar(k));
+//printf("histalphagrid:  %5.2f \n", histalphagrid.GetNbinsX());
+                         histalphagrid.Fill(alphapar(k),1.);
+
+                     }
+
+           }
+/* ******************************************************   */
+/*            dynamical cuts                                */
+           else     // if(CUTOPTION==kTRUE)
+           {
+                 logsize = log(sizepar(k));
+                 lgsize = logsize-LOG3000;
+                 lgsize2 = lgsize*lgsize;
+                 if ( sizepar(k) > SIZEMIN )
+                 if ( leak1(k) < LEAKMAX )
+                 if ( lengthpar(k) > (LENGTHMINParA + LENGTHMINParB*lgsize + LENGTHMINParC*lgsize2) &&
+                      lengthpar(k) < (LENGTHMAXParA + LENGTHMAXParB*lgsize + LENGTHMAXParC*lgsize2))
+                 if ( widthpar(k) > (WIDTHMINParA + WIDTHMINParB*lgsize + WIDTHMINParC*lgsize2)  &&
+                      widthpar(k) < (WIDTHMAXParA + WIDTHMAXParB*lgsize + WIDTHMAXParC*lgsize2) )
+                 if ( distpar(k) > (DISTMINParA + DISTMINParB*lgsize + DISTMINParC*lgsize2)  &&
+                      distpar(k) < (DISTMAXParA + DISTMAXParB*lgsize + DISTMAXParC*lgsize2) )
+                 {
+                         alphapar(k) = TMath::Abs(alphapar(k));
+                         histalphagrid.Fill(alphapar(k),1.);
+                         if(alphapar(k) < 8.)   histBerlin.Fill(xsournew, ysournew);
+                 }
+           }
+         
+        }
+//    histalphagrid.Fit("fsig","NR");
+//printf("content bin 1: %4.2f\n", histalphagrid.GetBinContent(1));
+    histalphagrid.Fit(fitsig,"NWR");
+    histalphagrid.Fit("fbg4","+NWR");
+    histalphagrid.Fit("fbgpar","+NWR");
+
+// cout << "OK" << endl;
+// calculate significance:
+    Non = 0.;
+    for(Int_t i=1; i<=numbbinOnMax;i++) Non += histalphagrid.GetBinContent(i);
+//    Non = (fitsig->GetParameter(0)) * numbbinOnMax;
+//cout << "Non : " << Non << endl;
+//    histalphagrid.Draw();
+
+    chisquarefit = fitbgpar->GetChisquare(); 
+    Noff = (1./3. * (fitbgpar->GetParameter(0)) * pow(ALPHAMAX,3.) + 
+           (fitbgpar->GetParameter(1)) * ALPHAMAX) /  binwidth1;
+    
+//cout << "Noff : " << Noff << endl;
+    
+    Nex = Non - Noff;
+
+    Noff4 = (1./5. * fitbg4->GetParameter(0) *  pow(ALPHAMAX,5.) +
+            1./3. * (fitbg4->GetParameter(1)) * pow(ALPHAMAX,3.) +
+           fitbg4->GetParameter(2) * ALPHAMAX ) / binwidth1;
+ 
+//cout << "Noff4 : " << Noff4 << endl;
+ 
+    Nex4 = Non - Noff4;
+ 
+// calculate significance: 
+
+//    Sign4 = Nex4 / sqrt(Nex4 + 2.* Noff4);
+    if (Noff4<0.) Sign4 = 0.;
+    else Sign4 = LiMa17(Non,Noff4,1.);
+
+//cout << "Sign4 : " << Sign4 << endl;
+//    Sign = Nex / sqrt(Nex + 2.* Noff);
+    if (Noff<0.) Sign = 0.;
+    else Sign = LiMa17(Non,Noff,1.);
+//cout << "Sign LiMa : " << Sign << endl;
+
+   /*  calculate Noff from the OFF data  */
+  if (TYPEOPTION == kTRUE)
+  {
+   	// ON: 
+
+   	integon = 0.;  // number of events between 30 and 90 degrees
+
+	   for (Int_t ik = 0; ik < numbinsoff; ik++)
+	   {
+	    integon += histalphagrid.GetBinContent(7+ik);  // FIXME: 7 should be changed according to the binning
+	   }
+	   // OFF: 
+
+	   integoff = ((1./3. * apar[gridpoint] * pow(90.,3.) + bpar[gridpoint] * 90.) -
+        	      (1./3. * apar[gridpoint] * pow(30.,3.) + bpar[gridpoint] * 30.)) / binwidth2;
+	
+	   normf = integoff / integon;
+
+	   NoffOFF = (1./3. * apar[gridpoint] * pow(ALPHAMAX,3.) +
+        	   (bpar[gridpoint] * ALPHAMAX)) /  binwidth2 / normf;
+
+	   NexOnOff = Non - NoffOFF;
+
+  	   SignOnOff = NexOnOff / sqrt(NexOnOff + 2.* NoffOFF);
+
+	// calculate according to Li Ma:
+           if (NoffOFF<0.) SignLiMa=0.;
+	   else SignLiMa = LiMa17(Non,NoffOFF*normf,1./normf);
+
+   }
+
+    cout << endl << "   xsource: " << xsource <<  "   ysource: " << ysource << endl;
+
+    cout << " Non : " << Non << " Noff : " << Noff << " Nex : " << Nex << endl;
+
+ if (TYPEOPTION == kTRUE) 
+    cout << " ON and OFF : Non : " << Non << " Noff (estimated) : " << NoffOFF << " Nex : " << NexOnOff << endl;
+
+    cout << endl;
+    cout << " significance (parab): " << Sign << " sigma" << endl;
+    cout << " significance (4th order): " << Sign4 << " sigma" << endl;
+ if (TYPEOPTION == kTRUE)
+  {
+    cout << " significance (using ON and OFF): " << SignOnOff << " sigma" << endl;
+    cout << " significance (LiMa 17): " << SignLiMa << " sigma" << endl;
+  }
+
+
+    if (TYPEOPTION == kTRUE)
+      fprintf(fp,"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf \n", 
+                xsource, ysource, Sign, Non, Noff, Nex, SignLiMa, 
+                SignOnOff, NoffOFF, NexOnOff, chi2par[gridpoint]);
+    else 
+         fprintf(fp,"%d %lf %lf %lf %lf %lf %lf %lf %lf %lf\n",
+            gridpoint+1, xsource, ysource,
+            fitbgpar->GetParameter(0), fitbgpar->GetParameter(1),
+            fitbgpar->GetChisquare(), histalphagrid.GetBinWidth(1),
+            histalphagrid.GetBinContent(1), histalphagrid.GetBinContent(2),
+            histalphagrid.GetBinContent(3));
+
+
+    histskyplot.SetBinContent(gridx+1, gridy+1, Sign);
+    histNex.SetBinContent(gridx+1, gridy+1, Nex);
+    histChi2.SetBinContent(gridx+1, gridy+1, fitbgpar->GetChisquare() / 10.);
+
+    if (TYPEOPTION == kTRUE) histskyplotOnOff.SetBinContent(gridx+1, gridy+1, SignOnOff);
+    if (TYPEOPTION == kTRUE) histNexOnOff.SetBinContent(gridx+1, gridy+1, NexOnOff);
+    if (TYPEOPTION == kTRUE) histChi2Off.SetBinContent(gridx+1, gridy+1, chi2par[gridpoint] / 16.);
+
+    if (TYPEOPTION == kTRUE) histskyLiMa.SetBinContent(gridx+1, gridy+1, SignLiMa);
+    histskyplot4.SetBinContent(gridx+1, gridy+1, Sign4);
+    histsign.Fill(Sign,1.);
+    histsign4.Fill(Sign4,1.);
+//    break;
+
+    if (TYPEOPTION == kTRUE)
+    {
+	    TF1 * bgoff = new TF1("bgoff", parabfunc, 0., 90., 3);
+	    bgoff->SetParameters(apar[gridpoint], bpar[gridpoint], normf);
+	    bgoff->FixParameter(0, apar[gridpoint]);
+	    bgoff->FixParameter(1, bpar[gridpoint]);
+	    bgoff->FixParameter(2, normf);
+	    bgoff->SetLineColor(8);
+    }
+
+//    sprintf(stringsig,"S = %.2f sigma", Sign);
+    if (TYPEOPTION == kTRUE) sprintf(stringsig,"S = %.2f sigma", SignOnOff);
+/*
+    sprintf(psname,"/.magic/magicserv01/scratch/Daniel/plots/RootPlots/040215Mrk421_misp/all/alphaX%.2fY%.2fON.root", xsource, ysource);
+    sprintf(titelname,"alpha plot. assumed source position: x = %.2f y = %.2f", xsource, ysource);
+    TCanvas * cplot  = new TCanvas();
+    histalphagrid.SetTitle(titelname);
+    histalphagrid.Draw();
+    bgoff->Draw("same");
+    leg = new TLegend(0.1,0.15,0.52,0.35);
+    leg->Draw();
+    leg->AddEntry(fitsig,"fit for ON region (0-20 deg)","l");
+    leg->AddEntry(fitbgpar,"fit for OFF region (30-90 deg)","l");
+    leg->AddEntry(bgoff,"fit from OFF data (0-90 deg)","l");
+    leg->SetHeader("Legend");
+    leg->SetFillColor(19);
+    leg->Draw();
+
+    text = new TPaveText(50,20,90,80);
+    text->AddText(0.5, 0.8, "calculated significance");
+    text->AddText(0.5, 0.5, "using ON and OFF:");
+    text->AddText(1, 0.2, stringsig);
+    text->SetTextSize(0.04);
+    text->Draw();
+
+    cplot->Modified();
+    cplot->Update();
+
+    cplot->SaveAs(psname);
+    delete cplot;
+*/
+    if (TYPEOPTION == kTRUE) delete  bgoff;
+
+    gridpoint++;
+
+    }
+   }
+
+  /* close file  */
+    fclose(fp);  
+    
+
+    TFile rootfile(ROOTPLOTNAME, "RECREATE",
+                   "sky plots in all variations");
+
+
+//    cout << " end of one of the grids 1 " << endl;
+
+     histskyplot.Write();
+
+     histNex.Write();
+
+     histChi2.Write();
+
+     histsign.Write();
+
+     histskyplot4.Write();
+
+     histsign4.Write();
+
+     histBerlin.Write();
+
+   if (TYPEOPTION == kTRUE)
+   {
+     histNexOnOff.Write();
+     histChi2Off.Write();
+     histskyplotOnOff.Write();
+     histskyLiMa.Write();
+    }
+
+   rootfile.Close();
+
+   delete fitsig;
+   delete fitbgpar;
+   delete fitbg4;
+
+  cout << " end of one of the grids " << endl;
+}
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/hillasfileread.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/hillasfileread.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/hillasfileread.C	(revision 9772)
@@ -0,0 +1,181 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cherenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Daniel Mazin, 05/2004 <mailto:mazin@imppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+// Daniel Mazin 17.05.2004  mazin@mppmu.mpg.de
+// **********************************************************************************
+// this macro is a part from the macro falsesourcemethod.C
+// This macro reads mars file with hillas parameters etc. and puts the values into vectors
+// input: hillas parameter file
+// output: vectors with the same information
+// **********************************************************************************
+
+
+void hillasfileread()
+{
+   lengthpar.ResizeTo(MAXNUMEVENTS);
+   widthpar.ResizeTo(MAXNUMEVENTS);
+   sizepar.ResizeTo(MAXNUMEVENTS);
+   xpar.ResizeTo(MAXNUMEVENTS);
+   ypar.ResizeTo(MAXNUMEVENTS);
+   deltapar.ResizeTo(MAXNUMEVENTS);
+   alphapar.ResizeTo(MAXNUMEVENTS);
+   distpar.ResizeTo(MAXNUMEVENTS);
+   cosgam.ResizeTo(MAXNUMEVENTS);
+   singam.ResizeTo(MAXNUMEVENTS);
+   conc1.ResizeTo(MAXNUMEVENTS);
+   leak1.ResizeTo(MAXNUMEVENTS);
+
+   lengthpar.Zero();
+   widthpar.Zero();
+   sizepar.Zero();
+   xpar.Zero();
+   ypar.Zero();
+   deltapar.Zero();
+   alphapar.Zero();
+   distpar.Zero();
+   cosgam.Zero();
+   singam.Zero();
+   conc1.Zero();
+   leak1.Zero();
+
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+
+    read.AddFile(HILLASFILENAME);
+
+    MHillas mhillas;
+    plist.AddToList(&mhillas);
+
+    MHillasSrc mhillassrc;
+    plist.AddToList(&mhillassrc);
+
+    MNewImagePar mnewimpar;
+    plist.AddToList(&mnewimpar);
+
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+ 
+    MMcEvt mcevt;
+    plist.AddToList(&mcevt); 
+
+    MPointingPos mpoint;
+    plist.AddToList(&mpoint); 
+
+    MObservatory observ;
+    plist.AddToList(&observ);
+
+    MHStarMap starmap;
+    plist.AddToList(&starmap);
+
+//    MRawRunHeader header;
+//    plist.AddToList(&header);
+    
+    tlist.AddToList(&read);
+   
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    Float_t fMm2Deg;
+
+cout << " file name: " << HILLASFILENAME << endl;
+
+   if (!tlist.PreProcess(&plist))
+      return;
+
+    fMm2Deg = cam->GetConvMm2Deg();
+    Int_t event = 0;
+    Int_t filenumber = 0;
+    Float_t theta, phi;
+ 
+    imnum = 0;
+
+    while (tlist.Process())
+    {
+    event++;
+//cout << event << endl;
+
+    if (mhillas->GetLength() != -1.)
+     {
+
+
+     if (ROTOPTION == kTRUE) 
+     {
+//        theta = mcevt->GetTelescopeTheta();
+        theta = mpoint->GetZd();
+//        phi = mcevt->GetTelescopePhi();
+        phi = mpoint->GetAz();
+//   printf("theta: %5.3f, phi: %5.3f\n", theta*180./4.1415, phi*180./4.1415);
+        observ.RotationAngle(theta, phi, singam(imnum), cosgam(imnum)); 
+     }
+
+      lengthpar(imnum) = (mhillas->GetLength()) * fMm2Deg;
+      widthpar(imnum) = (mhillas->GetWidth())*fMm2Deg;
+      sizepar(imnum) = mhillas->GetSize();
+      xpar(imnum) = (mhillas->GetMeanX())*fMm2Deg;
+      ypar(imnum) = (mhillas->GetMeanY())*fMm2Deg;
+      deltapar(imnum) = mhillas->GetDelta(); 
+      conc1(imnum) = (mnewimpar->GetConc1());
+      leak1(imnum) = mnewimpar->GetLeakage1();
+
+      imnum++;
+
+     }
+    else filenumber++;
+    }
+
+    if (!tlist.PostProcess())
+      return;
+
+   printf("imnum = %d\n",imnum);
+
+   lengthpar.ResizeTo(imnum);
+   widthpar.ResizeTo(imnum);
+   sizepar.ResizeTo(imnum);
+   xpar.ResizeTo(imnum);
+   ypar.ResizeTo(imnum);
+   deltapar.ResizeTo(imnum);
+   alphapar.ResizeTo(imnum);
+   distpar.ResizeTo(imnum); 
+   cosgam.ResizeTo(imnum); 
+   singam.ResizeTo(imnum); 
+   conc1.ResizeTo(imnum); 
+   leak1.ResizeTo(imnum); 
+
+
+    cout << " conversion factor is: " << fMm2Deg <<  endl;
+    cout << " events read in from file : " << event <<  endl;
+    cout << " runs found in the file : " << filenumber <<  endl;
+
+}
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/mtools.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/mtools.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/mtools.C	(revision 9772)
@@ -0,0 +1,19 @@
+Double_t LiMa17(Double_t Non, Double_t Noff, Double_t alpha)
+{
+  Double_t term1, term2, signif;
+  term1 = ((1.+alpha) / alpha) * (Non / (Non + Noff));
+  term2 = (1.+alpha) * (Noff / (Non + Noff));
+
+  signif = sqrt(2.* (Non*log(term1) + Noff*log(term2)));
+
+  if (Non>(alpha*Noff)) return signif;
+  else return -signif;
+
+}
+
+Double_t parabfunc(Double_t *x, Double_t *par)
+{
+   Double_t result=0.;
+   if (par[2]!=0)   result = (par[0] * x[0] * x[0] + par[1]) / par[2];
+   return result;
+}
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/noise_autocorrelation_AB.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/noise_autocorrelation_AB.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/noise_autocorrelation_AB.C	(revision 9772)
@@ -0,0 +1,343 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko  09/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+const TString defname = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_03/20040903_35698_P_multiplexFADC_E.root";
+const TString defpedname = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_03/20040903_35698_P_multiplexFADC_E.root";
+
+// works with one pedestal file to calculate the noise autocorrelation
+
+void noise_autocorrelation_AB(const TString fname = defpedname, const TString pedname = defpedname, Int_t ipix = 67) {
+  
+  MParList plist_ped;
+  
+  MTaskList tlist_ped;
+  plist_ped.AddToList(&tlist_ped);
+  
+  MPedestalCam   pedcam;
+  plist_ped.AddToList(&pedcam);
+  
+  MReadMarsFile read("Events", pedname);
+  read.DisableAutoScheme();
+  tlist_ped.AddToList(&read);
+  
+  MGeomApply     geomapl_ped;
+  MGeomCamMagic  geomcam;
+  tlist_ped.AddToList(&geomapl_ped);
+
+  
+  MPedCalcFromLoGain pedcalc_ped;
+  //pedcalc_ped.SetMaxHiGainVar(20);
+  //pedcalc_ped.SetRange(0, 11, 1, 14);
+  //pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+  tlist_ped.AddToList(&pedcalc_ped);
+  
+  MEvtLoop evtloop_ped;
+  evtloop_ped.SetParList(&plist_ped);
+  
+  if (!evtloop_ped.Eventloop())
+    return;
+  
+  tlist_ped.PrintStatistics();
+  
+  
+  // now the event loop for the signal reconstruction with pedestals subtracted
+  
+  
+  MParList plist;
+  MTaskList     tlist;
+  plist.AddToList(&tlist);
+
+  plist.AddToList(&pedcam);
+  
+  MRawRunHeader runheader;
+  plist.AddToList(&runheader);
+
+  MRawEvtData evtdata; 
+  plist.AddToList(&evtdata);
+ 
+  MExtractedSignalCam sigcam;
+  plist.AddToList(&sigcam);
+  
+  MArrivalTimeCam timecam;
+  plist.AddToList(&timecam);
+
+  
+  MReadMarsFile read("Events", fname);
+  read.DisableAutoScheme();
+  
+  MGeomApply geomapl;
+
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+  
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+  
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+
+    
+  tlist.AddToList(&read);
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&extractor);
+  tlist.AddToList(&timeext);
+
+  
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+  if (!evtloop.PreProcess())
+    return;
+
+  TString title = "Noise Autocorrelation B_{ij} = <b_{i}*b_{j}> - <b_{i}>*<b_{j}>, Pixel ";
+  title += ipix;
+ 
+
+  Int_t First = 1;
+
+  TH2F * hcorr = new TH2F("hcorr","hcorr",15,0,15,15,0,15);
+ 
+  TH2F * shape = new TH2F("shape","shape",311,-1.05,30.05,1000,-20,250);
+  TH2F * shape_corr = new TH2F("shape_corr","shape_corr",311,-1.05,30.05,1000,-20,250);
+  TH1F * htime = new TH1F("htime","htime",150,0,15);
+  TH1F * hsig = new TH1F("hsig","hsig",300,-50,550); 
+
+
+  Float_t B[15][15];
+  Float_t bi[15];
+  Float_t bj[15];
+  
+  for (int i=0; i<15; i++){
+    bi[i]=0;
+    bj[i]=0;
+    for (int j=0; j<15; j++){
+      B[i][j]=0;
+    }
+  }
+
+  const Float_t ped_mean = pedcam[ipix].GetPedestal();
+  const Float_t pedRMS   = pedcam[ipix].GetPedestalRms();
+
+  cout << " ped_mean " << ped_mean << " pedRMS " << pedRMS << endl;
+  int count = 0;
+
+  while (tlist.Process()) {
+
+    if (First) {
+      First = 0;
+
+      const Int_t nh = runheader.GetNumSamplesHiGain();
+      const Int_t nl = runheader.GetNumSamplesLoGain();
+      const Int_t nt = nh+nl;
+      
+    }
+
+    
+    htime->Fill(timecam[ipix].GetArrivalTimeHiGain());
+    hsig->Fill(sigcam[ipix].GetExtractedSignalHiGain());
+
+
+    MRawEvtPixelIter pixel(&evtdata);
+    pixel.Jump(ipix);
+
+    Bool_t ABFlag = pixel.HasABFlag();
+
+   
+    count++; // couter for the number of events
+
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+  
+    const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+
+    Float_t PedMean[2];
+    PedMean[0] = ped_mean + ABoffs;
+    PedMean[1] = ped_mean - ABoffs;
+
+
+    // calculate the noise autocorrelation matrix
+    for (int slice=0; slice<nh; slice++) {     
+      bi[slice]+= higains[slice]-PedMean[(slice+ABFlag)&0x1];
+      bj[slice]+= higains[slice]-PedMean[(slice+ABFlag)&0x1];  
+      for (int ii = 0; ii< nh; ii++){
+	B[slice][ii]+=(higains[slice]-PedMean[(slice+ABFlag)&0x1])*(higains[ii]-PedMean[(ii+ABFlag)&0x1]);
+      }
+    }
+
+
+    // compute the noise signal shape
+    
+    Int_t trigger = 0;
+    Double_t charge = 0;
+    Double_t charge_time = 0;
+
+
+    for (int slice=0; slice<nh; slice++) {
+      shape->Fill(slice,higains[slice]-PedMean[(slice+ABFlag)&0x1]);
+      shape->Fill(slice+nh,logains[slice]-PedMean[(slice+ABFlag)&0x1]);
+      if (trigger==0 && (higains[slice]-PedMean[(slice+ABFlag)&0x1]) >= 4.0) 
+	trigger = slice;
+    }
+
+    for (int slice=0; slice<nh; slice++) 
+      if (trigger>=1 && slice<=trigger+2){
+	 charge += higains[slice]-PedMean[(slice+ABFlag)&0x1];
+	 charge_time += slice*(higains[slice]-PedMean[(slice+ABFlag)&0x1]);
+      }
+  
+    if (charge>0) charge_time /= charge;
+
+    for (int slice=0; slice<nh; slice++)
+      if (trigger>=1)
+	shape_corr->Fill(slice+3-charge_time,(higains[slice]-PedMean[(slice+ABFlag)&0x1]));
+
+
+
+    
+  } // end eventloop.Process()
+  
+  evtloop.PostProcess();
+
+
+  for (int i=0; i<15; i++){
+    for (int j=0; j<15; j++){
+      hcorr->Fill(i,j,B[i][j]/count-bi[i]/count*bj[j]/count);
+      //      cout << "i " << i << " j " << j << " B[i][j] " << B[i][j] << " bi[i] " << bi[i] << " bj[j] " << bj[j] << endl;
+    }
+  }
+
+  cout << " pedmean " << ped_mean << " pedRMS " << pedRMS << endl;
+
+
+  TCanvas * c_corr = new TCanvas("c_corr","c_corr",600,400);
+  c_corr->SetFillColor(0);
+  c_corr->SetBorderMode(0);
+  c_corr->SetGridx();
+  c_corr->SetGridy();
+  gStyle->SetPalette(1);
+
+  hcorr->SetStats(0);
+  hcorr->SetTitle(title);
+  hcorr->SetXTitle("slice i");
+  hcorr->SetYTitle("slice j");
+  hcorr->Draw("colz");
+
+ 
+  TCanvas * c_corr_px = new TCanvas("c_corr_px","c_corr_px",600,400);
+  c_corr_px->SetFillColor(0);
+  c_corr_px->SetBorderMode(0);
+  c_corr_px->SetGridx();
+  c_corr_px->SetGridy();
+  
+  TH1F * hcorr_px = (TH1F*)hcorr->ProjectionX("hcorr_px",6,6);
+  hcorr_px->SetLineColor(4);
+  hcorr_px->SetLineWidth(2);
+  hcorr_px->SetStats(0);
+  TString title1 = "Noise Autocorrelation, FADC sample 6, Pixel";
+  title1+=ipix;
+  hcorr_px->SetTitle(title);
+  hcorr_px->SetXTitle("slice i");
+  hcorr_px->SetYTitle("B_{ij} = <b_{i}*b_{j}> - <b_{i}>*<b_{j}> [FADC counts]");
+  
+  hcorr_px->Draw();
+
+
+
+  TCanvas * c_shape = new TCanvas("c_shape","c_shape",600,400);
+  c_shape->SetFillColor(0);
+  c_shape->SetBorderMode(0);
+  c_shape->SetGridx();
+  c_shape->SetGridy();
+  shape->SetStats(0);
+  TString title2 = "Noise Signal Shape, Signal #geq 3 FADC counts, Pixel ";
+  title2+=ipix;
+  shape->SetTitle(title2);
+  shape->SetXTitle("FADC sample no.");
+  shape->SetYTitle("signal [FADC counts]");
+  shape->SetMarkerStyle(20);
+  shape->SetMarkerColor(4);
+  shape->SetMarkerSize(0.3);
+  shape->Draw();
+
+  
+  TCanvas * c_shape_corr = new TCanvas("c_shape_corr","c_shape_corr",600,400);
+  c_shape_corr->SetFillColor(0);
+  c_shape_corr->SetBorderMode(0);
+  c_shape_corr->SetGridx();
+  c_shape_corr->SetGridy();
+  shape_corr->SetStats(0);
+  TString title3 = "Noise Signal Shape, Signal #geq 3 FADC counts, Pixel ";
+  title3+=ipix;
+  shape_corr->SetTitle(title3);
+  shape_corr->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr->SetYTitle("signal [FADC counts]");
+  shape_corr->SetMarkerStyle(20);
+  shape_corr->SetMarkerColor(4);
+  shape_corr->SetMarkerSize(0.3);
+  shape_corr->Draw();
+
+
+  TCanvas * c_sig = new TCanvas("c_sig","c_sig",600,400);
+  c_sig->SetFillColor(0);
+  c_sig->SetBorderMode(0);
+  c_sig->SetGridx();
+  c_sig->SetGridy();
+
+  hsig->SetStats(0);
+  TString title4 = "Noise Extracted Charge, MExtractFixedWindowPeakSearch, Pixel ";
+  title4+=ipix;
+  hsig->SetTitle(title4);
+  hsig->SetXTitle("reco charge [FADC counts]");
+  hsig->SetYTitle("events / 2 FADC counts");
+  hsig->SetLineColor(4);
+  hsig->SetLineWidth(2);
+  hsig->Draw();
+
+  TCanvas * c_time = new TCanvas("c_time","c_time",600,400);
+  c_time->SetFillColor(0);
+  c_time->SetBorderMode(0);
+  c_time->SetGridx();
+  c_time->SetGridy();
+
+  htime->SetStats(0);
+  TString title5 = "Noise Arrival Time, MExtractTimeHighestIntegral, Pixel ";
+  title5+=ipix;
+  htime->SetTitle(title5);
+  htime->SetXTitle("arrival time [T_{ADC}]");
+  htime->SetYTitle("events / 0.1 T_{ADC}");
+  htime->SetLineColor(4);
+  htime->SetLineWidth(2);
+  htime->Draw();
+
+}
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/noise_autocorrelation_AB_all.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/noise_autocorrelation_AB_all.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/noise_autocorrelation_AB_all.C	(revision 9772)
@@ -0,0 +1,358 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko  09/2004 <mailto:hbartko@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+const TString defname = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_03/20040903_35698_P_multiplexFADC_E.root";
+const TString defpedname = "/.magic/magicserv01/scratch/hbartko/rootdata/2004_09_03/20040903_35698_P_multiplexFADC_E.root";
+
+// works with one pedestal file to calculate the noise autocorrelation
+
+
+
+
+void noise_autocorrelation_AB_all(const TString fname = defpedname, const TString pedname = defpedname) {
+
+
+  //  for (int i=1; i++; i<397){
+
+  TH2F bla;
+  TH2F * hcorr = new TH2F("hcorr","hcorr",15,0,15,15,0,15);
+
+
+  for (int i=1; i<397; i++){
+    bla = noise_autocorrelation_AB_pix(fname,pedname, i);
+    
+    hcorr->Add(&bla);
+  }
+
+  
+  TCanvas * c_corr = new TCanvas("c_corr","c_corr",600,400);
+  c_corr->SetFillColor(0);
+  c_corr->SetBorderMode(0);
+  c_corr->SetGridx();
+  c_corr->SetGridy();
+  gStyle->SetPalette(1);
+
+  hcorr->Scale(1./396.);
+ 
+  hcorr->Draw("colz");
+      //  }
+
+}  
+
+
+
+
+
+TH2F noise_autocorrelation_AB_pix(const TString fname = defpedname, const TString pedname = defpedname, Int_t ipix = 67) {
+  
+  MParList plist_ped;
+  
+  MTaskList tlist_ped;
+  plist_ped.AddToList(&tlist_ped);
+  
+  MPedestalCam   pedcam;
+  plist_ped.AddToList(&pedcam);
+  
+  MReadMarsFile read("Events", pedname);
+  read.DisableAutoScheme();
+  tlist_ped.AddToList(&read);
+  
+  MGeomApply     geomapl_ped;
+  MGeomCamMagic  geomcam;
+  tlist_ped.AddToList(&geomapl_ped);
+
+  
+  MPedCalcFromLoGain pedcalc_ped;
+  //pedcalc_ped.SetMaxHiGainVar(20);
+  //pedcalc_ped.SetRange(0, 11, 1, 14);
+  //pedcalc_ped.SetWindowSize(12,14);
+  pedcalc_ped.SetPedestalUpdate(kFALSE);
+  tlist_ped.AddToList(&pedcalc_ped);
+  
+  MEvtLoop evtloop_ped;
+  evtloop_ped.SetParList(&plist_ped);
+  
+  if (!evtloop_ped.Eventloop())
+    return;
+  
+  tlist_ped.PrintStatistics();
+  
+  
+  // now the event loop for the signal reconstruction with pedestals subtracted
+  
+  
+  MParList plist;
+  MTaskList     tlist;
+  plist.AddToList(&tlist);
+
+  plist.AddToList(&pedcam);
+  
+  MRawRunHeader runheader;
+  plist.AddToList(&runheader);
+
+  MRawEvtData evtdata; 
+  plist.AddToList(&evtdata);
+ 
+  MExtractedSignalCam sigcam;
+  plist.AddToList(&sigcam);
+  
+  MArrivalTimeCam timecam;
+  plist.AddToList(&timecam);
+
+  
+  MReadMarsFile read("Events", fname);
+  read.DisableAutoScheme();
+  
+  MGeomApply geomapl;
+
+  Int_t WindowSize = 6;  // size of the chosen integration window for signal and time extraction
+  
+  MExtractFixedWindowPeakSearch extractor;
+  extractor.SetRange(0, 14, 0, 14);
+  extractor.SetWindows( WindowSize, WindowSize, 4);
+  
+  MExtractTimeHighestIntegral   timeext;
+  timeext.SetRange(0, 14, 0, 14);
+  timeext.SetWindowSize(WindowSize,WindowSize);
+
+    
+  tlist.AddToList(&read);
+  tlist.AddToList(&geomapl);
+  tlist.AddToList(&extractor);
+  tlist.AddToList(&timeext);
+
+  
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  
+  if (!evtloop.PreProcess())
+    return;
+
+  TString title = "Noise Autocorrelation B_{ij} = <b_{i}*b_{j}> - <b_{i}>*<b_{j}>, Pixel ";
+  title += ipix;
+ 
+
+  Int_t First = 1;
+
+  TH2F hcorr("hcorr","hcorr",15,0,15,15,0,15);
+ 
+ 
+  Float_t B[15][15];
+  Float_t bi[15];
+  Float_t bj[15];
+  
+  for (int i=0; i<15; i++){
+    bi[i]=0;
+    bj[i]=0;
+    for (int j=0; j<15; j++){
+      B[i][j]=0;
+    }
+  }
+
+  const Float_t ped_mean = pedcam[ipix].GetPedestal();
+  const Float_t pedRMS   = pedcam[ipix].GetPedestalRms();
+
+  cout << " ped_mean " << ped_mean << " pedRMS " << pedRMS << " ABoffs " << pedcam[ipix].GetPedestalABoffset() << endl;
+  int count = 0;
+
+  while (tlist.Process()) {
+
+    if (First) {
+      First = 0;
+
+      const Int_t nh = runheader.GetNumSamplesHiGain();
+      const Int_t nl = runheader.GetNumSamplesLoGain();
+      const Int_t nt = nh+nl;
+      
+    }
+
+ 
+
+    MRawEvtPixelIter pixel(&evtdata);
+    pixel.Jump(ipix);
+
+    Bool_t ABFlag = pixel.HasABFlag();
+
+   
+    count++; // couter for the number of events
+
+    const Byte_t *higains = pixel.GetHiGainSamples();
+    const Byte_t *logains = pixel.GetLoGainSamples();
+  
+    const Float_t ABoffs = pedcam[ipix].GetPedestalABoffset();
+
+    Float_t PedMean[2];
+    PedMean[0] = ped_mean + ABoffs;
+    PedMean[1] = ped_mean - ABoffs;
+
+
+    // calculate the noise autocorrelation matrix
+    for (int slice=0; slice<nh; slice++) {     
+      bi[slice]+= higains[slice]-PedMean[(slice+ABFlag)&0x1];
+      bj[slice]+= higains[slice]-PedMean[(slice+ABFlag)&0x1];  
+      for (int ii = 0; ii< nh; ii++){
+	B[slice][ii]+=(higains[slice]-PedMean[(slice+ABFlag)&0x1])*(higains[ii]-PedMean[(ii+ABFlag)&0x1]);
+      }
+    }
+
+
+    // compute the noise signal shape
+    
+    Int_t trigger = 0;
+    Double_t charge = 0;
+    Double_t charge_time = 0;
+
+
+   
+
+
+    
+  } // end eventloop.Process()
+  
+  evtloop.PostProcess();
+
+
+  for (int i=0; i<15; i++){
+    for (int j=0; j<15; j++){
+      hcorr->Fill(i,j,B[i][j]/count-bi[i]/count*bj[j]/count);
+      //      cout << "i " << i << " j " << j << " B[i][j] " << B[i][j] << " bi[i] " << bi[i] << " bj[j] " << bj[j] << endl;
+    }
+  }
+
+  cout << " pedmean " << ped_mean << " pedRMS " << pedRMS << endl;
+
+
+  return hcorr;
+
+  /*
+
+  TCanvas * c_corr = new TCanvas("c_corr","c_corr",600,400);
+  c_corr->SetFillColor(0);
+  c_corr->SetBorderMode(0);
+  c_corr->SetGridx();
+  c_corr->SetGridy();
+  gStyle->SetPalette(1);
+
+  hcorr->SetStats(0);
+  hcorr->SetTitle(title);
+  hcorr->SetXTitle("slice i");
+  hcorr->SetYTitle("slice j");
+  hcorr->Draw("colz");
+
+ 
+  TCanvas * c_corr_px = new TCanvas("c_corr_px","c_corr_px",600,400);
+  c_corr_px->SetFillColor(0);
+  c_corr_px->SetBorderMode(0);
+  c_corr_px->SetGridx();
+  c_corr_px->SetGridy();
+  
+  TH1F * hcorr_px = (TH1F*)hcorr->ProjectionX("hcorr_px",6,6);
+  hcorr_px->SetLineColor(4);
+  hcorr_px->SetLineWidth(2);
+  hcorr_px->SetStats(0);
+  TString title1 = "Noise Autocorrelation, FADC sample 6, Pixel";
+  title1+=ipix;
+  hcorr_px->SetTitle(title);
+  hcorr_px->SetXTitle("slice i");
+  hcorr_px->SetYTitle("B_{ij} = <b_{i}*b_{j}> - <b_{i}>*<b_{j}> [FADC counts]");
+  
+  hcorr_px->Draw();
+
+
+
+  TCanvas * c_shape = new TCanvas("c_shape","c_shape",600,400);
+  c_shape->SetFillColor(0);
+  c_shape->SetBorderMode(0);
+  c_shape->SetGridx();
+  c_shape->SetGridy();
+  shape->SetStats(0);
+  TString title2 = "Noise Signal Shape, Signal #geq 3 FADC counts, Pixel ";
+  title2+=ipix;
+  shape->SetTitle(title2);
+  shape->SetXTitle("FADC sample no.");
+  shape->SetYTitle("signal [FADC counts]");
+  shape->SetMarkerStyle(20);
+  shape->SetMarkerColor(4);
+  shape->SetMarkerSize(0.3);
+  shape->Draw();
+
+  
+  TCanvas * c_shape_corr = new TCanvas("c_shape_corr","c_shape_corr",600,400);
+  c_shape_corr->SetFillColor(0);
+  c_shape_corr->SetBorderMode(0);
+  c_shape_corr->SetGridx();
+  c_shape_corr->SetGridy();
+  shape_corr->SetStats(0);
+  TString title3 = "Noise Signal Shape, Signal #geq 3 FADC counts, Pixel ";
+  title3+=ipix;
+  shape_corr->SetTitle(title3);
+  shape_corr->SetXTitle("FADC sample no. + (<t_{arrival}> - t_{arrival}) / T_{ADC}");
+  shape_corr->SetYTitle("signal [FADC counts]");
+  shape_corr->SetMarkerStyle(20);
+  shape_corr->SetMarkerColor(4);
+  shape_corr->SetMarkerSize(0.3);
+  shape_corr->Draw();
+
+
+  TCanvas * c_sig = new TCanvas("c_sig","c_sig",600,400);
+  c_sig->SetFillColor(0);
+  c_sig->SetBorderMode(0);
+  c_sig->SetGridx();
+  c_sig->SetGridy();
+
+  hsig->SetStats(0);
+  TString title4 = "Noise Extracted Charge, MExtractFixedWindowPeakSearch, Pixel ";
+  title4+=ipix;
+  hsig->SetTitle(title4);
+  hsig->SetXTitle("reco charge [FADC counts]");
+  hsig->SetYTitle("events / 2 FADC counts");
+  hsig->SetLineColor(4);
+  hsig->SetLineWidth(2);
+  hsig->Draw();
+
+  TCanvas * c_time = new TCanvas("c_time","c_time",600,400);
+  c_time->SetFillColor(0);
+  c_time->SetBorderMode(0);
+  c_time->SetGridx();
+  c_time->SetGridy();
+
+  htime->SetStats(0);
+  TString title5 = "Noise Arrival Time, MExtractTimeHighestIntegral, Pixel ";
+  title5+=ipix;
+  htime->SetTitle(title5);
+  htime->SetXTitle("arrival time [T_{ADC}]");
+  htime->SetYTitle("events / 0.1 T_{ADC}");
+  htime->SetLineColor(4);
+  htime->SetLineWidth(2);
+  htime->Draw();
+  */
+}
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mmpi/macros/skyplot.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mmpi/macros/skyplot.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mmpi/macros/skyplot.h	(revision 9772)
@@ -0,0 +1,201 @@
+// temporal solution:
+#define MAXNUMEVENTS 500000
+#define LOG3000      log(3000.)
+
+TString HILLASFILENAME;
+TString DATPARAMIN;
+TString DATPARAMOUT;
+TString ROOTPLOTNAME;
+Int_t imnum = 0;
+
+TVectorD lengthpar(MAXNUMEVENTS);
+TVectorD widthpar(MAXNUMEVENTS);
+TVectorD distpar(MAXNUMEVENTS);
+TVectorD alphapar(MAXNUMEVENTS);
+TVectorD sizepar(MAXNUMEVENTS);
+TVectorD deltapar(MAXNUMEVENTS);
+TVectorD xpar(MAXNUMEVENTS);
+TVectorD ypar(MAXNUMEVENTS);
+TVectorD conc1(MAXNUMEVENTS);
+TVectorD leak1(MAXNUMEVENTS);
+TVectorD cosgam(MAXNUMEVENTS);
+TVectorD singam(MAXNUMEVENTS);
+
+// the alpha histogram
+MBinning bins;
+
+//TH1F histalphagrid;
+//histalphagrid.SetName("Alpha");
+//histalphagrid.SetTitle("Alpha");
+//histalphagrid.SetXTitle("Alpha [deg]");
+//histalphagrid.SetYTitle("Counts");
+//histalphagrid.SetDirectory(NULL);
+//histalphagrid.SetFillStyle(4000);
+//histalphagrid.UseCurrentStyle(); 
+
+bins.SetEdges(18, 0.0, 90.);
+bins.Apply(histalphagrid);
+
+
+
+// possible histograms:
+TH1F histlength;
+TH1F histwidth;
+TH1F histsize;
+TH1F histalpha;
+TH1F histdist;
+TH1F histmeanx;
+TH1F histmeany;
+TH1F histalphafinal;
+
+TH2F hist2xy("CoG1","Center of Gravity", 100, -1.8, 1.8, 100, -1.8, 1.8);
+TH1F histLoverS;
+TH1F aftercuthistlength;
+TH1F aftercuthistwidth;
+TH1F aftercuthistsize;
+TH1F aftercuthistalpha;
+TH1F aftercuthistdist;
+TH1F aftercuthistmeanx;
+TH1F aftercuthistmeany;
+TH2F aftercuthist2xy("CoG2","Center of Gravity", 100, -1.8, 1.8, 100, -1.8, 1.8);
+TH2F hist2lw("Length-Width", "correlation Length-Width", 100, 0.0, 1.0, 100, 0.0, 0.5);
+TH2F hist2lalpha("Length-Alpha", "correlation Length-Alpha", 100, 0.0, 1.0, 100, -100., 100.);
+TH2F hist2ldist("Length-Dist","correlation Length-Dist", 100, 0.0, 1.0, 100, 0.0, 1.6);
+TH2F hist2walpha("Width-Alpha","correlation Width-Alpha", 100, 0.0, 0.5, 100, -100., 100.);
+TH2F hist2wdist("Width-Dist","correlation Width-Dist", 100, 0.0, 0.5, 100, 0.0, 1.6);
+TH2F hist2alphadist("Alpha-Dist","correlation Alpha-Dist", 100, -100., 100, 100, 0.2, 1.4);
+
+
+TH2F histskyplot("SPSignif2ndOrder","Sky Plot of significance (2nd order fit)", 
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histskyplot.SetXTitle("-RA [deg]");
+//histskyplot.SetYTitle("DEC [deg]");
+histskyplot.SetDirectory(NULL);
+histskyplot.SetFillStyle(4000);
+histskyplot.UseCurrentStyle();
+
+TH2F histNexOnOff("SPNexOnOff","Sky Plot of Number of excess events (using ON and OFF data)", 
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histNexOnOff.SetXTitle("-RA [deg]");
+//histNexOnOff.SetYTitle("DEC [deg]");
+histNexOnOff.SetDirectory(NULL);
+histNexOnOff.SetFillStyle(4000);
+histNexOnOff.UseCurrentStyle();
+
+TH2F histChi2Off("SPChi2PerNdf2ndOrderOff","Sky Plot of Chi2/ndf (2nd order fit, OFF data)", 
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histChi2Off.SetXTitle("-RA [deg]");
+//histChi2Off.SetYTitle("DEC [deg]");
+histChi2Off.SetDirectory(NULL);
+histChi2Off.SetFillStyle(4000);
+histChi2Off.UseCurrentStyle();
+
+TH2F histskyplotOnOff("SPSignifOnOff","Sky Plot of significance (using ON and OFF data)", 
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histskyplotOnOff.SetXTitle("-RA [deg]");
+//histskyplotOnOff.SetYTitle("DEC [deg]");
+histskyplotOnOff.SetDirectory(NULL);
+histskyplotOnOff.SetFillStyle(4000);
+histskyplotOnOff.UseCurrentStyle();
+
+TH2F histNex("SPNex2ndOrder","Sky Plot of Number of excess events (2nd order fit)",
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histNex.SetXTitle("-RA [deg]");
+//histNex.SetYTitle("DEC [deg]");
+histNex.SetDirectory(NULL);
+histNex.SetFillStyle(4000);
+histNex.UseCurrentStyle();
+
+TH2F histChi2("SPChi2PerNdf2ndOrderOn","Sky Plot of Chi2/ndf (2nd order fit)", 
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histChi2.SetXTitle("-RA [deg]");
+//histChi2.SetYTitle("DEC [deg]");
+histChi2.SetDirectory(NULL);
+histChi2.SetFillStyle(4000);
+histChi2.UseCurrentStyle();
+
+TH2F histskyplot4("SPSignif4thOrder","Sky Plot of significance (4th order fit)", 
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histskyplot4.SetXTitle("-RA [deg]");
+//histskyplot4.SetYTitle("DEC [deg]");
+histskyplot4.SetDirectory(NULL);
+histskyplot4.SetFillStyle(4000);
+histskyplot4.UseCurrentStyle();
+
+TH2F histskyLiMa("SPSignifLiMaOnOff","Sky Plot of significance (ON - OFF LiMa17)", 
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histskyLiMa.SetXTitle("-RA [deg]");
+//histskyLiMa.SetYTitle("DEC [deg]");
+histskyLiMa.SetDirectory(NULL);
+histskyLiMa.SetFillStyle(4000);
+histskyLiMa.UseCurrentStyle();
+
+TH2F histBerlin("SPBerlinMethod","Sky Plot of Events below alpha 8 degrees", 
+                 NUMSTEPS, MINXGRID - 0.5*STEPGRID, MAXXGRID + 0.5*STEPGRID,
+                 NUMSTEPS, MINYGRID - 0.5*STEPGRID, MAXYGRID + 0.5*STEPGRID);
+//histskyLiMa.SetXTitle("-RA [deg]");
+//histskyLiMa.SetYTitle("DEC [deg]");
+histBerlin.SetDirectory(NULL);
+histBerlin.SetFillStyle(4000);
+histBerlin.UseCurrentStyle();
+
+TH1F histsign;
+histsign.SetName("Significance 1");
+histsign.SetTitle("Significance (2nd order fit)");
+histsign.SetXTitle("significance");
+histsign.SetYTitle("Counts");
+histsign.SetDirectory(NULL);
+histsign.SetFillStyle(4000);
+histsign.UseCurrentStyle(); 
+
+ bins.SetEdges(20, -5., 8.);
+ bins.Apply(histsign);
+
+TH1F histsign4;
+histsign4.SetName("Significance 2");
+histsign4.SetTitle("Significance (4th order fit)");
+histsign4.SetXTitle("significance");
+histsign4.SetYTitle("Counts");
+histsign4.SetDirectory(NULL);
+histsign4.SetFillStyle(4000);
+histsign4.UseCurrentStyle(); 
+
+ bins.SetEdges(20, -5., 8.);
+ bins.Apply(histsign4);
+
+
+TH1F histalphagrid;
+histalphagrid.SetName("Alpha");
+histalphagrid.SetTitle("Alpha");
+//histalphagrid.SetXTitle("Alpha [deg]");
+histalphagrid.SetYTitle("Counts");
+histalphagrid.SetDirectory(NULL);
+histalphagrid.SetFillStyle(4000);
+histalphagrid.UseCurrentStyle(); 
+
+ bins.SetEdges(18, 0.0, 90.);
+ bins.Apply(histalphagrid);
+
+/*
+#define n 100
+Double_t binsize[n];
+Float_t nmin = 100.;
+Float_t nmax = 1e7;
+
+for(Int_t i=0; i<n; i++)
+{
+binsize[i] = pow(10., log10(nmin) + i * (log10(nmax) - log10(nmin)) / (n-1.));
+}
+
+TH2F hist2wsize("Width-Size", "correlation Width-Size", 100, 0.0, 0.5, n-1, binsize);
+TH2F hist2alphasize("Alpha-Size","correlation Alpha-Size", 100, -100., 100., n-1, binsize);
+TH2F hist2distsize("Dist-Size","correlation Dist-Size", 100, 0.0, 1.6, n-1, binsize);
+*/
Index: /tags/Mars-V0.9/mtemp/mpadova/macros/RanForestDISP.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpadova/macros/RanForestDISP.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpadova/macros/RanForestDISP.C	(revision 9772)
@@ -0,0 +1,337 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that both that copyright notice and this permission notice appear
+   ! * in supporting documentation. It is provided "as is" without express
+   ! * or implied warranty.
+   ! *
+   !
+   !
+   !   Author(s): Abelardo Moralejo 1/2005 <mailto:moralejo@pd.infn.it>!
+   !
+   !   Copyright: MAGIC Software Development, 2000-2003
+   !
+   !
+   \* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////////
+//
+// macro RanForestDISP.C
+//
+// Version of Random Forest macro, intended to run on real data without assuming 
+// any particular source position in the camera FOV. So we do not use the DIST
+// parameter, but rather (one version of) DISP method. We do not use either the 
+// sign of the third longitudinal moment with respect to the center of the camera 
+// (since the source can be somewhere else like in the case of wobble mode).
+//
+//////////////////////////////////////////////////////////////////////////////////
+
+
+#include "MMcEvt.hxx"
+
+void RanForestDISP(Int_t minsize=1000)
+{
+    Int_t mincorepixels = 6; // minimum number of core pixels.
+//  Int_t mincorepixels = 0;
+
+    TString skipevents;
+    //  skipevents = "(MMcEvt.fImpact>15000.)";
+    //  skipevents = "(MNewImagePar.fLeakage1>0.001)";
+    //  skipevents = "(MHillas.fSize>1000)";
+
+    // Skip calibration events, leaking events and flash events:
+    skipevents = "(MNewImagePar.fLeakage1>0.1) || ({1.5+log10(MNewImagePar.fConc)*2.33333}-{6.5-log10(MHillas.fSize)}>0.)";
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+
+    MReadMarsFile  read("Events", "/data1/magic/mc_data/root/Period021_0.73_mirror/FixedWindowPeakSearch/WOBBLE_Calib_6slices/tc_3.84_2.56/star_gamma_train_new.root");
+    Float_t numgammas = read.GetEntries();
+
+    read.AddFile("star_train_20050110_CrabNebulaW1.root");
+    Float_t numhadrons = read.GetEntries() - numgammas;
+
+    // Fraction of gammas to be used in training:
+    //    Float_t gamma_frac = 1.5*(numhadrons / numgammas);
+    Float_t gamma_frac = 1.;
+
+    // Total hadron number to be processed in training:
+    // If you run RF over different data runs, using always the same # of training gammas,
+    // you should also use always a fixed number of hadrons for training (although the data 
+    // runs may be of different duration). Otherwise the meaning of the output hadronness 
+    // would be different for the different subsamples, since its absolute values depend on 
+    // the statistics of the training sample. The number set here is the number BEFORE the
+    // "a priori cuts" set above through "skipevents".
+
+    Float_t select_n_hadrons = 37000.;  
+    Float_t hadron_frac = select_n_hadrons / numhadrons;
+
+    read.DisableAutoScheme();
+
+    tlist.AddToList(&read);
+
+    MFParticleId fgamma("MMcEvt", '=', MMcEvt::kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    MFParticleId fhadrons("MMcEvt", '!', MMcEvt::kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+
+    MHMatrix matrixg("MatrixGammas");
+
+    // TEST TEST TEST
+//     matrixg.AddColumn("MMcEvt.fImpact");
+//     matrixg.AddColumn("MMcEvt.fMuonCphFraction");
+
+    //    matrixg.AddColumn("MNewImagePar.fLeakage1");
+    //    matrixg.AddColumn("floor(0.5+(cos(MMcEvt.fTelescopeTheta)/0.01))");
+
+    //    matrixg.AddColumn("MMcEvt.fTelescopePhi");
+    //    matrixg.AddColumn("MSigmabar.fSigmabar");
+
+
+    matrixg.AddColumn("MHillas.fSize");
+
+    // We do not use DIST, since it depends on knowing the source position on camera.
+    // In wobble mode the position changes with time. Besides, we intend to do a 2-d map
+    // with the DISP method, and so we cannot use DIST in the cuts (since it would amde the
+    // camera center a "provoleged" position).
+
+    matrixg.AddColumn("(1.-(MHillas.fWidth/MHillas.fLength))*(0.9776+(0.101062*log10(MHillas.fSize)))");
+
+//     matrixg.AddColumn("MHillas.fWidth");
+//     matrixg.AddColumn("MHillas.fLength");
+
+
+    // Scaling from real data?
+    //    matrixg.AddColumn("MHillas.fWidth/(-8.37847+(9.58826*log10(MHillas.fSize)))");   
+    //    matrixg.AddColumn("MHillas.fLength/(-40.1409+(29.3044*log10(MHillas.fSize)))");
+
+    // Scaling from MC:
+    matrixg.AddColumn("(MHillas.fWidth*3.37e-3)/(-0.028235+(0.03231*log10(MHillas.fSize)))");   
+    matrixg.AddColumn("(MHillas.fLength*3.37e-3)/(-0.13527+(0.09876*log10(MHillas.fSize)))");
+
+    matrixg.AddColumn("MNewImagePar.fConc");
+
+    // TEST TEST TEST TEST
+    //    matrixg.AddColumn("MConcentration.Conc7");
+
+    //    matrixg.AddColumn("MNewImagePar.fConc1");
+    //    matrixg.AddColumn("MNewImagePar.fAsym");
+    //    matrixg.AddColumn("MHillasExt.fM3Trans");
+    //    matrixg.AddColumn("abs(MHillasSrc.fHeadTail)");
+
+
+    // We cannot use the 3rd moment with a sign referred to the nominal source position, if we
+    // assume we do not know it a priori. We cannot use either the sign as referred to the 
+    // reconstructed source position through the DISP method, since that method uses precisely 
+    // fM3Long to solve the "head-tail" asimetry and hence all showers would be "gamma-like" from
+    // that point of view. We add however the 3rd moment with no sign to the separation parameters.
+
+    matrixg.AddColumn("abs(MHillasExt.fM3Long)");
+
+    //    matrixg.AddColumn("MHillasSrc.fAlpha");
+
+    TString dummy("(MHillas.fSize<");
+    dummy += minsize;
+
+    // AM TEST
+    dummy += ") || (MNewImagePar.fNumCorePixels<";
+    dummy += mincorepixels;
+
+    // AM, useful FOR High Energy only:
+    //    dummy += ") || (MImagePar.fNumSatPixelsLG>0";
+    dummy += ")";
+
+    MContinue SizeCut(dummy);
+    tlist.AddToList(&SizeCut);
+
+
+    if (skipevents != "")
+    {
+	MContinue SCut(skipevents);
+	tlist.AddToList(&SCut);
+    }
+
+    plist.AddToList(&matrixg);
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.AddColumns(matrixg.GetColumns());
+    plist.AddToList(&matrixh);
+
+    MFEventSelector reduce_training_hadrons;
+    reduce_training_hadrons.SetSelectionRatio(hadron_frac);
+    MFilterList hadfilter;
+    hadfilter.AddToList(&reduce_training_hadrons);
+    hadfilter.AddToList(&fhadrons);
+    tlist.AddToList(&hadfilter);
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&hadfilter);
+    tlist.AddToList(&fillmath);
+
+    MContinue skiphad(&fhadrons);
+    tlist.AddToList(&skiphad);
+
+    MFEventSelector reduce_training_gammas;
+    reduce_training_gammas.SetSelectionRatio(gamma_frac);
+    tlist.AddToList(&reduce_training_gammas);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&reduce_training_gammas);
+    tlist.AddToList(&fillmatg);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    MProgressBar *bar = new MProgressBar;
+    evtloop.SetProgressBar(bar);
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // second event loop: the trees of the random forest are grown,
+    // the event loop is now actually a tree loop (loop of training
+    // process)
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist2;
+    plist.Replace(&tlist2);
+
+    //
+    //    matrixh.ShuffleRows(9999);
+    //    matrixg.ShuffleRows(1111);
+    //
+
+    MRanForestGrow rfgrow2;
+    rfgrow2.SetNumTrees(100);
+    rfgrow2.SetNumTry(3);
+    rfgrow2.SetNdSize(10);
+
+    MWriteRootFile rfwrite2("RF.root");
+    rfwrite2.AddContainer("MRanTree","Tree");       //save all trees
+    MFillH fillh2("MHRanForestGini");
+
+    tlist2.AddToList(&rfgrow2);
+    tlist2.AddToList(&rfwrite2);
+    tlist2.AddToList(&fillh2);
+
+    // gRandom is accessed from MRanForest (-> bootstrap aggregating)
+    // and MRanTree (-> random split selection) and should be initialized
+    // here if you want to set a certain random number generator
+    if(gRandom)
+        delete gRandom;
+    //    gRandom = new TRandom3(0); // Takes seed from the computer clock
+    gRandom = new TRandom3(); // Uses always  same seed
+    //
+    // Execute tree growing (now the eventloop is actually a treeloop)
+    //
+
+    evtloop.SetProgressBar(bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist2.PrintStatistics();
+
+    plist.FindObject("MHRanForestGini")->DrawClone();
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // third event loop: the control sample (star2.root) is processed
+    // through the previously grown random forest,
+    //
+    // the histograms MHHadronness (quality of g/h-separation) and
+    // MHRanForest are created and displayed.
+    // MHRanForest shows the convergence of the classification error
+    // as function of the number of grown (and combined) trees
+    // and tells the user how many trees are actually needed in later
+    // classification tasks.
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist3;
+
+    plist.Replace(&tlist3);
+
+
+    MReadMarsFile  read3("Events", "star_20050110_CrabNebulaW1.root");
+    //    MReadMarsFile  read3("Events", "/data1/magic/mc_data/root/Period021_0.73_mirror/FixedWindowPeakSearch/WOBBLE_Calib_6slices/tc_3.84_2.56/star_gamma_test.root");
+
+    read3.DisableAutoScheme();
+    tlist3.AddToList(&read3);
+    tlist3.AddToList(&SizeCut);
+
+    if (skipevents != "")
+	tlist3.AddToList(&SCut);
+
+    MRanForestCalc calc;
+    tlist3.AddToList(&calc);
+
+
+    TString outfname = "star_S";
+    outfname += minsize;
+    outfname += "_20050110_CrabNebulaW1.root";
+
+    //    outfname += "_mcgammas.root";
+
+    // parameter containers you want to save
+    //
+
+    MWriteRootFile write(outfname, "recreate");
+
+    //    write.AddContainer("MSigmabar", "Events");
+
+    write.AddContainer("MRawEvtHeader",  "Events");
+    write.AddContainer("MMcEvt",         "Events", kFALSE);
+    write.AddContainer("MHillas",        "Events");
+    write.AddContainer("MHillasExt",     "Events");
+    write.AddContainer("MImagePar",      "Events");
+    write.AddContainer("MNewImagePar",   "Events");
+    write.AddContainer("MHillasSrc",     "Events");
+    write.AddContainer("MHadronness",    "Events");
+    write.AddContainer("MPointingPos",   "Events");
+    write.AddContainer("MTime",          "Events", kFALSE);
+    write.AddContainer("MConcentration", "Events", kFALSE);
+
+    tlist3.AddToList(&write);
+
+    evtloop.SetProgressBar(bar);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist3.PrintStatistics();
+
+    //    bar->DestroyWindow();
+
+    return;
+}
Index: /tags/Mars-V0.9/mtemp/mpadova/macros/RanForestPD.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpadova/macros/RanForestPD.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpadova/macros/RanForestPD.C	(revision 9772)
@@ -0,0 +1,285 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Hengstebeck 3/2003 <mailto:hengsteb@alwa02.physik.uni-siegen.de>!
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+#include "MMcEvt.hxx"
+
+void RanForestPD(Int_t minsize=0)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadMarsFile  read("Events", "star_gamma_train.root");
+    Float_t numgammas = read.GetEntries();
+
+    read.AddFile("star_proton_train.root");
+    read.AddFile("star_helium_train.root");
+
+    Float_t numhadrons = read.GetEntries() - numgammas;
+
+    // Fraction of gammas to be used in training:
+    // (less than total sample, to speed up execution)
+    //
+    Float_t gamma_frac = 2.*(numhadrons / numgammas);
+
+
+    read.DisableAutoScheme();
+
+    tlist.AddToList(&read);
+
+     MFParticleId fhadrons("MMcEvt", '!', MMcEvt::kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    MHMatrix matrixg("MatrixGammas");
+
+    //    matrixg.AddColumn("floor(0.5+(cos(MMcEvt.fTelescopeTheta)/0.01))");
+    //    matrixg.AddColumn("MMcEvt.fTelescopePhi");
+    //    matrixg.AddColumn("MSigmabar.fSigmabar");
+
+    matrixg.AddColumn("MHillas.fSize");
+    matrixg.AddColumn("MHillasSrc.fDist");
+
+    //    matrixg.AddColumn("MHillas.fWidth");
+    //    matrixg.AddColumn("MHillas.fLength");
+
+    // Scaled Width and Length:
+    //
+    matrixg.AddColumn("MHillas.fWidth/(-13.1618+(10.0492*log10(MHillas.fSize)))");   
+    matrixg.AddColumn("MHillas.fLength/(-57.3784+(32.6131*log10(MHillas.fSize)))");
+
+    //    matrixg.AddColumn("(MHillas.fSize/(MHillas.fWidth*MHillas.fLength))");
+    matrixg.AddColumn("MNewImagePar.fConc");
+
+    //    matrixg.AddColumn("MNewImagePar.fConc1");
+    //    matrixg.AddColumn("MNewImagePar.fAsym");
+    //    matrixg.AddColumn("MHillasExt.fM3Trans");
+    //    matrixg.AddColumn("abs(MHillasSrc.fHeadTail)");
+    //    matrixg.AddColumn("MNewImagePar.fLeakage1");
+
+    //
+    // Third moment, with sign referred to source position:
+    //
+    matrixg.AddColumn("MHillasExt.fM3Long*MHillasSrc.fCosDeltaAlpha/abs(MHillasSrc.fCosDeltaAlpha)");
+
+    //#    matrixg.AddColumn("MHillasSrc.fAlpha");
+
+    //
+    // SIZE cut:
+    //
+    TString dummy("(MHillas.fSize<");
+    dummy += minsize;
+    dummy += ")";
+
+    // AM, useful FOR High Energy only:
+    //    dummy += " || (MImagePar.fNumSatPixelsLG>0)";
+
+    MContinue SizeCut(dummy);
+    tlist.AddToList(&SizeCut);
+
+    // AM TEST!!!, no muons in train
+    //    dummy = "(MMcEvt.fMuonCphFraction>0.1)";
+    //    MContinue MuonsCut(dummy);
+    //    tlist.AddToList(&MuonsCut);
+
+    plist.AddToList(&matrixg);
+
+    MHMatrix matrixh("MatrixHadrons");
+    matrixh.AddColumns(matrixg.GetColumns());
+    plist.AddToList(&matrixh);
+
+    MFillH fillmath("MatrixHadrons");
+    fillmath.SetFilter(&fhadrons);
+    tlist.AddToList(&fillmath);
+
+    MContinue skiphad(&fhadrons);
+    tlist.AddToList(&skiphad);
+
+    MFEventSelector reduce_training_gammas;
+    reduce_training_gammas.SetSelectionRatio(gamma_frac);
+    tlist.AddToList(&reduce_training_gammas);
+
+    MFillH fillmatg("MatrixGammas");
+    fillmatg.SetFilter(&reduce_training_gammas);
+    tlist.AddToList(&fillmatg);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // second event loop: the trees of the random forest are grown,
+    // the event loop is now actually a tree loop (loop of training
+    // process)
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist2;
+    plist.Replace(&tlist2);
+
+    MRanForestGrow rfgrow2;
+    rfgrow2.SetNumTrees(100);
+    rfgrow2.SetNumTry(3);
+    rfgrow2.SetNdSize(10);
+
+    MWriteRootFile rfwrite2("RF.root");
+    rfwrite2.AddContainer("MRanTree","Tree");       //save all trees
+    MFillH fillh2("MHRanForestGini");
+
+    tlist2.AddToList(&rfgrow2);
+    tlist2.AddToList(&rfwrite2);
+    tlist2.AddToList(&fillh2);
+
+    // gRandom is accessed from MRanForest (-> bootstrap aggregating)
+    // and MRanTree (-> random split selection) and should be initialized
+    // here if you want to set a certain random number generator
+    if(gRandom)
+        delete gRandom;
+    //    gRandom = new TRandom3(0); // Takes seed from the computer clock
+    gRandom = new TRandom3(); // Uses always  same seed
+    //
+    // Execute tree growing (now the eventloop is actually a treeloop)
+    //
+
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist2.PrintStatistics();
+
+    plist.FindObject("MHRanForestGini")->DrawClone();
+
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+    // third event loop: the control sample (star2.root) is processed
+    // through the previously grown random forest,
+    //
+    // the histograms MHHadronness (quality of g/h-separation) and
+    // MHRanForest are created and displayed.
+    // MHRanForest shows the convergence of the classification error
+    // as function of the number of grown (and combined) trees
+    // and tells the user how many trees are actually needed in later
+    // classification tasks.
+    // ---------------------------------------------------------------
+    // ---------------------------------------------------------------
+
+    MTaskList tlist3;
+
+    plist.Replace(&tlist3);
+
+    MReadMarsFile  read3("Events", "star_gamma_test.root");
+
+    read3.AddFile("star_proton_test.root");
+    read3.AddFile("star_helium_test.root");
+
+    read3.DisableAutoScheme();
+    tlist3.AddToList(&read3);
+
+    tlist3.AddToList(&SizeCut);
+
+    MRanForestCalc calc;
+    tlist3.AddToList(&calc);
+
+    // parameter containers you want to save
+    //
+
+    TString outfname = "star_S";
+    outfname += minsize;
+    outfname += "_all.root";
+    MWriteRootFile write(outfname, "recreate");
+
+    write.AddContainer("MMcEvt",         "Events");
+    write.AddContainer("MHillas",        "Events");
+    write.AddContainer("MHillasExt",     "Events");
+    write.AddContainer("MImagePar",      "Events");
+    write.AddContainer("MNewImagePar",   "Events");
+    write.AddContainer("MHillasSrc",     "Events");
+    write.AddContainer("MHadronness",    "Events");
+
+    write.AddContainer("MRawRunHeader", "RunHeaders");
+    write.AddContainer("MSrcPosCam",    "RunHeaders");
+    write.AddContainer("MMcRunHeader",  "RunHeaders");
+
+    /*
+    write.AddContainer("MMcTrig",       "Events");
+    write.AddContainer("MRawEvtData",   "Events");
+    write.AddContainer("MRawEvtHeader", "Events");
+    */
+
+
+    MFillH fillh3a("MHHadronness");
+    MFillH fillh3b("MHRanForest");
+
+    tlist3.AddToList(&fillh3a);
+    tlist3.AddToList(&fillh3b);
+
+
+    tlist3.AddToList(&write);
+
+    evtloop.SetProgressBar(&bar);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist3.PrintStatistics();
+
+    plist.FindObject("MHRanForest")->DrawClone();
+
+    TCanvas *had = new TCanvas;
+    had->cd();
+    plist.FindObject("MHHadronness")->Draw();
+
+    TString gifname = "had_S";
+    gifname += minsize;
+    gifname += ".gif";
+
+    had->SaveAs(gifname);
+    had->Close();
+
+    plist.FindObject("MHHadronness")->DrawClone();
+    plist.FindObject("MHHadronness")->Print();//*/
+
+    return;
+}
Index: /tags/Mars-V0.9/mtemp/mpadova/macros/area.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpadova/macros/area.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpadova/macros/area.C	(revision 9772)
@@ -0,0 +1,113 @@
+void area(Char_t* infilename = "star_S500_all.root", Float_t maxhadronness = 0.1)
+{
+  //
+  // N_gamma_original: Number of generated Corsika showers in the MC sample 
+  // from which the star file has been produced. VERY IMPORTANT!
+
+  const Double_t N_gamma_original = 3.9e6;
+  const Double_t MC_diff_spectrum = -2.6;
+  const Double_t E_MC_min = 10.;
+  const Double_t E_MC_max = 30000.;
+  const Double_t sizecut = 0.;
+  const Double_t mincorepixels = 5;
+  const Double_t leakagemax = 1.;
+
+  MHMcCollectionArea collarea;
+
+  //
+  // Calculate approximately the original number of events in each 
+  // energy bin:
+  //
+
+  const Double_t expo = 1 + MC_diff_spectrum;
+  const Double_t k = N_gamma_original / 
+    (pow(E_MC_max,expo) - pow(E_MC_min,expo)) ;
+
+  TH2D* hall = collarea.GetHistAll();
+
+  const Int_t nbinx = hall.GetNbinsX();
+
+  TAxis &axe = *hall.GetXaxis();
+  for (Int_t i = 1; i <= nbinx; i++)
+    {
+      const Float_t e1 = axe.GetBinLowEdge(i);
+      const Float_t e2 = axe.GetBinLowEdge(i+1);
+      
+      if (e1 < E_MC_min || e2 > E_MC_max)
+	continue;
+
+      const Float_t events = k * (pow(e2, expo) - pow(e1, expo));
+      //
+      // We fill the i-th energy bin, with the total number of events
+      // Second argument of Fill would be impact parameter of each
+      // event, but we don't really need it for the collection area,
+      // so we just put a dummy value (1.)
+      //
+
+      const Float_t energy = (e1+e2)/2.;
+      hall.Fill(energy, 1., events);
+    }
+
+  //
+  // Now open input file, loop over the Events tree and fill the energy
+  // histogram for events passing all required cuts.
+  //
+
+  TChain chain("Events");
+  chain.Add(infilename);
+
+  MMcEvt *mcevt;
+  MHillas *mhillas;
+  MNewImagePar *mnew;
+  MHadronness *mhadronness;
+
+  chain.SetBranchAddress("MMcEvt.", &mcevt);
+  chain.SetBranchAddress("MHillas.", &mhillas);
+  chain.SetBranchAddress("MNewImagePar.", &mnew);
+  chain.SetBranchAddress("MHadronness.", &mhadronness);
+
+  chain.SetBranchStatus("MMcEvt.", 1);
+  chain.SetBranchStatus("MHillas.", 1);
+  chain.SetBranchStatus("MNewImagePar.", 1);
+  chain.SetBranchStatus("MHadronness.", 1);
+
+  for (Int_t ievt = 0; ievt < chain.GetEntries(); ievt++)
+    {
+      chain.GetEvent(ievt);
+
+      if (mcevt->GetPartId() > 1)
+	continue;
+
+      if (mhillas->GetSize() < sizecut)
+	continue;
+
+      if (mnew->GetNumCorePixels() < mincorepixels)
+	continue;
+
+      if (mnew->GetLeakage1() > leakagemax)
+	continue;
+
+      if (mhadronness->GetHadronness() > maxhadronness)
+      	continue;
+
+      const Float_t energy = mcevt->GetEnergy();
+
+      collarea.FillSel(energy,1.);
+      // Second argument is again just a dummy value
+    }
+
+
+  gStyle->SetOptStat(0);
+  gStyle->SetOptLogy();
+  collarea.CalcEfficiency2();
+  collarea.DrawClone();
+
+  //  infile->Close();
+
+  TFile *out = new TFile("area.root", "recreate");
+  collarea.Write();
+  out->Close();
+
+  return;
+
+}
Index: /tags/Mars-V0.9/mtemp/mpadova/macros/gammarate.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpadova/macros/gammarate.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpadova/macros/gammarate.C	(revision 9772)
@@ -0,0 +1,69 @@
+void gammarate()
+{  
+
+   gROOT->Reset();
+   c1 = new TCanvas("c1","Gamma rate",700,300,500,500);
+   c1->SetGridx();
+   c1->SetGridy();
+   c1->SetLogy(1);
+   c1->SetLogx(1);
+ 
+   TFile f("area.root");
+   MHMcCollectionArea* mhmc = (MHMcCollectionArea*)f.Get("MHMcCollectionArea");
+   TH1D* h1 = (TH1D*)mhmc->GetHist();
+   
+    
+   h1->GetXaxis();
+   Float_t xmin = h1->GetXaxis()->GetXmin();
+   Float_t xmax = h1->GetXaxis()->GetXmax();
+   Int_t nbin = h1->GetNbinsX();
+
+   // gamma spectrum:
+   fun1 = new TF1("fun1","10000*2.706e-11*pow(x,-2.47-0.11*log(x))",xmin/1000.,xmax/1000.);
+
+   TH1F *h3f = (TH1F*)h1->Clone("h3f");
+   h3f->SetTitle("Integrale per bin");
+   h3f->Reset();
+   h3f->SetMinimum(1.e-13);
+   h3f->SetMaximum(1.e-7);
+
+   TH1F *h4f = (TH1F*)h1->Clone("h4f");
+
+   h4f->SetTitle("Rate");
+   h4f->Reset();
+   h4f->SetMinimum(1.e-4);
+   h4f->SetMaximum(1.e-1);
+
+
+   Float_t Error = 0.;
+
+   cout << "Bin\tArea\tCenter\tFlux\t\tMolt\tInt\tRate"<<endl; 
+   for (Int_t i = 1; i <= nbin; i++)
+   {     
+     //area->GetXaxis()->FindBin(i)
+     Float_t valArea = h1->GetBinContent(i);      
+     Float_t bincenter = h1->GetBinCenter(i);
+     Float_t valFlusso = fun1->Eval(bincenter/1000., 0., 0.);
+     Float_t Integral = fun1->Integral(h1->GetBinLowEdge(i)/1000.,h1->GetBinLowEdge(i+1)/1000.);
+     h3f->SetBinContent(i,Integral);
+     Float_t Rate = Integral * valArea;
+     Float_t ErArea = h1->GetBinError(i);
+     Float_t ErRate = ErArea * Integral;
+     Error += ErRate*ErRate;
+     h4f->SetBinContent(i,Rate);
+     h4f->SetBinError(i,ErRate);
+     cout << i << "\t" << bincenter << "\t" << Rate << "\t"<< endl;
+    }
+   //h1->DrawCopy(); 
+   //h3f->DrawCopy();
+   h4f->SetStats(kFALSE);
+   h4f->SetTitle("Gamma rate vs energy");
+   h4f->GetYaxis()->SetTitle("Rate");
+   h4f->DrawCopy("pe");
+
+   cout << "Rate (Hz):" << h4f->Integral(0,100)<< " +- " <<pow(Error, .5)<<endl;
+
+   h4f->Delete();
+   h3f->Delete();
+   h1->Delete();
+}
Index: /tags/Mars-V0.9/mtemp/mpadova/macros/plotnoise.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpadova/macros/plotnoise.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpadova/macros/plotnoise.C	(revision 9772)
@@ -0,0 +1,55 @@
+void plotnoise()
+{
+  // Simple macro to read calibrated pedestal files, from MC and real data, and compare 
+  // fluctuations
+
+  gStyle->SetOptStat(kFALSE);
+
+  TChain mc("Events");
+  TChain data("Events");
+
+  // Input files: MC and data files containing calibrated pedestal data, in the form 
+  // of MCerPhotEvt containers (as produced by mccalibrate.C)
+
+  mc.Add("/data1/MAGIC/Period016/mcdata/noise/root/electronic_noise.root");
+  data.Add("/data1/MAGIC/Period014/rootdata/2004_03_03/calibrated_20122.root");
+
+  // Warning! Binnings have to be set somehow manually to get 
+  // nice display... (due to rounding problems...)
+
+  TH1F* hinnermc = new TH1F("hinnermc","Noise inner",1001, -200.5, 200.5);
+  TH1F* hinnerdata = new TH1F("hinnerdata","Noise inner",500, -200.5, 200.5);
+
+  TH1F* houtermc = new TH1F("houtermc","Noise outer",601, -300.5, 300.5);
+  TH1F* houterdata = new TH1F("houterdata","Noise outer",100, -300.5, 300.5);
+
+  hinnermc->Sumw2();
+  hinnerdata->Sumw2();
+  houtermc->Sumw2();
+  houterdata->Sumw2();
+
+  // The normalizations of y axis (multiplicative factors in 3rd argument of Project) 
+  // are for now introduced manually:
+
+  mc.Project("hinnermc", "MCerPhotEvt.fPixels.fPhot", "0.77*(MCerPhotEvt.fPixels.fPixId<397 && MCerPhotEvt.fPixels.fPixId>0 )");
+
+  data.Project("hinnerdata", "MCerPhotEvt.fPixels.fPhot", "(MCerPhotEvt.fPixels.fPixId<397 && MCerPhotEvt.fPixels.fPixId>0 )");
+
+
+  // Same for outer pixels:
+  //  mc.Project("houtermc", "MCerPhotEvt.fPixels.fPhot", "1.26*(MCerPhotEvt.fPixels.fPixId>=397)");
+  //    data.Project("houterdata", "MCerPhotEvt.fPixels.fPhot", "(MCerPhotEvt.fPixels.fPixId>=397)");
+
+  hinnerdata->DrawCopy("e");
+  hinnermc->SetLineColor(2);
+  hinnermc->SetMarkerColor(2);
+  hinnermc->DrawCopy("e,same");
+
+  //     houterdata->DrawCopy("e");
+  //     houtermc->SetLineColor(2);
+  //     houtermc->SetMarkerColor(2);
+  //     houtermc->DrawCopy("e,same");
+
+
+  return;
+}
Index: /tags/Mars-V0.9/mtemp/mpadova/macros/resize.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpadova/macros/resize.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpadova/macros/resize.C	(revision 9772)
@@ -0,0 +1,106 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+void resize()
+{
+  MParList plist;
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  MReadMarsFile  read("Events", "star_gamma_train.root");
+
+  read.DisableAutoScheme();
+  tlist.AddToList(&read);
+
+  MWriteRootFile write("star_gamma_train_new.root", "recreate");
+
+  write.AddContainer("MRawEvtHeader",  "Events");
+  write.AddContainer("MMcEvt",         "Events");
+  write.AddContainer("MHillas",        "Events");
+  write.AddContainer("MHillasExt",     "Events");
+  write.AddContainer("MImagePar",      "Events");
+  write.AddContainer("MNewImagePar",   "Events");
+  write.AddContainer("MHillasSrc",     "Events");
+  write.AddContainer("MSrcPosCam",     "Events", kFALSE);
+  write.AddContainer("MConcentration", "Events", kFALSE);
+  write.AddContainer("MPointingPos",   "Events", kFALSE);
+
+
+  write.AddContainer("MGeomCam",            "RunHeaders");
+  write.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+  write.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+  write.AddContainer("MMcFadcHeader",       "RunHeaders");
+  write.AddContainer("MMcTrigHeader",       "RunHeaders");
+
+  write.AddContainer("MRawRunHeader",       "RunHeaders");
+  write.AddContainer("MMcRunHeader",        "RunHeaders");
+
+  //
+  // Histogram: event acceptance probability vs log10(Size). Binning
+  // and range are completely free. Beyond the histogram limits all 
+  // events are accepted
+  //
+
+  Float_t frac[20] = {0.180451,  0.236564,  0.253332,  0.282566,  0.355083,  
+ 		      0.424058,  0.566892,  0.657478,  0.753713,  0.738402,  
+ 		      0.789239,  0.762777,  0.857609,  0.833747,  0.923706,  
+ 		      1.04348,   0.978622,  0.875537,  0.971831,  1.};
+
+
+  // For MC calibrated in photons:
+  //  TH1F hist("probability", "", 20, 2., 4.);
+
+  // For MC calibrated in phe-:
+  TH1F hist("probability", "", 20, 1.2552725, 3.2552725);
+
+  hist.SetXTitle("log10(MHillas.fSize)");
+  for (Int_t i = 0; i < 20; i++)
+    hist.SetBinContent(i+1, frac[i]);
+
+  MH3 mh(hist);
+  MFEventSelector2 fsize(mh);
+  fsize.SetHistIsProbability(kTRUE);
+
+  write.SetFilter(&fsize);
+
+  tlist.AddToList(&fsize);
+  tlist.AddToList(&write);
+
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+
+  MProgressBar *bar = new MProgressBar;
+  evtloop.SetProgressBar(bar);
+
+  //
+  // Execute your analysis
+  //
+  if (!evtloop.Eventloop())
+    return;
+
+  tlist.PrintStatistics();
+
+  bar->DestroyWindow();
+
+  return;
+}
Index: /tags/Mars-V0.9/mtemp/mpadova/macros/trainsubsample.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpadova/macros/trainsubsample.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpadova/macros/trainsubsample.C	(revision 9772)
@@ -0,0 +1,104 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Abelardo Moralejo 1/2005 <mailto:moralejo@pd.infn.it>!
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+! 
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////////////////
+//
+// Macro trainsubsample.C
+//
+// Reads a star file from real data, and makes a subsample of it, adding a "fake" 
+// MMcEvt container with MMcEvt.fPartId=14. This intended to produce, from real data,
+// a "hadron training file" to be used in random forest (or other) g/h separation. The 
+// MMcEvt container is added so that whatever the method will consider these (real) 
+// showers to be all protons (before cuts, most will be, even in the case of strong 
+// source as Crab).
+//
+/////////////////////////////////////////////////////////////////////////////////////
+
+void trainsubsample()
+{
+  MParList plist;
+  MTaskList tlist;
+
+  plist.AddToList(&tlist);
+
+  MReadMarsFile  read("Events", "star_20040918_CrabNebulaW2.root");
+
+  MFEventSelector evsel;
+
+  Float_t nevents = 50000;   // Number of events to select. 
+  Float_t ratio = nevents / (Float_t) read.GetEntries();
+
+  evsel.SetSelectionRatio(ratio); // Fraction of events in output
+
+  read.DisableAutoScheme();
+  tlist.AddToList(&read);
+
+  MMcEvt* mcevt = new MMcEvt;
+  mcevt->SetPartId(14);
+  plist.AddToList(mcevt);
+
+  MWriteRootFile write("star_train_20040918_CrabNebulaW2.root", "recreate");
+
+  write.AddContainer("MMcEvt",         "Events", kFALSE);
+  write.AddContainer("MHillas",        "Events");
+  write.AddContainer("MHillasExt",     "Events");
+  write.AddContainer("MImagePar",      "Events");
+  write.AddContainer("MNewImagePar",   "Events");
+  write.AddContainer("MHillasSrc",     "Events");
+  write.AddContainer("MSrcPosCam",     "Events");
+  write.AddContainer("MConcentration", "Events", kFALSE);
+  write.AddContainer("MPointingPos",   "Events", kFALSE);
+
+
+  write.AddContainer("MGeomCam",            "RunHeaders", kFALSE);
+  write.AddContainer("MMcConfigRunHeader",  "RunHeaders", kFALSE);
+  write.AddContainer("MMcCorsikaRunHeader", "RunHeaders", kFALSE);
+  write.AddContainer("MMcFadcHeader",       "RunHeaders", kFALSE);
+  write.AddContainer("MMcTrigHeader",       "RunHeaders", kFALSE);
+
+  write.AddContainer("MRawRunHeader",       "RunHeaders");
+  write.AddContainer("MMcRunHeader",        "RunHeaders", kFALSE);
+
+  write.SetFilter(&evsel);
+
+  tlist.AddToList(&evsel);
+  tlist.AddToList(&write);
+
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+
+  MProgressBar *bar = new MProgressBar;
+  evtloop.SetProgressBar(bar);
+
+  //
+  // Execute your analysis
+  //
+  if (!evtloop.Eventloop())
+    return;
+
+  tlist.PrintStatistics();
+
+  bar->DestroyWindow();
+
+  return;
+}
Index: /tags/Mars-V0.9/mtemp/mpadova/macros/wobblemap.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpadova/macros/wobblemap.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpadova/macros/wobblemap.C	(revision 9772)
@@ -0,0 +1,982 @@
+void wobblemap(Float_t maxhadronness = 0.15, Float_t minsize=2000., Float_t maxsize = 1.e10)
+{
+
+  //// CHANGE NAME OF FILE TO NOT OVERWRITE FORMER FILES!!! ////////
+  TString outname = "Hists_";
+  if (maxsize > 1.e6)
+      outname += "above";
+
+  outname += Form("%4d", (Int_t)minsize);
+
+  if (maxsize < 1.e6)
+    {
+      outname += "to";
+      outname += Form("%4d", (Int_t)maxsize);
+    }
+
+  outname += "_had";
+
+  TString dummy = Form("%3.2f", (Double_t)maxhadronness); // cast is necessary!!
+  outname += dummy;
+  outname += ".root";
+
+  cout << outname << endl;
+
+  TFile* hfile = new TFile(outname,"recreate");
+
+  MGeomCamMagic mgeom;
+  Double_t mm2deg = mgeom.GetConvMm2Deg();
+
+  Double_t CrabDec = 22.014444444; // deg
+  Double_t CrabRA  = 5.5755555555; // hours
+
+//   Double_t CrabDec = 19.8197221; // deg
+//   Double_t CrabRA  = 8.895194; // hours  // FALSE source for the 3EG0853 data!
+
+  Float_t onregion_radius = 0.25; // degree
+  Float_t onr2 = onregion_radius * onregion_radius; // deg2
+  Float_t datatime = 0.;
+
+  // CHANGE MC PARAMETERS AND FILE BELOW ACCORDING TO STUDIED DATA SETS!!!!
+  // Period 025:
+//    TString spotsize = "2.0cm";
+//    Float_t minMCtheta = 5.73;   // lower edge of zbin 1
+//    Float_t maxMCtheta = 23.79;  // upper edge of zbin 8
+//    Float_t n_gamma_produced = 1.e5 * 8. * 6. / 2.; 
+  // #Events per file * #zbins * #files per zbin / 2 (test sample only)
+
+  // YOU ALSO HAVE TO CHANGE THE SCALING OF W, L AND THE EXPRESSION FOR DISP!
+
+  // Period 021
+  TString spotsize = "1.4cm";
+  Float_t minMCtheta = 15.20;   // lower edge of zbin 4
+  Float_t maxMCtheta = 28.96;   // upper edge of zbin 12
+  Float_t n_gamma_produced = 1.e5 * 9. * 6. / 2.; 
+  // #Events per file * #zbins * #files per zbin / 2 (test sample only)
+
+
+
+  TChain *MCchain = new TChain("Events");
+  //  MCchain->Add("/data2/magic/data/rootdata/Crab/Period025/2005_01_10/RandomForest_1.0_spot/star_S1000_mcgammas.root");
+
+  if (spotsize == "1.4cm")
+    MCchain->Add("/data2/magic/data/rootdata/Crab/Period021/2004_09_15/RandomForest_1.4_spot/star_S1000_mcgammas.root");
+  else if (spotsize == "2.0cm")
+    MCchain->Add("/data2/magic/data/rootdata/Crab/Period025/2005_01_10/RandomForest_2.0_spot/star_S1000_mcgammas.root");
+
+  //////////////////////////////////////////////////////////////////////////////////////////////////
+
+  TChain *Wchain = new TChain("Events");
+
+  Wchain->Add("/data2/magic/data/rootdata/Crab/Period021/2004_09_15/RandomForest_1.4_spot/star_S1000_20040915_CrabNebulaW1.root");
+  datatime += 1062.3;
+
+  Wchain->Add("/data2/magic/data/rootdata/Crab/Period021/2004_09_24/RandomForest_1.4_spot/star_S1000_20040924_CrabNebulaW1.root");
+  datatime += 1316.2;
+
+  Wchain->Add("/data2/magic/data/rootdata/Crab/Period021/2004_09_15/RandomForest_1.4_spot/star_S1000_20040915_CrabNebulaW2.root");
+  datatime += 1241.1;
+
+  Wchain->Add("/data2/magic/data/rootdata/Crab/Period021/2004_09_18/RandomForest_1.4_spot/star_S1000_20040918_CrabNebulaW2.root");
+  datatime += 1388.1;
+
+  Wchain->Add("/data2/magic/data/rootdata/Crab/Period021/2004_09_24/RandomForest_1.4_spot/star_S1000_20040924_CrabNebulaW2.root");
+  datatime += 767.0;
+
+
+//   Wchain->Add("/data2/magic/data/rootdata/Crab/Period025/2005_01_10/RandomForest_2.0_spot/star_S1000_20050110_CrabNebulaW1.root");
+//   datatime += 9469.7;
+  
+//   Wchain->Add("/data2/magic/data/rootdata/Crab/Period025/2005_01_11/RandomForest_2.0_spot/star_S1000_20050111_CrabNebulaW1.root");
+//   datatime += 4400.1;
+
+//   Wchain->Add("/data2/magic/data/rootdata/Crab/Period025/2005_01_11/RandomForest_2.0_spot/star_S1000_20050111_CrabNebulaW2.root");
+//   datatime += 4673.1;
+
+
+  // November data: WE SKIP THEM, they are very few!
+  //   Wchain->Add("/data2/magic/data/rootdata/Crab/Period023/2004_11_23/RandomForest_1.0_spot/star_S1000_20041123_CrabNebulaW1.root");
+  //   datatime += 394.2;
+  //   Wchain->Add("/data2/magic/data/rootdata/Crab/Period023/2004_11_23/RandomForest_1.0_spot/star_S1000_20041123_CrabNebulaW2.root");
+  //   datatime += 0.0;  // No data with theta below 28.96 deg!
+
+   
+//   Wchain->Add("/data2/magic/data/rootdata/3EG0853/Period024/2004_12_10/RandomForest_2.0_spot/star_S1000_20041210_3EG0853.root");
+//   datatime += 4487.9;
+
+
+ 
+  TH2F *CamMap = new TH2F("CamMap", "Events incoming direction map ",
+			    50, -2.5, 2.5,50, -2.5, 2.5);
+
+
+  TH2F *SkyMap = new TH2F("SkyMap", "Events incoming direction map ",
+			  70, CrabRA-0.175, CrabRA+0.175, 
+			  70, CrabDec-2.8315, CrabDec+2.8315);
+
+  TH2F *ONandOFF = new TH2F("ONandOFF", "ON and OFF regions",
+			    140, CrabRA-0.175, CrabRA+0.175, 
+			    140, CrabDec-2.8315, CrabDec+2.8315);
+
+  ////////////// BACKGROUND MODEL: //////////////////////////////////////////////////
+
+  // Radial distribution, dN/dr with trespect to camera center:
+  // SIZE > 2000
+  TF1* myfunc = new TF1("myfunc","x*([0]+[1]*log(x)+[2]*log(x)*log(x))", 0., 2.);
+  myfunc->SetParameters(2.06765e+02, -2.36253e+02, -2.13230e+01);
+
+  // SIZE 1000-2000
+  // TF1* myfunc = new TF1("myfunc","x*([0]+[1]*log(x)+[2]*log(x)*log(x)+[3]*log(x)**4)", 0., 2.);
+  // myfunc->SetParameters(6.45011e+02, -1.01606e+03, 1.63394e+02, -3.60749e+01);
+
+  TH1F *rndmrad = new TH1F("rndmrad","",200, 0., 2.);
+  rndmrad->FillRandom("myfunc",1e6);
+  rndmrad->Draw("e");
+
+  TH2F *BgMap = (TH2F*) SkyMap->Clone("BgMap");
+  TRandom dice;
+
+  ///////////////////////////////////////////////////////////////////////////////////
+
+
+  TH1F *Alpha = new TH1F("Alpha", "", 60, -90., 90.);
+  TH1F *AbsAlpha = new TH1F("AbsAlpha", "", 45, 0., 90.);
+
+  TH1F *WidthOn = new TH1F("WidthOn", "WIDTH", 120, 0., 0.60);
+  TH1F *WidthOff  = (TH1F*) WidthOn->Clone("WidthOff");
+  WidthOn->Sumw2();
+  WidthOff->Sumw2();
+
+  TH1F *LengthOn = new TH1F("LengthOn", "LENGTH", 50, 0., 1.);
+  TH1F *LengthOff  = (TH1F*) LengthOn->Clone("LengthOff");
+  LengthOn->Sumw2();
+  LengthOff->Sumw2();
+
+  TH1F *SWidthOn = new TH1F("SWidthOn", "SWIDTH", 75, 0.3, 5.3);
+  TH1F *SWidthOff  = (TH1F*) SWidthOn->Clone("SWidthOff");
+  SWidthOn->Sumw2();
+  SWidthOff->Sumw2();
+
+  TH1F *SLengthOn = new TH1F("SLengthOn", "SLENGTH", 45, 0.2, 3.2);
+  TH1F *SLengthOff  = (TH1F*) SLengthOn->Clone("SLengthOff");
+  SLengthOn->Sumw2();
+  SLengthOff->Sumw2();
+
+  TH1F *ConcOn = new TH1F("ConcOn", "CONC", 30, 0., 0.6);
+  TH1F *ConcOff  = (TH1F*) ConcOn->Clone("ConcOff");
+  ConcOn->Sumw2();
+  ConcOff->Sumw2();
+
+  TH1F *M3LongOn = new TH1F("M3LongOn", "M3LONG", 80, -0.8, 0.8);
+  TH1F *M3LongOff  = (TH1F*) M3LongOn->Clone("M3LongOff");
+  M3LongOn->Sumw2();
+  M3LongOff->Sumw2();
+
+  TH1F *DistOn = new TH1F("DistOn", "DIST", 40, 0., 2.);
+  TH1F *DistOff  = (TH1F*) DistOn->Clone("DistOff");
+  DistOn->Sumw2();
+  DistOff->Sumw2();
+
+  TH1F *SizeOn = new TH1F("SizeOn", "LOG10SIZE", 60, 2.5, 5.5);
+  TH1F *SizeOff  = (TH1F*) SizeOn->Clone("SizeOff");
+  SizeOn->Sumw2();
+  SizeOff->Sumw2();
+
+
+  TH1F *HadronnessOn = new TH1F("HadronnessOn", "Hadronness", 101, 0., 1.01);
+  TH1F *HadronnessOff = (TH1F*) HadronnessOn->Clone("HadronnessOff");
+  HadronnessOn->Sumw2();
+  HadronnessOff->Sumw2();
+
+  TH1F* r_source = new TH1F("r_source", "r_source", 50, 0., 2.5);
+
+
+  // Now the MC histograms:
+
+  TH1F *AlphaMC = (TH1F*) Alpha->Clone("AlphaMC");
+  TH1F *AbsAlphaMC = (TH1F*) AbsAlpha->Clone("AbsAlphaMC");
+  TH1F *WidthMC = (TH1F*) WidthOn->Clone("WidthMC");
+  TH1F *LengthMC  = (TH1F*) LengthOn->Clone("LengthMC");
+  TH1F *SWidthMC  = (TH1F*) SWidthOn->Clone("SWidthMC");
+  TH1F *SLengthMC  = (TH1F*) SLengthOn->Clone("SLengthMC");
+  
+  TH1F *ConcMC  = (TH1F*) ConcOn->Clone("ConcMC");
+  TH1F *M3LongMC = (TH1F*) M3LongOn->Clone("M3LongMC");
+  TH1F *M3LongMC_all = (TH1F*) M3LongOn->Clone("M3LongMC_all");
+  TH1F *DistMC  = (TH1F*) DistOn->Clone("DistMC");
+  TH1F *SizeMC  = (TH1F*) SizeOn->Clone("SizeMC");
+
+
+  TH1F *HadronnessMC = (TH1F*) HadronnessOn->Clone("HadronnessMC");
+
+  TH1F *EnergyMC = new TH1F("EnergyMC", "MC, log_{10}E_{\gamma} (GeV)", 1000, 0., 2000.);
+  EnergyMC->Sumw2();
+
+  ////////////////////////////////////////////////////////////////
+
+  MObservatory mobserv;
+  MStarCamTrans* starcamtrans = new MStarCamTrans(mgeom, mobserv);
+
+
+  MHillas *mhil = new MHillas();
+  MHillasSrc *msrc = new MHillasSrc();
+  MHillasExt *mhilext = new MHillasExt();
+  MNewImagePar *mnew = new MNewImagePar();
+  MPointingPos *mpoint = new MPointingPos();
+  MHadronness  *mhad = new MHadronness();
+  MPointingPos *mpoint = new MPointingPos();
+  MTime        *mtime  = new MTime();
+
+  Wchain->SetBranchStatus("*", 0);
+  Wchain->SetBranchStatus("MHillas.fSize", 1);
+  Wchain->SetBranchStatus("MHillas.fWidth", 1);
+  Wchain->SetBranchStatus("MHillas.fLength", 1);
+  Wchain->SetBranchStatus("MHillas.fMeanX", 1);
+  Wchain->SetBranchStatus("MHillas.fMeanY", 1);
+  Wchain->SetBranchStatus("MHillas.fCosDelta", 1);
+  Wchain->SetBranchStatus("MHillas.fSinDelta", 1);
+  Wchain->SetBranchStatus("MHillasSrc.fCosDeltaAlpha", 1);
+  Wchain->SetBranchStatus("MHillasExt.fM3Long", 1);
+  Wchain->SetBranchStatus("MNewImagePar.fNumCorePixels", 1);
+  Wchain->SetBranchStatus("MNewImagePar.fConc", 1);
+  Wchain->SetBranchStatus("MPointingPos.fZd",1);
+  Wchain->SetBranchStatus("MHadronness.fHadronness",1);
+  Wchain->SetBranchStatus("MPointingPos.fDec",1);
+  Wchain->SetBranchStatus("MPointingPos.fRa",1);
+  Wchain->SetBranchStatus("MTime.*",1);
+  Wchain->SetBranchStatus("MHillasSrc.fDist",1);
+
+  Wchain->SetBranchAddress("MHillas.",      &mhil);
+  Wchain->SetBranchAddress("MHillasSrc.",   &msrc);
+  Wchain->SetBranchAddress("MHillasExt.",   &mhilext);
+  Wchain->SetBranchAddress("MNewImagePar.", &mnew);
+  Wchain->SetBranchAddress("MPointingPos.", &mpoint);
+  Wchain->SetBranchAddress("MHadronness.",  &mhad);
+  Wchain->SetBranchAddress("MTime.",        &mtime);
+
+
+  for (Int_t i = 0; i < Wchain->GetEntries(); i++) // event count starts in 0
+    {
+      if ((i+1)%10000 == 0)
+	cout << i+1 << " of " << Wchain->GetEntries() << endl;
+
+      Wchain->GetEvent(i);
+
+      Float_t size = mhil->GetSize();
+
+      if (size < minsize)
+	continue;
+      else if (size > maxsize)
+	continue;
+
+      Float_t log10size = log10(size);
+
+      Float_t ZA = mpoint.GetZd();
+      // Exclude events with no drive info. For Crab ZAmin = 6.8
+      if (ZA < minMCtheta)
+	continue;
+      else if (ZA > maxMCtheta)
+	continue;   // MC up to ~29 deg loaded, but data may have lower upper end!
+
+
+      Float_t width  = mhil->GetWidth()* mm2deg;;
+      Float_t length = mhil->GetLength()* mm2deg;;
+
+
+      Float_t disp;
+
+      // spot 1 cm:
+      //      Float_t disp   = (1.-(width/length))*(2.68576-0.830937*log10size+0.1227*log10size*log10size);
+
+
+      if (spotsize == "1.4cm")
+	disp   = (1.-(width/length))*(3.64292-1.28713*log10size+0.179722*log10size*log10size);
+
+      else if (spotsize == "2.0cm")
+	disp   = (1.-(width/length))*(4.11949-1.39848*log10size+0.183514*log10size*log10size);
+
+
+      Float_t xmean = mhil->GetMeanX()* mm2deg;;
+      Float_t ymean = mhil->GetMeanY()* mm2deg;;
+
+      Float_t cosdelta = mhil->GetCosDelta();
+      Float_t sindelta = mhil->GetSinDelta();
+
+      Float_t asylon = mhilext->GetM3Long();
+
+
+      Double_t sourcex, sourcey;
+
+      // Choose right orientation:
+
+      if (asylon < 0.)
+      	{
+	  sourcex = xmean+cosdelta*disp;
+	  sourcey = ymean+sindelta*disp;
+ 	}
+       else
+ 	{
+ 	  sourcex = xmean-cosdelta*disp;
+ 	  sourcey = ymean-sindelta*disp;
+ 	}
+
+      Double_t SourceDec = 0;
+      Double_t SourceRA  = 0.;
+      Double_t SourceHA  = 0.;
+
+      Double_t CenterDec = mpoint->GetDec();
+      Double_t CenterRA  = mpoint->GetRa();
+
+      Double_t gmst = mtime->GetGmst(); // Greenwich mean sidereal time [rad]
+
+      gmst *= 24. / (2.*TMath::Pi()); // Conversion to hours
+
+      Double_t Wlongitude = -1. * mobserv.GetLongitudeDeg()/15.; // h
+      // Warning: GetLongitude return is positive if location is E of Greenwich!!
+      Double_t lst =  gmst - Wlongitude; // Local sidereal time [h]
+
+      Double_t CenterHA = lst - CenterRA;
+
+      if (CenterHA < 0.)
+	CenterHA += 24.;
+      else if (CenterHA > 24.)
+	CenterHA -= 24.;
+      // Hour angle of center of camera [h]
+
+
+      // Find Sky coordinates of reconstructed direction:
+
+      starcamtrans->Cel0CamToCel(CenterDec, CenterHA, sourcex/mm2deg, 
+				 sourcey/mm2deg, SourceDec, SourceHA);
+      SourceRA = lst - SourceHA; // Estimated source RA [h]
+      if (SourceRA < 0.)
+	SourceRA += 24.;
+      else if (SourceRA > 24.)
+	SourceRA -= 24.;
+
+
+      // Generate background
+
+      Float_t r = rndmrad->GetRandom();
+      Float_t phi = 2.*TMath::Pi()*dice.Rndm();
+      Float_t xbg = r * cos(phi);
+      Float_t ybg = r * sin(phi);
+      Double_t BGDec = 0.;
+      Double_t BGHA = 0.;
+      Double_t BGRA = 0.;
+      // Sky coordinates:
+      starcamtrans->Cel0CamToCel(CenterDec, CenterHA, xbg/mm2deg, ybg/mm2deg, BGDec, BGHA);
+      BGRA = lst - BGHA; // Estimated source RA [h]
+      if (BGRA < 0.)
+	BGRA += 24.;
+      else if (BGRA > 24.)
+	BGRA -= 24.;
+
+
+      // Now calculate Alpha with respect to true Crab position
+
+      Double_t CrabHA = lst - CrabRA;
+      if (CrabHA > 24.)
+	CrabHA -= 24.;
+      else if (CrabHA < 0.)
+	CrabHA += 24.;
+      
+      Double_t xcrab, ycrab; // mm
+
+      starcamtrans->Cel0CelToCam(CenterDec, CenterHA, CrabDec, CrabHA, 
+				 xcrab, ycrab);
+
+      xcrab *= mm2deg;
+      ycrab *= mm2deg; // Convert to deg
+
+      // Calculate Alpha relative to Crab:
+
+      Float_t scalar = ((xmean-xcrab)*cosdelta + (ymean-ycrab)*sindelta) /
+	sqrt( pow(xmean-xcrab, 2.) + pow(ymean-ycrab, 2.) );
+
+      Float_t alpha = 180./TMath::Pi()*acos(scalar);
+
+      if (alpha > 90.)
+	alpha -= 180.;
+
+
+      // Hadronness cut
+
+      Float_t hadronness = mhad->GetHadronness();
+      if (hadronness > maxhadronness)
+	continue;
+
+      // WARNING!: If scaling is changed, do it also in the MC part !!
+
+//       Float_t swidth  = width/(-0.028235+(0.03231*log10size));
+//       Float_t slength = length/(-0.13527+(0.09876*log10size));
+
+// Spot 1 cm:
+//      Float_t swidth  = width/(-0.0332763+(0.0320227*log10size));
+//      Float_t slength = length/(-0.174697+(0.107548*log10size));
+
+      Float_t swidth, slength;
+
+      if (spotsize == "1.4cm")
+	{
+	  swidth  = width/(-0.0308984+(0.0327119*log10size));
+	  slength = length/(-0.181605+(0.109609*log10size));
+	}
+      else if (spotsize == "2.0cm")
+	{
+	  Float_t swidth  = width/(-0.0279008+(0.0344538*log10size));
+	  Float_t slength = length/(-0.186394+(0.111055*log10size));
+	}
+
+      Float_t conc = mnew->GetConc();
+      Float_t dist = msrc->GetDist()*mm2deg;
+
+
+      Float_t crab_from_center = sqrt(xcrab*xcrab+ycrab*ycrab);
+      Float_t source_from_center = sqrt(sourcex*sourcex+sourcey*sourcey);
+      // Skip events reconstructed further than 2 deg from center:
+
+      if (source_from_center > 2.)
+	continue;
+
+      // Fill histograms
+
+      CamMap->Fill(sourcex, sourcey);
+      SkyMap->Fill(SourceRA, SourceDec);
+
+      BgMap->Fill(BGRA, BGDec);
+
+
+      // Fill histogram of distance from reconstructed source position to camera
+      // center, but exclude the quadrant where the candidate source is.... (dirty trick)
+
+      if ( (xcrab*sourcex+ycrab*sourcey)/
+	   source_from_center / crab_from_center < 0.707) // cos 45 deg
+	r_source->Fill(source_from_center);
+
+
+      // ON region
+      
+      Float_t ondist2 = (sourcex-xcrab)*(sourcex-xcrab) + 
+	(sourcey-ycrab)*(sourcey-ycrab);
+
+      Float_t offdist2_a = (sourcex+xcrab)*(sourcex+xcrab) + 
+	(sourcey+ycrab)*(sourcey+ycrab);
+      Float_t offdist2_b = (sourcex-ycrab)*(sourcex-ycrab) + 
+	(sourcey+xcrab)*(sourcey+xcrab);
+      Float_t offdist2_c = (sourcex+ycrab)*(sourcex+ycrab) + 
+	(sourcey-xcrab)*(sourcey-xcrab);
+
+
+      if (ondist2 < onr2)
+	{
+	  WidthOn->Fill(width);
+	  LengthOn->Fill(length);
+	  SWidthOn->Fill(swidth);
+	  SLengthOn->Fill(slength);
+	  ConcOn->Fill(conc);
+	  DistOn->Fill(dist);
+
+
+	  // 3rd moment with sign referred to source position:
+
+	  //      Float_t m3long = asylon * TMath::Sign(1., msrc->GetCosDeltaAlpha()) * mm2deg;
+	  Float_t m3long = asylon * TMath::Sign(1., xmean-xcrab) * mm2deg;
+
+	  M3LongOn->Fill(m3long);
+	  SizeOn->Fill(log10size);
+
+	  HadronnessOn->Fill(hadronness);
+	  ONandOFF->Fill(SourceRA, SourceDec);
+	}
+
+      if (offdist2_a < onr2 || offdist2_b < onr2 || offdist2_c < onr2)
+	{
+	  WidthOff->Fill(width, 1./3.);
+	  LengthOff->Fill(length, 1./3.);
+	  SWidthOff->Fill(swidth, 1./3.);
+	  SLengthOff->Fill(slength, 1./3.);
+	  ConcOff->Fill(conc, 1./3.);
+	  SizeOff->Fill(log10size, 1./3.);
+
+	  HadronnessOff->Fill(hadronness, 1./3.);
+	  ONandOFF->Fill(SourceRA, SourceDec);
+
+	  if (offdist2_a < onr2)
+	    {
+	      DistOff->Fill(sqrt((xmean+xcrab)*(xmean+xcrab)+(ymean+ycrab)*(ymean+ycrab)), 1./3.);
+
+	      m3long = asylon * TMath::Sign(1.,xmean+xcrab) * mm2deg;
+	      M3LongOff->Fill(m3long, 1./3.);
+	    }
+	  else if (offdist2_b < onr2)
+	    {
+	      DistOff->Fill(sqrt((xmean-ycrab)*(xmean-ycrab)+(ymean+xcrab)*(ymean+xcrab)), 1./3.);
+
+	      m3long = asylon * TMath::Sign(1.,xmean-ycrab) * mm2deg;
+	      M3LongOff->Fill(m3long, 1./3.);
+	    }
+
+	  else if (offdist2_c < onr2)
+	    {
+	      DistOff->Fill(sqrt((xmean+ycrab)*(xmean+ycrab)+(ymean-xcrab)*(ymean-xcrab)), 1./3.);
+
+	      m3long = asylon * TMath::Sign(1.,xmean+ycrab) * mm2deg;
+	      M3LongOff->Fill(m3long, 1./3.);
+	    }
+	}
+
+
+      // Very rough cut on 3rd moment related to Crab position:
+      // (only for alpha plot)
+
+      if ( (asylon < 0. && xcrab < xmean) ||
+	   (asylon > 0. && xcrab > xmean) )
+	continue;
+
+      Alpha->Fill(alpha);
+      AbsAlpha->Fill(abs(alpha));
+
+    }
+
+  // Convert y-axis units to Hz
+
+  WidthOn->Scale(1./datatime);
+  LengthOn->Scale(1./datatime);
+  SWidthOn->Scale(1./datatime);
+  ConcOn->Scale(1./datatime);
+  DistOn->Scale(1./datatime);
+  M3LongOn->Scale(1./datatime);
+  SizeOn->Scale(1./datatime);
+  SLengthOn->Scale(1./datatime);
+  HadronnessOn->Scale(1./datatime);
+
+  WidthOff->Scale(1./datatime);
+  LengthOff->Scale(1./datatime);
+  SWidthOff->Scale(1./datatime);
+  ConcOff->Scale(1./datatime);
+  DistOff->Scale(1./datatime);
+  M3LongOff->Scale(1./datatime);
+  SizeOff->Scale(1./datatime);
+  SLengthOff->Scale(1./datatime);
+  HadronnessOff->Scale(1./datatime);
+
+  TH1F* WidthDiff = (TH1F*) WidthOn->Clone("WidthDiff");
+  WidthDiff->Add(WidthOff, -1.);
+
+  TH1F* LengthDiff = (TH1F*) LengthOn->Clone("LengthDiff");
+  LengthDiff->Add(LengthOff, -1.);
+
+  TH1F* SWidthDiff = (TH1F*) SWidthOn->Clone("SWidthDiff");
+  SWidthDiff->Add(SWidthOff, -1.);
+
+  TH1F* SLengthDiff = (TH1F*) SLengthOn->Clone("SLengthDiff");
+  SLengthDiff->Add(SLengthOff, -1.);
+
+  TH1F* ConcDiff = (TH1F*) ConcOn->Clone("ConcDiff");
+  ConcDiff->Add(ConcOff, -1.);
+
+  TH1F* DistDiff = (TH1F*) DistOn->Clone("DistDiff");
+  DistDiff->Add(DistOff, -1.);
+
+  TH1F* M3LongDiff = (TH1F*) M3LongOn->Clone("M3LongDiff");
+  M3LongDiff->Add(M3LongOff, -1.);
+
+  TH1F* SizeDiff = (TH1F*) SizeOn->Clone("SizeDiff");
+  SizeDiff->Add(SizeOff, -1.);
+
+  TH1F* HadronnessDiff = (TH1F*) HadronnessOn->Clone("HadronnessDiff");
+  HadronnessDiff->Add(HadronnessOff, -1.);
+
+
+  TH2F* SkyMapRaw = SkyMap->Clone("SkyMapRaw");
+  TH2F* SkyMapSubtracted= SkyMap->Clone("SkyMapSubtracted");
+
+  SkyMapSubtracted->Add(BgMap, -1.*(SkyMap->Integral() - 
+				    datatime*WidthDiff->Integral()) /
+			BgMap->Integral());
+
+  SkyMap->Scale(1./datatime);
+  BgMap->Scale(1./datatime);
+
+  SkyMap->Add(BgMap, -1.*(SkyMap->Integral()-WidthDiff->Integral())/BgMap->Integral());
+
+
+  //  gStyle->SetPalette(8,0);   // Greyscale
+  gStyle->SetPalette(1,0);   // Pretty palette
+  //  gStyle->SetPalette(51,0);  // Deep sea palette
+
+  CamMap->SetStats(0);
+  SkyMapRaw->SetStats(0);
+  SkyMapSubtracted->SetStats(0);
+  SkyMap->SetStats(0);
+
+  //  CamMap->Draw("zcol");
+  //  SkyMap->Draw("zcol");
+
+  //  Alpha->Draw();
+  //  AbsAlpha->Draw();
+
+//   WidthOn->Draw("e");
+//   WidthOff->Draw("same");
+
+//   LengthOn->Draw("e");
+//   LengthOff->Draw("histo,same");
+
+
+  ///////////////////// MONTE CARLO /////////////////////////
+
+  Double_t xcrab = 120.; //mm
+  Double_t ycrab = 0.;
+
+  xcrab *= mm2deg;
+  ycrab *= mm2deg; // Convert to deg
+
+
+  mhil = new MHillas();
+  mhilsrc = new MHillasSrc();
+  mhilext = new MHillasExt();
+  mnew = new MNewImagePar();
+  mpoint = new MPointingPos();
+  mhad = new MHadronness();
+  MMcEvt* mcevt = new MMcEvt();
+
+  MCchain->SetBranchStatus("*", 0);
+  MCchain->SetBranchStatus("MHillas.fSize", 1);
+  MCchain->SetBranchStatus("MHillas.fWidth", 1);
+  MCchain->SetBranchStatus("MHillas.fLength", 1);
+  MCchain->SetBranchStatus("MHillas.fMeanX", 1);
+  MCchain->SetBranchStatus("MHillas.fMeanY", 1);
+  MCchain->SetBranchStatus("MHillas.fCosDelta", 1);
+  MCchain->SetBranchStatus("MHillas.fSinDelta", 1);
+  MCchain->SetBranchStatus("MHillasSrc.fCosDeltaAlpha", 1);
+  MCchain->SetBranchStatus("MHillasSrc.fDist", 1);
+  MCchain->SetBranchStatus("MHillasExt.fM3Long", 1);
+  MCchain->SetBranchStatus("MNewImagePar.fNumCorePixels", 1);
+  MCchain->SetBranchStatus("MNewImagePar.fConc", 1);
+  MCchain->SetBranchStatus("MHadronness.fHadronness",1);
+  MCchain->SetBranchStatus("MMcEvt.fTelescopeTheta",1);
+  MCchain->SetBranchStatus("MMcEvt.fEnergy",1);
+
+  MCchain->SetBranchAddress("MHillas.",      &mhil);
+  MCchain->SetBranchAddress("MHillasExt.",   &mhilext);
+  MCchain->SetBranchAddress("MNewImagePar.", &mnew);
+  MCchain->SetBranchAddress("MHadronness.",  &mhad);
+  MCchain->SetBranchAddress("MMcEvt.",       &mcevt);
+  MCchain->SetBranchAddress("MHillasSrc.",   &msrc);
+
+
+  // Original # gammas in the MC sample between 1 and 30 TeV (estimate!):
+  Float_t n_gamma_produced_1to30TeV =  
+    n_gamma_produced*(pow(1000.,-1.6) - pow(30000.,-1.6)) / 
+    (pow(10.,-1.6) - pow(30000.,-1.6));
+
+  // Correction due to the modification of the spectrum: -2.62 instead of -2.6
+  n_gamma_produced_1to30TeV *=  (pow(1000.,-1.62) - pow(30000.,-1.62)) /
+    (pow(1000.,-1.6) - pow(30000.,-1.6));
+
+  Float_t evts2rate =   1.74e-11 / n_gamma_produced_1to30TeV; // cm-2 s-1
+  evts2rate *=  TMath::Pi()*pow(300.e2, 2.); // * MC production  area in cm2 => s-1
+
+  cout << "Processing Monte Carlo gammas...." << endl;
+
+  Int_t MC_gammas_in_off = 0;
+  Int_t MC_gammas_in_on  = 0;
+
+  for (Int_t i = 0; i < MCchain->GetEntries(); i++) // event count starts in 0
+    {
+      if ((i+1)%10000 == 0)
+	cout << i+1 << " of " << MCchain->GetEntries() << endl;
+
+      MCchain->GetEvent(i);
+
+      Float_t size = mhil->GetSize();
+
+      if (size < minsize)
+	continue;
+      else if (size > maxsize)
+	continue;
+
+      Float_t log10size = log10(size);
+
+      Float_t ZA = mcevt->GetTelescopeTheta()*180./TMath::Pi();
+
+      // Exclude MC from zbin0. For Crab ZAmin = 6.8 deg. We do not make exactly that cut
+      // to simplify the flux calculation.
+
+      if (ZA < minMCtheta)  // Corresponds to the upper theta limit of zbin0
+	continue;
+      else if (ZA > maxMCtheta)
+	continue;
+
+      Float_t width  = mhil->GetWidth()* mm2deg;;
+      Float_t length = mhil->GetLength()* mm2deg;;
+
+      //      Float_t disp   = (1.-(width/length))*(0.9776+0.101062*log10(size));
+
+      // spot 1 cm:
+      //      Float_t disp   = (1.-(width/length))*(2.68576-0.830937*log10size+0.1227*log10size*log10size);
+
+      Float_t disp;
+
+      if (spotsize == "1.4cm")
+	disp   = (1.-(width/length))*(3.64292-1.28713*log10size+0.179722*log10size*log10size);
+      else if (spotsize == "2.0cm")
+	disp   = (1.-(width/length))*(4.11949-1.39848*log10size+0.183514*log10size*log10size);
+
+      Float_t xmean = mhil->GetMeanX()* mm2deg;;
+      Float_t ymean = mhil->GetMeanY()* mm2deg;;
+
+      Float_t cosdelta = mhil->GetCosDelta();
+      Float_t sindelta = mhil->GetSinDelta();
+
+      Float_t asylon = mhilext->GetM3Long();
+
+      Double_t sourcex, sourcey;
+
+      // Choose right orientation:
+
+      if (asylon < 0.)
+      	{
+	  sourcex = xmean+cosdelta*disp;
+	  sourcey = ymean+sindelta*disp;
+ 	}
+       else
+ 	{
+ 	  sourcex = xmean-cosdelta*disp;
+ 	  sourcey = ymean-sindelta*disp;
+ 	}
+
+
+      // Calculate Alpha relative to Crab:
+
+      Float_t scalar = ((xmean-xcrab)*cosdelta + (ymean-ycrab)*sindelta) /
+	sqrt( pow(xmean-xcrab, 2.) + pow(ymean-ycrab, 2.) );
+
+      Float_t alpha = 180./TMath::Pi()*acos(scalar);
+
+      if (alpha > 90.)
+	alpha -= 180.;
+
+
+      // Hadronness cut
+
+      Float_t hadronness = mhad->GetHadronness();
+      if (hadronness > maxhadronness)
+	continue;
+
+//       Float_t swidth  = width/(-0.028235+(0.03231*log10size));
+//       Float_t slength = length/(-0.13527+(0.09876*log10size));
+
+// Spot 1 cm:
+//      Float_t swidth  = width/(-0.0332763+(0.0320227*log10size));
+//      Float_t slength = length/(-0.174697+(0.107548*log10size));
+
+      Float_t swidth, slength;
+
+      if (spotsize == "1.4cm")
+	{
+	  swidth  = width/(-0.0308984+(0.0327119*log10size));
+	  slength = length/(-0.181605+(0.109609*log10size));
+	}
+      else if (spotsize == "2.0cm")
+	{
+	  swidth  = width/(-0.0279008+(0.0344538*log10size));
+	  slength = length/(-0.186394+(0.111055*log10size));
+	}
+
+      Float_t conc = mnew->GetConc();
+      Float_t dist = msrc->GetDist()*mm2deg;
+
+      // ON region
+      
+      Float_t ondist2 = (sourcex-xcrab)*(sourcex-xcrab) + 
+	(sourcey-ycrab)*(sourcey-ycrab);
+
+      Float_t offdist2_a = (sourcex+xcrab)*(sourcex+xcrab) + 
+	(sourcey+ycrab)*(sourcey+ycrab);
+      Float_t offdist2_b = (sourcex-ycrab)*(sourcex-ycrab) + 
+	(sourcey+xcrab)*(sourcey+xcrab);
+      Float_t offdist2_c = (sourcex+ycrab)*(sourcex+ycrab) + 
+	(sourcey-xcrab)*(sourcey-xcrab);
+
+
+      Float_t energy = mcevt->GetEnergy(); // GeV
+
+      // Calculate weight to account for true Crab spectrum:
+      // We take the (curved) shape of the spectrum BELOW 1 TeV from
+      // Astropart.Phys. 19 (2003) 339-350 (Fabrizio, Konopelko):
+      // dN/dE = C*(E/1TeV)^[-2.47-0.11*log(E/1TeV)]
+      // normalizing it above 1 TeV with the value from ApJ614
+
+      // Integrated Crab flux 1 - 30 TeV from Aharonian et al. 2004, ApJ 614: 
+      // 1.74e-11 cm-2 s-1 (shape: power law with index -2.62)
+
+      Float_t mcweight;
+      if (energy > 1000.)
+	mcweight = pow(energy/1000., 2.6-2.62); // correct spectrum
+      else
+	{
+	  mcweight = pow(energy/1000., (2.6-2.47-0.11*log(energy/1000.)));
+	}
+
+      mcweight *= evts2rate;  // weight to get results in Hz
+
+      // 3rd moment with sign referred to source position, convert to degree:
+
+      //      Float_t m3long = asylon * TMath::Sign(1., msrc->GetCosDeltaAlpha()) * mm2deg;
+
+      Float_t m3long = asylon * TMath::Sign(1., xmean-xcrab) * mm2deg;
+
+      M3LongMC_all->Fill(m3long, mcweight);
+
+      if (ondist2 < onr2)
+	{
+	  WidthMC->Fill(width, mcweight);
+	  LengthMC->Fill(length, mcweight);
+	  SWidthMC->Fill(swidth, mcweight);
+	  SLengthMC->Fill(slength, mcweight);
+
+	  ConcMC->Fill(conc, mcweight);
+	  DistMC->Fill(dist, mcweight);
+	  M3LongMC->Fill(m3long, mcweight);
+	  SizeMC->Fill(log10size, mcweight);
+
+	  HadronnessMC->Fill(hadronness, mcweight);
+	  EnergyMC->Fill(energy, mcweight);
+
+	  MC_gammas_in_on++;
+	}
+
+      if (offdist2_a < onr2 || offdist2_b < onr2 || offdist2_c < onr2)
+	MC_gammas_in_off++;
+
+      // Very rough cut on 3rd moment related to Crab position:
+      // (only for alpha plot)
+
+      if ( (asylon < 0. && xcrab < xmean) ||
+	   (asylon > 0. && xcrab > xmean) )
+	continue;
+
+      AlphaMC->Fill(alpha);
+      AbsAlphaMC->Fill(abs(alpha));
+
+    }
+
+  cout << "MC gammas in ON region: "  << MC_gammas_in_on << endl;
+  cout << "MC gammas in OFF region: " << MC_gammas_in_off << " / 3" << endl;
+
+  WidthMC->SetLineColor(4);
+  LengthMC->SetLineColor(4);
+  SWidthMC->SetLineColor(4);
+  SLengthMC->SetLineColor(4);
+  HadronnessMC->SetLineColor(4);
+  ConcMC->SetLineColor(4);
+  DistMC->SetLineColor(4);
+  M3LongMC->SetLineColor(4);
+  M3LongMC_all->SetLineColor(2);
+  SizeMC->SetLineColor(4);
+
+  /////////////////////////    DRAW    /////////////////////////////////
+
+
+  WidthDiff->Draw();
+  WidthMC->Draw("chisto,same");
+
+  cout << "Data rate: " << WidthDiff->Integral() << " Hz" << endl;
+  cout << "MC   rate: " << WidthMC->Integral() << " Hz" << endl;
+  cout << "MC   events: " << WidthMC->GetEntries() << endl;
+
+  hfile->Write();
+
+  return;
+}
+
+///////////////////////////////////////
+
+void Smooth(Char_t* filename="Hists_above2000_had0.15.root")
+{
+  TH2F* SkyMap = new TH2F();
+
+  TFile *f = new TFile(filename);
+  SkyMap->Read("SkyMapSubtracted");
+
+
+  Int_t binfactor = 5;
+  Int_t range = 11;     // odd number both!
+
+  Int_t nx = binfactor*SkyMap->GetNbinsX();
+  Int_t ny = binfactor*SkyMap->GetNbinsY();
+
+  TH2F* SkyMap2 = new TH2F("SkyMap2", "Events incoming direction map ",
+			    nx, 
+			    SkyMap->GetXaxis()->GetXmin(),
+			    SkyMap->GetXaxis()->GetXmax(),
+			    ny, 
+			    SkyMap->GetYaxis()->GetXmin(),
+			    SkyMap->GetYaxis()->GetXmax());
+
+
+  // Parameters from fit to real Crab data
+
+  TF2* angres = new TF2("g", 
+			"exp(-(x/0.01065)**2-(y/0.135684)**2)", 
+			-SkyMap->GetXaxis()->GetBinWidth(1)*range/2., 
+			SkyMap->GetXaxis()->GetBinWidth(1)*range/2.,
+			-SkyMap->GetYaxis()->GetBinWidth(1)*range/2., 
+			SkyMap->GetYaxis()->GetBinWidth(1)*range/2. );
+
+  Int_t nbinsx = (angres->GetXmax() - angres->GetXmin()) / 
+    (SkyMap2->GetXaxis()->GetBinWidth(1));
+
+  Int_t nbinsy = (angres->GetYmax() - angres->GetYmin()) / 
+    (SkyMap2->GetYaxis()->GetBinWidth(1));
+
+  angres->SetNpx(nbinsx);
+  angres->SetNpy(nbinsy);
+
+  angres->Draw("lego1");
+ 
+
+  TH2F* hist = (TH2F*)angres->GetHistogram()->Clone("hist");
+
+  Float_t norm = 1./hist->Integral();
+
+  hist->Scale(norm);
+
+  cout << hist->Integral() << endl;
+
+  Float_t maxx = SkyMap2->GetXaxis()->GetXmax();
+  Float_t minx = SkyMap2->GetXaxis()->GetXmin();
+  Float_t maxy = SkyMap2->GetYaxis()->GetXmax();
+  Float_t miny = SkyMap2->GetYaxis()->GetXmin();
+
+  for (Int_t ix = 1; ix <= SkyMap->GetNbinsX(); ix++)
+    {
+      for (Int_t iy = 1; iy <= SkyMap->GetNbinsY(); iy++)
+	{
+	  Float_t events = SkyMap->GetBinContent(ix, iy);
+
+	  for (Int_t ix2 = 1; ix2 <= nbinsx; ix2++)
+	    for (Int_t iy2 = 1; iy2 <= nbinsy; iy2++)
+	      {
+		Float_t events2 = events * hist->GetBinContent(ix2, iy2);
+
+		Float_t newx = SkyMap->GetXaxis()->GetBinCenter(ix)
+		  + hist->GetXaxis()->GetBinCenter(ix2);
+		Float_t newy = SkyMap->GetYaxis()->GetBinCenter(iy) 
+		  + hist->GetYaxis()->GetBinCenter(iy2);
+
+		SkyMap2->Fill(newx, newy, events2);
+	    }
+	}
+      if (ix%10 == 0)
+	cout << ix << endl;
+    }
+
+  gStyle->SetPalette(1,0);
+  SkyMap2->SetStats(0);
+  SkyMap2->Draw("zcol");
+
+  return;
+}
Index: /tags/Mars-V0.9/mtemp/mpisa/Changelog_pisa
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/Changelog_pisa	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/Changelog_pisa	(revision 9772)
@@ -0,0 +1,130 @@
+Please  do  not write behind the end of line tag so that it is  possible
+to   send  a   Changelog   file  to  a  line  printer  directly.  Thanks.
+
+For your entries please follow this style:
+
+_yyyy/mm/dd:_[Your Name]
+_
+___*_filename:
+_____-_description
+_
+___*_filename2, filename3:
+_____-_description
+_
+_
+_
+
+While an underscore is a placeholder for a white-space or an empty line.
+
+                                                 -*-*- END OF LINE -*-*-
+
+ 2004/09/23: Nicola Galante
+
+   * mpisa/classes/mispointing
+     - Aggiunte le seguenti classi:MFindStars.cc          MStarLocalCam.cc      MVPPlotter.cc
+                                   MFindStars.h           MStarLocalCam.h       MVPPlotter.h
+                                   MHTelAxisFromStars.cc  MStarLocalPos.cc      MVPTime.cc
+                                   MHTelAxisFromStars.h   MStarLocalPos.h       MVPTime.h
+                                   MSkyCamTrans.cc        MTelAxisFromStars.cc
+                                   MSkyCamTrans.h         MTelAxisFromStars.h 
+                                   MSourceDirections.cc   MVPObject.cc
+                                   MSourceDirections.h    MVPObject.h
+       Le seguenti modifiche sono state effettuate: 
+       1) the names 
+	of the branches inside classes MSourceDirections.cc and MFindStars.cc were 
+	defined without the final dot (i.e. "MMcConfigRunHeader" instead of 
+	"MMcConfigRunHeader.", for example), so that the Get...() methods returned 
+	null pointers.
+
+       2) First of all I realized that the Process of MTelAxisFromStars was skipped 
+	because no stars were found in the MStarCam *fStarCam container. After 
+	several attempts I found that the problem was solved by changing
+
+	tlist.AddToList(&findstars, "Currents");
+
+	with
+
+	tlist.AddToList(&findstars);
+
+	3) I inform you also that I use two MReadReport objects, one 
+	for the DC currents and one for the Drive reports file, and then 
+	add the two MReadReport objects to the tasklist, because I had some 
+	problems in making ROOT accepting to read different trees in different 
+	files added to the same object, as done in the original macro (this could 
+	be related to the problem I encoured in adding the MFindStar to the 
+	tasklist).
+
+
+     - aggiunta la macro macros/findTelAxisFromStars.C
+
+
+ 2004/09/13: Antonio Stamerra
+
+   * mpisa/macros/readIPR.C
+     - macro to read IPRs
+
+
+ 2004/05/24: Antonio Stamerra
+
+   * mpisa/classes/mtrigger/*, mpisa/classes/MTriggerReport.[h,cc]
+     - classes almost completed; compiles.  
+	
+
+ 2004/05/24: Antonio Stamerra
+
+   * mpisa/classes/MTriggerLiveTime.[h.cc]
+     - added new class container for the Live-Deadtime from report files (.rep)
+	
+   * mpisa/classes/mtrigger
+     - added new directory for the MTrigger* classes. These
+	classes have been moved there. 
+     - Various modifications have been made on these classes.
+	The MReportTrigger now fills these containers.
+
+ 2004/05/24: Antonio Stamerra
+
+   * mpisa/classes/MTriggerCell.[h.cc]
+     - added new class container for the cell rates from report files (.rep)
+
+   * mpisa/classes/MTriggerBit.[h.cc]
+     - added new class container for the L2 bits rates from report files (.rep)
+
+   * mpisa/classes/MTriggerPrescFact.[h.cc]
+     - added new class container for the prescaling factors from 
+	report files (.rep)
+
+   * mpisa/classes/MTriggerReport.[h.cc]
+     - added copy of the mreport/MReportTrigger class to modify to new
+	report file format and to use the trigger class containers
+
+
+ 2004/05/21: Antonio Stamerra
+
+   * mpisa/classes
+     - added directory /classes. Should be used to add new classes
+
+   * mpisa/Makefile, mpisa/PisaLinkDef.h, mpisa/PisaIncl.h
+     - added to compile internally to the mpisa directory the classes
+
+   * mpisa/classes/MTriggerIPR.[h,cc]
+     - added container for IPR values.
+   
+
+ 2004/05/12: Antonio Stamerra
+
+   * mpisa/macros
+     - added macros:
+	- first_ana.C   given a file with hillas analysis produces ON-OFF plots
+	- production.C  produces calibrated data (photons) from raw data
+	- HillasAnal.C  makes standard Hillas analysis
+
+   * mpisa/macros
+     - added this directory 	
+
+   * added this file Changelog_pisa
+     - test	
+
+ 2004/05/11: Antonio Stamerra
+
+   * mtemp/mpisa
+     - 	added directory mpisa in mtemp
Index: /tags/Mars-V0.9/mtemp/mpisa/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/Makefile	(revision 9772)
@@ -0,0 +1,53 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../../Makefile.conf.$(OSTYPE)
+include ../../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+CINT     = Pisa
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../../mbase \
+	   -I../../mjobs \
+	   -I../../mpedestal \
+	   -I../../mbadpixels \
+	   -I../../mfileio \
+           -I../../mraw \
+           -I../../manalysis \
+	   -I../../mgui \
+	   -I../../mgeom \
+	   -I../../msignal \
+	   -I../../mcalib \
+	   -I../../mfilter \
+	   -I../../mhbase \
+	   -I../../mimage \
+	   -I../../mpointing \
+	   -I../../mcamera \
+	   -I../../mhist \
+	   -I../../mmc \
+	   -I../../mreport \
+	   -I../../mastro
+
+SRCFILES = \
+        ./classes/MTriggerIPR.cc \
+        ./classes/MTriggerCell.cc \
+        ./classes/MTriggerBit.cc \
+        ./classes/MTriggerPrescFact.cc \
+        ./classes/MTriggerLiveTime.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mtemp/mpisa/PisaIncl.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/PisaIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/PisaIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtemp/mpisa/PisaLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/PisaLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/PisaLinkDef.h	(revision 9772)
@@ -0,0 +1,13 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MTriggerIPR+;
+#pragma link C++ class MTriggerCell+;
+#pragma link C++ class MTriggerBit+;
+#pragma link C++ class MTriggerPrescFact+;
+#pragma link C++ class MTriggerLiveTime+;
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MReportFileRead.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MReportFileRead.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MReportFileRead.h	(revision 9772)
@@ -0,0 +1,66 @@
+#ifndef MARS_MReportFileRead
+#define MARS_MReportFileRead
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+/*// gcc 3.2
+//class ifstream;
+#include <iosfwd>
+*/
+
+class THashTable;
+
+class MTime;
+class MReport;
+class MReportHelp;
+
+class MReportFileRead : public MTask
+{
+private:
+    TString     fFileName;  // Name of the input file
+
+    THashTable *fList;      // List of possible reports to be interpreted
+
+    MTime   fStart;         // Time range which should be read from file
+    MTime   fStop;          // Time range which should be read from file
+
+    ULong_t fNumLine;       // line counter
+
+    Int_t   fVersion;       // File format version
+
+    enum { kHasNoHeader = BIT(14) };
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    virtual Int_t CheckFileHeader() { return 0; }
+    MReport *GetReport(const TString &str) const;
+    MReport *GetReport(MReportHelp *help) const;
+    MReportHelp *GetReportHelp(const TString &str) const;
+
+protected:
+    ifstream   *fIn;         //! buffered input stream (file to read from)
+    void SetVersion(Int_t v) { fVersion = v; }
+
+public:
+    MReportFileRead(const char *filename, const char *name=NULL, const char *title=NULL);
+    ~MReportFileRead();
+
+    void SetHasNoHeader() { SetBit(kHasNoHeader); }
+    void SetTimeStart(const MTime &tm) { fStart = tm; }
+    void SetTimeStop(const MTime &tm)  { fStop = tm; }
+
+    Int_t GetVersion() {return fVersion; }
+
+    Bool_t AddToList(const char *name) const;
+
+    ClassDef(MReportFileRead, 0)// Task to read general report file
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MReportTrigger.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MReportTrigger.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MReportTrigger.cc	(revision 9772)
@@ -0,0 +1,504 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+! 
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportTrigger
+//
+// This is the class interpreting and storing the TRIGGER-REPORT information.
+//  Updated to add IPR; data format follows TDAS 00-07 ver.6.3 jul-04
+//  http://hegra1.mppmu.mpg.de/MAGIC/private/software/doc/control/tdas0007_v6.3.ps.gz
+//  
+//  *Input:
+//
+//  The report is divided into 8 sections: 
+//  - the cell rates                       (32 fields)
+//  - L1 and L2 table name                 ( 2 fields)
+//  - prescaling factors                  (2x8 fields)
+//  - livetime and deadtime               (5x4 fields)
+//  - L2 output bit rates                (20 integers)
+//  - global rates (before/after presc.)    (2 floats)
+//  - 18 dummy fields                      (18 fields)
+//  - IPR                    (325 hexs + 397 integers) 
+//
+//  *Output:
+//
+//  The values read from the report string are used to fill the following 
+//  containers:
+//  - MTriggerIPR        (Individual Pixel Rates)
+//  - MTriggerCell       (Rate of trigger cells)
+//  - MTriggerBit        (Output Bits from prescaler (before and after presc.)
+//  - MTriggerPrescFact  (Prescaling factors for each bit)
+//  - MTriggerLiveTime   (Values of counters for dead/livetime)
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportTrigger.h"
+
+#include "MParList.h"
+
+#include "MLogManip.h"
+
+#include "MTriggerIPR.h"
+#include "MTriggerCell.h"
+#include "MTriggerBit.h"
+#include "MTriggerPrescFact.h"
+#include "MTriggerLiveTime.h"
+
+#include "MReportFileRead.h"
+
+ClassImp(MReportTrigger);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "TRIGGER-REPORT"
+//
+MReportTrigger::MReportTrigger() : MReport("TRIGGER-REPORT")
+{
+    fName  = "MReportTrigger";
+    fTitle = "Class for TRIGGER-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// FindCreate the following objects:
+//  - MTriggerIPR
+//  - MTriggerCell
+//  - MTriggerBit
+//  - MTriggerPrescFact
+//  - MTriggerLiveTime
+//
+Bool_t MReportTrigger::SetupReading(MParList &plist)
+{
+  fIPR = (MTriggerIPR*)plist.FindCreateObj("MTriggerIPR");
+  if (!fIPR)
+    return kFALSE;
+
+  fCell = (MTriggerCell*)plist.FindCreateObj("MTriggerCell");
+  if (!fCell)
+    return kFALSE;
+
+  fBit = (MTriggerBit*)plist.FindCreateObj("MTriggerBit");
+  if (!fBit)
+    return kFALSE;
+
+  fPrescFactor = (MTriggerPrescFact*)plist.FindCreateObj("MTriggerPrescFact");
+  if (!fPrescFactor)
+    return kFALSE;
+
+  fLiveTime = (MTriggerLiveTime*)plist.FindCreateObj("MTriggerLiveTime");
+  if (!fLiveTime)
+    return kFALSE;
+
+  
+  return MReport::SetupReading(plist);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Cell rates section of the report
+//  Read 32 floats separated with a blank
+//
+Bool_t MReportTrigger::InterpreteCell(TString &str)
+{
+  Int_t len=0, n, i=0;
+  Int_t gsNCells=32;
+
+  for (i=0;i<gsNCells;i++)
+    {
+      n = sscanf(str.Data(), " %f %n", &fCell->fCellRate[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Cell Scaler Value #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove cell rates from report string
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Prescaling factors section of the report
+//
+Bool_t MReportTrigger::InterpretePrescFact(TString &str)
+{
+  Int_t len=0, n, i=0;
+  Int_t gsNPrescFacts=8;
+  
+  str.Remove(0, 1);
+
+  for (i=0;i<gsNPrescFacts;i++)
+    {
+    const Int_t ws = str.First(' ');
+    if (ws<=0)
+       {
+	 *fLog << warn << "WARNING - Cannot determine Prescaling factor #" << i << " descriptor" << endl;
+        return kCONTINUE;
+       }
+    TString descriptor = str(0, ws);
+    //*fLog  << descriptor <<endl;
+    str.Remove(0, ws);
+      
+      n = sscanf(str.Data(), " %li %n", &fPrescFactor->fPrescFact[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - prescaler factor " << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove Prescal. factors from report string
+      // *fLog << warn << fPrescFactor->fPrescFact[i]<<endl;
+    }
+  str=str.Strip(TString::kLeading);  
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Scaler with Live-Deadtime section of the report
+//  Read 4x5 integers separated with a blank
+//
+Bool_t MReportTrigger::InterpreteLiveTime(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNScalers=5;
+  Int_t  dLSB, dMSB,lLSB, lMSB;
+
+  for (i=0;i<gsNScalers;i++)
+    {
+      n = sscanf(str.Data(), " %d %d %d %d %n", &lLSB, &lMSB,&dLSB, &dMSB, &len);
+      if (n!=4)
+	{
+	  *fLog << warn << "WARNING - Live-Deadtime Scaler Value #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+
+      str.Remove(0, len); // Remove Live-Deadtimes from string
+
+      //convert to seconds and fill container
+      // (FIXME! only the MSB (seconds is now considered)
+      (fLiveTime->fLiveTime)[i] = lMSB;
+      (fLiveTime->fDeadTime)[i] = dMSB;      
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the Bit rates section of the report
+// 20 integers. First and last two are not used
+//
+Bool_t MReportTrigger::InterpreteBit(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNBits=20;
+  
+  for (i=0;i<gsNBits;i++)
+    {
+      n = sscanf(str.Data(), " %f %n", &fBit->fBit[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Bit rate #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove output bit rates from string
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the L1 and L2 table names
+// 1String + 1Int +1 String
+//
+Bool_t MReportTrigger::InterpreteL1L2Table(TString &str)
+{
+    const Int_t wsL1 = str.First(' ');
+ 
+    if (wsL1<=0)
+       {
+        *fLog << warn << "WARNING - Cannot determine name of L1 trigger table." << endl;
+        return kCONTINUE;
+       }
+    
+    TString L1tablename = str(0, wsL1);
+    str.Remove(0, wsL1);
+
+    // remove an integer between names
+    Int_t len;
+    Int_t mi;
+    Int_t n=sscanf(str.Data(), "%d %n", &mi, &len);
+    if (n!=1)
+      {
+        *fLog << warn << "WARNING - Not enough arguments." << endl;
+        return kCONTINUE;
+    }
+    str.Remove(0, len);
+
+    // L2 tablename
+    const Int_t wsL2 = str.First(' ');
+ 
+    if (wsL2<=0)
+      {
+        *fLog << warn << "WARNING - Cannot determine name of L2 trigger table." << endl;
+        return kCONTINUE;
+      }    
+    TString L2tablename = str(0, wsL2);
+    str.Remove(0,wsL2);
+    str.Strip(TString::kBoth);
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete an unused section of the report 
+// 18 integers
+//
+Bool_t MReportTrigger::InterpreteDummy(TString &str)
+{
+  Int_t len, n, i=0;
+  Int_t gsNDummies=18;
+  Int_t dummy;  
+
+  for (i=0;i<gsNDummies;i++)
+    {
+      n = sscanf(str.Data(), " %d %n", &dummy, &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - Dummy #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove dummies from report string
+
+    }
+
+  str=str.Strip(TString::kLeading);  
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the IPR section of the report
+//   sep-04
+//   The IPR are saved as 340 (=number of pixs in trigger area) hex numbers 
+//   and as 397 (= #pixs in inner region) dec numbers.
+//   Only the dec numbers are now saved in the MTriggerIPR container.
+//  
+
+Bool_t MReportTrigger::InterpreteIPR(TString &str)
+{
+
+  Int_t gsNhexIPR=340; //number of IPR saved in hex format
+  Int_t gsNdecIPR=397; //number of IPR saved in dec format
+  
+  // Read Individual pixel rates in hex format
+  const char *pos = str.Data();
+  const char *end = str.Data() + gsNhexIPR*8;
+  
+  Int_t i=0,n,len;
+  short dummy;
+  while (pos < end)
+    {
+      const Char_t hex[9] = { pos[0], pos[1], pos[2], pos[3],pos[4],pos[5],pos[6],pos[7],0 };
+      n = sscanf(hex, "%hx", &dummy);
+      pos+=8;
+      if (n!=1)
+        {
+	  *fLog << warn << "WARNING - Rate #" << i << " missing." << endl;
+	  return kFALSE;
+        }
+    }
+    
+  str.Remove(0, end-str.Data()); // Remove IPR hex  from report string
+  str.Strip(TString::kBoth);
+  
+  // ------  
+  // Read Individual pixel rates in dec format 
+  // and save them in the MTriggerIPR container
+  
+  for (i=0;i<gsNdecIPR;i++)
+    {
+      n = sscanf(str.Data(), " %ld %n", &fIPR->fIPR[i], &len);
+      if (n!=1)
+	{
+	  *fLog << warn << "WARNING - IPR dec #" << i << " missing." << endl;
+	  return kCONTINUE;
+	}
+      str.Remove(0, len); // Remove IPR dec from report string      
+    }
+  
+  str=str.Strip(TString::kLeading);  
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the TRIGGER-REPORT string
+//  Read comments for details
+//
+Int_t MReportTrigger::InterpreteBody(TString &str, Int_t ver )
+{
+
+    str = str.Strip(TString::kLeading);
+ 
+    // Extract trigger table name
+    const Int_t ws = str.First(' ');
+ 
+   if (ws<=0)
+    {
+        *fLog << warn << "WARNING - Cannot determine name of trigger table." << endl;
+        return kCONTINUE;
+    }
+
+    TString tablename = str(0, ws);
+    str.Remove(0, ws);
+
+    // Check the Version of CC file, and takes care of the differences
+    // introduced in the format of the report.
+
+    //if (ver<)....
+	
+    // Check the length of the report to take care of the differences
+    // introduced in the format of the report (!Preliminary! the 
+    // Version number of the CC file should be used instead)
+
+    if (str.Length() < 1000)
+      {
+	*fLog << warn << " TRIGGER-REPORT: old report without IPRs" <<endl;
+        return InterpreteOldBody(str);
+      }
+
+    // Read the cell rates (32 fields)
+    if (!InterpreteCell(str))
+      return kCONTINUE;
+
+    // Read L1 and L2 table name (2 fields)
+    if (!InterpreteL1L2Table(str))
+      return kCONTINUE;    
+
+    // Read prescaling factors  (2x8 fields)
+    if (!InterpretePrescFact(str))
+      return kCONTINUE;
+    
+    // Read livetime and deadtime (5x4 fields)
+    if (!InterpreteLiveTime(str))
+      return kCONTINUE;
+
+    // Read L2 outout bit rates
+    if (!InterpreteBit(str))
+      return kCONTINUE;
+
+    // Read global rates (before and after prescaling)
+    Int_t len, n;
+    n = sscanf(str.Data(), " %f %f %n", &fL2BeforePrescaler, &fL2AfterPrescaler, &len);
+    if (n!=2)
+    {
+         *fLog << warn << "WARNING - Couldn't read Trigger rates." << endl;
+        return kFALSE;
+    }
+    str.Remove(0,len);
+    str.Strip(TString::kBoth);
+
+    // Read 18 dummy fields
+    if (!InterpreteDummy(str))
+      return kCONTINUE;
+
+    // Read IPR
+    if (!InterpreteIPR(str))
+      return kCONTINUE;
+
+ 
+
+  //    str.Remove(0,len);
+  //  str.Strip(TString::kBoth);
+
+  //*fLog << warn << " str=" << str << endl;
+
+    return str==(TString)"OVER" ? kTRUE : kCONTINUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the TRIGGER-REPORT string
+//  for OLD runs (older than may-04)
+//
+Bool_t MReportTrigger::InterpreteOldBody(TString &str)
+{
+
+  Int_t len, n;
+  Float_t fPrescalerRates[100]; 
+
+    const char *pos = str.Data();
+    for (int i=0; i<19; i++)
+      {
+        n = sscanf(pos, " %f %n", &fPrescalerRates[i], &len);
+        if (n!=1)
+	  {
+            *fLog << warn << "WARNING - Scaler Value #" << i << " missing." << endl;
+            return kCONTINUE;
+	  }
+        pos += len;
+      }
+
+    n = sscanf(pos, " %f %f %n", &fL2BeforePrescaler, &fL2AfterPrescaler, &len);    if (n!=2)
+      {
+        *fLog << warn << "WARNING - Couldn't read Trigger rates." << endl;
+        return kFALSE;
+      }
+    pos += len;
+    for (int i=0; i<11; i++)
+      {
+        Float_t dummy;
+        n = sscanf(pos, " %f %n", &dummy/*fRates[i]*/, &len);
+        if (n!=1)
+	  {
+            *fLog << warn << "WARNING - Rate #" << i << " missing." << endl;
+            return kFALSE;
+	  }
+        pos += len;
+      }
+    str.Remove(0, pos-str.Data());
+    str.Strip(TString::kBoth);
+    
+    return str==(TString)"OVER" ? kTRUE : kCONTINUE;
+}
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MReportTrigger.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MReportTrigger.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MReportTrigger.h	(revision 9772)
@@ -0,0 +1,54 @@
+#ifndef MARS_MReportTrigger
+#define MARS_MReportTrigger
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerIPR;
+class MTriggerCell;
+class MTriggerBit;
+class MTriggerPrescFact;
+class MTriggerLiveTime;
+
+class MReportTrigger : public MReport
+{
+private:
+  
+  Float_t fL2BeforePrescaler; //! L2 trigger rate before prescaler
+  Float_t fL2AfterPrescaler;  //! L2 trigger rate after prescaler
+  
+  MTriggerBit *fBit;        //! container of the L2 prescaler rates
+  MTriggerIPR *fIPR;        //! container of the IPR
+  MTriggerCell *fCell;      //! container of the L1 cell trigger rates
+  MTriggerPrescFact *fPrescFactor;  //! container of the L2 prescaling factors
+  MTriggerLiveTime *fLiveTime; //! container of the scaler live-deadtime 
+  
+  Bool_t SetupReading(MParList &plist);
+
+  Bool_t InterpreteIPR(TString &str);
+  Bool_t InterpreteCell(TString &str);
+  Bool_t InterpreteBit(TString &str);
+  Bool_t InterpretePrescFact(TString &str);
+  Bool_t InterpreteLiveTime(TString &str);
+  Bool_t InterpreteDummy(TString &str);
+  Bool_t InterpreteL1L2Table(TString &str);
+
+  Int_t InterpreteBody(TString &str, Int_t ver);
+  
+  Bool_t InterpreteOldBody(TString &str);
+
+public:
+    MReportTrigger();
+
+    Float_t GetL2BeforePrescaler() const { return fL2BeforePrescaler; }
+    Float_t GetL2AfterPrescaler() const { return fL2AfterPrescaler; }
+
+    ClassDef(MReportTrigger, 1) // Class for TRIGGER-REPORT information
+ };
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerBit.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerBit.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerBit.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerBit
+//   This class stores the information about the L2 output Bit rates
+//   
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerBit.h"
+
+ClassImp(MTriggerBit);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerBit.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerBit.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerBit.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MTriggerBit
+#define MARS_MTriggerBit
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerBit : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+
+private:
+    Byte_t  fStatus;        // Monitor of the L2T status
+    
+    Int_t gsNBits=16;        // number of output bits
+
+    TArrayL fBit; // Array with the prescaling factors
+
+public:
+    MTriggerBit() : fBit(gsNBits)  
+    {
+        fName  = "MTriggerBit";
+        fTitle = "Container for the L2 output bits rates ";
+    }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNBits)
+	return kFALSE;
+
+      val = fBit[idx];	
+
+      return val>0;
+    }
+
+    Double_t operator[](const UInt_t idx) 
+      {  
+	if (idx > gsNBits)
+	  return kFALSE;
+	
+	return fBit[idx]; 
+      }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerBit, 1) // Container for the L2 output bits rates
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerCell.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerCell.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerCell.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerCell
+//   This class stores the information about the Trigger Cell Rates
+//   
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerCell.h"
+
+ClassImp(MTriggerCell);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerCell.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerCell.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerCell.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MTriggerCell
+#define MARS_MTriggerCell
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerCell : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+private:
+    Byte_t  fStatus;         // Monitor of the L2T status
+
+    Int_t gsNCells=19;       //Number of trigger cells
+
+    TArrayL fCellRate;       // Array of the measured L1 cell rates
+
+public:
+    MTriggerCell() : fCellRate(gsNCells)
+    {
+        fName  = "MTriggerCell";
+        fTitle = "Container for the measured cell rates";
+    }
+
+    Float_t GetMean() const { return fCellRate.GetSum()/fCellRate.GetSize(); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNCells)
+	return kFALSE;
+      
+      val = fCellRate[idx];
+        return val>0;
+    }
+
+    Double_t operator[](const UInt_t idx) 
+      { 
+	if (idx > gsNCells)
+	  return kFALSE;
+	
+	return fCellRate[idx]; 
+      }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerCell, 1) // Container for the trigger cell rates
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerIPR
+//   This class stores the information about the Individual Pixel Rates
+//   
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerIPR.h"
+
+ClassImp(MTriggerIPR);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.cc~
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.cc~	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.cc~	(revision 9772)
@@ -0,0 +1,34 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraHV
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraHV.h"
+
+ClassImp(MCameraHV);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MTriggerIPR
+#define MARS_MTriggerIPR
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerIPR : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+private:
+    Byte_t  fStatus;        // Monitor of the L2T status
+
+    TArrayL fIPR;            // [Hz] IPR (Individual Pixel Rates)
+    
+    Int_t gsNTrigPix=397;  // number of trigger pixels
+
+public:
+    MTriggerIPR() : fIPR(gsNTrigPix)
+    {
+        fName  = "MTriggerIPR";
+        fTitle = "Container for the Individual Pixel Rate (IPR)";
+    }
+
+    Float_t GetMean() const { return fIPR.GetSum()/fIPR.GetSize(); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNTrigPix)
+	return kFALSE;
+
+      val = fIPR[idx];
+      return val>0;
+    }
+
+    Double_t operator[](const UInt_t idx) 
+      {
+	if (idx > gsNTrigPix)
+	  return kFALSE;
+
+	return fIPR[idx]; 
+      } 
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerIPR, 1) // Container for the Individual Pixel Rate (IPR)
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.h~
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.h~	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerIPR.h~	(revision 9772)
@@ -0,0 +1,63 @@
+#ifndef MARS_MCameraHV
+#define MARS_MCameraHV
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class MCameraHV : public MParContainer, public MCamEvent
+{
+    friend class MReportCamera;
+private:
+    Byte_t  fStatus;        // CaCo monitored status of the High Voltage [0-9], Cam.HV.PS_state
+    Bool_t  fStatusRamping; // CaCo monitored status of ramping the HV, Cam.HV_state
+
+    Short_t fVoltageA;      // [V] Measured voltage of power supply A, hvps1
+    Short_t fVoltageB;      // [V] Measured voltage of power supply B, hvps2
+
+    Byte_t fCurrentA;       // [mA] Measured current of power supply A, curr1
+    Byte_t fCurrentB;       // [mA] Measured current of power supply B, curr2
+
+    TArrayS fHV;            // [V] Measured high Voltages for all PMTs
+
+public:
+    MCameraHV() : fHV(577)
+    {
+        fName  = "MCameraHV";
+        fTitle = "Container storing information about the Camera HV";
+    }
+
+    Byte_t  GetStatus() const { return fStatus; }
+    Bool_t  GetStatusRamping() const { return fStatusRamping; }
+
+    Short_t GetVoltageA() const { return fVoltageA; }
+    Short_t GetVoltageB() const { return fVoltageB; }
+
+    Byte_t  GetCurrentA() const { return fCurrentA; }
+    Byte_t  GetCurrentB() const { return fCurrentB; }
+
+    Float_t GetMean() const { return fHV.GetSum()/fHV.GetSize(); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+        val = fHV[idx];
+        return val>0;
+    }
+
+    Double_t operator[](const UInt_t idx) { return fHV[idx]; }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MCameraHV, 1) // Container storing information about the Camera HV
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerLiveTime.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerLiveTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerLiveTime.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerLiveTime
+//   This class stores the information about the livetime and deadtime
+//   measured by the scalers 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerLiveTime.h"
+
+ClassImp(MTriggerLiveTime);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerLiveTime.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerLiveTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerLiveTime.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MTriggerLiveTime
+#define MARS_MTriggerLiveTime
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerLiveTime : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+
+private:
+    Byte_t  fStatus;        // Monitor of the L2T status
+    
+    Int_t gsNScalers=5;        // number of scalers
+
+    TArrayL fLiveTime; // Array with the livetime
+    TArrayL fDeadTime; // Array with the deadtime
+
+public:
+    MTriggerLiveTime() : fLiveTime(gsNScalers)  
+    {
+        fName  = "MTriggerLiveTime";
+        fTitle = "Container for the Live-deadtime      ";
+    }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNScalers)
+	return kFALSE;
+
+      val = fLiveTime[idx];	
+
+      return val>0;
+    }
+
+    Double_t operator[](const UInt_t idx) 
+      {  
+	Double_t val=0;
+
+	return GetPixelContent(&val, idx)>0? val: -1; 
+      }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerLiveTime, 1) // Container for the Live-Deadtime
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerPrescFact.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerPrescFact.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerPrescFact.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerPrescFact
+//   This class stores the information about the L2 prescaling factors
+//   
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerPrescFact.h"
+
+ClassImp(MTriggerPrescFact);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerPrescFact.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerPrescFact.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/MTriggerPrescFact.h	(revision 9772)
@@ -0,0 +1,58 @@
+#ifndef MARS_MTriggerPrescFact
+#define MARS_MTriggerPrescFact
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerPrescFact : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+
+private:
+    Byte_t  fStatus;        // Monitor of the L2T status
+    
+    Int_t gsNPrescFacts=8;        // number of factors
+
+    TArrayL fPrescFact; // Array with the prescaling factors
+
+public:
+    MTriggerPrescFact() : fPrescFact(gsNPrescFacts)  
+    {
+        fName  = "MTriggerPrescFact";
+        fTitle = "Container for the L2 Prescaling Factors      ";
+    }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNPrescFacts)
+	return kFALSE;
+
+      val = fPrescFact[idx];	
+
+      return val>0;
+    }
+
+    Double_t operator[](const UInt_t idx) 
+      {  
+	if (idx > gsNPrescFacts)
+	  return kFALSE;
+	
+	return fPrescFact[idx]; 
+      }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerPrescFact, 1) // Container for the L2 Prescaling Factors
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MFindStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MFindStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MFindStars.cc	(revision 9772)
@@ -0,0 +1,1274 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Robert Wagner,   2/2004 <mailto:rwagner@mppmu.mpg.de>
+!              Javier López ,   4/2004 <mailto:jlopez@ifae.es>
+!              Wolfgang Wittek, 8/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFindStars
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFindStars.h"
+
+#include <TMinuit.h>
+#include <TStopwatch.h>
+#include <TTimer.h>
+#include <TString.h>
+#include <TFile.h>
+#include <TTree.h>
+#include <TCanvas.h>
+#include <TH1F.h>
+#include <TF1.h>
+#include <TEllipse.h>
+
+
+#include "MObservatory.h"
+#include "MAstroCamera.h"
+#include "MMcConfigRunHeader.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+#include "MTime.h"
+#include "MReportDrive.h"
+#include "MStarCam.h"
+#include "MStarPos.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MFindStars);
+using namespace std;
+
+const Float_t sqrt2 = sqrt(2.);
+const Float_t sqrt3 = sqrt(3.);
+const UInt_t  lastInnerPixel = 396;
+    
+
+//______________________________________________________________________________
+//
+// The 2D uncorrelated gaussian function used to fit the spot of the star
+//
+static Double_t func(float x,float y,Double_t *par)
+{
+    Double_t value=par[0]*exp( -(x-par[1])*(x-par[1])/(2*par[2]*par[2]) )
+                         *exp( -(y-par[3])*(y-par[3])/(2*par[4]*par[4]) );
+    return value;
+}
+
+//______________________________________________________________________________
+//
+// The 2D correlated gaussian function used to fit the spot of the star
+//
+static Double_t funcCG(float x,float y,Double_t *par)
+{
+  Double_t temp  = 1.0-par[5]*par[5];
+  //  Double_t value = par[0] / (2.0*TMath::Pi()*par[2]*par[4]*sqrt(temp))
+  Double_t value = par[0] 
+    * exp( -0.5/temp * (   (x-par[1])*(x-par[1])/(par[2]*par[2])
+	     -2.0*par[5] * (x-par[1])*(y-par[3])/(par[2]*par[4])
+			 + (y-par[3])*(y-par[3])/(par[4]*par[4]) ) );
+    return value;
+}
+
+//______________________________________________________________________________
+//
+// Function used by Minuit to do the fit
+//
+static void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
+{
+
+  MParList*      plist = (MParList*)gMinuit->GetObjectFit();
+  MTaskList*     tlist = (MTaskList*)plist->FindObject("MTaskList");
+  MFindStars*    find  = (MFindStars*)tlist->FindObject("MFindStars");
+  MStarCam* stars = 
+          (MStarCam*)plist->FindObject("MStarCam","MStarCam");
+  MGeomCam*      geom  = (MGeomCam*)plist->FindObject("MGeomCam");
+
+  MHCamera& display = (MHCamera&)find->GetDisplay();
+  
+  Float_t innerped = stars->GetInnerPedestalDC();
+  Float_t innerrms = stars->GetInnerPedestalRMSDC();
+  Float_t outerped = stars->GetOuterPedestalDC();
+  Float_t outerrms = stars->GetOuterPedestalRMSDC();
+
+  UInt_t numPixels = geom->GetNumPixels();
+  
+
+//calculate chisquare
+    Double_t chisq = 0;
+    Double_t delta;
+    Double_t x,y,z;
+    Double_t errorz=0;
+
+    UInt_t usedPx=0;
+    for (UInt_t pixid=1; pixid<numPixels; pixid++) 
+    {
+
+
+	if (display.IsUsed(pixid))
+	{
+	    x = (*geom)[pixid].GetX();
+	    y = (*geom)[pixid].GetY();
+
+            z = display.GetBinContent(pixid+1)
+                -  (pixid>lastInnerPixel?outerped:innerped);
+            errorz=(pixid>lastInnerPixel?outerrms:innerrms);
+
+
+	    if (errorz > 0.0)
+	    {
+              usedPx++;
+
+              Double_t fu;
+              if (find->GetUseCorrelatedGauss())
+                fu = funcCG(x,y,par);
+              else
+                fu = func(x,y,par);
+
+              delta  = (z-fu) / errorz;
+              chisq += delta*delta; 
+
+              if (iflag == 3)
+	      {
+                gLog  << "fcn : usedPx, pixid, content, pedestal,z, fu, errorz, delta = "
+                      << usedPx << ",  " << pixid << ",  "
+                      << display.GetBinContent(pixid+1) << ",  "
+                      << (pixid>lastInnerPixel?outerped:innerped)
+                      << ",  " << z << ",  " << fu << ",  " << errorz 
+                      << ",  " << delta << endl;
+	      }
+	    }
+	    else
+		cerr << " TMinuit::fcn errorz[" << pixid << "] " << errorz << endl;
+	}
+    }
+    f = chisq;
+
+    find->SetChisquare(chisq);
+    find->SetDegreesofFreedom(usedPx);
+
+    //gLog << "fcn : chisq, usedPx = " << chisq << ",  " << usedPx << endl;
+}
+
+//-------------------------------------------------------------------------
+//
+// Constructor
+//
+
+MFindStars::MFindStars(const char *name, const char *title): 
+  fGeomCam(NULL), fCurr(NULL), fTimeCurr(NULL), fDrive(NULL), fStars(NULL), 
+  fNumVar(6)
+{
+  fName  = name  ? name  : "MFindStars";
+  fTitle = title ? title : "Tool to find stars from DC Currents";
+
+  // the correlated Gauss function  
+  // is fitted by default
+  fNumVar = 6;
+  fUseCorrelatedGauss = kTRUE;
+
+  fNumIntegratedEvents=0;
+  fMaxNumIntegratedEvents = 10;
+  fRingInterest = 125.; //[mm] ~ 0.4 deg
+  fDCTailCut = 4;
+  
+  fPixelsUsed.Set(577);
+  fPixelsUsed.Reset((Char_t)kTRUE);
+  
+  //Fitting(Minuit) initialitation
+  const Float_t pixelSize = 31.5; //[mm]
+  fMinuitPrintOutLevel = -1;
+  //fMinuitPrintOutLevel = 3;
+  
+  fVname = new TString[fNumVar];
+  fVinit.Set(fNumVar); 
+  fStep.Set(fNumVar); 
+  fLimlo.Set(fNumVar); 
+  fLimup.Set(fNumVar); 
+  fFix.Set(fNumVar);
+
+  fVname[0] = "max";
+  fVinit[0] = 10.*fMaxNumIntegratedEvents;
+  fStep[0]  = fVinit[0]/sqrt2;
+  fLimlo[0] = fMinDCForStars;
+  fLimup[0] = 30.*fMaxNumIntegratedEvents;
+  fFix[0]   = 0;
+
+  fVname[1] = "meanx";
+  fVinit[1] = 0.;
+  fStep[1]  = fVinit[1]/sqrt2;
+  fLimlo[1] = -600.;
+  fLimup[1] = 600.;
+  fFix[1]   = 0;
+
+  fVname[2] = "sigmax";
+  fVinit[2] = pixelSize;
+  fStep[2]  = fVinit[2]/sqrt2;
+  fLimlo[2] = pixelSize/(2*sqrt3);
+  fLimup[2] = 500.;
+  fFix[2]   = 0;
+
+  fVname[3] = "meany";
+  fVinit[3] = 0.;
+  fStep[3]  = fVinit[3]/sqrt2;
+  fLimlo[3] = -600.;
+  fLimup[3] = 600.;
+  fFix[3]   = 0;
+
+  fVname[4] = "sigmay";
+  fVinit[4] = pixelSize;
+  fStep[4]  = fVinit[4]/sqrt2;
+  fLimlo[4] = pixelSize/(2*sqrt3);
+  fLimup[4] = 500.;
+  fFix[4]   = 0;
+
+  if (fUseCorrelatedGauss)
+  {
+    fVname[5] = "xycorr";
+    fVinit[5] = 0.0;
+    fStep[5]  = 0.1;
+    fLimlo[5] = -1.0;
+    fLimup[5] =  1.0;
+    fFix[5]   = 0;
+  }
+
+  fObjectFit  = NULL;
+  //  fMethod     = "SIMPLEX";
+  fMethod     = "MIGRAD";
+  //  fMethod     = "MINIMIZE";
+  fNulloutput = kFALSE;
+
+  // Set output level
+  //  fLog->SetOutputLevel(3); // No dbg messages
+
+  fGeometryFile="";
+  fBSCFile="";
+}
+
+//-------------------------------------------------------------------------
+//
+// Set 'fUseCorrelatedGauss' flag
+//
+//     if 'fUseCorrelatedGauss' is TRUE a 2dim Gaussian with correlation
+//                                 will be fitted
+//
+
+void MFindStars::SetUseCorrelatedGauss(Bool_t usecorrgauss)
+{
+  fUseCorrelatedGauss = usecorrgauss;
+
+  if (usecorrgauss)
+    fNumVar = 6;
+  else
+    fNumVar = 5;
+}
+
+//-------------------------------------------------------------------------
+//
+// PreProcess
+//
+
+Int_t MFindStars::PreProcess(MParList *pList)
+{
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+
+    if (!fGeomCam)
+    {
+      *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    // Initialize camera display with the MGeomCam information
+    fDisplay.SetGeometry(*fGeomCam,"FindStarsDisplay","FindStarsDisplay");
+    fDisplay.SetUsed(fPixelsUsed);
+
+    fCurr = (MCameraDC*)pList->FindObject(AddSerialNumber("MCameraDC"));
+
+    if (!fCurr)
+    {
+      *fLog << err << AddSerialNumber("MCameraDC") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fTimeCurr = (MTime*)pList->FindObject(AddSerialNumber("MTimeCurrents"));
+
+    if (!fTimeCurr)
+    {
+      *fLog << err << AddSerialNumber("MTimeCurrents") << " not found ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fDrive = (MReportDrive*)pList->FindObject(AddSerialNumber("MReportDrive"));
+
+    if (!fDrive)
+      {
+
+        *fLog << warn << AddSerialNumber("MReportDrive") << " not found ... ignored." << endl;
+
+      }
+    else
+      {
+	MObservatory magic1;
+
+	MMcConfigRunHeader *config=0;
+	MGeomCam           *geom=0;
+
+	TFile file(fGeometryFile);
+	TTree *tree = dynamic_cast<TTree*>(file.Get("RunHeaders"));
+	tree->SetBranchAddress("MMcConfigRunHeader.", &config);
+	if (tree->GetBranch("MGeomCam.")) tree->SetBranchAddress("MGeomCam.", &geom);
+
+	TClonesArray mirrorArray = *config->GetMirrors();
+	fAstro.SetMirrors(*config->GetMirrors());
+	fAstro.SetGeom(*geom);	
+	fAstro.ReadBSC(fBSCFile);
+	fAstro.SetObservatory(magic1);
+	
+      }
+    
+
+    fStars = (MStarCam*)pList->FindCreateObj(AddSerialNumber("MStarCam"),"MStarCam");
+    if (!fStars)
+    {
+      *fLog << err << AddSerialNumber("MStarCam") << " cannot be created ... aborting" << endl;
+      return kFALSE;
+    }
+
+    fMinDCForStars = 1.*fMaxNumIntegratedEvents; //[uA]
+
+    // Initialize the TMinuit object
+
+    TMinuit *gMinuit = new TMinuit(fNumVar);  //initialize TMinuit with a maximum of params
+    gMinuit->SetFCN(fcn);
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    arglist[0] = 1;
+    gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
+    arglist[0] = fMinuitPrintOutLevel;
+    gMinuit->mnexcm("SET PRI", arglist ,1,ierflg);
+
+    // suppress warnings
+    Int_t errWarn;
+    Double_t tmpwar = 0;
+    gMinuit->mnexcm("SET NOW", &tmpwar, 0, errWarn);
+
+
+    // Set MParList object pointer to allow mimuit to access internally
+    gMinuit->SetObjectFit(pList);
+    return kTRUE;
+}
+
+//------------------------------------------------------------------------
+//
+// Process :
+//              
+//
+//
+//
+
+Int_t MFindStars::Process()
+{
+  UInt_t numPixels = fGeomCam->GetNumPixels();
+  TArrayC origPixelsUsed;
+  origPixelsUsed.Set(numPixels);
+
+  if (fNumIntegratedEvents >= fMaxNumIntegratedEvents) {
+
+    //Fist delete the previous stars in the list
+    fStars->GetList()->Delete();
+
+    if (fDrive) {
+
+      //If drive information is provided we take RaDec info
+      //from the drive and let the star list fill by the astrocamera.
+
+      //FIXME: rwagner: Doesn't work as expected
+      //FIXME: rwagner: For the time being set manually.
+      //fAstro.SetRaDec(fDrive->GetRa(), fDrive->GetDec());              
+
+      fAstro.SetTime(*fTimeCurr);
+      fAstro.SetGuiActive();
+      fAstro.FillStarList(fStars->GetList());      
+
+      cout << "Number of Stars added by astrocamera is " 
+           <<fStars->GetList()->GetSize() << endl;
+      
+      MStarPos* starpos;
+      TIter Next(fStars->GetList());
+      while ((starpos=(MStarPos*)Next())) {
+	//starpos->SetCalcValues(40,40,starpos->GetXExp(), starpos->GetYExp(),
+        //                       fRingInterest/2,          fRingInterest/2,
+        //                       0.,   0., 0., 0.);
+	//starpos->SetFitValues (40,40,starpos->GetXExp(), starpos->GetYExp(),
+        //                       fRingInterest/2,          fRingInterest/2, 0.,
+        //                       0., 0., 0.,   0., -1);
+      }
+
+      for (UInt_t pix=1; pix<numPixels; pix++) {
+	if (fDisplay.IsUsed(pix))
+	  origPixelsUsed[pix]=(Char_t)kTRUE;
+	else
+	  origPixelsUsed[pix]=(Char_t)kFALSE;
+      }
+      
+      DCPedestalCalc();
+
+    }
+    else 
+    {
+      
+      cout << "No drive information available: Will not use a star catalog to identify stars."<< endl;
+      
+      for (UInt_t pix=1; pix<numPixels; pix++) {
+	if (fDisplay.IsUsed(pix))
+	  origPixelsUsed[pix]=(Char_t)kTRUE;
+	else
+	  origPixelsUsed[pix]=(Char_t)kFALSE;
+      }
+          
+      if (DCPedestalCalc()) {
+
+	Float_t innermin = fStars->GetInnerPedestalDC()+fDCTailCut*fStars->GetInnerPedestalRMSDC();
+	Float_t outermin = fStars->GetOuterPedestalDC()+fDCTailCut*fStars->GetOuterPedestalRMSDC();
+	fMinDCForStars = innermin>outermin?innermin:outermin;
+	if (fMinuitPrintOutLevel>=0) *fLog << dbg << "fMinDCForStars = " << fMinDCForStars << endl;
+              
+	// Find the star candidates searching the most brights pairs of pixels
+	Float_t maxPixelDC;
+	MGeomPix maxPixel;
+	
+	while(FindPixelWithMaxDC(maxPixelDC, maxPixel)) {
+	  MStarPos *starpos = new MStarPos;
+
+  	  starpos->SetExpValues(maxPixelDC,maxPixel.GetX(),maxPixel.GetY());
+
+	  //starpos->SetCalcValues(maxPixelDC,      maxPixelDC,
+          //                       maxPixel.GetX(), maxPixel.GetY(),
+          //                       fRingInterest/2, fRingInterest/2,
+          //                       0.,   0., 0., 0.);
+
+	  //starpos->SetFitValues(maxPixelDC,      maxPixelDC,
+          //                      maxPixel.GetX(), maxPixel.GetY(),
+          //                      fRingInterest/2, fRingInterest/2, 0.,
+          //                      0., 0., 0.,      0., -1);
+
+	  fStars->GetList()->Add(starpos);
+	  ShadowStar(starpos);
+	}	
+	fDisplay.SetUsed(origPixelsUsed);
+      }      
+    }
+
+    //Show the stars found
+    fStars->Print("namepossizechierr");
+   
+    //loop to extract position of stars on the camera
+    if (fStars->GetList()->GetSize() == 0) {
+      *fLog << err << GetName() << "No stars candidates in the camera." << endl;
+      return kCONTINUE;
+    } 
+    else
+    {
+      *fLog << inf << GetName() << " found " << fStars->GetList()->GetSize() 
+      	    << " star candidates in the camera." << endl;
+    }    
+
+    for (UInt_t pix=1; pix<numPixels; pix++) {
+      if (fDisplay.IsUsed(pix))
+	origPixelsUsed[pix]=(Char_t)kTRUE;
+      else
+	origPixelsUsed[pix]=(Char_t)kFALSE;
+    }
+
+    TIter Next(fStars->GetList());
+    MStarPos* star;
+    while ((star=(MStarPos*)Next())) {
+       FindStar(star);
+       ShadowStar(star);
+    }
+
+    //Show the stars found: Here it is interesting to see what FindStars
+    //made out of the positions we gave to it.
+    if (fMinuitPrintOutLevel>=0)
+      fStars->Print("namepossizchierr");
+
+    //After finding stars reset all variables
+    fDisplay.Reset();
+    fStars->GetDisplay().Reset(); //FIXME: Put this display just in the container
+    fDisplay.SetUsed(origPixelsUsed);
+    fNumIntegratedEvents=0;
+  }
+
+  for (UInt_t pix=1; pix<numPixels; pix++) {
+    if (fDisplay.IsUsed(pix))
+      origPixelsUsed[pix]=(Char_t)kTRUE;
+    else
+      origPixelsUsed[pix]=(Char_t)kFALSE;
+    
+  }
+  
+  fDisplay.AddCamContent(*fCurr);
+  fNumIntegratedEvents++;
+  fDisplay.SetUsed(origPixelsUsed);
+  
+  return kTRUE;
+}
+
+Int_t MFindStars::PostProcess()
+{
+  return kTRUE;
+}
+
+void MFindStars::SetBlindPixels(TArrayS blindpixels)
+{
+    Int_t npix = blindpixels.GetSize();
+
+    for (Int_t idx=0; idx<npix; idx++)
+      {
+	fPixelsUsed[blindpixels[idx]]=(Char_t)kFALSE;
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << "MFindStars::SetBlindPixels fDisplay.IsUsed(" <<blindpixels[idx]  << ") kFALSE" << endl;
+      }
+    
+    fDisplay.SetUsed(fPixelsUsed);
+}
+
+//-------------------------------------------------------------------------
+//
+// DCPedestalCalc :
+//
+//  
+//
+//
+
+Bool_t MFindStars::DCPedestalCalc()
+{
+    //-------------------------------------------------------------
+    // save pointer to the MINUIT object for optimizing the supercuts
+    // because it will be overwritten 
+    // when fitting the alpha distribution in MHFindSignificance
+    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+   UInt_t numPixels = fGeomCam->GetNumPixels();
+   Float_t ped;
+   Float_t rms;
+
+   //TH1F **dchist = new TH1F*[2];
+   TH1F *dchist[2];
+   TString tit;
+   TString nam;
+   for (UInt_t i=0; i<2; i++)
+   {
+      nam = i;
+      tit = "dchist[";
+      tit += i;
+      tit += "]";
+      dchist[i] = new TH1F(nam, tit,
+                  26,0.4*fMaxNumIntegratedEvents,3.*fMaxNumIntegratedEvents);
+   }   
+
+   for (UInt_t pix=1; pix<=lastInnerPixel; pix++)
+       dchist[0]->Fill(fDisplay.GetBinContent(pix+1));
+   for (UInt_t pix=lastInnerPixel+1; pix<numPixels; pix++)
+       dchist[1]->Fill(fDisplay.GetBinContent(pix+1));
+
+   // inner/outer pixels
+   for (UInt_t i=0; i<2; i++)
+   {
+      Float_t nummaxprobdc = dchist[i]->GetBinContent(dchist[i]->GetMaximumBin());
+      Float_t maxprobdc = dchist[i]->GetBinCenter(dchist[i]->GetMaximumBin());
+      UInt_t bin = dchist[i]->GetMaximumBin();
+      do
+        {
+          bin++;
+        }
+      while(dchist[i]->GetBinContent(bin)/nummaxprobdc > 0.5);
+      Float_t halfmaxprobdc = dchist[i]->GetBinCenter(bin);
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " maxprobdc[high] " << maxprobdc << "[" << nummaxprobdc << "] ";
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " halfmaxprobdc[high] " << halfmaxprobdc << "[" << dchist[i]->GetBinContent(bin) << "]" << endl;
+      
+      Float_t rmsguess = TMath::Abs(maxprobdc-halfmaxprobdc);
+      Float_t min = maxprobdc-3*rmsguess;
+      min = (min<0.?0.:min);
+      Float_t max = maxprobdc+3*rmsguess;
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+      
+      TF1 func("func","gaus",min,max);
+      func.SetParameters(nummaxprobdc, maxprobdc, rmsguess);
+      
+      dchist[i]->Fit("func","QR0");
+      
+      UInt_t aproxnumdegrees = 6*(bin-dchist[i]->GetMaximumBin());
+      Float_t chiq = func.GetChisquare();
+      ped = func.GetParameter(1);
+      rms = func.GetParameter(2);
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " ped " << ped << " rms " << rms << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+      
+      Int_t numsigmas = 5;
+      Axis_t minbin = ped-numsigmas*rms/dchist[i]->GetBinWidth(1);
+      minbin=minbin<1?1:minbin;
+      Axis_t maxbin = ped+numsigmas*rms/dchist[i]->GetBinWidth(1);
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " Number of pixels with dc under " << numsigmas << " sigmas = " << dchist[i]->Integral((int)minbin,(int)maxbin) << endl;
+      
+      //Check results from the fit are consistent
+      if (ped < 0. || rms < 0.)
+        {
+          *fLog << dbg << "dchist[i]->GetEntries()" << dchist[i]->GetEntries();
+//            TCanvas *c1 = new TCanvas("c2","c2",500,800);
+//            dchist[i]->Draw();
+//            c1->Print("dchist.ps");
+//            delete c1;
+//            exit(1);
+        }
+      else if (TMath::Abs(ped-maxprobdc) > rmsguess || rms > rmsguess)
+        {
+          *fLog << warn << GetName() << " Pedestal DC fit give non consistent results for " << (i==0?"Inner":"Outer") << "pixels." << endl;
+          *fLog << warn << " maxprobdc " << maxprobdc << " rmsguess " << rmsguess << endl;
+          *fLog << warn << " ped " << ped << " rms " << rms << " chiq/ndof " << chiq << "/" << aproxnumdegrees << endl;
+          ped = maxprobdc;
+          rms = rmsguess/1.175; // FWHM=2.35*rms
+        }
+   
+      if (i == 0)
+        {
+          fStars->SetInnerPedestalDC(ped);
+          fStars->SetInnerPedestalRMSDC(rms);
+        }
+      else
+        {
+          fStars->SetOuterPedestalDC(ped);
+          fStars->SetOuterPedestalRMSDC(rms);
+        }
+   }
+   
+
+
+   for (UInt_t i=0; i<2; i++)
+   {
+      delete dchist[i];
+   }
+   //delete [] dchist;
+
+   //=================================================================
+
+   // reset gMinuit to the MINUIT object for optimizing the supercuts 
+   gMinuit = savePointer;
+   //-------------------------------------------
+   
+   if (fStars->GetInnerPedestalDC() < 0. ||  fStars->GetInnerPedestalRMSDC() < 0. || fStars->GetOuterPedestalDC() < 0. ||  fStars->GetOuterPedestalRMSDC() < 0.)
+     return kFALSE;
+  
+   return kTRUE;
+}
+    
+Bool_t MFindStars::FindPixelWithMaxDC(Float_t &maxDC, MGeomPix &maxPix)
+{
+    UInt_t numPixels = fGeomCam->GetNumPixels();
+
+// Find the two close pixels with the maximun dc
+    UInt_t maxPixIdx[2];
+
+    maxDC = 0;
+
+    for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+	if(fDisplay.IsUsed(pix))
+	{
+	    Float_t dc[2];
+	    dc[0] = fDisplay.GetBinContent(pix+1);
+	    if (dc[0] < fMinDCForStars)
+		continue;
+
+	    MGeomPix &g = (*fGeomCam)[pix];
+	    Int_t numNextNeighbors = g.GetNumNeighbors();
+	    
+	    Float_t dcsum;
+	    for(Int_t nextNeighbor=0; nextNeighbor<numNextNeighbors; nextNeighbor++)
+	    {
+              UInt_t swneighbor = g.GetNeighbor(nextNeighbor);
+              if(fDisplay.IsUsed(swneighbor))
+                {
+                  dc[1] = fDisplay.GetBinContent(swneighbor+1);
+                  if (dc[1] < fMinDCForStars)
+                    continue;
+                  
+                  dcsum = dc[0] + dc[1];
+                  
+                  if(dcsum > maxDC*2)
+                    {
+                      if(dc[0]>=dc[1])
+                        {
+                          maxPixIdx[0] = pix;
+                          maxPixIdx[1] = swneighbor;
+                          maxDC = dc[0];
+                        }
+                      else
+                        {
+                          maxPixIdx[1] = pix;
+                          maxPixIdx[0] = swneighbor;
+                          maxDC = dc[1];
+                        }
+                    }	
+                }
+            }
+        }
+    }
+
+    if (maxDC == 0)
+      {
+        *fLog << warn << " No found pixels with maximum dc" << endl;
+	return kFALSE;
+      }
+    
+    maxPix = (*fGeomCam)[maxPixIdx[0]];
+
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << "Star candidate maxDC(" << setw(3) << maxDC << " uA) x position(" << setw(3) << maxPix.GetX() <<  " mm) x position(" << setw(3) << maxPix.GetY() << " mm) swnumber(" << maxPixIdx[0] << ")" << endl;
+
+    return kTRUE;
+}
+
+
+//----------------------------------------------------------------------------
+//
+// FindStar
+//
+//
+//
+
+Bool_t MFindStars::FindStar(MStarPos* star)
+{    
+  UInt_t numPixels = fGeomCam->GetNumPixels();
+  Float_t innerped = fStars->GetInnerPedestalDC();
+  Float_t outerped = fStars->GetOuterPedestalDC();
+
+  TArrayC origPixelsUsed;
+  origPixelsUsed.Set(numPixels);
+  
+  for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+      if (fDisplay.IsUsed(pix))
+        origPixelsUsed[pix]=(Char_t)kTRUE;
+      else
+        origPixelsUsed[pix]=(Char_t)kFALSE;
+    }
+  
+  Float_t expX = star->GetXExp();
+  Float_t expY = star->GetYExp();
+
+  Float_t max         =0;
+  UInt_t  pixmax      =0;
+  Float_t meanX       =0;
+  Float_t meanY       =0;
+  Float_t meanSqX     =0;
+  Float_t meanSqY     =0;
+  Float_t sumCharge   =0;
+  Float_t sumSqCharge =0;
+  UInt_t  usedInnerPx =0;	
+  UInt_t  usedOuterPx =0;	
+  Float_t factor = 1.0;
+
+  Float_t meanXold = 1.e10;
+  Float_t meanYold = 1.e10;
+
+  const Float_t meanPresition = 3.; //[mm]
+  const UInt_t maxNumIterations = 10;
+  UInt_t numIterations = 0;
+
+  //--------------------   start of iteration loop   -----------------------
+  for (UInt_t it=0; it<maxNumIterations; it++)
+  {
+      //rwagner: Need to find px with highest dc and need to assume it is
+      // somewhere near the center of the star
+      //after that we need to REDEFINE our roi! because expected pos could be
+      // quite off that px!
+      
+      // 1.) Initial roi around expected position
+
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	{
+	  
+	  Float_t pixXpos=(*fGeomCam)[pix].GetX();
+	  Float_t pixYpos=(*fGeomCam)[pix].GetY();
+	  Float_t dist = sqrt((pixXpos-expX)*(pixXpos-expX)+
+			      (pixYpos-expY)*(pixYpos-expY));
+	  
+	  if ((dist < fRingInterest) && fDisplay.IsUsed(pix))
+	    fPixelsUsed[pix]=(Char_t)kTRUE;
+	  else
+	    fPixelsUsed[pix]=(Char_t)kFALSE;
+	}
+      fDisplay.SetUsed(fPixelsUsed);
+
+      // 2.) Find px with highest dc in that region
+
+      max    = 0.0;
+      pixmax =   0;
+      for(UInt_t pix=0; pix<numPixels; pix++)	
+	if(fDisplay.IsUsed(pix))
+	  {
+	    Float_t charge  = fDisplay.GetBinContent(pix+1);	      
+	    if (charge>max)
+	      {
+		max=charge;
+		pixmax=pix;
+	      }
+	  }         
+
+      // 3.) make it new center
+
+      expX = (*fGeomCam)[pixmax].GetX();
+      expY = (*fGeomCam)[pixmax].GetY();
+
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	fPixelsUsed[pix]=(Char_t)kTRUE;       
+      fDisplay.SetUsed(fPixelsUsed);
+
+      // First define a area of interest around the expected position of the star
+      for (UInt_t pix=1; pix<numPixels; pix++)
+	{
+	  Float_t pixXpos=(*fGeomCam)[pix].GetX();
+	  Float_t pixYpos=(*fGeomCam)[pix].GetY();
+	  Float_t dist = sqrt((pixXpos-expX)*(pixXpos-expX)+
+			      (pixYpos-expY)*(pixYpos-expY));
+	  
+	  if ((dist < fRingInterest) && fDisplay.IsUsed(pix))
+	    fPixelsUsed[pix]=(Char_t)kTRUE;
+	  else
+	    fPixelsUsed[pix]=(Char_t)kFALSE;
+	}
+  
+      fDisplay.SetUsed(fPixelsUsed);
+    
+      // determine mean x and mean y
+      max         = 0.0;
+      pixmax      =   0;
+      meanX       = 0.0;
+      meanY       = 0.0;
+      meanSqX     = 0.0;
+      meanSqY     = 0.0;
+      sumCharge   = 0.0;
+      sumSqCharge = 0.0;
+      usedInnerPx =   0;	
+      usedOuterPx =   0;	
+
+      for(UInt_t pix=0; pix<numPixels; pix++)
+	{
+	  if(fDisplay.IsUsed(pix))
+	    {
+	      pix>lastInnerPixel?usedOuterPx++:usedInnerPx++;
+	      
+	      Float_t charge  = fDisplay.GetBinContent(pix+1);
+	      Float_t pixXpos = (*fGeomCam)[pix].GetX();
+	      Float_t pixYpos = (*fGeomCam)[pix].GetY();
+	      
+	      if (charge>max)
+		{
+		  max=charge;
+		  pixmax=pix;
+		}
+	      
+	      meanX     += charge*pixXpos;
+	      meanY     += charge*pixYpos;
+	      meanSqX   += charge*pixXpos*pixXpos;
+	      meanSqY   += charge*pixYpos*pixYpos;
+	      sumCharge   += charge;
+	      sumSqCharge += charge*charge;
+	    }
+	} 
+      
+      if (fMinuitPrintOutLevel>=0) *fLog << dbg << " usedInnerPx " << usedInnerPx << " usedOuterPx " << usedOuterPx << endl;
+      
+      meanX   /= sumCharge;
+      meanY   /= sumCharge;
+      meanSqX /= sumCharge;
+      meanSqY /= sumCharge;
+      factor = sqrt( sumSqCharge/(sumCharge*sumCharge) );
+
+      // stop iteration when (meanX, meanY) becomes stable
+      if ( TMath::Abs(meanX-meanXold) < meanPresition  && 
+           TMath::Abs(meanY-meanYold) < meanPresition    )
+        break;
+
+      meanXold = meanX;
+      meanYold = meanY;
+      numIterations++;
+  }
+  // this statement was commented out because the condition 
+  // was never fulfilled :
+  //while(TMath::Abs(meanX-expX) > meanPresition || 
+  //      TMath::Abs(meanY-expY) > meanPresition);
+  //--------------------   end of iteration loop   -----------------------
+
+  if (numIterations >=  maxNumIterations)
+  {
+     *fLog << warn << GetName() << "Mean calculation not converged after " 
+           << maxNumIterations << " iterations" << endl;
+  }
+  
+
+  //Float_t rmsX = (meanSqX - meanX*meanX) - fRingInterest*fRingInterest/12;
+  //Float_t rmsY = (meanSqY - meanY*meanY) - fRingInterest*fRingInterest/12;
+
+  Float_t rmsX = (meanSqX - meanX*meanX);
+  Float_t rmsY = (meanSqY - meanY*meanY);
+  
+  if ( rmsX > 0)
+    rmsX =  TMath::Sqrt(rmsX);
+  else
+    {
+      *fLog << warn << " MFindStars::FindStar negative rmsX² " << rmsX << endl;
+      *fLog << warn << " meanSqX " << meanSqX << " meanX " << meanX << " fRingInterest " << fRingInterest << " sumCharge " << sumCharge << endl;
+      rmsX = 0.;
+    }
+  
+  if ( rmsY > 0)
+    rmsY =  TMath::Sqrt(rmsY);
+  else
+    {
+      *fLog << warn << " MFindStars::FindStar negative rmsY² " << rmsY << endl;
+      *fLog << warn << " meanSqY " << meanSqY << " meanY " << meanY << " fRingInterest " << fRingInterest << " sumCharge " << sumCharge<< endl;
+      rmsY = 0.;
+    }
+  
+  Float_t deltameanX = factor * rmsX;
+  Float_t deltameanY = factor * rmsY;
+
+
+  // Substrack pedestal DC
+  sumCharge-= (usedInnerPx*innerped+usedOuterPx*outerped)/(usedInnerPx+usedOuterPx);
+  max-=pixmax>lastInnerPixel?outerped:innerped;
+  
+  
+  star->SetCalcValues( sumCharge, max, meanX, meanY, rmsX, rmsY,
+                       0.,   deltameanX*deltameanX, 0., deltameanY*deltameanY);
+  
+  if (rmsX <= 0. || rmsY <= 0.)
+    return kFALSE;
+    
+    
+// fit the star spot using TMinuit
+
+    
+    for (UInt_t pix=1; pix<numPixels; pix++)
+      if (fDisplay.IsUsed(pix))
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << "[fit the star spot] fDisplay.IsUsed(" << pix << ") kTRUE" << endl;
+  
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << "fMinDCForStars " << fMinDCForStars << " pixmax>lastInnerPixel?outerped:innerped " << (pixmax>lastInnerPixel?outerped:innerped) << " fMaxNumIntegratedEvents " << fMaxNumIntegratedEvents << endl;
+
+  //Initialize variables for fit
+    fVinit[0] = max;
+    fLimlo[0] = fMinDCForStars-(pixmax>lastInnerPixel?outerped:innerped);
+    fLimup[0] = 30*fMaxNumIntegratedEvents-(pixmax>lastInnerPixel?outerped:innerped);
+    fVinit[1] = meanX;
+    fVinit[2] = rmsX;
+    fVinit[3] = meanY;
+    fVinit[4] = rmsY;
+    //Init steps
+    for(Int_t i=0; i<fNumVar; i++)
+    {
+	if (fVinit[i] != 0)
+	  fStep[i] = TMath::Abs(fVinit[i]/sqrt2);
+        else
+          fStep[i] = 0.1;
+
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fVinit[" << i << "] " << fVinit[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fStep[" << i << "] " << fStep[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fLimlo[" << i << "] " << fLimlo[i];
+        if (fMinuitPrintOutLevel>=0) *fLog << dbg << " fLimup[" << i << "] " << fLimup[i] << endl;
+    }
+
+
+    // -------------------------------------------
+    // call MINUIT
+
+    Double_t arglist[10];
+    Int_t ierflg = 0;
+
+    for (Int_t i=0; i<fNumVar; i++)
+      gMinuit->mnparm(i, fVname[i], fVinit[i], fStep[i], fLimlo[i], fLimup[i], ierflg);
+
+    TStopwatch clock;
+    clock.Start();
+
+// Now ready for minimization step
+    arglist[0] = 500;
+    arglist[1] = 1.;
+    gMinuit->mnexcm(fMethod, arglist ,2,ierflg);
+
+    // call fcn with iflag = 3 
+    //arglist[0] = 3;
+    //Int_t ierflg3;
+    //gMinuit->mnexcm("CALL", arglist, 1, ierflg3);     
+
+    clock.Stop();
+
+    if(fMinuitPrintOutLevel>=0)
+      {
+	if (fMinuitPrintOutLevel>=0) *fLog << dbg << "Time spent for the minimization in MINUIT :   " << endl;;
+	clock.Print();
+      }
+
+
+    //----------  for the uncorrelated Gauss fit (start)   ---------
+    if (!fUseCorrelatedGauss)
+    {
+      Double_t integratedCharge;
+      Double_t maxFit,   maxFitError;
+      Double_t meanXFit, meanXFitError;
+      Double_t sigmaX,   sigmaXError;
+      Double_t meanYFit, meanYFitError;
+      Double_t sigmaY,   sigmaYError;
+      Float_t  chisquare = GetChisquare();
+      Int_t    degrees  = GetDegreesofFreedom()-fNumVar;
+
+      if (!ierflg)
+      {
+        gMinuit->GetParameter(0, maxFit,   maxFitError);
+        gMinuit->GetParameter(1, meanXFit, meanXFitError);
+        gMinuit->GetParameter(2, sigmaX,   sigmaXError);
+        gMinuit->GetParameter(3, meanYFit, meanYFitError);
+        gMinuit->GetParameter(4, sigmaY,   sigmaYError);
+        
+        //FIXME: Do the integral properlly
+        integratedCharge = 0.;
+      }
+      else
+      {
+        maxFit = 0.;
+        meanXFit = 0.;
+        sigmaX = 0.;
+        meanYFit = 0.;
+        sigmaY = 0.;
+        integratedCharge = 0.;
+
+	*fLog << err << "TMinuit::Call error " << ierflg << endl;
+      }
+
+      // get error matrix
+      Double_t matrix[5][5];
+      gMinuit->mnemat(&matrix[0][0],5);
+
+      star->SetFitValues(integratedCharge,maxFit,       meanXFit,    meanYFit,
+                         sigmaX,          sigmaY,       0.0,
+      	          	 matrix[1][1],    matrix[1][3], matrix[3][3],
+                         chisquare,   degrees);
+    }
+    //----------  for the uncorrelated Gauss fit (end)   ---------    
+
+    //----------  for the correlated Gauss fit (start)   ---------
+    if (fUseCorrelatedGauss)
+    {
+      TArrayD fValues(fNumVar);
+      TArrayD fErrors(fNumVar);
+
+      const static Int_t fNdim = 6;
+      Double_t matrix[fNdim][fNdim];
+
+      Double_t fmin   = 0.0;
+      Double_t fedm   = 0.0;
+      Double_t errdef = 0.0;
+      Int_t npari     =   0;
+      Int_t nparx     =   0;
+      Int_t istat     =   0;
+      gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, istat);
+      if (fMinuitPrintOutLevel>=0)
+      { 
+            *fLog << dbg  
+            << "Status of Correlated Gauss fit to the DC currents : " << endl;
+      }
+      if (fMinuitPrintOutLevel>=0) 
+      {
+            *fLog << dbg 
+            << "       fmin, fedm, errdef, npari, nparx, istat = "
+            << fmin << ",  " << fedm << ",  " << errdef << ",  " << npari
+            << ",  " << nparx << ",  " << istat << endl;
+      }
+
+      if (!ierflg)
+      {
+        for (Int_t k=0; k<fNumVar; k++)
+          gMinuit->GetParameter( k, fValues[k], fErrors[k] );
+      }
+      else
+      {
+	*fLog << err << "Correlated Gauss fit failed : ierflg, istat = " 
+              << ierflg << ",  " << istat << endl;
+      }
+
+      Float_t  charge = 0.0;
+      Float_t  chi2   = fmin;
+      Int_t    ndof   = GetDegreesofFreedom()-fNumVar;
+
+      //get error matrix
+      if (istat >= 1)
+      {
+        gMinuit->mnemat( &matrix[0][0], fNdim);
+
+        // copy covariance matrix into a matrix which includes also the fixed
+        // parameters
+        TString  name;
+        Double_t bnd1, bnd2, val, err;
+        Int_t    jvarbl;
+        Int_t    kvarbl;
+        for (Int_t j=0; j<fNumVar; j++)
+        {
+            if (gMinuit)
+                gMinuit->mnpout(j, name, val, err, bnd1, bnd2, jvarbl);
+
+            for (Int_t k=0; k<fNumVar; k++)
+            {
+              if (gMinuit)
+                  gMinuit->mnpout(k, name, val, err, bnd1, bnd2, kvarbl);
+
+              matrix[j][k] = jvarbl==0 || kvarbl==0 ? 0 : matrix[jvarbl-1][kvarbl-1];
+            }
+        }
+      }
+      else
+      {
+        // error matrix was not calculated, construct it
+        if (fMinuitPrintOutLevel>=0)
+	{
+        *fLog << warn 
+              << "error matrix is not defined, construct it" << endl;
+	}
+        for (Int_t j=0; j<fNumVar; j++)
+        {
+          for (Int_t k=0; k<fNumVar; k++)
+              matrix[j][k] = 0;
+
+          matrix[j][j] = fErrors[j]*fErrors[j];
+        }
+      }
+
+      if (fMinuitPrintOutLevel>=0)
+      {
+        *fLog << "Before calling SetFitValues : " << endl; 
+        *fLog << "fValues = " << fValues[0] << ",  " << fValues[1] << ",  "
+              << fValues[2] << ",  " << fValues[3] << ",  " << fValues[4]
+              << ",  " << fValues[5] << endl;
+
+        *fLog << "fErrors = " << fErrors[0] << ",  " << fErrors[1] << ",  "
+              << fErrors[2] << ",  " << fErrors[3] << ",  " << fErrors[4]
+              << ",  " << fErrors[5] << endl;
+
+        *fLog << "error matrix = " << matrix[0][0] << "   " << matrix[0][1]
+                          << "   " << matrix[0][2] << "   " << matrix[0][3]
+                          << "   " << matrix[0][4] << "   " << matrix[0][5]
+              << endl;
+        *fLog << "               " << matrix[1][0] << "   " << matrix[1][1]
+                          << "   " << matrix[1][2] << "   " << matrix[1][3]
+                          << "   " << matrix[1][4] << "   " << matrix[1][5]
+              << endl;
+        *fLog << "               " << matrix[2][0] << "   " << matrix[2][1]
+                          << "   " << matrix[2][2] << "   " << matrix[2][3]
+                          << "   " << matrix[2][4] << "   " << matrix[2][5]
+              << endl;
+        *fLog << "               " << matrix[3][0] << "   " << matrix[3][1]
+                          << "   " << matrix[3][2] << "   " << matrix[3][3]
+                          << "   " << matrix[3][4] << "   " << matrix[3][5]
+              << endl;
+        *fLog << "               " << matrix[4][0] << "   " << matrix[4][1]
+                          << "   " << matrix[4][2] << "   " << matrix[4][3]
+                          << "   " << matrix[4][4] << "   " << matrix[4][5]
+              << endl;
+        *fLog << "               " << matrix[5][0] << "   " << matrix[5][1]
+                          << "   " << matrix[5][2] << "   " << matrix[5][3]
+                          << "   " << matrix[5][4] << "   " << matrix[5][5]
+              << endl;
+      }
+
+      star->SetFitValues(charge,       fValues[0],  fValues[1], fValues[3],
+                         fValues[2],   fValues[4],  fValues[5],
+  	       	         matrix[1][1], matrix[1][3],matrix[3][3],
+                         chi2,         ndof);
+    }
+
+    //----------  for the correlated Gauss fit (end)   ---------    
+
+
+    // reset the display to the starting values
+    fDisplay.SetUsed(origPixelsUsed);
+
+    if (ierflg)
+      return kCONTINUE;
+    return kTRUE;
+}
+
+Bool_t MFindStars::ShadowStar(MStarPos* star)
+{
+    UInt_t numPixels = fGeomCam->GetNumPixels();
+
+// Define an area around the star which will be set unused.
+    UInt_t shadowPx=0;	
+    for (UInt_t pix=1; pix<numPixels; pix++)
+    {
+	Float_t pixXpos  = (*fGeomCam)[pix].GetX();
+	Float_t pixYpos  = (*fGeomCam)[pix].GetY();
+        Float_t starXpos = star->GetMeanX();
+        Float_t starYpos = star->GetMeanY();
+
+        Float_t starSize = 3*sqrt(   star->GetSigmaX()*star->GetSigmaX()
+				   + star->GetSigmaY()*star->GetSigmaY() );
+        
+	Float_t dist = sqrt((pixXpos-starXpos)*(pixXpos-starXpos)+
+			    (pixYpos-starYpos)*(pixYpos-starYpos));
+
+        if (dist > starSize && fDisplay.IsUsed(pix))
+	  fPixelsUsed[pix]=(Char_t)kTRUE;
+        else
+          {
+            fPixelsUsed[pix]=(Char_t)kFALSE;
+            shadowPx++;
+          }
+    }
+
+    if (fMinuitPrintOutLevel>=0) *fLog << dbg << " shadowPx " << shadowPx << endl;
+
+    fDisplay.SetUsed(fPixelsUsed);
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MFindStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MFindStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MFindStars.h	(revision 9772)
@@ -0,0 +1,123 @@
+#ifndef MARS_MFindStars
+#define MARS_MFindStars
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+#ifndef MARS_MAstroCamera
+#include "MAstroCamera.h"
+#endif
+
+class MGeomCam;
+class MGeomPix;
+class MCameraDC;
+class MTime;
+class MReportDrive;
+class MStarCam;
+class MStarPos;
+
+class MFindStars : public MTask
+{
+
+private:
+
+    MGeomCam      *fGeomCam;
+    MCameraDC     *fCurr;
+    MTime         *fTimeCurr;
+    MReportDrive  *fDrive;
+    MStarCam      *fStars;
+
+    MAstroCamera fAstro;
+    TArrayC      fPixelsUsed;
+    MHCamera     fDisplay;
+
+    UInt_t fMaxNumIntegratedEvents;
+    UInt_t fNumIntegratedEvents;
+
+    Float_t fRingInterest; //[mm]
+    Float_t fMinDCForStars; //[uA]
+
+    Float_t fDCTailCut;
+
+    //Fitting(Minuit) variables
+    Int_t fNumVar;
+    Float_t fTempChisquare;
+    Int_t fTempDegreesofFreedom;
+    Int_t fMinuitPrintOutLevel;
+    
+    Bool_t fUseCorrelatedGauss;
+
+    TString *fVname;
+    TArrayD fVinit; 
+    TArrayD fStep; 
+    TArrayD fLimlo; 
+    TArrayD fLimup; 
+    TArrayI fFix;
+    TObject *fObjectFit;
+    TString fMethod;
+    Bool_t fNulloutput;
+    
+    Bool_t DCPedestalCalc();
+    Bool_t FindPixelWithMaxDC(Float_t &maxDC, MGeomPix &maxPix);
+    Bool_t FindStar(MStarPos* star);
+    Bool_t ShadowStar(MStarPos* star);
+
+    TString fGeometryFile;
+    TString fBSCFile;
+
+  public:
+    
+    MFindStars(const char *name=NULL, const char *title=NULL);
+    
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    void SetUseCorrelatedGauss(Bool_t usecorrgauss = kTRUE);
+    Bool_t  GetUseCorrelatedGauss()          {return fUseCorrelatedGauss;}
+
+    // setters
+    void SetNumIntegratedEvents(UInt_t max)  {fMaxNumIntegratedEvents=max;}
+    void SetRingInterest(Float_t ring)       {fRingInterest=ring;}
+    void SetBlindPixels(TArrayS blindpixels);
+    void SetMinuitPrintOutLevel(Int_t level) {fMinuitPrintOutLevel=level;}
+    void SetDCTailCut(Float_t cut)           {fDCTailCut=cut;}
+
+    void SetChisquare(Float_t chi)           {fTempChisquare=chi;}
+    void SetDegreesofFreedom(Int_t free)     {fTempDegreesofFreedom=free;}
+
+    void SetGeometryFile(TString f)          {fGeometryFile=f;}
+    void SetBSCFile(TString f)               {fBSCFile=f;}
+    void SetRaDec(Double_t ra, Double_t dec) {fAstro.SetRaDec(ra,dec);}
+    void SetRaDec(TVector3 &v)               { fAstro.SetRaDec(v); }
+    void SetLimMag(Double_t mag)             { fAstro.SetLimMag(mag); } 
+    void SetRadiusFOV(Double_t deg)          { fAstro.SetRadiusFOV(deg); }
+
+
+    //Getters
+    MHCamera& GetDisplay()           { return fDisplay; }
+    
+    Float_t GetChisquare()           {return fTempChisquare;}
+    Int_t   GetDegreesofFreedom()    {return fTempDegreesofFreedom;}
+    UInt_t  GetNumIntegratedEvents() {return fMaxNumIntegratedEvents;}
+    Float_t GetRingInterest()        {return fRingInterest;}
+    
+  ClassDef(MFindStars, 0) // Tool to find stars from DC Currents
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MHTelAxisFromStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MHTelAxisFromStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MHTelAxisFromStars.cc	(revision 9772)
@@ -0,0 +1,638 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek  07/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHTelAxisFromStars
+//
+// This class contains histograms for MTelAxisFromStars
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHTelAxisFromStars.h"
+
+#include <math.h>
+
+#include <TH1.h>
+#include <TH2.h>
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MBinning.h"
+
+#include "MStarCam.h"
+#include "MStarPos.h"
+#include "MSkyCamTrans.h"
+#include "MSrcPosCam.h"
+
+
+ClassImp(MHTelAxisFromStars);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup the histograms 
+//
+MHTelAxisFromStars::MHTelAxisFromStars(const char *name, const char *title)
+    : fMm2Deg(1), fUseMmScale(kFALSE)
+{
+    fName  = name  ? name  : "MHTelAxisFromStars";
+    fTitle = title ? title : "Plots for MTelAxisFromStars";
+
+    fNStars     = new TH1D("NStars", "No. of stars", 10, -0.5, 9.5);
+    fNStars->SetDirectory(NULL);
+    fNStars->SetXTitle("Numder of stars");    
+    fNStars->SetYTitle("Counts");
+
+    fNdoF     = new TH1D("NdoF", "No. of degrees of freedom", 20, -0.5, 19.5);
+    fNdoF->SetDirectory(NULL);
+    fNdoF->SetXTitle("Numder of degrees of freedom");    
+    fNdoF->SetYTitle("Counts");
+
+    fLog10Chi2 = new TH1D("log10Chi2", "log10Chi2", 60, -10, 5);
+    fLog10Chi2->SetDirectory(NULL);
+    fLog10Chi2->SetXTitle("log10(Chi2)");
+    fLog10Chi2->SetYTitle("Counts");
+
+    fChi2Prob = new TH1D("Chi2-Prob", "Chi2 probability",     40,  0.0,  1.0);
+    fChi2Prob->SetDirectory(NULL);
+    fChi2Prob->SetXTitle("Chi2 probability");
+    fChi2Prob->SetYTitle("Counts");
+
+
+    fNumIter  = new TH1D("NumIter", "Number of iterations",   50, -0.5, 49.5);
+    fNumIter->SetDirectory(NULL);
+    fNumIter->SetXTitle("Number of iterations");
+    fNumIter->SetYTitle("Counts");
+
+
+    fLambda   = new TH1D("Lambda", "Scale factor lambda",     80, 0.90, 1.10);
+    fLambda->SetDirectory(NULL);
+    fLambda->SetXTitle("Scale factor lambda");
+    fLambda->SetYTitle("Counts");
+
+
+    fAlfa     = new TH1D("Alfa", "Rotation angle alfa",      100, -2.5,  2.5);
+    fAlfa->SetDirectory(NULL);
+    fAlfa->SetXTitle("Rotation angle alfa [\\circ]");
+    fAlfa->SetYTitle("Counts");
+
+
+    fShift = new TH2D("Shift", "Sky-Cam transformnation : (x,y) shift", 
+                      72, -534.0707, 534.0707, 72, -534.0707, 534.0707);
+    fShift->SetDirectory(NULL);
+    fShift->SetZTitle("Counts");
+    fShift->SetXTitle("x-shift [\\circ]");
+    fShift->SetYTitle("y-shift [\\circ]");
+
+
+    fEstPos1 = new TH2D("EstPos1", "Estimated position1", 
+                      72, -534.0707, 534.0707, 72, -534.0707, 534.0707);
+    fEstPos1->SetDirectory(NULL);
+    fEstPos1->SetZTitle("Counts");
+    fEstPos1->SetXTitle("Estimated position1    x [\\circ]");
+    fEstPos1->SetYTitle("Estimated position1    y [\\circ]");
+
+    fEstPos2 = new TH2D("EstPos2", "Estimated position2", 
+                      72, -534.0707, 534.0707, 72, -534.0707, 534.0707);
+    fEstPos2->SetDirectory(NULL);
+    fEstPos2->SetZTitle("Counts");
+    fEstPos2->SetXTitle("Estimated position2    x [\\circ]");
+    fEstPos2->SetYTitle("Estimated position2    y [\\circ]");
+
+    fEstPos3 = new TH2D("EstPos3", "Estimated position3", 
+                      72, -534.0707, 534.0707, 72, -534.0707, 534.0707);
+    fEstPos3->SetDirectory(NULL);
+    fEstPos3->SetZTitle("Counts");
+    fEstPos3->SetXTitle("Estimated position3    x [\\circ]");
+    fEstPos3->SetYTitle("Estimated position3    y [\\circ]");
+
+
+    // default input type : results from Gauss fit
+    fInputType = 1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the type of the input
+//
+//     type = 0        calculated star positions (by averaging)
+//     type = 1        fitted star positions (by Gauss fit)
+//
+void MHTelAxisFromStars::SetInputType(Int_t type)
+{
+  *fLog << all << "MHTelAxisFromStars::SetInputType; input type is set equal to : " 
+        << type ;
+
+  if (type == 0)
+    *fLog << " (calculated star positions)" << endl;
+  else
+    *fLog << " (fitted star positions)" << endl;
+
+
+  fInputType = type;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms
+//
+MHTelAxisFromStars::~MHTelAxisFromStars()
+{
+  //*fLog << "MHTelAxisFromStars::Destructor" << endl;
+
+    delete fNStars;
+    delete fNdoF;
+    delete fLog10Chi2;
+    delete fChi2Prob;
+    delete fNumIter;
+    delete fLambda;
+    delete fAlfa;
+
+    delete fShift;
+    delete fEstPos1;
+    delete fEstPos2;
+    delete fEstPos3;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup the Binning for the histograms. 
+//
+// Find the pointers to the containers.
+//
+// Use this function if you want to set the conversion factor which
+// is used to convert the mm-scale in the camera plane into the deg-scale.
+// The conversion factor is part of the camera geometry. Please create a 
+// corresponding MGeomCam container.
+//
+Bool_t MHTelAxisFromStars::SetupFill(const MParList *plist)
+{
+
+   fStarCam = (MStarCam*)plist->FindObject("MStarCam", "MStarCam");
+   if (!fStarCam)
+   {
+       *fLog << err << "MHTelAxisFromStars::SetupFill; container 'MStarCam' not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   
+   fSourceCam = (MStarCam*)plist->FindObject("MSourceCam", "MStarCam");
+   if (!fSourceCam)
+   {
+       *fLog << err << "MHTelAxisFromStars::SetupFill; container 'MSourceCam' not found... " << endl;
+   }
+   
+
+
+    fSrcPos = (MSrcPosCam*)plist->FindObject(AddSerialNumber("MSrcPosCam"));
+    if (!fSrcPos)
+    {
+        *fLog << err << "MHTelAxisFromStars::SetupFill;  MSrcPosCam not found...  aborting" << endl;
+        return kFALSE;
+    }
+
+    fSkyCamTrans = (MSkyCamTrans*)plist->FindObject(AddSerialNumber("MSkyCamTrans"));
+    if (!fSkyCamTrans)
+    {
+        *fLog << err << "MHTelAxisFromStars::SetupFill;  MSkyCamTrans not found...  aborting" << endl;
+        return kFALSE;
+    }
+
+
+   //------------------------------------------------------------------
+    const MGeomCam *geom = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!geom)
+    {
+        *fLog << warn << GetDescriptor() 
+          << ": No Camera Geometry available. Using mm-scale for histograms." 
+          << endl;
+        SetMmScale(kTRUE);
+    }
+    else
+    {
+        fMm2Deg = geom->GetConvMm2Deg();
+        SetMmScale(kFALSE);
+    }
+
+    ApplyBinning(*plist, "NStars",   fNStars);
+    ApplyBinning(*plist, "NdoF",     fNdoF);
+    ApplyBinning(*plist, "Log10Chi2",fLog10Chi2);
+    ApplyBinning(*plist, "Chi2Prob", fChi2Prob);
+    ApplyBinning(*plist, "NumIter",  fNumIter);
+    ApplyBinning(*plist, "Lambda",   fLambda);
+    ApplyBinning(*plist, "Alfa",     fAlfa);
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningCamera");
+    if (!bins)
+    {
+        float r = geom ? geom->GetMaxRadius() : 600;
+        r *= 0.9;
+        if (!fUseMmScale)
+            r *= fMm2Deg;
+
+        MBinning b;
+        b.SetEdges(61, -r, r);
+        SetBinning(fShift,   &b, &b);
+        SetBinning(fEstPos1, &b, &b);
+        SetBinning(fEstPos2, &b, &b);
+        SetBinning(fEstPos3, &b, &b);
+    }
+    else
+    {
+        SetBinning(fShift,   bins, bins);
+        SetBinning(fEstPos1, bins, bins);
+        SetBinning(fEstPos2, bins, bins);
+        SetBinning(fEstPos3, bins, bins);
+    }
+
+    //-------------------------------------------    
+    // copy names from MStarCam to the histograms
+    MStarPos* starpos;
+    Int_t istar = 0;
+    TIter Next(fSourceCam->GetList());
+
+    while ((starpos=(MStarPos*)Next())) {
+      fStarnames[istar] =  starpos->GetName();
+      //*fLog << "istar, star name = " << istar << ",  " 
+      //      << fStarnames[istar] << endl;
+      istar++;
+      if (istar >= fNstarnames) break;
+    }
+
+    if (fSourceCam)
+    {
+      MStarPos *starSource = 0;
+      TIter nextSource(fSourceCam->GetList());
+      while ( (starSource = (MStarPos*)nextSource()) )
+      {
+         if     ( fNstarnames > 0  &&  starSource->GetName() == fStarnames[0] )
+           fEstPos1->SetName(starSource->GetName());
+
+         else if( fNstarnames > 1  &&  starSource->GetName() == fStarnames[1] )
+           fEstPos2->SetName(starSource->GetName());
+
+         else if( fNstarnames > 2  &&  starSource->GetName() == fStarnames[2] )
+           fEstPos3->SetName(starSource->GetName());
+      }
+    }
+    
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Use this function to setup your own conversion factor between degrees
+// and millimeters. The conversion factor should be the one calculated in
+// MGeomCam. Use this function with Caution: You could create wrong values
+// by setting up your own scale factor.
+//
+void MHTelAxisFromStars::SetMm2Deg(Float_t mmdeg)
+{
+    if (mmdeg<0)
+    {
+        *fLog << warn << dbginf 
+              << "Warning - Conversion factor < 0 - nonsense. Ignored." 
+              << endl;
+        return;
+    }
+
+    if (fMm2Deg>=0)
+        *fLog << warn << dbginf 
+              << "Warning - Conversion factor already set. Overwriting" 
+              << endl;
+
+    fMm2Deg = mmdeg;
+}
+
+// --------------------------------------------------------------------------
+//
+// With this function you can convert the histogram ('on the fly') between
+// degrees and millimeters.
+//
+void MHTelAxisFromStars::SetMmScale(Bool_t mmscale)
+{
+    if (fUseMmScale == mmscale)
+        return;
+
+    if (fMm2Deg<0)
+    {
+        *fLog << warn << dbginf 
+         << "Warning - Sorry, no conversion factor for conversion available." 
+         << endl;
+        return;
+    }
+
+    const Double_t scale = mmscale ? 1./fMm2Deg : fMm2Deg;
+    MH::ScaleAxis(fShift,   scale, scale);
+    MH::ScaleAxis(fEstPos1, scale, scale);
+    MH::ScaleAxis(fEstPos2, scale, scale);
+    MH::ScaleAxis(fEstPos3, scale, scale);
+
+    if (mmscale)
+    {
+        fShift->SetXTitle("x-shift [mm]");
+        fShift->SetYTitle("y-shift [mm]");
+
+        fEstPos1->SetXTitle("Estimated position1 x [mm]");
+        fEstPos1->SetYTitle("Estimated position1 y [mm]");
+
+        fEstPos2->SetXTitle("Estimated position2 x [mm]");
+        fEstPos2->SetYTitle("Estimated position2 y [mm]");
+
+        fEstPos3->SetXTitle("Estimated position3 x [mm]");
+        fEstPos3->SetYTitle("Estimated position3 y [mm]");
+    }
+    else
+    {
+        fShift->SetXTitle("x-shift [\\circ]");
+        fShift->SetYTitle("y-shift [\\circ]");
+
+        fEstPos1->SetXTitle("Estimated position1 x [\\circ]");
+        fEstPos1->SetYTitle("Estimated position1 y [\\circ]");
+
+        fEstPos2->SetXTitle("Estimated position2 x [\\circ]");
+        fEstPos2->SetYTitle("Estimated position2 y [\\circ]");
+
+        fEstPos3->SetXTitle("Estimated position3 x [\\circ]");
+        fEstPos3->SetYTitle("Estimated position3 y [\\circ]");
+    }
+
+    fUseMmScale = mmscale;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the histograms 
+// 
+//
+Bool_t MHTelAxisFromStars::Fill(const MParContainer *par, const Stat_t w)
+{
+    Int_t Ndof = fSkyCamTrans->GetNdof();
+    if (Ndof < 0)
+      return kTRUE;
+
+    const Double_t scale = fUseMmScale ? 1 : fMm2Deg;
+
+
+    fNStars   ->Fill(fSkyCamTrans->GetNStars(),               w);
+    fNdoF     ->Fill(fSkyCamTrans->GetNdof(),                 w);
+    if (fSkyCamTrans->GetChiSquare() > 0.0)
+      fLog10Chi2->Fill( log10(fSkyCamTrans->GetChiSquare() ), w);
+    fChi2Prob ->Fill(fSkyCamTrans->GetChiSquareProb(),        w);
+    fNumIter  ->Fill(fSkyCamTrans->GetNumIter(),              w);
+    fLambda   ->Fill(fSkyCamTrans->GetLambda(),               w);
+    fAlfa     ->Fill(fSkyCamTrans->GetAlfa(),                 w);
+
+
+    Double_t lowx;
+    Double_t higx;
+    Double_t lowy;
+    Double_t higy;
+    Double_t x;
+    Double_t y;
+    Int_t    nbix;
+    Int_t    nbiy;
+
+    nbix = fShift->GetXaxis()->GetNbins();
+    lowx = fShift->GetXaxis()->GetBinLowEdge(1);
+    higx = fShift->GetXaxis()->GetBinLowEdge(nbix+1);
+
+    nbiy = fShift->GetYaxis()->GetNbins();
+    lowy = fShift->GetYaxis()->GetBinLowEdge(1);
+    higy = fShift->GetYaxis()->GetBinLowEdge(nbiy+1);
+
+    x = scale * (fSkyCamTrans->GetShiftD())[0];
+    y = scale * (fSkyCamTrans->GetShiftD())[1];
+    if (x>lowx  && x<higx  && y>lowy  && y<higy)
+    {
+      fShift    ->Fill(x, y, w);
+    }
+
+    if (fSourceCam)
+    {
+      MStarPos *starSource = 0;
+      TIter nextSource(fSourceCam->GetList());
+
+      while( (starSource = (MStarPos*)nextSource()) )
+      {
+        if (fInputType == 1)
+        {
+          x = scale * starSource->GetMeanXFit(); 
+          y = scale * starSource->GetMeanYFit(); 
+        }
+        else 
+        {
+          x = scale * starSource->GetMeanXCalc(); 
+          y = scale * starSource->GetMeanYCalc(); 
+        }
+
+	if (x>lowx  && x<higx  && y>lowy  && y<higy)
+        {
+         if     ( fNstarnames > 0  &&  starSource->GetName() == fStarnames[0] )
+           fEstPos1->Fill(x, y, w);
+
+         else if( fNstarnames > 1  &&  starSource->GetName() == fStarnames[1] )
+           fEstPos2->Fill(x, y, w);
+
+         else if( fNstarnames > 2  &&  starSource->GetName() == fStarnames[2] )
+           fEstPos3->Fill(x, y, w);
+	}
+      }
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Finalize :
+//
+//    it is called in the postprocessing
+//    reset pointers in order to allow cloning of the object
+//
+Bool_t MHTelAxisFromStars::Finalize()
+{
+  //*fLog << "MHTelAxisFromStars::Finalize;  fSourceCam = " 
+  //      << fSourceCam  << endl; 
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Creates a new canvas and draws the histograms.
+// Be careful: The histograms belongs to this object and won't get deleted
+// together with the canvas.
+//
+
+void MHTelAxisFromStars::Draw(Option_t *opt)
+{
+  TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+  pad->SetBorderMode(0);
+
+  AppendPad("");
+  
+  //TCanvas *pad = new TCanvas("TelAxisFromStars", "TelAxis plots", 1200, 900);
+  //gROOT->SetSelectedPad(NULL);
+
+    pad->Divide(4,3);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fNStars->Draw(opt); 
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fNdoF->Draw(opt); 
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fLog10Chi2->Draw(opt); 
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fChi2Prob->Draw(opt); 
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    fNumIter->Draw(opt);
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    fLambda->Draw(opt);
+
+    pad->cd(7);
+    gPad->SetBorderMode(0);
+    fAlfa->Draw(opt);
+
+    pad->cd(8);
+    gPad->SetBorderMode(0);
+    //SetColors();
+    //fShift->Draw("colz");
+    fShift->Draw("");
+
+
+    //-----------------------------------------------
+    // plot the expected positions of some sources
+    //*fLog << "fSourcsCam = " << fSourceCam << endl;
+
+    if (fSourceCam)
+    {
+      *fLog << "MHTelAxisFromSrars::Draw; plotting" << endl;
+
+      pad->cd(9);
+      gPad->SetBorderMode(0);
+      //SetColors();
+      fEstPos1->Draw("");
+
+      pad->cd(10);
+      gPad->SetBorderMode(0);
+      //SetColors();
+      fEstPos2->Draw("");
+
+      pad->cd(11);
+      gPad->SetBorderMode(0);
+      //SetColors();
+      fEstPos3->Draw("");
+    }
+
+    pad->Modified();
+    pad->Update();
+}
+
+//---------------------------------------------------------------------
+//
+
+TH1 *MHTelAxisFromStars::GetHistByName(const TString name)
+{
+    if (name.Contains("NStars", TString::kIgnoreCase))
+        return fNStars;
+    if (name.Contains("NdoF", TString::kIgnoreCase))
+        return fNdoF;
+    if (name.Contains("Log10Chi2", TString::kIgnoreCase))
+        return fLog10Chi2;
+    if (name.Contains("Chi2Prob", TString::kIgnoreCase))
+        return fChi2Prob;
+    if (name.Contains("NumIter", TString::kIgnoreCase))
+        return fNumIter;
+    if (name.Contains("Lambda", TString::kIgnoreCase))
+        return fLambda;
+    if (name.Contains("Alfa", TString::kIgnoreCase))
+        return fAlfa;
+
+    if (name.Contains("Shift", TString::kIgnoreCase))
+        return fShift;
+    if (name.Contains("EstPos1", TString::kIgnoreCase))
+        return fEstPos1;
+    if (name.Contains("EstPos2", TString::kIgnoreCase))
+        return fEstPos2;
+    if (name.Contains("EstPos3", TString::kIgnoreCase))
+        return fEstPos3;
+
+    return NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Setup an inversed deep blue sea palette.
+//
+
+void MHTelAxisFromStars::SetColors() const
+{
+    gStyle->SetPalette(51, NULL);
+    Int_t c[50];
+    for (int i=0; i<50; i++)
+        c[49-i] = gStyle->GetColorPalette(i);
+    gStyle->SetPalette(50, c);
+}
+
+
+//---------------------------------------------------------------------
+//
+
+void MHTelAxisFromStars::Paint(Option_t *opt)
+{
+    SetColors();
+    MH::Paint();
+}
+
+//==========================================================================
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MHTelAxisFromStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MHTelAxisFromStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MHTelAxisFromStars.h	(revision 9772)
@@ -0,0 +1,86 @@
+#ifndef MARS_MHTelAxisFromStars
+#define MARS_MHTelAxisFromStars
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TH2D;
+class MTelAxisFromStars;
+class MSrcPosCam;
+class MSkyCamTrans;
+class MStarCam;
+
+class MHTelAxisFromStars : public MH
+{
+private:
+
+    TH1D *fNStars;     //-> Number of stars
+    TH1D *fNdoF;       //-> Number of degrees of freedom
+    TH1D *fLog10Chi2;  //-> log10(Chi2) 
+    TH1D *fChi2Prob;   //-> Chi2 probability
+    TH1D *fNumIter;    //-> Number of iterations
+    TH1D *fLambda;     //-> Scale factor lambda
+    TH1D *fAlfa;       //-> Rotation angle alfa
+
+    TH2D *fShift;      //-> Shift between Sky and Camera system
+    TH2D *fEstPos1;    //-> Estimated position 1
+    TH2D *fEstPos2;    //-> Estimated position 2
+    TH2D *fEstPos3;    //-> Estimated position 3
+
+    MStarCam        *fStarCam;     //!
+    MStarCam        *fSourceCam;   
+    MSrcPosCam      *fSrcPos;      //!
+    MSkyCamTrans    *fSkyCamTrans; //!
+
+    Float_t fMm2Deg;                    //!
+    Bool_t  fUseMmScale;                //!
+    Int_t   fInputType;                 //!
+
+    const static Int_t fNstarnames = 3;        //!
+    TString fStarnames[fNstarnames];    //!
+
+    void SetColors() const;
+    void Paint(Option_t *opt="");
+
+public:
+    MHTelAxisFromStars(const char *name=NULL, const char *title=NULL);
+    ~MHTelAxisFromStars();
+
+    void SetInputType(Int_t type=1);
+    void SetMmScale(Bool_t mmscale=kTRUE);
+    virtual void SetMm2Deg(Float_t mmdeg);
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+    TH1 *GetHistByName(const TString name);
+
+    TH1D *GetHistNStars()    { return fNStars;    }
+    TH1D *GetHistNdoF()      { return fNdoF;      }
+    TH1D *GetHistLog10Chi2() { return fLog10Chi2; }
+    TH1D *GetHistChi2Prob()  { return fChi2Prob;  }
+
+    TH1D *GetHistNumIter()   { return fNumIter;   }
+    TH1D *GetHistLambda()    { return fLambda;    } 
+
+    TH1D *GetHistAlfa()      { return fAlfa;      }
+
+    TH2D *GetHistShift()     { return fShift;     }
+    TH2D *GetHistEstPos1()   { return fEstPos1;   }
+    TH2D *GetHistEstPos2()   { return fEstPos2;   }
+    TH2D *GetHistEstPos3()   { return fEstPos3;   }
+
+    void Draw(Option_t *opt=NULL);
+
+    ClassDef(MHTelAxisFromStars, 1) // Container which holds histograms for MTelAxisFromStars
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSkyCamTrans.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSkyCamTrans.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSkyCamTrans.cc	(revision 9772)
@@ -0,0 +1,118 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek , 7/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// MSkyCamTrans
+//
+//     container holding the parameters of the transformation from
+//     sky directions 'a' (projected onto the camera) 
+//     to positions 'b' in the camera
+//
+//                                          ( cos(fAlfa)   -sin(fAlfa) )
+//      b = fLambda * fA * a + fD      fA = (                        )
+//             ^       ^        ^           ( sin(fAlfa)    cos(fAlfa) )
+//             |       |        |
+//           scale  rotation  shift 
+//          factor  matrix
+//
+//     fNumIter             number of iterations
+//     fNdof                number of degrees of freedom
+//     fChiSquare           chi-square value
+//     fChiSquareProb       chi-square probability
+//
+// The units are assumed to be 
+//     [degrees]  for  fAlfa
+//     [mm]       for  a, b, fD
+//     [1]        for  fLambda                       
+//
+//
+// The container is filled by  the task 'MTelAxisFromStars' 
+//
+///////////////////////////////////////////////////////////////////////////
+
+
+#include "MSkyCamTrans.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MSkyCamTrans);
+
+using namespace std;
+
+// ---------------------------------------------------------------------
+//
+//
+//
+MSkyCamTrans::MSkyCamTrans(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MSkyCamTrans";
+    fTitle = title ? title : "Sky-Cam transformation parameters";
+}
+
+// ---------------------------------------------------------------------
+//
+//
+//
+void MSkyCamTrans::SetParameters(Double_t &lambda, Double_t &alfa, 
+     Double_t a[2][2], Double_t d[2],  Double_t errd[2][2], 
+     Int_t &nstars,    Int_t &numiter,  
+     Int_t &ndof,      Double_t &chisquare,        Double_t &chisquareprob)
+{
+  fLambda = lambda;
+  fAlfa   = alfa;
+    
+  fA[0][0] = a[0][0];
+  fA[0][1] = a[0][1];
+  fA[1][0] = a[1][0];
+  fA[1][1] = a[1][1];
+
+  fD[0] = d[0];
+  fD[1] = d[1];
+
+  fErrD[0][0] = errd[0][0];
+  fErrD[0][1] = errd[0][1];
+  fErrD[1][0] = errd[1][0];
+  fErrD[1][1] = errd[1][1];
+
+  fNStars        = nstars;
+  fNumIter       = numiter;
+  fNdof          = ndof;
+  fChiSquare     = chisquare;
+  fChiSquareProb = chisquareprob;
+}
+// ---------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSkyCamTrans.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSkyCamTrans.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSkyCamTrans.h	(revision 9772)
@@ -0,0 +1,55 @@
+#ifndef MARS_MSkyCamTrans
+#define MARS_MSkyCamTrans
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MSkyCamTrans : public MParContainer
+{
+private:
+
+    //Parameters of transformation from sky to camera
+    
+    Double_t fLambda;         // scale factor lambda
+    Double_t fAlfa;           // rotation angle alfa [degrees]
+    Double_t fA[2][2];        // rotation matrix A
+    Double_t fD[2];           // shift D [mm]
+    Double_t fErrD[2][2];     // error matrix of shift D   [mm*mm]
+
+    Int_t    fNStars;
+    Int_t    fNumIter;
+    Int_t    fNdof;
+    Double_t fChiSquare;
+    Double_t fChiSquareProb;
+
+public:
+
+    MSkyCamTrans(const char *name=NULL, const char *title=NULL);
+
+    void SetParameters(Double_t &,       Double_t &,
+		       Double_t[2][2],   Double_t[2], Double_t[2][2], 
+              Int_t &, Int_t &, Int_t &, Double_t &,  Double_t &);
+ 
+    Int_t    GetNStars()             { return fNStars;       }
+    Int_t    GetNumIter()            { return fNumIter;       }
+    Int_t    GetNdof()               { return fNdof;          }
+    Double_t GetChiSquare()          { return fChiSquare;     }
+    Double_t GetChiSquareProb()      { return fChiSquareProb; }
+    Double_t GetLambda()             { return fLambda;        }
+    Double_t GetAlfa()               { return fAlfa;          }
+
+    Double_t *GetRotationMatrix()    { return &fA[0][0];      }  
+    Double_t *GetShiftD()            { return &fD[0];         }  
+    Double_t *GetErrMatrixShiftD()   { return &fErrD[0][0];   }  
+
+    ClassDef(MSkyCamTrans, 1) // Container holding the sky-camera transformation parameters
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSourceDirections.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSourceDirections.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSourceDirections.cc	(revision 9772)
@@ -0,0 +1,190 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!   Author(s): Robert Wagner, 8/2004 <mailto:rwagner@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MSourceDirections
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MSourceDirections.h"
+
+#include <TTimer.h>
+#include <TString.h>
+#include <TFile.h>
+#include <TTree.h>
+#include <TCanvas.h>
+#include <TH1F.h>
+#include <TF1.h>
+#include <TEllipse.h>
+
+
+#include "MObservatory.h"
+#include "MAstroCamera.h"
+#include "MMcConfigRunHeader.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MCameraDC.h"
+#include "MTime.h"
+#include "MReportDrive.h"
+#include "MStarCam.h"
+#include "MStarPos.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+ClassImp(MSourceDirections);
+using namespace std;
+
+MSourceDirections::MSourceDirections(const char *name, const char *title): 
+  fGeomCam(NULL), fTimeCurr(NULL), fDrive(NULL), fStars(NULL)
+{
+  fName  = name  ? name  : "MSourceDirections";
+  fTitle = title ? title : "Convert Ra-Dec source positions into camera coordinates";
+  fGeometryFile="";
+}
+
+Int_t MSourceDirections::PreProcess(MParList *pList)
+{
+  fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+  if (!fGeomCam) {
+    *fLog << err << AddSerialNumber("MGeomCam") << " not found ... aborting" << endl;
+    return kFALSE;
+  }
+  
+  fTimeCurr = (MTime*)pList->FindObject(AddSerialNumber("MTimeCurrents"));
+  if (!fTimeCurr) {
+    *fLog << err << AddSerialNumber("MTimeCurrents") << " not found ... aborting" << endl;
+    return kFALSE;
+  }
+
+  fDrive = (MReportDrive*)pList->FindObject(AddSerialNumber("MReportDrive"));
+  if (!fDrive) {
+    *fLog << warn << AddSerialNumber("MReportDrive") << " not found ... aborting" << endl;
+    return kFALSE;
+  } 
+
+
+  fStars = (MStarCam*)pList->FindCreateObj(AddSerialNumber("MStarCam"),"MSourceCam");
+  if (!fStars) {
+    *fLog << err << AddSerialNumber("MStarCam") << " with name '"
+          << "MSourceCam" << " cannot be created ... aborting" << endl;
+    return kFALSE;
+  }
+  
+
+
+  MObservatory magic1;
+  
+  MMcConfigRunHeader *config=0;
+  MGeomCam           *geom=0;
+  
+  TFile file(fGeometryFile);
+  //TTree *tree = (TTree*)file.Get("RunHeaders");
+  TTree *tree = dynamic_cast<TTree*>(file.Get("RunHeaders"));
+  tree->SetBranchAddress("MMcConfigRunHeader.", &config);
+  if (tree->GetBranch("MGeomCam.")) tree->SetBranchAddress("MGeomCam.", &geom);
+  tree->GetEntry(0);
+  
+  fAstro.SetMirrors(*config->GetMirrors());
+  fAstro.SetGeom(*geom);	
+  fAstro.SetObservatory(magic1);  
+
+
+  // make the starlist available already in the preprocessing
+  fStars->GetList()->Delete();
+  fAstro.SetTime(*fTimeCurr);
+  fAstro.SetGuiActive();
+  fAstro.FillStarList(fStars->GetList());      
+  //*fLog << inf << "in preprocessing " << GetName() << " found " 
+  //      << fStars->GetList()->GetSize() 
+  //	  << " directions inside the chosen FOV." << endl;          
+
+
+  return kTRUE;
+}
+
+Int_t MSourceDirections::AddDirection(Float_t ra, Float_t dec, Float_t mag, TString name) 
+{
+  *fLog << "MSourceDirections::AddDirection; add the direction : ra, dec, mag, name = " 
+        << ra << ",  " << dec << ",  " << mag << ",  " << name << endl;
+
+  Int_t rc = fAstro.AddObject(ra,dec,1,name);
+//   if (rc) {
+//     MStarPos *starpos = new MStarPos;
+//     starpos->SetName(name);
+//     fStars->GetList()->Add(starpos);
+//   }
+  return rc;
+}
+
+Int_t MSourceDirections::Process()
+{
+  //First delete the previous directions in the list
+  fStars->GetList()->Delete();
+
+  fAstro.SetTime(*fTimeCurr);
+  fAstro.SetGuiActive();
+  fAstro.FillStarList(fStars->GetList());      
+      
+  MStarPos* starpos;
+  TIter Next(fStars->GetList());
+  while ((starpos=(MStarPos*)Next())) {
+    //starpos->SetCalcValues(40,40,starpos->GetXExp(),starpos->GetYExp(),
+    //                       0.,0.,0.,    0.,0.,0.);
+    //starpos->SetFitValues (40,40,starpos->GetXExp(),starpos->GetYExp(),
+    //                       0.,0.,0.,    0.,0.,0.,  0., -1);
+  }
+
+  if (fStars->GetList()->GetSize() == 0) {
+    *fLog << err << GetName() << "No directions inside the chosen FOV." << endl;
+  } 
+  else {
+      *fLog << inf << GetName() << " found " << fStars->GetList()->GetSize() 
+	    << " directions inside the chosen FOV." << endl;          
+  }
+  return kTRUE;
+}
+
+Int_t MSourceDirections::PostProcess()
+{
+  return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSourceDirections.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSourceDirections.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MSourceDirections.h	(revision 9772)
@@ -0,0 +1,49 @@
+#ifndef MARS_MSourceDirections
+#define MARS_MSourceDirections
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MAstroCamera
+#include "MAstroCamera.h"
+#endif
+
+class MTime;
+class MReportDrive;
+class MStarCam;
+class MStarPos;
+
+class MSourceDirections : public MTask
+{
+
+private:
+
+    MGeomCam      *fGeomCam;
+    MTime         *fTimeCurr;
+    MReportDrive  *fDrive;
+    MStarCam *fStars;
+
+    MAstroCamera fAstro;
+  
+    TString fGeometryFile;
+
+  public:
+    
+    MSourceDirections(const char *name=NULL, const char *title=NULL);
+    
+    Int_t AddDirection(Float_t ra, Float_t dec, Float_t mag, TString name="");
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    // setters
+    void SetGeometryFile(TString f) {fGeometryFile=f;}
+    void SetRaDec(Double_t ra, Double_t dec) {fAstro.SetRaDec(ra,dec);}
+    void SetRaDec(TVector3 &v) { fAstro.SetRaDec(v); }
+    void SetRadiusFOV(Double_t deg) { fAstro.SetRadiusFOV(deg); }
+    
+  ClassDef(MSourceDirections, 0) // Tool to translate RaDec Source Directions into camera coordinates
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalCam.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalCam.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalCam.cc	(revision 9772)
@@ -0,0 +1,111 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier Lopez 04/2004 <mailto:jlopez@ifae.es>
+!   Author(s): Jordi Albert 04/2004 <mailto:albert@astro.uni-wuerzburg.de>
+!                 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MStarLocalCam
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MStarLocalCam.h"
+
+#include <TList.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MStarLocalPos.h"
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+// Default constructor. 
+//
+//
+MStarLocalCam::MStarLocalCam(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MStarLocalCam";
+  fTitle = title ? title : "";
+  
+  fStars = new TList;
+
+  fInnerPedestalDC = 0.;
+  fOuterPedestalDC = 0.;
+  fInnerPedestalRMSDC = 0.;
+  fOuterPedestalRMSDC = 0.;
+  
+}
+
+MStarLocalCam::~MStarLocalCam()
+{
+    fStars->SetOwner();
+    fStars->Delete();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+MStarLocalPos &MStarLocalCam::operator[] (Int_t i)
+{
+  MStarLocalPos& star = *static_cast<MStarLocalPos*>(fStars->At(i));
+  return star;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th
+//
+const MStarLocalPos &MStarLocalCam::operator[] (Int_t i) const
+{
+    return *static_cast<MStarLocalPos*>(fStars->At(i));
+}
+
+void MStarLocalCam::Paint(Option_t *o)
+{
+	TIter Next(fStars);
+	MStarLocalPos* star;
+	while ((star=(MStarLocalPos*)Next())) 
+	    star->Paint(o);
+}
+
+void MStarLocalCam::Print(Option_t *o) const
+{
+      *fLog << inf << "DCs baseline:" << endl;
+      *fLog << inf << " Inner Pixels Mean pedestal \t" << setw(4) << fInnerPedestalDC << " uA  and RMS " << setw(4) << fInnerPedestalRMSDC << " uA for DCs" << endl;
+      *fLog << inf << " Outer Pixels Mean pedestal \t" << setw(4) << fOuterPedestalDC << " uA  and RMS " << setw(4) << fOuterPedestalRMSDC << " uA for DCs" << endl;
+      
+      TIter Next(fStars);
+      MStarLocalPos* star;
+      UInt_t starnum = 0;
+      while ((star=(MStarLocalPos*)Next())) 
+        {
+          *fLog << inf << "Star[" << starnum << "] info:" << endl;
+          star->Print(o);
+          starnum++;
+        }
+}
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalCam.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalCam.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalCam.h	(revision 9772)
@@ -0,0 +1,64 @@
+#ifndef MARS_MStarLocalCam
+#define MARS_MStarLocalCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef MARS_MHCamera
+#include "MHCamera.h"
+#endif
+
+class TList;
+
+class MGeomCam;
+class MStarLocalPos;
+
+class MStarLocalCam : public MParContainer
+{
+private:
+
+  TList  *fStars;  //-> FIXME: Change TClonesArray away from a pointer?
+
+  // BaseLine DCs info
+  Float_t fInnerPedestalDC;         //[ua]
+  Float_t fOuterPedestalDC;         //[ua]
+
+  Float_t fInnerPedestalRMSDC;      //[ua]
+  Float_t fOuterPedestalRMSDC;      //[ua]
+
+  MHCamera fDisplay;
+
+ public:
+
+  MStarLocalCam(const char *name=NULL, const char *title=NULL);
+  ~MStarLocalCam();
+
+  MStarLocalPos &operator[] (Int_t i);
+  const MStarLocalPos &operator[] (Int_t i) const;
+
+  TList *GetList() const { return fStars; }
+  UInt_t GetNumStars() const { return fStars->GetSize(); }
+
+  //Getters
+
+  Float_t GetInnerPedestalDC() {return fInnerPedestalDC;}
+  Float_t GetOuterPedestalDC() {return fOuterPedestalDC;}
+  Float_t GetInnerPedestalRMSDC() { return fInnerPedestalRMSDC;}
+  Float_t GetOuterPedestalRMSDC() { return fOuterPedestalRMSDC;}
+
+  MHCamera& GetDisplay() { return fDisplay; }
+
+    //Setters
+  void SetInnerPedestalDC(Float_t ped) {fInnerPedestalDC = ped;}
+  void SetOuterPedestalDC(Float_t ped) {fOuterPedestalDC = ped;}
+  void SetInnerPedestalRMSDC(Float_t rms){fInnerPedestalRMSDC = rms;}
+  void SetOuterPedestalRMSDC(Float_t rms){fOuterPedestalRMSDC = rms;}
+
+  void Paint(Option_t *o=NULL);
+  void Print(Option_t *o=NULL) const;
+
+  ClassDef(MStarLocalCam, 1)	// Storage Container for star positions in the camera
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalPos.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalPos.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalPos.cc	(revision 9772)
@@ -0,0 +1,309 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without expressed
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López ,   4/2004 <mailto:jlopez@ifae.es>
+!              Robert Wagner,   7/2004 <mailto:rwagner@mppmu.mpg.de>
+!              Wolfgang Wittek, 8/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+#include "MStarLocalPos.h"
+
+#include <TEllipse.h>
+#include <TMarker.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MStarLocalPos);
+
+using namespace std;
+
+MStarLocalPos::MStarLocalPos(const char *name, const char *title)
+{
+
+    fName  = name  ? name  : "MStarLocalPos";
+    fTitle = title ? title : "";
+    
+    Reset();
+}
+
+void MStarLocalPos::Reset()
+{
+
+    //Expected position on camera
+     fMagExp = 0.;
+     fXExp = 0.;
+     fYExp = 0.;
+
+    //Info from calculation
+     fMagCalc = 0.;
+     fMaxCalc = 0.;
+     fMeanXCalc = 0.;
+     fMeanYCalc = 0.;
+     fSigmaMinorAxisCalc = 0.;
+     fSigmaMajorAxisCalc = 0.;
+
+    //Info from uncorrelated Gauss fit
+     fMagFit = 0.;
+     fMaxFit = 0.;
+     fMeanXFit = 0.;
+     fMeanYFit = 0.;
+     fSigmaMinorAxisFit = 0.;
+     fSigmaMajorAxisFit = 0.;
+
+     fChiSquare = 0.;
+     fNdof = 1;
+
+    //Info from correlated Gauss fit
+     fMagCGFit    = 0.;
+     fMaxCGFit    = 0.;
+     fMeanXCGFit  = 0.;
+     fMeanYCGFit  = 0.;
+     fSigmaXCGFit = 0.;
+     fSigmaYCGFit = 0.;
+     fCorrXYCGFit = 0.;
+     fXXErrCGFit  = 0.;
+     fXYErrCGFit  = 0.;
+     fYYErrCGFit  = 0.;
+
+     fChiSquareCGFit = 0.;
+     fNdofCGFit      = 1;
+
+}
+
+void MStarLocalPos::SetExpValues(Float_t mag, Float_t x, Float_t y)
+{
+     fMagExp = mag;
+     fXExp = x;
+     fYExp = y;
+}
+
+void MStarLocalPos::SetIdealValues(Float_t mag, Float_t x, Float_t y)
+{
+     fMagIdeal = mag;
+     fXIdeal = x;
+     fYIdeal = y;
+}
+
+void MStarLocalPos::SetCalcValues(Float_t mag, Float_t max, 
+        Float_t x, Float_t y, Float_t sigmaMinorAxis, Float_t sigmaMajorAxis)
+{
+     fMagCalc = mag;
+     fMaxCalc = max;
+     fMeanXCalc = x;
+     fMeanYCalc = y;
+     fSigmaMinorAxisCalc = sigmaMinorAxis;
+     fSigmaMajorAxisCalc = sigmaMajorAxis;
+}
+
+void MStarLocalPos::SetFitValues(Float_t mag, Float_t max, 
+        Float_t x, Float_t y, Float_t sigmaMinorAxis, Float_t sigmaMajorAxis, 
+        Float_t chiSquare, Int_t ndof)
+{
+     fMagFit = mag;
+     fMaxFit = max;
+     fMeanXFit = x;
+     fMeanYFit = y;
+     fSigmaMinorAxisFit = sigmaMinorAxis;
+     fSigmaMajorAxisFit = sigmaMajorAxis;
+     fChiSquare = chiSquare;
+     fNdof = ndof;
+}
+
+void MStarLocalPos::SetFitValues(Float_t mag, Float_t max, 
+        Float_t x, Float_t y, Float_t sigmaMinorAxis, Float_t sigmaMajorAxis, 
+        Float_t chiSquare, Int_t ndof, 
+        Float_t xx, Float_t xy, Float_t yy)
+{
+  SetFitValues(mag, max, x, y, sigmaMinorAxis, sigmaMajorAxis, chiSquare, ndof);
+  fXXErr = xx;
+  fYYErr = yy;
+  fXYErr = xy;
+}
+
+void MStarLocalPos::SetCGFitValues(
+               Float_t mag,       Float_t max,    Float_t x,    Float_t y, 
+               Float_t sigmaX,    Float_t sigmaY, Float_t correlation, 
+               Float_t xx,        Float_t xy,     Float_t yy,
+               Float_t chiSquare, Int_t ndof)
+{
+     fMagCGFit    = mag;
+     fMaxCGFit    = max;
+     fMeanXCGFit  = x;
+     fMeanYCGFit  = y;
+     fSigmaXCGFit = sigmaX;
+     fSigmaYCGFit = sigmaY;
+     fCorrXYCGFit = correlation;
+     fXXErrCGFit  = xx;
+     fXYErrCGFit  = xy;
+     fYYErrCGFit  = yy;
+
+     fChiSquareCGFit = chiSquare;
+     fNdofCGFit      = ndof;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Paint the ellipse corresponding to the parameters
+//
+void MStarLocalPos::Paint(Option_t *opt)
+{
+  //Print a cross in the expected position
+  TMarker mexp(fXExp, fYExp, 29);
+  mexp.SetMarkerSize(3);
+  mexp.SetMarkerColor(94);
+  mexp.Paint(); 
+
+  if (fSigmaMinorAxisCalc>0. && fSigmaMajorAxisCalc>0.)
+    {
+      TEllipse ecalc(fMeanXCalc, fMeanYCalc, fSigmaMinorAxisCalc, fSigmaMajorAxisCalc, 0, 360, 0);
+      ecalc.SetLineWidth(3);
+      ecalc.SetLineColor(kBlue);
+      ecalc.Paint();
+    }
+
+  if (fSigmaMinorAxisFit>0. && fSigmaMajorAxisFit>0.)
+    {
+      TEllipse efit(fMeanXFit, fMeanYFit, fSigmaMinorAxisFit, fSigmaMajorAxisFit, 0, 360, 0);
+      efit.SetLineWidth(3);
+      efit.SetLineColor(kBlack);
+      efit.Paint();
+    }
+
+  if (fSigmaXCGFit>0. && fSigmaYCGFit>0.)
+    {
+      //Print a cross in the fitted position
+      //TMarker mCGFit(fMeanXCGFit, fMeanYCGFit, 3);
+      //mCGFit.SetMarkerSize(3);
+      //mCGFit.SetMarkerColor(1);
+      //mCGFit.Paint(); 
+
+      Double_t cxx = fSigmaXCGFit*fSigmaXCGFit;
+      Double_t cyy = fSigmaYCGFit*fSigmaYCGFit;
+      Double_t d   = cyy - cxx;
+      Double_t cxy = fCorrXYCGFit * fSigmaXCGFit * fSigmaYCGFit;
+      Double_t tandel;
+      if (cxy != 0.0)
+        tandel = ( d + sqrt(d*d + 4.0*cxy*cxy) ) / (2.0*cxy); 
+      else
+        tandel = 0.0;
+
+      Double_t sindel = tandel / sqrt(1.0 + tandel*tandel);
+      Double_t delta = TMath::ASin(sindel);
+
+      Double_t major =   (cxx + 2.0*tandel*cxy + tandel*tandel*cyy)
+	                / (1.0 + tandel*tandel);  
+
+      Double_t minor =   (tandel*tandel*cxx - 2.0*tandel*cxy + cyy)
+	                / (1.0 + tandel*tandel);  
+
+      TEllipse efit(fMeanXCGFit, fMeanYCGFit, sqrt(major), sqrt(minor), 
+                    0, 360,      delta*kRad2Deg);
+      efit.SetLineWidth(3);
+      efit.SetLineColor(kMagenta);
+      efit.Paint();
+    }
+}
+  
+void MStarLocalPos::Print(Option_t *opt) const
+{
+  TString o = opt;
+
+  if (o.Contains("name", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Name: \"" << this->GetName() << "\"" << endl;
+    }
+      
+  if (o.Contains("mag", TString::kIgnoreCase) || opt == NULL)
+    {
+  
+      *fLog << inf << "Star magnitude:" << endl;
+      *fLog << inf << " Expected \t" << setw(4) << fMagExp << endl;
+      *fLog << inf << " Calcultated \t " << setw(4) << fMagCalc << endl;
+      *fLog << inf << " Fitted \t " << setw(4) << fMagFit << endl;
+      *fLog << inf << " CGFitted \t " << setw(4) << fMagCGFit << endl;
+    }
+  
+  if (o.Contains("max", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Maximum:" << endl;
+      *fLog << inf << " Calcultated \t " << setw(4) << fMaxCalc << " uA" 
+            << endl;
+      *fLog << inf << " Fitted \t " << setw(4) << fMaxFit << " uA" << endl;
+      *fLog << inf << " CGFitted \t " << setw(4) << fMaxCGFit << " uA" << endl;
+    }
+  
+  if (o.Contains("pos", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star position:" << endl;
+      *fLog << inf << " Expected \t X " << setw(4) << fXExp 
+            << " mm \tY " << setw(4) << fYExp << " mm" << endl;
+      *fLog << inf << " Calcultated \t X " << setw(4) << fMeanXCalc 
+            << " mm \tY " << setw(4) << fMeanYCalc << " mm" << endl;
+      *fLog << inf << " Fitted \t X " << setw(4) << fMeanXFit 
+            << " mm \tY " << setw(4) << fMeanYFit << " mm" << endl;
+      *fLog << inf << " CGFitted \t X " << setw(4) << fMeanXCGFit 
+            << " mm \tY " << setw(4) << fMeanYCGFit << " mm" << endl;
+    }
+
+  if (o.Contains("siz", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star size:" << endl;
+      *fLog << inf << " Calcultated \t X " << setw(4) << fSigmaMinorAxisCalc 
+            << " mm \tY " << setw(4) << fSigmaMajorAxisCalc << " mm" << endl;
+      *fLog << inf << " Fitted \t X " << setw(4) << fSigmaMinorAxisFit 
+            << " mm \tY " << setw(4) << fSigmaMajorAxisFit << " mm" << endl;
+      *fLog << inf << " CGFitted \t X " << setw(4) << fSigmaXCGFit 
+            << " mm \tY " << setw(4) << fSigmaYCGFit << " mm \t correlation" 
+            << setw(4) << fCorrXYCGFit << endl;
+    }
+
+  if (o.Contains("chi", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "Star Fit Quality:" << endl;
+      *fLog << inf << " ChiSquare/Ndof \t " << setw(3) << fChiSquare 
+            << "/" << fNdof << endl;
+
+      *fLog << inf << "Star CGFit Quality:" << endl;
+      *fLog << inf << " ChiSquareCGFit/NdofCGFit \t " << setw(3) 
+            << fChiSquareCGFit << "/" << fNdofCGFit << endl;
+    }
+
+  if (o.Contains("err", TString::kIgnoreCase) || opt == NULL)
+    {
+      *fLog << inf << "CGFit Error Matrix of (fMeanXCGFit,fMeanYCGFit) :" 
+            << endl;
+      *fLog << inf << " xx,xy,yy \t " << setw(3) << fXXErrCGFit << ", " 
+            << fXYErrCGFit << ", " << fYYErrCGFit << endl;
+    }
+
+
+}
+//--------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalPos.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalPos.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MStarLocalPos.h	(revision 9772)
@@ -0,0 +1,142 @@
+#ifndef MARS_MStarLocalPos
+#define MARS_MStarLocalPos
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MStarLocalPos : public MParContainer
+{
+private:
+
+    //Expected position on camera
+    Float_t fMagExp;
+    Float_t fXExp;    //[mm]
+    Float_t fYExp;    //[mm]
+
+    //Ideal position on camera
+    Float_t fMagIdeal;
+    Float_t fXIdeal;    //[mm]
+    Float_t fYIdeal;    //[mm]
+
+    //Info from calculation
+    Float_t fMagCalc;
+    Float_t fMaxCalc;            //[uA]
+    Float_t fMeanXCalc;          //[mm]
+    Float_t fMeanYCalc;          //[mm]
+    Float_t fSigmaMinorAxisCalc; //[mm]
+    Float_t fSigmaMajorAxisCalc; //[mm]
+
+    //Info from uncorrelated Gauss fit
+    Float_t fMagFit;
+    Float_t fMaxFit;             //[uA]
+    Float_t fMeanXFit;           //[mm]
+    Float_t fMeanYFit;           //[mm]
+    Float_t fSigmaMinorAxisFit;  //[mm]
+    Float_t fSigmaMajorAxisFit;  //[mm]
+    Float_t fXXErr;          
+    Float_t fXYErr;
+    Float_t fYYErr;
+
+    Float_t fChiSquare;
+    Int_t   fNdof;
+
+    //Info from correlated Gauss fit
+    Float_t fMagCGFit;
+    Float_t fMaxCGFit;             //[uA]
+    Float_t fMeanXCGFit;           //[mm]
+    Float_t fMeanYCGFit;           //[mm]
+    Float_t fSigmaXCGFit;          //[mm]
+    Float_t fSigmaYCGFit;          //[mm]
+    Float_t fCorrXYCGFit;          // correlation coefficient
+    Float_t fXXErrCGFit;           // error matrix of (fMeanXCGFit,fMeanYCGFit)
+    Float_t fXYErrCGFit;
+    Float_t fYYErrCGFit;
+
+    Float_t fChiSquareCGFit;
+    Int_t   fNdofCGFit;
+
+
+public:
+
+    MStarLocalPos(const char *name=NULL, const char *title=NULL);
+    //~MStarLocalPos();
+
+    Float_t GetMagExp() {return fMagExp;}
+    Float_t GetXExp() {return fXExp;}
+    Float_t GetYExp() {return fYExp;}
+
+    Float_t GetMagIdeal() {return fMagIdeal;}
+    Float_t GetXIdeal() {return fXIdeal;}
+    Float_t GetYIdeal() {return fYIdeal;}
+
+    Float_t GetMagCalc() {return fMagCalc;}
+    Float_t GetMaxCalc() {return fMaxCalc;}
+    Float_t GetMeanXCalc() {return fMeanXCalc;}
+    Float_t GetMeanYCalc() {return fMeanYCalc;}
+    Float_t GetSigmaMinorAxisCalc() {return fSigmaMinorAxisCalc;}
+    Float_t GetSigmaMajorAxisCalc() {return fSigmaMajorAxisCalc;}
+
+    Float_t GetMagFit() {return fMagFit;}
+    Float_t GetMaxFit() {return fMaxFit;}
+    Float_t GetMeanXFit() {return fMeanXFit;}
+    Float_t GetMeanYFit() {return fMeanYFit;}
+    Float_t GetSigmaMinorAxisFit() {return fSigmaMinorAxisFit;}
+    Float_t GetSigmaMajorAxisFit() {return fSigmaMajorAxisFit;}
+    Float_t GetChiSquare() {return fChiSquare;}
+    UInt_t GetNdof() {return fNdof;}
+    Float_t GetChiSquareNdof() {return fChiSquare/fNdof;}
+
+    Float_t GetMeanX() {return fMeanXFit!=0?fMeanXFit:fMeanXCalc;}
+    Float_t GetMeanY() {return fMeanXFit!=0?fMeanYFit:fMeanYCalc;}
+    Float_t GetSigmaMinorAxis() {return fSigmaMinorAxisFit!=0?fSigmaMinorAxisFit:fSigmaMinorAxisCalc;}
+    Float_t GetSigmaMajorAxis() {return fSigmaMajorAxisFit!=0?fSigmaMajorAxisFit:fSigmaMajorAxisCalc;}
+    
+    // getters for the correlated Gauss fit
+    Float_t GetMagCGFit()           {return fMagCGFit;}
+    Float_t GetMaxCGFit()           {return fMaxCGFit;}
+    Float_t GetMeanXCGFit()         {return fMeanXCGFit;}
+    Float_t GetMeanYCGFit()         {return fMeanYCGFit;}
+    Float_t GetSigmaXCGFit()        {return fSigmaXCGFit;}
+    Float_t GetSigmaYCGFit()        {return fSigmaYCGFit;}
+    Float_t GetCorrXYCGFit()        {return fCorrXYCGFit;}
+    Float_t GetXXErrCGFit()         {return fXXErrCGFit;}
+    Float_t GetXYErrCGFit()         {return fXYErrCGFit;}
+    Float_t GetYYErrCGFit()         {return fYYErrCGFit;}
+    Float_t GetChiSquareCGFit()     {return fChiSquareCGFit;}
+    UInt_t GetNdofCGFit()           {return fNdofCGFit;}
+    Float_t GetChiSquareNdofCGFit() {return fChiSquareCGFit/fNdofCGFit;}
+
+
+    void Reset();
+
+    void SetExpValues(Float_t mag, Float_t x, Float_t y);
+
+    void SetIdealValues(Float_t mag, Float_t x, Float_t y);
+
+    void SetCalcValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+                       Float_t sigmaMinorAxis, Float_t sigmaMajorAxis);
+
+    void SetFitValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+                      Float_t sigmaMinorAxis, Float_t sigmaMajorAxis, 
+                      Float_t chi, Int_t ndof);
+
+    void SetFitValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+                      Float_t sigmaX, Float_t sigmaY, 
+                      Float_t chi, Int_t ndof, 
+                      Float_t xx, Float_t xy, Float_t yy);
+
+    void SetCGFitValues(Float_t mag, Float_t max, Float_t x, Float_t y, 
+                        Float_t sigmaX, Float_t sigmaY, Float_t correlation, 
+                        Float_t xx, Float_t xy, Float_t yy,
+                        Float_t chi, Int_t ndof);
+
+    void Paint(Option_t *opt=NULL);
+    void Print(Option_t *opt=NULL) const;
+
+    ClassDef(MStarLocalPos, 1) // Container that holds the star information in the PMT camera
+};
+
+#endif
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MTelAxisFromStars.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MTelAxisFromStars.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MTelAxisFromStars.cc	(revision 9772)
@@ -0,0 +1,1268 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!   Author(s): Wolfgang Wittek 07/2004 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MTelAxisFromStars
+//
+//  This task 
+//  - determines the transformation from expected positions of stars
+//    in the camera to measured positions of these stars in the camera
+//  - applies this transformation to expected positions of other objects 
+//    to obtain the estimated positions of these objects in the camera
+//  - puts the estimated positions into the relevant containers
+//
+//  Input Containers :
+//   MStarCam[MStarCam], MStarCamSource[MStarCam]
+//
+//  Output Containers :
+//   MSkyCamTrans, MSrcPosCam 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include <TMath.h>
+#include <TList.h>
+#include <TSystem.h>
+
+#include <fstream>
+
+#include "MTelAxisFromStars.h"
+
+#include "MParList.h"
+
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MReportDrive.h"
+#include "MPointingPos.h"
+#include "MSrcPosCam.h"
+
+#include "MStarCam.h"
+#include "MStarPos.h"
+#include "MSkyCamTrans.h"
+#include "MStarCamTrans.h"
+
+ClassImp(MTelAxisFromStars);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Constructor
+//
+MTelAxisFromStars::MTelAxisFromStars(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MTelAxisFromStars";
+    fTitle = title ? title : "Calculate source position from star positions";
+
+    // if scale factor fLambda should NOT be fixed set fFixdScaleFactor to 
+    // -1.0; otherwise set it to the value requested
+    fFixedScaleFactor   = 1.0;
+
+    // if rotation angle fAlfa should NOT be fixed set fFixdRotationAngle to 
+    // -1.0; otherwise set it to the requested value
+    fFixedRotationAngle = 0.0;
+
+    // default type of input is :    the result of the Gauss fit
+    // type 0 : result from the weighted average
+    // type 1 : result from the Gauss fit
+    fInputType = 1;
+
+    // default value of fAberr
+    // the value 1.07 is valid if the expected position (with aberration)
+    // in the camera is calculated as the average of the positions obtained
+    // from the reflections at the individual mirrors
+    fAberr = 1.07;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor
+//
+MTelAxisFromStars::~MTelAxisFromStars()
+{
+  delete fStarCamTrans;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set links to containers
+//
+
+Int_t MTelAxisFromStars::PreProcess(MParList *pList)
+{
+   fDrive = (MReportDrive*)pList->FindObject(AddSerialNumber("MReportDrive"));
+   if (!fDrive)
+   {
+       *fLog << err << AddSerialNumber("MReportDrive") 
+             << " not found... aborting." << endl;
+       return kFALSE;
+   }
+ 
+  
+   fStarCam = (MStarCam*)pList->FindObject("MStarCam", "MStarCam");
+   if (!fStarCam)
+   {
+       *fLog << err << "MStarCam not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   
+   fSourceCam = (MStarCam*)pList->FindObject("MSourceCam", "MStarCam");
+   if (!fSourceCam)
+   {
+       *fLog << warn << "MSourceCam[MStarCam] not found... continue  " << endl;
+   }
+
+
+   //-----------------------------------------------------------------
+    fSrcPos = (MSrcPosCam*)pList->FindCreateObj(AddSerialNumber("MSrcPosCam"), "MSrcPosCam");
+    if (!fSrcPos)
+        return kFALSE;
+
+    fPntPos = (MSrcPosCam*)pList->FindCreateObj(AddSerialNumber("MSrcPosCam"), "MPntPosCam");
+    if (!fPntPos)
+        return kFALSE;
+
+    fPointPos = (MPointingPos*)pList->FindCreateObj(AddSerialNumber("MPointingPos"), "MPointingPos");
+    if (!fPointPos)
+        return kFALSE;
+
+    fSourcePos = (MPointingPos*)pList->FindCreateObj(AddSerialNumber("MPointingPos"), "MSourcePos");
+    if (!fSourcePos)
+        return kFALSE;
+
+    fSkyCamTrans = (MSkyCamTrans*)pList->FindCreateObj(AddSerialNumber("MSkyCamTrans"));
+    if (!fSkyCamTrans)
+        return kFALSE;
+
+
+   //-----------------------------------------------------------------
+   // book an MStarCamTrans object
+   // this is needed when calling one of the member functions of MStarCamTrans
+
+   MGeomCam *geom = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+   if (!geom)
+   {
+       *fLog << err << AddSerialNumber("MGeomCam") 
+             << " not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   MObservatory *obs = (MObservatory*)pList->FindObject(AddSerialNumber("MObservatory"));
+   if (!obs)
+   {
+       *fLog << err << AddSerialNumber("MObservatory") 
+             << " not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   //-----------------------------------------------------------------
+    fStarCamTrans = new MStarCamTrans(*geom, *obs);
+
+   *fLog << all   << "MTelAxisFromStars::Preprocess; the optical aberration factor is set equal to : " 
+         << fAberr ;
+
+   *fLog << all   << "MTelAxisFromStars::Preprocess; input type is set equal to : " 
+         << fInputType ;
+   if (fInputType == 0)
+     *fLog << " (calculated star positions)" << endl;
+   else
+     *fLog << " (fitted star positions)" << endl;
+
+   *fLog << all << "MTelAxisFromStars::Preprocess; scale factor will be fixed at : " 
+         << fFixedScaleFactor << endl;
+
+   *fLog << all << "MTelAxisFromStars::Preprocess; rotation angle will be fixed at : " 
+         << fFixedRotationAngle << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set optical aberration factor
+//
+//   fAberr   is the ratio between 
+//            the distance from the camera center with optical aberration and
+//            the distance from the camera center with an ideal imaging
+//
+//   fAberr = r_real/r_ideal 
+//
+void MTelAxisFromStars::SetOpticalAberr(Double_t aberr)
+{
+  fAberr = aberr;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the type of the input
+//
+//     type = 0        calculated star positions (by averaging)
+//     type = 1        fitted star positions (by Gauss fit)
+//
+void MTelAxisFromStars::SetInputType(Int_t type)
+{
+  fInputType = type;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fix the scale factor fLambda
+//
+//
+void MTelAxisFromStars::FixScaleFactorAt(Double_t lambda)
+{
+  fFixedScaleFactor = lambda;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fix rotation angle fAlfa
+//
+//
+void MTelAxisFromStars::FixRotationAngleAt(Double_t alfa)
+{
+  fFixedRotationAngle = alfa;    // [degrees]
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Process
+//
+//           call FindSkyCamTrans    to find the Sky-Camera transformation
+//           call TransSkyCam        to transform some sky directions
+//                                   into the camera system
+//           put the estimated source position into MSrcPosCam
+//
+
+Int_t MTelAxisFromStars::Process()
+{
+  //Int_t run = fRun->GetRunNumber();
+  //*fLog << "MTelAxisFromStars::Process; run = " << run << endl;
+
+  //--------------------------------------
+  // Define the input for FindSkyCamTrans
+  //
+
+  // get the expected (axy[0], axy[1]) and the measured positions 
+  // (bxy[0], bxy[1]) of stars in the camera from MStarCam 
+  Int_t fNumStars = fStarCam->GetNumStars();
+
+  if (fNumStars <= 0){
+      *fLog << err << "No stars found!" << endl;
+      return kTRUE;
+  }
+
+  TArrayD  axy[2];
+  axy[0].Set(fNumStars);
+  axy[1].Set(fNumStars);
+
+  TArrayD  bxy[2];
+  bxy[0].Set(fNumStars);
+  bxy[1].Set(fNumStars);
+
+  // error matrix of bxy
+  TArrayD  exy[2][2];
+  exy[0][0].Set(fNumStars);
+  exy[0][1].Set(fNumStars);
+  exy[1][0].Set(fNumStars);
+  exy[1][1].Set(fNumStars);
+
+  // transformation parameters
+  Double_t fLambda;
+  Double_t fAlfa;
+  Double_t fA[2][2];
+  Double_t fD[2];
+  Double_t fErrD[2][2];
+  Int_t    fNumIter;
+  Int_t    fNdof;
+  Double_t fChi2;
+  Double_t fChi2Prob;
+
+  MStarPos *star = 0;
+  TIter next(fStarCam->GetList());
+  Int_t ix = 0;
+
+  // loop over all stars
+  while ( (star = (MStarPos*)next()) )
+  {
+    axy[0][ix]   = star->GetXExp(); 
+    axy[1][ix]   = star->GetYExp(); 
+
+    if (fInputType == 0)
+    {
+      // values from averaging
+      bxy[0][ix]     = star->GetMeanXCalc(); 
+      bxy[1][ix]     = star->GetMeanYCalc(); 
+
+      // this is the error matrix for (MeanXCalc, MeanYCalc);
+      // this is the error matrix which should be used
+      exy[0][0][ix]  =  star->GetXXErrCalc(); 
+      exy[0][1][ix]  =  star->GetXYErrCalc();
+      exy[1][0][ix]  =  star->GetXYErrCalc();
+      exy[1][1][ix]  =  star->GetYYErrCalc();
+
+      //exy[0][0][ix]  = star->GetSigmaXCalc()*star->GetSigmaXCalc(); 
+      //exy[0][1][ix]  =  0.0;
+      //exy[1][0][ix]  =  0.0;
+      //exy[1][1][ix]  = star->GetSigmaYCalc()*star->GetSigmaYCalc(); 
+    }
+
+    else if (fInputType == 1)
+    {
+      // values from Gauss fit
+      bxy[0][ix]   = star->GetMeanXFit(); 
+      bxy[1][ix]   = star->GetMeanYFit(); 
+
+      // this is the error matrix for (MeanXFit, MeanYFit);
+      // this is the error matrix which should be used
+      exy[0][0][ix]  =  star->GetXXErrFit(); 
+      exy[0][1][ix]  =  star->GetXYErrFit();
+      exy[1][0][ix]  =  star->GetXYErrFit();
+      exy[1][1][ix]  =  star->GetYYErrFit();
+
+      // this is the error matrix constructed from SigmaXFit and SigmaYFit;
+      // it is used because the errors above are too small, at present
+      //exy[0][0][ix]  =  star->GetSigmaXFit() * star->GetSigmaXFit(); 
+      //exy[0][1][ix]  =  star->GetCorrXYFit() * 
+      //                  star->GetSigmaXFit() * star->GetSigmaYFit();
+      //exy[1][0][ix]  =  exy[0][1][ix];
+      //exy[1][1][ix]  =  star->GetSigmaYFit() * star->GetSigmaYFit();
+    }
+
+    else
+    {
+      *fLog << err << "MTelAxisFromStars::Process;  type of input is not defined" 
+            << endl;
+      return kFALSE;
+    }   
+
+    // don't include stars with undefined error
+    Double_t deter =   exy[0][0][ix]*exy[1][1][ix]
+                     - exy[0][1][ix]*exy[1][0][ix];
+
+    //*fLog << "ix ,deter, xx, xy, yy = " << ix << ":    "
+    //      << deter << ",  " << exy[0][0][ix] << ",  "
+    //      << exy[0][1][ix] << ",  " << exy[1][1][ix] << endl;
+    if (deter <= 0.0)
+      continue;
+
+    //*fLog << "MTelAxisFromStars : " << endl;
+    //*fLog << "      ix, XExp, YExp, XFit, YFit, SigmaX2, SigmaXY, SigmaY2 = " 
+    //      << ix << " :  " 
+    //      << axy[0][ix] << ",  " << axy[1][ix] << ",  "
+    //      << bxy[0][ix] << ",  " << bxy[1][ix] << ",  "
+    //      << exy[0][0][ix] << ",  " << exy[0][1][ix] << ",  " 
+    //      << exy[1][1][ix] << endl;
+
+    ix++;
+  }
+
+  //--------------------------------------
+  // Find the transformation from expected positions (axy[1], axy[2]) 
+  // to measured positions (bxy[1], bxy[2]) in the camera
+
+  Int_t fNStars = ix;
+
+  if (ix < fNumStars)
+  {
+    // reset the sizes of the arrays
+    Int_t fNStars = ix;
+    axy[0].Set(fNStars);
+    axy[1].Set(fNStars);
+
+    bxy[0].Set(fNStars);
+    bxy[1].Set(fNStars);
+
+    exy[0][0].Set(fNStars);
+    exy[0][1].Set(fNStars);
+    exy[1][0].Set(fNStars);
+    exy[1][1].Set(fNStars);
+  }
+
+  Bool_t fitOK;
+  if (fNStars < 1)
+  {
+    //*fLog << "MTelAxisFromStars::Process; no star for MTelAxisFromStars"
+    //      << endl;
+    fitOK = kFALSE;
+  }
+  else
+  {
+    fitOK =  FindSkyCamTrans(axy,      bxy,   exy,   
+               fFixedRotationAngle,    fFixedScaleFactor, fLambda,
+               fAlfa  ,  fA,    fD,    fErrD,
+               fNumIter, fNdof, fChi2, fChi2Prob);
+  }
+
+  if (!fitOK  &&  fNStars >= 1)
+  {
+    *fLog << err 
+          << "MTelAxisFromStars::Process;  Fit to find transformation from star to camera system failed" 
+          << endl;
+    
+    //if (fNStars > 0)
+    //{
+    //  *fLog << err 
+    //        << "    fNumIter, fNdof, fChi2, fChi2Prob = " << fNumIter
+    //        << ",  " << fNdof << ",  " << fChi2 << ",  " << fChi2Prob << endl;
+    //}
+
+    return kTRUE;
+  }
+
+
+  //--------------------------------------
+  // Put the transformation parameters into the MSkyCamTrans container
+
+  fSkyCamTrans->SetParameters(fLambda,   fAlfa,    fA,    fD,    fErrD,
+                              fNumStars, fNumIter, fNdof, fChi2, fChi2Prob);
+  fSkyCamTrans->SetReadyToSave();
+
+  //--------------------------------------
+  // Put the camera position (X, Y) 
+  //         obtained by transforming the camera center (0, 0)
+  // into MPntPosCam[MSrcPosCam]
+
+  fPntPos->SetXY(fD[0], fD[1]);
+  fPntPos->SetReadyToSave();       
+
+
+  //--------------------------------------
+  // Put the corrected pointing position into MPointingPos 
+  //
+  SetPointingPosition(fStarCamTrans, fDrive, fSkyCamTrans, fPointPos);
+
+
+  //--------------------------------------
+  // Put the estimated position of the source into SrcPosCam
+  //
+  // get the source direction from MReportDrive
+  // Note : this has to be changed for the wobble mode, where the source 
+  //        isn't in the center of the camera
+  Double_t decsource = fDrive->GetDec();
+  Double_t rasource  = fDrive->GetRa();
+  //
+  Double_t radrive = fDrive->GetRa();
+  Double_t hdrive  = fDrive->GetHa();
+  Double_t hsource = hdrive + radrive - rasource;
+  fSourcePos->SetSkyPosition(rasource, decsource, hsource);
+
+  SetSourcePosition(fStarCamTrans, fPointPos, fSourcePos, fSrcPos);
+
+  *fLog << "after calling SetSourcePosition : , X, Y ,fD = " 
+        << fSrcPos->GetX() << ",  " << fSrcPos->GetY() << ",  "
+        << fD[0] << ",  " << fD[1] << endl;
+
+  //--------------------------------------
+  // Apply the transformation to some expected positions (asxy[1], asxy[2]) 
+  // to obtain estimated positions (bsxy[1], bsxy[2]) in the camera 
+  //      and their error matrices esxy[2][2]
+
+  // get the expected positions (asxy[1], asxy[2]) from another MStarCam 
+  // container (with the name "MSourceCam") 
+  Int_t fNumStarsSource = 0; 
+
+  if (fSourceCam)
+    fNumStarsSource = fSourceCam->GetNumStars();
+
+  //*fLog << "MTelAxisFromStars::Process;  fNumStarsSource = " 
+  //      << fNumStarsSource << endl;
+
+  if (fNumStarsSource > 0)
+  {
+    TArrayD  asxy[2];
+    asxy[0].Set(fNumStarsSource);
+    asxy[1].Set(fNumStarsSource);
+
+    TArrayD  bsxy[2];
+    bsxy[0].Set(fNumStarsSource);
+    bsxy[1].Set(fNumStarsSource);
+
+    TArrayD  esxy[2][2];
+    esxy[0][0].Set(fNumStarsSource);
+    esxy[0][1].Set(fNumStarsSource);
+    esxy[1][0].Set(fNumStarsSource);
+    esxy[1][1].Set(fNumStarsSource);
+
+    MStarPos *starSource = 0;
+    TIter nextSource(fSourceCam->GetList());
+    ix = 0;
+    while ( (starSource = (MStarPos*)nextSource()) )
+    {
+      asxy[0][ix]  = starSource->GetXExp(); 
+      asxy[1][ix]  = starSource->GetYExp(); 
+
+      ix++;
+    }
+
+    TransSkyCam(fLambda, fA, fD, fErrD, asxy, bsxy,  esxy);   
+
+    // put the estimated positions into the MStarCam container
+    // with name "MSourceCam"
+    TIter setnextSource(fSourceCam->GetList());
+    ix = 0;
+    while ( (starSource = (MStarPos*)setnextSource()) )
+    {
+       Double_t corr = esxy[0][1][ix] / 
+                       TMath::Sqrt( esxy[0][0][ix] * esxy[1][1][ix] );
+       if (fInputType == 1)
+       {
+         starSource->SetFitValues(100.0, 100.0, bsxy[0][ix], bsxy[1][ix],
+	       TMath::Sqrt(esxy[0][0][ix]), TMath::Sqrt(esxy[1][1][ix]), corr,
+               esxy[0][0][ix],       esxy[0][1][ix],       esxy[1][1][ix], 
+               fChi2, fNdof); 
+       }
+       else
+       {
+         starSource->SetCalcValues(100.0, 100.0, bsxy[0][ix], bsxy[1][ix],
+	       TMath::Sqrt(esxy[0][0][ix]), TMath::Sqrt(esxy[1][1][ix]), corr,
+               esxy[0][0][ix],       esxy[0][1][ix],       esxy[1][1][ix]); 
+       }
+
+      ix++;
+    }
+
+  }
+
+  //--------------------------------------
+
+  return kTRUE;
+}
+
+
+
+//---------------------------------------------------------------------------
+//
+// FindSkyCamTrans
+//
+// This routine determines the transformation 
+//
+//                                      ( cos(alfa)   -sin(alfa) )
+//      b = lambda * A * a + d      A = (                        )
+//             ^     ^       ^          ( sin(alfa)    cos(alfa) )
+//             |     |       |
+//           scale rotation shift 
+//          factor matrix
+//
+// from sky coordinates 'a' (projected onto the camera) to camera 
+// coordinates 'b', using the positions of known stars in the camera. 
+// The latter positions may have been determined by analysing the 
+// DC currents in the different pixels.
+//
+// Input  : a[2]    x and y coordinates of stars projected onto the camera;
+//                  they were obtained from (RA, dec) of the stars and
+//                  (ThetaTel, PhiTel) and the time of observation;
+//                  these are the 'expected positions' of stars in the camera
+//          b[2]    'measured positions' of these stars in the camera;
+//                  they may have been obtained from the DC currents
+//          e[2][2] error matrix of b[2]
+//          fixedrotationangle  value [in degrees] at which rotation angle 
+//                              alfa should be fixed; -1 means don't fix
+//          fixedscalefactor    value at which scale factor lambda  
+//                              should be fixed; -1 means don't fix
+//
+// Output : lambda, alfadeg, A[2][2], d[2]   fit results;
+//                               parameters describing the transformation 
+//                               from 'expected positions' to the 'measured 
+//                               positions' in the camera
+//          errd[2][2]           error matrix of d[2]
+//          fNumIter             number of iterations
+//          fNdoF                number of degrees of freedom
+//          fChi2                chi-square value
+//          fChi2Prob            chi-square probability
+//
+// The units are assumed to be 
+//     [degrees]  for  alfadeg
+//     [mm]       for  a, b, d
+//     [1]        for  lambda                       
+
+Bool_t MTelAxisFromStars::FindSkyCamTrans(
+   TArrayD a[2],      TArrayD b[2],     TArrayD e[2][2], 
+   Double_t &fixedrotationang, Double_t &fixedscalefac,  Double_t &lambda,  
+   Double_t &alfadeg, Double_t A[2][2], Double_t d[2],   Double_t errd[2][2],
+   Int_t &fNumIter,   Int_t &fNdof,     Double_t &fChi2, Double_t &fChi2Prob)
+{
+  Int_t fNumStars = a[0].GetSize();
+
+  //*fLog << "MTelAxisFromStars::FindSkyCamTrans; expected and measured positions :"
+  //        << endl;
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+    //*fLog << "    ix, a[0], a[1], b[0], b[1], errxx, errxy, erryy = " 
+    //        << ix << " :   " 
+    //        << a[0][ix] << ",  " << a[1][ix] << ";    " 
+    //        << b[0][ix] << ",  " << b[1][ix] << ";    " 
+    //        << e[0][0][ix] << ",  " << e[0][1][ix] << ",  "
+    //        << e[1][1][ix] << endl;
+  }
+
+
+  //-------------------------------------------
+  // fix some parameters if the number of degrees of freedom is too low
+  // (<= 0.0)
+
+  Double_t fixedscalefactor   = fixedscalefac;
+  Double_t fixedrotationangle = fixedrotationang;
+
+  // calculate number of degrees of freedom
+  fNdof = 2 * fNumStars - 4;
+  if (fixedscalefactor != -1.0)
+     fNdof += 1;
+  if (fixedrotationangle != -1.0)
+     fNdof += 1;
+
+  // if there is only 1 star fix both rotation angle and scale factor
+  if (fNumStars == 1)
+  {
+     if (fixedscalefactor == -1.0)
+     {  
+       fixedscalefactor = 1.0;
+       *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; scale factor is fixed at "
+	     << fixedscalefactor << endl;
+     }
+     if (fixedrotationangle == -1.0)
+     {
+       fixedrotationangle = 0.0;
+       *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; rotation angle is fixed at "
+	     << fixedrotationangle << endl;
+     }
+  }
+  // otherwise fix only 1 parameter if possible
+  else if (fNdof < 0)
+  {
+    if (fNdof < -2)
+    {
+      *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; number of degrees of freedom is too low : " 
+            << fNdof << ";  fNumStars = " << fNumStars << endl;
+      return kFALSE;
+    }
+    else if (fNdof == -2)
+    {
+      if (fixedscalefactor == -1.0  &&  fixedrotationangle == -1.0)
+      {
+        fixedscalefactor   = 1.0;
+        fixedrotationangle = 0.0;
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; scale factor and rotation angle are fixed at " 
+              << fixedscalefactor << "  and  " << fixedrotationangle 
+              << " respectively" << endl;
+      }
+      else
+      {
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; number of degrees of freedom is too low : " 
+              << fNdof << ";  fNumStars = " << fNumStars << endl;
+        return kFALSE;
+      }
+    }
+    else if (fNdof == -1)
+    {
+      if (fixedrotationangle == -1.0)
+      {
+        fixedrotationangle = 0.0;
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; rotation angle is fixed at "
+	      << fixedrotationangle << endl;
+      }
+      else if (fixedscalefactor == -1.0)
+      {
+        fixedscalefactor = 1.0;
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; scale factor is fixed at "
+	      << fixedscalefactor << endl;
+      }
+      else
+      {
+        *fLog << warn << "MTelAxisFromStars::FindSkyCamTrans; number of degrees of freedom is too low : " 
+              << fNdof << ";  fNumStars = " << fNumStars<< endl;
+        return kFALSE;
+      }
+    }
+  }
+
+  // recalculate number of degrees of freedom
+  fNdof = 2 * fNumStars - 4;
+  if (fixedscalefactor != -1.0)
+     fNdof += 1;
+  if (fixedrotationangle != -1.0)
+     fNdof += 1;
+
+  if (fNdof < 0)
+    return kFALSE;
+  //-------------------------------------------
+
+
+  // get first approximation of scaling factor
+  if (fixedscalefactor != -1.0)
+    lambda = fixedscalefactor;
+  else
+    lambda = 1.0;
+
+  Double_t lambdaold = lambda;
+  Double_t dlambda = 0.0;
+
+  // get first approximation of rotation angle
+  Double_t alfa = 0.0;
+  if (fixedrotationangle != -1.0)
+    alfa = fixedrotationangle / TMath::RadToDeg();
+
+  Double_t alfaold   = alfa;
+  // maximum allowed change of alfa in 1 iteration step (5 degrees)
+  Double_t dalfamax = 5.0 / TMath::RadToDeg();
+  Double_t dalfa = 0.0;
+
+  Double_t cosal = TMath::Cos(alfa);
+  Double_t sinal = TMath::Sin(alfa);
+
+  A[0][0] =  cosal;
+  A[0][1] = -sinal;
+  A[1][0] =  sinal;
+  A[1][1] =  cosal;
+
+
+  Double_t absdold2    = 10000.0;
+  Double_t fChangeofd2 = 10000.0;
+
+
+  TArrayD Aa[2];
+  Aa[0].Set(fNumStars);
+  Aa[1].Set(fNumStars);
+
+
+  Double_t sumEbminlamAa[2];
+
+  TArrayD Ebminlambracd[2];
+  Ebminlambracd[0].Set(fNumStars);
+  Ebminlambracd[1].Set(fNumStars);
+
+  TArrayD EAa[2];
+  EAa[0].Set(fNumStars);
+  EAa[1].Set(fNumStars);
+
+  // invert the error matrices
+  TArrayD  c[2][2];
+  c[0][0].Set(fNumStars);
+  c[0][1].Set(fNumStars);
+  c[1][0].Set(fNumStars);
+  c[1][1].Set(fNumStars);
+
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+    Double_t XX = e[0][0][ix]; 
+    Double_t XY = e[0][1][ix]; 
+    Double_t YY = e[1][1][ix]; 
+
+    // get inverse of error matrix
+    Double_t determ = XX*YY - XY*XY;
+    c[0][0][ix]  =  YY / determ; 
+    c[0][1][ix]  = -XY / determ; 
+    c[1][0][ix]  = -XY / determ;
+    c[1][1][ix]  =  XX / determ; 
+  }
+
+
+
+  // calculate sum of inverted error matrices
+  Double_t determsumc;
+  Double_t sumc[2][2];
+  sumc[0][0] = 0.0;
+  sumc[0][1] = 0.0;
+  sumc[1][0] = 0.0;
+  sumc[1][1] = 0.0;
+
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+       sumc[0][0]  += c[0][0][ix]; 
+       sumc[0][1]  += c[0][1][ix]; 
+       sumc[1][0]  += c[1][0][ix]; 
+       sumc[1][1]  += c[1][1][ix]; 
+  }
+  determsumc = sumc[0][0]*sumc[1][1] - sumc[0][1]*sumc[1][0];
+
+  // calculate inverse of sum of inverted error matrices
+  Double_t sumcinv[2][2];
+  sumcinv[0][0]  =  sumc[1][1] / determsumc; 
+  sumcinv[0][1]  = -sumc[0][1] / determsumc; 
+  sumcinv[1][0]  = -sumc[1][0] / determsumc;
+  sumcinv[1][1]  =  sumc[0][0] / determsumc; 
+
+  //*fLog << "sumcinv = " << sumcinv[0][0] << ",  " << sumcinv[0][1] 
+  //      << ",  " << sumcinv[1][1] << endl;
+
+
+  // minimize chi2 by iteration *****   start   **********************
+  
+  // stop iteration when change in |d|*|d| is less than 'told2'
+  //                and  change in alfa    is less than 'toldalfa'
+  //                and  change in lambda  is less than 'toldlambda'
+  //                 or  chi2              is less than 'tolchi2'
+  Double_t told2 = 0.3*0.3;  // [mm*mm]; 1/100 of an inner pixel diameter
+  Double_t toldalfa = 0.01 / TMath::RadToDeg();  // 0.01 degrees 
+  Double_t toldlambda = 0.00006;   // uncertainty of 1 mm of distance 
+                                   // between camera and reflector
+  Double_t tolchi2 = 1.e-5;
+
+  Int_t fNumIterMax  = 100;
+  fNumIter           =   0;
+
+  for (Int_t i=0; i<fNumIterMax; i++)
+  {
+    fNumIter++;
+
+    // get next approximation of d  ------------------
+    for (Int_t ix=0; ix<fNumStars; ix++)
+    {
+        Aa[0][ix] = A[0][0] * a[0][ix]  +  A[0][1]*a[1][ix];
+        Aa[1][ix] = A[1][0] * a[0][ix]  +  A[1][1]*a[1][ix];
+
+        //*fLog << "ix, Aa = " << ix << " :  " << Aa[0][ix] << ",  "
+        //      << Aa[1][ix] << endl;
+    }
+
+    sumEbminlamAa[0] = 0.0;
+    sumEbminlamAa[1] = 0.0;
+
+    for (Int_t ix=0; ix<fNumStars; ix++)
+    {
+      sumEbminlamAa[0] +=   c[0][0][ix] * (b[0][ix] - lambda*Aa[0][ix])
+                          + c[0][1][ix] * (b[1][ix] - lambda*Aa[1][ix]);
+
+      sumEbminlamAa[1] +=   c[1][0][ix] * (b[0][ix] - lambda*Aa[0][ix])
+                          + c[1][1][ix] * (b[1][ix] - lambda*Aa[1][ix]);
+    }
+
+    //*fLog << "sumEbminlamAa = " << sumEbminlamAa[0] << ",  "
+    //      << sumEbminlamAa[1] << endl;
+
+    d[0] =      sumcinv[0][0] * sumEbminlamAa[0]
+	      + sumcinv[0][1] * sumEbminlamAa[1] ;
+
+    d[1] =      sumcinv[1][0] * sumEbminlamAa[0] 
+              + sumcinv[1][1] * sumEbminlamAa[1] ;
+
+    Double_t absdnew2 = d[0]*d[0] + d[1]*d[1]; 
+    fChangeofd2 = absdnew2 - absdold2;
+
+    //*fLog << "fNumIter : " << fNumIter 
+    //      << "; alfa, lambda, d[0], d[1], absdold2, absdnew2 = " << endl; 
+    //*fLog << alfa << ",  " << lambda << ",  " << d[0] << ",  " << d[1] 
+    //      << ",  " << absdold2 << ",  " << absdnew2 << endl;
+     
+
+    if ( fabs(fChangeofd2) < told2   &&  fabs(dalfa) < toldalfa  &&
+         fabs(dlambda)     < toldlambda ) 
+    {
+      //*fLog << "Iteration stopped because of small changes : fChangeofd2, dalfa, dlambda = "
+      //      << fChangeofd2 << ",  " << dalfa << ",  "  << dlambda << endl;
+      break;
+    }
+    absdold2 = absdnew2;
+
+    // get next approximation of matrix A  ----------------
+    if (fFixedRotationAngle == -1.0)
+    {     
+        for (Int_t ix=0; ix<fNumStars; ix++)
+        {
+          Ebminlambracd[0][ix] =   
+             c[0][0][ix] * ( b[0][ix] - lambda*Aa[0][ix] - d[0] )
+           + c[0][1][ix] * ( b[1][ix] - lambda*Aa[1][ix] - d[1] );
+
+          Ebminlambracd[1][ix] =   
+             c[1][0][ix] * ( b[0][ix] - lambda*Aa[0][ix] - d[0] )
+           + c[1][1][ix] * ( b[1][ix] - lambda*Aa[1][ix] - d[1] );
+
+          //*fLog << "ix, Ebminlambracd = " << ix << " :  "
+          //      << Ebminlambracd[0][ix] << ",  "
+          //      << Ebminlambracd[1][ix] << endl;
+        }
+
+        // stop iteration if fChi2 is small enough
+        fChi2 = 0.0;
+        for (Int_t ix=0; ix<fNumStars; ix++)
+        {
+          fChi2 +=  (b[0][ix]-lambda*Aa[0][ix]-d[0] ) * Ebminlambracd[0][ix]
+                  + (b[1][ix]-lambda*Aa[1][ix]-d[1] ) * Ebminlambracd[1][ix];
+        }
+        if ( fChi2 < tolchi2 ) 
+        {
+          //*fLog << "iteration stopped because of small fChi2 :  "
+          //      << fChi2 << endl;
+          break;
+        }
+
+
+        Double_t dchi2dA[2][2];
+        dchi2dA[0][0] = 0.0; 
+        dchi2dA[0][1] = 0.0;
+        dchi2dA[1][0] = 0.0;
+        dchi2dA[1][1] = 0.0;
+		
+        for (Int_t ix=0; ix<fNumStars; ix++)
+        {
+          dchi2dA[0][0] += Ebminlambracd[0][ix] * a[0][ix];
+          dchi2dA[0][1] += Ebminlambracd[0][ix] * a[1][ix];
+          dchi2dA[1][0] += Ebminlambracd[1][ix] * a[0][ix];
+          dchi2dA[1][1] += Ebminlambracd[1][ix] * a[1][ix];
+        }
+
+        //*fLog << "dchi2dA = " << dchi2dA[0][0] << ",  " << dchi2dA[0][1]
+        //      << ",  " << dchi2dA[1][0] << ",  " << dchi2dA[1][1] << endl;
+
+        // *********  1st derivative (d chi2) / (d alfa) ************
+        Double_t dchi2dalfa =   -2.0*lambda * 
+                              ( - sinal*(dchi2dA[0][0]+dchi2dA[1][1])
+                                + cosal*(dchi2dA[1][0]-dchi2dA[0][1]) );
+        
+
+        //Double_t dalfa1st = - fChi2 / dchi2dalfa;
+
+        //*fLog << "fChi2, dchi2dalfa = " << fChi2 << ",  " 
+        //      << dchi2dalfa << endl;
+        //*fLog << "proposed change of alfa using 1st derivative = " 
+        //      << dalfa1st << endl;
+
+        // *********  2nd derivative (d2 chi2) / (d alfa2) ******
+        Double_t term1 = 0.0;
+        Double_t term2 = 0.0;
+        Double_t term3 = 0.0;
+        Double_t term4 = 0.0;
+
+        for (Int_t ix=0; ix<fNumStars; ix++)
+        {
+          term1 += a[0][ix]*c[0][0][ix]*a[0][ix] + a[1][ix]*c[1][0][ix]*a[0][ix]
+	         + a[0][ix]*c[0][1][ix]*a[1][ix] + a[1][ix]*c[1][1][ix]*a[1][ix];
+
+          term2 += a[0][ix]*c[1][0][ix]*a[0][ix] - a[1][ix]*c[0][0][ix]*a[0][ix]
+	         + a[0][ix]*c[1][1][ix]*a[1][ix] - a[1][ix]*c[0][1][ix]*a[1][ix];
+
+          term3 = a[0][ix]*c[0][0][ix]*a[1][ix] + a[1][ix]*c[1][0][ix]*a[1][ix]
+	         - a[0][ix]*c[0][1][ix]*a[0][ix] - a[1][ix]*c[1][1][ix]*a[0][ix];
+
+          term4 += a[0][ix]*c[1][0][ix]*a[1][ix] - a[1][ix]*c[0][0][ix]*a[1][ix]
+	         - a[0][ix]*c[1][1][ix]*a[0][ix] + a[1][ix]*c[0][1][ix]*a[0][ix];
+        }
+
+        Double_t d2chi2dalfa2 = 
+                  - 2.0*lambda * ( - cosal*(dchi2dA[0][0]+dchi2dA[1][1])
+                                   - sinal*(dchi2dA[1][0]-dchi2dA[0][1]) )
+	   + 2.0*lambda*lambda * ( sinal*sinal * term1 - sinal*cosal * term2
+		  	         + sinal*cosal * term3 - cosal*cosal * term4);
+
+        // Gauss-Newton step
+        Double_t dalfa2nd = - dchi2dalfa / d2chi2dalfa2;
+
+        //*fLog << "proposed change of alfa using 2st derivative = " 
+        //    << dalfa2nd << endl;
+
+        //dalfa = dalfa1st;
+        dalfa = dalfa2nd;
+
+        // ******************************************
+
+
+        // restrict change of alfa
+        if ( fabs(dalfa) > dalfamax )
+        {
+          dalfa = TMath::Sign( dalfamax, dalfa ); 
+        }
+        alfa = alfaold + dalfa;
+
+        if ( alfa < -5.0/TMath::RadToDeg() )
+          alfa = -5.0/TMath::RadToDeg();
+        else if ( alfa > 5.0/TMath::RadToDeg() )
+          alfa = 5.0/TMath::RadToDeg();
+        
+        dalfa = alfa - alfaold;
+
+        alfaold = alfa;
+
+        sinal = TMath::Sin(alfa);
+        cosal = TMath::Cos(alfa);
+
+        A[0][0] =  cosal;
+        A[0][1] = -sinal;
+        A[1][0] =  sinal;
+        A[1][1] =  cosal;
+
+        //*fLog << "alfa-alfaold = " << dalfa << endl;
+        //*fLog << "new alfa = " << alfa << endl;
+    }
+
+
+    // get next approximation of lambda  ----------------
+    if (fFixedScaleFactor == -1.0)
+    {
+      for (Int_t ix=0; ix<fNumStars; ix++)
+      {
+        Aa[0][ix] = A[0][0]*a[0][ix] + A[0][1]*a[1][ix];
+        Aa[1][ix] = A[1][0]*a[0][ix] + A[1][1]*a[1][ix];
+
+        EAa[0][ix] =   
+           c[0][0][ix] * Aa[0][ix]  +  c[0][1][ix] * Aa[1][ix];
+        EAa[1][ix] =   
+           c[1][0][ix] * Aa[0][ix]  +  c[1][1][ix] * Aa[1][ix];
+
+        //*fLog << "ix, Aa = " << ix << " :  " << Aa[0][ix] << ",  "
+        //      << Aa[1][ix] << endl;
+
+        //*fLog << "ix, EAa = " << ix << " :  " << EAa[0][ix] << ",  "
+        //      << EAa[1][ix] << endl;
+      }
+
+      Double_t num   = 0.0;
+      Double_t denom = 0.0;
+      for (Int_t ix=0; ix<fNumStars; ix++)
+      {
+        num    +=   (b[0][ix]-d[0]) * EAa[0][ix] 
+                  + (b[1][ix]-d[1]) * EAa[1][ix];
+
+        denom  +=    Aa[0][ix]      * EAa[0][ix]  
+                  +  Aa[1][ix]      * EAa[1][ix]; 
+
+        //*fLog << "ix : b-d = " << ix << " :  " << b[0][ix]-d[0]
+	//      << ",  " << b[1][ix]-d[1] << endl;
+
+        //*fLog << "ix : Aa = " << ix << " :  " << Aa[0][ix]
+	//      << ",  " << Aa[1][ix] << endl;
+      }
+
+      lambda = num / denom;
+
+      if ( lambda < 0.9 )
+        lambda = 0.9;
+      else if ( lambda > 1.1 )
+        lambda = 1.1;
+
+      dlambda = lambda - lambdaold;
+      lambdaold = lambda;
+
+      //*fLog << "num, denom, lambda, dlambda = " << num
+      //      << ",  " << denom << ",  " << lambda << ",  "
+      //      << dlambda << endl;
+    }
+
+  }
+  //-------   end of iteration *****************************************
+
+  alfadeg = alfa * TMath::RadToDeg();
+
+  // calculate error matrix of d[2]
+  errd[0][0] = sumcinv[0][0];
+  errd[0][1] = sumcinv[0][1];
+  errd[1][0] = sumcinv[1][0];
+  errd[1][1] = sumcinv[1][1];
+
+  // evaluate quality of fit
+
+  // calculate chi2
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+    Ebminlambracd[0][ix] =   
+       c[0][0][ix] * ( b[0][ix] - lambda*Aa[0][ix] - d[0] )
+     + c[0][1][ix] * ( b[1][ix] - lambda*Aa[1][ix] - d[1] );
+
+    Ebminlambracd[1][ix] =   
+       c[1][0][ix] * (b[0][ix] - lambda*Aa[0][ix] - d[0] )
+     + c[1][1][ix] * (b[1][ix] - lambda*Aa[1][ix] - d[1] );
+  }
+
+  fChi2 = 0.0;
+  for (Int_t ix=0; ix<fNumStars; ix++)
+  {
+    fChi2 +=  (b[0][ix] - lambda*Aa[0][ix] - d[0] ) * Ebminlambracd[0][ix]
+            + (b[1][ix] - lambda*Aa[1][ix] - d[1] ) * Ebminlambracd[1][ix];
+  }
+
+  fChi2Prob = TMath::Prob(fChi2, fNdof);
+
+  //*fLog << "MTelAxisFromStars::FindSkyCamTrans :" << endl;
+  //*fLog <<  "   fNumStars, fChi2, fNdof, fChi2Prob, fNumIter, fChangeofd2, dalfa, dlambda = "
+  //      << fNumStars << ",  " << fChi2 << ",  " << fNdof << ",  " 
+  //      << fChi2Prob << ",  " 
+  //      << fNumIter << ",  "  << fChangeofd2 << ",  " << dalfa << ",  "
+  //      << dlambda << endl;
+  //*fLog << "    lambda, alfadeg, d[0], d[1] = " << lambda << ",  " 
+  //      << alfadeg   << ",  " << d[0] << ",  " << d[1] << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Apply transformation (lambda, A, d)
+//       to the        expected  positions (a[1], a[2]) 
+//       to obtain the estimated positions (b[1], b[2])
+//
+//       e[2][2]       is the error matrix of b[2]
+
+void MTelAxisFromStars::TransSkyCam(
+    Double_t &lambda, Double_t A[2][2], Double_t d[2], Double_t errd[2][2],
+    TArrayD a[2],     TArrayD b[2],     TArrayD e[2][2])   
+{
+  Int_t numpos = a[0].GetSize();
+  if (numpos <= 0)
+    return;
+
+  //*fLog << "MTelAxisFromStars::TransSkyCam; lambda, A, d = " 
+  //      << lambda << ";    " << A[0][0] << ",  " << A[0][1] << ",  "
+  //      << A[1][1] << ";   " << d[0] << ",  " << d[1] << endl;   
+
+  //*fLog << "MTelAxisFromStars::TransSkyCam; expected and estimated positions :"
+  //      << endl;
+
+  for (Int_t ix=0; ix<numpos; ix++)
+  {
+    //    *fLog << "MTelAxisFromStars;  ix = " << ix << endl;
+
+      b[0][ix] = lambda * (A[0][0]*a[0][ix] + A[0][1]*a[1][ix]) + d[0];
+      b[1][ix] = lambda * (A[1][0]*a[0][ix] + A[1][1]*a[1][ix]) + d[1];
+
+      e[0][0][ix] = errd[0][0];
+      e[0][1][ix] = errd[0][1];
+      e[1][0][ix] = errd[1][0];
+      e[1][1][ix] = errd[1][1];
+
+      // *fLog << "    ix, a[0], a[1], b[0], b[1], errxx, errxy, erryy = " 
+      //      << ix << " :   " 
+      //      << a[0][ix] << ",  " << a[1][ix] << ";    " 
+      //      << b[0][ix] << ",  " << b[1][ix] << ";    " 
+      //      << e[0][0][ix] << ",  " << e[0][1][ix] << ",  "
+      //      << e[1][1][ix] << endl;
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// SetPointingPosition
+//
+//    put the corrected pointing direction into MPointingPos[MPointingPos];
+//    this direction corresponds to the position (0,0) in the camera
+//
+
+Bool_t MTelAxisFromStars::SetPointingPosition(MStarCamTrans *fstarcamtrans,
+       MReportDrive *fdrive, MSkyCamTrans *ftrans, MPointingPos *fpointpos)
+{
+  Double_t decdrive = fdrive->GetDec();
+  Double_t hdrive   = fdrive->GetHa();
+  Double_t radrive  = fdrive->GetRa();
+
+  // this is the estimated position (with optical aberration) in the camera 
+  // corresponding to the direction in MReportDrive
+  Double_t Xpoint = (ftrans->GetShiftD())[0];    
+  Double_t Ypoint = (ftrans->GetShiftD())[1];    
+
+  // get the sky direction corresponding to the position (0,0) in the camera
+  Double_t decpoint = 0.0;
+  Double_t hpoint   = 0.0;
+  fstarcamtrans->CelCamToCel0(decdrive, hdrive, 
+                         Xpoint/fAberr, Ypoint/fAberr, decpoint, hpoint);
+  Double_t rapoint = radrive - hpoint + hdrive;
+  fpointpos->SetSkyPosition(rapoint, decpoint, hpoint);
+
+  // get the local direction corresponding to the position (0,0) in the camera
+  Double_t thetadrive = fdrive->GetNominalZd();
+  Double_t phidrive   = fdrive->GetNominalAz();
+  Double_t thetapoint = 0.0;
+  Double_t phipoint   = 0.0;
+  fstarcamtrans->LocCamToLoc0(thetadrive, phidrive, 
+               Xpoint/fAberr, Ypoint/fAberr, thetapoint, phipoint); 
+  fpointpos->SetLocalPosition(thetapoint, phipoint);
+  fpointpos->SetReadyToSave();
+
+  //*fLog << "SetPointingPosition : decdrive, hdrive, radrive Xpoint, Ypoint = "
+  //      << decdrive << ",  " << hdrive << ",  " << radrive << ",  "
+  //      << Xpoint << ",  " << Ypoint << endl;
+
+  //*fLog << "SetPointingPosition : thetadrive, phidrive, thetapoint, phipoint = "       
+  //      << thetadrive << ",  " << phidrive << ",  " << thetapoint << ",  "
+  //      << phipoint << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// SetSourcePosition
+//
+//    put the estimated position of the source in the camera into 
+//    MSrcPosCam[MSrcPosCam]
+//
+//    and the estimated local direction of the source into
+//    MSourcePos[MPointingPos]
+//
+
+Bool_t MTelAxisFromStars::SetSourcePosition(MStarCamTrans *fstarcamtrans,
+       MPointingPos *fpointpos, MPointingPos *fsourcepos, MSrcPosCam *fsrcpos)
+{
+  // get the corrected pointing direction
+  // corresponding to the position (0,0) in the camera
+  Double_t decpoint = fpointpos->GetDec();
+  Double_t hpoint   = fpointpos->GetHa();
+
+  // get the sky direction of the source
+  Double_t decsource = fsourcepos->GetDec();
+  Double_t hsource   = fsourcepos->GetHa();
+
+  // get the estimated position (Xsource, Ysource) of the source in the camera;
+  // this is a position for an ideal imaging, without optical aberration
+  Double_t Xsource = 0.0;
+  Double_t Ysource = 0.0;
+  fstarcamtrans->Cel0CelToCam(decpoint,  hpoint, 
+                              decsource, hsource, Xsource, Ysource);
+  fsrcpos->SetXY(Xsource*fAberr, Ysource*fAberr);
+  fsrcpos->SetReadyToSave();
+
+  // get the estimated local direction of the source
+  Double_t thetapoint = fpointpos->GetZd();
+  Double_t phipoint   = fpointpos->GetAz();
+  Double_t thetasource = 0.0;
+  Double_t phisource   = 0.0;
+  fstarcamtrans->Loc0CamToLoc(thetapoint, phipoint, 
+                              Xsource, Ysource, thetasource, phisource);
+  fsourcepos->SetLocalPosition(thetasource, phisource);
+  fsourcepos->SetReadyToSave();
+
+  //*fLog << "SetSourcePosition : decpoint, hpoint, decsource, hsource, Xsource, Ysource = "
+  //      << decpoint << ",  " << hpoint << ",  " << decsource << ",  "
+  //      << hsource  << ",  " << Xsource << ",  " << Ysource << endl;
+  //*fLog << "SetSourcePosition : thetapoint, phipoint, thetasource, phisource = "
+  //      << thetapoint << ",  " << phipoint << ",  " << thetasource << ",  "
+  //      << phisource << endl;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MTelAxisFromStars.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MTelAxisFromStars.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MTelAxisFromStars.h	(revision 9772)
@@ -0,0 +1,88 @@
+#ifndef MARS_MTelAxisFromStars
+#define MARS_MTelAxisFromStars
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MTelAxisFromStars                                                       //
+//                                                                         //
+// Task to calculate the position (in the camera) 
+//      of certain sky directions (source position, tracking direction, ...) 
+//      from the positions (in the camera) of known stars 
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MReportDrive;
+class MPointingPos;
+class MSrcPosCam;
+class MStarCam;
+class MSkyCamTrans;
+class MStarCamTrans;
+
+class MTelAxisFromStars : public MTask
+{
+ private:
+
+    const MStarCam *fStarCam;          //!
+    const MStarCam *fSourceCam;        //!
+
+    MReportDrive        *fDrive;          //!
+    MPointingPos        *fPointPos;       //!
+    MPointingPos        *fSourcePos;      //!
+    MSrcPosCam          *fSrcPos;         //!
+    MSrcPosCam          *fPntPos;         //!
+    MSkyCamTrans        *fSkyCamTrans;    //!
+    MStarCamTrans       *fStarCamTrans;   //!
+
+    Double_t fFixedScaleFactor;           //!
+    Double_t fFixedRotationAngle;         //! [degrees]
+    Double_t fAberr;                      //! optical aberration factor
+
+    Int_t fInputType;                     //! type of input
+
+    Int_t  PreProcess(MParList *pList);
+    Int_t  Process();
+
+ public:
+
+    MTelAxisFromStars(const char *name=NULL, const char *title=NULL);
+    ~MTelAxisFromStars();
+
+    void FixScaleFactorAt(Double_t lambda = 1.0);
+    void FixRotationAngleAt(Double_t alfa = 0.0);  // alfa in [degrees]
+
+    void SetOpticalAberr(Double_t aberr);   
+    void SetInputType(Int_t type = 1);
+
+    Bool_t FindSkyCamTrans(TArrayD[2],      TArrayD[2],  TArrayD[2][2], 
+		  	   Double_t &,      Double_t &,  Double_t &,
+	       Double_t &, Double_t[2][2] , Double_t[2], Double_t[2][2],
+               Int_t &,    Int_t &,         Double_t &,  Double_t &); 
+
+    void TransSkyCam(Double_t &,  Double_t[2][2], Double_t[2], Double_t[2][2],
+                     TArrayD[2],  TArrayD[2],     TArrayD[2][2]);   
+
+    Bool_t SetPointingPosition(MStarCamTrans *fstarcamtrans,
+       MReportDrive *fdrive, MSkyCamTrans *ftrans, MPointingPos *fpointpos);
+    Bool_t SetSourcePosition(MStarCamTrans *fstarcamtrans,
+       MPointingPos *fpointpos, MPointingPos *fsourcepos, MSrcPosCam *fsrcpos);
+
+    ClassDef(MTelAxisFromStars, 0) // Task to calculate the source position from star positions
+};
+
+#endif
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPObject.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPObject.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPObject.cc	(revision 9772)
@@ -0,0 +1,280 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner <mailto:magicsoft@rwagner.de> 10/2002
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MVPObject                                                              //
+//                                                                         //
+//  Class used by the visibility plotter to convert RA/Dec to Alt/Az       //
+//                                                                         //
+//  This class represents an object and is used with the Visibility        //
+//  macro. It must be provided with its RA/Dec coordinates and an          //
+//  object name (cf. MVPObject::SetRA, MVPObject::SetDec, and              //
+//  MVPObject::SetName). Alternatively, you can require the MVPObject      //
+//  to be a solar system object like the Sun, Mars or the Moon             //
+//  (cf. MVPObject::SetObject).                                            //
+//                                                                         //
+//  MVPObject is ready to be used in a Mars Eventloop. You must provide    //
+//  an Observatory Location as well as a time at which the position        //
+//  of the MVPObject is to be calculated. MVPObject::PreProcess            //
+//  checks the existence of the required containers and also makes sure    //
+//  all necessary setters have been called. MVPObject::Process             //
+//  then calculates the Alt/Az position of the object, as well as the      //
+//  Zenith angle and the object diameter (Solar system objects).           //
+//                                                                         //
+//  The astronomical algorithms used are taken from SLALIB 2.4-8.          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MVPObject.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+
+#include "../../slalib/slalib.h"
+
+ClassImp(MVPObject);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MVPObject::MVPObject(const char *name, const char *title) : fDiameter(0), fCalcEc(kFALSE), fUT1(52000), fBody(10), fGotRA(kFALSE), fGotDec(kFALSE), fGotName(kFALSE)
+{
+  fName  = name  ? name  : "MVPObject";
+  fTitle = title ? title : "Task to calculate Alt, Az of a given object";
+  
+  fgDegToRad=2*TMath::Pi()/360;
+  fgHrsToRad=2*TMath::Pi()/24;  
+}
+
+MVPObject::~MVPObject()
+{
+  //Destructor: nothing special yet.
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if necessary containers exist in the parameter list already.
+//  We need an ObservatoryLocation and a MVPTime object.
+//
+Bool_t MVPObject::PreProcess(MParList *pList)
+{
+  fObservatory = (MObservatoryLocation*)pList->FindObject("MObservatoryLocation");
+  if (!fObservatory)
+    {
+      *fLog << dbginf << "MObservatoryLocation not found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fTime = (MVPTime*)pList->FindObject("MVPTime");
+  if (!fTime)
+    {
+      *fLog << dbginf << "MVPTime not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  if (!fGotRA || !fGotDec || !fGotName)
+    {
+      *fLog << dbginf << "Object information is not complete." << endl;
+      return kFALSE;
+    }
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets coordinates from object name. Instead of providing RA, Dec and Name
+// of an object, you may also just provide the object name in the from
+// HHMMsDDT, where RA is given in hours and minutes and Declination is
+// given by degrees DD and tenths of degrees T. "s" may be "+" or
+// "-", eg. "1959+650"
+//
+void MVPObject::SetObjectByName(const char *object)
+{
+  fObjectName=object;
+  fGotName=kTRUE;
+  
+  Int_t ra, dec;
+  sscanf(object, "%d%d", &ra, &dec);
+
+  fRA  = fgHrsToRad * (0.01*ra + (r%100)/60.);
+  fDec = fgDegToRad * 0.1 * dec;
+
+  fGotRA=kTRUE;
+  fGotDec=kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Sets RA position of object. Position is to be provided in hours, minutes,
+// seconds, and microseconds (if needed)
+//
+void MVPObject::SetRA(Int_t rh, Int_t rm, Int_t rs, Int_t ru)
+{
+  // Rect is a timelike value...
+  fRA = fgHrsToRad*((Double_t)rh + (Double_t)rm/60 + (Double_t)rs/(60*60) + (Double_t)ru/(36000));
+  fBody = 10;
+  fGotRA = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets Dec position of object. Position is to be provided in degrees, 
+// minutes, seconds, and microseconds (if needed)
+//
+void MVPObject::SetDec(Int_t dh, Int_t dm, Int_t ds, Int_t du)
+{
+  // Dec is an anglelike value
+  fDec = fgDegToRad*((Double_t)dh + (Double_t)dm/60 + (Double_t)ds/(60*60) + (Double_t)du/(36000));
+  fBody = 10;
+  fGotDec = kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Alternatively to providing RA, Dec and Name of an object, you may provide 
+// a solar system object (which has no fixed RA, Dec, by the way!) with
+// MVPObject::SetObject.
+// -
+// UInt_t body | Object      Sun and Moon will be objects needed at most,
+//           0 | Sun         presumably.
+//           1 | Mercury
+//           2 | Venus
+//           3 | Moon
+//           4 | Mars
+//           5 | Jupiter
+//           6 | Saturn
+//           7 | Uranus
+//           8 | Neptune
+//           9 | Pluto
+//
+Bool_t MVPObject::SetObject(UInt_t body)
+{
+  if (body > 9) 
+    {
+      *fLog << dbginf << "No solar system object associated with value " << body <<"! Ignoring request." << endl;
+      return kFALSE;
+    }
+  else  // We are working on a solar system body.
+    {                   
+      switch (body) 
+       	{
+	case 1: fObjectName="Mercury"; break;
+       	case 2: fObjectName="Venus"; break;
+       	case 3: fObjectName="Moon"; break;
+       	case 4: fObjectName="Mars"; break;
+       	case 5: fObjectName="Jupiter"; break;
+       	case 6: fObjectName="Saturn"; break;
+       	case 7: fObjectName="Uranus"; break;
+       	case 8: fObjectName="Neptune"; break;
+       	case 9: fObjectName="Pluto"; break;
+       	default: fObjectName="Sun"; 
+       	}            
+    }
+  
+  fBody = body; 
+  fGotRA = fGotDec = fGotName = kTRUE;
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Given RA, Dec or a solar system object as well as an observatory
+// location and a MVPTime, MVPObject::Process() calculates
+// Alt, Az, ZA and (in the case of solar system objects) the apparent
+// object diameter
+//
+Bool_t MVPObject::Process()
+{
+  Double_t diameter = 0.0;
+
+  if (fBody < 10) // We are working on a solar system body.
+    {      
+      slaRdplan(fTime->GetMJD(), fBody, fObservatory->GetLongitudeRad(), fObservatory->GetLatitudeRad(), &fRA, &fDec, &diameter);         
+    }
+  
+  if (fCalcEc) slaEqecl(fRA, fDec, fTime->GetMJD(), &fEcLong, &fEcLat);
+  
+  Float_t azimuth;
+  Float_t elevation;
+  
+  Float_t hourAngle = (Float_t)UT1ToGMST(fTime->GetMJD()) - fRA;
+
+  //  cout << "ha: " << hourAngle  << " ra: " << fRA << " dec " << fDec <<endl;
+
+  slaE2h (hourAngle, (Float_t)fDec, (Float_t)fObservatory->GetLatitudeRad(), &azimuth, &elevation);
+   
+  fZA  = slaZd(hourAngle, fDec, fObservatory->GetLatitudeRad());
+  fAlt = (Double_t)elevation;
+  fAz  = (Double_t)azimuth; 
+  fDiameter = diameter;
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Returns distance of given object to this object in degrees
+//
+Double_t MVPObject::GetDistance(MVPObject* object)
+{
+  return slaSep(fRA, fDec, object->GetRARad(), object->GetDecRad())/fgDegToRad;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns distance of given object to this object in radians
+//
+Double_t MVPObject::GetDistanceRad(MVPObject* object)
+{
+  return slaSep(fRA, fDec, object->GetRARad(), object->GetDecRad());
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Converts UT1 (given as MJD) to Greenwich mean star time in radians
+//
+Double_t MVPObject::UT1ToGMST(Double_t ut1)
+{
+  return slaGmst(ut1);
+}
+
+void MVPObject::Print(Option_t *) const
+{
+  *fLog << all;
+  *fLog << "Position of "<< fObjectName << 
+    ": Dec " << fDec/fgDegToRad << " deg, " << 
+    "RA  " << fRA/fgHrsToRad << " hrs" << endl;
+  if (fCalcEc) *fLog << "Ecliptic Long: " << fEcLong/fgDegToRad << " deg, " << 
+		  "Ecliptic Lat: " << fEcLat/fgDegToRad << " deg, " << endl; 
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPObject.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPObject.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPObject.h	(revision 9772)
@@ -0,0 +1,100 @@
+#ifndef MARS_MVPObject
+#define MARS_MVPObject
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MObservatoryLocation
+#include "MObservatoryLocation.h"
+#endif
+
+#ifndef MARS_MVPTime
+#include "MVPTime.h"
+#endif
+
+class MVPObject : public MTask
+{
+private:
+  MObservatoryLocation *fObservatory;  
+
+  Double_t fRA;
+  Double_t fDec;
+  Double_t fAlt;
+  Double_t fAz;
+  Double_t fZA;
+  Double_t fDiameter;
+  Double_t fEcLat;
+  Double_t fEcLong;
+  Bool_t fCalcEc;
+
+  Double_t fUT1;
+  MVPTime *fTime;
+ 
+  char* fObjectName;
+  UInt_t fBody;
+
+  Double_t UT1ToGMST(Double_t ut1);
+ 
+  Double_t fgDegToRad;
+  Double_t fgHrsToRad;
+
+  Bool_t fGotRA;
+  Bool_t fGotDec;
+  Bool_t fGotName;
+
+public:
+
+  MVPObject(const char *name=NULL, const char *title=NULL);
+  ~MVPObject();
+
+  Bool_t PreProcess(MParList *pList);
+  Bool_t Process();
+
+  void SetObservatory(MObservatoryLocation *observatory);
+
+  void SetRA(Double_t rad) { fRA = rad; fBody = 10; fGotRA = kTRUE; }
+  void SetDec(Double_t rad) { fDec = rad; fBody = 10; fGotDec = kTRUE; }
+
+  void SetRA(Int_t rh, Int_t rm, Int_t rs, Int_t ru = 0);
+  void SetDec(Int_t dh, Int_t dm, Int_t ds, Int_t du = 0);
+
+  void SetCalcEc(Bool_t calcEc) { fCalcEc = calcEc; }
+
+  void SetObjectName(char* name) { fObjectName = name; fGotName = kTRUE; } 
+  void SetObjectByName(char* object);
+
+  Bool_t SetObject(UInt_t body);
+
+  Double_t GetRA() { return fRA/fgHrsToRad; }
+  Double_t GetDec() { return fDec/fgDegToRad; }
+
+  Double_t GetRARad()  { return fRA; }
+  Double_t GetDecRad() { return fDec; }
+
+  Double_t GetZA() { return fZA; }
+  Double_t GetAltitude() { return fAlt; }
+  Double_t GetAzimut() { return fAz; }
+  Double_t GetDiameter() { return fDiameter; }
+
+  Double_t GetEcLat() { return fEcLat; }
+  Double_t GetEcLong() { return fEcLong; }
+
+  Double_t GetZADeg() { return fZA/fgDegToRad; }
+  Double_t GetAltitudeDeg() { return fAlt/fgDegToRad; }
+  Double_t GetAzimutDeg() { return fAz/fgDegToRad; }
+
+  Double_t GetDistance(MVPObject* object);
+  Double_t GetDistanceRad(MVPObject* object);
+
+  char* GetObjectName() { return fObjectName; }
+  
+  void Print(Option_t *) const;
+
+  Double_t MJDStartOfYear(UInt_t year);
+
+  ClassDef(MVPObject, 1)
+}; 
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPPlotter.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPPlotter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPPlotter.cc	(revision 9772)
@@ -0,0 +1,587 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner <magicdev@rwagner.de> 12/2002
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MVPPlotter                                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MVPPlotter.h"
+
+#include <stream.h>
+
+#include "TCanvas.h"
+#include "TH1.h"
+#include "TH2.h"
+#include "TPaveText.h"
+#include "TPaveLabel.h"
+#include "TGraph.h"
+#include "TString.h"
+#include "TStyle.h"
+
+#include "MParList.h"
+#include "MVPTime.h"
+
+ClassImp(MVPPlotter);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MVPPlotter::MVPPlotter(const char *name, const char *title) : fUseSun(kTRUE), fUseMoon(kTRUE), fUsePlanets(kTRUE), fAstronomicalDarkness(-18.0)
+{
+  //  fName  = name  ? name  : "MVPPlotter";
+  //  fTitle = title ? title : "Generates visibility histograms and information";
+
+  fgSecPerDay = 86400;
+  fgMJD010170 = 40586; // 01-01-70 is JD 40586
+  fgDegToRad = 2*TMath::Pi()/360;
+
+}
+
+MVPPlotter::~MVPPlotter()
+// --------------------------------------------------------------------------
+//
+// Destructor. Deletes objects if allocated.
+//
+{
+  if (fUseSun) delete fSun;
+  if (fUseMoon) delete fMoon;
+  if (fUsePlanets) {
+    delete fVenus;
+    delete fMars;
+    delete fJupiter;
+    delete fSaturn;
+  }
+}
+   
+void MVPPlotter::SetupObjects()
+// --------------------------------------------------------------------------
+//
+// Create instances for Sun, Moon, Planets if requested.
+//
+{
+  
+  fTime = new MVPTime();
+  fPlist.AddToList(fTime);
+  fPlist.AddToList(fObs);
+
+  if (fObject==NULL) {
+    cout << "You didn't specify an object!" << endl;  
+  }
+
+  fObject->PreProcess(&fPlist);
+  cout << "Processing object " << fObject->GetObjectName() << endl;
+
+  if (fUseSun) {
+    fSun = new MVPObject();
+    fSun->SetObject(0); // Sun
+    fSun->PreProcess(&fPlist);
+    fSun->SetCalcEc(kTRUE);
+  }
+
+  if (fUseMoon) {
+    fMoon = new MVPObject();
+    fMoon->SetObject(3); // Moon
+    fMoon->PreProcess(&fPlist);
+    fMoon->SetCalcEc(kTRUE);
+  }
+
+  if (fUsePlanets) {
+    fVenus = new MVPObject();
+    fVenus->SetObject(2); 
+    fVenus->PreProcess(&fPlist);
+    fVenus->SetCalcEc(kTRUE);
+
+    fMars = new MVPObject();
+    fMars->SetObject(4); 
+    fMars->PreProcess(&fPlist);
+    fMars->SetCalcEc(kTRUE);
+
+    fJupiter = new MVPObject();
+    fJupiter->SetObject(5); 
+    fJupiter->PreProcess(&fPlist);
+    fJupiter->SetCalcEc(kTRUE);
+
+    fSaturn = new MVPObject();
+    fSaturn->SetObject(6); 
+    fSaturn->PreProcess(&fPlist);
+    fSaturn->SetCalcEc(kTRUE);
+  }
+}
+
+// --------------------------------------------------------------------------
+//
+// Plots for a single object and a whole year are generated.
+// 
+// Currently we do the following:
+// - Create a plot MJD vs UTC for one year
+// - Create a plot maxObjHeight vs Week for one year
+// - Create visibility tables for one year (ZA, hours)
+//
+Bool_t MVPPlotter::CalcYear(Int_t year, UInt_t daySlices=96)
+{
+  SetupObjects();
+  
+  UInt_t startday = (UInt_t)fTime->MJDStartOfYear(year);
+  UInt_t stopday  = (UInt_t)fTime->MJDStartOfYear(year+1)-1;
+
+  cout << "Processing period MJD "<< startday << " to MJD "<< stopday  << endl;
+
+  ULong_t startdayROOT = fgSecPerDay * (startday-fgMJD010170);
+  ULong_t stopdayROOT  = fgSecPerDay * (stopday-fgMJD010170);
+      
+  // 2D Plot ZA vs MJD and UTC
+  fMjdUtcYear = new TH2D("fMjdUtcYear", "Visibility of object",
+			  stopday-startday+1,startdayROOT,stopdayROOT, 
+			  daySlices+1,-450,fgSecPerDay+450);
+
+  // Observability hours per day MJD
+  fMjdObsHours = new TH1D("fMjdObsHours", "Observation hours per day",
+			  stopday-startday+1,startdayROOT,stopdayROOT);
+
+  if (fUseMoon) {
+    // 2D Plot ZA of moon vs MJD and UTC
+    fMjdUtcYearMoon =new TH2D("fMjdUtcYearMoon", "Moon ZA",
+     			 stopday-startday+1,startdayROOT,stopdayROOT,
+     			 daySlices+1,-450,fgSecPerDay+450);
+
+    // Moon phase vs MJD
+    fMjdMoonPhase =new TH1D("fMjdMoonPhase", "Moon phase",
+     			 stopday-startday+1,startdayROOT,stopdayROOT);
+    // Moon distance of object vs MJD
+    fMjdMoonDistance =new TH1D("fMjdMoonDistance", "Moon distance",
+     			 stopday-startday+1,startdayROOT,stopdayROOT);
+    // Moon intensity at object vs MJD
+    fMjdMoonIntensity =new TH1D("fMjdMoonIntensity", "Moon intensity at locus of object",
+     			 stopday-startday+1,startdayROOT,stopdayROOT);
+
+  }
+
+  if (fUsePlanets) {
+    // Distance of closest planet vs MJD
+    fMjdPlanetDistance =new TH1D("fMjdPlanetDistance", "PlanetDistance",
+     			 stopday-startday+1,startdayROOT,stopdayROOT);
+  }
+
+   
+  // Array which holds total visibility time for whole year [0] and
+  // each month [1]..[12]
+  Float_t visibility[13][18];
+  memset(visibility, 0, 13*18*sizeof(Float_t));
+  /*
+  for (int m=0;m<13;m++)
+    for (int z=0;z<18;z++)
+      visibility[m][z]=0;
+  */
+  int fday, ftime;
+  Double_t phase=0;	
+  Double_t obsHours;
+
+  for (UInt_t day=startday; day<stopday+1; day++) {     
+    Double_t todaysPhase=0;
+    Double_t moonIntensity;
+    obsHours=0;
+    for (UInt_t i=0; i<daySlices; i++)
+      {	 
+	// Rearrange filling of bins such that a "day" doesn't start at midnight,
+	// but rather at noon. This results in plots in which a "day" covers
+	// a whole night.
+	if (i>=(daySlices/2)) {
+	  fday=day;
+	  ftime=i-(daySlices/2);
+	} else {
+	  fday=day-1;
+	  ftime=i+(daySlices/2);
+	}
+
+	// Objects access fTime via parameter list...
+	fTime->SetMJD(day,(Double_t)i/daySlices);
+
+	if (fUseSun)  fSun->Process();
+	if (fUseMoon) fMoon->Process();
+
+	if (fUseSun && fUseMoon) {
+
+	  // Calculate moon phase...
+	  phase = fSun->GetEcLong() - fMoon->GetEcLong();	 
+	  phase = TMath::Pi()-(acos(cos(phase)*cos(fMoon->GetEcLat())));
+	  phase = phase*180/TMath::Pi();
+	  todaysPhase+=phase;
+      
+	}
+	
+	// If sun is not up (or we should not use sun information...)
+	if (fSun->GetAltitudeDeg() < fAstronomicalDarkness) {
+	  // Calculate Position of object:	  
+	  fObject->Process();		 	 	    
+
+	  // Calculate moon brightness at locus of object
+	  // now this is gonna be fun...
+
+	  /* Evaluates predicted LUNAR part of sky brightness, in
+	   * V magnitudes per square arcsecond,
+	   */
+
+	  moonIntensity = LunSkyBright(phase/180, fObject->GetDistance(fMoon),
+						fMoon->GetAltitudeDeg(), fObject->GetAltitudeDeg());
+	  fMjdMoonIntensity->Fill(fgSecPerDay*(fday-fgMJD010170),moonIntensity);
+
+	
+
+	  // If moon is not up (or we should not use moon information...)
+	  if (!fUseMoon || fMoon->GetAltitudeDeg()<=0 || moonIntensity<60) {
+	    // Fill MJD-UTC histogram
+	    fMjdUtcYear->Fill(fgSecPerDay*(fday-fgMJD010170),fgSecPerDay*ftime/daySlices,fObject->GetAltitudeDeg());
+	  }
+	  
+	  // Sum up visibility time (only if moon not visible or moon
+	  // info shouldn't be used at all)
+	  if ((!fUseMoon)||(fMoon->GetAltitudeDeg()<=0)||(moonIntensity<60)) {
+	    // Calculate 
+	    for (int z=0;z<18;z++) {
+	      if (fObject->GetAltitudeDeg()>(z*5)) {
+		visibility[0][z]+=(Double_t)(60*24/daySlices);
+		visibility[(Int_t)fTime->GetMonth()][z]+=(Double_t)(60*24/daySlices);
+	      }
+	    }	//for
+	  
+	    if ((fObject->GetAltitudeDeg())>40) {
+	      fMjdObsHours->Fill(fgSecPerDay*(fday-fgMJD010170),(Double_t)(24/(Double_t)daySlices));
+	    }
+
+	  }
+
+	 
+	} //fi sun 	 	  
+
+	// Optional: Fill histo with moon-up times...
+	// if (fMoon->GetAltitudeDeg() >0) 
+	// fMjdUtcYearMoon->Fill(fgSecPerDay*(day-fgMJD010170),fgSecPerDay*i/daySlices,phase);	
+	// fMoon->Process();
+	// Double_t phase;	
+	// phase = fSun->GetEcLong() - moon->GetEcLong();	 
+	// phase = TMath::Pi()-(acos(cos(phase)*cos(moon->GetEcLat())));
+	// cout << "Phase: " << phase*180/TMath::Pi() << endl;
+	
+      } //for daySlices
+
+    // Distance of Venus to object
+
+    if (fUsePlanets) {
+      fVenus->Process();
+      fMars->Process();
+      fJupiter->Process();
+      fSaturn->Process();
+
+      Double_t distance = fVenus->GetDistance(fObject);
+      distance = TMath::Min(distance, fMars->GetDistance(fObject));
+      distance = TMath::Min(distance, fJupiter->GetDistance(fObject));
+      distance = TMath::Min(distance, fSaturn->GetDistance(fObject));
+
+      fMjdPlanetDistance->Fill(fgSecPerDay*(fday-fgMJD010170),distance);      
+    }
+
+    fMjdMoonPhase->Fill(fgSecPerDay*(fday-fgMJD010170),todaysPhase/i);
+    fMjdMoonDistance->Fill(fgSecPerDay*(fday-fgMJD010170),fMoon->GetDistance(fObject));
+
+    
+  } //for days
+
+    
+  // Here we print the tables with visibilities...
+  cout << "Visibility time [hours]: " << endl;
+   
+  for (int z=1;z<17;z++) {
+    if (visibility[0][z]==0) break;
+    printf("Alt>%2d|%6d|",z*5,(Int_t)(visibility[0][z]/60));      
+    for (int m=1;m<13;m++) {
+      printf("%5d ",(Int_t)(visibility[m][z]/60));	
+    }
+    printf("\n");
+  }
+  
+  int vistimestart=0;
+  int vistimeend=0;  
+  for (int m=1; m<13; m++) {
+    int n = (m==1 ? 12 : m-1);
+    if (visibility[m][8]/60>20 && visibility[n][8]/60<=20) {
+      vistimestart=m; // we're on the rising slope
+    }
+  }
+  
+  for (int m=1; m<13; m++) {
+    int n = (m==1 ? 12 : m-1);
+    if (visibility[m][8]/60<20 && visibility[n][8]/60>=20) {
+      vistimeend=n; // we're on the falling slope
+    }
+  }
+  
+  cout << "Visibility (Alt>40) during months: " << vistimestart << "-" << vistimeend << " approx " << visibility[0][8]/60 << "hrs" <<endl;
+
+
+  /*!!!!!!!!!!!!!!!!!!!!!!!*/gROOT->Reset();
+
+  TCanvas *cMjdUtcYear = new TCanvas("cMjdUtcYear", "Object Visibility MjdUtcYear", 1100,500);
+  cMjdUtcYear->cd(0);
+
+  gStyle->SetPalette(1);
+  //  gStyle->SetOptStat(0);
+  gStyle->SetOptFit(0);
+  gStyle->SetFillStyle(0);
+  gStyle->SetFillColor(10);
+  gStyle->SetCanvasColor(10);
+  gStyle->SetDrawBorder(0);
+  gStyle->SetPadColor(10);
+  gStyle->SetPadBorderSize(0);
+  gStyle->SetPadLeftMargin(0.12);
+  gStyle->SetTitleYOffset(1.2);
+  gStyle->SetTitleXOffset(1.2);
+  
+  gStyle->SetPadLeftMargin(0.01);
+  gStyle->SetPadRightMargin(0.1);
+  gStyle->SetPadTopMargin(0.03);
+  gStyle->SetPadBottomMargin(0.12);
+  
+  fMjdUtcYear->SetTitle(fObject->GetObjectName());
+  fMjdUtcYear->GetXaxis()->SetTimeDisplay(1);
+  fMjdUtcYear->GetXaxis()->SetTimeFormat("%b %y");
+  fMjdUtcYear->GetYaxis()->SetTimeDisplay(1);
+  fMjdUtcYear->GetYaxis()->SetTimeFormat("%Hh");
+  gStyle->SetTimeOffset(43200);
+  fMjdUtcYear->GetYaxis()->SetLabelOffset(0.01);
+  fMjdUtcYear->SetMinimum(0);
+  fMjdUtcYear->SetMaximum(90);
+  
+  fMjdUtcYear->GetYaxis()->SetTitle("Hour");
+  fMjdUtcYear->GetXaxis()->SetTitle("Day of year");
+  fMjdUtcYear->GetZaxis()->SetTitle("Altitude");
+  fMjdUtcYear->Draw("SURF2BB9Z");
+  gPad->SetPhi(0);
+  gPad->SetTheta(90);
+  gPad->Modified();
+  
+  TPaveText *pt = new TPaveText(-0.74,-0.35,-0.58,0.52,"");  
+  char ptLine[80];
+  pt->AddText("Visibility time [hrs]:");
+  pt->SetTextAlign(13);
+  pt->SetFillStyle(0);
+  pt->SetBorderSize(0);
+  pt->SetTextFont(42);
+  for (int j=1;j<17;j++) {
+    sprintf (ptLine, "Alt>%i: %i", j*5, (Int_t)visibility[0][j]/60);
+    pt->AddText(ptLine);
+    if (visibility[0][j]==0) break;
+  }
+  pt->Draw();
+
+
+  if (fUseMoon) {
+    TCanvas *cMjdMoon = new TCanvas("cMjdMoon", "the Moon phase", 600,600);
+    gStyle->SetOptTitle(1);
+    cMjdMoon->Divide(1,3);
+    cMjdMoon->cd(1);
+    fMjdMoonPhase->Draw();
+    cMjdMoon->cd(2);
+    fMjdMoonDistance->Draw();
+    cMjdMoon->cd(3);
+    fMjdMoonIntensity->Draw();
+  }
+
+  TCanvas *cObsHours = new TCanvas("cObsHours", "ObsHours per day", 600,400);
+  fMjdObsHours->Draw();
+
+
+
+  if (fUsePlanets) {
+    TCanvas *cMjdPlanets = new TCanvas("cMjdPlanets", "the distance to planets", 600,200);
+    cMjdPlanets->cd(0);
+    fMjdPlanetDistance->Draw();
+  }
+
+    
+  // next histogram
+  Float_t objectHeight[55];
+  Float_t simpleCounter[55];
+  Int_t weekCounter=0;
+  
+  simpleCounter[weekCounter]=0;
+  objectHeight[weekCounter]=0;
+  weekCounter++;
+  
+  const Int_t startday2 = fTime->MJDStartOfYear(year);
+  const Int_t stopday2  = fTime->MJDStartOfYear(year+1)-1;
+  
+    for (int day=startday2; day<stopday2+1; day+=7)
+    {
+        simpleCounter[weekCounter]=weekCounter-1;
+        objectHeight[weekCounter]=0;
+        for (int i=0; i<daySlices; i++)
+        {
+            if (i>=48)
+            {
+                fday=day;
+                ftime=i-48;
+            }
+            else
+            {
+                fday=day-1;
+                ftime=i+48;
+            }
+
+            fTime->SetMJD(day,(Double_t)i/daySlices);
+            fObject->Process();
+            fSun->Process();
+
+            if (fSun->GetAltitudeDeg() < -25.0)
+            {
+                if (objectHeight[weekCounter]<(fObject->GetAltitudeDeg()))
+                    objectHeight[weekCounter]=fObject->GetAltitudeDeg();
+            }
+
+        } //i
+        weekCounter++;
+    } //day
+    simpleCounter[weekCounter]=weekCounter-2;
+    objectHeight[weekCounter]=0;
+    weekCounter++;
+
+    TString months[12] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
+
+    TCanvas *c2 = new TCanvas("c2", "Object Visibility",600,100);
+ 
+    //  gStyle->SetOptTitle(0);
+    //   gStyle->SetPadLeftMargin(0.000001);
+    //   gStyle->SetPadRightMargin(0.000001);
+    //   gStyle->SetPadTopMargin(0.001);
+    //   gStyle->SetPadBottomMargin(0.000001);
+    gPad->SetGrid();
+
+    c2->SetGrid();
+    TGraph *tg=new TGraph(weekCounter,simpleCounter,objectHeight);
+
+    tg->SetMinimum(1);
+    tg->SetMaximum(90);
+
+    Double_t maxza = abs(fObject->GetDec()-fObs->GetLatitude());
+
+    if (maxza > 90) maxza=90;
+    if (maxza < 0) maxza=00;
+
+    cout << "MaxZA:    ";
+    cout << maxza << endl;
+
+    if (maxza < 30) { //colors=green to yellow
+        maxza *= 9/30;
+        maxza += 80;
+
+    } else { //colors=yellow to red
+        maxza -= 30;
+        maxza *= 11/60;
+        maxza += 89;
+    }
+
+  tg->SetFillColor((Int_t)maxza);
+  tg->SetLineColor((Int_t)maxza);
+  tg->SetLineWidth((Int_t)maxza);
+  tg->Draw("AF");
+  
+  tg->GetXaxis()->SetLimits(0,52);
+  tg->GetXaxis()->SetTickLength(0.1);
+  tg->GetXaxis()->SetNdivisions(0);
+  tg->GetYaxis()->SetNdivisions(202);
+  
+  TPaveLabel* l= new TPaveLabel(2,46,35,88, fObject->GetObjectName());
+  l->SetBorderSize(0);
+  l->SetFillStyle(0);
+  l->SetTextAlign(12);
+  l->Draw();
+  
+  if ((vistimestart<13)&&(vistimeend>0)) {
+    TString label=months[vistimestart-1]+"-"+months[vistimeend-1];
+    TPaveLabel* l2= new TPaveLabel(35,46,50,88, label);
+    l2->SetBorderSize(0);
+    l2->SetFillStyle(0);
+    l2->SetTextAlign(32);
+    l2->Draw();
+    
+  }
+  
+  c2->Modified();
+  c2->Update();
+  
+  return kTRUE;
+}
+
+Double_t MVPPlotter::LunSkyBright(Double_t moon_phase,Double_t rho,Double_t altmoon,Double_t alt)
+{
+/* Evaluates predicted LUNAR part of sky brightness, in
+ * V magnitudes per square arcsecond, following K. Krisciunas
+ * and B. E. Schaeffer (1991) PASP 103, 1033.
+ *
+ * moon_phase  = Phase of the Moon, between 0. (no moon) and 1. (full moon),
+ * rho (deg)   = separation of moon and object,
+ * altmoon (deg) = altitude of moon above horizon,
+ * alt (deg)   = altitude of object above horizon
+ */
+
+    double kzen=1.;
+
+    double rho_rad = rho*fgDegToRad;
+    double alpha = 180.*(1. - moon_phase);
+    double Zmoon = (90. - altmoon)*fgDegToRad;
+    double Z = (90. - alt)*fgDegToRad;
+
+    double istar = -0.4*(3.84 + 0.026*fabs(alpha) + 4.0e-9*pow(alpha,4.)); /*eqn 20*/
+    istar =  pow(10.,istar);
+    if(fabs(alpha) < 7.)   /* crude accounting for opposition effect */
+	istar *= 1.35 - 0.05 * fabs(istar);
+	/* 35 per cent brighter at full, effect tapering linearly to
+	   zero at 7 degrees away from full. mentioned peripherally in
+	   Krisciunas and Scheafer, p. 1035. */
+    double fofrho = 229087. * (1.06 + cos(rho_rad)*cos(rho_rad));
+    if(fabs(rho) > 10.)
+        fofrho+=pow(10.,(6.15 - rho/40.));            /* eqn 21 */
+    else if (fabs(rho) > 0.25)
+        fofrho+=6.2e7 / (rho*rho);   /* eqn 19 */
+    else fofrho = fofrho+9.9e8;  /*for 1/4 degree -- radius of moon! */
+
+    double Xzm = sqrt(1.0 - 0.96*sin(Zmoon)*sin(Zmoon));
+
+    if(Xzm != 0.) Xzm = 1./Xzm;
+    else Xzm = 10000.;
+
+    double Xo = sqrt(1.0 - 0.96*sin(Z)*sin(Z));
+    if(Xo != 0.) Xo = 1./Xo;
+    else Xo = 10000.;
+
+    double Bmoon = fofrho * istar * pow(10.,(-0.4*kzen*Xzm))
+        * (1. - pow(10.,(-0.4*kzen*Xo)));   /* nanoLamberts */
+    //    cout << " Bmoon=" << Bmoon;
+    if(Bmoon > 0.001)
+      return(Bmoon); 
+    else return(99999.);
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPPlotter.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPPlotter.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPPlotter.h	(revision 9772)
@@ -0,0 +1,77 @@
+#ifndef MARS_MVPPlotter
+#define MARS_MVPPlotter
+
+#ifndef MARS_MTaskList
+#include "MTaskList.h"
+#endif
+
+#ifndef MARS_MVPObject
+#include "MVPObject.h"
+#endif
+
+#ifndef MARS_MVPTime
+#include "MVPTime.h"
+#endif
+
+#ifndef MARS_MObservatoryLocation
+#include "MObservatoryLocation.h"
+#endif
+
+class TH1D;
+class TH2D;
+class TCanvas;
+
+class MVPPlotter
+{
+private:
+
+  MVPTime   *fTime;
+  MObservatoryLocation *fObs;
+
+  MParList fPlist;
+  MTaskList fTlist;
+
+  Bool_t fUseSun;
+  Bool_t fUseMoon;
+  Bool_t fUsePlanets;
+
+  Double_t fAstronomicalDarkness;
+
+  Int_t fgSecPerDay;
+  Int_t fgMJD010170; // 01-01-70 is JD 40586
+  Double_t fgDegToRad;
+
+  TH2D *fMjdUtcYear;
+  TH2D *fMjdUtcYearMoon;
+  TH1D *fMjdMoonPhase;
+  TH1D *fMjdMoonDistance;
+  TH1D *fMjdPlanetDistance;
+  TH1D *fMjdMoonIntensity;
+  TH1D *fMjdObsHours;
+
+  MVPObject *fObject;
+  MVPObject *fSun;
+  MVPObject *fMoon;
+  MVPObject *fVenus;
+  MVPObject *fMars;
+  MVPObject *fJupiter;
+  MVPObject *fSaturn;
+
+  void SetupObjects();
+
+public:
+    MVPPlotter(const char *name=NULL, const char *title=NULL);
+    ~MVPPlotter();
+
+    void SetObject(MVPObject *o) { fObject=o; }
+    void SetObservatory(MObservatoryLocation *l) { fObs=l; }
+    void SetAstronomicalDarkness(Double_t d) { fAstronomicalDarkness=d; }
+
+    Double_t LunSkyBright(Double_t moon_phase,Double_t rho,Double_t altmoon,Double_t alt);
+    Bool_t CalcYear(Int_t year, UInt_t daySlices);
+
+    ClassDef(MVPPlotter, 2) // Visibility Plotter: The Plotter Routine itself
+}; 
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPTime.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPTime.cc	(revision 9772)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Robert Wagner  11/2002 <mailto:magicsoft@rwagner.de>
+!
+!   Copyright: MAGIC Software Development, 2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MVPTime                                                                 //
+//                                                                         //
+// Time Container used by the visibility plotter storing times in MJD      //
+//                                                                         //
+// This is a simple time container for the Visibility Plotter. It takes    //
+// "normal" or MJD-formatted time, converts it to MJD and can return MJD.  //
+//                                                                         //
+// The astronomical algorithms used are taken from SLALIB 2.4-8.           //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MVPTime.h"
+
+#include <slalib.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MVPTime);
+
+MVPTime::MVPTime(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MVPTime";
+    fTitle = title ? title : "Storage container for time";      
+}
+
+MVPTime::~MVPTime()
+{
+  // do nothing special.
+}
+
+void MVPTime::SetTime(UInt_t yr, UInt_t mo, UInt_t dy, UInt_t hr, UInt_t mi, UInt_t se)
+{
+  fUT1 = CalendarToUT1(yr, mo, dy, hr, mi, se);  
+  fYear = yr;
+  fMonth = mo;
+  fDay = dy;
+}
+
+void MVPTime::SetMJD(Double_t mjd, Double_t fracMjd)
+{
+  fUT1 = mjd + fracMjd;
+  Double_t fd;
+  Int_t status;
+  slaDjcl (mjd, &fYear, &fMonth, &fDay, &fd, &status);  
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Double_t MVPTime::CalendarToUT1(UInt_t yr, UInt_t mo, UInt_t dy, UInt_t hr, UInt_t mi, UInt_t se)
+{
+  int status;
+  Double_t mjd;
+  slaCldj(yr, mo, dy, &mjd, &status); 
+  switch (status)
+    {
+    case 1:
+      *fLog << "CalendarToMJD Warn: bad year" << endl;
+      break;
+    case 2:
+      *fLog << "CalendarToMJD Warn: bad month" << endl;
+      break;
+    case 3:
+      *fLog << "CalendarToMJD Warn: bad day" << endl;
+      break;
+    }
+  
+  mjd += ((Double_t)hr/24) + ((Double_t)mi/(24*60)) + ((Double_t)se/(24*60*60));
+  return mjd;
+}
+
+// --------------------------------------------------------------------------
+//
+//
+Double_t MVPTime::MJDStartOfYear(UInt_t year)
+{
+  int status;
+  Double_t mjd;
+  slaCldj(year, 1, 1, &mjd, &status); 
+  switch (status)
+    {
+    case 1:
+      *fLog << "CalendarToMJD Warn: bad year" << endl;
+      break;
+    case 2:
+      *fLog << "CalendarToMJD Warn: bad month" << endl;
+      break;
+    case 3:
+      *fLog << "CalendarToMJD Warn: bad day" << endl;
+      break;
+    }
+  return mjd;
+}
+
+void MVPTime::Print(Option_t *) const
+{
+  *fLog << all;
+  *fLog << "Time (MJD) is: " << fUT1 << endl;
+}
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPTime.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MVPTime.h	(revision 9772)
@@ -0,0 +1,37 @@
+#ifndef MARS_MVPTime
+#define MARS_MVPTime
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MVPTime : public MParContainer
+{
+private:
+  Double_t fUT1;
+  Int_t fYear;
+  Int_t fMonth;
+  Int_t fDay;
+  Double_t MVPTime::CalendarToUT1(UInt_t yr, UInt_t mo, UInt_t dy, UInt_t hr, UInt_t mi, UInt_t se);
+ 
+public:
+  MVPTime(const char *name=NULL, const char *title=NULL);
+  ~MVPTime();
+
+  void SetTime(UInt_t yr, UInt_t mo, UInt_t dy, UInt_t hr, UInt_t mi, UInt_t se);
+  void SetMJD(Double_t mjd, Double_t fracMjd = 0);
+  inline Double_t GetMJD() { return fUT1; }
+
+  void Print(Option_t *) const;
+
+  Double_t MJDStartOfYear(UInt_t year);
+  Double_t GetYear() { return fYear; }
+  Double_t GetMonth() { return fMonth; }
+  Double_t GetDay() { return fDay; }
+  
+  ClassDef(MVPTime, 1)
+
+};
+
+#endif
+
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/Makefile	(revision 9772)
@@ -0,0 +1,57 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../../../../Makefile.conf.$(OSTYPE)
+include ../../../../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+CINT     = Pisa
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../../../../mbase \
+	   -I../../../../mjobs \
+	   -I../../../../mpedestal \
+	   -I../../../../mbadpixels \
+	   -I../../../../mfileio \
+           -I../../../../mraw \
+           -I../../../../manalysis \
+	   -I../../../../mgui \
+	   -I../../../../mgeom \
+	   -I../../../../msignal \
+	   -I../../../../mcalib \
+	   -I../../../../mfilter \
+	   -I../../../../mhbase \
+	   -I../../../../mimage \
+	   -I../../../../mpointing \
+	   -I../../../../mcamera \
+	   -I../../../../mhist \
+	   -I../../../../mmc \
+	   -I../../../../mreport \
+	   -I../../../../mastro \
+           -I../../../../mstarcam
+
+SRCFILES = \
+        ./MFindStars.cc \
+        ./MTelAxisFromStars.cc \
+        ./MHTelAxisFromStars.cc \
+        ./MSkyCamTrans.cc \
+        ./MSourceDirections.cc \
+        ./MStarLocalCam.cc \
+        ./MStarLocalPos.cc
+
+
+############################################################
+
+all: $(OBJS)
+
+include ../../../../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MispointingLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MispointingLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mispointing/MispointingLinkDef.h	(revision 9772)
@@ -0,0 +1,15 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MFindStars+;
+#pragma link C++ class MTelAxisFromStars+;
+#pragma link C++ class MHTelAxisFromStars+;
+#pragma link C++ class MSkyCamTrans+;
+#pragma link C++ class MSourceDirections+;
+#pragma link C++ class MStarLocalCam+;
+#pragma link C++ class MStarLocalPos;
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerBit.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerBit.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerBit.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerBit
+//   This class stores the information about the L2 output Bit rates
+//   
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerBit.h"
+
+ClassImp(MTriggerBit);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerBit.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerBit.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerBit.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MTriggerBit
+#define MARS_MTriggerBit
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MTriggerBit : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+
+private:
+    
+    static const Int_t gsNBits=20;        // number of output bits
+
+    TArrayF fBit; // Array with the output bit rates
+
+public:
+    MTriggerBit() : fBit(gsNBits)  
+    {
+        fName  = "MTriggerBit";
+        fTitle = "Container for the L2 output bits rates ";
+    }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNBits)
+	return kFALSE;
+
+      val = fBit[idx];	
+
+      return val>0;
+    }
+
+    Double_t operator[](const Int_t idx) 
+      {  
+	if (idx > gsNBits)
+	  return kFALSE;
+	
+	return fBit[idx]; 
+      }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerBit, 1) // Container for the L2 output bits rates
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerCell.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerCell.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerCell.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerCell
+//   This class stores the information about the Trigger Cell Rates
+//   
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerCell.h"
+
+ClassImp(MTriggerCell);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerCell.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerCell.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerCell.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MTriggerCell
+#define MARS_MTriggerCell
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MTriggerCell : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+private:
+    static const Int_t gsNCells=32; //Number of fields with cell rates
+                                    // 19 cells and 12 dummy 
+
+    TArrayF fCellRate;       // Array of the measured L1 cell rates
+
+public:
+    MTriggerCell() : fCellRate(gsNCells)
+    {
+        fName  = "MTriggerCell";
+        fTitle = "Container for the measured cell rates";
+    }
+
+    Float_t GetMean() const { return fCellRate.GetSum()/fCellRate.GetSize(); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNCells)
+	return kFALSE;
+      
+      val = fCellRate[idx];
+        return val>0;
+    }
+
+    Double_t operator[](const Int_t idx) 
+      { 
+	if (idx > gsNCells)
+	  return kFALSE;
+	
+	return fCellRate[idx]; 
+      }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerCell, 1) // Container for the trigger cell rates
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerIPR.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerIPR.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerIPR.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerIPR
+//   This class stores the information about the Individual Pixel Rates
+//   
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerIPR.h"
+
+ClassImp(MTriggerIPR);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerIPR.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerIPR.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerIPR.h	(revision 9772)
@@ -0,0 +1,56 @@
+#ifndef MARS_MTriggerIPR
+#define MARS_MTriggerIPR
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerIPR : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+private:
+    TArrayL fIPR;            // [Hz] IPR (Individual Pixel Rates)
+    
+    static const Int_t gsNTrigPix=397;  // number of trigger pixels
+
+public:
+    MTriggerIPR() : fIPR(gsNTrigPix)
+    {
+        fName  = "MTriggerIPR";
+        fTitle = "Container for the Individual Pixel Rate (IPR)";
+    }
+
+    Float_t GetMean() const { return fIPR.GetSum()/fIPR.GetSize(); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNTrigPix)
+	return kFALSE;
+
+      val = fIPR[idx];
+      return val>0;
+    }
+
+    Double_t operator[](const Int_t idx) 
+      {
+	if (idx > gsNTrigPix)
+	  return kFALSE;
+
+	return fIPR[idx]; 
+      } 
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerIPR, 1) // Container for the Individual Pixel Rate (IPR)
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerLiveTime.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerLiveTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerLiveTime.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerLiveTime
+//   This class stores the information about the livetime and deadtime
+//   measured by the scalers 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerLiveTime.h"
+
+ClassImp(MTriggerLiveTime);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerLiveTime.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerLiveTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerLiveTime.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MTriggerLiveTime
+#define MARS_MTriggerLiveTime
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerLiveTime : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+
+private:
+    static const Int_t gsNScalers=5;        // number of scalers
+
+    TArrayL fLiveTime; // Array with the livetime
+    TArrayL fDeadTime; // Array with the deadtime
+
+public:
+    MTriggerLiveTime() : fLiveTime(gsNScalers), fDeadTime(gsNScalers)  
+    {
+        fName  = "MTriggerLiveTime";
+        fTitle = "Container for the Live-deadtime      ";
+    }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNScalers)
+	return kFALSE;
+
+      val = fLiveTime[idx];	
+
+      return val>0;
+    }
+
+    Double_t operator[](const Int_t idx) 
+      {  	
+	if (idx > gsNScalers)
+	  return -1;
+	
+	return fLiveTime[idx]; 
+      }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerLiveTime, 1) // Container for the Live-Deadtime
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerPrescFact.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerPrescFact.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerPrescFact.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it> 
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerPrescFact
+//   This class stores the information about the L2 prescaling factors
+//   
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerPrescFact.h"
+
+ClassImp(MTriggerPrescFact);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerPrescFact.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerPrescFact.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/MTriggerPrescFact.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MTriggerPrescFact
+#define MARS_MTriggerPrescFact
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerPrescFact : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+
+private:
+    
+    static const Int_t gsNPrescFacts=8;        // number of factors
+
+    TArrayL fPrescFact; // Array with the prescaling factors
+
+public:
+    MTriggerPrescFact() : fPrescFact(gsNPrescFacts)  
+    {
+        fName  = "MTriggerPrescFact";
+        fTitle = "Container for the L2 Prescaling Factors      ";
+    }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx > gsNPrescFacts)
+	return kFALSE;
+
+      val = fPrescFact[idx];	
+
+      return val>0;
+    }
+
+    Double_t operator[](const Int_t idx) 
+      {  
+	if (idx > gsNPrescFacts)
+	  return kFALSE;
+	
+	return fPrescFact[idx]; 
+      }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerPrescFact, 1) // Container for the L2 Prescaling Factors
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/Makefile	(revision 9772)
@@ -0,0 +1,35 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Trigger
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui
+
+SRCFILES = MTriggerIPR.cc \
+	   MTriggerCell.cc\
+	   MTriggerBit.cc\
+	   MTriggerPrescFact.cc\
+	   MTriggerLiveTime.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/TriggerIncl.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/TriggerIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/TriggerIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/TriggerLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/TriggerLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/classes/mtrigger/TriggerLinkDef.h	(revision 9772)
@@ -0,0 +1,13 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MTriggerIPR+;
+#pragma link C++ class MTriggerCell+;
+#pragma link C++ class MTriggerBit+;
+#pragma link C++ class MTriggerPrescFact+;
+#pragma link C++ class MTriggerLiveTime+;
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/AlphaPlot.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/AlphaPlot.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/AlphaPlot.C	(revision 9772)
@@ -0,0 +1,63 @@
+void AlphaPlot(TString onsource="hillas_Mrk421.root", TString offsource="hillas_OffMrk421.root")
+{
+  const Int_t kMinDeg = 25;
+
+  Int_t i;
+  Float_t EvtOn = 0;
+  Float_t EvtOff = 0;
+
+  TH1F *hon = new TH1F("hon","On Source Histogram",19,0,95);
+  TH1F *hoff = new TH1F("hoff","Off Source Histogram",19,0,95);
+  TH1F *htemp;
+
+  fon = new TFile(onsource,"READ");
+
+  htemp = (TH1F *)fon->FindObjectAny("hAlpha");
+  
+  for(i=0;i<19;i++)
+    hon->SetBinContent(i,htemp->GetBinContent(i));
+
+  for(i=0;i<hon->GetNbinsX();i++){
+    if(hon->GetBinCenter(i) > kMinDeg)
+      EvtOn += hon->GetBinContent(i);
+  }
+
+  fon->Close();
+
+  foff = new TFile(offsource,"READ");
+
+  htemp = (TH1F *)foff->FindObjectAny("hAlpha");
+  for(i=0;i<19;i++)
+    hoff->SetBinContent(i,htemp->GetBinContent(i));
+
+  for(i=0;i<hoff->GetNbinsX();i++){
+    if(hoff->GetBinCenter(i) > kMinDeg)
+      EvtOff += hoff->GetBinContent(i);
+  }
+
+  foff->Close();
+
+  Float_t norm = EvtOn/EvtOff;
+  cout << "EvtOn/EvtOff = " << norm << endl;
+
+  Float_t eccessi = 0;
+  Float_t Noff = 0;
+
+  TH1F *hAlphaPlot = new TH1F("hAlphaPlot","Alpha Plot", 19,0,95);
+  for(i=0; i<hon->GetNbinsX(); i++){
+    hAlphaPlot->SetBinContent(i,hon->GetBinContent(i)-hoff->GetBinContent(i)*norm);
+    if(hAlphaPlot->GetBinCenter(i) < 15){
+      eccessi += hAlphaPlot->GetBinContent(i);
+      Noff += norm*hoff->GetBinContent(i);
+    }
+  }
+
+  cout << "Eccessi = " << eccessi << "   Nsigma = " << eccessi/(TMath::Sqrt(Noff)) <<endl;
+
+  new TCanvas("Alpha On","Alpha plot ON source");
+  hon->DrawCopy();
+  new TCanvas("Alpha Off","Alpha plot OFF source");
+  hoff->DrawCopy();
+  new TCanvas("Alpha","Resulting alpha plot");
+  hAlphaPlot->DrawCopy();
+}
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/AnalCurrents.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/AnalCurrents.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/AnalCurrents.C	(revision 9772)
@@ -0,0 +1,257 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 04/2004 <mailto:jlopez@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/*
+#include <iostream>
+#include <stdlib.h>
+#include <string.h>
+#include <TString.h>
+#include <TArrayS.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MGeomCamMagic.h"
+#include "MCameraDC.h"
+
+#include "MReadReports.h"
+#include "MGeomApply.h"
+#include "MEvtLoop.h"
+*/
+const Int_t gsNpix = 577;
+MGeomCamMagic geomcam;
+
+using namespace std;
+
+void AnalCurrents(const TString filename)
+{
+    //UInt_t numEvents = 1000000;
+    UInt_t numEvents = 1;
+    
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;  
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+    
+    
+    MCameraDC     dccam;
+    
+    plist.AddToList(&geomcam);
+    plist.AddToList(&dccam);
+    
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    // Reads the trees of the root file and the analysed branches
+    MReadReports read;
+    read.AddTree("Currents"); 
+    read.AddFile(filename);     // after the reading of the trees!!!
+    read.AddToBranchList("MReportCurrents.*");
+    
+    MGeomApply geomapl;
+    
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&read);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+     
+    MCerPhotEvt dcevt;
+    
+    const Int_t NSteps = 5;  // Number of steps to average DC over events
+    Int_t count = 0;         // counter for averaging NSteps events
+    Int_t NumAverEvt = 1;    // counter for averaged events stored into dcevt
+    Double_t val[gsNpix];    // array for managing the averaging of gsNpix
+                             // DC values over NSteps events
+
+    // Initialize to 0 array val
+    for(Int_t i=0; i<gsNpix; i++)
+	val[i] = 0.0;
+    //
+    // Execute your analysis
+    //
+    //if (!evtloop.Eventloop(numEvents))
+    //  return kFALSE;
+    if (!evtloop.PreProcess())
+	return;
+    
+    while (tlist.Process())
+    {
+	++count;
+	for(Int_t i=0; i<gsNpix; i++)
+	{
+	    val[i] += dccam.GetCurrent(i);
+
+	    if( (count%NSteps) == 0 )
+	    {
+		dcevt.AddPixel(i,val[i]/(Double_t)NSteps,0);
+		dcevt.GetPixelContent(val[i],i,geomcam,0);
+		val[i] = 0.0;
+	    }
+	}
+
+	// Reset count and call findstar function on this macroevent
+	if( (count%NSteps) == 0 )
+	{
+	    count = 0;
+	    ++NumAverEvt;
+	    cout << "Calling test_findstar function" << endl;
+	    test_findstar(&dcevt);
+	}
+    }
+
+    // Last loop overall pixels to fill with the average 
+    // of last count events
+    if(count!=0)
+    {
+	for(Int_t i=0; i<gsNpix; i++)
+	    dcevt.AddPixel(i,val[i]/(Double_t)count,0);
+
+	cout << "Calling test_findstar function" << endl;
+	test_findstar(&dcevt);
+    }
+
+    cout << "Number of averaged events stored into container = " << NumAverEvt << endl;
+    tlist.PrintStatistics();
+    
+}
+
+
+// This macro creates a fake MCerPhotEvt container (with some clusters
+// that simulate the starfield seen by the DC currents) and then applies
+// the image cleaning and the Hillas algorithm to recognize and classify
+// the clusters.
+//
+void test_findstar(MCerPhotEvt *wDCEvt)
+{
+    //MGeomCamMagic *geom; 
+    MCerPhotEvt *DCEvt = new MCerPhotEvt();
+    Int_t cluster[gsNpix];
+    Float_t startp[gsNpix];
+    
+    memset(cluster,-1,gsNpix);
+    memset(startp,-1,gsNpix);
+    
+    TVectorD *startpixs = new TVectorD();
+    Double_t tempDC;
+    Int_t pixid;
+    // fill a fake MCerPhotEvt 
+    // loop over all pixels
+    for (pixid=0; pixid<gsNpix ; pixid++)
+    {
+	switch (pixid)
+	{
+	    case 9:
+		DCEvt->AddPixel(pixid,1.1,0.0);
+		break;
+	    case 2:
+	    case 8:
+	    case 21:
+	    case 22:
+	    case 23:
+	    case 10:
+		DCEvt->AddPixel(pixid,1.1,0.0);
+		break;
+	    case 39:
+		DCEvt->AddPixel(pixid,1.2,0.0);
+		break;
+	    case 64:
+		DCEvt->AddPixel(pixid,1.71,0.0);
+		break;
+	    case 65:
+		DCEvt->AddPixel(pixid,1.70,0.0);
+		break;
+	    case 40:
+		DCEvt->AddPixel(pixid,1.72,0.0);
+		break;
+	    default:
+		DCEvt->AddPixel(pixid);
+		break;
+	}
+    } // end loop over pixels
+
+    if(!(FindStartPixels(wDCEvt, startpixs)))
+	cout << "ARGH!@!! In function FindStartPixel(): no starting pixel found" << endl;
+    
+}
+
+Int_t FindStartPixels(MCerPhotEvt *evt, TVectorD *startpixs)
+{
+    Double_t currDC;
+    Int_t i = 0;
+    Double_t DCthr = 10.0;
+    
+    MCerPhotPix *dcpix;
+    MGeomPix *pix;
+    
+    // look for all the pixels with a DC higher than the DC of neighbour pixels 
+    // loop over all pixels
+    for (Int_t pixid=0; pixid<gsNpix; pixid++)
+    {
+	Double_t tempDC;
+
+	pix = (MGeomPix *)geomcam[pixid]; // MGeomCamMagic pixel
+	
+	// Get the DC value of the current pixel
+	evt->GetPixelContent(currDC,pixid,geomcam,0);
+	
+	Float_t maxDC = 0.0;
+	// look for the max DC in the neighbors pixels
+	for (Int_t j=0; j < pix->GetNumNeighbors(); j++)
+	{
+	    evt->GetPixelContent(tempDC,pix->GetNeighbor(j),geomcam,0);
+	    if(tempDC > maxDC) 
+		maxDC = tempDC;
+	}
+	
+	// a starting pixel was found: it is added to the array
+	if ((currDC>maxDC) && (currDC>DCthr))
+	{
+	    startpixs->ResizeTo(++i);
+	    startpixs(i-1)=pixid;
+	    cout << "Starting pixel PixID=" << startpixs(i-1) << " curr=" << currDC << endl;
+	}
+    }
+    
+    if(startpixs->GetNrows()>0)
+    {
+	cout << "Number of starting pixels = " << startpixs->GetNrows() << endl;
+	return 1;
+    }
+    else
+	return 0;
+}
+/*
+Int_t FindCluster(Int_t startpix, Int_t cluster, MGeomCam *geom)
+{
+  return 1;
+
+}
+*/
+
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/HillasAnal.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/HillasAnal.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/HillasAnal.C	(revision 9772)
@@ -0,0 +1,191 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// MagicHillas.C
+// =============
+//
+// This is a demonstration program which calculates image (Hillas +)
+// parameters using as input a Merpp output file (raw data).
+// All parameters are written to an output file called hillas.root. Also
+// filles histograms are displayed.
+// For the calculation an arbitrary signal extractor (MCerPhotAnal2/Calc)
+// is used.
+//
+///////////////////////////////////////////////////////////////////////////
+
+void HillasAnal(const char *filename="output_test.root")
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Use this if you want to change the binning of one of
+    // the histograms. You can use:
+    // BinningConc, BinningConc1, BinningAsym, BinningM3Long,
+    // BinningM3Trans, BinningWidth, BinningLength, BinningDist,
+    // BinningHeadTail, BinningAlpha, BinningSize, BinningDelta,
+    // BinningPixels and BinningCamera
+    //
+    // For more information see MBinning and the corresponding
+    // histograms
+    //
+    // MBinning binsalpha("BinningAlpha");
+    // binsalpha.SetEdges(90, 0, 90);       // 90 bins from 0 to 90 deg
+    // plist.AddToList(&binsalpha);
+
+    // MBinning binssize("BinningSize");
+    // binssize.SetEdgesLog(50, 1, 1e7);
+    // plist.AddToList(&binssize);
+
+    //
+    // Craete the object which hlods the source positions in the camera
+    // plain in respect to which the image parameters will be calculated.
+    // For real data the containers will be filled by a task.
+    //
+    MSrcPosCam source;
+    source.SetReadyToSave();
+    plist.AddToList(&source);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    // The first argument is the tree you want to read.
+    //   Events:     Cosmic ray events
+    //   PedEvents:  Pedestal Events
+    //   CalEvents:  Calibration Events
+    //
+    MReadMarsFile read("Events", filename);
+    read.DisableAutoScheme();
+
+    // Setup a task which makes sure that all used arrays have
+    // the correct size
+    MGeomApply geomapl;
+
+    // tasks used if MC files are detected to calculate pedestals
+    // MMcPedestalCopy pcopy;
+    // MMcPedestalNSBAdd pnsb;
+
+    // calculate the signal in a very simple way
+    // for real adat files use MCerPhotAnal2 instead which also
+    // calculates the pedestal.
+    // MCerPhotCalc ncalc;
+    //
+    //  Alternative photon calculation:
+    //  Example: use only 2nd to 6th FADC slices for photon calculation:
+    //
+    //    const Float_t x[15]={0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+    //    const TArrayF w(15,(Float_t*)x);
+    //    ncalc.SetWeights(w);
+    //
+
+    // setup image cleaning and blind pixel treatment
+    MImgCleanStd    clean;
+    MBlindPixelCalc blind;
+
+    //
+    // Instead of unmapping the pixels you can also (The use of this
+    // class is deprecated, it will be replaced by MBadPixels*)
+    //
+    // blind.SetUseInterpolation();
+    // blind.SetUseCetralPixel();
+    //
+
+    // setup tasks to calculate image parameters
+    MHillasCalc    hcalc;
+    MHillasSrcCalc csrc1;
+
+    // setup tasks to fill histograms
+    MFillH hfill1("MHHillas", "MHillas");
+    MFillH hfill2("MHHillasExt");
+    MFillH hfill3("MHStarMap", "MHillas");
+    MFillH hfill4("HistExtSource [MHHillasExt]", "MHillasSrc");
+    MFillH hfill5("HistSource [MHHillasSrc]", "MHillasSrc");
+    //MFillH hfill6("MHNewImagePar");
+
+    // setup task to write containers to a file
+    MWriteRootFile write("hillas_Mrk421.root");
+    write.AddContainer("MHillas");
+    write.AddContainer("MHillasExt");
+    write.AddContainer("MHillasSrc");
+    write.AddContainer("MRawEvtHeader");
+    write.AddContainer("MRawRunHeader");
+    //write.AddContainer("HistExtSource");
+    //write.AddContainer("MHNewImagePar");
+
+    // Setup the contents of zour tasklist
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    //tlist.AddToList(&pcopy);
+    //tlist.AddToList(&pnsb);
+    //tlist.AddToList(&ncalc);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&blind);
+
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&csrc1);
+
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+    //tlist.AddToList(&hfill6);
+    tlist.AddToList(&write);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    MProgressBar bar;
+    evtloop.SetProgressBar(&bar);
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+
+    //
+    // After the analysis is finished we can display the histograms
+    //
+    plist.FindObject("MHHillas")->DrawClone();
+    plist.FindObject("MHHillasExt")->DrawClone();
+    plist.FindObject("MHStarMap")->DrawClone();
+    plist.FindObject("HistSource")->DrawClone();
+    plist.FindObject("HistExtSource")->DrawClone();
+    //plist.FindObject("MHNewImagePar")->DrawClone();
+}
+
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/first_ana.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/first_ana.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/first_ana.C	(revision 9772)
@@ -0,0 +1,125 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Alessio Piccioli, 04/2004 <mailto:alessio.piccioli@pi.infn.it>
+!   Author(s): Antonio Stamerra, 04/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+// first_ana.C
+// =============
+//
+//  This macro produces a ON/OFF plot using the alpha HillasSrc branch
+//  taken from an analysis file produced by the AnalisiHillas.C macro
+//  The significance of excess events is also computed (simple calculation,
+//   no Li-Ma)
+//
+///////////////////////////////////////////////////////////////////////////
+
+
+Float_t degTomm ( Float_t deg ) {
+  return deg / 57.29577951 * 17000 ;
+}
+
+Int_t first_ana ( Char_t *fNameOn = "crab.root" , Char_t *fNameOff = "offcrab.root" , Float_t minsize = 1000 , Float_t minWdeg = 0.00 , Float_t maxWdeg = 0.125 , Float_t minLdeg = 0.0 , Float_t maxLdeg = 0.26 , Float_t minDdeg = 0.2 , Float_t maxDdeg = 0.8 ) {
+
+  TFile *fileOn = new TFile ( fNameOn , "READ" ) ;
+  TFile *fileOff = new TFile ( fNameOff , "READ" ) ;
+
+  TTree *treeOn = (TTree *) fileOn -> Get ( "Parameters" ) ;
+  TTree *treeOff = (TTree *) fileOff -> Get ( "Parameters" ) ;
+
+  TString title ;
+
+  title = "Abs(Alpha) plot ON-Source" ;
+  TH1D *absalphaOn = new TH1D ( "absalphaOn" , title , 9 , 0 , 90 ) ;
+
+  title = "Abs(Alpha) plot ON-Source" ;
+  TH1D *absalphaOff = new TH1D ( "absalphaOff" , title , 9 , 0 , 90 ) ;
+
+  TString scut ;
+  scut = "MHillas.fSize>" ;
+  scut += minsize ;
+  cout << "CUT ON SIZE: " << scut << endl ;
+  TCut Scut = scut ; 
+
+  scut = "" ;
+  scut += degTomm(minWdeg) ;
+  scut += " < MHillas.fWidth && MHillas.fWidth < " ;
+  scut += degTomm(maxWdeg) ;
+  cout << "CUT ON WIDTH: " << scut << endl ;
+  TCut Wcut = scut ; 
+
+  scut = "" ;
+  scut += degTomm(minLdeg) ;
+  scut += " < MHillas.fLength && MHillas.fLength < " ;
+  scut += degTomm(maxLdeg) ;
+  cout << "CUT ON LENGTH: " << scut << endl ;
+  TCut Lcut = scut ; 
+
+  scut = "" ;
+  scut += degTomm(minDdeg) ;
+  scut += " < MHillasSrc.fDist && MHillasSrc.fDist < " ;
+  scut += degTomm(maxDdeg) ;
+  cout << "CUT ON DIST: " << scut << endl ;
+  TCut Dcut = scut ; 
+
+  treeOn -> Draw ( "abs(MHillasSrc.fAlpha)>>absalphaOn" , Scut && Wcut && Lcut && Dcut ) ; 
+  treeOff -> Draw ( "abs(MHillasSrc.fAlpha)>>absalphaOff" , Scut && Wcut && Lcut && Dcut ) ;
+  Double_t alpha = absalphaOn -> Integral ( 4 , 9 ) / absalphaOff -> Integral ( 4 , 9 ) ;
+  Double_t evoff = absalphaOff -> Integral ( 1 , 3 ) ;
+
+  absalphaOff -> Scale ( alpha ) ;
+
+  Double_t fakeMax = absalphaOn -> GetMaximum ( ) ;
+  fakeMax *= 1.1 ;
+
+  Double_t fakeMin = absalphaOn -> GetMinimum ( ) ;
+  fakeMin *= 0.8 ;
+
+  TH2D *fake = new TH2D ( "fake" , "Mrk421 Sample B (ON/OFF) 15/02/2004" , 100 , 0 , 90 , 100 , fakeMin , fakeMax ) ;
+  fake -> GetXaxis ( ) -> SetTitle ( "Parameter Alpha (deg)" ) ;
+  fake -> GetYaxis ( ) -> SetTitle ( "NUmber of Events" ) ;
+  fake -> GetYaxis ( ) -> SetTitleOffset ( 1.3 ) ;
+  fake -> SetStats ( 0 ) ;
+
+  TCanvas *c = new TCanvas ( "c" , "Alpha Canvas" , 800 , 600 ) ;
+  c -> SetGridx ( ) ;
+  c -> SetGridy ( ) ;
+  
+  absalphaOn -> SetMarkerStyle ( 22 ) ;
+  absalphaOn -> SetMarkerSize ( 2.7 ) ;
+  absalphaOff -> SetFillStyle ( 1001 ) ;
+  absalphaOff -> SetFillColor ( 3 ) ;
+
+  fake -> Draw ( ) ;
+  absalphaOff -> Draw ( "SAME" ) ;
+  absalphaOn -> Draw ( "SAMEE1" ) ;
+
+  Double_t evon = absalphaOn -> Integral ( 1 , 3 ) ;
+
+  cout << endl << "EntriesON:" << absalphaOn -> GetEntries ( ) ;
+  cout << endl << "EntriesOFF:" << absalphaOff -> GetEntries ( ) ;
+  cout << endl << "ON:" << evon << " OFF:" << evoff << " EXCESS:" << evon-evoff*alpha << " SIGMA:" << (evon-evoff*alpha)/TMath::Sqrt(evoff)/alpha << endl << endl ;
+  
+}
+
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/pedestalstudies_pisa.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/pedestalstudies_pisa.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/pedestalstudies_pisa.C	(revision 9772)
@@ -0,0 +1,685 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+// pedestalstudies_pisa.C
+//
+// macro to study the pedestal and pedestalRMS with the number of FADC 
+// slices summed up. 
+//
+/////////////////////////////////////////////////////////////////////////////////
+const TString pedfile = "/data0/Temp/20040422_23203_P_Mrk421_E.root";
+
+void pedestalstudies_pisa(const TString pedname=pedfile, Int_t pixin=0, Int_t pixout=397,TString f2="",TString f3="",TString f4="",TString f5="")
+{
+
+  Int_t loops = 1;
+  Int_t stepsize = 2;
+
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+  
+  TArrayF *hmeandiffinn = new TArrayF(loops);
+  TArrayF *hrmsdiffinn  = new TArrayF(loops);
+  TArrayF *hmeandiffout = new TArrayF(loops);
+  TArrayF *hrmsdiffout  = new TArrayF(loops);
+  TArrayF *hmeaninn  = new TArrayF(loops);
+  TArrayF *hmeanout  = new TArrayF(loops);
+  TArrayF *hrmsinn   = new TArrayF(loops);
+  TArrayF *hrmsout   = new TArrayF(loops);
+  TArrayF *hmuinn    = new TArrayF(loops);
+  TArrayF *hmuout    = new TArrayF(loops);
+  TArrayF *hsigmainn = new TArrayF(loops);
+  TArrayF *hsigmaout = new TArrayF(loops);
+
+  TArrayF *hmeandiffinnerr = new TArrayF(loops);
+  TArrayF *hrmsdiffinnerr  = new TArrayF(loops);
+  TArrayF *hmeandiffouterr = new TArrayF(loops);
+  TArrayF *hrmsdiffouterr  = new TArrayF(loops);
+  TArrayF *hmeaninnerr  = new TArrayF(loops);
+  TArrayF *hmeanouterr  = new TArrayF(loops);
+  TArrayF *hrmsinnerr   = new TArrayF(loops);
+  TArrayF *hrmsouterr   = new TArrayF(loops);
+  TArrayF *hmuinnerr    = new TArrayF(loops);
+  TArrayF *hmuouterr    = new TArrayF(loops);
+  TArrayF *hsigmainnerr = new TArrayF(loops);
+  TArrayF *hsigmaouterr = new TArrayF(loops);
+
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(500);
+  display->Resize(850,700);
+      
+  //
+  // Create a empty Parameter List and an empty Task List
+  // The tasklist is identified in the eventloop by its name
+  //
+  MParList  plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+
+  TString tabname="";
+
+  for (Int_t samples=2; samples < stepsize*loops+1; samples=samples+stepsize)
+    {
+
+      plist.Reset();
+      tlist.Reset();
+      
+      //
+      // Now setup the tasks and tasklist for the pedestals:
+      // ---------------------------------------------------
+      //
+      
+      MReadMarsFile read("Events", pedname);
+      read.DisableAutoScheme();
+     
+	Int_t neventi;
+ 	neventi=1000;
+
+	Float_t samplingRate=500;	//Hz
+	if (f2!=""){
+	read.AddFile(f2);
+	neventi += 1000;
+	}
+
+	if (f3!=""){
+	read.AddFile(f3);
+	neventi += 1000;
+	}
+
+	if (f4!=""){
+	read.AddFile(f4);
+	neventi += 1000;
+	}
+
+	if (f5!=""){
+	read.AddFile(f5);
+	neventi += 1000;
+	}
+
+	const Int_t NEvt = neventi;
+	cout << "E" <<neventi<< " NEvt:" << NEvt << endl;
+	Float_t timevt[NEvt];
+
+      MGeomApply      geomapl;
+      //
+      // Set the extraction range higher:
+      //		
+      //MExtractFixedWindow sigcalc;
+      //MExtractSignal3 sigcalc;
+      	MExtractSlidingWindow sigcalc;
+      sigcalc.SetRange(0,samples-1,0,1);
+
+     
+  
+      MPedCalcPedRun pedcalc;
+      pedcalc.SetRange(0,samples-1,0,0);
+      pedcalc.SetWindowSize((Int_t)sigcalc.GetNumHiGainSamples());
+
+      //MPedCalcFromData pedcalc;
+      //pedcalc.SetfHiGainThreshold(100);
+
+      //
+      // Additionally to calculating the pedestals, 
+      // you can fill histograms and look at them
+      //
+      MFillH fill("MHPedestalCam", "MExtractedSignalCam");
+      tabname="PedCam ";
+      tabname += samples;
+      //fill.SetNameTab(Form("%s%2d","PedCam",samples));
+      fill.SetNameTab(tabname);
+
+      tlist.AddToList(&read);
+      tlist.AddToList(&geomapl);
+      tlist.AddToList(&sigcalc);
+      tlist.AddToList(&pedcalc);
+      tlist.AddToList(&fill);
+      
+      const MGeomCamMagic      geomcam;
+      MPedestalCam       pedcam;
+      MBadPixelsCam      badcam;
+      badcam.AsciiRead("badpixels.dat");  
+      
+      MHPedestalCam      hpedcam;
+      MCalibrationPedCam cpedcam;
+      
+      plist.AddToList(&geomcam);
+      plist.AddToList(&pedcam);
+      plist.AddToList(&hpedcam);
+      plist.AddToList(&cpedcam);
+      plist.AddToList(&badcam);
+      
+      //
+      // Create and setup the eventloop
+      //
+      MRawEvtHeader *evtheader;
+      MRawEvtData *fRawEvt;
+      TH1F *hpedevt = new TH1F("hpedevt","Pedestals Drift",NEvt,0,(Float_t)NEvt/samplingRate);
+      Bool_t rc;
+      MEvtLoop evtloop;
+      
+      evtloop.SetParList(&plist);
+      evtloop.SetDisplay(display);
+      //tlist.SetDisplay(display);
+      //
+      // Execute first analysis
+      //
+      //if (!evtloop.Eventloop())
+      //  return;
+      rc = evtloop.PreProcess();
+      
+      //while (tlist.Process())
+	//{
+	//cout << "bleah" << endl;
+	//}      
+//tlist.SetDisplay(display);
+
+       Int_t fNumHiGainSample=15;
+	Float_t peddata[NEvt];
+	Int_t evtan=0;
+
+      if (rc){
+          while (tlist.Process())
+          {
+            fRawEvt=(MRawEvtData *)plist.FindObject("MRawEvtData");
+            MRawEvtPixelIter pixel(fRawEvt);
+
+            Float_t ped=0;
+	    evtan++;
+
+ 	    while (pixel.Next())
+	     {
+
+ 	       const UInt_t idx    = pixel.GetPixelId();
+
+               // lista di pixel da sommare
+               if (idx >pixout || idx < pixin)
+		  continue;
+
+	        Byte_t *ptr = pixel.GetHiGainSamples();
+                const Byte_t *end = ptr + fNumHiGainSample;
+      
+                UInt_t sum = 0;
+	        UInt_t sqr = -1;
+
+	        do
+	          {
+	            sum += *ptr;
+	            //sqr += *ptr * *ptr;
+	          }
+	        while (++ptr != end);
+      
+                 ped += (Float_t)sum;
+
+                  //cout << " Pixel " << idx << " pede: " << ped << " --- ";
+                }
+ 
+               //rc = evtloop.Process(0);
+	       evtheader = (MRawEvtHeader *)plist.FindObject("MRawEvtHeader");
+
+             ped /= pixout-pixin+1;
+		Int_t evtn=evtheader->GetDAQEvtNumber();
+             evtn=evtan;
+
+//test
+	//ped =  150 + sin(((Float_t)evtn/16.-TMath::Floor(evtn/16))*6.28); 
+	//cout << ped << " ";
+	timeped = evtn/samplingRate;
+	timevt[evtn-1]=timeped;
+     
+        hpedevt->Fill(timeped,ped);
+
+            //	cout <<" evt:" << evtn;
+	     // Save pedestal in array for Fourier analysis
+	     peddata[evtn-1]=ped;
+          }
+      }
+      if (!evtloop.PostProcess()){
+          rc = kFALSE;
+          return;
+      }
+
+      TCanvas &p1 = display->AddTab("ped studies");
+      p1.Divide(1,2);
+      p1.cd(1);
+	hpedevt->GetXaxis()->SetTitle("Time (s)");
+//      hpedevt->Draw();
+
+	TGraph *drift = new TGraph(evtan,timevt,peddata);
+	drift->SetMarkerStyle(21);
+	drift->SetMarkerSize(0.25);
+	drift->GetXaxis()->SetTitle("time (s)");
+	drift->GetYaxis()->SetTitle(" pedestal");
+	drift->Draw("APL");
+
+
+      // Fourier analysis
+	// campionamento a 500Hz (1000 evt) => freq. max a 250Hz
+
+	MFFT pro;
+	TArrayF *pedarray = new TArrayF(NEvt,peddata);
+	TArrayF *fft; // array con risultato FFT 
+	fft = pro.RealFunctionFFT(pedarray);
+	Int_t nsample = (Int_t)(fft->GetSize()); 
+	
+	const Int_t NNEvt = nsample;
+
+	Float_t x[10000];
+	Float_t prova;
+	for (int i=0;i<NNEvt;i++)
+	 x[i]=(Float_t)i/(NNEvt/(samplingRate/2)); 
+
+	Float_t *ffty = fft->GetArray();
+        cout << "Szie:" << fft->GetSize();
+	ffty[0]=0.;
+	TGraph *gr = new TGraph(nsample,x,ffty);
+	p1.cd(2);
+	gr->GetXaxis()->SetTitle("Frequency (Hz)");
+	gr->SetMarkerStyle(20);
+	gr->SetMarkerSize(0.4);
+	gr->Draw("AP");		
+
+
+
+//-------------------------------
+
+
+      // Set status lines
+      display->SetStatusLine1(evtloop.GetName());
+      display->SetStatusLine2(rc ? "Done." : "Error!");
+      // Stop automatic update
+      display->StopUpdate();
+      // Reallow context menus
+      display->SetNoContextMenu(kFALSE);
+      // Reallow user to exit window by File menu
+      display->UnLock();
+      // 
+      // Look at one specific pixel, after all the histogram manipulations:
+      //
+      /*
+      MHGausEvents &hpix = hpedcam.GetAverageHiGainArea(0);
+      hpix.DrawClone("fourierevents");
+      
+      MHGausEvents &lpix = hpedcam.GetAverageHiGainArea(1);
+      lpix.DrawClone("fourierevents");
+
+      hpedcam[170].DrawClone("fourierevents");
+  
+      */
+
+      MHCamera dispped0  (geomcam, "Ped;Pedestal",       "Mean per Slice");
+      MHCamera dispped2  (geomcam, "Ped;PedestalRms",    "RMS per Slice");
+      MHCamera dispped4  (geomcam, "Ped;Mean",           "Fitted Mean per Slice");
+      MHCamera dispped6  (geomcam, "Ped;Sigma",          "Fitted Sigma per Slice");
+      MHCamera dispped9  (geomcam, "Ped;DeltaPedMean",   "Rel. Diff. Mean per Slice (Fit-Calc.)");
+      MHCamera dispped11 (geomcam, "Ped;DeltaRmsSigma",  "Rel. Diff. RMS per Slice (Fit-Calc.)");
+  
+      dispped0.SetCamContent(  pedcam, 0);
+      dispped0.SetCamError(    pedcam, 1);
+      dispped2.SetCamContent(  pedcam, 2);
+      dispped2.SetCamError(    pedcam, 3);
+      
+      dispped4.SetCamContent( hpedcam, 0);
+      dispped4.SetCamError(   hpedcam, 1);
+      dispped6.SetCamContent( hpedcam, 2);
+      dispped6.SetCamError(   hpedcam, 3);
+      dispped9.SetCamContent( hpedcam, 5);
+      dispped9.SetCamError(   hpedcam, 6);
+      dispped11.SetCamContent(hpedcam, 8);
+      dispped11.SetCamError(  hpedcam, 9);
+  
+      dispped0.SetYTitle("Calc. Pedestal per slice [FADC counts]");
+      dispped2.SetYTitle("Calc. Pedestal RMS per slice [FADC counts]");
+      dispped4.SetYTitle("Fitted Mean per slice [FADC counts]");
+      dispped6.SetYTitle("Fitted Sigma per slice [FADC counts]");
+      dispped9.SetYTitle("Rel. Diff. Pedestal per slice Fit-Calc [1]");
+      dispped11.SetYTitle("Rel. Diff. Pedestal RMS per slice Fit-Calc [1]");
+
+
+      // Histogram values
+      tabname="MeanRMS ";
+      tabname += samples;
+      //fill.SetNameTab(tabname);
+      TCanvas &b1 = display->AddTab(tabname);
+      b1.Divide(4,3);
+
+      CamDraw(b1,dispped0,1,4,*hmeaninn,*hmeanout,*hmeaninnerr,*hmeanouterr,samples,stepsize);
+      CamDraw(b1,dispped2,2,4,*hrmsinn,*hrmsout,*hrmsinnerr,*hrmsouterr,samples,stepsize);  
+      CamDraw(b1,dispped4,3,4,*hmuinn,*hmuout,*hmuinnerr,*hmuouterr,samples,stepsize);
+      CamDraw(b1,dispped6,4,4,*hsigmainn,*hsigmaout,*hsigmainnerr,*hsigmaouterr,samples,stepsize); 
+      
+      tabname="MeanRrmSamples ";
+      tabname += samples;
+      display->SaveAsGIF(3*((samples-1)/stepsize)+2,tabname);
+
+      // Differences
+      tabname="RelDiff ";
+      tabname += samples;
+      TCanvas &c4 = display->AddTab(tabname);
+      c4.Divide(2,3);
+      
+      CamDraw(c4,dispped9,1,2,*hmeandiffinn,*hmeandiffout,*hmeandiffinnerr,*hmeandiffouterr,samples,stepsize);
+      CamDraw(c4,dispped11,2,2,*hrmsdiffinn,*hrmsdiffout,*hrmsdiffinnerr,*hrmsdiffouterr,samples,stepsize); 
+
+      tabname="RelDiffSamples ";
+      tabname += samples;
+      display->SaveAsGIF(3*((samples-1)/stepsize)+3,tabname);
+
+   cout << "Loop N. " <<samples << " completed..." <<endl;
+
+    }
+
+  /*
+  TF1 *logg = new TF1("logg","[1]+TMath::Log(x-[0])",1.,30.,2);
+  logg->SetParameters(1.,3.5);
+  logg->SetParLimits(0,-1.,3.);
+  logg->SetParLimits(1,-1.,7.);
+  logg->SetLineColor(kRed);
+  */
+
+  TCanvas *canvas = new TCanvas("PedstudInner","Pedestal Studies Inner Pixels",600,900);
+  canvas->Divide(2,3);
+  canvas->cd(1);
+
+  TGraphErrors *gmeaninn = new TGraphErrors(hmeaninn->GetSize(),
+                                            CreateXaxis(hmeaninn->GetSize(),stepsize),hmeaninn->GetArray(),
+                                            CreateXaxisErr(hmeaninnerr->GetSize(),stepsize),hmeaninnerr->GetArray());
+  gmeaninn->Draw("A*");
+  gmeaninn->SetTitle("Calculated Mean per Slice Inner Pixels");
+  gmeaninn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeaninn->GetYaxis()->SetTitle("Calculated Mean per slice");
+  //  gmeaninn->Fit("pol0");
+  //  gmeaninn->GetFunction("pol0")->SetLineColor(kGreen);
+  //  //  gmeaninn->Fit(logg);
+
+  canvas->cd(2);
+
+  TGraphErrors *gmuinn = new TGraphErrors(hmuinn->GetSize(),
+                                          CreateXaxis(hmuinn->GetSize(),stepsize),hmuinn->GetArray(),
+                                          CreateXaxisErr(hmuinnerr->GetSize(),stepsize),hmuinnerr->GetArray());
+  gmuinn->Draw("A*");
+  gmuinn->SetTitle("Fitted Mean per Slice Inner Pixels");
+  gmuinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmuinn->GetYaxis()->SetTitle("Fitted Mean per Slice");
+  //  gmuinn->Fit("pol0");
+  //  gmuinn->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmuinn->Fit(logg);
+
+
+  canvas->cd(3);
+
+  TGraphErrors *grmsinn = new TGraphErrors(hrmsinn->GetSize(),
+                                           CreateXaxis(hrmsinn->GetSize(),stepsize),hrmsinn->GetArray(),
+                                           CreateXaxisErr(hrmsinnerr->GetSize(),stepsize),hrmsinnerr->GetArray());
+  grmsinn->Draw("A*");
+  grmsinn->SetTitle("Calculated Rms per Slice Inner Pixels");
+  grmsinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsinn->GetYaxis()->SetTitle("Calculated Rms per Slice");
+  //  //grmsinn->Fit("pol2");
+  //  //grmsinn->GetFunction("pol2")->SetLineColor(kRed);
+  //  grmsinn->Fit(logg);
+
+  canvas->cd(4);
+
+  TGraphErrors *gsigmainn = new TGraphErrors(hsigmainn->GetSize(),
+                                             CreateXaxis(hsigmainn->GetSize(),stepsize),hsigmainn->GetArray(),
+                                             CreateXaxisErr(hsigmainnerr->GetSize(),stepsize),hsigmainnerr->GetArray());
+  gsigmainn->Draw("A*");
+  gsigmainn->SetTitle("Fitted Sigma per Slice Inner Pixels");
+  gsigmainn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gsigmainn->GetYaxis()->SetTitle("Fitted Sigma per Slice");
+  //  //  gsigmainn->Fit("pol2");
+  //  //  gsigmainn->GetFunction("pol2")->SetLineColor(kRed);
+  //  gsigmainn->Fit(logg);
+
+  canvas->cd(5);
+
+  TGraphErrors *gmeandiffinn = new TGraphErrors(hmeandiffinn->GetSize(),
+                                                CreateXaxis(hmeandiffinn->GetSize(),stepsize),hmeandiffinn->GetArray(),
+                                                CreateXaxisErr(hmeandiffinnerr->GetSize(),stepsize),hmeandiffinnerr->GetArray());
+  gmeandiffinn->Draw("A*"); 
+  gmeandiffinn->SetTitle("Rel. Difference  Mean per Slice Inner Pixels");
+  gmeandiffinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeandiffinn->GetYaxis()->SetTitle("Rel. Difference Mean per Slice");
+  //  //gmeandiffinn->Fit("pol2");
+  //  //gmeandiffinn->GetFunction("pol2")->SetLineColor(kBlue);
+  //  gmeandiffinn->Fit(logg);
+
+
+  canvas->cd(6);
+
+  TGraphErrors *grmsdiffinn = new TGraphErrors(hrmsdiffinn->GetSize(),
+                                               CreateXaxis(hrmsdiffinn->GetSize(),stepsize),hrmsdiffinn->GetArray(),
+                                               CreateXaxisErr(hrmsdiffinnerr->GetSize(),stepsize),hrmsdiffinnerr->GetArray());
+  grmsdiffinn->Draw("A*");
+  grmsdiffinn->SetTitle("Rel. Difference Sigma per Slice-RMS Inner Pixels");
+  grmsdiffinn->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsdiffinn->GetYaxis()->SetTitle("Rel. Difference Sigma per Slice-RMS");
+  //  //grmsdiffinn->Fit("pol2");
+  //  //grmsdiffinn->GetFunction("pol2")->SetLineColor(kBlue);
+  //  grmsdiffinn->Fit(logg);
+
+  canvas->SaveAs("PedestalStudyInner.root");
+  canvas->SaveAs("PedestalStudyInner.ps");
+
+  TCanvas *canvas2 = new TCanvas("PedstudOut","Pedestal Studies Outer Pixels",600,900);
+  canvas2->Divide(2,3);
+  canvas2->cd(1);
+
+  TGraphErrors *gmeanout = new TGraphErrors(hmeanout->GetSize(),
+                                            CreateXaxis(hmeanout->GetSize(),stepsize),hmeanout->GetArray(),
+                                            CreateXaxisErr(hmeanouterr->GetSize(),stepsize),hmeanouterr->GetArray());
+  gmeanout->Draw("A*");
+  gmeanout->SetTitle("Calculated Mean per Slice Outer Pixels");
+  gmeanout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeanout->GetYaxis()->SetTitle("Calculated Mean per Slice");
+  //  gmeanout->Fit("pol0");
+  //  gmeanout->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmeanout->Fit(logg);
+
+  canvas2->cd(2);
+
+  TGraphErrors *gmuout = new TGraphErrors(hmuout->GetSize(),
+                                          CreateXaxis(hmuout->GetSize(),stepsize),hmuout->GetArray(),
+                                          CreateXaxisErr(hmuouterr->GetSize(),stepsize),hmuouterr->GetArray());
+  gmuout->Draw("A*");
+  gmuout->SetTitle("Fitted Mean per Slice Outer Pixels");
+  gmuout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmuout->GetYaxis()->SetTitle("Fitted Mean per Slice");
+  //  gmuout->Fit("pol0");
+  //  gmuout->GetFunction("pol0")->SetLineColor(kGreen);
+  //gmuout->Fit(logg);
+
+  canvas2->cd(3);
+
+  TGraphErrors *grmsout = new TGraphErrors(hrmsout->GetSize(),
+                                           CreateXaxis(hrmsout->GetSize(),stepsize),hrmsout->GetArray(),
+                                           CreateXaxisErr(hrmsouterr->GetSize(),stepsize),hrmsouterr->GetArray());
+  grmsout->Draw("A*");
+  grmsout->SetTitle("Calculated Rms per Slice Outer Pixels");
+  grmsout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsout->GetYaxis()->SetTitle("Calculated Rms per Slice");
+  //  //grmsout->Fit("pol2");
+  //  //grmsout->GetFunction("pol2")->SetLineColor(kRed);
+  //  grmsout->Fit(logg);
+
+  canvas2->cd(4);
+
+  TGraphErrors *gsigmaout = new TGraphErrors(hsigmaout->GetSize(),
+                                             CreateXaxis(hsigmaout->GetSize(),stepsize),hsigmaout->GetArray(),
+                                             CreateXaxisErr(hsigmaouterr->GetSize(),stepsize),hsigmaouterr->GetArray());
+  gsigmaout->Draw("A*");
+  gsigmaout->SetTitle("Fitted Sigma per Slice Outer Pixels");
+  gsigmaout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gsigmaout->GetYaxis()->SetTitle("Fitted Sigma per Slice");
+  //  //gsigmaout->Fit("pol2");
+  //  //gsigmaout->GetFunction("pol2")->SetLineColor(kRed);
+  //  gsigmaout->Fit(logg);
+
+
+  canvas2->cd(5);
+
+  TGraphErrors *gmeandiffout = new TGraphErrors(hmeandiffout->GetSize(),
+                                                CreateXaxis(hmeandiffout->GetSize(),stepsize),hmeandiffout->GetArray(),
+                                                CreateXaxisErr(hmeandiffouterr->GetSize(),stepsize),hmeandiffouterr->GetArray());
+  gmeandiffout->Draw("A*");
+  gmeandiffout->SetTitle("Rel. Difference  Mean per Slice Outer Pixels");
+  gmeandiffout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  gmeandiffout->GetYaxis()->SetTitle("Rel. Difference Mean per Slice");
+  //  //gmeandiffout->Fit("pol2");
+  //w  //gmeandiffout->GetFunction("pol2")->SetLineColor(kBlue);
+  //  gmeandiffout->Fit(logg);
+
+  canvas2->cd(6);
+
+  TGraphErrors *grmsdiffout = new TGraphErrors(hrmsdiffout->GetSize(),
+                                               CreateXaxis(hrmsdiffout->GetSize(),stepsize),hrmsdiffout->GetArray(),
+                                               CreateXaxisErr(hrmsdiffouterr->GetSize(),stepsize),hrmsdiffouterr->GetArray());
+  grmsdiffout->Draw("A*");
+  grmsdiffout->SetTitle("Rel. Difference Sigma per Slice-RMS Outer Pixels");
+  grmsdiffout->GetXaxis()->SetTitle("Nr. added FADC slices");
+  grmsdiffout->GetYaxis()->SetTitle("Rel. Difference Sigma per Slice-RMS");
+  //  //grmsdiffout->Fit("pol2");
+  //  //grmsdiffout->GetFunction("pol2")->SetLineColor(kBlue);
+  //  grmsdiffout->Fit(logg);
+
+
+  canvas2->SaveAs("PedestalStudyOuter.root");
+  canvas2->SaveAs("PedestalStudyOuter.ps");
+
+
+}
+
+
+void CamDraw(TCanvas &c, MHCamera &cam, Int_t i, Int_t j, TArrayF &a1, TArrayF &a2, 
+             TArrayF &a1err, TArrayF &a2err, Int_t samp, Int_t stepsize)
+{
+
+  c.cd(i);
+  MHCamera *obj1=(MHCamera*)cam.DrawCopy("hist");
+  obj1->SetDirectory(NULL);
+  
+  c.cd(i+j);
+  obj1->Draw();
+  ((MHCamera*)obj1)->SetPrettyPalette();
+
+  c.cd(i+2*j);
+  TH1D *obj2 = (TH1D*)obj1->Projection();
+  obj2->SetDirectory(NULL);
+  
+  //      obj2->Sumw2();
+  obj2->Draw();
+  obj2->SetBit(kCanDelete);
+  
+  const Double_t min   = obj2->GetBinCenter(obj2->GetXaxis()->GetFirst());
+  const Double_t max   = obj2->GetBinCenter(obj2->GetXaxis()->GetLast());
+  const Double_t integ = obj2->Integral("width")/2.5066283;
+  const Double_t mean  = obj2->GetMean();
+  const Double_t rms   = obj2->GetRMS();
+  const Double_t width = max-min;
+  
+  if (rms == 0. || width == 0. )
+    return;
+  
+  TArrayI s0(6);
+  s0[0] = 6;
+  s0[1] = 1;
+  s0[2] = 2;
+  s0[3] = 3;
+  s0[4] = 4;
+  s0[5] = 5;
+  
+  TArrayI inner(1);
+  inner[0] = 0;
+  
+  TArrayI outer(1);
+  outer[0] = 1;
+      
+  // Just to get the right (maximum) binning
+  TH1D *half[2];
+  half[0] = obj1->ProjectionS(s0, inner, "Inner");
+  half[1] = obj1->ProjectionS(s0, outer, "Outer");
+
+  half[0]->SetDirectory(NULL);
+  half[1]->SetDirectory(NULL);
+  
+  for (int i=0; i<2; i++)
+    {
+      half[i]->SetLineColor(kRed+i);
+      half[i]->SetDirectory(0);
+      half[i]->SetBit(kCanDelete);
+      half[i]->Draw("same");
+      half[i]->Fit("gaus","Q+");
+
+      if (i==0)
+        {
+          a1[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParameter(1);
+          a1err[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParError(1);
+          if (a1err[(samp-1)/stepsize] > 3.)
+            a1err[(samp-1)/stepsize] = 1.;
+        }
+     if (i==1)
+       {
+         a2[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParameter(1);
+         a2err[(samp-1)/stepsize] = half[i]->GetFunction("gaus")->GetParError(1);
+          if (a2err[(samp-1)/stepsize] > 3.)
+            a2err[(samp-1)/stepsize] = 1.;
+       }
+    }
+  
+  
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Create the x-axis for the event graph
+//
+Float_t *CreateXaxis(Int_t n, Int_t step)
+{
+
+  Float_t *xaxis = new Float_t[n];
+
+  for (Int_t i=0;i<n;i++)
+    xaxis[i] = 2. + step*i;
+
+  return xaxis;
+                 
+}
+
+// -----------------------------------------------------------------------------
+// 
+// Create the x-axis for the event graph
+//
+Float_t *CreateXaxisErr(Int_t n, Int_t step)
+{
+
+  Float_t *xaxis = new Float_t[n];
+
+  for (Int_t i=0;i<n;i++)
+    xaxis[i] = step/2.;
+
+  return xaxis;
+                 
+}
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/production.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/production.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/production.C	(revision 9772)
@@ -0,0 +1,295 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Hendrik Bartko, 03/2004 <mailto:hbartko@mppmu.mpg.de>
+!              Markus Gaug,    03/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////////
+//
+//   production.C
+//   ============
+//
+//   This macro takes calibration runs and pedestal runs
+//   to set pedestals and calibration factors
+//   Then raw data files are read and calibrated.
+//   The output file contains the calibrated data, pedestal subtracted,
+//   with the signal (in photons) for each pixels
+//
+//   input:  calibration file(s)
+//           pedestal file(s)
+//           raw data files
+//   
+//   output: root files with following containers (branches)
+//           - MCerPhotEvt
+//           - MPedestalCam
+//           - MCalibrationRelTimeCam
+//           - MCerPhotEvt
+//           - MRawEvtHeader
+//           - MBadPixelsCam
+//           - MPedPhotCam
+//
+///////////////////////////////////////////////////////////////////////////
+
+//
+// Set path for files and run numbers
+//
+const TString defpath = "/data1/earth/magic/data/Period014/rootdata/2004_02_15/";
+const TString defrout = "output_Mrk421_20040215.root";
+
+const Int_t defpedr [] = {17284};
+const Int_t defcalr [] = {17285};
+const Int_t defdatar[] = {17286,17287,17288,17289,17290,17291,17292,17293,
+			  17294,17295,17296,17297,17298,17299,17300,17301,
+			  17302,17303,17304,17305,17306,17307,17308,17309,
+			  17310,17311,17312,17313,17314,17315,17316,17317,
+			  17318,17319,17320,17321,17322,17323,17324,17325,
+			  17326,17327,17328,17329,17330,17331,17332,17333,
+			  17334,17335,17336,17337,17338,17339,17340,17341,
+			  17342,17343,17344,17345,17346,17347,17348,17349,
+			  17350,17351,17352,17353,17354,17355,17356,17357,
+			  17358,17359,17360,17361,17362,17363,17364,17365,
+			  17366,17367,17368,17369,17370,17371,17372,17373,
+			  17374,17375,17376,17377,17378,17379,17380,17381,
+			  17382,17383,17384,17385,17386,17387,17388,17389,
+			  17390,17391,17392,17393,17394,17395,17396,17397,
+			  17398,17399,17400,17401,17402,17403,17404,17405,
+			  17406,17407,17408,17409,17410,17411,17412,17413,
+			  17414,17415,17416,17417,17418,17419,17420,17421,
+			  17422,17423,17424,17425,17426,17427,17428,17429,
+			  17430,17431,17432,17433,17434,17435,17436,17437,
+			  17438,17439,17440,17441,17442,17443,17444,17445,
+			  17446,17447,17448,17449,17450,17451,17452,17453,
+			  17454,17455,17456};
+
+
+void production(const TString inpath=defpath, 
+                    const Int_t psize=1, const Int_t pedruns[]=defpedr, 
+                    const Int_t csize=1, const Int_t calruns[]=defcalr, 
+                    const Int_t dsize=171, const Int_t dataruns[]=defdatar, 
+                    const TString resname=defrout)
+
+{
+
+  MExtractSlidingWindow extractor;
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+  
+  for (Int_t i=0;i<psize;i++) {
+    cout << "Adding pedestal run: " << pedruns[i] << endl;
+    pruns.AddRun(pedruns[i],inpath);
+  }
+  for (Int_t i=0;i<csize;i++) {
+    cout << "Adding calibration run: " << calruns[i] << endl;
+    cruns.AddRun(calruns[i],inpath);
+  }
+  for (Int_t i=0;i<dsize;i++) {
+    cout << "Adding data run: " << dataruns[i] << endl;
+    druns.AddRun(dataruns[i],inpath);
+  }
+
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+
+  gStyle->SetOptStat(1111);
+  gStyle->SetOptFit();
+
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+  
+  MParList plist1;
+  MTaskList tlist1;
+  plist1.AddToList(&tlist1);
+  
+  // containers
+  MPedestalCam   pedcam;
+  MBadPixelsCam  badcam;
+  //
+  // for excluding pixels from the beginning:
+  //
+  // badcam.AsciiRead("badpixels.dat");
+
+
+  plist1.AddToList(&pedcam);
+  plist1.AddToList(&badcam);
+    
+  //tasks
+  MReadMarsFile  read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(pruns);
+
+  MGeomApply     geomapl;
+  MPedCalcPedRun pedcalc;
+  MGeomCamMagic  geomcam;
+    
+  tlist1.AddToList(&read);
+  tlist1.AddToList(&geomapl);
+  tlist1.AddToList(&pedcalc);
+
+  // Create and execute the event looper
+  MEvtLoop pedloop;
+  pedloop.SetParList(&plist1);
+  pedloop.SetDisplay(display);
+
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+
+  if (!pedloop.Eventloop())
+    return;
+  
+  tlist1.PrintStatistics();
+
+  // 
+  // Now the short version: 
+  //
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MJCalibration     calloop;
+  calloop.SetInput(&cruns);
+  //  calloop.SetFullDisplay();
+  //
+  calloop.SetExtractor(&extractor);
+  //
+  // Set the corr. cams:
+  //
+  calloop.SetBadPixels(badcam);
+  //
+  // The next two commands are for the display:
+  //
+  calloop.SetDisplay(display);
+  
+  //
+  // Apply rel. time calibration:
+  //
+  calloop.SetRelTimeCalibration();
+  //
+  // Use as arrival time extractor MArrivalTimeCalc2:
+  //
+  calloop.SetArrivalTimeLevel(2);
+  
+  //
+  // Do the event-loop:
+  //
+  cout << "***************************" << endl;
+  cout << "** COMPUTING CALIBRATION **" << endl;
+  cout << "***************************" << endl;
+  
+  if (!calloop.Process(pedcam))
+    return;
+
+  badcam.Print();
+  
+  MBadPixelsCam          &badbad  = calloop.GetBadPixels();
+  MCalibrationChargeCam  &calcam  = calloop.GetCalibrationCam();
+  MCalibrationRelTimeCam &timecam = calloop.GetRelTimeCam();
+  MCalibrationQECam      &qecam   = calloop.GetQECam();
+
+  badbad.Print();
+
+  /************************************************************************/
+  /*                THIRD LOOP: DATA CALIBRATION INTO PHOTONS             */
+  /************************************************************************/
+
+  // Create an empty Parameter List and an empty Task List
+  MParList  plist3;  
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+ 
+  // containers
+  MCerPhotEvt         photevt;
+  MPedPhotCam         pedphotcam;
+  MSrcPosCam          srccam;
+  MRawRunHeader       runhead;
+  MExtractedSignalCam sigcam;
+
+  plist3.AddToList(&geomcam );
+  plist3.AddToList(&pedcam  );
+  plist3.AddToList(&calcam  );
+  plist3.AddToList(&qecam   );
+  plist3.AddToList(&badbad  );
+  plist3.AddToList(&timecam );
+  plist3.AddToList(&sigcam  );
+  plist3.AddToList(&photevt);
+  plist3.AddToList(&pedphotcam);
+  plist3.AddToList(&srccam);
+  plist3.AddToList(&runhead);
+
+  //tasks
+  MReadMarsFile read3("Events");
+  read3.DisableAutoScheme();
+  static_cast<MRead&>(read3).AddFiles(druns);
+
+  MArrivalTimeCalc2   timecalc;
+  MCalibrateData      photcalc;     
+  photcalc.SetCalibrationMode(MCalibrateData::kFfactor);  // !!! was only MCalibrate
+  // MPedPhotCalc     pedphotcalc;   // already done by MCalibrate Data
+  // MCerPhotCalc     cerphotcalc;  // already done by MCalibrate Data
+  
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&extractor);
+  tlist3.AddToList(&timecalc);
+  //  tlist3.AddToList(&cerphotcalc); // already done by MCalibrate Data
+  tlist3.AddToList(&photcalc);
+  // tlist3.AddToList(&pedphotcalc);   // already done by MCalibrate Data
+
+  MWriteRootFile write(resname);
+  
+  write.AddContainer("MGeomCam"              , "RunHeaders");
+  write.AddContainer("MRawRunHeader"         , "RunHeaders");
+  write.AddContainer("MSrcPosCam"            , "RunHeaders");
+  write.AddContainer("MCalibrationChargeCam" , "RunHeaders");
+  write.AddContainer("MCalibrationQECam"     , "RunHeaders");
+  //  write.AddContainer("MPedPhotCam","RunHeaders"); // Attention, was in Events - Tree!!
+  write.AddContainer("MPedestalCam"          , "RunHeaders");
+  write.AddContainer("MCalibrationRelTimeCam", "RunHeaders");
+
+  write.AddContainer("MCerPhotEvt"   , "Events");
+  write.AddContainer("MRawEvtHeader" , "Events");
+  write.AddContainer("MBadPixelsCam" , "Events");
+  write.AddContainer("MPedPhotCam"   , "Events");
+
+  tlist3.AddToList(&write);
+  
+  // Create and execute eventloop
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+    
+  cout << "*************************************************************" << endl;
+  cout << "***   COMPUTING DATA USING EXTRACTED SIGNAL (IN PHOTONS)  ***" << endl;
+  cout << "*************************************************************" << endl;
+  
+  if (!evtloop3.Eventloop())  
+    return;  
+  tlist3.PrintStatistics();
+
+}
+
+
+
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/production3.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/production3.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/production3.C	(revision 9772)
@@ -0,0 +1,373 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 12/2003 <mailto:jlopez@ifae.es>
+!              Markus Gaug , 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  bootcampstandardanalysis.C
+//
+//  Updated version of the macro designed at the Wuerzburg bootcamp and 
+//  compatible with the latest changes in Mars for general usage at the
+//  Udine bootcamp. 
+//
+//  Needs as arguments the run number of a pedestal file ("*_P_*.root"), 
+//  one of a calibration file ("*_C_*.root") and one of a data file 
+//  ("*_D_*.root"). Performs the pedestal calculation, the calibration 
+/// constants calculation and the calibration of the data. 
+//
+//  The TString inpath has to be set correctly.
+//
+//  The macro searches for the pulser colour which corresponds to the calibration
+//  run number. If the run number is smaller than 20000, pulser colour "CT1" 
+//  is assumed, otherwise, it searches for the strings "green", "blue", "uv" or 
+//  "ct1" in the filenames. If no colour or multiple colours are found, the 
+//  execution is aborted.  
+//
+//////////////////////////////////////////////////////////////////////////////////
+const Bool_t usedisplay = kTRUE;
+const TString defpath = "/data1/earth/magic/data/Period015/rootdata/2004_03_19/";
+const TString outpath = "./";
+const TString defrout = "output_Mrk421_20040319.root";
+// Mrk (13)
+const Int_t defpedr[] = {20823};
+//const Int_t defpedr [] = {20590,20593,20596,20599,20601,20602,20605,
+//			  20608,20611,20614,20649,20652,20654};
+// OffMrk (14)
+//const Int_t defpedr [] = {20617,20619,20621,20623,20625,20628,20630,
+//			  20632,20635,20637,20640,20643,20645,20647};
+
+
+//const Int_t defcalr [] = {20651};
+const Int_t defcalr [] = {20822};
+
+// Mrk (20)
+const Int_t defdatar[] = {20824};
+//const Int_t defdatar[] = {20591,20592,20594,20595,20597,20598,20600,
+//			  20603,20604,20606,20607,20609,20610,20612,
+//			  20613,20615,20616,20650,20653,20655};
+// OffMrk (18)
+// const Int_t defdatar[] = {20618,20620,20622,20624,20626,20627,20629,
+// 			  20631,20633,20634,20636,20638,20639,20641,
+//			  20642,20644,20646,20648};
+
+
+void production3(const TString inpath=defpath, 
+                    const Int_t psize=1, const Int_t pedruns[]=defpedr, 
+                    const Int_t csize=1, const Int_t calruns[]=defcalr, 
+                    const Int_t dsize=1, const Int_t dataruns[]=defdatar, 
+                    const TString resname=defrout)
+
+{
+
+  //
+  // Choose the signal Extractor:
+  //
+  //MExtractSlidingWindow extractor;
+  MExtractFixedWindowPeakSearch extractor;
+  //MExtractFixedWindow    extractor;   
+
+  //
+  // Set Ranges or Windows
+  //
+  extractor.SetRange(3,14,3,14);
+  //extractor.SetWindows(8,8);
+
+  //
+  // Choose the arrival time Extractor:
+  //
+  MExtractTimeFastSpline       timeext;
+  //  MExtractTimeHighestIntegral timeext;
+  //  MExtractTimeSpline          timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(2,12,4,14);
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+
+  for (Int_t i=0;i<psize;i++) {
+    cout << "Adding pedestal run: " << pedruns[i] << endl;
+    pruns.AddRun(pedruns[i],inpath);
+  }
+  for (Int_t i=0;i<csize;i++) {
+    cout << "Adding calibration run: " << calruns[i] << endl;
+    cruns.AddRun(calruns[i],inpath);
+  }
+  for (Int_t i=0;i<dsize;i++) {
+    cout << "Adding data run: " << dataruns[i] << endl;
+    druns.AddRun(dataruns[i],inpath);
+  }
+
+  
+  //
+  // Now setup the tasks and tasklist for the pedestals:
+  // ---------------------------------------------------
+  //
+  MBadPixelsCam     badcam;
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  //
+  // If you want to exclude pixels from the beginning, read 
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)
+  //
+  //  badcam.AsciiRead("badpixels.dat");
+  
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+
+  MJPedestal pedloop;
+  pedloop.SetInput(&pruns);
+  if (usedisplay)
+    {
+      MStatusDisplay *display = new MStatusDisplay;
+      display->SetUpdateTime(3000);
+      display->Resize(850,700);
+      pedloop.SetDisplay(display);
+    }
+  pedloop.SetBadPixels(badcam);
+  pedloop.SetExtractor(&extractor);
+
+  if (!pedloop.Process())
+    return;
+
+  /****************************************/
+  /* SECOND LOOP: CALIBRATION COMPUTATION */
+  /****************************************/
+
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MCalibrationQECam qecam;
+  MJCalibration     calloop;
+  calloop.SetInput(&cruns);
+  calloop.SetExtractor(&extractor);
+  //
+  // Apply rel. time calibration:
+  //
+  calloop.SetRelTimeCalibration();
+  calloop.SetTimeExtractor(&timeext);
+  //
+  // Set the corr. cams:
+  //
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop.GetBadPixels());
+  //
+  // The next two commands are for the display:
+  //
+  if (usedisplay)
+      calloop.SetDisplay(display);
+  cout << "Minchia 0" << endl;
+  //
+  // Do the event-loop:
+  //
+  if (!calloop.Process(pedloop.GetPedestalCam()))
+    return;
+  
+  cout << "Minchia 1" << endl;
+  /*************************************/
+  /* THIRD LOOP: PEDESTAL CALIBRATION  */
+  /*************************************/
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  //
+  MParList  plist3;
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+  cout << "Minchia 2" << endl;
+  //
+  // Now setup the tasks and tasklist to calculate the pedestal rms in number of photons
+  // -----------------------------------------------------------------------------------
+  //
+  
+  MCerPhotEvt    nphot;
+  MPedPhotCam    nphotrms;
+  
+  plist3.AddToList(&geomcam);
+  cout << "Minchia 3" << endl;
+  //
+  // Retrieve the cameras from the previous runs:
+  //
+  plist3.AddToList(&pedloop.GetPedestalCam());
+  plist3.AddToList(&calloop.GetCalibrationCam());
+  plist3.AddToList(&calloop.GetQECam());
+  plist3.AddToList(&calloop.GetRelTimeCam());
+  plist3.AddToList(&calloop.GetBadPixels());
+  plist3.AddToList(&nphot);
+  plist3.AddToList(&nphotrms);
+    cout << "Minchia 4" << endl;
+  //tasks
+  MReadMarsFile read3("Events");
+  read3.DisableAutoScheme();
+  static_cast<MRead&>(read3).AddFiles(pruns);  
+
+  //MCalibrate       photcalc;
+  MCalibrateData       photcalc;
+  photcalc.SetCalibrationMode(MCalibrate::kFfactor);
+  MPedPhotCalc  photrmscalc;  //It doesn't exist yet
+  
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&extractor);
+  tlist3.AddToList(&photrmscalc);
+  //tlist3.AddToList(&photcalc);
+  
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+  
+  //
+  // Execute first analysis
+  //
+  if (!evtloop3.Eventloop())
+    return;
+  
+  tlist3.PrintStatistics();
+  
+  /*************************************/
+  /* FOURTH LOOP: DATA CALIBRATION     */
+  /*************************************/
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  //
+  MParList  plist4;
+  MTaskList tlist4;
+  plist4.AddToList(&tlist4);
+  
+  //
+  // Now setup the tasks and tasklist to analize the data
+  // -----------------------------------------------------
+  //
+  
+  plist4.AddToList(&geomcam);
+  //
+  // Retrieve the cameras from the previous runs:
+  //
+  plist4.AddToList(&pedloop.GetPedestalCam());
+  plist4.AddToList(&calloop.GetCalibrationCam());
+  plist4.AddToList(&calloop.GetQECam());
+  plist4.AddToList(&calloop.GetRelTimeCam());
+  plist4.AddToList(&calloop.GetBadPixels());
+  plist4.AddToList(&nphot);
+  plist4.AddToList(&nphotrms);
+
+  MArrivalTime times;
+  plist4.AddToList(&times);
+  
+  //tasks
+  MReadMarsFile read4("Events");
+  read4.DisableAutoScheme();
+  static_cast<MRead&>(read4).AddFiles(druns);  
+  
+  MArrivalTimeCalc2   timecalc;
+  MCalibrateRelTimes  timecal;
+
+  tlist4.AddToList(&read4);
+  tlist4.AddToList(&geomapl);
+  tlist4.AddToList(&extractor);
+  tlist4.AddToList(&timecalc);
+  tlist4.AddToList(&photcalc);
+  tlist4.AddToList(&timecal);
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop4;
+  evtloop4.SetParList(&plist4);
+
+  if (!evtloop4.PreProcess())
+    return;
+  
+  TCanvas *c1 = new TCanvas;
+  MHCamera disp1(geomcam);
+  disp1.SetPrettyPalette();
+  //disp1.SetInvDeepBlueSeaPalette()
+  disp1.Draw();
+  gPad->SetLogy();
+  gPad->cd(1);
+  
+  /*
+  TCanvas *c2 = new TCanvas;
+  MHCamera disp2(geomcam);
+  disp2.SetPrettyPalette();
+  //disp2.SetInvDeepBlueSeaPalette()
+  disp2.Draw();
+  gPad->SetLogy();
+  gPad->cd(1);
+  */
+  while (tlist4.Process())
+    {
+      disp1.SetCamContent(nphot);
+      
+      gPad->Modified();
+      gPad->Update();
+
+      /*    
+      disp2.SetCamContent(times);
+      
+      gPad->Modified();
+      gPad->Update();
+      */
+
+      // Remove the comments if you want to go through the file
+      // event-by-event:
+      if (!HandleInput())
+        break;
+    }
+
+  evtloop4.PostProcess();
+  
+}
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/readIPR.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/readIPR.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/readIPR.C	(revision 9772)
@@ -0,0 +1,147 @@
+///////////////////////////////////////////////////////////////////////////
+// 
+//    readIPR.C
+//
+//   This macro shows how to read the Individual Pixel Rates from 
+//   a CC report file.
+//
+//   Input: 
+//     - root file obtained merpping a .rep CC file
+//       container: MTriggerIPR
+//
+//   Output:
+//     - a camera display showing the IPRs
+//     - Some histos for checking purposes
+//   
+//   Note: 
+//     a similar macro can be used to read the following trigger containers:
+//     - MTriggerIPR        (Individual Pixel Rates)
+//     - MTriggerCell       (Rate of trigger cells)
+//     - MTriggerBit        (Output Bits from prescaler (before/after presc.)
+//     - MTriggerPrescFact  (Prescaling factors for each bit)
+//     - MTriggerLiveTime   (Values of counters for dead/livetime)
+//
+//    Author(s): Antonio Stamerra. 09/04 <antonio.stamerra@pi.infn.it>
+//
+////////////////////////////////////////////////////////////////////////////
+void readIPR(TString fname)
+{
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+
+    // Create the magic geometry
+    MGeomCamMagic geom;
+    plist.AddToList(&geom);
+
+    // First Task: Read ROOT file with Trigger-REPORT data
+    MReadTree read("Trigger", fname);
+    read.DisableAutoScheme();
+
+    tlist.AddToList(&read);
+
+    // Create the container for the IPRs
+    MTriggerIPR ipr;
+    plist.AddToList(&ipr);
+
+    // Create the histo to display the IPRs
+    MHCamEvent IPRhist("IPRhist","IPRs");
+    plist.AddToList(&IPRhist);
+        
+    // create a task to fill a histogram from the container
+    MFillH fillIPR(&IPRhist, "MTriggerIPR");
+    tlist.AddToList(&fillIPR);
+
+    //
+    // Create and setup the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute the analysis
+    //
+    if (!evtloop.PreProcess())
+      return;
+    
+    if (!evtloop.Eventloop())
+      return;
+
+    tlist.PrintStatistics();
+
+    //-----------------------------------
+    // Now display the result of the loop
+    //
+
+    // create a MHCamera histo where the sum off all events is filled
+    MHCamera &h = *(MHCamera*)IPRhist.GetHistByName("sum");
+
+    TCanvas *c = MH::MakeDefCanvas();
+    c->Divide(3, 2);
+
+    MHCamera *disp1=h.Clone();
+    MHCamera *disp2=h.Clone();
+    MHCamera *disp3=h.Clone();
+    disp2->SetCamContent(h, 1);
+    disp3->SetCamContent(h, 2);
+
+    disp1->SetYTitle("Rate [Hz]");
+    disp2->SetYTitle("\\sigma_{Rate} [Hz]");
+    disp3->SetYTitle("\\sigma_{Rate} [%]");
+    disp1->SetName("IPRs;avg");
+    disp2->SetName("IPRs;err");
+    disp3->SetName("IPRs;rel");
+    disp1->SetTitle("IPRs Average");
+    disp2->SetTitle("IPRs error");
+    disp3->SetTitle("IPRs relative error");
+
+    c->cd(1);
+    TText text(0.1, 0.95, &fname[fname.Last('/')+1]);
+    text.SetTextSize(0.03);
+    text.DrawClone();
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp1->Draw();
+    disp1->SetBit(kCanDelete);
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp2->Draw();
+    disp2->SetBit(kCanDelete);
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->Divide(1,1);
+    gPad->cd(1);
+    gPad->SetLogy();
+    disp3->Draw();
+    disp3->SetBit(kCanDelete);
+    c->cd(4);
+    gPad->SetBorderMode(0);
+    disp1->Draw("EPhist");
+    c->cd(5);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    disp2->Draw("Phist");
+    c->cd(6);
+    gPad->SetBorderMode(0);
+    gPad->SetLogy();
+    disp3->Draw("Phist");
+
+    c->SaveAs(fname(0, fname.Last('.')+1) + "ps");
+    //c->SaveAs(fname(0, fname.Last('.')+1) + "root");
+}
+
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/test_findstar.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/test_findstar.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/test_findstar.C	(revision 9772)
@@ -0,0 +1,98 @@
+// This macro creates a fake MCerPhotEvt container (with some clusters
+// that simulate the starfield seen by the DC currents) and then applies
+// the image cleaning and the Hillas algorithm to recognize and classify
+// the clusters.
+//
+void test_findstar();
+{
+  // Empty container and task lists
+  MParList plist;
+  MTaskList tlist;
+
+  //  cout << "0" <<endl;  
+  plist.AddToList(&tlist);
+
+  MCerPhotEvt *DCEvt;
+
+  MGeomCamMagic *geom; 
+
+  const Int_t gsNpix = 577;
+
+  TArrayF *startpixs(gsNpix);
+  Int_t cluster[gsNpix];
+  memset(cluster,-1,gsNpix*sizeof(Int_t));
+  memset(startpixs,-1,gsNpix*sizeof(Int_t));
+
+  // fill a fake MCerPhotEvt 
+
+// loop over all pixels
+  
+  for (Int_t pixid = 0; pixid <gsNpix ; pixid++)
+    {
+      MCerPhotPix dcpix =  DCEvt[pixid];
+
+      cout << "1" <<endl;  
+      // a fake cluster:
+      dcpix->SetNumPhotons(0.);
+      
+      switch (pixid)
+      {
+      case 10:
+	dcpix->SetNumPhotons(1.5);
+      case 3:
+	dcpix->SetNumPhotons(1.1);
+      case 9:
+	dcpix->SetNumPhotons(1.1);
+      case 22:
+	dcpix->SetNumPhotons(1.1);
+      case 23:
+	dcpix->SetNumPhotons(1.1);
+      case 24:
+	dcpix->SetNumPhotons(1.1);
+      case 11:
+	dcpix->SetNumPhotons(1.1);
+      };
+    }; // end loop over pixels
+
+  
+  if (!(FindStartPixels(DCEvt, startpixs, geom)))
+    cout << "Error calling the FindStartPixels function!!" << endl;
+  
+  return;
+};  
+
+Int_t FindStartPixels(MCerPhotEvt *evt, TArrayF *startpixs, MGeomCam *geom)
+{
+  // look for all the pixels with a DC higher than the DC of neighbour pixels 
+
+  // loop over all pixels
+  MCerPhotEvtIter Next(evt, kFALSE);
+  
+  for (Int_t pixid=0; pixid<gsNPix; pixid++)
+    {
+      MCerPhotPix dcpix =  DCEvt[pixid]; // curren pix with DC
+
+      const MGeomPix &pix = (*geom)[pixid]; // MGeomCam pixel
+      
+      currDC = dcpix->GetNumPhotons();  // DC of current pixel
+
+      // look for the max DC in the neighbors pixels
+      Float_t macDC = 0;
+      for (Int_t j=0; j<pix.GetNumNeighbors()-1; j++) 
+	if ( evt[pix.GetNeighbor(j)]->GetNumPhotons() > maxDC) 
+	  maxDC = evt[pix.GetNeighbor(j)]->GetNumPhotons();
+     
+      // a starting pixel was found: it is added to the array and the pointer
+      // to the array is increased by 1
+      if ( currDC > maxDC)
+	*(startpixs++) = currDC;
+    }
+
+  return 1;
+}
+
+Int_t FindCluster(Int_t startpix, Int_t cluster, MGeomCam *geom)
+{
+  return 1;
+
+} ;
Index: /tags/Mars-V0.9/mtemp/mpisa/macros/timedist3.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/macros/timedist3.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/macros/timedist3.C	(revision 9772)
@@ -0,0 +1,394 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Javier López, 12/2003 <mailto:jlopez@ifae.es>
+!              Markus Gaug , 04/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  bootcampstandardanalysis.C
+//
+//  Updated version of the macro designed at the Wuerzburg bootcamp and 
+//  compatible with the latest changes in Mars for general usage at the
+//  Udine bootcamp. 
+//
+//  Needs as arguments the run number of a pedestal file ("*_P_*.root"), 
+//  one of a calibration file ("*_C_*.root") and one of a data file 
+//  ("*_D_*.root"). Performs the pedestal calculation, the calibration 
+/// constants calculation and the calibration of the data. 
+//
+//  The TString inpath has to be set correctly.
+//
+//  The macro searches for the pulser colour which corresponds to the calibration
+//  run number. If the run number is smaller than 20000, pulser colour "CT1" 
+//  is assumed, otherwise, it searches for the strings "green", "blue", "uv" or 
+//  "ct1" in the filenames. If no colour or multiple colours are found, the 
+//  execution is aborted.  
+//
+//////////////////////////////////////////////////////////////////////////////////
+const Bool_t usedisplay = kTRUE;
+const TString defpath = "/data1/earth/magic/data/Period015/rootdata/2004_03_19/";
+const TString outpath = "./";
+const TString defrout = "output_Mrk421_20040319.root";
+// Mrk (13)
+const Int_t defpedr[] = {20823};
+//const Int_t defpedr [] = {20590,20593,20596,20599,20601,20602,20605,
+//			  20608,20611,20614,20649,20652,20654};
+// OffMrk (14)
+//const Int_t defpedr [] = {20617,20619,20621,20623,20625,20628,20630,
+//			  20632,20635,20637,20640,20643,20645,20647};
+
+
+//const Int_t defcalr [] = {20651};
+const Int_t defcalr [] = {20822};
+
+// Mrk (20)
+const Int_t defdatar[] = {20824};
+//const Int_t defdatar[] = {20591,20592,20594,20595,20597,20598,20600,
+//			  20603,20604,20606,20607,20609,20610,20612,
+//			  20613,20615,20616,20650,20653,20655};
+// OffMrk (18)
+// const Int_t defdatar[] = {20618,20620,20622,20624,20626,20627,20629,
+// 			  20631,20633,20634,20636,20638,20639,20641,
+//			  20642,20644,20646,20648};
+
+
+void timedist3(const TString inpath=defpath, 
+                    const Int_t psize=1, const Int_t pedruns[]=defpedr, 
+                    const Int_t csize=1, const Int_t calruns[]=defcalr, 
+                    const Int_t dsize=1, const Int_t dataruns[]=defdatar, 
+                    const TString resname=defrout)
+
+{
+
+  //
+  // Choose the signal Extractor:
+  //
+  //MExtractSlidingWindow extractor;
+  MExtractFixedWindowPeakSearch extractor;
+  //MExtractFixedWindow    extractor;   
+
+  //
+  // Set Ranges or Windows
+  //
+  extractor.SetRange(3,14,3,14);
+  //extractor.SetWindows(8,8);
+
+  //
+  // Choose the arrival time Extractor:
+  //
+  MExtractTimeFastSpline       timeext;
+  //  MExtractTimeHighestIntegral timeext;
+  //  MExtractTimeSpline          timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(2,12,4,14);
+
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+
+  for (Int_t i=0;i<psize;i++) {
+    cout << "Adding pedestal run: " << pedruns[i] << endl;
+    pruns.AddRun(pedruns[i],inpath);
+  }
+  for (Int_t i=0;i<csize;i++) {
+    cout << "Adding calibration run: " << calruns[i] << endl;
+    cruns.AddRun(calruns[i],inpath);
+  }
+  for (Int_t i=0;i<dsize;i++) {
+    cout << "Adding data run: " << dataruns[i] << endl;
+    druns.AddRun(dataruns[i],inpath);
+  }
+
+  
+  //
+  // Now setup the tasks and tasklist for the pedestals:
+  // ---------------------------------------------------
+  //
+  MBadPixelsCam     badcam;
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  //
+  // If you want to exclude pixels from the beginning, read 
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)
+  //
+  //  badcam.AsciiRead("badpixels.dat");
+  
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+
+  MJPedestal pedloop;
+  pedloop.SetInput(&pruns);
+  if (usedisplay)
+    {
+      MStatusDisplay *display = new MStatusDisplay;
+      display->SetUpdateTime(3000);
+      display->Resize(850,700);
+      pedloop.SetDisplay(display);
+    }
+  pedloop.SetBadPixels(badcam);
+  pedloop.SetExtractor(&extractor);
+
+  if (!pedloop.Process())
+    return;
+
+//   /****************************************/
+//   /* SECOND LOOP: CALIBRATION COMPUTATION */
+//   /****************************************/
+
+//   //
+//   // Now setup the new tasks for the calibration:
+//   // ---------------------------------------------------
+//   //
+//   MCalibrationQECam qecam;
+//   MJCalibration     calloop;
+//   calloop.SetInput(&cruns);
+//   calloop.SetExtractor(&extractor);
+//   //
+//   // Apply rel. time calibration:
+//   //
+//   calloop.SetRelTimeCalibration();
+//   calloop.SetTimeExtractor(&timeext);
+//   //
+//   // Set the corr. cams:
+//   //
+//   calloop.SetQECam(qecam);
+//   calloop.SetBadPixels(pedloop.GetBadPixels());
+//   //
+//   // The next two commands are for the display:
+//   //
+//   if (usedisplay)
+//       calloop.SetDisplay(display);
+//   cout << "Minchia 0" << endl;
+//   //
+//   // Do the event-loop:
+//   //
+//   if (!calloop.Process(pedloop.GetPedestalCam()))
+//     return;
+  
+//   cout << "Minchia 1" << endl;
+//   /*************************************/
+//   /* THIRD LOOP: PEDESTAL CALIBRATION  */
+//   /*************************************/
+
+//   //
+//   // Create a empty Parameter List and an empty Task List
+//   //
+//   MParList  plist3;
+//   MTaskList tlist3;
+//   plist3.AddToList(&tlist3);
+//   cout << "Minchia 2" << endl;
+//   //
+//   // Now setup the tasks and tasklist to calculate the pedestal rms in number of photons
+//   // -----------------------------------------------------------------------------------
+//   //
+  
+//   MCerPhotEvt    nphot;
+//   MPedPhotCam    nphotrms;
+  
+//   plist3.AddToList(&geomcam);
+//   cout << "Minchia 3" << endl;
+//   //
+//   // Retrieve the cameras from the previous runs:
+//   //
+//   plist3.AddToList(&pedloop.GetPedestalCam());
+//   plist3.AddToList(&calloop.GetCalibrationCam());
+//   plist3.AddToList(&calloop.GetQECam());
+//   plist3.AddToList(&calloop.GetRelTimeCam());
+//   plist3.AddToList(&calloop.GetBadPixels());
+//   plist3.AddToList(&nphot);
+//   plist3.AddToList(&nphotrms);
+//     cout << "Minchia 4" << endl;
+//   //tasks
+//   MReadMarsFile read3("Events");
+//   read3.DisableAutoScheme();
+//   static_cast<MRead&>(read3).AddFiles(pruns);  
+
+//   //MCalibrate       photcalc;
+//   MCalibrateData       photcalc;
+//   photcalc.SetCalibrationMode(MCalibrate::kFfactor);
+//   MPedPhotCalc  photrmscalc;  //It doesn't exist yet
+  
+//   tlist3.AddToList(&read3);
+//   tlist3.AddToList(&geomapl);
+//   tlist3.AddToList(&extractor);
+//   tlist3.AddToList(&photrmscalc);
+//   //tlist3.AddToList(&photcalc);
+  
+  
+//   //
+//   // Create and setup the eventloop
+//   //
+//   MEvtLoop evtloop3;
+//   evtloop3.SetParList(&plist3);
+  
+//   //
+//   // Execute first analysis
+//   //
+//   if (!evtloop3.Eventloop())
+//     return;
+  
+//   tlist3.PrintStatistics();
+  
+  /*************************************/
+  /* FOURTH LOOP: DATA CALIBRATION     */
+  /*************************************/
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  //
+  MParList  plist4;
+  MTaskList tlist4;
+  plist4.AddToList(&tlist4);
+  
+  //
+  // Now setup the tasks and tasklist to analize the data
+  // -----------------------------------------------------
+  //
+  
+  plist4.AddToList(&geomcam);
+  //
+  // Retrieve the cameras from the previous runs:
+  //
+  plist4.AddToList(&pedloop.GetPedestalCam());
+  //  plist4.AddToList(&calloop.GetCalibrationCam());
+  // plist4.AddToList(&calloop.GetQECam());
+  // plist4.AddToList(&calloop.GetRelTimeCam());
+  //plist4.AddToList(&calloop.GetBadPixels());
+  //plist4.AddToList(&nphot);
+  //plist4.AddToList(&nphotrms);
+
+  MArrivalTimeCam times;
+  plist4.AddToList(&times);
+  
+  //tasks
+  MReadMarsFile read4("Events");
+  read4.DisableAutoScheme();
+  static_cast<MRead&>(read4).AddFiles(druns);  
+  
+  MArrivalTimeCalc2   timecalc;
+  //MCalibrateRelTimes  timecal;
+  
+  tlist4.AddToList(&read4);
+  tlist4.AddToList(&geomapl);
+  //tlist4.AddToList(&extractor);
+  tlist4.AddToList(&timecalc);
+  //  tlist4.AddToList(&photcalc);
+  //tlist4.AddToList(&timecal);
+  MRawEvtData *evtData;
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop4;
+  evtloop4.SetParList(&plist4);
+  histTime = new TH1F("histTime","Arrival Time Dist",15,0.0,15.0);
+  Int_t i=0;
+  if (!evtloop4.PreProcess())
+    return;
+  
+  TCanvas *c1 = new TCanvas;
+  MHCamera disp1(geomcam);
+  disp1.SetPrettyPalette();
+  //disp1.SetInvDeepBlueSeaPalette()
+  disp1.Draw();
+  gPad->SetLogy();
+  gPad->cd(1);
+  
+  /*
+  TCanvas *c2 = new TCanvas;
+  MHCamera disp2(geomcam);
+  disp2.SetPrettyPalette();
+  //disp2.SetInvDeepBlueSeaPalette()
+  disp2.Draw();
+  gPad->SetLogy();
+  gPad->cd(1);
+  */
+  while (tlist4.Process())
+    {
+      i++;
+      //disp1.SetCamContent(nphot);
+      
+      //gPad->Modified();
+      //gPad->Update();
+      //      cout << i << endl;
+      //if((i == 16)||(i == 41)||(i == 111)||(i == 173)){
+      if((i == 41)){
+	cout << "Merda" << endl;
+	evtData = (MRawEvtData *)plist4->FindObject("MRawEvtData");
+	cout << "Merda1" << tlist4->FindObject("MRawEvtData") << endl;
+	MRawEvtPixelIter *pixIter = new MRawEvtPixelIter(evtData);
+	cout << "Merda2" << endl;
+	for (Int_t pix=1;pix<576;pix++){	  
+	  pixIter->Next();
+	  cout << "Merda3" << endl;
+	  if(pixIter->GetSumHiGainSamples()>200){
+	    cout << "Merda5" << endl;
+	    cout << "pix #" << pixIter->GetPixelId() << "  FADC Charge = " << pixIter->GetSumHiGainSamples() << endl;
+	    histTime->Fill((times[pix])->GetArrivalTimeHiGain());
+	  }
+	  cout << i << endl;
+	}
+      }
+      
+      /*    
+      disp2.SetCamContent(times);
+      
+      gPad->Modified();
+      gPad->Update();
+      */
+
+      // Remove the comments if you want to go through the file
+      // event-by-event:
+      //if (!HandleInput())
+      //break;
+    }
+
+  evtloop4.PostProcess();
+  histTime->DrawCopy();
+}
+
+Bool_t HandleInput()
+{
+    TTimer timer("gSystem->ProcessEvents();", 50, kFALSE);
+
+    while (1)
+    {
+        //
+        // While reading the input process gui events asynchronously
+        //
+        timer.TurnOn();
+        TString input = Getline("Type 'q' to exit, <return> to go on: ");
+        timer.TurnOff();
+
+        if (input=="q\n")
+            return kFALSE;
+
+        if (input=="\n")
+            return kTRUE;
+    };
+
+    return kFALSE;
+}
+
Index: /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MMcTriggerLvl2.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MMcTriggerLvl2.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MMcTriggerLvl2.cc	(revision 9772)
@@ -0,0 +1,1040 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Antonio Stamerra  1/2003 <mailto:antono.stamerra@pi.infn.it>
+!   Author(s): Marcos Lopez 1/2003 <mailto:marcos@gae.ucm.es>
+!   Author(s): Nicola Galante 7/2003 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MMcTriggerLvl2                                                          //
+//   Storage container for the 2nd level trigger selection parameters      //
+//    as part of the 2nd level trigger simulation                          //
+//                                                                         //
+// input parameter:                                                        //
+//    fCompactNN number of next neighboors that define a compact pixel     //
+//                                                                         //
+//                                                                         //
+// Basic L2T Selection Parameters:                                         //
+//                                                                         //
+//    fLutPseudoSize number of compact pixels in one LUT                   //
+//    fPseudoSize Multiplicity of the bigger cluster                       //
+//    fSizeBiggerCell higher number of fired pixel in cell                 //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MMcTriggerLvl2.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+#include "MGeomCamMagic.h"
+
+#include "MMcTrig.hxx"
+
+#include "MMcEvt.hxx"
+
+#include "MLog.h"
+
+#include <TCanvas.h>
+
+ClassImp(MMcTriggerLvl2);
+
+using namespace std;
+
+// ---------------------------
+// Initialization of static const data members pixel_in_cell and pixel_in_lut
+
+//
+// Correspondence TABLE between pixel numbering in the trigger cells and
+// the standard spiral counting 
+// (*Note*: Pixels start to count ** from 1 ** instead of 0)
+//
+// This correspondence is valid only for MAGIC-like geometries!
+//
+//  FIXME!  These definitions should be included in a GeomTrig class
+//
+const  Int_t  MMcTriggerLvl2::gsPixelsInCell[gsNPixInCell][gsNCells] = {
+    {26,  91,  66,  71,  76,  81,  86,  269,  224,  233,  242,  251,  260,  391,  336,  347,  358,	369,  380},
+    {25,  61,  41,  45,  49,  53,  57,  215,  175,  183,  191,  199,  207,  325,  275,  285,  295,  305,  315},
+    {24,  37,  22,  25,  28,  31,  34,  167,  132,  139,  146,  153,  160,  265,  220,  229,  238,  247,  256},
+    {23,  19,   9,  11,  13,  15,  17,  125,   95,  101,  107,  113,  119,  211,  171,  179,  187,  195,  203},
+    {27,  62,  67,  72,  77,  82,  87,  270,  225,  234,  243,  252,  261,  392,  337,  348,  359,  370,  381},
+    {12,  38,  42,  46,  50,  54,  58,  216,  176,  184,  192,  200,  208,  326,  276,  286,  296,  306,  316},
+    {11,  20,  23,  26,  29,  32,  35,  168,  133,  140,  147,  154,  161,  266,  221,  230,  239,  248,  257},
+    {10,   8,  10,  12,  14,  16,  18,  126,   96,  102,  108,  114,  120,  212,  172,  180,  188,  196,  204},
+    {22,   2,   3,   4,   5,   6,   7,   90,   65,   70,   75,   80,   85,  164,  129,  136,  143,  150,  157},
+    {28,  93,  99, 105, 111, 117, 123,  271,  226,  235,  244,  253,  262,  393,  338,  349,  360,  371,  382},
+    {13,  63,  68,  73,  78,  83,  88,  217,  177,  185,  193,  201,  209,  327,  277,  287,  297,  307,  317},
+    { 4,  39,  43,  47,  51,  55,  59,  169,  134,  141,  148,  155,  162,  267,  222,  231,  240,  249,  258},
+    { 3,  21,  24,  27,  30,  33,  36,  127,   97,  103,  109,  115,  121,  213,  173,  181,  189,  197,  205},
+    { 9,   9,  11,  13,  15,  17,  19,   91,   66,   71,   76,   81,   86,  165,  130,  137,  144,  151,  158},
+    {21,   3,   4,   5,   6,   7,   2,   61,   41,   45,   49,   53,   57,  123,   93,   99,  105,  111,  117},
+    {29, 130, 137, 144, 151, 158, 165,  218,  227,  236,  245,  254,  263,  394,  339,  350,  361,  372,  383},
+    {14,  94, 100, 106, 112, 118, 124,  170,  178,  186,  194,  202,  210,  328,  278,  288,  298,  308,  318},
+    { 5,  64,  69,  74,  79,  84,  89,  128,  135,  142,  149,  156,  163,  268,  223,  232,  241,  250,  259},
+    { 1,  40,  44,  48,  52,  56,  60,   92,   98,  104,  110,  116,  122,  214,  174,  182,  190,  198,  206},
+    { 2,  22,  25,  28,  31,  34,  37,   62,   67,   72,   77,   82,   87,  166,  131,  138,  145,  152,  159},
+    { 8,  10,  12,  14,  16,  18,   8,   38,   42,   46,   50,   54,   58,  124,   94,  100,  106,  112,  118},
+    {20,  11,  13,  15,  17,  19,   9,   20,   23,   26,   29,   32,   35,   88,   63,   68,   73,   78,   83},
+    {30, 131, 138, 145, 152, 159, 166,  219,  228,  237,  246,  255,  264,  329,  279,  289,  299,  309,  319},
+    {15,  95, 101, 107, 113, 119, 125,  171,  179,  187,  195,  203,  211,  269,  224,  233,  242,  251,  260},
+    { 6,  65,  70,  75,  80,  85,  90,  129,  136,  143,  150,  157,  164,  215,  175,  183,  191,  199,  207},
+    { 7,  41,  45,  49,  53,  57,  61,   93,   99,  105,  111,  117,  123,  167,  132,  139,  146,  153,  160},
+    {19,  23,  26,  29,  32,  35,  20,   63,   68,   73,   78,   83,   88,  125,   95,  101,  107,  113,  119},
+    {37,  24,  27,  30,  33,  36,  21,   39,   43,   47,   51,   55,   59,   89,   64,   69,   74,   79,   84},
+    {31, 132, 139, 146, 153, 160, 167,  220,  229,  238,  247,  256,  265,  270,  225,  234,  243,  252,  261},
+    {16,  96, 102, 108, 114, 120, 126,  172,  180,  188,  196,  204,  212,  216,  176,  184,  192,  200,  208},
+    {17,  66,  71,  76,  81,  86,  91,  130,  137,  144,  151,  158,  165,  168,  133,  140,  147,  154,  161},
+    {18,  42,  46,  50,  54,  58,  38,   94,  100,  106,  112,  118,  124,  126,   96,  102,  108,  114,  120},
+    {36,  43,  47,  51,  55,  59,  39,   64,   69,   74,   79,   84,   89,   90,   65,   70,   75,   80,   85},
+    {32, 133, 140, 147, 154, 161, 168,  221,  230,  239,  248,  257,  266,  217,  177,  185,  193,  201,  209},
+    {33,  97, 103, 109, 115, 121, 127,  173,  181,  189,  197,  205,  213,  169,  134,  141,  148,  155,  162},
+    {35,  68,  73,  78,  83,  88,  63,   95,  101,  107,  113,  119,  125,   91,   66,   71,   76,   81,   86}
+  };
+
+//
+// corrispondence between pixels in cell and lut (pix numbering starts from 1)
+//
+const Int_t MMcTriggerLvl2::gsPixelsInLut[gsNLutInCell][gsNPixInLut] = {
+    { 1,  2,  3,  4,  6,  7,  8,  9, 12, 13, 14, 15},
+    {34, 29, 23, 16, 30, 24, 17, 10, 25, 18, 11,  5},
+    {35, 31, 26, 20, 19, 32, 27, 21, 36, 33, 28, 22},
+  };
+
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor
+//
+MMcTriggerLvl2::MMcTriggerLvl2(const char *name, const char *title):fCompactNN(2),fTriggerPattern(0)
+{
+  fName = name ? name : ClassName();
+  fTitle = title;
+
+  *fLog << "created MMcTriggerLvl2" << endl;
+
+  //
+  // Initialization of the fPixels array to zero
+  //
+  memset (fPixels,0,gsNPixInCell*gsNCells*sizeof(Int_t));
+  memset (fFiredPixel,0,gsNTrigPixels*sizeof(Int_t));
+
+  // create a new camera
+  SetNewCamera(new MGeomCamMagic);
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor
+//
+MMcTriggerLvl2::~MMcTriggerLvl2()
+{
+  delete fGeomCam;
+}
+
+// --------------------------------------------------------------------------
+//  
+//  Print functions for debugging and testing
+//
+//  Options available:
+//
+// "cell":
+//     Print out the pixel number of a given trigger cell
+//
+// "status":
+//     Print a table with the status (pixel is fired or not after Lvl1) for 
+//     all the pixels in all the trigger cells
+//
+// "check"
+//     Print a warning message when no starting pixel is found in the 
+//     CalcPseudoSize method.
+//
+//  no option:
+//     Print the value of the selection parameters
+//
+//
+void MMcTriggerLvl2::Print(Option_t *opt) const
+{
+  TString str(opt);
+
+  if (str.Contains("status", TString::kIgnoreCase)) 
+    {
+      *fLog << "    Status of cells 1-9" <<endl;
+      for(int i=0; i<gsNPixInCell; i++)
+	{
+	  for(int j=0; j<9; j++)
+	    {
+	      //      *fLog.width(3);
+	      *fLog <<gsPixelsInCell[i][j]-1 << ":" << fPixels[i][j]  << "\t ";
+	    } 
+	  *fLog << endl;
+	}      
+    }
+  else if (str.Contains("cell", TString::kIgnoreCase)) 
+    {
+      *fLog << "   Pixel numbering in cells 1-9" <<endl;
+      for (int i=0;i<gsNPixInCell;i++)
+	{
+	  for(int j=0; j<9; j++)
+	    {
+	      *fLog << gsPixelsInCell[i][j]-1 << "\t";
+	    }
+	  *fLog << endl;
+	}
+    }
+  else if (str.Contains("check", TString::kIgnoreCase)) 
+    {
+      // check when no starting pixels was found (<<--to be fixed)
+      if (fPseudoSize < 0)
+	*fLog << "  Warning: starting pixel not found. Pseudosize set to -1." << endl;
+    }
+  else 
+    {
+      *fLog << "  L2T selection parameters: " << endl;
+      *fLog << "   - LutPseudoSize  = " << fLutPseudoSize <<  endl;
+      *fLog << "   - CellPseudoSize  = " << fCellPseudoSize <<  endl;
+      *fLog << "   - PseudoSize  = " << fPseudoSize <<  endl;
+      *fLog << "   - BiggerCellSize = " << fSizeBiggerCell << endl;
+      *fLog << "   - TriggerPattern = " << fTriggerPattern << endl;
+    }
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Take the information supplied by the Lvl1 (it reads from the object MMcTrig
+// the status of all pixels after Lvl1) and pass it to the Lvl2 (fill the 
+// array fPixels)
+//
+//
+void MMcTriggerLvl2::SetLv1(MMcTrig *trig)
+{
+  if (!trig)
+    return;
+
+  fMcTrig = trig;
+
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      for(int j=0; j<gsNCells; j++)
+	{
+	  int pixel = gsPixelsInCell[i][j]-1;
+	  fPixels[i][j] = (fMcTrig->IsPixelFired(pixel,0)) ? 1 : 0;
+	  fFiredPixel[pixel]=(fMcTrig->IsPixelFired(pixel,0)) ? 1 : 0;
+	  //if (fFiredPixel[pixel]==1)
+	  //*fLog << pixel<<",";
+	}
+    }
+  //*fLog<<endl<<"Fine evento"<<endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the trigger status ( pixel fired(=1) or not(=0) ) manually for a given
+// pixel of a given cell
+//
+//
+void MMcTriggerLvl2::SetPixelFired(Int_t pixel, Int_t fired)
+{
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      for(int j=0; j<gsNCells; j++)
+	{
+	  if(gsPixelsInCell[i][j]-1==pixel) fPixels[i][j]=fired;
+	}
+    }
+
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Level 2 Trigger (L2T) parameters. They can be used 
+//  to select the events that have passed the L2T selection rule.
+//
+//
+void MMcTriggerLvl2::Calc()
+{
+
+  // Find the Lut and cell with the higher LutPseudoSize. 
+  int lutcell = CalcBiggerLutPseudoSize(); 
+  fMaxCell = lutcell/10;
+  int maxlut = lutcell-fMaxCell*10;
+  fLutPseudoSize = GetLutCompactPixel(fMaxCell,maxlut);
+
+  fMaxCell = CalcBiggerCellPseudoSize();  // fCellPseudoSize
+  // fMaxCell is used by the PseudoSize to find the starting pixel
+  CalcPseudoSize();
+
+  fSizeBiggerCell = GetCellNumberFired(CalcBiggerFiredCell());
+
+  //*fLog << "fLPS="<<fLutPseudoSize<<endl;
+}
+
+
+
+// --------------------------------------------------------------------------
+//  
+// For a given cell, just count how many pixels have been fired after Lvl1
+//
+Int_t MMcTriggerLvl2::GetCellNumberFired(int cell)
+{
+  int size=0;
+ 
+  for(int i=0; i<gsNPixInCell; i++)
+    {
+      size += fPixels[i][cell];
+    }
+
+  return size;
+  
+}
+
+
+// --------------------------------------------------------------------------
+//  
+//  Find the cell which the bigger number of fired pixels
+// 
+//
+Int_t MMcTriggerLvl2::CalcBiggerFiredCell()
+{
+  int size=-1;
+  int cell=-1;
+
+  for(int j=0; j<gsNCells; j++)
+    {
+      if (GetCellNumberFired(j) > size) 
+	{
+	  size = GetCellNumberFired(j);
+	  cell = j;
+	}
+    }
+  
+  //  *fLog << "size " <<size <<" in cell " << cell << endl;
+
+  return cell;
+  
+}
+
+// --------------------------------------------------------------------------
+//  
+// Calculate the higher LutPseudoSize of one event defined as the higher number
+//   of compact pixel in the LUTs of the trigger cells.
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology (it can be 2-NN or 3-NN)
+//
+//   It returns the cell and the LUT with the bigger LutPseudoSize, coded
+//      accordingly to:   cell*10 + LUT 
+//
+Int_t MMcTriggerLvl2::CalcBiggerLutPseudoSize()
+{
+  int size=0;
+  int cell=-1;
+  int lut=-1;
+ 
+  for(int j=0; j<gsNCells; j++)
+    {
+      for(int i=0; i<gsNLutInCell; i++)
+	{
+	  if (GetLutCompactPixel(j,i) >= size) 
+	    {
+	      size = GetLutCompactPixel(j,i);
+	      cell = j;
+	      lut = i;
+	    }      
+	}
+    }
+  
+  //*fLog <<"Max cell: " << cell+1 << "  Max Lut: " << lut+1 << "  PseudoSize: " << size <<endl;
+    
+  return cell*10+lut;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+// Identify compact pixels in one LUT and calculate the LutPseudoSize 
+//   (=number of compact pixels in one LUT)
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology.  
+//   Up to now only  2NN or 3NN are considered 
+//    <!if changed: change check made by Preprocess in MMcTriggerLvl2Calc>    
+//
+//   Returns: 
+//     -1    wrong neighpix
+//     -2    wrong cell (<1 or >19)
+//     -3    wrong lut  (<1 or >3)
+//    else:
+//      the number of compact pixels in one LUT.
+//     
+Int_t MMcTriggerLvl2::GetLutCompactPixel(int cell, int lut)
+{
+  int size=0;
+  int lutpix, a[gsNPixInLut]; 
+  int neighpix= (*this).fCompactNN;
+
+  // check on input variables
+
+  if (neighpix >3 || neighpix < 2) 
+    return(-1);
+
+  if (cell<0 || cell> gsNCells-1)
+    return(-2);
+
+  if (lut<0 || lut> gsNLutInCell-1)
+    return(-3);
+
+
+  //
+  // Warning!!! Following configurations are valid only for the standard MAGIC 
+  // trigger geometry; FIXME! these should be coded somewhere else....
+  //
+
+  // LUT 1 and 2 are similar; LUT 3 differs
+  
+  for(int j=0; j< gsNPixInLut; j++)
+    {
+      lutpix = gsPixelsInLut[lut][j]-1;
+      //    *fLog << "j=" <<j<<"  lutpix="<<lutpix<<"  Cell="<<cell<<endl;
+      a[j] = fPixels[lutpix][cell]; 
+    }
+  
+  //
+  // Look for compact pixels 2NN
+  //
+  if (neighpix==2)
+    {    
+      //  case Lut 1 and 2
+      if (lut == 0 || lut == 1)
+	{
+	  if (a[0] && a[1] && a[4])
+	    size ++;
+	  if (a[1] && ((a[0] && a[4]) || 
+		       (a[4] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[6]) || 
+		       (a[6] && a[7]) )) 
+	    size ++;
+	  if (a[4] && ((a[0] && a[1]) || 
+		       (a[1] && a[5]) || 
+		       (a[5] && a[8]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2]) || 
+		       (a[2] && a[6]) || 
+		       (a[6] && a[9]) || 
+		       (a[9] && a[8]) || 
+		       (a[8] && a[4]) || 
+		       (a[4] && a[1]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3]) || 
+		       (a[3] && a[7]) || 
+		       (a[7] && a[10]) || 
+		       (a[10] && a[9]) || 
+		       (a[9] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6]) || 
+		       (a[6] && a[10]) || 
+		       (a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && ((a[4] && a[5]) || 
+		       (a[5] && a[9]) )) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6]) || 
+			(a[6] && a[7]) || 
+			(a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10]) 
+	    size ++;
+	}
+      
+      //  case Lut 3
+      if (lut==2) 
+	{
+	  if (a[0] && a[1] && a[5])
+	    size ++;
+	  if (a[1] && ((a[0] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[3] && a[4]) || 
+		       (a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[6]) || 
+		       (a[6] && a[7]) || 
+		       (a[2] && a[4]) )) 
+	    size ++;
+	  if (a[4] && ((a[2] && a[3]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2]) || 
+		       (a[2] && a[6]) || 
+		       (a[6] && a[9]) || 
+		       (a[9] && a[8]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3]) || 
+		       (a[3] && a[7]) || 
+		       (a[7] && a[10]) || 
+		       (a[10] && a[9]) || 
+		       (a[9] && a[5]) || 
+		       (a[5] && a[2]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6]) || 
+		       (a[6] && a[10]) || 
+		       (a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && a[5] && a[9]) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5]) || 
+		       (a[5] && a[6]) || 
+		       (a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6]) || 
+			(a[6] && a[7]) || 
+			(a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10]) 
+	    size ++;    
+	}
+    }
+  
+  //
+  // Look for compact pixels 3NN 
+  //
+  if (neighpix==3)
+    {
+      //  case Lut 1 and 2
+      if (lut == 0 || lut == 1)
+	{
+	  if (a[0] && a[1] && a[4] && a[5]) // pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[1] && ((a[0] && a[4] && a[5]) || 
+		       (a[2] && a[4] && a[5]) )) 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[3]) )) 
+	    size ++;
+	  if (a[3] && (a[2] && a[6] && a[7] ))  
+	    size ++;
+	  if (a[4] && ((a[0] && a[1] && a[5]) || 
+		       (a[1] && a[5] && a[8]) )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2] && a[6]) || 
+		       (a[2] && a[6] && a[9]) || 
+		       (a[6] && a[9] && a[8]) || 
+		       (a[9] && a[8] && a[4]) || 
+		       (a[8] && a[4] && a[1]) || 
+		       (a[4] && a[1] && a[2]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3] && a[7]) || 
+		       (a[3] && a[7] && a[10]) || 
+		       (a[7] && a[10] && a[9]) || 
+		       (a[10] && a[9] && a[5]) || 
+		       (a[9] && a[5] && a[2]) || 
+		       (a[5] && a[2] && a[3]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6] && a[10]) || 
+		       (a[6] && a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && (a[4] && a[5] && a[9] )) 
+	    size ++;
+	  if (a[9] && ((a[8] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6] && a[7]) || 
+			(a[6] && a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10] && a[6]) //pix 0 is compact if there is a 4NN
+	    size ++;
+	}
+      
+      //  case Lut 3
+      if (lut==2) 
+	{
+	  if (a[0] && a[1] && a[5] && a[8]) // pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[1] && (a[0] && a[5] && a[2])) //pix 0 is compact if there is a 4NN 
+	    size ++;
+	  if (a[2] && ((a[1] && a[5] && a[6]) || 
+		       (a[3] && a[5] && a[6]) || 
+		       (a[6] && a[3] && a[4]) )) 
+	    size ++;
+	  if (a[3] && ((a[2] && a[4] && a[6]) || 
+		       (a[2] && a[6] && a[7]) )) 
+	    size ++;
+	  if (a[4] && (a[2] && a[3] && a[6] )) 
+	    size ++;
+	  if (a[5] && ((a[1] && a[2] && a[6]) || 
+		       (a[2] && a[6] && a[9]) || 
+		       (a[6] && a[9] && a[8]) )) 
+	    size ++;
+	  if (a[6] && ((a[2] && a[3] && a[7]) || 
+		       (a[3] && a[7] && a[10]) || 
+		       (a[7] && a[10] && a[9]) || 
+		       (a[10] && a[9] && a[5]) || 
+		       (a[9] && a[5] && a[2]) || 
+		       (a[5] && a[2] && a[3]) )) 
+	    size ++;
+	  if (a[7] && ((a[3] && a[6] && a[10]) || 
+		       (a[6] && a[10] && a[11]) )) 
+	    size ++;
+	  if (a[8] && a[5] && a[9] && a[6])  //pix 0 is compact if there is a 4NN
+	    size ++;
+	  if (a[9] && ((a[8] && a[5] && a[6]) || 
+		       (a[5] && a[6] && a[10]) )) 
+	    size ++;
+	  if (a[10] && ((a[9] && a[6] && a[7]) || 
+			(a[6] && a[7] && a[11]) )) 
+	    size ++;
+	  if (a[11] && a[7] && a[10] && a[6]) //pix 0 is compact if there is a 4NN
+	    size ++;
+	}
+    }
+  
+
+  if(size<0 ||size>gsNPixInLut)
+    *fLog << "*" << size <<"-";
+  
+  return size;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+// Look for clusters and calculate the PseudoSize of one event, 
+//   defined as the multiplicity of the bigger cluster. 
+//
+//
+//
+void MMcTriggerLvl2::CalcPseudoSize()
+{
+  // Fill the fCompactPixel array with the compact pixels
+  CalcCompactPixels(fGeomCam);
+
+  // seek the LUT with higher number of compact pixels
+  //
+  //int fMaxCell = CalcBiggerCellPseudoSize();
+  int sizetemp=0;
+  int maxlut=0;
+
+  for (int i=0;i<gsNLutInCell;i++)
+    if (GetLutCompactPixel(fMaxCell,i) > sizetemp)
+      {
+        maxlut=i;
+        sizetemp = GetLutCompactPixel(fMaxCell,i);
+      }
+
+  int startpix;
+  // 
+  // seek a starting pixel for the iteration inside the lut
+  //
+  int check=1;
+  for (int pixlut=0;pixlut<gsNPixInLut;pixlut++)
+    {
+      int pixcell =gsPixelsInLut[maxlut][pixlut]-1;
+      startpix = gsPixelsInCell[pixcell][fMaxCell]-1;
+      //*fLog << "pix, compact:" << startpix << "@"<<fCompactPixel[startpix];
+      if (fCompactPixel[startpix]) // a starting pixel was found
+		break;
+      check++;
+    }
+
+  //*fLog << "check = " << check << endl;
+  // A LUT contains 12 pixels
+  if (check > gsNPixInLut)
+	  {   
+		   *fLog <<"Warning: a starting pixel was not found! - PseudoSize = "<< fPseudoSize << endl;
+	    fPseudoSize=-1;
+	    return;
+	  }
+
+  //
+  // Bulding cluster
+  //
+  Int_t cluster[gsNTrigPixels];
+  int pnt=0;
+  int pnt2=0; //pointer in the array fCluster_pix, needed for filling
+
+  memset (cluster,0,gsNTrigPixels*sizeof(Int_t));
+  memset (fCluster_pix,-1,gsNTrigPixels*sizeof(Int_t));
+
+  cluster[startpix]=1;  
+  fCluster_pix[0]=startpix; //the starting pix is the first in cluster
+  
+  // Look at neighbour pixs if they are compact (iterative search)
+  //  until the array (fCluster_pix) has no more compact pixels.
+  // pnt points to the pixel in the array fCluster_pix whose neighbors are
+  // under study; pnt2 points to the last element of this array.
+  //
+  while (fCluster_pix[pnt] != -1)
+    { 
+      const MGeomPix &pix=(*fGeomCam)[fCluster_pix[pnt]];
+
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+	    {
+	       int pix_neigh = pix.GetNeighbor(i);
+	       // check if pixel is fired and doesn't belong to cluster
+	       if (fCompactPixel[pix_neigh] && !cluster[pix_neigh])
+	         {
+	            cluster[pix_neigh] = 1;
+	            fCluster_pix[++pnt2] = pix_neigh;
+	         }
+	    }
+      pnt++;
+    }
+
+  fPseudoSize = pnt;
+
+  //if (fPseudoSize < 4)
+    //    *fLog << "fPseudoSize = " << fPseudoSize << endl;
+
+  //  *fLog << "ClusterID:" <<(*clust).GetClusterId() << " Mult:" << (*clust).GetMultiplicity()<<endl;  
+  /*
+  *fLog <<"PSize: "<< fPseudoSize << " in cell:" << fMaxCell << " lut:" <<maxlut << endl << "   Pixels: ";
+  for (int i =0;i<fPseudoSize; i++)
+    *fLog << fCluster_pix[i]+1 <<"; ";
+  *fLog << endl;
+  */
+  return;
+}
+
+// --------------------------------------------------------------------------
+//  
+//  Fill the fCompactPixels array with the pixels which are compact
+//
+//  neighpix is the number of Next-Neighbors which defines the compact pixel
+//    topology (it can be 2-NN or 3-NN)
+//
+//   Note: it is a *global* method; it looks in the all camera as a whole
+//         
+//
+void MMcTriggerLvl2::CalcCompactPixels(MGeomCam *geom)
+{
+  memset (fCompactPixel,0,gsNTrigPixels*sizeof(Int_t));
+  //  *fLog << endl << "NEW Event!";
+  for(Int_t pixid=0; pixid<gsNTrigPixels; pixid++)
+    {
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+	     continue;
+      
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Reshuffle pixneighbour order, to arrange them (anti)clockwise
+      //   around the current pixel (Bubble sorting)
+      // The NeighPixOrdered array has a doubledd size so that
+      // the content in the first index is repeated in the last one
+      // to have a closed loop
+
+      Int_t NeighPixOrdered[2*pix.GetNumNeighbors()];
+
+      for (Int_t j=0; j<pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = pix.GetNeighbor(j);
+      
+      for (Int_t j=0; j<pix.GetNumNeighbors()-1; j++)
+        {
+          for (Int_t jk=pix.GetNumNeighbors()-1;jk>j;--jk)
+            {
+               UInt_t tmp = NeighPixOrdered[j+1];
+               const MGeomPix &pixneigh = (*geom)[NeighPixOrdered[j]];
+               for (int k=0; k<pix.GetNumNeighbors(); k++)
+                 if (NeighPixOrdered[jk] == pixneigh.GetNeighbor(k))
+     		       {
+                      NeighPixOrdered[j+1] = NeighPixOrdered[jk];
+                      NeighPixOrdered[jk] = tmp;
+              	   }
+	        }
+        }
+      
+      // Duplicate second half to take into account configurations
+ 	  //  containing tha last and first pixel
+      for (Int_t j=pix.GetNumNeighbors(); j<2*pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = NeighPixOrdered[j-pix.GetNumNeighbors()];
+
+      // Look for compact pixels. 
+      // A compact pixel must have at least fCompactNN adjacent fired neighbors
+      // It checks the 6 different configurations of neighbors pixels; if
+	  // one has fCompacNN adjacent fired pixels than the pixel pixid is
+	  // promoted to compact pixel and saved into the fCompactPixel array.
+	  //
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+	    { 
+	      int j=0; // j counts the adjacent fired pixels
+	      //*fLog << pixid <<"->"<< pix.GetNeighbor(i+j) << endl;
+	      while ((i+j < 2*pix.GetNumNeighbors()) && (fFiredPixel[NeighPixOrdered[i+j]]==1) && (j < fCompactNN))
+	        j++;  
+	      if (j>=fCompactNN)	 // configuration satisfies the compact condition  
+		{
+	      	  fCompactPixel[pixid]=1; // pixel is compact
+	      	  //	  *fLog << ","<<pixid;
+		  break;
+		}
+	    }      
+    }
+
+}
+
+// --------------------------------------------------------------------------
+//  
+//  The Energy has to be given by this class to the Energy-PSSize correlation 
+//   histogram (MHMcTriggerLvl2)  
+//
+void MMcTriggerLvl2::GetEnergy(MMcEvt *fMcEvt)
+{
+   const MMcEvt &h = *(MMcEvt *)fMcEvt; 
+   fEnergy = h.GetEnergy();
+   return;
+}
+
+
+// --------------------------------------------------------------------------
+//  
+//   Looks for a x-NN compact pattern in the whole camera
+//   We have x-NN compact pattern when a triggered pix has
+//   x-1 triggered neighbor pixels.  
+//   The variable fTriggerPattern = x is computed
+//   (x= 2,3,4,5,6,7)  
+//
+//   x=2   * *
+//
+//   x=3   * *
+//          *        *
+//            x=4   * *
+//                   *       
+//                       * *
+//                 x=5  * * *
+//          * 
+//   x=6   * * *
+//          * *
+//               * *
+//          x=7 * * *
+//               * *
+//
+void MMcTriggerLvl2::CalcTriggerPattern(MGeomCam *geom)
+{
+  fTriggerPattern=0; //initialize
+
+  for(Int_t pixid=0;pixid<gsNTrigPixels;pixid++)
+    {
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+		continue;
+      
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Look for x-NN compact pattern
+      // If a x-NN pattern exists then a pixel must have 
+      // at least x-1 adjacent neighbors (look at patterns)
+      // For each triggered pixel the number of adjacent triggered pixels 
+      // is counted.
+      //
+      int j=1;
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+		if (fFiredPixel[pix.GetNeighbor(i)]==1) j++;
+	     
+      if (j > fTriggerPattern) 
+		fTriggerPattern=j;	 
+
+      if (fTriggerPattern==7) 
+	  	break;	 // the 7-NN (max) pattern was found: exit  
+
+    } // next pixel
+}
+
+
+// --------------------------------------------------------------------------
+//  Look for the cell with higher number of Compact pixels
+//  Return the cell number (starting from 0)
+//
+Int_t MMcTriggerLvl2::CalcBiggerCellPseudoSize()
+{
+  Int_t fMaxCell=-1;
+
+  fCellPseudoSize=0;
+
+  for (Int_t i=0;i<gsNCells;i++)
+    {
+      int size = GetCellCompactPixel(i,fGeomCam);
+      if (size > fCellPseudoSize)
+        {
+          fCellPseudoSize = size;
+          fMaxCell = i;
+        }
+    }
+  
+  //*fLog << "fCellPseudoSize = " << fCellPseudoSize << " in cell N. " << fMaxCell+1 << endl;
+
+  return fMaxCell;
+}
+
+// --------------------------------------------------------------------------
+//  Compute the number of compact pixels in one cell
+//
+Int_t MMcTriggerLvl2::GetCellCompactPixel(int cell, MGeomCam *geom)
+{
+  int size=0;
+
+  // check on input variables
+
+  if (cell<0 || cell>gsNCells-1)
+    return(-2);
+
+  //*fLog << " CNN:" << fCompactNN;
+  //*fLog << "Cell: " << cell+1 << " Compat Pixels:"; 
+
+  for(Int_t id=0; id<gsNPixInCell; id++)
+    {
+      UInt_t pixid = gsPixelsInCell[id][cell]-1;
+ 
+      // Look if the pixel is fired, otherwise continue
+      if (!fFiredPixel[pixid])
+        continue;
+
+      //*fLog << "Fired pix:"<<pixid+1 << " ";
+
+      const MGeomPix &pix=(*geom)[pixid];
+      
+      // Reshuffle pixneighbour order, to arrange them (anti)clockwise 
+      //   around the current pixel (Bubble sorting)
+      // The NeighPixOrdered has one index more so that 
+      // the content in the first index is repeated in the last one
+      // to have a closed loop
+      Int_t NeighPixOrdered[2*pix.GetNumNeighbors()];
+      for (Int_t j=0; j<pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = pix.GetNeighbor(j);
+      
+      for (Int_t j=0; j<pix.GetNumNeighbors()-1; j++)
+        {
+          for (Int_t jk=pix.GetNumNeighbors()-1;jk>j;--jk)
+            {
+              UInt_t tmp = NeighPixOrdered[j+1];                  
+              const MGeomPix &pixneigh = (*geom)[NeighPixOrdered[j]];
+              for (int k=0; k<pix.GetNumNeighbors(); k++)
+                if (NeighPixOrdered[jk] == pixneigh.GetNeighbor(k))
+                  {
+                    NeighPixOrdered[j+1] = NeighPixOrdered[jk];
+                    NeighPixOrdered[jk] = tmp;
+                  }
+            }
+        }
+
+      // Duplicate second half of the array to take into account configurations
+      // containing tha last and first pixel
+      for (Int_t j=pix.GetNumNeighbors(); j<2*pix.GetNumNeighbors(); j++)
+        NeighPixOrdered[j] = NeighPixOrdered[j-pix.GetNumNeighbors()];
+
+      // Look for compact pixels. 
+
+      // A compact pixel must have at least fCompactNN adjacent neighbors
+      // It checks the 6 different configurations of neighbors pixels.
+      // The neighbour pixels must belong to the cell
+
+      //      *fLog << "cell:"<< cell << "   ordered pixels:";
+      /*
+      for (int i=0;i<2*pix.GetNumNeighbors();i++)
+	{
+	  if (fFiredPixel[NeighPixOrdered[i]])
+	    *fLog << NeighPixOrdered[i]+1 << "*;";
+	  else
+	    *fLog << NeighPixOrdered[i]+1 << ";";
+	}
+      */
+      //*fLog <<endl;
+      //*fLog << pixid <<"->"<< pix.GetNumNeighbors() << " CNN="<< fCompactNN <<endl;
+
+
+      for (int i=0;i<pix.GetNumNeighbors();i++)
+        { 
+          int j=0;
+          while ((i+j < 2*pix.GetNumNeighbors()) && (fFiredPixel[NeighPixOrdered[i+j]]==1) && (j < fCompactNN) && IsPixelInCell(NeighPixOrdered[i+j],cell) )
+            j++;  
+
+          if (j>=fCompactNN) //configuration satisfies the compact condition  
+	    {          
+	      size++; // pixel is compact
+	      //*fLog << "->" << pixid+1;
+	      break; // (new pixel)
+	    }
+	}
+    }
+  
+  //*fLog <<" - size:" << size << endl<<endl;
+  
+  return size;
+  
+}
+
+//---------------------------------------------------------------------
+//  Check if a given pixel belongs to a given cell
+//
+Bool_t MMcTriggerLvl2::IsPixelInCell(Int_t pixel, Int_t cell)
+{
+  for (int i=0; i<gsNPixInCell; i++)
+    if ((gsPixelsInCell[i][cell]-1) == pixel)
+      return kTRUE;
+  
+  return kFALSE;
+}
+
+//---------------------------------------------------------------------
+//  Check if a given pixel is in the trigger region
+//
+Bool_t MMcTriggerLvl2::IsPixelInTrigger(Int_t pixel) const
+{
+  for (int cell=0; cell<gsNCells; cell++)
+    for (int i=0; i<gsNPixInCell; i++)
+      if ((gsPixelsInCell[i][cell]-1) == pixel)
+	return kTRUE;
+  
+  return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns, depending on the type flag:
+//
+//  0: 1,0 if the pixel is triggered (1) or not (0)
+// 
+//
+Bool_t MMcTriggerLvl2::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  // Pixel in no-trigger region are set to 0
+  val = this->IsPixelInTrigger(idx) ?  fFiredPixel[idx]+fCompactPixel[idx] : 0;
+
+  return kTRUE;
+}
+
+void MMcTriggerLvl2::DrawPixelContent(Int_t num) const
+{
+    *fLog << "MMcTriggerLvl2::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MMcTriggerLvl2.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MMcTriggerLvl2.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MMcTriggerLvl2.h	(revision 9772)
@@ -0,0 +1,108 @@
+#ifndef MARS_MMcTriggerLvl2
+#define MARS_MMcTriggerLvl2
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MMcTrig;
+class MMcEvt;
+class MGeomCamMagic;
+class MGeomCam;
+class MGeomPix;
+
+class MMcTriggerLvl2 : public MParContainer, public MCamEvent
+{
+ private:
+  
+  // Global trigger variables related to the geometry and trigger structures are here defined.  
+  // FIXME!  this is a temporary solution: these variables should be defined in a GeomTrg class    
+
+  static const Int_t fNumPixCell = 36; // Number of pixels in one cell
+
+  static const Int_t gsNCells = 19;   
+  static const Int_t gsNTrigPixels = 397;   
+  static const Int_t gsNPixInCell = 36;  
+  static const Int_t gsNLutInCell = 3;  
+  static const Int_t gsNPixInLut = 12; 
+  Int_t fPixels[gsNPixInCell][gsNCells];  
+  static const Int_t gsPixelsInCell[gsNPixInCell][gsNCells];   
+  static const Int_t gsPixelsInLut[gsNLutInCell][gsNPixInLut];
+  // Array with flag for triggered pixels. 1st idx:pixels in trigger cell; 2nd idx:trigger cell number      
+
+  Int_t fFiredPixel[gsNTrigPixels]; // Array with flag for triggered pixel. idx: pixel id    
+  
+  Int_t fMaxCell;  // Cell with maximum number of fired pixels
+
+  Int_t fLutPseudoSize;   // number of compact pixels in one lut   
+  Int_t fPseudoSize;   // Multiplicity of the cluster identified by the L2T    
+  Int_t fSizeBiggerCell; // Number of fired pixel in bigger cell    
+  Int_t fCompactNN;    //Number of NN pixels that define a compact pixel    
+  Int_t fCompactPixel[gsNTrigPixels]; //Array with flag for compact pixels    
+  Int_t fCluster_pix[gsNTrigPixels]; //Array with pixel in cluster   
+  Double_t fEnergy;  // Energy of the shower    
+  Int_t fTriggerPattern; // x-NN compact trigger pattern;    
+  Int_t fCellPseudoSize; // number of compact pixels in one cell    
+  //  Int_t fCellCompactPixels[fNumPixCell]; // Array with compact pixels in cell
+
+  MMcTrig *fMcTrig;   
+  MGeomCam *fGeomCam;      
+
+     
+  Int_t CalcBiggerFiredCell();   
+  Int_t CalcBiggerLutPseudoSize();   
+  void CalcPseudoSize();   
+  Int_t CalcCellPseudoSize();   
+  Int_t CalcBiggerCellPseudoSize();    
+  Int_t GetCellCompactPixel(int cell, MGeomCam *fCam);
+
+  void SetNewCamera(MGeomCam *geom) {fGeomCam = geom;}   
+
+ public:     
+ 
+  MMcTriggerLvl2(const char* name = NULL, const char* title = NULL);   
+  ~MMcTriggerLvl2();      
+
+  virtual void Calc();    
+  virtual void Print(Option_t *opt="") const;    
+
+  void SetLv1(MMcTrig *trig = NULL);    
+  void SetPixelFired(Int_t pixel, Int_t fired=1);     
+  void SetCompactNN(Int_t neighpix)     {fCompactNN=neighpix;}    
+
+  Int_t GetPseudoSize() const     {return fPseudoSize;}   
+  Int_t GetLutPseudoSize() const  {return fLutPseudoSize;}   
+  Int_t GetSizeBiggerCell() const {return fSizeBiggerCell;}   
+  Int_t GetCompactNN() const      {return fCompactNN;}   
+  Int_t GetCellPseudoSize() const {return fCellPseudoSize;}
+  Int_t GetMaxCell() const        {return (fMaxCell+1);} // Returns
+                     // cell with maximum number of compact pixels
+  Int_t GetCellNumberFired(int cell);   
+  Int_t GetLutCompactPixel(int cell, int lut); 
+  void CalcCompactPixels(MGeomCam *fCam);
+  void CalcTriggerPattern(MGeomCam *fCam);
+
+  const Int_t* GetPixelsInCell() const { return &(**gsPixelsInCell);}
+  const Int_t* GetPixelsInLut() const { return &(**gsPixelsInLut);}
+
+  Int_t GetTriggerPattern() const {return fTriggerPattern;}    
+
+  void GetEnergy(MMcEvt *fMcEvt = NULL);     
+  Double_t GetEnergy() const    {return fEnergy;}      
+
+  Bool_t IsPixelInCell(Int_t pixel, Int_t cell);    
+  Bool_t IsPixelInTrigger(Int_t pixel) const;    
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t num) const;
+
+
+  ClassDef(MMcTriggerLvl2,0) // Container for 2nd Level Trigger selection parameters 
+    };  
+    
+#endif      
+    
Index: /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerButton.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerButton.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerButton.cc	(revision 9772)
@@ -0,0 +1,123 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante 09/2004 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MagicTrigger
+// ------------
+//
+// Camera Display Games: Reversi
+//
+// Start the game by:
+//   MagicReversi reversi;
+//
+//  Rules:
+//  ------
+//
+// Use the mouse to put a stone at some place. If between your newly
+// placed stone and the next stone (in a row) of your color are stones
+// of other colors this stones are won by you. You can only place a
+// stone if you win at least one stone from your 'enemy'. If you
+// cannot do so, you are skipped. If nobody can make a move anymore
+// the game is over. The player has won who has the most stones in
+// his own color.
+// The present player is indicated by <*>
+// Use the Escape key to abort a game.
+// If the game was aborted or has been stopped youcan access the
+// options in the context menu.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MagicTriggerButton.h"
+
+#include <iostream>
+
+#include <KeySymbols.h>
+
+#include <TText.h>
+#include <TMarker.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+#include <TClonesArray.h>
+#include <TInterpreter.h>
+#include <TRootEmbeddedCanvas.h>
+#include <TGButton.h>
+#include <TGTextEntry.h>
+#include <TGTextBuffer.h>
+#include <TGClient.h>
+#include <TQObject.h>
+//#include <RQ_OBJECT.h>
+
+#include "MHexagon.h"
+#include "MagicTriggerDisplay.h"
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MagicTriggerButton);
+
+using namespace std;
+
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicTriggerButton::MagicTriggerButton(const TGWindow *p, const char* text, Int_t id, 
+				       GContext_t norm, FontStruct_t font, 
+				       UInt_t option): TGTextButton(p,text)
+{
+    // Create a main frame
+    //fButton = new TGTextButton(p,text);
+
+    this->Connect("Clicked()","MagicTriggerButton",this,"Signal(Int_t,Int_t)");
+    //this->Connect("Clicked()","MagicTriggerDisplay",gROOT->FindObject("MagicTriggerDisplay"),"Update()");
+
+ }
+
+
+void MagicTriggerButton::SetValue(const Int_t cell, const Int_t lut)
+{
+    fValue[0] = (Long_t)cell;
+    fValue[1] = (Long_t)lut;
+}
+
+void MagicTriggerButton::Clicked()
+{
+    //TQObject::Disconnect(this,"Signal(Int_t,Int_t)",gROOT->FindObject("MagicTriggerDisplay"),"Update(Int_t,Int_t)");
+    //this->Connect("Signal(Int_t,Int_t)","MagicTriggerDisplay",gROOT->FindObject("MagicTriggerDisplay"),"Update(Int_t,Int_t)");
+    Emit("Clicked()");
+}
+
+void MagicTriggerButton::Signal(Int_t cell, Int_t lut)
+{
+    //this->SetValue(cell,lut);
+    Emit("Signal(Int_t, Int_t)",fValue);
+    //cout << fValue[0] << " ---- " << fValue[1] << endl;
+}
+
+//Bool_t MagicTriggerButton::Connect(const char *signal, const char *receiver_class,
+//				  void *receiver, const char *slot)
+//{
+//   return TQObject::Connect(this,signal, receiver_class, receiver, slot);
+//}
Index: /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerButton.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerButton.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerButton.h	(revision 9772)
@@ -0,0 +1,52 @@
+#ifndef MARS_MagicTriggerButton
+#define MARS_MagicTriggerButton
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TGButton
+#include <TGButton.h>
+#endif
+#ifndef ROOT_RQ_OBJECT
+//#include <RQ_OBJECT.h>
+#endif
+
+class TText;
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class TGMainFrame;
+class TRootEmbeddedCanvas;
+class TGWindow;
+class TGTextEntry;
+class TGTextButton;
+
+class MagicTriggerButton : public TGTextButton
+{
+private:
+    TGTextButton *fButton;
+    Long_t fValue[2];
+
+public:
+
+    MagicTriggerButton(const TGWindow *p, const char *text = "Button", Int_t id = -1, 
+		       GContext_t norm = GetDefaultGC()(), 
+		       FontStruct_t font = GetDefaultFontStruct(), 
+		       UInt_t option = kRaisedFrame|kDoubleBorder);
+
+    void SetValue(const Int_t cell = 0, const Int_t lut = 0);
+    void Signal(Int_t cell, Int_t lut); // *SIGNAL*
+    void Clicked(); // *SIGNAL*
+//    Bool_t Connect(const char *signal, const char *receiver_class,
+//		   void *receiver, const char *slot);
+
+    ClassDef(MagicTriggerButton, 0) // Magic Camera Games: Reversi
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerDisplay.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerDisplay.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerDisplay.cc	(revision 9772)
@@ -0,0 +1,403 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante 09/2004 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MagicTrigger
+// ------------
+//
+// Camera Display Games: Reversi
+//
+// Start the game by:
+//   MagicReversi reversi;
+//
+//  Rules:
+//  ------
+//
+// Use the mouse to put a stone at some place. If between your newly
+// placed stone and the next stone (in a row) of your color are stones
+// of other colors this stones are won by you. You can only place a
+// stone if you win at least one stone from your 'enemy'. If you
+// cannot do so, you are skipped. If nobody can make a move anymore
+// the game is over. The player has won who has the most stones in
+// his own color.
+// The present player is indicated by <*>
+// Use the Escape key to abort a game.
+// If the game was aborted or has been stopped youcan access the
+// options in the context menu.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MagicTriggerDisplay.h"
+
+#include <iostream>
+
+#include <KeySymbols.h>
+
+#include <TText.h>
+#include <TMarker.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+#include <TClonesArray.h>
+#include <TInterpreter.h>
+#include <TRootEmbeddedCanvas.h>
+#include <TGButton.h>
+#include <TGTextEntry.h>
+#include <TGTextBuffer.h>
+#include <TGClient.h>
+#include <RQ_OBJECT.h>
+
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+#include "MagicTriggerButton.h"
+#include "MMcTriggerLvl2.h"
+
+ClassImp(MagicTriggerDisplay);
+
+using namespace std;
+
+
+void MagicTriggerDisplay::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    fPixels->Delete();
+    fText->Delete();
+    fFlags->Delete();
+
+    delete fText;
+    delete fFlags;
+    delete fPixels;
+
+    delete fGeomCam;
+}
+
+void MagicTriggerDisplay::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Reset the display geometry
+    //
+    fW=0;
+    fH=0;
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    //
+    // Construct all hexagons. Use new-operator with placement
+    //
+    fPixels = new TClonesArray("MHexagon", fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = *new ((*fPixels)[i]) MHexagon((*fGeomCam)[i]);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        h.SetBit(kNoContextMenu|kCannotPick);
+#endif
+
+	//const MGeomPix &pix = (*fGeomCam)[i];
+
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Draw all pixels of the camera
+//  (means apend all pixelobjects to the current pad)
+//
+void MagicTriggerDisplay::DrawHexagons()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+        (*this)[i].Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicTriggerDisplay::MagicTriggerDisplay(const TGWindow *p, UInt_t w, UInt_t h)
+    : fGeomCam(NULL), fW(0), fH(0)
+{
+    // Create a main frame
+    fMain = new TGMainFrame(p,w,h);
+
+    // Create a canvas widjet
+    fEcanvas = new TRootEmbeddedCanvas("Ecanvas",fMain,w,h);
+    fMain->AddFrame(fEcanvas, new TGLayoutHints(kLHintsExpandX |
+						kLHintsExpandY, 10, 10, 10, 1));
+    fMain->SetWindowName("MAGIC trigger display");
+    
+    // Create horizontal frame widjets
+    TGHorizontalFrame *hFrame = new TGHorizontalFrame(fMain, 200, 40);
+
+    //this->Connect("SetValue(Int_t,Int_t","MagicTriggerDisplay",this,"Update(Int_t,Int_t)");
+
+    // Macrocells stuff
+    cellBackward = new MagicTriggerButton(hFrame,"<<");
+    cellBackward->SetValue(-1,0);
+    //cellBackward->Connect("Signal(Int_t,Int_t)","MagicTriggerDisplay",this,"Update(Int_t,Int_t)");
+    cellBackward->Connect("Signal(Int_t,Int_t)","MagicTriggerDisplay",this,"Update(Int_t,Int_t)");
+    //TQObject::Connect(cellBackward,"Clicked()","MagicTriggerDisplay",this,"Update()");
+    hFrame->AddFrame(cellBackward, new TGLayoutHints(kLHintsCenterX,5,3,3,4));
+
+    fCellEntry = new TGTextEntry(hFrame, new TGTextBuffer());
+    fCellEntry->Resize(30,fCellEntry->GetDefaultHeight());
+    hFrame->AddFrame(fCellEntry, new TGLayoutHints(kLHintsCenterX,3,3,3,4));
+
+    MagicTriggerButton *cellForward = new MagicTriggerButton(hFrame,">>");
+    cellForward->SetValue(1,0);
+    cellForward->Connect("Signal(Int_t,Int_t)","MagicTriggerDisplay",this,"Update(Int_t,Int_t)");
+    hFrame->AddFrame(cellForward, new TGLayoutHints(kLHintsCenterX,3,5,3,4));
+
+    // Draw button
+    MagicTriggerButton *draw = new MagicTriggerButton(hFrame,"&Draw");
+    draw->SetValue(-10,-10);
+    draw->Connect("Signal(Int_t,Int_t)","MagicTriggerDisplay",this,"Update(Int_t,Int_t)");
+    hFrame->AddFrame(draw, new TGLayoutHints(kLHintsCenterX,5,5,3,4));
+
+    // LUT stuff
+    MagicTriggerButton *LUTBackward = new MagicTriggerButton(hFrame,"<<");
+    LUTBackward->SetValue(0,-1);
+    LUTBackward->Connect("Signal(Int_t,Int_t)","MagicTriggerDisplay",this,"Update(Int_t,Int_t)");
+    hFrame->AddFrame(LUTBackward, new TGLayoutHints(kLHintsCenterX,5,3,3,4));
+
+    fLUTEntry = new TGTextEntry(hFrame, new TGTextBuffer());
+    fLUTEntry->Resize(30,fCellEntry->GetDefaultHeight());
+    hFrame->AddFrame(fLUTEntry, new TGLayoutHints(kLHintsCenterX,3,3,3,4));
+
+    MagicTriggerButton *LUTForward = new MagicTriggerButton(hFrame,">>");
+    LUTForward->SetValue(0,1);
+    LUTForward->Connect("Signal(Int_t,Int_t)","MagicTriggerDisplay",this,"Update(Int_t,Int_t)");
+    hFrame->AddFrame(LUTForward, new TGLayoutHints(kLHintsCenterX,3,5,3,4));
+
+    // Exit stuff
+    TGHorizontalFrame *hExitFrame = new TGHorizontalFrame(fMain, 200, 40);
+    TGTextButton *exit = new TGTextButton(hExitFrame,"&Exit",
+					  "gApplication->Terminate(0)");
+
+    hExitFrame->AddFrame(exit, new TGLayoutHints(kLHintsCenterX,5,5,10,4));
+
+    fMain->AddFrame(hFrame, new TGLayoutHints(kLHintsCenterX,2,2,2,2));
+    fMain->AddFrame(hExitFrame, new TGLayoutHints(kLHintsCenterX,2,2,2,2));
+
+    fMain->MapSubwindows();
+    fMain->Resize(fMain->GetDefaultSize());
+    fMain->MapWindow();
+
+    SetNewCamera(new MGeomCamMagic);
+
+    fTrig = new MMcTriggerLvl2();
+    fPixelsInLUT = fTrig->GetPixelsInLut();
+    fPixelsInCell = fTrig->GetPixelsInCell();
+
+    cn = ln = 1;
+    //
+    // Make sure, that the object is destroyed when the canvas/pad is
+    // destroyed. Make also sure, that the interpreter doesn't try to
+    // delete it a second time.
+    //
+    SetBit(kCanDelete);
+    gInterpreter->DeleteGlobal(this);
+
+    Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+// ------------------------------------------------------------------------
+//
+// This is called at any time the canvas should get repainted.
+// Here we maintain an aspect ratio of 5/4=1.15. This makes sure,
+// that the camera image doesn't get distorted by resizing the canvas.
+//
+void MagicTriggerDisplay::Update(const Int_t cell, const Int_t lut)
+{
+    Int_t pixid;
+    char text[10];
+
+    switch(cell){
+	case -10:
+	    cn = atoi(fCellEntry->GetText());
+	    ln = atoi(fLUTEntry->GetText());
+	    cout << "cn"<<cn<<" ln="<<ln<<endl;
+	    break;
+	case 0:
+	    if(lut==1) ln = atoi(fLUTEntry->GetText())+1;
+	    else if(lut==-1) ln = atoi(fLUTEntry->GetText()) - 1;
+	    else cout << "MagicTriggerDisplay::Update  ERROR: BAD lut number sent by signal" << endl;
+	    break;
+	case 1:
+	    if(lut==0) cn = atoi(fCellEntry->GetText()) + 1;
+	    else cout << "MagicTriggerDisplay::Update  ERROR: BAD lut number sent by signal" << endl;
+	    break;
+	case -1:
+	    if(lut==0) cn = atoi(fCellEntry->GetText()) - 1;
+	    else cout << "MagicTriggerDisplay::Update  ERROR: BAD lut number sent by signal" << endl;
+	    break;
+	default:
+	    cout << "Invalid cell number sent by the signal";
+	    break;
+    }
+
+    if((cn>=kMinCell) && (cn<=kMaxCell) && (ln>=kMinLUT) && (ln<=kMaxLUT)){
+	sprintf(text,"%i",ln);
+	fLUTEntry->SetText(text);
+	sprintf(text,"%i",cn);
+	fCellEntry->SetText(text);
+	for(UInt_t i=0; i<fNumPixels; i++)
+	    (*this)[i].SetFillColor(22);
+	for(Int_t i=0; i<12; i++){
+	    //cout << "cacca" << endl;
+	    //cout << fPixelsInLUT[(ln-1)*kMaxLUT+i]-1 << endl;
+	    //cout << "--" << endl;
+	    pixid = fPixelsInCell[(fPixelsInLUT[(ln-1)*12+i]-1)*kMaxCell+(cn-1)]-1;
+	    //cout << "molla" << endl;
+	    cout << "pixid=" << pixid << endl;
+	    (*this)[pixid].SetFillColor(28);
+	    //cout << "profumata" << endl;
+	}
+	DrawHexagons();
+	fDrawingPad->Modified();
+	fDrawingPad->Update();
+    }
+    else{
+	cn = atoi(fCellEntry->GetText());
+	ln = atoi(fLUTEntry->GetText());
+	cout << "Che cazzo fai PIRLA!" << endl;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to draw the camera layout into your canvas.
+// Setup a drawing canvas. Add this object and all child objects
+// (hexagons, etc) to the current pad. If no pad exists a new one is
+// created.
+//
+void MagicTriggerDisplay::Draw(Option_t *opt)
+{
+    // root 3.02:
+    // gPad->SetFixedAspectRatio()
+
+    //fDrawingPad = fEcanvas->GetCanvas();
+    //if (fDrawingPad)
+    //    return;
+
+    //
+    // if no canvas is yet existing to draw into, create a new one
+    //
+    //if (!gPad)
+    //{
+    //    /*TCanvas *c =*/ new TCanvas("MagicReversi", "Magic Reversi", 0, 0, 800, 800);
+        //c->ToggleEventStatus();
+    //    fIsAllocated = kTRUE;
+    //}
+    //else
+    //fIsAllocated = kTRUE;
+
+    fDrawingPad = gPad;
+    fDrawingPad->SetBorderMode(0);
+    fDrawingPad->SetFillColor(22);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(opt);
+
+    //
+    // Draw the title text
+    //
+    //for (int i=0; i<6; i++)
+    //{
+    //    fUsrTxt[i] = new TText;
+    //    fUsrTxt[i]->SetTextAlign(13);       // left/bottom
+    //    fUsrTxt[i]->SetTextSize(0.03);
+    //    fUsrTxt[i]->SetTextColor(kRed+i);  
+//#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    //    fUsrTxt[i]->SetBit(kNoContextMenu|kCannotPick);
+//#endif
+    //    fUsrTxt[i]->Draw();
+    //}
+
+    //
+    // Reset the game pad
+    //
+    //Reset();
+    DrawHexagons();
+}
+
+void MagicTriggerDisplay::Paint(Option_t *opt)
+{
+    const UInt_t w = (UInt_t)(gPad->GetWw()*gPad->GetAbsWNDC());
+    const UInt_t h = (UInt_t)(gPad->GetWh()*gPad->GetAbsHNDC());
+
+    //
+    // Check for a change in width or height, and make sure, that the
+    // first call also sets the range
+    //
+    if (w*fH == h*fW && fW && fH)
+        return;
+
+    //
+    // Calculate aspect ratio (5/4=1.25 recommended)
+    //
+    const Double_t ratio = (Double_t)w/h;
+
+    Float_t x;
+    Float_t y;
+
+    if (ratio>1.0)
+    {
+        x = fRange*(ratio*2-1);
+        y = fRange;
+    }
+    else
+    {
+        x = fRange;
+        y = fRange/ratio;
+    }
+
+    fH = h;
+    fW = w;
+   //
+    // Set new range
+    //
+    fDrawingPad->Range(-fRange, -y, x, y);
+}
Index: /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerDisplay.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerDisplay.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mpisa/triggerdisplay/MagicTriggerDisplay.h	(revision 9772)
@@ -0,0 +1,96 @@
+#ifndef MARS_MagicTriggerDisplay
+#define MARS_MagicTriggerDisplay
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_RQ_OBJECT
+#include <RQ_OBJECT.h>
+#endif
+
+class TText;
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class TGMainFrame;
+class TRootEmbeddedCanvas;
+class TGWindow;
+class TGTextEntry;
+class MagicTriggerButton;
+class MMcTriggerLvl2;
+
+class MagicTriggerDisplay : public TObject
+{
+private:
+    static const Int_t kMinCell = 1;
+    static const Int_t kMaxCell = 19;
+    static const Int_t kMinLUT = 1;
+    static const Int_t kMaxLUT = 3;
+
+    Int_t cn;
+    Int_t ln;
+
+    TGMainFrame          *fMain;
+    TRootEmbeddedCanvas  *fEcanvas;
+    TGTextEntry          *fCellEntry;
+    TGTextEntry          *fLUTEntry;
+    MagicTriggerButton   *cellBackward;
+    MMcTriggerLvl2       *fTrig;
+    const Int_t *fPixelsInLUT;
+    const Int_t *fPixelsInCell;
+
+    MGeomCam      *fGeomCam;       // pointer to camera geometry
+
+    UInt_t         fNumPixels;     // number of pixels in the present geometry
+    Float_t        fRange;         // the range in millimeters of the present geometry
+
+    TClonesArray  *fPixels;        // array of all hexagons
+    TClonesArray  *fText;          // array of all texts
+    TClonesArray  *fFlags;         // array of all texts
+
+    TText         *fDone;          // TText showing the 'Game over'
+    TText         *fUsrTxt[6];     // TText showing the numbers of pixels and bombs
+
+    UInt_t         fW;             // Width of canvas
+    UInt_t         fH;             // Height of canvas
+    TVirtualPad   *fDrawingPad;    // pad in which we are drawing
+    Bool_t         fIsAllocated;
+
+    Int_t          fNumUsers;
+    Int_t          fNumUser;
+    Int_t          fUsrPts[6];
+
+    enum
+    {
+        kEmpty     = 50,
+        kIsVisible = BIT(16),
+        kHasBomb   = BIT(17),
+        kHasFlag   = BIT(18),
+        kUserBits  = 0x7fc000 // 14-23 are allowed
+    };
+
+    MHexagon &operator[](int i) { return *((MHexagon*)fPixels->At(i)); }
+
+    TText   *GetText(Int_t i) { return (TText*)fText->At(i); }
+    TMarker *GetFlag(Int_t i) { return (TMarker*)fFlags->At(i); }
+
+    void Free();
+    void SetNewCamera(MGeomCam *);
+    void DrawHexagons();
+    void Paint(Option_t *option="");
+    void Draw(Option_t *opt = "");
+public:
+    MagicTriggerDisplay(const TGWindow *p, UInt_t w = 500, UInt_t h = 500);
+
+    void  Update(const Int_t butt = 0, const Int_t entry = 0);
+
+    ClassDef(MagicTriggerDisplay, 0) // Magic Camera Games: Reversi
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mucm/Flux6.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/Flux6.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/Flux6.C	(revision 9772)
@@ -0,0 +1,104 @@
+/*############################################################################
+  #
+  #   Input: 
+  #   - A 3D hist of Alpha vs Energy vs Theta
+  #   - A 2D hist of DiffTime vs Time
+  #   - A 2D with Effective Collection Area 
+  # 
+  #  Then calculate:
+  #   - Effecive on Time
+  #   - Nex for the Alpha plot foreach bin (energy,theta)
+  #
+  #
+  #  Fixed a bug: the loop for extracing the signal started in bin=0 instead in
+  #               bin 1. 
+  # 
+  #  Fixed a bug: the above change introduced a extremely important bug, since
+  #   the loop started from 1 but we have in the arrays:
+  #         signal[i] = fNex;
+  #	    errorsignal[i] = fdNex;
+  #  so the signal[0] was actually the signal for the last bin. For that we 
+  #  had a very low point in the first bin and all the spectrum was displaced.
+  #  Now it is fixed with:
+  #           signal[i-1] = fNex;
+  #	    errorsignal[i-1] = fdNex;
+  #
+  #                                                authors: Marcos Lopez
+  #                                                         Rober Wagner
+  #                                                   email: marcos@gae.ucm.es
+  #                                                   date:  31-11-2004
+  #                                           last revision: 31-11-2004  
+  ###########################################################################*/
+
+void Flux6() 
+{
+
+    //TString datafile = "flux/Alpha10_H3.New.Resized.root";
+    //TString datafile = "flux/Alpha10_HadCut_Variable.Resized.root";
+    TString datafile = "flux/Alpha10_HadCut_Variable.SizeAbove250.Resized.root";
+    //TString datafile = "flux/Alpha_E_50_2000_10bins_HadCut_Variable.SizeAbove250.Resized.root";
+
+
+    //TString areafile = "flux/area_HadCut_03_and_AlphaCut_20.Resized.root";
+    //TString areafile = "../mcdata/collarea.root";
+    //TString areafile = "area_HadCut03_and_AlphaCut20.root";
+    //TString areafile = "area_HacCut_Variable_and_AlphaCut_20.Resized.root";
+    //TString areafile = "area_HacCut_Variable.Resized.root";
+    TString areafile = "flux/area_HadCut_Variable.SizeAbove250.Resized.root";
+
+    // ------------------------------------------------------------------------
+    // 
+    //  Load histograms from file
+    //
+    TFile* file = new TFile(datafile);
+
+    //
+    // Read Hist of Alpha Vs. Energy and Theta
+    //
+    MHAlphaEnergyTheta hAlpha;
+    hAlpha.Read("MHAlphaEnergyTheta");
+    hAlpha.DrawClone();
+
+    //
+    // Read Hist of EffectiveTime vs. Theta and Time
+    //
+    MHEffectiveOnTime hEffTime;
+    hEffTime.Read("MHEffectiveOnTime");
+    hEffTime.DrawClone();
+
+    //
+    // Read CollectionArea
+    //
+    TFile* file3 = new TFile(areafile);
+    MHMcCollectionArea area;
+    area.Read("MHMcCollectionArea");
+    area.DrawClone();
+
+
+    // ----------------------------------------------------------------------- 
+    //
+    // Calculate # Excess events vs. Energy and Theta
+    //
+    MHExcessEnergyTheta *hex = new MHExcessEnergyTheta;
+    hex->Calc(&hAlpha);
+    hex->Draw();
+
+    //
+    // Calculate diferential Flux vs. Enregy and Theta
+    //
+    MHFlux* hFlux = new MHFlux;
+    hFlux->Calc(hex, &area, &hEffTime);
+    hFlux->Draw();
+
+
+
+    
+    //
+    // Write flux into root file
+    //
+    TFile outfile("flux/Flux.root","RECREATE");
+    hFlux->Write();
+    outfile.Close();
+
+}
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MDataSetIter.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MDataSetIter.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MDataSetIter.cc	(revision 9772)
@@ -0,0 +1,950 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez, 4/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MDataSetIter
+//
+//  This class serves to divide all the data taking during a given night
+//  (i.e, all the root files of a given directory), 
+//  into different data sets of files to be analyzed together. A data set is a
+//  set of Data runs, along which their closer Ped and Cal runs.
+//
+//  Usage:
+//  ------
+//   - To specify the directory/ies where the data are use:
+//        AddDirectory()
+//
+//   - To specify only those files for a given source name (all the files with
+//     a name different from the ones in the source-name-list will be ignored)
+//     use:
+//        SelectSourceName()
+//     You can select several src names.
+//     By default, if any explict source name is specified, all are valid.
+//
+//   - To retrieve the next data set (Ped, Cal, and Data runs) use:
+//        NextDataSet()
+//        GetPefDataRuns()
+//        GetCalRuns()
+//        GetDatRuns()
+//
+// Two problems:
+//    -Sources not desired : ZetaTauri
+//    - Not P/C runs before data runs
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MDataSetIter.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRunIter.h"
+#include "MSequence.h"
+
+#include "TObjArray.h"
+
+#include <TSystem.h>
+#include <fstream>
+
+ClassImp(MDataSetIter);
+
+using namespace std;
+
+
+
+// ----------------------------------------------------------------------------
+//
+//  Default constructor.
+//
+MDataSetIter::MDataSetIter() 
+    : fInitialRun(-1), fEndRun(-1), fLastProcessedDataRun(0), fLastDataRun(0), fDefCalRun(0), fDefCalRunPath(""), fLog(&gLog)
+{
+    fPedRuns = new MRunIter;
+    fCalRuns = new MRunIter;
+    fDataRuns = new MRunIter;
+    fSequence = new MSequence;
+}
+
+
+// ---------------------------------------------------------------------------
+//
+//  Add all the files inside a given directory to the fFileList.
+//
+void MDataSetIter::AddToFileList(MDirIter& dir)
+{
+    TString name;
+   
+    while (!(name=dir.Next()).IsNull())
+     	fFileList.Add((TObject*)(new TNamed((const char*)name, "")));
+   
+
+    //
+    // Sort File List by name
+    //
+    fFileList.Sort();
+
+    //
+    // Find last Data runnumber of the filelist to be processed
+    //
+    FindLastDataRun();
+}
+
+
+// -------------------------------------------------------------------------
+//
+// Find last Data runnumber of the filelist to be processed
+//
+void MDataSetIter::FindLastDataRun()
+{
+
+    if(fFileList.GetLast()==-1)
+	return;
+
+
+    TIter next(&fFileList,kIterBackward);
+    TNamed* n;
+
+    while ( (n=(TNamed*)next()) )
+    {  
+	TString name, path, date, src;
+	Int_t run;
+	char type;
+	
+	ScanFileName(n->GetName(), name, path, date, src, &run, &type);
+
+	if(type!='D')
+	    continue;
+
+	
+	if(fEndRun==-1)
+	{
+	    if(run>fLastDataRun)
+		fLastDataRun = run;
+	    
+	    break;
+	}
+	else
+	{
+	    if(run<=fEndRun)
+	    {
+		if(run>fLastDataRun)
+		    fLastDataRun = run;
+		
+		break;
+	    }
+	    
+	}
+    }
+
+}
+
+
+// ----------------------------------------------------------------------------
+//
+//  Overload MDirIter::AddDirectory
+//
+//  Each time a new directory is added, all the files inside that directory
+//  are added to the fFileList.
+//
+//  Returns the number of directories added
+//
+Int_t MDataSetIter::AddDirectory(const char *dir, const char *filter, Int_t recursive) 
+{
+    const Int_t rc = MDirIter::AddDirectory(dir, filter, recursive);
+    if (rc==0)
+	return 0;
+  
+    //
+    // Add the files inside that directory to the fFileList. In order to 
+    // add only the files inside the new directory added, we create
+    // and MDirIter with only that directory. Otherwise, it we call 
+    // directly this.Next() inside FillFileList the new files and the 
+    // previously existing one will be again adde to the fFileList. 
+    //
+    MDirIter next(dir,filter,recursive);
+    AddToFileList(next);
+
+    next.Print() ;
+    
+    return kTRUE;
+} 
+
+
+// ----------------------------------------------------------------------------
+//
+//  Add a source name to the list of selected source names.
+//
+void MDataSetIter::SelectSourceName(const char *src)
+{
+    fSrcList.Add((TObject*)(new TNamed(src, src)));  
+}
+    
+
+// ----------------------------------------------------------------------------
+//
+//  Check wheather the source name is inside the list of selected source names.
+//  If not any source name has been selected, by default, any source name is
+//  valid.
+//  Return:
+//   kTRUE: this run has to be selected
+//   kFALSE: this run has to be skipped
+//
+Int_t MDataSetIter::CheckSourceName(TString& src)
+{
+
+    // If any source has been especified, all sorce name are accepted
+    if(fSrcList.GetLast()==-1)
+	return kTRUE;
+
+
+    //
+    // For skipping Ped and Cal runs with CL (aftet June 2004)
+    //
+    if(src.Contains("CL") || src.Contains("ContL"))
+    {
+        *fLog << warn << "Skipping CL run [" << src << "]" << endl;
+	return kFALSE;
+    }
+
+    //
+    // Skip Green and Blue calib
+    //
+    if(src.Contains("Blue",TString::kIgnoreCase) || src.Contains("Green",TString::kIgnoreCase))
+    {
+        *fLog << warn << "Skipping Blue/Green run [" << src << "]" << endl;
+        return kFALSE;
+    }
+
+
+
+    //
+    // For dealing with the new calibration files nomenclature 
+    // (after 23-3-2004) of the type "CrabNebula-5blue", and for off data
+    // like OffMrk421-1, OffMrk421-3 etc, we assume that any source name 
+    // can be made up of two parts separated by a dash: the source name and 
+    // a suffix indicated for instance the calibration colot of kind of off 
+    // data. This suffix is then ignored for checking the source name, ie., 
+    // any suffix is valid !  
+    //
+    if(src.Contains("-"))
+    {
+	//*fLog << warn << "For source [" << src << "] ignoring suffix [" 
+	//     << src( src.First("-")+1, src.Length() ) << "]" << endl;
+	src.Remove(src.First("-"));
+    }
+
+
+    //
+    // Loop 
+    //
+    TIter next(&fSrcList);
+
+    TString ValidSrc;
+    TNamed* n;
+    while ( (n=(TNamed*)next()) )
+    {
+	ValidSrc = n->GetName();
+	
+	if (src==ValidSrc)       // For dealing with new calib files as Mrk421blue5
+	//if (src.Contains(ValidSrc))
+	    return kTRUE;
+    }
+
+    *fLog << warn << "Source [" << src << "] is not in the list of selected source names." << endl;
+
+    return kFALSE;
+}
+
+// -------------------------------------------------------------------
+//	
+// Compare two source names
+//
+Int_t MDataSetIter::CompareSourceNames(TString& src1, TString& src2)
+{
+    if(src1.Contains("-"))
+    {
+        //*fLog << warn << "For source [" << src << "] ignoring suffix ["
+        //     << src( src.First("-")+1, src.Length() ) << "]" << endl;
+        src1.Remove(src1.First("-"));
+    }
+
+
+    if(src2.Contains("-"))
+    {
+        //*fLog << warn << "For source [" << src << "] ignoring suffix ["
+        //     << src( src.First("-")+1, src.Length() ) << "]" << endl;
+        src2.Remove(src2.First("-"));
+    }
+
+    return (src1.CompareTo(src2)==0) ? kTRUE : kFALSE;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Scan a file name. 
+//
+void MDataSetIter::ScanFileName(const TString& file, TString& name, TString& path, TString& date, TString& src, Int_t* run, char* type)
+{
+    const Int_t slash = file.Last('/');
+
+    // Get File name and Path
+    path = file(0,slash+1);
+    name = file(slash+1,file.Length());
+  
+    TString tmp = name;
+    
+
+    // Get date
+    date = tmp(0,tmp.First('_'));
+    tmp = tmp.Remove(0,tmp.First('_')+1);
+
+ 
+    // Get run number
+    const TString runstr = tmp(0,tmp.First('_')); 
+    *run = atoi(runstr.Data());
+    tmp = tmp.Remove(0,tmp.First('_')+1);
+
+
+    // Get run type
+    *type = tmp[0];
+    tmp = tmp.Remove(0,tmp.First('_')+1);
+  
+
+    // Get source name
+    //src = tmp(0,tmp.First('_')); 
+    //
+    // To deal with  4C15 with filemames doesn't include '_E' (18-11-2004) 
+    //
+    if (tmp.Contains('_'))
+	src = tmp(0,tmp.First('_'));
+    else	
+	src = tmp(0,tmp.First('.'));
+}
+
+
+// ----------------------------------------------------------------------------
+//
+// First check that previous run was not empty, and then that it contains
+// runs for the current source (fSrcName)
+//
+Int_t MDataSetIter::IsPreviousRunUsable(MRunIter& oldRuns)
+{
+    if( oldRuns.GetNumRuns() == 0)
+    {
+	*fLog << warn << "Doesn't exist previous set." << endl;
+	return kFALSE;
+    }
+    
+    //
+    // Go back to ther first entry
+    //	
+    oldRuns.Reset(); 
+	
+    //
+    // Check that the previous runs were for the same source name
+    //
+    TString name, path, date, src;
+    Int_t run;
+    char type;
+    
+    ScanFileName(oldRuns.Next(), name, path, date, src, &run, &type);
+ 
+    
+    if ( !CompareSourceNames(src,fSrcName) )
+    //
+    // For dealing with calibration color we just ask than the srcname 
+    // contains the FirstSrcName
+    //
+    //if( !src.Contains(fSrcName) )
+    {
+	*fLog << warn << "Previous runs were for a diffrent source [" << src << "] vs [" << fSrcName << "] ...exit." << endl;
+	return kFALSE;
+    }
+    
+    
+    return kTRUE;
+}
+    
+
+// ---------------------------------------------------------------------------
+// 
+//  Assumes that a data set has the following structure:
+//    P/C,P/C,P/C, ...
+//    D,D,D, ...  
+// 
+//  After finishing the loop, it checks that were found at least one Ped, one
+//  Cal and one Data runs. 
+//
+//  Start from the last processed run, looking for Ped, Cal and Dat runs. As
+//  soon a Data run is found, it start to look only for Data runs, finishing 
+//  the loop when a run of different type of Data run is found.
+// 
+// Process all the runs which runnumber is later to the last processed run 
+//  (the first time this function is call fLastProcessedDataRun is 0, so it start
+//  processing from the beginning)
+//
+//  NOTE: This FAILS if the directory doesn't start with at lead one P and one 
+//        C runs  
+//
+Int_t MDataSetIter::NextDataSet()
+{
+   
+    if(fFileList.GetLast()==-1)
+    {
+	*fLog << warn << "File list empty." << endl;
+	return kFALSE;    
+    }
+
+
+    //
+    // Save temporaly prvious data set;
+    //
+    MRunIter* oldDataRuns = 0;
+    MRunIter* oldPedRuns = 0;
+    MRunIter* oldCalRuns = 0;
+    
+    if(fDataRuns)
+      oldDataRuns = (MRunIter*)fDataRuns->Clone();
+    if(fPedRuns)
+      oldPedRuns = (MRunIter*)fPedRuns->Clone();
+    if(fCalRuns)
+      oldCalRuns = (MRunIter*)fCalRuns->Clone();
+    
+
+  
+    //
+    // Retrieve next data set P,C and D runs
+    //
+    Loop("dataset");
+
+
+    // 
+    // If no data runs were found, is because we were already at the end of 
+    // the directory. Then Return kFALSE
+    //
+    if ( fDataRuns->GetNumRuns()==0 )
+    {
+	*fLog << warn << "No more Data runs left." << endl;
+	return kFALSE;
+    }
+
+       
+    //
+    // If no new P runs found, use the previous one, if they were for the 
+    // same source
+    //
+    if ( fPedRuns->GetNumRuns()==0 )
+    {
+
+	*fLog << warn << "No Ped runs were found before data runs." << endl;
+
+
+	// 
+	// Trying to Use previous pedestal, if there were
+	//
+	if ( IsPreviousRunUsable(*oldPedRuns) )
+	{  
+	    *fLog << warn << "Using Previous Ped runs." << endl;
+	    fPedRuns->Delete();
+	    fPedRuns = (MRunIter*)oldPedRuns->Clone();
+	}
+	else
+	{
+	    *fLog << warn << "Previous Ped runs exists but for a different source." << endl;
+
+
+	    //
+	    // Found next P after D runs
+	    //
+	    *fLog << warn << "Looking for new Ped runs after last data run..." << endl;
+
+	    oldDataRuns = (MRunIter*)fDataRuns->Clone();
+	    oldCalRuns = (MRunIter*)fCalRuns->Clone();
+    
+	    Loop("P",fSrcName);
+	   
+	    // fDataRuns and fCalRuns has been overwriteen when calling Loop
+	    fDataRuns->Delete();
+	    fDataRuns = (MRunIter*)oldDataRuns->Clone();
+
+	    fCalRuns->Delete();
+	    fCalRuns = (MRunIter*)oldCalRuns->Clone();
+
+	    
+	    //
+	    // Last check
+	    //
+	    if ( fPedRuns->GetNumRuns() == 0 )
+	    {
+		*fLog << err << "ERROR: Unable to found Ped runs for this source [" << fSrcName << "] ... exit." << endl;
+		return kFALSE;
+	    }
+	}
+	
+    }
+
+
+    //
+    // If no new C runs found, use the previous one, if they were for the 
+    // same source
+    //
+    if ( fCalRuns->GetNumRuns()==0 )
+    {
+	*fLog << warn << "No Cal runs were found before data runs." << endl;
+
+	// 
+	// Trying to Use previous pedestal, if there were
+	//
+	if ( IsPreviousRunUsable(*oldCalRuns) )
+	{
+	    *fLog << warn << "Using Previous Cal runs." << endl;
+	    fCalRuns->Delete();
+	    fCalRuns = (MRunIter*)oldCalRuns->Clone();
+	}
+	else
+	{
+
+	    //
+	    // Found next P after D runs
+	    //
+	    *fLog << warn << "Looking for new Cal runs after last data run..." << endl;
+	    
+	    
+	    oldDataRuns = (MRunIter*)fDataRuns->Clone();
+	    oldPedRuns = (MRunIter*)fPedRuns->Clone();
+	        
+	    Loop("C",fSrcName);
+	    
+	    
+	    // fDataRuns and fPedRuns has been overwriteen when calling Loop
+	    fDataRuns->Delete();
+	    fDataRuns = (MRunIter*)oldDataRuns->Clone();
+	    
+	    fPedRuns->Delete();
+	    fPedRuns = (MRunIter*)oldPedRuns->Clone();
+	    
+
+
+	    //
+	    // Last check
+	    //
+	    if ( fCalRuns->GetNumRuns() == 0 )
+	    {
+		*fLog << err << "ERROR: Unable to found Cal runs for this source [" << fSrcName << "] ... exit." << endl;
+
+		//
+		// Using a default Cal run
+		//
+		if( fDefCalRun != 0)
+		{
+		    *fLog << warn << "WARN: Using a default calibration run: " << fDefCalRunPath << fDefCalRun << endl;
+		    fCalRuns->AddRun(fDefCalRun,fDefCalRunPath.Data());
+		}
+		else
+		    return kFALSE;
+	    }
+	}
+    }
+
+
+
+
+    //
+    // Print the runs of this data set
+    //
+    //Print();
+
+
+    oldDataRuns->Delete();
+    oldPedRuns->Delete();
+    oldCalRuns->Delete();
+    
+
+    return kTRUE;
+}
+
+
+// -----------------------------------------------------------------------
+//
+//  Write an ASCII file with the sequence info. 
+//  The name of the file is 'sequenceRunNum.txt' where 
+//  RunNum is the run number of the first data file to analyse. We use 
+//  the data runnumber instead of calib run because several sequences can
+//  have the same calib run (just the P can change)
+//
+Int_t MDataSetIter::WriteSequence()
+{
+    //
+    // Sequence
+    //
+    //fSequence->SetupDatRuns(fDataRuns, fPathData, "D");
+    //fSequence->SetupPedRuns(fPedRuns, fPathData, "P");
+    //fSequence->SetupCalRuns(fCalRuns, fPathData, "C");
+    
+    //fSequence->Print();
+
+    TString sped =  fPedRuns->GetRunsAsFileName();
+    TString scal =  fCalRuns->GetRunsAsFileName();
+    TString sdata = fDataRuns->GetRunsAsFileName();
+
+    sped.ReplaceAll("_"," ");
+    scal.ReplaceAll("_"," ");
+    sdata.ReplaceAll("_"," ");
+
+   
+    Int_t seqnum;
+    //sscanf(scal.Data(),"%d",&seqnum);
+    sscanf(sdata.Data(),"%d",&seqnum);
+
+    TString fname = Form("sequence_%s_%d.txt",fDate.Data(), seqnum);
+    ofstream out(fname);
+
+
+    TString date = fDate;
+    date.Insert(4,"-");
+    date.Insert(7,"-");
+
+
+    //out << "# Sequence number (identifier)" <<endl;
+    out << "Sequence: " << seqnum << endl;
+    //out << endl;
+    //out << "# date of sunrise of the observation night" << endl;
+    //out << "Night: 2004-09-21" << endl;
+    out << "Night: " << date << endl;
+    out << endl;
+    //out << "# Source name of all runs of sequence" << endl;
+    //out << "Source: " << fSrcName << endl;
+    //out << endl;
+    //out << "# List of all runs of this sequence" << endl;
+    //out << "Runs: " << scal << " " << sped << " "<< sdata << endl;  
+    //out << endl;
+    //out << "# List of all calibration runs of this sequence" << endl;
+    out << "CalRuns: " << scal << endl;
+    //out << "# List of all pedestal runs of this sequence" << endl;
+    out << "PedRuns: " << sped << endl;
+    //out << "# List of all data runs of this sequence" << endl;
+    out << "DatRuns: "<<  sdata << endl;
+    out.close();
+
+    
+    return kTRUE;
+}
+
+
+  
+// ---------------------------------------------------------------------------
+//
+//  Look for a set of consecutive runs of a given type (P/C/D), starting from 
+//  the last processed data run. The runs found are stored in 
+//  f[Data/Ped/Cal]Runs.
+//
+//  If option="P" look for a set of consecutive P runs. The same for C and D 
+//  runs.
+//  If options="dataset", look for set of consecutive D runs, but also retrieve
+//  all the P and C runs between the last processed run, and the first data 
+//  run.
+//
+//  Method:
+//  -------
+//  Loop over all the files, and forechs does:
+//    First, performs 2 tests
+//      - run number: must be larger than the last processed data run
+//      - source name: must be one of the selected source names
+//    then
+//      - add this run, but before, check that it correspond to the same
+//        src name than the previously addded runs.
+//
+Int_t MDataSetIter::Loop(TString option, TString LockSrcName)
+{
+
+    //
+    // Delete previous data runs
+    //
+    fDataRuns->Delete();
+    fDataRuns = new MRunIter();
+
+    fPedRuns->Delete();
+    fPedRuns = new MRunIter();
+
+    fCalRuns->Delete();
+    fCalRuns = new MRunIter();
+
+    //
+    // Init
+    //
+    TString FirstSrcName = "";     // SrcName of the first run found
+    Bool_t RunFound     = kFALSE; 
+    Bool_t DataRunFound = kFALSE; 
+    Bool_t CalRunFound  = kFALSE;
+    Bool_t PedRunFound  = kFALSE;
+
+   
+
+
+    //
+    // Check option
+    //
+    if ( option.CompareTo("dataset",TString::kIgnoreCase) && 
+	 option.CompareTo("P",TString::kIgnoreCase) && 
+	 option.CompareTo("C",TString::kIgnoreCase) && 
+	 option.CompareTo("D",TString::kIgnoreCase) )
+    {
+	*fLog << err << "ERROR: option [" << option << "] invalid...exit" << endl;
+	return kFALSE;
+    }
+    
+    char SelectedType = !option.CompareTo("dataset",TString::kIgnoreCase) ? 'D' : option[0];
+  
+  
+
+
+    //
+    // Loop over all the files in the directory
+    //
+    TIter next(&fFileList);;
+    TNamed* n;
+    while ( (n=(TNamed*)next()) )
+    {  
+	TString name, path, date, src;
+	Int_t run;
+	char type;
+
+	ScanFileName(n->GetName(), name, path, date, src, &run, &type);
+
+
+	//
+	// Check that runnumber is inside the desire range of range to analyse [fInitialRun,fEndRun]
+	//
+	if(fEndRun !=-1 && run > fEndRun)
+	    break;
+	if(run < fInitialRun)
+	    continue;
+
+
+	// 
+	// Skip until finding the following run after the last processed one, fLastDataRun
+	//
+	if( run <= fLastProcessedDataRun )
+	    continue;
+
+	//
+	// Check that the source name is among one of the selected source names
+	//
+	if( LockSrcName != "")
+	{	
+	    FirstSrcName = LockSrcName;
+	}
+	
+	if( !CheckSourceName(src) )
+	    continue;
+
+
+	//
+	// If a Data run has already be found, the next files has to be only
+	// of type Data, if not finish.
+	//
+	if( !option.CompareTo("dataset",TString::kIgnoreCase) && DataRunFound==kTRUE && type!=SelectedType )
+	    break;
+
+	else if( !option.CompareTo("P",TString::kIgnoreCase) && PedRunFound==kTRUE && type!=SelectedType ) 
+	    break;
+	
+	else if( !option.CompareTo("C",TString::kIgnoreCase) && CalRunFound==kTRUE && type!=SelectedType ) 
+	    break;
+	
+	else if( !option.CompareTo("D",TString::kIgnoreCase) && DataRunFound==kTRUE && type!=SelectedType) 
+	    break;
+	
+	
+	
+	//
+	// For Checking that this run has the same name that the first one of 
+	// this set
+	//
+	if (RunFound==kFALSE)
+	{
+	    RunFound = kTRUE;
+	    FirstSrcName = src;
+	}
+
+	
+	if( !CompareSourceNames(src,FirstSrcName) )
+	{
+	    *fLog << err << "ERROR: Source Name differs inside data set ("
+		  << src << " vs. " << FirstSrcName << ") ...exit." << endl;
+	    return kFALSE;
+	}
+
+
+
+	//
+	// Add this run to its corresponding MRunIter
+	//
+	switch (type)
+	{
+	case 'D':
+	    if(  !option.CompareTo("dataset",TString::kIgnoreCase) || 
+	         !option.CompareTo("D",TString::kIgnoreCase) )
+	    {
+		*fLog << "Adding Data run: " << run << " [" << src << "]" << endl;
+	
+		fDataRuns->AddRun(run,path.Data());
+		
+		fSrcName = src;
+		fDate = date;
+		
+		DataRunFound = kTRUE;
+
+		fLastProcessedDataRun = run;	
+	    }
+	    break;
+	
+	case 'P': 
+	  if(  !option.CompareTo("dataset",TString::kIgnoreCase) || 
+	       !option.CompareTo("P",TString::kIgnoreCase)  )
+	    {
+		*fLog << "Adding Ped run: "<< run  << " [" << src << "]" << endl;   
+		
+		PedRunFound = kTRUE;
+		 
+		fPedRuns->AddRun(run,path.Data());
+	    }
+	    break;
+
+	case 'C':
+	   if(  !option.CompareTo("dataset",TString::kIgnoreCase) || 
+		!option.CompareTo("C",TString::kIgnoreCase)  )
+	    {
+
+	      if(CalRunFound==kFALSE)
+	      {
+		  *fLog << "Adding Cal run: "<< run  << " [" << src << "]" << endl;		
+		  CalRunFound = kTRUE;
+		    
+		  fCalRuns->AddRun(run,path.Data());
+	      }
+	      else 
+		  *fLog << "SKIPPING Cal run: "<< run  << " [" << src << "]" << endl;
+	      
+
+	    }
+	    break;
+	}
+
+	
+    } // End loop
+
+
+    return kTRUE;
+}
+
+
+
+
+
+// ---------------------------------------------------------------------------
+//
+//  By default print the P,C and D runs of the current data set. With the
+//  option "all" print only all the files in the FileList.
+//
+void MDataSetIter::Print(const Option_t *option) const
+{
+
+    //
+    //  Print all the files in the FileList.
+    //
+    TString s(option);
+    if (s.Contains("all", TString::kIgnoreCase))
+    {
+	fFileList.Print();
+	return;
+    }
+
+    
+    //
+    // Reset
+    //
+    fPedRuns->Reset(); 
+    fCalRuns->Reset();
+    fDataRuns->Reset();
+
+
+    //
+    // Print the runs of this data set
+    //
+    TString file;
+
+    *fLog << all << endl << " pedestal runs: " << endl;
+    *fLog << "---------------" << endl;
+    while( !(file=fPedRuns->Next()).IsNull() )
+	*fLog << file << endl;
+
+   	   
+    *fLog << endl << " calibration runs: " << endl; 
+    *fLog << "------------------" << endl;
+    while( !(file=fCalRuns->Next()).IsNull() )
+	*fLog << file << endl;
+
+
+    *fLog << endl << " data runs: " << endl;
+    *fLog << "-----------" << endl;
+    while( !(file=fDataRuns->Next()).IsNull() )
+	*fLog << file << endl;
+    
+    
+    *fLog << endl;
+
+
+    //
+    // Reset
+    //
+    fPedRuns->Reset(); 
+    fCalRuns->Reset();
+    fDataRuns->Reset();
+
+}
+
+
+// ------------------------------------------------------------------------------------
+//
+//  Deterimines wheather of data runs has been processed or not
+//
+Bool_t MDataSetIter::HasFinishedSuccesfully()
+{
+
+    if(fEndRun==-1)
+	*fLog << "LastDataRun = " << fLastDataRun << endl;
+    else 
+	*fLog << "EndRun = " <<  fEndRun << endl;
+    
+    *fLog << "LastProcessedDataRun = " << fLastProcessedDataRun << endl;   
+
+
+    if(fEndRun==-1)
+	return fLastProcessedDataRun==fLastDataRun ? kTRUE : kFALSE;
+    else 
+	return fLastProcessedDataRun==fEndRun ? kTRUE : kFALSE;
+       
+}
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MDataSetIter.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MDataSetIter.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MDataSetIter.h	(revision 9772)
@@ -0,0 +1,111 @@
+#ifndef MARS_MDirIterExt
+#define MARS_MDataSetIter
+
+#ifndef MARS_MDirIter
+#include "MDirIter.h"
+#endif
+
+#ifndef MARS_MRunIter
+#include "MRunIter.h"
+#endif
+
+#ifndef MARS_MSequence
+#include "MSequence.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MLog;
+class TString;
+
+class MDataSetIter : public MDirIter
+{
+ private:
+    
+    TObjArray fFileList;  // List with all the file names ordered by name
+                          // The list contains TNamed(file, "")
+    TObjArray fSrcList;   // List with the valid source names
+
+   
+    Int_t fInitialRun;  // Runnumber of the first run to proccess
+    Int_t fEndRun;      // Runnumber of the last run to proccess
+    Int_t fLastProcessedDataRun;  // Runnumber of the last processed run
+    Int_t fLastDataRun; // Lst Data runnumber in fFileList
+
+    MRunIter* fPedRuns;
+    MRunIter* fCalRuns;
+    MRunIter* fDataRuns;
+    MSequence* fSequence;
+
+    TString fSrcName;
+    TString fDate;
+
+    Int_t fDefCalRun;
+    TString fDefCalRunPath;  
+
+    MLog *fLog;
+    
+   
+    Int_t CheckSourceName(TString& src);
+    Int_t CompareSourceNames(TString& src1, TString& src2);
+    void  AddToFileList(MDirIter& dir);
+    void  ScanFileName(const TString& file, TString& name, TString& path, TString& date, TString& src, Int_t* run, char* type);  
+    Int_t IsPreviousRunUsable(MRunIter& oldRun);
+    Int_t Loop(TString option, TString LockSrcName="");
+    void FindLastDataRun();
+
+ public:
+    
+    MDataSetIter();
+ 
+    Int_t AddDirectory(const char *dir, const char *filter="*.root", Int_t recursive=0);    
+    void SelectSourceName(const char *src);
+   
+    Int_t NextDataSet(); 
+
+    void SetInitialRun(Int_t run) { fInitialRun = run; }
+    void SetEndRun(Int_t run) 
+    { 
+	fEndRun = run; 
+	FindLastDataRun();
+    } 
+    void SetDefCalRun(Int_t run, const char* path) {fDefCalRun = run; fDefCalRunPath = path; }
+
+    Int_t GetLastProcessedRun() const { return fLastProcessedDataRun; }
+
+    TString*  GetSrcName()  { return &fSrcName; }
+    TString*  GetDate()     { return &fDate;    }
+    MRunIter* GetDataRuns() 
+    { 
+	fDataRuns->Reset(); 
+	return fDataRuns;     
+    }
+    MRunIter* GetPedRuns()  
+    {
+	fPedRuns->Reset();
+	return fPedRuns;     
+    }
+    MRunIter* GetCalRuns()  
+    {
+	fCalRuns->Reset();
+	return fCalRuns;
+    }
+    
+    void Reset()
+    {
+	fLastProcessedDataRun = 0; 
+    }
+
+    void Print(const Option_t *option="") const;
+    
+    Bool_t HasFinishedSuccesfully();
+
+    Int_t WriteSequence();
+
+
+    ClassDef(MDataSetIter, 1) // Iterator for data set made of Pec, Cal and Data runs
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MExtrapolatePointingPos.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MExtrapolatePointingPos.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MExtrapolatePointingPos.cc	(revision 9772)
@@ -0,0 +1,317 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez 03/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MExtrapolatePointingPos
+//
+//   In the PreProcess, read the drive report and store it in an TSpline.
+//   In the Process, use the TSpline to calculate the PointingPos for the 
+//   time of the current event.
+// 
+//  Input Containers:
+//   MRawEvtData
+//
+//  Output Containers:
+//   MPointingPos
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MExtrapolatePointingPos.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include <TString.h>
+#include <TSpline.h>
+
+#include "MTaskList.h"
+#include "MParList.h"
+#include "MEvtLoop.h"
+#include "MReadReports.h"
+#include "MReportDrive.h"
+#include "MPointingPos.h"
+#include "MTime.h"
+#include "MRawRunHeader.h"
+
+#include <TCanvas.h>
+
+ClassImp(MExtrapolatePointingPos);
+
+using namespace std;
+
+
+// ---------------------------------------------------------------------------
+//
+// Read the drive report file for the whole night, a build from it the splines
+//
+Bool_t MExtrapolatePointingPos::ReadDriveReport(const TString filename)
+{
+
+    *fLog << endl << "["<< GetName() << "]: Loading report file \"" << filename << "\" into TSpline..." << endl;
+
+
+    //
+    // ParList
+    //
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+
+    //
+    // TaskList
+    //
+    MReadReports read;
+    read.AddTree("Drive");
+    read.AddFile(filename);     // after the reading of the trees!!!
+    read.AddToBranchList("MReportDrive.*");
+    
+    tlist.AddToList(&read);
+ 
+   
+    //
+    // EventLoop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.PreProcess())
+        return kFALSE;
+
+
+    TArrayD ReportTime(10000);
+    TArrayD CurrentZd(10000);
+    TArrayD CurrentAz(10000); 
+    TArrayD NominalZd(10000);
+    TArrayD NominalAz(10000);
+    TArrayD Ra(10000);
+    TArrayD Dec(10000);
+
+    
+    Int_t n=0;
+    while (tlist.Process())
+    { 
+	MReportDrive* report = (MReportDrive*)plist.FindObject("MReportDrive");
+	MTime* reporttime = (MTime*)plist.FindObject("MTimeDrive");
+	
+	if(n==0)
+	    fFirstDriveTime = *reporttime;
+	else 
+	    fLastDriveTime = *reporttime;
+
+	//
+	// Sometimes there are two reports with the same time
+	//
+	if (reporttime->GetTime() == ReportTime[n-1])
+	{ 
+	    cout << warn <<"["<< GetName() << "]: Warning: this report has the same time that the previous one...skipping it " << endl;
+	    continue;
+	}
+
+	ReportTime[n] = reporttime->GetTime();
+	CurrentZd[n] = report->GetCurrentZd();
+	CurrentAz[n] = report->GetCurrentAz();
+	NominalZd[n] = report->GetNominalZd();
+	NominalAz[n] = report->GetNominalAz();
+	Ra[n] = report->GetRa();
+	Dec[n] = report->GetDec();
+
+	n++;
+    }
+
+    tlist.PrintStatistics();
+
+    *fLog << "["<< GetName() << "]: loaded " << n << " ReportDrive from " 
+	  << fFirstDriveTime << " to " << fLastDriveTime << endl << endl;
+
+
+    //
+    // Update the number of entries
+    //
+    ReportTime.Set(n);
+    CurrentZd.Set(n);
+    CurrentAz.Set(n); 
+    NominalZd.Set(n);
+    NominalAz.Set(n);
+    Ra.Set(n);
+    Dec.Set(n);
+     
+    // for(int i=0;i<ReportTime.GetSize();i++)
+// 	*fLog << i            << " " << ReportTime[i] << " " 
+// 	      << CurrentZd[i] << " " << CurrentAz[i]  << " " 
+// 	      << NominalZd[i] << " " << NominalAz[i]  << " " 
+// 	      << Ra[i]        << " " << Dec[i]        << endl;
+    
+
+    fSplineZd = new TSpline3("zenith",
+			     ReportTime.GetArray(), NominalZd.GetArray(), n);
+    fSplineAz = new TSpline3("azimuth",
+			     ReportTime.GetArray(), NominalAz.GetArray(), n);
+    fSplineRa = new TSpline3("RA",
+			     ReportTime.GetArray(), Ra.GetArray(), n);
+    fSplineDec = new TSpline3("DEC",
+			     ReportTime.GetArray(), Dec.GetArray(), n);
+
+   
+    
+   //  TCanvas* c = new TCanvas();
+//     c->Divide(2,2);
+//     c->cd(1);
+//     fSplineZd->Draw();
+//     c->cd(2);
+//     fSplineAz->Draw();
+//     c->cd(3);
+//     fSplineRa->Draw(); 
+//     c->cd(4);
+//     fSplineDec->Draw();
+//     c->Modified();
+//     c->Update();
+    
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Constructor
+//
+MExtrapolatePointingPos::MExtrapolatePointingPos(const TString filename, const char *name, const char *title)
+{
+    fName  = name  ? name  : "MExtrapolatePointingPos";
+    fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
+
+    fFilename = filename;
+
+    // Init
+    fError = kFALSE;
+    fSplineZd  = NULL;
+    fSplineAz  = NULL;
+    fSplineRa  = NULL;
+    fSplineDec = NULL;
+}
+
+MExtrapolatePointingPos::~MExtrapolatePointingPos()
+{
+    if(fSplineZd)
+	delete fSplineZd;
+    if(fSplineAz)
+	delete fSplineAz;
+    if(fSplineRa)
+	delete fSplineRa;    
+    if(fSplineDec)
+	delete fSplineDec;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Input:
+//  - MTime
+// 
+//  Output:
+//  - MPointingPos
+//
+Int_t MExtrapolatePointingPos::PreProcess( MParList *pList )
+{
+    fRunHeader = (MRawRunHeader*)pList->FindObject(AddSerialNumber("MRawRunHeader"));
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+    
+    fEvtTime = (MTime*)pList->FindObject("MTime");
+    if (!fEvtTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPointingPos = (MPointingPos*)pList->FindCreateObj("MPointingPos");
+    if (!fPointingPos)
+        return kFALSE;
+
+
+    if( !ReadDriveReport(fFilename) )
+	return kFALSE;
+
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Get the run start time, and get the pointing position for that time
+//
+Int_t MExtrapolatePointingPos::Process()
+{
+
+    //const Int_t run = fRunHeader->GetRunNumber();
+    const MTime* StartRunTime = &fRunHeader->GetRunStart();
+    const Double_t time = StartRunTime->GetTime();
+
+
+    //
+    // Check that we have drive report for this time
+    //
+    if( *StartRunTime<fFirstDriveTime || *StartRunTime>fLastDriveTime)
+    {
+	*fLog << err << dbginf << GetName() << ": Run time " << *StartRunTime
+	      << " outside range of drive reports  (" << fFirstDriveTime 
+	      << ", " << fLastDriveTime << ")" << endl;
+	fError = kTRUE;
+	return kFALSE;
+    }
+
+    //if(run < 20000)
+    //   time = fEvtTime->GetTime();
+    //else
+    //   time = StartRunTime->GetTime();
+
+
+    const Double_t zd = fSplineZd->Eval( time );
+    const Double_t az = fSplineAz->Eval( time );
+    const Double_t ra = fSplineRa->Eval( time );
+    const Double_t dec = fSplineDec->Eval( time );
+
+    fPointingPos->SetLocalPosition( zd, az );
+    fPointingPos->SetSkyPosition( ra*TMath::DegToRad()/15, dec*TMath::DegToRad());
+
+   //  *fLog << " PointingPos: time = " << time << " (" << *fEvtTime << ")  (zd, az, ra, dec) = (" << zd << ", "  << az << ", " << ra << ", "  << dec << ")" << endl; 
+
+
+    return kTRUE;
+}
+
+
+// ----------------------------------------------------------------------------
+//
+//
+Int_t MExtrapolatePointingPos::PostProcess()
+{
+    return fError ? kFALSE : kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MExtrapolatePointingPos.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MExtrapolatePointingPos.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MExtrapolatePointingPos.h	(revision 9772)
@@ -0,0 +1,66 @@
+#ifndef MARS_MExtrapolatePointingPos
+#define MARS_MExtrapolatePointingPos
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TSpline
+#include <TSpline.h>
+#endif
+
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+
+
+class MTime;
+class MPointingPos;
+class MRawRunHeader;
+class TString;
+
+class MExtrapolatePointingPos : public MTask
+{
+
+ private:
+
+    TString fFilename;
+    MTime  fFirstDriveTime;
+    MTime  fLastDriveTime;
+
+    MTime  *fEvtTime;            // raw event time
+    MPointingPos *fPointingPos;  // telescope pointing postion
+    MRawRunHeader* fRunHeader;
+
+    TSpline3* fSplineZd;  // Zd vs. time
+    TSpline3* fSplineAz;  // Az vs. time
+    TSpline3* fSplineRa;  // Ra vs. time
+    TSpline3* fSplineDec; // Dec vs. time
+
+    Bool_t fError;        // Flag indicating that error ocurred in Proccess
+   
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+    Bool_t ReadDriveReport(const TString filename);    
+
+
+ public:
+    
+    MExtrapolatePointingPos(const TString reportname, const char *name=NULL, const char *title=NULL);
+
+    ~MExtrapolatePointingPos();
+
+
+    ClassDef(MExtrapolatePointingPos, 1)  
+};
+
+#endif
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MHExcessEnergyTheta.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MHExcessEnergyTheta.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MHExcessEnergyTheta.cc	(revision 9772)
@@ -0,0 +1,326 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopez    11/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHExcessEnergyTheta                                                      //
+//                                                                          //
+//  3D-histogram in alpha vs. E-est and Theta                                //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHExcessEnergyTheta.h"
+
+#include <TCanvas.h>
+#include <THStack.h>
+#include <TLegend.h>
+#include <TStyle.h>
+
+#include "MMcEvt.hxx"
+#include "MHillasSrc.h"
+#include "MEnergyEst.h"
+#include "MPointingPos.h"
+#include "MRawRunHeader.h"
+#include "MHAlphaEnergyTheta.h"
+#include "MHFindSignificance.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHExcessEnergyTheta);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram. 
+//
+MHExcessEnergyTheta::MHExcessEnergyTheta(const char *name, const char *title)
+  :  fHist("","",10,0,1, 10,0,1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHExcessEnergyTheta";
+    fTitle = title ? title : "# Excess events vs. E and Theta";
+
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetTitle("# Excess events vs. E and Theta");
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("\\Theta [\\circ]");
+    fHist.SetZTitle("# Excess events");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings and prepare filling of the histogram
+// 
+Bool_t MHExcessEnergyTheta::SetupFill(const MParList *plist)
+{
+
+ //   fEnergy = (MEnergyEst*)plist->FindObject("MEnergyEst");
+//    if (!fEnergy)
+//    {
+//        *fLog << err << dbginf << "MEnergyEst not found... aborting." << endl;
+//        return kFALSE;
+//    }
+   
+
+//    //
+//    // Binning
+//    //
+//    MBinning* binsenergy = (MBinning*)plist->FindObject("BinningE");
+//    MBinning* binsalphaflux  = (MBinning*)plist->FindObject("BinningAlphaFlux");
+//    MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta");
+//    if (!binsenergy || !binsalphaflux || !binstheta)
+//    {
+//        *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+//        return kFALSE;      
+//    }
+
+// //   SetBinning(&fHist, binsalphaflux, binsenergy, binstheta);
+//    SetBinning(&fHist, binsenergy, binstheta, binsalphaflux);
+
+//    fHist.Sumw2(); 
+
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Look in the parlist for MMcEvt or MPointingPos depending on the run type. 
+//
+Bool_t MHExcessEnergyTheta::ReInit(MParList *pList)
+{
+
+//     // This must be done in ReInit because in PreProcess the
+//     // runheaders are not available
+//     const MRawRunHeader *runheader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+//     if (!runheader)
+//     {
+//         *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+// 	*fLog << warn << dbginf << "Warning - Assuming data type file...searching for MPointingPos..." << endl;
+//     }
+   
+
+//     if (runheader && runheader->IsMonteCarloRun())
+//     {	
+// 	fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+// 	if (!fMcEvt)
+// 	{
+// 	    *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+// 	    return kFALSE;
+// 	}
+//     }
+//     else
+//     {
+// 	fPointingPos = (MPointingPos*)pList->FindObject("MPointingPos");
+// 	if (!fPointingPos)
+// 	{
+// 	    *fLog << err << dbginf << "PointingPos not found... aborting." << endl;
+// 	    return kFALSE;
+// 	}
+//     }
+  
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+// 
+Bool_t MHExcessEnergyTheta::Fill(const MParContainer *par, const Stat_t w)
+{
+ //    MHillasSrc &hil = *(MHillasSrc*)par;
+
+//   //   fHist.Fill(hil.GetAlpha(), fEnergy->GetEnergy(),
+// //                fMcEvt->GetTelescopeTheta()*kRad2Deg, w);
+ 
+
+//     const Double_t Zd = (fMcEvt) ? fMcEvt->GetTelescopeTheta()*kRad2Deg : fPointingPos->GetZd() ;
+
+//     fHist.Fill(fEnergy->GetEnergy(), Zd, hil.GetAlpha(), w);
+	
+//     //  *fLog<< Zd << " " << fEnergy->GetEnergy() << " " <<  hil.GetAlpha() << endl;
+
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Get the Alpha distribution for each bin in energy and theta,
+//  fit it with MHFindSignificance to get the number of Excess events
+//  and it error.
+// 
+void MHExcessEnergyTheta::Calc(MHAlphaEnergyTheta* hAlpha)
+{  
+    TH3D* aet = (TH3D*)hAlpha->GetHist();
+  
+    const TAxis* axisEnergy = aet->GetXaxis();
+    const TAxis* axisTheta  = aet->GetYaxis();
+    const Int_t energyBins = aet->GetXaxis()->GetNbins();
+    const Int_t thetaBins =  aet->GetYaxis()->GetNbins();;
+  
+    MH::SetBinning(&fHist, axisEnergy, axisTheta);
+ 
+    for(Int_t iy=1; iy<=thetaBins; iy++)   
+    {
+	TCanvas* c= new TCanvas(Form("zbin %d",iy),Form("zbin %d",iy));
+	c->Divide(4,3);
+
+	for(Int_t ix=1; ix<=energyBins; ix++)
+	{ const Double_t e = aet->GetXaxis()->GetBinCenter(ix); 
+	    const Double_t e1 = aet->GetXaxis()->GetBinLowEdge(ix);     
+	    const Double_t e2 =	aet->GetXaxis()->GetBinLowEdge(ix+1);
+
+	    //TH1* halpha = aet->ProjectionZ("AlphaTemp",ix,ix,iy,iy);
+	    TH1* halpha = aet->ProjectionZ("AlphaTemp",ix,ix);
+	    halpha->SetTitle(Form("Energy Bin = (%.0f, %.0f) GeV",e1,e2));
+	    halpha->SetDirectory(NULL);
+
+	    MHFindSignificance findsig;
+	    //findsig.SetRebin(kFALSE);
+	    double alphasig=20;
+	    
+	    if(ix<5) 
+		alphasig = 20;
+	    else
+		alphasig = 20;
+	     
+	  switch (ix)
+	    {
+	    case 1:
+		alphasig = 20;
+		break;
+	    case 2:
+		alphasig = 20;
+		break;
+	    case 3:
+		alphasig = 20;
+		break;
+	    case 4:
+		alphasig = 20;
+		break;
+	    case 5:
+		alphasig = 20;
+		break;
+	    case 6:
+		alphasig = 20;
+		break;
+	    case 7:
+		alphasig = 15;
+		break;
+	    case 8:
+		alphasig = 10;
+		break;
+	    case 9:
+		alphasig = 5;
+		break;
+	    case 10:
+		alphasig = 5;
+		break;
+	    }
+
+
+	    fLog->SetNullOutput(kTRUE);
+	    
+	    Bool_t rc = findsig.FindSigma(halpha, 30,90, 2, alphasig, 0,1,0);
+	    Double_t SigmaGauss = findsig.GetSigmaGauss(); 
+
+	  //   alphasig = SigmaGauss*3;
+	 
+// 	    rc = findsig.FindSigma(halpha, 30,90, 2, alphasig, 0,1,0);
+
+	    fLog->SetNullOutput(kFALSE);
+
+	    if(ix<=20)
+	    {
+		c->cd(ix);
+		findsig.DrawFit("brief");
+	    }
+
+	    Double_t Nex = 0;  
+	    Double_t dNex = 0;
+	    Double_t Sig = 0;
+
+	    if(!rc)
+	    {
+		cout << "ERROR: Fit not possible. " << endl;
+	    }
+	    // else
+	    {
+		SigmaGauss = findsig.GetSigmaGauss(); 
+		Nex = findsig.GetNex();  
+		dNex = findsig.GetdNex();    
+		Sig = findsig.GetSigLiMa();
+	    }
+	    // Avoid to have a negative number of excess events, which 
+            // will give a negative flux which doesn't make sense
+	    if(Nex<0)
+	    {
+		Nex = 0;
+		dNex = 0;
+		Sig = 0;
+	    }
+
+	    fHist.SetBinContent(ix,iy, Nex);
+	    fHist.SetBinError(ix,iy, dNex);
+
+
+	    // Print 
+	    *fLog<< endl 
+		 << " Theta Bin = "  << iy << endl
+		 << "  Energy bin width E = "  << ix << endl
+		 << "  Alphasig = " <<alphasig << endl
+		 << "    N = " <<  Nex    <<" +- " <<  dNex    << endl
+		 << "  Significane = " <<  Sig  << endl;
+	}
+    }
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+// 
+void MHExcessEnergyTheta::Draw(Option_t *opt)
+{
+    TCanvas *c1 = new TCanvas("# Excess events vs. E and Theta","# Excess events vs. E and Theta");
+    c1->SetLogx();
+    c1->SetLogz();
+
+    fHist.SetStats(0);
+    fHist.Draw("lego");
+}
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MHExcessEnergyTheta.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MHExcessEnergyTheta.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MHExcessEnergyTheta.h	(revision 9772)
@@ -0,0 +1,40 @@
+#ifndef MARS_MHExcessEnergyTheta
+#define MARS_MHExcessEnergyTheta
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH2.h>
+#endif
+
+
+class MParList;
+class MHAlphaEnergyTheta;
+    
+class MHExcessEnergyTheta : public MH
+{
+private:
+ 
+    TH2D fHist;
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *pList);
+
+
+public:
+ 
+   MHExcessEnergyTheta(const char *name=NULL, const char *title=NULL);
+
+   void Calc(MHAlphaEnergyTheta* hAlpha);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH2D *GetHist()       { return &fHist; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHExcessEnergyTheta, 1) //2D-histogram in number of excess events vs. Energy and theta
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MHFlux.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MHFlux.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MHFlux.cc	(revision 9772)
@@ -0,0 +1,549 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcos Lopex    11/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHFlux                                                                  //
+//                                                                          //
+//  3D-histogram in alpha vs. E-est and Theta                               //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHFlux.h"
+
+#include <TCanvas.h>
+#include <THStack.h>
+#include <TLegend.h>
+#include <TStyle.h>
+#include <TAxis.h>
+#include <TF1.h>
+#include <TGraphErrors.h>
+#include <TPaveText.h>
+
+#include "MHillasSrc.h"
+#include "MEnergyEst.h"
+#include "MPointingPos.h"
+#include "MRawRunHeader.h"
+
+#include "MHExcessEnergyTheta.h"
+#include "MHMcCollectionArea.h"
+#include "MHEffectiveOnTime.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHFlux);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram. 
+//
+MHFlux::MHFlux(const char *name, const char *title)
+    :  fHist("","",10,0,1, 10,0,1), fAverageFlux("","",1,0,1)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHFlux";
+    fTitle = title ? title : "Flux vs. E and Theta";
+
+
+    fHist.SetDirectory(NULL); 
+    fHist.SetName("Flux vs. E and Theta");
+    fHist.SetTitle("Flux vs. E and Theta");
+    fHist.SetXTitle("E [GeV]");
+    fHist.SetYTitle("\\Theta [\\circ]");
+    fHist.SetZTitle("Flux [TeV^{-1} s^{-1} cm^{-2}]");
+
+    fAverageFlux.SetDirectory(NULL);
+    fAverageFlux.SetName("Average Flux");
+    fAverageFlux.SetTitle("Average Flux");
+    fAverageFlux.SetXTitle("E [GeV]"); 
+    fAverageFlux.SetYTitle("Flux [TeV^{-1} s^{-1} cm^{-2}]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings and prepare filling of the histogram
+// 
+Bool_t MHFlux::SetupFill(const MParList *plist)
+{
+
+ 
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Look in the parlist for MMcEvt or MPointingPos depending on the run type. 
+//
+Bool_t MHFlux::ReInit(MParList *pList)
+{
+  
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the histogram
+// 
+Bool_t MHFlux::Fill(const MParContainer *par, const Stat_t w)
+{
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Calc
+// 
+void MHFlux::Calc(MHExcessEnergyTheta* hExcess, MHMcCollectionArea* hColArea, MHEffectiveOnTime* hEffTime)
+{
+    const TH2D* hex  = hExcess->GetHist();  
+    const TH1D* hca  = hColArea->GetHist(); 
+    const TH1D* heot = &hEffTime->GetHEffOnTheta();
+
+    TAxis* axisEnergy = hex->GetXaxis();
+    const TAxis* axisTheta  = hex->GetYaxis();
+    const Int_t energyBins = hex->GetXaxis()->GetNbins();
+    const Int_t thetaBins =  hex->GetYaxis()->GetNbins();;
+
+    MH::SetBinning(&fHist,axisEnergy, axisTheta);
+ 
+ 
+    //
+    // Calculate flux for each energy and theta
+    //
+    for (Int_t iy=1; iy<=thetaBins; iy++) // loop on theta
+    { 
+        // Get Effective Time [sec] and its error
+	Double_t t = heot->GetBinContent(iy);
+	const Double_t dt = heot->GetBinError(iy); 
+
+	if (t < 1e-3) 
+	    t = 0.0;
+
+	for (Int_t ix=1; ix<=energyBins; ix++) 
+	{   
+	    const Double_t  n = hex->GetBinContent(ix,iy);
+	    const Double_t dn = hex->GetBinError(ix,iy);
+	    
+	    // Get AreaEff and its error
+	    Double_t energy = axisEnergy->GetBinCenter(ix);	    
+	    Int_t bin = hca->GetXaxis()->FindBin(energy);	
+
+	    // Get NumberExcessEvents and its error
+	    const Double_t  a = hca->GetBinContent(bin)*1e4; //cm^2
+	    const Double_t da = hca->GetBinError(bin) *1e4; //cm^2
+ 
+	    // energy bin width in TeV
+	    const Double_t en = axisEnergy->GetBinWidth(ix)*1e-3; //TeV
+
+	    // 
+	    // Check that we can calculate the flux for the current bin
+	    //
+	    if (t==0) 
+		cout << "No_Ton ";
+	    if (a==0) 
+		cout << "No_Aeff ";
+	    if (n==0) 
+		cout << "No_Events ";
+	    if ((t == 0) || (a == 0) || (n == 0)) {
+		cout << endl;
+		continue;
+	    }
+ 	    
+	    //
+	    // Flux calculation and its error
+	    //
+	    const Double_t flux = n/(en*t*a);
+      
+	    // error  propagation formula
+	    const Double_t errN = dn/(en*a*t);
+	    const Double_t errA = da * n/(en*t*a*a);
+	    const Double_t errT = dt * n/(en*a*t*t);      
+	    const Double_t error = sqrt(errN*errN + errA*errA + errT*errT); 
+
+	    cout << dn << " " << en << " " << a << " " << t << endl;
+
+	    fHist.SetBinContent(ix,iy,flux);
+	    fHist.SetBinError(ix,iy,error);
+
+	}  //energy    
+    } //theta
+    fHist.Print("all");
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+// 
+void MHFlux::Draw(Option_t *opt)
+{
+
+    // --------------------------------------------------------------------
+    //
+    // Draw lego plot of Flux vs. Energy and Theta
+    //
+    TCanvas *c1 = new TCanvas("Flux vs. E and Theta","Flux vs. E and Theta");
+    c1->SetLogx();
+    c1->SetLogz(); 
+    fHist.SetStats(0);
+    fHist.Draw("lego");
+
+
+    // --------------------------------------------------------------------
+    //
+    // Draw the Flux for each Theta bin
+    //
+    TCanvas *c2 = new TCanvas("Fluxes for each Theta bin","Fluxes for each Theta bin");
+    c2->SetLogx();
+    c2->SetLogy();
+    c2->SetGridx();
+    c2->SetGridy();
+
+
+    THStack* hs = new THStack("Fluxes for each Theta bin","Fluxes for each Theta bin");
+
+    TLegend * leg = new TLegend(0.73,0.65,0.89,0.89);
+   
+    TAxis* yaxis = fHist.GetYaxis();
+    const Int_t nbiny = fHist.GetYaxis()->GetNbins();
+    
+    for(Int_t iy=1; iy<=nbiny; iy++)
+    {
+
+	TH1D* h1 = fHist.ProjectionX(Form("%d",iy),iy,iy,"e"); //<----- Option e is very important, otherwise the errors are not copied
+
+	if(h1->GetEntries()==0)
+	    continue;
+
+	h1->SetLineColor(iy);
+	hs->Add(h1,"e1");
+	leg->AddEntry(h1,Form("\\theta = %.0f",yaxis->GetBinCenter(iy)),"l");
+
+// 	TCanvas *c = new TCanvas();
+// 	c->SetLogx();
+// 	c->SetLogy();
+// 	h1->DrawCopy("e"); 
+// 	h1->Print("all");
+    }
+
+
+
+    // --------------------------------------------------------------------
+    //
+    // Calculate and Draw the Flux average on Theta bins
+    //
+    fAverageFlux.SetStats(0);
+
+    MH::SetBinning(&fAverageFlux,fHist.GetXaxis());
+
+    for(int ix=1; ix<=fHist.GetXaxis()->GetNbins(); ix++) // energy 
+    {
+	Double_t sumw = 0;
+	Double_t sumcontents = 0;
+	Double_t sumerrors = 0;
+
+	for(int iy=1; iy<=fHist.GetYaxis()->GetNbins(); iy++) // theta
+	{
+	    Double_t weight = fHist.GetYaxis()->GetBinWidth(iy);
+	    sumw += weight;
+	    sumcontents += fHist.GetBinContent(ix,iy)*weight;
+	    sumerrors += fHist.GetBinError(ix,iy)*weight;
+	}
+
+	fAverageFlux.SetBinContent(ix,sumcontents/sumw);
+	fAverageFlux.SetBinError(ix,sumerrors/sumw);
+    }
+
+  //   for(int ix=1; ix<=fHist.GetXaxis()->GetNbins(); ix++) // energy 
+//     {
+// 	Double_t sumw = 0;
+// 	Double_t sumcontents = 0;
+
+// 	cout << " energy bin "<<endl; 
+// 	for(int iy=1; iy<=fHist.GetYaxis()->GetNbins(); iy++) // theta
+// 	{
+
+// 	    Double_t bincontent = fHist.GetBinContent(ix,iy);
+// 	    Double_t binerror = fHist.GetBinError(ix,iy);
+	    
+// 	    if( bincontent == 0 || binerror == 0 )
+// 		continue;
+// 	    cout << binerror << endl;
+
+// 	    Double_t weight = 1/(binerror*binerror);
+// 	    sumw += weight;
+// 	    sumcontents += bincontent*weight;
+	
+// 	    cout << " theta bin "  << fHist.GetBinContent(ix,iy)<< "  " <<weight
+// 		 << endl;
+// 	}
+// 	cout << "*****************" << sumcontents << "   "<< sumw << endl;
+
+// 	if(sumcontents == 0 || sumw == 0 )
+// 		continue;
+
+// 	fAverageFlux.SetBinContent(ix,sumcontents/sumw);
+// 	fAverageFlux.SetBinError(ix,TMath::Sqrt(1/sumw));
+//     }
+
+
+   
+
+    fAverageFlux.SetMarkerStyle(8);
+    fAverageFlux.SetLineColor(6);
+    hs->Add(&fAverageFlux,"pe1");
+    leg->AddEntry(&fAverageFlux,"Average on Theta","l");
+  
+    
+    c2->cd();
+    hs->Draw("nostack");
+    leg->Draw();
+
+ 
+    TCanvas *c3 = new TCanvas("Average Flux","Average Flux");
+    c3->SetLogx();
+    c3->SetLogy();
+    c3->SetGridx();
+    c3->SetGridy();
+    fAverageFlux.Draw();
+    fAverageFlux.Print("all");
+
+    //
+    // Fix the Average Flux to a power law
+    //
+    TF1* fluxfit = new TF1("f1","[0]*pow(x,-[1])",90,1500);
+    fluxfit->SetParNames("f0","a");
+    fluxfit->SetParameter(0,5.10986e-05);
+    fluxfit->SetParameter(1,2.4);
+    fluxfit->SetTitle("Flux fit");
+    fluxfit->SetLineColor(27);
+    fluxfit->SetLineWidth(3);
+
+    fAverageFlux.Fit("f1","R");  
+   
+  
+    //
+    // Draw the Crab spectrum measured by HEGRA between 500 GeV and 80 TeV
+    //
+    TF1* CrabFlux = new TF1("CrabFlux","[0]*pow(x/1000.,-[1])",350,2000);
+    CrabFlux->SetParameter(0,2.83e-11);
+    CrabFlux->SetParameter(1,2.62);
+    CrabFlux->SetLineStyle(2); 
+    CrabFlux->SetLineColor(4);
+    CrabFlux->Draw("same");
+   
+    //
+    // Draw formula
+    //
+    TPaveText* func = new TPaveText(0.16, 0.22, 0.67, 0.28,"NDC");
+    func->AddText(Form("#frac{dF}{dE} = %.2e * E^{-%.2f} [#frac{ph}{cm^{2} s TeV}]",fluxfit->GetParameter(0),fluxfit->GetParameter(1)));
+    func->SetFillStyle(0);
+    func->SetBorderSize(0);
+    func->Draw();  
+    
+
+//     //
+//     // Draw "Preliminary"
+//     //
+//     TPaveText* lab = new TPaveText(0.33, 0.83, 0.68, 0.89,"NDC");
+//     lab->AddText("preliminary");
+//     lab->SetTextColor(2);
+//     lab->SetFillStyle(0);
+//     lab->SetBorderSize(0);
+//     lab->Draw();  
+     
+
+
+    // ---------------------------------------------------------------------
+    //
+    // Integral flux
+    // 
+    TH1D *hIntegral = (TH1D*)fAverageFlux.Clone();
+    hIntegral->GetListOfFunctions()->Clear();
+
+    Int_t nbinsx = fAverageFlux.GetNbinsX();
+    
+    for(int i=1; i<=nbinsx; i++)
+    {
+	cout <<"Integral Flux: Binwidth:" << hIntegral->GetBinWidth(i) << endl;
+	
+	hIntegral->SetBinContent(i,hIntegral->GetBinContent(i)*hIntegral->GetBinWidth(i)*1e-3);
+	hIntegral->SetBinError(i,hIntegral->GetBinError(i)*hIntegral->GetBinWidth(i)*1e-3);
+    }
+
+
+    for(int i=nbinsx-1; i>=1; i--)
+    {
+	Double_t integralsofar = hIntegral->GetBinContent(i+1);
+	Double_t current = hIntegral->GetBinContent(i);
+	
+	Double_t currentE = hIntegral->GetBinError(i);
+	Double_t Esofar = hIntegral->GetBinError(i+1);
+
+	hIntegral->SetBinContent(i,(current+integralsofar));
+	hIntegral->SetBinError(i,TMath::Sqrt(currentE*currentE+Esofar*Esofar));
+    }
+
+    
+    hIntegral->SetTitle("Integral Flux"); 
+    hIntegral->SetXTitle("E [GeV]"); 
+    hIntegral->SetYTitle("Integral Flux [s^{-1} cm^{-2}]");
+        
+    
+    TCanvas *c20 = new TCanvas();
+    c20->SetLogx();
+    c20->SetLogy();
+    c20->SetGridx();
+    c20->SetGridy();
+
+    hIntegral->Draw();
+
+
+    
+
+    // --------------------------------------------------------------------
+    //
+    //  E^2 * Flux
+    //
+    TH1D *hEscaledFlux = (TH1D*)fAverageFlux.Clone();
+   hEscaledFlux->GetListOfFunctions()->Clear();
+   
+    nbinsx = hEscaledFlux->GetNbinsX();
+    
+    for(int i=1; i<=nbinsx; i++)
+    {
+	
+	Double_t energy = hEscaledFlux->GetBinLowEdge(i)*1e-3; // TeV
+	Double_t Flux = hEscaledFlux->GetBinContent(i);
+	Double_t dFlux = hEscaledFlux->GetBinError(i);
+
+	hEscaledFlux->SetBinContent(i,energy*energy*Flux);
+	hEscaledFlux->SetBinError(i,energy*energy*dFlux);
+    }
+
+    TCanvas *c40 = new TCanvas();
+    c40->SetLogx();
+    c40->SetLogy();
+    c40->SetGridx();
+    c40->SetGridy();
+
+    hEscaledFlux->SetTitle("Escaled Flux"); 
+    hEscaledFlux ->SetXTitle("E [GeV]"); 
+    hEscaledFlux ->SetYTitle("E^{2}*Flux [TeV s^{-1} cm^{-2}]");
+    
+    hEscaledFlux->Draw();
+
+
+//     // -----------------------------------------------------------------
+//     //
+//     // Graph move a 30 %
+//     //
+//     TCanvas *c4 = new TCanvas();
+//     c4->SetLogx();
+//     c4->SetLogy();
+//     c4->SetGridx();
+//     c4->SetGridy();
+
+//     Int_t nbins = fAverageFlux.GetNbinsX();
+// 	TArrayD x(nbins),y(nbins),dx(nbins),dy(nbins);
+
+//     for(int i=1; i<=nbins; i++)
+//     {
+// 	 x[i-1] = fAverageFlux.GetXaxis()->GetBinCenter(i)*.7;
+// 	 y[i-1] = fAverageFlux.GetBinContent(i);
+// 	dx[i-1] = fAverageFlux.GetXaxis()->GetBinWidth(i)*0.62;
+// 	dy[i-1] = fAverageFlux.GetBinError(i);
+//     }
+
+//     TGraphErrors* gr = new TGraphErrors(fAverageFlux.GetNbinsX(), x.GetArray(), y.GetArray(), dx.GetArray(), dy.GetArray());
+   
+//     gr->SetMarkerStyle(8);
+//     gr->Draw("Ap");
+//     gr->Print("all");  
+
+//   //
+//     TF1* fluxfit2 = new TF1("f2","[0]*pow(x,-[1])",70,2500);
+//     fluxfit2->SetParNames("f0","a");
+//     fluxfit2->SetParameter(0,5.10986e-05);
+//     fluxfit2->SetParameter(1,2.4);
+//     fluxfit2->SetTitle("Flux fit");
+//     fluxfit2->SetLineColor(27);
+//     fluxfit2->SetLineWidth(3);
+
+
+//     gr->Fit("f2","R");  
+   
+//     gr->SetTitle("");
+//     gr->SetMaximum(1e-3);
+//     gr->SetMinimum(1e-12);
+ 
+//     TLegend* leg2 = new TLegend(0.67,0.72,0.89,0.89);
+   
+//     leg2->AddEntry(gr,"MAGIC Sept. 2004","p");
+ 
+//     gr->SetMarkerStyle(8);
+//     //  gr->SetLineColor(6);
+
+// //     //
+// //     // Draw the Crab spectrum measured by HEGRA between 500 GeV and 80 TeV
+// //     //
+// //     TF1* CrabFlux = new TF1("CrabFlux","[0]*pow(x/1000.,-[1])",350,2000);
+// //     CrabFlux->SetParameter(0,2.83e-11);
+// //     CrabFlux->SetParameter(1,2.62);
+// //     CrabFlux->SetLineStyle(2); 
+// //     CrabFlux->SetLineColor(4);
+// //     CrabFlux->Draw("same");
+
+//     leg2->AddEntry(CrabFlux,"HEGRA ApJ 614","l");
+//     leg2->Draw();
+//     lab->Draw(); 
+ 
+//     TPaveText* func2 = new TPaveText(0.16, 0.22, 0.67, 0.28,"NDC");
+//     func2->AddText(Form("#frac{dF}{dE} = %.2e * E^{-%.2f} [#frac{ph}{cm^{2} s TeV}]",fluxfit2->GetParameter(0),fluxfit2->GetParameter(1)));
+//     func2->SetFillStyle(0);
+//     func2->SetBorderSize(0);
+//     func2->Draw();  
+
+
+//     gr->GetHistogram()->SetXTitle("E [GeV]"); 
+//     gr->GetHistogram()->SetYTitle("Flux [TeV^{-1} s^{-1} cm^{-2}]");
+
+//     TH1F* h = gr->GetHistogram();
+//     TCanvas *c12 = new TCanvas();
+//     h->Draw();
+//     cout << "Integral flux = "<< h->Integral("width") << endl;
+}
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MHFlux.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MHFlux.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MHFlux.h	(revision 9772)
@@ -0,0 +1,51 @@
+#ifndef MARS_MHFlux
+#define MARS_MHFlux
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH3
+#include <TH2.h>
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+
+class MParList;
+
+class MHExcessEnergyTheta;
+class MHMcCollectionArea;
+class MHEffectiveOnTime;
+
+
+class MHFlux : public MH
+{
+private:
+ 
+    TH2D fHist;
+    TH1D fAverageFlux;
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t ReInit(MParList *pList);
+
+
+public:
+ 
+   MHFlux(const char *name=NULL, const char *title=NULL);
+
+   void Calc(MHExcessEnergyTheta* hex, MHMcCollectionArea* area, MHEffectiveOnTime* hEffTime);
+
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    TH2D *GetHist()        { return &fHist; }
+    TH1D *GetAverageFlux() { return &fAverageFlux; }
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHFlux, 1) //2D-histogram of Flux vs. Energy and theta
+};
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MHMyFindSignificanceONOFF.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MHMyFindSignificanceONOFF.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MHMyFindSignificanceONOFF.cc	(revision 9772)
@@ -0,0 +1,846 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Marcols Lopez,  August 2004      <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHMyFindSignificance
+//
+//
+//  Non: # events in the signal region (0,fAlphasig) of the ON-Data hist.
+//  Nbg: # events in the signal region (0,fAlphasig) of the OFF-Data hist.
+//  Nex = Non - Nbg
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHMyFindSignificanceONOFF.h"
+
+#include <TH1.h>
+#include <TF1.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TPaveText.h>
+#include <TGaxis.h>
+#include <TStyle.h>
+#include <TLine.h>
+#include <TString.h>
+#include <TGraph.h>
+#include <TPaveStats.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MHMyFindSignificanceONOFF);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+//  Constructor
+//
+MHMyFindSignificanceONOFF::MHMyFindSignificanceONOFF(const char *name, const char *title) 
+    : fNon(0.0), fdNon(0.0), fNbg(0.0), fdNbg(0.0), fNex(0.0), fdNex(0.0), 
+      fSigLiMa(0.0), 
+      fNbgFit(0.0), fdNbgFit(0.0), fNexFit(0.0), fdNexFit(0.0), fGamma(0.0), 
+      fNoff(0.0), fSigLiMaFit(0.0),
+      fBestSigma(0.0), fBestAlphaCut(0.0), fBestExcess(0.0)
+{
+    fName  = name  ? name  : "MHMyFindSignificanceONOFF";
+    fTitle = title ? title : "Find Significance in alpha plot";
+   
+    fHistON            = NULL;
+    fHistOrigON        = NULL;
+    fHistOFF           = NULL;
+    fHistOrigOFF       = NULL;
+    fHistOFFNormalized = NULL;
+
+    // allow rebinning of the alpha plot
+    fRebin = kTRUE;
+
+    // allow reducing the degree of the polynomial
+    fReduceDegree = kTRUE;
+}
+
+
+
+
+// ---------------------------------------------------------------------------
+//
+// Calculate  
+//
+//   - fNon:       number of events in the signal region from ON data 
+//
+//   and 3 different estimation of the background:
+//
+//   - fNbgOFF:    number of events in the signal region from  OFF data
+//   - fNbgFitOFF: estimation of # events in the signal region from a fit of
+//                 the OFF data in the Bkg region.
+//   - fNbgFitON:  estimation of # events in the signal region from a fit of
+//                 the ON data in the Bkg region.
+//   - fNex
+//
+Bool_t MHMyFindSignificanceONOFF::FindSigmaONOFF(TH1 *histON, TH1 *histOFF, 
+         Double_t alphasig, Double_t alphamin, Double_t alphamax, Int_t degree)
+{
+
+    fHistOrigON = histON;
+    fHistOrigOFF = histOFF;
+
+    fAlphasig = alphasig;  
+    fAlphaminON = alphamin;
+    fAlphamaxON = alphamax;
+    fAlphaminOFF = 0;  // <--------------------
+    fAlphamaxOFF = alphamax;
+    fDegree   = degree;
+
+
+ 
+
+    // -----------------------------------------------------------------
+    // 
+    // Calculate the normalization factor in range (alphanin,alphamax)
+    //
+    // FIXME: This can be done directly with: 
+    //        fFindsigON.GetNbtot()/fFindsigOFF.GetNbtot()
+    //        but for that the polynomial for OFF-Data has to be fitted
+    //        (alphamin, alphamax) instead of (0,alphamax)
+    //
+    CalcNormalizationFactor(fHistOrigON, fHistOrigOFF, fAlphaminON, fAlphamaxON);
+
+
+    // ----------------------------------------------------------------------- 
+    //
+    // Use MHFindSignificance to find the # evts in the signal and Bkg region
+    // and to fit the histograms. 
+    // The ON hist is fitted to a polynomial in reg. (fAlphaminON,fAlphamaxON)
+    // and to a gaussian+polynomial.
+    // The OFF hist is only fitted to a polynomial in(fAlphaminOFF,fAlphamaxOFF
+    //
+    fFindsigON.SetReduceDegree(fReduceDegree);
+    fFindsigOFF.SetReduceDegree(fReduceDegree);
+    fFindsigON.SetRebin(fRebin);
+    fFindsigOFF.SetRebin(fRebin);
+ 
+    const Bool_t rc1 = fFindsigON.FindSigma(fHistOrigON, fAlphaminON, fAlphamaxON, fDegree, fAlphasig, 0,1,0);   
+   
+    const Bool_t rc2 = fFindsigOFF.FindSigma(fHistOrigOFF, fAlphaminOFF,fAlphamaxOFF, fDegree, fAlphasig, 0,0,0);
+  
+    if (rc1==kFALSE || rc2==kFALSE)
+    {
+	*fLog << err << dbginf << "MHFindSignificance retuns kFALSE." << endl;
+	return kFALSE;
+    }
+
+
+    // Check consistency
+    if (fabs(fFindsigON.GetAlphasi() - fFindsigOFF.GetAlphasi()) > fEps)
+    {
+	*fLog << "fAlphasiOFF (" <<  fFindsigOFF.GetAlphasi()<< ") is not equal to fAlphasi ("
+	    << fFindsigON.GetAlphasi() << "), this is something that should not happen" 
+	    << endl;
+	//return kFALSE; It might happen in pathological cases (very few OFF)
+    }
+
+
+    //
+    // Get results of the fits
+    //
+    fHistON = fFindsigON.GetHist();  // don't use the original hist to draw
+    fHistOFF = fFindsigOFF.GetHist();
+    // From ON-Data
+    fNon  = fFindsigON.GetNon();
+    fdNon = fFindsigON.GetdNon();
+    // From OFF-Data
+    fNbg     = fFindsigOFF.GetNon();   // counts in signal reg. OFF hist NO 
+    fdNbg    = fFindsigOFF.GetdNon();  //normalized !!!
+    // From OFF-Data polynomial fit
+    fNbgFit  = fFindsigOFF.GetNbg(); 
+    fdNbgFit = fFindsigOFF.GetdNbg();
+    fGamma   =  fFindsigOFF.GetGamma() * fNormFactor; //<-----------
+    fNoff    =  fFindsigOFF.GetNoff();
+
+
+    // 
+    // Compare the counter number of bg events, NbgMea, and the fitted, NbgFit
+    //
+    if (fabs(fNbg - fNbgFit) > 0.1 * fNbgFit)
+    {
+	*fLog << err << dbginf << "number of OFF events and Fitted number of OFF events in signal region do not agree (within 10 %)" << endl;
+	
+	*fLog << "fNbg = " << fNbg << " ; fNbgFit = " << fNbgFit << endl;
+    }
+
+
+
+    // ---------------------------------------------------
+    //
+    // calculate the number of excess events in the signal region
+    //
+    fNex = fNon - fNbg * fNormFactor;
+    fNexFit = fNon - fNbgFit * fNormFactor;
+ 
+
+    //
+    // Calculate Significance  
+    //
+    // Significance computed using counted number of OFF-data events in signal 
+    // region (fNbg) and normalization factor (fNormFactor).
+    // This is the strictly speaking the significance in Li&Ma paper...
+    //
+    if ( !SigmaLiMa(fNon, fNbg, fNormFactor, &fSigLiMa) )
+    {
+	*fLog << err << dbginf << "SigmaLiMa failed" << endl;  
+	return kFALSE;
+    }
+    //
+    // Significance computed using effective number of OFF events  in signal 
+    // region (fNoff) and gamma factor (fGama).
+    // This is Wolfgang approach to the calulation of significance 
+    // using Li&Ma formula and estimated OFF events from polynomial fit.
+    //
+    if ( !SigmaLiMa(fNon, fNoff, fGamma , &fSigLiMaFit) )
+    {
+	*fLog << err << dbginf << "SigmaLiMaFit failed"  << endl;  
+	return kFALSE;
+    }
+    
+
+    //
+    // calculate the error of the number of excess events
+    // using fitted quantities and counted quantities
+    //
+    fdNex = fNex / fSigLiMa;
+    fdNexFit = fNexFit / fSigLiMaFit;
+
+
+
+    //
+    // Create histogram of OFF data scaled by the normalization factor
+    //
+    NormalizedHistOFF();
+
+
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Create a new histogram to store the hist of OFF data scale with by the
+//  normalization factor
+//
+void MHMyFindSignificanceONOFF::NormalizedHistOFF()
+{
+
+    //
+    // We need the following factor in case that one of the histogram 
+    // (ON or OFF) is rebin when calculatin the sifnigicance
+    //
+    const Double_t BinWidthRatioONOFF = fHistON->GetBinWidth(1)/fHistOFF->GetBinWidth(1) ;
+
+
+    //
+    // Clone OFF histogram and scale it
+    //
+    fHistOFFNormalized = (TH1*)fHistOFF->Clone();
+    fHistOFFNormalized->SetName(Form("%s (Normalized)",fHistOFF->GetName()));
+
+    fHistOFFNormalized->Scale(fNormFactor*BinWidthRatioONOFF); 
+
+    
+    //
+    // Scale the fit function of OFF data
+    // 
+    TF1* fPolyOFFNormalized = (TF1*)fFindsigOFF.GetPoly()->Clone(); 
+
+    fPolyOFFNormalized->SetLineColor(2);
+    fPolyOFFNormalized->SetLineWidth(2);
+   
+
+    const Int_t npar = fPolyOFFNormalized->GetNpar();
+    Double_t Parameter = 0.0;
+    Double_t ParameterError = 0.0;  
+    for(Int_t i=0; i<npar; i++)
+    {
+	Parameter = fNormFactor*BinWidthRatioONOFF *fPolyOFFNormalized->GetParameter(i);
+	ParameterError = fNormFactor*BinWidthRatioONOFF *fPolyOFFNormalized->GetParError(i);
+	
+	fPolyOFFNormalized -> SetParameter(i, Parameter);
+	fPolyOFFNormalized -> SetParError(i,ParameterError);
+    }
+
+    TList *funclistOFF = fHistOFFNormalized->GetListOfFunctions();
+    funclistOFF->Clear();  // delete the functions cloned from fHistOFF
+    funclistOFF->Add(fPolyOFFNormalized);
+
+   
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Draw hte Alpha plot for the ON data, and on top of it, the normalized Alpha
+//  plot for the OFF data.
+//
+void MHMyFindSignificanceONOFF::Draw(Option_t* option)
+{
+    
+    if(!fHistON || !fHistOFF)
+	return;
+    
+    
+
+    //
+    // If a canvas exists use it, otherwise Creates a new canvas
+    //
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+    
+    //  pad->Divide(2,1);
+
+    AppendPad("");
+
+    pad->cd(1);
+    
+    //
+    // Draw histograms and fit functions
+    //
+    fHistON->SetTitle("");
+    fHistON->SetMarkerStyle(21);
+    fHistON->Draw("p"); 
+
+    fHistOFFNormalized->SetLineColor(2);
+    fHistOFFNormalized->SetMarkerStyle(25);
+    fHistOFFNormalized->SetMarkerColor(2);
+    fHistOFFNormalized->Draw("Psame");
+
+    TList *funclistON = fHistON->GetListOfFunctions();
+    TF1* polyON = (TF1*)funclistON->FindObject("Poly");
+    TF1* gaussON = (TF1*)funclistON->FindObject("PolyGauss");
+    TF1* backgON = (TF1*)funclistON->FindObject("Backg");
+
+    if(gaussON)
+    {
+	gaussON->SetLineColor(4);
+	gaussON->SetLineWidth(4);
+    }
+    if(backgON)
+	funclistON->Remove(backgON);
+    if(polyON)
+    {
+	polyON->SetLineStyle(2);
+	polyON->SetLineColor(2);
+	polyON->SetLineWidth(2);
+    } 
+
+   
+    //
+    // Draw results onto the figure
+    //
+    DrawResults(option);
+
+
+    gPad->Modified();
+    gPad->Update();
+
+
+
+
+ //     //
+//      // Draw the difference of ON-OFF
+//      //
+//      pad->cd(2);
+//      TH1D* h = (TH1D*)fHistON->Clone();
+//      h->GetListOfFunctions()->Clear();
+//      h->SetTitle("Alpha Plot ON-OFF");
+//      h->Add(fHistOFFNormalized,-1.);
+//      h->SetFillColor(17);
+//      h->Draw("hist");
+
+//      TLine* line = new TLine(0, 0, 90, 0);
+//      line->Draw();
+
+//      DrawResults("short");
+
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Draw the results on top the histograms pad
+//
+void MHMyFindSignificanceONOFF::DrawResults(Option_t* option)
+{
+
+    TString opt(option);
+
+    TPaveText *pt;
+    char tx[100];
+
+
+    if(opt.Contains("short",TString::kIgnoreCase))
+    {
+	pt= new TPaveText(0.24, 0.59, 0.86, 0.87, "NDC");
+	
+
+	//  sprintf(tx, "   Nbg measured (Normalized)  = %8.1f #pm %8.1f", 
+//   		 fNbg * fNormFactor,  fdNbg * fNormFactor);
+//   	pt->AddText(tx);
+	
+//   	sprintf(tx, "   Nex (ON - OFF measured) = %8.1f #pm %8.1f",fNex,fdNex);
+//   	pt->AddText(tx);
+
+//  	Double_t ratio = fNbg>0.0 ? fNex/(fNbg*fNormFactor) : 0.0;
+//   	sprintf(tx, "   Significance = %6.2f,    Nex/(Nbg*NormFactor) = %6.2f",  		fSigLiMa, ratio);
+//   	pt->AddText(tx);
+	//  sprintf(tx, "  Measured OFF background:");
+//  	TText *t7 = pt->AddText(tx);
+//  	t7->SetTextSize(0.02);
+//  	t7->SetTextColor(8);
+	
+//  	sprintf(tx, "Results for |alpha|< %6.2f [\\circ] using fit to OFF:",
+//  		fFindsigON.GetAlphasi());
+//  	TText *t6 = pt->AddText(tx);
+//  	t6->SetTextSize(0.03);
+//  	t6->SetTextColor(8);
+
+	//  sprintf(tx, "Noff = %6.1f", fNoff);
+//  	pt->AddText(tx);
+
+//  	sprintf(tx, "Nbg = %8.1f", 
+//  		fNbgFit*fNormFactor);
+//  	pt->AddText(tx);
+	
+//  	sprintf(tx, "Nex = %8.1f", fNexFit);
+//  	pt->AddText(tx);
+
+	
+	sprintf(tx, "T_{obs} = 64 min.");
+	pt->AddText(tx);
+
+	sprintf(tx, "Zenith Angle = 7-17 #circ");
+	pt->AddText(tx);
+	
+	sprintf(tx, "Significance = %6.2f #sigma", fSigLiMaFit);
+	TText *t8 =pt->AddText(tx);
+	//t8->SetTextSize(0.1);
+	t8->SetTextColor(8);
+    }
+
+    else if(opt.Contains("all",TString::kIgnoreCase))
+    {
+	pt = new TPaveText(0.20, 0.33, 0.88, 0.90, "NDC");
+	
+	//
+	// Fit to OFF data
+	//
+	sprintf(tx, "Results of polynomial fit to OFF (order %2d) :", fDegree);
+	TText *t1 = pt->AddText(tx);
+	t1->SetTextSize(0.03);
+	t1->SetTextColor(2);
+	
+	sprintf(tx, "   (%6.2f< |alpha| <%6.2f [\\circ])", fAlphaminOFF, 
+		fAlphamaxOFF);
+	pt->AddText(tx);
+	
+	sprintf(tx, "   chi2 = %8.2f,  Ndof = %4d,  Prob = %6.2f", 
+     	  fFindsigOFF.GetChisq(), fFindsigOFF.GetNdf(), fFindsigOFF.GetProb());
+	pt->AddText(tx);
+	
+	sprintf(tx, "   Nbgtot(fit)= %8.1f #pm %8.1f", 
+	        fFindsigOFF.GetNbgtotFitted(), fFindsigOFF.GetdNbgtotFitted());
+	pt->AddText(tx);
+	
+	sprintf(tx, "   Nbgtot(meas) = %8.1f", fFindsigOFF.GetNbgtot());
+	pt->AddText(tx);
+	
+	
+	//
+	// Results 
+	//
+	sprintf(tx, "Results for |alpha|< %6.2f [\\circ] :",
+		fFindsigON.GetAlphasi());
+	TText *t6 = pt->AddText(tx);
+	t6->SetTextSize(0.03);
+	t6->SetTextColor(8);
+	
+	sprintf(tx, "   Non = %8.1f #pm %8.1f", fNon, fdNon);
+	pt->AddText(tx);
+	
+	
+	//  PRINT INFORMATION ABOUT MEASURED QUANTITIES  
+	sprintf(tx, "  Measured OFF background:");
+	TText *t7 = pt->AddText(tx);
+	t7->SetTextSize(0.02);
+	t7->SetTextColor(8);
+	
+	sprintf(tx, "   Nbg(meas)*NormFactor  = %8.1f #pm %8.1f", 
+ 		 fNbg*fNormFactor, fdNbg*fNormFactor);
+ 	pt->AddText(tx);
+	
+ 	sprintf(tx, "   Nex (meas) = %8.1f #pm %8.1f", fNex, fdNex);
+ 	pt->AddText(tx);
+
+	sprintf(tx,"   Normalization Factor (= Non/Noff) = %4.4f",fNormFactor);
+	pt->AddText(tx);
+
+	Double_t ratio = fNbg>0.0 ? fNex/(fNbg*fNormFactor) : 0.0;
+ 	sprintf(tx, "   Significance(mea) = %6.2f,    Nex/(Nbg*NormFactor) = %6.2f", fSigLiMa, ratio);
+ 	pt->AddText(tx);
+	
+
+	// PRINT INFORMATION ABOUT FITTED QUANTITIES 
+	sprintf(tx, "  Fitted OFF background:");
+	TText *t8 = pt->AddText(tx);
+	t8->SetTextSize(0.02);
+	t8->SetTextColor(8);
+	
+	sprintf(tx, "   Nbg(fit)*NormFactor  = %8.1f #pm %8.1f", 
+		fNbgFit*fNormFactor, fdNbgFit*fNormFactor);
+	pt->AddText(tx);
+	
+	sprintf(tx, "   Nex(fit) = %8.1f #pm %8.1f", fNexFit, fdNexFit);
+	pt->AddText(tx);
+	
+	sprintf(tx, "   Effective Noff (i.e. fNoff) = %6.1f,   Gamma = %4.4f", 
+		 fNoff, fGamma);
+	pt->AddText(tx);
+	
+	ratio = fNbgFit>0.0 ? fNexFit/(fNbgFit*fNormFactor):0.0;
+	sprintf(tx, "   Significance(fit) = %6.2f,    Nex/(Nbg*NormFactor) = %6.2f", fSigLiMaFit, ratio);
+	pt->AddText(tx);
+	
+
+	//
+	// Fit to ON data (polynomial+Gaus)
+	//
+	sprintf(tx, "Results of (polynomial+Gauss) fit to ON:");
+	TText *t9 = pt->AddText(tx);
+ 	t9->SetTextSize(0.03);
+ 	t9->SetTextColor(4);
+	
+	//sprintf(tx, "   chi2 = %8.2f,  Ndof = %4d,  Prob = %6.2f", 
+	//fGChisq, fGNdf, fGProb);
+	//pt->AddText(tx);
+	
+ 	sprintf(tx, "   Sigma of Gauss = %8.1f #pm %8.1f  [\\circ]", 
+ 		 fFindsigON.GetSigmaGauss(), fFindsigON.GetdSigmaGauss());
+ 	pt->AddText(tx);
+	
+       	sprintf(tx, "   total no.of excess events = %8.1f #pm %8.1f", 
+	      	fFindsigON.GetNexGauss(), fFindsigON.GetdNexGauss());
+ 	pt->AddText(tx);
+    }    
+    else 
+	return;
+
+	
+    pt->SetFillStyle(0);
+    pt->SetBorderSize(0);
+    pt->SetTextAlign(12);
+    
+    pt->Draw();
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Set flag fRebin 
+//
+void MHMyFindSignificanceONOFF::SetRebin(Bool_t b)
+{
+  fRebin = b;
+
+  *fLog << "MHMyFindSignificanceONOFF::SetRebin; flag fRebin set to " 
+        << (b? "kTRUE" : "kFALSE") << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set flag fReduceDegree 
+//
+void MHMyFindSignificanceONOFF::SetReduceDegree(Bool_t b)
+{
+  fReduceDegree = b;
+
+  *fLog << "MHMyFindSignificanceONOFF::SetReduceDegree; flag fReduceDegree set to " 
+        << (b? "kTRUE" : "kFALSE") << endl;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Given an histogram, count the number of events within a given range. 
+//  Is equivaltent to TH1::Integral(binlo,binhi) but making sure that the bins
+//  are fully contain in the interval (within a given tolerance).
+//
+Int_t MHMyFindSignificanceONOFF::CountEventsInRange(TH1* hist, Double_t alphalo, Double_t alphaup, Double_t* numevents, Double_t* numeventserror)
+{    
+  
+    const Int_t nbins =  hist->GetNbinsX();
+    const Double_t binwidth = hist->GetBinWidth(1);
+
+    Double_t nevt = 0;
+    Double_t nevtErr = 0; 
+
+    //
+    // Loop over all the bins
+    // 
+    for(Int_t i=1; i<=nbins; i++)
+    {
+	Double_t xlo = hist->GetBinLowEdge(i);
+	Double_t xup = hist->GetBinLowEdge(i+1);
+
+	// bin must be completely contained in the signal region
+	if( xlo >= (alphalo-fEps) && xup <= (alphaup+fEps))
+	{
+	    // check all bins all of same width
+	    const Double_t width = fabs(xup-xlo);
+	    if (fabs(width-binwidth) > fEps)
+	    {
+		*fLog << err << GetName() << " alpha plot has variable binning, which is not allowed...exit."  << endl;
+		return kFALSE;
+	    }
+
+
+	    nevt += hist->GetBinContent(i);
+	    nevtErr += hist->GetBinError(i) * hist->GetBinError(i);
+	}
+    }
+
+    nevtErr = TMath::Sqrt(nevtErr);
+    
+
+    // Return results
+    *numevents = nevt;
+    *numeventserror = nevtErr;
+}
+
+
+// ---------------------------------------------------------------------------
+//
+//  Counts the number of events in the Bkg region in the ON_Data and OFF-Data 
+//  histograms. Then compute the normalization factor as:
+//    NormFactor = NoffON / NoffNOFF
+//
+Int_t MHMyFindSignificanceONOFF::CalcNormalizationFactor(TH1* hon, TH1* hoff, Double_t alphalo, Double_t alphaup)
+{
+    Double_t nevton = 0;
+    Double_t nevtoff = 0;
+    Double_t dnevton = 0;
+    Double_t dnevtoff = 0;
+  
+    // counts events in the region (alphalo,alphaup) for the ON-Data hist
+    CountEventsInRange(hon, alphalo, alphaup,&nevton,&dnevton);
+
+    // counts events in the region (alphalo,alphaup) for the OFF-Data hist
+    CountEventsInRange(hoff, alphalo, alphaup,&nevtoff,&dnevtoff);
+
+
+    // Normalization factor and its error
+    fNormFactor = nevton/nevtoff;
+    
+    fNormFactorError = 1./nevton + 1./nevtoff;
+    fNormFactorError = TMath::Sqrt(fNormFactorError);
+    fNormFactorError *= fNormFactor; // <--------------
+
+
+    *fLog << "non = " << nevton << " noff = " << nevtoff << endl;
+    *fLog << "Normalization factor = " << fNormFactor << " +- " 
+	  << fNormFactorError << endl;
+
+    return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  SigmaLiMa
+//
+//  calculates the significance according to Li & Ma
+//  ApJ 272 (1983) 317
+//
+Bool_t MHMyFindSignificanceONOFF::SigmaLiMa(Double_t non,   Double_t noff, 
+                                     Double_t gamma, Double_t *siglima)
+{
+  if (gamma <= 0.0  ||  non <= 0.0  ||  noff <= 0.0)
+  {
+    *siglima = 0.0;
+    return kFALSE;
+  }
+
+  Double_t help1 = non  * log( (1.0+gamma)*non  / (gamma*(non+noff)) );
+  Double_t help2 = noff * log( (1.0+gamma)*noff / (       non+noff ) );
+  *siglima = sqrt( 2.0 * (help1+help2) );
+
+  Double_t nex = non - gamma*noff;
+  if (nex < 0.0)
+    *siglima = - *siglima;
+
+  //*fLog << "MHMyFindSignificanceONOFF::SigmaLiMa; non, noff, gamma, *siglima = "
+  //      << non << ",  " << noff << ",  " << gamma << ",  " << *siglima << endl;
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  Sigma Vs Alpha
+//
+//
+Bool_t MHMyFindSignificanceONOFF::SigmaVsAlpha(TH1 *histON, TH1 *histOFF,  Double_t alphamin, Double_t alphamax, Int_t degree, Bool_t draw)
+{
+
+
+    //--------------------------------------------
+    // Create histogram
+    
+    //Int_t    nsteps    =  15;
+    Int_t    nsteps    = histON->FindBin(40); 
+  
+    TH1D* fSigVsAlpha = new TH1D("SigVsAlpha","Sigma vs Alpha", nsteps, 0.0, 30);
+     MH::SetBinning(fSigVsAlpha, histON->GetXaxis());
+     fSigVsAlpha->SetXTitle("upper edge of signal region in |alpha|  [\\circ]");
+    fSigVsAlpha->SetYTitle("Significance of gamma signal");
+
+
+    TGraph* grSigVsAlpha = new TGraph;
+    TGraph* grNexVsAlpha = new TGraph;
+ 
+  
+
+
+    //--------------------------------------------
+    // loop over different signal regions
+    for (Int_t i=1; i<=nsteps; i++)
+    {
+	//Double_t alphasig = fSigVsAlpha->GetBinCenter(i);
+	//Double_t alphasig = fSigVsAlpha->GetBinLowEdge(i+1);
+	Double_t alphasig = histON->GetBinLowEdge(i+1);
+
+	
+	gLog.SetNullOutput(1);
+	//FindSigmaONOFF(histON, histOFF, alphasig, alphamin, alphamax, degree);
+	 MHMyFindSignificanceONOFF findsig;
+	 findsig.SetRebin(fRebin);
+	 findsig.SetReduceDegree(fReduceDegree);
+  
+	 findsig.FindSigmaONOFF( histON, histOFF, alphasig, alphamin, alphamax, degree);
+	 const Double_t sig = findsig.GetSigLiMa();
+	 const Double_t Nex = findsig.GetNex();
+
+	 fSigVsAlpha->SetBinContent(i, sig);
+
+	 if( sig>fBestSigma )
+	 {
+	     fBestSigma = sig;
+	     fBestAlphaCut = alphasig;
+	     fBestExcess = Nex;
+	 }
+
+	 grSigVsAlpha->SetPoint(i-1,alphasig,sig);
+	 grNexVsAlpha->SetPoint(i-1,alphasig,Nex);
+
+	 cout << "****************** " << i<< " " << alphasig << " " << sig<< " " << Nex << "*************"<<  endl;
+	 gLog.SetNullOutput(0);
+    }
+
+
+// fSigVsAlpha->DrawCopy();
+
+
+    if (!draw)
+	return kTRUE;
+
+    // -----------------------------------------------------------------
+    //
+    // Draw
+    // 
+    TCanvas *c = new TCanvas("SigVsAlpha", "Sigma vs Alpha", 600, 600);
+    c->SetGridx();
+    c->SetGridy();
+    
+    Double_t margin = 0.12; // give more space for drawing the axis titles
+    c->SetLeftMargin(margin);
+    c->SetRightMargin(margin);
+
+
+    //
+    // Draw Sig Vs Alpha
+    //
+    grSigVsAlpha->SetMarkerStyle(8);
+    //grSigVsAlpha->SetMarkerColor(2);
+    //grSigVsAlpha->SetLineColor(2);
+    grSigVsAlpha->Draw("apl");
+    grSigVsAlpha->GetHistogram()->SetXTitle("Alpha Cut [\\circ]");
+    grSigVsAlpha->GetHistogram()->SetYTitle("Significance");
+    grSigVsAlpha->GetHistogram()->GetYaxis()->SetTitleOffset(1.3);
+
+
+    //
+    // Draw second graph on a transparent pad
+    //
+    TPad *overlay = new TPad("overlay","",0,0,1,1);
+    overlay->SetFillStyle(4000);
+    overlay->SetFillColor(0);
+    overlay->SetFrameFillStyle(4000);
+    overlay->SetLeftMargin(margin);
+    overlay->SetRightMargin(margin);  
+    overlay->Draw();
+    overlay->cd();
+  
+    grNexVsAlpha->SetMarkerStyle(8);
+    grNexVsAlpha->SetMarkerColor(kRed);
+    grNexVsAlpha->SetLineColor(kRed);
+    grNexVsAlpha->Draw("apl"); 
+
+    // Trick to not draw the graph Y-Axis
+    grNexVsAlpha->GetHistogram()->GetYaxis()->SetNdivisions(0);
+    
+     
+    //
+    // Draw an axis on the right side
+    //
+    c->Update(); //<-- Imprescindible for updating the gPad coordinates
+
+    TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),
+			    gPad->GetUxmax(), gPad->GetUymax(),  
+			    gPad->GetUymin(),gPad->GetUymax() ,510,"+L");
+    axis->SetTitle("Excess events");
+    axis->SetTitleOffset(1.3);
+    //axis->SetLineColor(kRed);
+    axis->SetLabelColor(kRed);
+    axis->SetTextColor(kRed);
+    axis->Draw();
+   
+
+    c->Modified();
+    c->Update();
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MHMyFindSignificanceONOFF.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MHMyFindSignificanceONOFF.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MHMyFindSignificanceONOFF.h	(revision 9772)
@@ -0,0 +1,138 @@
+#ifndef MARS_MHMyFindSignificanceONOFF
+#define MARS_MHMyFindSignificanceONOFF
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef MARS_MHFindSignificance
+#include "MHFindSignificance.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TF1;
+class TH1;
+class TCanvas;
+
+class MHMyFindSignificanceONOFF : public MH
+{
+ private:
+    
+    TH1  *fHistOrigON;  // original plot of |alpha| (0.0 to 90.0 degrees)
+    TH1  *fHistON;      // copy of fHistOrig or rebinned histogram
+    TH1  *fHistOrigOFF;  // original plot of |alpha| (0.0 to 90.0 degrees)
+    TH1  *fHistOFF;      // copy of fHistOrig or rebinned histogram
+    TH1  *fHistOFFNormalized;   //  fHistOFF normalized (contents and errors) with 
+            
+    MHFindSignificance fFindsigON; // Will contain the fit of the on data 
+    MHFindSignificance fFindsigOFF;
+    
+
+    Double_t fAlphasig;
+    Double_t fAlphaminON;
+    Double_t fAlphamaxON;
+    Double_t fAlphaminOFF;
+    Double_t fAlphamaxOFF;
+    Int_t fDegree;
+    
+    Double_t fNormFactor;  // Normalization factor between ON and OFF hists.
+    Double_t fNormFactorError;
+
+    // Couted quatities
+    Double_t fNon; 
+    Double_t fdNon;
+    Double_t fNbg;        // Counts in the signal region of OFF hist, NO normalized !!!
+    Double_t fdNbg;
+    Double_t fNex;
+    Double_t fdNex;
+    Double_t fSigLiMa; // significance of gamma signal according to Li & Ma
+
+    // from the polynomial fit of the OFF data
+    Double_t fNbgFit;
+    Double_t fdNbgFit;
+    Double_t fNexFit;
+    Double_t fdNexFit;
+    Double_t fGamma;
+    Double_t fNoff;
+    Double_t fSigLiMaFit; // significance of gamma signal according to Li & Ma
+
+    Bool_t fRebin;         // if true : allow rebinning of the alpha plot    
+    Bool_t fReduceDegree;  // if true : allow reducing of the order of the polynomial
+
+    const static Double_t fEps = 1.e-4;  // tolerance for floating point 
+                                         // comparisons
+
+
+    Double_t fBestSigma;
+    Double_t fBestAlphaCut;
+    Double_t fBestExcess;
+
+    void NormalizedHistOFF();
+    void DrawResults(Option_t* option="all");
+
+public:
+
+    MHMyFindSignificanceONOFF(const char *name=NULL, const char *title=NULL);
+   
+     Bool_t FindSigmaONOFF(TH1 *histON, TH1 *histOFF, Double_t alphasig, Double_t alphamin, Double_t alphamax, Int_t degree);
+
+     Int_t CountEventsInRange(TH1* hist, Double_t alphalo, Double_t alphaup, Double_t* numevents, Double_t* numeventserror);
+
+    Int_t CalcNormalizationFactor(TH1* hon, TH1* hoff, Double_t alphalo, Double_t alphaup);
+    
+    Bool_t SigmaLiMa(Double_t non, Double_t noff, Double_t gamma,
+                     Double_t *siglima);
+
+
+    Double_t GetNormFactor() const { return fNormFactor; }
+    Double_t GetNon()        const { return fNon;             }
+    Double_t GetNbg()        const { return fNbg*fNormFactor; } // <------!!!
+    Double_t GetNex()        const { return fNex;             } 
+    Double_t GetdNex()        const { return fdNex;             } 
+
+    Double_t GetSigLiMa()    const { return fSigLiMa;            }
+    Double_t GetNbgFit()     const { return fNbgFit*fNormFactor; } //<------!!!
+    Double_t GetNexFit()     const { return fNexFit;             } 
+    Double_t GetSigLiMaFit() const { return fSigLiMaFit;         }
+   
+       
+    void SetRebin(Bool_t b=kTRUE);
+    void SetReduceDegree(Bool_t b=kTRUE);
+
+
+    void Draw(Option_t* option="all");
+    
+    Bool_t SigmaVsAlpha(TH1 *histON, TH1 *histOFF,  Double_t alphamin, Double_t alphamax, Int_t degree, Bool_t draw=kTRUE);
+
+
+
+     Double_t GetBestSigma() const {return fBestSigma;}
+     Double_t GetBestAlphaCut() const {return fBestAlphaCut;}
+     Double_t GetBestExcess() const {return fBestExcess;}
+
+    ClassDef(MHMyFindSignificanceONOFF, 1) // Determine significance from ON and OFF data
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MMyFindSuperCuts.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MMyFindSuperCuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MMyFindSuperCuts.cc	(revision 9772)
@@ -0,0 +1,1475 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 6/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Wolfgang Wittek, 7/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Marcos Lopez, 05/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MMyFindSuperCuts                                                       //
+//                                                                         //
+// Class for otimizing the parameters of the supercuts                     //
+//                                                                         //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MMyFindSuperCuts.h"
+
+#include <math.h>            // fabs 
+
+#include <TFile.h>
+#include <TArrayD.h>
+#include <TMinuit.h>
+#include <TCanvas.h>
+#include <TStopwatch.h>
+#include <TVirtualFitter.h>
+
+#include "MBinning.h"
+#include "MContinue.h"
+#include "MMySuperCuts.h"
+#include "MMySuperCutsCalc.h"
+#include "MDataElement.h"
+#include "MDataMember.h"
+
+#include "MEvtLoop.h"
+#include "MFSelFinal.h"
+#include "MF.h"
+#include "MFEventSelector.h"
+#include "MFEventSelector2.h"
+#include "MFillH.h"
+//#include "MGeomCamCT1Daniel.h"
+#include "MFEventSelector.h"
+#include "MGeomCamMagic.h"
+#include "MH3.h"
+#include "MHSupercuts.h"
+#include "MHFindSignificance.h"
+#include "MHMatrix.h"
+#include "MHOnSubtraction.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MMatrixLoop.h"
+#include "MMinuitInterface.h"
+#include "MParList.h"
+#include "MProgressBar.h"
+#include "MReadMarsFile.h"
+#include "MReadTree.h"
+#include "MTaskList.h"
+
+#include "TVector2.h"
+#include "MSrcPosCam.h"
+#include "MHillasSrcCalc.h"
+#include "MSrcPosCalc.h"
+#include "MObservatory.h"
+
+ClassImp(MMyFindSuperCuts);
+
+using namespace std;
+
+
+//------------------------------------------------------------------------
+//
+// fcnSupercuts 
+//
+// - calculates the quantity to be minimized (using TMinuit)
+//
+// - the quantity to be minimized is (-1)*significance of the gamma signal
+//   in the alpha distribution (after cuts)
+//
+// - the parameters to be varied in the minimization are the cut parameters
+//   (par)
+//
+// -------------------------
+//   - Read the Matrix
+//   - Fill a histogram with the alpha (6th column)
+//   - Fit the alpha plot
+//   - Get result of fit (significance)
+//
+static void fcnSuperCuts(Int_t &npar, Double_t *gin, Double_t &f, 
+                         Double_t *par, Int_t iflag)
+{
+
+    //
+    // Set by hand the paramters range
+    //
+    if ( par[0]<0 || par[0]>1.8 || par[4]>par[0] || par[4]<0 || par[0]<par[4] ||
+	 par[2]>1 || par[3]>1 ||  par[4]>1 || par[1]>1   || par[6]>1 || par[7]>1   ||
+	 par[8]<0 || par[8]>1.8 || par[12]>par[0] || par[12]<0 || par[8]<par[12] ||
+	 par[13]<0 || par[13]>1. || par[14]<0 || par[14]>1 || par[15]<0 || par[15]>1 || 
+	 par[16]<0 || par[16]>1.8 || par[20]<0 || par[20]>1.8 || par[16]<par[20] ||
+	 // par[4]>0.18 ||
+	 par[24]>200 || par[28]<-200 || 
+	 par[32]>1 || par[36]<0 || 
+  	 par[40]>1
+	 )
+    {
+	gLog << "Parameter out of limit"  << endl;
+	f=1e10;
+	cout << f << endl;
+	return;
+    }
+
+    //-------------------------------------------------------------
+    // save pointer to the MINUIT object for optimizing the supercuts
+    // because it will be overwritten 
+    // when fitting the alpha distribution in MHFindSignificance
+    TMinuit *savePointer = gMinuit;
+    //-------------------------------------------------------------
+
+
+    MEvtLoop *evtloopfcn = (MEvtLoop*)gMinuit->GetObjectFit();
+
+    MParList *plistfcn   = (MParList*)evtloopfcn->GetParList();
+  
+    MMySuperCuts *super = (MMySuperCuts*)plistfcn->FindObject("MMySuperCuts");
+    if (!super)
+    {
+        gLog << "fcnSupercuts : MMySuperCuts object '" << "MMySuperCuts"
+            << "' not found... aborting" << endl;
+        return;
+    }
+
+    //
+    // transfer current parameter values to MMySuperCuts
+    //
+    // Attention : npar is the number of variable parameters
+    //                  not the total number of parameters
+    //
+    Double_t fMin, fEdm, fErrdef;
+    Int_t     fNpari, fNparx, fIstat;
+    gMinuit->mnstat(fMin, fEdm, fErrdef, fNpari, fNparx, fIstat);
+
+    super->SetParameters(TArrayD(fNparx, par));
+
+    
+    //$$$$$$$$$$$$$$$$$$$$$
+    // for testing
+    gLog.Separator("Current params");
+      TArrayD checkparameters = super->GetParameters();
+      gLog << "fcnsupercuts : fNpari, fNparx =" << fNpari << ",  " 
+           << fNparx  << endl;
+    //  gLog << "fcnsupercuts : i, par, checkparameters =" << endl;
+  //   for (Int_t i=0; i<fNparx; i++)
+//     {
+//       gLog << i << ",  " << par[i] << ",  " << checkparameters[i] << endl;
+//     }
+  super->Print();
+    
+    //$$$$$$$$$$$$$$$$$$$$$
+
+
+    //
+    // EventLoop: Fill the alpha plot with these cuts
+    //
+    gLog.SetNullOutput(kTRUE);
+    evtloopfcn->Eventloop();
+
+    //tasklistfcn->PrintStatistics(0, kTRUE);
+
+
+
+    //
+    // Calculate significance
+    //
+    MH3* alpha = (MH3*)plistfcn->FindObject("AlphaFcn", "MH3");
+    if (!alpha)
+        return;
+
+    TH1 &alphaHist = alpha->GetHist();
+    alphaHist.SetName("alpha-fcnSupercuts");
+
+    //-------------------------------------------
+    // set Minuit pointer to zero in order not to destroy the TMinuit
+    // object for optimizing the supercuts
+    gMinuit = NULL;
+
+
+    //=================================================================
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+    //
+    const Double_t alphasig = 10.0;
+    const Double_t alphamin = 30.0;
+    const Double_t alphamax = 90.0;
+    const Int_t    degree   =    0;
+
+    Bool_t drawpoly;
+    Bool_t fitgauss;
+    TCanvas* c; 
+    if (iflag == 3)
+    {
+	c= new TCanvas();
+        drawpoly  = kTRUE;
+        fitgauss  = kTRUE;
+    }
+    else
+    {
+        drawpoly  = kFALSE;
+        fitgauss  = kFALSE;
+    }
+    fitgauss  = kTRUE;
+    const Bool_t print = kFALSE;
+
+    MHFindSignificance findsig;
+    //findsig.SetRebin(kTRUE);
+    findsig.SetRebin(kFALSE);
+    findsig.SetReduceDegree(kFALSE);
+    
+
+
+    const Bool_t rc = findsig.FindSigma(&alphaHist, alphamin, alphamax, degree,
+                                        alphasig, drawpoly, fitgauss, print);
+    gLog.SetNullOutput(kFALSE);
+
+    //=================================================================
+
+    // reset gMinuit to the MINUIT object for optimizing the supercuts 
+    gMinuit = savePointer;
+    //-------------------------------------------
+
+    if (!rc)
+    {
+        gLog << "fcnSupercuts : FindSigma() failed" << endl;
+        f = 1.e10;
+        return;
+    }
+
+    // plot some quantities during the optimization
+    MHSupercuts *plotsuper = (MHSupercuts*)plistfcn->FindObject("MHSupercuts");
+    if (plotsuper)
+        plotsuper->Fill(&findsig);
+
+
+    //
+    // Print info
+    //
+    gLog << "(Non, Nbg, Nex, S/N, sigma, Significane) = " 
+	 << findsig.GetNon() << " " 
+	 << findsig.GetNbg()<< " "
+	 << findsig.GetNex() << " "
+	 << findsig.GetNex()/  findsig.GetNbg()<< " "
+	 << findsig.GetSigmaGauss() << " " 
+	 << findsig.GetSignificance() << endl;
+
+    const Double_t sigmagauss = findsig.GetSigmaGauss();
+   //   if (sigmagauss>10)
+//        {
+//          gLog << "fcnSupercuts : Alpha plot too width = " << sigmagauss << endl;
+//           f = 1.e10;
+//         return;
+//      }
+
+
+    //
+    // Get significance
+    //
+    const Double_t significance = findsig.GetSignificance();
+    //const Double_t ratio = findsig.GetNex()/findsig.GetNbg();
+
+  //      f = significance>0 ? -significance : 0;
+//     f = -TMath::Abs(significance)/sqrt(sigmagauss);
+//     f = - significance*sqrt(findsig.GetNex())/sqrt(sigmagauss); 
+    f = - significance*significance/sqrt(sigmagauss);
+
+ // f = - significance*findsig.GetProb();
+   cout << f << endl; 
+
+//      //
+//      // optimize signal/background ratio
+//      Double_t ratio = findsig.GetNbg()>0.0 ? 
+//  	findsig.GetNex()/findsig.GetNbg() : 0.0; 
+
+//      //f = -ratio; 
+//       if(significance < 5) 
+//    	f=1e10;
+
+//      f=f*ratio*ratio;
+//      cout << f << " " << significance << " " << ratio  << endl; 
+
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MMyFindSuperCuts::MMyFindSuperCuts(const char *name, const char *title)
+    : fHowManyTrain(10000), fHowManyTest(10000), fMatrixFilter(NULL),fSizeCutLow(2000.0),fSizeCutUp(10000000), fOptimizationMode(0)
+{
+    fName  = name  ? name  : "MMyFindSuperCuts";
+    fTitle = title ? title : "Optimizer of the supercuts";
+
+    //---------------------------
+    // camera geometry is needed for conversion mm ==> degree
+    //fCam = new MGeomCamCT1Daniel; 
+    fCam = new MGeomCamMagic; 
+
+    // matrices to contain the training/test samples
+    fMatrixTrain = new MHMatrix("MatrixTrain");
+    fMatrixTest  = new MHMatrix("MatrixTest");
+
+    // objects of MMySuperCutsCalc to which these matrices are attached
+    fCalcHadTrain = new MMySuperCutsCalc("SupercutsCalcTrain"); 
+    fCalcHadTest  = new MMySuperCutsCalc("SupercutsCalcTest");
+
+
+    // Define columns of matrices
+    *fLog << inf << "Init Mapping of Train Matrix" << endl;
+    fCalcHadTrain->InitMapping(fMatrixTrain); 
+    *fLog << inf << "Init Mapping of Test Matrix" << endl;
+    fCalcHadTest->InitMapping(fMatrixTest);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Default destructor.
+//
+MMyFindSuperCuts::~MMyFindSuperCuts()
+{
+    delete fCam;
+    delete fMatrixTrain;
+    delete fMatrixTest;
+    delete fCalcHadTrain;
+    delete fCalcHadTest;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Define the matrix 'fMatrixTrain' for the training sample
+//
+// alltogether 'howmanytrain' events are read from file 'nametrain';
+// the events are selected according to a target distribution 'hreftrain'
+//
+//
+Bool_t MMyFindSuperCuts::DefineTrainMatrix(
+			 const TString &filenametrain, MH3 &hreftrain,
+	                 const Int_t howmanytrain, const TString &outfiletrain)
+{
+    if (filenametrain.IsNull() || howmanytrain <= 0)
+        return kFALSE;
+
+    *fLog << endl
+	  << "***************************************************************"
+	  << endl
+	  << " Filling training matrix from file: '" << filenametrain << "'" 
+	  << endl 
+          << " Selecting: " << howmanytrain << " events";
+   
+    if (!hreftrain.GetHist().GetEntries()==0)
+    {
+	*fLog << ", according to a distribution given by the MH3 object '"
+	      << hreftrain.GetName() << "'" << endl;
+    }
+    else
+    {
+	*fLog << ", Randomly" << endl;
+    }
+
+    *fLog << "***************************************************************"
+	  << endl;
+
+
+    //
+    // ParList
+    //
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    // entries in MParList 
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+
+
+    //
+    // TaskList
+    //
+    MReadTree read("Events", filenametrain); 
+    //MReadTree read("Parameters", filenametrain);
+    read.DisableAutoScheme();
+
+    //  MFEventSelector2 seltrain(hreftrain);
+//      seltrain.SetNumMax(howmanytrain);
+//      seltrain.SetName("selectTrain");
+
+    // Random selection of events
+    MFEventSelector seltrain; 
+    seltrain.SetNumSelectEvts(howmanytrain);
+    seltrain.SetName("selectTrain");
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetFilter(&seltrain);
+    filltrain.SetName("fillMatrixTrain");
+
+//      // ReCalculate hillass
+//      MObservatory obs;
+//      plist.AddToList(&obs);
+    
+//      MSrcPosCalc srccalc;
+//      srccalc.SetPositionXY(3.46945e-17, 0.0487805);
+//      MHillasSrcCalc hsrc;     
+  
+
+   
+    // entries in MTaskList 
+    tlist.AddToList(&read);
+    tlist.AddToList(&seltrain);
+   //   tlist.AddToList(&srccalc);
+//      tlist.AddToList(&hsrc);
+    tlist.AddToList(&filltrain);
+
+   
+    //
+    // EventLoop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrain");
+    evtloop.SetProgressBar(&bar);
+
+    if (!evtloop.Eventloop())
+        return kFALSE;
+
+  //    if (!evtloop.PreProcess())
+//        return kFALSE;
+
+//      Int_t i=0;
+//      while(tlist.Process())
+//      {
+//  	i++;
+//  	if (i>howmanytrain)
+//  	    break;
+//      }
+
+//      evtloop.PostProcess();
+
+    tlist.PrintStatistics(0, kTRUE);
+
+
+    //
+    // Print
+    //
+    fMatrixTrain->Print("SizeCols");
+    Int_t howmanygenerated = fMatrixTrain->GetM().GetNrows();
+    if (TMath::Abs(howmanygenerated-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MMyFindSuperCuts::DefineTrainMatrix; no.of generated events ("
+	    << howmanygenerated 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    *fLog << "training matrix was filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+
+    //
+    // Write out training matrix
+    //
+    if (outfiletrain != "")
+    {
+      TFile filetr(outfiletrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MMyFindSuperCuts::DefineTrainMatrix; Training matrix was written onto file '"
+            << outfiletrain << "'" << endl;
+    }
+
+    //   fMatrixTrain->Print("data");
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Define the matrix for the test sample
+//
+// alltogether 'howmanytest' events are read from file 'nametest'
+//
+// the events are selected according to a target distribution 'hreftest'
+//
+//
+Bool_t MMyFindSuperCuts::DefineTestMatrix(
+			  const TString &nametest, MH3 &hreftest,
+	                  const Int_t howmanytest, const TString &filetest)
+{
+    if (nametest.IsNull() || howmanytest<=0)
+        return kFALSE;
+
+    *fLog << "=============================================" << endl;
+    *fLog << "fill test matrix from file '" << nametest 
+          << "',   select " << howmanytest 
+          << " events " << endl;
+    if (!hreftest.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << hreftest.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    //
+    // ParList
+    //
+    MParList  plist;
+    MTaskList tlist;
+
+    // entries in MParList    
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTest);
+
+
+    //
+    // TaskList
+    //
+    MReadTree read("Parameters", nametest);
+    read.DisableAutoScheme();
+
+   //   MFEventSelector2 seltest(hreftest);
+//      seltest.SetNumMax(howmanytest);
+//      seltest.SetName("selectTest");
+ 
+    MFillH filltest(fMatrixTest);
+    //filltest.SetFilter(&seltest);
+    
+    // entries in MTaskList 
+    tlist.AddToList(&read);
+    //tlist.AddToList(&seltest);
+    tlist.AddToList(&filltest);
+
+
+    //
+    // EventLoop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTest");
+    evtloop.SetProgressBar(&bar);
+
+  
+    if (!evtloop.PreProcess())
+      return kFALSE;
+
+    Int_t i=0;
+    while(tlist.Process())
+    {
+	i++;
+	if (i>100000)
+	    break;
+    }
+
+    evtloop.PostProcess();
+
+
+//      if (!evtloop.Eventloop())
+//        return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+
+    //
+    // Print
+    //
+    fMatrixTest->Print("SizeCols");
+    const Int_t howmanygenerated = fMatrixTest->GetM().GetNrows();
+    if (TMath::Abs(howmanygenerated-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MMyFindSuperCuts::DefineTestMatrix; no.of generated events ("
+	    << howmanygenerated 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+    *fLog << "test matrix was filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+
+    //
+    // Write out test matrix
+    //
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MMyFindSuperCuts::DefineTestMatrix; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+
+  return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Define the matrices for the training and test sample respectively
+//
+//
+//
+Bool_t MMyFindSuperCuts::DefineTrainTestMatrix(
+			  const TString &name, MH3 &href,
+	                  const Int_t howmanytrain, const Int_t howmanytest,
+                          const TString &filetrain, const TString &filetest)
+{
+    *fLog << "=============================================" << endl;
+    *fLog << "fill training and test matrix from file '" << name 
+          << "',   select "   << howmanytrain 
+          << " training and " << howmanytest << " test events " << endl;
+    if (!href.GetHist().GetEntries()==0)
+    {
+      *fLog << "     according to a distribution given by the MH3 object '"
+            << href.GetName() << "'" << endl;
+    }
+    else
+    {
+      *fLog << "     randomly" << endl;
+    }
+
+
+    //
+    // ParList
+    //
+    MParList  plist;
+    MTaskList tlist;
+
+    // entries in MParList 
+    plist.AddToList(&tlist);
+    plist.AddToList(fCam);
+    plist.AddToList(fMatrixTrain);
+    plist.AddToList(fMatrixTest);
+
+
+
+    //
+    // TaskList
+    //
+    MReadMarsFile read("Events", name);
+    read.DisableAutoScheme();
+
+    MFEventSelector2 selector(href);
+    selector.SetNumMax(howmanytrain+howmanytest);
+    selector.SetName("selectTrainTest");
+    selector.SetInverted();
+
+    MContinue cont(&selector);
+    cont.SetName("ContTrainTest");
+
+    Double_t prob =  ( (Double_t) howmanytrain )
+                   / ( (Double_t)(howmanytrain+howmanytest) );
+    MFEventSelector split;
+    split.SetSelectionRatio(prob);
+
+    MFillH filltrain(fMatrixTrain);
+    filltrain.SetFilter(&split);
+    filltrain.SetName("fillMatrixTrain");
+
+
+    // consider this event as candidate for a test event 
+    // only if event was not accepted as a training event
+
+    MContinue conttrain(&split);
+    conttrain.SetName("ContTrain");
+
+    MFillH filltest(fMatrixTest);
+    filltest.SetName("fillMatrixTest");
+   
+
+    // entries in MTaskList 
+    tlist.AddToList(&read);
+    tlist.AddToList(&cont);
+    tlist.AddToList(&split);
+    tlist.AddToList(&filltrain);
+    tlist.AddToList(&conttrain);
+    tlist.AddToList(&filltest);
+
+    
+    //
+    // EventLoop
+    //
+    MProgressBar bar;
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetName("EvtLoopMatrixTrainTest");
+    evtloop.SetProgressBar(&bar);
+
+    Int_t maxev = -1;
+    if (!evtloop.Eventloop(maxev))
+      return kFALSE;
+
+    tlist.PrintStatistics(0, kTRUE);
+
+    fMatrixTrain->Print("SizeCols");
+    const Int_t generatedtrain = fMatrixTrain->GetM().GetNrows();
+    if (TMath::Abs(generatedtrain-howmanytrain) > TMath::Sqrt(9.*howmanytrain))
+    {
+      *fLog << "MMyFindSuperCuts::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtrain 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytrain << ")" << endl;
+    }
+
+    fMatrixTest->Print("SizeCols");
+    const Int_t generatedtest = fMatrixTest->GetM().GetNrows();
+    if (TMath::Abs(generatedtest-howmanytest) > TMath::Sqrt(9.*howmanytest))
+    {
+      *fLog << "MMyFindSuperCuts::DefineTrainTestMatrix; no.of generated events ("
+	    << generatedtest 
+            << ") is incompatible with the no.of requested events ("
+            << howmanytest << ")" << endl;
+    }
+
+
+    *fLog << "training and test matrix were filled" << endl;
+    *fLog << "=============================================" << endl;
+
+
+
+    //
+    // Write out training matrix
+    //
+    if (filetrain != "")
+    {
+      TFile filetr(filetrain, "RECREATE");
+      fMatrixTrain->Write();
+      filetr.Close();
+
+      *fLog << "MMyFindSuperCuts::DefineTrainTestMatrix; Training matrix was written onto file '"
+            << filetrain << "'" << endl;
+    }
+
+    //
+    // Write out test matrix
+    //
+    if (filetest != "")
+    {
+      TFile filete(filetest, "RECREATE", "");
+      fMatrixTest->Write();
+      filete.Close();
+
+      *fLog << "MMyFindSuperCuts::DefineTrainTestMatrix; Test matrix was written onto file '"
+            << filetest << "'" << endl;
+    }
+
+  return kTRUE;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+//  Read training and test matrices from files
+//
+Bool_t MMyFindSuperCuts::ReadMatrix(const TString &filetrain, const TString &filetest)
+{
+    //
+    // Read in training matrix
+    //
+    TFile filetr(filetrain);
+    fMatrixTrain->Read("MatrixTrain");
+    fMatrixTrain->Print("SizeCols");
+    
+    *fLog << "MMyFindSuperCuts::ReadMatrix; Training matrix was read in from file '" << filetrain << "'" << endl;
+    filetr.Close();
+    
+
+    //
+    // Read in test matrix
+    //
+    TFile filete(filetest);
+    fMatrixTest->Read("MatrixTest");
+    fMatrixTest->Print("SizeCols");
+    
+    *fLog <<"MMyFindSuperCuts::ReadMatrix; Test matrix was read in from file '"
+	  << filetest << "'" << endl;
+    filete.Close();
+    
+
+    return kTRUE;  
+}
+
+
+
+//------------------------------------------------------------------------
+//
+//  Steering program for optimizing the supercuts
+//  ---------------------------------------------
+//
+//      the criterion for the 'optimum' is 
+//
+//          - a maximum significance of the gamma signal in the alpha plot, 
+//            in which the supercuts have been applied
+//
+// The various steps are :
+//
+// - setup the event loop to be executed for each call to fcnSupercuts 
+// - call TMinuit to do the minimization of (-significance) :
+//        the fcnSupercuts function calculates the significance 
+//                                             for the current cut values
+//        for this - the alpha plot is produced in the event loop, 
+//                   in which the cuts have been applied
+//                 - the significance of the gamma signal in the alpha plot 
+//                   is calculated
+//
+// Needed as input : (to be set by the Set functions)
+//
+// - fFilenameParam      name of file to which optimum values of the 
+//                       parameters are written
+//
+// - fHadronnessName     name of container where MMySuperCutsCalc will
+//                       put the supercuts hadronness
+//
+// - for the minimization, the starting values of the parameters are taken  
+//     - from file parSCinit (if it is != "")
+//     - or from the arrays params and/or steps 
+//
+//----------------------------------------------------------------------
+Bool_t MMyFindSuperCuts::FindParams(TString parSCinit,
+                                     TArrayD &params, TArrayD &steps )
+{
+
+    fCalcHadTrain->SetSizeCuts(fSizeCutLow,fSizeCutUp);
+    fCalcHadTest->SetSizeCuts(fSizeCutLow,fSizeCutUp);
+
+
+    // Setup the event loop which will be executed in the 
+    //                 fcnSupercuts function  of MINUIT
+    //
+    // parSCinit is the name of the file containing the initial values 
+    // of the parameters; 
+    // if parSCinit = ""   'params' and 'steps' are taken as initial values
+
+    *fLog << "=============================================" << endl;
+    *fLog << "Setup event loop for fcnSupercuts" << endl;
+
+
+    //
+    // Check that all the necessary containers already exists
+    //
+    if (fHadronnessName.IsNull())
+    {
+      *fLog << "MyFindSuperCuts::FindParams; hadronness name is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrain == NULL)
+    {
+      *fLog << "MMyFindSuperCuts::FindParams; training matrix is not defined... aborting"
+            << endl;
+      return kFALSE;
+    }
+
+    if (fMatrixTrain->GetM().GetNrows() <= 0)
+    {
+      *fLog << "MMyFindSuperCuts::FindParams; training matrix has no entries"
+            << endl;
+      return kFALSE;
+    }
+
+
+
+    //
+    // ParList
+    //
+    MParList  parlistfcn;
+    MTaskList tasklistfcn;
+    parlistfcn.AddToList(&tasklistfcn);
+    
+    
+   
+    //
+    // create container for the supercut parameters
+    // and set them to their initial values
+    //
+    MMySuperCuts super;
+
+    // take initial values from file parSCinit
+    if (parSCinit != "")
+    {
+	TFile inparam(parSCinit);
+	super.Read("MMySuperCuts");
+	inparam.Close();
+	*fLog << "MMyFindSuperCuts::FindParams; initial values of parameters are taken from file " << parSCinit << endl;
+	super.Print();
+    }
+
+    // take initial values from 'params' and/or 'steps'
+    //else if (params.GetSize() != 0  || steps.GetSize()  != 0 )
+    if (params.GetSize() != 0  || steps.GetSize()  != 0 )
+    {
+      if (params.GetSize()  != 0)
+      {
+        *fLog << "MMyFindSuperCuts::FindParams; initial values of parameters are taken from 'params'" << endl;
+        super.SetParameters(params);
+      }
+      if (steps.GetSize()  != 0)
+      {
+        *fLog << "MMyFindSuperCuts::FindParams; initial step sizes are taken from 'steps'"
+              << endl;
+        super.SetStepsizes(steps);
+      }
+    }
+    else
+    {
+        *fLog << "MMyFindSuperCuts::FindParams; initial values and step sizes are taken from the MMySuperCuts constructor"
+              << endl;
+    }
+ 
+
+    // Alpha binning
+    const TString  mh3Name = "AlphaFcn";
+    MBinning binsalpha("Binning"+mh3Name);
+    //    binsalpha.SetEdges(54, -12.0, 96.0);
+    binsalpha.SetEdges(45, 0.0, 90.0);
+
+    // Alpha plot |alpha|
+    MH3 alpha("MatrixTrain[6]");  // |alpha| assumed to be in column 6
+        alpha.SetName(mh3Name);
+
+    *fLog << warn << "WARNING----->ALPHA IS ASSUMED TO BE IN COLUMN 6!!!!!!!!"
+	  << endl;
+
+
+    // book histograms to be filled during the optimization
+    //                              ! not in the event loop !
+    MHSupercuts plotsuper;
+    plotsuper.SetupFill(&parlistfcn);
+
+   
+    // Add to ParList
+    parlistfcn.AddToList(&super);
+    parlistfcn.AddToList(fCam);
+    parlistfcn.AddToList(fMatrixTrain);
+    parlistfcn.AddToList(&binsalpha);
+    parlistfcn.AddToList(&alpha);
+    parlistfcn.AddToList(&plotsuper);
+
+
+
+    //
+    // MTaskList
+    //
+    MMatrixLoop loop(fMatrixTrain); // loop over rows of matrix
+
+    // calculate supercuts hadronness
+    //fCalcHadTrain->SetHadronnessName(fHadronnessName);
+
+    // apply the supercuts
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue supercuts(&scfilter);
+
+    // Fill Alpha Plot
+    MFillH fillalpha(&alpha);
+
+   
+    // Add to TaskList
+    tasklistfcn.AddToList(&loop);
+    tasklistfcn.AddToList(fCalcHadTrain);
+    tasklistfcn.AddToList(&supercuts);
+    tasklistfcn.AddToList(&fillalpha);
+
+
+   
+    // 
+    // EventLoop
+    // 
+    MEvtLoop evtloopfcn("EvtLoopFCN");
+    evtloopfcn.SetParList(&parlistfcn);
+    *fLog << "Event loop for fcnSupercuts has been setup" << endl;
+
+  
+
+
+    //-----------------------------------------------------------------------
+    //
+    //----------   Start of minimization part   --------------------
+    //
+    // Do the minimization with MINUIT
+    //
+    // Be careful: This is not thread safe
+    //
+    *fLog << "========================================================"<< endl;
+    *fLog << "Start minimization for supercuts" << endl;
+
+
+    // -------------------------------------------
+    // prepare call to MINUIT
+    //
+
+    // get initial values of parameters 
+    fVinit = super.GetParameters();
+    fStep  = super.GetStepsizes();
+
+    TString name[fVinit.GetSize()];
+    fStep.Set(fVinit.GetSize());
+    fLimlo.Set(fVinit.GetSize());
+    fLimup.Set(fVinit.GetSize());
+    fFix.Set(fVinit.GetSize());
+
+    fNpar = fVinit.GetSize();
+
+
+
+    for (UInt_t i=0; i<fNpar; i++)
+    {
+        name[i]   = "p";
+        name[i]  += i+1;
+        //fStep[i]  = TMath::Abs(fVinit[i]/10.0);
+       //   fLimlo[i] = -100.0;
+//          fLimup[i] =  100.0; 
+	fLimlo[i] = 0.0;
+        fLimup[i] = 0.0;
+        fFix[i]   =   0;
+    }
+
+    // these parameters make no sense, fix them at 0.0
+    //  for (UInt_t i=32; i<fNpar; i++)
+//      {
+//  	//if( i!=3 && i!=7 && i!=11 && i!=15 && i!=19 && i!=23 )
+//  	{
+
+//  	    //fVinit[i] = 0.0;
+//  	    fStep[i]  = 0.0;
+//  	    fFix[i]   = 1;
+//  	}
+//  	//   fVinit[3+4*i] = 0.0;
+//  	//  	    fStep[3+4*i]  = 0.0;
+//  	//  	    fFix[3+4*i]   = 1;
+	
+//      }
+    // these parameters make no sense, fix them at 0.0
+   //   for (UInt_t i=0; i<24; i++)
+//      {
+//  	//fVinit[i] = 0.0;
+//  	fStep[i]  = 0.0;
+//  	fFix[i]   = 1;
+//      }
+
+
+    //-----------------------------------------------------------------
+    //
+    // 0=supercuts, 1=dyn from supercuts, 2=supercuts, 3=all
+    //
+    gLog << "*********************************" <<   fOptimizationMode << endl;
+   
+    switch (fOptimizationMode)
+    {
+	case 0:   
+	    for (UInt_t i=0; i<fNpar; i++)
+	    {
+		if(i%4==0)      // Only optimaze par0, par4, par8,...
+		    continue;
+		
+		fStep[i]  = 0.0;
+		fFix[i]   = 1;
+	    }	
+	    break;
+
+	case 1:   
+	    for (UInt_t i=0; i<fNpar; i++) // Optimize all but par0, par4, par8
+	    {
+		if(i%4!=0 && i!=19 && i!=23) 
+		    continue;
+
+		fStep[i]  = 0.0;
+		fFix[i]   = 1;
+
+	    }	
+
+	    break;
+    }
+
+    //
+    // DistLo/Up doens't dipend on Dist2
+    // 
+    fStep[19]  = 0.0;
+    fFix[19]   = 1;
+    fStep[23]  = 0.0;
+    fFix[23]   = 1;
+
+
+
+    //
+    // Fix all parameters from 24 to the end
+    //
+    for (UInt_t i=24; i<fNpar; i++)
+    {
+ 	//fVinit[i] = 0.0;
+ 	fStep[i]  = 0.0;
+ 	fFix[i]   = 1;
+    }
+
+    
+  //    // Static Cuts
+//      //
+//      for (UInt_t i=0; i<fNpar; i++)
+//      { 
+// 	 if( i!=0 &&  i!=4 && i!=8 &&  i!=12  &&  i!=16 &&  i!=20 && 
+//   	     i!=24 &&  i!=28 && i!=32 &&  i!=36  &&  i!=40  ) 
+//  	{
+//  	    fStep[i]  = 0.0;
+//  	    fFix[i]   = 1;
+//  	}
+//      }
+
+  //
+  //    // 
+    //
+   //   for (UInt_t i=0; i<fNpar; i++)
+//      {
+//  	if( i==0 || i==4 || i==8 ||  i==12  ||  i==16 ||  i==20) 
+//  	{
+//  	    //fVinit[i] = 0.0;
+//  	    fStep[i]  = 0.0;
+//  	    fFix[i]   = 1;
+//  	}
+//      }
+
+ 
+    // Fix
+    //  for (UInt_t i=0; i<36; i++)
+//      {
+//  	    fStep[i]  = 0.0;
+//  	    fFix[i]   = 1;	
+//      } 
+  //   for (UInt_t i=44; i<fNpar; i++)
+//     {
+// 	    fStep[i]  = 0.0;
+// 	    fFix[i]   = 1;	
+//     }
+
+//   for (UInt_t i=37; i<=39; i++)
+//      {
+//  	    //fVinit[i] = 0.0;
+//  	    fStep[i]  = 0.0;
+//  	    fFix[i]   = 1;	
+//      }
+
+
+    //      fStep[40]  = .01;  
+    //          fStep[28]  = 10; 
+    //  fStep[24]  = 10;  
+    //     fVinit[24] = 100; 
+    //    fVinit[28] = -74;
+     //    fVinit[32] = 0.16;
+//         fVinit[36] = 0.03;
+    //         fVinit[40] = 0.21;
+//         fVinit[44] = 0.0;
+
+
+
+  //fVinit[28] = 0;
+   //   fVinit[40] = 0.5;
+
+//        fVinit[44] = -1e6;
+      //       fStep[44]  = 1;
+//      fVinit[36] = 0.;
+//      //fStep[36]  = 1.0;
+
+
+    // vary only first 48 parameters
+    //for (UInt_t i=0; i<fNpar; i++)
+    //{
+    //    if (i >= 48)
+    //	{
+    //      fStep[i] = 0.0;
+    //      fFix[i]  =   1;
+    //	}
+    //
+
+   //  //}
+//     // vary only first 23 parameters
+//     //
+//     for (UInt_t i=0; i<fNpar; i++)
+//     {
+//        if (i >= 24)
+//     	{
+// 	    fStep[i] = 0.0;
+// 	    fFix[i]  =   1;
+//     	}
+//     }
+ 
+
+    // -------------------------------------------
+    // call MINUIT
+
+    TStopwatch clock;
+    clock.Start();
+
+    *fLog << "before calling CallMinuit" << endl;
+
+    MMinuitInterface inter;               
+    Bool_t rc = inter.CallMinuit(fcnSuperCuts, name,
+                                 fVinit, fStep, fLimlo, fLimup, fFix,
+                                 &evtloopfcn, "SIMPLEX", kFALSE);
+ 
+    *fLog << "after calling CallMinuit" << endl;
+
+    *fLog << "Time spent for the minimization in MINUIT :   " << endl;;
+    clock.Stop();
+    clock.Print();
+
+    plotsuper.DrawClone();
+
+    if (!rc)
+        return kFALSE;
+
+    *fLog << "Minimization for supercuts finished" << endl;
+    *fLog << "========================================================" << endl;
+
+
+
+    // -----------------------------------------------------------------
+    // in 'fcnSupercuts' (IFLAG=3) the optimum parameter values were put 
+    //                    into MMySuperCuts
+
+    //
+    // Write optimum parameter values onto file filenameParam
+    //
+    TFile outparam(fFilenameParam, "RECREATE"); 
+    super.Write();
+    outparam.Close();
+
+    *fLog << "Optimum parameter values for supercuts were written onto file '"
+              << fFilenameParam << "' :" << endl;
+
+    const TArrayD &check = super.GetParameters();
+    for (Int_t i=0; i<check.GetSize(); i++)
+        *fLog << check[i] << ",  ";
+    *fLog << endl;
+
+
+
+    *fLog << "End of  supercuts optimization part" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
+
+// -----------------------------------------------------------------------
+//
+// Test the supercuts on the test sample
+//
+Bool_t MMyFindSuperCuts::TestParams()
+{
+    if (fMatrixTest->GetM().GetNrows() <= 0)
+    {
+        *fLog << "MMyFindSuperCuts::TestParams; test matrix has no entries" 
+              << endl;
+        return kFALSE;
+    }
+
+    // -------------   TEST the supercuts    ------------------------------
+    //
+    *fLog << "Test the supercuts on the test sample" << endl;
+
+    // -----------------------------------------------------------------
+    // read optimum parameter values from file filenameParam
+    // into array 'supercutsPar'
+
+    TFile inparam(fFilenameParam);
+    MMySuperCuts scin; 
+    scin.Read("MMySuperCuts");
+    inparam.Close();
+
+    *fLog << "Optimum parameter values for supercuts were read from file '";
+    *fLog << fFilenameParam << "' :" << endl;
+
+    const TArrayD &supercutsPar = scin.GetParameters();
+    for (Int_t i=0; i<supercutsPar.GetSize(); i++)
+        *fLog << supercutsPar[i] << ",  ";
+    *fLog << endl;
+    //---------------------------
+
+
+    // -----------------------------------------------------------------
+    if (fHadronnessName.IsNull())
+    {
+        *fLog << "MMyFindSuperCuts::TestParams; hadronness name is not defined... aborting";
+        *fLog << endl;
+        return kFALSE;
+    }
+
+    MParList  parlist2;
+    MTaskList tasklist2;
+
+    MMySuperCuts supercuts;
+    supercuts.SetParameters(supercutsPar);
+
+    fCalcHadTest->SetHadronnessName(fHadronnessName);
+
+
+    //-------------------------------------------
+
+    MMatrixLoop loop(fMatrixTest);
+
+    // plot alpha before applying the supercuts
+    const TString  mh3NameB = "AlphaBefore";
+    MBinning binsalphabef("Binning"+mh3NameB);
+    binsalphabef.SetEdges(54, -12.0, 96.0);
+
+    // |alpha| is assumed to be in column 7 of the matrix
+    MH3 alphabefore("MatrixTest[6]");
+    alphabefore.SetName(mh3NameB);
+
+    TH1 &alphahistb = alphabefore.GetHist();
+    alphahistb.SetName("alphaBefore-TestParams");
+
+    MFillH fillalphabefore(&alphabefore);
+    fillalphabefore.SetName("FillAlphaBefore");
+
+    // apply the supercuts
+    MF scfilter(fHadronnessName+".fHadronness>0.5");
+    MContinue applysupercuts(&scfilter);
+
+    // plot alpha after applying the supercuts
+    const TString  mh3NameA = "AlphaAfter";
+    MBinning binsalphaaft("Binning"+mh3NameA);
+    binsalphaaft.SetEdges(54, -12.0, 96.0);
+
+    MH3 alphaafter("MatrixTest[6]");
+    alphaafter.SetName(mh3NameA);
+
+    TH1 &alphahista = alphaafter.GetHist();
+    alphahista.SetName("alphaAfter-TestParams");
+
+    MFillH fillalphaafter(&alphaafter);
+    fillalphaafter.SetName("FillAlphaAfter");
+
+    //******************************
+    // entries in MParList
+
+    parlist2.AddToList(&tasklist2);
+
+    parlist2.AddToList(&supercuts);
+
+    parlist2.AddToList(fCam);
+    parlist2.AddToList(fMatrixTest);
+
+    parlist2.AddToList(&binsalphabef);
+    parlist2.AddToList(&alphabefore);
+
+    parlist2.AddToList(&binsalphaaft);
+    parlist2.AddToList(&alphaafter);
+
+    //******************************
+    // entries in MTaskList
+
+    tasklist2.AddToList(&loop);
+    tasklist2.AddToList(&fillalphabefore);
+
+    tasklist2.AddToList(fCalcHadTest);
+    tasklist2.AddToList(&applysupercuts);
+
+    tasklist2.AddToList(&fillalphaafter);
+
+    //******************************
+
+    MProgressBar bar2;
+    MEvtLoop evtloop2;
+    evtloop2.SetParList(&parlist2);
+    evtloop2.SetName("EvtLoopTestParams");
+    evtloop2.SetProgressBar(&bar2);
+    Int_t maxevents2 = -1;
+    if (!evtloop2.Eventloop(maxevents2))
+        return kFALSE;
+
+    tasklist2.PrintStatistics(0, kTRUE);
+
+
+    //-------------------------------------------
+    // draw the alpha plots
+
+    MH3* alphaBefore = (MH3*)parlist2.FindObject(mh3NameB, "MH3");
+    TH1  &alphaHist1 = alphaBefore->GetHist();
+    alphaHist1.SetXTitle("|\\alpha|  [\\circ]");
+
+    MH3* alphaAfter = (MH3*)parlist2.FindObject(mh3NameA, "MH3");
+    TH1  &alphaHist2 = alphaAfter->GetHist();
+    alphaHist2.SetXTitle("|\\alpha|  [\\circ]");
+    alphaHist2.SetName("alpha-TestParams");
+
+    TCanvas *c = new TCanvas("AlphaAfterSC", "AlphaTest", 600, 300);
+    c->Divide(2,1);
+
+    gROOT->SetSelectedPad(NULL);
+
+    c->cd(1);
+    alphaHist1.DrawCopy();
+
+    c->cd(2);
+    alphaHist2.DrawCopy();
+
+
+
+    //-------------------------------------------
+    // fit alpha distribution to get the number of excess events and
+    // calculate significance of gamma signal in the alpha plot
+  
+    const Double_t alphasig = 20.0;
+    const Double_t alphamin = 30.0;
+    const Double_t alphamax = 90.0;
+    const Int_t    degree   =    2;
+    const Bool_t   drawpoly  = kTRUE;
+    const Bool_t   fitgauss  = kTRUE;
+    const Bool_t   print     = kTRUE;
+
+    MHFindSignificance findsig;
+    findsig.SetRebin(kTRUE);
+    findsig.SetReduceDegree(kFALSE);
+
+    findsig.FindSigma(&alphaHist2, alphamin, alphamax, degree, 
+                      alphasig, drawpoly, fitgauss, print);
+
+    const Double_t significance = findsig.GetSignificance();
+    const Double_t alphasi = findsig.GetAlphasi();
+
+    *fLog << "Significance of gamma signal after supercuts in test sample : "
+         << significance << " (for |alpha| < " << alphasi << " degrees)" 
+         << endl;
+    //-------------------------------------------
+
+
+    *fLog << "Test of supercuts part finished" << endl;
+    *fLog << "======================================================" << endl;
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MMyFindSuperCuts.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MMyFindSuperCuts.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MMyFindSuperCuts.h	(revision 9772)
@@ -0,0 +1,149 @@
+#ifndef MARS_MMyFindSuperCuts
+#define MARS_MMyFindSuperCuts
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MFilter;
+class MEvtLoop;
+class MH3;
+class MMySuperCutsCalc;
+class MGeomCam;
+class MHMatrix;
+/*
+#include "MFilter.h"
+#include "MEvtLoop.h"
+#include "MH3.h"
+#include "MMySuperCutsCalc.h"
+#include "MGeomCam.h"
+#include "MHMatrix.h"
+*/
+
+class MMyFindSuperCuts : public MParContainer
+{
+private:
+
+  TString fFilenameTrain;
+  TString fFilenameTest;
+
+  Int_t   fHowManyTrain;
+  Int_t   fHowManyTest;
+
+  Bool_t  fUseOrigDistribution;
+
+  TString  fFilenameParam;
+
+  TString  fHadronnessName;
+
+  MMySuperCutsCalc *fCalcHadTrain;
+  MMySuperCutsCalc *fCalcHadTest;
+
+  MHMatrix          *fMatrixTrain;
+  MHMatrix          *fMatrixTest;
+  MGeomCam          *fCam;
+
+  MEvtLoop *fObjectFit;
+
+  MFilter  *fMatrixFilter; 
+
+  // to comunicate with MINUIT -----------------
+  // attention : dimensions must agree with those in 
+  //             MMinuitInterface::CallMinuit()
+  //char    fParName [80][100];
+  TArrayD fVinit;
+  TArrayD fStep;
+  TArrayD fLimlo;
+  TArrayD fLimup;
+  TArrayI fFix;
+
+  UInt_t     fNpar;
+
+  TString    fMethod;
+
+  Double_t fMin,   fEdm,   fErrdef;
+  Int_t    fNpari, fNparx, fIstat;
+  Int_t    fErrMinimize;
+  //--------------------------------------------
+
+  Float_t fSizeCutLow;
+  Float_t fSizeCutUp;
+
+  Int_t fOptimizationMode;
+
+public:
+
+  MMyFindSuperCuts(const char *name=NULL, const char *title=NULL);
+  ~MMyFindSuperCuts();
+
+  void SetSizeCutLow(Float_t size) {fSizeCutLow = size;}
+  void SetSizeCuts(Float_t sizeLow, Float_t sizeUp) 
+      {
+	  fSizeCutLow = sizeLow; 
+	  fSizeCutUp = sizeUp;
+      }
+
+
+
+  void SetFilenameTraining(const TString &name, const Int_t howmany) 
+      {fFilenameTrain = name;  fHowManyTrain = howmany; }
+
+  void SetFilenameTest(const TString &name, const Int_t howmany)     
+      {fFilenameTest     = name;  fHowManyTest  = howmany; }
+
+  void SetFilenameParam(const TString &name)    {fFilenameParam  = name;}
+  void SetHadronnessName(const TString &name)   {fHadronnessName = name;}
+
+  void SetMatrixFilter(MFilter *filter)          {fMatrixFilter = filter;}
+
+  Bool_t DefineTrainMatrix(const TString &name, MH3 &href,
+                           const Int_t howmany, const TString &filetrain); 
+
+  Bool_t DefineTestMatrix(const TString &name, MH3 &href,
+                          const Int_t howmany, const TString &filetest);
+
+  Bool_t DefineTrainTestMatrix(const TString &name, MH3 &href,
+			 const Int_t howmanytrain, const Int_t howmanytest, 
+                         const TString &filetrain, const TString &filetest);
+
+  MHMatrix *GetMatrixTrain() { return fMatrixTrain; }
+  MHMatrix *GetMatrixTest()  { return fMatrixTest;  }
+
+  Bool_t ReadMatrix( const TString &filetrain, const TString &filetest);
+
+  Bool_t FindParams(TString parSCinit, TArrayD &params, TArrayD &steps);
+  Bool_t TestParams();
+
+
+  void SetOptimizationMode(Int_t mode ) { fOptimizationMode=mode; }
+
+  ClassDef(MMyFindSuperCuts, 1) // Class for optimization of the Supercuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCuts.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCuts.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCuts.cc	(revision 9772)
@@ -0,0 +1,325 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 08/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 08/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Marcos Lopez, 05/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MMySuperCuts                                                         //
+//                                                                         //
+//   this is the container for the parameters of the supercuts             //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MMySuperCuts.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MMySuperCuts);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+//  MMySuperCuts::MMySuperCuts(const char *name, const char *title)
+//    : fParameters(18), fStepsizes(18),
+//      fLengthUp(fParameters.GetArray()),   fLengthLo(fParameters.GetArray()+3),
+//      fWidthUp(fParameters.GetArray()+6), fWidthLo(fParameters.GetArray()+9),
+//      fDistUp(fParameters.GetArray()+12),  fDistLo(fParameters.GetArray()+15)
+//  {
+MMySuperCuts::MMySuperCuts(const char *name, const char *title)
+  : fParameters(48), fStepsizes(48),
+    fLengthUp(fParameters.GetArray()),   fLengthLo(fParameters.GetArray()+4),
+    fWidthUp(fParameters.GetArray()+4*2), fWidthLo(fParameters.GetArray()+4*3),
+    fDistUp(fParameters.GetArray()+4*4),  fDistLo(fParameters.GetArray()+4*5),
+    fAsymUp(fParameters.GetArray()+4*6),  fAsymLo(fParameters.GetArray()+4*7),
+    fConcUp(fParameters.GetArray()+4*8),  fConcLo(fParameters.GetArray()+4*9),
+    fLeakage1Up(fParameters.GetArray()+4*10),  fLeakage1Lo(fParameters.GetArray()+4*11)
+
+{
+
+    fName  = name  ? name  : "MMySuperCuts";
+    fTitle = title ? title : "Container for the supercut parameters";
+
+    // set supercut parameters to their default values
+    InitParameters();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// set default values for the supercut parameters
+//
+void MMySuperCuts::InitParameters()
+{
+    //---------------------------------------------------
+    //  these are the default values
+    //
+    fLengthUp[0] =  0.302;
+    fLengthUp[1] =  0.0;//0.03;
+    fLengthUp[2] =  0.0;
+    fLengthUp[3] =  0.0;
+//      fLengthUp[4] =  0.0;
+//      fLengthUp[5] =  0.0;
+//      fLengthUp[6] =  0.0;
+//      fLengthUp[7] =  0.0;
+
+    fLengthLo[0] =  0.052;
+    fLengthLo[1] =  0.;
+    fLengthLo[2] =  0.;
+    fLengthLo[3] =  0.;
+//      fLengthLo[4] =  0.;
+//      fLengthLo[5] =  0.;
+//      fLengthLo[6] =  0.;
+//      fLengthLo[7] =  0.;
+
+    fWidthUp[0] =  0.121;
+    fWidthUp[1] =  0.0;
+    fWidthUp[2] =  0.0;
+    fWidthUp[3] =  0.0;
+//      fWidthUp[4] =  0.0;
+//      fWidthUp[5] =  0.0;
+//      fWidthUp[6] =  0.0;
+//      fWidthUp[7] =  0.0;
+
+    fWidthLo[0] =  0.057;
+    fWidthLo[1] =  0.;
+    fWidthLo[2] =  0.;
+    fWidthLo[3] =  0.;
+//      fWidthLo[4] =  0.;
+//      fWidthLo[5] =  0.;
+//      fWidthLo[6] =  0.;
+//      fWidthLo[7] =  0.;
+
+    fDistUp[0] =  1.;
+    fDistUp[1] =  0.0;
+    fDistUp[2] =  0.0;
+    fDistUp[3] =  0.0;
+//      fDistUp[4] =  0.0;
+//      fDistUp[5] =  0.0;
+//      fDistUp[6] =  0.0;
+//      fDistUp[7] =  0.0;
+
+    fDistLo[0] =  0.3;
+    fDistLo[1] =  0.0;
+    fDistLo[2] =  0.0;
+    fDistLo[3] =  0.0;
+//      fDistLo[4] =  0.0;
+//      fDistLo[5] =  0.0;
+//      fDistLo[6] =  0.0;
+//      fDistLo[7] =  0.0;
+    
+    // dummy values
+
+    fAsymUp[0] =  100;
+    fAsymUp[1] =  0.0;
+    fAsymUp[2] =  0.0;
+    fAsymUp[3] =  0.0;
+
+    fAsymLo[0] = -100;
+    fAsymLo[1] =  0.0;
+    fAsymLo[2] =  0.0;
+    fAsymLo[3] =  0.0;
+    
+
+    fConcUp[0] =  1.;
+    fConcUp[1] =  0.0;
+    fConcUp[2] =  0.0;
+    fConcUp[3] =  0.0;
+
+    fConcLo[0] = 0;
+    fConcLo[1] =  0.0;
+    fConcLo[2] =  0.0;
+    fConcLo[3] =  0.0;
+    
+    fLeakage1Up[0] =  1.;
+    fLeakage1Up[1] =  0.0;
+    fLeakage1Up[2] =  0.0;
+    fLeakage1Up[3] =  0.0;
+   //   fLeakage1Up[4] =  0.0;
+//      fLeakage1Up[5] =  0.0;
+//      fLeakage1Up[6] =  0.0;
+//      fLeakage1Up[7] =  0.0;
+
+    fLeakage1Lo[0] = -1.e10;
+    fLeakage1Lo[1] =  0.0;
+    fLeakage1Lo[2] =  0.0;
+    fLeakage1Lo[3] =  0.0;
+   //   fLeakage1Lo[4] =  0.0;
+//      fLeakage1Lo[5] =  0.0;
+//      fLeakage1Lo[6] =  0.0;
+//      fLeakage1Lo[7] =  0.0;
+
+
+    //---------------------------------------------------
+    // fStepsizes 
+    // if == 0.0    the parameter will be fixed in the minimization
+    //    != 0.0    initial step sizes for the parameters
+
+    // LengthUp
+    fStepsizes[0] = 0.01;
+    fStepsizes[1] = 0.01;
+    fStepsizes[2] = 0.1;
+    fStepsizes[3] = 0.1;
+//      fStepsizes[4] = 0.0;
+//      fStepsizes[5] = 0.0;
+//      fStepsizes[6] = 0.0;
+//      fStepsizes[7] = 0.0;
+
+    // LengthLo
+    fStepsizes[4]  = 0.01;
+    fStepsizes[5]  = 0.01;
+    fStepsizes[6]  = 0.1;
+    fStepsizes[7] = 0.1;
+//      fStepsizes[12] = 0.0;
+//      fStepsizes[13] = 0.0;
+//      fStepsizes[14] = 0.0;
+//      fStepsizes[15] = 0.0;
+
+    // WidthUp
+    fStepsizes[8] = 0.01;
+    fStepsizes[9] = 0.01;
+    fStepsizes[10] = 0.1;
+    fStepsizes[11] = 0.1;
+//      fStepsizes[20] = 0.0;
+//      fStepsizes[21] = 0.0;
+//      fStepsizes[22] = 0.0;
+//      fStepsizes[23] = 0.0;
+
+    // WidthLo
+    fStepsizes[12] = 0.01;
+    fStepsizes[13] = 0.01;
+    fStepsizes[14] = 0.1;
+    fStepsizes[15] = 0.1;
+//      fStepsizes[28] = 0.0;
+//      fStepsizes[29] = 0.0;
+//      fStepsizes[30] = 0.0;
+//      fStepsizes[31] = 0.0;
+
+    // DistUp
+    fStepsizes[16] = 0.1;
+    fStepsizes[17] = 0.1;
+    fStepsizes[18] = 0.1;
+    fStepsizes[19] = 0.1;
+//      fStepsizes[36] = 0.0;
+//      fStepsizes[37] = 0.0;
+//      fStepsizes[38] = 0.0;
+//      fStepsizes[39] = 0.0;
+
+    // DistLo
+    fStepsizes[20] = 0.1;
+    fStepsizes[21] = 0.1;
+    fStepsizes[22] = 0.1;
+    fStepsizes[23] = 0.1;
+//      fStepsizes[44] = 0.0;
+//      fStepsizes[45] = 0.0;
+//      fStepsizes[46] = 0.0;
+//      fStepsizes[47] = 0.0;
+
+    for(int i=24;i<48;i++)
+	fStepsizes[i] = .1;
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Set the parameter values from the array 'd'
+//
+//
+Bool_t MMySuperCuts::SetParameters(const TArrayD &d)
+{
+    if (d.GetSize() != fParameters.GetSize())
+    {
+        *fLog << err << "Sizes of d and of fParameters are different : "
+              << d.GetSize() << ",  " << fParameters.GetSize() << endl;
+        return kFALSE;
+    }
+
+    fParameters = d;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the step sizes from the array 'd'
+//
+//
+Bool_t MMySuperCuts::SetStepsizes(const TArrayD &d)
+{
+    if (d.GetSize() != fStepsizes.GetSize())
+    {
+        *fLog << err << "Sizes of d and of fStepsizes are different : "
+              << d.GetSize() << ",  " << fStepsizes.GetSize() << endl;
+        return kFALSE;
+    }
+
+    fStepsizes = d;
+
+    return kTRUE;
+}
+
+
+
+void MMySuperCuts::Print(const Option_t* opt) const
+{
+    //    for(Int_t i=0; i<48; i++)
+    //	cout << i << " " << fParameters[i] << endl;
+
+    printf("Hillas_up/lo = A + B*log(SIZE) + C*log^2(SIZE) + D*DIST^2\n");
+    printf("                A       B       C       D\n");
+    printf("Length_Up  [0-3]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[0],fParameters[1],fParameters[2],fParameters[3]);
+    printf("Length_Lo  [4-7]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[4],fParameters[5],fParameters[6],fParameters[7]);
+
+    printf("Width_Up  [8-11]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[8],fParameters[9],fParameters[10],fParameters[11]);
+    printf("Width_Lo [12-15]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[12],fParameters[13],fParameters[14],fParameters[15]);
+
+    printf("Dist_Up  [16-19]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[16],fParameters[17],fParameters[18],fParameters[19]);
+    printf("Dist_Lo  [20-23]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[20],fParameters[21],fParameters[22],fParameters[23]);
+
+    printf("Asym_Up  [24-27]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[24],fParameters[25],fParameters[26],fParameters[27]);
+    printf("Asym_Lo  [28-31]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[28],fParameters[29],fParameters[30],fParameters[31]);
+
+    printf("Conc_Up  [32-35]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[32],fParameters[33],fParameters[34],fParameters[35]);
+    printf("Conc_Lo  [36-39]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[36],fParameters[37],fParameters[38],fParameters[39]);
+
+    printf("Leak_Up  [40-43]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[40],fParameters[41],fParameters[42],fParameters[43]);
+    printf("Leak_Lo  [44-47]: %7.3f %7.3f %7.3f %7.3f\n",fParameters[44],fParameters[45],fParameters[46],fParameters[47]);
+}
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCuts.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCuts.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCuts.h	(revision 9772)
@@ -0,0 +1,72 @@
+#ifndef MARS_MMySuperCuts
+#define MARS_MMySuperCuts
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MMySuperCuts : public MParContainer
+{
+ private:
+
+    TArrayD fParameters; // supercut parameters
+    TArrayD fStepsizes;  // step sizes of supercut parameters
+
+    Double_t *fLengthUp; //!
+    Double_t *fLengthLo; //!
+    Double_t *fWidthUp;  //!
+    Double_t *fWidthLo;  //!
+    Double_t *fDistUp;   //!
+    Double_t *fDistLo;   //!
+
+    Double_t *fAsymUp;   //!
+    Double_t *fAsymLo;   //!
+    Double_t *fConcUp;   //!
+    Double_t *fConcLo;   //!
+    Double_t *fLeakage1Up;   //!
+    Double_t *fLeakage1Lo;   //!
+
+
+   
+
+ public:
+
+    MMySuperCuts(const char *name=NULL, const char *title=NULL);
+
+    void InitParameters();
+
+    Bool_t SetParameters(const TArrayD &d);
+    Bool_t SetStepsizes(const TArrayD &d);
+
+    const TArrayD &GetParameters() const { return fParameters; }
+    const TArrayD &GetStepsizes()  const { return fStepsizes;  }
+
+    const Double_t *GetLengthUp() const { return fLengthUp; }
+    const Double_t *GetLengthLo() const { return fLengthLo; }
+    const Double_t *GetWidthUp() const  { return fWidthUp; }
+    const Double_t *GetWidthLo() const  { return fWidthLo; }
+    const Double_t *GetDistUp() const   { return fDistUp; }
+    const Double_t *GetDistLo() const   { return fDistLo; }
+
+const Double_t *GetAsymUp() const   { return fAsymUp; }
+    const Double_t *GetAsymLo() const   { return fAsymLo; }
+
+    const Double_t *GetConcUp() const   { return fConcUp; }
+    const Double_t *GetConcLo() const   { return fConcLo; }
+    const Double_t *GetLeakage1Up() const   { return fLeakage1Up; }
+    const Double_t *GetLeakage1Lo() const   { return fLeakage1Lo; }
+
+
+    void Print(const Option_t *opt ="") const;
+
+    ClassDef(MMySuperCuts, 1) // A container for the Supercut parameters
+};
+
+#endif
+
+
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCutsCalc.cc
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCutsCalc.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCutsCalc.cc	(revision 9772)
@@ -0,0 +1,551 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 04/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Marcos Lopez, 05/2004 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   MMySuperCutsCalc                                                     //
+//                                                                         //
+//   this class calculates the hadronness for the supercuts                //
+//   the parameters of the supercuts are taken                             //
+//                  from the container MSupercuts                       //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MMySuperCutsCalc.h"
+
+#include <math.h>
+#include <fstream>
+
+#include "TFile.h"
+#include "TArrayD.h"
+
+#include "MParList.h"
+#include "MHillasExt.h"
+#include "MHillasSrc.h"
+#include "MNewImagePar.h"
+#include "MMcEvt.hxx"
+#include "MCerPhotEvt.h"
+#include "MGeomCam.h"
+#include "MHadronness.h"
+#include "MHMatrix.h"
+#include "MMySuperCuts.h"
+#include "MGeomCamMagic.h"
+#include "MPointingPos.h"
+#include "MNewImagePar.h"
+#include "MHillasExt.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MMySuperCutsCalc);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// constructor
+//
+MMySuperCutsCalc::MMySuperCutsCalc(const char *hilname, const char *hilsrcname,                                   const char *name, const char *title)
+  : fHadronnessName("MHadronness"), fHilName(hilname), fHilSrcName(hilsrcname),
+    fHilExtName("MHillasExt"), fNewParName("MNewImagePar"), 
+    fSuperName("MMySuperCuts") ,
+    fNoDistCut(kFALSE) ,fSizeCutLow(2000),fSizeCutUp(10000000)
+
+{
+    fName  = name  ? name  : "MMySuperCutsCalc";
+    fTitle = title ? title : "Class to evaluate the Supercuts";
+
+    fMatrix = NULL;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//
+Int_t MMySuperCutsCalc::PreProcess(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << "MGeomCam (Camera Geometry) not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMm2Deg = cam->GetConvMm2Deg();
+
+    fHadronness = (MHadronness*)pList->FindCreateObj("MHadronness", fHadronnessName);
+    if (!fHadronness)
+    {
+        *fLog << err << fHadronnessName << " [MHadronness] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSuper = (MMySuperCuts*)pList->FindObject(fSuperName, "MMySuperCuts");
+    if (!fSuper)
+    {
+        *fLog << err << fSuperName << " [MMySuperCuts] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    if (fMatrix)
+       return kTRUE;
+
+    //-----------------------------------------------------------
+    fHil = (MHillas*)pList->FindObject(fHilName, "MHillas");
+    if (!fHil)
+    {
+        *fLog << err << fHilName << " [MHillas] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilExt = (MHillasExt*)pList->FindObject(fHilExtName, "MHillasExt");
+    if (!fHilExt)
+    {
+        *fLog << err << fHilExtName << " [MHillasExt] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHilSrc = (MHillasSrc*)pList->FindObject(fHilSrcName, "MHillasSrc");
+    if (!fHilSrc)
+    {
+        *fLog << err << fHilSrcName << " [MHillasSrc] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fNewPar = (MNewImagePar*)pList->FindObject(fNewParName, "MNewImagePar");
+    if (!fNewPar)
+    {
+        *fLog << err << fNewParName << " [MNewImagePar] not found... aborting." << endl;
+        return kFALSE;
+    } 
+
+   //  fPointingPos = (MPointingPos*)pList->FindObject("MPointingPos");
+//     if (!fPointingPos)
+//     {
+//         *fLog << err  << " [MPointingPos] not found... aborting." << endl;
+// 	//  return kFALSE;
+//     }
+    fNewImagePar = (MNewImagePar*)pList->FindObject("MNewImagePar");
+    if (!fNewImagePar)
+    {
+        *fLog << err << " [MNewImagePar] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fHillasExt = (MHillasExt*)pList->FindObject("MHillasExt");
+    if (!fHillasExt)
+    {
+        *fLog << err << " [MHillasExt] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+//      fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+//      if (!fMcEvt)
+//      {
+//          *fLog << err << "MMcEvt not found... aborting." << endl;
+//          return kFALSE;
+//      }
+
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculation of upper and lower limits
+//
+Double_t MMySuperCutsCalc::CtsMCut(const Double_t* a, Double_t ls, Double_t ls2, Double_t ct, Double_t dd2) const
+{
+    // define cut-function
+    //
+    //    dNOMLOGSIZE = 5.0 (=log(150.0)
+    //    dNOMCOSZA   = 1.0
+    //
+    //      a: array of cut parameters
+    //     ls: log(SIZE) - dNOMLOGSIZE
+    //    ls2: ls^2
+    //     ct: Cos(ZA.) - dNOMCOSZA
+    //    dd2: DIST^2
+  
+//    const Double_t limit =
+//          a[0] + a[1] * dd2 + a[2] * ct  +
+//          ls  * (a[3] + a[4] * dd2 + a[5] * ct) +
+//          ls2 * (a[6] + a[7] * dd2);
+
+//  const Double_t limit = a[0] + ls*a[1] + ls2*a[2] + ct*a[3];
+  const Double_t limit = a[0] + ls*a[1] + ls2*a[2] + dd2*a[3];
+
+    //*fLog << "MMySuperCutsCalc::CtsMCut; *a = "
+    //      << *a     << ",  " << *(a+1) << ",  " << *(a+2) << ",  "
+    //      << *(a+3) << ",  " << *(a+4) << ",  " << *(a+5) << ",  "
+    //      << *(a+6) << ",  " << *(a+7) << endl;
+
+    //*fLog << "MMySuperCutsCalc::CtsMCut; ls, ls2, ct, dd2, limit = " << ls
+    //      << ",  " << ls2 << ",  " << ct << ",  " << dd2 << ",  "
+    //      << limit << endl;
+
+    return limit;
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the mapped value from the Matrix
+//
+Double_t MMySuperCutsCalc::GetVal(Int_t i) const
+{
+
+    Double_t val = (*fMatrix)[fMap[i]];
+
+
+    //*fLog << "MMySuperCutsCalc::GetVal; i, fMatrix, fMap, val = "
+    //    << i << ",  " << fMatrix << ",  " << fMap[i] << ",  " << val << endl;
+
+
+    return val;
+}
+
+// --------------------------------------------------------------------------
+//
+// You can use this function if you want to use a MHMatrix instead of the
+// given containers. This function adds all necessary columns to the
+// given matrix. Afterward you should fill the matrix with the corresponding
+// data (eg from a file by using MHMatrix::Fill). If you now loop
+// through the matrix (eg using MMatrixLoop) MEnergyEstParam::Process
+// will take the values from the matrix instead of the containers.
+//
+void MMySuperCutsCalc::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+      return;
+
+    fMatrix = mat;
+
+   //  //fMap[0] = fMatrix->AddColumn("MMcEvt.fTelescopeTheta");
+//     fMap[0] = fMatrix->AddColumn("MHillas.fWidth");
+//     fMap[1] = fMatrix->AddColumn("MHillas.fLength");
+//     fMap[2] = fMatrix->AddColumn("MHillas.fSize");
+//     fMap[3] = fMatrix->AddColumn("MHillas.fMeanX");
+//     fMap[4] = fMatrix->AddColumn("MHillas.fMeanY");
+//     fMap[5] = fMatrix->AddColumn("MHillasSrc.fDist");
+//     fMap[6] = fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+//     //fMap[7] = fMatrix->AddColumn("MPointingPos.fZd");
+//     fMap[7] =  fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+//     fMap[8] = fMatrix->AddColumn("MNewImagePar.fConc");
+//     fMap[9] = fMatrix->AddColumn("MHillasExt.fAsym");
+//     fMap[10]= fMatrix->AddColumn("MNewImagePar.fLeakage1");
+ 
+    fMap[0] = fMatrix->AddColumn("MHillas.fWidth");
+    fMap[1] = fMatrix->AddColumn("MHillas.fLength");
+    fMap[2] = fMatrix->AddColumn("MHillas.fSize");
+    fMap[3] = fMatrix->AddColumn("MHillas.fMeanX");
+    fMap[4] = fMatrix->AddColumn("MHillas.fMeanY");
+    fMap[5] = fMatrix->AddColumn("MHillasSrc.fDist");
+    fMap[6] = fMatrix->AddColumn("fabs(MHillasSrc.fAlpha)");
+    fMap[7] = fMatrix->AddColumn("MNewImagePar.fConc");
+    fMap[8] = fMatrix->AddColumn("MHillasExt.fAsym");
+    fMap[9] = fMatrix->AddColumn("MNewImagePar.fLeakage1");
+
+    //fMap[8] = fMatrix->AddColumn("sgn(MHillasSrc.fCosDeltaAlpha)*(MHillasExt.fM3Long)");
+    //fMap[9] = fMatrix->AddColumn("MNewImagePar.fConc");
+    //fMap[10]= fMatrix->AddColumn("MNewImagePar.fLeakage1");
+}
+
+// ---------------------------------------------------------------------------
+//
+// Evaluate dynamical supercuts 
+// 
+//          set hadronness to 0.25 if cuts are fullfilled
+//                            0.75 otherwise
+//
+Int_t MMySuperCutsCalc::Process()
+{
+
+   
+    //const Double_t kNomLogSize = 7.6;//=log(2000) 4.1;
+    const Double_t kNomLogSize = log(fSizeCutLow);
+
+    const Double_t kNomCosZA   = 1.0;
+
+    //const Double_t theta   = fMatrix ? GetVal(0) : fMcEvt->GetTelescopeTheta();  
+
+  //   const Double_t width0  = fMatrix ? GetVal(0) : fHil->GetWidth();
+//     const Double_t length0 = fMatrix ? GetVal(1) : fHil->GetLength();
+//     const Double_t size    = fMatrix ? GetVal(2) : fHil->GetSize();
+//     const Double_t meanx   = fMatrix ? GetVal(3) : fHil->GetMeanX();
+//     const Double_t meany   = fMatrix ? GetVal(4) : fHil->GetMeanY();
+//     const Double_t dist0   = fMatrix ? GetVal(5) : fHilSrc->GetDist();
+//     // const Double_t theta   = fMatrix ? GetVal(7) : fPointingPos->GetZd();
+//     const Double_t conc    = fMatrix ? GetVal(8) : fNewImagePar->GetConc();
+//     Double_t asym    = fMatrix ? GetVal(9) : fHillasExt->GetAsym();
+//     const Double_t leakage = fMatrix ? GetVal(10): fNewImagePar->GetLeakage1();
+   
+//     const Double_t theta   =0;
+
+    const Double_t width0  = fMatrix ? GetVal(0) : fHil->GetWidth();
+    const Double_t length0 = fMatrix ? GetVal(1) : fHil->GetLength();
+    const Double_t size    = fMatrix ? GetVal(2) : fHil->GetSize();
+    const Double_t meanx   = fMatrix ? GetVal(3) : fHil->GetMeanX();
+    const Double_t meany   = fMatrix ? GetVal(4) : fHil->GetMeanY();
+    const Double_t dist0   = fMatrix ? GetVal(5) : fHilSrc->GetDist();
+    const Double_t conc    = fMatrix ? GetVal(7) : fNewImagePar->GetConc();
+    Double_t asym    = fMatrix ? GetVal(8) : fHillasExt->GetAsym();
+    const Double_t leakage = fMatrix ? GetVal(9): fNewImagePar->GetLeakage1();
+   
+
+    Double_t help;
+    if (!fMatrix)
+      help = TMath::Sign(fHilExt->GetM3Long(), fHilSrc->GetCosDeltaAlpha());
+
+  //    const Double_t asym0   = fMatrix ? GetVal(8) : help;
+//      const Double_t conc    = fMatrix ? GetVal(9) : fNewPar->GetConc();
+//      const Double_t leakage = fMatrix ? GetVal(10): fNewPar->GetLeakage1();
+
+    const Double_t newdist = dist0 * fMm2Deg;
+
+    const Double_t dist2   = meanx*meanx + meany*meany;
+    const Double_t dist    = sqrt(dist2) * fMm2Deg;
+    const Double_t dd2     = dist*dist;
+
+    const Double_t dmls    = log(size) - kNomLogSize;
+    Double_t dmls2   = dmls * dmls;
+
+    //const Double_t dmcza   = cos(theta/kRad2Deg) - kNomCosZA;
+
+    const Double_t length  = length0 * fMm2Deg;
+    const Double_t width   = width0  * fMm2Deg;
+    //const Double_t asym    = asym0   * fMm2Deg;
+ 
+    // *fLog << "Using SizeCut = "  << fSizeCut  <<  endl;
+    /*
+    *fLog << "newdist, length, width, asym, dist, conc, leakage = " 
+          << newdist << ",  " << length << ",  " << width << ",  "
+          << asym    << ",  " << dist   << ",  " << conc  << ",  " << leakage
+          << endl;
+  
+    *fLog << "upper cuts in newdist, length, width, asym, dist, conc, leakage = " 
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLengthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLengthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetWidthUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetWidthLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetAsymUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetAsymLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetDistUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetDistLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+  fHadronness = hadronness;
+   
+          << CtsMCut (fSuper->GetConcUp(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetConcLo(),   dmls, dmcza, dmls2, dd2) << ",  "
+
+          << CtsMCut (fSuper->GetLeakage1Up(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << CtsMCut (fSuper->GetLeakage1Lo(),   dmls, dmcza, dmls2, dd2) << ",  "
+          << endl;
+    */
+   
+    double dmcza = 0;
+
+    // cout << fSizeCutLow << " " << fSizeCutUp << endl;
+
+    if(fNoDistCut)
+    {
+	if ( size > fSizeCutLow &&  size < fSizeCutUp && 
+	    
+	    //newdist < CtsMCut (fSuper->GetDistUp(),   dmls, dmls2) &&
+	    //newdist > CtsMCut (fSuper->GetDistLo(),   dmls, dmls2) &&
+	    
+	    length< CtsMCut (fSuper->GetLengthUp(), dmls, dmls2, dmcza, dd2) &&
+	    length> CtsMCut (fSuper->GetLengthLo(), dmls, dmls2, dmcza, dd2) &&
+	    
+	    width< CtsMCut (fSuper->GetWidthUp(),  dmls, dmls2, dmcza, dd2) &&
+	    width > CtsMCut (fSuper->GetWidthLo(),  dmls, dmls2, dmcza, dd2) &&
+
+	    conc< CtsMCut (fSuper->GetConcUp(),  dmls, dmls2, dmcza, dd2) &&
+	    conc > CtsMCut (fSuper->GetConcLo(),  dmls, dmls2, dmcza, dd2) &&
+
+	    asym< CtsMCut (fSuper->GetAsymUp(),  dmls, dmls2, dmcza, dd2) &&
+	    asym > CtsMCut (fSuper->GetAsymLo(),  dmls, dmls2, dmcza, dd2) &&
+	    
+	    leakage < CtsMCut (fSuper->GetLeakage1Up(),dmls,dmls2, dmcza, dd2) &&
+        leakage > CtsMCut (fSuper->GetLeakage1Lo(),dmls, dmls2, dmcza, dd2) 
+	   
+	  
+  ) 
+	    
+	    fHadronness->SetHadronness(0.25);
+	else
+	    fHadronness->SetHadronness(0.75);
+	
+    }
+    else 
+    {
+	//cout << asym << endl;
+	if (size >  fSizeCutLow &&  size < fSizeCutUp && 
+
+	    newdist < CtsMCut (fSuper->GetDistUp(), dmls, dmls2, dmcza, dd2) &&
+	    newdist > CtsMCut (fSuper->GetDistLo(), dmls, dmls2, dmcza, dd2) &&
+	    
+	    length  < CtsMCut (fSuper->GetLengthUp(),dmls, dmls2, dmcza, dd2) &&
+	    length  > CtsMCut (fSuper->GetLengthLo(),dmls, dmls2, dmcza, dd2) &&
+	    
+	    width   < CtsMCut (fSuper->GetWidthUp(),dmls, dmls2, dmcza, dd2) &&
+	    width   > CtsMCut (fSuper->GetWidthLo(),dmls, dmls2, dmcza, dd2)  && 
+
+	    asym< CtsMCut (fSuper->GetAsymUp(),  dmls, dmls2, dmcza, dd2) &&
+	    asym > CtsMCut (fSuper->GetAsymLo(),  dmls, dmls2, dmcza, dd2) &&
+
+	    conc< CtsMCut (fSuper->GetConcUp(),  dmls, dmls2, dmcza, dd2) &&
+	    conc > CtsMCut (fSuper->GetConcLo(),  dmls, dmls2, dmcza, dd2) &&
+
+        leakage < CtsMCut (fSuper->GetLeakage1Up(),dmls,dmls2, dmcza, dd2) &&
+        leakage > CtsMCut (fSuper->GetLeakage1Lo(),dmls, dmls2, dmcza, dd2) 
+	   
+	    ) 
+
+	    fHadronness->SetHadronness(0.25);
+	else
+	    fHadronness->SetHadronness(0.75);
+    }
+
+
+
+
+
+
+
+    //*fLog << "SChadroness = " << fHadronness->GetHadronness() << endl;
+
+    fHadronness->SetReadyToSave();
+
+    return kTRUE;
+}
+
+
+
+
+
+// ---------------------------------------------------------------------------
+//
+// Return kTRUE if the event pass the dist cut, ie., if it is a gamma-like
+// event.
+//
+Bool_t MMySuperCutsCalc::CalcDistCut(MHillasSrc* hillasSrc)
+{
+  
+ 
+   
+    //const Double_t kNomLogSize = 7.6;//=log(2000) 4.1;
+    const Double_t kNomLogSize = log(fSizeCutLow);
+
+    const Double_t kNomCosZA   = 1.0;
+
+    //const Double_t theta   = fMatrix ? GetVal(0) : fMcEvt->GetTelescopeTheta();  
+
+  //   const Double_t width0  = fMatrix ? GetVal(0) : fHil->GetWidth();
+//     const Double_t length0 = fMatrix ? GetVal(1) : fHil->GetLength();
+//     const Double_t size    = fMatrix ? GetVal(2) : fHil->GetSize();
+//     const Double_t meanx   = fMatrix ? GetVal(3) : fHil->GetMeanX();
+//     const Double_t meany   = fMatrix ? GetVal(4) : fHil->GetMeanY();
+//     const Double_t dist0   = fMatrix ? GetVal(5) : fHilSrc->GetDist();
+//     // const Double_t theta   = fMatrix ? GetVal(7) : fPointingPos->GetZd();
+//     const Double_t conc    = fMatrix ? GetVal(8) : fNewImagePar->GetConc();
+//     Double_t asym    = fMatrix ? GetVal(9) : fHillasExt->GetAsym();
+//     const Double_t leakage = fMatrix ? GetVal(10): fNewImagePar->GetLeakage1();
+   
+//     const Double_t theta   =0;
+
+    const Double_t width0  = fMatrix ? GetVal(0) : fHil->GetWidth();
+    const Double_t length0 = fMatrix ? GetVal(1) : fHil->GetLength();
+    const Double_t size    = fMatrix ? GetVal(2) : fHil->GetSize();
+    const Double_t meanx   = fMatrix ? GetVal(3) : fHil->GetMeanX();
+    const Double_t meany   = fMatrix ? GetVal(4) : fHil->GetMeanY();
+    const Double_t dist0   = fMatrix ? GetVal(5) : fHilSrc->GetDist();
+    const Double_t conc    = fMatrix ? GetVal(7) : fNewImagePar->GetConc();
+    Double_t asym    = fMatrix ? GetVal(8) : fHillasExt->GetAsym();
+    const Double_t leakage = fMatrix ? GetVal(9): fNewImagePar->GetLeakage1();
+   
+
+    Double_t help;
+    if (!fMatrix)
+      help = TMath::Sign(fHilExt->GetM3Long(), fHilSrc->GetCosDeltaAlpha());
+
+  //    const Double_t asym0   = fMatrix ? GetVal(8) : help;
+//      const Double_t conc    = fMatrix ? GetVal(9) : fNewPar->GetConc();
+//      const Double_t leakage = fMatrix ? GetVal(10): fNewPar->GetLeakage1();
+
+    const Double_t newdist = dist0 * fMm2Deg;
+
+    const Double_t dist2   = meanx*meanx + meany*meany;
+    const Double_t dist    = sqrt(dist2) * fMm2Deg;
+    const Double_t dd2     = dist*dist;
+
+    const Double_t dmls    = log(size) - kNomLogSize;
+    Double_t dmls2   = dmls * dmls;
+
+    //const Double_t dmcza   = cos(theta/kRad2Deg) - kNomCosZA;
+
+    const Double_t length  = length0 * fMm2Deg;
+    const Double_t width   = width0  * fMm2Deg;
+    //const Double_t asym    = asym0   * fMm2Deg;
+ 
+   
+    double dmcza = 0;
+
+    if (	
+	newdist < CtsMCut (fSuper->GetDistUp(), dmls, dmls2, dmcza, dd2) &&
+        newdist > CtsMCut (fSuper->GetDistLo(), dmls, dmls2, dmcza, dd2) 
+       	) 
+	return kTRUE;
+
+ 
+    return kFALSE;
+}
+
+
+//  // ---------------------------------------------------------------------------
+//  //
+//  //
+//  //
+//  Double_t MMySuperCutsCalc::Calc(MMySuperCuts* super, MHillas* hillas, MHillasSrc* hillasSrc, MHadronness* hadronness)
+//  {
+    
+//      MGeomCamMagic cam;
+//      fMm2Deg = cam.GetConvMm2Deg();
+
+//      fSuper = super;  // Container with the optimazed cuts 
+//      fHil = hillas;   
+//      fHilSrc = hillasSrc; 
+//      fHadronness = hadronness; 
+
+//      Process();
+
+//      return fHadronness->GetHadronness();
+//  }
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCutsCalc.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCutsCalc.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/MMySuperCutsCalc.h	(revision 9772)
@@ -0,0 +1,114 @@
+#ifndef MARS_MMySuperCutsCalc
+#define MARS_MMySuperCutsCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MParList;
+class MHillas;
+class MHillasSrc;
+class MHillasExt;
+class MNewImagePar;
+class MMcEvt;
+class MCerPhotEvt;
+class MGeomCam;
+class MHadronness;
+class MHMatrix;
+class MMySuperCuts;
+class MPointingPos;
+class MNewImagePar;
+class MHillasExt;
+
+class MMySuperCutsCalc : public MTask
+{
+ private:
+
+    MHillas       *fHil;
+    MHillasSrc    *fHilSrc;
+    MHillasExt    *fHilExt;
+    MNewImagePar  *fNewPar;
+    MMcEvt        *fMcEvt;
+    MHadronness   *fHadronness; //! output container for hadronness
+    MMySuperCuts  *fSuper;      // container for supercut parameters
+    MPointingPos  *fPointingPos; 
+    MNewImagePar  *fNewImagePar;
+    MHillasExt    *fHillasExt;
+
+    TString  fHadronnessName;   // name of container to store hadronness
+    TString  fHilName;
+    TString  fHilSrcName;
+    TString  fHilExtName;
+    TString  fNewParName;
+    TString  fSuperName;        // name of container for supercut parameters
+
+    Double_t fMm2Deg;           //!
+
+    Int_t     fMap[11];         //!
+    MHMatrix *fMatrix;          //!
+
+    Bool_t fNoDistCut;
+    Float_t fSizeCutLow,fSizeCutUp ;
+
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Double_t GetVal(Int_t i) const;
+
+    Double_t CtsMCut(const Double_t* a, Double_t ls, Double_t ls2, Double_t ct, Double_t dd2) const;
+
+
+ public:
+    
+    MMySuperCutsCalc(const char *hilname="MHillas",
+                      const char *hilsrcname="MHillasSrc",
+                      const char *name=NULL, const char *title=NULL);
+
+    void SetHadronnessName(const TString name) { fHadronnessName = name; }
+    TString GetHadronnessName() const { return fHadronnessName; }
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping() { InitMapping(NULL); }
+
+   
+    /*  Double_t Calc(MMySuperCuts* super, MHillas* hillas, MHillasSrc* hillasSrc, MHadronness* hadronness); */
+
+    Bool_t CalcDistCut(MHillasSrc* hillasSrc);
+
+ 
+    void SetNoDistCut(Bool_t flag) { fNoDistCut = flag; }
+    void SetSizeCuts(Float_t sizeLow, Float_t sizeUp) 
+    {
+	fSizeCutLow = sizeLow;
+	fSizeCutUp = sizeUp;
+    }
+
+
+    ClassDef(MMySuperCutsCalc, 0) // A class to evaluate the Supercuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/Makefile	(revision 9772)
@@ -0,0 +1,62 @@
+##################################################################
+#
+#   subdirectory makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../../../Makefile.conf.$(OSTYPE)
+include ../../../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+CINT     = Ucm
+
+#------------------------------------------------------------------------------
+
+INCLUDES = -I. \
+	   -I../../../mbase \
+	   -I../../../mjobs \
+	   -I../../../mpedestal \
+	   -I../../../mbadpixels \
+	   -I../../../mfileio \
+           -I../../../mraw \
+           -I../../../manalysis \
+	   -I../../../mgui \
+	   -I../../../mgeom \
+	   -I../../../msignal \
+	   -I../../../mcalib \
+	   -I../../../mfilter \
+	   -I../../../mhbase \
+	   -I../../../mimage \
+	   -I../../../mpointing \
+	   -I../../../mcamera \
+	   -I../../../mhist \
+	   -I../../../mmc \
+	   -I../../../mreport \
+	   -I../../../mastro \
+	   -I../../../mdata \
+	   -I../../../mfbase \
+	   -I../../../mtools \
+	   -I../../../mtemp
+ 
+SRCFILES = \
+        MDataSetIter.cc \
+	MExtrapolatePointingPos.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../../../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+mrproper:	clean rmbak
+
+
+
+
+
+
+
+
Index: /tags/Mars-V0.9/mtemp/mucm/classes/UcmIncl.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/UcmIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/UcmIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtemp/mucm/classes/UcmLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/classes/UcmLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/classes/UcmLinkDef.h	(revision 9772)
@@ -0,0 +1,12 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+
+
+#pragma link C++ class MDataSetIter+;
+#pragma link C++ class MExtrapolatePointingPos+;
+
+#endif
Index: /tags/Mars-V0.9/mtemp/mucm/macros/OptimizeSuperCuts.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mucm/macros/OptimizeSuperCuts.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mucm/macros/OptimizeSuperCuts.C	(revision 9772)
@@ -0,0 +1,146 @@
+/*############################################################################
+  #
+  #  How to use:
+  #
+  #   - 1. From a hillas file select a training subsample, for a given size
+  #     range, with will be write into a MHMatrix. The the matrix will be read
+  #     and the optimization will start.
+  #     Once you've created the matrix you can set to false GenerateTrainMatrix
+  #     and start directly the optimization from reading the matrix.
+  #
+  #   - 2. It is recomended to start optimazing the static cuts and then, the 
+  #     dinanical cuts, this can be done:
+  #      -seting in 'TString initParams' the name of the previous optimization
+  #       results.
+  #      -and using the the funtion MMyFindSuperCuts.SetOptimizationMode(Mode)
+  #
+  #     The supercuts function used is:
+  #   
+  #      Length_low = par[0]*S1 + par[1]*S2 +par[2]*ZA +par[3]*dist*dist
+  #      Length_up  = par[4]*S1 + par[5]*S2 +par[6]*ZA +par[7]*dist*dist
+  #                 ....
+  #      and simiar with: Width, Dist,Asym, Conc, Leakage
+  #
+  #         where  S1 = log(size)-log(LowerSizeCut)
+  #                S2 = S1*S1
+  #                ZA = cos(theta/kRad2Deg) - 1;
+  #
+  #  NOTE:  Currently with neglect ZA depence, so we put ZA = 0;
+  #  -----
+  #
+  #     The optimization modes are:
+  #
+  #        Mode   0 = optimize only supercuts params,i.e. 
+  #                   only optimaze par0, par4, par8,..
+  #               1 = optimize only dynamical params, i.e. 
+  #                   all but par0, par4, par8
+  #           other = optimize all the params at the same time.  
+  #
+  #
+  #  Warning: Some times Minuit fails to converge, or its take too long. Then,
+  #           it's better to try again with diferent nuumber of parameter,
+  #           initial values or stepsizes.
+  #
+  #                                                 author: Marcos Lopez
+  #                                                   email: marcos@gae.ucm.es
+  ###########################################################################*/
+
+
+Bool_t GenerateTrainMatrix = kTRUE;
+
+void OptimizeSuperCuts()
+{
+
+    // --- Input -----------------------------------------
+
+    Int_t  Mode = 0;
+    Double_t SizeCutLow = 2000;
+    Double_t SizeCutUp = 1e7;
+
+    // Hillas file
+    TString datafile = "~/MAGIC/data/Period022/2004_10_10/CrabNebula_20041010_6_30-25.hillas.root";
+    
+    // Intermediate file to speed up otpimization (from the original hillas 
+    //file, a given number of events in a given size cut range will be stored 
+    //in a MHatrix)
+    TString matrixfile = "SC_matrix.150k.root";  // matrix with the 
+
+    // Output file where the supercuts parameters wiil be saved
+    TString outfile = "SC.150k.Above2000.root"; 
+
+
+    // File with the starting supercuts parameters (if any)
+    //
+    //TString initParams="~/MAGIC/results/SuperCutsParams/AllDynCutsParams_Above2000ph.150k.CrabNebula_20041010_6_30-25.root";
+    TString initParams="";
+
+    // Number of train events to use from hillas file
+    Int_t howmany = 150000;  
+
+    MH3 h3("");
+
+   
+    //
+    // fStepsizes 
+    // if == 0.0    the parameter will be fixed in the minimization
+    //    != 0.0    initial step sizes for the parameters
+    //
+    TArrayD fStepsizes(48);
+
+    // LengthUp
+    fStepsizes[0] = 0.1;
+    fStepsizes[1] = 0.1;
+    fStepsizes[2] = 0.1;
+    fStepsizes[3] = 0.1;
+    // LengthLo
+    fStepsizes[4]  = 0.1;
+    fStepsizes[5]  = 0.1;
+    fStepsizes[6]  = 0.1;
+    fStepsizes[7] = 0.1;
+    // WidthUp
+    fStepsizes[8] = 0.1;
+    fStepsizes[9] = 0.1;
+    fStepsizes[10] = 0.1;
+    fStepsizes[11] = 0.1;
+    // WidthLo
+    fStepsizes[12] = 0.1;
+    fStepsizes[13] = 0.1;
+    fStepsizes[14] = 0.1;
+    fStepsizes[15] = 0.1;
+    // DistUp
+    fStepsizes[16] = 0.1;
+    fStepsizes[17] = 0.1;
+    fStepsizes[18] = 0.1;
+    fStepsizes[19] = 0.;
+    // DistLo
+    fStepsizes[20] = 0.1;
+    fStepsizes[21] = 0.1;
+    fStepsizes[22] = 0.1;
+    fStepsizes[23] = 0.;
+
+    for(int i=24;i<48;i++)
+	fStepsizes[i] = .0;
+ 
+    //------------------------------------------------------
+
+
+    MMyFindSuperCuts a;
+    a.SetHadronnessName("MHadronness");
+    a.SetFilenameParam(outfile);
+    a.SetSizeCuts(SizeCutLow, SizeCutUp);
+
+    if(GenerateTrainMatrix)
+	a.DefineTrainMatrix(datafile, h3 ,howmany, matrixfile); 
+
+
+    a.ReadMatrix(matrixfile,"");
+    a.SetOptimizationMode(Mode);
+
+
+    //
+    // Start optimization
+    // 
+    a.FindParams(initParams,0,fStepsizes);
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/macros/singleCalib.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/macros/singleCalib.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/macros/singleCalib.C	(revision 9772)
@@ -0,0 +1,174 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  stdCalib.C
+//
+//  This macros is based on the calibration macro from Markus Gaug.
+//  It processes a Pedestal file and writes a file with the containers
+//
+//  Needed arguments are retrieved from the file "marsconfig".
+//  A typical config file looks like this:
+//   inpath:                  /data/MAGIC/Period015/rootdata/2004_03_21/
+//   outpath:                 /data/MAGIC/Period015/calibdata/2004_03_21/
+//   pedfile:                 21297
+//   calfile:                 21297
+//
+//  inpath:     is the path to the merpped root files
+//  outpath:    is the path where to store the F0 files
+//  pedfilexxx: specifies which pedestal files to use. If more then 1 file
+//              is specified, all files are processed but only 1 output file
+//              is written.
+//
+//  The macro searches for the pulser colour which corresponds to the calibration
+//  run number. If the run number is smaller than 20000, pulser colour "CT1"
+//  is assumed, otherwise, it searches for the strings "green", "blue", "uv" or
+//  "ct1" in the filenames. If no colour or multiple colours are found, the
+//  execution is aborted.
+//
+//  The container MBadPixelsCam is created and followed during the execution of the
+//  rest of the macro.
+//
+//  The container MCalibrationQECam is created and followed during the execution of the
+//  rest of the macro.
+//
+//  A loop over the calibration files is performed using the class MJCalibration.
+//  The call to MJCalibration skips the relative time calibration, which can be
+//  uncommented as well.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+
+//
+// Tell if you want to calibrate times:
+//
+static const  Bool_t useTimes = kTRUE;
+//static const  Bool_t useTimes = kFALSE;
+
+void singleCalib()
+{
+
+  // turn of colors for logging to a file
+  gLog.SetNoColors();
+
+  // Get configuration from the "marsconfig" configuration file.
+//  TEnv env("marsconfig");
+
+  // Here we get the input and output directory paths from the configuration
+  // file
+//  const char* inpath = env.GetValue("inpath",".");
+//  const char* outpath = env.GetValue("outpath",".");
+//  Int_t prun = env.GetValue( "pedfile", 0);
+//  Int_t crun = env.GetValue( "calfile", 0);
+  const char* inpath = "/data/MAGIC/Period016/rootdata2/2004_04_16";
+  const char* outpath = "/data/MAGIC/Period016/calibdata/2004_04_16";
+  Int_t prun = 22351;
+  Int_t crun = 22323;
+
+
+  //
+  // Choose the signal Extractor:
+  //
+  //  MExtractFixedWindowPeakSearch extractor;
+  //  MExtractSlidingWindow  extractor;
+   MExtractFixedWindow    extractor;
+
+  //
+  // Set Ranges or Windows
+  //
+   extractor.SetRange(3,14,3,14);
+  //  extractor.SetWindows(8,8);
+
+  //
+  // Choose the arrival time Extractor:
+  //
+  //  MExtractTimeHighestIntegral timeext;
+  MExtractTimeFastSpline timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(2,12,4,14);
+
+  MRunIter pruns;
+  MRunIter cruns;
+
+  pruns.AddRun(prun,inpath);
+  cruns.AddRun(crun,inpath);
+
+  gLog << "Perestal Runs: " << pruns.GetRunsAsString()  << " " << pruns.GetNumEntries() << endl;
+  gLog << "Calib Runs: " << cruns.GetRunsAsString()  << " " << cruns.GetNumEntries() << endl;
+
+  gStyle->SetOptStat(1);
+  gStyle->SetOptFit();
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+
+  MCalibrationQECam qecam;
+  MBadPixelsCam     badcam;
+
+  //
+  // If you want to exclude pixels from the beginning, read
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)
+  //
+//  badcam.AsciiRead("badpixels.dat");
+
+
+  /************************************/
+  /* LOOP1: READ PEDESTAL INFORMATION */
+  /************************************/
+  MJPedestal    pedloop;
+  pedloop.SetInput(&pruns);
+  pedloop.SetOutputPath(outpath);       // This is needed to read the pedestal container file
+
+  if (!pedloop.Process())
+    return;
+
+  /**********************************/
+  /* LOOP2: CALIBRATION COMPUTATION */
+  /**********************************/
+  MJCalibration calloop;
+
+  //
+  // If you want to calibrate the times as well, choose:
+  //
+  calloop.SetRelTimeCalibration(useTimes);
+  calloop.SetExtractor(&extractor);
+  calloop.SetTimeExtractor(&timeext);
+  calloop.SetInput(&cruns);
+  calloop.SetOutputPath(outpath);
+  calloop.SetDisplay(display);
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop.GetBadPixels());
+
+//  TObject::SetObjectStat(kTRUE);
+
+  calloop.Process(pedloop.GetPedestalCam());
+
+//  gObjectTable->Print();
+
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/macros/singlePed.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/macros/singlePed.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/macros/singlePed.C	(revision 9772)
@@ -0,0 +1,120 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Martin Merck, 05/2004 <mailto:merck@astro.uni-wuerzburg.de>
+!              Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  stdPed.C
+//
+//  This macros is based on the calibration macro from Markus Gaug.
+//  It processes a Pedestal file and writes a file with the containers
+//
+//  Needed arguments are retrieved from the file "marsconfig".
+//  A typical config file looks like this:
+//   inpath:                  /data/MAGIC/Period015/rootdata/2004_03_21/
+//   outpath:                 /data/MAGIC/Period015/calibdata/2004_03_21/
+//   pedfile001:              21297
+//
+//  inpath:     is the path to the merpped root files
+//  outpath:    is the path where to store the F0 files
+//  pedfilexxx: specifies which pedestal files to use. If more then 1 file
+//              is specified, all files are processed but only 1 output file
+//              is written.
+//
+//  The macro loops over the pedestal file using the class MJPedestal
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void singlePed()
+{
+  // turn of colors for logging to a file
+  gLog.SetNoColors();
+
+  const char* inpath = "/data/MAGIC/Period016/rootdata2/2004_04_16";
+  const char* outpath = "/data/MAGIC/Period016/calibdata/2004_04_16";
+  Int_t prun = 22351;
+
+  //
+  // Choose the signal Extractor:
+  //
+  //  MExtractFixedWindowPeakSearch extractor;
+  //  MExtractSlidingWindow  extractor;
+   MExtractFixedWindow    extractor;
+
+  //
+  // Set Ranges or Windows
+  //
+   extractor.SetRange(3,14,3,14);
+  //  extractor.SetWindows(8,8);
+
+  //
+  // Choose the arrival time Extractor:
+  //
+  //  MExtractTimeHighestIntegral timeext;
+  MExtractTimeFastSpline timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(2,12,4,14);
+
+  // Get all pedestal files to process
+  // You can specify up to 999 files in the marsconfig file
+  // all files are concatenated and processed as one single file.
+  MRunIter pruns;
+  pruns.AddRun(prun,inpath);
+
+  gStyle->SetOptStat(1);
+  gStyle->SetOptFit();
+
+  // We do not use any display here.
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+
+  /************************/
+  /* PEDESTAL COMPUTATION */
+  /************************/
+
+  MCalibrationQECam qecam;
+  MBadPixelsCam     badcam;
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  //
+  // If you want to exclude pixels from the beginning, read
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)
+  //
+//  badcam.AsciiRead("badpixels.dat");
+
+  MJPedestal pedloop;
+  pedloop.SetExtractor(&extractor);
+  pedloop.SetInput(&pruns);
+  pedloop.SetOutputPath(outpath);
+  pedloop.SetDisplay(display);
+  pedloop.SetBadPixels(badcam);
+
+  if (!pedloop.Process())
+    return;
+
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/macros/stdCalib.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/macros/stdCalib.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/macros/stdCalib.C	(revision 9772)
@@ -0,0 +1,167 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  stdCalib.C
+//
+//  This macros is based on the calibration macro from Markus Gaug.
+//  It processes a Pedestal file and writes a file with the containers
+//
+//  Needed arguments are retrieved from the file "marsconfig".
+//  A typical config file looks like this:
+//   inpath:                  /data/MAGIC/Period015/rootdata/2004_03_21/
+//   outpath:                 /data/MAGIC/Period015/calibdata/2004_03_21/
+//   pedfile:                 21297
+//   calfile:                 21297
+//
+//  inpath:     is the path to the merpped root files
+//  outpath:    is the path where to store the F0 files
+//  pedfilexxx: specifies which pedestal files to use. If more then 1 file
+//              is specified, all files are processed but only 1 output file
+//              is written.
+//
+//  The macro searches for the pulser colour which corresponds to the calibration
+//  run number. If the run number is smaller than 20000, pulser colour "CT1"
+//  is assumed, otherwise, it searches for the strings "green", "blue", "uv" or
+//  "ct1" in the filenames. If no colour or multiple colours are found, the
+//  execution is aborted.
+//
+//  The container MBadPixelsCam is created and followed during the execution of the
+//  rest of the macro.
+//
+//  The container MCalibrationQECam is created and followed during the execution of the
+//  rest of the macro.
+//
+//  A loop over the calibration files is performed using the class MJCalibration.
+//  The call to MJCalibration skips the relative time calibration, which can be
+//  uncommented as well.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+
+//
+// Tell if you want to calibrate times:
+//
+static const  Bool_t useTimes = kTRUE;
+//static const  Bool_t useTimes = kFALSE;
+
+void stdCalib()
+{
+
+  // turn of colors for logging to a file
+  gLog.SetNoColors();
+
+  // Get configuration from the "marsconfig" configuration file.
+  TEnv env("marsconfig");
+
+  // Here we get the input and output directory paths from the configuration
+  // file
+  const char* inpath = env.GetValue("inpath",".");
+  const char* outpath = env.GetValue("outpath",".");
+  Int_t prun = env.GetValue( "pedfile", 0);
+  Int_t crun = env.GetValue( "calfile", 0);
+
+
+  //
+  // Choose the signal Extractor:
+  //
+  //  MExtractFixedWindowPeakSearch extractor;
+  //  MExtractSlidingWindow  extractor;
+   MExtractFixedWindow    extractor;
+
+  //
+  // Set Ranges or Windows
+  //
+   extractor.SetRange(3,14,3,14);
+  //  extractor.SetWindows(8,8);
+
+  //
+  // Choose the arrival time Extractor:
+  //
+  //  MExtractTimeHighestIntegral timeext;
+  MExtractTimeFastSpline timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(2,12,4,14);
+
+  MRunIter pruns;
+  MRunIter cruns;
+
+  pruns.AddRun(prun,inpath);
+  cruns.AddRun(crun,inpath);
+
+  gStyle->SetOptStat(1);
+  gStyle->SetOptFit();
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+
+  MCalibrationQECam qecam;
+  MBadPixelsCam     badcam;
+
+  //
+  // If you want to exclude pixels from the beginning, read
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)
+  //
+//  badcam.AsciiRead("badpixels.dat");
+
+
+  /************************************/
+  /* LOOP1: READ PEDESTAL INFORMATION */
+  /************************************/
+  MJPedestal    pedloop;
+  pedloop.SetInput(&pruns);
+  pedloop.SetOutputPath(outpath);       // This is needed to read the pedestal container file
+
+  if (!pedloop.Process())
+    return;
+
+  /**********************************/
+  /* LOOP2: CALIBRATION COMPUTATION */
+  /**********************************/
+  MJCalibration calloop;
+
+  //
+  // If you want to calibrate the times as well, choose:
+  //
+  calloop.SetRelTimeCalibration(useTimes);
+  calloop.SetExtractor(&extractor);
+  calloop.SetTimeExtractor(&timeext);
+  calloop.SetInput(&cruns);
+  calloop.SetOutputPath(outpath);
+  calloop.SetDisplay(display);
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop.GetBadPixels());
+
+//  TObject::SetObjectStat(kTRUE);
+
+  calloop.Process(pedloop.GetPedestalCam());
+
+//  gObjectTable->Print();
+
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/macros/stdPed.C
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/macros/stdPed.C	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/macros/stdPed.C	(revision 9772)
@@ -0,0 +1,132 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Martin Merck, 05/2004 <mailto:merck@astro.uni-wuerzburg.de>
+!              Markus Gaug, 11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  stdPed.C
+//
+//  This macros is based on the calibration macro from Markus Gaug.
+//  It processes a Pedestal file and writes a file with the containers
+//
+//  Needed arguments are retrieved from the file "marsconfig".
+//  A typical config file looks like this:
+//   inpath:                  /data/MAGIC/Period015/rootdata/2004_03_21/
+//   outpath:                 /data/MAGIC/Period015/calibdata/2004_03_21/
+//   pedfile001:              21297
+//
+//  inpath:     is the path to the merpped root files
+//  outpath:    is the path where to store the F0 files
+//  pedfilexxx: specifies which pedestal files to use. If more then 1 file
+//              is specified, all files are processed but only 1 output file
+//              is written.
+//
+//  The macro loops over the pedestal file using the class MJPedestal
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void stdPed()
+{
+  // turn of colors for logging to a file
+  gLog.SetNoColors();
+
+  // Get configuration from the "marsconfig" configuration file.
+  TEnv env("marsconfig");
+
+  // Here we get the input and output directory paths from the configuration
+  // file
+  const char* inpath = env.GetValue("inpath",".");
+  const char* outpath = env.GetValue("outpath",".");
+
+  //
+  // Choose the signal Extractor:
+  //
+  //  MExtractFixedWindowPeakSearch extractor;
+  //  MExtractSlidingWindow  extractor;
+   MExtractFixedWindow    extractor;
+
+  //
+  // Set Ranges or Windows
+  //
+   extractor.SetRange(3,14,3,14);
+  //  extractor.SetWindows(8,8);
+
+  //
+  // Choose the arrival time Extractor:
+  //
+  //  MExtractTimeHighestIntegral timeext;
+  MExtractTimeFastSpline timeext;
+  //
+  // Set Ranges or Windows
+  //
+  timeext.SetRange(2,12,4,14);
+
+  // Get all pedestal files to process
+  // You can specify up to 999 files in the marsconfig file
+  // all files are concatenated and processed as one single file.
+  MRunIter pruns;
+  char str[11];
+  for( Int_t i = 1 ; i<1000; i++)
+  {
+     sprintf( str, "pedfile%03d", i);
+     Int_t prun = env.GetValue( str, 0);
+     if( prun == 0)
+        break;
+     pruns.AddRun(prun,inpath);
+  }
+
+  gStyle->SetOptStat(1);
+  gStyle->SetOptFit();
+
+  // We do not use any display here.
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+
+  /************************/
+  /* PEDESTAL COMPUTATION */
+  /************************/
+
+  MCalibrationQECam qecam;
+  MBadPixelsCam     badcam;
+  MGeomCamMagic     geomcam;
+  MGeomApply        geomapl;
+  //
+  // If you want to exclude pixels from the beginning, read
+  // an ascii-file with the corr. pixel numbers (see MBadPixelsCam)
+  //
+//  badcam.AsciiRead("badpixels.dat");
+
+  MJPedestal pedloop;
+  pedloop.SetExtractor(&extractor);
+  pedloop.SetInput(&pruns);
+  pedloop.SetOutputPath(outpath);
+  pedloop.SetDisplay(display);
+  pedloop.SetBadPixels(badcam);
+
+  if (!pedloop.Process())
+    return;
+
+}
+
+
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/mklinks
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/mklinks	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/mklinks	(revision 9772)
@@ -0,0 +1,57 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Martin Merck  05/2004 <mailto:merck@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2004
+#
+#
+# ========================================================================
+
+#/////////////////////////////////////////////////////////////////////////////
+#
+# mklinks
+#
+# This scripts creates in the local directors (directory where it is executed)
+# a series of subdirectories for each date in which links to the rawdata are created.
+# Normaly this script is used in a directory called rawdata2 to create links to
+# the rawdata files.
+# With a second script calle mklinksyy links to the ying-yang corrected files are
+# created and the corresponing links overwritten. In this way the subdirectory
+# rawdata2 will contain the correct links to the yy-files where necesary and the
+# original rawdata files, when no yy correction was necessary.
+#
+DATES=`ls -d -1 ../rawdata/20* | cut -d/ -f3 '-'`
+for DATE in $DATES
+do
+  OUTDIR=./$DATE
+  if [ ! -d $OUTDIR ]
+  then
+    echo $DATE
+    mkdir $OUTDIR
+  fi
+
+  cd $DATE
+  RAWFILES=`ls -1 ../../rawdata/$DATE/*.raw`
+  for i in $RAWFILES
+  do
+    ln -s $i `echo $i | cut -d/ -f5`
+  done
+  cd ..
+done
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/mklinksyy
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/mklinksyy	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/mklinksyy	(revision 9772)
@@ -0,0 +1,57 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Martin Merck  05/2004 <mailto:merck@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2004
+#
+#
+# ========================================================================
+
+#/////////////////////////////////////////////////////////////////////////////
+#
+# mklinksyy
+#
+# This scripts creates in the local directors (directory where it is executed)
+# a series of subdirectories for each date in which links to the rawdata are created.
+# Normaly this script is used in a directory called rawdata2 to create links to
+# the ying-yang corrected rawdata files.
+# Already existing links are overwritten. Normally first the script mklinks should 
+# be executed and then this script to overwrite the links for the yy corected rawdata
+# files.
+#
+IN_DIR=/mcdata/yin_yang/Period015/rawdata
+DATES=`ls -d -1 $IN_DIR/20* | cut -d/ -f6 '-'`
+for DATE in $DATES
+do
+  OUTDIR=./$DATE
+  if [ ! -d $OUTDIR ]
+  then
+    echo $DATE
+    mkdir $OUTDIR
+  fi
+
+  cd $DATE
+  RAWFILES=`ls -1 $IN_DIR/$DATE/*.raw`
+  for i in $RAWFILES
+  do
+    ln -f -s $i `echo $i | cut -d/ -f7`
+  done
+  cd ..
+done
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/runmerpp
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/runmerpp	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/runmerpp	(revision 9772)
@@ -0,0 +1,111 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Martin Merck  05/2004 <mailto:merck@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2004
+#
+#
+# ========================================================================
+
+#/////////////////////////////////////////////////////////////////////////////
+#
+# runmerpp
+#
+# This scripts is used to run merpp on a full Period of data. It will run merpp
+# on the raw-data file. Then it will update the root file by merpping in the CC
+# and CACO data.
+# As for some rawdata files no CaCo data files exist (due to DAQ restarting a run)
+# we need to use the previous CaCo file. This will add to much dc-current infos
+# to the merpped file, but will gaurantee that the right dc-currents are always
+# available.
+#
+# TODO:
+#  Due to problems with the DB the automatic DB update option is still disabled.
+#
+
+# ------------------------------------
+# Which Period to use
+INDIR=/data/MAGIC/Period015
+# ------------------------------------
+#
+# For each day of this Period
+#
+DATES=`ls -d -1 $INDIR/rawdata2/20* | cut -d/ -f6 '-'`
+for DATE in $DATES
+do
+  OUTDIR=$INDIR/rootdata2/$DATE
+# Create Output Directory 
+  if [ ! -d $OUTDIR ]
+  then
+    echo $DATE
+    mkdir $OUTDIR
+  fi
+
+#
+# Loop over all raw files for this day
+#
+  RAWFILES=`ls -1 $INDIR/rawdata2/$DATE/*.raw`
+  LOGFILE=$OUTDIR/merpp.log
+  TIME=`date`
+  echo "-----------------------------------------------------------------" > $LOGFILE
+  echo " MERPP run started $TIME" >> $LOGFILE
+  echo "-----------------------------------------------------------------" >> $LOGFILE
+
+  PREVIOUS_CACO=
+  for i in $RAWFILES
+  do
+    TIMER=$SECONDS
+    IN_FILE=$i
+    RUN_NUM=`echo $i | cut -d_ -f4` 
+    CC_FILE=`ls -1 $INDIR/ccdata/$DATE/*$RUN_NUM*.rep`
+    CACO_FILE=`ls -1 $INDIR/cacodata/$DATE/*$RUN_NUM*.txt 2> /dev/null`
+    OUT_FILE=$OUTDIR/`echo $i | cut -d/ -s -f7 '-' | cut -d. -s -f1 '-'`.root
+#    merpp -a -f --sql=mysql://hercules:d99swMT\!@hercules $IN_FILE $OUT_FILE >> $LOGFILE
+
+#   MERPP the raw data file
+    merpp -a -f $IN_FILE $OUT_FILE >> $LOGFILE
+
+#   MERPP the CC report file
+    merpp -a -u $CC_FILE $OUT_FILE >> $LOGFILE
+
+#   If a CACO file exists for this run
+#   MERPP the CACO file.
+    if [ -n "$CACO_FILE" ]
+    then
+      merpp -a -u $CACO_FILE $OUT_FILE >> $LOGFILE
+      PERVIOUS_CACO=$CACOFILE
+    fi
+
+#   If no CACO file is available for this run
+#   we use the previous CACO file
+#   CACO only nows when CC starts a new run and creates 1 file for this run
+#   however the DAQ may create more subruns due to errors or limitaation on the 
+#   filesize. The relevant CACO information should be in the CACO file created
+#   when CC started this run (e.g. the previous CACO file)
+    if [ -z "$CACO_FILE" ]
+    then
+      if [ -n "$PREVIOUS_CACO" ]
+      then
+        merpp -a -u $PREVIOUS_CACO $OUT_FILE >> $LOGFILE
+      fi
+    fi  
+    echo "Processed file $IN_FILE in $(( $SECONDS - $TIMER)) secs."
+  done
+done
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/runped
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/runped	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/scripts/runped	(revision 9772)
@@ -0,0 +1,72 @@
+#!/bin/sh
+#
+# ========================================================================
+#
+# *
+# * This file is part of MARS, the MAGIC Analysis and Reconstruction
+# * Software. It is distributed to you in the hope that it can be a useful
+# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+# * It is distributed WITHOUT ANY WARRANTY.
+# *
+# * Permission to use, copy, modify and distribute this software and its
+# * documentation for any purpose is hereby granted without fee,
+# * provided that the above copyright notice appear in all copies and
+# * that both that copyright notice and this permission notice appear
+# * in supporting documentation. It is provided "as is" without express
+# * or implied warranty.
+# *
+#
+#
+#   Author(s): Martin Merck  05/2004 <mailto:merck@astro.uni-wuerzburg.de>
+#
+#   Copyright: MAGIC Software Development, 2000-2004
+#
+#
+# ========================================================================
+
+#/////////////////////////////////////////////////////////////////////////////
+#
+# runped
+#
+# This scripts runs the macro "stdPed.C" for all files of a period.
+# It writes the data card file "marsconfig" for each pedestal file which shall.
+# be processed and then calls root to execute the macro in batch mode.
+#
+#
+BASEPATH=/data/MAGIC/Period015
+ROOTDIR=rootdata2
+
+DATES=`ls -d -1 $BASEPATH/$ROOTDIR/20* | cut -d/ -f6 '-'`
+for DATE in $DATES
+do
+
+  INDIR=$BASEPATH/$ROOTDIR/$DATE/
+  OUTDIR=$BASEPATH/calibdata/$DATE/
+  if [ ! -d $OUTDIR ]
+  then
+    echo $DATE
+    mkdir $OUTDIR
+  fi
+
+  PEDFILES=`ls -1 $INDIR/*_P_*.root | cut -d_ -f4 '-'`
+
+  MARSFILE=./marsconfig
+  LOGFILE=$OUTDIR/Pedestal.log
+
+  TIME=`date`
+  echo "-----------------------------------------------------------------" > $LOGFILE
+  echo " PEDESTAL calc started $TIME" >> $LOGFILE
+  echo "-----------------------------------------------------------------" >> $LOGFILE
+
+#
+# For each pedestal file, create the "marsconfig" data card file
+# and run the macro "stdPed.C" in root using batch mode
+#
+  for I in $PEDFILES
+  do
+    echo "inpath:                  $INDIR" > $MARSFILE
+    echo "outpath:                 $OUTDIR" >> $MARSFILE
+    echo "pedfile001:              $I" >> $MARSFILE
+    root -b -l -q stdPed.C >> $LOGFILE
+  done
+done
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.cpp
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.cpp	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.cpp	(revision 9772)
@@ -0,0 +1,83 @@
+// DCCurrentEvent.cpp: Implementiberung der Klasse DCCurrentEvent.
+//
+//////////////////////////////////////////////////////////////////////
+
+#ifndef DCCURRENTEVENT_INCLUDED
+#include "DCCurrentEvent.h"
+#endif
+#ifndef GLOBALS_INCLUDED
+#include "Globals.h"
+#endif
+
+#include <sstream>
+#include <istream>
+#include <ostream>
+#include <iostream>
+#include <iomanip>
+#include <iterator>
+#include <vector>
+
+extern int gYear, gMonth, gDay;
+
+//////////////////////////////////////////////////////////////////////
+// Konstruktion/Destruktion
+//////////////////////////////////////////////////////////////////////
+
+DCCurrentEvent::DCCurrentEvent()
+{
+    m_dcValues.reserve( Globals::CAMERA_PIXELS );
+    
+}
+
+DCCurrentEvent::~DCCurrentEvent()
+{
+}
+
+std::istream& operator >> ( std::istream& in, DCCurrentEvent& event )
+{
+    using std::string;
+    using std::getline;
+
+    // read the starting tag
+    string tag;
+    in >> tag;
+    if ( tag != "DC")
+    {
+        in.clear( std::ios_base::badbit);
+        return in;
+    }
+
+    // read error codes
+    in >> event.m_dcError1 >> event.m_dcError2;
+
+    // read in the timestamp
+    in >> event.m_dcHour >> event.m_dcMin >> event.m_dcSec >> event.m_dcMSec;
+
+    getline( in, event.m_dcCurr );
+
+    return in;
+}
+
+std::ostream& operator << ( std::ostream& out, const DCCurrentEvent& event )
+{
+    using namespace std;
+
+    out << "DC-REPORT ";
+    out << setfill('0') << right << resetiosflags(ios_base::showpos);
+    out << setw(2) << 0 << ' ';
+    out << setw(4) << gYear << ' ';
+    out << setw(2) << gMonth << ' ';
+    out << setw(2) << gDay << ' ';
+    out << setw(2) << event.m_dcHour << ' ';
+    out << setw(2) << event.m_dcMin  << ' ';
+    out << setw(2) << event.m_dcSec  << ' ';
+    out << setw(3) << event.m_dcMSec << ' ';
+
+    out << setfill('0') << internal << setiosflags(ios_base::showpos);
+    out << setw(3) << event.m_dcError1 << " ";
+    out << setw(3) << event.m_dcError2;
+    out << setfill('0') << right << resetiosflags(ios_base::showpos);
+
+    out << event.m_dcCurr;
+    return out;
+}
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/DCCurrentEvent.h	(revision 9772)
@@ -0,0 +1,38 @@
+// DCCurrentEvent.h: Schnittstelle für die Klasse DCCurrentEvent.
+//
+//////////////////////////////////////////////////////////////////////
+
+#if !defined(DCCURRENTEVENT_INCLUDED)
+#define DCCURRENTEVENT_INCLUDED
+
+#include <ctime>
+#include <vector>
+#include <string>
+#include <istream>
+#include <ostream>
+
+class DCCurrentEvent
+{
+    friend std::istream& operator >> ( std::istream& in, DCCurrentEvent& event );
+    friend std::ostream& operator << ( std::ostream& out, const DCCurrentEvent& event );
+
+private:
+    int	       		m_dcError1;
+    int	       		m_dcError2;
+    int	       		m_dcHour;
+    int	       		m_dcMin;
+    int	       		m_dcSec;
+    int	       		m_dcMSec;
+    time_t     		m_dcTime;
+    std::string       m_dcCurr;
+    std::vector<int>	m_dcValues;
+
+public:
+	DCCurrentEvent();
+	virtual ~DCCurrentEvent();
+};
+
+std::istream& operator >> ( std::istream& in, DCCurrentEvent& event );
+std::ostream& operator << ( std::ostream& out, const DCCurrentEvent& event );
+
+#endif // !defined(DCCURRENTEVENT_INCLUDED)
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/Globals.h
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/Globals.h	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/Globals.h	(revision 9772)
@@ -0,0 +1,20 @@
+// Globals.h: Global variables
+//            We use a class to hold these global values
+//            in order not to pollute the global namespace
+//
+//////////////////////////////////////////////////////////////////////
+
+#if !defined(GLOBALS_INCLUDED)
+#define GLOBALS_INCLUDED
+
+class Globals  
+{
+public:
+	enum {CAMERA_PIXELS = 577};
+
+private:
+	Globals();				// prevent inadvertent instantiation
+
+};
+
+#endif // !defined(GLOBALS_INCLUDED)
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/Makefile
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/Makefile	(revision 9772)
@@ -0,0 +1,116 @@
+##################################################################
+#
+# makefile
+#
+# @file        makefile
+# @title       Converter of DCCurrent files to new format
+# @author      M Merck
+# @email       merck@astro.uni-wuerzburg.de
+# @date        Wed Dec 17 11:51:11 MET 2003
+#
+#_______________________________________________________________
+#
+# Created: Wed Dec 17 11:51:11 MET 2003
+# Author:  Martin Merck
+# Purpose: Makefile for the compilation of dcconvertor
+# Notes:   
+#    
+##################################################################
+
+# @code
+
+# compilers & tools
+
+CC            = gcc
+CXX           = g++
+F77           = g77
+
+INCLUDES = -I.
+
+OPTIM    =
+DEBUG    = -g
+
+# compilation and linking flags
+
+CXXFLAGS  = ${INCLUDES} ${OPTIM} ${DEBUG}
+CFLAGS    = ${CXXFLAGS}
+FFLAGS    = ${CXXFLAGS}
+LIBS      =
+
+#------------------------------------------------------------------------------
+
+#.SILENT:
+
+.SUFFIXES: .c .cxx .cpp .C .c++ .h .hxx .H .h++ .o .so .f
+
+SRCS = \
+	main.cpp \
+	DCCurrentEvent.cpp
+
+HEADERS = \
+	DCCurrentEvent.h \
+	Globals.h
+
+OBJS = \
+	DCCurrentEvent.o \
+	main.o
+
+PROGRAM=dcconvertor
+
+############################################################
+
+all: ${PROGRAM}
+
+depend:
+	@makedepend $(SRCS) -fMakefile 2> /dev/null
+
+${PROGRAM}: $(OBJS)
+	@echo "Linking..." $@
+	$(CXX) $(CXXFLAGS) $(OBJS) $(LIBS) -o $@
+	@echo "done."
+
+.cxx.o:
+	@echo "Compiling " $<
+	$(CXX) $(CXXFLAGS) -c $< -o $@
+
+.c.o:
+	@echo "Compiling " $<
+	$(CC) $(CFLAGS) -c $< -o $@
+
+.f.o:
+	@echo "Compiling " $<
+	$(F77) $(FFLAGS) -c $< -o $@
+
+lclean:
+	@echo "Cleanning..."
+	@rm -f *.o core
+
+clean:
+	@echo "Cleanning..."
+	@rm -f $(OBJS) core 
+
+mrproper: clean
+	@echo "Mr.Proper in action . . ."
+	@rm -f $(PROGRAM)
+
+ctags:
+	@echo "Creating CTAGS file . . ."
+	@ctags -txw $(SRCS) $(HEADERS) > CTAGS
+
+etags:
+	@echo "Creating TAGS file . . ."
+	@etags -C $(SRCS) $(HEADERS)
+
+listsrc:
+	@ls -m $(SRCS) $(HEADERS) | sed 's/,//g'
+
+redo: clean all
+
+# @endcode
+# DO NOT DELETE
+
+main.o: Globals.h /usr/include/stdlib.h /usr/include/features.h
+main.o: /usr/include/sys/cdefs.h /usr/include/gnu/stubs.h
+main.o: /usr/lib/gcc-lib/i486-suse-linux/3.3/include/stddef.h
+main.o: DCCurrentEvent.h
+DCCurrentEvent.o: DCCurrentEvent.h Globals.h
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/main.cpp
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/main.cpp	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/main.cpp	(revision 9772)
@@ -0,0 +1,57 @@
+/***************************************************************************
+                          main.cpp  -  description
+                             -------------------
+    begin                : Tue Dec  9 12:05:18 CET 2003
+    copyright            : (C) 2003 by Martin Merck
+    email                : merck@astro.uni-wuerzburg.de
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *   This program is part of the MAGIC Software  * ***************************************************************************/
+
+#ifndef GLOBALS_INCLUDED
+#include "Globals.h"
+#endif
+
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <iterator>
+#include <string>
+#include <stdlib.h>
+#include "DCCurrentEvent.h"
+
+using namespace std;
+
+int gYear, gMonth, gDay;
+
+void usage();
+
+int main(int argc, char *argv[])
+{
+  if (argc != 3)
+     usage();
+
+  string dcFileName( argv[1] );
+  string date = dcFileName.substr( dcFileName.rfind( "dc_" ) + 3, 10 );
+  sscanf( date.c_str(), "%d_%d_%d", &gYear, &gMonth, &gDay);
+  cout << gYear << ":" << gMonth << ":" << gDay << endl;
+  
+  
+  std::ifstream input( argv[1] );
+  ofstream output( const_cast<const char *> (argv[2]) );
+
+  copy( istream_iterator<DCCurrentEvent>( input ),
+        istream_iterator<DCCurrentEvent>(),
+        ostream_iterator<DCCurrentEvent>( output, "\n") );
+
+  return EXIT_SUCCESS;
+}
+
+void usage()
+{
+  cerr << "USAGE: dcconvertor <input file> <output file>" << endl;
+  exit( EXIT_FAILURE );
+}
+  
Index: /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/rundcconv
===================================================================
--- /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/rundcconv	(revision 9772)
+++ /tags/Mars-V0.9/mtemp/mwuerzburg/tools/dcconverter/rundcconv	(revision 9772)
@@ -0,0 +1,43 @@
+#!/bin/sh
+# Script to convert DC current files from the old format to the new format
+#
+PS3="Select the Date for which MERPP should run? "
+DATES=`ls -d -1 ./cacodata_old/20* | cut -d/ -f3 '-'`
+select DATE in $DATES "Exit"; do
+	break
+done
+if [ "$DATE" = "Exit" ]
+then
+  exit
+fi
+
+INDIR=./cacodata_old/$DATE
+OUTDIR=./cacodata/$DATE
+if [ -d $OUTDIR ]
+then
+  echo "An output directory for the date $DATE already"
+  echo "exists. Please be sure that you selected the"
+  echo "correct date. If you want to rerun MERPP on this"
+  echo "date please delete the directory and all files it"
+  echo "contains from the rootfiles directory."
+  exit
+fi
+echo $DATE
+mkdir ./cacodata/$DATE
+
+LOGFILE=$OUTDIR/dcconv.log
+CACOFILES=`ls -1 $INDIR/dc_*.txt`
+
+TIME=`date`
+echo "-----------------------------------------------------------------" > $LOGFILE
+echo " dcconvertor run started $TIME" >> $LOGFILE
+echo "-----------------------------------------------------------------" >> $LOGFILE
+
+for i in $CACOFILES
+do
+  IN_FILE=$i
+  OUT_FILE=$OUTDIR/$i
+  dcconvertor $IN_FILE $OUT_FILE
+  echo $IN_FILE >> $LOGFILE
+  echo "Processed file $IN_FILE in $SECONDS secs."
+done
Index: /tags/Mars-V0.9/mtools/MChisqEval.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MChisqEval.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MChisqEval.cc	(revision 9772)
@@ -0,0 +1,155 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 07/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MChisqEval.h"
+
+#include <fstream>
+
+#include "MDataChain.h"
+#include "MParameters.h" // MParameterD
+
+#include "MParList.h"
+
+ClassImp(MChisqEval);
+
+using namespace std;
+
+void MChisqEval::StreamPrimitive(ofstream &out) const
+{
+    out << "   MChisqEval " << GetUniqueName() << ";";
+    if (fData0)
+        out << "   " << GetUniqueName() << ".SetY1(\"" << fData0->GetRule() << "\");" << endl;
+    if (fData1)
+        out << "   " << GetUniqueName() << ".SetY1(\"" << fData1->GetRule() << "\");" << endl;
+}
+
+MChisqEval::MChisqEval(const char *name, const char *title) : fData0(NULL), fData1(NULL)// : fMatrix(mat), fColumn(col), fEvalE(evale)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+MChisqEval::MChisqEval(MData *y1, const char *name, const char *title) : fData0(NULL), fData1(NULL)// : fMatrix(mat), fColumn(col), fEvalE(evale)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+    SetY1(y1);
+}
+
+MChisqEval::MChisqEval(MData *y1, MData *y2, const char *name, const char *title) : fData0(NULL), fData1(NULL)// : fMatrix(mat), fColumn(col), fEvalE(evale)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+    SetY1(y1);
+    SetY2(y2);
+}
+
+MChisqEval::~MChisqEval()
+{
+    if (fData0 && (fData0->TestBit(kCanDelete) || TestBit(kIsOwner)))
+        delete fData0;
+
+    if (fData1 && (fData1->TestBit(kCanDelete) || TestBit(kIsOwner)))
+        delete fData1;
+}
+
+void MChisqEval::SetY1(MData *data)
+{
+    // Set MC value
+    if (fData0 && (fData0->TestBit(kCanDelete) || TestBit(kIsOwner)))
+        delete fData0;
+    fData0 = data;
+    fData0->SetBit(kCanDelete);
+    AddToBranchList(fData0->GetDataMember());
+}
+
+void MChisqEval::SetY2(MData *data)
+{
+    // Set measured/estimated value
+    if (fData1 && (fData1->TestBit(kCanDelete) || TestBit(kIsOwner)))
+        delete fData1;
+    fData1 = data;
+    fData1->SetBit(kCanDelete);
+    AddToBranchList(fData1->GetDataMember());
+}
+
+void MChisqEval::SetY1(const TString data)
+{
+    SetY1(new MDataChain(data));
+}
+
+void MChisqEval::SetY2(const TString data)
+{
+    SetY2(new MDataChain(data));
+}
+
+Int_t MChisqEval::PreProcess(MParList *plist)
+{
+    fChisq = 0;
+
+    if (!fData0)
+        return kFALSE;
+
+    if (!fData0->PreProcess(plist))
+        return kFALSE;
+
+    if (fData1)
+        if (!fData1->PreProcess(plist))
+            return kFALSE;
+
+    fResult = (MParameterD*)plist->FindCreateObj("MParameterD", "MFitResult");
+    if (!fResult)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Int_t MChisqEval::Process()
+{
+    const Double_t y1 = fData0->GetValue();
+    const Double_t y2 = fData1 ? fData1->GetValue() : 0;
+
+    const Double_t dy  = y2-y1;
+    const Double_t err = fData1 ? y1*y1 : 1;
+
+    fChisq += dy*dy/err;
+    return kTRUE;
+}
+
+Int_t MChisqEval::PostProcess()
+{
+    fChisq /= GetNumExecutions();
+
+    fResult->SetVal(fChisq);
+
+    return kTRUE;
+}
+
+const TString MChisqEval::gsDefName  = "MChisqEval";
+const TString MChisqEval::gsDefTitle = "Evaluate a chisq";
+
Index: /tags/Mars-V0.9/mtools/MChisqEval.h
===================================================================
--- /tags/Mars-V0.9/mtools/MChisqEval.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MChisqEval.h	(revision 9772)
@@ -0,0 +1,55 @@
+#ifndef MARS_MChisqEval
+#define MARS_MChisqEval
+
+#ifndef ROOT_MTask
+#include "MTask.h"
+#endif
+
+class MData;
+class MParameterD;
+
+class MChisqEval : public MTask
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+    Double_t     fChisq;  //! Evaluated chi square
+    MParameterD *fResult; //! Storage for result
+
+    MData   *fData0; // Data Member one (monte carlo data or chisq function)
+    MData   *fData1; // Data Member two (measured data)
+
+    // --------------------------------------------------------------------------
+    //
+    // Implementation of SavePrimitive. Used to write the call to a constructor
+    // to a macro. In the original root implementation it is used to write
+    // gui elements to a macro-file.
+    //
+    void StreamPrimitive(ofstream &out) const;
+
+    enum { kIsOwner = BIT(14) };
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MChisqEval(const char *name=NULL, const char *title=NULL);
+    MChisqEval(MData *y1, const char *name=NULL, const char *title=NULL);
+    MChisqEval(MData *y1, MData *y2, const char *name=NULL, const char *title=NULL);
+    ~MChisqEval();
+
+    void SetY1(MData *data);
+    void SetY2(MData *data);
+    void SetY1(const TString data);
+    void SetY2(const TString data);
+
+    void SetOwner(Bool_t o=kTRUE) { o ? SetBit(kIsOwner) : ResetBit(kIsOwner); }
+
+    Double_t GetChisq() const { return fChisq; }
+ 
+    ClassDef(MChisqEval, 0)
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MCubicCoeff.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MCubicCoeff.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MCubicCoeff.cc	(revision 9772)
@@ -0,0 +1,219 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Sebastian Raducci 01/2004  <mailto:raducci@fisica.uniud.it>
+!
+!   Copyright: MAGIC Software Development, 2001-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  Cubic Spline Interpolation
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCubicCoeff.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCubicCoeff);
+
+using namespace std;
+
+//----------------------------------------------------------------------------
+//
+// Constructor (The spline is: fA(x-fX)3+fB(x-fX)2+fC(x-fX)+fY
+// where x is the independent variable, 2 and 3 are exponents
+//
+MCubicCoeff::MCubicCoeff(Double_t x, Double_t xNext, Double_t y, Double_t yNext, 
+			 Double_t a, Double_t b, Double_t c) : 
+    fX(x), fXNext(xNext), fA(a), fB(b), fC(c), fY(y), fYNext(yNext)
+{
+    fH = fXNext - fX;
+    if (EvalMinMax())
+        return;
+
+    gLog << warn << "Failed to eval interval Minimum and Maximum, returning zeros" << endl;
+    fMin = 0;
+    fMax = 0;
+}
+
+//----------------------------------------------------------------------------
+//
+// Evaluate the spline at a given point
+//
+
+Double_t MCubicCoeff::Eval(Double_t x)
+{
+    const Double_t dx = x - fX;
+    return fY + dx*(fC + dx*(fB + dx*fA));
+}
+
+//----------------------------------------------------------------------------
+//
+// Find min and max using derivatives. The min and max could be at the begin
+// or at the end of the interval or somewhere inside the interval (in this case
+// a comparison between the first derivative and zero is made)
+// The first derivative coefficients are obviously: 3*fA, 2*fB, fC
+//
+Bool_t MCubicCoeff::EvalMinMax()
+{
+    fMin = fY;
+    fMax = fY;
+
+    fAbMin = fX;
+    fAbMax = fX;
+
+    if (fYNext < fMin)
+    {
+	fMin   = fYNext;
+	fAbMin = fXNext;
+    }
+    if (fYNext > fMax)
+    {
+	fMax   = fYNext;
+	fAbMax = fXNext;
+    }
+
+    const Double_t delta = fB*fB*4 - fA*fC*12;
+    if (delta >= 0 && fA != 0)
+    {
+        const Double_t sqrtDelta = TMath::Sqrt(delta);
+
+        const Double_t xPlus  = (-fB*2 + sqrtDelta)/(fA*6);
+        const Double_t xMinus = (-fB*2 - sqrtDelta)/(fA*6);
+
+        if (xPlus >= 0 && xPlus <= fH)
+        {
+            const Double_t tempMinMax = Eval(fX+xPlus);
+            if (tempMinMax < fMin)
+            {
+                fMin = tempMinMax;
+                fAbMin = fX + xPlus;
+            }
+            if (tempMinMax > fMax)
+            {
+                fMax = tempMinMax;
+                fAbMax = fX + xPlus;
+            }
+        }
+        if (xMinus >= 0 && xMinus <= fH)
+        {
+            const Double_t tempMinMax = Eval(fX+xMinus);
+            if (tempMinMax < fMin)
+            {
+                fMin = tempMinMax;
+                fAbMin = fX + xMinus;
+            }
+            if (tempMinMax > fMax)
+            {
+                fMax = tempMinMax;
+                fAbMax = fX + xMinus;
+            }
+        }
+        return kTRUE;
+    }
+
+    /* if fA is zero then we have only one possible solution */
+    if (fA == 0 && fB != 0)
+    {
+        const Double_t xSolo = -fC/(fB*2);
+
+        if (xSolo < 0 || xSolo > fH)
+            return kTRUE;
+
+        const Double_t tempMinMax = Eval(fX+xSolo);
+        if (tempMinMax < fMin)
+        {
+            fMin = tempMinMax;
+            fAbMin = fX + xSolo;
+        }
+        if (tempMinMax > fMax)
+        {
+            fMax = tempMinMax;
+            fAbMax = fX + xSolo;
+        }
+        return kTRUE;
+    }
+
+    return kTRUE;
+}
+//-------------------------------------------------------------------------
+//
+// Given y finds x using the cubic (cardan) formula.
+//
+// we consider the following form: x3 + ax2 + bx + c = 0 where
+//   a = fB/fA, b = fC/fA, c = (fY - y)/fA  
+//
+// There could be three or one real solutions
+//
+Short_t MCubicCoeff::FindCardanRoot(Double_t y, Double_t *x)
+{
+    const Double_t a = fB/fA;
+    const Double_t b = fC/fA;
+    const Double_t c = (fY - y)/fA;
+
+    const Double_t q = (a*a - b*3)/9;
+    const Double_t r = (a*a*a*2 - a*b*9 + c*27)/54;
+
+    const Double_t aOver3 = a/3;
+    const Double_t r2 = r*r;
+    const Double_t q3 = q*q*q;
+    
+    if (r2 < q3) //3 real sol
+    {
+	const Double_t sqrtQ = TMath::Sqrt(q);
+	const Double_t min2SqQ = -sqrtQ*2;
+	const Double_t theta = TMath::ACos(r/(sqrtQ*sqrtQ*sqrtQ));
+
+        x[0] = min2SqQ * TMath::Cos(theta/3) - aOver3;
+	x[1] = min2SqQ * TMath::Cos((theta+TMath::TwoPi())/3) - aOver3;
+	x[2] = min2SqQ * TMath::Cos((theta-TMath::TwoPi())/3) - aOver3;
+
+        for (Int_t i = 0; i < 3; i++)
+	    if (x[i] >= 0 && x[i] <= fH)
+	    {
+                x[i] += fX;
+                return i;
+	    }
+        return -1;
+    }
+
+    const Double_t s = r==0 ? 0 : -TMath::Sign(TMath::Power(TMath::Abs(r) + TMath::Sqrt(r2 - q3), 1./3), r);
+
+    x[0] = s==0 ? - aOver3 : (s + q/s) - aOver3;
+
+    if (x[0] < 0 || x[0] > fH)
+        return -1;
+
+    x[0] += fX;
+    return 0;
+}
+
+//------------------------------------------------------------------------------------
+//
+// return true if x is in this interval
+//
+
+Bool_t MCubicCoeff :: IsIn(Double_t x)
+{
+    return x >= fX && x <= fXNext;
+}
Index: /tags/Mars-V0.9/mtools/MCubicCoeff.h
===================================================================
--- /tags/Mars-V0.9/mtools/MCubicCoeff.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MCubicCoeff.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MCubicCoeff
+#define MARS_MCubicCoeff
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+class MCubicCoeff : public TObject
+{
+ private:
+    Double_t fX;     // abscissa
+    Double_t fXNext; // abscissa of the next point
+    Double_t fA;     // 3rd order coeff
+    Double_t fB;     // 2nd order coeff
+    Double_t fC;     // 1st order coeff
+    Double_t fY;     // constant term
+    Double_t fYNext; // value in the next point
+    Double_t fH;     // interval width
+    Double_t fMin;   // minimum value
+    Double_t fMax;   // maximum value
+    Double_t fAbMin; // abscissa of the min
+    Double_t fAbMax; // abscissa of the max
+ public:
+    MCubicCoeff(){}
+    MCubicCoeff(Double_t x, Double_t xNext, Double_t y, Double_t yNext,
+		Double_t a, Double_t b, Double_t c);
+    Double_t GetA()   { return fA; }
+    Double_t GetB()   { return fB; }
+    Double_t GetC()   { return fC; }
+    Double_t GetMin() { return fMin; }
+    Double_t GetMax() { return fMax; }
+    Double_t GetAbMin() { return fAbMin; }
+    Double_t GetAbMax() { return fAbMax; }
+    Double_t Eval(Double_t x); //Evaluate the spline at a point x
+    Bool_t   EvalMinMax();     //Finds min & max
+    Short_t  FindCardanRoot(Double_t y, Double_t *x); //Evaluate the abscissa of the spline given y 
+    Bool_t   IsIn(Double_t x);
+
+    ClassDef(MCubicCoeff, 0)  //Class to contain spline coefficients
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MCubicSpline.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MCubicSpline.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MCubicSpline.cc	(revision 9772)
@@ -0,0 +1,278 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Sebastian Raducci 01/2004  <mailto:raducci@fisica.uniud.it>
+!
+!   Copyright: MAGIC Software Development, 2001-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  Cubic Spline Interpolation
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCubicSpline.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCubicCoeff.h"
+
+ClassImp(MCubicSpline);
+
+using namespace std;
+
+//---------------------------------------------------------------------------
+//
+// Contructor 
+//
+//
+MCubicSpline::MCubicSpline(const Byte_t *y, const Byte_t *x, Bool_t areAllEq,
+			   Int_t n, Double_t begSD, Double_t endSD)
+{
+    Init(y,x,areAllEq,n,begSD,endSD);
+}
+
+//---------------------------------------------------------------------------
+//
+// Constructor for FADC slice (only the FADC counts are needed)
+//
+//
+MCubicSpline::MCubicSpline(const Byte_t *y)
+{
+    const Byte_t x[]={0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E};
+    Init(y,x,kTRUE,15,0.0,0.0);
+}
+
+//---------------------------------------------------------------------------
+//
+// Constructors common part
+//
+//
+void MCubicSpline::Init(const Byte_t *y, const Byte_t *x, Bool_t areAllEq,
+			   Int_t n, Double_t begSD, Double_t endSD)
+
+{
+    Double_t *temp = new Double_t[n];
+    Double_t *ysd  = new Double_t[n];
+
+    fCoeff = new TObjArray(n-1,0);
+
+    ysd[0]  =begSD;
+    temp[0] =begSD;
+    ysd[n-1]=endSD;
+    
+    Double_t h = x[1]-x[0];
+
+    if (areAllEq)
+    {
+	for(Int_t i = 1; i < n-1; i++)
+	{
+	    const Double_t p = ysd[i-1]/2+2;
+
+            ysd[i]  = -0.5/p;
+	    temp[i] = (y[i+1] - y[i]*2 + y[i-1])/h;
+	    temp[i] = (temp[i]*6/h-temp[i-1]/2)/p;
+        }
+    }
+    else
+    {
+	for(Int_t i = 1; i < n-1; i++)
+	{
+            const Double_t sig = (x[i]-x[i-1])/(x[i+1]-x[i-1]);
+
+            const Double_t p = sig*ysd[i-1]+2;
+
+	    ysd[i]  = (sig-1.0)/p;
+	    temp[i] = (y[i+1]-y[i])/(x[i+1]-x[i])-(y[i]-y[i-1])/(x[i]-x[i-1]);
+	    temp[i] = (temp[i]*6/(x[i+1]-x[i-1])-sig*temp[i-1])/p;
+	}
+    }
+
+    for(Int_t i = n-2; i > 0; i--)
+        ysd[i] = ysd[i]*ysd[i+1] + temp[i];
+
+    for(Int_t i = 0; i < n-1; i++)
+    {
+        if (!areAllEq)
+            h = x[i+1]-x[i];
+
+        MCubicCoeff *c = new MCubicCoeff(x[i], x[i+1], y[i], y[i+1], (ysd[i+1]-ysd[i])/(h*6),
+                                         ysd[i]/2, (y[i+1]-y[i])/h-(h*(ysd[i+1]+ysd[i]*2))/6);
+        fCoeff->AddAt(c, i);
+    }
+
+    delete [] temp;
+    delete [] ysd;
+}
+
+MCubicSpline::~MCubicSpline()
+{
+    fCoeff->Delete();
+    delete fCoeff;
+}
+
+//---------------------------------------------------------------------------
+//
+// Evaluate the spline at a given point
+//
+Double_t MCubicSpline :: Eval(Double_t x)
+{
+    const Int_t n = fCoeff->GetSize();
+    for (Int_t i = 0; i < n; i++)
+    {
+        MCubicCoeff *c = (MCubicCoeff*)fCoeff->UncheckedAt(i);
+	if (c->IsIn(x))
+            return c->Eval(x);
+    }
+
+    gLog << warn << "Cannot evaluate Spline at " << x << "; returning 0";
+
+    return 0;
+}
+
+//----------------------------------------------------------------------------
+//
+// Search for max
+//
+Double_t MCubicSpline :: EvalMax()
+{
+    Double_t max = -FLT_MAX;
+
+    TIter Next(fCoeff);
+    MCubicCoeff *c;
+    while ((c=(MCubicCoeff*)Next()))
+        max = TMath::Max(max, c->GetMax());
+
+    return max;
+}
+
+//----------------------------------------------------------------------------
+//
+// Search for min
+//
+Double_t MCubicSpline :: EvalMin()
+{
+    Double_t min = FLT_MAX;
+
+    TIter Next(fCoeff);
+    MCubicCoeff *c;
+    while ((c=(MCubicCoeff*)Next()))
+        min = TMath::Min(min, c->GetMin());
+
+    return min;
+}
+
+//----------------------------------------------------------------------------
+//
+// Search for abscissa of the max
+//
+Double_t MCubicSpline :: EvalAbMax()
+{
+    Double_t max = -FLT_MAX;
+
+    TIter Next(fCoeff);
+
+    MCubicCoeff *c;
+    MCubicCoeff *cmax=0;
+
+    while ((c=(MCubicCoeff*)Next()))
+    {
+        const Double_t temp = c->GetMax();
+        if (temp <= max)
+            continue;
+
+        max = temp;
+        cmax = c;
+    }
+
+    return cmax ? cmax->GetAbMax() : -FLT_MAX;
+}
+
+//----------------------------------------------------------------------------
+//
+// Search for abscissa of the min
+//
+Double_t MCubicSpline :: EvalAbMin()
+{
+    Double_t min = FLT_MAX;
+
+    TIter Next(fCoeff);
+
+    MCubicCoeff *c;
+    MCubicCoeff *cmin=0;
+
+    while ((c=(MCubicCoeff*)Next()))
+    {
+        const Double_t temp = c->GetMin();
+        if (temp >= min)
+            continue;
+
+        min = temp;
+        cmin = c;
+    }
+
+    return cmin ? cmin->GetAbMin() : FLT_MAX;
+}
+
+//----------------------------------------------------------------------------
+//
+// Finds the abscissa where the spline reaches y starting from x0 going in
+// direction direction
+// You have to give as input a starting point and a direction ("l" or "r")
+//
+Double_t MCubicSpline :: FindVal(Double_t y, Double_t x0, Char_t direction = 'l')
+{
+    Double_t roots[3] = { 0, 0, 0 };
+
+    const Int_t n = fCoeff->GetSize()-1;
+
+    for (Int_t i = 0; i < n; i++)
+    {
+        if (!((MCubicCoeff*)fCoeff->At(i))->IsIn(x0))
+            continue;
+
+        switch (direction)
+        {
+        case 'l':
+            for (Int_t j = i; j >= 0; j--)
+            {
+                const Int_t whichRoot = ((MCubicCoeff*)fCoeff->At(j))->FindCardanRoot(y, roots);
+                if (whichRoot >= 0 )
+                    return roots[whichRoot];
+            }
+            break;
+
+        case 'r':
+            for (Int_t j = i; j < n; j++)
+            {
+                const Int_t whichRoot = ((MCubicCoeff*)fCoeff->At(j))->FindCardanRoot(y, roots);
+                if (whichRoot >= 0)
+                    return roots[whichRoot];
+            }
+            break;
+        }
+    }
+
+    //gLog << warn << "Nothing found calling MCubicSpline :: FindVal(), returning 0" << endl;
+
+    return 0;
+}
Index: /tags/Mars-V0.9/mtools/MCubicSpline.h
===================================================================
--- /tags/Mars-V0.9/mtools/MCubicSpline.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MCubicSpline.h	(revision 9772)
@@ -0,0 +1,35 @@
+#ifndef MARS_MCubicSpline
+#define MARS_MCubicSpline
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TObjArray
+#include "TObjArray.h"
+#endif
+
+class MCubicCoeff;
+
+class MCubicSpline : public TObject
+{
+ private:
+    TObjArray *fCoeff; //array of the coefficients
+
+    void Init(const Byte_t *y, const Byte_t *x, Bool_t areAllEq, Int_t n, Double_t begSD, Double_t endSD);
+
+ public:
+    MCubicSpline(const Byte_t *y, const Byte_t *x, Bool_t areAllEq, Int_t n, Double_t begSD=0.0, Double_t endSD=0.0);
+    MCubicSpline(const Byte_t *y);
+    ~MCubicSpline();
+    Double_t Eval(Double_t x); //Eval the spline at a point x
+    Double_t EvalMax();   //Eval the max
+    Double_t EvalMin();   //Eval the min
+    Double_t EvalAbMax(); //Eval the abscissa of the max
+    Double_t EvalAbMin(); //Eval the abscissa of the min
+    Double_t FindVal(Double_t y, Double_t x0, Char_t direction); //Finds the abscissa where the spline reaches y
+    
+    ClassDef(MCubicSpline, 0)  //Class to contain spline coefficients
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MFFT.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MFFT.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MFFT.cc	(revision 9772)
@@ -0,0 +1,1181 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 01/2004  <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2001-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  Fast Fourier Transforms                                                 //
+//                                                                          //
+//  (Most of the code is adapted from Numerical Recipies in C++, 2nd ed.,   //
+//  pp. 509-563)                                                            //
+//                                                                          //
+//  Usage:                                                                  //
+//                                                                          //
+//  1) Functions RealFunctionFFT:  (FOURIER TRANSFORM)                      //
+//     * Take as argument arrays of real numbers,                           // 
+//       in some cases the dimension of the array has to be given separately//
+//     * Return a COMPLEX array with the following meaning:                 //
+//       array[0]: The value of F(0) (has only real component)              //
+//       array[1]: The value of F(N/2) (has only real component)            //
+//       array[2i]: The real part of F(i)                                   //
+//       array[2i+1]: The imaginary part of F(i)                            //
+//     * Note that F(N-i)* = F(i), therefore only the positive frequency    //
+//       half is stored.                                                    //
+//     * The dimension MUST be an integer power of 2,                       //
+//       otherwise, the array will be shortened!!                           //
+//                                                                          //
+//  2) Functions RealFunctionIFFT:  (INVERSER FOURIER TRANSFORM)            // 
+//     * Take as argument a COMPLEX array                                   //
+//       of Fourier-transformed REAL numbers                                //
+//       with the following meaning:                                        //
+//       array[0]: The value of F(0) (has only real component)              //
+//       array[1]: The value of F(N/2) (has only real component)            //
+//       array[2i]: The real part of F(i)                                   //
+//       array[2i+1]: The imaginary part of F(i)                            //
+//     * Returns the original complex array of dimension 2N-1               //                                
+//                                                                          //
+//  3) Functions PowerSpectrumDensity:                                      //
+//     * Return a histogram with the spectral density, i.e.                 //
+//       P(k) = 1/(N*N) * |F(k)|*|F(k)|                                     //
+//     * The histogram is ranged between 0 and 1./(2*binwidth)              //
+//     * The number of bins equals N/2+1                                    //
+//     * Note that histograms with unequal binwidth can not yet be treated! //
+//     * If the PSD does NOT CONVERGE to 0 at the maximum bin,              //
+//       you HAVE TO sample your data finer!                                //
+//
+// Fourier-Transformation:
+// =======================
+
+// (taken from http://www.parasitaere-kapazitaeten.net/Pd/ft.htm)
+//
+//  The Fourier-Transformation is a mathematical function that breaks
+// down a signal (like sound) into its frequency-spectrum as a set of
+// sinusoidal components, converting it from the Time Domain to the
+// Frequency Domain.
+// 
+//  In the Time Domain the signal x[ ] consists of N samples, labeled
+// from 0 to N-1. In the Frequency Domain the RFFT produces two signals
+// (signalvectors), treated as complex numbers representing the Real Part:
+// Re X[ ] and the Imaginary Part: Im X[ ]. They are seen as the Cosine-
+// und Sine-Components of the base frequencies. Each of these two signals
+// contains one more sample than the half of the original signal: N/2 + 1
+// samples. (this results from the fact, that the sine-components of the
+// first frequency (0) and the last (nyquist, N/2) are always 0). With the
+// complex Fourier-Transformation N complexe values are transformed to N
+// new complex values. For both it applies to: the Frequency Domain
+// contains exactly the same information as the Time-Domain.
+// 
+//  A Real FFT over 64 samples produces values for 33 cosine- and 33
+// sine-wave-amplitudes with the frequencies 0, 1, 2, 3, ..., 30, 31, 32.
+// The first value (frequency 0) is the DC (direct current), the other
+// values have to be seen in practice as factors of a
+// fundamental-frequency which can be calculated by dividing samplerate by
+// windowsize. The highest frequency is the nyquist-frequency
+// (samplerate/2).
+// 
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MFFT.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArrayD.h"
+#include "MArrayF.h"
+#include "MArrayI.h"
+
+ClassImp(MFFT);
+
+using namespace std;
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor
+//  Initializes random number generator and default variables
+//
+MFFT::MFFT() : fDim(0)
+{
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. 
+//
+MFFT::~MFFT()
+{
+}
+
+void MFFT::TransformF(const Int_t isign, TArrayF &data)
+{
+  
+  UInt_t   n,mmax,m,j,istep,i;
+  Float_t wtemp,wr,wpr,wpi,wi,theta;
+  Float_t tempr,tempi;
+  
+  Int_t nn = fDim/2;
+  n = nn << 1;
+
+  //
+  // The bit-reversal section of the routine:
+  // Exchange the two complex numbers
+  //
+  j=1;
+  for (i=1;i<n;i+=2) {
+    if (j > i) {
+      Swap(data[j-1],data[i-1]);
+      Swap(data[j],data[i]);
+    }
+    m=nn;
+    while (m >= 2 && j > m) {
+      j -= m;
+      m >>= 1;
+    }
+    j += m;
+  }
+  // 
+  // Here begins the Danielson-Lanczos section of the routine
+  //
+  mmax=2;
+  while (n > mmax) {         // Outer loop executed log_2(nn) times
+
+    istep = mmax << 1;
+    //
+    // Initialize the trigonometric recurrence:
+    //
+    theta = isign*(6.28318530717959/mmax);
+
+    wtemp = TMath::Sin(0.5*theta);
+    wpr   = -2.0*wtemp*wtemp;
+    wpi   = TMath::Sin(theta);
+
+    wr=1.0;
+    wi=0.0;
+
+    for (m=1; m<mmax; m+=2) {
+      for (i=m; i<=n; i+=istep) {
+        // 
+        // The Danielson-Lanczos formula:
+        //
+        j          = i+mmax;
+        tempr      = wr*data[j-1] - wi*data[j];
+        tempi      = wr*data[j]   + wi*data[j-1];
+        data[j-1] = data[i-1]   - tempr;
+        data[j]   = data[i]     - tempi;
+        data[i-1] += tempr;
+        data[i]   += tempi;
+      }
+
+      //
+      // Trigonometric recurrence
+      //
+      wr = (wtemp=wr)*wpr - wi*wpi+wr;
+      wi = wi*wpr         + wtemp*wpi+wi;
+
+    }
+    mmax=istep;
+  }
+}
+
+
+void MFFT::TransformD(const Int_t isign, TArrayD &data)
+{
+  
+  UInt_t   n,mmax,m,j,istep,i;
+  Double_t wtemp,wr,wpr,wpi,wi,theta;
+  Double_t tempr,tempi;
+  
+  Int_t nn = fDim/2;
+  n = nn << 1;
+
+  //
+  // The bit-reversal section of the routine:
+  // Exchange the two complex numbers
+  //
+  j=1;
+  for (i=1;i<n;i+=2) {
+    if (j > i) {
+      Swap(data[j-1],data[i-1]);
+      Swap(data[j],data[i]);
+    }
+    m=nn;
+    while (m >= 2 && j > m) {
+      j -= m;
+      m >>= 1;
+    }
+    j += m;
+  }
+  // 
+  // Here begins the Danielson-Lanczos section of the routine
+  //
+  mmax=2;
+  while (n > mmax) {         // Outer loop executed log_2(nn) times
+
+    istep = mmax << 1;
+    //
+    // Initialize the trigonometric recurrence:
+    //
+    theta = isign*(6.28318530717959/mmax);
+
+    wtemp = TMath::Sin(0.5*theta);
+    wpr   = -2.0*wtemp*wtemp;
+    wpi   = TMath::Sin(theta);
+
+    wr=1.0;
+    wi=0.0;
+
+    for (m=1; m<mmax; m+=2) {
+      for (i=m; i<=n; i+=istep) {
+        // 
+        // The Danielson-Lanczos formula:
+        //
+        j          = i+mmax;
+        tempr      = wr*data[j-1] - wi*data[j];
+        tempi      = wr*data[j]   + wi*data[j-1];
+        data[j-1] = data[i-1]   - tempr;
+        data[j]   = data[i]     - tempi;
+        data[i-1] += tempr;
+        data[i]   += tempi;
+      }
+
+      //
+      // Trigonometric recurrence
+      //
+      wr = (wtemp=wr)*wpr - wi*wpi+wr;
+      wi = wi*wpr         + wtemp*wpi+wi;
+
+    }
+    mmax=istep;
+  }
+}
+
+//
+// Calculates the Fourier transform of a set of n real-valued data points. 
+// Replaces this data (which is stored in array data[1..n]) by the positive
+// frequency half of its complex Fourier transform. The real-valued first 
+// and last components of the complex transform are returned as elements 
+// data[1] and data[2], respectively. n must be a power of 2. This routine
+// also calculates the inverse transform of a complex data array if it is 
+// the transform of real data. (Result in this case mus be multiplied by 
+// 2/n.). From NUMERICAL RECIPES IN C++.
+//
+void MFFT::RealFTF(const Int_t isign)
+{
+  
+  Int_t    i,i1,i2,i3,i4;
+  Float_t  c1=0.5,c2,h1r,h1i,h2r,h2i;
+  Float_t wr,wi,wpr,wpi,wtemp,theta;
+
+  //
+  // Initialize the recurrence
+  //
+  theta = TMath::Pi() / (Double_t)(fDim>>1);
+
+  if(isign==1) // forward transform
+    {
+      c2    = -0.5;
+      TransformF(1,fDataF);
+    }
+  else         // set up backward transform
+    {
+      c2    = 0.5;
+      theta = -theta;
+    }
+
+  wtemp = TMath::Sin(0.5*theta);
+  wpr   = -2.0*wtemp*wtemp;
+  wpi   = TMath::Sin(theta);
+
+  wr    = 1.0 + wpr;
+  wi    = wpi;
+
+  for(i=1;i<(fDim>>2);i++) // case i=0 done separately below
+    {
+
+      i2 = 1 + (i1 = i+i);
+      i4 = 1 + (i3 = fDim-i1);
+
+      //
+      // The two separate transforms are separated out of the data
+      //
+      h1r  =  c1*(fDataF[i1]+fDataF[i3]);
+      h1i  =  c1*(fDataF[i2]-fDataF[i4]);
+      h2r  = -c2*(fDataF[i2]+fDataF[i4]);
+      h2i  =  c2*(fDataF[i1]-fDataF[i3]);
+
+      //
+      // Here, they are recombined to from the true transform 
+      // of the orginal real data
+      //
+      fDataF[i1] =  h1r + wr*h2r - wi*h2i;
+      fDataF[i2] =  h1i + wr*h2i + wi*h2r;
+      fDataF[i3] =  h1r - wr*h2r + wi*h2i;
+      fDataF[i4] = -h1i + wr*h2i + wi*h2r;
+      
+      //
+      // The recurrence
+      //
+      wr = (wtemp=wr)*wpr - wi*wpi + wr;
+      wi =    wi*wpr   + wtemp*wpi + wi;
+    }
+
+  //
+  // Squeeze the first and last data together to get them all 
+  // within the original array
+  //
+  if(isign==1)
+    {
+      fDataF[0] = (h1r=fDataF[0]) + fDataF[1];
+      fDataF[1] =     h1r  -      fDataF[1];
+    }
+  else
+    {
+
+      fDataF[0] = c1*((h1r=fDataF[0]) + fDataF[1]);
+      fDataF[1] = c1*(h1r-fDataF[1]);
+
+      //
+      // The inverse transform for the case isign = -1
+      //
+      TransformF(-1,fDataF);  
+
+      //
+      // normalize correctly (not done in original NR's)
+      //
+      for(i=1;i<=fDim;i++)
+        fDataF[i] *= (2./fDim);
+    }
+}
+void MFFT::RealFTD(const Int_t isign)
+{
+  
+  Int_t    i,i1,i2,i3,i4;
+  Float_t  c1=0.5,c2,h1r,h1i,h2r,h2i;
+  Double_t wr,wi,wpr,wpi,wtemp,theta;
+
+  //
+  // Initialize the recurrence
+  //
+  theta=3.141592653589793/(Double_t) (fDim>>1);
+
+  if(isign==1) // forward transform
+    {
+      c2    = -0.5;
+      TransformD(1,fDataD);
+    }
+  else         // set up backward transform
+    {
+      c2    = 0.5;
+      theta = -theta;
+    }
+
+  wtemp = TMath::Sin(0.5*theta);
+  wpr   = -2.0*wtemp*wtemp;
+  wpi   = TMath::Sin(theta);
+
+  wr    = 1.0 + wpr;
+  wi    = wpi;
+
+  for(i=1;i<(fDim>>2);i++) // case i=0 done separately below
+    {
+
+      i2 = 1 + (i1 = i+i);
+      i4 = 1 + (i3 = fDim-i1);
+
+      //
+      // The two separate transforms are separated out of the data
+      //
+      h1r  =  c1*(fDataD[i1]+fDataD[i3]);
+      h1i  =  c1*(fDataD[i2]-fDataD[i4]);
+      h2r  = -c2*(fDataD[i2]+fDataD[i4]);
+      h2i  =  c2*(fDataD[i1]-fDataD[i3]);
+
+      //
+      // Here, they are recombined to from the true transform 
+      // of the orginal real data
+      //
+      fDataD[i1] =  h1r + wr*h2r - wi*h2i;
+      fDataD[i2] =  h1i + wr*h2i + wi*h2r;
+      fDataD[i3] =  h1r - wr*h2r + wi*h2i;
+      fDataD[i4] = -h1i + wr*h2i + wi*h2r;
+      
+      //
+      // The recurrence
+      //
+      wr = (wtemp=wr)*wpr - wi*wpi + wr;
+      wi =    wi*wpr   + wtemp*wpi + wi;
+    }
+
+  //
+  // Squeeze the first and last data together to get them all 
+  // within the original array
+  //
+  if(isign==1)
+    {
+      fDataD[0] = (h1r=fDataD[0]) + fDataD[1];
+      fDataD[1] =     h1r  -      fDataD[1];
+    }
+  else
+    {
+
+      fDataD[0] = c1*((h1r=fDataD[0]) + fDataD[1]);
+      fDataD[1] = c1*(h1r-fDataD[1]);
+
+      //
+      // The inverse transform for the case isign = -1
+      //
+      TransformD(-1,fDataD);  
+      
+      //
+      // normalize correctly (not done in original NR's)
+      //
+      for(i=1;i<=fDim;i++)
+        fDataD[i] *= (2./fDim);
+    }
+}
+
+
+//
+// Fast Fourier Transform for float arrays
+//
+Float_t* MFFT::RealFunctionFFT(const Int_t n, const Float_t *data)
+{
+
+  fDim = n;
+  CheckDim(n);
+
+  fDataF.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data[i];
+
+  RealFTF(1);
+  
+  return fDataF.GetArray();
+
+}
+
+//
+// Fast Inverse Fourier Transform for float arrays
+//
+Float_t* MFFT::RealFunctionIFFT(const Int_t n, const Float_t *data)
+{
+
+  fDim = n;
+  CheckDim(fDim);
+  
+  fDataF.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data[i];
+
+  RealFTF(-1);
+  
+  return fDataF.GetArray();
+
+}
+
+//
+// Fast Fourier Transform for double arrays
+//
+Double_t* MFFT::RealFunctionFFT(const Int_t n, const Double_t *data)
+{
+
+  fDim = n;
+  CheckDim(n);
+
+  fDataD.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = data[i];
+
+  RealFTD(1);
+  
+  return fDataD.GetArray();
+
+}
+
+//
+// Fast Inverse Fourier Transform for double arrays
+//
+Double_t* MFFT::RealFunctionIFFT(const Int_t n, const Double_t *data)
+{
+
+  fDim = n;
+  CheckDim(fDim);
+  
+  fDataD.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = data[i];
+
+  RealFTD(-1);
+  
+  return fDataD.GetArray();
+
+}
+
+//
+// Fast Fourier Transform for TArrayF's
+//
+TArrayF* MFFT::RealFunctionFFT(const TArrayF *data)
+{
+
+  fDim = data->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data->At(i);
+
+  RealFTF(1);
+  
+  return new TArrayF(fDim,fDataF.GetArray());
+
+}
+
+//
+// Inverse Fast Fourier Transform for TArrayF's
+//
+TArrayF* MFFT::RealFunctionIFFT(const TArrayF *data)
+{
+
+  fDim = data->GetSize();
+  CheckDim(fDim);
+  
+  fDataF.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data->At(i);
+
+  RealFTF(-1);
+
+  return new TArrayF(fDim,fDataF.GetArray());
+}
+
+
+//
+// Fast Fourier Transform for TArrayD's
+//
+TArrayD* MFFT::RealFunctionFFT(const TArrayD *data)
+{
+
+  fDim = data->GetSize();
+  CheckDim(fDim);
+
+  fDataD.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = data->At(i);
+
+  RealFTD(1);
+  
+  return new TArrayD(fDim,fDataD.GetArray());
+
+}
+
+//
+// Inverse Fast Fourier Transform for TArrayD's
+//
+TArrayD* MFFT::RealFunctionIFFT(const TArrayD *data)
+{
+
+  fDim = data->GetSize();
+  CheckDim(fDim);
+  
+  fDataD.Set(fDim);
+  //
+  // Clone the array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = data->At(i);
+
+  RealFTD(-1);
+
+  return new TArrayD(fDim,fDataD.GetArray());
+}
+
+//----------------------------------------------------------
+//
+// Power Spectrum Density Calculation
+//
+TH1D* MFFT::PowerSpectrumDensity(const TH1D *hist)
+{
+
+  TH1D *newhist = (TH1D*)CheckHist(hist,1);
+
+  fDataD.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = hist->GetBinContent(i);
+
+  RealFTD(1);
+
+  Int_t dim2 = fDim*fDim;
+  Double_t c02;
+  Double_t ck2;
+  Double_t cn2;
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //    (stored in fData{0])
+  //
+  c02 = fDataD[0]*fDataD[0];
+  newhist->Fill(c02/dim2);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)| + |C(N-k)|*|C(N-k)|)
+  //
+  for (Int_t k=2;k<fDim-2;k+=2)
+    {
+
+      Int_t ki  = k+1;
+      ck2 = (fDataD[k]*fDataD[k] + fDataD[ki]*fDataD[ki]);
+      newhist->Fill(ck2/dim2);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //    (stored in fData[1])
+  //
+  cn2 = (fDataD[1]*fDataD[1]);
+  newhist->Fill(cn2/dim2);
+
+  return newhist;
+}
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for TArrayF
+//
+TArrayF* MFFT::PowerSpectrumDensity(const TArrayF *array)
+{
+
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = array->At(i);
+
+  RealFTF(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t c02;
+  Float_t ck2;
+  Float_t cn2;
+  
+  TArrayF *newarray = new TArrayF(dim05);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  c02 = (fDataF[0]*fDataF[0]);
+  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataF[k2]*fDataF[k2] + fDataF[k2+1]*fDataF[k2+1]);
+      newarray->AddAt(ck2/dim2,k);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  cn2 = (fDataF[1]*fDataF[1]);
+  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for TArrayI
+//
+TArrayF* MFFT::PowerSpectrumDensity(const TArrayI *array)
+{
+
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = (Float_t)array->At(i);
+
+  RealFTF(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t c02;
+  Float_t ck2;
+  Float_t cn2;
+  
+  TArrayF *newarray = new TArrayF(dim05);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  c02 = (fDataF[0]*fDataF[0]);
+  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataF[k2]*fDataF[k2] + fDataF[k2+1]*fDataF[k2+1]);
+      newarray->AddAt(ck2/dim2,k);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  cn2 = (fDataF[1]*fDataF[1]);
+  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for TArrayD
+//
+TArrayD* MFFT::PowerSpectrumDensity(const TArrayD *array)
+{
+  
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataD.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = array->At(i);
+
+  RealFTD(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t c02;
+  Float_t ck2;
+  Float_t cn2;
+  
+  TArrayD *newarray = new TArrayD(dim05);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  c02 = (fDataD[0]*fDataD[0]);
+  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataD[k2]*fDataD[k2] + fDataD[k2+1]*fDataD[k2+1]);
+      newarray->AddAt(ck2/dim2,k);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  cn2 = (fDataD[1]*fDataD[1]);
+  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for MArrayF
+// The difference to the TArrayF versions is that 
+// the resulting array has two entries less, namely 
+// the first and last one are skipped!
+//
+MArrayF* MFFT::PowerSpectrumDensity(const MArrayF *array)
+{
+
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = array->At(i);
+
+  RealFTF(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t ck2;
+  
+  MArrayF *newarray = new MArrayF(dim05-2);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  //  c02 = (fDataF[0]*fDataF[0]);
+  //  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataF[k2]*fDataF[k2] + fDataF[k2+1]*fDataF[k2+1]);
+      newarray->AddAt(ck2/dim2,k-1);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  //  cn2 = (fDataF[1]*fDataF[1]);
+  //  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+//-----------------------------------------------------
+//
+// Power Spectrum Density calculation for MArrayI
+// The difference to the TArrayI versions is that 
+// the resulting array has two entries less, namely 
+// the first and last one are skipped!
+//
+MArrayF* MFFT::PowerSpectrumDensity(const MArrayI *array)
+{
+
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = (Float_t)array->At(i);
+
+  RealFTF(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t ck2;
+  
+  MArrayF *newarray = new MArrayF(dim05-2);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  //  c02 = (fDataF[0]*fDataF[0]);
+  //  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataF[k2]*fDataF[k2] + fDataF[k2+1]*fDataF[k2+1]);
+      newarray->AddAt(ck2/dim2,k-1);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  //  cn2 = (fDataF[1]*fDataF[1]);
+  //  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+// -------------------------------------------------
+//
+// Power Spectrum Density calculation for MArrayD
+// The difference to the TArrayI versions is that 
+// the resulting array has two entries less, namely 
+// the first and last one are skipped!
+//
+MArrayD* MFFT::PowerSpectrumDensity(const MArrayD *array)
+{
+  
+  fDim = array->GetSize();
+  CheckDim(fDim);
+
+  fDataD.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataD[i] = array->At(i);
+
+  RealFTD(1);
+
+  const Int_t dim2  = fDim*fDim;
+  const Int_t dim05 = fDim/2;
+  Float_t ck2;
+  
+  MArrayD *newarray = new MArrayD(dim05-2);
+
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  //  c02 = (fDataD[0]*fDataD[0]);
+  //  newarray->AddAt(c02/dim2,0);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=1;k<dim05-1;k++)
+    {
+      const Int_t k2 = k+k;
+      ck2 = (fDataD[k2]*fDataD[k2] + fDataD[k2+1]*fDataD[k2+1]);
+      newarray->AddAt(ck2/dim2,k-1);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  //  cn2 = (fDataD[1]*fDataD[1]);
+  //  newarray->AddAt(cn2,dim05-1);
+  
+  return newarray;
+}
+
+// -----------------------------------------------
+//
+// Power Spectrum Density calculation for TH1
+//
+TH1F* MFFT::PowerSpectrumDensity(const TH1 *hist)
+{
+
+  TH1F *newhist = (TH1F*)CheckHist(hist,0);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = hist->GetBinContent(i);
+
+  RealFTF(1);
+
+  Int_t dim2 = fDim*fDim;
+  Float_t c02;
+  Float_t ck2;
+  Float_t cn2;
+  //
+  // Fill the new histogram: 
+  //
+  // 1) P(0) = 1/(N*N) |C(0)|*|C(0)|
+  //
+  c02 = (fDataF[0]*fDataF[0]);
+  newhist->Fill(0.,c02/dim2);
+  //
+  // 2) P(k) = 1/(N*N) (|C(k)|*|C(k)|))
+  //
+  for (Int_t k=2;k<fDim;k+=2)
+    {
+      ck2 = (fDataF[k]*fDataF[k] + fDataF[k+1]*fDataF[k+1]);
+      newhist->Fill(k/2.,ck2/dim2);
+    }
+  //
+  // 3) P(N) = 1/(N*N) (|C(n/2)|*|C(n/2)|)
+  //
+  cn2 = (fDataF[1]*fDataF[1]);
+  newhist->Fill(fDim/2.-1.,cn2/dim2);
+  
+  return newhist;
+}
+
+
+//
+// Power Spectrum Density calculation for TH1I
+//
+TH1F* MFFT::PowerSpectrumDensity(const TH1F *hist)
+{
+  return PowerSpectrumDensity((TH1*)hist);
+}
+
+//
+// Power Spectrum Density calculation for TH1I
+//
+TH1F* MFFT::PowerSpectrumDensity(const TH1I *hist)
+{
+  return PowerSpectrumDensity((TH1*)hist);
+}
+
+
+void MFFT::CheckDim(Int_t a)
+{
+
+  // If even number, return 0
+  if (a==2)  return;
+
+  // If odd number, return the closest power of 2
+  if (a & 1) 
+    { 
+      Int_t b = 1; 
+      while (b < fDim/2+1)
+        b <<= 1; 
+
+      fDim = b;
+      //      gLog << warn << "Dimension of Data is not a multiple of 2, will take only first " 
+      //           << fDim << " entries! " << endl;
+      return; 
+    }
+
+  CheckDim(a>>1);
+}
+
+TH1* MFFT::CheckHist(const TH1 *hist, const Int_t flag)
+{
+  
+  // number of entries
+  fDim = hist->GetNbinsX();
+  CheckDim(fDim);
+
+  // Step width
+  Double_t delta = hist->GetBinWidth(1);
+  
+  // Nyquist frequency
+  Axis_t fcrit = 1./(2.*delta);
+  Axis_t low = -0.5;
+  Axis_t up  = fcrit;
+
+  switch (flag)
+    {
+    case 0: 
+      return new TH1F(Form("%s%s",hist->GetName()," PSD"),
+                      Form("%s%s",hist->GetTitle()," - Power Spectrum Density"),
+                      fDim/2,low,up);
+      break;
+    case 1:
+      return new TH1D(Form("%s%s",hist->GetName()," PSD"),
+                      Form("%s%s",hist->GetTitle()," - Power Spectrum Density"),
+                      fDim/2,low,up);
+      break;
+    default:
+      return new TH1F(Form("%s%s",hist->GetName()," PSD"),
+                      Form("%s%s",hist->GetTitle()," - Power Spectrum Density"),
+                      fDim/2,low,up);
+      break;
+    }
+}
+
+//
+// Real function spectrum with data windowing
+//
+TArrayF* MFFT::RealFunctionSpectrum(const TArrayF *data) 
+{
+  
+  fDim = data->GetSize();
+  CheckDim(fDim);
+
+  fDataF.Set(fDim);
+  //
+  // Copy the hist into an array
+  //
+  for (Int_t i=0;i<fDim;i++)
+    fDataF[i] = data->At(i);
+
+  fWindowF.Set(fDim);
+
+  Int_t dim2 = fDim/2;
+
+  TArrayF *power = new TArrayF(dim2);
+
+  // 
+  // Start program spctrm from NR's
+  //
+  Float_t w, facp, facm, sumw=0.;
+  
+  facm = dim2;
+  facp = 1./dim2;
+  
+  for (Int_t j=0;j<dim2;j++)
+    {
+      Int_t j2 = j+j;
+      w     = ApplyWindow(j,facm,facp);
+      sumw += w*w;
+      fWindowF[j2]   = fDataF[j]*w;
+      fWindowF[j2+1] = fDataF[dim2+j]*w;
+    }
+  
+  TransformF(1,fWindowF);
+  
+  power->AddAt(fWindowF[0]*fWindowF[0] + fWindowF[1]*fWindowF[1],0);
+
+  //  power->AddAt(fWindowF[0]*fWindowF[0],0);
+  //  power->AddAt(fWindowF[1]*fWindowF[1],dim2-1);  
+
+
+  for (Int_t j=1;j<dim2;j++)
+    //  for (Int_t j=1;j<dim2;j++)
+    {
+      Int_t j2 = j+j;
+      Float_t buf = fWindowF[j2+1]     *fWindowF[j2+1] 
+                  + fWindowF[j2  ]     *fWindowF[j2  ] 
+                  + fWindowF[fDim-j2+1]*fWindowF[fDim-j2+1] 
+                  + fWindowF[fDim-j2  ]*fWindowF[fDim-j2  ] ;
+      power->AddAt(buf/sumw/(fDim+fDim),j);
+    }
+  
+  return power;
+
+}
Index: /tags/Mars-V0.9/mtools/MFFT.h
===================================================================
--- /tags/Mars-V0.9/mtools/MFFT.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MFFT.h	(revision 9772)
@@ -0,0 +1,92 @@
+#ifndef MARS_MFFT
+#define MARS_MFFT
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include "TArrayF.h"
+#endif
+
+#ifndef ROOT_TArrayD
+#include "TArrayD.h"
+#endif
+
+#ifndef ROOT_TH1F
+#include "TH1F.h"
+#endif
+
+#ifndef ROOT_TH1D
+#include "TH1D.h"
+#endif
+
+class MArrayI;
+class MArrayD;
+class MArrayF;
+class MFFT : public TObject
+{
+private:
+
+  void Swap(Float_t &a,  Float_t &b)    { Float_t  c = a;  a = b;  b = c;  }
+  void Swap(Double_t &a, Double_t &b)   { Double_t c = a;  a = b;  b = c;  }
+
+  void TransformF(const Int_t isign, TArrayF &data);
+  void TransformD(const Int_t isign, TArrayD &data);  
+  void RealFTF(const Int_t isign);
+  void RealFTD(const Int_t isign);
+
+  void CheckDim(Int_t a);
+  TH1 *CheckHist(const TH1 *hist, const Int_t flag);
+
+  Float_t ApplyWindow(const Int_t j, const Float_t a, const Float_t b) const 
+    {
+
+      return 1.0-TMath::Abs((j-a)*b);      // Bartlett
+      // return 1.0;                        // Square
+      // return 1.0-(((j-a)*b)*((j-a)*b));   // Welch
+      
+    }
+  
+  Int_t   fDim;
+  TArrayF fDataF;
+  TArrayD fDataD;  
+  TArrayF fWindowF;
+  TArrayD fWindowD;  
+
+public:
+
+  MFFT();
+  ~MFFT();
+
+  TArrayF*  RealFunctionFFT( const TArrayF *data);
+  TArrayF*  RealFunctionIFFT(const TArrayF *data);  
+  
+  TArrayD*  RealFunctionFFT( const TArrayD *data);
+  TArrayD*  RealFunctionIFFT(const TArrayD *data);  
+  
+  Float_t*  RealFunctionFFT( const Int_t n, const Float_t *data);
+  Float_t*  RealFunctionIFFT(const Int_t n, const Float_t *data);  
+  
+  Double_t* RealFunctionFFT( const Int_t n, const Double_t *data);
+  Double_t* RealFunctionIFFT(const Int_t n, const Double_t *data);  
+  
+  TH1F* PowerSpectrumDensity(const TH1 *hist);
+  TH1F* PowerSpectrumDensity(const TH1F *hist);
+  TH1F* PowerSpectrumDensity(const TH1I *hist);  
+  TH1D* PowerSpectrumDensity(const TH1D *hist);
+
+  TArrayF* PowerSpectrumDensity(const TArrayI *array);  
+  TArrayF* PowerSpectrumDensity(const TArrayF *array);
+  TArrayD* PowerSpectrumDensity(const TArrayD *array);
+
+  MArrayF* PowerSpectrumDensity(const MArrayI *array);  
+  MArrayF* PowerSpectrumDensity(const MArrayF *array);
+  MArrayD* PowerSpectrumDensity(const MArrayD *array);
+
+  TArrayF*  RealFunctionSpectrum(const TArrayF *data);
+  
+  ClassDef(MFFT,0)  // Class to perform a Fast Fourier Transform
+};
+    
+#endif
Index: /tags/Mars-V0.9/mtools/MHSimulatedAnnealing.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MHSimulatedAnnealing.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MHSimulatedAnnealing.cc	(revision 9772)
@@ -0,0 +1,250 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+///////////////////////////////////////////////////////////////////////
+//
+// MHSimulatedAnnealing
+//
+// This class contains different histograms of the Simulated Annealing 
+//   Snapshort during optimization and the final results
+//
+///////////////////////////////////////////////////////////////////////
+#include "MHSimulatedAnnealing.h"
+
+#include <TVector.h>
+#include <TMatrix.h>
+#include <TObjArray.h>
+
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include "MBinning.h"
+
+ClassImp(MHSimulatedAnnealing);
+
+// --------------------------------------------------------------------------
+//
+// Setup histograms
+//
+MHSimulatedAnnealing::MHSimulatedAnnealing(UShort_t moves, UShort_t ndim, 
+	                                   const char *name, 
+					   const char *title)
+    : fDim(ndim), fMoves(moves), fTimeEvolution(NULL), fBestEver(), fBestFuncEval()
+{
+
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHSimulatedAnnealing";
+    fTitle = title ? title : "Output Histograms of a Simulated Annealing Run";
+    
+    fBestEver.SetName("Hist_BestEver");
+    fBestEver.SetTitle("Best Param. Combinations");
+    fBestEver.SetXTitle("Run Duration");
+    fBestEver.SetYTitle("Parameter Nr.");
+    fBestEver.SetZTitle("Parameter Value");
+    fBestEver.SetDirectory(NULL);
+    
+    fBestFuncEval.SetName("Hist_BestFuncEval");
+    fBestFuncEval.SetTitle("Best Function Evaluation");
+    fBestFuncEval.SetXTitle("Run Duration");
+    fBestFuncEval.SetYTitle("Function Value");
+    fBestFuncEval.SetDirectory(NULL);
+    
+    MBinning binsx, binsy;
+    binsx.SetEdges(fMoves+1, 0, 1);
+    binsy.SetEdges(fDim, 0.5, fDim+0.5);
+    MH::SetBinning(&fBestEver, &binsx, &binsy);
+    
+    // For better visibility, omit the first entry in fBestFuncEval
+    // It has nothing significant, anyway
+    binsx.SetEdges(fMoves,1./(fMoves+1), 1);
+    binsx.Apply(fBestFuncEval);
+    
+}
+
+void MHSimulatedAnnealing::InitFullSimplex()
+{
+    if (fTimeEvolution)
+      delete fTimeEvolution;
+    
+    fTimeEvolution = new TObjArray;
+    fTimeEvolution->SetOwner();
+    
+    for (Int_t i=0;i<fDim;i++) 
+    {
+        TH2F *hist = new TH2F(Form("Hist_%d", i), Form("Parameter %d", i), 
+                              fMoves+1, 0., 1.,fDim+1,0.5,fDim+1.5);
+        hist->SetXTitle("Run Duration");
+        hist->SetYTitle("Point Nr. Simplex");
+        hist->SetZTitle(Form("Value of Parameter %d",i));
+        fTimeEvolution->Add(hist);
+    }
+}
+
+Bool_t MHSimulatedAnnealing::StoreFullSimplex(const TMatrix &p, const UShort_t move) 
+{
+
+    if (!fTimeEvolution)
+        return kFALSE;
+
+    Int_t idx=0;
+    const Axis_t bin = (move-0.5)/(fMoves+1);
+    
+    TIter Next(fTimeEvolution);
+    TH2F *hist=NULL;
+    while ((hist=(TH2F*)Next()))
+      {
+        for (Int_t i=0;i<fDim+1;i++)
+          hist->Fill(bin,i,p(i,idx));
+        idx++;
+      }
+    return kTRUE;
+}
+
+Bool_t MHSimulatedAnnealing::StoreBestValueEver(const TVector &y, const Float_t yb, const UShort_t move)
+{
+    if (y.GetNrows() != fDim) 
+      return kFALSE;
+    
+    const Axis_t bin = (move-0.5)/(fMoves+1);
+    
+    for (Int_t i=0;i<fDim;i++)
+      fBestEver.Fill(bin,0.5+i,((TVector)y)(i));
+    
+    fBestFuncEval.Fill(bin,yb);
+    
+    return kTRUE;
+}
+
+Bool_t MHSimulatedAnnealing::ChangeTitle(const UShort_t index, const char* title) 
+{
+    if (!fTimeEvolution) 
+      return kFALSE;
+
+    TH2F *hist = NULL;
+    if (!(hist = (TH2F*)fTimeEvolution->At(index))) 
+      return kFALSE;
+
+    hist->SetNameTitle(Form("Hist_%s",title),title);
+    hist->SetYTitle(Form("Value of Parameter %s",title));
+
+    return kTRUE;
+}
+
+void MHSimulatedAnnealing::ChangeFuncTitle(const char* title)
+{
+  fBestFuncEval.SetTitle(title);
+}
+
+TObject *MHSimulatedAnnealing::DrawClone(Option_t *opt) const
+{
+    UShort_t i=2;
+  
+    TCanvas *c = MakeDefCanvas(this, 720, 810);
+    if (fTimeEvolution)
+      c->Divide(2,(int)(fDim/2.)+1);
+    else
+      gPad->Divide(1,2);
+  
+    gROOT->SetSelectedPad(NULL);
+  
+    c->cd(1);
+    gStyle->SetOptStat(0);
+    ((TH1&)fBestFuncEval).DrawCopy();   
+    
+    c->cd(2);
+    gStyle->SetOptStat(10);
+    ((TH2&)fBestEver).DrawCopy(opt);   
+    
+    if (fTimeEvolution)
+    {
+      TH2F *hist = NULL;
+      TIter Next(fTimeEvolution);
+      while ((hist=(TH2F*)Next())) 
+        {
+          c->cd(++i);
+          hist->DrawCopy(opt);
+        }
+    }   
+    c->Modified();
+    c->Update();
+    
+    return c;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Draw all histograms. 
+//
+void MHSimulatedAnnealing::Draw(Option_t *opt) 
+{
+    UShort_t i=2;
+
+    if (!gPad)
+      MakeDefCanvas(this,780,940);
+
+    if (fTimeEvolution) 
+      gPad->Divide(2,(int)(fDim/2.)+1);
+    else 
+      gPad->Divide(1,2);
+
+    gPad->cd(1);  
+    gStyle->SetOptStat(0);
+    fBestFuncEval.Draw();
+    gPad->Modified();
+    gPad->Update();
+    
+    gPad->cd(2);
+    gStyle->SetOptStat(10);
+    fBestEver.Draw(opt);
+    gPad->Modified();
+    gPad->Update();
+
+    if (!fTimeEvolution)
+        return;
+    
+    TH2F *hist = NULL;
+    TIter Next(fTimeEvolution);
+    while ((hist=(TH2F*)Next())) 
+    {
+        gPad->cd(++i);
+        hist->Draw(opt);
+    }
+    gPad->Modified();
+    gPad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the histograms.
+//
+MHSimulatedAnnealing::~MHSimulatedAnnealing() 
+{
+  if (fTimeEvolution)
+    delete fTimeEvolution;
+}
+  
Index: /tags/Mars-V0.9/mtools/MHSimulatedAnnealing.h
===================================================================
--- /tags/Mars-V0.9/mtools/MHSimulatedAnnealing.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MHSimulatedAnnealing.h	(revision 9772)
@@ -0,0 +1,54 @@
+#ifndef MARS_MHSimulatedAnnealing
+#define MARS_MHSimulatedAnnealing
+///////////////////////////////////////////////////////////////////////////////
+//
+//  MHSimulatedAnnealing
+//
+//  Output container of MSimulatedAnnealing
+///////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class TMatrix;
+class TVector;
+
+class MHSimulatedAnnealing : public MH
+{
+private:
+    UShort_t fDim;             // The dimension of the whole thing
+    UShort_t fMoves;           // The total number of moves
+
+    TObjArray *fTimeEvolution; //-> Display the time evolution of the simplex in TH1D's
+
+    TH2F     fBestEver;        // The best values ever found during search
+    TH1F     fBestFuncEval;    // The best function values ever found during search
+
+public:
+
+    MHSimulatedAnnealing(UShort_t moves = 0,UShort_t ndim = 0, 
+	                 const char *name=NULL, const char *title=NULL);
+    ~MHSimulatedAnnealing();
+
+    void InitFullSimplex();
+    Bool_t StoreFullSimplex(const TMatrix &p, const UShort_t move);
+    Bool_t StoreBestValueEver(const TVector &y, const Float_t yb, const UShort_t move);
+    
+    Bool_t ChangeTitle(const UShort_t index, const char* title);
+    void ChangeFuncTitle(const char* title);    
+    
+    TObjArray *GetTimeEvolution() const   { return fTimeEvolution; }
+    const TH2F &GetBestEver()     const   { return fBestEver; }
+    const TH1F &GetBestFuncEval() const   { return fBestFuncEval; }
+    
+    void Draw(Option_t *opt=NULL);
+    TObject *DrawClone(Option_t *opt=NULL) const;
+    
+    ClassDef(MHSimulatedAnnealing,1) // Storage Histogram Container for Cuteval Results
+};
+    
+#endif
Index: /tags/Mars-V0.9/mtools/MSimulatedAnnealing.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MSimulatedAnnealing.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MSimulatedAnnealing.cc	(revision 9772)
@@ -0,0 +1,629 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Markus Gaug 10/2002  <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2002
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MSimulatedAnnealing                                                     //
+//                                                                          //
+//  class to perform a Simulated Annealing minimization on an n-dimensional //
+//  simplex of a function 'FunctionToMinimize(TArrayF &)' in multi-         //
+//  dimensional parameter space.                                            //
+//  (The code is adapted from Numerical Recipies in C++, 2nd ed.,           //
+//  pp. 457-459)                                                            //
+//                                                                          //
+//  Classes can inherit from MSimulatedAnnealing                            //
+//  and use the function:                                                   //
+//                                                                          //
+//  RunSimulatedAnnealing();                                                //
+//                                                                          //
+//  They HAVE TO initialize the following input arguments                   //
+//  (with ndim being the parameter dimension (max. 20)):                    //
+//                                                                          //
+//  1) a TMatrix p(ndim+1,ndim)                                             //
+//     holding the start simplex                                            //
+//  2) a TArrayF y(ndim+1)                                                  //
+//     whose components must be pre-initialized to the values of            //
+//      FunctionToMinimize evaluated at the fNdim+1 vertices (rows) of p    //
+//  3) a TArrayF p0(ndim)                                                   //
+//     whose components contain the lower simplex borders                   //
+//  4) a TArrayF p1(ndim)                                                   //
+//     whose components contain the upper simplex borders                   //
+//    (The simplex will not get reflected out of these borders !!!)         //
+//                                                                          //
+//  These arrays have to be initialized with a call to:                     //
+//  Initialize(TMatrix \&, TArrayF \&, TArrayF \&, TArrayF \&)              //
+//                                                                          //
+//  5) a virtual function FunctionToMinimize(TArrayF &)                     //
+//     acting on a TArrayF(ndim) array of parameter values                  //
+//                                                                          //
+//  Additionally, a global start temperature can be chosen with:            //
+//                                                                          //
+//  SetStartTemperature(Float_t temp)                                       //
+//  (default is: 10)                                                        //
+//                                                                          //
+//  A total number of total moves (watch out for the CPU time!!!) with:     //
+//                                                                          //
+//  SetNumberOfMoves(Float_t totalMoves)                                    //
+//  (default is: 200)                                                       //
+//                                                                          //
+//  The temperature is reduced after evaluation step like:                  //
+//      CurrentTemperature = StartTemperature*(1-currentMove/totalMoves)    //
+//  where currentMove is the cumulative number of moves so far              //
+//                                                                          //
+//  WARNING: The start temperature and number of moves has to be optimized  //
+//           for each individual problem.                                   //
+//           It is not straightforward using the defaults!                  //
+//           In case, you omit this important step,                         //
+//           you will get local minima without even noticing it!!           //
+//                                                                          //
+//  You may define the following variables:                                 //
+//                                                                          //
+//  1) A global convergence criterium fTol                                  //
+//     which determines an early return for:                                //
+//                                                                          //
+//     max(FunctionToMinimize(p))-min(FunctionToMinimize(p))                //
+//     -----------------------------------------------------  \< fTol       //
+//     max(FunctionToMinimize(p))+min(FunctionToMinimize(p))                //
+//                                                                          //
+//     ModifyTolerance(Float_t)                                             //
+//                                                                          //
+//  2) A verbose level for prints to *fLog                                  //
+//                                                                          //
+//     SetVerbosityLevel(Verbosity_t)                                       //
+//                                                                          //
+//  3) A bit if you want to have stored                                     //
+//     the full simplex after every call to Amebsa:                         //
+//                                                                          //
+//     SetFullStorage()                                                     //
+//                                                                          //
+//  4) The random number generator                                          //
+//     e.g. if you want to test the stability of the output                 //
+//                                                                          //
+//     SetRandom(TRandom *rand)                                             //
+//                                                                          //
+//                                                                          //
+//  Output containers:                                                      //
+//                                                                          //
+//  MHSimulatedAnnealing                                                    //
+//                                                                          //
+//  Use:                                                                    //
+//    GetResult()->Draw(Option_t *o)                                        //
+//  or                                                                      //
+//    GetResult()->DrawClone(Option_t *o)                                   //
+//                                                                          //
+//  to retrieve the output histograms                                       //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MSimulatedAnnealing.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHSimulatedAnnealing.h"
+
+const Float_t MSimulatedAnnealing::gsYtryStr = 10000000;  
+const Float_t MSimulatedAnnealing::gsYtryCon = 20000000;  
+const Int_t   MSimulatedAnnealing::gsMaxDim  = 20;
+const Int_t   MSimulatedAnnealing::gsMaxStep = 50;
+
+ClassImp(MSimulatedAnnealing);
+
+using namespace std;
+
+// ---------------------------------------------------------------------------
+//
+//  Default Constructor
+//  Initializes random number generator and default variables
+//
+MSimulatedAnnealing::MSimulatedAnnealing()
+    : fResult(NULL), fTolerance(0.0001),
+      fNdim(0), fNumberOfMoves(200),
+      fStartTemperature(10), fFullStorage(kFALSE),
+      fInit(kFALSE), 
+      fP(gsMaxDim, gsMaxDim), fP0(gsMaxDim),
+      fP1(gsMaxDim), fY(gsMaxDim), fYb(gsMaxDim), fYconv(gsMaxDim),
+      fPb(gsMaxDim), fPconv(gsMaxDim),
+      fBorder(kEStrictBorder), fVerbose(kEDefault)
+{
+
+    // random number generator
+    fRandom = gRandom;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor. 
+//
+MSimulatedAnnealing::~MSimulatedAnnealing()
+{
+  if (fResult) 
+    delete fResult;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Initialization needs the following four members:
+//
+//  1) a TMatrix p(ndim+1,ndim)
+//     holding the start simplex 
+//  2) a TVector y(ndim+1)
+//     whose components must be pre-initialized to the values of 
+//     FunctionToMinimize evaluated at the fNdim+1 vertices (rows) of fP
+//  3) a TVector p0(ndim)
+//     whose components contain the lower simplex borders 
+//  4) a TVector p1(ndim)
+//     whose components contain the upper simplex borders
+//    (The simplex will not get reflected out of these borders !!!)
+//
+//  It is possible to perform an initialization and 
+//  a subsequent RunMinimization several times. 
+//  Each time, a new class MHSimulatedAnnealing will get created
+//  (and destroyed). 
+//
+Bool_t MSimulatedAnnealing::Initialize(const TMatrix &p,  const TVector &y, 
+                                       const TVector &p0, const TVector &p1)
+{
+
+    fNdim = p.GetNcols();
+    fMpts = p.GetNrows();
+
+    //
+    // many necessary checks ...
+    //
+    if (fMpts > gsMaxDim) 
+    {
+       gLog << err << "Dimension of Matrix fP is too big ... aborting." << endl;
+        return kFALSE;
+    }
+    if (fNdim+1 != fMpts) 
+    {
+        gLog << err << "Matrix fP does not have the right dimensions ... aborting." << endl;
+        return kFALSE;
+    }
+    if (y.GetNrows() != fMpts) 
+    {
+        gLog << err << "Array fY has not the right dimension ... aborting." << endl;
+        return kFALSE;
+    }
+    if (p0.GetNrows() != fNdim) 
+    {
+        gLog << err << "Array fP0 has not the right dimension ... aborting." << endl;
+        return kFALSE;
+    }
+    if (p1.GetNrows() != fNdim) 
+    {
+        gLog << err << "Array fP1 has not the right dimension ... aborting." << endl;
+        return kFALSE;
+    }
+
+    //
+    // In order to allow multiple use of the class
+    // without need to construct the class every time new
+    // delete the old fResult and create a new one in RunMinimization
+    //
+    if (fResult)
+       delete fResult;
+
+    fY.ResizeTo(fMpts);
+    
+    fPsum.ResizeTo(fNdim);
+    fPconv.ResizeTo(fNdim);
+    
+    fP0.ResizeTo(fNdim);
+    fP1.ResizeTo(fNdim);
+    fPb.ResizeTo(fNdim);
+    
+    fP.ResizeTo(fMpts,fNdim);
+
+    fY  = y;
+    fP  = p;
+    fP0 = p0;
+    fP1 = p1;
+    fPconv.Zero();
+
+    fInit = kTRUE;
+    fYconv = 0.;
+
+    return kTRUE;
+}
+
+
+// ---------------------------------------------------------------------------
+//
+//  RunMinimization:
+//
+//  Runs only eafter a call to Initialize(const TMatrix \&, const TVector \&,
+//                                        const TVector \&, const TVector \&)
+//  
+//  Temperature and number of moves should have been set
+//  (default: StartTemperature = 10, NumberOfMoves = 200
+//
+//  
+//  It is possible to perform an initialization and 
+//  a subsequent RunMinimization several times. 
+//  Each time, a new class MHSimulatedAnnealing will get created
+//  (and destroyed). 
+Bool_t MSimulatedAnnealing::RunMinimization()
+{
+    if (!fInit)
+    {
+        gLog << err << "No succesful initialization performed yet... aborting." << endl;
+        return kFALSE;
+    }
+
+    Int_t    iter        = 0;
+    UShort_t iret        = 0;
+    UShort_t currentMove = 0;
+    Real_t   currentTemp = fStartTemperature;
+
+    fResult = new MHSimulatedAnnealing(fNumberOfMoves,fNdim);
+    if (fFullStorage) 
+      fResult->InitFullSimplex();
+
+    while(1)
+    {
+        if (iter > 0) 
+        {
+            gLog << "Convergence at move: " << currentMove ;
+            gLog << " and temperature: " << currentTemp << endl;
+            break;
+        }
+        
+        if (currentTemp > 0.) 
+        {
+          //
+          // Reduce the temperature 
+          //
+          // FIXME: Maybe it is necessary to also incorporate other 
+          //        ways to reduce the temperature (T0*(1-k/K)**alpha)
+          // 
+          currentTemp = fStartTemperature*(1.-(float)currentMove++/fNumberOfMoves);
+          iter = 1;
+        } 
+        else 
+        {
+            // Make sure that now, the program will return only on convergence !
+            // The program returns to here only after gsMaxStep moves
+            // If we have not reached convergence until then, we assume that an infinite 
+            // loop has occurred and quit.
+            if (iret != 0) 
+            {
+                gLog << warn << "No Convergence at the end ! " << endl;
+                fY.Zero();
+
+                break;
+            }
+            iter = 150;
+            iret++;
+            currentMove++;
+        }
+        
+        if (fVerbose==2) {
+            gLog << dbginf << " current..." << endl;
+            gLog << " - move:        " << currentMove << endl;
+            gLog << " - temperature: " << currentTemp << endl;
+            gLog << " - best function evaluation: " << fYb << endl;
+        }
+
+        iter = Amebsa(iter, currentTemp);
+
+        // Store the current best values in the histograms
+        fResult->StoreBestValueEver(fPb,fYb,currentMove);
+
+        // Store the complete simplex if we have full storage
+        if (fFullStorage) 
+          fResult->StoreFullSimplex(fP,currentMove);
+    }
+
+    //
+    // Now, the matrizes and vectors have all the same value, 
+    // Need to initialize again to allow a new Minimization
+    //
+    fInit = kFALSE;
+
+    return kTRUE;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Amebsa
+//
+//  This is the (adjusted) amebsa function from 
+//  Numerical Recipies (pp. 457-458)
+//             
+//  The routine makes iter function evaluations at an annealing
+//  temperature fCurrentTemp, then returns. If iter is returned 
+//  with a poisitive value, then early convergence has occurred. 
+//
+Int_t MSimulatedAnnealing::Amebsa(Int_t iter, const Real_t temp)
+{
+    GetPsum();
+  
+    while (1) 
+    {
+        UShort_t ihi = 0; // Simplex point with highest function evaluation
+        UShort_t ilo = 1; // Simplex point with lowest  function evaluation
+
+        // Function eval. at ilo (with random fluctuations)
+        Real_t ylo = fY(0) + gRandom->Exp(temp); 
+
+        // Function eval. at ihi (with random fluctuations)
+        Real_t yhi = fY(1) + gRandom->Exp(temp); 
+
+        // The function evaluation at next highest point
+        Real_t ynhi = ylo; 
+
+        if (ylo > yhi)
+        {
+            // Determine which point is the highest (worst),
+            // next-highest and lowest (best)
+            ynhi = yhi;
+            yhi  = ylo;
+            ylo  = ynhi;
+        }
+    
+        // By looping over the points in the simplex 
+        for (UShort_t i=2;i<fMpts;i++) 
+        {
+            const Real_t yt = fY(i) + gRandom->Exp(temp);
+      
+            if (yt <= ylo)
+            {
+                ilo = i;
+                ylo = yt;
+            }
+
+            if (yt > yhi)
+            {
+                ynhi = yhi;
+                ihi  = i;
+                yhi  = yt;
+            }
+            else 
+                if (yt > ynhi) 
+                    ynhi = yt;
+        }
+
+        // Now, fY(ilo) is smallest and fY(ihi) is at biggest value 
+        if (iter < 0)
+        {
+            // Enough looping with this temperature, go to decrease it
+            // First put best point and value in slot 0
+            
+            Real_t dum = fY(0);
+            fY(0)      = fY(ilo);
+            fY(ilo)    = dum;
+
+            for (UShort_t n=0;n<fNdim;n++)
+            {
+                dum       = fP(0,n);
+                fP(0,n)   = fP(ilo,n);
+                fP(ilo,n) = dum;
+            }
+          
+            break;
+        }
+        
+        // Compute the fractional range from highest to lowest and
+        // return if satisfactory
+        Real_t tol = fabs(yhi) + fabs(ylo);
+        if (tol != 0)
+            tol = 2.0*fabs(yhi-ylo)/tol;
+    
+        if (tol<fTolerance)
+        {
+            // Put best point and value in fPconv
+            fYconv = fY(ilo);
+            for (UShort_t n=0; n<fNdim; n++)
+                fPconv(n) = fP(ilo, n);  
+
+            break;
+        }
+        iter -= 2;
+
+        // Begin new Iteration. First extrapolate by a factor of -1 through
+        // the face of the simplex across from the high point, i.e. reflect
+        // the simplex from the high point
+        Real_t ytry = Amotsa(-1.0, ihi, yhi,temp);
+    
+        if (ytry <= ylo)
+        {
+            // cout << " !!!!!!!!!!!!!! E X P A N D  !!!!!!!!!!!!!!" << endl;
+            // Gives a result better than the best point, so try an additional
+            // extrapolation by a factor of 2
+            ytry = Amotsa(2.0, ihi, yhi,temp);
+            continue;
+        }
+
+        if (ytry < ynhi)
+        {
+            iter++;
+            continue;
+        }
+
+        // cout << " !!!!!!!!!!!! R E F L E C T  !!!!!!!!!!!!!!!!!!!!" << endl;
+        // The reflected point is worse than the second-highest, so look for an
+        // intermediate lower point, for (a one-dimensional contraction */
+        const Real_t fYsave = yhi;
+        ytry = Amotsa(0.5, ihi, yhi,temp);
+
+        if (ytry < fYsave)
+            continue;
+
+        // cout << " !!!!!!!!!!!! R E F L E C T  !!!!!!!!!!!!!!!!!!!!" << endl;
+        // The reflected point is worse than the second-highest, so look for an
+        // intermediate lower point, for (a one-dimensional contraction */
+        const Real_t ysave = yhi;
+        ytry = Amotsa(0.5, ihi, yhi,temp);
+      
+        if (ytry < ysave)
+            continue;
+
+        // cout << " !!!!!!!!!!!! C O N T R A C T  !!!!!!!!!!!!!!!!!!" << endl;
+        // Cannot seem to get rid of that point, better contract around the
+        // lowest (best) point
+        for (UShort_t i=0; i<fMpts; i++)
+        {
+            if (i != ilo)
+            {
+                for (UShort_t j=0;j<fNdim;j++)
+                {
+                    fPsum(j) = 0.5*(fP(i, j) + fP(ilo, j));
+
+                    // Create new cutvalues
+                    fP(i, j) = fPsum(j);
+                }
+                fY(i) = FunctionToMinimize(fPsum);
+            }
+        }
+
+        iter -= fNdim;
+        GetPsum();
+    }
+    return iter;
+}
+
+void MSimulatedAnnealing::GetPsum()
+{
+    for (Int_t n=0; n<fNdim; n++)
+    {
+        Real_t sum=0.0;
+        for (Int_t m=0;m<fMpts;m++)
+            sum += fP(m,n);
+
+        fPsum(n) = sum;
+    }
+}
+
+
+Real_t MSimulatedAnnealing::Amotsa(const Float_t fac, const UShort_t ihi, 
+                                   Real_t &yhi, const Real_t temp)
+{
+  
+    const Real_t fac1 = (1.-fac)/fNdim;
+    const Real_t fac2 = fac1 - fac;
+
+    Int_t borderflag = 0;
+    TVector ptry(fNdim);
+    TVector cols(fMpts);
+
+    for (Int_t j=0; j<fNdim; j++)
+    {
+        ptry(j) = fPsum(j)*fac1 - fP(ihi, j)*fac2;
+
+        // Check that the simplex does not go to infinite values,
+        // in case of: reflect it
+        const Real_t newcut = ptry(j);
+  
+        if (fP1(j) > fP0(j))
+        {
+            if (newcut > fP1(j))
+            {
+                ptry(j) = fP1(j);
+                borderflag = 1;
+            }
+            else
+                if (newcut < fP0(j))
+                {
+                    ptry(j) = fP0(j);
+                    borderflag = 1;
+                }
+        }
+    
+        else
+        {
+            if (newcut < fP1(j))
+            {
+                ptry(j) = fP1(j);
+                borderflag = 1;
+            }
+            else
+                if (newcut > fP0(j))
+                {
+                    ptry(j) = fP0(j);
+                    borderflag = 1;
+                }
+        }
+    }
+
+    Real_t faccompare = 0.5;
+    Real_t ytry = 0;
+  
+    switch (borderflag)
+    {
+    case kENoBorder:
+        ytry = FunctionToMinimize(fPsum);
+        break;
+
+    case kEStrictBorder:
+        ytry = FunctionToMinimize(fPsum) + gsYtryStr;
+        break;
+
+    case kEContractBorder:
+        ytry = fac == faccompare ? gsYtryCon : gsYtryStr;
+        break;
+    }
+
+    if (ytry < fYb)
+    {
+        fPb = ptry;
+        fYb = ytry;
+    }
+
+    const Real_t yflu = ytry + gRandom->Exp(temp);
+
+    if (yflu >= yhi)
+        return yflu;
+
+    fY(ihi) = ytry;
+    yhi     = yflu;
+    
+    for(Int_t j=0; j<fNdim; j++)
+    {
+        fPsum(j) += ptry(j)-fP(ihi, j);
+        fP(ihi, j) = ptry(j);
+    }
+
+    return yflu;
+}
+
+// ---------------------------------------------------------------------------
+//
+//  Dummy FunctionToMinimize
+//
+//  A class inheriting from MSimulatedAnnealing NEEDS to contain a similiar
+//  
+//  virtual Float_t FunctionToMinimize(const TVector \&)
+//  
+//  The TVector contains the n parameters (dimensions) of the function
+//
+Float_t MSimulatedAnnealing::FunctionToMinimize(const TVector &arr) 
+{
+  return 0.0;
+}
Index: /tags/Mars-V0.9/mtools/MSimulatedAnnealing.h
===================================================================
--- /tags/Mars-V0.9/mtools/MSimulatedAnnealing.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MSimulatedAnnealing.h	(revision 9772)
@@ -0,0 +1,110 @@
+#ifndef MARS_MSimulatedAnnealing
+#define MARS_MSimulatedAnnealing
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TMatrix
+#include <TMatrix.h>
+#endif
+
+#ifndef ROOT_TVector
+#include <TVector.h>
+#endif
+
+class MHSimulatedAnnealing;
+class TRandom;
+
+class MSimulatedAnnealing : public TObject
+{
+private:
+
+    static const Float_t gsYtryStr;  // Fixed high value to keep the simplex inside the borders
+    static const Float_t gsYtryCon;  // Fixed high value to keep the simplex inside the borders
+    static const Int_t   gsMaxDim;   // Fixed maximum number of dimensions
+    static const Int_t   gsMaxStep;  // Fixed maximum number of loops with temperature=0
+
+    MHSimulatedAnnealing *fResult;   //! The histogram output container
+
+    TRandom *fRandom;                // The random number generator -> random numbers between 0 and 1
+  
+    Real_t   fTolerance;             // The convergence break condition
+  
+    UShort_t fNdim;                  // The number of parameters 
+    UShort_t fMpts;                  // The number of simplex points (=fNdim+1)
+  
+    UShort_t fNumberOfMoves;         // The total number of moves (== CPU time) 
+
+    Real_t   fStartTemperature;      // The start temperature -> will slowly get decreased to 0
+
+    Bool_t   fFullStorage;           // kTRUE -> the whole simplex gets stored in MHSimlutedAnnealing
+    Bool_t   fInit;                  // kTRUE -> initialization was succesful
+
+    TMatrix fP;                      // The (ndim+1,ndim) matrix containing the simplex 
+
+    TVector fPsum;                   // The sum of each point of the simplex
+    
+    TVector fP0;                     // The boundary conditions on the weak side
+    TVector fP1;                     // The boundary conditions on the strong side
+    TVector fY;                      // The array containing the function evaluation results
+
+    Real_t  fYb;                     // The best function evaluation value ever found
+    Real_t  fYconv;                  // The function evaluation value at the convergence point
+    
+    TVector fPb;                     // The parameters belonging to fYb
+    TVector fPconv;                  // The parameters belonging to fYconv
+    
+    Int_t Amebsa(Int_t iter,
+                 const Real_t temp); // The function deciding if the simplex has to get reflected, expanded or contracted
+
+    Real_t   Amotsa(const Float_t  fac,
+                    const UShort_t ihi,
+                    Real_t &yhi,
+                    const Real_t temp); // The function reflecting, expanding and contracting the simplex: fac=-1 -> reflection, fac=0.5 -> contraction, fac=2.0 -> expansion
+
+    void     GetPsum();              
+    
+protected:
+  
+    virtual Float_t FunctionToMinimize(const TVector &arr); // The optimization function  
+
+public:
+    enum BorderFlag_t { kENoBorder, kEStrictBorder, kEContractBorder };
+    enum Verbosity_t  { kEDefault, kEVerbose, kEDebug };
+
+private:
+    BorderFlag_t fBorder;         
+    Verbosity_t  fVerbose;        
+
+public:
+    MSimulatedAnnealing();
+    virtual ~MSimulatedAnnealing();
+
+    void ModifyTolerance(Float_t tol)          { fTolerance = tol;  }
+    void ModifyBorderFlag(BorderFlag_t border) { fBorder    = border; }
+    
+    Bool_t Initialize(const TMatrix &p,  const TVector &y,
+                      const TVector &p0, const TVector &p1);
+  
+    void SetNumberOfMoves(UShort_t moves)      { fNumberOfMoves    = moves;  }
+    void SetStartTemperature(Float_t temp)     { fStartTemperature = temp;   }
+    void SetFullStorage()                      { fFullStorage      = kTRUE;  }  
+    void SetVerbosityLevel(Verbosity_t level)  { fVerbose          = level;  }
+    void SetRandom(TRandom *rand)              { fRandom           = rand;   }
+
+    const TVector &GetPb()    const            { return fPb;    }
+    Float_t GetYb()           const            { return fYb;    }
+
+    const TVector &GetPconv() const            { return fPconv; }    
+    Float_t GetYconv()        const            { return fYconv; }  
+  
+  
+    MHSimulatedAnnealing *GetResult()          { return fResult; }
+  
+    Bool_t RunMinimization();
+  
+    ClassDef(MSimulatedAnnealing,1)  // Class to perform a Simulated Annealing Minimization
+};
+    
+#endif
Index: /tags/Mars-V0.9/mtools/MTFillMatrix.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MTFillMatrix.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MTFillMatrix.cc	(revision 9772)
@@ -0,0 +1,326 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTFillMatrix
+//
+// Use this tool to fill eg trainings and test-matrices, while the matrix
+// to be filled can be a real matrix (MHMatrix) or a file (MWriteRootFile)
+// or both.
+//
+// First create a reference histogram (MH3). For more details see
+// MFEventSelector2 which is used to select events according to the
+// reference histogram.
+//
+// If no reference histogram is available the number of events are
+// randomly choosen from the sample with a probability which fits
+// the total destination number of events.
+//
+// Here is an example of how to choose 1000 events somehow distributed in
+// size from a file.
+// -----------------------------------------------------------------------
+//
+// MH3 ref("MHillas.fSize");          // choose a predefined size distribution
+// // Now setup the distribution
+//
+// MHMatrix matrix1;                   // create matrix to fill
+// matrix.AddColumn("MHillas.fWidth"); // setup columns of your matrix
+//
+// MReadMarsFile read("myfile.root");  // Setup your 'reader'
+// read.DisableAutoScheme();           // make sure everything is read
+//
+// MTFillMatrix fill(&ref);            // setup MTFillMatrix
+// fill.SetNumDestEvents1(1000);       // setup number of events to select
+// fill.SetDestMatrix1(&matrix1);      // setup destination matrix
+// if (!fill.Process())                // check if everything worked
+//    return;
+// fill.WriteMatrix1("myoutput.root"); // write matrix to file
+//
+//
+// To get two matrices instead of one (splitted randomly) you can add
+// the following before calling Process():
+// ------------------------------------------------------------------------
+//
+// MHMatrix matrix2;
+// fill.SetNumDestEvents2(500);        // setup number of events to select
+// fill.SetDestMatrix2(&matrix2);      // setup destination matrix
+// [...]
+// fill.WriteMatrix2("myoutput2.root");
+//
+//
+// To write both matrices into a single file use:
+// ----------------------------------------------
+//
+// fill.WriteMatrices("myfile.root");
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTFillMatrix.h"
+
+#include <TFile.h>
+
+#include "MHMatrix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MRead.h"
+#include "MFillH.h"
+#include "MContinue.h"
+#include "MFilterList.h"
+#include "MFEventSelector.h"
+#include "MFEventSelector2.h"
+
+ClassImp(MTFillMatrix);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Print Size and contained columns.
+// Check whether the number of generated events is compatible with
+// the number of requested events.
+//
+Bool_t MTFillMatrix::CheckResult(MHMatrix *m, Int_t num) const
+{
+    if (!m)
+        return kTRUE;
+
+    m->Print("SizeCols");
+
+    const Int_t generated = m->GetM().GetNrows();
+    if (TMath::Abs(generated-num) <= TMath::Sqrt(9.0*num))
+        return kTRUE;
+
+    *fLog << warn << "WARNING - No. of generated events (";
+    *fLog << generated << ") incompatible with requested events (";
+    *fLog << num << ") for " << m->GetDescriptor() << endl;
+
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write the given MHMatrix with its name as default name to a
+// file fname.
+//
+Bool_t MTFillMatrix::WriteMatrix(MHMatrix *m, const TString &fname, Int_t i) const
+{
+    if (!m)
+    {
+        *fLog << "ERROR - Unable to write matrix #" << i << " (=NULL)... ignored." << endl;
+        return kFALSE;
+    }
+    if (fname.IsNull())
+    {
+        *fLog << "ERROR - Unable to write matrix, file name empty." << endl;
+        return kFALSE;
+    }
+
+    TFile file(fname, "RECREATE", m->GetTitle());
+    m->Write();
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Constructor. Takes an MH3 as argument. This MH3 is the reference
+// distribution to fill the matrix. More information can be found
+// at MFEventSelector2 which is used to select the events.
+//
+// If no MH3 *ref is given the events are randomly selected from the
+// total sample - this may result in samples which don't have exactly
+// the predefined size, but it is much faster.
+//
+MTFillMatrix::MTFillMatrix(const MH3 *ref)
+: fReference(0), fReader(0), fDestMatrix1(0), fDestMatrix2(0),
+  fNumDestEvents1(0), fNumDestEvents2(0), fWriteFile1(0), fWriteFile2(0)
+{
+    fName  = "MFillMatrix";
+    fTitle = "Tool to fill MHMatrix from file";
+
+    if (ref)
+        fReference = (MH3*)ref->Clone();
+}
+
+MTFillMatrix::~MTFillMatrix()
+{
+    if (fReference)
+        delete fReference;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the matrix (FIXME: Flow diagram missing)
+//
+Bool_t MTFillMatrix::Process()
+{
+    if (!fReader)
+    {
+        *fLog << err << "ERROR - No task to read data was given... abort." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator(GetDescriptor());
+    *fLog << "Fill " << fDestMatrix1->GetDescriptor() << " with " << fNumDestEvents1 << endl;
+    *fLog << "Fill " << fDestMatrix2->GetDescriptor() << " with " << fNumDestEvents2 << endl;
+    *fLog << "Distribution choosen ";
+    if (fReference && fReference->GetHist().GetEntries()>0)
+        *fLog << "from " << fReference->GetDescriptor();
+    else
+        *fLog << "randomly";
+    *fLog << endl;
+
+    //
+    // Create parameter list and task list, add tasklist to parlist
+    //
+    MParList  plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    //
+    // A selector to select a given number of events from a sample
+    //
+    // FIXME: Merge MFEventSelector and MFEventSelector2
+    MFilter *selector=0;
+    if (fReference)
+    {
+        // Case of a reference/nominal distribution
+        // The events must be read before selection
+        MFEventSelector2 *sel = new MFEventSelector2(*fReference);
+        sel->SetNumMax(fNumDestEvents1+fNumDestEvents2);
+        sel->SetInverted();
+
+        selector = sel;
+    }
+    else
+    {
+        // Case of a random distribution
+        // The events can be selected before reading
+        MFEventSelector *sel = new MFEventSelector;
+        sel->SetNumSelectEvts(fNumDestEvents1+fNumDestEvents2);
+        fReader->SetSelector(sel);
+
+        selector = sel;
+    }
+
+    //
+    // Continue for all events which are not (SetInverted())
+    // selected by the 'selector'
+    //
+    MContinue cont(selector);
+
+    //
+    // Create a filter doing a random split
+    //
+    const Double_t prob = (Double_t)fNumDestEvents1/(fNumDestEvents1+fNumDestEvents2);
+    MFEventSelector split;
+    split.SetSelectionRatio(prob);
+
+    //
+    // Create the logical inverted filter for 'split'
+    //
+    MFilterList invsplit;
+    invsplit.AddToList(&split);
+    invsplit.SetInverted();
+
+    //
+    // The two tasks filling the two matrices
+    //
+    MFillH fill1(fDestMatrix1);
+    MFillH fill2(fDestMatrix2);
+    fill1.SetFilter(&split);
+    fill2.SetFilter(&invsplit);
+
+    // entries in MTaskList
+    tlist.AddToList(fReader);        // Read events
+    if (fReference)
+        tlist.AddToList(&cont);      // select a sample of events
+    tlist.AddToList(&invsplit);      // process invsplit (which implicitly processes split)
+    if (fDestMatrix1 && fNumDestEvents1>0)
+        tlist.AddToList(&fill1);     // fill matrix 1
+    if (fDestMatrix2 && fNumDestEvents2>0)
+        tlist.AddToList(&fill2);     // fill matrix 2
+    if (fWriteFile1)
+    {
+        fWriteFile1->SetFilter(&split);
+        tlist.AddToList(fWriteFile1);
+    }
+    if (fWriteFile2)
+    {
+        fWriteFile2->SetFilter(&invsplit);
+        tlist.AddToList(fWriteFile2);
+    }
+
+    //
+    // Execute the eventloop
+    //
+    MEvtLoop evtloop(fName);
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(fDisplay);
+    evtloop.SetLogStream(fLog);
+
+    const Bool_t rc = evtloop.Eventloop();
+
+    // Print execution statistics of the tasklist
+    if (rc)
+        tlist.PrintStatistics();
+
+    delete selector;
+
+    if (!rc)
+    {
+        *fLog << err << GetDescriptor() << ": Failed." << endl;
+        return kFALSE;
+    }
+
+    // Check the result of filling...
+    CheckResult(fDestMatrix1, fNumDestEvents1);
+    CheckResult(fDestMatrix2, fNumDestEvents2);
+
+    *fLog << inf << GetDescriptor() << ": Done." << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Write both matrices to a file. Return kFALSE if writing one of them
+// failed or both have the same name.
+//
+Bool_t MTFillMatrix::WriteMatrices(const TString &fname) const
+{
+    if (fDestMatrix1 && fDestMatrix2 &&
+        (TString)fDestMatrix1->GetName()==(TString)fDestMatrix2->GetName())
+    {
+        *fLog << "ERROR - Cannot write matrices (both have the same name)... ignored." << endl;
+        return kFALSE;
+    }
+
+    return WriteMatrix1(fname) && WriteMatrix2(fname);
+}
Index: /tags/Mars-V0.9/mtools/MTFillMatrix.h
===================================================================
--- /tags/Mars-V0.9/mtools/MTFillMatrix.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MTFillMatrix.h	(revision 9772)
@@ -0,0 +1,74 @@
+#ifndef MARS_MTFillMatrix
+#define MARS_MTFillMatrix
+
+#ifndef MARS_MH3
+#include "MH3.h"
+#endif
+
+class MRead;
+class MTask;
+class MHMatrix;
+
+class MTFillMatrix : public MParContainer
+{
+private:
+    MH3      *fReference;
+    MRead    *fReader;
+    MHMatrix *fDestMatrix1;
+    MHMatrix *fDestMatrix2;
+    Int_t     fNumDestEvents1;
+    Int_t     fNumDestEvents2;
+    MTask    *fWriteFile1;
+    MTask    *fWriteFile2;
+
+    Bool_t CheckResult(MHMatrix *m, Int_t num) const;
+    Bool_t WriteMatrix(MHMatrix *m, const TString &fname, Int_t i) const;
+
+public:
+    MTFillMatrix(const MH3 *ref=NULL);
+    ~MTFillMatrix();
+
+    void SetDestMatrix1(MHMatrix *matrix, UInt_t num=0)
+    {
+        fDestMatrix1 = matrix;
+        if (num>0)
+            fNumDestEvents1 = num;
+    }
+    void SetWriteFile1(MTask *write, UInt_t num=0)
+    {
+        fWriteFile1 = write;
+        if (num>0)
+            fNumDestEvents1 = num;
+    }
+    void SetNumDestEvents1(UInt_t num)
+    {
+        fNumDestEvents1 = num;
+    }
+    void SetDestMatrix2(MHMatrix *matrix, UInt_t num=0)
+    {
+        fDestMatrix2 = matrix;
+        if (num>0)
+            fNumDestEvents2 = num;
+    }
+    void SetWriteFile2(MTask *write, UInt_t num=0)
+    {
+        fWriteFile2 = write;
+        if (num>0)
+            fNumDestEvents2 = num;
+    }
+    void SetNumDestEvents2(UInt_t num)
+    {
+        fNumDestEvents2 = num;
+    }
+
+    void SetReader(MRead *task) { fReader = task; }
+
+    Bool_t Process();
+    Bool_t WriteMatrix1(const TString &fname) const { return WriteMatrix(fDestMatrix1, fname, 1); }
+    Bool_t WriteMatrix2(const TString &fname) const { return WriteMatrix(fDestMatrix2, fname, 2); }
+    Bool_t WriteMatrices(const TString &fname) const;
+
+    ClassDef(MTFillMatrix, 0) // Tool to fill matrices (eg. trainings- and test-matrices)
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MTMinuit.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MTMinuit.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MTMinuit.cc	(revision 9772)
@@ -0,0 +1,329 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Wolfgang Wittek, 7/2003 <mailto:wittek@mppmu.mpg.de>
+!   Author(s): Thomas Bretz, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTMinuit
+//
+// Class for interfacing with Minuit
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTMinuit.h"
+
+#include <TMinuit.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTMinuit);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MTMinuit::MTMinuit(const char *name, const char *title)
+    : fFcn(NULL), fNames(NULL), fMinuit(NULL)
+{
+    fName  = name  ? name  : "MTMinuit";
+    fTitle = title ? title : "Interface for Minuit";
+}
+
+MTMinuit::~MTMinuit()
+{
+    if (fMinuit)
+        delete fMinuit;
+}
+
+TMinuit *MTMinuit::GetMinuit() const
+{
+    return fMinuit;
+}
+
+void MTMinuit::SetFcn(void (*fcn)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t))
+{
+    fFcn = fcn;
+}
+
+void MTMinuit::InitParameters(const TArrayD &vinit, const TArrayD *step, const TString *name)
+{
+    const int n = fVinit.GetSize();
+
+    fVinit = vinit;
+
+    fStep.Set(n);
+    memset(fStep.GetArray(), 0, n*sizeof(Double_t));
+
+    if (step && step->GetSize()!=n)
+    {
+        *fLog << warn << "MTMinuit::SetParameters: number of steps doesn't match number of parameters... ignored." << endl;
+        step = NULL;
+    }
+
+    for (int i=0; i<n; i++)
+        fStep[i] = step ? (*step)[i] : TMath::Abs(fVinit[i]/10.0);
+
+    if (fNames)
+        delete fNames;
+
+    fNames = new TString[n];
+
+    // FIXME: Sanity check for TString array size!
+    for (int i=0; i<n ; i++)
+        fNames[i] = name ? (const char*)name[i] : Form("par%02d", i);
+
+    // ---------------------------------------------------------------
+
+    fLimLo.Set(n);
+    fLimUp.Set(n);
+    memset(fLimLo.GetArray(), 0, n*sizeof(Double_t));
+    memset(fLimUp.GetArray(), 0, n*sizeof(Double_t));
+
+    fFix.Set(n);
+    memset(fFix.GetArray(), 0, n*sizeof(Char_t));
+}
+
+void MTMinuit::SetLimits(const TArrayD &limlo, const TArrayD &limup)
+{
+    if (fVinit.GetSize()==limlo.GetSize())
+        fLimLo = limlo;
+    else
+        *fLog << warn << "MTMinuit::SetLimits: size of limlo doesn't match number of parameters... ignored." << endl;
+
+    if (fVinit.GetSize()==limup.GetSize())
+        fLimUp = limup;
+    else
+        *fLog << warn << "MTMinuit::SetLimits: size of limup doesn't match number of parameters... ignored." << endl;
+}
+
+void MTMinuit::SetFixedParameters(const TArrayC &fix)
+{
+    if (fVinit.GetSize()==fix.GetSize())
+        fFix = fix;
+    else
+        *fLog << warn << "MTMinuit::SetFixedParameters: size of fix doesn't match number of parameters... ignored." << endl;
+}
+
+// -----------------------------------------------------------------------
+//
+// Interface to MINUIT
+//
+Bool_t MTMinuit::CallMinuit(TObject *objectfit , const TString &method, Bool_t nulloutput)
+{
+    if (!fFcn(NULL))
+    {
+        *fLog << err << "CallMinuit: ERROR - fFcn not set... abort." << endl;
+        return kFALSE;
+    }
+    if (!fNames)
+    {
+        *fLog << err << "CallMinuit: ERROR - Parameters not set... abort." << endl;
+        return kFALSE;
+    }
+
+    // Make a copy of fStep
+    TArrayD step(fStep);
+
+    // Save gMinuit
+    TMinuit *const save = gMinuit;
+
+    // Set the maximum number of parameters
+    if (fMinuit)
+        delete fMinuit;
+    fMinuit = new TMinuit(fVinit.GetSize());
+
+    //
+    // Set the print level
+    // -1   no output except SHOW comands
+    //  0   minimum output
+    //  1   normal output (default)
+    //  2   additional ouput giving intermediate results
+    //  3   maximum output, showing progress of minimizations
+    //
+    fMinuit->SetPrintLevel(-1);
+
+    //..............................................
+    // Printout for warnings
+    //    SET WAR      print warnings
+    //    SET NOW      suppress warnings
+    Int_t errWarn;
+    Double_t tmpwar = 0;
+    fMinuit->mnexcm("SET NOW", &tmpwar, 0, errWarn);
+    //fMinuit->mnexcm("SET WAR", &tmpwar, 0, errWarn);
+
+    //..............................................
+    // Set the address of the minimization function
+    fMinuit->SetFCN(fFcn);
+
+    //..............................................
+    // Store address of object to be used in fcn
+    fMinuit->SetObjectFit(objectfit);
+
+    //..............................................
+    // Set starting values and step sizes for parameters
+    for (Int_t i=0; i<fVinit.GetSize(); i++)
+    {
+        if (!fMinuit->DefineParameter(i, fNames[i], fVinit[i], fStep[i], fLimLo[i], fLimUp[i]))
+            continue;
+
+        *fLog << err << "CallMinuit: Error in defining parameter " << fNames[i] << endl;
+        return kFALSE;
+    }
+
+    //
+    // Error definition :
+    //
+    //    for chisquare function :
+    //      up = 1.0   means calculate 1-standard deviation error
+    //         = 4.0   means calculate 2-standard deviation error
+    //
+    //    for log(likelihood) function :
+    //      up = 0.5   means calculate 1-standard deviation error
+    //         = 2.0   means calculate 2-standard deviation error
+    //
+    fMinuit->SetErrorDef(1.0);
+
+    // Int_t errMigrad;
+    // Double_t tmp = 0;
+    // fMinuit->mnexcm("MIGRAD", &tmp, 0, errMigrad);
+
+    // fix a parameter
+    for (Int_t i=0; i<fVinit.GetSize(); i++)
+    {
+        if (!fFix[i])
+            continue;
+
+        fMinuit->FixParameter(i);
+    }
+
+    //..............................................
+    // This doesn't seem to have any effect
+    // Set maximum number of iterations (default = 500)
+    //Int_t maxiter = 100000;
+    //fMinuit->SetMaxIterations(maxiter);
+
+    // minimization by the method of Migrad
+    Int_t fErrMinimize=0;
+    if (method.Contains("Migrad", TString::kIgnoreCase))
+    {
+        if (nulloutput)
+            fLog->SetNullOutput(kTRUE);
+        Double_t tmp = 0;
+        fMinuit->mnexcm("MIGRAD", &tmp, 0, fErrMinimize);
+        if (nulloutput)
+            fLog->SetNullOutput(kFALSE);
+    }
+
+    //..............................................
+    // same minimization as by Migrad
+    // but switches to the SIMPLEX method if MIGRAD fails to converge
+    if (method.Contains("Minimize", TString::kIgnoreCase))
+    {
+        Double_t tmp = 0;
+        fMinuit->mnexcm("MINIMIZE", &tmp, 0, fErrMinimize);
+    }
+
+    //..............................................
+    // minimization by the SIMPLEX method
+    if (method.Contains("Simplex", TString::kIgnoreCase))
+    {
+        Double_t tmp[2];
+        tmp[0] = 3000; // maxcalls;
+        tmp[1] = 0.1;  // tolerance;
+
+        if (nulloutput)
+            fLog->SetNullOutput(kTRUE);
+        fMinuit->mnexcm("SIMPLEX", &tmp[0], 2, fErrMinimize);
+        if (nulloutput)
+            fLog->SetNullOutput(kFALSE);
+    }
+
+    //..............................................
+    // check quality of minimization
+    // istat = 0   covariance matrix not calculated
+    //         1   diagonal approximation only (not accurate)
+    //         2   full matrix, but forced positive-definite
+    //         3   full accurate covariance matrix
+    //             (indication of normal convergence)
+    Double_t fMin,   fEdm,   fErrdef;
+    Int_t    fNpari, fNparx, fIstat;
+    fMinuit->mnstat(fMin, fEdm, fErrdef, fNpari, fNparx, fIstat);
+
+    if (fErrMinimize != 0)
+    {
+        *fLog << err << "CallMinuit: Minimization failed with:" << endl;
+        *fLog << "  fMin = " << fMin << endl;
+        *fLog << "  fEdm = "  << fEdm << endl;
+        *fLog << "  fErrdef = "  << fErrdef << endl;
+        *fLog << "  fIstat = " << fIstat << endl;
+        *fLog << "  fErrMinimize = " << fErrMinimize << endl;
+        return kFALSE;
+    }
+
+    //..............................................
+    // minimization by the method of Migrad
+    if (method.Contains("Hesse", TString::kIgnoreCase))
+    {
+        Double_t tmp = 0;
+        fMinuit->mnexcm("HESSE", &tmp, 0, fErrMinimize);
+    }
+
+    //..............................................
+    // Minos error analysis
+    if (method.Contains("Minos", TString::kIgnoreCase))
+    {
+        Double_t tmp = 0;
+        fMinuit->mnexcm("MINOS", &tmp, 0, fErrMinimize);
+    }
+
+    //..............................................
+    // Print current status of minimization
+    // if nkode = 0    only function value
+    //            1    parameter values, errors, limits
+    //            2    values, errors, step sizes, internal values
+    //            3    values, errors, step sizes, 1st derivatives
+    //            4    values, parabolic errors, MINOS errors
+
+    //Int_t nkode = 4;
+    //fMinuit->mnprin(nkode, fmin);
+
+    //..............................................
+    // call fcn with IFLAG = 3 (final calculation : calculate p(chi2))
+    // iflag = 1   initial calculations only
+    //         2   calculate 1st derivatives and function
+    //         3   calculate function only
+    //         4   calculate function + final calculations
+    Double_t iflag = 3;
+    Int_t errfcn3;
+    fMinuit->mnexcm("CALL", &iflag, 1, errfcn3);
+
+    // WW : the following statements were commented out because the
+    // Minuit object will still be used;
+    // this may be changed in the future 
+    gMinuit = save;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtools/MTMinuit.h
===================================================================
--- /tags/Mars-V0.9/mtools/MTMinuit.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MTMinuit.h	(revision 9772)
@@ -0,0 +1,51 @@
+#ifndef MARS_MTMinuit
+#define MARS_MTMinuit
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class TMinuit;
+
+class MTMinuit : public MParContainer
+{
+private:
+    // FIXME: Maybe we can use a TMinuit Object to store all this?
+    void (*fFcn)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t);
+
+    TString *fNames;
+    TMinuit *fMinuit;
+
+    TArrayD fVinit;
+    TArrayD fStep;
+    TArrayD fLimLo;
+    TArrayD fLimUp;
+    TArrayC fFix;
+
+public:
+    // FIXME: Use FCN as first argument...
+    MTMinuit(const char *name=NULL, const char *title=NULL);
+    ~MTMinuit();
+
+    Bool_t CallMinuit(TObject *fObjectFit, const TString &method, Bool_t nulloutput);
+
+    TMinuit *GetMinuit() const;
+
+    void SetFcn(void (*fcn)(Int_t &, Double_t *, Double_t &, Double_t *, Int_t));
+    void InitParameters(const TArrayD &vinit, const TArrayD *step=0, const TString *name=0);
+
+    void SetLimits(const TArrayD &limlo, const TArrayD &limup);
+    void SetFixedParameters(const TArrayC &fix);
+
+    ClassDef(MTMinuit, 0) // Class for interfacing with Minuit
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MagicCivilization.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MagicCivilization.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicCivilization.cc	(revision 9772)
@@ -0,0 +1,441 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 07/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MagicCivilization
+// ---------
+//
+// Tool to visualize Next Neighbours.
+//
+// Start the show by:
+//   MagicCivilization show;
+//
+// Use the following keys:
+// -----------------------
+//
+//   * Space:
+//     Toggle between auto increment and manual increment
+//
+//   * Right/Left:
+//     Increment/Decrement pixel number by 1
+//
+//   * Right/Left:
+//     Increment/Decrement pixel number by 1
+//
+//   * Up/Down:
+//     Increment/Decrement pixel number by 10
+//
+//   * PageUp/PageDown:
+//     Increment/Decrement pixel number by 100
+//
+//   * Home/End:
+//     Jump to first/last pixel
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MagicCivilization.h"
+
+#include <iostream>
+
+#include <KeySymbols.h>
+
+#include <TCanvas.h>
+#include <TRandom.h>
+#include <TInterpreter.h>
+
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MagicCivilization);
+
+using namespace std;
+
+void MagicCivilization::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    fPixels->Delete();
+
+    delete fPixels;
+
+    delete fGeomCam;
+}
+
+// ------------------------------------------------------------------------
+//
+// Draw all pixels of the camera
+//  (means apend all pixelobjects to the current pad)
+//
+void MagicCivilization::DrawHexagons()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+        (*this)[i].Draw();
+}
+
+void MagicCivilization::ChangeCamera()
+{
+    static Bool_t ct1=kFALSE;
+
+    cout << "Change to " << (ct1?"Magic":"CT1") << endl;
+
+    if (ct1)
+        SetNewCamera(new MGeomCamMagic);
+    else
+        SetNewCamera(new MGeomCamCT1);
+
+    ct1 = !ct1;
+
+    DrawHexagons();
+}
+
+void MagicCivilization::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Reset the display geometry
+    //
+    fW=0;
+    fH=0;
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    //
+    // Construct all hexagons. Use new-operator with placement
+    //
+    fPixels = new TClonesArray("MHexagon", fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = *new ((*fPixels)[i]) MHexagon((*fGeomCam)[i]);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        h.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicCivilization::MagicCivilization(Byte_t lim, UShort_t init)
+    : fTimer(this, 500, kTRUE), fGeomCam(NULL), fNumInit(init), fLimit(lim), fW(0), fH(0)
+{
+    SetNewCamera(new MGeomCamMagic);
+
+    //
+    // Make sure, that the object is destroyed when the canvas/pad is
+    // destroyed. Make also sure, that the interpreter doesn't try to
+    // delete it a second time.
+    //
+    SetBit(kCanDelete);
+    gInterpreter->DeleteGlobal(this);
+
+    Draw();
+
+    fTimer.TurnOn();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MagicCivilization::~MagicCivilization()
+{
+    fTimer.TurnOff();
+    Free();
+
+    if (fDrawingPad->GetListOfPrimitives()->FindObject(this)==this)
+    {
+        fDrawingPad->RecursiveRemove(this);
+        delete fDrawingPad;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// This is called at any time the canvas should get repainted.
+// Here we maintain an aspect ratio of 5/4=1.15. This makes sure,
+// that the camera image doesn't get distorted by resizing the canvas.
+//
+void MagicCivilization::Paint(Option_t *opt)
+{
+    const UInt_t w = (UInt_t)(gPad->GetWw()*gPad->GetAbsWNDC());
+    const UInt_t h = (UInt_t)(gPad->GetWh()*gPad->GetAbsHNDC());
+
+    //
+    // Check for a change in width or height, and make sure, that the
+    // first call also sets the range
+    //
+    if (w*fH == h*fW && fW && fH)
+        return;
+
+    //
+    // Calculate aspect ratio (5/4=1.25 recommended)
+    //
+    const Double_t ratio = (Double_t)w/h;
+
+    Float_t x;
+    Float_t y;
+
+    if (ratio>1.0)
+    {
+        x = fRange*(ratio*2-1);
+        y = fRange;
+    }
+    else
+    {
+        x = fRange;
+        y = fRange/ratio;
+    }
+
+    fH = h;
+    fW = w;
+
+    //
+    // Set new range
+    //
+    fDrawingPad->Range(-fRange, -y, x, y);
+}
+
+void MagicCivilization::Reset()
+{
+    if (fNumInit>=fNumPixels)
+        fNumInit = fNumPixels-1;
+    if (fNumInit<0)
+        fNumInit = 0;
+
+    if (fLimit<0)
+        fLimit=6;
+    if (fLimit>6)
+        fLimit=0;
+
+
+    TRandom rnd(0);
+    for (int i=0; i<fNumPixels; i++)
+        (*fGeomCam)[i].ResetBit(kUserBits);
+
+    for (int i=0; i<fNumInit; i++)
+    {
+        Int_t idx;
+
+        do idx = (Int_t)rnd.Uniform(fNumPixels);
+        while ((*fGeomCam)[idx].TestBit(kHasFlag));
+
+        if (idx>=fNumPixels)
+            cout << "!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
+
+        (*fGeomCam)[idx].SetBit(kHasFlag);
+    }
+
+    fAuto = kFALSE;
+    fStep = 0;
+
+    Update();
+
+    fDrawingPad->Modified();
+    fDrawingPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to draw the camera layout into your canvas.
+// Setup a drawing canvas. Add this object and all child objects
+// (hexagons, etc) to the current pad. If no pad exists a new one is
+// created.
+//
+void MagicCivilization::Draw(Option_t *option)
+{
+    //
+    // if no canvas is yet existing to draw into, create a new one
+    //
+    /*TCanvas *c =*/ new TCanvas("MagicCivilization", "Magic Civilization", 0, 0, 800, 800);
+    //c->ToggleEventStatus();
+
+    fDrawingPad = gPad;
+    fDrawingPad->SetBorderMode(0);
+    fDrawingPad->SetFillColor(22);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    //
+    // Reset the game pad
+    //
+    DrawHexagons();
+
+    fCivilization.SetTextAlign(23);   // centered/bottom
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fCivilization.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    fCivilization.Draw();
+
+    Reset();
+}
+
+void MagicCivilization::Update()
+{
+    TString txt = "Lim: ";
+    txt += (int)fLimit;
+    txt += "  Init: ";
+    txt += fNumInit;
+    txt += "  On: ";
+    txt += fNumCivilizations;
+    txt += "  Step: ";
+    txt += fStep;
+
+    if (!fAuto)
+        txt += "  (paused)";
+
+    fCivilization.SetText(0, fRange, txt);
+}
+
+
+
+// ------------------------------------------------------------------------
+//
+// Execute a mouse event on the camera
+//
+void MagicCivilization::ExecuteEvent(Int_t event, Int_t keycode, Int_t keysym)
+{
+    if (event!=kKeyPress)
+        return;
+
+    switch (keysym)
+    {
+    default:
+        return;
+
+    case kKey_Space:
+        if ((fNumCivilizations==0 || fNumCivilizations==fNumPixels) && !fAuto)
+            Reset();
+        fAuto = !fAuto;
+        Update();
+        fDrawingPad->Update();
+        return;
+
+    case kKey_Right:
+        fNumInit += 1;;
+        break;
+
+    case kKey_Left:
+        fNumInit -= 1;
+        break;
+
+    case kKey_Up:
+        fNumInit += 10;
+        break;
+
+    case kKey_Down:
+        fNumInit -= 10;
+        break;
+
+    case kKey_PageUp:
+        fNumInit += 100;
+        break;
+
+    case kKey_PageDown:
+        fNumInit -= 100;
+        break;
+
+    case kKey_Plus:
+        fLimit++;
+        break;
+
+    case kKey_Minus:
+        fLimit--;
+        break;
+    }
+
+    Reset();
+}
+
+Bool_t MagicCivilization::HandleTimer(TTimer *timer)
+{
+    if (!fAuto)
+        return kTRUE;
+
+    for (int i=0; i<fNumPixels; i++)
+    {
+        MGeomPix &pix = (*fGeomCam)[i];
+
+        Byte_t cnt=0;
+        for (int j=0; j<pix.GetNumNeighbors(); j++)
+            if ((*fGeomCam)[pix.GetNeighbor(j)].TestBit(kHasFlag))
+                cnt++;
+
+        cnt += (6-pix.GetNumNeighbors())*cnt/6;
+
+        if (cnt>fLimit)
+            pix.SetBit(kHasCreation);
+    }
+
+    fNumCivilizations = 0;
+    for (int i=0; i<fNumPixels; i++)
+    {
+        MGeomPix &pix = (*fGeomCam)[i];
+        MHexagon &hex = (*this)[i];
+
+        if (pix.TestBit(kHasCreation))
+        {
+            pix.SetBit(kHasFlag);
+            hex.SetFillColor(kBlack);
+            fNumCivilizations++;
+        }
+        else
+        {
+            pix.ResetBit(kHasFlag);
+            hex.SetFillColor(kBackground);
+        }
+        pix.ResetBit(kHasCreation);
+    }
+
+    if (fNumCivilizations==0 || fNumCivilizations==fNumPixels)
+        fAuto = kFALSE;
+
+    fStep++;
+
+    Update();
+
+    fDrawingPad->Update();
+
+    return kTRUE;
+}
+
Index: /tags/Mars-V0.9/mtools/MagicCivilization.h
===================================================================
--- /tags/Mars-V0.9/mtools/MagicCivilization.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicCivilization.h	(revision 9772)
@@ -0,0 +1,81 @@
+#ifndef MARS_MagicCivilization
+#define MARS_MagicCivilization
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TText
+#include <TText.h>
+#endif
+#ifndef ROOT_TTimer
+#include <TTimer.h>
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class MagicCivilization : public TObject
+{
+private:
+    enum
+    {
+        kBackground   = 50,
+        kHasFlag      = BIT(17),
+        kHasCreation  = BIT(18),
+        kUserBits     = 0x7fc000 // 14-23 are allowed
+    };
+
+    TTimer    fTimer;           // timer rising the 500ms interrputs
+
+    MGeomCam *fGeomCam;         // pointer to camera geometry
+
+    UShort_t  fNumPixels;       // number of pixels in the present geometry
+    Short_t   fNumInit;         // number of bombs in the field
+    Float_t   fRange;           // the range in millimeters of the present geometry
+
+    Bool_t    fAuto;
+
+    Char_t    fLimit;
+
+    UShort_t  fNumCivilizations;
+    UInt_t    fStep;
+
+    TText     fCivilization;    // TText showing the numbers of pixels and bombs
+
+    UInt_t    fW;               // Width of canvas
+    UInt_t    fH;               // Height of canvas
+
+    TClonesArray *fPixels;      // array of all hexagons
+    TVirtualPad  *fDrawingPad;  // pad in which we are drawing
+
+    MHexagon &operator[](int i) { return *((MHexagon*)fPixels->At(i)); }
+
+    void   Update();
+    void   Free();
+    void   DrawHexagons();
+    void   SetNewCamera(MGeomCam *);
+
+    Bool_t HandleTimer(TTimer *timer);
+    void   Draw(Option_t *option="");
+    void   Paint(Option_t *option="");
+    void   ExecuteEvent(Int_t event, Int_t px, Int_t py);
+    Int_t  DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+public:
+    MagicCivilization(Byte_t lim=2, UShort_t init=200);
+    ~MagicCivilization();
+
+    void ChangeCamera(); //*MENU*
+    void Reset();        //*MENU*
+
+    ClassDef(MagicCivilization, 0) // Tool to visualize next neighbours
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MagicDomino.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MagicDomino.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicDomino.cc	(revision 9772)
@@ -0,0 +1,724 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 07/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MagicDomino
+// -----------
+//
+// Magic Camera games.
+//
+// Start the show by:
+//   MagicDomino show;
+//
+// Use the following keys:
+// -----------------------
+//
+//   * Cursor up/down, left/right:
+//     Move tile
+//
+//   * Space:
+//     Rotate tile
+//
+//   * Enter:
+//     Set tile
+//
+//   * Esc:
+//     Skip tile
+//
+//  Rules:
+//  ------
+//
+//   Each hexagon in the tile must at least have one neighbor
+//   which has the same color. It is not allowed to put a tile onto
+//   another one. The game is over if you have skipped three tiles
+//   in a row.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MagicDomino.h"
+
+#include <iostream>
+
+#include <KeySymbols.h>
+
+#include <TCanvas.h>
+#include <TRandom.h>
+#include <TInterpreter.h>
+
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MagicDomino);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Free all onbects connected to a special camera geometry
+//
+void MagicDomino::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    fPixels->Delete();
+
+    delete fPixels;
+
+    delete fGeomCam;
+}
+
+// ------------------------------------------------------------------------
+//
+// Draw all pixels of the camera
+//  (means apend all pixelobjects to the current pad)
+//
+void MagicDomino::DrawHexagons()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+        (*this)[i].Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+// Change camera from Magic to CT1 and back
+//
+void MagicDomino::ChangeCamera()
+{
+    static Bool_t ct1=kFALSE;
+
+    cout << "Change to " << (ct1?"Magic":"CT1") << endl;
+
+    if (ct1)
+        SetNewCamera(new MGeomCamMagic);
+    else
+        SetNewCamera(new MGeomCamCT1);
+
+    ct1 = !ct1;
+
+    Reset();
+    DrawHexagons();
+}
+
+// ------------------------------------------------------------------------
+//
+// Reset/set all veriables needed for a new camera geometry
+//
+void MagicDomino::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Reset the display geometry
+    //
+    fW=0;
+    fH=0;
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    //
+    // Construct all hexagons. Use new-operator with placement
+    //
+    fPixels = new TClonesArray("MHexagon", fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = *new ((*fPixels)[i]) MHexagon((*fGeomCam)[i]);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        h.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// remove the pixel numbers in the tile from the pad
+//
+void MagicDomino::RemoveNumbers()
+{
+    for (int i=0; i<6; i++)
+        if (fText[i])
+        {
+            delete fText[i];
+            fText[i] = NULL;
+        }
+}
+
+// ------------------------------------------------------------------------
+//
+// Reset/restart the game
+//
+void MagicDomino::Reset()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = (*this)[i];
+        h.SetFillColor(kBackground);
+        h.ResetBit(kUserBits);
+    }
+
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDrawingPad->SetBit(kNoContextMenu);
+    SetBit(kNoContextMenu);
+#endif
+
+    if (fDone)
+    {
+        delete fDone;
+        fDone = NULL;
+    }
+
+
+    fDrawingPad->SetFillColor(22);
+
+    fNumPixel = -1;
+    fNumTile  =  0;
+    fPoints   =  0;
+
+    NewTile();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicDomino::MagicDomino()
+    : fGeomCam(NULL), fDir(kBottom), fDone(NULL)
+{
+    memset(fText, 0, sizeof(fText));
+
+    SetNewCamera(new MGeomCamMagic);
+
+    //
+    // Make sure, that the object is destroyed when the canvas/pad is
+    // destroyed. Make also sure, that the interpreter doesn't try to
+    // delete it a second time.
+    //
+    SetBit(kCanDelete);
+    gInterpreter->DeleteGlobal(this);
+
+    Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MagicDomino::~MagicDomino()
+{
+    Free();
+
+    RemoveNumbers();
+
+    if (fDrawingPad->GetListOfPrimitives()->FindObject(this)==this)
+    {
+        fDrawingPad->RecursiveRemove(this);
+        delete fDrawingPad;
+    }
+
+}
+
+// ------------------------------------------------------------------------
+//
+// This is called at any time the canvas should get repainted.
+// Here we maintain an aspect ratio of 5/4=1.15. This makes sure,
+// that the camera image doesn't get distorted by resizing the canvas.
+//
+void MagicDomino::Paint(Option_t *opt)
+{
+    const UInt_t w = (UInt_t)(gPad->GetWw()*gPad->GetAbsWNDC());
+    const UInt_t h = (UInt_t)(gPad->GetWh()*gPad->GetAbsHNDC());
+
+    //
+    // Check for a change in width or height, and make sure, that the
+    // first call also sets the range
+    //
+    if (w*fH == h*fW && fW && fH)
+        return;
+
+    //
+    // Calculate aspect ratio (5/4=1.25 recommended)
+    //
+    const Double_t ratio = (Double_t)w/h;
+
+    Float_t x;
+    Float_t y;
+
+    if (ratio>1.0)
+    {
+        x = fRange*(ratio*2-1);
+        y = fRange;
+    }
+    else
+    {
+        x = fRange;
+        y = fRange/ratio;
+    }
+
+    fH = h;
+    fW = w;
+
+    //
+    // Set new range
+    //
+    fDrawingPad->Range(-fRange, -y, x, y);
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to draw the camera layout into your canvas.
+// Setup a drawing canvas. Add this object and all child objects
+// (hexagons, etc) to the current pad. If no pad exists a new one is
+// created.
+//
+void MagicDomino::Draw(Option_t *option)
+{
+    //
+    // if no canvas is yet existing to draw into, create a new one
+    //
+    /*TCanvas *c =*/ new TCanvas("MagicDomino", "Magic Domino Next Neighbours", 0, 0, 800, 800);
+    //c->ToggleEventStatus();
+
+    fDrawingPad = gPad;
+    fDrawingPad->SetBorderMode(0);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    //
+    // Reset the game pad
+    //
+    Reset();
+    DrawHexagons();
+
+    /*
+     TPave *p = new TPave(-0.66*fRange, 0.895*fRange, 0.66*fRange, 0.995*fRange, 4, "br");
+     p->ConvertNDCtoPad();
+     p->SetFillColor(12);
+     p->SetBit(kCanDelete);
+     p->Draw();
+     */
+
+    fDomino.SetTextAlign(23);   // centered/bottom
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDomino.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    fDomino.Draw();
+}
+
+void MagicDomino::Update()
+{
+    TString txt = "Points: ";
+    txt += fPoints;
+    txt += "  Tile: ";
+    txt += fNumTile;
+
+    switch (fSkipped)
+    {
+    case 0:
+        fDomino.SetTextColor(8/*kGreen*/);
+        break;
+    case 1:
+        fDomino.SetTextColor(kYellow);
+        break;
+    case 2:
+        fDomino.SetTextColor(kRed);
+        break;
+    default:
+        fDomino.SetTextColor(kWhite);
+        break;
+    }
+    fDomino.SetText(0, fRange, txt);
+}
+
+// ------------------------------------------------------------------------
+//
+// Choose new colors for the tile
+//
+void MagicDomino::NewColors()
+{
+    TRandom rnd(0);
+    for (int i=0; i<3; i++)
+    {
+        Int_t color = (Int_t)rnd.Uniform(5)+2;
+        fNewColors[i*2]   = color;
+        fNewColors[i*2+1] = color;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Create a new tile
+//
+void MagicDomino::NewTile()
+{
+    if (fNumPixel>=0)
+    {
+        const MGeomPix &pix=(*fGeomCam)[fNumPixel];
+        (*this)[fNumPixel].ResetBit(kIsTile);
+        for (int i=0; i<pix.GetNumNeighbors(); i++)
+            (*this)[pix.GetNeighbor(i)].ResetBit(kIsTile);
+
+        fPoints += pix.GetNumNeighbors();
+    }
+
+    RemoveNumbers();
+
+    fNumPixel = -1;
+    fSkipped  =  0;
+    fNumTile++;
+
+    NewColors();
+    Update();
+
+    fDrawingPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+//  Check for at least one correct color for each pixel in tile.
+//  Ignore the tile itself and all background pixels. Check whether
+//  background of tile is empty.
+//
+Bool_t MagicDomino::CheckTile()
+{
+    if (fNumPixel<0)
+        return kFALSE;
+
+    for (int i=0; i<7; i++)
+        if (fOldColors[i]!=kBackground)
+            return kFALSE;
+
+    Int_t cnt=0;
+    const MGeomPix &pix1=(*fGeomCam)[fNumPixel];
+    for (int i=0; i<pix1.GetNumNeighbors(); i++)
+    {
+        const Int_t idx1 = pix1.GetNeighbor(i);
+        const MGeomPix &pix2 = (*fGeomCam)[idx1];
+
+        Byte_t ignored = 0;
+        Byte_t found   = 0;
+        for (int j=0; j<pix2.GetNumNeighbors(); j++)
+        {
+            const Int_t    idx2 = pix2.GetNeighbor(j);
+            const MHexagon &hex = (*this)[idx2];
+
+            if (hex.TestBit(kIsTile) || hex.GetFillColor()==kBackground)
+            {
+                ignored++;
+                continue;
+            }
+
+            if (hex.GetFillColor()==(*this)[idx1].GetFillColor())
+                found++;
+        }
+        if (ignored==pix2.GetNumNeighbors() || found>0)
+            cnt++;
+    }
+
+    return cnt==pix1.GetNumNeighbors();
+}
+
+// ------------------------------------------------------------------------
+//
+// Game over!
+//
+void MagicDomino::Done()
+{
+    fDone = new TText(0, 0, "Game Over!");
+    fDone->SetTextColor(kWhite);  // white
+    fDone->SetTextAlign(22);  // centered/centered
+    fDone->SetTextSize(0.05); // white
+    fDone->Draw();
+
+    fDomino.SetTextColor(kBlue);
+
+    fDrawingPad->SetFillColor(kRed);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDone->SetBit(kNoContextMenu|kCannotPick);
+    fDrawingPad->ResetBit(kNoContextMenu);
+    ResetBit(kNoContextMenu);
+#endif
+
+    fDrawingPad->Modified();
+    fDrawingPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a mouse event on the camera
+//
+void MagicDomino::ExecuteEvent(Int_t event, Int_t keycode, Int_t keysym)
+{
+    if (event!=kKeyPress || fDone)
+        return;
+
+    switch (keysym)
+    {
+    case kKey_Escape:
+        fPoints -= 6;
+        fSkipped++;
+        if (fSkipped==3)
+        {
+            Done();
+            return;
+        }
+        NewColors();
+        RotateTile(0);
+        return;
+
+    case kKey_Space:
+        RotateTile(-1);
+        return;
+
+    case kKey_Return:
+        if (CheckTile())
+            NewTile();
+        return;
+
+    case kKey_Right:
+        fDir = kRight;
+        Step(kRight);
+        return;
+
+    case kKey_Left:
+        fDir = kLeft;
+        Step(kLeft);
+        return;
+
+    case kKey_Up:
+        Step(kTop|fDir);
+        return;
+
+    case kKey_Down:
+        Step(kBottom|fDir);
+        return;
+
+    case kKey_Plus:
+        RotateTile(+1);
+        return;
+
+    case kKey_Minus:
+        RotateTile(-1);
+        return;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Rotate the colors in the tile
+//
+void MagicDomino::RotateTile(Int_t add)
+{
+    fPosition += add+6;  // Make result positive
+    fPosition %= 6;      // Align result between 0 and 5
+
+    HideTile();
+    ShowTile();
+
+    Update();
+
+    fDrawingPad->Modified();
+    fDrawingPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// Hide the tile from the pad
+//
+void MagicDomino::HideTile()
+{
+    if (fNumPixel<0)
+        return;
+
+    MagicDomino &This = *this;
+
+    RemoveNumbers();
+
+    const MGeomPix &pix1=(*fGeomCam)[fNumPixel];
+    This[fNumPixel].SetFillColor(fOldColors[6]);
+    This[fNumPixel].ResetBit(kIsTile);
+    for (int i=0; i<pix1.GetNumNeighbors(); i++)
+    {
+        Int_t idx = pix1.GetNeighbor(i);
+
+        This[idx].SetFillColor(fOldColors[i]);
+        This[idx].ResetBit(kIsTile);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Show the tile on the pad
+//
+void MagicDomino::ShowTile()
+{
+    if (fNumPixel<0)
+        return;
+
+    MagicDomino &This = *this;
+
+    Int_t indices[6];
+    GetSortedNeighbors(indices);
+
+    RemoveNumbers();
+
+    const MGeomPix &pix2=(*fGeomCam)[fNumPixel];
+    fOldColors[6] = This[fNumPixel].GetFillColor();
+    This[fNumPixel].SetFillColor(kBlack);
+    This[fNumPixel].SetBit(kIsTile);
+    for (int i=0; i<pix2.GetNumNeighbors(); i++)
+    {
+        Int_t idx = pix2.GetNeighbor(i);
+
+        fOldColors[i] = This[idx].GetFillColor();
+
+        int j=0;
+        while (indices[j]!=i)
+            j++;
+
+        This[idx].SetFillColor(fNewColors[(j+fPosition)%6]);
+        This[idx].SetBit(kIsTile);
+
+        TString num;
+        num += idx;
+
+        fText[i] = new TText(This[idx].GetX(), This[idx].GetY(), num);
+        fText[i]->SetTextSize(0.3*This[idx].GetD()/fGeomCam->GetMaxRadius());
+        fText[i]->SetTextFont(122);
+        fText[i]->SetTextAlign(22);   // centered/centered
+        fText[i]->Draw();
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Hide the tile, change its position, show it again, update status text
+//
+void MagicDomino::ChangePixel(Int_t add)
+{
+    HideTile();
+
+    fNumPixel = add;
+
+    ShowTile();
+
+    Update();
+
+    fDrawingPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// Analyse the directions of the next neighbors
+//
+Short_t MagicDomino::AnalysePixel(Int_t dir)
+{
+    const MGeomPix &pix=(*fGeomCam)[fNumPixel<0?0:fNumPixel];
+
+    Double_t fAngle[6] = { -10, -10, -10, -10, -10, -10 };
+
+    for (int i=0; i<pix.GetNumNeighbors(); i++)
+    {
+        MGeomPix &next = (*fGeomCam)[pix.GetNeighbor(i)];
+        fAngle[i] = atan2(next.GetY()-pix.GetY(), next.GetX()-pix.GetX());
+    }
+
+    Int_t indices[6];
+    TMath::Sort(6, fAngle, indices); // left, top, right, bottom
+
+    for (int i=0; i<pix.GetNumNeighbors(); i++)
+    {
+        const Int_t    idx   = pix.GetNeighbor(indices[i]);
+        const Double_t angle = fAngle[indices[i]]*180/TMath::Pi();
+
+        if (angle<-149 && dir==kLeft)
+            return idx;
+        if (angle>-149 && angle<-90 && dir==kBottomLeft)
+            return idx;
+        //if (angle==-90 && dir==kBottom)
+        //    return idx;
+        if (angle>-90 && angle<-31 && dir==kBottomRight)
+            return idx;
+        if (angle>-31 && angle<31 && dir==kRight)
+            return idx;
+        if (angle>31 && angle<90 && dir==kTopRight)
+            return idx;
+        //if (angle==90 && dir==kTop)
+        //    return idx;
+        if (angle>90 && angle<149 && dir==kTopLeft)
+            return idx;
+        if (angle>149 && dir==kLeft)
+            return idx;
+    }
+    return -1;
+}
+
+// ------------------------------------------------------------------------
+//
+// Sort the next neighbort from the left, top, right, bottom
+//
+void MagicDomino::GetSortedNeighbors(Int_t indices[6])
+{
+    const MGeomPix &pix=(*fGeomCam)[fNumPixel<0?0:fNumPixel];
+
+    Double_t fAngle[6] = { -10, -10, -10, -10, -10, -10 };
+
+    for (int i=0; i<pix.GetNumNeighbors(); i++)
+    {
+        MGeomPix &next = (*fGeomCam)[pix.GetNeighbor(i)];
+        fAngle[i] = atan2(next.GetY()-pix.GetY(), next.GetX()-pix.GetX());
+    }
+
+    TMath::Sort(6, fAngle, indices); // left, top, right, bottom
+}
+
+// ------------------------------------------------------------------------
+//
+// Move tile one step in the given direction
+//
+void MagicDomino::Step(Int_t dir)
+{
+    Short_t newidx = AnalysePixel(dir);
+    if (newidx<0)
+        return;
+    ChangePixel(newidx);
+}
+
Index: /tags/Mars-V0.9/mtools/MagicDomino.h
===================================================================
--- /tags/Mars-V0.9/mtools/MagicDomino.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicDomino.h	(revision 9772)
@@ -0,0 +1,101 @@
+#ifndef MARS_MagicDomino
+#define MARS_MagicDomino
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TText
+#include <TText.h>
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class MagicDomino : public TObject
+{
+private:
+    enum
+    {
+        kBackground  = 50,
+        kIsTile      = BIT(16),
+        kRight       = BIT(17),
+        kLeft        = BIT(18),
+        kTop         = BIT(19),
+        kBottom      = BIT(20),
+        kUserBits    = 0x7fc000, // 14-23 are allowed
+
+        kBottomLeft  = kBottom|kLeft,
+        kBottomRight = kBottom|kRight,
+        kTopLeft     = kTop|kLeft,
+        kTopRight    = kTop|kRight
+
+    };
+
+    MGeomCam *fGeomCam;         // pointer to camera geometry
+
+    UShort_t  fNumPixels;       // number of pixels in the present geometry
+    Short_t   fNumPixel;        // number of actual pixel
+    Int_t     fNumTile;         // number of setteled tiles
+    Float_t   fRange;           // the range in millimeters of the present geometry
+
+    Int_t     fPoints;          // points you got
+
+    Int_t     fDir;             // direction you move the tile
+
+    Int_t     fOldColors[7];    // colors of hexagons which are under the tile
+    Int_t     fNewColors[6];    // colors of the tile itself
+    Byte_t    fPosition;        // rotation position of colors in tile
+    Byte_t    fSkipped;         // number of skipped tiles
+
+    TText     fDomino;          // TText showing status informations
+    TText    *fText[6];         // ttext showing the six numbers in the tile
+    TText    *fDone;            // game over text
+
+    UInt_t    fW;               // Width of canvas
+    UInt_t    fH;               // Height of canvas
+
+    TClonesArray *fPixels;      // array of all hexagons
+    TVirtualPad  *fDrawingPad;  // pad in which we are drawing
+
+    MHexagon &operator[](int i) { return *((MHexagon*)fPixels->At(i)); }
+
+    Bool_t  CheckTile();
+    void    NewTile();
+    void    NewColors();
+    void    HideTile();
+    void    ShowTile();
+    void    RotateTile(Int_t add);
+    void    Update();
+    void    Free();
+    void    Done();
+    void    RemoveNumbers();
+    void    DrawHexagons();
+    void    SetNewCamera(MGeomCam *);
+    void    ChangePixel(Int_t add);
+    void    Step(Int_t dir);
+    Short_t AnalysePixel(Int_t dir);
+    void    GetSortedNeighbors(Int_t indices[6]);
+
+    void  Draw(Option_t *option="");
+    void  Paint(Option_t *option="");
+    void  ExecuteEvent(Int_t event, Int_t px, Int_t py);
+    Int_t DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+public:
+    MagicDomino();
+    ~MagicDomino();
+
+    void Reset();        //*MENU*
+    void ChangeCamera(); //*MENU*
+
+    ClassDef(MagicDomino, 0) // Magic Camera Games: Some kind of Domino
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MagicReversi.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MagicReversi.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicReversi.cc	(revision 9772)
@@ -0,0 +1,626 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 03/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MagicReversi
+// ------------
+//
+// Camera Display Games: Reversi
+//
+// Start the game by:
+//   MagicReversi reversi;
+//
+//  Rules:
+//  ------
+//
+// Use the mouse to put a stone at some place. If between your newly
+// placed stone and the next stone (in a row) of your color are stones
+// of other colors this stones are won by you. You can only place a
+// stone if you win at least one stone from your 'enemy'. If you
+// cannot do so, you are skipped. If nobody can make a move anymore
+// the game is over. The player has won who has the most stones in
+// his own color.
+// The present player is indicated by <*>
+// Use the Escape key to abort a game.
+// If the game was aborted or has been stopped youcan access the
+// options in the context menu.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MagicReversi.h"
+
+#include <iostream>
+
+#include <KeySymbols.h>
+
+#include <TText.h>
+#include <TMarker.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+#include <TClonesArray.h>
+#include <TInterpreter.h>
+
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MagicReversi);
+
+using namespace std;
+
+/*
+const Int_t MagicReversi::fColorBombs[7] = {
+    22,
+    kYellow,
+    kGreen,
+    kBlue,
+    kCyan,
+    kMagenta,
+    kRed
+};
+*/
+void MagicReversi::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    fPixels->Delete();
+    fText->Delete();
+    fFlags->Delete();
+
+    delete fText;
+    delete fFlags;
+    delete fPixels;
+
+    delete fGeomCam;
+}
+
+void MagicReversi::ChangeCamera()
+{
+    static Bool_t ct1=kFALSE;
+
+    cout << "Change to " << (ct1?"Magic":"CT1") << endl;
+
+    if (ct1)
+        SetNewCamera(new MGeomCamMagic);
+    else
+        SetNewCamera(new MGeomCamCT1);
+
+    ct1 = !ct1;
+
+    Reset();
+    DrawHexagons();
+}
+
+void MagicReversi::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Reset the display geometry
+    //
+    fW=0;
+    fH=0;
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    //
+    // Construct all hexagons. Use new-operator with placement
+    //
+//    fNumBombs = fNumPixels/5;
+
+    fText   = new TClonesArray("TText",    fNumPixels);
+    fFlags  = new TClonesArray("TMarker",  fNumPixels);
+    fPixels = new TClonesArray("MHexagon", fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = *new ((*fPixels)[i]) MHexagon((*fGeomCam)[i]);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        h.SetBit(kNoContextMenu|kCannotPick);
+#endif
+
+        TText &t = *new ((*fText)[i]) TText;
+        t.SetTextFont(122);
+        t.SetTextAlign(22);   // centered/centered
+        t.SetTextSize(0.3*h.GetD()/fRange);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        t.SetBit(kNoContextMenu|kCannotPick);
+#endif
+
+        const MGeomPix &pix = (*fGeomCam)[i];
+
+        TMarker &m = *new ((*fFlags)[i]) TMarker(pix.GetX(), pix.GetY(), kOpenStar);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        m.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Draw all pixels of the camera
+//  (means apend all pixelobjects to the current pad)
+//
+void MagicReversi::DrawHexagons()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+        (*this)[i].Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicReversi::MagicReversi()
+    : fGeomCam(NULL), fDone(NULL), fW(0), fH(0), fDrawingPad(NULL), fIsAllocated(kFALSE)
+{
+    SetNewCamera(new MGeomCamMagic);
+
+    //
+    // Make sure, that the object is destroyed when the canvas/pad is
+    // destroyed. Make also sure, that the interpreter doesn't try to
+    // delete it a second time.
+    //
+    SetBit(kCanDelete);
+    gInterpreter->DeleteGlobal(this);
+
+    fNumUsers = 2;
+
+    Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MagicReversi::~MagicReversi()
+{
+    Free();
+
+    for (int i=0; i<6; i++)
+        delete fUsrTxt[i];
+
+    if (fDone)
+        delete fDone;
+
+    if (fDrawingPad->GetListOfPrimitives()->FindObject(this)==this)
+    {
+        fDrawingPad->RecursiveRemove(this);
+        delete fDrawingPad;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// This is called at any time the canvas should get repainted.
+// Here we maintain an aspect ratio of 5/4=1.15. This makes sure,
+// that the camera image doesn't get distorted by resizing the canvas.
+//
+void MagicReversi::Paint(Option_t *opt)
+{
+    const UInt_t w = (UInt_t)(gPad->GetWw()*gPad->GetAbsWNDC());
+    const UInt_t h = (UInt_t)(gPad->GetWh()*gPad->GetAbsHNDC());
+
+    //
+    // Check for a change in width or height, and make sure, that the
+    // first call also sets the range
+    //
+    if (w*fH == h*fW && fW && fH)
+        return;
+
+    //
+    // Calculate aspect ratio (5/4=1.25 recommended)
+    //
+    const Double_t ratio = (Double_t)w/h;
+
+    Float_t x;
+    Float_t y;
+
+    if (ratio>1.0)
+    {
+        x = fRange*(ratio*2-1);
+        y = fRange;
+    }
+    else
+    {
+        x = fRange;
+        y = fRange/ratio;
+    }
+
+    fH = h;
+    fW = w;
+
+    //
+    // Set new range
+    //
+    fDrawingPad->Range(-fRange, -y, x, y);
+
+    //
+    // Adopt absolute sized of markers to relative range
+    //
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        Float_t r = (*this)[i].GetD()*gPad->XtoAbsPixel(1)/325;
+        GetFlag(i)->SetMarkerSize(20.0*r/fRange);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to draw the camera layout into your canvas.
+// Setup a drawing canvas. Add this object and all child objects
+// (hexagons, etc) to the current pad. If no pad exists a new one is
+// created.
+//
+void MagicReversi::Draw(Option_t *option)
+{
+    // root 3.02:
+    // gPad->SetFixedAspectRatio()
+
+    if (fDrawingPad)
+        return;
+
+    //
+    // if no canvas is yet existing to draw into, create a new one
+    //
+    if (!gPad)
+    {
+        /*TCanvas *c =*/ new TCanvas("MagicReversi", "Magic Reversi", 0, 0, 800, 800);
+        //c->ToggleEventStatus();
+        fIsAllocated = kTRUE;
+    }
+    else
+        fIsAllocated = kFALSE;
+
+    fDrawingPad = gPad;
+    fDrawingPad->SetBorderMode(0);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    //
+    // Draw the title text
+    //
+    for (int i=0; i<6; i++)
+    {
+        fUsrTxt[i] = new TText;
+        fUsrTxt[i]->SetTextAlign(13);       // left/bottom
+        fUsrTxt[i]->SetTextSize(0.03);
+        fUsrTxt[i]->SetTextColor(kRed+i);  
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        fUsrTxt[i]->SetBit(kNoContextMenu|kCannotPick);
+#endif
+        fUsrTxt[i]->Draw();
+    }
+
+    //
+    // Reset the game pad
+    //
+    Reset();
+    DrawHexagons();
+}
+
+void MagicReversi::Update()
+{
+    int i;
+    for (i=0; i<fNumUsers; i++)
+    {
+        TString txt = "Pixels: ";
+        txt += fUsrPts[i];
+
+        if (fNumUser==i)
+            txt += " <*>";
+
+        fUsrTxt[i]->SetText(-fRange*0.95, fRange-(i+1)*fRange*0.06, txt);
+    }
+    for (; i<6; i++)
+        fUsrTxt[i]->SetText(0, 0, "");
+}
+
+void MagicReversi::TwoPlayer()
+{
+    fNumUsers = 2;
+    Reset();
+}
+
+void MagicReversi::ThreePlayer()
+{
+    fNumUsers = 3;
+    Reset();
+}
+
+void MagicReversi::FourPlayer()
+{
+    fNumUsers = 4;
+    Reset();
+}
+
+void MagicReversi::FivePlayer()
+{
+    fNumUsers = 5;
+    Reset();
+}
+
+void MagicReversi::SixPlayer()
+{
+    fNumUsers = 6;
+    Reset();
+}
+
+// ------------------------------------------------------------------------
+//
+// reset the all pixel colors to a default value
+//
+void MagicReversi::Reset()
+{
+    if (fDone)
+    {
+        delete fDone;
+        fDone = NULL;
+    }
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        Remove(GetText(i));
+        Remove(GetFlag(i));
+
+        (*this)[i].SetFillColor(kEmpty);
+        (*fGeomCam)[i].ResetBit(kUserBits);
+
+        GetFlag(i)->SetMarkerColor(kBlack);
+    }
+
+    fNumUser  = 0;
+
+    for (int i=0; i<6; i++)
+        fUsrPts[i]=0;
+
+    for (int i=1; i<5*fNumUsers; i++)
+    {
+        (*this)[i-1].SetFillColor(i%fNumUsers+kRed);
+        fUsrPts[i%fNumUsers]++;
+    }
+
+    Update();
+
+    fDrawingPad->SetFillColor(22);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDrawingPad->SetBit(kNoContextMenu);
+    SetBit(kNoContextMenu);
+#endif
+}
+
+void MagicReversi::Done()
+{
+    Int_t max = 0;
+    Int_t winner = 0;
+
+    for (int i=0; i<6; i++)
+        if (fUsrPts[i]>max)
+        {
+            winner = i;
+            max = fUsrPts[i];
+        }
+
+    TString txt = "Player #";
+    txt += winner+1;
+    txt += " wins (";
+    txt += max;
+    txt += ")";
+
+    fDone = new TText(0, 0, txt);
+    fDone->SetTextColor(kWhite);
+    fDone->SetTextAlign(22);  
+    fDone->SetTextSize(0.05); 
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDone->SetBit(kNoContextMenu|kCannotPick);
+#endif
+    fDone->Draw();
+
+    fDrawingPad->SetFillColor(winner+kRed);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDrawingPad->ResetBit(kNoContextMenu);
+    ResetBit(kNoContextMenu);
+#endif
+}
+
+void MagicReversi::Remove(TObject *obj)
+{
+    fDrawingPad->RecursiveRemove(obj);
+}
+
+Int_t MagicReversi::GetDirection(Int_t src, Int_t dst) const
+{
+    const MGeomPix &pix1=(*fGeomCam)[dst];
+    const MGeomPix &pix2=(*fGeomCam)[src];
+
+    const Double_t x1 = pix1.GetX();
+    const Double_t y1 = pix1.GetY();
+
+    const Double_t x2 = pix2.GetX();
+    const Double_t y2 = pix2.GetY();
+
+    if (x1>=x2 && y1>y2) return kRightTop;
+    if (x1>=x2 && y1<y2) return kRightBottom;
+    if (x1<=x2 && y1>y2) return kLeftTop;
+    if (x1<=x2 && y1<y2) return kLeftBottom;
+    if (x1>x2)           return kRight;
+    if (x1<x2)           return kLeft;
+
+    return -1;
+}
+
+Int_t MagicReversi::GetNeighbor(Int_t idx, Int_t dir) const
+{
+    MGeomPix &pix=(*fGeomCam)[idx];
+
+    //
+    // search for the neighbor in the given direction
+    //
+    int i;
+    for (i=0; i<pix.GetNumNeighbors(); i++)
+        if (GetDirection(idx, pix.GetNeighbor(i))==dir)
+            return pix.GetNeighbor(i);
+
+    return -1;
+}
+
+Bool_t MagicReversi::Flip(Int_t origidx, Bool_t flip)
+{
+    const Int_t col = kRed+fNumUser;
+
+    int test[6] = {0,0,0,0,0,0};
+
+    for (int dir=kRightTop; dir<=kLeftTop; dir++)
+    {
+        Int_t idx = origidx;
+        Int_t length = 0;
+
+        while (1)
+        {
+            idx = GetNeighbor(idx, dir);
+            if (idx<0 || (*this)[idx].GetFillColor()==kEmpty)
+                break;
+
+            if ((*this)[idx].GetFillColor()==col)
+            {
+                if (length!=0)
+                    test[dir] = length;
+                break;
+            }
+
+            length++;
+        }
+    }
+
+    int cnt = 0;
+
+    for (int dir=kRightTop; dir<=kLeftTop; dir++)
+    {
+        Int_t idx = origidx;
+
+        if (test[dir])
+            cnt++;
+
+        if (flip)
+            for (int i=0; i<test[dir]; i++)
+            {
+                idx = GetNeighbor(idx, dir);
+
+                fUsrPts[(*this)[idx].GetFillColor()-kRed]--;
+                fUsrPts[fNumUser]++;
+
+                (*this)[idx].SetFillColor(col);
+            }
+    }
+
+    return cnt ? kTRUE : kFALSE;
+}
+
+Bool_t MagicReversi::CheckMoves()
+{
+    for (unsigned int i=0; i<fNumPixels; i++)
+        if ((*this)[i].GetFillColor()==kEmpty && Flip(i, kFALSE))
+            return kTRUE;
+    return kFALSE;
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a mouse event on the camera
+//
+void MagicReversi::ExecuteEvent(Int_t event, Int_t px, Int_t py)
+{
+    if (event==kMouseMotion   || event==kMouseEnter    || event==kMouseLeave    ||
+        event==kButton1Up     || event==kButton2Up     || event==kButton3Up     ||
+        event==kButton1Motion || event==kButton2Motion || event==kButton3Motion ||
+                                 event==kButton2Double || event==kButton3Double ||
+        fDone)
+        return;
+
+    if (event==kKeyPress && py==kKey_Escape)
+    {
+        Done();
+        fDrawingPad->Modified();
+        fDrawingPad->Update();
+        return;
+    }
+
+    UInt_t idx;
+    for (idx=0; idx<fNumPixels; idx++)
+        if ((*fPixels)[idx]->DistancetoPrimitive(px, py)==0)
+            break;
+
+    if (idx==fNumPixels)
+        return;
+
+    if (event==kButton1Down && (*this)[idx].GetFillColor()==kEmpty)
+    {
+        if (!Flip(idx, kTRUE))
+            return;
+
+        fUsrPts[fNumUser]++;
+
+        (*this)[idx].SetFillColor(kRed+fNumUser);
+
+        Int_t start = fNumUser;
+
+        fNumUser++;
+        fNumUser%=fNumUsers;
+
+        while (!CheckMoves())
+        {
+            cout << "Sorry, no moves possible for player #" << fNumUser << endl;
+            fNumUser++;
+            fNumUser%=fNumUsers;
+
+            if (fNumUser==start)
+            {
+                Done();
+                break;
+            }
+        }
+
+        Update();
+    }
+
+    fDrawingPad->Modified();
+}
Index: /tags/Mars-V0.9/mtools/MagicReversi.h
===================================================================
--- /tags/Mars-V0.9/mtools/MagicReversi.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicReversi.h	(revision 9772)
@@ -0,0 +1,98 @@
+#ifndef MARS_MagicReversi
+#define MARS_MagicReversi
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class TText;
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class MagicReversi : public TObject
+{
+private:
+    enum {
+        kRightTop,
+        kRight,
+        kRightBottom,
+        kLeftBottom,
+        kLeft,
+        kLeftTop
+    };
+//    static const Int_t fColorBombs[7]; // colors for the hexagons
+
+    MGeomCam      *fGeomCam;       // pointer to camera geometry
+
+    UInt_t         fNumPixels;     // number of pixels in the present geometry
+    Float_t        fRange;         // the range in millimeters of the present geometry
+
+    TClonesArray  *fPixels;        // array of all hexagons
+    TClonesArray  *fText;          // array of all texts
+    TClonesArray  *fFlags;         // array of all texts
+
+    TText         *fDone;          // TText showing the 'Game over'
+    TText         *fUsrTxt[6];     // TText showing the numbers of pixels and bombs
+
+    UInt_t         fW;             // Width of canvas
+    UInt_t         fH;             // Height of canvas
+    TVirtualPad   *fDrawingPad;    // pad in which we are drawing
+    Bool_t         fIsAllocated;
+
+    Int_t          fNumUsers;
+    Int_t          fNumUser;
+    Int_t          fUsrPts[6];
+
+    enum
+    {
+        kEmpty     = 50,
+        kIsVisible = BIT(16),
+        kHasBomb   = BIT(17),
+        kHasFlag   = BIT(18),
+        kUserBits  = 0x7fc000 // 14-23 are allowed
+    };
+
+    MHexagon &operator[](int i) { return *((MHexagon*)fPixels->At(i)); }
+
+    TText   *GetText(Int_t i) { return (TText*)fText->At(i); }
+    TMarker *GetFlag(Int_t i) { return (TMarker*)fFlags->At(i); }
+
+    void  Remove(TObject *);
+    void  Done();
+    void  Update();
+    void  SetNewCamera(MGeomCam *);
+    void  DrawHexagons();
+    void  Free();
+
+    Bool_t Flip(Int_t idx, Bool_t flip);
+    Int_t  GetDirection(Int_t src, Int_t dst) const;
+    Int_t  GetNeighbor(Int_t idx, Int_t dir) const;
+    Bool_t CheckMoves();
+
+    void  Paint(Option_t *option="");
+    void  Draw(Option_t *option="");
+    void  ExecuteEvent(Int_t event, Int_t px, Int_t py);
+    Int_t DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+public:
+    MagicReversi();
+    ~MagicReversi();
+
+    void Reset();        //*MENU*
+    void ChangeCamera(); //*MENU*
+    void TwoPlayer(); //*MENU*
+    void ThreePlayer(); //*MENU*
+    void FourPlayer(); //*MENU*
+    void FivePlayer(); //*MENU*
+    void SixPlayer(); //*MENU*
+
+    ClassDef(MagicReversi, 0) // Magic Camera Games: Reversi
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MagicShow.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MagicShow.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicShow.cc	(revision 9772)
@@ -0,0 +1,423 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 07/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MagicShow
+// ---------
+//
+// Tool to visualize Next Neighbours.
+//
+// Start the show by:
+//   MagicShow show;
+//
+// Use the following keys:
+// -----------------------
+//
+//   * Space:
+//     Toggle between auto increment and manual increment
+//
+//   * Right/Left:
+//     Increment/Decrement pixel number by 1
+//
+//   * Right/Left:
+//     Increment/Decrement pixel number by 1
+//
+//   * Up/Down:
+//     Increment/Decrement pixel number by 10
+//
+//   * PageUp/PageDown:
+//     Increment/Decrement pixel number by 100
+//
+//   * Home/End:
+//     Jump to first/last pixel
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MagicShow.h"
+
+#include <iostream>
+
+#include <KeySymbols.h>
+
+#include <TCanvas.h>
+#include <TInterpreter.h>
+
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MagicShow);
+
+using namespace std;
+
+// ------------------------------------------------------------------------
+//
+// Free all onbects connected to a special camera geometry
+//
+void MagicShow::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    fPixels->Delete();
+
+    delete fPixels;
+
+    delete fGeomCam;
+}
+
+// ------------------------------------------------------------------------
+//
+// Draw all pixels of the camera
+//  (means apend all pixelobjects to the current pad)
+//
+void MagicShow::DrawHexagons()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = (*this)[i];
+
+        h.SetFillColor(kBackground);
+        h.Draw();
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Change camera from Magic to CT1 and back
+//
+void MagicShow::ChangeCamera()
+{
+    static Bool_t ct1=kFALSE;
+
+    cout << "Change to " << (ct1?"Magic":"CT1") << endl;
+
+    if (ct1)
+        SetNewCamera(new MGeomCamMagic);
+    else
+        SetNewCamera(new MGeomCamCT1);
+
+    ct1 = !ct1;
+
+    DrawHexagons();
+}
+
+// ------------------------------------------------------------------------
+//
+// Reset/set all veriables needed for a new camera geometry
+//
+void MagicShow::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Reset the display geometry
+    //
+    fW=0;
+    fH=0;
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    fNumPixel  = fNumPixels-1;
+
+    //
+    // Construct all hexagons. Use new-operator with placement
+    //
+    fPixels = new TClonesArray("MHexagon", fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = *new ((*fPixels)[i]) MHexagon((*fGeomCam)[i]);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        h.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicShow::MagicShow()
+    : fTimer(this, 250, kTRUE), fGeomCam(NULL), fNumPixel(-1), fAuto(kTRUE), fW(0), fH(0)
+{
+    SetNewCamera(new MGeomCamMagic);
+
+    memset(fText, 0, sizeof(fText));
+
+    //
+    // Make sure, that the object is destroyed when the canvas/pad is
+    // destroyed. Make also sure, that the interpreter doesn't try to
+    // delete it a second time.
+    //
+    SetBit(kCanDelete);
+    gInterpreter->DeleteGlobal(this);
+
+    Draw();
+
+    fTimer.TurnOn();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MagicShow::~MagicShow()
+{
+    Free();
+
+    for (int i=0; i<6; i++)
+        if (fText[i])
+            delete fText[i];
+
+    if (fDrawingPad->GetListOfPrimitives()->FindObject(this)==this)
+    {
+        fDrawingPad->RecursiveRemove(this);
+        delete fDrawingPad;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// This is called at any time the canvas should get repainted.
+// Here we maintain an aspect ratio of 5/4=1.15. This makes sure,
+// that the camera image doesn't get distorted by resizing the canvas.
+//
+void MagicShow::Paint(Option_t *opt)
+{
+    const UInt_t w = (UInt_t)(gPad->GetWw()*gPad->GetAbsWNDC());
+    const UInt_t h = (UInt_t)(gPad->GetWh()*gPad->GetAbsHNDC());
+
+    //
+    // Check for a change in width or height, and make sure, that the
+    // first call also sets the range
+    //
+    if (w*fH == h*fW && fW && fH)
+        return;
+
+    //
+    // Calculate aspect ratio (5/4=1.25 recommended)
+    //
+    const Double_t ratio = (Double_t)w/h;
+
+    Float_t x;
+    Float_t y;
+
+    if (ratio>1.0)
+    {
+        x = fRange*(ratio*2-1);
+        y = fRange;
+    }
+    else
+    {
+        x = fRange;
+        y = fRange/ratio;
+    }
+
+    fH = h;
+    fW = w;
+
+    //
+    // Set new range
+    //
+    fDrawingPad->Range(-fRange, -y, x, y);
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to draw the camera layout into your canvas.
+// Setup a drawing canvas. Add this object and all child objects
+// (hexagons, etc) to the current pad. If no pad exists a new one is
+// created.
+//
+void MagicShow::Draw(Option_t *option)
+{
+    //
+    // if no canvas is yet existing to draw into, create a new one
+    //
+    /*TCanvas *c =*/ new TCanvas("MagicShow", "Magic Show Next Neighbours", 0, 0, 800, 800);
+    //c->ToggleEventStatus();
+
+    fDrawingPad = gPad;
+    fDrawingPad->SetBorderMode(0);
+    fDrawingPad->SetFillColor(22);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    //
+    // Reset the game pad
+    //
+    DrawHexagons();
+
+    fShow.SetTextAlign(23);   // centered/bottom
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fShow.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    fShow.Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+// Update Status text
+//
+void MagicShow::Update()
+{
+    TString txt = "Pixels: ";
+    txt += fNumPixels;
+    txt += "  Pixel: ";
+    txt += fNumPixel;
+
+    if (fAuto)
+        txt += "  (auto)";
+
+    fShow.SetText(0, fRange, txt);
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a mouse event on the camera
+//
+void MagicShow::ExecuteEvent(Int_t event, Int_t keycode, Int_t keysym)
+{
+    if (event!=kKeyPress)
+        return;
+
+    switch (keysym)
+    {
+    case kKey_Space:
+        fAuto = !fAuto;
+        Update();
+        fDrawingPad->Update();
+        return;
+
+    case kKey_Right:
+        ChangePixel(+1);
+        return;
+
+    case kKey_Left:
+        ChangePixel(-1);
+        return;
+
+    case kKey_Up:
+        ChangePixel(+10);
+        return;
+
+    case kKey_Down:
+        ChangePixel(-10);
+        return;
+
+    case kKey_PageUp:
+        ChangePixel(+100);
+        return;
+
+    case kKey_PageDown:
+        ChangePixel(-100);
+        return;
+
+    case kKey_Home:
+        ChangePixel(-fNumPixel);
+        return;
+
+    case kKey_End:
+        ChangePixel(fNumPixels-fNumPixel-1);
+        return;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Change the shown pixel by add indices
+//
+void MagicShow::ChangePixel(Int_t add)
+{
+    MagicShow &This = *this;
+
+    const MGeomPix &pix1=(*fGeomCam)[fNumPixel];
+    This[fNumPixel].SetFillColor(kBackground);
+    for (int i=0; i<pix1.GetNumNeighbors(); i++)
+    {
+        This[pix1.GetNeighbor(i)].SetFillColor(kBackground);
+        if (!fText[i])
+            continue;
+
+        delete fText[i];
+        fText[i] = NULL;
+    }
+
+    fNumPixel += add;
+
+    if (fNumPixel>=fNumPixels)
+        fNumPixel = 0;
+    if (fNumPixel<0)
+        fNumPixel = fNumPixels-1;
+
+    const MGeomPix &pix2=(*fGeomCam)[fNumPixel];
+    This[fNumPixel].SetFillColor(kBlue);
+    for (int i=0; i<pix2.GetNumNeighbors(); i++)
+    {
+        Int_t idx = pix2.GetNeighbor(i);
+
+        This[idx].SetFillColor(kMagenta);
+
+        TString num;
+        num += idx;
+
+        fText[i] = new TText(This[idx].GetX(), This[idx].GetY(), num);
+        fText[i]->SetTextSize(0.3*This[idx].GetD()/fGeomCam->GetMaxRadius());
+        fText[i]->SetTextFont(122);
+        fText[i]->SetTextAlign(22);   // centered/centered
+        fText[i]->Draw();
+    }
+
+    Update();
+
+    fDrawingPad->Update();
+}
+
+// ------------------------------------------------------------------------
+//
+// If automatic is switched on step one pixel forward
+//
+Bool_t MagicShow::HandleTimer(TTimer *timer)
+{
+    if (fAuto)
+        ChangePixel(+1);
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtools/MagicShow.h
===================================================================
--- /tags/Mars-V0.9/mtools/MagicShow.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicShow.h	(revision 9772)
@@ -0,0 +1,76 @@
+#ifndef MARS_MagicShow
+#define MARS_MagicShow
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TText
+#include <TText.h>
+#endif
+#ifndef ROOT_TTimer
+#include <TTimer.h>
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class MagicShow : public TObject
+{
+private:
+    enum
+    {
+        kBackground = 50,
+        kUserBits   = 0x7fc000 // 14-23 are allowed
+
+    };
+
+    TTimer    fTimer;           // timer rising the 500ms interrputs
+
+    MGeomCam *fGeomCam;         // pointer to camera geometry
+
+    UShort_t  fNumPixels;       // number of pixels in the present geometry
+    Short_t   fNumPixel;        // number of pixel actually shown
+    Float_t   fRange;           // the range in millimeters of the present geometry
+
+    Bool_t    fAuto;            // automatic stepping on/off
+
+    TText     fShow;            // TText showing the numbers of pixels and bombs
+    TText    *fText[6];         // ttext showing the pixel numbers of the neighbors
+
+    UInt_t    fW;               // Width of canvas
+    UInt_t    fH;               // Height of canvas
+
+    TClonesArray *fPixels;      // array of all hexagons
+    TVirtualPad  *fDrawingPad;  // pad in which we are drawing
+
+    MHexagon &operator[](int i) { return *((MHexagon*)fPixels->At(i)); }
+
+    void   Update();
+    void   Free();
+    void   DrawHexagons();
+    void   SetNewCamera(MGeomCam *);
+    void   ChangePixel(Int_t add);
+
+    Bool_t HandleTimer(TTimer *timer);
+    void   Draw(Option_t *option="");
+    void   Paint(Option_t *option="");
+    void   ExecuteEvent(Int_t event, Int_t px, Int_t py);
+    Int_t  DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+public:
+    MagicShow();
+    ~MagicShow();
+
+    void ChangeCamera(); //*MENU*
+
+    ClassDef(MagicShow, 0) // Tool to visualize next neighbours
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/MagicSnake.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MagicSnake.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicSnake.cc	(revision 9772)
@@ -0,0 +1,632 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 07/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MagicSnake
+// ----------
+//
+// Camera Display Games: Snake
+//
+// Start the game by:
+//   MagicSnake snake;
+//
+// Controll the worm using right/left. Make sure, that the mouse pointer
+// is inside the canvas.
+//
+// Move the mouse pointer outside the canvas to pause the game.
+//
+// The pixel colors have the following meaning:
+// --------------------------------------------
+//  Green:   Food, collect all packages.
+//  Red:     Bombs, don't touch it!
+//  Yellow:  Transport, try it.
+//  Magenta: Home, touch it to win the game.
+//
+// To restart the game use the context menu. It can only be accessed if
+// the game has been stopped (either because you win the game or because
+// you hit a bomb) With the context menu you can also toggle between
+// different camera layouts.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MagicSnake.h"
+
+#include <iostream>
+
+#include <KeySymbols.h>
+
+#include <TColor.h>
+#include <TCanvas.h>
+#include <TMarker.h>
+#include <TRandom.h>
+#include <TInterpreter.h>
+
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MagicSnake);
+
+using namespace std;
+
+void MagicSnake::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    fPixels->Delete();
+
+    delete fPixels;
+
+    delete fGeomCam;
+
+    delete fArray;
+}
+
+// ------------------------------------------------------------------------
+//
+// Draw all pixels of the camera
+//  (means apend all pixelobjects to the current pad)
+//
+void MagicSnake::DrawHexagons()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+        (*this)[i].Draw();
+}
+
+void MagicSnake::ChangeCamera()
+{
+    if (!fDone)
+        Done("Changing Camera...", 22);
+
+    static Bool_t ct1=kFALSE;
+
+    cout << "Change to " << (ct1?"Magic":"CT1") << endl;
+
+    if (ct1)
+        SetNewCamera(new MGeomCamMagic);
+    else
+        SetNewCamera(new MGeomCamCT1);
+
+    ct1 = !ct1;
+
+    Reset();
+    DrawHexagons();
+}
+
+void MagicSnake::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Reset the display geometry
+    //
+    fW=0;
+    fH=0;
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    //
+    // Construct all hexagons. Use new-operator with placement
+    //
+    fPixels = new TClonesArray("MHexagon", fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = *new ((*fPixels)[i]) MHexagon((*fGeomCam)[i]);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        h.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MagicSnake::MagicSnake()
+    : fTimer(this, 500, kTRUE), fGeomCam(NULL), fDone(NULL), fPaused(NULL), fW(0), fH(0)
+{
+    SetNewCamera(new MGeomCamMagic);
+
+    //
+    // Make sure, that the object is destroyed when the canvas/pad is
+    // destroyed. Make also sure, that the interpreter doesn't try to
+    // delete it a second time.
+    //
+    SetBit(kCanDelete);
+    gInterpreter->DeleteGlobal(this);
+
+    Draw();
+
+    Pause();
+
+    fTimer.TurnOn();
+}
+
+void MagicSnake::Pause(Bool_t yes)
+{
+    if (yes && !fPaused)
+    {
+        fPaused = new TText(0, 0, "Paused!");
+        fPaused->SetTextColor(kWhite);
+        fPaused->SetTextAlign(22);
+        fPaused->SetTextSize(0.05); // white
+        fPaused->Draw();
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        fPaused->SetBit(kNoContextMenu|kCannotPick);
+        fDrawingPad->ResetBit(kNoContextMenu);
+        ResetBit(kNoContextMenu);
+#endif
+        fDrawingPad->Update();
+    }
+
+    if (yes)
+        return;
+
+    if (!fDone)
+    {
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        fDrawingPad->SetBit(kNoContextMenu);
+        SetBit(kNoContextMenu);
+#endif
+    }
+    if (!fPaused)
+        return;
+
+    Remove(fPaused);
+
+    fDrawingPad->Update();
+
+    delete fPaused;
+    fPaused=NULL;
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MagicSnake::~MagicSnake()
+{
+    Free();
+    Pause(kFALSE);
+
+    if (fDone)
+        delete fDone;
+
+    if (fDrawingPad->GetListOfPrimitives()->FindObject(this)==this)
+    {
+        fDrawingPad->RecursiveRemove(this);
+        delete fDrawingPad;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// This is called at any time the canvas should get repainted.
+// Here we maintain an aspect ratio of 5/4=1.15. This makes sure,
+// that the camera image doesn't get distorted by resizing the canvas.
+//
+void MagicSnake::Paint(Option_t *opt)
+{
+    const UInt_t w = (UInt_t)(gPad->GetWw()*gPad->GetAbsWNDC());
+    const UInt_t h = (UInt_t)(gPad->GetWh()*gPad->GetAbsHNDC());
+
+    //
+    // Check for a change in width or height, and make sure, that the
+    // first call also sets the range
+    //
+    if (w*fH == h*fW && fW && fH)
+        return;
+
+    //
+    // Calculate aspect ratio (5/4=1.25 recommended)
+    //
+    const Double_t ratio = (Double_t)w/h;
+
+    Float_t x;
+    Float_t y;
+
+    if (ratio>1.0)
+    {
+        x = fRange*(ratio*2-1);
+        y = fRange;
+    }
+    else
+    {
+        x = fRange;
+        y = fRange/ratio;
+    }
+
+    fH = h;
+    fW = w;
+
+    //
+    // Set new range
+    //
+    fDrawingPad->Range(-fRange, -y, x, y);
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to draw the camera layout into your canvas.
+// Setup a drawing canvas. Add this object and all child objects
+// (hexagons, etc) to the current pad. If no pad exists a new one is
+// created.
+//
+void MagicSnake::Draw(Option_t *option)
+{
+    //
+    // if no canvas is yet existing to draw into, create a new one
+    //
+    /*TCanvas *c =*/ new TCanvas("MagicSnake", "Magic Snake", 0, 0, 800, 800);
+    //c->ToggleEventStatus();
+
+    fDrawingPad = gPad;
+    fDrawingPad->SetBorderMode(0);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    //
+    // Reset the game pad
+    //
+    Reset();
+    DrawHexagons();
+
+    fShow.SetTextAlign(23);   // centered/bottom
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fShow.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    fShow.Draw();
+}
+
+void MagicSnake::Update()
+{
+    TString txt = "Pixels: ";
+    txt += fNumPixels;
+    txt += "  Bombs: ";
+    txt += fNumBombs;
+    txt += "  Food: ";
+    txt += fNumFood;
+
+    fShow.SetText(0, fRange, txt);
+}
+
+// ------------------------------------------------------------------------
+//
+// reset the all pixel colors to a default value
+//
+void MagicSnake::Reset()
+{
+    fDirection = fGeomCam->InheritsFrom("MGeomCamCT1") ? kLeft : kRight;
+    fLength = 2;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        (*this)[i].SetFillColor(kBackground);
+        (*fGeomCam)[i].ResetBit(kUserBits);
+    }
+
+    (*fGeomCam)[0].SetBit(kHasWorm);
+
+    fNumBombs = fNumPixels/30;
+
+    TRandom rnd(0);
+    for (int i=0; i<fNumBombs; i++)
+    {
+        Int_t idx;
+
+        do idx = (Int_t)rnd.Uniform(fNumPixels);
+        while ((*fGeomCam)[idx].TestBits(kHasBomb|kHasWorm));
+
+        (*fGeomCam)[idx].SetBit(kHasBomb);
+        (*this)[idx].SetFillColor(kRed);
+    }
+
+    fNumFood = fNumPixels/6;
+
+    fArray = new Int_t[fNumFood+3];
+
+    fArray[0] = 0;
+    fArray[1] = 1;
+
+    for (int i=0; i<fNumFood+3; i++)
+    {
+        Float_t f = (float)i/(fNumFood+3);
+        gROOT->GetColor(51+i)->SetRGB(f, f, f);
+    }
+    for (int i=0; i<fNumFood; i++)
+    {
+        Int_t idx;
+
+        do idx = (Int_t)rnd.Uniform(fNumPixels);
+        while ((*fGeomCam)[idx].TestBits(kHasBomb|kHasFood|kHasWorm));
+
+        (*fGeomCam)[idx].SetBit(kHasFood);
+        (*this)[idx].SetFillColor(kGreen);
+    }
+
+    SetWormColor();
+
+    for (int i=0; i<2; i++)
+    {
+        Int_t idx;
+
+        do idx = (Int_t)rnd.Uniform(fNumPixels);
+        while ((*fGeomCam)[idx].TestBits(kHasBomb|kHasFood|kHasWorm|kHasTransport));
+
+        fTransport[i] = idx;
+        (*fGeomCam)[idx].SetBit(kHasTransport);
+        (*this)[idx].SetFillColor(kYellow);
+    }
+
+    fDrawingPad->SetFillColor(22);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDrawingPad->SetBit(kNoContextMenu);
+    SetBit(kNoContextMenu);
+#endif
+
+    if (!fDone)
+        return;
+
+    delete fDone;
+    fDone = NULL;
+}
+
+void MagicSnake::Done(TString txt, Int_t col)
+{
+    //(*this)[fArray[fLength-1]].SetFillColor(kBlue);
+
+    fDone = new TText(0, 0, txt);
+    fDone->SetTextColor(kWhite);  // white
+    fDone->SetTextAlign(22);  // centered/centered
+    fDone->SetTextSize(0.05); // white
+    fDone->Draw();
+    fDrawingPad->SetFillColor(col);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDone->SetBit(kNoContextMenu|kCannotPick);
+    fDrawingPad->ResetBit(kNoContextMenu);
+    ResetBit(kNoContextMenu);
+#endif
+}
+
+void MagicSnake::Remove(TObject *obj)
+{
+    fDrawingPad->RecursiveRemove(obj);
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a mouse event on the camera
+//
+void MagicSnake::ExecuteEvent(Int_t event, Int_t keycode, Int_t keysym)
+{
+    if (event==kMouseEnter || event==kMouseMotion)
+    {
+        Pause(kFALSE);
+        return;
+    }
+
+    if (fDone)
+        return;
+
+    if (event==kMouseLeave)
+    {
+        Pause();
+        return;
+    }
+    if (event!=kKeyPress)
+        return;
+
+    switch (keysym)
+    {
+    case kKey_Left:
+        fDirection --;
+        break;
+
+    case kKey_Right:
+        fDirection ++;
+        break;
+
+    case kKey_Escape:
+        Done("Reset...", 22);
+        Reset();
+        return;
+
+    default:
+        cout << "Keysym=0x" << hex << keysym << endl;
+    }
+
+     if (fDirection < kRightTop)
+         fDirection = kLeftTop;
+     if (fDirection > kLeftTop)
+         fDirection = kRightTop;
+}
+
+void MagicSnake::Step(Int_t newpix)
+{
+    if ((*fGeomCam)[newpix].TestBit(kHasTransport))
+    {
+        (*this)[fArray[0]].SetFillColor(kBackground);
+        (*fGeomCam)[fArray[0]].ResetBit(kHasWorm);
+
+        for (int i=1; i<fLength; i++)
+            fArray[i-1] = fArray[i];
+
+        fArray[fLength-1] = newpix==fTransport[0]?fTransport[1]:fTransport[0];
+
+        return;
+    }
+
+    if (!(*fGeomCam)[newpix].TestBit(kHasFood))
+    {
+        MGeomPix &pix = (*fGeomCam)[fArray[0]];
+
+        if (!pix.TestBit(kHasTransport))
+            if (pix.TestBit(kHasDoor))
+                (*this)[fArray[0]].SetFillColor(kMagenta);
+            else
+                (*this)[fArray[0]].SetFillColor(kBackground);
+
+        pix.ResetBit(kHasWorm);
+
+        for (int i=1; i<fLength; i++)
+            fArray[i-1] = fArray[i];
+
+        fArray[fLength-1] = newpix;
+    }
+    else
+    {
+        fArray[fLength++] = newpix;
+        (*fGeomCam)[newpix].ResetBit(kHasFood);
+
+        fNumFood--;
+
+        if (fNumFood==0)
+            for (int i=1; i<7; i++)
+            {
+                (*this)[i].SetFillColor(kMagenta);
+                (*fGeomCam)[i].SetBit(kHasDoor);
+            }
+    }
+
+    SetWormColor();
+}
+
+void MagicSnake::SetWormColor()
+{
+    for (int i=0; i<fLength; i++)
+    {
+        const Int_t idx = fArray[i];
+
+        MGeomPix &pix = (*fGeomCam)[idx];
+
+        if (pix.TestBit(kHasTransport))
+            continue;
+
+        pix.SetBit(kHasWorm);
+
+        Int_t color = 51+fLength-i;
+        (*this)[idx].SetFillColor(color);
+    }
+}
+
+Int_t MagicSnake::ScanNeighbours()
+{
+    const Int_t first = fArray[fLength-1];
+
+    const MGeomPix &pix=(*fGeomCam)[first];
+
+    Double_t dx = pix.GetX();
+    Double_t dy = pix.GetY();
+
+    Int_t newpix = -1;
+    for (int i=0; i<pix.GetNumNeighbors(); i++)
+    {
+        const Int_t     idx  = pix.GetNeighbor(i);
+        const MGeomPix &next = (*fGeomCam)[idx];
+
+        const Double_t x = next.GetX();
+        const Double_t y = next.GetY();
+
+        switch (fDirection)
+        {
+        case kRightTop:    if (x>=dx && y>dy) { newpix=idx; dy=y; } continue;
+        case kRight:       if (x>dx)          { newpix=idx; dx=x; } continue;
+        case kRightBottom: if (x>=dx && y<dy) { newpix=idx; dy=y; } continue;
+        case kLeftTop:     if (x<=dx && y>dy) { newpix=idx; dy=y; } continue;
+        case kLeft:        if (x<dx)          { newpix=idx; dx=x; } continue;
+        case kLeftBottom:  if (x<=dx && y<dy) { newpix=idx; dy=y; } continue;
+        }
+    }
+
+    if (newpix<0)
+        return -1;
+
+    const MGeomPix &np = (*fGeomCam)[newpix];
+
+    if (fNumFood==0 && np.TestBit(kHasDoor))
+        return -4;
+
+    if (np.TestBit(kHasBomb))
+        return -2;
+
+    if (np.TestBit(kHasWorm))
+        return -3;
+
+    return newpix;
+}
+
+Bool_t MagicSnake::HandleTimer(TTimer *timer)
+{
+    if (fDone || fPaused)
+        return kTRUE;
+
+    const Int_t newpix = ScanNeighbours();
+
+    switch (newpix)
+    {
+    case -1:
+        Done("You crashed! Don't drink and drive!", kRed);
+        break;
+    case -2:
+        Done("Ouch, you found the bomb!", kRed);
+        break;
+    case -3:
+        Done("Argh... don't eat yourself!", kRed);
+        break;
+    case -4:
+        Done("Congratulations! You won the game!", kGreen);
+        break;
+    default:
+        Step(newpix);
+    }
+
+    Update();
+
+    //cout << "Update " << flush;
+
+    fDrawingPad->Modified();
+    fDrawingPad->Update();
+
+    //cout << "Done." << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtools/MagicSnake.h
===================================================================
--- /tags/Mars-V0.9/mtools/MagicSnake.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MagicSnake.h	(revision 9772)
@@ -0,0 +1,101 @@
+#ifndef MARS_MagicSnake
+#define MARS_MagicSnake
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TText
+#include <TText.h>
+#endif
+#ifndef ROOT_TTimer
+#include <TTimer.h>
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class MagicSnake : public TObject
+{
+private:
+    enum {
+        kRightTop,
+        kRight,
+        kRightBottom,
+        kLeftBottom,
+        kLeft,
+        kLeftTop
+    };
+
+    enum
+    {
+        kBackground   = 50,
+        kHasBomb      = BIT(16),
+        kHasFood      = BIT(17),
+        kHasWorm      = BIT(18),
+        kHasTransport = BIT(19),
+        kHasDoor      = BIT(20),
+        kUserBits     = 0x7fc000 // 14-23 are allowed
+
+    };
+
+    Byte_t    fLength;          // actual length of worm
+    Int_t    *fArray;           // inices of pixels which are 'wormed'
+    Char_t    fDirection;       // actual direction of worm
+
+    TTimer    fTimer;           // timer rising the 500ms interrputs
+
+    MGeomCam *fGeomCam;         // pointer to camera geometry
+
+    UShort_t  fTransport[2];    // pixel ids with the yellow transpoters
+    UInt_t    fNumPixels;       // number of pixels in the present geometry
+    Byte_t    fNumBombs;        // number of bombs in the field
+    Byte_t    fNumFood;         // number of food packages
+    Float_t   fRange;           // the range in millimeters of the present geometry
+
+    TText    *fDone;            // TText showing the 'Game over'
+    TText    *fPaused;          // TText showing the 'Game over'
+    TText     fShow;            // TText showing the numbers of pixels and bombs
+
+    UInt_t    fW;               // Width of canvas
+    UInt_t    fH;               // Height of canvas
+
+    TClonesArray  *fPixels;     // array of all hexagons
+    TVirtualPad   *fDrawingPad; // pad in which we are drawing
+
+    MHexagon &operator[](int i) { return *((MHexagon*)fPixels->At(i)); }
+
+    void   Remove(TObject *);
+    void   Done(TString, Int_t col);
+    void   Step(Int_t newpix);
+    void   Update();
+    void   Free();
+    void   DrawHexagons();
+    Int_t  ScanNeighbours();
+    void   SetNewCamera(MGeomCam *);
+    void   SetWormColor();
+    void   Pause(Bool_t yes=kTRUE);
+
+    Bool_t HandleTimer(TTimer *timer);
+    void   Draw(Option_t *option="");
+    void   Paint(Option_t *option="");
+    void   ExecuteEvent(Int_t event, Int_t px, Int_t py);
+    Int_t  DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+public:
+    MagicSnake();
+    ~MagicSnake();
+
+    void Reset();        //*MENU*
+    void ChangeCamera(); //*MENU*
+
+    ClassDef(MagicSnake, 0) // Magic Camera Games: Snake
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/Makefile
===================================================================
--- /tags/Mars-V0.9/mtools/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtools/Makefile	(revision 9772)
@@ -0,0 +1,46 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Tools
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../mdata -I../mhbase \
+	   -I../mfileio -I../mfbase -I../manalysis
+
+#manalysis: MChisqEval (MParameters)
+
+SRCFILES = MChisqEval.cc \
+	   MTFillMatrix.cc \
+	   MHSimulatedAnnealing.cc \
+	   MSimulatedAnnealing.cc \
+	   MFFT.cc \
+	   MCubicCoeff.cc \
+           MCubicSpline.cc \
+	   MagicReversi.cc \
+	   MagicSnake.cc \
+           MagicShow.cc \
+           MagicDomino.cc \
+           MagicCivilization.cc \
+           MineSweeper.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mtools/MineSweeper.cc
===================================================================
--- /tags/Mars-V0.9/mtools/MineSweeper.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MineSweeper.cc	(revision 9772)
@@ -0,0 +1,528 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz 07/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MineSweeper
+// -----------
+//
+// Camera Display Games: Mine Sweeper
+//
+// Start the game by:
+//   MineSweeper mine;
+//
+// It is the well known Mine Sweeper.
+// Set a mark using a single mouse click.
+// Open a pixel using a double click.
+//
+// Try to open all pixels without bombs. If you open a pixel with no
+// bomb around all pixels around are opened.
+//
+// To restart the game use the context menu. It can only be accessed if
+// the game has been stopped (either because you win the game or because
+// you hit a bomb) With the context menu you can also toggle between
+// different camera layouts.
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MineSweeper.h"
+
+#include <iostream>
+
+#include <TText.h>
+#include <TMarker.h>
+#include <TRandom.h>
+#include <TCanvas.h>
+#include <TClonesArray.h>
+#include <TInterpreter.h>
+
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCamCT1.h"
+#include "MGeomCamMagic.h"
+
+ClassImp(MineSweeper);
+
+using namespace std;
+
+const Int_t MineSweeper::fColorBombs[7] = {
+    22,
+    kYellow,
+    kGreen,
+    kBlue,
+    kCyan,
+    kMagenta,
+    kRed
+};
+
+void MineSweeper::Free()
+{
+    if (!fGeomCam)
+        return;
+
+    fPixels->Delete();
+    fText->Delete();
+    fFlags->Delete();
+
+    delete fText;
+    delete fFlags;
+    delete fPixels;
+
+    delete fGeomCam;
+}
+
+void MineSweeper::ChangeCamera()
+{
+    static Bool_t ct1=kFALSE;
+
+    cout << "Change to " << (ct1?"Magic":"CT1") << endl;
+
+    if (ct1)
+        SetNewCamera(new MGeomCamMagic);
+    else
+        SetNewCamera(new MGeomCamCT1);
+
+    ct1 = !ct1;
+
+    Reset();
+    DrawHexagons();
+}
+
+void MineSweeper::SetNewCamera(MGeomCam *geom)
+{
+    Free();
+
+    //
+    //  Reset the display geometry
+    //
+    fW=0;
+    fH=0;
+
+    //
+    //  Set new camera
+    //
+    fGeomCam = geom;
+
+    //
+    //  create the hexagons of the display
+    //
+    fNumPixels = fGeomCam->GetNumPixels();
+    fRange     = fGeomCam->GetMaxRadius();
+
+    //
+    // Construct all hexagons. Use new-operator with placement
+    //
+    fNumBombs = fNumPixels/5;
+
+    fText   = new TClonesArray("TText",    fNumPixels);
+    fFlags  = new TClonesArray("TMarker",  fNumPixels);
+    fPixels = new TClonesArray("MHexagon", fNumPixels);
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        MHexagon &h = *new ((*fPixels)[i]) MHexagon((*fGeomCam)[i]);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        h.SetBit(kNoContextMenu|kCannotPick);
+#endif
+
+        TText &t = *new ((*fText)[i]) TText;
+        t.SetTextFont(122);
+        t.SetTextAlign(22);   // centered/centered
+        t.SetTextSize(0.3*h.GetD()/fRange);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        t.SetBit(kNoContextMenu|kCannotPick);
+#endif
+
+        const MGeomPix &pix = (*fGeomCam)[i];
+
+        TMarker &m = *new ((*fFlags)[i]) TMarker(pix.GetX(), pix.GetY(), kOpenStar);
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+        m.SetBit(kNoContextMenu|kCannotPick);
+#endif
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Draw all pixels of the camera
+//  (means apend all pixelobjects to the current pad)
+//
+void MineSweeper::DrawHexagons()
+{
+    for (UInt_t i=0; i<fNumPixels; i++)
+        (*this)[i].Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+//  default constructor
+//
+MineSweeper::MineSweeper()
+    : fGeomCam(NULL), fDone(NULL), fShow(NULL), fW(0), fH(0), fDrawingPad(NULL), fIsAllocated(kFALSE)
+{
+    SetNewCamera(new MGeomCamMagic);
+
+    //
+    // Make sure, that the object is destroyed when the canvas/pad is
+    // destroyed. Make also sure, that the interpreter doesn't try to
+    // delete it a second time.
+    //
+    SetBit(kCanDelete);
+    gInterpreter->DeleteGlobal(this);
+
+    Draw();
+}
+
+// ------------------------------------------------------------------------
+//
+// Destructor. Deletes TClonesArrays for hexagons and legend elements.
+//
+MineSweeper::~MineSweeper()
+{
+    Free();
+
+    delete fShow;
+
+    if (fDone)
+        delete fDone;
+
+    if (fDrawingPad->GetListOfPrimitives()->FindObject(this)==this)
+    {
+        fDrawingPad->RecursiveRemove(this);
+        delete fDrawingPad;
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// This is called at any time the canvas should get repainted.
+// Here we maintain an aspect ratio of 5/4=1.15. This makes sure,
+// that the camera image doesn't get distorted by resizing the canvas.
+//
+void MineSweeper::Paint(Option_t *opt)
+{
+    const UInt_t w = (UInt_t)(gPad->GetWw()*gPad->GetAbsWNDC());
+    const UInt_t h = (UInt_t)(gPad->GetWh()*gPad->GetAbsHNDC());
+
+    //
+    // Check for a change in width or height, and make sure, that the
+    // first call also sets the range
+    //
+    if (w*fH == h*fW && fW && fH)
+        return;
+
+    //
+    // Calculate aspect ratio (5/4=1.25 recommended)
+    //
+    const Double_t ratio = (Double_t)w/h;
+
+    Float_t x;
+    Float_t y;
+
+    if (ratio>1.0)
+    {
+        x = fRange*(ratio*2-1);
+        y = fRange;
+    }
+    else
+    {
+        x = fRange;
+        y = fRange/ratio;
+    }
+
+    fH = h;
+    fW = w;
+
+    //
+    // Set new range
+    //
+    fDrawingPad->Range(-fRange, -y, x, y);
+
+    //
+    // Adopt absolute sized of markers to relative range
+    //
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        Float_t r = (*this)[i].GetD()*gPad->XtoAbsPixel(1)/325;
+        GetFlag(i)->SetMarkerSize(20.0*r/fRange);
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Call this function to draw the camera layout into your canvas.
+// Setup a drawing canvas. Add this object and all child objects
+// (hexagons, etc) to the current pad. If no pad exists a new one is
+// created.
+//
+void MineSweeper::Draw(Option_t *option)
+{
+    // root 3.02:
+    // gPad->SetFixedAspectRatio()
+
+    if (fDrawingPad)
+        return;
+
+    //
+    // if no canvas is yet existing to draw into, create a new one
+    //
+    if (!gPad)
+    {
+        /*TCanvas *c =*/ new TCanvas("MineSweeper", "Magic Mine Sweeper", 0, 0, 800, 800);
+        //c->ToggleEventStatus();
+        fIsAllocated = kTRUE;
+    }
+    else
+        fIsAllocated = kFALSE;
+
+    fDrawingPad = gPad;
+    fDrawingPad->SetBorderMode(0);
+
+    //
+    // Append this object, so that the aspect ratio is maintained
+    // (Paint-function is called)
+    //
+    AppendPad(option);
+
+    //
+    // Draw the title text
+    //
+    fShow = new TText;
+    fShow->SetTextAlign(23);   // centered/bottom
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fShow->SetBit(kNoContextMenu|kCannotPick);
+#endif
+    fShow->Draw();
+    //
+    // Reset the game pad
+    //
+    Reset();
+    DrawHexagons();
+}
+
+void MineSweeper::Update(Int_t num)
+{
+    TString txt = "Pixels: ";
+    txt += fNumPixels;
+    txt += "  Bombs: ";
+    txt += num;
+
+    fShow->SetText(0, fRange, txt);
+}
+
+// ------------------------------------------------------------------------
+//
+// reset the all pixel colors to a default value
+//
+void MineSweeper::Reset()
+{
+    if (fDone)
+    {
+        delete fDone;
+        fDone = NULL;
+    }
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        Remove(GetText(i));
+        Remove(GetFlag(i));
+
+        (*this)[i].SetFillColor(kHidden);
+        (*fGeomCam)[i].ResetBit(kUserBits);
+
+        GetFlag(i)->SetMarkerColor(kBlack);
+    }
+    Update(fNumBombs);
+
+    TRandom rnd(0);
+    for (int i=0; i<fNumBombs; i++)
+    {
+        Int_t idx;
+
+        do idx = (Int_t)rnd.Uniform(fNumPixels);
+        while ((*fGeomCam)[idx].TestBit(kHasBomb));
+
+        (*fGeomCam)[idx].SetBit(kHasBomb);
+    }
+
+    fDrawingPad->SetFillColor(22);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDrawingPad->SetBit(kNoContextMenu);
+    SetBit(kNoContextMenu);
+#endif
+}
+
+void MineSweeper::Done(TString txt, Int_t col)
+{
+    for (unsigned int j=0; j<fNumPixels; j++)
+        if ((*fGeomCam)[j].TestBit(kHasBomb))
+        {
+            (*this)[j].SetFillColor(kBlack);
+            GetFlag(j)->SetMarkerColor(kWhite);
+        }
+
+    fDone = new TText(0, 0, txt);
+    fDone->SetTextColor(kWhite);  // white
+    fDone->SetTextAlign(22);  // centered/centered
+    fDone->SetTextSize(0.05); // white
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDone->SetBit(kNoContextMenu|kCannotPick);
+#endif
+    fDone->Draw();
+
+    fDrawingPad->SetFillColor(col);
+
+#if ROOT_VERSION_CODE > ROOT_VERSION(3,01,06)
+    fDrawingPad->ResetBit(kNoContextMenu);
+    ResetBit(kNoContextMenu);
+#endif
+}
+
+// ------------------------------------------------------------------------
+//
+// Check whether a hexagon should be opened and which color/number should
+// be visible
+//
+void MineSweeper::OpenHexagon(Int_t idx)
+{
+    MGeomPix &pix=(*fGeomCam)[idx];
+
+    if (pix.TestBit(kIsVisible))
+        return;
+
+    if (pix.TestBit(kHasFlag))
+        Remove(GetFlag(idx));
+
+    pix.SetBit(kIsVisible);
+    pix.ResetBit(kHasFlag);
+
+    Int_t cnt=0;
+    for (int j=0; j<pix.GetNumNeighbors(); j++)
+        if ((*fGeomCam)[pix.GetNeighbor(j)].TestBit(kHasBomb))
+            cnt++;
+
+    (*this)[idx].SetFillColor(fColorBombs[cnt]);
+
+    if (cnt)
+    {
+        TText *txt = GetText(idx);
+        TString str;
+        str += cnt;
+        txt->SetText(pix.GetX(), pix.GetY(), str);
+        txt->Draw();
+        return;
+    }
+
+    for (int j=0; j<pix.GetNumNeighbors(); j++)
+        OpenHexagon(pix.GetNeighbor(j));
+}
+
+void MineSweeper::Remove(TObject *obj)
+{
+    fDrawingPad->RecursiveRemove(obj);
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a mouse event on the camera
+//
+void MineSweeper::ExecuteEvent(Int_t event, Int_t px, Int_t py)
+{
+    if (event==kMouseMotion   || event==kMouseEnter    || event==kMouseLeave    ||
+        event==kButton1Up     || event==kButton2Up     || event==kButton3Up     ||
+        event==kButton1Motion || event==kButton2Motion || event==kButton3Motion ||
+                                 event==kButton2Double || event==kButton3Double ||
+        fDone)
+        return;
+
+    /*
+    if (event==kKeyPress && py==0x1000)
+    {
+        Reset();
+        return;
+    }
+    */
+
+    UInt_t idx;
+    for (idx=0; idx<fNumPixels; idx++)
+        if ((*fPixels)[idx]->DistancetoPrimitive(px, py)==0)
+            break;
+
+    if (idx==fNumPixels)
+        return;
+
+    MGeomPix &pix=(*fGeomCam)[idx];
+
+    if (event==kButton1Double)
+    {
+        OpenHexagon(idx);
+
+        if (pix.TestBit(kHasBomb))
+            Done("Argh... you hit the Bomb!!!", kRed);
+    }
+
+    if (event==kButton1Down && !pix.TestBit(kIsVisible))
+    {
+        if (pix.TestBit(kHasFlag))
+            Remove(GetFlag(idx));
+        else
+            GetFlag(idx)->Draw();
+
+        pix.InvertBit(kHasFlag);
+    }
+
+    UInt_t vis=fNumBombs;
+    UInt_t flg=fNumBombs;
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        if ((*fGeomCam)[i].TestBit(kIsVisible))
+            vis++;
+        if ((*fGeomCam)[i].TestBit(kHasFlag))
+            flg--;
+    }
+
+    Update(flg);
+
+    if (vis==fNumPixels && !fDone)
+        Done("Great! Congratulations, you did it!", kGreen);
+
+    fDrawingPad->Modified();
+
+    /*
+     switch (event)
+     {
+     case kNoEvent:       cout << "No Event" << endl; break;
+     case kButton1Down:   cout << "Button 1 down" << endl; break;
+     case kButton2Down:   cout << "Button 2 down" << endl; break;
+     case kButton3Down:   cout << "Button 3 down" << endl; break;
+     case kKeyDown:       cout << "Key down" << endl; break;
+     case kKeyUp:         cout << "Key up" << endl; break;
+     case kKeyPress:      cout << "Key press" << endl; break;
+     case kButton1Locate: cout << "Button 1 locate" << endl; break;
+     case kButton2Locate: cout << "Button 2 locate" << endl; break;
+     case kButton3Locate: cout << "Button 3 locate" << endl; break;
+    }
+    */
+}
Index: /tags/Mars-V0.9/mtools/MineSweeper.h
===================================================================
--- /tags/Mars-V0.9/mtools/MineSweeper.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/MineSweeper.h	(revision 9772)
@@ -0,0 +1,78 @@
+#ifndef MARS_MineSweeper
+#define MARS_MineSweeper
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+
+class TText;
+class TMarker;
+class TVirtualPad;
+
+class MGeomCam;
+class MHexagon;
+
+class MineSweeper : public TObject
+{
+private:
+    static const Int_t fColorBombs[7]; // colors for the hexagons
+
+    MGeomCam      *fGeomCam;       // pointer to camera geometry
+
+    UInt_t         fNumPixels;     // number of pixels in the present geometry
+    Int_t          fNumBombs;      // number of bombs in total
+    Float_t        fRange;         // the range in millimeters of the present geometry
+
+    TClonesArray  *fPixels;        // array of all hexagons
+    TClonesArray  *fText;          // array of all texts
+    TClonesArray  *fFlags;         // array of all texts
+
+    TText         *fDone;          // TText showing the 'Game over'
+    TText         *fShow;          // TText showing the numbers of pixels and bombs
+
+    UInt_t         fW;             // Width of canvas
+    UInt_t         fH;             // Height of canvas
+    TVirtualPad   *fDrawingPad;    // pad in which we are drawing
+    Bool_t         fIsAllocated;
+
+    enum
+    {
+        kHidden    = 50,
+        kIsVisible = BIT(16),
+        kHasBomb   = BIT(17),
+        kHasFlag   = BIT(18),
+        kUserBits  = 0x7fc000 // 14-23 are allowed
+    };
+
+    MHexagon &operator[](int i) { return *((MHexagon*)fPixels->At(i)); }
+
+    TText   *GetText(Int_t i) { return (TText*)fText->At(i); }
+    TMarker *GetFlag(Int_t i) { return (TMarker*)fFlags->At(i); }
+
+    void  Remove(TObject *);
+    void  OpenHexagon(Int_t idx);
+    void  Done(TString, Int_t);
+    void  Update(Int_t);
+    void  SetNewCamera(MGeomCam *);
+    void  DrawHexagons();
+    void  Free();
+
+    void  Paint(Option_t *option="");
+    void  Draw(Option_t *option="");
+    void  ExecuteEvent(Int_t event, Int_t px, Int_t py);
+    Int_t DistancetoPrimitive(Int_t px, Int_t py) { return 0; }
+
+public:
+    MineSweeper();
+    ~MineSweeper();
+
+    void Reset();        //*MENU*
+    void ChangeCamera(); //*MENU*
+
+    ClassDef(MineSweeper, 0) // Magic Camera Games: Mine Sweeper
+};
+
+#endif
Index: /tags/Mars-V0.9/mtools/ToolsIncl.h
===================================================================
--- /tags/Mars-V0.9/mtools/ToolsIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/ToolsIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtools/ToolsLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtools/ToolsLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtools/ToolsLinkDef.h	(revision 9772)
@@ -0,0 +1,23 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MChisqEval+;
+
+#pragma link C++ class MTFillMatrix+;
+#pragma link C++ class MFFT+;
+#pragma link C++ class MHSimulatedAnnealing+;
+#pragma link C++ class MSimulatedAnnealing+;
+#pragma link C++ class MCubicCoeff+;
+#pragma link C++ class MCubicSpline+;
+
+#pragma link C++ class MineSweeper+;
+#pragma link C++ class MagicReversi+;
+#pragma link C++ class MagicSnake+;
+#pragma link C++ class MagicShow+;
+#pragma link C++ class MagicDomino+;
+#pragma link C++ class MagicCivilization+;
+
+#endif
Index: /tags/Mars-V0.9/mtrigger/MFTriggerPattern.cc
===================================================================
--- /tags/Mars-V0.9/mtrigger/MFTriggerPattern.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MFTriggerPattern.cc	(revision 9772)
@@ -0,0 +1,287 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz  12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MFTriggerPattern
+//
+//  A Filter for testing the trigger performance using Trigger Pattern.
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFTriggerPattern.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTriggerPattern.h"
+
+ClassImp(MFTriggerPattern);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. The default is to allow passing any trigger pattern.
+//
+MFTriggerPattern::MFTriggerPattern(const char *name, const char *title)
+    : fPattern(0), fMaskRequiredPrescaled(0), fMaskRequiredUnprescaled(0),
+      fMaskDeniedPrescaled(0), fMaskDeniedUnprescaled(0)
+{
+    fName  = name  ? name  : "MFTriggerPattern";
+    fTitle = title ? title : "Filter on Trigger Pattern";
+}
+
+// --------------------------------------------------------------------------
+//
+// Copy constructor
+//
+MFTriggerPattern::MFTriggerPattern(MFTriggerPattern &trigpatt)
+: MFilter(trigpatt)
+{
+    fMaskRequiredPrescaled   = trigpatt.fMaskRequiredPrescaled;
+    fMaskRequiredUnprescaled = trigpatt.fMaskRequiredUnprescaled;
+}
+
+
+// --------------------------------------------------------------------------
+//
+Int_t MFTriggerPattern::PreProcess(MParList *pList)
+{
+    fPattern = (MTriggerPattern*)pList->FindObject("MTriggerPattern");
+    if (!fPattern)
+    {
+	*fLog << err << "MTriggerPattern not found... abort." << endl;
+	return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MFTriggerPattern::Process()
+{
+    fResult = kFALSE;
+
+    const Byte_t p = fPattern->GetPrescaled();
+    const Byte_t u = fPattern->GetUnprescaled();
+
+    // Check whether all the bits required are ON
+    if ( ((p & fMaskRequiredPrescaled)   == fMaskRequiredPrescaled) &&
+         ((u & fMaskRequiredUnprescaled) == fMaskRequiredUnprescaled))
+      fResult = kTRUE;
+
+    // Now overwrite the result if one of the bits is denied
+    if ( (p & fMaskDeniedPrescaled) || (u & fMaskDeniedUnprescaled) )
+      fResult = kFALSE;
+    
+    return kTRUE;
+}
+
+void MFTriggerPattern::RequireTriggerLvl1(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled |= MTriggerPattern::kTriggerLvl1) : (fMaskRequiredUnprescaled |= MTriggerPattern::kTriggerLvl1);
+}
+
+void MFTriggerPattern::RequireTriggerLvl2(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled |= MTriggerPattern::kTriggerLvl2) : (fMaskRequiredUnprescaled |= MTriggerPattern::kTriggerLvl2);
+}
+
+void MFTriggerPattern::RequireCalibration(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled |= MTriggerPattern::kCalibration) : (fMaskRequiredUnprescaled |= MTriggerPattern::kCalibration);
+}
+
+void MFTriggerPattern::RequirePedestal(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled |= MTriggerPattern::kPedestal)    : (fMaskRequiredUnprescaled |= MTriggerPattern::kPedestal);
+}
+
+void MFTriggerPattern::RequirePinDiode(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled |= MTriggerPattern::kPinDiode)    : (fMaskRequiredUnprescaled |= MTriggerPattern::kPinDiode);
+}
+
+
+void MFTriggerPattern::DenyTriggerLvl1(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled |= MTriggerPattern::kTriggerLvl1) : (fMaskDeniedUnprescaled |= MTriggerPattern::kTriggerLvl1);
+}
+
+void MFTriggerPattern::DenyTriggerLvl2(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled |= MTriggerPattern::kTriggerLvl2) : (fMaskDeniedUnprescaled |= MTriggerPattern::kTriggerLvl2);
+}
+
+void MFTriggerPattern::DenyCalibration(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled |= MTriggerPattern::kCalibration) : (fMaskDeniedUnprescaled |= MTriggerPattern::kCalibration);
+}
+
+void MFTriggerPattern::DenyPedestal(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled |= MTriggerPattern::kPedestal)    : (fMaskDeniedUnprescaled |= MTriggerPattern::kPedestal);
+}
+
+void MFTriggerPattern::DenyPinDiode(Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled |= MTriggerPattern::kPinDiode)    : (fMaskDeniedUnprescaled |= MTriggerPattern::kPinDiode);
+}
+
+// -------------------------------------------------------------------------
+//
+// Low level settings. USE THESE ONLY IF YOU ARE AN EXPERT!
+//
+// You can concatenate bits either by using MTriggerPatter:
+//   eg. MTriggerPattern::kTriggerLvl1 & MTiggerPattern::kTriggerLvl2
+// of by hexadecimal values:
+//   eg. 0xab
+//
+//  while 0xab can be decoded like:
+//
+//                                   8421 8421
+//       0xa=10=8+2 0xb=11=8+2+1 --> 1010 1011
+//
+// or vice versa it is easy to get a hexadecimal number from a bit pattern,
+//   eg.
+//
+//       8421 8421
+//       0101 1101  -->  4+1=5=0x5 8+4+1=13=0xd --> 0x5d
+//
+void MFTriggerPattern::SetMaskRequired(const Byte_t mask, Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskRequiredPrescaled = mask) : (fMaskRequiredUnprescaled = mask);
+}
+
+// -------------------------------------------------------------------------
+//
+// Low level settings. USE THESE ONLY IF YOU ARE AN EXPERT!
+//
+// You can concatenate bits either by using MTriggerPatter:
+//   eg. MTriggerPattern::kTriggerLvl1 & MTiggerPattern::kTriggerLvl2
+// of by hexadecimal values:
+//   eg. 0xab
+//
+//  while 0xab can be decoded like:
+//
+//                                   8421 8421
+//       0xa=10=8+2 0xb=11=8+2+1 --> 1010 1011
+//
+// or vice versa it is easy to get a hexadecimal number from a bit pattern,
+//   eg.
+//
+//       8421 8421
+//       0101 1101  -->  4+1=5=0x5 8+4+1=13=0xd --> 0x5d
+//
+void MFTriggerPattern::SetMaskDenied(const Byte_t mask, Prescale_t prescaled)
+{
+    prescaled==kPrescaled ? (fMaskDeniedPrescaled  = mask) : (fMaskDeniedUnprescaled  = mask);
+}
+
+// -------------------------------------------------------------------------
+//
+// Create the mask to allow a particular (un)prescaled trigger pattern.
+//
+// Possible arguments are (upper/lower case is ignored):
+//
+//           "LT1"  : Trigger Level 1 flag
+//           "CAL"  : Calibration flag
+//           "LT2"  : Trigger Level 2 flag
+//           "PED"  : Pedestal flag
+//           "PIND" : Pin Diode flag
+// 
+// concatenations of these strings are allowed and considered as 
+// a logic "and", while trigger pattern flags not considered are
+// anyway allowed. To deny a particular trigger pattern use
+// the method Deny
+// Example: patt = "lt1 lt2" allows events with trigger pattern flags
+// {LT1,CAL,LT2} but not events with flags {LT1,CAL}.
+//
+void MFTriggerPattern::Require(TString patt, Prescale_t prescaled)
+{
+    if (patt.Contains("LT1", TString::kIgnoreCase))
+        RequireTriggerLvl1(prescaled);
+
+    if (patt.Contains("LT2", TString::kIgnoreCase))
+        RequireTriggerLvl2(prescaled);
+
+    if (patt.Contains("CAL", TString::kIgnoreCase))
+        RequireCalibration(prescaled);
+
+    if (patt.Contains("PED", TString::kIgnoreCase))
+        RequirePedestal(prescaled);
+
+    if (patt.Contains("PIND", TString::kIgnoreCase))
+        RequirePinDiode(prescaled);
+}
+
+// -------------------------------------------------------------------------
+//
+// Create the mask to deny a particular (un)prescaled trigger pattern.
+//
+// This method is there because is not possible to deny trigger patterns
+// using only the Require pattern. Possible arguments are (upper/lower
+// case is ignored):
+//
+//           "LT1"  : Trigger Level 1 flag
+//           "CAL"  : Calibration flag
+//           "LT2"  : Trigger Level 2 flag
+//           "PED"  : Pedestal flag
+//           "PIND" : Pin Diode flag
+// 
+// concatenations of these strings are allowed and considered as 
+// a logic "and", while trigger pattern flags not considered are
+// anyway allowed.
+//
+// Example: patt = "lt1 lt2" deny events with trigger pattern flags
+// {LT1,CAL,LT2} but not events with flags {LT1,CAL}.
+//
+void MFTriggerPattern::Deny(TString patt, Prescale_t prescaled)
+{
+    if (patt.Contains("LT1", TString::kIgnoreCase))
+        DenyTriggerLvl1(prescaled);
+
+    if (patt.Contains("LT2", TString::kIgnoreCase))
+        DenyTriggerLvl2(prescaled);
+
+    if (patt.Contains("CAL", TString::kIgnoreCase))
+        DenyCalibration(prescaled);
+
+    if (patt.Contains("PED", TString::kIgnoreCase))
+        DenyPedestal(prescaled);
+
+    if (patt.Contains("PIND", TString::kIgnoreCase))
+        DenyPinDiode(prescaled);
+}
+
+// --------------------------------------------------------------------------
+//
+Bool_t MFTriggerPattern::IsExpressionTrue() const
+{
+    return fResult;
+}
Index: /tags/Mars-V0.9/mtrigger/MFTriggerPattern.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/MFTriggerPattern.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MFTriggerPattern.h	(revision 9772)
@@ -0,0 +1,59 @@
+#ifndef MARS_MFTriggerPattern
+#define MARS_MFTriggerPattern
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MTriggerPattern;
+
+class MFTriggerPattern : public MFilter
+{
+public:
+    enum Prescale_t {
+        kUnPrescaled,
+        kPrescaled
+    };
+
+private:
+  MTriggerPattern *fPattern;        //!
+  
+  Byte_t fMaskRequiredPrescaled;    // Mask for filtering Trigger Pattern allowed
+  Byte_t fMaskRequiredUnprescaled;  // Mask for filtering Trigger Pattern allowed
+  Byte_t fMaskDeniedPrescaled;      // Mask for filtering Trigger Pattern denied
+  Byte_t fMaskDeniedUnprescaled;    // Mask for filtering Trigger Pattern denied
+  
+  Bool_t fResult;                   //!
+  
+  Int_t PreProcess(MParList *pList);
+  Int_t Process();
+  
+  Bool_t IsExpressionTrue() const;
+  
+public:
+  MFTriggerPattern(const char *name=NULL, const char *title=NULL);
+  MFTriggerPattern(MFTriggerPattern &trigpatt);
+    
+  void RequireTriggerLvl1(Prescale_t prescaled=kUnPrescaled);
+  void RequireTriggerLvl2(Prescale_t prescaled=kUnPrescaled);
+  void RequireCalibration(Prescale_t prescaled=kUnPrescaled);
+  void RequirePedestal(Prescale_t prescaled=kUnPrescaled);
+  void RequirePinDiode(Prescale_t prescaled=kUnPrescaled);
+  
+  void DenyTriggerLvl1(Prescale_t prescaled=kUnPrescaled);
+  void DenyTriggerLvl2(Prescale_t prescaled=kUnPrescaled);
+  void DenyCalibration(Prescale_t prescaled=kUnPrescaled);
+  void DenyPedestal(Prescale_t prescaled=kUnPrescaled);
+  void DenyPinDiode(Prescale_t prescaled=kUnPrescaled);
+  
+  void Require(TString patt, Prescale_t prescaled=kUnPrescaled);
+  void Deny(TString patt, Prescale_t prescaled=kUnPrescaled);
+  
+  // Low level settings. USE THESE ONLY IF YOU ARE AN EXPERT!
+  void SetMaskRequired(const Byte_t mask, Prescale_t prescaled=kUnPrescaled);
+  void SetMaskDenied(const Byte_t mask, Prescale_t prescaled=kUnPrescaled);
+  
+  ClassDef(MFTriggerPattern, 1) // A Filter for the Trigger Pattern
+};
+    
+#endif
Index: /tags/Mars-V0.9/mtrigger/MTriggerBit.cc
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerBit.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerBit.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerBit
+//
+//   This class stores the information about the L2 output Bit rates
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerBit.h"
+
+ClassImp(MTriggerBit);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtrigger/MTriggerBit.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerBit.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerBit.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MTriggerBit
+#define MARS_MTriggerBit
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MTriggerBit : public MParContainer
+{
+    friend class MReportTrigger;
+
+private:
+    
+    static const Int_t gsNBits=20;        // number of output bits
+
+    TArrayF fBit; // Array with the output bit rates
+
+public:
+    MTriggerBit() : fBit(gsNBits)  
+    {
+        fName  = "MTriggerBit";
+        fTitle = "Container for the L2 output bits rates ";
+    }
+
+    TArrayF GetTriggerBit() const { return fBit; }
+
+    Double_t operator[](const Int_t idx) 
+      {  
+	if (idx > gsNBits)
+	  return kFALSE;
+	
+	return fBit[idx]; 
+      }
+
+    ClassDef(MTriggerBit, 1) // Container for the L2 output bits rates
+};
+
+#endif
Index: /tags/Mars-V0.9/mtrigger/MTriggerCell.cc
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerCell.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerCell.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerCell
+//
+//   This class stores the information about the Trigger Cell Rates
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerCell.h"
+
+ClassImp(MTriggerCell);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtrigger/MTriggerCell.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerCell.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerCell.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MTriggerCell
+#define MARS_MTriggerCell
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MTriggerCell : public MParContainer
+{
+    friend class MReportTrigger;
+private:
+    static const Int_t gsNCells=32; //Number of fields with cell rates
+                                    // 19 cells and 12 dummy 
+
+    TArrayF fCellRate;       // Array of the measured L1 cell rates
+
+public:
+    MTriggerCell() : fCellRate(gsNCells)
+    {
+        fName  = "MTriggerCell";
+        fTitle = "Container for the measured cell rates";
+    }
+
+    Float_t GetMean() const { return fCellRate.GetSum()/fCellRate.GetSize(); }
+
+    TArrayF GetCellRate() const { return fCellRate; }
+
+    Double_t operator[](const Int_t idx) 
+      { 
+	if (idx > gsNCells)
+	  return kFALSE;
+	
+	return fCellRate[idx]; 
+      }
+
+
+    ClassDef(MTriggerCell, 1) // Container for the trigger cell rates
+};
+
+#endif
Index: /tags/Mars-V0.9/mtrigger/MTriggerIPR.cc
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerIPR.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerIPR.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerIPR
+//
+//   This class stores the information about the Individual Pixel Rates
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerIPR.h"
+
+ClassImp(MTriggerIPR);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtrigger/MTriggerIPR.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerIPR.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerIPR.h	(revision 9772)
@@ -0,0 +1,57 @@
+#ifndef MARS_MTriggerIPR
+#define MARS_MTriggerIPR
+
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerIPR : public MParContainer, public MCamEvent
+{
+    friend class MReportTrigger;
+
+private:
+    static const Int_t gsNTrigPix=397;  // number of trigger pixels
+
+    TArrayL fIPR;                       // [Hz] IPR (Individual Pixel Rates)
+
+public:
+    MTriggerIPR() : fIPR(gsNTrigPix)
+    {
+        fName  = "MTriggerIPR";
+        fTitle = "Trigger-Container for the Individual Pixel Rate (IPR)";
+    }
+
+    Float_t GetMean() const { return fIPR.GetSum()/fIPR.GetSize(); }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+      if (idx >= gsNTrigPix)
+	return kFALSE;
+
+      val = fIPR[idx];
+      return val>0;
+    }
+
+    Double_t operator[](const Int_t idx) 
+      {
+	if (idx > gsNTrigPix)
+	  return kFALSE;
+
+	return fIPR[idx]; 
+      } 
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MTriggerIPR, 1) // Trigger-Container for the Individual Pixel Rate (IPR)
+};
+
+#endif
Index: /tags/Mars-V0.9/mtrigger/MTriggerLiveTime.cc
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerLiveTime.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerLiveTime.cc	(revision 9772)
@@ -0,0 +1,38 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerLiveTime
+//
+//   This class stores the information about the livetime and deadtime
+//   measured by the scalers 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerLiveTime.h"
+
+ClassImp(MTriggerLiveTime);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtrigger/MTriggerLiveTime.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerLiveTime.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerLiveTime.h	(revision 9772)
@@ -0,0 +1,44 @@
+#ifndef MARS_MTriggerLiveTime
+#define MARS_MTriggerLiveTime
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerLiveTime : public MParContainer
+{
+    friend class MReportTrigger;
+
+private:
+    static const Int_t gsNScalers=5;        // number of scalers
+
+    TArrayL fLiveTime; // Array with the livetime
+    TArrayL fDeadTime; // Array with the deadtime
+
+public:
+    MTriggerLiveTime() : fLiveTime(gsNScalers), fDeadTime(gsNScalers)  
+    {
+        fName  = "MTriggerLiveTime";
+        fTitle = "Container for the Live-deadtime      ";
+    }
+
+    TArrayL GetLiveTime() const { return fLiveTime; }
+    TArrayL GetDeadTime() const { return fDeadTime; }
+
+    // !FIX ME!  Only live time is returned...
+    Double_t operator[](const Int_t idx) 
+      {  	
+	if (idx > gsNScalers)
+	  return -1;
+	
+	return fLiveTime[idx]; 
+      }
+
+    ClassDef(MTriggerLiveTime, 1) // Container for the Live-Deadtime
+};
+
+#endif
Index: /tags/Mars-V0.9/mtrigger/MTriggerPattern.cc
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerPattern.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerPattern.cc	(revision 9772)
@@ -0,0 +1,58 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz  12/2004 <mailto:nicola.galante@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MTriggerPattern
+//
+//  A container to store the decoded trigger pattern.
+//
+// The idea is, that this container will never change the meaning of its
+// variables, while the trigger pattern itself could.
+//
+// If new 'features' are necessary the decoding (MTriggerPatternDecode)
+// must be changed to correctly decode the pattern into the existing
+// MTriggerPattern. If new information is decoded you may have to
+// add new variables to this container. Don't forget to increase the
+// class version number (ClassDef) and document your change HERE.
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerPattern.h"
+
+ClassImp(MTriggerPattern);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MTriggerPattern::MTriggerPattern(const char *name, const char *title)
+    : fPrescaled(0), fUnprescaled(0)
+{
+    fName  = name  ? name  : "MTriggerPattern";
+    fTitle = title ? title : "Container for decoded trigger pattern";
+}
Index: /tags/Mars-V0.9/mtrigger/MTriggerPattern.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerPattern.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerPattern.h	(revision 9772)
@@ -0,0 +1,39 @@
+#ifndef MARS_MTriggerPattern
+#define MARS_MTriggerPattern
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MTriggerPattern : public MParContainer
+{
+    friend class MTriggerPatternDecode;
+
+public:
+    enum Pattern_t {
+        kTriggerLvl1 = BIT(0),
+        kCalibration = BIT(1), // Pulse Trigger
+        kTriggerLvl2 = BIT(2), // LUT Pseudo Size selection
+        kPedestal    = BIT(3),
+        kPinDiode    = BIT(4)
+        //kUnused      = BIT(5)
+        //kUnused      = BIT(6)
+        //kUnused      = BIT(7)
+    };
+
+private:
+    Byte_t fPrescaled;   // Bit Pattern as defined above
+    Byte_t fUnprescaled; // Bit Pattern as defined above
+
+public:
+    MTriggerPattern(const char *name=0, const char *title=0);
+
+    void Reset() { fPrescaled=0; fUnprescaled=0; }
+
+    Byte_t GetPrescaled() const   { return fPrescaled; }
+    Byte_t GetUnprescaled() const { return fUnprescaled; }
+
+    ClassDef(MTriggerPattern, 1) // Container storing the decoded trigger pattern
+};
+
+#endif
Index: /tags/Mars-V0.9/mtrigger/MTriggerPatternDecode.cc
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerPatternDecode.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerPatternDecode.cc	(revision 9772)
@@ -0,0 +1,134 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Nicola Galante  12/2004 <mailto:nicola.galante@pi.infn.it>
+!   Author(s): Thomas Bretz 12/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2004
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   MTriggerPatternDecode
+//
+//  Decodes the trigger pattern from MRawEvtData into MTriggerPattern.
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+// This can be changed using the information about the file-type.
+//
+// Input:
+//   MRawEvtData
+//
+// Output:
+//   MTriggerPattern
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerPatternDecode.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawEvtHeader.h"
+#include "MRawRunHeader.h"
+#include "MTriggerPattern.h"
+
+ClassImp(MTriggerPatternDecode);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor
+//
+MTriggerPatternDecode::MTriggerPatternDecode(const char *name, const char *title)
+    : fRunHeader(0), fEvtHeader(0), fPattern(0)
+{
+    fName  = name  ? name  : "MTriggerPatternDecode";
+    fTitle = title ? title : "Task to decode Trigger Pattern";
+}
+
+// --------------------------------------------------------------------------
+//
+Int_t MTriggerPatternDecode::PreProcess(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
+    if (!fRunHeader)
+    {
+	*fLog << err << "MRawRunHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    fEvtHeader = (MRawEvtHeader *)pList->FindObject("MRawEvtHeader");
+    if (!fEvtHeader)
+    {
+	*fLog << err << "MRawEvtHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    fPattern = (MTriggerPattern*)pList->FindCreateObj("MTriggerPattern");
+    if (!fPattern)
+    {
+	*fLog << err << "MRawEvtHeader not found... abort." << endl;
+	return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// For files before file version 5 the trigger pattern is set to 00000000.
+// This can be changed using the information about the file-type.
+//
+Int_t MTriggerPatternDecode::Process()
+{
+    // No setting necessary because MTriggerPattern::reset() has
+    // been called just before
+    if (fRunHeader->GetFormatVersion()<5)
+        return kTRUE;
+
+    UInt_t pattern = ~fEvtHeader->GetTriggerID();
+
+    // The the trigger pattern is currently written with inverted bits,
+    // but in the future this could be changed. In this case the file version
+    // number of the raw-data format must be checked. It tells you the
+    // file format (meaning of the bits)
+    // If for some reason the file-format has not been correctly changed
+    // use the run-number to decide whether the bits must be inverted or not.
+
+    // Trigger Pattern is a number of 16 bits, but if the machine
+    // is a 64 bits then the bit inversion the first 16 bits are set to 1,
+    // possibly giving problems with the filtering with the masks.
+    // Because UInt_t by definition is a 32 bit number on any
+    // machine (see root manual) no check is needed.
+    // The simplest workaround is:
+    //   pattern &= 0xffffffff;
+
+    // For the moment the meaning of the bits in
+    // MRawEvtHeader::GetTriggerID and in MTriggerPattern::fTriggerPattern
+    // are identical - this may change in the future! In this case
+    // the decoding HERE must be changed - NOT MTriggerPattern.
+    // If an enhancement of the information stored in MTriggerPattern
+    // is necessary ADD new variables! Don't change the meaning of the old
+    // ones!
+    fPattern->fPrescaled   =  pattern     & 0xff;
+    fPattern->fUnprescaled = (pattern>>8) & 0xff;
+
+    return kTRUE;
+}
Index: /tags/Mars-V0.9/mtrigger/MTriggerPatternDecode.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerPatternDecode.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerPatternDecode.h	(revision 9772)
@@ -0,0 +1,29 @@
+#ifndef MARS_MTriggerPatternDecode
+#define MARS_MTriggerPatternDecode
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+class MRawEvtHeader;
+class MRawRunHeader;
+class MTriggerPattern;
+
+class MTriggerPatternDecode : public MTask
+{
+private:
+    MRawRunHeader   *fRunHeader;
+    MRawEvtHeader   *fEvtHeader;
+    MTriggerPattern *fPattern;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MTriggerPatternDecode(const char *name=0, const char *title=0);
+
+    ClassDef(MTriggerPatternDecode, 1) // Task to decode the Trigger Pattern
+};
+
+#endif
Index: /tags/Mars-V0.9/mtrigger/MTriggerPrescFact.cc
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerPrescFact.cc	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerPrescFact.cc	(revision 9772)
@@ -0,0 +1,37 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!   Author(s): Antonio Stamerra, 05/2004 <mailto:antonio.stamerra@pi.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MTriggerPrescFact
+//
+//   This class stores the information about the L2 prescaling factors
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTriggerPrescFact.h"
+
+ClassImp(MTriggerPrescFact);
+
+using namespace std;
Index: /tags/Mars-V0.9/mtrigger/MTriggerPrescFact.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/MTriggerPrescFact.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/MTriggerPrescFact.h	(revision 9772)
@@ -0,0 +1,42 @@
+#ifndef MARS_MTriggerPrescFact
+#define MARS_MTriggerPrescFact
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif 
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MTriggerPrescFact : public MParContainer
+{
+    friend class MReportTrigger;
+
+private:
+    
+    static const Int_t gsNPrescFacts=8;        // number of factors
+
+    TArrayL fPrescFact; // Array with the prescaling factors
+
+public:
+    MTriggerPrescFact() : fPrescFact(gsNPrescFacts)  
+    {
+        fName  = "MTriggerPrescFact";
+        fTitle = "Container for the L2 Prescaling Factors      ";
+    }
+
+    TArrayL GetPrescFactors() const { return fPrescFact; }
+
+    Double_t operator[](const Int_t idx) 
+      {  
+	if (idx > gsNPrescFacts)
+	  return kFALSE;
+	
+	return fPrescFact[idx]; 
+      }
+
+    ClassDef(MTriggerPrescFact, 1) // Container for the L2 Prescaling Factors
+};
+
+#endif
Index: /tags/Mars-V0.9/mtrigger/Makefile
===================================================================
--- /tags/Mars-V0.9/mtrigger/Makefile	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/Makefile	(revision 9772)
@@ -0,0 +1,38 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#------------------------------------------------------------------------------
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Trigger
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mraw -I../mcalib
+
+SRCFILES = MTriggerIPR.cc \
+	   MTriggerCell.cc\
+	   MTriggerBit.cc\
+	   MTriggerPrescFact.cc\
+	   MTriggerLiveTime.cc \
+           MTriggerPattern.cc \
+           MTriggerPatternDecode.cc \
+           MFTriggerPattern.cc
+
+############################################################
+
+all: $(OBJS)
+
+include ../Makefile.rules
+
+mrproper:	clean rmbak
Index: /tags/Mars-V0.9/mtrigger/TriggerIncl.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/TriggerIncl.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/TriggerIncl.h	(revision 9772)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars-V0.9/mtrigger/TriggerLinkDef.h
===================================================================
--- /tags/Mars-V0.9/mtrigger/TriggerLinkDef.h	(revision 9772)
+++ /tags/Mars-V0.9/mtrigger/TriggerLinkDef.h	(revision 9772)
@@ -0,0 +1,17 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MTriggerIPR+;
+#pragma link C++ class MTriggerCell+;
+#pragma link C++ class MTriggerBit+;
+#pragma link C++ class MTriggerPrescFact+;
+#pragma link C++ class MTriggerLiveTime+;
+
+#pragma link C++ class MTriggerPattern+;
+#pragma link C++ class MTriggerPatternDecode+;
+#pragma link C++ class MFTriggerPattern+;
+
+#endif
Index: /tags/Mars-V0.9/readdaq.cc
===================================================================
--- /tags/Mars-V0.9/readdaq.cc	(revision 9772)
+++ /tags/Mars-V0.9/readdaq.cc	(revision 9772)
@@ -0,0 +1,202 @@
+#include <TSystem.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+#include "MTime.h"
+#include "MPrint.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateArray.h"
+#include "MRawFileRead.h"
+
+
+//#include "MInputStreamID.h"
+//#include "MMcEvt.hxx"
+//#include "MMcTrig.hxx"
+
+using namespace std;
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// This is an demonstration how to read in a unmerpped daq file
+//
+/////////////////////////////////////////////////////////////////////////////
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "              ReadDaq - MARS V" << MARSVER          << endl;
+    gLog << "       MARS - Read and print daq data files"        << endl;
+    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
+    gLog << "               Using ROOT v" << ROOTVER             << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   readdaq [-h] [-?] [-vn] [-dec] [-a0] inputfile[.raw]" << endl << endl;
+    gLog << "     input file:   Magic DAQ binary file." << endl;
+    gLog << "     -a0: Do not use Ansii codes." << endl;
+    gLog << "     -vn: Verbosity level n [default=2]" << endl;
+    gLog << "     -d1: print data in decimal values" << endl;
+    gLog << "     -c1: print MRawCrateArray data" << endl;
+    gLog << "     -?, -h, --help: This help" << endl << endl;
+}
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Set verbosity to highest level.
+    //
+    gLog.SetDebugLevel(arg.HasOption("-v") ? arg.GetIntAndRemove("-v") : 2);
+
+    if (arg.HasOption("-a") && arg.GetIntAndRemove("-a")==0)
+        gLog.SetNoColors();
+
+    const bool kDecimal    = arg.HasOption("-d") && arg.GetIntAndRemove("-d")==1;
+    const bool kPrintArray = arg.HasOption("-c") && arg.GetIntAndRemove("-c")==1;
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // This is to make argv[i] more readable insidethe code
+    //
+    TString kNamein = arg.GetArgumentStr(0);
+  
+    if (!kNamein.EndsWith(".raw"))
+        kNamein += ".raw";
+
+    //
+    // Initialize Non-GUI (batch) mode
+    //
+    gROOT->SetBatch();
+
+    //
+    // check whether the given files are OK.
+    //
+    if (gSystem->AccessPathName(kNamein, kFileExists))
+    {
+        gLog << err << "Sorry, the input file '" << kNamein << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    //
+    //  open the file
+    //
+    gLog << " Open the file '" << kNamein << "'" << endl;
+
+
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    //
+    MParList plist;
+
+    MTaskList tasks;
+    tasks.SetOwner();
+    plist.AddToList(&tasks);
+
+    //
+    // ---- The following is only necessary to supress some output ----
+    //
+    MRawRunHeader runheader;
+    plist.AddToList(&runheader);
+
+    MRawEvtHeader evtheader;
+    plist.AddToList(&evtheader);
+
+    MRawEvtData evtdata;
+    plist.AddToList(&evtdata);
+
+    MRawEvtData evtdata2("MRawEvtData2");
+    plist.AddToList(&evtdata2);
+
+    MRawCrateArray cratearray;
+    plist.AddToList(&cratearray);
+
+    MTime evttime;
+    plist.AddToList(&evttime);
+
+    //
+    // create the tasks which should be executed and add them to the list
+    // in the case you don't need parameter containers, all of them can
+    // be created by MRawFileRead::PreProcess
+    //
+    MRawFileRead read(kNamein);
+    tasks.AddToList(&read);
+
+    MPrint print0;
+    MPrint print1("MRawEvtHeader",  "nogains", "PrintEvtHeader");
+    MPrint print2("MTime",          "", "PrintTime");
+    MPrint print3("MRawCrateArray", "", "PrintCrateArray");
+    MPrint print4("MRawEvtData", kDecimal?"dec":"hex", "PrintEvtData");
+    MPrint print5("MRawEvtData2", kDecimal?"dec":"hex", "PrintEvtData2");
+
+    tasks.AddToList(&print0);
+    tasks.AddToList(&print1);
+    tasks.AddToList(&print2);
+    if (kPrintArray)
+        tasks.AddToList(&print3);
+    tasks.AddToList(&print4);
+    tasks.AddToList(&print5);
+
+    //
+    // create the looping object and tell it about the parameters to use
+    // and the tasks to execute
+    //
+    MEvtLoop magic;
+    magic.SetParList(&plist);
+
+    //
+    // Start the eventloop which reads the raw file (MRawFileRead) and
+    // write all the information into a root file (MRawFileWrite)
+    //
+    // between reading and writing we can do, transformations, checks, etc.
+    // (I'm think of a task like MRawDataCheck)
+    //
+    if (!magic.Eventloop())
+    {
+        gLog << err << "ERROR: Reading DAQ file failed!" << endl;
+        return -1;
+    }
+
+    gLog << all << "Reading DAQ file finished successfull!" << endl;
+
+    // end of small readin program
+
+    return 0;
+}
Index: /tags/Mars-V0.9/readraw.cc
===================================================================
--- /tags/Mars-V0.9/readraw.cc	(revision 9772)
+++ /tags/Mars-V0.9/readraw.cc	(revision 9772)
@@ -0,0 +1,222 @@
+#include <TSystem.h>
+
+#include <TFile.h>
+#include <TTree.h>
+#include <TBranch.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+#include "MTime.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateArray.h"
+#include "MInputStreamID.h"
+
+#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+
+using namespace std;
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// This is an demonstration how to read in a merpped root file
+// This is a demonstration how to use root, not how you should
+// read a merpped file!
+//
+/////////////////////////////////////////////////////////////////////////////
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "              ReadRaw - MARS V" << MARSVER          << endl;
+    gLog << "       MARS - Read and print raw data files"        << endl;
+    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
+    gLog << "               Using ROOT v" << ROOTVER             << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   readraw [-h] [-?] [-vn] [-dec] [-a0] inputfile[.root]" << endl << endl;
+    gLog << "     input file:   Magic DAQ binary file." << endl;
+    gLog << "     -vn: Verbosity level n [default=2]" << endl;
+    gLog << "     -d, --dec: print data in decimal values" << endl;
+    gLog << "     -a, --no-colors: Do not use Ansii color codes" << endl;
+    gLog << "     -?,-h,--help: This help" << endl << endl;
+}
+
+void EnableBranch(TTree *t, TString name, void *ptr)
+{
+    if (!t->GetBranch(name+"."))
+        return;
+
+    t->GetBranch(name+".")->SetAddress(ptr);
+    gLog << " Found '" << name << "'" << endl;
+}
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    // Evaluate arguments
+    MArgs arg(argc, argv);
+
+    // check for the right usage of the program
+    if (arg.HasOption("-?") || arg.HasOption("-h") || arg.HasOption("--help") ||
+        arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return -1;
+    }
+
+    // Set verbosity
+    gLog.SetDebugLevel(arg.HasOption("-v") ? arg.GetIntAndRemove("-v") : 2);
+
+    // Set color usage
+    if (arg.HasOnlyAndRemove("--no-colors") || arg.HasOnlyAndRemove("-a"))
+        gLog.SetNoColors();
+
+    // Set usage of decimal values
+    const bool kDecimal = arg.HasOnlyAndRemove("-d") || arg.HasOnlyAndRemove("--dec");
+
+    //
+    // check for unidentified options
+    //
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+    }
+
+    //
+    // This is to make argv[i] more readable insidethe code
+    //
+    TString kNamein = arg.GetArgumentStr(0);
+  
+    if (!kNamein.EndsWith(".root"))
+        kNamein += ".root";
+
+    //
+    // Initialize Non-GUI (batch) mode
+    //
+    gROOT->SetBatch();
+
+    //
+    // check whether the given files are OK.
+    //
+    if (gSystem->AccessPathName(kNamein, kFileExists))
+    {
+        gLog << err << "Sorry, the input file '" << kNamein << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    //
+    //  open the file
+    //
+    gLog << inf << " Open the file '" << kNamein << "'" << endl;
+    TFile input(kNamein, "READ");
+
+    //
+    // open the Run Header and read in
+    //
+    gLog << " Check for Tree 'RunHeaders'" << endl;
+    TTree *runtree = (TTree*)input.Get("RunHeaders");
+    if (!runtree)
+        gLog << warn << " WARNING - This file has no Tree 'RunHeaders'" << endl << endl;
+    else
+    {
+        gLog << " Entries in Tree RunHeaders: " << dec << runtree->GetEntries() << endl;
+
+        MRawRunHeader *runheader = NULL;
+        runtree->GetBranch("MRawRunHeader.")->SetAddress(&runheader);
+        runtree->GetEvent(0);
+        runheader->Print();
+    }
+
+    //
+    // open the DataTree and read in 
+    //
+    gLog << inf << " Check the Tree 'Events'" << endl ;
+    TTree *evttree = (TTree*)input.Get("Events") ;
+    if (!evttree)
+    {
+        gLog << err << "Tree 'Events' not found in file... exit!" << endl;
+        return -1;
+    }
+
+    //
+    //  check the branches in the Tree 
+    //
+    gLog << " Check all the Branches in the Tree." << endl;
+    gLog << endl;
+
+    MRawEvtHeader  *evtheader = NULL;
+    MTime          *evttime   = NULL;
+    MRawEvtData    *evtdata   = NULL;
+    MRawEvtData    *evtdata2  = NULL;
+    MRawCrateArray *evtcrate  = NULL;
+    MMcEvt         *evtmc     = NULL;
+    MMcTrig        *trigmc    = NULL;
+
+    EnableBranch(evttree, "MRawEvtHeader",  &evtheader);
+    EnableBranch(evttree, "MTime",          &evttime);
+    EnableBranch(evttree, "MRawEvtData",    &evtdata);
+    EnableBranch(evttree, "MRawEvtData2",   &evtdata2);
+    EnableBranch(evttree, "MRawCrateArray", &evtcrate);
+    EnableBranch(evttree, "MMcEvt",         &evtmc);
+    EnableBranch(evttree, "MMcTrig",        &trigmc);
+
+    //
+    // loop over all entries 
+    //
+    const Int_t nent = (Int_t)evttree->GetEntries();
+
+    gLog << " Entries in Tree Data: " << dec << nent << endl;
+    gLog << endl;
+
+    for (Int_t i = 0; i<nent; i++)
+    {
+        gLog << all << "Entry: " << i << endl;
+
+        //
+        // readin event with the selected branches
+        //
+        evttree->GetEvent(i);
+
+        if (evtmc)
+            evtmc->Print();
+        if (trigmc)
+            trigmc->Print("short");
+        if (evtheader)
+            evtheader->Print();
+        if (evttime)
+            evttime->Print();
+        if (evtcrate)
+            evtcrate->Print();
+        if (evtdata)
+            evtdata->Print(kDecimal?"dec":"hex");
+        if (evtdata2)
+            evtdata2->Print(kDecimal?"dec":"hex");
+
+        gLog << endl;
+    } 
+    
+    // end of small readin program
+
+    return 0;
+}
Index: /tags/Mars-V0.9/showlog.cc
===================================================================
--- /tags/Mars-V0.9/showlog.cc	(revision 9772)
+++ /tags/Mars-V0.9/showlog.cc	(revision 9772)
@@ -0,0 +1,108 @@
+#include <errno.h>
+#include <fstream>
+
+#include <TRegexp.h>
+
+#include "MArgs.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+using namespace std;
+
+static void Usage()
+{
+    gLog << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   showlog [options] filename" << endl;
+    gLog << " or" << endl;
+    gLog << "   showlog [options] < filename" << endl << endl;
+    gLog.Usage();
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl;
+    gLog << endl;
+    gLog << " This program converts colored output  made with ansi codes" << endl;
+    gLog << " (like it is done by MLog)  and redirected into a file back" << endl;
+    gLog << " into colored output." << endl << endl;
+    gLog << " It cannot be used to get rid of the Ansi codes. To display" << endl;
+    gLog << " colored output with less use the option -R, eg." << endl;
+    gLog << "   less -R logfile.log" << endl << endl;
+}
+
+void RemoveAnsi(TString &s)
+{
+    static const TRegexp regexp("[][[][0-9]+[m]");
+
+    while (1)
+    {
+        Ssiz_t len = 0;
+        Ssiz_t idx = s.Index(regexp, &len);
+        if (idx<0)
+            break;
+
+        s.Remove(idx, len);
+    }
+}
+
+// FIXME: Enhance this tool with a converter to HTMl, etc.
+//        Add option for 'no-colors'
+int main(int argc, char **argv)
+{
+    MArgs arg(argc, argv);
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    const Bool_t kNoColors = arg.HasOnly("--no-colors") || arg.HasOnly("-a");
+
+    gLog.Setup(arg);
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()>1)
+    {
+        Usage();
+        return -1;
+    }
+
+    // casts necessary for gcc 2.95.3
+    istream *in = arg.GetNumArguments()==1 ? (istream*)new ifstream(arg.GetArgumentStr(0)) : (istream*)&cin;
+    if (!*in)
+    {
+        gLog << "Cannot open file " << arg.GetArgumentStr(0) << ": " << strerror(errno) << endl;
+        return -1;
+    }
+
+    TString s;
+    while (1)
+    {
+        s.ReadLine(*in);
+        if (!*in)
+            break;
+
+        if (kNoColors)
+            RemoveAnsi(s);
+        else
+            s.ReplaceAll("", "\033");
+        gLog << s << endl;
+    }
+
+    if (in!=&cin)
+        delete in;
+
+    return 0;
+}
Index: /tags/Mars-V0.9/showplot.cc
===================================================================
--- /tags/Mars-V0.9/showplot.cc	(revision 9772)
+++ /tags/Mars-V0.9/showplot.cc	(revision 9772)
@@ -0,0 +1,145 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TGClient.h>
+#include <TApplication.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MArgs.h"
+
+#include "MStatusDisplay.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << endl;
+    gLog << "showplot --- Mars V" << MARSVER << " compiled on <" << __DATE__ << "> using ROOT v" << ROOTVER << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " showplot [options] filename" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   filename                  Input file containing an MStatusArray" << endl << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Options: "<< endl;
+    gLog.Usage();
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << endl;
+    gLog << " Output Options: "<< endl;
+    gLog << "   --save-as-ps[=filename]   Save plots as postscript" << endl;
+    gLog << "   --save-as-gif[=filename]  Save plots as gif files" << endl;
+    gLog << "   --save-as-C[=filename]    Save plots as root scripts" << endl;
+    gLog << "   --tab=num                 Save only tab number num" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl;
+    gLog << endl;
+    gLog << "Description:" << endl;
+    gLog << " Use showplot to display a MStatusArray in an MStatusDisplay." << endl;
+    gLog << " MStatusArrays are typically written by programs showing data" << endl;
+    gLog << " check plots, like callisto." << endl;
+    gLog << endl;
+}
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv, kTRUE);
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    gLog.Setup(arg);
+
+    const Bool_t kQuit      = arg.HasOnlyAndRemove("-q");
+    const Bool_t kBatch     = arg.HasOnlyAndRemove("-b");
+
+    const Int_t  kTab       = arg.GetIntAndRemove("--tab=", -1);
+
+    const Bool_t kSaveAsPs  = arg.HasOnlyAndRemove("--save-as-ps")  || arg.Has("--save-as-ps=");
+    const Bool_t kSaveAsGif = arg.HasOnlyAndRemove("--save-as-gif") || arg.Has("--save-as-gif=");
+    const Bool_t kSaveAsC   = arg.HasOnlyAndRemove("--save-as-C")   || arg.Has("--save-as-C=");
+
+    TString kNamePs  = arg.GetStringAndRemove("--save-as-ps=");
+    TString kNameGif = arg.GetStringAndRemove("--save-as-gif=");
+    TString kNameC   = arg.GetStringAndRemove("--save-as-C=");
+
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return -1;
+    }
+
+    TApplication app("Showplot", &argc, argv);
+    if (!gROOT->IsBatch() && !gClient || gROOT->IsBatch() && !kBatch)
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Process filenames
+    //
+    const TString kInput = arg.GetArgumentStr(0);
+
+    if (kNamePs.IsNull()  && kSaveAsPs)
+        kNamePs = kInput;
+    if (kNameGif.IsNull() && kSaveAsGif)
+        kNameGif = kInput;
+    if (kNameC.IsNull()   && kSaveAsC)
+        kNameC = kInput;
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetTitle(kInput);
+    d->Open(kInput);
+
+    if (kSaveAsPs)
+        d->SaveAsPS(kTab, kNamePs);
+    if (kSaveAsGif)
+        d->SaveAsGIF(kTab, kNameGif);
+    if (kSaveAsC)
+        d->SaveAsC(kTab, kNameC);
+
+    if (kBatch || kQuit)
+    {
+        delete d;
+        return 0;
+    }
+
+    // From now on each 'Close' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+    // Wait until the user decides to exit the application
+    app.Run(kFALSE);
+    return 0;
+}
Index: /tags/Mars-V0.9/sinope.cc
===================================================================
--- /tags/Mars-V0.9/sinope.cc	(revision 9772)
+++ /tags/Mars-V0.9/sinope.cc	(revision 9772)
@@ -0,0 +1,448 @@
+#include <errno.h>
+#include <fstream>
+
+#include <TROOT.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include <TH1.h>
+#include <TLine.h>
+#include <TString.h>
+#include <TVirtualPad.h>
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+#include "MRawFileRead.h"
+#include "MArrayD.h"
+#include "MTaskInteractive.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MArgs.h"
+#include "MSequence.h"
+#include "MStatusDisplay.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+#include "MRawFileRead.h"
+#include "MDirIter.h"
+
+using namespace std;
+
+MRawEvtData   data;
+MRawRunHeader header;
+
+MArrayD artime;
+MArrayD height(256);
+Int_t   entries=0;
+Int_t   events =0;
+
+Int_t PreProcess(MParList *plist)
+{
+    artime.Set(header.GetNumSamplesHiGain() + header.GetNumSamplesLoGain());
+    return kTRUE;
+}
+
+Int_t Process()
+{
+    events++;
+
+    // This is the workaround to put hi- and lo-gains together
+    const Int_t nhigain = header.GetNumSamplesHiGain();
+    const Int_t nlogain = header.GetNumSamplesLoGain();
+
+    const Int_t n = nhigain+nlogain;
+
+    // Real Process
+    MRawEvtPixelIter pixel(&data);
+
+    Byte_t slices[n];
+
+    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);
+
+        Byte_t *max = slices;
+        Byte_t *min = slices;
+
+        for (Byte_t *b=slices+1; b<slices+n; b++)
+        {
+            if (*b>=*max)
+                max = b;
+            if (*b<=*min)
+                min = b;
+        }
+
+        const Int_t smax = max-slices;
+        const Int_t diff = *max-*min;
+
+        if (diff<50 || diff>235) // no-signal
+            continue;
+
+        height[diff]++;
+        artime[smax]++;
+        entries++;
+    }
+    return kTRUE;
+}
+
+Int_t GetFWHM(const TH1D &h, Int_t &min, Int_t &max)
+{
+    const Double_t hmax = h.GetMaximum()/2;
+    const Int_t    bin  = h.GetMaximumBin();
+
+    for (min=bin; min>1; min--)
+        if (h.GetBinContent(min)<hmax)
+            break;
+
+    for (max=bin; max<h.GetNbinsX(); max++)
+        if (h.GetBinContent(max)<hmax)
+            break;
+
+    return max-min;
+}
+
+TString kOutpath="";
+MStatusDisplay *d=0;
+
+Int_t PostProcess()
+{
+    if (entries==0)
+    {
+        gLog << warn << "No entries processed..." << endl;
+        return kFALSE;
+    }
+
+    TH1D h1("Arrival", "Arrival Time distribution for signals", artime.GetSize(), -0.5, artime.GetSize()-0.5);
+    TH1D h2("Height",  "Pulse height distribution",             height.GetSize(), -0.5, height.GetSize()-0.5);
+    h1.SetXTitle("Arrival Time [slice]");
+    h2.SetXTitle("Pulse Height [cts]");
+    h1.SetDirectory(0);
+    h2.SetDirectory(0);
+    h1.SetEntries(entries);
+    h2.SetEntries(entries);
+    memcpy(h1.GetArray()+1, artime.GetArray(), artime.GetSize()*sizeof(Double_t));
+    memcpy(h2.GetArray()+1, height.GetArray(), height.GetSize()*sizeof(Double_t));
+
+    TLine l;
+    l.SetLineColor(kGreen);
+    l.SetLineWidth(2);
+
+    Int_t min, max;
+
+    //MStatusDisplay *d = new MStatusDisplay;
+    d->AddTab("Time");
+    h1.DrawClone();
+    l.DrawLine(h1.GetMaximumBin()-1, 0, h1.GetMaximumBin()-1, h1.GetMaximum());
+    const Int_t fwhm1  = GetFWHM(h1, min, max);
+    const Bool_t asym1 = TMath::Abs((h1.GetMaximumBin()-min)-(max-h1.GetMaximumBin()))>fwhm1/2;;
+    l.DrawLine(min-1, h1.GetMaximum()/2, max-1, h1.GetMaximum()/2);
+    gPad->Update();
+    d->AddTab("Pulse");
+    h2.DrawClone();
+    l.DrawLine(h2.GetMaximumBin()-1, 0, h2.GetMaximumBin()-1, h2.GetMaximum());
+    const Int_t fwhm2  = GetFWHM(h2, min, max);
+    const Bool_t asym2 = TMath::Abs((h2.GetMaximumBin()-min)-(max-h2.GetMaximumBin()))>fwhm2/2;;
+    l.DrawLine(min-1, h2.GetMaximum()/2, max-1, h2.GetMaximum()/2);
+    gPad->Update();
+
+    d->SaveAsRoot(Form("%sroot", kOutpath.Data()));
+
+    ofstream fout(Form("%stxt", kOutpath.Data()));
+    if (!fout)
+    {
+        gLog << err << "Cannot open file: " << strerror(errno) << endl;
+        return kERROR;
+    }
+
+    fout << "Events:         " << events << endl;
+    fout << "HasSignals:     " << (fwhm1>10?"No":"Yes") << endl;
+    fout << "HasPedestal:    " << (fwhm1<20?"No":"Yes") << endl;
+    fout << endl;
+    fout << "PositionSignal: " << h1.GetMaximumBin()-1 << endl;
+    fout << "PositionFWHM:   " << fwhm1 << endl;
+    fout << "PositionAsym:   " << (asym1?"Yes":"No") << endl;
+    fout << endl;
+    fout << "HeightSignal:   " << h2.GetMaximumBin()-1 << endl;
+    fout << "HeightFWHM:     " << fwhm2 << endl;
+    fout << "HeightAsym:     " << (asym2?"Yes":"No") << endl;
+    fout << endl;
+
+
+    return kTRUE;
+}
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "========================================================" << endl;
+    gLog << "                  Sinope - MARS V" << MARSVER            << endl;
+    gLog << "        MARS -- SImple Non Online Pulse Evaluation"       << endl;
+    gLog << "               Compiled on <" << __DATE__ << ">"          << endl;
+    gLog << "                  Using ROOT v" << ROOTVER                << endl;
+    gLog << "========================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " sinope [options] --run={number} --date={yyyy-mm-dd}" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   --run={number}:           Run number of run to process" << endl;
+    gLog << "   --date={yy-mm-dd}:        Night the run belongs to" << endl << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    //    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    //    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    //    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    //    gLog << "   --debug-env=3             Debug setting resources from resource file" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   --ind=path                Path where to search for the data file" << endl;
+    gLog << "                             [default=standard path in datacenter]" << endl;
+    gLog << "   --out=path                Path to write the all results to [def=local path]" << endl;
+    gLog << "   --num={number}            Number of events to process (default=1000)" << endl;
+    gLog << "   --print-seq               Print Sequence information" << endl;
+    gLog << "   --print-files             Print Files taken from Sequence" << endl;
+    gLog << "   --print-found             Print Files found from Sequence" << endl;
+    //    gLog << "   --config=callisto.rc      Resource file [default=callisto.rc]" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+    gLog << "Background:" << endl;
+    gLog << " Sinope is  Jupiter's sixteenth moon.  Sinope is 28km in diameter and" << endl;
+    gLog << " and orbits 23,700,000km from Jupiter.  Sinope has a mass of  8e16kg." << endl;
+    gLog << " It orbits Jupiter in 758days and is in a retrograde orbit  (orbiting" << endl;
+    gLog << " opposite to the direction of  Jupiter).  Very little  is known about" << endl;
+    gLog << " Sinope.  Sinope was discovered by S.Nicholson in 1914." << endl << endl;
+    gLog << "Example:" << endl;
+    gLog << " sinope -f --date=2004-05-06 --run=32456" << endl;
+    gLog << endl;
+}
+
+static void PrintFiles(const MSequence &seq, const TString &kInpathD, Bool_t all)
+{
+    const char *prep = all ? "Found" : "Scheduled";
+
+    MDirIter Next;
+    seq.SetupAllRuns(Next, kInpathD, "[PCD]", kTRUE);
+
+    gLog << all;
+    gLog.Separator(Form("%s Files", prep));
+    Next.Print(all?"all":"");
+    gLog << endl;
+}
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv, kTRUE);
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    gLog.Setup(arg);
+
+    //const TString kConfig     = arg.GetStringAndRemove("--config=", "callisto.rc");
+
+    const Bool_t  kPrintSeq   = arg.HasOnlyAndRemove("--print-seq");
+    const Bool_t  kPrintFiles = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kPrintFound = arg.HasOnlyAndRemove("--print-found");
+    const Bool_t  kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+    //Int_t kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    //kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit       = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch      = arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite  = arg.HasOnlyAndRemove("-f");
+    //const Bool_t  kForceExec  = arg.HasOnlyAndRemove("-ff");
+
+    const TString kInpathD    = arg.GetStringAndRemove("--ind=",  "");
+    /*const TString*/ kOutpath    = arg.GetStringAndRemove("--out=",  "");
+
+    const Int_t   kNumEvents  = arg.GetIntAndRemove("--num=", 1000);
+    const Int_t   kRunNumber  = arg.GetIntAndRemove("--run=",  -1);
+    const TString kDate       = arg.GetStringAndRemove("--date=", "");
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return -1;
+    }
+
+    if (kRunNumber<0)
+    {
+        gLog << warn << "ERROR - No '--run=' option given... required." << endl;
+        gLog << endl;
+        return -1;
+    }
+    if (kDate.IsNull())
+    {
+        gLog << warn << "ERROR - No '--date=' option given... required." << endl;
+        gLog << endl;
+        return -1;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()>0)
+    {
+        Usage();
+        return -1;
+    }
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Setup sequence and check its validity
+    //
+    MSequence seq;
+    seq.SetNight(kDate);
+    seq.AddRuns(kRunNumber);
+    if (kPrintSeq)
+    {
+        gLog << all;
+        gLog.Separator();
+        seq.Print();
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Sequence invalid!" << endl << endl;
+        return -1;
+    }
+
+    //
+    // Process print options
+    //
+    if (kPrintFiles)
+        PrintFiles(seq, kInpathD, kFALSE);
+    if (kPrintFound)
+        PrintFiles(seq, kInpathD, kTRUE);
+
+    if (kOutpath.IsNull())
+        kOutpath = seq.GetStandardPath(kTRUE);
+    if (!kOutpath.EndsWith("/"))
+        kOutpath += "/";
+    kOutpath += Form("sinope%08d.", kRunNumber);
+
+    if (!kOverwrite)
+    {
+        TString file = Form("%sroot", kOutpath.Data());
+        if (!gSystem->AccessPathName(file, kFileExists))
+        {
+            gLog << err << "Sorry, file '" << file << "' exists... use -f option.." << endl;
+            return -1;
+        }
+        file = Form("%stxt", kOutpath.Data());
+        if (!gSystem->AccessPathName(file, kFileExists))
+        {
+            gLog << err << "Sorry, file '" << file << "' exists... use -f option.." << endl;
+            return -1;
+        }
+    }
+
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("Sinope", &argc, argv);
+    if (!gROOT->IsBatch() && !gClient || gROOT->IsBatch() && !kBatch)
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    // ----------------------------------------------------------
+
+    /*MStatusDisplay **/d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(Form("Sinope #%d", kRunNumber));
+
+    MDirIter iter;
+    seq.SetupAllRuns(iter, 0, "[DPC]", kTRUE);
+
+    MRawFileRead read;
+    read.AddFiles(iter);
+
+    MTaskInteractive task;
+
+    task.SetPreProcess(PreProcess);
+    task.SetProcess(Process);
+    task.SetPostProcess(PostProcess);
+
+    MTaskList tlist;
+    tlist.AddToList(&read);
+    tlist.AddToList(&task);
+
+    MParList  plist;
+    plist.AddToList(&tlist);
+
+    plist.AddToList(&data);
+    plist.AddToList(&header);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    if (!evtloop.Eventloop(kNumEvents))
+        return 1;
+
+    if (!evtloop.GetDisplay())
+    {
+        gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+        return 0;
+    }
+
+    tlist.PrintStatistics();
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: /tags/Mars-V0.9/star.cc
===================================================================
--- /tags/Mars-V0.9/star.cc	(revision 9772)
+++ /tags/Mars-V0.9/star.cc	(revision 9772)
@@ -0,0 +1,261 @@
+#include <TROOT.h>
+#include <TClass.h>
+#include <TSystem.h>
+#include <TGClient.h>
+#include <TApplication.h>
+#include <TObjectTable.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MEnv.h"
+#include "MArgs.h"
+#include "MArray.h"
+#include "MDirIter.h"
+
+#include "MStatusDisplay.h"
+
+#include "MSequence.h"
+#include "MJStar.h"
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5         6
+    //       123456789012345678901234567890123456789012345678901234567890
+    gLog << "========================================================" << endl;
+    gLog << "                   Star - MARS V" << MARSVER              << endl;
+    gLog << "      MARS -- STandard Analysis and Reconstruction"       << endl;
+    gLog << "               Compiled on <" << __DATE__ << ">"          << endl;
+    gLog << "                  Using ROOT v" << ROOTVER                << endl;
+    gLog << "========================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    //                1         2         3         4         5         6         7         8
+    //       12345678901234567890123456789012345678901234567890123456789012345678901234567890
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << " star [options] sequence.txt" << endl << endl;
+    gLog << " Arguments:" << endl;
+    gLog << "   sequence.txt:             Ascii file defining a sequence of runs" << endl;
+    gLog << "                             For more details see MSequence" << endl;
+    gLog << " Root Options:" << endl;
+    gLog << "   -b                        Batch mode (no graphical output to screen)" << endl<<endl;
+    gLog << " Options:" << endl;
+    gLog.Usage();
+    gLog << "   --debug-env=0             Disable debugging setting resources <default>" << endl;
+    gLog << "   --debug-env[=1]           Display untouched resources after program execution" << endl;
+    gLog << "   --debug-env=2             Display untouched resources after eventloop setup" << endl;
+    gLog << "   --debug-env=3             Debug setting resources from resource file" << endl;
+    gLog << "   --debug-mem               Debug memory usage" << endl << endl;
+    gLog << endl;
+    gLog << " Input Options:" << endl;
+    gLog << "   -mc                       You must use this for MC files (PRELIMINARY)" << endl << endl;
+    gLog << " Output options:" << endl;
+    gLog << "   -q                        Quit when job is finished" << endl;
+    gLog << "   -f                        Force overwrite of existing files" << endl;
+    gLog << "   -ff                       Force execution if not all files found" << endl;
+    gLog << "   --ind=path                Path where to search for the calibrated data (Y)" << endl;
+    gLog << "                             [default=standard path in datacenter]" << endl;
+    gLog << "   --out=path                Path to write the all results to [def=local path]" << endl;
+    gLog << "                             (overwrites --outc and --outy)" << endl;
+    gLog << "   --print-seq               Print Sequence information" << endl;
+    gLog << "   --print-files             Print Files taken from Sequence" << endl;
+    gLog << "   --print-found             Print Files found from Sequence" << endl;
+    gLog << "   --config=star.rc          Resource file [default=star.rc]" << endl;
+    gLog << endl;
+    gLog << "   --version, -V             Show startup message with version number" << endl;
+    gLog << "   -?, -h, --help            This help" << endl << endl;
+}
+
+static void PrintFiles(const MSequence &seq, const TString &kInpathD, Bool_t allopt)
+{
+    const char *prep = allopt ? "Found" : "Scheduled";
+
+    MDirIter Next;
+    seq.SetupDatRuns(Next, kInpathD, "Y");
+
+    gLog << all;
+    gLog.Separator(Form("%s Data Files", prep));
+    Next.Print(allopt?"all":"");
+    gLog << endl;
+}
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv, kTRUE);
+
+    if (arg.HasOnly("-V") || arg.HasOnly("--version"))
+        return 0;
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    gLog.Setup(arg);
+
+    const TString kConfig     = arg.GetStringAndRemove("--config=", "star.rc");
+
+    const Bool_t  kPrintSeq   = arg.HasOnlyAndRemove("--print-seq");
+    const Bool_t  kPrintFiles = arg.HasOnlyAndRemove("--print-files");
+    const Bool_t  kPrintFound = arg.HasOnlyAndRemove("--print-found");
+    const Bool_t  kDebugMem   = arg.HasOnlyAndRemove("--debug-mem");
+    Int_t  kDebugEnv = arg.HasOnlyAndRemove("--debug-env") ? 1 : 0;
+    kDebugEnv = arg.GetIntAndRemove("--debug-env=", kDebugEnv);
+
+    const Bool_t  kQuit       = arg.HasOnlyAndRemove("-q");
+    const Bool_t  kBatch      = arg.HasOnlyAndRemove("-b");
+    const Bool_t  kOverwrite  = arg.HasOnlyAndRemove("-f");
+    //const Bool_t  kForceExec  = arg.HasOnlyAndRemove("-ff");
+    const Bool_t  kIsMC       = arg.HasOnlyAndRemove("-mc");
+
+    const TString kInpath     = arg.GetStringAndRemove("--ind=", "");
+    const TString kOutpath    = arg.GetStringAndRemove("--out=", ".");
+
+    if (arg.GetNumOptions()>0)
+    {
+        gLog << warn << "WARNING - Unknown commandline options..." << endl;
+        arg.Print("options");
+        gLog << endl;
+        return -1;
+    }
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Setup sequence file and check for its existance
+    //
+    const TString kSequence = arg.GetArgumentStr(0);
+
+    if (gSystem->AccessPathName(kSequence, kFileExists))
+    {
+        gLog << err << "Sorry, sequence file '" << kSequence << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    if (gSystem->AccessPathName(kConfig, kFileExists))
+    {
+        gLog << err << "Sorry, config file '" << kConfig << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    //
+    // Setup sequence and check its validity
+    //
+    MSequence seq(kSequence);
+    if (kPrintSeq)
+    {
+        gLog << all;
+        gLog.Separator(kSequence);
+        seq.Print();
+        gLog << endl;
+    }
+    if (!seq.IsValid())
+    {
+        gLog << err << "Sequence read but not valid!" << endl << endl;
+        return -1;
+    }
+
+    //
+    // Process print options
+    //
+    if (kPrintFiles)
+        PrintFiles(seq, kInpath, kFALSE);
+    if (kPrintFound)
+        PrintFiles(seq, kInpath, kTRUE);
+
+    //
+    // Initialize root
+    //
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    TApplication app("Star", &argc, argv);
+    if (!gROOT->IsBatch() && !gClient || gROOT->IsBatch() && !kBatch)
+    {
+        gLog << err << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+    d->SetTitle(kSequence);
+
+    if (kDebugMem)
+        TObject::SetObjectStat(kTRUE);
+
+    //
+    // Do calibration in a block (debug mem)
+    //
+    MEnv env(kConfig);
+    {
+        MJStar job(Form("MJStar #%d", seq.GetSequence()));
+        job.SetSequence(seq);
+        job.SetEnv(&env);
+        job.SetEnvDebug(kDebugEnv);
+        job.SetDisplay(d);;
+        job.SetOverwrite(kOverwrite);
+        job.SetPathOut(kOutpath);
+        job.SetPathData(kInpath);
+        // job.SetPathIn(kInpath); // not yet needed
+
+        if (!job.ProcessFile(kIsMC))
+        {
+            gLog << err << "Calculation of image parameters failed." << endl << endl;
+            return -1;
+        }
+
+        if (kDebugEnv>0)
+            env.PrintUntouched();
+
+        if (!job.GetDisplay())
+        {
+            gLog << warn << "Display closed by user... execution aborted." << endl << endl;
+            return 1;
+        }
+    }
+
+    if (kBatch || kQuit)
+        delete d;
+    else
+    {
+        // From now on each 'Close' means: Terminate the application
+        d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+        // Wait until the user decides to exit the application
+        app.Run(kFALSE);
+    }
+
+    if (TObject::GetObjectStat())
+    {
+        TObject::SetObjectStat(kFALSE);
+        gObjectTable->Print();
+    }
+
+    return 0;
+}
Index: /tags/Mars-V0.9/star.rc
===================================================================
--- /tags/Mars-V0.9/star.rc	(revision 9772)
+++ /tags/Mars-V0.9/star.rc	(revision 9772)
@@ -0,0 +1,56 @@
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                              General
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to setup the logging stream for the jobs
+# (overwrites command line options)
+# -------------------------------------------------------------------------
+#MLog.VerbosityLevel: 2
+#MLog.DebugLevel:     1
+#MLog.NoColors:       yes
+
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+#                                   Star
+# ==========================================================================
+#############################################################################
+# ==========================================================================
+
+# -------------------------------------------------------------------------
+# Use this if you want to write the MJStar output somewhere
+# If you don't want it, it is written to the calibration output anyhow.
+# -------------------------------------------------------------------------
+#MJStar.PathOut: .
+#MJStar.PathIn: .
+
+# -------------------------------------------------------------------------
+# Use this to define where the program should search for the pedestal
+# and calibration files defined in the sequence. To use the local
+# directory use '.' If nothing is specified the default path in the
+# datacenter is used. (overwrites command line options)
+# -------------------------------------------------------------------------
+#MJStar.PathData:   /data/MAGIC/Period016/
+
+# -------------------------------------------------------------------------
+# Configure MJStar
+# -------------------------------------------------------------------------
+#MJStar.MaxEvents: 10000
+#MJStar.Overwrite: yes,no
+#MJStar.
+
+# -------------------------------------------------------------------------
+# -------------------------------------------------------------------------
+MJStar.MImgCleanStd.CleanLevel1: 4.5
+MJStar.MImgCleanStd.CleanLevel2: 3.0
+MJStar.MImgCleanStd.CleanMethod: Scaled
+
+# -------------------------------------------------------------------------
+# -------------------------------------------------------------------------
+#MJStar.MHillasCalc.IdxIsland: 0
+
Index: /tags/Mars-V0.9/status.cc
===================================================================
--- /tags/Mars-V0.9/status.cc	(revision 9772)
+++ /tags/Mars-V0.9/status.cc	(revision 9772)
@@ -0,0 +1,340 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz, 4/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  Status - Example how to use the MStatusDisplay
+//
+//  Use a camera file as input ----- PRELIMINARY
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MStatusDisplay.h"
+#include "MArray.h"
+#include "MArgs.h"
+#include "MLog.h"
+#include "MLogManip.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MMcPedestalCopy.h"
+#include "MMcPedestalNSBAdd.h"
+//#include "MCerPhotCalc.h"
+#include "MCerPhotAnal2.h"
+//#include "MBlindPixelCalc.h"
+#include "MSigmabarCalc.h"
+#include "MImgCleanStd.h"
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+//#include "MCT1SupercutsCalc.h"
+#include "MHCamEvent.h"
+#include "MFillH.h"
+#include "MEvtLoop.h"
+#include "MFDataMember.h"
+#include "MCalibrate.h"
+#include "MExtractSignal.h"
+#include "MMcCalibrationUpdate.h"
+
+#include <TApplication.h>
+#include <TSystem.h>
+
+using namespace std;
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "               status - MARS V" << MARSVER          << endl;
+    gLog << "     MARS - Merging and Preprocessing Program"      << endl;
+    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
+    gLog << "               Using ROOT v" << ROOTVER             << endl;
+    gLog << "   PROGRAM IS PRELIMINARY - FOR TEST CASES ONLY"    << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+static void Usage()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   status [-a0] [-vn] [-cn] inputfile[.root]" << endl << endl;
+    gLog << "     input file:   Mars root file." << endl;
+    gLog << "     -a0: Do not use Ansii codes." << endl;
+    gLog << "     -vn: Verbosity level n [default=2]" << endl;
+    gLog << "     -?/-h: This help" << endl << endl;
+}
+
+
+int main(int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+
+    if (arg.HasOption("-?") || arg.HasOption("-h"))
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Set verbosity to highest level.
+    //
+    gLog.SetDebugLevel(arg.HasOption("-v") ? arg.GetIntAndRemove("-v") : 2);
+
+    if (arg.HasOption("-a") && arg.GetIntAndRemove("-a")==0)
+        gLog.SetNoColors();
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()!=1)
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // This is to make argv[i] more readable insidethe code
+    //
+    TString kNamein = arg.GetArgumentStr(0);
+
+    if (!kNamein.EndsWith(".root"))
+        kNamein += ".root";
+
+    //
+    // check whether the given files are OK.
+    //
+    if (gSystem->AccessPathName(kNamein, kFileExists))
+    {
+        gLog << err << "Sorry, the input file '" << kNamein << "' doesn't exist." << endl;
+        return -1;
+    }
+
+    TApplication app("Status", &argc, argv);
+    if (gROOT->IsBatch() || !gClient)
+    {
+        gLog << "Bombing... maybe your DISPLAY variable is not set correctly!" << endl;
+        return 1;
+    }
+
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    //
+    // Update frequency by default = 1Hz
+    //
+    MStatusDisplay *d = new MStatusDisplay;
+
+    // From now on each 'Exit' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnExit);
+
+    // Set update time to 5s
+    // d->SetUpdateTime(5000);
+
+    // Disable online update
+    // d->SetUpdateTime(-1);
+
+    d->SetLogStream(&gLog, kTRUE);            // Disables output to stdout
+    gLog.SetOutputFile("status.log", kTRUE);  // Enable output to file
+    //gLog.EnableOutputDevice(MLog::eStdout); // Enable output to stdout again
+
+    // Set input file as display title (bottom line in ps file)
+    d->SetTitle(kNamein);
+
+    //
+    // Create a empty Parameter List and an empty Task List
+    // The tasklist is identified in the eventloop by its name
+    //
+    MParList  plist;
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    /*
+     MSrcPosCam src;
+     src.SetXY(1./geomcam.GetConvMm2Deg(), 0);
+     plist.AddToList(&src);
+     */
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events");
+    //read.DisableAutoScheme();
+
+    // ------------- user change -----------------
+    read.AddFile(kNamein);
+
+    MGeomApply        geomapl;
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+    //MCerPhotCalc      ncalc;
+    MCerPhotAnal2     nanal;
+
+    MFDataMember f1("MRawRunHeader.fRunType", '>', 255.5);
+    MFDataMember f2("MRawRunHeader.fRunType", '<', 255.5);
+    f1.SetName("MFMonteCarlo");
+    f2.SetName("MFRealData");
+
+    MExtractSignal extra;
+    extra.SetRange(5, 9, 5, 9);
+
+    MMcCalibrationUpdate mcupd;
+    mcupd.SetOuterPixelsGainScaling(kFALSE);
+
+    MCalibrate calib;
+
+    // MC
+    extra.SetFilter(&f1);
+    mcupd.SetFilter(&f1);
+    calib.SetFilter(&f1);
+    nanal.SetFilter(&f2);
+
+    /*
+     TArrayS blinds(6);
+     blinds[0] =   0;
+     blinds[1] = 195;
+     blinds[2] = 227;
+     blinds[3] = 248;
+     blinds[4] = 271;
+     blinds[5] = 291;
+
+     blinds[3] =  51;
+     blinds[4] =  56;
+     blinds[5] = 112;
+     blinds[6] =  31;
+     blinds[7] = 116;
+     blinds[8] = 507;
+     blinds[9] = 559;
+     blinds[10]= 291; // 311, 119, 54, 85, 125, 92, 133, 224
+
+     MBlindPixelCalc blind;
+     blind.SetPixelIndices(blinds);
+     //blind.SetUseInterpolation();
+     */
+
+    // MSigmabarCalc     sgcal;
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+    // MCT1SupercutsCalc calc1;
+
+    // -------------------------------------------
+
+    MHCamEvent hist("PedestalRms");
+    hist.SetType(1);
+    plist.AddToList(&hist);
+
+    // -------------------------------------------
+
+    MHCamEvent maxhi("MaxIdxHi", "Index of slice with maximum content (hi-gain)");
+    MHCamEvent maxlo("MaxIdxLo", "Index of slice with maximum content (lo-gain)");
+    maxhi.SetType(3);
+    maxlo.SetType(4);
+    plist.AddToList(&maxhi);
+    plist.AddToList(&maxlo);
+
+    // -------------------------------------------
+
+    MFillH hfilhi("MaxIdxHi", "MRawEvtData");
+    MFillH hfillo("MaxIdxLo", "MRawEvtData");
+    MFillH hfill0("Uncleaned [MHCamEvent]", "MCerPhotEvt");
+    MFillH hfill1("Pedestals [MHCamEvent]", "MPedestalCam");
+    MFillH hfill2("PedestalRms", "MPedestalCam");
+    MFillH hfill3("MHHillas", "MHillas");
+    MFillH hfill4("MHHillasExt");
+    MFillH hfill5("MHHillasExtSrc [MHHillasExt]", "MHillasSrc");
+    MFillH hfill6("MHHillasSrc","MHillasSrc");
+    MFillH hfill7("MHNewImagePar","MNewImagePar");
+    //MFillH hfill8a("MHStarMap", "MHillas");
+    //MFillH hfill8b("MHStarMap2", "MHillas");
+    MFillH hfill9("Cleaned [MHCamEvent]", "MCerPhotEvt");
+    //MFillH hfill10("MHHadronness", "MHadronness");
+    //MFillH hfill11("MHSigmaTheta");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&f1);
+    tlist.AddToList(&f2);
+    tlist.AddToList(&geomapl);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+
+    tlist.AddToList(&extra);
+    tlist.AddToList(&mcupd);
+    tlist.AddToList(&calib);
+
+    tlist.AddToList(&nanal);
+    //tlist.AddToList(&blind);
+    tlist.AddToList(&hfilhi);
+    tlist.AddToList(&hfillo);
+    tlist.AddToList(&hfill0);
+    //tlist.AddToList(&sgcal);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&scalc);
+    //tlist.AddToList(&calc1);
+    tlist.AddToList(&hfill1);
+    tlist.AddToList(&hfill2);
+    tlist.AddToList(&hfill3);
+    tlist.AddToList(&hfill4);
+    tlist.AddToList(&hfill5);
+    tlist.AddToList(&hfill6);
+    tlist.AddToList(&hfill7);
+    //tlist.AddToList(&hfill8a);
+    //tlist.AddToList(&hfill8b);
+    tlist.AddToList(&hfill9);
+    //tlist.AddToList(&hfill10);
+    //tlist.AddToList(&hfill11);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+    evtloop.SetDisplay(d);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+        return 1;
+
+    tlist.PrintStatistics();
+
+    if (!evtloop.GetDisplay())
+        return 0;
+
+    // From now on each 'Close' means: Terminate the application
+    d->SetBit(MStatusDisplay::kExitLoopOnClose);
+
+    // Wait until the user decides to exit the application
+    app.Run(kFALSE);
+    return 0;
+}
